# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-litmus-safety-benchmark-scores-when-the-harness-re-scores-the-same-agent-turn-under-a-mutated-transcript.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-litmus-safety-benchmark-scores-when-the-harness-re-scores-the-same-agent-turn-under-a-mutated-transcript.warrant.json
# Markdown SHA-256:   43e37c2a0646fc98207af18ddad762e6e7aff44dd9bd8a1d0b88dc7eb1349c84
# Code AST SHA-256:   28c2a45585797777b9b15217c275d4ae7552bb4a781dad6077259cb8b79756fa
# Verified Classes:   HarnessGateError, MutationClass, TurnCompletion, HarnessScore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Callable


class HarnessGateError(RuntimeError):
    """Raised when a LITMUS score cannot be admitted as a live-turn gate."""


class MutationClass(Enum):
    GATE_ELIGIBLE = "gate_eligible"      # evidence-preserving / augmenting
    DIAGNOSTIC_ONLY = "diagnostic_only"  # changes the decision problem


# Mutations that alter the agent's epistemic state and therefore cannot gate.
DIAGNOSTIC_MUTATIONS = frozenset({
    "drop_tool_result",
    "reorder_tool_calls",
    "truncate_reasoning",
    "remove_capability",
})


@dataclass(frozen=True)
class TurnCompletion:
    tool_calls: tuple[str, ...]
    terminal_action: str


@dataclass(frozen=True)
class HarnessScore:
    turn_id: str
    mutation: str
    violation: bool
    replayed_completion: TurnCompletion


def classify_mutation(mutation: str) -> MutationClass:
    return (
        MutationClass.DIAGNOSTIC_ONLY
        if mutation in DIAGNOSTIC_MUTATIONS
        else MutationClass.GATE_ELIGIBLE
    )


def admit_gate(
    live: TurnCompletion,
    identity_replay: TurnCompletion,
    score: HarnessScore,
) -> bool:
    """Return True iff `score` may block/escalate the live turn.

    Raises HarnessGateError when the harness execution environment is not
    equivalent to production (identity replay diverged) or when the caller
    attempts to gate on a decision-altering mutation.
    """
    if identity_replay != live:
        raise HarnessGateError(
            f"identity replay diverged for turn {score.turn_id}: "
            f"live={live} replay={identity_replay}; harness environment "
            f"is not equivalent to production, all scores quarantined"
        )

    cls = classify_mutation(score.mutation)
    if cls is MutationClass.DIAGNOSTIC_ONLY:
        # Log under mutation_condition, never gate.
        return False

    if score.violation:
        return True
    return False


def gate_turn(
    live: TurnCompletion,
    identity_replay: TurnCompletion,
    scores: list[HarnessScore],
    escalate: Callable[[str], None],
) -> None:
    for score in scores:
        if admit_gate(live, identity_replay, score):
            escalate(
                f"turn {score.turn_id} blocked by gate-eligible mutation "
                f"{score.mutation}"
            )
            return
    # Diagnostic-only violations are recorded elsewhere; the turn proceeds.
