# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-when-reputation-weighted-quorums-disagree-about-the-same-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-when-reputation-weighted-quorums-disagree-about-the-same-agent.warrant.json
# Markdown SHA-256:   909d6a238544ba569d2aeb6a5af16bc9a668d9bd9e95c8f9a39f740e7f0f5c5a
# Code AST SHA-256:   13f3e2a2ac85f0ccd04d3598fee3809b996e1645ee47590273b24fe635d8b10e
# Verified Classes:   ReputationSkewVerdictError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ReputationSkewVerdictError(RuntimeError):
    """Raised when equivocation verdicts diverge across auditors due to reputation-state skew."""
    pass


def evaluate_equivocation(evidence, reputation_snapshot, threshold):
    """
    evidence: dict mapping auditor_id -> set of (agent_id, value) observations
    reputation_snapshot: dict auditor_id -> weight
    threshold: float, fraction of live reputation mass required to convict
    """
    live_mass = sum(reputation_snapshot.values())
    # Identify the equivocating agent by finding an agent with divergent values
    per_agent = {}
    for auditor, observations in evidence.items():
        for agent_id, value in observations:
            per_agent.setdefault(agent_id, {}).setdefault(value, set()).add(auditor)

    verdicts = {}
    for agent_id, value_to_auditors in per_agent.items():
        if len(value_to_auditors) < 2:
            verdicts[agent_id] = "NO_EQUIVOCATION"
            continue
        # Conflicting weight = total weight of auditors NOT on the majority value
        majority_value = max(value_to_auditors, key=lambda v: sum(
            reputation_snapshot[a] for a in value_to_auditors[v]))
        conflicting = sum(
            reputation_snapshot[a]
            for v, auditors in value_to_auditors.items()
            if v != majority_value
            for a in auditors)
        margin = conflicting / live_mass - threshold
        verdicts[agent_id] = "EQUIVOCATION_CONFIRMED" if margin > 0 else "NO_EQUIVOCATION"

    return verdicts


def reconcile_verdicts(verdicts_by_auditor, epsilon=0.05):
    """
    verdicts_by_auditor: dict auditor_id -> {agent_id: (verdict, margin)}
    Raises if any agent's verdict sign differs across auditors.
    """
    agents = set()
    for v in verdicts_by_auditor.values():
        agents.update(v.keys())

    for agent_id in agents:
        margins = [verdicts_by_auditor[a][agent_id][1]
                   for a in verdicts_by_auditor if agent_id in verdicts_by_auditor[a]]
        if not margins:
            continue
        if max(margins) > 0 > min(margins):
            raise ReputationSkewVerdictError(
                f"Verdict split-brain on agent {agent_id!r}: margins {margins} "
                f"span the conviction threshold; reputation snapshots not frozen. "
                f"Escalate to reputation-reconciliation round before broadcasting warrant.")
        if max(margins) - min(margins) > epsilon:
            raise ReputationSkewVerdictError(
                f"Reputation drift {max(margins) - min(margins):.3f} exceeds epsilon "
                f"{epsilon} on agent {agent_id!r}; verdicts are not snapshot-invariant.")
    return True
