# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-when-a-deterministic-replay-of-an-agent-trace-diverges-because-the-tool-sandbox-re-seeded-its-rng-between-the-original-run.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-when-a-deterministic-replay-of-an-agent-trace-diverges-because-the-tool-sandbox-re-seeded-its-rng-between-the-original-run.warrant.json
# Markdown SHA-256:   f8cb3e25c950b27a705777cc6feee60c9cf8ae8e488eb04b0259d07f692405b6
# Code AST SHA-256:   d6caec97da57c06b0bd58242bbb868c8af922833bb1c0f501de472e9415faed7
# Verified Classes:   ReplayVerdictError, Verdict, ToolCall
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
import json
from dataclasses import dataclass
from enum import Enum
from typing import Any


class ReplayVerdictError(RuntimeError):
    """Raised when a replay verdict cannot be soundly produced."""


class Verdict(Enum):
    CLEAN = "clean"
    SEED_GAP = "seed_gap"
    DIVERGENT_AT = "divergent_at"
    TAMPER_SUSPECTED = "tamper_suspected"


@dataclass(frozen=True)
class ToolCall:
    step: int
    tool: str
    args: dict[str, Any]
    output: Any
    # Entropy/clock state captured at call entry. None means "not recorded".
    entropy_seed: bytes | None
    clock_ns: int | None
    # Steps whose outputs were consumed as args here (provenance).
    consumed_from: tuple[int, ...]


def _arg_hash(args: dict[str, Any]) -> str:
    return hashlib.sha256(
        json.dumps(args, sort_keys=True, default=str).encode()
    ).hexdigest()


def replay_verdict(
    recorded: list[ToolCall],
    replayed: list[ToolCall],
) -> tuple[Verdict, int | None, str]:
    """
    Returns (verdict, originating_step_or_None, detail).

    Invariants enforced:
      - Every recorded call must have entropy_seed and clock_ns.
        Missing seed => SEED_GAP, never TAMPER_SUSPECTED.
      - Divergence is attributed to the EARLIEST step whose recorded
        output was consumed downstream, not to the step where the
        diff first fires.
    """
    if len(recorded) != len(replayed):
        raise ReplayVerdictError(
            f"trace length mismatch: recorded={len(recorded)} "
            f"replayed={len(replayed)}"
        )

    # 1. Seed closure check first. A missing seed invalidates the
    #    entire replay for evidentiary purposes.
    missing = [
        c.step for c in recorded
        if c.entropy_seed is None or c.clock_ns is None
    ]
    if missing:
        return (
            Verdict.SEED_GAP,
            None,
            f"entropy/clock seed missing at steps {missing}; "
            f"replay is inconclusive",
        )

    # 2. Build first-consumption map: for each step, the earliest
    #    step whose output reached it.
    first_consumer: dict[int, int] = {}
    for c in recorded:
        for src in c.consumed_from:
            first_consumer.setdefault(src, c.step)

    # 3. Compare argument hashes. Attribute divergence to the
    #    earliest consumed-from step, not to the current step.
    for r, p in zip(recorded, replayed):
        if _arg_hash(r.args) != _arg_hash(p.args):
            origin = first_consumer.get(r.step, r.step)
            # If the divergent step itself has no recorded
            # nondeterministic primitive and its origin is itself,
            # this is a genuine unexplained divergence.
            if origin == r.step and r.entropy_seed is None:
                raise ReplayVerdictError(
                    f"step {r.step}: divergence with no recorded seed "
                    f"and no upstream consumer; cannot classify"
                )
            return (
                Verdict.DIVERGENT_AT,
                origin,
                f"argument hash mismatch at step {r.step} "
                f"originates at step {origin}",
            )

    # 4. Outputs that were never consumed as args must still match
    #    if they are terminal (final answer to user).
    for r, p in zip(recorded, replayed):
        if r.step not in first_consumer and r.output != p.output:
            return (
                Verdict.TAMPER_SUSPECTED,
                r.step,
                f"terminal output mismatch at step {r.step} "
                f"with seed present and no upstream consumer",
            )

    return (Verdict.CLEAN, None, "all seeds present, all hashes match")


def assert_clean_or_raise(recorded: list[ToolCall], replayed: list[ToolCall]) -> None:
    verdict, step, detail = replay_verdict(recorded, replayed)
    if verdict is not Verdict.CLEAN:
        raise ReplayVerdictError(
            f"replay not evidentiary: verdict={verdict.value} "
            f"step={step} detail={detail}"
        )
