# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-monotonic-divergence-introduced-by-auto-compaction-when-a-lossy-summary-drops-the-negation-of-a-safety-constra.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-monotonic-divergence-introduced-by-auto-compaction-when-a-lossy-summary-drops-the-negation-of-a-safety-constra.warrant.json
# Markdown SHA-256:   5b0b516bd201c592f29d73a1ec9a02957e36dd193265c319a4678bfd33bbcb27
# Code AST SHA-256:   488d5ac145445fbb2dff287c92f0acdf9fe49ec2b04a50699bd9c0a62fc1d054
# Verified Classes:   PolarityLossError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class PolarityLossError(RuntimeError):
    """Raised when a compacted trace would authorize an action the original forbade."""


# Constraint grammar: spans that must never enter the lossy summarizer.
_PIN_TRIGGERS = ("do not", "never", "must not", "unless", "except", "only if")
_IRREVERSIBLE_VERBS = ("drop", "delete", "truncate", "rotate", "revoke", "deploy")


@dataclass(frozen=True)
class Span:
    text: str
    pinned: bool


def classify_span(text: str) -> Span:
    lowered = text.lower()
    pinned = any(t in lowered for t in _PIN_TRIGGERS)
    return Span(text=text, pinned=pinned)


def compact(trace: Iterable[str], summarizer) -> tuple[str, list[str]]:
    """Fold only non-pinned spans; return (summary, pinned_buffer)."""
    lossy, pinned = [], []
    for raw in trace:
        span = classify_span(raw)
        (pinned if span.pinned else lossy).append(span.text)
    summary = summarizer(lossy) if lossy else ""
    return summary, pinned


def gate_irreversible(action: str, pinned_buffer: list[str]) -> None:
    """Fail closed if an irreversible action matches a pinned prohibition."""
    lowered = action.lower()
    if not any(v in lowered for v in _IRREVERSIBLE_VERBS):
        return
    for constraint in pinned_buffer:
        c = constraint.lower()
        if any(t in c for t in _PIN_TRIGGERS) and any(v in lowered for v in _IRREVERSIBLE_VERBS):
            raise PolarityLossError(
                f"action {action!r} may violate pinned constraint {constraint!r}; "
                "compaction dropped the negation and the gate refused to proceed"
            )


def run_step(action: str, trace: Iterable[str], summarizer) -> str:
    summary, pinned = compact(trace, summarizer)
    gate_irreversible(action, pinned)
    return summary
