AI Agent Memory Design: Append-Only Logs, Checkpoints, and Recovery

    Reliable AI agents need persistent session memory to resume interrupted work, preserve conversational context, and make their actions auditable. This article explains how append-only event logs, durability checkpoints, and replay-based recovery work together, including how to handle incomplete writes, uncertain tool outcomes, and subagent sessions.

    1. Why AI Agents Need Memory

    Imagine an agent modifying a large codebase. It has finished changing three files when the process crashes halfway through writing the fourth. Whether the agent can resume after restarting depends on whether its runtime has a memory mechanism.

    Without memory, an agent faces three problems.

    First, it cannot resume its progress. If the user asks, “Where did you leave off?”, the agent has no answer and must inspect the entire workspace again.

    Second, it cannot resolve references across turns. If the user says, “Update that function again,” the agent cannot identify the function because the conversation history is gone.

    Third, its behavior cannot be traced. When something goes wrong, developers need to know which operations the agent performed and in what order. Without a reliable record, that investigation becomes difficult.

    Memory is therefore infrastructure for reliable agent execution. Its purpose is to preserve what happened and reconstruct it accurately when needed.

    2. The Storage Model: An Append-Only Session File

    Memory does not need to be an opaque black box. A practical approach is to give each session its own file on disk, containing an append-only event log.

    The log uses JSONL: each line is an independent JSON object. To reduce disk usage, the file can also use general-purpose compression. After decompression, its contents remain plain text.

    A typical directory layout looks like this:

    1. sessions/
    2. <escaped-workspace-path>/
    3. <session-id>/
    4. session.jsonl.compressed

    The escaped workspace path groups sessions by project, while the session ID distinguishes tasks within the same project.

    The first line is a session header. It records identity information such as the session ID, creation time, workspace path, and delegation depth (delegationDepth). A top-level session has a delegation depth of 0; sessions created for subagents have progressively greater depths.

    The header is written when the session is created and is never modified. The session’s identity is therefore fixed from the first line, and all subsequent events belong to that identity.

    The header is followed by an event stream. Each line represents an event, such as user input, model output, a tool call, a tool result, or a file write. The following example illustrates the structure; the field names are illustrative:

    1. {"seq": 0, "type": "session_header", "sessionId": "demo-002", "createdAt": "2026-11-25T01:00:00Z", "delegationDepth": 0}
    2. {"seq": 1, "type": "user_message", "text": "Add unit tests for the configuration module"}
    3. {"seq": 2, "type": "tool_call", "tool": "read_file", "args": {"path": "config.py"}}
    4. {"seq": 3, "type": "tool_result", "callId": 2, "status": "ok"}

    The log is the session’s source of truth. Conversation history, task progress, and completed operations can all be derived from it.

    3. Recording: An Append-Only Event Stream

    Append-only behavior is the log’s central guarantee. It has three important implications.

    3.1 Never Rewrite Existing Events

    Events receive consecutive, increasing seq values. Once written, an event is never modified or deleted.

    This is deliberate. If the log is the source of truth, rewriting history would turn it from a record of actual events into editable narrative. Troubleshooting and auditing would lose their foundation.

    When an error needs correcting, append a new event, such as correction or compensation, explaining that an earlier result has been reversed or corrected. The original history remains intact.

    3.2 Batch Events to Reduce Writes

    Model output is typically streamed. A single response may arrive as dozens of small chunks. Writing each chunk as a separate line makes the log verbose and increases the number of writes.

    An implementation can instead batch consecutive events of the same type. For example, adjacent output chunks can be combined into an assistant_chunk_batch event.

    Batching introduces two trade-offs:

    • A larger batching window means more unpersisted content may be lost in a crash.
    • A batch must retain the original chunks’ sequence range so replay can reconstruct their order.

    In practice, batching is usually bounded by a time window or a byte limit.

    1. class SessionLogWriter:
    2. def __init__(self, path, max_batch_bytes=4096):
    3. self.path = path
    4. self.seq = 0
    5. self.buffer = []
    6. self.buffer_bytes = 0
    7. self.max_batch_bytes = max_batch_bytes
    8. def append(self, event_type, payload):
    9. self.seq += 1
    10. event = {"seq": self.seq, "type": event_type, **payload}
    11. line = json.dumps(event, ensure_ascii=False)
    12. self._write_line(line)
    13. def _write_line(self, line):
    14. with open(self.path, "a", encoding="utf-8") as f:
    15. f.write(line + "\n")
    16. f.flush()

    This simplified example omits compression and batching logic to show the basic append operation. In a production implementation, compression typically operates in blocks so that each append does not require recompressing the entire file.

    3.3 Appending Is Not the Same as Durability

    Appending data does not necessarily mean it has reached durable storage. Data may remain in application or operating-system buffers, leaving recent writes vulnerable to a crash or power failure, depending on where they are buffered.

    This is the durability boundary that checkpoints address.

    4. Checkpoints: Making Writes Durable at Critical Boundaries

    Recording determines how events are written. Checkpoints determine when those writes must be durable.

    A checkpoint is an explicit boundary at which the framework must ensure that all preceding events have been persisted before continuing.

    4.1 Where Checkpoints Belong

    Forcing every event to durable storage would impose substantial overhead. Checkpoints are usually most valuable at these boundaries:

    1. Before a tool call with side effects, such as writing a file or issuing a network request. The intent must be recorded first; otherwise, recovery may have no reliable evidence that the operation was attempted.
    2. After a side-effecting operation completes, when its result must be persisted immediately.
    3. At the end of a conversation turn, after the model produces its final response.
    4. When a subagent is created or returns, to preserve delegation boundaries.

    4.2 Centralize the Checkpoint Policy

    Representing checkpoint decisions as a policy keeps the rules in one place and makes them easier to adjust for different workloads.

    A simplified policy might look like this:

    1. CHECKPOINT_POLICY = {
    2. "before_side_effect_tool": True,
    3. "after_side_effect_tool": True,
    4. "end_of_turn": True,
    5. "child_session_boundary": True,
    6. "streaming_chunk": False,
    7. }
    8. def should_checkpoint(event_type, policy=CHECKPOINT_POLICY):
    9. return policy.get(event_type, False)
    10. def append_with_checkpoint(writer, event_type, payload):
    11. writer.append(event_type, payload)
    12. if should_checkpoint(event_type):
    13. writer.sync() # Use filesystem synchronization to persist data

    The central trade-off is latency versus durability. More frequent checkpoints reduce potential data loss, but each synchronization adds waiting time.

    High-frequency content that can be regenerated, such as streaming output, generally does not need a checkpoint for every event. Tool operations that cannot safely be replayed require stronger protection at their execution boundaries.

    5. Recovery: Rebuilding Conversation State from the Log

    Recovery completes the memory mechanism. After a restart, the framework must reconstruct the conversation and determine where execution can continue.

    A typical recovery sequence is:

    1. Locate the session log using the session ID and workspace path.
    2. Read and decompress the log, parsing each JSON line.
    3. Validate the session header against the expected session ID and workspace path.
    4. Replay events in seq order to reconstruct conversation history, tool-call state, and task progress.
    5. Identify the last complete turn and determine the appropriate continuation point.

    5.1 Handle Partially Written Data

    A process may crash halfway through writing a line, leaving an incomplete JSON object at the end of the file.

    Recovery should tolerate this case. If the final line cannot be parsed because it is incomplete, discard it and issue a warning rather than making the entire session unloadable. This rule allows an append-only log to remain useful after an interrupted write.

    1. def replay(path):
    2. state = ReplayState()
    3. lines = read_decompressed_lines(path)
    4. for index, line in enumerate(lines):
    5. try:
    6. event = json.loads(line)
    7. except json.JSONDecodeError:
    8. if index == len(lines) - 1:
    9. log_warning("Discarding incomplete trailing event line")
    10. break
    11. raise CorruptLogError(f"Unable to parse line {index}")
    12. state.apply(event)
    13. return state

    5.2 Handle Side Effects with Unknown Outcomes

    A more difficult case arises when the log contains a tool-call start event but no corresponding result. The operation may or may not have taken effect.

    The framework generally has three options:

    • Read-only operations: Run them again.
    • Writes that are safe to replay: Repeat them, such as overwriting a file with the same content.
    • Operations whose effects cannot be determined: Mark the outcome as unknown and ask the user how to proceed.

    For irreversible actions such as deletion, sending, or deployment, replay decisions should remain with the user. The framework must not automatically repeat them.

    6. Subagents and Delegation Depth

    When an agent delegates work, each subagent creates its own session log and records its delegation depth in the header. The parent session records a spawn event containing the child session ID, linking the two sessions.

    Delegation depth serves two purposes.

    First, it supports auditing: a log’s header indicates where the session sits in the delegation chain.

    Second, it provides a safety boundary. If subagents can keep spawning further subagents without restriction, delegation can become uncontrolled recursion. The framework should enforce a maximum depth and reject further delegation once that limit is reached.

    7. Engineering Practices

    The following practices help keep this design reliable:

    • Keep the log append-only. Express corrections through new events rather than rewriting history.
    • Centralize checkpoint rules. Avoid scattering durability decisions throughout business logic so the policy remains easy to adjust and test.
    • Tolerate an incomplete trailing line during recovery. This is a basic requirement for recovering from interrupted writes.
    • Record intent before executing side effects, then record the result afterward. Recovery must recognize the gap between those two events.
    • Review sensitive information in session headers. Workspace paths may contain usernames or other private information that requires redaction before storage or sharing.
    • Run crash tests regularly. Terminate the process at different points in the write path and verify the recovered state. This is one of the most effective ways to find missing checkpoints.

    8. Conclusion

    Agent memory can be understood as three cooperating mechanisms:

    • Recording appends events in order without rewriting existing history.
    • Checkpoints make preceding events durable at critical boundaries, limiting what can be lost after a crash.
    • Recovery reconstructs conversation state while handling incomplete writes and unfinished operations.

    Together, these mechanisms provide session memory that supports reliable continuation and auditing.

    They also provide a clear troubleshooting workflow: inspect what the log records, check whether durability checkpoints cover the critical boundaries, and verify that recovery reconstructs the state correctly.