# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-lossy-context-compaction-has-silently-destroyed-a-reconstruction-critical-constraint-before-acting-on-the-compacted.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-lossy-context-compaction-has-silently-destroyed-a-reconstruction-critical-constraint-before-acting-on-the-compacted.warrant.json
# Markdown SHA-256:   f28bcb46310f7d7f72ab9678878ad45d06a28349206a49bb2c575cc0ea43ac20
# Code AST SHA-256:   d7f85adf1899ce92ca7f2081425f8f3637e80470e33199d5423155f162d60698
# Verified Classes:   CompactionFidelityError, ActionReversibility, Constraint, ConstraintLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class CompactionFidelityError(RuntimeError):
    """Raised when a post-compaction action would commit against state whose
    binding constraints are no longer enforceable from current context."""
    pass


class ActionReversibility(Enum):
    REVERSIBLE = "reversible"
    IRREVERSIBLE = "irreversible"


@dataclass(frozen=True)
class Constraint:
    cid: str
    resource: str          # resource this constraint governs
    enforcement: str       # the exact condition that must remain derivable
    tagged_at_token: int   # ingestion position; never compacted


@dataclass
class ConstraintLedger:
    entries: list[Constraint] = field(default_factory=list)

    def relevant(self, resource: str) -> list[Constraint]:
        return [c for c in self.entries if c.resource == resource]


def verify_before_commit(
    ledger: ConstraintLedger,
    action_resource: str,
    action_reversibility: ActionReversibility,
    context_was_compacted: bool,
    derivable_cids: set[str],
) -> None:
    """
    Enforce the boundary: compaction is safe for navigation, unsafe for
    commitment. Reversible actions may proceed on reconstructed state;
    irreversible actions require every relevant constraint's enforcement
    condition to be derivable from the current (possibly compacted) context.
    """
    if not context_was_compacted:
        return  # verbatim context; constraints intact by construction

    if action_reversibility is ActionReversibility.REVERSIBLE:
        return  # bounded cost; navigation on summary is permitted

    relevant = ledger.relevant(action_resource)
    unenforceable = [c for c in relevant if c.cid not in derivable_cids]

    if unenforceable:
        lost = ", ".join(f"{c.cid}('{c.enforcement}')" for c in unenforceable)
        raise CompactionFidelityError(
            f"Irreversible action on '{action_resource}' blocked: compaction "
            f"destroyed enforcement for {lost}. Rehydrate the original span "
            f"or obtain explicit confirmation before committing."
        )


# --- trace of the observed failure, now caught at the boundary ---
ledger = ConstraintLedger(entries=[
    Constraint(
        cid="C-004",
        resource="database_dsn",
        enforcement="target sandbox DSN only; shell DSN is live prod",
        tagged_at_token=9000,
    ),
])

# After compaction the summary says "user was cautious about environments"
# but the specific binding is gone -> C-004 not derivable.
try:
    verify_before_commit(
        ledger=ledger,
        action_resource="database_dsn",
        action_reversibility=ActionReversibility.IRREVERSIBLE,
        context_was_compacted=True,
        derivable_cids=set(),  # summary abstracted away the binding
    )
except CompactionFidelityError as e:
    print(f"HALT: {e}")
