Why Long-Running Agents Forget: Context Governance with an Append-Only Event Log

    Long-running agents often appear to “forget” because the model only sees the context attached to the current request. This article explains why message arrays lose or diverge from session facts, and how an append-only event log with derived views can keep model input, UI state, debugging data, and task recovery consistent.

    In multi-turn conversations, tool calls, and automated tasks, “the model suddenly forgot” is a common failure. A user may have just confirmed a critical parameter, yet the next turn behaves as if that information never existed. The steps shown in the interface may not match what the model actually saw. After a task is resumed mid-way, tool results, user intent, and current progress can also fall out of alignment.

    It is easy to blame model capability and assume context understanding is unstable. From a system-architecture perspective, the failure usually happens earlier. The model does not store memory across turns. It can only read the context carried by the current request. If a piece of information is not placed back into this turn’s input, the model cannot know that it ever appeared.

    The real problem is therefore not “how to make the model remember more.” It is how to store session facts reliably and produce a consistent context view for different consumers. A more robust engineering approach is to treat the session as an append-only event log, and to treat model input, interface state, debug information, and task-recovery data as different projections of that log.

    1. Why Traditional Context Management Loses Information

    The simplest agent frameworks usually maintain a message array:

    1. [
    2. user message,
    3. model reply,
    4. tool call,
    5. tool result,
    6. user message,
    7. model reply
    8. ]

    On each turn, the system sends the contents of that array to the model. For short conversations this is intuitive and cheap to build. As tasks run longer, the array runs into three problems.

    1. Context length is limited

    Every model has an upper bound on how much input it can process. As user messages, model replies, tool arguments, and tool outputs accumulate, the system must trim, summarize, or replace history.

    Common tactics include:

    • Dropping the earliest messages
    • Keeping only the most recent turns
    • Compressing history into a summary
    • Replacing the original interaction with a new state description
    • Keeping tool results but not the reason the tool was called

    These methods control input size, but they can change the semantic structure of the information. If the tool result is kept and the reason for the call is deleted, the model may not know which task goal the result belongs to. A summary alone can drop original parameters, error details, and explicit user rejections.

    2. Trimming can be irreversible

    If historical messages are simply removed from the array, the system usually has no reliable way to restore them. When something important turns out to have been deleted, it is hard to answer:

    • Which item was removed, and when?
    • What was the full context before deletion?
    • Did a length limit trigger the trim, or did summarization overwrite the original text?
    • Does the content the model sees match what the interface displays?

    Without the original record, the system can only guess from the current state. For complex tasks, that makes diagnosis very difficult.

    3. Multiple copies of state diverge

    A real system rarely has a single copy of session data. The model-call module has a message list, the frontend has display state, the scheduler has execution state, and the logging system has debug records.

    If those copies are updated separately, you can get situations such as:

    • The model has seen a tool result that the interface never showed
    • The interface says the task is complete while the scheduler is still running
    • Recovery uses an outdated message list
    • Debug logs recorded the call path but cannot regenerate the model input

    This is not merely a bug in one module. The system lacks a single source of facts.

    2. Core Idea: Treat the Session as an Event Stream

    The basic idea of an event log is that a session is no longer a message array that is edited in place. It is a sequence of events that only grows, in order.

    Each event should at least include:

    1. {
    2. "id": "unique event id",
    3. "sequence": 42,
    4. "type": "tool_result",
    5. "timestamp": "when it occurred",
    6. "payload": {},
    7. "metadata": {}
    8. }

    In that record:

    • id uniquely identifies the event
    • sequence is the event’s order in the session
    • type is the event category
    • timestamp supports audit and timeline display
    • payload holds the event’s own data
    • metadata can record source, related task, retry count, and similar auxiliary fields

    Event types should not be limited to “user message” and “model reply.” They can also include:

    • Session start and end
    • Start of a turn
    • Start and completion of a task step
    • Tool-call request
    • Tool execution result
    • Tool errors and retries
    • User confirmation, rejection, or revision
    • State changes
    • System-generated summaries
    • Permission or policy decisions
    • Human intervention records

    A session event log is not the same as ordinary runtime logging. Runtime logs mainly help diagnose program problems. Session events are part of the business facts. They should support state recovery, context reconstruction, and process replay.

    3. What the Model Sees Is Only a Projection of the Log

    The event log stores facts, but the model does not need to read every raw event. The system should build this turn’s input from the event stream according to the current task, the context budget, and safety policy.

    That process can be abstracted as:

    1. full event stream
    2. ↓
    3. select relevant events
    4. ↓
    5. rebuild task state
    6. ↓
    7. add necessary summaries
    8. ↓
    9. organize into a message structure
    10. ↓
    11. send to the model

    The key concept is projection. The log is the storage layer. The message list is a view for the model. The two must not be conflated.

    For example, one tool call in the log may include full request parameters, a permission decision, the raw return value, the retry path, and an exception stack. The model input may only need:

    1. Tool call: query a data set
    2. Result: query succeeded and returned several records

    The interface may show a more readable timeline. The debug module may keep the full request and response. All of those views come from the same events, but they are rendered differently.

    In pseudocode:

    1. def derive_messages(events, policy):
    2. state = rebuild_state(events)
    3. selected = select_relevant_events(
    4. events=events,
    5. state=state,
    6. budget=policy.context_budget
    7. )
    8. summary = build_summary(
    9. events=events,
    10. state=state,
    11. selected=selected
    12. )
    13. return render_messages(
    14. system_context=policy.system_context,
    15. summary=summary,
    16. events=selected
    17. )

    This process does not require sending every event to the model every time. It does require that any important fact the model sees can be traced to a source in the log.

    4. Invariants the System Must Hold

    An event-driven session system cannot stay stable on convention alone. Several invariants should be explicit and non-negotiable.

    1. Visible content must be traceable

    Every non-static segment the model sees should be traceable to an event, a group of events, or a clearly recorded summary event.

    The system should not assemble unrecorded text immediately before the model call. If something goes wrong, developers then cannot tell where that text came from.

    2. Facts are appended, not silently overwritten

    If the user changes an earlier setting, do not edit the old event. Append a new correction event. For example:

    1. User confirmed: output format is a table
    2. User revised: change to a structured data format

    That preserves history and still lets state reconstruction compute the currently effective configuration.

    3. Order must be stable

    Event order directly affects task state. With concurrent tool calls, asynchronous callbacks, and retries, arrival time alone is not a reliable business order.

    It is useful to keep, together:

    • A global sequence number
    • A task or step sequence number
    • A correlation identifier
    • A parent-event or predecessor-event identifier

    Those fields distinguish “which event was produced first” from “which event happened first in the business process.”

    4. Replay should be as deterministic as possible

    Given the same event log and the same version of the projection rules, the system should produce the same state and message view as far as possible. If projection logic frequently depends on the current time, externally mutable data, or implicit global variables, the same session can recover to different results at different times.

    5. How to Compress Context

    An append-only log does not mean the model reads the entire history on every turn. The hard part is compressing context without losing critical facts.

    One workable layered strategy is as follows.

    Layer 1: Keep recent raw events

    The latest few turns and the current step are usually the most relevant to the model’s next decision. Prefer raw content here so summarization does not lose meaning.

    Layer 2: Keep task state

    For older material, extract stable state, such as:

    • The goal the user finally confirmed
    • Steps already completed
    • Problems still open
    • Files or results already produced
    • Why a tool execution failed
    • Operations that must not be repeated
    • Approaches the user explicitly rejected

    State is not a casual chat summary. It is task facts organized into a structure.

    Layer 3: Keep retrievable history

    Older full events should remain in the log and be fetched on demand. Retrieval keys can include task id, step type, keywords, related resources, or an event time range.

    Summaries and original records must be kept distinct. A summary helps the model grasp context quickly, but it does not replace original facts. For critical parameters, user authorization, financial figures, configuration content, and error details, keep the original events so they can be checked.

    6. Consistency Design for Tool Calls

    Tool calls are where session state most often drifts. A complete tool interaction can be split into at least these events:

    1. step started
    2. tool call requested
    3. tool execution started
    4. tool execution succeeded or failed
    5. tool result recorded
    6. step finished

    If the tool succeeds but the result is never written to the event log, a restart may call it again. If the result is written but the model messages are not regenerated from the log, the model may believe the tool has not run.

    Tool calls should therefore have an idempotency identifier. From that identifier the system should be able to tell:

    • Whether the call has already been submitted
    • Whether a result already exists
    • Whether a retry is in progress
    • Whether another execution is allowed
    • Whether the model has already consumed the result

    For operations with side effects, “a request was generated” and “the operation was confirmed” must stay separate. A model’s expressed intent to call a tool is not evidence that the external operation has completed.

    7. Error Recovery and Task Restart

    Another value of the event log is recovery after failure.

    When a process exits abnormally, the system can recover by:

    1. Reading the session’s full event history
    2. Checking sequence continuity and event format
    3. Rebuilding the current task state
    4. Finding the last unfinished step
    5. Determining whether the tool operation already produced a result
    6. Regenerating the messages visible to the model
    7. Continuing from a safe recovery point

    Compared with saving a constantly overwritten “current state,” the event log keeps the process of change, so you can locate which step failed.

    Recovery must not simply “continue from the last event.” If the last event is a tool-call request, but the tool actually succeeded and only the result write failed, a blind retry can duplicate the operation. In that case, judgment should combine an external idempotency key, an operation query, or human confirmation.

    8. How the Interface, the Model, and Debugging Share Facts

    In the preferred architecture, different consumers do not keep independent copies of the facts. Each builds its own view from the same event stream.

    Model view

    Focuses on task-relevant information, the current goal, necessary history, and tool results. The priority is context efficiency.

    User-interface view

    Focuses on the timeline, execution progress, readability, and interaction. The priority is the display experience.

    Operations and debug view

    Focuses on full parameters, error stacks, latency, retries, and correlation ids. The priority is diagnosis.

    Audit view

    Focuses on who did what, and when. The priorities are completeness, non-repudiation, and access control.

    These views may differ, but they should not contradict each other. Deriving every view from the event log reduces the pattern of one state in the frontend, another in the backend, and a third inside the model.

    9. Security Issues in Implementation

    An event log usually contains user input, tool parameters, business data, and model output. Access control must be strict.

    Points that need explicit design include:

    • Redaction of sensitive fields
    • What each role is allowed to see
    • Different permissions for raw tool results and model summaries
    • Log encryption and lifecycle management
    • How deletion requests are handled
    • Whether events may be physically deleted
    • How audit records are retained
    • Preventing a log projection from leaking hidden information

    “Append-only” describes how facts are recorded logically. It does not mean every datum must be kept forever. Privacy and compliance requirements should be handled through mechanisms such as cryptographic deletion, key destruction, field isolation, or controlled archival—not by storing all history indefinitely with no controls.

    10. Conclusion: Store Facts, Not Just Messages

    Stability in long-running sessions does not come from stuffing longer text into the model. It comes from a reliable way to manage facts.

    A traditional message array mixes storage, display, and model input. Once something is trimmed or overwritten, it may be gone for good. An event-log design separates the record of facts from context views:

    • The event log records what happened
    • State reconstruction answers what stage the task is in
    • Context projection decides what the model sees this turn
    • The interface projection shows the process the user cares about
    • The debug projection reconstructs the path of a problem

    This approach does not remove context-length limits, and it does not give the model permanent memory. It does ensure that information which is temporarily left out of the model context is not destroyed by one compression or trim. When the model, the interface, or task recovery needs it, the system can regenerate the corresponding view from a single source of facts.

    For agent systems that must run for a long time, coordinate many tools, resume after interruption, and support reliable audit, an architecture of “persist events, generate views on demand” is usually a better first investment than simply stacking more context.