This question might result too broad and subjective to answer, so apologize first, but I'll try to make it as specific as possible.
Recently I had a piano exam, consisting in three pieces: Partita No. 6 in E minor BMW 830, Brahms Rhapsody op. 70 No.1 in B minor and Beethoven's Sonata No. 15 (Pastoral).
I had to play one of the pieces by heart, and I chose the Partita. Fortunately, I played it well enough to pass the exam, but I still have the feeling that my memory wasn't that good at playing, that is, there were certain parts where I knew exactly which notes I was playing, as if I could write them all on a partiture, but there were others where I simply had to take a chance and trust my muscle memory to play the right notes. That's the kind of playing I'd like to avoid, specially when playing long pieces, since the probability of missing a note or simply go blank increases.
That hasn't caused me any troubles yet, but I'd like to continue my piano studies further, and I know it is the kind of thing I need to stop or control, since there will be times when my muscle memory fail. My question then is
How can I train my memory, specially when playing long or difficult pieces like fugues or suites, so I don't have to rely on my muscle memory to play them by heart?