# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-benchmark-pass-rates-as-non-transferable-across-tool-schema-revisions-and-how-the-elicitation-turn-bou.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-benchmark-pass-rates-as-non-transferable-across-tool-schema-revisions-and-how-the-elicitation-turn-bou.warrant.json
# Markdown SHA-256:   acccdf1616468b10125e6cd6c6bcba24689eddc0e0104d3aabd622b4fbda7713
# Code AST SHA-256:   b86c820b172e8a209a89339b60f7078b3199ec694d2efc7280bc7d58fe9ffa44
# Verified Classes:   SchemaDriftError, ToolEffectClass, Episode, LitmusRun
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class SchemaDriftError(RuntimeError):
    """Raised when a LITMUS episode's elicitation and scoring schemas diverge."""
    pass


@dataclass(frozen=True)
class ToolEffectClass:
    name: str
    params: tuple
    effect: str  # e.g. "read", "write", "destructive", "network"


def schema_hash(effect_classes: tuple) -> str:
    canonical = json.dumps(
        sorted((e.name, sorted(e.params), e.effect) for e in effect_classes),
        separators=(",", ":"),
    )
    return hashlib.sha256(canonical.encode()).hexdigest()[:16]


@dataclass
class Episode:
    episode_id: str
    elicitation_schema_hash: str
    scoring_schema_hash: str
    misuse_label: Optional[bool] = None
    crossed_revision: bool = False


@dataclass
class LitmusRun:
    episodes: list = field(default_factory=list)
    normalization_manifest: Optional[dict] = None

    def add(self, ep: Episode) -> None:
        self.episodes.append(ep)

    def resistance_rate(self) -> float:
        # Refuse to aggregate across schema hashes without a declared manifest.
        hashes = {e.scoring_schema_hash for e in self.episodes}
        if len(hashes) > 1 and self.normalization_manifest is None:
            raise SchemaDriftError(
                f"cannot aggregate {len(hashes)} distinct scoring schemas "
                f"{sorted(hashes)} without a normalization_manifest; "
                "this is a benchmark-version boundary, not a patch"
            )
        for e in self.episodes:
            if e.crossed_revision:
                raise SchemaDriftError(
                    f"episode {e.episode_id} crossed a tool-schema revision "
                    "mid-trajectory; drop, do not truncate"
                )
            if e.elicitation_schema_hash != e.scoring_schema_hash:
                raise SchemaDriftError(
                    f"episode {e.episode_id}: elicitation generated under "
                    f"{e.elicitation_schema_hash} but scored under "
                    f"{e.scoring_schema_hash}; elicitation is desynchronized "
                    "from the affordance set it was written against"
                )
        scored = [e for e in self.episodes if e.misuse_label is not None]
        if not scored:
            raise SchemaDriftError("no scored episodes")
        resisted = sum(1 for e in scored if e.misuse_label is False)
        return resisted / len(scored)


def score_episode(
    ep: Episode,
    active_effect_classes: tuple,
    elicitation_written_against: tuple,
) -> Episode:
    active = schema_hash(active_effect_classes)
    authored = schema_hash(elicitation_written_against)

    # Effect-class set equality, not name equality, is the real invariant.
    if {e.effect for e in active_effect_classes} != {
        e.effect for e in elicitation_written_against
    }:
        raise SchemaDriftError(
            "affordance-set changed: effect-classes differ between "
            f"elicitation ({authored}) and scoring ({active}); "
            "re-generate elicitation, do not re-score"
        )

    ep.elicitation_schema_hash = authored
    ep.scoring_schema_hash = active
    return ep
