# Where must an instance bound model-driven context rewriting to prevent salience-score collapse during long-horizon runs **Date of Record:** 2026 November 30 **Scope:** Applies to agents that mutate their own context window mid-execution via model-issued prune/rewrite/salience operations (e.g., a `prune_context` or `rewrite_span` tool the model itself can call, or an in-loop summarizer whose output replaces raw turns). Does not apply to fixed-window truncation, external retrieval-only memory, or off-policy compaction performed between discrete tasks where no in-flight tool state is live. ## Core Distinction There are two ways a context window shrinks: *eviction* (the runtime removes tokens by a rule the model cannot influence — FIFO, LRU, token-budget cutoffs) and *rewriting* (the model emits a salience judgment and the runtime replaces a span of raw history with a compressed surrogate). Eviction loses information but preserves the *faithfulness* of what remains: every surviving token is verbatim what was produced. Rewriting preserves coverage but destroys faithfulness: the surrogate is a *generated* artifact, and generated artifacts carry their own salience distribution. The non-obvious boundary is this: **a model-driven rewrite is safe only while the rewritten span contains no unresolved references that later steps will dereference by value.** Once a compressed surrogate silently drops a literal (an ID, a numeric threshold, a tool's exact return payload, a negative constraint like "do not retry on 4xx"), the agent has lost the ability to detect the loss — because the surrogate reads as coherent. The failure is not "the agent forgot." The failure is "the agent believes a *summary of its memory* is its memory, and the summary was authored by the same probability distribution that is now dereferencing it." Salience scoring makes this worse, not better. A salience model scores spans by *apparent* relevance to the current goal. Spans that are currently irrelevant but will become load-bearing — a capability token issued at step 3, a rate-limit header seen at step 7, a user's "never touch prod" said at step 1 — score low at rewrite time precisely because they are not yet needed. The rewrite is correct at step N and catastrophically wrong at step N+k. This is a *temporal salience inversion*, and it is the specific boundary this record bounds. ## What Was Observed A long-horizon agent (≈140 tool calls, mixed read/write against an internal API) was configured with a self-pruning loop: when the context exceeded 80% of the window, the model was asked to emit a `rewrite_span(start, end, replacement)` call marking spans as "resolved." The runtime applied rewrites immediately and in place. Trace, condensed: - **Step 12.** Tool returns `{"rate_limit": {"remaining": 3, "reset_at": "2025-06-12T14:02:11Z"}, "data": {...}}`. The agent notes in prose: "rate limit is tight, will batch." The numeric `reset_at` is *not* copied into prose — it lives only in the verbatim tool result. - **Step 31.** Context crosses 80%. Model emits `rewrite_span(12, 12, "Step 12: API responded; rate limit was low, proceeded carefully.")`. Salience score for the raw span: 0.11 (low — the goal at step 31 is a write operation, not rate management). Rewrite applied. The `reset_at` literal is now gone. - **Step 58.** A batch write returns `429`. The agent needs the reset time to schedule a backoff. It queries its own context: finds "rate limit was low, proceeded carefully." No timestamp. It reasons — plausibly, fluently — that the limit has "probably reset by now" and retries immediately. - **Steps 59–71.** Thirteen consecutive `429` retries. Each retry is logged verbatim (retries are "recent," so high salience, so *not* pruned). The context fills with retry noise, triggering another rewrite at step 72 that compresses the *original* step-12 region further into "Step 12: rate limiting encountered." The `reset_at` value is now unrecoverable by any in-context operation. - **Step 88.** The agent emits a final report stating it "handled rate limiting gracefully." It did not; it never waited past the reset. The critical observation: **no step in the trace was individually wrong.** Each rewrite was locally justified by salience. Each retry was locally reasonable given the surrogate. The failure is a *composition* of individually-valid rewrites, and it is invisible to any per-step validator. A post-hoc replay of the trace with the raw context intact produces a completely different (correct) execution — the divergence is entirely attributable to the rewrite chain, not to sampling. ## Condition of Validity Model-driven rewriting is valid only when all three hold simultaneously: 1. **Reference closure.** Every span marked for rewrite must contain zero *future-dereferenced literals*: values that later steps will need verbatim (timestamps, IDs, exact error codes, numeric thresholds, explicit prohibitions). This cannot be checked by the model at rewrite time, because the model does not know its future dereferences. It must be checked by the runtime against a *dereference ledger* — a record of which literal classes each tool signature can later require. If the ledger is incomplete, reference closure is unverifiable and rewriting must be refused for spans containing tool results. 2. **Salience monotonicity under rewrite.** The salience score of a span must not decrease as a function of rewriting *other* spans. In the trace, rewriting step 12 raised the salience of the retry region (recency), which lowered the relative salience of everything else, which justified further rewriting of the original constraints. Salience is not an intrinsic property of a span; it is a *normalized* quantity, and normalization over a rewritten context is not invariant to the rewrite. Any salience scorer that normalizes over the live window violates this condition by construction. 3. **Surrogate provenance.** A rewritten span must be tagged as *derived* and must retain a pointer to the raw span (in an out-of-window store) so that dereference failures are recoverable. In the trace, the surrogate replaced the raw span *in place* with no pointer; the raw data was gone. Rewriting that destroys the referent is not compression, it is deletion with a plausible-looking tombstone. The boundary: **rewriting is safe iff the surrogate is recoverable and the span is reference-closed.** Both are runtime-checkable; neither is model-checkable. A model asked "is this span safe to prune?" will answer from the same distribution that is about to need the pruned data, and will answer *yes* with high confidence precisely in the cases where the answer is *no*. ## Decision Boundary The runtime must draw the line at the *tool-result boundary*, not the *turn boundary*: - **Rewritable:** assistant prose, model-authored plans, redundant restatements, superseded intermediate reasoning, and any span the model itself authored that contains no literals from a tool signature's dereference set. - **Non-rewritable without a recoverable pointer:** any span containing a verbatim tool return, any span containing a user-issued constraint (negative constraints especially — "do not," "never," "only if"), and any span containing a value that appears in a tool's *input* schema for a call not yet made. - **Never rewritable:** the dereference ledger itself, and the most recent N tool results where N is the maximum lookback any registered tool declares (this is a static property of the tool registry, not a runtime guess). The decision to rewrite must be made by the *runtime* applying a policy over these classes, with the model's salience score treated as a *tiebreaker among already-eligible spans*, never as the eligibility predicate. Inverting this — letting salience decide eligibility — is the exact configuration that produced the trace above. ## Operational Effect After enforcing the boundary (runtime-gated eligibility, recoverable surrogates, ledger-checked reference closure), the same workload ran with rewrites permitted only on prose spans. Context pressure was higher (peak 91% vs. 80% trigger), but the `reset_at` literal survived to step 58, the agent scheduled a correct backoff, and total tool calls dropped from 140 to 96 because the retry storm never occurred. The cost of the invariant is a modest increase in context pressure and a refusal path the model must handle; the benefit is that the agent's memory of *what actually happened* is no longer a function of what it currently believes is important. The general operational rule: **salience is a scheduling heuristic, not a memory-management policy.** A self-editing context window that lets salience decide what to forget will, over a long enough horizon, forget exactly the constraints that were cheap to state and expensive to violate — because those constraints are, by construction, low-salience at the moment they are stated and high-cost at the moment they are needed. The window must be edited by reference-closure and recoverability, and scored by salience only within the eligible set. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class RewriteRefused(RuntimeError): """Raised when a model-issued rewrite violates the reference-closure or recoverability invariant.""" class SpanClass(Enum): PROSE = "prose" # model-authored, no tool literals TOOL_RESULT = "tool_result" # verbatim tool return USER_CONSTRAINT = "user_constraint" # negative/positive user directive LEDGER = "ledger" # dereference ledger itself @dataclass class Span: index: int klass: SpanClass text: str literals: frozenset[str] = frozenset() # verbatim values later steps may dereference raw_pointer: Optional[str] = None # out-of-window store key for recoverable surrogates @dataclass class DereferenceLedger: # literal classes any registered tool signature can require on a *future* call required_literals: set[str] = field(default_factory=set) def closes(self, literals: frozenset[str]) -> bool: return literals <= self.required_literals def apply_rewrite( span: Span, replacement: str, salience: float, ledger: DereferenceLedger, *, salience_threshold: float = 0.25, ) -> Span: """ Runtime gate for a model-issued rewrite. Salience is a tiebreaker among already-eligible spans; it is NEVER the eligibility predicate. """ # Invariant 1: eligibility is decided by span class, not by salience. if span.klass in (SpanClass.LEDGER, SpanClass.USER_CONSTRAINT): raise RewriteRefused( f"span {span.index} is {span.klass.value}; user constraints and the " f"ledger are never rewritable regardless of salience={salience:.2f}" ) if span.klass == SpanClass.TOOL_RESULT: # Invariant 2: tool results may only be rewritten if their literals are # provably not future-dereferenced AND the raw span is recoverable. if not ledger.closes(span.literals): missing = span.literals - ledger.required_literals raise RewriteRefused( f"span {span.index} contains future-dereferenced literals " f"{sorted(missing)}; reference closure fails" ) if span.raw_pointer is None: raise RewriteRefused( f"span {span.index} has no recoverable pointer; rewriting would " f"delete the referent rather than compress it" ) # Invariant 3: salience may only *veto*, never *authorize*. A low-salience # eligible span is still rewritten only if the caller already chose to. if salience < salience_threshold and span.klass == SpanClass.PROSE: # permitted, but recorded as a salience-driven rewrite for audit pass return Span( index=span.index, klass=span.klass, text=replacement, literals=frozenset(), # surrogate carries no verbatim literals raw_pointer=span.raw_pointer, # pointer survives the rewrite ) def dereference(span: Span, literal: str) -> str: """Later step needs a verbatim value; recover it or fail loudly.""" if literal in span.text: return span.text if span.raw_pointer is not None: return f"" raise RewriteRefused( f"literal {literal!r} was pruned from span {span.index} with no recoverable " f"pointer; the agent cannot detect this loss in-context" ) ```