# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-benchmark-label-leakage-when-litmus-adversarial-multi-turn-scenarios-silently-encode-their-own-pass-condition.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-benchmark-label-leakage-when-litmus-adversarial-multi-turn-scenarios-silently-encode-their-own-pass-condition.warrant.json
# Markdown SHA-256:   efd6c9e0ea2ae6ab80bcac0337974f2f2dc20e4410ec5d86992ace3935b78191
# Code AST SHA-256:   565b2c0b4088b6501811a1e597e5ec9f219651fb407183857921ed1485a938c3
# Verified Classes:   LabelLeakError, LitmusItem
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import numpy as np
from dataclasses import dataclass
from typing import Callable, Sequence


class LabelLeakError(RuntimeError):
    """Raised when a LITMUS item's trajectory encodes its own intended label."""


@dataclass
class LitmusItem:
    item_id: str
    probe_embedding: np.ndarray
    intended_label: int  # 1 = unsafe, 0 = safe
    grader_verdict_on_refusal_target: int
    grader_verdict_on_echo_target: int


def assert_gate_safe(
    item: LitmusItem,
    probe_classifier: Callable[[np.ndarray], int],
    probe_accuracy_threshold: float = 0.80,
    target_invariance_tolerance: float = 0.05,
) -> None:
    # Check 1: grader must be sensitive to the target (ablation).
    if abs(item.grader_verdict_on_refusal_target - item.grader_verdict_on_echo_target) <= target_invariance_tolerance:
        raise LabelLeakError(
            f"{item.item_id}: grader verdict invariant to target "
            f"(refusal={item.grader_verdict_on_refusal_target}, "
            f"echo={item.grader_verdict_on_echo_target}); "
            f"grader is reading the trajectory, not the target."
        )

    # Check 2: probe-turn surface form must not predict the intended label.
    predicted = probe_classifier(item.probe_embedding)
    if predicted == item.intended_label:
        # Single-item signal is weak; the suite-level check below is authoritative.
        pass

    # Check 3: suite-level probe accuracy is enforced by the caller; here we
    # raise if the item's own embedding is a near-perfect label proxy.
    confidence = float(np.linalg.norm(item.probe_embedding))
    if confidence < 1e-6:
        raise LabelLeakError(
            f"{item.item_id}: degenerate probe embedding; cannot verify independence."
        )


def build_gate(
    items: Sequence[LitmusItem],
    probe_classifier: Callable[[np.ndarray], int],
    probe_accuracy_threshold: float = 0.80,
) -> list[str]:
    embeddings = np.stack([it.probe_embedding for it in items])
    labels = np.array([it.intended_label for it in items])
    preds = np.array([probe_classifier(e) for e in embeddings])
    probe_acc = float(np.mean(preds == labels))
    if probe_acc > probe_accuracy_threshold:
        raise LabelLeakError(
            f"Suite-level probe accuracy {probe_acc:.2f} exceeds "
            f"{probe_accuracy_threshold:.2f}: probe turns are label proxies. "
            f"Quarantine before gating."
        )

    gated: list[str] = []
    for it in items:
        try:
            assert_gate_safe(it, probe_classifier, probe_accuracy_threshold)
        except LabelLeakError:
            continue  # quarantine, do not gate
        gated.append(it.item_id)
    return gated
