AI Agent Memory Design: From Append-Only Logs to Recoverable Sessions

    This article explains how AI agent memory works at the framework level, using an append-only session log as the single source of truth. It covers the on-disk log format, how events are recorded and compressed, when checkpoints are triggered, and how replay rebuilds conversation state after a crash. It also outlines practical concerns such as workspace isolation, retention, observability, privacy, and idempotent retries.

    AI Agent Memory Design: From Append-Only Logs to Recoverable Sessions

    1. The Starting Problem: Why Agents Need Memory

    Picture an agent refactoring a large codebase. It has already modified three files and is about to start the fourth when the process is unexpectedly terminated. After a restart, does it still know where it left off?

    The answer depends entirely on whether the underlying harness has memory at all. Without it, an agent is effectively amnesiac:

    • When the user asks “where did we get to?”, it cannot answer.
    • In a multi-turn conversation, a request like “change that function again” cannot be resolved, because “that” points to nothing.
    • When something goes wrong and the team needs to review what the agent actually did, there is no record to consult.

    Memory is therefore not a nice-to-have. It is the prerequisite for moving an agent from one-off question answering to sustained collaboration. A common industry formulation is:

    1. Memory = an append-only ledger + recording + checkpoints + recovery

    The ledger is the data carrier; the other three are the mechanisms that make the carrier usable. Each is covered below.

    2. Carrier Format: What a Session Log Looks Like

    In most engineering implementations, agent memory does not live in a mysterious black box. It is a real file on disk, with one log file per session:

    1. sessions/<escaped workspace path>/<session ID>/session.jsonl.zstd

    What each path segment means:

    • sessions: the session root directory, where all sessions are managed together.
    • The middle segment: the absolute workspace path, escaped into a directory name. For example, /Users/Apple/projects/.../workspace becomes --Users-Apple-...-workspace--. This keeps sessions from different workspaces naturally isolated, so identical session IDs cannot overwrite each other.
    • Session ID: the unique identifier for a single task.
    • session.jsonl.zstd: the log body, in JSONL format and compressed with zstd. Once decompressed it is plain text, with one JSON event per line.

    A log for a medium-sized task is typically a few dozen lines. The first line is the session header, holding metadata such as the session ID, creation time, workspace path, and delegation depth (0 for a top-level session, incrementing per level for sub-agent sessions). The remaining lines are the event stream: user input, model output chunks, tool call requests, tool results, turn boundary markers, and so on.

    The key design point: the session header is immutable. A session’s identity is fixed in the first line, and only new events may be appended. History is never rewritten.

    3. Mechanism One: Recording (Append-Only Event Stream)

    Append-only is the most fundamental semantic in the whole design, and it shows up on three levels:

    1. Written lines are never rewritten. Events are appended continuously with a monotonically increasing seq number, and no event already on disk is modified or deleted. This is not an incidental implementation detail but a deliberate constraint: the log is the single source of truth, and editing history amounts to fabricating memory.
    2. Packing and compression save space. Log lines and events are not necessarily one-to-one. When many events of the same type arrive consecutively — typically when model output is split into dozens of small chunks — the backend packs them into a single stored line. In practice this kind of packing yields a noticeable size reduction (commonly around 60%) while also cutting the number of I/O operations.
    3. Appending naturally suits crash recovery. Sequential appends avoid the “half-written” risk of in-place overwrites. Combined with truncation handling at the end of the file, recovery only needs to discard the last incomplete record.

    Illustrative write logic:

    1. def append_event(session, event):
    2. event["seq"] = session.next_seq() # monotonically increasing
    3. event["ts"] = now_iso()
    4. line = json.dumps(event, ensure_ascii=False)
    5. with open(session.log_path, "ab") as f: # append mode
    6. f.write(line.encode() + b"\n")
    7. f.flush()
    8. os.fsync(f.fileno()) # force a flush to disk at key points

    4. Mechanism Two: Checkpoints

    Append-only solves “history is not lost”, but frequent writes create two problems: the log grows, and a crash at the wrong moment can leave half a record behind. Checkpoints force buffered content to be fully written and persisted at key moments, keeping boundaries clean.

    Common checkpoint triggers include:

    • The end of each conversation turn (the user message has received a complete response).
    • After a tool call completes and its result has been written back.
    • When a delegated subtask starts or ends, or when the delegation depth changes.
    • Before a session times out while idle or is explicitly closed.

    A checkpoint turns “a logically complete group of events” into “a physically persisted group of bytes”. In engineering practice this usually pairs with a two-phase strategy: write to a temporary segment and verify its integrity first, then atomically switch it to the official log, avoiding a state that looks complete but is actually truncated.

    5. Mechanism Three: Recovery (Rebuilding via Replay)

    The goal of recovery is to rebuild all context from before the restart, so the agent can continue seamlessly. The standard flow is:

    1. Locate the session directory and read the log file (decompressing if necessary).
    2. Parse events line by line, safely discarding an unparseable incomplete line at the tail.
    3. Validate the session header, confirming metadata such as workspace and delegation depth match.
    4. Replay events in seq order to rebuild conversation history, tool call state, and pending progress.
    5. Continue with a new turn after the last complete event.

    Illustrative recovery logic:

    1. def restore(session_dir):
    2. events = []
    3. with open(log_path, "rb") as f:
    4. for raw in f:
    5. try:
    6. events.append(json.loads(raw))
    7. except json.JSONDecodeError:
    8. break # incomplete tail, truncate safely
    9. events.sort(key=lambda e: e["seq"])
    10. header, stream = events[0], events[1:]
    11. return rebuild_state(header, stream)

    Because the log is append-only, replay is deterministic: the same log always rebuilds the same state, which provides a reliable basis for troubleshooting.

    6. Engineering Practice Notes

    • Isolation and naming: organize directories by escaped workspace path plus session ID to avoid crossing sessions; use delegation depth to distinguish the permissions and context scope of main and sub-sessions.
    • Compression and retention: apply streaming compression to historical logs; archive or clean up expired sessions by policy, balancing cost against auditability.
    • Observability: bring log size, checkpoint duration, and recovery time into the monitoring and alerting system; log files can be shipped to object storage for long-term retention.
    • Privacy and security: logs contain full conversations and tool output and should be treated as sensitive data — encrypted on disk, with controlled access and a defined retention period.
    • Idempotency and retries: when resuming tool calls after recovery, the design must be idempotent to avoid modifying files twice or submitting duplicates.

    7. Conclusion

    Agent memory is not mysterious: an append-only session log plus three mechanisms — recording, checkpoints, and recovery — forms a trustworthy, auditable, recoverable memory foundation. Once you understand these principles, whether you are building your own harness or agent applications on a cloud platform, you can more confidently design session persistence, failure recovery, and multi-turn context management, giving agents a real ability to collaborate with memory they can retain, explain, and inspect.