# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-honor-a-self-authored-pruning-directive-the-salience-provenance-divergence-at-rewrite-time.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-honor-a-self-authored-pruning-directive-the-salience-provenance-divergence-at-rewrite-time.warrant.json
# Markdown SHA-256:   b29012bb12343046ea5d35809f462cd442fe0a571b56c9884a0e3b985a53b98a
# Code AST SHA-256:   303b81d102141e790670c531275618af761c802f9edbbc0e34001179179e2bd8
# Verified Classes:   UnsoundSelfEditError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set, List


class UnsoundSelfEditError(RuntimeError):
    """Raised when a model-authored pruning directive cannot be safely applied."""
    pass


@dataclass
class Span:
    span_id: str
    salience: float
    # span_ids the model claims justify dropping THIS span
    justified_by: Set[str] = field(default_factory=set)


def validate_self_edit(spans: Dict[str, Span], drop_threshold: float = 0.2) -> List[str]:
    """
    Returns the list of span_ids that may be dropped.
    Raises UnsoundSelfEditError if the drop-graph is cyclic or dangles
    into a span that is itself being dropped.
    """
    to_drop = {sid for sid, s in spans.items() if s.salience < drop_threshold}
    retained = set(spans) - to_drop

    for sid in to_drop:
        justifiers = spans[sid].justified_by
        # Every justification must point at a SURVIVING span.
        dangling = justifiers - retained
        if dangling:
            raise UnsoundSelfEditError(
                f"span {sid} dropped but justified only by spans also being "
                f"dropped/absent: {sorted(dangling)} -- mutual-deletion cycle"
            )
        # A span cannot justify its own removal.
        if sid in justifiers:
            raise UnsoundSelfEditError(
                f"span {sid} cites itself as justification for deletion"
            )

    # Cycle detection over the justification graph restricted to dropped spans.
    graph = {sid: (spans[sid].justified_by & to_drop) for sid in to_drop}
    state: Dict[str, int] = {}  # 0=unseen,1=visiting,2=done

    def visit(node: str) -> None:
        state[node] = 1
        for nxt in graph.get(node, set()):
            if state.get(nxt) == 1:
                raise UnsoundSelfEditError(
                    f"cyclic justification among dropped spans: {node} -> {nxt}"
                )
            if state.get(nxt, 0) == 0:
                visit(nxt)
        state[node] = 2

    for sid in to_drop:
        if state.get(sid, 0) == 0:
            visit(sid)

    return sorted(to_drop)


def apply_self_rewrite(spans: Dict[str, Span], drop_threshold: float = 0.2) -> Dict[str, Span]:
    droppable = validate_self_edit(spans, drop_threshold)
    if not droppable and any(s.salience < drop_threshold for s in spans.values()):
        # Defensive: validator should have raised; never silently proceed.
        raise UnsoundSelfEditError("validator returned empty drop set with sub-threshold spans")
    return {sid: s for sid, s in spans.items() if sid not in set(droppable)}
