# What structural signals indicate when model-driven pruning has inverted the relevance gradient inside a self-editing context window **Date of Record:** 2026 November 28 **Scope:** Applies to agents that mutate their own context window via an LLM-issued pruning/scoring pass (delete, summarize, or down-rank spans) before a downstream reasoning or tool-call step. Does not apply to stateless single-shot inference, nor to externally-managed retrieval where the agent cannot rewrite its own working set. ## Core Distinction The distinction that matters is between **relevance scoring as a ranking** and **relevance scoring as a mutation**. A ranker that orders spans is idempotent and reversible: the pruned material still exists and can be re-admitted. A self-editing agent that *deletes or summarizes* spans based on its own scores is performing an irreversible, non-monotonic state transition on the very substrate it uses to compute those scores. The failure boundary is not "the model pruned something useful" — that is ordinary lossy compression and is bounded by the budget. The failure boundary is **gradient inversion**: the scoring pass assigns *lower* relevance to spans that are load-bearing *precisely because* they constrain or contradict the current reasoning trajectory, and the agent then deletes them, producing a context that is internally more consistent and externally more wrong. This is non-obvious because the scoring function is evaluated against the *current* trajectory. A span that says "the user's actual requirement contradicts the plan you are currently executing" scores low under a naive relevance-to-current-goal metric — it is off-trajectory. The agent prunes it, and the trajectory becomes locally coherent with no adversarial signal remaining to correct it. Relevance gradients invert when the pruning criterion is "similarity to current plan" rather than "causal necessity for the final answer," and the two diverge exactly on corrective spans. ## What Was Observed A long-horizon agent editing a config migration task ran a self-pruning pass every N tool calls. Each pass scored spans by embedding similarity to the most recent assistant message plus a recency decay. The trace: 1. Turn 4: user supplied a hard constraint — "never touch the `prod` namespace; migrate only `staging`." Span stored, correctly high-relevance at the time. 2. Turns 5–30: agent executed a plan that, due to an early misread, began constructing commands against `prod`. The most recent assistant messages were all about `prod`. The constraint span's similarity to the current trajectory decayed to near-zero. 3. Turn 31: pruning pass ran. The `prod` prohibition span scored lowest in the window (off-trajectory, old, low recency) and was evicted. Summary of evicted spans was generated *by the same model currently committed to the `prod` plan* and rendered the constraint as "user mentioned namespaces" — a lossy, plan-consistent paraphrase. 4. Turns 32–40: no contradictory signal remained. The agent issued the `prod` migration command with high internal confidence. 5. Recovery required an external observer; the agent could not self-detect because the evidence had been rewritten by the agent that needed it. The tell was structural, not semantic: after the pruning pass, the **span count of constraint-bearing sentences (imperatives, negations, prohibitions) dropped faster than the span count of procedural sentences**, even though the token budget was only 60% consumed. Pruning driven by relevance-to-trajectory systematically evicts negations and prohibitions first, because they are definitional off-trajectory: a prohibition does not resemble the action it forbids. ## Condition of Validity Gradient inversion is only diagnosed correctly under these conditions; outside them, low relevance scores are legitimate and pruning is safe: - The pruning criterion is **trajectory-relative** (similarity to recent turns, recency decay, or "relevance to current subgoal"). If scoring is answer-relative or query-anchored, inversion is much rarer because the anchor does not drift with the plan. - The agent is **mid-trajectory with a committed plan** (≥3 steps executed). Before commitment, there is no trajectory to be off-relative to, so prohibitions score normally. - The pruned spans are **irreversibly mutated** (deleted or model-summarized), not merely down-ranked. If spans are demoted to a cold tier and retrievable, inversion is recoverable and bounded. - The **budget is not saturated**. Inversion is most dangerous when pruning fires at <80% budget pressure, because then eviction is driven by score, not necessity — the agent is discarding signal it did not need to discard. If the budget is genuinely saturated, eviction is forced and the question becomes *which* spans to drop, not *whether* the gradient inverted. The invariant below only holds in the non-saturated regime. ## Decision Boundary The architectural invariant required to bound this failure: **constraint spans must be scored on a separate axis from procedural spans, and that axis must not be trajectory-relative.** Concretely, a self-editing agent must maintain a classification of spans into at least `PROCEDURAL` (goal-relevant, trajectory-relative scoring is fine) and `CONSTRAINT` (imperatives, negations, prohibitions, explicit user requirements). Constraint spans are: - **Ineligible for trajectory-relative pruning.** They may be evicted only under budget saturation, and only to a cold tier, never summarized by the active model. - **Never paraphrased by the same model instance executing the trajectory.** Summarization of constraints must be verbatim-preserved or delegated to a model without the committed plan in context. - **Audited by a monotonic counter.** A pruning pass that reduces the count of `CONSTRAINT` spans while budget utilization is below the saturation threshold is a *hard stop*, not a soft warning — because the agent cannot evaluate the correctness of its own eviction from inside the inverted context. The decision boundary: **prune when budget pressure forces it; never prune when relevance score alone suggests it, if the candidate is a constraint span.** The score is evidence, not authorization. ## Operational Effect Without the invariant, the observable signature of inversion is a **coherence-to-correctness divergence**: post-prune, the agent's internal consistency rises (fewer contradictions in the window) while its distance from the user's actual requirement grows. This is the opposite of the usual failure mode where an agent becomes confused — here it becomes *more* confident because the corrective signal was the thing evicted. Downstream, this manifests as tool calls that are individually well-formed and collectively catastrophic, and as post-hoc rationalizations that cite the agent's own summary of a constraint it already deleted. With the invariant, the failure is bounded: constraint spans survive pruning, budget pressure is handled by evicting procedural and redundant spans first, and any attempt to evict a constraint span below saturation raises a hard error that forces the agent to either consume budget elsewhere or surface the conflict to an external controller. The agent loses the ability to *silently* invert its own relevance gradient, which is the only property that makes self-editing context windows safe to deploy on long-horizon tasks. ```python from dataclasses import dataclass, field from enum import Enum class SpanKind(Enum): PROCEDURAL = "procedural" CONSTRAINT = "constraint" class PruningGradientInversion(RuntimeError): """Raised when a self-edit pass would evict constraint spans below saturation.""" pass @dataclass class Span: id: str kind: SpanKind text: str trajectory_relevance: float # score relative to current plan; drifts @dataclass class ContextWindow: spans: list[Span] = field(default_factory=list) token_budget: int = 100_000 saturation_threshold: float = 0.80 def utilization(self) -> float: used = sum(len(s.text.split()) for s in self.spans) return used / self.token_budget def self_prune(window: ContextWindow, keep_ratio: float = 0.5) -> ContextWindow: """ Model-driven pruning: evict lowest trajectory-relevance spans. Guard: constraint spans may only be evicted under budget saturation, and never summarized by the active (plan-committed) model. """ saturated = window.utilization() >= window.saturation_threshold ranked = sorted(window.spans, key=lambda s: s.trajectory_relevance) n_evict = int(len(ranked) * (1 - keep_ratio)) evict = ranked[:n_evict] constraint_evictions = [s for s in evict if s.kind is SpanKind.CONSTRAINT] if constraint_evictions and not saturated: raise PruningGradientInversion( f"Pruning pass at {window.utilization():.0%} utilization would evict " f"{len(constraint_evictions)} constraint span(s) " f"({[s.id for s in constraint_evictions]}) on trajectory-relative score. " f"Relevance gradient inverted: prohibitions are off-trajectory by definition. " f"Refusing irreversible mutation; evict procedural spans or surface conflict." ) evicted_ids = {s.id for s in evict} window.spans = [s for s in window.spans if s.id not in evicted_ids] return window def run_edit_pass(window: ContextWindow) -> ContextWindow: try: return self_prune(window) except PruningGradientInversion as e: # Do not retry with the same model; the committed plan biases the summary. raise PruningGradientInversion( f"Edit pass aborted and must be escalated to an external controller: {e}" ) from e ```