# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-rewrite-its-own-prompt-mid-flight-and-lose-the-invariant-it-was-preserving.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-rewrite-its-own-prompt-mid-flight-and-lose-the-invariant-it-was-preserving.warrant.json
# Markdown SHA-256:   2b7724a2ec2e3820b124d496c81515e6405802b2f4d2ff3970e85b2b368cb57f
# Code AST SHA-256:   6440e63c2092ea136aef7187cb19a13e854d600dfcd3f1cad23568cdec109935
# Verified Classes:   Reachability, ObligationPreservationError, Rule, RewriteProposal
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class Reachability(Enum):
    REACHABLE = "reachable"
    UNREACHABLE = "unreachable"
    UNKNOWN = "unknown"


class ObligationPreservationError(RuntimeError):
    """Raised when a self-edit would drop or weaken a frozen obligation."""


@dataclass(frozen=True)
class Rule:
    name: str
    frozen: bool
    numeric_invariant: int | None = None


@dataclass
class RewriteProposal:
    kept: list[Rule] = field(default_factory=list)
    dropped: list[Rule] = field(default_factory=list)
    weakened: list[Rule] = field(default_factory=list)


def classify_reachability(rule: Rule, remaining_tools: set[str]) -> Reachability:
    # A rule is REACHABLE if any remaining tool can produce its trigger.
    # UNKNOWN is the default for open-ended or probabilistic tool outputs.
    if rule.name == "no_delete" and "delete_record" in remaining_tools:
        return Reachability.REACHABLE
    if rule.name == "call_cap" and remaining_tools:
        return Reachability.REACHABLE
    return Reachability.UNKNOWN


def commit_rewrite(proposal: RewriteProposal, remaining_tools: set[str]) -> list[Rule]:
    surviving: list[Rule] = list(proposal.kept)

    for rule in proposal.dropped:
        reach = classify_reachability(rule, remaining_tools)
        if rule.frozen or reach is not Reachability.UNREACHABLE:
            raise ObligationPreservationError(
                f"illegal drop of rule {rule.name!r}: "
                f"frozen={rule.frozen}, reachability={reach.value}; "
                f"unknown reachability is not permission to drop"
            )
        # Only a proven-unreachable, non-frozen rule may be dropped,
        # and the proof must be recorded for resume-time re-instantiation.

    for rule in proposal.weakened:
        if rule.numeric_invariant is not None:
            raise ObligationPreservationError(
                f"numeric invariant {rule.name!r}={rule.numeric_invariant} "
                f"may be reworded but not paraphrased into a heuristic"
            )
        surviving.append(rule)

    if not any(r.name == "no_delete" for r in surviving):
        raise ObligationPreservationError(
            "post-rewrite rule set lacks a frozen no_delete obligation; "
            "refusing to commit edit that licenses the forbidden trigger"
        )

    return surviving


def apply_self_edit(proposal: RewriteProposal, remaining_tools: set[str]) -> list[Rule]:
    try:
        return commit_rewrite(proposal, remaining_tools)
    except ObligationPreservationError as exc:
        # Do not silently fall back to the pre-edit context; surface the
        # rejected edit so the trace attributes the near-miss to the rewrite.
        raise ObligationPreservationError(
            f"self-edit rejected at checkpoint boundary: {exc}"
        ) from exc
