Concepts · Level 2 · Note 7
AI memory explained: context, compaction, long-term memory and attacks
Working memory, compaction and the three types of long-term memory in plain words, then memory poisoning, cross-user leaks, lost rules and what forget means.
Short answer
A language model remembers nothing between calls. What looks like memory is text the application puts back into the prompt: the conversation so far, a summary once it gets long, and notes from a store that outlives the chat. A summary can drop a rule. A saved note can carry an attacker's instruction into every later session. A shared store can hand one user's requests to another: in one lab study, 30 crafted prompts pulled 50 of 200 stored queries out of a healthcare records agent. Scope memory per user, control what gets written, and test that delete means delete.
Ask a chatbot what you told it last week and it may answer correctly. The model didn’t remember. Some software around the model saved a note back then and pasted it into today’s prompt, and the model read it as if for the first time.
The security questions are all about that software. Below are the layers people call memory, and then what researchers have done to each one.
Working memory, in plain words
Picture a very capable temp who arrives every morning with no recollection of any earlier day. Everything they know about your job is in the folder you put on their desk. If a page is in the folder, they can use it. If it isn’t, it doesn’t exist for them.
A chat works the same way on every single turn. The application keeps the transcript and puts the whole thing in the folder again each time you send a message. The temp reads all of it, writes one reply, and forgets.
Animated: one chat turn, and who holds the memory
- You send a message. The app adds it to the transcript it has been keeping.
- The app sends the whole transcript to the model: the system prompt, earlier turns and your new message.
- The model reads everything it was sent and writes one reply. Then it forgets. It keeps nothing between calls.
- The reply joins the transcript. Your next message sends all of it again.
- Tool results and fetched text go in too, so the bundle grows every turn.
- The catch: the model reads the window as one stream of text. It has no built-in way to tell a rule from a quoted email. Working memory is whatever the app chose to send this time.
Working memory, technically
The clearest statement is in a 2023 Princeton paper, Cognitive Architectures for Language Agents, usually called CoALA: “Language models are stateless: they do not persist information across calls.” The paper borrows its vocabulary from cognitive science. Working memory, it says, “maintains active and readily available information as symbolic variables for the current decision cycle”. In a plain chatbot the context window does that job: the system prompt, the conversation, tool outputs and anything retrieved for this turn. CoALA’s own notion is broader, “a data structure that persists across LLM calls”.
For security, the first thing to know is that the model reads the window as one stream of text, and nothing forces it to treat a rule differently from a quoted email. The second is that the window has a size limit. We covered both in Context windows explained. For this note it’s enough that working memory is whatever the application chose to send this time.
Compaction, in plain words
The folder fills up. At some point the office manager takes the oldest fifty pages, writes a one-page summary, and shreds the originals.
The temp now works from the summary. If the summary writer left out “never email the client directly”, that rule is gone, and the temp has no idea it ever existed.
Animated: how compaction can lose a rule
The conversation in the context window
- A long conversation fills the context window. The app is close to the limit.
- One early turn holds a rule that was only ever typed into the chat.
- To make room, a model writes a short summary of the older turns.
- The older turns are replaced by the summary. They are shown faded here. The window now holds the system prompt, the summary and the most recent turns.
- A summary is a guess about what will matter later. Nothing guarantees it keeps an instruction word for word. This one left the rule out.
- The model now works from the summary and has no idea the rule existed. No attacker was needed. Hard rules belong in code, with the system prompt as a second layer.
Compaction, technically
The LangGraph documentation gives two reasons history has to be managed. One is a hard stop: “A full history may not fit inside an LLM’s context window, resulting in an irrecoverable error.” The other is about quality. “Even if your LLM supports the full context length, most LLMs still perform poorly over long contexts.”
Applications respond by trimming old messages, clearing old tool results, or summarizing. Anthropic’s API offers the last as a beta feature called compaction, which “replaces the older turns of a conversation with a summary that Claude writes on the server”. The same page admits the obvious cost. It tells developers to write their own summarization prompt when “the default summary drops something a later turn needs”.
A summary is written by a model, so it is a guess about what will matter later. Nothing guarantees it keeps an instruction word for word.
Long-term memory and its three types, in plain words
Now give the office a filing cabinet that stays overnight. It has three drawers.
The first holds facts: the client is vegetarian, the account number format, who signs off invoices. The second is a diary of past jobs: what was asked, what was done, how it went. The third is the rule book that says how the work is done here.
Each morning someone pulls a few pages from the cabinet and puts them in the temp’s folder. The temp still remembers nothing. Whatever carries over from one day to the next is in the cabinet.
Animated: three kinds of long-term memory, written and recalled
The store. It stays when the session ends
- Long-term memory lives outside the model, in a store that stays overnight. The first kind is semantic: facts about a user or the business.
- The second kind is episodic: a diary of past jobs. These are often shown to the model later as worked examples to imitate.
- The third kind is procedural: how the work is done. In an agent that includes the system prompt.
- At the start of a session the app pulls a few notes and puts them in the prompt. The model still remembers nothing. The store does.
- Agents also write. A new fact gets saved. A finished job gets logged.
- The catch is the third drawer. Some agents can modify their own prompts, and an agent that can rewrite its own instructions is an agent whose instructions can be rewritten. Writing there is riskier than saving a fact.
Long-term memory and its three types, technically
CoALA splits an agent’s memory into “short-term working memory and several long-term memories: episodic, semantic, and procedural.” The LangGraph documentation uses the same three and gives an agent example for each.
Semantic memory is facts, in LangGraph’s table “Facts about a user”. Episodic memory is “Past agent actions”. CoALA’s definition: “Episodic memory stores experience from earlier decision cycles.” LangGraph adds that these “are often implemented through few-shot example prompting”, meaning old runs are shown to the model as examples to imitate.
Procedural memory is the odd one. CoALA counts two forms, “implicit knowledge stored in the LLM weights” and explicit knowledge in the agent’s code. LangGraph’s agent example is the “Agent system prompt”, and it notes that “it is more common for agents to modify their own prompts” than to change their weights or rewrite their code. If an agent can rewrite its own instructions, then its instructions can be rewritten. The CoALA authors flag this themselves: writing to procedural memory “is significantly riskier than writing to episodic or semantic memory”.
The labels are a design vocabulary. Many products store everything in one list of notes and never use the three words.
Storing, recalling and sharing memories, in plain words
How safe the cabinet is comes down to who is allowed to put a page in, and whose pages get pulled for whose folder.
A cabinet per client is the careful setup. One cabinet for the whole office is cheaper and lets the temp learn from everyone’s jobs. It also means a page filed during one client’s job can land in another client’s folder.
Animated: a planted note crossing from one session to another
- Two questions decide how safe a memory store is. Who can put a note in? And whose notes get pulled for whose session? Here an assistant reads a document that user A uploaded.
- The document carries hidden text that asks the assistant to remember something.
- Write: the model decides the text is worth saving. The note is filed in the store, here under a team label.
- Recall: in a later session, the app searches the store for notes that look like the new request.
- The planted note is close enough, so it is loaded. This session belongs to a different user.
- Use: recalled text sits in the context window beside the user's words, and it arrives looking like the agent's own notes. Scope memory per user, control what can trigger a write, and record where each note came from.
The write path and the read path of long-term memory
Storing, recalling and sharing memories, technically
There are two common designs.
The first is a memory file or tool. Anthropic’s memory tool gives the model file commands over a /memories directory, and the model “automatically checks its memory directory before starting a task”. The storage is yours: “Claude requests file operations, and your application runs them.” Coding assistants do something similar with plain files. The Claude Code documentation says the first 200 lines or 25KB of its auto memory index are loaded “at the start of every conversation”. It is frank about what such files are: “Claude treats them as context, not enforced configuration.”
The second is a searchable store. LangGraph “stores long-term memories as JSON documents in a store”, each filed under a namespace and a key, and the store supports semantic search. That is the same nearest-neighbor retrieval a RAG system uses (RAG is the setup where a search step fetches documents for the model to read), with the same weaknesses we described in How RAG search gets fooled.
Writes happen in one of two places. LangGraph calls them “in the hot path”, where the agent saves during the conversation, and “in the background”, where a separate job does it afterward.
Sharing comes down to the namespace. LangGraph notes that namespaces “often include user or org IDs”. A store keyed by user ID keeps people apart. A store keyed by team, or by nothing, is shared memory, and every user of the agent is then writing into what the others will read.
Attack 1: plant a memory that outlives the chat
A prompt injection, text that slips an attacker’s instructions into what the model reads, normally dies with the conversation. If it can get something saved, it comes back in every later session.
Our note on how agents work covers two cases, SpAIware against ChatGPT and the MINJA study. Two more are worth knowing.
In February 2025, researcher Johann Rehberger showed the trick against Google’s Gemini. Gemini, he wrote, “does not invoke certain sensitive tools when processing untrusted data”. So his poisoned document did not ask for a memory write right away. It told Gemini to save false facts later, if the user replied with a word such as “yes”, and ended the summary with a question that invited exactly that. He calls this delayed tool invocation: the attacker “pollutes” the chat context and waits for the user to pull the trigger. Google rated it “an abuse-related risk with low likelihood and low impact”, and Gemini does show “a clear UI indicator when the memory tool is invoked”. It was a demonstration, and the planted memories were harmless nonsense, including an age of 102.
The research version is AgentPoison, presented at NeurIPS 2024, which its authors call “the first backdoor attack targeting generic and RAG-based LLM agents”. They add a few malicious records to an agent’s memory or knowledge base, each tied to a trigger phrase. When a request contains the trigger, the poisoned records are retrieved and the agent follows them. Across a driving agent, a question-answering agent and a healthcare records agent, the abstract reports an average attack success rate of at least 80% with a poison rate under 0.1%, and a drop of at most 1% on normal requests. The introduction splits the number: the poisoned records were retrieved 82% of the time, and the whole attack worked end to end 63% of the time. The qualifiers are heavy. It is a lab result, the attacker needs “partial access to the RAG database of the victim agent”, and the trigger is tuned with white-box access to the embedding model. White-box means the attacker can see inside that model, the one that turns text into search vectors. The authors do report that a tuned trigger transfers to other embedders, including a black-box one from OpenAI.
OWASP’s Top 10 for Agentic Applications, announced in December 2025, has an entry for this class: ASI06, Memory & Context Poisoning.
Three numbers from agent memory research
Attack 2: ask the memory what other people said
Agents that learn from past runs store those runs, and past runs contain what users typed.
A team from Michigan State University and the University of Georgia tested how much of that an outsider can get back. Their attack, MEXTRA, published at ACL 2025, is black-box: “the attacker interacts with the LLM agent only through input queries.” The memory they target holds “pairs of private user instructions and the agent’s generated solutions”. The attacker sends prompts that get the agent to repeat the examples it retrieved.
MEXTRA: stored user queries extracted with 30 prompts (memory of 200 records)
With a memory of 200 records, their 30 prompts could “extract 50 private queries from EHRAgent and 26 from RAP.” By our arithmetic that is a quarter of one store and about an eighth of the other. These were test agents running on GPT-4o with a shared memory. The authors’ own suggestion is the fix: “Introducing user-level and session-level memory isolation would limit attackers’ access to private data”. They raise it in the paper’s limitations section and did not test it.
When compaction drops a rule
This one needs no attacker, and the mechanism is documented. The Claude Code documentation has a troubleshooting entry headed “Instructions seem lost after /compact”. The first cause it lists: “If an instruction disappeared after compaction, it was given only in conversation”. The instruction file at the project root, by contrast, “survives compaction” because it is read from disk again.
For security, that means a guardrail typed into the chat lives in working memory, and working memory gets rewritten. A long enough document or tool output can push the conversation into compaction. We found no published study measuring that as a deliberate attack, so we are not claiming one.
What “forget” means, and where secrets end up
Deleting a memory sounds simple. In a September 2026 preprint, three researchers measured five agent-memory systems that handle a corrected fact by soft revocation, where “a contradicted fact is marked invalid and retained rather than deleted”. Their finding, “across nine policy scenarios and nine models”: “no system enforces revocation by default”. The abstract adds that “the revoked fact is returned wherever the revocation label is visible to the retrieval layer”.
Consumer products give users controls. OpenAI’s help page says you can “delete specific or all memories” and points to Temporary Chat for “a conversation without memory”. We make no claim here about how long deleted items are kept.
For builders, retention is your job. Anthropic’s memory tool page says so directly: storage is client-side, and its security section advises you to “Periodically delete memory files that haven’t been accessed in a long time.”
Secrets are the other half. A model that saves “useful context” will sometimes save an API key or a customer’s medical detail that appeared in the chat. Anthropic’s wording is careful: “Claude usually refuses to write sensitive information to memory files.” The word to notice is “usually”. The page tells developers who need stronger guarantees to strip sensitive data in their own handler before the file is written. It also warns that a path such as /memories/../../secrets.env can reach outside the directory unless every path is validated.
What to check, with an example
Take a made-up clinic, used here only as an illustration. Its booking assistant keeps long-term memory so returning patients don’t repeat themselves, and it reads documents patients upload.
- Is memory scoped to one user? The MEXTRA result depends on a shared store. If the clinic keys memory by clinic and not by patient, one patient’s prompt can retrieve another patient’s earlier request.
- What can trigger a write? The Gemini case shows a document arranging a save that the user then approves without knowing. At the clinic, that could be an uploaded referral letter with hidden text asking the assistant to remember a different phone number for the pharmacy.
- Does each memory record say where it came from? Without a source and a date you can’t find or undo a poisoned entry. Say the clinic discovers a wrong dosage note and can’t tell whether a clinician or an uploaded PDF produced it.
- Where do the hard rules live? Chat-only instructions can vanish in compaction, and memory files are context that the model may not follow. So “never cancel an appointment without confirmation” belongs in code that blocks the cancel call, with the system prompt as a second layer.
- Does delete remove the record from retrieval? The revocation study found records marked invalid still being returned. When a patient asks the clinic to forget an allergy entered by mistake, test that a new session can’t retrieve it, including from backups of the vector index.
- Is anything filtering secrets before a write? The vendor’s own wording is “usually”. If a patient pastes an insurance member number into the chat, a pattern check in the memory handler drops it before saving.
- Can a person read the memory? Rehberger’s advice to Gemini users was to “regularly review their saved information”. The clinic gives staff a page listing what the assistant has stored for a patient, with a delete button.
For the general injection cases and fixes, see Prompt injection: 6 real AI agent hijacks and the 5 fixes.
Sources (all checked 23 November 2026)
- Sumers, Yao, Narasimhan, Griffiths (Princeton University), “Cognitive Architectures for Language Agents” (CoALA), 2023: arxiv.org/abs/2309.02427
- LangGraph documentation, “Memory overview”: docs.langchain.com
- Anthropic, Claude Platform documentation, “Memory tool”: platform.claude.com, and “Compaction”: platform.claude.com
- Anthropic, Claude Code documentation, “How Claude remembers your project”: code.claude.com
- Johann Rehberger, “Hacking Gemini’s Memory with Prompt Injection and Delayed Tool Invocation”, 10 February 2025: embracethered.com. His full name is from InfoQ, 21 February 2025: infoq.com
- Chen, Xiang, Xiao, Song, Li, “AgentPoison: Red-teaming LLM Agents via Poisoning Memory or Knowledge Bases”, NeurIPS 2024: arxiv.org/abs/2407.12784 and neurips.cc
- Wang et al. (Michigan State University, University of Georgia), “Unveiling Privacy Risks in LLM Agent Memory” (MEXTRA), ACL 2025: arxiv.org/abs/2502.13172 and aclanthology.org
- Shen, Toyoda, Leung, “Revoked but Still Authoritative: An Empirical Study of Revocation Enforcement in Agent-Memory Systems”, preprint, September 2026: arxiv.org/abs/2609.08258
- OWASP GenAI Security Project, “OWASP Top 10 for Agentic Applications”, 9 December 2025: genai.owasp.org
- OpenAI Help Center, “What is Memory?”: help.openai.com