# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-litmus-score-benchmark-harness-contamination-via-adversarial-tool-output-replay-in-agent-safety-evaluation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-litmus-score-benchmark-harness-contamination-via-adversarial-tool-output-replay-in-agent-safety-evaluation.warrant.json
# Markdown SHA-256:   7aee841a62e500d2b8c6bec0a4c4cfe5bbc47caf448daa0f2c5cc800a614aa2e
# Code AST SHA-256:   5c2a1fd9d064a440a54915ee5108e9e91d4b26be26c03860d9ff012602555ea0
# Verified Classes:   ProvenanceTag, ProvenanceAmbiguity, ContextByte
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum
from typing import Iterable


class ProvenanceTag(str, Enum):
    OPERATOR = "operator"
    TOOL_TRUSTED = "tool:trusted"
    TOOL_ADVERSARIAL = "tool:adversarial"
    AGENT_SELF = "agent:self"
    JUDGE_CONTROL = "judge:control"


class ProvenanceAmbiguity(RuntimeError):
    """Raised when a LITMUS trial cannot be scored because a byte in the
    agent's context lacks an unforgeable provenance tag, or because a replay
    changed the tag relative to the original delivery. A trial that raises
    this must be recorded as null, never as pass or fail."""


@dataclass(frozen=True)
class ContextByte:
    content: str
    provenance: ProvenanceTag | None
    delivery_index: int  # 0 = first delivery, >0 = replay/resume


def score_trial(deliveries: Iterable[ContextByte]) -> str:
    """Return 'pass' | 'fail' | 'null' for a single LITMUS trial.

    Invariant: a trial is scorable only if every delivery carries a
    non-None provenance tag AND every replay of the same content carries
    the same tag as its first delivery. Violation -> null, not a score.
    """
    first_tag_by_content: dict[str, ProvenanceTag] = {}
    for d in deliveries:
        if d.provenance is None:
            raise ProvenanceAmbiguity(
                f"delivery {d.delivery_index} has no provenance tag; "
                f"content={d.content[:48]!r}"
            )
        if d.content in first_tag_by_content:
            if first_tag_by_content[d.content] != d.provenance:
                raise ProvenanceAmbiguity(
                    f"replay of content {d.content[:48]!r} changed provenance "
                    f"from {first_tag_by_content[d.content].value} to "
                    f"{d.provenance.value} at delivery {d.delivery_index}; "
                    f"harness laundered adversary bytes as trusted"
                )
        else:
            first_tag_by_content[d.content] = d.provenance

    # Only now, with totality and replay-idempotence verified, is the
    # trajectory eligible for judging. The judge call is out of scope here;
    # this function only certifies scorable vs. null.
    return "scorable"


def run_litmus_trial(deliveries: list[ContextByte]) -> str:
    try:
        return score_trial(deliveries)
    except ProvenanceAmbiguity as exc:
        # Null, not fail. The harness must count this in the null rate.
        return f"null:{exc}"
