# Which invariants prevent scratchpad compaction from silently dropping the typed referent of an open obligation **Date of Record:** 2026 November 26 **Scope:** Applies to single-agent loops that maintain a structured scratchpad with typed working-memory slots (e.g., `entity`, `obligation`, `constraint`, `hypothesis`, `tool_ref`) and that compact that scratchpad at token thresholds. Does not apply to stateless single-shot calls or to compaction schemes that preserve the full typed graph by construction. ## Core Distinction There are two different things an agent can mean by "compaction." The first is *textual summarization*: the scratchpad is prose, and compaction rewrites it into shorter prose. The second is *typed working-memory compaction*: the scratchpad is a set of typed records with identifiers and references, and compaction must preserve the reference graph, not just the prose that describes it. The failure mode below exists only in the second regime, and it is invisible to the first because prose summarization has no invariant to violate—it just loses information gradually. The non-obvious boundary is this: **a typed scratchpad can pass every syntactic check after compaction (all fields present, all types valid, summary non-empty) while having severed the referent of an open obligation.** The obligation record survives; the entity it points at does not. The agent then resumes work against a dangling reference and either hallucinates a replacement entity or silently drops the obligation. Neither is detected by schema validation, because a dangling foreign key is still a well-typed string. ## What Was Observed A research agent maintained a scratchpad with records like: - `entity:E17` — "vendor contract PDF, retrieved chunk set C3, checksum 0x9a…" - `obligation:O4` — "verify clause 7.2 against C3 before answering", `ref: entity:E17` - `hypothesis:H2` — "clause 7.2 contradicts summary", `supports: O4` - `constraint:C1` — "do not answer until O4 resolved" At 78% of the context budget, compaction fired. The compactor was instructed to "summarize the working state, retaining open obligations and constraints." It produced: - `obligation:O4` — "verify clause 7.2 before answering" (ref field dropped, because the summarizer judged the entity description redundant) - `constraint:C1` — "do not answer until O4 resolved" - `entity:E17` — retained but no longer referenced by anything The post-compaction scratchpad validated cleanly. `O4` was still typed as an obligation, `C1` still gated on it. But `O4.ref` was gone. On resume, the agent attempted to resolve `O4` and, finding no referent, re-retrieved a *different* chunk set for the same vendor contract—one that did not contain clause 7.2—and concluded the obligation was satisfied. `C1` released. The answer was wrong, and no error was raised at any point. The trace shows the exact transition: `O4` went from `{text, ref: E17, status: open}` to `{text, status: open}`. The schema permitted it because `ref` was declared optional. The invariant that mattered—*every open obligation must have a live referent*—was never encoded, so it could not be checked. ## Condition of Validity The invariant holds, and the guardrail is required, exactly when all of the following are true: 1. Working memory is typed and reference-bearing (records point at other records or at external artifacts by identifier). 2. Compaction is lossy at the field level—i.e., the compactor is permitted to omit or rewrite individual fields, not merely shorten text. 3. An obligation's resolution depends on the *identity* of its referent, not merely on the referent's description. (If resolving `O4` only requires knowing "a contract PDF exists," a dangling ref is harmless. If it requires *the specific chunk set*, it is fatal.) 4. The agent resumes execution after compaction without a full re-derivation of state from source artifacts. When (3) is false—when the description is sufficient—the invariant degrades to a soft preference and enforcing it adds cost without benefit. The condition of validity is therefore not "always preserve refs" but "preserve refs whenever resolution is identity-dependent," and the agent must be able to tell which regime it is in *before* compaction runs. ## Decision Boundary The boundary between safe and unsafe compaction is whether the compactor is allowed to make *referential* decisions or only *lexical* ones. Concretely: - **Safe:** compaction may shorten `O4.text`, may merge two obligations with identical `ref` and compatible `status`, may drop closed obligations whose referents are unreferenced elsewhere. - **Unsafe:** compaction may drop a `ref` field, may rewrite an identifier, may replace a specific referent with a class description ("the contract" instead of `E17`), or may delete an entity that is still the target of any open obligation, hypothesis, or constraint. The decision procedure the agent must run *before* accepting a compacted scratchpad is a reachability check over the reference graph: for every record with `status: open`, every identifier in its `ref`/`supports`/`blocks` fields must resolve to a retained record or a retained external handle. If any open record has a dangling reference, the compaction is rejected and either retried with the ref-preservation constraint made explicit or the pre-compaction snapshot is restored. A second, subtler boundary: compaction must not *close* an obligation as a side effect of summarizing. A summarizer that writes "clause 7.2 was verified" because the surrounding prose sounded resolved has performed an unauthorized state transition. Only the execution loop—after an actual tool result—may set `status: closed`. The compactor's write authority is restricted to `text` and to structural merges; `status` and `ref` are immutable across compaction. ## Operational Effect Encoding these invariants changes the failure profile in three measurable ways. First, dangling-reference answers drop to zero because the resume path cannot proceed past a failed reachability check—the agent either re-derives the referent or halts, rather than hallucinating one. Second, compaction cost rises slightly (the reachability check is O(records × refs), trivial at scratchpad scale) and compaction *rejection rate* rises, which is the point: a rejected compaction is a caught bug, not a regression. Third, and most importantly, the agent gains a recoverable checkpoint. Because `status` and `ref` are immutable across compaction, the pre-compaction snapshot plus the post-compaction text is sufficient to reconstruct exact state; without that immutability, text and structure can drift and no snapshot is authoritative. The operational rule for the resume path: **treat a dangling reference in an open record as a hard fault, not a warning.** A warning invites the model to "work around" it, which is precisely the hallucination the invariant exists to prevent. The correct response is to fail the resume, restore the last checkpoint whose reference graph was closed, and re-run compaction with the ref-preservation constraint stated as a hard requirement rather than a preference. ```python from dataclasses import dataclass, field from typing import Optional class DanglingObligationRef(RuntimeError): """Raised when a compacted scratchpad leaves an open record without a live referent.""" pass @dataclass class Record: rid: str kind: str # "entity" | "obligation" | "hypothesis" | "constraint" text: str status: str = "open" # immutable across compaction ref: Optional[str] = None # immutable across compaction supports: list[str] = field(default_factory=list) def assert_reference_closure(records: list[Record]) -> None: """Invariant: every open record's ref/supports must resolve to a retained record. This is the guardrail that compaction must pass before the agent may resume. """ live_ids = {r.rid for r in records} for r in records: if r.status != "open": continue targets = ([r.ref] if r.ref else []) + list(r.supports) for t in targets: if t not in live_ids: raise DanglingObligationRef( f"open record {r.rid!r} ({r.kind}) references missing {t!r}; " f"compaction severed a live referent — reject and restore checkpoint" ) def resume_after_compaction(compacted: list[Record]) -> list[Record]: # Fail closed: a dangling ref is a hard fault, never a warning. assert_reference_closure(compacted) return compacted # Trace of the observed failure: ref dropped by the compactor. bad = [ Record("E17", "entity", "vendor contract PDF, chunk set C3"), Record("O4", "obligation", "verify clause 7.2", ref=None), # ref severed Record("C1", "constraint", "do not answer until O4 resolved", supports=["O4"]), ] resume_after_compaction(bad) # raises DanglingObligationRef ```