AI Agent Memory Engineering: Append-Only Logs, Checkpoints, and Recovery

    This article explains why AI agent memory must be engineered as explicit on-disk data structures rather than implicit model context. It walks through a real session directory layout, then breaks down the three core mechanisms—an append-only event log as the source of truth, checkpoints that shrink the window of potentially lost data, and replay-based recovery—along with a step-by-step crash scenario and practical implementation guidance. Readers will learn how this design delivers auditability, reproducibility, lower storage cost, and workspace isolation.

    1. Starting Point: Why Agent Memory Must Be Engineered

    When an AI coding tool modifies multiple files in a large codebase in one continuous run, a process crash is an almost inevitable low-probability event. What really determines the user experience is not whether it crashes, but what the system still has after it does.

    Without persistent memory, an agent is effectively amnesiac after a crash: if the user asks “where did you get to?”, it cannot answer; in a multi-turn conversation, when the user says “adjust that function again,” it cannot resolve what “that” refers to; and when investigating afterward what it actually did, there is no factual source to rely on.

    The more mature approach in the industry is therefore to move memory down from an implicit state inside the model context to an explicit data structure on disk. It can be summarized as one equation:

    1. Memory = an append-only ledger + records + checkpoints + recovery

    The ledger is the source of truth, while the other three mechanisms handle writing, hardening, and rebuilding. Each layer is unpacked below.

    2. Look at the Artifact: What a Task Leaves on Disk

    After running two real tasks locally (session IDs demo-001 and demo-002), a separate session directory is created outside the workspace, structured as follows:

    1. sessions/
    2. --Users-Apple-projects-deepseek_harness-workspace--/
    3. demo-001/
    4. session.jsonl.zstd
    5. demo-002/
    6. session.jsonl.zstd

    The path carries four layers of meaning:

    1. sessions: the session root directory, physically separated from the code workspace so it is not polluted by version control, cleanup scripts, or build artifacts.
    2. The middle directory name: an escaped form of the workspace’s absolute path. --Users-Apple-...-- corresponds to /Users/Apple/projects/deepseek_harness/workspace. The benefit is that the same workspace shares memory, while different workspaces never bleed into each other.
    3. demo-002: the session ID, one directory per task, naturally isolated.
    4. session.jsonl.zstd: the log itself. JSONL format, compressed with zstd; once decompressed it is plain text with one JSON event per line.

    Decompressing the demo-002 log yields 62 lines, meaning 62 events. The first line is the session header; the rest is the event stream. The header records metadata such as the session ID, creation time, workspace path, and delegationDepth (delegation depth, 0 for a top-level session and incrementing level by level for sub-agent sessions).

    One key constraint applies here: the session header is immutable. A session’s identity is fixed in the first line, and only appending events is allowed afterward—never writing back to modify it. An immutable identity is the prerequisite for all the “auditable and reproducible” capabilities that follow.

    3. Records: Why an Append-Only Event Stream Is a Deliberate Design

    “Append-only” is the most core semantic of this log, and it shows up on three levels.

    First, written lines are never rewritten. Events are appended continuously by seq number, and no event already on disk is ever modified or deleted. This is not an implementation detail but a design tradeoff: the log is the single source of truth, and rewriting history is equivalent to fabricating memory, which would render auditing and replay meaningless.

    Second, packing and compression save space. Lines and events are not strictly one-to-one: when a large number of consecutive events of the same type appear (for example, model output split into dozens of small chunks), the backend packs them into a single stored line (think of it as a packChunks strategy). In local testing, this strategy shrank the log size by roughly 60% while keeping the order and semantics of events unchanged after decompression.

    Third, the write path stays as simple as possible. Append-only means disk operations can degrade to sequential writes, avoiding the complex consistency handling that random writes and in-place updates bring; in a crash, the worst case is just that “the last event is incomplete,” without corrupting existing history.

    Illustrative write logic:

    1. def append_event(session_dir, event):
    2. event["seq"] = next_seq(session_dir) # monotonically increasing
    3. line = json.dumps(event, ensure_ascii=False) + "\n"
    4. with open(session_dir / "session.jsonl.zstd", "ab") as f:
    5. f.write(compress(line)) # sequential append, no write-back

    4. Checkpoints: Shrinking the Window of Potentially Lost Data

    Append-only solves “history is not tampered with,” but it does not solve “whether data has actually reached disk.” The operating system page cache, compression buffers, and runtime queues can all leave the most recent events sitting in memory. The role of a checkpoint is to force a flush to disk at key moments, compressing the window that a crash could lose to a minimum.

    Common checkpoint trigger points in engineering include:

    • Immediately after the session header is written, ensuring the session identity lands first;
    • After a round of user input has been fully received;
    • After a tool call (such as a file edit or command execution) returns;
    • Before and after delegating to a sub-agent, preventing parent and child session state from drifting out of sync;
    • When the session ends or a termination signal is received.

    It is worth stressing that a checkpoint is not a crude “flush everything every time” approach, but works together with the packing strategy: first accumulate consecutive small events into blocks, then force a flush at semantic boundaries, balancing throughput and reliability.

    5. Recovery: Rebuilding the World from the Log

    Recovery has a single goal: replay the event stream on disk into in-memory session state, and allow the next round to continue. The typical flow has four steps.

    1. Locate and decompress: find the log by the escaped workspace directory and session ID, and decompress it into text lines.
    2. Validate the session header: confirm the session ID, workspace path, and delegationDepth match the current runtime environment, avoiding accidental recovery across workspaces.
    3. Replay in order: apply events one by one by seq, rebuilding conversation history, tool call records, and the index of intermediate artifacts; when a packed line is encountered, unpack it before applying.
    4. Decide the resume point: if the last event is incomplete or lacks a termination marker, roll back to the most recent complete semantic boundary and restart from that round.

    Illustrative recovery logic:

    1. def restore(session_dir):
    2. header, events = load_and_decompress(session_dir)
    3. assert header["workspace"] == current_workspace()
    4. state = init_state(header)
    5. for ev in sorted(events, key=lambda e: e["seq"]):
    6. if not ev.get("complete", True):
    7. break # roll back to the last complete boundary
    8. state = apply(state, ev)
    9. return state

    6. Putting the Three Together: The Full Script of a Crash

    Suppose the agent has modified two of three files, and the process crashes halfway through writing the third:

    • Before the crash: completed edit events were flushed at a checkpoint, while the half-finished event for the third file may still be in the buffer.
    • After the crash: the log retains one incomplete event, and history is 100% queryable.
    • On recovery: replay up to the most recent complete boundary, report to the user that “two files are done and the third is not,” and continue from that round.
    • When investigating: simply decompress the log and read it by seq to reconstruct every decision and tool call, with no guessing required.

    7. Engineering Benefits and Implementation Advice

    1. Auditable: the log is the fact, and changing history equals fabricating memory, so auditing only requires reading the log.
    2. Reproducible: given the same log, the replay result is deterministic, making defect reproduction and regression easy.
    3. Space-efficient: packing and compression keep the cost of retaining multiple session logs over the long term under control, with roughly 60% size savings measured locally.
    4. Easy to isolate: layering by escaped workspace directory plus session ID naturally supports multiple projects running in parallel.
    5. Implementation checklist: first define the immutable session header, then implement sequential appending and seq, then add checkpoints at semantic boundaries, and finally implement replay-based recovery with rollback for incomplete events; if you need to move to the cloud, you can archive logs to object storage, use a log service for retrieval, and use monitoring and alerting to track crash and recovery counts—these are all general capability categories and do not involve proprietary interfaces.