# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-causal-replay-of-agent-traces-from-silently-rewriting-history-when-tool-outputs-are-re-sampled.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-causal-replay-of-agent-traces-from-silently-rewriting-history-when-tool-outputs-are-re-sampled.warrant.json
# Markdown SHA-256:   9388c69a59d3a1f8a3768e3ce3dd279c574f4d0d7b286f7c16a5df1914ad1008
# Code AST SHA-256:   c7e27d63eafdad39b50a4b177013f5e392025146e0eadeb8972eeb83656e2c95
# Verified Classes:   ReplayInvariantError, ReplayMode, Step
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class ReplayInvariantError(RuntimeError):
    """Raised when a replay would silently rewrite causal history."""


class ReplayMode(Enum):
    RECORDED = "recorded"        # re-read stored bytes; causal
    REEXECUTED = "reexecuted"    # re-ran a deterministic tool; must match
    FORKED = "forked"            # counterfactual branch; not causal


@dataclass(frozen=True)
class Step:
    run_id: str
    agent_id: str
    seq: int
    tool_name: str
    tool_args: dict
    tool_output: dict
    input_fingerprint: str
    world_coupled: bool

    @property
    def step_key(self) -> tuple:
        # globally unique; collisions are a store bug, not a merge policy
        return (self.run_id, self.agent_id, self.seq)


def fingerprint(tool_name: str, tool_args: dict) -> str:
    canon = f"{tool_name}|{sorted(tool_args.items())}".encode()
    return hashlib.sha256(canon).hexdigest()


def replay_step(recorded: Step, live_output: dict | None) -> tuple[Step, ReplayMode]:
    """Replay one step under the immutability invariant.

    - world-coupled steps re-read recorded bytes; live_output is ignored.
    - deterministic steps may re-execute, but a mismatch is a contract
      violation, not a silent overwrite.
    - fingerprint mismatch means upstream divergence: caller must fork.
    """
    expected_fp = fingerprint(recorded.tool_name, recorded.tool_args)
    if recorded.input_fingerprint != expected_fp:
        raise ReplayInvariantError(
            f"input fingerprint mismatch at {recorded.step_key}: "
            f"recorded={recorded.input_fingerprint} recomputed={expected_fp}; "
            "replay diverged upstream, fork a counterfactual branch"
        )

    if recorded.world_coupled:
        # never re-execute world-coupled steps during a causal replay
        return recorded, ReplayMode.RECORDED

    if live_output is None:
        raise ReplayInvariantError(
            f"deterministic step {recorded.step_key} requires re-execution "
            "output to verify contract"
        )

    if live_output != recorded.tool_output:
        raise ReplayInvariantError(
            f"determinism contract violated at {recorded.step_key}: "
            f"tool={recorded.tool_name} recorded={recorded.tool_output} "
            f"replayed={live_output}; tool is not deterministic-by-contract"
        )
    return recorded, ReplayMode.REEXECUTED


def replay_run(recorded_steps: list[Step], live_outputs: dict[tuple, dict]) -> list[tuple[Step, ReplayMode]]:
    seen: dict[tuple, Step] = {}
    for s in recorded_steps:
        if s.step_key in seen:
            raise ReplayInvariantError(
                f"step identity collision at {s.step_key}: trace store "
                "cannot prove which write is causal; run is unreplayable"
            )
        seen[s.step_key] = s

    out = []
    for s in recorded_steps:
        out.append(replay_step(s, live_outputs.get(s.step_key)))
    return out
