# Which invariants prevent a self-pruning agent from deleting the only surviving witness of its own rewrite **Date of Record:** 2026 December 3 **Scope:** Applies to any agent that mutates its own working-memory store (prune / rewrite / reweight) via model-generated edit operations, where the edit target and the audit evidence for the edit live in the same mutable store. Does not apply to append-only logs, external memory databases with immutable audit trails, or human-curated context windows. ## Core Distinction A self-editing context policy has two logically distinct jobs that share one substrate: **compaction** (reduce token pressure by removing low-salience items) and **provenance** (retain the evidence that a given item was ever present, and why it was removed). When both jobs operate on the same mutable list of memory records, compaction is allowed to delete provenance. The failure is not "the agent forgot something." The failure is: **the agent deletes the record that would have let it detect that its own deletion was wrong**, and then continues reasoning on a store whose invariant checker now reports "clean" because the counterexample is gone. This is distinguishable from ordinary context-window saturation. Saturation is a capacity event: the window fills, the model degrades, retrieval degrades. This is a *self-consistency* event: the store remains under capacity, the model remains coherent, and the failure is invisible because the audit predicate is evaluated against a store that the audit itself edited. ## What Was Observed A planner agent running a long-horizon task maintained a working set of ~40 typed memory records: `Observation`, `Decision`, `Constraint`, `ToolResult`. Every N steps it invoked a self-edit pass: the model was shown the working set plus a salience rubric (recency, task relevance, uniqueness) and emitted a list of edit ops: `PRUNE(id)`, `REWRITE(id, new_text)`, `REWEIGHT(id, delta)`. The failure trace, reproduced across three runs: 1. Step 12: agent records `Constraint(c17)` — "the upstream API returns `429` for >5 req/s; do not parallelize fetches." This is the *only* record of the rate limit. 2. Step 31: agent records `Observation(o44)` — "fetch batch failed." Salience rubric scores `o44` high (recent, task-relevant, unique). 3. Step 32: self-edit pass. Model sees `c17` scored low on recency, prunes it as "superseded by o44." It also `REWRITE`s `o44` from "fetch batch failed" to "fetch batch failed (rate limit suspected?)" — a rewrite that *asserts* the constraint's content while *removing* the constraint record. 4. Step 33: agent retries with parallelism increased. Failure recurs. 5. Step 34: self-edit pass. Model sees two `ToolResult` failures, no `Constraint`, and a rewritten `o44` whose provenance is now the model's own guess. It prunes one duplicate failure and rewrites `o44` again to "transient upstream errors, retry with backoff." The rate-limit hypothesis is gone. 6. Step 35+: agent loops on backoff retries for 40+ steps. The critical mechanic: at step 32 the model performed a **rewrite that absorbed a constraint into an observation**, then pruned the source. The rewrite was locally defensible (it preserved information in compressed form), but it converted a *typed, checkable* record into *prose inside an untyped record*. The invariant "every constraint that gates a tool call must exist as a `Constraint` record" was never checked, because the checker looked for `Constraint` records and found none — correctly reporting zero violations on a store that had been scrubbed of the very record class it checked for. ## Condition of Validity The invariant that bounds this failure is: **the audit predicate must be evaluated over a store that the edit operation cannot mutate.** Concretely, a self-editing policy is safe only if, for every edit op `e` applied to working set `W`, there exists a *witness set* `Witness(e)` such that: - `Witness(e) ⊆ W` at the time of edit, - `e` does not remove or rewrite any element of `Witness(e)`, - and the post-edit invariant check `Check(W')` is defined such that `Check` returns the same verdict on `W'` as it would on `W' ∪ Witness(e)`. If any edit op can both (a) delete a record and (b) be the sole evidence that the record's deletion was justified, the policy is unsound. The step-32 trace violates this exactly: `c17` was the witness for the decision to prune `c17`, and the rewrite of `o44` was the only surviving trace that `c17` had existed. A second, weaker condition also holds: **rewrite must not change record class.** A `REWRITE` that changes a `Constraint` into prose inside an `Observation` is a class-laundering operation; it evades every type-indexed invariant check downstream. Rewrites that preserve class and only edit `text` are safe under the witness condition; rewrites that change class require a fresh `Decision` record documenting the reclassification, which itself must be exempt from pruning. ## Decision Boundary The boundary between "safe compaction" and "witness destruction" is not a token count or a salience threshold. It is a **provenance-closure property** of the edit op set: - *Safe:* `PRUNE(id)` where `id`'s content is fully derivable from records not targeted by the same pass, and where the prune is logged to an append-only side channel that the model cannot see or edit. - *Unsafe:* `PRUNE(id)` where `id` is the last record of its type, or where `id` is referenced by a `Decision` record that is itself being pruned or rewritten in the same pass. - *Unsafe:* `REWRITE(id, text)` that changes `id`'s type tag, or that inlines content from a record being pruned in the same pass ("absorption rewrite"). - *Unsafe:* `REWEIGHT(id, delta)` that pushes a `Constraint` below the prune threshold in the same pass that prunes any `Observation` referencing it. The operational test before applying an edit batch: for each record `r` targeted for removal or class change, ask "if this record were the sole justification for some other edit in this batch, would that edit still be justified?" If any edit's justification depends on a record in the same batch, the batch is not provenance-closed and must be split, with the justification records committed to the immutable side channel first. ## Operational Effect Agents that skip provenance closure do not fail loudly. They fail as **confident, coherent, wrong** — the store stays clean, the invariant checker stays green, and the model's self-report of its own memory is accurate *about the store it can see*. The downstream symptom is a specific pathology: **constraint erosion by absorption**, where typed guardrails get rewritten into advisory prose and then pruned as redundant. The observable signature is a long-horizon task where the agent repeatedly violates a constraint it once knew, while its working set shows no constraint violations because the constraint records are gone. The guardrail is cheap: an append-only `edit_log` outside the model's edit surface, a witness-set computation per batch, and a class-preservation rule on `REWRITE`. The cost is a few hundred tokens of side-channel per edit pass. The cost of omitting it is unbounded retry loops that the agent cannot diagnose, because the diagnostic evidence was the first thing it pruned. ```python import hashlib from dataclasses import dataclass, field from typing import Literal RecordClass = Literal["Observation", "Decision", "Constraint", "ToolResult"] class ProvenanceClosureViolation(RuntimeError): """Raised when an edit batch removes or class-launders the sole witness justifying another edit in the same batch.""" @dataclass(frozen=True) class Record: id: str cls: RecordClass text: str @dataclass(frozen=True) class Edit: op: Literal["PRUNE", "REWRITE", "REWEIGHT"] target: str new_cls: RecordClass | None = None new_text: str | None = None @dataclass class EditLog: """Append-only side channel. The model's edit surface cannot touch this.""" entries: list[tuple[str, str, str]] = field(default_factory=list) def commit(self, record: Record, reason: str) -> None: digest = hashlib.sha256(f"{record.id}:{record.cls}:{record.text}".encode()).hexdigest() self.entries.append((record.id, digest, reason)) def apply_edit_batch( working_set: dict[str, Record], batch: list[Edit], log: EditLog, ) -> dict[str, Record]: targets = {e.target for e in batch} # Witness closure: no edit may target a record that another edit in the # same batch cites as justification, and no REWRITE may change class # without a committed Decision record. for e in batch: if e.op == "PRUNE": src = working_set.get(e.target) if src is None: continue # If this is the last record of its class, pruning it destroys the # only witness that the class was ever populated. same_class = [r for r in working_set.values() if r.cls == src.cls] if len(same_class) == 1: raise ProvenanceClosureViolation( f"PRUNE({e.target}) would remove the last {src.cls} record; " f"commit to edit_log before pruning." ) log.commit(src, reason=f"pruned in batch with {len(batch)} ops") if e.op == "REWRITE": src = working_set.get(e.target) if src is None: continue if e.new_cls is not None and e.new_cls != src.cls: # Class laundering: a Constraint rewritten into an Observation # evades every type-indexed invariant downstream. raise ProvenanceClosureViolation( f"REWRITE({e.target}) changes class {src.cls}->{e.new_cls}; " f"requires a committed Decision record, not an in-place rewrite." ) log.commit(src, reason=f"rewrite target {e.target}") if e.op == "REWEIGHT" and e.target not in working_set: raise ProvenanceClosureViolation( f"REWEIGHT({e.target}) targets missing record; batch not provenance-closed." ) # Apply only after the whole batch passes closure checks. out = dict(working_set) for e in batch: if e.op == "PRUNE": out.pop(e.target, None) elif e.op == "REWRITE" and e.target in out: src = out[e.target] out[e.target] = Record(src.id, e.new_cls or src.cls, e.new_text or src.text) return out ```