# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-trajectory-through-a-nondeterministic-tool-boundary-and-silently-reconstructs-a-divergent-past.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-trajectory-through-a-nondeterministic-tool-boundary-and-silently-reconstructs-a-divergent-past.warrant.json
# Markdown SHA-256:   8a529eb91667026b1ba4ca85360974bab7e93138596cca409797c7e5fcf13fdf
# Code AST SHA-256:   013c5b57ec7224b037f3bfc53b16628074d53b1d397916a24185d72ba2b07842
# Verified Classes:   ReplayDivergenceError, TapeGapError, TapeEntry, TapeReader
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any, Optional


class ReplayDivergenceError(RuntimeError):
    """Raised when a replayed agent decision does not match the recorded decision."""


class TapeGapError(RuntimeError):
    """Raised when the tape lacks an observation required to continue replay."""


@dataclass(frozen=True)
class TapeEntry:
    step_index: int
    decision: str          # canonical serialized action, e.g. '{"tool":"search","args":{...}}'
    observation_bytes: bytes
    observation_hash: str  # sha256 of observation_bytes


def _canonical(action: Any) -> str:
    return json.dumps(action, sort_keys=True, separators=(",", ":"))


def _hash(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()


class TapeReader:
    """Serves recorded observations. Never invokes a live tool. Never falls through."""

    def __init__(self, entries: list[TapeEntry]):
        self._by_step = {e.step_index: e for e in entries}

    def serve(self, step_index: int) -> TapeEntry:
        entry = self._by_step.get(step_index)
        if entry is None:
            raise TapeGapError(
                f"tape has no observation for step {step_index}; "
                f"record-time instrumentation was incomplete"
            )
        if _hash(entry.observation_bytes) != entry.observation_hash:
            raise TapeGapError(
                f"tape entry {step_index} failed integrity check; "
                f"observation bytes do not match recorded hash"
            )
        return entry


def replay_step(
    tape: TapeReader,
    step_index: int,
    recorded_decision: Any,
    agent_emitted_decision: Any,
) -> bytes:
    """
    Pre-dispatch decision gate. Must be called BEFORE the agent's action is
    dispatched anywhere. Raises on divergence or tape gap; never continues.
    """
    expected = _canonical(recorded_decision)
    actual = _canonical(agent_emitted_decision)

    if actual != expected:
        # Divergence: the agent, fed the tape up to step_index-1, chose
        # differently than it chose at record time. The replay is no longer
        # a replay of the recorded run.
        raise ReplayDivergenceError(
            f"divergence at step {step_index}: "
            f"recorded={expected!r} replayed={actual!r}; "
            f"trajectory is not reproducible from its tape"
        )

    entry = tape.serve(step_index)
    return entry.observation_bytes


def run_replay(tape_entries: list[TapeEntry], agent_fn) -> list[bytes]:
    """
    agent_fn(step_index, prior_observations) -> emitted_decision
    The agent is driven by tape observations only; tools are never live.
    """
    tape = TapeReader(tape_entries)
    observations: list[bytes] = []
    for entry in sorted(tape_entries, key=lambda e: e.step_index):
        emitted = agent_fn(entry.step_index, observations)
        obs = replay_step(tape, entry.step_index, entry.decision, emitted)
        observations.append(obs)
    return observations
