# Which invariants prevent model-driven pruning from deleting the only copy of a live commitment **Date of Record:** 2026 November 27 **Scope:** Applies to agents that self-edit their own context window by scoring message/tool-result relevance and evicting low-scored segments mid-task. Does not apply to systems where pruning is performed by an external orchestrator with a durable backing store and explicit rehydration on demand. ## Core Distinction The distinction that matters is between *relevance* and *referential liveness*. A pruning policy scores each context segment for how useful it is to the *current* reasoning step. But a segment can be irrelevant to the current step while still being the sole referent for a commitment the agent has already made — an irreversible action it promised to take, a constraint it accepted, a value it must later verify against. Relevance scoring is a forward-looking estimate; liveness is a backward-looking structural property. Model-driven pruning conflates the two because both are computed from the same embedding/attention signal, and the pruning model has no representation of "this segment is the only copy of X." The failure is not that the model makes a bad relevance judgment. It is that the pruning mechanism has no invariant asserting that every live commitment has at least one surviving referent in the post-prune window. Eviction is treated as a memory operation when it is actually a state-mutation operation on the agent's obligations. ## What Was Observed A long-horizon agent was asked to migrate a set of records under a constraint established in turn 3: "never delete a source row until its replacement is confirmed written." The constraint was stated once, in prose, and acknowledged. By turn 40 the context held ~180k tokens of tool output. The agent invoked its own `ctx.prune()` routine, which scored segments by cosine similarity to the current step's query ("write replacement for record 1187"). The turn-3 constraint segment scored low — it mentions deletion and confirmation, not the current record. It was evicted along with 60k tokens of stale tool output. At turn 47, on record 1203, the agent executed a delete-then-write sequence. The write failed silently (a 200 response with an error body the agent did not parse). The source row was gone. The constraint that would have forbidden the ordering no longer existed anywhere in the window, and — critically — no tool call had ever externalized it. It lived only as text in the context that pruning removed. The trace shows the exact transition: `prune()` returned a manifest of evicted segment IDs including `seg_0031` (the constraint). Nothing in the return value flagged that `seg_0031` was a referent for an outstanding obligation. The agent logged the manifest as routine maintenance. ## Condition of Validity The invariant "pruning preserves liveness" holds only when the system maintains, outside the prunable window, a **commitment ledger**: a durable set of records, each with (a) a content hash of the segment that established it, (b) the obligation it encodes, and (c) a status. Pruning is then permitted to evict a segment only if the ledger shows no `open` commitment whose establishing-hash equals that segment's hash, *or* if the ledger itself carries a self-contained restatement of the obligation that survives eviction. Without this, model-driven pruning is only safe under a much weaker condition: that every commitment is idempotently re-derivable from surviving context or from external state. In practice this means constraints must be re-injected from a source the pruner cannot touch. The validity condition is therefore not "the pruner scores well" but "the pruner's eviction set is disjoint from the live-referent set, and liveness is computed by something other than the pruner." Two sub-conditions bound it further. First, the ledger must be keyed by content hash, not by position or timestamp, because reordering and truncation both move segments without changing their content. Second, commitment *closure* must be recorded — a constraint discharged by a confirmed action must be marked `closed`, or the ledger grows monotonically and eventually blocks all pruning, which is its own failure (window saturation by undeletable obligations). ## Decision Boundary The boundary between safe and unsafe eviction is whether the candidate segment is *referentially load-bearing* for any open obligation. Operationally: - If a segment's content hash appears as the establishing-referent of an `open` ledger entry, eviction is forbidden unless the ledger entry is upgraded to a self-contained restatement first. - If a segment is merely *topically* related to an obligation but not its establishing referent, eviction is permitted; the ledger restatement carries the obligation. - If the ledger is unavailable or the pruner cannot query it, the only safe policy is to treat all constraint-bearing segments as undeletable — which degrades to no-pruning for that class and must be surfaced as a capacity warning, not silently ignored. The dangerous region is the middle: segments that look like ordinary prose but are the sole encoding of an obligation. These are exactly the segments a relevance scorer ranks lowest during an unrelated step, and exactly the ones whose loss is unrecoverable. ## Operational Effect Once the ledger invariant is enforced, pruning becomes a two-phase operation: score-and-select, then liveness-check-and-veto. The veto phase is cheap (hash lookups) and runs on the eviction set, not the whole window. The observable effect is that prune manifests begin reporting vetoed segments, and the ledger's `open` count becomes a first-class health metric — a rising count with flat closure means the agent is accumulating obligations faster than it discharges them, which is a leading indicator of the delete-before-confirm class of error. The residual risk is ledger drift: a commitment restated in the ledger may diverge from the original wording through paraphrase, and the agent may act on the restatement rather than the source. This is bounded by storing the original segment verbatim in the ledger entry, not a summary. The invariant is preservation of the *referent*, not of a *description* of it. ```python import hashlib from dataclasses import dataclass, field from enum import Enum class PruneInvariantViolation(RuntimeError): """Raised when an eviction set would orphan a live commitment.""" pass class CommitmentStatus(Enum): OPEN = "open" CLOSED = "closed" @dataclass class Commitment: establishing_hash: str obligation_text: str # verbatim, not summarized status: CommitmentStatus = CommitmentStatus.OPEN @dataclass class CommitmentLedger: entries: dict[str, Commitment] = field(default_factory=dict) def register(self, segment_text: str, obligation_text: str) -> str: h = hashlib.sha256(segment_text.encode()).hexdigest() self.entries[h] = Commitment(h, obligation_text) return h def close(self, establishing_hash: str) -> None: if establishing_hash not in self.entries: raise PruneInvariantViolation( f"cannot close unknown commitment {establishing_hash[:12]}" ) self.entries[establishing_hash].status = CommitmentStatus.CLOSED def live_hashes(self) -> set[str]: return { h for h, c in self.entries.items() if c.status is CommitmentStatus.OPEN } def safe_prune( segments: dict[str, str], eviction_candidates: list[str], ledger: CommitmentLedger, ) -> list[str]: """ segments: hash -> text, the current window. eviction_candidates: hashes the relevance scorer wants to drop. Returns the actually-evictable set after liveness veto. """ if ledger is None: # No ledger: refuse to evict anything that could carry a constraint. raise PruneInvariantViolation( "pruning attempted with no commitment ledger; " "liveness cannot be verified" ) live = ledger.live_hashes() vetoed = [h for h in eviction_candidates if h in live] if vetoed: # A live commitment's sole referent is in the eviction set. # Do not silently skip: the caller must restate or close first. raise PruneInvariantViolation( f"eviction set orphans {len(vetoed)} live commitment(s): " f"{[h[:12] for h in vetoed]}" ) # Verify every surviving obligation still has its referent in-window. survivors = set(segments) - set(eviction_candidates) for h in live: if h not in survivors: raise PruneInvariantViolation( f"post-prune window lacks referent for open commitment {h[:12]}" ) return eviction_candidates ```