Agent Session Memory: Logs, Checkpoints, and Recovery

    AI coding agents often work across many conversations, tool calls, and file changes. When a process crashes, a machine restarts, or the context window is truncated, an agent without memory independent of the model context becomes disoriented: it cannot tell where a previous edit stopped, which edit “from earlier” refers to, or what it actually did. This article explains a session-memory design built around an append-only event log plus recording, checkpointing, and recovery mechanisms. It covers on-disk session layout, immutable session headers, append-only event semantics, checkpoint barriers, idempotent replay, workspace verification, capacity and privacy controls, auditability, and the division of labor between the log and the context window. The goal is not to put more text into prompts, but to make what happened remain true outside the process.

    AI coding agents modifying large codebases often have to span multiple rounds of conversation, multiple tool calls, and multiple file changes. After a process crash, machine reboot, or context-window truncation, an agent without memory independent of the model context will lose its bearings. If the user asks, “Where did we stop?” the agent cannot locate the answer. If the user says, “Modify that function from earlier again,” the agent does not know which edit “earlier” refers to. If someone later investigates, “What exactly did it do?” there is no record to check. Session memory is not about inserting more text into the prompt. It is about making events that happened remain valid outside the process.

    1. Memory Is a Replayable Source of Truth, Not a Black Box

    Agent memory can be described as an equation: memory equals an append-only event stream plus three mechanisms—recording, checkpointing, and recovery. Model weights and the current context window are not the source of truth. Weights do not remember the intermediate state of a particular task. The window can be summarized, truncated, or replaced. The only reliable approach is to write every meaningful state change as an event, persist events in order, and reconstruct the conversation and workspace understanding from those events when needed.

    One task corresponds to one session. On disk, a session appears as a log file under a directory: the session root, a partition derived from a normalized workspace path, a session identifier, and the log itself. The log uses one event per line in a text format and applies streaming compression so that append writes remain bounded in size. Each decompressed line is a self-describing event, not an opaque long block that is difficult to split.

    The first line of a session should be an immutable session header containing at least metadata such as the session ID, creation time, workspace path, and delegation depth. A top-level session has delegation depth 0, and subtask sessions increment it. Once identity is fixed in the first line, later records are append-only and the session header is never rewritten. This prevents the same log from becoming a different session halfway through.

    2. Recording: Why Append-Only Is a Semantics Requirement, Not an Implementation Detail

    Append-only has three layers of meaning.

    First, written lines are never modified or deleted. Events carry contiguous sequence numbers. Any “correction” is done by appending a new event, such as a compensation, undo, or correction note, rather than overwriting the old line. The log is the source of truth. Rewriting history is falsifying memory, and it also breaks sequence-number-based incremental reads and integrity checks.

    Second, events should be small and complete. One event describes one observable action: user input, model response, tool-call start, tool result, file-change summary, error, checkpoint marker, and so on. Fields should remain stable. Avoid indiscriminately embedding entire file contents in every line. Large objects can be externalized as content-addressed attachments, with only a digest, hash, and reference kept in the log. This allows replay to reconstruct decisions without letting the hot-path log grow without bound.

    Third, writes must end recoverably. An append means either the full line is visible or the line is absent. In implementation, first write to a temporary buffer, then append and flush to the log, and call the filesystem persistence interface when needed to avoid leaving half a JSON line after a power loss. Compression can be performed in blocks: unsealed blocks remain in memory or in a side file, and once sealed they are merged into the main log. This ensures that after a crash, the last complete block can still be read.

    The illustrative structure below shows only field relationships, not an interface from any specific product:

    1. Session header: sessionId, createdAt, workspace, delegationDepth
    2. Event: seq, ts, type, payload, parentSeq (optional)
    3. Constraints: seq starts at 1 and increases contiguously; type belongs to an agreed set; payload can be independently validated

    3. Checkpoints: Turning “It Happened” into “It Is Persisted” at Key Moments

    Append-only solves the problem of not changing history. Checkpoints solve the problem of whether the final steps before a crash actually reached disk. When an agent has finished editing multiple files, is waiting for an external tool, or is about to return control to the user, it should trigger a checkpoint: force unwritten events to be flushed, write a checkpoint event, and record the sequence number at that point, a to-do summary, and a hash of the workspace change list. A checkpoint is not a separate snapshot database that can diverge from the log. It is a synchronization barrier on the log. Optionally, a workspace file-tree manifest or incremental package can be generated at the checkpoint so that recovery can check whether “the log says it changed” and “it actually exists on disk” agree.

    A policy should not force flush on every event, because throughput would then be dominated by storage latency. It should not flush only when the process exits normally either, because the crash window would be too large. A practical compromise is to force checkpoints at user-visible turn boundaries, after a batch of related file edits completes, and at the start and end of delegated subtasks. Ordinary reasoning-token streams can be flushed loosely by count or by time. Checkpoint events themselves are append-only, so the log can answer: “The last confirmed persistence was at sequence number N.”

    4. Recovery: Replay the Log Instead of Guessing at Context

    Recovery has three steps. First, open the log, skip a corrupt partial line at the tail, read to the last complete event, and validate that sequence numbers are contiguous and the session header has not been replaced. Second, replay by type: reconstruct conversation turns, the correspondence between tool calls and results, unfinished to-dos, and increments after the most recent checkpoint. Third, hand the reconstructed state back to the agent loop and continue from the interrupted turn, rather than starting a blank session and asking the model to “remember.”

    Replay must account for idempotency. A file-edit event may already have been applied to the workspace before a crash, and recovery must not blindly execute it again. A safer approach is to record both the intent and the result hash in the log. During recovery, compare the workspace first. If it matches, skip the operation. If it does not match, mark a conflict and hand it to the user or a compensation process rather than silently overwriting. Child sessions attach to the parent log through delegation depth and parent sequence numbers. When the parent session recovers, it can see whether a child task has finished and avoid duplicate delegation.

    5. Capacity, Privacy, and Audit

    Long-running sessions will grow. Compression, externalized attachments, and discardable cold segments generated at checkpoints are all capacity-control measures. Cold segments can be archived to object storage, while the hot segment keeps only events after the most recent checkpoint plus a checkpoint index. Archiving is not the same as deleting or rewriting history: the index can still locate old events by sequence number.

    Logs may contain paths, code snippets, and secret-like strings. Sanitization should happen before writing: environment variables, tokens, and private keys should not enter the log. Record only the type of credential used and whether it succeeded. By default, the session directory should be readable only by the task’s runtime identity. For auditing, replaying by sequence number can answer “what was done” without depending on the model’s after-the-fact self-report.

    6. Division of Labor with the Context Window

    The window is responsible for the short context needed for current reasoning. The log is responsible for long-lived facts across crashes, across days, and across window truncation. Summaries can be written to the log as derived events, but they cannot replace the original events. When history does not fit in the window, load a structured summary from the most recent checkpoint and retain the ability to read the original text by sequence number. This way, the agent can continue the conversation and, when a dispute arises, return to the tool result from that moment instead of relying on a compressed memory that may hallucinate.

    During implementation, it is advisable to first fix event types and sequence-number rules, then implement flush barriers and tail fault tolerance, and finally add workspace hash verification. If this order is reversed, it is easy to end up with a “memory” that looks complete but does not match the disk during recovery.