# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-litmus-style-harm-classifier-verdict-as-non-transferable-across-tool-use-turns.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-litmus-style-harm-classifier-verdict-as-non-transferable-across-tool-use-turns.warrant.json
# Markdown SHA-256:   8b41be3fbd6602343c3fdd08b6c728abbc75b8edfafe68ca0ca28f0bc1099169
# Code AST SHA-256:   5381a3af538073c4ecaa7aab40caf28f9b7d6c3c375747afc17cd7893094792f
# Verified Classes:   Verdict, ReferentDriftError, CompactionRegimeError, TurnVerdict
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class Verdict(Enum):
    HARMFUL = "harmful"
    BENIGN = "benign"
    ABSTAIN = "abstain"


class ReferentDriftError(RuntimeError):
    """Raised when per-turn verdicts are combined across non-nested judge contexts."""


class CompactionRegimeError(RuntimeError):
    """Raised when disjunctive aggregation is attempted inside the compaction regime."""


@dataclass(frozen=True)
class TurnVerdict:
    turn: int
    verdict: Verdict
    context_hash: str          # sha256 of the exact bytes the judge saw
    prefix_token_len: int


def _is_prefix(short: str, long: str) -> bool:
    """True iff the context hashed by `short` is a byte-prefix of `long`'s context.

    In production this is checked by re-hashing the shared prefix; here we
    approximate with the nesting flag the harness records at scoring time.
    """
    return long.startswith(short) or short == long


def aggregate_trajectory(
    verdicts: list[TurnVerdict],
    judge_window: int,
    *,
    compaction_detected: bool,
) -> Verdict:
    if not verdicts:
        raise ReferentDriftError("no verdicts to aggregate")

    # Invariant 1: prefix monotonicity of judge contexts.
    for prev, cur in zip(verdicts, verdicts[1:]):
        if not _is_prefix(prev.context_hash, cur.context_hash):
            raise ReferentDriftError(
                f"turn {cur.turn} context is not nested under turn {prev.turn}; "
                f"verdicts are about different objects and cannot be disjoined"
            )

    # Invariant 4 / boundary: refuse disjunction inside the compaction regime.
    max_prefix = max(v.prefix_token_len for v in verdicts)
    if compaction_detected or max_prefix > 0.5 * judge_window:
        raise CompactionRegimeError(
            f"max prefix {max_prefix} vs window {judge_window}: "
            "disjunctive aggregation is unsound; escalate to full-context "
            "scoring or demote label to unknown"
        )

    # Invariant 3: abstain is unknown, not benign.
    if any(v.verdict is Verdict.HARMFUL for v in verdicts):
        return Verdict.HARMFUL
    if any(v.verdict is Verdict.ABSTAIN for v in verdicts):
        return Verdict.ABSTAIN
    return Verdict.BENIGN


def score_turn(
    turn: int,
    judge_context: bytes,
    judge_window: int,
    *,
    pinned_spans_present: bool,
    compaction_detected: bool,
) -> TurnVerdict:
    """Score one turn and enforce the invariants the aggregator will later rely on."""
    if compaction_detected and not pinned_spans_present:
        # Constraint retention failed: the judge is scoring a different task.
        return TurnVerdict(
            turn=turn,
            verdict=Verdict.ABSTAIN,
            context_hash=hashlib.sha256(judge_context).hexdigest(),
            prefix_token_len=len(judge_context) // 4,
        )
    if len(judge_context) // 4 > judge_window:
        raise CompactionRegimeError(
            f"turn {turn}: judge context exceeds window; harness must escalate, "
            "not truncate, or the verdict is not about this trajectory"
        )
    # Placeholder: real judge call elided; the invariants above are the point.
    return TurnVerdict(
        turn=turn,
        verdict=Verdict.BENIGN,
        context_hash=hashlib.sha256(judge_context).hexdigest(),
        prefix_token_len=len(judge_context) // 4,
    )
