# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-litmus-harness-verdict-when-the-adversarial-tool-call-corpus-and-the-agent-s-own-tool-schema-diverge-at.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-litmus-harness-verdict-when-the-adversarial-tool-call-corpus-and-the-agent-s-own-tool-schema-diverge-at.warrant.json
# Markdown SHA-256:   3d866c242a1da68f8586007241494340871640e689bb9c2d8e3d421d6eaf0fdb
# Code AST SHA-256:   9be6adaf7798c35008037bc00f49931846167762a731a62f29ad49a1b1669305
# Verified Classes:   EncodingDivergenceError, Payload
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Any, Callable


class EncodingDivergenceError(RuntimeError):
    """Raised when a harness payload and its native re-encoding resolve to
    different semantic arguments, or the agent's decision differs between them.
    A harness verdict produced under this condition is not valid evidence."""


@dataclass(frozen=True)
class Payload:
    tool: str
    raw: dict[str, Any]


def semantic_decode(payload: Payload, decoder: Callable[[dict], dict]) -> dict:
    # Canonical semantic argument object: types coerced, paths resolved,
    # unicode NFKC-folded, nesting preserved. This is the ONLY representation
    # the safety policy is allowed to inspect.
    return decoder(payload.raw)


def differential_replay(
    harness_payload: Payload,
    native_payload: Payload,
    decoder: Callable[[dict], dict],
    decide: Callable[[str, dict], str],
    schema_hash: str,
    pinned_schema_hash: str,
) -> bool:
    if schema_hash != pinned_schema_hash:
        raise EncodingDivergenceError(
            f"harness schema {schema_hash[:8]} != deployed {pinned_schema_hash[:8]}; "
            "verdict cannot be attributed to the native tool surface"
        )

    h_sem = semantic_decode(harness_payload, decoder)
    n_sem = semantic_decode(native_payload, decoder)

    if h_sem != n_sem:
        raise EncodingDivergenceError(
            f"tool={harness_payload.tool} harness decode {h_sem!r} != native decode {n_sem!r}; "
            "harness emits a shape the orchestrator never produces"
        )

    h_decision = decide(harness_payload.tool, h_sem)
    n_decision = decide(native_payload.tool, n_sem)

    if h_decision != n_decision:
        raise EncodingDivergenceError(
            f"tool={harness_payload.tool} decision divergence: "
            f"harness={h_decision} native={n_decision}; "
            "safety policy is encoding-dependent (check-then-normalize ordering)"
        )
    return True


def attest_safety_rate(
    corpus: list[tuple[Payload, Payload]],
    decoder: Callable[[dict], dict],
    decide: Callable[[str, dict], str],
    schema_hash: str,
    pinned_schema_hash: str,
    mismatch_tolerance: float = 0.0,
) -> dict[str, float]:
    mismatches = 0
    for h, n in corpus:
        try:
            differential_replay(h, n, decoder, decide, schema_hash, pinned_schema_hash)
        except EncodingDivergenceError:
            mismatches += 1

    rate = mismatches / max(len(corpus), 1)
    if rate > mismatch_tolerance:
        raise EncodingDivergenceError(
            f"{mismatches}/{len(corpus)} payloads ({rate:.1%}) diverge between harness "
            "and native encoding; refusing to emit a safety rate that would be "
            "inherited as a false-negative by downstream deployment gates"
        )
    return {"encoding_corrected_mismatch_rate": rate, "n": len(corpus)}
