# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-mid-prune-self-reference-hazard-in-model-driven-context-rewriting.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-mid-prune-self-reference-hazard-in-model-driven-context-rewriting.warrant.json
# Markdown SHA-256:   2aeb556df0150218b5e8064aea2ccaa50ac5daa3322f067e4c8fc039e6b86606
# Code AST SHA-256:   caff7d8d49fa3a815932e3b200801ea5d74e828d6bb177cfc6484d3066745c6c
# Verified Classes:   SelfReferentialPruneError, PruneAction, ContextMutator
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class SelfReferentialPruneError(RuntimeError):
    """Raised when a prune action's rationale cites spans it neither deletes nor pins."""


@dataclass
class PruneAction:
    action_id: str
    targets: set[str]          # span_ids being deleted
    rationale_refs: set[str]   # span_ids cited by the rationale


@dataclass
class ContextMutator:
    pinned: set[str] = field(default_factory=set)
    prune_log: list[PruneAction] = field(default_factory=list)

    def apply(self, action: PruneAction) -> None:
        # Closure rule: every cited span must be deleted in this action
        # or already pinned (or pinned by this action).
        unprotected = action.rationale_refs - action.targets - self.pinned
        if unprotected:
            raise SelfReferentialPruneError(
                f"prune {action.action_id} cites spans {sorted(unprotected)} "
                f"that are neither deleted nor pinned; applying it would "
                f"sever the rationale's own evidence and enable a "
                f"contradictory second-pass prune."
            )
        # Pin referenced-but-surviving spans for all future passes.
        new_pins = action.rationale_refs - action.targets
        self.pinned |= new_pins
        self.prune_log.append(action)

    def unpin(self, span_id: str, justification_refs: Iterable[str]) -> None:
        # Unpinning must not cite the span being unpinned (prevents unpin-loops).
        refs = set(justification_refs)
        if span_id in refs:
            raise SelfReferentialPruneError(
                f"cannot unpin {span_id} using a justification that cites it."
            )
        self.pinned.discard(span_id)


def run_pass(mutator: ContextMutator, actions: list[PruneAction]) -> None:
    for action in actions:
        mutator.apply(action)  # raises SelfReferentialPruneError on violation
