Cross-Session Memory Architecture for AI Agents: Offline Replay and Experience Correction

    This article explains how to build a cross-session memory layer for AI agents that is searchable, auditable, and updatable. It covers a four-layer architecture from raw records to context injection, an offline “dreaming” pipeline for replay and correction, key-event tagging and predictive note-taking, a staged learning loop with long-horizon memory evaluation, and practical engineering considerations such as hybrid retrieval, injection budgets, security, and human review.

    Cross-Session Memory Architecture for AI Agents: Offline Replay and Experience Correction

    1. Background: Why Agents Need Cross-Session Memory

    Most agents perform well within a single session, but once the session ends and the context is cleared, the next task often starts from zero. Errors corrected by users, validated business rules, and troubleshooting experience accumulated during tasks cannot be reliably carried into later sessions. This “session isolation” creates three direct problems: repeated questions, repeated mistakes, and experience that cannot be reused.

    The goal of cross-session memory is not to bring all historical conversations into the next request verbatim. Instead, the agent should extract reusable experience from past interactions and store it in a form that can be retrieved, audited, and updated. Here, “memory” needs a strict definition: it specifically refers to experience that the agent gains from tasks and user interactions, can persist across sessions, and can be read later as plain-text context. It does not include model weight modification, in-context learning within a single session, or replacing the context with a compressed summary of old conversations. Weight modification belongs to training, is costly, and cannot be audited immediately. Single-session in-context learning is short-term working memory. Summary replacement is lossy compression and cannot support on-demand retrieval and correction. Clarifying these boundaries is necessary to make memory an independent engineering layer rather than mixing it into the inference path.

    2. Layered Memory Architecture: From Raw Records to Context Injection

    A practical cross-session memory system usually has four layers, each with a different responsibility. This avoids the crude approach of putting everything into a single vector database.

    1. Raw record layer: Stores raw logs such as session events, tool calls, task results, and user feedback. It is the source of truth for tracing and reprocessing and should not be injected wholesale into context. Raw records should include timestamps, session identifiers, task identifiers, permission labels, and desensitization markers.

    2. Memory note layer: Natural-language notes extracted from raw records by the agent or by offline curation tasks. These include rules, facts, counterexamples, operating steps, and failure lessons. Notes should be short, verifiable, and source-referenced rather than long narratives. Each note should ideally include fields such as applicability conditions, conclusion, evidence, confidence, and expiration time.

    3. Memory representation layer: Structured representations for retrieval, including keyword indexes, vector indexes, entity relations, task tags, and time-decay factors. The representation layer does not replace notes; it helps the system quickly find relevant notes when needed. It should support version management and conflict detection so that old conclusions do not overwrite new facts.

    4. Context injection layer: Recalls a small number of highly relevant experiences from notes and representations based on the current task and assembles them into prompt context. The injection layer must control budget, deduplicate, rank, and label sources and confidence to prevent “memory contamination” from affecting current reasoning.

    These four layers form a closed loop of “record—extract—index—inject.” Raw records ensure traceability, memory notes ensure readability, memory representations ensure retrievability, and context injection ensures usability.

    3. Offline “Dreaming”: Replay, Recombination, Verification, and Consolidation

    During sleep and rest, human hippocampal-like structures replay recent experiences and integrate important content into the cortex to form long-term knowledge. Agents can borrow this division of labor: online sessions handle immediate responses, while idle offline compute handles memory curation. The industry often refers to “sleep-time compute” as using idle time between interactions to reorganize context. This article calls this offline curation process “dreaming.”

    Offline dreaming is not simple summarization. It is a multi-stage pipeline:

    1. Replay: Extract recent raw records by time, task, user feedback, and other dimensions, prioritizing events marked as critical.
    2. Error detection: Compare user corrections, tool returns, and verification results to identify incorrect conclusions, outdated rules, and conflicting notes.
    3. Recombination: Merge scattered observations into higher-level rules, turn failure cases into counterexample notes, and abstract recurring steps into operation templates.
    4. Verification: Self-check candidate notes or call external verification tools and assign confidence. Notes that cannot be verified enter a “pending observation” area and are not injected directly into high-priority context.
    5. Consolidation: Write notes into the memory note layer and representation layer, update indexes, and record versions and sources.
    6. Forgetting and downweighting: Downweight, archive, or delete notes that have not been hit for a long time, have expired, or have been disproven, avoiding memory bloat and contamination.

    A pseudocode sketch is shown below:

    1. def offline_dream(event_logs, memory_store):
    2. candidates = select_events(event_logs, priority="key_or_recent")
    3. for batch in batchify(candidates):
    4. replay = reconstruct_context(batch)
    5. errors = detect_conflicts(replay, memory_store)
    6. notes = extract_notes(replay, errors)
    7. for note in notes:
    8. note.confidence = verify_note(note, replay)
    9. if note.confidence >= THRESHOLD:
    10. memory_store.upsert(note, source=batch.ids)
    11. else:
    12. memory_store.stage(note) # pending observation area
    13. memory_store.decay_and_archive(ttl_policy)

    The key benefit of offline dreaming is separating high-cost reflection from online requests, reducing response latency while using idle compute to continuously correct memory. It also creates engineering requirements: offline tasks need to be idempotent, retryable, and auditable; memory writes need version control; and error correction needs to preserve an evidence chain.

    4. Key Event Tagging and Predictive Note-Taking

    The human brain tags important memories under emotional or chemical signals so that they receive more replay during sleep. Agents can similarly mark key events online: explicit user corrections, task failures, verification passes, recurring patterns, high-impact decisions, and rules involving permissions or funds. Tagging can be done by labeling logs or by writing to a candidate area in an external memory folder for later offline curation.

    There is a core difficulty here: how can an agent predict which current event will matter in the future? The answer is that “taking a note is itself a prediction about the future.” Writing down a rule predicts that it will be needed again. Recording a verified fact predicts that it will not need to be checked again in a future call. Recording a counterexample predicts that a similar mistake can be avoided. Therefore, notes should be designed around future reuse, not around complete retelling of the past. Actionable principles include: short and specific, with applicability conditions, evidence sources, confidence, and expiration policies. Use “candidate notes” for uncertain conclusions and “stable notes” for verified conclusions.

    5. Learning Loop and Capability Stages

    The value of cross-session memory must be demonstrated through evaluation. A general long-horizon memory evaluation can be designed: the agent answers a series of questions by looking up tables in a database or document library. After each answer, the system reveals the correct answer, and the agent can write experience into a memory directory for later sessions. Comparing the cumulative reward curves of a “stateless baseline” and a “memory-enabled store” makes it possible to see whether memory truly improves later task performance.

    Agents at different maturity levels often show different learning patterns:

    • Stage 0: Stateless. Each session is independent, with repeated queries and repeated mistakes; the cumulative reward curve is flat.
    • Stage 1: Scattered notes. The agent can generate many guesses and fragmentary theories, but verification is lacking. Notes conflict with one another, and recall can interfere with reasoning.
    • Stage 2: Integrated notes. The agent begins to merge duplicate observations into rules and steps, but correction depends on manual work and expiration cleanup is insufficient.
    • Stage 3: Verified correction loop. Correct answers, failure counterexamples, and user corrections can be written into memory. Offline replay actively corrects conflicts, and context injection ranks by confidence.
    • Stage 4: Stable reuse and governance. Version management, permission isolation, forgetting policies, and observable metrics are in place, making memory an operational asset.

    The key leap from Stage 1 to Stage 3 is not “remembering more,” but “remembering more accurately, verifiably, and correctably.” Therefore, a memory system must treat verification and conflict resolution as first-class capabilities.

    6. Engineering Implementation Considerations

    In engineering implementation, a memory system can be assembled from general cloud capabilities: object storage for raw logs and note snapshots, logging services for event collection, message queues for triggering offline curation tasks, and vector retrieval plus keyword retrieval for hybrid recall. Monitoring and alerting can observe hit rates and error rates. For example, on Baidu AI Cloud, generic capabilities such as object storage, logging, message queues, and vector retrieval can be combined to build a memory repository, an offline task queue, and a retrieval pipeline. Key points include:

    1. Separate storage and indexing: Store raw records, notes, and representations separately to avoid damaging the source of truth when updating indexes.
    2. Hybrid recall: Combine keywords, vectors, time decay, and task tags to reduce bias from a single path.
    3. Injection budget control: Inject only a small number of highly relevant, high-confidence, unexpired notes, with sources attached.
    4. Security and compliance: Use desensitization, permission labels, audit logs, and injection attack protection to prevent memory from becoming a privilege-escalation channel.
    5. Evaluation system: Establish offline replay evaluation and online A/B metrics, focusing on task success rate, repeated error rate, recall hit rate, and memory contamination rate.
    6. Human fallback: Set up review queues for high-impact rules to prevent incorrect memories from being固化 over time.

    7. Conclusion

    Cross-session memory is not about concatenating historical conversations indefinitely. It is about engineering interaction experience into an independent layer that can be retrieved, verified, and updated. The layered architecture addresses “what to store, how to find it, and how to use it.” Offline dreaming addresses “when to curate and how to correct errors.” Key event tagging and predictive notes address “what is worth remembering.” Evaluation and governance address “whether remembering is effective.” When an agent can replay history during idle time, correct errors, and consolidate experience, it truly has a long-term learning loop across sessions.