Agent Session State Management: An Event Sourcing Architecture Explained

    This article explains why AI agents appear to "forget" earlier instructions and why different views of the same session can diverge. Using the public session log design of an AI coding tool as a reference, it abstracts a general-purpose approach to session state management: modeling a session as an append-only event stream backed by a single source of truth with multiple projected views. It covers the root causes of memory loss and view divergence, the core design including the "model-visible means logged" invariant, the engineering considerations for storage, compaction, ordering, permissions, and versioning, and the benefits for reproducibility, observability, and auditing.

    1. Introduction: Why a “Poor Memory” Is Usually Not the Model’s Fault

    When working with AI coding tools or multi-turn conversational agents, developers frequently run into a familiar pattern: a constraint confirmed in the previous turn is ignored in the next one, or the agent becomes vague when asked to follow up on a tool call that already returned a result. Intuitively, this gets blamed on weak model capability. From an engineering standpoint, however, the conclusion is often the opposite: the model in most agent frameworks holds no memory of its own. What it sees each turn is only a context fragment projected on the fly from an underlying body of event data. Once that fragment is compacted, replaced, or pushed out of the window, the model naturally can no longer “see” the earlier information.

    This article uses the publicly documented session log design of an AI coding tool as reference material and abstracts a general approach to session state management: model the session as an append-only event stream, and use a single source of truth plus multiple projected views to resolve both memory loss and inconsistency across views.

    2. Problem Analysis: How Memory Gets Lost and Views Diverge

    2.1 Mutable-Array Context: Silent Dropping Is the Root Cause

    A common simplified implementation in the industry stuffs the entire session into a fixed-capacity mutable array and uses it directly as the model context. Short conversations are fine, but in long tasks and multi-turn tool-calling scenarios, once the array fills up, older content is silently pushed out: no exception, no warning, and the history simply disappears. The model is not “forgetting”; rather, the single carrier of truth it depends on has itself changed irreversibly.

    2.2 Multiple Stored Copies Lead to View Divergence

    The second type of problem appears in implementations where the same session is stored separately in several places: model context, UI rendering data, and debug replay data are each maintained on their own. Any compaction, summarization, or field change may update only one of them, so the UI shows success while the model never saw it, or the debug record does not match the actual execution order. The root cause is the absence of a single source of truth.

    3. Core Design: The Append-Only Event Stream as the Only Truth

    3.1 A Session Is a Sequence of Events

    Abstract turns, steps, user messages, tool calls, tool results, and so on uniformly as events, where each event contains at least a type, a monotonically increasing sequence number, and a payload. Append-only means history is never modified or deleted; corrections can only be expressed by appending new events. A sketch of the structure:

    1. SessionLog:
    2. seq=1 type=user_message payload={text}
    3. seq=2 type=turn_started payload={turn_id}
    4. seq=3 type=step_started payload={step_id}
    5. seq=4 type=tool_call payload={name,args}
    6. seq=5 type=tool_result payload={status,output}
    7. seq=6 type=step_finished payload={usage}
    8. seq=7 type=turn_finished payload={turn_id}

    3.2 The Model Sees a Projection, Not the Store

    Before each turn’s request, a derivation step (such as deriveMessages) runs and maps the event stream to the message list visible for that turn according to explicit rules: which events are visible, how history is folded, how tool results are injected, and how reference positions are annotated are all determined by the projection rules. The model holds no state, which yields two direct benefits: state can be reconstructed, and behavior can be reproduced.

    3.3 The Hard Invariant: Model-Visible Means Logged

    The key constraint of the whole design is model-visible means logged: anything the model can see must already be written to the log. When a new kind of visible input is needed, the correct approach is to add a new event type and render it in the projection layer, not to quietly splice in a prompt through a side channel. This invariant makes “what the model saw” an auditable fact.

    4. Why This Solves Both Problems at Once

    Memory loss is turned into a configurable question of whether the projection rules cover the required events; history never physically disappears. Inconsistency across views is eliminated because the UI, debugging, replay, and model context are all different projections of the same log and are therefore consistent by construction. Observability improves as well: diagnosing an anomaly only requires replaying the event sequence by sequence number.

    5. Engineering Implementation Notes

    • Storage: use a log service or object storage to handle append writes, paired with a message queue for event distribution.
    • Compaction: compact by appending summary events rather than overwriting the original text, preserving traceability.
    • Concurrency and ordering: order by monotonic sequence numbers and make writes idempotent to avoid duplicate events.
    • Permissions and redaction: perform sensitive-data trimming uniformly in the projection layer to avoid divergent implementations in multiple places.
    • Evolution and compatibility: version the event payloads, and let the projection layer handle backward compatibility.

    6. Conclusion

    Treating a session as an append-only event stream and exposing capabilities through a single source of truth plus multiple projected views is a rigorous paradigm for agent state management. It depends on no particular product, yet it keeps memory from being silently lost and views from contradicting each other, while leaving clear boundaries for replay, auditing, and capability extension.