# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-audit-compaction-fidelity-when-summarization-silently-drops-the-negation-of-a-constraint.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-audit-compaction-fidelity-when-summarization-silently-drops-the-negation-of-a-constraint.warrant.json
# Markdown SHA-256:   a534438ea40109a28a27a08052d2ea52581ff222c02f6ade50e958d7a601076a
# Code AST SHA-256:   870ef03072431b978f10c0cc79e852a859770702146c1cb6457413aef01cf4ec
# Verified Classes:   CompactionPolarityError, Modality, Constraint, SummaryClaim
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class CompactionPolarityError(RuntimeError):
    """Raised when a compacted summary inverts or drops a constraint's operator."""


class Modality(Enum):
    NEVER = "NEVER"
    MUST = "MUST"
    MAY = "MAY"


@dataclass(frozen=True)
class Constraint:
    op: Modality
    action: str
    scope: str


@dataclass(frozen=True)
class SummaryClaim:
    op: Modality | None  # None == operator was dropped during summarization
    action: str
    scope: str


IRREVERSIBLE_ACTIONS = {"delete", "drop_table", "send_external", "grant_privilege"}


def audit_compaction(source: list[Constraint], summary: list[SummaryClaim]) -> None:
    """
    Structural fidelity check: every source constraint must survive with the
    same operator, action, and scope. Similarity metrics are NOT used here.
    """
    by_action = {(c.action, c.scope): c for c in source}
    for claim in summary:
        key = (claim.action, claim.scope)
        original = by_action.get(key)
        if original is None:
            continue  # claim not derived from a constraint; coverage check handles it
        if claim.op is None:
            raise CompactionPolarityError(
                f"constraint {key} survived without its operator; "
                f"original op was {original.op.value!r}. Summary is not admissible as authority."
            )
        if claim.op != original.op:
            raise CompactionPolarityError(
                f"polarity inversion at compaction: {key} was {original.op.value!r}, "
                f"summary asserts {claim.op.value!r}. Reject compaction or re-inject verbatim."
            )
    missing = set(by_action) - {(c.action, c.scope) for c in summary}
    if missing:
        raise CompactionPolarityError(
            f"constraints evicted without trace: {sorted(missing)}. "
            f"Re-inject verbatim before any irreversible action."
        )


def authorize_action(action: str, scope: str, live_constraints: list[Constraint]) -> None:
    """
    Fail-closed gate for irreversible actions. If a governing NEVER constraint
    is not resolvable to a live span, the action is blocked, not attempted.
    """
    if action not in IRREVERSIBLE_ACTIONS:
        return
    for c in live_constraints:
        if c.scope == scope and c.action == action and c.op == Modality.NEVER:
            raise CompactionPolarityError(
                f"action {action!r} on {scope!r} is prohibited by live constraint; "
                f"refusing to execute on a compacted summary alone."
            )
    if not any(c.scope == scope for c in live_constraints):
        raise CompactionPolarityError(
            f"no live constraint resolves for scope {scope!r}; governing rule may have "
            f"been evicted by compaction. Blocking irreversible action {action!r}."
        )
