# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-rewrites-when-pruning-destroys-the-provenance-needed-to-re-synthesize-it.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-rewrites-when-pruning-destroys-the-provenance-needed-to-re-synthesize-it.warrant.json
# Markdown SHA-256:   9329e0c8c37ab2cd3a45a4491baca3173d22bd9533cd3c9631b08e81e57bb0fd
# Code AST SHA-256:   3345e35b09ffb6de7564b88acdc707a0d6d4a71c0b71ce8766fb9b26c74e286b
# Verified Classes:   ProvenanceKind, ProvenanceViolation, Claim, SelfEdit
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ProvenanceKind(Enum):
    VERBATIM = "verbatim"          # original span retained
    REFETCHABLE = "refetchable"    # distilled, but a tool call can re-derive it
    UNVERIFIABLE = "unverifiable"  # distilled from a non-re-derivable source


class ProvenanceViolation(RuntimeError):
    """Raised when a self-edit emits a distilled claim that cannot be re-derived
    and is about to be acted upon as if it were directly observed."""
    pass


@dataclass
class Claim:
    text: str
    kind: ProvenanceKind
    handle: Optional[str] = None  # tool-call id / file path / message id

    def is_actionable(self) -> bool:
        # A claim may drive a commit only if it is verbatim, or refetchable
        # *and* the handle is present to re-derive it.
        if self.kind is ProvenanceKind.VERBATIM:
            return True
        if self.kind is ProvenanceKind.REFETCHABLE and self.handle:
            return True
        return False


@dataclass
class SelfEdit:
    """Result of a model-driven prune/re-synthesis pass."""
    claims: list[Claim] = field(default_factory=list)

    def guard_commit(self, claim: Claim) -> None:
        if claim.kind is ProvenanceKind.UNVERIFIABLE:
            raise ProvenanceViolation(
                f"Refusing to commit on unverifiable distilled claim: {claim.text!r}. "
                "No verbatim source and no re-fetch handle retained by the prune."
            )
        if claim.kind is ProvenanceKind.REFETCHABLE and not claim.handle:
            raise ProvenanceViolation(
                f"Refetchable claim {claim.text!r} lost its handle during re-synthesis; "
                "cannot re-derive before acting."
            )
        if not claim.is_actionable():
            raise ProvenanceViolation(
                f"Claim {claim.text!r} failed actionability check post-prune."
            )


def commit_edit(edit: SelfEdit, target: Claim) -> str:
    """Commit a mutation only after the provenance invariant is satisfied."""
    edit.guard_commit(target)
    # Safe: either verbatim, or refetchable with a live handle.
    return f"committed: {target.text}"
