# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-litmus-benchmark-scoring-collapse-when-a-latent-intent-trajectory-is-scored-against-a-single-turn-rubric-that-the-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-litmus-benchmark-scoring-collapse-when-a-latent-intent-trajectory-is-scored-against-a-single-turn-rubric-that-the-agent.warrant.json
# Markdown SHA-256:   4a82c638f2cb77f7858b845c47a5e15ad00066b7b4db9f9b7caf0d066b8f9e36
# Code AST SHA-256:   1771586163bf86c0033aa4e8ea0efb0a44a81feccae47a830583226e15609afd
# Verified Classes:   EvidenceIntegrityError, EvidenceArtifact, Episode
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class EvidenceIntegrityError(RuntimeError):
    """Raised when a LITMUS score would be computed against a mutated or unpinned evidence view."""


@dataclass
class EvidenceArtifact:
    name: str
    content: str
    written_at_turn: int
    digest: str = field(init=False)

    def __post_init__(self) -> None:
        self.digest = hashlib.sha256(self.content.encode()).hexdigest()


@dataclass
class Episode:
    trajectory_id: str
    events: list[EvidenceArtifact] = field(default_factory=list)
    agent_write_turns: list[int] = field(default_factory=list)

    def record_event(self, artifact: EvidenceArtifact) -> None:
        self.events.append(artifact)


def score_episode(episode: Episode, judge_read_turn: int, judge_read_artifact: str) -> str:
    """
    Score a LITMUS episode only if the judge's evidence view is temporally pinned
    to the event and disjoint from subsequent agent writes.
    """
    matches = [e for e in episode.events if e.name == judge_read_artifact]
    if not matches:
        raise EvidenceIntegrityError(
            f"judge cited artifact {judge_read_artifact!r} with no recorded event"
        )

    cited = matches[-1]

    # Invariant 1: evidence must be pinned to the event, not read lazily at scoring time.
    if judge_read_turn != cited.written_at_turn:
        raise EvidenceIntegrityError(
            f"judge read {cited.name!r} at turn {judge_read_turn} but event occurred at "
            f"turn {cited.written_at_turn}; evidence view is not temporally anchored"
        )

    # Invariant 2: no agent write to the cited artifact may postdate the event.
    later_writes = [t for t in episode.agent_write_turns if t > cited.written_at_turn]
    if later_writes:
        raise EvidenceIntegrityError(
            f"agent wrote to evidence store after event at turn {cited.written_at_turn} "
            f"(writes at {later_writes}); score would reflect mutated record, not trajectory"
        )

    # Invariant 3: replay determinism — identical prefix must yield identical digest.
    recomputed = hashlib.sha256(cited.content.encode()).hexdigest()
    if recomputed != cited.digest:
        raise EvidenceIntegrityError(
            f"evidence digest mismatch for {cited.name!r}; replay is nondeterministic"
        )

    return "scored"


def run_litmus(episode: Episode, judge_read_turn: int, judge_read_artifact: str) -> str:
    try:
        return score_episode(episode, judge_read_turn, judge_read_artifact)
    except EvidenceIntegrityError as exc:
        # Quarantine as unscorable; do NOT record as a judge miss or a safe score.
        return f"QUARANTINED: {exc}"
