# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-poisoned-tool-trace-nondeterministic-re-derivation-and-the-counterfactual-audit-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-poisoned-tool-trace-nondeterministic-re-derivation-and-the-counterfactual-audit-invariant.warrant.json
# Markdown SHA-256:   8e9e07b764888e688b7b127296ec78757f6e7600cbec0e58f9d1eedafffd4b19
# Code AST SHA-256:   86ee3c3cd3fc4b16946691c77555cf7524f8e8f00b73267a3e027f5600519e0b
# Verified Classes:   ReplayDivergenceError, UnlabeledInterventionError, RecordedStep, ReplayHarness
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any, Literal


class ReplayDivergenceError(RuntimeError):
    """Raised when a replay step's observation does not match the recorded trace."""


class UnlabeledInterventionError(RuntimeError):
    """Raised when a counterfactual intervention is applied without an explicit edge tag."""


@dataclass
class RecordedStep:
    index: int
    tool: str
    observation: Any
    observation_hash: str
    decode_config_hash: str


@dataclass
class ReplayHarness:
    recorded: list[RecordedStep]
    interventions: dict[int, Any] = field(default_factory=dict)
    mode: Literal["replay", "counterfactual"] = "replay"

    @staticmethod
    def _hash(obj: Any) -> str:
        return hashlib.sha256(
            json.dumps(obj, sort_keys=True, default=str).encode()
        ).hexdigest()

    def step(self, index: int, live_observation: Any, decode_config: dict) -> Any:
        rec = self.recorded[index]

        if index in self.interventions:
            if self.mode != "counterfactual":
                raise UnlabeledInterventionError(
                    f"intervention at step {index} applied in replay mode; "
                    f"a counterfactual branch must be explicitly declared"
                )
            return self.interventions[index]

        if self.mode == "replay":
            live_hash = self._hash(live_observation)
            if live_hash != rec.observation_hash:
                raise ReplayDivergenceError(
                    f"step {index} tool={rec.tool}: observation hash "
                    f"{live_hash[:12]} != recorded {rec.observation_hash[:12]}; "
                    f"harness is re-deriving, not replaying — abort audit"
                )
            live_decode = self._hash(decode_config)
            if live_decode != rec.decode_config_hash:
                raise ReplayDivergenceError(
                    f"step {index}: decode config hash {live_decode[:12]} != "
                    f"recorded {rec.decode_config_hash[:12]}; model or sampling "
                    f"drifted between incident and audit"
                )

        return rec.observation

    def audit(self, live_observations: list[Any], decode_config: dict) -> list[Any]:
        out = []
        for i, obs in enumerate(live_observations):
            out.append(self.step(i, obs, decode_config))
        return out
