# 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.

- Published: 2026-11-23
- Topics: AI security, AI agents, LLM security
- Canonical page: https://thesecguy.com/notes/ai-memory-types-context-long-term-memory-security/
- Publisher: The Sec Guy (https://thesecguy.com)

**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.

<figure class="fig">
<p class="fig-k">One turn of a chat: who holds the memory</p>
<div class="flow">
<div class="node"><b>1. You send a message</b><span>The application adds it to the transcript it has been keeping</span><div class="chips"><i class="chip">app keeps state</i></div></div>
<div class="node"><b>2. The whole transcript goes in</b><span>System prompt, earlier turns, tool results and your new message are sent together</span><div class="chips"><i class="chip">context window</i></div></div>
<div class="node"><b>3. The model answers</b><span>It reads everything it was sent and writes a reply</span><div class="chips"><i class="chip">no state kept</i></div></div>
<div class="node"><b>4. Repeat</b><span>The reply joins the transcript, and the next turn sends it all again</span><div class="chips"><i class="chip">grows every turn</i></div></div>
</div>
<figcaption>Our illustration of a standard chat loop, following the description of working memory in the CoALA paper.</figcaption>
</figure>

## Working memory, technically

The clearest statement is in a 2023 Princeton paper, [Cognitive Architectures for Language Agents](https://arxiv.org/abs/2309.02427), 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](https://thesecguy.com/notes/llm-context-window-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.

<figure class="fig">
<p class="fig-k">What compaction does to a long conversation</p>
<div class="flow">
<div class="node"><b>Before</b><span>System prompt, then every turn and tool result in full</span><div class="chips"><i class="chip">near the limit</i></div></div>
<div class="node"><b>Summarize</b><span>A model writes a short summary of the older turns</span><div class="chips"><i class="chip">lossy step</i></div></div>
<div class="node"><b>After</b><span>System prompt, the summary, then the most recent turns</span><div class="chips"><i class="chip">older turns gone</i></div></div>
<div class="node"><b>What survives</b><span>Only what the summary kept, plus anything reloaded from a file</span><div class="chips"><i class="chip">chat-only rules at risk</i></div></div>
</div>
<figcaption>Our illustration, based on Anthropic's compaction documentation and the Claude Code documentation.</figcaption>
</figure>

## 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](https://platform.claude.com/docs/en/build-with-claude/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.

<figure class="fig">
<p class="fig-k">Three types of long-term memory in an agent</p>
<div class="flow">
<div class="node"><b>Semantic</b><span>Facts. In an agent: facts about a user or the business</span><div class="chips"><i class="chip">what is true</i></div></div>
<div class="node"><b>Episodic</b><span>Experiences. In an agent: past actions, often replayed as worked examples</span><div class="chips"><i class="chip">what happened</i></div></div>
<div class="node"><b>Procedural</b><span>Instructions. In an agent: the system prompt, the code and the model's weights</span><div class="chips"><i class="chip">how to act</i></div></div>
</div>
<figcaption>Our illustration of the memory types table in the LangGraph documentation, which follows the CoALA paper.</figcaption>
</figure>

## 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](https://docs.langchain.com/oss/python/concepts/memory) 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.

<figure class="fig">
<p class="fig-k">The write path and the read path of long-term memory</p>
<div class="flow">
<div class="node"><b>Write</b><span>The model, or a background job, decides something is worth saving</span><div class="chips"><i class="chip">who can trigger this?</i></div></div>
<div class="node"><b>Store</b><span>A file, a database row or a vector, filed under a user or team label</span><div class="chips"><i class="chip">scope</i><i class="chip">retention</i></div></div>
<div class="node"><b>Recall</b><span>Loaded at the start of a session, or searched by similarity to the new request</span><div class="chips"><i class="chip">whose records?</i></div></div>
<div class="node"><b>Use</b><span>Recalled text sits in the context window beside the user's words</span><div class="chips"><i class="chip">read as trusted</i></div></div>
</div>
<figcaption>Our illustration. The chips mark the questions the attacks below turn on.</figcaption>
</figure>

## Storing, recalling and sharing memories, technically

There are two common designs.

The first is a memory file or tool. Anthropic's [memory tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/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](https://code.claude.com/docs/en/claude-md) 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](https://thesecguy.com/notes/rag-cosine-similarity-reranking-poisoning/).

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](https://thesecguy.com/notes/ai-agents-tool-calling-mcp-memory-security/) 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](https://embracethered.com/blog/posts/2025/gemini-memory-persistence-prompt-injection). 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](https://arxiv.org/abs/2407.12784), 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.

<figure class="fig">
<p class="fig-k">Three numbers from agent memory research</p>
<div class="tiles">
<div class="tile hot"><b>&lt;0.1%</b><span>of memory records poisoned was enough</span><small>82% retrieved, 63% end to end, AgentPoison, lab</small></div>
<div class="tile"><b>30</b><span>crafted prompts used to pull other users' requests out of memory</span><small>MEXTRA, ACL 2025, lab</small></div>
<div class="tile"><b>0 of 5</b><span>memory systems enforced a withdrawn fact by default</span><small>Shen, Toyoda and Leung, 2026</small></div>
</div>
<figcaption>Sources: Chen et al. 2024; Wang et al. 2025; Shen, Toyoda and Leung 2026. "0 of 5" is our wording of their finding that "no system enforces revocation by default" across five systems.</figcaption>
</figure>

## 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](https://arxiv.org/abs/2502.13172), 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.

<figure class="fig">
<p class="fig-k">MEXTRA: stored user queries extracted with 30 prompts (memory of 200 records)</p>
<div class="hbars">
<div class="hbar hot"><em>EHRAgent, a healthcare records agent</em><div class="track"><i style="width:25%"></i></div><b>50 of 200</b></div>
<div class="hbar"><em>RAP, a web shopping agent</em><div class="track"><i style="width:13%"></i></div><b>26 of 200</b></div>
</div>
<figcaption>Source: Wang et al., "Unveiling Privacy Risks in LLM Agent Memory", ACL 2025. Bar widths are our arithmetic: 25% and 13% of the 200 stored records.</figcaption>
</figure>

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](https://arxiv.org/abs/2609.08258) 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.

1. **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.
2. **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.
3. **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.
4. **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.
5. **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.
6. **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.
7. **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](https://thesecguy.com/notes/prompt-injection-6-real-ai-agent-hijacks/).

---

**Sources** (all checked 23 November 2026)
- Sumers, Yao, Narasimhan, Griffiths (Princeton University), "Cognitive Architectures for Language Agents" (CoALA), 2023: [arxiv.org/abs/2309.02427](https://arxiv.org/abs/2309.02427)
- LangGraph documentation, "Memory overview": [docs.langchain.com](https://docs.langchain.com/oss/python/concepts/memory)
- Anthropic, Claude Platform documentation, "Memory tool": [platform.claude.com](https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool), and "Compaction": [platform.claude.com](https://platform.claude.com/docs/en/build-with-claude/compaction)
- Anthropic, Claude Code documentation, "How Claude remembers your project": [code.claude.com](https://code.claude.com/docs/en/claude-md)
- Johann Rehberger, "Hacking Gemini's Memory with Prompt Injection and Delayed Tool Invocation", 10 February 2025: [embracethered.com](https://embracethered.com/blog/posts/2025/gemini-memory-persistence-prompt-injection). His full name is from InfoQ, 21 February 2025: [infoq.com](https://www.infoq.com/news/2025/02/gemini-long-term-memory-attack/)
- Chen, Xiang, Xiao, Song, Li, "AgentPoison: Red-teaming LLM Agents via Poisoning Memory or Knowledge Bases", NeurIPS 2024: [arxiv.org/abs/2407.12784](https://arxiv.org/abs/2407.12784) and [neurips.cc](https://neurips.cc/virtual/2024/poster/94715)
- Wang et al. (Michigan State University, University of Georgia), "Unveiling Privacy Risks in LLM Agent Memory" (MEXTRA), ACL 2025: [arxiv.org/abs/2502.13172](https://arxiv.org/abs/2502.13172) and [aclanthology.org](https://aclanthology.org/2025.acl-long.1227/)
- 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](https://arxiv.org/abs/2609.08258)
- OWASP GenAI Security Project, "OWASP Top 10 for Agentic Applications", 9 December 2025: [genai.owasp.org](https://genai.owasp.org/2025/12/09/owasp-top-10-for-agentic-applications-the-benchmark-for-agentic-security-in-the-age-of-autonomous-ai/)
- OpenAI Help Center, "What is Memory?": [help.openai.com](https://help.openai.com/en/articles/8983136-what-is-memory)
