# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-self-rewrite-the-idempotence-orphan-boundary-in-policy-constrained-context-controllers.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-self-rewrite-the-idempotence-orphan-boundary-in-policy-constrained-context-controllers.warrant.json
# Markdown SHA-256:   15aafc5460adbe832926498558be10a62d36bdb7385a78a2eb637718252b8f53
# Code AST SHA-256:   45cbf042c829adfe3fa6d89f73c46c5f0d8d1dfc7ad9d8d5042ba44c7b0e235f
# Verified Classes:   OrphanedRewriteError, Buffer, Operator
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class OrphanedRewriteError(RuntimeError):
    """Raised when a rewrite would leave the buffer in a state no admitted operator can repair."""


@dataclass
class Buffer:
    claims: dict[str, set[str]] = field(default_factory=dict)  # claim_id -> provenance_ids
    sources: set[str] = field(default_factory=set)


@dataclass
class Operator:
    name: str
    precondition: Callable[[Buffer], bool]
    apply: Callable[[Buffer], Buffer]
    lossy: bool = False


def policy_holds(buf: Buffer) -> bool:
    # Invariant 1: every claim's provenance resolves.
    for prov in buf.claims.values():
        if not prov.issubset(buf.sources):
            return False
    # Invariant 2: no dangling sources.
    referenced = set().union(*buf.claims.values()) if buf.claims else set()
    if not buf.sources.issubset(referenced):
        return False
    return True


def admitted_operators(buf: Buffer, ops: list[Operator]) -> list[Operator]:
    return [op for op in ops if op.precondition(buf)]


def assert_recoverable(buf: Buffer, op: Operator, ops: list[Operator]) -> None:
    """Pre-check the no-deadlock invariant before applying op."""
    if not policy_holds(buf):
        raise OrphanedRewriteError(f"refusing {op.name}: current buffer already violates policy")
    if not op.precondition(buf):
        raise OrphanedRewriteError(f"refusing {op.name}: precondition false")

    post = op.apply(buf)

    if not policy_holds(post):
        # Permitted but not recoverable: no operator may be admitted on post.
        if not admitted_operators(post, ops):
            raise OrphanedRewriteError(
                f"refusing {op.name}: post-state violates policy and admits no repair operator"
            )
        return

    # Post-state is valid; still require that a further rewrite is possible.
    if not admitted_operators(post, ops):
        raise OrphanedRewriteError(
            f"refusing {op.name}: post-state is a rewrite dead-end (no operator admitted)"
        )


def rewrite(buf: Buffer, op: Operator, ops: list[Operator]) -> Buffer:
    assert_recoverable(buf, op, ops)
    return op.apply(buf)
