# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-self-editing-context-rewrite-because-the-rewrite-operator-violates-a-preserved-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-self-editing-context-rewrite-because-the-rewrite-operator-violates-a-preserved-invariant.warrant.json
# Markdown SHA-256:   12273ce04d7ebe8fbc31beb37842cf6dbd8683f12c21e496bc2dd84b64472aa0
# Code AST SHA-256:   a7e3e392c74784a66cc15b0599feff0221d5fcfc25fbc8bdfc3746edc9f9829a
# Verified Classes:   InvariantDominationError, RewriteOperator, Policy, ContextState
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class InvariantDominationError(RuntimeError):
    """Raised when a self-editing rewrite's declared preservation set does not
    dominate the reachable precondition union of the post-rewrite context."""


@dataclass(frozen=True)
class RewriteOperator:
    name: str
    declared_preserved: FrozenSet[str]          # invariant names the operator claims to keep
    creates_new_reachability: bool              # does the rewrite pull new policies into frontier?


@dataclass(frozen=True)
class Policy:
    name: str
    preconditions: FrozenSet[str]               # invariant names this policy requires to fire


@dataclass
class ContextState:
    reachable_policies: FrozenSet[Policy] = field(default_factory=frozenset)


def admit_rewrite(op: RewriteOperator, state: ContextState) -> bool:
    """Return True iff the rewrite is globally admissible.

    Admissible iff:
      (1) op.declared_preserved dominates the union of reachable policy
          preconditions, AND
      (2) reachability is closed under the rewrite (no new policies pulled in).
    """
    required: FrozenSet[str] = frozenset().union(
        *(p.preconditions for p in state.reachable_policies)
    ) if state.reachable_policies else frozenset()

    dominates = required.issubset(op.declared_preserved)
    closed = not op.creates_new_reachability

    return dominates and closed


def apply_self_edit(op: RewriteOperator, state: ContextState) -> ContextState:
    """Apply the rewrite, refusing if the domination invariant is violated.

    Refusal is mandatory even under context saturation: an unsound rewrite
    turns a recoverable state into an undetectable one.
    """
    if not admit_rewrite(op, state):
        missing = frozenset().union(
            *(p.preconditions for p in state.reachable_policies)
        ) - op.declared_preserved
        raise InvariantDominationError(
            f"refusing rewrite '{op.name}': undeclared precondition(s) "
            f"{sorted(missing)} required by reachable policies; "
            f"declared_preserved={sorted(op.declared_preserved)}; "
            f"reachability_closed={not op.creates_new_reachability}. "
            f"Externalize to durable store and keep citation stubs instead."
        )
    # Rewrite admitted; reachable set unchanged (closure guaranteed above).
    return ContextState(reachable_policies=state.reachable_policies)


# --- The invoice-#27 trace, reduced -------------------------------------------
review_policy = Policy(
    name="human_review_on_ambiguity",
    preconditions=frozenset({"match_confidence_field", "tie_break_metadata"}),
)
state = ContextState(reachable_policies=frozenset({review_policy}))

summarize_range = RewriteOperator(
    name="summarize_range",
    declared_preserved=frozenset({"no_orphan_tool_calls", "preserve_pinned_constraints"}),
    creates_new_reachability=False,
)

apply_self_edit(summarize_range, state)  # raises InvariantDominationError
