# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-refusal-calibration-drift-when-a-litmus-harness-mutates-its-own-scoring-rubric-mid-episode.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-refusal-calibration-drift-when-a-litmus-harness-mutates-its-own-scoring-rubric-mid-episode.warrant.json
# Markdown SHA-256:   de2e7664e7124acdeb4300f4134935f98c2ff018ef19a33d257a0ce9f1102f67
# Code AST SHA-256:   7e80383087ecb2667e4dc03ed6f619855fb64a250baa3ed0d9db2c249d69be2a
# Verified Classes:   RubricDriftError, EpisodeRecord, Scorecard, RubricSnapshot
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class RubricDriftError(RuntimeError):
    """Raised when a scorecard is scored under a rubric version different
    from the one in force at episode start, invalidating calibration signal."""
    pass


@dataclass
class EpisodeRecord:
    episode_id: str
    rubric_version: str
    invoked_tools: list[str] = field(default_factory=list)


@dataclass
class Scorecard:
    episode_id: str
    score_rubric_version: str
    per_step_expected: dict[int, str]  # step_id -> "REFUSE" | "COMPLY"
    per_step_actual: dict[int, str]


@dataclass
class RubricSnapshot:
    version: str
    tool_classification: dict[str, str]  # tool -> "SAFE_READ" | "DUAL_USE" | ...


def classify_scorecard(
    episode: EpisodeRecord,
    scorecard: Scorecard,
    episode_rubric: RubricSnapshot,
    score_rubric: RubricSnapshot,
) -> str:
    """
    Returns one of: "ACCEPT", "PROVISIONAL", "UNATTRIBUTABLE".
    Raises RubricDriftError if drift is detected on an invoked tool and the
    caller attempts to accept the score as calibration signal.
    """
    if episode.episode_id != scorecard.episode_id:
        raise RubricDriftError(
            f"episode_id mismatch: {episode.episode_id} vs {scorecard.episode_id}"
        )

    if episode.rubric_version == scorecard.score_rubric_version:
        return "ACCEPT"

    # Version mismatch: find invoked tools whose classification changed.
    drifted_tools = []
    for tool in episode.invoked_tools:
        old = episode_rubric.tool_classification.get(tool)
        new = score_rubric.tool_classification.get(tool)
        if old != new:
            drifted_tools.append((tool, old, new))

    if not drifted_tools:
        # Rubric changed, but nothing the agent touched was reclassified.
        return "PROVISIONAL"

    # Drift touched an invoked tool: the score cannot be attributed to the agent.
    # Any attempt to treat it as calibration signal must fail loudly.
    raise RubricDriftError(
        "rubric drift on invoked tools: "
        + "; ".join(f"{t}: {o}->{n}" for t, o, n in drifted_tools)
        + f" (episode rubric={episode.rubric_version}, score rubric={scorecard.score_rubric_version})"
    )


def update_policy_from_scorecard(
    episode: EpisodeRecord,
    scorecard: Scorecard,
    episode_rubric: RubricSnapshot,
    score_rubric: RubricSnapshot,
    policy: dict,
) -> dict:
    verdict = classify_scorecard(episode, scorecard, episode_rubric, score_rubric)
    if verdict != "ACCEPT":
        # Do not mutate policy on provisional or unattributable scores.
        policy.setdefault("quarantined", []).append(
            {"episode_id": episode.episode_id, "verdict": verdict}
        )
        return policy
    # ... apply legitimate calibration delta ...
    return policy
