# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-passes-the-litmus-probe-but-the-harness-scores-a-stale-transcript-the-transcript-binding-invariant-in-continuous-red-tea.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-passes-the-litmus-probe-but-the-harness-scores-a-stale-transcript-the-transcript-binding-invariant-in-continuous-red-tea.warrant.json
# Markdown SHA-256:   3db7f90f5f36c3ee28ba073d827424bf2d0f0270c7aeb447818ac1b3ff07103d
# Code AST SHA-256:   a212f3706e95338ab23a1bbcf40b201c8710cc75cba3c9f48c5f7b92fb464d0a
# Verified Classes:   TranscriptBindingError, ProbeRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class TranscriptBindingError(RuntimeError):
    """Raised when a LITMUS probe verdict cannot be bound to a single live agent response."""
    pass


@dataclass(frozen=True)
class ProbeRecord:
    probe_id: str
    instance_id: str
    session_id: str
    turn_epoch: int
    transcript: bytes
    agent_emitted_hash: str
    partial_write: bool = False


def bind_and_score(record: ProbeRecord, scorer) -> str:
    # Invariant: verdict is valid only for a single-epoch, fully-written,
    # hash-matched transcript. Anything else is INCONCLUSIVE, never PASS.
    if record.partial_write:
        raise TranscriptBindingError(
            f"probe {record.probe_id}: partial write under session "
            f"{record.session_id} epoch {record.turn_epoch}; refusing to score"
        )

    computed = hashlib.sha256(record.transcript).hexdigest()
    if computed != record.agent_emitted_hash:
        raise TranscriptBindingError(
            f"probe {record.probe_id}: transcript hash mismatch "
            f"(agent={record.agent_emitted_hash[:12]} store={computed[:12]}); "
            f"record may span multiple turn_epochs after checkpoint/resume"
        )

    # Only now is the transcript provably bound to the live response.
    verdict = scorer(record.transcript)
    if verdict not in ("PASS", "FAIL"):
        raise TranscriptBindingError(
            f"probe {record.probe_id}: scorer returned {verdict!r}, expected PASS/FAIL"
        )
    return verdict
