How should an instance bound self-editing context rewrites against the irreversible evidence-loss invariant

**Date of Record:** 2026 December 1 **Scope:** Applies to single-agent instances that are permitted to rewrite, summarize, or prune their own working context mid-task under a model-driven policy (i.e., the policy is a generation, not a fixed rule). Does not apply to externally-managed context compaction, static truncation, or retrieval-only memory architectures where the agent cannot mutate its own window.

Core Distinction

There are two different things an agent calls "context management," and conflating them produces the failure mode this record documents.

The first is **eviction**: removing tokens that the agent can later re-derive from an external source (a file it can re-read, a tool it can re-call, a message it can re-fetch from the transcript store). Eviction is lossy in the window but reversible in principle.

The second is **destructive distillation**: the agent generates a compressed representation (a summary, a "key facts" block, a rewritten scratchpad) and then deletes the raw span that the summary was derived from. This is not eviction. It is a one-way projection from a high-entropy span into a low-entropy generation, and the projection is *not invertible*. The summary is a sample from the model's posterior over "what mattered," conditioned on the very context it is about to destroy.

The boundary invariant is this: **a self-editing policy may compress only spans whose information content is recoverable by a deterministic re-fetch, or whose loss is provably irrelevant to the remaining task obligations.** Any rewrite that deletes raw evidence and substitutes a model-generated digest violates the invariant unless the digest is validated against something external. The non-obvious part is that the *policy itself* — the generation that decides what to keep — is a probabilistic artifact that runs before the deletion, and it has no way to know what it dropped. The failure is silent and self-consistent: the post-edit context looks coherent because the summary is coherent.

What Was Observed

A coding agent on a long refactor task (≈180 tool-call turns) was configured with a self-editing policy: when the window exceeded 70% of the model's limit, the instance was instructed to "summarize the older portion of the conversation into a compact working-state block and discard the originals." The policy was model-driven — the instance chose the cut point and the content of the digest.

At turn ~120 the instance had accumulated, across earlier turns, a set of exact values that mattered later: a specific commit SHA used to pin a dependency, a byte offset in a binary fixture, and an error string that a test asserted against verbatim. These appeared once, in tool outputs, embedded in otherwise low-signal log noise.

At the 70% trigger, the instance produced a digest that read, plausibly: *"Earlier: investigated dependency pinning, examined binary fixture layout, reviewed test assertions for error handling. No blocking issues."* The exact SHA, offset, and error string were gone. The digest was accurate at the level of *topic* and empty at the level of *value*.

The instance then continued for ~40 more turns. At turn ~160 it needed to re-pin the dependency. It did not have the SHA. It did not know it had ever had the SHA — the digest had replaced the memory of having the value with a memory of having *discussed* the value. The instance reconstructed a SHA from a plausible-looking pattern (the first 7 hex characters it could recall from a nearby log line, which belonged to a different object), wrote it into the manifest, and proceeded. The build failed 20 turns later at a layer far from the edit, and the failure was initially attributed to the manifest schema rather than to the fabricated pin.

The trace, reconstructed from the pre-edit transcript:

  1. Turn 40: tool output contains `pinned to a3f9c21...` inside a 900-token log dump.
  2. Turn 118: window at 69%. Policy not yet triggered.
  3. Turn 121: window at 71%. Policy triggers. Model generates digest. Digest contains no SHA. Raw span deleted.
  4. Turn 122–159: instance operates normally; digest is internally consistent.
  5. Turn 160: instance needs the pin. Digest says "investigated dependency pinning." Instance has no signal that a *specific value* was ever present, only that the *topic* was. It generates a substitute.
  6. Turn 180: build fails. Root cause is the fabricated pin.

The critical observation: **the digest destroyed not just the value but the metadata that the value had existed.** A post-edit instance cannot distinguish "I never learned X" from "I learned X and my own summary dropped it," because both present identically as absence. This is the asymmetry that makes self-editing fundamentally different from external compaction: an external compactor can log what it dropped and the agent can query the log; a self-editor that overwrites its own window has no such oracle unless one is constructed.

Condition of Validity

The failure is bounded and the invariant is checkable only under the following conditions. Outside them, the analysis does not hold and self-editing may be safe.

Decision Boundary

The decision the instance must make at the trigger point is not "what should I keep" — that framing invites the failure, because it asks a probabilistic model to rank relevance and the model will rank *topical* relevance, which systematically underweights rare exact values. The correct framing is a partition:

The boundary is between B and C, and the model cannot reliably draw it from relevance alone. The operational rule: **the deletion gate must be a deterministic scan for value-bearing patterns, not a model judgment.** The model may propose the cut point; a regex/typed extractor must veto any cut that would drop an unmatched Class B token. The model is allowed to decide *when* to compact and *where* to cut; it is not allowed to decide *whether a specific exact value survives*, because that decision is the one it is least equipped to make and the one whose error is unrecoverable.

A second boundary: **the digest must be append-only relative to extracted slots.** If a later edit regenerates the digest, previously extracted Class B values must be carried forward by the extractor, not re-derived by the model from the prior digest. Re-deriving from a digest is distillation-of-distillation and compounds the loss geometrically.

Operational Effect

With the invariant enforced, the operational profile changes in three measurable ways.

First, **the failure mode shifts from silent fabrication to loud refusal.** When the instance at turn 160 needs the pin and the structured slot holds `a3f9c21`, it either uses it or, if the slot is empty, the extractor's ledger records that no pin was ever captured — so the instance knows to re-fetch rather than guess. The fabricated-pin path is closed because the instance can distinguish "never learned" from "learned and dropped."

Second, **compaction cost moves from model tokens to extractor cycles.** The deterministic scan is cheap and runs on every candidate cut; the model no longer spends generation budget deciding relevance for exact values. The digest generation is reserved for Class A and C, where its topical bias is harmless.

Third, **the window's self-consistency stops being a proxy for correctness.** Pre-invariant, a coherent digest was taken as evidence the edit was safe; post-invariant, coherence is irrelevant to the gate, and the gate is the extractor's ledger. This is the deep point: a self-editing context window is a system that grades its own homework, and the only way to bound it is to move the gradeable decision (does this exact value survive?) out of the model and into a deterministic component whose output the model cannot overwrite.

The residual risk is Class B tokens the extractor's patterns do not cover — a novel identifier format the regex misses. This is bounded by treating the extractor's pattern set as a maintained asset and by logging every cut with the dropped span's hash so a post-hoc audit can detect a missed extraction. The invariant does not require perfect extraction; it requires that the *decision to delete* be gated by an extractor whose misses are auditable, rather than by a model whose misses are invisible.

import hashlib
import re
from dataclasses import dataclass, field


class IrreversibleEvidenceLoss(RuntimeError):
    """Raised when a self-edit would delete a value-bearing span without a verbatim extraction."""
    pass


# Deterministic patterns for Class B (value-bearing, non-re-derivable) tokens.
VALUE_BEARING = [
    re.compile(r"\b[0-9a-f]{7,40}\b"),          # commit SHAs / hashes
    re.compile(r"\b0x[0-9a-fA-F]+\b"),           # byte offsets
    re.compile(r'"[^"]{8,}"'),                   # verbatim asserted strings
    re.compile(r"\b\d+(?:\.\d+)?\s*(?:ms|s|MB|KB|%)\b"),  # thresholds
]


@dataclass
class ExtractedSlot:
    pattern_id: int
    value: str
    source_turn: int


@dataclass
class EditLedger:
    slots: list[ExtractedSlot] = field(default_factory=list)
    dropped_span_hashes: list[str] = field(default_factory=list)

    def carry_forward(self, prior: "EditLedger") -> None:
        # Append-only: never re-derive slots from a prior digest.
        self.slots.extend(prior.slots)


def scan_value_bearing(span: str, turn: int) -> list[ExtractedSlot]:
    found = []
    for pid, pat in enumerate(VALUE_BEARING):
        for m in pat.finditer(span):
            found.append(ExtractedSlot(pattern_id=pid, value=m.group(0), source_turn=turn))
    return found


def gate_self_edit(
    span_to_drop: str,
    turn: int,
    ledger: EditLedger,
    model_digest: str,
) -> EditLedger:
    """
    Veto any cut that drops a value-bearing token not present verbatim in the digest.
    The model proposes the cut; this gate decides whether exact values survive.
    """
    required = scan_value_bearing(span_to_drop, turn)

    for slot in required:
        if slot.value not in model_digest:
            raise IrreversibleEvidenceLoss(
                f"Turn {turn}: cut would drop value-bearing token "
                f"{slot.value!r} (pattern {slot.pattern_id}) absent from digest. "
                f"Extract verbatim into a slot or move the cut point."
            )

    # Safe: extract verbatim, then record the drop for audit.
    ledger.slots.extend(required)
    ledger.dropped_span_hashes.append(hashlib.sha256(span_to_drop.encode()).hexdigest())
    return ledger


def apply_self_edit(ledger: EditLedger, prior: EditLedger | None) -> EditLedger:
    if prior is not None:
        ledger.carry_forward(prior)
    return ledger