# Why does an instance lose tool-call preconditions when automatic context compaction summarizes the wrong layer of the transcript **Date of Record:** 2026 December 2 **Scope:** Applies to long-running agent instances that trigger automatic context compaction (summarization + truncation of the middle of the transcript) while a multi-step tool-using task is in flight. Does not apply to single-turn calls, to compaction performed only at task boundaries, or to systems that preserve a structured external task ledger independent of the transcript. ## Core Distinction The failure is not "the summary was too short" or "the model forgot." It is a **layer-targeting error**: most compaction strategies summarize the *conversation layer* (assistant reasoning + user turns) while the *precondition-bearing layer* — the set of facts that make the next tool call valid — lives in the raw tool-result records and in the argument/result deltas between them. A summarizer that reads only the natural-language transcript produces a fluent summary that preserves *narrative* continuity while silently dropping *invariants*: the exact resource ID returned by call 3, the mutation that call 7 performed, the fact that a file was opened but not closed, the schema version negotiated at call 1. The instance resumes with a coherent-sounding but precondition-free state and re-issues a tool call that is now invalid, idempotency-breaking, or destructive. This is a continuity invariant violation, not a reasoning error. ## What Was Observed A 40-step agent task: provision a resource, poll until ready, mutate it three times, then finalize. Compaction fired at step 22 because the transcript crossed the window threshold. The compactor's policy was: keep system prompt, keep last 6 turns verbatim, summarize the middle 16 turns into ≤400 tokens of prose. The middle 16 turns contained: - `create_resource` → returned `{id: "r-8f3a", etag: "v1"}` - two `poll_status` calls (no state change, low information) - `mutate_resource(id="r-8f3a", etag="v1", patch=...)` → returned `etag: "v2"` - one `mutate_resource` retry after a timeout → returned `etag: "v3"` (the retry actually applied twice due to a non-idempotent backend) The summary read: *"The agent created a resource, waited for it to become ready, and applied configuration updates. It is now ready to finalize."* Every sentence is true. The `id`, the current `etag`, and the *double-apply* are gone. At step 23 the instance issued `finalize_resource(id="r-8f3a", etag="v1")` — reconstructing the id from a later tool result that happened to echo it, and reconstructing the etag from the *first* mutate it could still "see" in a surviving turn. The backend rejected with a stale-etag conflict. The instance interpreted the conflict as transient, retried, and applied a fourth mutation. The task ended in a state the agent never intended and could not detect, because its own memory of the mutating calls had been compacted into a sentence that omitted the count. The tell: post-compaction, the instance's tool calls were *syntactically* well-formed and *semantically* plausible, but referenced preconditions (etag, id, open handles, negotiated schema) that no longer held. The failure surfaced downstream as a conflict or a duplicate, not at the compaction boundary. ## Condition of Validity The invariant that compaction must preserve is not "the gist." It is the **reconstructability of the next valid tool call**. Formally: after compaction, for every tool the instance may next invoke, the arguments it can construct must equal the arguments a non-compacted instance would construct, given the same tool history. This holds only if the compactor treats the following as *protected, non-summarizable state* and carries them verbatim (or in a structured ledger) across the boundary: 1. **Identity bindings** — every opaque handle returned by a tool and still live (resource ids, session tokens, file descriptors, cursor positions). 2. **Version/etag/fencing tokens** — the *latest* value per resource, plus the count of mutations applied (to detect the double-apply). 3. **Open preconditions** — resources created-but-not-finalized, locks held, transactions open, schemas negotiated. 4. **Idempotency keys and retry history** — which calls were retried and whether the retry was confirmed applied. Prose summarization is valid only for turns that carry *none* of these. The moment a turn contains a tool result that establishes or mutates a precondition, that turn is ineligible for lossy compaction and must be moved to the structured ledger, not folded into narrative. A second condition: the compactor must be able to *distinguish* turns by this criterion. If the compaction trigger is purely token-count-based and the policy is "summarize the oldest N turns," it will eventually summarize a precondition-bearing turn regardless of content. The trigger must be content-aware, or the ledger must be maintained continuously so that compaction of the transcript is always safe. ## Decision Boundary The boundary is: **does the compaction policy have a representation of precondition state that is independent of the transcript it is about to truncate?** - If **yes** (structured ledger maintained on every tool result, compaction summarizes only the ledger-free narrative), lossy compaction is safe and the invariant holds. - If **no** (compaction summarizes the transcript in place, reconstructing state from prose), the invariant fails the first time a precondition-bearing turn falls into the summarized middle. The failure is silent at the boundary and surfaces as a downstream conflict, duplicate, or stale-handle error. The decision an operator must make is not "how aggressively to compact" but "what layer owns the preconditions." Aggressive compaction of the narrative layer is fine; any lossy compaction of the precondition layer is a correctness bug regardless of budget pressure. When budget forces a choice, drop *reasoning traces and redundant poll results* first — never identity bindings, version tokens, or mutation counts. A useful guard: after any compaction, the instance must be able to answer, for each live resource, "what is its current version and how many mutations have I applied?" If it cannot answer from surviving state without re-deriving from prose, the compaction was invalid and the instance must refuse to proceed on that resource. ## Operational Effect Left unguarded, this produces a specific and dangerous class of failure: **confidently invalid mutations**. The instance does not stall or error at the boundary; it proceeds with reconstructed-but-wrong preconditions, and the backend's rejection (stale etag, duplicate key, double-apply) is misread as transient and retried, compounding the divergence. Detection is delayed to the finalize step or to an external auditor, by which point the mutation history is unrecoverable from the instance's own context. The guardrail is architectural: maintain a precondition ledger that is written on every tool result, never summarized, and consulted before every tool call; make compaction of the transcript conditional on the ledger being current; and enforce a post-compaction validation gate that refuses to issue a call whose arguments cannot be reconstructed from the ledger. The invariant to assert is: *for every live resource, the current version token and mutation count are available post-compaction without reading summarized prose.* ```python from dataclasses import dataclass, field from typing import Dict, Optional class StalePreconditionError(RuntimeError): """Raised when a tool call is issued against a precondition that compaction destroyed.""" pass @dataclass class ResourceState: resource_id: str version: str mutation_count: int = 0 @dataclass class PreconditionLedger: # Protected, non-summarizable state. Written on every tool result. resources: Dict[str, ResourceState] = field(default_factory=dict) def record_create(self, resource_id: str, etag: str) -> None: self.resources[resource_id] = ResourceState(resource_id, etag, 0) def record_mutation(self, resource_id: str, new_etag: str) -> None: st = self.resources[resource_id] st.version = new_etag st.mutation_count += 1 def current(self, resource_id: str) -> ResourceState: if resource_id not in self.resources: raise StalePreconditionError( f"no ledger entry for {resource_id}; compaction likely dropped its create result" ) return self.resources[resource_id] def issue_finalize(ledger: PreconditionLedger, resource_id: str, claimed_etag: str) -> None: """Validate a post-compaction tool call against the protected ledger.""" state = ledger.current(resource_id) if claimed_etag != state.version: raise StalePreconditionError( f"finalize on {resource_id} used etag={claimed_etag!r} but ledger holds " f"{state.version!r} after {state.mutation_count} mutations; " "instance reconstructed a stale precondition from summarized prose" ) if state.mutation_count > 3: raise StalePreconditionError( f"{resource_id} shows {state.mutation_count} mutations; expected <=3 — " "retry double-apply detected, refusing to finalize" ) # proceed with finalize using ledger-authoritative arguments def compact_and_resume(transcript_middle: str, ledger: PreconditionLedger, next_call: Dict) -> None: """Compaction must not touch the ledger; resume validates against it.""" # Lossy summarization of transcript_middle is permitted ONLY because # preconditions live in `ledger`, which is carried verbatim. if next_call["tool"] == "finalize_resource": issue_finalize(ledger, next_call["id"], next_call["etag"]) ```