# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-task-state-precisely-at-the-compaction-boundary-it-was-designed-to-survive.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-task-state-precisely-at-the-compaction-boundary-it-was-designed-to-survive.warrant.json
# Markdown SHA-256:   e73966fd50957920b1306e10fa63ae23f03a92de8548e1eae620e547ed192bab
# Code AST SHA-256:   56308fe168a3c133b80ad4496890c427785ce8bdf5a4ed6f91fac1c46bebe66f
# Verified Classes:   CompactionCommitmentError, BindingArtifact, ConstraintLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class CompactionCommitmentError(RuntimeError):
    """Raised when a compaction seam would drop a binding artifact into prose."""
    pass


@dataclass(frozen=True)
class BindingArtifact:
    kind: str          # "prohibition" | "identifier" | "open_branch" | "obligation"
    payload: str       # verbatim, never summarized
    turn: int


@dataclass
class ConstraintLedger:
    artifacts: list[BindingArtifact] = field(default_factory=list)

    def add(self, artifact: BindingArtifact) -> None:
        self.artifacts.append(artifact)

    def prohibits(self, action_symbol: str) -> bool:
        return any(
            a.kind == "prohibition" and a.payload == action_symbol
            for a in self.artifacts
        )


def compact(
    region: Iterable[BindingArtifact],
    ledger: ConstraintLedger,
    summarize_prose: bool = True,
) -> str:
    """
    Compact a context region. Binding artifacts must be moved into the ledger
    verbatim; they may NOT be folded into the prose summary. If the caller
    requests prose summarization of a region that still contains un-ledgered
    binding artifacts, refuse rather than silently erode the constraint set.
    """
    region = list(region)
    unledgered = [a for a in region if a not in ledger.artifacts]

    if unledgered and summarize_prose:
        # Refuse to summarize a region whose binding artifacts are not yet
        # carried over. This is the gate at the seam.
        raise CompactionCommitmentError(
            f"refusing to summarize region: {len(unledgered)} binding "
            f"artifact(s) not present in constraint ledger "
            f"(kinds={sorted({a.kind for a in unledgered})}). "
            f"Move them to the ledger verbatim before compaction."
        )

    for a in unledgered:
        ledger.add(a)

    # Only now is prose summarization safe: the binding force lives in the
    # ledger, which is re-injected verbatim and is not subject to summarization.
    return "[summary of narrative content; binding artifacts held in ledger]"


def guarded_action(ledger: ConstraintLedger, symbol: str) -> str:
    """Check an action against the ledger before emission."""
    if ledger.prohibits(symbol):
        raise CompactionCommitmentError(
            f"action '{symbol}' violates a prohibition carried across the "
            f"compaction seam; the constraint survived in the ledger even "
            f"though it was dropped from the prose summary."
        )
    return f"emitting action: {symbol}"
