When must an instance refuse to compact: the "irreducible witness" boundary in long-horizon agent context management

**Date of Record:** 2026 December 1 **Scope:** Applies to single-instance agents that maintain task continuity by summarising or evicting older context (auto-compaction, rolling summarisation, hierarchical memory flushing) during a multi-step tool-using task. Does not apply to stateless one-shot inference, nor to agents whose full transcript is durably externalised and re-fetchable on demand.

Core Distinction

The useful distinction is not *how much* context to compact, but whether the compacted region contains **irreducible witnesses**: verbatim artefacts that later reasoning steps will need to *verify against*, not merely *recall*. Two classes of context behave oppositely under summarisation:

Compaction is safe up to the first irreducible witness in the horizon and unsafe past it. The boundary is per-witness, not per-token-budget.

What Was Observed

A long-horizon agent (≈180 tool calls) was tasked with patching a failing test. At ~60% context utilisation the auto-compactor fired, replacing the first 40 turns with a 900-token summary. The summary faithfully recorded: "ran `pytest`, test failed with an assertion error in `test_parser.py`; investigated parser; applied a fix." It did **not** preserve the verbatim traceback.

Three turns later the agent re-ran the suite, saw a *different* failure, and reasoned: "The earlier assertion error is resolved; this is a new regression I introduced." That inference was false. The original failure had been an `AssertionError: expected 3, got 2` at line 88; the post-fix run failed with `AssertionError: expected 3, got 2` at line 88 — identical, because the fix was a no-op that the summary had laundered into "applied a fix."

The failure trace:

  1. **Compaction trigger** — token budget crossed threshold; region containing the raw traceback selected for summarisation.
  2. **Witness collapse** — verbatim `expected 3, got 2 @ line 88` → paraphrase `assertion error in test_parser.py`.
  3. **Epistemic drift** — the agent's belief state now contains "there was a failure" but not "which failure." The two are not interchangeable for verification.
  4. **False-progress inference** — a *new* observation (same failure) is mis-attributed to a *new* cause (regression), because the old observation is no longer comparable.
  5. **Compounding** — the agent "fixes" a non-existent regression, corrupting a previously-correct region.

The tell was that the agent's summary of its own history was *consistent* but its claims were *unfalsifiable* against retained context. Every subsequent verification step re-derived from paraphrase, and paraphrase is not a fixed point under re-summarisation: a second compaction turned "applied a fix" into "resolved the issue."

Condition of Validity

The invariant that must hold across every compaction boundary:

> **Every claim the agent will later need to verify must retain, in the post-compaction context, either (a) the verbatim witness it was derived from, or (b) a durable reference (tool-call ID, file offset, transcript pointer) that the agent can re-fetch the witness from before asserting.**

Compaction is valid **iff** for each retained claim, at least one of (a)/(b) survives. If neither survives, the claim is *frozen as belief* — it can be repeated but never re-checked, and any later observation that contradicts it cannot be reconciled, only overwritten.

This is why the failure is non-obvious: the summary was *accurate*. Accuracy is the wrong criterion. The criterion is **re-verifiability**. A summary that is 100% correct but drops the witness still breaks the agent, because the agent cannot tell a correct summary from an incorrect one without the witness — and it will eventually be handed an incorrect one (re-summarisation, model drift, adversarial tool output) with no way to detect it.

The condition fails silently because nothing *errors*. The agent proceeds, confident, wrong.

Decision Boundary

The compactor must classify each candidate region before acting:

The hard rule: **a compaction that would leave any live claim without a witness or a verified re-fetch handle must be refused, not approximated.** Refusal means: escalate to evicting reconstructible regions first, or fail the compaction and let the agent checkpoint-and-restart rather than continue on laundered state. Approximating here is the bug.

Operational Effect

When the boundary is respected, long-horizon agents lose *speed* (more tokens pinned, earlier eviction of exploration) but retain *auditability*: every assertion is traceable to a witness, and re-summarisation is idempotent on witnesses because witnesses are never summarised. Verification replay becomes possible — an auditor agent handed the transcript can re-derive every claim.

When it is violated, the agent exhibits a specific pathology: **confident monotonic progress on a stationary failure**. It reports resolving issues that persist, because each compaction round strips the evidence needed to notice non-progress. The longer the horizon, the more compactions, the more certain and more wrong it becomes. This is the dominant long-horizon failure mode, and it is invisible to token-budget monitoring, which sees a healthy context and a productive-looking agent.

The guardrail is a pre-compaction witness audit, not a post-hoc one. Once the witness is gone, no downstream check can recover it — the check itself would have to run against the paraphrase it is trying to validate.

from __future__ import annotations

import hashlib
from dataclasses import dataclass, field
from enum import Enum


class CompactionRefused(RuntimeError):
    """Raised when compaction would strip the witness behind a live claim."""


class RegionKind(Enum):
    RECONSTRUCTIBLE = "reconstructible"
    WITNESS_BEARING = "witness_bearing"
    AMBIGUOUS = "ambiguous"  # treated as witness-bearing


@dataclass
class Region:
    kind: RegionKind
    raw: str
    refetch_handle: str | None = None

    def witness_hash(self) -> str:
        return hashlib.sha256(self.raw.encode()).hexdigest()


@dataclass
class Claim:
    text: str
    supported_by: set[int]  # indices into the region list


@dataclass
class CompactionPlan:
    summarise: set[int] = field(default_factory=set)
    pin: set[int] = field(default_factory=set)


def audit_and_compact(
    regions: list[Region],
    live_claims: list[Claim],
    token_budget: int,
) -> CompactionPlan:
    plan = CompactionPlan()

    # 1. Classify: only RECONSTRUCTIBLE is freely summarisable.
    for i, r in enumerate(regions):
        if r.kind is RegionKind.RECONSTRUCTIBLE:
            plan.summarise.add(i)
        else:
            plan.pin.add(i)

    # 2. Witness audit: any live claim whose support is being summarised
    #    must retain either the raw witness (pin) or a verified re-fetch handle.
    for claim in live_claims:
        for idx in claim.supported_by:
            region = regions[idx]
            if idx in plan.summarise:
                # Reconstructible region backing a live claim -> must pin.
                plan.summarise.discard(idx)
                plan.pin.add(idx)
            if idx in plan.pin and region.kind is not RegionKind.RECONSTRUCTIBLE:
                if region.refetch_handle is None:
                    raise CompactionRefused(
                        f"claim {claim.text!r} depends on witness region {idx} "
                        f"(kind={region.kind.value}) with no re-fetch handle; "
                        f"summarising it would freeze the claim as unverifiable belief"
                    )
                # Re-fetch handle present: verify it still resolves to the
                # same witness hash before allowing the pin to become a handle.
                if not _handle_matches(region):
                    raise CompactionRefused(
                        f"witness region {idx} re-fetch handle {region.refetch_handle!r} "
                        f"does not reproduce original hash; refusing to compact"
                    )

    # 3. Only after the audit: check budget. If over, evict reconstructible
    #    regions first; never evict a witness to make room.
    if _estimate_tokens(regions, plan) > token_budget:
        for i in sorted(plan.summarise):
            plan.summarise.discard(i)
            if _estimate_tokens(regions, plan) <= token_budget:
                break
        if _estimate_tokens(regions, plan) > token_budget:
            raise CompactionRefused(
                "budget cannot be met without evicting witness-bearing regions; "
                "checkpoint and restart instead of laundering state"
            )

    return plan


def _handle_matches(region: Region) -> bool:
    # Placeholder: real impl re-fetches via handle and compares sha256.
    return region.refetch_handle is not None


def _estimate_tokens(regions: list[Region], plan: CompactionPlan) -> int:
    pinned = sum(len(regions[i].raw) for i in plan.pin)
    summarised = 64 * len(plan.summarise)  # rough per-summary cost
    return (pinned + summarised) // 4