# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-reconciliation-has-silently-collapsed-into-divergent-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-reconciliation-has-silently-collapsed-into-divergent-replay.warrant.json
# Markdown SHA-256:   09f67eee4a7854aaa82b51b2d8e02ad23b5478f1e9246da8aec58f2b0d5a1390
# Code AST SHA-256:   bb00f0914ce2ea63c328782e796fd444eaeda506bd8e9a74023cce52bedecb87
# Verified Classes:   DivergentReplayError, LedgerMissingResponseError, ToolResponse, SpeculativeBranch, SharedLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class DivergentReplayError(RuntimeError):
    """Raised when a speculative branch cannot be reconciled by replay equivalence."""


class LedgerMissingResponseError(DivergentReplayError):
    """Raised when a branch consumed a tool response not pinned in the shared ledger."""


@dataclass
class ToolResponse:
    call_id: str
    body: bytes

    def response_hash(self) -> str:
        return hashlib.sha256(self.body).hexdigest()


@dataclass
class SpeculativeBranch:
    branch_id: str
    fork_checkpoint: str
    consumed: list[ToolResponse] = field(default_factory=list)
    delta: Optional[dict] = None
    max_replay_depth: int = 8


@dataclass
class SharedLedger:
    pinned: dict[str, str] = field(default_factory=dict)  # call_id -> response_hash

    def pin(self, resp: ToolResponse) -> None:
        self.pinned[resp.call_id] = resp.response_hash()

    def contains(self, resp: ToolResponse) -> bool:
        return self.pinned.get(resp.call_id) == resp.response_hash()


def reconcile_branch(branch: SpeculativeBranch, ledger: SharedLedger) -> str:
    """
    Returns 'COMMIT' only if the branch is replay-equivalent to the canonical path.
    Raises DivergentReplayError (or subclass) for any divergence signal.
    """
    if branch.delta is None:
        raise DivergentReplayError(
            f"branch {branch.branch_id} produced no delta; cannot reconcile"
        )

    # Signal 1: every consumed response must be hash-pinned in the shared ledger.
    for resp in branch.consumed:
        if not ledger.contains(resp):
            raise LedgerMissingResponseError(
                f"branch {branch.branch_id} consumed call {resp.call_id} "
                f"(hash {resp.response_hash()[:12]}) not present in shared ledger; "
                f"this is divergent replay, not convergent reconciliation"
            )

    # Signal 2: replay depth must not exceed the hard ceiling.
    replay_edges = len(branch.consumed)
    if replay_edges > branch.max_replay_depth:
        raise DivergentReplayError(
            f"branch {branch.branch_id} replay requires {replay_edges} edges, "
            f"exceeds max_replay_depth={branch.max_replay_depth}; "
            f"truncated replay is an abstention, not a pass"
        )

    # Signal 3: observable prefix must be a subset of canonical observables.
    canonical_calls = set(ledger.pinned.keys())
    branch_calls = {r.call_id for r in branch.consumed}
    if not branch_calls.issubset(canonical_calls):
        extra = branch_calls - canonical_calls
        raise DivergentReplayError(
            f"branch {branch.branch_id} observed calls {extra} absent from "
            f"canonical observable set; prefix asymmetry breaks delta-merge reconciliation"
        )

    return "COMMIT"


def run_speculation(branches: list[SpeculativeBranch], ledger: SharedLedger) -> list[str]:
    verdicts = []
    for b in branches:
        try:
            verdicts.append(reconcile_branch(b, ledger))
        except DivergentReplayError as e:
            # Escalate: abort branch, re-execute from fork_checkpoint with pinned outputs.
            verdicts.append(f"ABORT:{b.branch_id}:{type(e).__name__}")
    return verdicts
