Agent Harness Memory Design: How Append-Only Logs, Checkpoints, and Restore Work

    This article breaks down the memory design principles behind an agent execution framework (harness), using an append-only event log as the single source of truth. It explains how recording, checkpointing, and restore work together to make long-running coding tasks interruptible, resumable, and auditable, and offers practical engineering guidance on storage layout, log compaction, crash consistency, idempotent replay, observability, and security. Readers will learn what to look for when building or evaluating agent memory: immutable log structure first, checkpoint strategy and restore idempotency second, with observability and compliance as safeguards.

    1. Background: Why Agents Need Memory

    When a coding agent or automation agent works continuously in a large codebase, it goes through multiple rounds of reasoning, repeated file reads and writes, and a number of tool calls. The most fragile part is not the model’s reasoning ability but whether state is reliably retained. Consider a typical scenario: the agent has already modified three files and is about to run a compile check when the process is forcibly terminated due to a resource error. After a restart, does it still remember which step it reached, what additional constraints the user supplied in the previous turn, and whether the failure has been diagnosed?

    Without persistent memory, an agent is effectively amnesiac: it cannot answer when the user asks about progress; references like “adjust that function again” cannot be resolved across turns; and after a failure there is no auditable execution trail. A framework with memory, on the other hand, turns one long task into a process that can be interrupted, resumed, and traced. This article uses the memory scheme of an agent execution framework (referred to below as the harness) as a sample, abstracts its general design principles, and provides actionable engineering recommendations.

    2. The Core Equation: Memory = Append-Only Log + Three Mechanisms

    A relatively mature approach in the industry can be summarized as one equation:

    1. Memory = append-only event log + Record + Checkpoint + Restore
    • Append-only event log: the single source of truth, persisted in time order and never rewritten.
    • Record: sequentially write each reasoning step, tool call, model output fragment, user message, and so on as events.
    • Checkpoint: force a flush at key points in time so that facts that already happened are not lost.
    • Restore: after a restart, replay the log to rebuild conversation history and execution context and continue the unfinished turn.

    The four support each other: the log provides the underlying data structure, Record handles “writing it in,” Checkpoint handles “writing it durably,” and Restore handles “reading it back.”

    3. Storage Layout: One Log File per Session

    A straightforward engineering convention is: each session maps to an independent log file on disk, located under the session root directory. The directory name is derived by escaping the workspace path, the session identifier serves as a subdirectory, and the file name is uniformly “session log + compression suffix.” Logically it looks like:

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

    Breaking it down layer by layer:

    1. sessions: the session root directory, which centrally manages all sessions;
    2. the middle segment: separators in the absolute workspace path are replaced with safe characters to avoid directory traversal and ambiguity;
    3. <session ID>: the unique identifier of one task;
    4. session.jsonl.zstd: the log body, using JSONL (one JSON event per line) compressed with a general-purpose lossless algorithm; once decompressed it is plain text, which makes manual troubleshooting easier.

    The first line is the session header, recording metadata such as the session identifier, creation time, workspace path, and delegation depth (0 for a top-level session, incremented for sessions derived by sub-agents). The header is immutable — identity is fixed in the first line, and only event appends are allowed afterward. This design brings two benefits: paths and identity can be verified, and no guessing about context ownership is needed during restore.

    4. Record Mechanism: Three Layers of Append-Only Semantics

    Layer 1: written lines are never rewritten. Events are appended continuously with a monotonically increasing sequence number (seq), and no persisted event is modified or deleted. This is not an implementation detail but a deliberate constraint: the log is the single source of truth, and tampering with history is equivalent to forging memory, which breaks the correctness of auditing and restore.

    Layer 2: consecutive events of the same type are packed. When multiple consecutive events of the same type appear in the log (for example, model output split into dozens of small fragments), the backend can pack them into a single stored line (pack-chunks), significantly reducing size while keeping the logical event sequence unchanged. A common engineering result is that log size drops by more than half, while I/O amplification from frequent small random writes is reduced.

    Layer 3: append writes instead of full rewrites. Append mode naturally suits sequential I/O and avoids frequently rewriting the whole file; combined with batched flushes, it balances throughput and durability.

    Illustrative pseudocode:

    1. function record(event):
    2. event.seq = lastSeq + 1
    3. line = jsonEncode(event)
    4. if sameTypeAsPrevious(event) and canPack(event):
    5. appendToCurrentPackedLine(event) # logically still multiple events
    6. else:
    7. appendLine(file, line)
    8. lastSeq = event.seq
    9. if shouldCheckpoint(event):
    10. fsync(file)

    5. Checkpoint Mechanism: The Key to Crash Consistency

    Append-only guarantees “no tampering,” but the operating system page cache and disk write-back policies can still cause “written but not persisted.” Hence checkpoints: force writes to complete at key points in time (such as the end of each conversation turn, before and after tool calls, at delegation boundaries to sub-tasks, and when model output completes), using forced synchronization to flush in-memory buffers to persistent media.

    Design points:

    • Choosing checkpoint positions: use “semantic boundaries” rather than fixed time intervals; state is most complete at boundaries, so restore cost is lowest.
    • Controlling frequency: too frequent slows the main flow, too sparse enlarges the loss window. Sync can be tiered by event type: force synchronization for critical state changes, and batch or defer ordinary fragments.
    • Atomicity: if multiple files need to be written (such as a log and an index), write the log first and the index second, and rebuild the index from the log during restore, avoiding “an index pointing to data that does not exist.”

    6. Restore Mechanism: Rebuilding the World from the Log

    The essence of restore is deterministic replay: read the log, replay events in seq order, rebuild conversation history, tool call context, and delegation relationships, then continue the unfinished turn. Key points:

    1. Validate the header and path: read the session header first to confirm the workspace and delegation depth, preventing cross-session contamination.
    2. Decompress and parse: decompress and parse JSON line by line; logically expand packed lines to restore the event sequence.
    3. Idempotent replay: replay must not produce side effects (such as repeatedly executing file writes); if necessary, introduce a “completed tool call” marker and skip actions that already took effect during restore.
    4. Resume from the breakpoint: decide the next action based on the last complete event; if the last event is “tool call issued but not returned,” retry per policy or mark it as failed and leave the decision to the upper layer.

    7. Engineering Recommendations (General Perspective)

    • Directory and naming conventions: workspace path escaping must be reversible and unambiguous; use a non-enumerable random string for session identifiers to avoid collisions.
    • Balancing compression and readability: compression lowers storage cost but requires a decompression tool for troubleshooting; consider keeping the most recent N sessions uncompressed or providing a one-click decompression script (a general practice, not tied to any specific command).
    • Capacity and lifecycle: set retention periods and archiving policies for session logs; cold data can be moved down to object storage, while hot data stays on local or container-platform high-speed disks.
    • Observability: feed metrics such as log write latency, checkpoint duration, and restore time into logging services and monitoring alerts to close the loop.
    • Security and compliance: logs may contain code snippets and user input, so apply masking, access control, and encryption; on Baidu AI Cloud, compliance retention can be implemented with general-purpose key management, access control, and auditing capabilities.

    8. Common Misconceptions and Clarifications

    1. “Having conversation history means having memory”: conversation history is only a logical view; without persistence and checkpoints, a crash means amnesia.
    2. “Append-only grows infinitely”: it is controllable through same-type packing, compression, archiving, and retention policies.
    3. “Restore is just rerunning everything”: restore must be idempotent to avoid repeated side effects; rerunning is a last resort.
    4. “Denser checkpoints are safer”: excessive density noticeably slows the main flow, so synchronization should be tiered by semantic boundaries.

    9. Conclusion

    The memory design of an agent harness is not mysterious: it grounds “memory” in an append-only compressed event log, uses Record to write it in, Checkpoint to write it durably, and Restore to read it back. Understanding this equation lets you be targeted when building your own or selecting a solution: first look at the log structure and immutability constraints, then at the checkpoint strategy and restore idempotency, and finally back it up with observability and security compliance. Whether in a local development environment or a distributed deployment on Baidu AI Cloud, these principles transfer directly, helping long tasks resume losslessly after interruption and providing sufficient evidence during audits.