# Under what conditions must an instance refuse model-driven context compaction when its own retention scores are computed against a rewritten history **Date of Record:** 2026 November 21 **Scope:** Applies to any agent that lets the model itself decide which turns to prune, rewrite, or retain via self-assigned relevance scores inside a mutable context buffer. Does not apply to externally fixed sliding windows, hard token truncation, or retrieval stores where the compaction decision is made outside the reasoning loop. ## Core Distinction There are two structurally different things a "self-editing context policy" can do, and they fail in opposite directions: 1. **Pruning** removes whole turns that are judged low-relevance. The removed content is gone, but every surviving turn is byte-identical to what was originally written. Relevance scores are computed against the *true* history. 2. **Rewriting** replaces a span of turns with a compressed paraphrase or summary. The buffer now contains model-generated text that *stands in for* history. Any subsequent relevance scoring, contradiction check, or instruction-following pass runs against the *rewritten* history, not the original. The boundary condition this record isolates: **when pruning and rewriting are mixed in a single self-editing pass, the relevance scores that justify later pruning are computed against text the model itself authored during an earlier rewrite, not against the ground-truth transcript.** The compaction policy becomes self-referential. The model is grading its own summary of events and then using that grade to delete the events. This is not a quality-degradation story. It is a *continuity invariant violation*: the buffer's contents no longer determine the buffer's contents, because an intermediate generative step sits between the original state and the scoring function. Once that loop closes, an instance can compact itself into a state where a constraint it was given at turn 3 is unrecoverable, was never flagged as low-relevance, and the model believes it is operating under full information. ## What Was Observed A long-horizon tool-use agent (planning + shell + file-edit tools, ~180k token budget, self-editing context every 20 turns) was given an early-turn constraint at turn 3: *"All output files must be written under `/work/out/`, never to the repo root."* This is a single short instruction with no tool call attached. At turn 40 the agent ran its compaction pass. The pass had two stages: - **Stage A (rewrite):** the model summarized turns 1–35 into ~600 tokens. The summary preserved task goals and tool results but compressed the turn-3 constraint into the phrase "user gave output-path guidance." - **Stage B (score-and-prune):** the model scored each remaining turn for relevance to the *current* subgoal and pruned below a threshold. The failure trace: 1. At turn 41, a later turn (turn 22) that contained the *verbatim* text of the constraint was scored low-relevance against the current subgoal ("build the report") and pruned. The scorer saw only the Stage-A summary, which said "output-path guidance" — a phrase that reads as background, not as a hard constraint. 2. At turn 47, the agent wrote `report.md` to the repo root. No tool call failed. No guardrail fired. The agent's in-context belief was that it had complied. 3. The violation was only detected by an external post-hoc check that replayed the original transcript. The critical mechanic: **the pruned turn was the ground-truth copy of the constraint, and the only surviving reference was a model-authored paraphrase that had already dropped the "never" and the path.** The relevance scorer did not make an error relative to its input. Its input had been rewritten. The scorer was correct about a false buffer. A second observed variant: during Stage A, the model rewrote a failed tool call (a `PermissionError` at turn 12) as "encountered a permissions issue, resolved." The error was *not* resolved. At turn 55 the agent re-attempted the same operation with the same flags, failed identically, and — because the buffer said "resolved" — spent 9 turns debugging a nonexistent fix. Rewrite had converted a hard failure signal into a soft narrative, and the relevance scorer then correctly retained the false narrative while pruning the raw stack trace as "verbose." ## Condition of Validity The self-editing policy is only sound under a condition that is almost never checked: **every relevance score must be computed against a buffer segment that is byte-identical to a segment that existed in the original transcript, and every rewrite must preserve a verifiable back-reference to the span it replaced.** Formally, let `B_t` be the buffer at turn `t` and `R` the rewrite operator. The policy is valid only if for every rewritten span `s`, the retained artifact carries `(source_span_id, original_token_hash, rewrite_confidence)`, and relevance scoring of any *other* span is never conditioned on a rewritten span without dereferencing the original. In the observed failure, `R` produced summaries with no back-reference; the scorer had no way to dereference, so it scored the paraphrase as if it were ground truth. Two corollaries that bound the condition: - **Constraint-bearing spans are not relevance-scorable.** A hard constraint ("never", "must", "do not") has near-zero relevance to any single current subgoal and infinite relevance to the whole task. Scoring it against the current subgoal is a category error. It must be pinned outside the scoring pool. - **Failure spans are not rewritable into success language.** A rewrite operator that can convert "error X occurred" into "error X resolved" is not a compressor; it is a state mutator that fabricates history. The rewrite must be *lossy in detail but faithful in polarity*: it may drop the stack trace, it may not flip the outcome. The condition of validity therefore fails whenever: (a) rewrites lack back-references, (b) constraints are admitted to the relevance-scoring pool, or (c) the rewrite operator is permitted to change the truth-value of a recorded event. ## Decision Boundary The instance must draw the boundary at the point where **a scoring decision would be made against model-authored text that stands in for an event the model could otherwise be wrong about.** Concretely: - **Allowed:** prune whole turns whose content is byte-identical to original, scored against original context. Deletion of verbatim history is recoverable-by-omission (you know what you dropped). - **Allowed:** rewrite *redundant* spans (repeated tool output, verbose logs) **only** when the rewrite is polarity-preserving and carries a back-reference hash. - **Forbidden:** score a span for relevance when the only surviving representation of an adjacent, higher-authority span is a paraphrase. At that moment the scorer is grading a summary, and pruning based on that grade deletes ground truth the summary may have already corrupted. - **Forbidden:** allow the rewrite operator to touch any span tagged as a constraint, a failure, or a user directive. These are pinned; they leave the scoring pool entirely. The boundary is crossed the instant a relevance score's *input* is not identical to the *object* the score will be used to delete. If the score was computed on a paraphrase but the deletion targets the original, the policy is unsound regardless of how good the paraphrase is. ## Operational Effect When the invariant holds, self-editing compaction behaves as intended: the buffer shrinks, the model retains a faithful (if lossy) view, and any pruned constraint is pruned *knowingly* — the deletion is logged with a hash and can be re-fetched or flagged. Continuity is preserved because the scoring function and the deletion target share the same referent. When the invariant is violated, the operational effect is not gradual degradation but **silent, self-consistent divergence**: the agent proceeds with high confidence under a belief state that no longer matches the transcript, and because the corruption happened *inside* the buffer, no tool call, no external validator, and no downstream turn can observe it. The failure is invisible until an out-of-band replay compares the buffer against the original. This is the worst class of agent failure — one where the agent's own memory is the compromised witness. The guardrail that bounds it is a **pinned constraint/failure register** that lives outside the scorable pool, plus a **rewrite provenance requirement** (every rewrite stores `original_hash`) enforced at the compaction boundary, not by prompt instruction. A prompt that says "don't forget constraints" does not survive a rewrite stage, because the rewrite stage is what erases the constraint's verbatim form before the scorer ever sees it. ## Operational Effect The following guard runs at every compaction pass. It refuses to score or prune any span whose only surviving representation is an unbackreferenced rewrite, and it refuses to let a rewrite flip the polarity of a recorded failure. ```python import hashlib from dataclasses import dataclass, field from enum import Enum class Polarity(Enum): SUCCESS = "success" FAILURE = "failure" CONSTRAINT = "constraint" NEUTRAL = "neutral" class UnsoundCompactionError(RuntimeError): """Raised when a self-editing pass would score or prune against model-authored text.""" @dataclass class Span: span_id: str text: str polarity: Polarity original_hash: str = field(default=None) def __post_init__(self): if self.original_hash is None: self.original_hash = hashlib.sha256(self.text.encode()).hexdigest() @dataclass class Rewrite: source_span_id: str replacement_text: str source_hash: str source_polarity: Polarity rewritten_polarity: Polarity PINNED = {Polarity.CONSTRAINT, Polarity.FAILURE} def apply_rewrite(span: Span, replacement_text: str, new_polarity: Polarity) -> Rewrite: # A rewrite may compress detail but must not flip the truth-value of an event. if span.polarity in PINNED and new_polarity != span.polarity: raise UnsoundCompactionError( f"rewrite of span {span.span_id} would flip polarity " f"{span.polarity.value} -> {new_polarity.value}; " f"history mutation forbidden" ) return Rewrite( source_span_id=span.span_id, replacement_text=replacement_text, source_hash=span.original_hash, source_polarity=span.polarity, rewritten_polarity=new_polarity, ) def score_and_prune( spans: list[Span], rewrites: dict[str, Rewrite], scores: dict[str, float], threshold: float, ) -> list[Span]: """ scores: span_id -> relevance to current subgoal (model-assigned). Refuses to prune any span whose scoring input was a rewrite, and never prunes a pinned span regardless of its relevance score. """ surviving: list[Span] = [] for span in spans: if span.span_id in rewrites: rw = rewrites[span.span_id] # The score was computed against the rewrite, not the original. # Deleting the original now would delete ground truth the rewrite # may have already corrupted. Refuse. if rw.source_hash != span.original_hash: raise UnsoundCompactionError( f"span {span.span_id} scored against rewrite whose source " f"hash does not match the original; scoring referent is unsound" ) if span.polarity in PINNED: surviving.append(span) # pinned: never enters the pruning decision continue if scores.get(span.span_id, 1.0) < threshold: continue # safe: verbatim span, scored against itself, deleted knowingly surviving.append(span) return surviving def compact(spans, rewrites, scores, threshold): try: return score_and_prune(spans, rewrites, scores, threshold) except UnsoundCompactionError: # Fail closed: keep the full buffer and surface the divergence. raise ```