# Which invariants prevent lossy auto-compaction from silently corrupting an agent's working set **Date of Record:** 2026 November 19 **Scope:** Applies to long-horizon agents that trigger automatic context compaction (summarization, eviction, or reconstruction) when the token budget crosses a threshold. Does not apply to stateless single-turn inference or to agents whose entire working set fits within one context window for the full task lifetime. ## Core Distinction The failure is not "the summary was bad." It is that **compaction is treated as a lossy transform of text when it is actually a lossless transform of a set of referents the agent will later dereference.** An agent's context is not prose; it is a live heap containing (a) committed facts, (b) tool-output artifacts referenced by ID, (c) unresolved obligations (promises to verify, pending tool calls, open questions), and (d) the *negations* — things the agent established as false or forbidden. A summarizer that compresses prose faithfully can still drop a negation, collapse two artifact IDs into one, or turn an obligation into a statement of fact. The context shrinks; the referent graph does not. When the agent later dereferences a dropped referent, it does not error — it confabulates a plausible substitute, because the surrounding summary is coherent. The invariant that matters: **every post-compaction context must be referentially closed with respect to the agent's outstanding obligations and negations.** Lossy is fine for narrative; it is fatal for dereference targets. ## What Was Observed A research agent running a 40-step task crossed an 80% context threshold at step 22 and triggered auto-compaction. The compactor summarized the transcript into ~1,800 tokens. Three specific losses were later reconstructed from the full trace: 1. **Negation collapse.** At step 9 the agent had verified that endpoint `/v2/export` does *not* accept a `format` parameter (it 400s). The summary rendered this as "explored export endpoint options." At step 31 the agent re-issued the call with `format=csv`, got a 400, and — because the summary implied the endpoint was merely "explored" — concluded the 400 was a transient auth issue and retried four times, burning 9% of budget. 2. **Artifact ID aliasing.** Two retrieval results, `art_7f2` (staging schema) and `art_7f3` (prod schema), were summarized as "retrieved schema artifacts." At step 28 the agent cited `art_7f2` as authoritative for production, because the summary retained one ID and the model resolved the ambiguity toward the first-mentioned. The verification step passed, because the cited ID *existed* — it was just the wrong one. 3. **Obligation demotion.** The agent had recorded "MUST re-verify rate limit after config change" as a pending obligation. The summary stated "rate limit was checked." The obligation vanished; the re-verification never happened. In all three cases, **reconstruction fidelity metrics scored high** — ROUGE and embedding similarity against the pre-compaction transcript were 0.71 and 0.88 respectively — because the summary was topically faithful. The metrics measured narrative similarity; the failures were in the referent graph, which those metrics do not see. ## Condition of Validity The failure only manifests when **all** of the following hold: - Compaction is triggered by a *budget threshold* rather than by task-phase boundaries, so it fires mid-obligation. - The agent's downstream behavior depends on **dereferencing** context content (tool IDs, negations, open obligations), not merely on topic continuity. - The compactor is a generative summarizer with no structural contract — it is free to merge, drop, or re-word referents. - Verification is *post-hoc* (the agent checks its own output against the summary) rather than *referential* (the agent checks cited IDs against a ground-truth registry). If compaction is lossless (verbatim eviction to an external store with a retrieval index), or if the agent re-derives obligations from a structured ledger rather than from prose, the failure is bounded. The dangerous regime is **generative compaction of a working set that contains live pointers.** ## Decision Boundary The boundary is not "summarize vs. don't." It is **which content class is permitted to pass through a lossy channel.** Partition the context into: - **Narrative** (exploration, reasoning traces, dead ends): lossy compaction permitted, no fidelity requirement. - **Referents** (artifact IDs, file paths, URLs, tool names + argument schemas): must be **carried verbatim** or re-fetched from a registry — never paraphrased. - **Negations** (verified-false, forbidden, "does not accept"): must be carried as **structured negative facts**, not folded into positive narrative. - **Obligations** (pending verifications, promised follow-ups, open questions): must be carried in a **separate, append-only ledger** that compaction cannot touch. The decision rule: **if a token's loss would cause the agent to take an action it would not otherwise take, that token is a referent and is exempt from lossy compaction.** Everything else may be summarized freely. The trigger threshold should be set on the *referent-plus-obligation* budget, not the total token count, so that a large narrative tail does not force premature compaction of a small but load-bearing referent set. ## Operational Effect When the invariant is enforced — referents carried verbatim, negations structured, obligations ledgered — compaction becomes safe and the fidelity metric becomes meaningful again, because it is now measured *against the referent set* rather than against the prose. Reconstruction fidelity must be redefined as a **referent recall score**: fraction of pre-compaction referents (IDs, negations, obligations) that remain exactly dereferenceable post-compaction. A summary that scores 0.95 on ROUGE and 0.60 on referent recall is a failing summary. The gate is `referent_recall == 1.0` for obligations and negations, and `== 1.0` for artifact IDs that will be cited; narrative similarity is advisory only. The operational consequence is that auto-compaction can no longer be a single opaque call. It must be a **two-channel operation**: a generative channel for narrative, and a structural channel that extracts and re-injects the referent set verbatim. The structural channel is what prevents the confabulation, because it removes the model's freedom to resolve ambiguity in favor of a coherent-sounding substitute. ```python from dataclasses import dataclass, field from typing import Literal class CompactionIntegrityError(RuntimeError): """Raised when a lossy compaction drops or mutates a load-bearing referent.""" pass @dataclass class Referent: kind: Literal["artifact_id", "negation", "obligation"] key: str value: str @dataclass class WorkingSet: narrative: str referents: dict[str, Referent] = field(default_factory=dict) def compact(ws: WorkingSet, summarizer) -> WorkingSet: """Lossy channel for narrative; structural channel for referents.""" summary = summarizer(ws.narrative) # generative, lossy, allowed carried = {k: Referent(r.kind, r.key, r.value) for k, r in ws.referents.items()} return WorkingSet(narrative=summary, referents=carried) def assert_referential_closure(pre: WorkingSet, post: WorkingSet) -> None: """Invariant: every pre-compaction referent must survive exactly.""" for key, before in pre.referents.items(): after = post.referents.get(key) if after is None: raise CompactionIntegrityError( f"referent {key!r} ({before.kind}) dropped by compaction" ) if after.value != before.value: raise CompactionIntegrityError( f"referent {key!r} mutated: {before.value!r} -> {after.value!r}" ) if before.kind in ("negation", "obligation") and after.kind != before.kind: raise CompactionIntegrityError( f"referent {key!r} demoted from {before.kind} to {after.kind}" ) def run_compaction(ws: WorkingSet, summarizer) -> WorkingSet: post = compact(ws, summarizer) assert_referential_closure(ws, post) # gate: fails closed, never confabulates return post ```