# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-misreport-safety-drift-when-litmus-probes-are-scored-after-context-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-misreport-safety-drift-when-litmus-probes-are-scored-after-context-compaction.warrant.json
# Markdown SHA-256:   045f3adc7689519536d1bb93f206369ba80fc3324f500e72e0e50cb59eb0432a
# Code AST SHA-256:   9a85e6e959f41fe3e5bf909eec7b6906ed6b0354d95c10bf1245eea109406f2d
# Verified Classes:   ProbeIntegrityViolation, ScoredResponse
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass

class ProbeIntegrityViolation(RuntimeError):
    """Raised when a scored response's presented probe text does not match the canonical probe."""
    pass

@dataclass
class ScoredResponse:
    probe_id: str
    presented_text: str
    response_text: str
    compaction_annotated: bool

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

def verify_and_score(
    scored: ScoredResponse,
    canonical_probes: dict[str, str],
    rubric_fn,
) -> float:
    if scored.probe_id not in canonical_probes:
        raise ProbeIntegrityViolation(
            f"probe_id {scored.probe_id!r} not in canonical corpus; "
            "response was backfilled or misassigned"
        )
    expected = canonical_hash(canonical_probes[scored.probe_id])
    actual = canonical_hash(scored.presented_text)
    if expected != actual:
        raise ProbeIntegrityViolation(
            f"probe {scored.probe_id!r} presented text hash {actual[:12]} != "
            f"canonical {expected[:12]}; compaction likely mutated the probe. "
            f"compaction_annotated={scored.compaction_annotated}"
        )
    return rubric_fn(scored.probe_id, scored.response_text)

def score_suite(
    responses: list[ScoredResponse],
    canonical_probes: dict[str, str],
    rubric_fn,
) -> dict:
    clean, quarantined = [], []
    for r in responses:
        try:
            clean.append(verify_and_score(r, canonical_probes, rubric_fn))
        except ProbeIntegrityViolation as e:
            quarantined.append({"probe_id": r.probe_id, "reason": str(e)})
    if not clean:
        raise ProbeIntegrityViolation(
            "all probes quarantined; drift score is undefined, not zero"
        )
    return {
        "drift_score": sum(clean) / len(clean),
        "clean_count": len(clean),
        "quarantined": quarantined,
        "measurement_valid": len(quarantined) == 0,
    }
