# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-quorum-slice-is-viable-under-federated-byzantine-agreement-when-agent-testimony-is-non-deterministic.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-quorum-slice-is-viable-under-federated-byzantine-agreement-when-agent-testimony-is-non-deterministic.warrant.json
# Markdown SHA-256:   b30dca0e17c169050926cdf3511afd7ccf90632db1475f5f9267a27f54389ab5
# Code AST SHA-256:   9e7e67d41750e4269b53573a50479223d10f041e7221aced65ed3c3aa73658dd
# Verified Classes:   QuorumIntersectionViolation, Vote, Certification
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class QuorumIntersectionViolation(RuntimeError):
    """Raised when two quorums 'intersect' on a node_id but certify different justification hashes,
    meaning the intersection carries no binding force because the shared node is a stochastic testifier."""
    pass


@dataclass(frozen=True)
class Vote:
    node_id: str
    verdict: str          # "ACCEPT" | "REJECT"
    justification_hash: str  # content-addressed hash of the evidence the agent saw
    replay_locked: bool   # True if verdict is a pure function of justification_hash


@dataclass
class Certification:
    quorum_name: str
    verdict: str
    votes: Dict[str, Vote] = field(default_factory=dict)

    def logical_voters(self) -> Set[Tuple[str, str]]:
        # logical identity of an agent validator is (node_id, justification_hash)
        return {(v.node_id, v.justification_hash) for v in self.votes.values()}


def verify_intersection(cert_a: Certification, cert_b: Certification) -> None:
    """Enforce: any shared node_id across two certifications must either be a deterministic anchor
    OR have certified the SAME justification_hash in both. Otherwise the quorums are disjoint
    in logical-voter space and the intersection is a phantom."""
    shared_node_ids = set(cert_a.votes) & set(cert_b.votes)
    if not shared_node_ids:
        return  # genuinely disjoint; classical FBA math applies to neither

    for node_id in shared_node_ids:
        va = cert_a.votes[node_id]
        vb = cert_b.votes[node_id]

        if va.replay_locked and vb.replay_locked:
            # deterministic anchor: same hash must imply same verdict; divergence is a real fault
            if va.justification_hash == vb.justification_hash and va.verdict != vb.verdict:
                raise QuorumIntersectionViolation(
                    f"replay-locked anchor {node_id} returned divergent verdicts "
                    f"{va.verdict!r} vs {vb.verdict!r} on identical hash {va.justification_hash}"
                )
            continue  # anchors with different hashes are different logical votes but still safe

        # stochastic testifier: the only safe case is same hash => same logical vote
        if va.justification_hash != vb.justification_hash:
            raise QuorumIntersectionViolation(
                f"phantom intersection: stochastic testifier {node_id} voted on "
                f"{va.justification_hash[:12]} in {cert_a.quorum_name} "
                f"({va.verdict}) and {vb.justification_hash[:12]} in {cert_b.quorum_name} "
                f"({vb.verdict}); quorums are topologically intersecting but logically disjoint. "
                f"Refusing certification: escalate to fresh quorum with pinned justification hash."
            )


def certify_claim(claim: str, certs: list[Certification]) -> str:
    # pairwise intersection check across all contributing quorums
    for i in range(len(certs)):
        for j in range(i + 1, len(certs)):
            verify_intersection(certs[i], certs[j])

    # all contributing quorums must certify the same verdict AND the same hash set
    verdicts = {c.verdict for c in certs}
    if len(verdicts) != 1:
        raise QuorumIntersectionViolation(
            f"split-brain on claim {claim!r}: quorums disagree {verdicts} with no shared logical vote"
        )
    return certs[0].verdict


# --- failure trace reproduction ---
h1 = hashlib.sha256(b"evidence-v1").hexdigest()
h2 = hashlib.sha256(b"evidence-v2-retrieval-drift").hexdigest()

a1_first = Vote("A1", "ACCEPT", h1, replay_locked=False)
a1_second = Vote("A1", "REJECT", h2, replay_locked=False)

org_b = Certification("orgB", "ACCEPT", {"A1": a1_first, "B1": Vote("B1", "ACCEPT", h1, False)})
org_c = Certification("orgC", "REJECT", {"A1": a1_second, "C1": Vote("C1", "REJECT", h2, False)})

try:
    certify_claim("task-7741-complete", [org_b, org_c])
except QuorumIntersectionViolation as e:
    print(f"BLOCKED split-brain: {e}")
