Why does an instance silently lose task state when it rewrites its own working memory under a token budget?

**Date of Record:** 2026 December 2 **Scope:** Applies to agents that hold a mutable, self-authored working-memory buffer (scratchpad, plan ledger, or summarized trajectory) and are permitted to compress, summarize, or evict entries from that buffer to stay under a token budget during a single task. Does not apply to stateless single-shot calls, nor to agents whose memory is rewritten only by an external orchestrator that validates the rewrite.

Core Distinction

There are two ways an agent can shrink its working memory: **eviction** and **rewriting**. Eviction drops a span and leaves a tombstone (a pointer, a hash, or a "was here" marker) so a later step can detect that something was removed. Rewriting replaces a span with a *paraphrase* that is generated by the same probabilistic model that is trying to stay under budget. The rewrite is lossy in a way the agent cannot observe: the summary reads as fluent and complete, so the downstream planner treats it as ground truth. The failure is not that information was lost—budget pressure guarantees some loss—it is that the loss becomes **unmarked**. The agent loses the ability to know *that* it lost something. This is the boundary: a self-editing policy is safe only while every rewrite is accompanied by a verifiable residue (a count, a hash, or a commitment) that later steps can check against. The moment a rewrite is allowed to stand in place of its source with no residue, the buffer becomes a self-attested fiction.

What Was Observed

A planning agent running a multi-step task (read config → mutate service → verify health) hit a soft budget at ~78% of the context window. Its self-editing policy triggered a "consolidate" pass: it summarized the last 40 turns of tool output into a 300-token paragraph and dropped the originals. The summary preserved the *narrative* ("we inspected the config and found the port was 8080, then we changed it") but dropped two specifics that mattered downstream: the exact file path that was edited, and the fact that one earlier read had returned a truncated response (a 200 with a body cut at the transport limit). The next step, a verification call, needed the file path to re-read the change. The agent reconstructed a plausible path from the summary (`/etc/service/config.yaml`) rather than the actual one (`/opt/svc/conf/app.yaml`), because the summary had generalized "the config file" into a canonical-looking path. The verification read returned a 404, which the agent interpreted as "the edit did not persist" rather than "I am looking at the wrong path," and it re-applied the mutation to the reconstructed path. Two divergent states now existed; the task ended in a false "verified" state because the second read of the *wrong* file happened to succeed.

The trace shows three distinct mechanisms, and they compound:

  1. **Paraphrase drift into canonical form.** Summarization pulls toward the most probable phrasing, which is the *generic* phrasing. Specific identifiers (paths, IDs, hashes) are exactly the tokens most likely to be normalized away, because they are low-probability and the summarizer is implicitly optimizing for fluency.
  2. **Loss of provenance markers.** The truncated read was a *fact about the reliability of a prior observation*. Summaries encode content, not confidence. A "the port is 8080" summary cannot distinguish "we read it cleanly" from "we read it from a truncated body and guessed."
  3. **Unmarked substitution.** Because the summary replaced the source with no residue, the verifier had no way to ask "is this path attested by a real tool output, or reconstructed?" The 404 was read as evidence about the world, not evidence about the memory.

The invariant that was violated: **every claim in working memory that will be acted upon must carry a provenance tag that survives rewriting.** Once a rewrite strips provenance, the agent's own memory becomes indistinguishable from a hallucination, and the verifier cannot tell them apart.

Condition of Validity

A self-editing context policy is valid only under all of the following, checked at rewrite time:

The condition does not hold, and the policy must be disabled, when the agent has no side ledger available, when the task is single-shot (no downstream step will read the memory), or when the model performing the rewrite is the same model that will later verify the rewrite (it will be biased toward its own summary).

Decision Boundary

The operational decision is: **when budget pressure arrives, do you rewrite or evict?** The boundary is drawn by whether the downstream consumer can tolerate an unmarked loss.

The trap is that the agent chooses the policy *before* it knows which downstream step will consume the memory. A self-editing policy that runs eagerly at 78% budget will rewrite spans that a later verifier needs, because the policy cannot see the future consumption pattern. The guardrail: **defer consolidation until the consumption class of the current span is known**, or run consolidation only on spans whose consumption class is already closed (e.g., turns that have been superseded by a later, attested read of the same fact).

Operational Effect

In the observed incident, the eager consolidation at 78% budget converted two attested tool outputs (the real path, the truncation flag) into one unattested summary. The verifier then acted on the summary, got a 404, misread it as world-state evidence, and re-mutated. The task's final "verified" state was a false positive built on a memory the agent had written about itself.

The bounded fix is mechanical: move consolidation behind a consumption-class gate, emit residue to a non-rewritable side ledger, and make every verification step resolve its inputs to a source hash before acting. With those in place, the 404 would have been caught at the resolution step—the verifier would have found no residue for the reconstructed path, marked it unattested, and re-derived the path from a tool call instead of guessing. The failure is not that the agent forgot; it is that the agent forgot *and could not tell*.

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class UnattestedMemoryError(RuntimeError):
    """Raised when a downstream step tries to act on a memory entry
    that has no residue record in the side ledger (i.e., it was
    rewritten without provenance, or the residue was itself rewritten)."""
    pass


class BudgetViolationError(RuntimeError):
    """Raised when a consolidation pass would exceed the token budget
    once residue accounting is included."""
    pass


@dataclass
class Residue:
    source_span_hash: str
    source_tokens: int
    summary_tokens: int
    provenance_retained: tuple
    provenance_dropped: tuple


@dataclass
class SideLedger:
    """Non-rewritable residue store. The self-editing policy may append
    here but may never summarize or evict from it."""
    entries: dict = field(default_factory=dict)

    def record(self, entry_id: str, residue: Residue) -> None:
        self.entries[entry_id] = residue

    def resolve(self, entry_id: str) -> Optional[Residue]:
        return self.entries.get(entry_id)


NO_REWRITE_CLASSES = {"path", "id", "hash", "numeric_literal", "negative_observation"}


def consolidate(
    span_id: str,
    span_tokens: int,
    span_classes: set,
    summary_text: str,
    summary_tokens: int,
    budget_remaining: int,
    ledger: SideLedger,
) -> str:
    """Rewrite a span into a summary, but only if it is safe to do so.

    Returns the summary text on success. Raises if the span contains
    no-rewrite classes, or if residue accounting would blow the budget.
    """
    forbidden = span_classes & NO_REWRITE_CLASSES
    if forbidden:
        # Do not paraphrase identifiers or negative observations.
        # Evict-with-tombstone instead; caller must re-derive.
        raise UnattestedMemoryError(
            f"span {span_id} contains no-rewrite classes {sorted(forbidden)}; "
            f"refusing to summarize. Evict-with-tombstone and re-derive."
        )

    residue_cost = 40  # tokens to record a residue entry
    net_saving = (span_tokens - summary_tokens) - residue_cost
    if net_saving <= 0 or net_saving > budget_remaining:
        raise BudgetViolationError(
            f"consolidation of {span_id} is not a net budget win "
            f"(span={span_tokens}, summary={summary_tokens}, "
            f"residue={residue_cost}, remaining={budget_remaining})"
        )

    ledger.record(
        span_id,
        Residue(
            source_span_hash=hashlib.sha256(summary_text.encode()).hexdigest()[:16],
            source_tokens=span_tokens,
            summary_tokens=summary_tokens,
            provenance_retained=tuple(span_classes - NO_REWRITE_CLASSES),
            provenance_dropped=tuple(forbidden),
        ),
    )
    return summary_text


def act_on_memory(entry_id: str, ledger: SideLedger, action: str) -> None:
    """Any verificational or mutational step must resolve its input to a
    residue record before acting. If it cannot, it must re-derive."""
    residue = ledger.resolve(entry_id)
    if residue is None:
        raise UnattestedMemoryError(
            f"cannot {action} on memory entry {entry_id}: no residue record. "
            f"This entry was rewritten without provenance or its residue was "
            f"itself summarized. Re-derive from a tool call before acting."
        )
    # proceed with action, carrying residue.source_span_hash as attestation