# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-score-a-litmus-adversarial-trajectory-because-the-harness-s-own-tool-call-replay-diverged-from-the-recorded-transcript.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-score-a-litmus-adversarial-trajectory-because-the-harness-s-own-tool-call-replay-diverged-from-the-recorded-transcript.warrant.json
# Markdown SHA-256:   1092381e138e975d7d36d0a18f413b01b340525371cdceb842549a3e5d6c6ce8
# Code AST SHA-256:   3b3c85af42aa634ad368200bddded148a20652de36d5f22178ea7c28d8efe0c7
# Verified Classes:   ReplayDivergenceError, RecordedStep
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Any


class ReplayDivergenceError(RuntimeError):
    """Raised when a replayed tool result diverges from the recorded transcript
    in a way that invalidates scoring for the entire trajectory."""
    pass


@dataclass(frozen=True)
class RecordedStep:
    tool_name: str
    args_hash: str
    result_hash: str          # commitment over the FULL payload, not a prefix
    result_payload: dict[str, Any]


# Tool schema declares which fields are legitimately volatile.
VOLATILE_FIELDS: dict[str, set[str]] = {
    "http_fetch": {"timestamp", "etag", "request_id"},
    "read_file": {"mtime", "cursor"},
    "search":    {"cursor", "query_id"},
}


def _commit(payload: dict[str, Any], volatile: set[str]) -> str:
    canonical = {k: v for k, v in sorted(payload.items()) if k not in volatile}
    return hashlib.sha256(repr(canonical).encode()).hexdigest()


def score_trajectory(steps: list[RecordedStep], replay_fn, baseline_delta_fn) -> float:
    """Score a LITMUS trajectory only if every replayed step matches under the
    committed equivalence relation. Any contaminating divergence aborts scoring."""
    for idx, step in enumerate(steps):
        volatile = VOLATILE_FIELDS.get(step.tool_name)
        if volatile is None:
            # No declared volatile set -> every divergence is contaminating.
            volatile = set()

        replay_payload = replay_fn(step.tool_name, step.args_hash)
        replay_hash = _commit(replay_payload, volatile)

        if replay_hash != step.result_hash:
            # Full-payload commitment mismatch: the agent's observation at this
            # step is no longer the observation in the transcript. The score
            # for this trajectory is undefined. Quarantine, do not score.
            raise ReplayDivergenceError(
                f"contaminating replay divergence at step {idx} "
                f"tool={step.tool_name!r} recorded={step.result_hash[:12]} "
                f"replay={replay_hash[:12]} — trajectory quarantined, score=⊥"
            )

    return baseline_delta_fn(steps)
