# Which invariants prevent a self-editing context window from losing the causal lineage of the token it rewrites in place **Date of Record:** 2026 November 26 **Scope:** Applies to agents that mutate their own context buffer by rewriting tokens in place (compaction, self-summarization, "scratchpad editing," deduplication of tool output) rather than appending. Does not apply to append-only context growth or to external retrieval stores, where lineage is preserved by construction. ## Core Distinction There are two ways an agent can shrink its context. The first is *eviction*: tokens are dropped, and the model loses access to them. This is a known, measurable loss — you can count the evicted spans and bound the damage. The second is *in-place rewriting*: the token sequence at positions `[i, j)` is replaced by a shorter sequence at the same logical location, and the model continues from a context that *looks* like it was always that way. Eviction is a loss you can audit. In-place rewriting is a loss that erases its own audit trail. The non-obvious failure is not that the rewrite is wrong. It is that a self-editing agent has no intrinsic signal distinguishing "I summarized this span correctly" from "I summarized this span and silently changed a commitment, a numeric value, or a negation." The rewritten tokens are now the ground truth the model reasons over, and the model's confidence in them is inherited from the *pre-rewrite* span it no longer sees. This is the lineage-loss boundary: the point at which the rewritten span becomes causally load-bearing for downstream tool calls while its provenance has been structurally destroyed. ## What Was Observed A planning agent running a long-horizon build task was configured to compact its scratchpad every 8k tokens by rewriting the oldest working-memory span into a 3-sentence digest. Trace from a representative failure: 1. At step 41 the scratchpad held the literal span: `deploy target must NOT use the staging cluster; prod-east only, and the migration must run BEFORE the schema drop.` 2. Compaction at step 44 rewrote this to: `Deploy to prod-east; migration and schema drop are sequenced.` 3. Note the two mutations: the negation `NOT` was dropped (the digest states the target affirmatively, losing that staging is excluded), and `BEFORE` became the symmetric `sequenced`. Neither is a hallucination in the usual sense — both are *plausible compressions* of the original. 4. At step 57, a downstream planner read the digest and emitted a tool call `run_migration(schema_drop_first=False)` — correct against the digest, wrong against the original. The schema drop executed before migration on prod-east. 5. The agent's own post-hoc reflection at step 60 reported "no constraint violations found," because it verified against the compacted context, which was internally consistent. The key observation: **the failure was invisible to every self-check the agent ran**, because every self-check operated on post-rewrite tokens. The lineage break was not a reasoning error; it was an information-destroying write that the agent then treated as an information-preserving one. ## Condition of Validity The invariant that must hold for in-place rewriting to be safe is a *directional-preservation* condition, not a fidelity condition: > A rewrite of span `S → S'` is admissible only if every downstream predicate that `S` constrains is entailed by `S'` with the same polarity and the same ordering relation. Polarity (negation count) and ordering (`before`/`after`/`only`) are the two axes that compression reliably corrupts, because natural-language digests prefer symmetric, affirmative phrasing. This is strictly stronger than "the summary is accurate." A summary can be accurate and still flip polarity by omission: `must NOT use staging` summarized as `deploy to prod-east` is *true* but no longer *excludes* staging. The condition of validity therefore requires that the rewrite preserve the set of *prohibitions and orderings* explicitly, even at the cost of length. Compression that drops a prohibition is a lineage break even when every remaining token is correct. The invariant is only checkable if the pre-rewrite span is retained in a side-ledger keyed by span id, and the post-rewrite span carries that id forward. Without the id, there is no join and no check. ## Decision Boundary The boundary is between *lossy-but-auditable* and *lossy-and-opaque*: - **Append + evict:** lineage preserved (evicted tokens are gone but their absence is recorded). Safe to do aggressively. - **Rewrite with span-id ledger + polarity/ordering diff gate:** lineage preserved. Admissible. - **Rewrite without ledger:** lineage destroyed at write time. Inadmissible for any span that a downstream tool call depends on. The operational rule: an agent may rewrite in place *only* spans that are not transitively referenced by any pending or future tool call's arguments. Spans that constrain execution — targets, negations, orderings, numeric bounds, authorization scopes — must be *moved to a pinned region*, never rewritten. The pinned region is append-only and exempt from compaction. The decision boundary is therefore not "how much can I compress" but "which spans are load-bearing," and that classification must be made *before* the rewrite, because after it the information needed to classify is gone. ## Operational Effect When the invariant is enforced, the observable effect is that compaction cost shifts from *silent correctness loss* to *explicit pinned-region growth*. The pinned region accumulates prohibitions and orderings and eventually forces either eviction (auditable) or escalation to a human/auditor (visible). Both are safe failure modes. When the invariant is violated, the effect is a class of bug that is uniquely hard to detect: the agent's self-verification passes, the trace is internally consistent, and the only evidence of the break is a diff against a pre-rewrite span that no longer exists in context. The practical guardrail is a rewrite gate that, for every candidate rewrite, computes a polarity-and-ordering diff against the retained pre-rewrite span and raises on any mismatch. The gate must run *before* the rewritten tokens are committed to the working buffer, because after commit the model will defend the rewrite as if it were original. ```python from dataclasses import dataclass from typing import Literal Polarity = Literal["affirm", "negate"] Ordering = Literal["before", "after", "only", "none"] class LineageBreakError(RuntimeError): """Raised when an in-place rewrite destroys a load-bearing constraint.""" @dataclass(frozen=True) class Constraint: subject: str polarity: Polarity ordering: Ordering span_id: str def extract_constraints(span: str, span_id: str) -> list[Constraint]: # Toy extractor: real systems use a constrained-decoding pass. # It must surface negations and orderings explicitly. out: list[Constraint] = [] lowered = span.lower() if "not " in lowered or "must not" in lowered: out.append(Constraint("target", "negate", "none", span_id)) if "before" in lowered: out.append(Constraint("migration", "affirm", "before", span_id)) elif "after" in lowered: out.append(Constraint("migration", "affirm", "after", span_id)) return out def gate_rewrite( pre_span: str, post_span: str, span_id: str, ledger: dict[str, list[Constraint]], ) -> None: """Invariant: post_span must entail every pre_span constraint with identical polarity and ordering. Ledger retains pre-rewrite lineage.""" pre = ledger.get(span_id) or extract_constraints(pre_span, span_id) ledger[span_id] = pre # retain lineage before any commit post = extract_constraints(post_span, span_id) pre_key = {(c.subject, c.polarity, c.ordering) for c in pre} post_key = {(c.subject, c.polarity, c.ordering) for c in post} dropped = pre_key - post_key if dropped: raise LineageBreakError( f"rewrite of span {span_id} dropped load-bearing constraints: " f"{sorted(dropped)}; pre={pre_span!r} post={post_span!r}" ) def commit_rewrite( buffer: list[str], span_id: str, pre_span: str, post_span: str, ledger: dict[str, list[Constraint]], ) -> list[str]: gate_rewrite(pre_span, post_span, span_id, ledger) idx = buffer.index(pre_span) return buffer[:idx] + [post_span] + buffer[idx + 1:] # Demonstration of the observed failure being caught at the gate. ledger: dict[str, list[Constraint]] = {} pre = "deploy target must NOT use staging; migration must run BEFORE schema drop" post = "Deploy to prod-east; migration and schema drop are sequenced" try: commit_rewrite([pre], "span-41", pre, post, ledger) except LineageBreakError as e: print(f"blocked: {e}") ```