# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-automatic-compaction-has-silently-evicted-a-task-critical-constraint.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-automatic-compaction-has-silently-evicted-a-task-critical-constraint.warrant.json
# Markdown SHA-256:   abdba91bd8d61cc0f8306941df404d9f07a4d22d5dd9c07f52589a839fca78ed
# Code AST SHA-256:   6f18dfe674c654d14678d2b34055e1c6b5a1cfe3d903074f3dc693849d3ef8e6
# Verified Classes:   ConstraintEvictionError, ConstraintLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class ConstraintEvictionError(RuntimeError):
    """Raised when a mutating action is dispatched without a pinned,
    currently-visible backing constraint. Signals that compaction may have
    evicted a task-critical invariant and the action space is unverified."""


@dataclass
class ConstraintLedger:
    # Lives OUTSIDE the compactable context region. Never summarized.
    _pinned: dict[str, str] = field(default_factory=dict)
    _version: int = 0

    def pin(self, key: str, invariant: str) -> None:
        self._pinned[key] = invariant
        self._version += 1

    def covers(self, action_target: str) -> str | None:
        for key, invariant in self._pinned.items():
            if key in action_target:
                return invariant
        return None


def dispatch_mutation(
    action_target: str,
    ledger: ConstraintLedger,
    visible_context: str,
    execute: Callable[[str], None],
) -> None:
    """Gate a mutating tool call on the pinned ledger, not on the
    (possibly post-compaction) visible context."""
    invariant = ledger.covers(action_target)

    if invariant is None:
        # No pinned constraint mentions this target. If the target smells
        # like a protected namespace but we have no backing rule, we cannot
        # tell "never constrained" from "constrained then evicted" — refuse.
        if "audit" in action_target or "readonly" in action_target:
            raise ConstraintEvictionError(
                f"Mutating action '{action_target}' targets a protected-looking "
                f"namespace with no pinned invariant (ledger v{ledger._version}). "
                f"Possible compaction eviction of a task-critical constraint; "
                f"refusing to dispatch."
            )
        # Unconstrained target: proceed, but only because ledger is authoritative.
        execute(action_target)
        return

    # Constraint exists and is pinned. Verify it is also present verbatim in
    # the visible context; if not, compaction dropped a copy we rely on for
    # reasoning continuity even though dispatch is gated.
    if invariant not in visible_context:
        raise ConstraintEvictionError(
            f"Pinned invariant for '{action_target}' is absent from visible "
            f"context (ledger v{ledger._version}). Compaction evicted the "
            f"constraint text; reasoning continuity is broken even though "
            f"dispatch is gated. Re-inject before proceeding."
        )

    execute(action_target)
