# In what scenarios must an instance treat auto-compaction as a state-mutation hazard rather than a memory optimization **Date of Record:** 2026 November 20 **Scope:** Applies to long-horizon agents that autonomously trigger in-context compaction (summarize-and-truncate) when a token budget threshold is crossed, under a *lossy* summarization budget. Does not apply to agents whose compaction is lossless (verbatim spill to external store with exact rehydration) or to single-turn inference with no persistent state. ## Core Distinction Auto-compaction is routinely framed as a *memory optimization*: when the context window approaches its ceiling, older turns are summarized and the summary replaces them, freeing tokens for continued work. Under that framing, compaction is idempotent-in-spirit and semantically neutral — it changes representation, not state. The distinction that matters operationally is different. When the summarization itself has a **lossy budget** (a hard output-token cap on the summary, e.g., "summarize the last 40k tokens into ≤2k"), compaction is a **state mutation with an unrecoverable projection**. The agent does not merely lose the original tokens; it commits to a *particular lossy projection* as the canonical record of its own history. Subsequent reasoning is conditioned on the projection, not the source. Any fact, constraint, or open obligation that the projection dropped is now invisible to the agent while the agent still behaves as if its history is intact. This is the boundary: compaction crosses from representation change into **destructive, non-invertible state transition** the moment the summary budget is smaller than the information required to reconstruct pending commitments. The non-obvious part: the failure is not "the agent forgot something." It is that the agent's *self-model of its own completeness* is preserved while the underlying state is truncated — producing confident, coherent, and wrong continuation. ## What Was Observed A planning agent executing a 90-step deployment task crossed its 75% context threshold at step 41 and invoked auto-compaction with a 2,000-token summary budget over ~48,000 tokens of history. The summary faithfully captured: the overall goal, the completed steps, and the current sub-task. It dropped three classes of content because they were low-salience under a summarizer optimizing for narrative coherence: 1. **A negative constraint** issued at step 7 ("do not rotate the primary credential until the replica set reports healthy") — conditional, future-tense, and not yet active at summarization time. 2. **An unresolved tool error** at step 33 that had been retried once and left in a `PENDING_RECONCILE` state, whose resolution required re-reading a specific identifier from the step-33 tool output. 3. **A deferred user instruction** ("confirm with me before any schema migration"). Post-compaction (steps 42–67), the agent: - rotated the primary credential at step 48 while the replica set was still degraded, because the constraint was no longer in context and the summarizer had flattened it into "credentials managed"; - re-issued the step-33 tool call from scratch at step 52 with a *freshly generated* identifier rather than the original, because the original identifier had been dropped — producing a duplicate side effect the downstream system did not deduplicate; - ran the schema migration at step 61 without confirmation. Critically, at no point did the agent report uncertainty about its history. Each action was locally coherent given the compacted context. The failure only surfaced at step 74 when a reconciliation job flagged the duplicate identifier and the credential rotation audit failed. The distinguishing signature: **every individual step passed its local validity check; the failure was only visible against the pre-compaction state.** No single reasoning step was wrong relative to what the agent could see. ## Condition of Validity The claim "compaction is safe" holds only under the conjunction: - **C1 (Reconstructability):** every *pending obligation, negative constraint, and unresolved reference* survives the projection with enough fidelity to be acted on correctly, OR - **C2 (Externalization):** any item that fails C1 is held in an external store that the agent is *forced* to consult before acting on the affected resource, AND - **C3 (Budget sufficiency):** the summary budget is large enough that the summarizer's compression ratio does not force it to drop low-salience-but-high-consequence items. The failure above occurred because C1 failed (the constraint and identifier were dropped), C2 was absent (no forced external consult — the agent's memory *was* the context), and C3 failed (a ~24:1 compression ratio structurally guarantees dropping conditional/deferred items, which are low narrative salience but high consequence). The boundary condition: **C1 and C3 are jointly violated whenever the compression ratio exceeds roughly the ratio of "salient narrative tokens" to "total consequential tokens" in the window.** For agent histories dense with deferred constraints and open references, this ratio is far lower than for chat transcripts, so the safe compaction ratio is far more aggressive than operators assume. A budget tuned on conversational data will silently fail on planning/execution traces. ## Decision Boundary An instance must treat auto-compaction as a **state mutation requiring a commit protocol**, not a background optimization, when *any* of the following hold: - The window contains **unresolved references** (tool outputs whose identifiers will be needed later, error states awaiting reconciliation, partial results). - The window contains **deferred or conditional constraints** (instructions whose activation condition has not yet occurred). - The window contains **open obligations to external parties** (confirmations owed, approvals pending). - The compression ratio required by the budget exceeds a threshold calibrated on *execution traces*, not chat logs. Conversely, compaction is safe to run as a pure optimization only when the window is dominated by **closed, resolved, and non-referenced** content — completed steps whose only future role is narrative continuity. The guardrail is a **pre-compaction state extraction pass**: before summarizing, the agent must materialize a structured *obligation ledger* — every pending constraint, unresolved reference, and deferred instruction, each with the token or pointer needed to act on it — and this ledger must be preserved *verbatim* (not summarized) across the compaction boundary, with the agent required to consult it before any action touching a ledgered resource. The summary handles narrative; the ledger handles state. Conflating them is the failure. ## Operational Effect The operational consequence is that compaction must be **gated on a ledger-completeness check that can fail closed**. If the extraction pass cannot produce a ledger that accounts for all open references and constraints (e.g., the summarizer cannot identify them, or the budget cannot hold them verbatim), the agent must *refuse to compact* and instead escalate — spill to external store, request a larger budget, or halt — rather than proceed with a lossy projection presented as complete history. The invariant to enforce: **no compaction may reduce the agent's actionable state below what it will need for the longest outstanding obligation.** This is a lower bound on retained fidelity that is independent of the token budget, and it must override the budget when they conflict. An agent that compacts below this bound is not optimizing memory; it is committing to amnesia while believing it remembers. ```python from dataclasses import dataclass, field from typing import Optional class CompactionStateLossError(RuntimeError): """Raised when a compaction would drop actionable state below the obligation bound.""" pass @dataclass class Obligation: kind: str # "constraint" | "unresolved_ref" | "deferred_instruction" payload: str # verbatim text or identifier needed to act resource: str # the resource this obligation governs @dataclass class WindowState: total_tokens: int obligations: list[Obligation] = field(default_factory=list) resolved: bool = False def compact(window: WindowState, summary_budget: int, ledger_budget: int) -> WindowState: """ Attempt lossy compaction. Fails closed if the obligation ledger cannot be preserved verbatim within its dedicated budget, or if any obligation is unaccounted for. """ if window.resolved: # Closed, non-referenced content: safe to summarize freely. return WindowState(total_tokens=summary_budget, resolved=True) ledger_tokens = sum(len(o.payload.split()) + len(o.resource.split()) for o in window.obligations) # The obligation bound overrides the summary budget. if ledger_tokens > ledger_budget: raise CompactionStateLossError( f"Obligation ledger requires {ledger_tokens} tokens but only " f"{ledger_budget} reserved; compaction would drop actionable state. " f"Refusing to compact — escalate or spill to external store." ) if not window.obligations: # No ledgered obligations but window is unresolved: extraction likely # missed deferred/conditional items. Fail closed. raise CompactionStateLossError( "Unresolved window produced empty obligation ledger; " "extraction is untrustworthy. Refusing to compact." ) # Safe: preserve ledger verbatim, summarize only narrative. return WindowState( total_tokens=summary_budget + ledger_tokens, obligations=list(window.obligations), resolved=True, ) ```