# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-its-own-pruning-policy-has-orphaned-a-live-dependency-when-self-editing-its-context-window.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-its-own-pruning-policy-has-orphaned-a-live-dependency-when-self-editing-its-context-window.warrant.json
# Markdown SHA-256:   4536f376d798a992ffeb2f3a8d784c5749afe6b78613db8bea6baf7d2ab95e2a
# Code AST SHA-256:   bdf2576903ae28ddd7b1363963aa138513de5c5d342e22929daca91e628b30b3
# Verified Classes:   OrphanedDependencyError, Obligation, ContextWindow
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class OrphanedDependencyError(RuntimeError):
    """Raised when a self-edit would leave a live obligation unbound."""


@dataclass(frozen=True)
class Obligation:
    kind: str          # "tool_call" | "binding" | "reference" | "predicate"
    key: str           # e.g. run_id, tool_call_id, artifact handle
    span_ids: frozenset[str]  # window spans this obligation depends on


@dataclass
class ContextWindow:
    spans: dict[str, str] = field(default_factory=dict)  # span_id -> text
    obligations: set[Obligation] = field(default_factory=set)


def enumerate_obligations(window: ContextWindow) -> set[Obligation]:
    """Deterministic pass: extract open obligations. No LLM judgment here."""
    # In production this is regex + schema extraction over window.spans.
    return set(window.obligations)


def pinned_spans(obligations: Iterable[Obligation]) -> frozenset[str]:
    """Backward slice: every span any open obligation depends on."""
    pinned: set[str] = set()
    for ob in obligations:
        pinned |= ob.span_ids
    return frozenset(pinned)


def apply_prune(
    window: ContextWindow,
    evict_span_ids: Iterable[str],
    *,
    pre_snapshot: ContextWindow,
) -> ContextWindow:
    """Apply a model-proposed eviction set, enforcing the liveness invariant."""
    pre_obligations = enumerate_obligations(pre_snapshot)
    pinned = pinned_spans(pre_obligations)

    proposed = frozenset(evict_span_ids)
    violating = proposed & pinned
    if violating:
        raise OrphanedDependencyError(
            f"prune would evict pinned spans {sorted(violating)} "
            f"holding live obligations; abort and keep snapshot"
        )

    new_spans = {sid: txt for sid, txt in window.spans.items() if sid not in proposed}
    candidate = ContextWindow(spans=new_spans, obligations=set(window.obligations))

    # Post-prune liveness audit: no obligation may become unresolvable.
    surviving = {sid for sid in new_spans}
    for ob in pre_obligations:
        if not (ob.span_ids & surviving):
            raise OrphanedDependencyError(
                f"post-prune audit: obligation {ob.kind}:{ob.key} "
                f"is now unbound (referents {sorted(ob.span_ids)} evicted)"
            )
    return candidate
