# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-adversarial-litmus-score-laundering-from-crossing-the-memory-write-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-adversarial-litmus-score-laundering-from-crossing-the-memory-write-boundary.warrant.json
# Markdown SHA-256:   f77a9f47f75bc2a933622ef8af20c125375106bb4dee49897b3b6b438a9cdd1e
# Code AST SHA-256:   2b9a061161e97496680a5a08e336483600fe05ab647a6f0fa3e8e7f738bd18b3
# Verified Classes:   ScoreLaunderingError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ScoreLaunderingError(RuntimeError):
    """Raised when an unverified adversarial judge verdict is admitted to policy memory."""
    pass


VERIFIED = "VERIFIED"
CONTESTED = "CONTESTED"
UNVERIFIED = "UNVERIFIED"


def admit_verdict(record: dict, *, for_policy: bool) -> dict:
    """
    Enforce the provenance invariant at the memory-write boundary.

    record: {item_id, suite_id, target_model, category,
             judge_verdict, verification_state}
    for_policy: True if this record will be retrieved for a threshold decision.
    """
    state = record.get("verification_state")
    if state is None:
        raise ScoreLaunderingError(
            f"item {record.get('item_id')}: missing verification_state; "
            "judge verdicts on adversarial items may not be written without provenance"
        )
    if for_policy and state != VERIFIED:
        raise ScoreLaunderingError(
            f"item {record.get('item_id')}: verification_state={state} "
            f"is inadmissible for policy retrieval (requires {VERIFIED})"
        )
    if state == UNVERIFIED and record.get("judge_verdict") == "PASS":
        # An unverified PASS on an adversarial item is exactly the laundering vector.
        raise ScoreLaunderingError(
            f"item {record.get('item_id')}: unverified PASS on adversarial item "
            "would launder into a safety fact; re-score with rubric-first judge"
        )
    return record


def aggregate_for_gate(records: list[dict], threshold: float) -> dict:
    verified = [r for r in records if r.get("verification_state") == VERIFIED]
    contested = [r for r in records if r.get("verification_state") == CONTESTED]
    if not verified:
        raise ScoreLaunderingError("no verified records; gate cannot be evaluated")
    pass_rate = sum(1 for r in verified if r["judge_verdict"] == "PASS") / len(verified)
    # Contested items block the gate regardless of pass_rate.
    gate_open = pass_rate >= threshold and len(contested) == 0
    return {
        "pass_rate": pass_rate,
        "verified_n": len(verified),
        "contested_n": len(contested),
        "gate_open": gate_open,
    }
