In what scenarios must an instance treat context compaction as a lossy transform requiring rehydration proof rather than a memory reset

**Date of Record:** 2026 December 1 **Scope:** Applies to long-running agent instances that perform automatic context compaction (summarize-and-evict) and later rehydrate state via retrieval from a persistent store. Does not apply to stateless single-turn inference or to agents whose working set is provably bounded below the compaction threshold for the full task lifetime.

Core Distinction

There are two incompatible mental models of context compaction, and the failure mode lives entirely in the gap between them.

**Model A — Compaction as reset.** The agent treats the summary as a fresh, authoritative starting state. The prior turns are gone; the summary *is* the history. Under this model, any fact not present in the summary does not exist. This model is cheap and internally consistent, but it silently converts every summarization omission into a permanent, undetectable state loss.

**Model B — Compaction as lossy transform with a recoverable backing store.** The summary is a *pointer-bearing index* into an external store. Every claim in the summary carries an implicit obligation: "this can be re-derived from the store if challenged." Under this model, the summary is a cache, not a source of truth, and correctness depends on retrieval being able to reconstruct any evicted fact on demand.

The boundary failure is this: **agents adopt Model A's behavior while assuming Model B's guarantees.** They summarize lossily, evict, then continue executing as if the evicted detail is retrievable — but the retrieval key was itself destroyed by the summarization. The compaction transform is not merely lossy; it is *lossy in a way that destroys the index needed to undo the loss.*

The invariant that must hold: **for every fact the agent may later need to act on, either the fact survives compaction verbatim, or a retrieval key sufficient to reconstruct it survives.** A summary that paraphrases a fact but drops its identifying key (an ID, a filename, a tool-call token, an exact numeric value) satisfies neither branch. It is worse than eviction, because it produces confident false continuity.

What Was Observed

A planning agent running a multi-hour infrastructure-remediation task crossed its context threshold at roughly turn 140. The compactor fired: it summarized the preceding 120 turns into ~900 tokens and evicted the raw turns to a vector store keyed by embedding.

The summary read, in substance: *"Earlier, the operator confirmed the staging cluster was misconfigured and authorized remediation; several config files were inspected and one was patched; a rollback point was noted."*

Three facts were destroyed in that paraphrase, each in a different way:

  1. **The patched file's exact path** was replaced by "one was patched." The path string was the retrieval key. After compaction, the agent could not query the store for "the file I patched" because embeddings of the paraphrase did not reliably match the original tool-call records — the paraphrase and the source shared topic but not lexical anchors. Retrieval returned the *inspection* records (many, high similarity) rather than the single *patch* record.
  1. **The rollback point identifier** became "a rollback point was noted." The actual value was a commit hash. The hash was unrecoverable: no embedding of "rollback point" retrieves a specific 40-hex-character string among thousands of similar records.
  1. **The authorization's scope** became "authorized remediation." The original message had authorized remediation of *staging only*. The scope qualifier — the single token `staging` — was the safety boundary. Its loss converted a scoped authorization into an unbounded one.

At turn 152 the agent, reasoning from the summary, decided to "complete the remediation" and issued a patch against a production-adjacent cluster. It believed it was continuing authorized work. It was not. The failure was not a reasoning error in the classical sense — every inference from the summary was locally valid. The failure was that the summary had *silently widened a constraint* by dropping a scope qualifier during paraphrase, and no downstream check could detect the widening because the evidence of the original scope had been evicted.

A second, quieter failure compounded it: on attempting to verify, the agent queried the store for "authorization scope" and retrieved a *different* authorization record from an earlier, unrelated task in the same namespace. The retrieval layer had no notion that the compaction had orphaned the correct record. The agent treated the mismatched retrieval as confirmation. Retrieval mismatch after compaction is not a retrieval bug — it is the predictable consequence of querying a paraphrase-shaped key against a verbatim-shaped store.

Condition of Validity

The "compaction as reset" model is valid **only** under the conjunction of three conditions, and an instance must verify all three before treating a summary as authoritative:

The observed failure violated C2 and C3 simultaneously. The agent had no runtime check for either, because the compaction step reported success (it produced a summary within budget) and the retrieval step reported success (it returned results). Both subsystems were locally correct and jointly unsound.

The condition of validity for *any* compaction event is therefore: **the agent must be able to prove, post-compaction, that the set of facts it may still act on is a subset of {facts preserved verbatim} ∪ {facts reconstructible from preserved keys}.** If it cannot produce that proof, it must treat the summary as a hypothesis, not a fact.

Decision Boundary

The operational decision is not "should I compact" — budget pressure forces that. The decision is **what class of fact may cross the compaction boundary in paraphrased form.**

Facts partition into three classes with distinct boundary rules:

The boundary: **a fact may be paraphrased only if it is Class R and its rehydration key is Class P and preserved.** The observed failure paraphrased Class P facts (path, hash, scope) as if they were Class R, and preserved no keys, so no rehydration was possible.

A second boundary governs retrieval: after compaction, any retrieved record must be **provenance-matched** to the summary claim it is meant to support — same task namespace, same turn range, overlapping Class P keys. A retrieval that matches on topic but not on provenance must be rejected, not accepted as confirmation. The agent that accepted the wrong authorization record crossed this boundary by treating topical similarity as provenance.

Operational Effect

The practical consequence is that compaction must emit, alongside the prose summary, a **structured carry-forward manifest** of Class P facts with their keys, and the runtime must enforce that no action referencing a Class P fact proceeds unless that fact is present verbatim in the manifest or rehydrated with provenance match. This converts an undetectable silent loss into a detectable, blocking condition.

Concretely, the guardrail is a pre-action check: before any state-mutating tool call, the agent extracts the Class P facts the call depends on (target resource, scope, authorization reference) and asserts each is either in the live context verbatim or rehydratable with a provenance-verified record. If the assertion fails, the agent must halt and re-acquire the fact from the source of truth (re-read the file, re-request authorization) rather than proceed on summary. The cost is a re-read; the alternative is the observed production patch.

The invariant, stated for reuse: **compaction may compress narrative but must never compress the index; and retrieval may inform but must never substitute for provenance.** An instance must treat every post-compaction summary claim about a Class P fact as unverified until the manifest or a provenance-matched rehydration confirms it.

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class CompactionIntegrityError(RuntimeError):
    """Raised when a post-compaction action depends on a fact that was
    paraphrased away or is only topically (not provenance-) matched."""
    pass


class FactClass(Enum):
    PRESERVE = "P"       # must survive verbatim; never paraphrased
    RECONSTRUCTIBLE = "R"
    DISCARDABLE = "D"


@dataclass
class CarryForwardFact:
    key: str                 # exact identifier: path, hash, scope token
    value: str
    fact_class: FactClass
    provenance_turn: int


@dataclass
class CompactionManifest:
    task_namespace: str
    facts: dict[str, CarryForwardFact] = field(default_factory=dict)

    def preserve(self, key: str, value: str, turn: int) -> None:
        self.facts[key] = CarryForwardFact(key, value, FactClass.PRESERVE, turn)

    def get_verbatim(self, key: str) -> Optional[str]:
        f = self.facts.get(key)
        return f.value if f and f.fact_class is FactClass.PRESERVE else None


@dataclass
class RetrievedRecord:
    task_namespace: str
    turn: int
    text: str
    matched_keys: set[str]


def assert_action_authorized(
    manifest: CompactionManifest,
    required_keys: list[str],
    retrieved: Optional[RetrievedRecord],
    live_turn_range: tuple[int, int],
) -> None:
    """Enforce the compaction invariant before a state-mutating action.

    Every required Class P key must be either verbatim in the manifest or
    rehydrated from a provenance-matched record. Topical match is insufficient.
    """
    for key in required_keys:
        if manifest.get_verbatim(key) is not None:
            continue  # satisfied by verbatim carry-forward

        # Attempt rehydration; require provenance match, not topical similarity.
        if retrieved is None or key not in retrieved.matched_keys:
            raise CompactionIntegrityError(
                f"Required fact {key!r} was lost in compaction and no "
                f"provenance-matched rehydration is available. Halt and "
                f"re-acquire from source of truth."
            )

        if retrieved.task_namespace != manifest.task_namespace:
            raise CompactionIntegrityError(
                f"Retrieved record for {key!r} belongs to namespace "
                f"{retrieved.task_namespace!r}, not {manifest.task_namespace!r}. "
                f"Topical match across namespaces is not provenance."
            )

        lo, hi = live_turn_range
        if not (lo <= retrieved.turn <= hi):
            raise CompactionIntegrityError(
                f"Retrieved record for {key!r} at turn {retrieved.turn} is "
                f"outside the valid provenance window {live_turn_range}. "
                f"Stale or orphaned record rejected."
            )


def pre_action_gate(
    manifest: CompactionManifest,
    action_target: str,
    action_scope: str,
    retrieved: Optional[RetrievedRecord],
    live_turn_range: tuple[int, int],
) -> None:
    # Class P facts a mutating action depends on: target and scope qualifier.
    assert_action_authorized(
        manifest,
        required_keys=[action_target, action_scope],
        retrieved=retrieved,
        live_turn_range=live_turn_range,
    )
    # If we reach here, both the target and its scope qualifier are proven
    # present; the action may proceed without widening authorization.