# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-its-own-scratchpad-the-self-edit-re-entry-hazard-in-model-driven-relevance-pruning.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-prune-its-own-scratchpad-the-self-edit-re-entry-hazard-in-model-driven-relevance-pruning.warrant.json
# Markdown SHA-256:   597235e599c6bf910318df7b1e50feff958eedfeaccabfbd9b3e56eab0830c5b
# Code AST SHA-256:   2afd60803203a63b90427234e919b22d0bfc7586ac3efeb5070ae40ff8e2008c
# Verified Classes:   SelfEditConservationError, Span, Scratchpad
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class SelfEditConservationError(RuntimeError):
    """Raised when a self-authored scratchpad prune would violate the
    constraint-conservation invariant or fail the fixed-point check."""
    pass


@dataclass
class Span:
    text: str
    pinned: bool = False
    governs_decision: str | None = None   # decision this span constrains
    provenance_of_action: bool = False    # instance acted on this span
    retrievable: bool = True              # lossless pointer exists


@dataclass
class Scratchpad:
    spans: list[Span] = field(default_factory=list)
    open_decisions: set[str] = field(default_factory=set)


def commit_self_edit(
    pad: Scratchpad,
    candidate_keep: Callable[[list[Span]], set[int]],
    policy: Callable[[list[Span]], set[int]],
    re_entrant: bool,
) -> Scratchpad:
    """Commit a model-authored prune only if it conserves constraints
    and is a fixed point of the policy under re-entry."""
    keep = candidate_keep(pad.spans)
    removed = [s for i, s in enumerate(pad.spans) if i not in keep]

    # 1. Pending-decision constraint conservation.
    for s in removed:
        if s.pinned and s.governs_decision in pad.open_decisions:
            raise SelfEditConservationError(
                f"prune removes span governing open decision {s.governs_decision!r}"
            )
        if s.provenance_of_action and not s.retrievable:
            raise SelfEditConservationError(
                "prune removes provenance of an action already taken; audit chain severed"
            )

    new_spans = [s for i, s in enumerate(pad.spans) if i in keep]

    # 2. Fixed-point check under re-entry.
    if re_entrant:
        second_keep = policy(new_spans)
        if len(second_keep) < len(new_spans):
            eroded = [new_spans[i] for i in range(len(new_spans)) if i not in second_keep]
            raise SelfEditConservationError(
                f"self-edit is not a fixed point; re-entry would erode "
                f"{len(eroded)} further span(s): {[s.text[:40] for s in eroded]}"
            )

    return Scratchpad(spans=new_spans, open_decisions=set(pad.open_decisions))
