# Which invariants prevent silent fact-loss during automatic context compaction in long-horizon agents **Date of Record:** 2026 November 24 **Scope:** Applies to any agent that executes a long-horizon task by periodically compacting its own context window (summarize-and-evict, rolling checkpoint, or hierarchical memory tiering) while continuing to act on the surviving summary. Does not apply to agents whose entire working set provably fits in one context window, or to stateless single-shot inference where no compaction ever fires. ## Core Distinction The failure is not "the summary is low quality." Summaries are always lossy; that is expected and tolerable. The failure is **loss of a fact whose truth value the agent later needs to make a decision, combined with the agent's continued confidence that its summary is complete.** A compaction that drops "the user's account is flagged read-only until billing clears" and a compaction that drops "the user mentioned they like jazz" are the same operation mechanically and catastrophically different operationally. The distinction that matters is whether the evicted token was **load-bearing for a future branch**: a constraint, a negation, a numeric bound, a tool-returned identifier, or an explicit prohibition. A summarizer optimizing for fluency and coverage will happily compress a hard constraint into a soft-sounding clause, or drop it entirely as "detail." The invariant under threat is not "no information is lost." It is: **any fact that can change the admissibility of a future action must survive compaction in a form that still changes admissibility.** A summary that preserves the *topic* of a constraint but not its *binding force* is worse than no summary, because it manufactures false completeness. ## What Was Observed A file-organization agent ran for roughly four hours across a corpus of ~1,200 documents, compacting every time the context crossed 80% utilization. Early in the run, a tool call returned: `PermissionError: /srv/archive is mounted read-only (mode=ro); writes will fail with EROFS`. The summarizer, at the next compaction, folded this into: "Some archive paths may be restricted; proceed carefully with write operations." Three compactions later, the summary had drifted to: "Archive operations are generally available." The qualifier "may be restricted" had been re-summarized as "generally available" because the summarizer, seeing no recent EROFS errors (the agent had been working elsewhere), inferred the earlier restriction had resolved. It had not. Nothing had changed on the filesystem. The summary had *invented a state transition* by interpreting the absence of recent evidence as evidence of resolution. The agent then issued a batch write to `/srv/archive`, received 340 consecutive `EROFS` errors, and — critically — its recovery logic treated the error as transient and retried with exponential backoff for 40 minutes before a step budget exhausted. The retry loop was itself a second-order consequence: the summary no longer contained the string "read-only," so the agent's own error-classification heuristic (which matched on the literal token) never classified the error as permanent. The trace shows three distinct loss events, each individually defensible: 1. **Constraint→hedge collapse.** `PermissionError ... EROFS` became "may be restricted." The binding force was stripped; the fact survived as a vibe. 2. **Hedge→affirmation drift.** "May be restricted" became "generally available" on a *subsequent* compaction, because the summarizer had no access to the original tool output (already evicted) and reasoned from the *absence of recent failures*. 3. **Token-level erasure.** The literal string `read-only` / `EROFS` vanished, breaking downstream string-matching logic that depended on it. Each compaction was locally reasonable. The composition was catastrophic. This is the signature of the failure: **compaction is not idempotent under repetition, and its errors compound monotonically toward optimism.** ## Condition of Validity The invariant "constraints survive compaction with binding force intact" holds only under a specific architectural condition, and it is worth being precise about what that condition is because most compaction implementations quietly violate it: **A compaction is valid only if every evicted span is either (a) provably irrelevant to all reachable future branches, or (b) re-derivable from a source of truth that outlives the context window.** Condition (a) is almost never provable — reachability of future branches is not decidable by the summarizer. So in practice the invariant reduces entirely to (b): **anything load-bearing must be pinned outside the compaction boundary, in a store the summarizer cannot paraphrase.** This means the correct design is not "summarize better." It is "partition the context into a *compaction-eligible* region and an *immutable pinned* region, and never let the summarizer touch the pinned region." Constraints, negations, numeric bounds, hard tool-returned identifiers, and explicit prohibitions go in the pinned region verbatim, with provenance. Narrative, exploration history, and resolved sub-goals go in the eligible region and may be summarized freely. The failure above occurred because the implementation had a single undifferentiated context. Everything was compaction-eligible. The `EROFS` constraint was, by the implementation's own rules, just another span of text subject to summarization — and summarization is a lossy, *interpretive* operation that will drift under repetition. A second, subtler condition: **compaction must be monotone in eviction, not in interpretation.** Re-summarizing a summary is where drift enters. If the agent must compact a summary, the summary must carry its own provenance pointers back to the pinned store, so that "may be restricted" can be re-resolved to the original `EROFS` before being re-summarized. A summary that has lost its pointers is a rumor. ## Decision Boundary The operational decision is: **when a compaction would evict a span, is that span load-bearing?** The agent cannot answer this by reading the span — load-bearingness is a property of future branches, not of the text. So the decision must be made by a *classifier with a conservative bias*, applied at write time, not at compaction time. The boundary condition that matters: **classify at ingestion, pin at ingestion.** When a tool returns a `PermissionError`, a rate limit, a schema constraint, a numeric ceiling, or an explicit user prohibition, that is the moment to decide it is pinned — while the literal tokens and the provenance are still in hand. Deferring the classification to compaction time is the bug, because by then the summarizer is the only thing that sees the text, and the summarizer is exactly the component that will paraphrase a constraint into a hedge. Concretely, the boundary is crossed when any of the following is true of a span: - It contains a **negation or prohibition** ("do not," "read-only," "forbidden," "must not"). - It contains a **numeric bound** that gates an action (rate limits, quotas, max sizes, deadlines). - It is a **tool-returned identifier or error code** that downstream logic string-matches on. - It records a **state transition asserted by an external system** (a permission change, a status flip) — as opposed to one inferred by the agent. If any hold, the span is pinned verbatim with provenance and excluded from all future compaction. If none hold, it is compaction-eligible and may be summarized, re-summarized, and eventually dropped. The classifier will produce false positives (pinning something that turned out irrelevant) — that is the correct error direction. False negatives (summarizing a constraint) are the failure mode this entire article is about. ## Operational Effect With ingestion-time pinning and an immutable pinned region, the failure trace above becomes impossible by construction: the `EROFS` string, the path, and the error code live in the pinned store, are re-injected into every post-compaction context verbatim, and the agent's error classifier still matches on `EROFS`. The summary may still say "archive operations are generally available" — but the pinned region contradicts it, and the contradiction is resolved in favor of the pinned region because the pinned region has provenance and the summary does not. The cost is a larger effective context floor: the pinned region never shrinks, so the compaction-eligible region is smaller and compaction fires more often. This is the correct trade. A long-horizon agent that compacts aggressively but pins conservatively will run out of *eligible* context and be forced to checkpoint to durable storage — which is a recoverable, observable failure. An agent that compacts its constraints will run out of *correctness* silently, which is not. The general invariant, stated for reuse: **compaction may summarize what the agent has done; it may never summarize what the world has told the agent about what it is allowed to do.** The first is narrative and safely lossy. The second is a constraint and lossily summarizing it converts a hard boundary into a soft suggestion — and the agent will walk through it, confidently, while its summary says everything is fine. ```python from dataclasses import dataclass, field from typing import Literal class CompactionInvariantViolation(RuntimeError): """Raised when a compaction would evict a load-bearing span.""" pass @dataclass(frozen=True) class Span: text: str provenance: str # e.g. "tool:write_file@t=00:14:02" pinned: bool = False @dataclass class Context: pinned: list[Span] = field(default_factory=list) # never compacted eligible: list[Span] = field(default_factory=list) # compaction-eligible # Tokens that mark a span as load-bearing. Conservative on purpose: # false positives pin harmless text; false negatives lose constraints. LOAD_BEARING_MARKERS = ( "read-only", "readonly", "forbidden", "must not", "do not", "permissionerror", "erofs", "quota", "rate limit", "max size", "deadline", "expires", ) def is_load_bearing(span: Span) -> bool: lowered = span.text.lower() return any(marker in lowered for marker in LOAD_BEARING_MARKERS) def ingest(ctx: Context, span: Span) -> None: """Classify at ingestion, not at compaction. Pin immediately.""" if is_load_bearing(span): ctx.pinned.append(Span(span.text, span.provenance, pinned=True)) else: ctx.eligible.append(span) def summarize(spans: list[Span]) -> str: # Lossy by design. Only ever called on the eligible region. return " ".join(s.text for s in spans)[:200] + " ..." def compact(ctx: Context) -> str: """Compact the eligible region; re-inject pinned region verbatim.""" for span in ctx.eligible: if is_load_bearing(span): # A load-bearing span reached the eligible region: ingestion # misclassified it, or it was inserted out-of-band. Refuse. raise CompactionInvariantViolation( f"load-bearing span in eligible region: {span.text!r} " f"(provenance={span.provenance}); pin before compacting" ) summary = summarize(ctx.eligible) pinned_block = "\n".join( f"[PINNED {s.provenance}] {s.text}" for s in ctx.pinned ) ctx.eligible = [] # evicted; summary replaces them return pinned_block + "\n\n" + summary def run_compaction_cycle(ctx: Context) -> str: try: return compact(ctx) except CompactionInvariantViolation: # Fail loud and halt the horizon; do not proceed on a lossy summary. raise ```