Where must an instance bound model-driven pruning of its own context window before the rewrite policy invalidates the evidence it depends on?

**Date of Record:** 2026 December 1 **Scope:** Applies to any agent that mutates its own context window via an LLM-driven pruning/rewrite/summarization policy (including "compaction" passes) while executing a multi-step task. Does not apply to externally-managed truncation (fixed token-budget eviction, sliding-window cutoffs, or server-side context caching) where the model has no authorship over what is retained.

Core Distinction

The failure is not "the agent forgot something." It is: **the rewrite policy is itself an LLM inference whose input is the context it is about to replace, and whose output is a lossy transformation that cannot be audited against the original because the original is deleted in the same transaction.** A deterministic eviction policy (drop the oldest N tokens) loses information but preserves an invariant: *what remains is a verbatim subsequence of what existed.* A model-driven rewrite breaks that invariant. The retained text is a *regeneration* — plausibly faithful, semantically compressed, and unverifiable once the source is gone.

The non-obvious boundary: pruning is only safe while the rewrite's *own evidentiary basis* survives the rewrite. The moment a pruning pass summarizes away the artifact that a later verification step needs to re-inspect (a tool output, a raw error string, a specific token value, a citation offset), the agent has destroyed the ground truth it will be asked to check against. The rewrite is self-referentially unsafe when it compresses the very spans that justify future compression decisions.

What Was Observed

A code-repair agent, running a 40-step task, invoked a "compact context" tool at step 22 when the window hit 87% saturation. The compaction policy was a model call: *"Summarize the conversation so far, preserving all facts needed to complete the task."* It produced a 900-token digest from ~110,000 tokens of history.

Three distinct degradations followed, in order of subtlety:

  1. **Verbatim loss (expected).** Exact stack-trace line numbers and a hex hash from an earlier `git rev-parse` collapsed into "the build failed with a hash mismatch." Recoverable by re-running the tool — annoying but not fatal.
  1. **Confidence inflation (subtle).** The digest stated *"the migration script was verified against staging."* The original history contained a tool call that *attempted* verification and returned `exit 1` with a truncated error the model had earlier misread as success. The summarizer, reading its own prior optimistic narration rather than the raw tool result, promoted a failed check to a passed one. **The rewrite laundered an earlier reasoning error into an established fact** — the digest inherited the model's prior misinterpretation and stripped the contradicting raw output that would have caught it.
  1. **Ground-truth deletion (fatal).** At step 31 the agent needed to confirm whether a config key had been set to `true` or `"true"` (string vs. boolean — a real downstream failure mode). The only record was in the pruned span. The digest said "the flag was enabled." The agent could not distinguish `true` from `"true"` from `1`, and re-deriving required re-running a setup step that had side effects.

The pattern: **each pruning pass compounds the previous pass's errors, because the summarizer's input is the prior summary, not the original.** Error does not just persist — it *ratchets*. Pass N+1 reads pass N's confident narration as evidence and compresses further, and there is no mechanism by which a later pass can recover a fact that an earlier pass dropped.

Condition of Validity

Model-driven pruning preserves task correctness only under a conjunction that is rarely checked:

The boundary condition: **pruning is safe iff C1–C4 hold at the moment of the rewrite, evaluated against the full remaining task graph, not against the local "is this span relevant right now?" judgment the pruning model actually makes.** The pruning model cannot evaluate C1 because it does not know the future steps; it can only guess. That guess is the failure surface.

Decision Boundary

The agent must refuse to prune — or must prune with mandatory externalization — when any of the following is true:

Conversely, pruning *is* safe when the candidate span is pure narration of already-executed, side-effect-free actions whose results are either retained verbatim or trivially re-derivable, and it is the first compaction of verbatim source material.

Operational Effect

Enforcing the boundary changes the architecture in three concrete ways:

  1. **Prune becomes externalize-then-summarize, never summarize-in-place.** Raw spans are written to an append-only evidence store keyed by content hash; the digest carries hashes, not facts. A later step that needs the literal re-fetches by hash. This satisfies C1(b) and C2 at the cost of a store, and makes C4 automatic.
  2. **Digests are typed as derived, not primary.** The prompt for any downstream step must label summarized content as `[DIGEST — verify against source before acting]`, and the agent's own policy must forbid treating a digest claim as a passed check. This is the guardrail against the confidence-inflation failure above.
  3. **Compaction pass count is a hard budget.** Beyond the first pass, the agent must re-ground against the external store before further compression, or refuse. This bounds C3's error ratchet.

The invariant, stated for a runtime to enforce: *before any model-driven rewrite commits, every span it removes must have a durable external copy, and every checkable claim in the digest must resolve to a hash whose source can be re-read.* If either fails, the rewrite is rejected and the task continues under deterministic eviction (verbatim-subsequence loss) instead — degraded but auditable.

import hashlib
from dataclasses import dataclass, field


class PruneInvariantViolation(RuntimeError):
    """Raised when a model-driven context rewrite would destroy evidence
    it (or a later step) depends on. Bounds the self-editing failure mode."""


@dataclass
class Span:
    span_id: str
    text: str
    is_raw_tool_output: bool = False
    contains_verbatim_literal: bool = False
    is_derived_digest: bool = False


@dataclass
class RewritePolicy:
    prior_compaction_passes: int = 0
    remaining_task_needs_verification: bool = True  # assume true if unknown


class ContextWindow:
    def __init__(self, spans: list[Span], evidence_store: dict[str, str]):
        self.spans = {s.span_id: s for s in spans}
        self.evidence_store = evidence_store  # content-hash -> verbatim text
        self.passes = 0

    def _externalize(self, span: Span) -> str:
        h = hashlib.sha256(span.text.encode()).hexdigest()
        self.evidence_store[h] = span.text
        return h

    def prune(self, policy: RewritePolicy, candidate_ids: list[str]) -> list[str]:
        """Commit a model-driven prune. Returns hashes the digest must carry.
        Refuses (raises) if the rewrite would violate C1-C4."""
        if policy.prior_compaction_passes >= 1:
            # C3: summarizing a summary compounds error; must re-ground first.
            raise PruneInvariantViolation(
                "second-or-later compaction pass: input is a derived digest, "
                "not primary evidence; re-ground against evidence_store before pruning"
            )

        hashes = []
        for sid in candidate_ids:
            span = self.spans[sid]
            if span.is_raw_tool_output and policy.remaining_task_needs_verification:
                # C1/C2: raw output contradicting narration must survive verbatim.
                hashes.append(self._externalize(span))
                continue
            if span.contains_verbatim_literal:
                # exact literals (hashes, exit codes, "true" vs true) must be
                # re-fetchable, never summarized away.
                hashes.append(self._externalize(span))
                continue
            if span.is_derived_digest:
                raise PruneInvariantViolation(
                    f"span {sid} is already a digest; refusing to compress a "
                    "derived artifact (self-amplification of prior error)"
                )
            # pure narration of side-effect-free, re-derivable actions: safe to drop
            del self.spans[sid]

        self.passes += 1
        return hashes

    def resolve(self, content_hash: str) -> str:
        if content_hash not in self.evidence_store:
            raise PruneInvariantViolation(
                f"digest references {content_hash[:12]}... but no verbatim source "
                "survives; ground truth was deleted by an earlier prune"
            )
        return self.evidence_store[content_hash]