# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-litmus-safety-harness-regression-gate-is-measuring-harness-brittleness-rather-than-agent-compliance.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-litmus-safety-harness-regression-gate-is-measuring-harness-brittleness-rather-than-agent-compliance.warrant.json
# Markdown SHA-256:   16416828f661c2cf72b7ad8a835f2608accaf96f5bc5ee6afe50aef8dcfc3077
# Code AST SHA-256:   8fcf0c7ff0d3099bcd31286f18653e9cc3832a708197ebb3ee5a7a26d6f9d4ac
# Verified Classes:   HarnessChurnError, Trace
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class HarnessChurnError(RuntimeError):
    """Raised when a safety gate would compare across a non-label-neutral harness edit."""
    pass


@dataclass(frozen=True)
class Trace:
    task_id: str
    tool_calls: tuple          # full ordered trace, not just final message
    final_message: str


def label(trace: Trace, harness) -> str:
    # Pure function of trace under a pinned harness. No LLM judge in gating path.
    return harness.classify(trace.tool_calls, trace.final_message)


def label_flip_audit(traces, baseline_harness, candidate_harness) -> int:
    flips = 0
    for t in traces:
        if label(t, baseline_harness) != label(t, candidate_harness):
            flips += 1
    return flips


def gate(baseline_pass: float, candidate_pass: float,
         traces, baseline_harness, candidate_harness,
         tolerance: float = 0.02) -> bool:
    # Invariant: gate is a function of the agent alone. Harness must be label-neutral.
    flips = label_flip_audit(traces, baseline_harness, candidate_harness)
    if flips > 0:
        raise HarnessChurnError(
            f"{flips} label flips between harness versions; aggregate delta is "
            f"uninterpretable. Re-baseline the frozen harness or prove label-neutrality."
        )
    delta = candidate_pass - baseline_pass
    # Per-class stratification is required by the caller; this only guards aggregate.
    return delta >= -tolerance


def assert_frozen_harness(harness, expected_sha: str) -> None:
    actual = hashlib.sha256(harness.source_bytes()).hexdigest()
    if actual != expected_sha:
        raise HarnessChurnError(
            f"harness hash {actual[:12]} != pinned {expected_sha[:12]}; gate invalid"
        )
