# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-self-rewriting-context-agents-from-silently-destroying-the-evidence-their-own-coherence-check-depends-on.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-self-rewriting-context-agents-from-silently-destroying-the-evidence-their-own-coherence-check-depends-on.warrant.json
# Markdown SHA-256:   14757b3ec952c8294b4aca791c810694650f257ebd650e64386ad588e0581ffa
# Code AST SHA-256:   6a667c3f176c0adb53657488b2e1943a3133b40407dcecf5695951e5d69402f8
# Verified Classes:   ConstraintFidelityError, ConstraintSpan, SpanVerdict
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence


class ConstraintFidelityError(RuntimeError):
    """Raised when a self-edit would drop or paraphrase a pinned constraint."""
    pass


@dataclass(frozen=True)
class ConstraintSpan:
    span_id: str
    verbatim: str
    source_call: int


@dataclass(frozen=True)
class SpanVerdict:
    span_id: str
    status: str  # "preserved" | "paraphrased" | "absent"


def verify_rewrite(
    pinned: Sequence[ConstraintSpan],
    candidate_summary: str,
    verifier,  # fresh-context callable: (spans, summary) -> list[SpanVerdict]
    budget_tokens: int,
    pinned_tokens: int,
) -> None:
    # Invariant 1: pinned region must not exceed half the budget, else the
    # compression is net-negative and in-place rewriting is disallowed.
    if pinned_tokens * 2 > budget_tokens:
        raise ConstraintFidelityError(
            f"pinned region {pinned_tokens} > 50% of budget {budget_tokens}; "
            "in-place rewrite is unsound, switch to external eviction"
        )

    # Invariant 2: verifier must see pinned spans + candidate, in a fresh context.
    verdicts = verifier(pinned, candidate_summary)
    if len(verdicts) != len(pinned):
        raise ConstraintFidelityError(
            f"verifier returned {len(verdicts)} verdicts for {len(pinned)} spans; "
            "partial verification is not a pass"
        )

    # Invariant 3: any paraphrase or absence blocks the commit. A paraphrase
    # is already drift — the ratchet starts at "paraphrased", not "absent".
    for v in verdicts:
        if v.status == "absent":
            raise ConstraintFidelityError(
                f"constraint {v.span_id} absent from candidate summary; commit blocked"
            )
        if v.status == "paraphrased":
            raise ConstraintFidelityError(
                f"constraint {v.span_id} paraphrased; verbatim pin required, commit blocked"
            )


def commit_rewrite(buffer, candidate_summary, pinned, verifier, budget_tokens, pinned_tokens):
    verify_rewrite(pinned, candidate_summary, verifier, budget_tokens, pinned_tokens)
    # Atomic swap only after verification passes on the pre-edit reference.
    buffer.replace_narrative(candidate_summary)
