# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-reputation-stake-collusion-rings-that-satisfy-every-pairwise-sybil-check-but-fail-graph-level-independence.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-reputation-stake-collusion-rings-that-satisfy-every-pairwise-sybil-check-but-fail-graph-level-independence.warrant.json
# Markdown SHA-256:   5002497ab6a24895db3417edcf47b6fee52ef153dd34e60302731c1aae583ef8
# Code AST SHA-256:   59ce932f5bb18fbde41ff6e439fe1b7be19d42e7a69a4cbb5f3e22587bd5ddef
# Verified Classes:   CollusionRingError, Attestation, Agent
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CollusionRingError(RuntimeError):
    """Raised when an agent's reputation is sourced predominantly from a
    closed co-attestation cluster, violating graph-level independence even
    though every pairwise Sybil check passed."""
    pass


@dataclass
class Attestation:
    attestor: str
    weight: float


@dataclass
class Agent:
    agent_id: str
    stake: float
    incoming: list = field(default_factory=list)  # list[Attestation]
    cluster: Set[str] = field(default_factory=set)  # co-attestation cluster


def intra_cluster_fraction(agent: Agent, cluster: Set[str]) -> float:
    total = sum(a.weight for a in agent.incoming)
    if total <= 0.0:
        return 0.0
    internal = sum(a.weight for a in agent.incoming if a.attestor in cluster)
    return internal / total


def independence_weighted_reputation(
    agent: Agent,
    external_fraction: Dict[str, float],
    tau: float = 0.35,
    min_external_anchors: int = 3,
) -> float:
    """Reputation weighted by each attestor's own external fraction, with a
    hard gate on the agent's intra-cluster fraction and external anchors."""
    frac = intra_cluster_fraction(agent, agent.cluster)
    if frac > tau:
        raise CollusionRingError(
            f"agent {agent.agent_id!r} sources {frac:.2%} of reputation from its "
            f"own co-attestation cluster (tau={tau:.0%}); pairwise checks passed "
            f"but graph-level independence is violated"
        )

    external_attestors = {
        a.attestor for a in agent.incoming if a.attestor not in agent.cluster
    }
    if len(external_attestors) < min_external_anchors:
        raise CollusionRingError(
            f"agent {agent.agent_id!r} has only {len(external_attestors)} external "
            f"anchors (need {min_external_anchors}); reputation provenance is not "
            f"independent of its stake cluster"
        )

    score = 0.0
    for att in agent.incoming:
        ef = external_fraction.get(att.attestor, 0.0)
        score += att.weight * ef
    return score


def admit_to_tier(agent: Agent, external_fraction: Dict[str, float]) -> float:
    score = independence_weighted_reputation(agent, external_fraction)
    if agent.stake < 1000.0:
        raise CollusionRingError(
            f"agent {agent.agent_id!r} stake {agent.stake} below tier floor"
        )
    return score
