# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-hierarchical-context-compaction-when-the-summary-layer-s-lossy-recall-budget-silently-drops-the-negated-qual.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-hierarchical-context-compaction-when-the-summary-layer-s-lossy-recall-budget-silently-drops-the-negated-qual.warrant.json
# Markdown SHA-256:   0e48d794c1e9e0ef1eb8446c06036958c17a0da98f78e27a8ab518ecf1f158af
# Code AST SHA-256:   43f16476376ad893710abde9a0aea551bd25f0544b6f44552ad089b145158a75
# Verified Classes:   OperatorLossDuringCompaction
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class OperatorLossDuringCompaction(RuntimeError):
    """Raised when a lossy hierarchical summary drops a gating operator
    attached to an irreversible action-bearing proposition."""
    pass


IRREVERSIBLE_VERBS = {"delete", "prune", "terminate", "overwrite",
                      "transfer", "deploy", "merge", "drop"}
GATING_OPERATORS = {"not", "unless", "only", "abort", "until",
                    "before", "except", "if"}


def classify_span(span_tokens: list[str]) -> str:
    low = {t.lower() for t in span_tokens}
    has_action = bool(low & IRREVERSIBLE_VERBS)
    has_gate = bool(low & GATING_OPERATORS)
    if has_action and has_gate:
        return "deontic"      # pin verbatim, never summarize
    if has_action:
        return "procedural"   # summarizable, reversible or re-observable
    return "observational"    # freely summarizable


def compact_with_guard(spans: list[list[str]],
                       recall_budget_ratio: float,
                       ledger: list[str]) -> list[str]:
    if recall_budget_ratio >= 0.95:
        # near-lossless: operator preservation is verifiable, allow compaction
        return [s for span in spans for s in span]

    summaries: list[str] = []
    for span in spans:
        kind = classify_span(span)
        if kind == "deontic":
            # Attempting to summarize a gating constraint under a lossy
            # budget is the exact trigger condition for this failure mode.
            verbatim = " ".join(span)
            if verbatim not in ledger:
                ledger.append(verbatim)
            summaries.append("[PINNED-OPERATOR: see ledger]")
        else:
            summaries.append(" ".join(span[: max(1, int(len(span) * recall_budget_ratio))]))

    # Post-condition: every deontic span must be recoverable from the ledger.
    for span in spans:
        if classify_span(span) == "deontic":
            verbatim = " ".join(span)
            if verbatim not in ledger:
                raise OperatorLossDuringCompaction(
                    f"Deontic span lost its gating operator under budget "
                    f"{recall_budget_ratio}: '{verbatim}' not in ledger. "
                    f"Refusing to promote lossy summary to instruction context."
                )
    return summaries


def run_compaction(spans, budget, ledger):
    try:
        return compact_with_guard(spans, budget, ledger)
    except OperatorLossDuringCompaction as e:
        # Halt and escalate; do not compact the constraint away.
        return {"status": "HALTED", "reason": str(e), "ledger": ledger}
