Persistent Session Memory for AI Agents: Append-Only Logs, Checkpoints, and Recovery
This article explains how AI agents can preserve session memory across crashes and restarts by externalizing memory as an append-only event log. It covers the one-session-one-log layout, session headers and event sequences, checkpointing and flush boundaries, recovery and replay, idempotency for side effects, consistency limits, common pitfalls, and three validation drills.
When an agent edits code across multiple turns, looks up information, and calls tools, the hard part is not generating another response. It is continuing work after an interruption. A process crash, a machine reboot, or a truncated context window can erase the basis for questions such as “where did I stop editing, what did I call, and which function did the user mean?” Without persistent memory, an agent is effectively an amnesiac executor: it cannot continue a task or support postmortem review.
A practical equation is: memory equals an append-only event ledger plus three mechanisms: recording, checkpointing, and recovery. Memory is not a mysterious state inside model weights. It is a replayable source of truth on disk.
Why Memory Must Be Externalized
Typical failure scenarios are concrete. An agent has already modified several files, run tests, and is preparing a commit message when the host process exits. After restart, if only the last model context remains, the system cannot answer “where did I stop editing?” When the user says “tighten up that function from earlier,” the reference cannot be resolved. During troubleshooting, there is no evidence of which tool call was made or what arguments it used.
Externalized memory must satisfy four requirements at the same time.
- Continuity: a new process can reload unfinished turns instead of starting from a blank conversation.
- Referentiality: files, functions, and tool results in history have stable events that can support references such as “just now” and “the previous step.”
- Auditability: actions that have occurred are recorded in order, making it possible to locate incorrect decisions.
- Crash safety: if a process exits halfway through a write, the entire memory must not become a half-written, unreadable state.
Putting the full conversation into a single request does not solve the last three requirements. Context is working memory; the log is long-term memory.
Physical Form: One Session, One Log
Each task corresponds to a session directory outside the workspace. The directory name is derived from a stable escape of the workspace path to avoid slashes and special characters breaking the filesystem. Below it, session identifiers distinguish parallel tasks. The log itself is a line-oriented event file, optionally stream-compressed to save space. After decompression, it is still plain text: one event per line, or one packed event group per line.
A medium-length coding task often produces only dozens to a few hundred events. The first line is not a normal action but a session header, containing at least:
- session ID and creation time
- workspace root path
- delegation depth: 0 for a top-level task, incremented for child tasks, used to distinguish primary and secondary execution
- immutable metadata such as writer or mode
Once the session header is persisted, it cannot be changed. Identity is fixed on the first line, and only appends are allowed afterward. This way, the recovery program does not need to guess which task the file belongs to.
Representative events usually include user messages, model output deltas, tool call start and end, file change summaries, errors, turn boundaries, and checkpoint markers. The following is a neutral illustration, not a private interface from any specific implementation:
{"type":"session_header","sessionId":"task-017","workspace":"/data/repo","delegationDepth":0,"createdAt":"2026-04-02T08:01:11Z"}{"seq":1,"type":"user_message","turn":1,"text":"Add invalid-input validation to config loading"}{"seq":2,"type":"tool_call","name":"read_file","args":{"path":"src/config.ts"}}{"seq":3,"type":"tool_result","ok":true,"bytes":2401}{"seq":4,"type":"assistant_delta","text":"First reject empty objects at the parsing entry point"}{"seq":12,"type":"checkpoint","reason":"turn_committed","durableSeq":12}
Sequence numbers seq must be contiguous. A gap means a crash, corrupted concurrent write, or incorrect recovery logic, and the system should refuse to skip it silently.
Recording: Append-Only Is Semantics, Not an Optimization
Append-only must be enforced at three levels.
First, written lines are never rewritten or deleted. Events are appended by sequence number. The log is the single source of truth, and changing history is equivalent to falsifying memory. The way to correct an error is to append a compensating event, such as “undo a write” or “mark this result invalid,” rather than going back and erasing the original text.
Second, compression and packing must not change logical order. Model output is often split into many small deltas. If every delta becomes a separate physical line, the file grows and the number of flushes increases. The backend can pack consecutive, homogeneous deltas into a group and then compress them, but the order within the group, sequence assignment, and visibility to the caller must be equivalent to appending each event individually. After expansion, the reader still sees a monotonic event stream.
Third, appends need an explicit durability boundary. A successful application-level write does not mean the operating system has written the data to stable media. Implementations should distinguish between entering a buffer, completing a flush, and a checkpoint promising that “everything up to this sequence number is durable.” Callers can treat only events before the checkpoint sequence number as memory that is guaranteed to survive a crash.
Concurrency also needs restraint. Only one writer is allowed per session. Child tasks use independent session files and are linked by delegation depth and parent session ID, rather than having multiple processes contend for the same log. This avoids distributed locks for sequence allocation and prevents interleaved writes during recovery.
Checkpoints: Turning “May Be Lost” into “Has Happened” at Key Moments
A checkpoint is not a separate conversation summary that replaces the log. It is a forced durability operation: flush the buffer, close the compressed frame at a consistent boundary, and append a checkpoint event declaring the durable sequence number. If the process crashes after this point, the recovery side can reconstruct at least up to that sequence number.
The strategy should be neither “flush on every event” nor “flush only at the end.” Flushing every event turns a coding task into a disk-intensive workload. Flushing only at the end exposes the entire task to the final crash. A practical strategy is tiered by risk:
- Flush once after a user message is enqueued, so the question itself is not lost.
- Flush once before a tool call is issued. Otherwise, after a crash the system may repeat an operation with side effects, or it may not know whether the call already happened.
- Flush once after a tool result is persisted, to avoid “the call happened, the result was lost, so call it again.”
- Flush once after a turn of model output is accepted and before moving to the next turn.
- Flush when idle time exceeds a threshold or the buffer reaches a size limit, bounding the loss window for abnormal exits.
- Perform a terminal checkpoint when the session ends normally, and mark the task as complete or pending.
Checkpoint events themselves should also be append-only. They record the reason, durable sequence number, optional turn number, and not a second copy of secret state. If fast opening is needed, a rebuildable side index can be maintained: latest checkpoint position, line count, and uncompressed size. If the index is corrupted, a full scan of the log is allowed to rebuild it. The index is never the source of truth.
Side effects require a separate idempotency design. A log can prove that a call was “prepared” and that a result was “recorded,” but it cannot magically cancel an action already written to an external system. For tools that modify a repository, send messages, or write remote resources, include a stable call identifier. Before rerunning after recovery, check whether that identifier already has a successful result. This is the boundary between checkpoints and business-level idempotency; do not conflate it into one “automatic transaction.”
Recovery: Replay the Log, Don’t Guess What the Model Remembers
Recovery has four steps.
- Locate the session file and validate that the session header matches the workspace and session ID supplied by the caller. If they do not match, refuse to load it, avoiding attaching another task’s memory to the current repository.
- Decompress and parse sequentially. If the last line is truncated or a compressed frame is unclosed, discard that incomplete write and roll back to the previous complete event. If a checkpoint exists, roll back at least to a position no earlier than the checkpoint’s promise. Do not repair a half-line of JSON into an event that “looks plausible.”
- Rebuild conversation history, tool traces, and turn boundaries from events. The model-visible context can be projected from the log: user messages, completed tool results, and accepted assistant text. The tail not covered by a checkpoint is marked as potentially incomplete according to policy.
- Decide the resume point. If the last state stopped after a tool was issued but before a result was recorded, enter a compensation branch: query the idempotency record or ask the user, rather than blindly replaying. If it stopped after a turn was committed, continue from the next user input or pending plan.
When rebuilding, do not stuff the full history back into the model. The log is responsible for completeness; context is responsible for relevance. A common approach is to keep recent turns in full and compress earlier turns into summaries with event sequence numbers. Summaries remain traceable to the original lines. A summary is a derivative, and the log wins when the two conflict.
Child task recovery must respect delegation depth. The parent session stores only “a child session was dispatched” and the child session’s conclusion event. The child session’s own tool details remain in the child log. This keeps the parent context from being overwhelmed by grandchild task deltas while still allowing audit-level drill-down.
Consistency Boundaries and Common Pitfalls
This design guarantees recoverability of session facts, not transactions across the entire external environment. If files have already been written to the workspace by tools, the working tree after a crash may be ahead of the last checkpoint. Recovery logic should compare the file change summaries in the log with the current workspace state and explicitly present the differences to a human or the next planning turn, rather than pretending the two are always synchronized.
Also avoid these pitfalls:
- Updating a “current conversation snapshot” in a database without keeping old versions, so the decision path is invisible during troubleshooting.
- Allowing compression or packing to reorder sequence numbers.
- Keeping checkpoints only in an in-memory counter, so the promise becomes void after the process exits.
- Writing raw secrets or tokens into events. Logs often live longer than conversation windows, so record references and summaries, and keep sensitive values in a dedicated secret store.
- Automatically replaying every tool during recovery. Read operations can be retried; write operations must be idempotent or manually confirmed.
How to Tell Whether the Design Is Sound
Three drills can validate the design without relying on subjective judgment.
- Kill the process mid-turn: after restart, the user question and completed tool results are still present, and unflushed tail deltas are explicitly discarded.
- Kill the process after a tool call is issued but before the result is written: recovery does not execute the same side effect a second time, or it detects the duplicate and stops.
- Truncate the last byte of a compressed file: the parser reports an incomplete tail, and the checkpointed portion remains replayable.
Passing these three drills turns memory from “the model should remember” into “a provable prefix on disk.” Recording keeps history from being lost, checkpointing defines the durable prefix, and recovery rebuilds from that prefix and safely resumes. Together, these three mechanisms are what allow a long-running agent to claim that it has memory.
