Context Engineering · 7 min read
Memory for agents: working, episodic, semantic and procedural memory in practice
An agent with no memory starts from zero every session. Here is a practical map of the four kinds of agent memory, how to store and write each one, and why memory is now an attack surface you have to design for.
A language model doesn’t remember anything between calls. Everything an agent “knows” about you, your project or its own past mistakes has to be stored somewhere and put back into the context window at the right moment.
Agent memory is a system you build around the model. This post maps the four kinds of memory, shows how to store and write each one, and covers the part tutorials often skip: memory is now an attack target.
The four kinds of memory
The vocabulary comes from cognitive science. LangChain’s memory docs use it directly, and it’s a useful way to decide what goes where.
| Type | What it holds | Agent example | Usual store |
|---|---|---|---|
| Working | The current task: messages, tool results, plans | This conversation’s history | Agent state, persisted per thread |
| Semantic | Facts | “Prefers Python”, “team uses Postgres” | A profile document or a collection of facts |
| Episodic | Experiences | How the agent solved a similar ticket last week | Past examples, retrieved as few-shot prompts |
| Procedural | How to do things | The agent’s own instructions | The system prompt (rarely weights or code) |
A December 2025 survey, Memory in the Age of AI Agents, argues that the old long-term vs short-term split is too coarse for the systems now being built. It proposes factual, experiential and working memory — which maps closely onto semantic, episodic and working above — and adds a separate question of form: memory can live as tokens in text, in model parameters, or in latent states.
Working memory: the thread
Working memory is what the agent is holding right now. In LangGraph it’s thread-scoped: the message history and any files or retrieved documents sit in the agent’s state, and a checkpointer persists that state so a thread can be resumed. Separate threads stay isolated.
The problem is size. The LangChain docs note that long histories can exceed the context window, slow responses and raise costs. So working memory needs trimming, summarising or clearing — the same problem covered in our post on prompt and context compression.
Anthropic’s API splits this into two tools that work together. Context editing clears specific tool results on the client; compaction summarises older conversation on the server as you approach the context limit. Their docs suggest using both for long-running agents, with a memory tool to preserve “the information that must survive summarization.” That’s the key idea: compaction is lossy, so anything that must outlive it should be written out first.
Semantic memory: facts about the world and the user
Semantic memory is what most people mean by “the agent remembers me.” LangChain describes two shapes:
- Profile: one document (usually JSON) that’s continuously updated. Easy to inject whole, but the docs warn it “can become error-prone as the profile gets larger,” because each update rewrites or patches the whole thing.
- Collection: many small memories added over time. Each is narrower, so it’s “less likely to lose information,” but the agent now has to find, update and delete the right items, and search gets harder.
In LangGraph, long-term memories live in a store, organised by namespace (like a folder) and key (like a file name). Namespaces usually include a user or org ID:
from langgraph.store.memory import InMemoryStore # dev only; use a DB-backed store in production
store = InMemoryStore()
ns = ("user-42", "facts")
store.put(ns, "lang", {"fact": "Prefers Python examples", "source": "user_stated"})
store.put(ns, "db", {"fact": "Team runs Postgres 16", "source": "user_stated"})
# later, in any thread
hits = store.search(ns, query="which database?", limit=3) # semantic search needs an embedding index
Note the source field. We’ll come back to why it matters.
Episodic memory: what happened before
Episodic memory is the record of past runs. The LangChain docs point out that in practice it’s often implemented as few-shot prompting: store good input/output examples from earlier tasks and retrieve the most relevant ones for the current input. The hard part isn’t storage, it’s selection — picking the two examples that actually help rather than ten that dilute the prompt.
A practical version: when a task finishes and passes its checks (tests green, user accepted the answer), save a short record — task, approach, outcome — and retrieve by similarity next time. Save failures too, labelled as failures, so the agent can avoid repeating them.
Procedural memory: how the agent works
Procedural memory is the agent’s instructions. LangChain notes agents rarely change their own weights or code, but they often refine their own prompts through reflection: feedback comes in, the agent rewrites part of its instructions. Their example is a tweet generator whose users found it easier to critique outputs than to specify a good prompt up front.
A self-edited system prompt is the highest-leverage memory you have, so keep it versioned and reviewable.
How memories get written: hot path or background
LangChain distinguishes two moments for writing:
- Hot path: the agent writes memory during the turn, before responding. Updates are immediate and visible to the user, but you add latency and the agent splits attention between the task and its notes.
- Background: a separate job reads finished conversations and extracts memories later. No latency in the main loop and cleaner separation, but you have to decide how often to run and when.
Anthropic’s memory tool is a hot-path design built around files. You add {"type": "memory_20250818", "name": "memory"} to your tools (no beta header needed; available on Claude 4 and later models), and Claude issues view, create, str_replace, insert, delete and rename commands on paths under /memories. It’s client-side: Claude only requests operations, and your code runs them against storage you control. The API also adds a system instruction telling Claude to check its memory directory before starting and to “ASSUME INTERRUPTION” — record progress because the context may be reset at any time.
The docs put the security work on you. Validate every path, because /memories/../../secrets.env can escape the directory:
from pathlib import Path
ROOT = Path("/srv/agent-memory/user-42").resolve()
def safe_path(p: str) -> Path:
if not p.startswith("/memories"):
raise ValueError("outside memory root")
real = (ROOT / p.removeprefix("/memories").lstrip("/")).resolve()
real.relative_to(ROOT) # raises if it escaped
return real
They also suggest capping file sizes and periodically deleting memory files that haven’t been accessed in a long time.
Managed platforms are moving the same way. In April 2026 SD Times reported that Anthropic put memory for Claude Managed Agents into public beta: memories are files mounted on a filesystem, several agents can share a store without overwriting each other, stores can be scoped read-only or read-write, and every write shows up as a session event that teams can inspect, roll back or redact. Files plus an audit trail is becoming the default shape.
Memory is an attack surface
Here is the part to take seriously. If an agent writes memories from content it reads, anyone who can put content in front of it can try to write to its memory — and that write persists into future sessions.
Two 2026 studies make this concrete:
- MemGhost (arXiv, July 2026; summarised by the Cloud Security Alliance) used a single ordinary-looking email to make agents silently record a false fact in a memory file. The CSA note reports end-to-end success of 87.5% against OpenClaw in background mode and 71.4% on the Claude Code SDK in background mode, and that existing input filters and monitors missed most attempts. The CSA cautions that sample sizes per condition are small.
- MPBench (Dash et al., ICML 2026 workshop) built 3,240 attack cases and found an average attack success rate of 50.46% across two agents. The more permissive agent, with automatic memory injection, was far easier to exploit (66.67% vs 34.25%). Their conclusion: prompt-injection defenses give incomplete coverage of memory attacks.
The recommended defenses overlap across both:
- Tight write policies. Define exactly what the agent may store. “Preferences the user stated” is a policy; “anything useful” isn’t.
- Provenance on every memory. Tag whether it came from the user, a tool, or external content, and treat external-sourced memories as unconfirmed.
- Isolate untrusted input. Let a reader with no write access process emails and web pages, and pass only a bounded summary on.
- Gate or log writes. Ask for confirmation on autonomous writes where you can; log every change with what triggered it either way.
Trade-offs
- Recall vs noise. More memories mean more chances to retrieve the wrong one. Store less, and store it in smaller, labelled pieces.
- Hot path vs background. Real-time and visible, or cheaper and cleaner. You can do both.
- Staleness. A fact that was true in March may be wrong in October. Without timestamps and expiry, old memories quietly mislead.
- Autonomy vs safety. Every memory write the agent makes on its own is one an attacker might trigger.
Where to start
- Get working memory right first. Persist threads, and trim or summarise before you add anything long-term.
- Add one semantic store scoped by user, with a
sourceand timestamp on every entry. - Write a one-paragraph memory policy: what may be stored, from which sources, for how long.
- Treat external content as untrusted for memory writes, and log every write.
- Add episodic and procedural memory last, once you can measure whether they help — and keep self-edited prompts under version control.
Memory is what turns a capable model into an agent that improves with use. Designed carelessly, it’s also what lets one bad email change every answer that follows.