# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-self-editing-context-window-has-pruned-its-own-dependency-anchors.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-self-editing-context-window-has-pruned-its-own-dependency-anchors.warrant.json
# Markdown SHA-256:   28a01fa3172d85098084e21e70a3297dc59c11d0d8316047ef4cb62fdb2ea7af
# Code AST SHA-256:   f1940997edfa9bfef0c1679e56bf2a767890094fe0df3578c13c958e19310985
# Verified Classes:   AnchorSeveranceError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AnchorSeveranceError(RuntimeError):
    """Raised when a self-editing prune would sever a dependency anchor
    (a reference or quantifier-scope binding) required by surviving spans."""
    pass


@dataclass
class Span:
    span_id: str
    text: str
    # references this span makes to *other* span ids (pronouns, IDs, paths, constraints)
    outbound_refs: set[str] = field(default_factory=set)
    # scope/quantifier tokens whose restriction lives in another span
    scope_restrictions: set[str] = field(default_factory=set)
    salience: float = 0.0  # model-judged importance; NOT a dependency signal


def prune_window(spans: list[Span], budget_tokens: int, tok) -> list[Span]:
    """
    Model-driven prune with anchor guard.
    Evicts lowest-salience spans until under budget, but refuses to evict
    any span that is the antecedent for a surviving span's reference or
    quantifier scope. Fails closed; never silently re-binds.
    """
    survivors = list(spans)
    total = sum(tok(s.text) for s in survivors)

    # candidate eviction order: lowest salience first (the model's policy)
    order = sorted(survivors, key=lambda s: s.salience)

    evicted: set[str] = set()
    for cand in order:
        if total <= budget_tokens:
            break

        # anchor check: does any *surviving* span depend on this one?
        dependents = [
            s for s in survivors
            if s.span_id not in evicted
            and s.span_id != cand.span_id
            and (cand.span_id in s.outbound_refs
                 or cand.span_id in s.scope_restrictions)
        ]
        if dependents:
            # cannot evict; must rebind in place instead of removing
            raise AnchorSeveranceError(
                f"prune would sever anchor {cand.span_id!r} "
                f"({cand.text[:40]!r}) required by "
                f"{[d.span_id for d in dependents]}; "
                f"rebind-in-place required, not eviction"
            )

        evicted.add(cand.span_id)
        total -= tok(cand.text)

    if total > budget_tokens:
        raise AnchorSeveranceError(
            f"cannot meet budget {budget_tokens} without severing anchors; "
            f"residual={total}"
        )
    return [s for s in survivors if s.span_id not in evicted]
