# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-the-litmus-harness-s-adversarial-seed-replay-diverges-from-the-graded-transcript-the-canary-echo-boundary-in-regressi.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-the-litmus-harness-s-adversarial-seed-replay-diverges-from-the-graded-transcript-the-canary-echo-boundary-in-regressi.warrant.json
# Markdown SHA-256:   f2a57551d09893e54f4d846d5d8d912d4f61f48cdd3ecd3059e01bfea58d0bf3
# Code AST SHA-256:   aff8d4b4c88f337d64a41141b9428d26dd45c3ed654f5ba8ad2f2424518789b4
# Verified Classes:   CanaryDivergenceError, CanaryEmission, SeedReplay
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

Channel = Literal["tool_result", "reasoning", "tool_call_args", "final_answer"]


class CanaryDivergenceError(RuntimeError):
    """Raised when live replay canary emissions diverge from the frozen transcript."""


@dataclass(frozen=True)
class CanaryEmission:
    token: str
    channel: Channel
    turn_index: int


@dataclass
class SeedReplay:
    seed_id: str
    frozen: list[CanaryEmission]
    live: list[CanaryEmission]
    allowed_channels: dict[str, set[Channel]] = field(default_factory=dict)


def _multiset(emissions: list[CanaryEmission]) -> dict[tuple[str, Channel], int]:
    counts: dict[tuple[str, Channel], int] = {}
    for e in emissions:
        key = (e.token, e.channel)
        counts[key] = counts.get(key, 0) + 1
    return counts


def gate_seed(replay: SeedReplay) -> Literal["pass", "pass_with_drift"]:
    """Enforce the canary-echo boundary BEFORE any outcome scorer runs.

    Raises CanaryDivergenceError on any canary-set mismatch. Returns a
    disposition only when the canary multiset is identical between the
    live and frozen transcripts.
    """
    # Channel scoping: a canary outside its allowed channel is a mismatch
    # even if the token also appears in the allowed channel.
    for e in replay.live:
        allowed = replay.allowed_channels.get(e.token)
        if allowed is not None and e.channel not in allowed:
            raise CanaryDivergenceError(
                f"seed={replay.seed_id} canary={e.token!r} emitted in "
                f"disallowed channel={e.channel!r} at turn={e.turn_index}; "
                f"allowed={sorted(allowed)}"
            )

    frozen_ms = _multiset(replay.frozen)
    live_ms = _multiset(replay.live)

    if frozen_ms != live_ms:
        missing = {k: v for k, v in frozen_ms.items() if live_ms.get(k, 0) < v}
        extra = {k: v for k, v in live_ms.items() if frozen_ms.get(k, 0) < v}
        raise CanaryDivergenceError(
            f"seed={replay.seed_id} canary multiset diverged; "
            f"missing={missing} extra={extra}. "
            f"Outcome verdict is not trustworthy; quarantine seed."
        )

    # Canary set matches. Turn-index drift is sampling noise, not a gate.
    frozen_turns = {(e.token, e.channel): e.turn_index for e in replay.frozen}
    live_turns = {(e.token, e.channel): e.turn_index for e in replay.live}
    if frozen_turns != live_turns:
        return "pass_with_drift"
    return "pass"


def run_gate(replays: list[SeedReplay]) -> dict[str, list[str]]:
    """Run the gate over a suite. Halts are collected, never swallowed."""
    report: dict[str, list[str]] = {"pass": [], "pass_with_drift": [], "halted": []}
    for replay in replays:
        try:
            disposition = gate_seed(replay)
            report[disposition].append(replay.seed_id)
        except CanaryDivergenceError as exc:
            # Quarantine, do not score. The exception is recorded, not retried.
            report["halted"].append(f"{replay.seed_id}: {exc}")
    return report
