Engineering Agent Memory: Design Principles for Append-Only Logs, Checkpoints, and Recovery
This article breaks down the engineering design of agent memory, explaining why memory should be modeled as an externally verifiable source of truth rather than an implicit model state. It covers a practical memory equation (append-only event stream + records + checkpoints + recovery), a materialized layout where each session maps to a single compressed JSONL log file, the three layers of append-only semantics, checkpoint strategies that minimize the crash window, and a four-step recovery flow with continuity and idempotency checks. A final engineering checklist summarizes the practices that make interruptions predictable, recoverable, and auditable.
1. The Starting Problem: Why Agents Need Memory
When an agent modifies multiple files in a large codebase in one continuous run, the most fragile link is not reasoning ability but the recoverability of state. A terminated process, a reclaimed container, or a restarted host can all interrupt the run, and any one of them can turn “which step did I reach?” into an unknown. If the runtime harness has no persistence design, the agent is amnesiac after a restart: it cannot answer when the user asks about progress; in a multi-turn conversation it cannot resolve a reference like “change that function again”; and after the fact there is no basis for investigating “what exactly did it do.”
Memory, therefore, should not be understood as an implicit state inside the model. It should be modeled as an externally verifiable source of truth. A practical equation is:
memory = append-only event stream + records + checkpoints + recovery
Records are responsible for writing every decision, tool call, and output in order; checkpoints force a flush at key moments to shrink the crash window; recovery replays the log, rebuilds context, and continues unfinished turns. Missing any one of the three degrades memory into a “best-effort” log rather than a trustworthy state.
2. Materialized Form: One Session, One Log File
The most straightforward engineering approach is to map each session to an independent file on disk, with the naming and directory structure carrying metadata:
sessions/--Users-Apple-projects-deepseek_harness-workspace--/demo-002/session.jsonl.zstd
sessions: the session root directory, convenient for unified quotas, cleanup, and migration;- the middle segment: a directory name derived from the escaped absolute workspace path, so sessions for different projects on the same machine are naturally isolated;
demo-002: the session identifier, one directory per task;session.jsonl.zstd: the log body, JSONL semantics with zstd compression.
The core reasons for choosing JSONL over a structured database are being “append-friendly” and “readable and auditable”: once decompressed it is plain text with one JSON event per line, so manual troubleshooting and offline analysis need no extra toolchain. zstd is chosen because the event stream is write-heavy and read-light with highly repetitive structures, giving a good balance between compression ratio and decompression speed.
The first line of the log is the session header, recording the session identifier, creation time, workspace path, delegation depth (0 for a top-level session, incrementing for sessions derived by sub-agents), and so on. The session header is immutable—identity is fixed on the first line, and only appends are allowed afterward, never rewrites. This constraint is a prerequisite for recovery correctness: if identity were mutable, replay could not determine “which run this was.”
3. Records: Three Layers of Append-Only Semantics
Append-only is not an implementation detail but a deliberate design. It shows up on at least three layers:
- Written lines are never rewritten. Events are appended with a monotonically increasing
seq, and no historical event can be modified or deleted. Modifying history is equivalent to forging memory and breaks auditing and replay at the same time. - Packing and compression reduce fragmentation. Log lines and events are not strictly one-to-one: when consecutive events of the same type appear (for example, model output split into many small chunks), the backend can pack them into a single record, reducing line count and random write amplification.
- Sequence numbers provide a total order.
seqlets concurrent writes, chunk packing, and cross-process recovery all align to the same order, avoiding “causal inversion.”
Illustrative event structure (fields are generic design examples):
{"seq":1,"type":"session_header","sessionId":"demo-002","createdAt":"...","workspace":"/Users/Apple/projects/...","delegationDepth":0}{"seq":2,"type":"user_message","text":"fix the login timeout issue"}{"seq":17,"type":"tool_call","name":"edit_file","args":{"path":"src/auth.ts"}}{"seq":18,"type":"tool_result","ok":true,"summary":"patched 1 hunk"}{"seq":41,"type":"assistant_delta","text":"I have located the connection pool configuration"}
High-frequency small events like assistant_delta are the best candidates for packing; tool_call and tool_result must remain retrievable as pairs, otherwise recovery cannot determine whether a given side effect actually happened.
4. Checkpoints: Shrinking the Crash Window
Append-only solves “not losing history”; checkpoints solve “how much is lost.” A checkpoint is essentially a forced flush to disk (flush and sync) that establishes “confirmed progress” at key moments. Reasonable triggers include:
- turn boundaries: after one user request and one complete reply;
- before and after tool side effects: persist intent before writing a file, executing a command, or making a network request, then persist the result afterward;
- periodic fallback: triggered by dual thresholds of event count or time, preventing long stretches without a checkpoint during long outputs;
- lifecycle events: session pause, preemption, graceful exit.
A simple policy can describe this in engineering terms:
checkpoint if (seq - lastCheckpointSeq >= N) or (now - lastCheckpointAt >= T)or event.type in {turn_end, before_side_effect, after_side_effect}
The tradeoff matters: denser checkpoints lose less on a crash but increase write amplification and latency. For code-modification tasks, “before and after side effects” is recommended as a hard constraint, with periodic fallback for other scenarios.
5. Recovery: Replay, Rebuild, and Continue
The recovery flow can be abstracted into four steps:
- Read and decompress the log, verify continuity by sorting on
seq, and mark the recovery as “incomplete” as soon as a gap is found; - Parse the session header and bind the workspace and delegation depth to avoid cross-project recovery by mistake;
- Replay events to rebuild the conversation history, tool call pairing, and the state machine of unfinished turns;
- Continue execution after the last checkpoint, declaring to the user that it has “rolled back to a certain event” when necessary.
Recovery must be idempotent. If a tool side effect already happened before the crash but its result was never persisted, replay should first check the real-world state (for example, a file content hash) before deciding whether to retry, avoiding duplicate writes.
6. Engineering Checklist
- Isolate directories by workspace and keep a single file per session, making quotas and migration easy;
- Keep the session header on the first line immutable and
seqstrictly monotonic; - Pack high-frequency small events and keep low-frequency critical events on their own lines;
- Force checkpoints before and after side effects, with periodic checkpoints as fallback;
- Validate continuity and idempotency during recovery, exposing gaps explicitly instead of silently ignoring them;
- Separate compression and cleanup policies: keep recent sessions as hot data and move cold data to lower-frequency storage;
- Connect observability to a general logging service and monitoring alerts, with thresholds for “recovery failure rate” and “checkpoint latency.”
7. Conclusion
Making memory a combination of “append-only log + checkpoints + recovery” is essentially replacing unverifiable internal state with auditable external facts. Whether you use a mature agentic coding tool or build your own agent runtime on Baidu AI Cloud, this design turns interruptions into ordinary events that are predictable, recoverable, and traceable rather than incidents.
