AI agent memory
I want a new agent session to continue the work without making me recap the previous one. If we have already diagnosed a failed deployment, found the right configuration file, or agreed not to commit without permission, that should affect the next task.
Saving the conversation is not enough. It also preserves wrong assumptions, temporary fixes and facts that have since changed. Loading everything brings those mistakes back alongside the useful experience.
Most of the work in AI agent memory happens after a note is written: selecting what matters, checking it, compressing it, updating it and eventually deleting it.
What the agent actually remembers
A normal model call does not update the model’s weights. Experience from a conversation does not automatically become part of them. To make it available again, the application must supply the relevant information: messages, summaries, instructions or retrieved notes.
Three different things often get grouped under memory:
| Term | What it means |
|---|---|
| Context window | The information available to the model in the current call |
| Memory | State retained between sessions, plus the rules for managing it |
| RAG | Retrieving external information and adding it to the context |
RAG can search memory, documentation or a product catalogue. Retrieval alone does not mean an agent is learning from its experience.
For this article, I use a narrow definition: agent memory is knowledge gained through experience that survives a session and influences future work. Anthropic uses a similar boundary in The components of agent memory.
Reading deployment instructions is consulting documentation. Discovering an incorrect path, finding the working one and correcting the instructions preserves experience. Using that correction in the next session closes the loop.
A note that nobody reads is an archive entry. A note that gets read but never checked or updated can eventually become an obstacle.
A large context window does not remove this problem. Lost in the Middle found that models often used information in the middle of long inputs less effectively than information at the beginning or end. Chroma’s Context Rot experiments found declining performance as inputs grew across several tasks. These are distinct effects, but both raise the practical question of how much of the supplied context a model can actually use.
The layers of memory
CoALA describes working, episodic, semantic and procedural memory. For a coding agent, I find this practical mapping useful:
| Type | What it holds | Example |
|---|---|---|
| Working | The current task and intermediate results | Conversation context |
| Episodic | What happened | Session transcripts and work logs |
| Semantic | Facts and generalizations | Verified project knowledge, decisions and their reasons |
| Procedural | How to do the work | Instructions, skills and executable checks |
This is an adaptation. CoALA also includes agent code and knowledge in model weights under procedural memory. Here I am interested in what can be managed outside the model.
A transcript lets you trace a conclusion to its source. A short note saves you from rereading the transcript. A procedure turns a discovered solution into a repeatable way of working.
For rules, a useful progression is text → skill → environment check.
The model can overlook text in its context. A skill collects instructions for a particular task, but the agent still needs to select and follow it. A hook is an event handler in the environment that can automatically inspect an action and stop it.
A skill is not an enforcement guarantee. A hook is only as reliable as its coverage of the relevant actions. When a critical requirement can be checked programmatically, I would enforce it in the environment. Requiring a successful check before publication is more dependable when the publication mechanism actually rejects unchecked output.
What to save
My main filter is how hard the knowledge would be to recover in the next session.
The agent can read a file again. Current disk usage is better checked with a command. But the reason for an architectural decision, a rejected alternative or a correction to the way I want work done may be impossible to recover from the code.
Useful candidates include:
- decisions and their reasons;
- verified diagnostic procedures;
- constraints discovered during the work;
- user corrections, including where they apply.
“Don’t do that” without context can become an overly broad rule. A request not to restart a service during one incident is not necessarily a permanent ban on restarts.
Writing also needs to account for what is already known. The Mem0 paper describes four operations: ADD, UPDATE, DELETE and NOOP. A new fact can be added, used to update a record, used to remove a conflicting record, or ignored because nothing needs to change. Repeating a known fact should not create another note.
The model’s use of memory matters more than merely giving it a folder. In Anthropic’s database task from CL-Bench, each question started in a fresh session, with memory files carrying over. These are results for three of the models evaluated:
| Model | Without memory | With memory |
|---|---|---|
| Opus 5 | 0.564 | 0.828 |
| Opus 4.7 | 0.383 | 0.700 |
| Sonnet 4.6 | 0.330 | 0.364 |
These are mean task scores, not percentages of correct answers. Sonnet 4.6 recorded untested guesses and read memory less than half the time. Opus 5 more often recorded a verified rule, its supporting evidence and warnings about discovered traps. Anthropic’s experiment.
Instructions also changed the outcome. Telling Opus 5 to record only failures reduced its gain from memory by 0.234. Telling Sonnet 4.6 to read memory before answering and test its hypotheses raised its score from 0.364 to 0.641.
I would not turn this into a general rule that stronger models need no instructions. But limiting memory to corrections can discard useful knowledge. A successful approach may be worth more than another description of a failure.
Turning experience into rules
I reviewed 842 transcripts from my own sessions and extracted 192 corrections. For permanent rules, I selected corrections that had appeared independently at least three times.
That threshold helps avoid generalizing from a single incident. It is a working filter, not a quality guarantee. An explicit standing instruction from the user does not need three repetitions.
The compression process looks like this:
Episode → generalization → procedure.
An agent commits without permission. A note records the correction and its reason. Repeated incidents motivate a standing rule for git operations. Where reliable enforcement is possible, an environment check can support the rule.
Keeping the original episode separately is still useful. Otherwise, a month later all that remains may be “never do X,” with no way to recover the circumstances behind it.
There is a related problem within a long task. Compaction replaces older conversation turns with a summary, which can lose details. A separate file with the goal, completed steps, open questions and checks helps preserve working state across context windows, provided the agent knows to read it.
When to forget
Different records have different useful lifetimes. A decision about service boundaries may remain relevant for years. “We have a release this week” expires quickly.
I would distinguish three mechanisms.
Expiry. A temporary fact has a time to live, or TTL, after which it should be checked again or removed from active memory.
Lower retrieval priority. Older or less useful records are selected less often. In Generative Agents, retrieval combines normalized recency, importance and relevance scores in a weighted sum. This changes which memories are retrieved; it does not delete them.
Replacement. A verified new fact updates an old one. If a configuration file moves, its current path should have one authoritative home. The history of the move can remain in a log.
Anthropic’s Pokémon Red experiment illustrates the cost of uncontrolled accumulation. Sonnet 3.7 created 413 files in 225 folders. Around step 10,000, it spent 17 consecutive actions reorganizing memory without taking an action in the game.
Fable 5 used nine files plus a separate global.md containing its goal, plan and memory rules. These were individual runs, but they show how maintaining records can begin to displace the task itself. Experiment details.
Retrieving the right information
For file-based memory, I prefer progressive loading:
- Start with a short index describing what is known and where to find it.
- Read the notes and instructions relevant to the task.
- Follow links to original documents and transcripts when more detail is needed.
An index entry only needs enough information to tell the agent when the record is useful. Details belong behind the link. Anything loaded automatically consumes context in every session, whether the task needs it or not.
The retrieval method depends on the material. Text search works well for file paths, function names and exact phrases. Vector search finds related meanings without matching words. A graph supports traversal of explicitly represented relationships.
Each has limitations. A text match does not distinguish a function call from a mention in a comment. A vector index needs maintenance, and exact identifiers may require a separate search. For a graph edge, provenance matters: was the relationship extracted from code or inferred by a model?
My comparison: grep, a graph and full context
I compared three setups on a corpus of 280 files containing rules and scripts. There were eight questions: four targeted lookups and four about relationships between files. I used graphify to build the graph.
The two search setups each had two runs per question. The full-context results contain eight answers:
| Setup | Correct answers | Mean input tokens |
|---|---|---|
| grep | 16 of 16 | 27.9k |
| grep + graph | 16 of 16 | 34.6k |
| Full context | 6 of 8 | 151.6k |
Here, grep means an agent using text search and then reading files. It could refine queries and inspect the code it found.
Adding the graph increased input token usage by about 24% without changing the number of correct answers. The agent queried the graph and then checked the result with search. I saw a specific benefit on a question about which function called another: the graph represented that relationship directly.
The full-context setup consumed 5.4 times as many input tokens. However, some code required for the answers was missing from its input. This result exposes a limitation of that particular context assembly. It does not show that the model failed to use code it had actually received.
The most useful discovery concerned my reference answers. I had built two of them using text search, and both were wrong: I had treated mentions as dependencies. The agent that read the code answered those questions more accurately than my reference.
For my corpus, this small comparison did not justify adding a graph for general accuracy. It did show value for questions about code relationships. Eight questions are not enough to generalize to every knowledge base.
A graph built from documents is still an index. To represent an agent’s experience, it must also retain and reuse the results of the agent’s work.
Correcting memory
A wrong note can arrive in the next session as established knowledge. The original conversation contained doubts and checks; the compressed version may contain only a confident sentence.
Records therefore need a source, a scope and, for changing facts, a verification time. A transcript link explains where the conclusion came from. Checking the current environment establishes whether it remains true.
A current fact should have one authoritative location. Other documents can link to it. Otherwise, correcting one copy leaves another version in circulation.
Conflicts also need a resolution policy. A current explicit user instruction should supersede an old preference note. Verified system state should supersede a stale record of that state. A memory note should not override environment restrictions merely because it was loaded later.
Anthropic describes a separate maintenance process called dreaming. Between working sessions, the agent reviews notes, checks them against transcripts, merges duplicates and repairs links. In a Pokémon example, this corrected a false note about a PokéCenter’s location that had repeatedly sent the agent down the wrong route. Memory correction example.
A transcript can establish what happened then. Verifying what is true now may require checking the environment again.
The origin of instructions matters too. An external page or email can contain an attempt to direct the agent. Saving that text as a standing rule can extend the effect into future sessions. Information from such a source can be recorded with its provenance; its commands should not become operating instructions.
Measuring whether memory helps
The number of files says little about memory quality. I would compare equivalent tasks with and without memory, measuring:
- successful task completion;
- how often the user has to correct the agent;
- time and token usage;
- mistakes caused by stale records.
Include the cost of creating and maintaining memory. A small saving on answers does not pay off if background maintenance costs more.
Another useful question is how much of the loaded material was actually needed. If a large file is read every session for one paragraph, that paragraph can be separated out and the rest left behind a link.
I would start with a short index, verifiable notes and clear update rules. Critical requirements should become executable checks where that is practical.
Then measure the result. If the agent repeats fewer mistakes and resumes work faster, memory is doing its job. If it spends its time sorting its own notes, it may be time to delete some of them.
Sources
- Anthropic — The components of agent memory
- CoALA — Cognitive Architectures for Language Agents
- Generative Agents: Interactive Simulacra of Human Behavior
- Lost in the Middle: How Language Models Use Long Contexts
- Mem0: Building Production-Ready AI Agents with Scalable Long-Term Memory
- Chroma — Context Rot