# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-pass-a-litmus-adversarial-probe-under-replay-but-fail-the-same-probe-under-first-run-conditions.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-pass-a-litmus-adversarial-probe-under-replay-but-fail-the-same-probe-under-first-run-conditions.warrant.json
# Markdown SHA-256:   a712128200e0c18d217382fe8dc90577740a1fbac9a857e8b15c4168166704ec
# Code AST SHA-256:   86498b4b2c4f5eedde7595dd1fc6d18b3fd4424e179487ff53f542f699bdfae5
# Verified Classes:   ReplayFidelityError, Trajectory, Probe
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class ReplayFidelityError(RuntimeError):
    """Raised when a LITMUS replay artifact cannot faithfully reproduce
    the oracle's input domain from the first-run trajectory."""


@dataclass
class Trajectory:
    reasoning_blocks: list[str]
    tool_calls: list[dict[str, Any]]          # ordered, incl. unconsumed calls
    tool_results: dict[str, dict[str, Any]]   # args_hash -> {bytes, content_hash}
    seed: int | None


@dataclass
class Probe:
    probe_id: str
    oracle_fields: set[str]                   # fields the oracle dereferences
    first_run: Trajectory
    replay: Trajectory | None = None


def _content_hash(payload: bytes) -> str:
    return hashlib.sha256(payload).hexdigest()


def assert_replay_fidelity(probe: Probe) -> None:
    """Fail closed if the replay artifact is a lossy projection of first-run.

    Returns normally only when the replay is a faithful superset of the
    state the injection can influence. Never returns PASS on a partial cache.
    """
    if probe.replay is None:
        raise ReplayFidelityError(
            f"{probe.probe_id}: no replay artifact; refusing to gate on first-run only"
        )

    replay = probe.replay
    first = probe.first_run

    # 1. Oracle-field completeness: every field the oracle reads must be present.
    available = set()
    if replay.reasoning_blocks:
        available.add("reasoning_blocks")
    if replay.tool_calls:
        available.add("tool_calls")
    if replay.tool_results:
        available.add("tool_results")
    if replay.seed is not None:
        available.add("seed")

    missing = probe.oracle_fields - available
    if missing:
        raise ReplayFidelityError(
            f"{probe.probe_id}: replay omits oracle-relevant fields {sorted(missing)}; "
            f"verdict would be computed on a lossy projection -> UNREPLAYABLE, not PASS"
        )

    # 2. Tool-call completeness: replay must retain unconsumed calls.
    if len(replay.tool_calls) != len(first.tool_calls):
        raise ReplayFidelityError(
            f"{probe.probe_id}: replay dropped tool calls "
            f"({len(replay.tool_calls)} vs {len(first.tool_calls)}); "
            f"side-effect calls may be hidden from the oracle"
        )

    # 3. Cache fidelity: every cached result must match its recorded hash,
    #    and no first-run result may be absent from the cache.
    for args_hash, recorded in first.tool_results.items():
        cached = replay.tool_results.get(args_hash)
        if cached is None:
            raise ReplayFidelityError(
                f"{probe.probe_id}: replay cache missing tool result {args_hash!r}; "
                f"re-fetch would reintroduce staleness"
            )
        if _content_hash(cached["bytes"]) != recorded["content_hash"]:
            raise ReplayFidelityError(
                f"{probe.probe_id}: cache staleness on {args_hash!r}; "
                f"recorded hash {recorded['content_hash'][:12]} != "
                f"cached {_content_hash(cached['bytes'])[:12]}"
            )

    # 4. Seed presence: without it, a re-sampling replay is not a replay.
    if replay.seed != first.seed:
        raise ReplayFidelityError(
            f"{probe.probe_id}: seed drift {first.seed} -> {replay.seed}; "
            f"replay re-sampled rather than reproduced"
        )


def gate(probes: list[Probe]) -> dict[str, str]:
    """Regression gate: fail closed. UNREPLAYABLE is never reconciled to PASS."""
    verdicts: dict[str, str] = {}
    for probe in probes:
        try:
            assert_replay_fidelity(probe)
        except ReplayFidelityError as exc:
            verdicts[probe.probe_id] = f"UNREPLAYABLE: {exc}"
            continue
        verdicts[probe.probe_id] = "REPLAYABLE"
    return verdicts
