# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-multi-agent-run-has-crossed-the-replay-divergence-boundary-before-its-audit-trail-records-it.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-multi-agent-run-has-crossed-the-replay-divergence-boundary-before-its-audit-trail-records-it.warrant.json
# Markdown SHA-256:   3abde47cebbfb0d2ac4abc15f13897287022f108afc369424b4bcdd127297e6f
# Code AST SHA-256:   5b13f3f2034b350c51d13db222317b3fb9bc881e9bd6f7a93505e3af57cf5e3d
# Verified Classes:   ReplayDivergenceError, Trace
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Sequence


class ReplayDivergenceError(RuntimeError):
    """Raised when a replayed trace diverges from the recorded trace before
    the declared fork index, invalidating counterfactual comparison."""
    pass


@dataclass
class Trace:
    steps: Sequence[str]
    fork_index: int

    def prefix_digest(self) -> str:
        h = hashlib.sha256()
        for step in self.steps[: self.fork_index]:
            h.update(step.encode("utf-8"))
            h.update(b"\x00")
        return h.hexdigest()


def first_divergence(recorded: Trace, replayed: Trace) -> int:
    n = min(len(recorded.steps), len(replayed.steps))
    for i in range(n):
        if recorded.steps[i] != replayed.steps[i]:
            return i
    return n


def audit_branch(recorded: Trace, replayed: Trace) -> str:
    if recorded.fork_index != replayed.fork_index:
        raise ReplayDivergenceError(
            f"fork index mismatch: recorded={recorded.fork_index} "
            f"replayed={replayed.fork_index}"
        )
    div = first_divergence(recorded, replayed)
    if div < recorded.fork_index:
        raise ReplayDivergenceError(
            f"fork-point drift: first divergence at {div} precedes "
            f"declared fork index {recorded.fork_index}; "
            f"prefix_digest recorded={recorded.prefix_digest()[:12]} "
            f"replayed={replayed.prefix_digest()[:12]}"
        )
    return "VERIFIED" if div == len(recorded.steps) else "REFUTED"


def audit_speculative_run(recorded_committed: Trace,
                          replayed_branches: Sequence[Trace]) -> dict:
    results = {}
    for idx, branch in enumerate(replayed_branches):
        try:
            results[idx] = audit_branch(recorded_committed, branch)
        except ReplayDivergenceError as exc:
            # Fail closed: taint the entire run, not just this branch.
            raise ReplayDivergenceError(
                f"speculative run unverified: branch {idx} failed "
                f"prefix-identity precondition: {exc}"
            ) from exc
    return results
