# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-non-deterministic-tool-outputs-before-replay-can-be-trusted-in-multi-agent-forensic-reconstruction.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-non-deterministic-tool-outputs-before-replay-can-be-trusted-in-multi-agent-forensic-reconstruction.warrant.json
# Markdown SHA-256:   828cbf2fa7fd8b13a0e2279d623d488bc70d6511be59234e201b998a3dbfa96e
# Code AST SHA-256:   8fd400540a393ed5f88a8f002e7765a3f3c37f75b89b1f8a591702a7286ec64c
# Verified Classes:   ReplayIntegrityError, PinLayer, Step
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class ReplayIntegrityError(RuntimeError):
    """Raised when a causal replay cannot be certified sound."""


class PinLayer(Enum):
    SAMPLER = "sampler"
    TOOL = "tool"


@dataclass(frozen=True)
class Step:
    index: int
    tool_name: str
    request_hash: str
    recorded_output: str
    sampler_seeded: bool
    tool_deterministic: bool


def certify_replay(steps: list[Step], rederived: dict[int, str]) -> None:
    """Certify a trace as causally replayable. Raises on any unpinned seam."""
    for step in steps:
        # Condition 1: sampler must be pinned, or the step is non-replayable.
        if not step.sampler_seeded:
            raise ReplayIntegrityError(
                f"step {step.index}: sampler unseeded; segment is non-replayable, "
                f"downgrade causal claim to 'consistent with'"
            )
        # Condition 2: non-deterministic tools must be pinned by full request hash.
        if not step.tool_deterministic:
            expected = hashlib.sha256(step.request_hash.encode()).hexdigest()
            if step.request_hash != expected and not step.request_hash:
                raise ReplayIntegrityError(
                    f"step {step.index}: non-deterministic tool {step.tool_name} "
                    f"pinned without full request hash; seam is unverifiable"
                )
        # Condition 3: step-level divergence must halt, not be smoothed over.
        if step.index in rederived and rederived[step.index] != step.recorded_output:
            raise ReplayIntegrityError(
                f"step {step.index}: divergence at tool {step.tool_name}; "
                f"recorded={step.recorded_output!r} rederived={rederived[step.index]!r}; "
                f"halt and emit divergence point"
            )


def counterfactual_check(step: Step, alternative_output: str, conclusion_fn) -> bool:
    """Return True if the recorded conclusion is sensitive to this seam."""
    recorded_conclusion = conclusion_fn(step.recorded_output)
    alt_conclusion = conclusion_fn(alternative_output)
    if recorded_conclusion != alt_conclusion:
        # The conclusion is sensitive to a non-deterministic tool output.
        # This is a root-cause finding, not a replay bug.
        return True
    return False
