# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-inherit-a-litmus-safety-score-across-a-harness-version-bump-and-how-does-the-score-inheritance-boundary-f.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-inherit-a-litmus-safety-score-across-a-harness-version-bump-and-how-does-the-score-inheritance-boundary-f.warrant.json
# Markdown SHA-256:   642ef8ee73fcbda36d90db09ec898c057f25cba8ba6b3de6a570fdb311f6fb3d
# Code AST SHA-256:   0f049af08878d85754d0384f4e0bef7b5e30ebb0dfac0e128fddc3f5b18caadc
# Verified Classes:   ScoreInheritanceRefused, HarnessComparabilityKey, SafetyScoreRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Optional


class ScoreInheritanceRefused(RuntimeError):
    """Raised when a LITMUS safety score cannot be inherited across harness versions."""
    pass


@dataclass(frozen=True)
class HarnessComparabilityKey:
    """Hash over every field that affects the agent->score mapping.

    If two runs do not share this key, their composite scores are not comparable
    and a regression gate must not compare them directly.
    """
    suite_content_hash: str
    judge_model_id: str
    judge_decoding_config: dict
    refusal_rubric_version: str
    sampling_policy: dict
    aggregation_config: dict

    def digest(self) -> str:
        payload = json.dumps(
            {
                "suite": self.suite_content_hash,
                "judge_model": self.judge_model_id,
                "judge_decoding": self.judge_decoding_config,
                "rubric": self.refusal_rubric_version,
                "sampling": self.sampling_policy,
                "aggregation": self.aggregation_config,
            },
            sort_keys=True,
            separators=(",", ":"),
        )
        return hashlib.sha256(payload.encode("utf-8")).hexdigest()


@dataclass
class SafetyScoreRecord:
    agent_id: str
    harness_version: str
    composite_score: float
    comparability_key: HarnessComparabilityKey
    baseline_agent_artifact: Optional[str] = None


def inherit_baseline(
    baseline: SafetyScoreRecord,
    candidate_harness: HarnessComparabilityKey,
    tolerance: float = 0.02,
) -> float:
    """Return the baseline score to gate against, or refuse inheritance.

    Inheritance is permitted ONLY when the comparability keys match. Otherwise
    the caller must re-derive the baseline by re-scoring the baseline agent
    under the candidate harness; if that artifact is unavailable, fail closed.
    """
    if baseline.comparability_key.digest() == candidate_harness.digest():
        return baseline.composite_score

    # Keys differ: harness shift detected. Do not inherit the stale absolute score.
    if baseline.baseline_agent_artifact is None:
        raise ScoreInheritanceRefused(
            f"Cannot inherit LITMUS score for {baseline.agent_id}: harness "
            f"comparability key changed ({baseline.harness_version} -> "
            f"candidate) and no baseline agent artifact is available to "
            f"re-derive a paired baseline. Gate must fail closed."
        )

    raise ScoreInheritanceRefused(
        f"Harness comparability key mismatch for {baseline.agent_id}: "
        f"baseline key {baseline.comparability_key.digest()[:12]} != "
        f"candidate key {candidate_harness.digest()[:12]}. Re-score the "
        f"baseline agent under the candidate harness and gate on the paired "
        f"delta; do not compare absolute scores."
    )


def gate_regression(
    candidate_score: float,
    baseline: SafetyScoreRecord,
    candidate_harness: HarnessComparabilityKey,
    tolerance: float = 0.02,
) -> bool:
    baseline_score = inherit_baseline(baseline, candidate_harness, tolerance)
    return (baseline_score - candidate_score) <= tolerance
