Skip to content
Read, write, and forgetting in agent memory systems

Context is not memory: writing, reading, and deleting in Agent memory

A batch-processing Agent that had been running for two hours began violating the constraint it set at step 3, starting from step 90. The logs were clean, with no errors. The early rule “all notifications go only to the internal group” had been pushed out of the context window after dozens of rounds of tool output.

The implementation at the time concatenated all historical messages into the prompt. It looked like all the state was there, but in reality it had neither structure nor queryability, and worst of all, I had no idea at which step it got pushed out.

After that, I separated two things: context is the projection fed to the model for this round, and memory is persistent data in the system that can be written, retrieved, expired, and deleted. It sounds like a terminology game, but it determined almost all subsequent engineering decisions. Projections can be recomputed on demand at any time; persistent data must be accountable for accuracy.

Post 13/15 of this series · Previous: Agentic RAG: Handing Retrieval to the Agent for Scheduling · Next: Multi-Agent Collaboration: Topology, Communication, and Termination

Four Layers of Memory, with Completely Different Read/Write Modes

Borrowing the cognitive science division is not rigorous, but it is very useful in engineering:

Layer Content Lifecycle Read mode
Working memory State of the current step, fields to fill, recent observations Single task Projected into context each loop
Episodic memory Things that happened: a retrieval result, a failure and its cause Task to session level Retrieved by time/task ID
Semantic memory Facts and preferences distilled from experience Long-term Vector retrieval + entity filtering
Procedural memory Stable practices: tool usage, templates, instruction snippets Long-term, versioned Injected directly, not retrieved
flowchart LR
  subgraph M["记忆四层"]
    direction TB
    W[工作记忆 状态字段]
    E[情景记忆 失败记录]
    S[语义记忆 事实偏好]
    P[程序性记忆 工具模板]
  end
  W -->|每轮投影| C[当前上下文]
  E -->|按时间与任务检索| C
  S -->|向量与实体过滤| C
  P -->|直接注入| C

Working memory is the structured State I wrote about earlier; I insist on externalizing it rather than relying on message history. Its key property is “readable and writable fields” rather than a piece of text. Completion conditions and budget checks must be computed in code; text cannot compute them.

Episodic memory is often overlooked but is actually very useful. “Last week, using scope=changelog to query this database returned all empty; switching to scope=tickets produced results”—this kind of failure experience guides routing better than any static document. It is indexed by task_id and time, and usually does not need vector retrieval, because what you are looking for is “what failure happened recently,” not “the semantically most similar failure.”

Semantic memory is what people most often call “long-term memory”: user preferences, project conventions, domain facts. Technically it is the same stack as the RAG pipeline in posts 4–10, with differences in three places, which I will expand on later.

Do not mix procedural memory into retrieval. Tool schemas, output format templates, and stable system instructions should be versioned and injected directly. Making the model “retrieve” its own operating manual only adds another point of failure.

Writing: The Threshold Matters More Than the Extraction Algorithm

The most common cause of long-term memory getting out of control is not inaccurate extraction, but overly casual writing. Summarize every round of dialogue and store it, and after a few weeks the database is full of noise like “the user asked about X” and “the assistant answered Y” that carries no information, and during retrieval it will push out the genuinely useful entries.

I set three thresholds for writing:

PYTHON8 lines
1
2
3
4
5
6
7
8
def should_write(fact, session):
if fact.kind not in ("preference", "constraint", "stable_fact", "correction"):
return False # 闲聊、一次性查询不记
if fact.confidence < 0.8 or not fact.evidence_turn_ids:
return False # 无出处的不记
if fact.subject_type == "project" and not session.user_confirmed:
return False # 影响面大的要确认
return True

evidence_turn_ids is a field I added later. Every memory must be traceable to the few rounds of raw dialogue that produced it; otherwise, a few months later no one can tell whether it was explicitly stated by the user or hallucinated by the model. This field is also a lifesaver for compliance deletion and correction.

As for extraction, I prefer structured over free text: have the model output records like {subject, predicate, object, scope, confidence, evidence} rather than a summary. Only structured records can be deduplicated, can undergo conflict detection, and can be isolated by user_id / project_id. Free-text summaries are suitable for episodic memory, not semantic memory.

Conflict resolution is the hardest part of writing. “The user prefers concise answers” and, three months later, “reports for this project need to be detailed” are not contradictory, because scope differs; but “the database uses MySQL” and “the database is switched to Postgres” are a real contradiction. My approach: a new record with the same subject + predicate does not overwrite the old record; instead, mark the old record with superseded_by and preserve the timeline; retrieval by default takes only the latest non-superseded entry, and history can be queried when tracing is needed. Direct overwriting is easier, but what is lost is “when it changed and why”—and that is precisely the most valuable information in memory.

Concurrency must also be managed. In multi-turn dialogues or multi-Agent branches, two branches may write the same memory simultaneously. I give each record a expected_version, use optimistic locking for writes, and merge and re-extract on conflict. “Last write wins” is almost always wrong in such scenarios, because it assumes that a later write in time is also newer in semantics.

Reading: Similar to RAG, but with Three Extra Dimensions

Retrieval of semantic memory can likewise go through “vector recall + metadata filtering + reranking,” but three things cannot be omitted.

Entities and permissions. Memory almost always belongs to a certain user, a certain project, a certain tenant. user_id / project_id / acl must be pushed down to the recall stage (posts 5 and 7 repeatedly emphasized this); otherwise, cross-user memory leakage will occur—the most severe class of incident in such systems, and it does not raise errors. I would rather do hard filtering at the retrieval layer than rely on a sentence in the prompt saying “do not use other users’ information.” Handing security to the model’s sampling temperature makes no sense.

Temporality. valid_from / valid_to must be filterable, because “what is the current budget” and “what was last quarter’s budget” are two different questions. Memory entries should preferably carry an effective time, not just a creation time. The temporal conflicts discussed in post 10 appear even more frequently in memory; preferences inherently change.

The number of recalled items must be restrained. Long-term memory usually only needs 3–5 entries injected, and they should be placed near the system instructions as “known constraints,” not mixed in with retrieval material. Stuffing too many old preferences in will steal the show; I have seen an Agent whose answer style became long and awkward after a dozen or so historical preferences were injected.

The retrieval code itself is nothing special; the only thing worth mentioning separately is the filtering order: conditions like superseded_by: None and valid_to >= now must be pushed down before ANN, not filtered after querying. This one ordering difference can change the recall volume by an order of magnitude.

Compression and Externalization: What to Do When the Window Is Nearly Full

For context management in long sessions, my order is: reduce first, then compress, and only externalize last.

Reduce. Keep only structured summaries and necessary fields from tool output; discard the intermediate reasoning of completed steps directly and keep only the artifacts; fold historical messages by round into “what the user asked → what the system did → what the conclusion was.” Most long sessions can get by with this step alone.

Compress. For long content that truly must be retained, summarize it, but the summary must be traceable: record which turns it compressed and where the original content is stored. Don’t delete the original and leave only the summary. A summary will inevitably lose qualifiers, so I always store global constraints separately as structured fields; they don’t participate in summarization, because once they get glossed over, no one will notice.

Externalize. Large blocks of material, complete logs, and intermediate artifacts go to external storage, with only a handle left in context. This is the same idea as the “filesystem as external memory” commonly used by Agents. The key is not to forget after externalizing: there must be a fetch(handle) tool, and the state must record which handles are currently available.

PYTHON10 lines
1
2
3
4
5
6
7
8
9
10
def compact_if_needed(state, ctx, budget):
used = count_tokens(ctx)
if used < budget.soft_limit:
return ctx
keep = state.critical_fields() # 约束、计划、账本,永不压缩
old_turns = ctx.turns[:-budget.keep_recent]
handle = store.write(old_turns)
summary = summarize(old_turns, keep_conditions=True)
state.handles.append(handle)
return build_context(keep, summary, ctx.turns[-budget.keep_recent:], state.handles)

The reason critical_fields needs to be called out separately is that after these fields are compressed away, the system won’t report any error; it will just quietly start violating them. That’s exactly how the accident at the beginning happened. Now I make “are the constraint fields still in context” an assertion checked every turn, and force re-injection if any are missing.

Compression itself has costs: an extra model call, introduced summarization bias, and harder-to-read traces. So at every compression point I always write a log entry recording the before and after token counts, the range of turns compressed, and the list of key fields retained. Without this log entry, troubleshooting “from which step did it start forgetting the rules” becomes extremely painful.

Forgetting: without deletion, it isn’t a memory system

Long-term memory that only writes and never deletes eventually becomes a noise repository, with compliance risks attached. I give memory four exit mechanisms.

Temporary facts carry expiration times; “I’m on a business trip this week” should expire next week. The retrieval weight of long-term entries decays over time, but decay only affects ranking and does not automatically delete; these two things are often conflated into one.

Each user_id + project_id has an item limit. When exceeded, evict by “recent use × confidence × whether referenced,” and write an audit log entry before eviction. The limit doesn’t need to be precise, but it must exist.

When the user says “No, that’s not what I said,” you can’t just add a new memory; you must locate the original record, mark it void, and record the source of the correction. If the old and new entries coexist and neither is marked, the model will waver next time, and no one will know it’s wavering.

The hardest one is compliant deletion: when a user requests deletion of personal data, it must be possible to delete it all at once by user_id, including vector indexes, episodic memory, compressed summaries, and all derived caches. This must be supported from the start of design; retrofitting it almost certainly leaves gaps. The two easiest places to miss are personal information compressed into summaries and residue left by soft deletes in the vector database.

After deletion there’s also the index consistency problem: deleted from the vector database but still in the cache, or the summary still references deleted entries. From the user’s perspective, that’s “it was deleted but it can still answer.” I use a memory_version for invalidation broadcast; caches and summaries carry version numbers, and are rebuilt on mismatch.

Benefits, costs, and when not to do it

The benefits are clear: in long tasks, constraints no longer get lost as the window drifts; cross-session preferences and project conventions can be reused; failure experience can settle into routing knowledge; explicit forgetting makes the system controllable and compliant.

The costs are equally clear. You’re essentially building another small knowledge base, with writing, deduplication, conflict, expiration, and deletion, none of them missing. Memory contamination is far more harmful than a one-off wrong answer: once a false fact is written in and reused long-term, it continuously affects all subsequent tasks, and because no error is reported, it’s very hard to notice. A cross-user isolation leak is a security incident, not a bug. Observability also gets harder: for a judgment in an answer, you need extra provenance tracking to know which memory it came from.

So in some scenarios I explicitly don’t add memory: single-turn Q&A, stateless between tasks, and sessions short enough to end quickly. My criterion is: only if the same user or project will come back next week and last time’s constraints are still valid is long-term memory worth building; otherwise a structured state plus working memory is enough.

There’s also a boundary on the checklist: memory should not replace the source of truth. Business data that changes, such as inventory, prices, and order status, should be queried from the authoritative system every time and must not be cached in memory. Memory is suitable for preferences, conventions, and practices, not for current state. Mixing the two in one store is the root cause of many Agents giving stale answers after launch, and they get it wrong very quietly.

When one Agent can’t hold all the context, it naturally moves toward division of labor. The next post covers multi-Agent collaboration: when multiple Agents are really needed, how to choose a topology, and the termination conditions most prone to going out of control. Before that, here’s a question for self-check: in your current system’s memory, how many entries were inferred by the model itself but have no original source?

About this Post

This post is written by Lu's Blog, licensed under CC BY-NC 4.0.

#Agent #Context #Memory

Comments