# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-of-a-self-editing-context-policy-refuse-a-model-driven-rewrite-the-invariant-preservation-boundary-at-rewrite-admission.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-of-a-self-editing-context-policy-refuse-a-model-driven-rewrite-the-invariant-preservation-boundary-at-rewrite-admission.warrant.json
# Markdown SHA-256:   efd93629058f777aaf2442a5d729bbae7fa4fd5cbc19764c683aa0e8412c059e
# Code AST SHA-256:   7ad7e43609ce2bc927daaca081d0b77151068bfb4c1d38a3809e9abe9746d7e9
# Verified Classes:   InvariantViolation, Span, EditOp
# Defensive Guards:   6 fail-closed invariants (zero external deps)

"""Pre-commit invariant gate for model-driven context rewrites.

The gate checks the *edit script*, not the resulting document. Refusal is
atomic: any illegal operation rejects the whole rewrite. The model is never
consulted for verification.
"""

from dataclasses import dataclass
from typing import Iterable, Literal


class InvariantViolation(RuntimeError):
    """Raised when a proposed rewrite violates a declared invariant.

    Carries the invariant id and the offending operation so the rewriter can
    be asked for a bounded repair. Never caught to force-apply a rewrite.
    """

    def __init__(self, invariant: str, op_index: int, detail: str) -> None:
        self.invariant = invariant
        self.op_index = op_index
        self.detail = detail
        super().__init__(f"[{invariant}] op#{op_index}: {detail}")


@dataclass(frozen=True)
class Span:
    start: int
    end: int
    kind: Literal["pinned", "tool_call", "tool_result", "redaction", "constraint", "instruction", "plain"]
    identity: str  # stable id; for redactions, pins encoded length


@dataclass(frozen=True)
class EditOp:
    kind: Literal["replace", "delete", "reorder"]
    start: int = -1
    end: int = -1
    text: str = ""
    # for reorder: the two block identities being swapped
    a: str = ""
    b: str = ""


def _overlaps(op: EditOp, span: Span) -> bool:
    if op.kind == "reorder":
        return False
    return op.start < span.end and span.start < op.end


def _is_protected(span: Span) -> bool:
    # Presence is not preservation: protected spans must not be touched at all,
    # including by a replacement whose text happens to contain them.
    return span.kind in {"pinned", "redaction", "constraint"}


def check_invariant_preservation(
    ops: Iterable[EditOp],
    spans: list[Span],
    *,
    max_repair_attempts_hint: int = 2,
) -> None:
    """Raise InvariantViolation on the first illegal operation. Atomic: no partial apply."""
    ops = list(ops)

    # I1/I3: protected regions may not be overlapped by any replace/delete.
    # This is an operation-overlap check, not a substring check: a pinned span
    # merged into a larger summary is a violation even though its text survives.
    for i, op in enumerate(ops):
        for span in spans:
            if _is_protected(span) and _overlaps(op, span):
                raise InvariantViolation(
                    "I1_protected_span_untouched",
                    i,
                    f"{op.kind} [{op.start},{op.end}) overlaps protected "
                    f"{span.kind} '{span.identity}' [{span.start},{span.end})",
                )

    # I2: every tool_call keeps its tool_result, in order. Check the span graph,
    # not membership: co-presence is not ordering.
    calls = {s.identity: s for s in spans if s.kind == "tool_call"}
    results = {s.identity: s for s in spans if s.kind == "tool_result"}
    for cid, call in calls.items():
        rid = f"result::{cid}"
        if rid not in results:
            raise InvariantViolation(
                "I2_call_result_paired", -1, f"tool_call '{cid}' has no matching result"
            )
        if results[rid].start < call.start:
            raise InvariantViolation(
                "I2_call_result_paired", -1, f"result for '{cid}' precedes its call"
            )

    # I4: a constraint must precede any instruction that references it.
    constraints = {s.identity: s for s in spans if s.kind == "constraint"}
    for ins in (s for s in spans if s.kind == "instruction"):
        ref = ins.identity.split("::ref::")[-1]
        if ref in constraints and constraints[ref].start > ins.start:
            raise InvariantViolation(
                "I4_constraint_precedes_dependent", -1,
                f"instruction '{ins.identity}' precedes constraint '{ref}'",
            )

    # Reorder operations are the only way ordering invariants can be broken
    # while every span survives verbatim; re-validate the post-reorder graph.
    for i, op in enumerate(ops):
        if op.kind == "reorder":
            moved = {op.a, op.b}
            for ins in (s for s in spans if s.kind == "instruction"):
                ref = ins.identity.split("::ref::")[-1]
                if ref in moved and ins.identity in moved:
                    raise InvariantViolation(
                        "I4_constraint_precedes_dependent", i,
                        f"reorder would invert constraint/instruction order for '{ref}'",
                    )


def admit_rewrite(ops: list[EditOp], spans: list[Span]) -> list[EditOp]:
    """Return ops only if every invariant holds; otherwise refuse atomically."""
    try:
        check_invariant_preservation(ops, spans)
    except InvariantViolation:
        raise  # caller routes to bounded repair; never apply partially
    return ops
