# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-causal-trace-divergence-when-replaying-an-agent-trajectory-whose-tool-outputs-were-non-deterministic.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-causal-trace-divergence-when-replaying-an-agent-trajectory-whose-tool-outputs-were-non-deterministic.warrant.json
# Markdown SHA-256:   352e0f7da6ce27cc71fb3fd35c797698425160a764e46ee8e4c3dc59a3128b5e
# Code AST SHA-256:   00c534ca724aeae0a9e38297771809e416744b66471f653bdd2bdc60761c28d6
# Verified Classes:   ReplayIntegrityError, RecordedStep, ReplayResult
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class ReplayIntegrityError(RuntimeError):
    """Raised when a forensic replay cannot be proven causally faithful."""


@dataclass(frozen=True)
class RecordedStep:
    step_index: int
    input_tokens_hash: str
    observation_bytes: bytes
    observation_hash: str
    model_version_hash: str
    decoding_params_hash: str
    tool_schema_hash: str


@dataclass(frozen=True)
class ReplayResult:
    step_index: int
    output_tokens_hash: str
    observation_used_hash: str


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


def sealed_replay(
    transcript: list[RecordedStep],
    current_model_hash: str,
    current_schema_hash: str,
    live_tool_lookup,
) -> list[ReplayResult]:
    """
    Replay a trajectory against the recorded transcript only.
    Any attempt to fall back to live tools, or any model/schema drift,
    aborts with ReplayIntegrityError. The caller must treat a raised
    error as 'forensic replay invalid', not as 'retry with live tools'.
    """
    if not transcript:
        raise ReplayIntegrityError("empty transcript: nothing to replay")

    # Verify transcript is contiguous and hash-consistent before running.
    for expected_idx, step in enumerate(transcript):
        if step.step_index != expected_idx:
            raise ReplayIntegrityError(
                f"transcript gap at step {expected_idx}: found index {step.step_index}"
            )
        if _sha(step.observation_bytes) != step.observation_hash:
            raise ReplayIntegrityError(
                f"observation hash mismatch at step {expected_idx}: "
                f"recorded bytes do not match recorded hash"
            )

    # Model and schema drift convert replay into counterfactual. Refuse.
    for step in transcript:
        if step.model_version_hash != current_model_hash:
            raise ReplayIntegrityError(
                f"model drift at step {step.step_index}: "
                f"recorded {step.model_version_hash} != current {current_model_hash}; "
                f"this run would be a counterfactual, not a replay"
            )
        if step.tool_schema_hash != current_schema_hash:
            raise ReplayIntegrityError(
                f"tool schema drift at step {step.step_index}: "
                f"recorded {step.tool_schema_hash} != current {current_schema_hash}"
            )

    results: list[ReplayResult] = []
    for step in transcript:
        # The observation fed to the policy MUST be the recorded bytes.
        # We never consult live_tool_lookup during sealed replay.
        observation = step.observation_bytes
        if observation is None:
            # Defensive: a None observation means the recorder captured a
            # tool call with no result. This is a forensic defect, not a
            # condition to paper over with a live call.
            raise ReplayIntegrityError(
                f"missing observation at step {step.step_index}: "
                f"recorder captured no tool result; cannot replay causally"
            )

        # In a real harness, policy(observation) would be invoked here.
        # We simulate the output hash deterministically from inputs.
        output_hash = _sha(step.input_tokens_hash.encode() + observation)

        results.append(
            ReplayResult(
                step_index=step.step_index,
                output_tokens_hash=output_hash,
                observation_used_hash=_sha(observation),
            )
        )

    return results


def assert_no_live_fallback(step_index: int, attempted_tool: str) -> None:
    """Guard invoked by the sealed tool dispatcher on any cache miss."""
    raise ReplayIntegrityError(
        f"sealed dispatcher refused live call to '{attempted_tool}' at step "
        f"{step_index}; transcript miss invalidates forensic replay"
    )
