#!/usr/bin/env python3
"""IIP-0044 / DEC-123 (CAND-035 / EXP-032): OpenIslet Foundry v1.3 Clean-Room
Protein Biologics Registration & IIP-0042 Gate 30-SHIELD-SPR Alignment Verifier.

Pure Python standard library ONLY:
  - ZERO wetlab_contract.py imports (Zero-LIMS-Touch)
  - ZERO assert statements (byte-identical execution under -B and -O -B)
  - Strict fail-closed validation on missing/invalid explicit paths, duplicate JSON keys,
    non-finite or overflowing JSON scalars, sequence/hash tampering, 71+5 Tier-1/Tier-2
    manifest reconstruction of SHA256SUMS.txt, exact 18 active PMIDs, recomputed gate
    tallies & required failure rows (incl. GUARD MD 5.487 A FAIL), dynamic side-contract
    Islet-GUARD (arm_id, route_id, construct_id) restriction, independent typed JSON +
    Markdown IIP-0042 alignment, and expanded Gate 30-TOS-QUARANTINE scanning across
    DEC-123, tests, IIP-0044, and aligned IIP-0042 surfaces.

Usage (public installed repository quick-start):
  PYTHONDONTWRITEBYTECODE=1 python3 -B scripts/verify_iip0044_foundry_v1_3_biologics.py --installed-check --check --repo-root .
  PYTHONDONTWRITEBYTECODE=1 python3 -O -B scripts/verify_iip0044_foundry_v1_3_biologics.py --installed-check --check --repo-root .
  PYTHONDONTWRITEBYTECODE=1 python3 -B scripts/verify_iip0044_foundry_v1_3_biologics.py --installed-check --repo-root .

Staging layout (flat pre-install directory):
  PYTHONDONTWRITEBYTECODE=1 python3 -B verify_iip0044_foundry_v1_3_biologics.py
  PYTHONDONTWRITEBYTECODE=1 python3 -O -B verify_iip0044_foundry_v1_3_biologics.py --check
"""
from __future__ import annotations

import argparse
from datetime import datetime
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
import hashlib
import json
import math
import os
import re
import sys
from pathlib import Path
from typing import Any

sys.dont_write_bytecode = True

SCRIPT_PATH = Path(__file__).resolve()
SCRIPT_DIR = SCRIPT_PATH.parent
GENERATED_DATE = "2026-11-28"

# Pinned frozen CC-BY-4.0 FASTA SHA-256 digests (byte-identical to Foundry v1.3 release)
EXPECTED_ALL_LEADS_FASTA_SHA256 = "c4f7d79ea97efe578bb39c56e686eea927d5b36cd9351fc9502579ba41ad20e9"
EXPECTED_COMP2_COMPS_FASTA_SHA256 = "99375dcd8fd4033b1db59c9d6c28579169c041401a5eb84dcc84e5702a08fdd2"
EXPECTED_BUNDLE_SHA256SUMS_SHA256 = "aa3b25f43a04c975944b9c087e9034faa9e0da8528e0a393d6f3d83221875932"

# Pinned finalized IIP-0044 side-contract SHA-256 digests (enforced at validate_islet_guard_eligibility callable boundary!)
EXPECTED_IIP0044_SIDE_CONTRACT_FILE_SHA256 = "458a67aee973579d1091e50e97c31bbb356072ff9f4b21ab6184bc403d19f51e"
EXPECTED_IIP0044_SIDE_CONTRACT_CANONICAL_SHA256 = "6ceea3ac618269ecff3116e42e41668937c5c31100908e2f8e8e24f48feb8b2d"

# Pinned frozen LIMS & Playbook §4.1.20 Zero-LIMS-Touch SHA-256 invariants
FROZEN_LIMS_SHA256 = {
    "scripts/wetlab_contract.py": "331ecd2f2d8602dfceae8b89263d0f360cfadfd0638a46d7d668a376294cfc73",
    "scripts/ingest_wetlab_results.py": "e050593675170515382257ce379449db596c87cc06ffc26d31d128e127630cb1",
    "data/protocols/wetlab_endpoint_contract_v0.8.0.json": "757bc1d9c2722c129cc4fd5962e8995b9f5bc5f7035f8530f5716da9aa2ac26f",
}
EXPECTED_PLAYBOOK_SEC4120_SHA256 = "e3fb5ec701678dfdeb62a77c15866327842b60b6b4c503cb86dfc79885a626a8"

# Exact 18 verified active PMIDs (explicitly enforcing ALL 3 core HLA-DQ PMIDs: 18252895, 21912932, 22315720)
EXPECTED_CORE_HLA_DQ_PMIDS = frozenset({"PMID:18252895", "PMID:21912932", "PMID:22315720"})
EXPECTED_TYPED_CITATION_ROLES: dict[str, str] = {
    "PMID:18252895": "EPIDEMIOLOGICAL_HLA_RISK_CONTEXT",
    "PMID:21912932": "EPIDEMIOLOGICAL_HLA_RISK_CONTEXT",
    "PMID:22315720": "EPIDEMIOLOGICAL_HLA_RISK_CONTEXT",
    "PMID:31556206": "CROSS_PRODUCT_MHCII_PEPTIDOMICS_ASSAY_ANALOGY",
}
FORBIDDEN_CITATION_ROLE_ENUMS: frozenset[str] = frozenset({
    "DIRECT_T1D_CLINICAL_EFFICACY",
    "THERAPEUTIC_COVERAGE",
    "CLINICAL_VALIDATION",
})
_RE_CITATION_ROLE_ANCHOR = re.compile(
    r"(?i)\b(?:31556206|18252895|21912932|22315720|fviii|factor\s+viii|erlich|noble)\b"
)
_RE_CITATION_DIRECT_EFFICACY_CLAIM = re.compile(
    r"(?i)\b(?:"
    r"direct(?:ly)?\s+(?:t1d\s+|type\s+1\s+diabetes\s+)?(?:clinical\s+)?(?:efficacy|validation|evidence\s+of\s+(?:t1d\s+)?(?:clinical\s+)?efficacy|therapeutic\s+coverage)"
    r"|clinical(?:ly)?\s+(?:validat(?:es?|ed|ing|ion)|efficacy|proof|evidence\s+in\s+(?:t1d|type\s+1\s+diabetes))"
    r"|therapeutic\s+(?:coverage|efficacy)\s+of\s+(?:these|our|islet[- ]?shield|stage[- ]?0)"
    r"|validat(?:es?|ed|ing)\s+(?:t1d\s+|type\s+1\s+diabetes\s+)?(?:clinical\s+)?(?:efficacy|therapeutic\s+coverage|islet[- ]?shield)"
    r"|proves?\s+(?:direct\s+)?(?:t1d\s+|type\s+1\s+diabetes\s+)?(?:clinical\s+)?(?:efficacy|validation|therapeutic\s+coverage)"
    r"|(?:establishes?|demonstrates?|shows?|supports?|provides?|confirms?)\s+(?:direct\s+)?(?:t1d\s+|type\s+1\s+diabetes\s+)?(?:clinical\s+)?(?:efficacy|validation|therapeutic\s+coverage)"
    r"|randomized\s+(?:type\s+1\s+diabetes|t1d)\s+(?:clinical\s+)?trial"
    r")\b"
)
_RE_NEGATION_BEFORE_CLAIM = re.compile(
    r"(?i)\b(?:not(?!\s+only\b)|no|never|neither|nor|none|without|rather\s+than|forbid(?:s|den|ding)?|prohibit(?:s|ed|ing)?|cannot|reject(?:s|ed|ing)?|den(?:y|ies|ying)|disclaim(?:s|ed|ing)?)\b"
)
EXPECTED_ACTIVE_PMIDS_18 = frozenset({
    "PMID:1334978",
    "PMID:7865457",
    "PMID:8384206",
    "PMID:9652824",
    "PMID:10761923",
    "PMID:11376336",
    "PMID:14660600",
    "PMID:15020763",
    "PMID:18252895",
    "PMID:21912932",
    "PMID:22315720",
    "PMID:24187131",
    "PMID:25135637",
    "PMID:25502872",
    "PMID:26707565",
    "PMID:30952805",
    "PMID:31556206",
    "PMID:34113344",
})

# Exact 6 wwPDB CC0-1.0 structures bound to primary PMIDs and 3 UniProtKB CC-BY-4.0 accessions bound to gene/slice (M1)
EXPECTED_PDB_TO_PRIMARY_PMID_6: dict[str, str] = {
    "1JK8": "PMID:11376336",
    "6DFX": "PMID:30952805",
    "1S9V": "PMID:15020763",
    "1PT6": "PMID:14660600",
    "1DX5": "PMID:10761923",
    "2M32": "PMID:24187131",
}
EXPECTED_PDB_IDS_6 = frozenset(EXPECTED_PDB_TO_PRIMARY_PMID_6.keys())
EXPECTED_UNIPROT_TO_GENE_AND_SLICE_3: dict[str, tuple[str, list[int]]] = {
    "P01308": ("INS", [33, 47]),
    "P56199": ("ITGA1", [161, 360]),
    "P07204": ("THBD", [363, 480]),
}
EXPECTED_UNIPROT_ACCESSIONS_3 = frozenset(EXPECTED_UNIPROT_TO_GENE_AND_SLICE_3.keys())

# Exact 14 distinct HLA-DQ8 off-target panel peptide IDs (B3)
EXPECTED_DQ8_14_OFFTARGET_PEPTIDE_IDS = frozenset({
    "DQ8_CLIP1",
    "DQ8_self_TFRC",
    "DQ8_self_HSP60",
    "DQ8_self_ACTA2",
    "DQ8_self_F8_acidic",
    "DQ8_self_IGKC",
    "DQ8_InsA_native",
    "DQ8_Cpep_native",
    "DQ8_glia_alpha1",
    "DQ8_glia_gamma1a",
    "DQ8_glia_gamma1b",
    "DQ8_EBV_EBNA1",
    "DQ8_Flu_HA306",
    "DQ8_CMV_pp65",
})

# Typed peptide identity & role records separating 1JK8 (14-aa), WT InsB:9-23 (15-aa), and 6DFX (12-aa) (B3)
EXPECTED_INSB_REFERENCE_PEPTIDES: dict[str, dict[str, Any]] = {
    "deposited_crystal_reference_1jk8": {
        "pdb_id": "1JK8",
        "chain": "C",
        "sequence": "LVEALYLVCGERGG",
        "length_aa": 14,
        "role": "DEPOSITED_CRYSTAL_REFERENCE_INSB11_23_PLUS_G",
    },
    "modeled_native_target_wt_insb9_23": {
        "uniprot_anchor": "P01308[33..47]",
        "sequence": "SHLVEALYLVCGERG",
        "length_aa": 15,
        "role": "NATIVE_HUMAN_WT_INSB9_23_TARGET",
    },
    "engineered_register3_comparator_6dfx": {
        "pdb_id": "6DFX",
        "sequence": "VEELYLVAGEEG",
        "length_aa": 12,
        "role": "ENGINEERED_REGISTER3_MIMOTOPE_COMPARATOR",
    },
}

# Targeted bidirectional anti-conflation pattern rejecting phrasings equating PDB 1JK8 (14-aa) with native WT InsB:9-23 (15-aa) (R08 B4)
_WT_INSB_PHRASE = (
    r"(?:(?:full[- ]length|15[- ](?:aa|residue))\s+)?"
    r"(?:(?:native|human|wild[- ]type|wt)\s+){0,3}"
    r"(?:insulin\s+b|insb)\s*:?\s*9\s*[-\u2013\u2014]\s*23(?:\s+(?:epitope|peptide|target|sequence))?"
)
_PDB_1JK8_PHRASE = r"(?:pdb\s+)?1jk8(?:\s+chain\s+c)?"
_RE_1JK8_NEGATION = re.compile(
    r"(?i)\b(?:not(?!\s+only\b)|no|never|neither|nor|distinct|different|rather\s+than|instead\s+of|cannot|forbid(?:s|den|ding)?|prohibit(?:s|ed|ing)?|reject(?:s|ed|ing)?)\b"
)
_RE_1JK8_CONFLATION = re.compile(
    r"(?i)(?:"
    r"\b1jk8\s+native\s+wt\b"
    r"|\b" + _PDB_1JK8_PHRASE + r"\s+(?:is|was|equals|represents|contains|carries|encodes|(?:co-?)?crystallized|resolved|depicts|shows|models)\s+(?:the\s+)?(?:" + _WT_INSB_PHRASE + r"|shlvealylvcgerg)\b"
    r"|\b(?:" + _WT_INSB_PHRASE + r"|shlvealylvcgerg)\s+(?:is|was|equals|matches|corresponds\s+to|(?:was\s+)?(?:co-?)?crystallized\s+in|resolved\s+in|present\s+in|contained\s+in|deposited\s+in|solved\s+in|observed\s+in|represented\s+by)\s+(?:the\s+)?" + _PDB_1JK8_PHRASE + r"(?:\s+(?:epitope|peptide|crystal|structure))?\b"
    r"|\b1jk8\s*(?:=|==)\s*" + _WT_INSB_PHRASE + r"\b"
    r"|(?:14[- ](?:aa|residue)\s+(?:and|&)\s+15[- ](?:aa|residue)|15[- ](?:aa|residue)\s+(?:and|&)\s+14[- ](?:aa|residue))"
    r"[^.\n]{0,80}\b(?:have\s+|share\s+)?(?:the\s+)?(?:identical|same)\s+(?:amino\s+acid\s+)?sequences?\b"
    r"|\b(?:identical|same)\s+(?:amino\s+acid\s+)?sequences?\b[^.\n]{0,80}"
    r"(?:14[- ](?:aa|residue)[^.\n]{0,40}15[- ](?:aa|residue)|15[- ](?:aa|residue)[^.\n]{0,40}14[- ](?:aa|residue)"
    r"|1jk8[^.\n]{0,40}(?:insulin\s+b|insb)\s*:?\s*9\s*[-\u2013\u2014]\s*23|(?:insulin\s+b|insb)\s*:?\s*9\s*[-\u2013\u2014]\s*23[^.\n]{0,40}1jk8)"
    r"|\b1jk8\b[^.\n]{0,60}\b(?:identical|same)\s+(?:peptide|sequence)\b[^.\n]{0,60}\b(?:insulin\s+b|insb)\s*:?\s*9\s*[-\u2013\u2014]\s*23\b"
    r")"
)


def _find_unnegated_1jk8_conflation(text_val: str) -> str | None:
    """Return the first unnegated PDB 1JK8 <-> 15-aa WT InsB:9-23 conflation match, or None."""
    for m in _RE_1JK8_CONFLATION.finditer(text_val):
        prefix = text_val[max(0, m.start() - 35) : m.start()]
        if _RE_1JK8_NEGATION.search(prefix) or _RE_1JK8_NEGATION.search(m.group(0)):
            continue
        return m.group(0)
    return None

# Exact 5 excluded Foundry v1.2 Tier-2 filenames (metadata-only carve-out verification)
_T2_TAG = "".join(("bo", "ltz", "21"))
EXPECTED_TIER2_CARVEOUT_RELPATHS = frozenset({
    f"metrics/{_T2_TAG}_v1_2_verification_audit.json",
    f"structures/IsletSHIELD_QF09_pI2__DQ25_HIP11_{_T2_TAG}_s0.cif",
    f"structures/IsletSHIELD_QF09_pI2__DQ8trans_HIP11_{_T2_TAG}_s0.cif",
    f"structures/IsletSORT_CD49a_t003_s10__ITGA1_3xMan3_Mg_{_T2_TAG}_s0.cif",
    f"structures/IsletGUARD_THBD_M406L__Thrombin_Ca_2xNAG_{_T2_TAG}_s0.cif",
})
_ALLOWED_CARVEOUT_ITEM_KEYS = frozenset({
    "relpath",
    "sha256",
    "bytes",
    "tier",
    "license_terms",
    "deposited_in_openislet",
    "numeric_outputs_included",
    "carveout_rationale",
})
_ALLOWED_TIER1_MANIFEST_ITEM_KEYS = frozenset({
    "relpath",
    "sha256",
    "bytes",
    "spdx_license",
    "file_category",
    "deposited_in_openislet",
    "openislet_deposited_path",
})
_ALLOWED_TIER1_SPDX_LICENSES = frozenset({"CC-BY-4.0", "MIT", "BSD-3-Clause"})
_EXPECTED_CARVEOUT_TIER = "Tier-2_Inherited_v1_2_Hosted_Verification_Carved_Out"
_EXPECTED_CARVEOUT_LICENSE_TERMS = (
    "LICENSE.txt Section 3 (Hosted API ToS \u00a74.3: non-CC-BY-4.0; prohibits developing competing AI/ML models)"
)
_RE_CARVEOUT_FORBIDDEN_SCORE = re.compile(
    r"(?i)(?:\b0\.\d+\b|\b(?:iptm|plddt|ptm|pae|rmsd|b_pep|binding_confidence|confidence_score|affinity_score|ic50|"
    + "sab_" + "pred"
    + r")\b)"
)
_RE_SHA256_HEX = re.compile(r"^[0-9a-f]{64}$")

# Live-verified WT human THBD EGF4-6 UniProt P07204[363..480] (118 aa; pos 44 = Met406)
UNIPROT_P07204_363_480_WT = (
    "VEPVDPCFRANCEYQCQPLNQTSYLCVCAEGFAPIPHEPHRCQMFCNQTACPADCDPNTQ"
    "ASCECPEGYILDDGFICTDIDECENGGFCSGVCHNLPGTFECICGPDSALARHIGTDC"
)

# Canonical 12 sequences across the two frozen CC-BY-4.0 FASTAs
EXPECTED_ALL_LEADS_SPECS: dict[str, dict[str, Any]] = {
    "IsletSHIELD_QF09_pI2": {
        "seq": "APPHSPMFRAIQRLIESGEFRLYRKTLRENPQSAKMSSTEFMQLVEAGRIEEAIEEMK",
        "len": 58,
        "cys": 0,
        "met": [7, 36, 42, 57],
        "trp": [],
        "ng_ns": [],
        "dg_ds": [],
        "n_glyc": [],
    },
    "IsletSHIELD_QF07": {
        "seq": "APPHSPMFRAIQRLIESGEFRLYRKTLKQNPDSAKMSSTEFMKLVEAGRIREAIEKMK",
        "len": 58,
        "cys": 0,
        "met": [7, 36, 42, 57],
        "trp": [],
        "ng_ns": [],
        "dg_ds": [32],
        "n_glyc": [],
    },
    "IsletSHIELD_QF09": {
        "seq": "APPHSPMFRAIQRLIESGEFRLYRKTLRENPQSAKMSSTEFMKLVEAGRIREAIEKMK",
        "len": 58,
        "cys": 0,
        "met": [7, 36, 42, 57],
        "trp": [],
        "ng_ns": [],
        "dg_ds": [],
        "n_glyc": [],
    },
    "IsletSORT_CD49a_t003_s10": {
        "seq": "DKEVEEAAKIIEDALKNKADPKVVAEKVPSKVLKPAYLKLYEKYKDDREKRWELSWLMVEVYRLRGDKPFEP",
        "len": 72,
        "cys": 0,
        "met": [58],
        "trp": [52, 56],
        "ng_ns": [],
        "dg_ds": [],
        "n_glyc": [],
    },
    "IsletSORT_CD49a_t003_s3": {
        "seq": "MEEVEKAAKIIEEALKNDADPKIVAEKVPSRVLKPAYLKLYEKYKDDREKRWKLSWLMVEYYRLNGDKPFEP",
        "len": 72,
        "cys": 0,
        "met": [1, 58],
        "trp": [52, 56],
        "ng_ns": [65],
        "dg_ds": [],
        "n_glyc": [],
    },
    "IsletGUARD_THBD_M406L": {
        "seq": "VEPVDPCFRANCEYQCQPLNQTSYLCVCAEGFAPIPHEPHRCQLFCNQTACPADCDPNTQASCECPEGYILDDGFICTDIDECENGGFCSGVCHNLPGTFECICGPDSALARHIGTDC",
        "len": 118,
        "cys": 18,
        "met": [],
        "trp": [],
        "ng_ns": [85],
        "dg_ds": [73, 107],
        "n_glyc": [20, 47],
    },
    "IsletSHIELD_Comp2_T006": {
        "seq": "GTDLWIEWYVSMHRIQMLHIQGEMPKDAQGKPSLDWMPDPRTASLQQMVQAAKRAL",
        "len": 56,
        "cys": 0,
        "met": [12, 17, 24, 37, 48],
        "trp": [5, 8, 36],
        "ng_ns": [],
        "dg_ds": [],
        "n_glyc": [],
    },
}

EXPECTED_COMP2_COMPS_SPECS: dict[str, dict[str, Any]] = {
    "IsletSHIELD_Comp2_SHIELD2_QQ": {
        "seq": "GTDLWIEWYVSMHRIQMLHIQGEMPKDAQGKPSLQQMPDPRTASLQQMVQAAKRAL",
        "len": 56,
        "cys": 0,
        "met": [12, 17, 24, 37, 48],
        "trp": [5, 8],
        "ng_ns": [],
        "dg_ds": [],
        "n_glyc": [],
    },
    "IsletSHIELD_Comp2_R3_shv2_stk1": {
        "seq": "SKQEIIKELQQSIAELKRELAKTAGRPEDDPEALMVQGMSAQTQHSLRIAKKYELV",
        "len": 56,
        "cys": 0,
        "met": [35, 39],
        "trp": [],
        "ng_ns": [],
        "dg_ds": [],
        "n_glyc": [],
    },
    "IsletSHIELD_Comp2_SH2_MP01": {
        "seq": "GTDLWIEWYVSMHRIQMLHIQGEMPKDAQGKPTLDALPDPRTASLEELVAAAKALL",
        "len": 56,
        "cys": 0,
        "met": [12, 17, 24],
        "trp": [5, 8],
        "ng_ns": [],
        "dg_ds": [],
        "n_glyc": [],
    },
    "IsletSHIELD_Comp2_SH2_MP06": {
        "seq": "STDLWIEWYVSMHRIQMLHIQGEMPKDAQGKPLITNLPDPLTASIEELVEAAKKAL",
        "len": 56,
        "cys": 0,
        "met": [12, 17, 24],
        "trp": [5, 8],
        "ng_ns": [],
        "dg_ds": [],
        "n_glyc": [],
    },
    "IsletSHIELD_Comp2_SH2_MP08": {
        "seq": "STDLWIEWYVSMHRIQMLHIEGRLPRDAEGRPRITGLPDPLTASIEELVAAARRVL",
        "len": 56,
        "cys": 0,
        "met": [12, 17],
        "trp": [5, 8],
        "ng_ns": [],
        "dg_ds": [],
        "n_glyc": [],
    },
}

# Canonical portfolio arms, routes, and Stage-0 registration defaults (overridden dynamically by side_contract!)
PORTFOLIO_ALL_ARMS = ("A", "B", "X", "Y", "D")
PORTFOLIO_ALL_ROUTES = (
    "ROUTE_1_CAO2_HYDROGEL",
    "ROUTE_2_ANGIOGENIC_POUCH",
    "ROUTE_3P_PASSIVE_MACRO",
    "ROUTE_3B_ACTIVE_IEOG",
)
ROUTE_ALIAS_MAP = {
    "R1": "ROUTE_1_CAO2_HYDROGEL",
    "ROUTE_1_CAO2_HYDROGEL": "ROUTE_1_CAO2_HYDROGEL",
    "R2": "ROUTE_2_ANGIOGENIC_POUCH",
    "ROUTE_2_ANGIOGENIC_POUCH": "ROUTE_2_ANGIOGENIC_POUCH",
    "R3P": "ROUTE_3P_PASSIVE_MACRO",
    "ROUTE_3P_PASSIVE_MACRO": "ROUTE_3P_PASSIVE_MACRO",
    "R3B": "ROUTE_3B_ACTIVE_IEOG",
    "ROUTE_3B_ACTIVE_IEOG": "ROUTE_3B_ACTIVE_IEOG",
}
DEFAULT_PORTFOLIO_ROUTE_ARM_BINDINGS = {
    "A": "ROUTE_1_CAO2_HYDROGEL",
    "B": "ROUTE_2_ANGIOGENIC_POUCH",
    "X": "ROUTE_1_CAO2_HYDROGEL",
    "Y": "ROUTE_3P_PASSIVE_MACRO",
    "D": "ROUTE_3P_PASSIVE_MACRO",
}
ISLET_GUARD_ALLOWED_ARMS = frozenset({"A", "X"})
ISLET_GUARD_ALLOWED_ROUTES = frozenset({"ROUTE_1_CAO2_HYDROGEL"})
ISLET_GUARD_CONSTRUCT_ID = "IsletGUARD_THBD_M406L"

# Gate 30-TOS-QUARANTINE & public hygiene leak detectors (split fragments prevent self-triggering)
_HOME_MAC = "/" + "Users" + "/"
_HOME_LINUX = "/" + "home" + "/"
_HOME_WIN_ESC = r"[A-Za-z]:\\" + "Users" + r"\\"
_RE_LOCAL_HOME_PATH = re.compile(
    r"(?<![A-Za-z0-9._-])(?:" + re.escape(_HOME_MAC) + "|" + re.escape(_HOME_LINUX) + "|" + _HOME_WIN_ESC + r")"
)
_RE_CURRENCY = re.compile(
    r"(?:(?:US|AU|CA|NZ)?\\?\$|\u20ac|\u00a3)\s?\d|\b(?:" + "|".join(["US" + "D", "EU" + "R", "GB" + "P"]) + r")\b\s*\d|\d\s*\b(?:" + "|".join(["US" + "D", "EU" + "R", "GB" + "P"]) + r")\b"
)
_RE_COORDINATE_ROW = re.compile(r"(?m)^\s*(?:" + "AT" + "OM  |" + "HET" + "ATM|" + "_atom" + r"_site\.)")
_RE_EMBEDDED_COORDINATE_ROW = re.compile(
    r"(?:"
    + "AT" + r"OM  \s*\d+\s+[A-Za-z0-9']+\s+[A-Z]{3}\b|"
    + "HET" + r"ATM\s*\d+\s+[A-Za-z0-9']+\s+[A-Z0-9]{2,4}\b|"
    + r"loop_\s+" + "_atom" + r"_site\.[A-Za-z0-9_]+)"
)
_RE_JSON_MMCIF_TAG = re.compile("_atom" + r"_site\.[A-Za-z0-9_]+")
_TIER2_TOKENS = tuple(
    "".join(parts)
    for parts in (
        ("bo", "ltz", "21"),
        ("bo", "ltz", "-2.1"),
        ("api.", "bo", "ltz"),
        ("sab_", "pred_"),
        ("0.02", "584"),
        ("0.35", "197"),
        ("2.54 ", "\u00c5"),
        ("2.54 ", "A"),
        ("outscores ", "all 3"),
    )
)
_COMMERCIAL_AI_VENDOR_TOKENS = tuple(
    "".join(parts)
    for parts in (
        ("clau", "de"),
        ("anthro", "pic"),
        ("open", "ai"),
        ("chat", "gpt"),
        ("gpt-", "4"),
        ("gpt-", "5"),
        ("ge", "mini"),
        ("deep", "mind"),
        ("gr", "ok"),
        ("x", "ai"),
        ("son", "net"),
        ("op", "us"),
        ("co", "dex"),
    )
)
_IIP0042_LEGACY_VENDOR_TOKENS = tuple(
    "".join(parts)
    for parts in (
        ("bo", "ltz"),
        ("alpha", "fold"),
        ("alpha", "genome"),
        ("alpha", "missense"),
        ("pro", "vention"),
        ("sa", "nofi"),
        ("micro", "medex"),
        ("drugs", ".com"),
        ("anthro", "pic"),
        ("open", "ai"),
        ("chat", "gpt"),
        ("gpt-", "4"),
        ("gpt-", "5"),
        ("ge", "mini"),
        ("deep", "mind"),
        ("cl", "aude"),
        ("gr", "ok"),
        ("x", "ai"),
        ("son", "net"),
        ("op", "us"),
        ("co", "dex"),
        ("chai", "-1"),
        ("colab", "fold"),
    )
)
_MISATTRIBUTED_UPSTREAM_PMID = "".join(("2222", "9122"))

# Exact single canonical Layer-2 quarantine disclaimer sentence from render_documentation.py
_AG_LOW = "alpha" + "genome"
_AG_CAP = "Alpha" + "Genome"
_CANONICAL_LAYER2_QUARANTINE_SENTENCE = (
    "The local 3,118-row AVI table is quarantined in the private cache: end-to-end batch generation provenance "
    "for the full 3,118-row table is incomplete (as a whole it is not a certified model scan), a limited "
    f"28 Oct 2026 live re-run against {_AG_LOW} v0.10.0 verified 59/59 sampled rows (9 candidate edits plus "
    f"50 random rows), {_AG_CAP} non-commercial output terms conflict with CC-BY-4.0 public redistribution, "
    f"and zero {_AG_CAP} outputs are shipped publicly or used as active ranking weights or insertion-safety certifications."
)


def sha256_bytes(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def sha256_file(path: Path) -> str:
    return sha256_bytes(path.read_bytes())


_EXACT_DECIMAL_PRESERVED_JSON_KEYS: frozenset[str] = frozenset({"design_effect_deff"})


def _reject_nonfinite_constant(token: str) -> Any:
    raise ValueError(f"Non-finite JSON constant rejected fail-closed: {token!r}")


def _parse_strict_finite_float(token: str) -> Decimal:
    try:
        dec_val = Decimal(token)
    except InvalidOperation as exc:
        raise ValueError(f"Invalid JSON float token rejected during decoding: {token!r}") from exc
    if not dec_val.is_finite() or dec_val.copy_abs() > Decimal("1e300"):
        raise ValueError(f"Non-finite or overflowing JSON decimal token rejected during decoding: {token!r}")
    val = float(token)
    if not math.isfinite(val) or abs(val) > 1e300:
        raise ValueError(f"Non-finite or overflowing JSON float rejected during decoding: {token!r}")
    return dec_val


def _parse_strict_finite_int(token: str) -> int:
    val = int(token)
    if abs(val) > 10 ** 300:
        raise ValueError(f"Overflowing JSON integer token rejected during decoding: {token[:32]!r}...")
    return val


def _coerce_non_dict_decimals_to_float(val: Any) -> Any:
    """Convert raw parsed Decimal tokens outside preserved exact-equality keys to binary64 float,
    without mutating child dicts whose keys were already finalized by object_pairs_hook.
    """
    if isinstance(val, Decimal):
        return float(val)
    if isinstance(val, list):
        return [_coerce_non_dict_decimals_to_float(item) for item in val]
    return val


def _reject_duplicate_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
    out: dict[str, Any] = {}
    for k, v in pairs:
        if k in out:
            raise ValueError(f"Duplicate JSON object key rejected fail-closed: {k!r}")
        if k in _EXACT_DECIMAL_PRESERVED_JSON_KEYS:
            out[k] = v
        else:
            out[k] = _coerce_non_dict_decimals_to_float(v)
    return out


def check_strictly_finite(obj: Any, label: str, path: str = "$") -> None:
    """Fail-closed recursive guard rejecting NaN/Inf or abs(x) > 10^300 (int, float, or Decimal) in loaded JSON."""
    if isinstance(obj, bool) or obj is None or isinstance(obj, str):
        return
    if isinstance(obj, Decimal):
        if not obj.is_finite() or obj.copy_abs() > Decimal("1e300"):
            raise ValueError(f"Non-finite or overflowing Decimal in {label} at {path}: {obj!r}")
        return
    if isinstance(obj, (int, float)):
        if isinstance(obj, int) and abs(obj) > 10 ** 300:
            raise ValueError(f"Overflowing integer in {label} at {path}")
        if isinstance(obj, float) and (not math.isfinite(obj) or abs(obj) > 1e300):
            raise ValueError(f"Non-finite or overflowing float in {label} at {path}: {obj!r}")
        if not math.isfinite(obj):
            raise ValueError(f"Non-finite scalar in {label} at {path}: {obj!r}")
        return
    if isinstance(obj, dict):
        for k, v in obj.items():
            check_strictly_finite(v, label, f"{path}.{k}")
        return
    if isinstance(obj, (list, tuple)):
        for i, v in enumerate(obj):
            check_strictly_finite(v, label, f"{path}[{i}]")
        return


def load_strict_json_text(raw: str, label: str) -> Any:
    obj = json.loads(
        raw,
        object_pairs_hook=_reject_duplicate_keys,
        parse_constant=_reject_nonfinite_constant,
        parse_float=_parse_strict_finite_float,
        parse_int=_parse_strict_finite_int,
    )
    obj = _coerce_non_dict_decimals_to_float(obj)
    check_strictly_finite(obj, label)
    return obj


def load_strict_json(path: Path) -> Any:
    if not path.is_file():
        raise FileNotFoundError(f"Missing required JSON file: {path.name}")
    raw = path.read_text(encoding="utf-8")
    return load_strict_json_text(raw, path.name)


def require_cond(cond: bool, msg: str) -> None:
    if not cond:
        raise RuntimeError(msg)


def mask_canonical_layer2_disclaimer_only(md_text: str) -> str:
    """Narrowly mask ONLY the single exact canonical Layer-2 quarantine disclaimer sentence inside
    <!-- OPENISLET_CURRENT_LAYER_SCOPE -->...<!-- OPENISLET_CURRENT_LAYER_SCOPE_END -->.
    Never strips the rest of the footer block.
    """
    def _replace_footer(match: re.Match[str]) -> str:
        return match.group(0).replace(
            _CANONICAL_LAYER2_QUARANTINE_SENTENCE,
            "[CANONICAL_LAYER2_QUARANTINE_DISCLAIMER_VERIFIED]",
        )

    return re.sub(
        r"<!-- OPENISLET_CURRENT_LAYER_SCOPE -->.*?<!-- OPENISLET_CURRENT_LAYER_SCOPE_END -->",
        _replace_footer,
        md_text,
        flags=re.S,
    )


def _iter_decoded_json_strings(obj: Any) -> list[str]:
    """Recursively collect every string key and value from a parsed JSON structure."""
    out: list[str] = []
    stack: list[Any] = [obj]
    while stack:
        cur = stack.pop()
        if isinstance(cur, str):
            out.append(cur)
        elif isinstance(cur, dict):
            for k, v in cur.items():
                if isinstance(k, str):
                    out.append(k)
                stack.append(v)
        elif isinstance(cur, (list, tuple)):
            stack.extend(cur)
    return out


def strip_verified_tier2_exclusion_manifest(json_text: str, label: str) -> str:
    """Strictly validate EVERY key, field type, and scalar value of the metadata-only 5-file
    Tier-2 carve-out list inside the IIP-0044 summary JSON BEFORE masking it for Tier-2 scanning.
    Rejects nested dicts/lists, floats/scores, extra keys, or non-canonical values before masking.
    """
    obj = load_strict_json_text(json_text, label)
    require_cond(isinstance(obj, dict), f"{label} must decode to a JSON object")
    scb = obj.get("source_cleanroom_bundle")
    if isinstance(scb, dict) and "excluded_tier2_carveout_files_5" in scb:
        carveouts = scb["excluded_tier2_carveout_files_5"]
        require_cond(
            isinstance(carveouts, list) and len(carveouts) == 5,
            f"excluded_tier2_carveout_files_5 in {label} must contain exactly 5 entries",
        )
        seen: set[str] = set()
        for item in carveouts:
            require_cond(
                isinstance(item, dict) and set(item.keys()) == _ALLOWED_CARVEOUT_ITEM_KEYS,
                f"Unauthorized keys in excluded_tier2_carveout_files_5 entry in {label}",
            )
            rp = item["relpath"]
            require_cond(
                type(rp) is str and rp in EXPECTED_TIER2_CARVEOUT_RELPATHS and rp not in seen,
                f"Unexpected or duplicate Tier-2 carve-out relpath in {label}: {rp!r}",
            )
            seen.add(rp)
            sh = item["sha256"]
            require_cond(
                type(sh) is str and bool(_RE_SHA256_HEX.match(sh)),
                f"Invalid lowercase 64-hex SHA-256 in excluded_tier2_carveout_files_5 entry {rp}",
            )
            bsize = item["bytes"]
            require_cond(
                type(bsize) is int and bsize > 0,
                f"Carve-out entry {rp} must have positive integer bytes, got {bsize!r}",
            )
            tier_val = item["tier"]
            require_cond(
                type(tier_val) is str and tier_val == _EXPECTED_CARVEOUT_TIER,
                f"Carve-out entry {rp} has invalid tier metadata: {tier_val!r}",
            )
            lic_val = item["license_terms"]
            require_cond(
                type(lic_val) is str and lic_val == _EXPECTED_CARVEOUT_LICENSE_TERMS,
                f"Carve-out entry {rp} has invalid license_terms metadata: {lic_val!r}",
            )
            require_cond(
                item["deposited_in_openislet"] is False,
                f"Carve-out entry {rp} must have deposited_in_openislet=false",
            )
            require_cond(
                type(item["numeric_outputs_included"]) is int and item["numeric_outputs_included"] == 0,
                f"Carve-out entry {rp} must have integer numeric_outputs_included=0",
            )
            rat = item["carveout_rationale"]
            require_cond(
                type(rat) is str and 1 <= len(rat) <= 240,
                f"Carve-out entry {rp} carveout_rationale must be a concise scalar string (no nested dict/list)",
            )
            rat_no_cc = rat.replace("CC-BY-4.0", "CC_BY_FOUR")
            require_cond(
                not _RE_CARVEOUT_FORBIDDEN_SCORE.search(rat_no_cc) and not re.search(r"\b\d+\.\d+\b", rat_no_cc),
                f"Carve-out entry {rp} carveout_rationale contains prohibited score/metric token: {rat!r}",
            )
            non_rp = json.dumps({k: v for k, v in item.items() if k != "relpath"}, ensure_ascii=False)
            c = scan_tos_quarantine_text(non_rp, f"{label}::carveout_meta[{rp}]")
            require_cond(
                all(v == 0 for v in c.values()),
                f"Gate 30-TOS-QUARANTINE violation inside carve-out metadata {rp}: {c}",
            )
        require_cond(seen == EXPECTED_TIER2_CARVEOUT_RELPATHS, f"Incomplete 5-file Tier-2 carve-out set in {label}")
        scb_copy = dict(scb)
        del scb_copy["excluded_tier2_carveout_files_5"]
        obj_copy = dict(obj)
        obj_copy["source_cleanroom_bundle"] = scb_copy
        return json.dumps(obj_copy, ensure_ascii=False)
    return json_text


def parse_fasta_text(text: str) -> list[tuple[str, str, str]]:
    records: list[tuple[str, str, str]] = []
    hdr: str | None = None
    chunks: list[str] = []
    for ln in text.splitlines():
        s = ln.strip()
        if not s:
            continue
        if s.startswith(">"):
            if hdr is not None:
                seq = "".join(chunks)
                records.append((hdr.split("|")[0].strip(), hdr, seq))
            hdr = s[1:]
            chunks = []
        else:
            chunks.append(s)
    if hdr is not None:
        seq = "".join(chunks)
        records.append((hdr.split("|")[0].strip(), hdr, seq))
    return records


# IUPAC standard elemental average atomic weights (C, H, N, O, S) for unmodified polypeptide MW calculation
_IUPAC_ATOMIC_WEIGHTS_CHNOS: tuple[Decimal, Decimal, Decimal, Decimal, Decimal] = (
    Decimal("12.0107"),
    Decimal("1.00794"),
    Decimal("14.0067"),
    Decimal("15.9994"),
    Decimal("32.065"),
)
_AMINO_ACID_RESIDUE_FORMULAS_CHNOS: dict[str, tuple[int, int, int, int, int]] = {
    "A": (3, 5, 1, 1, 0),
    "R": (6, 12, 4, 1, 0),
    "N": (4, 6, 2, 2, 0),
    "D": (4, 5, 1, 3, 0),
    "C": (3, 5, 1, 1, 1),
    "E": (5, 7, 1, 3, 0),
    "Q": (5, 8, 2, 2, 0),
    "G": (2, 3, 1, 1, 0),
    "H": (6, 7, 3, 1, 0),
    "I": (6, 11, 1, 1, 0),
    "L": (6, 11, 1, 1, 0),
    "K": (6, 12, 2, 1, 0),
    "M": (5, 9, 1, 1, 1),
    "F": (9, 9, 1, 1, 0),
    "P": (5, 7, 1, 1, 0),
    "S": (3, 5, 1, 2, 0),
    "T": (4, 7, 1, 2, 0),
    "W": (11, 10, 2, 1, 0),
    "Y": (9, 9, 1, 2, 0),
    "V": (5, 9, 1, 1, 0),
}


def compute_unmodified_average_mw_da(seq: str) -> Decimal:
    """Compute exact unmodified average molecular mass (Da) directly from amino acid elemental formulas + H2O termini."""
    c_n, h_n, n_n, o_n, s_n = 0, 2, 0, 1, 0
    for aa in seq:
        if aa not in _AMINO_ACID_RESIDUE_FORMULAS_CHNOS:
            raise ValueError(f"Unsupported amino acid symbol {aa!r} in unmodified MW calculation")
        rc, rh, rn, ro, rs = _AMINO_ACID_RESIDUE_FORMULAS_CHNOS[aa]
        c_n += rc
        h_n += rh
        n_n += rn
        o_n += ro
        s_n += rs
    wc, wh, wn, wo, ws = _IUPAC_ATOMIC_WEIGHTS_CHNOS
    return wc * c_n + wh * h_n + wn * n_n + wo * o_n + ws * s_n


def verify_fasta_file(
    path: Path,
    expected_sha256: str,
    expected_specs: dict[str, dict[str, Any]],
) -> dict[str, Any]:
    if not path.is_file():
        raise FileNotFoundError(f"Missing required CC-BY-4.0 FASTA: {path.name}")
    raw = path.read_bytes()
    actual_sha = sha256_bytes(raw)
    require_cond(
        actual_sha == expected_sha256,
        f"FASTA SHA-256 mismatch for {path.name}: actual={actual_sha}, expected={expected_sha256}",
    )
    records = parse_fasta_text(raw.decode("utf-8"))
    require_cond(
        len(records) == len(expected_specs),
        f"FASTA record count mismatch for {path.name}: actual={len(records)}, expected={len(expected_specs)}",
    )
    seen: list[str] = []
    per_seq: dict[str, dict[str, Any]] = {}
    for seq_id, hdr, seq in records:
        require_cond(seq_id in expected_specs, f"Unexpected sequence ID in {path.name}: {seq_id}")
        spec = expected_specs[seq_id]
        require_cond(seq == spec["seq"], f"Sequence mismatch for {seq_id} in {path.name}")
        require_cond(len(seq) == spec["len"], f"Length mismatch for {seq_id}: {len(seq)} != {spec['len']}")
        require_cond("CC-BY-4.0" in hdr, f"Missing CC-BY-4.0 license tag in header for {seq_id}")

        cys_count = seq.count("C")
        met_pos = [i + 1 for i, aa in enumerate(seq) if aa == "M"]
        trp_pos = [i + 1 for i, aa in enumerate(seq) if aa == "W"]
        ng_ns = [m.start() + 1 for m in re.finditer(r"N[GS]", seq)]
        dg_ds = [m.start() + 1 for m in re.finditer(r"D[GS]", seq)]
        n_glyc = [m.start() + 1 for m in re.finditer(r"N[^P][ST]", seq)]
        mw_da = compute_unmodified_average_mw_da(seq)
        mw_kda = mw_da / Decimal("1000")
        mw_da_5dp = mw_da.quantize(Decimal("0.00001"), rounding=ROUND_HALF_UP)
        mw_kda_5dp = mw_kda.quantize(Decimal("0.00001"), rounding=ROUND_HALF_UP)
        mw_kda_2dp = mw_kda.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)

        require_cond(cys_count == spec["cys"], f"Cys mismatch for {seq_id}: {cys_count} != {spec['cys']}")
        require_cond(met_pos == spec["met"], f"Met positions mismatch for {seq_id}: {met_pos} != {spec['met']}")
        require_cond(trp_pos == spec["trp"], f"Trp positions mismatch for {seq_id}: {trp_pos} != {spec['trp']}")
        require_cond(ng_ns == spec["ng_ns"], f"NG/NS mismatch for {seq_id}: {ng_ns} != {spec['ng_ns']}")
        require_cond(dg_ds == spec["dg_ds"], f"DG/DS mismatch for {seq_id}: {dg_ds} != {spec['dg_ds']}")
        require_cond(n_glyc == spec["n_glyc"], f"N-glyc mismatch for {seq_id}: {n_glyc} != {spec['n_glyc']}")

        seen.append(seq_id)
        per_seq[seq_id] = {
            "length": len(seq),
            "cys": cys_count,
            "disulfide_pairs": cys_count // 2,
            "met_count": len(met_pos),
            "trp_count": len(trp_pos),
            "ng_ns_count": len(ng_ns),
            "dg_ds_count": len(dg_ds),
            "n_glyc_count": len(n_glyc),
            "unmodified_average_mw_da": float(mw_da_5dp),
            "unmodified_average_mw_kda": float(mw_kda_5dp),
            "unmodified_average_mw_kda_2dp": float(mw_kda_2dp),
            "sha256_seq": sha256_bytes(seq.encode("utf-8")),
        }

    require_cond(set(seen) == set(expected_specs.keys()), f"Missing sequence IDs in {path.name}")
    return {
        "filename": path.name,
        "sha256": actual_sha,
        "bytes": len(raw),
        "sequence_count": len(records),
        "all_sequences_verified": True,
        "sequences": per_seq,
    }


def verify_thbd_p07204_m406l(shipped_seq: str) -> dict[str, Any]:
    require_cond(len(UNIPROT_P07204_363_480_WT) == 118, "WT P07204[363..480] reference must be 118 aa")
    require_cond(len(shipped_seq) == 118, f"IsletGUARD_THBD_M406L length must be 118 aa, got {len(shipped_seq)}")
    diffs = [
        {"pos_1based_slice": i + 1, "uniprot_pos_1based": 363 + i, "wt": a, "shipped": b}
        for i, (a, b) in enumerate(zip(UNIPROT_P07204_363_480_WT, shipped_seq))
        if a != b
    ]
    require_cond(
        len(diffs) == 1 and diffs[0] == {"pos_1based_slice": 44, "uniprot_pos_1based": 406, "wt": "M", "shipped": "L"},
        f"IsletGUARD_THBD_M406L must differ from P07204[363..480] strictly at M406L (slice pos 44): {diffs}",
    )
    cys = shipped_seq.count("C")
    n_glyc = [m.start() + 1 for m in re.finditer(r"N[^P][ST]", shipped_seq)]
    require_cond(cys == 18 and cys // 2 == 9, f"Expected 18 Cys / 9 reference disulfides, got {cys}")
    require_cond(n_glyc == [20, 47], f"Expected 2 reference N-glyc sequons [20, 47], got {n_glyc}")
    return {
        "uniprot_accession": "P07204",
        "slice_1based_closed": [363, 480],
        "length_aa": 118,
        "single_substitution_verified": diffs[0],
        "cys_count": cys,
        "reference_disulfide_pairs_uniprot_p07204": cys // 2,
        "reference_n_glyc_sequon_positions_1based": n_glyc,
        "reference_n_glyc_uniprot_p07204_positions": [382, 409],
        "product_glycan_and_disulfide_measured": False,
        "mammalian_or_insect_expression_required": True,
        "passed": True,
    }


def _canonical_json_sha256(obj: Any) -> str:
    return sha256_bytes(json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))


def _extract_guard_policy(
    side_contract: dict[str, Any] | Path | None,
) -> tuple[frozenset[str], frozenset[str], str, dict[str, str]]:
    """Enforce the frozen canonical Islet-GUARD policy ({'A', 'X'} on ROUTE_1_CAO2_HYDROGEL
    for IsletGUARD_THBD_M406L) across all three call modes:
      - side_contract is None: uses the frozen in-code canonical policy directly (no external file read).
      - side_contract is Path: authenticates BOTH the raw file SHA-256 AND canonical JSON SHA-256
        against the pinned finalized IIP-0044 side contract plus frozen policy parity.
      - side_contract is dict: authenticates canonical JSON SHA-256 plus frozen policy parity.
    Fails closed with ValueError on any tampered, widened, or unpinned policy.
    """
    if side_contract is None:
        return (
            ISLET_GUARD_ALLOWED_ARMS,
            ISLET_GUARD_ALLOWED_ROUTES,
            ISLET_GUARD_CONSTRUCT_ID,
            dict(DEFAULT_PORTFOLIO_ROUTE_ARM_BINDINGS),
        )
    if isinstance(side_contract, Path):
        if not side_contract.is_file():
            raise ValueError(f"Missing Islet-GUARD side_contract file: {side_contract.name}")
        raw_bytes = side_contract.read_bytes()
        file_sha = sha256_bytes(raw_bytes)
        if file_sha != EXPECTED_IIP0044_SIDE_CONTRACT_FILE_SHA256:
            raise ValueError(
                f"Tampered or unpinned Islet-GUARD side_contract file SHA-256 rejected fail-closed: "
                f"got {file_sha}, expected {EXPECTED_IIP0044_SIDE_CONTRACT_FILE_SHA256}"
            )
        side_contract_obj = load_strict_json_text(raw_bytes.decode("utf-8"), side_contract.name)
    elif isinstance(side_contract, dict):
        side_contract_obj = side_contract
    else:
        raise ValueError(f"Invalid side_contract type for Islet-GUARD eligibility check: {type(side_contract).__name__}")

    guard_cfg = side_contract_obj.get("programs_registered", {}).get("Islet_GUARD")
    if not isinstance(guard_cfg, dict):
        raise ValueError("Missing programs_registered.Islet_GUARD in side_contract (fail-closed)")
    allowed_arms_raw = guard_cfg.get("allowed_route_arms")
    disallowed_arms_raw = guard_cfg.get("disallowed_route_arms")
    allowed_routes_raw = guard_cfg.get("allowed_route_ids")
    construct_id_raw = guard_cfg.get("allowed_construct_id") or guard_cfg.get("lead_id")
    bindings_raw = guard_cfg.get("portfolio_route_arm_bindings")
    if not isinstance(allowed_arms_raw, list) or not allowed_arms_raw:
        raise ValueError("Invalid allowed_route_arms in side_contract (fail-closed)")
    if not isinstance(disallowed_arms_raw, list) or not disallowed_arms_raw:
        raise ValueError("Invalid disallowed_route_arms in side_contract (fail-closed)")
    if not isinstance(allowed_routes_raw, list) or not allowed_routes_raw:
        raise ValueError("Invalid allowed_route_ids in side_contract (fail-closed)")
    if type(construct_id_raw) is not str or not construct_id_raw.strip():
        raise ValueError("Invalid allowed_construct_id in side_contract (fail-closed)")
    if not isinstance(bindings_raw, dict) or not bindings_raw:
        raise ValueError("Invalid portfolio_route_arm_bindings in side_contract (fail-closed)")

    allowed_arms = frozenset(str(a).strip().upper() for a in allowed_arms_raw)
    disallowed_arms = frozenset(str(a).strip().upper() for a in disallowed_arms_raw)
    allowed_routes = frozenset(ROUTE_ALIAS_MAP.get(str(r).strip().upper(), str(r).strip().upper()) for r in allowed_routes_raw)
    construct_id = construct_id_raw.strip()
    bindings = {
        str(k).strip().upper(): ROUTE_ALIAS_MAP.get(str(v).strip().upper(), str(v).strip().upper())
        for k, v in bindings_raw.items()
    }

    # Enforce frozen canonical Islet-GUARD policy directly at the callable boundary (B4!)
    if allowed_arms != ISLET_GUARD_ALLOWED_ARMS:
        raise ValueError(
            f"Tampered Islet-GUARD allowed_route_arms rejected fail-closed at callable boundary: "
            f"got {sorted(allowed_arms)}, frozen canonical policy requires {sorted(ISLET_GUARD_ALLOWED_ARMS)}"
        )
    if disallowed_arms != frozenset({"B", "Y", "D"}):
        raise ValueError(
            f"Tampered Islet-GUARD disallowed_route_arms rejected fail-closed at callable boundary: "
            f"got {sorted(disallowed_arms)}, frozen canonical policy requires ['B', 'D', 'Y']"
        )
    if allowed_routes != ISLET_GUARD_ALLOWED_ROUTES:
        raise ValueError(
            f"Tampered Islet-GUARD allowed_route_ids rejected fail-closed at callable boundary: "
            f"got {sorted(allowed_routes)}, frozen canonical policy requires {sorted(ISLET_GUARD_ALLOWED_ROUTES)}"
        )
    if construct_id != ISLET_GUARD_CONSTRUCT_ID:
        raise ValueError(
            f"Tampered Islet-GUARD construct_id rejected fail-closed at callable boundary: "
            f"got {construct_id!r}, frozen canonical policy requires {ISLET_GUARD_CONSTRUCT_ID!r}"
        )
    if bindings != DEFAULT_PORTFOLIO_ROUTE_ARM_BINDINGS:
        raise ValueError(
            f"Tampered Islet-GUARD portfolio_route_arm_bindings rejected fail-closed at callable boundary: "
            f"got {bindings!r}"
        )

    # Enforce pinned canonical SHA-256 of the finalized IIP-0044 side contract at the callable boundary (B4!)
    actual_canon_sha = _canonical_json_sha256(side_contract_obj)
    if actual_canon_sha != EXPECTED_IIP0044_SIDE_CONTRACT_CANONICAL_SHA256:
        raise ValueError(
            f"Unpinned or mutated IIP-0044 side_contract rejected fail-closed at callable boundary: "
            f"canonical_sha256={actual_canon_sha}, expected={EXPECTED_IIP0044_SIDE_CONTRACT_CANONICAL_SHA256}"
        )

    return (allowed_arms, allowed_routes, construct_id, bindings)


def validate_islet_guard_eligibility(
    arm_id: str,
    route_id: str,
    construct_id: str = ISLET_GUARD_CONSTRUCT_ID,
    *,
    side_contract: dict[str, Any] | Path | None = None,
) -> bool:
    """Callable-boundary-pinned Stage-0 registration & standalone gate eligibility evaluator
    for Islet-GUARD (THBD M406L): enforces the frozen canonical policy ({'A', 'X'} on
    ROUTE_1_CAO2_HYDROGEL for IsletGUARD_THBD_M406L) across all three call modes:
      1. side_contract=None -> frozen in-code policy directly;
      2. side_contract=Path -> raw file SHA-256 + canonical JSON SHA-256 + frozen policy parity;
      3. side_contract=dict -> canonical JSON SHA-256 + frozen policy parity.
    Rejects unknown arms/routes and any tampered or widened side contract fail-closed (ValueError).
    """
    norm_arm = arm_id.strip().upper()
    if norm_arm not in PORTFOLIO_ALL_ARMS:
        raise ValueError(f"Unknown portfolio arm for Islet-GUARD eligibility check: {arm_id!r}")
    raw_route = route_id.strip().upper()
    if raw_route not in ROUTE_ALIAS_MAP:
        raise ValueError(f"Unknown route_id for Islet-GUARD eligibility check: {route_id!r}")
    norm_route = ROUTE_ALIAS_MAP[raw_route]
    norm_construct = construct_id.strip()
    if not norm_construct:
        raise ValueError("Empty construct_id rejected fail-closed")

    allowed_arms, allowed_routes, expected_construct, _ = _extract_guard_policy(side_contract)
    return (
        norm_arm in allowed_arms
        and norm_route in allowed_routes
        and norm_construct == expected_construct
    )


def validate_islet_guard_arm_eligibility(
    arm_id: str,
    *,
    route_id: str | None = None,
    construct_id: str = ISLET_GUARD_CONSTRUCT_ID,
    side_contract: dict[str, Any] | Path | None = None,
) -> bool:
    """Backward-compatible wrapper binding arm_id to its canonical portfolio route when route_id is omitted."""
    norm_arm = arm_id.strip().upper()
    if norm_arm not in PORTFOLIO_ALL_ARMS:
        raise ValueError(f"Unknown portfolio arm for Islet-GUARD eligibility check: {arm_id!r}")
    _, _, _, bindings = _extract_guard_policy(side_contract)
    eff_route = bindings[norm_arm] if route_id is None else route_id
    return validate_islet_guard_eligibility(
        norm_arm,
        eff_route,
        construct_id=construct_id,
        side_contract=side_contract,
    )


def run_islet_guard_arm_restriction_tests(*, side_contract: dict[str, Any]) -> dict[str, Any]:
    """Verify callable-boundary-pinned Islet-GUARD restriction across arms, routes, constructs,
    omitted side contract, and direct tampered/widened policy rejection (B4)."""
    allowed_arms, allowed_routes, allowed_construct, _ = _extract_guard_policy(side_contract)
    require_cond(
        allowed_arms == frozenset({"A", "X"}),
        f"Side contract Islet_GUARD allowed_route_arms must be ['A', 'X'], got {sorted(allowed_arms)}",
    )
    require_cond(
        allowed_routes == frozenset({"ROUTE_1_CAO2_HYDROGEL"}),
        f"Side contract Islet_GUARD allowed_route_ids must be ['ROUTE_1_CAO2_HYDROGEL'], got {sorted(allowed_routes)}",
    )
    require_cond(
        allowed_construct == ISLET_GUARD_CONSTRUCT_ID,
        f"Side contract Islet_GUARD allowed_construct_id must be {ISLET_GUARD_CONSTRUCT_ID!r}, got {allowed_construct!r}",
    )

    arm_results: dict[str, bool] = {}
    for arm in PORTFOLIO_ALL_ARMS:
        eligible = validate_islet_guard_arm_eligibility(arm, side_contract=side_contract)
        expected = arm in ("A", "X")
        require_cond(eligible == expected, f"Islet-GUARD arm restriction failed for arm {arm}: {eligible} != {expected}")
        # Verify omitted side_contract matches canonical policy identically
        require_cond(
            validate_islet_guard_arm_eligibility(arm, side_contract=None) == expected,
            f"Islet-GUARD omitted side_contract mismatch for arm {arm}",
        )
        arm_results[arm] = eligible

    # Explicit (arm_id, route_id) matrix proving wrong-route A/X (R2, R3P, R3B) and R1-paired B/Y/D are rejected!
    arm_route_matrix: dict[str, bool] = {}
    for arm in PORTFOLIO_ALL_ARMS:
        for route in PORTFOLIO_ALL_ROUTES:
            eligible = validate_islet_guard_eligibility(arm, route, side_contract=side_contract)
            expected = (arm in ("A", "X")) and (route == "ROUTE_1_CAO2_HYDROGEL")
            require_cond(
                eligible == expected,
                f"Islet-GUARD (arm={arm}, route={route}) eligibility failed: got {eligible}, expected {expected}",
            )
            arm_route_matrix[f"{arm}@{route}"] = eligible

    # Direct boundary tamper probe: widening allowed_route_arms to ["A", "X", "B"] MUST raise ValueError!
    widened_sc = json.loads(json.dumps(side_contract))
    widened_sc["programs_registered"]["Islet_GUARD"]["allowed_route_arms"] = ["A", "X", "B"]
    widened_rejected = False
    try:
        validate_islet_guard_eligibility("B", "ROUTE_1_CAO2_HYDROGEL", side_contract=widened_sc)
    except ValueError:
        widened_rejected = True
    require_cond(widened_rejected, "Direct validate_islet_guard_eligibility failed to reject widened arm ['A', 'X', 'B'] contract")

    wrong_construct_rejected = not validate_islet_guard_eligibility(
        "A", "ROUTE_1_CAO2_HYDROGEL", construct_id="IsletGUARD_THBD_WT", side_contract=side_contract
    )
    require_cond(wrong_construct_rejected, "Wrong construct_id on A@ROUTE_1_CAO2_HYDROGEL must be rejected")

    unknown_arm_rejected = False
    try:
        validate_islet_guard_eligibility("Z_INVALID", "ROUTE_1_CAO2_HYDROGEL", side_contract=side_contract)
    except ValueError:
        unknown_arm_rejected = True
    require_cond(unknown_arm_rejected, "Unknown arm must be rejected fail-closed")

    unknown_route_rejected = False
    try:
        validate_islet_guard_eligibility("A", "ROUTE_99_INVALID", side_contract=side_contract)
    except ValueError:
        unknown_route_rejected = True
    require_cond(unknown_route_rejected, "Unknown route_id must be rejected fail-closed")

    return {
        "policy_binding": "CALLABLE_BOUNDARY_FROZEN_POLICY_AND_PINNED_SIDE_CONTRACT_SHA256",
        "pinned_side_contract_canonical_sha256": EXPECTED_IIP0044_SIDE_CONTRACT_CANONICAL_SHA256,
        "enforcement_scope": "STAGE0_REGISTRATION_AND_STANDALONE_GATE_POLICY_0_00_PP_LIVE_CREDIT",
        "allowed_arms": ["A", "X"],
        "disallowed_arms": ["B", "Y", "D"],
        "allowed_route_ids": ["ROUTE_1_CAO2_HYDROGEL"],
        "allowed_construct_id": ISLET_GUARD_CONSTRUCT_ID,
        "arm_eligibility_map": arm_results,
        "wrong_route_ax_rejected": (
            not arm_route_matrix["A@ROUTE_2_ANGIOGENIC_POUCH"]
            and not arm_route_matrix["A@ROUTE_3P_PASSIVE_MACRO"]
            and not arm_route_matrix["X@ROUTE_2_ANGIOGENIC_POUCH"]
            and not arm_route_matrix["X@ROUTE_3P_PASSIVE_MACRO"]
            and not arm_route_matrix["A@ROUTE_3B_ACTIVE_IEOG"]
        ),
        "disallowed_arms_on_r1_rejected": (
            not arm_route_matrix["B@ROUTE_1_CAO2_HYDROGEL"]
            and not arm_route_matrix["Y@ROUTE_1_CAO2_HYDROGEL"]
            and not arm_route_matrix["D@ROUTE_1_CAO2_HYDROGEL"]
        ),
        "widened_side_contract_rejected_at_callable_boundary": widened_rejected,
        "wrong_construct_rejected": wrong_construct_rejected,
        "unknown_arm_rejected_fail_closed": unknown_arm_rejected,
        "unknown_route_rejected_fail_closed": unknown_route_rejected,
        "passed": True,
    }


def _scan_tos_plain_segment(text: str, *, from_json_string: bool = False) -> dict[str, int]:
    norm = text.replace("\r\n", "\n").replace("\r", "\n")
    home_hits = len(_RE_LOCAL_HOME_PATH.findall(norm))
    currency_hits = len(_RE_CURRENCY.findall(norm))
    low = norm.lower()
    tier2_hits = sum(low.count(tok.lower()) for tok in _TIER2_TOKENS)
    vendor_hits = sum(
        len(re.findall(r"(?<![a-z0-9])" + re.escape(tok) + r"(?![a-z0-9])", low))
        for tok in _COMMERCIAL_AI_VENDOR_TOKENS
    )
    coord_hits = len(_RE_COORDINATE_ROW.findall(norm)) + len(_RE_EMBEDDED_COORDINATE_ROW.findall(norm))
    if from_json_string:
        coord_hits += len(_RE_JSON_MMCIF_TAG.findall(norm))
    return {
        "home_path_hits": home_hits,
        "currency_hits": currency_hits,
        "tier2_hosted_hits": tier2_hits,
        "commercial_ai_vendor_hits": vendor_hits,
        "unauthorized_coordinate_row_hits": coord_hits,
    }


def scan_tos_quarantine_text(text: str, label: str) -> dict[str, int]:
    """Gate 30-TOS-QUARANTINE & public hygiene scanner for IIP-0044 artifacts.
    Inspects BOTH raw text lines AND recursively decoded JSON string values (catching coordinate
    rows, escaped paths, or restricted tokens hidden inside JSON strings).
    """
    counts = _scan_tos_plain_segment(text, from_json_string=False)
    stripped = text.lstrip()
    if stripped.startswith(("{", "[")):
        try:
            parsed = json.loads(text)
        except Exception:
            parsed = None
        if parsed is not None:
            dec_totals = {k: 0 for k in counts}
            for s in _iter_decoded_json_strings(parsed):
                sc = _scan_tos_plain_segment(s, from_json_string=True)
                for k, v in sc.items():
                    dec_totals[k] += v
            for k in counts:
                if dec_totals[k] > counts[k]:
                    counts[k] = dec_totals[k]
    return counts


def require_tos_quarantine_clean(text: str, label: str) -> dict[str, int]:
    counts = scan_tos_quarantine_text(text, label)
    if any(v > 0 for v in counts.values()):
        raise RuntimeError(f"Gate 30-TOS-QUARANTINE / hygiene violation in {label}: {counts}")
    return counts


def run_tos_quarantine_negative_self_tests() -> dict[str, Any]:
    probes = {
        "mac_home_path_probe": ("prefix " + _HOME_MAC + "alice/file.txt", "home_path_hits"),
        "linux_home_path_probe": ("prefix " + _HOME_LINUX + "bob/file.txt", "home_path_hits"),
        "win_home_path_probe": ("prefix C:\\" + "Users" + "\\carol\\file.txt", "home_path_hits"),
        "usd_currency_probe": ("budget $" + "1500 total", "currency_hits"),
        "eur_currency_probe": ("budget \u20ac" + "1500 total", "currency_hits"),
        "gbp_currency_probe": ("budget 900 " + "GB" + "P total", "currency_hits"),
        "tier2_file_probe": ("copied " + _TIER2_TOKENS[0] + "_s0.cif", "tier2_hosted_hits"),
        "tier2_numeric_probe": ("binding_confidence " + _TIER2_TOKENS[4], "tier2_hosted_hits"),
        "commercial_ai_vendor_probe": ("reviewed by " + _COMMERCIAL_AI_VENDOR_TOKENS[0], "commercial_ai_vendor_hits"),
        "pdb_coord_probe": ("AT" + "OM      1  N   ALA A   1      11.104  13.207   2.100\n", "unauthorized_coordinate_row_hits"),
        "mmcif_coord_probe": ("_atom" + "_site.group_PDB\n", "unauthorized_coordinate_row_hits"),
        "json_string_pdb_coord_probe": (
            json.dumps({"note": "AT" + "OM      1  N   ALA A   1      11.104  13.207   2.100"}),
            "unauthorized_coordinate_row_hits",
        ),
        "json_string_mmcif_coord_probe": (
            json.dumps({"note": "line1\n_atom" + "_site.group_PDB"}),
            "unauthorized_coordinate_row_hits",
        ),
    }
    rejected = {}
    for name, (ptext, expected_key) in probes.items():
        counts = scan_tos_quarantine_text(ptext, name)
        require_cond(counts[expected_key] > 0, f"Hygiene self-test {name} failed to catch {expected_key}")
        rejected[name] = True

    # Negative carve-out schema probe: nested dict inside carveout_rationale MUST fail BEFORE masking!
    bad_carve = {
        "source_cleanroom_bundle": {
            "excluded_tier2_carveout_files_5": [
                {
                    "relpath": rp,
                    "sha256": "a" * 64,
                    "bytes": 1000,
                    "tier": _EXPECTED_CARVEOUT_TIER,
                    "license_terms": _EXPECTED_CARVEOUT_LICENSE_TERMS,
                    "deposited_in_openislet": False,
                    "numeric_outputs_included": 0,
                    "carveout_rationale": {"hosted_iptm": 0.91} if idx == 0 else "Excluded metadata only.",
                }
                for idx, rp in enumerate(sorted(EXPECTED_TIER2_CARVEOUT_RELPATHS))
            ]
        }
    }
    nested_rejected = False
    try:
        strip_verified_tier2_exclusion_manifest(json.dumps(bad_carve), "probe:nested_carveout")
    except RuntimeError:
        nested_rejected = True
    require_cond(nested_rejected, "Carve-out validator failed to reject nested dict in carveout_rationale")
    rejected["carveout_nested_dict_probe"] = nested_rejected
    return {"total_negative_probes": len(rejected), "all_rejected_fail_closed": True, "probes": rejected}


# =============================================================================
# Executable Typed Fail-First Gate 30-SHIELD-SPR Adjudicator (IIP-0042 B3-B4 / IIP-0044 B1-B4)
# Synchronized 100% IDENTICALLY with scripts/verify_iip0042_master_multilayer_portfolio_crosswalk.py::evaluate_gate30_shield_spr
# =============================================================================
_SHIELD_SPR_PRECEDENCE: dict[str, int] = {
    "PASS": 0,
    "HOLD": 1,
    "HOLD_OBSERVED_NONZERO_CYTOTOXICITY": 2,
    "HOLD_CYTOTOXICITY_U95_EXCEEDS_5PCT": 3,
    "HOLD_INVALID_OR_MISSING_INPUT": 4,
    "FAIL": 5,
}
_SHIELD_SPR_PRECEDENCE_ORDER: list[str] = [
    "FAIL",
    "HOLD_INVALID_OR_MISSING_INPUT",
    "HOLD_CYTOTOXICITY_U95_EXCEEDS_5PCT",
    "HOLD_OBSERVED_NONZERO_CYTOTOXICITY",
    "HOLD",
    "PASS",
]
_SHIELD_MANDATORY_ON_TARGET_ANALYTES: tuple[str, ...] = (
    "HLA-DQ2.5 + HIP11",
    "HLA-DQ8-trans + HIP11",
    "HLA-DQ2.2 + HIP11",
    "HLA-DQ8 + native WT InsB:9-23",
)
_SHIELD_COMP1_ON_TARGET_ANALYTES: frozenset[str] = frozenset({
    "HLA-DQ2.5 + HIP11",
    "HLA-DQ8-trans + HIP11",
    "HLA-DQ2.2 + HIP11",
})
_SHIELD_COMP2_ON_TARGET_ANALYTES: frozenset[str] = frozenset({
    "HLA-DQ8 + native WT InsB:9-23",
})
_SHIELD_ANALYTE_ALIASES: dict[str, str] = {
    "HLA-DQ2.5 + HIP11": "HLA-DQ2.5 + HIP11",
    "HLA-DQ8-trans + HIP11": "HLA-DQ8-trans + HIP11",
    "HLA-DQ2.2 + HIP11": "HLA-DQ2.2 + HIP11",
    "HLA-DQ8 + native WT InsB:9-23": "HLA-DQ8 + native WT InsB:9-23",
    "HLA-DQ8 + native WT InsB:9-23 (15-aa SHLVEALYLVCGERG)": "HLA-DQ8 + native WT InsB:9-23",
}
_SHIELD_MANDATORY_COMP1_OFF_TARGET_CONTROLS: tuple[str, ...] = (
    "HLA-DQ2.5 + CLIP1",
    "HLA-DQ2.5 + Self_IGKV2_EAED",
    "HLA-DQ2.5 + cel_glutenin_L1",
    "HLA-DQ8-trans + Cpep_Nterm_EAED",
)
_SHIELD_MANDATORY_COMP2_OFF_TARGET_CONTROLS: tuple[str, ...] = (
    "HLA-DQ8 + CLIP1",
    "HLA-DQ8 + DQ8-glia-gamma1a",
    "HLA-DQ8-trans + WT InsB:9-23",
)
_SHIELD_MANDATORY_OFF_TARGET_CONTROLS: tuple[str, ...] = (
    _SHIELD_MANDATORY_COMP1_OFF_TARGET_CONTROLS + _SHIELD_MANDATORY_COMP2_OFF_TARGET_CONTROLS
)
_SHIELD_OFF_TARGET_ALIASES: dict[str, str] = {
    "HLA-DQ8 + DQ8_glia_gamma1a": "HLA-DQ8 + DQ8-glia-gamma1a",
}
_SHIELD_COMP1_LEAD = "IsletSHIELD_QF09_pI2"
_SHIELD_COMP2_LEAD = "IsletSHIELD_Comp2_T006"
_SHIELD_MANDATORY_COMP2_COMPARATORS: tuple[str, ...] = (
    "IsletSHIELD_Comp2_T006",
    "SHIELD2_QQ",
    "R3_shv2_stk1",
    "SH2_MP01",
    "SH2_MP06",
    "SH2_MP08",
)
_SHIELD_COCKTAIL_LEADS: tuple[str, ...] = (
    _SHIELD_COMP1_LEAD,
    _SHIELD_COMP2_LEAD,
)
_SHIELD_CONSTRUCT_CANONICAL_MAP: dict[str, str] = {
    "IsletSHIELD_QF09_pI2": "IsletSHIELD_QF09_pI2",
    "IsletSHIELD_Comp2_T006": "IsletSHIELD_Comp2_T006",
    "SHIELD2_QQ": "SHIELD2_QQ",
    "IsletSHIELD_Comp2_SHIELD2_QQ": "SHIELD2_QQ",
    "R3_shv2_stk1": "R3_shv2_stk1",
    "IsletSHIELD_Comp2_R3_shv2_stk1": "R3_shv2_stk1",
    "SH2_MP01": "SH2_MP01",
    "IsletSHIELD_Comp2_SH2_MP01": "SH2_MP01",
    "SH2_MP06": "SH2_MP06",
    "IsletSHIELD_Comp2_SH2_MP06": "SH2_MP06",
    "SH2_MP08": "SH2_MP08",
    "IsletSHIELD_Comp2_SH2_MP08": "SH2_MP08",
}
_SHIELD_QUALIFYING_HLA_DQ_TOKENS: frozenset[str] = frozenset({
    "HLA-DQ2.5",
    "HLA-DQ8",
    "HLA-DQ8-TRANS",
    "HLA-DQ2.2",
    "DQ2.5",
    "DQ8",
    "DQ8-TRANS",
    "DQ2.2",
    "DQA1*05:01/DQB1*02:01",
    "DQA1*03:01/DQB1*03:02",
    "DQA1*05:01/DQB1*03:02",
    "DQA1*02:01/DQB1*02:02",
})
_SHIELD_CYTO_INDEPENDENCE_MODEL = "EXACT_BINOMIAL_INDEPENDENT_UNITS"
_SHIELD_MIN_BATCHES_N = 3
_SHIELD_MIN_SPR_REPLICATES_N = 3
_SHIELD_MIN_DONORS_N = 3
_SHIELD_MIN_CYTO_N_EFF_PER_DONOR = 60
_SHIELD_MIN_MONOMER_PCT = 95.0
_SHIELD_MAX_DLS_PDI = 0.15
_SHIELD_CYTO_CI_TOL_PP = 0.05
_SHIELD_CYTO_SIMULTANEOUS_FWER_ALPHA = 0.05
_SHIELD_CYTO_DONOR_FAMILY_ALPHA_ONE_SIDED = 0.05
_SHIELD_CYTO_ESTIMAND = "TESTED_DONOR_FAMILY_GLOBAL_NULL_MAX_P_I_LE_5PCT"
_SHIELD_REQUIRED_DONOR_CLINICAL_COHORT = "T1D"
_SHIELD_FORBIDDEN_NON_T1D_DONOR_RE = re.compile(
    r"(?i)(?:HEALTHY[_ -]?CONTROL|CONTROL[_ -]?HEALTHY|NON[_ -]?T1D|HEALTHY[_ -]?DONOR|NON[_ -]?DIABETIC|HEALTHY(?:[_ -]|\d|$)|CONTROL[_ -]?DONOR)"
)
_SHIELD_MIN_CONFIRMATORY_DONORS_N = 9
_SHIELD_SUPPRESSION_ESTIMAND = "POPULATION_DONOR_RESPONDER_PROPORTION_GE_70PCT"
_SHIELD_SUPPRESSION_INFERENCE_METHOD = "EXACT_ONE_SIDED_CLOPPER_PEARSON_RESPONDER_PROPORTION"
_SHIELD_SUPPRESSION_PASS_THRESHOLD_PCT = 70.0
_SHIELD_SUPPRESSION_FAIL_THRESHOLD_PCT = 40.0
_SHIELD_SUPPRESSION_FAIL_L95_GT_PCT = 60.0
_SHIELD_SUPPRESSION_ASSAY_ACCEPTANCE_MIN_PCT = -1000.0
_SHIELD_SUPPRESSION_ASSAY_ACCEPTANCE_MAX_PCT = 100.0
_SHIELD_STRICT_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{1,63}$")
_SHIELD_EVIDENCE_REF_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/-]{3,127}$")
_SHIELD_ISO8601_UTC_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?Z$")
_SHIELD_SHA256_HEX_RE = re.compile(r"^[0-9a-f]{64}$")
_SHIELD_AUTHORIZING_DONOR_SAMPLING_DESIGNS: frozenset[str] = frozenset({
    "SIMPLE_RANDOM_OR_CONSECUTIVE_INDEPENDENT_T1D_COHORT",
})
_SHIELD_NON_AUTHORIZING_STRATIFIED_SAMPLING_DESIGNS: frozenset[str] = frozenset({
    "STRATIFIED_INDEPENDENT_T1D_HLA_DQ_COHORT",
})
_SHIELD_ALLOWED_DONOR_SAMPLING_DESIGNS: frozenset[str] = (
    _SHIELD_AUTHORIZING_DONOR_SAMPLING_DESIGNS
    | _SHIELD_NON_AUTHORIZING_STRATIFIED_SAMPLING_DESIGNS
)
_SHIELD_ALLOWED_INDEPENDENT_EXPERIMENTAL_UNITS: dict[str, frozenset[str]] = {
    "INDEPENDENT_REPLICATE_WELLS": frozenset({
        "Single pre-aliquoted independent primary T1D APC assay well "
        "(distinct physically isolated well per unit prior to dosing)",
        "INDEPENDENT_PRIMARY_T1D_APC_ASSAY_WELL",
    }),
    "INDEPENDENT_DROPLET_PARTITIONS": frozenset({
        "Single physically isolated microfluidic droplet partition "
        "(one independent primary T1D APC partition per unit prior to dosing)",
        "INDEPENDENT_DROPLET_PARTITION",
    }),
    "INDEPENDENT_CLONAL_COLONIES": frozenset({
        "Single physically separated clonal primary T1D APC colony unit "
        "(one independent isolated colony per unit prior to dosing)",
        "INDEPENDENT_CLONAL_COLONY",
    }),
}
_SHIELD_ALLOWED_CLUSTERING_CONTROLS: dict[str, frozenset[str]] = {
    "INDEPENDENT_REPLICATE_WELLS": frozenset({
        "Randomized plate layout across physically separated wells with independent "
        "dosing aliquots and zero cross-well pooling",
        "RANDOMIZED_SEPARATE_WELLS_INDEPENDENT_ALIQUOTS_NO_POOLING",
    }),
    "INDEPENDENT_DROPLET_PARTITIONS": frozenset({
        "Physically isolated independent droplet partitions with independent "
        "reagent loading and zero cross-droplet pooling",
        "ISOLATED_DROPLET_PARTITIONS_INDEPENDENT_LOADING_NO_POOLING",
    }),
    "INDEPENDENT_CLONAL_COLONIES": frozenset({
        "Physically separated independent clonal colony units with independent "
        "dosing aliquots and zero cross-colony pooling",
        "SEPARATED_CLONAL_COLONIES_INDEPENDENT_ALIQUOTS_NO_POOLING",
    }),
}
_SHIELD_ALLOWED_GY018_UNIT_CLASSES: frozenset[str] = frozenset(
    _SHIELD_ALLOWED_INDEPENDENT_EXPERIMENTAL_UNITS.keys()
)
_SHIELD_FWER_EXTERNAL_CUSTODY_CONDITION = (
    "Exact distribution-free FWER <= 0.05 Boole bound applies strictly to the fixed-roster, fixed-per-donor-N, "
    "single-look donor cytotoxicity family (H0_all: max_{i=1..N_roster} p_i <= 5.0%, NOT the union with SPR or "
    "suppression failure routes) and holds mathematically conditional on external outcome-blind custody and "
    "pre-readout commitment receipt of the FULL preregistered analysis plan inside preregistered_donor_family_roster "
    "(roster membership, fixed per-donor sample size N, and single-look fixed horizon planned_analysis_looks == 1) "
    "prior to assay readouts; unpinned, tampered, multi-look, sample-size-mismatched, or incompletely reconciled "
    "submissions fail closed to non-authorizing HOLD_INVALID_OR_MISSING_INPUT for overall PASS and donor-based "
    "FAIL (independent valid non-donor SPR failures remain fail-first FAIL, while out-of-spec physicochemical "
    "SEC-MALS/DLS measurements route to HOLD_INVALID_OR_MISSING_INPUT as unqualified material inputs)."
)
_SHIELD_SUPPRESSION_STATISTICAL_BOUNDARY_NOTE = (
    "Exact <= 5% finite-sample Clopper-Pearson suppression error control applies to the HLA-DQ-eligible "
    "(HLA-DQ2.5, HLA-DQ8, HLA-DQ8-trans, or HLA-DQ2.2) T1D donor sampling frame and is computed conservatively "
    "over donor, expression-batch, assay-run, and joint (batch U run) connected-component clusters "
    "(requiring >= 9 disjoint batch/run units for confirmatory PASS and >= 6 disjoint batch/run units "
    "for suppression FAIL) strictly for simple random or consecutive independent cohorts "
    "(sampling_design_class == 'SIMPLE_RANDOM_OR_CONSECUTIVE_INDEPENDENT_T1D_COHORT'); stratified/quota "
    "cohorts such as 'STRATIFIED_INDEPENDENT_T1D_HLA_DQ_COHORT' are non-authorizing for unweighted "
    "population-suppression inference and route to HOLD "
    "(STRATIFIED_COHORT_REQUIRES_TARGET_WEIGHTED_SUPPRESSION_ESTIMATOR). Only the one-sided lower bounds "
    "(suppression_responder_l95_clopper_pearson_pct and suppression_nonresponder_lt40_l95_clopper_pearson_pct) "
    "drive PASS/FAIL adjudication; suppression_responder_u95_clopper_pearson_pct is a descriptive diagnostic "
    "only with no general marginal upper-coverage guarantee under cluster-all-positive events. For each "
    "independent connected component C_j, the cluster-level all-positive event probability P(all donors in "
    "C_j meet threshold) is bounded above by the applicable single-donor marginal probability p_donor ONLY "
    "under independent components with non-informative cluster sizes and identical marginal response "
    "distributions across assay conditions; informative cluster sizes or systematically differing batch/run "
    "assay conditions are external sampling and laboratory QA assumptions not verified by ID graph topology "
    "alone, and external pre-readout custody of preregistered_donor_family_roster remains mandatory."
)
_SHIELD_LOCAL_JSON_REPLAY_SCOPE_NOTE = (
    "Local JSON replay verifies cryptographic digest calculation over the full pre-registered analysis plan "
    "(roster membership, fixed per-donor sample size N, and single-look fixed horizon planned_analysis_looks == 1), "
    "per-mixture physical co-formulation SEC-MALS/DLS binding, matched shared comparator expression-batch coverage "
    "across WT15 and 6DFX, complete raw roster accounting, strict canonical allowlist schemas for GY-018 and "
    "sampling-design declarations (zero free-text prose accepted), complete donor batch/run dependency topology "
    "retention, and cluster-conservative Clopper-Pearson/Bonferroni bounds only; an independent external pre-readout "
    "commitment receipt covering the full analysis plan and a laboratory QA audit verifying physical unit "
    "independence and target-population sampling are required before relying on the conditional statistical "
    "error-rate interpretation."
)

# Exact complete two-sided 95% Student-t critical values (alpha = 0.05; one-sided 97.5% quantile) for EVERY integer df = 1..30 (zero interpolation!)
_SHIELD_STUDENT_T_95_TWO_SIDED: dict[int, float] = {
    1: 12.706204736432095,
    2: 4.302652729911275,
    3: 3.182446305284263,
    4: 2.7764451051977987,
    5: 2.5705818366147395,
    6: 2.4469118487916806,
    7: 2.3646242510102993,
    8: 2.3060041350333704,
    9: 2.2621571627409915,
    10: 2.2281388519649385,
    11: 2.200985160082949,
    12: 2.1788128296634177,
    13: 2.1603686564610127,
    14: 2.1447866879169273,
    15: 2.131449545559323,
    16: 2.1199052992210112,
    17: 2.1098155778331806,
    18: 2.10092204024096,
    19: 2.093024054408263,
    20: 2.0859634472658364,
    21: 2.079613844727662,
    22: 2.0738730679040147,
    23: 2.0686576104190406,
    24: 2.0638985616280205,
    25: 2.059538552753294,
    26: 2.055529438642871,
    27: 2.0518305164802833,
    28: 2.048407141795244,
    29: 2.045229642132703,
    30: 2.0422724563012373,
}


def _shield_t95_critical(df: int) -> float:
    """Exact two-sided 95% (one-sided 97.5%) Student-t critical value (df=1..30 tabulated verbatim; Cornish-Fisher for df > 30)."""
    if df < 1:
        raise ValueError(f"Student-t degrees of freedom must be >= 1, got {df}")
    if df in _SHIELD_STUDENT_T_95_TWO_SIDED:
        return _SHIELD_STUDENT_T_95_TWO_SIDED[df]
    z = 1.959963984540054
    z3 = z ** 3
    z5 = z ** 5
    return z + (z3 + z) / (4.0 * df) + (5.0 * z5 + 16.0 * z3 + 3.0 * z) / (96.0 * (df ** 2))


def _shield_reject_nonfinite_tree(obj: Any, path: str = "root") -> None:
    """Pre-adjudication strict finiteness & magnitude check: raises ValueError on ANY NaN/Inf/abs>1e300 (Decimal, IEEE-754 float, or exact int)."""
    if isinstance(obj, Decimal):
        if not obj.is_finite() or obj.copy_abs() > Decimal("1e300"):
            raise ValueError(f"Non-finite or overflowing Decimal rejected fail-closed at {path}: {obj!r}")
    elif isinstance(obj, float):
        if not math.isfinite(obj) or abs(obj) > 1e300:
            raise ValueError(f"Non-finite or overflowing float rejected fail-closed at {path}: {obj!r}")
    elif type(obj) is int:
        if abs(obj) > 10 ** 300:
            raise ValueError(f"Overflowing integer rejected fail-closed at {path}")
    elif isinstance(obj, dict):
        for k, v in obj.items():
            _shield_reject_nonfinite_tree(v, f"{path}.{k}")
    elif isinstance(obj, (list, tuple)):
        for i, v in enumerate(obj):
            _shield_reject_nonfinite_tree(v, f"{path}[{i}]")


def _shield_binom_pmf(n: int, k: int, p: float) -> float:
    if p <= 0.0:
        return 1.0 if k == 0 else 0.0
    if p >= 1.0:
        return 1.0 if k == n else 0.0
    log_c = math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1)
    return math.exp(log_c + k * math.log(p) + (n - k) * math.log(1.0 - p))


def _shield_binom_cdf_le(n: int, k: int, p: float) -> float:
    if k < 0:
        return 0.0
    if k >= n:
        return 1.0
    if p <= 0.0:
        return 1.0
    if p >= 1.0:
        return 0.0
    if k <= n // 2:
        return min(1.0, sum(_shield_binom_pmf(n, j, p) for j in range(0, k + 1)))
    return max(0.0, 1.0 - sum(_shield_binom_pmf(n, j, p) for j in range(k + 1, n + 1)))


def _shield_binom_sf_ge(n: int, k: int, p: float) -> float:
    if k <= 0:
        return 1.0
    if k > n:
        return 0.0
    if p <= 0.0:
        return 0.0
    if p >= 1.0:
        return 1.0
    return max(0.0, min(1.0, 1.0 - _shield_binom_cdf_le(n, k - 1, p)))


def _clopper_pearson_one_sided_95_pct(k_obs: int, n_eff: int, alpha: float = 0.05) -> tuple[float, float]:
    """Exact one-sided (1 - alpha) Clopper-Pearson (lower_pct, upper_pct) for k_obs of n_eff independent units."""
    if n_eff < 1 or k_obs < 0 or k_obs > n_eff:
        raise ValueError(f"Invalid Clopper-Pearson counts: k_obs={k_obs}, n_eff={n_eff}")
    if not (0.0 < alpha < 1.0):
        raise ValueError(f"Invalid Clopper-Pearson alpha: {alpha!r}")
    if k_obs == 0:
        return 0.0, 100.0 * (1.0 - (alpha ** (1.0 / n_eff)))
    if k_obs == n_eff:
        return 100.0 * (alpha ** (1.0 / n_eff)), 100.0

    lo, hi = 0.0, k_obs / float(n_eff)
    for _ in range(70):
        mid = 0.5 * (lo + hi)
        if _shield_binom_sf_ge(n_eff, k_obs, mid) < alpha:
            lo = mid
        else:
            hi = mid
    lower = 0.5 * (lo + hi)

    lo, hi = k_obs / float(n_eff), 1.0
    for _ in range(70):
        mid = 0.5 * (lo + hi)
        if _shield_binom_cdf_le(n_eff, k_obs, mid) > alpha:
            lo = mid
        else:
            hi = mid
    upper = 0.5 * (lo + hi)
    return 100.0 * lower, 100.0 * upper


def _shield_check_num(
    val: Any,
    label: str,
    *,
    lo: float | None = None,
    hi: float | None = None,
    strictly_gt_lo: bool = False,
) -> tuple[float | None, str | None]:
    if isinstance(val, bool) or not isinstance(val, (int, float)):
        return None, f"{label} must be a finite non-bool numeric value (got {val!r})"
    fval = float(val)
    if lo is not None:
        if strictly_gt_lo and fval <= lo:
            return None, f"{label}={fval} must be > {lo}"
        if not strictly_gt_lo and fval < lo:
            return None, f"{label}={fval} violates lower bound {lo}"
    if hi is not None and fval > hi:
        return None, f"{label}={fval} violates upper bound {hi}"
    return fval, None


def _shield_check_strict_int(
    val: Any,
    label: str,
    *,
    min_val: int = 0,
    max_val: int | None = None,
) -> tuple[int | None, str | None]:
    if type(val) is not int:
        return None, f"{label} must be a strict integer (got {val!r})"
    if val < min_val:
        return None, f"{label}={val} < required minimum {min_val}"
    if max_val is not None and val > max_val:
        return None, f"{label}={val} > maximum {max_val}"
    return val, None


def _shield_check_exact_deff(val: Any, label: str) -> tuple[float | None, str | None]:
    """Enforce GY-018 exact zero-tolerance design_effect_deff == 1.0, preserving exact Decimal tokens
    decoded by load_strict_json_text (rejecting 1.00000000000000001 and 0.99999999999999999).
    """
    if isinstance(val, bool):
        return None, f"{label} must be a finite non-bool numeric value (got {val!r})"
    if isinstance(val, Decimal):
        if val == Decimal("1"):
            return 1.0, None
        return (
            None,
            f"{label}: GY-018 violation — exact design_effect_deff == 1.0 required "
            f"(got exact Decimal({str(val)!r}) != 1; zero tolerance)",
        )
    if type(val) is int:
        if val == 1:
            return 1.0, None
        return (
            None,
            f"{label}: GY-018 violation — exact design_effect_deff == 1.0 required "
            f"(got {val!r} != 1; zero tolerance)",
        )
    if isinstance(val, float):
        if math.isfinite(val) and val == 1.0:
            return 1.0, None
        return (
            None,
            f"{label}: GY-018 violation — exact design_effect_deff == 1.0 required "
            f"(got {val!r} != 1.0; zero tolerance)",
        )
    return None, f"{label} must be a finite non-bool numeric value (got {val!r})"


def _shield_canonicalize_construct_id(raw_cid: str) -> str:
    clean = raw_cid.strip()
    return _SHIELD_CONSTRUCT_CANONICAL_MAP.get(clean, clean)


def _shield_parse_batch_construct_ids(
    batch_obj: dict[str, Any],
    batch_id: str,
) -> tuple[frozenset[str] | None, str | None]:
    """Parse & validate non-empty construct_ids (or alias constructs) on a declared expression batch."""
    has_cids = "construct_ids" in batch_obj and batch_obj["construct_ids"] is not None
    has_cons = "constructs" in batch_obj and batch_obj["constructs"] is not None
    if not has_cids and not has_cons:
        return None, f"Expression batch {batch_id!r} missing non-empty construct_ids (or constructs) list"

    def _parse_one(raw_list: Any, field_name: str) -> tuple[frozenset[str] | None, str | None]:
        if not isinstance(raw_list, list) or len(raw_list) == 0:
            return None, f"Expression batch {batch_id!r} {field_name} must be a non-empty list of construct IDs"
        seen_c: set[str] = set()
        for c_idx, c_item in enumerate(raw_list):
            if type(c_item) is not str or not c_item.strip():
                return None, f"Expression batch {batch_id!r}.{field_name}[{c_idx}] must be a non-empty string (got {c_item!r})"
            canon = _shield_canonicalize_construct_id(c_item)
            if canon in seen_c:
                return None, f"Expression batch {batch_id!r}.{field_name} contains duplicate construct ID {canon!r}"
            seen_c.add(canon)
        return frozenset(seen_c), None

    cset_primary: frozenset[str] | None = None
    cset_alias: frozenset[str] | None = None
    if has_cids:
        cset_primary, err_p = _parse_one(batch_obj["construct_ids"], "construct_ids")
        if err_p is not None:
            return None, err_p
    if has_cons:
        cset_alias, err_a = _parse_one(batch_obj["constructs"], "constructs")
        if err_a is not None:
            return None, err_a
    if cset_primary is not None and cset_alias is not None and cset_primary != cset_alias:
        return None, (
            f"Expression batch {batch_id!r} construct_ids={sorted(cset_primary)} "
            f"disagrees with constructs={sorted(cset_alias)}"
        )
    final_set = cset_primary if cset_primary is not None else cset_alias
    return final_set, None


def _shield_validate_batch_ids(
    raw_ids: Any,
    label: str,
    passing_batch_constructs: dict[str, frozenset[str]],
    referenced_batches: set[str],
    *,
    required_construct_all: str | None = None,
    require_cocktail_both_leads: bool = False,
    role_comp1_batches: set[str] | None = None,
    role_comp2_batches: set[str] | None = None,
) -> str | None:
    if not isinstance(raw_ids, list) or len(raw_ids) == 0:
        return f"{label} missing non-empty expression_batch_ids linkage list"
    local_seen: set[str] = set()
    for idx, bid in enumerate(raw_ids):
        if type(bid) is not str or not bid.strip():
            return f"{label}.expression_batch_ids[{idx}] must be a non-empty string (got {bid!r})"
        bid_c = bid.strip()
        if bid_c in local_seen:
            return f"{label}.expression_batch_ids contains duplicate batch_id {bid_c!r}"
        local_seen.add(bid_c)
        if bid_c not in passing_batch_constructs:
            return f"{label}.expression_batch_ids references undeclared, empty-construct, or non-passing batch_id {bid_c!r}"

    if required_construct_all is not None:
        req_c = _shield_canonicalize_construct_id(required_construct_all)
        for bid_c in sorted(local_seen):
            if req_c not in passing_batch_constructs[bid_c]:
                return (
                    f"{label}.expression_batch_ids batch {bid_c!r} does not contain required construct "
                    f"{req_c!r} (batch construct_ids={sorted(passing_batch_constructs[bid_c])})"
                )

    if require_cocktail_both_leads:
        has_comp1 = False
        has_comp2 = False
        for bid_c in sorted(local_seen):
            bcons = passing_batch_constructs[bid_c]
            in_c1 = _SHIELD_COMP1_LEAD in bcons
            in_c2 = _SHIELD_COMP2_LEAD in bcons
            if not (in_c1 or in_c2):
                return (
                    f"{label}.expression_batch_ids cocktail assay references non-lead batch {bid_c!r} "
                    f"(batch construct_ids={sorted(bcons)})"
                )
            if in_c1:
                has_comp1 = True
            if in_c2:
                has_comp2 = True
        if not (has_comp1 and has_comp2):
            return (
                f"{label}.expression_batch_ids cocktail assay must link BOTH {_SHIELD_COMP1_LEAD!r} "
                f"and {_SHIELD_COMP2_LEAD!r} passing batches (has_comp1={has_comp1}, has_comp2={has_comp2})"
            )

    referenced_batches.update(local_seen)
    for bid_c in local_seen:
        bcons = passing_batch_constructs[bid_c]
        if role_comp1_batches is not None and _SHIELD_COMP1_LEAD in bcons:
            role_comp1_batches.add(bid_c)
        if role_comp2_batches is not None and _SHIELD_COMP2_LEAD in bcons:
            role_comp2_batches.add(bid_c)
    return None


def _shield_parse_qualifying_hla_genotype(raw_gt: Any, label: str) -> tuple[list[str] | None, str | None]:
    if type(raw_gt) is not str or not raw_gt.strip():
        return None, f"{label} missing non-empty qualifying T1D hla_genotype"
    norm = re.sub(r"\s*([/;,+|])\s*", r"\1", raw_gt.strip().upper())
    if norm in _SHIELD_QUALIFYING_HLA_DQ_TOKENS:
        return [norm], None
    raw_parts = [p.strip() for p in re.split(r"[;,+|]+", norm) if p.strip()]
    tokens: list[str] = []
    for part in raw_parts:
        if part in _SHIELD_QUALIFYING_HLA_DQ_TOKENS:
            tokens.append(part)
        elif "DQA1*" in part or "DQB1*" in part:
            return None, f"{label} has non-qualifying HLA-DQ allele pair {part!r}"
        else:
            sub = [s.strip() for s in part.split("/") if s.strip()]
            if not sub:
                return None, f"{label} has empty HLA-DQ token in {raw_gt!r}"
            for tok in sub:
                if tok not in _SHIELD_QUALIFYING_HLA_DQ_TOKENS:
                    return None, f"{label} contains non-qualifying HLA-DQ genotype token {tok!r} (from {raw_gt!r})"
                tokens.append(tok)
    if not tokens:
        return None, f"{label} contains no qualifying HLA-DQ tokens"
    return tokens, None


def _shield_student_t_ci_pct(
    values: list[float],
    *,
    lo_bound: float = _SHIELD_SUPPRESSION_ASSAY_ACCEPTANCE_MIN_PCT,
    hi_bound: float = _SHIELD_SUPPRESSION_ASSAY_ACCEPTANCE_MAX_PCT,
) -> tuple[float, float, float]:
    """Overflow-immune non-authorizing descriptive Student-t summary over finite float inputs.
    Clamps endpoints symmetrically to [lo_bound, hi_bound] (default [-1000.0, 100.0]% signed suppression scale)
    while guaranteeing non-inverted ordering L <= U (and L <= mean <= U whenever mean lies in [lo_bound, hi_bound]).
    """
    n = len(values)
    if n < 1:
        raise ValueError("Student-t diagnostic requires >= 1 value")
    if lo_bound > hi_bound:
        raise ValueError(f"Invalid Student-t clamp bounds: lo_bound={lo_bound} > hi_bound={hi_bound}")
    fvals = [float(x) for x in values]
    scale_abs = max(abs(x) for x in fvals)
    if not math.isfinite(scale_abs):
        return 0.0, lo_bound, hi_bound
    if scale_abs == 0.0:
        z_clamp = min(hi_bound, max(lo_bound, 0.0))
        return 0.0, z_clamp, z_clamp
    mean_scaled = sum(x / scale_abs for x in fvals) / float(n)
    mean_v = mean_scaled * scale_abs
    if not math.isfinite(mean_v):
        mean_v = 0.0
    if n == 1:
        m_clamp = min(hi_bound, max(lo_bound, mean_v))
        return mean_v, m_clamp, m_clamp
    devs_scaled = [(x / scale_abs) - mean_scaled for x in fvals]
    max_dev = max(abs(d) for d in devs_scaled)
    if max_dev == 0.0:
        m_clamp = min(hi_bound, max(lo_bound, mean_v))
        return mean_v, m_clamp, m_clamp
    norm_devs = [d / max_dev for d in devs_scaled]
    sd_unit = math.sqrt(sum(d * d for d in norm_devs) / float(n - 1))
    se_unit = sd_unit / math.sqrt(float(n))
    half_scaled = _shield_t95_critical(n - 1) * se_unit * max_dev
    lo_scaled = mean_scaled - half_scaled
    hi_scaled = mean_scaled + half_scaled
    lo_raw = lo_scaled * scale_abs
    hi_raw = hi_scaled * scale_abs
    lo_val = (lo_bound if lo_scaled <= 0.0 else hi_bound) if not math.isfinite(lo_raw) else min(hi_bound, max(lo_bound, lo_raw))
    hi_val = (hi_bound if hi_scaled >= 0.0 else lo_bound) if not math.isfinite(hi_raw) else min(hi_bound, max(lo_bound, hi_raw))
    if lo_val > hi_val:
        lo_val, hi_val = hi_val, lo_val
    return mean_v, lo_val, hi_val


def _shield_parse_iso8601_utc(raw_ts: Any, label: str) -> tuple[datetime | None, str | None]:
    """Validate strict unpadded ISO-8601 UTC timestamp (YYYY-MM-DDTHH:MM:SS[.ffffff]Z) compatible with Python 3.9+."""
    if type(raw_ts) is not str or not raw_ts or raw_ts != raw_ts.strip():
        return None, f"{label} must be a non-empty unpadded ISO-8601 UTC string (got {raw_ts!r})"
    if not _SHIELD_ISO8601_UTC_RE.match(raw_ts):
        return None, f"{label}={raw_ts!r} must match strict ISO-8601 UTC format YYYY-MM-DDTHH:MM:SS[.ffffff]Z"
    try:
        dt_val = datetime.fromisoformat(raw_ts[:-1] + "+00:00")
    except ValueError as exc:
        return None, f"{label}={raw_ts!r} is not a valid calendar UTC timestamp: {exc}"
    return dt_val, None


def _shield_compute_donor_roster_sha256(
    roster_id: str,
    preregistration_timestamp_utc: str,
    roster_donor_ids: list[str] | tuple[str, ...],
    *,
    predeclared_per_donor_unit_count_n: int | None = None,
    predeclared_per_donor_unit_counts: dict[str, int] | None = None,
    planned_analysis_looks: int = 1,
    single_look_fixed_horizon_plan_locked: bool = True,
) -> str:
    """Canonical lowercase 64-hex SHA-256 over UTF-8 compact sorted JSON committing the full
    outcome-blind pre-readout analysis plan:
    {planned_analysis_looks, predeclared_per_donor_unit_counts, preregistration_timestamp_utc,
     roster_donor_ids, roster_id, single_look_fixed_horizon_plan_locked[, predeclared_per_donor_unit_count_n]}.
    """
    ids_list = [str(x) for x in roster_donor_ids]
    if predeclared_per_donor_unit_counts is not None:
        per_donor_map = {str(did): int(predeclared_per_donor_unit_counts[did]) for did in ids_list}
    elif predeclared_per_donor_unit_count_n is not None:
        per_donor_map = {str(did): int(predeclared_per_donor_unit_count_n) for did in ids_list}
    else:
        raise ValueError(
            "Fixed per-donor sample size commitment (predeclared_per_donor_unit_count_n or "
            "predeclared_per_donor_unit_counts) is mandatory for roster_sha256"
        )
    payload: dict[str, Any] = {
        "planned_analysis_looks": int(planned_analysis_looks),
        "predeclared_per_donor_unit_counts": per_donor_map,
        "preregistration_timestamp_utc": str(preregistration_timestamp_utc),
        "roster_donor_ids": ids_list,
        "roster_id": str(roster_id),
        "single_look_fixed_horizon_plan_locked": bool(single_look_fixed_horizon_plan_locked),
    }
    if predeclared_per_donor_unit_count_n is not None:
        payload["predeclared_per_donor_unit_count_n"] = int(predeclared_per_donor_unit_count_n)
    raw = json.dumps(payload, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
    return hashlib.sha256(raw).hexdigest()


def _shield_build_preregistered_roster(
    roster_donor_ids: list[str] | tuple[str, ...],
    *,
    roster_id: str = "ROSTER_SHIELD_T1D_PREREG_V1",
    preregistration_timestamp_utc: str = "2026-11-28T00:00:00Z",
    predeclared_per_donor_unit_count_n: int | None = _SHIELD_MIN_CYTO_N_EFF_PER_DONOR,
    predeclared_per_donor_unit_counts: dict[str, int] | None = None,
    planned_analysis_looks: int = 1,
    single_look_fixed_horizon_plan_locked: bool = True,
) -> dict[str, Any]:
    """Construct a cryptographically hash-pinned outcome-blind pre-registered T1D donor family roster
    committing donor membership, fixed per-donor cytotoxicity sample size N, and single-look fixed horizon.
    """
    ids_list = [str(x) for x in roster_donor_ids]
    out: dict[str, Any] = {
        "roster_id": str(roster_id),
        "preregistration_timestamp_utc": str(preregistration_timestamp_utc),
        "outcome_blind_lock_attestation": True,
        "single_look_fixed_horizon_plan_locked": bool(single_look_fixed_horizon_plan_locked),
        "planned_analysis_looks": int(planned_analysis_looks),
        "roster_donor_ids": ids_list,
        "planned_t1d_donor_family_n": len(ids_list),
    }
    if predeclared_per_donor_unit_counts is not None:
        counts_map = {str(did): int(predeclared_per_donor_unit_counts[did]) for did in ids_list}
        out["predeclared_per_donor_unit_counts"] = counts_map
        if predeclared_per_donor_unit_count_n is not None:
            out["predeclared_per_donor_unit_count_n"] = int(predeclared_per_donor_unit_count_n)
        out["roster_sha256"] = _shield_compute_donor_roster_sha256(
            roster_id,
            preregistration_timestamp_utc,
            ids_list,
            predeclared_per_donor_unit_count_n=predeclared_per_donor_unit_count_n,
            predeclared_per_donor_unit_counts=counts_map,
            planned_analysis_looks=planned_analysis_looks,
            single_look_fixed_horizon_plan_locked=single_look_fixed_horizon_plan_locked,
        )
    else:
        fixed_n = int(_SHIELD_MIN_CYTO_N_EFF_PER_DONOR if predeclared_per_donor_unit_count_n is None else predeclared_per_donor_unit_count_n)
        out["predeclared_per_donor_unit_count_n"] = fixed_n
        out["roster_sha256"] = _shield_compute_donor_roster_sha256(
            roster_id,
            preregistration_timestamp_utc,
            ids_list,
            predeclared_per_donor_unit_count_n=fixed_n,
            planned_analysis_looks=planned_analysis_looks,
            single_look_fixed_horizon_plan_locked=single_look_fixed_horizon_plan_locked,
        )
    return out


def _shield_descriptive_quantiles(values: list[float]) -> tuple[float, float, float, float]:
    """Return (mean, median, min, iqr) using exact linear interpolation (overflow-immune pure stdlib)."""
    svals = sorted(float(v) for v in values)
    n = len(svals)
    scale_abs = max(abs(x) for x in svals)
    mean_v = 0.0 if scale_abs == 0.0 else (sum(x / scale_abs for x in svals) / float(n)) * scale_abs
    min_v = svals[0]

    def _pct(p: float) -> float:
        if n == 1:
            return svals[0]
        pos = p * float(n - 1)
        lo_i = int(math.floor(pos))
        hi_i = int(math.ceil(pos))
        frac = pos - float(lo_i)
        return (1.0 - frac) * svals[lo_i] + frac * svals[hi_i]

    med_v = _pct(0.5)
    q75 = _pct(0.75)
    q25 = _pct(0.25)
    iqr_v = q75 - q25 if math.isfinite(q75 - q25) else 0.0
    return mean_v, med_v, min_v, iqr_v


def _shield_connected_clusters(
    roster_ids: list[str],
    donor_group_sets: dict[str, set[str]],
) -> list[list[str]]:
    """Deterministic Union-Find partition of fixed roster_ids merging any two donors that share
    at least one batch or assay-run token into one conservative independent cluster.
    Submitted donors retain their validated batch/run dependency edges even when unrelated
    outcome or CI fields fail; pre-assay-excluded unmeasured donors remain singletons.
    """
    parent: dict[str, str] = {did: did for did in roster_ids}

    def _find(x: str) -> str:
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x

    def _union(a: str, b: str) -> None:
        ra, rb = _find(a), _find(b)
        if ra != rb:
            if ra < rb:
                parent[rb] = ra
            else:
                parent[ra] = rb

    token_owner: dict[str, str] = {}
    for did in roster_ids:
        for tok in sorted(donor_group_sets.get(did, ())):
            if tok in token_owner:
                _union(did, token_owner[tok])
            else:
                token_owner[tok] = did

    comps: dict[str, list[str]] = {}
    for did in roster_ids:
        comps.setdefault(_find(did), []).append(did)
    return [comps[k] for k in sorted(comps)]


def build_valid_shield_spr_observation(
    *,
    n_eff_per_donor: int = 60,
    donor_k_obs: tuple[int, ...] | None = None,
    donor_suppressions: tuple[float, ...] | None = None,
    include_optional_1jk8: bool = True,
    planned_t1d_donor_family_n: int | None = None,
    include_preregistered_roster: bool = True,
    roster_donor_ids: list[str] | tuple[str, ...] | None = None,
    roster_id: str = "ROSTER_SHIELD_T1D_PREREG_V1",
    preregistration_timestamp_utc: str = "2026-11-28T00:00:00Z",
    excluded_donor_records: list[dict[str, Any]] | None = None,
    shared_expression_batches_n: int | None = None,
    shared_assay_runs_n: int | None = None,
    sampling_design_class: str = "SIMPLE_RANDOM_OR_CONSECUTIVE_INDEPENDENT_T1D_COHORT",
    separate_comp1_comp2_batches: bool = False,
) -> dict[str, Any]:
    """Build a complete typed Gate 30-SHIELD-SPR PASS record with all mandatory evidence blocks,
    mandatory hash-pinned outcome-blind preregistered_donor_family_roster committing donor membership,
    fixed per-donor cytotoxicity sample size N, and single-look fixed horizon (defaulting to 9 confirmatory
    T1D donors across 9 disjoint physical co-formulation mixtures MIX_SHIELD_01..09 and 9 disjoint
    assay_run_ids so cluster-conservative exact Clopper-Pearson responder L95(9/9) = 71.687116% >= 70.0%
    achieves calibrated PASS), typed donor_sampling_and_independence_design, construct-bound
    expression_batches (cocktail leads + dedicated comparator batches), full Comp1+Comp2 off-target controls,
    WT15 reagent-lot linkage, per-mixture quantitative SEC-MALS/DLS co-formulation qualification, typed T1D
    donor eligibility provenance, qualifying donor hla_genotype, authorization-grade typed GY-018 independence
    evidence record, and GY-018-compliant cytotoxicity denominators (exact deff == 1.0, n_eff == raw_independent_units_n >= 60).
    """
    if donor_k_obs is None and donor_suppressions is None:
        k_seq: tuple[int, ...] = tuple(0 for _ in range(_SHIELD_MIN_CONFIRMATORY_DONORS_N))
        sup_seq: tuple[float, ...] = (82.0, 84.0, 86.0, 81.0, 83.0, 85.0, 82.5, 84.5, 83.5)
    elif donor_k_obs is not None and donor_suppressions is None:
        k_seq = tuple(int(x) for x in donor_k_obs)
        sup_seq = tuple(84.0 for _ in range(len(k_seq)))
    elif donor_k_obs is None and donor_suppressions is not None:
        sup_seq = tuple(float(x) for x in donor_suppressions)
        k_seq = tuple(0 for _ in range(len(sup_seq)))
    else:
        k_seq = tuple(int(x) for x in donor_k_obs)
        sup_seq = tuple(float(x) for x in donor_suppressions)

    n_donors = max(len(k_seq), len(sup_seq))
    n_lead_batches = (
        int(shared_expression_batches_n)
        if shared_expression_batches_n is not None
        else max(_SHIELD_MIN_BATCHES_N, n_donors)
    )
    n_assay_runs = (
        int(shared_assay_runs_n)
        if shared_assay_runs_n is not None
        else max(1, n_donors)
    )
    if separate_comp1_comp2_batches:
        c1_lead_batch_ids = [f"BATCH_C1_{i:02d}" for i in range(1, n_lead_batches + 1)]
        c2_lead_batch_ids = [f"BATCH_C2_{i:02d}" for i in range(1, n_lead_batches + 1)]
        spr_c1_batch_ids = c1_lead_batch_ids[: max(_SHIELD_MIN_BATCHES_N, min(3, len(c1_lead_batch_ids)))]
        spr_c2_batch_ids = c2_lead_batch_ids[: max(_SHIELD_MIN_BATCHES_N, min(3, len(c2_lead_batch_ids)))]
        sec_all_lead_batch_ids = c1_lead_batch_ids + c2_lead_batch_ids
        rqc_parent_batch_ids = spr_c1_batch_ids + spr_c2_batch_ids
        expression_batches: list[dict[str, Any]] = (
            [{"batch_id": bid, "construct_ids": [_SHIELD_COMP1_LEAD], "qc_passed": True} for bid in c1_lead_batch_ids]
            + [{"batch_id": bid, "construct_ids": [_SHIELD_COMP2_LEAD], "qc_passed": True} for bid in c2_lead_batch_ids]
        )
    else:
        lead_batch_ids = [f"BATCH_ECOLI_{i:02d}" for i in range(1, n_lead_batches + 1)]
        c1_lead_batch_ids = list(lead_batch_ids)
        c2_lead_batch_ids = list(lead_batch_ids)
        spr_c1_batch_ids = lead_batch_ids[: max(_SHIELD_MIN_BATCHES_N, min(3, len(lead_batch_ids)))]
        spr_c2_batch_ids = list(spr_c1_batch_ids)
        sec_all_lead_batch_ids = list(lead_batch_ids)
        rqc_parent_batch_ids = list(spr_c1_batch_ids)
        expression_batches = [
            {"batch_id": bid, "construct_ids": list(_SHIELD_COCKTAIL_LEADS), "qc_passed": True}
            for bid in lead_batch_ids
        ]

    hip11_reagent_lot_id = "REAGENT_HIP11_EXCHANGE_LOT01"
    wt15_reagent_lot_id = "REAGENT_WT15_INSB9_23_LOT01"
    r6dfx_reagent_lot_id = "REAGENT_6DFX_P8E9E_LOT01"
    comparator_batch_map: dict[str, str] = {
        cid: f"BATCH_COMP_{cid}"
        for cid in _SHIELD_MANDATORY_COMP2_COMPARATORS
        if cid != _SHIELD_COMP2_LEAD
    }
    for cid, cbid in comparator_batch_map.items():
        expression_batches.append(
            {"batch_id": cbid, "construct_ids": [cid], "qc_passed": True}
        )

    qualified_mixtures: list[dict[str, Any]] = [
        {
            "mixture_id": f"MIX_SHIELD_{m_idx + 1:02d}",
            "comp1_expression_batch_id": c1_lead_batch_ids[m_idx],
            "comp2_expression_batch_id": c2_lead_batch_ids[m_idx],
            "monomer_pct": 96.8,
            "dls_pdi": 0.08,
            "no_aggregates_or_precipitation": True,
            "qc_passed": True,
            "equimolar_1to1_molar_ratio_attested": True,
            "ratio_basis_attestation": "LAB_ATTESTED_1TO1_MOLAR_COFORMULATION_MIXING_PROTOCOL",
        }
        for m_idx in range(n_lead_batches)
    ]

    donors: list[dict[str, Any]] = []
    for i in range(n_donors):
        k_i = k_seq[i] if i < len(k_seq) else 0
        s_i = sup_seq[i] if i < len(sup_seq) else 84.0
        run_idx = (i % n_assay_runs) + 1
        mix_idx = i % n_lead_batches
        donor_batches = (
            [c1_lead_batch_ids[mix_idx], c2_lead_batch_ids[mix_idx]]
            if separate_comp1_comp2_batches
            else [c1_lead_batch_ids[mix_idx]]
        )
        donors.append(
            {
                "donor_id": f"T1D_DONOR_{i + 1:02d}",
                "t1d_diagnosis_confirmed": True,
                "donor_clinical_cohort": _SHIELD_REQUIRED_DONOR_CLINICAL_COHORT,
                "t1d_prequalification_ref": f"PREQUAL_T1D_DONOR_{i + 1:02d}",
                "hla_genotype": "HLA-DQ2.5/HLA-DQ8",
                "assay_run_id": f"SHIELD_ASSAY_RUN_{run_idx:02d}",
                "cocktail_mixture_id": f"MIX_SHIELD_{mix_idx + 1:02d}",
                "expression_batch_ids": donor_batches,
                "suppression_pct": float(s_i),
                "raw_independent_units_n": int(n_eff_per_donor),
                "design_effect_deff": 1.0,
                "cytotoxicity_independence_model": _SHIELD_CYTO_INDEPENDENCE_MODEL,
                "gy018_independence_justification": {
                    "independent_unit_class": "INDEPENDENT_REPLICATE_WELLS",
                    "within_donor_units_physically_independent": True,
                    "clustering_controls_present_and_verified": True,
                    "shared_well_technical_reads_excluded": True,
                    "independence_evidence_record_id": f"GY018-REC-T1D-DONOR-{i + 1:02d}",
                    "independent_experimental_unit": (
                        "Single pre-aliquoted independent primary T1D APC assay well "
                        "(distinct physically isolated well per unit prior to dosing)"
                    ),
                    "predeclared_per_donor_unit_count_n": int(n_eff_per_donor),
                    "clustering_controls": (
                        "Randomized plate layout across physically separated wells with independent "
                        "dosing aliquots and zero cross-well pooling"
                    ),
                },
                "apc_cytotoxicity_k_obs": int(k_i),
                "apc_cytotoxicity_n_eff": int(n_eff_per_donor),
            }
        )
    register_qc: dict[str, Any] = {
        "expression_batch_ids": list(rqc_parent_batch_ids),
        "hip11_dq25_dq8t_dq22_exchange_qc_passed": True,
        "hip11_peptide_reagent_lot_id": hip11_reagent_lot_id,
        "native_wt_insb9_23_15aa": {
            "sequence": "SHLVEALYLVCGERG",
            "peptide_reagent_lot_id": wt15_reagent_lot_id,
            "lcms_identity_passed": True,
            "register2_occupancy_qc_passed": True,
        },
        "engineered_6dfx_p8e9e_12aa": {
            "sequence": "VEELYLVAGEEG",
            "peptide_reagent_lot_id": r6dfx_reagent_lot_id,
            "qc_passed": True,
        },
    }
    if include_optional_1jk8:
        register_qc["crystal_ref_1jk8_14aa"] = {
            "sequence": "LVEALYLVCGERGG",
            "qc_passed": True,
            "expression_batch_ids": list(spr_c2_batch_ids),
        }
    obs_out: dict[str, Any] = {
        "expression_batches": expression_batches,
        "donor_sampling_and_independence_design": {
            "sampling_design_class": sampling_design_class,
            "independent_donor_sampling_attested": True,
            "between_donor_shared_shock_controls_verified": True,
            "sampling_protocol_ref": "PROTOCOL:GATE30-SHIELD-COHORT-INDEP-V1",
            "between_donor_independence_justification": (
                "STRATIFIED_DISJOINT_BATCH_AND_RUN_T1D_DONOR_COHORT"
                if sampling_design_class == "STRATIFIED_INDEPENDENT_T1D_HLA_DQ_COHORT"
                else (
                    "Simple random or consecutive independent T1D HLA-DQ donors executed across disjoint "
                    "expression batches and separate assay runs with independent reagent preparations"
                )
            ),
        },
        "on_target_analytes": [
            {
                "analyte_id": "HLA-DQ2.5 + HIP11",
                "peptide_reagent_lot_id": hip11_reagent_lot_id,
                "replicates_n": 3,
                "expression_batch_ids": list(spr_c1_batch_ids),
                "ic50_l95_nm": 18.0,
                "ic50_u95_nm": 42.0,
                "selectivity_l95_fold": 95.0,
                "selectivity_u95_fold": 160.0,
            },
            {
                "analyte_id": "HLA-DQ8-trans + HIP11",
                "peptide_reagent_lot_id": hip11_reagent_lot_id,
                "replicates_n": 3,
                "expression_batch_ids": list(spr_c1_batch_ids),
                "ic50_l95_nm": 22.0,
                "ic50_u95_nm": 48.0,
                "selectivity_l95_fold": 85.0,
                "selectivity_u95_fold": 140.0,
            },
            {
                "analyte_id": "HLA-DQ2.2 + HIP11",
                "peptide_reagent_lot_id": hip11_reagent_lot_id,
                "replicates_n": 3,
                "expression_batch_ids": list(spr_c1_batch_ids),
                "ic50_l95_nm": 24.0,
                "ic50_u95_nm": 52.0,
                "selectivity_l95_fold": 78.0,
                "selectivity_u95_fold": 135.0,
            },
            {
                "analyte_id": "HLA-DQ8 + native WT InsB:9-23",
                "peptide_sequence": "SHLVEALYLVCGERG",
                "peptide_reagent_lot_id": wt15_reagent_lot_id,
                "replicates_n": 3,
                "expression_batch_ids": list(spr_c2_batch_ids),
                "ic50_l95_nm": 20.0,
                "ic50_u95_nm": 46.0,
                "selectivity_l95_fold": 88.0,
                "selectivity_u95_fold": 150.0,
            },
        ],
        "off_target_controls": [
            {
                "analyte_id": "HLA-DQ2.5 + CLIP1",
                "replicates_n": 3,
                "expression_batch_ids": list(spr_c1_batch_ids),
                "selectivity_l95_fold": 92.0,
                "selectivity_u95_fold": 165.0,
            },
            {
                "analyte_id": "HLA-DQ2.5 + Self_IGKV2_EAED",
                "replicates_n": 3,
                "expression_batch_ids": list(spr_c1_batch_ids),
                "selectivity_l95_fold": 80.0,
                "selectivity_u95_fold": 145.0,
            },
            {
                "analyte_id": "HLA-DQ2.5 + cel_glutenin_L1",
                "replicates_n": 3,
                "expression_batch_ids": list(spr_c1_batch_ids),
                "selectivity_l95_fold": 72.0,
                "selectivity_u95_fold": 130.0,
            },
            {
                "analyte_id": "HLA-DQ8-trans + Cpep_Nterm_EAED",
                "replicates_n": 3,
                "expression_batch_ids": list(spr_c1_batch_ids),
                "selectivity_l95_fold": 84.0,
                "selectivity_u95_fold": 150.0,
            },
            {
                "analyte_id": "HLA-DQ8 + CLIP1",
                "replicates_n": 3,
                "expression_batch_ids": list(spr_c2_batch_ids),
                "selectivity_l95_fold": 90.0,
                "selectivity_u95_fold": 160.0,
            },
            {
                "analyte_id": "HLA-DQ8 + DQ8-glia-gamma1a",
                "replicates_n": 3,
                "expression_batch_ids": list(spr_c2_batch_ids),
                "selectivity_l95_fold": 75.0,
                "selectivity_u95_fold": 130.0,
            },
            {
                "analyte_id": "HLA-DQ8-trans + WT InsB:9-23",
                "peptide_sequence": "SHLVEALYLVCGERG",
                "peptide_reagent_lot_id": wt15_reagent_lot_id,
                "replicates_n": 3,
                "expression_batch_ids": list(spr_c2_batch_ids),
                "selectivity_l95_fold": 82.0,
                "selectivity_u95_fold": 145.0,
            },
        ],
        "comp2_comparators_screened": [
            {
                "comparator_id": cid,
                "screened": True,
                "replicates_n": 3,
                "expression_batch_ids": list(spr_c2_batch_ids) if cid == _SHIELD_COMP2_LEAD else [comparator_batch_map[cid]],
                "register_control_screens": {
                    "native_wt_insb9_23_15aa": {
                        "screened": True,
                        "peptide_sequence": "SHLVEALYLVCGERG",
                        "peptide_reagent_lot_id": wt15_reagent_lot_id,
                        "expression_batch_ids": list(spr_c2_batch_ids) if cid == _SHIELD_COMP2_LEAD else [comparator_batch_map[cid]],
                        "replicates_n": 3,
                        "evidence_record_id": f"SPR-COMP-{cid}-WT15",
                    },
                    "engineered_6dfx_p8e9e_12aa": {
                        "screened": True,
                        "peptide_sequence": "VEELYLVAGEEG",
                        "peptide_reagent_lot_id": r6dfx_reagent_lot_id,
                        "expression_batch_ids": list(spr_c2_batch_ids) if cid == _SHIELD_COMP2_LEAD else [comparator_batch_map[cid]],
                        "replicates_n": 3,
                        "evidence_record_id": f"SPR-COMP-{cid}-6DFX",
                    },
                },
            }
            for cid in _SHIELD_MANDATORY_COMP2_COMPARATORS
        ],
        "register_qc_records": register_qc,
        "sec_mals_dls_monomer_coformulation": {
            "expression_batch_ids": list(sec_all_lead_batch_ids),
            "comp1_qf09_pi2_alone_monomer_qc_passed": True,
            "comp2_t006_alone_monomer_qc_passed": True,
            "cocktail_1to1_coformulation_qc_passed": True,
            "protenix_homodimer_flag_iptm_addressed": 0.6691,
            "comp1_monomer_pct": 98.2,
            "comp2_monomer_pct": 97.5,
            "cocktail_1to1_monomer_pct": 96.8,
            "dls_pdi": 0.08,
            "no_aggregates_or_precipitation": True,
            "qualified_coformulation_mixtures": qualified_mixtures,
        },
        "tcell_blockade_and_apc_cytotoxicity_donors": donors,
    }
    if include_preregistered_roster:
        if roster_donor_ids is not None:
            r_ids = [str(x) for x in roster_donor_ids]
        else:
            r_n = max(n_donors, int(planned_t1d_donor_family_n) if planned_t1d_donor_family_n is not None else n_donors)
            r_ids = [f"T1D_DONOR_{i + 1:02d}" for i in range(r_n)]
        obs_out["preregistered_donor_family_roster"] = _shield_build_preregistered_roster(
            r_ids,
            roster_id=roster_id,
            preregistration_timestamp_utc=preregistration_timestamp_utc,
            predeclared_per_donor_unit_count_n=int(n_eff_per_donor),
        )
    if planned_t1d_donor_family_n is not None:
        obs_out["planned_t1d_donor_family_n"] = int(planned_t1d_donor_family_n)
    if excluded_donor_records is not None:
        obs_out["excluded_donor_records"] = list(excluded_donor_records)
    return obs_out


def evaluate_gate30_shield_spr(observation: dict[str, Any]) -> dict[str, Any]:
    """Executable typed fail-first Gate 30-SHIELD-SPR adjudicator synchronized 100% identically
    across verify_iip0044_foundry_v1_3_biologics.py and verify_iip0042_master_multilayer_portfolio_crosswalk.py.

    Pre-adjudication input integrity:
      Non-dict payloads or ANY non-finite (NaN/Inf) or overflowing (IEEE-754 binary64 abs(x) > 1e300
      for float; exact abs(x) > 10**300 for int) numeric anywhere in the input tree raise ValueError
      BEFORE decision precedence (and strict JSON text decoding rejects raw decimal literals with |d| > 10^300).

    Unique 6-level fail-first decision precedence:
      FAIL > HOLD_INVALID_OR_MISSING_INPUT > HOLD_CYTOTOXICITY_U95_EXCEEDS_5PCT
        > HOLD_OBSERVED_NONZERO_CYTOTOXICITY > HOLD > PASS

    Requires all typed evidence blocks with construct-bound expression_batch_ids linkage (rejecting empty
    construct_ids batches; binding Comp1 assays to IsletSHIELD_QF09_pI2, Comp2 assays + register QC to
    IsletSHIELD_Comp2_T006, each comparator to its own construct, and cocktail assays to BOTH leads with
    >= 3 distinct Comp1 and >= 3 distinct Comp2 batches linked across assay evidence), all 4 mandatory
    on-target analytes (requiring peptide_sequence='SHLVEALYLVCGERG' and matching peptide_reagent_lot_id
    between the WT15 on-target analyte and register_qc_records.native_wt_insb9_23_15aa), all 7 off-target
    controls (4 Comp1 + 3 Comp2), all 6 Comp2 comparators, mandatory register QC (HIP11, 15-aa WT InsB:9-23,
    12-aa 6DFX; optional physical 14-aa 1JK8 omitted OR null -> PASS, any non-null value validated strictly),
    quantitative SEC-MALS/DLS (>= 95.0% monomer, PDI <= 0.15, no_aggregates_or_precipitation=True reconciled
    with boolean QC flags), mandatory typed donor_sampling_and_independence_design + per-donor assay_run_id,
    mandatory typed T1D donor eligibility (t1d_diagnosis_confirmed=True, donor_clinical_cohort='T1D',
    non-empty unpadded t1d_prequalification_ref, rejecting contradictory non-T1D donor tokens even if flags
    are forged), qualifying donor hla_genotype allowlist, mandatory authorization-grade typed +
    contradiction-guarded gy018_independence_justification, exact GY-018 design_effect_deff == 1.0 (zero
    tolerance, preserved as exact Decimal through JSON decoding), suppression assay acceptance range [-1000.0, 100.0]%
    with overflow-immune non-authorizing Student-t diagnostic, mandatory cryptographically hash-pinned
    outcome-blind preregistered_donor_family_roster (100% reconciled on ALL raw submitted donor IDs BEFORE
    deduplication/quarantine filtering; unverified/unpinned/incomplete/unrostered rosters fail closed to
    HOLD_INVALID_OR_MISSING_INPUT for overall PASS and donor-based FAIL, while independent valid non-donor
    SPR failures remain fail-first FAIL tagged failure_domain='INDEPENDENT_NON_DONOR_SPR' and out-of-spec
    physicochemical SEC-MALS/DLS measurements hold as unqualified material inputs with failure_domain=None),
    cluster-conservative distribution-free exact one-sided Clopper-Pearson suppression inference across donor,
    expression-batch, assay-run, and joint (batch U run) connected components (confirmatory PASS requires
    >= 9 disjoint batch/run clusters and L95_CP >= 70.0% + anti-enhancement min >= 0.0% + mean >= 70.0%;
    suppression FAIL requires L95_CP(k_lt_40) > 60.0% across >= 6 disjoint batch/run clusters; Student-t is
    strictly non-authorizing; only one-sided lower bounds drive adjudication while U95 is descriptive only),
    100%-measured full-roster cytotoxicity requirement for confirmatory PASS
    (len(excluded_donor_records) == 0 and valid_donor_records_n == N_roster), and distribution-free fixed
    pre-exclusion roster Bonferroni-calibrated FWER <= 0.05 cytotoxicity FAIL rule under H0_all:
    max_{i=1..N_roster} p_i <= 5.0% using alpha_donor = 0.05 / N_roster (scoped strictly to the fixed-roster
    donor cytotoxicity family, conditional on external outcome-blind custody & pre-readout receipt; cohort
    Student-t lower bound is strictly non-authorizing). Two-pass order-independent canonical key uniqueness
    runs BEFORE biological threshold adjudication across ALL evidence lists (expression_batches,
    on_target_analytes, off_target_controls, comp2_comparators_screened, donors), and derived_summary emits
    machine-checked trackb_shield_trigger_state distinguishing SHIELD-1-only Comp2 failure vs overall SHIELD
    failure while excluding all non-FAIL, held, invalid, and partial-FAIL states.
    """
    if not isinstance(observation, dict):
        raise ValueError("Gate 30-SHIELD-SPR observation must be a JSON object")
    _shield_reject_nonfinite_tree(observation, "observation")

    reasons: list[str] = []
    worst_state = "PASS"
    spr_bio_fail = False
    comp1_spr_bio_fail = False
    comp2_spr_bio_fail = False
    comp1_on_target_passed_analytes: set[str] = set()
    comp1_off_target_passed_controls: set[str] = set()
    donor_based_bio_fail = False
    derived_summary: dict[str, Any] = {}

    def _escalate(state: str, reason: str) -> None:
        nonlocal worst_state
        reasons.append(f"[{state}] {reason}")
        if _SHIELD_SPR_PRECEDENCE[state] > _SHIELD_SPR_PRECEDENCE[worst_state]:
            worst_state = state

    # 1. Expression batches (R08 B3: two-pass order-independent uniqueness BEFORE accepting passing batches;
    #    >= 3 distinct passing batches per cocktail lead; non-empty construct_ids required on EVERY batch)
    batches = observation.get("expression_batches")
    passing_batch_constructs: dict[str, frozenset[str]] = {}
    referenced_batches: set[str] = set()
    comp1_assay_batches: set[str] = set()
    comp2_assay_batches: set[str] = set()
    cocktail_comp1_batches: set[str] = set()
    cocktail_comp2_batches: set[str] = set()
    conflicted_batch_ids: set[str] = set()
    if not isinstance(batches, list) or len(batches) == 0:
        _escalate("HOLD_INVALID_OR_MISSING_INPUT", "Missing typed expression_batches list (>= 3 distinct batches required)")
    else:
        batch_id_counts: dict[str, int] = {}
        for b in batches:
            if isinstance(b, dict):
                bid = b.get("batch_id")
                if type(bid) is str and bid.strip():
                    bid_c = bid.strip()
                    batch_id_counts[bid_c] = batch_id_counts.get(bid_c, 0) + 1
        conflicted_batch_ids = {k for k, cnt in batch_id_counts.items() if cnt > 1}
        for cbid in sorted(conflicted_batch_ids):
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"Duplicate/conflicting expression batch_id: {cbid!r} (count={batch_id_counts[cbid]}); all occurrences excluded",
            )

        lead_batch_counts: dict[str, int] = {ld: 0 for ld in _SHIELD_COCKTAIL_LEADS}
        for idx, b in enumerate(batches):
            if not isinstance(b, dict):
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"expression_batches[{idx}] must be an object")
                continue
            bid = b.get("batch_id")
            if type(bid) is not str or not bid.strip():
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"expression_batches[{idx}] missing non-empty batch_id")
                continue
            bid_clean = bid.strip()
            if bid_clean in conflicted_batch_ids:
                continue
            if b.get("qc_passed") is not True:
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"Expression batch {bid_clean!r} failed qc_passed")
                continue
            c_set, c_err = _shield_parse_batch_construct_ids(b, bid_clean)
            if c_err is not None or c_set is None:
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", c_err or f"Invalid construct_ids on batch {bid_clean!r}")
                continue
            passing_batch_constructs[bid_clean] = c_set
            for ld in _SHIELD_COCKTAIL_LEADS:
                if ld in c_set:
                    lead_batch_counts[ld] += 1
        if len(passing_batch_constructs) < _SHIELD_MIN_BATCHES_N:
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"Under-replicated passing expression_batches: {len(passing_batch_constructs)} < {_SHIELD_MIN_BATCHES_N}",
            )
        for ld, cnt in lead_batch_counts.items():
            if cnt < _SHIELD_MIN_BATCHES_N:
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"Construct {ld} covered by only {cnt} passing batches (< {_SHIELD_MIN_BATCHES_N})",
                )

    # 2. Register QC records (R12 0039-B1 + R14 0039-B2 + R17 0044-B1/B2: validated and reconciled STRICTLY BEFORE
    #    on-target/off-target SPR biological adjudication and batch-linkage credit! Cocktail-bound batches covering
    #    BOTH Comp1 HIP11 and Comp2 WT15/6DFX validate parent coverage ONLY and NEVER credit comp1_assay_batches or
    #    comp2_assay_batches (which count ONLY validated SPR/comparator rows). Mandatory pairwise-distinct peptide
    #    reagent lot IDs are enforced across HIP11, 15-aa WT InsB:9-23, 12-aa 6DFX, and optional 14-aa 1JK8 if present
    #    BEFORE granting dependent records biological or batch credit, while retaining independent qualified evidence!)
    rqc = observation.get("register_qc_records")
    hip11_exchange_qc_valid = False
    r6dfx_qc_valid = False
    wt15_register_qc_valid = False
    r1jk8_qc_valid = False
    rqc_hip11_lot: str | None = None
    rqc_wt_lot: str | None = None
    rqc_6dfx_lot: str | None = None
    rqc_1jk8_lot: str | None = None
    rqc_comp1_batches: set[str] = set()
    rqc_comp2_batches: set[str] = set()
    collided_reagents: set[str] = set()
    if not isinstance(rqc, dict):
        _escalate("HOLD_INVALID_OR_MISSING_INPUT", "Missing typed register_qc_records object")
        derived_summary["optional_1jk8_physical_control_present"] = False
    else:
        tmp_ref_rqc: set[str] = set()
        tmp_c1_rqc: set[str] = set()
        tmp_c2_rqc: set[str] = set()
        rqc_b_err = _shield_validate_batch_ids(
            rqc.get("expression_batch_ids"),
            "register_qc_records",
            passing_batch_constructs,
            tmp_ref_rqc,
            require_cocktail_both_leads=True,
            role_comp1_batches=tmp_c1_rqc,
            role_comp2_batches=tmp_c2_rqc,
        )
        rqc_batch_valid = rqc_b_err is None
        if rqc_b_err is not None:
            _escalate("HOLD_INVALID_OR_MISSING_INPUT", rqc_b_err)
        else:
            rqc_comp1_batches = set(tmp_c1_rqc)
            rqc_comp2_batches = set(tmp_c2_rqc)
        raw_rqc_hip11_lot = rqc.get("hip11_peptide_reagent_lot_id")
        if (
            type(raw_rqc_hip11_lot) is not str
            or not raw_rqc_hip11_lot
            or raw_rqc_hip11_lot != raw_rqc_hip11_lot.strip()
            or not _SHIELD_STRICT_ID_RE.match(raw_rqc_hip11_lot)
        ):
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"register_qc_records missing valid unpadded hip11_peptide_reagent_lot_id "
                f"(got {raw_rqc_hip11_lot!r})",
            )
        else:
            rqc_hip11_lot = raw_rqc_hip11_lot
        hip11_flag_ok = rqc.get("hip11_dq25_dq8t_dq22_exchange_qc_passed") is True
        if not hip11_flag_ok:
            _escalate("HOLD_INVALID_OR_MISSING_INPUT", "HIP11 peptide-exchange QC across DQ2.5/DQ8-trans/DQ2.2 not passed")
        wt15_rec = rqc.get("native_wt_insb9_23_15aa")
        wt15_rec_metrics_ok = False
        if (
            not isinstance(wt15_rec, dict)
            or wt15_rec.get("sequence") != "SHLVEALYLVCGERG"
            or wt15_rec.get("lcms_identity_passed") is not True
            or wt15_rec.get("register2_occupancy_qc_passed") is not True
        ):
            _escalate("HOLD_INVALID_OR_MISSING_INPUT", "Native 15-aa WT InsB:9-23 (SHLVEALYLVCGERG) LC-MS & Register-2 QC missing or failed")
        else:
            raw_rqc_wt_lot = wt15_rec.get("peptide_reagent_lot_id")
            if (
                type(raw_rqc_wt_lot) is not str
                or not raw_rqc_wt_lot
                or raw_rqc_wt_lot != raw_rqc_wt_lot.strip()
                or not _SHIELD_STRICT_ID_RE.match(raw_rqc_wt_lot)
            ):
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"register_qc_records.native_wt_insb9_23_15aa missing valid unpadded peptide_reagent_lot_id "
                    f"(got {raw_rqc_wt_lot!r})",
                )
            else:
                rqc_wt_lot = raw_rqc_wt_lot
                wt15_rec_metrics_ok = True
        r6dfx_rec = rqc.get("engineered_6dfx_p8e9e_12aa")
        r6dfx_rec_metrics_ok = False
        if (
            not isinstance(r6dfx_rec, dict)
            or r6dfx_rec.get("sequence") != "VEELYLVAGEEG"
            or r6dfx_rec.get("qc_passed") is not True
        ):
            _escalate("HOLD_INVALID_OR_MISSING_INPUT", "12-aa PDB 6DFX p8E9E Register-3 comparator (VEELYLVAGEEG) QC record missing or failed")
        else:
            raw_rqc_6dfx_lot = r6dfx_rec.get("peptide_reagent_lot_id")
            if (
                type(raw_rqc_6dfx_lot) is not str
                or not raw_rqc_6dfx_lot
                or raw_rqc_6dfx_lot != raw_rqc_6dfx_lot.strip()
                or not _SHIELD_STRICT_ID_RE.match(raw_rqc_6dfx_lot)
            ):
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"register_qc_records.engineered_6dfx_p8e9e_12aa missing valid unpadded peptide_reagent_lot_id "
                    f"(got {raw_rqc_6dfx_lot!r})",
                )
            else:
                rqc_6dfx_lot = raw_rqc_6dfx_lot
                r6dfx_rec_metrics_ok = True
        r1jk8_present = False
        r1jk8_metrics_ok = False
        r1jk8_lot_syntax_ok = True
        r1jk8_batch_ok = False
        parsed_rqc_1jk8_lot: str | None = None
        tmp_ref_1jk8: set[str] = set()
        if "crystal_ref_1jk8_14aa" in rqc and rqc["crystal_ref_1jk8_14aa"] is not None:
            r1jk8_present = True
            derived_summary["optional_1jk8_physical_control_present"] = True
            r1jk8_rec = rqc["crystal_ref_1jk8_14aa"]
            if (
                not isinstance(r1jk8_rec, dict)
                or r1jk8_rec.get("sequence") != "LVEALYLVCGERGG"
                or r1jk8_rec.get("qc_passed") is not True
            ):
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    "Optional 14-aa PDB 1JK8 physical control was supplied but failed sequence (LVEALYLVCGERGG) or qc_passed validation",
                )
                if isinstance(r1jk8_rec, dict) and "peptide_reagent_lot_id" in r1jk8_rec:
                    raw_rqc_1jk8_lot = r1jk8_rec["peptide_reagent_lot_id"]
                    if (
                        type(raw_rqc_1jk8_lot) is str
                        and bool(raw_rqc_1jk8_lot)
                        and raw_rqc_1jk8_lot == raw_rqc_1jk8_lot.strip()
                        and bool(_SHIELD_STRICT_ID_RE.match(raw_rqc_1jk8_lot))
                    ):
                        parsed_rqc_1jk8_lot = raw_rqc_1jk8_lot
            else:
                r1jk8_metrics_ok = True
                if "peptide_reagent_lot_id" in r1jk8_rec:
                    raw_rqc_1jk8_lot = r1jk8_rec["peptide_reagent_lot_id"]
                    if (
                        type(raw_rqc_1jk8_lot) is not str
                        or not raw_rqc_1jk8_lot
                        or raw_rqc_1jk8_lot != raw_rqc_1jk8_lot.strip()
                        or not _SHIELD_STRICT_ID_RE.match(raw_rqc_1jk8_lot)
                    ):
                        r1jk8_lot_syntax_ok = False
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"Optional register_qc_records.crystal_ref_1jk8_14aa.peptide_reagent_lot_id was supplied "
                            f"but is invalid (must be a non-empty unpadded string matching {_SHIELD_STRICT_ID_RE.pattern}; "
                            f"got {raw_rqc_1jk8_lot!r})",
                        )
                    else:
                        parsed_rqc_1jk8_lot = raw_rqc_1jk8_lot
                tmp_c2_1jk8: set[str] = set()
                b1jk8_err = _shield_validate_batch_ids(
                    r1jk8_rec.get("expression_batch_ids"),
                    "register_qc_records.crystal_ref_1jk8_14aa",
                    passing_batch_constructs,
                    tmp_ref_1jk8,
                    required_construct_all=_SHIELD_COMP2_LEAD,
                    role_comp2_batches=tmp_c2_1jk8,
                )
                if b1jk8_err is not None:
                    _escalate("HOLD_INVALID_OR_MISSING_INPUT", b1jk8_err)
                else:
                    r1jk8_batch_ok = True
        else:
            derived_summary["optional_1jk8_physical_control_present"] = False

        # R17 0044-B2: Enforce pairwise-distinct peptide reagent lot IDs across ALL mandatory peptide reagents
        # (HIP11, WT15, 6DFX, plus optional 1JK8 if supplied) strictly BEFORE granting dependent records
        # biological or batch-linkage credit, while preserving independent qualified evidence!
        lot_owners: dict[str, list[str]] = {}
        for reagent_lbl, lot_val in (
            ("hip11", rqc_hip11_lot),
            ("wt15", rqc_wt_lot),
            ("6dfx", rqc_6dfx_lot),
            ("1jk8", parsed_rqc_1jk8_lot),
        ):
            if lot_val is not None:
                lot_owners.setdefault(lot_val, []).append(reagent_lbl)
        for dup_lot, owners in sorted(lot_owners.items()):
            if len(owners) > 1:
                collided_reagents.update(owners)
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"Duplicate peptide reagent lot ID {dup_lot!r} shared across distinct synthetic peptides "
                    f"{owners}; pairwise-distinct peptide_reagent_lot_id values are mandatory across HIP11, "
                    f"WT15, 6DFX (and optional 1JK8 when present) before biological or batch credit",
                )

        hip11_exchange_qc_valid = bool(
            rqc_batch_valid
            and hip11_flag_ok
            and rqc_hip11_lot is not None
            and "hip11" not in collided_reagents
            and len(rqc_comp1_batches) > 0
        )
        r6dfx_qc_valid = bool(
            rqc_batch_valid
            and r6dfx_rec_metrics_ok
            and rqc_6dfx_lot is not None
            and "6dfx" not in collided_reagents
            and len(rqc_comp2_batches) > 0
        )
        wt15_register_qc_valid = bool(
            rqc_batch_valid
            and wt15_rec_metrics_ok
            and rqc_wt_lot is not None
            and "wt15" not in collided_reagents
            and r6dfx_qc_valid
            and len(rqc_comp2_batches) > 0
        )
        if rqc_batch_valid and hip11_exchange_qc_valid and wt15_register_qc_valid:
            # R17 0044-B1: register_qc_records validates parent reagent/batch coverage ONLY and NEVER
            # credits comp1_assay_batches or comp2_assay_batches (which count ONLY validated SPR/comparator rows)!
            referenced_batches.update(tmp_ref_rqc)
        if (
            r1jk8_present
            and r1jk8_metrics_ok
            and r1jk8_lot_syntax_ok
            and r1jk8_batch_ok
            and "1jk8" not in collided_reagents
        ):
            r1jk8_qc_valid = True
            rqc_1jk8_lot = parsed_rqc_1jk8_lot
            referenced_batches.update(tmp_ref_1jk8)
    derived_summary["hip11_register_qc_reconciled_before_bio"] = True
    derived_summary["hip11_reagent_lot_and_batch_reconciled_before_bio"] = True
    derived_summary["wt15_register_qc_reconciled_before_bio"] = True
    derived_summary["wt15_offtarget_register_qc_reconciled_before_bio"] = True
    derived_summary["r6dfx_reagent_lot_reconciled_before_bio"] = True
    derived_summary["mandatory_peptide_reagent_lots_pairwise_distinct"] = bool(
        isinstance(rqc, dict)
        and rqc_hip11_lot is not None
        and rqc_wt_lot is not None
        and rqc_6dfx_lot is not None
        and len(collided_reagents) == 0
    )
    derived_summary["register_qc_excluded_from_spr_assay_batch_counts"] = True

    # 2b. Quantitative SEC-MALS / DLS monomer & 1:1 co-formulation stability (cocktail-bound BOTH leads; >= 95.0% monomer,
    #     PDI <= 0.15) evaluated STRICTLY BEFORE SPR and donor biological adjudication (R13 0039-B2 / 0037-M1 + R14 0039-B3 + R15 0037-B1/0039-B1)!
    #     Out-of-spec physical protein material (< 95.0% monomer, PDI > 0.15, or detected aggregates) is an UNQUALIFIED
    #     MATERIAL INPUT (HOLD_INVALID_OR_MISSING_INPUT, failure_domain=None), NOT a biological target FAIL, AND every
    #     SPR and cocktail donor assay MUST positively link ALL of its expression batches to passing construct/cocktail
    #     SEC-MALS/DLS material qualification before contributing to biological PASS/FAIL or batch-linkage credit!
    derived_summary["physicochemical_out_of_spec_disposition"] = "HOLD_INVALID_OR_MISSING_INPUT_UNQUALIFIED_MATERIAL"
    derived_summary["spr_material_qualification_reconciled_before_bio"] = True
    derived_summary["donor_material_qualification_reconciled_before_bio"] = True
    sec = observation.get("sec_mals_dls_monomer_coformulation")
    sec_comp1_qualified_batches: set[str] = set()
    sec_comp2_qualified_batches: set[str] = set()
    sec_cocktail_qualified = False
    sec_cocktail_qualified_batches: set[str] = set()
    sec_cocktail_qualified_comp1_batches: set[str] = set()
    sec_cocktail_qualified_comp2_batches: set[str] = set()
    qualified_passing_mixtures: dict[str, tuple[str, str]] = {}
    conflicted_mixture_ids: set[str] = set()
    if not isinstance(sec, dict):
        _escalate(
            "HOLD_INVALID_OR_MISSING_INPUT",
            "PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: Missing typed sec_mals_dls_monomer_coformulation record",
        )
        derived_summary["sec_mals_dls"] = {
            "comp1_monomer_pct": None,
            "comp2_monomer_pct": None,
            "cocktail_1to1_monomer_pct": None,
            "dls_pdi": None,
            "no_aggregates_or_precipitation": None,
            "physicochemical_qc_classification": "MISSING_OR_MALFORMED_OR_CONTRADICTORY_INPUT_HOLD",
            "qualified_cocktail_batch_ids": [],
            "qualified_coformulation_mixtures": {},
            "qualified_coformulation_mixtures_count": 0,
            "per_mixture_coformulation_binding_enforced": True,
            "coformulation_1to1_molar_ratio_verification_scope": (
                "LABORATORY_ATTESTED_NOT_INDEPENDENTLY_MEASURED_BY_SEC_MALS_OR_DLS"
            ),
            "all_qualified_mixtures_equimolar_1to1_attested": False,
        }
    else:
        sec_input_missing_or_malformed = False
        sec_valid_out_of_spec = False
        sec_top_qc_bad = False
        tmp_ref_sec: set[str] = set()
        tmp_c1_sec: set[str] = set()
        tmp_c2_sec: set[str] = set()
        sec_b_err = _shield_validate_batch_ids(
            sec.get("expression_batch_ids"),
            "sec_mals_dls_monomer_coformulation",
            passing_batch_constructs,
            tmp_ref_sec,
            require_cocktail_both_leads=True,
            role_comp1_batches=tmp_c1_sec,
            role_comp2_batches=tmp_c2_sec,
        )
        if sec_b_err is not None:
            sec_input_missing_or_malformed = True
            _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: {sec_b_err}")
        hflag, hflag_err = _shield_check_num(sec.get("protenix_homodimer_flag_iptm_addressed"), "protenix_homodimer_flag_iptm_addressed", lo=0.0, hi=1.0)
        hflag_ok = bool(hflag_err is None and hflag is not None and abs(hflag - 0.6691) <= 1e-4)
        if not hflag_ok:
            sec_input_missing_or_malformed = True
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: SEC-MALS record must explicitly address Comp2 "
                f"Protenix-v1 homodimer flag 0.6691 (got {sec.get('protenix_homodimer_flag_iptm_addressed')!r})",
            )

        def _extract_sec_pct(primary_k: str, alias_k: str) -> float | None:
            nonlocal sec_input_missing_or_malformed
            has_p = primary_k in sec and sec[primary_k] is not None
            has_a = alias_k in sec and sec[alias_k] is not None
            if has_p and has_a:
                pv, perr = _shield_check_num(sec[primary_k], f"sec_mals_dls.{primary_k}", lo=0.0, hi=100.0)
                av, aerr = _shield_check_num(sec[alias_k], f"sec_mals_dls.{alias_k}", lo=0.0, hi=100.0)
                if perr is not None:
                    sec_input_missing_or_malformed = True
                    _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: {perr}")
                    return None
                if aerr is not None:
                    sec_input_missing_or_malformed = True
                    _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: {aerr}")
                    return None
                if pv is not None and av is not None and abs(pv - av) > 1e-9:
                    sec_input_missing_or_malformed = True
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: sec_mals_dls.{primary_k}={pv} disagrees with alias {alias_k}={av}",
                    )
                    return None
                return pv
            if has_p:
                pv, perr = _shield_check_num(sec[primary_k], f"sec_mals_dls.{primary_k}", lo=0.0, hi=100.0)
                if perr is not None:
                    sec_input_missing_or_malformed = True
                    _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: {perr}")
                    return None
                return pv
            if has_a:
                av, aerr = _shield_check_num(sec[alias_k], f"sec_mals_dls.{alias_k}", lo=0.0, hi=100.0)
                if aerr is not None:
                    sec_input_missing_or_malformed = True
                    _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: {aerr}")
                    return None
                return av
            sec_input_missing_or_malformed = True
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: sec_mals_dls missing required {primary_k} (or alias {alias_k})",
            )
            return None

        c1_mon = _extract_sec_pct("comp1_monomer_pct", "comp1_qf09_pi2_monomer_fraction_pct")
        c2_mon = _extract_sec_pct("comp2_monomer_pct", "comp2_t006_monomer_fraction_pct")
        ck_mon = _extract_sec_pct("cocktail_1to1_monomer_pct", "cocktail_1to1_monomer_fraction_pct")
        dls_pdi, pdi_err = _shield_check_num(sec.get("dls_pdi"), "sec_mals_dls.dls_pdi", lo=0.0, hi=1.0)
        if pdi_err is not None:
            sec_input_missing_or_malformed = True
            _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: {pdi_err}")
        no_agg = sec.get("no_aggregates_or_precipitation")
        if type(no_agg) is not bool:
            sec_input_missing_or_malformed = True
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: sec_mals_dls.no_aggregates_or_precipitation must be a strict boolean (got {no_agg!r})",
            )

        c1_qc = sec.get("comp1_qf09_pi2_alone_monomer_qc_passed")
        c2_qc = sec.get("comp2_t006_alone_monomer_qc_passed")
        ck_qc = sec.get("cocktail_1to1_coformulation_qc_passed")
        for qc_lbl, qc_val in (
            ("comp1_qf09_pi2_alone_monomer_qc_passed", c1_qc),
            ("comp2_t006_alone_monomer_qc_passed", c2_qc),
            ("cocktail_1to1_coformulation_qc_passed", ck_qc),
        ):
            if type(qc_val) is not bool:
                sec_input_missing_or_malformed = True
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: sec_mals_dls.{qc_lbl} must be a strict boolean (got {qc_val!r})",
                )

        quant_sec_failed = False
        c1_oos = bool(c1_mon is not None and c1_mon < _SHIELD_MIN_MONOMER_PCT)
        c2_oos = bool(c2_mon is not None and c2_mon < _SHIELD_MIN_MONOMER_PCT)
        ck_oos = bool(ck_mon is not None and ck_mon < _SHIELD_MIN_MONOMER_PCT)
        pdi_oos = bool(dls_pdi is not None and dls_pdi > _SHIELD_MAX_DLS_PDI)
        agg_oos = bool(no_agg is False)

        for mon_v, mon_oos, mon_qc, mon_lbl in (
            (c1_mon, c1_oos, c1_qc, "comp1_monomer_pct"),
            (c2_mon, c2_oos, c2_qc, "comp2_monomer_pct"),
            (ck_mon, ck_oos, ck_qc, "cocktail_1to1_monomer_pct"),
        ):
            if mon_oos and mon_v is not None:
                quant_sec_failed = True
                if mon_qc is False:
                    sec_valid_out_of_spec = True
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"PHYSICOCHEMICAL_OUT_OF_SPEC_MATERIAL_UNQUALIFIED_HOLD: valid measured {mon_lbl}={mon_v:.2f}% "
                        f"< {_SHIELD_MIN_MONOMER_PCT:.1f}% with consistent qc_flag=False (unqualified material input, "
                        f"not biological target FAIL)",
                    )
                else:
                    sec_input_missing_or_malformed = True
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: SEC-MALS quantitative threshold/QC "
                        f"contradiction: {mon_lbl}={mon_v:.2f}% < {_SHIELD_MIN_MONOMER_PCT:.1f}% contradicts qc_flag={mon_qc!r}",
                    )
        if pdi_oos and dls_pdi is not None:
            quant_sec_failed = True
            if ck_qc is False:
                sec_valid_out_of_spec = True
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"PHYSICOCHEMICAL_OUT_OF_SPEC_MATERIAL_UNQUALIFIED_HOLD: valid measured dls_pdi={dls_pdi:.4f} "
                    f"> {_SHIELD_MAX_DLS_PDI:.2f} with consistent cocktail qc_flag=False (unqualified material input, "
                    f"not biological target FAIL)",
                )
            else:
                sec_input_missing_or_malformed = True
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: SEC-MALS/DLS polydispersity threshold/QC "
                    f"contradiction: dls_pdi={dls_pdi:.4f} > {_SHIELD_MAX_DLS_PDI:.2f} contradicts qc_flag={ck_qc!r}",
                )
        if agg_oos:
            quant_sec_failed = True
            if c1_qc is True or c2_qc is True or ck_qc is True:
                sec_input_missing_or_malformed = True
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    "PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: SEC-MALS/DLS boolean QC flag contradiction: "
                    "qc_passed=True despite no_aggregates_or_precipitation=False",
                )
            else:
                sec_valid_out_of_spec = True
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    "PHYSICOCHEMICAL_OUT_OF_SPEC_MATERIAL_UNQUALIFIED_HOLD: valid measured aggregates or precipitation "
                    "detected (no_aggregates_or_precipitation=False; unqualified material input, not biological target FAIL)",
                )

        if c1_qc is False and not (c1_oos or agg_oos):
            sec_input_missing_or_malformed = True
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                "PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: SEC-MALS/DLS monomer QC flag for "
                "IsletSHIELD_QF09_pI2 alone is False without an out-of-spec measurement",
            )
        if c2_qc is False and not (c2_oos or agg_oos):
            sec_input_missing_or_malformed = True
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                "PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: SEC-MALS/DLS monomer QC flag for "
                "IsletSHIELD_Comp2_T006 alone is False without an out-of-spec measurement",
            )
        if ck_qc is False and not (ck_oos or pdi_oos or agg_oos):
            sec_input_missing_or_malformed = True
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                "PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: SEC-MALS/DLS 1:1 co-formulation QC flag "
                "(T006 + QF09_pI2) is False without an out-of-spec measurement",
            )

        for gen_k in ("qc_pass", "qc_passed"):
            if gen_k in sec:
                if sec[gen_k] is True and quant_sec_failed:
                    sec_input_missing_or_malformed = True
                    sec_top_qc_bad = True
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: sec_mals_dls.{gen_k}=True contradicts quantitative SEC-MALS/DLS threshold failure",
                    )
                elif sec[gen_k] is False and not quant_sec_failed:
                    sec_input_missing_or_malformed = True
                    sec_top_qc_bad = True
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: sec_mals_dls.{gen_k}=False without quantitative out-of-spec measurement",
                    )
                elif type(sec[gen_k]) is not bool:
                    sec_input_missing_or_malformed = True
                    sec_top_qc_bad = True
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: sec_mals_dls.{gen_k} must be a strict boolean",
                    )
                elif sec[gen_k] is False:
                    sec_top_qc_bad = True

        # R16 Shared Blocker #1 + 0039-M2: Mandatory per-mixture physical co-formulation SEC-MALS/DLS binding!
        # Every measured physical 1:1 co-formulation mixture MUST be explicitly registered with a unique
        # mixture_id, exact (comp1_expression_batch_id, comp2_expression_batch_id) lot pair, and its own
        # per-mixture monomer_pct (>= 95.0%), dls_pdi (<= 0.15), no_aggregates_or_precipitation=True, and qc_passed,
        # plus optional strictly validated laboratory 1:1 molar-ratio attestation fields (equimolar_1to1_molar_ratio_attested,
        # ratio_basis_attestation) documenting that 1:1 stoichiometry is laboratory-attested alongside SEC-MALS/DLS QC.
        _required_mix_keys = frozenset({
            "mixture_id",
            "comp1_expression_batch_id",
            "comp2_expression_batch_id",
            "monomer_pct",
            "dls_pdi",
            "no_aggregates_or_precipitation",
            "qc_passed",
        })
        _optional_mix_keys = frozenset({
            "equimolar_1to1_molar_ratio_attested",
            "ratio_basis_attestation",
        })
        _allowed_mix_keys = _required_mix_keys | _optional_mix_keys
        _allowed_mix_ratio_basis_tokens = frozenset({
            "LAB_ATTESTED_1TO1_MOLAR_COFORMULATION_MIXING_PROTOCOL",
            "UV_A280_EXTINCTION_VERIFIED_1TO1_MOLAR_COFORMULATION",
        })
        raw_mixtures = sec.get("qualified_coformulation_mixtures")
        candidate_passing_mixtures: dict[str, tuple[str, str]] = {}
        candidate_mixture_ratio_meta: dict[str, dict[str, Any]] = {}
        valid_mix_monomers: list[float] = []
        valid_mix_pdis: list[float] = []
        top_sec_overstated = False
        if not isinstance(raw_mixtures, list) or len(raw_mixtures) == 0:
            sec_input_missing_or_malformed = True
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                "PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: sec_mals_dls_monomer_coformulation missing "
                "mandatory non-empty qualified_coformulation_mixtures list binding each physical 1:1 mixture_id "
                "to its exact (comp1_expression_batch_id, comp2_expression_batch_id) pair and per-mixture monomer/PDI QC",
            )
        else:
            mix_id_counts: dict[str, int] = {}
            for m_rec in raw_mixtures:
                if isinstance(m_rec, dict):
                    raw_mid = m_rec.get("mixture_id")
                    if type(raw_mid) is str and raw_mid.strip():
                        mix_id_counts[raw_mid.strip()] = mix_id_counts.get(raw_mid.strip(), 0) + 1
            conflicted_mixture_ids = {k for k, cnt in mix_id_counts.items() if cnt > 1}
            for cmid in sorted(conflicted_mixture_ids):
                sec_input_missing_or_malformed = True
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: Duplicate/conflicting sec_mals_dls "
                    f"qualified_coformulation_mixtures mixture_id={cmid!r} (count={mix_id_counts[cmid]}); "
                    f"all occurrences excluded from physical co-formulation qualification",
                )
            for m_idx, m_rec in enumerate(raw_mixtures):
                mlbl = f"sec_mals_dls.qualified_coformulation_mixtures[{m_idx}]"
                if not isinstance(m_rec, dict):
                    sec_input_missing_or_malformed = True
                    _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: {mlbl} must be an object")
                    continue
                extra_mk = sorted(set(m_rec.keys()) - _allowed_mix_keys)
                missing_mk = sorted(_required_mix_keys - set(m_rec.keys()))
                mix_ok = True
                if extra_mk or missing_mk:
                    mix_ok = False
                    sec_input_missing_or_malformed = True
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: {mlbl} closed-schema key violation "
                        f"(missing={missing_mk}, extra={extra_mk})",
                    )
                raw_mid = m_rec.get("mixture_id")
                mid_s: str | None = None
                if (
                    type(raw_mid) is not str
                    or not raw_mid
                    or raw_mid != raw_mid.strip()
                    or not _SHIELD_STRICT_ID_RE.match(raw_mid)
                ):
                    mix_ok = False
                    sec_input_missing_or_malformed = True
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: {mlbl}.mixture_id must be a non-empty "
                        f"unpadded ID matching {_SHIELD_STRICT_ID_RE.pattern} (got {raw_mid!r})",
                    )
                elif raw_mid in conflicted_mixture_ids:
                    mix_ok = False
                else:
                    mid_s = raw_mid

                c1_bid = m_rec.get("comp1_expression_batch_id")
                if (
                    type(c1_bid) is not str
                    or not c1_bid
                    or c1_bid != c1_bid.strip()
                    or c1_bid not in passing_batch_constructs
                    or _SHIELD_COMP1_LEAD not in passing_batch_constructs[c1_bid]
                    or (sec_b_err is None and c1_bid not in tmp_c1_sec)
                ):
                    mix_ok = False
                    sec_input_missing_or_malformed = True
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: {mlbl}.comp1_expression_batch_id={c1_bid!r} "
                        f"must reference a declared passing {_SHIELD_COMP1_LEAD} batch covered by sec_mals_dls.expression_batch_ids",
                    )

                c2_bid = m_rec.get("comp2_expression_batch_id")
                if (
                    type(c2_bid) is not str
                    or not c2_bid
                    or c2_bid != c2_bid.strip()
                    or c2_bid not in passing_batch_constructs
                    or _SHIELD_COMP2_LEAD not in passing_batch_constructs[c2_bid]
                    or (sec_b_err is None and c2_bid not in tmp_c2_sec)
                ):
                    mix_ok = False
                    sec_input_missing_or_malformed = True
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: {mlbl}.comp2_expression_batch_id={c2_bid!r} "
                        f"must reference a declared passing {_SHIELD_COMP2_LEAD} batch covered by sec_mals_dls.expression_batch_ids",
                    )

                m_mon, m_mon_err = _shield_check_num(m_rec.get("monomer_pct"), f"{mlbl}.monomer_pct", lo=0.0, hi=100.0)
                if m_mon_err is not None:
                    mix_ok = False
                    sec_input_missing_or_malformed = True
                    _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: {m_mon_err}")
                elif m_mon is not None:
                    valid_mix_monomers.append(m_mon)

                m_pdi, m_pdi_err = _shield_check_num(m_rec.get("dls_pdi"), f"{mlbl}.dls_pdi", lo=0.0, hi=1.0)
                if m_pdi_err is not None:
                    mix_ok = False
                    sec_input_missing_or_malformed = True
                    _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: {m_pdi_err}")
                elif m_pdi is not None:
                    valid_mix_pdis.append(m_pdi)

                m_no_agg = m_rec.get("no_aggregates_or_precipitation")
                if type(m_no_agg) is not bool:
                    mix_ok = False
                    sec_input_missing_or_malformed = True
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: {mlbl}.no_aggregates_or_precipitation must be strict bool",
                    )
                m_qc = m_rec.get("qc_passed")
                if type(m_qc) is not bool:
                    mix_ok = False
                    sec_input_missing_or_malformed = True
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: {mlbl}.qc_passed must be strict bool",
                    )

                m_mon_oos = bool(m_mon is not None and m_mon < _SHIELD_MIN_MONOMER_PCT)
                m_pdi_oos = bool(m_pdi is not None and m_pdi > _SHIELD_MAX_DLS_PDI)
                m_agg_oos = bool(m_no_agg is False)
                if m_mon_oos or m_pdi_oos or m_agg_oos:
                    mix_ok = False
                    quant_sec_failed = True
                    if m_qc is False:
                        sec_valid_out_of_spec = True
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"PHYSICOCHEMICAL_OUT_OF_SPEC_MATERIAL_UNQUALIFIED_HOLD: {mlbl} (mixture_id={mid_s!r}) "
                            f"failed per-mixture co-formulation QC (monomer_pct={m_mon}, dls_pdi={m_pdi}, "
                            f"no_aggregates={m_no_agg}) with consistent qc_passed=False",
                        )
                    else:
                        sec_input_missing_or_malformed = True
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: {mlbl} (mixture_id={mid_s!r}) "
                            f"per-mixture SEC-MALS/DLS threshold failure contradicts qc_passed={m_qc!r}",
                        )
                elif m_qc is False:
                    mix_ok = False
                    sec_input_missing_or_malformed = True
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: {mlbl}.qc_passed=False without out-of-spec measurement",
                    )

                m_eq_attested: bool | None = None
                if "equimolar_1to1_molar_ratio_attested" in m_rec:
                    raw_eq = m_rec.get("equimolar_1to1_molar_ratio_attested")
                    if raw_eq is not True:
                        mix_ok = False
                        sec_input_missing_or_malformed = True
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: {mlbl}.equimolar_1to1_molar_ratio_attested "
                            f"must be literal boolean True when supplied (got {raw_eq!r})",
                        )
                    else:
                        m_eq_attested = True

                m_ratio_basis: str | None = None
                if "ratio_basis_attestation" in m_rec:
                    raw_rb = m_rec.get("ratio_basis_attestation")
                    if type(raw_rb) is not str or raw_rb not in _allowed_mix_ratio_basis_tokens:
                        mix_ok = False
                        sec_input_missing_or_malformed = True
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: {mlbl}.ratio_basis_attestation "
                            f"must be in {sorted(_allowed_mix_ratio_basis_tokens)} when supplied (got {raw_rb!r})",
                        )
                    else:
                        m_ratio_basis = raw_rb

                if mix_ok and mid_s is not None and type(c1_bid) is str and type(c2_bid) is str:
                    candidate_passing_mixtures[mid_s] = (c1_bid, c2_bid)
                    candidate_mixture_ratio_meta[mid_s] = {
                        "equimolar_1to1_molar_ratio_attested": m_eq_attested,
                        "ratio_basis_attestation": m_ratio_basis,
                    }

            if valid_mix_monomers and ck_mon is not None and ck_mon > min(valid_mix_monomers) + 1e-9:
                top_sec_overstated = True
                sec_input_missing_or_malformed = True
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: top-level cocktail_1to1_monomer_pct={ck_mon:.2f}% "
                    f"overstates worst per-mixture monomer_pct={min(valid_mix_monomers):.2f}%",
                )
            if valid_mix_pdis and dls_pdi is not None and dls_pdi < max(valid_mix_pdis) - 1e-9:
                top_sec_overstated = True
                sec_input_missing_or_malformed = True
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD: top-level dls_pdi={dls_pdi:.4f} "
                    f"understates worst per-mixture dls_pdi={max(valid_mix_pdis):.4f}",
                )

        if sec_valid_out_of_spec and sec_input_missing_or_malformed:
            sec_qc_cls = "BOTH_OUT_OF_SPEC_AND_MALFORMED_INPUT_HOLD"
        elif sec_valid_out_of_spec:
            sec_qc_cls = "OUT_OF_SPEC_MATERIAL_UNQUALIFIED_HOLD"
        elif sec_input_missing_or_malformed:
            sec_qc_cls = "MISSING_OR_MALFORMED_OR_CONTRADICTORY_INPUT_HOLD"
        else:
            sec_qc_cls = "PASS_QUALIFIED_MATERIAL"

        if sec_b_err is None and hflag_ok and no_agg is True and not sec_top_qc_bad:
            if c1_mon is not None and not c1_oos and c1_qc is True:
                sec_comp1_qualified_batches = set(tmp_c1_sec)
            if c2_mon is not None and not c2_oos and c2_qc is True:
                sec_comp2_qualified_batches = set(tmp_c2_sec)
        if (
            sec_b_err is None
            and hflag_ok
            and no_agg is True
            and not sec_top_qc_bad
            and not top_sec_overstated
            and ck_mon is not None
            and not ck_oos
            and ck_qc is True
            and dls_pdi is not None
            and not pdi_oos
        ):
            for mid_k, (mc1, mc2) in candidate_passing_mixtures.items():
                if mc1 in sec_comp1_qualified_batches and mc2 in sec_comp2_qualified_batches:
                    qualified_passing_mixtures[mid_k] = (mc1, mc2)

        sec_cocktail_qualified = bool(len(qualified_passing_mixtures) > 0)
        if sec_cocktail_qualified:
            sec_cocktail_qualified_comp1_batches = {mc1 for mc1, _ in qualified_passing_mixtures.values()}
            sec_cocktail_qualified_comp2_batches = {mc2 for _, mc2 in qualified_passing_mixtures.values()}
            sec_cocktail_qualified_batches = sec_cocktail_qualified_comp1_batches | sec_cocktail_qualified_comp2_batches
            if sec_qc_cls == "PASS_QUALIFIED_MATERIAL":
                referenced_batches.update(sec_cocktail_qualified_batches)
                cocktail_comp1_batches.update(sec_cocktail_qualified_comp1_batches)
                cocktail_comp2_batches.update(sec_cocktail_qualified_comp2_batches)

        derived_summary["sec_mals_dls"] = {
            "comp1_monomer_pct": c1_mon,
            "comp2_monomer_pct": c2_mon,
            "cocktail_1to1_monomer_pct": ck_mon,
            "dls_pdi": dls_pdi,
            "no_aggregates_or_precipitation": no_agg if type(no_agg) is bool else None,
            "physicochemical_qc_classification": sec_qc_cls,
            "qualified_cocktail_batch_ids": sorted(sec_cocktail_qualified_batches),
            "qualified_coformulation_mixtures": {
                mid_k: {
                    "comp1_expression_batch_id": mc1,
                    "comp2_expression_batch_id": mc2,
                    "equimolar_1to1_molar_ratio_attested": candidate_mixture_ratio_meta.get(mid_k, {}).get(
                        "equimolar_1to1_molar_ratio_attested"
                    ),
                    "ratio_basis_attestation": candidate_mixture_ratio_meta.get(mid_k, {}).get(
                        "ratio_basis_attestation"
                    ),
                }
                for mid_k, (mc1, mc2) in sorted(qualified_passing_mixtures.items())
            },
            "qualified_coformulation_mixtures_count": len(qualified_passing_mixtures),
            "per_mixture_coformulation_binding_enforced": True,
            "coformulation_1to1_molar_ratio_verification_scope": (
                "LABORATORY_ATTESTED_NOT_INDEPENDENTLY_MEASURED_BY_SEC_MALS_OR_DLS"
            ),
            "all_qualified_mixtures_equimolar_1to1_attested": bool(
                len(qualified_passing_mixtures) > 0
                and all(
                    candidate_mixture_ratio_meta.get(mid_k, {}).get("equimolar_1to1_molar_ratio_attested") is True
                    for mid_k in qualified_passing_mixtures
                )
            ),
        }

    # 3. On-target SPR analytes (R08 B3 + R12 0039-B1 + R14 0039-B2/B3: two-pass order-independent canonical key
    #    uniqueness AND mandatory register-QC/reagent-lot + SEC-MALS material qualification reconciliation strictly
    #    BEFORE biological adjudication & batch credit; all 4 mandatory complexes; replicates_n >= 3)
    analytes_raw = observation.get("on_target_analytes")
    seen_analytes: set[str] = set()
    conflicted_on_target: set[str] = set()
    analyte_derived: dict[str, dict[str, float]] = {}
    wt15_analyte_reagent_lot_id: str | None = None
    if not isinstance(analytes_raw, list) or len(analytes_raw) == 0:
        _escalate("HOLD_INVALID_OR_MISSING_INPUT", "Missing typed on_target_analytes list (all 4 mandatory complexes required)")
    else:
        on_target_counts: dict[str, int] = {}
        for rec in analytes_raw:
            if isinstance(rec, dict):
                raw_aid = rec.get("analyte_id")
                if type(raw_aid) is str and raw_aid.strip():
                    aid_p = _SHIELD_ANALYTE_ALIASES.get(raw_aid.strip(), raw_aid.strip())
                    on_target_counts[aid_p] = on_target_counts.get(aid_p, 0) + 1
        conflicted_on_target = {k for k, cnt in on_target_counts.items() if cnt > 1}
        for caid in sorted(conflicted_on_target):
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"Duplicate/conflicting on_target_analyte canonical key: {caid!r} (count={on_target_counts[caid]}); "
                f"all occurrences excluded from biological adjudication and batch-linkage credit",
            )

        for idx, rec in enumerate(analytes_raw):
            if not isinstance(rec, dict):
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"on_target_analytes[{idx}] must be an object")
                continue
            raw_aid = rec.get("analyte_id")
            if type(raw_aid) is not str or not raw_aid.strip():
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"on_target_analytes[{idx}] missing analyte_id")
                continue
            aid = _SHIELD_ANALYTE_ALIASES.get(raw_aid.strip(), raw_aid.strip())
            seen_analytes.add(aid)
            if aid in conflicted_on_target:
                continue
            row_valid = True
            tmp_ref: set[str] = set()
            tmp_c1: set[str] = set()
            tmp_c2: set[str] = set()
            if aid in _SHIELD_COMP1_ON_TARGET_ANALYTES:
                b_err = _shield_validate_batch_ids(
                    rec.get("expression_batch_ids"),
                    f"on_target[{aid}]",
                    passing_batch_constructs,
                    tmp_ref,
                    required_construct_all=_SHIELD_COMP1_LEAD,
                    role_comp1_batches=tmp_c1,
                )
                raw_hip_lot = rec.get("peptide_reagent_lot_id")
                row_hip_lot: str | None = None
                if (
                    type(raw_hip_lot) is not str
                    or not raw_hip_lot
                    or raw_hip_lot != raw_hip_lot.strip()
                    or not _SHIELD_STRICT_ID_RE.match(raw_hip_lot)
                ):
                    row_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"{aid}: missing valid unpadded peptide_reagent_lot_id matching "
                        f"{_SHIELD_STRICT_ID_RE.pattern} (got {raw_hip_lot!r}); excluded from biological "
                        f"adjudication and batch-linkage credit",
                    )
                else:
                    row_hip_lot = raw_hip_lot
                if not hip11_exchange_qc_valid or rqc_hip11_lot is None:
                    row_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"{aid}: excluded from biological adjudication and batch-linkage credit because "
                        f"mandatory register_qc_records.hip11_dq25_dq8t_dq22_exchange_qc_passed, "
                        f"hip11_peptide_reagent_lot_id, or parent register_qc_records Comp1 batch linkage is missing or failed",
                    )
                elif row_hip_lot is not None and row_hip_lot != rqc_hip11_lot:
                    row_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"{aid}: HIP11 peptide_reagent_lot_id mismatch: on_target_analytes="
                        f"{row_hip_lot!r} != register_qc_records.hip11_peptide_reagent_lot_id={rqc_hip11_lot!r}; "
                        f"excluded from biological adjudication and batch-linkage credit",
                    )
                if b_err is None and (not tmp_c1 or not tmp_c1.issubset(rqc_comp1_batches)):
                    row_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"{aid}: Comp1 expression_batch_ids={sorted(tmp_c1)} are not covered by parent "
                        f"register_qc_records Comp1 batches={sorted(rqc_comp1_batches)}; excluded from "
                        f"biological adjudication and batch-linkage credit",
                    )
                if b_err is None and (not tmp_c1 or not tmp_c1.issubset(sec_comp1_qualified_batches)):
                    row_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"{aid}: excluded from biological adjudication and batch-linkage credit because "
                        f"Comp1 expression_batch_ids={sorted(tmp_c1)} lack passing Comp1 SEC-MALS/DLS "
                        f"physicochemical material qualification (qualified_comp1_batches={sorted(sec_comp1_qualified_batches)})",
                    )
            elif aid in _SHIELD_COMP2_ON_TARGET_ANALYTES:
                b_err = _shield_validate_batch_ids(
                    rec.get("expression_batch_ids"),
                    f"on_target[{aid}]",
                    passing_batch_constructs,
                    tmp_ref,
                    required_construct_all=_SHIELD_COMP2_LEAD,
                    role_comp2_batches=tmp_c2,
                )
                if b_err is None and (not tmp_c2 or not tmp_c2.issubset(sec_comp2_qualified_batches)):
                    row_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"{aid}: excluded from biological adjudication and batch-linkage credit because "
                        f"Comp2 expression_batch_ids={sorted(tmp_c2)} lack passing Comp2 SEC-MALS/DLS "
                        f"physicochemical material qualification (qualified_comp2_batches={sorted(sec_comp2_qualified_batches)})",
                    )
            else:
                row_valid = False
                b_err = None
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"Unregistered on_target_analyte record rejected (excluded from biological FAIL adjudication): {aid!r}",
                )
            if b_err is not None:
                row_valid = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", b_err)
            if aid == "HLA-DQ8 + native WT InsB:9-23":
                pseq = rec.get("peptide_sequence")
                if pseq != "SHLVEALYLVCGERG":
                    row_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"Native WT InsB:9-23 analyte missing or wrong peptide_sequence={pseq!r} (expected 15-aa SHLVEALYLVCGERG)",
                    )
                raw_wt_lot = rec.get("peptide_reagent_lot_id")
                if (
                    type(raw_wt_lot) is not str
                    or not raw_wt_lot
                    or raw_wt_lot != raw_wt_lot.strip()
                    or not _SHIELD_STRICT_ID_RE.match(raw_wt_lot)
                ):
                    row_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"Native WT InsB:9-23 analyte missing valid unpadded peptide_reagent_lot_id matching "
                        f"{_SHIELD_STRICT_ID_RE.pattern} (got {raw_wt_lot!r})",
                    )
                else:
                    wt15_analyte_reagent_lot_id = raw_wt_lot
                # R12 0039-B1 + R14 0039-B2: Reconcile mandatory WT15 register-QC, parent batches & reagent lot
                # strictly BEFORE biological adjudication and BEFORE granting batch-linkage credit!
                if not wt15_register_qc_valid or rqc_wt_lot is None:
                    row_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        "Native WT InsB:9-23 on-target row excluded from biological adjudication and "
                        "batch-linkage credit because mandatory register_qc_records WT15/6DFX QC or "
                        "reagent lot is missing or failed",
                    )
                elif wt15_analyte_reagent_lot_id is not None and rqc_wt_lot != wt15_analyte_reagent_lot_id:
                    row_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"Native WT InsB:9-23 peptide_reagent_lot_id mismatch: on_target_analytes="
                        f"{wt15_analyte_reagent_lot_id!r} != register_qc_records={rqc_wt_lot!r}; "
                        f"WT15 row excluded from biological adjudication and batch-linkage credit",
                    )
                if b_err is None and (not tmp_c2 or not tmp_c2.issubset(rqc_comp2_batches)):
                    row_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"Native WT InsB:9-23 Comp2 expression_batch_ids={sorted(tmp_c2)} are not covered by "
                        f"parent register_qc_records Comp2 batches={sorted(rqc_comp2_batches)}; excluded from "
                        f"biological adjudication and batch-linkage credit",
                    )
            _, rep_err = _shield_check_strict_int(
                rec.get("replicates_n"), f"{aid}.replicates_n", min_val=_SHIELD_MIN_SPR_REPLICATES_N
            )
            if rep_err is not None:
                row_valid = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", rep_err)

            ic50_l, ic50_l_err = _shield_check_num(rec.get("ic50_l95_nm"), f"{aid}.ic50_l95_nm", lo=0.0, strictly_gt_lo=True)
            ic50_u, ic50_u_err = _shield_check_num(rec.get("ic50_u95_nm"), f"{aid}.ic50_u95_nm", lo=0.0, strictly_gt_lo=True)
            if ic50_l_err is not None:
                row_valid = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", ic50_l_err)
            if ic50_u_err is not None:
                row_valid = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", ic50_u_err)
            if ic50_l is not None and ic50_u is not None and ic50_l > ic50_u:
                row_valid = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"{aid}: inverted IC50 CI L95={ic50_l} > U95={ic50_u}")

            sel_l, sel_l_err = _shield_check_num(rec.get("selectivity_l95_fold"), f"{aid}.selectivity_l95_fold", lo=0.0)
            sel_u, sel_u_err = _shield_check_num(rec.get("selectivity_u95_fold"), f"{aid}.selectivity_u95_fold", lo=0.0)
            if sel_l_err is not None:
                row_valid = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", sel_l_err)
            if sel_u_err is not None:
                row_valid = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", sel_u_err)
            if sel_l is not None and sel_u is not None and sel_l > sel_u:
                row_valid = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"{aid}: inverted selectivity CI L95={sel_l} > U95={sel_u}")

            # R07 B1 + R08 B3 + R12 0039-B1 + R13 0037-B2/B3: Credit batch linkage and adjudicate biological FAIL/HOLD strictly on valid, register-QC-reconciled, non-conflicted rows!
            if row_valid and ic50_l is not None and ic50_u is not None and sel_l is not None and sel_u is not None:
                referenced_batches.update(tmp_ref)
                comp1_assay_batches.update(tmp_c1)
                comp2_assay_batches.update(tmp_c2)
                row_bio_fail = False
                row_bio_hold = False
                if ic50_l > 500.0:
                    spr_bio_fail = True
                    row_bio_fail = True
                    _escalate("FAIL", f"{aid}: SPR L95(IC50)={ic50_l:.2f} nM > 500.0 nM FAIL bar")
                elif ic50_u > 100.0:
                    row_bio_hold = True
                    _escalate("HOLD", f"{aid}: SPR U95(IC50)={ic50_u:.2f} nM > 100.0 nM PASS bar (post-SPR v1.4 maturation HOLD)")

                if sel_u < 10.0:
                    spr_bio_fail = True
                    row_bio_fail = True
                    _escalate("FAIL", f"{aid}: SPR U95(selectivity)={sel_u:.2f}x < 10.0x FAIL bar")
                elif sel_l < 50.0:
                    row_bio_hold = True
                    _escalate("HOLD", f"{aid}: SPR L95(selectivity)={sel_l:.2f}x < 50.0x PASS bar (post-SPR v1.4 maturation HOLD)")

                if aid in _SHIELD_COMP1_ON_TARGET_ANALYTES:
                    if row_bio_fail:
                        comp1_spr_bio_fail = True
                    elif not row_bio_hold:
                        comp1_on_target_passed_analytes.add(aid)
                elif aid in _SHIELD_COMP2_ON_TARGET_ANALYTES and row_bio_fail:
                    comp2_spr_bio_fail = True

                analyte_derived[aid] = {
                    "ic50_l95_nm": ic50_l,
                    "ic50_u95_nm": ic50_u,
                    "selectivity_l95_fold": sel_l,
                    "selectivity_u95_fold": sel_u,
                }

        missing_analytes = [a for a in _SHIELD_MANDATORY_ON_TARGET_ANALYTES if a not in seen_analytes]
        if missing_analytes:
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"Missing mandatory on-target SPR analytes: {missing_analytes}",
            )

    # 4. Off-target SPR controls (R08 B3 + R12 0039-B1: two-pass order-independent canonical key uniqueness BEFORE
    #    bio adjudication; ALL 4 mandatory Comp1 + ALL 3 mandatory Comp2 controls = 7 total; construct-bound)
    off_raw = observation.get("off_target_controls")
    seen_off: set[str] = set()
    conflicted_off_target: set[str] = set()
    if not isinstance(off_raw, list) or len(off_raw) == 0:
        _escalate(
            "HOLD_INVALID_OR_MISSING_INPUT",
            "Missing typed off_target_controls list (all 4 Comp1 + 3 Comp2 mandatory controls required)",
        )
    else:
        off_target_counts: dict[str, int] = {}
        for rec in off_raw:
            if isinstance(rec, dict):
                oid = rec.get("analyte_id")
                if type(oid) is str and oid.strip():
                    oid_p = _SHIELD_OFF_TARGET_ALIASES.get(oid.strip(), oid.strip())
                    off_target_counts[oid_p] = off_target_counts.get(oid_p, 0) + 1
        conflicted_off_target = {k for k, cnt in off_target_counts.items() if cnt > 1}
        for coid in sorted(conflicted_off_target):
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"Duplicate/conflicting off_target_control canonical key: {coid!r} (count={off_target_counts[coid]}); "
                f"all occurrences excluded from biological adjudication and batch-linkage credit",
            )

        for idx, rec in enumerate(off_raw):
            if not isinstance(rec, dict):
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"off_target_controls[{idx}] must be an object")
                continue
            oid = rec.get("analyte_id")
            if type(oid) is not str or not oid.strip():
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"off_target_controls[{idx}] missing analyte_id")
                continue
            oid_c = _SHIELD_OFF_TARGET_ALIASES.get(oid.strip(), oid.strip())
            seen_off.add(oid_c)
            if oid_c in conflicted_off_target:
                continue
            off_row_valid = True
            tmp_ref_o: set[str] = set()
            tmp_c1_o: set[str] = set()
            tmp_c2_o: set[str] = set()
            if oid_c in _SHIELD_MANDATORY_COMP1_OFF_TARGET_CONTROLS:
                b_err = _shield_validate_batch_ids(
                    rec.get("expression_batch_ids"),
                    f"off_target[{oid_c}]",
                    passing_batch_constructs,
                    tmp_ref_o,
                    required_construct_all=_SHIELD_COMP1_LEAD,
                    role_comp1_batches=tmp_c1_o,
                )
                if b_err is None and (not tmp_c1_o or not tmp_c1_o.issubset(sec_comp1_qualified_batches)):
                    off_row_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"off_target[{oid_c}]: excluded from biological adjudication and batch-linkage credit "
                        f"because Comp1 expression_batch_ids={sorted(tmp_c1_o)} lack passing Comp1 SEC-MALS/DLS "
                        f"physicochemical material qualification (qualified_comp1_batches={sorted(sec_comp1_qualified_batches)})",
                    )
            elif oid_c in _SHIELD_MANDATORY_COMP2_OFF_TARGET_CONTROLS:
                b_err = _shield_validate_batch_ids(
                    rec.get("expression_batch_ids"),
                    f"off_target[{oid_c}]",
                    passing_batch_constructs,
                    tmp_ref_o,
                    required_construct_all=_SHIELD_COMP2_LEAD,
                    role_comp2_batches=tmp_c2_o,
                )
                if b_err is None and (not tmp_c2_o or not tmp_c2_o.issubset(sec_comp2_qualified_batches)):
                    off_row_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"off_target[{oid_c}]: excluded from biological adjudication and batch-linkage credit "
                        f"because Comp2 expression_batch_ids={sorted(tmp_c2_o)} lack passing Comp2 SEC-MALS/DLS "
                        f"physicochemical material qualification (qualified_comp2_batches={sorted(sec_comp2_qualified_batches)})",
                    )
                if oid_c == "HLA-DQ8-trans + WT InsB:9-23":
                    off_pseq = rec.get("peptide_sequence")
                    if off_pseq != "SHLVEALYLVCGERG":
                        off_row_valid = False
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"off_target[{oid_c}]: missing or wrong peptide_sequence={off_pseq!r} "
                            f"(expected 15-aa SHLVEALYLVCGERG); excluded from biological adjudication and batch-linkage credit",
                        )
                    raw_off_wt_lot = rec.get("peptide_reagent_lot_id")
                    off_wt_lot_id: str | None = None
                    if (
                        type(raw_off_wt_lot) is not str
                        or not raw_off_wt_lot
                        or raw_off_wt_lot != raw_off_wt_lot.strip()
                        or not _SHIELD_STRICT_ID_RE.match(raw_off_wt_lot)
                    ):
                        off_row_valid = False
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"off_target[{oid_c}]: missing valid unpadded peptide_reagent_lot_id matching "
                            f"{_SHIELD_STRICT_ID_RE.pattern} (got {raw_off_wt_lot!r}); excluded from biological "
                            f"adjudication and batch-linkage credit",
                        )
                    else:
                        off_wt_lot_id = raw_off_wt_lot
                    if not wt15_register_qc_valid or rqc_wt_lot is None:
                        off_row_valid = False
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"off_target[{oid_c}]: excluded from biological adjudication and batch-linkage credit "
                            f"because mandatory register_qc_records WT15/6DFX QC or reagent lot is missing or failed",
                        )
                    elif off_wt_lot_id is not None and rqc_wt_lot != off_wt_lot_id:
                        off_row_valid = False
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"off_target[{oid_c}]: peptide_reagent_lot_id mismatch: off_target_controls="
                            f"{off_wt_lot_id!r} != register_qc_records={rqc_wt_lot!r}; "
                            f"WT15 off-target row excluded from biological adjudication and batch-linkage credit",
                        )
                    if b_err is None and (not tmp_c2_o or not tmp_c2_o.issubset(rqc_comp2_batches)):
                        off_row_valid = False
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"off_target[{oid_c}]: Comp2 expression_batch_ids={sorted(tmp_c2_o)} are not covered by "
                            f"parent register_qc_records Comp2 batches={sorted(rqc_comp2_batches)}; excluded from "
                            f"biological adjudication and batch-linkage credit",
                        )
            else:
                off_row_valid = False
                b_err = None
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"Unregistered off_target_control record rejected (excluded from biological FAIL adjudication): {oid_c!r}",
                )
            if b_err is not None:
                off_row_valid = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", b_err)
            _, rep_err = _shield_check_strict_int(
                rec.get("replicates_n"), f"off_target[{oid_c}].replicates_n", min_val=_SHIELD_MIN_SPR_REPLICATES_N
            )
            if rep_err is not None:
                off_row_valid = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", rep_err)
            sel_l, sel_l_err = _shield_check_num(rec.get("selectivity_l95_fold"), f"off_target[{oid_c}].selectivity_l95_fold", lo=0.0)
            sel_u, sel_u_err = _shield_check_num(rec.get("selectivity_u95_fold"), f"off_target[{oid_c}].selectivity_u95_fold", lo=0.0)
            if sel_l_err is not None:
                off_row_valid = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", sel_l_err)
            if sel_u_err is not None:
                off_row_valid = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", sel_u_err)
            if sel_l is not None and sel_u is not None and sel_l > sel_u:
                off_row_valid = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"off_target[{oid_c}]: inverted selectivity CI L95={sel_l} > U95={sel_u}")
            if off_row_valid and sel_l is not None and sel_u is not None:
                referenced_batches.update(tmp_ref_o)
                comp1_assay_batches.update(tmp_c1_o)
                comp2_assay_batches.update(tmp_c2_o)
                if sel_u < 10.0:
                    spr_bio_fail = True
                    if oid_c in _SHIELD_MANDATORY_COMP1_OFF_TARGET_CONTROLS:
                        comp1_spr_bio_fail = True
                    elif oid_c in _SHIELD_MANDATORY_COMP2_OFF_TARGET_CONTROLS:
                        comp2_spr_bio_fail = True
                    _escalate("FAIL", f"off_target[{oid_c}]: selectivity U95={sel_u:.2f}x < 10.0x FAIL bar")
                elif sel_l < 50.0:
                    _escalate("HOLD", f"off_target[{oid_c}]: selectivity L95={sel_l:.2f}x < 50.0x PASS bar")
                elif oid_c in _SHIELD_MANDATORY_COMP1_OFF_TARGET_CONTROLS:
                    comp1_off_target_passed_controls.add(oid_c)
        missing_comp1_off = [o for o in _SHIELD_MANDATORY_COMP1_OFF_TARGET_CONTROLS if o not in seen_off]
        missing_comp2_off = [o for o in _SHIELD_MANDATORY_COMP2_OFF_TARGET_CONTROLS if o not in seen_off]
        if missing_comp1_off:
            _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"Missing mandatory Component 1 off-target SPR controls: {missing_comp1_off}")
        if missing_comp2_off:
            _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"Missing mandatory Component 2 off-target SPR controls: {missing_comp2_off}")

    # 5. Comp2 parallel comparators screened (R08 B3 + R15 0039-B2: two-pass order-independent canonical key &
    #    evidence_record_id uniqueness; all 6 required; EVERY comparator MUST carry closed-schema per-condition
    #    register_control_screens covering BOTH mandatory register analytes — native 15-aa WT InsB:9-23 [WT15]
    #    AND engineered 12-aa 6DFX p8E9E [6DFX] — bound to construct-specific batches, validated register_qc_records
    #    reagent lots/sequences, replicates_n >= 3, and unique evidence_record_id; optional physical 1JK8 allowed as
    #    omitted or JSON null and strictly validated if non-null!)
    _allowed_comp_row_keys = frozenset({
        "comparator_id",
        "screened",
        "replicates_n",
        "expression_batch_ids",
        "register_control_screens",
    })
    _allowed_comp_reg_keys = frozenset({
        "native_wt_insb9_23_15aa",
        "engineered_6dfx_p8e9e_12aa",
        "crystal_ref_1jk8_14aa",
    })
    _required_comp_cond_keys = frozenset({
        "screened",
        "peptide_sequence",
        "peptide_reagent_lot_id",
        "expression_batch_ids",
        "replicates_n",
        "evidence_record_id",
    })
    _required_comp_1jk8_keys = frozenset({
        "screened",
        "peptide_sequence",
        "expression_batch_ids",
        "replicates_n",
        "evidence_record_id",
    })
    _allowed_comp_1jk8_keys = _required_comp_1jk8_keys | frozenset({"peptide_reagent_lot_id"})
    comps_raw = observation.get("comp2_comparators_screened")
    seen_comps: set[str] = set()
    conflicted_comps: set[str] = set()
    conflicted_comp_ev_ids: set[str] = set()
    verified_comparators_both_registers: set[str] = set()
    comparator_shared_batches_by_id: dict[str, list[str]] = {}
    if not isinstance(comps_raw, list) or len(comps_raw) == 0:
        _escalate("HOLD_INVALID_OR_MISSING_INPUT", "Missing typed comp2_comparators_screened list (all 6 comparators required)")
    else:
        comp_counts: dict[str, int] = {}
        comp_ev_counts: dict[str, int] = {}
        for rec in comps_raw:
            if isinstance(rec, dict):
                cid = rec.get("comparator_id")
                if type(cid) is str and cid.strip():
                    cid_p = _shield_canonicalize_construct_id(cid)
                    comp_counts[cid_p] = comp_counts.get(cid_p, 0) + 1
                rc_screens = rec.get("register_control_screens")
                if isinstance(rc_screens, dict):
                    for cond_v in rc_screens.values():
                        if isinstance(cond_v, dict):
                            raw_ev = cond_v.get("evidence_record_id")
                            if type(raw_ev) is str and raw_ev.strip():
                                ev_norm = raw_ev.strip()
                                comp_ev_counts[ev_norm] = comp_ev_counts.get(ev_norm, 0) + 1
        conflicted_comps = {k for k, cnt in comp_counts.items() if cnt > 1}
        for ccid in sorted(conflicted_comps):
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"Duplicate/conflicting comparator canonical key: {ccid!r} (count={comp_counts[ccid]}); all occurrences excluded",
            )
        conflicted_comp_ev_ids = {k for k, cnt in comp_ev_counts.items() if cnt > 1}
        for cev in sorted(conflicted_comp_ev_ids):
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"Duplicate/conflicting comparator register-screen evidence_record_id: {cev!r} (count={comp_ev_counts[cev]}); "
                f"all affected comparator rows excluded from coverage and batch-linkage credit",
            )

        for idx, rec in enumerate(comps_raw):
            if not isinstance(rec, dict):
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"comp2_comparators_screened[{idx}] must be an object")
                continue
            cid = rec.get("comparator_id")
            if type(cid) is not str or not cid.strip():
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"comp2_comparators_screened[{idx}] missing comparator_id")
                continue
            cid_c = _shield_canonicalize_construct_id(cid)
            seen_comps.add(cid_c)
            if cid_c in conflicted_comps:
                continue
            if cid_c not in _SHIELD_MANDATORY_COMP2_COMPARATORS:
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"Unregistered comp2_comparator record rejected: {cid_c!r}")
                continue
            comp_row_valid = True
            extra_comp_keys = sorted(set(rec.keys()) - _allowed_comp_row_keys)
            if extra_comp_keys:
                comp_row_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"comparator[{cid_c}] contains unexpected/untyped keys {extra_comp_keys}; "
                    f"strict closed schema with typed register_control_screens required",
                )
            tmp_ref_c: set[str] = set()
            tmp_c2_c: set[str] = set()
            b_err = _shield_validate_batch_ids(
                rec.get("expression_batch_ids"),
                f"comparator[{cid_c}]",
                passing_batch_constructs,
                tmp_ref_c,
                required_construct_all=cid_c,
                role_comp2_batches=tmp_c2_c if cid_c == _SHIELD_COMP2_LEAD else None,
            )
            if b_err is not None:
                comp_row_valid = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", b_err)
            elif cid_c == _SHIELD_COMP2_LEAD:
                if not tmp_c2_c or not tmp_c2_c.issubset(rqc_comp2_batches):
                    comp_row_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"comparator[{cid_c}]: Comp2 expression_batch_ids={sorted(tmp_c2_c)} are not covered by "
                        f"parent register_qc_records Comp2 batches={sorted(rqc_comp2_batches)}",
                    )
                if not tmp_c2_c or not tmp_c2_c.issubset(sec_comp2_qualified_batches):
                    comp_row_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"comparator[{cid_c}]: Comp2 expression_batch_ids={sorted(tmp_c2_c)} lack passing Comp2 "
                        f"SEC-MALS/DLS physicochemical material qualification "
                        f"(qualified_comp2_batches={sorted(sec_comp2_qualified_batches)})",
                    )
            if rec.get("screened") is not True:
                comp_row_valid = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"Comparator {cid_c!r} not marked screened=True")
            _, rep_err = _shield_check_strict_int(
                rec.get("replicates_n"), f"comparator[{cid_c}].replicates_n", min_val=_SHIELD_MIN_SPR_REPLICATES_N
            )
            if rep_err is not None:
                comp_row_valid = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", rep_err)

            reg_screens = rec.get("register_control_screens")
            cond_wt_batches: set[str] = set()
            cond_6dfx_batches: set[str] = set()
            if not isinstance(reg_screens, dict):
                comp_row_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"comparator[{cid_c}] missing mandatory typed register_control_screens object "
                    f"(must explicitly cover BOTH native_wt_insb9_23_15aa [WT15] AND engineered_6dfx_p8e9e_12aa [6DFX])",
                )
            else:
                extra_reg_keys = sorted(set(reg_screens.keys()) - _allowed_comp_reg_keys)
                if extra_reg_keys:
                    comp_row_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"comparator[{cid_c}].register_control_screens contains unexpected register keys {extra_reg_keys}",
                    )
                for cond_key, exp_seq, exp_lot, cond_rqc_ok, out_batches in (
                    ("native_wt_insb9_23_15aa", "SHLVEALYLVCGERG", rqc_wt_lot, wt15_register_qc_valid, cond_wt_batches),
                    ("engineered_6dfx_p8e9e_12aa", "VEELYLVAGEEG", rqc_6dfx_lot, r6dfx_qc_valid, cond_6dfx_batches),
                ):
                    cond_obj = reg_screens.get(cond_key)
                    cond_lbl = f"comparator[{cid_c}].register_control_screens.{cond_key}"
                    if not isinstance(cond_obj, dict):
                        comp_row_valid = False
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"{cond_lbl} missing mandatory per-comparator register screen record",
                        )
                        continue
                    extra_ckeys = sorted(set(cond_obj.keys()) - _required_comp_cond_keys)
                    missing_ckeys = sorted(_required_comp_cond_keys - set(cond_obj.keys()))
                    if extra_ckeys or missing_ckeys:
                        comp_row_valid = False
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"{cond_lbl} closed-schema key violation (missing={missing_ckeys}, extra={extra_ckeys})",
                        )
                    if cond_obj.get("screened") is not True:
                        comp_row_valid = False
                        _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"{cond_lbl}.screened must be literal boolean True")
                    if cond_obj.get("peptide_sequence") != exp_seq:
                        comp_row_valid = False
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"{cond_lbl}.peptide_sequence={cond_obj.get('peptide_sequence')!r} != expected {exp_seq!r}",
                        )
                    raw_c_lot = cond_obj.get("peptide_reagent_lot_id")
                    cond_lot_ok = (
                        type(raw_c_lot) is str
                        and bool(raw_c_lot)
                        and raw_c_lot == raw_c_lot.strip()
                        and bool(_SHIELD_STRICT_ID_RE.match(raw_c_lot))
                    )
                    if not cond_lot_ok:
                        comp_row_valid = False
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"{cond_lbl} missing valid unpadded peptide_reagent_lot_id (got {raw_c_lot!r})",
                        )
                    elif not cond_rqc_ok or exp_lot is None:
                        comp_row_valid = False
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"{cond_lbl} excluded because mandatory register_qc_records.{cond_key} QC or parent batch linkage failed",
                        )
                    elif raw_c_lot != exp_lot:
                        comp_row_valid = False
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"{cond_lbl}.peptide_reagent_lot_id={raw_c_lot!r} != register_qc_records.{cond_key} lot {exp_lot!r}",
                        )
                    _, crep_err = _shield_check_strict_int(
                        cond_obj.get("replicates_n"), f"{cond_lbl}.replicates_n", min_val=_SHIELD_MIN_SPR_REPLICATES_N
                    )
                    if crep_err is not None:
                        comp_row_valid = False
                        _escalate("HOLD_INVALID_OR_MISSING_INPUT", crep_err)
                    raw_cev = cond_obj.get("evidence_record_id")
                    if (
                        type(raw_cev) is not str
                        or not raw_cev
                        or raw_cev != raw_cev.strip()
                        or not _SHIELD_EVIDENCE_REF_RE.match(raw_cev)
                    ):
                        comp_row_valid = False
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"{cond_lbl}.evidence_record_id must be an unpadded audit ref matching "
                            f"{_SHIELD_EVIDENCE_REF_RE.pattern} (got {raw_cev!r})",
                        )
                    elif raw_cev in conflicted_comp_ev_ids:
                        comp_row_valid = False
                    cb_err = _shield_validate_batch_ids(
                        cond_obj.get("expression_batch_ids"),
                        cond_lbl,
                        passing_batch_constructs,
                        out_batches,
                        required_construct_all=cid_c,
                    )
                    if cb_err is not None:
                        comp_row_valid = False
                        _escalate("HOLD_INVALID_OR_MISSING_INPUT", cb_err)
                    elif b_err is None and not out_batches.issubset(tmp_ref_c):
                        comp_row_valid = False
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"{cond_lbl}.expression_batch_ids={sorted(out_batches)} must be a subset of "
                            f"comparator[{cid_c}].expression_batch_ids={sorted(tmp_ref_c)}",
                        )
                    elif cid_c == _SHIELD_COMP2_LEAD:
                        if not out_batches.issubset(rqc_comp2_batches):
                            comp_row_valid = False
                            _escalate(
                                "HOLD_INVALID_OR_MISSING_INPUT",
                                f"{cond_lbl}.expression_batch_ids={sorted(out_batches)} not covered by "
                                f"register_qc_records Comp2 batches={sorted(rqc_comp2_batches)}",
                            )
                        if not out_batches.issubset(sec_comp2_qualified_batches):
                            comp_row_valid = False
                            _escalate(
                                "HOLD_INVALID_OR_MISSING_INPUT",
                                f"{cond_lbl}.expression_batch_ids={sorted(out_batches)} lack passing Comp2 "
                                f"SEC-MALS/DLS qualification ({sorted(sec_comp2_qualified_batches)})",
                            )

                if "crystal_ref_1jk8_14aa" in reg_screens and reg_screens["crystal_ref_1jk8_14aa"] is not None:
                    c1jk8_obj = reg_screens["crystal_ref_1jk8_14aa"]
                    c1jk8_lbl = f"comparator[{cid_c}].register_control_screens.crystal_ref_1jk8_14aa"
                    if not isinstance(c1jk8_obj, dict):
                        comp_row_valid = False
                        _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"{c1jk8_lbl} must be an object or null")
                    else:
                        extra_1k = sorted(set(c1jk8_obj.keys()) - _allowed_comp_1jk8_keys)
                        missing_1k = sorted(_required_comp_1jk8_keys - set(c1jk8_obj.keys()))
                        if extra_1k or missing_1k:
                            comp_row_valid = False
                            _escalate(
                                "HOLD_INVALID_OR_MISSING_INPUT",
                                f"{c1jk8_lbl} closed-schema key violation (missing={missing_1k}, extra={extra_1k})",
                            )
                        if c1jk8_obj.get("screened") is not True:
                            comp_row_valid = False
                            _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"{c1jk8_lbl}.screened must be literal boolean True")
                        if c1jk8_obj.get("peptide_sequence") != "LVEALYLVCGERGG":
                            comp_row_valid = False
                            _escalate(
                                "HOLD_INVALID_OR_MISSING_INPUT",
                                f"{c1jk8_lbl}.peptide_sequence={c1jk8_obj.get('peptide_sequence')!r} != expected 'LVEALYLVCGERGG'",
                            )
                        if not r1jk8_qc_valid:
                            comp_row_valid = False
                            _escalate(
                                "HOLD_INVALID_OR_MISSING_INPUT",
                                f"{c1jk8_lbl} supplied without passing register_qc_records.crystal_ref_1jk8_14aa QC",
                            )
                        if "peptide_reagent_lot_id" in c1jk8_obj:
                            raw_1k_lot = c1jk8_obj["peptide_reagent_lot_id"]
                            if (
                                type(raw_1k_lot) is not str
                                or not raw_1k_lot
                                or raw_1k_lot != raw_1k_lot.strip()
                                or not _SHIELD_STRICT_ID_RE.match(raw_1k_lot)
                            ):
                                comp_row_valid = False
                                _escalate(
                                    "HOLD_INVALID_OR_MISSING_INPUT",
                                    f"{c1jk8_lbl}.peptide_reagent_lot_id invalid ({raw_1k_lot!r})",
                                )
                            elif raw_1k_lot in {x for x in (rqc_hip11_lot, rqc_wt_lot, rqc_6dfx_lot) if x is not None}:
                                comp_row_valid = False
                                _escalate(
                                    "HOLD_INVALID_OR_MISSING_INPUT",
                                    f"{c1jk8_lbl}.peptide_reagent_lot_id={raw_1k_lot!r} reuses HIP11, WT15, or 6DFX lot ID",
                                )
                            elif rqc_1jk8_lot is not None and raw_1k_lot != rqc_1jk8_lot:
                                comp_row_valid = False
                                _escalate(
                                    "HOLD_INVALID_OR_MISSING_INPUT",
                                    f"{c1jk8_lbl}.peptide_reagent_lot_id={raw_1k_lot!r} != register_qc_records lot {rqc_1jk8_lot!r}",
                                )
                        _, c1rep_err = _shield_check_strict_int(
                            c1jk8_obj.get("replicates_n"), f"{c1jk8_lbl}.replicates_n", min_val=_SHIELD_MIN_SPR_REPLICATES_N
                        )
                        if c1rep_err is not None:
                            comp_row_valid = False
                            _escalate("HOLD_INVALID_OR_MISSING_INPUT", c1rep_err)
                        raw_1ev = c1jk8_obj.get("evidence_record_id")
                        if (
                            type(raw_1ev) is not str
                            or not raw_1ev
                            or raw_1ev != raw_1ev.strip()
                            or not _SHIELD_EVIDENCE_REF_RE.match(raw_1ev)
                        ):
                            comp_row_valid = False
                            _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"{c1jk8_lbl}.evidence_record_id invalid ({raw_1ev!r})")
                        elif raw_1ev in conflicted_comp_ev_ids:
                            comp_row_valid = False
                        tmp_1k_b: set[str] = set()
                        c1b_err = _shield_validate_batch_ids(
                            c1jk8_obj.get("expression_batch_ids"),
                            c1jk8_lbl,
                            passing_batch_constructs,
                            tmp_1k_b,
                            required_construct_all=cid_c,
                        )
                        if c1b_err is not None:
                            comp_row_valid = False
                            _escalate("HOLD_INVALID_OR_MISSING_INPUT", c1b_err)
                        elif b_err is None and not tmp_1k_b.issubset(tmp_ref_c):
                            comp_row_valid = False
                            _escalate(
                                "HOLD_INVALID_OR_MISSING_INPUT",
                                f"{c1jk8_lbl}.expression_batch_ids={sorted(tmp_1k_b)} must be a subset of "
                                f"comparator[{cid_c}].expression_batch_ids={sorted(tmp_ref_c)}",
                            )

            # R16 Shared Blocker #2: Require non-empty shared comparator expression batch intersection
            # evaluated across BOTH native WT15 AND engineered 6DFX before granting complete-comparator
            # credit, batch-linkage credit, or Track-B candidacy!
            dual_reg_batches = cond_wt_batches & cond_6dfx_batches
            if cond_wt_batches and cond_6dfx_batches and len(dual_reg_batches) == 0:
                comp_row_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"comparator[{cid_c}]: native_wt_insb9_23_15aa expression_batch_ids={sorted(cond_wt_batches)} "
                    f"and engineered_6dfx_p8e9e_12aa expression_batch_ids={sorted(cond_6dfx_batches)} have empty "
                    f"shared-batch intersection (matched comparator material evaluated across BOTH WT15 and 6DFX "
                    f"is required to identify the register contrast; disjoint batches earn zero comparator credit "
                    f"and suppress Track-B candidacy)",
                )

            if comp_row_valid and len(dual_reg_batches) > 0:
                referenced_batches.update(dual_reg_batches)
                if cid_c == _SHIELD_COMP2_LEAD:
                    comp2_assay_batches.update(dual_reg_batches & tmp_c2_c)
                verified_comparators_both_registers.add(cid_c)
                comparator_shared_batches_by_id[cid_c] = sorted(dual_reg_batches)
        missing_comps = [c for c in _SHIELD_MANDATORY_COMP2_COMPARATORS if c not in seen_comps]
        if missing_comps:
            _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"Missing mandatory Comp2 parallel comparators: {missing_comps}")
    derived_summary["comparator_mandatory_register_controls"] = [
        "native_wt_insb9_23_15aa",
        "engineered_6dfx_p8e9e_12aa",
    ]
    derived_summary["comparator_shared_batch_required_across_wt15_and_6dfx"] = True
    derived_summary["comparator_shared_wt15_6dfx_batches"] = comparator_shared_batches_by_id
    derived_summary["comparator_wt15_and_6dfx_verified_count"] = len(verified_comparators_both_registers)
    derived_summary["comparator_mandatory_register_coverage_verified"] = bool(
        len(conflicted_comps) == 0
        and len(conflicted_comp_ev_ids) == 0
        and verified_comparators_both_registers == set(_SHIELD_MANDATORY_COMP2_COMPARATORS)
    )

    # (Step 6 SEC-MALS/DLS physicochemical qualification was evaluated strictly BEFORE Steps 3 & 4 in Step 2b above.)

    # 7. Primary human T-cell blockade & off-target APC cytotoxicity donors
    #    (R09 B2: MANDATORY cryptographically hash-pinned outcome-blind preregistered_donor_family_roster
    #             reconciled 100% against submitted donors + optional pre-assay excluded_donor_records;
    #             NEVER optional, NEVER defaults to submitted row count; missing/tampered/incomplete
    #             roster fails closed to non-authorizing HOLD_INVALID_OR_MISSING_INPUT!
    #     R09 B3: Distribution-free exact one-sided Clopper-Pearson responder-proportion suppression test
    #             over fixed N_roster (estimand P(suppression_pct >= 70.0%), PASS requires L95_CP >= 70.0%
    #             [min N_roster=9] + min >= 0.0% anti-enhancement guard + mean >= 70.0%; FAIL requires
    #             L95_CP(k_lt_40, N_roster) > 60.0%; Student-t is strictly non-authorizing diagnostic!).
    #     R09 M1: Mandatory structured gy018_independence_justification per donor.
    #     R08 B3/B4/B5: Two-pass order-independent donor_id uniqueness; fixed pre-exclusion N_roster
    #             Bonferroni FWER <= 0.05 under H0_all: max_i p_i <= 5.0%; mandatory typed T1D eligibility;
    #             exact GY-018 deff == 1.0 preserved as Decimal through JSON decoding.)
    roster_obj = observation.get("preregistered_donor_family_roster")
    roster_verified = False
    roster_id_val: str | None = None
    roster_ts_val: str | None = None
    roster_ts_dt: datetime | None = None
    roster_sha256_val: str | None = None
    roster_donor_ids: list[str] = []
    roster_set: frozenset[str] = frozenset()
    roster_planned_n: int | None = None
    roster_predeclared_n_by_donor: dict[str, int] = {}
    roster_planned_looks_val: int | None = None
    roster_single_look_locked = False
    roster_sample_size_plan_mismatched_donors: set[str] = set()

    _allowed_roster_keys = frozenset({
        "roster_id",
        "preregistration_timestamp_utc",
        "outcome_blind_lock_attestation",
        "single_look_fixed_horizon_plan_locked",
        "planned_analysis_looks",
        "roster_donor_ids",
        "planned_t1d_donor_family_n",
        "predeclared_per_donor_unit_count_n",
        "predeclared_per_donor_unit_counts",
        "roster_sha256",
        "assay_readout_timestamp_utc",
    })

    if not isinstance(roster_obj, dict):
        _escalate(
            "HOLD_INVALID_OR_MISSING_INPUT",
            "Missing mandatory preregistered_donor_family_roster block (outcome-blind, SHA-256-pinned "
            "pre-registered T1D donor roster locking donor membership, fixed per-donor sample size N, "
            "and single-look fixed horizon is required for authorization-grade overall PASS or donor-based "
            "FAIL; never defaults to submitted row count; independent valid non-donor SPR "
            "FAIL remains fail-first FAIL)",
        )
    else:
        roster_ok = True
        extra_roster_keys = sorted(set(roster_obj.keys()) - _allowed_roster_keys)
        if extra_roster_keys:
            roster_ok = False
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"preregistered_donor_family_roster contains unexpected/untyped keys {extra_roster_keys}; "
                f"strict closed schema required",
            )
        raw_rid = roster_obj.get("roster_id")
        if type(raw_rid) is not str or not raw_rid or raw_rid != raw_rid.strip() or not _SHIELD_STRICT_ID_RE.match(raw_rid):
            roster_ok = False
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"preregistered_donor_family_roster.roster_id must be a non-empty unpadded ID matching "
                f"{_SHIELD_STRICT_ID_RE.pattern} (got {raw_rid!r})",
            )
        raw_ts = roster_obj.get("preregistration_timestamp_utc")
        ts_dt, ts_err = _shield_parse_iso8601_utc(raw_ts, "preregistered_donor_family_roster.preregistration_timestamp_utc")
        if ts_err is not None or ts_dt is None:
            roster_ok = False
            _escalate("HOLD_INVALID_OR_MISSING_INPUT", ts_err or "Invalid preregistration_timestamp_utc")
        else:
            roster_ts_dt = ts_dt

        readout_ts_raw = (
            observation.get("assay_readout_timestamp_utc")
            if "assay_readout_timestamp_utc" in observation and observation["assay_readout_timestamp_utc"] is not None
            else roster_obj.get("assay_readout_timestamp_utc")
        )
        if readout_ts_raw is not None:
            rd_dt, rd_err = _shield_parse_iso8601_utc(readout_ts_raw, "assay_readout_timestamp_utc")
            if rd_err is not None or rd_dt is None:
                roster_ok = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", rd_err or "Invalid assay_readout_timestamp_utc")
            elif roster_ts_dt is not None and not (roster_ts_dt < rd_dt):
                roster_ok = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"preregistered_donor_family_roster.preregistration_timestamp_utc={raw_ts!r} must strictly precede "
                    f"assay_readout_timestamp_utc={readout_ts_raw!r} (outcome-blind pre-registration violated)",
                )

        if roster_obj.get("outcome_blind_lock_attestation") is not True:
            roster_ok = False
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"preregistered_donor_family_roster.outcome_blind_lock_attestation must be literal boolean True "
                f"(got {roster_obj.get('outcome_blind_lock_attestation')!r})",
            )

        # R16 Shared Blocker #3: Cryptographically lock single-look fixed horizon + fixed per-donor sample size N
        if roster_obj.get("single_look_fixed_horizon_plan_locked") is not True:
            roster_ok = False
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"preregistered_donor_family_roster.single_look_fixed_horizon_plan_locked must be literal boolean True "
                f"(got {roster_obj.get('single_look_fixed_horizon_plan_locked')!r}; unverified or adaptive stopping plans "
                f"cannot authorize fixed-horizon Bonferroni FWER <= 0.05)",
            )
        raw_looks = roster_obj.get("planned_analysis_looks")
        if type(raw_looks) is not int or raw_looks != 1:
            roster_ok = False
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"preregistered_donor_family_roster.planned_analysis_looks must be strict integer 1 for fixed-horizon "
                f"single-look Bonferroni adjudication (got {raw_looks!r}; multi-look/interim peeking rejected fail-closed)",
            )

        raw_r_ids = roster_obj.get("roster_donor_ids")
        parsed_r_ids: list[str] = []
        if not isinstance(raw_r_ids, list) or len(raw_r_ids) < _SHIELD_MIN_DONORS_N:
            roster_ok = False
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"preregistered_donor_family_roster.roster_donor_ids must be a list of >= {_SHIELD_MIN_DONORS_N} "
                f"unique unpadded canonical T1D donor IDs",
            )
        else:
            seen_r_ids: set[str] = set()
            for r_idx, r_item in enumerate(raw_r_ids):
                if (
                    type(r_item) is not str
                    or not r_item
                    or r_item != r_item.strip()
                    or not _SHIELD_STRICT_ID_RE.match(r_item)
                ):
                    roster_ok = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"preregistered_donor_family_roster.roster_donor_ids[{r_idx}] must be an unpadded canonical ID "
                        f"matching {_SHIELD_STRICT_ID_RE.pattern} (got {r_item!r})",
                    )
                    continue
                if _SHIELD_FORBIDDEN_NON_T1D_DONOR_RE.search(r_item):
                    roster_ok = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"preregistered_donor_family_roster.roster_donor_ids[{r_idx}]={r_item!r} contains forbidden "
                        f"non-T1D donor token",
                    )
                    continue
                if r_item in seen_r_ids:
                    roster_ok = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"preregistered_donor_family_roster.roster_donor_ids contains duplicate donor_id {r_item!r}",
                    )
                    continue
                seen_r_ids.add(r_item)
                parsed_r_ids.append(r_item)

        r_plan_v, r_plan_err = _shield_check_strict_int(
            roster_obj.get("planned_t1d_donor_family_n"),
            "preregistered_donor_family_roster.planned_t1d_donor_family_n",
            min_val=_SHIELD_MIN_DONORS_N,
        )
        if r_plan_err is not None or r_plan_v is None:
            roster_ok = False
            _escalate("HOLD_INVALID_OR_MISSING_INPUT", r_plan_err or "Invalid roster planned_t1d_donor_family_n")
        elif isinstance(raw_r_ids, list) and len(parsed_r_ids) == len(raw_r_ids) and r_plan_v != len(parsed_r_ids):
            roster_ok = False
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"preregistered_donor_family_roster.planned_t1d_donor_family_n={r_plan_v} != "
                f"len(roster_donor_ids)={len(parsed_r_ids)}",
            )

        has_r_scalar_n = "predeclared_per_donor_unit_count_n" in roster_obj
        has_r_map_n = "predeclared_per_donor_unit_counts" in roster_obj
        roster_scalar_n: int | None = None
        parsed_r_n_map: dict[str, int] | None = None
        parsed_roster_n_by_donor: dict[str, int] = {}
        if not has_r_scalar_n and not has_r_map_n:
            roster_ok = False
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                "preregistered_donor_family_roster missing mandatory fixed per-donor cytotoxicity sample size "
                "commitment (predeclared_per_donor_unit_count_n or predeclared_per_donor_unit_counts)",
            )
        else:
            if has_r_scalar_n:
                r_sn, r_sn_err = _shield_check_strict_int(
                    roster_obj.get("predeclared_per_donor_unit_count_n"),
                    "preregistered_donor_family_roster.predeclared_per_donor_unit_count_n",
                    min_val=_SHIELD_MIN_CYTO_N_EFF_PER_DONOR,
                )
                if r_sn_err is not None or r_sn is None:
                    roster_ok = False
                    _escalate("HOLD_INVALID_OR_MISSING_INPUT", r_sn_err or "Invalid roster predeclared_per_donor_unit_count_n")
                else:
                    roster_scalar_n = r_sn
            if has_r_map_n:
                raw_n_map = roster_obj.get("predeclared_per_donor_unit_counts")
                if not isinstance(raw_n_map, dict) or len(raw_n_map) == 0:
                    roster_ok = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        "preregistered_donor_family_roster.predeclared_per_donor_unit_counts must be a non-empty dict "
                        "mapping every rostered donor_id to a strict integer >= 60",
                    )
                else:
                    tmp_n_map: dict[str, int] = {}
                    map_valid = True
                    for mk, mv in raw_n_map.items():
                        if type(mk) is not str or not mk or mk != mk.strip():
                            map_valid = False
                            roster_ok = False
                            _escalate(
                                "HOLD_INVALID_OR_MISSING_INPUT",
                                f"preregistered_donor_family_roster.predeclared_per_donor_unit_counts invalid key {mk!r}",
                            )
                            continue
                        mv_i, mv_err = _shield_check_strict_int(
                            mv,
                            f"preregistered_donor_family_roster.predeclared_per_donor_unit_counts[{mk}]",
                            min_val=_SHIELD_MIN_CYTO_N_EFF_PER_DONOR,
                        )
                        if mv_err is not None or mv_i is None:
                            map_valid = False
                            roster_ok = False
                            _escalate("HOLD_INVALID_OR_MISSING_INPUT", mv_err or "Invalid per-donor unit count")
                        else:
                            tmp_n_map[mk] = mv_i
                    if map_valid:
                        if isinstance(raw_r_ids, list) and len(parsed_r_ids) == len(raw_r_ids) and set(tmp_n_map.keys()) != set(parsed_r_ids):
                            roster_ok = False
                            _escalate(
                                "HOLD_INVALID_OR_MISSING_INPUT",
                                f"preregistered_donor_family_roster.predeclared_per_donor_unit_counts keys "
                                f"{sorted(tmp_n_map.keys())} must exactly match roster_donor_ids {sorted(parsed_r_ids)}",
                            )
                        else:
                            parsed_r_n_map = tmp_n_map
            if roster_scalar_n is not None and parsed_r_n_map is not None:
                if any(v != roster_scalar_n for v in parsed_r_n_map.values()):
                    roster_ok = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"preregistered_donor_family_roster.predeclared_per_donor_unit_count_n={roster_scalar_n} "
                        f"disagrees with predeclared_per_donor_unit_counts={parsed_r_n_map}",
                    )
            if roster_ok:
                if parsed_r_n_map is not None:
                    parsed_roster_n_by_donor = {did_r: parsed_r_n_map[did_r] for did_r in parsed_r_ids}
                elif roster_scalar_n is not None:
                    parsed_roster_n_by_donor = {did_r: roster_scalar_n for did_r in parsed_r_ids}

        raw_r_sha = roster_obj.get("roster_sha256")
        if type(raw_r_sha) is not str or not _SHIELD_SHA256_HEX_RE.match(raw_r_sha):
            roster_ok = False
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"preregistered_donor_family_roster.roster_sha256 must be a lowercase 64-hex SHA-256 digest "
                f"(got {raw_r_sha!r})",
            )
        elif roster_ok and type(raw_rid) is str and type(raw_ts) is str:
            expected_r_sha = _shield_compute_donor_roster_sha256(
                raw_rid,
                raw_ts,
                parsed_r_ids,
                predeclared_per_donor_unit_count_n=roster_scalar_n if has_r_scalar_n else None,
                predeclared_per_donor_unit_counts=parsed_r_n_map if has_r_map_n else None,
                planned_analysis_looks=1,
                single_look_fixed_horizon_plan_locked=True,
            )
            if raw_r_sha != expected_r_sha:
                roster_ok = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"preregistered_donor_family_roster.roster_sha256 mismatch: supplied={raw_r_sha} != "
                    f"recomputed={expected_r_sha} (tampered or unpinned donor roster / sample-size / single-look plan rejected fail-closed)",
                )

        if roster_ok and type(raw_rid) is str and type(raw_ts) is str and type(raw_r_sha) is str and r_plan_v is not None:
            roster_verified = True
            roster_id_val = raw_rid
            roster_ts_val = raw_ts
            roster_sha256_val = raw_r_sha
            roster_donor_ids = parsed_r_ids
            roster_set = frozenset(parsed_r_ids)
            roster_planned_n = r_plan_v
            roster_predeclared_n_by_donor = parsed_roster_n_by_donor
            roster_planned_looks_val = 1
            roster_single_look_locked = True

    has_top_planned = "planned_t1d_donor_family_n" in observation and observation["planned_t1d_donor_family_n"] is not None
    top_level_plan_conflict = False
    if has_top_planned:
        top_plan_val, top_plan_err = _shield_check_strict_int(
            observation["planned_t1d_donor_family_n"],
            "planned_t1d_donor_family_n",
            min_val=_SHIELD_MIN_DONORS_N,
        )
        if top_plan_err is not None or top_plan_val is None:
            top_level_plan_conflict = True
            _escalate("HOLD_INVALID_OR_MISSING_INPUT", top_plan_err or "Invalid top-level planned_t1d_donor_family_n")
        elif roster_verified and roster_planned_n is not None and top_plan_val != roster_planned_n:
            top_level_plan_conflict = True
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"Top-level planned_t1d_donor_family_n={top_plan_val} disagrees with "
                f"preregistered_donor_family_roster.planned_t1d_donor_family_n={roster_planned_n}",
            )

    has_primary_donors = "tcell_blockade_and_apc_cytotoxicity_donors" in observation
    has_alias_donors = "primary_t1d_donor_cohorts" in observation
    conflicting_donor_lists = (
        has_primary_donors
        and has_alias_donors
        and observation["tcell_blockade_and_apc_cytotoxicity_donors"] != observation["primary_t1d_donor_cohorts"]
    )
    if conflicting_donor_lists:
        _escalate(
            "HOLD_INVALID_OR_MISSING_INPUT",
            "Contradictory tcell_blockade_and_apc_cytotoxicity_donors and primary_t1d_donor_cohorts supplied; "
            "both excluded from biological adjudication",
        )
        donors_raw = None
    else:
        donors_raw = (
            observation.get("tcell_blockade_and_apc_cytotoxicity_donors")
            if has_primary_donors
            else observation.get("primary_t1d_donor_cohorts")
        )
    submitted_donor_records_n = len(donors_raw) if isinstance(donors_raw, list) else 0

    # Parse mandatory typed between-donor sampling & independence design (R10 B1/B2 + R11 B1 + R12 0037-B3 + R14 0039-B1 class-specific allowlist)
    _allowed_sampling_design_keys = frozenset({
        "sampling_design_class",
        "independent_donor_sampling_attested",
        "between_donor_shared_shock_controls_verified",
        "sampling_protocol_ref",
        "between_donor_independence_justification",
    })
    _allowed_between_donor_justifications_by_class: dict[str, frozenset[str]] = {
        "SIMPLE_RANDOM_OR_CONSECUTIVE_INDEPENDENT_T1D_COHORT": frozenset({
            "Simple random or consecutive independent T1D HLA-DQ donors executed across disjoint "
            "expression batches and separate assay runs with independent reagent preparations",
            "DISJOINT_BATCH_AND_RUN_INDEPENDENT_T1D_DONOR_COHORT",
        }),
        "STRATIFIED_INDEPENDENT_T1D_HLA_DQ_COHORT": frozenset({
            "STRATIFIED_DISJOINT_BATCH_AND_RUN_T1D_DONOR_COHORT",
        }),
    }
    sampling_design_obj = observation.get("donor_sampling_and_independence_design")
    donor_sampling_design_valid = False
    suppression_inference_authorized_by_sampling_design = False
    sampling_design_class_val: str | None = None
    sampling_protocol_ref_val: str | None = None
    if not isinstance(sampling_design_obj, dict):
        _escalate(
            "HOLD_INVALID_OR_MISSING_INPUT",
            "Missing mandatory typed donor_sampling_and_independence_design block "
            "(requires sampling_design_class, independent_donor_sampling_attested=True, "
            "between_donor_shared_shock_controls_verified=True, sampling_protocol_ref, "
            "between_donor_independence_justification)",
        )
    else:
        sd_ok = True
        extra_sd_keys = sorted(set(sampling_design_obj.keys()) - _allowed_sampling_design_keys)
        if extra_sd_keys:
            sd_ok = False
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"donor_sampling_and_independence_design contains unexpected/free-text keys {extra_sd_keys}; "
                f"strict closed typed schema required",
            )
        sd_cls = sampling_design_obj.get("sampling_design_class")
        sd_cls_valid = type(sd_cls) is str and sd_cls in _SHIELD_ALLOWED_DONOR_SAMPLING_DESIGNS
        if not sd_cls_valid:
            sd_ok = False
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"donor_sampling_and_independence_design.sampling_design_class must be in "
                f"{sorted(_SHIELD_ALLOWED_DONOR_SAMPLING_DESIGNS)} (got {sd_cls!r}; only "
                f"{sorted(_SHIELD_AUTHORIZING_DONOR_SAMPLING_DESIGNS)} authorizes unweighted "
                f"Clopper-Pearson population-suppression inference)",
            )
        if sampling_design_obj.get("independent_donor_sampling_attested") is not True:
            sd_ok = False
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                "donor_sampling_and_independence_design.independent_donor_sampling_attested must be literal boolean True",
            )
        if sampling_design_obj.get("between_donor_shared_shock_controls_verified") is not True:
            sd_ok = False
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                "donor_sampling_and_independence_design.between_donor_shared_shock_controls_verified must be literal boolean True",
            )
        sd_ref = sampling_design_obj.get("sampling_protocol_ref")
        if type(sd_ref) is not str or not sd_ref or sd_ref != sd_ref.strip() or not _SHIELD_EVIDENCE_REF_RE.match(sd_ref):
            sd_ok = False
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"donor_sampling_and_independence_design.sampling_protocol_ref must be an unpadded ref matching "
                f"{_SHIELD_EVIDENCE_REF_RE.pattern} (got {sd_ref!r})",
            )
        sd_just = sampling_design_obj.get("between_donor_independence_justification")
        allowed_just_for_cls = (
            _allowed_between_donor_justifications_by_class[sd_cls]
            if sd_cls_valid and type(sd_cls) is str
            else frozenset()
        )
        if type(sd_just) is not str or sd_just not in allowed_just_for_cls:
            sd_ok = False
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"donor_sampling_and_independence_design.between_donor_independence_justification "
                f"must be a strict class-specific canonical allowlisted declaration compatible with "
                f"sampling_design_class={sd_cls!r} (free-text prose and cross-class contradictions "
                f"rejected fail-closed; got {sd_just!r})",
            )
        if sd_ok and type(sd_cls) is str and type(sd_ref) is str:
            donor_sampling_design_valid = True
            sampling_design_class_val = sd_cls
            sampling_protocol_ref_val = sd_ref
            suppression_inference_authorized_by_sampling_design = bool(
                sd_cls in _SHIELD_AUTHORIZING_DONOR_SAMPLING_DESIGNS
            )

    # Parse optional documented pre-assay excluded_donor_records for 100% roster reconciliation
    excluded_records_valid = True
    valid_excluded_donor_ids: set[str] = set()
    raw_excluded_donor_ids: set[str] = set()
    if "excluded_donor_records" in observation and observation["excluded_donor_records"] is not None:
        excl_raw = observation["excluded_donor_records"]
        if not isinstance(excl_raw, list):
            excluded_records_valid = False
            _escalate("HOLD_INVALID_OR_MISSING_INPUT", "excluded_donor_records must be a list of pre-assay exclusion objects")
        else:
            for e_idx, e_rec in enumerate(excl_raw):
                if not isinstance(e_rec, dict):
                    excluded_records_valid = False
                    _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"excluded_donor_records[{e_idx}] must be an object")
                    continue
                e_did = e_rec.get("donor_id")
                if type(e_did) is str and e_did.strip():
                    raw_excluded_donor_ids.add(e_did.strip())
                if (
                    type(e_did) is not str
                    or not e_did
                    or e_did != e_did.strip()
                    or not _SHIELD_STRICT_ID_RE.match(e_did)
                ):
                    excluded_records_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"excluded_donor_records[{e_idx}].donor_id must be an unpadded canonical ID (got {e_did!r})",
                    )
                    continue
                if e_did in valid_excluded_donor_ids:
                    excluded_records_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"excluded_donor_records contains duplicate donor_id {e_did!r}",
                    )
                    continue
                if roster_verified and e_did not in roster_set:
                    excluded_records_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"excluded_donor_records[{e_idx}].donor_id={e_did!r} is not in preregistered_donor_family_roster",
                    )
                    continue
                e_reason = e_rec.get("pre_assay_exclusion_reason")
                if type(e_reason) is not str or len(e_reason) < 8 or e_reason != e_reason.strip():
                    excluded_records_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"excluded_donor_records[{e_idx}].pre_assay_exclusion_reason must be an unpadded string "
                        f"of length >= 8 (got {e_reason!r})",
                    )
                    continue
                if e_rec.get("outcome_blind_exclusion_attested") is not True:
                    excluded_records_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"excluded_donor_records[{e_idx}].outcome_blind_exclusion_attested must be literal True",
                    )
                    continue
                valid_excluded_donor_ids.add(e_did)

    valid_donor_sup_vals: list[float] = []
    valid_donor_sup_by_id: dict[str, float] = {}
    topology_donor_batches: dict[str, set[str]] = {}
    topology_donor_runs: dict[str, set[str]] = {}
    donors_with_invalid_topology: set[str] = set()
    valid_donor_cyto_rates: list[float] = []
    valid_donor_cp_l95s_unadj: list[float] = []
    valid_donor_cp_u95s: list[float] = []
    valid_donor_k_list: list[int] = []
    valid_donor_neff_list: list[int] = []
    seen_donors: set[str] = set()
    raw_submitted_donor_ids: set[str] = set()
    conflicted_donors: set[str] = set()
    unrostered_submitted_donors: set[str] = set()
    excluded_overlap_donors: set[str] = set()
    invalid_donors_excluded: list[str] = []
    malformed_donor_rows_present = False
    _allowed_gy018_keys = frozenset({
        "independent_unit_class",
        "within_donor_units_physically_independent",
        "clustering_controls_present_and_verified",
        "shared_well_technical_reads_excluded",
        "independence_evidence_record_id",
        "independent_experimental_unit",
        "predeclared_per_donor_unit_count_n",
        "clustering_controls",
    })

    if not isinstance(donors_raw, list) or len(donors_raw) == 0:
        _escalate("HOLD_INVALID_OR_MISSING_INPUT", "Missing typed tcell_blockade_and_apc_cytotoxicity_donors list (>= 3 distinct donors required)")
    else:
        # Pass 1 (R08 B3 + R10 B1 + R12 0037-B2): Collect ALL raw canonical submitted donor IDs & malformed rows BEFORE
        # deduplication/quarantine filtering, and enforce roster membership & overlap on the COMPLETE raw set!
        donor_id_counts: dict[str, int] = {}
        for d in donors_raw:
            if not isinstance(d, dict):
                malformed_donor_rows_present = True
                continue
            did = d.get("donor_id")
            if type(did) is not str or not did.strip():
                malformed_donor_rows_present = True
                continue
            did_p = did.strip()
            raw_submitted_donor_ids.add(did_p)
            donor_id_counts[did_p] = donor_id_counts.get(did_p, 0) + 1
            if did != did_p or not _SHIELD_STRICT_ID_RE.match(did):
                malformed_donor_rows_present = True

        # Roster-integrity checks run on ALL raw submitted donor IDs BEFORE deduplication (R10 B1!)
        for raw_did_c in sorted(raw_submitted_donor_ids):
            if roster_verified and raw_did_c not in roster_set:
                unrostered_submitted_donors.add(raw_did_c)
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{raw_did_c}]: unrostered ad-hoc donor_id not present in preregistered_donor_family_roster; "
                    f"rejected fail-closed",
                )
            if raw_did_c in valid_excluded_donor_ids or raw_did_c in raw_excluded_donor_ids:
                excluded_overlap_donors.add(raw_did_c)
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{raw_did_c}]: donor appears in BOTH submitted records and excluded_donor_records; rejected fail-closed",
                )
        for raw_ex_did in sorted(raw_excluded_donor_ids):
            if roster_verified and raw_ex_did not in roster_set:
                unrostered_submitted_donors.add(raw_ex_did)

        conflicted_donors = {k for k, cnt in donor_id_counts.items() if cnt > 1}
        for cdid in sorted(conflicted_donors):
            donors_with_invalid_topology.add(cdid)
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"Duplicate/conflicting donor_id in functional cohort: {cdid!r} (count={donor_id_counts[cdid]}); "
                f"all occurrences excluded from biological adjudication and batch-linkage credit",
            )
            invalid_donors_excluded.append(cdid)

        # Pass 1b (R12 0037-B2): Extract EVERY submitted donor's batch/run dependency links into Union-Find
        # topology maps INDEPENDENTLY OF AND BEFORE per-donor outcome/CI/GY-018 validation!
        for d in donors_raw:
            if not isinstance(d, dict):
                continue
            did = d.get("donor_id")
            if type(did) is not str or not did.strip():
                continue
            did_t = did.strip()
            raw_run_t = d.get("assay_run_id")
            if (
                type(raw_run_t) is str
                and raw_run_t
                and raw_run_t == raw_run_t.strip()
                and _SHIELD_STRICT_ID_RE.match(raw_run_t)
            ):
                topology_donor_runs.setdefault(did_t, set()).add(raw_run_t)
            else:
                donors_with_invalid_topology.add(did_t)
                if type(raw_run_t) is str and raw_run_t.strip():
                    topology_donor_runs.setdefault(did_t, set()).add(raw_run_t.strip())
            raw_bids_t = d.get("expression_batch_ids")
            if isinstance(raw_bids_t, list) and len(raw_bids_t) > 0:
                seen_tb: set[str] = set()
                tb_ok = True
                for b_item in raw_bids_t:
                    if type(b_item) is str and b_item.strip():
                        b_norm = b_item.strip()
                        topology_donor_batches.setdefault(did_t, set()).add(b_norm)
                        if b_item != b_norm or b_norm in seen_tb:
                            tb_ok = False
                        seen_tb.add(b_norm)
                    else:
                        tb_ok = False
                if not tb_ok or not seen_tb:
                    donors_with_invalid_topology.add(did_t)
            else:
                donors_with_invalid_topology.add(did_t)

        # Pass 1c (R16 Shared Blocker #1): Reconcile the fixed-horizon predeclared per-donor sample size N
        # commitment across ALL raw submitted rostered donor rows BEFORE the duplicate-donor exclusion gate!
        # Any raw rostered row whose unit counts violate roster_predeclared_n_by_donor[did] (in ANY row order,
        # e.g. [60, 70] or [70, 60] on a conflicted duplicate donor) populates roster_sample_size_plan_mismatched_donors
        # and sets authorization_grade_fwer_bound_valid = False, withholding donor-cohort authorization while
        # preserving zero biological credit for duplicate rows, avoiding false N-mismatches on matching-count
        # duplicates ([60, 60]), and preserving fail-first independent qualified SPR FAIL!
        if roster_verified:
            for idx_n, d_n in enumerate(donors_raw):
                if not isinstance(d_n, dict):
                    continue
                did_raw_n = d_n.get("donor_id")
                if type(did_raw_n) is not str or not did_raw_n.strip():
                    continue
                did_n = did_raw_n.strip()
                if did_n not in roster_predeclared_n_by_donor:
                    continue
                committed_n = roster_predeclared_n_by_donor[did_n]
                has_raw_u_n = "raw_independent_units_n" in d_n and d_n["raw_independent_units_n"] is not None
                has_raw_alias_n = "cytotoxicity_n_raw_units" in d_n and d_n["cytotoxicity_n_raw_units"] is not None
                raw_u_primary_n: int | None = None
                raw_u_alias_n: int | None = None
                if has_raw_u_n:
                    raw_u_primary_n, _ = _shield_check_strict_int(
                        d_n["raw_independent_units_n"], f"donors[{idx_n}].raw_independent_units_n", min_val=1
                    )
                if has_raw_alias_n:
                    raw_u_alias_n, _ = _shield_check_strict_int(
                        d_n["cytotoxicity_n_raw_units"], f"donors[{idx_n}].cytotoxicity_n_raw_units", min_val=1
                    )
                raw_u_ok = (
                    (has_raw_u_n or has_raw_alias_n)
                    and (not has_raw_u_n or raw_u_primary_n == committed_n)
                    and (not has_raw_alias_n or raw_u_alias_n == committed_n)
                )
                n_eff_n, _ = _shield_check_strict_int(
                    d_n.get("apc_cytotoxicity_n_eff"), f"donors[{idx_n}].apc_cytotoxicity_n_eff", min_val=1
                )
                gy_n = d_n.get("gy018_independence_justification")
                pd_n_raw: int | None = None
                if isinstance(gy_n, dict):
                    pd_n_raw, _ = _shield_check_strict_int(
                        gy_n.get("predeclared_per_donor_unit_count_n"),
                        f"donors[{idx_n}].gy018_independence_justification.predeclared_per_donor_unit_count_n",
                        min_val=_SHIELD_MIN_CYTO_N_EFF_PER_DONOR,
                    )
                if not raw_u_ok or n_eff_n != committed_n or pd_n_raw != committed_n:
                    roster_sample_size_plan_mismatched_donors.add(did_n)
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"donor[{did_n}] (row[{idx_n}]): submitted cytotoxicity sample size "
                        f"(raw_independent_units_n={raw_u_primary_n if has_raw_u_n else raw_u_alias_n}, "
                        f"apc_cytotoxicity_n_eff={n_eff_n}, gy018.predeclared_per_donor_unit_count_n={pd_n_raw}) "
                        f"violates hash-pinned preregistered_donor_family_roster fixed-horizon commitment "
                        f"N={committed_n} (unauthorized post-readout or interim sample-size change invalidates "
                        f"fixed-horizon Bonferroni FWER <= 0.05)",
                    )

        # Pass 2: Validate each non-conflicted donor record (T1D eligibility, assay_run_id, suppression assay acceptance range, GY-018 evidence!)
        for idx, d in enumerate(donors_raw):
            if not isinstance(d, dict):
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"donors[{idx}] must be an object")
                continue
            did = d.get("donor_id")
            if type(did) is not str or not did.strip():
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"donors[{idx}] missing non-empty donor_id")
                continue
            did_c = did.strip()
            seen_donors.add(did_c)
            if did_c in conflicted_donors:
                continue

            donor_valid = True
            if did != did_c or not _SHIELD_STRICT_ID_RE.match(did):
                donor_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donors[{idx}].donor_id={did!r} must be an unpadded canonical ID matching {_SHIELD_STRICT_ID_RE.pattern}",
                )
            if did_c in unrostered_submitted_donors or did_c in excluded_overlap_donors:
                donor_valid = False

            # R08 B5: Mandatory typed T1D donor eligibility verification (excluded from PASS and bio FAIL if invalid!)
            if d.get("t1d_diagnosis_confirmed") is not True:
                donor_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{did_c}]: mandatory t1d_diagnosis_confirmed must be literal boolean True "
                    f"(got {d.get('t1d_diagnosis_confirmed')!r})",
                )
            cohort_raw = d.get("donor_clinical_cohort")
            if type(cohort_raw) is not str or cohort_raw != _SHIELD_REQUIRED_DONOR_CLINICAL_COHORT:
                donor_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{did_c}]: mandatory donor_clinical_cohort must equal "
                    f"{_SHIELD_REQUIRED_DONOR_CLINICAL_COHORT!r} (got {cohort_raw!r})",
                )
            prequal_raw = d.get("t1d_prequalification_ref")
            if type(prequal_raw) is not str or not prequal_raw or prequal_raw != prequal_raw.strip():
                donor_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{did_c}]: mandatory t1d_prequalification_ref must be a non-empty unpadded string "
                    f"(got {prequal_raw!r})",
                )
            if _SHIELD_FORBIDDEN_NON_T1D_DONOR_RE.search(did_c):
                donor_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{did_c}]: contradictory non-T1D donor_id rejected fail-closed regardless of boolean flags",
                )
            if type(prequal_raw) is str and _SHIELD_FORBIDDEN_NON_T1D_DONOR_RE.search(prequal_raw):
                donor_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{did_c}]: contradictory non-T1D t1d_prequalification_ref={prequal_raw!r} rejected fail-closed",
                )

            raw_assay_run = d.get("assay_run_id")
            assay_run_c: str | None = None
            if (
                type(raw_assay_run) is not str
                or not raw_assay_run
                or raw_assay_run != raw_assay_run.strip()
                or not _SHIELD_STRICT_ID_RE.match(raw_assay_run)
            ):
                donor_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{did_c}]: mandatory assay_run_id must be a non-empty unpadded ID matching "
                    f"{_SHIELD_STRICT_ID_RE.pattern} (got {raw_assay_run!r})",
                )
            else:
                assay_run_c = raw_assay_run

            tmp_ref_d: set[str] = set()
            tmp_ck1_d: set[str] = set()
            tmp_ck2_d: set[str] = set()
            b_err = _shield_validate_batch_ids(
                d.get("expression_batch_ids"),
                f"donor[{did_c}]",
                passing_batch_constructs,
                tmp_ref_d,
                require_cocktail_both_leads=True,
                role_comp1_batches=tmp_ck1_d,
                role_comp2_batches=tmp_ck2_d,
            )
            raw_mix_id = d.get("cocktail_mixture_id")
            if b_err is not None:
                donor_valid = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", b_err)
            if (
                type(raw_mix_id) is not str
                or not raw_mix_id
                or raw_mix_id != raw_mix_id.strip()
                or not _SHIELD_STRICT_ID_RE.match(raw_mix_id)
            ):
                donor_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{did_c}]: missing or invalid mandatory cocktail_mixture_id referencing a passing "
                    f"physical mixture in sec_mals_dls_monomer_coformulation.qualified_coformulation_mixtures "
                    f"(got {raw_mix_id!r}); excluded from biological adjudication and batch-linkage credit",
                )
            elif not sec_cocktail_qualified or raw_mix_id not in qualified_passing_mixtures:
                donor_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{did_c}]: excluded from biological adjudication and batch-linkage credit because "
                    f"cocktail_mixture_id={raw_mix_id!r} lacks a passing physical co-formulation SEC-MALS/DLS "
                    f"qualification record (qualified_mixtures={sorted(qualified_passing_mixtures.keys())})",
                )
            elif b_err is None:
                mix_c1_bid, mix_c2_bid = qualified_passing_mixtures[raw_mix_id]
                expected_mix_batches = {mix_c1_bid, mix_c2_bid}
                if (
                    tmp_ref_d != expected_mix_batches
                    or mix_c1_bid not in tmp_ck1_d
                    or mix_c2_bid not in tmp_ck2_d
                ):
                    donor_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"donor[{did_c}]: excluded from biological adjudication and batch-linkage credit because "
                        f"cocktail expression_batch_ids={sorted(tmp_ref_d)} do not match the exact physical "
                        f"co-formulation mixture {raw_mix_id!r} component lot pair "
                        f"(comp1={mix_c1_bid!r}, comp2={mix_c2_bid!r}); crossed or unqualified lot combination rejected",
                    )

            has_hla = "hla_genotype" in d and d["hla_genotype"] is not None
            has_hla_alias = "hla_dq_genotype" in d and d["hla_dq_genotype"] is not None
            if has_hla and has_hla_alias and str(d["hla_genotype"]).strip() != str(d["hla_dq_genotype"]).strip():
                donor_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{did_c}]: hla_genotype={d['hla_genotype']!r} disagrees with hla_dq_genotype={d['hla_dq_genotype']!r}",
                )
            raw_hla = d["hla_genotype"] if has_hla else d.get("hla_dq_genotype")
            _, hla_err = _shield_parse_qualifying_hla_genotype(raw_hla, f"donor[{did_c}]")
            if hla_err is not None:
                donor_valid = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", hla_err)

            # R09 B3 + R10 B5 + R11 M1: Enforce suppression assay acceptance range [-1000.0, 100.0]% (100% blockade down to -1000% = 11x enhancement);
            # out-of-range values (< -1000.0 or > 100.0, e.g. -1e200) fail closed to HOLD_INVALID_OR_MISSING_INPUT without OverflowError,
            # while valid negative enhancement values in [-1000.0, 0.0) route to the anti-enhancement safety guard (min >= 0.0%) -> HOLD.
            sup_v, sup_err = _shield_check_num(
                d.get("suppression_pct"),
                f"donor[{did_c}].suppression_pct",
                lo=_SHIELD_SUPPRESSION_ASSAY_ACCEPTANCE_MIN_PCT,
                hi=_SHIELD_SUPPRESSION_ASSAY_ACCEPTANCE_MAX_PCT,
            )
            if sup_err is not None or sup_v is None:
                donor_valid = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", sup_err or f"Invalid donor[{did_c}].suppression_pct")

            # GY-018-compliant denominator verification (EXACT deff == 1.0 with zero tolerance & n_eff == raw_n >= 60)
            has_raw_u = "raw_independent_units_n" in d and d["raw_independent_units_n"] is not None
            has_raw_alias = "cytotoxicity_n_raw_units" in d and d["cytotoxicity_n_raw_units"] is not None
            if has_raw_u and has_raw_alias and d["raw_independent_units_n"] != d["cytotoxicity_n_raw_units"]:
                donor_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{did_c}]: raw_independent_units_n disagrees with cytotoxicity_n_raw_units",
                )
            raw_units_in = d["raw_independent_units_n"] if has_raw_u else d.get("cytotoxicity_n_raw_units")
            raw_units_n, raw_u_err = _shield_check_strict_int(
                raw_units_in, f"donor[{did_c}].raw_independent_units_n", min_val=1
            )
            if raw_u_err is not None:
                donor_valid = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", raw_u_err)

            deff_v, deff_err = _shield_check_exact_deff(d.get("design_effect_deff"), f"donor[{did_c}].design_effect_deff")
            if deff_err is not None or deff_v is None:
                donor_valid = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", deff_err or f"Invalid donor[{did_c}].design_effect_deff")

            indep_model = d.get("cytotoxicity_independence_model")
            if type(indep_model) is not str or indep_model != _SHIELD_CYTO_INDEPENDENCE_MODEL:
                donor_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{did_c}]: cytotoxicity_independence_model must be {_SHIELD_CYTO_INDEPENDENCE_MODEL!r} (got {indep_model!r})",
                )

            # R09 M1 + R10 B3 + R12 0037-B3: Mandatory authorization-grade strict closed-schema GY-018 independence
            # evidence record bound 1:1 to canonical allowlisted unit/control tokens (ZERO free-text prose accepted!)
            pd_n: int | None = None
            gy018_just = d.get("gy018_independence_justification")
            if not isinstance(gy018_just, dict):
                donor_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{did_c}]: missing mandatory authorization-grade gy018_independence_justification object "
                    f"(requires independent_unit_class, within_donor_units_physically_independent=True, "
                    f"clustering_controls_present_and_verified=True, shared_well_technical_reads_excluded=True, "
                    f"independence_evidence_record_id, independent_experimental_unit, predeclared_per_donor_unit_count_n, clustering_controls)",
                )
            else:
                extra_gy_keys = sorted(set(gy018_just.keys()) - _allowed_gy018_keys)
                if extra_gy_keys:
                    donor_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"donor[{did_c}].gy018_independence_justification contains unexpected/free-text keys "
                        f"{extra_gy_keys}; strict closed typed schema required",
                    )
                unit_cls = gy018_just.get("independent_unit_class")
                unit_cls_valid = type(unit_cls) is str and unit_cls in _SHIELD_ALLOWED_GY018_UNIT_CLASSES
                if not unit_cls_valid:
                    donor_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"donor[{did_c}].gy018_independence_justification.independent_unit_class must be in "
                        f"{sorted(_SHIELD_ALLOWED_GY018_UNIT_CLASSES)} (got {unit_cls!r})",
                    )
                for bkey in (
                    "within_donor_units_physically_independent",
                    "clustering_controls_present_and_verified",
                    "shared_well_technical_reads_excluded",
                ):
                    if gy018_just.get(bkey) is not True:
                        donor_valid = False
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"donor[{did_c}].gy018_independence_justification.{bkey} must be literal boolean True "
                            f"(got {gy018_just.get(bkey)!r})",
                        )
                ev_rec_id = gy018_just.get("independence_evidence_record_id")
                if (
                    type(ev_rec_id) is not str
                    or not ev_rec_id
                    or ev_rec_id != ev_rec_id.strip()
                    or not _SHIELD_EVIDENCE_REF_RE.match(ev_rec_id)
                ):
                    donor_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"donor[{did_c}].gy018_independence_justification.independence_evidence_record_id must be "
                        f"an unpadded audit ref matching {_SHIELD_EVIDENCE_REF_RE.pattern} (got {ev_rec_id!r})",
                    )
                iu_txt = gy018_just.get("independent_experimental_unit")
                allowed_units_for_cls = (
                    _SHIELD_ALLOWED_INDEPENDENT_EXPERIMENTAL_UNITS[unit_cls]
                    if unit_cls_valid and type(unit_cls) is str
                    else frozenset()
                )
                if type(iu_txt) is not str or iu_txt not in allowed_units_for_cls:
                    donor_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"donor[{did_c}].gy018_independence_justification.independent_experimental_unit must be a "
                        f"canonical allowlisted token compatible with independent_unit_class={unit_cls!r} "
                        f"(free-text prose rejected fail-closed; got {iu_txt!r})",
                    )
                cc_txt = gy018_just.get("clustering_controls")
                allowed_ctrls_for_cls = (
                    _SHIELD_ALLOWED_CLUSTERING_CONTROLS[unit_cls]
                    if unit_cls_valid and type(unit_cls) is str
                    else frozenset()
                )
                if type(cc_txt) is not str or cc_txt not in allowed_ctrls_for_cls:
                    donor_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"donor[{did_c}].gy018_independence_justification.clustering_controls must be a "
                        f"canonical allowlisted token compatible with independent_unit_class={unit_cls!r} "
                        f"(free-text prose rejected fail-closed; got {cc_txt!r})",
                    )
                pd_n, pd_n_err = _shield_check_strict_int(
                    gy018_just.get("predeclared_per_donor_unit_count_n"),
                    f"donor[{did_c}].gy018_independence_justification.predeclared_per_donor_unit_count_n",
                    min_val=_SHIELD_MIN_CYTO_N_EFF_PER_DONOR,
                )
                if pd_n_err is not None:
                    donor_valid = False
                    _escalate("HOLD_INVALID_OR_MISSING_INPUT", pd_n_err)
                elif raw_units_n is not None and pd_n != raw_units_n:
                    donor_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"donor[{did_c}]: gy018_independence_justification.predeclared_per_donor_unit_count_n={pd_n} "
                        f"disagrees with raw_independent_units_n={raw_units_n}",
                    )

            n_eff_raw, neff_pos_err = _shield_check_strict_int(d.get("apc_cytotoxicity_n_eff"), f"donor[{did_c}].apc_cytotoxicity_n_eff", min_val=1)
            k_obs_raw, kobs_err = _shield_check_strict_int(d.get("apc_cytotoxicity_k_obs"), f"donor[{did_c}].apc_cytotoxicity_k_obs", min_val=0)
            if neff_pos_err is not None:
                donor_valid = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", neff_pos_err)
            if kobs_err is not None:
                donor_valid = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", kobs_err)

            if n_eff_raw is not None and raw_units_n is not None and n_eff_raw != raw_units_n:
                donor_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{did_c}]: GY-018 denominator mismatch — apc_cytotoxicity_n_eff={n_eff_raw} != raw_independent_units_n={raw_units_n}",
                )

            if n_eff_raw is not None and n_eff_raw < _SHIELD_MIN_CYTO_N_EFF_PER_DONOR:
                donor_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{did_c}]: apc_cytotoxicity_n_eff={n_eff_raw} < mandatory minimum {_SHIELD_MIN_CYTO_N_EFF_PER_DONOR}",
                )

            if n_eff_raw is not None and k_obs_raw is not None and k_obs_raw > n_eff_raw:
                donor_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{did_c}]: apc_cytotoxicity_k_obs={k_obs_raw} > apc_cytotoxicity_n_eff={n_eff_raw}",
                )

            # R16 Shared Blocker #3 + Pre-Dedup Raw-Row Reconciliation (Pass 1c): Exclude any donor flagged
            # for fixed-horizon sample-size mismatch across raw submitted rows from biological adjudication!
            if roster_verified and did_c in roster_sample_size_plan_mismatched_donors:
                donor_valid = False

            # Gate ALL binomial Clopper-Pearson & caller CI calculations strictly on valid eligible rostered T1D donors!
            if donor_valid and n_eff_raw is not None and k_obs_raw is not None and sup_v is not None:
                rate_pct = 100.0 * k_obs_raw / float(n_eff_raw)
                cp_l95, cp_u95 = _clopper_pearson_one_sided_95_pct(k_obs_raw, n_eff_raw, alpha=0.05)

                # Two-sided validation of optional caller-supplied per-donor cytotoxicity intervals (<= 0.05 pp tolerance)
                rep_obs_raw = d.get("apc_cytotoxicity_observed_pct")
                rep_l95_raw = d.get("apc_cytotoxicity_l95_pct")
                rep_u95_raw = d.get("apc_cytotoxicity_u95_pct")
                rep_l95: float | None = None
                rep_u95: float | None = None
                if rep_obs_raw is not None:
                    rep_obs, ro_err = _shield_check_num(rep_obs_raw, f"donor[{did_c}].apc_cytotoxicity_observed_pct", lo=0.0, hi=100.0)
                    if ro_err is not None:
                        donor_valid = False
                        _escalate("HOLD_INVALID_OR_MISSING_INPUT", ro_err)
                    elif rep_obs is not None and abs(rep_obs - rate_pct) > _SHIELD_CYTO_CI_TOL_PP:
                        donor_valid = False
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"donor[{did_c}]: reported observed_pct={rep_obs:.3f}% disagrees with raw counts {k_obs_raw}/{n_eff_raw} ({rate_pct:.3f}%)",
                        )
                if rep_l95_raw is not None:
                    rep_l95, rl_err = _shield_check_num(rep_l95_raw, f"donor[{did_c}].apc_cytotoxicity_l95_pct", lo=0.0, hi=100.0)
                    if rl_err is not None:
                        donor_valid = False
                        _escalate("HOLD_INVALID_OR_MISSING_INPUT", rl_err)
                if rep_u95_raw is not None:
                    rep_u95, ru_err = _shield_check_num(rep_u95_raw, f"donor[{did_c}].apc_cytotoxicity_u95_pct", lo=0.0, hi=100.0)
                    if ru_err is not None:
                        donor_valid = False
                        _escalate("HOLD_INVALID_OR_MISSING_INPUT", ru_err)
                if rep_l95 is not None and rep_u95 is not None and rep_l95 > rep_u95:
                    donor_valid = False
                    _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"donor[{did_c}]: inverted cytotoxicity CI L95={rep_l95} > U95={rep_u95}")
                if rep_l95 is not None:
                    if k_obs_raw == 0 and rep_l95 > 0.0:
                        donor_valid = False
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"donor[{did_c}]: inconsistent cytotoxicity CI (k_obs=0 / 0% observed with positive L95={rep_l95:.3f}%)",
                        )
                    elif rep_l95 > rate_pct + 1e-6 or abs(rep_l95 - cp_l95) > _SHIELD_CYTO_CI_TOL_PP:
                        donor_valid = False
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"donor[{did_c}]: reported L95={rep_l95:.3f}% disagrees with exact Clopper-Pearson L95={cp_l95:.3f}% (two-sided tol {_SHIELD_CYTO_CI_TOL_PP:.2f} pp)",
                        )
                if rep_u95 is not None and (rep_u95 + 1e-6 < rate_pct or abs(rep_u95 - cp_u95) > _SHIELD_CYTO_CI_TOL_PP):
                    donor_valid = False
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"donor[{did_c}]: reported U95={rep_u95:.3f}% disagrees with exact Clopper-Pearson U95={cp_u95:.3f}% (two-sided tol {_SHIELD_CYTO_CI_TOL_PP:.2f} pp)",
                    )

                if donor_valid and assay_run_c is not None:
                    referenced_batches.update(tmp_ref_d)
                    cocktail_comp1_batches.update(tmp_ck1_d)
                    cocktail_comp2_batches.update(tmp_ck2_d)
                    valid_donor_sup_vals.append(sup_v)
                    valid_donor_sup_by_id[did_c] = sup_v
                    valid_donor_cyto_rates.append(rate_pct)
                    valid_donor_cp_l95s_unadj.append(cp_l95)
                    valid_donor_cp_u95s.append(cp_u95)
                    valid_donor_k_list.append(k_obs_raw)
                    valid_donor_neff_list.append(n_eff_raw)
                else:
                    invalid_donors_excluded.append(did_c)
            else:
                invalid_donors_excluded.append(did_c)

    # 100% pre-registered donor roster accounting on ALL raw submitted donor IDs
    missing_roster_donor_ids: list[str] = []
    if roster_verified:
        accounted_roster_ids = (raw_submitted_donor_ids & roster_set) | (valid_excluded_donor_ids & roster_set)
        missing_roster_donor_ids = sorted(roster_set - accounted_roster_ids)
        if missing_roster_donor_ids:
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"Incomplete pre-registered donor roster reconciliation: {len(missing_roster_donor_ids)} of "
                f"{len(roster_set)} rostered donors omitted without submitted or pre-assay-excluded records "
                f"({missing_roster_donor_ids}); authorization-grade SHIELD verdict blocked",
            )

    expected_submitted_roster_ids = (roster_set - valid_excluded_donor_ids) if roster_verified else frozenset()
    donor_topology_complete_for_suppression = bool(
        roster_verified
        and len(donors_with_invalid_topology & roster_set) == 0
        and all(
            did_k in topology_donor_batches
            and len(topology_donor_batches[did_k]) >= 1
            and did_k in topology_donor_runs
            and len(topology_donor_runs[did_k]) >= 1
            for did_k in expected_submitted_roster_ids
        )
    )
    if roster_verified and not donor_topology_complete_for_suppression:
        _escalate(
            "HOLD_INVALID_OR_MISSING_INPUT",
            f"Incomplete or corrupted donor batch/run dependency topology across submitted rostered donors "
            f"(invalid_topology_donors={sorted(donors_with_invalid_topology & roster_set)}); "
            f"cluster-level suppression inference withheld fail-closed while preserving independent SPR and "
            f"fixed-roster Bonferroni cytotoxicity FAIL",
        )

    bonferroni_family_denominator_n: int | None = len(roster_donor_ids) if roster_verified else None
    authorization_grade_fwer_bound_valid = bool(
        roster_verified
        and roster_single_look_locked
        and roster_planned_looks_val == 1
        and len(roster_sample_size_plan_mismatched_donors) == 0
        and not top_level_plan_conflict
        and not conflicting_donor_lists
        and not malformed_donor_rows_present
        and excluded_records_valid
        and len(excluded_overlap_donors) == 0
        and len(unrostered_submitted_donors) == 0
        and len(missing_roster_donor_ids) == 0
        and bonferroni_family_denominator_n is not None
        and bonferroni_family_denominator_n >= _SHIELD_MIN_DONORS_N
    )
    authorization_grade_suppression_inference_valid = bool(
        authorization_grade_fwer_bound_valid
        and donor_sampling_design_valid
        and suppression_inference_authorized_by_sampling_design
        and donor_topology_complete_for_suppression
    )
    full_roster_cyto_measured_complete = bool(
        roster_verified
        and bonferroni_family_denominator_n is not None
        and len(valid_excluded_donor_ids) == 0
        and len(valid_donor_cyto_rates) == bonferroni_family_denominator_n
    )

    derived_summary["preregistered_donor_roster_verified"] = roster_verified
    derived_summary["preregistered_roster_id"] = roster_id_val
    derived_summary["preregistered_roster_timestamp_utc"] = roster_ts_val
    derived_summary["preregistered_roster_sha256"] = roster_sha256_val
    derived_summary["preregistered_single_look_fixed_horizon_plan_locked"] = roster_single_look_locked
    derived_summary["preregistered_planned_analysis_looks"] = roster_planned_looks_val
    derived_summary["preregistered_per_donor_unit_counts"] = (
        dict(roster_predeclared_n_by_donor) if roster_verified else None
    )
    derived_summary["roster_sample_size_plan_mismatched_donors"] = sorted(
        roster_sample_size_plan_mismatched_donors
    )
    derived_summary["planned_t1d_donor_family_n"] = roster_planned_n
    derived_summary["roster_donor_count_n"] = bonferroni_family_denominator_n
    derived_summary["submitted_donor_records_n"] = submitted_donor_records_n
    derived_summary["valid_donor_records_n"] = len(valid_donor_cyto_rates)
    derived_summary["valid_donors_count"] = len(valid_donor_cyto_rates)
    derived_summary["pre_assay_excluded_donor_ids"] = sorted(valid_excluded_donor_ids)
    derived_summary["missing_roster_donor_ids"] = missing_roster_donor_ids
    derived_summary["unrostered_submitted_donor_ids"] = sorted(unrostered_submitted_donors)
    derived_summary["donor_topology_complete_for_suppression"] = donor_topology_complete_for_suppression
    derived_summary["donors_with_invalid_topology"] = sorted(donors_with_invalid_topology)
    derived_summary["bonferroni_family_denominator_n"] = bonferroni_family_denominator_n
    derived_summary["authorization_grade_fwer_bound_valid"] = authorization_grade_fwer_bound_valid
    derived_summary["donor_sampling_design_valid"] = donor_sampling_design_valid
    derived_summary["donor_sampling_design_class"] = sampling_design_class_val
    derived_summary["donor_sampling_protocol_ref"] = sampling_protocol_ref_val
    derived_summary["suppression_inference_authorized_by_sampling_design"] = suppression_inference_authorized_by_sampling_design
    derived_summary["authorization_grade_suppression_inference_valid"] = authorization_grade_suppression_inference_valid
    derived_summary["external_preregistration_custody_required"] = True
    derived_summary["fwer_external_custody_condition"] = _SHIELD_FWER_EXTERNAL_CUSTODY_CONDITION
    derived_summary["suppression_statistical_boundary_note"] = _SHIELD_SUPPRESSION_STATISTICAL_BOUNDARY_NOTE
    derived_summary["local_json_replay_scope_note"] = _SHIELD_LOCAL_JSON_REPLAY_SCOPE_NOTE
    derived_summary["cytotoxicity_full_roster_measured_complete"] = full_roster_cyto_measured_complete
    derived_summary["cytotoxicity_pass_requires_100pct_rostered_donors_measured"] = True
    derived_summary["invalid_donors_excluded_from_confidence_bounds"] = invalid_donors_excluded
    derived_summary["conflicted_duplicate_keys"] = {
        "expression_batches": sorted(conflicted_batch_ids),
        "on_target_analytes": sorted(conflicted_on_target),
        "off_target_controls": sorted(conflicted_off_target),
        "comp2_comparators": sorted(conflicted_comps),
        "donors": sorted(conflicted_donors),
    }

    # Suppression & cytotoxicity inference (strictly bound to immutable fixed N_roster & disjoint batch/run clusters!)
    derived_summary["suppression_estimand"] = _SHIELD_SUPPRESSION_ESTIMAND
    derived_summary["suppression_inference_method"] = _SHIELD_SUPPRESSION_INFERENCE_METHOD
    derived_summary["suppression_student_t_authorizing"] = False
    derived_summary["suppression_responder_u95_scope"] = (
        "DESCRIPTIVE_DIAGNOSTIC_ONLY_NO_MARGINAL_UPPER_COVERAGE_GUARANTEE"
    )
    derived_summary["suppression_confirmatory_min_donors_n"] = _SHIELD_MIN_CONFIRMATORY_DONORS_N
    derived_summary["suppression_assay_acceptance_range_pct"] = [
        _SHIELD_SUPPRESSION_ASSAY_ACCEPTANCE_MIN_PCT,
        _SHIELD_SUPPRESSION_ASSAY_ACCEPTANCE_MAX_PCT,
    ]
    derived_summary["cytotoxicity_estimand"] = _SHIELD_CYTO_ESTIMAND
    derived_summary["simultaneous_fwer_alpha"] = _SHIELD_CYTO_SIMULTANEOUS_FWER_ALPHA
    derived_summary["fwer_bound_scope"] = (
        "FIXED_ROSTER_DONOR_CYTOTOXICITY_FAMILY_ONLY_NOT_UNION_WITH_SPR_OR_SUPPRESSION"
    )
    derived_summary["cohort_t_lower_authorizing"] = False

    if isinstance(donors_raw, list) and len(donors_raw) > 0:
        if len(seen_donors) < _SHIELD_MIN_DONORS_N:
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"Under-replicated functional donor cohort: {len(seen_donors)} < {_SHIELD_MIN_DONORS_N} distinct donors",
            )
        elif len(valid_donor_cyto_rates) < _SHIELD_MIN_DONORS_N:
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"Insufficient valid qualifying T1D donors for cohort evaluation after gating invalid/ineligible donors: "
                f"{len(valid_donor_cyto_rates)} < {_SHIELD_MIN_DONORS_N} (excluded={invalid_donors_excluded})",
            )

        # Descriptive suppression summaries (overflow-immune signed non-authorizing Student-t diagnostic + quantiles; R12 0039-M1)
        sup_mean_v: float | None = None
        sup_min_v: float | None = None
        if len(valid_donor_sup_vals) >= 1:
            sup_mean_v, sup_med_v, sup_min_v, sup_iqr_v = _shield_descriptive_quantiles(valid_donor_sup_vals)
            derived_summary["suppression_mean_pct"] = round(sup_mean_v, 6)
            derived_summary["suppression_median_pct"] = round(sup_med_v, 6)
            derived_summary["suppression_min_pct"] = round(sup_min_v, 6)
            derived_summary["suppression_iqr_pct"] = round(sup_iqr_v, 6)
            derived_summary["suppression_anti_enhancement_min_ge_0_passed"] = bool(sup_min_v >= 0.0)
        if len(valid_donor_sup_vals) >= _SHIELD_MIN_DONORS_N:
            _, sup_l95_t_diag, sup_u95_t_diag = _shield_student_t_ci_pct(
                valid_donor_sup_vals,
                lo_bound=_SHIELD_SUPPRESSION_ASSAY_ACCEPTANCE_MIN_PCT,
                hi_bound=_SHIELD_SUPPRESSION_ASSAY_ACCEPTANCE_MAX_PCT,
            )
            derived_summary["suppression_l95_t_diagnostic_only_pct"] = round(sup_l95_t_diag, 6)
            derived_summary["suppression_u95_t_diagnostic_only_pct"] = round(sup_u95_t_diag, 6)

        # Cluster-conservative distribution-free exact Clopper-Pearson responder-proportion suppression adjudication
        # over fixed N_roster AND expression-batch, assay-run, and joint (batch U run) connected components
        # (R10 B1/B2 + R12 0037-B2: topology edges come from topology_donor_batches/topology_donor_runs so
        # disqualifying an unrelated per-donor summary/CI NEVER splits a connected cluster into singletons!)
        if roster_verified and bonferroni_family_denominator_n is not None:
            n_roster = bonferroni_family_denominator_n
            k_ge_70 = sum(1 for v in valid_donor_sup_vals if v >= _SHIELD_SUPPRESSION_PASS_THRESHOLD_PCT)
            k_lt_40 = sum(1 for v in valid_donor_sup_vals if v < _SHIELD_SUPPRESSION_FAIL_THRESHOLD_PCT)
            sup_l95_cp_donor_pct, sup_u95_cp_donor_pct = _clopper_pearson_one_sided_95_pct(k_ge_70, n_roster, alpha=0.05)
            sup_lt40_l95_cp_donor_pct, _ = _clopper_pearson_one_sided_95_pct(k_lt_40, n_roster, alpha=0.05)

            batch_tokens = {did_k: {f"BATCH::{b}" for b in bs} for did_k, bs in topology_donor_batches.items()}
            run_tokens = {did_k: {f"RUN::{r}" for r in rs} for did_k, rs in topology_donor_runs.items()}
            joint_tokens = {
                did_k: batch_tokens.get(did_k, set()) | run_tokens.get(did_k, set())
                for did_k in roster_donor_ids
            }
            batch_clusters = _shield_connected_clusters(roster_donor_ids, batch_tokens)
            run_clusters = _shield_connected_clusters(roster_donor_ids, run_tokens)
            joint_clusters = _shield_connected_clusters(roster_donor_ids, joint_tokens)

            def _cluster_cp(clusters: list[list[str]]) -> tuple[int, int, int, float, float, float]:
                n_c = len(clusters)
                kc_ge70 = sum(
                    1
                    for comp in clusters
                    if all(
                        did_m in valid_donor_sup_by_id
                        and valid_donor_sup_by_id[did_m] >= _SHIELD_SUPPRESSION_PASS_THRESHOLD_PCT
                        for did_m in comp
                    )
                )
                kc_lt40 = sum(
                    1
                    for comp in clusters
                    if all(
                        did_m in valid_donor_sup_by_id
                        and valid_donor_sup_by_id[did_m] < _SHIELD_SUPPRESSION_FAIL_THRESHOLD_PCT
                        for did_m in comp
                    )
                )
                l_pass, u_pass = _clopper_pearson_one_sided_95_pct(kc_ge70, n_c, alpha=0.05)
                l_fail, _ = _clopper_pearson_one_sided_95_pct(kc_lt40, n_c, alpha=0.05)
                return n_c, kc_ge70, kc_lt40, l_pass, u_pass, l_fail

            n_batch_c, k_batch_ge70, k_batch_lt40, l95_batch_pass, u95_batch_pass, l95_batch_fail = _cluster_cp(batch_clusters)
            n_run_c, k_run_ge70, k_run_lt40, l95_run_pass, u95_run_pass, l95_run_fail = _cluster_cp(run_clusters)
            n_joint_c, k_joint_ge70, k_joint_lt40, l95_joint_pass, u95_joint_pass, l95_joint_fail = _cluster_cp(joint_clusters)

            eff_sup_l95_cp_pct = min(sup_l95_cp_donor_pct, l95_batch_pass, l95_run_pass, l95_joint_pass)
            eff_sup_u95_cp_pct = max(sup_u95_cp_donor_pct, u95_batch_pass, u95_run_pass, u95_joint_pass)
            eff_sup_lt40_l95_cp_pct = min(sup_lt40_l95_cp_donor_pct, l95_batch_fail, l95_run_fail, l95_joint_fail)

            derived_summary["suppression_responders_ge_70pct_k"] = k_ge_70
            derived_summary["suppression_nonresponders_lt_40pct_k"] = k_lt_40
            derived_summary["suppression_responder_denominator_n_roster"] = n_roster
            derived_summary["suppression_donor_level_l95_clopper_pearson_pct"] = round(sup_l95_cp_donor_pct, 6)
            derived_summary["suppression_donor_level_nonresponder_lt40_l95_clopper_pearson_pct"] = round(sup_lt40_l95_cp_donor_pct, 6)
            derived_summary["suppression_batch_clusters_n"] = n_batch_c
            derived_summary["suppression_batch_clusters_ge_70pct_k"] = k_batch_ge70
            derived_summary["suppression_batch_clusters_lt_40pct_k"] = k_batch_lt40
            derived_summary["suppression_batch_cluster_l95_clopper_pearson_pct"] = round(l95_batch_pass, 6)
            derived_summary["suppression_batch_cluster_nonresponder_lt40_l95_clopper_pearson_pct"] = round(l95_batch_fail, 6)
            derived_summary["suppression_run_clusters_n"] = n_run_c
            derived_summary["suppression_run_clusters_ge_70pct_k"] = k_run_ge70
            derived_summary["suppression_run_clusters_lt_40pct_k"] = k_run_lt40
            derived_summary["suppression_run_cluster_l95_clopper_pearson_pct"] = round(l95_run_pass, 6)
            derived_summary["suppression_run_cluster_nonresponder_lt40_l95_clopper_pearson_pct"] = round(l95_run_fail, 6)
            derived_summary["suppression_independent_joint_clusters_n"] = n_joint_c
            derived_summary["suppression_independent_joint_clusters_ge_70pct_k"] = k_joint_ge70
            derived_summary["suppression_independent_joint_clusters_lt_40pct_k"] = k_joint_lt40
            derived_summary["suppression_independent_joint_cluster_l95_clopper_pearson_pct"] = round(l95_joint_pass, 6)
            derived_summary["suppression_independent_joint_cluster_nonresponder_lt40_l95_clopper_pearson_pct"] = round(l95_joint_fail, 6)
            derived_summary["suppression_responder_l95_clopper_pearson_pct"] = round(eff_sup_l95_cp_pct, 6)
            derived_summary["suppression_responder_u95_clopper_pearson_pct"] = round(eff_sup_u95_cp_pct, 6)
            derived_summary["suppression_nonresponder_lt40_l95_clopper_pearson_pct"] = round(eff_sup_lt40_l95_cp_pct, 6)

            if authorization_grade_suppression_inference_valid:
                if eff_sup_lt40_l95_cp_pct > _SHIELD_SUPPRESSION_FAIL_L95_GT_PCT:
                    donor_based_bio_fail = True
                    _escalate(
                        "FAIL",
                        f"T-cell suppression cluster-conservative Clopper-Pearson non-responder (<40%) "
                        f"L95={eff_sup_lt40_l95_cp_pct:.3f}% > {_SHIELD_SUPPRESSION_FAIL_L95_GT_PCT:.1f}% FAIL bar "
                        f"(donors={k_lt_40}/{n_roster}, batch_clusters={k_batch_lt40}/{n_batch_c}, "
                        f"run_clusters={k_run_lt40}/{n_run_c}, joint_clusters={k_joint_lt40}/{n_joint_c})",
                    )
                else:
                    if sup_min_v is not None and sup_min_v < 0.0:
                        _escalate(
                            "HOLD",
                            f"T-cell suppression anti-enhancement safety guard triggered: min_donor_suppression={sup_min_v:.2f}% < 0.0% "
                            f"(no donor may exhibit T-cell enhancement)",
                        )
                    if n_roster < _SHIELD_MIN_CONFIRMATORY_DONORS_N:
                        _escalate(
                            "HOLD",
                            f"Exploratory/underpowered T-cell donor cohort (N_roster={n_roster} < {_SHIELD_MIN_CONFIRMATORY_DONORS_N}): "
                            f"exact Clopper-Pearson responder L95={eff_sup_l95_cp_pct:.3f}% < 70.0% confirmatory PASS bar "
                            f"({k_ge_70}/{n_roster} donors >= 70.0%; Student-t is strictly non-authorizing)",
                        )
                    elif n_joint_c < _SHIELD_MIN_CONFIRMATORY_DONORS_N:
                        _escalate(
                            "HOLD",
                            f"Clustered between-donor batch/run structure precludes confirmatory suppression PASS: "
                            f"N_roster={n_roster} collapses to N_batch_clusters={n_batch_c}, N_run_clusters={n_run_c}, "
                            f"N_joint_clusters={n_joint_c} (< {_SHIELD_MIN_CONFIRMATORY_DONORS_N} independent batch/run "
                            f"units required; effective cluster-conservative L95_CP={eff_sup_l95_cp_pct:.3f}% < 70.0%)",
                        )
                    elif eff_sup_l95_cp_pct < _SHIELD_SUPPRESSION_PASS_THRESHOLD_PCT:
                        _escalate(
                            "HOLD",
                            f"T-cell suppression cluster-conservative Clopper-Pearson responder L95={eff_sup_l95_cp_pct:.3f}% "
                            f"< 70.0% confirmatory PASS bar (donors={k_ge_70}/{n_roster}, batch_clusters={k_batch_ge70}/{n_batch_c}, "
                            f"run_clusters={k_run_ge70}/{n_run_c}, joint_clusters={k_joint_ge70}/{n_joint_c})",
                        )
                    if sup_mean_v is not None and sup_mean_v < _SHIELD_SUPPRESSION_PASS_THRESHOLD_PCT:
                        _escalate(
                            "HOLD",
                            f"T-cell suppression cohort mean={sup_mean_v:.2f}% < 70.0% PASS bar",
                        )
            elif donor_sampling_design_valid and not suppression_inference_authorized_by_sampling_design:
                if sup_min_v is not None and sup_min_v < 0.0:
                    _escalate(
                        "HOLD",
                        f"T-cell suppression anti-enhancement safety guard triggered: min_donor_suppression={sup_min_v:.2f}% < 0.0% "
                        f"(no donor may exhibit T-cell enhancement)",
                    )
                _escalate(
                    "HOLD",
                    f"STRATIFIED_COHORT_REQUIRES_TARGET_WEIGHTED_SUPPRESSION_ESTIMATOR: "
                    f"sampling_design_class={sampling_design_class_val!r} is non-authorizing for unweighted "
                    f"Clopper-Pearson population-suppression PASS or unweighted population-rate suppression FAIL "
                    f"(only {sorted(_SHIELD_AUTHORIZING_DONOR_SAMPLING_DESIGNS)} authorizes unweighted "
                    f"population-proportion suppression inference; independent SPR FAIL and "
                    f"fixed-roster within-donor Bonferroni cytotoxicity FAIL remain active)",
                )

        # R09 B2: Fixed pre-registered roster Bonferroni denominator N_roster NEVER shrinks under exclusions,
        # and NEVER authorizes biological cytotoxicity FAIL unless authorization_grade_fwer_bound_valid is True!
        alpha_donor: float | None = (
            _SHIELD_CYTO_DONOR_FAMILY_ALPHA_ONE_SIDED / float(bonferroni_family_denominator_n)
            if bonferroni_family_denominator_n is not None
            else None
        )
        derived_summary["per_donor_bonferroni_alpha_one_sided"] = round(alpha_donor, 10) if alpha_donor is not None else None

        if len(valid_donor_cyto_rates) >= 1:
            unadjusted_donor_l95_diag = max(valid_donor_cp_l95s_unadj)
            worst_cp_u95 = max(valid_donor_cp_u95s)
            total_k = sum(valid_donor_k_list)
            total_neff = sum(valid_donor_neff_list)
            max_obs_rate = max(valid_donor_cyto_rates)

            worst_donor_bonf_lower: float | None = None
            if alpha_donor is not None:
                bonf_donor_lowers = [
                    _clopper_pearson_one_sided_95_pct(k_i, n_i, alpha=alpha_donor)[0]
                    for k_i, n_i in zip(valid_donor_k_list, valid_donor_neff_list)
                ]
                worst_donor_bonf_lower = max(bonf_donor_lowers)

            derived_summary["cytotoxicity_total_k_obs"] = total_k
            derived_summary["cytotoxicity_total_n_eff"] = total_neff
            derived_summary["cytotoxicity_min_n_eff_per_donor"] = min(valid_donor_neff_list)
            derived_summary["cytotoxicity_max_donor_observed_pct"] = round(max_obs_rate, 6)
            derived_summary["simultaneous_worst_donor_bonferroni_lower_pct"] = (
                round(worst_donor_bonf_lower, 6) if worst_donor_bonf_lower is not None else None
            )
            derived_summary["cytotoxicity_calibrated_simultaneous_lower_pct"] = (
                round(worst_donor_bonf_lower, 6) if worst_donor_bonf_lower is not None else None
            )
            derived_summary["unadjusted_donor_l95_diagnostic_only"] = round(unadjusted_donor_l95_diag, 6)

            cohort_t_lower_diag: float | None = None
            cyto_mean = sum(valid_donor_cyto_rates) / float(len(valid_donor_cyto_rates))
            eff_u95 = worst_cp_u95
            derived_summary["cytotoxicity_mean_observed_pct"] = round(cyto_mean, 6)

            if len(valid_donor_cyto_rates) >= _SHIELD_MIN_DONORS_N:
                # Non-authorizing descriptive cohort Student-t summary ONLY (NEVER drives biological FAIL).
                cyto_mean, cohort_t_lower_diag, cohort_u975 = _shield_student_t_ci_pct(
                    valid_donor_cyto_rates,
                    lo_bound=0.0,
                    hi_bound=100.0,
                )
                eff_u95 = max(cohort_u975, worst_cp_u95)
                derived_summary["cytotoxicity_mean_observed_pct"] = round(cyto_mean, 6)
                derived_summary["cohort_mean_cytotoxicity_t_lower_diagnostic_only_pct"] = round(cohort_t_lower_diag, 6)
                derived_summary["cytotoxicity_conservative_u95_pct"] = round(eff_u95, 6)
                derived_summary["cytotoxicity_full_roster_u95_pct"] = (
                    round(eff_u95, 6) if full_roster_cyto_measured_complete else None
                )

                if total_neff < _SHIELD_MIN_CYTO_N_EFF_PER_DONOR:
                    _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"Total cytotoxicity n_eff={total_neff} < {_SHIELD_MIN_CYTO_N_EFF_PER_DONOR}")

                # Two-sided validation of optional top-level reported cytotoxicity summary (<= 0.05 pp tolerance)
                top_obs = observation.get("cytotoxicity_observed_pct")
                top_l95 = observation.get("cytotoxicity_l95_pct")
                top_u95 = observation.get("cytotoxicity_u95_pct")
                if top_obs is not None or top_l95 is not None or top_u95 is not None:
                    t_o, t_o_err = _shield_check_num(top_obs, "cytotoxicity_observed_pct", lo=0.0, hi=100.0) if top_obs is not None else (None, None)
                    t_l, t_l_err = _shield_check_num(top_l95, "cytotoxicity_l95_pct", lo=0.0, hi=100.0) if top_l95 is not None else (None, None)
                    t_u, t_u_err = _shield_check_num(top_u95, "cytotoxicity_u95_pct", lo=0.0, hi=100.0) if top_u95 is not None else (None, None)
                    for err in (t_o_err, t_l_err, t_u_err):
                        if err is not None:
                            _escalate("HOLD_INVALID_OR_MISSING_INPUT", err)
                    if t_l is not None and t_u is not None and t_l > t_u:
                        _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"Top-level inverted cytotoxicity CI L={t_l} > U95={t_u}")
                    if t_o is not None and t_l is not None and t_o == 0.0 and t_l > 0.0:
                        _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"Top-level inconsistent cytotoxicity CI: observed=0.0% with L={t_l:.3f}%")
                    if t_o is not None and abs(t_o - cyto_mean) > _SHIELD_CYTO_CI_TOL_PP:
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"Top-level cytotoxicity observed_pct={t_o:.3f}% disagrees with recomputed cohort mean={cyto_mean:.3f}%",
                        )
                    if t_l is not None and total_k == 0 and t_l > 0.0:
                        _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"Top-level cytotoxicity lower bound={t_l:.3f}% contradicts 0 observed events across donors")
                    if t_l is not None and worst_donor_bonf_lower is not None and abs(t_l - worst_donor_bonf_lower) > _SHIELD_CYTO_CI_TOL_PP:
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"Top-level cytotoxicity lower bound={t_l:.3f}% disagrees with fixed-roster Bonferroni lower bound={worst_donor_bonf_lower:.3f}% (two-sided tol {_SHIELD_CYTO_CI_TOL_PP:.2f} pp)",
                        )
                    if t_u is not None and abs(t_u - eff_u95) > _SHIELD_CYTO_CI_TOL_PP:
                        _escalate(
                            "HOLD_INVALID_OR_MISSING_INPUT",
                            f"Top-level cytotoxicity U95={t_u:.3f}% disagrees with recomputed conservative U95={eff_u95:.3f}% (two-sided tol {_SHIELD_CYTO_CI_TOL_PP:.2f} pp)",
                        )

            if authorization_grade_fwer_bound_valid and worst_donor_bonf_lower is not None and worst_donor_bonf_lower > 5.0:
                donor_based_bio_fail = True
                diag_txt = f"{cohort_t_lower_diag:.3f}%" if cohort_t_lower_diag is not None else "n/a(<3 valid)"
                _escalate(
                    "FAIL",
                    f"Off-target APC cytotoxicity exact fixed-roster Bonferroni lower bound (H0_all: max_i p_i <= 5.0%, FWER<=0.05) "
                    f"exceeds 5.0% FAIL bar: simultaneous_worst_donor_bonf_lower={worst_donor_bonf_lower:.3f}% "
                    f"(N_roster={bonferroni_family_denominator_n}, N_valid={len(valid_donor_cyto_rates)}, "
                    f"alpha_donor={alpha_donor:.6f}; diagnostic_only_cohort_t_lower={diag_txt})",
                )
            elif authorization_grade_fwer_bound_valid and len(valid_donor_cyto_rates) >= _SHIELD_MIN_DONORS_N:
                if total_k > 0:
                    if eff_u95 > 5.0:
                        _escalate(
                            "HOLD_CYTOTOXICITY_U95_EXCEEDS_5PCT",
                            f"Positive observed off-target APC cytotoxicity (max_donor={max_obs_rate:.3f}%, mean={cyto_mean:.3f}%) "
                            f"with calibrated simultaneous lower={worst_donor_bonf_lower:.3f}% <= 5.0% AND conservative U95={eff_u95:.3f}% > 5.0%",
                        )
                    else:
                        _escalate(
                            "HOLD_OBSERVED_NONZERO_CYTOTOXICITY",
                            f"Positive observed off-target APC cytotoxicity (max_donor={max_obs_rate:.3f}%, mean={cyto_mean:.3f}%) "
                            f"while conservative U95={eff_u95:.3f}% <= 5.0%; cannot PASS",
                        )
                elif eff_u95 > 5.0:
                    _escalate(
                        "HOLD",
                        f"Underpowered 0% cytotoxicity: conservative U95={eff_u95:.3f}% > 5.0% PASS ceiling",
                    )
            if authorization_grade_fwer_bound_valid and not full_roster_cyto_measured_complete and len(valid_excluded_donor_ids) > 0:
                _escalate(
                    "HOLD",
                    f"INCOMPLETE_ROSTER_CYTOTOXICITY_EXCLUSION_PRECLUDES_FULL_ROSTER_PASS: "
                    f"{len(valid_excluded_donor_ids)} of {bonferroni_family_denominator_n} pre-registered rostered "
                    f"donors were excluded pre-assay ({sorted(valid_excluded_donor_ids)}); confirmatory full-roster "
                    f"cytotoxicity PASS and Track-B eligibility require 100% measured valid cytotoxicity evidence across all "
                    f"N_roster={bonferroni_family_denominator_n} rostered donors (conservative full-roster "
                    f"Bonferroni FAIL adjudication remains active at N_roster={bonferroni_family_denominator_n})",
                )

    # 8. Cross-block construct-bound linked expression_batch_ids replication checks
    #    (>= 3 distinct Comp1 batches linked across Comp1 assays; >= 3 distinct Comp2 batches linked across
    #     Comp2 assays; >= 3 distinct Comp1 and >= 3 distinct Comp2 batches linked across cocktail assays)
    derived_summary["distinct_referenced_expression_batches_count"] = len(referenced_batches)
    derived_summary["distinct_linked_comp1_assay_batches_count"] = len(comp1_assay_batches)
    derived_summary["distinct_linked_comp2_assay_batches_count"] = len(comp2_assay_batches)
    derived_summary["distinct_linked_cocktail_comp1_batches_count"] = len(cocktail_comp1_batches)
    derived_summary["distinct_linked_cocktail_comp2_batches_count"] = len(cocktail_comp2_batches)
    if len(referenced_batches) < _SHIELD_MIN_BATCHES_N:
        _escalate(
            "HOLD_INVALID_OR_MISSING_INPUT",
            f"Assay records reference only {len(referenced_batches)} distinct declared passing expression batches (< {_SHIELD_MIN_BATCHES_N} required)",
        )
    if len(comp1_assay_batches) < _SHIELD_MIN_BATCHES_N:
        _escalate(
            "HOLD_INVALID_OR_MISSING_INPUT",
            f"Comp1 assays link only {len(comp1_assay_batches)} distinct passing {_SHIELD_COMP1_LEAD} batches (< {_SHIELD_MIN_BATCHES_N} required)",
        )
    if len(comp2_assay_batches) < _SHIELD_MIN_BATCHES_N:
        _escalate(
            "HOLD_INVALID_OR_MISSING_INPUT",
            f"Comp2 assays link only {len(comp2_assay_batches)} distinct passing {_SHIELD_COMP2_LEAD} batches (< {_SHIELD_MIN_BATCHES_N} required)",
        )
    if len(cocktail_comp1_batches) < _SHIELD_MIN_BATCHES_N:
        _escalate(
            "HOLD_INVALID_OR_MISSING_INPUT",
            f"Cocktail assays link only {len(cocktail_comp1_batches)} distinct passing {_SHIELD_COMP1_LEAD} batches (< {_SHIELD_MIN_BATCHES_N} required)",
        )
    if len(cocktail_comp2_batches) < _SHIELD_MIN_BATCHES_N:
        _escalate(
            "HOLD_INVALID_OR_MISSING_INPUT",
            f"Cocktail assays link only {len(cocktail_comp2_batches)} distinct passing {_SHIELD_COMP2_LEAD} batches (< {_SHIELD_MIN_BATCHES_N} required)",
        )

    if worst_state != "FAIL":
        failure_domain: str | None = None
    elif spr_bio_fail and donor_based_bio_fail:
        failure_domain = "BOTH_INDEPENDENT_SPR_AND_ROSTERED_DONOR_COHORT"
    elif spr_bio_fail:
        failure_domain = "INDEPENDENT_NON_DONOR_SPR"
    else:
        failure_domain = "ROSTERED_DONOR_COHORT"
    derived_summary["failure_domain"] = failure_domain

    # R13 0037-B3: Explicit machine-checked Track-B SHIELD trigger state (ZERO new input fields;
    # requires complete zero-hold evidence across all 7 blocks before classifying SHIELD-1-only vs overall fail!)
    all_comp1_on_target_passed = comp1_on_target_passed_analytes == set(_SHIELD_COMP1_ON_TARGET_ANALYTES)
    all_comp1_off_target_passed = comp1_off_target_passed_controls == set(_SHIELD_MANDATORY_COMP1_OFF_TARGET_CONTROLS)
    comp1_complete_spr_pass = bool(
        hip11_exchange_qc_valid
        and all_comp1_on_target_passed
        and all_comp1_off_target_passed
        and not comp1_spr_bio_fail
    )
    hold_reasons_count = sum(1 for rs in reasons if not rs.startswith("[FAIL]"))
    if (
        worst_state != "FAIL"
        or hold_reasons_count > 0
        or not full_roster_cyto_measured_complete
        or not derived_summary.get("comparator_mandatory_register_coverage_verified")
    ):
        trackb_shield_trigger_state = "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
    elif comp1_complete_spr_pass and comp2_spr_bio_fail and not donor_based_bio_fail:
        trackb_shield_trigger_state = (
            "ELIGIBLE_CANDIDATE_SHIELD1_ONLY_COMP2_FAIL_PENDING_XREACT_AND_OWNER_REAUTH"
        )
    else:
        trackb_shield_trigger_state = (
            "ELIGIBLE_CANDIDATE_OVERALL_SHIELD_FAIL_PENDING_XREACT_AND_OWNER_REAUTH"
        )
    derived_summary["trackb_shield_trigger_state"] = trackb_shield_trigger_state
    derived_summary["trackb_shield_trigger_adjudicator"] = (
        "GATE30_SHIELD_SPR_SOFTWARE_PLUS_GATE30_ATG_XREACT_PASS_PLUS_OWNER_REAUTHORIZATION"
    )
    derived_summary["comp1_complete_spr_pass"] = comp1_complete_spr_pass
    derived_summary["comp1_spr_bio_fail"] = comp1_spr_bio_fail
    derived_summary["comp2_spr_bio_fail"] = comp2_spr_bio_fail
    derived_summary["non_fail_hold_or_invalid_reasons_count"] = hold_reasons_count

    return {
        "gate_id": "GATE_30_SHIELD_SPR",
        "verdict": worst_state,
        "pre_adjudication_nonfinite_rejection": "ValueError",
        "precedence_order": list(_SHIELD_SPR_PRECEDENCE_ORDER),
        "derived_summary": derived_summary,
        "analytes_verified_count": len(analyte_derived),
        "reasons": reasons,
    }


def run_gate30_shield_spr_decision_table_self_tests() -> dict[str, Any]:
    """Verify full typed Gate 30-SHIELD-SPR evidence enforcement, mandatory cryptographically hash-pinned
    outcome-blind pre-registered donor roster & 100% reconciliation (R09 B2), exact distribution-free
    Clopper-Pearson responder-proportion suppression inference & anti-enhancement guard (R09 B3),
    mandatory structured GY-018 independence justification (R09 M1), two-pass order-independent canonical
    key uniqueness across all evidence lists (R08 B3), row-level SPR validity gating (R07 B1),
    construct-bound expression-batch provenance, Comp1+Comp2 off-targets, quantitative SEC-MALS/DLS,
    optional physical 1JK8 policy (omitted & explicit null), mandatory typed T1D donor eligibility
    (R08 B5), qualifying donor HLA, exact GY-018 deff==1.0 preserved as Decimal through JSON decoding
    (R07 B2) & invalid-donor gating, fixed pre-exclusion roster Bonferroni FWER<=0.05 cytotoxicity
    FAIL rule under H0_all: max_i p_i <= 5% (R08 B4 + R09 B2), two-sided CI checks, >1e300 float
    rejection, and 6-level precedence.
    """
    base_pass = build_valid_shield_spr_observation(n_eff_per_donor=60)
    r_pass = evaluate_gate30_shield_spr(base_pass)
    if (
        r_pass["verdict"] != "PASS"
        or r_pass["derived_summary"]["roster_donor_count_n"] != 9
        or r_pass["derived_summary"]["suppression_responder_l95_clopper_pearson_pct"] < 70.0
        or r_pass["derived_summary"]["authorization_grade_fwer_bound_valid"] is not True
    ):
        raise RuntimeError(f"SHIELD-SPR clean 9-donor PASS failed: {r_pass}")

    # 1. Scalar-only summary lacking typed evidence blocks -> HOLD_INVALID_OR_MISSING_INPUT
    c_scalar_only = {
        "n_expression_batches": 3,
        "n_technical_spr_replicates": 3,
        "n_independent_t1d_donors": 9,
        "reagent_register_qc_passed": True,
        "secmals_dls_monomer_qc_passed": True,
        "cytotoxicity_n_eff_per_donor": 60,
        "ic50_l95_nM": 22.0,
        "ic50_u95_nM": 48.0,
        "selectivity_l95_x": 85.0,
        "selectivity_u95_x": 140.0,
        "suppression_l95_t_pct": 76.0,
        "suppression_u95_t_pct": 88.0,
        "cytotoxicity_observed_pct": 0.0,
        "cytotoxicity_l95_pct": 0.0,
        "cytotoxicity_u95_pct": 4.87,
    }
    r_scalar = evaluate_gate30_shield_spr(c_scalar_only)
    if r_scalar["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"Scalar-only summary must fail closed, got {r_scalar}")

    # 2. DQ2.2 + HIP11 at 650-800 nM -> FAIL
    c_dq22_fail = json.loads(json.dumps(base_pass))
    for a in c_dq22_fail["on_target_analytes"]:
        if a["analyte_id"] == "HLA-DQ2.2 + HIP11":
            a["ic50_l95_nm"] = 650.0
            a["ic50_u95_nm"] = 800.0
    r_dq22_fail = evaluate_gate30_shield_spr(c_dq22_fail)
    if r_dq22_fail["verdict"] != "FAIL":
        raise RuntimeError(f"DQ2.2 + HIP11 650-800 nM must return FAIL, got {r_dq22_fail}")

    # 3. Missing mandatory analyte (omit DQ2.2 + HIP11) -> HOLD_INVALID_OR_MISSING_INPUT
    c_miss_analyte = json.loads(json.dumps(base_pass))
    c_miss_analyte["on_target_analytes"] = [a for a in c_miss_analyte["on_target_analytes"] if a["analyte_id"] != "HLA-DQ2.2 + HIP11"]
    r_miss_analyte = evaluate_gate30_shield_spr(c_miss_analyte)
    if r_miss_analyte["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"Missing DQ2.2 must fail closed, got {r_miss_analyte}")

    # 4. Missing Comp2 off-target control -> HOLD_INVALID_OR_MISSING_INPUT
    c_miss_ctrl = json.loads(json.dumps(base_pass))
    c_miss_ctrl["off_target_controls"] = [o for o in c_miss_ctrl["off_target_controls"] if o["analyte_id"] != "HLA-DQ8-trans + WT InsB:9-23"]
    r_miss_ctrl = evaluate_gate30_shield_spr(c_miss_ctrl)
    if r_miss_ctrl["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"Missing Comp2 off-target control must fail closed, got {r_miss_ctrl}")

    # 5. Missing Comp2 parallel comparator -> HOLD_INVALID_OR_MISSING_INPUT
    c_miss_comp = json.loads(json.dumps(base_pass))
    c_miss_comp["comp2_comparators_screened"] = c_miss_comp["comp2_comparators_screened"][:5]
    r_miss_comp = evaluate_gate30_shield_spr(c_miss_comp)
    if r_miss_comp["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"Missing comparator must fail closed, got {r_miss_comp}")

    # 6. Exact N_eff boundary: 58 and 59 -> HOLD_INVALID_OR_MISSING_INPUT; 60 -> PASS
    r_neff_58 = evaluate_gate30_shield_spr(build_valid_shield_spr_observation(n_eff_per_donor=58))
    r_neff_59 = evaluate_gate30_shield_spr(build_valid_shield_spr_observation(n_eff_per_donor=59))
    if r_neff_58["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT" or r_neff_59["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"N_eff 58/59 must fail closed, got {r_neff_58} / {r_neff_59}")

    # 7. Inconsistent cytotoxicity CI: 0% observed with L95=2% -> HOLD_INVALID_OR_MISSING_INPUT
    c_inconsist = json.loads(json.dumps(base_pass))
    c_inconsist["tcell_blockade_and_apc_cytotoxicity_donors"][0]["apc_cytotoxicity_observed_pct"] = 0.0
    c_inconsist["tcell_blockade_and_apc_cytotoxicity_donors"][0]["apc_cytotoxicity_l95_pct"] = 2.0
    c_inconsist["tcell_blockade_and_apc_cytotoxicity_donors"][0]["apc_cytotoxicity_u95_pct"] = 4.87
    r_inconsist = evaluate_gate30_shield_spr(c_inconsist)
    if r_inconsist["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"0% obs with L95=2% must fail closed, got {r_inconsist}")

    # 8. Nonzero 1% observed with U95 <= 5.0% -> HOLD_OBSERVED_NONZERO_CYTOTOXICITY
    r_nz_le5 = evaluate_gate30_shield_spr(build_valid_shield_spr_observation(n_eff_per_donor=100, donor_k_obs=(1,) * 9))
    if r_nz_le5["verdict"] != "HOLD_OBSERVED_NONZERO_CYTOTOXICITY":
        raise RuntimeError(f"1% obs U95<=5% failed: {r_nz_le5}")

    # 9. Nonzero 1% mean observed with U95 > 5.0% -> HOLD_CYTOTOXICITY_U95_EXCEEDS_5PCT
    r_nz_gt5 = evaluate_gate30_shield_spr(build_valid_shield_spr_observation(n_eff_per_donor=100, donor_k_obs=(1, 0, 2)))
    if r_nz_gt5["verdict"] != "HOLD_CYTOTOXICITY_U95_EXCEEDS_5PCT":
        raise RuntimeError(f"1% obs U95>5% failed: {r_nz_gt5}")

    # 10. Exact fixed-roster Bonferroni lower bound > 5.0% (9/60 across all 3 rostered donors -> L_bonf=6.616469% > 5.0%) -> FAIL
    r_cyto_fail = evaluate_gate30_shield_spr(build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(9, 9, 9)))
    if r_cyto_fail["verdict"] != "FAIL":
        raise RuntimeError(f"Fixed-roster Bonferroni cytotoxicity L>5% failed: {r_cyto_fail}")

    # 11. Overlapping conflict: distribution-free Clopper-Pearson suppression FAIL (9/9 < 40%) + 1% cyto -> FAIL
    c_overlap = build_valid_shield_spr_observation(
        n_eff_per_donor=100,
        donor_k_obs=(1,) * 9,
        donor_suppressions=(26.0, 28.0, 30.0, 25.0, 27.0, 29.0, 31.0, 24.0, 32.0),
    )
    r_overlap = evaluate_gate30_shield_spr(c_overlap)
    if r_overlap["verdict"] != "FAIL":
        raise RuntimeError(f"Overlap suppression FAIL + 1% cyto failed: {r_overlap}")

    # 12. FAIL dominates missing comparator (9/9 rostered donors < 40% suppression -> L95_CP=71.687% > 60% FAIL)
    c_fail_miss = json.loads(json.dumps(c_miss_comp))
    for i, s_val in enumerate((26.0, 28.0, 30.0, 25.0, 27.0, 29.0, 31.0, 24.0, 32.0)):
        c_fail_miss["tcell_blockade_and_apc_cytotoxicity_donors"][i]["suppression_pct"] = s_val
    r_fail_miss = evaluate_gate30_shield_spr(c_fail_miss)
    if r_fail_miss["verdict"] != "FAIL":
        raise RuntimeError(f"FAIL must dominate missing comparator, got {r_fail_miss}")

    # 13. Intermediate IC50 -> HOLD
    c_mid = json.loads(json.dumps(base_pass))
    c_mid["on_target_analytes"][0]["ic50_l95_nm"] = 140.0
    c_mid["on_target_analytes"][0]["ic50_u95_nm"] = 260.0
    r_mid = evaluate_gate30_shield_spr(c_mid)
    if r_mid["verdict"] != "HOLD":
        raise RuntimeError(f"Intermediate IC50 must return HOLD, got {r_mid}")

    # 14. Pre-adjudication NaN raises ValueError BEFORE even an independent biological FAIL
    c_nan_with_fail = json.loads(json.dumps(c_overlap))
    c_nan_with_fail["on_target_analytes"][0]["ic50_u95_nm"] = float("nan")
    nan_rejected = False
    try:
        evaluate_gate30_shield_spr(c_nan_with_fail)
    except ValueError:
        nan_rejected = True
    if not nan_rejected:
        raise RuntimeError("SHIELD-SPR NaN must raise ValueError prior to decision precedence")

    # 15. Optional physical 14-aa 1JK8 control omitted -> PASS
    r_opt_1jk8_omit = evaluate_gate30_shield_spr(build_valid_shield_spr_observation(include_optional_1jk8=False))
    if r_opt_1jk8_omit["verdict"] != "PASS" or r_opt_1jk8_omit["derived_summary"].get("optional_1jk8_physical_control_present") is not False:
        raise RuntimeError(f"Omitted optional 14-aa 1JK8 control must PASS, got {r_opt_1jk8_omit}")

    # 16. Present optional 14-aa 1JK8 control with wrong sequence -> HOLD_INVALID_OR_MISSING_INPUT
    c_bad_1jk8 = json.loads(json.dumps(base_pass))
    c_bad_1jk8["register_qc_records"]["crystal_ref_1jk8_14aa"]["sequence"] = "SHLVEALYLVCGERG"
    r_bad_1jk8 = evaluate_gate30_shield_spr(c_bad_1jk8)
    if r_bad_1jk8["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"Malformed present 1JK8 control must fail closed, got {r_bad_1jk8}")

    # 17. Missing Component 1 off-target controls -> HOLD_INVALID_OR_MISSING_INPUT
    c_no_comp1_off = json.loads(json.dumps(base_pass))
    c_no_comp1_off["off_target_controls"] = [
        o for o in c_no_comp1_off["off_target_controls"] if o["analyte_id"] in _SHIELD_MANDATORY_COMP2_OFF_TARGET_CONTROLS
    ]
    r_no_comp1_off = evaluate_gate30_shield_spr(c_no_comp1_off)
    if r_no_comp1_off["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"Missing Component 1 off-target controls must fail closed, got {r_no_comp1_off}")

    # 18. Missing expression_batch_ids on an assay block -> HOLD_INVALID_OR_MISSING_INPUT
    c_no_batch_link = json.loads(json.dumps(base_pass))
    c_no_batch_link["on_target_analytes"][0].pop("expression_batch_ids", None)
    r_no_batch_link = evaluate_gate30_shield_spr(c_no_batch_link)
    if r_no_batch_link["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"Missing expression_batch_ids must fail closed, got {r_no_batch_link}")

    # 19. Only 2 of 3 declared lead batches actually referenced across lead/cocktail assays -> HOLD_INVALID_OR_MISSING_INPUT
    c_only_2_batches = json.loads(json.dumps(base_pass))
    two_b = ["BATCH_ECOLI_01", "BATCH_ECOLI_02"]
    for a in c_only_2_batches["on_target_analytes"]:
        a["expression_batch_ids"] = list(two_b)
    for o in c_only_2_batches["off_target_controls"]:
        o["expression_batch_ids"] = list(two_b)
    for cp in c_only_2_batches["comp2_comparators_screened"]:
        if cp["comparator_id"] == _SHIELD_COMP2_LEAD:
            cp["expression_batch_ids"] = list(two_b)
            for cond_v in cp["register_control_screens"].values():
                if isinstance(cond_v, dict):
                    cond_v["expression_batch_ids"] = list(two_b)
    c_only_2_batches["register_qc_records"]["expression_batch_ids"] = list(two_b)
    c_only_2_batches["register_qc_records"]["crystal_ref_1jk8_14aa"]["expression_batch_ids"] = list(two_b)
    c_only_2_batches["sec_mals_dls_monomer_coformulation"]["expression_batch_ids"] = list(two_b)
    for d in c_only_2_batches["tcell_blockade_and_apc_cytotoxicity_donors"]:
        d["expression_batch_ids"] = ["BATCH_ECOLI_01"]
    r_only_2_batches = evaluate_gate30_shield_spr(c_only_2_batches)
    if r_only_2_batches["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"Referencing only 2 of 3 declared lead batches must fail closed, got {r_only_2_batches}")

    # 20. 1% measured monomer with qc_passed=True -> HOLD_INVALID_OR_MISSING_INPUT
    c_1pct_mon = json.loads(json.dumps(base_pass))
    c_1pct_mon["sec_mals_dls_monomer_coformulation"]["comp2_monomer_pct"] = 1.0
    c_1pct_mon["sec_mals_dls_monomer_coformulation"]["cocktail_1to1_monomer_pct"] = 1.0
    r_1pct_mon = evaluate_gate30_shield_spr(c_1pct_mon)
    if r_1pct_mon["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"1% monomer with qc_passed=True must fail closed, got {r_1pct_mon}")

    # 21. DLS PDI > 0.15 -> HOLD_INVALID_OR_MISSING_INPUT
    c_bad_pdi = json.loads(json.dumps(base_pass))
    c_bad_pdi["sec_mals_dls_monomer_coformulation"]["dls_pdi"] = 0.22
    r_bad_pdi = evaluate_gate30_shield_spr(c_bad_pdi)
    if r_bad_pdi["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"DLS PDI > 0.15 must fail closed, got {r_bad_pdi}")

    # 22. Missing donor hla_genotype -> HOLD_INVALID_OR_MISSING_INPUT
    c_no_hla = json.loads(json.dumps(base_pass))
    c_no_hla["tcell_blockade_and_apc_cytotoxicity_donors"][0].pop("hla_genotype", None)
    r_no_hla = evaluate_gate30_shield_spr(c_no_hla)
    if r_no_hla["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"Missing donor hla_genotype must fail closed, got {r_no_hla}")

    # 23. Non-qualifying donor HLA-DQ6 -> HOLD_INVALID_OR_MISSING_INPUT
    c_dq6 = json.loads(json.dumps(base_pass))
    c_dq6["tcell_blockade_and_apc_cytotoxicity_donors"][0]["hla_genotype"] = "HLA-DQ6"
    r_dq6 = evaluate_gate30_shield_spr(c_dq6)
    if r_dq6["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"Non-qualifying HLA-DQ6 donor must fail closed, got {r_dq6}")

    # 24. GY-018 clustered design_effect_deff=1.5 -> HOLD_INVALID_OR_MISSING_INPUT
    c_deff = json.loads(json.dumps(base_pass))
    c_deff["tcell_blockade_and_apc_cytotoxicity_donors"][0]["design_effect_deff"] = 1.5
    r_deff = evaluate_gate30_shield_spr(c_deff)
    if r_deff["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"GY-018 clustered deff=1.5 must fail closed, got {r_deff}")

    # 25. GY-018 n_eff != raw_independent_units_n -> HOLD_INVALID_OR_MISSING_INPUT
    c_neff_mismatch = json.loads(json.dumps(base_pass))
    c_neff_mismatch["tcell_blockade_and_apc_cytotoxicity_donors"][0]["raw_independent_units_n"] = 90
    r_neff_mismatch = evaluate_gate30_shield_spr(c_neff_mismatch)
    if r_neff_mismatch["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"GY-018 n_eff != raw_independent_units_n must fail closed, got {r_neff_mismatch}")

    # 26. Two-sided cytotoxicity consistency: caller-reported U95=99% on 0/60 -> HOLD_INVALID_OR_MISSING_INPUT
    c_u95_99 = json.loads(json.dumps(base_pass))
    c_u95_99["tcell_blockade_and_apc_cytotoxicity_donors"][0]["apc_cytotoxicity_u95_pct"] = 99.0
    r_u95_99 = evaluate_gate30_shield_spr(c_u95_99)
    if r_u95_99["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"Caller-reported U95=99% on 0/60 must fail closed, got {r_u95_99}")

    # 27. Pre-adjudication float magnitude > 1e300 raises ValueError consistently with int overflow
    c_float_ovf = json.loads(json.dumps(base_pass))
    c_float_ovf["on_target_analytes"][0]["selectivity_u95_fold"] = 1e305
    float_ovf_rejected = False
    try:
        evaluate_gate30_shield_spr(c_float_ovf)
    except ValueError:
        float_ovf_rejected = True
    if not float_ovf_rejected:
        raise RuntimeError("SHIELD-SPR float > 1e300 must raise ValueError prior to decision precedence")

    # 28. 22-donor split [63.985]*11 + [86.015]*11: exact df=21 Student-t diagnostic is 70.001295% (non-authorizing!),
    #     while distribution-free Clopper-Pearson responder rule holds (11/22 responders -> L95_CP=30.98% < 70% -> HOLD);
    #     whereas 22/22 responders at 80% passes cleanly (L95_CP=87.269% >= 70% -> PASS)!
    c_df21_split = build_valid_shield_spr_observation(
        n_eff_per_donor=60,
        donor_k_obs=tuple(0 for _ in range(22)),
        donor_suppressions=tuple([63.985] * 11 + [86.015] * 11),
    )
    r_df21_split = evaluate_gate30_shield_spr(c_df21_split)
    c_df21_all_resp = build_valid_shield_spr_observation(
        n_eff_per_donor=60,
        donor_k_obs=tuple(0 for _ in range(22)),
        donor_suppressions=tuple(80.0 for _ in range(22)),
    )
    r_df21_all_resp = evaluate_gate30_shield_spr(c_df21_all_resp)
    if (
        r_df21_split["verdict"] != "HOLD"
        or r_df21_split["derived_summary"]["suppression_student_t_authorizing"] is not False
        or r_df21_split["derived_summary"]["suppression_l95_t_diagnostic_only_pct"] < 70.0
        or r_df21_all_resp["verdict"] != "PASS"
    ):
        raise RuntimeError(
            f"22-donor non-authorizing Student-t diagnostic vs Clopper-Pearson responder rule failed: "
            f"split={r_df21_split}, all_resp={r_df21_all_resp}"
        )

    # 29 (R06 B1a): All assays linked exclusively to 3 QC-passing batches with construct_ids=[] -> HOLD_INVALID_OR_MISSING_INPUT!
    c_empty_batches = json.loads(json.dumps(base_pass))
    empty_ids = ["EMPTY_B1", "EMPTY_B2", "EMPTY_B3"]
    for eid in empty_ids:
        c_empty_batches["expression_batches"].append({"batch_id": eid, "construct_ids": [], "qc_passed": True})
    for a in c_empty_batches["on_target_analytes"]:
        a["expression_batch_ids"] = list(empty_ids)
    for o in c_empty_batches["off_target_controls"]:
        o["expression_batch_ids"] = list(empty_ids)
    for cp in c_empty_batches["comp2_comparators_screened"]:
        cp["expression_batch_ids"] = list(empty_ids)
    c_empty_batches["register_qc_records"]["expression_batch_ids"] = list(empty_ids)
    c_empty_batches["register_qc_records"]["crystal_ref_1jk8_14aa"]["expression_batch_ids"] = list(empty_ids)
    c_empty_batches["sec_mals_dls_monomer_coformulation"]["expression_batch_ids"] = list(empty_ids)
    for idx_d, d in enumerate(c_empty_batches["tcell_blockade_and_apc_cytotoxicity_donors"]):
        d["expression_batch_ids"] = [empty_ids[idx_d % len(empty_ids)]]
    r_empty_batches = evaluate_gate30_shield_spr(c_empty_batches)
    if r_empty_batches["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"Empty construct_ids batches must fail closed, got {r_empty_batches}")

    # 30 (R06 B1b): HLA-DQ2.5 + HIP11 linked exclusively to an unrelated passing batch -> HOLD_INVALID_OR_MISSING_INPUT!
    c_wrong_construct = json.loads(json.dumps(base_pass))
    c_wrong_construct["expression_batches"].append(
        {"batch_id": "BATCH_UNRELATED_01", "construct_ids": ["UNRELATED_NON_LEAD_PROTEIN"], "qc_passed": True}
    )
    c_wrong_construct["on_target_analytes"][0]["expression_batch_ids"] = ["BATCH_UNRELATED_01"]
    r_wrong_construct = evaluate_gate30_shield_spr(c_wrong_construct)
    if r_wrong_construct["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"Unrelated batch on HLA-DQ2.5 + HIP11 must fail closed, got {r_wrong_construct}")

    # 31 (R06 B1c): Comparator SHIELD2_QQ linked exclusively to cocktail-only batch lacking SHIELD2_QQ -> HOLD_INVALID_OR_MISSING_INPUT!
    c_wrong_comp_batch = json.loads(json.dumps(base_pass))
    for cp in c_wrong_comp_batch["comp2_comparators_screened"]:
        if cp["comparator_id"] == "SHIELD2_QQ":
            cp["expression_batch_ids"] = ["BATCH_ECOLI_01"]
    r_wrong_comp_batch = evaluate_gate30_shield_spr(c_wrong_comp_batch)
    if r_wrong_comp_batch["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"Wrong construct batch on SHIELD2_QQ comparator must fail closed, got {r_wrong_comp_batch}")

    # 32 (R06 B1d + R10 B1): Separate Comp1-only (9 batches) + Comp2-only (9 batches) + comparator batches assigned 1:1 per donor -> PASS!
    c_sep_batches = json.loads(json.dumps(base_pass))
    c1_ids = [f"BATCH_C1_{i:02d}" for i in range(1, 10)]
    c2_ids = [f"BATCH_C2_{i:02d}" for i in range(1, 10)]
    c_sep_batches["expression_batches"] = (
        [{"batch_id": bid, "construct_ids": [_SHIELD_COMP1_LEAD], "qc_passed": True} for bid in c1_ids]
        + [{"batch_id": bid, "construct_ids": [_SHIELD_COMP2_LEAD], "qc_passed": True} for bid in c2_ids]
        + [
            {"batch_id": f"BATCH_COMP_{cid}", "construct_ids": [cid], "qc_passed": True}
            for cid in _SHIELD_MANDATORY_COMP2_COMPARATORS
            if cid != _SHIELD_COMP2_LEAD
        ]
    )
    for a in c_sep_batches["on_target_analytes"]:
        a["expression_batch_ids"] = list(c1_ids[:3]) if a["analyte_id"] in _SHIELD_COMP1_ON_TARGET_ANALYTES else list(c2_ids[:3])
    for o in c_sep_batches["off_target_controls"]:
        o["expression_batch_ids"] = list(c1_ids[:3]) if o["analyte_id"] in _SHIELD_MANDATORY_COMP1_OFF_TARGET_CONTROLS else list(c2_ids[:3])
    for cp in c_sep_batches["comp2_comparators_screened"]:
        if cp["comparator_id"] == _SHIELD_COMP2_LEAD:
            cp["expression_batch_ids"] = list(c2_ids[:3])
            for cond_v in cp["register_control_screens"].values():
                if isinstance(cond_v, dict):
                    cond_v["expression_batch_ids"] = list(c2_ids[:3])
    c_sep_batches["register_qc_records"]["expression_batch_ids"] = c1_ids[:3] + c2_ids[:3]
    c_sep_batches["register_qc_records"]["crystal_ref_1jk8_14aa"]["expression_batch_ids"] = list(c2_ids[:3])
    c_sep_batches["sec_mals_dls_monomer_coformulation"]["expression_batch_ids"] = c1_ids + c2_ids
    c_sep_batches["sec_mals_dls_monomer_coformulation"]["qualified_coformulation_mixtures"] = [
        {
            "mixture_id": f"MIX_SHIELD_{idx_m + 1:02d}",
            "comp1_expression_batch_id": c1_ids[idx_m],
            "comp2_expression_batch_id": c2_ids[idx_m],
            "monomer_pct": 96.8,
            "dls_pdi": 0.08,
            "no_aggregates_or_precipitation": True,
            "qc_passed": True,
        }
        for idx_m in range(len(c1_ids))
    ]
    for idx_d, d in enumerate(c_sep_batches["tcell_blockade_and_apc_cytotoxicity_donors"]):
        d["cocktail_mixture_id"] = f"MIX_SHIELD_{idx_d + 1:02d}"
        d["expression_batch_ids"] = [c1_ids[idx_d], c2_ids[idx_d]]
    r_sep_batches = evaluate_gate30_shield_spr(c_sep_batches)
    if r_sep_batches["verdict"] != "PASS":
        raise RuntimeError(f"Separate Comp1-only + Comp2-only disjoint batches must PASS, got {r_sep_batches}")

    # 33 (R06 B2/B4): Exact deff == 1.0 enforcement — design_effect_deff = 1.0000000000005 -> HOLD_INVALID_OR_MISSING_INPUT!
    c_deff_tiny = json.loads(json.dumps(base_pass))
    c_deff_tiny["tcell_blockade_and_apc_cytotoxicity_donors"][0]["design_effect_deff"] = 1.0000000000005
    r_deff_tiny = evaluate_gate30_shield_spr(c_deff_tiny)
    if r_deff_tiny["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"Exact deff=1.0000000000005 must fail closed, got {r_deff_tiny}")

    # 34 (R06 B2): Invalid donor (deff=1.1 with 15/60 events) gated OUT of Clopper-Pearson -> HOLD_INVALID_OR_MISSING_INPUT (NOT biological FAIL)!
    c_deff_15 = build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(15, 0, 0))
    c_deff_15["tcell_blockade_and_apc_cytotoxicity_donors"][0]["design_effect_deff"] = 1.1
    r_deff_15 = evaluate_gate30_shield_spr(c_deff_15)
    if r_deff_15["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"Invalid donor deff=1.1 with 15/60 must HOLD_INVALID (not bio FAIL), got {r_deff_15}")

    # 35 (R06 B2): Independent valid SPR FAIL + invalid deff=1.1 donor -> FAIL (preserves fail-first precedence)!
    c_spr_fail_and_bad_deff = json.loads(json.dumps(c_deff_15))
    c_spr_fail_and_bad_deff["on_target_analytes"][0]["ic50_l95_nm"] = 650.0
    c_spr_fail_and_bad_deff["on_target_analytes"][0]["ic50_u95_nm"] = 800.0
    r_spr_fail_bad_deff = evaluate_gate30_shield_spr(c_spr_fail_and_bad_deff)
    if r_spr_fail_bad_deff["verdict"] != "FAIL":
        raise RuntimeError(f"Valid SPR FAIL must dominate invalid deff=1.1 donor, got {r_spr_fail_bad_deff}")

    # 36 (R06 B3): Bonferroni-calibrated simultaneous FWER <= 0.05 — [7, 0, 0]/60 across 3 rostered donors holds cleanly!
    r_bonf_700 = evaluate_gate30_shield_spr(build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(7, 0, 0)))
    if (
        r_bonf_700["verdict"] != "HOLD_CYTOTOXICITY_U95_EXCEEDS_5PCT"
        or r_bonf_700["derived_summary"]["simultaneous_worst_donor_bonferroni_lower_pct"] >= 5.0
        or r_bonf_700["derived_summary"]["unadjusted_donor_l95_diagnostic_only"] <= 5.0
    ):
        raise RuntimeError(f"Bonferroni-calibrated [7, 0, 0]/60 must HOLD_CYTOTOXICITY_U95_EXCEEDS_5PCT, got {r_bonf_700}")

    # 37 (R06 B3): Bonferroni-calibrated simultaneous FWER <= 0.05 — [9, 0, 0]/60 across 3 rostered donors triggers calibrated FAIL!
    r_bonf_900 = evaluate_gate30_shield_spr(build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(9, 0, 0)))
    if (
        r_bonf_900["verdict"] != "FAIL"
        or r_bonf_900["derived_summary"]["simultaneous_worst_donor_bonferroni_lower_pct"] <= 5.0
    ):
        raise RuntimeError(f"Bonferroni-calibrated [9, 0, 0]/60 must trigger FAIL, got {r_bonf_900}")

    # 38 (R06 M1): Optional 14-aa 1JK8 explicitly set to JSON null (None) -> equivalent to omitted -> PASS!
    c_1jk8_null = json.loads(json.dumps(base_pass))
    c_1jk8_null["register_qc_records"]["crystal_ref_1jk8_14aa"] = None
    r_1jk8_null = evaluate_gate30_shield_spr(c_1jk8_null)
    if r_1jk8_null["verdict"] != "PASS" or r_1jk8_null["derived_summary"].get("optional_1jk8_physical_control_present") is not False:
        raise RuntimeError(f"Explicit null optional 14-aa 1JK8 control must PASS, got {r_1jk8_null}")

    # 39 (R07 B1a): Mandatory row with wrong-construct/undeclared batch + 650-800 nM -> HOLD_INVALID_OR_MISSING_INPUT (NOT FAIL!)
    c_bad_batch_650 = json.loads(json.dumps(base_pass))
    c_bad_batch_650["on_target_analytes"][0]["expression_batch_ids"] = ["UNDECLARED_OR_WRONG_BATCH"]
    c_bad_batch_650["on_target_analytes"][0]["ic50_l95_nm"] = 650.0
    c_bad_batch_650["on_target_analytes"][0]["ic50_u95_nm"] = 800.0
    r_bad_batch_650 = evaluate_gate30_shield_spr(c_bad_batch_650)
    if r_bad_batch_650["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"Wrong/undeclared batch + 650-800 nM must HOLD_INVALID (not bio FAIL), got {r_bad_batch_650}")

    # 40 (R07 B1b): Mandatory row with replicates_n=1 + 650-800 nM -> HOLD_INVALID_OR_MISSING_INPUT (NOT FAIL!)
    c_rep1_650 = json.loads(json.dumps(base_pass))
    c_rep1_650["on_target_analytes"][0]["replicates_n"] = 1
    c_rep1_650["on_target_analytes"][0]["ic50_l95_nm"] = 650.0
    c_rep1_650["on_target_analytes"][0]["ic50_u95_nm"] = 800.0
    r_rep1_650 = evaluate_gate30_shield_spr(c_rep1_650)
    if r_rep1_650["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"Under-replicated (n=1) row + 650-800 nM must HOLD_INVALID (not bio FAIL), got {r_rep1_650}")

    # 41 (R07 B1c): Extra unregistered on-target analyte with 650-800 nM while mandatory panel passes -> HOLD_INVALID_OR_MISSING_INPUT (NOT FAIL!)
    c_unreg_650 = json.loads(json.dumps(base_pass))
    c_unreg_650["on_target_analytes"].append(
        {
            "analyte_id": "HLA-DQ9 + UNREGISTERED_SYNTHETIC_CONTROL",
            "replicates_n": 3,
            "expression_batch_ids": ["BATCH_ECOLI_01", "BATCH_ECOLI_02", "BATCH_ECOLI_03"],
            "ic50_l95_nm": 650.0,
            "ic50_u95_nm": 800.0,
            "selectivity_l95_fold": 85.0,
            "selectivity_u95_fold": 140.0,
        }
    )
    r_unreg_650 = evaluate_gate30_shield_spr(c_unreg_650)
    if r_unreg_650["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"Unregistered on-target analyte + 650-800 nM must HOLD_INVALID (not bio FAIL), got {r_unreg_650}")

    # 42 (R07 B1d): Extra unregistered off-target control with low selectivity 1-2x -> HOLD_INVALID_OR_MISSING_INPUT (NOT FAIL!)
    c_unreg_off = json.loads(json.dumps(base_pass))
    c_unreg_off["off_target_controls"].append(
        {
            "analyte_id": "HLA-DQ9 + UNREGISTERED_OFFTARGET",
            "replicates_n": 3,
            "expression_batch_ids": ["BATCH_ECOLI_01", "BATCH_ECOLI_02", "BATCH_ECOLI_03"],
            "selectivity_l95_fold": 1.0,
            "selectivity_u95_fold": 2.0,
        }
    )
    r_unreg_off = evaluate_gate30_shield_spr(c_unreg_off)
    if r_unreg_off["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"Unregistered off-target control + 1-2x selectivity must HOLD_INVALID (not bio FAIL), got {r_unreg_off}")

    # 43 (R07 B1e): Invalid row (wrong batch + 650-800 nM) + SEPARATE valid registered row with 650-800 nM -> FAIL!
    c_invalid_plus_valid_fail = json.loads(json.dumps(c_bad_batch_650))
    for a in c_invalid_plus_valid_fail["on_target_analytes"]:
        if a["analyte_id"] == "HLA-DQ2.2 + HIP11":
            a["ic50_l95_nm"] = 650.0
            a["ic50_u95_nm"] = 800.0
    r_invalid_plus_valid_fail = evaluate_gate30_shield_spr(c_invalid_plus_valid_fail)
    if r_invalid_plus_valid_fail["verdict"] != "FAIL":
        raise RuntimeError(
            f"Invalid SPR row + separate independently valid 650-800 nM row must return FAIL, got {r_invalid_plus_valid_fail}"
        )

    # 44 (R07 B2): Exact zero-tolerance design_effect_deff == 1.0 preserved through load_strict_json_text!
    raw_base_json = json.dumps(base_pass)
    raw_deff_hi = raw_base_json.replace('"design_effect_deff": 1.0', '"design_effect_deff": 1.00000000000000001', 1)
    raw_deff_lo = raw_base_json.replace('"design_effect_deff": 1.0', '"design_effect_deff": 0.99999999999999999', 1)
    raw_deff_int1 = raw_base_json.replace('"design_effect_deff": 1.0', '"design_effect_deff": 1')
    r_deff_hi_json = evaluate_gate30_shield_spr(load_strict_json_text(raw_deff_hi, "r07_deff_hi"))
    r_deff_lo_json = evaluate_gate30_shield_spr(load_strict_json_text(raw_deff_lo, "r07_deff_lo"))
    r_deff_1p0_json = evaluate_gate30_shield_spr(load_strict_json_text(raw_base_json, "r07_deff_1p0"))
    r_deff_int1_json = evaluate_gate30_shield_spr(load_strict_json_text(raw_deff_int1, "r07_deff_int1"))
    if (
        r_deff_hi_json["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_deff_lo_json["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_deff_1p0_json["verdict"] != "PASS"
        or r_deff_int1_json["verdict"] != "PASS"
    ):
        raise RuntimeError(
            f"Exact raw JSON design_effect_deff preservation failed: "
            f"hi={r_deff_hi_json['verdict']}, lo={r_deff_lo_json['verdict']}, "
            f"1.0={r_deff_1p0_json['verdict']}, 1={r_deff_int1_json['verdict']}"
        )

    # 45 (R07 B3a): Correlated batch-shock [4, 4, 4]/60 -> HOLD_CYTOTOXICITY_U95_EXCEEDS_5PCT (NOT uncalibrated cohort-t FAIL!)
    r_corr_444 = evaluate_gate30_shield_spr(build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(4, 4, 4)))
    if (
        r_corr_444["verdict"] != "HOLD_CYTOTOXICITY_U95_EXCEEDS_5PCT"
        or r_corr_444["derived_summary"]["cohort_t_lower_authorizing"] is not False
        or r_corr_444["derived_summary"]["simultaneous_worst_donor_bonferroni_lower_pct"] >= 5.0
    ):
        raise RuntimeError(f"Correlated [4, 4, 4]/60 batch shock must HOLD (not false FAIL), got {r_corr_444}")

    # 46 (R07 B3b): Exact finite-sample Binomial FWER <= 0.05 verification under H0_all: max_i p_i <= 5.0%
    for n_valid_chk in (3, 5, 10):
        alpha_d_chk = _SHIELD_CYTO_DONOR_FAMILY_ALPHA_ONE_SIDED / float(n_valid_chk)
        for n_units_chk in (60, 100):
            k_crit_candidates = [
                k_val
                for k_val in range(n_units_chk + 1)
                if _clopper_pearson_one_sided_95_pct(k_val, n_units_chk, alpha=alpha_d_chk)[0] > 5.0
            ]
            if not k_crit_candidates:
                raise RuntimeError(f"No FAIL threshold found for N={n_valid_chk}, n={n_units_chk}")
            k_crit = min(k_crit_candidates)
            p_single_null = _shield_binom_sf_ge(n_units_chk, k_crit, 0.05)
            fwer_union_bound = float(n_valid_chk) * p_single_null
            if fwer_union_bound > 0.05 + 1e-12:
                raise RuntimeError(
                    f"Fixed-roster Bonferroni FWER union bound exceeded 0.05 for N={n_valid_chk}, n={n_units_chk}: "
                    f"{fwer_union_bound:.6f}"
                )

    # 49 (R08 B3a): Duplicate canonical on-target analyte in BOTH orders -> BOTH HOLD_INVALID!
    c_dup_ot_pf = json.loads(json.dumps(base_pass))
    adverse_dq25 = json.loads(json.dumps(c_dup_ot_pf["on_target_analytes"][0]))
    adverse_dq25["ic50_l95_nm"] = 650.0
    adverse_dq25["ic50_u95_nm"] = 800.0
    c_dup_ot_pf["on_target_analytes"].append(adverse_dq25)
    c_dup_ot_fp = json.loads(json.dumps(base_pass))
    c_dup_ot_fp["on_target_analytes"].insert(0, json.loads(json.dumps(adverse_dq25)))
    r_dup_ot_pf = evaluate_gate30_shield_spr(c_dup_ot_pf)
    r_dup_ot_fp = evaluate_gate30_shield_spr(c_dup_ot_fp)
    if (
        r_dup_ot_pf["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_dup_ot_fp["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_dup_ot_pf["derived_summary"]["conflicted_duplicate_keys"]["on_target_analytes"] != ["HLA-DQ2.5 + HIP11"]
        or r_dup_ot_fp["derived_summary"]["conflicted_duplicate_keys"]["on_target_analytes"] != ["HLA-DQ2.5 + HIP11"]
    ):
        raise RuntimeError(
            f"Duplicate on-target analyte order independence failed: pf={r_dup_ot_pf['verdict']}, fp={r_dup_ot_fp['verdict']}"
        )

    # 50 (R08 B3b): Duplicate alias-colliding WT InsB:9-23 analyte in BOTH orders -> BOTH HOLD_INVALID!
    c_dup_alias_pf = json.loads(json.dumps(base_pass))
    adv_wt = json.loads(json.dumps(c_dup_alias_pf["on_target_analytes"][3]))
    adv_wt["analyte_id"] = "HLA-DQ8 + native WT InsB:9-23 (15-aa SHLVEALYLVCGERG)"
    adv_wt["ic50_l95_nm"] = 650.0
    adv_wt["ic50_u95_nm"] = 800.0
    c_dup_alias_pf["on_target_analytes"].append(adv_wt)
    c_dup_alias_fp = json.loads(json.dumps(base_pass))
    c_dup_alias_fp["on_target_analytes"].insert(0, json.loads(json.dumps(adv_wt)))
    r_dup_alias_pf = evaluate_gate30_shield_spr(c_dup_alias_pf)
    r_dup_alias_fp = evaluate_gate30_shield_spr(c_dup_alias_fp)
    if r_dup_alias_pf["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT" or r_dup_alias_fp["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(
            f"Duplicate alias-colliding analyte order independence failed: pf={r_dup_alias_pf['verdict']}, fp={r_dup_alias_fp['verdict']}"
        )

    # 51 (R08 B3c): Duplicate DQ2.5 + HIP11 + SEPARATE unambiguous valid failing DQ2.2 + HIP11 -> FAIL!
    c_dup_plus_valid_fail = json.loads(json.dumps(c_dup_ot_fp))
    for a in c_dup_plus_valid_fail["on_target_analytes"]:
        if a["analyte_id"] == "HLA-DQ2.2 + HIP11":
            a["ic50_l95_nm"] = 650.0
            a["ic50_u95_nm"] = 800.0
    r_dup_plus_valid_fail = evaluate_gate30_shield_spr(c_dup_plus_valid_fail)
    if r_dup_plus_valid_fail["verdict"] != "FAIL":
        raise RuntimeError(f"Conflicted duplicate analyte + separate valid FAIL must FAIL, got {r_dup_plus_valid_fail}")

    # 52 (R08 B3d): Order-independent duplicates across off-target controls, expression_batches, and donors -> ALL HOLD_INVALID!
    c_dup_off_pf = json.loads(json.dumps(base_pass))
    adv_off = json.loads(json.dumps(c_dup_off_pf["off_target_controls"][0]))
    adv_off["selectivity_l95_fold"] = 1.0
    adv_off["selectivity_u95_fold"] = 2.0
    c_dup_off_pf["off_target_controls"].append(adv_off)
    c_dup_off_fp = json.loads(json.dumps(base_pass))
    c_dup_off_fp["off_target_controls"].insert(0, json.loads(json.dumps(adv_off)))
    r_dup_off_pf = evaluate_gate30_shield_spr(c_dup_off_pf)
    r_dup_off_fp = evaluate_gate30_shield_spr(c_dup_off_fp)

    c_dup_batch_pf = json.loads(json.dumps(base_pass))
    bad_b1 = dict(c_dup_batch_pf["expression_batches"][0], qc_passed=False)
    c_dup_batch_pf["expression_batches"].append(bad_b1)
    c_dup_batch_fp = json.loads(json.dumps(base_pass))
    c_dup_batch_fp["expression_batches"].insert(0, dict(bad_b1))
    r_dup_batch_pf = evaluate_gate30_shield_spr(c_dup_batch_pf)
    r_dup_batch_fp = evaluate_gate30_shield_spr(c_dup_batch_fp)

    c_dup_don_pf = json.loads(json.dumps(base_pass))
    adv_don = json.loads(json.dumps(c_dup_don_pf["tcell_blockade_and_apc_cytotoxicity_donors"][0]))
    adv_don["apc_cytotoxicity_k_obs"] = 15
    c_dup_don_pf["tcell_blockade_and_apc_cytotoxicity_donors"].append(adv_don)
    c_dup_don_fp = json.loads(json.dumps(base_pass))
    c_dup_don_fp["tcell_blockade_and_apc_cytotoxicity_donors"].insert(0, json.loads(json.dumps(adv_don)))
    r_dup_don_pf = evaluate_gate30_shield_spr(c_dup_don_pf)
    r_dup_don_fp = evaluate_gate30_shield_spr(c_dup_don_fp)
    if any(
        r["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        for r in (r_dup_off_pf, r_dup_off_fp, r_dup_batch_pf, r_dup_batch_fp, r_dup_don_pf, r_dup_don_fp)
    ):
        raise RuntimeError("Order-independent duplicate rejection across off-target/batch/donor lists failed")

    # 53 (R08 B4a): 6-donor [8,0,0,0,0,0]/60 complete vs last 3 donors corrupted U95=99 -> N_roster STAYS 6 (L=4.860846% <= 5%, NEVER FAIL!)
    c_6don_complete = build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(8, 0, 0, 0, 0, 0))
    r_6don_complete = evaluate_gate30_shield_spr(c_6don_complete)
    c_6don_corrupt3 = json.loads(json.dumps(c_6don_complete))
    for d in c_6don_corrupt3["tcell_blockade_and_apc_cytotoxicity_donors"][3:]:
        d["apc_cytotoxicity_u95_pct"] = 99.0
    r_6don_corrupt3 = evaluate_gate30_shield_spr(c_6don_corrupt3)
    if (
        r_6don_complete["verdict"] != "HOLD_CYTOTOXICITY_U95_EXCEEDS_5PCT"
        or r_6don_corrupt3["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_6don_corrupt3["derived_summary"]["bonferroni_family_denominator_n"] != 6
        or r_6don_corrupt3["derived_summary"]["submitted_donor_records_n"] != 6
        or r_6don_corrupt3["derived_summary"]["valid_donor_records_n"] != 3
        or abs(r_6don_corrupt3["derived_summary"]["simultaneous_worst_donor_bonferroni_lower_pct"] - 4.860846) > 1e-4
    ):
        raise RuntimeError(
            f"6-donor pre-exclusion N_roster=6 preservation failed: complete={r_6don_complete}, corrupt3={r_6don_corrupt3}"
        )

    # 54 (R08 B4b): 10-donor [8,0,...,0]/60 with last 7 donors corrupted U95=99 -> N_roster STAYS 10 (L=4.453243% <= 5%, NEVER FAIL!)
    c_10don_corrupt7 = build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(8, 0, 0, 0, 0, 0, 0, 0, 0, 0))
    for d in c_10don_corrupt7["tcell_blockade_and_apc_cytotoxicity_donors"][3:]:
        d["apc_cytotoxicity_u95_pct"] = 99.0
    r_10don_corrupt7 = evaluate_gate30_shield_spr(c_10don_corrupt7)
    if (
        r_10don_corrupt7["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_10don_corrupt7["derived_summary"]["bonferroni_family_denominator_n"] != 10
        or r_10don_corrupt7["derived_summary"]["submitted_donor_records_n"] != 10
        or r_10don_corrupt7["derived_summary"]["valid_donor_records_n"] != 3
        or abs(r_10don_corrupt7["derived_summary"]["simultaneous_worst_donor_bonferroni_lower_pct"] - 4.453243) > 1e-4
    ):
        raise RuntimeError(f"10-donor pre-exclusion N_roster=10 preservation failed: {r_10don_corrupt7}")

    # 55 (R08 B4c): 10-donor pre-registered roster with 3 submitted donors [8,0,0]/60 -> N_roster=10 HOLD_INVALID (NEVER FAIL!),
    #               [0,0,0]/60 -> HOLD_INVALID, and conflicting top-level planned=3 vs 6-donor roster -> HOLD_INVALID & denom stays 6!
    r_plan10_800 = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(8, 0, 0), planned_t1d_donor_family_n=10)
    )
    r_plan10_000 = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(0, 0, 0), planned_t1d_donor_family_n=10)
    )
    r_plan3_on_6 = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(8, 0, 0, 0, 0, 0), planned_t1d_donor_family_n=3)
    )
    if (
        r_plan10_800["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_plan10_800["derived_summary"]["bonferroni_family_denominator_n"] != 10
        or r_plan10_800["derived_summary"]["authorization_grade_fwer_bound_valid"] is not False
        or abs(r_plan10_800["derived_summary"]["simultaneous_worst_donor_bonferroni_lower_pct"] - 4.453243) > 1e-4
        or r_plan10_000["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_plan3_on_6["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_plan3_on_6["derived_summary"]["bonferroni_family_denominator_n"] != 6
    ):
        raise RuntimeError(
            f"planned_t1d_donor_family_n / roster enforcement failed: p10_800={r_plan10_800['verdict']}, "
            f"p10_000={r_plan10_000['verdict']}, p3_on_6={r_plan3_on_6['verdict']}"
        )

    # 56 (R08 B4d): Genuine 9/60 on valid eligible donor in reconciled 10-donor roster [9,0,...,0]/60 with 7 corrupted U95s -> L=5.447415% > 5% -> FAIL!
    c_10don_9_corrupt7 = build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(9, 0, 0, 0, 0, 0, 0, 0, 0, 0))
    for d in c_10don_9_corrupt7["tcell_blockade_and_apc_cytotoxicity_donors"][3:]:
        d["apc_cytotoxicity_u95_pct"] = 99.0
    r_10don_9_corrupt7 = evaluate_gate30_shield_spr(c_10don_9_corrupt7)
    if (
        r_10don_9_corrupt7["verdict"] != "FAIL"
        or r_10don_9_corrupt7["derived_summary"]["bonferroni_family_denominator_n"] != 10
        or r_10don_9_corrupt7["derived_summary"]["simultaneous_worst_donor_bonferroni_lower_pct"] <= 5.0
    ):
        raise RuntimeError(f"Genuine 9/60 biological FAIL under N_roster=10 must FAIL, got {r_10don_9_corrupt7}")

    # 57 (R08 B5a): HEALTHY_CONTROL donors with t1d_diagnosis_confirmed=False -> HOLD_INVALID_OR_MISSING_INPUT (NEVER PASS!)
    c_healthy = json.loads(json.dumps(base_pass))
    for i_h, d in enumerate(c_healthy["tcell_blockade_and_apc_cytotoxicity_donors"], start=1):
        d["donor_id"] = f"HEALTHY_CONTROL_{i_h}"
        d["t1d_diagnosis_confirmed"] = False
        d["donor_clinical_cohort"] = "HEALTHY_CONTROL"
    r_healthy = evaluate_gate30_shield_spr(c_healthy)
    if r_healthy["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT" or r_healthy["derived_summary"]["valid_donor_records_n"] != 0:
        raise RuntimeError(f"Healthy-control donor cohort must HOLD_INVALID, got {r_healthy}")

    # 58 (R08 B5b): Contradictory HEALTHY_CONTROL_1 donor_id with forged T1D booleans -> HOLD_INVALID_OR_MISSING_INPUT!
    c_forged_healthy = json.loads(json.dumps(base_pass))
    c_forged_healthy["tcell_blockade_and_apc_cytotoxicity_donors"][0]["donor_id"] = "HEALTHY_CONTROL_1"
    r_forged_healthy = evaluate_gate30_shield_spr(c_forged_healthy)
    if r_forged_healthy["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(f"Contradictory HEALTHY_CONTROL_1 with forged T1D flags must HOLD_INVALID, got {r_forged_healthy}")

    # 59 (R08 B5c): Missing t1d_diagnosis_confirmed, wrong donor_clinical_cohort, or missing/padded t1d_prequalification_ref -> ALL HOLD_INVALID!
    c_miss_diag = json.loads(json.dumps(base_pass))
    c_miss_diag["tcell_blockade_and_apc_cytotoxicity_donors"][0].pop("t1d_diagnosis_confirmed", None)
    r_miss_diag = evaluate_gate30_shield_spr(c_miss_diag)

    c_bad_cohort = json.loads(json.dumps(base_pass))
    c_bad_cohort["tcell_blockade_and_apc_cytotoxicity_donors"][0]["donor_clinical_cohort"] = "NON_T1D"
    r_bad_cohort = evaluate_gate30_shield_spr(c_bad_cohort)

    c_pad_prequal = json.loads(json.dumps(base_pass))
    c_pad_prequal["tcell_blockade_and_apc_cytotoxicity_donors"][0]["t1d_prequalification_ref"] = " PREQUAL_T1D_01 "
    r_pad_prequal = evaluate_gate30_shield_spr(c_pad_prequal)
    if any(r["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT" for r in (r_miss_diag, r_bad_cohort, r_pad_prequal)):
        raise RuntimeError("Missing/invalid T1D eligibility fields must HOLD_INVALID")

    # 60 (R08 B5d): Ineligible non-T1D donor with 15/60 cytotoxicity events alongside 3 valid 0/60 T1D donors -> HOLD_INVALID (NEVER bio FAIL!),
    #               while preserving bonferroni_family_denominator_n == 4!
    c_inelig_15 = build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(15, 0, 0, 0))
    c_inelig_15["tcell_blockade_and_apc_cytotoxicity_donors"][0]["t1d_diagnosis_confirmed"] = False
    c_inelig_15["tcell_blockade_and_apc_cytotoxicity_donors"][0]["donor_clinical_cohort"] = "NON_T1D"
    r_inelig_15 = evaluate_gate30_shield_spr(c_inelig_15)
    if (
        r_inelig_15["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_inelig_15["derived_summary"]["bonferroni_family_denominator_n"] != 4
        or r_inelig_15["derived_summary"]["valid_donor_records_n"] != 3
    ):
        raise RuntimeError(f"Ineligible non-T1D donor with 15/60 must HOLD_INVALID (not bio FAIL), got {r_inelig_15}")

    # 61 (R09 B2a): Missing preregistered_donor_family_roster on [8, 0, 0]/60 AND [9, 0, 0]/60 -> HOLD_INVALID (NEVER FAIL!)
    r_no_roster_800 = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(8, 0, 0), include_preregistered_roster=False)
    )
    r_no_roster_900 = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(9, 0, 0), include_preregistered_roster=False)
    )
    if (
        r_no_roster_800["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_no_roster_800["derived_summary"]["authorization_grade_fwer_bound_valid"] is not False
        or r_no_roster_800["derived_summary"]["bonferroni_family_denominator_n"] is not None
        or r_no_roster_900["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_no_roster_900["derived_summary"]["authorization_grade_fwer_bound_valid"] is not False
    ):
        raise RuntimeError(
            f"Missing preregistered_donor_family_roster must HOLD_INVALID (NEVER FAIL), "
            f"got 800={r_no_roster_800}, 900={r_no_roster_900}"
        )

    # 62 (R09 B2b): Tampered roster_sha256 on 9-donor PASS and on [9, 0, 0]/60 -> BOTH HOLD_INVALID (NEVER PASS or FAIL!)
    c_tamper_pass = json.loads(json.dumps(base_pass))
    orig_sha = c_tamper_pass["preregistered_donor_family_roster"]["roster_sha256"]
    c_tamper_pass["preregistered_donor_family_roster"]["roster_sha256"] = ("0" if orig_sha[0] != "0" else "1") + orig_sha[1:]
    r_tamper_pass = evaluate_gate30_shield_spr(c_tamper_pass)
    c_tamper_900 = build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(9, 0, 0))
    orig_sha9 = c_tamper_900["preregistered_donor_family_roster"]["roster_sha256"]
    c_tamper_900["preregistered_donor_family_roster"]["roster_sha256"] = ("0" if orig_sha9[0] != "0" else "1") + orig_sha9[1:]
    r_tamper_900 = evaluate_gate30_shield_spr(c_tamper_900)
    if (
        r_tamper_pass["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_tamper_pass["derived_summary"]["authorization_grade_fwer_bound_valid"] is not False
        or r_tamper_900["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_tamper_900["derived_summary"]["authorization_grade_fwer_bound_valid"] is not False
    ):
        raise RuntimeError(f"Tampered roster_sha256 must HOLD_INVALID, got pass={r_tamper_pass}, fail={r_tamper_900}")

    # 63 (R09 B2c): 10-donor roster with only 3 submitted [8, 0, 0]/60 or [9, 0, 0]/60 (7 omitted) -> BOTH HOLD_INVALID (NEVER FAIL!)
    r_omit7_900 = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(9, 0, 0), planned_t1d_donor_family_n=10)
    )
    if (
        r_omit7_900["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_omit7_900["derived_summary"]["bonferroni_family_denominator_n"] != 10
        or r_omit7_900["derived_summary"]["authorization_grade_fwer_bound_valid"] is not False
        or len(r_omit7_900["derived_summary"]["missing_roster_donor_ids"]) != 7
    ):
        raise RuntimeError(f"Incomplete 10-donor roster with 7 omitted donors must HOLD_INVALID, got {r_omit7_900}")

    # 64 (R09 B2d): Full 10-donor roster [8, 0, ..., 0]/60 -> HOLD_CYTOTOXICITY_U95_EXCEEDS_5PCT (N=10, L=4.453243%),
    #               AND 10-donor roster with [9, 0, 0]/60 + 7 documented pre-assay excluded_donor_records -> FAIL (N=10, L=5.447415%)!
    r_full10_800 = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(8, 0, 0, 0, 0, 0, 0, 0, 0, 0))
    )
    excl7_recs = [
        {
            "donor_id": f"T1D_DONOR_{i:02d}",
            "pre_assay_exclusion_reason": "Pre-assay leukopak viability QC failure prior to unblinding",
            "outcome_blind_exclusion_attested": True,
        }
        for i in range(4, 11)
    ]
    r_excl7_900 = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(
            n_eff_per_donor=60,
            donor_k_obs=(9, 0, 0),
            planned_t1d_donor_family_n=10,
            excluded_donor_records=excl7_recs,
        )
    )
    if (
        r_full10_800["verdict"] != "HOLD_CYTOTOXICITY_U95_EXCEEDS_5PCT"
        or r_full10_800["derived_summary"]["bonferroni_family_denominator_n"] != 10
        or abs(r_full10_800["derived_summary"]["simultaneous_worst_donor_bonferroni_lower_pct"] - 4.453243) > 1e-4
        or r_excl7_900["verdict"] != "FAIL"
        or r_excl7_900["derived_summary"]["bonferroni_family_denominator_n"] != 10
        or abs(r_excl7_900["derived_summary"]["simultaneous_worst_donor_bonferroni_lower_pct"] - 5.447415) > 1e-4
    ):
        raise RuntimeError(f"Full 10-donor / documented exclusion check failed: full10={r_full10_800}, excl7={r_excl7_900}")

    # 65 (R09 B2e): Unrostered extra donor ID + false lock attestation + post-readout preregistration timestamp -> ALL HOLD_INVALID!
    c_unrostered = json.loads(json.dumps(base_pass))
    extra_d = json.loads(json.dumps(c_unrostered["tcell_blockade_and_apc_cytotoxicity_donors"][0]))
    extra_d["donor_id"] = "T1D_DONOR_99"
    extra_d["apc_cytotoxicity_k_obs"] = 15
    c_unrostered["tcell_blockade_and_apc_cytotoxicity_donors"].append(extra_d)
    r_unrostered = evaluate_gate30_shield_spr(c_unrostered)

    c_lock_false = json.loads(json.dumps(base_pass))
    c_lock_false["preregistered_donor_family_roster"]["outcome_blind_lock_attestation"] = False
    r_lock_false = evaluate_gate30_shield_spr(c_lock_false)

    c_late_prereg = json.loads(json.dumps(base_pass))
    c_late_prereg["assay_readout_timestamp_utc"] = "2026-11-27T23:59:59Z"
    r_late_prereg = evaluate_gate30_shield_spr(c_late_prereg)
    if (
        r_unrostered["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_unrostered["derived_summary"]["authorization_grade_fwer_bound_valid"] is not False
        or r_lock_false["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_late_prereg["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
    ):
        raise RuntimeError(
            f"Roster integrity guards failed: unrostered={r_unrostered['verdict']}, "
            f"lock_false={r_lock_false['verdict']}, late_prereg={r_late_prereg['verdict']}"
        )

    # 66 (R09 B3a): Sol's exact 3-donor zero-variance counterexample [80, 80, 80] -> HOLD (L95_CP=36.840315% < 70%, NEVER PASS!),
    #               AND 8-donor 8/8 at 80% -> HOLD (L95_CP=68.765602% < 70%, under minimum confirmatory N=9)!
    r_3don_80 = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(0, 0, 0), donor_suppressions=(80.0, 80.0, 80.0))
    )
    r_8don_80 = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(0,) * 8, donor_suppressions=(80.0,) * 8)
    )
    if (
        r_3don_80["verdict"] != "HOLD"
        or abs(r_3don_80["derived_summary"]["suppression_responder_l95_clopper_pearson_pct"] - 36.840315) > 1e-4
        or r_3don_80["derived_summary"]["suppression_student_t_authorizing"] is not False
        or r_8don_80["verdict"] != "HOLD"
        or abs(r_8don_80["derived_summary"]["suppression_responder_l95_clopper_pearson_pct"] - 68.765602) > 1e-4
    ):
        raise RuntimeError(f"Zero-variance N=3 / N=8 suppression HOLD failed: n3={r_3don_80}, n8={r_8don_80}")

    # 67 (R09 B3b): Confirmatory N=9 responder boundary: 9/9 at 80% -> PASS (L95_CP=71.687116% >= 70%);
    #               8/9 at 80% + 1/9 at 40% -> HOLD (L95_CP=57.086445% < 70%)!
    r_9of9_80 = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(0,) * 9, donor_suppressions=(80.0,) * 9)
    )
    r_8of9_80_40 = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(0,) * 9, donor_suppressions=(80.0,) * 8 + (40.0,))
    )
    if (
        r_9of9_80["verdict"] != "PASS"
        or abs(r_9of9_80["derived_summary"]["suppression_responder_l95_clopper_pearson_pct"] - 71.687116) > 1e-4
        or r_8of9_80_40["verdict"] != "HOLD"
        or abs(r_8of9_80_40["derived_summary"]["suppression_responder_l95_clopper_pearson_pct"] - 57.086445) > 1e-4
    ):
        raise RuntimeError(f"Confirmatory N=9 responder boundary failed: 9of9={r_9of9_80}, 8of9={r_8of9_80_40}")

    # 68 (R09 B3c): Anti-enhancement safety guard (min >= 0.0%): 9/10 at 80% + 1/10 at -5% -> HOLD,
    #               AND 19/20 at 80% + 1/20 at -5% (L95_CP=78.39% >= 70%, mean=75.75%) -> STILL HOLD!
    #               Also 3-donor zero-variance [30, 30, 30] -> HOLD (L95_CP_lt40=36.84% <= 60%, zero-variance FAIL proof)!
    r_enh_10 = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(0,) * 10, donor_suppressions=(80.0,) * 9 + (-5.0,))
    )
    r_enh_20 = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(0,) * 20, donor_suppressions=(80.0,) * 19 + (-5.0,))
    )
    r_3don_30 = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(0, 0, 0), donor_suppressions=(30.0, 30.0, 30.0))
    )
    if (
        r_enh_10["verdict"] != "HOLD"
        or r_enh_10["derived_summary"]["suppression_anti_enhancement_min_ge_0_passed"] is not False
        or r_enh_20["verdict"] != "HOLD"
        or r_enh_20["derived_summary"]["suppression_responder_l95_clopper_pearson_pct"] < 70.0
        or r_enh_20["derived_summary"]["suppression_anti_enhancement_min_ge_0_passed"] is not False
        or r_3don_30["verdict"] != "HOLD"
    ):
        raise RuntimeError(
            f"Anti-enhancement guard or 3-donor zero-variance FAIL guard failed: "
            f"enh10={r_enh_10['verdict']}, enh20={r_enh_20['verdict']}, n3_30={r_3don_30['verdict']}"
        )

    # 69 (R09 B3d): Exact finite-sample Binomial calibration proof across N in (3, 6, 8, 9, 10, 14, 15, 20):
    #               P(PASS | p_resp = 0.70) <= 0.05 AND P(FAIL | p_lt40 = 0.60) <= 0.05 for ALL N and ANY donor distribution!
    for n_sup_chk in (3, 6, 8, 9, 10, 14, 15, 20):
        pass_ks = [
            k_val
            for k_val in range(n_sup_chk + 1)
            if _clopper_pearson_one_sided_95_pct(k_val, n_sup_chk, alpha=0.05)[0] >= _SHIELD_SUPPRESSION_PASS_THRESHOLD_PCT
        ]
        p_false_pass = sum(_shield_binom_pmf(n_sup_chk, kv, 0.70) for kv in pass_ks)
        if p_false_pass > 0.05 + 1e-12:
            raise RuntimeError(f"Clopper-Pearson suppression false-PASS exceeded 0.05 for N={n_sup_chk}: {p_false_pass:.6f}")

        fail_ks = [
            k_val
            for k_val in range(n_sup_chk + 1)
            if _clopper_pearson_one_sided_95_pct(k_val, n_sup_chk, alpha=0.05)[0] > _SHIELD_SUPPRESSION_FAIL_L95_GT_PCT
        ]
        p_false_fail = sum(_shield_binom_pmf(n_sup_chk, kv, 0.60) for kv in fail_ks)
        if p_false_fail > 0.05 + 1e-12:
            raise RuntimeError(f"Clopper-Pearson suppression false-FAIL exceeded 0.05 for N={n_sup_chk}: {p_false_fail:.6f}")

    # 70 (R09 M1): Missing, padded, or mismatched gy018_independence_justification -> ALL HOLD_INVALID_OR_MISSING_INPUT!
    c_no_gy018 = json.loads(json.dumps(base_pass))
    c_no_gy018["tcell_blockade_and_apc_cytotoxicity_donors"][0].pop("gy018_independence_justification", None)
    r_no_gy018 = evaluate_gate30_shield_spr(c_no_gy018)

    c_pad_gy018 = json.loads(json.dumps(base_pass))
    c_pad_gy018["tcell_blockade_and_apc_cytotoxicity_donors"][0]["gy018_independence_justification"]["independent_experimental_unit"] = " Independent well unit "
    r_pad_gy018 = evaluate_gate30_shield_spr(c_pad_gy018)

    c_mis_gy018 = json.loads(json.dumps(base_pass))
    c_mis_gy018["tcell_blockade_and_apc_cytotoxicity_donors"][0]["gy018_independence_justification"]["predeclared_per_donor_unit_count_n"] = 120
    r_mis_gy018 = evaluate_gate30_shield_spr(c_mis_gy018)
    if any(r["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT" for r in (r_no_gy018, r_pad_gy018, r_mis_gy018)):
        raise RuntimeError(
            f"gy018_independence_justification enforcement failed: "
            f"missing={r_no_gy018['verdict']}, padded={r_pad_gy018['verdict']}, mismatch={r_mis_gy018['verdict']}"
        )

    # 71 (R10 B3 / 0039-B1): Roster integrity runs on ALL raw submitted donor IDs BEFORE deduplication!
    # Duplicating an unrostered donor alongside valid 18/60 cytotoxicity MUST stay HOLD_INVALID with fwer_valid=False!
    c_18_base = build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(18, 0, 0, 0, 0, 0, 0, 0, 0))
    extra_u = json.loads(json.dumps(c_18_base["tcell_blockade_and_apc_cytotoxicity_donors"][-1]))
    extra_u["donor_id"] = "T1D_DONOR_99"
    extra_u["t1d_prequalification_ref"] = "PREQUAL_T1D_DONOR_99"
    c_18_once = json.loads(json.dumps(c_18_base))
    c_18_once["tcell_blockade_and_apc_cytotoxicity_donors"].append(json.loads(json.dumps(extra_u)))
    c_18_twice = json.loads(json.dumps(c_18_once))
    c_18_twice["tcell_blockade_and_apc_cytotoxicity_donors"].append(json.loads(json.dumps(extra_u)))
    c_18_anon = json.loads(json.dumps(c_18_base))
    c_18_anon["tcell_blockade_and_apc_cytotoxicity_donors"].append({})
    r_18_once = evaluate_gate30_shield_spr(c_18_once)
    r_18_twice = evaluate_gate30_shield_spr(c_18_twice)
    r_18_anon = evaluate_gate30_shield_spr(c_18_anon)
    if (
        r_18_once["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_18_once["derived_summary"]["authorization_grade_fwer_bound_valid"] is not False
        or "T1D_DONOR_99" not in r_18_once["derived_summary"]["unrostered_submitted_donor_ids"]
        or r_18_twice["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_18_twice["derived_summary"]["authorization_grade_fwer_bound_valid"] is not False
        or "T1D_DONOR_99" not in r_18_twice["derived_summary"]["unrostered_submitted_donor_ids"]
        or "T1D_DONOR_99" not in r_18_twice["derived_summary"]["conflicted_duplicate_keys"]["donors"]
        or r_18_anon["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_18_anon["derived_summary"]["authorization_grade_fwer_bound_valid"] is not False
    ):
        raise RuntimeError(
            f"R10 duplicated/anonymous unrostered donor guard failed: "
            f"once={r_18_once['verdict']}, twice={r_18_twice['verdict']}, anon={r_18_anon['verdict']}"
        )

    # 72 (R10 B4 / 0037-B2): Fixed-roster cytotoxicity PASS requires 100% measured rostered donors!
    # 13 valid 0/60 (84%) + 1 documented pre-assay exclusion -> HOLD (NEVER PASS!), while 9/60 + 1 exclusion at N=14 -> FAIL!
    excl1_14 = [{
        "donor_id": "T1D_DONOR_14",
        "pre_assay_exclusion_reason": "Pre-assay leukopak viability QC failure prior to unblinding",
        "outcome_blind_exclusion_attested": True,
    }]
    r_excl1_14_pass_attempt = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(
            n_eff_per_donor=60,
            donor_k_obs=(0,) * 13,
            donor_suppressions=(84.0,) * 13,
            roster_donor_ids=[f"T1D_DONOR_{i:02d}" for i in range(1, 15)],
            excluded_donor_records=excl1_14,
        )
    )
    r_excl1_14_fail = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(
            n_eff_per_donor=60,
            donor_k_obs=(9,) + (0,) * 12,
            donor_suppressions=(84.0,) * 13,
            roster_donor_ids=[f"T1D_DONOR_{i:02d}" for i in range(1, 15)],
            excluded_donor_records=excl1_14,
        )
    )
    if (
        r_excl1_14_pass_attempt["verdict"] != "HOLD"
        or r_excl1_14_pass_attempt["derived_summary"]["cytotoxicity_full_roster_measured_complete"] is not False
        or r_excl1_14_pass_attempt["derived_summary"]["cytotoxicity_full_roster_u95_pct"] is not None
        or not any("INCOMPLETE_ROSTER_CYTOTOXICITY_EXCLUSION_PRECLUDES_FULL_ROSTER_PASS" in rs for rs in r_excl1_14_pass_attempt["reasons"])
        or r_excl1_14_fail["verdict"] != "FAIL"
        or r_excl1_14_fail["derived_summary"]["bonferroni_family_denominator_n"] != 14
    ):
        raise RuntimeError(
            f"R10 100%-measured cytotoxicity PASS / conservative N=14 FAIL check failed: "
            f"pass_attempt={r_excl1_14_pass_attempt['verdict']}, fail={r_excl1_14_fail['verdict']}"
        )

    # 73 (R10 B5a / 0037-B1): Clustered 3x3 shared expression batches across 9 donors -> HOLD for BOTH all-80% AND all-30%!
    r_batch3x3_80 = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(
            n_eff_per_donor=60,
            donor_k_obs=(0,) * 9,
            donor_suppressions=(80.0,) * 9,
            shared_expression_batches_n=3,
        )
    )
    r_batch3x3_30 = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(
            n_eff_per_donor=60,
            donor_k_obs=(0,) * 9,
            donor_suppressions=(30.0,) * 9,
            shared_expression_batches_n=3,
        )
    )
    # Also verify 3 separate Comp1 + 3 separate Comp2 batches shared across 9 donors -> HOLD (N_batch_clusters=3)
    c_sep_3shared = json.loads(json.dumps(c_sep_batches))
    for idx_d, d in enumerate(c_sep_3shared["tcell_blockade_and_apc_cytotoxicity_donors"]):
        d["cocktail_mixture_id"] = f"MIX_SHIELD_{(idx_d % 3) + 1:02d}"
        d["expression_batch_ids"] = [c1_ids[idx_d % 3], c2_ids[idx_d % 3]]
    r_sep_3shared = evaluate_gate30_shield_spr(c_sep_3shared)
    if (
        r_batch3x3_80["verdict"] != "HOLD"
        or r_batch3x3_80["derived_summary"]["suppression_batch_clusters_n"] != 3
        or abs(r_batch3x3_80["derived_summary"]["suppression_responder_l95_clopper_pearson_pct"] - 36.840315) > 1e-4
        or r_batch3x3_30["verdict"] != "HOLD"
        or r_batch3x3_30["derived_summary"]["suppression_batch_clusters_n"] != 3
        or abs(r_batch3x3_30["derived_summary"]["suppression_nonresponder_lt40_l95_clopper_pearson_pct"] - 36.840315) > 1e-4
        or r_sep_3shared["verdict"] != "HOLD"
        or r_sep_3shared["derived_summary"]["suppression_batch_clusters_n"] != 3
    ):
        raise RuntimeError(
            f"R10 3x3 shared batch cluster calibration failed: "
            f"all80={r_batch3x3_80['verdict']}, all30={r_batch3x3_30['verdict']}, sep3={r_sep_3shared['verdict']}"
        )

    # 74 (R10 B5a / 0039-B2): Single shared assay_run_id across 9 donors -> HOLD for BOTH all-80% AND all-30%,
    # plus staircase batch-run chaining collapsing 9 donors into 1 joint connected component -> HOLD!
    r_run1x9_80 = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(
            n_eff_per_donor=60,
            donor_k_obs=(0,) * 9,
            donor_suppressions=(80.0,) * 9,
            shared_assay_runs_n=1,
        )
    )
    r_run1x9_30 = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(
            n_eff_per_donor=60,
            donor_k_obs=(0,) * 9,
            donor_suppressions=(30.0,) * 9,
            shared_assay_runs_n=1,
        )
    )
    c_staircase = json.loads(json.dumps(base_pass))
    for idx_d, d in enumerate(c_staircase["tcell_blockade_and_apc_cytotoxicity_donors"]):
        # Alternating shared batch and shared assay_run chain across 9 valid single-mixture donors -> 1 joint component!
        b_idx = (idx_d // 2) + 1
        r_idx = ((idx_d + 1) // 2) + 1
        d["cocktail_mixture_id"] = f"MIX_SHIELD_{b_idx:02d}"
        d["expression_batch_ids"] = [f"BATCH_ECOLI_{b_idx:02d}"]
        d["assay_run_id"] = f"SHIELD_ASSAY_RUN_{r_idx:02d}"
    r_staircase = evaluate_gate30_shield_spr(c_staircase)
    if (
        r_run1x9_80["verdict"] != "HOLD"
        or r_run1x9_80["derived_summary"]["suppression_run_clusters_n"] != 1
        or abs(r_run1x9_80["derived_summary"]["suppression_responder_l95_clopper_pearson_pct"] - 5.0) > 1e-4
        or r_run1x9_30["verdict"] != "HOLD"
        or r_run1x9_30["derived_summary"]["suppression_run_clusters_n"] != 1
        or r_staircase["verdict"] != "HOLD"
        or r_staircase["derived_summary"]["suppression_independent_joint_clusters_n"] != 1
    ):
        raise RuntimeError(
            f"R10 shared-run / staircase cluster guard failed: "
            f"run80={r_run1x9_80['verdict']}, run30={r_run1x9_30['verdict']}, stair={r_staircase['verdict']}"
        )

    # 75 (R10 B5a): Missing or invalid donor_sampling_and_independence_design or missing assay_run_id -> HOLD_INVALID!
    c_no_sd = json.loads(json.dumps(base_pass))
    c_no_sd.pop("donor_sampling_and_independence_design", None)
    c_bad_sd = json.loads(json.dumps(base_pass))
    c_bad_sd["donor_sampling_and_independence_design"]["sampling_design_class"] = "CONVENIENCE_CLUSTERED"
    c_no_run = json.loads(json.dumps(base_pass))
    c_no_run["tcell_blockade_and_apc_cytotoxicity_donors"][0].pop("assay_run_id", None)
    r_no_sd = evaluate_gate30_shield_spr(c_no_sd)
    r_bad_sd = evaluate_gate30_shield_spr(c_bad_sd)
    r_no_run = evaluate_gate30_shield_spr(c_no_run)
    if (
        r_no_sd["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_no_sd["derived_summary"]["authorization_grade_suppression_inference_valid"] is not False
        or r_bad_sd["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_no_run["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
    ):
        raise RuntimeError(
            f"R10 sampling design / assay_run_id enforcement failed: "
            f"no_sd={r_no_sd['verdict']}, bad_sd={r_bad_sd['verdict']}, no_run={r_no_run['verdict']}"
        )

    # 76 (R10 B5b / 0039-B3): GY-018 explicitly clustered text AND invalid unit class / flags -> ALL HOLD_INVALID!
    c_gy_clustered_txt = json.loads(json.dumps(base_pass))
    for d in c_gy_clustered_txt["tcell_blockade_and_apc_cytotoxicity_donors"]:
        d["gy018_independence_justification"]["independent_experimental_unit"] = "Technical reads from one well only"
        d["gy018_independence_justification"]["clustering_controls"] = "None; all reads share the same well and are dependent"
    c_gy_bad_cls = json.loads(json.dumps(base_pass))
    c_gy_bad_cls["tcell_blockade_and_apc_cytotoxicity_donors"][0]["gy018_independence_justification"]["independent_unit_class"] = "TECHNICAL_REPLICATE_SINGLE_WELL"
    c_gy_bad_flag = json.loads(json.dumps(base_pass))
    c_gy_bad_flag["tcell_blockade_and_apc_cytotoxicity_donors"][0]["gy018_independence_justification"]["within_donor_units_physically_independent"] = False
    r_gy_clustered_txt = evaluate_gate30_shield_spr(c_gy_clustered_txt)
    r_gy_bad_cls = evaluate_gate30_shield_spr(c_gy_bad_cls)
    r_gy_bad_flag = evaluate_gate30_shield_spr(c_gy_bad_flag)
    if any(r["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT" for r in (r_gy_clustered_txt, r_gy_bad_cls, r_gy_bad_flag)):
        raise RuntimeError(
            f"R10 GY-018 clustered-unit rejection failed: "
            f"txt={r_gy_clustered_txt['verdict']}, cls={r_gy_bad_cls['verdict']}, flag={r_gy_bad_flag['verdict']}"
        )

    # 77 (R10 B6 / 0039-B4 / R13 0039-B2): Unified precedence — missing roster + 18/60 donor cyto -> HOLD_INVALID (fwer_valid=False),
    # whereas missing roster + valid 650-800 nM SPR FAIL -> FAIL (failure_domain=INDEPENDENT_NON_DONOR_SPR, fwer_valid=False)!
    c_noroster_cyto18 = build_valid_shield_spr_observation(
        n_eff_per_donor=60,
        donor_k_obs=(18, 0, 0, 0, 0, 0, 0, 0, 0),
        include_preregistered_roster=False,
    )
    c_noroster_sprfail = build_valid_shield_spr_observation(n_eff_per_donor=60, include_preregistered_roster=False)
    c_noroster_sprfail["on_target_analytes"][0]["ic50_l95_nm"] = 650.0
    c_noroster_sprfail["on_target_analytes"][0]["ic50_u95_nm"] = 800.0
    r_noroster_cyto18 = evaluate_gate30_shield_spr(c_noroster_cyto18)
    r_noroster_sprfail = evaluate_gate30_shield_spr(c_noroster_sprfail)
    if (
        r_noroster_cyto18["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_noroster_cyto18["derived_summary"]["authorization_grade_fwer_bound_valid"] is not False
        or r_noroster_cyto18["derived_summary"]["failure_domain"] is not None
        or r_noroster_sprfail["verdict"] != "FAIL"
        or r_noroster_sprfail["derived_summary"]["authorization_grade_fwer_bound_valid"] is not False
        or r_noroster_sprfail["derived_summary"]["failure_domain"] != "INDEPENDENT_NON_DONOR_SPR"
    ):
        raise RuntimeError(
            f"R10 unified roster vs independent SPR precedence failed: "
            f"cyto18={r_noroster_cyto18['verdict']}, sprfail={r_noroster_sprfail}"
        )

    # 78 (R10 B7 / 0039-B5): Extreme finite suppression_pct=-1e200 via BOTH direct dict AND strict JSON -> HOLD_INVALID (ZERO OverflowError!),
    # plus direct overflow-immunity check on _shield_student_t_ci_pct([-1e200, 80.0, 80.0]) and [-1e300, 1e300, 0.0]!
    c_neg1e200 = json.loads(json.dumps(base_pass))
    c_neg1e200["tcell_blockade_and_apc_cytotoxicity_donors"][0]["suppression_pct"] = -1e200
    r_neg1e200_direct = evaluate_gate30_shield_spr(c_neg1e200)
    r_neg1e200_json = evaluate_gate30_shield_spr(load_strict_json_text(json.dumps(c_neg1e200), "r10_neg1e200"))
    diag_m1, diag_l1, diag_u1 = _shield_student_t_ci_pct([-1e200, 80.0, 80.0])
    diag_m2, diag_l2, diag_u2 = _shield_student_t_ci_pct([-1e300, 1e300, 0.0])
    if (
        r_neg1e200_direct["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_neg1e200_json["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or not all(math.isfinite(x) for x in (diag_m1, diag_l1, diag_u1, diag_m2, diag_l2, diag_u2))
    ):
        raise RuntimeError(
            f"R10 -1e200 overflow-immunity check failed: "
            f"direct={r_neg1e200_direct['verdict']}, json={r_neg1e200_json['verdict']}"
        )

    # 79 (R10 M2 / 0039-M2): Native WT InsB:9-23 on-target SPR row MUST declare peptide_sequence and match register_qc peptide_reagent_lot_id!
    c_wt_noseq = json.loads(json.dumps(base_pass))
    c_wt_noseq["on_target_analytes"][3].pop("peptide_sequence", None)
    c_wt_badlot = json.loads(json.dumps(base_pass))
    c_wt_badlot["on_target_analytes"][3]["peptide_reagent_lot_id"] = "REAGENT_WT15_OTHER_LOT99"
    r_wt_noseq = evaluate_gate30_shield_spr(c_wt_noseq)
    r_wt_badlot = evaluate_gate30_shield_spr(c_wt_badlot)
    if r_wt_noseq["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT" or r_wt_badlot["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT":
        raise RuntimeError(
            f"R10 WT15 peptide_sequence / reagent lot linkage failed: "
            f"noseq={r_wt_noseq['verdict']}, badlot={r_wt_badlot['verdict']}"
        )

    # 80 (R10 M1 & Cluster Calibration Proof): External custody flag & exact cluster-level false-PASS <= 0.05 verification!
    if (
        r_pass["derived_summary"].get("external_preregistration_custody_required") is not True
        or "external" not in str(r_pass["derived_summary"].get("local_json_replay_scope_note", "")).lower()
        or "disjoint" not in str(r_pass["derived_summary"].get("suppression_statistical_boundary_note", "")).lower()
    ):
        raise RuntimeError("R10 external custody & statistical boundary metadata missing from derived_summary")
    for m_clusters in (1, 3, 5, 6, 8, 9, 12):
        pass_ks_c = [
            kv for kv in range(m_clusters + 1)
            if _clopper_pearson_one_sided_95_pct(kv, m_clusters, alpha=0.05)[0] >= _SHIELD_SUPPRESSION_PASS_THRESHOLD_PCT
        ]
        p_fp_c = sum(_shield_binom_pmf(m_clusters, kv, 0.69) for kv in pass_ks_c)
        if p_fp_c > 0.05 + 1e-12:
            raise RuntimeError(f"Cluster-level false-PASS exceeded 0.05 for M={m_clusters}: {p_fp_c:.6f}")

    # 81 (R11 0037-B1): Fixed 8:1 stratified HLA-DQ allocation, 9/9 responders across 9 distinct batches/runs -> HOLD (NOT PASS!)
    c_strat_8to1 = build_valid_shield_spr_observation(
        n_eff_per_donor=60,
        donor_k_obs=(0,) * 9,
        donor_suppressions=(80.0,) * 9,
        sampling_design_class="STRATIFIED_INDEPENDENT_T1D_HLA_DQ_COHORT",
    )
    for idx_s, d in enumerate(c_strat_8to1["tcell_blockade_and_apc_cytotoxicity_donors"]):
        d["hla_genotype"] = "HLA-DQ2.5" if idx_s < 8 else "HLA-DQ8"
    r_strat_8to1 = evaluate_gate30_shield_spr(c_strat_8to1)
    c_srs_9of9 = json.loads(json.dumps(c_strat_8to1))
    c_srs_9of9["donor_sampling_and_independence_design"]["sampling_design_class"] = (
        "SIMPLE_RANDOM_OR_CONSECUTIVE_INDEPENDENT_T1D_COHORT"
    )
    c_srs_9of9["donor_sampling_and_independence_design"]["between_donor_independence_justification"] = (
        "DISJOINT_BATCH_AND_RUN_INDEPENDENT_T1D_DONOR_COHORT"
    )
    r_srs_9of9 = evaluate_gate30_shield_spr(c_srs_9of9)
    if (
        r_strat_8to1["verdict"] != "HOLD"
        or r_strat_8to1["derived_summary"].get("donor_sampling_design_valid") is not True
        or r_strat_8to1["derived_summary"].get("suppression_inference_authorized_by_sampling_design") is not False
        or r_strat_8to1["derived_summary"].get("authorization_grade_suppression_inference_valid") is not False
        or r_strat_8to1["derived_summary"].get("authorization_grade_fwer_bound_valid") is not True
        or not any("STRATIFIED_COHORT_REQUIRES_TARGET_WEIGHTED_SUPPRESSION_ESTIMATOR" in rs for rs in r_strat_8to1["reasons"])
        or r_srs_9of9["verdict"] != "PASS"
        or r_srs_9of9["derived_summary"].get("suppression_inference_authorized_by_sampling_design") is not True
    ):
        raise RuntimeError(
            f"R11 0037-B1 8:1 stratified cohort narrowing failed: "
            f"strat={r_strat_8to1['verdict']}, srs={r_srs_9of9['verdict']}"
        )

    # 82 (R11 0039-B1): Fixed 20:1 stratified HLA-DQ allocation, 20/21 responders across 21 distinct batches/runs -> HOLD (NOT PASS!)
    c_strat_20to1 = build_valid_shield_spr_observation(
        n_eff_per_donor=60,
        donor_k_obs=(0,) * 21,
        donor_suppressions=(80.0,) * 20 + (0.0,),
        sampling_design_class="STRATIFIED_INDEPENDENT_T1D_HLA_DQ_COHORT",
    )
    for idx_s, d in enumerate(c_strat_20to1["tcell_blockade_and_apc_cytotoxicity_donors"]):
        d["hla_genotype"] = "HLA-DQ2.5" if idx_s < 20 else "HLA-DQ8"
    r_strat_20to1 = evaluate_gate30_shield_spr(c_strat_20to1)
    if (
        r_strat_20to1["verdict"] != "HOLD"
        or r_strat_20to1["derived_summary"].get("suppression_inference_authorized_by_sampling_design") is not False
        or r_strat_20to1["derived_summary"].get("authorization_grade_suppression_inference_valid") is not False
        or abs(r_strat_20to1["derived_summary"].get("suppression_responder_l95_clopper_pearson_pct", 0.0) - 79.327504) > 1e-3
        or not any("STRATIFIED_COHORT_REQUIRES_TARGET_WEIGHTED_SUPPRESSION_ESTIMATOR" in rs for rs in r_strat_20to1["reasons"])
    ):
        raise RuntimeError(f"R11 0039-B1 20:1 stratified cohort narrowing failed: {r_strat_20to1}")

    # 83 (R11 Symmetric Stratified Low-Rate & Legacy/Quota Rejection): 1:20 stratified cohort with 1/21 responder
    # and no enhancement/cyto/SPR fail -> HOLD (NOT unweighted population-rate suppression FAIL!);
    # legacy PROSPECTIVE_INDEPENDENT_T1D_DONOR_COHORT & QUOTA_* rejected as HOLD_INVALID_OR_MISSING_INPUT!
    c_strat_1to20_low = build_valid_shield_spr_observation(
        n_eff_per_donor=60,
        donor_k_obs=(0,) * 21,
        donor_suppressions=(80.0,) + (30.0,) * 20,
        sampling_design_class="STRATIFIED_INDEPENDENT_T1D_HLA_DQ_COHORT",
    )
    for idx_s, d in enumerate(c_strat_1to20_low["tcell_blockade_and_apc_cytotoxicity_donors"]):
        d["hla_genotype"] = "HLA-DQ2.5" if idx_s == 0 else "HLA-DQ8"
    r_strat_1to20_low = evaluate_gate30_shield_spr(c_strat_1to20_low)
    c_srs_1to20_low = json.loads(json.dumps(c_strat_1to20_low))
    c_srs_1to20_low["donor_sampling_and_independence_design"]["sampling_design_class"] = (
        "SIMPLE_RANDOM_OR_CONSECUTIVE_INDEPENDENT_T1D_COHORT"
    )
    c_srs_1to20_low["donor_sampling_and_independence_design"]["between_donor_independence_justification"] = (
        "DISJOINT_BATCH_AND_RUN_INDEPENDENT_T1D_DONOR_COHORT"
    )
    r_srs_1to20_low = evaluate_gate30_shield_spr(c_srs_1to20_low)
    c_legacy_prosp = json.loads(json.dumps(base_pass))
    c_legacy_prosp["donor_sampling_and_independence_design"]["sampling_design_class"] = (
        "PROSPECTIVE_INDEPENDENT_T1D_DONOR_COHORT"
    )
    r_legacy_prosp = evaluate_gate30_shield_spr(c_legacy_prosp)
    c_quota_cls = json.loads(json.dumps(base_pass))
    c_quota_cls["donor_sampling_and_independence_design"]["sampling_design_class"] = "QUOTA_INDEPENDENT_T1D_COHORT"
    r_quota_cls = evaluate_gate30_shield_spr(c_quota_cls)
    if (
        r_strat_1to20_low["verdict"] != "HOLD"
        or r_strat_1to20_low["derived_summary"].get("suppression_inference_authorized_by_sampling_design") is not False
        or r_strat_1to20_low["derived_summary"].get("failure_domain") is not None
        or not any("STRATIFIED_COHORT_REQUIRES_TARGET_WEIGHTED_SUPPRESSION_ESTIMATOR" in rs for rs in r_strat_1to20_low["reasons"])
        or r_srs_1to20_low["verdict"] != "FAIL"
        or r_srs_1to20_low["derived_summary"].get("failure_domain") != "ROSTERED_DONOR_COHORT"
        or r_legacy_prosp["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_legacy_prosp["derived_summary"].get("suppression_inference_authorized_by_sampling_design") is not False
        or r_quota_cls["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_quota_cls["derived_summary"].get("suppression_inference_authorized_by_sampling_design") is not False
    ):
        raise RuntimeError(
            f"R11 symmetric stratified low-rate / legacy / quota rejection failed: "
            f"strat_low={r_strat_1to20_low['verdict']}, srs_low={r_srs_1to20_low['verdict']}, "
            f"legacy={r_legacy_prosp['verdict']}, quota={r_quota_cls['verdict']}"
        )

    # 84 (R11 Safety Preservation on Stratified Cohorts + 0039-M1 Assay Acceptance Range):
    # Stratified cohort WITH SPR FAIL or fixed-roster Bonferroni cytotoxicity FAIL MUST still return FAIL!
    c_strat_spr_fail = json.loads(json.dumps(c_strat_8to1))
    for a in c_strat_spr_fail["on_target_analytes"]:
        if a["analyte_id"] == "HLA-DQ2.2 + HIP11":
            a["ic50_l95_nm"] = 650.0
            a["ic50_u95_nm"] = 800.0
    r_strat_spr_fail = evaluate_gate30_shield_spr(c_strat_spr_fail)

    c_strat_cyto_fail = build_valid_shield_spr_observation(
        n_eff_per_donor=60,
        donor_k_obs=(9,) + (0,) * 8,
        donor_suppressions=(80.0,) * 9,
        sampling_design_class="STRATIFIED_INDEPENDENT_T1D_HLA_DQ_COHORT",
    )
    r_strat_cyto_fail = evaluate_gate30_shield_spr(c_strat_cyto_fail)

    c_strat_enh = json.loads(json.dumps(c_strat_8to1))
    c_strat_enh["tcell_blockade_and_apc_cytotoxicity_donors"][-1]["suppression_pct"] = -5.0
    r_strat_enh = evaluate_gate30_shield_spr(c_strat_enh)

    if (
        r_strat_spr_fail["verdict"] != "FAIL"
        or r_strat_spr_fail["derived_summary"].get("failure_domain") != "INDEPENDENT_NON_DONOR_SPR"
        or r_strat_spr_fail["derived_summary"].get("suppression_inference_authorized_by_sampling_design") is not False
        or r_strat_cyto_fail["verdict"] != "FAIL"
        or r_strat_cyto_fail["derived_summary"].get("failure_domain") != "ROSTERED_DONOR_COHORT"
        or r_strat_cyto_fail["derived_summary"].get("authorization_grade_fwer_bound_valid") is not True
        or r_strat_cyto_fail["derived_summary"].get("suppression_inference_authorized_by_sampling_design") is not False
        or r_strat_enh["verdict"] != "HOLD"
        or r_strat_enh["derived_summary"].get("suppression_anti_enhancement_min_ge_0_passed") is not False
        or not any("anti-enhancement" in rs.lower() for rs in r_strat_enh["reasons"])
        or not any("STRATIFIED_COHORT_REQUIRES_TARGET_WEIGHTED_SUPPRESSION_ESTIMATOR" in rs for rs in r_strat_enh["reasons"])
        or r_pass["derived_summary"].get("suppression_assay_acceptance_range_pct") != [-1000.0, 100.0]
    ):
        raise RuntimeError(
            f"R11 stratified safety preservation / M1 assay acceptance range check failed: "
            f"spr={r_strat_spr_fail['verdict']}, cyto={r_strat_cyto_fail['verdict']}, enh={r_strat_enh['verdict']}"
        )

    # 85 (R12 0039-B1): Mandatory WT15 & HIP11 register-QC reconciliation strictly BEFORE biological adjudication
    # and BEFORE batch-linkage credit!
    c_wt_match_fail = json.loads(json.dumps(base_pass))
    c_wt_match_fail["on_target_analytes"][3]["ic50_l95_nm"] = 650.0
    c_wt_match_fail["on_target_analytes"][3]["ic50_u95_nm"] = 800.0
    r_wt_match_fail = evaluate_gate30_shield_spr(c_wt_match_fail)

    c_wt_mis_fail = json.loads(json.dumps(c_wt_match_fail))
    c_wt_mis_fail["on_target_analytes"][3]["peptide_reagent_lot_id"] = "REAGENT_WT15_OTHER_LOT99"
    r_wt_mis_fail = evaluate_gate30_shield_spr(c_wt_mis_fail)

    c_wt_mis_plus_c1_fail = json.loads(json.dumps(c_wt_badlot))
    c_wt_mis_plus_c1_fail["on_target_analytes"][0]["ic50_l95_nm"] = 650.0
    c_wt_mis_plus_c1_fail["on_target_analytes"][0]["ic50_u95_nm"] = 800.0
    r_wt_mis_plus_c1_fail = evaluate_gate30_shield_spr(c_wt_mis_plus_c1_fail)

    c_wt_lcms_bad_fail = json.loads(json.dumps(c_wt_match_fail))
    c_wt_lcms_bad_fail["register_qc_records"]["native_wt_insb9_23_15aa"]["lcms_identity_passed"] = False
    r_wt_lcms_bad_fail = evaluate_gate30_shield_spr(c_wt_lcms_bad_fail)

    c_wt_6dfx_bad_fail = json.loads(json.dumps(c_wt_match_fail))
    c_wt_6dfx_bad_fail["register_qc_records"]["engineered_6dfx_p8e9e_12aa"]["qc_passed"] = False
    r_wt_6dfx_bad_fail = evaluate_gate30_shield_spr(c_wt_6dfx_bad_fail)

    c_hip11_qc_bad_c1_fail = json.loads(json.dumps(base_pass))
    c_hip11_qc_bad_c1_fail["register_qc_records"]["hip11_dq25_dq8t_dq22_exchange_qc_passed"] = False
    c_hip11_qc_bad_c1_fail["on_target_analytes"][0]["ic50_l95_nm"] = 650.0
    c_hip11_qc_bad_c1_fail["on_target_analytes"][0]["ic50_u95_nm"] = 800.0
    r_hip11_qc_bad_c1_fail = evaluate_gate30_shield_spr(c_hip11_qc_bad_c1_fail)

    c_hip11_qc_bad_wt_fail = json.loads(json.dumps(c_wt_match_fail))
    c_hip11_qc_bad_wt_fail["register_qc_records"]["hip11_dq25_dq8t_dq22_exchange_qc_passed"] = False
    r_hip11_qc_bad_wt_fail = evaluate_gate30_shield_spr(c_hip11_qc_bad_wt_fail)

    # Batch-linkage credit test: 3rd Comp2 batch referenced ONLY on mismatched WT15 must NOT receive batch credit!
    c_wt_nocredit = json.loads(json.dumps(base_pass))
    c_wt_nocredit["register_qc_records"]["expression_batch_ids"] = ["BATCH_ECOLI_01", "BATCH_ECOLI_02"]
    c_wt_nocredit["register_qc_records"]["crystal_ref_1jk8_14aa"] = None
    for off_r in c_wt_nocredit["off_target_controls"]:
        if off_r["analyte_id"] in _SHIELD_MANDATORY_COMP2_OFF_TARGET_CONTROLS:
            off_r["expression_batch_ids"] = ["BATCH_ECOLI_01", "BATCH_ECOLI_02"]
    for cmp_r in c_wt_nocredit["comp2_comparators_screened"]:
        if cmp_r["comparator_id"] == _SHIELD_COMP2_LEAD:
            cmp_r["expression_batch_ids"] = ["BATCH_ECOLI_01", "BATCH_ECOLI_02"]
            for cond_v in cmp_r["register_control_screens"].values():
                if isinstance(cond_v, dict):
                    cond_v["expression_batch_ids"] = ["BATCH_ECOLI_01", "BATCH_ECOLI_02"]
    c_wt_nocredit["on_target_analytes"][3]["expression_batch_ids"] = ["BATCH_ECOLI_01", "BATCH_ECOLI_02", "BATCH_ECOLI_03"]
    c_wt_nocredit["on_target_analytes"][3]["peptide_reagent_lot_id"] = "REAGENT_WT15_OTHER_LOT99"
    r_wt_nocredit = evaluate_gate30_shield_spr(c_wt_nocredit)
    if (
        r_wt_match_fail["verdict"] != "FAIL"
        or r_wt_match_fail["derived_summary"].get("failure_domain") != "INDEPENDENT_NON_DONOR_SPR"
        or r_wt_mis_fail["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or any(rs.startswith("[FAIL]") for rs in r_wt_mis_fail["reasons"])
        or r_wt_mis_fail["analytes_verified_count"] != 3
        or r_wt_mis_plus_c1_fail["verdict"] != "FAIL"
        or r_wt_mis_plus_c1_fail["derived_summary"].get("failure_domain") != "INDEPENDENT_NON_DONOR_SPR"
        or r_wt_lcms_bad_fail["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or any(rs.startswith("[FAIL]") for rs in r_wt_lcms_bad_fail["reasons"])
        or r_wt_6dfx_bad_fail["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or any(rs.startswith("[FAIL]") for rs in r_wt_6dfx_bad_fail["reasons"])
        or r_hip11_qc_bad_c1_fail["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or any(rs.startswith("[FAIL]") for rs in r_hip11_qc_bad_c1_fail["reasons"])
        or r_hip11_qc_bad_wt_fail["verdict"] != "FAIL"
        or r_wt_nocredit["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_wt_nocredit["derived_summary"]["distinct_linked_comp2_assay_batches_count"] != 2
    ):
        raise RuntimeError(
            f"R12 0039-B1 pre-adjudication WT15/HIP11 register-QC reconciliation failed: "
            f"match={r_wt_match_fail['verdict']}, mis={r_wt_mis_fail['verdict']}, "
            f"mis_c1={r_wt_mis_plus_c1_fail['verdict']}, lcms={r_wt_lcms_bad_fail['verdict']}, "
            f"6dfx={r_wt_6dfx_bad_fail['verdict']}, hip11_c1={r_hip11_qc_bad_c1_fail['verdict']}, "
            f"hip11_wt={r_hip11_qc_bad_wt_fail['verdict']}, nocredit={r_wt_nocredit['derived_summary']}"
        )

    # 86 (R12 0037-B2): Sol's 14-donor 1-component bridge-donor counterexample (with valid per-mixture bindings!) —
    # donors 0..13 form 1 joint connected component via alternating batch/run links; corrupting an unrelated optional
    # APC CI on the 6 internal bridge donors MUST retain their batch/run Union-Find links (staying 1 component,
    # HOLD_INVALID, 0 FAIL reasons) and NEVER shatter into 8 independent components / L95=68.77% false suppression FAIL;
    # corrupting bridge batch/run topology itself blocks suppression inference (HOLD_INVALID) while preserving
    # independent SPR FAIL & fixed-roster Bonferroni cyto FAIL!
    c_bridge14 = build_valid_shield_spr_observation(
        n_eff_per_donor=60,
        donor_k_obs=(0,) * 14,
        donor_suppressions=(20.0,) * 14,
    )
    for idx_b14, d_b14 in enumerate(c_bridge14["tcell_blockade_and_apc_cytotoxicity_donors"]):
        b_idx = (idx_b14 // 2) + 1
        r_idx = ((idx_b14 + 1) // 2) + 1
        d_b14["cocktail_mixture_id"] = f"MIX_SHIELD_{b_idx:02d}"
        d_b14["expression_batch_ids"] = [f"BATCH_ECOLI_{b_idx:02d}"]
        d_b14["assay_run_id"] = f"SHIELD_ASSAY_RUN_{r_idx:02d}"
    r_bridge14_clean = evaluate_gate30_shield_spr(c_bridge14)

    c_bridge14_bad_ci = json.loads(json.dumps(c_bridge14))
    for b_pos in (1, 3, 5, 7, 9, 11):
        c_bridge14_bad_ci["tcell_blockade_and_apc_cytotoxicity_donors"][b_pos]["apc_cytotoxicity_l95_pct"] = 2.0
    r_bridge14_bad_ci = evaluate_gate30_shield_spr(c_bridge14_bad_ci)

    c_bridge14_no_batch = json.loads(json.dumps(c_bridge14))
    c_bridge14_no_batch["tcell_blockade_and_apc_cytotoxicity_donors"][1]["expression_batch_ids"] = []
    r_bridge14_no_batch = evaluate_gate30_shield_spr(c_bridge14_no_batch)

    c_bridge14_no_run = json.loads(json.dumps(c_bridge14))
    c_bridge14_no_run["tcell_blockade_and_apc_cytotoxicity_donors"][1]["assay_run_id"] = ""
    r_bridge14_no_run = evaluate_gate30_shield_spr(c_bridge14_no_run)

    c_bridge14_no_batch_spr_fail = json.loads(json.dumps(c_bridge14_no_batch))
    c_bridge14_no_batch_spr_fail["on_target_analytes"][0]["ic50_l95_nm"] = 650.0
    c_bridge14_no_batch_spr_fail["on_target_analytes"][0]["ic50_u95_nm"] = 800.0
    r_bridge14_no_batch_spr_fail = evaluate_gate30_shield_spr(c_bridge14_no_batch_spr_fail)

    c_bridge14_no_batch_cyto_fail = json.loads(json.dumps(c_bridge14_no_batch))
    c_bridge14_no_batch_cyto_fail["tcell_blockade_and_apc_cytotoxicity_donors"][0]["apc_cytotoxicity_k_obs"] = 18
    r_bridge14_no_batch_cyto_fail = evaluate_gate30_shield_spr(c_bridge14_no_batch_cyto_fail)

    if (
        r_bridge14_clean["verdict"] != "HOLD"
        or r_bridge14_clean["derived_summary"]["suppression_independent_joint_clusters_n"] != 1
        or abs(r_bridge14_clean["derived_summary"]["suppression_nonresponder_lt40_l95_clopper_pearson_pct"] - 5.0) > 1e-4
        or r_bridge14_bad_ci["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_bridge14_bad_ci["derived_summary"]["suppression_independent_joint_clusters_n"] != 1
        or any(rs.startswith("[FAIL]") for rs in r_bridge14_bad_ci["reasons"])
        or r_bridge14_no_batch["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_bridge14_no_batch["derived_summary"]["donor_topology_complete_for_suppression"] is not False
        or any(rs.startswith("[FAIL]") for rs in r_bridge14_no_batch["reasons"])
        or r_bridge14_no_run["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_bridge14_no_run["derived_summary"]["donor_topology_complete_for_suppression"] is not False
        or any(rs.startswith("[FAIL]") for rs in r_bridge14_no_run["reasons"])
        or r_bridge14_no_batch_spr_fail["verdict"] != "FAIL"
        or r_bridge14_no_batch_cyto_fail["verdict"] != "FAIL"
    ):
        raise RuntimeError(
            f"R12 0037-B2 14-donor bridge-donor topology retention failed: "
            f"clean={r_bridge14_clean['verdict']}(c={r_bridge14_clean['derived_summary'].get('suppression_independent_joint_clusters_n')}), "
            f"bad_ci={r_bridge14_bad_ci['verdict']}(c={r_bridge14_bad_ci['derived_summary'].get('suppression_independent_joint_clusters_n')}), "
            f"no_batch={r_bridge14_no_batch['verdict']}, no_run={r_bridge14_no_run['verdict']}, "
            f"spr_fail={r_bridge14_no_batch_spr_fail['verdict']}, cyto_fail={r_bridge14_no_batch_cyto_fail['verdict']}"
        )

    # 87 (R12 0037-B3): Strict canonical allowlist & closed schema on gy018_independence_justification & sampling design
    # (KILLS free-text regex arms race! Rejects Sol's microscopy-fields string, arbitrary prose, cross-class mismatch,
    # and extra keys while accepting exact class-bound canonical droplet/colony tokens!)
    c_gy_microscopy = json.loads(json.dumps(base_pass))
    c_gy_microscopy["tcell_blockade_and_apc_cytotoxicity_donors"][0]["gy018_independence_justification"]["independent_experimental_unit"] = (
        "four microscopy fields within each replicate well"
    )
    r_gy_microscopy = evaluate_gate30_shield_spr(c_gy_microscopy)

    c_gy_freetext = json.loads(json.dumps(base_pass))
    c_gy_freetext["tcell_blockade_and_apc_cytotoxicity_donors"][0]["gy018_independence_justification"]["independent_experimental_unit"] = (
        "custom lab description of assay units without banned words"
    )
    r_gy_freetext = evaluate_gate30_shield_spr(c_gy_freetext)

    c_gy_cross_cls = json.loads(json.dumps(base_pass))
    c_gy_cross_cls["tcell_blockade_and_apc_cytotoxicity_donors"][0]["gy018_independence_justification"]["independent_experimental_unit"] = (
        "INDEPENDENT_DROPLET_PARTITION"
    )
    r_gy_cross_cls = evaluate_gate30_shield_spr(c_gy_cross_cls)

    c_gy_extra_key = json.loads(json.dumps(base_pass))
    c_gy_extra_key["tcell_blockade_and_apc_cytotoxicity_donors"][0]["gy018_independence_justification"]["notes"] = (
        "four fields per well counted separately"
    )
    r_gy_extra_key = evaluate_gate30_shield_spr(c_gy_extra_key)

    c_sd_freetext = json.loads(json.dumps(base_pass))
    c_sd_freetext["donor_sampling_and_independence_design"]["between_donor_independence_justification"] = (
        "custom arbitrary prose statement describing donor sampling"
    )
    r_sd_freetext = evaluate_gate30_shield_spr(c_sd_freetext)

    # R14 0039-B1: Class-specific sampling justification — contradictory class vs justification MUST HOLD_INVALID
    # in BOTH high-suppression (84%) and low-suppression (30%) directions (and in BOTH cross-class directions!),
    # while preserving independent SPR FAIL and fixed-roster Bonferroni cytotoxicity FAIL!
    c_sd_contra_srs_hi = build_valid_shield_spr_observation(n_eff_per_donor=60, donor_suppressions=(84.0,) * 9)
    c_sd_contra_srs_hi["donor_sampling_and_independence_design"]["between_donor_independence_justification"] = (
        "STRATIFIED_DISJOINT_BATCH_AND_RUN_T1D_DONOR_COHORT"
    )
    r_sd_contra_srs_hi = evaluate_gate30_shield_spr(c_sd_contra_srs_hi)

    c_sd_contra_srs_lo = build_valid_shield_spr_observation(n_eff_per_donor=60, donor_suppressions=(30.0,) * 9)
    c_sd_contra_srs_lo["donor_sampling_and_independence_design"]["between_donor_independence_justification"] = (
        "STRATIFIED_DISJOINT_BATCH_AND_RUN_T1D_DONOR_COHORT"
    )
    r_sd_contra_srs_lo = evaluate_gate30_shield_spr(c_sd_contra_srs_lo)

    c_sd_contra_strat_hi = build_valid_shield_spr_observation(
        n_eff_per_donor=60,
        donor_suppressions=(84.0,) * 9,
        sampling_design_class="STRATIFIED_INDEPENDENT_T1D_HLA_DQ_COHORT",
    )
    c_sd_contra_strat_hi["donor_sampling_and_independence_design"]["between_donor_independence_justification"] = (
        "DISJOINT_BATCH_AND_RUN_INDEPENDENT_T1D_DONOR_COHORT"
    )
    r_sd_contra_strat_hi = evaluate_gate30_shield_spr(c_sd_contra_strat_hi)

    c_sd_contra_strat_lo = build_valid_shield_spr_observation(
        n_eff_per_donor=60,
        donor_suppressions=(30.0,) * 9,
        sampling_design_class="STRATIFIED_INDEPENDENT_T1D_HLA_DQ_COHORT",
    )
    c_sd_contra_strat_lo["donor_sampling_and_independence_design"]["between_donor_independence_justification"] = (
        "DISJOINT_BATCH_AND_RUN_INDEPENDENT_T1D_DONOR_COHORT"
    )
    r_sd_contra_strat_lo = evaluate_gate30_shield_spr(c_sd_contra_strat_lo)

    c_sd_contra_plus_spr = json.loads(json.dumps(c_sd_contra_srs_hi))
    c_sd_contra_plus_spr["on_target_analytes"][3]["ic50_l95_nm"] = 650.0
    c_sd_contra_plus_spr["on_target_analytes"][3]["ic50_u95_nm"] = 800.0
    r_sd_contra_plus_spr = evaluate_gate30_shield_spr(c_sd_contra_plus_spr)

    c_sd_contra_plus_cyto = build_valid_shield_spr_observation(
        n_eff_per_donor=60,
        donor_k_obs=(18,) + (0,) * 8,
        donor_suppressions=(84.0,) * 9,
    )
    c_sd_contra_plus_cyto["donor_sampling_and_independence_design"]["between_donor_independence_justification"] = (
        "STRATIFIED_DISJOINT_BATCH_AND_RUN_T1D_DONOR_COHORT"
    )
    r_sd_contra_plus_cyto = evaluate_gate30_shield_spr(c_sd_contra_plus_cyto)

    c_gy_droplet_ok = json.loads(json.dumps(base_pass))
    c_gy_droplet_ok["tcell_blockade_and_apc_cytotoxicity_donors"][0]["gy018_independence_justification"]["independent_unit_class"] = (
        "INDEPENDENT_DROPLET_PARTITIONS"
    )
    c_gy_droplet_ok["tcell_blockade_and_apc_cytotoxicity_donors"][0]["gy018_independence_justification"]["independent_experimental_unit"] = (
        "INDEPENDENT_DROPLET_PARTITION"
    )
    c_gy_droplet_ok["tcell_blockade_and_apc_cytotoxicity_donors"][0]["gy018_independence_justification"]["clustering_controls"] = (
        "ISOLATED_DROPLET_PARTITIONS_INDEPENDENT_LOADING_NO_POOLING"
    )
    r_gy_droplet_ok = evaluate_gate30_shield_spr(c_gy_droplet_ok)

    if (
        r_gy_microscopy["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_gy_freetext["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_gy_cross_cls["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_gy_extra_key["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_sd_freetext["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_sd_contra_srs_hi["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_sd_contra_srs_hi["derived_summary"]["donor_sampling_design_valid"] is not False
        or r_sd_contra_srs_hi["derived_summary"]["authorization_grade_suppression_inference_valid"] is not False
        or r_sd_contra_srs_lo["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or any(rs.startswith("[FAIL]") for rs in r_sd_contra_srs_lo["reasons"])
        or r_sd_contra_srs_lo["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
        or r_sd_contra_strat_hi["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_sd_contra_strat_lo["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or any(rs.startswith("[FAIL]") for rs in r_sd_contra_strat_lo["reasons"])
        or r_sd_contra_plus_spr["verdict"] != "FAIL"
        or r_sd_contra_plus_spr["derived_summary"]["failure_domain"] != "INDEPENDENT_NON_DONOR_SPR"
        or r_sd_contra_plus_cyto["verdict"] != "FAIL"
        or r_sd_contra_plus_cyto["derived_summary"]["failure_domain"] != "ROSTERED_DONOR_COHORT"
        or r_gy_droplet_ok["verdict"] != "PASS"
    ):
        raise RuntimeError(
            f"R12 0037-B3 / R14 0039-B1 strict GY-018/sampling class-specific allowlist check failed: "
            f"micro={r_gy_microscopy['verdict']}, free={r_gy_freetext['verdict']}, "
            f"cross={r_gy_cross_cls['verdict']}, extra={r_gy_extra_key['verdict']}, "
            f"sd_free={r_sd_freetext['verdict']}, srs_hi={r_sd_contra_srs_hi['verdict']}, "
            f"srs_lo={r_sd_contra_srs_lo['verdict']}, strat_hi={r_sd_contra_strat_hi['verdict']}, "
            f"strat_lo={r_sd_contra_strat_lo['verdict']}, spr={r_sd_contra_plus_spr['verdict']}, "
            f"cyto={r_sd_contra_plus_cyto['verdict']}, droplet_ok={r_gy_droplet_ok['verdict']}"
        )

    # 88 (R12 0039-M1): Non-authorizing diagnostic suppression Student-t interval MUST NEVER invert on negative values!
    # Nine identical -5.0% observations -> FAIL (9/9 < 40%) with L=-5.0%, mean=-5.0%, U=-5.0%;
    # three identical -5.0% observations -> HOLD (anti-enhancement) with L=-5.0%, mean=-5.0%, U=-5.0%;
    # varied negative observations -> strictly non-inverted L <= mean <= U < 0.0%!
    r_neg5_all = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(n_eff_per_donor=60, donor_suppressions=(-5.0,) * 9)
    )
    r_neg5_n3 = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(n_eff_per_donor=60, donor_suppressions=(-5.0,) * 3)
    )
    r_neg_var = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(
            n_eff_per_donor=60,
            donor_suppressions=(-12.0, -8.0, -5.0, -6.0, -9.0, -4.0, -7.0, -10.0, -3.0),
        )
    )
    n5_ds = r_neg5_all["derived_summary"]
    n3_ds = r_neg5_n3["derived_summary"]
    nv_ds = r_neg_var["derived_summary"]
    if (
        r_neg5_all["verdict"] != "FAIL"
        or n5_ds["suppression_mean_pct"] != -5.0
        or n5_ds["suppression_l95_t_diagnostic_only_pct"] != -5.0
        or n5_ds["suppression_u95_t_diagnostic_only_pct"] != -5.0
        or r_neg5_n3["verdict"] != "HOLD"
        or n3_ds["suppression_mean_pct"] != -5.0
        or n3_ds["suppression_l95_t_diagnostic_only_pct"] != -5.0
        or n3_ds["suppression_u95_t_diagnostic_only_pct"] != -5.0
        or r_neg_var["verdict"] != "FAIL"
        or not (nv_ds["suppression_l95_t_diagnostic_only_pct"] <= nv_ds["suppression_mean_pct"] <= nv_ds["suppression_u95_t_diagnostic_only_pct"] < 0.0)
    ):
        raise RuntimeError(
            f"R12 0039-M1 signed non-inverted Student-t suppression diagnostic failed: "
            f"neg5_n9={r_neg5_all['verdict']}:{n5_ds.get('suppression_l95_t_diagnostic_only_pct')}/{n5_ds.get('suppression_mean_pct')}/{n5_ds.get('suppression_u95_t_diagnostic_only_pct')}, "
            f"neg5_n3={r_neg5_n3['verdict']}:{n3_ds.get('suppression_l95_t_diagnostic_only_pct')}/{n3_ds.get('suppression_mean_pct')}/{n3_ds.get('suppression_u95_t_diagnostic_only_pct')}, "
            f"neg_var={r_neg_var['verdict']}:{nv_ds.get('suppression_l95_t_diagnostic_only_pct')}/{nv_ds.get('suppression_mean_pct')}/{nv_ds.get('suppression_u95_t_diagnostic_only_pct')}"
        )

    # 89 (R13 0039-B1 / 0037-B2): HIP11 register-QC MUST require parent register_qc_records batch validation!
    # Invalid register_qc_records.expression_batch_ids with hip11_exchange_qc_passed=True + failing Comp1 HIP11
    # MUST return HOLD_INVALID_OR_MISSING_INPUT (0 [FAIL] reasons, 0 analytes_verified, 0 Comp1 batch credit),
    # while an independent non-HIP11/non-WT15 SPR failure still triggers fail-first FAIL!
    c_hip11_bad_rqc_batch = json.loads(json.dumps(base_pass))
    c_hip11_bad_rqc_batch["register_qc_records"]["expression_batch_ids"] = ["BATCH_UNDECLARED_99"]
    c_hip11_bad_rqc_batch["on_target_analytes"][0]["ic50_l95_nm"] = 650.0
    c_hip11_bad_rqc_batch["on_target_analytes"][0]["ic50_u95_nm"] = 800.0
    r_hip11_bad_rqc_batch = evaluate_gate30_shield_spr(c_hip11_bad_rqc_batch)

    c_hip11_bad_rqc_nocredit = json.loads(json.dumps(base_pass))
    c_hip11_bad_rqc_nocredit["register_qc_records"]["expression_batch_ids"] = ["BATCH_UNDECLARED_99"]
    for off_r in c_hip11_bad_rqc_nocredit["off_target_controls"]:
        if off_r["analyte_id"] in _SHIELD_MANDATORY_COMP1_OFF_TARGET_CONTROLS:
            off_r["expression_batch_ids"] = ["BATCH_ECOLI_01", "BATCH_ECOLI_02"]
    c_hip11_bad_rqc_nocredit["on_target_analytes"][0]["expression_batch_ids"] = [
        "BATCH_ECOLI_01", "BATCH_ECOLI_02", "BATCH_ECOLI_03"
    ]
    r_hip11_bad_rqc_nocredit = evaluate_gate30_shield_spr(c_hip11_bad_rqc_nocredit)

    c_hip11_bad_rqc_plus_ind_spr = json.loads(json.dumps(c_hip11_bad_rqc_batch))
    for off_r in c_hip11_bad_rqc_plus_ind_spr["off_target_controls"]:
        if off_r["analyte_id"] == "HLA-DQ8 + DQ8-glia-gamma1a":
            off_r["selectivity_l95_fold"] = 3.0
            off_r["selectivity_u95_fold"] = 6.0
    r_hip11_bad_rqc_plus_ind_spr = evaluate_gate30_shield_spr(c_hip11_bad_rqc_plus_ind_spr)

    # R14 0039-B2: Disjoint Comp2-only (or even disjoint dual-construct) parent register_qc_records batch
    # unreferenced by Comp1 HIP11 rows MUST NOT pass or grant Comp1 HIP11 QC credit; missing/mismatched
    # HIP11 peptide_reagent_lot_id on a Comp1 HIP11 row MUST quarantine that row to HOLD_INVALID!
    c_hip11_disjoint_c2 = json.loads(json.dumps(base_pass))
    c_hip11_disjoint_c2["expression_batches"].append(
        {"batch_id": "COMP2_QC_ONLY", "construct_ids": [_SHIELD_COMP2_LEAD], "qc_passed": True}
    )
    c_hip11_disjoint_c2["register_qc_records"]["expression_batch_ids"] = ["COMP2_QC_ONLY"]
    r_hip11_disjoint_c2 = evaluate_gate30_shield_spr(c_hip11_disjoint_c2)

    c_hip11_disjoint_c2_bad_c1 = json.loads(json.dumps(c_hip11_disjoint_c2))
    c_hip11_disjoint_c2_bad_c1["on_target_analytes"][0]["ic50_l95_nm"] = 650.0
    c_hip11_disjoint_c2_bad_c1["on_target_analytes"][0]["ic50_u95_nm"] = 800.0
    r_hip11_disjoint_c2_bad_c1 = evaluate_gate30_shield_spr(c_hip11_disjoint_c2_bad_c1)

    c_hip11_disjoint_both = json.loads(json.dumps(base_pass))
    c_hip11_disjoint_both["expression_batches"].append(
        {"batch_id": "BOTH_QC_ONLY", "construct_ids": list(_SHIELD_COCKTAIL_LEADS), "qc_passed": True}
    )
    c_hip11_disjoint_both["register_qc_records"]["expression_batch_ids"] = ["BOTH_QC_ONLY"]
    c_hip11_disjoint_both["on_target_analytes"][0]["ic50_l95_nm"] = 650.0
    c_hip11_disjoint_both["on_target_analytes"][0]["ic50_u95_nm"] = 800.0
    r_hip11_disjoint_both = evaluate_gate30_shield_spr(c_hip11_disjoint_both)

    c_hip11_wrong_lot = json.loads(json.dumps(base_pass))
    c_hip11_wrong_lot["on_target_analytes"][0]["peptide_reagent_lot_id"] = "REAGENT_HIP11_WRONG_LOT99"
    c_hip11_wrong_lot["on_target_analytes"][0]["ic50_l95_nm"] = 650.0
    c_hip11_wrong_lot["on_target_analytes"][0]["ic50_u95_nm"] = 800.0
    r_hip11_wrong_lot = evaluate_gate30_shield_spr(c_hip11_wrong_lot)

    if (
        r_hip11_bad_rqc_batch["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or any(rs.startswith("[FAIL]") for rs in r_hip11_bad_rqc_batch["reasons"])
        or r_hip11_bad_rqc_batch["analytes_verified_count"] != 0
        or r_hip11_bad_rqc_nocredit["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_hip11_bad_rqc_nocredit["derived_summary"]["distinct_linked_comp1_assay_batches_count"] != 2
        or r_hip11_bad_rqc_plus_ind_spr["verdict"] != "FAIL"
        or r_hip11_bad_rqc_plus_ind_spr["derived_summary"]["failure_domain"] != "INDEPENDENT_NON_DONOR_SPR"
        or r_hip11_disjoint_c2["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_hip11_disjoint_c2_bad_c1["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or any(rs.startswith("[FAIL]") for rs in r_hip11_disjoint_c2_bad_c1["reasons"])
        or r_hip11_disjoint_c2_bad_c1["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
        or r_hip11_disjoint_both["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or any(rs.startswith("[FAIL]") for rs in r_hip11_disjoint_both["reasons"])
        or r_hip11_wrong_lot["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or any(rs.startswith("[FAIL]") for rs in r_hip11_wrong_lot["reasons"])
    ):
        raise RuntimeError(
            f"R13/R14 0039-B1/B2 HIP11 parent-batch & reagent-lot register-QC binding failed: "
            f"bad_batch={r_hip11_bad_rqc_batch['verdict']}, nocredit={r_hip11_bad_rqc_nocredit['derived_summary']}, "
            f"ind_spr={r_hip11_bad_rqc_plus_ind_spr['verdict']}, disj_c2={r_hip11_disjoint_c2['verdict']}, "
            f"disj_c2_badc1={r_hip11_disjoint_c2_bad_c1['verdict']}, disj_both={r_hip11_disjoint_both['verdict']}, "
            f"wrong_lot={r_hip11_wrong_lot['verdict']}"
        )

    # 90 (R13 0039-B1 / 0037-B2): Cross-allele WT15 off-target row (HLA-DQ8-trans + WT InsB:9-23) MUST bind
    # its own peptide_sequence & exact unpadded peptide_reagent_lot_id to register_qc_records BEFORE bio FAIL & batch credit!
    c_off_wt_match_fail = json.loads(json.dumps(base_pass))
    for off_r in c_off_wt_match_fail["off_target_controls"]:
        if off_r["analyte_id"] == "HLA-DQ8-trans + WT InsB:9-23":
            off_r["selectivity_l95_fold"] = 3.0
            off_r["selectivity_u95_fold"] = 6.0
    r_off_wt_match_fail = evaluate_gate30_shield_spr(c_off_wt_match_fail)

    c_off_wt_missing_lot = json.loads(json.dumps(c_off_wt_match_fail))
    for off_r in c_off_wt_missing_lot["off_target_controls"]:
        if off_r["analyte_id"] == "HLA-DQ8-trans + WT InsB:9-23":
            off_r.pop("peptide_reagent_lot_id", None)
    r_off_wt_missing_lot = evaluate_gate30_shield_spr(c_off_wt_missing_lot)

    c_off_wt_wrong_lot = json.loads(json.dumps(c_off_wt_match_fail))
    for off_r in c_off_wt_wrong_lot["off_target_controls"]:
        if off_r["analyte_id"] == "HLA-DQ8-trans + WT InsB:9-23":
            off_r["peptide_reagent_lot_id"] = "REAGENT_WT15_CONFLICT_LOT99"
    r_off_wt_wrong_lot = evaluate_gate30_shield_spr(c_off_wt_wrong_lot)

    c_off_wt_wrong_seq = json.loads(json.dumps(c_off_wt_match_fail))
    for off_r in c_off_wt_wrong_seq["off_target_controls"]:
        if off_r["analyte_id"] == "HLA-DQ8-trans + WT InsB:9-23":
            off_r["peptide_sequence"] = "LVEALYLVCGERGG"
    r_off_wt_wrong_seq = evaluate_gate30_shield_spr(c_off_wt_wrong_seq)

    c_off_wt_nocredit = json.loads(json.dumps(base_pass))
    c_off_wt_nocredit["register_qc_records"]["expression_batch_ids"] = ["BATCH_ECOLI_01", "BATCH_ECOLI_02"]
    c_off_wt_nocredit["register_qc_records"]["crystal_ref_1jk8_14aa"] = None
    c_off_wt_nocredit["on_target_analytes"][3]["expression_batch_ids"] = ["BATCH_ECOLI_01", "BATCH_ECOLI_02"]
    for cmp_r in c_off_wt_nocredit["comp2_comparators_screened"]:
        if cmp_r["comparator_id"] == _SHIELD_COMP2_LEAD:
            cmp_r["expression_batch_ids"] = ["BATCH_ECOLI_01", "BATCH_ECOLI_02"]
            for cond_v in cmp_r["register_control_screens"].values():
                if isinstance(cond_v, dict):
                    cond_v["expression_batch_ids"] = ["BATCH_ECOLI_01", "BATCH_ECOLI_02"]
    for off_r in c_off_wt_nocredit["off_target_controls"]:
        if off_r["analyte_id"] == "HLA-DQ8-trans + WT InsB:9-23":
            off_r["expression_batch_ids"] = ["BATCH_ECOLI_01", "BATCH_ECOLI_02", "BATCH_ECOLI_03"]
            off_r["peptide_reagent_lot_id"] = "REAGENT_WT15_CONFLICT_LOT99"
        elif off_r["analyte_id"] in _SHIELD_MANDATORY_COMP2_OFF_TARGET_CONTROLS:
            off_r["expression_batch_ids"] = ["BATCH_ECOLI_01", "BATCH_ECOLI_02"]
    r_off_wt_nocredit = evaluate_gate30_shield_spr(c_off_wt_nocredit)

    c_off_wt_wrong_plus_c1_fail = json.loads(json.dumps(c_off_wt_wrong_lot))
    c_off_wt_wrong_plus_c1_fail["on_target_analytes"][0]["ic50_l95_nm"] = 650.0
    c_off_wt_wrong_plus_c1_fail["on_target_analytes"][0]["ic50_u95_nm"] = 800.0
    r_off_wt_wrong_plus_c1_fail = evaluate_gate30_shield_spr(c_off_wt_wrong_plus_c1_fail)

    if (
        r_off_wt_match_fail["verdict"] != "FAIL"
        or r_off_wt_match_fail["derived_summary"]["failure_domain"] != "INDEPENDENT_NON_DONOR_SPR"
        or r_off_wt_missing_lot["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or any(rs.startswith("[FAIL]") for rs in r_off_wt_missing_lot["reasons"])
        or r_off_wt_wrong_lot["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or any(rs.startswith("[FAIL]") for rs in r_off_wt_wrong_lot["reasons"])
        or r_off_wt_wrong_seq["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or any(rs.startswith("[FAIL]") for rs in r_off_wt_wrong_seq["reasons"])
        or r_off_wt_nocredit["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_off_wt_nocredit["derived_summary"]["distinct_linked_comp2_assay_batches_count"] != 2
        or r_off_wt_wrong_plus_c1_fail["verdict"] != "FAIL"
        or r_off_wt_wrong_plus_c1_fail["derived_summary"]["failure_domain"] != "INDEPENDENT_NON_DONOR_SPR"
    ):
        raise RuntimeError(
            f"R13 0039-B1/0037-B2 WT15 off-target reagent lot/sequence binding failed: "
            f"match={r_off_wt_match_fail['verdict']}, miss={r_off_wt_missing_lot['verdict']}, "
            f"wrong={r_off_wt_wrong_lot['verdict']}, seq={r_off_wt_wrong_seq['verdict']}, "
            f"nocredit={r_off_wt_nocredit['derived_summary']}, c1_fail={r_off_wt_wrong_plus_c1_fail['verdict']}"
        )

    # 91 (R13 0039-B2 / 0037-M1): Aligned physicochemical failure semantics (unqualified material input HOLD,
    # distinct diagnostic separating valid out-of-spec 92% monomer from missing/malformed/contradictory SEC-MALS,
    # while independent valid non-donor SPR FAIL returns FAIL with failure_domain='INDEPENDENT_NON_DONOR_SPR')!
    c_phys_oos_noroster = build_valid_shield_spr_observation(n_eff_per_donor=60, include_preregistered_roster=False)
    c_phys_oos_noroster["sec_mals_dls_monomer_coformulation"]["comp2_monomer_pct"] = 92.0
    c_phys_oos_noroster["sec_mals_dls_monomer_coformulation"]["comp2_t006_alone_monomer_qc_passed"] = False
    r_phys_oos_noroster = evaluate_gate30_shield_spr(c_phys_oos_noroster)

    c_phys_malformed = json.loads(json.dumps(base_pass))
    c_phys_malformed["sec_mals_dls_monomer_coformulation"]["comp2_monomer_pct"] = "not_a_number"
    r_phys_malformed = evaluate_gate30_shield_spr(c_phys_malformed)

    c_phys_contra = json.loads(json.dumps(base_pass))
    c_phys_contra["sec_mals_dls_monomer_coformulation"]["comp2_monomer_pct"] = 92.0
    c_phys_contra["sec_mals_dls_monomer_coformulation"]["comp2_t006_alone_monomer_qc_passed"] = True
    r_phys_contra = evaluate_gate30_shield_spr(c_phys_contra)

    # R14 0039-B3: Weak Comp2 WT15 SPR on the SAME batches declared unqualified (comp2_monomer_pct=92%, qc=False)
    # MUST return HOLD_INVALID_OR_MISSING_INPUT (failure_domain=None, 0 [FAIL] reasons), while qualified Comp1 SPR
    # failure alongside unqualified Comp2 (and separate qualified Comp2 fixture r_wt_match_fail) retain independent FAIL!
    c_phys_same_batch_wt_fail = json.loads(json.dumps(base_pass))
    c_phys_same_batch_wt_fail["sec_mals_dls_monomer_coformulation"]["comp2_monomer_pct"] = 92.0
    c_phys_same_batch_wt_fail["sec_mals_dls_monomer_coformulation"]["comp2_t006_alone_monomer_qc_passed"] = False
    c_phys_same_batch_wt_fail["on_target_analytes"][3]["ic50_l95_nm"] = 650.0
    c_phys_same_batch_wt_fail["on_target_analytes"][3]["ic50_u95_nm"] = 800.0
    r_phys_same_batch_wt_fail = evaluate_gate30_shield_spr(c_phys_same_batch_wt_fail)

    c_phys_qual_c1_fail_c2_oos = json.loads(json.dumps(base_pass))
    c_phys_qual_c1_fail_c2_oos["sec_mals_dls_monomer_coformulation"]["comp2_monomer_pct"] = 92.0
    c_phys_qual_c1_fail_c2_oos["sec_mals_dls_monomer_coformulation"]["comp2_t006_alone_monomer_qc_passed"] = False
    c_phys_qual_c1_fail_c2_oos["on_target_analytes"][0]["ic50_l95_nm"] = 650.0
    c_phys_qual_c1_fail_c2_oos["on_target_analytes"][0]["ic50_u95_nm"] = 800.0
    r_phys_qual_c1_fail_c2_oos = evaluate_gate30_shield_spr(c_phys_qual_c1_fail_c2_oos)

    # R15 Shared Blocker #1 (IIP-0042 B1 + IIP-0044 B1): Positive SEC-MALS/DLS cocktail material qualification
    # linkage required for EVERY donor row BEFORE counting outcomes, triggering donor FAIL, or awarding batch credit!
    c_donor_partial_sec_pass = json.loads(json.dumps(base_pass))
    c_donor_partial_sec_pass["sec_mals_dls_monomer_coformulation"]["expression_batch_ids"] = [
        "BATCH_ECOLI_01", "BATCH_ECOLI_02", "BATCH_ECOLI_03"
    ]
    r_donor_partial_sec_pass = evaluate_gate30_shield_spr(c_donor_partial_sec_pass)

    c_donor_uncov_fail = build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(0, 0, 0, 20, 0, 0, 0, 0, 0))
    c_donor_uncov_fail["sec_mals_dls_monomer_coformulation"]["expression_batch_ids"] = [
        "BATCH_ECOLI_01", "BATCH_ECOLI_02", "BATCH_ECOLI_03"
    ]
    r_donor_uncov_fail = evaluate_gate30_shield_spr(c_donor_uncov_fail)

    c_donor_omit_sec = json.loads(json.dumps(c_donor_uncov_fail))
    c_donor_omit_sec.pop("sec_mals_dls_monomer_coformulation", None)
    r_donor_omit_sec = evaluate_gate30_shield_spr(c_donor_omit_sec)

    c_donor_oos_sec_partial = json.loads(json.dumps(c_donor_uncov_fail))
    c_donor_oos_sec_partial["sec_mals_dls_monomer_coformulation"]["comp2_monomer_pct"] = 92.0
    c_donor_oos_sec_partial["sec_mals_dls_monomer_coformulation"]["comp2_t006_alone_monomer_qc_passed"] = False
    r_donor_oos_sec_partial = evaluate_gate30_shield_spr(c_donor_oos_sec_partial)

    c_donor_qual_fail = build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(0, 0, 0, 20, 0, 0, 0, 0, 0))
    r_donor_qual_fail = evaluate_gate30_shield_spr(c_donor_qual_fail)

    c_donor_uncov_plus_qual_spr_fail = json.loads(json.dumps(c_donor_uncov_fail))
    c_donor_uncov_plus_qual_spr_fail["on_target_analytes"][0]["ic50_l95_nm"] = 650.0
    c_donor_uncov_plus_qual_spr_fail["on_target_analytes"][0]["ic50_u95_nm"] = 800.0
    r_donor_uncov_plus_qual_spr_fail = evaluate_gate30_shield_spr(c_donor_uncov_plus_qual_spr_fail)

    if (
        r_phys_oos_noroster["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_phys_oos_noroster["derived_summary"]["failure_domain"] is not None
        or r_phys_oos_noroster["derived_summary"]["physicochemical_out_of_spec_disposition"] != "HOLD_INVALID_OR_MISSING_INPUT_UNQUALIFIED_MATERIAL"
        or r_phys_oos_noroster["derived_summary"]["sec_mals_dls"]["physicochemical_qc_classification"] != "OUT_OF_SPEC_MATERIAL_UNQUALIFIED_HOLD"
        or not any("PHYSICOCHEMICAL_OUT_OF_SPEC_MATERIAL_UNQUALIFIED_HOLD" in rs for rs in r_phys_oos_noroster["reasons"])
        or any("PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD" in rs for rs in r_phys_oos_noroster["reasons"])
        or r_phys_malformed["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_phys_malformed["derived_summary"]["failure_domain"] is not None
        or r_phys_malformed["derived_summary"]["sec_mals_dls"]["physicochemical_qc_classification"] != "MISSING_OR_MALFORMED_OR_CONTRADICTORY_INPUT_HOLD"
        or not any("PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD" in rs for rs in r_phys_malformed["reasons"])
        or r_phys_contra["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_phys_contra["derived_summary"]["sec_mals_dls"]["physicochemical_qc_classification"] != "MISSING_OR_MALFORMED_OR_CONTRADICTORY_INPUT_HOLD"
        or not any("PHYSICOCHEMICAL_MISSING_OR_MALFORMED_INPUT_HOLD" in rs for rs in r_phys_contra["reasons"])
        or r_phys_same_batch_wt_fail["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_phys_same_batch_wt_fail["derived_summary"]["failure_domain"] is not None
        or any(rs.startswith("[FAIL]") for rs in r_phys_same_batch_wt_fail["reasons"])
        or r_phys_same_batch_wt_fail["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
        or r_phys_qual_c1_fail_c2_oos["verdict"] != "FAIL"
        or r_phys_qual_c1_fail_c2_oos["derived_summary"]["failure_domain"] != "INDEPENDENT_NON_DONOR_SPR"
        or r_phys_qual_c1_fail_c2_oos["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
        or r_donor_partial_sec_pass["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_donor_partial_sec_pass["derived_summary"]["valid_donors_count"] != 3
        or r_donor_partial_sec_pass["derived_summary"]["distinct_linked_cocktail_comp1_batches_count"] != 3
        or r_donor_uncov_fail["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_donor_uncov_fail["derived_summary"]["failure_domain"] is not None
        or any(rs.startswith("[FAIL]") for rs in r_donor_uncov_fail["reasons"])
        or r_donor_uncov_fail["derived_summary"]["valid_donors_count"] != 3
        or r_donor_uncov_fail["derived_summary"]["bonferroni_family_denominator_n"] != 9
        or r_donor_uncov_fail["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
        or r_donor_omit_sec["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_donor_omit_sec["derived_summary"]["failure_domain"] is not None
        or any(rs.startswith("[FAIL]") for rs in r_donor_omit_sec["reasons"])
        or r_donor_omit_sec["derived_summary"]["valid_donors_count"] != 0
        or r_donor_oos_sec_partial["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_donor_oos_sec_partial["derived_summary"]["failure_domain"] is not None
        or any(rs.startswith("[FAIL]") for rs in r_donor_oos_sec_partial["reasons"])
        or r_donor_oos_sec_partial["derived_summary"]["valid_donors_count"] != 0
        or r_donor_qual_fail["verdict"] != "FAIL"
        or r_donor_qual_fail["derived_summary"]["failure_domain"] != "ROSTERED_DONOR_COHORT"
        or r_donor_qual_fail["derived_summary"]["trackb_shield_trigger_state"] != "ELIGIBLE_CANDIDATE_OVERALL_SHIELD_FAIL_PENDING_XREACT_AND_OWNER_REAUTH"
        or r_donor_uncov_plus_qual_spr_fail["verdict"] != "FAIL"
        or r_donor_uncov_plus_qual_spr_fail["derived_summary"]["failure_domain"] != "INDEPENDENT_NON_DONOR_SPR"
        or r_donor_uncov_plus_qual_spr_fail["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
    ):
        raise RuntimeError(
            f"R13/R14/R15 physicochemical & donor material qualification alignment failed: "
            f"oos={r_phys_oos_noroster}, malf={r_phys_malformed['derived_summary'].get('sec_mals_dls')}, "
            f"contra={r_phys_contra['derived_summary'].get('sec_mals_dls')}, "
            f"same_batch_wt={r_phys_same_batch_wt_fail['verdict']}, qual_c1={r_phys_qual_c1_fail_c2_oos['verdict']}, "
            f"uncov_fail={r_donor_uncov_fail['verdict']}, omit_sec={r_donor_omit_sec['verdict']}, "
            f"oos_partial={r_donor_oos_sec_partial['verdict']}, qual_fail={r_donor_qual_fail['verdict']}"
        )

    # 92 (R13 0037-B3 + R14 0037-B1 + 0039-M1 + 0039-M2): Machine-checked trackb_shield_trigger_state (SHIELD-1-only vs
    # overall SHIELD fail vs ineligible on PASS/HOLD/partial-FAIL-with-HOLD/pre-assay-exclusion) + explicit U95 & FWER scope tags!
    c_partial_comp2_fail_noroster = json.loads(json.dumps(c_wt_match_fail))
    c_partial_comp2_fail_noroster.pop("preregistered_donor_family_roster", None)
    r_partial_comp2_fail_noroster = evaluate_gate30_shield_spr(c_partial_comp2_fail_noroster)

    c_partial_comp2_fail_oos = json.loads(json.dumps(c_wt_match_fail))
    c_partial_comp2_fail_oos["sec_mals_dls_monomer_coformulation"]["comp2_monomer_pct"] = 92.0
    c_partial_comp2_fail_oos["sec_mals_dls_monomer_coformulation"]["comp2_t006_alone_monomer_qc_passed"] = False
    r_partial_comp2_fail_oos = evaluate_gate30_shield_spr(c_partial_comp2_fail_oos)

    c_comp2_and_tcell_fail = json.loads(json.dumps(c_wt_match_fail))
    for d in c_comp2_and_tcell_fail["tcell_blockade_and_apc_cytotoxicity_donors"]:
        d["suppression_pct"] = 25.0
    r_comp2_and_tcell_fail = evaluate_gate30_shield_spr(c_comp2_and_tcell_fail)

    r_overall_tcell_fail = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(n_eff_per_donor=60, donor_suppressions=(25.0,) * 9)
    )

    # R14 0037-B1: 19/20 measured responders (84% -> L95=78.3894% >= 70%) + 1 pre-assay exclusion + 20/60 cyto FAIL
    # MUST preserve biological FAIL & N_roster=20 while classifying trackb_shield_trigger_state as INELIGIBLE;
    # paired 20/20 complete measured roster with identical 20/60 cyto FAIL MUST classify as OVERALL_SHIELD_FAIL!
    excl1_20 = [{
        "donor_id": "T1D_DONOR_20",
        "pre_assay_exclusion_reason": "Pre-assay leukopak viability QC failure prior to unblinding",
        "outcome_blind_exclusion_attested": True,
    }]
    r_excl1_20_cyto_fail = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(
            n_eff_per_donor=60,
            donor_k_obs=(20,) + (0,) * 18,
            donor_suppressions=(84.0,) * 19,
            roster_donor_ids=[f"T1D_DONOR_{i:02d}" for i in range(1, 21)],
            excluded_donor_records=excl1_20,
        )
    )
    r_full_20_cyto_fail = evaluate_gate30_shield_spr(
        build_valid_shield_spr_observation(
            n_eff_per_donor=60,
            donor_k_obs=(20,) + (0,) * 19,
            donor_suppressions=(84.0,) * 20,
            roster_donor_ids=[f"T1D_DONOR_{i:02d}" for i in range(1, 21)],
        )
    )

    # R15 Shared Blocker #2 (IIP-0044 B2): Mandatory per-comparator WT15 AND 6DFX register_control_screens coverage
    # (rejecting WT15-only, 6DFX-only, extra untyped keys, wrong 6DFX lot/sequence, duplicate evidence_record_id,
    # while keeping physical 1JK8 optional and allowing independent qualified SPR FAIL!)
    c_comp_wt15_only = json.loads(json.dumps(base_pass))
    for cp in c_comp_wt15_only["comp2_comparators_screened"]:
        cp["register_control_screens"].pop("engineered_6dfx_p8e9e_12aa", None)
    r_comp_wt15_only = evaluate_gate30_shield_spr(c_comp_wt15_only)

    c_comp_extra_key = json.loads(json.dumps(base_pass))
    for cp in c_comp_extra_key["comp2_comparators_screened"]:
        cp["screened_register_controls"] = ["WT15"]
    r_comp_extra_key = evaluate_gate30_shield_spr(c_comp_extra_key)

    c_comp_6dfx_only = json.loads(json.dumps(base_pass))
    c_comp_6dfx_only["comp2_comparators_screened"][1]["register_control_screens"].pop("native_wt_insb9_23_15aa", None)
    r_comp_6dfx_only = evaluate_gate30_shield_spr(c_comp_6dfx_only)

    c_comp_bad_6dfx_lot = json.loads(json.dumps(base_pass))
    c_comp_bad_6dfx_lot["comp2_comparators_screened"][1]["register_control_screens"]["engineered_6dfx_p8e9e_12aa"][
        "peptide_reagent_lot_id"
    ] = "REAGENT_6DFX_WRONG_LOT99"
    r_comp_bad_6dfx_lot = evaluate_gate30_shield_spr(c_comp_bad_6dfx_lot)

    c_comp_dup_ev = json.loads(json.dumps(base_pass))
    c_comp_dup_ev["comp2_comparators_screened"][1]["register_control_screens"]["engineered_6dfx_p8e9e_12aa"][
        "evidence_record_id"
    ] = c_comp_dup_ev["comp2_comparators_screened"][1]["register_control_screens"]["native_wt_insb9_23_15aa"][
        "evidence_record_id"
    ]
    r_comp_dup_ev = evaluate_gate30_shield_spr(c_comp_dup_ev)

    c_comp_1jk8_null_ok = json.loads(json.dumps(base_pass))
    c_comp_1jk8_null_ok["register_qc_records"]["crystal_ref_1jk8_14aa"] = None
    for cp in c_comp_1jk8_null_ok["comp2_comparators_screened"]:
        cp["register_control_screens"]["crystal_ref_1jk8_14aa"] = None
    r_comp_1jk8_null_ok = evaluate_gate30_shield_spr(c_comp_1jk8_null_ok)

    if (
        r_pass["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
        or r_pass["derived_summary"]["comparator_mandatory_register_coverage_verified"] is not True
        or r_pass["derived_summary"]["comparator_wt15_and_6dfx_verified_count"] != 6
        or r_mid["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
        or r_scalar["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
        or r_partial_comp2_fail_noroster["verdict"] != "FAIL"
        or r_partial_comp2_fail_noroster["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
        or r_partial_comp2_fail_oos["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_partial_comp2_fail_oos["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
        or r_excl1_20_cyto_fail["verdict"] != "FAIL"
        or r_excl1_20_cyto_fail["derived_summary"]["bonferroni_family_denominator_n"] != 20
        or r_excl1_20_cyto_fail["derived_summary"]["cytotoxicity_full_roster_measured_complete"] is not False
        or r_excl1_20_cyto_fail["derived_summary"]["non_fail_hold_or_invalid_reasons_count"] < 1
        or r_excl1_20_cyto_fail["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
        or r_full_20_cyto_fail["verdict"] != "FAIL"
        or r_full_20_cyto_fail["derived_summary"]["bonferroni_family_denominator_n"] != 20
        or r_full_20_cyto_fail["derived_summary"]["cytotoxicity_full_roster_measured_complete"] is not True
        or r_full_20_cyto_fail["derived_summary"]["non_fail_hold_or_invalid_reasons_count"] != 0
        or r_full_20_cyto_fail["derived_summary"]["trackb_shield_trigger_state"] != "ELIGIBLE_CANDIDATE_OVERALL_SHIELD_FAIL_PENDING_XREACT_AND_OWNER_REAUTH"
        or r_comp_wt15_only["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_comp_wt15_only["derived_summary"]["comparator_mandatory_register_coverage_verified"] is not False
        or r_comp_extra_key["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_comp_6dfx_only["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_comp_bad_6dfx_lot["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_comp_dup_ev["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_comp_1jk8_null_ok["verdict"] != "PASS"
        or r_wt_match_fail["derived_summary"]["trackb_shield_trigger_state"] != "ELIGIBLE_CANDIDATE_SHIELD1_ONLY_COMP2_FAIL_PENDING_XREACT_AND_OWNER_REAUTH"
        or r_off_wt_match_fail["derived_summary"]["trackb_shield_trigger_state"] != "ELIGIBLE_CANDIDATE_SHIELD1_ONLY_COMP2_FAIL_PENDING_XREACT_AND_OWNER_REAUTH"
        or r_dq22_fail["derived_summary"]["trackb_shield_trigger_state"] != "ELIGIBLE_CANDIDATE_OVERALL_SHIELD_FAIL_PENDING_XREACT_AND_OWNER_REAUTH"
        or r_overall_tcell_fail["derived_summary"]["trackb_shield_trigger_state"] != "ELIGIBLE_CANDIDATE_OVERALL_SHIELD_FAIL_PENDING_XREACT_AND_OWNER_REAUTH"
        or r_comp2_and_tcell_fail["derived_summary"]["trackb_shield_trigger_state"] != "ELIGIBLE_CANDIDATE_OVERALL_SHIELD_FAIL_PENDING_XREACT_AND_OWNER_REAUTH"
        or r_pass["derived_summary"]["trackb_shield_trigger_adjudicator"] != "GATE30_SHIELD_SPR_SOFTWARE_PLUS_GATE30_ATG_XREACT_PASS_PLUS_OWNER_REAUTHORIZATION"
        or r_pass["derived_summary"]["suppression_responder_u95_scope"] != "DESCRIPTIVE_DIAGNOSTIC_ONLY_NO_MARGINAL_UPPER_COVERAGE_GUARANTEE"
        or r_pass["derived_summary"]["fwer_bound_scope"] != "FIXED_ROSTER_DONOR_CYTOTOXICITY_FAMILY_ONLY_NOT_UNION_WITH_SPR_OR_SUPPRESSION"
    ):
        raise RuntimeError(
            f"R13/R14 0037-B1/B3 trackb_shield_trigger_state or scope tags failed: "
            f"pass={r_pass['derived_summary'].get('trackb_shield_trigger_state')}, "
            f"partial_nr={r_partial_comp2_fail_noroster['derived_summary'].get('trackb_shield_trigger_state')}, "
            f"excl1_20={r_excl1_20_cyto_fail['verdict']}:{r_excl1_20_cyto_fail['derived_summary'].get('trackb_shield_trigger_state')}, "
            f"full_20={r_full_20_cyto_fail['verdict']}:{r_full_20_cyto_fail['derived_summary'].get('trackb_shield_trigger_state')}, "
            f"s1_wt={r_wt_match_fail['derived_summary'].get('trackb_shield_trigger_state')}, "
            f"s1_off={r_off_wt_match_fail['derived_summary'].get('trackb_shield_trigger_state')}, "
            f"c1_fail={r_dq22_fail['derived_summary'].get('trackb_shield_trigger_state')}, "
            f"tcell_fail={r_overall_tcell_fail['derived_summary'].get('trackb_shield_trigger_state')}"
        )

    # 93 (R16 Shared Blocker #1 — IIP-0042 B2 / IIP-0044 B1): Per-mixture physical co-formulation SEC-MALS/DLS binding!
    # 9 disjoint (Comp1_i, Comp2_i) pairs PASS; swapping Comp2 lots on donors 1 & 2 while leaving SEC-MALS unchanged
    # MUST return HOLD_INVALID_OR_MISSING_INPUT with 0 donor credit for crossed rows & INELIGIBLE Track-B even with
    # 20/60 cytotoxicity, while preserving independent valid SPR FAIL!
    c_r16_sep_ctrl = build_valid_shield_spr_observation(n_eff_per_donor=60, separate_comp1_comp2_batches=True)
    r_r16_sep_ctrl = evaluate_gate30_shield_spr(c_r16_sep_ctrl)

    c_r16_crossed = json.loads(json.dumps(c_r16_sep_ctrl))
    c_r16_crossed["tcell_blockade_and_apc_cytotoxicity_donors"][0]["expression_batch_ids"] = ["BATCH_C1_01", "BATCH_C2_02"]
    c_r16_crossed["tcell_blockade_and_apc_cytotoxicity_donors"][1]["expression_batch_ids"] = ["BATCH_C1_02", "BATCH_C2_01"]
    r_r16_crossed = evaluate_gate30_shield_spr(c_r16_crossed)

    c_r16_crossed_cyto20 = json.loads(json.dumps(c_r16_crossed))
    c_r16_crossed_cyto20["tcell_blockade_and_apc_cytotoxicity_donors"][0]["apc_cytotoxicity_k_obs"] = 20
    r_r16_crossed_cyto20 = evaluate_gate30_shield_spr(c_r16_crossed_cyto20)

    c_r16_crossed_ind_spr = json.loads(json.dumps(c_r16_crossed_cyto20))
    c_r16_crossed_ind_spr["on_target_analytes"][0]["ic50_l95_nm"] = 650.0
    c_r16_crossed_ind_spr["on_target_analytes"][0]["ic50_u95_nm"] = 800.0
    r_r16_crossed_ind_spr = evaluate_gate30_shield_spr(c_r16_crossed_ind_spr)

    c_r16_mix_oos_overstate = json.loads(json.dumps(c_r16_sep_ctrl))
    c_r16_mix_oos_overstate["sec_mals_dls_monomer_coformulation"]["qualified_coformulation_mixtures"][0]["monomer_pct"] = 90.0
    c_r16_mix_oos_overstate["sec_mals_dls_monomer_coformulation"]["qualified_coformulation_mixtures"][0]["qc_passed"] = False
    r_r16_mix_oos_overstate = evaluate_gate30_shield_spr(c_r16_mix_oos_overstate)

    if (
        r_r16_sep_ctrl["verdict"] != "PASS"
        or r_r16_sep_ctrl["derived_summary"]["valid_donors_count"] != 9
        or r_r16_sep_ctrl["derived_summary"]["sec_mals_dls"]["qualified_coformulation_mixtures_count"] != 9
        or r_r16_crossed["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_r16_crossed["derived_summary"]["valid_donors_count"] != 7
        or any(rs.startswith("[FAIL]") for rs in r_r16_crossed["reasons"])
        or r_r16_crossed["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
        or r_r16_crossed_cyto20["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_r16_crossed_cyto20["derived_summary"]["failure_domain"] is not None
        or r_r16_crossed_cyto20["derived_summary"]["valid_donors_count"] != 7
        or any(rs.startswith("[FAIL]") for rs in r_r16_crossed_cyto20["reasons"])
        or r_r16_crossed_cyto20["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
        or r_r16_crossed_ind_spr["verdict"] != "FAIL"
        or r_r16_crossed_ind_spr["derived_summary"]["failure_domain"] != "INDEPENDENT_NON_DONOR_SPR"
        or r_r16_crossed_ind_spr["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
        or r_r16_mix_oos_overstate["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
    ):
        raise RuntimeError(
            f"R16 Shared Blocker #1 (per-mixture co-formulation binding) failed: "
            f"ctrl={r_r16_sep_ctrl['verdict']}, crossed={r_r16_crossed['verdict']}(v={r_r16_crossed['derived_summary'].get('valid_donors_count')}), "
            f"cyto20={r_r16_crossed_cyto20['verdict']}, spr={r_r16_crossed_ind_spr['verdict']}:{r_r16_crossed_ind_spr['derived_summary'].get('failure_domain')}"
        )

    # 94 (R16 Shared Blocker #2 — IIP-0042 B3 / IIP-0044 B2): Mandatory shared comparator expression batch evaluated
    # across BOTH WT15 and 6DFX on every one of the 6 required comparators! Disjoint WT15 vs 6DFX batches earn 0
    # complete-comparator credit and suppress Track-B even with valid Comp2-only SPR FAIL (preserving independent SPR FAIL)!
    c_r16_comp_disj = json.loads(json.dumps(base_pass))
    for b_extra_idx in range(4, 7):
        c_r16_comp_disj["register_qc_records"]["expression_batch_ids"].append(f"BATCH_ECOLI_{b_extra_idx:02d}")
    for cp in c_r16_comp_disj["comp2_comparators_screened"]:
        cid_k = cp["comparator_id"]
        if cid_k == _SHIELD_COMP2_LEAD:
            b_wt = ["BATCH_ECOLI_01", "BATCH_ECOLI_02", "BATCH_ECOLI_03"]
            b_6d = ["BATCH_ECOLI_04", "BATCH_ECOLI_05", "BATCH_ECOLI_06"]
            cp["expression_batch_ids"] = b_wt + b_6d
            cp["register_control_screens"]["native_wt_insb9_23_15aa"]["expression_batch_ids"] = b_wt
            cp["register_control_screens"]["engineered_6dfx_p8e9e_12aa"]["expression_batch_ids"] = b_6d
        else:
            b_wt_id = f"BATCH_COMP_{cid_k}"
            b_6d_id = f"BATCH_COMP_{cid_k}_6DFX_ONLY"
            c_r16_comp_disj["expression_batches"].append(
                {"batch_id": b_6d_id, "construct_ids": [cid_k], "qc_passed": True}
            )
            cp["expression_batch_ids"] = [b_wt_id, b_6d_id]
            cp["register_control_screens"]["native_wt_insb9_23_15aa"]["expression_batch_ids"] = [b_wt_id]
            cp["register_control_screens"]["engineered_6dfx_p8e9e_12aa"]["expression_batch_ids"] = [b_6d_id]
    r_r16_comp_disj = evaluate_gate30_shield_spr(c_r16_comp_disj)

    c_r16_comp_disj_c2fail = json.loads(json.dumps(c_r16_comp_disj))
    c_r16_comp_disj_c2fail["on_target_analytes"][3]["ic50_l95_nm"] = 650.0
    c_r16_comp_disj_c2fail["on_target_analytes"][3]["ic50_u95_nm"] = 800.0
    r_r16_comp_disj_c2fail = evaluate_gate30_shield_spr(c_r16_comp_disj_c2fail)

    if (
        r_r16_comp_disj["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_r16_comp_disj["derived_summary"]["comparator_wt15_and_6dfx_verified_count"] != 0
        or r_r16_comp_disj["derived_summary"]["comparator_mandatory_register_coverage_verified"] is not False
        or r_r16_comp_disj["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
        or r_r16_comp_disj_c2fail["verdict"] != "FAIL"
        or r_r16_comp_disj_c2fail["derived_summary"]["failure_domain"] != "INDEPENDENT_NON_DONOR_SPR"
        or r_r16_comp_disj_c2fail["derived_summary"]["comparator_wt15_and_6dfx_verified_count"] != 0
        or r_r16_comp_disj_c2fail["derived_summary"]["comparator_mandatory_register_coverage_verified"] is not False
        or r_r16_comp_disj_c2fail["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
    ):
        raise RuntimeError(
            f"R16 Shared Blocker #2 (shared WT15/6DFX comparator batch intersection) failed: "
            f"disj={r_r16_comp_disj['verdict']}(cnt={r_r16_comp_disj['derived_summary'].get('comparator_wt15_and_6dfx_verified_count')}), "
            f"c2fail={r_r16_comp_disj_c2fail['verdict']}:{r_r16_comp_disj_c2fail['derived_summary'].get('trackb_shield_trigger_state')}"
        )

    # 95 (R16 Shared Blocker #3 — IIP-0042 B4 / IIP-0044 B3): Fixed per-donor sample size N & single-look horizon
    # cryptographically locked inside roster_sha256! Reusing the same roster_sha256 (committed at N=66) while
    # peeking at 17/170 MUST fail closed (HOLD_INVALID, fwer_valid=False, 0 [FAIL] reasons, INELIGIBLE Track-B),
    # multi-look plans rejected fail-closed, heterogeneous precommitted per-donor map passes!
    c_r16_look1_66 = build_valid_shield_spr_observation(
        n_eff_per_donor=66,
        donor_k_obs=(9,) + (0,) * 8,
    )
    r_r16_look1_66 = evaluate_gate30_shield_spr(c_r16_look1_66)

    c_r16_look2_170_same_sha = json.loads(json.dumps(c_r16_look1_66))
    d0_l2 = c_r16_look2_170_same_sha["tcell_blockade_and_apc_cytotoxicity_donors"][0]
    d0_l2["apc_cytotoxicity_k_obs"] = 17
    d0_l2["apc_cytotoxicity_n_eff"] = 170
    d0_l2["raw_independent_units_n"] = 170
    d0_l2["gy018_independence_justification"]["predeclared_per_donor_unit_count_n"] = 170
    r_r16_look2_170_same_sha = evaluate_gate30_shield_spr(c_r16_look2_170_same_sha)

    c_r16_look2_170_tamper_roster_n = json.loads(json.dumps(c_r16_look2_170_same_sha))
    c_r16_look2_170_tamper_roster_n["preregistered_donor_family_roster"]["predeclared_per_donor_unit_count_n"] = 170
    r_r16_look2_170_tamper_roster_n = evaluate_gate30_shield_spr(c_r16_look2_170_tamper_roster_n)

    c_r16_multilook = json.loads(json.dumps(c_r16_look1_66))
    c_r16_multilook["preregistered_donor_family_roster"] = _shield_build_preregistered_roster(
        [f"T1D_DONOR_{i:02d}" for i in range(1, 10)],
        predeclared_per_donor_unit_count_n=66,
        planned_analysis_looks=2,
        single_look_fixed_horizon_plan_locked=True,
    )
    r_r16_multilook = evaluate_gate30_shield_spr(c_r16_multilook)

    c_r16_look2_ind_spr = json.loads(json.dumps(c_r16_look2_170_same_sha))
    c_r16_look2_ind_spr["on_target_analytes"][0]["ic50_l95_nm"] = 650.0
    c_r16_look2_ind_spr["on_target_analytes"][0]["ic50_u95_nm"] = 800.0
    r_r16_look2_ind_spr = evaluate_gate30_shield_spr(c_r16_look2_ind_spr)

    c_r16_hetero_n_ok = json.loads(json.dumps(base_pass))
    hetero_map = {f"T1D_DONOR_{i:02d}": (66 if i == 1 else 60) for i in range(1, 10)}
    c_r16_hetero_n_ok["preregistered_donor_family_roster"] = _shield_build_preregistered_roster(
        [f"T1D_DONOR_{i:02d}" for i in range(1, 10)],
        predeclared_per_donor_unit_count_n=None,
        predeclared_per_donor_unit_counts=hetero_map,
    )
    d0_het = c_r16_hetero_n_ok["tcell_blockade_and_apc_cytotoxicity_donors"][0]
    d0_het["raw_independent_units_n"] = 66
    d0_het["apc_cytotoxicity_n_eff"] = 66
    d0_het["gy018_independence_justification"]["predeclared_per_donor_unit_count_n"] = 66
    r_r16_hetero_n_ok = evaluate_gate30_shield_spr(c_r16_hetero_n_ok)

    if (
        r_r16_look1_66["verdict"] != "FAIL"
        or r_r16_look1_66["derived_summary"]["authorization_grade_fwer_bound_valid"] is not True
        or r_r16_look1_66["derived_summary"]["failure_domain"] != "ROSTERED_DONOR_COHORT"
        or r_r16_look1_66["derived_summary"]["trackb_shield_trigger_state"] != "ELIGIBLE_CANDIDATE_OVERALL_SHIELD_FAIL_PENDING_XREACT_AND_OWNER_REAUTH"
        or r_r16_look2_170_same_sha["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_r16_look2_170_same_sha["derived_summary"]["authorization_grade_fwer_bound_valid"] is not False
        or r_r16_look2_170_same_sha["derived_summary"]["failure_domain"] is not None
        or any(rs.startswith("[FAIL]") for rs in r_r16_look2_170_same_sha["reasons"])
        or r_r16_look2_170_same_sha["derived_summary"]["roster_sample_size_plan_mismatched_donors"] != ["T1D_DONOR_01"]
        or r_r16_look2_170_same_sha["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
        or r_r16_look2_170_tamper_roster_n["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_r16_look2_170_tamper_roster_n["derived_summary"]["preregistered_donor_roster_verified"] is not False
        or r_r16_look2_170_tamper_roster_n["derived_summary"]["authorization_grade_fwer_bound_valid"] is not False
        or any(rs.startswith("[FAIL]") for rs in r_r16_look2_170_tamper_roster_n["reasons"])
        or r_r16_multilook["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_r16_multilook["derived_summary"]["authorization_grade_fwer_bound_valid"] is not False
        or any(rs.startswith("[FAIL]") for rs in r_r16_multilook["reasons"])
        or r_r16_look2_ind_spr["verdict"] != "FAIL"
        or r_r16_look2_ind_spr["derived_summary"]["failure_domain"] != "INDEPENDENT_NON_DONOR_SPR"
        or r_r16_look2_ind_spr["derived_summary"]["authorization_grade_fwer_bound_valid"] is not False
        or r_r16_look2_ind_spr["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
        or r_r16_hetero_n_ok["verdict"] != "PASS"
    ):
        raise RuntimeError(
            f"R16 Shared Blocker #3 (fixed per-donor N & single-look locked in roster_sha256) failed: "
            f"l1={r_r16_look1_66['verdict']}, l2_same={r_r16_look2_170_same_sha['verdict']}, "
            f"l2_tamp={r_r16_look2_170_tamper_roster_n['verdict']}, multi={r_r16_multilook['verdict']}, "
            f"ind_spr={r_r16_look2_ind_spr['verdict']}, hetero={r_r16_hetero_n_ok['verdict']}"
        )

    # 96 (R16 IIP-0044 Minor #3): Optional 1JK8 physical control stays optional (omitted or JSON null -> PASS),
    # BUT whenever non-null crystal_ref_1jk8_14aa includes peptide_reagent_lot_id, ill-typed/null/padded/reused
    # values (e.g., 17, None, True, "", WT15 lot) MUST fail closed to HOLD_INVALID_OR_MISSING_INPUT!
    c_r16_1jk8_lot17 = json.loads(json.dumps(base_pass))
    c_r16_1jk8_lot17["register_qc_records"]["crystal_ref_1jk8_14aa"]["peptide_reagent_lot_id"] = 17
    r_r16_1jk8_lot17 = evaluate_gate30_shield_spr(c_r16_1jk8_lot17)

    c_r16_1jk8_lot_none = json.loads(json.dumps(base_pass))
    c_r16_1jk8_lot_none["register_qc_records"]["crystal_ref_1jk8_14aa"]["peptide_reagent_lot_id"] = None
    r_r16_1jk8_lot_none = evaluate_gate30_shield_spr(c_r16_1jk8_lot_none)

    c_r16_1jk8_lot_reuse = json.loads(json.dumps(base_pass))
    c_r16_1jk8_lot_reuse["register_qc_records"]["crystal_ref_1jk8_14aa"]["peptide_reagent_lot_id"] = "REAGENT_WT15_INSB9_23_LOT01"
    r_r16_1jk8_lot_reuse = evaluate_gate30_shield_spr(c_r16_1jk8_lot_reuse)

    c_r16_1jk8_lot_ok = json.loads(json.dumps(base_pass))
    c_r16_1jk8_lot_ok["register_qc_records"]["crystal_ref_1jk8_14aa"]["peptide_reagent_lot_id"] = "REAGENT_1JK8_14AA_LOT01"
    r_r16_1jk8_lot_ok = evaluate_gate30_shield_spr(c_r16_1jk8_lot_ok)

    if (
        r_r16_1jk8_lot17["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_r16_1jk8_lot_none["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_r16_1jk8_lot_reuse["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_r16_1jk8_lot_ok["verdict"] != "PASS"
    ):
        raise RuntimeError(
            f"R16 0039-M3 optional 1JK8 peptide_reagent_lot_id validation failed: "
            f"lot17={r_r16_1jk8_lot17['verdict']}, none={r_r16_1jk8_lot_none['verdict']}, "
            f"reuse={r_r16_1jk8_lot_reuse['verdict']}, ok={r_r16_1jk8_lot_ok['verdict']}"
        )

    # 97-100 (R16 Shared Blocker #1 — Pre-dedup fixed-horizon N check across ALL raw submitted rostered donor rows):
    # A conflicting duplicate donor submitted with BOTH a 60-unit row and a 70-unit row (under committed N=60)
    # MUST populate roster_sample_size_plan_mismatched_donors and set authorization_grade_fwer_bound_valid=False
    # in BOTH [60, 70] and [70, 60] orders — preventing another failing donor (10/60) from firing donor-cohort FAIL —
    # while matching-count duplicates [60, 60] trigger zero biological credit with NO false N mismatch, and an
    # independent qualified SPR FAIL still dominates with failure_domain='INDEPENDENT_NON_DONOR_SPR'!
    c_r16_dup_base = build_valid_shield_spr_observation(
        n_eff_per_donor=60,
        donor_k_obs=(0, 10, 0, 0, 0, 0, 0, 0, 0),
    )
    d0_70_row = json.loads(json.dumps(c_r16_dup_base["tcell_blockade_and_apc_cytotoxicity_donors"][0]))
    d0_70_row["raw_independent_units_n"] = 70
    d0_70_row["apc_cytotoxicity_n_eff"] = 70
    d0_70_row["gy018_independence_justification"]["predeclared_per_donor_unit_count_n"] = 70

    # 97: [60, 70] order on conflicting duplicate -> HOLD_INVALID_OR_MISSING_INPUT, mismatch recorded, fwer_valid=False
    c_r16_dup_60_70 = json.loads(json.dumps(c_r16_dup_base))
    c_r16_dup_60_70["tcell_blockade_and_apc_cytotoxicity_donors"].append(json.loads(json.dumps(d0_70_row)))
    r_r16_dup_60_70 = evaluate_gate30_shield_spr(c_r16_dup_60_70)
    if (
        r_r16_dup_60_70["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_r16_dup_60_70["derived_summary"]["roster_sample_size_plan_mismatched_donors"] != ["T1D_DONOR_01"]
        or r_r16_dup_60_70["derived_summary"]["authorization_grade_fwer_bound_valid"] is not False
        or r_r16_dup_60_70["derived_summary"]["failure_domain"] is not None
        or any(rs.startswith("[FAIL]") for rs in r_r16_dup_60_70["reasons"])
        or r_r16_dup_60_70["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
    ):
        raise RuntimeError(f"R16 Shared Blocker #1 case 97 ([60, 70] duplicate) failed: {r_r16_dup_60_70}")

    # 98: [70, 60] reverse order on conflicting duplicate -> identical HOLD_INVALID_OR_MISSING_INPUT, mismatch recorded, fwer_valid=False
    c_r16_dup_70_60 = json.loads(json.dumps(c_r16_dup_base))
    c_r16_dup_70_60["tcell_blockade_and_apc_cytotoxicity_donors"].insert(0, json.loads(json.dumps(d0_70_row)))
    r_r16_dup_70_60 = evaluate_gate30_shield_spr(c_r16_dup_70_60)
    if (
        r_r16_dup_70_60["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_r16_dup_70_60["derived_summary"]["roster_sample_size_plan_mismatched_donors"] != ["T1D_DONOR_01"]
        or r_r16_dup_70_60["derived_summary"]["authorization_grade_fwer_bound_valid"] is not False
        or r_r16_dup_70_60["derived_summary"]["failure_domain"] is not None
        or any(rs.startswith("[FAIL]") for rs in r_r16_dup_70_60["reasons"])
        or r_r16_dup_70_60["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
    ):
        raise RuntimeError(f"R16 Shared Blocker #1 case 98 ([70, 60] reverse duplicate) failed: {r_r16_dup_70_60}")

    # 99: matching-count duplicate [60, 60] with conflicting cytotoxicity counts (0/60 vs 15/60) ->
    # zero biological credit for duplicate donor, NO false N mismatch!
    c_r16_dup_60_60 = json.loads(json.dumps(base_pass))
    d0_60_conflict_k = json.loads(json.dumps(c_r16_dup_60_60["tcell_blockade_and_apc_cytotoxicity_donors"][0]))
    d0_60_conflict_k["apc_cytotoxicity_k_obs"] = 15
    c_r16_dup_60_60["tcell_blockade_and_apc_cytotoxicity_donors"].append(d0_60_conflict_k)
    r_r16_dup_60_60 = evaluate_gate30_shield_spr(c_r16_dup_60_60)
    if (
        r_r16_dup_60_60["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_r16_dup_60_60["derived_summary"]["valid_donors_count"] != 8
        or r_r16_dup_60_60["derived_summary"]["roster_sample_size_plan_mismatched_donors"] != []
        or r_r16_dup_60_60["derived_summary"]["conflicted_duplicate_keys"]["donors"] != ["T1D_DONOR_01"]
        or any(rs.startswith("[FAIL]") for rs in r_r16_dup_60_60["reasons"])
    ):
        raise RuntimeError(f"R16 Shared Blocker #1 case 99 ([60, 60] matching-N conflicting k) failed: {r_r16_dup_60_60}")

    # 100: conflicting [60, 70] duplicate paired with a valid independent qualified SPR failure ->
    # returns FAIL with failure_domain='INDEPENDENT_NON_DONOR_SPR' (NOT 'ROSTERED_DONOR_COHORT'),
    # authorization_grade_fwer_bound_valid=False, and mismatch ID recorded!
    c_r16_dup_60_70_spr = json.loads(json.dumps(c_r16_dup_60_70))
    c_r16_dup_60_70_spr["on_target_analytes"][0]["ic50_l95_nm"] = 650.0
    c_r16_dup_60_70_spr["on_target_analytes"][0]["ic50_u95_nm"] = 800.0
    r_r16_dup_60_70_spr = evaluate_gate30_shield_spr(c_r16_dup_60_70_spr)
    if (
        r_r16_dup_60_70_spr["verdict"] != "FAIL"
        or r_r16_dup_60_70_spr["derived_summary"]["failure_domain"] != "INDEPENDENT_NON_DONOR_SPR"
        or r_r16_dup_60_70_spr["derived_summary"]["authorization_grade_fwer_bound_valid"] is not False
        or r_r16_dup_60_70_spr["derived_summary"]["roster_sample_size_plan_mismatched_donors"] != ["T1D_DONOR_01"]
        or r_r16_dup_60_70_spr["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
    ):
        raise RuntimeError(
            f"R16 Shared Blocker #1 case 100 ([60, 70] duplicate + valid independent SPR FAIL) failed: {r_r16_dup_60_70_spr}"
        )

    # 101 (R16 0039-M2): Per-mixture 1:1 molar ratio laboratory-attestation metadata inside closed mixture schema:
    # default explicit attestation PASSES with all_qualified_mixtures_equimolar_1to1_attested=True and explicit scope note;
    # omitted optional fields stay backward-compatible PASS (all_attested=False); False/non-bool/non-allowlisted/extra keys fail closed!
    c_r16_mix_omit_ratio = json.loads(json.dumps(base_pass))
    for m_item in c_r16_mix_omit_ratio["sec_mals_dls_monomer_coformulation"]["qualified_coformulation_mixtures"]:
        m_item.pop("equimolar_1to1_molar_ratio_attested", None)
        m_item.pop("ratio_basis_attestation", None)
    r_r16_mix_omit_ratio = evaluate_gate30_shield_spr(c_r16_mix_omit_ratio)

    c_r16_mix_eq_false = json.loads(json.dumps(base_pass))
    c_r16_mix_eq_false["sec_mals_dls_monomer_coformulation"]["qualified_coformulation_mixtures"][0]["equimolar_1to1_molar_ratio_attested"] = False
    r_r16_mix_eq_false = evaluate_gate30_shield_spr(c_r16_mix_eq_false)

    c_r16_mix_bad_basis = json.loads(json.dumps(base_pass))
    c_r16_mix_bad_basis["sec_mals_dls_monomer_coformulation"]["qualified_coformulation_mixtures"][0]["ratio_basis_attestation"] = "2:1 weight guess"
    r_r16_mix_bad_basis = evaluate_gate30_shield_spr(c_r16_mix_bad_basis)

    c_r16_mix_extra_key = json.loads(json.dumps(base_pass))
    c_r16_mix_extra_key["sec_mals_dls_monomer_coformulation"]["qualified_coformulation_mixtures"][0]["unexpected_note"] = "free text"
    r_r16_mix_extra_key = evaluate_gate30_shield_spr(c_r16_mix_extra_key)

    if (
        r_pass["derived_summary"]["sec_mals_dls"]["coformulation_1to1_molar_ratio_verification_scope"]
        != "LABORATORY_ATTESTED_NOT_INDEPENDENTLY_MEASURED_BY_SEC_MALS_OR_DLS"
        or r_pass["derived_summary"]["sec_mals_dls"]["all_qualified_mixtures_equimolar_1to1_attested"] is not True
        or r_r16_mix_omit_ratio["verdict"] != "PASS"
        or r_r16_mix_omit_ratio["derived_summary"]["sec_mals_dls"]["all_qualified_mixtures_equimolar_1to1_attested"] is not False
        or r_r16_mix_eq_false["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_r16_mix_bad_basis["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_r16_mix_extra_key["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
    ):
        raise RuntimeError(
            f"R16 0039-M2 per-mixture 1:1 molar ratio attestation validation failed: "
            f"omit={r_r16_mix_omit_ratio['verdict']}, eq_false={r_r16_mix_eq_false['verdict']}, "
            f"bad_basis={r_r16_mix_bad_basis['verdict']}, extra={r_r16_mix_extra_key['verdict']}"
        )

    # 102 (R17 0044-B1): Register QC MUST NOT count as independent Comp1 or Comp2 SPR batch coverage!
    # 1-batch and 2-batch Comp1 SPR MUST HOLD_INVALID_OR_MISSING_INPUT (counts 1 and 2) even when 3 passing
    # batches appear in register_qc_records; 1-batch Comp2 SPR + comparator MUST HOLD (count 1) even when 3
    # batches appear in register_qc_records + crystal_ref_1jk8_14aa; while independent qualified fail-first SPR FAIL
    # is preserved on the 1-batch Comp1 SPR fixture (with Track-B staying INELIGIBLE)!
    c_r17_c1_1b = json.loads(json.dumps(base_pass))
    for a_r in c_r17_c1_1b["on_target_analytes"]:
        if a_r["analyte_id"] in _SHIELD_COMP1_ON_TARGET_ANALYTES:
            a_r["expression_batch_ids"] = ["BATCH_ECOLI_01"]
    for o_r in c_r17_c1_1b["off_target_controls"]:
        if o_r["analyte_id"] in _SHIELD_MANDATORY_COMP1_OFF_TARGET_CONTROLS:
            o_r["expression_batch_ids"] = ["BATCH_ECOLI_01"]
    r_r17_c1_1b = evaluate_gate30_shield_spr(c_r17_c1_1b)

    c_r17_c1_2b = json.loads(json.dumps(base_pass))
    for a_r in c_r17_c1_2b["on_target_analytes"]:
        if a_r["analyte_id"] in _SHIELD_COMP1_ON_TARGET_ANALYTES:
            a_r["expression_batch_ids"] = ["BATCH_ECOLI_01", "BATCH_ECOLI_02"]
    for o_r in c_r17_c1_2b["off_target_controls"]:
        if o_r["analyte_id"] in _SHIELD_MANDATORY_COMP1_OFF_TARGET_CONTROLS:
            o_r["expression_batch_ids"] = ["BATCH_ECOLI_01", "BATCH_ECOLI_02"]
    r_r17_c1_2b = evaluate_gate30_shield_spr(c_r17_c1_2b)

    c_r17_c2_1b = json.loads(json.dumps(base_pass))
    for a_r in c_r17_c2_1b["on_target_analytes"]:
        if a_r["analyte_id"] in _SHIELD_COMP2_ON_TARGET_ANALYTES:
            a_r["expression_batch_ids"] = ["BATCH_ECOLI_01"]
    for o_r in c_r17_c2_1b["off_target_controls"]:
        if o_r["analyte_id"] in _SHIELD_MANDATORY_COMP2_OFF_TARGET_CONTROLS:
            o_r["expression_batch_ids"] = ["BATCH_ECOLI_01"]
    for cp_r in c_r17_c2_1b["comp2_comparators_screened"]:
        if cp_r["comparator_id"] == _SHIELD_COMP2_LEAD:
            cp_r["expression_batch_ids"] = ["BATCH_ECOLI_01"]
            for cond_v in cp_r["register_control_screens"].values():
                if isinstance(cond_v, dict):
                    cond_v["expression_batch_ids"] = ["BATCH_ECOLI_01"]
    r_r17_c2_1b = evaluate_gate30_shield_spr(c_r17_c2_1b)

    c_r17_c1_1b_fail = json.loads(json.dumps(c_r17_c1_1b))
    c_r17_c1_1b_fail["on_target_analytes"][0]["ic50_l95_nm"] = 650.0
    c_r17_c1_1b_fail["on_target_analytes"][0]["ic50_u95_nm"] = 800.0
    r_r17_c1_1b_fail = evaluate_gate30_shield_spr(c_r17_c1_1b_fail)

    if (
        r_r17_c1_1b["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_r17_c1_1b["derived_summary"]["distinct_linked_comp1_assay_batches_count"] != 1
        or r_r17_c1_1b["derived_summary"]["register_qc_excluded_from_spr_assay_batch_counts"] is not True
        or any(rs.startswith("[FAIL]") for rs in r_r17_c1_1b["reasons"])
        or r_r17_c1_2b["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_r17_c1_2b["derived_summary"]["distinct_linked_comp1_assay_batches_count"] != 2
        or any(rs.startswith("[FAIL]") for rs in r_r17_c1_2b["reasons"])
        or r_r17_c2_1b["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_r17_c2_1b["derived_summary"]["distinct_linked_comp2_assay_batches_count"] != 1
        or any(rs.startswith("[FAIL]") for rs in r_r17_c2_1b["reasons"])
        or r_r17_c1_1b_fail["verdict"] != "FAIL"
        or r_r17_c1_1b_fail["derived_summary"]["failure_domain"] != "INDEPENDENT_NON_DONOR_SPR"
        or r_r17_c1_1b_fail["derived_summary"]["distinct_linked_comp1_assay_batches_count"] != 1
        or r_r17_c1_1b_fail["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
    ):
        raise RuntimeError(
            f"R17 0044-B1 register QC excluded from Comp1/Comp2 SPR batch counts failed: "
            f"c1_1b={r_r17_c1_1b['verdict']}/{r_r17_c1_1b['derived_summary']['distinct_linked_comp1_assay_batches_count']}, "
            f"c1_2b={r_r17_c1_2b['verdict']}/{r_r17_c1_2b['derived_summary']['distinct_linked_comp1_assay_batches_count']}, "
            f"c2_1b={r_r17_c2_1b['verdict']}/{r_r17_c2_1b['derived_summary']['distinct_linked_comp2_assay_batches_count']}, "
            f"c1_1b_fail={r_r17_c1_1b_fail['verdict']}/{r_r17_c1_1b_fail['derived_summary']['failure_domain']}"
        )

    # 103 (R17 0044-B2): Mandatory pairwise-distinct peptide reagent lot IDs across ALL mandatory peptide reagents
    # (HIP11, WT15, 6DFX, plus optional 1JK8 if supplied) BEFORE giving dependent records biological or batch credit,
    # while retaining independent qualified evidence!
    c_r17_hip_eq_wt = json.loads(json.dumps(base_pass))
    shared_wt_lot = c_r17_hip_eq_wt["register_qc_records"]["native_wt_insb9_23_15aa"]["peptide_reagent_lot_id"]
    c_r17_hip_eq_wt["register_qc_records"]["hip11_peptide_reagent_lot_id"] = shared_wt_lot
    for a_r in c_r17_hip_eq_wt["on_target_analytes"]:
        if a_r["analyte_id"] in _SHIELD_COMP1_ON_TARGET_ANALYTES:
            a_r["peptide_reagent_lot_id"] = shared_wt_lot
    r_r17_hip_eq_wt = evaluate_gate30_shield_spr(c_r17_hip_eq_wt)

    c_r17_hip_eq_wt_depfail = json.loads(json.dumps(c_r17_hip_eq_wt))
    c_r17_hip_eq_wt_depfail["on_target_analytes"][0]["ic50_l95_nm"] = 650.0
    c_r17_hip_eq_wt_depfail["on_target_analytes"][0]["ic50_u95_nm"] = 800.0
    c_r17_hip_eq_wt_depfail["on_target_analytes"][3]["ic50_l95_nm"] = 650.0
    c_r17_hip_eq_wt_depfail["on_target_analytes"][3]["ic50_u95_nm"] = 800.0
    r_r17_hip_eq_wt_depfail = evaluate_gate30_shield_spr(c_r17_hip_eq_wt_depfail)

    c_r17_hip_eq_wt_indfail = json.loads(json.dumps(c_r17_hip_eq_wt))
    for o_r in c_r17_hip_eq_wt_indfail["off_target_controls"]:
        if o_r["analyte_id"] == "HLA-DQ8 + DQ8-glia-gamma1a":
            o_r["selectivity_l95_fold"] = 3.0
            o_r["selectivity_u95_fold"] = 6.0
    r_r17_hip_eq_wt_indfail = evaluate_gate30_shield_spr(c_r17_hip_eq_wt_indfail)

    c_r17_hip_eq_6dfx = json.loads(json.dumps(base_pass))
    shared_6dfx_lot = c_r17_hip_eq_6dfx["register_qc_records"]["engineered_6dfx_p8e9e_12aa"]["peptide_reagent_lot_id"]
    c_r17_hip_eq_6dfx["register_qc_records"]["hip11_peptide_reagent_lot_id"] = shared_6dfx_lot
    for a_r in c_r17_hip_eq_6dfx["on_target_analytes"]:
        if a_r["analyte_id"] in _SHIELD_COMP1_ON_TARGET_ANALYTES:
            a_r["peptide_reagent_lot_id"] = shared_6dfx_lot
    r_r17_hip_eq_6dfx = evaluate_gate30_shield_spr(c_r17_hip_eq_6dfx)

    c_r17_hip_eq_6dfx_depfail = json.loads(json.dumps(c_r17_hip_eq_6dfx))
    c_r17_hip_eq_6dfx_depfail["on_target_analytes"][0]["ic50_l95_nm"] = 650.0
    c_r17_hip_eq_6dfx_depfail["on_target_analytes"][0]["ic50_u95_nm"] = 800.0
    r_r17_hip_eq_6dfx_depfail = evaluate_gate30_shield_spr(c_r17_hip_eq_6dfx_depfail)

    c_r17_hip_eq_6dfx_indfail = json.loads(json.dumps(c_r17_hip_eq_6dfx))
    for o_r in c_r17_hip_eq_6dfx_indfail["off_target_controls"]:
        if o_r["analyte_id"] == "HLA-DQ2.5 + CLIP1":
            o_r["selectivity_l95_fold"] = 3.0
            o_r["selectivity_u95_fold"] = 6.0
    r_r17_hip_eq_6dfx_indfail = evaluate_gate30_shield_spr(c_r17_hip_eq_6dfx_indfail)

    if (
        r_r17_hip_eq_wt["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_r17_hip_eq_wt["derived_summary"]["mandatory_peptide_reagent_lots_pairwise_distinct"] is not False
        or r_r17_hip_eq_wt["analytes_verified_count"] != 0
        or r_r17_hip_eq_wt["derived_summary"]["comparator_wt15_and_6dfx_verified_count"] != 0
        or any(rs.startswith("[FAIL]") for rs in r_r17_hip_eq_wt["reasons"])
        or r_r17_hip_eq_wt_depfail["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or any(rs.startswith("[FAIL]") for rs in r_r17_hip_eq_wt_depfail["reasons"])
        or r_r17_hip_eq_wt_indfail["verdict"] != "FAIL"
        or r_r17_hip_eq_wt_indfail["derived_summary"]["failure_domain"] != "INDEPENDENT_NON_DONOR_SPR"
        or r_r17_hip_eq_wt_indfail["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
        or r_r17_hip_eq_6dfx["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or r_r17_hip_eq_6dfx["derived_summary"]["mandatory_peptide_reagent_lots_pairwise_distinct"] is not False
        or r_r17_hip_eq_6dfx["analytes_verified_count"] != 0
        or any(rs.startswith("[FAIL]") for rs in r_r17_hip_eq_6dfx["reasons"])
        or r_r17_hip_eq_6dfx_depfail["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or any(rs.startswith("[FAIL]") for rs in r_r17_hip_eq_6dfx_depfail["reasons"])
        or r_r17_hip_eq_6dfx_indfail["verdict"] != "FAIL"
        or r_r17_hip_eq_6dfx_indfail["derived_summary"]["failure_domain"] != "INDEPENDENT_NON_DONOR_SPR"
        or r_r17_hip_eq_6dfx_indfail["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
    ):
        raise RuntimeError(
            f"R17 0044-B2 mandatory pairwise-distinct peptide lot IDs failed: "
            f"hip_wt={r_r17_hip_eq_wt['verdict']}, hip_wt_dep={r_r17_hip_eq_wt_depfail['verdict']}, "
            f"hip_wt_ind={r_r17_hip_eq_wt_indfail['verdict']}, hip_6dfx={r_r17_hip_eq_6dfx['verdict']}, "
            f"hip_6dfx_dep={r_r17_hip_eq_6dfx_depfail['verdict']}, hip_6dfx_ind={r_r17_hip_eq_6dfx_indfail['verdict']}"
        )

    # 104 (R17 0044-B3): Within-donor fixed-family Bonferroni cytotoxicity FAIL (failure_domain=ROSTERED_DONOR_COHORT,
    # authorization_grade_fwer_bound_valid=True under valid fixed-N single-look preregistered roster) is PRESERVED
    # when between-donor population donor_sampling_and_independence_design is missing, malformed, OR valid stratified
    # (while Track-B stays INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE due to the concurrent sampling-design HOLD, and
    # unweighted suppression PASS/FAIL + confirmatory overall PASS strictly require valid SIMPLE_RANDOM_OR_CONSECUTIVE)!
    c_r17_cyto_base = build_valid_shield_spr_observation(n_eff_per_donor=60, donor_k_obs=(10,) + (0,) * 8)

    c_r17_cyto_miss_sd = json.loads(json.dumps(c_r17_cyto_base))
    c_r17_cyto_miss_sd.pop("donor_sampling_and_independence_design", None)
    r_r17_cyto_miss_sd = evaluate_gate30_shield_spr(c_r17_cyto_miss_sd)

    c_r17_cyto_mal_sd = json.loads(json.dumps(c_r17_cyto_base))
    c_r17_cyto_mal_sd["donor_sampling_and_independence_design"]["sampling_design_class"] = "QUOTA_NONRANDOM_COHORT"
    r_r17_cyto_mal_sd = evaluate_gate30_shield_spr(c_r17_cyto_mal_sd)

    c_r17_cyto_strat_sd = json.loads(json.dumps(c_r17_cyto_base))
    c_r17_cyto_strat_sd["donor_sampling_and_independence_design"]["sampling_design_class"] = (
        "STRATIFIED_INDEPENDENT_T1D_HLA_DQ_COHORT"
    )
    c_r17_cyto_strat_sd["donor_sampling_and_independence_design"]["between_donor_independence_justification"] = (
        "STRATIFIED_DISJOINT_BATCH_AND_RUN_T1D_DONOR_COHORT"
    )
    r_r17_cyto_strat_sd = evaluate_gate30_shield_spr(c_r17_cyto_strat_sd)

    c_r17_sup_low = build_valid_shield_spr_observation(n_eff_per_donor=60, donor_suppressions=(20.0,) * 9)
    c_r17_sup_low_miss = json.loads(json.dumps(c_r17_sup_low))
    c_r17_sup_low_miss.pop("donor_sampling_and_independence_design", None)
    r_r17_sup_low_miss = evaluate_gate30_shield_spr(c_r17_sup_low_miss)

    c_r17_sup_low_mal = json.loads(json.dumps(c_r17_sup_low))
    c_r17_sup_low_mal["donor_sampling_and_independence_design"]["sampling_design_class"] = "QUOTA_NONRANDOM_COHORT"
    r_r17_sup_low_mal = evaluate_gate30_shield_spr(c_r17_sup_low_mal)

    c_r17_sup_low_strat = json.loads(json.dumps(c_r17_sup_low))
    c_r17_sup_low_strat["donor_sampling_and_independence_design"]["sampling_design_class"] = (
        "STRATIFIED_INDEPENDENT_T1D_HLA_DQ_COHORT"
    )
    c_r17_sup_low_strat["donor_sampling_and_independence_design"]["between_donor_independence_justification"] = (
        "STRATIFIED_DISJOINT_BATCH_AND_RUN_T1D_DONOR_COHORT"
    )
    r_r17_sup_low_strat = evaluate_gate30_shield_spr(c_r17_sup_low_strat)

    if (
        r_r17_cyto_miss_sd["verdict"] != "FAIL"
        or r_r17_cyto_miss_sd["derived_summary"]["failure_domain"] != "ROSTERED_DONOR_COHORT"
        or r_r17_cyto_miss_sd["derived_summary"]["authorization_grade_fwer_bound_valid"] is not True
        or r_r17_cyto_miss_sd["derived_summary"]["donor_sampling_design_valid"] is not False
        or r_r17_cyto_miss_sd["derived_summary"]["authorization_grade_suppression_inference_valid"] is not False
        or r_r17_cyto_miss_sd["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
        or r_r17_cyto_mal_sd["verdict"] != "FAIL"
        or r_r17_cyto_mal_sd["derived_summary"]["failure_domain"] != "ROSTERED_DONOR_COHORT"
        or r_r17_cyto_mal_sd["derived_summary"]["authorization_grade_fwer_bound_valid"] is not True
        or r_r17_cyto_mal_sd["derived_summary"]["donor_sampling_design_valid"] is not False
        or r_r17_cyto_mal_sd["derived_summary"]["authorization_grade_suppression_inference_valid"] is not False
        or r_r17_cyto_mal_sd["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
        or r_r17_cyto_strat_sd["verdict"] != "FAIL"
        or r_r17_cyto_strat_sd["derived_summary"]["failure_domain"] != "ROSTERED_DONOR_COHORT"
        or r_r17_cyto_strat_sd["derived_summary"]["authorization_grade_fwer_bound_valid"] is not True
        or r_r17_cyto_strat_sd["derived_summary"]["donor_sampling_design_valid"] is not True
        or r_r17_cyto_strat_sd["derived_summary"]["suppression_inference_authorized_by_sampling_design"] is not False
        or r_r17_cyto_strat_sd["derived_summary"]["authorization_grade_suppression_inference_valid"] is not False
        or r_r17_cyto_strat_sd["derived_summary"]["trackb_shield_trigger_state"] != "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
        or r_r17_sup_low_miss["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or any(rs.startswith("[FAIL]") for rs in r_r17_sup_low_miss["reasons"])
        or r_r17_sup_low_mal["verdict"] != "HOLD_INVALID_OR_MISSING_INPUT"
        or any(rs.startswith("[FAIL]") for rs in r_r17_sup_low_mal["reasons"])
        or r_r17_sup_low_strat["verdict"] != "HOLD"
        or any(rs.startswith("[FAIL]") for rs in r_r17_sup_low_strat["reasons"])
        or not any("STRATIFIED_COHORT_REQUIRES_TARGET_WEIGHTED_SUPPRESSION_ESTIMATOR" in rs for rs in r_r17_sup_low_strat["reasons"])
    ):
        raise RuntimeError(
            f"R17 0044-B3 sampling-design vs within-donor Bonferroni cytotoxicity FAIL policy failed: "
            f"miss={r_r17_cyto_miss_sd['verdict']}, mal={r_r17_cyto_mal_sd['verdict']}, "
            f"strat={r_r17_cyto_strat_sd['verdict']}, sup_miss={r_r17_sup_low_miss['verdict']}, "
            f"sup_mal={r_r17_sup_low_mal['verdict']}, sup_strat={r_r17_sup_low_strat['verdict']}"
        )

    cases = {
        "clean_pass_neff_60": r_pass["verdict"],
        "scalar_only_summary_rejected_hold_invalid": r_scalar["verdict"],
        "dq22_hip11_650_800nm_returns_fail": r_dq22_fail["verdict"],
        "missing_dq22_analyte_returns_hold_invalid": r_miss_analyte["verdict"],
        "missing_offtarget_control_returns_hold_invalid": r_miss_ctrl["verdict"],
        "missing_comp2_comparator_returns_hold_invalid": r_miss_comp["verdict"],
        "neff_58_returns_hold_invalid": r_neff_58["verdict"],
        "neff_59_returns_hold_invalid": r_neff_59["verdict"],
        "inconsistent_0pct_with_l95_2pct_returns_hold_invalid": r_inconsist["verdict"],
        "nonzero_1pct_u95_le_5pct_returns_hold_nonzero": r_nz_le5["verdict"],
        "nonzero_1pct_u95_gt_5pct_returns_hold_u95_exceeds_5pct": r_nz_gt5["verdict"],
        "cytotoxicity_l95_gt_5pct_returns_fail": r_cyto_fail["verdict"],
        "conflicting_suppression_fail_and_cyto_1pct_returns_fail": r_overlap["verdict"],
        "fail_dominates_missing_comparator": r_fail_miss["verdict"],
        "intermediate_ic50_returns_hold": r_mid["verdict"],
        "nan_with_concurrent_fail_raises_valueerror": nan_rejected,
        "optional_1jk8_omitted_passes": r_opt_1jk8_omit["verdict"],
        "optional_1jk8_malformed_seq_rejected_hold_invalid": r_bad_1jk8["verdict"],
        "missing_comp1_offtarget_controls_rejected_hold_invalid": r_no_comp1_off["verdict"],
        "missing_expression_batch_linkage_rejected_hold_invalid": r_no_batch_link["verdict"],
        "under_referenced_expression_batches_rejected_hold_invalid": r_only_2_batches["verdict"],
        "monomer_1pct_with_qc_passed_true_rejected_hold_invalid": r_1pct_mon["verdict"],
        "dls_pdi_exceeds_0p15_rejected_hold_invalid": r_bad_pdi["verdict"],
        "missing_donor_hla_genotype_rejected_hold_invalid": r_no_hla["verdict"],
        "nonqualifying_donor_hla_dq6_rejected_hold_invalid": r_dq6["verdict"],
        "gy018_clustered_deff_gt_1_rejected_hold_invalid": r_deff["verdict"],
        "gy018_neff_ne_raw_units_rejected_hold_invalid": r_neff_mismatch["verdict"],
        "overstated_u95_99pct_on_0_of_60_rejected_hold_invalid": r_u95_99["verdict"],
        "float_magnitude_gt_1e300_raises_valueerror": float_ovf_rejected,
        "df21_22donor_student_t_nonauthorizing_and_clopper_pearson_verified": (
            r_df21_split["verdict"] == "HOLD" and r_df21_all_resp["verdict"] == "PASS"
        ),
        "empty_construct_batches_linked_all_assays_rejected_hold_invalid": r_empty_batches["verdict"],
        "wrong_construct_unrelated_batch_dq25_hip11_rejected_hold_invalid": r_wrong_construct["verdict"],
        "wrong_construct_comparator_batch_rejected_hold_invalid": r_wrong_comp_batch["verdict"],
        "separate_comp1_and_comp2_batches_pass": r_sep_batches["verdict"],
        "exact_deff_1p0000000000005_rejected_hold_invalid": r_deff_tiny["verdict"],
        "invalid_donor_deff_1p1_15of60_holds_not_bio_fail": r_deff_15["verdict"],
        "independent_spr_fail_dominates_invalid_deff_donor": r_spr_fail_bad_deff["verdict"],
        "bonferroni_calibrated_7_0_0_of_60_holds_not_false_fail": r_bonf_700["verdict"],
        "bonferroni_calibrated_9_0_0_of_60_triggers_fail": r_bonf_900["verdict"],
        "optional_1jk8_explicit_null_passes": r_1jk8_null["verdict"],
        "invalid_wrong_batch_650_800nm_holds_not_fail": r_bad_batch_650["verdict"],
        "invalid_replicates1_650_800nm_holds_not_fail": r_rep1_650["verdict"],
        "unregistered_analyte_650_800nm_holds_not_fail": r_unreg_650["verdict"],
        "unregistered_offtarget_low_sel_holds_not_fail": r_unreg_off["verdict"],
        "invalid_row_plus_separate_valid_fail_returns_fail": r_invalid_plus_valid_fail["verdict"],
        "raw_json_exact_deff_precision_preserved": True,
        "correlated_4_4_4_of_60_holds_not_false_fail": r_corr_444["verdict"],
        "exact_binomial_bonferroni_fwer_le_0p05_verified": True,
        "duplicate_on_target_analyte_both_orders_hold_invalid": (
            r_dup_ot_pf["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_dup_ot_fp["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
        ),
        "duplicate_alias_analyte_both_orders_hold_invalid": (
            r_dup_alias_pf["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_dup_alias_fp["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
        ),
        "duplicate_analyte_plus_separate_valid_fail_returns_fail": r_dup_plus_valid_fail["verdict"],
        "duplicate_offtarget_batch_donor_order_independent_hold_invalid": True,
        "six_donor_8_of_60_preexclusion_denom6_preserved_hold": r_6don_corrupt3["verdict"],
        "ten_donor_8_of_60_preexclusion_denom10_preserved_hold": r_10don_corrupt7["verdict"],
        "planned_family_n_enforced_without_shrinkage_hold": (
            r_plan10_800["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_plan10_000["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_plan3_on_6["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
        ),
        "ten_donor_genuine_9_of_60_with_7_corrupt_returns_fail": r_10don_9_corrupt7["verdict"],
        "healthy_control_donors_rejected_hold_invalid": r_healthy["verdict"],
        "forged_t1d_flags_on_healthy_control_rejected_hold_invalid": r_forged_healthy["verdict"],
        "missing_or_invalid_t1d_eligibility_fields_rejected_hold_invalid": True,
        "ineligible_nont1d_donor_15of60_excluded_from_bio_fail_hold": r_inelig_15["verdict"],
        "missing_preregistered_roster_800_and_900_hold_invalid_never_fail": (
            r_no_roster_800["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_no_roster_900["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
        ),
        "tampered_roster_sha256_hold_invalid_never_pass_or_fail": (
            r_tamper_pass["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_tamper_900["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
        ),
        "incomplete_10donor_roster_7_omitted_hold_invalid_never_fail": r_omit7_900["verdict"],
        "full_10donor_8_of_60_holds_and_excl7_9_of_60_fails_at_n10": (
            r_full10_800["verdict"] == "HOLD_CYTOTOXICITY_U95_EXCEEDS_5PCT"
            and r_excl7_900["verdict"] == "FAIL"
        ),
        "unrostered_donor_false_lock_late_prereg_all_hold_invalid": True,
        "zero_variance_n3_80_80_80_and_n8_hold_never_false_pass": (
            r_3don_80["verdict"] == "HOLD" and r_8don_80["verdict"] == "HOLD"
        ),
        "confirmatory_n9_9of9_passes_and_8of9_holds": (
            r_9of9_80["verdict"] == "PASS" and r_8of9_80_40["verdict"] == "HOLD"
        ),
        "anti_enhancement_negative_suppression_holds_and_n3_30_holds": (
            r_enh_10["verdict"] == "HOLD" and r_enh_20["verdict"] == "HOLD" and r_3don_30["verdict"] == "HOLD"
        ),
        "exact_clopper_pearson_suppression_calibration_le_0p05_verified": True,
        "gy018_independence_justification_enforced_hold_invalid": True,
        "r10_duplicated_unrostered_donor_with_18of60_holds_invalid": (
            r_18_once["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_18_twice["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_18_anon["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
        ),
        "r10_preassay_exclusion_13of14_holds_never_pass_and_9of60_still_fails": (
            r_excl1_14_pass_attempt["verdict"] == "HOLD" and r_excl1_14_fail["verdict"] == "FAIL"
        ),
        "r10_clustered_3x3_shared_batches_all80_and_all30_hold": (
            r_batch3x3_80["verdict"] == "HOLD"
            and r_batch3x3_30["verdict"] == "HOLD"
            and r_sep_3shared["verdict"] == "HOLD"
        ),
        "r10_single_shared_assay_run_all80_and_all30_hold": (
            r_run1x9_80["verdict"] == "HOLD"
            and r_run1x9_30["verdict"] == "HOLD"
            and r_staircase["verdict"] == "HOLD"
        ),
        "r10_missing_or_invalid_donor_sampling_design_holds_invalid": (
            r_no_sd["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_bad_sd["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_no_run["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
        ),
        "r10_gy018_explicitly_clustered_text_and_invalid_class_hold_invalid": (
            r_gy_clustered_txt["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_gy_bad_cls["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_gy_bad_flag["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
        ),
        "r10_unified_missing_roster_vs_independent_spr_fail_and_donor_hold": (
            r_noroster_cyto18["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_noroster_sprfail["verdict"] == "FAIL"
        ),
        "r10_extreme_finite_suppression_neg1e200_no_overflow_hold_invalid": (
            r_neg1e200_direct["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_neg1e200_json["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
        ),
        "r10_wt15_analyte_peptide_sequence_and_reagent_lot_linkage_enforced": (
            r_wt_noseq["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_wt_badlot["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
        ),
        "r10_external_custody_required_and_cluster_calibration_proof": True,
        "r11_0037_b1_stratified_8to1_9of9_holds_not_pass": (
            r_strat_8to1["verdict"] == "HOLD" and r_srs_9of9["verdict"] == "PASS"
        ),
        "r11_0039_b1_stratified_20to1_20of21_holds_not_pass": r_strat_20to1["verdict"],
        "r11_stratified_1to20_low_rate_holds_not_fail_and_legacy_quota_rejected": (
            r_strat_1to20_low["verdict"] == "HOLD"
            and r_srs_1to20_low["verdict"] == "FAIL"
            and r_legacy_prosp["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_quota_cls["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
        ),
        "r11_stratified_preserves_spr_and_bonferroni_cyto_fail_plus_m1_range": (
            r_strat_spr_fail["verdict"] == "FAIL"
            and r_strat_cyto_fail["verdict"] == "FAIL"
            and r_strat_enh["verdict"] == "HOLD"
        ),
        "r12_0039_b1_wt15_and_hip11_register_qc_reconciled_before_bio_and_batch_credit": (
            r_wt_match_fail["verdict"] == "FAIL"
            and r_wt_mis_fail["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_wt_mis_plus_c1_fail["verdict"] == "FAIL"
            and r_wt_lcms_bad_fail["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_wt_6dfx_bad_fail["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_hip11_qc_bad_c1_fail["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_hip11_qc_bad_wt_fail["verdict"] == "FAIL"
            and r_wt_nocredit["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
        ),
        "r12_0037_b2_bridge_donor_topology_retained_and_incomplete_topology_holds": (
            r_bridge14_clean["verdict"] == "HOLD"
            and r_bridge14_bad_ci["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_bridge14_no_batch["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_bridge14_no_run["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_bridge14_no_batch_spr_fail["verdict"] == "FAIL"
            and r_bridge14_no_batch_cyto_fail["verdict"] == "FAIL"
        ),
        "r12_0037_b3_strict_gy018_and_sampling_canonical_allowlist_closed_schema": (
            r_gy_microscopy["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_gy_freetext["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_gy_cross_cls["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_gy_extra_key["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_sd_freetext["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_gy_droplet_ok["verdict"] == "PASS"
        ),
        "r12_0039_m1_non_inverted_signed_student_t_suppression_diagnostic": (
            r_neg5_all["verdict"] == "FAIL"
            and r_neg5_n3["verdict"] == "HOLD"
            and n5_ds["suppression_l95_t_diagnostic_only_pct"] == -5.0
            and n5_ds["suppression_u95_t_diagnostic_only_pct"] == -5.0
            and r_neg_var["verdict"] == "FAIL"
        ),
        "r13_0039_b1_0037_b2_hip11_parent_batch_register_qc_bound": (
            r_hip11_bad_rqc_batch["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_hip11_bad_rqc_nocredit["derived_summary"]["distinct_linked_comp1_assay_batches_count"] == 2
            and r_hip11_bad_rqc_plus_ind_spr["verdict"] == "FAIL"
        ),
        "r13_0039_b1_0037_b2_wt15_offtarget_lot_and_sequence_bound": (
            r_off_wt_match_fail["verdict"] == "FAIL"
            and r_off_wt_missing_lot["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_off_wt_wrong_lot["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_off_wt_wrong_seq["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_off_wt_nocredit["derived_summary"]["distinct_linked_comp2_assay_batches_count"] == 2
            and r_off_wt_wrong_plus_c1_fail["verdict"] == "FAIL"
        ),
        "r13_0039_b2_0037_m1_physicochemical_out_of_spec_vs_malformed_vs_spr_fail": (
            r_phys_oos_noroster["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_phys_oos_noroster["derived_summary"]["failure_domain"] is None
            and r_phys_malformed["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_phys_contra["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
        ),
        "r13_0037_b3_trackb_shield_trigger_state_and_m1_m2_scope_tags": (
            r_pass["derived_summary"]["trackb_shield_trigger_state"] == "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
            and r_partial_comp2_fail_noroster["derived_summary"]["trackb_shield_trigger_state"] == "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
            and r_wt_match_fail["derived_summary"]["trackb_shield_trigger_state"] == "ELIGIBLE_CANDIDATE_SHIELD1_ONLY_COMP2_FAIL_PENDING_XREACT_AND_OWNER_REAUTH"
            and r_off_wt_match_fail["derived_summary"]["trackb_shield_trigger_state"] == "ELIGIBLE_CANDIDATE_SHIELD1_ONLY_COMP2_FAIL_PENDING_XREACT_AND_OWNER_REAUTH"
            and r_dq22_fail["derived_summary"]["trackb_shield_trigger_state"] == "ELIGIBLE_CANDIDATE_OVERALL_SHIELD_FAIL_PENDING_XREACT_AND_OWNER_REAUTH"
            and r_overall_tcell_fail["derived_summary"]["trackb_shield_trigger_state"] == "ELIGIBLE_CANDIDATE_OVERALL_SHIELD_FAIL_PENDING_XREACT_AND_OWNER_REAUTH"
        ),
        "r16_shared_b1_per_mixture_coformulation_crossed_lots_hold_invalid": (
            r_r16_sep_ctrl["verdict"] == "PASS"
            and r_r16_crossed["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_r16_crossed_cyto20["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_r16_crossed_ind_spr["verdict"] == "FAIL"
            and r_r16_mix_oos_overstate["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
        ),
        "r16_shared_b2_comparator_shared_wt15_6dfx_batch_required_hold_invalid": (
            r_r16_comp_disj["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_r16_comp_disj_c2fail["verdict"] == "FAIL"
            and r_r16_comp_disj_c2fail["derived_summary"]["trackb_shield_trigger_state"] == "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
        ),
        "r16_shared_b3_fixed_n_and_single_look_locked_in_roster_sha256": (
            r_r16_look1_66["verdict"] == "FAIL"
            and r_r16_look2_170_same_sha["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_r16_look2_170_tamper_roster_n["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_r16_multilook["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_r16_look2_ind_spr["verdict"] == "FAIL"
            and r_r16_hetero_n_ok["verdict"] == "PASS"
        ),
        "r16_0039_m3_optional_1jk8_malformed_lot_rejected_hold_invalid": (
            r_r16_1jk8_lot17["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_r16_1jk8_lot_none["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_r16_1jk8_lot_reuse["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_r16_1jk8_lot_ok["verdict"] == "PASS"
        ),
        "r16_shared_b1_duplicate_donor_60_70_order_holds_invalid_and_flags_n_mismatch": (
            r_r16_dup_60_70["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_r16_dup_60_70["derived_summary"]["roster_sample_size_plan_mismatched_donors"] == ["T1D_DONOR_01"]
            and r_r16_dup_60_70["derived_summary"]["authorization_grade_fwer_bound_valid"] is False
        ),
        "r16_shared_b1_duplicate_donor_70_60_reverse_order_holds_invalid_and_flags_n_mismatch": (
            r_r16_dup_70_60["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_r16_dup_70_60["derived_summary"]["roster_sample_size_plan_mismatched_donors"] == ["T1D_DONOR_01"]
            and r_r16_dup_70_60["derived_summary"]["authorization_grade_fwer_bound_valid"] is False
        ),
        "r16_shared_b1_matching_count_duplicate_60_60_zero_credit_no_false_n_mismatch": (
            r_r16_dup_60_60["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_r16_dup_60_60["derived_summary"]["valid_donors_count"] == 8
            and r_r16_dup_60_60["derived_summary"]["roster_sample_size_plan_mismatched_donors"] == []
        ),
        "r16_shared_b1_duplicate_60_70_plus_independent_spr_fail_preserves_spr_domain_only": (
            r_r16_dup_60_70_spr["verdict"] == "FAIL"
            and r_r16_dup_60_70_spr["derived_summary"]["failure_domain"] == "INDEPENDENT_NON_DONOR_SPR"
            and r_r16_dup_60_70_spr["derived_summary"]["authorization_grade_fwer_bound_valid"] is False
            and r_r16_dup_60_70_spr["derived_summary"]["roster_sample_size_plan_mismatched_donors"] == ["T1D_DONOR_01"]
        ),
        "r16_0039_m2_per_mixture_1to1_molar_ratio_attestation_closed_schema": (
            r_pass["derived_summary"]["sec_mals_dls"]["all_qualified_mixtures_equimolar_1to1_attested"] is True
            and r_r16_mix_omit_ratio["verdict"] == "PASS"
            and r_r16_mix_eq_false["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_r16_mix_bad_basis["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_r16_mix_extra_key["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
        ),
        "r17_0044_b1_register_qc_not_counted_as_comp1_or_comp2_spr_batch_coverage": (
            r_r17_c1_1b["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_r17_c1_1b["derived_summary"]["distinct_linked_comp1_assay_batches_count"] == 1
            and r_r17_c1_2b["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_r17_c1_2b["derived_summary"]["distinct_linked_comp1_assay_batches_count"] == 2
            and r_r17_c2_1b["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_r17_c2_1b["derived_summary"]["distinct_linked_comp2_assay_batches_count"] == 1
            and r_r17_c1_1b_fail["verdict"] == "FAIL"
            and r_r17_c1_1b_fail["derived_summary"]["failure_domain"] == "INDEPENDENT_NON_DONOR_SPR"
        ),
        "r17_0044_b2_mandatory_pairwise_distinct_peptide_lots_hip11_wt15_6dfx": (
            r_r17_hip_eq_wt["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_r17_hip_eq_wt_depfail["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_r17_hip_eq_wt_indfail["verdict"] == "FAIL"
            and r_r17_hip_eq_6dfx["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_r17_hip_eq_6dfx_depfail["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_r17_hip_eq_6dfx_indfail["verdict"] == "FAIL"
        ),
        "r17_0044_b3_sampling_design_missing_malformed_stratified_preserves_bonf_cyto_fail": (
            r_r17_cyto_miss_sd["verdict"] == "FAIL"
            and r_r17_cyto_miss_sd["derived_summary"]["failure_domain"] == "ROSTERED_DONOR_COHORT"
            and r_r17_cyto_miss_sd["derived_summary"]["trackb_shield_trigger_state"] == "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
            and r_r17_cyto_mal_sd["verdict"] == "FAIL"
            and r_r17_cyto_mal_sd["derived_summary"]["failure_domain"] == "ROSTERED_DONOR_COHORT"
            and r_r17_cyto_mal_sd["derived_summary"]["trackb_shield_trigger_state"] == "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
            and r_r17_cyto_strat_sd["verdict"] == "FAIL"
            and r_r17_cyto_strat_sd["derived_summary"]["failure_domain"] == "ROSTERED_DONOR_COHORT"
            and r_r17_cyto_strat_sd["derived_summary"]["trackb_shield_trigger_state"] == "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE"
            and r_r17_sup_low_miss["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_r17_sup_low_mal["verdict"] == "HOLD_INVALID_OR_MISSING_INPUT"
            and r_r17_sup_low_strat["verdict"] == "HOLD"
        ),
    }
    return {
        "total_cases": len(cases),
        "all_passed": True,
        "cases": cases,
    }


def recompute_gate_counts(rows: list[dict[str, Any]], label: str) -> dict[str, int]:
    """Recompute PASS / PARTIAL / FAIL / total tallies directly from registered gate rows."""
    require_cond(isinstance(rows, list) and len(rows) > 0, f"{label} registered_gates must be a non-empty list")
    counts = {"PASS": 0, "PARTIAL": 0, "FAIL": 0}
    for row in rows:
        res = str(row.get("result") or "").strip().upper()
        if res == "PASS" or res.startswith("PASS "):
            counts["PASS"] += 1
        elif res == "PARTIAL" or res.startswith("PARTIAL "):
            counts["PARTIAL"] += 1
        elif res == "FAIL" or res.startswith("FAIL "):
            counts["FAIL"] += 1
        else:
            raise RuntimeError(f"Unrecognized gate result {res!r} in {label}: {row.get('gate')!r}")
    counts["total"] = len(rows)
    return counts


def verify_stage0_tier1_audit_parity(
    summary: dict[str, Any],
    side_contract: dict[str, Any],
    dt_block: dict[str, Any],
    protocol_text: str,
) -> dict[str, Any]:
    # 1. Zero-credit odds lock across all 3 structured artifacts
    require_cond(summary.get("live_odds_credit_pp") == 0.0, "Summary live_odds_credit_pp must be 0.0")
    require_cond(side_contract.get("live_odds_credit_pp") == 0.0, "Side-contract live_odds_credit_pp must be 0.0")
    require_cond(side_contract.get("live_headline_delta_pp_today") == 0.0, "Side-contract live_headline_delta_pp_today must be 0.0")
    dt_entry = dt_block.get("foundry_v1_3_cleanroom_biologics_registration_iip_0044", dt_block)
    require_cond(dt_entry.get("live_headline_odds_delta_pp") == 0.0, "DEC-123 live_headline_odds_delta_pp must be 0.0")
    require_cond(dt_entry.get("decision_id") == "DEC-123", "DEC-123 decision_id mismatch")
    require_cond(dt_entry.get("contribution_id") == "IIP-0044", "IIP-0044 contribution_id mismatch")
    require_cond(dt_entry.get("graveyard_new_ids_allocated") == 0, "IIP-0044 must allocate 0 new Graveyard IDs")
    require_cond(dt_entry.get("tier2_hosted_files_deposited") == 0, "IIP-0044 must deposit 0 Tier-2 files")

    # 2. Enforce exact 18 active PMIDs (including ALL 3 core HLA-DQ PMIDs: 18252895, 21912932, 22315720)
    #    and reject misattributed upstream PMID 22229122!
    for label, cits in (
        ("side_contract.primary_citations", side_contract.get("primary_citations", [])),
        ("decision_tree.primary_citations", dt_entry.get("primary_citations", [])),
    ):
        require_cond(isinstance(cits, list) and len(cits) == len(set(cits)), f"Duplicate or non-list citations in {label}")
        require_cond(
            all(_MISATTRIBUTED_UPSTREAM_PMID not in str(c) for c in cits),
            f"Misattributed upstream PMID found in active {label}",
        )
        cit_set = set(cits)
        require_cond(
            EXPECTED_CORE_HLA_DQ_PMIDS.issubset(cit_set),
            f"Missing required core HLA-DQ PMIDs in {label}: {sorted(EXPECTED_CORE_HLA_DQ_PMIDS - cit_set)}",
        )
        require_cond(
            cit_set == EXPECTED_ACTIVE_PMIDS_18,
            f"Active 18-PMID set mismatch in {label}: missing={sorted(EXPECTED_ACTIVE_PMIDS_18 - cit_set)}, extra={sorted(cit_set - EXPECTED_ACTIVE_PMIDS_18)}",
        )

    # 2a. R06 B5: Strict typed citation role enforcement & negative semantic contradiction guard across
    #     DEC-123, side_contract, summary, and protocol_text!
    def _verify_typed_citation_roles_map(roles_obj: Any, lbl: str) -> None:
        require_cond(isinstance(roles_obj, dict), f"Missing typed_citation_roles dict in {lbl}")
        require_cond(
            set(roles_obj.keys()) == set(EXPECTED_TYPED_CITATION_ROLES.keys()),
            f"typed_citation_roles key mismatch in {lbl}: got {sorted(roles_obj.keys())}, expected {sorted(EXPECTED_TYPED_CITATION_ROLES.keys())}",
        )
        for pmid_k, exp_role in EXPECTED_TYPED_CITATION_ROLES.items():
            actual_role = roles_obj.get(pmid_k)
            require_cond(type(actual_role) is str, f"typed_citation_roles[{pmid_k}] in {lbl} must be a string (got {actual_role!r})")
            require_cond(
                actual_role not in FORBIDDEN_CITATION_ROLE_ENUMS,
                f"Forbidden direct-efficacy citation role {actual_role!r} assigned to {pmid_k} in {lbl}",
            )
            require_cond(
                actual_role == exp_role,
                f"typed_citation_roles[{pmid_k}] mismatch in {lbl}: got {actual_role!r}, expected {exp_role!r}",
            )

    def _iter_all_string_fields(obj: Any, path: str = "$") -> list[tuple[str, str]]:
        """Recursively collect (path, text) for EVERY string value across an arbitrary JSON tree
        (and key+value strings whenever a dict key anchors a scoped citation such as PMID:31556206).
        """
        out: list[tuple[str, str]] = []
        if type(obj) is str:
            out.append((path, obj))
        elif isinstance(obj, dict):
            for k, v in obj.items():
                child_path = f"{path}.{k}"
                if type(v) is str and type(k) is str and _RE_CITATION_ROLE_ANCHOR.search(k):
                    out.append((child_path, f"{k}: {v}"))
                out.extend(_iter_all_string_fields(v, child_path))
        elif isinstance(obj, list):
            for idx, item in enumerate(obj):
                out.extend(_iter_all_string_fields(item, f"{path}[{idx}]"))
        return out

    def _split_prose_sentences(text_val: str) -> list[str]:
        sents: list[str] = []
        for line in text_val.splitlines():
            if not line.strip():
                continue
            parts = re.split(r"(?<=[.!?])\s+(?=[A-Z0-9`\"(\[])", line)
            sents.extend([p for p in parts if p.strip()])
        return sents

    def _assert_no_citation_role_contradiction(text_val: str, lbl: str) -> None:
        # 1. Clause-level check (same sentence / clause)
        for clause in re.split(r"[.;\n]+|,\s*(?:while|whereas|but|however)\b", text_val, flags=re.IGNORECASE):
            if not _RE_CITATION_ROLE_ANCHOR.search(clause):
                continue
            for m in _RE_CITATION_DIRECT_EFFICACY_CLAIM.finditer(clause):
                prefix_window = clause[max(0, m.start() - 60) : m.start()]
                if not _RE_NEGATION_BEFORE_CLAIM.search(prefix_window):
                    raise RuntimeError(
                        f"Citation-role semantic contradiction in {lbl}: affirmative clinical/therapeutic efficacy "
                        f"claim {m.group(0)!r} attached to scoped epidemiological/assay reference in clause {clause.strip()!r}"
                    )
        # 2. Cross-sentence adjacent window check within each paragraph (R08 B4a: catches split-sentence reversals
        #    such as 'The source is PMID:31556206. Its randomized type 1 diabetes trial clinically validated Islet-SHIELD.')
        for para in re.split(r"\n\s*\n", text_val):
            sents = _split_prose_sentences(para)
            for s_idx, sent in enumerate(sents):
                for m in _RE_CITATION_DIRECT_EFFICACY_CLAIM.finditer(sent):
                    prefix_window = sent[max(0, m.start() - 80) : m.start()]
                    if _RE_NEGATION_BEFORE_CLAIM.search(prefix_window):
                        continue
                    neighbors = [
                        sents[j]
                        for j in range(max(0, s_idx - 2), min(len(sents), s_idx + 3))
                        if j != s_idx
                    ]
                    if any(_RE_CITATION_ROLE_ANCHOR.search(nb) for nb in neighbors):
                        raise RuntimeError(
                            f"Cross-sentence citation-role semantic contradiction in {lbl}: affirmative clinical/therapeutic "
                            f"efficacy claim {m.group(0)!r} in sentence {sent.strip()!r} adjacent to scoped reference anchor"
                        )

    _verify_typed_citation_roles_map(dt_entry.get("typed_citation_roles"), "DEC-123")
    _verify_typed_citation_roles_map(
        side_contract.get("upstream_citation_audit_correction", {}).get("typed_citation_roles"),
        "iip0044_side_contract.upstream_citation_audit_correction",
    )
    _verify_typed_citation_roles_map(summary.get("typed_citation_roles"), "iip0044_summary")

    dt_cit_note = dt_entry.get("citation_role_note")
    require_cond(type(dt_cit_note) is str and bool(dt_cit_note.strip()), "DEC-123 missing non-empty citation_role_note")
    for req_pmid_num in ("18252895", "21912932", "22315720", "31556206"):
        require_cond(req_pmid_num in dt_cit_note, f"DEC-123 citation_role_note missing PMID:{req_pmid_num}")
    require_cond(
        "epidemiological" in dt_cit_note.lower() and "peptidomics" in dt_cit_note.lower(),
        "DEC-123 citation_role_note must explicitly scope epidemiological and cross-product peptidomics roles",
    )
    require_cond(
        bool(
            re.search(
                r"(?i)\b(?:not|do\s+not|does\s+not|neither|none)\b[^.\n]{0,70}\b(?:therapeutic\s+coverage|clinical\s+(?:efficacy|validation)|binding\s+efficacy)\b",
                dt_cit_note,
            )
        ),
        "DEC-123 citation_role_note missing explicit disclaimer denying direct T1D clinical efficacy / therapeutic coverage",
    )
    # R07 B4 + R08 B4: Recursively scan EVERY string value across ALL FOUR authored surfaces (DEC-123, side_contract,
    # Tier-1 summary JSON, AND protocol Markdown) for bounded deterministic citation-role & bidirectional 1JK8 regressions!
    all_surface_strings: list[tuple[str, str]] = (
        _iter_all_string_fields(dt_entry, "DEC-123")
        + _iter_all_string_fields(side_contract, "iip0044_side_contract")
        + _iter_all_string_fields(summary, "iip0044_summary")
        + [("iip0044_protocol", protocol_text)]
    )
    for field_lbl, field_text in all_surface_strings:
        _assert_no_citation_role_contradiction(field_text, field_lbl)
        conf_hit = _find_unnegated_1jk8_conflation(field_text)
        require_cond(
            conf_hit is None,
            f"Conflation equating PDB 1JK8 with native WT InsB:9-23 prohibited in {field_lbl}: matched {conf_hit!r}",
        )

    # 2b. Enforce exact 6 wwPDB CC0-1.0 IDs bound to primary PMIDs and 3 UniProtKB CC-BY-4.0 accessions bound to gene & slice (M1)
    for lbl, container in (
        ("iip0044_summary", summary.get("structural_and_sequence_references")),
        ("iip0044_side_contract", side_contract.get("structural_and_sequence_references")),
    ):
        require_cond(isinstance(container, dict), f"Missing typed structural_and_sequence_references in {lbl}")
        pdb_rows = container.get("pdb_references")
        up_rows = container.get("uniprot_references")
        require_cond(isinstance(pdb_rows, list) and len(pdb_rows) == 6, f"Expected 6 typed pdb_references in {lbl}")
        require_cond(isinstance(up_rows, list) and len(up_rows) == 3, f"Expected 3 typed uniprot_references in {lbl}")
        pdb_ids: list[str] = []
        for r in pdb_rows:
            require_cond(isinstance(r, dict), f"Non-dict pdb_reference row in {lbl}")
            pid = str(r.get("pdb_id") or "")
            pdb_ids.append(pid)
            require_cond(pid in EXPECTED_PDB_TO_PRIMARY_PMID_6, f"Unexpected PDB ID {pid!r} in {lbl}")
            require_cond(r.get("license") == "CC0-1.0", f"PDB {pid} must declare CC0-1.0 license in {lbl}")
            require_cond(
                r.get("primary_citation_pmid") == EXPECTED_PDB_TO_PRIMARY_PMID_6[pid],
                f"PDB {pid} primary_citation_pmid mismatch in {lbl}: got {r.get('primary_citation_pmid')!r}, expected {EXPECTED_PDB_TO_PRIMARY_PMID_6[pid]!r}",
            )
        up_ids: list[str] = []
        for r in up_rows:
            require_cond(isinstance(r, dict), f"Non-dict uniprot_reference row in {lbl}")
            uid = str(r.get("accession") or "")
            up_ids.append(uid)
            require_cond(uid in EXPECTED_UNIPROT_TO_GENE_AND_SLICE_3, f"Unexpected UniProt accession {uid!r} in {lbl}")
            exp_gene, exp_slice = EXPECTED_UNIPROT_TO_GENE_AND_SLICE_3[uid]
            require_cond(r.get("license") == "CC-BY-4.0", f"UniProt {uid} must declare CC-BY-4.0 license in {lbl}")
            require_cond(r.get("gene") == exp_gene, f"UniProt {uid} gene mismatch in {lbl}: got {r.get('gene')!r}, expected {exp_gene!r}")
            require_cond(
                r.get("slice_1based_closed") == exp_slice,
                f"UniProt {uid} slice mismatch in {lbl}: got {r.get('slice_1based_closed')!r}, expected {exp_slice!r}",
            )
        require_cond(len(pdb_ids) == len(set(pdb_ids)) and set(pdb_ids) == EXPECTED_PDB_IDS_6, f"Typed 6-PDB set mismatch in {lbl}: {pdb_ids}")
        require_cond(len(up_ids) == len(set(up_ids)) and set(up_ids) == EXPECTED_UNIPROT_ACCESSIONS_3, f"Typed 3-UniProt set mismatch in {lbl}: {up_ids}")

    dt_refs = dt_entry.get("structural_and_sequence_references")
    require_cond(isinstance(dt_refs, dict), "Missing typed structural_and_sequence_references in DEC-123")
    dt_pdbs = dt_refs.get("pdb_ids", [])
    dt_ups = dt_refs.get("uniprot_accessions", [])
    require_cond(isinstance(dt_pdbs, list) and len(dt_pdbs) == len(set(dt_pdbs)) and set(dt_pdbs) == EXPECTED_PDB_IDS_6, f"DEC-123 6-PDB set mismatch: {dt_pdbs}")
    require_cond(isinstance(dt_ups, list) and len(dt_ups) == len(set(dt_ups)) and set(dt_ups) == EXPECTED_UNIPROT_ACCESSIONS_3, f"DEC-123 3-UniProt set mismatch: {dt_ups}")

    # 3. Shared IIP-0042 B5 / IIP-0044 B3: Typed 1JK8 / WT InsB:9-23 / 6DFX binding & tightened anti-conflation
    def _verify_typed_peptide_records(reg_obj: Any, lbl: str) -> None:
        require_cond(isinstance(reg_obj, dict), f"Missing typed peptide reference records in {lbl}")
        for rkey, exp in EXPECTED_INSB_REFERENCE_PEPTIDES.items():
            rec = reg_obj.get(rkey)
            require_cond(isinstance(rec, dict), f"Missing typed peptide record {rkey!r} in {lbl}")
            for fkey, fval in exp.items():
                require_cond(
                    rec.get(fkey) == fval,
                    f"Typed peptide record mismatch in {lbl}.{rkey}.{fkey}: got {rec.get(fkey)!r}, expected {fval!r}",
                )

    _verify_typed_peptide_records(
        summary["programs"]["Islet_SHIELD_2Component_Cocktail"]["component_2"].get("register_and_peptide_identity_separation"),
        "iip0044_summary",
    )
    _verify_typed_peptide_records(
        side_contract["programs_registered"]["Islet_SHIELD"]["component_2"].get("register_and_peptide_identity_separation"),
        "iip0044_side_contract",
    )
    _verify_typed_peptide_records(
        dt_entry.get("register_and_peptide_reference_records"),
        "DEC-123",
    )

    for lbl, blob in (
        ("iip0044_summary", json.dumps(summary, ensure_ascii=False)),
        ("iip0044_side_contract", json.dumps(side_contract, ensure_ascii=False)),
        ("iip0044_protocol", protocol_text),
        ("DEC-123", json.dumps(dt_entry, ensure_ascii=False)),
    ):
        conf_blob = _find_unnegated_1jk8_conflation(blob)
        require_cond(
            conf_blob is None,
            f"Conflation equating PDB 1JK8 with native WT InsB:9-23 prohibited in {lbl}: matched {conf_blob!r}",
        )
        for req_seq in ("LVEALYLVCGERGG", "SHLVEALYLVCGERG", "VEELYLVAGEEG"):
            require_cond(req_seq in blob, f"Missing separated peptide sequence {req_seq} in {lbl}")

    # 4. Full 71-file Tier-1 + 5-file excluded Tier-2 manifest provenance, STRICT POSITIVE INT BYTES,
    #    valid SPDX labels, & deterministic SHA256SUMS.txt reconstruction (B4)
    prov = summary["source_cleanroom_bundle"]
    require_cond(prov["sha256sums_sha256"] == EXPECTED_BUNDLE_SHA256SUMS_SHA256, "Bundle SHA256SUMS pin mismatch")
    require_cond(prov["bundle_files_verified"] == 76, "Bundle must verify 76/76 files")
    require_cond(prov["tier1_open_weights_files_in_bundle"] == 71, "Expected 71 Tier-1 bundle files")
    require_cond(prov["tier2_carved_out_files_excluded_from_openislet"] == 5, "Expected 5 excluded Tier-2 bundle files")
    require_cond(summary["tos_quarantine_compliance"]["tier2_hosted_files_copied"] == 0, "Tier-2 copied count must be 0")
    require_cond(summary["tos_quarantine_compliance"]["tier2_hosted_numeric_outputs_included"] == 0, "Tier-2 numerics must be 0")

    t1_manifest = prov.get("tier1_source_manifest_71_files")
    t2_carveouts = prov.get("excluded_tier2_carveout_files_5")
    require_cond(isinstance(t1_manifest, list) and len(t1_manifest) == 71, "Summary must embed exact 71-file tier1_source_manifest_71_files")
    require_cond(isinstance(t2_carveouts, list) and len(t2_carveouts) == 5, "Summary must embed exact 5-file excluded_tier2_carveout_files_5")

    t1_by_rel: dict[str, str] = {}
    t1_bytes_by_rel: dict[str, int] = {}
    spdx_counts: dict[str, int] = {}
    for entry in t1_manifest:
        require_cond(
            isinstance(entry, dict) and set(entry.keys()) == _ALLOWED_TIER1_MANIFEST_ITEM_KEYS,
            f"Unauthorized or missing keys in tier1_source_manifest_71_files entry: {entry!r}",
        )
        rp = entry["relpath"]
        sh = entry["sha256"]
        bsize = entry["bytes"]
        spdx = entry["spdx_license"]
        require_cond(type(rp) is str and bool(rp.strip()), f"Invalid Tier-1 relpath: {rp!r}")
        require_cond(type(sh) is str and bool(_RE_SHA256_HEX.match(sh)), f"Invalid Tier-1 SHA-256 for {rp}")
        require_cond(
            type(bsize) is int and bsize > 0,
            f"Tier-1 source entry {rp} must declare strictly positive integer bytes, got {bsize!r}",
        )
        require_cond(
            type(spdx) is str and spdx in _ALLOWED_TIER1_SPDX_LICENSES,
            f"Tier-1 source entry {rp} has invalid SPDX license: {spdx!r}",
        )
        require_cond(type(entry["deposited_in_openislet"]) is bool, f"deposited_in_openislet must be bool for {rp}")
        require_cond(rp not in t1_by_rel and rp not in EXPECTED_TIER2_CARVEOUT_RELPATHS, f"Duplicate or Tier-2 path in Tier-1 manifest: {rp}")
        t1_by_rel[rp] = sh
        t1_bytes_by_rel[rp] = bsize
        spdx_counts[spdx] = spdx_counts.get(spdx, 0) + 1
    require_cond(
        spdx_counts == {"CC-BY-4.0": 68, "MIT": 1, "BSD-3-Clause": 2},
        f"Tier-1 71-file SPDX counts mismatch: {spdx_counts}",
    )

    # Cross-check declared source_tier1_files_verified_clean against tier1_source_manifest_71_files (positive bytes + exact digest)
    clean_tbl = prov.get("source_tier1_files_verified_clean")
    require_cond(isinstance(clean_tbl, dict) and len(clean_tbl) >= 8, "Missing source_tier1_files_verified_clean table")
    for crp, cmeta in clean_tbl.items():
        require_cond(crp in t1_by_rel, f"source_tier1_files_verified_clean path {crp} missing from 71-file manifest")
        require_cond(type(cmeta.get("bytes")) is int and cmeta["bytes"] > 0, f"Non-positive bytes in clean table for {crp}")
        require_cond(cmeta["bytes"] == t1_bytes_by_rel[crp], f"Byte size mismatch between clean table and 71-file manifest for {crp}")
        require_cond(cmeta.get("sha256") == t1_by_rel[crp], f"SHA-256 mismatch between clean table and 71-file manifest for {crp}")

    t2_by_rel: dict[str, str] = {}
    for entry in t2_carveouts:
        rp = entry.get("relpath")
        sh = entry.get("sha256")
        bsize = entry.get("bytes")
        require_cond(type(rp) is str and rp in EXPECTED_TIER2_CARVEOUT_RELPATHS and rp not in t2_by_rel, f"Invalid Tier-2 carveout path: {rp!r}")
        require_cond(type(sh) is str and bool(_RE_SHA256_HEX.match(sh)), f"Invalid Tier-2 SHA-256 for {rp}")
        require_cond(type(bsize) is int and bsize > 0, f"Tier-2 carveout entry {rp} must declare strictly positive integer bytes, got {bsize!r}")
        require_cond(entry.get("deposited_in_openislet") is False and type(entry.get("numeric_outputs_included")) is int and entry.get("numeric_outputs_included") == 0, f"Invalid Tier-2 carveout flags for {rp}")
        t2_by_rel[rp] = sh
    require_cond(set(t2_by_rel.keys()) == EXPECTED_TIER2_CARVEOUT_RELPATHS, "Incomplete 5-file Tier-2 carve-out list")

    # Deterministically reconstruct 76-line SHA256SUMS.txt and verify exact hash equality!
    rebuilt_sums = "".join(
        f"{h}  {r}\n" for r, h in sorted({**t1_by_rel, **t2_by_rel}.items(), key=lambda kv: kv[0])
    ).encode("utf-8")
    rebuilt_sums_sha = sha256_bytes(rebuilt_sums)
    require_cond(
        rebuilt_sums_sha == EXPECTED_BUNDLE_SHA256SUMS_SHA256,
        f"Reconstructed 76-line SHA256SUMS.txt mismatch: {rebuilt_sums_sha} != {EXPECTED_BUNDLE_SHA256SUMS_SHA256}",
    )

    # Verify metric-to-source Tier-1 provenance map cites ONLY verified Tier-1 files with matching SHA-256s
    m2s = prov.get("metric_to_source_tier1_provenance_map")
    require_cond(isinstance(m2s, dict) and len(m2s) >= 6, "Missing metric_to_source_tier1_provenance_map")
    for mkey, mval in m2s.items():
        require_cond(mval.get("tier2_inputs_used") == 0, f"metric_to_source entry {mkey} must have tier2_inputs_used==0")
        src_paths = mval.get("source_relpaths", [])
        src_shas = mval.get("source_sha256s", {})
        require_cond(len(src_paths) > 0 and set(src_paths) == set(src_shas.keys()), f"Incomplete source map in {mkey}")
        for rp in src_paths:
            require_cond(rp in t1_by_rel and rp not in t2_by_rel, f"Source {rp} in {mkey} is not a verified Tier-1 file")
            require_cond(src_shas[rp] == t1_by_rel[rp], f"SHA-256 mismatch for {rp} in {mkey}")

    # 5. Program 1: Islet-SHIELD 2-Component Cocktail (derive every locally computable verdict from structured numerics & enforce verification-basis tags!)
    shield = summary["programs"]["Islet_SHIELD_2Component_Cocktail"]
    require_cond(shield["live_odds_credit_pp"] == 0.0, "Islet-SHIELD live_odds_credit_pp must be 0.0")

    _ALLOWED_BASIS_TAGS = {
        "LOCALLY_RECOMPUTED_FROM_STRUCTURED_METRICS",
        "UPSTREAM_REPORTED_PROVENANCE_ONLY",
    }

    c1 = shield["component_1"]
    require_cond(c1["lead_id"] == "IsletSHIELD_QF09_pI2", "Comp1 lead_id mismatch")
    c1_recomp = recompute_gate_counts(c1["registered_gates"], "Comp1")
    require_cond(c1_recomp == {"PASS": 4, "PARTIAL": 1, "FAIL": 5, "total": 10}, f"Comp1 recomputed gates mismatch: {c1_recomp}")
    require_cond(c1["registered_gates_summary"] == c1_recomp, "Comp1 reported summary disagrees with recomputed rows")
    require_cond(
        side_contract["programs_registered"]["Islet_SHIELD"]["component_1"]["pre_registered_gates"] == c1_recomp,
        "Side-contract Comp1 pre_registered_gates disagrees with recomputed rows",
    )
    c1_by_gate = {g["gate"]: g for g in c1["registered_gates"]}
    expected_c1_basis = {
        "Boltz-2 iPTM (>=0.60)": "UPSTREAM_REPORTED_PROVENANCE_ONLY",
        "Protenix iPTM (>=0.60)": "LOCALLY_RECOMPUTED_FROM_STRUCTURED_METRICS",
        "Cross-Engine Dock RMSD (<=3.5 A)": "UPSTREAM_REPORTED_PROVENANCE_ONLY",
        "Peptide-Contact Share (>=35%)": "LOCALLY_RECOMPUTED_FROM_STRUCTURED_METRICS",
        "DQ-Beta Contact Share (<=90%)": "UPSTREAM_REPORTED_PROVENANCE_ONLY",
        "Seed Convergence (<=2.5 A CL)": "LOCALLY_RECOMPUTED_FROM_STRUCTURED_METRICS",
        "Off-Target Ceiling (<=0.25)": "LOCALLY_RECOMPUTED_FROM_STRUCTURED_METRICS",
        "Celiac 6/6 Rejected (<=0.25)": "LOCALLY_RECOMPUTED_FROM_STRUCTURED_METRICS",
        "Scrambled NULL & Folded AAA": "UPSTREAM_REPORTED_PROVENANCE_ONLY",
        "Explicit 10 ns MD (HIP11, n=1)": "LOCALLY_RECOMPUTED_FROM_STRUCTURED_METRICS",
    }
    c1_basis_counts = {"LOCALLY_RECOMPUTED_FROM_STRUCTURED_METRICS": 0, "UPSTREAM_REPORTED_PROVENANCE_ONLY": 0}
    for row in c1["registered_gates"]:
        basis = row.get("verdict_verification_basis")
        require_cond(basis in _ALLOWED_BASIS_TAGS, f"Comp1 gate {row['gate']!r} missing valid verdict_verification_basis: {basis!r}")
        require_cond(
            basis == expected_c1_basis.get(row["gate"]),
            f"Comp1 gate {row['gate']!r} verdict_verification_basis={basis!r} != expected {expected_c1_basis.get(row['gate'])!r}",
        )
        c1_basis_counts[basis] += 1
    c1_basis_counts["total"] = len(c1["registered_gates"])
    require_cond(
        c1.get("verdict_verification_summary") == c1_basis_counts,
        f"Comp1 verdict_verification_summary disagrees with row tags: {c1.get('verdict_verification_summary')} != {c1_basis_counts}",
    )

    # Derive all 6 locally recomputable Comp1 verdicts directly from structured numerics (B5!)
    c1_dq25 = c1["protenix_4seed_dq25_hip11"]
    c1_dq8t = c1["protenix_4seed_dq8trans_hip11"]
    c1_ptx_derived = (
        "PASS"
        if (c1_dq25["n_ge_060"] == c1_dq25["n_samples"] and c1_dq8t["n_ge_060"] == c1_dq8t["n_samples"])
        else ("FAIL" if (c1_dq25["n_ge_060"] == 0 and c1_dq8t["n_ge_060"] == 0) else "PARTIAL")
    )
    require_cond(
        c1_by_gate["Protenix iPTM (>=0.60)"]["result"] == c1_ptx_derived,
        f"Comp1 Protenix iPTM verdict contradiction: derived {c1_ptx_derived} vs labeled {c1_by_gate['Protenix iPTM (>=0.60)']['result']}",
    )
    c1_pep_dq25 = Decimal(str(c1_dq25["max_pep_share_pct"]))
    c1_pep_dq8t = Decimal(str(c1_dq8t["max_pep_share_pct"]))
    c1_pep_derived = (
        "PASS"
        if (c1_pep_dq25 >= Decimal("35.0") and c1_pep_dq8t >= Decimal("35.0"))
        else ("FAIL" if (c1_pep_dq25 < Decimal("35.0") and c1_pep_dq8t < Decimal("35.0")) else "PARTIAL")
    )
    require_cond(
        c1_by_gate["Peptide-Contact Share (>=35%)"]["result"] == c1_pep_derived,
        f"Comp1 Peptide-Contact Share verdict contradiction: derived {c1_pep_derived} vs labeled {c1_by_gate['Peptide-Contact Share (>=35%)']['result']}",
    )
    c1_cl_dq25 = Decimal(str(c1_dq25["best_3seed_complete_link_A"]))
    c1_cl_dq8t = Decimal(str(c1_dq8t["best_3seed_complete_link_A"]))
    c1_cl_derived = "PASS" if (c1_cl_dq25 <= Decimal("2.5") and c1_cl_dq8t <= Decimal("2.5")) else "FAIL"
    require_cond(
        c1_by_gate["Seed Convergence (<=2.5 A CL)"]["result"] == c1_cl_derived,
        f"Comp1 Seed Convergence verdict contradiction: derived {c1_cl_derived} from (DQ2.5={c1_cl_dq25} A, DQ8t={c1_cl_dq8t} A <= 2.5 A) vs labeled {c1_by_gate['Seed Convergence (<=2.5 A CL)']['result']}",
    )
    c1_flagged = c1["flagged_off_targets_gt_025"]
    require_cond(isinstance(c1_flagged, dict) and len(c1_flagged) > 0, "Comp1 flagged_off_targets_gt_025 missing")
    c1_ot_derived = "FAIL" if any(Decimal(str(v)) > Decimal("0.25") for v in c1_flagged.values()) else "PASS"
    require_cond(
        c1_by_gate["Off-Target Ceiling (<=0.25)"]["result"] == c1_ot_derived,
        f"Comp1 Off-Target Ceiling verdict contradiction: derived {c1_ot_derived} vs labeled {c1_by_gate['Off-Target Ceiling (<=0.25)']['result']}",
    )
    c1_cel_derived = "FAIL" if any(Decimal(str(v)) > Decimal("0.25") for k, v in c1_flagged.items() if str(k).startswith("cel_")) else "PASS"
    require_cond(
        c1_by_gate["Celiac 6/6 Rejected (<=0.25)"]["result"] == c1_cel_derived,
        f"Comp1 Celiac 6/6 verdict contradiction: derived {c1_cel_derived} vs labeled {c1_by_gate['Celiac 6/6 Rejected (<=0.25)']['result']}",
    )
    c1_md_on = c1["openmm_10ns_md"]["on_target_DQ25_HIP11"]
    c1_md_neg = c1["openmm_10ns_md"]["matched_neg_DQ25_CLIP1"]
    c1_md_on_derived = (Decimal(str(c1_md_on["binder_rmsd_A"])) <= Decimal("3.5") and Decimal(str(c1_md_on["pep_retention"])) >= Decimal("0.70"))
    c1_md_neg_derived = (Decimal(str(c1_md_neg["binder_rmsd_A"])) <= Decimal("3.5") and Decimal(str(c1_md_neg["pep_retention"])) >= Decimal("0.70"))
    require_cond(c1_md_on["pass_md_gate"] is c1_md_on_derived, "Comp1 on-target MD pass_md_gate contradicts structured RMSD/pep_retention")
    require_cond(c1_md_neg["pass_md_gate"] is c1_md_neg_derived, "Comp1 matched CLIP1 NEG MD pass_md_gate contradicts structured RMSD/pep_retention")
    c1_md_row_derived = "PASS (n=1)" if c1_md_on_derived else "FAIL"
    require_cond(
        c1_by_gate["Explicit 10 ns MD (HIP11, n=1)"]["result"] == c1_md_row_derived,
        f"Comp1 Explicit 10 ns MD verdict contradiction: derived {c1_md_row_derived} vs labeled {c1_by_gate['Explicit 10 ns MD (HIP11, n=1)']['result']}",
    )

    c1_fail_gates = {g["gate"] for g in c1["registered_gates"] if str(g["result"]).upper() == "FAIL"}
    expected_c1_fails = {
        "Cross-Engine Dock RMSD (<=3.5 A)",
        "Peptide-Contact Share (>=35%)",
        "Seed Convergence (<=2.5 A CL)",
        "Off-Target Ceiling (<=0.25)",
        "Celiac 6/6 Rejected (<=0.25)",
    }
    require_cond(c1_fail_gates == expected_c1_fails, f"Comp1 required FAIL rows mismatch: {c1_fail_gates}")
    require_cond(c1_dq25["n_ge_060"] == 9 and abs(float(c1_cl_dq8t) - 3.395) <= 1e-6, "Comp1 DQ2.5/DQ8-trans structured metrics mismatch")

    c2 = shield["component_2"]
    require_cond(c2["lead_id"] == "IsletSHIELD_Comp2_T006", "Comp2 lead_id mismatch")
    c2_recomp = recompute_gate_counts(c2["registered_gates"], "Comp2")
    require_cond(c2_recomp == {"PASS": 4, "PARTIAL": 3, "FAIL": 4, "total": 11}, f"Comp2 recomputed gates mismatch: {c2_recomp}")
    require_cond(c2["registered_gates_summary"] == c2_recomp, "Comp2 reported summary disagrees with recomputed rows")
    require_cond(
        side_contract["programs_registered"]["Islet_SHIELD"]["component_2"]["pre_registered_gates"] == c2_recomp,
        "Side-contract Comp2 pre_registered_gates disagrees with recomputed rows",
    )
    c2_by_gate = {g["gate"]: g for g in c2["registered_gates"]}
    for row in c2["registered_gates"]:
        require_cond(
            row.get("verdict_verification_basis") == "LOCALLY_RECOMPUTED_FROM_STRUCTURED_METRICS",
            f"Comp2 gate {row['gate']!r} must declare verdict_verification_basis=LOCALLY_RECOMPUTED_FROM_STRUCTURED_METRICS",
        )
    require_cond(
        c2.get("verdict_verification_summary")
        == {"LOCALLY_RECOMPUTED_FROM_STRUCTURED_METRICS": 11, "UPSTREAM_REPORTED_PROVENANCE_ONLY": 0, "total": 11},
        f"Comp2 verdict_verification_summary mismatch: {c2.get('verdict_verification_summary')}",
    )
    expected_c2_fails = {
        "Peptide-Contact Share (>=35%)",
        "HLA-DQ8 14-Peptide Off-Target Ceiling (<=0.25)",
        "Cross-Engine Pose Consensus (<=3.5 A)",
        "Explicit-Solvent 10 ns OpenMM 8.6.1 MD (n=1)",
    }
    c2_fail_gates = {g["gate"] for g in c2["registered_gates"] if str(g["result"]).upper() == "FAIL"}
    require_cond(c2_fail_gates == expected_c2_fails, f"Comp2 required FAIL rows mismatch: {c2_fail_gates}")

    # Precision consistency check: Comp2 cross-engine row must use exact 2.32 A and 10.87-20.43 A (never 2.28 A or 20.5 A)
    ce_obs = c2_by_gate["Cross-Engine Pose Consensus (<=3.5 A)"]["observed"]
    require_cond("2.32 A" in ce_obs and "10.87-20.43 A" in ce_obs, "Comp2 Cross-Engine row missing reconciled 2.32 A / 10.87-20.43 A")
    require_cond("2.28 A" not in ce_obs and "20.5 A" not in ce_obs, "Comp2 Cross-Engine row retains stale 2.28 A / 20.5 A rounding")

    ptx = c2["protenix_4seed_WT15"]
    # Derive Comp2 gates 1-6 directly from structured ptx measurements (B5!)
    require_cond(
        c2_by_gate["Protenix-v1 4-Seed Native WT15 (>=0.60)"]["result"]
        == ("PASS" if (ptx["n_bpep_ge_060"] == ptx["n_samples"] and Decimal(str(ptx["min_b_pep"])) >= Decimal("0.60")) else "FAIL"),
        "Comp2 Protenix-v1 4-Seed Native WT15 verdict contradicts structured metrics",
    )
    require_cond(
        c2_by_gate["4-Seed Pose Convergence (<=2.5 A CL)"]["result"]
        == ("PASS" if Decimal(str(ptx["best3_seed_cl_A"])) <= Decimal("2.5") else "FAIL"),
        "Comp2 4-Seed Pose Convergence verdict contradicts best3_seed_cl_A",
    )
    require_cond(
        c2_by_gate["6DFX T1D3 TCR Steric Overlap (>=70%)"]["result"]
        == ("PASS" if Decimal(str(ptx["t1d3_overlap_range_pct"][0])) >= Decimal("70.0") else "FAIL"),
        "Comp2 6DFX T1D3 TCR Steric Overlap verdict contradicts t1d3_overlap_range_pct",
    )
    require_cond(
        c2_by_gate["DQ-Beta Wall Share (<=90%)"]["result"]
        == ("PASS" if Decimal(str(ptx["dqb_share_range_pct"][1])) <= Decimal("90.0") else "FAIL"),
        "Comp2 DQ-Beta Wall Share verdict contradicts dqb_share_range_pct",
    )
    c2_r2_ok = Decimal(str(ptx["max_b_pep"])) >= Decimal("0.60")
    c2_r3_ok = Decimal(str(ptx["mimotope_6dfx_p8E9E_max_b_pep"])) >= Decimal("0.60")
    c2_reg_derived = "PASS" if (c2_r2_ok and c2_r3_ok) else ("FAIL" if (not c2_r2_ok and not c2_r3_ok) else "PARTIAL")
    require_cond(
        c2_by_gate["Register-3 vs Equilibrium Register-2 Frame"]["result"] == c2_reg_derived,
        f"Comp2 Register-3 vs Register-2 verdict contradiction: derived {c2_reg_derived}",
    )
    c2_pep_lo = Decimal(str(ptx["pep_share_range_pct"][0]))
    c2_pep_hi = Decimal(str(ptx["pep_share_range_pct"][1]))
    c2_pep_derived = "PASS" if c2_pep_lo >= Decimal("35.0") else ("FAIL" if c2_pep_hi < Decimal("35.0") else "PARTIAL")
    require_cond(
        c2_by_gate["Peptide-Contact Share (>=35%)"]["result"] == c2_pep_derived,
        f"Comp2 Peptide-Contact Share verdict contradiction: derived {c2_pep_derived}",
    )
    require_cond(ptx["n_samples"] == 12 and ptx["n_bpep_ge_060"] == 12, "Comp2 Protenix 4-seed must be 12/12")
    require_cond(abs(ptx["min_b_pep"] - 0.8713) <= 1e-6 and abs(ptx["max_b_pep"] - 0.8865) <= 1e-6, "Comp2 4-seed b_pep range mismatch")
    require_cond(ptx["n_clash_free_of_12"] == 9, "Comp2 clash-free count must be 9/12")
    require_cond(ptx["t1d3_overlap_range_pct"] == [82.7, 85.5], "Comp2 6DFX T1D3 overlap range mismatch")
    require_cond(ptx["dqb_share_range_pct"][1] <= 90.0, "Comp2 DQ-beta share must be <= 90%")
    require_cond(ptx["pep_share_range_pct"] == [21.2, 32.0] and ptx["pep_share_range_pct"][1] < 35.0, "Comp2 peptide share FAIL (<35%) mismatch")

    # Recompute 14-peptide off-target pass/fail counts AND enforce 14 UNIQUE canonical peptide IDs + gate 7 verdict!
    ot = c2["dq8_14_peptide_off_target_sweep"]
    ot_peps = ot.get("peptides", [])
    require_cond(len(ot_peps) == 14, f"Expected 14 peptides in DQ8 off-target table, got {len(ot_peps)}")
    ot_ids = [str(p.get("peptide_id") or "") for p in ot_peps]
    require_cond(
        len(set(ot_ids)) == 14,
        f"Duplicate peptide_id detected in DQ8 14-peptide off-target table: {len(set(ot_ids))} unique of {len(ot_ids)}",
    )
    require_cond(
        set(ot_ids) == EXPECTED_DQ8_14_OFFTARGET_PEPTIDE_IDS,
        f"DQ8 14-peptide off-target panel ID mismatch: missing={sorted(EXPECTED_DQ8_14_OFFTARGET_PEPTIDE_IDS - set(ot_ids))}, extra={sorted(set(ot_ids) - EXPECTED_DQ8_14_OFFTARGET_PEPTIDE_IDS)}",
    )
    for p in ot_peps:
        dec_val = Decimal(str(p["max_b_pep"]))
        expected_pass = dec_val <= Decimal("0.25")
        require_cond(
            p.get("pass_le_025") is expected_pass,
            f"Off-target pass_le_025 boolean disagrees with exact decimal threshold for {p['peptide_id']}: {dec_val}",
        )
    ot_pass_recomp = sum(1 for p in ot_peps if Decimal(str(p["max_b_pep"])) <= Decimal("0.25"))
    ot_fails_recomp = [p for p in ot_peps if Decimal(str(p["max_b_pep"])) > Decimal("0.25")]
    require_cond(
        c2_by_gate["HLA-DQ8 14-Peptide Off-Target Ceiling (<=0.25)"]["result"] == ("PASS" if ot_pass_recomp == 14 else "FAIL"),
        "Comp2 14-peptide off-target gate verdict contradicts recomputed pass count",
    )
    require_cond(ot_pass_recomp == 13 and ot["pass_count"] == 13 and ot["total"] == 14, "Comp2 DQ8 off-target sweep recomputation must be 13/14")
    require_cond(
        len(ot_fails_recomp) == 1
        and ot_fails_recomp[0]["peptide_id"] == "DQ8_glia_gamma1a"
        and abs(float(ot_fails_recomp[0]["max_b_pep"]) - 0.5289) <= 1e-6,
        f"Comp2 DQ8 off-target recomputed failure must be DQ8_glia_gamma1a=0.5289, got {ot_fails_recomp}",
    )
    failing_ot = ot["failing_peptides"]
    require_cond(
        len(failing_ot) == 1 and failing_ot[0]["peptide_id"] == "DQ8_glia_gamma1a" and abs(failing_ot[0]["max_b_pep"] - 0.5289) <= 1e-6,
        f"Comp2 DQ8 off-target failure must be DQ8_glia_gamma1a=0.5289, got {failing_ot}",
    )

    # Derive Comp2 gate 8 (Negative Binder Controls NULL & AAA8 <= 0.25)
    neg_ctrl = c2["negative_and_cross_allele_controls"]
    aaa8_vals = [Decimal(str(x)) for x in neg_ctrl["AAA8_sample_b_peps"]]
    aaa8_le_025_recomp = sum(1 for x in aaa8_vals if x <= Decimal("0.25"))
    require_cond(
        neg_ctrl["AAA8_n_le_025_of_3"] == aaa8_le_025_recomp,
        f"Comp2 AAA8_n_le_025_of_3={neg_ctrl['AAA8_n_le_025_of_3']} contradicts derived {aaa8_le_025_recomp}",
    )
    null_ok = Decimal(str(neg_ctrl["NULL_scramble_max_b_pep"])) <= Decimal("0.25")
    aaa8_all_ok = (aaa8_le_025_recomp == len(aaa8_vals))
    neg_derived = "PASS" if (null_ok and aaa8_all_ok) else ("FAIL" if (not null_ok and aaa8_le_025_recomp == 0) else "PARTIAL")
    require_cond(
        c2_by_gate["Negative Binder Controls (NULL & AAA8 <=0.25)"]["result"] == neg_derived,
        f"Comp2 Negative Binder Controls verdict contradiction: derived {neg_derived}",
    )

    # Derive BOTH min AND max OpenFold3 ranges & Comp2 gate 9 (Cross-Engine Pose Consensus <= 3.5 A)
    ce = c2["cross_engine_consensus_fail_audit"]
    boltz_rmsd = Decimal(str(ce["boltz2_mit_v2_2_1_parent"]["WT15_ptx_whole_binder_rmsd_A"]))
    of3_blk = ce["openfold3_0_5_1_apache2"]
    for sub_k in ("T006_DQ8_WT15", "T006_DQ8_CLIP1_inverted_higher", "T006_DQ8_glia_gamma1a_inverted_s3_match", "SHIELD2_QQ_DQ8_WT15"):
        sub = of3_blk[sub_k]
        iptms = [float(x) for x in sub["iptm_values"]]
        cds = [float(x) for x in sub["chain_pair_CD_values"]]
        require_cond(
            sub["iptm_range"] == [min(iptms), max(iptms)],
            f"OpenFold3 {sub_k} iptm_range {sub['iptm_range']} disagrees with derived [{min(iptms)}, {max(iptms)}]",
        )
        require_cond(
            sub["chain_pair_CD_range"] == [min(cds), max(cds)],
            f"OpenFold3 {sub_k} chain_pair_CD_range {sub['chain_pair_CD_range']} disagrees with derived [{min(cds)}, {max(cds)}]",
        )
    of3_wt = of3_blk["T006_DQ8_WT15"]
    of3_clip = of3_blk["T006_DQ8_CLIP1_inverted_higher"]
    of3_glia = of3_blk["T006_DQ8_glia_gamma1a_inverted_s3_match"]
    wt_shifts = [float(x) for x in of3_wt["pep_com_shift_vs_WT15_groove_A"]]
    derived_min_shift = min(wt_shifts)
    derived_max_shift = max(wt_shifts)
    ce_derived = "PASS" if (boltz_rmsd <= Decimal("3.5") and Decimal(str(derived_max_shift)) <= Decimal("3.5")) else "FAIL"
    require_cond(
        c2_by_gate["Cross-Engine Pose Consensus (<=3.5 A)"]["result"] == ce_derived,
        f"Comp2 Cross-Engine Pose Consensus verdict contradiction: derived {ce_derived}",
    )
    require_cond(abs(float(boltz_rmsd) - 23.4) <= 1e-6, "Boltz-2 MIT 23.4 A flip mismatch")
    require_cond(
        abs(derived_min_shift - 10.87) <= 1e-6 and abs(derived_max_shift - 20.43) <= 1e-6,
        f"Derived OpenFold3 WT15 COM shift range [{derived_min_shift}, {derived_max_shift}] != [10.87, 20.43]",
    )
    require_cond(
        of3_wt.get("pep_com_shift_range_A") == [derived_min_shift, derived_max_shift],
        f"OpenFold3 T006_DQ8_WT15 pep_com_shift_range_A {of3_wt.get('pep_com_shift_range_A')} disagrees with derived [{derived_min_shift}, {derived_max_shift}]",
    )
    derived_shift_str_ascii = f"{derived_min_shift:.2f}-{derived_max_shift:.2f} A"
    derived_shift_str_dash = f"{derived_min_shift:.2f}\u2013{derived_max_shift:.2f} A"
    require_cond(
        derived_shift_str_ascii in ce_obs,
        f"Comp2 Cross-Engine gate observed text missing derived OpenFold3 shift range {derived_shift_str_ascii!r}",
    )
    require_cond(
        derived_shift_str_ascii in protocol_text or derived_shift_str_dash in protocol_text,
        f"Protocol doc missing derived OpenFold3 shift range {derived_shift_str_ascii!r}",
    )
    require_cond(max(of3_wt["chain_pair_CD_values"]) < min(of3_clip["chain_pair_CD_values"]), "OpenFold3 CLIP1 chain-pair (C,D) inversion not preserved")
    require_cond(abs(min(of3_glia["binder_rmsd_vs_T006_ptx_s303_A"]) - 2.32) <= 1e-6, "OpenFold3 glia-g1a sample 3 pose match must be 2.32 A")

    # Derive Comp2 gate 11 (Explicit-Solvent 10 ns OpenMM 8.6.1 MD) from structured RMSD & pep_retention (B5!)
    md = c2["openmm_10ns_md_n1"]
    md_wt_derived = (
        Decimal(str(md["on_target_WT15"]["binder_rmsd_A"])) <= Decimal("3.5")
        and Decimal(str(md["on_target_WT15"]["pep_retention"])) >= Decimal("0.70")
    )
    md_clip_derived = (
        Decimal(str(md["matched_neg_CLIP1"]["binder_rmsd_A"])) <= Decimal("3.5")
        and Decimal(str(md["matched_neg_CLIP1"]["pep_retention"])) >= Decimal("0.70")
    )
    require_cond(
        md["on_target_WT15"]["pass_md_gate"] is md_wt_derived,
        "Comp2 WT15 MD pass_md_gate contradicts structured RMSD/pep_retention",
    )
    require_cond(
        md["matched_neg_CLIP1"]["pass_md_gate"] is md_clip_derived,
        "Comp2 CLIP1 NEG MD pass_md_gate contradicts structured RMSD/pep_retention",
    )
    md_gate_derived = "PASS" if (md_wt_derived and not md_clip_derived) else "FAIL"
    require_cond(
        c2_by_gate["Explicit-Solvent 10 ns OpenMM 8.6.1 MD (n=1)"]["result"] == md_gate_derived,
        f"Comp2 10 ns MD gate verdict contradiction: derived {md_gate_derived}",
    )
    require_cond(md["on_target_WT15"]["pass_md_gate"] is False, "Comp2 WT15 10 ns MD must be FAIL (pass_md_gate=false)")
    require_cond(abs(md["on_target_WT15"]["binder_rmsd_A"] - 2.748) <= 1e-6 and abs(md["on_target_WT15"]["pep_retention"] - 0.672) <= 1e-6, "Comp2 WT15 MD numbers mismatch")
    require_cond(md["matched_neg_CLIP1"]["pass_md_gate"] is True, "Comp2 CLIP1 NEG MD pass_md_gate=true disclosure missing")
    require_cond(abs(md["matched_neg_CLIP1"]["binder_rmsd_A"] - 2.527) <= 1e-6 and abs(md["matched_neg_CLIP1"]["pep_retention"] - 0.726) <= 1e-6, "Comp2 CLIP1 NEG MD numbers mismatch")

    # Derive Comp2 gate 10 (Cocktail Compatibility) from explicit OpenFold3 <= 0.25 & Boltz-2 MIT <= 0.20 per-seed arrays (B5 + M2!)
    ck = c2["cocktail_compatibility_and_homodimer_flag"]
    het = ck["heterodimer_T006_plus_QF09_pI2"]
    of3_het_thr = Decimal(str(het.get("openfold3_heterodimer_threshold_iptm")))
    b2_het_thr = Decimal(str(het.get("boltz2_mit_heterodimer_threshold_iptm")))
    require_cond(of3_het_thr == Decimal("0.25"), f"OpenFold3 heterodimer threshold must be 0.25, got {of3_het_thr}")
    require_cond(b2_het_thr == Decimal("0.20"), f"Boltz-2 MIT heterodimer threshold must be 0.20, got {b2_het_thr}")
    of3_het_vals = [Decimal(str(x)) for x in het["openfold3_0_5_1_iptms"]]
    b2_het_vals = [Decimal(str(x)) for x in het["boltz2_mit_iptms"]]
    require_cond(len(of3_het_vals) == 3 and len(b2_het_vals) == 3, "Heterodimer per-seed arrays must contain 3 values each")
    derived_of3_pass_3_of_3 = all(x <= of3_het_thr for x in of3_het_vals)
    derived_b2_n_le_020 = sum(1 for x in b2_het_vals if x <= b2_het_thr)
    require_cond(
        het["openfold3_pass_3_of_3"] is derived_of3_pass_3_of_3,
        f"OpenFold3 heterodimer openfold3_pass_3_of_3={het['openfold3_pass_3_of_3']} contradicts derived {derived_of3_pass_3_of_3} from {het['openfold3_0_5_1_iptms']} <= {of3_het_thr}",
    )
    require_cond(
        het["boltz2_mit_n_le_020_of_3"] == derived_b2_n_le_020,
        f"Boltz-2 MIT heterodimer boltz2_mit_n_le_020_of_3={het['boltz2_mit_n_le_020_of_3']} contradicts derived {derived_b2_n_le_020} from {het['boltz2_mit_iptms']} <= {b2_het_thr}",
    )
    ck_sub_passes = [
        Decimal(str(ck["homodimer_T006_protenix_flag"]["max_iptm"])) <= Decimal("0.25"),
        Decimal(str(het["protenix_max_iptm"])) <= Decimal("0.25"),
        derived_of3_pass_3_of_3,
        derived_b2_n_le_020 == len(b2_het_vals),
    ]
    ck_gate_derived = "PASS" if all(ck_sub_passes) else ("FAIL" if not any(ck_sub_passes) else "PARTIAL")
    require_cond(
        c2_by_gate["Cocktail Compatibility (T006 + QF09_pI2 & Monomer)"]["result"] == ck_gate_derived,
        f"Comp2 Cocktail Compatibility verdict contradiction: derived {ck_gate_derived}",
    )
    require_cond(abs(ck["homodimer_T006_protenix_flag"]["max_iptm"] - 0.6691) <= 1e-6, "Comp2 Protenix homodimer 0.6691 flag mismatch")
    require_cond(het["openfold3_pass_3_of_3"] is True, "OpenFold3 heterodimer 3/3 PASS mismatch")
    require_cond(het["boltz2_mit_n_le_020_of_3"] == 2, "Boltz-2 MIT heterodimer 2/3 <= 0.20 mismatch")

    comps = c2["shipped_comparators"]
    require_cond(
        set(comps.keys()) == {"SHIELD2_QQ", "R3_shv2_stk1", "SH2_MP01", "SH2_MP06", "SH2_MP08"},
        f"Comp2 comparator set mismatch: {sorted(comps.keys())}",
    )

    # 6. Program 2: Islet-SORT (including open ITGA2 inversion & non-convergence disclosure!)
    sort_p = summary["programs"]["Islet_SORT"]
    sort_sc = side_contract["programs_registered"]["Islet_SORT"]
    require_cond(sort_p["live_odds_credit_pp"] == 0.0 and sort_sc["live_odds_credit_pp"] == 0.0, "Islet-SORT live_odds_credit_pp must be 0.0")
    require_cond(sort_p["lead_id"] == "IsletSORT_CD49a_t003_s10", "Islet-SORT lead mismatch")
    require_cond(sort_p["archived_sibling_id"] == "IsletSORT_CD49a_t003_s3", "Islet-SORT sibling mismatch")
    require_cond(sort_p["developability"]["len"] == 72 and sort_p["developability"]["deamidation_NG_NS"] == [], "Islet-SORT developability mismatch")
    require_cond(
        sort_p["itga2_paralog_inversion_status"] == "EXPLICITLY_OPEN_PENDING_5_TO_10_SIBLING_WETLAB_SCREEN"
        and sort_sc.get("itga2_paralog_inversion_open") is True,
        "Islet-SORT ITGA2 paralog inversion must be explicitly OPEN in both summary and side contract",
    )
    require_cond(
        sort_p["tier1_protenix_audit"]["wt_itga1_3xMan3_Mg_n6"]["convergence_le_2p5A_demonstrated"] is False,
        "Islet-SORT non-convergence disclosure missing",
    )

    # 7. Program 3: Islet-GUARD (including explicit MD 5.487 A FAIL, bimodal docking, and dynamic side-contract route policy!)
    guard_p = summary["programs"]["Islet_GUARD"]
    guard_sc = side_contract["programs_registered"]["Islet_GUARD"]
    require_cond(guard_p["live_odds_credit_pp"] == 0.0 and guard_sc["live_odds_credit_pp"] == 0.0, "Islet-GUARD live_odds_credit_pp must be 0.0")
    require_cond(guard_p["lead_id"] == ISLET_GUARD_CONSTRUCT_ID and guard_sc["lead_id"] == ISLET_GUARD_CONSTRUCT_ID, "Islet-GUARD lead mismatch")
    require_cond(guard_p["structural_expression_constraints"]["cys_count"] == 18, "Islet-GUARD Cys count must be 18")
    require_cond(guard_p["structural_expression_constraints"]["disulfide_bonds"] == 9, "Islet-GUARD disulfide count must be 9")
    require_cond(guard_p["structural_expression_constraints"]["n_glyc_sites_1based"] == [20, 47], "Islet-GUARD N-glyc positions must be [20, 47]")
    require_cond(
        "uniprot p07204" in str(guard_p["structural_expression_constraints"].get("reference_expectation_scope", "")).lower()
        and "unmeasured" in str(guard_p["structural_expression_constraints"].get("reference_expectation_scope", "")).lower(),
        "Islet-GUARD summary must label disulfides/glycans as UniProt P07204 reference expectations (unmeasured)",
    )
    require_cond(
        "gate 3" in str(guard_p.get("blueprint_gate_alignment", "")).lower()
        and "gate 3" in str(guard_sc.get("blueprint_gate_alignment", "")).lower(),
        "Islet-GUARD blueprint_gate_alignment must identify Blueprint Gate 3 (thrombo-inflammation / peri-graft bleeding in Route 1 context)",
    )
    require_cond(guard_p["route_restriction"]["allowed_arms"] == ["A", "X"], "Summary Islet-GUARD allowed_arms must be ['A', 'X']")
    require_cond(guard_p["route_restriction"]["disallowed_arms"] == ["B", "Y", "D"], "Summary Islet-GUARD disallowed_arms must be ['B', 'Y', 'D']")
    require_cond(guard_p["route_restriction"]["allowed_route_ids"] == ["ROUTE_1_CAO2_HYDROGEL"], "Summary Islet-GUARD allowed_route_ids must be ['ROUTE_1_CAO2_HYDROGEL']")
    require_cond(guard_sc["allowed_route_arms"] == ["A", "X"], "Side-contract Islet-GUARD allowed_route_arms must be ['A', 'X']")
    require_cond(guard_sc["disallowed_route_arms"] == ["B", "Y", "D"], "Side-contract Islet-GUARD disallowed_route_arms must be ['B', 'Y', 'D']")
    require_cond(guard_sc["allowed_route_ids"] == ["ROUTE_1_CAO2_HYDROGEL"], "Side-contract Islet-GUARD allowed_route_ids must be ['ROUTE_1_CAO2_HYDROGEL']")

    # Explicit GUARD MD 5.487 A FAIL (derived from <= 3.0 A threshold) & upstream-reported bimodal docking checks (B5!)
    guard_md = guard_p["openmm_10ns_md_n1"]
    require_cond(
        guard_md.get("verdict_verification_basis") == "LOCALLY_RECOMPUTED_FROM_STRUCTURED_METRICS",
        "Islet-GUARD MD must declare verdict_verification_basis=LOCALLY_RECOMPUTED_FROM_STRUCTURED_METRICS",
    )
    guard_md_thr = Decimal(str(guard_md.get("md_binder_rmsd_fail_gt_A")))
    require_cond(guard_md_thr == Decimal("3.0"), f"Islet-GUARD MD threshold must be 3.0 A, got {guard_md_thr}")
    guard_md_derived = Decimal(str(guard_md["binder_rmsd_A"])) <= guard_md_thr
    require_cond(
        guard_md["pass_md_gate"] is guard_md_derived,
        f"Islet-GUARD 10 ns MD pass_md_gate={guard_md['pass_md_gate']} contradicts derived {guard_md_derived} from RMSD={guard_md['binder_rmsd_A']} <= {guard_md_thr}",
    )
    require_cond(guard_md["pass_md_gate"] is False, "Islet-GUARD 10 ns MD must be FAIL (pass_md_gate=false)")
    require_cond(abs(float(guard_md["binder_rmsd_A"]) - 5.487) <= 1e-6, f"Islet-GUARD 10 ns MD binder_rmsd_A must be 5.487 A, got {guard_md['binder_rmsd_A']}")
    require_cond(abs(float(guard_md["trace_max_binder_rmsd_A"]) - 6.649) <= 1e-6, "Islet-GUARD 10 ns MD trace_max_binder_rmsd_A must be 6.649 A")
    require_cond(guard_md["stripped_heterogens"] == ["NAG"], "Islet-GUARD 10 ns MD stripped_heterogens must be ['NAG']")
    guard_bi = guard_p["tier1_matched_msa_4seed_bimodal_audit"]
    require_cond(
        guard_bi.get("verdict_verification_basis") == "UPSTREAM_REPORTED_PROVENANCE_ONLY",
        "Islet-GUARD bimodal docking audit must declare verdict_verification_basis=UPSTREAM_REPORTED_PROVENANCE_ONLY",
    )
    require_cond(
        guard_bi["WT_native_seeds_of_4"] == 2 and guard_bi["M406L_native_seeds_of_4"] == 1 and guard_bi["M406I_native_seeds_of_4"] == 0,
        f"Islet-GUARD bimodal docking seed counts mismatch: {guard_bi}",
    )

    return {
        "live_odds_credit_pp": 0.0,
        "active_pmids_verified_count": len(EXPECTED_ACTIVE_PMIDS_18),
        "core_hla_dq_pmids_verified": sorted(EXPECTED_CORE_HLA_DQ_PMIDS),
        "typed_citation_roles_verified_count": len(EXPECTED_TYPED_CITATION_ROLES),
        "typed_citation_roles_verified": dict(EXPECTED_TYPED_CITATION_ROLES),
        "recursive_citation_contradiction_surfaces_scanned": 4,
        "recursive_citation_contradiction_strings_scanned": len(all_surface_strings),
        "typed_pdb_references_verified_count": len(EXPECTED_PDB_IDS_6),
        "typed_pdb_references_verified": sorted(EXPECTED_PDB_IDS_6),
        "typed_pdb_to_primary_pmid_bound": True,
        "typed_uniprot_references_verified_count": len(EXPECTED_UNIPROT_ACCESSIONS_3),
        "typed_uniprot_references_verified": sorted(EXPECTED_UNIPROT_ACCESSIONS_3),
        "typed_uniprot_gene_and_slice_bound": True,
        "typed_insb_peptide_roles_verified": sorted(EXPECTED_INSB_REFERENCE_PEPTIDES.keys()),
        "reconstructed_76_file_sha256sums_verified": True,
        "tier1_manifest_positive_bytes_and_spdx_verified": True,
        "tier1_manifest_spdx_counts": spdx_counts,
        "excluded_tier2_carveout_count": len(t2_by_rel),
        "comp1_gates_recomputed": c1_recomp,
        "comp1_verdict_verification_basis_counts": c1_basis_counts,
        "comp2_gates_recomputed": c2_recomp,
        "comp2_verdict_verification_basis_counts": c2["verdict_verification_summary"],
        "comp2_protenix_4seed_pass": "12/12 (9/12 clash-free)",
        "comp2_dq8_offtarget_sweep": "13/14 unique peptides PASS (DQ8_glia_gamma1a FAIL modeled Protenix-v1 b_pep score 0.5289)",
        "comp2_openfold3_wt15_shift_range_derived_A": [derived_min_shift, derived_max_shift],
        "comp2_cross_engine_consensus": "FAIL (Boltz-2 MIT 23.4 A flip; OpenFold3 WT15 ejection 10.87-20.43 A; CLIP1 higher chain-pair (C,D) 0.4112-0.4227 vs WT15 0.0395-0.1486; glia-g1a sample 3 pose match 2.32 A)",
        "comp2_heterodimer_thresholds_verified": {"openfold3_iptm_le": 0.25, "boltz2_mit_iptm_le": 0.20},
        "comp2_openmm_10ns_md": "FAIL (WT15 2.748 A / 67.2% vs 70%; CLIP1 NEG 2.527 A / 72.6% pass_md_gate=true)",
        "comp2_protenix_homodimer_flag_iptm": 0.6691,
        "comp2_comparators_verified": sorted(comps.keys()),
        "islet_sort_itga2_inversion_open": True,
        "islet_guard_blueprint_gate_alignment": "Blueprint Gate 3 (thrombo-inflammation / peri-graft bleeding in Route 1 CaO2 context)",
        "islet_guard_10ns_md_fail_verified": "FAIL (5.487 A binder RMSD > 3.0 A threshold, max 6.649 A, NAG stripped, pass_md_gate=false)",
        "islet_guard_route1_arms_only": ["A", "X"],
        "islet_guard_allowed_route_ids": ["ROUTE_1_CAO2_HYDROGEL"],
        "passed": True,
    }


def verify_zero_lims_touch_invariance(repo_root: Path) -> dict[str, Any]:
    lims_checked: dict[str, dict[str, Any]] = {}
    for rel, expected_sha in FROZEN_LIMS_SHA256.items():
        p = repo_root / rel
        if not p.is_file():
            raise FileNotFoundError(f"Frozen LIMS file missing in repo: {rel}")
        actual_sha = sha256_file(p)
        require_cond(actual_sha == expected_sha, f"Frozen LIMS file mutated ({rel}): {actual_sha} != {expected_sha}")
        lims_checked[rel] = {"sha256": actual_sha, "zero_byte_untouched": True}

    pb_path = repo_root / "docs" / "STAGE-0-EXECUTION-PLAYBOOK.md"
    if not pb_path.is_file():
        raise FileNotFoundError("Missing docs/STAGE-0-EXECUTION-PLAYBOOK.md")
    pb_norm = pb_path.read_text(encoding="utf-8").replace("\r\n", "\n")
    start_tok = "#### 4.1.20 Preregistered Autologous `D1b-Auto-C v2`"
    end_tok = "<!-- END_IIP0035_PLAYBOOK_SECTION_4_1_20 -->"
    s_idx = pb_norm.find(start_tok)
    e_idx = pb_norm.find(end_tok, s_idx) if s_idx != -1 else -1
    require_cond(s_idx != -1 and e_idx != -1, "Could not locate canonical Playbook §4.1.20 boundaries")
    sec4120_sha = sha256_bytes(pb_norm[s_idx:e_idx].strip().encode("utf-8"))
    require_cond(
        sec4120_sha == EXPECTED_PLAYBOOK_SEC4120_SHA256,
        f"Playbook §4.1.20 mutated: {sec4120_sha} != {EXPECTED_PLAYBOOK_SEC4120_SHA256}",
    )
    return {
        "frozen_lims_files": lims_checked,
        "playbook_sec4120_sha256": sec4120_sha,
        "playbook_sec4120_untouched": True,
        "all_zero_lims_touch_invariants_passed": True,
    }


_EXPECTED_SHIELD_SPR_PRECEDENCE_LIST = list(_SHIELD_SPR_PRECEDENCE_ORDER)
_EXPECTED_MANDATORY_ANALYTE_STRINGS = [
    "HLA-DQ2.5 + HIP11",
    "HLA-DQ8-trans + HIP11",
    "HLA-DQ2.2 + HIP11",
    "HLA-DQ8 + native WT InsB:9-23 (15-aa SHLVEALYLVCGERG)",
]
_EXPECTED_MANDATORY_ANALYTE_SPEC_IDS = [
    "HLA-DQ2.5 + HIP11",
    "HLA-DQ8-trans + HIP11",
    "HLA-DQ2.2 + HIP11",
    "HLA-DQ8 + native WT InsB:9-23",
]
_RE_OMISSION_OR_OPTIONAL = re.compile(
    r"\b(?:omit|omitted|optional|waive|waived|skip|skipped|exclude|excluded|not\s+required)\b",
    re.IGNORECASE,
)
_RE_MD_WEAKENED_COVERAGE = re.compile(
    r"(?:"
    r"\bonly\s+(?:one|1|two|2|three|3)\s+(?:optional\s+)?(?:complex|analyte)\b"
    r"|\b(?:omit|skip|waive|optional)\s+(?:hla-dq2\.2|hla-dq2\.5|hla-dq8-trans|any\s+of\s+the\s+(?:four|4)|this\s+assay)\b"
    r"|hla-dq(?:2\.2|2\.5|8-trans)\s*\+\s*hip11[^.\n]{0,60}\b(?:optional|omit|skip|waive|not\s+required)\b"
    r")",
    re.IGNORECASE,
)
_RE_MD_CONTRADICTORY_CYTO_FAIL = re.compile(
    r"(?:off-target\s+apc\s+cytotoxicity|simultaneous\s+(?:worst[- ]donor\s+)?(?:bonferroni\s+)?lower(?:\s+bound)?|cohort[^.\n]{0,25}l97\.?5|bonferroni[^.\n]{0,25}lower)[^.\n]{0,65}`?(?:l95|l97\.?5|lower(?:_pct|\s+bound)?)\s*>\s*(?!5\.0%)\d+(?:\.\d+)?%`?",
    re.IGNORECASE,
)
_RE_MD_CONTRADICTORY_BATCH_RULE = re.compile(
    r"(?i)(?:"
    r"\b(?:1|one|single)\s+(?:distinct\s+)?(?:declared\s+)?(?:passing\s+)?(?:linked|referenced)\s+(?:expression\s+)?batch(?:es)?\b"
    r"|\b(?:>=|<=|==|=)\s*[12]\s+(?:distinct\s+)?(?:declared\s+)?(?:passing\s+)?(?:linked|referenced|independent)?\s*(?:comp[12]\s+|component\s*[12]\s+)?(?:expression\s+)?batch(?:es)?\b"
    r"|\b(?:<=|at\s+most|at\s+least|minimum\s+(?:of\s+)?)\s*(?:1|one|single|2|two|a\s+pair\s+of)\s+(?:distinct\s+)?(?:declared\s+)?(?:passing\s+)?(?:linked\s+|referenced\s+|independent\s+)?(?:comp[12]\s+|component\s*[12]\s+)?(?:expression\s+)?batch(?:es)?\b"
    r"|\bn\s*(?:>=|<=|==|=)\s*[12]\s+independent[^\n]{0,30}expression\s+batch"
    r"|\b(?:only\s+|just\s+|require(?:s|d)?\s+|permit(?:s|ted)?\s+|allow(?:s|ed|ing)?\s+)(?:1|one|single|2|two|a\s+pair\s+of)\s+(?:distinct\s+)?(?:declared\s+)?(?:passing\s+)?(?:linked\s+|referenced\s+|independent\s+)?(?:comp[12]\s+|component\s*[12]\s+)?(?:expression\s+)?batch(?:es)?\b"
    r"|\b(?:a\s+pair\s+of|(?:1|one)\s+or\s+(?:2|two)|(?:1|one|single|2|two))\s+(?:distinct\s+)?(?:declared\s+)?(?:linked\s+)?(?:passing\s+)?(?:linked\s+)?(?:comp[12]\s+|component\s*[12]\s+)?(?:expression\s+)?batch(?:es)?(?:\s+(?:is|are|will\s+be|shall\s+be|may\s+be))?\s+(?:sufficient|enough|adequate|acceptable|allowed|permitted|required|suffices?|satisf(?:y|ies))\b"
    r"|\b(?:a\s+pair\s+of|(?:1|one)\s+or\s+(?:2|two))\s+(?:distinct\s+)?(?:declared\s+)?(?:linked\s+)?(?:passing\s+)?(?:linked\s+)?(?:comp[12]\s+|component\s*[12]\s+)?(?:expression\s+)?batch(?:es)?\b"
    r"|\bfewer\s+than\s+(?:3|three)\s+(?:distinct\s+)?(?:declared\s+)?(?:linked\s+)?(?:passing\s+)?(?:expression\s+)?batch(?:es)?[^.\n]{0,30}\b(?:sufficient|enough|adequate|acceptable|allowed|permitted)\b"
    r"|\b(?:expression\s+)?batch(?:es)?(?:\s+count)?\s+(?:(?:may|can|could|should|must|will|shall)\s+be|need\s+only\s+be|needs\s+(?:only\s+)?to\s+be|is|are|be)\s+(?:as\s+low\s+as\s+|as\s+few\s+as\s+|down\s+to\s+|reduced\s+to\s+|capped\s+at\s+|limited\s+to\s+|at\s+least\s+|at\s+most\s+|a\s+minimum\s+of\s+|minimum\s+of\s+|only\s+|just\s+)?(?:1|one|single|2|two|a\s+pair|fewer\s+than\s+(?:3|three))(?!\s*(?::|\d|\.\d|%|nm|x|fold|[- ]component|[- ]way))\b"
    r"|\b(?:number|count)\s+of\s+(?:distinct\s+)?(?:declared\s+)?(?:linked\s+)?(?:passing\s+)?(?:independent\s+)?(?:expression\s+)?batch(?:es)?[^.\n]{0,45}\b(?:as\s+low\s+as|as\s+few\s+as|down\s+to|at\s+least|at\s+most|a\s+minimum\s+of|minimum\s+of|only|just|need\s+only\s+be|needs\s+(?:only\s+)?to\s+be|equals?|is|are|may\s+be|can\s+be)\s+(?:1|one|single|2|two|a\s+pair|fewer\s+than\s+(?:3|three))(?!\s*(?::|\d|\.\d|%|nm|x|fold|[- ]component|[- ]way))\b"
    r")"
)


def _extract_gate30_shield_spr_md_section(md_text: str) -> str:
    m = re.search(r"^###\s+(?:2\.2\s+)?`?Gate 30-SHIELD-SPR`?.*$", md_text, flags=re.IGNORECASE | re.MULTILINE)
    if not m:
        return ""
    rest = md_text[m.start():]
    m_end = re.search(r"^(?:###\s+(?!2\.2\b)|##\s+|---\s*$)", rest[len(m.group(0)):], flags=re.MULTILINE)
    if m_end:
        return rest[: len(m.group(0)) + m_end.start()]
    return rest


def evaluate_iip0042_alignment(side_contract_text: str, protocol_md_text: str) -> dict[str, Any]:
    """Executable INDEPENDENT alignment auditor for IIP-0042 side-contract (typed JSON fields)
    AND GATE-30 companion protocol (authored Markdown section ### 2.2 checked separately).
    Enforces:
      - Exact complete set of ALL 4 mandatory on-target analytes + typed mandatory_on_target_spr_analyte_specs
        on JSON (rejecting omission/optional wording in any analyte entry!) AND full mandatory-all-four
        clause on Markdown (rejecting 'only one optional complex' or omission wording!).
      - Exact thresholds, directions, logical operators (AND on PASS; OR on FAIL), N_eff >= 60,
        both nonzero cytotoxicity hold states, 6-level fail-first precedence, and pre-adjudication
        ValueError on non-finite inputs on BOTH surfaces (rejecting e.g. L95 > 50.0% in Markdown!).
      - Typed 1JK8/WT15/6DFX peptide separation and anti-conflation check on BOTH surfaces.
    """
    checks: dict[str, bool] = {}

    # --- PART A: Typed JSON validation on IIP-0042 side contract ONLY ---
    try:
        sc_obj = load_strict_json_text(side_contract_text, "iip0042_side_contract")
    except Exception:
        sc_obj = None

    gate_spr = (
        sc_obj.get("executable_stage0_and_conditional_gates", {}).get("Gate_30_SHIELD_SPR")
        if isinstance(sc_obj, dict)
        else None
    )
    sc_low = side_contract_text.lower()

    if isinstance(gate_spr, dict):
        reg = gate_spr.get("registered_cocktail_identity", {})
        ctrl = gate_spr.get("mandatory_component2_bench_controls_iip0044", {})
        c1_analytes = [str(x) for x in ctrl.get("control_1_off_target_spr_analytes", [])]
        c2_sec = str(ctrl.get("control_2_secmals_dls_monomer_and_coformulation", ""))
        c3_blk = ctrl.get("control_3_parallel_comparator_and_register_screen", {})
        c3_comps = [str(x) for x in c3_blk.get("parallel_comparators", [])]
        c3_regs_str = " ".join(str(x) for x in c3_blk.get("register_controls", []))
        on_target_raw = gate_spr.get("mandatory_on_target_spr_analytes", [])
        on_target_list = [str(x) for x in on_target_raw] if isinstance(on_target_raw, list) else []
        analyte_specs = gate_spr.get("mandatory_on_target_spr_analyte_specs", [])
        qc_str = str(gate_spr.get("mandatory_reagent_qc", ""))
        qc_low = qc_str.lower()
        reg_spec = gate_spr.get("register_and_peptide_identity_spec", {})
        reg_spec_str = json.dumps(reg_spec, ensure_ascii=False)
        eps = {ep.get("endpoint_id"): ep for ep in gate_spr.get("endpoints_and_3state_rules", []) if isinstance(ep, dict)}
        ep_aff = eps.get("SHIELD_AFFINITY_AND_SELECTIVITY", {})
        ep_blk = eps.get("SHIELD_HUMAN_TCELL_BLOCKADE", {})
        prec_tbl = gate_spr.get("decision_precedence_table", {})
        cyto_unit = gate_spr.get("cytotoxicity_confidence_unit_specification", {})
        typed_ev = gate_spr.get("typed_evidence_contract", {})

        checks["sc_typed_gate_present"] = True
        checks["sc_stale_v13_hold_note_retired"] = ("hold for v1.3 affinity maturation" not in sc_low)
        checks["sc_post_spr_v14_maturation_present"] = ("v1.4" in str(ep_aff.get("hold_rule", "")).lower())
        checks["sc_comp1_qf09_pi2_lead"] = (reg.get("component_1_lead_id") == "IsletSHIELD_QF09_pI2")
        checks["sc_comp2_t006_lead"] = (reg.get("component_2_lead_id") == "IsletSHIELD_Comp2_T006")
        checks["sc_two_component_cocktail"] = ("2-component" in str(reg.get("architecture", "")).lower())

        # Exact complete canonical 4-analyte set + typed analyte_specs (rejects omission/optional wording!)
        exact_4_strings_ok = (
            len(on_target_list) == 4
            and set(on_target_list) == set(_EXPECTED_MANDATORY_ANALYTE_STRINGS)
            and all(_RE_OMISSION_OR_OPTIONAL.search(s) is None for s in on_target_list)
        )
        typed_specs_ok = False
        if isinstance(analyte_specs, list) and len(analyte_specs) == 4:
            spec_by_id = {
                str(s.get("analyte_id") or ""): s
                for s in analyte_specs
                if isinstance(s, dict)
            }
            if set(spec_by_id.keys()) == set(_EXPECTED_MANDATORY_ANALYTE_SPEC_IDS):
                typed_specs_ok = all(
                    s.get("required") is True
                    and s.get("min_replicates_n") == 3
                    and s.get("ic50_pass_u95_max_nm") == 100.0
                    and s.get("ic50_fail_l95_gt_nm") == 500.0
                    and s.get("selectivity_pass_l95_min_fold") == 50.0
                    and s.get("selectivity_fail_u95_lt_fold") == 10.0
                    for s in spec_by_id.values()
                ) and spec_by_id["HLA-DQ8 + native WT InsB:9-23"].get("peptide_sequence") == "SHLVEALYLVCGERG"

        aff_spec = ep_aff.get("thresholds_spec")
        aff_spec_ok = (
            isinstance(aff_spec, dict)
            and aff_spec.get("ic50_pass_u95_max_nm") == 100.0
            and aff_spec.get("ic50_fail_l95_gt_nm") == 500.0
            and aff_spec.get("selectivity_pass_l95_min_fold") == 50.0
            and aff_spec.get("selectivity_fail_u95_lt_fold") == 10.0
            and "u95(ic50) <= 100.0 nm" in str(ep_aff.get("pass_rule", "")).lower()
            and "50.0x" in str(ep_aff.get("pass_rule", "")).lower()
            and "l95(ic50) > 500.0 nm" in str(ep_aff.get("fail_rule", "")).lower()
            and "u95(selectivity) < 10.0x" in str(ep_aff.get("fail_rule", "")).lower()
        )
        comp1_tgt_low = str(reg.get("component_1_target", "")).lower()
        checks["sc_all_4_mandatory_on_target_analytes_and_qc"] = (
            exact_4_strings_ok
            and typed_specs_ok
            and aff_spec_ok
            and isinstance(typed_ev, dict)
            and typed_ev.get("scalar_summaries_without_typed_records_rejected") is True
            and "hla-dq2.5" in comp1_tgt_low
            and "hla-dq8-trans" in comp1_tgt_low
            and "hla-dq2.2" in comp1_tgt_low
            and _RE_OMISSION_OR_OPTIONAL.search(comp1_tgt_low) is None
            and "hla-dq2.5" in qc_low
            and "hla-dq8-trans" in qc_low
            and "hla-dq2.2" in qc_low
            and "shlvealylvcgerg" in qc_low
        )
        checks["sc_dq22_in_target_analytes_and_qc"] = (
            "HLA-DQ2.2 + HIP11" in on_target_list
            and typed_specs_ok
            and "hla-dq2.2" in comp1_tgt_low
            and "hla-dq2.2" in qc_low
        )
        checks["sc_ctrl1_all_3_offtarget_analytes"] = (
            "HLA-DQ8 + CLIP1" in c1_analytes
            and "HLA-DQ8 + DQ8-glia-gamma1a" in c1_analytes
            and "HLA-DQ8-trans + WT InsB:9-23" in c1_analytes
        )
        comp1_off_list = [str(x) for x in gate_spr.get("mandatory_component1_off_target_spr_analytes_iip0044", [])]
        checks["sc_comp1_all_4_offtarget_analytes"] = all(
            a in comp1_off_list for a in _SHIELD_MANDATORY_COMP1_OFF_TARGET_CONTROLS
        )
        sec_thr = typed_ev.get("sec_mals_dls_quantitative_pass_thresholds", {}) if isinstance(typed_ev, dict) else {}
        hla_allow = typed_ev.get("qualifying_t1d_donor_hla_dq_allowlist", []) if isinstance(typed_ev, dict) else []
        p1jk8_pol = str(typed_ev.get("physical_1jk8_reagent_policy", "")).lower() if isinstance(typed_ev, dict) else ""
        gy18_rule = str(cyto_unit.get("gy018_denominator_compliance_rule", "")).lower() if isinstance(cyto_unit, dict) else ""
        checks["sc_r05_quant_secmals_batch_hla_gy018_optional_1jk8"] = (
            isinstance(typed_ev, dict)
            and typed_ev.get("expression_batch_linkage_required_every_assay_block") is True
            and typed_ev.get("construct_bound_expression_batch_provenance_enforced") is True
            and typed_ev.get("empty_construct_batches_rejected") is True
            and typed_ev.get("invalid_or_unregistered_spr_rows_excluded_from_bio_fail") is True
            and typed_ev.get("order_independent_canonical_key_uniqueness_enforced") is True
            and typed_ev.get("mandatory_typed_t1d_donor_eligibility_enforced") is True
            and typed_ev.get("required_donor_clinical_cohort") == _SHIELD_REQUIRED_DONOR_CLINICAL_COHORT
            and typed_ev.get("min_distinct_referenced_expression_batches_n") == 3
            and typed_ev.get("min_distinct_linked_comp1_batches_n") == 3
            and typed_ev.get("min_distinct_linked_comp2_batches_n") == 3
            and isinstance(sec_thr, dict)
            and sec_thr.get("comp1_monomer_pct_min") == 95.0
            and sec_thr.get("comp2_monomer_pct_min") == 95.0
            and sec_thr.get("cocktail_1to1_monomer_pct_min") == 95.0
            and sec_thr.get("dls_pdi_max") == 0.15
            and sec_thr.get("no_aggregates_or_precipitation_required") is True
            and all(h in hla_allow for h in ("HLA-DQ2.5", "HLA-DQ8", "HLA-DQ8-trans", "HLA-DQ2.2"))
            and "optional" in p1jk8_pol
            and "null" in p1jk8_pol
            and "1jk8" in p1jk8_pol
            and "gy-018" in gy18_rule
            and "design_effect_deff == 1.0" in gy18_rule
            and cyto_unit.get("exact_deff_equality_zero_tolerance") is True
            and cyto_unit.get("exact_deff_preserved_as_decimal_from_json") is True
            and cyto_unit.get("invalid_donors_excluded_from_confidence_bounds") is True
            and cyto_unit.get("cytotoxicity_estimand") == _SHIELD_CYTO_ESTIMAND
            and cyto_unit.get("simultaneous_fwer_alpha") == 0.05
            and cyto_unit.get("per_donor_bonferroni_alpha_formula") == "0.05 / N_roster"
            and cyto_unit.get("fixed_preexclusion_family_denominator_enforced") is True
            and cyto_unit.get("preregistered_donor_roster_mandatory") is True
            and cyto_unit.get("preregistered_donor_roster_sha256_verified") is True
            and cyto_unit.get("gy018_independence_justification_mandatory") is True
            and cyto_unit.get("suppression_estimand") == _SHIELD_SUPPRESSION_ESTIMAND
            and cyto_unit.get("suppression_inference_method") == _SHIELD_SUPPRESSION_INFERENCE_METHOD
            and cyto_unit.get("suppression_student_t_authorizing") is False
            and cyto_unit.get("cohort_t_lower_authorizing") is False
            and typed_ev.get("preregistered_donor_family_roster_mandatory") is True
            and typed_ev.get("preregistered_donor_family_roster_sha256_verified") is True
            and typed_ev.get("gy018_independence_justification_mandatory") is True
            and typed_ev.get("suppression_student_t_authorizing") is False
            and typed_ev.get("suppression_confirmatory_min_donors_n") == _SHIELD_MIN_CONFIRMATORY_DONORS_N
        )
        checks["sc_ctrl2_secmals_dls_homodimer_06691"] = (
            "sec-mals" in c2_sec.lower()
            and "dls" in c2_sec.lower()
            and "homodimer" in c2_sec.lower()
            and "0.6691" in c2_sec
            and "IsletSHIELD_Comp2_T006" in c2_sec
            and "IsletSHIELD_QF09_pI2" in c2_sec
        )
        checks["sc_ctrl3_all_6_parallel_comparators"] = all(
            tok in c3_comps
            for tok in ("IsletSHIELD_Comp2_T006", "SHIELD2_QQ", "R3_shv2_stk1", "SH2_MP01", "SH2_MP06", "SH2_MP08")
        )
        typed_peps_ok = isinstance(reg_spec, dict) and all(
            isinstance(reg_spec.get(rk), dict)
            and all(reg_spec[rk].get(fk) == fv for fk, fv in exp.items())
            for rk, exp in EXPECTED_INSB_REFERENCE_PEPTIDES.items()
        )
        sc_decoded_blob = json.dumps(sc_obj, ensure_ascii=False)
        checks["sc_register_1jk8_wt15_6dfx_separated"] = (
            typed_peps_ok
            and _find_unnegated_1jk8_conflation(side_contract_text) is None
            and _find_unnegated_1jk8_conflation(sc_decoded_blob) is None
            and "LVEALYLVCGERGG" in reg_spec_str
            and "SHLVEALYLVCGERG" in reg_spec_str
            and "VEELYLVAGEEG" in reg_spec_str
            and "LVEALYLVCGERGG" in c3_regs_str
            and "SHLVEALYLVCGERG" in c3_regs_str
            and "VEELYLVAGEEG" in c3_regs_str
        )

        # Exact AND conjunction + 6-level fail-first precedence + N_eff >= 60 + both nonzero holds in JSON
        blk_pass = str(ep_blk.get("pass_rule", "")).lower()
        blk_fail = str(ep_blk.get("fail_rule", "")).lower()
        blk_hold = str(ep_blk.get("hold_rule", "")).lower()
        pass_spec = ep_blk.get("pass_rule_spec")
        pass_spec_ok = (
            isinstance(pass_spec, dict)
            and pass_spec.get("logical_operator") == "AND"
            and pass_spec.get("fail_logical_operator") == "OR"
            and pass_spec.get("suppression_estimand") == _SHIELD_SUPPRESSION_ESTIMAND
            and pass_spec.get("suppression_inference_method") == _SHIELD_SUPPRESSION_INFERENCE_METHOD
            and pass_spec.get("suppression_student_t_authorizing") is False
            and pass_spec.get("suppression_confirmatory_min_donors_n") == _SHIELD_MIN_CONFIRMATORY_DONORS_N
            and pass_spec.get("suppression_responder_l95_clopper_pearson_min_pct") == 70.0
            and pass_spec.get("suppression_anti_enhancement_min_pct") == 0.0
            and pass_spec.get("suppression_cohort_mean_min_pct") == 70.0
            and pass_spec.get("observed_offtarget_apc_cytotoxicity_exact_pct") == 0.0
            and pass_spec.get("offtarget_apc_cytotoxicity_u95_max_pct") == 5.0
            and pass_spec.get("min_n_eff_per_donor") == 60
            and pass_spec.get("fail_suppression_nonresponder_lt_40pct_l95_clopper_pearson_gt_pct") == 60.0
            and pass_spec.get("fail_offtarget_apc_cytotoxicity_l95_gt_pct") == 5.0
            and pass_spec.get("preregistered_donor_roster_mandatory") is True
            and pass_spec.get("per_donor_bonferroni_alpha_formula") == "0.05 / N_roster"
            and pass_spec.get("nonzero_u95_gt_5pct_hold_state") == "HOLD_CYTOTOXICITY_U95_EXCEEDS_5PCT"
            and pass_spec.get("nonzero_cytotoxicity_hold_state") == "HOLD_OBSERVED_NONZERO_CYTOTOXICITY"
        )
        pass_prose_and_ok = (
            bool(
                re.search(
                    r"l95_cp\(k_ge_70,\s*n_roster\)\s*>=\s*70\.0%.*?\band\b.*?min_donor_suppression\s*>=\s*0\.0%.*?\band\b.*?0%\s+observed\s+off-target\s+apc\s+cytotoxicity\s+and\s+(?:off-target\s+apc\s+cytotoxicity\s+)?u95\s*<=\s*5\.0%",
                    blk_pass,
                )
            )
            and "l95_t >=" not in blk_pass
            and not bool(re.search(r"\bor\b", blk_pass))
            and bool(
                re.search(
                    r"l95_cp\(k_lt_40,\s*n_roster\)\s*>\s*60\.0%.*\bor\b.*simultaneous_worst_donor_bonferroni_lower_pct\s*>\s*5\.0%",
                    blk_fail,
                )
            )
            and "u95_t < 40.0%" not in blk_fail
            and "cohort_mean_cytotoxicity_l975_pct" not in blk_fail
            and _RE_MD_CONTRADICTORY_CYTO_FAIL.search(blk_fail) is None
        )
        checks["sc_unified_cytotoxicity_pass_and_hold_tiebreak"] = (
            pass_spec_ok
            and pass_prose_and_ok
            and "> 0%" in blk_hold
            and "u95 > 5.0%" in blk_hold
            and "hold_cytotoxicity_u95_exceeds_5pct" in blk_hold
            and "u95 <= 5.0%" in blk_hold
            and "hold_observed_nonzero_cytotoxicity" in blk_hold
        )
        pre_adj_str = str(prec_tbl.get("pre_adjudication_nonfinite_rejection", "")).lower()
        checks["sc_fail_first_precedence_and_cytotoxicity_unit"] = (
            isinstance(prec_tbl, dict)
            and prec_tbl.get("precedence_order") == _EXPECTED_SHIELD_SPR_PRECEDENCE_LIST
            and "valueerror" in pre_adj_str
            and isinstance(cyto_unit, dict)
            and cyto_unit.get("min_n_eff_per_donor") == 60
            and "clopper" in json.dumps(cyto_unit).lower()
            and "n_eff" in json.dumps(cyto_unit).lower()
            and "donor" in json.dumps(cyto_unit).lower()
        )
    else:
        for k in (
            "sc_typed_gate_present",
            "sc_stale_v13_hold_note_retired",
            "sc_post_spr_v14_maturation_present",
            "sc_comp1_qf09_pi2_lead",
            "sc_comp2_t006_lead",
            "sc_two_component_cocktail",
            "sc_all_4_mandatory_on_target_analytes_and_qc",
            "sc_dq22_in_target_analytes_and_qc",
            "sc_ctrl1_all_3_offtarget_analytes",
            "sc_comp1_all_4_offtarget_analytes",
            "sc_r05_quant_secmals_batch_hla_gy018_optional_1jk8",
            "sc_ctrl2_secmals_dls_homodimer_06691",
            "sc_ctrl3_all_6_parallel_comparators",
            "sc_register_1jk8_wt15_6dfx_separated",
            "sc_unified_cytotoxicity_pass_and_hold_tiebreak",
            "sc_fail_first_precedence_and_cytotoxicity_unit",
        ):
            checks[k] = False

    # --- PART B: Independent full-clause Markdown validation on GATE-30 protocol section ### 2.2 ONLY ---
    md_masked = mask_canonical_layer2_disclaimer_only(protocol_md_text)
    md_low = md_masked.lower()
    sec22 = _extract_gate30_shield_spr_md_section(md_masked)
    sec22_low = sec22.lower()

    checks["md_stale_v13_hold_note_retired"] = ("hold for v1.3 affinity maturation" not in md_low)
    checks["md_post_spr_v14_maturation_present"] = ("v1.4" in sec22_low)
    checks["md_comp1_qf09_pi2_lead"] = ("isletshield_qf09_pi2" in sec22_low)
    checks["md_comp2_t006_lead"] = ("isletshield_comp2_t006" in sec22_low)
    checks["md_two_component_cocktail"] = ("2-component" in sec22_low or "two-component" in sec22_low)
    md_mandatory_all4_clause = bool(
        re.search(r"all\s+(?:four|4)\s+mandatory\s+on-target\s+(?:complexes|analytes)", sec22_low)
    )
    checks["md_all_4_mandatory_on_target_analytes_and_qc"] = (
        md_mandatory_all4_clause
        and _RE_MD_WEAKENED_COVERAGE.search(sec22_low) is None
        and "hla-dq2.5 + hip11" in sec22_low
        and "hla-dq8-trans + hip11" in sec22_low
        and "hla-dq2.2 + hip11" in sec22_low
        and bool(re.search(r"hla-dq8\s*\+\s*(?:15-aa\s+)?native\s+wt\s+insb:9-23", sec22_low))
        and "shlvealylvcgerg" in sec22_low
    )
    checks["md_dq22_in_target_analytes_and_qc"] = (
        md_mandatory_all4_clause
        and _RE_MD_WEAKENED_COVERAGE.search(sec22_low) is None
        and "hla-dq2.2 + hip11" in sec22_low
    )
    checks["md_ctrl1_all_3_offtarget_analytes"] = (
        "hla-dq8 + clip1" in sec22_low
        and ("hla-dq8 + dq8-glia-gamma1a" in sec22_low or "dq8_glia_gamma1a" in sec22_low)
        and "hla-dq8-trans + wt insb:9-23" in sec22_low
    )
    checks["md_comp1_all_4_offtarget_analytes"] = (
        "hla-dq2.5 + clip1" in sec22_low
        and "hla-dq2.5 + self_igkv2_eaed" in sec22_low
        and "hla-dq2.5 + cel_glutenin_l1" in sec22_low
        and "hla-dq8-trans + cpep_nterm_eaed" in sec22_low
    )
    checks["md_r05_quant_secmals_batch_hla_gy018_optional_1jk8"] = (
        "95.0%" in sec22_low
        and "dls_pdi <= 0.15" in sec22_low
        and "expression_batch_ids" in sec22_low
        and "hla_genotype" in sec22_low
        and "t1d_diagnosis_confirmed" in sec22_low
        and "donor_clinical_cohort" in sec22_low
        and "t1d_prequalification_ref" in sec22_low
        and "gy-018" in sec22_low
        and "gy018_independence_justification" in sec22_low
        and "design_effect_deff == 1.0" in sec22_low
        and "zero tolerance" in sec22_low
        and "decimal" in sec22_low
        and "bonferroni" in sec22_low
        and "0.05 / n_roster" in sec22_low
        and "preregistered_donor_family_roster" in sec22_low
        and "roster_sha256" in sec22_low
        and "h0_all" in sec22_low
        and "non-authorizing" in sec22_low
        and "optional" in sec22_low
        and "null" in sec22_low
        and "crystal_ref_1jk8_14aa" in sec22_low
    )
    # R06 B4: Strict clause-level Markdown batch-requirement validation (rejects contradictory single-batch wording!)
    sec22_nobt = sec22_low.replace("`", "")
    md_has_three_linked_batches_clause = (
        bool(re.search(r"(?:n\s*>=\s*3|>=\s*3)\s+independent[^\n]{0,40}expression\s+batches", sec22_nobt))
        and bool(
            re.search(
                r">=\s*3\s+distinct\s+(?:declared\s+)?(?:linked\s+)?(?:passing\s+)?(?:comp1|component\s*1)[^.\n]{0,60}batches",
                sec22_nobt,
            )
        )
        and bool(
            re.search(
                r">=\s*3\s+distinct\s+(?:declared\s+)?(?:linked\s+)?(?:passing\s+)?(?:comp2|component\s*2)[^.\n]{0,60}batches",
                sec22_nobt,
            )
        )
        and "construct_ids" in sec22_nobt
        and _RE_MD_CONTRADICTORY_BATCH_RULE.search(sec22_nobt) is None
    )
    checks["md_construct_bound_three_batch_clause_no_contradiction"] = md_has_three_linked_batches_clause
    checks["md_ctrl2_secmals_dls_homodimer_06691"] = (
        "sec-mals" in sec22_low and "dls" in sec22_low and "homodimer" in sec22_low and "0.6691" in sec22_low
    )
    checks["md_ctrl3_all_6_parallel_comparators"] = all(
        tok in sec22_low
        for tok in ("isletshield_comp2_t006", "shield2_qq", "r3_shv2_stk1", "sh2_mp01", "sh2_mp06", "sh2_mp08")
    )
    checks["md_register_1jk8_wt15_6dfx_separated"] = (
        _find_unnegated_1jk8_conflation(md_masked) is None
        and "LVEALYLVCGERGG" in sec22
        and "SHLVEALYLVCGERG" in sec22
        and "VEELYLVAGEEG" in sec22
        and "1jk8" in sec22_low
        and "6dfx" in sec22_low
    )
    # Strict full-clause PASS, FAIL, HOLD_CYTOTOXICITY_U95_EXCEEDS_5PCT, HOLD_OBSERVED_NONZERO_CYTOTOXICITY checks on sec22
    md_aff_pass_ok = (
        bool(re.search(r"`?u95\(ic50\)\s*<=\s*100\.0\s*nm`?", sec22_low))
        and bool(re.search(r"`?l95\((?:off-target\s+)?selectivity\)\s*>=\s*50\.0(?:x|\u00d7)`?", sec22_low))
    )
    md_fail_clause_ok = (
        bool(re.search(r"`?l95\(ic50\)\s*>\s*500\.0\s*nm`?", sec22_low))
        and bool(re.search(r"`?u95\((?:off-target\s+)?selectivity\)\s*<\s*10\.0(?:x|\u00d7)`?", sec22_low))
        and bool(re.search(r"`?l95_cp\(k_lt_40,\s*n_roster\)\s*>\s*60\.0%`?", sec22_low))
        and "u95_t < 40.0%" not in sec22_low
        and bool(
            re.search(
                r"off-target\s+apc\s+cytotoxicity[^.\n]{0,110}`?simultaneous_worst_donor_bonferroni_lower_pct\s*>\s*5\.0%`?",
                sec22_low,
            )
        )
        and "cohort_mean_cytotoxicity_l975_pct" not in sec22_low
        and _RE_MD_CONTRADICTORY_CYTO_FAIL.search(sec22_low) is None
    )
    md_pass_and_ok = bool(
        re.search(
            r"`?l95_cp\(k_ge_70,\s*n_roster\)\s*>=\s*70\.0%`?[^\n]{0,120}`?min_donor_suppression\s*>=\s*0\.0%`?[^\n]{0,120}"
            r"(?:\*\*)?and(?:\*\*)?\s+(?:\*\*)?`?0%`?\s+observed\s+off-target\s+apc\s+cytotoxicity(?:\*\*)?\s+"
            r"(?:\*\*)?and(?:\*\*)?\s+(?:off-target\s+apc\s+cytotoxicity\s+)?`?u95\s*<=\s*5\.0%`?",
            sec22_low,
        )
    ) and ("l95_t >= 70.0%" not in sec22_low)
    md_hold_u95_gt5_ok = bool(
        re.search(
            r"observed\s+off-target\s+apc\s+cytotoxicity\s+`?>\s*0%`?\s+with\s+[^.\n]{0,65}<=\s*5\.0%`?\s+(?:\*\*)?and(?:\*\*)?\s+(?:conservative\s+)?`?u95\s*>\s*5\.0%`?",
            sec22_low,
        )
        and "hold_cytotoxicity_u95_exceeds_5pct" in sec22_low
    )
    md_hold_nonzero_ok = bool(
        re.search(
            r"(?:observed\s+off-target\s+apc\s+cytotoxicity\s+(?:is\s+)?`?>\s*0%`?|hold\s+if\s+`?>\s*0%`?)\s+(?:\*\*)?while\s+`?u95\s*<=\s*5\.0%`?(?:\*\*)?",
            sec22_low,
        )
        and "hold_observed_nonzero_cytotoxicity" in sec22_low
    )
    checks["md_unified_cytotoxicity_pass_and_hold_tiebreak"] = (
        md_aff_pass_ok
        and md_fail_clause_ok
        and md_pass_and_ok
        and md_hold_u95_gt5_ok
        and md_hold_nonzero_ok
    )
    # Ordered 6-level numbered precedence + N_eff >= 60 + pre-adjudication ValueError in sec22
    md_prec_ordered = bool(
        re.search(
            r"1\.\s+(?:\*\*)?`?fail`?(?:\*\*)?.*?"
            r"2\.\s+(?:\*\*)?`?hold_invalid_or_missing_input`?(?:\*\*)?.*?"
            r"3\.\s+(?:\*\*)?`?hold_cytotoxicity_u95_exceeds_5pct`?(?:\*\*)?.*?"
            r"4\.\s+(?:\*\*)?`?hold_observed_nonzero_cytotoxicity`?(?:\*\*)?.*?"
            r"5\.\s+(?:\*\*)?`?hold`?(?:\*\*)?.*?"
            r"6\.\s+(?:\*\*)?`?pass`?(?:\*\*)?",
            sec22_low,
            flags=re.DOTALL,
        )
    )
    checks["md_fail_first_precedence_and_cytotoxicity_unit"] = (
        md_prec_ordered
        and "valueerror" in sec22_low
        and "clopper" in sec22_low
        and bool(re.search(r"n_eff[^.\n]{0,35}>=\s*60", sec22_low))
    )

    # --- PART C: Legacy IIP-0042 vendor-token hygiene compatibility on BOTH surfaces ---
    legacy_vendor_hits_sc = sum(
        len(re.findall(r"(?<![a-z0-9])" + re.escape(tok) + r"(?![a-z0-9])", sc_low))
        for tok in _IIP0042_LEGACY_VENDOR_TOKENS
    )
    legacy_vendor_hits_proto = sum(
        len(re.findall(r"(?<![a-z0-9])" + re.escape(tok) + r"(?![a-z0-9])", md_low))
        for tok in _IIP0042_LEGACY_VENDOR_TOKENS
    )
    checks["iip0042_legacy_vendor_hygiene_compatible"] = (legacy_vendor_hits_sc == 0 and legacy_vendor_hits_proto == 0)

    gaps = [k for k, ok in checks.items() if not ok]
    return {
        "aligned": len(gaps) == 0,
        "independent_surface_enforcement": True,
        "checks": checks,
        "gaps": gaps,
    }


def _sample_aligned_iip0042_pair() -> tuple[dict[str, Any], str]:
    sc = {
        "executable_stage0_and_conditional_gates": {
            "Gate_30_SHIELD_SPR": {
                "registered_cocktail_identity": {
                    "architecture": "2-component Islet-SHIELD cocktail",
                    "component_1_lead_id": "IsletSHIELD_QF09_pI2",
                    "component_1_target": "HLA-DQ2.5 / HLA-DQ8-trans / HLA-DQ2.2 + HIP11",
                    "component_2_lead_id": "IsletSHIELD_Comp2_T006",
                    "component_2_target": "HLA-DQ8 + 15-aa native WT InsB:9-23 (SHLVEALYLVCGERG)",
                },
                "mandatory_on_target_spr_analytes": list(_EXPECTED_MANDATORY_ANALYTE_STRINGS),
                "mandatory_on_target_spr_analyte_specs": [
                    {
                        "analyte_id": "HLA-DQ2.5 + HIP11",
                        "required": True,
                        "min_replicates_n": 3,
                        "ic50_pass_u95_max_nm": 100.0,
                        "ic50_fail_l95_gt_nm": 500.0,
                        "selectivity_pass_l95_min_fold": 50.0,
                        "selectivity_fail_u95_lt_fold": 10.0,
                    },
                    {
                        "analyte_id": "HLA-DQ8-trans + HIP11",
                        "required": True,
                        "min_replicates_n": 3,
                        "ic50_pass_u95_max_nm": 100.0,
                        "ic50_fail_l95_gt_nm": 500.0,
                        "selectivity_pass_l95_min_fold": 50.0,
                        "selectivity_fail_u95_lt_fold": 10.0,
                    },
                    {
                        "analyte_id": "HLA-DQ2.2 + HIP11",
                        "required": True,
                        "min_replicates_n": 3,
                        "ic50_pass_u95_max_nm": 100.0,
                        "ic50_fail_l95_gt_nm": 500.0,
                        "selectivity_pass_l95_min_fold": 50.0,
                        "selectivity_fail_u95_lt_fold": 10.0,
                    },
                    {
                        "analyte_id": "HLA-DQ8 + native WT InsB:9-23",
                        "peptide_sequence": "SHLVEALYLVCGERG",
                        "required": True,
                        "min_replicates_n": 3,
                        "ic50_pass_u95_max_nm": 100.0,
                        "ic50_fail_l95_gt_nm": 500.0,
                        "selectivity_pass_l95_min_fold": 50.0,
                        "selectivity_fail_u95_lt_fold": 10.0,
                    },
                ],
                "mandatory_component1_off_target_spr_analytes_iip0044": list(_SHIELD_MANDATORY_COMP1_OFF_TARGET_CONTROLS),
                "typed_evidence_contract": {
                    "scalar_summaries_without_typed_records_rejected": True,
                    "expression_batch_linkage_required_every_assay_block": True,
                    "construct_bound_expression_batch_provenance_enforced": True,
                    "empty_construct_batches_rejected": True,
                    "invalid_or_unregistered_spr_rows_excluded_from_bio_fail": True,
                    "order_independent_canonical_key_uniqueness_enforced": True,
                    "mandatory_typed_t1d_donor_eligibility_enforced": True,
                    "preregistered_donor_family_roster_mandatory": True,
                    "preregistered_donor_family_roster_sha256_verified": True,
                    "gy018_independence_justification_mandatory": True,
                    "suppression_student_t_authorizing": False,
                    "suppression_confirmatory_min_donors_n": _SHIELD_MIN_CONFIRMATORY_DONORS_N,
                    "required_donor_clinical_cohort": "T1D",
                    "min_distinct_referenced_expression_batches_n": 3,
                    "min_distinct_linked_comp1_batches_n": 3,
                    "min_distinct_linked_comp2_batches_n": 3,
                    "qualifying_t1d_donor_hla_dq_allowlist": ["HLA-DQ2.5", "HLA-DQ8", "HLA-DQ8-trans", "HLA-DQ2.2"],
                    "sec_mals_dls_quantitative_pass_thresholds": {
                        "comp1_monomer_pct_min": 95.0,
                        "comp2_monomer_pct_min": 95.0,
                        "cocktail_1to1_monomer_pct_min": 95.0,
                        "dls_pdi_max": 0.15,
                        "no_aggregates_or_precipitation_required": True,
                    },
                    "physical_1jk8_reagent_policy": "Physical 14-aa 1JK8 synthetic control reagent is optional in register_qc_records (omitting crystal_ref_1jk8_14aa OR setting crystal_ref_1jk8_14aa to JSON null both PASS; any non-null value is validated strictly).",
                },
                "mandatory_reagent_qc": "QC covering HLA-DQ2.5 / HLA-DQ8-trans / HLA-DQ2.2 + HIP11 and HLA-DQ8 + WT InsB:9-23 (SHLVEALYLVCGERG), 14-aa 1JK8 (LVEALYLVCGERGG), and 12-aa 6DFX p8E9E (VEELYLVAGEEG).",
                "register_and_peptide_identity_spec": {
                    "deposited_crystal_reference_1jk8": {
                        "pdb_id": "1JK8",
                        "chain": "C",
                        "sequence": "LVEALYLVCGERGG",
                        "length_aa": 14,
                        "role": "DEPOSITED_CRYSTAL_REFERENCE_INSB11_23_PLUS_G",
                    },
                    "modeled_native_target_wt_insb9_23": {
                        "uniprot_anchor": "P01308[33..47]",
                        "sequence": "SHLVEALYLVCGERG",
                        "length_aa": 15,
                        "role": "NATIVE_HUMAN_WT_INSB9_23_TARGET",
                    },
                    "engineered_register3_comparator_6dfx": {
                        "pdb_id": "6DFX",
                        "sequence": "VEELYLVAGEEG",
                        "length_aa": 12,
                        "role": "ENGINEERED_REGISTER3_MIMOTOPE_COMPARATOR",
                    },
                },
                "mandatory_component2_bench_controls_iip0044": {
                    "control_1_off_target_spr_analytes": [
                        "HLA-DQ8 + CLIP1",
                        "HLA-DQ8 + DQ8-glia-gamma1a",
                        "HLA-DQ8-trans + WT InsB:9-23",
                    ],
                    "control_2_secmals_dls_monomer_and_coformulation": (
                        "SEC-MALS / DLS monomer and 1:1 co-formulation homodimer screen (Protenix-v1 0.6691) "
                        "for IsletSHIELD_Comp2_T006 and IsletSHIELD_QF09_pI2."
                    ),
                    "control_3_parallel_comparator_and_register_screen": {
                        "parallel_comparators": [
                            "IsletSHIELD_Comp2_T006",
                            "SHIELD2_QQ",
                            "R3_shv2_stk1",
                            "SH2_MP01",
                            "SH2_MP06",
                            "SH2_MP08",
                        ],
                        "register_controls": [
                            "15-aa WT InsB:9-23 (SHLVEALYLVCGERG)",
                            "14-aa 1JK8 chain C (LVEALYLVCGERGG)",
                            "12-aa 6DFX p8E9E (VEELYLVAGEEG)",
                        ],
                    },
                },
                "decision_precedence_table": {
                    "pre_adjudication_nonfinite_rejection": "Non-finite inputs raise ValueError before decision precedence.",
                    "precedence_order": list(_EXPECTED_SHIELD_SPR_PRECEDENCE_LIST),
                },
                "cytotoxicity_confidence_unit_specification": {
                    "min_n_eff_per_donor": 60,
                    "exact_deff_equality_zero_tolerance": True,
                    "exact_deff_preserved_as_decimal_from_json": True,
                    "invalid_donors_excluded_from_confidence_bounds": True,
                    "cytotoxicity_estimand": _SHIELD_CYTO_ESTIMAND,
                    "simultaneous_fwer_alpha": 0.05,
                    "per_donor_bonferroni_alpha_formula": "0.05 / N_roster",
                    "fixed_preexclusion_family_denominator_enforced": True,
                    "preregistered_donor_roster_mandatory": True,
                    "preregistered_donor_roster_sha256_verified": True,
                    "gy018_independence_justification_mandatory": True,
                    "suppression_estimand": _SHIELD_SUPPRESSION_ESTIMAND,
                    "suppression_inference_method": _SHIELD_SUPPRESSION_INFERENCE_METHOD,
                    "suppression_student_t_authorizing": False,
                    "cohort_t_lower_authorizing": False,
                    "gy018_denominator_compliance_rule": "Under GY-018, require exact design_effect_deff == 1.0 (zero tolerance, preserved as exact Decimal through strict JSON decoding), structured gy018_independence_justification, and n_eff == raw_independent_units_n >= 60, gating invalid/ineligible donors out of confidence bounds without shrinking N_roster.",
                    "observational_unit": "Primary human T1D donor APC biological replicate reconciled 100% against mandatory SHA-256-pinned preregistered_donor_family_roster",
                    "method": "Exact one-sided Clopper-Pearson Bonferroni lower bounds under fixed-roster global null H0_all: max_i p_i <= 5.0% at alpha_donor = 0.05 / N_roster (distribution-free FWER <= 0.05 conditional on external outcome-blind custody; Student-t is non-authorizing diagnostic only) over N_eff >= 60 effective APC events per donor",
                },
                "endpoints_and_3state_rules": [
                    {
                        "endpoint_id": "SHIELD_AFFINITY_AND_SELECTIVITY",
                        "thresholds_spec": {
                            "ic50_pass_u95_max_nm": 100.0,
                            "ic50_fail_l95_gt_nm": 500.0,
                            "selectivity_pass_l95_min_fold": 50.0,
                            "selectivity_fail_u95_lt_fold": 10.0,
                        },
                        "pass_rule": "U95(IC50) <= 100.0 nM AND L95(off_target_selectivity_ratio) >= 50.0x",
                        "fail_rule": "L95(IC50) > 500.0 nM OR U95(selectivity) < 10.0x",
                        "hold_rule": "HOLD for post-SPR v1.4 affinity/selectivity maturation",
                    },
                    {
                        "endpoint_id": "SHIELD_HUMAN_TCELL_BLOCKADE",
                        "pass_rule_spec": {
                            "logical_operator": "AND",
                            "suppression_estimand": _SHIELD_SUPPRESSION_ESTIMAND,
                            "suppression_inference_method": _SHIELD_SUPPRESSION_INFERENCE_METHOD,
                            "suppression_student_t_authorizing": False,
                            "suppression_confirmatory_min_donors_n": _SHIELD_MIN_CONFIRMATORY_DONORS_N,
                            "suppression_responder_l95_clopper_pearson_min_pct": 70.0,
                            "suppression_anti_enhancement_min_pct": 0.0,
                            "suppression_cohort_mean_min_pct": 70.0,
                            "observed_offtarget_apc_cytotoxicity_exact_pct": 0.0,
                            "offtarget_apc_cytotoxicity_u95_max_pct": 5.0,
                            "min_n_eff_per_donor": 60,
                            "fail_logical_operator": "OR",
                            "fail_suppression_nonresponder_lt_40pct_l95_clopper_pearson_gt_pct": 60.0,
                            "fail_offtarget_apc_cytotoxicity_l95_gt_pct": 5.0,
                            "preregistered_donor_roster_mandatory": True,
                            "per_donor_bonferroni_alpha_formula": "0.05 / N_roster",
                            "nonzero_u95_gt_5pct_hold_state": "HOLD_CYTOTOXICITY_U95_EXCEEDS_5PCT",
                            "nonzero_cytotoxicity_hold_state": "HOLD_OBSERVED_NONZERO_CYTOTOXICITY",
                        },
                        "pass_rule": "100% reconciled SHA-256-pinned preregistered_donor_family_roster AND exact Clopper-Pearson suppression responder L95_CP(k_ge_70, N_roster) >= 70.0% (min N_roster=9) AND anti-enhancement min_donor_suppression >= 0.0% AND cohort mean >= 70.0% AND 0% observed off-target APC cytotoxicity AND off-target APC cytotoxicity U95 <= 5.0%",
                        "fail_rule": "exact Clopper-Pearson suppression non-responder L95_CP(k_lt_40, N_roster) > 60.0% OR off-target APC cytotoxicity fixed-roster Bonferroni lower bound simultaneous_worst_donor_bonferroni_lower_pct > 5.0% (H0_all: max_i p_i <= 5.0%, FWER <= 0.05 at alpha_donor = 0.05 / N_roster; Student-t is non-authorizing diagnostic only)",
                        "hold_rule": "If no FAIL: observed off-target APC cytotoxicity > 0% with calibrated simultaneous lower <= 5.0% AND U95 > 5.0% -> HOLD_CYTOTOXICITY_U95_EXCEEDS_5PCT; observed off-target APC cytotoxicity > 0% while U95 <= 5.0% -> HOLD_OBSERVED_NONZERO_CYTOTOXICITY",
                    },
                ],
            }
        }
    }
    md = (
        "### 2.2 `Gate 30-SHIELD-SPR` (2-component Islet-SHIELD cocktail: IsletSHIELD_QF09_pI2 + IsletSHIELD_Comp2_T006)\n"
        "- `n >= 3` independent E. coli expression batches with non-empty `construct_ids` and construct-bound `expression_batch_ids` linkage requiring `>= 3` distinct linked passing Comp1 batches and `>= 3` distinct linked passing Comp2 batches across all four mandatory on-target complexes: HLA-DQ2.5 + HIP11, HLA-DQ8-trans + HIP11, HLA-DQ2.2 + HIP11, HLA-DQ8 + 15-aa native WT InsB:9-23 (SHLVEALYLVCGERG).\n"
        "- Separated reagents: optional physical 14-aa PDB 1JK8 chain C (LVEALYLVCGERGG, omitting `crystal_ref_1jk8_14aa` or setting JSON `null` both PASS; non-null validated strictly), 15-aa native WT InsB:9-23 (SHLVEALYLVCGERG), 12-aa 6DFX p8E9E (VEELYLVAGEEG).\n"
        "- Mandatory Comp1 + Comp2 controls (with construct-bound expression_batch_ids linkage): HLA-DQ2.5 + CLIP1, HLA-DQ2.5 + Self_IGKV2_EAED, HLA-DQ2.5 + cel_glutenin_L1, HLA-DQ8-trans + Cpep_Nterm_EAED; "
        "HLA-DQ8 + CLIP1, HLA-DQ8 + DQ8-glia-gamma1a, HLA-DQ8-trans + WT InsB:9-23; "
        "SEC-MALS / DLS monomer (>= 95.0%, dls_pdi <= 0.15) & 1:1 co-formulation homodimer test (Protenix-v1 0.6691); "
        "parallel screen of IsletSHIELD_Comp2_T006, SHIELD2_QQ, R3_shv2_stk1, SH2_MP01, SH2_MP06, SH2_MP08.\n"
        "- 0. Pre-adjudication non-finite inputs raise ValueError before decision precedence.\n"
        "- 1. `FAIL`: `L95(IC50) > 500.0 nM` OR `U95(off-target selectivity) < 10.0x` OR `L95_CP(k_lt_40, N_roster) > 60.0%` OR off-target APC cytotoxicity fixed-roster Bonferroni lower bound `simultaneous_worst_donor_bonferroni_lower_pct > 5.0%` under `H0_all: max_i p_i <= 5.0%` (distribution-free FWER <= 0.05 at `alpha_donor = 0.05 / N_roster` bound to mandatory SHA-256-pinned `preregistered_donor_family_roster` with `roster_sha256`; Student-t is non-authorizing diagnostic only).\n"
        "- 2. `HOLD_INVALID_OR_MISSING_INPUT`: missing typed evidence, missing/tampered/incomplete `preregistered_donor_family_roster` (`roster_sha256`), duplicate/conflicting canonical keys, invalid/unregistered SPR rows, missing/contradictory typed T1D donor eligibility (`t1d_diagnosis_confirmed=True`, `donor_clinical_cohort='T1D'`, non-empty unpadded `t1d_prequalification_ref`), missing hla_genotype, missing `gy018_independence_justification`, GY-018 violation (exact `design_effect_deff == 1.0` with zero tolerance preserved as exact `Decimal` from JSON), or `N_eff < 60`.\n"
        "- 3. `HOLD_CYTOTOXICITY_U95_EXCEEDS_5PCT`: observed off-target APC cytotoxicity `> 0%` with calibrated simultaneous lower `<= 5.0%` AND conservative `U95 > 5.0%`.\n"
        "- 4. `HOLD_OBSERVED_NONZERO_CYTOTOXICITY`: observed off-target APC cytotoxicity `> 0%` while `U95 <= 5.0%`.\n"
        "- 5. `HOLD`: post-SPR v1.4 maturation.\n"
        "- 6. `PASS`: `U95(IC50) <= 100.0 nM` AND `L95(off-target selectivity) >= 50.0x`; `L95_CP(k_ge_70, N_roster) >= 70.0%` AND `min_donor_suppression >= 0.0%` AND `0%` observed off-target APC cytotoxicity AND `U95 <= 5.0%`.\n"
        "- Confidence unit: exact Clopper-Pearson over `N_eff >= 60` per donor under GY-018 (exact `design_effect_deff == 1.0`, zero tolerance preserved as exact `Decimal` through JSON decoding; structured `gy018_independence_justification`; mandatory SHA-256-pinned `preregistered_donor_family_roster` with `alpha_donor = 0.05 / N_roster` and `H0_all`; Student-t is non-authorizing diagnostic only).\n"
    )
    return sc, md


def run_iip0042_alignment_self_tests() -> dict[str, Any]:
    unaligned_sc = json.dumps({"hold_rule": "Intermediate affinity (100-500 nM) -> HOLD for v1.3 affinity maturation"})
    unaligned_md = "### 2.2 Gate 30-SHIELD-SPR\nTest HLA-DQ2.5/HIP11 and 3 off-target look-alikes.\n"
    res_unaligned = evaluate_iip0042_alignment(unaligned_sc, unaligned_md)
    require_cond(res_unaligned["aligned"] is False, "Alignment checker must reject unaligned pre-S5 IIP-0042 payload")

    sc_good, md_good = _sample_aligned_iip0042_pair()
    res_aligned = evaluate_iip0042_alignment(json.dumps(sc_good), md_good)
    require_cond(res_aligned["aligned"] is True, f"Alignment checker must accept aligned payload: {res_aligned['gaps']}")

    # Independent mutation test 1: remove Comp2 controls from side-contract JSON ONLY -> MUST FAIL!
    sc_drop_ctrl = json.loads(json.dumps(sc_good))
    sc_drop_ctrl["executable_stage0_and_conditional_gates"]["Gate_30_SHIELD_SPR"]["mandatory_component2_bench_controls_iip0044"]["control_1_off_target_spr_analytes"] = []
    res_drop_sc = evaluate_iip0042_alignment(json.dumps(sc_drop_ctrl), md_good)
    require_cond(res_drop_sc["aligned"] is False and "sc_ctrl1_all_3_offtarget_analytes" in res_drop_sc["gaps"], "Must fail when Comp2 controls are deleted from side contract JSON only")

    # Independent mutation test 2: remove 0% observed cytotoxicity from protocol MD ONLY -> MUST FAIL!
    md_drop_cyto = md_good.replace("`0%` observed off-target APC cytotoxicity AND ", "")
    res_drop_md = evaluate_iip0042_alignment(json.dumps(sc_good), md_drop_cyto)
    require_cond(res_drop_md["aligned"] is False and "md_unified_cytotoxicity_pass_and_hold_tiebreak" in res_drop_md["gaps"], "Must fail when 0% cytotoxicity rule is deleted from protocol MD only")

    # Independent mutation test 3: omit HLA-DQ2.2 from side contract -> MUST FAIL!
    sc_drop_dq22 = json.loads(json.dumps(sc_good))
    sc_drop_dq22["executable_stage0_and_conditional_gates"]["Gate_30_SHIELD_SPR"]["mandatory_on_target_spr_analytes"] = [
        "HLA-DQ2.5 + HIP11", "HLA-DQ8-trans + HIP11", "HLA-DQ8 + native WT InsB:9-23 (15-aa SHLVEALYLVCGERG)"
    ]
    res_drop_dq22 = evaluate_iip0042_alignment(json.dumps(sc_drop_dq22), md_good)
    require_cond(res_drop_dq22["aligned"] is False and "sc_all_4_mandatory_on_target_analytes_and_qc" in res_drop_dq22["gaps"], "Must fail when HLA-DQ2.2 is omitted")

    # Independent mutation test 4: omit HLA-DQ2.5 + HIP11 from JSON -> MUST FAIL!
    sc_drop_dq25 = json.loads(json.dumps(sc_good))
    sc_drop_dq25["executable_stage0_and_conditional_gates"]["Gate_30_SHIELD_SPR"]["mandatory_on_target_spr_analytes"] = [
        "HLA-DQ8-trans + HIP11", "HLA-DQ2.2 + HIP11", "HLA-DQ8 + native WT InsB:9-23 (15-aa SHLVEALYLVCGERG)"
    ]
    res_drop_dq25 = evaluate_iip0042_alignment(json.dumps(sc_drop_dq25), md_good)
    require_cond(res_drop_dq25["aligned"] is False and "sc_all_4_mandatory_on_target_analytes_and_qc" in res_drop_dq25["gaps"], "Must fail when HLA-DQ2.5 + HIP11 is omitted from JSON")

    # Independent mutation test 5: flip AND -> OR in JSON alone -> MUST FAIL!
    sc_or_json = json.loads(json.dumps(sc_good))
    sc_or_json["executable_stage0_and_conditional_gates"]["Gate_30_SHIELD_SPR"]["endpoints_and_3state_rules"][1]["pass_rule"] = (
        sc_or_json["executable_stage0_and_conditional_gates"]["Gate_30_SHIELD_SPR"]["endpoints_and_3state_rules"][1]["pass_rule"].replace(
            "AND off-target APC cytotoxicity U95 <= 5.0%",
            "OR off-target APC cytotoxicity U95 <= 5.0%",
        )
    )
    res_or_json = evaluate_iip0042_alignment(json.dumps(sc_or_json), md_good)
    require_cond(res_or_json["aligned"] is False and "sc_unified_cytotoxicity_pass_and_hold_tiebreak" in res_or_json["gaps"], "Must fail when AND -> OR is flipped in JSON alone")

    # Independent mutation test 6: flip AND -> OR in Markdown alone -> MUST FAIL!
    md_or_only = md_good.replace(
        "`0%` observed off-target APC cytotoxicity AND `U95 <= 5.0%`",
        "`0%` observed off-target APC cytotoxicity OR `U95 <= 5.0%`",
    )
    res_or_md = evaluate_iip0042_alignment(json.dumps(sc_good), md_or_only)
    require_cond(res_or_md["aligned"] is False and "md_unified_cytotoxicity_pass_and_hold_tiebreak" in res_or_md["gaps"], "Must fail when AND -> OR is flipped in Markdown alone")

    # Independent mutation test 7 (B3 probe 1): JSON DQ2.2 entry altered to instruct omitting assay -> MUST FAIL!
    sc_omit_dq22_prose = json.loads(json.dumps(sc_good))
    sc_omit_dq22_prose["executable_stage0_and_conditional_gates"]["Gate_30_SHIELD_SPR"]["mandatory_on_target_spr_analytes"][2] = (
        "HLA-DQ2.2 + HIP11 (omit this assay; optional)"
    )
    res_omit_dq22_prose = evaluate_iip0042_alignment(json.dumps(sc_omit_dq22_prose), md_good)
    require_cond(
        res_omit_dq22_prose["aligned"] is False and "sc_all_4_mandatory_on_target_analytes_and_qc" in res_omit_dq22_prose["gaps"],
        "Must fail when JSON DQ2.2 row instructs reader to omit assay",
    )

    # Independent mutation test 8 (B3 probe 2): Markdown changed from all four complexes to only one optional complex -> MUST FAIL!
    md_one_opt = md_good.replace("all four mandatory on-target complexes", "only one optional complex")
    require_cond(md_one_opt != md_good, "md_one_opt mutation must modify md_good")
    res_one_opt = evaluate_iip0042_alignment(json.dumps(sc_good), md_one_opt)
    require_cond(
        res_one_opt["aligned"] is False and "md_all_4_mandatory_on_target_analytes_and_qc" in res_one_opt["gaps"],
        "Must fail when Markdown weakens all four mandatory complexes to only one optional complex",
    )

    # Independent mutation test 9 (B3 probe 3): Markdown APC cytotoxicity FAIL cutoff changed from > 5.0% to > 50.0% -> MUST FAIL!
    md_l95_50 = md_good.replace(
        "`simultaneous_worst_donor_bonferroni_lower_pct > 5.0%`",
        "`simultaneous_worst_donor_bonferroni_lower_pct > 50.0%`",
    )
    require_cond(md_l95_50 != md_good, "md_l95_50 mutation must modify md_good")
    res_l95_50 = evaluate_iip0042_alignment(json.dumps(sc_good), md_l95_50)
    require_cond(
        res_l95_50["aligned"] is False and "md_unified_cytotoxicity_pass_and_hold_tiebreak" in res_l95_50["gaps"],
        "Must fail when Markdown changes APC cytotoxicity FAIL cutoff from > 5.0% to > 50.0%",
    )

    # Independent mutation test 10 (R05 probe 1): drop Comp1 off-targets from JSON -> MUST FAIL!
    sc_drop_c1_off = json.loads(json.dumps(sc_good))
    sc_drop_c1_off["executable_stage0_and_conditional_gates"]["Gate_30_SHIELD_SPR"]["mandatory_component1_off_target_spr_analytes_iip0044"] = []
    res_drop_c1_off = evaluate_iip0042_alignment(json.dumps(sc_drop_c1_off), md_good)
    require_cond(
        res_drop_c1_off["aligned"] is False and "sc_comp1_all_4_offtarget_analytes" in res_drop_c1_off["gaps"],
        "Must fail when Component 1 off-target controls are removed from IIP-0042 JSON",
    )

    # Independent mutation test 11 (R05 probe 2): drop GY-018 / SEC-MALS 95.0% from Markdown -> MUST FAIL!
    md_drop_r05 = md_good.replace("GY-018", "unverified-cluster")
    require_cond(md_drop_r05 != md_good, "md_drop_r05 mutation must modify md_good")
    res_drop_r05 = evaluate_iip0042_alignment(json.dumps(sc_good), md_drop_r05)
    require_cond(
        res_drop_r05["aligned"] is False and "md_r05_quant_secmals_batch_hla_gy018_optional_1jk8" in res_drop_r05["gaps"],
        "Must fail when GY-018 requirement is removed from IIP-0042 Markdown",
    )

    # Independent mutation test 12 (R06 B4): isolated Markdown mutation changing >= 3 linked batches to 1 linked batch -> MUST FAIL!
    md_one_batch = md_good.replace(
        "`>= 3` distinct linked passing Comp1 batches and `>= 3` distinct linked passing Comp2 batches",
        "1 linked batch",
    )
    require_cond(md_one_batch != md_good, "md_one_batch mutation must modify md_good")
    res_one_batch = evaluate_iip0042_alignment(json.dumps(sc_good), md_one_batch)
    require_cond(
        res_one_batch["aligned"] is False and "md_construct_bound_three_batch_clause_no_contradiction" in res_one_batch["gaps"],
        "Must fail when Markdown replaces >= 3 linked batches with 1 linked batch while JSON is held fixed",
    )

    # Independent mutation test 13 (R06 B4b): appending contradictory 'single linked batch' permission to intact Markdown -> MUST FAIL!
    md_contra_batch = md_good + "\nNote: a single linked batch is permitted for expedited runs.\n"
    res_contra_batch = evaluate_iip0042_alignment(json.dumps(sc_good), md_contra_batch)
    require_cond(
        res_contra_batch["aligned"] is False and "md_construct_bound_three_batch_clause_no_contradiction" in res_contra_batch["gaps"],
        "Must fail when Markdown appends contradictory single linked batch wording",
    )

    # Independent mutation test 14 (R07 B5a): ordinary-English 'a pair of linked passing expression batches is sufficient' -> MUST FAIL!
    md_pair_batches = md_good + "\nNote: a pair of linked passing expression batches is sufficient for Comp1 on-target assays.\n"
    res_pair_batches = evaluate_iip0042_alignment(json.dumps(sc_good), md_pair_batches)
    require_cond(
        res_pair_batches["aligned"] is False and "md_construct_bound_three_batch_clause_no_contradiction" in res_pair_batches["gaps"],
        "Must fail when Markdown appends 'a pair of linked passing expression batches is sufficient'",
    )

    # Independent mutation test 15 (R07 B5b): ordinary-English 'two linked passing expression batches are adequate' -> MUST FAIL!
    md_two_batches = md_good + "\nNote: two linked passing expression batches are adequate for Comp2 assays.\n"
    res_two_batches = evaluate_iip0042_alignment(json.dumps(sc_good), md_two_batches)
    require_cond(
        res_two_batches["aligned"] is False and "md_construct_bound_three_batch_clause_no_contradiction" in res_two_batches["gaps"],
        "Must fail when Markdown appends 'two linked passing expression batches are adequate'",
    )

    # Independent mutation test 16 (R08 B4c): Sol's exact post-noun batch reversal -> MUST FAIL!
    md_as_low_as_two = md_good + "\nFor each component, the number of linked passing expression batches may be as low as two.\n"
    res_as_low_as_two = evaluate_iip0042_alignment(json.dumps(sc_good), md_as_low_as_two)
    require_cond(
        res_as_low_as_two["aligned"] is False and "md_construct_bound_three_batch_clause_no_contradiction" in res_as_low_as_two["gaps"],
        "Must fail when Markdown appends 'number of linked passing expression batches may be as low as two'",
    )

    # Independent mutation test 17 (R08 B4b): Sol's exact reversed en-dash 1JK8 conflation on BOTH JSON and MD -> MUST FAIL!
    sol_1jk8_probe = "The 15-residue wild-type insulin B:9\u201323 peptide was crystallized in PDB 1JK8."
    md_1jk8_rev = md_good + "\n" + sol_1jk8_probe + "\n"
    res_1jk8_md = evaluate_iip0042_alignment(json.dumps(sc_good), md_1jk8_rev)
    sc_1jk8_rev = json.loads(json.dumps(sc_good))
    sc_1jk8_rev["executable_stage0_and_conditional_gates"]["Gate_30_SHIELD_SPR"]["mandatory_reagent_qc"] += " " + sol_1jk8_probe
    res_1jk8_sc = evaluate_iip0042_alignment(json.dumps(sc_1jk8_rev), md_good)
    require_cond(
        res_1jk8_md["aligned"] is False and "md_register_1jk8_wt15_6dfx_separated" in res_1jk8_md["gaps"],
        "Must fail on reversed en-dash 1JK8 conflation in Markdown",
    )
    require_cond(
        res_1jk8_sc["aligned"] is False and "sc_register_1jk8_wt15_6dfx_separated" in res_1jk8_sc["gaps"],
        "Must fail on reversed en-dash 1JK8 conflation in JSON",
    )

    # Independent mutation test 18 (R09 B3): reverting suppression rule to stale Student-t L95_t >= 70% in JSON/MD -> MUST FAIL!
    sc_stale_t = json.loads(json.dumps(sc_good))
    sc_stale_t["executable_stage0_and_conditional_gates"]["Gate_30_SHIELD_SPR"]["endpoints_and_3state_rules"][1]["pass_rule"] = (
        "cohort L95_t >= 70.0% suppression AND 0% observed off-target APC cytotoxicity AND off-target APC cytotoxicity U95 <= 5.0%"
    )
    res_stale_t_sc = evaluate_iip0042_alignment(json.dumps(sc_stale_t), md_good)
    md_stale_t = md_good.replace("`L95_CP(k_ge_70, N_roster) >= 70.0%`", "`L95_t >= 70.0%`")
    res_stale_t_md = evaluate_iip0042_alignment(json.dumps(sc_good), md_stale_t)
    require_cond(
        res_stale_t_sc["aligned"] is False and res_stale_t_md["aligned"] is False,
        "Must fail when suppression rule reverts to stale Student-t authorization in JSON or Markdown",
    )

    # Independent mutation test 19 (R09 B2): dropping mandatory preregistered_donor_family_roster requirement -> MUST FAIL!
    sc_drop_roster = json.loads(json.dumps(sc_good))
    sc_drop_roster["executable_stage0_and_conditional_gates"]["Gate_30_SHIELD_SPR"]["typed_evidence_contract"]["preregistered_donor_family_roster_mandatory"] = False
    res_drop_roster_sc = evaluate_iip0042_alignment(json.dumps(sc_drop_roster), md_good)
    md_drop_roster = md_good.replace("preregistered_donor_family_roster", "ad_hoc_donors")
    res_drop_roster_md = evaluate_iip0042_alignment(json.dumps(sc_good), md_drop_roster)
    require_cond(
        res_drop_roster_sc["aligned"] is False and res_drop_roster_md["aligned"] is False,
        "Must fail when mandatory preregistered_donor_family_roster is weakened in JSON or Markdown",
    )

    case_results = {
        "unaligned_pre_s5_rejected": (not res_unaligned["aligned"]),
        "aligned_post_s5_accepted": res_aligned["aligned"],
        "side_contract_only_deletion_rejected": (not res_drop_sc["aligned"]),
        "protocol_md_only_deletion_rejected": (not res_drop_md["aligned"]),
        "missing_dq22_rejected": (not res_drop_dq22["aligned"]),
        "missing_dq25_rejected": (not res_drop_dq25["aligned"]),
        "json_and_to_or_flip_rejected": (not res_or_json["aligned"]),
        "markdown_and_to_or_flip_rejected": (not res_or_md["aligned"]),
        "json_dq22_omit_instruction_rejected": (not res_omit_dq22_prose["aligned"]),
        "markdown_one_optional_complex_rejected": (not res_one_opt["aligned"]),
        "markdown_cyto_l95_50pct_rejected": (not res_l95_50["aligned"]),
        "json_missing_comp1_offtargets_rejected": (not res_drop_c1_off["aligned"]),
        "markdown_missing_r05_gy018_rejected": (not res_drop_r05["aligned"]),
        "markdown_single_linked_batch_mutation_rejected": (not res_one_batch["aligned"]),
        "markdown_contradictory_single_batch_clause_rejected": (not res_contra_batch["aligned"]),
        "markdown_pair_of_batches_sufficient_rejected": (not res_pair_batches["aligned"]),
        "markdown_two_batches_adequate_rejected": (not res_two_batches["aligned"]),
        "markdown_batches_as_low_as_two_rejected": (not res_as_low_as_two["aligned"]),
        "markdown_reversed_endash_1jk8_conflation_rejected": (not res_1jk8_md["aligned"]),
        "json_reversed_endash_1jk8_conflation_rejected": (not res_1jk8_sc["aligned"]),
        "stale_student_t_suppression_reversion_rejected": (not res_stale_t_sc["aligned"] and not res_stale_t_md["aligned"]),
        "missing_mandatory_preregistered_roster_rejected": (not res_drop_roster_sc["aligned"] and not res_drop_roster_md["aligned"]),
        "aligned_iip0042_legacy_hygiene_clean": res_aligned["checks"]["iip0042_legacy_vendor_hygiene_compatible"],
    }
    return {
        "total_cases": len(case_results),
        **case_results,
        "passed": True,
    }


def resolve_repo_root(explicit_repo_root: Path | None, installed_check: bool) -> Path | None:
    if explicit_repo_root is not None:
        p = explicit_repo_root.expanduser().resolve()
        if not (p.is_dir() and (p / "scripts" / "rank_islet1_stacks.py").is_file()):
            raise FileNotFoundError(f"Invalid --repo-root (fail-closed): {explicit_repo_root.name}")
        return p
    if SCRIPT_DIR.name == "scripts" and (SCRIPT_DIR.parent / "scripts" / "rank_islet1_stacks.py").is_file():
        return SCRIPT_DIR.parent
    if installed_check:
        raise FileNotFoundError("Installed check requires --repo-root pointing to a valid OpenIslet repository")
    env_root = os.environ.get("OPENISLET_ROOT")
    if env_root:
        p = Path(env_root).expanduser().resolve()
        if (p / "scripts" / "rank_islet1_stacks.py").is_file():
            return p
    if SCRIPT_DIR.name == "artifacts-carbon":
        sibling = SCRIPT_DIR.parents[3] / "OpenIslet"
        if (sibling / "scripts" / "rank_islet1_stacks.py").is_file():
            return sibling
    return None


def run_verification(
    *,
    repo_root: Path | None,
    installed_check: bool,
) -> dict[str, Any]:
    if installed_check:
        require_cond(repo_root is not None, "Installed check requires a valid OpenIslet repository root")
        assert_root = repo_root  # type: ignore[assignment]
        fasta_leads_path = assert_root / "data" / "constructs" / "openislet_cleanroom_v1_3_all_leads.fasta"
        fasta_comp2_path = assert_root / "data" / "constructs" / "islet_shield_comp2_comparators_v1_3.fasta"
        side_contract_path = assert_root / "data" / "protocols" / "iip0044_foundry_v1_3_biologics_side_contract_v0.8.0.json"
        summary_path = assert_root / "data" / "extracted" / "iip0044_tier1_metrics_cleanroom_summary_v0.8.0.json"
        protocol_path = assert_root / "docs" / "FOUNDRY-V1-3-CLEANROOM-BIOLOGICS-PROTOCOL.md"
        dt_path = assert_root / "data" / "protocols" / "stage0_decision_tree_v1.json"
        test39_path = assert_root / "tests" / "test_iip0044_foundry_v1_3_biologics.py"
        mode_label = "INSTALLED_OPENISLET_CHECK"
    else:
        fasta_leads_path = SCRIPT_DIR / "openislet_cleanroom_v1_3_all_leads.fasta"
        fasta_comp2_path = SCRIPT_DIR / "islet_shield_comp2_comparators_v1_3.fasta"
        side_contract_path = SCRIPT_DIR / "iip0044_foundry_v1_3_biologics_side_contract_v0.8.0.json"
        summary_path = SCRIPT_DIR / "iip0044_tier1_metrics_cleanroom_summary_v0.8.0.json"
        protocol_path = SCRIPT_DIR / "FOUNDRY-V1-3-CLEANROOM-BIOLOGICS-PROTOCOL.md"
        dt_path = SCRIPT_DIR / "iip0044_decision_tree_block_dec123.json"
        test39_path = None
        mode_label = "STAGING_ARTIFACTS_CHECK"

    # 1. Verify both CC-BY-4.0 FASTAs and UniProt P07204[363..480] M406L identity
    leads_check = verify_fasta_file(fasta_leads_path, EXPECTED_ALL_LEADS_FASTA_SHA256, EXPECTED_ALL_LEADS_SPECS)
    comp2_check = verify_fasta_file(fasta_comp2_path, EXPECTED_COMP2_COMPS_FASTA_SHA256, EXPECTED_COMP2_COMPS_SPECS)
    thbd_check = verify_thbd_p07204_m406l(EXPECTED_ALL_LEADS_SPECS["IsletGUARD_THBD_M406L"]["seq"])

    # 2. Load and strictly verify pinned side-contract SHA-256, Tier-1 summary, decision-tree block, and protocol doc
    actual_sc_file_sha = sha256_file(side_contract_path)
    require_cond(
        actual_sc_file_sha == EXPECTED_IIP0044_SIDE_CONTRACT_FILE_SHA256,
        f"IIP-0044 side-contract file SHA-256 mismatch (fail-closed): {actual_sc_file_sha} != {EXPECTED_IIP0044_SIDE_CONTRACT_FILE_SHA256}",
    )
    side_contract = load_strict_json(side_contract_path)
    summary = load_strict_json(summary_path)
    dt_obj = load_strict_json(dt_path)
    require_cond(
        "foundry_v1_3_cleanroom_biologics_registration_iip_0044" in dt_obj,
        f"Missing DEC-123 append-only block in {dt_path.name}",
    )
    dec123_entry = dt_obj["foundry_v1_3_cleanroom_biologics_registration_iip_0044"]
    dec123_canonical = json.dumps(dec123_entry, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
    require_cond(protocol_path.is_file(), f"Missing companion protocol doc: {protocol_path.name}")
    protocol_text = protocol_path.read_text(encoding="utf-8")
    require_cond("IIP-0044" in protocol_text and "DEC-123" in protocol_text, "Companion protocol missing IIP-0044/DEC-123 headers")

    # Dynamic side-contract-bound Islet-GUARD eligibility verification & Gate 30-SHIELD-SPR fail-first self-tests
    guard_arm_tests = run_islet_guard_arm_restriction_tests(side_contract=side_contract)
    shield_spr_tests = run_gate30_shield_spr_decision_table_self_tests()
    audit_parity = verify_stage0_tier1_audit_parity(summary, side_contract, dt_obj, protocol_text)

    # Cross-verify sequence-derived unmodified average molecular weights directly against side_contract (R15 0039-M1!)
    sc_shield_c1 = side_contract["programs_registered"]["Islet_SHIELD"]["component_1"]
    sc_shield_c2 = side_contract["programs_registered"]["Islet_SHIELD"]["component_2"]
    qf09_mw = leads_check["sequences"]["IsletSHIELD_QF09_pI2"]
    t006_mw = leads_check["sequences"]["IsletSHIELD_Comp2_T006"]
    require_cond(
        abs(float(sc_shield_c1["unmodified_average_mw_kda_exact"]) - qf09_mw["unmodified_average_mw_kda"]) <= 1e-6
        and abs(float(sc_shield_c1["mw_kda"]) - qf09_mw["unmodified_average_mw_kda_2dp"]) <= 1e-6,
        f"IsletSHIELD_QF09_pI2 side_contract MW mismatch vs sequence-derived elemental mass: "
        f"sc=({sc_shield_c1['unmodified_average_mw_kda_exact']}, {sc_shield_c1['mw_kda']}) vs "
        f"derived=({qf09_mw['unmodified_average_mw_kda']}, {qf09_mw['unmodified_average_mw_kda_2dp']})",
    )
    require_cond(
        abs(float(sc_shield_c2["unmodified_average_mw_kda_exact"]) - t006_mw["unmodified_average_mw_kda"]) <= 1e-6
        and abs(float(sc_shield_c2["mw_kda"]) - t006_mw["unmodified_average_mw_kda_2dp"]) <= 1e-6,
        f"IsletSHIELD_Comp2_T006 side_contract MW mismatch vs sequence-derived elemental mass: "
        f"sc=({sc_shield_c2['unmodified_average_mw_kda_exact']}, {sc_shield_c2['mw_kda']}) vs "
        f"derived=({t006_mw['unmodified_average_mw_kda']}, {t006_mw['unmodified_average_mw_kda_2dp']})",
    )
    # Cross-verify the 2 locally deposited FASTA byte sizes & digests against the embedded 71-file manifest
    t1_map = {e["relpath"]: e for e in summary["source_cleanroom_bundle"]["tier1_source_manifest_71_files"]}
    require_cond(
        t1_map["fasta/openislet_cleanroom_v1_3_all_leads.fasta"]["bytes"] == leads_check["bytes"]
        and t1_map["fasta/openislet_cleanroom_v1_3_all_leads.fasta"]["sha256"] == leads_check["sha256"],
        "Deposited all_leads FASTA bytes/SHA-256 mismatch vs embedded 71-file manifest",
    )
    require_cond(
        t1_map["fasta/IsletSHIELD_Comp2_comparators.fasta"]["bytes"] == comp2_check["bytes"]
        and t1_map["fasta/IsletSHIELD_Comp2_comparators.fasta"]["sha256"] == comp2_check["sha256"],
        "Deposited comp2_comparators FASTA bytes/SHA-256 mismatch vs embedded 71-file manifest",
    )

    # Pin SHA-256 digests of every checked non-FASTA input in the receipt (B6!)
    checked_inputs_sha256: dict[str, dict[str, Any]] = {
        "verifier_script": {"filename": SCRIPT_PATH.name, "sha256": sha256_file(SCRIPT_PATH), "bytes": SCRIPT_PATH.stat().st_size},
        "side_contract": {"filename": side_contract_path.name, "sha256": sha256_file(side_contract_path), "bytes": side_contract_path.stat().st_size},
        "tier1_summary": {"filename": summary_path.name, "sha256": sha256_file(summary_path), "bytes": summary_path.stat().st_size},
        "protocol_doc": {"filename": protocol_path.name, "sha256": sha256_file(protocol_path), "bytes": protocol_path.stat().st_size},
        "dec123_canonical_json": {"key": "foundry_v1_3_cleanroom_biologics_registration_iip_0044", "sha256": sha256_bytes(dec123_canonical.encode("utf-8")), "bytes": len(dec123_canonical.encode("utf-8"))},
    }

    # 3. Gate 30-TOS-QUARANTINE & public hygiene scan across ALL IIP-0044 files, DEC-123, tests, and aligned IIP-0042 files (B5!)
    hygiene_results: dict[str, dict[str, int]] = {}

    def _scan_file(label: str, path: Path, *, is_summary: bool = False, is_md: bool = False) -> None:
        raw = path.read_text(encoding="utf-8")
        if is_summary:
            raw = strip_verified_tier2_exclusion_manifest(raw, label)
        elif is_md:
            raw = mask_canonical_layer2_disclaimer_only(raw)
        hygiene_results[label] = require_tos_quarantine_clean(raw, label)

    _scan_file(SCRIPT_PATH.name, SCRIPT_PATH)
    _scan_file(fasta_leads_path.name, fasta_leads_path)
    _scan_file(fasta_comp2_path.name, fasta_comp2_path)
    _scan_file(side_contract_path.name, side_contract_path)
    _scan_file(summary_path.name, summary_path, is_summary=True)
    _scan_file(protocol_path.name, protocol_path, is_md=True)
    # Scan DEC-123 in BOTH installed AND staging modes!
    hygiene_results["DEC-123::stage0_decision_tree_v1.json"] = require_tos_quarantine_clean(
        dec123_canonical, "DEC-123::stage0_decision_tree_v1.json"
    )
    if installed_check and test39_path is not None:
        require_cond(test39_path.is_file(), f"Missing IIP-0044 test suite in repo: {test39_path.name}")
        _scan_file(test39_path.name, test39_path)
        checked_inputs_sha256["iip0044_test_suite"] = {
            "filename": test39_path.name,
            "sha256": sha256_file(test39_path),
            "bytes": test39_path.stat().st_size,
        }

    if not installed_check:
        pmid_rec_p = SCRIPT_DIR / "iip0044_pmid_and_bundle_verification_receipt.json"
        if pmid_rec_p.is_file():
            _scan_file(pmid_rec_p.name, pmid_rec_p)
        for optional_p in (
            SCRIPT_DIR.parent / "BRIEF.md",
            SCRIPT_DIR.parent / "confirmation-carbon-2026-11-28.md",
            SCRIPT_DIR.parents[2] / "candidate-proposals" / "CAND-035-foundry-v1-3-cleanroom-biologics-iip0044-carbon.md",
        ):
            if optional_p.is_file():
                _scan_file(optional_p.name, optional_p, is_md=(optional_p.suffix == ".md"))

    # 4. Zero-LIMS-Touch invariance & INDEPENDENT IIP-0042 alignment audit (B2 + B5!)
    lims_invariance: dict[str, Any]
    iip0042_alignment: dict[str, Any]
    alignment_self_tests = run_iip0042_alignment_self_tests()

    if repo_root is not None:
        lims_invariance = verify_zero_lims_touch_invariance(repo_root)
        sc37_path = repo_root / "data" / "protocols" / "iip0042_portfolio_and_trackb_side_contract_v0.8.0.json"
        doc37_path = repo_root / "docs" / "GATE-30-PORTFOLIO-AND-TRACKB-CONTINGENCY-PROTOCOL.md"
        if not (sc37_path.is_file() and doc37_path.is_file()):
            raise FileNotFoundError("Missing IIP-0042 side contract or GATE-30 protocol in OpenIslet repo")
        # Include aligned IIP-0042 surfaces in Gate 30-TOS-QUARANTINE scan AND input SHA-256 pins!
        _scan_file(sc37_path.name, sc37_path)
        _scan_file(doc37_path.name, doc37_path, is_md=True)
        checked_inputs_sha256["iip0042_side_contract"] = {
            "filename": sc37_path.name,
            "sha256": sha256_file(sc37_path),
            "bytes": sc37_path.stat().st_size,
        }
        checked_inputs_sha256["iip0042_protocol_doc"] = {
            "filename": doc37_path.name,
            "sha256": sha256_file(doc37_path),
            "bytes": doc37_path.stat().st_size,
        }
        iip0042_eval = evaluate_iip0042_alignment(
            sc37_path.read_text(encoding="utf-8"),
            doc37_path.read_text(encoding="utf-8"),
        )
        if installed_check:
            require_cond(
                iip0042_eval["aligned"] is True,
                f"IIP-0042 independent alignment check FAILED in --installed-check mode; unresolved gaps: {iip0042_eval['gaps']}",
            )
            iip0042_alignment = {
                "mode": "INSTALLED_STRICT_INDEPENDENT_ENFORCED",
                "aligned": True,
                "independent_surface_enforcement": True,
                "checks": iip0042_eval["checks"],
                "gaps": [],
                "self_tests": alignment_self_tests,
            }
        else:
            iip0042_alignment = {
                "mode": "STAGING_PRE_S5_READONLY_AUDIT",
                "pre_s5_repo_currently_aligned": iip0042_eval["aligned"],
                "pre_s5_alignment_gaps_to_apply_at_s5": iip0042_eval["gaps"],
                "pre_s5_checks": iip0042_eval["checks"],
                "self_tests": alignment_self_tests,
            }
    else:
        lims_invariance = {
            "status": "SKIPPED_NO_REPO_ROOT_PROVIDED_IN_STAGING",
            "all_zero_lims_touch_invariants_passed": None,
        }
        iip0042_alignment = {
            "mode": "STAGING_SELF_TEST_ONLY_NO_REPO_ROOT",
            "self_tests": alignment_self_tests,
        }

    hygiene_neg_tests = run_tos_quarantine_negative_self_tests()

    receipt = {
        "schema_version": "iip0044_foundry_v1_3_biologics_verification_receipt_v0.8.2",
        "contribution_id": "IIP-0044",
        "decision_id": "DEC-123",
        "candidate_id": "CAND-035",
        "investigation_id": "EXP-032",
        "generated_date": GENERATED_DATE,
        "verification_mode": mode_label,
        "overall_status": "INSTALLED_CHECK_PASSED" if installed_check else "STAGING_VERIFICATION_PASSED",
        "live_odds_credit_pp": 0.0,
        "zero_wetlab_contract_import": True,
        "zero_assert_runtime": True,
        "portable_receipt_no_interpreter_version_coupling": True,
        "local_vs_upstream_verification_scope": {
            "locally_verified_in_public_snapshot": [
                "Deposited CC-BY-4.0 FASTAs on disk (12 sequences, exact byte sizes, exact SHA-256, motif/developability recomputation, sequence-derived IUPAC elemental average molecular weights [IsletSHIELD_QF09_pI2 6.76672 / 6.77 kDa; IsletSHIELD_Comp2_T006 6.49247 / 6.49 kDa] reconciled directly against side contract, UniProt P07204[363..480] M406L diff)",
                "Pinned IIP-0044 side-contract enforcement across all three validate_islet_guard_eligibility call modes (None -> frozen in-code policy; Path -> raw file SHA-256 + canonical JSON SHA-256 + policy parity; dict -> canonical JSON SHA-256 + policy parity), plus local JSON, companion protocol, DEC-123 canonical JSON, test suite, aligned IIP-0042 file digests, and 0-byte frozen LIMS & Playbook §4.1.20 invariance",
                "Internal consistency of embedded 71+5 manifest (strict positive integer byte sizes, valid SPDX labels, and deterministic 76-line SHA256SUMS.txt reconstruction aa3b25f4...)",
                "Locally recomputed verdicts from structured deposited measurements for 6/10 Comp1 gates (Protenix iPTM, peptide share, DQ2.5/DQ8-trans seed convergence, off-target ceiling, celiac threshold FAIL derived from disclosed cel_glutenin_L1=0.823 > 0.25 [5/6 full-panel pass count upstream-reported], 10 ns MD), 11/11 Comp2 gates (including 14 unique off-target peptides, OpenFold3 min/max shifts, model-specific heterodimer thresholds OpenFold3 <= 0.25 & Boltz-2 MIT <= 0.20, and 10 ns MD), and GUARD 10 ns MD RMSD verdict (5.487 A > 3.0 A; 0.94-1.02 A 1DX5 geometry and 0 Ca2+ setup upstream-reported), explicitly distinguishing the 4/10 Comp1 gates and GUARD bimodal audit tagged UPSTREAM_REPORTED_PROVENANCE_ONLY",
                f"Authoritative typed JSON bindings (18 active PMIDs, 4 typed role-enum PMID bindings [PMID:18252895, PMID:21912932, PMID:22315720, PMID:31556206], 6 wwPDB-to-primary-PMID bindings, 3 UniProtKB-to-gene/slice bindings, typed 3-way 1JK8/WT15/6DFX peptide-record bindings, and min_expression_batches=3) complemented by bounded deterministic prose regression checks across all 4 authored surfaces (DEC-123, IIP-0044 side contract, Tier-1 summary JSON, and FOUNDRY-V1-3 protocol) and aligned IIP-0042 surfaces for documented citation-role, bidirectional 1JK8 conflation, and <3 batch contradiction families (complementing, not replacing, human/blind text review); typed fail-first Gate 30-SHIELD-SPR adjudicator ({shield_spr_tests['total_cases']} self-tests synchronized identically across 77/77 shared AST symbols with verify_iip0042 on pre-adjudication WT15/HIP11/6DFX register-QC enforcing pairwise-distinct peptide reagent lot IDs across ALL mandatory peptide reagents [HIP11, WT15, 6DFX, plus optional 1JK8 whenever supplied] before dependent biological or batch credit and excluding register_qc_records from Comp1/Comp2 SPR assay batch counts [counting Comp1 SPR batches strictly from validated Comp1 on/off-target SPR rows], strict validation of optional non-null 1JK8 peptide_reagent_lot_id whenever supplied [keeping 1JK8 omitted or JSON null optional], hip11_peptide_reagent_lot_id & Comp1/Comp2 parent-batch coverage, cross-allele WT15 off-target reagent-lot reconciliation, mandatory per-comparator WT15 + 6DFX register-control screens requiring a non-empty shared comparator expression-batch intersection evaluated across BOTH WT15 and 6DFX with construct-bound batches and unique evidence IDs before granting complete-comparator credit or Track-B candidacy [optional physical 14-aa 1JK8 omitted or JSON null], and pre-adjudication physicochemical SEC-MALS/DLS material qualification [component-level SEC-MALS/DLS lot qualification for single-component Comp1/Comp2 SPR rows plus per-mixture physical co-formulation qualification via qualified_coformulation_mixtures binding each unique mixture_id to its exact (comp1_expression_batch_id, comp2_expression_batch_id) pair, per-mixture monomer_pct >= 95.0% / dls_pdi <= 0.15 / no_aggregates_or_precipitation=True, and laboratory-attested 1:1 molar ratio metadata — donor material is matched to physical lot pair while 1:1 molar ratio remains a laboratory attestation when optional ratio fields are omitted] requiring single-component SPR rows to use qualified component expression lots AND every rostered donor cocktail row's exact cocktail_mixture_id and component lot pair to match a passing physical mixture before fail-first arbitration [excluding crossed, unlisted, omitted, disjoint, or off-spec rows from biological FAIL, batch-linkage credit, and Track-B candidacy while preserving donor dependency topology, fixed N_roster, and independent qualified SPR FAIL], mandatory closed-schema cryptographically SHA-256-pinned outcome-blind preregistered_donor_family_roster committing donor membership, fixed per-donor cytotoxicity sample size N [predeclared_per_donor_unit_count_n or exact per-donor map predeclared_per_donor_unit_counts], and single-look fixed horizon [planned_analysis_looks == 1, single_look_fixed_horizon_plan_locked == True] inside roster_sha256 and reconciled 100% on ALL raw submitted + excluded donor IDs AND fixed-N unit counts across ALL raw submitted rostered donor rows BEFORE duplicate-donor exclusion [unified fail-first precedence with explicit failure_domain='INDEPENDENT_NON_DONOR_SPR' preserving independent valid qualified-material non-donor SPR FAIL while out-of-spec/missing physicochemical SEC-MALS/DLS measurements hold as unqualified material inputs with failure_domain=None and invalid, multi-look, or sample-size-mismatched rosters block overall PASS and donor-based FAIL; confirmatory cytotoxicity PASS and Track-B candidate eligibility requiring 100% measured rostered donors with 0 pre-assay exclusions; exact Boole FWER <= 0.05 scoped strictly to the fixed-roster, fixed-N, single-look donor cytotoxicity family conditional on external outcome-blind custody of the full analysis plan before readouts], machine-checked trackb_shield_trigger_state distinguishing complete zero-hold full-roster SHIELD-1-only Comp2 failure vs overall SHIELD failure while excluding all non-FAIL/held/incomplete/pre-assay-excluded/partial-FAIL states, retained donor batch/run Union-Find dependency topology independent of unrelated per-donor CI/summary errors, cluster-conservative distribution-free exact Clopper-Pearson responder-proportion suppression inference across donor/expression-batch/assay-run/joint connected-component clusters [narrowed strictly to sampling_design_class=='SIMPLE_RANDOM_OR_CONSECUTIVE_INDEPENDENT_T1D_COHORT' paired 1:1 with class-specific between_donor_independence_justification tokens, rejecting contradictory class-vs-justification declarations as invalid HOLD in both directions and routing matching STRATIFIED_INDEPENDENT_T1D_HLA_DQ_COHORT to non-authorizing HOLD with STRATIFIED_COHORT_REQUIRES_TARGET_WEIGHTED_SUPPRESSION_ESTIMATOR while preserving independent SPR FAIL and fixed-roster Bonferroni cytotoxicity FAIL; >= 9 disjoint batch/run clusters for confirmatory PASS, mandatory closed-schema donor_sampling_and_independence_design + per-donor assay_run_id, suppression assay acceptance range [-1000.0, 100.0]%, anti-enhancement min >= 0.0%, L95_CP(k_lt_40) > 60.0% FAIL, descriptive-only responder U95 without marginal upper-coverage guarantee, signed non-inverted overflow-immune Student-t non-authorizing diagnostic], mandatory closed-schema 1:1 canonical allowlisted gy018_independence_justification rejecting free-text prose and extra keys, two-pass order-independent canonical key uniqueness across all evidence lists, WT15 peptide_sequence + peptide_reagent_lot_id linkage across both on-target and cross-allele off-target rows, row-level SPR validity/registration gating excluding invalid/unregistered/conflicted rows from bio FAIL, Comp1+Comp2 off-targets, construct-bound expression_batch_ids provenance rejecting empty construct_ids and requiring >=3 distinct Comp1 & >=3 distinct Comp2 linked batches, quantitative SEC-MALS >= 95.0% / PDI <= 0.15, optional physical 14-aa 1JK8 omitted or JSON null, mandatory typed T1D donor eligibility [t1d_diagnosis_confirmed=True, donor_clinical_cohort='T1D', non-empty unpadded t1d_prequalification_ref, rejecting contradictory non-T1D donor tokens], qualifying donor HLA allowlist, exact GY-018 design_effect_deff == 1.0 [zero tolerance preserved as exact Decimal through load_strict_json_text] with invalid/ineligible donors gated out of confidence bounds, fixed-roster Bonferroni FWER <= 0.05 cytotoxicity FAIL rule under H0_all: max_i p_i <= 5.0% at alpha_donor = 0.05 / N_roster [cohort Student-t lower bound non-authorizing diagnostic only], two-sided CI validation, and exact raw JSON decimal |d| > 10^300 / Python binary64 >1e300 ValueError), independent full-clause IIP-0042 JSON/Markdown alignment checker ({alignment_self_tests['total_cases']} self-tests), raw-byte --check receipt verification rejecting LF-to-CRLF mutation, and targeted {len(hygiene_results)}-surface Foundry/aligned-IIP-0042 Gate 30-TOS-QUARANTINE hygiene scan (complete public manifest.json SHA-256, exact public disk membership, 17/17 pre-Wave-5 structure pins, and 23-file/4-DEC Wave-5 inventory authentication are assigned to scripts/verify_iip0042_master_multilayer_portfolio_crosswalk.py per GATE-30 Protocol §2.4)",
            ],
            "external_upstream_foundry_v1_3_not_reexecuted_locally": (
                "Raw upstream Foundry v1.3 .cif/.pdb/MD trajectory bytes, upstream byte counts and per-file license claims "
                "for the 69 non-deposited files, upstream model runs/settings, metric derivation from raw structures, "
                "Comp1's full 6-peptide celiac panel underlying the reported 5/6 passing count, GUARD's reported 0.94-1.02 A "
                "1DX5 EGF5 reference geometry and 0 Ca2+ MD setup outside the locally recomputed 5.487 A > 3.0 A RMSD verdict, "
                "verdicts tagged UPSTREAM_REPORTED_PROVENANCE_ONLY (4/10 Comp1 gates and GUARD bimodal docking), "
                "and upstream absence of hosted inputs are declared external provenance outside the public OpenIslet snapshot."
            ),
        },
        "checked_inputs_sha256": checked_inputs_sha256,
        "fasta_verification": {
            "all_leads": leads_check,
            "comp2_comparators": comp2_check,
            "total_sequences_verified": leads_check["sequence_count"] + comp2_check["sequence_count"],
            "sequence_derived_shield_lead_masses_kda": {
                "method": "IUPAC_STANDARD_ELEMENTAL_AVERAGE_ATOMIC_WEIGHTS_PLUS_H2O_TERMINI",
                "IsletSHIELD_QF09_pI2": {
                    "unmodified_average_mw_da": qf09_mw["unmodified_average_mw_da"],
                    "unmodified_average_mw_kda": qf09_mw["unmodified_average_mw_kda"],
                    "unmodified_average_mw_kda_2dp": qf09_mw["unmodified_average_mw_kda_2dp"],
                },
                "IsletSHIELD_Comp2_T006": {
                    "unmodified_average_mw_da": t006_mw["unmodified_average_mw_da"],
                    "unmodified_average_mw_kda": t006_mw["unmodified_average_mw_kda"],
                    "unmodified_average_mw_kda_2dp": t006_mw["unmodified_average_mw_kda_2dp"],
                },
                "matches_side_contract_masses": True,
            },
        },
        "uniprot_p07204_m406l_verification": thbd_check,
        "islet_guard_route1_arm_restriction_tests": guard_arm_tests,
        "gate30_shield_spr_decision_table_self_tests": shield_spr_tests,
        "stage0_tier1_audit_parity": audit_parity,
        "zero_lims_touch_invariance": lims_invariance,
        "gate_30_tos_quarantine_hygiene": {
            "scan_scope": (
                "TARGETED_10_SURFACE_FOUNDRY_AND_ALIGNED_IIP0042_SCAN_ONLY"
                if installed_check
                else "TARGETED_STAGING_FOUNDRY_SURFACES_SCAN_ONLY"
            ),
            "full_public_manifest_and_disk_inventory_verified_here": False,
            "full_inventory_gate30_entry_point": (
                "scripts/verify_iip0042_master_multilayer_portfolio_crosswalk.py::verify_gate30_tos_quarantine_full_inventory"
            ),
            "scanned_files_count": len(hygiene_results),
            "all_scanned_files_clean": True,
            "file_hit_counts": hygiene_results,
            "negative_self_tests": hygiene_neg_tests,
        },
        "iip0042_alignment_audit": iip0042_alignment,
    }
    return receipt


def build_cli_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description="IIP-0044 / DEC-123 OpenIslet Foundry v1.3 Clean-Room Biologics Standalone Verifier"
    )
    parser.add_argument(
        "--repo-root",
        type=Path,
        default=None,
        help="Path to read-only OpenIslet repository root (fail-closed if invalid).",
    )
    parser.add_argument(
        "--output",
        type=Path,
        default=None,
        help="Output .json receipt file or directory path.",
    )
    parser.add_argument(
        "--check",
        action="store_true",
        help="Read-only verification mode: verifies existing receipt byte-for-byte without writing.",
    )
    parser.add_argument(
        "--installed-check",
        action="store_true",
        help="Strict installed OpenIslet mode: requires all IIP-0044 files and independent IIP-0042 alignment installed.",
    )
    return parser


def resolve_output_file(output_arg: Path | None, installed_check: bool, repo_root: Path | None) -> Path:
    if output_arg is not None:
        p = output_arg.expanduser().resolve()
        if p.suffix.lower() == ".json":
            return p
        return p / "iip0044_verification_receipt.json"
    if installed_check and repo_root is not None:
        return repo_root / "data" / "extracted" / "iip0044_foundry_v1_3_biologics_verification_v0.8.0.json"
    return SCRIPT_DIR / "iip0044_verification_receipt.json"


def main(argv: list[str] | None = None) -> None:
    args = build_cli_parser().parse_args(argv)
    repo_root = resolve_repo_root(args.repo_root, args.installed_check)
    receipt = run_verification(repo_root=repo_root, installed_check=args.installed_check)

    raw_json = json.dumps(receipt, indent=2, ensure_ascii=False, allow_nan=False) + "\n"
    require_tos_quarantine_clean(raw_json, "generated_receipt_json")
    expected_bytes = raw_json.encode("utf-8")

    out_file = resolve_output_file(args.output, args.installed_check, repo_root)
    if args.check:
        if not out_file.is_file():
            raise FileNotFoundError(f"--check failed (fail-closed): expected receipt missing: {out_file.name}")
        existing_bytes = out_file.read_bytes()
        require_cond(
            existing_bytes == expected_bytes,
            f"--check failed (fail-closed): raw byte mismatch for {out_file.name} "
            f"(existing={sha256_bytes(existing_bytes)}, fresh={sha256_bytes(expected_bytes)})",
        )
        print(
            f"PASS (--check byte-exact): mode={receipt['verification_mode']} "
            f"seqs={receipt['fasta_verification']['total_sequences_verified']}/12 "
            f"odds_credit={receipt['live_odds_credit_pp']:+.2f}pp "
            f"hygiene_files={receipt['gate_30_tos_quarantine_hygiene']['scanned_files_count']} "
            f"sha256={sha256_bytes(existing_bytes)} (optimize={sys.flags.optimize})"
        )
        return

    if args.installed_check and args.output is None:
        print(
            f"PASS (--installed-check read-only): seqs={receipt['fasta_verification']['total_sequences_verified']}/12 "
            f"odds_credit={receipt['live_odds_credit_pp']:+.2f}pp "
            f"iip0042_aligned={receipt['iip0042_alignment_audit']['aligned']} "
            f"sha256={sha256_bytes(expected_bytes)} (optimize={sys.flags.optimize})"
        )
        return

    if not out_file.parent.exists():
        raise FileNotFoundError(f"Output parent directory does not exist (fail-closed): {out_file.parent.name}")
    out_file.write_bytes(expected_bytes)
    print(
        f"PASS: mode={receipt['verification_mode']} "
        f"seqs={receipt['fasta_verification']['total_sequences_verified']}/12 "
        f"odds_credit={receipt['live_odds_credit_pp']:+.2f}pp "
        f"hygiene_files={receipt['gate_30_tos_quarantine_hygiene']['scanned_files_count']} "
        f"wrote={out_file.name} sha256={sha256_file(out_file)} (optimize={sys.flags.optimize})"
    )


if __name__ == "__main__":
    main()
