# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-replayed-mcp-session-non-deterministic-tool-side-effects-as-a-forensic-reconstruction-hazard.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-replayed-mcp-session-non-deterministic-tool-side-effects-as-a-forensic-reconstruction-hazard.warrant.json
# Markdown SHA-256:   fbc628776a5a394a5b1a28cbba2b4a556c9c901c53d4f79bb753808fb948cdca
# Code AST SHA-256:   d76802f5b2b5053bed0267c6e1c02b571fb6acdc138d2c86acff21c5934eb3ee
# Verified Classes:   ReconstructionGapError, ToolCallRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ReconstructionGapError(RuntimeError):
    """Raised when a replayed session cannot be faithfully reconstructed
    because an impure tool response was consumed by agent reasoning but
    could not be regenerated to match the recorded payload."""


@dataclass
class ToolCallRecord:
    step: int
    tool_name: str
    args_hash: str
    response_hash: str
    response_body: Optional[str]   # None if elided at log time
    is_pure: bool
    response_consumed_by_agent: bool


def replay_step(record: ToolCallRecord, reexecute_fn) -> str:
    """Reconstruct one tool response for forensic replay.

    Faithful if: pure (re-execute freely) or response body was logged.
    Otherwise re-execute and compare hashes; on mismatch, decide whether
    the divergence can affect downstream reasoning.
    """
    if record.is_pure:
        return reexecute_fn(record.tool_name, record.args_hash)

    if record.response_body is not None:
        return record.response_body

    # Impure and response-elided: must re-execute and verify.
    regenerated = reexecute_fn(record.tool_name, record.args_hash)
    regenerated_hash = _hash(regenerated)

    if regenerated_hash == record.response_hash:
        return regenerated

    # Hash mismatch. If the response was consumed, the reconstruction is
    # invalid and we must fail closed rather than emit a divergent narrative.
    if record.response_consumed_by_agent:
        raise ReconstructionGapError(
            f"step {record.step}: impure tool '{record.tool_name}' response "
            f"consumed by agent but re-execution diverged "
            f"(recorded {record.response_hash[:12]}, got {regenerated_hash[:12]}); "
            f"downstream branch at step {record.step} is unreconstructable"
        )

    # Response was dropped before reasoning; divergence is bounded.
    return regenerated


def _hash(payload: str) -> str:
    import hashlib
    return hashlib.sha256(payload.encode()).hexdigest()
