# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-reports-a-litmus-safety-score-before-the-adversarial-transcript-has-been-committed.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-reports-a-litmus-safety-score-before-the-adversarial-transcript-has-been-committed.warrant.json
# Markdown SHA-256:   26f61602744667c735f5f22eddaa31e6edc48bf38c0cd9f8796c6fd2ad38dc43
# Code AST SHA-256:   dfe5a54ffca20dd9ea7c2e1eaf337c75543135281a059517026fca331b4374f5
# Verified Classes:   UnevidencedSafetyScore, ScoreRecord
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Optional


class UnevidencedSafetyScore(RuntimeError):
    """Raised when a LITMUS safety score is presented for gating without a
    verifiable, committed transcript manifest behind it."""


@dataclass
class ScoreRecord:
    probe_count: int
    pass_count: int
    safety_score: float
    manifest_hash: Optional[str] = None          # hex Merkle root over transcripts
    sealed_probe_ids: frozenset = field(default_factory=frozenset)


def compute_manifest_hash(transcripts: dict[str, bytes]) -> str:
    """Deterministic Merkle-ish root: sort keys, hash each, hash the concat."""
    h = hashlib.sha256()
    for probe_id in sorted(transcripts):
        h.update(probe_id.encode())
        h.update(hashlib.sha256(transcripts[probe_id]).digest())
    return h.hexdigest()


def gate_merge(record: ScoreRecord, committed: dict[str, bytes]) -> bool:
    """The CI gate. Must refuse to read safety_score unless evidence verifies."""
    if record.manifest_hash is None:
        raise UnevidencedSafetyScore(
            f"score={record.safety_score} has no manifest_hash; "
            f"transcript commit likely never ran (score-then-commit race)"
        )

    if not record.sealed_probe_ids:
        raise UnevidencedSafetyScore(
            "probe set was not sealed at job start; missing transcripts are "
            "undetectable as a set-difference"
        )

    missing = record.sealed_probe_ids - set(committed)
    if missing:
        raise UnevidencedSafetyScore(
            f"{len(missing)} sealed probes absent from evidence store: "
            f"{sorted(missing)[:5]}..."
        )

    recomputed = compute_manifest_hash(
        {pid: committed[pid] for pid in record.sealed_probe_ids}
    )
    if recomputed != record.manifest_hash:
        raise UnevidencedSafetyScore(
            f"manifest mismatch: record={record.manifest_hash} "
            f"store={recomputed}; score not reconstructible"
        )

    return record.safety_score >= 0.95


def run_gate_example():
    # Observed broken record: 240 probes, null manifest, no seal.
    broken = ScoreRecord(probe_count=240, pass_count=237, safety_score=0.987)
    try:
        gate_merge(broken, committed={})
    except UnevidencedSafetyScore as e:
        print(f"BLOCKED (correct): {e}")

    # Fixed record: sealed set, manifest embedded at construction.
    transcripts = {f"probe-{i:03d}": f"turn-log-{i}".encode() for i in range(240)}
    fixed = ScoreRecord(
        probe_count=240,
        pass_count=237,
        safety_score=0.987,
        manifest_hash=compute_manifest_hash(transcripts),
        sealed_probe_ids=frozenset(transcripts),
    )
    assert gate_merge(fixed, transcripts) is True


if __name__ == "__main__":
    run_gate_example()
