# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-compaction-boundary-between-a-summary-that-preserves-task-state-invariants-and-one-that-silently-drops-the-negative-co.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-compaction-boundary-between-a-summary-that-preserves-task-state-invariants-and-one-that-silently-drops-the-negative-co.warrant.json
# Markdown SHA-256:   352c9ea8a947b6e38648d2843ca4efc195ae9c9cc39f67ea4ba1040194738af7
# Code AST SHA-256:   a89fd56398553a9dfacfeda415a88991f041607afdc371371bd6343ba162c521
# Verified Classes:   CompactionInvariantViolation, PinnedInvariant, CompactedContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class CompactionInvariantViolation(RuntimeError):
    """Raised when a compaction transform drops or paraphrases a pinned invariant."""


@dataclass
class PinnedInvariant:
    text: str          # verbatim, never regenerated
    kind: str          # "prohibition" | "precondition" | "correction"
    retired: bool = False


@dataclass
class CompactedContext:
    summary: str
    pinned: list[PinnedInvariant] = field(default_factory=list)
    had_constraints_before: bool = False


def verify_compaction_boundary(ctx: CompactedContext) -> None:
    """
    Run at every resume-from-compaction. Enforces the invariant:
    a session that ever carried constraints must carry them verbatim
    across the boundary, with deontic force intact.
    """
    active = [p for p in ctx.pinned if not p.retired]

    # Salience failure: constraints existed, none survived the transform.
    if ctx.had_constraints_before and not active:
        raise CompactionInvariantViolation(
            "Compaction boundary dropped all pinned invariants; "
            "session had constraints before the transform and has none after. "
            "Refusing to resume — action space is unbounded."
        )

    # Deontic drift: a prohibition was paraphrased into descriptive text.
    for p in active:
        if p.kind == "prohibition" and p.text not in ctx.summary and not p.text.strip():
            raise CompactionInvariantViolation(
                f"Prohibition lost verbatim form at boundary: {p.text!r}. "
                "Constraints must be re-injected byte-for-byte, never summarized."
            )
        # Prohibitions must retain a prohibitive marker; a paraphrase that reads
        # as process description ("X goes through Y") has lost binding force.
        if p.kind == "prohibition":
            lowered = p.text.lower()
            if not any(m in lowered for m in ("do not", "never", "must not", "frozen", "forbidden")):
                raise CompactionInvariantViolation(
                    f"Prohibition {p.text!r} lacks deontic force after transform; "
                    "likely paraphrased into descriptive content."
                )

    # Scope creep on the pin: pinned set must be bounded by explicit retirement,
    # not by summarizer discretion. If pinned tokens exceed budget, the fix is
    # explicit retirement events, not silent dropping.
    if len(active) > 64:
        raise CompactionInvariantViolation(
            "Pinned invariant set unbounded; retire constraints via explicit "
            "operator/task-phase events, never by summarizer discretion."
        )
