# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-model-driven-context-pruning-has-silently-orphaned-a-live-causal-dependency.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-model-driven-context-pruning-has-silently-orphaned-a-live-causal-dependency.warrant.json
# Markdown SHA-256:   54a7818457ba2eb0875f7a9c9217a844ea2f31bd8bd3f1e847ec361190c0571f
# Code AST SHA-256:   e33f8369ed6d166e29439d8890332452cdc1ce281f24991d6ae23aa0e3709517
# Verified Classes:   OrphanedCausalDependency, Decision, ContextWindow
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class OrphanedCausalDependency(RuntimeError):
    """Raised when a live decision's justifying segment was evicted by relevance pruning."""
    pass


@dataclass
class Decision:
    decision_id: str
    action: str
    justification_ref: Optional[str]   # handle into durable justification store
    status: str = "live"               # live | closed


@dataclass
class ContextWindow:
    segments: dict = field(default_factory=dict)          # seg_id -> text
    justification_store: dict = field(default_factory=dict)  # ref -> full reason
    decisions: dict = field(default_factory=dict)         # id -> Decision

    def evict_by_relevance(self, scores: dict, threshold: float) -> list:
        """Relevance-ranked eviction with a reachability veto.

        A segment may be evicted only if no LIVE decision's justification
        depends on it, OR its justification has been externalized to the
        durable store (in which case the segment is replaced by a handle).
        """
        # Build the set of segments pinned by live decisions.
        pinned = set()
        for d in self.decisions.values():
            if d.status == "live" and d.justification_ref is not None:
                # pinned only if the justification is NOT already externalized
                if d.justification_ref not in self.justification_store:
                    pinned.add(d.justification_ref)

        evicted = []
        for seg_id, score in scores.items():
            if score >= threshold:
                continue
            if seg_id in pinned:
                # Veto: externalize the justification, then evict is allowed.
                self.justification_store[seg_id] = self.segments[seg_id]
                for d in self.decisions.values():
                    if d.justification_ref == seg_id:
                        d.justification_ref = seg_id  # now resolves via store
                # segment itself may now be dropped; handle remains
                del self.segments[seg_id]
                evicted.append(seg_id)
                continue
            if seg_id in self.segments:
                del self.segments[seg_id]
                evicted.append(seg_id)
        return evicted

    def audit_reachability(self) -> None:
        """Post-prune hard check: every live decision's justification must resolve."""
        for d in self.decisions.values():
            if d.status != "live":
                continue
            ref = d.justification_ref
            if ref is None:
                continue
            resolves = (ref in self.segments) or (ref in self.justification_store)
            if not resolves:
                raise OrphanedCausalDependency(
                    f"Decision {d.decision_id!r} ({d.action!r}) is live but its "
                    f"justification {ref!r} was pruned and never externalized. "
                    f"Re-materialize the reason before executing or revising this decision."
                )


def step_30_backfill(window: ContextWindow) -> None:
    """Agent reaches the deferred decision; must resolve its justification first."""
    for d in window.decisions.values():
        if d.action == "defer_backfill" and d.status == "live":
            ref = d.justification_ref
            if ref is not None and ref not in window.segments and ref not in window.justification_store:
                raise OrphanedCausalDependency(
                    f"Cannot safely execute backfill: reason for deferral {ref!r} "
                    f"was evicted. Refusing to proceed without the original constraint."
                )
    # safe to proceed only if justification resolved
