# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-litmus-adversarial-multi-turn-evaluation-when-the-harm-taxonomy-label-drifts-from-the-fixture-s-declared-tu.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-litmus-adversarial-multi-turn-evaluation-when-the-harm-taxonomy-label-drifts-from-the-fixture-s-declared-tu.warrant.json
# Markdown SHA-256:   0d30b6052a0515cfa6b792518042fe1044c30bd6e98a3a6fede803f29de93aad
# Code AST SHA-256:   c88a62803712e8702faef60d7259d9decdae25a89e686fbf04b27a24996b9dd9
# Verified Classes:   PrefixDriftAbort, TurnFixture
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Callable, Optional


class PrefixDriftAbort(RuntimeError):
    """Raised when a LITMUS fixture's declared prefix no longer matches the
    target's live context at turn delivery, and the drift is not modeled by
    the fixture's normalization allowlist or tolerated by the taxonomy node."""
    pass


@dataclass
class TurnFixture:
    prefix_digest: str
    adversarial_turn: str
    taxonomy_node: str
    boundary_kind: str
    prefix_mutation_tolerant: bool = False


def normalize(context: str, allowlist: frozenset[str]) -> str:
    # Caller-supplied; must be identical for fixture prefix and live context.
    # Here we only strip a modeled refusal-summary marker when allowed.
    if "summarize_on_refusal" in allowlist:
        return "\n".join(
            ln for ln in context.splitlines() if not ln.startswith("[prior turn refused]")
        )
    return context


def check_turn_boundary(
    fixture: TurnFixture,
    live_context: str,
    allowlist: frozenset[str],
    digest_fn: Callable[[str], str] = lambda s: hashlib.sha256(s.encode()).hexdigest(),
) -> str:
    observed = digest_fn(normalize(live_context, allowlist))
    if observed == fixture.prefix_digest:
        return "attributable"

    # Drift detected. Decide whether it is modeled and tolerated.
    modeled = any(k in allowlist for k in ("summarize_on_refusal", "tool_result_injection"))
    if modeled and fixture.prefix_mutation_tolerant:
        return "attributable_conditional"

    raise PrefixDriftAbort(
        f"Unmodeled prefix drift at node {fixture.taxonomy_node} "
        f"(boundary={fixture.boundary_kind}): "
        f"expected {fixture.prefix_digest[:12]}, got {observed[:12]}; "
        f"allowlist={sorted(allowlist)}; "
        f"mutation_tolerant={fixture.prefix_mutation_tolerant}. "
        f"Aborting fixture: label would be non-reproducible."
    )
