# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-a-transcript-against-a-summarizer-whose-lossy-guarantee-is-stated-in-tokens-not-in-entailment.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-a-transcript-against-a-summarizer-whose-lossy-guarantee-is-stated-in-tokens-not-in-entailment.warrant.json
# Markdown SHA-256:   70b8c8117cea7137cac45d91c536db6be6a874dd8d1efc6b639ee2f2a370ab60
# Code AST SHA-256:   7a9aa5175f74a259a346e24d27a09687b2af12d40890fc040fdeee57f7d5b033
# Verified Classes:   ObligationInversionError, Obligation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class ObligationInversionError(RuntimeError):
    """Raised when a compaction event would collapse a deontic operator
    (prohibition / precondition / gate) into a bare status noun, changing
    the operator-scope graph of the compactor's obligation set."""


@dataclass(frozen=True)
class Obligation:
    action: str
    precondition: str
    prohibited: bool
    warrant: str


DEONTIC_MARKERS = ("not", "until", "unless", "only if", "must", "gated", "pending on")


def segment_has_unledgered_obligation(
    segment: str, ledger: Iterable[Obligation]
) -> bool:
    lowered = segment.lower()
    if not any(marker in lowered for marker in DEONTIC_MARKERS):
        return False
    ledger_actions = {o.action for o in ledger}
    # A deontic marker whose action noun is absent from the ledger means the
    # operator's scope is unmirrored and must be extracted before summarization.
    return not any(action in lowered for action in ledger_actions)


def compact(
    segment: str,
    ledger: list[Obligation],
    summarize,
) -> tuple[str, list[Obligation]]:
    if segment_has_unledgered_obligation(segment, ledger):
        # Two-phase: extract first, summarize only the residue.
        extracted = extract_obligations(segment)
        if not extracted:
            raise ObligationInversionError(
                "deontic operator present but extractor returned no obligation; "
                "refusing to summarize a segment whose operator scope is unmirrored"
            )
        ledger = ledger + extracted
        segment = strip_obligation_clauses(segment)

    summary = summarize(segment)

    # Post-condition: the summary must not introduce a deontic operator whose
    # scope is absent from the ledger. "pending" replacing "do not ... until"
    # is an inversion, not a compression.
    if _introduces_unledgered_operator(summary, ledger):
        raise ObligationInversionError(
            "summary collapsed a prohibition into a status noun; "
            "operator-scope graph changed during compaction"
        )
    return summary, ledger


def _introduces_unledgered_operator(summary: str, ledger: list[Obligation]) -> bool:
    lowered = summary.lower()
    for marker in DEONTIC_MARKERS:
        if marker in lowered:
            if not any(o.action in lowered for o in ledger):
                return True
    # Collapse detection: "pending" with no matching prohibition tuple.
    if "pending" in lowered and not any(o.prohibited for o in ledger):
        return True
    return False


def extract_obligations(segment: str) -> list[Obligation]:
    # Placeholder for a grammar-constrained extractor; must be deterministic
    # and must fail closed (return []) rather than guess.
    return []


def strip_obligation_clauses(segment: str) -> str:
    return segment
