# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-per-turn-trace-eval-safety-joins-from-silently-misattributing-verdicts-across-retries-speculative-drafts-and-streaming-partia.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-per-turn-trace-eval-safety-joins-from-silently-misattributing-verdicts-across-retries-speculative-drafts-and-streaming-partia.warrant.json
# Markdown SHA-256:   9e36f98b0d67d1f74a401ecf8201dae2a40a356fd10415209161b56c99dec783
# Code AST SHA-256:   780d968280e259554cd237bfb8140935953e15e67b2fcec9a83c8443e5562cbe
# Verified Classes:   MisattributedVerdictError, Verdict, TurnCommit, TurnRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class MisattributedVerdictError(RuntimeError):
    """Raised when a verdict's content identity cannot be pinned to the
    committed attempt of a turn, and the join is not permitted to guess."""


@dataclass(frozen=True)
class Verdict:
    turn_id: str
    attempt_id: Optional[int]
    content_hash: Optional[str]
    kind: str          # "eval" | "safety"
    severity: int      # 0 = clean, higher = worse
    scope: str = "attempt"   # "attempt" | "window" | "unknown"


@dataclass
class TurnCommit:
    turn_id: str
    committed_attempt_id: int
    committed_content_hash: str


@dataclass
class TurnRecord:
    turn_id: str
    committed_attempt_id: int
    verdicts: list[Verdict] = field(default_factory=list)
    quarantined: list[Verdict] = field(default_factory=list)
    join_complete: bool = True


def join_turn(commit: Optional[TurnCommit], verdicts: list[Verdict]) -> TurnRecord:
    if commit is None:
        # No commit marker: refuse to select an attempt by arrival order.
        raise MisattributedVerdictError(
            "no committed_attempt_id for turn; emit pending_commit instead of guessing"
        )

    record = TurnRecord(
        turn_id=commit.turn_id,
        committed_attempt_id=commit.committed_attempt_id,
    )

    for v in verdicts:
        if v.turn_id != commit.turn_id:
            raise MisattributedVerdictError(
                f"verdict for turn {v.turn_id!r} offered to join for {commit.turn_id!r}"
            )
        if v.attempt_id is None or v.content_hash is None:
            # Unpinned verdict: cannot prove which attempt it judged.
            record.quarantined.append(v)
            continue
        if v.attempt_id != commit.committed_attempt_id:
            # Verdict about a non-committed attempt (retry shadow / draft).
            record.quarantined.append(v)
            continue
        if v.content_hash != commit.committed_content_hash:
            # Same attempt id, different content: hash mismatch is fatal.
            raise MisattributedVerdictError(
                f"content hash mismatch on committed attempt {v.attempt_id}: "
                f"{v.content_hash!r} != {commit.committed_content_hash!r}"
            )
        if v.scope == "window":
            # Window verdicts are retained but do not roll into turn severity
            # without an explicit declared rollup policy.
            record.quarantined.append(v)
            continue
        record.verdicts.append(v)

    return record
