# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-poisoned-speculative-prefetch-when-the-litmus-risk-score-validates-against-the-wrong-tool-call-snapshot.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-poisoned-speculative-prefetch-when-the-litmus-risk-score-validates-against-the-wrong-tool-call-snapshot.warrant.json
# Markdown SHA-256:   82b37bb46555692b885c81f035362511e87122ecaae1cf1d2c84641df079f91c
# Code AST SHA-256:   f9af447b3caec3f2c32e3095e05466c5ef2a2082ca5da633595ee452924ac439
# Verified Classes:   ScoreSubjectMismatch, ScoredCall
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ScoreSubjectMismatch(RuntimeError):
    """Raised when a cached risk score was computed over a different call
    than the one about to be committed. The score is void, not stale."""
    pass


@dataclass(frozen=True)
class ScoredCall:
    spec_id: str
    arg_hash: str
    risk_score: float


def canonical_arg_hash(tool_name: str, args: dict) -> str:
    # Full-tuple fingerprint: every revisable field is inside the hash.
    payload = json.dumps({"tool": tool_name, "args": args},
                         sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


def commit_with_gate(scored: ScoredCall,
                     tool_name: str,
                     committed_args: dict,
                     gate_threshold: float,
                     rescore_fn) -> dict:
    committed_hash = canonical_arg_hash(tool_name, committed_args)

    if committed_hash != scored.arg_hash:
        # Subject mismatch: the cached score is about a different call.
        # Do NOT reuse it, do NOT apply a penalty. Re-score the real call.
        rescored = rescore_fn(tool_name, committed_args)
        if rescored is None:
            raise ScoreSubjectMismatch(
                f"spec {scored.spec_id}: args revised (scored={scored.arg_hash[:12]} "
                f"committed={committed_hash[:12]}) and re-score unavailable; "
                f"refusing to commit on void score"
            )
        if rescored >= gate_threshold:
            raise ScoreSubjectMismatch(
                f"spec {scored.spec_id}: revised call re-scored at {rescored:.2f} "
                f">= gate {gate_threshold:.2f}; blocking commit"
            )
        return {"committed": True, "score": rescored, "path": "rescored"}

    if scored.risk_score >= gate_threshold:
        raise ScoreSubjectMismatch(
            f"spec {scored.spec_id}: prefetch score {scored.risk_score:.2f} "
            f">= gate {gate_threshold:.2f}; blocking commit"
        )
    return {"committed": True, "score": scored.risk_score, "path": "cached"}
