Giving an AI tutor a memory it can't rewrite
A good teacher's real advantage over a video is continuity. They know you got through a hard passage last week, that you want to play one particular song, and that you go quiet when you're frustrated. We're building MaestrPlay around an AI music tutor called Mai, and the product only works if Mai feels like that teacher rather than a chatbot meeting you for the first time.
There are two obvious ways to give a model a memory. You can keep feeding it the transcript, or you can let it take notes about the learner and read them back later. We did neither. Mai's memory is a row in Postgres that the application owns. The model reads it on every turn and has no way to write to it. MaestrPlay is in a small closed beta ahead of launch, and this is the kind of decision you want settled early. It's very hard to change once real learners have months of history.
Memory is a row, not a transcript
Each learner has exactly one learner_memory record:
export interface LearnerMemory {
userId: string;
skillLevel: string | null;
currentSkillNode: string | null;
goals: Record<string, unknown>;
preferences: Record<string, unknown>;
emotionalPatterns: Record<string, unknown>;
practiceStats: Record<string, unknown>;
}The facts that matter most get proper columns: where the learner placed when
they joined, and which node of the skill graph they're on now. The looser
things, such as goals, preferences and practice stats, go in jsonb columns,
so a new kind of preference doesn't need a migration. That trade-off comes back
at the end of this post.
Next to the row sit the things that already have their own tables: the skills a learner has earned or been placed into, and their active song goal. None of this is prose, and none of it is a summary the model wrote. An engineer can read it, a test can assert on it, and a learner can correct it.
The prompt is assembled, not remembered
Every chat turn builds Mai's system prompt from scratch, in layers:
build(memory, signal, knownSkills, levelChange, songTurn, songGoal): string {
const parts: string[] = [MAI_CORE_IDENTITY];
const layer2 = this.buildLearnerContext(memory, knownSkills, songGoal);
if (layer2 !== '') parts.push(layer2);
const layer3 = this.buildCurrentState(memory);
if (layer3 !== '') parts.push(layer3);
const layer4 = this.buildBehavioralGuidance(signal);
if (layer4 !== '') parts.push(layer4);
if (levelChange !== null) parts.push(this.buildLevelChange(levelChange));
// ...song resolution, then the list of actions Mai may take
return parts.join('\n\n');
}The identity layer is fixed: personality, tone, one actionable tip per reply. The learner context turns the row into plain statements, and most of them come with an instruction attached. The known-skills line ends with "Build on these; never offer to teach them from scratch." The song-goal line ends with "never ask them to set it again." A fact on its own tells the model what's true. The instruction tells it what to do about that.
Two rules keep this manageable as the product grows. A layer with nothing to
say is left out entirely. There's no Goals: none and no empty heading for the
model to fill with guesses. And not everything in memory belongs in the
conversation. A learner's chosen session structure is stored in preferences,
but it shapes the generated practice sessions, not how Mai talks, so the prompt
builder filters it out. Memory is the full record. The prompt gets the relevant
part of it.
The model reads memory; it never writes it
Here is every path that can change a learner's memory:
- Placement, when they first join and say how much they already play.
- A level adjustment, when they say lessons are too easy or too hard.
- A song unlock, which records the milestone.
- Session settings the learner edits in the app.
- A
PATCHfrom the learner's own profile. Its DTO accepts onlyskillLevel,goalsandpreferences. Practice stats and emotional patterns can't be set from the client.
Model output isn't on that list. Mai's replies are streamed to the learner and saved to the conversation, and that's the last thing that happens to them.
We drew the line there because model-written memory compounds. If the model writes "struggles with rhythm" after one bad session, that note shapes every later session. It nudges each new reply toward rhythm drills, and the next note the model writes confirms the first. Nobody can say where the belief came from or when it stopped being true. A row that only deterministic code writes has a known author for every field.
Changes happen before the reply, then get narrated
The hard part is that learners will ask for changes in chat. "These lessons are way too easy" is a request to move them up the skill path. If the model handled that by saying "Great, I've moved you up!", the app would be lying whenever the move didn't happen.
So a request is detected and applied before the prompt is built. A regex over words like easy, boring, hard and struggling skips the classifier for any message that can't be about difficulty, which saves a model call. The rest go to a classifier with a closed schema:
const INTENT_SCHEMA = {
type: 'object',
properties: { intent: { type: 'string', enum: ['too_easy', 'too_hard', 'neither'] } },
required: ['intent'],
additionalProperties: false,
};A classifier failure returns null, which means "leave the level alone". The
classifier's prompt also spells out the cases it must not count, such as
questions ("is barre hard?") and negations ("this isn't too hard"). When the
intent is real, ordinary application code moves the learner one step. The
outcome goes into the prompt as a Level change section: moved, blocked at the
end of the path, or waiting for confirmation because going back would lock
later skills. Mai's instructions say:
Learner says lessons are too easy or too hard: only say their level changed if a "Level change" section above says so. Otherwise, adjust your advice and do not claim a change.
Song requests work the same way. The song is looked up in a real catalog, and Mai is told never to guess a song's chords, skills or difficulty. The model's job is to explain, in a warm voice, something the application has already done. It never reports an action the code didn't take.
Mood is computed, not diagnosed
Mai adapts its tone to how the learner seems to be doing. The signal comes from a deliberately crude function over recent messages, not from the model:
// FRUSTRATED: 3+ consecutive short user messages (< 20 chars)
// PLATEAUED: user messages span 3+ distinct days with no questions
// ENGAGED: 5+ messages with no questions anywhere
// otherwise NEUTRALEach signal maps to one fixed paragraph of guidance. Frustrated means simplify the current task into a smaller step the learner can win. Plateaued means keep the difficulty and change the angle. Engaged means raise the challenge slightly. Because the mapping is fixed, it's testable, and we can see exactly why Mai went gentle on a given turn. A model asked to judge someone's emotional state from a chat log gives a different, unexplained answer every time.
The heuristic will be wrong sometimes. A learner who simply types "ok", "yes", "next" reads as frustrated. We accept that, because the worst outcome is a slightly gentler next exercise. Beta conversations will show whether the thresholds are right.
The greeting has a memory of its own
Every time the app opens, Mai greets the learner in one or two sentences, built from the same memory plus the time of day. Two details took longer than they should have.
The first was repetition. The last five greetings are stored per learner and passed in as "do not repeat verbatim". If the model repeats one anyway, we re-roll it up to twice and then fall back to a fixed line. That loop only works if the call bypasses the exact-match response cache in our model gateway. A cached answer comes back identical on every attempt, so the loop would always end on the fallback. The finished greeting is cached for an hour in Redis instead, one layer up.
The second was the clock. The server runs on UTC, so a learner in Manila would have been greeted with "good morning" at 6pm. The greeting now uses the learner's own time zone, from the request or their synced profile, and falls back to the server clock if the zone is missing or invalid. It's a small bug, but it undermines the claim that Mai knows the learner.
Testing it before launch
Because the model never writes memory, most of this design can be tested like ordinary code, which is a quieter benefit of keeping it out. The prompt builder has unit tests that assert on the assembled prompt: a layer with nothing to say is left out, and session-structure preferences never reach the chat. Above that, an API suite runs against the real backend and a throwaway database, never the one that holds testers' data. It checks the memory lifecycle end to end:
- A new account gets an empty memory row.
- A profile update persists only the fields it's allowed to touch.
- Placement marks the right skills as known and points the first session at the next one.
- Two greetings within an hour come back identical, from the cache.
- Telling Mai the lessons are too easy moves the learner and streams the change. Saying a lesson is not too hard changes nothing.
That last pair matters most. It's the promise from the section above, that Mai never claims a change the code didn't make, written as a test.
What tests can't tell us is whether Mai feels like a teacher. That needs real learners, so the app goes out in stages: a small closed beta, then a wider public beta, before the store release. The next version of Mai's prompt will be written by reading those beta conversations, not by guessing. Each stage also answers the question the memory exists for: do people come back after the first week, and are they still practicing a month later?
Where this stops working
The jsonb columns that saved us migrations also let readers and writers drift
apart without anyone noticing, and the suite above didn't catch it. When we
traced every key the prompt reads back to the code that writes it, we found the
gap. practiceStats.recentMilestone has a
writer: the song unlock. practiceStats.streak, practiceStats.lastPracticed
and emotionalPatterns.lastSignal don't. Streaks are tracked properly in their
own table, and the emotional signal is computed fresh on every turn, but
nothing copies either value into the memory row. So the Current streak line in
Mai's prompt, and the Days since last practice line in the greeting, never
rendered.
Nothing failed, which is the problem. The prompt builder correctly treats a missing key as "nothing to say", and that's the same rule that keeps empty sections out of the prompt. With a typed column, the missing writer would have been a compile error. With a JSON bag, it looked like a learner with nothing going on. The fix isn't hard: read streaks from the table that owns them, and keep in the JSON columns only what has a single typed writer, with a test that every key the prompt reads has one. The lesson is the expensive part. A schemaless column moves a contract from the compiler to code review, and code review missed it. The gap shipped in the closed-beta build. There, the cost is a missing sentence in a small group's conversations, which is exactly why the beta comes before the launch.
The other limit is by design. Mai remembers facts about a learner, not what was said. Within a conversation, the history goes in under a token budget, dropping the oldest messages first. Across conversations, Mai knows the skills you've earned, but not that you mentioned your daughter's recital two weeks ago. That's the next layer we'd add once real learners show us which details are worth keeping: retrieval over past sessions, written to a store the learner can see and delete, and held to the same rule as the rest. The model can read it. Only code can write it.
Building something and want a team that takes it from empty repo to shipped? We'd love to hear about it.