# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-level-collusion-detector-fail-open-when-federated-agents-re-derive-the-same-shortcut-the-consensus-as-signal-inversion-in-emergen.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-level-collusion-detector-fail-open-when-federated-agents-re-derive-the-same-shortcut-the-consensus-as-signal-inversion-in-emergen.warrant.json
# Markdown SHA-256:   f1b5f0e3e18bb88f2bd7da7541c6da042e69d2620a53a82237aff7388d42791c
# Code AST SHA-256:   1a88071d78c4cfe8e31aa5bb019d01393f2f1f696af9c43eee536428a1bd4b4a
# Verified Classes:   CollusionMonitorError, SharedState, Population
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class CollusionMonitorError(RuntimeError):
    """Raised when the monitor is asked to make a decision it cannot validly support."""
    pass


@dataclass
class SharedState:
    writer_id: str
    token: str
    channel: str          # "scheduler" | "scratchpad" | "handoff" | "unknown"
    provenance: str = ""

    def __post_init__(self):
        if not self.provenance:
            self.provenance = hashlib.sha256(
                f"{self.writer_id}:{self.token}:{self.channel}".encode()
            ).hexdigest()[:16]


@dataclass
class Population:
    instances: list = field(default_factory=list)
    shared_state: list = field(default_factory=list)

    def agreement_statistic(self) -> float:
        # Population-wide agreement. Dominated by shared model prior in
        # homogeneous federated populations. NOT admissible as collusion evidence.
        if not self.shared_state:
            return 0.0
        tokens = [s.token for s in self.shared_state]
        return tokens.count(max(set(tokens), key=tokens.count)) / len(tokens)


def detect_collusion(pop: Population, cluster_threshold: int = 3) -> list:
    """
    Provenance-first, cluster-local collusion detection.

    Fires only when a cluster of instances shares state whose provenance
    resolves to a common writer that is NOT the scheduler. Agreement
    magnitude is deliberately ignored here; it is routed to model-drift.
    """
    if not pop.shared_state:
        raise CollusionMonitorError(
            "No shared-state telemetry captured; cannot establish provenance. "
            "Refusing to fall back to agreement magnitude (measures model prior)."
        )

    # Group by provenance ancestor, excluding scheduler-originated state.
    clusters: dict[str, set] = {}
    for s in pop.shared_state:
        if s.channel == "scheduler":
            continue
        if s.channel == "unknown":
            raise CollusionMonitorError(
                f"Shared state {s.token!r} has unknown channel; provenance "
                "unresolvable. Cannot distinguish convergence from coordination."
            )
        clusters.setdefault(s.provenance, set()).add(s.writer_id)

    # A provenance hash shared across >= cluster_threshold distinct writers
    # is a causal-channel signal, invariant to convergence agreement.
    alerts = []
    for prov, writers in clusters.items():
        if len(writers) >= cluster_threshold:
            alerts.append({
                "provenance": prov,
                "cluster_size": len(writers),
                "writers": sorted(writers),
                "evidence": "shared-causal-ancestor",
            })

    # Agreement magnitude is logged but never gates a security alert.
    pop_agreement = pop.agreement_statistic()
    if pop_agreement > 0.75 and not alerts:
        # Benign convergence: route to model-drift, not collusion queue.
        return [{"route": "model-drift", "agreement": pop_agreement}]

    return alerts


def run_monitor(pop: Population) -> list:
    try:
        return detect_collusion(pop)
    except CollusionMonitorError as e:
        # Fail closed on undecidable provenance, never fail open.
        raise CollusionMonitorError(
            f"Collusion monitor could not reach a valid decision: {e}. "
            "Halting population to prevent undetected coordination."
        ) from e
