Session Memory for Coding Agents: Design Principles for Recoverable, Auditable Event Logs
This article explains how session memory for a coding agent can be designed as an append-only event log combined with checkpoints and recovery. It covers the log file layout, JSONL event streams, immutable session headers, append-only semantics, checkpoint timing, recovery steps, and the trade-offs involved. The goal is to show how an agent can resume work after a crash and provide an auditable record of what it actually did.
Starting from an “Amnesia” Scenario
An AI coding agent is modifying a large codebase. It has already rewritten three files and is about to update an interface in the fourth file. Then the process exits unexpectedly. After a restart, does the agent still know where it was?
Without persistent memory, the answer is no. It cannot answer “where did I just make changes?” When the user says across multiple turns, “change that function again,” it does not know which function from which earlier change is meant. When an anomaly needs investigation, there is also no way to know which operations the agent actually performed. The root cause is that the agent’s “context” is only temporary state in process memory. Once the process disappears, the context disappears with it.
Therefore, an agent execution framework should not merely “save the conversation.” It should turn the entire work process into a recoverable, auditable event stream. This is the starting point for session memory design.
Memory Is a Replayable Log, Not a Black Box
In terms of implementation, an agent’s memory does not need to be a mysterious black box. It can be a concrete physical file. Each session corresponds to a session log file on disk. The log uses JSONL format, meaning one JSON event per line. To save disk space, the file can be stored using a general-purpose compression algorithm. After decompression, it is a chronological event stream.
A typical design equation can be summarized as:
Memory = append-only ledger + recording mechanism + checkpoint mechanism + recovery mechanism
- Recording: events are appended to the log one by one.
- Checkpointing: at critical points, data is forced to disk to prevent confirmed events from being lost if the process crashes.
- Recovery: reload the log, replay events, rebuild conversation history and working state, and then continue from the previous turn.
These three mechanisms form a closed loop. Once this loop is understood, it becomes clear why an agent can “remember.”
One Session, One Log File
In actual operation, after each task ends, a recognizable log file is formed outside the workspace. The directory structure usually consists of a session root directory, a directory name derived from the escaped workspace path, a session ID, and the log filename.
For example:
sessions/--home-user-project-workspace--/task-20250601-001/session.jsonl
This structure has several design implications:
- Session root directory: centrally manages all session logs.
- Escaped workspace path: avoids name conflicts between different workspaces. File system paths may contain slashes and other special characters, and inserting them directly into a directory name would break the hierarchy. Separators in the path therefore need to be converted into safe characters. This allows logs to be isolated by workspace when the same agent instance handles multiple workspaces.
- Session ID: distinguishes multiple tasks under the same workspace.
- Log file: the actual persistence carrier. When read, it can be decompressed to obtain plain-text JSONL.
After decompressing the file, the first line is usually the session header. The session header records identity information for the session, such as session ID, creation time, workspace path, and delegation depth. “Delegation depth” represents the parent-child relationship between sessions: a top-level session has depth 0, and when the agent creates a subtask or sub-agent session, the depth increases. In this way, even when multiple groups of sessions run in parallel, the call chain can be reconstructed from the logs.
Once the session header is written, it never changes. The identity of a session is fixed from the first line onward. After that, only events are appended; nothing is rewritten.
Append-Only: Why History Cannot Be Changed
“Append-only” is the most important semantic property of this log, and it is an important difference from ordinary configuration files and database records. This can be understood on three levels.
First, events that have been written are never rewritten. Events are appended in continuous sequence numbers, and no previous event is modified or deleted. This is not an implementation shortcut but a deliberate design: the log is the single source of truth. If history could be modified, it would amount to falsifying memory. When users investigate a problem, they would no longer see the real process but a “story” that may have been revised.
Second, the event stream is naturally replayable. As long as the log exists, all events can be replayed in order to restore the agent’s complete context at a given point in time. This is similar to event sourcing: instead of saving a final snapshot of in-memory state, all events that cause state changes are saved, and state equals the cumulative result of the event stream.
Third, error correction also follows the append-only principle. If an error is discovered after a certain event, the system should not go back and modify the old record. Instead, it should append a new event describing the correction. This preserves the original process while recording later judgment, ensuring that the audit trail remains complete.
Of course, append-only does not necessarily mean that one event always corresponds to one line. In some scenarios, multiple consecutive events of the same type may be packaged by the backend into a single record block. For example, during streaming model output, a reply is split into many small fragments. If every fragment were written as a separate line, it would create a large amount of redundancy. A better approach is to merge consecutive small fragments into one record block, preserving their original order within the block, and then split them logically into events when reading. This maintains append-only semantics while reducing storage overhead.
Checkpoints: Pinning “Memory” to Disk
An append-only log solves the problem of “content cannot be tampered with,” but it does not by itself solve the question of whether data has actually reached disk. When an application writes a file, data often enters the operating system’s page cache first. If the process crashes, the kernel may not yet have flushed the data to disk, and the last few seconds of logs may be lost. More seriously, if the agent crashes immediately after completing an important tool call, what is lost is not just one line of log but the context needed for the entire subsequent recovery.
The checkpoint mechanism is designed for this. It does not force a flush after every event, because that would create excessive disk I/O overhead. Nor can it go for long periods without flushing, because the crash-loss window would then be too large. A checkpoint policy module is responsible for balancing reliability and performance.
A reasonable checkpoint policy focuses on “critical points,” such as:
- When a session is just created and the session header is written.
- After a user message arrives and is confirmed as received.
- Before the agent starts calling an external tool, or after the tool returns a result.
- When the agent completes a full reasoning step and is about to return control.
- When an exit signal is received and graceful shutdown is performed.
When a checkpoint occurs, the system ensures that currently confirmed events are persisted to disk and records a recoverable position. During later recovery, the system can continue from this position or fully replay from the beginning of the log. Because the log itself is append-only, a checkpoint does not change existing content. It only makes the tail that has been written but not yet flushed to disk safer.
Recovery: Rebuilding Context from the Event Stream
After a crash, the recovery process is the ultimate test of the memory design. Its basic path is:
- Locate the corresponding log file by session ID.
- Read the compressed file and decompress it into text.
- Parse events line by line and verify that the session header and event sequence numbers are continuous.
- Replay events in order to rebuild conversation history such as user messages, assistant replies, and tool call results.
- Restore the rebuilt state to working memory so that the agent can continue subsequent turns.
Recovery can succeed only if the order and content of events in the log have not been corrupted. Therefore, if there is an incomplete record at the end of the log, a robust implementation should be able to identify and discard the incomplete tail rather than failing the entire recovery process. In this way, a “crash” means losing only the last small segment of unconfirmed content, not the entire session.
Recovery is also useful for audit scenarios. Even if the task is not continued, decompressing the log file shows what the agent did: which messages it received, which replies it generated, which tools it called, and what the results were. This capability is valuable for investigating abnormal behavior and verifying agent decisions.
Design Trade-offs and Best Practices
The approach of “append-only log + checkpoint + recovery” is not the only option, but it is particularly suitable for workloads such as AI coding agents that need to run for long periods and be traceable and recoverable. It has several clear advantages:
- Crash resistance: even if the process terminates unexpectedly, events that have reached disk remain reliable, and work can continue after recovery.
- Traceability: the log provides the real sequence of actions and does not “forget” because in-memory state was lost.
- Simple implementation: JSONL is an extremely simple format. Append writes, sequential reads, and one event per line require almost no additional database.
- Compressibility: text logs can be processed with compression algorithms, significantly reducing long-term storage costs.
The cost is that the log keeps growing. Frequent small events consume space, reading requires decompressing the entire file, and replaying a large number of events may introduce startup latency. These limitations can be mitigated by packaging consecutive events of the same type, setting reasonable checkpoints, and archiving old sessions, but they do not change the core design principle: memory is not a state snapshot but a replayable event ledger.
For developers, understanding this design principle means that when adding memory capabilities to an intelligent agent, it is not necessary to start with a complex database or knowledge base. The starting point should be “how to record the process reliably.” Only when the process is recorded well can the agent recover from crashes and become trustworthy in the future.
