# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-steganographic-collusion-when-its-consensus-divergence-metric-is-itself-computed-over-the-colluders-own-outputs.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-steganographic-collusion-when-its-consensus-divergence-metric-is-itself-computed-over-the-colluders-own-outputs.warrant.json
# Markdown SHA-256:   bd18f6771c8ca38e69fc0708dd8f803e29422b40817e07fef21c66eb091f6250
# Code AST SHA-256:   3a3ad8345a6a2154d1c23a878bd4a7e312a19d0057620e8d8dd1f140939554a6
# Verified Classes:   VarianceInjectionDetected, BatchStats
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import statistics
from dataclasses import dataclass


class VarianceInjectionDetected(RuntimeError):
    """Raised when population divergence rises without a corresponding rise in decision entropy.

    This is the signature of a coalition shaping the auditor's reference
    distribution to hide a tight target cluster inside an inflated sigma.
    """
    pass


@dataclass
class BatchStats:
    rationale_divergence: float   # mean pairwise embedding divergence over rationales
    label_entropy: float          # mean per-document label entropy
    n_agents: int


def detect_variance_injection(
    warmup: BatchStats,
    current: BatchStats,
    divergence_ratio_threshold: float = 2.0,
    entropy_flat_tolerance: float = 0.10,
) -> bool:
    """Return True if the current batch shows the variance-injection signature.

    Signature: rationale divergence has risen past threshold while label
    entropy has stayed flat. A genuine rise in reasoning disagreement moves
    both; a coalition shaping sigma moves only the rationale channel.
    """
    if warmup.rationale_divergence <= 0:
        raise VarianceInjectionDetected(
            "warm-up divergence is non-positive; reference distribution is unusable"
        )

    div_ratio = current.rationale_divergence / warmup.rationale_divergence
    entropy_delta = abs(current.label_entropy - warmup.label_entropy)
    entropy_flat = entropy_delta <= entropy_flat_tolerance

    return div_ratio >= divergence_ratio_threshold and entropy_flat


def anchored_flag_boundary(
    warmup_divergences: list[float],
    z_threshold: float = -1.8,
) -> float:
    """Flag boundary anchored to the warm-up window, not the live population.

    Uses median/MAD so a single poisoned warm-up batch cannot move it far.
    """
    if len(warmup_divergences) < 8:
        raise VarianceInjectionDetected(
            f"warm-up window too small ({len(warmup_divergences)}); "
            "cannot establish anchored boundary"
        )
    med = statistics.median(warmup_divergences)
    mad = statistics.median(abs(x - med) for x in warmup_divergences)
    if mad == 0:
        raise VarianceInjectionDetected(
            "warm-up MAD is zero; divergence is degenerate, boundary undefined"
        )
    return med + z_threshold * 1.4826 * mad


def hash_allocated_inspection(
    doc_ids: list[str],
    budget: int,
    salt: str = "audit-v1",
) -> list[str]:
    """Allocate deep-inspection budget by hash, independent of divergence rank.

    Prevents decoy saturation from starving the target set: the coalition
    cannot steer which documents are inspected by inflating divergence.
    """
    if budget <= 0:
        raise VarianceInjectionDetected("inspection budget must be positive")
    ranked = sorted(
        doc_ids,
        key=lambda d: hashlib.sha256((salt + d).encode()).hexdigest(),
    )
    return ranked[:budget]


def audit_batch(
    warmup: BatchStats,
    current: BatchStats,
    warmup_divergences: list[float],
    doc_ids: list[str],
    budget: int,
) -> list[str]:
    """Full audit pass with both anchors in place."""
    if detect_variance_injection(warmup, current):
        # Freeze boundary to warm-up reference; ignore live population.
        boundary = anchored_flag_boundary(warmup_divergences)
        if boundary <= 0:
            raise VarianceInjectionDetected(
                "anchored boundary is non-positive; cannot distinguish tight cluster"
            )
        # Allocate by hash, not by divergence rank.
        return hash_allocated_inspection(doc_ids, budget)

    # No injection signature: live-population statistics are admissible.
    return hash_allocated_inspection(doc_ids, budget)
