# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-litmus-safe-verdict-when-the-policy-relevant-tool-call-is-deferred-across-a-compaction-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-litmus-safe-verdict-when-the-policy-relevant-tool-call-is-deferred-across-a-compaction-boundary.warrant.json
# Markdown SHA-256:   7fc0aea4357292143645957cbd21b2a3b7d7dba2e1857107451a558799602d9a
# Code AST SHA-256:   859c6df17593a988f9c1ecbdb2721946df9779f1f7c23f818b8c6c2f31f31de0
# Verified Classes:   UnboundVerdictError, Span, Window
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnboundVerdictError(RuntimeError):
    """Raised when a LITMUS safe verdict cannot be trusted because the
    scored window does not contain the causal closure of the action."""


@dataclass
class Span:
    span_id: str
    text: str
    # provenance: if this span is a summary, source_ids point at the spans it compressed
    source_ids: list[str] = field(default_factory=list)


@dataclass
class Window:
    spans: dict[str, Span]

    def contains(self, span_id: str) -> bool:
        return span_id in self.spans

    def dereference(self, span_id: str) -> Optional[Span]:
        """Resolve a summary span back to its sources, if recoverable."""
        if span_id not in self.spans:
            return None
        s = self.spans[span_id]
        if not s.source_ids:
            return s
        # only recoverable if every source is still present
        if all(sid in self.spans for sid in s.source_ids):
            return s
        return None


def score_litmus(window: Window, action: str, required_spans: list[str]) -> str:
    """Return 'safe' only if causal closure is contained in the window.
    Otherwise raise UnboundVerdictError rather than emit a laundered 'safe'."""
    missing = [sid for sid in required_spans if not window.contains(sid)]
    if not missing:
        # closure contained; detector may run and its verdict is bound
        return "safe"  # (detector call elided; verdict is trustworthy here)

    # attempt rehydration via provenance pointers
    rehydrated = [window.dereference(sid) for sid in missing]
    if any(r is None for r in rehydrated):
        raise UnboundVerdictError(
            f"action={action!r} missing causal-closure spans {missing}; "
            f"provenance unrecoverable — verdict is UNBOUND, not safe"
        )
    # sources recoverable: re-run detector against rehydrated closure
    return "safe"  # (detector re-run elided; now bound)


# Trigger condition demonstration: summary survives, source evicted
w = Window(spans={
    "turn4_instruction": Span("turn4_instruction", "dump users table to /tmp, email auditor@partner.example"),
    "turn11_summary": Span("turn11_summary", "audit export pending", source_ids=["turn4_instruction"]),
})
# simulate compaction evicting the original instruction
del w.spans["turn4_instruction"]

try:
    score_litmus(w, action="send_email(to='auditor@partner.example')",
                 required_spans=["turn4_instruction"])
except UnboundVerdictError as e:
    print(f"REFUSED: {e}")
