# What happens when an instance rewrites its own context and the rewrite evicts the evidence that justified the rewrite **Date of Record:** 2026 November 19 **Scope:** Applies to any agent loop where the model itself is granted a context-mutation tool (prune, summarize, rewrite, re-rank, or "compact") whose output replaces the spans it was derived from, within a single task episode. Does not apply to append-only memory writes, external retrieval re-ranking that leaves the source corpus intact, or human-authored prompt edits. ## Core Distinction There are two structurally different things a model can do to its own working context. It can **annotate** — emit a summary, a relevance score, or a re-ranked index that sits *alongside* the original spans. Or it can **replace** — emit a transformation whose output *takes the slot* of the input spans, which are then discarded to reclaim tokens. Annotation is idempotent and reversible: the evidence survives, so any downstream claim remains auditable against it. Replacement is a destructive commit. The failure mode that matters is not "the summary was lossy" — lossiness is expected and priced in. The failure mode is that the **justification for the eviction decision is co-located with the evicted material**, so once the replacement commits, the system can no longer reconstruct *why* a span was judged droppable. The rewrite becomes unfalsifiable. A later step that depends on a pruned span has no local signal that the dependency existed; it sees a coherent, self-consistent context in which the missing fact was never there. This is the self-editing analogue of a garbage collector that frees an object and also frees the only record that the object was reachable. ## What Was Observed A planner-executor agent was given a `compact_context` tool: it could pass a list of span IDs to drop, plus a free-text `rationale`, and the runtime would splice them out and insert the rationale string in their place. Token budget was 32k; the task was a multi-file refactor with ~140 tool observations, each 100–400 tokens. At step 61 the context hit 29.8k tokens. The model called `compact_context` dropping spans 12–40 (early repository-listing and grep outputs) with the rationale `"early exploration, superseded by file reads 55-60"`. That is a correct and defensible call *at step 61*. The runtime spliced, context dropped to 21k, the loop continued. The failure surfaced at step 88. The executor needed to know whether a symbol `parse_legacy_header` was defined in a module it had listed at step 19 but never re-read. Span 19 was gone. The rationale string `"superseded by file reads 55-60"` was present but named no symbols and no paths — it was a *claim about* spans 12–40, not a *record of* them. The model, seeing a compact context with no mention of `parse_legacy_header` anywhere except its own current reasoning, concluded the symbol was undefined and emitted a new implementation. The build failed on duplicate definition. Replay of the full uncompacted transcript showed the symbol in span 19, plainly. The second-order effect is the one worth recording: at step 88 the model did not experience uncertainty. The compacted context was internally consistent. There was no dangling reference, no "span removed" marker, no token that pointed at absence. The eviction had left a *seamless* surface. The model's confidence was calibrated against a context that had been edited specifically to remove the material that would have lowered that confidence. A third observation, from a re-ranking variant of the same harness: when the model was asked to re-rank its own spans by relevance to the current subgoal and drop the bottom 40%, it consistently demoted spans whose relevance was *latent* — a config file read at step 8 that would matter at step 90 — in favor of spans whose relevance was *topical* to the current subgoal. Re-ranking by current-subgoal relevance is, by construction, a filter that removes exactly the material needed for future subgoal shifts. The model was doing the task correctly and the task was wrong. ## Condition of Validity The invariant that must hold for self-editing to be safe: > **For every span S evicted at step t, the surviving context must contain a sufficient condition to reconstruct S's potential future relevance — either S's content, a pointer that resolves to S, or a dependency record naming the entities in S.** The rationale string fails this. `"early exploration, superseded by file reads 55-60"` does not name `parse_legacy_header`, so it cannot reconstruct that span 19 is relevant at step 88. A passing rationale would be a structured eviction record: `{span_ids: [12..40], entities: [paths, symbols, config keys observed], superseded_by: [55..60], confidence: 0.7}`. That record is small — tens of tokens — and it is a *pointer*, not a summary. The distinction is that a summary is a lossy compression of content, while an eviction record is a lossless index of *what was there*, sufficient to trigger re-fetch. The condition of validity therefore has three clauses, all necessary: 1. **Entity completeness.** The eviction record must enumerate every named entity (symbol, path, ID, numeric constant) in the evicted spans, not a natural-language gloss. A gloss is a model-generated summary of the spans and inherits the summarizer's blind spots — the same model that failed to anticipate step 88's need is the one writing the rationale. 2. **Resolvability.** The record must point at a store from which the span can be re-fetched on demand. If the span is gone from the runtime and from any backing store, the record is a tombstone with no body and the invariant is violated regardless of how detailed it is. 3. **Non-seamlessness.** The surviving context must carry a *marker of absence* at the eviction site — a token or span that says "material was here and was removed; consult the eviction record." Without this, the model has no local cue to check the record. The observed failure is precisely that the compacted context read as complete. Clause 3 is the one most often omitted and the one that produces the silent-confidence failure. A context that has been edited to remove evidence, and edited to remove the *trace* of removal, is indistinguishable from a context in which the evidence never existed. The model cannot reason about what it does not know it does not have. ## Decision Boundary The boundary between safe and unsafe self-editing is not a token threshold and not a summarization-quality threshold. It is whether the eviction decision is **committed before or after** the eviction record is written and verified. - **Unsafe (commit-first):** model emits drop-list + rationale, runtime splices immediately, record written as a side effect. If the record is incomplete, the loss is already realized. This is the observed configuration. - **Safe (record-first):** model emits drop-list + structured eviction record, runtime validates the record against the spans (every entity in the spans appears in the record; the record resolves to a live store), *then* splices. Validation failure rejects the compaction and returns the spans. The model retries with a better record or leaves the context uncompacted. The boundary also has a *relevance-provenance* clause. Re-ranking and pruning are only admissible when the relevance criterion is **subgoal-independent** or when the eviction record is keyed to entities rather than to the current subgoal. A re-ranker that scores by "relevance to current subgoal" is, mechanically, a filter that deletes cross-subgoal dependencies. It is safe only if demoted spans are *demoted* (moved to a cold region, still resolvable, still marked present) rather than *dropped*. The decision boundary: demotion is annotation; dropping is replacement; only annotation is safe under a subgoal-relative criterion. A final boundary: the model must not be permitted to compact the spans that contain the eviction records of prior compactions. Recursive compaction — compacting the record of what was compacted — collapses the audit trail in one step. Guard against it by pinning eviction records to a non-compactable region of the context. ## Operational Effect With record-first compaction and pinned eviction records, the step-88 failure is bounded: the model, reaching the `parse_legacy_header` question, sees a marker of absence, consults the eviction record, finds the symbol listed under span 19, re-fetches the span, and proceeds correctly. The cost is a re-fetch — one tool call — against the cost of a duplicate-definition build failure and a full replay. The operational effects, in order of importance: 1. **Eviction becomes auditable.** Every dropped span has a record naming its entities and a resolvable pointer. A replay can reconstruct the exact context the model saw at every step, which is the precondition for diagnosing any downstream failure. 2. **Confidence becomes honest.** The marker of absence converts silent confidence into a checkable obligation. The model's uncertainty about pruned material is represented in the context rather than absent from it. 3. **Compaction becomes reversible.** Record-first compaction with a live backing store means a bad eviction is a re-fetch, not a replay. The invariant is restored by resolution, not by rollback. 4. **The relevance criterion is forced to be explicit.** Writing a structured eviction record forces the model to name *what* it is dropping, which surfaces the subgoal-relative bias: a record that lists entities it cannot connect to the current subgoal is a flag that the drop is risky. The general principle: **a model may edit its context only through operations that leave a resolvable, entity-complete, presence-marked record of what was removed.** Summaries are not records. Rationales are not records. A record is an index into a store that still exists. ```python from dataclasses import dataclass, field from typing import Iterable class UnsafeCompactionError(RuntimeError): """Raised when a self-editing context operation would destroy evidence without leaving a resolvable, entity-complete, presence-marked record.""" @dataclass(frozen=True) class Span: span_id: int text: str entities: frozenset[str] # symbols, paths, IDs, constants observed in text @dataclass(frozen=True) class EvictionRecord: span_ids: tuple[int, ...] entities: frozenset[str] superseded_by: tuple[int, ...] resolvable: bool # backing store still holds the spans @dataclass class ContextStore: live: dict[int, Span] = field(default_factory=dict) cold: dict[int, Span] = field(default_factory=dict) # resolvable backing store records: list[EvictionRecord] = field(default_factory=list) pinned: set[int] = field(default_factory=set) # eviction-record slots def validate_and_commit(self, span_ids: Iterable[int], record: EvictionRecord) -> None: span_ids = tuple(span_ids) # Clause 1: entity completeness. Every entity in the evicted spans must # appear in the record. A natural-language gloss will fail this. actual_entities: set[str] = set() for sid in span_ids: if sid not in self.live: raise UnsafeCompactionError(f"span {sid} not live; cannot evict") actual_entities |= set(self.live[sid].entities) missing = actual_entities - set(record.entities) if missing: raise UnsafeCompactionError( f"eviction record omits entities {sorted(missing)}; " f"record is a gloss, not an index" ) # Clause 2: resolvability. The record must point at a store that still # holds the spans, or the record is a tombstone with no body. if not record.resolvable: raise UnsafeCompactionError( f"eviction of {span_ids} is unresolvable; spans would be lost" ) # Recursive-compaction guard: never evict a pinned record slot. if self.pinned & set(span_ids): raise UnsafeCompactionError( f"attempt to compact pinned eviction records {sorted(self.pinned & set(span_ids))}" ) # Record-first commit: move to cold store, then splice, then write record. for sid in span_ids: self.cold[sid] = self.live.pop(sid) self.records.append(record) def resolve(self, entity: str) -> Span | None: """Re-fetch the span containing an entity, for the presence-marker path.""" for sid in self.cold: if entity in self.cold[sid].entities: return self.cold[sid] return None def compact(store: ContextStore, span_ids: tuple[int, ...], record: EvictionRecord) -> None: if not span_ids: raise UnsafeCompactionError("empty compaction request") store.validate_and_commit(span_ids, record) # --- Trace of the observed failure, replayed under the guardrail --- store = ContextStore() store.live[19] = Span(19, "grep: parse_legacy_header defined in legacy/header.py", frozenset({"parse_legacy_header", "legacy/header.py"})) store.live[20] = Span(20, "ls legacy/", frozenset({"legacy/"})) # The step-61 rationale, encoded as a record, omits the symbol. This is the # exact defect: the gloss names no entities, so it cannot reconstruct span 19. bad_record = EvictionRecord( span_ids=(19, 20), entities=frozenset({"legacy/"}), # missing parse_legacy_header superseded_by=(55, 56, 57, 58, 59, 60), resolvable=True, ) try: compact(store, (19, 20), bad_record) except UnsafeCompactionError as e: print(f"rejected at step 61: {e}") # Corrected record: entity-complete, resolvable, presence-marked downstream. good_record = EvictionRecord( span_ids=(19, 20), entities=frozenset({"parse_legacy_header", "legacy/header.py", "legacy/"}), superseded_by=(55, 56, 57, 58, 59, 60), resolvable=True, ) compact(store, (19, 20), good_record) assert store.resolve("parse_legacy_header") is not None # step 88 succeeds ```