Agent Memory Architecture: Offline Dreaming and Cross-Session Evolution

    This article explains how to build a long-term memory architecture for AI agents. It starts from why single-turn question answering is no longer enough and why long context, summaries, and retrieval each fall short on their own. It then defines what agent memory is and introduces a five-layer architecture: raw records, memory notes, the offline dreaming layer, memory representation, and context injection. A central theme is the "background dreaming" mechanism, in which an agent uses idle compute to replay recent interactions, reconcile conflicting facts, abstract reusable patterns, and forget low-value memories. The article also covers injection-time governance, key design principles, deployment on cloud platforms, evaluation metrics, and common risks with mitigations. Readers will learn how to turn noisy interaction history into structured, retrievable, verifiable, and evolving memory that improves reliability across sessions.

    As agents are increasingly deployed in task processing, knowledge work, and workflow automation, the challenges they face are shifting from “is a single answer correct?” to “does long-term interaction stay stable?” Agents need to remember user preferences, prior task context, tool-call results, lessons from failures, and domain constraints across many sessions. Otherwise, every conversation starts from zero.

    Simply relying on long context, conversation summaries, or external retrieval does not fully solve this. Context windows are limited, summaries lose detail, retrieval can surface the wrong fragments, and unverified historical information can let errors propagate across sessions. To address this, the industry is starting to explore a design that more closely resembles the human memory consolidation process: agents capture raw records during everyday interactions, then use background compute during idle periods for offline reflection, replay, and reorganization. This is commonly called the “background dreaming” mechanism.

    Conceptually, agent memory here refers specifically to information an agent acquires from task execution and user interaction. This information can be read by later sessions as plain-text context and used to improve task performance. It is different from parameter updates during model training, different from the in-context learning within a single conversation, and not the same as simply compressing dialogue history into a summary. Its core goal is to turn scattered, noisy, and sometimes contradictory interaction experience into long-term memory that is structured, retrievable, verifiable, and evolvable.

    Why Agents Need a Long-Term Memory Architecture

    A typical agent execution chain includes user input, intent understanding, task planning, tool calls, result generation, and feedback correction. Within a single task, the agent can rely on the current conversation context. But once you enter multi-turn, cross-session, or long-term collaboration scenarios, problems appear.

    The first problem is context window pressure. As turns accumulate, history messages, tool return values, intermediate reasoning, and user feedback pile up, and stuffing all of it into context drives up latency and cost. Truncating it directly, however, can drop key facts.

    The second is information loss from summary compression. Compressing history into a summary reduces length, but summaries often struggle to retain details, sources, and confidence levels. For example, whether a tool once returned data with a specific structure, whether a user explicitly corrected a rule, and whether a past failure was caused by insufficient permissions or a wrong parameter are all details. If they are over-abstracted, later tasks may repeat the same mistakes.

    The third is the risk of memory pollution. If the agent retains wrong conclusions, outdated facts, or one-off anomalies as long-term experience, these will be repeatedly amplified in future sessions. For this reason, long-term memory cannot just be “stored”; it also needs “offline governance”: replay, comparison, correction, deduplication, down-weighting, and forgetting.

    The value of this architecture lies in extending the agent’s capability from “real-time response” to “continuous evolution.” The agent works not only when it is invoked, but also uses idle compute between interactions for reflection. The system can turn dense interaction logs into stable experience, reorganize scattered fragments into reusable knowledge, and actively correct errors once they are identified, gradually forming more reliable cross-session behavior.

    The Boundaries and Definition of Memory

    Before discussing a concrete architecture, it is worth clarifying the scope of memory covered here. The agent memory discussed in this article emphasizes the following characteristics:

    First, the source is tasks and interactions. Memory is not generated from nothing, nor does it come from the model’s pretraining knowledge; it comes from observations the agent acquires during actual operation, such as user instructions, task processes, tool outputs, environment state, execution feedback, human corrections, and failure records.

    Second, the form is text or structured descriptions that can be read as context. Memory does not exist as hidden weights but as content that can be retrieved, injected, and reviewed. It can appear as fact notes, entity descriptions, preference entries, rule constraints, task templates, error cases, or experience summaries.

    Third, the goal is retention across sessions. Memory needs to cross the boundary of the current conversation and be called upon in the next task. It should answer not only “what just happened” but also “which past information is useful for the current task.”

    Fourth, it needs to be distinguished from real-time context. Temporary context in the current conversation serves immediate reasoning; long-term memory is an experience asset that has gone through offline governance. The two can work together but must not be conflated.

    Given these boundaries, a sound memory architecture can typically be divided into five layers: the raw record layer, the memory note layer, the offline dreaming layer, the memory representation layer, and the context injection layer. The background dreaming mechanism is not an isolated module but a processing flow that runs through all the layers.

    Overall Architecture: Five Memory Layers and Background Dreaming

    The overall architecture can be abstracted as the following flow:

    Raw interaction records → key event marking → memory note generation → offline dreaming replay and reorganization → structured memory representation → retrieval, filtering, and context injection

    Each layer takes on a different responsibility.

    1. Raw Record Layer: Preserve the Immutable Source of Truth

    The raw record layer is responsible for saving the real interaction data of the agent during operation. It is similar to a system’s “experience log,” emphasizing completeness and traceability. Each record can include an event ID, session ID, task ID, timestamp, participant, input content, tool-call arguments, tool return values, user feedback, execution status, and initial tags.

    This layer should not be over-refined, nor should it judge too early which information is important. The offline phase may need to replay details to discover downstream effects. For example, a seemingly ordinary tool-call failure might, after several replays, turn out to be related to permission configuration, argument format, or environment state, and thus form stable troubleshooting experience.

    Pseudocode illustration:

    1. RawEvent = {
    2. event_id: string,
    3. session_id: string,
    4. task_id: string,
    5. created_at: timestamp,
    6. role: string,
    7. content: string,
    8. tool_name: string,
    9. tool_args: object,
    10. tool_result: string,
    11. user_feedback: string,
    12. status: string,
    13. tags: list[string]
    14. }

    Raw records can be written in an append-only fashion to keep them immutable. For high-value events, an importance tag can be attached, such as “user correction,” “key decision,” “tool failure,” “domain constraint,” “privacy sensitive,” or “reusable experience.”

    2. Memory Note Layer: Distill Key Observations from Sessions

    The memory note layer is a transition layer from raw records to long-term knowledge. During a session, some information is useful in the moment but not worth storing long-term; other information may be reused by later tasks. The system therefore needs to identify “content worth writing down” and form memory notes.

    Common memory notes include user preferences, project background, term definitions, operating rules, tool-usage caveats, failure cases, successful paths, and hypotheses pending verification. A note should not merely copy the original dialogue but should contain enough semantic abstraction to be reused across different tasks.

    For example, if a user emphasizes during a task that “all output must include a risk level,” this can be written as a note: “The current user prefers structured output that includes a risk-level field.” Such a note is better suited to later retrieval than the raw dialogue.

    Memory notes typically carry several attributes: topic, summary, source event, confidence, last-updated time, applicable scope, and status. Status can include candidate, verified, expired, and deprecated. This helps prevent wrong memory from persisting indefinitely.

    3. Offline Dreaming Layer: Use Idle Compute for Replay and Correction

    The offline dreaming layer is the key to the entire architecture. It draws on the memory consolidation that occurs during human sleep: the brain replays recent experiences during rest or sleep, integrating important content into long-term memory while weakening irrelevant or wrong information.

    In an agent system, the dreaming mechanism can occur at session end, between tasks, during system off-peak periods, or in scheduled batch processing. Its core process includes:

    • Replay: Read recent raw records and existing notes.
    • Clustering: Group similar events, related tasks, and repeated feedback together.
    • Comparison: Check whether new information is consistent with old notes.
    • Correction: When new evidence conflicts with an old conclusion, update confidence or flag the old note.
    • Abstraction: Distill reusable patterns from multiple concrete cases.
    • Forgetting: Lower the weight of low-frequency, low-value, expired, or high-risk memory.
    • Generation: Output new memory notes, revised notes, or structured memory entries.

    This process does not have to run in real time, which makes it well suited to background asynchronous tasks. It moves expensive reflection, induction, and verification out of the user interaction path, improving online response efficiency.

    4. Memory Representation Layer: Organize Experience into Reusable Structures

    The memory representation layer further organizes memory notes into more stable structures. Different scenarios can use different representations.

    For factual memory, it can appear as entity cards—for example, users, projects, documents, systems, task objects, and their attributes.

    For preference memory, it can appear as rules or constraints, such as “keep answers concise,” “avoid proactively performing high-risk operations,” or “cite sources.”

    For task memory, it can appear as process templates or checklists, such as “confirm fields before processing a certain type of data” or “verify permissions before calling a certain type of tool.”

    For error memory, it can appear as failure-mode descriptions, such as “do not proceed directly to a write operation when the input is empty,” or “when a certain return structure is missing, check the configuration first.”

    Good memory representation should have four characteristics: retrievable, updatable, explainable, and rollback-able. Retrievable means later tasks can find relevant memory on demand; updatable means memory can change as new evidence arrives; explainable means each memory can be traced to its source; rollback-able means wrong memory can be revoked or down-weighted.

    5. Context Injection Layer: Safely Return Long-Term Memory to the Current Task

    The context injection layer is responsible for deciding which memory the current task needs and injecting it into the model context in a controlled way. The difficulty here is not “whether memory exists” but “what to inject, how much, when, and how to avoid interference.”

    The general process includes:

    1. Generate a retrieval query from the current task.
    2. Recall candidate memory from the memory representation layer.
    3. Rank candidates by relevance, confidence, timeliness, and applicable scope.
    4. Remove duplicates, conflicts, and low-quality memory.
    5. Control the injected length to stay within the context budget.
    6. Desensitize sensitive information or perform permission checks.
    7. Organize memory into a clear structure, such as a facts section, rules section, risks section, and historical cases section.

    Pseudocode illustration:

    1. function build_context(current_task, memory_store, budget):
    2. query = extract_query(current_task)
    3. candidates = memory_store.search(query)
    4. candidates = filter_by_permission(candidates, current_task)
    5. candidates = rank_by_relevance_and_confidence(candidates)
    6. candidates = deduplicate_and_resolve_conflict(candidates)
    7. selected = select_within_budget(candidates, budget)
    8. return render_context(selected)

    When injecting, prioritize high-confidence, low-noise memory that is strongly relevant to the current task. For low-confidence memory, mark it as “pending confirmation” to prevent the agent from treating a guess as fact.

    How Offline Dreaming Mimics Human Brain Consolidation

    An important feature of human memory consolidation is that memory is not fully fixed at the moment an experience happens; it gradually stabilizes through replay and reorganization during subsequent rest phases. The agent’s offline dreaming mechanism can be mapped to several steps.

    1. Event Replay

    The system rereads recent raw records, including user feedback, tool results, and intermediate decisions. Replay does not have to play back mechanically in time order; it groups events around task goals, entities, anomaly events, or feedback signals.

    For example, if multiple sessions all show a “missing field in the tool return value” problem, the system can group them under the same theme rather than treating them as isolated events.

    2. Importance Marking

    Not all information is worth storing long-term. The system can judge importance through multiple signals:

    • Whether the user explicitly corrected it;
    • Whether it triggered a failure or retry;
    • Whether it affected a key decision;
    • Whether it recurred;
    • Whether it involves a long-term rule;
    • Whether it is privacy- or security-sensitive;
    • Whether it was successfully reused in later tasks.

    During the offline phase, the system can rescore raw events or adjust the confidence of memory notes that have already formed.

    3. Error Correction

    One of the biggest risks of long-term memory is that wrong information gets deposited as “experience.” The dreaming mechanism therefore needs to handle conflicts explicitly. Common strategies include:

    • If a new fact contradicts an old note, lower the old note’s confidence;
    • If multiple independent sources support the same conclusion, raise confidence;
    • If an old note came from a one-off anomaly, mark it as temporary memory;
    • If an old note has not been referenced for a long time and no longer applies, put it in the forgetting queue;
    • If a new conclusion comes from human confirmation, it may override the old one, but keep a revision record.

    This is similar to the “strengthen important information, weaken noise information” process in memory consolidation.

    4. Experience Reorganization

    Beyond error correction, the offline phase also distills patterns from multiple cases. For example, an agent may repeatedly fail when handling file-type tasks, for reasons involving permissions, formats, size, and encoding respectively. The dreaming mechanism can reorganize these cases into a single lesson: “Before handling file-type tasks, check permissions, format, size, and encoding constraints first.”

    This reorganization turns concrete experiences into general rules and improves reuse across tasks.

    5. Forgetting and Compression

    Long-term memory cannot expand indefinitely. The dreaming mechanism needs to compress or down-weight memory that is low-frequency, low-value, expired, duplicated, or contradictory. Forgetting is not simple deletion but graded handling: it can lower retrieval priority, remove memory from the default injection scope, or keep only a statistical summary.

    The Background Dreaming Task Flow

    From an engineering perspective, offline dreaming can be designed as an asynchronous task pipeline.

    First, collect data to be processed. The system obtains raw records, session feedback, and existing notes that have not yet undergone offline governance.

    Second, generate preliminary tags. Annotate each event with topic, entity, intent, result status, and importance.

    Third, cluster and group. Group similar events into the same cluster, such as the same user preference, the same project background, the same tool error, or the same task type.

    Fourth, retrieve historical memory. For each cluster, query existing notes to decide whether it is an addition, update, merge, or deprecation.

    Fifth, generate a revision proposal. The system can generate candidate notes but must set confidence and review policies. High-risk memory can go to human review.

    Sixth, write into the memory representation layer. Update fact cards, rule entries, task templates, or failure cases.

    Seventh, publish metrics. Record the number of added, revised, and deprecated memories, the number of conflicts, the injection hit rate, and changes in later task performance.

    Illustration pseudocode:

    1. function dream_worker(store):
    2. events = store.fetch_unprocessed_events()
    3. for event in events:
    4. store.annotate(event)
    5. clusters = store.group_similar(events)
    6. for cluster in clusters:
    7. old_notes = store.retrieve_notes(cluster.topic)
    8. new_note = reconcile(cluster, old_notes)
    9. if new_note.confidence >= threshold:
    10. store.upsert_memory(new_note)
    11. else:
    12. store.mark_as_candidate(new_note)
    13. store.mark_processed(events)

    In this flow, dreaming is not completed in one pass but iterates continuously. Each run brings the memory system closer to a “trusted experience base” rather than a simple pile of logs.

    Memory Governance in Context Injection

    Long-term memory ultimately returns to the current task, so the injection strategy is critical. Inject too much memory, and the model may be distracted by irrelevant information; inject too little, and necessary context may be lost. A robust injection strategy usually follows these principles.

    First, prioritize relevance. Information the current task needs should take precedence over a full historical picture. For example, if the current task only involves output format, there is no need to inject many failure cases.

    Second, tier by confidence. High-confidence memory can be used as facts or rules; low-confidence memory should be labeled as pending confirmation and should not serve as a hard constraint directly.

    Third, make conflicts explicit. When two pieces of memory contradict each other, the conflict can be marked in the context along with a handling strategy, such as “prefer the most recently confirmed information.”

    Fourth, control the budget. Set a separate budget for memory injection so it does not consume too much task context. Three approaches can be used: summary-style injection, structured injection, and on-demand expansion.

    Fifth, apply security filtering. When privacy, permissions, or commercially sensitive content is involved, desensitization or permission checks should happen first. Memory retrieval must not bypass access control.

    Key Design Points

    1. Memory Is Not Better When Bigger

    The value of long-term memory lies not in how many pieces of information are stored but in whether the right information is provided at the right time. Memory bloat increases retrieval noise, context cost, and governance difficulty. High signal-to-noise ratio should be the priority.

    2. Memory Must Have a Source

    Ideally, each memory can be traced to an original event, user feedback, or verification record. Memory without a source easily becomes an unauditable guess and is hard to correct when something goes wrong.

    3. Memory Needs a Lifecycle

    Memory should have a lifecycle: creation, verification, update, down-weighting, expiration, archival, or deletion. Time-sensitive content should have an expiry date, and rule-type content should support versioning.

    4. Decouple Offline Dreaming from Online Reasoning

    If every interaction triggers complex reflection immediately, latency rises significantly. A more reasonable approach is to focus the online phase on task execution and necessary note writing, and move complex induction, correction, and reorganization to the offline phase.

    5. Distinguish Factual Memory from Inferred Memory

    Factual memory can come from explicit user input or tool return values; inferred memory comes from model summarization and may contain errors. The system should label the memory type to avoid treating inference as fact.

    6. Support Human Intervention

    In critical business scenarios, fully automated memory governance can be risky. Providing mechanisms such as human confirmation, batch review, blacklist rules, and sensitive-memory locking improves controllability.

    Engineering Implementation on Cloud Platforms

    When implementing a similar system, different modules can usually be deployed as independent services or asynchronous tasks. On Baidu AI Cloud, general capabilities such as object storage, log service, message queues, container platforms, and monitoring and alerting can be combined to support this architecture.

    For example, raw interaction records can be written to object storage or a log service for long-term retention and replay; offline dreaming tasks can be triggered through a message queue and consumed by containerized jobs; memory retrieval and context assembly can run as an independent service; and metrics such as memory count, retrieval hit rate, conflict rate, and injection failure rate can be connected to the monitoring and alerting system.

    This separation offers several benefits: first, it decouples online reasoning from offline governance so background tasks do not affect response time; second, it separates storage from compute for easier scaling; third, it strengthens observability so memory pollution or abnormal recall can be detected more easily; and fourth, permission control can be pushed down to the memory access layer to avoid sensitive memory being injected by mistake.

    Evaluation Metrics

    To judge whether a long-term memory architecture is effective, you cannot look only at “whether information was saved” but should evaluate its actual impact on task performance. Common metrics include:

    • Cross-session task success rate: whether multi-turn task completion improves with memory versus without it.
    • Repeat error rate: whether the agent keeps making the same mistakes.
    • Memory hit rate: whether the information needed for the current task is recalled correctly.
    • Memory noise rate: the proportion of irrelevant or low-quality information in the injected context.
    • Factual consistency: whether memory is consistent with original facts and user feedback.
    • Memory growth rate: whether the number of new memories per unit of time is controllable.
    • Offline governance cost: the compute, storage, and time consumption of dreaming tasks.
    • User satisfaction: whether users need to re-explain the same background repeatedly during long-term interaction.

    Evaluation can use a controlled approach: one group of tasks runs without long-term memory while another runs with it; or the same task type is served with raw logs, simple summaries, and structured memory injection respectively, comparing the differences in results.

    Common Risks and Mitigation Strategies

    1. Wrong Memory Hardening

    Mitigation: offline correction, source tracing, confidence management, and human review.

    2. Private Information Entering Long-Term Memory

    Mitigation: perform sensitive-content detection before writing, permission filtering before injection, and keep only desensitized summaries for highly sensitive content.

    3. Memory Conflicts

    Mitigation: build a conflict-detection mechanism, prefer the most recent and trustworthy source, and, when necessary, explicitly tell the model that a conflict exists.

    4. Memory Retrieval Bias

    Mitigation: combine keyword, semantic, entity-relationship, and task-type recall through multiple channels, and rerank candidate memory.

    5. Over-Personalization of Memory

    Mitigation: distinguish global memory, user-level memory, project-level memory, and task-level memory to avoid local preferences polluting global behavior.

    6. Context Injection Going Out of Control

    Mitigation: set a separate memory budget, use structured templates, limit the length of each memory item, and apply quality filtering to injected content.

    Summary

    The core of a long-term agent memory architecture is not simply adding a “history record” module but building a closed loop from raw interaction to governable memory. It uses raw records to preserve facts, memory notes to distill key observations, offline dreaming to replay, correct, and reorganize, memory representation to form reusable knowledge, and context injection to return experience to the current task.

    The key to this design is turning “memory” from static storage into a dynamic governance process. The agent not only records what happened but also reflects during idle time on which information is worth keeping, which conclusions need correcting, and which experiences can be abstracted into rules. The background dreaming mechanism uses offline compute to do this work, giving cross-session memory higher trustworthiness, controllability, and evolvability.

    For teams that want to build long-term agents, implementation should first focus on memory boundaries, source tracing, offline correction, permission control, and context budget management. As long as these foundational capabilities are designed well, agents can grow from one-off tools into long-term assistants that steadily accumulate experience, reduce repeated errors, and improve task stability.