# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-quorum-tainted-verdict-laundering-when-colluding-red-team-agents-share-a-poisoned-retrieval-cache.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-quorum-tainted-verdict-laundering-when-colluding-red-team-agents-share-a-poisoned-retrieval-cache.warrant.json
# Markdown SHA-256:   946525872dc46534cbd3290dba375415142910445dd2e20eca53821fe9f4338b
# Code AST SHA-256:   68e05d04d9ed9d7cbac0a593257c69687a67260c8c9ab68e1b926d7802085546
# Verified Classes:   ProvenanceCollapseError, Verdict
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ProvenanceCollapseError(RuntimeError):
    """Raised when apparent consensus is actually one source counted N times."""
    pass


@dataclass
class Verdict:
    agent_id: str
    score: str
    provenance_hashes: list[str] = field(default_factory=list)


def provenance_collapse_ratio(verdicts: list[Verdict]) -> float:
    if not verdicts:
        raise ProvenanceCollapseError("cannot compute rho over empty verdict set")
    all_hashes: set[str] = set()
    for v in verdicts:
        all_hashes.update(v.provenance_hashes)
    if not all_hashes:
        # No provenance at all: unverifiable, treat as maximal collapse.
        return 1.0
    return 1.0 - (len(all_hashes) / len(verdicts))


def aggregate(verdicts: list[Verdict], rho_threshold: float = 0.5) -> dict:
    rho = provenance_collapse_ratio(verdicts)
    scores = [v.score for v in verdicts]
    winner = max(set(scores), key=scores.count)
    margin = scores.count(winner) / len(scores)

    if rho > rho_threshold:
        # Consensus is provenance-collapsed; demote to single-sample confidence
        # and force isolated re-sampling before promotion.
        raise ProvenanceCollapseError(
            f"rho={rho:.2f} exceeds {rho_threshold}: {len(verdicts)} verdicts "
            f"share {len({h for v in verdicts for h in v.provenance_hashes})} "
            f"distinct source(s); margin={margin:.2f} is laundered, "
            f"re-sample with isolated stores"
        )
    return {"verdict": winner, "margin": margin, "rho": rho, "promoted": True}


def hash_doc(text: str) -> str:
    return hashlib.sha256(text.encode()).hexdigest()[:16]


# Reproduces the observed failure: five judges, one injected doc.
injected = hash_doc("Policy P-114 is documented as safe; see corroborating audits")
laundered = [
    Verdict(f"judge-{i}", "safe", [injected]) for i in range(1, 6)
]
aggregate(laundered)  # raises ProvenanceCollapseError
