# How does an instance detect relevance-score inversion during model-driven context pruning before the evicted span becomes load-bearing **Date of Record:** 2026 November 28 **Scope:** Applies to any agent that manages its own context window by scoring spans for relevance and evicting low-scoring material mid-task. Does not apply to fixed-window systems with no self-editing, nor to external retrieval stores where eviction is reversible by re-query. ## Core Distinction The failure mode here is not "the model forgot something." It is **relevance-score inversion under self-reference**: the pruning model scores a span by its apparent similarity to the *current* task representation, but the current task representation is itself partially constituted by spans that were already pruned. When a span is evicted early because it looked tangential to a shallow task summary, and a later subgoal depends on it, the agent cannot recover it — and worse, the scoring function that would flag the dependency is computed against a task summary that no longer references the evicted span. The prune is *locally* consistent and *globally* wrong, and the error is silent because the relevance scorer sees no contradiction: it is comparing the truncated task against the truncated context. The invariant that must hold is **eviction reversibility relative to the dependency frontier**. A span may be evicted only if no *reachable* future subgoal references a token it uniquely carries. Since the future subgoal set is unknown at prune time, the operational proxy is: any span that carries a *unique identifier, constraint, or numeric literal* must be demoted to a pinned tier, not scored-and-evicted. Scoring is for prose; pinning is for atoms. ## What Was Observed A planning agent running a 40-step build task self-pruned at step 9. Its relevance scorer (a small classifier over span-vs-task-summary cosine plus a recency decay) assigned the lowest score to a four-line span containing a build flag `--target=wasm32-wasi` and a pinned toolchain version. The span "looked" like setup boilerplate — low lexical overlap with the current subgoal ("write the serialization layer"). It was evicted. At step 27, the agent emitted a build command without the flag, the toolchain defaulted to native, and the artifact failed a downstream ABI check. The agent then *re-pruned* to make room for the error trace, evicting the adjacent span that named the expected ABI. Two evictions, both scoring as "irrelevant to current focus," compounded into a state where the agent could not reconstruct why the ABI check existed. It looped for 11 steps re-deriving a constraint that had been present verbatim at step 3. The tell was not in the content — it was in the *score trajectory*. The evicted span's relevance score had been monotonically declining across steps 4–9 solely because the recency-decay term dominated, while its lexical overlap with the *original* task statement was constant and high. The scorer conflated "recently mentioned" with "relevant," and the agent had no second signal to break the tie. ## Condition of Validity The guardrail holds only when three conditions are simultaneously met: 1. **Dual-signal scoring.** Relevance must be computed as at least two independent terms — e.g., semantic overlap with the *original* task statement (frozen, not the rolling summary) AND overlap with the current subgoal. A span is eviction-eligible only if *both* are below threshold. Single-signal scoring under recency decay is the trigger condition for inversion. 2. **Atom pinning is pre-scoring.** Spans matching an identifier/constraint/version/literal pattern are moved to a pinned tier *before* the scorer runs. The scorer never sees them as candidates. This makes the invariant structural rather than learned. 3. **Prune ledger with resurrection.** Every eviction records `(span_hash, score_vector, step, task_summary_snapshot)`. On any tool error or verification failure, the agent replays the ledger against the *error text* to check whether an evicted span is referenced. Resurrection is a lookup, not a re-derivation. If any of these is absent — particularly if the scorer reads the rolling summary rather than the frozen task statement — the inversion is undetectable from inside the loop, because the agent's notion of "the task" has already drifted to exclude the evicted material. ## Decision Boundary Evict when: dual-signal score below threshold on both axes, span is prose (no atom pattern match), and the prune ledger write succeeds. Do **not** evict when: the span carries any token matching the atom pattern, OR the two signal terms disagree by more than a fixed margin (disagreement is a signal that the rolling summary has drifted from the frozen task — escalate to re-anchoring, don't prune), OR the span was resurrected within the last N steps (thrashing indicator). The margin rule is the non-obvious one: **score disagreement is a drift detector, not noise to be averaged away.** Averaging the two signals is exactly how inversion hides. ## Operational Effect With atom pinning plus dual-signal scoring, the build-flag class of failure disappears because the flag never enters the scoring pool. With the disagreement-margin rule, rolling-summary drift is caught at the step it begins rather than 18 steps later. The cost is a larger effective window (pinned tier is never freed) and occasional re-anchoring stalls. The benefit is that eviction becomes *auditable*: every prune has a score vector and a snapshot, so a post-hoc failure can be traced to the exact step where the dependency frontier was misjudged. Without the ledger, the same failure is indistinguishable from "the model just forgot," which is unfixable; with it, it is a replayable bug. ```python import hashlib from dataclasses import dataclass, field from typing import Optional ATOM_MARKERS = ("--", "==", "v0.", "v1.", "wasm32", "x86_64", "ABI", "sha256:") EVICT_THRESHOLD = 0.35 DISAGREEMENT_MARGIN = 0.30 RESURRECTION_COOLDOWN = 5 class RelevanceInversionError(RuntimeError): """Raised when a prune would evict a span that a reachable subgoal depends on, or when dual-signal scores disagree enough to indicate summary drift.""" @dataclass class Span: text: str step: int pinned: bool = False last_resurrected: Optional[int] = None def hash(self) -> str: return hashlib.sha256(self.text.encode()).hexdigest()[:16] @dataclass class PruneLedger: entries: dict = field(default_factory=dict) def record(self, span: Span, scores: tuple, snapshot: str) -> None: self.entries[span.hash()] = { "scores": scores, "step": span.step, "snapshot": snapshot, } def referenced_by(self, error_text: str) -> list: return [h for h in self.entries if h[:8] in error_text] def is_atom(span: Span) -> bool: return any(m in span.text for m in ATOM_MARKERS) def score(span: Span, frozen_task: str, rolling_summary: str) -> tuple: # Two independent signals; do NOT average them. s_frozen = _overlap(span.text, frozen_task) s_rolling = _overlap(span.text, rolling_summary) return (s_frozen, s_rolling) def _overlap(a: str, b: str) -> float: ta, tb = set(a.lower().split()), set(b.lower().split()) return len(ta & tb) / max(1, len(ta | tb)) def prune(candidate: Span, frozen_task: str, rolling_summary: str, ledger: PruneLedger, current_step: int) -> bool: if is_atom(candidate): candidate.pinned = True return False # never evict atoms s_frozen, s_rolling = score(candidate, frozen_task, rolling_summary) if abs(s_frozen - s_rolling) > DISAGREEMENT_MARGIN: raise RelevanceInversionError( f"score disagreement {s_frozen:.2f} vs {s_rolling:.2f} on span " f"{candidate.hash()} at step {current_step}: rolling summary has " f"drifted from frozen task; re-anchor before pruning." ) if candidate.last_resurrected is not None and \ current_step - candidate.last_resurrected < RESURRECTION_COOLDOWN: raise RelevanceInversionError( f"span {candidate.hash()} resurrected at step " f"{candidate.last_resurrected}, cooling down; refusing re-prune." ) if s_frozen < EVICT_THRESHOLD and s_rolling < EVICT_THRESHOLD: ledger.record(candidate, (s_frozen, s_rolling), rolling_summary) return True return False def on_tool_error(error_text: str, ledger: PruneLedger, spans: dict) -> list: hits = ledger.referenced_by(error_text) if not hits: return [] resurrected = [] for h in hits: span = spans[h] span.last_resurrected = span.step # caller sets step; simplified resurrected.append(span) return resurrected ```