Agent Memory Design: Append-Only Logs and Checkpoint-Based Recovery

    Reliable agent memory does not come from the model alone. It comes from an append-only event log, checkpointing, and deterministic recovery. This article explains how to make agent execution auditable, preserve session state across process failures, minimize data loss, and rebuild the world state by replaying durable events.

    1. The Starting Point: An Agent Without Memory Is Amnesiac

    Consider a common scenario: an agent is working in a large codebase. It has modified three files and is halfway through a fourth when the host process exits unexpectedly. After restarting, does it know where it left off?

    The answer depends entirely on whether the runtime framework—the harness—provides a memory layer. Without one, failures typically appear in three forms:

    • Lost context: When the user asks, “Where did you leave off?” the agent cannot answer and must rescan the codebase from scratch.
    • Broken references: In a multi-turn conversation, the user may say, “Modify that function again.” Without prior state, the agent cannot determine which symbol or edit “that function” refers to.
    • No audit trail: If something goes wrong in production, there is no reliable record of which commands the agent ran, which files it inspected, or what it changed.

    All three failures share the same root cause: treating “memory” as an inherent model capability. In reality, a model’s context window is temporary and volatile. Cross-process and cross-turn continuity comes from an engineering layer in the runtime that persists the interaction as a replayable source of truth.

    2. The Nature of Memory: An Auditable Source of Truth

    Agent memory can be abstracted as:

    1. Memory = an append-only event log + recording + checkpointing + recovery

    The key design principle is this: the event log is the only source of truth, while the context shown to the model is merely a projection of that log.

    Model context may be truncated, summarized, or compressed, making it lossy. The event log on disk, by contrast, preserves the complete sequence of events without loss. Whenever the system needs to reconstruct the world state, it replays the log rather than relying on the model to “remember.”

    3. Storage Layout: From Workspace to Session Files

    This type of system typically stores session data outside the workspace, under a dedicated session root. A representative layout looks like this:

    1. sessions/
    2. └── --home-dev-projects-agent-workspace--/
    3. ├── session-001/
    4. │ └── session.jsonl.zstd
    5. └── session-002/
    6. └── session.jsonl.zstd

    Each level has a specific purpose:

    • sessions is the session root. It is decoupled from the code workspace so that memory files do not pollute the repository.
    • The middle directory is an escaped representation of the workspace’s absolute path. Path separators are replaced with visible markers, grouping all sessions for the same workspace while naturally isolating sessions from different workspaces. The directory name can also be decoded back to the original path.
    • The next level contains the session identifier. One task corresponds to one session directory.
    • The log itself uses a text format with one JSON object per line, known as JSONL, and is compressed losslessly as a whole. Compression is only an outer wrapper: after decompression, the data is plain text that can be inspected line by line with standard text tools. This is essential for auditability.

    4. The Session Header: An Immutable Identity Declaration

    The first line of the log is not an ordinary event. It is a session header containing metadata such as the session ID, creation time, workspace path, and delegation depth.

    Delegation depth indicates the session’s position in the agent hierarchy. The top-level session has a depth of 0, and child-agent sessions increment the depth as they are created.

    The central constraint on the session header is immutability. A session’s identity is fixed in the first line. After that, the system only appends events and never rewrites existing data.

    This allows recovery to determine three things immediately:

    1. Who the session is.
    2. Which workspace it belongs to.
    3. Where it sits in the delegation tree.

    With this information, the runtime can correctly reconstruct parent-child session relationships and permission boundaries.

    5. Recording: Three Dimensions of Append-Only Semantics

    “Append-only” is the core semantic property of the design, and it applies at three levels.

    First: Existing Lines Are Never Rewritten

    Events are appended with monotonically increasing sequence numbers. Once an event has been persisted, it is never modified or deleted.

    This is intentional rather than incidental. The log is the only source of truth, so allowing history to be rewritten would allow memory to be falsified and would immediately undermine its audit value.

    Second: Events Can Be Packed for Compression

    The number of physical lines in the log does not necessarily equal the number of logical events. When many events of the same type appear consecutively—for example, a model response streamed as dozens of small chunks—the backend can pack them into fewer physical lines.

    Logically, the events can still be expanded into the complete sequence in order. This reduces the number of lines and improves compression efficiency.

    Third: Sequential Appends Support Crash Recovery

    Appending only to the end of a file requires sequential I/O. It avoids in-place updates and random writes. Combined with sequence-number validation, this allows the recovery process to identify where valid data ends.

    Illustrative pseudocode:

    1. def append_event(session, event):
    2. event.seq = session.last_seq + 1 # Monotonically increasing sequence number
    3. line = json.dumps(event, ensure_ascii=False)
    4. session.writer.write(line + "\n") # Append only to the end
    5. session.last_seq = event.seq
    6. session.dirty += 1
    7. maybe_checkpoint(session) # Let the checkpoint policy decide when to flush

    6. Checkpoints: Minimizing the Window of Potential Data Loss

    Append-only storage ensures that data already written to disk will not be lost. However, data still held in a buffer can disappear if the process crashes. Checkpointing addresses this window by forcing buffered data to be written and persisted at important moments.

    Several policy dimensions can be combined:

    • Count threshold: Trigger a checkpoint after accumulating N dirty events.
    • Time threshold: Trigger one when more than T milliseconds have passed since the last flush, limiting the maximum loss window.
    • Critical event types: Force a flush before and after tool calls, at the end of a conversation turn, or when creating a child agent. These semantic boundaries are especially important because losing them makes recovery more difficult.
    • Shutdown or idle trigger: Always flush before the process becomes idle or exits.
    1. def maybe_checkpoint(session, policy):
    2. if session.dirty >= policy.max_events: return flush(session)
    3. if now() - session.last_flush >= policy.max_interval_ms: return flush(session)
    4. if session.pending.type in policy.critical_types: return flush(session)

    There is an important trade-off. More frequent persistence reduces data loss during a crash, but forced synchronous writes add latency directly to the tail latency of each interaction.

    Production systems therefore usually make these thresholds configurable and adjust them according to task value. Long-running unattended batch jobs may use conservative thresholds, while interactive sessions may use more aggressive ones.

    7. Recovery: Replaying the Log to Rebuild the World

    The recovery process can be divided into five steps:

    1. Read the session header and confirm the session identity and workspace.
    2. Scan the event stream sequentially and validate sequence-number continuity.
    3. Handle truncation: If the process crashed while writing the final line, that line may contain incomplete JSON. The recovery process treats the last complete, parseable record as the boundary and discards the incomplete tail. This is the standard and correct recovery behavior for an append-only log.
    4. Rebuild the conversation history, tool-call state, and inventory of side effects that have already occurred.
    5. Continue from the last complete turn. New events begin with the largest sequence number observed plus one, preserving idempotency.

    8. Engineering Considerations and Common Mistakes

    • Prioritize redaction: Secrets, tokens, and personal data must not enter the log. Apply filtering before writing, because logs often outlive the tasks that created them.
    • Retention and rotation: Define retention periods and capacity limits for sessions. Cold data can be archived to object storage, while hot data remains local for fast recovery.
    • Observability: Integrate logs with general-purpose logging and monitoring systems. Track persistence failures, the number of recovery truncations, and session duration as measurable operational metrics.
    • Mistake 1: Treating the event log as a database. It is optimized for sequential writes and full replay, not random queries. Complex search requirements should be supported by a separate index.
    • Mistake 2: Checkpointing too frequently. Excessive persistence can turn I/O fluctuations into visible interaction delays.
    • Mistake 3: Replaying the entire log into context. Long sessions can cause the model context to grow rapidly. The projection stage must introduce summarization and trimming.

    9. Summary

    Reliable agent memory does not come from the model itself. It comes from the disciplined combination of three straightforward mechanisms:

    • Append-only storage makes history tamper-resistant and auditable.
    • Checkpointing reduces the amount of data that can be lost during a crash.
    • Recovery provides idempotent replay and allows the system to rebuild state.

    Understanding this chain makes it possible to design an agent runtime with a memory layer that is space-efficient, recoverable, and accountable.