Rebuilding a General-Purpose AI Agent Memory Architecture: Offline "Dreaming" Consolidation for Cross-Session Experience Learning

    This article breaks down how to build long-term memory for AI agents by separating online capture from offline consolidation—an approach inspired by the hippocampus–cortex split in human memory. It defines what counts as agent memory (external, inspectable text rather than weight updates or in-window context), maps four memory layers from raw logs to injected context, and walks through a background "dreaming" loop that replays recent logs to correct wrong conclusions, merge scattered observations into rules, deduplicate, and prune stale entries. You will also find practical guidance on tagging memories by importance, confidence, recency, and source; on lightweight online writes, hybrid retrieval, bounded injection budgets, and asynchronous replay; and on evaluation, privacy, prompt-injection safety, and staged rollout. The core takeaway: memory is valuable only when it is accurate, revisable, and injected sparingly.

    1. The Starting Point: Why Agents “Forget”

    An agent often performs well within a single session. It reads context, calls tools, and completes tasks. But once the session closes, everything resets. Preferences the user emphasized last week, pitfalls hit on similar tasks, and the correct value for an API parameter discovered only after repeated adjustments are all lost.

    Three workarounds are common in practice:

    1. Stuff the raw conversation history into the context window. Cost grows linearly with session length, hits the limit quickly, and large amounts of irrelevant text dilute attention.
    2. Summarize and compress conversation history. Information density improves, but detail is flattened away, and wrong conclusions can be “locked in” along with the good ones.
    3. Attach retrieval-based memory to the prompt. Relevant snippets are spliced into the prompt. Without a consolidation mechanism, the memory store slowly turns into a pile of fragmented, duplicated, and even contradictory drafts.

    The real problem is not that the agent cannot store enough. It is that what gets stored is messy, retrieval is disorganized, and nothing ever revises what was written. Human beings retain experience over the long term not by piling up raw material, but because memory is repeatedly replayed and reorganized while the brain is offline.

    2. Drawing the Boundary: What Counts as Agent Memory

    Before discussing architecture, it helps to define what agent memory means here. It usually has three traits: it originates from task execution and user interaction, it persists across sessions, and it is read back later as plain-text context. That definition rules out three mechanisms that are easily confused with it:

    • Modifying model weights. This belongs to training or fine-tuning and is out of scope here.
    • In-context learning within a single conversation. It is valid only in the current window and has no cross-session capability by nature.
    • Replacing old conversations with a single summary. This is a context management technique, not a memory system in itself.

    This distinction matters. Without updating weights and without expanding the context window, an agent can still have real long-term memory, because the memory lives outside the model and can be inspected, versioned, rolled back, and deleted.

    3. The Core Idea: Offline Consolidation and “Dreaming”

    3.1 The Hippocampus–Cortex Division of Labor

    The human memory system has a clear division of labor. The hippocampus captures information quickly in the present and forms temporary memories that are immediately usable. When the brain enters an offline state such as sleep or rest, the hippocampus replays recent experiences and refines and integrates the important parts into the cortex, converting them into long-term knowledge.

    Two aspects of this mechanism are worth borrowing for engineering:

    • Online capture and offline consolidation are separate activities. The online path only records; it adds no inference cost to the critical path.
    • The offline stage is not a simple backup, but selective replay and reorganization, while keeping the flexibility to overwrite and forget.

    3.2 Engineering Mapping: Sleep-Time Compute and Background Reflection

    A few years ago, researchers proposed the idea of “sleep-time compute”: the model uses the idle time between two interactions to reorganize existing context instead of spending all its compute on response generation. Following that line of thinking, you can build a background “dreaming” loop for memory consolidation:

    • Online phase: during a session, only do lightweight recording. Write key observations into memory files and tag important events.
    • Idle phase: use the gaps between requests, or idle periods when the user has been inactive for a long time, to have a background job replay recent logs.
    • Consolidation phase: correct conclusions later disproved by feedback, merge scattered observations into rules, deduplicate and compress repeated content, and demote or delete outdated entries.

    One point deserves emphasis: “dreaming” here is a metaphor for the offline consolidation process. It refers to the model reviewing and reorganizing content on idle compute. It is not an anthropomorphic claim, nor does it refer to any built-in capability of a specific product.

    3.3 Tagging: Giving Memory a Sense of “Salience”

    The human brain has something similar to an emotional or chemical signal that marks a memory at a key moment so it gets replayed more often during sleep. In an agent system, this mechanism can be implemented explicitly:

    • Importance tiers: high-importance memories are processed first during replay and injection.
    • Confidence tiers: separate “verified facts” from “unverified hypotheses.”
    • Recency and validity tiers: annotate the valid period or invalidation conditions of an entry.
    • Source labels: record whether an entry came from an explicit user instruction, a tool return value, or the model’s own inference.

    The tiers directly affect later behavior. High-confidence facts are injected into context first. Low-confidence entries only enter the replay candidate pool and are not used in answers directly.

    3.4 The Hard Problem: Predicting “What Will Matter Later”

    Taking notes is essentially a prediction about the future. When the agent writes down a rule, it is predicting that the pattern will be useful again later. When it records a verified fact, it is predicting that its future self will not need to re-check it.

    There is a fundamental tension here: memory is written now, but its value can only be validated later. This means the memory system must be reversible. A sensible objective function should account for two kinds of payoff at once:

    • the probability that the entry will be retrieved in the future;
    • the amount of repeated work or error the entry can help avoid.

    On that basis, a few low-cost signals can be used to filter what is worth keeping:

    • Recurring phenomena: the same class of problem showing up repeatedly within a task family suggests an underlying pattern.
    • Explicit feedback already available: a task being verified or disproved means the conclusion is worth keeping.
    • Explicit user preferences: once a preference stabilizes, its reuse value across sessions is very high.
    • Recovery paths after failures: the path taken to hit and recover from a pitfall usually carries more information than a smooth path.
    • Stable external facts: API parameters, data structures, and domain constraints that rarely change.

    By contrast, one-off details and context fragments that cannot be reused should not enter long-term memory.

    4. Memory Tier Architecture: Four Layers with “Dreaming” Running Through Them

    A practical way to structure this is to split the memory system into four layers, each with a clear job:

    Layer 1: Raw records
    Stores complete interaction logs and tool call traces. It applies no filtering and serves as the traceable source of truth for retrospection and auditing.

    Layer 2: Memory notes
    Structured text written by the online phase, typically containing observations, hypotheses, and items pending verification. It sits between “raw” and “certain,” and contradictions and redundancy are allowed to exist.

    Layer 3: Memory representations
    High-density knowledge produced by offline consolidation: verified facts, reusable rules, failure lessons, and operational checklists. It has explicit structure, confidence, and scope of applicability.

    Layer 4: Injected context
    At the start of each session, the most relevant entries from Layer 3 are retrieved for the current task and injected as part of the prompt. Injection must be restrained, generally following the principle of few entries, high relevance, and with sources.

    The “dreaming” mechanism runs through Layers 2, 3, and 4. Between Layers 2 and 3, it handles replay, correction, merging, deduplication, and promotion. Between Layers 3 and 4, it maintains the index, recency, and conflict state, which keeps the injected content trustworthy.

    An illustrative directory structure:

    1. memory/
    2. ├── raw/ # Raw interaction records (append-only)
    3. │ └── 2026-08-27/
    4. │ ├── session-001.jsonl
    5. │ └── session-002.jsonl
    6. ├── notes/ # Memory notes (written online)
    7. │ ├── 2026-08-27-observ.md
    8. │ └── 2026-08-27-hypo.md
    9. ├── consolidated/ # Representations after offline consolidation
    10. │ ├── facts/ # Verified facts
    11. │ ├── rules/ # Reusable rules and checklists
    12. │ └── lessons/ # Failure and recovery lessons
    13. ├── index/ # Retrieval index (vector + keyword)
    14. └── meta/ # Confidence, validity, source, version

    5. The Full Offline “Dreaming” Loop

    The following sample consolidation flow is illustrative only, meant to explain the logic. It does not represent the interface or parameters of any specific product.

    1. def offline_consolidate(memory_dir, raw_window, budget_ms):
    2. """Replay and integrate recent records during interaction idle time."""
    3. notes = load_notes(memory_dir / "notes", since=raw_window)
    4. # 1. Extract candidate experience: observations, hypotheses, failure paths
    5. candidates = extract_candidates(notes)
    6. # 2. Deduplicate and merge: keep the most specific, most actionable
    7. # phrasing under the same topic
    8. merged = dedup_and_merge(candidates, existing=load_consolidated(memory_dir))
    9. # 3. Resolve conflicts: higher confidence wins; on equal confidence,
    10. # the newer timestamp wins
    11. resolved = resolve_conflicts(merged)
    12. # 4. Correct: downgrade or archive entries disproved by later feedback,
    13. # and keep the correction record
    14. archived = verify_and_downgrade(resolved)
    15. # 5. Abstract and promote: merge multiple observations from the same
    16. # source into a rule, with its scope of applicability
    17. rules = abstract_to_rules(resolved)
    18. # 6. Prune and forget: gradually downweight entries that have not been
    19. # retrieved for a long time and have low confidence
    20. prune(resolved, hit_stats=load_hit_stats(memory_dir))
    21. # 7. Rebuild the index and metadata, and write back version info
    22. write_consolidated(memory_dir, rules, archived)
    23. rebuild_index(memory_dir)

    Three steps in this flow are the most often overlooked, yet they decide memory quality directly.

    5.1 Correction and Self-Repair

    If the online phase writes down unverified guesses, they accumulate into noise as sessions pile up. One of the core values of the offline phase is aligning “the conclusion from before” with “the result that came after”: any entry overturned by later evidence should no longer exist at high confidence. It should be demoted, annotated with the reason for correction, or archived as a “historical error” for review.

    5.2 Merging, Abstraction, and Deduplication

    Scattered observations on the same topic, if left as independent entries, cause retrieval to surface multiple fragments that repeat or even conflict with each other, which wastes context and lowers accuracy. The reasonable approach is to merge at the topic level, abstract at the rule level, and keep the best option at the conflict level.

    5.3 Forgetting and Pruning

    A memory system that never forgets eventually degrades. Forgetting should not mean physical deletion but gradual downweighting: entries that have not been retrieved for a long time, whose confidence stays persistently low, or whose applicable conditions no longer exist should gradually exit the injection set while an audit trail is preserved.

    6. Engineering Implementation Notes

    Keep online writes light. The online phase should append as much as possible and avoid high-latency retrieval and inference. Give the model a minimal write format, for example emitting a short structured “key observations” block after the answer, which the system writes to disk as a notes file.

    Make retrieval hybrid. Pure vector retrieval is insensitive to content that is semantically similar but factually conflicting, while pure keyword retrieval is not robust to changes in phrasing. In practice, combine vector recall with keyword recall, then re-rank with metadata such as time, confidence, and source.

    Give injection a budget. Set explicit caps on the number of entries and characters for memory injection in each session, and prioritize high-confidence, highly relevant, recently verified content.

    Make replay asynchronous. Idle-time work should run in the background as much as possible, constrained by low-priority queues and resource quotas, so it does not compete for the compute and latency budget of online requests.

    Rely on general-purpose components for storage and operations. Memory files and snapshots suit object storage with version management, replay jobs are scheduled through a message queue, and memory-related logs and metrics feed into a unified logging service with monitoring and alerting, so hit rate, conflict rate, and growth trends can be observed. On cloud platforms such as Baidu AI Cloud, these general capabilities—object storage, message queues, container platforms, logging services, and monitoring and alerting—can be composed directly without depending on proprietary interfaces.

    7. Evaluation: Long-Horizon Tasks and Cumulative Payoff

    Evaluating a memory system should not look only at single-turn answer quality, but at cumulative performance across sessions. A general and effective approach is to construct a task family that requires looking things up and verifying across turns:

    • The system presents a set of questions that need to be looked up, and the correct answer is revealed immediately after each response.
    • The model can write experience into the memory directory for use in later sessions.
    • Compare a “stateless baseline” with a “memory store” condition, and observe the slope and final level of the cumulative reward curve.

    From publicly available general experience, models of different capability levels show noticeably different learning shapes under the same mechanism: the weaker tier tends to generate only scattered, unverified guesses, filling the notes files with contradictory hypotheses; the middle tier begins to try integrating notes but lacks verification and deduplication; the stronger tier tends to verify first and write second, forming structured, reusable rules and checklists.

    This difference shows that the effectiveness of a memory architecture depends heavily on the model’s own reasoning and self-verification ability. The engineering-side consolidation flow can amplify that ability but cannot fully replace it. Evaluation therefore needs to cover three dimensions at once:

    • Memory quality: whether entries are structured and carry source and confidence.
    • Correction efficiency: how long it takes a disproved entry to be fixed.
    • Reuse payoff: changes in latency and success rate on the second and third run of the same task.

    8. Adoption Advice and Governance

    Proceed in stages. In the first stage, do only raw records and simple notes to verify whether cross-session gains are real. In the second stage, introduce offline consolidation and focus on correction and deduplication. In the third stage, add conflict resolution, forgetting, and version management.

    Permissions and privacy. Memory files often contain user preferences and business details. Isolate them per user or per tenant, and verify access permissions at the start of each session. Entries containing personal information should have a clear deletion and forgetting path.

    Injection safety. Raw interaction records may contain external content. If that content is written into memory and injected into context without constraints, it creates a risk of indirect prompt injection. Treat memory as untrusted data: usable as reference information only, and never allowed to change the system’s behavioral rules.

    Observability and rollback. Establish versions and change logs for memory entries so that any consolidation can be traced, compared, and rolled back. This is critical for troubleshooting in production.

    State the boundaries clearly. Consolidation changes external text, not model weights. Its gains come from better information organization, not from improved capability. Making this clear avoids unrealistic expectations of what a memory mechanism can do.

    9. Conclusion

    The point of agent memory has never been “how much you store,” but “store accurately, be able to revise, and inject little but well.” Separating online capture from offline consolidation, using idle compute for replay, correction, and integration, and pairing that with sensible injection budgets and governance gives an agent a real chance to accumulate experience across sessions instead of starting from zero every time. This approach depends on no specific product or interface and can be built with general-purpose storage, retrieval, and scheduling components. Any team building long-lived agents should validate it early.