# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-prune-a-salience-weighted-context-window-because-the-rewrite-would-orphan-an-unverified-tool-call-premise.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-prune-a-salience-weighted-context-window-because-the-rewrite-would-orphan-an-unverified-tool-call-premise.warrant.json
# Markdown SHA-256:   b2199d4461a00d4bb70f4d51fb9229e995a9151c8c306d3e8107cf80975ed531
# Code AST SHA-256:   8041492498f68b80ca02fa1146b4e82ba2f3ac1b06a483002189675667814d4d
# Verified Classes:   SpanKind, PremiseOrphaningError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class SpanKind(Enum):
    CHATTER = "chatter"                 # dependency-closed, freely prunable
    RESOLVED = "resolved"               # dependents already discharged
    CONSTRAINT = "constraint"           # user/system literal, paraphrase-lossy
    VERIFICATION_WITNESS = "verification_witness"  # tool return gating a side effect
    INTERMEDIATE = "intermediate"       # value a pending branch will dereference


class PremiseOrphaningError(RuntimeError):
    """Raised when a rewrite would remove the only in-window support for a live premise."""


@dataclass
class Span:
    span_id: str
    kind: SpanKind
    salience: float
    live_dependents: set[str] = field(default_factory=set)
    externally_committed: bool = False


def is_admissible_to_prune(span: Span) -> bool:
    # Dependency classification gates admissibility; salience is irrelevant here.
    if span.kind in (SpanKind.VERIFICATION_WITNESS, SpanKind.CONSTRAINT):
        return span.externally_committed
    if span.kind == SpanKind.INTERMEDIATE:
        return span.externally_committed and not span.live_dependents
    if span.live_dependents and not span.externally_committed:
        return False
    return True


def rewrite_window(spans: list[Span], token_budget: int) -> list[Span]:
    # Order by salience ascending: cheapest meaning first.
    candidates = sorted(spans, key=lambda s: s.salience)
    kept: list[Span] = []
    pruned: list[Span] = []

    for span in candidates:
        if len(kept) + len(pruned) >= token_budget and is_admissible_to_prune(span):
            pruned.append(span)
        else:
            kept.append(span)

    # Post-condition: no protected span was pruned without external commitment.
    for span in pruned:
        if not is_admissible_to_prune(span):
            raise PremiseOrphaningError(
                f"Rewrite pruned span {span.span_id} ({span.kind.value}) with "
                f"live dependents {sorted(span.live_dependents)} and no external "
                f"commitment; downstream steps would confabulate a replacement premise."
            )

    # Saturation with all candidates protected is a checkpoint trigger, not a prune.
    if len(kept) > token_budget:
        raise PremiseOrphaningError(
            "Window saturated with protected spans; refusing to force-prune. "
            "Halt branch, persist state, resume with a re-derived window."
        )

    return kept
