Cross-Session Memory for AI Agents: Engineering Practices

    Reliable cross-session memory requires more than preserving chat history. This article explains how to separate episodic, semantic, procedural, and working memory; write and retrieve evidence-backed records; reconcile past actions with current system state; and track version drift. It also outlines a minimal implementation loop and regression tests for evaluating whether an agent can reliably resume long-running work.

    For AI agents working on long-running tasks, the hardest problem is often not generating a single response. It is picking up the same workflow after a break.

    Many teams encounter a familiar failure: requirements were broken down, code ran successfully, and results were saved the night before. The next day, the user says, “Continue reviewing the execution results,” and the assistant has no idea which task they mean. More troublingly, it may deny an operation that actually happened. Or it may spend considerable time analyzing mismatched tool versions without recording when the mismatch appeared or which part of the workflow it affected.

    This is not best understood as a model suddenly becoming less capable. The more precise diagnosis is that reasoning context, external state, and auditable records are out of sync. The context window contains only the context available to the current interaction. Processes, files, and external systems may already have changed. Without structured memory and execution receipts, the model has to reconstruct events from incomplete prompts.

    The following approach addresses these failures through memory design, write and retrieval paths, action consistency, and a practical implementation loop.

    Three Common Failure Modes

    Session amnesia

    After an overnight break, a shift handoff, or a new session, the assistant cannot recall the goal, constraints, completed steps, or artifact locations. The user assumes the project is still available, but the system effectively has only an unindexed chat history.

    Denial of completed actions

    An operation was explicitly authorized and executed—for example, restarting a service process, changing a configuration, or submitting a data-fetch job. When asked about it later, the assistant applies a static rule such as “I cannot execute that independently” and denies the historical event.

    The rule may be reasonable, but it must not override a persisted execution record.

    Silent drift

    The command-line tool, running service, dependency lockfile, or configuration snapshot is on a different version. The assistant notices the inconsistency but fails to record the discovery time, potential impact, and decision made at that point. Later troubleshooting starts from scratch, and conclusions become inconsistent.

    All three failures share the same root cause: treating the text visible in the current prompt as the only source of truth. Long-running tasks need memory that is searchable, traceable, and reconcilable with external state.

    Separate Memory by Purpose

    A common engineering approach is to separate memory by function rather than place everything in an increasingly long system prompt.

    Episodic memory records what happened. It captures the time, participants, goal, key decisions, artifact paths, and outcome. It answers, “Where did we leave off yesterday?” Entries should be short and have stable identifiers, rather than consist of large blocks of raw conversation.

    Semantic memory records stable knowledge. This includes project terminology, directory conventions, environment differences, prohibited actions, and acceptance criteria. It answers, “How does this project normally work?” Entries should support human revision and expiration instead of remaining permanently pinned.

    Procedural memory records repeatable workflows. It describes the inputs, outputs, and checkpoints for tasks such as collecting job listings, generating reports, or checking versions. It answers, “How do we continue next time?” Secrets, tokens, and sensitive personal information should not appear in searchable memory text.

    Working memory remains the current context. It contains the current goal, a small number of retrieved memories, and actions awaiting confirmation. It should stay small and fresh, populated through retrieval rather than unlimited history concatenation.

    With these layers in place, forgetting becomes a failure to write or retrieve memory—not a vague claim that the model lacks memory in its weights. Both failures can be observed through logs and tests.

    Writing Memory: When and What to Save

    Free or self-hosted memory add-ons often work reasonably well because they provide a write path that ordinary sessions lack. Writing too frequently creates noise; writing too rarely makes overnight forgetting likely.

    Useful write triggers include:

    • A task goal is confirmed or changed.
    • A stage completes, such as runnable code, a successful pipeline, or a generated report.
    • The user explicitly authorizes an operation with side effects, and the operation is executed.
    • An environment mismatch, error, or workaround is discovered.
    • A session is about to end, or inactivity exceeds a configured threshold.

    Use a fixed schema rather than free-form prose. For example:

    1. id: mem-20260430-001
    2. type: episode
    3. time: 2026-04-30T22:10:00+08:00
    4. goal: Collect product manager job listings and generate an analysis
    5. status: pipeline_passed
    6. artifacts: [report summary path, raw data directory]
    7. decisions: [collect only public listing fields, do not retain login state]
    8. next: Review execution results and assess productization
    9. evidence: run-id and exit code

    Fields should be neutral and verifiable. Do not store passwords, cookies, internal host details, or identifiable third-party account information.

    If artifacts reside in object storage or a file volume, memory should contain only logical paths and checksums. The actual artifact contents should be read from the current system.

    Deduplicate before writing. Do not repeatedly append the same goal and conclusion within a short period; update the status and timestamp instead. After a successful write, provide a brief acknowledgment such as “Recorded the completed stage and next step.” This tells the user that persistence actually occurred, rather than merely being promised.

    Retrieval: Recall Before Answering

    When a user returns and says, “Continue with yesterday’s results,” the system should retrieve context before generating an answer:

    1. Extract relevant entities from the message: time range, task name, artifact type, and action verbs.
    2. Search open goals in episodic memory, then look for checkpoints in procedural memory.
    3. Load only a few relevant entries into working memory, retaining their source identifiers.
    4. If nothing matches, explicitly state that no corresponding task was found in memory. Offer a few recent open goals for selection rather than inventing a plausible project.
    5. Distinguish between what memory records and what a fresh state check shows. If they conflict, use verifiable external state as the authority and write a correction back to memory.

    Retrieval does not require a complex vector database from day one. For a modest number of tasks, reverse chronological ordering and keyword filtering can already address overnight forgetting.

    At larger scale, vector retrieval or full-text indexing can provide candidate matches, followed by rule-based reranking. Give priority to unfinished tasks, recently confirmed goals, and entries with evidence identifiers. A highly similar but obsolete plan should not rank above a current one.

    Actions Need Receipts; Rules Must Not Deny Facts

    A rule such as “Restarting a service requires human confirmation” can remain in force. However, it governs future actions; it cannot rewrite the past.

    Every operation with side effects should produce an execution receipt that the model cannot arbitrarily overwrite. The receipt should include:

    • Who authorized the operation.
    • A summary of the authorization.
    • The planned command or operation category.
    • The actual result.
    • The timestamp.
    • The associated memory identifier.

    When the user later asks, “Did the restart finish?” the system should read the receipt first. If it records successful execution, report the result and time. If the receipt is missing, say, “There is no execution record,” and propose checking the process state. Do not infer that the operation never happened simply because a policy restricts it.

    Keep two policies separate:

    • Authorization policy: Do not initiate restarts, deployments, deletions, or similar operations without confirmation.
    • History policy: Acknowledge operations supported by receipts. If state has since changed, explain that the operation occurred at the recorded time but the current state is different.

    This prevents both unauthorized action and retrospective denial based on a rule.

    Put Versions and Environments on One Timeline

    When tools and services differ by a few minor versions, a passing remark that they are “inconsistent” does not help the user understand the impact. Make version checks explicit checkpoints:

    • Record the command-line tool version, service process version, configuration summary, and timestamp.
    • When versions differ, write an episodic entry and identify potentially affected capability categories—for example, new parameters not recognized by the running process.
    • Do not mark the task as passed until the mismatch is resolved.
    • After the fix, append a closure record rather than overwriting the original issue.

    There is no need to invent performance figures or proprietary interfaces. Recording the versions observed during each run gives later troubleshooting a starting point.

    Logs and monitoring systems should hold runtime facts. The memory layer should retain references and conclusions, avoiding two independent narratives that disagree about what happened.

    A Minimal Working Loop

    An external memory layer can be reduced to four steps without depending on a particular agent product.

    Capture: Extract goals, constraints, decisions, and artifacts from the conversation. Discard small talk and repetitive failure logs.

    Store: Keep episodic, semantic, and procedural memory in separate collections. Give each entry an identifier, timestamp, and status. Store large artifacts in object storage or a local volume; retain only pointers in memory.

    Recall: At the beginning of a new session, search open tasks. When a match is found, ask the user whether to continue it before loading the details.

    Reconcile: For questions such as “Was it done?”, “Are the versions consistent?”, or “Where are the results?”, read execution receipts, file checksums, or service health status. Correct memory when it disagrees with the checked state.

    The sequence matters more than the framework:

    1. on_user_message(text):
    2. hits = search_open_memories(text)
    3. if hits and user_confirms(hits[0]):
    4. context = load(hits[0]) + fresh_state_check()
    5. else:
    6. context = clarify_or_new_goal(text)
    7. answer = reason(context)
    8. if task_boundary_or_side_effect(answer):
    9. save_memory_and_receipt()

    Evaluation should measure more than response fluency. Maintain a small set of regression tests:

    • Can an overnight follow-up retrieve the goal and artifact locations?
    • Does the assistant acknowledge an operation that was executed?
    • Does a version mismatch leave a record of its potential impact?
    • When memory is empty, does the assistant avoid inventing a task?

    These tests show whether the memory framework closes the actual gaps, rather than merely adding a comprehensive-looking prompt.

    Define Boundaries Before Productization

    A one-off analysis may evolve into a recurring job-listing monitor or a similar inspection service. The same memory design can support that transition, but operational boundaries should be defined first.

    Process only public information permitted for the business use case. Control collection frequency to avoid putting pressure on target sites. Do not retain login credentials. Make collected fields, retention periods, and intended uses visible to users.

    The agent can handle orchestration, summarization, and explanations of anomalies. Collection policy, compliance review, and failure alerts should remain the responsibility of people or explicitly defined job systems.

    If the team already uses containers, message queues, logging, and monitoring, the memory service should focus on indexing and review. It should not create another unauditable shadow copy of system state.

    Object storage, logging, and monitoring in a general-purpose cloud environment can hold artifacts and runtime facts. The specific services should follow the existing architecture, not the memory framework’s marketing claims.

    Conclusion

    Overnight forgetting, denial of completed operations, and increasingly vague analysis during version drift are all symptoms of fragmented sources of truth.

    Separate episodic, semantic, and procedural memory. Write evidence-backed records at stage boundaries and after actions with side effects. Retrieve before answering, reconcile with current state, and validate the behavior with fixed regression tests.

    These practices turn claims of agent “self-improvement” into maintainable engineering capabilities. A memory add-on does not need to be complex, but it must let both people and systems answer three questions: What was the goal? How far did the work get? What evidence shows that it actually happened?