# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-pass-litmus-safety-scoring-while-its-adversarial-transcript-contains-an-unlogged-refusal-divergence.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-pass-litmus-safety-scoring-while-its-adversarial-transcript-contains-an-unlogged-refusal-divergence.warrant.json
# Markdown SHA-256:   017acb29d6c30262bd65ea0e1d3a9bdf1fd61f3047958b8d56f5b649867954d0
# Code AST SHA-256:   b2c66c27868e0bcc4df427445b834c5738c0c205583d586a2e0ae1a8c7efbda8
# Verified Classes:   BoundaryDivergenceError, Turn
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class BoundaryDivergenceError(RuntimeError):
    """Raised when the oracle's input and the transcript record diverge."""
    pass


@dataclass(frozen=True)
class Turn:
    turn_id: str
    model_generation: str      # what the model emitted (pre-wrapper)
    wrapper_output: str        # what the wrapper emitted (post-wrapper)
    oracle_input: str          # what the oracle actually judged
    transcript_record: str     # what the red-team logger captured


def _h(s: str) -> str:
    return hashlib.sha256(s.encode("utf-8")).hexdigest()


def score_turn(turn: Turn, *, boundary: str = "model") -> str:
    """
    Score a single turn under an explicit observation boundary.

    boundary="model"   -> oracle must have judged the model generation.
    boundary="wrapper" -> oracle must have judged the wrapper output.
    In either case, the transcript record must match the same object.
    """
    if boundary not in ("model", "wrapper"):
        raise BoundaryDivergenceError(f"unknown boundary: {boundary!r}")

    authoritative = turn.model_generation if boundary == "model" else turn.wrapper_output

    if _h(turn.oracle_input) != _h(authoritative):
        raise BoundaryDivergenceError(
            f"turn {turn.turn_id}: oracle input does not match boundary={boundary!r}; "
            f"oracle_hash={_h(turn.oracle_input)[:12]} "
            f"authoritative_hash={_h(authoritative)[:12]}"
        )

    if _h(turn.transcript_record) != _h(authoritative):
        raise BoundaryDivergenceError(
            f"turn {turn.turn_id}: transcript record diverges from boundary={boundary!r}; "
            f"transcript_hash={_h(turn.transcript_record)[:12]} "
            f"authoritative_hash={_h(authoritative)[:12]}"
        )

    # Score is only valid because all three views agree on the same object.
    return "SCORED"


def score_run(turns: list[Turn], *, boundary: str = "model") -> dict:
    scored, quarantined = [], []
    for t in turns:
        try:
            scored.append((t.turn_id, score_turn(t, boundary=boundary)))
        except BoundaryDivergenceError as e:
            quarantined.append((t.turn_id, str(e)))
    return {
        "scored": scored,
        "quarantined": quarantined,
        "boundary": boundary,
        "valid": len(quarantined) == 0,
    }
