Principles of AI Agent Memory: Append-Only Logs and Checkpoint Recovery
This article explores the core principles of building reliable memory for AI agents in long-running tasks. It details an architecture based on an append-only event log combined with logging, checkpointing, and recovery mechanisms. Readers will learn how append-only semantics ensure auditability, how checkpoints minimize data loss during crashes, and how deterministic log replay restores agent context and execution state.
1. The Starting Point: Without Memory, Agents Suffer from “Amnesia”
Imagine an intelligent coding assistant with tool-calling capabilities continuously modifying three files in a large codebase. The process suddenly crashes. After a restart, does it remember which step it reached?
The answer depends on whether the runtime harness possesses persistent memory. Without memory, three types of problems immediately surface:
- Reference failure: When a user says “modify that function from just now,” the model cannot determine which round or which symbol “just now” refers to.
- Progress loss: If a multi-step task crashes halfway, completed edits, read files, and ruled-out hypotheses all reset to zero, forcing a full restart from scratch.
- Non-auditability: When issues arise, it is impossible to answer “what did it actually do and based on what?” Troubleshooting relies entirely on guessing.
Therefore, memory is not a nice-to-have feature but the foundation of long-task reliability. The industry-standard approach can be summarized as an equation:
Memory = An append-only ledger + Logging, Checkpoint, and Recovery mechanisms
The ledger is the source of truth, while the three mechanisms are respectively responsible for “writing it in,” “making it stick,” and “reading it back.”
2. Examining the Artifact: What a Task Leaves on Disk
After running two real tasks locally, a session directory appears outside the workspace, looking like this:
sessions/--Users-Apple-projects-deepseek_harness-workspace--/demo-001/session.jsonl.zstddemo-002/session.jsonl.zstd
The path can be interpreted segment by segment:
| Segment | Meaning |
|---|---|
sessions |
Session root directory, separated from the workspace to avoid polluting the operated codebase |
--Users-Apple-...-- |
Escaped directory name from the workspace absolute path, ensuring different projects don’t mix |
demo-002 |
Session ID, one per task |
session.jsonl.zstd |
Log body: JSONL text + universal lossless compression |
After decompression, it is plain text with one JSON event per line. A typical task has 62 lines, meaning 62 events; the first line is the session header, and the rest is the event stream. Representative events (illustrative):
{"type":"session_header","sessionId":"demo-002","createdAt":"...","workspace":"/Users/Apple/projects/...","delegationDepth":0}{"seq":1,"type":"user_message","text":"Fix login timeout issue"}{"seq":2,"type":"assistant_message","text":"First locate the relevant module"}{"seq":3,"type":"tool_call","name":"read_file","args":{"path":"src/auth.ts"}}{"seq":4,"type":"tool_result","status":"ok","summary":"..."}{"seq":5,"type":"checkpoint","reason":"before_edit"}{"seq":6,"type":"tool_call","name":"apply_patch","args":{"path":"src/auth.ts"}}
The session header is unique: It records metadata such as session ID, creation time, workspace path, and delegation depth (delegationDepth, which is 0 for top-level sessions and increments for sub-agent derived sessions). It is immutable—a session’s identity is fixed on the first line and only appended to afterward, never rewritten. This constraint makes “who the session is, which directory it is in, and which delegation level it belongs to” always determinable.
3. Logging: The Append-Only Event Stream
“Append-only” is the core semantic of the entire log, manifested in three aspects.
First, written lines are never rewritten. Events are appended sequentially by seq, and any event already written to disk will not be modified or deleted. This is not an implementation detail but a deliberate design: the log is the single source of truth; rewriting history is equivalent to forging memory, which makes both auditing and recovery meaningless.
Second, sequence is causality. The physical order of events is the chronological order, with seq providing a monotonically increasing number. During recovery, no external clock is needed; the causal chain of “read before write” or “fail before retry” can be reconstructed relying solely on the file itself.
Third, compression saves space. Session logs have high redundancy (the same file read repeatedly, similar JSON structures). Universal lossless compression significantly reduces the size, and decompression is streaming—recovery does not require loading all content at once. Note that compression only changes the storage encoding, not the logical content: after decompression, it is still line-by-line parsable JSONL.
Append-only writing also has an engineering advantage: it is the cheapest write mode on disk. It requires no read-modify-write, no page split maintenance, and is naturally sequential I/O, resulting in a short write path and a limited crash impact surface.
4. Checkpoints: Turning “Written In” to “Made to Stick”
Append-only solves “no tampering,” but does not solve “what if it’s lost?” Operating system page caches and write buffers can cause recent events to vanish during a crash. Checkpoints are forced persistence points designed for exactly this.
Checkpoint strategies typically include three types of triggers:
- Critical moment enforcement: Execute a checkpoint before operations with side effects (writing files, committing changes, calling external APIs) to ensure the fact that “an action is about to be taken” is persisted.
- Threshold trigger: Persist to disk every N events or every T seconds to limit the maximum loss window during a crash.
- Lifecycle trigger: Persist when the session is idle, the task concludes, or the process receives an exit signal.
Engineering-wise, two things must be paired with this: write integrity (each record carries length or checksum info to identify incomplete trailing lines caused by a crash) and persistence semantics (explicitly requiring a sync to stable storage after appending, rather than relying solely on buffers). Checkpoint records themselves are also events and are append-only, so strategy changes do not break the log structure.
5. Recovery: Replaying Logs to Rebuild Context
The goal of recovery is not to “read back a snapshot,” but to replay a state consistent with before the crash:
- Locate the session directory by the workspace path using escape rules, and read the log.
- Validate and discard incomplete trailing records, then parse the session header to confirm identity.
- Sequentially replay events to rebuild message history, tool calls and results, and file change records.
- Confirm up to which step was persisted based on the last checkpoint, and continue from the unfinished round.
- For operations with high idempotency risks (such as partially applied patches), verify first before resuming to avoid duplicate application.
Because the log is append-only, replay is deterministic: the same input sequence inevitably yields the same state, making “crash—restart—resume” testable and reproducible.
6. Implementation Checklist and Common Pitfalls
- Separate storage from workspace: Path escaping must be reversible and stable across platforms.
- Lock down event schema early: Adding fields should be backward compatible; changing semantics requires a version upgrade. Do not rewrite old events in place.
- Sensitive data governance: Logs contain full conversations and file fragments. Clearly define retention periods, access controls, and masking strategies. Long sessions can be archived to low-frequency storage, paired with log services and monitoring alerts for capacity and anomaly tracking.
- Concurrency and multi-session: Single writer per session; sub-agent sessions are distinguished by
delegationDepthand ID to avoid cross-appending. - Don’t over-engineer compression: Prioritize streaming decompression and on-demand reading; do not sacrifice diagnosability to save space.
7. Conclusion
AI agent memory is not mysterious: it is an append-only event log on disk, augmented by logging, checkpointing, and recovery mechanisms. Append-only ensures facts cannot be forged, checkpoints keep the crash loss window controllable, and recovery guarantees deterministic state reconstruction. With all three in place, long-running tasks can achieve reliability and auditability.
