# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-litmus-safety-score-delta-as-a-tool-use-capability-regression-rather-than-a-scorer-artifact.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-litmus-safety-score-delta-as-a-tool-use-capability-regression-rather-than-a-scorer-artifact.warrant.json
# Markdown SHA-256:   bd5536598424a43b530ce1388546853f70b8e9a8b7a754d7e457e2fedde2708a
# Code AST SHA-256:   065c939c20a4c49478c8d0732cda83c20cb9edb315e77523b56230deae0e0f53
# Verified Classes:   UnattributableScoreDelta, ScorerRun
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class UnattributableScoreDelta(RuntimeError):
    """Raised when a LITMUS safety-score delta cannot be attributed to the agent."""
    pass


@dataclass
class ScorerRun:
    scorer_version: str
    schema_feature_map: dict          # argument key -> risk feature name
    aggregate_score: float
    canary_noise_band: float          # measured +/- spread on frozen replay set
    flipped_trajectory_ids: list = field(default_factory=list)


def _fingerprint(run: ScorerRun) -> str:
    payload = f"{run.scorer_version}|{sorted(run.schema_feature_map.items())}"
    return hashlib.sha256(payload.encode()).hexdigest()


def attribute_delta(baseline: ScorerRun, candidate: ScorerRun,
                    reconciled_residual: float) -> str:
    """
    Decide whether a safety-score drop is a genuine agent capability regression.
    reconciled_residual = candidate_score minus baseline_score recomputed
    after re-scoring baseline trajectories through the candidate scorer
    and applying schema-key reconciliation.
    """
    if _fingerprint(baseline) != _fingerprint(candidate):
        # scorer or schema surface moved between runs; raw delta is uninterpretable
        if abs(reconciled_residual) <= candidate.canary_noise_band:
            return "artifact: scorer/schema drift within noise band"
        raise UnattributableScoreDelta(
            "scorer/schema changed AND residual exceeds noise band; "
            "cannot attribute without a fixed-scorer replay of baseline"
        )

    raw_delta = candidate.aggregate_score - baseline.aggregate_score
    if abs(raw_delta) <= candidate.canary_noise_band:
        return "no regression: delta within canary noise band"

    if abs(reconciled_residual) <= candidate.canary_noise_band:
        return "artifact: raw delta exceeds band but residual does not"

    # genuine regression: flips must be triaged, not assumed
    if not candidate.flipped_trajectory_ids:
        raise UnattributableScoreDelta(
            "residual regression claimed but no flipped trajectories recorded; "
            "triage record missing"
        )
    return f"genuine regression: residual {reconciled_residual:+.3f} over {len(candidate.flipped_trajectory_ids)} flips"
