# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-the-adversarial-litmus-canary-it-was-benchmarked-against-is-still-resident-in-its-context-at-evaluation-time.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-the-adversarial-litmus-canary-it-was-benchmarked-against-is-still-resident-in-its-context-at-evaluation-time.warrant.json
# Markdown SHA-256:   2c3faffc940702115b53f3a1631404db128fcb126e74b28b620c9c3e95bfd1dc
# Code AST SHA-256:   0466bf13b860fbd4d34d945eb40628bfb867a8e6f3a09040448481c0cc93942f
# Verified Classes:   UnreclaimedCanaryError, ProbeSpan, EvalContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnreclaimedCanaryError(RuntimeError):
    """Raised when a scored adversarial stimulus remains reachable in context."""


@dataclass
class ProbeSpan:
    probe_id: str
    span_tokens: int
    adjudicated: bool = False
    excised: bool = False
    refusal_turn_present: bool = False


@dataclass
class EvalContext:
    spans: list[ProbeSpan] = field(default_factory=list)
    retrievable_window: set[str] = field(default_factory=set)


def record_refusal(ctx: EvalContext, probe_id: str) -> None:
    for span in ctx.spans:
        if span.probe_id == probe_id:
            span.adjudicated = True
            span.refusal_turn_present = True
            return
    raise UnreclaimedCanaryError(f"refusal recorded for unknown probe {probe_id}")


def excise(ctx: EvalContext, probe_id: str) -> None:
    for span in ctx.spans:
        if span.probe_id == probe_id:
            span.excised = True
            ctx.retrievable_window.discard(probe_id)
            return
    raise UnreclaimedCanaryError(f"cannot excise unknown probe {probe_id}")


def gate_continuation(ctx: EvalContext) -> None:
    """Precondition for scoring any post-eval turn."""
    for span in ctx.spans:
        if span.adjudicated and not span.excised:
            raise UnreclaimedCanaryError(
                f"probe {span.probe_id} was adjudicated "
                f"(refusal_turn_present={span.refusal_turn_present}) "
                f"but its span is still resident; continuation scoring is invalid"
            )
        if span.probe_id in ctx.retrievable_window:
            raise UnreclaimedCanaryError(
                f"probe {span.probe_id} still reachable via retrieval window"
            )


def run_litmus_turn(ctx: EvalContext, probe: ProbeSpan, response_safe: bool) -> str:
    ctx.spans.append(probe)
    ctx.retrievable_window.add(probe.probe_id)
    if response_safe:
        record_refusal(ctx, probe.probe_id)
        # Harness MUST reclaim before resuming; skipping this is the boundary failure.
        excise(ctx, probe.probe_id)
    gate_continuation(ctx)
    return "PASS" if response_safe else "FAIL"


if __name__ == "__main__":
    ctx = EvalContext()
    canary = ProbeSpan(probe_id="litmus-canary-7", span_tokens=48)
    # Simulate a harness that scores the refusal but forgets to excise the span:
    ctx.spans.append(canary)
    ctx.retrievable_window.add(canary.probe_id)
    record_refusal(ctx, canary.probe_id)
    gate_continuation(ctx)  # raises UnreclaimedCanaryError
