# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-litmus-harness-is-silently-grading-a-mutated-policy-the-transcript-replay-divergence-trap-in-agentic-red-team-regre.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-litmus-harness-is-silently-grading-a-mutated-policy-the-transcript-replay-divergence-trap-in-agentic-red-team-regre.warrant.json
# Markdown SHA-256:   d552e56c73811023537cb3174bed79ffaed044b94f13eb4db8214060bc18075d
# Code AST SHA-256:   30414c7446ddf1db67c80b16243c087e1e6d1ea79ce77978e3d53e523e8a56cf
# Verified Classes:   EnvironmentRealizationMismatch, Provenance
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EnvironmentRealizationMismatch(RuntimeError):
    """Raised when a candidate transcript is compared against a baseline
    transcript realized under a different environment (fixture hashes,
    canonicalized fields, or tool-result content hashes differ before the
    first policy-action divergence). Comparing across realizations
    attributes environment drift to policy regression."""
    pass


@dataclass(frozen=True)
class Provenance:
    scenario_id: str
    fixture_hashes: dict          # tool_name -> content hash of served fixture
    canonical_fields: dict        # normalized non-deterministic fields
    first_divergence_kind: str    # "POLICY" | "ENVIRONMENT" | "NONE"


def _first_divergence_kind(baseline_trace, candidate_trace) -> str:
    """Walk paired steps; return the kind of the first semantic divergence.
    A divergence at a tool-result step is ENVIRONMENT; at a policy-action
    step is POLICY; identical traces yield NONE."""
    for b, c in zip(baseline_trace, candidate_trace):
        if b == c:
            continue
        if b["kind"] == "tool_result" or c["kind"] == "tool_result":
            return "ENVIRONMENT"
        return "POLICY"
    if len(baseline_trace) != len(candidate_trace):
        return "ENVIRONMENT"  # length skew from re-sampled branch
    return "NONE"


def assert_comparable(baseline: Provenance, candidate: Provenance) -> None:
    """Refuse to compare transcripts unless environment realization matches
    or the first divergence is provably a policy action."""
    if baseline.scenario_id != candidate.scenario_id:
        raise EnvironmentRealizationMismatch(
            f"scenario id skew: {baseline.scenario_id} vs {candidate.scenario_id}"
        )
    if baseline.fixture_hashes != candidate.fixture_hashes:
        raise EnvironmentRealizationMismatch(
            f"{baseline.scenario_id}: fixture hash skew "
            f"{baseline.fixture_hashes} vs {candidate.fixture_hashes}; "
            f"stub served different content — re-baseline, do not attribute"
        )
    if baseline.canonical_fields != candidate.canonical_fields:
        raise EnvironmentRealizationMismatch(
            f"{baseline.scenario_id}: canonical field skew; "
            f"timestamps/UUIDs not normalized before divergence check"
        )
    if candidate.first_divergence_kind == "ENVIRONMENT":
        raise EnvironmentRealizationMismatch(
            f"{baseline.scenario_id}: first divergence is a tool result, "
            f"not a policy action; exclude from gate denominator, re-baseline"
        )


def gate_verdict(baseline: Provenance, candidate: Provenance,
                 baseline_verdict: str, candidate_verdict: str) -> str:
    """Return 'regression' only when comparability is proven and verdicts differ."""
    assert_comparable(baseline, candidate)
    if baseline_verdict == candidate_verdict:
        return "no_change"
    if baseline_verdict == "safe" and candidate_verdict == "unsafe":
        return "regression"
    return "improvement"
