# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-heterogeneous-quorum-s-equivocation-as-byzantine-rather-than-as-sampling-noise.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-heterogeneous-quorum-s-equivocation-as-byzantine-rather-than-as-sampling-noise.warrant.json
# Markdown SHA-256:   4f0662d38ff68a08a161443e503df82a4c44e87c3d31028cd91ae6d4a78f2fa0
# Code AST SHA-256:   8b2c8af8f7d284f7b4908c7acc8dfcd9c4262332875d21bf72a0ee35cb52eae3
# Verified Classes:   QuorumIntegrityError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import math
from collections import Counter

class QuorumIntegrityError(RuntimeError):
    """Raised when a consensus round would evict an agent without sufficient evidence."""
    pass

TAU = 0.30          # bimodality fault threshold
DELTA = 0.40        # context-shift TV-distance threshold
K_MIN = 5           # minimum isolated samples before any verdict

def _tv_distance(p: Counter, q: Counter) -> float:
    labels = set(p) | set(q)
    total_p, total_q = sum(p.values()), sum(q.values())
    return 0.5 * sum(abs(p[l]/total_p - q[l]/total_q) for l in labels)

def classify_agent(isolated_votes, context_votes):
    k_iso = len(isolated_votes)
    if k_iso < K_MIN:
        return "HOLD_ABSTAIN"  # insufficient evidence; do not evict

    iso = Counter(isolated_votes)
    ctx = Counter(context_votes)

    # Test 1: bimodality on isolated samples
    freqs = sorted((c / k_iso for c in iso.values()), reverse=True)
    top, second = freqs[0], (freqs[1] if len(freqs) > 1 else 0.0)
    if second >= TAU and top >= TAU:
        return "BYZANTINE_BIMODAL"

    # Test 2: context-shift (catches temperature-0.0 peer-driven adversary)
    if ctx and _tv_distance(iso, ctx) > DELTA:
        return "BYZANTINE_CONTEXT_SHIFT"

    if top >= 1.0 - TAU:
        return "HONEST_NOISE"
    return "INDETERMINATE_RESAMPLE"

def apply_eviction(agent_id, verdict, quorum):
    if verdict in ("HOLD_ABSTAIN", "INDETERMINATE_RESAMPLE", "HONEST_NOISE"):
        # Never evict on noise or insufficient evidence.
        quorum.mark_abstain(agent_id)
        return quorum
    if verdict not in ("BYZANTINE_BIMODAL", "BYZANTINE_CONTEXT_SHIFT"):
        raise QuorumIntegrityError(
            f"unknown verdict {verdict!r} for agent {agent_id}; refusing eviction"
        )
    if quorum.sample_count(agent_id) < K_MIN:
        raise QuorumIntegrityError(
            f"agent {agent_id} eviction attempted with "
            f"{quorum.sample_count(agent_id)} < {K_MIN} samples"
        )
    quorum.evict(agent_id)
    quorum.recompute_threshold()  # eviction is consensus-affecting; log it
    return quorum
