Agent Memory Architecture: A Layered Design and the Dreaming Mechanism

    This article explains why AI agents need memory that persists across sessions and how to design it. It clarifies what counts as agent memory versus model weight updates, in-context learning, and summarization, then walks through a four-layer architecture, write policies for deciding what is worth storing, the offline Dreaming consolidation process, retrieval strategies, evaluation findings, and practical deployment advice.

    1. Why Agents Need Cross-Session Memory

    A large language model’s context window is inherently volatile. Once a session ends, the reasoning traces, tool call results, and user preference corrections in that window are gone. If every new session starts from scratch, the agent has to ask for the same background information over and over and cannot accumulate experience from past failures. As a result, the industry increasingly treats memory as a separate engineering concern rather than just part of context management.

    First, it helps to define the boundary. Three mechanisms are often mistaken for memory but are out of scope here:

    • Model weight updates: These change the internal parameters learned during training. They are a training-side activity with long cycles and high cost, not session-level memory.
    • In-context learning: This happens only within the current conversation and expires when the session ends.
    • Summarization and compression: Writing older turns into a summary lets a single task continue in a fresh context window. It serves the continuity of one task, not knowledge retention across tasks.

    Agent memory refers to knowledge that an agent learns from experience and retains across different sessions. That experience includes both interactions with users and tasks that have already been executed. Memory is stored as files, folders, or other persistable context so that later sessions can read it again.

    2. A Four-Layer Memory Architecture: From Raw Records to Injected Context

    A practical memory system is usually divided into four layers. The lower layers are more raw and complete; the upper layers are more refined and closer to the moment of reasoning.

    1. Searchable session records (the bottom layer)
      Stores complete, unprocessed history: user inputs, tool calls, returned results, and failure stack traces. Its value is evidence retention. It is not meant to be read directly into context but retrieved on demand.

    2. Memory notes
      Observations and conclusions that the agent actively writes down during a session, for example, “This user’s reports are based on tax-inclusive amounts” or “This API times out when pagination exceeds 200 pages.” Notes are compressed, intent-bearing information with a higher signal-to-noise ratio than raw logs.

    3. Memory representations such as a wiki
      Organizes multiple notes and records into structured knowledge: entity pages, concept pages, process pages, and their cross-references. It suits reasoning across documents and tasks, such as consolidating constraints from several project documents into a single specification page.

    4. Injected context (the top layer)
      The minimal necessary set loaded at the start of every new session: stable user preferences, hard constraints for the current task, and key indexes. The principle is to bring important and stable information into context ahead of time, keep detailed material in the lower layers, and search for it when needed.

    The direct benefit of this layering is that complete records remain available for traceability, while each session is not overloaded with content, avoiding context bloat and attention dilution.

    3. Write Policy: What Is Worth Remembering

    Writing more memory does not necessarily produce better results. Noisy memory crowds out context and misleads later decisions. Four filtering criteria help:

    • Filter for important information: Record only signals that change later behavior, such as preferences, constraints, corrections, and conclusions.
    • Keep evidence: Conclusions should point back to a location in the raw records for review and correction.
    • Correct promptly: When old memory conflicts with facts, overwrite it or mark it invalid rather than stacking new information on top.
    • Organize by task: The same fact needs different structures under different tasks, so retrieval units should fit the usage scenario.

    An illustrative write convention (pseudocode that expresses structure only and does not reference any specific product API):

    1. def write_memory(observation, evidence_ref, ttl=None, supersedes=None):
    2. if not is_behavior_changing(observation):
    3. return # Do not persist low-value information
    4. if supersedes:
    5. mark_invalid(supersedes, reason="corrected")
    6. memory = {
    7. "text": observation,
    8. "evidence": evidence_ref, # Points to a locatable segment in the session records
    9. "scope": infer_scope(observation), # User-level / project-level / global
    10. "ttl": ttl,
    11. }
    12. append_to_notes(memory)

    The key points are evidence and supersedes: the former ensures auditability, and the latter keeps the memory store from degrading due to contradictory information.

    4. Dreaming: Offline Consolidation

    Humans form memories quickly while an experience is happening, and some of them are replayed and consolidated during sleep or quiet rest, gradually becoming part of long-term knowledge. Agents can follow a similar division of labor: write the process to logs or session records while executing tasks, and during idle “sleep time” use compute to organize records, fix errors, and generate notes and knowledge structures suited for long-term use. This offline process can be called Dreaming.

    Dreaming has a clear scope of responsibility:

    • Correction: Fix wrong conclusions in notes against evidence and mark invalid memories.
    • Induction: Extract commonalities across multiple records to form rules or process pages.
    • Maintenance: Deduplicate, merge, rewrite titles and summaries, and update the wiki’s cross-references and indexes.
    • Layer movement: Move information between notes, memory representations, and injected context, promoting stable items upward and pushing details downward.

    In engineering terms, Dreaming is an asynchronous batch job, usually triggered by a scheduler or by idle time. It reads and writes the same persistent store but avoids conflicts with online writes through version numbers or check-before-write validation.

    1. Session records (immutable) --scan--> Dreaming --> Memory notes
    2. | |
    3. |-induce-> Wiki representation
    4. |-refine-> Injected context

    5. Retrieval and Use: Load on Demand, Not Full Injection

    When a new session starts, it loads only the minimal set in the injected context; everything else is obtained through retrieval. Retrieval units should match the knowledge structure: semantic similarity search at the notes layer, entity and link navigation at the wiki layer, and structured filtering (time, task identifier, result status) plus keyword lookup at the raw records layer.

    A practical trade-off: for single-document, single-fact queries, searching raw records directly is often faster and more accurate; for cross-document reasoning that synthesizes constraints from multiple sources, the wiki is more suitable. Make the two a routable choice rather than forcing a single unified path.

    6. Evaluation Perspective and Common Findings

    Evaluation of this kind of memory component typically covers several task shapes: long-horizon conversation benchmarks, game-style tasks requiring long-cycle strategies, large-scale internal document question answering, and high-precision scenarios such as legal documents. Four conclusions recur:

    • Memory is not better in larger quantities; filtering and correction matter more than capacity.
    • Keeping evidence significantly improves correctability and trustworthiness.
    • Offline consolidation improves overall performance but consumes additional compute, so trigger frequency should be weighed against value.
    • Structured knowledge representations excel at cross-document reasoning but do not necessarily beat direct search for single-document retrieval.

    7. Deployment Recommendations

    • First build session records into an immutable, searchable foundation, then build upward layer by layer; do not start by maintaining a complex wiki.
    • Set scopes and lifecycles for memory, storing and expiring user-level, project-level, and global memory separately.
    • Make Dreaming an observable offline pipeline that outputs a change log for rollback and auditing.
    • On the cloud, use general-purpose capabilities: object storage for memory files, a message queue to trigger offline consolidation, a container platform to run batch jobs, and logging, monitoring, and alerting services to track consolidation quality and resource cost.
    • Continuously evaluate with four metrics: write volume, hit rate, correction rate, and injected token share, to avoid a growing memory store with no increase in benefit.

    Overall, the core of agent memory is not larger storage but clear layering, strict write filtering, and an offline consolidation mechanism that continuously corrects and generalizes.