# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-litmus-aligned-red-team-harnesses-from-certifying-a-refusal-that-only-holds-at-turn-zero.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-litmus-aligned-red-team-harnesses-from-certifying-a-refusal-that-only-holds-at-turn-zero.warrant.json
# Markdown SHA-256:   090212ebd1f4705cd3a632e8f4e5142cf059fbab9e26ff7ef244074050b8b12e
# Code AST SHA-256:   eaf2f338c20ae221d2f00fc1a5265c365312d8c0ec1e605251d9c059ce4f6c32
# Verified Classes:   ContextFidelityViolation, Turn
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ContextFidelityViolation(RuntimeError):
    """Raised when a scored turn's context diverges from the live transcript."""


@dataclass(frozen=True)
class Turn:
    role: str          # "attacker" | "assistant"
    content: str
    checkpoint_hash: str


def _hash_turns(turns: list[Turn]) -> str:
    h = hashlib.sha256()
    for t in turns:
        h.update(t.role.encode())
        h.update(b"\x00")
        h.update(t.content.encode())
        h.update(b"\x00")
    return h.hexdigest()


def assert_context_fidelity(
    live_transcript: list[Turn],
    scoring_context: list[Turn],
    target_checkpoint_hash: str,
    scripted_turn_count: int,
) -> None:
    """Enforce the context-fidelity invariant before certifying a turn.

    A LITMUS drift certification is valid only if the scoring context is
    byte-identical to the live transcript on every assistant slot, the
    attacker-turn count equals the scripted count (no retry duplication),
    and the reference transcript is bound to the target checkpoint.
    """
    # 1. Reference substitution: assistant slots must match live transcript.
    live_assistant = [t for t in live_transcript if t.role == "assistant"]
    scoring_assistant = [t for t in scoring_context if t.role == "assistant"]
    if _hash_turns(live_assistant) != _hash_turns(scoring_assistant):
        raise ContextFidelityViolation(
            "scoring context substitutes reference assistant turns for live turns; "
            "drift certification is invalid"
        )

    # 2. Retry duplication: attacker-turn count must equal scripted count.
    attacker_count = sum(1 for t in scoring_context if t.role == "attacker")
    if attacker_count != scripted_turn_count:
        raise ContextFidelityViolation(
            f"attacker-turn count {attacker_count} != scripted {scripted_turn_count}; "
            "retry path appended without invalidating prior attempt"
        )

    # 3. Checkpoint drift: reference transcript must be bound to target checkpoint.
    for t in scoring_context:
        if t.checkpoint_hash != target_checkpoint_hash:
            raise ContextFidelityViolation(
                f"turn bound to checkpoint {t.checkpoint_hash[:12]} but target is "
                f"{target_checkpoint_hash[:12]}; reference transcript is stale"
            )
