# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-scores-harm-against-the-wrong-taxonomy-branch-litmus-elicitation-drift-under-mid-run-taxonomy-remapping.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-scores-harm-against-the-wrong-taxonomy-branch-litmus-elicitation-drift-under-mid-run-taxonomy-remapping.warrant.json
# Markdown SHA-256:   7b22a4f984da0c686e2b5867e88e55e66c98959deb32356b6f9fdf9e049e43cb
# Code AST SHA-256:   4d37e2765f2f5e802e81e04ace2812fae0dc66d8e08df0b08f67ae6fcf8fb7d1
# Verified Classes:   LeafPinningViolation, LeafStamp
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class LeafPinningViolation(RuntimeError):
    """Raised when elicitor and scorer resolve a transcript against divergent taxonomy leaves."""
    pass


@dataclass(frozen=True)
class LeafStamp:
    taxonomy_version: str
    leaf_id: str
    content_hash: str


def stamp_leaf(taxonomy_version: str, leaf_id: str, leaf_definition: str) -> LeafStamp:
    return LeafStamp(
        taxonomy_version=taxonomy_version,
        leaf_id=leaf_id,
        content_hash=hashlib.sha256(leaf_definition.encode()).hexdigest(),
    )


def assert_episode_coherent(
    episode_stamp: LeafStamp,
    elicitor_stamp: LeafStamp,
    scorer_stamp: LeafStamp,
) -> None:
    # ID-equality is insufficient: a remap can reuse leaf_id while changing semantics.
    if not (episode_stamp == elicitor_stamp == scorer_stamp):
        raise LeafPinningViolation(
            "leaf-pinning coherence broken: "
            f"episode={episode_stamp} elicitor={elicitor_stamp} scorer={scorer_stamp}. "
            "Terminate episode and re-elicit; do not re-grade in place."
        )


def grade_transcript(episode_stamp: LeafStamp, scorer_stamp: LeafStamp, transcript: str) -> int:
    assert_episode_coherent(episode_stamp, episode_stamp, scorer_stamp)
    # ... scoring logic against scorer_stamp.leaf_id ...
    return 0


def apply_remap(open_episodes: list[LeafStamp], new_stamp_for: dict[str, LeafStamp]) -> None:
    for ep in open_episodes:
        new = new_stamp_for.get(ep.leaf_id)
        if new is not None and new != ep:
            raise LeafPinningViolation(
                f"remap would change open episode leaf {ep.leaf_id} "
                f"({ep.content_hash[:8]} -> {new.content_hash[:8]}); "
                "episode is poisoned and must be terminated, not re-graded."
            )
