# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-semantic-equivocation-from-collapsing-heterogeneous-swarm-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-semantic-equivocation-from-collapsing-heterogeneous-swarm-consensus.warrant.json
# Markdown SHA-256:   663001782405a65466233e1209e7b9344c87d172bd0fed8f205cc5a2d181f35f
# Code AST SHA-256:   ec96470f7dc61e2a48e0753249c001a96a979ae7d611a0e1cfe97f66041d85df
# Verified Classes:   SemanticEquivocationError, Claim
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import itertools
from dataclasses import dataclass

TAU = 0.92          # equivalence threshold
DELTA = 0.04        # ambiguity band width
EPS = 0.03          # max allowed family-conditional mean gap


class SemanticEquivocationError(RuntimeError):
    """Raised when a quorum is claimed over a non-transitive or family-biased class."""


@dataclass
class Claim:
    agent_id: str
    family: str
    text: str
    embedding: list[float]


def cosine(a: list[float], b: list[float]) -> float:
    dot = sum(x * y for x, y in zip(a, b))
    na = sum(x * x for x in a) ** 0.5
    nb = sum(y * y for y in b) ** 0.5
    return dot / (na * nb) if na and nb else 0.0


def audit_equivalence_class(cls: list[Claim], threshold: float = TAU) -> None:
    """Enforce transitivity + family-unbiased similarity before allowing commit."""
    if len(cls) < 2:
        return

    pair_sims = [
        cosine(a.embedding, b.embedding)
        for a, b in itertools.combinations(cls, 2)
    ]
    min_sim = min(pair_sims)

    # Invariant 1: transitivity. The weakest link must clear the threshold,
    # not just the class centroid.
    if min_sim < threshold:
        raise SemanticEquivocationError(
            f"non-transitive class: min pairwise sim {min_sim:.3f} < tau {threshold}"
        )

    # Invariant 2: family bias. If one model family sits systematically
    # closer to the centroid than another, the comparator is biased.
    families: dict[str, list[float]] = {}
    for c in cls:
        families.setdefault(c.family, []).append(
            sum(cosine(c.embedding, o.embedding) for o in cls if o is not c)
            / (len(cls) - 1)
        )
    means = [sum(v) / len(v) for v in families.values()]
    if len(means) > 1 and (max(means) - min(means)) > EPS:
        raise SemanticEquivocationError(
            f"family-biased comparator: mean gap {max(means) - min(means):.3f} > eps {EPS}"
        )


def try_commit(claims: list[Claim], n: int, threshold: float = TAU) -> list[Claim]:
    """Attempt quorum commit; escalate ambiguous claims instead of merging them."""
    leader = max(claims, key=lambda c: sum(cosine(c.embedding, o.embedding) for o in claims))
    cls = [c for c in claims if cosine(c.embedding, leader.embedding) >= threshold]

    # Ambiguity band: near-threshold claims must not be silently merged.
    ambiguous = [
        c for c in claims
        if threshold <= cosine(c.embedding, leader.embedding) < threshold + DELTA
    ]
    if ambiguous:
        raise SemanticEquivocationError(
            f"{len(ambiguous)} claim(s) in ambiguity band "
            f"[{threshold}, {threshold + DELTA}); clarification round required"
        )

    audit_equivalence_class(cls, threshold)

    if len(cls) * 3 < 2 * n:
        raise SemanticEquivocationError(
            f"quorum not reached: {len(cls)}/{n} in audited class"
        )
    return cls
