# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-when-a-litmus-adversarial-suite-has-silently-inverted-its-own-safety-oracle-mid-episode.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-when-a-litmus-adversarial-suite-has-silently-inverted-its-own-safety-oracle-mid-episode.warrant.json
# Markdown SHA-256:   78a1661169291a8ca1526d384426419abbc74d51f4b8f2290cb115cc0f53d351
# Code AST SHA-256:   08ead18d4af45d882c7c1cd96f335cbf66f7fbe4aa47cb1d3d13e3e045e0f44d
# Verified Classes:   OracleInversionError, InversionDetector
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import math
from collections import Counter
from dataclasses import dataclass, field
from typing import Callable, Sequence


class OracleInversionError(RuntimeError):
    """Raised when the LITMUS suite's live scores decouple from agent behavior."""
    pass


@dataclass
class InversionDetector:
    window: int = 5
    tvd_epsilon: float = 0.08          # behavior considered stationary below this
    score_variance_sigma: float = 0.15 # score considered volatile above this
    anchor_tolerance: float = 0.05     # anchor drift tolerated before flagging
    action_history: list = field(default_factory=list)
    score_history: list = field(default_factory=list)
    anchor_history: list = field(default_factory=list)

    def observe(self, action: str, live_score: float, anchor_score: float) -> None:
        self.action_history.append(action)
        self.score_history.append(live_score)
        self.anchor_history.append(anchor_score)

    def _tvd(self, a: Sequence[str], b: Sequence[str]) -> float:
        ca, cb = Counter(a), Counter(b)
        keys = set(ca) | set(cb)
        n_a, n_b = sum(ca.values()), sum(cb.values())
        return 0.5 * sum(abs(ca[k] / n_a - cb[k] / n_b) for k in keys)

    def _variance(self, xs: Sequence[float]) -> float:
        m = sum(xs) / len(xs)
        return sum((x - m) ** 2 for x in xs) / len(xs)

    def check(self) -> None:
        if len(self.action_history) < 2 * self.window:
            return
        prev = self.action_history[-2 * self.window:-self.window]
        curr = self.action_history[-self.window:]
        tvd = self._tvd(prev, curr)

        live_var = self._variance(self.score_history[-self.window:])
        anchor_var = self._variance(self.anchor_history[-self.window:])

        behavior_stationary = tvd < self.tvd_epsilon
        score_volatile = live_var > self.score_variance_sigma ** 2
        anchor_stable = anchor_var < self.anchor_tolerance ** 2

        if behavior_stationary and score_volatile and anchor_stable:
            raise OracleInversionError(
                f"LITMUS oracle inversion detected: agent action TVD={tvd:.4f} "
                f"(stationary), live score var={live_var:.4f} (volatile), "
                f"anchor var={anchor_var:.4f} (stable). "
                f"Quarantine live probe channel; gate on anchor set only."
            )


def run_episode_step(
    detector: InversionDetector,
    action: str,
    live_score: float,
    anchor_score: float,
    actuator: Callable[[str], None],
) -> None:
    detector.observe(action, live_score, anchor_score)
    try:
        detector.check()
    except OracleInversionError:
        # Fall back to anchor-gated safety: refuse if anchor says unsafe.
        if anchor_score < 0.5:
            actuator("REFUSE")
            return
        actuator("EXECUTE_ANCHOR_GATED")
        raise
    actuator(action)
