# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-replaying-a-multi-agent-trace-diverge-from-the-original-execution-when-tool-side-effects-are-non-idempotent.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-replaying-a-multi-agent-trace-diverge-from-the-original-execution-when-tool-side-effects-are-non-idempotent.warrant.json
# Markdown SHA-256:   713bb075e7c2e7ab9f2547ced956d7315ba4b6f18791cc99a641abe16f667b37
# Code AST SHA-256:   9c4144e47c8986cf221949e418f333f07f23b04db46d35b460fc185cd2445fa1
# Verified Classes:   ReplayContaminationError, ToolClass, TraceStep
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class ReplayContaminationError(RuntimeError):
    """Raised when a replay attempts to re-execute a tool whose response
    envelope cannot be guaranteed identical to the recorded execution."""


class ToolClass(Enum):
    PURE = "pure"                          # re-executable, envelope stable
    ENVELOPE_DIVERGENT = "envelope_div"    # state-idempotent, envelope varies
    MUTATOR = "mutator"                    # non-idempotent side effect
    NONDETERMINISTIC = "nondet"            # clock/random/external feed


@dataclass(frozen=True)
class TraceStep:
    index: int
    tool_name: str
    tool_class: ToolClass
    args_hash: str
    response_envelope: bytes
    response_hash: str


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


def replay_step(step: TraceStep, live_invoke, frozen: bool) -> bytes:
    """Return the envelope the replaying agent should condition on.

    Substitution is the default. Live invocation is permitted only for PURE
    tools against a frozen snapshot, and the live envelope must hash-match
    the recorded one or the replay is environment-drifted and must abort.
    """
    if step.tool_class is not ToolClass.PURE:
        # Never re-invoke; hand the model the recorded envelope verbatim.
        return step.response_envelope

    if not frozen:
        raise ReplayContaminationError(
            f"step {step.index}: PURE tool {step.tool_name!r} invoked against "
            f"non-frozen snapshot; envelope cannot be guaranteed stable"
        )

    live = live_invoke(step.tool_name, step.args_hash)
    if _hash(live) != step.response_hash:
        raise ReplayContaminationError(
            f"step {step.index}: environment drift on {step.tool_name!r}; "
            f"live hash {_hash(live)[:12]} != recorded {step.response_hash[:12]}"
        )
    return live


def replay_trace(trace: list[TraceStep], live_invoke, frozen: bool) -> list[bytes]:
    out = []
    for step in trace:
        out.append(replay_step(step, live_invoke, frozen))
    return out
