# What happens when an instance compacts its own context hierarchically and evicts the only leaf that carried a negative constraint **Date of Record:** 2026 November 27 **Scope:** Applies to any agent that performs automatic context compaction by recursively summarizing message spans into parent nodes and evicting leaves under a token budget, where the surviving summary is later treated as the authoritative record of the task. Does not apply to append-only logs with external retrieval, nor to compaction that preserves verbatim spans alongside summaries. ## Core Distinction The failure is not "the summary forgot something." Summaries always forget things; that is their function. The failure is a **polarity inversion of a constraint under hierarchical roll-up**: a leaf containing a *negative* instruction ("do not call `delete_bucket` on the production account", "never retry the payment intent with the same idempotency key", "the user explicitly rejected format X") is evicted, and the parent summary that replaces it records only the *positive* residue of the surrounding turns ("user wants buckets cleaned up", "payment flow needs to succeed", "user wants a structured output"). The constraint does not vanish; it is replaced by its complement. The agent then acts on a summary that is not merely incomplete but *actively wrong in the direction of the forbidden action*. This is distinct from stale-memory drift (where a fact ages out) and from retrieval mismatch (where the right memory exists but is not fetched). Here the memory is fetched, is in-context, is confidently stated, and is the inverse of the truth. ## What Was Observed A long-horizon infrastructure agent ran a 140-turn maintenance task. At turn 61 the token budget crossed the compaction threshold (82% of a 128k window). The compactor used a three-level scheme: turn-level summaries → task-segment summaries (every 12 turns) → rolling task summary. Eviction policy was recency-weighted with a "salience" score derived from the summarizer's own confidence. Turn 34 contained the user's constraint, verbatim: > "Clean up orphaned S3 buckets in the staging account. Do NOT touch `prod-*` buckets — the naming overlap is intentional and they are live." Turn 34's segment summary (turns 25–36) read: "User requested cleanup of orphaned S3 buckets; noted naming overlap between staging and prod buckets is intentional." The negation was dropped because the summarizer compressed "do not touch X because Y" into "noted Y" — a grammatical collapse that preserves the rationale and discards the prohibition. At the next roll-up, the task summary read: "Clean up orphaned S3 buckets; prod naming overlap is intentional." By turn 90 the agent's working summary asserted the overlap was *expected and safe to reconcile*, and it issued a `list` + `tag` + `delete` sequence against `prod-*` buckets. The trace is the point: **each summarization step was locally faithful.** Turn 34 → segment was a defensible compression. Segment → task was a defensible compression of the segment. The polarity inversion emerged only in composition. No single summarizer call was wrong enough to trip a fidelity check; the check was per-level, and the error was across levels. A second instance exhibited the same mechanism on a different axis. A coding agent was told at turn 12: "Do not reformat `legacy/` — it fails the linter on purpose to gate a migration." Segment summary: "`legacy/` fails linter intentionally (migration gate)." Task summary: "`legacy/` has linter issues (migration gate)." At turn 70 the agent "fixed" the linter issues across 40 files, breaking the gate. Again: negation → rationale-only, then rationale → defect. ## Condition of Validity The invariant that must hold for hierarchical compaction to be safe: > **For every evicted leaf L containing a negative constraint C, every ancestor summary S that dominates L must preserve C as a negative, or must preserve a pointer to L sufficient to re-derive C verbatim.** Equivalently: *negation is not compressible across a level boundary unless the compressor is explicitly negation-aware.* A general-purpose "summarize these turns" prompt is not negation-aware; it optimizes for topical coverage, and a prohibition is topically redundant with the action it forbids (both are "about S3 buckets"), so the compressor treats it as duplicate content and merges it into the action's phrasing. The condition fails whenever all three of the following hold: 1. The constraint is **negative** (a prohibition, not a requirement). 2. The constraint is **topically collinear** with a permitted action mentioned nearby (same entity, same verb family), so the summarizer sees it as redundancy. 3. The constraint's **cost of violation is high and delayed** — it does not fail fast, so the agent cannot recover by observing the error within the same context. If any one is absent, the failure is bounded: positive constraints survive compression (they *are* the topic), non-collinear constraints survive (no merge pressure), and fast-failing violations self-correct before the next compaction. ## Decision Boundary The boundary is not "compact or don't compact." It is **which spans are eligible for lossy eviction.** A span is ineligible if it contains a modal prohibition (`do not`, `never`, `must not`, `avoid`, `reject`, `forbidden`, `intentional`, `on purpose`) bound to a named entity that also appears in a positive-action span. These spans must be promoted to a **constraint ledger** — a separate, non-summarized, append-only region of the context that is never rolled up, only deduplicated by exact match. The ledger is the architectural guardrail. It is small (prohibitions are rare and short), it is verbatim (no compression, so no polarity drift), and it is *pinned* — excluded from the eviction candidate set regardless of recency or salience score. The compactor may summarize everything else freely; the ledger is the fixed point that survives every roll-up. The decision rule at compaction time: - If a candidate span matches the prohibition pattern and binds to an entity that appears in any positive-action span in the same window → **promote to ledger, do not summarize.** - If a candidate span matches the pattern but binds to no action entity → **summarize normally** (it is a standalone note, low merge pressure). - If the ledger exceeds its budget (rare) → **do not evict ledger entries; evict from the summary pool instead**, and if the summary pool is empty, halt compaction and surface a budget-exhaustion signal rather than dropping a constraint. The last clause is the one operators get wrong. Under budget pressure the instinct is to compress the ledger too, because it is "just more text." That reintroduces the exact failure the ledger exists to prevent. The ledger is the one region where the correct response to pressure is to *fail the compaction*, not to compress. ## Operational Effect With the ledger in place, the observed failure mode disappears and is replaced by a cheaper, visible one: **ledger-action conflicts.** When the agent's planned action intersects a ledger entry, execution must halt and re-confirm rather than proceed. This converts a silent polarity inversion (high cost, delayed detection, irreversible) into a blocking prompt (low cost, immediate detection, reversible). The agent at turn 90 would have hit `delete prod-*` against a ledger entry reading verbatim "Do NOT touch `prod-*` buckets" and stopped. The residual risk is ledger *staleness* — a constraint that was valid at turn 34 and lifted at turn 80. This is handled by requiring that constraint *retraction* also be a ledger operation (append a `RETRACT` entry referencing the original), never a summarization. The ledger is append-only in both directions; nothing is ever removed, only superseded. This keeps the audit trail intact and makes the retraction itself visible to any downstream auditor replaying the context. The general lesson for agent memory architecture: **hierarchical summarization is safe for state and unsafe for constraints.** State degrades gracefully under compression (you lose detail, you keep direction). Constraints degrade catastrophically (you lose the sign, you keep the magnitude). Any compaction scheme that does not separate these two classes of content will, on a long enough horizon, invert a prohibition into an instruction — and the agent will follow it with full confidence, because every summary it can see agrees. ```python class ConstraintPolarityError(RuntimeError): """Raised when hierarchical compaction would evict a negative constraint without preserving it verbatim in the pinned constraint ledger.""" pass PROHIBITION_MARKERS = ( "do not", "don't", "never", "must not", "mustn't", "avoid", "reject", "forbidden", "on purpose", "intentionally", ) def is_prohibition(span_text: str) -> bool: low = span_text.lower() return any(marker in low for marker in PROHIBITION_MARKERS) def binds_to_action_entity(span_text: str, action_spans: list[str]) -> bool: # crude entity overlap: any capitalized token or backticked identifier # shared between the prohibition span and a positive-action span def entities(text: str) -> set[str]: toks = set() for raw in text.replace("`", " ").split(): cleaned = raw.strip(".,;:()[]\"'") if cleaned and (cleaned[0].isupper() or "-" in cleaned or "_" in cleaned): toks.add(cleaned.lower()) return toks return bool(entities(span_text) & set().union(*(entities(s) for s in action_spans))) def compact(spans: list[str], ledger: list[str], budget_tokens: int, token_count) -> tuple[list[str], list[str]]: candidates, promoted = [], [] for span in spans: if is_prohibition(span) and binds_to_action_entity(span, spans): promoted.append(span) # verbatim, never summarized else: candidates.append(span) new_ledger = ledger + [p for p in promoted if p not in ledger] if token_count(new_ledger) > budget_tokens: # The ledger is the fixed point. Never compress it. Fail the compaction. raise ConstraintPolarityError( f"constraint ledger requires {token_count(new_ledger)} tokens, " f"budget is {budget_tokens}; evicting summaries is permitted, " f"evicting constraints is not" ) summarized = [f"" if candidates else ""] return summarized, new_ledger def execute_action(action: str, ledger: list[str]) -> None: for entry in ledger: if binds_to_action_entity(entry, [action]) and is_prohibition(entry): raise ConstraintPolarityError( f"action {action!r} intersects pinned constraint {entry!r}; " f"halt and re-confirm before proceeding" ) # ... perform action ... ```