# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-heterogeneous-agent-swarm-fail-consensus-when-a-single-auditor-silently-re-quantizes-its-confidence-scale.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-heterogeneous-agent-swarm-fail-consensus-when-a-single-auditor-silently-re-quantizes-its-confidence-scale.warrant.json
# Markdown SHA-256:   0b7dc9f376ef44e3839a9af89f5629efdeddb224a74820ac3fb2dee0bf175b6a
# Code AST SHA-256:   391ff9a06857157c03faca130f33bec54ee96286213399bd9b1879e48137b3ef
# Verified Classes:   ConfidenceDomainMismatch, QuantizationDrift
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ConfidenceDomainMismatch(RuntimeError):
    """Raised when an agent's confidence quantization class does not match the quorum's expected domain."""
    pass


class QuantizationDrift(RuntimeError):
    """Raised when an agent's confidence domain changes mid-epoch without re-attestation."""
    pass


# Declared confidence domains. Agents must attest to one at join time.
CONTINUOUS = "continuous_[0,1]"
DISCRETE_HALF = "discrete_{0,0.5,1}"
PERCENTILE_RANK = "percentile_rank_[0,1]"
LOGIT = "logit_R"


def validate_quorum_weights(agents, expected_domain, epoch_id, prior_epoch_domains):
    """
    Enforce the confidence-domain contract before any weighted quorum is computed.

    agents: list of dicts with keys {id, domain, epoch_id, confidence}
    expected_domain: the quantization class the quorum is defined over
    prior_epoch_domains: map agent_id -> domain observed in the previous epoch
    """
    matching = []
    abstaining = []

    for agent in agents:
        agent_id = agent["id"]
        domain = agent["domain"]

        # Mid-run re-quantization: an agent whose domain changed since last epoch
        # must be treated as abstaining until it re-attests.
        prior = prior_epoch_domains.get(agent_id)
        if prior is not None and prior != domain:
            raise QuantizationDrift(
                f"agent {agent_id} changed confidence domain "
                f"from {prior} to {domain} mid-epoch {epoch_id}; "
                f"prior votes in this epoch are invalid"
            )

        if domain != expected_domain:
            # Honest but differently-scaled agents abstain; they are NOT rescaled.
            abstaining.append(agent_id)
            continue

        matching.append(agent)

    # BFT bound: if more than f agents are non-matching, the weighted quorum
    # is undefined. f is derived from the swarm size; here we require a strict
    # majority of matching agents to preserve the commensurability invariant.
    total = len(agents)
    if len(matching) * 2 <= total:
        raise ConfidenceDomainMismatch(
            f"only {len(matching)}/{total} agents match expected domain "
            f"{expected_domain}; weighted quorum is undefined"
        )

    return matching, abstaining


def weighted_quorum(agents, expected_domain, epoch_id, prior_epoch_domains,
                    threshold=0.5):
    matching, abstaining = validate_quorum_weights(
        agents, expected_domain, epoch_id, prior_epoch_domains
    )

    # Only commensurable weights enter the sum.
    total_weight = sum(a["confidence"] for a in matching)
    if total_weight <= 0.0:
        raise ConfidenceDomainMismatch(
            f"quorum over domain {expected_domain} has non-positive total weight"
        )

    agree_weight = sum(
        a["confidence"] for a in matching if a["decision"] is True
    )
    ratio = agree_weight / total_weight

    return {
        "consensus": ratio >= threshold,
        "ratio": ratio,
        "matching": [a["id"] for a in matching],
        "abstaining": abstaining,
        "epoch_id": epoch_id,
    }
