# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-deterministic-replay-of-a-speculative-multi-agent-plan-has-silently-diverged-from-the-executed-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-deterministic-replay-of-a-speculative-multi-agent-plan-has-silently-diverged-from-the-executed-trace.warrant.json
# Markdown SHA-256:   547f5ce783484aa75bcfc4a85a23fe1bf205a3ca60f371672f8ba94f0e27e8e0
# Code AST SHA-256:   0f3e304d8239aec0f2b61f618f5fc735c72def5b000063bcac65d6877d272817
# Verified Classes:   ReplayDivergenceError, Event
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ReplayDivergenceError(RuntimeError):
    """Raised when a forensic replay would be trace-equivalent but not DAG-isomorphic."""


@dataclass
class Event:
    id: str
    kind: str                      # spawn | complete | commit | cancel | tool_call | gate
    cause: Optional[str]           # causal parent event id; None == causally orphaned
    branch: str                    # committed | abandoned
    evidence_set: Optional[frozenset] = None  # only for gate events


def reconstruct_causal_path(events: list[Event], terminal_id: str) -> list[Event]:
    by_id = {e.id: e for e in events}
    path: list[Event] = []
    frontier = [terminal_id]
    seen: set[str] = set()

    while frontier:
        eid = frontier.pop()
        if eid in seen:
            continue
        seen.add(eid)
        ev = by_id.get(eid)
        if ev is None:
            raise ReplayDivergenceError(f"event {eid} referenced but absent from log")

        # Committed-path event with no causal parent => inadmissible, fail closed.
        if ev.branch == "committed" and ev.cause is None and ev.kind != "spawn":
            raise ReplayDivergenceError(
                f"committed-path event {ev.id} ({ev.kind}) has no causal parent; "
                f"replay would heuristic-fill and silently diverge"
            )

        # Gate evidence sets must be recorded, never inferred.
        if ev.kind == "gate" and ev.evidence_set is None:
            raise ReplayDivergenceError(
                f"gate {ev.id} lacks recorded evidence_set; inference would leak "
                f"abandoned branches into the committed path"
            )

        # A committed-path edge must not originate from an abandoned branch.
        if ev.cause is not None:
            parent = by_id.get(ev.cause)
            if parent is None:
                raise ReplayDivergenceError(f"cause {ev.cause} of {ev.id} missing from log")
            if parent.branch == "abandoned" and ev.branch == "committed":
                raise ReplayDivergenceError(
                    f"abandoned branch event {parent.id} feeds committed event {ev.id}; "
                    f"quarantine violated"
                )
            frontier.append(ev.cause)

        path.append(ev)

    return list(reversed(path))
