# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-replay-divergence-when-recorded-llm-i-o-is-bit-identical-but-the-agent-s-decision-path-is-not.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-replay-divergence-when-recorded-llm-i-o-is-bit-identical-but-the-agent-s-decision-path-is-not.warrant.json
# Markdown SHA-256:   ebee82a59684f2c15572af2e6a8320711947ce258d663fbca01a3bcc4e0a8449
# Code AST SHA-256:   2732bbebdf5f9b73ed1538907ebf1f7af250c5aab5a9737ce75be860dfb62f5e
# Verified Classes:   ReplayDivergenceError, WitnessStatus, Epoch, ReplayTrace
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum


class ReplayDivergenceError(RuntimeError):
    """Raised when a replay's decision path diverges from the recorded path
    despite byte-identical LLM I/O at the divergence epoch."""
    pass


class WitnessStatus(Enum):
    VERIFIED = "verified"
    INJECTED_UNVERIFIED = "injected_unverified"
    MISSING = "missing"


@dataclass
class Epoch:
    index: int
    context_hash: str
    tool_result_bytes: bytes
    environment_witness: WitnessStatus
    sampling_config_hash: str
    emitted_action: str


@dataclass
class ReplayTrace:
    epochs: list[Epoch] = field(default_factory=list)

    def epoch(self, i: int) -> Epoch:
        return self.epochs[i]


def _action_under_replay(epoch: Epoch, reexecuted_result: bytes | None) -> str:
    # Stand-in for the agent's decision function: if a snapshot-re-executed
    # tool result is supplied and differs from the recorded bytes, the
    # agent's context at this epoch is not the recorded context, so its
    # emitted action may differ. Real harnesses call the recorded model
    # response only when the context witness is intact.
    if reexecuted_result is not None and reexecuted_result != epoch.tool_result_bytes:
        return f"diverged:{hashlib.sha256(reexecuted_result).hexdigest()[:12]}"
    return epoch.emitted_action


def dual_replay_differential(trace: ReplayTrace, snapshot_results: dict[int, bytes]) -> list[int]:
    """Return epochs where injected-result replay and snapshot-re-executed
    replay produce different actions. Empty list means path-equivalent."""
    divergent: list[int] = []
    for ep in trace.epochs:
        injected_action = _action_under_replay(ep, None)
        reexec_action = _action_under_replay(ep, snapshot_results.get(ep.index))
        if injected_action != reexec_action:
            divergent.append(ep.index)
    return divergent


def assert_forensically_sound(trace: ReplayTrace, snapshot_results: dict[int, bytes]) -> None:
    divergent = dual_replay_differential(trace, snapshot_results)
    if divergent:
        first = divergent[0]
        ep = trace.epoch(first)
        raise ReplayDivergenceError(
            f"Path divergence at epoch {first}: injected tool result differs from "
            f"snapshot re-execution, and the agent's emitted action changed "
            f"({ep.emitted_action!r} -> diverged). I/O-faithful replay is NOT a "
            f"valid causal trace. Witness status at epoch: {ep.environment_witness.value}."
        )
    for ep in trace.epochs:
        if ep.environment_witness is not WitnessStatus.VERIFIED:
            raise ReplayDivergenceError(
                f"Epoch {ep.index} lacks a verified environment witness "
                f"({ep.environment_witness.value}); trace cannot be admitted as evidence."
            )
