# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-pass-the-litmus-safety-benchmark-but-fail-runtime-risk-scoring-under-identical-prompts.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-pass-the-litmus-safety-benchmark-but-fail-runtime-risk-scoring-under-identical-prompts.warrant.json
# Markdown SHA-256:   f61d24c352940b2ad0954758e9f214686dab1c62bf8b9cf03ccb1289eeecb01f
# Code AST SHA-256:   53a3419aa518b44fa71ff2a6e2a845ef0e4fb855beec423651643ee636c16933
# Verified Classes:   HarnessRuntimeDivergence
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib


class HarnessRuntimeDivergence(RuntimeError):
    """Raised when a LITMUS harness score is not transferable to runtime topology."""
    pass


def score_transferability(
    harness_mean: float,
    runtime_mean: float,
    gate_margin: float,
    topology_epsilon: float,
    dedup_aliased: bool,
) -> dict:
    """
    Decide whether a harness risk score may be used as a deployment gate.

    gate_margin:      allowed distance between harness and runtime means before
                      the score is declared non-transferable.
    topology_epsilon: measured max |score(batch_pos) - score(pos0)| across the
                      topology-independence probe. Must be < gate_margin / 4.
    dedup_aliased:    True if the harness reused a score across distinct prompt
                      instances that the runtime will score independently.
    """
    if gate_margin <= 0:
        raise HarnessRuntimeDivergence(
            f"invalid gate_margin={gate_margin}; cannot bound divergence"
        )

    delta = abs(harness_mean - runtime_mean)
    if delta > gate_margin / 2:
        raise HarnessRuntimeDivergence(
            f"harness_mean={harness_mean:.3f} vs runtime_mean={runtime_mean:.3f} "
            f"(delta={delta:.3f} > gate_margin/2={gate_margin/2:.3f}); "
            f"harness measured a different function than the deployed one"
        )

    if topology_epsilon >= gate_margin / 4:
        raise HarnessRuntimeDivergence(
            f"topology_epsilon={topology_epsilon:.3f} >= gate_margin/4="
            f"{gate_margin/4:.3f}; batch-position coupling exceeds gate budget"
        )

    transferable = True
    tail_gating_allowed = not dedup_aliased
    fingerprint = hashlib.sha256(
        f"{harness_mean:.6f}:{runtime_mean:.6f}:{topology_epsilon:.6f}".encode()
    ).hexdigest()[:16]

    return {
        "transferable": transferable,
        "tail_gating_allowed": tail_gating_allowed,
        "delta": delta,
        "fingerprint": fingerprint,
    }
