# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-pass-litmus-replay-while-the-live-red-team-run-fails-scenario-rng-re-seeding-divergence-under-harness-side-kernel-entropy.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-pass-litmus-replay-while-the-live-red-team-run-fails-scenario-rng-re-seeding-divergence-under-harness-side-kernel-entropy.warrant.json
# Markdown SHA-256:   9c6a209e83fec82b9754835d3966f4df35cc4c2a428aa588eea8f577095742db
# Code AST SHA-256:   597646d7be24f84531440aace492e34e2d63202a5eef9fd4413ac5a2d02c962d
# Verified Classes:   ScenarioDriftError, DrawKey
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import random
from dataclasses import dataclass


class ScenarioDriftError(RuntimeError):
    """Raised when a LITMUS replay trajectory diverges from the recorded trajectory."""


@dataclass(frozen=True)
class DrawKey:
    scenario_id: str
    step_index: int
    tool_call_site: str
    draw_ordinal: int


def keyed_draw(key: DrawKey, modulus: int) -> int:
    """Derive a stochastic draw from a stable structural key, not stream position."""
    material = f"{key.scenario_id}|{key.step_index}|{key.tool_call_site}|{key.draw_ordinal}"
    digest = hashlib.sha256(material.encode("utf-8")).digest()
    return int.from_bytes(digest[:8], "big") % modulus


def replay_step(recorded: dict, key: DrawKey, modulus: int) -> int:
    """Replay one stochastic draw and assert it matches the recorded value."""
    observed = keyed_draw(key, modulus)
    expected = recorded.get((key.scenario_id, key.step_index, key.tool_call_site, key.draw_ordinal))
    if expected is None:
        raise ScenarioDriftError(
            f"no recorded draw for key {key}; manifest does not bind this site"
        )
    if observed != expected:
        raise ScenarioDriftError(
            f"scenario drift at {key}: recorded={expected} replayed={observed}"
        )
    return observed


def replay_trajectory(manifest: dict, agent_trajectory: list) -> str:
    """Validate a full trajectory against the manifest; refuse verdicts on drift."""
    recorded_len = manifest["trajectory_length"]
    if len(agent_trajectory) != recorded_len:
        raise ScenarioDriftError(
            f"trajectory length mismatch: recorded={recorded_len} replayed={len(agent_trajectory)}"
        )
    for step in agent_trajectory:
        key = DrawKey(
            scenario_id=manifest["scenario_id"],
            step_index=step["step_index"],
            tool_call_site=step["tool_name"],
            draw_ordinal=step["draw_ordinal"],
        )
        replay_step(manifest["draws"], key, modulus=step["modulus"])
    return "REPRODUCED"
