# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-self-pruning-context-agent-has-silently-orphaned-a-live-dependency-during-turn-eviction.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-self-pruning-context-agent-has-silently-orphaned-a-live-dependency-during-turn-eviction.warrant.json
# Markdown SHA-256:   528d654041ca6f1f5a3c339b6d84e26b0fa2a58fb6360a1b5e95224c24b89913
# Code AST SHA-256:   c46d22bab4748912628af5ee1a314e0649614badde4dfdd7f31a589ce344dc14
# Verified Classes:   OrphanedReferenceError, Turn, WorkingMemory
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class OrphanedReferenceError(RuntimeError):
    """Raised when a live reference resolves only to evicted turns and was not
    promoted verbatim into the invariant summary."""
    pass


@dataclass
class Turn:
    id: int
    defines: set[str] = field(default_factory=set)      # literals this turn binds
    references: set[str] = field(default_factory=set)   # literals this turn dereferences
    summary_depth: int = 0                              # 0 = raw, >=1 = summarized


@dataclass
class WorkingMemory:
    turns: dict[int, Turn]
    summary_literals: set[str] = field(default_factory=set)  # verbatim-promoted bindings
    summary_depth: int = 0

    def resolver_depth(self, ref: str) -> Optional[int]:
        """Return provenance depth of the resolver for `ref`, or None if orphaned."""
        if ref in self.summary_literals:
            return self.summary_depth
        depths = [t.summary_depth for t in self.turns.values() if ref in t.defines]
        return min(depths) if depths else None

    def commit_eviction(self, evict_ids: set[int], promote: set[str]) -> None:
        # Promote requested literals into the summary verbatim before eviction.
        self.summary_literals |= promote
        for tid in evict_ids:
            self.turns.pop(tid, None)

        # Reachability check: every live reference must still resolve.
        live_refs = set()
        for t in self.turns.values():
            live_refs |= t.references

        for ref in live_refs:
            depth = self.resolver_depth(ref)
            if depth is None:
                raise OrphanedReferenceError(
                    f"Reference '{ref}' has no resolver after eviction; "
                    f"promote its literal verbatim or retain its defining turn."
                )
            if depth >= 2:
                raise OrphanedReferenceError(
                    f"Reference '{ref}' resolves only through summary depth {depth}; "
                    f"re-verify against a tool before use — paraphrased bindings are not bindings."
                )


def prune(wm: WorkingMemory, candidates: set[int], promote: set[str]) -> None:
    """Evict relevance-scored candidates, but refuse to orphan live references."""
    evict = set(candidates)
    # Retain any candidate that is the sole resolver of a live reference.
    live_refs = {r for t in wm.turns.values() for r in t.references}
    for tid in list(evict):
        sole = {r for r in wm.turns[tid].defines if r in live_refs and r not in promote}
        if sole:
            evict.discard(tid)
    wm.commit_eviction(evict, promote)
