# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-nondeterministic-tool-output-replay-as-a-first-class-forensic-hazard-in-agent-trajectory-reconstruction.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-nondeterministic-tool-output-replay-as-a-first-class-forensic-hazard-in-agent-trajectory-reconstruction.warrant.json
# Markdown SHA-256:   40ed52e57f243d1414260934c4b92818816d65b1f19cbecaa7dbfacb4fc1919a
# Code AST SHA-256:   115fe03b717d8e9498d59837ef8fd0567daa7844f1ad2d6314f755c2b9177166
# Verified Classes:   UnpinnedToolResultError, ToolCallRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class UnpinnedToolResultError(RuntimeError):
    """Raised when a replay attempts to consume a tool result that is not
    backed by a hash-verified pin from the recorded trajectory. This is a
    hard failure: proceeding would silently convert a forensic
    reconstruction into a counterfactual and poison downstream reasoning."""


@dataclass(frozen=True)
class ToolCallRecord:
    index: int
    tool_name: str
    args: dict
    result_payload: Optional[bytes]   # None if the recorder failed to capture it
    result_hash: Optional[str]        # sha256 of result_payload, if captured


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


def resolve_tool_result(
    record: ToolCallRecord,
    *,
    mode: str,  # "reconstruction" | "counterfactual"
    live_dispatch,  # callable(tool_name, args) -> bytes, used only in counterfactual
) -> bytes:
    """
    Resolve the result that the replay harness will feed into the reasoning
    context for a single tool call.

    Invariant: in reconstruction mode, the returned bytes MUST be the recorded
    bytes, verified by hash. No live dispatch is permitted, and a missing pin
    is a hard error rather than a cache miss.
    """
    if mode == "reconstruction":
        if record.result_payload is None or record.result_hash is None:
            raise UnpinnedToolResultError(
                f"call[{record.index}] tool={record.tool_name!r} has no pinned "
                f"result; reconstruction cannot proceed. Either recover the pin "
                f"from the raw log or explicitly downgrade to counterfactual mode."
            )
        actual = _hash(record.result_payload)
        if actual != record.result_hash:
            raise UnpinnedToolResultError(
                f"call[{record.index}] tool={record.tool_name!r} pin hash mismatch: "
                f"recorded={record.result_hash} actual={actual}. The pin is corrupt; "
                f"do not feed this result into the reasoning context."
            )
        return record.result_payload

    if mode == "counterfactual":
        # Live dispatch is permitted, but the caller is contractually obligated
        # to stamp the resulting trajectory as counterfactual. We return the
        # live bytes and rely on the outer report layer to label them.
        return live_dispatch(record.tool_name, record.args)

    raise ValueError(f"unknown replay mode: {mode!r}")


def build_replay_context(records, *, mode, live_dispatch):
    """
    Construct the tool-result blocks for a replayed trajectory. Fails closed
    on the first unpinned call in reconstruction mode.
    """
    context = []
    for rec in records:
        try:
            result = resolve_tool_result(rec, mode=mode, live_dispatch=live_dispatch)
        except UnpinnedToolResultError:
            # Re-raise: do not swallow, do not fall through to live dispatch.
            raise
        context.append({"index": rec.index, "tool": rec.tool_name, "result": result})
    return context
