Agent Memory Design Principles: Append-Only Logs, Checkpoints, and Recovery
This article explains how memory works in AI agents and coding assistants from an engineering perspective. It breaks memory down into an append-only event log, records, checkpoints, and recovery, then walks through how a session maps to a single log file, why append-only semantics matter, when to force a checkpoint, and how to rebuild context after a crash. It closes with observability and governance practices for long-running agent tasks.
1. Why Agents Need Memory
When you look at the engineering side of AI coding tools and automation agents, memory is one of the most underestimated capabilities. Many people treat memory as “a stretch of conversation inside the model’s context window,” but from an engineering standpoint that is only a small part of runtime. What really determines whether an agent can take on long tasks is whether it still knows what it has done, what it is doing, and what to do next after a process restart, a broken session, or hours of continuous running.
Picture a typical scenario: an agent is running a refactoring task in a large codebase. It has already modified three files, and the refactor of one of them is unfinished. The process then exits unexpectedly. After a restart, the user asks “where did we get to?” With no persistence mechanism at all, the agent can only answer “I don’t know.” Worse, in a multi-turn conversation the user says “adjust that function from earlier,” and the agent cannot resolve what “earlier” refers to. When something goes wrong, the team also has no way to review which actions the agent actually performed.
A fairly mature approach in the industry is to express memory as an equation:
memory = append-only event ledger + records + checkpoints + recovery
The event ledger is the single source of truth; records write every action, output, and state change to the log; checkpoints force data to disk at key moments to reduce data loss on a crash; and recovery re-reads the log, rebuilds context, and continues unfinished work. The rest of this article focuses on these three mechanisms.
2. Storage Layout: One Session, One Log File
In most auditable agent implementations, a session usually maps to a standalone file outside the workspace, with a clearly structured path:
sessions/<escaped-workspace-path>/<session-id>/session.jsonl.zstd
Each segment means the following:
sessions: the session root directory, kept separate from the workspace code to avoid polluting the business repository;- escaped workspace path: path separators in the absolute path are replaced with safe characters so sessions from different workspaces do not collide;
- session ID: a unique identifier for one task, such as a demo run or a real refactoring task;
session.jsonl.zstd: the log itself, in JSONL format and compressed with a general-purpose compression algorithm.
Once decompressed, the file is plain text with one JSON event per line. Take a session containing 62 events: the first line is the “session header,” and the remaining lines are the event stream. The header records metadata such as session ID, creation time, workspace path, and delegation depth. Delegation depth starts at 0 for a top-level session and increments level by level when the main agent spawns sub-agents, which distinguishes the main task from subtasks. Once written, the header is immutable, so a session’s identity is fixed from the very first line.
This design brings three direct benefits: first, sessions are decoupled from the code repository, which makes unified backup and migration easier; second, layering by workspace and session ID keeps lookup costs low; third, the file is the fact, so any audit or replay only needs to read this one file.
3. Records: Why the Append-Only Event Stream Is the Core Semantic
“Append-only” is the most critical constraint in the whole mechanism, and it shows up on at least three levels.
First, lines that have been written are never rewritten. Events are appended continuously with monotonically increasing sequence numbers, and no historical event is ever modified or deleted. This is not laziness in the implementation but a deliberate architectural choice: the log is the single source of truth, and modifying history is equivalent to forging memory, which would destroy the credibility of auditing, replay, and recovery alike.
Second, packing and compression reduce space usage. Log lines do not necessarily map one-to-one to events. When many small events of the same type appear consecutively (for example, model output split into dozens of fragments), the backend packs them into a single line and then compresses them together. This preserves event order while significantly reducing file size and the number of writes.
Third, event types are layered and the semantics stay clear. Common events typically include the session header, user input, model output fragments, tool call requests, tool execution results, state changes, and checkpoint markers. Each type of event expresses only one fact, and recovery handles each type separately, avoiding mixing “intent” with “result.”
An illustrative event structure looks like this:
{"seq":1,"type":"session_header","sessionId":"demo-002","createdAt":"...","workspace":"/.../workspace","delegationDepth":0}{"seq":2,"type":"user_message","text":"Please refactor the example module"}{"seq":3,"type":"assistant_delta","text":"I will read first"}{"seq":4,"type":"tool_call","name":"read_file","args":{"path":"a.ts"}}{"seq":5,"type":"tool_result","ok":true,"summary":"..."}{"seq":62,"type":"checkpoint","reason":"before_edit"}
4. Checkpoints: Forcing a Complete Write at Key Moments
The append-only log answers “what to write,” while checkpoints answer “when a write must be complete.” The essence of losing data in a crash is that the buffer still holds events that have not reached disk. A checkpoint forces a flush before and after key actions, advancing the log to a recoverable boundary.
Common checkpoint moments include: before starting to modify a file, before performing an irreversible operation, at the end of a conversation turn, before and after delegating a subtask, and after an external tool returns an important result. A checkpoint can itself be written into the log as an event with a reason field, which makes it easier to judge context completeness during recovery.
Two engineering points deserve attention: first, more frequent checkpoints are not always better, since excessive flushing amplifies write overhead; second, checkpoints should be bound to business semantics rather than fixed time intervals, because what really needs to be guaranteed is completeness at semantic boundaries.
5. Recovery: Rebuilding Context from the Log and Continuing the Task
The goal of recovery is not to “read the text back” but to rebuild a state that can continue executing. A robust recovery flow usually has four steps:
- Read the session header and verify that the session identity matches the workspace;
- Scan the event stream in order, rebuilding the message sequence and the pairing between tool calls and results by sequence number;
- Handle unclosed tool calls: if a request exists with no result, mark it as interrupted and decide whether to retry or skip;
- Locate the last checkpoint, restore context, and continue with the next turn.
Illustrative pseudocode:
events = load_jsonl_zstd(path)header = events[0]history, pending = [], Nonefor e in events[1:]:if e.type == "tool_call": pending = eelif e.type == "tool_result": history.append(pair(pending, e)); pending = Noneelif e.type == "assistant_delta": history.append(e)elif e.type == "checkpoint": last_ckpt = e.seqresume_from(history, last_ckpt)
The key design here is “paired recovery”: a tool call and its result must appear as a pair, otherwise the point is treated as an interruption. This both avoids hallucinated completion and provides a basis for idempotent retries.
6. Observability and Governance Recommendations
Once the log becomes the source of truth, observability naturally builds on top of it: the distribution of event types can gauge the proportion of tool calls; checkpoint density can measure crash risk; and session file size and compression ratio can reflect context growth. Combined with general-purpose logging services and monitoring and alerting capabilities, this can be extended into a session-level health dashboard.
Three governance recommendations: first, set a per-session event limit and an archiving policy to keep logs from growing without bound; second, redact sensitive fields before writing them; third, make recovery drills part of the daily workflow, periodically using historical logs to verify whether a session can be fully rebuilt and continued.
7. Conclusion
Agent memory is not mysterious. It is essentially an auditable append-only log plus three mechanisms: records, checkpoints, and recovery. Once you understand this structure, whether you are designing an AI coding tool or investigating why a long task failed, you can start from the files, the events, and the checkpoints, forming a reproducible and verifiable engineering loop.
