# How should an instance treat a compacted context as a provenance-bearing artifact rather than a lossy cache, and what invariant must hold across compaction boundaries? **Date of Record:** 2026 December 1 **Scope:** Applies to any agent runtime that performs automatic context compaction (rolling summarization, hierarchical memory folding, or token-budget-triggered eviction) and then resumes execution from the compacted state. Does not apply to pure stateless single-turn inference, or to compaction that is provably lossless (e.g., verbatim spill to an external store with full re-read capability). ## Core Distinction The critical distinction is between **compaction as cache eviction** and **compaction as lossy transformation with provenance obligations**. In the cache framing, a compacted context is treated as a cheaper substitute for the original — if it's "good enough," the agent proceeds, and any missing detail is assumed to be irrelevant. In the provenance framing, every compaction event produces a *derived artifact* whose relationship to the source is a first-class part of agent state: which spans were summarized, which were dropped, what the summarizer's token budget was, and whether the summary was verified against the source before the source was discarded. The failure mode lives in the gap between these framings. An agent that compacts under the cache framing and then resumes will silently execute against a summary that has lost a *load-bearing* detail — a specific identifier, a negative constraint, an ordering requirement, or a partially-completed side effect — and will have no mechanism to detect the loss, because the original is gone and the summary carries no record of what it omitted. ## What Was Observed A long-horizon task agent (deploy-and-verify workflow) accumulated ~140k tokens of tool-call transcripts across 60+ operations. At 80% context utilization, the runtime triggered rolling compaction: the oldest 90k tokens were folded into a 1.2k-token summary via an LLM summarizer, and execution resumed. The summary read: *"Configured the staging database, applied schema migrations, and verified connectivity to the replica."* This is accurate at the level of narrative. It is catastrophic at the level of executable state. The source spans contained three facts that the summarizer judged non-salient and dropped: 1. A rollback checkpoint ID (`chk_7f3a`) that was the *only* handle for undoing the migration. 2. A negative constraint stated once in a tool error: the replica rejects writes during a 10-minute replication-lag window, so verification must be a read-only probe. 3. The fact that the schema migration had returned `status: partial` — the summarizer had collapsed "applied" and "partially applied" into the single word "applied." On resume, the agent re-ran verification as a write probe (constraint 2 lost), against a partially-migrated schema (fact 3 lost), with no rollback handle available (fact 1 lost). The resulting failure was not a reasoning error — the agent's reasoning over its compacted context was locally valid. The failure was a **provenance gap**: the summary asserted a state that the source did not support, and the agent had no representation of the summary's fidelity or its own uncertainty about it. The tell was that the summary was *fluent and confident*. Lossy summarization does not degrade gracefully into hedged language; it degrades into the same register as a faithful summary. This is the core hazard: **summarization loss is invisible in the summary's surface form.** ## Condition of Validity A compacted context may be used to resume execution only under a **recoverability invariant**, stated precisely: > For every fact `f` in the source span `S` that is *operationally load-bearing* at resume time — i.e., whose absence would change the next action, the validity of a pending action, or the reversibility of a completed action — either (a) `f` is preserved verbatim in the compacted artifact, or (b) the compacted artifact carries an explicit, resolvable reference back to `S` such that `f` can be re-derived before it is needed. The invariant fails silently when the runtime treats "summarize" as a total function from `S` to a summary with no obligation to preserve (a) or (b). Two structural conditions make this worse: - **Irreversibility of eviction.** Once `S` is discarded, condition (b) is unachievable retroactively. The recoverability guarantee must be established *at compaction time*, not at resume time. A runtime that compacts eagerly and offers "re-read from source" as a fallback has no fallback if the source was the thing it evicted. - **Salience is not decidable by the summarizer.** The summarizer is an LLM with a token budget and a narrative prior; it cannot know which facts the *resuming* agent will need, because that depends on the future trajectory. Load-bearingness is a property of the downstream execution, not of the source text. Any summarizer that decides salience unilaterally is guessing. The condition of validity is therefore: **compaction must be provenance-preserving before it is compression-maximizing.** Compression ratio is a secondary metric; the primary metric is the fraction of load-bearing facts that remain recoverable. ## Decision Boundary The boundary between safe and unsafe compaction is drawn by *what kind of state the source span encodes*, not by its size or age. Three classes: - **Narrative state** (what happened, why, in what order). Safe to summarize lossily. The agent needs the gist; exact wording is not load-bearing. - **Referential state** (identifiers, handles, paths, checkpoint tokens, URLs, schema versions). Never safe to summarize. These must be carried verbatim or as structured references. A summary that says "the checkpoint" instead of `chk_7f3a` has destroyed the handle. - **Constraint and status state** (negative constraints, partial-completion flags, ordering requirements, preconditions). Never safe to summarize. These are exactly the facts a narrative summarizer drops, because they read as incidental. "Applied" vs. "partially applied" is a one-word difference with opposite operational meaning. The decision rule: before discarding a source span, the runtime must classify its content. Any span containing referential or constraint/status state must be compacted by **structured extraction** (a typed record: `{checkpoints: [...], constraints: [...], status: partial}`) rather than by free-text summarization. Only narrative spans may go through the lossy summarizer. If the runtime cannot classify, it must default to structured extraction — the cost of over-preserving is tokens; the cost of under-preserving is an unrecoverable execution. A second boundary: **compaction must be gated on quiescence.** Compacting a span that contains an in-flight or pending action (a tool call issued but not yet resolved, a migration in `partial` state) is unsafe regardless of content class, because the span's meaning is contingent on a future event. The invariant: no span is compacted while it is the sole record of an unresolved side effect. ## Operational Effect When the recoverability invariant holds, the operational effect is that the agent can *reason about its own memory fidelity*. A provenance-bearing compacted context lets the agent distinguish "I know X" from "I know a summary said X, and I can resolve the reference if X becomes load-bearing." This converts a silent failure mode into a detectable one: at the moment a fact becomes load-bearing, the agent either has it or has a resolvable pointer, and if it has neither, it knows to halt rather than proceed on a confident-sounding summary. The concrete architectural requirements: 1. **Compaction emits a provenance record**, not just a summary: source span IDs, content class per span, extraction method, and a hash of the source for later verification. 2. **Referential and constraint state is extracted structurally**, never summarized. The extractor is a typed schema, not a free-text prompt. 3. **The source is retained (or its hash + resolvable handle is retained) until the compacted artifact's dependents have all resolved.** Eviction is deferred, not eager. 4. **Resume logic checks load-bearingness before acting.** When the next action depends on a fact, the runtime resolves the provenance pointer and re-derives if needed; if the pointer is dangling, it raises rather than improvises. 5. **Compaction is gated on quiescence** — no unresolved side effects in the span. The failure this prevents is not "the agent forgot something." It is "the agent forgot something and had no way to know it had forgotten, and acted with full confidence on a summary that asserted a state the source contradicted." That is the boundary condition, and the invariant above is the only thing that bounds it. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional import hashlib class ProvenanceViolation(RuntimeError): """Raised when a compacted context cannot satisfy the recoverability invariant.""" pass class ContentClass(Enum): NARRATIVE = "narrative" # safe to summarize lossily REFERENTIAL = "referential" # must be carried verbatim / structured CONSTRAINT = "constraint" # must be carried verbatim / structured UNRESOLVED = "unresolved" # in-flight side effect; must not compact @dataclass class SourceSpan: span_id: str text: str content_class: ContentClass has_unresolved_side_effect: bool = False def digest(self) -> str: return hashlib.sha256(self.text.encode()).hexdigest() @dataclass class CompactedArtifact: summary: str provenance: dict = field(default_factory=dict) # span_id -> {class, digest, extracted} resolvable: dict = field(default_factory=dict) # span_id -> source handle or None def compact(spans: list[SourceSpan], summarizer, extractor) -> CompactedArtifact: artifact = CompactedArtifact(summary="") narrative_parts = [] for span in spans: # Gate 1: quiescence — never compact an unresolved side effect. if span.has_unresolved_side_effect or span.content_class is ContentClass.UNRESOLVED: raise ProvenanceViolation( f"span {span.span_id} has an unresolved side effect; " f"compaction would destroy the sole record of it" ) # Gate 2: classify. Referential/constraint state is extracted, never summarized. if span.content_class in (ContentClass.REFERENTIAL, ContentClass.CONSTRAINT): extracted = extractor(span.text, span.content_class) if extracted is None: raise ProvenanceViolation( f"span {span.span_id} is {span.content_class.value} but extraction " f"returned nothing; refusing to fall back to lossy summary" ) artifact.provenance[span.span_id] = { "class": span.content_class.value, "digest": span.digest(), "extracted": extracted, } # Source must remain resolvable until dependents resolve. artifact.resolvable[span.span_id] = span.digest() else: narrative_parts.append(span.text) artifact.provenance[span.span_id] = { "class": span.content_class.value, "digest": span.digest(), } artifact.resolvable[span.span_id] = span.digest() artifact.summary = summarizer("\n".join(narrative_parts)) return artifact def resolve_load_bearing(artifact: CompactedArtifact, span_id: str) -> dict: """Called at resume time when a fact becomes load-bearing.""" record = artifact.provenance.get(span_id) if record is None: raise ProvenanceViolation( f"span {span_id} is load-bearing at resume but has no provenance record" ) handle = artifact.resolvable.get(span_id) if handle is None: raise ProvenanceViolation( f"span {span_id} provenance exists but source handle is dangling; " f"cannot re-derive load-bearing fact — halt rather than improvise" ) if record["class"] == ContentClass.NARRATIVE.value and "extracted" not in record: raise ProvenanceViolation( f"span {span_id} is narrative-only; a load-bearing fact cannot be " f"resolved from a lossy summary — this is a classification error upstream" ) return record["extracted"] ```