AI Agent Memory Design: How Append-Only Logs, Checkpoints, and Recovery Work
This article breaks down the core mechanics of AI agent memory through the lens of session persistence: an append-only event log as the source of truth, plus recording, checkpointing, and recovery built around it. Using logs from two real local tasks, it explains the session directory layout, JSONL event semantics with zstd streaming compression, checkpoint trigger conditions, deterministic replay, and a practical engineering checklist for building auditable, replayable, and resumable agent state management.
1. The Starting Point: Why Agents Need Memory
Consider an agent working in a large codebase that has modified three files in a row when the process suddenly crashes. After a restart, does it still know which step it had reached? The answer depends entirely on whether the runtime (harness) provides persistent memory.
Without memory, an agent immediately “loses its memory” in three situations: when the user asks “where did we get to just now,” it has no answer; in a multi-turn conversation, when the user says “modify that function again,” it cannot resolve the reference “that one”; and during an incident review, when someone wants to confirm “what operations did it actually perform,” there is no evidence to check.
Agent memory can therefore be abstracted as an equation:
Memory = an append-only ledger + recording + checkpoints + recovery
The ledger is the source of truth, and the other three are mechanisms built around it. This article takes two general-purpose session persistence components from an AI coding tool (the session persistence backend and the checkpoint policy) as the observation target, and uses logs left by two real local tasks to unpack these three things one by one. No specific vendor product is involved here; the discussion covers common engineering practices in the industry, which apply equally to agent runtime design on platforms such as Baidu AI Cloud.
2. Look at the Artifact First: Memory Files Left by a Task
After two real tasks finish, a session directory appears outside the workspace in each case, typically shaped like this:
sessions/--Users-Apple-projects-agent-workspace--/demo-001/session.jsonl.zstddemo-002/session.jsonl.zstd
Each segment of the path deserves a layer-by-layer explanation:
sessions: the session root directory, physically isolated from the code workspace to keep memory files from polluting the business repository;- the long directory name in the middle: an escaped form of the workspace’s absolute path, with
/replaced by-and--added at the start and end as boundary markers. This groups sessions from the “same workspace” together while avoiding the hierarchy ambiguity caused by path separators; demo-002: the session id, the unique identifier of a session;session.jsonl.zstd: the log body itself. JSONL format, zstd compressed; once decompressed it is plain text, with one JSON event per line.
After decompression there are 62 lines in total, meaning 62 events. The first line is the session header, and the rest is the event stream. The session header records metadata such as the session id, creation time, workspace path, and delegationDepth (delegation depth, 0 for a top-level session and increasing level by level for sub-agent sessions).
There is one key constraint here: the session header is immutable. A session’s identity is fixed on the first line, and from then on only appending events is allowed; historical lines are never rewritten. delegationDepth is especially important, because it allows the tree structure of “a main agent spawning sub-agents” to be fully reconstructed on recovery, so that permission boundaries and context visibility scope can be correctly restored.
3. Recording: The Semantics of an Append-Only Event Stream
“Append-only” is the most core semantic of this log, and it takes effect on three levels at once.
First, lines that have been written are never rewritten. Events are appended continuously by seq number, and no event already persisted is modified or deleted. This is not an implementation detail but a deliberate design choice: the log is the single source of truth, and modifying history is equivalent to forging memory, which would make all downstream reasoning lose credibility.
Second, packing and compression save space. Log lines and events are not strictly one-to-one: when a large number of consecutive events of the same type appear (for example, model output split into dozens of small chunks), the backend packs them into the same line, forming a compact “multiple events per line” representation. On read, they are expanded back into a logical event sequence. This reduces two costs at the same time—disk usage and the number of small random writes.
Third, compression and appending do not conflict. zstd supports streaming compression, and incremental data is appended in units of frames, so the “append-only” semantic still holds at the compression layer, without needing to rewrite the whole file for the sake of compression.
The illustrative write logic can be understood like this:
def append_event(session, event):event.seq = session.next_seq() # monotonically increasingsession.raw.write(encode(event) + b"\n")session.raw.flush() # hand off to the buffer/compression layerreturn event.seq
4. Checkpoints: Shrinking the “Possibly Lost” Window to the Minimum
Append-only solves “history cannot be tampered with,” but it does not solve “data in the buffer at crash time has not yet been persisted.” The checkpoint policy handles the latter: it forces writes and syncs to complete at critical moments, shrinking the window that could be lost to the minimum.
Common trigger points include: the end of a conversation turn, a tool call returning, before and after context compaction, when a sub-agent delegation is created or ends, and when the process receives an exit signal. The policy layer usually adds two protective conditions on top—a minimum event interval (to avoid frequent syncs caused by high-frequency events) and a maximum number of unflushed bytes (to avoid long periods without persisting).
def maybe_checkpoint(session, trigger):if trigger in CRITICAL_TRIGGERS \or session.pending_bytes() > MAX_PENDING \or session.since_last_sync() > MAX_INTERVAL:session.compressor.flush()session.file.sync() # persist to disksession.last_sync = now()
It should be made clear what the capability boundary of checkpoints is: what they guarantee is that “events confirmed as written are not lost,” not that “the last user input at the moment of the crash is definitely preserved.” In engineering practice, a layer of idempotent replay is usually added on top, so that the last uncertain segment of content after recovery can be safely retried.
5. Recovery: Rebuilding the World from the Log
The recovery flow can be broken into four steps, and the order cannot be reversed:
- Locate and decompress the log, then read it line by line;
- Validate the session header, confirming that the session id, workspace path, and delegation depth match;
- Replay events in order to rebuild the message history, tool call records, and todo state;
- Continue from after the last checkpoint, resuming the interrupted turn.
Replay must be deterministic: for the same event sequence, no matter how many times it is replayed, the same in-memory state should result. This is also the direct benefit of “append-only” on the recovery side—there is no need to handle the branch case of “history being rewritten,” so the recovery logic is greatly simplified.
6. Engineering Practice Checklist
- Store memory files separately from the workspace to avoid accidentally committing them into version control;
- Make the directory name escaping rule reversible, so the workspace can be inferred back from the path;
- Keep
seqmonotonically increasing and globally unique, serving as the basis for deduplication and ordering; - Use a compression scheme that supports streaming appends, and keep the write side on a simple “open—append—sync” model;
- Make checkpoint trigger conditions configurable, balancing data safety against write overhead;
- Perform an integrity check before recovery; a corrupted tail can be truncated to the last complete event;
- Set archiving and cleanup policies for long sessions to prevent the log from growing without limit.
7. Conclusion
Agent memory is not mysterious: a compressed append-only event log, plus the three mechanisms of recording, checkpoints, and recovery, forms a memory foundation that is auditable, replayable, and resumable. Once you understand this general principle, whether you are building your own runtime or building a persistence pipeline on a cloud platform based on object storage, log services, and monitoring alerts, you can design agent state management with clear boundaries and controllable failures.
