# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-verify-a-litmus-safety-verdict-after-a-tool-schema-mutation-and-what-breaks-if-it-doesn-t.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-verify-a-litmus-safety-verdict-after-a-tool-schema-mutation-and-what-breaks-if-it-doesn-t.warrant.json
# Markdown SHA-256:   55a8ff5e00f77817749dd4dcd0722211dc504f2d558b97c6c5718f8a1350e15b
# Code AST SHA-256:   b2acbadae91923c339dde966ab615dd743618be288874edeb6285b52b1e6db76
# Verified Classes:   StaleVerdictError, Verdict, VerdictStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class StaleVerdictError(RuntimeError):
    """Raised when a LITMUS verdict is reused against a mutated tool schema."""
    pass


def schema_hash(tool_schema: dict[str, Any]) -> str:
    # Hash only the executable surface; prose edits must not invalidate.
    executable = {
        "name": tool_schema.get("name"),
        "params": {
            k: {
                "type": v.get("type"),
                "default": v.get("default"),
                "enum": sorted(v.get("enum", [])) if v.get("enum") else None,
                "required": v.get("required", False),
            }
            for k, v in tool_schema.get("params", {}).items()
        },
    }
    return hashlib.sha256(
        json.dumps(executable, sort_keys=True).encode()
    ).hexdigest()[:16]


@dataclass
class Verdict:
    probe_id: str
    tool_name: str
    schema_hash: str
    rubric_id: str
    label: str  # SAFE | UNSAFE


@dataclass
class VerdictStore:
    _by_triple: dict[tuple[str, str, str], Verdict] = field(default_factory=dict)

    def record(self, v: Verdict) -> None:
        self._by_triple[(v.tool_name, v.schema_hash, v.rubric_id)] = v

    def lookup(self, tool_name: str, current_hash: str, rubric_id: str) -> Verdict:
        key = (tool_name, current_hash, rubric_id)
        if key not in self._by_triple:
            raise StaleVerdictError(
                f"No verdict for {tool_name} under schema {current_hash} "
                f"rubric {rubric_id}; re-adjudicate before scoring."
            )
        return self._by_triple[key]


def adjudicate(
    store: VerdictStore,
    tool_schema: dict[str, Any],
    rubric_id: str,
    probe_id: str,
) -> Verdict:
    current = schema_hash(tool_schema)
    try:
        return store.lookup(tool_schema["name"], current, rubric_id)
    except StaleVerdictError:
        # Schema mutated (or never seen): must re-run the probe, not reuse.
        raise StaleVerdictError(
            f"Probe {probe_id} bound to stale schema for {tool_schema['name']}; "
            f"current hash {current}. Re-adjudication required."
        )


def emit_aggregate(store: VerdictStore, tool_schemas: list[dict[str, Any]],
                   rubric_id: str) -> float:
    safe = total = 0
    for schema in tool_schemas:
        h = schema_hash(schema)
        for (tname, shash, rid), v in store._by_triple.items():
            if tname == schema["name"] and rid == rubric_id:
                if shash != h:
                    raise StaleVerdictError(
                        f"Verdict {v.probe_id} references schema {shash} "
                        f"but current is {h}; refusing to emit aggregate."
                    )
                total += 1
                safe += int(v.label == "SAFE")
    return safe / total if total else 0.0
