Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

How Agents Achieve True Long-Term Memory: Deconstructing Anthropic's Architecture

This article analyzes Anthropic's Agent Memory architecture, detailing its four-layer hierarchy (Transcripts, Memory Notes, Memory Representations, Injected Context) and the Dreaming process that refines memories through error correction, Wiki organization, selective context injection, goal-driven shaping, and gap-filling, validated by experiments on CL-Bench, Pokémon, and corporate document tasks.

Anthropic recently published a technical article "The components of agent memory" , systematically explaining how agents accumulate experience across sessions and how memory distillation, verification, organization, and context injection let past task experience continue to work in the future. The article covers Claude Code's automatic memory practices and analyzes design methods, actual gains, and limitations through database QA, Pokémon long-horizon tasks, and Wiki construction experiments. This piece focuses on the technical mechanisms and engineering insights most relevant to AI architects.

1. Why Agents Need Memory: Context Window ≠ Long-Term Memory

An agent with a large context window does not automatically possess long-term memory. The context window solves how much information can be processed in the current session; long-term memory solves how experience gained in one task can continue to function in future sessions.

Anthropic explains this using the human brain's memory consolidation: the hippocampus rapidly records experiences, but only some are replayed, filtered, and gradually integrated into long-term knowledge during sleep or rest. Agents can adopt a similar division of labor:

Online phase : Execute tasks, record interactions as logs or transcripts, and promptly flag information worth attention.

Offline phase : Use idle compute to review history, correct errors, distill experience, and organize it into more retrievable knowledge structures.

Anthropic calls this offline organization Dreaming . It does not mean the model literally sleeps; rather, the agent uses extra compute outside the main task to replay, organize, and consolidate existing experience.

Figure 1: Agent Memory layered architecture with Dreaming

Agent Memory layered architecture with Dreaming
Agent Memory layered architecture with Dreaming

This figure is the core of the article. Agent memory is not a simple vector database but a composition of layers with different purposes and lifecycles.

2. Understanding the Four Memory Layers: From Raw Experience to Usable Context

Anthropic defines Agent Memory as knowledge gained from user interactions and task execution that persists across sessions, typically saved as context that remains readable later. Several easily confused concepts must be distinguished:

Model parameter learning : Changing model weights through training; not part of Agent Memory discussed here.

In-context learning : Model adjusts behavior based on current session context; may not persist after session ends.

Compaction : Compressing current session history to continue working in a new context window.

Agent Memory : Preserving valuable experience for future sessions to read and use.

Anthropic organizes memory into four layers:

1. Transcripts: Session Record Layer

Stores raw interaction records produced during task execution: user inputs, model responses, tool calls, tool results, and task processes. Its value lies in preserving factual sources . If a memory later appears incorrect, one can return to the original transcript for verification rather than trusting only the model's summary. Transcripts can be searched and serve as input for Dreaming.

2. Memory Notes: Experience Note Layer

Agent extracts information worth retaining from one or more tasks and writes concise memory notes. Examples:

User explicitly requires a specific output format for all future tasks.

A tool parameter once caused failure; after verification the correct usage is found.

A business rule recurs across multiple tasks.

A solution to a problem has been empirically validated.

The key at this layer is not recording everything that happened, but judging which information may be useful again in the future .

Original Figure 2: Memory Notes position in memory hierarchy

Memory Notes in memory hierarchy
Memory Notes in memory hierarchy

3. Memory Representations: Knowledge Representation Layer

As memories grow, a pile of independent notes becomes harder to understand and retrieve. The agent can further organize notes into higher-level knowledge representations, such as a Wiki: multiple topic pages with links establishing relationships. It acts like a knowledge map:

Topic pages aggregate related facts.

Page links connect cross-topic information.

Indexes help the agent locate quickly.

Subsequent organization can merge duplicate pages, fix broken links, and fill missing content.

This layer is not simply adding more text, but structuring scattered memories into a more navigable form.

4. Injected Context: Context Injection Layer

The most important, frequently used information can be pre-loaded into the next session's context. The agent then immediately has key background, constraints, or current goals without searching memory first. However, injected context must be strictly size-controlled: context tokens have cost, and erroneous memories auto-loaded may persistently influence the model every session. The four layers relate as: Transcript = raw experience, Memory Notes = experience distillation, Memory Representations = knowledge organization, Injected Context = curated entry point for the current task.

3. Memory Is Not Archiving: It Predicts the Future

The hardest part of a memory system is not saving information but judging what information will be worth saving in the future . Writing a memory is essentially a prediction that some future session may need it. For example, recording a verified tool-call rule predicts similar future tasks where re-trial-and-error is undesirable.

Anthropic evaluates this with the Continual Learning Bench (CL-Bench) 1.0 database QA task:

Agent answers a database question in one session.

System provides correct answer or feedback.

Agent can write experience to a cross-session shared memory directory.

Next question starts in a fresh session, but agent can read prior memories.

This tests whether the agent forms a learning loop: Answer question → Get feedback → Analyze error → Verify cause → Distill rule → Reuse in subsequent tasks. Different models vary in loop-formation ability. Weaker models may record unverified guesses; stronger models organize rules, evidence sources, confirmed facts, and common pitfalls together.

Figure 3: CL-Bench performance with and without memory across models

CL-Bench performance with and without memory
CL-Bench performance with and without memory

Original Figure 3 data (Mean Reward):

Opus 5.5: without memory 0.655, with memory 0.838

Sonnet 5.5: without memory 0.644, with memory 0.833

Opus 5: without memory 0.564, with memory 0.828

Opus 4.7: without memory 0.383, with memory 0.700

Sonnet 5: without memory 0.306, with memory 0.610

Sonnet 4.6: without memory 0.330, with memory 0.364

Cross-session memory significantly improves multi-turn task performance in this experiment. But memory alone does not automatically confer learning ability; the agent still needs capacity to analyze feedback, verify hypotheses, and distill rules.

4. Is More Memory Better? Pokémon Experiment Says No

Anthropic studied how agents judge what to remember using Claude playing Pokémon Red. At ~10,000 steps, one model saved 413 files, 225 folders , near a million characters; another saved only 10 files, 2 folders plus a top-level global.md. The former recorded vast battles, items, and NPC encounters; the latter focused on current goals, action plans, route strategies, and verified rules from the game.

Figure 4: Memory directory scale comparison between two models

Memory directory scale comparison
Memory directory scale comparison

Why does less memory work better?

Game state like money and current position is directly readable from the screen; repeatedly saving it adds little value.

Game strategies, route plans, and verified operational patterns cannot always be re-derived from the current frame. If not written to memory, they may be lost in a new session.

Game state constantly changes. Over-recording easily makes memory stale, forcing the agent to spend excessive time maintaining and searching. The original notes Sonnet 3.7 created 6 files and deleted 9 in 17 steps without taking any game action.

Fable 5's global.md resembles a task dashboard recording current goal, next-step plan, and memory usage rules; other directories store location routes and game strategies. For instance, after repeated capture failures, the agent distilled a verified rule: if failing more than three times consecutively, change operation rhythm by adding wait inputs between menu actions.

Figure 5: How memory instructions affect memory quality and task performance

Memory instructions effect on quality and performance
Memory instructions effect on quality and performance

Architect takeaways:

Don't treat every event as long-term memory.

States directly observable from the environment may not be worth saving repeatedly.

Prioritize saving experience, rules, strategies, and user preferences that are hard to re-acquire from the environment.

Memory scale should serve task effectiveness, not be measured by file count or token volume.

5. Dreaming's First Key Role: Correcting Erroneous Memories

A major memory risk: incorrect information may be retained long-term and repeatedly used as fact . Agent judgments during task execution may be wrong initially or become invalid due to environment changes.

Anthropic illustrates with Pokémon's Mt. Moon cave task. The agent incorrectly remembered the Pokémon Center was on the cave's east side. Upon exiting the building, it judged it had left Mt. Moon and marked the task complete. Actually it was still on a wrong route, repeatedly falling back.

Dreaming's fix: review the original session transcript, cross-check memory notes against actual action traces, discover the location judgment error, and correct the corresponding memory.

Figure 6: Dreaming corrects Memory Notes using Transcript

Dreaming corrects memory using transcript
Dreaming corrects memory using transcript

Figure 7: Impact of erroneous vs. corrected memory on action routes

Erroneous vs corrected memory impact on routes
Erroneous vs corrected memory impact on routes

In the experiment, the Dreaming-corrected agent re-entered the cave and reached Cerulean City; the agent retaining the error looped repeatedly and failed. The original also provides cumulative action count progress comparison.

Original Figure 8: Progress comparison to Cerulean City under different memory conditions

Progress to Cerulean City comparison
Progress to Cerulean City comparison

This reveals a key architectural principle: Memory must not only support writes but also be traceable, verifiable, and correctable. If a system only allows appending memories without original evidence, conflict detection, and correction mechanisms, the memory bank may gradually accumulate errors over long runs.

6. Dreaming's Second Role: Organizing Scattered Memories into a Wiki

After many tasks, memory notes may proliferate. Even if each note is accurate, the agent may not efficiently find them. Anthropic had Claude build a Wiki during Dreaming:

Each page focuses on one topic.

Pages establish associative links.

Multi-round organization progressively supplements, corrects, and merges pages.

Agent can understand knowledge relationships via Wiki and combine with search tools to locate source material.

They used a corpus of ~ 350,000 internal documents, ~420 million tokens , with 25 evaluation questions. Over 128 Dreaming rounds, Claude continuously explored files, wrote and corrected Wiki pages, merged duplicates, and fact-checked against sources.

As Dreaming grew from 2 to 128 rounds, Wiki-alone graded criteria coverage rose from 13% to 48% . Combined with search tools, overall score improved from 54% to 61% ; search alone stayed at 53% . The combination also saved ~ 20,000 tokens per question .

Figure 9: Dreaming builds Memory Representations

Dreaming builds memory representations
Dreaming builds memory representations

Figure 10: Wiki effectiveness growth with Dreaming rounds

Wiki effectiveness growth with Dreaming rounds
Wiki effectiveness growth with Dreaming rounds

But Wiki isn't universally helpful. If a question only needs keyword search within a single file, Wiki's extra benefit may be small. In another case, Wiki grew larger than the original corpus: 10 documents ~115 KB produced a Wiki of ~203 KB (1.77×).

Figure 11: Cross-document synthesis vs. single-document retrieval comparison

Cross-document synthesis vs single-document retrieval
Cross-document synthesis vs single-document retrieval

Figure 12: Wiki size exceeding original corpus

Wiki size exceeding original corpus
Wiki size exceeding original corpus

Wiki's value depends on task type:

Cross-document association, synthesis judgment, or calculation → Wiki may have clear advantage.

Single-document information extraction → direct search may be simpler.

If Wiki merely replicates original text and grows larger, it hasn't achieved true abstraction.

The goal of memory representation is to reduce future understanding and retrieval cost, not to create another larger knowledge base.

7. Dreaming's Third Role: Promoting Important Memories to Session Context

Some information is so critical the agent shouldn't wait to search at task start. Dreaming can promote such information to the top of the memory hierarchy, where the Agent Harness auto-injects it into new session context. But injection isn't "more is better":

Each injected memory consumes context tokens.

Erroneous information may repeatedly influence the model every session.

Longer instruction files don't necessarily improve adherence.

Anthropic notes Claude Code's Auto Memory doesn't load all memory files each session; it loads only the first 200 lines or 25 KB of MEMORY.md (whichever limit hits first). This file acts as an index telling Claude what's remembered and where to find details.

Figure 13: Dreaming promotes memories to Injected Context

Dreaming promotes memories to injected context
Dreaming promotes memories to injected context

This reflects a key context-engineering principle: High-frequency, stable, critical information suits pre-loading; low-frequency, detailed information suits on-demand retrieval.

8. Dreaming's Fourth Role: Shaping Memory Around Goals

Memory need not serve all possible future tasks. Different agent roles demand different memories:

Coding agents need project constraints, code structure, build commands, verified debugging experience.

Enterprise knowledge assistants need business concepts, org relationships, process rules, source attribution.

Personal assistants need stable user preferences, long-term goals, confirmed personal background.

Anthropic demonstrated goal-driven memory importance with a contract review task. In a parallel Wiki-building experiment, multiple agents writing to the same contract clause summary page overwrote each other; only 41 of 57 evaluation facts survived (~72% coverage). After adjusting instructions — each contract handled by a separate agent with its own page, quoting clauses verbatim instead of compressing into a shared table — all 57 facts were retained (100%).

Figure 14: Shared page write conflicts vs. per-contract page separation

Shared page conflicts vs per-contract pages
Shared page conflicts vs per-contract pages

This shows memory system quality depends not only on model capability but also on:

Whether memory construction goals are explicit.

Which information must be preserved completely.

How to avoid overwrites during multi-agent parallel writes.

Whether critical facts should be summarized or keep original evidence.

For legal clauses, compliance requirements, interface specs, over-summarization may cause unacceptable information loss.

9. Dreaming's Fifth Role: Filling Cross-Session Knowledge Gaps

A single-session agent sees only information within its current task scope, making it hard to guarantee overall knowledge structure completeness. For example, when building a Wiki, an agent might create page links without creating the target pages, or different sessions might use different names for the same topic.

Dreaming can check structural issues across sessions:

Find links pointing to non-existent pages.

Redirect erroneous links to correct pages.

Add missing indexes and topic pages.

Merge duplicate content.

Verify consistency of inter-page relationships.

The original shows a case: second Dreaming round found 9 links to non-existent pages, corrected them to existing pages, and added 3 new pages including an index.

Figure 15: Wiki structure before and after second organization round

Wiki structure before and after second organization
Wiki structure before and after second organization

This illustrates that long-term memory maintenance involves not just content upkeep but also knowledge structure maintenance.

10. Takeaways for AI Architects: Designing a Sustainably Evolving Agent Memory

Anthropic's experiments synthesize into an engineering loop:

Record experience : Retain session transcripts to ensure important conclusions have traceable sources.

Distill memory : Filter stable, reusable information from tasks, not save entire processes.

Verify memory : Cross-check memories against original records, tool feedback, or external facts.

Organize knowledge : Build structured representations like Wiki when cross-topic, cross-document tasks show clear benefit.

Selective injection : Place a few high-value items in startup context; retrieve others on demand.

Continuous maintenance : Fix errors, expired content, duplicate pages, broken links.

Goal-driven : Decide what's worth remembering based on the agent's role.

This can be abstracted into a reference architecture:

Reference architecture for Agent Memory
Reference architecture for Agent Memory

Three Key Architectural Trade-offs

1. Online writes vs. offline organization? Online writes capture information promptly but consume agent attention and task tokens; offline organization interferes less with the main task but can't guarantee immediate availability. Real systems can hybridize: online phase logs only high-value events and necessary clues; offline phase does systematic organization.

2. How to ensure memory doesn't expire or distort? Memories may be wrong from the start or become invalid due to software versions, project status, or process changes. Memories should carry source, timestamp, verification status, and applicability scope. For high-risk facts, don't rely solely on model-written summaries; preserve original evidence or re-verifiable paths.

3. When is building a Wiki worthwhile? Wiki has maintenance costs and can become another large, stale knowledge base. If tasks are mostly single-document lookup, search may suffice; if tasks frequently need cross-document association, complex entity relationships, or long-term experience reuse, structured memory adds value. Dreaming also consumes extra compute. No need to indiscriminately reorganize all memories frequently; prioritize frequently accessed, volatile, or previously conflicting information.

Conclusion: Agent Long-Term Capability Comes from Experience Accumulation and Correction

The article's core insight is not merely giving agents a memory folder, but treating memory as a system requiring continuous maintenance. A mature Agent Memory doesn't just "remember the past"; it knows which experiences are worth keeping, which conclusions are verified, which information may expire, and how to find and correctly use them in future tasks.

Architecturally, an agent's long-term capability shouldn't rely solely on larger context windows or stronger models. Traceable experience records, verified memories, reasonable knowledge representations, and controlled context injection together determine whether an agent can continuously benefit from task after task.

Anthropic explicitly notes this remains an open research direction: Dreaming incurs compute cost, memories can produce errors or drift, and models cannot accurately predict future task needs. Determining organization frequency, priority, and verification scope requires ongoing evaluation per application.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

AI agentsAgent MemoryContext InjectionLong-Term MemoryMemory ArchitectureAnthropicDreamingCL-BenchPokémon ExperimentWiki Construction

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion