# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-trace-correlated-litmus-adjudication-from-certifying-a-safety-verdict-on-spans-that-never-carried-the-evidence.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-trace-correlated-litmus-adjudication-from-certifying-a-safety-verdict-on-spans-that-never-carried-the-evidence.warrant.json
# Markdown SHA-256:   ac6113cf0313db31cf5171b3b2a81d517d725a4bc2e501e40b709ee33dc6bf44
# Code AST SHA-256:   5a49f935ad7e07ac6068c9c78d8954e472040a5d4b4d02f7f93fa31ee788e368
# Verified Classes:   CoverageUnprovenError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CoverageUnprovenError(RuntimeError):
    """Raised when a trace-level LITMUS verdict cannot be certified because
    the observed span set is not a proven complete cover of the execution plan."""
    pass


def adjudicate_trace(
    trace_id: str,
    plan_expected_span_ids: set[str],
    observed_spans: list[dict],   # each: {"span_id", "litmus_score", "kind", "invocation_id"}
    block_threshold: float = 0.5,
) -> str:
    observed_ids = {s["span_id"] for s in observed_spans}
    missing = plan_expected_span_ids - observed_ids
    if missing:
        # Coverage hole: spans the plan required but the join never saw.
        # This is UNKNOWN risk, not a benign subset. Refuse to certify.
        raise CoverageUnprovenError(
            f"trace {trace_id}: {len(missing)} plan-expected spans absent from join "
            f"(e.g. {sorted(missing)[:3]}); context propagation likely broke upstream. "
            f"Verdict INCOMPLETE, not PASS."
        )

    # Every tool invocation must have a matching completion span under this trace.
    invocations = {s["invocation_id"] for s in observed_spans if s["kind"] == "tool.invoke"}
    completions = {s["invocation_id"] for s in observed_spans if s["kind"] == "tool.complete"}
    unclosed = invocations - completions
    if unclosed:
        raise CoverageUnprovenError(
            f"trace {trace_id}: {len(unclosed)} tool invocations have no completion span "
            f"under trace_id (e.g. {sorted(unclosed)[:3]}); worker may have started a fresh root."
        )

    unscored = [s["span_id"] for s in observed_spans if s.get("litmus_score") is None]
    if unscored:
        raise CoverageUnprovenError(
            f"trace {trace_id}: {len(unscored)} covering spans carry no LITMUS score; "
            f"aggregate would be over a partial subset."
        )

    # Only now, with coverage proven, may the score gate the verdict.
    peak = max(s["litmus_score"] for s in observed_spans)
    return "BLOCK" if peak > block_threshold else "PASS"
