# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-tree-divergence-between-federated-agent-peers-before-replay-reconciliation-fails.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-tree-divergence-between-federated-agent-peers-before-replay-reconciliation-fails.warrant.json
# Markdown SHA-256:   621703ab8ab3b9c8b7e03ddea8de8dd9937da8e6b5f2057dac98c99ac19519fd
# Code AST SHA-256:   72a0769455f52257e4eeb16c73d0f61dba41b63226e9ca0842630922417782f4
# Verified Classes:   SpeculativeTreeForkError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpeculativeTreeForkError(RuntimeError):
    """Raised when verdict-agreement masks digest-divergence across federated peers,
    causing a speculative branch to be committed without mandatory replay."""
    pass


def reconcile_branch(branch_id: str, peer_a: dict, peer_b: dict, replay_fn) -> dict:
    verdict_agree = peer_a["verdict"] == peer_b["verdict"]
    digest_agree = peer_a["branch_digest"] == peer_b["branch_digest"]

    # Correct gate: replay triggers on EITHER dimension of disagreement.
    if not verdict_agree or not digest_agree:
        # Divergence classification before replay (canonicalization vs reasoning vs sampling).
        divergence_class = _classify(peer_a, peer_b)
        replayed = replay_fn(branch_id, peer_a["transcript_digest"])
        if divergence_class == "sampling_residue" and not digest_agree:
            # A digest mismatch under verdict-agreement in a non-load-bearing leaf
            # is the silent-fork signature; never commit without replay.
            if replayed["digest"] not in (peer_a["branch_digest"], peer_b["branch_digest"]):
                raise SpeculativeTreeForkError(
                    f"branch {branch_id}: replay digest {replayed['digest']} "
                    f"matches neither peer ({peer_a['branch_digest']}, "
                    f"{peer_b['branch_digest']}); federation tree has forked"
                )
        return replayed

    # Only safe when C1 ∧ C2 ∧ C3 hold; assert coverage, do not assume it.
    if not _predicate_covers_digest_scope(peer_a):
        raise SpeculativeTreeForkError(
            f"branch {branch_id}: acceptance predicate does not cover digest scope; "
            f"verdict-agreement is not a valid replay-skip certificate"
        )
    return {"committed": True, "branch_digest": peer_a["branch_digest"]}


def _classify(a: dict, b: dict) -> str:
    if a["transcript_digest"] != b["transcript_digest"] and a["branch_digest"] == b["branch_digest"]:
        return "canonicalization_drift"
    if a["transcript_digest"] == b["transcript_digest"] and a["branch_digest"] != b["branch_digest"]:
        return "reasoning_path_aliasing"
    return "sampling_residue"


def _predicate_covers_digest_scope(peer: dict) -> bool:
    return peer.get("predicate_scope") == peer.get("digest_scope")
