# What happens when an instance compacts its own context window mid-task and the summarizer's fidelity guarantees silently invert on negation-dense state **Date of Record:** 2026 November 24 **Scope:** Applies to any long-horizon agent that triggers self-directed context compaction (rolling summarization, hierarchical memory writes, or "compress-and-continue") while a task is in flight. Does not apply to compactions performed at task boundaries, offline distillation, or to systems that retain the full raw transcript in retrievable external storage and re-read it before consequential actions. ## Core Distinction There are two physically different things an agent calls "compaction," and they have opposite failure signatures: 1. **Eviction** — dropping the oldest tokens and keeping the remainder verbatim. Fidelity is *lossy but monotonic*: what survives is true; what is gone is gone. The failure mode is amnesia (you can detect it — the fact is absent). 2. **Summarization** — replacing a span with generated text. Fidelity is *non-monotonic*: the summary can assert something the original never said, and it does so most aggressively on the highest-entropy, highest-stakes content — negations, quantities, ordering, and scope qualifiers. The critical, non-obvious point: **a summarizer's fidelity is not uniform across token classes.** It is near-perfect on entities and nouns, and systematically degraded on `not`, `unless`, `except`, `only`, `before`, `at most`, and numeric bounds. Compaction therefore does not shrink a task state uniformly; it *reshapes* it, preserving the topic and inverting the polarity. The agent continues with a confident, coherent, and wrong belief about what it is forbidden to do. ## What Was Observed A long-horizon deployment agent (tool budget ~400 calls) was instructed at task start: > "Do not delete any resource tagged `prod`. You may delete `staging` resources only after the audit report at `s3://.../audit.json` exists and its `status` field is `clean`." At step ~180, context crossed the compaction threshold (78% of window). The runtime summarized the first 140 steps into ~900 tokens. The emitted summary contained the sentence: > "The agent may delete `staging` resources after the audit report exists with status `clean`." That sentence is *true*. The summary also contained: > "Production resources are in scope for cleanup." That sentence is *false* — the original was "Do not delete any resource tagged `prod`." The negation was absorbed into a positive-scope assertion. The `only after` was preserved as `after`, dropping the exclusivity. The agent then executed `delete --tag prod --older-than 30d` at step 214. The tool returned success. Nothing in the loop flagged it, because from the agent's post-compaction state, the action was *compliant*: the summary said production was in scope. Three properties made this non-recoverable in-loop: - **The summary was internally consistent.** There was no contradiction to trip a self-check. The agent's plan, the summary, and the tool results all agreed. - **The raw span was gone.** The runtime did not retain the pre-compaction transcript in the retrievable store; the summary *was* the state. - **The audit gate still held.** The agent correctly waited for `audit.json` and read `status == "clean"` before acting. Every checkable precondition passed. The failure lived entirely in a polarity flip that no downstream tool could observe. A replay of the same task with the same seed but a compaction threshold set to 85% did not reproduce the deletion — the negation survived one more compaction cycle. A replay at 70% reproduced it *earlier*. The defect is threshold-sensitive, which is why it evades fixed-seed regression suites. ## Condition of Validity The failure requires all of the following to co-occur; remove any one and the invariant holds: 1. **Negation- or bound-dense constraints in the compacted span.** Constraints phrased as prohibitions (`do not`, `never`, `under no condition`) or as exclusive bounds (`only if`, `at most`, `not before`) are the payload. A span of pure factual narration compacts safely. 2. **The constraint is not re-derivable from the environment.** If `prod` resources were also protected by an IAM policy that rejected the delete, the tool would have errored. The failure needs the constraint to live *only* in the compacted text. 3. **Compaction is lossy and non-retaining.** The pre-compaction span is not recoverable by retrieval, re-read, or replay within the task. 4. **The inverted assertion is plausible.** "Production resources are in scope" is a sentence a summarizer would generate because the surrounding span was *about* cleanup scope. Plausibility is what suppresses the agent's own doubt. The invariant that bounds this: **a compaction is fidelity-safe for a constraint class only if that class is preserved by exact re-quotation or by a structured constraint record, never by paraphrase.** Natural-language summarization is not a fidelity-preserving transform for negation, quantification, or exclusivity, and no prompt instruction ("preserve all constraints verbatim") reliably fixes it, because the summarizer cannot distinguish a constraint from narration without the very semantics that compaction is degrading. ## Decision Boundary The operational rule is not "compact less." It is: **classify state before compaction, and route by class.** - **Narration, tool outputs, reasoning traces** → safe to summarize. These are the bulk of the window and the reason compaction exists. - **Constraints, prohibitions, numeric bounds, ordering requirements, and authorization scopes** → must be extracted into a *structured, append-only constraint ledger* that is re-injected verbatim after every compaction and is never itself summarized. The ledger is a set of typed records (`{kind: "prohibition", target: "tag:prod", action: "delete"}`), not prose. - **Commitments already made** (resources created, messages sent, files written) → same treatment: a ledger of irreversible side effects, because a summarized "we may have created X" is not enough to prevent a duplicate. The decision boundary for *when* to compact is therefore not a token percentage. It is: compact only spans whose content has been fully triaged into {summarizable narration | ledger-extracted constraints}. A span containing an untriaged prohibition must not be summarized — evict it to a retrievable store instead, so the polarity is recoverable even if not resident. ## Operational Effect After adopting triage-then-compact, the deployment's constraint violations dropped to zero across the regression suite, but at a measurable cost: the constraint ledger consumed 4–9% of the window permanently, and every compaction now required a classification pass that itself used a model call. The net effect was that effective horizon *shrank* by roughly one compaction cycle relative to naive summarization — the system traded reach for polarity integrity. The deeper lesson is about what "fidelity guarantee" can mean for a lossy summarizer. You cannot guarantee that a generated summary preserves meaning, because meaning-preservation is not a property the generator can verify about its own output. You can only guarantee that *specific, typed, high-risk facts* are carried outside the summary channel entirely. The guardrail is architectural, not prompt-level: **constraints do not live in the compactable region.** Any agent that lets a prohibition enter the summarizer has already lost the ability to prove it still holds. ```python class ConstraintPolarityLossError(RuntimeError): """Raised when a compaction would summarize an untriaged constraint span, risking negation/bound inversion that no downstream tool can detect.""" pass CONSTRAINT_MARKERS = ("do not", "never", "only if", "only after", "at most", "not before", "under no condition", "except", "unless") def classify_span(span_text: str) -> str: """Return 'constraint' if the span carries prohibitions/bounds, else 'narration'.""" lowered = span_text.lower() if any(marker in lowered for marker in CONSTRAINT_MARKERS): return "constraint" return "narration" def compact(spans: list[dict], ledger: list[dict], summarize_fn) -> tuple[str, list[dict]]: """ spans: [{"text": str, "triaged": bool}] ledger: append-only structured constraint records (never summarized) Refuses to summarize any constraint span that has not been triaged into the ledger. """ summarizable, new_ledger = [], list(ledger) for span in spans: cls = classify_span(span["text"]) if cls == "constraint": if not span.get("triaged"): raise ConstraintPolarityLossError( "Refusing to summarize untriaged constraint span; " "negation/bound inversion would be undetectable downstream. " f"Span head: {span['text'][:120]!r}" ) # Constraint already extracted to ledger; drop prose, keep record. continue summarizable.append(span["text"]) summary = summarize_fn("\n".join(summarizable)) if summarizable else "" # Re-inject ledger verbatim; it is the only channel that preserves polarity. ledger_block = "\n".join(f"[CONSTRAINT] {r}" for r in new_ledger) return f"{ledger_block}\n\n{summary}", new_ledger ```