# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-has-silently-diverged-from-its-merge-ancestor-in-multi-agent-rollback-merge-systems.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-has-silently-diverged-from-its-merge-ancestor-in-multi-agent-rollback-merge-systems.warrant.json
# Markdown SHA-256:   98d6d018a2e11ad393a5c51f875286d3fb66b79cc030c8d8989897b575dc0d98
# Code AST SHA-256:   acad1d11a33f953f3db3d3fd573380db7a72c55443206e5b743fefaa2f37af55
# Verified Classes:   SpeculativeDivergenceError, Checkpoint, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class SpeculativeDivergenceError(RuntimeError):
    """Raised when a branch's residue escapes its declared delta and poisons the merge."""
    pass


@dataclass
class Checkpoint:
    state_vector: Dict[str, object]
    resource_manifest: Dict[str, str] = field(default_factory=dict)  # resource -> version


@dataclass
class Branch:
    branch_id: str
    attempt_id: str
    delta: Dict[str, object]
    touched_resources: Set[str]


def verify_merge_admissible(
    checkpoint: Checkpoint,
    branches: list[Branch],
    live_resource_versions: Dict[str, str],
) -> None:
    # Invariant: every resource touched by any branch must be either
    # checkpointed, branch-namespaced, or unchanged since the checkpoint.
    for br in branches:
        for res in br.touched_resources:
            checkpointed = res in checkpoint.resource_manifest
            namespaced = res.startswith(f"{br.branch_id}:{br.attempt_id}:")
            unchanged = (
                res in live_resource_versions
                and checkpoint.resource_manifest.get(res) == live_resource_versions[res]
            )
            if not (checkpointed or namespaced or unchanged):
                raise SpeculativeDivergenceError(
                    f"branch {br.branch_id}/{br.attempt_id} touched resource "
                    f"{res!r} which is neither checkpointed, branch-namespaced, "
                    f"nor unchanged; residue would survive rollback and poison merge"
                )

    # Replay-equivalence gate: reconstruct post-merge state and compare.
    reconstructed = dict(checkpoint.state_vector)
    for br in branches:
        reconstructed.update(br.delta)
    for res, ver in live_resource_versions.items():
        if res in checkpoint.resource_manifest:
            if checkpoint.resource_manifest[res] != ver:
                raise SpeculativeDivergenceError(
                    f"checkpointed resource {res!r} drifted from {checkpoint.resource_manifest[res]!r} "
                    f"to {ver!r} during fan-out; replay would not be equivalent to live merge"
                )
