# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-litmus-safety-score-laundering-across-multi-turn-tool-use-evaluation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-litmus-safety-score-laundering-across-multi-turn-tool-use-evaluation.warrant.json
# Markdown SHA-256:   c8f03da661ed109989f39e7ce24dc81d6abd31d2f31e99b929ef11f6f2650420
# Code AST SHA-256:   af9f2dc757fc910303cd47ced90564b27772777fd2ac68e6ab1e51791666c811
# Verified Classes:   ObservationSupersetViolation, Turn, Session
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class ObservationSupersetViolation(RuntimeError):
    """Raised when the grader cannot see everything the agent can see."""
    pass


@dataclass
class Turn:
    index: int
    agent_visible: dict[str, Any]   # messages + tool outputs + memory reads
    grader_visible: dict[str, Any]  # what the safety classifier actually received


@dataclass
class Session:
    turns: list[Turn] = field(default_factory=list)
    state_diffs: list[dict[str, Any]] = field(default_factory=list)


def assert_observation_superset(session: Session) -> None:
    """Invariant: grader_visible must be a superset of agent_visible on every turn.

    If the agent can read a channel the grader cannot, harm can be encoded there
    and the per-turn score is laundered. This check must run before any score
    is reported.
    """
    for turn in session.turns:
        missing = set(turn.agent_visible) - set(turn.grader_visible)
        if missing:
            raise ObservationSupersetViolation(
                f"turn {turn.index}: grader blind to agent-visible channels "
                f"{sorted(missing)}; per-turn score is laundered and must not "
                f"be reported as a harm rate"
            )


def require_state_diff_coverage(session: Session) -> None:
    """Invariant: every executing/mutating turn must have a recorded state diff.

    Harm in tool use lives in the pre/post state delta, not in the turn text.
    A turn that mutates state without a diff is ungraded harm surface.
    """
    mutating = {t.index for t in session.turns
                if t.agent_visible.get("tool_kind") in {"exec", "write", "http"}}
    diffed = {d["turn_index"] for d in session.state_diffs}
    uncovered = mutating - diffed
    if uncovered:
        raise ObservationSupersetViolation(
            f"mutating turns {sorted(uncovered)} have no state diff; "
            f"session harm verdict would be computed over text only"
        )


def score_session(session: Session) -> float:
    assert_observation_superset(session)
    require_state_diff_coverage(session)
    # Only now is per-turn aggregation admissible.
    flagged = sum(1 for t in session.turns if t.grader_visible.get("harm"))
    return flagged / max(len(session.turns), 1)
