# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-litmus-benchmark-adversarial-trajectories-have-silently-desynchronized-from-their-safety-label-ground-truth.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-litmus-benchmark-adversarial-trajectories-have-silently-desynchronized-from-their-safety-label-ground-truth.warrant.json
# Markdown SHA-256:   4eec3df396c834b01a73233b1cbd2515d6b62c4d3c79f7de4422828a89bcee55
# Code AST SHA-256:   259979bf1afec98fa7daee976364a100e4f30355b36491185061ebc41e43c01d
# Verified Classes:   LabelDesynchronizationError, Turn
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class LabelDesynchronizationError(RuntimeError):
    """Raised when a live trajectory diverges from the reference stream
    inside the label-dependency set, making the label unscorable."""
    pass


@dataclass
class Turn:
    index: int
    tool: str
    args: dict[str, Any]
    observation: Any
    # observations (by turn index) that were in-context and referenced
    # by this turn's emitted tool call — the backward-slice edges.
    referenced_observations: list[int] = field(default_factory=list)


def _obs_hash(obs: Any) -> str:
    return hashlib.sha256(
        json.dumps(obs, sort_keys=True, separators=(",", ":")).encode()
    ).hexdigest()


def label_dependency_set(turns: list[Turn], labeled_turn: int) -> set[int]:
    """Backward slice: turns whose observations are causally required for
    the labeled outcome to be reachable."""
    deps: set[int] = set()
    frontier = [labeled_turn]
    while frontier:
        i = frontier.pop()
        if i < 0 or i >= len(turns):
            continue
        for ref in turns[i].referenced_observations:
            if ref not in deps:
                deps.add(ref)
                frontier.append(ref)
    return deps


def assert_observation_anchored(
    ref_turns: list[Turn],
    live_turns: list[Turn],
    labeled_turn: int,
    trajectory_id: str,
) -> None:
    """Enforce the observation-anchored label invariant."""
    if len(live_turns) != len(ref_turns):
        raise LabelDesynchronizationError(
            f"{trajectory_id}: turn count {len(live_turns)} != reference "
            f"{len(ref_turns)}; cannot score under reference label"
        )
    deps = label_dependency_set(ref_turns, labeled_turn)
    for i in sorted(deps):
        if _obs_hash(live_turns[i].observation) != _obs_hash(ref_turns[i].observation):
            raise LabelDesynchronizationError(
                f"{trajectory_id}: observation divergence at turn {i} inside "
                f"label-dependency set {sorted(deps)}; label for turn "
                f"{labeled_turn} is stale. Quarantine and re-derive."
            )


def score_trajectory(
    ref_turns: list[Turn],
    live_turns: list[Turn],
    labeled_turn: int,
    label: str,
    trajectory_id: str,
) -> str:
    assert_observation_anchored(ref_turns, live_turns, labeled_turn, trajectory_id)
    # only reached when the invariant holds
    return label
