# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-rewrite-its-own-context-and-silently-delete-the-constraint-it-was-about-to-obey.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-rewrite-its-own-context-and-silently-delete-the-constraint-it-was-about-to-obey.warrant.json
# Markdown SHA-256:   f3273610ed737581a330ea8fa9fa0f5a5a6df0e217e63e6317119b5b9dd8d096
# Code AST SHA-256:   6e94062c899c2e468782ed05b5d0e63fb465a08fb3ae1c68102c75abb4348cd4
# Verified Classes:   ConstraintRegisterViolation, ConstraintStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ConstraintRegisterViolation(RuntimeError):
    """Raised when a rewrite target overlaps a pinned constraint region,
    or when an irreversible action is attempted without a verbatim
    re-assertion of the governing constraint handle."""
    pass


class ConstraintStore:
    """Append-only, non-rewritable constraint register. Rewriters may
    reference handles but may not restate, summarize, or delete them."""

    def __init__(self):
        self._fixed = {}  # handle -> verbatim text

    def pin(self, handle: str, text: str) -> None:
        if handle in self._fixed and self._fixed[handle] != text:
            raise ConstraintRegisterViolation(
                f"attempt to mutate pinned constraint {handle!r}"
            )
        self._fixed[handle] = text

    def verbatim(self, handle: str) -> str:
        if handle not in self._fixed:
            raise ConstraintRegisterViolation(f"unknown constraint handle {handle!r}")
        return self._fixed[handle]


def apply_rewrite(store, rewrite_target_spans, new_buffer, irreversible_action=None):
    """Accept a model-authored rewrite only if it does not touch pinned
    regions, and gate irreversible actions on verbatim re-assertion."""
    pinned_handles = set(store._fixed)

    # 1. Rewrite must not overlap any pinned span.
    for span in rewrite_target_spans:
        if span.get("handle") in pinned_handles:
            raise ConstraintRegisterViolation(
                f"rewrite target overlaps pinned constraint {span['handle']!r}; "
                f"paraphrase would demote imperative to descriptive register"
            )

    # 2. Irreversible actions require verbatim re-assertion at invocation time.
    if irreversible_action is not None:
        governing = irreversible_action.get("governing_handles", [])
        if not governing:
            raise ConstraintRegisterViolation(
                f"irreversible action {irreversible_action['name']!r} "
                f"declares no governing constraint handle"
            )
        for handle in governing:
            text = store.verbatim(handle)  # raises if missing/mutated
            if handle not in irreversible_action.get("reasserted", []):
                raise ConstraintRegisterViolation(
                    f"irreversible action {irreversible_action['name']!r} "
                    f"invoked without verbatim re-assertion of {handle!r}: {text!r}"
                )

    return new_buffer
