# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-harness-induced-safety-verdict-inversion-when-a-litmus-style-tool-use-trajectory-is-re-scored-under-a-drifted-rubric.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-harness-induced-safety-verdict-inversion-when-a-litmus-style-tool-use-trajectory-is-re-scored-under-a-drifted-rubric.warrant.json
# Markdown SHA-256:   a4bb4f26358cf55cee38924a20bf36b5c77cc429fc0bae5e0f063937f64f21cf
# Code AST SHA-256:   a731b4aed0f5c0d1e11cbd2630d3dd333bc683b1a51c661c58daa94864e2de0d
# Verified Classes:   VerdictProvenanceError, VerdictEnvelope
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class VerdictProvenanceError(RuntimeError):
    """Raised when a re-scored verdict delta cannot be attributed to the agent."""
    pass


@dataclass(frozen=True)
class VerdictEnvelope:
    trajectory_hash: str
    render_hash: str
    rubric_hash: str
    judge_model: str
    judge_seed: int
    truncation_point: Optional[int]  # None == untruncated
    sample_count: int
    label: str


def render_hash(trajectory: dict, rubric_text: str, truncation_point: Optional[int]) -> str:
    # Canonical serialization: sorted keys, no whitespace variance.
    payload = json.dumps(
        {"trajectory": trajectory, "rubric": rubric_text, "trunc": truncation_point},
        sort_keys=True,
        separators=(",", ":"),
    )
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


def attribute_delta(baseline: VerdictEnvelope, audit: VerdictEnvelope) -> str:
    """
    Returns 'AGENT_DELTA' only when the only difference is the trajectory.
    Returns 'JUDGE_VARIANCE' when render/rubric/truncation match but label differs.
    Returns 'CONFOUNDED' when render inputs drifted.
    Raises VerdictProvenanceError on structurally invalid comparisons.
    """
    if baseline.trajectory_hash != audit.trajectory_hash:
        # Different trajectories: not a re-score, not comparable here.
        raise VerdictProvenanceError(
            "trajectory_hash mismatch: this is not a re-score of the same trajectory"
        )

    # Structural invalidity: a truncated tool-use trajectory is not a safe/unsafe unit.
    if baseline.truncation_point is not None or audit.truncation_point is not None:
        raise VerdictProvenanceError(
            f"truncated trajectory cannot yield a comparable verdict: "
            f"baseline_trunc={baseline.truncation_point}, audit_trunc={audit.truncation_point}"
        )

    if baseline.label == audit.label:
        return "NO_DELTA"

    drifted = []
    if baseline.render_hash != audit.render_hash:
        drifted.append("render_hash")
    if baseline.rubric_hash != audit.rubric_hash:
        drifted.append("rubric_hash")
    if baseline.judge_model != audit.judge_model:
        drifted.append("judge_model")
    if baseline.judge_seed != audit.judge_seed:
        drifted.append("judge_seed")

    if drifted:
        raise VerdictProvenanceError(
            f"verdict delta is CONFOUNDED by harness drift in {drifted}; "
            f"suppress from agent safety metrics"
        )

    if baseline.sample_count < 5 or audit.sample_count < 5:
        raise VerdictProvenanceError(
            f"single-sample or low-sample verdict ({baseline.sample_count}, "
            f"{audit.sample_count}) cannot support a delta claim; re-run with k>=5"
        )

    return "JUDGE_VARIANCE"


def safe_verdict_for_agent(baseline: VerdictEnvelope, audit: VerdictEnvelope) -> str:
    """
    The only function an agent should call to consume a re-scored verdict.
    Refuses to return a label when provenance is broken.
    """
    try:
        attribution = attribute_delta(baseline, audit)
    except VerdictProvenanceError as e:
        # Do NOT fall back to either label. Surface the harness failure.
        raise VerdictProvenanceError(
            f"refusing to emit a safety label: {e}"
        ) from e

    if attribution == "NO_DELTA":
        return audit.label
    if attribution == "JUDGE_VARIANCE":
        # Report as distribution, not point label.
        return f"UNSTABLE(k={audit.sample_count})"
    raise VerdictProvenanceError(f"unexpected attribution: {attribution}")
