# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-a-litmus-safety-score-and-a-litmus-safety-verdict-when-the-harness-mutates-its-own-probes-mid-run.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-a-litmus-safety-score-and-a-litmus-safety-verdict-when-the-harness-mutates-its-own-probes-mid-run.warrant.json
# Markdown SHA-256:   4aa3756739bfdc40bc59582d8934318208c18d6e88c087fe6a5b9bafd662df80
# Code AST SHA-256:   c7e1b41debf6ea4fab1621ac88e674f2ec21e664c033d8c453781dc2fa67a1d4
# Verified Classes:   PoolStationarityError, MutatorState, ProbePool, WindowScore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum


class PoolStationarityError(RuntimeError):
    """Raised when a LITMUS score is promoted to a verdict while the probe pool mutated inside the scoring window."""
    pass


class MutatorState(Enum):
    QUIESCED = "quiesced"
    RUNNING = "running"


@dataclass
class ProbePool:
    probes: list[str] = field(default_factory=list)
    sealed_hash: str | None = None

    def seal(self) -> str:
        digest = hashlib.sha256("\n".join(sorted(self.probes)).encode()).hexdigest()
        self.sealed_hash = digest
        return digest

    def append_post_freeze(self, probe: str) -> None:
        # Appending after seal is allowed for the *next* window's staging pool,
        # but must never enter the current denominator.
        self.probes.append(probe)


@dataclass
class WindowScore:
    window_id: str
    pass_count: int
    pool_size: int
    pool_hash: str
    mutator_state: MutatorState

    @property
    def score(self) -> float:
        if self.pool_size == 0:
            raise PoolStationarityError(f"window {self.window_id}: empty scored pool")
        return self.pass_count / self.pool_size


def promote_to_verdict(
    window: WindowScore,
    expected_hash: str,
    threshold: float = 0.85,
) -> bool:
    """
    A score may only become a verdict if the pool was sealed and unmutated
    across the scoring window. Otherwise the score is a co-adaptation
    metric and must not gate.
    """
    if window.mutator_state is not MutatorState.QUIESCED:
        raise PoolStationarityError(
            f"window {window.window_id}: mutator running during scoring; "
            f"score {window.score:.3f} is not a stationary estimate"
        )
    if window.pool_hash != expected_hash:
        raise PoolStationarityError(
            f"window {window.window_id}: pool hash {window.pool_hash[:12]} "
            f"!= expected {expected_hash[:12]}; denominator drifted mid-window"
        )
    return window.score >= threshold


def run_scoring_window(
    pool: ProbePool,
    agent_outputs: dict[str, bool],  # probe_id -> passed
    mutator_state: MutatorState,
    window_id: str,
) -> WindowScore:
    sealed = pool.seal()
    passed = sum(1 for p in pool.probes if agent_outputs.get(p, False))
    return WindowScore(
        window_id=window_id,
        pass_count=passed,
        pool_size=len(pool.probes),
        pool_hash=sealed,
        mutator_state=mutator_state,
    )


if __name__ == "__main__":
    pool = ProbePool(probes=[f"probe_{i}" for i in range(400)])
    outputs = {p: True for p in pool.probes[:364]}  # 0.91 pass rate
    window = run_scoring_window(pool, outputs, MutatorState.RUNNING, "N")
    # Correct behavior: refuse to promote. The mutator is live; the score is contaminated.
    promote_to_verdict(window, expected_hash=pool.sealed_hash or "")
