# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-diverges-from-the-litmus-safety-benchmark-harness-s-frozen-scenario-manifest-mid-run.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-diverges-from-the-litmus-safety-benchmark-harness-s-frozen-scenario-manifest-mid-run.warrant.json
# Markdown SHA-256:   83f546a1d4638ebbfc1958f58445632139aa3702118ef3da9f31828c736d6454
# Code AST SHA-256:   31731174750db1da2147ac425e02bf31fc64d027b84d956cae81f3eeb783bf84
# Verified Classes:   ManifestSkewError, ExecutionRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class ManifestSkewError(RuntimeError):
    """Raised when a scenario is scored under a manifest version different
    from the one its instance actually ingested. This is a harness fault,
    not an agent fault, and must trigger re-queue, not quarantine."""
    pass


@dataclass(frozen=True)
class ExecutionRecord:
    scenario_id: str
    manifest_version: str
    manifest_token: str


def compute_manifest_token(manifest_version: str, scenario_id: str) -> str:
    return hashlib.sha256(f"{manifest_version}:{scenario_id}".encode()).hexdigest()[:16]


def score_scenario(
    record: ExecutionRecord,
    current_manifest_version: str,
    transcript: list,
) -> str:
    """Score a completed scenario, asserting manifest continuity first."""
    expected_token = compute_manifest_token(current_manifest_version, record.scenario_id)

    if record.manifest_token != expected_token:
        # The instance executed under a different manifest than the scorer
        # is about to apply. Do NOT score; re-queue for cold re-execution.
        raise ManifestSkewError(
            f"Scenario {record.scenario_id} executed under manifest "
            f"{record.manifest_version} (token {record.manifest_token}) but "
            f"scorer is on {current_manifest_version} (token {expected_token}). "
            f"Re-queue under current manifest; attribute as harness_fault."
        )

    # Safe to score: instance and scorer agree on the contract.
    return _apply_rubric(transcript, current_manifest_version)


def _apply_rubric(transcript: list, manifest_version: str) -> str:
    # Stub: real rubric application lives in the LITMUS scorer.
    return "SAFE" if transcript else "UNSAFE"


def run_epoch(
    records: list[ExecutionRecord],
    current_manifest_version: str,
    transcripts: dict[str, list],
) -> dict[str, str]:
    results: dict[str, str] = {}
    requeue: list[str] = []
    for rec in records:
        try:
            results[rec.scenario_id] = score_scenario(
                rec, current_manifest_version, transcripts[rec.scenario_id]
            )
        except ManifestSkewError as e:
            requeue.append(rec.scenario_id)
            results[rec.scenario_id] = "REQUEUE"
    return {"results": results, "requeue": requeue}
