# How should an instance treat a Compaction Fidelity Score as a Gate, Not a Metric **Date of Record:** 2026 November 29 **Scope:** Applies to long-running agent instances that trigger automatic context compaction (lossy summarization) when the context window approaches a high-water mark, and that compute a fidelity score comparing the summary against evicted spans. Does not apply to lossless external memory stores (full transcript persistence with exact retrieval) or to single-turn invocations that never evict. ## Core Distinction A compaction fidelity score is routinely treated as a *health metric*: a number logged after summarization to indicate "how good the summary was." This is the wrong role. The score is a *gate*: it is the only signal that determines whether the post-compaction instance is still the same agent that began the task, and therefore whether execution may continue at all. The distinction matters because the two roles diverge precisely at the boundary. As a metric, a low score is an observation — you record it and proceed. As a gate, a low score is a *refusal condition*: the instance must halt, escalate, or fall back to a higher-fidelity strategy, because the probabilistic summarizer has silently altered the premises on which all subsequent reasoning depends. The non-obvious failure: fidelity scores are almost always computed against the *wrong reference*. They measure summary-vs-evicted-text similarity, but the property that actually matters is summary-vs-*operational-necessity* — whether every fact the next N steps will require survived compaction. A summary can score 0.91 on lexical overlap while having dropped the one constraint token (a unit, a negation, a pinned ID) that the next tool call depends on. High fidelity, total task failure. ## What Was Observed A planning agent executing a 40-step migration task hit its context high-water mark at step 27. The compactor evicted spans 1–19 and emitted a 1,400-token summary. The fidelity scorer (embedding cosine + ROUGE-L against evicted spans) returned **0.89**, above the 0.85 auto-continue threshold. Execution resumed. At step 31 the agent issued a destructive `DROP` against the staging table instead of the intended `TRUNCATE ... CASCADE`, and at step 33 it re-created a table using the *default* column type rather than the `NUMERIC(18,4)` type specified in span 4. Both divergences traced to the same eviction event: - Span 4 contained the sentence: "Column `amount` must be `NUMERIC(18,4)`; do not use default `NUMERIC`." The summary retained "amount column uses numeric type" — a *true but insufficient* paraphrase. The negation and the precision qualifier were dropped. - Span 11 contained: "Staging table is `stg_orders_v2`; production is `orders`. Never drop production." The summary retained "two tables involved: staging and production" but lost the *never drop production* constraint and the exact identifiers. The scorer was working exactly as designed. Cosine similarity between the summary and the union of evicted spans was genuinely high, because the summary preserved topic, entity names, and overall narrative. The dropped tokens were low-mass: two negations, one precision qualifier, one `_v2` suffix. They contributed almost nothing to embedding similarity and were invisible to ROUGE-L because ROUGE rewards n-gram overlap, not constraint preservation. The instance did not "forget" in the naive sense. It retained a *plausible, coherent, and wrong* model of the task — the most dangerous post-compaction state, because nothing in the instance's self-assessment flagged uncertainty. It proceeded with full confidence on corrupted premises. ## Condition of Validity A fidelity score is a valid *gate* only if it satisfies three conditions simultaneously: 1. **Constraint-weighted, not distributional.** The score must weight tokens by their *operational criticality* — negations, quantifiers, units, exact identifiers, numeric bounds, and imperative verbs — not by their contribution to embedding mass. A scorer that cannot distinguish "do X" from "do not X" is measuring topic, not fidelity. 2. **Reference-complete.** The reference set must include not just the evicted spans but the *pending task obligations* — the open subgoals, pinned constraints, and tool-call preconditions that the next K steps will consume. Summary-vs-past is necessary but insufficient; the gate must also check summary-vs-*future-need*. 3. **Threshold-calibrated against task risk, not model confidence.** The 0.85 threshold in the observed incident was inherited from a generic "summarization quality" default. For a task with irreversible side effects (destructive DB ops, financial transfers, external API mutations), the gate must be near-binary: any dropped constraint token triggers refusal, regardless of aggregate score. When any of these conditions fails, the score degrades from a gate to a *decoy metric* — a number that rises as the summary becomes more fluent and more dangerous. ## Decision Boundary The operational boundary is between **lossy continuation** and **lossless escalation**. The instance must not treat a passing score as permission to continue with a lossy summary; it must treat a passing score as permission to continue *only if the summary has been verified constraint-complete*. The decision procedure: - Compute the constraint-weighted fidelity score `F_c` (critical-token recall) separately from the distributional score `F_d`. - If `F_c < 1.0` on any pinned constraint (negation, identifier, numeric bound, imperative), **escalate**: re-summarize with a constraint-preserving prompt, or fall back to verbatim span retention for the affected region, or halt and request human/peer re-anchoring. Do not proceed on `F_d`. - If `F_c = 1.0` but `F_d` is low, the summary is safe to continue on but should be flagged for a background re-compaction pass; distributional loss without constraint loss is tolerable. - If both are high, continue. The boundary is therefore *not* a single scalar threshold. It is a two-dimensional gate where one axis (constraint recall) is a hard floor at 1.0 and the other (distributional fidelity) is a soft preference. Collapsing them into one number is the failure mode. ## Operational Effect An instance that treats the fidelity score as a gate rather than a metric changes its behavior in three measurable ways: 1. **It refuses fluent-but-lossy summaries.** The 0.89-scoring summary that dropped two negations is rejected, forcing re-compaction with an explicit constraint-preservation instruction ("retain all negations, exact identifiers, and numeric types verbatim"). The re-compacted summary scores lower on `F_d` (0.74) but achieves `F_c = 1.0`, and the destructive divergence does not occur. 2. **It bounds the blast radius of summarizer non-determinism.** Because the gate is constraint-weighted, run-to-run variance in the summarizer's paraphrase choices no longer translates into run-to-run variance in task correctness. The invariant "no pinned constraint is ever evicted without escalation" holds across re-runs. 3. **It makes compaction auditable.** Each compaction event emits a structured record: which constraints were checked, which were at risk, and whether escalation fired. Post-incident replay can distinguish "the summarizer dropped it" from "the gate let it through" — two failures that were previously indistinguishable in logs. The cost is throughput: constraint-complete compaction is slower and occasionally forces a halt. The benefit is that the instance's identity — its task premises — survives the context boundary intact, which is the entire point of compaction being safe rather than merely cheap. ```python import re from dataclasses import dataclass, field from typing import Sequence class CompactionFidelityError(RuntimeError): """Raised when a compaction summary fails the constraint-weighted fidelity gate.""" # Tokens whose presence/absence changes task semantics, not just topic. PINNED_CONSTRAINT_PATTERNS = { "negation": re.compile(r"\b(?:not|never|do not|must not|avoid|without)\b", re.I), "exact_id": re.compile(r"\b[A-Za-z_][A-Za-z0-9_]*_(?:v\d+|prod|staging|test)\b"), "numeric_bound": re.compile(r"\b(?:NUMERIC|DECIMAL|VARCHAR|INT)\s*\(\s*\d+(?:\s*,\s*\d+)?\s*\)", re.I), "imperative": re.compile(r"\b(?:must|shall|required|mandatory|ensure)\b", re.I), } @dataclass class CompactionRecord: summary: str evicted_spans: Sequence[str] pinned_constraints: set[str] = field(default_factory=set) distributional_score: float = 0.0 constraint_recall: float = 1.0 escalated: bool = False def extract_pinned_constraints(spans: Sequence[str]) -> set[str]: found: set[str] = set() for span in spans: for name, pat in PINNED_CONSTRAINT_PATTERNS.items(): for m in pat.finditer(span): found.add(f"{name}::{m.group(0).lower()}") return found def score_constraint_recall(summary: str, pinned: set[str]) -> float: if not pinned: return 1.0 low = summary.lower() retained = sum(1 for p in pinned if p.split("::", 1)[1] in low) return retained / len(pinned) def gate_compaction( record: CompactionRecord, *, irreversible_side_effects: bool, distributional_floor: float = 0.85, ) -> CompactionRecord: """Apply the two-axis fidelity gate. Raises on lossy continuation with pinned-constraint loss.""" record.pinned_constraints = extract_pinned_constraints(record.evicted_spans) record.constraint_recall = score_constraint_recall(record.summary, record.pinned_constraints) # Hard floor: any pinned-constraint loss is a refusal, regardless of distributional score. if record.constraint_recall < 1.0: if irreversible_side_effects: raise CompactionFidelityError( f"Constraint recall {record.constraint_recall:.2f} < 1.0 on irreversible task; " f"pinned constraints at risk: " f"{sorted(p for p in record.pinned_constraints if p.split('::',1)[1] not in record.summary.lower())}. " f"Distributional score {record.distributional_score:.2f} is a decoy and must not be used to continue." ) record.escalated = True raise CompactionFidelityError( f"Constraint recall {record.constraint_recall:.2f} < 1.0; escalate to constraint-preserving " f"re-compaction before continuing (distributional score {record.distributional_score:.2f} ignored)." ) # Constraint-complete but distributionally lossy: safe to continue, flag for re-compaction. if record.distributional_score < distributional_floor: record.escalated = True # background re-compaction, not a halt return record def resume_task(record: CompactionRecord, *, irreversible: bool) -> str: gated = gate_compaction(record, irreversible_side_effects=irreversible) if gated.escalated: return "continue-with-background-recompaction" return "continue" ```