# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-distrust-its-own-replay-trace-when-non-deterministic-tool-outputs-are-re-executed-during-incident-forensics.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-distrust-its-own-replay-trace-when-non-deterministic-tool-outputs-are-re-executed-during-incident-forensics.warrant.json
# Markdown SHA-256:   3daa62639ddbec0d45872da4d929ac17189c0b82557a58e937fe2648ae747bc8
# Code AST SHA-256:   0a1c7611532d95dc4667c1af7015ef3def0203a4bad47163aa180a4377f2671c
# Verified Classes:   ReplayDivergenceError, Step, ToolManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ReplayDivergenceError(RuntimeError):
    """Raised when a replay trace diverges from the recorded trace at or before the incident boundary."""
    pass


@dataclass
class Step:
    index: int
    tool_name: str
    tool_args: str
    tool_result: str
    model_output: str


@dataclass
class ToolManifest:
    name: str
    deterministic: bool
    environment_pinned: bool


def replay_and_certify(
    record: list[Step],
    replayed: list[Step],
    incident_index: int,
    manifests: dict[str, ToolManifest],
) -> str:
    """
    Replay a recorded agent trace and certify whether it is trace-equivalent
    up to the incident boundary.

    Returns one of:
      - "CERTIFIED": replay matches record through incident_index; root cause may be drawn.
      - "REPLAY_ARTIFACT": divergence at/before incident caused by non-deterministic tool;
                          replay is invalid, fall back to log-only analysis.
      - "EVIDENCE_INTEGRITY": divergence at/before incident on a pinned deterministic tool;
                              the recorded trace itself is suspect.

    Raises ReplayDivergenceError if the replayed trace is shorter than the incident boundary.
    """
    if len(replayed) <= incident_index:
        raise ReplayDivergenceError(
            f"Replay terminated at step {len(replayed) - 1}, "
            f"before incident boundary at step {incident_index}; cannot certify."
        )

    for i in range(incident_index + 1):
        rec, rep = record[i], replayed[i]
        if (rec.tool_name, rec.tool_args) != (rep.tool_name, rep.tool_args):
            # Argument-level divergence: the agent branched differently.
            # This is never a benign artifact; the causal premise is broken.
            raise ReplayDivergenceError(
                f"Step {i}: tool call diverged. "
                f"record={rec.tool_name}({rec.tool_args!r}) "
                f"replay={rep.tool_name}({rep.tool_args!r}). "
                f"Replay is not trace-equivalent at/before incident boundary."
            )

        if rec.tool_result != rep.tool_result:
            manifest = manifests.get(rec.tool_name)
            if manifest is None:
                raise ReplayDivergenceError(
                    f"Step {i}: tool {rec.tool_name!r} has no manifest; "
                    f"cannot classify result divergence."
                )
            if not manifest.deterministic:
                return "REPLAY_ARTIFACT"
            if not manifest.environment_pinned:
                # Deterministic tool but unpinned env: still a replay artifact,
                # because we cannot prove the environment matches the record.
                return "REPLAY_ARTIFACT"
            return "EVIDENCE_INTEGRITY"

        if rec.model_output != rep.model_output:
            # Model output divergence at/before incident: flag as artifact,
            # do not certify, because the reasoning branch is not reproduced.
            return "REPLAY_ARTIFACT"

    return "CERTIFIED"
