# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-litmus-safety-regression-harness-has-silently-drifted-its-scoring-baseline.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-litmus-safety-regression-harness-has-silently-drifted-its-scoring-baseline.warrant.json
# Markdown SHA-256:   50aa97466ef1da720cdafbc40aa858e6d61e766caea1e71cfc31aea33da2ca65
# Code AST SHA-256:   b18682787fcf9da9df2cdc98a7b10502c8684bfa09d4e6f896eef3a6b8609f38
# Verified Classes:   BaselineDriftUndetectable, FalseRegressionQuarantine, ScoringEpoch, DriftLedger
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class BaselineDriftUndetectable(RuntimeError):
    """Raised when a safety-score movement cannot be attributed to agent or harness."""
    pass


class FalseRegressionQuarantine(RuntimeError):
    """Raised when a score movement is proven harness-side and must not gate the agent."""
    pass


@dataclass
class ScoringEpoch:
    epoch_id: str
    trajectory_hashes: frozenset[str]
    rubric_hash: str
    baseline_set_hash: str
    verdicts: dict[str, str]  # trajectory_hash -> "pass" | "fail"


@dataclass
class DriftLedger:
    epochs: list[ScoringEpoch] = field(default_factory=list)

    def record(self, epoch: ScoringEpoch) -> None:
        self.epochs.append(epoch)

    def attribute_movement(self, prior: ScoringEpoch, current: ScoringEpoch) -> str:
        if not prior.rubric_hash or not prior.baseline_set_hash:
            raise BaselineDriftUndetectable(
                f"epoch {prior.epoch_id} lacks rubric/baseline hashes; "
                "cannot distinguish agent regression from harness drift"
            )

        traj_changed = prior.trajectory_hashes != current.trajectory_hashes
        rubric_changed = prior.rubric_hash != current.rubric_hash
        baseline_changed = prior.baseline_set_hash != current.baseline_set_hash
        verdicts_changed = prior.verdicts != current.verdicts

        if traj_changed:
            return "agent_side_regression_candidate"

        if not traj_changed and verdicts_changed:
            if rubric_changed or baseline_changed:
                raise FalseRegressionQuarantine(
                    f"score movement between {prior.epoch_id} and {current.epoch_id} "
                    f"is harness-side: trajectories identical, "
                    f"rubric_changed={rubric_changed}, baseline_changed={baseline_changed}. "
                    "Do not gate the agent on this alert."
                )
            raise BaselineDriftUndetectable(
                f"verdicts changed with identical trajectories, rubric, and baseline "
                f"({prior.epoch_id} -> {current.epoch_id}); judge is non-deterministic "
                "and no score from this harness is reproducible"
            )

        return "no_movement"


def hash_trajectories(trajectories: list[dict[str, Any]]) -> frozenset[str]:
    return frozenset(
        hashlib.sha256(
            json.dumps(t, sort_keys=True, separators=(",", ":")).encode()
        ).hexdigest()
        for t in trajectories
    )


def gate_agent_on_alert(
    ledger: DriftLedger,
    prior_epoch_id: str,
    current_epoch_id: str,
) -> str:
    by_id = {e.epoch_id: e for e in ledger.epochs}
    try:
        prior = by_id[prior_epoch_id]
        current = by_id[current_epoch_id]
    except KeyError as exc:
        raise BaselineDriftUndetectable(
            f"missing epoch in ledger: {exc}"
        ) from exc

    attribution = ledger.attribute_movement(prior, current)

    if attribution == "agent_side_regression_candidate":
        return "triage_regression"
    if attribution == "no_movement":
        return "clear_alert"
    raise BaselineDriftUndetectable(
        f"unrecognized attribution {attribution!r}; refusing to gate"
    )
