# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-replay-divergence-from-non-idempotent-tool-side-effects-in-agentic-forensic-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-replay-divergence-from-non-idempotent-tool-side-effects-in-agentic-forensic-traces.warrant.json
# Markdown SHA-256:   5629f27109d985bd7f1cfcad69f12436d0ac4c6b26bb8f5008fbd30992a94c0e
# Code AST SHA-256:   d87fd121e4f378166b6c4beb9999f3c0c7793434f617d243db425b7366988a91
# Verified Classes:   ReplaySafetyViolation, ToolSafety, ToolCall, ReplayPlan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable, Any


class ReplaySafetyViolation(RuntimeError):
    """Raised when a replay harness attempts to re-execute a tool that is not certified replay-safe."""
    pass


@dataclass
class ToolSafety:
    name: str
    idempotent: bool
    observation_stable: bool  # output fields free of server-generated/time-varying values

    @property
    def replay_safe(self) -> bool:
        return self.idempotent and self.observation_stable


@dataclass
class ToolCall:
    step: int
    tool: str
    args: dict
    recorded_output: Any
    output_referenced_downstream: bool


@dataclass
class ReplayPlan:
    stubbed: list[int] = field(default_factory=list)
    reexecuted: list[int] = field(default_factory=list)
    unverified: list[int] = field(default_factory=list)


def plan_replay(
    calls: list[ToolCall],
    manifest: dict[str, ToolSafety],
    allow_unverified_reexec: bool = False,
) -> ReplayPlan:
    plan = ReplayPlan()
    for call in calls:
        safety = manifest.get(call.tool)
        if safety is None:
            # No safety metadata: default to stub, flag as unverified.
            plan.stubbed.append(call.step)
            plan.unverified.append(call.step)
            continue
        if safety.replay_safe:
            plan.reexecuted.append(call.step)
        else:
            plan.stubbed.append(call.step)
    return plan


def execute_replay(
    calls: list[ToolCall],
    manifest: dict[str, ToolSafety],
    invoke: Callable[[str, dict], Any],
    allow_unverified_reexec: bool = False,
) -> ReplayPlan:
    plan = plan_replay(calls, manifest, allow_unverified_reexec)
    for call in calls:
        safety = manifest.get(call.tool)
        if call.step in plan.stubbed:
            if safety is None and allow_unverified_reexec:
                # Explicit operator override: still refuse, because an unsafe
                # re-execution corrupts the environment and the trace.
                raise ReplaySafetyViolation(
                    f"step {call.step}: tool '{call.tool}' has no safety manifest entry; "
                    f"re-execution would mutate environment and invalidate divergence attribution"
                )
            continue  # serve recorded_output
        if safety is None or not safety.replay_safe:
            raise ReplaySafetyViolation(
                f"step {call.step}: tool '{call.tool}' is not replay-safe "
                f"(idempotent={getattr(safety, 'idempotent', None)}, "
                f"observation_stable={getattr(safety, 'observation_stable', None)}); "
                f"must stub to preserve forensic validity"
            )
        invoke(call.tool, call.args)
    return plan
