# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-pruning-policy-has-evicted-the-load-bearing-premise-of-the-current-task.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-pruning-policy-has-evicted-the-load-bearing-premise-of-the-current-task.warrant.json
# Markdown SHA-256:   e73560c8ab4a15ad470cc75732111a897b35a12b11c290b7b1c223d3fc3d90fd
# Code AST SHA-256:   f3467dba2ab00adb68ec3abe1fc2b2e80c2e29da06801170e60fd13ba527e9b2
# Verified Classes:   PremiseEvictionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class PremiseEvictionError(RuntimeError):
    """Raised when a self-prune pass would evict the last handle to an open obligation."""
    pass


def guarded_prune(context_spans, proposed_evictions, open_obligations, durable_store):
    """
    context_spans: list of Span(id, text, kind) where kind in {"fact","instruction","definition","correction","reasoning"}
    proposed_evictions: set of span ids the relevance scorer wants to drop
    open_obligations: dict obligation_id -> span_id that currently anchors it
    durable_store: dict span_id -> text, for pinned persistence
    """
    evicted = set(proposed_evictions)

    # Step 1: identify obligations whose only anchor is about to be evicted.
    orphaned = {
        ob_id: anchor
        for ob_id, anchor in open_obligations.items()
        if anchor in evicted
    }

    # Step 2: any orphaned obligation is a hard stop unless it can be re-pinned
    # from a durable handle that survives the prune.
    for ob_id, anchor in orphaned.items():
        if anchor not in durable_store:
            raise PremiseEvictionError(
                f"Prune would evict last anchor {anchor!r} for open obligation "
                f"{ob_id!r} with no durable copy; refusing to prune."
            )

    # Step 3: constraints, definitions and corrections are never evicted
    # on relevance alone -- they are pinned regardless of score.
    pinned_kinds = {"instruction", "definition", "correction"}
    for span in context_spans:
        if span.kind in pinned_kinds and span.id in evicted:
            raise PremiseEvictionError(
                f"Span {span.id!r} of kind {span.kind!r} is load-bearing by type "
                f"and cannot be evicted by relevance score."
            )

    # Step 4: evict only what remains, and re-pin surviving anchors.
    survivors = [s for s in context_spans if s.id not in evicted]
    for ob_id, anchor in open_obligations.items():
        if anchor in durable_store and anchor not in {s.id for s in survivors}:
            # Re-inject a compact handle so the obligation stays visible.
            survivors.append(make_handle_span(ob_id, durable_store[anchor]))
    return survivors


def make_handle_span(ob_id, text):
    raise NotImplementedError  # build a minimal Span carrying ob_id + digest
