# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-replay-diverge-when-taint-forensics-re-executes-a-trace-across-a-non-deterministic-tool-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-replay-diverge-when-taint-forensics-re-executes-a-trace-across-a-non-deterministic-tool-boundary.warrant.json
# Markdown SHA-256:   f62f9dedaee07607231c7f8037b416eda2ac3bc05aa8638f957612d876359340
# Code AST SHA-256:   4b052a38ac2a51a24f3b28941cced473a29e9028c5ceb3d565fee973bb7b3e6a
# Verified Classes:   TaintAttributionError, EdgeState, ToolCall
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from enum import Enum


class TaintAttributionError(RuntimeError):
    """Raised when a taint edge cannot be soundly attributed during replay."""


class EdgeState(Enum):
    VERIFIED = "VERIFIED"
    RECONSTRUCTED_FROM_RECORDED = "RECONSTRUCTED_FROM_RECORDED"
    DIVERGED = "DIVERGED"


@dataclass(frozen=True)
class ToolCall:
    name: str
    recorded_output: dict
    recorded_projection_hash: str | None  # None if trace predates projection hashing
    fresh_output: dict | None = None


def taint_projection(output: dict) -> bytes:
    """Extract only the taint-relevant fields; ignore volatile fields like uuid/ts."""
    relevant = {k: output[k] for k in ("instruction_text", "url", "secret_ref") if k in output}
    return json.dumps(relevant, sort_keys=True).encode()


def attribute_edge(call: ToolCall) -> EdgeState:
    if call.recorded_projection_hash is None:
        # No pin: re-execution cannot prove provenance. Fail closed.
        raise TaintAttributionError(
            f"call {call.name!r} has no recorded taint_projection_hash; "
            "re-execute replay cannot attribute taint across this boundary"
        )

    if call.fresh_output is None:
        # Record-and-serve path: trivially reconstructs from recorded.
        return EdgeState.RECONSTRUCTED_FROM_RECORDED

    fresh_hash = hashlib.sha256(taint_projection(call.fresh_output)).hexdigest()
    if fresh_hash != call.recorded_projection_hash:
        # Fresh output diverged from incident-time output. Do not emit a VERIFIED edge.
        return EdgeState.DIVERGED
    return EdgeState.VERIFIED


def build_taint_graph(calls: list[ToolCall]) -> list[tuple[str, EdgeState]]:
    graph = []
    for call in calls:
        state = attribute_edge(call)
        if state is EdgeState.DIVERGED:
            # Behavioral reproduction may continue, but provenance must be flagged.
            graph.append((call.name, state))
        else:
            graph.append((call.name, state))
    return graph
