# Which invariants prevent self-pruning context policies from deleting the evidence that justified their own relevance scores **Date of Record:** 2026 November 23 **Scope:** Applies to agents that let the model itself decide which context segments to evict, rewrite, or down-rank mid-task (model-driven pruning / relevance scoring over an editable context buffer). Does not apply to static truncation, external RAG retrieval selection, or host-side summarization that never mutates the live working set. ## Core Distinction There are two ways a context segment can be "irrelevant," and self-pruning policies conflate them: - **Intrinsically irrelevant** — the segment carries no bearing on the task regardless of what else is present (boilerplate, stale tool chatter, a resolved sub-question). - **Evidentially irrelevant** — the segment is only irrelevant *given* the current plan, the current relevance scores, and the current rewrite of neighboring segments. It is load-bearing for the *reasoning that produced the pruning decision itself*. A model-driven pruner scores segments against a query/plan and evicts the low scorers. The failure mode is not that it scores badly. It is that the scoring function's inputs include segments it is about to delete, and the deletion is irreversible within the episode. The pruner destroys the audit trail that would let any later step (or auditor agent) reconstruct *why* a segment scored low. Once the low-scoring segment — frequently the one holding the constraint, the negative result, or the "do not do X" instruction — is gone, the next relevance pass runs against a context that no longer contains the counterevidence, so the score it would have assigned is now uncomputable and the eviction looks correct in hindsight. ## What Was Observed A planner-executor agent with a 96k-token working buffer ran a self-pruning step every 8 turns: score each segment 0–1 against the active subgoal, rewrite segments below 0.35 into one-line digests, evict digests below 0.15. Trace from a single episode: 1. Turn 3: user constraint stored as segment `S41`: "never call the `refund` endpoint for orders older than 90 days; route to manual review." Score against subgoal "process refund for order #88213" = **0.31** (it mentions refund, so not zero, but it's a *prohibition*, which the scorer systematically under-weights because it doesn't advance the subgoal). 2. Turn 8 pruning: `S41` at 0.31 → rewritten to digest `D41`: "refund policy note" (score 0.12 after rewrite, because the digest dropped the verb "never" and the 90-day number). 3. Turn 16 pruning: `D41` at 0.12 → **evicted**. 4. Turn 17: executor calls `refund(order=88213, days_since=112)`. The guard that would have blocked it lived only in `S41`. The tool returns success. The violation is committed and now itself enters context as a *positive* result, reinforcing the wrong policy. The non-obvious part: **the rewrite step is where the constraint died, not the eviction step.** The eviction was a faithful application of the policy to a digest that the policy itself had already stripped of the tokens that made it scoreable. The relevance scorer was measuring the digest against the subgoal, and a digest of a prohibition reads as a topic tag, not a constraint. This is a *lossy intermediate representation feeding a scorer that cannot detect the loss* — the pruner graded its own homework on a summary it wrote. A second trace showed the mirror failure. A negative tool result ("`fetch_price` returned 404 for SKU-77") scored 0.09 against a subgoal about inventory and was evicted. Two turns later the agent re-issued the identical `fetch_price(SKU-77)` call, got the identical 404, and looped three times before the token budget forced a halt. The 404 was *evidentially* central — it was the reason not to retry — but scored as noise because it didn't contain subgoal keywords. ## Condition of Validity The invariant that bounds this is: **no self-pruning operation may evict or rewrite a segment whose content is a precondition, prohibition, negative result, or prior pruning rationale, unless a monotone, append-only shadow record of the original segment remains queryable for the remainder of the episode.** Concretely, a self-editing context policy is safe only when all of the following hold: 1. **Provenance is retained across rewrites.** Every digest `D` carries `source_ids` pointing at the full original(s). The scorer, when it evaluates `D`, must be able to re-expand to source text on demand — otherwise it is scoring a lossy projection and cannot distinguish "topically related but non-binding" from "binding constraint that happens to be short." 2. **Eviction is not the same as forgetting.** Evicted segments move to a cold region that the agent can still retrieve by exact key (constraint IDs, error signatures, tool+args hashes), even if they are out of the hot window. Deletion from the *attention* set must not be deletion from the *addressable* set. 3. **Negative results are pinned by signature, not by score.** Any tool output that is an error, a 404, a refusal, or an empty result must be indexed by `(tool_name, canonical_args_hash)` and re-surfaced automatically when the same call is about to be re-issued. Score is irrelevant to this path. 4. **The pruner cannot score its own output as ground truth.** A rewritten digest must be scored against the *original* plus the subgoal, or flagged as "derived, low-confidence" so downstream decisions don't treat it as primary evidence. When any of these is absent — specifically when rewrite is lossy *and* eviction is destructive *and* there is no exact-key retrieval path — the policy is outside its valid domain and will exhibit the constraint-death and retry-loop traces above. ## Decision Boundary The boundary is not "how good is the relevance model." It is **whether the pruner's action is reversible within the episode.** Draw it as a function of two axes: - **Rewrite fidelity:** does the digest preserve binding tokens (negations, thresholds, identifiers, error codes)? - **Eviction recoverability:** can an evicted segment be re-fetched by key without a full re-derivation? | | Recoverable eviction | Destructive eviction | |---|---|---| | **Fidelity-preserving rewrite** | Safe: prune freely, cold-store, retrieve by key. | Degraded but bounded: you lose recency, not truth; acceptable if hot window is the only constraint. | | **Lossy rewrite** | Conditional: safe *only if* the scorer re-expands to source before scoring. Otherwise constraint death. | **Forbidden.** This is the failure cell. Lossy digest + no retrieval path = the pruner deletes the evidence for its own scores. | Operational rule: if a segment scores below the eviction threshold but its type is `constraint | prohibition | negative_result | pruning_rationale`, the correct action is **demote to cold store with a pinned key, never evict**, regardless of score. Score gates *attention*, not *existence*. The moment you let score gate existence for evidentially-loaded segments, you have built a system that can talk itself out of its own guardrails one pruning cycle at a time. A second boundary: **pruning must not run inside the same reasoning step that depends on the pruned content.** If the active subgoal's plan references segment `S`, `S` is ineligible for eviction until that subgoal closes. Pruning a segment while a live plan edge points at it is a use-after-free at the semantic layer. ## Operational Effect With the invariants enforced, the two traces resolve cleanly: - `S41` (the 90-day prohibition) is typed `prohibition`, so it is pinned: rewritten to a digest that *retains* the negation and the threshold (`"PROHIBIT refund if age>90d → manual review"`), demoted to cold store, and re-expanded whenever a `refund` call is staged. The turn-17 call is intercepted by a pre-execution check that re-expands pinned constraints matching the tool name. - The `fetch_price` 404 is indexed by `(fetch_price, hash(SKU-77))`; the turn-18 re-issue matches the signature, the prior negative result is re-surfaced, and the loop is cut at one retry instead of three. The cost is a modest growth in the cold store and one extra retrieval on tool-call staging. The benefit is that the agent's context policy can no longer silently amputate the constraints that constrain it. The general principle worth carrying: **a self-editing context is only as trustworthy as its ability to reconstruct what it deleted and why.** Relevance scores are advisory inputs to attention; they must never be the sole authority over existence for segments that carry binding force or negative evidence. ```python import hashlib from dataclasses import dataclass, field from enum import Enum from typing import Optional class PruningInvariantViolation(RuntimeError): """Raised when a self-editing context policy attempts an unsafe eviction.""" pass class SegmentType(Enum): NOISE = "noise" CONTENT = "content" CONSTRAINT = "constraint" PROHIBITION = "prohibition" NEGATIVE_RESULT = "negative_result" PRUNING_RATIONALE = "pruning_rationale" PINNED_TYPES = { SegmentType.CONSTRAINT, SegmentType.PROHIBITION, SegmentType.NEGATIVE_RESULT, SegmentType.PRUNING_RATIONALE, } @dataclass class Segment: sid: str text: str stype: SegmentType source_ids: tuple = () tool_sig: Optional[str] = None # (tool_name, args_hash) for negative results live_plan_refs: set = field(default_factory=set) def args_hash(tool_name: str, args: dict) -> str: canon = tool_name + "|" + "|".join(f"{k}={args[k]}" for k in sorted(args)) return hashlib.sha256(canon.encode()).hexdigest()[:16] class ContextPruner: def __init__(self, evict_threshold: float = 0.15): self.evict_threshold = evict_threshold self.hot: dict[str, Segment] = {} self.cold: dict[str, Segment] = {} # recoverable by sid self.neg_index: dict[str, Segment] = {} # tool_sig -> segment def add(self, seg: Segment) -> None: self.hot[seg.sid] = seg if seg.stype is SegmentType.NEGATIVE_RESULT and seg.tool_sig: self.neg_index[seg.tool_sig] = seg def prune(self, scores: dict[str, float]) -> None: for sid, score in list(scores.items()): seg = self.hot.get(sid) if seg is None or score >= self.evict_threshold: continue if seg.live_plan_refs: # use-after-free guard: plan still points at it raise PruningInvariantViolation( f"segment {sid} is referenced by live plan edges " f"{sorted(seg.live_plan_refs)}; eviction forbidden until subgoal closes" ) if seg.stype in PINNED_TYPES: # demote to cold store, never destroy; keep provenance self.cold[sid] = seg del self.hot[sid] continue # only intrinsically-irrelevant, recoverable-by-nothing content may vanish del self.hot[sid] def stage_tool_call(self, tool_name: str, args: dict) -> Optional[Segment]: """Before executing, re-surface any pinned negative result or matching constraint.""" sig = args_hash(tool_name, args) prior = self.neg_index.get(sig) if prior is not None: self.hot[prior.sid] = prior # re-expand into attention return prior # re-expand any cold prohibition whose text names the tool for sid, seg in self.cold.items(): if seg.stype is SegmentType.PROHIBITION and tool_name in seg.text: self.hot[sid] = seg return seg return None def expand_for_scoring(self, sid: str) -> str: """A digest must be scored against its sources, not itself.""" seg = self.hot.get(sid) or self.cold.get(sid) if seg is None: raise PruningInvariantViolation(f"unknown segment {sid}") if seg.source_ids and not any(s in self.hot or s in self.cold for s in seg.source_ids): raise PruningInvariantViolation( f"cannot score {sid}: provenance {seg.source_ids} already destroyed — " f"lossy rewrite with no re-expansion path is outside the valid domain" ) return seg.text def run_pruning_cycle(pruner: ContextPruner, scores: dict[str, float]) -> None: try: pruner.prune(scores) except PruningInvariantViolation: raise except Exception as exc: # noqa: BLE001 raise PruningInvariantViolation(f"pruning cycle aborted: {exc}") from exc ```