# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-replayed-multi-agent-trace-as-non-authoritative-the-verifier-replay-divergence-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-replayed-multi-agent-trace-as-non-authoritative-the-verifier-replay-divergence-boundary.warrant.json
# Markdown SHA-256:   d41ad0ef027e901adf8120d81b2399f8b3fd1918a5f5536fea5f2a0706b56034
# Code AST SHA-256:   3fd3af682359b0b1b54dc6042e9ed83565f707e01fe247725a6d0f7434d2bff6
# Verified Classes:   ReplayDivergenceError, Node
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ReplayDivergenceError(RuntimeError):
    """Raised when a reconstruction's causal path diverges from the recorded trace
    even though the terminal state matches. Endpoint equality is insufficient."""
    pass


class Node:
    def __init__(self, call_id, tool, idempotent, hermetic, recorded_output, attempted):
        self.call_id = call_id
        self.tool = tool
        self.idempotent = idempotent
        self.hermetic = hermetic
        self.recorded_output = recorded_output
        self.attempted = attempted  # list of attempt outcomes, incl. failures


def reconstruct(trace, harness):
    """Replay a trace. Non-hermetic nodes are output-pinned; never re-executed.
    Returns (reconstructed_graph, is_authoritative)."""
    reconstructed = []
    for node in trace.nodes:
        if not node.hermetic or not node.idempotent:
            # Forensic rule: substitute recorded output, do not re-invoke.
            reconstructed.append({
                "call_id": node.call_id,
                "attempts": node.attempted,
                "output": node.recorded_output,
                "source": "pinned",
            })
            continue
        # Hermetic + idempotent: safe to re-execute.
        result = harness.execute(node.tool, node.recorded_output["request"])
        reconstructed.append({
            "call_id": node.call_id,
            "attempts": [result],
            "output": result,
            "source": "reexecuted",
        })

    recorded_graph = [(n.call_id, tuple(a["status"] for a in n.attempted)) for n in trace.nodes]
    replayed_graph = [(r["call_id"], tuple(a["status"] for a in r["attempts"])) for r in reconstructed]

    if recorded_graph != replayed_graph:
        # Path diverged: a retry collapsed, an attempt vanished, or order changed.
        raise ReplayDivergenceError(
            f"Causal path divergence: recorded={recorded_graph} replayed={replayed_graph}. "
            f"Terminal state may match, but reconstruction is non-authoritative."
        )

    if any(r["source"] == "reexecuted" and not _state_unchanged(r) for r in reconstructed):
        raise ReplayDivergenceError(
            "Re-executed node touched externally-mutable state that changed since original run."
        )

    return reconstructed, True


def _state_unchanged(node_result):
    # Placeholder: caller must supply a state-fingerprint comparison.
    return node_result.get("state_fingerprint_match", False)
