Agent Offline Dreaming: A Design Approach for Cross-Session Long-Term Memory

    How can AI agents retain experience across sessions? This article explains why large language models need persistent memory, presents a four-layer memory architecture, and describes an offline "dreaming" mechanism that consolidates, reorganizes, and corrects memory while the system is idle.

    Why Agents Need Cross-Session Memory

    Large language models do not retain what users said in previous conversations. When a new session starts, the system can only feed the model the text it needs in the current context. If an agent repeats the same mistakes across dozens of tasks without carrying lessons forward, its efficiency cannot improve over time.

    Cross-session memory addresses exactly this question: whether experience can be preserved and reused. The scope of “memory” here is clearly defined — it is the experience an agent accumulates through tasks and user interactions, persists across sessions, and can later be read back as plain text. It does not mean modifying model parameters, nor does it mean in-context learning within a single conversation.

    Design Inspiration from Biological Memory

    The brain’s memory system is commonly understood as two cooperating phases. While awake, structures such as the hippocampus rapidly record recent experiences, forming temporary information that can be accessed immediately. During offline periods — sleep or quiet rest — the brain reactivates these experiences, filters out what matters, and integrates the rest into long-term knowledge structures in the cortex.

    This division of labor offers direct inspiration for agent design. Logging should be fast and complete, but raw logs are noisy and unsuitable for long-term storage as-is. Separating instant recording from offline organization keeps the online path simple and moves compute-intensive summarization and error correction to idle periods.

    This is only an analogy. It illustrates an engineering approach of layered systems and offline processing; it does not imply that an agent’s internal mechanisms resemble the brain’s.

    A Four-Layer Memory Architecture

    A complete cross-session memory system can be divided into four layers, each with distinct responsibilities and data forms.

    Layer 1: Raw Records

    The raw record layer stores complete interaction trajectories, including user inputs, model outputs, tool call results, and error messages. Its defining traits are completeness, chronological ordering, and the absence of interpretation. This layer exists for traceability: when a conclusion in an upper layer turns out to be wrong, engineers can go back and check the original evidence.

    Raw records are large in volume and are typically stored in object storage or databases, partitioned by session, with a retention period configured.

    Layer 2: Memory Notes

    The memory note layer holds key observations extracted directly from sessions, such as “this API requires one retry after a timeout” or “the user prefers results in table format.” Each note should be short, independently understandable, and carry source references pointing to the session ID and timestamp in the raw records.

    During a session, the agent can write key observations directly into the note layer. This step requires no elaborate processing — the goal is to leave a trail as soon as possible.

    Layer 3: Memory Representations

    The memory representation layer is structured knowledge produced by merging, deduplicating, and abstracting the notes. For example, multiple notes about the same API timeout can be consolidated into a single rule, annotated with applicable conditions and a confidence score. This layer is usually generated by offline processes and is the part that most needs quality control.

    Layer 4: Context Injection

    The context injection layer decides which memories enter the model’s input when a new session begins. It does not dump all memories at once; instead, it retrieves entries relevant to the current task and controls the total length. This layer is essentially a retrieval and ranking problem. Common approaches include keyword matching, vector search, and weighting by recency or usage frequency.

    The Offline “Dreaming” Mechanism

    Offline dreaming is the key step that ties the memory layers together. It runs when the system is idle, replaying history, reorganizing content, correcting errors, and consolidating experience.

    Trigger Timing

    There are three common triggering methods:

    • Scheduled trigger: process the previous day’s sessions at a fixed time each day.
    • Backlog trigger: start when new raw records exceed a threshold.
    • Idle trigger: start when a user or workspace has been inactive for a long time.

    Whichever method is used, offline jobs should be isolated from online services, running in a low-priority queue or on dedicated batch-processing resources, so they never consume compute needed for online inference.

    Replay and Reorganization

    Replay means reading a session in chronological order to reconstruct the task goal, intermediate decisions, and outcomes. Reorganization means clustering similar experiences scattered across multiple sessions and judging which are one-off incidents and which are stable patterns.

    This step can be handled by model-driven summarization, assisted by rules and statistical methods. The key requirement is that outputs must be reviewable: every conclusion must be traceable to specific original evidence.

    Error Correction

    One of the main values of the offline process is fixing earlier mistakes. Suppose a note says “this command runs without arguments,” but later sessions show it fails in certain environments. The offline job should lower that note’s confidence score, or replace it with a new rule that includes the condition.

    Correction requires version history. Old versions should not be directly overwritten, otherwise there is no way to roll back when problems appear.

    Writing Notes and Representations

    After consolidation, the system writes results into the memory representation layer and updates note statuses, for example marking them as merged, deprecated, or pending manual review.

    Below is a simplified illustrative snippet showing the basic structure of offline consolidation. The function names and data structures are generic examples and do not correspond to any specific system’s interfaces:

    1. from dataclasses import dataclass, field
    2. from datetime import datetime
    3. @dataclass
    4. class MemoryNote:
    5. note_id: str
    6. content: str
    7. source_refs: list[str] # references to session IDs and timestamps in raw records
    8. confidence: float # between 0 and 1, indicating trustworthiness
    9. created_at: datetime
    10. status: str = "active" # active / merged / deprecated
    11. history: list[str] = field(default_factory=list)
    12. def consolidate(notes: list[MemoryNote], summarize, contradicts) -> list[MemoryNote]:
    13. """Offline consolidation: merge similar notes and lower confidence for contradicted ones."""
    14. merged = []
    15. for note in notes:
    16. if note.status != "active":
    17. continue
    18. match = next((m for m in merged if summarize.similar(m, note)), None)
    19. if match:
    20. match.content = summarize.merge(match.content, note.content)
    21. match.source_refs.extend(note.source_refs)
    22. match.history.append(f"merged {note.note_id} at {datetime.now().isoformat()}")
    23. note.status = "merged"
    24. else:
    25. merged.append(note)
    26. for note in merged:
    27. for other in notes:
    28. if other.status == "active" and contradicts(note, other):
    29. note.confidence = max(0.0, note.confidence - 0.2)
    30. note.history.append(f"confidence lowered by {other.note_id}")
    31. return merged

    This code reflects three principles: preserve sources when merging, preserve history when modifying, and adjust confidence rather than deleting outright when correcting. In a real system, similar, merge, and contradicts can be implemented by a model or by rules, and they need accompanying evaluation.

    Boundaries with Adjacent Mechanisms

    Cross-session memory is easily confused with other techniques. Clarifying the boundaries helps with both design and troubleshooting.

    • Model weight modification: parameter updates change the model’s behavior itself; they are costly and hard to roll back. Offline dreaming only produces memory in text form and never touches parameters.
    • In-context learning within a single session: the model adjusts its answers based on prior context within one conversation, and this is lost when the session ends. This is immediate adaptation, not cross-session retention.
    • Context summarization replacement: compressing old conversations into summaries and placing them into a new session. This addresses length limits, but the information loss is hard to control, and it does not handle error correction.