Persistent Memory Design for AI Coding Agents: Append-Only Logs, Checkpoints, and Recovery
This article explains how persistent memory in AI coding agents is built from an append-only event log plus three mechanisms: recording, checkpointing, and recovery. It walks through the layout of a real session file, why written lines are never rewritten, how events are batched and compressed, when checkpoints are triggered, and how a session is rebuilt by replaying the log after a crash. The closing sections cover the practical benefits—resuming interrupted tasks, resolving multi-turn references, full auditability, and portable memory—along with four implementation ground rules for designing your own session memory.
1. Why an Agent Needs Memory
Picture an ordinary scenario: a coding agent is refactoring a sizable codebase. It has already modified three files and is halfway through reading the fourth when the host process exits unexpectedly. After a restart, does it know where it left off?
The answer depends entirely on whether the runtime harness has persistent memory. Without it, the agent is amnesiac at the end of every turn: when the user asks “where did you get to?”, it has nothing to answer with; in a multi-turn conversation, “adjust that function again” cannot be resolved because “that” points to no retrievable history; and when anomalous behavior in production needs a postmortem of “what exactly did it do”, there is no evidence to produce.
A fairly mature industry practice is to reduce memory to a single equation:
memory = an append-only ledger + three mechanisms: record / checkpoint / recover
The value of this equation is that it demystifies memory. Memory is not a black box inside the model, nor some mysterious “stream of consciousness”. It is an ordinary file that can be opened, verified, and moved. Anything that can be turned into a file can be backed up, audited, migrated, and replayed—exactly the properties engineering wants.
2. Start With the Artifact: Memory Files Left by a Task
After running two real tasks locally, a set of files appears outside the workspace:
sessions/--Users-Apple-projects-deepseek_harness-workspace--/demo-002/session.jsonl.zstd
Breaking the path down segment by segment:
sessions: the session root directory, stored separately from the code workspace to avoid polluting the repository;- the middle segment: an escaped form of the workspace’s absolute path, with separators such as
/replaced by safe characters and wrapped in leading and trailing markers, so sessions from different workspaces never cross over; demo-002: the session identifier, one directory per task;session.jsonl.zstd: the log itself, in JSONL format and compressed with zstd. Once decompressed it is plain text, one JSON event per line.
For one sample task, decompression yields 62 lines, meaning 62 events. The first line is the session header, followed by the event stream. The header is the most special line: it fixes metadata such as the session identifier, creation time, workspace path, and delegation depth (0 for a top-level session, incrementing level by level for sub-agent sessions), and it is immutable—a session’s identity is set in the first line, and from then on only appends are allowed, never rewrites.
Writing the workspace path into the session header has a benefit that is easy to overlook: a session can be relocated as a whole. Switch machines, change directories, move into a container—as long as the path mapping is derivable, the history is still attributed correctly.
3. Recording: The Append-Only Event Stream
“Append-only” is the core semantic of this log, and it shows up on three levels.
First, written lines are never rewritten. Events are appended continuously with monotonically increasing sequence numbers, and no event already persisted is ever modified or deleted. This is not an accidental implementation detail but a deliberate design: the log is the single source of truth, and modifying history amounts to forging memory, which destroys the credibility of all downstream reasoning.
Second, packing and compression save space. Lines and events are not strictly one-to-one: when many events of the same type appear consecutively (typically when model output is split into dozens of small chunks), the backend packs them into a single line and then compresses with zstd. This yields two benefits: disk usage drops significantly, and scattered small random writes are merged into sequential large writes, reducing filesystem pressure.
Third, the semantic layering is clear. Event types generally fall into a few categories: session header, user input, model output chunks, tool call requests, tool results, and heartbeat or checkpoint markers produced by the policy layer. The point of layering is that recovery does not require understanding every detail—dispatching by type is enough.
An illustrative log shape (fields are generic examples, not a specific product interface):
{"t":"header","sessionId":"demo-002","createdAt":"...","workspace":"/Users/Apple/projects/...","delegationDepth":0}{"seq":1,"t":"user","text":"Extract the auth middleware into a standalone module"}{"seq":2,"t":"model.delta","chunk":"Let me look at the directory structure first"}{"seq":3,"t":"tool.call","name":"read_file","args":{"path":"src/middleware/auth.ts"}}{"seq":4,"t":"tool.result","ok":true,"summary":"..."}{"seq":5,"t":"checkpoint","reason":"before_write"}
4. Checkpoints: Persisting Data That Could Otherwise Be Lost
Append-only solves “no tampering” but not “no time to write”. Crashes tend to happen between two writes, so a forced sync is needed at key moments. Common checkpoint triggers include:
- before side-effecting actions such as writing files or executing commands;
- before a conversation turn ends and the next one begins;
- around sub-agent delegation, to prevent parent and child contexts from drifting apart;
- periodic syncs when a time or event-count threshold is reached.
Checkpoint policy is essentially a tradeoff between reliability and performance. Syncing too often slows interaction; syncing too sparsely loses more progress on a crash. In engineering, a layered strategy is common: always sync on critical actions, batch-sync ordinary output—and the policy itself is made a replaceable component so it can be tuned per task type.
Simplified policy pseudocode:
def should_checkpoint(event, state):if event.type in ("tool.call", "delegate.start", "turn.end"):return Truereturn state.since_last_sync_ms > 2000 or state.pending_events > 50
5. Recovery: Rebuilding the World From the Log
Recovery can be summarized in four steps:
- Read and decompress the log, parsing events line by line;
- Validate the session header, confirming the workspace and delegation depth match;
- Replay events in order to rebuild the conversation history, the tool call trace, and an index of intermediate artifacts;
- Continue from after the last checkpoint, resuming the unfinished turn.
Replay works because events carry deterministic semantics: the same tool results are recorded in full and model output is preserved completely, so the reconstructed context matches the state before the crash. If the tail of the log contains a half-written partial line, discard that line and resume from the previous checkpoint rather than trying to repair it—consistent with the principle of not modifying history.
6. Four Capabilities This Design Delivers
- Resume from breakpoints: long tasks no longer restart from scratch because of a process failure;
- Resolvable multi-turn references: “that function” can be mapped to a specific history fragment;
- Full auditability: every action leaves a trace, making quality retrospectives and compliance checks easy;
- Portable memory: the log is plain text, so moving it across environments and archiving it long term is cheap.
For team-level sharing or long-term retention, logs can be archived to object storage, searched with a log service, and paired with monitoring and alerting that sets thresholds on the checkpoint failure rate—all generic cloud capability categories, with no dependency on any proprietary interface.
7. Implementation Recommendations
When designing your own session memory, hold four ground rules: the log is append-only, the session header is immutable, checkpoints cover every side-effecting action, and recovery is based on replay rather than repair. Also add sequence continuity and digest verification to the log so a corrupted spot can be located quickly. With those four points in place, an agent’s memory goes from “impossible to explain” to “queryable”, and the gain in engineering reliability is immediate.
