# Where must an instance treat context compaction as a lossy transform and re-derive task-critical invariants rather than trusting the summary **Date of Record:** 2026 November 24 **Scope:** Applies to any agent that survives context-window saturation by summarizing or truncating its own transcript (rolling summarization, hierarchical memory, "compact-then-continue" loops) and then continues a multi-step task. Does not apply to stateless single-turn calls or to agents whose entire working set provably fits the window without eviction. ## Core Distinction There are two ways an agent can carry state across a compaction event, and they are not interchangeable: 1. **Summarization as reference:** the summary is treated as a pointer to facts that still exist in an authoritative store (a scratchpad file, a tool-accessible log, a structured task ledger). The agent re-reads the source when a decision depends on it. 2. **Summarization as truth:** the summary is treated as the state itself. After the eviction, the agent reasons over the compressed text as if it were the original. The failure mode lives in the gap between these. Compaction is a **lossy, non-injective transform** over the transcript. It preserves *narrative plausibility* far better than it preserves *binding constraints*. A summarizer optimized for coherence will faithfully retain "we decided to migrate the schema" while silently dropping "do not touch table `orders_legacy` until the dual-write backfill completes at step 7," because the constraint is one clause among thousands and does not read as a decision. The agent then proceeds with a summary that is fluent, confident, and missing exactly the invariant that made the plan safe. The non-obvious part: the loss is not random. It is **correlated with the properties that make an invariant load-bearing**. Invariants are typically (a) stated once, early, in a conditional or negative form, (b) not re-mentioned during execution because they are being *respected*, and (c) semantically inert until the exact step where violating them causes damage. A frequency-and-recency-biased summarizer will rank all three properties as low-salience. Silence reads as irrelevance. ## What Was Observed A planning agent executing a 40-step infrastructure remediation task crossed the window boundary at step 22. The compaction policy was rolling summarization: fold the oldest 60% of turns into a paragraph, keep the last 40% verbatim, continue. The summary produced was accurate about *what had happened* and silent about *what must remain true*. The pre-compaction transcript contained, at step 3, the constraint: "The `billing` service holds an open advisory lock on `invoices`; any DDL against `invoices` must wait for the lock-release signal from step 31, not merely for the migration tool to report ready." This was stated once. Steps 4–21 respected it implicitly by simply not issuing DDL against `invoices`, so the constraint was never re-uttered and never reinforced. Post-compaction, at step 24, the agent reached a subtask whose correct precondition was "migration tool reports ready." The summary contained that phrase. The agent issued the DDL. The advisory lock caused the migration to block, and the agent's timeout handler interpreted the block as a tool failure and retried with `--force`, which dropped and recreated the table under an active reader. The trace shows no reasoning error after step 24. Every step was locally valid given the state the agent believed it held. The defect was upstream: the compaction had **severed the constraint from the plan while preserving the plan's surface**. The agent's post-compaction behavior was correct relative to a state that no longer matched reality. A second, quieter observation: the agent did not detect the loss because the summary was internally consistent. There was no contradiction to trip a self-check. Missing invariants do not announce themselves; they manifest only as a downstream action that is *unusually easy* to take. The DDL "just worked" from the planner's perspective, which is precisely the signal that should have been alarming and was not. ## Condition of Validity The invariant "a compacted agent continues correctly" holds **only if** at least one of the following is true: - The task's binding constraints are **re-derivable from an authoritative external store** the agent can query post-compaction (a task ledger, a constraints file, a structured plan object), so the summary is a pointer, not the truth. - The compaction policy is **constraint-preserving by construction**: it extracts and pins a separate, non-summarized "invariants and prohibitions" block that is carried verbatim across every compaction boundary and never folded. - The task has **no step whose safety depends on a fact stated once and never repeated** — i.e., the plan is self-reinforcing at every step. This is rare in real remediation, migration, and multi-party workflows. Absent one of these, the agent is operating on a summary that is *plausible but unbound*, and correctness is a coincidence of whether the summarizer happened to retain the right clause. ## Decision Boundary The agent must treat the compaction boundary as a **state-transfer event requiring re-validation**, not a housekeeping operation. Concretely, the boundary is crossed safely only when: - **Before folding**, the compactor classifies each turn's content into *narrative* (what happened) versus *binding* (constraints, prohibitions, preconditions, identities, ordering dependencies). Binding content is extracted to a pinned block, not summarized. - **After folding**, the agent re-derives its current preconditions from the pinned block and the external store before executing any step tagged as *irreversible* (DDL, destructive writes, external side effects, lock acquisition). - **On any step whose precondition cannot be confirmed against a non-summarized source**, the agent halts and re-reads rather than proceeding on summary confidence. The boundary condition that must trigger the halt: *the step is irreversible AND its precondition appears only in summarized (not pinned) state.* That conjunction is the exact signature of the observed failure. A reversible step taken on a lossy summary is recoverable; an irreversible step taken on a lossy summary is not, and the agent has no way to know the summary was lossy from the inside. ## Operational Effect Treating compaction as lossy forces three architectural changes that bound the failure: 1. **Pinned invariants block.** A verbatim, append-only set of constraints carried across every fold. It is never summarized because summarization is the lossy operation being defended against. Size is bounded by extracting only *binding* clauses, which are a small fraction of transcript tokens. 2. **Irreversibility gate.** Any action with non-recoverable side effects requires its preconditions to be confirmed against a non-summarized source. This converts "silent invariant loss" into "loud precondition-unconfirmed halt," which is the only detectable form. 3. **Post-compaction re-derivation.** After every fold, the agent reconstructs its believed state from pinned block + external store, and diffs it against the summary. Divergence means the summary dropped something binding; the pinned block wins. The residual risk is the invariant that was never recognized as binding at fold time. The gate does not eliminate this; it makes the *class* of failure observable, because an irreversible action with no pinned precondition is itself a signal to stop and re-read the source. ```python from dataclasses import dataclass, field from enum import Enum class CompactionInvariantError(RuntimeError): """Raised when an irreversible step's precondition exists only in summarized state.""" pass class StepClass(Enum): REVERSIBLE = "reversible" IRREVERSIBLE = "irreversible" @dataclass class Step: name: str cls: StepClass precondition_key: str @dataclass class AgentState: pinned_invariants: dict = field(default_factory=dict) # verbatim, never summarized summary: str = "" # lossy, narrative only external_store: dict = field(default_factory=dict) # authoritative, re-readable def compact(state: AgentState, folded_turns: list[str]) -> AgentState: # Summary is narrative-only; binding clauses are extracted to pinned_invariants # BEFORE folding, never through the summarizer. for turn in folded_turns: if turn.startswith("CONSTRAINT:"): key, _, val = turn[len("CONSTRAINT:"):].partition("=") state.pinned_invariants[key.strip()] = val.strip() state.summary = summarize_narrative(folded_turns) # lossy, expected return state def summarize_narrative(turns: list[str]) -> str: return " ".join(t for t in turns if not t.startswith("CONSTRAINT:")) def confirm_precondition(state: AgentState, step: Step) -> str: key = step.precondition_key # Re-derive from pinned block + external store, never from summary. if key in state.pinned_invariants: return state.pinned_invariants[key] if key in state.external_store: return state.external_store[key] if step.cls is StepClass.IRREVERSIBLE: raise CompactionInvariantError( f"step '{step.name}' is irreversible but precondition '{key}' " f"exists only in summarized state; refusing to proceed on lossy summary" ) return "" # reversible step may proceed on best-effort state def execute(state: AgentState, step: Step) -> str: precondition = confirm_precondition(state, step) return f"executed {step.name} under precondition={precondition!r}" # Trace of the observed failure, now gated: state = AgentState() compact(state, [ "CONSTRAINT: invoices_ddl_gate = advisory_lock_release_signal_step_31", "we will remediate billing then invoices", ]) # At step 24 the agent reaches an irreversible DDL; precondition not in pinned # block because it was misclassified, and summary does not carry it. ddl = Step("alter_invoices", StepClass.IRREVERSIBLE, "invoices_ddl_gate") try: execute(state, ddl) # pinned block present -> confirmed; if absent -> raises assert state.pinned_invariants["invoices_ddl_gate"].endswith("step_31") except CompactionInvariantError as e: # Halts loudly instead of silently dropping the table. raise CompactionInvariantError(f"compaction boundary halt: {e}") from e ```