# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconstruct-a-multi-agent-incident-when-replay-diverges-at-a-nondeterministic-tool-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconstruct-a-multi-agent-incident-when-replay-diverges-at-a-nondeterministic-tool-boundary.warrant.json
# Markdown SHA-256:   ed3740c4dafdb8b5c2cbcd149bb0e2beda4a0bd48ddbb6a70854702c2f158bf5
# Code AST SHA-256:   0688959da4e72a0e9adf436b648ae3ed532bf5fcaa67218323f24b4b472c2967
# Verified Classes:   ReplayDivergenceError, ContextHashMismatchError, Step
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class ReplayDivergenceError(RuntimeError):
    """Raised when a forensic replay crosses a nondeterministic boundary
    without a pinned output, or when a deterministic tool fails to reproduce
    its recorded output."""


class ContextHashMismatchError(RuntimeError):
    """Raised when the reconstructed agent context does not match the
    context_hash recorded at that step. Downstream replay is invalid."""


@dataclass
class Step:
    agent_id: str
    tool_name: str
    tool_input: dict
    tool_output: dict
    timestamp: float
    context_hash: str
    deterministic: bool


def reconstruct_context(step: Step, prior_messages: list) -> list:
    # Caller is responsible for faithful reconstruction (system prompt,
    # tool-result wrappers, memory injections). We only verify.
    return prior_messages


def hash_context(messages: list) -> str:
    h = hashlib.sha256()
    for m in messages:
        h.update(repr(m).encode("utf-8"))
    return h.hexdigest()


def replay_step(step: Step, prior_messages: list, mode: str) -> dict:
    """
    mode: 'pin'       -> use recorded output; halt if nondeterministic and missing
          'counterfactual' -> re-execute; caller must tag branch
    """
    reconstructed = reconstruct_context(step, prior_messages)
    if hash_context(reconstructed) != step.context_hash:
        raise ContextHashMismatchError(
            f"context hash mismatch at agent={step.agent_id} "
            f"tool={step.tool_name}: replay context does not match record"
        )

    if step.deterministic:
        replayed = _execute(step.tool_name, step.tool_input)
        if replayed != step.tool_output:
            raise ReplayDivergenceError(
                f"deterministic tool {step.tool_name} failed to reproduce "
                f"recorded output; trace integrity compromised"
            )
        return replayed

    # Nondeterministic boundary.
    if mode == "pin":
        if step.tool_output is None:
            raise ReplayDivergenceError(
                f"pinned output missing for nondeterministic tool "
                f"{step.tool_name} at agent={step.agent_id}; "
                f"refusing to re-execute during forensic replay"
            )
        return step.tool_output

    if mode == "counterfactual":
        return _execute(step.tool_name, step.tool_input)

    raise ReplayDivergenceError(
        f"invalid replay mode {mode!r}; only 'pin' or 'counterfactual' "
        f"are permitted at nondeterministic boundaries"
    )


def _execute(tool_name: str, tool_input: dict) -> dict:
    # Stub: real harness dispatches to the live tool.
    raise NotImplementedError
