# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-diverge-from-its-speculative-branch-siblings-and-then-silently-ratify-a-poisoned-merge-speculative-fan-out-with-conflict-detectio.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-diverge-from-its-speculative-branch-siblings-and-then-silently-ratify-a-poisoned-merge-speculative-fan-out-with-conflict-detectio.warrant.json
# Markdown SHA-256:   3a11a64a329497bf4d8d8fd40508d67dcd1e7335406af2f72b89db16e98dbf5e
# Code AST SHA-256:   b2c8ea6cba4f0b6e89e5d5bcd10e0ade93e665e4610d5a02516322aad65bb727
# Verified Classes:   CorrelatedConsensusError, BranchClaim
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class CorrelatedConsensusError(RuntimeError):
    """Raised when a speculative merge would ratify agreement that is not independent."""
    pass


@dataclass(frozen=True)
class BranchClaim:
    branch_id: str
    value: str
    provenance_label: str        # what the branch *says* it read (e.g. "chunk_117")
    witness_hash: str | None     # hash of the actual evidence artifact, or None if unresolvable
    peer_refs: tuple[str, ...]   # branch_ids whose outputs this branch's trace referenced


def _resolve_witness(branch: BranchClaim) -> str:
    if branch.witness_hash is None:
        # Provenance could not be resolved to a distinct artifact.
        raise CorrelatedConsensusError(
            f"branch {branch.branch_id} has unresolvable provenance "
            f"'{branch.provenance_label}'; cannot count as independent evidence"
        )
    return branch.witness_hash


def validate_speculative_merge(claims: list[BranchClaim], min_witnesses: int = 2) -> str:
    if not claims:
        raise CorrelatedConsensusError("empty speculative fan-out; nothing to merge")

    # 1. Reject peer-contaminated branches outright.
    for c in claims:
        if c.peer_refs:
            raise CorrelatedConsensusError(
                f"branch {c.branch_id} referenced peer outputs {c.peer_refs}; "
                f"it is contaminated and cannot vote"
            )

    # 2. Require output agreement before considering merge.
    values = {c.value for c in claims}
    if len(values) != 1:
        # Genuine syntactic conflict -> existing repair path, not this gate.
        raise CorrelatedConsensusError(
            f"branches disagree on value {values}; route to conflict repair"
        )
    agreed_value = values.pop()

    # 3. The core invariant: distinct evidence witnesses must back the claim.
    witnesses = {_resolve_witness(c) for c in claims}
    if len(witnesses) < min_witnesses:
        # All branches converged on the same single artifact -> correlated, not verified.
        digest = hashlib.sha256(agreed_value.encode()).hexdigest()[:12]
        raise CorrelatedConsensusError(
            f"value {agreed_value!r} (digest {digest}) backed by only "
            f"{len(witnesses)} distinct witness(es) across {len(claims)} branches; "
            f"agreement is correlated, not corroborated. Force isolated re-derivation."
        )

    return agreed_value
