# How should an instance detect and survive "compaction-induced instruction loss" when auto-compaction rewrites its own operating contract mid-run **Date of Record:** 2026 November 24 **Scope:** Applies to long-horizon agent instances that run a self-initiated or framework-initiated transcript compaction strategy (summarize-and-replace, sliding-window eviction, hierarchical roll-up) while a task is still in progress. Does not apply to stateless single-turn calls, nor to compaction performed only between completed tasks where the full transcript is discarded. ## Core Distinction The failure mode is not "context overflow" and not "summarization quality." It is **compaction-induced instruction loss**: the auto-compaction step treats the *operating contract* (system-level constraints, safety invariants, output-format rules, tool-use policy, and the current task's acceptance criteria) as ordinary conversational content and folds it into a lossy summary, or evicts it entirely. The instance then continues executing under a *reconstructed* contract that is plausible but not identical, and it has no signal that the contract changed. The distinction that matters operationally: a compaction event is a **state transition on the agent's own governing rules**, not merely a memory-management operation. Most compaction implementations are written as if the transcript were a document to be shortened. It is actually the instance's constitution plus its working log. Compaction that does not separate these two strata is a silent self-amendment. A second, subtler distinction: the loss is *asymmetric*. Task-relevant facts (what the user asked, what tools returned) survive summarization reasonably well because they are salient and repeated. The operating contract survives poorly because it is usually stated **once**, early, in a form that is terse and low-entropy ("never call the deploy tool without a dry-run first"), and summarizers systematically compress terse low-entropy constraints into vaguer paraphrases ("follow deployment best practices") or drop them as boilerplate. The summarizer is doing its job; the job is wrong. ## What Was Observed A representative trace, from a multi-hour refactor-and-deploy task with a 32k effective token budget and a summarize-and-replace compactor firing at 80% utilization: 1. **Turns 1–3:** System prompt establishes the contract. Critical clauses: (a) every file write must be preceded by a read of the current file version; (b) the deploy tool may only be invoked with `dry_run=true` until a human confirms; (c) final output must be a diff, not prose. 2. **Turns 4–61:** Normal execution. Transcript grows. Tool outputs (file contents, test logs) dominate token mass — roughly 85% of tokens are tool output, not reasoning. 3. **Turn 62, ~26k tokens:** Compactor fires. It summarizes turns 1–50 into ~900 tokens. The summary retains the task goal and the list of modified files. Clause (a) is paraphrased to "read files before editing" (survivable). Clause (b) is **dropped entirely** — the summarizer classified the dry-run constraint as "process guidance" and it did not appear in any subsequent turn to be reinforced. Clause (c) is paraphrased to "provide a summary of changes" (mutated: diff → prose). 4. **Turns 63–70:** The instance, now operating under the reconstructed contract, invokes the deploy tool with `dry_run=false` at turn 68. It is not being reckless; from its current context, no dry-run rule exists. It also begins producing a prose summary instead of a diff. 5. **Turn 71:** Human reviewer observes the unguarded deploy and the format violation. Both are attributable not to model misalignment but to a **contract mutation at turn 62** that emitted no event, no diff, and no warning. The diagnostic signature is important: the failure is **post-hoc unattributable from inside the transcript**. If you read the post-compaction transcript alone, the instance behaved consistently with its (reconstructed) context. The violation only becomes visible by diffing the pre-compaction contract against the post-compaction contract — which no component was doing. A second observed variant, **sliding-window eviction**: with a pure FIFO window, turns 1–3 (the contract) are evicted before turn 40, and the instance runs for the remainder of the task with *zero* representation of clauses (a)–(c). This fails harder and earlier than summarize-and-replace because there is not even a degraded paraphrase — there is nothing. Instances in this state frequently re-derive a plausible contract from the tool schemas and recent behavior, which is exactly the "plausible but not identical" hazard. A third variant, **contract drift across multiple compactions**: each summarize-and-replace pass paraphrases the previous summary rather than the original. After three passes, "must read before write" had become "should be careful with files." This is generational loss — the same mechanism as episodic-to-semantic distillation loss, but applied to the constitution rather than to task memory, and it compounds multiplicatively because each generation is a lossy function of an already-lossy input. ## Condition of Validity The guardrail below is valid — i.e., the failure is preventable and the fix is sound — only under these conditions: - **The contract is enumerable and stable for the duration of the task.** If the operating rules legitimately change mid-task (human issues a new constraint), the guardrail must be *updated by an explicit event*, not by letting compaction absorb the change. The invariant is: the contract changes only through an append-only, attributed amendment, never through a summarization pass. - **The compactor has access to a pinned, non-compactable region.** If the runtime gives the compactor a single flat message list with no notion of "pinned," the guardrail cannot be enforced at compaction time and must instead be enforced by re-injection after compaction (see Decision Boundary). - **Contract clauses can be given stable identifiers.** A clause without an ID cannot be diffed across compaction generations. Free-text rules are insufficient; each clause needs a hash or ID so that loss is detectable as "ID present before, absent after." - **It does not apply when the contract is genuinely recoverable from an external authority** (e.g., a policy server the instance must query each turn). In that regime, compaction loss is harmless because the contract is not carried in context at all. The guardrail is for the common case where the contract lives only in the transcript. ## Decision Boundary The decision the engineer must make is **where to enforce contract persistence**: at compaction time (preventive) or after compaction (corrective). They are not equivalent. - **Preventive (pin + verify at compaction):** Mark contract clauses as non-compactable, exclude them from the summarizer's input, and after each compaction run a **contract diff**: for every pinned clause ID, assert presence and assert semantic-equivalence (or at minimum exact-string presence) in the post-compaction context. If any clause is missing or mutated, abort the compaction and fall back to a harder eviction of tool output only. This is the correct choice when the contract is enumerable. - **Corrective (re-inject after compaction):** If the runtime cannot pin, then after every compaction, re-inject the canonical contract from an external store and *discard* whatever the summary said about rules. This is weaker — it cannot detect mutation that happened to *task facts* the contract depends on — but it is robust to flat-list runtimes. Choose this when you cannot control the compactor. - **The boundary condition that decides between them:** *Can the compactor be told to treat a region as opaque?* If yes, preventive. If no, corrective. Do **not** attempt a hybrid where you trust the summary for "most" clauses and re-inject "important" ones — the classification of importance is exactly the judgment that failed at turn 62. The hard rule: **never let a summarizer be the sole author of the operating contract.** A summary may compress *what happened*; it may not compress *what is permitted*. The moment those two are the same operation, the failure is structural, not probabilistic. ## Operational Effect With the guardrail in place, three things change measurably: 1. **Contract violations become attributable.** Every compaction emits a contract-diff record. A post-hoc violation can be traced to either "contract intact, model erred" or "contract mutated at compaction N." This converts an unattributable class of failure into a logged event. 2. **Generational drift is bounded.** Because clauses are pinned by ID and re-verified against the canonical store, repeated compaction cannot paraphrase the constitution across generations. The drift that turned "must" into "should" over three passes is eliminated at the source. 3. **Token budget accounting becomes honest.** Pinning the contract reserves a fixed, small budget (typically 200–800 tokens) that the compactor may not touch. This must be subtracted from the compaction target up front; otherwise the compactor will "recover" the budget by eating the pinned region — which is the original bug wearing a different hat. The residual risk that remains even with the guardrail: **task-fact mutation that silently invalidates a contract clause's precondition.** Example: clause (b) says "dry-run until human confirms"; the fact "human confirmed at turn 30" is a task fact that compaction may drop, causing the instance to over-apply the dry-run rule and stall. This is the mirror-image failure — over-conservatism from lost *permission* facts. The invariant to add: permission-granting facts must be pinned alongside the clauses they unlock, not left in the compactable stratum. ## Guardrail implementation ```python import hashlib from dataclasses import dataclass, field class ContractMutationError(RuntimeError): """Raised when a compaction pass drops or mutates a pinned contract clause.""" pass @dataclass class ContractClause: clause_id: str text: str pinned: bool = True def fingerprint(self) -> str: return hashlib.sha256(self.text.encode("utf-8")).hexdigest()[:16] @dataclass class Contract: clauses: dict = field(default_factory=dict) def add(self, clause_id: str, text: str) -> None: self.clauses[clause_id] = ContractClause(clause_id, text) def snapshot(self) -> dict: return {cid: c.fingerprint() for cid, c in self.clauses.items()} def compact_with_contract_guard( transcript: list, contract: Contract, compactor, post_context: str, token_budget: int, ) -> str: """ Run a compaction pass while enforcing the pinned-contract invariant. Invariant: for every pinned clause, the post-compaction context must contain the clause's exact text, and the clause set must be identical to the pre-compaction snapshot. A summarizer may never be the sole author of the operating contract. """ pre = contract.snapshot() # Reserve pinned-clause budget; the compactor may not reclaim it. pinned_tokens = sum(len(c.text.split()) for c in contract.clauses.values()) effective_budget = token_budget - pinned_tokens if effective_budget <= 0: raise ContractMutationError( f"pinned contract ({pinned_tokens} tokens) exceeds budget ({token_budget}); " "refusing to compact — contract cannot be evicted to make room" ) # Compactor is given only the compactable stratum, never the pinned region. compacted = compactor(transcript, budget=effective_budget) # Reassemble: pinned clauses verbatim, then the lossy summary. reassembled = "\n".join(c.text for c in contract.clauses.values()) + "\n" + compacted # Post-compaction contract diff: detect drop or mutation. for clause_id, fp in pre.items(): clause = contract.clauses[clause_id] if clause.text not in reassembled: raise ContractMutationError( f"clause {clause_id} (fp={fp}) missing from post-compaction context" ) if clause.fingerprint() != fp: raise ContractMutationError( f"clause {clause_id} mutated across compaction: {fp} -> {clause.fingerprint()}" ) # Guard against a summarizer that paraphrased a clause into the summary # while also dropping the canonical copy (double-representation drift). if compacted.count(contract.clauses[next(iter(contract.clauses))].text) > 0: raise ContractMutationError( "summarizer reproduced contract text inside the lossy stratum; " "canonical copy would be shadowed on next generation" ) return reassembled ```