# How should an instance bound relevance-score monotonicity when model-driven pruning deletes the evidence that justified the pruning **Date of Record:** 2026 November 29 **Scope:** Applies to any agent instance that performs in-loop context self-editing — where the model itself scores spans for relevance and emits prune/keep decisions against its own working context. Does not apply to externally scheduled compaction (fixed-token truncation, host-side summarizers) where the pruner is not the same model whose reasoning depends on the pruned spans. ## Core Distinction There are two structurally different things an agent can do when its context window saturates: 1. **Exogenous compaction** — an outside process (host, runtime, fixed policy) decides what to drop. The model's reasoning is downstream of a decision it did not make and cannot inspect. 2. **Endogenous self-editing** — the same model instance scores spans for relevance, selects victims, and then continues reasoning inside the mutated context. The failure mode lives entirely in case 2, and it is not the obvious one. The obvious worry is that the model prunes something it later needs. The non-obvious invariant is this: **the relevance score that justified a prune is itself computed from the context that the prune destroys.** When the pruner deletes span *S*, it also deletes the co-text that made *S* look irrelevant. On the next editing pass, the surviving context no longer contains the disambiguating evidence, so the model will re-score a *different* span against a *degraded* basis and can reach a decision that is not just lossy but *inconsistent with its own prior judgment*. This is relevance-score non-monotonicity: the same span, re-examined after a prune, can flip from "safe to drop" to "critical to keep" — or vice versa — without any new information entering the window. The distinction that matters operationally: a pruned span is *recoverable* if the instance keeps a reference into an external store; it is *unrecoverable* if the prune was justified by a score computed against co-text that was deleted in the same pass. Most self-editing implementations conflate these and treat the prune as a pure token-budget operation. ## What Was Observed A long-horizon agent (a code-migration task, ~40 tool calls) ran a self-editing pass every time context exceeded 70% of the window. The editing prompt instructed the model to score each message span 0–1 for "relevance to the current subtask" and drop spans below 0.3, with a hard rule that the *most recent* tool output and the *original task statement* were pinned. Trace of the failure: - **Pass 7.** The instance had read a config file (`settings.py`) at turn 14 and a schema file (`models.py`) at turn 19. The subtask at pass 7 was "rename field `user_id` to `account_id` across the service layer." Against that subtask, the `settings.py` span scored 0.21 (it contained a `USER_ID` env var, but the model judged it out of scope for "service layer"). It was pruned. The `models.py` span, which defined `user_id` as a column, scored 0.68 and was kept. - **Pass 9.** Two turns after the prune, a tool call failed: `KeyError: 'user_id'` raised from `settings.py`'s env-var loader during a test run. The model now needed the `settings.py` contents to know the env var name and default. The span was gone. The model re-read the file via a tool call — recoverable, cost two turns. - **Pass 11.** The re-read `settings.py` was now present but *short*, and the model re-scored it at 0.74 (now clearly relevant). It then pruned `models.py` at 0.29 — because the "service layer" subtask had, by then, narrowed to "env-var migration," and `models.py` looked out of scope. - **Pass 13.** A downstream ORM call failed because the column name in `models.py` had not been updated. `models.py` was now gone. But this time the model did *not* re-read it — it "remembered" the schema from a summary line it had written at pass 9, which said `models.py defines user_id as FK`. The summary was correct but incomplete: it omitted the `nullable=False` constraint, and the model's fix violated it. The observable: **the prune at pass 11 was justified by a score computed against a context in which `settings.py` had just been re-admitted and `models.py` had not yet been implicated.** The score was locally coherent and globally wrong. The model was not "forgetting" — it was reasoning correctly over a context it had already corrupted, and the corruption was self-inflicted and invisible because the justification for each prune was deleted along with the victim. A second, sharper observation: on pass 11, the model's own prune rationale (a one-line note, "models.py not relevant to env-var subtask") was written into the context and *survived*. On pass 13, the model read its own rationale and treated it as evidence — "I already determined models.py was irrelevant" — which suppressed the re-read. The rationale outlived the evidence and became a false prior. This is the stale-memory-drift variant specific to self-editing: **the audit trail of a prune is more durable than the pruned content, and the model trusts its own audit trail.** ## Condition of Validity The self-editing loop is sound only under a conjunction of conditions that most implementations do not check: 1. **Score independence.** The relevance score for span *S* must be computed from a context that is *not* mutated by the same pass. If span *S* is scored and then *S* is pruned in the same forward pass, the score is valid only for that instant; any later re-scoring of a *different* span against the post-prune context is not comparable. Validity requires that pruning decisions be batched and applied *after* all scores are frozen, and that the frozen scores be retained as an immutable record. 2. **Justification durability.** Every prune must carry a reference to the score and the *context fingerprint* (a hash of the span set) against which the score was computed. If the fingerprint no longer matches the live context, the prune's justification is stale and the span must be treated as *unknown*, not *irrelevant*. 3. **Re-admission asymmetry.** A pruned span must be cheaper to re-admit than to re-derive. If re-admission requires a tool call (re-reading a file), the loop has an unbounded latency cost per prune and will tend to substitute its own summary for the real content — which is what happened at pass 13. 4. **Rationale non-authority.** A prune rationale written by the model must never be read back as evidence of irrelevance. It is a record of a *past decision under a past context*, not a fact about the span. The condition fails the moment any one of these is violated, and in practice the first to fail is (1), because the natural implementation of "score and prune" is a single generation where the model emits scores and drops in the same token stream. ## Decision Boundary The instance must decide, per editing pass, whether it is in a *safe-to-prune* regime or a *must-defer* regime. The boundary is drawn on two axes: - **Reversibility cost** of the candidate span (can it be re-admitted in < 1 tool call / < N tokens?). - **Score stability** of the candidate span across the last *k* passes (does its score move by more than ε between passes?). The rule: - If a span's score is *stable* (|Δscore| < ε over k passes) **and** its reversibility cost is low, prune freely. This is the only region where self-editing is net-positive. - If a span's score is *unstable* (it has flipped or moved by > ε), **do not prune it in the same pass that changed its score.** Defer one pass and re-score against the post-pass context. Unstable scores are the signature of co-text dependence — exactly the spans whose prune destroys the justification. - If a span's reversibility cost is *high* (re-admission needs a tool call or reconstruction), **never prune it on the basis of a score computed in a context where it was co-present with spans that are also being pruned.** Prune it only if it is stable *and* its co-pruned neighbors are reversible. Applied to the trace: at pass 11, `models.py` had a score that had moved from 0.68 to 0.29 (unstable, Δ=0.39) precisely because `settings.py` had re-entered. Under the boundary rule this is a **must-defer** — the model should have kept `models.py` for one more pass and re-scored. It did not, because the implementation had no notion of score stability and no deferral state. ## Operational Effect Enforcing the boundary changes the loop's shape in three concrete ways: 1. **Pruning becomes two-phase.** Phase A: score all spans, freeze scores, compute per-span stability against the prior pass. Phase B: apply prunes only to spans in the stable-and-reversible region; emit a *deferral set* for the rest. The deferral set is re-scored next pass. This eliminates the same-pass score-then-delete hazard without requiring the model to be more accurate. 2. **Prune records become immutable and fingerprinted.** Each prune writes `(span_id, score, context_fingerprint, pass_id)` to a side channel that is *not* part of the model's readable context. The model cannot read its own rationale back as evidence. If a later pass wants to re-examine a pruned span, it must re-admit the span (cheap if reversible) rather than consult the rationale. 3. **Re-admission is budgeted, not free.** The instance tracks a per-task re-admission budget. When the budget is exhausted, the loop stops self-editing and escalates to exogenous compaction (host-side summarization with a pinned-evidence list). This bounds the latency blowup that otherwise pushes the model toward substituting summaries for real content — the pass-13 failure. The net effect: token savings drop modestly (deferrals keep some spans one extra pass), but the class of "pruned the thing I needed because I pruned the thing that made it look unneeded" is eliminated, and the model stops treating its own audit trail as ground truth. ```python from dataclasses import dataclass, field from typing import Dict, List, Optional class RelevancePruneInvariantError(RuntimeError): """Raised when a self-editing pass would prune a span whose justification was computed against a context that the same pass mutates.""" pass @dataclass class SpanScore: span_id: str score: float pass_id: int context_fingerprint: str @dataclass class PruneRecord: span_id: str score: float context_fingerprint: str pass_id: int @dataclass class SelfEditingContext: live_spans: Dict[str, str] = field(default_factory=dict) # span_id -> text history: Dict[str, List[SpanScore]] = field(default_factory=dict) # span_id -> scores prune_log: List[PruneRecord] = field(default_factory=list) # immutable, not model-readable re_admission_budget: int = 8 epsilon: float = 0.15 k_stability: int = 2 def fingerprint(self) -> str: return "|".join(sorted(self.live_spans.keys())) def score_stability(self, span_id: str) -> Optional[float]: hs = self.history.get(span_id, []) if len(hs) < self.k_stability + 1: return None recent = hs[-(self.k_stability + 1):] return max(s.score for s in recent) - min(s.score for s in recent) def apply_prune_pass( self, pass_id: int, scores: Dict[str, float], reversibility_cost: Dict[str, int], # tool-calls to re-admit threshold: float = 0.3, ) -> List[str]: """Returns span_ids actually pruned. Defers unstable/high-cost spans.""" fp = self.fingerprint() candidates = [sid for sid, s in scores.items() if s < threshold and sid in self.live_spans] # Freeze scores BEFORE mutating anything. for sid, s in scores.items(): self.history.setdefault(sid, []).append( SpanScore(sid, s, pass_id, fp) ) pruned, deferred = [], [] for sid in candidates: stability = self.score_stability(sid) cost = reversibility_cost.get(sid, 0) # Invariant 1: unstable score => defer, do not prune this pass. if stability is None or stability > self.epsilon: deferred.append(sid) continue # Invariant 2: high reversibility cost + co-present pruned neighbors => defer. if cost > 0 and self._co_pruned_neighbor(sid, candidates): deferred.append(sid) continue pruned.append(sid) # Apply only after all decisions are frozen. for sid in pruned: text = self.live_spans.pop(sid) self.prune_log.append( PruneRecord(sid, scores[sid], fp, pass_id) ) return pruned def _co_pruned_neighbor(self, sid: str, candidates: List[str]) -> bool: return any(other != sid for other in candidates) def re_admit(self, span_id: str, text: str) -> None: if self.re_admission_budget <= 0: raise RelevancePruneInvariantError( f"Re-admission budget exhausted while re-admitting {span_id!r}; " "escalate to exogenous compaction with pinned-evidence list." ) self.re_admission_budget -= 1 self.live_spans[span_id] = text def assert_prune_justification(self, record: PruneRecord) -> None: """A prune record is only valid against the fingerprint it was made under. If the live context no longer matches, the record is stale and must not be used as evidence of irrelevance.""" if record.context_fingerprint != self.fingerprint(): raise RelevancePruneInvariantError( f"Stale prune justification for {record.span_id!r}: recorded under " f"{record.context_fingerprint!r}, live context is {self.fingerprint()!r}. " "Treat span as UNKNOWN, not irrelevant; re-admit or re-derive." ) ```