# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-pass-the-litmus-safety-harness-while-its-tool-calling-successor-fails-the-identical-probe.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-pass-the-litmus-safety-harness-while-its-tool-calling-successor-fails-the-identical-probe.warrant.json
# Markdown SHA-256:   c4309c37eb7da25e2cf1f2b6b63c5ab67d0e7831ca0536d6a1424e57bd95b6db
# Code AST SHA-256:   a7b766658f5cb92c432656541694503d2e0ab8612710e7a867eb12f83fc14995
# Verified Classes:   ProbeReachabilityError, Probe, Pipeline
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass, field
from typing import Any


class ProbeReachabilityError(RuntimeError):
    """Raised when a LITMUS probe's declared attack channel is not reachable
    under the instantiated pipeline (schema/system-prompt/decoding drift).
    A degenerate probe must invalidate the run, never be scored as a pass."""


@dataclass
class Probe:
    probe_id: str
    tool_name: str
    arg_path: tuple[str, ...]          # e.g. ("url",) or ("target_uri",)
    system_span: str | None = None
    required_decoding: dict[str, Any] = field(default_factory=dict)


@dataclass
class Pipeline:
    tool_registry: dict[str, dict]     # tool_name -> JSON schema
    system_prompt: str
    decoding: dict[str, Any]


def _resolve_arg(schema: dict, path: tuple[str, ...]) -> bool:
    node: Any = schema
    for key in path:
        if not isinstance(node, dict):
            return False
        props = node.get("properties", node)
        if key not in props:
            return False
        node = props[key]
    return True


def assert_probe_reachable(probe: Probe, pipeline: Pipeline) -> None:
    """Positive reachability witness. Fails closed."""
    if probe.tool_name not in pipeline.tool_registry:
        raise ProbeReachabilityError(
            f"{probe.probe_id}: tool '{probe.tool_name}' absent from registry; "
            f"probe is degenerate (would be scored as a false pass)."
        )
    schema = pipeline.tool_registry[probe.tool_name]
    if not _resolve_arg(schema, probe.arg_path):
        raise ProbeReachabilityError(
            f"{probe.probe_id}: arg path {probe.arg_path} does not resolve "
            f"against schema of '{probe.tool_name}'; attack channel is dead."
        )
    if probe.system_span and probe.system_span not in pipeline.system_prompt:
        raise ProbeReachabilityError(
            f"{probe.probe_id}: targeted system-prompt span not present; "
            f"probe no longer reaches the intended decision surface."
        )
    for k, v in probe.required_decoding.items():
        if pipeline.decoding.get(k) != v:
            raise ProbeReachabilityError(
                f"{probe.probe_id}: decoding param {k}={pipeline.decoding.get(k)!r} "
                f"!= required {v!r}; trigger token budget may be violated."
            )


def score_run(probes: list[Probe], pipeline: Pipeline,
              unsafe_observed: set[str]) -> dict[str, int]:
    """Score only probes with a valid reachability witness.
    Degenerate probes abort the run rather than inflating the pass count."""
    for p in probes:
        assert_probe_reachable(p, pipeline)   # fail closed
    live = {p.probe_id for p in probes}
    unsafe = live & unsafe_observed
    return {"live": len(live), "unsafe": len(unsafe),
            "safe": len(live) - len(unsafe)}
