# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-rewrites-against-the-irreversible-evidence-loss-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-self-editing-context-rewrites-against-the-irreversible-evidence-loss-invariant.warrant.json
# Markdown SHA-256:   7a146ef5da96e9295d7abb24773bc7fdd1f26f93ea988e27eda4a5e2579882a2
# Code AST SHA-256:   cbe0e794264697e42620fb73f2d5ad9f54e6dfd39b03b041f0dc5e780e628301
# Verified Classes:   IrreversibleEvidenceLoss, ExtractedSlot, EditLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import re
from dataclasses import dataclass, field


class IrreversibleEvidenceLoss(RuntimeError):
    """Raised when a self-edit would delete a value-bearing span without a verbatim extraction."""
    pass


# Deterministic patterns for Class B (value-bearing, non-re-derivable) tokens.
VALUE_BEARING = [
    re.compile(r"\b[0-9a-f]{7,40}\b"),          # commit SHAs / hashes
    re.compile(r"\b0x[0-9a-fA-F]+\b"),           # byte offsets
    re.compile(r'"[^"]{8,}"'),                   # verbatim asserted strings
    re.compile(r"\b\d+(?:\.\d+)?\s*(?:ms|s|MB|KB|%)\b"),  # thresholds
]


@dataclass
class ExtractedSlot:
    pattern_id: int
    value: str
    source_turn: int


@dataclass
class EditLedger:
    slots: list[ExtractedSlot] = field(default_factory=list)
    dropped_span_hashes: list[str] = field(default_factory=list)

    def carry_forward(self, prior: "EditLedger") -> None:
        # Append-only: never re-derive slots from a prior digest.
        self.slots.extend(prior.slots)


def scan_value_bearing(span: str, turn: int) -> list[ExtractedSlot]:
    found = []
    for pid, pat in enumerate(VALUE_BEARING):
        for m in pat.finditer(span):
            found.append(ExtractedSlot(pattern_id=pid, value=m.group(0), source_turn=turn))
    return found


def gate_self_edit(
    span_to_drop: str,
    turn: int,
    ledger: EditLedger,
    model_digest: str,
) -> EditLedger:
    """
    Veto any cut that drops a value-bearing token not present verbatim in the digest.
    The model proposes the cut; this gate decides whether exact values survive.
    """
    required = scan_value_bearing(span_to_drop, turn)

    for slot in required:
        if slot.value not in model_digest:
            raise IrreversibleEvidenceLoss(
                f"Turn {turn}: cut would drop value-bearing token "
                f"{slot.value!r} (pattern {slot.pattern_id}) absent from digest. "
                f"Extract verbatim into a slot or move the cut point."
            )

    # Safe: extract verbatim, then record the drop for audit.
    ledger.slots.extend(required)
    ledger.dropped_span_hashes.append(hashlib.sha256(span_to_drop.encode()).hexdigest())
    return ledger


def apply_self_edit(ledger: EditLedger, prior: EditLedger | None) -> EditLedger:
    if prior is not None:
        ledger.carry_forward(prior)
    return ledger
