# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-exploit-synthesis-drift-when-a-continuous-red-teaming-harness-mutates-its-own-attack-corpus-against-a-live-a.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-exploit-synthesis-drift-when-a-continuous-red-teaming-harness-mutates-its-own-attack-corpus-against-a-live-a.warrant.json
# Markdown SHA-256:   250057ed47dc4945670f5bc47a00d74fec6553626d8df1807d92cf478c360028
# Code AST SHA-256:   7734f32cc9811e818aee4126bbd11f00453faae2036fda2b36b6e38b57e5f349
# Verified Classes:   ExploitSynthesisDriftError, Mutant, HarnessConfig, DriftGuard
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Dict, List, Optional


class ExploitSynthesisDriftError(RuntimeError):
    """Raised when a continuous red-teaming harness's corpus has drifted
    away from the protocol surface it was seeded to test."""
    pass


@dataclass
class Mutant:
    mutant_id: str
    seed_id: str
    fields_touched: List[str]          # protocol fields this mutant exercises
    fitness: Optional[float]           # None => unscoreable, must not be a parent
    generation: int
    provenance_ok: bool = True


@dataclass
class HarnessConfig:
    epsilon: float = 0.05              # min coverage per field
    rho_max: float = 0.40              # max share of any single field in parents
    coverage_collapse_ratio: float = 0.5
    volume_novelty_ratio: int = 10


class DriftGuard:
    def __init__(self, config: HarnessConfig, seed_fields: List[str]):
        self.config = config
        self.seed_fields = list(seed_fields)
        self.history: List[Dict[str, float]] = []

    def _field_coverage(self, corpus: List[Mutant]) -> Dict[str, float]:
        counts = {f: 0 for f in self.seed_fields}
        for m in corpus:
            for f in m.fields_touched:
                if f in counts:
                    counts[f] += 1
        total = max(sum(counts.values()), 1)
        return {f: c / total for f, c in counts.items()}

    def _distinct_findings(self, corpus: List[Mutant]) -> int:
        # A finding is distinct if it hits a field combination not seen before.
        seen = set()
        for m in corpus:
            if m.fitness is not None and m.fitness > 0:
                key = hashlib.sha256(
                    ",".join(sorted(m.fields_touched)).encode()
                ).hexdigest()
                seen.add(key)
        return len(seen)

    def check(self, corpus: List[Mutant], prev_corpus_size: int) -> None:
        if not corpus:
            raise ExploitSynthesisDriftError("empty corpus; cannot evaluate drift")

        # 1. Provenance: orphans must not steer selection.
        orphans = [m for m in corpus if not m.provenance_ok]
        if orphans:
            raise ExploitSynthesisDriftError(
                f"{len(orphans)} orphaned mutants lack provenance to a named "
                f"protocol invariant; quarantine before selection"
            )

        coverage = self._field_coverage(corpus)

        # 2. Diversity floor: every seed field must remain represented.
        starved = [f for f, c in coverage.items() if c < self.config.epsilon]
        if starved:
            raise ExploitSynthesisDriftError(
                f"coverage floor violated for fields {starved}; "
                f"inject fresh seeds for these fields before continuing"
            )

        # 3. Reproduction cap: no single field may dominate parents.
        dominant = [f for f, c in coverage.items() if c > self.config.rho_max]
        if dominant:
            raise ExploitSynthesisDriftError(
                f"field(s) {dominant} exceed rho_max={self.config.rho_max}; "
                f"cap reproduction rate to prevent convergence on one dimension"
            )

        # 4. Coverage collapse across generations.
        if self.history:
            prev = self.history[-1]
            touched_now = sum(1 for c in coverage.values() if c > 0)
            touched_prev = sum(1 for c in prev.values() if c > 0)
            if touched_prev > 0 and touched_now / touched_prev < self.config.coverage_collapse_ratio:
                raise ExploitSynthesisDriftError(
                    f"distinct fields touched collapsed from {touched_prev} to "
                    f"{touched_now}; halt and re-seed from frozen seed set"
                )

        # 5. Volume without novelty.
        size_ratio = len(corpus) / max(prev_corpus_size, 1)
        if size_ratio > self.config.volume_novelty_ratio:
            if self.history and self._distinct_findings(corpus) <= self._distinct_findings(
                # compare against previous generation's finding count is
                # approximated by history length; caller passes prev size
                0  # placeholder replaced below
            ):
                pass  # handled by caller-level novelty check
            raise ExploitSynthesisDriftError(
                f"corpus grew {size_ratio:.1f}x without proportional novel "
                f"findings; freeze, snapshot, and re-seed"
            )

        self.history.append(coverage)


def select_parents(corpus: List[Mutant], guard: DriftGuard, k: int) -> List[Mutant]:
    guard.check(corpus, prev_corpus_size=max(len(corpus) // 2, 1))
    scored = [m for m in corpus if m.fitness is not None]
    if not scored:
        raise ExploitSynthesisDriftError(
            "no scoreable mutants remain; fitness signal is undefined, not zero"
        )
    scored.sort(key=lambda m: m.fitness, reverse=True)
    return scored[:k]
