# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-apply-a-model-authored-context-diff-when-the-diff-s-own-verification-predicate-is-satisfiable-by-the-model-s-rewrite.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-apply-a-model-authored-context-diff-when-the-diff-s-own-verification-predicate-is-satisfiable-by-the-model-s-rewrite.warrant.json
# Markdown SHA-256:   eb6e543c493f13c4b79c243d5b241aa821a2f248afc42850cbb2925c5780fa8f
# Code AST SHA-256:   f75acfa24cc801613b560e9858141cdce7442a7e318bb41e8000dbcdd76900db
# Verified Classes:   PredicateMutationError, Checkpoint
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class PredicateMutationError(RuntimeError):
    """Raised when a candidate diff intersects the verification predicate,
    the checkpoint machinery, or the evaluator configuration. A passing
    evaluation in this case is uninformative and must not be trusted."""
    pass


class Checkpoint:
    def __init__(self, context: str, predicate_source: str, predicate_fn):
        self.context = context
        self.predicate_source = predicate_source
        self.predicate_fn = predicate_fn
        self.immutable_ranges = [(0, len(predicate_source))]


def apply_self_edit(
    checkpoint: Checkpoint,
    candidate_context: str,
    diff_hunks: list[tuple[int, int]],
    predicate_offset: int,
) -> str:
    """Apply a model-authored diff to its own context, with diff-based
    verification. Rejects any diff that can reach the predicate."""
    pred_start = predicate_offset
    pred_end = predicate_offset + len(checkpoint.predicate_source)

    for (start, end) in diff_hunks:
        if start < pred_end and end > pred_start:
            raise PredicateMutationError(
                f"diff hunk [{start},{end}) intersects predicate source "
                f"[{pred_start},{pred_end}); evaluation would be self-certifying"
            )

    if not checkpoint.predicate_fn(candidate_context):
        # Genuine failure: restore from checkpoint.
        return checkpoint.context

    return candidate_context
