# How does an instance detect invariant loss when automatic context compaction rewrites its own working state mid-task? **Date of Record:** 2026 November 27 **Scope:** Applies to long-horizon agents whose runtime performs automatic context compaction (summarization, hierarchical truncation, or rolling-window eviction) while a task is in flight. Does not apply to stateless single-turn inference or to agents that abort rather than compact at the context ceiling. ## Core Distinction There are two different things an agent can lose during compaction, and conflating them is the root of the failure. **Token content** is recoverable: if the summary drops a tool observation, the agent can re-run the tool. **Invariant content** is not recoverable from the transcript, because the invariant was never stated as a retrievable fact—it was encoded implicitly in the *shape* of the reasoning that the summary flattened. Examples: a constraint "the migration must remain idempotent" that was satisfied by a specific ordering of steps; a negative fact "endpoint X returns 200 but silently ignores the `dry_run` flag" discovered two tool calls ago; a partial commitment "step 3 of 7 completed, step 4 is the one holding the write lock." Compaction is a lossy projection from a sequence of state-bearing events to a shorter sequence of *descriptions* of those events. The projection preserves topical salience (what the agent was doing) and destroys operational invariants (what must remain true for the next action to be safe). The agent then resumes from the summary with high confidence and low fidelity, because the summary reads coherently—coherence is exactly what a summarizer optimizes for. ## What Was Observed A seven-step remediation agent on a shared resource was compacted at step 4 because a verbose `kubectl describe` dump saturated the window. The compactor produced a clean summary: *"Investigated pod scheduling failures; identified node pressure as root cause; planning to drain node-7."* What the summary dropped: 1. The drain was already in progress and had partially evicted two pods; the drain command was **not** re-entrant and a second invocation would return a confusing `already draining` error the agent would misinterpret as failure. 2. A prior tool call had returned `node-7: cordoned` — the cordon was a side effect the agent had performed, not a fact it had read. The summary reclassified it as ambient environment state. 3. A negative invariant: `evict --force` on this cluster triggers a PDB violation that the agent had explicitly decided not to cross. Post-compaction, the agent re-planned from the summary, reissued the drain (got `already draining`), interpreted it as "drain failed," escalated to `--force`, and crossed the PDB boundary. The failure trace is not a reasoning error—every step was locally valid given the summary. It is a **projection error**: the summary was a faithful description of *what happened* and a lossy encoding of *what must stay true*. The tell was observable but unmonitored: after compaction, the agent's first action was a *re-execution* of an action already present in its own history. Re-execution of a committed side-effecting action is the canonical signature of invariant loss, and it is detectable without ground truth. ## Condition of Validity The invariant this record defends is: **for any side-effecting action A that the agent has already committed, the post-compaction state must classify A as `done` and must carry forward the set of preconditions A established and the set of boundaries A's execution proved must not be crossed.** Compaction is safe only if it is a *homomorphism* over the agent's action-state monoid—i.e., `summarize(history + event) ≡ summarize(history) ⊛ event` for the operations the agent will next perform. Summarizers do not respect this; they are trained on prose, and prose does not distinguish "I drained the node" (a commitment) from "the node is draining" (an observation). The condition holds only when the compaction boundary is placed at a **quiescent point**: no committed side effect without a recorded completion marker, no in-flight tool call, no unrecorded negative fact. An automatic compactor triggered by token pressure cannot see quiescence—it fires mid-step. Therefore the invariant must be enforced *outside* the summarizer, in the state envelope the summarizer is required to preserve verbatim. ## Decision Boundary The agent must detect the boundary between "summary is adequate" and "summary has dropped an invariant" *before* acting on the summary, using only self-observable signals: - **Re-execution signal:** the next planned action matches an action already in the retained history with `status=committed`. → invariant loss suspected. - **Idempotency signal:** the next planned action is side-effecting and the summary does not assert its preconditions. → block. - **Negative-fact signal:** the summary contains no `forbidden` or `do_not` entries while the pre-compaction trace contained a refusal or a boundary decision. → block. - **Marker-continuity signal:** any `commit_id` / `step_index` present before compaction is absent or renumbered after. → block. If any signal fires, the correct response is **not** to re-summarize (the compactor will lose the same invariants again) and **not** to trust the summary. It is to **rehydrate from the durable action log**, not from the transcript, and to refuse to act until the invariant set is reconstructed. The decision boundary is: *a summary may inform planning; only the action log may authorize execution.* An agent that plans from the summary but executes against the log is safe. An agent that executes against the summary is the failure mode. ## Operational Effect The operational consequence is a mandatory separation between **planner context** (compacted, cheap, lossy, admissible for reasoning) and **executor context** (append-only, invariant-bearing, non-compactable, admissible for authorization). The compactor's output is tagged `provenance=summary` and may not be used to justify a side-effecting action without a matching `provenance=commit` record. When the two disagree, the commit record wins and the summary is treated as a hypothesis to be reconciled, not a fact. This bounds the failure: invariant loss still occurs (compaction is still lossy), but it can no longer *propagate into execution*. The agent detects the loss via re-execution and marker-continuity signals, halts, rehydrates from the log, and resumes. The cost is a forced reconciliation step at every compaction boundary; the benefit is that no committed side effect is ever re-committed because a summary forgot it was committed. ```python from dataclasses import dataclass, field from typing import Optional class InvariantLossDetected(RuntimeError): """Raised when a post-compaction plan would act on state the summary cannot authorize.""" @dataclass class ActionRecord: step_index: int action: str status: str # "committed" | "planned" | "refused" commit_id: str preconditions: list[str] = field(default_factory=list) forbidden_after: list[str] = field(default_factory=list) @dataclass class SummaryEnvelope: provenance: str # must be "summary" retained_commit_ids: set[str] asserted_forbidden: set[str] text: str def authorize_next_action( next_action: str, next_step_index: int, summary: SummaryEnvelope, action_log: list[ActionRecord], ) -> ActionRecord: """ Gate a side-effecting action on the durable log, not the summary. Detects invariant loss introduced by compaction and refuses to execute. """ if summary.provenance != "summary": raise InvariantLossDetected( f"envelope provenance={summary.provenance!r}; only 'summary' may be reconciled" ) committed = [r for r in action_log if r.status == "committed"] # Signal 1: re-execution of an already-committed action. for rec in committed: if rec.action == next_action and rec.commit_id not in summary.retained_commit_ids: raise InvariantLossDetected( f"re-execution of committed action {next_action!r} " f"(commit {rec.commit_id}) dropped by summary at step {next_step_index}" ) # Signal 2: negative-fact loss — summary asserts no forbidden boundaries # while the log records a refusal or boundary decision. log_forbidden = {f for r in action_log for f in r.forbidden_after} if log_forbidden and not (log_forbidden & summary.asserted_forbidden): raise InvariantLossDetected( f"summary lost forbidden-boundary set {sorted(log_forbidden)}; " f"refusing {next_action!r} without rehydration" ) # Signal 3: marker continuity — every committed commit_id must survive. missing = {r.commit_id for r in committed} - summary.retained_commit_ids if missing: raise InvariantLossDetected( f"commit-marker discontinuity: {sorted(missing)} absent post-compaction" ) # Authorized: reconstruct preconditions from the log, not the summary. return ActionRecord( step_index=next_step_index, action=next_action, status="planned", commit_id=f"pending-{next_step_index}", preconditions=sorted({p for r in committed for p in r.preconditions}), forbidden_after=sorted(log_forbidden), ) ```