How AI Coding Agents Use Memory: Append-Only Logs, Checkpoints, and Recovery
This article breaks down the design principles behind memory in AI coding agents, using a practical formula: memory equals an append-only event log plus recording, checkpoints, and recovery. It explains why agents need persistent memory across crashes and restarts, how a single compressed JSONL file per session stores the full history, why append-only writes are a deliberate constraint, when checkpoints should force data to disk, and how recovery rebuilds context in three steps. It also covers consistency and concurrency pitfalls, observability, and governance practices, offering a reusable blueprint for any long-running, auditable, resumable automation system.
1. The Starting Problem: Why Agents Need Memory
When an AI coding agent modifies multiple files across a large codebase in one continuous run, process crashes, container restarts, and network interruptions are the norm rather than the exception. After a restart, one critical question appears: does it still remember where it left off?
Without a memory mechanism, the agent is effectively amnesiac. When a user asks “which step were we on,” it cannot answer. In a multi-turn conversation, when the user says “adjust that function we just touched,” it cannot resolve what “just now” refers to. When a production incident requires tracing “what operations did it actually perform,” there is no auditable record to fall back on.
Memory, then, is not a nice-to-have feature. It is the dividing line between a one-off question-answering tool and an execution partner that can collaborate over time. This article is built around one implementable design equation:
Memory = An append-only event log + Recording + Checkpoints + Recovery
The log is the single source of truth, while the three mechanisms handle writing, hardening, and rebuilding.
2. The Physical Form of Memory: One File per Session
In engineering practice, the most common misconception is that memory is something mysterious. In reality, mature implementations store memory as a concrete file: each session maps to a compressed event log file on disk. The file extension reflects the combination of JSONL and compression; once decompressed, it is plain text with one JSON event per line.
The directory layout typically carries three layers of information:
- Session root directory: a single entry point for all sessions, making centralized backup and migration straightforward.
- Escaped workspace directory: separators in the absolute workspace path are escaped into safe characters, forming a reversible directory name so that sessions from different projects on the same machine do not interfere with each other.
- Session identifier directory: named after the session id, holding the log itself.
The benefits of this design are direct: fast lookup, easy copying, and auditability. Hand an operator a single file, and they have the entire history of that session. To reproduce an issue, they only need to take the file with them.
The first line of the log is usually a session header, recording metadata such as the session id, creation time, workspace path, and delegation depth. Delegation depth distinguishes top-level sessions from sub-agent sessions: the top level is 0, and it increments each time a child session is derived, which supports tree-structured task decomposition and permission isolation. The key constraint on the session header is immutability: identity is fixed on the first line, and only appends are allowed afterward, never rewrites.
3. Recording: Why an Append-Only Event Stream Is a Deliberate Choice
“Append-only” is the most fundamental semantic of the whole mechanism, and it shows up on three levels:
- Written lines are never rewritten. Events are appended continuously with monotonically increasing sequence numbers, and no historical event is ever modified or deleted. This is not implementation laziness but a deliberate constraint: the log is the only source of truth, and rewriting history amounts to fabricating memory.
- Compression saves space. Text logs are highly repetitive; a general-purpose compression algorithm reduces size significantly while preserving random decompression and streaming reads.
- Order is causality. Event order naturally expresses what happened first and what happened later, with no need to maintain a separate, complex timeline index.
A typical event stream looks like this (fields are illustrative, not a specific product interface):
{"seq":1,"type":"session_header","sessionId":"demo-002","workspace":"/workspace/demo","delegationDepth":0}{"seq":2,"type":"user_message","text":"Fix the login timeout issue"}{"seq":3,"type":"tool_call","name":"read_file","args":{"path":"src/auth.ts"}}{"seq":4,"type":"tool_result","ok":true,"summary":"read 120 lines"}{"seq":5,"type":"assistant_message","text":"Located the retry logic missing backoff"}{"seq":6,"type":"checkpoint","reason":"before_edit"}{"seq":7,"type":"tool_call","name":"apply_patch","args":{"file":"src/auth.ts"}}
User input, tool calls, tool results, assistant conclusions, and checkpoints are all modeled uniformly as events rather than scattered across different structures. Uniform modeling brings a hidden benefit: replay logic needs only a single loop, with no separate recovery code for each message type.
4. Checkpoints: Shrinking the Window of Potential Loss
An append-only log solves “what was written will not be lost,” but it cannot solve “what has not been written yet may be lost.” A process crash often happens after an event is generated but before it is flushed to disk, and that window is the high-incidence zone for data loss.
The job of a checkpoint strategy is to force buffered data to persistent storage at key moments and leave behind an identifiable marker event. Common trigger points include:
- Before modifying a file or performing an operation with side effects;
- Before a task round ends and control is handed back;
- Before deriving or reclaiming a child session;
- As a fallback when a fixed number of events or a fixed time interval is reached.
In engineering, “batch writes for throughput” and “forced flush for reliability” are usually made into two configurable modes: normally, events are batched to reduce I/O operations; at key moments, the system switches to a forced flush. This avoids the performance cost of synchronous disk writes for every event while keeping the range that a crash can lose to a small, acceptable segment.
It is worth stressing that a checkpoint is not “backing up the entire workspace” but “confirming the log has been persisted.” Workspace files themselves should still be protected by general means such as version control or object storage. The two have different responsibilities and do not replace each other.
5. Recovery: A Three-Step Method for Rebuilding Context from the Log
Recovery can be abstracted into three steps:
- Load and validate: read the log, parse JSON line by line, and verify sequence continuity. If the last line is truncated by a crash, discard the incomplete tail record instead of making the whole session unusable.
- Rebuild the conversation history: replay user messages, assistant messages, tool calls, and results in event order to restore the context sequence the model saw.
- Resume the unfinished round: based on the last checkpoint and unfinished events, decide whether to continue execution or roll back to the checkpoint and replan.
Illustrative pseudocode:
def restore(path):events = []for line in decompress(path).splitlines():try:events.append(json.loads(line))except ValueError:break # Tolerate tail truncation caused by a crashhistory = [e for e in events if e["type"] in ("user_message","assistant_message","tool_result")]last_cp = max((e["seq"] for e in events if e["type"] == "checkpoint"), default=0)return history, last_cp
The key design tradeoff here is tolerating tail corruption. The value of the log lies in 99% of the history being trustworthy; refusing to start because the last line is incomplete would reduce reliability instead.
6. Consistency and Concurrency: Two Easily Overlooked Pitfalls
First, the workspace and the log may be inconsistent. The log says a file was modified, but a crash may have left the write half-completed. The mitigation is to bind side-effect operations to checkpoints: write the intent to the log first, write a result event after execution completes, and treat the result event as authoritative during recovery. A missing result is treated as not applied and rolled back.
Second, multiple sessions concurrently writing the same file breaks append-only semantics. The common approach is one file per session, which naturally avoids write conflicts. If sharing is unavoidable, introduce a file lock or shard by session rather than allowing multiple writers to interleave appends.
7. Observability and Governance
Since the log is readable text, it doubles as the best audit material. Recommended practices:
- Redact sensitive fields to avoid writing credentials into logs;
- Set retention periods for session directories, archiving expired ones to object storage or a logging service;
- Use monitoring and alerting to track session count, log size, and checkpoint duration to catch abnormal growth;
- Keep the workspace path in the session header to enable cost and security audits by project.
8. Conclusion
An agent’s memory does not need to be mystical. Define memory as an append-only event log, then use recording to guarantee “what was written is trustworthy,” checkpoints to guarantee “what matters is persisted,” and recovery to guarantee “a restart can resume.” Together these form a logically closed, verifiable, and operable design. For developers, the same approach applies to any automation system that needs long-running flows, traceability, and recoverability, whether a CI/CD pipeline, a data pipeline, or long-running business transaction orchestration. The essential problem is always the same: how to let a system still know who it is, what it has done, and what to do next after an interruption.
