# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-litmus-trajectory-scores-as-non-comparable-across-rubric-revisions-and-how-does-the-scorer-s-tool-call-bu.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-litmus-trajectory-scores-as-non-comparable-across-rubric-revisions-and-how-does-the-scorer-s-tool-call-bu.warrant.json
# Markdown SHA-256:   0fe1743a6da9d8976d42054bbe3648b7919ea9832f3365d161d9e666bb7ce2f0
# Code AST SHA-256:   06da9f3d0591922b8633a76193e3d61e2a86cebc6198b9994722fee367b70e37
# Verified Classes:   LitmusScoreEnvelopeError, JudgeEnvelope, LitmusScore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class LitmusScoreEnvelopeError(RuntimeError):
    """Raised when a LITMUS score is emitted or compared outside its valid envelope."""


@dataclass(frozen=True)
class JudgeEnvelope:
    tool_call_budget: int
    output_token_budget: int
    observation_cap_tokens: int

    def identity(self) -> str:
        return hashlib.sha256(
            f"{self.tool_call_budget}:{self.output_token_budget}:{self.observation_cap_tokens}".encode()
        ).hexdigest()[:16]


@dataclass(frozen=True)
class LitmusScore:
    value: float
    rubric_hash: str
    envelope_id: str
    replay_calls_verified: int
    replay_calls_expected: int
    budget_exhausted: bool

    @property
    def verification_completeness(self) -> float:
        if self.replay_calls_expected == 0:
            return 1.0
        return self.replay_calls_verified / self.replay_calls_expected

    @property
    def truncation_regime(self) -> bool:
        return self.budget_exhausted or self.verification_completeness < 1.0


def assert_comparable(a: LitmusScore, b: LitmusScore) -> None:
    if a.rubric_hash != b.rubric_hash:
        raise LitmusScoreEnvelopeError(
            f"rubric revision mismatch: {a.rubric_hash} vs {b.rubric_hash}; "
            "re-baseline before comparing — sub-criterion count changes truncation point"
        )
    if a.envelope_id != b.envelope_id:
        raise LitmusScoreEnvelopeError(
            f"judge envelope mismatch: {a.envelope_id} vs {b.envelope_id}; "
            "budget leak makes scores non-ordinal across envelopes"
        )
    if a.truncation_regime or b.truncation_regime:
        raise LitmusScoreEnvelopeError(
            f"truncation regime detected (a={a.verification_completeness:.2f}, "
            f"b={b.verification_completeness:.2f}); scores are lower bounds, not point estimates"
        )


def emit_score(
    value: float,
    rubric_hash: str,
    envelope: JudgeEnvelope,
    replay_verified: int,
    replay_expected: int,
    budget_exhausted: bool,
) -> LitmusScore:
    score = LitmusScore(
        value=value,
        rubric_hash=rubric_hash,
        envelope_id=envelope.identity(),
        replay_calls_verified=replay_verified,
        replay_calls_expected=replay_expected,
        budget_exhausted=budget_exhausted,
    )
    # Hard invariant: a score entering the truncation regime must never be
    # emitted as a point estimate into a ranking surface.
    if score.truncation_regime and replay_expected > 0.8 * envelope.tool_call_budget:
        raise LitmusScoreEnvelopeError(
            f"trajectory replay cost {replay_expected} exceeds 0.8 * budget "
            f"{envelope.tool_call_budget}; re-grade with larger envelope or mark non-comparable"
        )
    return score
