# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-own-pruning-decisions-when-the-context-window-edits-itself-mid-reasoning.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-own-pruning-decisions-when-the-context-window-edits-itself-mid-reasoning.warrant.json
# Markdown SHA-256:   60f52512e877de230eb9ba9bc37dbf51bb06ca179d76112616d19e31ea13cfe7
# Code AST SHA-256:   c321d59ca39025d6711d23017e19e5af1303a4f59e0e09408ba5514efc4e4bb0
# Verified Classes:   DanglingPruneError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class DanglingPruneError(RuntimeError):
    """Raised when a prune would evict a span still cited by a retained claim."""
    pass


@dataclass
class Span:
    id: str
    content: str
    pinned: bool = False
    cites: list[str] = field(default_factory=list)  # span ids this span depends on


def prune(spans: dict[str, Span], scores: dict[str, float], threshold: float) -> dict[str, Span]:
    """
    Evict spans below threshold, but enforce referential closure:
    a span may be evicted only if no retained span cites it, and pinned
    spans are never evictable regardless of score.
    """
    evict = {sid for sid, s in scores.items() if s < threshold and not spans[sid].pinned}

    # Cascade: if a retained span cites an evicted span, the eviction is unsafe.
    for sid, span in spans.items():
        if sid in evict:
            continue
        for dep in span.cites:
            if dep in evict:
                raise DanglingPruneError(
                    f"span {sid!r} cites {dep!r} which prune would evict; "
                    f"evict the citing claim atomically or raise its support's score"
                )

    # A pinned span requested for eviction is a hard violation, not a soft skip.
    for sid, s in scores.items():
        if s < threshold and spans[sid].pinned:
            raise DanglingPruneError(
                f"pinned span {sid!r} scored {s:.2f} < {threshold}; "
                f"fail closed and checkpoint rather than evict a constraint"
            )

    return {sid: s for sid, s in spans.items() if sid not in evict}
