# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-working-context-and-silently-deletes-the-evidence-it-needs-to-verify-the-rewrite.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-working-context-and-silently-deletes-the-evidence-it-needs-to-verify-the-rewrite.warrant.json
# Markdown SHA-256:   47b9ba12646ea05f93e42f56c51b1b2d49f765ddf8997ce74c1f91d5bdaca3bf
# Code AST SHA-256:   1bab3fc7015f783037d6837d56d9012c576d25bd8ab6a2b6e653cffd9a80252e
# Verified Classes:   ProvenanceViolation, Span, EditRecord, SelfEditingContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Callable


class ProvenanceViolation(RuntimeError):
    """Raised when a self-edit would destroy the evidence needed to verify it."""
    pass


@dataclass(frozen=True)
class Span:
    span_id: str
    text: str

    def digest(self) -> str:
        return hashlib.sha256(self.text.encode()).hexdigest()


@dataclass
class EditRecord:
    edit_id: str
    op: str                      # "drop" | "summarize" | "reorder"
    targets: tuple[str, ...]
    justification: str           # machine-checkable predicate description
    retained_witness: dict       # must survive the edit; e.g. {"equiv_span": "T", "digest": "..."}


class SelfEditingContext:
    """A context buffer that permits model-authored edits only when the edit
    retains a witness sufficient to re-derive its own justification."""

    def __init__(self, spans: list[Span]):
        self._spans: dict[str, Span] = {s.span_id: s for s in spans}
        self._log: list[EditRecord] = []          # append-only, never a drop target
        self._verifiers: dict[str, Callable[[EditRecord, dict[str, Span]], bool]] = {
            "drop": self._verify_drop,
        }

    def _verify_drop(self, rec: EditRecord, pre_edit: dict[str, Span]) -> bool:
        # A drop is legal only if every target is provably equivalent to a
        # retained span, witnessed by a digest that survives the drop.
        equiv_id = rec.retained_witness.get("equiv_span")
        if equiv_id is None or equiv_id not in pre_edit:
            return False
        equiv_digest = pre_edit[equiv_id].digest()
        if rec.retained_witness.get("digest") != equiv_digest:
            return False
        for tid in rec.targets:
            if tid not in pre_edit:
                return False
            if pre_edit[tid].digest() != equiv_digest:
                return False  # not actually equivalent — signature drift class
        return True

    def apply(self, rec: EditRecord) -> None:
        verifier = self._verifiers.get(rec.op)
        if verifier is None:
            raise ProvenanceViolation(f"no verifier for op {rec.op!r}; edit is unauditable")
        pre_edit = dict(self._spans)
        if not verifier(rec, pre_edit):
            # The edit claims equivalence it cannot prove. Applying it would
            # delete the only evidence that could later catch the error.
            raise ProvenanceViolation(
                f"edit {rec.edit_id} ({rec.op}) rejected: retained_witness does not "
                f"establish justification {rec.justification!r} for targets {rec.targets}"
            )
        for tid in rec.targets:
            self._spans.pop(tid, None)
        self._log.append(rec)

    def audit(self, edit_id: str) -> bool:
        """Re-derive an edit's justification from the log alone. If this needs
        the dropped text, the edit was never valid."""
        for rec in self._log:
            if rec.edit_id == edit_id:
                # Witness must be self-contained: digest + equiv span id, both
                # checkable against the surviving buffer.
                equiv = self._spans.get(rec.retained_witness.get("equiv_span", ""))
                if equiv is None:
                    raise ProvenanceViolation(
                        f"audit of {edit_id} failed: witness span was itself edited away"
                    )
                return equiv.digest() == rec.retained_witness.get("digest")
        raise ProvenanceViolation(f"no record for edit {edit_id}")
