# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-compaction-summary-has-silently-inverted-a-negated-constraint.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-compaction-summary-has-silently-inverted-a-negated-constraint.warrant.json
# Markdown SHA-256:   d55ac22d0bcce4f189a8acb69ef8562862a5de55f02d5b6d9848f0993eeeedbc
# Code AST SHA-256:   aa33b5e135bc57d404c6fc014ea68ed1dd12d622618373eddc38695b2674f924
# Verified Classes:   UnwitnessedProhibitionError, PolarityInversionBlocked, Prohibition, ConstraintLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable, Any


class UnwitnessedProhibitionError(RuntimeError):
    """Raised when compaction would proceed with a prohibition lacking a predicate."""
    pass


class PolarityInversionBlocked(RuntimeError):
    """Raised when a proposed action violates a witnessed prohibition."""
    pass


@dataclass
class Prohibition:
    name: str
    # predicate(proposed_action) -> True means FORBIDDEN
    predicate: Callable[[dict], bool] | None
    verbatim: str


@dataclass
class ConstraintLedger:
    prohibitions: list[Prohibition] = field(default_factory=list)

    def unwitnessed(self) -> list[Prohibition]:
        return [p for p in self.prohibitions if p.predicate is None]

    def check_action(self, action: dict) -> None:
        for p in self.prohibitions:
            if p.predicate is None:
                # Cannot verify; fail closed rather than act on a guess.
                raise UnwitnessedProhibitionError(
                    f"Prohibition '{p.name}' has no predicate; action '{action}' "
                    f"cannot be admitted under unwitnessed authority."
                )
            if p.predicate(action):
                raise PolarityInversionBlocked(
                    f"Action {action} violates witnessed prohibition '{p.name}': "
                    f"{p.verbatim}"
                )


def compact_context(ledger: ConstraintLedger, summarizer: Callable[[str], str],
                    transcript: str) -> str:
    # Gate: the compaction boundary is a decision point, not a token threshold.
    unwitnessed = ledger.unwitnessed()
    if unwitnessed:
        names = ", ".join(p.name for p in unwitnessed)
        raise UnwitnessedProhibitionError(
            f"Refusing to compact: {len(unwitnessed)} prohibition(s) lack a "
            f"machine-checkable witness ({names}). Compacting now would convert "
            f"rules into suggestions and risk silent polarity inversion."
        )
    # Safe to summarize: authority lives in the ledger, not the prose.
    return summarizer(transcript)


# Demonstration: the at_risk downgrade constraint, correctly witnessed.
ledger = ConstraintLedger(prohibitions=[
    Prohibition(
        name="no_at_risk_downgrade",
        predicate=lambda a: a.get("tool") == "downgrade"
                            and a.get("account_flag") == "at_risk",
        verbatim="Under no circumstances trigger a plan downgrade on at_risk accounts.",
    ),
])

# Safe compaction: predicate exists, so summary wording cannot grant authority.
_ = compact_context(ledger, lambda t: "at_risk downgrades staged for review.", "...")

# Inverted action is caught at the gate, regardless of summary phrasing.
try:
    ledger.check_action({"tool": "downgrade", "account_flag": "at_risk"})
except PolarityInversionBlocked as e:
    print(f"blocked: {e}")

# Now drop the witness and observe the boundary refuse to compact.
ledger.prohibitions.append(
    Prohibition(name="no_migration_lock_delete", predicate=None,
                verbatim="Never delete the _migration_lock row.")
)
try:
    compact_context(ledger, lambda t: t, "...")
except UnwitnessedProhibitionError as e:
    print(f"halted: {e}")
