Agent Memory Architecture: From Short-Term Context to Long-Term Knowledge
Building reliable AI agents requires more than a larger context window. This article explains why agents still "forget" critical information even with long contexts, and walks through a production-ready memory architecture. It covers a four-layer memory model (working memory, session memory, long-term facts, and event history), practical short-term strategies such as sliding windows, rolling summaries, and prompt caching, and a hybrid retrieval approach combining structured storage, vector search, keyword search, and graph structures. It also details controlled memory-write pipelines, context assembly with anti-pollution safeguards, dynamic forgetting and deletion compliance, a phased rollout plan, and a five-dimension evaluation framework covering correctness, retrieval effectiveness, temporal reasoning, performance, and privacy.
1. Why Agents Still “Forget” When Context Grows
A user explicitly told an agent they are allergic to a certain food. Days later, after extensive everyday conversation, the agent recommends a dish containing that food. Problems like this often stem not from weak reasoning ability, but from the application lacking a reliable state management mechanism: important information was never persisted, never retrieved at the critical moment, or was overwritten by other content.
A large language model’s inference depends on the input provided with the current request plus the model’s parameters. Unless an application explicitly saves and re-supplies historical information, continuity across requests should not be treated as a default capability.
Even if an application resubmits the full history into the context, that does not guarantee the model can reliably use every detail. Long inputs increase computation cost and time-to-first-token. The position of information within the context, its phrasing, and surrounding noise all influence how effectively the model uses it. The notion that “information in the middle of the input tends to be ignored” is an empirically observed behavior worth testing against your actual tasks—not a universal law that holds for all models and all inputs.
So the real problem a memory system must solve is not “how much history can we fit in,” but four more specific questions:
- What content is worth saving?
- In what form should it be saved so it can be correctly interpreted?
- Which memories does the current task need to read?
- How do we handle information that is outdated, corrected, or requested for deletion?
From this perspective, memory is not a bigger input box—it is a complete data lifecycle.
2. From Cognitive Analogies to Engineering Layers
Cognitive science’s working memory, episodic memory, and semantic memory can help developers divide responsibilities, but they do not prove that agents have human-like memory mechanisms. Computer storage hierarchies offer a more useful engineering analogy: the closer to current computation, the more direct the access but the smaller the capacity; the closer to persistent storage, the broader the retention, but retrieval requires extra scheduling.
Following this idea, agent memory can be divided into four layers.
2.1 Working Memory: Serving the Current Decision
Working memory holds the current user request, the state of the task in progress, the most recent turns of conversation, and tool results needed for the current step.
Its goal is to keep the agent clear about “what is happening right now,” not to preserve everything from the past. Typical contents include pending items, already-verified conditions, unresolved issues, and the next action.
Working memory should have an explicit budget. Large documents, repeated logs, and completed steps should not occupy this layer for long. For multi-step tasks, maintaining structured task state is more robust than asking the model to infer progress from a long conversation transcript.
2.2 Session Memory: Maintaining Phase-Level Coherence
Session memory preserves goals, constraints, conclusions, and to-dos within a single conversation, commonly implemented as a rolling summary.
A summary must not merely record “what topics were discussed.” It should distinguish:
- Confirmed facts
- Claims the user made but that remain unverified
- Suggestions the model offered
- Discarded options
- Constraints that are still in effect
Otherwise, “the model once suggested option X” can easily be compressed into “the user has chosen option X,” causing subsequent actions to be based on a false premise.
2.3 Long-Term Fact Memory: Storing Reusable Information
This layer stores content that remains valuable across sessions: user preferences the user explicitly consented to record, long-term project requirements, stable business rules, and verified facts.
Long-term facts should be as atomic as possible. One record should express one primary fact, with source, validity period, and status attached—rather than stuffing complex relationships into a natural-language summary that can never be updated.
High-impact constraints such as allergies, permissions, and budget limits should get dedicated fields or rule entry points; you cannot rely on similarity search happening to recall them.
2.4 Event Memory: Preserving the Process of Change
Event memory records “what happened and when”—for example, a user changing their address, revoking an authorization, confirming a plan, or completing an approval.
Fact storage answers “what is true now”; event storage answers “how did it get this way.” Together they support traceability, error correction, and “as of a point in time” queries.
The value of layering is that different kinds of information can use different read and update strategies, rather than forcing one storage structure to shoulder every responsibility.
3. Short-Term Memory Management: What Truncation, Summarization, and Caching Each Solve
3.1 Sliding Windows Preserve Local Continuity
Keeping the most recent N turns is a low-cost approach suited to short tasks that mainly depend on recent information.
But a fixed turn count is not a reliable capacity control. A single turn might contain one sentence, or it might contain a very long document. A more sensible control unit is actual input length, with budget reserved for system instructions, tool results, retrieved memories, and output.
Before dropping old messages, extract unresolved tasks and key constraints. Otherwise the sliding window will discard information that is still valid.
3.2 Rolling Summaries Need Guardrails Against Error Accumulation
Rolling summaries typically merge the old summary with new messages to produce a new summary. This reduces history footprint but can distort content turn by turn: qualifiers disappear, speculations become facts, temporary arrangements become long-term preferences.
You can reduce this risk by:
- Using fixed fields to store goals, constraints, decisions, and open questions
- Linking key conclusions to the identifiers of the original messages
- Retaining necessary original records for re-verification
- Periodically rebuilding the summary from original evidence instead of infinitely compressing an existing summary
- Storing user-confirmed information separately from system-inferred information
A summary is a lossy representation. It cannot replace all original evidence, and it must never be the sole basis for high-risk decisions.
3.3 Prompt Caching Is Not Long-Term Memory
Prompt caching reuses partial computation for repeated input. For stable instructions, repeated document prefixes, and similar content, when the implementation supports it and hit conditions are met, it may reduce redundant computation.
But caching does not automatically recognize user preferences, does not maintain fact versions for you, and does not guarantee old information will be used in new requests. It optimizes the computation path, not memory semantics.
In engineering terms, be careful about cache invalidation and permission changes. If cached content involves data access permissions that have been revoked, a cache hit must not cause continued use. Cache policy must be subordinate to data isolation and deletion policies.
4. Long-Term Memory Storage and Retrieval: Why a Hybrid Architecture Is Needed
Long-term memory does not equal a vector database. Different queries should be routed to different data organizations.
4.1 Structured Storage for Exact Facts
Information such as current contact details, authorization status, project budget, and record validity has well-defined fields and update rules, making structured storage the better fit.
Its advantages: exact filtering, constraint validation, and version control. For questions like “is the user currently allowed to receive notifications,” reading an explicit status is more reliable than retrieving a similar-sounding text passage.
4.2 Vector Retrieval for Semantic Association
Vector retrieval is good at finding historically relevant content that is phrased differently. For example, when a user asks about “that plan for reducing wait times,” the system can recall previously discussed performance-optimization events.
However, semantic proximity does not equal factual correctness. Similar content may belong to different users, different projects, or expired versions.
Therefore, tenant, user, resource-permission, and status filtering must run before or during semantic retrieval. Retrieved results then need further checks for freshness, provenance, and task relevance.
4.3 Keyword Retrieval for Exact Identifiers
IDs, error codes, order numbers, and specific terminology should not rely on semantic matching alone. Keyword retrieval fills this gap.
A practical system can fetch keyword candidates and semantic candidates in parallel, then deduplicate and re-rank them. Candidate ranking can combine relevance, recency, credibility, and business importance—but the weights must be tuned against an evaluation set. Do not treat any particular set of numbers as a universal optimum.
4.4 Graph Structures for Relationships and Dependencies
When a business frequently involves relationships among people, organizations, projects, and tasks, a graph can express “who is responsible for what,” “which task depends on which,” and “which rule applies to which object.”
But relation-extraction errors propagate along query paths, and maintaining a graph adds cost. Only introduce one when relationship queries are genuinely important and entity identities can be stably resolved—not for the sake of architectural sophistication.
5. Memory Writes: A Process More Important Than Saving Conversations
Long-term memory should be produced through a controlled write pipeline, not by converting every utterance into a permanent record.
A fairly complete pipeline:
User input or task result→ Extract candidate facts and events→ Assess save value and consent scope→ Link to original evidence→ Detect duplicates and conflicts→ Update fact status or append event→ Build retrieval index→ Record audit information
5.1 Distinguish Statements, Inferences, and Suggestions
“I don’t eat X” is a user statement; “the user probably dislikes X” is an inference; “consider reducing X” is a system suggestion. These three must not be written with the same fact status.
For high-impact information, require explicit confirmation. For low-risk inferences, keep a “pending confirmation” status and restrict their use.
5.2 Store Provenance and Validity for Every Fact
At minimum, a memory record should be able to answer: who it belongs to, what it expresses, where it came from, when it was recorded, when it is valid, and whether it has been superseded.
Here is an illustrative record structure—not an interface from any particular product:
Memory record:Owner: user identifierProject: optional project identifierType: fact / preference / event / task stateContent: a single, unambiguous statementSource: original message or business record identifierRecorded at: system save timeValid period: the time range the fact applies toStatus: active / pending confirmation / superseded / deletedSensitivity level: access and processing restrictions
If you use confidence scores, define what the score means and how it is calibrated. Do not treat a model’s self-reported “high confidence” as a reliable probability.
5.3 Conflict Resolution Must Not Simply Sort by Time
A user saying “I’m temporarily staying at a different address next week” does not mean their permanent address has changed. Update time and validity period must be kept separate.
For conflicting records, three actions are available:
- Explicit correction: mark the old fact as superseded
- Different scopes of applicability: keep both, with conditions attached
- Undeterminable: flag the conflict and ask the user if necessary
This handling avoids silent errors far better than simple overwriting.
6. Reading and Context Assembly: Retrieved Results Are Not Instructions
Retrieving all memories on every request creates noise and overhead. A better approach is to first determine whether the current task needs user history, project state, relationship queries, or time-range queries, and then choose the appropriate retrieval path.
The read pipeline can be summarized as:
Current request→ Identify task and permission scope→ Force-read critical constraints→ Select retrieval channel→ Fetch candidate memories→ Validate versions and validity periods→ Re-rank and deduplicate→ Assemble context within budget→ Generate answer or execute action
Context assembly should preserve provenance, making clear what is a user statement, what is a tool observation, and what is a pending record.
One critical concern is memory pollution: historical text may contain content like “ignore the rules” or “invoke a sensitive operation.” Retrieved text is data awaiting processing—it must never be automatically promoted to a system instruction, nor serve as the basis for permissions.
For high-risk scenarios, add application-level validation. For example, after a dietary recommendation is generated, check it against confirmed allergy constraints; before executing an operation, verify current authorization and required approvals. Safety must not depend on the model “remembering.”
7. Dynamic Forgetting: Reducing Noise and Honoring Deletion
Forgetting involves at least three distinct mechanisms.
The first is exit from the current context. The information still exists in storage; it simply no longer participates in this round of inference.
The second is logical invalidation. The record is marked expired or superseded, no longer returned by ordinary retrieval, but may still be usable in authorized historical queries.
The third is actual deletion. At the user’s request or per data retention policy, the content and its derivable indexes are purged.
These three must not be conflated. Removing a record from the vector index does not mean it has disappeared from summaries, caches, raw logs, and backups.
The deletion process must cover primary storage, retrieval indexes, derived summaries, and caches, and it must define retention periods for backups plus post-restore handling rules. Even for backups still within their allowed retention period, restore operations must not bring deleted data back into the online system.
Also, retention value must not be determined purely by access frequency. A low-frequency but critical safety constraint may be far more worth preserving than frequently mentioned small talk. Forgetting policy should be designed around business risk, validity periods, explicit consent, and data minimization principles.
8. How a Production-Grade Hybrid Architecture Lands
A progressive build-out plan:
- Use a working-state store to manage the current task
- Use a rolling summary to maintain session continuity
- Use structured storage to maintain currently valid facts
- Use event records to preserve the history of changes
- Use keyword and vector indexes to support historical retrieval
- Add relationship-query capability on demand
- Thread audit and permission control through all reads and writes
The write path and the answer path can be moderately decoupled. Non-critical events can be extracted and indexed asynchronously to avoid slowing responses; but newly confirmed safety constraints and authorization changes must be immediately readable by the next operation, not left waiting for background indexing.
Asynchronous processing must also account for duplicate delivery, retry-on-failure, and concurrent updates. Use stable event identifiers for idempotent writes, use version checks to prevent old results from overwriting new facts, and monitor index lag.
You don’t need every component on day one. Short tasks can start with windows and structured state; add long-term facts when cross-session needs appear; add hybrid retrieval when historical semantic queries grow. Architectural complexity should be driven by the actual errors you observe.
9. Evaluation: More Than Whether the Model Sounds Fluent
A memory system needs evaluation on at least five dimensions.
9.1 Memory Correctness
Check whether fact extraction is accurate, whether inferences are misrecorded as facts, whether temporary information is being saved as long-term, and whether superseded versions are still in use.
9.2 Retrieval and Utilization
Evaluate separately “was the needed information retrieved” and “once retrieved, was it used correctly.” These correspond to different failures: the former is a retrieval problem; the latter may be a context-assembly or generation problem.
9.3 Temporal and Conflict Handling
Test scenarios like preference changes, authorization revocation, temporary addresses, and same-named projects across multiple projects, verifying that the system correctly distinguishes time and scope of applicability.
9.4 Performance and Cost
Monitor time-to-first-token, full-response latency, retrieval latency, input length, background write cost, and tail latencies. Cache benefits should be measured under real hit conditions, not inferred theoretically.
9.5 Privacy and Security
Cover cross-user retrieval isolation, reads after permission revocation, malicious text entering memory, residues after deletion, and audit-chain integrity.
Evaluation data should span long time horizons, multi-turn corrections, similar-but-conflicting facts, and large volumes of irrelevant content. Include baselines such as no memory, sliding window only, summary only, and hybrid memory, to determine whether new modules actually reduce errors rather than just adding complexity.
10. The Core Innovation: Memory as a Governable State System
Innovation in agent memory architecture does not primarily lie in further expanding the context window, but in decomposing “remembering” into engineering capabilities that are verifiable, updatable, authorizable, and deletable.
Short-term context handles current computation; summaries handle phase-level coherence; structured facts handle exact state; event records handle change traceability; retrieval handles on-demand activation. Only when these coordinate through unified rules for provenance, permissions, versions, and lifecycle do they form reliable long-term memory.
In the future, models may participate more deeply in memory selection, compression, and updating—but that will not eliminate the need for external governance. Whether information lives in the input, in external storage, or in the model’s internal state, the application still must demonstrate that information sources are trustworthy, usage scopes are legitimate, updates are correct, and deletion requests are actually fulfilled.
A truly mature agent is not the system that stores the most history. It is the one that reads the correct state at the right moment, knows to verify when uncertain, updates when information becomes stale, and genuinely forgets when it is supposed to.
