#!/usr/bin/env python3
"""
IIP-0042 / DEC-121 (CAND-033 / EXP-030): Master Exact 2^20 Multi-Layer Portfolio
& OpenIslet Foundry Crosswalk Verifier (Stage S3-R3 Round-2 Surgical Closure).

Key S3-R2 Remediations:
  1. Fail-closed CLI parity:
     - `--standalone`: verifies exact 2^20 engine + live IIP-0035 parity (24/24
       scalars exact at shipped 4-dp display precision + unrounded L0 parity
       <= 5e-9 + 4,096-state incumbent law <= 1e-12) without emitting misleading
       verified=False / passed=False cross-track flags.
     - `--cross-track-dir` (or default non-standalone mode): REQUIRES both
       EXP-028 and archived EXP-029 receipts to exist, be non-empty, and pass
       parity <= 1e-12 with positive verified=True, passed=True flags; fails
       closed (non-zero exit) otherwise.
     - Logs sys.version and cross-interpreter numeric tolerance policy (<= 1e-12).
  2. Strict live-eligibility masking of unregistered ROUTE_3B_ACTIVE_IEOG (R3B):
     - Headlines the live-eligible Strict series (no blocked R3B).
     - Masks unregistered R3B in strict live-eligible totals (W_U3 = 57.5945%,
       W_U4 = 56.8730%), segregating parked EXP-029 R3B rows strictly into a
       labeled parked counterfactual sensitivity section.
  3. Locked Policy Option 1 eligibility math & P(XREACT pass) sensitivity:
     - Track-B reset (Day-1 active 0.5 mg/kg MELD-ATG + Day-2 placebo; n=35
       assigned, n=34 safety, 8/34 CRS, 11/34 serum sickness; Design A
       unconditionally excluded from Track-B ATG/lymphodepleting induction)
       is NEVER credited inside the ineligible full-SHIELD
       cocktail branch (yielding +2.5372 pp gross / +0.9986 pp AE-adjusted on
       the legacy comparator at P(XREACT pass)=1.0, plus strict zero-R3B EV),
       swept across P(XREACT pass) in {0.25, 0.50, 0.75, 1.00}.
  4. Legal 0.003 checkerboard mass-transfer stress test:
     - Proves explicitly in code that a legal 0.003 checkerboard coupling
       preserving every hurdle marginal and the full 4,096-state incumbent law
       flips L4-AE slightly negative (-0.0569 pp vs L3B).
  5. Honest Stage-0 Foundry sensitivity block:
     - Reflects v1.2 computational reality (qualitative hosted Tier-2 non-binding
       and ITGA2 paralog inversion flags; zero hosted Tier-2 numerics copied):
       low Stage-0 base-rate priors (p_S1 in {0.03, 0.05, 0.10}), 0 credit for
       Islet-SORT / Islet-GUARD until wet lab, 50% delivery-feasibility /
       PK-clearance discount on 6.77/6.49 kDa miniproteins, reporting honest
       unconditional EV (+0.5 to +2 pp today) while holding live public odds
       strictly at +0.00 pp.
  6. Automated public-prose & Gate 30-TOS-QUARANTINE leak scan:
     - Enforces 0 personal home paths, 0 currency figures, 0 vendor/model
       identifiers, and 0 hosted Tier-2 numeric outputs.

Strictly READ-ONLY with respect to OpenIslet and OpenIslet-Website.
Run with:
  PYTHONDONTWRITEBYTECODE=1 python3 -B scripts/verify_iip0042_master_multilayer_portfolio_crosswalk.py --standalone --repo-root . --out /tmp/iip0042_standalone_check.json
  PYTHONDONTWRITEBYTECODE=1 python3 -B scripts/verify_iip0042_master_multilayer_portfolio_crosswalk.py --cross-track-dir <idea-exploration-dir> --repo-root . --out /tmp/iip0042_crosstrack_check.json
"""
from __future__ import annotations

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

import numpy as np

sys.dont_write_bytecode = True

ART_DIR = Path(__file__).resolve().parent
EXP_ROOT = ART_DIR.parents[1]  # idea-exploration/
INV_ROOT = ART_DIR.parents[2]  # OpenIslet-Investigations/
RECEIPT_PATH = (
    ART_DIR.parent / "data" / "extracted" / "iip0042_master_multilayer_portfolio_crosswalk_v0.8.0.json"
    if ART_DIR.name == "scripts"
    else ART_DIR / "exp030_verification_receipt.json"
)
GENERATED_DATE = "2026-11-28"

ARM_NAMES = ("A", "B", "X", "Y", "D")

# Canonical single-source-of-truth H3 Channel-(a) intervention scenario deltas
# (explicitly labeled as uncited modeling judgment scenarios, not measured exact-product values)
DC3_SHIELD1 = 0.015
DC3_SHIELD_COCKTAIL = 0.035
DC3_RESET_CENTRAL = 0.040
DC3_RESET_CONSERVATIVE = 0.030
DC3_RESET_AE_DOWNSIDE = 0.020

D_SHIELD1_ARMS = {"A": 0.025, "B": 0.025, "X": 0.025, "Y": 0.020, "D": 0.025}
D_SHIELD_COCKTAIL_ARMS_BASE = {"A": 0.055, "B": 0.055, "X": 0.055, "Y": 0.040, "D": 0.055}
D_SHIELD_COCKTAIL_ARMS_POST028 = {"A": 0.055, "B": 0.050, "X": 0.045, "Y": 0.040, "D": 0.055}

# Finite Reset arm deltas — IDENTICAL across L2C, L3A+Reset, SHIELD-Fail+Reset, and L4!
# Design A strictly 0.000 (unconditionally excluded from Track-B ATG/lymphodepleting induction).
D_RESET_ARMS_CENTRAL = {"A": 0.000, "B": 0.060, "X": 0.050, "Y": 0.040, "D": 0.060}
D_RESET_ARMS_CONSERVATIVE = {"A": 0.000, "B": 0.040, "X": 0.030, "Y": 0.020, "D": 0.040}
D_RESET_ARMS_AE_DOWNSIDE = {"A": 0.000, "B": 0.030, "X": 0.020, "Y": 0.020, "D": 0.030}
H4_AE_STEROID_HAIRCUT_NON_A = -0.015  # -1.5 pp H4 drag on {B, X, Y, D} from CRS/SS/steroid-rescue toxicity

# Islet-GUARD (THBD M406L) strictly restricted to R1 CaO2 peroxide arms (A, X) ONLY (enforced in code!)
# Set to 0.000 in Honest Stage-0 Zero-SORT/Zero-GUARD headline sensitivity until wet-lab data exist.
D_GUARD_H3_ARMS = {"A": 0.005, "B": 0.000, "X": 0.005, "Y": 0.000, "D": 0.000}
D_GUARD_H4_ARMS = {"A": 0.010, "B": 0.000, "X": 0.010, "Y": 0.000, "D": 0.000}

# Islet-SORT (CD49a/ITGA1 enrichment) — held at 0.000 in Honest Stage-0 headline sensitivity until wet lab!
D_SORT_H1_D = 0.040
D_SORT_H4_ALL = 0.015

# Delivery-feasibility / PK-clearance discount for 6.77/6.49 kDa miniproteins (conditional on route/formulation/dosing)
MINIPROTEIN_PK_DISCOUNT_FACTOR = 0.50

# Canonical pinned SHA-256 of frozen live IIP-0035 5-arm portfolio fixture (enforced BY DEFAULT in --standalone!)
CANONICAL_SHIPPED_IIP0035_SHA256 = "31320c0e6ac039773c2ca58160f064e8655d1a58b97050a713dfbf00d283ff99"

# Pinned 17-file pre-Wave-5 authorized coordinate structure inventory under data/structures/
# pinned by EXACT SHA-256 digest (RCSB PDB CC0 1.0 + pre-existing AFDB v6 reference structures;
# ZERO Foundry/Tier-2 coordinates in OpenIslet; rejects modified/spoofed files at these paths!)
AUTHORIZED_PRE_WAVE5_PUBLIC_COORDINATE_SHA256: dict[str, str] = {
    "data/structures/1EFX.pdb": "4e432fe894cc6b0390bab6071598f2f95249d5b6f0c4e5a9365c1ca110660fba",
    "data/structures/1IM9.pdb": "4c21ebf9e5ba064ab65569079cb8d10a73b718bdc8c4cd1c298bec7a8e4f0013",
    "data/structures/2WII.pdb": "93dc715a38124883028aea79a1e3a2715c1d82bed06f59e7889e9971f41543eb",
    "data/structures/5O32.pdb": "26b9d9684e7b3fa1757f91a173c8423d583ca6df88eb11d1fa2ecdc059a803d3",
    "data/structures/AF-P10144-F1-model_v6.cif": "6362a677cc62d80b89229ea40a4c3ae81007a631d1c038a2e158541c8d40e9a5",
    "data/structures/AF-P50453-F1-model_v6.cif": "d0b27f7cc8317acd9cd59b76d3080b4019ffd38930dbfddf3bd2560814baf5b9",
    "data/structures/pdb_00001bl4.cif": "ce142b747272c5fd3b7c0b5f5157750277614700bc32492f0eb7cb43056914d5",
    "data/structures/pdb_00001iau.cif": "c1ffdeab80cc9ecaf06c9901c756b0f59259e178a45a4a33ffc949bd01123161",
    "data/structures/pdb_00001jxq.cif": "4b7355537a8a81e90d5397cba398ff425dddc904a7748e3a25a0a9f57d1ff772",
    "data/structures/pdb_00001mhe.cif": "4f1bc39231d6ffb288cf85bb9322d264ceac92d6d427f755339a648e49d6227a",
    "data/structures/pdb_00001nw9.cif": "89edc3aa4833b22c9604872d163e64d53755af6de1c9163204f2244ac1ce5da4",
    "data/structures/pdb_00002jjs.cif": "84672a253e9c982dac16136cb76ae706eeafa2aa390cfdb2355ad68592cac10e",
    "data/structures/pdb_00003bze.cif": "839b87df50ced664fa5c516d0836667176b64895677c87de737b3a6615fc802c",
    "data/structures/pdb_00003cdg.cif": "36f9a9d45f9a3b7dbbf2d74e4c4d25e3edc66f5e02cafafac6acf5d6130b450a",
    "data/structures/pdb_00004cmm.cif": "13147521df35289b21488439170079c86286f58cdafe17544367ccf053d1f5fe",
    "data/structures/pdb_00004kjy.cif": "6294d015c1c24d97558650dc98ef8bced967b3fd658da8b49dc51090e8b2ccaa",
    "data/structures/pdb_00004zqk.cif": "ed7114a3c653cf964155c5491a5df30d5c5e4edfc6b09d399662c5764a1bad31",
}
AUTHORIZED_PRE_WAVE5_PUBLIC_COORDINATE_FILES = frozenset(AUTHORIZED_PRE_WAVE5_PUBLIC_COORDINATE_SHA256.keys())

# Exact 5 excluded Foundry v1.2 Tier-2 filenames permitted ONLY inside the schema-verified
# metadata-only carve-out table of iip0044_tier1_metrics_cleanroom_summary_v0.8.0.json
_T2_TAG = "".join(("bo", "ltz", "21"))
EXPECTED_IIP0044_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",
})
_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)\b)"
)

# Automated Gate 30-TOS-QUARANTINE & public hygiene leak regexes (constructed via split fragments)
_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_]+")
_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"),
    )
)
_COMMERCIAL_AI_VENDOR_TOKENS = tuple(
    "".join(parts)
    for parts in (
        ("cl", "aude"),
        ("anthro", "pic"),
        ("open", "ai"),
        ("chat", "gpt"),
        ("gpt-", "4"),
        ("gpt-", "5"),
        ("ge", "mini"),
        ("deep", "mind"),
        ("gr", "ok"),
        ("x", "ai"),
        ("son", "net"),
        ("op", "us"),
        ("co", "dex"),
    )
)
_TIER2_HOSTED_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"),
    )
)
# Exact single canonical Layer-2 quarantine disclaimer sentence from scripts/render_documentation.py
# (narrowly masked ONLY inside the rendered Layer-scope footer block — NEVER stripping arbitrary footer text!)
_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."
)

# Canonical Locked Policy Option 1 eligibility rule (must match side contract verbatim!)
CANONICAL_TRACKB_ELIGIBILITY_RULE = (
    "Under Locked Policy Option 1, Design A excludes ATG/lymphodepleting induction unconditionally "
    "(Track A targets zero chronic systemic recipient immunosuppression; rescue fail-safe prodrug AP1903 "
    "and any future investigational Islet-SHIELD protein exposure are explained individually to patients); "
    "optional Track-B reset (Day-1 active 0.5 mg/kg IV rabbit ATG + Day-2 IV placebo) "
    "is eligible ONLY if Gate 30-ATG-XREACT passes FIRST (ordered BEFORE Gate 30-SHIELD-SPR) "
    "AND Gate 30-SHIELD-SPR emits a complete zero-hold FAIL with machine-checked "
    "derived_summary.trackb_shield_trigger_state in "
    "{ELIGIBLE_CANDIDATE_SHIELD1_ONLY_COMP2_FAIL_PENDING_XREACT_AND_OWNER_REAUTH, "
    "ELIGIBLE_CANDIDATE_OVERALL_SHIELD_FAIL_PENDING_XREACT_AND_OWNER_REAUTH} "
    "(all non-FAIL, held, invalid, and partial-FAIL-with-HOLD states emit "
    "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE and remain ineligible) "
    "AND explicit owner re-authorization (adjudicator chain: "
    "GATE30_SHIELD_SPR_SOFTWARE_PLUS_GATE30_ATG_XREACT_PASS_PLUS_OWNER_REAUTHORIZATION). "
    "Full-cocktail branch carries strictly 0.0000 pp Track-B credit."
)

_RE_SHA256_HEX = re.compile(r"^[0-9a-f]{64}$")

# Exact two-sided 95% Student-t critical values (alpha = 0.05) for df = 1..30
_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 _student_t_95_critical(df: int) -> float:
    if df < 1:
        raise ValueError(f"Degrees of freedom must be >= 1, got {df}")
    if df in _STUDENT_T_95_TWO_SIDED:
        return _STUDENT_T_95_TWO_SIDED[df]
    # Cornish-Fisher expansion accurate to < 1e-6 for df > 30
    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))


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


def _reject_nonfinite_json_constant(token: str) -> Any:
    raise ValueError(f"Non-finite JSON constant rejected: {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_json_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 load_strict_json_text(raw_text: str, label: str) -> Any:
    """Strict fail-closed JSON parser rejecting duplicate keys, NaN/Inf constants, and overflowing numbers,
    while preserving exact Decimal precision on design_effect_deff for zero-tolerance GY-018 equality checks.
    """
    data = json.loads(
        raw_text,
        object_pairs_hook=_reject_duplicate_json_keys,
        parse_constant=_reject_nonfinite_json_constant,
        parse_float=_parse_strict_finite_float,
        parse_int=_parse_strict_finite_int,
    )
    data = _coerce_non_dict_decimals_to_float(data)
    assert_strictly_finite_json(data, label)
    return data


def assert_strictly_finite_json(obj: Any, label: str, path: str = "$") -> None:
    """Fail-closed recursive guard rejecting NaN/Inf or abs(x) > 10^300 (int, float, or Decimal) anywhere in loaded JSON fixtures."""
    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 numeric value in {label} at {path}: {obj!r}")
        return
    if isinstance(obj, dict):
        for k, v in obj.items():
            assert_strictly_finite_json(v, label, f"{path}.{k}")
        return
    if isinstance(obj, (list, tuple)):
        for idx, v in enumerate(obj):
            assert_strictly_finite_json(v, label, f"{path}[{idx}]")
        return


def require_finite_number(val: Any, label: str) -> float:
    """Reject booleans, None, non-numbers, NaN, Inf, and abs(x) > 10^300 (int or float) before any arithmetic comparison."""
    if isinstance(val, bool) or not isinstance(val, (int, float)):
        raise ValueError(f"Non-finite or non-numeric scalar for {label}: {val!r}")
    if isinstance(val, int) and abs(val) > 10 ** 300:
        raise ValueError(f"Overflowing integer scalar for {label}")
    fval = float(val)
    if not math.isfinite(fval) or abs(fval) > 1e300:
        raise ValueError(f"Non-finite or overflowing numeric scalar for {label}: {val!r}")
    return fval


def load_verified_json_fixture(
    path: Path,
    label: str,
    *,
    expected_sha256: str | None = None,
) -> tuple[dict[str, Any], str, int]:
    """
    Fail-closed fixture loader:
      1. Requires file to exist and be non-empty.
      2. Computes SHA-256 over the exact loaded bytes BEFORE parsing or parity comparison.
      3. Validates pinned SHA-256 BEFORE parity pass.
      4. Rejects duplicate JSON keys, non-finite JSON constants (NaN/Infinity/-Infinity),
         and overflowing float/int tokens DURING decoding, then recursively validates finiteness.
    """
    if not path.is_file():
        raise FileNotFoundError(f"Missing required fixture for {label}: {path.name}")
    raw_bytes = path.read_bytes()
    if not raw_bytes:
        raise ValueError(f"Empty fixture file for {label}: {path.name}")
    digest = hashlib.sha256(raw_bytes).hexdigest()
    if expected_sha256 is not None:
        exp_norm = expected_sha256.strip().lower()
        if not _RE_SHA256_HEX.match(exp_norm):
            raise ValueError(f"Invalid expected SHA-256 digest format for {label}: {expected_sha256!r}")
        if digest != exp_norm:
            raise RuntimeError(
                f"Pinned SHA-256 mismatch for {label} ({path.name}): got {digest}, expected {exp_norm}"
            )
    data = load_strict_json_text(raw_bytes.decode("utf-8"), label)
    if not isinstance(data, dict) or not data:
        raise ValueError(f"Fixture {label} ({path.name}) must decode to a non-empty JSON object")
    return data, digest, len(raw_bytes)


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 so any injected leak inside the footer still fails closed.
    """
    def _replace_footer(match: re.Match[str]) -> str:
        body = match.group(0)
        return body.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_iip0044_tier2_exclusion_manifest(json_text: str, label: str) -> str:
    """Strictly validate EVERY field type, scalar value, and schema constraint of the metadata-only
    5-file Tier-2 carve-out list inside 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)
    if not isinstance(obj, dict):
        raise ValueError(f"{label} must be 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"]
        if not isinstance(carveouts, list) or len(carveouts) != 5:
            raise RuntimeError(f"Invalid excluded_tier2_carveout_files_5 length in {label}")
        seen_paths: set[str] = set()
        for item in carveouts:
            if not isinstance(item, dict) or set(item.keys()) != _ALLOWED_CARVEOUT_ITEM_KEYS:
                raise RuntimeError(f"Unauthorized keys in excluded_tier2_carveout_files_5 entry in {label}")
            rp = item["relpath"]
            if type(rp) is not str or rp not in EXPECTED_IIP0044_TIER2_CARVEOUT_RELPATHS or rp in seen_paths:
                raise RuntimeError(f"Unexpected or duplicate Tier-2 carveout relpath in {label}: {rp!r}")
            seen_paths.add(rp)
            sh = item["sha256"]
            if type(sh) is not str or not _RE_SHA256_HEX.match(sh):
                raise RuntimeError(f"Invalid lowercase 64-hex sha256 in Tier-2 carveout entry {rp}")
            bsize = item["bytes"]
            if type(bsize) is not int or bsize <= 0:
                raise RuntimeError(f"Tier-2 carveout entry {rp} must declare positive integer bytes, got {bsize!r}")
            tier_val = item["tier"]
            if type(tier_val) is not str or tier_val != _EXPECTED_CARVEOUT_TIER:
                raise RuntimeError(f"Invalid tier metadata in Tier-2 carveout entry {rp}: {tier_val!r}")
            lic_val = item["license_terms"]
            if type(lic_val) is not str or lic_val != _EXPECTED_CARVEOUT_LICENSE_TERMS:
                raise RuntimeError(f"Invalid license_terms metadata in Tier-2 carveout entry {rp}: {lic_val!r}")
            if item["deposited_in_openislet"] is not False:
                raise RuntimeError(f"Tier-2 carveout entry {rp} must declare deposited_in_openislet=false")
            if type(item["numeric_outputs_included"]) is not int or item["numeric_outputs_included"] != 0:
                raise RuntimeError(f"Tier-2 carveout entry {rp} must declare integer numeric_outputs_included=0")
            rat = item["carveout_rationale"]
            if type(rat) is not str or not (1 <= len(rat) <= 240):
                raise RuntimeError(f"Tier-2 carveout rationale for {rp} must be a concise scalar string (<=240 chars)")
            rat_no_cc = rat.replace("CC-BY-4.0", "CC_BY_FOUR")
            if _RE_CARVEOUT_FORBIDDEN_SCORE.search(rat_no_cc) or re.search(r"\b\d+\.\d+\b", rat_no_cc):
                raise RuntimeError(f"Prohibited numeric score or metric keyword inside carveout rationale for {rp}: {rat!r}")
            # Validate all non-relpath fields carry ZERO Tier-2 markers, coordinates, home paths, or currency
            non_rp_str = json.dumps({k: v for k, v in item.items() if k != "relpath"}, ensure_ascii=False)
            sub_counts = scan_public_hygiene_text(
                non_rp_str, f"{label}::carveout_meta[{rp}]", check_vendor=False
            )
            if any(v > 0 for v in sub_counts.values()):
                raise RuntimeError(f"Gate 30-TOS-QUARANTINE violation inside carveout metadata {rp}: {sub_counts}")
        if seen_paths != EXPECTED_IIP0044_TIER2_CARVEOUT_RELPATHS:
            raise RuntimeError(f"Incomplete excluded_tier2_carveout_files_5 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 _scan_plain_text_segment(
    text: str,
    *,
    check_currency: bool,
    check_vendor: bool,
    vendor_token_set: tuple[str, ...],
    check_coords: bool,
    allow_authorized_coord_file: bool,
    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)) if check_currency else 0
    low = norm.lower()
    vendor_hits = (
        sum(
            len(re.findall(r"(?<![a-z0-9])" + re.escape(tok) + r"(?![a-z0-9])", low))
            for tok in vendor_token_set
        )
        if check_vendor
        else 0
    )
    tier2_hits = sum(low.count(tok.lower()) for tok in _TIER2_HOSTED_TOKENS)
    if not check_coords or allow_authorized_coord_file:
        coord_hits = 0
    else:
        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,
        "vendor_model_hits": vendor_hits,
        "tier2_hosted_numeric_hits": tier2_hits,
        "unauthorized_coordinate_row_hits": coord_hits,
    }


def scan_public_hygiene_text(
    text: str,
    label: str,
    *,
    check_currency: bool = True,
    check_vendor: bool = True,
    vendor_token_set: tuple[str, ...] = _VENDOR_TOKENS,
    check_coords: bool = True,
    allow_authorized_coord_file: bool = False,
) -> dict[str, int]:
    """Scan raw text AND (when valid JSON) every recursively decoded JSON string value against
    Gate 30-TOS-QUARANTINE classes without stripping arbitrary sections.
    """
    raw_counts = _scan_plain_text_segment(
        text,
        check_currency=check_currency,
        check_vendor=check_vendor,
        vendor_token_set=vendor_token_set,
        check_coords=check_coords,
        allow_authorized_coord_file=allow_authorized_coord_file,
        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 raw_counts}
            for s in _iter_decoded_json_strings(parsed):
                sc = _scan_plain_text_segment(
                    s,
                    check_currency=check_currency,
                    check_vendor=check_vendor,
                    vendor_token_set=vendor_token_set,
                    check_coords=check_coords,
                    allow_authorized_coord_file=allow_authorized_coord_file,
                    from_json_string=True,
                )
                for k, v in sc.items():
                    dec_totals[k] += v
            for k in raw_counts:
                if dec_totals[k] > raw_counts[k]:
                    raw_counts[k] = dec_totals[k]
    return raw_counts


def assert_public_hygiene_clean(
    text: str,
    label: str,
    *,
    check_currency: bool = True,
    check_vendor: bool = True,
    vendor_token_set: tuple[str, ...] = _VENDOR_TOKENS,
    check_coords: bool = True,
    allow_authorized_coord_file: bool = False,
) -> dict[str, int]:
    """Fail-closed Gate 30-TOS-QUARANTINE + public-prose hygiene scanner."""
    counts = scan_public_hygiene_text(
        text,
        label,
        check_currency=check_currency,
        check_vendor=check_vendor,
        vendor_token_set=vendor_token_set,
        check_coords=check_coords,
        allow_authorized_coord_file=allow_authorized_coord_file,
    )
    if any(v > 0 for v in counts.values()):
        raise RuntimeError(f"Gate 30-TOS-QUARANTINE / public hygiene violation in {label}: {counts}")
    return counts


def run_gate30_tos_quarantine_negative_self_tests() -> dict[str, Any]:
    """Built-in adversarial negative probes proving Gate 30-TOS-QUARANTINE catches every prohibited class,
    including coordinate rows hidden inside JSON strings and invalid carve-out metadata.
    """
    probes: list[tuple[str, str, str]] = [
        ("mac_home_path", "prefix " + _HOME_MAC + "alice/secret.txt", "home_path_hits"),
        ("linux_home_path", "prefix " + _HOME_LINUX + "bob/work/file.json", "home_path_hits"),
        ("win_home_path", "path C:\\" + "Users" + "\\carol\\notes.txt", "home_path_hits"),
        ("usd_dollar_amount", "cost $" + "250000 estimate", "currency_hits"),
        ("eur_symbol_amount", "cost \u20ac" + "1500 total", "currency_hits"),
        ("gbp_symbol_amount", "cost \u00a3" + "900 total", "currency_hits"),
        ("iso_eur_amount", "budget 4200 " + "EU" + "R planned", "currency_hits"),
        ("iso_gbp_amount", "budget GB" + "P 3100 planned", "currency_hits"),
        ("tier2_hosted_token", "copied " + _T2_TAG + "_s0.cif", "tier2_hosted_numeric_hits"),
        ("tier2_numeric_score", "score " + _TIER2_HOSTED_TOKENS[4], "tier2_hosted_numeric_hits"),
        ("pdb_atom_coordinate_row", "AT" + "OM      1  N   ALA A   1      11.104  13.207   2.100  1.00 20.00           N\n", "unauthorized_coordinate_row_hits"),
        ("mmcif_atom_site_row", "_atom" + "_site.group_PDB\n", "unauthorized_coordinate_row_hits"),
        (
            "json_string_pdb_coordinate_row",
            json.dumps({"note": "AT" + "OM      1  N   ALA A   1      11.104  13.207   2.100  1.00 20.00           N"}),
            "unauthorized_coordinate_row_hits",
        ),
        (
            "json_string_mmcif_coordinate_row",
            json.dumps({"note": "header\n_atom" + "_site.group_PDB"}),
            "unauthorized_coordinate_row_hits",
        ),
        ("vendor_model_token", "reviewed by " + _COMMERCIAL_AI_VENDOR_TOKENS[0], "vendor_model_hits"),
    ]
    results: dict[str, bool] = {}
    for pname, ptext, exp_key in probes:
        c = scan_public_hygiene_text(ptext, f"probe:{pname}")
        if c[exp_key] <= 0:
            raise RuntimeError(f"Gate 30-TOS-QUARANTINE self-probe {pname!r} failed to trigger {exp_key}: {c}")
        results[pname] = True
    # Positive URL control: public https://.../home/... URL MUST NOT false-trigger local home path
    url_ctrl = scan_public_hygiene_text("https://www.ncbi.nlm.nih.gov/home/about/policies/", "probe:url_control")
    if url_ctrl["home_path_hits"] != 0:
        raise RuntimeError(f"URL home-path control false-triggered: {url_ctrl}")
    # Narrow footer control: injecting a leak INSIDE the rendered footer block MUST still trigger!
    injected_footer = (
        "<!-- OPENISLET_CURRENT_LAYER_SCOPE -->\n"
        + _CANONICAL_LAYER2_QUARANTINE_SENTENCE
        + "\nInjected leak: "
        + _HOME_LINUX
        + "mallory/data \u20ac500\n"
        "<!-- OPENISLET_CURRENT_LAYER_SCOPE_END -->\n"
    )
    masked = mask_canonical_layer2_disclaimer_only(injected_footer)
    fc = scan_public_hygiene_text(masked, "probe:injected_footer")
    if fc["home_path_hits"] <= 0 or fc["currency_hits"] <= 0:
        raise RuntimeError(f"Narrow footer masking failed to catch injected footer leak: {fc}")
    # Carveout nested object / synthetic score probe MUST be rejected BEFORE masking!
    bad_carveout = {
        "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": {"nested_score": 0.91} if idx == 0 else "Excluded metadata only.",
                }
                for idx, rp in enumerate(sorted(EXPECTED_IIP0044_TIER2_CARVEOUT_RELPATHS))
            ]
        }
    }
    carveout_nested_rejected = False
    try:
        strip_verified_iip0044_tier2_exclusion_manifest(json.dumps(bad_carveout), "probe:nested_carveout")
    except RuntimeError:
        carveout_nested_rejected = True
    if not carveout_nested_rejected:
        raise RuntimeError("Carve-out schema validator failed to reject nested dict in carveout_rationale")
    return {
        "total_negative_probes": len(probes),
        "all_negative_probes_caught": True,
        "url_home_control_clean": True,
        "injected_footer_leak_caught": True,
        "carveout_nested_object_rejected": carveout_nested_rejected,
        "probes": results,
    }


def _extract_manifest_inventory_paths(container: Any, label: str) -> list[str]:
    """Parse BOTH list (list[str] or list[{path/relpath,...}]) and dict manifest inventory representations."""
    paths: list[str] = []
    if isinstance(container, dict):
        paths = [str(k) for k in container.keys()]
    elif isinstance(container, list):
        for idx, entry in enumerate(container):
            if isinstance(entry, str):
                p = entry.strip()
            elif isinstance(entry, dict):
                raw_p = entry.get("path") if "path" in entry else entry.get("relpath")
                if type(raw_p) is not str or not raw_p.strip():
                    raise RuntimeError(f"Invalid manifest entry at {label}[{idx}]: missing string path/relpath")
                p = raw_p.strip()
            else:
                raise RuntimeError(f"Unsupported manifest entry type at {label}[{idx}]: {type(entry).__name__}")
            if not p:
                raise RuntimeError(f"Empty path at {label}[{idx}]")
            paths.append(p)
    else:
        raise RuntimeError(f"Manifest {label} must be a list or dict, got {type(container).__name__}")
    if len(paths) != len(set(paths)):
        raise RuntimeError(f"Duplicate paths detected in manifest {label}")
    return sorted(paths)


WAVE5_STRICT_IIP0042_PUBLIC_FILES: tuple[str, ...] = (
    "data/protocols/iip0042_portfolio_and_trackb_side_contract_v0.8.0.json",
    "docs/GATE-30-PORTFOLIO-AND-TRACKB-CONTINGENCY-PROTOCOL.md",
    "scripts/verify_iip0042_master_multilayer_portfolio_crosswalk.py",
    "data/extracted/iip0042_master_multilayer_portfolio_crosswalk_v0.8.0.json",
)
WAVE5_STRICT_4CLASS_PUBLIC_FILES: tuple[str, ...] = (
    "data/constructs/islet1_abx_cd64t_il1rn_modeb_v0.8.0.fasta",
    "data/constructs/openislet_cleanroom_v1_3_all_leads.fasta",
    "data/constructs/islet_shield_comp2_comparators_v1_3.fasta",
    "data/protocols/iip0041_abx_cd64t_il1rn_side_contract_v0.8.0.json",
    "data/protocols/iip0044_foundry_v1_3_biologics_side_contract_v0.8.0.json",
    "data/extracted/iip0041_clinical_h1_cd64t_siglec_verification_v0.8.0.json",
    "data/extracted/iip0043_composite_release_evaluator_v0.8.0.json",
    "data/extracted/iip0043_wholegraft_gate0v_and_calibration_v0.8.0.json",
    "data/extracted/iip0044_tier1_metrics_cleanroom_summary_v0.8.0.json",
    "data/extracted/iip0044_foundry_v1_3_biologics_verification_v0.8.0.json",
    "docs/GATE-28-ABX-CD64T-IL1RN-AND-H1-PROTOCOL.md",
    "docs/GATE-0V-WHOLEGRAFT-PROTOCOL.md",
    "docs/FOUNDRY-V1-3-CLEANROOM-BIOLOGICS-PROTOCOL.md",
    "scripts/verify_iip0041_clinical_h1_cd64t_siglec.py",
    "scripts/verify_iip0043_wholegraft_gate0v_and_calibration.py",
    "scripts/evaluate_gate0v_composite_release.py",
    "scripts/verify_iip0044_foundry_v1_3_biologics.py",
    "tests/test_iip0041_iip0042_iip0043_wave5_suite.py",
    "tests/test_iip0044_foundry_v1_3_biologics.py",
)
WAVE5_REQUIRED_DECISION_TREE_BLOCKS: tuple[tuple[str, str], ...] = (
    ("clinical_h1_abx_cd64t_il1rn_siglec_iip_0041", "COMMERCIAL_AI"),
    ("master_2pow20_portfolio_and_option1_trackb_contingency_iip_0042", "STRICT_IIP0042"),
    ("wholegraft_gate0v_composite_and_nw08_calibration_iip_0043", "COMMERCIAL_AI"),
    ("foundry_v1_3_cleanroom_biologics_registration_iip_0044", "COMMERCIAL_AI"),
)


_PUBLIC_BUNDLE_MARKER_BYTES = b"openislet_public_bundle_v0.8.0\n"
_INVENTORY_TRUST_BOUNDARY_NOTE = (
    "Verifies every manifest-declared public artifact's exact SHA-256 digest and byte size against manifest.json, "
    "enforces zero unmanifested extra files across the public bundle root (or across all allowlisted public paths "
    "in a local checkout), and independently verifies the 17 hardcoded pre-Wave-5 structure SHA-256 pins and 23 "
    "declared Wave-5 public files plus 4 DEC blocks; cryptographic authentication of the root manifest.json file "
    "itself depends on external release verification rather than self-reference."
)


def verify_gate30_tos_quarantine_full_inventory(
    openislet_root: Path,
    *,
    extra_wave5_texts: dict[str, str] | None = None,
    require_manifest: bool = True,
) -> dict[str, Any]:
    """Execute fail-closed Gate 30-TOS-QUARANTINE enforcement aligned 1-to-1 with Protocol §2.4:
      1. Directly parses manifest.json (BOTH list and dict forms of public_export_file_inventory
         and artifacts; never falls back silently; fails closed if manifest or ANY manifest-declared
         public artifact is missing from disk), verifies EVERY manifest-listed public file's exact
         SHA-256 digest and byte count against manifest.json['artifacts'], verifies exact public
         disk membership confirming ZERO unmanifested extra files (across the entire public bundle
         root when .openislet_public_bundle is present, or across all allowlisted public paths in a
         local research checkout), independently verifies all 17/17 hardcoded pre-Wave-5 structure
         SHA-256 pins, and scans EVERY allowlisted public file for:
         - local home paths (raw + decoded JSON strings),
         - hosted Tier-2 tokens/numerics (with strict pre-masking scalar-schema validation on the
           5-item IIP-0044 summary carve-out),
         - coordinate rows (raw + recursively decoded JSON strings) strictly prohibited outside the
           EXACT SHA-256-pinned 17-file pre-Wave-5 data/structures/ origin allowlist.
      2. Scans ALL 23 published Wave-5 public files (failing closed if any declared file is missing)
         plus ALL 4 Wave-5 decision-tree blocks (DEC-120..DEC-123 extracted from
         stage0_decision_tree_v1.json, failing closed if stage0_decision_tree_v1.json or any block
         is missing) and extra_wave5_texts for ALL 4 prohibited classes.
      3. Discloses explicitly that cryptographic authentication of the root manifest.json file
         itself depends on external release verification rather than self-reference.
    """
    neg_self_tests = run_gate30_tos_quarantine_negative_self_tests()

    manifest_path = openislet_root / "manifest.json"
    public_inventory_scanned = 0
    manifest_sha256_verified_count = 0
    authorized_coord_files_verified: list[str] = []
    manifest_mode = "NO_MANIFEST_IN_ROOT"
    inventory_source = "no_manifest"
    manifest_file_sha256: str | None = None
    declared_manifest_verified = False
    exact_disk_membership_verified = False
    public_disk_membership_scope = "NONE"

    if not manifest_path.is_file():
        if require_manifest:
            raise FileNotFoundError(
                f"Gate 30-TOS-QUARANTINE fail-closed: required manifest.json missing in {openislet_root.name}"
            )
    else:
        manifest_bytes = manifest_path.read_bytes()
        manifest_file_sha256 = hashlib.sha256(manifest_bytes).hexdigest()
        mf = load_strict_json_text(manifest_bytes.decode("utf-8"), "manifest.json")
        if not isinstance(mf, dict):
            raise RuntimeError("manifest.json must decode to a JSON object")
        artifacts_obj = mf.get("artifacts")
        if not isinstance(artifacts_obj, dict) or not artifacts_obj:
            raise RuntimeError(
                "Gate 30-TOS-QUARANTINE fail-closed: manifest.json missing non-empty 'artifacts' digest map"
            )
        if "public_export_file_inventory" in mf:
            pub_rels = _extract_manifest_inventory_paths(
                mf["public_export_file_inventory"], "public_export_file_inventory"
            )
            manifest_mode = "PUBLIC_EXPORT_BUNDLE_MANIFEST"
            inventory_source = "public_bundle_manifest_json"
        else:
            all_rels = _extract_manifest_inventory_paths(artifacts_obj, "artifacts")
            spec = mf.get("public_redistribution_allowlist_spec")
            if isinstance(spec, dict) and spec.get("public_package_included_paths"):
                inc = spec.get("public_package_included_paths", [])
                exc = spec.get("local_research_cache_excluded_from_public_bundle", [])
                pub_rels = [
                    rel
                    for rel in all_rels
                    if not any(fnmatch.fnmatch(rel, pat) for pat in exc)
                    and any(fnmatch.fnmatch(rel, pat) for pat in inc)
                ]
            else:
                pub_rels = all_rels
            manifest_mode = "REPO_PUBLIC_ALLOWLIST_MANIFEST"
            inventory_source = "manifest_json"

        if not pub_rels:
            raise RuntimeError(f"Gate 30-TOS-QUARANTINE fail-closed: manifest {inventory_source} yielded 0 public files")

        # 1.0 Symmetric public-bundle marker enforcement BEFORE artifact loop (R10 B4):
        # Whenever manifest.json declares public_export_file_inventory (OR .openislet_public_bundle exists/is symlink),
        # require BOTH public_export_file_inventory AND a valid regular single-hardlink .openislet_public_bundle marker
        # (matching generate_release_manifest.py --verify-public-bundle 'invalid-public-marker' fail-closed!).
        marker_path = openislet_root / ".openislet_public_bundle"
        is_public_bundle_mode = (
            manifest_mode == "PUBLIC_EXPORT_BUNDLE_MANIFEST"
            or marker_path.exists()
            or marker_path.is_symlink()
        )
        if is_public_bundle_mode:
            if manifest_mode != "PUBLIC_EXPORT_BUNDLE_MANIFEST":
                raise RuntimeError(
                    "Gate 30-TOS-QUARANTINE fail-closed: invalid-public-inventory "
                    "(.openislet_public_bundle marker present without manifest.json['public_export_file_inventory'])"
                )
            if manifest_path.is_symlink():
                raise RuntimeError(
                    "Gate 30-TOS-QUARANTINE fail-closed: unsafe:manifest.json symlink prohibited inside public bundle"
                )
            mf_st = manifest_path.lstat()
            if not stat.S_ISREG(mf_st.st_mode) or mf_st.st_nlink != 1:
                raise RuntimeError(
                    "Gate 30-TOS-QUARANTINE fail-closed: unsafe:manifest.json must be a regular single-hardlink file inside public bundle"
                )
            if marker_path.is_symlink() or not marker_path.is_file():
                raise RuntimeError(
                    "Gate 30-TOS-QUARANTINE fail-closed: invalid-public-marker "
                    "(missing or non-regular .openislet_public_bundle marker required when manifest.json declares public_export_file_inventory)"
                )
            marker_st = marker_path.lstat()
            if (
                not stat.S_ISREG(marker_st.st_mode)
                or marker_st.st_nlink != 1
                or marker_path.read_bytes() != _PUBLIC_BUNDLE_MARKER_BYTES
            ):
                raise RuntimeError(
                    "Gate 30-TOS-QUARANTINE fail-closed: invalid-public-marker "
                    "(invalid .openislet_public_bundle marker bytes or file metadata)"
                )

        # 1a. Verify EVERY listed manifest artifact exists on disk, matches manifest.json SHA-256 & byte size,
        #     satisfies hardcoded 17-structure SHA-256 pins, and passes hygiene/coordinate scans!
        for rel in pub_rels:
            fp = openislet_root / rel
            if not fp.is_file():
                raise FileNotFoundError(
                    f"Gate 30-TOS-QUARANTINE fail-closed: manifest-declared public artifact missing from disk: {rel}"
                )
            pin = artifacts_obj.get(rel)
            if (
                not isinstance(pin, dict)
                or type(pin.get("sha256")) is not str
                or not _RE_SHA256_HEX.match(pin["sha256"])
                or type(pin.get("bytes")) is not int
                or pin["bytes"] < 0
            ):
                raise RuntimeError(
                    f"Gate 30-TOS-QUARANTINE fail-closed: manifest.json['artifacts'] missing valid sha256/bytes pin for {rel}"
                )
            raw_b = fp.read_bytes()
            actual_sha = hashlib.sha256(raw_b).hexdigest()

            # Check structure extension provenance: NO .cif/.mmcif/.pdb outside exact SHA-256-pinned pre-Wave-5 allowlist
            is_coord_ext = fp.suffix.lower() in (".cif", ".mmcif", ".pdb")
            expected_coord_sha = AUTHORIZED_PRE_WAVE5_PUBLIC_COORDINATE_SHA256.get(rel)
            is_auth_coord = expected_coord_sha is not None
            if is_coord_ext and not is_auth_coord:
                raise RuntimeError(
                    f"Gate 30-TOS-QUARANTINE: unauthorized coordinate structure file in public manifest: {rel}"
                )
            if is_auth_coord and actual_sha != expected_coord_sha:
                raise RuntimeError(
                    f"Gate 30-TOS-QUARANTINE fail-closed: SHA-256 mismatch on pre-Wave-5 coordinate file {rel}: "
                    f"got {actual_sha}, expected {expected_coord_sha}"
                )

            # Verify EVERY manifest-listed public file's SHA-256 digest & byte size against manifest.json!
            if actual_sha != pin["sha256"] or len(raw_b) != pin["bytes"]:
                raise RuntimeError(
                    f"Gate 30-TOS-QUARANTINE fail-closed: manifest.json SHA-256/bytes mismatch on public file {rel}: "
                    f"disk=({actual_sha}, {len(raw_b)} B) vs manifest=({pin['sha256']}, {pin['bytes']} B)"
                )
            manifest_sha256_verified_count += 1

            try:
                raw_txt = raw_b.decode("utf-8")
            except UnicodeDecodeError:
                if _T2_TAG.encode("ascii") in raw_b.lower() or ("sab_" + "pred_").encode("ascii") in raw_b.lower():
                    raise RuntimeError(f"Gate 30-TOS-QUARANTINE: Tier-2 marker in binary public file: {rel}")
                public_inventory_scanned += 1
                continue

            scan_txt = raw_txt
            if rel == "data/extracted/iip0044_tier1_metrics_cleanroom_summary_v0.8.0.json":
                scan_txt = strip_verified_iip0044_tier2_exclusion_manifest(raw_txt, rel)

            assert_public_hygiene_clean(
                scan_txt,
                rel,
                check_currency=False,
                check_vendor=False,
                check_coords=True,
                allow_authorized_coord_file=is_auth_coord,
            )
            if is_auth_coord:
                authorized_coord_files_verified.append(rel)
            public_inventory_scanned += 1

        # 1b. Declared-manifest completeness, mandatory 17/17 pre-Wave-5 structure pins & EXACT disk-membership check!
        if not isinstance(mf.get("public_redistribution_allowlist_spec"), dict):
            raise RuntimeError(
                "Gate 30-TOS-QUARANTINE fail-closed: manifest.json missing 'public_redistribution_allowlist_spec' "
                "required to verify declared public inventory completeness"
            )
        auth_spec = mf["public_redistribution_allowlist_spec"]
        auth_inc = auth_spec.get("public_package_included_paths")
        auth_exc = auth_spec.get("local_research_cache_excluded_from_public_bundle", [])
        if not isinstance(auth_inc, list) or len(auth_inc) == 0:
            raise RuntimeError(
                "Gate 30-TOS-QUARANTINE fail-closed: public_redistribution_allowlist_spec.public_package_included_paths empty"
            )
        all_manifest_artifacts = _extract_manifest_inventory_paths(artifacts_obj, "artifacts")
        expected_allowlisted_public = {
            rel
            for rel in all_manifest_artifacts
            if not any(fnmatch.fnmatch(rel, pat) for pat in auth_exc)
            and any(fnmatch.fnmatch(rel, pat) for pat in auth_inc)
        }
        pub_rel_set = set(pub_rels)
        missing_allowlisted = sorted(expected_allowlisted_public - pub_rel_set)
        if missing_allowlisted:
            raise RuntimeError(
                f"Gate 30-TOS-QUARANTINE fail-closed: incomplete/truncated public inventory omits "
                f"{len(missing_allowlisted)} allowlisted manifest artifacts (sample: {missing_allowlisted[:5]})"
            )
        required_wave5_all = set(WAVE5_STRICT_IIP0042_PUBLIC_FILES) | set(WAVE5_STRICT_4CLASS_PUBLIC_FILES)
        missing_wave5_in_manifest = sorted(required_wave5_all - pub_rel_set)
        if missing_wave5_in_manifest:
            raise RuntimeError(
                f"Gate 30-TOS-QUARANTINE fail-closed: public manifest inventory missing declared Wave-5 files: "
                f"{missing_wave5_in_manifest}"
            )
        verified_coord_set = set(authorized_coord_files_verified)
        if (
            len(authorized_coord_files_verified) != len(AUTHORIZED_PRE_WAVE5_PUBLIC_COORDINATE_FILES)
            or verified_coord_set != AUTHORIZED_PRE_WAVE5_PUBLIC_COORDINATE_FILES
        ):
            missing_coords = sorted(AUTHORIZED_PRE_WAVE5_PUBLIC_COORDINATE_FILES - verified_coord_set)
            raise RuntimeError(
                f"Gate 30-TOS-QUARANTINE fail-closed: incomplete pre-Wave-5 structure verification coverage "
                f"({len(verified_coord_set)}/{len(AUTHORIZED_PRE_WAVE5_PUBLIC_COORDINATE_FILES)} verified; "
                f"missing={missing_coords[:5]})"
            )
        structures_dir = openislet_root / "data" / "structures"
        if structures_dir.is_dir():
            disk_structs = {
                str(p.relative_to(openislet_root).as_posix())
                for p in structures_dir.rglob("*")
                if p.is_file() and p.suffix.lower() in (".cif", ".mmcif", ".pdb")
            }
            unmanifested_structs = sorted(disk_structs - AUTHORIZED_PRE_WAVE5_PUBLIC_COORDINATE_FILES)
            if unmanifested_structs:
                raise RuntimeError(
                    f"Gate 30-TOS-QUARANTINE fail-closed: unmanifested structure files under data/structures/: "
                    f"{unmanifested_structs}"
                )

        # 1c. Exact disk-membership check confirming ZERO unmanifested extra files!
        # Public-bundle mode & .openislet_public_bundle marker were verified symmetrically in Step 1.0 above.
        if is_public_bundle_mode:
            if (openislet_root / ".git").is_symlink():
                raise RuntimeError(
                    "Gate 30-TOS-QUARANTINE fail-closed: unsafe:.git symlink prohibited inside public bundle"
                )
            allowed_bundle_files = pub_rel_set | {"manifest.json", ".openislet_public_bundle"}
            unmanifested_extra: list[str] = []
            for p in openislet_root.rglob("*"):
                rel_p = p.relative_to(openislet_root).as_posix()
                if rel_p == ".git" or rel_p.startswith(".git/"):
                    continue
                if p.is_symlink():
                    raise RuntimeError(
                        f"Gate 30-TOS-QUARANTINE fail-closed: symlink prohibited inside public bundle: {rel_p}"
                    )
                if not p.is_dir():
                    pst = p.lstat()
                    if not stat.S_ISREG(pst.st_mode) or pst.st_nlink != 1:
                        raise RuntimeError(
                            f"Gate 30-TOS-QUARANTINE fail-closed: unsafe non-regular or multi-hardlink file inside public bundle: {rel_p}"
                        )
                    if rel_p not in allowed_bundle_files:
                        unmanifested_extra.append(rel_p)
            if unmanifested_extra:
                raise RuntimeError(
                    f"Gate 30-TOS-QUARANTINE fail-closed: {len(unmanifested_extra)} unmanifested extra file(s) "
                    f"in public bundle root (sample: {sorted(unmanifested_extra)[:5]})"
                )
            public_disk_membership_scope = "EXACT_PUBLIC_BUNDLE_ROOT"
            exact_disk_membership_verified = True
        else:
            # Local research checkout: verify ZERO unmanifested files anywhere matching public allowlist paths
            unmanifested_public_extra: list[str] = []
            for p in openislet_root.rglob("*"):
                rel_p = p.relative_to(openislet_root).as_posix()
                if rel_p == ".git" or rel_p.startswith(".git/"):
                    continue
                if not p.is_file():
                    continue
                if rel_p in ("manifest.json", ".openislet_public_bundle"):
                    continue
                if (
                    any(fnmatch.fnmatch(rel_p, pat) for pat in auth_inc)
                    and not any(fnmatch.fnmatch(rel_p, pat) for pat in auth_exc)
                    and rel_p not in pub_rel_set
                ):
                    unmanifested_public_extra.append(rel_p)
            if unmanifested_public_extra:
                raise RuntimeError(
                    f"Gate 30-TOS-QUARANTINE fail-closed: {len(unmanifested_public_extra)} unmanifested extra file(s) "
                    f"under public allowlist paths (sample: {sorted(unmanifested_public_extra)[:5]})"
                )
            public_disk_membership_scope = "ALLOWLISTED_PUBLIC_PATHS_IN_REPO_TREE"
            exact_disk_membership_verified = True

        declared_manifest_verified = bool(
            manifest_sha256_verified_count == len(pub_rels) and exact_disk_membership_verified
        )

    # Strict 4-class Wave-5 public surface scan across ALL 23 distinct installed Wave-5 public files (fail-closed if missing!)
    wave5_installed_scanned: list[str] = []
    for rel in WAVE5_STRICT_IIP0042_PUBLIC_FILES:
        fp = openislet_root / rel
        if not fp.is_file():
            raise FileNotFoundError(f"Gate 30-TOS-QUARANTINE fail-closed: missing declared Wave-5 file: {rel}")
        txt = fp.read_text(encoding="utf-8")
        if fp.suffix == ".md":
            txt = mask_canonical_layer2_disclaimer_only(txt)
        assert_public_hygiene_clean(txt, rel, vendor_token_set=_VENDOR_TOKENS)
        wave5_installed_scanned.append(rel)

    for rel in WAVE5_STRICT_4CLASS_PUBLIC_FILES:
        fp = openislet_root / rel
        if not fp.is_file():
            raise FileNotFoundError(f"Gate 30-TOS-QUARANTINE fail-closed: missing declared Wave-5 file: {rel}")
        txt = fp.read_text(encoding="utf-8")
        if fp.suffix == ".md":
            txt = mask_canonical_layer2_disclaimer_only(txt)
        elif rel == "data/extracted/iip0044_tier1_metrics_cleanroom_summary_v0.8.0.json":
            txt = strip_verified_iip0044_tier2_exclusion_manifest(txt, rel)
        assert_public_hygiene_clean(txt, rel, vendor_token_set=_COMMERCIAL_AI_VENDOR_TOKENS)
        wave5_installed_scanned.append(rel)

    # Extract and scan ALL 4 Wave-5 decision blocks (DEC-120..DEC-123) directly from stage0_decision_tree_v1.json (fail-closed!)
    dt_path = openislet_root / "data" / "protocols" / "stage0_decision_tree_v1.json"
    if not dt_path.is_file():
        raise FileNotFoundError(
            "Gate 30-TOS-QUARANTINE fail-closed: missing data/protocols/stage0_decision_tree_v1.json"
        )
    dt_obj = load_strict_json_text(dt_path.read_text(encoding="utf-8"), "stage0_decision_tree_v1.json")
    if not isinstance(dt_obj, dict):
        raise RuntimeError("stage0_decision_tree_v1.json must decode to a JSON object")
    dt_blocks_scanned: list[str] = []
    for key, mode_tag in WAVE5_REQUIRED_DECISION_TREE_BLOCKS:
        if key not in dt_obj:
            raise RuntimeError(
                f"Gate 30-TOS-QUARANTINE fail-closed: required Wave-5 decision-tree block missing: {key}"
            )
        vset = _VENDOR_TOKENS if mode_tag == "STRICT_IIP0042" else _COMMERCIAL_AI_VENDOR_TOKENS
        blk_txt = json.dumps(dt_obj[key], sort_keys=True, ensure_ascii=False)
        assert_public_hygiene_clean(blk_txt, f"stage0_decision_tree_v1.json::{key}", vendor_token_set=vset)
        if key == "DEC-121":
            _check_nct_prose_no_swaps(blk_txt, "stage0_decision_tree_v1.json::DEC-121")
        dt_blocks_scanned.append(key)

    extra_labels_scanned: list[str] = []
    if extra_wave5_texts:
        for lbl, txt in extra_wave5_texts.items():
            assert_public_hygiene_clean(txt, lbl, vendor_token_set=_VENDOR_TOKENS)
            extra_labels_scanned.append(lbl)

    coord_full_coverage = (
        len(authorized_coord_files_verified) == len(AUTHORIZED_PRE_WAVE5_PUBLIC_COORDINATE_FILES)
        and set(authorized_coord_files_verified) == AUTHORIZED_PRE_WAVE5_PUBLIC_COORDINATE_FILES
    )
    all_clean_flag = bool(declared_manifest_verified and coord_full_coverage)

    return {
        "inventory_source": inventory_source,
        "manifest_scan_mode": manifest_mode,
        "manifest_file_sha256": manifest_file_sha256,
        "declared_manifest_sha256_and_disk_membership_verified": declared_manifest_verified,
        "manifest_sha256_digests_verified_count": manifest_sha256_verified_count,
        "exact_public_disk_membership_verified": exact_disk_membership_verified,
        "public_disk_membership_scope": public_disk_membership_scope,
        "inventory_trust_boundary_note": _INVENTORY_TRUST_BOUNDARY_NOTE,
        "public_manifest_files_scanned": public_inventory_scanned,
        "authorized_pre_wave5_coordinate_files_expected_count": len(AUTHORIZED_PRE_WAVE5_PUBLIC_COORDINATE_FILES),
        "authorized_pre_wave5_coordinate_files_verified_count": len(authorized_coord_files_verified),
        "authorized_pre_wave5_coordinate_sha256_verified": coord_full_coverage,
        "wave5_4class_files_scanned_count": len(wave5_installed_scanned),
        "wave5_extra_texts_scanned_count": len(extra_labels_scanned),
        "decision_tree_blocks_scanned": dt_blocks_scanned,
        "negative_self_tests": neg_self_tests,
        "all_clean": all_clean_flag,
    }


def _mean_and_t95_ci(values: list[float], label: str) -> tuple[float, float, float, float, float]:
    """Return (mean, l95_t, u95_t, min_val, max_val) from strictly finite donor-level values (overflow-immune)."""
    if not isinstance(values, list) or len(values) < 2:
        raise ValueError(f"{label} requires a list of >= 2 donor observations")
    nums = [require_finite_number(v, f"{label}[{i}]") for i, v in enumerate(values)]
    n = len(nums)
    scale_abs = max(abs(x) for x in nums)
    if scale_abs == 0.0:
        return 0.0, 0.0, 0.0, 0.0, 0.0
    mean_scaled = sum(x / scale_abs for x in nums) / float(n)
    mean = mean_scaled * scale_abs
    devs = [(x / scale_abs) - mean_scaled for x in nums]
    max_dev = max(abs(d) for d in devs)
    if max_dev == 0.0:
        return mean, mean, mean, min(nums), max(nums)
    norm_devs = [d / max_dev for d in devs]
    se_scaled = (math.sqrt(sum(d * d for d in norm_devs) / float(n - 1)) / math.sqrt(float(n))) * max_dev
    half_scaled = _student_t_95_critical(n - 1) * se_scaled
    return mean, (mean_scaled - half_scaled) * scale_abs, (mean_scaled + half_scaled) * scale_abs, min(nums), max(nums)


_XREACT_REQUIRED_STRATA = (
    "sc_islet_cd64t_null",
    "sc_islet_cd64t_pos",
    "iec_cd64t_null",
    "iec_cd64t_pos",
)
_XREACT_CD64T_POS_STRATA = ("sc_islet_cd64t_pos", "iec_cd64t_pos")
_XREACT_SC_ISLET_STRATA = ("sc_islet_cd64t_null", "sc_islet_cd64t_pos")
_XREACT_IEC_STRATA = ("iec_cd64t_null", "iec_cd64t_pos")
_XREACT_REQUIRED_DOSES_UG_ML = (0.0, 1.0, 5.0, 15.0, 50.0)
_XREACT_CLINICAL_BRACKET_DOSES_UG_ML = (1.0, 5.0, 15.0)
_XREACT_INDEPENDENT_IGG_LOT_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{1,63}$")
_XREACT_PRECEDENCE = {
    "PASS": 0,
    "HOLD": 1,
    "HOLD_UNCLASSIFIED_DONOR_OUTLIER_REQUIRES_INVESTIGATION": 2,
    "HOLD_INVALID_OR_INCOMPLETE_ASSAY": 3,
    "FAIL": 4,
}


def _check_xreact_domain_number(
    val: Any,
    label: str,
    *,
    lo: float,
    hi: float | None,
) -> tuple[float | None, str | None]:
    """Validate strict finite non-bool numeric domain; raises ValueError on NaN/Inf/overflow (>1e300 int or float),
    returns (None, reason) for missing/wrong-type/bool/out-of-domain finite values.
    """
    if isinstance(val, float) and (not math.isfinite(val) or abs(val) > 1e300):
        raise ValueError(f"Non-finite or overflowing float rejected fail-closed for {label}: {val!r}")
    if isinstance(val, int) and not isinstance(val, bool) and abs(val) > 10 ** 300:
        raise ValueError(f"Overflowing integer rejected fail-closed for {label}")
    if isinstance(val, bool) or not isinstance(val, (int, float)):
        return None, f"{label} must be a strict finite non-bool numeric value (got {val!r})"
    fval = float(val)
    if fval < lo or (hi is not None and fval > hi):
        dom = f"[{lo}, {hi}]" if hi is not None else f">= {lo}"
        return None, f"{label}={fval} violates physical domain {dom}"
    return fval, None


def _xreact_trapz_mean(doses: tuple[float, ...], values: list[float]) -> float:
    """Exact dose-span-normalized trapezoidal AUC over strictly increasing doses."""
    if len(doses) < 2 or len(doses) != len(values):
        raise ValueError("Trapezoidal AUC requires >= 2 paired (dose, value) points")
    span = doses[-1] - doses[0]
    if span <= 0.0:
        raise ValueError(f"Non-positive dose span: {doses}")
    area = 0.0
    for i in range(len(doses) - 1):
        area += 0.5 * (values[i] + values[i + 1]) * (doses[i + 1] - doses[i])
    return area / span


def build_valid_xreact_lot(
    lot_id: str,
    *,
    donor_ids: list[str] | None = None,
    doses: tuple[float, ...] = _XREACT_REQUIRED_DOSES_UG_ML,
    strata: tuple[str, ...] = _XREACT_REQUIRED_STRATA,
    cd47_values: list[float] | None = None,
    hla_e_values: list[float] | None = None,
    cd64t_disp_values: list[float] | None = None,
    c3d_values: list[float] | None = None,
    c5b9_values: list[float] | None = None,
    lysis_values: list[float] | None = None,
    fab2_c3d_values: list[float] | None = None,
    fab2_c5b9_values: list[float] | None = None,
    fab2_lysis_values: list[float] | None = None,
    sc_islet_viab_values: list[float] | None = None,
    iec_viab_values: list[float] | None = None,
    gsis_si_values: list[float] | None = None,
    plate_or_run_id: str | None = None,
    lot_cd3_pos_ctrl_pct: float = 94.0,
    lot_b6h12_pos_ctrl_pct: float = 95.0,
) -> dict[str, Any]:
    """Construct a typed crossed paired-donor, lot- & run-linked positive-control, matched rabbit-IgG,
    direct HLA-E retention, lot-/donor-/run-linked F(ab')2 deconvolution, 5-dose, 4-stratum, and
    endpoint-complete Gate 30-ATG-XREACT lot.
    """
    d_ids = donor_ids if donor_ids is not None else [f"DONOR-{i:02d}" for i in range(1, 7)]
    n = len(d_ids)
    run_id = plate_or_run_id if plate_or_run_id is not None else f"RUN_{lot_id}_PLATE_01"

    def _expand(vals: list[float] | None, default: list[float]) -> list[float]:
        if vals is None:
            return [default[i % len(default)] for i in range(n)]
        if len(vals) != n:
            raise ValueError(f"Value list length {len(vals)} != donor_ids length {n}")
        return list(vals)

    v_cd47 = _expand(cd47_values, [94.0, 93.0, 95.0, 92.0, 96.0, 94.0])
    v_hla_e = _expand(hla_e_values, [94.5, 93.5, 95.5, 92.5, 96.0, 94.0])
    v_disp = _expand(cd64t_disp_values, [8.0, 9.5, 10.0, 7.5, 11.0, 9.0])
    v_c3d = _expand(c3d_values, [1.2, 1.8, 1.5, 1.8, 1.6, 1.7])
    v_c5b9 = _expand(c5b9_values, [1.0, 1.4, 1.3, 1.6, 1.2, 1.5])
    v_lysis = _expand(lysis_values, [1.5, 2.0, 1.8, 1.9, 1.9, 2.0])
    v_fab_c3d = _expand(fab2_c3d_values, v_c3d)
    v_fab_c5b9 = _expand(fab2_c5b9_values, v_c5b9)
    v_fab_lysis = _expand(fab2_lysis_values, v_lysis)
    v_sc_viab = _expand(sc_islet_viab_values, [96.0, 95.0, 97.0, 94.5, 96.5, 95.5])
    v_iec_viab = _expand(iec_viab_values, [95.5, 96.0, 94.8, 96.2, 95.0, 95.8])
    v_gsis = _expand(gsis_si_values, [3.2, 3.4, 3.1, 3.5, 3.0, 3.3])

    observations: list[dict[str, Any]] = []
    for dose in doses:
        for strat in strata:
            for idx, did in enumerate(d_ids):
                is_veh = (dose == 0.0)
                c3d_v = 0.5 if is_veh else v_c3d[idx]
                c5b9_v = 0.4 if is_veh else v_c5b9[idx]
                lysis_v = 0.6 if is_veh else v_lysis[idx]
                fab_c3d_v = 0.4 if is_veh else v_fab_c3d[idx]
                fab_c5b9_v = 0.3 if is_veh else v_fab_c5b9[idx]
                fab_lysis_v = 0.5 if is_veh else v_fab_lysis[idx]
                igg_rec: dict[str, Any] = {
                    "cd47_sirpa_retention_pct": 99.0 if is_veh else 99.5,
                    "hla_e_binding_retention_pct": 99.0 if is_veh else 99.5,
                    "c3d_pct": 0.4,
                    "c5b9_pct": 0.3,
                    "lysis_pct": 0.5,
                }
                rec: dict[str, Any] = {
                    "donor_id": did,
                    "stratum": strat,
                    "dose_ug_ml": dose,
                    "plate_or_run_id": run_id,
                    "control_matched_rabbit_igg": True,
                    "fab2_deconvolution_paired": True,
                    "cd47_sirpa_retention_pct": 99.0 if is_veh else v_cd47[idx],
                    "hla_e_binding_retention_pct": 99.0 if is_veh else v_hla_e[idx],
                    "c3d_pct": c3d_v,
                    "c5b9_pct": c5b9_v,
                    "lysis_pct": lysis_v,
                    "matched_rabbit_igg": igg_rec,
                    "fab2_deconvolution": {
                        "lot_id": lot_id,
                        "donor_id": did,
                        "stratum": strat,
                        "dose_ug_ml": dose,
                        "plate_or_run_id": run_id,
                        "intact_igg_c3d_pct": c3d_v,
                        "intact_igg_c5b9_pct": c5b9_v,
                        "intact_igg_lysis_pct": lysis_v,
                        "fab2_c3d_pct": fab_c3d_v,
                        "fab2_c5b9_pct": fab_c5b9_v,
                        "fab2_lysis_pct": fab_lysis_v,
                    },
                }
                if strat in _XREACT_CD64T_POS_STRATA:
                    rec["cd64t_displacement_pct"] = 1.0 if is_veh else v_disp[idx]
                    igg_rec["cd64t_displacement_pct"] = 0.8
                if strat in _XREACT_SC_ISLET_STRATA:
                    rec["sc_islet_viability_pct"] = 98.0 if is_veh else v_sc_viab[idx]
                    rec["gsis_si"] = 3.5 if is_veh else v_gsis[idx]
                    igg_rec["sc_islet_viability_pct"] = 98.0
                    igg_rec["gsis_si"] = 3.5
                if strat in _XREACT_IEC_STRATA:
                    rec["iec_viability_pct"] = 98.0 if is_veh else v_iec_viab[idx]
                    igg_rec["iec_viability_pct"] = 98.0
                observations.append(rec)
    return {
        "lot_id": lot_id,
        "lot_positive_controls": {
            "lot_id": lot_id,
            "plate_or_run_id": run_id,
            "cd3_pos_ctrl_pct": lot_cd3_pos_ctrl_pct,
            "b6h12_pos_ctrl_pct": lot_b6h12_pos_ctrl_pct,
        },
        "observations": observations,
    }


def build_valid_xreact_controls() -> dict[str, Any]:
    return {
        "cd3_pos_ctrl_pct": 94.0,
        "b6h12_pos_ctrl_pct": 95.0,
        "normal_rabbit_igg_isotype_valid": True,
        "normal_rabbit_igg_isotype_matched_doses_ug_ml": [0.0, 1.0, 5.0, 15.0, 50.0],
        "normal_rabbit_igg_max_lysis_pct": 1.8,
        "fab2_vs_intact_igg_deconvolution": {
            "valid": True,
            "doses_ug_ml": [0.0, 1.0, 5.0, 15.0, 50.0],
            "paired_isogenic_strata_tested": True,
            "direct_fab_c3d_max_pct": 1.8,
            "direct_fab_c5b9_max_pct": 1.6,
            "direct_fab_lysis_max_pct": 2.0,
        },
    }


def build_valid_xreact_independent_igg_control(
    lot_id: str,
    plate_or_run_id: str,
    control_lot_id: str,
    *,
    max_lysis_pct: float = 1.8,
    matched_doses_ug_ml: list[float] | None = None,
) -> dict[str, Any]:
    """Construct a traceable run-linked independent matched normal rabbit IgG control record."""
    return {
        "lot_id": lot_id,
        "plate_or_run_id": plate_or_run_id,
        "independent_matched_igg_isotype_valid": True,
        "independent_matched_igg_isotype_lot_id": control_lot_id,
        "matched_doses_ug_ml": (
            list(matched_doses_ug_ml)
            if matched_doses_ug_ml is not None
            else [0.0, 1.0, 5.0, 15.0, 50.0]
        ),
        "max_lysis_pct": float(max_lysis_pct),
    }


def evaluate_gate30_atg_xreact(observation: dict[str, Any]) -> dict[str, Any]:
    """Executable fail-closed Gate 30-ATG-XREACT crossed paired-donor, matched rabbit-IgG AUC,
    lot-/donor-linked F(ab')2 deconvolution, dose-, stratum-, endpoint-, control-, and lot-complete adjudicator.

    Enforces:
      - ONE consistent crossed donor panel WITHIN EACH independently adjudicated commercial lot
        (len(common_donors) >= 6 AND common_donors == union_donors across ALL 4 required strata x
        ALL 5 required doses {0, 1, 5, 15, 50} ug/mL; distinct commercial lots need not share the
        same physical donors, and optional cross-lot donor overlap is logged if present). Disconnected
        within-lot panels fail closed!
      - Numeric matched normal rabbit IgG comparator per (lot_id, donor_id, stratum, dose_ug_ml)
        governing EVERY endpoint: IgG lysis <= 5.0%, IgG CD64t displacement <= 10.0% at every dose,
        IgG GSIS SI >= 2.5 at every dose, exact trapezoidal per-donor dose-response AUC (0..50 and
        1..15 ug/mL) vs matched normal rabbit IgG across all endpoints (including paired excess
        CD64t displacement AUC_ATG - AUC_IgG and paired GSIS ratios ATG/IgG and AUC_ATG/AUC_IgG >= 0.85).
      - Lot- and donor-linked F(ab')2 vs intact IgG deconvolution per (lot_id, donor_id, stratum, dose_ug_ml),
        adjudicating direct F(ab')2 complement/lysis biologically (FAIL on breach), deriving exact F(ab')2 maxima,
        and failing closed (HOLD_INVALID_OR_INCOMPLETE_ASSAY) on ANY summary-vs-observation discrepancy.
      - Independent worst-lot evaluation across >= 2 distinct commercial ATG lots (NO lot pooling!).
      - Strict precedence: FAIL > HOLD_INVALID_OR_INCOMPLETE_ASSAY >
        HOLD_UNCLASSIFIED_DONOR_OUTLIER_REQUIRES_INVESTIGATION > HOLD > PASS.
    """
    if not isinstance(observation, dict):
        raise ValueError("Gate 30-ATG-XREACT observation must be a JSON object")

    reasons: list[str] = []
    worst_state = "PASS"

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

    # 1. Validate mandatory controls within strict physical domain [0.0, 100.0]
    controls = observation.get("controls")
    controls_valid = True
    global_matched_igg_valid = True
    global_fab_ctrl_valid = True
    reported_fab_maxima: dict[str, float] = {}
    reported_iso_max_lysis: float | None = None
    if not isinstance(controls, dict):
        controls_valid = False
        global_matched_igg_valid = False
        global_fab_ctrl_valid = False
        _escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", "Missing mandatory controls block")
    else:
        # CD3+ positive control (strict [80.0, 100.0]%)
        if "cd3_pos_ctrl_pct" not in controls:
            controls_valid = False
            if "positive_control_cd3_lysis_pct" in controls:
                _, leg_err = _check_xreact_domain_number(
                    controls["positive_control_cd3_lysis_pct"],
                    "controls.positive_control_cd3_lysis_pct",
                    lo=0.0,
                    hi=100.0,
                )
                extra = f" ({leg_err})" if leg_err else ""
                _escalate(
                    "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                    f"Missing typed controls.cd3_pos_ctrl_pct (legacy anonymous control schema rejected){extra}",
                )
            else:
                _escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", "Missing mandatory controls.cd3_pos_ctrl_pct")
        else:
            cd3_f, cd3_err = _check_xreact_domain_number(
                controls["cd3_pos_ctrl_pct"], "controls.cd3_pos_ctrl_pct", lo=0.0, hi=100.0
            )
            if cd3_err is not None or cd3_f is None:
                controls_valid = False
                _escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", cd3_err or "Invalid controls.cd3_pos_ctrl_pct")
            elif cd3_f < 80.0:
                controls_valid = False
                _escalate(
                    "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                    f"CD3+ positive control lysis {cd3_f:.2f}% < 80.0% minimum activity threshold",
                )

        # B6H12 anti-CD47 positive control (strict [80.0, 100.0]%)
        if "b6h12_pos_ctrl_pct" not in controls:
            controls_valid = False
            _escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", "Missing mandatory controls.b6h12_pos_ctrl_pct")
        else:
            b6_f, b6_err = _check_xreact_domain_number(
                controls["b6h12_pos_ctrl_pct"], "controls.b6h12_pos_ctrl_pct", lo=0.0, hi=100.0
            )
            if b6_err is not None or b6_f is None:
                controls_valid = False
                _escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", b6_err or "Invalid controls.b6h12_pos_ctrl_pct")
            elif b6_f < 80.0:
                controls_valid = False
                _escalate(
                    "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                    f"B6H12 CD47 positive control {b6_f:.2f}% < 80.0% dynamic-range threshold",
                )

        # Equal-ug/mL normal rabbit IgG isotype control across all 5 doses (R08 B2: invalidates inheriting rows!)
        if controls.get("normal_rabbit_igg_isotype_valid") is not True:
            controls_valid = False
            global_matched_igg_valid = False
            _escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", "Equal-ug/mL normal rabbit IgG isotype control invalid or missing")
        iso_doses_raw = controls.get("normal_rabbit_igg_isotype_matched_doses_ug_ml")
        if not isinstance(iso_doses_raw, list):
            controls_valid = False
            global_matched_igg_valid = False
            _escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", "Missing normal_rabbit_igg_isotype_matched_doses_ug_ml list")
        else:
            iso_doses: set[float] = set()
            for idx_d, dv in enumerate(iso_doses_raw):
                df, derr = _check_xreact_domain_number(dv, f"controls.isotype_dose[{idx_d}]", lo=0.0, hi=None)
                if derr is not None or df is None:
                    controls_valid = False
                    global_matched_igg_valid = False
                    _escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", derr or "Invalid isotype dose")
                else:
                    iso_doses.add(df)
            missing_iso_doses = sorted(set(_XREACT_REQUIRED_DOSES_UG_ML) - iso_doses)
            if missing_iso_doses:
                controls_valid = False
                global_matched_igg_valid = False
                _escalate(
                    "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                    f"Normal rabbit IgG isotype control missing required doses ug/mL: {missing_iso_doses}",
                )
        iso_lysis, iso_l_err = _check_xreact_domain_number(
            controls.get("normal_rabbit_igg_max_lysis_pct"), "controls.normal_rabbit_igg_max_lysis_pct", lo=0.0, hi=100.0
        )
        if iso_l_err is not None or iso_lysis is None:
            controls_valid = False
            global_matched_igg_valid = False
            _escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", iso_l_err or "Invalid normal_rabbit_igg_max_lysis_pct")
        elif iso_lysis > 5.0:
            controls_valid = False
            global_matched_igg_valid = False
            _escalate(
                "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                f"Normal rabbit IgG isotype background lysis {iso_lysis:.2f}% > 5.0% baseline limit",
            )
        else:
            reported_iso_max_lysis = iso_lysis

        # F(ab')2 vs intact IgG deconvolution control summary (reconciled below against lot-/donor-linked observations!)
        fab = controls.get("fab2_vs_intact_igg_deconvolution")
        if not isinstance(fab, dict):
            controls_valid = False
            global_fab_ctrl_valid = False
            _escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", "Missing mandatory fab2_vs_intact_igg_deconvolution control block")
        else:
            if fab.get("valid") is not True or fab.get("paired_isogenic_strata_tested") is not True:
                controls_valid = False
                global_fab_ctrl_valid = False
                _escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", "F(ab')2 vs intact IgG deconvolution invalid or unpaired across isogenic strata")
            fab_doses_raw = fab.get("doses_ug_ml")
            if not isinstance(fab_doses_raw, list):
                controls_valid = False
                global_fab_ctrl_valid = False
                _escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", "Missing fab2_vs_intact_igg_deconvolution.doses_ug_ml")
            else:
                fab_doses: set[float] = set()
                for idx_d, dv in enumerate(fab_doses_raw):
                    df, derr = _check_xreact_domain_number(dv, f"controls.fab2.doses[{idx_d}]", lo=0.0, hi=None)
                    if derr is not None or df is None:
                        controls_valid = False
                        global_fab_ctrl_valid = False
                        _escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", derr or "Invalid F(ab')2 dose")
                    else:
                        fab_doses.add(df)
                missing_fab = sorted(set(_XREACT_REQUIRED_DOSES_UG_ML) - fab_doses)
                if missing_fab:
                    controls_valid = False
                    global_fab_ctrl_valid = False
                    _escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", f"F(ab')2 deconvolution missing doses ug/mL: {missing_fab}")
            for fk in ("direct_fab_c3d_max_pct", "direct_fab_c5b9_max_pct", "direct_fab_lysis_max_pct"):
                fv, ferr = _check_xreact_domain_number(fab.get(fk), f"controls.fab2.{fk}", lo=0.0, hi=100.0)
                if ferr is not None or fv is None:
                    controls_valid = False
                    _escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", ferr or f"Invalid controls.fab2.{fk}")
                else:
                    reported_fab_maxima[fk] = fv

    # 2. Validate commercial ATG lot coverage (min 2 distinct lots; evaluate EVERY lot independently!)
    lots = observation.get("lots")
    if not isinstance(lots, list) or len(lots) == 0:
        _escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", "No commercial ATG lots provided (minimum 2 distinct lots required)")
        return {
            "gate_id": "GATE_30_ATG_XREACT",
            "verdict": worst_state,
            "lot_pooling_prohibited": True,
            "anonymous_arrays_rejected": True,
            "crossed_paired_donor_panel_enforced": True,
            "per_donor_dose_auc_vs_matched_igg_enforced": True,
            "uncapped_paired_ratios_enforced": True,
            "linked_fab2_deconvolution_reconciled": False,
            "derived_direct_fab_maxima_pct": {
                "direct_fab_c3d_max_pct": None,
                "direct_fab_c5b9_max_pct": None,
                "direct_fab_lysis_max_pct": None,
            },
            "withheld_cross_run_fab_maxima": {
                "direct_fab_c3d_max_pct": None,
                "direct_fab_c5b9_max_pct": None,
                "direct_fab_lysis_max_pct": None,
            },
            "withheld_cross_run_fab_rows_count": 0,
            "lots_evaluated": 0,
            "controls_valid": controls_valid,
            "per_lot_verdicts": {},
            "reasons": reasons,
        }

    def _parse_independent_igg_provenance(
        obj: dict[str, Any], ctx_label: str
    ) -> tuple[bool, bool, str | None, str | None]:
        """Validate optional independent per-lot/per-row matched rabbit-IgG provenance (R08 B2 + R09 B1).
        Enforces strict unpadded ID format BEFORE any normalization (never silently strips whitespace).
        Returns (has_valid_claim, explicitly_invalid, control_lot_id_or_none, err_msg).
        """
        has_flag = "independent_matched_igg_isotype_valid" in obj
        has_id = "independent_matched_igg_isotype_lot_id" in obj
        if not has_flag and not has_id:
            return False, False, None, None
        flag_v = obj.get("independent_matched_igg_isotype_valid")
        id_v = obj.get("independent_matched_igg_isotype_lot_id")
        if flag_v is not True:
            return (
                False,
                True,
                None,
                f"{ctx_label}: independent matched normal rabbit IgG provenance requires literal boolean "
                f"independent_matched_igg_isotype_valid=True (got valid={flag_v!r}, lot_id={id_v!r})",
            )
        if type(id_v) is not str or not id_v:
            return (
                False,
                True,
                None,
                f"{ctx_label}: independent matched normal rabbit IgG provenance requires non-empty unpadded string "
                f"independent_matched_igg_isotype_lot_id (got valid={flag_v!r}, lot_id={id_v!r})",
            )
        if id_v != id_v.strip():
            return (
                False,
                True,
                None,
                f"{ctx_label}: whitespace-padded independent_matched_igg_isotype_lot_id rejected fail-closed "
                f"(unpadded ID required; got {id_v!r})",
            )
        if not _XREACT_INDEPENDENT_IGG_LOT_ID_RE.fullmatch(id_v):
            return (
                False,
                True,
                None,
                f"{ctx_label}: non-conforming independent_matched_igg_isotype_lot_id rejected fail-closed "
                f"(must match ^[A-Za-z0-9][A-Za-z0-9._:-]{{1,63}}$ with zero whitespace; got {id_v!r})",
            )
        return True, False, id_v, None

    # Optional top-level traceable independent matched-IgG control table (reconciled per lot below)
    top_ind_igg_controls_raw = controls.get("independent_matched_igg_controls") if isinstance(controls, dict) else None
    top_ind_igg_entries_by_lot: dict[str, list[Any]] = {}
    if top_ind_igg_controls_raw is not None:
        if not isinstance(top_ind_igg_controls_raw, list):
            _escalate(
                "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                f"controls.independent_matched_igg_controls must be a list of control dicts (got {type(top_ind_igg_controls_raw).__name__})",
            )
        else:
            for t_idx, t_item in enumerate(top_ind_igg_controls_raw):
                if not isinstance(t_item, dict):
                    _escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"controls.independent_matched_igg_controls[{t_idx}] must be a dict",
                    )
                    continue
                t_lid = t_item.get("lot_id")
                if type(t_lid) is not str or not t_lid or t_lid != t_lid.strip():
                    _escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"controls.independent_matched_igg_controls[{t_idx}].lot_id must be a non-empty unpadded string (got {t_lid!r})",
                    )
                    continue
                top_ind_igg_entries_by_lot.setdefault(t_lid, []).append(t_item)

    # Pass 1 across commercial lots: detect duplicate/conflicting lot_ids BEFORE biological adjudication (order-independent!)
    lot_id_counts: dict[str, int] = {}
    for lot in lots:
        if isinstance(lot, dict):
            raw_lid = lot.get("lot_id")
            lid_c = raw_lid.strip() if type(raw_lid) is str else ""
            if lid_c:
                lot_id_counts[lid_c] = lot_id_counts.get(lid_c, 0) + 1
    conflicted_lot_ids: set[str] = {k for k, cnt in lot_id_counts.items() if cnt > 1}
    for clid in sorted(conflicted_lot_ids):
        _escalate(
            "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
            f"Duplicate/conflicting commercial lot_id: {clid!r} (count={lot_id_counts[clid]}); excluded from biological adjudication",
        )

    lot_ids_seen: set[str] = set()
    per_lot_verdicts: dict[str, dict[str, Any]] = {}
    all_linked_fab_c3d: list[float] = []
    all_linked_fab_c5b9: list[float] = []
    all_linked_fab_lysis: list[float] = []
    withheld_cross_run_fab_c3d: list[float] = []
    withheld_cross_run_fab_c5b9: list[float] = []
    withheld_cross_run_fab_lysis: list[float] = []
    invalid_vehicle_fab_c3d: list[float] = []
    invalid_vehicle_fab_c5b9: list[float] = []
    invalid_vehicle_fab_lysis: list[float] = []
    withheld_cross_run_fab_rows_count = 0
    withheld_invalid_fab_rows_count = 0
    withheld_invalid_vehicle_fab_rows_count = 0

    for idx, lot in enumerate(lots):
        if not isinstance(lot, dict):
            _escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", f"Lot entry {idx} is not a dict")
            continue
        raw_lid = lot.get("lot_id")
        lot_id = raw_lid.strip() if type(raw_lid) is str else ""
        if not lot_id:
            _escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", f"Missing commercial lot_id: {raw_lid!r}")
            continue
        if lot_id in conflicted_lot_ids:
            continue
        lot_ids_seen.add(lot_id)

        lot_state = "PASS"
        lot_endpoints: dict[str, Any] = {}

        def _lot_escalate(st: str, msg: str) -> None:
            nonlocal lot_state
            if _XREACT_PRECEDENCE[st] > _XREACT_PRECEDENCE[lot_state]:
                lot_state = st
            _escalate(st, f"lot={lot_id}: {msg}")

        # R08 B2 + R09 B1: Check optional lot-level independent matched normal rabbit IgG isotype provenance
        lot_ind_igg_valid, lot_ind_igg_explicit_bad, lot_ind_igg_id, lot_ind_igg_err = _parse_independent_igg_provenance(
            lot, f"lot={lot_id}"
        )
        if lot_ind_igg_err is not None:
            _lot_escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", lot_ind_igg_err)

        # R09 B1: Two-pass order-independent reconciliation of traceable lot/run independent_matched_igg_controls
        # (from lot.independent_matched_igg_controls AND any lot-matched controls.independent_matched_igg_controls).
        # Every independent matched-IgG claim on any lot/row MUST resolve to a verified, non-conflicted,
        # dose-complete, lysis-valid run record here BEFORE authorizing biological FAIL adjudication!
        lot_ind_ctrl_raw = lot.get("independent_matched_igg_controls")
        ind_ctrl_entries: list[Any] = []
        if lot_ind_ctrl_raw is not None:
            if isinstance(lot_ind_ctrl_raw, dict):
                ind_ctrl_entries.append(lot_ind_ctrl_raw)
            elif isinstance(lot_ind_ctrl_raw, list) and len(lot_ind_ctrl_raw) > 0:
                ind_ctrl_entries.extend(lot_ind_ctrl_raw)
            else:
                _lot_escalate(
                    "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                    f"independent_matched_igg_controls must be a dict or non-empty list of per-run control dicts (got {lot_ind_ctrl_raw!r})",
                )
        ind_ctrl_entries.extend(top_ind_igg_entries_by_lot.get(lot_id, []))

        candidate_valid_ind_igg_by_run: dict[str, dict[str, Any]] = {}
        conflicted_or_invalid_ind_igg_run_ids: set[str] = set()
        ind_ctrl_run_counts: dict[str, int] = {}
        for ic_item in ind_ctrl_entries:
            if isinstance(ic_item, dict):
                ic_run = ic_item.get("plate_or_run_id")
                ic_run_c = ic_run.strip() if type(ic_run) is str else ""
                if ic_run_c:
                    ind_ctrl_run_counts[ic_run_c] = ind_ctrl_run_counts.get(ic_run_c, 0) + 1
        for dup_irun in sorted(r for r, cnt in ind_ctrl_run_counts.items() if cnt > 1):
            conflicted_or_invalid_ind_igg_run_ids.add(dup_irun)
            _lot_escalate(
                "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                f"Duplicate/conflicting plate_or_run_id={dup_irun!r} inside independent_matched_igg_controls "
                f"(count={ind_ctrl_run_counts[dup_irun]}); run independent matched-IgG provenance invalidated prior to biological adjudication",
            )
        for ic_idx, ic_item in enumerate(ind_ctrl_entries):
            if not isinstance(ic_item, dict):
                _lot_escalate(
                    "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                    f"independent_matched_igg_controls[{ic_idx}] must be a dict (got {type(ic_item).__name__})",
                )
                continue
            ic_ok = True
            ic_lid = ic_item.get("lot_id")
            if type(ic_lid) is not str or not ic_lid or ic_lid != ic_lid.strip() or ic_lid != lot_id:
                ic_ok = False
                _lot_escalate(
                    "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                    f"independent_matched_igg_controls[{ic_idx}].lot_id={ic_lid!r} must be an unpadded exact match to parent lot_id={lot_id!r}",
                )
            ic_run = ic_item.get("plate_or_run_id")
            ic_run_norm = ic_run.strip() if type(ic_run) is str else ""
            if type(ic_run) is not str or not ic_run or ic_run != ic_run.strip():
                ic_ok = False
                _lot_escalate(
                    "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                    f"independent_matched_igg_controls[{ic_idx}].plate_or_run_id must be a non-empty unpadded string (got {ic_run!r})",
                )
            elif ind_ctrl_run_counts.get(ic_run, 0) > 1:
                ic_ok = False
            ic_prov_ok, _, ic_cid, ic_prov_err = _parse_independent_igg_provenance(
                ic_item, f"{lot_id}.independent_matched_igg_controls[{ic_idx}]"
            )
            if not ic_prov_ok or ic_cid is None:
                ic_ok = False
                _lot_escalate(
                    "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                    ic_prov_err or f"independent_matched_igg_controls[{ic_idx}] missing valid independent matched-IgG provenance",
                )
            ic_doses_raw = ic_item.get("matched_doses_ug_ml")
            if not isinstance(ic_doses_raw, list):
                ic_ok = False
                _lot_escalate(
                    "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                    f"independent_matched_igg_controls[{ic_idx}] missing matched_doses_ug_ml list covering {_XREACT_REQUIRED_DOSES_UG_ML}",
                )
            else:
                ic_doses: set[float] = set()
                for d_i, dv in enumerate(ic_doses_raw):
                    df, derr = _check_xreact_domain_number(
                        dv, f"{lot_id}.independent_matched_igg_controls[{ic_idx}].matched_doses_ug_ml[{d_i}]", lo=0.0, hi=None
                    )
                    if derr is not None or df is None:
                        ic_ok = False
                        _lot_escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", derr or "Invalid independent matched-IgG dose")
                    else:
                        ic_doses.add(df)
                miss_ic_doses = sorted(set(_XREACT_REQUIRED_DOSES_UG_ML) - ic_doses)
                if miss_ic_doses:
                    ic_ok = False
                    _lot_escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"independent_matched_igg_controls[{ic_idx}] missing required doses ug/mL: {miss_ic_doses}",
                    )
            ic_lysis, ic_lerr = _check_xreact_domain_number(
                ic_item.get("max_lysis_pct"),
                f"{lot_id}.independent_matched_igg_controls[{ic_idx}].max_lysis_pct",
                lo=0.0,
                hi=100.0,
            )
            if ic_lerr is not None or ic_lysis is None:
                ic_ok = False
                _lot_escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", ic_lerr or "Invalid independent matched-IgG max_lysis_pct")
            elif ic_lysis > 5.0:
                ic_ok = False
                _lot_escalate(
                    "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                    f"independent_matched_igg_controls[{ic_idx}].max_lysis_pct={ic_lysis:.2f}% > 5.0% baseline limit",
                )
            if ic_run_norm:
                if ic_ok and ic_cid is not None and ic_lysis is not None:
                    candidate_valid_ind_igg_by_run[ic_run_norm] = {
                        "control_lot_id": ic_cid,
                        "max_lysis_pct": ic_lysis,
                    }
                else:
                    conflicted_or_invalid_ind_igg_run_ids.add(ic_run_norm)
        valid_ind_igg_by_run: dict[str, dict[str, Any]] = {
            r: v for r, v in candidate_valid_ind_igg_by_run.items() if r not in conflicted_or_invalid_ind_igg_run_ids
        }

        # R06 B2 + R07 B4 + R08 B1: Two-pass order-independent reconciliation of lot_positive_controls.
        # Pass 1 scans ALL positive-control records for this lot, counting occurrences of each plate_or_run_id
        # and checking validity (exact lot_id match, non-empty plate_or_run_id, cd3>=90.0%, b6h12>=90.0%).
        # ANY plate_or_run_id with >1 record (duplicate/conflicting) OR any failing/invalid record is added to
        # conflicted_or_invalid_ctrl_run_ids and EXCLUDED from passing_ctrl_run_ids BEFORE biological adjudication
        # (so [pass, zero-CD3] and [zero-CD3, pass] produce identical HOLD_INVALID_OR_INCOMPLETE_ASSAY!).
        lot_pos_ctrl = lot.get("lot_positive_controls")
        lot_pos_ctrl_valid = True
        candidate_passing_ctrl_run_ids: set[str] = set()
        conflicted_or_invalid_ctrl_run_ids: set[str] = set()
        ctrl_run_counts: dict[str, int] = {}
        if isinstance(lot_pos_ctrl, dict):
            lpc_entries: list[Any] = [lot_pos_ctrl]
        elif isinstance(lot_pos_ctrl, list) and len(lot_pos_ctrl) > 0:
            lpc_entries = lot_pos_ctrl
        else:
            lpc_entries = []
            lot_pos_ctrl_valid = False
            _lot_escalate(
                "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                "Missing mandatory lot-specific lot_positive_controls block (dict or non-empty per-run list) bound to lot_id and plate_or_run_id",
            )

        # Pass 1a: Count occurrences of every non-empty plate_or_run_id across ALL records in lot_positive_controls
        for lpc_item in lpc_entries:
            if isinstance(lpc_item, dict):
                lpc_run = lpc_item.get("plate_or_run_id")
                lpc_run_c = lpc_run.strip() if type(lpc_run) is str else ""
                if lpc_run_c:
                    ctrl_run_counts[lpc_run_c] = ctrl_run_counts.get(lpc_run_c, 0) + 1

        for dup_run_id in sorted(r for r, cnt in ctrl_run_counts.items() if cnt > 1):
            lot_pos_ctrl_valid = False
            conflicted_or_invalid_ctrl_run_ids.add(dup_run_id)
            _lot_escalate(
                "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                f"Duplicate/conflicting plate_or_run_id={dup_run_id!r} inside lot_positive_controls (count={ctrl_run_counts[dup_run_id]}); run invalidated prior to biological adjudication",
            )

        # Pass 1b: Validate every entry and separate candidate passing runs from invalid/conflicted runs
        for lpc_idx, lpc_item in enumerate(lpc_entries):
            if not isinstance(lpc_item, dict):
                lot_pos_ctrl_valid = False
                _lot_escalate(
                    "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                    f"lot_positive_controls[{lpc_idx}] must be a dict (got {type(lpc_item).__name__})",
                )
                continue
            entry_ok = True
            lpc_lid = lpc_item.get("lot_id")
            if type(lpc_lid) is not str or lpc_lid.strip() != lot_id:
                entry_ok = False
                lot_pos_ctrl_valid = False
                _lot_escalate(
                    "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                    f"lot_positive_controls[{lpc_idx}].lot_id={lpc_lid!r} does not match parent lot_id={lot_id!r}",
                )
            lpc_run = lpc_item.get("plate_or_run_id")
            lpc_run_c = lpc_run.strip() if type(lpc_run) is str else ""
            if not lpc_run_c:
                entry_ok = False
                lot_pos_ctrl_valid = False
                _lot_escalate(
                    "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                    f"lot_positive_controls[{lpc_idx}].plate_or_run_id must be a non-empty string (got {lpc_run!r})",
                )
            elif ctrl_run_counts.get(lpc_run_c, 0) > 1:
                entry_ok = False
            lpc_cd3, lpc_cd3_err = _check_xreact_domain_number(
                lpc_item.get("cd3_pos_ctrl_pct"), f"{lot_id}.lot_positive_controls[{lpc_idx}].cd3_pos_ctrl_pct", lo=0.0, hi=100.0
            )
            if lpc_cd3_err is not None or lpc_cd3 is None:
                entry_ok = False
                lot_pos_ctrl_valid = False
                _lot_escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", lpc_cd3_err or "Invalid lot_positive_controls.cd3_pos_ctrl_pct")
            elif lpc_cd3 < 90.0:
                entry_ok = False
                lot_pos_ctrl_valid = False
                _lot_escalate(
                    "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                    f"Lot-specific CD3+ T-cell ATG positive control ({lpc_run_c or lpc_idx}) {lpc_cd3:.2f}% < 90.0% minimum lot activity threshold",
                )
            lpc_b6, lpc_b6_err = _check_xreact_domain_number(
                lpc_item.get("b6h12_pos_ctrl_pct"), f"{lot_id}.lot_positive_controls[{lpc_idx}].b6h12_pos_ctrl_pct", lo=0.0, hi=100.0
            )
            if lpc_b6_err is not None or lpc_b6 is None:
                entry_ok = False
                lot_pos_ctrl_valid = False
                _lot_escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", lpc_b6_err or "Invalid lot_positive_controls.b6h12_pos_ctrl_pct")
            elif lpc_b6 < 90.0:
                entry_ok = False
                lot_pos_ctrl_valid = False
                _lot_escalate(
                    "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                    f"Lot-specific B6H12 anti-CD47 positive control ({lpc_run_c or lpc_idx}) {lpc_b6:.2f}% < 90.0% minimum run dynamic-range threshold",
                )
            if lpc_run_c:
                if entry_ok:
                    candidate_passing_ctrl_run_ids.add(lpc_run_c)
                else:
                    conflicted_or_invalid_ctrl_run_ids.add(lpc_run_c)

        # Finalize Pass 1 strictly BEFORE adjudicating any observation or fab2_deconvolution row!
        passing_ctrl_run_ids: set[str] = candidate_passing_ctrl_run_ids - conflicted_or_invalid_ctrl_run_ids

        obs_list = lot.get("observations")
        if not isinstance(obs_list, list) or len(obs_list) == 0:
            _lot_escalate(
                "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                "Missing typed observations list (anonymous unindexed arrays are rejected fail-closed)",
            )
            per_lot_verdicts[lot_id] = {
                "lot_verdict": lot_state,
                "lot_positive_controls_verified": lot_pos_ctrl_valid,
                "covered_positive_control_run_ids": sorted(passing_ctrl_run_ids),
                "conflicted_or_invalid_positive_control_run_ids": sorted(conflicted_or_invalid_ctrl_run_ids),
                "independent_matched_igg_provenance_verified": False,
                "verified_independent_igg_control_run_ids": [],
                "conflicted_or_invalid_independent_igg_run_ids": sorted(conflicted_or_invalid_ind_igg_run_ids),
                "observed_run_ids": [],
                "endpoints": lot_endpoints,
            }
            continue

        # Pass 2a: Pre-scan observations to detect duplicate/conflicting (donor_id, stratum, dose_ug_ml) keys order-independently!
        obs_key_counts: dict[tuple[str, str, float], int] = {}
        for r_idx, rec in enumerate(obs_list):
            if not isinstance(rec, dict):
                continue
            raw_did = rec.get("donor_id")
            did_p = raw_did.strip() if type(raw_did) is str else ""
            raw_strat = rec.get("stratum")
            dose_p, dose_p_err = _check_xreact_domain_number(
                rec.get("dose_ug_ml"), f"{lot_id}.observations[{r_idx}].dose_ug_ml", lo=0.0, hi=None
            )
            if did_p and type(raw_strat) is str and raw_strat in _XREACT_REQUIRED_STRATA and dose_p_err is None and dose_p in _XREACT_REQUIRED_DOSES_UG_ML:
                k_p = (did_p, raw_strat, dose_p)
                obs_key_counts[k_p] = obs_key_counts.get(k_p, 0) + 1
        conflicted_obs_keys: set[tuple[str, str, float]] = {k for k, cnt in obs_key_counts.items() if cnt > 1}
        for c_did, c_strat, c_dose in sorted(conflicted_obs_keys):
            _lot_escalate(
                "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                f"Duplicate/conflicting donor observation rejected (excluded from biological adjudication): "
                f"donor_id={c_did!r}, stratum={c_strat}, dose={c_dose} (count={obs_key_counts[(c_did, c_strat, c_dose)]})",
            )

        # Pass 2b: Parse & index typed observations by (stratum, dose_ug_ml) -> {donor_id: validated_record}
        by_sd: dict[tuple[str, float], dict[str, dict[str, Any]]] = {}
        observed_run_ids: set[str] = set()
        observed_fab_run_ids: set[str] = set()
        excluded_invalid_control_rows = 0
        linked_endpoint_conflicts_quarantined = 0
        lot_inherited_invalid_global_igg = False
        lot_ind_igg_reconciliation_conflict = False
        lot_ind_igg_any_row_failed_provenance = False
        verified_ind_igg_run_ids_used: set[str] = set()
        for r_idx, rec in enumerate(obs_list):
            if not isinstance(rec, dict):
                _lot_escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", f"observations[{r_idx}] is not a dict")
                continue
            raw_did = rec.get("donor_id")
            if type(raw_did) is not str or not raw_did.strip():
                _lot_escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", f"observations[{r_idx}] missing non-empty string donor_id")
                continue
            did = raw_did.strip()

            raw_strat = rec.get("stratum")
            if type(raw_strat) is not str or raw_strat not in _XREACT_REQUIRED_STRATA:
                _lot_escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", f"observations[{r_idx}] invalid stratum: {raw_strat!r}")
                continue
            strat = raw_strat

            dose_val, dose_err = _check_xreact_domain_number(
                rec.get("dose_ug_ml"), f"{lot_id}.observations[{r_idx}].dose_ug_ml", lo=0.0, hi=None
            )
            if dose_err is not None or dose_val is None or dose_val not in _XREACT_REQUIRED_DOSES_UG_ML:
                _lot_escalate(
                    "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                    dose_err or f"observations[{r_idx}] dose_ug_ml={dose_val!r} not in required 5-point curve {_XREACT_REQUIRED_DOSES_UG_ML}",
                )
                continue

            dup_key = (did, strat, dose_val)
            is_conflicted_obs = dup_key in conflicted_obs_keys

            # R07 B4 + R08 B1: Require non-empty plate_or_run_id covered by finalized passing_ctrl_run_ids for this lot!
            obs_run_ctrl_valid = True
            raw_obs_run = rec.get("plate_or_run_id")
            obs_run_id = raw_obs_run.strip() if type(raw_obs_run) is str else ""
            if not obs_run_id:
                obs_run_ctrl_valid = False
                lot_pos_ctrl_valid = False
                _lot_escalate(
                    "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                    f"Observation {did}/{strat}/{dose_val} missing non-empty string plate_or_run_id",
                )
            else:
                observed_run_ids.add(obs_run_id)
                if obs_run_id not in passing_ctrl_run_ids:
                    obs_run_ctrl_valid = False
                    lot_pos_ctrl_valid = False
                    _lot_escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"Observation {did}/{strat}/{dose_val} plate_or_run_id={obs_run_id!r} not covered by passing lot_positive_controls (covered={sorted(passing_ctrl_run_ids)})",
                    )

            igg_baseline_valid = True
            if rec.get("control_matched_rabbit_igg") is not True:
                igg_baseline_valid = False
                _lot_escalate(
                    "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                    f"Missing matched normal rabbit IgG control flag for {did}/{strat}/{dose_val}",
                )

            # R08 B2 + R09 B1: Reconcile global normal_rabbit_igg_isotype_valid AND all lot/observation/nested
            # independent matched-IgG provenance declarations strictly BEFORE biological adjudication!
            # Explicit override semantics:
            #   - Every declared level (lot, observation, nested matched_rabbit_igg) must be unpadded & format-valid.
            #   - If > 1 level declares an independent matched-IgG lot ID, ALL declared levels MUST agree
            #     character-for-character (silent row-level override of a conflicting lot-level ID is PROHIBITED).
            #   - Every claimed independent matched-IgG ID MUST resolve to a verified, non-conflicted run control
            #     record in independent_matched_igg_controls for (lot_id, plate_or_run_id) with matching lot ID.
            row_ind_igg_valid, row_ind_igg_explicit_bad, row_ind_igg_id, row_ind_igg_err = _parse_independent_igg_provenance(
                rec, f"{lot_id}.{did}.{strat}.{dose_val}"
            )
            if row_ind_igg_err is not None:
                igg_baseline_valid = False
                lot_ind_igg_any_row_failed_provenance = True
                _lot_escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", row_ind_igg_err)

            igg_raw = rec.get("matched_rabbit_igg")
            nested_ind_igg_valid = False
            nested_ind_igg_explicit_bad = False
            nested_ind_igg_id: str | None = None
            if isinstance(igg_raw, dict):
                nested_ind_igg_valid, nested_ind_igg_explicit_bad, nested_ind_igg_id, nested_ind_igg_err = _parse_independent_igg_provenance(
                    igg_raw, f"{lot_id}.{did}.{strat}.{dose_val}.matched_rabbit_igg"
                )
                if nested_ind_igg_err is not None:
                    igg_baseline_valid = False
                    lot_ind_igg_any_row_failed_provenance = True
                    _lot_escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", nested_ind_igg_err)

            declared_ind_levels: list[tuple[str, str]] = []
            if lot_ind_igg_valid and lot_ind_igg_id is not None:
                declared_ind_levels.append(("lot", lot_ind_igg_id))
            if row_ind_igg_valid and row_ind_igg_id is not None:
                declared_ind_levels.append(("observation", row_ind_igg_id))
            if nested_ind_igg_valid and nested_ind_igg_id is not None:
                declared_ind_levels.append(("matched_rabbit_igg", nested_ind_igg_id))

            cross_level_ind_conflict = len({cid for _, cid in declared_ind_levels}) > 1
            if cross_level_ind_conflict:
                igg_baseline_valid = False
                lot_ind_igg_reconciliation_conflict = True
                lot_ind_igg_any_row_failed_provenance = True
                _lot_escalate(
                    "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                    f"Conflicting independent_matched_igg_isotype_lot_id across declaration levels "
                    f"({declared_ind_levels}) for {did}/{strat}/{dose_val}; silent row-level override prohibited",
                )

            explicit_ind_bad = (
                lot_ind_igg_explicit_bad
                or row_ind_igg_explicit_bad
                or nested_ind_igg_explicit_bad
                or cross_level_ind_conflict
            )
            has_independent_igg_provenance = False
            matched_ind_ctrl_max_lysis: float | None = None
            if explicit_ind_bad:
                igg_baseline_valid = False
                lot_ind_igg_any_row_failed_provenance = True
            elif declared_ind_levels:
                claimed_ind_id = declared_ind_levels[0][1]
                run_ind_ctrl = valid_ind_igg_by_run.get(obs_run_id)
                if run_ind_ctrl is None or run_ind_ctrl["control_lot_id"] != claimed_ind_id:
                    igg_baseline_valid = False
                    lot_ind_igg_any_row_failed_provenance = True
                    _lot_escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"Untraceable or mismatched independent_matched_igg_isotype_lot_id={claimed_ind_id!r} "
                        f"for run={obs_run_id!r} on {did}/{strat}/{dose_val} "
                        f"(requires matching verified non-conflicted record in independent_matched_igg_controls)",
                    )
                else:
                    has_independent_igg_provenance = True
                    matched_ind_ctrl_max_lysis = float(run_ind_ctrl["max_lysis_pct"])
                    verified_ind_igg_run_ids_used.add(obs_run_id)
            elif not global_matched_igg_valid:
                igg_baseline_valid = False
                lot_inherited_invalid_global_igg = True

            fab_flag_valid = True
            if rec.get("fab2_deconvolution_paired") is not True:
                fab_flag_valid = False
                _lot_escalate(
                    "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                    f"Missing paired F(ab')2 vs intact IgG deconvolution flag for {did}/{strat}/{dose_val}",
                )

            parsed_rec: dict[str, Any] = {
                "donor_id": did,
                "stratum": strat,
                "dose_ug_ml": dose_val,
                "plate_or_run_id": obs_run_id,
            }
            # R07 B6: Require direct HLA-E binding retention alongside CD47-SIRPa retention and complement/lysis!
            req_pct_fields = [
                "cd47_sirpa_retention_pct",
                "hla_e_binding_retention_pct",
                "c3d_pct",
                "c5b9_pct",
                "lysis_pct",
            ]
            if strat in _XREACT_CD64T_POS_STRATA:
                req_pct_fields.append("cd64t_displacement_pct")
            if strat in _XREACT_SC_ISLET_STRATA:
                req_pct_fields.append("sc_islet_viability_pct")
            if strat in _XREACT_IEC_STRATA:
                req_pct_fields.append("iec_viability_pct")

            for fkey in req_pct_fields:
                if fkey not in rec:
                    _lot_escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", f"Missing {fkey} for {did}/{strat}/{dose_val}")
                    continue
                fv, ferr = _check_xreact_domain_number(
                    rec[fkey], f"{lot_id}.{did}.{strat}.{dose_val}.{fkey}", lo=0.0, hi=100.0
                )
                if ferr is not None or fv is None:
                    _lot_escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", ferr or f"Invalid {fkey}")
                else:
                    parsed_rec[fkey] = fv

            if strat in _XREACT_SC_ISLET_STRATA:
                if "gsis_si" not in rec:
                    _lot_escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", f"Missing gsis_si for {did}/{strat}/{dose_val}")
                else:
                    gv, gerr = _check_xreact_domain_number(
                        rec["gsis_si"], f"{lot_id}.{did}.{strat}.{dose_val}.gsis_si", lo=0.0, hi=None
                    )
                    if gerr is not None or gv is None:
                        _lot_escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", gerr or "Invalid gsis_si")
                    else:
                        parsed_rec["gsis_si"] = gv

            # B1 + R06 B3 + R07 B5/B6 + R08 B2: Parse & validate required per-observation matched_rabbit_igg comparator!
            # Any compromised or missing matched normal rabbit IgG control marks this row invalid for biological FAIL!
            if not isinstance(igg_raw, dict):
                igg_baseline_valid = False
                _lot_escalate(
                    "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                    f"Missing numeric matched_rabbit_igg comparator object for {did}/{strat}/{dose_val}",
                )
            else:
                parsed_igg: dict[str, float] = {}
                for fkey in req_pct_fields:
                    if fkey not in igg_raw:
                        igg_baseline_valid = False
                        _lot_escalate(
                            "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                            f"Missing matched_rabbit_igg.{fkey} for {did}/{strat}/{dose_val}",
                        )
                        continue
                    iv, ierr = _check_xreact_domain_number(
                        igg_raw[fkey], f"{lot_id}.{did}.{strat}.{dose_val}.matched_rabbit_igg.{fkey}", lo=0.0, hi=100.0
                    )
                    if ierr is not None or iv is None:
                        igg_baseline_valid = False
                        _lot_escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", ierr or f"Invalid matched_rabbit_igg.{fkey}")
                    else:
                        parsed_igg[fkey] = iv
                if strat in _XREACT_SC_ISLET_STRATA:
                    if "gsis_si" not in igg_raw:
                        igg_baseline_valid = False
                        _lot_escalate(
                            "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                            f"Missing matched_rabbit_igg.gsis_si for {did}/{strat}/{dose_val}",
                        )
                    else:
                        igv, igerr = _check_xreact_domain_number(
                            igg_raw["gsis_si"], f"{lot_id}.{did}.{strat}.{dose_val}.matched_rabbit_igg.gsis_si", lo=0.0, hi=None
                        )
                        if igerr is not None or igv is None:
                            igg_baseline_valid = False
                            _lot_escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", igerr or "Invalid matched_rabbit_igg.gsis_si")
                        else:
                            parsed_igg["gsis_si"] = igv
                # R06 B3 + R07 B5/B6: Prespecified independent matched normal rabbit IgG baseline validity floors & caps at EVERY dose!
                if "cd47_sirpa_retention_pct" in parsed_igg and parsed_igg["cd47_sirpa_retention_pct"] < 80.0:
                    igg_baseline_valid = False
                    _lot_escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"Matched normal rabbit IgG CD47-SIRPa retention {parsed_igg['cd47_sirpa_retention_pct']:.2f}% < 80.0% minimum valid control baseline for {did}/{strat}/{dose_val}",
                    )
                if "hla_e_binding_retention_pct" in parsed_igg and parsed_igg["hla_e_binding_retention_pct"] < 80.0:
                    igg_baseline_valid = False
                    _lot_escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"Matched normal rabbit IgG HLA-E binding retention {parsed_igg['hla_e_binding_retention_pct']:.2f}% < 80.0% minimum valid control baseline for {did}/{strat}/{dose_val}",
                    )
                if "c3d_pct" in parsed_igg and parsed_igg["c3d_pct"] > 10.0:
                    igg_baseline_valid = False
                    _lot_escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"Matched normal rabbit IgG background C3d {parsed_igg['c3d_pct']:.2f}% > 10.0% control cap for {did}/{strat}/{dose_val}",
                    )
                if "c5b9_pct" in parsed_igg and parsed_igg["c5b9_pct"] > 10.0:
                    igg_baseline_valid = False
                    _lot_escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"Matched normal rabbit IgG background C5b-9 {parsed_igg['c5b9_pct']:.2f}% > 10.0% control cap for {did}/{strat}/{dose_val}",
                    )
                if "lysis_pct" in parsed_igg and parsed_igg["lysis_pct"] > 5.0:
                    igg_baseline_valid = False
                    _lot_escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"Matched normal rabbit IgG background lysis {parsed_igg['lysis_pct']:.2f}% > 5.0% baseline limit for {did}/{strat}/{dose_val}",
                    )
                if (
                    has_independent_igg_provenance
                    and matched_ind_ctrl_max_lysis is not None
                    and "lysis_pct" in parsed_igg
                    and parsed_igg["lysis_pct"] > matched_ind_ctrl_max_lysis + 0.05
                ):
                    igg_baseline_valid = False
                    lot_ind_igg_any_row_failed_provenance = True
                    _lot_escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"Matched rabbit IgG lysis {parsed_igg['lysis_pct']:.2f}% exceeds independent_matched_igg_controls max_lysis_pct={matched_ind_ctrl_max_lysis:.2f}% for run={obs_run_id!r}",
                    )
                if (
                    not has_independent_igg_provenance
                    and reported_iso_max_lysis is not None
                    and "lysis_pct" in parsed_igg
                    and parsed_igg["lysis_pct"] > reported_iso_max_lysis + 0.05
                ):
                    igg_baseline_valid = False
                    _lot_escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"Matched rabbit IgG lysis {parsed_igg['lysis_pct']:.2f}% exceeds reported controls.normal_rabbit_igg_max_lysis_pct={reported_iso_max_lysis:.2f}%",
                    )
                if strat in _XREACT_CD64T_POS_STRATA and "cd64t_displacement_pct" in parsed_igg and parsed_igg["cd64t_displacement_pct"] > 10.0:
                    igg_baseline_valid = False
                    _lot_escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"Matched normal rabbit IgG negative-control CD64t displacement {parsed_igg['cd64t_displacement_pct']:.2f}% > 10.0% baseline limit for {did}/{strat}/{dose_val}",
                    )
                if strat in _XREACT_SC_ISLET_STRATA and "sc_islet_viability_pct" in parsed_igg and parsed_igg["sc_islet_viability_pct"] < 80.0:
                    igg_baseline_valid = False
                    _lot_escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"Matched normal rabbit IgG SC-islet viability {parsed_igg['sc_islet_viability_pct']:.2f}% < 80.0% minimum valid control baseline for {did}/{strat}/{dose_val}",
                    )
                if strat in _XREACT_IEC_STRATA and "iec_viability_pct" in parsed_igg and parsed_igg["iec_viability_pct"] < 80.0:
                    igg_baseline_valid = False
                    _lot_escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"Matched normal rabbit IgG iEC viability {parsed_igg['iec_viability_pct']:.2f}% < 80.0% minimum valid control baseline for {did}/{strat}/{dose_val}",
                    )
                if strat in _XREACT_SC_ISLET_STRATA and "gsis_si" in parsed_igg and parsed_igg["gsis_si"] < 2.5:
                    igg_baseline_valid = False
                    _lot_escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"Matched normal rabbit IgG control GSIS SI {parsed_igg['gsis_si']:.3f} < 2.5 minimum baseline for {did}/{strat}/{dose_val}",
                    )
                parsed_rec["matched_rabbit_igg"] = parsed_igg

            # B2 + R07 B4/B5 + R08 B1/B2 + R10 B3 + R16 B1 + R17 B1: Parse & link required lot-/donor-/run-linked
            # fab2_deconvolution observations, requiring established same-run (lot_id, donor_id, stratum, dose) identity,
            # valid provenance, AND per-endpoint linked Fab vehicle qualification BEFORE any nested Fab row's intact_igg
            # copy can quarantine a qualified primary endpoint!
            fab_obs = rec.get("fab2_deconvolution")
            fab_row_valid = fab_flag_valid and global_fab_ctrl_valid
            fab_row_valid_pre_discord = False
            is_cross_run_fab = False
            candidate_conflicted_linked_endpoints: dict[str, tuple[str, float, float]] = {}
            if not isinstance(fab_obs, dict):
                fab_row_valid = False
                _lot_escalate(
                    "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                    f"Missing lot-/donor-linked fab2_deconvolution record for {did}/{strat}/{dose_val}",
                )
            else:
                fab_linkage_identity_ok = True
                fab_provenance_ok = fab_flag_valid and global_fab_ctrl_valid
                f_lid = fab_obs.get("lot_id")
                f_did = fab_obs.get("donor_id")
                f_str = fab_obs.get("stratum")
                f_dose, f_derr = _check_xreact_domain_number(
                    fab_obs.get("dose_ug_ml"), f"{lot_id}.{did}.{strat}.{dose_val}.fab2_deconvolution.dose_ug_ml", lo=0.0, hi=None
                )
                if f_lid != lot_id or f_did != did or f_str != strat or f_derr is not None or f_dose != dose_val:
                    fab_linkage_identity_ok = False
                    fab_row_valid = False
                    _lot_escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"Mismatched fab2_deconvolution linkage ({f_lid!r}/{f_did!r}/{f_str!r}/{f_dose!r}) vs ({lot_id!r}/{did!r}/{strat!r}/{dose_val!r})",
                    )
                raw_fab_run = fab_obs.get("plate_or_run_id")
                fab_run_id = raw_fab_run.strip() if type(raw_fab_run) is str else ""
                if not fab_run_id:
                    fab_provenance_ok = False
                    fab_row_valid = False
                    lot_pos_ctrl_valid = False
                    _lot_escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"fab2_deconvolution {did}/{strat}/{dose_val} missing non-empty string plate_or_run_id",
                    )
                else:
                    observed_fab_run_ids.add(fab_run_id)
                    if fab_run_id not in passing_ctrl_run_ids:
                        fab_provenance_ok = False
                        fab_row_valid = False
                        lot_pos_ctrl_valid = False
                        _lot_escalate(
                            "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                            f"fab2_deconvolution {did}/{strat}/{dose_val} plate_or_run_id={fab_run_id!r} not covered by passing lot_positive_controls (covered={sorted(passing_ctrl_run_ids)})",
                        )

                # R13 0037-B1 (Pure Subtraction): Cross-run fab2_deconvolution (fab_run_id != obs_run_id) has no
                # donor-, stratum-, and dose-matched quantitative matched_rabbit_igg comparator measured on fab_run_id
                # (pairing fab_run signal against obs_run's matched_rabbit_igg in paired AUC is invalid).
                # UNCONDITIONALLY withhold biological adjudication for ALL cross-run fab2_deconvolution endpoints
                # (fab_run_id != obs_run_id -> HOLD_INVALID_OR_INCOMPLETE_ASSAY, fab_row_valid = False, zero [FAIL]
                # reasons on cross-run Fab, while preserving separate valid same-run biological FAIL)!
                fab_ind_igg_valid, fab_ind_igg_explicit_bad, fab_ind_igg_id, fab_ind_igg_err = _parse_independent_igg_provenance(
                    fab_obs, f"{lot_id}.{did}.{strat}.{dose_val}.fab2_deconvolution"
                )
                if fab_ind_igg_err is not None:
                    fab_provenance_ok = False
                    fab_row_valid = False
                    lot_ind_igg_any_row_failed_provenance = True
                    _lot_escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", fab_ind_igg_err)
                fab_level_conflict = bool(
                    fab_ind_igg_valid
                    and fab_ind_igg_id is not None
                    and lot_ind_igg_valid
                    and lot_ind_igg_id is not None
                    and fab_ind_igg_id != lot_ind_igg_id
                )
                if fab_level_conflict:
                    fab_provenance_ok = False
                    fab_row_valid = False
                    lot_ind_igg_reconciliation_conflict = True
                    lot_ind_igg_any_row_failed_provenance = True
                    _lot_escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"Conflicting independent_matched_igg_isotype_lot_id between lot={lot_ind_igg_id!r} and "
                        f"fab2_deconvolution={fab_ind_igg_id!r} for {did}/{strat}/{dose_val}; silent override prohibited",
                    )
                if fab_run_id and fab_run_id in conflicted_or_invalid_ind_igg_run_ids:
                    fab_provenance_ok = False
                    fab_row_valid = False
                    lot_ind_igg_any_row_failed_provenance = True
                    _lot_escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"fab2_deconvolution {did}/{strat}/{dose_val} plate_or_run_id={fab_run_id!r} "
                        f"references a conflicted or invalid independent_matched_igg_controls run; "
                        f"linked Fab endpoint excluded from biological adjudication",
                    )
                if fab_run_id and fab_run_id != obs_run_id:
                    is_cross_run_fab = True
                    fab_provenance_ok = False
                    fab_row_valid = False
                    _lot_escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"CROSS_RUN_FAB_DECONVOLUTION_UNSUPPORTED_REQUIRES_SAME_RUN_PAIRED_CONTROL: "
                        f"fab2_deconvolution {did}/{strat}/{dose_val} plate_or_run_id={fab_run_id!r} != "
                        f"observation plate_or_run_id={obs_run_id!r}; paired quantitative (donor, stratum, dose) "
                        f"matched_rabbit_igg comparator must be measured on the SAME run (fab_run == obs_run); "
                        f"linked Fab point and paired-AUC biological adjudication withheld",
                    )
                elif fab_run_id and (fab_ind_igg_valid or fab_ind_igg_explicit_bad):
                    if (
                        fab_ind_igg_explicit_bad
                        or fab_level_conflict
                        or (not explicit_ind_bad and declared_ind_levels and fab_ind_igg_id != declared_ind_levels[0][1])
                    ):
                        fab_provenance_ok = False
                        fab_row_valid = False
                        lot_ind_igg_reconciliation_conflict = True
                        lot_ind_igg_any_row_failed_provenance = True
                        _lot_escalate(
                            "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                            f"Conflicting/invalid fab2_deconvolution independent_matched_igg_isotype_lot_id="
                            f"{fab_ind_igg_id!r} on same run={fab_run_id!r} for {did}/{strat}/{dose_val}",
                        )
                    else:
                        same_run_ctrl = valid_ind_igg_by_run.get(fab_run_id)
                        if same_run_ctrl is None or same_run_ctrl["control_lot_id"] != fab_ind_igg_id:
                            fab_provenance_ok = False
                            fab_row_valid = False
                            lot_ind_igg_any_row_failed_provenance = True
                            _lot_escalate(
                                "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                                f"Untraceable fab2_deconvolution independent_matched_igg_isotype_lot_id="
                                f"{fab_ind_igg_id!r} for run={fab_run_id!r} on {did}/{strat}/{dose_val}",
                            )
                fab_same_run_linked_and_provenance_valid = bool(
                    fab_linkage_identity_ok
                    and fab_provenance_ok
                    and not is_cross_run_fab
                    and bool(fab_run_id)
                    and bool(obs_run_id)
                    and fab_run_id == obs_run_id
                )
                parsed_fab: dict[str, float] = {}
                for fk, primary_k in (
                    ("intact_igg_c3d_pct", "c3d_pct"),
                    ("intact_igg_c5b9_pct", "c5b9_pct"),
                    ("intact_igg_lysis_pct", "lysis_pct"),
                ):
                    fv, ferr = _check_xreact_domain_number(
                        fab_obs.get(fk), f"{lot_id}.{did}.{strat}.{dose_val}.fab2_deconvolution.{fk}", lo=0.0, hi=100.0
                    )
                    if ferr is not None or fv is None:
                        fab_row_valid = False
                        _lot_escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", ferr or f"Missing/invalid fab2_deconvolution.{fk}")
                    else:
                        parsed_fab[fk] = fv
                for fk in ("fab2_c3d_pct", "fab2_c5b9_pct", "fab2_lysis_pct"):
                    fv, ferr = _check_xreact_domain_number(
                        fab_obs.get(fk), f"{lot_id}.{did}.{strat}.{dose_val}.fab2_deconvolution.{fk}", lo=0.0, hi=100.0
                    )
                    if ferr is not None or fv is None:
                        fab_row_valid = False
                        _lot_escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", ferr or f"Missing/invalid fab2_deconvolution.{fk}")
                    else:
                        parsed_fab[fk] = fv
                fab_row_valid_pre_discord = fab_row_valid
                for fk, primary_k in (
                    ("intact_igg_c3d_pct", "c3d_pct"),
                    ("intact_igg_c5b9_pct", "c5b9_pct"),
                    ("intact_igg_lysis_pct", "lysis_pct"),
                ):
                    if (
                        fab_same_run_linked_and_provenance_valid
                        and fk in parsed_fab
                        and primary_k in parsed_rec
                        and abs(parsed_fab[fk] - parsed_rec[primary_k]) > 1e-6
                    ):
                        fab_row_valid = False
                        candidate_conflicted_linked_endpoints[primary_k] = (
                            fk,
                            parsed_fab[fk],
                            parsed_rec[primary_k],
                        )
                parsed_rec["fab2_deconvolution"] = parsed_fab

            if is_conflicted_obs:
                excluded_invalid_control_rows += 1
                continue

            row_ctrl_valid_for_bio = obs_run_ctrl_valid and igg_baseline_valid
            fab_ctrl_valid_for_bio = row_ctrl_valid_for_bio and fab_row_valid
            parsed_rec["_control_valid_for_bio"] = row_ctrl_valid_for_bio
            parsed_rec["_fab_control_valid_for_bio"] = fab_ctrl_valid_for_bio
            parsed_rec["_fab_pre_discord_valid"] = row_ctrl_valid_for_bio and fab_row_valid_pre_discord
            parsed_rec["_is_cross_run_fab"] = is_cross_run_fab
            parsed_rec["_candidate_conflicted_linked_endpoints"] = candidate_conflicted_linked_endpoints
            parsed_rec["_conflicted_linked_endpoints"] = frozenset()
            if not row_ctrl_valid_for_bio:
                excluded_invalid_control_rows += 1

            by_sd.setdefault((strat, dose_val), {})[did] = parsed_rec

        if lot_inherited_invalid_global_igg:
            _lot_escalate(
                "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                "Inherits invalid global normal_rabbit_igg_isotype_valid control without independent per-lot/per-row matched IgG provenance; inheriting rows excluded from biological FAIL adjudication",
            )

        # B1(a): Check complete 5-dose x 4-stratum coverage AND ONE consistent crossed paired donor panel!
        distinct_donors_by_cell: dict[str, int] = {}
        cell_donor_sets: list[set[str]] = []
        for strat in _XREACT_REQUIRED_STRATA:
            for dose in _XREACT_REQUIRED_DOSES_UG_ML:
                cell = by_sd.get((strat, dose), {})
                distinct_donors_by_cell[f"{strat}@{dose:g}"] = len(cell)
                cell_donor_sets.append(set(cell.keys()))
                if len(cell) < 6:
                    _lot_escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"Incomplete donor coverage in {strat} at {dose:g} ug/mL: {len(cell)} distinct donor_ids (< 6 required)",
                    )

        union_donors: set[str] = set().union(*cell_donor_sets) if cell_donor_sets else set()
        common_donors: set[str] = set.intersection(*cell_donor_sets) if cell_donor_sets else set()
        crossed_panel_exact_match = (len(common_donors) >= 6 and common_donors == union_donors)
        if not crossed_panel_exact_match:
            _lot_escalate(
                "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                f"Disconnected or unpaired donor panel across 4 strata x 5 doses: "
                f"{len(common_donors)} donors appear in all 20 cells vs {len(union_donors)} union donor_ids (exact crossed panel >= 6 required)",
            )

        # Helper to evaluate upper-bounded toxicity endpoints (c3d_pct, c5b9_pct, lysis_pct)
        def _eval_upper_5_8(vals: list[float], lbl: str) -> tuple[str, dict[str, Any]]:
            mean, l95, u95, mn, mx = _mean_and_t95_ci(vals, lbl)
            if l95 > 5.0:
                st = "FAIL"
            elif u95 <= 5.0 and mx <= 8.0:
                st = "PASS"
            elif mx > 8.0 and l95 <= 5.0:
                st = "HOLD_UNCLASSIFIED_DONOR_OUTLIER_REQUIRES_INVESTIGATION"
            elif l95 <= 5.0 < u95:
                st = "HOLD"
            else:
                st = "HOLD_UNCLASSIFIED_DONOR_OUTLIER_REQUIRES_INVESTIGATION"
            return st, {
                "verdict": st,
                "n_distinct_donors": len(vals),
                "mean": round(mean, 4),
                "l95_t": round(l95, 4),
                "u95_t": round(u95, 4),
                "max_donor": round(mx, 4),
            }

        # Helper to evaluate CD47-SIRPa retention
        def _eval_cd47(vals: list[float], lbl: str) -> tuple[str, dict[str, Any]]:
            mean, l95, u95, mn, mx = _mean_and_t95_ci(vals, lbl)
            n_lt_75 = sum(1 for x in vals if x < 75.0)
            n_75_80 = sum(1 for x in vals if 75.0 <= x < 80.0)
            if u95 < 85.0 or n_lt_75 >= 2:
                st = "FAIL"
            elif l95 >= 85.0 and mn >= 80.0:
                st = "PASS"
            elif n_lt_75 == 1 and l95 >= 85.0:
                st = "HOLD_UNCLASSIFIED_DONOR_OUTLIER_REQUIRES_INVESTIGATION"
            elif (l95 < 85.0 <= u95) or (n_75_80 == 1 and n_lt_75 == 0):
                st = "HOLD"
            else:
                st = "HOLD_UNCLASSIFIED_DONOR_OUTLIER_REQUIRES_INVESTIGATION"
            return st, {
                "verdict": st,
                "n_distinct_donors": len(vals),
                "mean": round(mean, 4),
                "l95_t": round(l95, 4),
                "u95_t": round(u95, 4),
                "min_donor": round(mn, 4),
            }

        # R07 B6: Helpers to evaluate direct HLA-E binding retention (absolute >= 80.0% PASS / < 70.0% FAIL
        # and paired ATG / IgG >= 0.85 [85.0%] PASS / < 70.0% FAIL; identical structure to CD47-SIRPa!)
        def _eval_hla_e_abs(vals: list[float], lbl: str) -> tuple[str, dict[str, Any]]:
            mean, l95, u95, mn, mx = _mean_and_t95_ci(vals, lbl)
            n_lt_70 = sum(1 for x in vals if x < 70.0)
            if u95 < 70.0 or n_lt_70 >= 2:
                st = "FAIL"
            elif l95 >= 80.0 and mn >= 80.0:
                st = "PASS"
            elif n_lt_70 == 1 and l95 >= 80.0:
                st = "HOLD_UNCLASSIFIED_DONOR_OUTLIER_REQUIRES_INVESTIGATION"
            elif n_lt_70 == 0:
                st = "HOLD"
            else:
                st = "HOLD_UNCLASSIFIED_DONOR_OUTLIER_REQUIRES_INVESTIGATION"
            return st, {
                "verdict": st,
                "n_distinct_donors": len(vals),
                "mean": round(mean, 4),
                "l95_t": round(l95, 4),
                "u95_t": round(u95, 4),
                "min_donor": round(mn, 4),
            }

        def _eval_hla_e_paired(vals: list[float], lbl: str) -> tuple[str, dict[str, Any]]:
            mean, l95, u95, mn, mx = _mean_and_t95_ci(vals, lbl)
            n_lt_70 = sum(1 for x in vals if x < 70.0)
            if u95 < 70.0 or n_lt_70 >= 2:
                st = "FAIL"
            elif l95 >= 85.0 and mn >= 80.0:
                st = "PASS"
            elif n_lt_70 == 1 and l95 >= 85.0:
                st = "HOLD_UNCLASSIFIED_DONOR_OUTLIER_REQUIRES_INVESTIGATION"
            elif n_lt_70 == 0:
                st = "HOLD"
            else:
                st = "HOLD_UNCLASSIFIED_DONOR_OUTLIER_REQUIRES_INVESTIGATION"
            return st, {
                "verdict": st,
                "n_distinct_donors": len(vals),
                "mean": round(mean, 4),
                "l95_t": round(l95, 4),
                "u95_t": round(u95, 4),
                "min_donor": round(mn, 4),
            }

        # Helper to evaluate CD64t displacement
        def _eval_disp(vals: list[float], lbl: str) -> tuple[str, dict[str, Any]]:
            mean, l95, u95, mn, mx = _mean_and_t95_ci(vals, lbl)
            if l95 > 20.0:
                st = "FAIL"
            elif u95 <= 20.0 and mx <= 25.0:
                st = "PASS"
            elif mx > 25.0 and l95 <= 20.0:
                st = "HOLD_UNCLASSIFIED_DONOR_OUTLIER_REQUIRES_INVESTIGATION"
            elif l95 <= 20.0 < u95:
                st = "HOLD"
            else:
                st = "HOLD_UNCLASSIFIED_DONOR_OUTLIER_REQUIRES_INVESTIGATION"
            return st, {
                "verdict": st,
                "n_distinct_donors": len(vals),
                "mean": round(mean, 4),
                "l95_t": round(l95, 4),
                "u95_t": round(u95, 4),
                "max_donor": round(mx, 4),
            }

        # Helper to evaluate separate viability endpoints (SC-islet and iEC)
        def _eval_viab(vals: list[float], lbl: str) -> tuple[str, dict[str, Any]]:
            mean, l95, u95, mn, mx = _mean_and_t95_ci(vals, lbl)
            if u95 < 85.0:
                st = "FAIL"
            elif l95 >= 90.0:
                st = "PASS"
            else:
                st = "HOLD_UNCLASSIFIED_DONOR_OUTLIER_REQUIRES_INVESTIGATION"
            return st, {
                "verdict": st,
                "n_distinct_donors": len(vals),
                "mean": round(mean, 4),
                "l95_t": round(l95, 4),
                "u95_t": round(u95, 4),
                "min_donor": round(mn, 4),
            }

        # Helper to evaluate separate dynamic GSIS SI endpoint
        def _eval_gsis(vals: list[float], lbl: str) -> tuple[str, dict[str, Any]]:
            mean, l95, u95, mn, mx = _mean_and_t95_ci(vals, lbl)
            if mn < 2.0:
                st = "FAIL"
            elif mn >= 2.5:
                st = "PASS"
            else:
                st = "HOLD_UNCLASSIFIED_DONOR_OUTLIER_REQUIRES_INVESTIGATION"
            return st, {
                "verdict": st,
                "n_distinct_donors": len(vals),
                "mean": round(mean, 4),
                "l95_t": round(l95, 4),
                "u95_t": round(u95, 4),
                "min_gsis_si": round(mn, 4),
            }

        # Helper to evaluate paired GSIS ATG/IgG ratios (per-dose and trapezoidal AUC_ATG / AUC_IgG)
        def _eval_gsis_paired_ratio(ratios: list[float], lbl: str) -> tuple[str, dict[str, Any]]:
            mean, l95, u95, mn, mx = _mean_and_t95_ci(ratios, lbl)
            if u95 < 0.70 or mn < 0.65:
                st = "FAIL"
            elif l95 >= 0.85 and mn >= 0.85:
                st = "PASS"
            elif mn < 0.70 and l95 >= 0.85:
                st = "HOLD_UNCLASSIFIED_DONOR_OUTLIER_REQUIRES_INVESTIGATION"
            else:
                st = "HOLD"
            return st, {
                "verdict": st,
                "n_distinct_donors": len(ratios),
                "mean_ratio": round(mean, 4),
                "l95_t_ratio": round(l95, 4),
                "u95_t_ratio": round(u95, 4),
                "min_donor_ratio": round(mn, 4),
            }

        # R11 B3 + R12 0037-B1: Validate 0.0 ug/mL vehicle control baselines AND positive-control / matched-IgG
        # control validity flags (for BOTH observation and linked Fab endpoints!) strictly BEFORE point-level,
        # 1..15 ug/mL AUC, AND 0..50 ug/mL AUC biological adjudication! Any (stratum, donor_id, endpoint) series
        # whose 0.0 ug/mL vehicle control fails positive-control, matched-IgG, or baseline sanity (or is missing
        # or conflicted) is quarantined to HOLD_INVALID_OR_INCOMPLETE_ASSAY and EXCLUDED from biological
        # adjudication (NEVER triggering permanent biological FAIL from a failed vehicle!), while preserving
        # biological FAIL on separate independently validated series/strata/lots.
        invalid_vehicle_endpoints_by_sd: dict[tuple[str, str], set[str]] = {}
        vehicle_series_quarantined = 0
        for strat in _XREACT_REQUIRED_STRATA:
            obs_veh_eps: set[str] = {
                "c3d_pct",
                "c5b9_pct",
                "lysis_pct",
                "cd47_sirpa_retention_pct",
                "hla_e_binding_retention_pct",
            }
            if strat in _XREACT_CD64T_POS_STRATA:
                obs_veh_eps.add("cd64t_displacement_pct")
            if strat in _XREACT_SC_ISLET_STRATA:
                obs_veh_eps.update({"sc_islet_viability_pct", "gsis_si"})
            if strat in _XREACT_IEC_STRATA:
                obs_veh_eps.add("iec_viability_pct")
            fab_veh_eps: set[str] = {"fab2_c3d_pct", "fab2_c5b9_pct", "fab2_lysis_pct"}
            vcell = by_sd.get((strat, 0.0), {})
            for did_v, vrec in sorted(vcell.items()):
                bad_v_eps: set[str] = set()
                v_obs_ctrl_ok = vrec.get("_control_valid_for_bio") is True
                v_fab_pre_discord_ok = vrec.get("_fab_pre_discord_valid") is True
                if not v_obs_ctrl_ok:
                    bad_v_eps.update(obs_veh_eps)
                    bad_v_eps.update(fab_veh_eps)
                    _lot_escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"Vehicle 0 ug/mL observation row failed positive-control or matched-IgG validation for "
                        f"{did_v}/{strat}; all dependent endpoint series quarantined prior to point, 1-15 AUC, "
                        f"and 0-50 AUC biological adjudication",
                    )
                elif not v_fab_pre_discord_ok:
                    bad_v_eps.update(fab_veh_eps)
                    _lot_escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"Vehicle 0 ug/mL linked fab2_deconvolution row failed positive-control or matched-IgG "
                        f"validation for {did_v}/{strat}; linked Fab endpoint series quarantined prior to point, "
                        f"1-15 AUC, and 0-50 AUC biological adjudication",
                    )
                for fkey in ("c3d_pct", "c5b9_pct", "lysis_pct"):
                    if fkey not in vrec:
                        bad_v_eps.add(fkey)
                    elif vrec[fkey] > 5.0:
                        bad_v_eps.add(fkey)
                        _lot_escalate(
                            "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                            f"Vehicle 0 ug/mL baseline {fkey}={vrec[fkey]:.3f}% > 5.0% for {did_v}/{strat}; "
                            f"affected series quarantined prior to biological point and 0-50 AUC adjudication",
                        )
                fab_v = vrec.get("fab2_deconvolution")
                for fab_k in ("fab2_c3d_pct", "fab2_c5b9_pct", "fab2_lysis_pct"):
                    if not isinstance(fab_v, dict) or fab_k not in fab_v:
                        bad_v_eps.add(fab_k)
                    elif fab_v[fab_k] > 5.0:
                        bad_v_eps.add(fab_k)
                        _lot_escalate(
                            "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                            f"Vehicle 0 ug/mL baseline {fab_k}={fab_v[fab_k]:.3f}% > 5.0% for {did_v}/{strat}; "
                            f"affected linked Fab series quarantined prior to biological point and 0-50 AUC adjudication",
                        )
                if "cd47_sirpa_retention_pct" not in vrec:
                    bad_v_eps.add("cd47_sirpa_retention_pct")
                elif vrec["cd47_sirpa_retention_pct"] < 85.0:
                    bad_v_eps.add("cd47_sirpa_retention_pct")
                    _lot_escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"Vehicle 0 ug/mL baseline cd47_sirpa_retention_pct={vrec['cd47_sirpa_retention_pct']:.3f}% < 85.0% "
                        f"for {did_v}/{strat}; affected series quarantined prior to biological adjudication",
                    )
                if "hla_e_binding_retention_pct" not in vrec:
                    bad_v_eps.add("hla_e_binding_retention_pct")
                elif vrec["hla_e_binding_retention_pct"] < 80.0:
                    bad_v_eps.add("hla_e_binding_retention_pct")
                    _lot_escalate(
                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                        f"Vehicle 0 ug/mL baseline hla_e_binding_retention_pct={vrec['hla_e_binding_retention_pct']:.3f}% < 80.0% "
                        f"for {did_v}/{strat}; affected series quarantined prior to biological adjudication",
                    )
                if strat in _XREACT_CD64T_POS_STRATA:
                    if "cd64t_displacement_pct" not in vrec:
                        bad_v_eps.add("cd64t_displacement_pct")
                    elif vrec["cd64t_displacement_pct"] > 10.0:
                        bad_v_eps.add("cd64t_displacement_pct")
                        _lot_escalate(
                            "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                            f"Vehicle 0 ug/mL baseline cd64t_displacement_pct={vrec['cd64t_displacement_pct']:.3f}% > 10.0% "
                            f"for {did_v}/{strat}; affected series quarantined prior to biological adjudication",
                        )
                if strat in _XREACT_SC_ISLET_STRATA:
                    if "sc_islet_viability_pct" not in vrec:
                        bad_v_eps.add("sc_islet_viability_pct")
                    elif vrec["sc_islet_viability_pct"] < 85.0:
                        bad_v_eps.add("sc_islet_viability_pct")
                        _lot_escalate(
                            "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                            f"Vehicle 0 ug/mL SC-islet viability={vrec['sc_islet_viability_pct']:.3f}% < 85.0% "
                            f"for {did_v}/{strat}; affected series quarantined prior to biological adjudication",
                        )
                    if "gsis_si" not in vrec:
                        bad_v_eps.add("gsis_si")
                    elif vrec["gsis_si"] < 2.5:
                        bad_v_eps.add("gsis_si")
                        _lot_escalate(
                            "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                            f"Vehicle 0 ug/mL GSIS SI={vrec['gsis_si']:.3f} < 2.5 "
                            f"for {did_v}/{strat}; affected series quarantined prior to biological adjudication",
                        )
                if strat in _XREACT_IEC_STRATA:
                    if "iec_viability_pct" not in vrec:
                        bad_v_eps.add("iec_viability_pct")
                    elif vrec["iec_viability_pct"] < 85.0:
                        bad_v_eps.add("iec_viability_pct")
                        _lot_escalate(
                            "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                            f"Vehicle 0 ug/mL iEC viability={vrec['iec_viability_pct']:.3f}% < 85.0% "
                            f"for {did_v}/{strat}; affected series quarantined prior to biological adjudication",
                        )
                if bad_v_eps:
                    invalid_vehicle_endpoints_by_sd[(strat, did_v)] = bad_v_eps
                    vehicle_series_quarantined += len(bad_v_eps)

        # R17 B1: Qualify linked Fab vehicle per endpoint STRICTLY BEFORE applying same-run intact-IgG discordance
        # quarantine to primary XREACT series! Vehicle-valid same-run intact-IgG conflicts still quarantine the
        # disputed primary endpoint to HOLD, whereas an invalid linked Fab vehicle NEVER quarantines or suppresses
        # a qualified primary FAIL!
        def _fab_veh_qualified_pre_discord(strat_k: str, did_k: str, fab_k: str) -> bool:
            vrec_k = by_sd.get((strat_k, 0.0), {}).get(did_k)
            if not isinstance(vrec_k, dict):
                return False
            if vrec_k.get("_control_valid_for_bio") is not True:
                return False
            if vrec_k.get("_fab_pre_discord_valid") is not True:
                return False
            return fab_k not in invalid_vehicle_endpoints_by_sd.get((strat_k, did_k), ())

        _primary_to_fab_ep = {
            "c3d_pct": "fab2_c3d_pct",
            "c5b9_pct": "fab2_c5b9_pct",
            "lysis_pct": "fab2_lysis_pct",
        }
        for (strat_c, dose_c), cell_c in sorted(by_sd.items()):
            for did_c, rec_c in sorted(cell_c.items()):
                cand_map = rec_c.get("_candidate_conflicted_linked_endpoints")
                if not cand_map:
                    continue
                active_conf: set[str] = set()
                for primary_k, (fk, fv, pv) in sorted(cand_map.items()):
                    fab_k = _primary_to_fab_ep[primary_k]
                    if _fab_veh_qualified_pre_discord(strat_c, did_c, fab_k):
                        active_conf.add(primary_k)
                        _lot_escalate(
                            "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                            f"fab2_deconvolution.{fk}={fv:.3f}% contradicts primary {primary_k}={pv:.3f}% "
                            f"for {did_c}/{strat_c}/{dose_c}; disputed endpoint quarantined from biological point and AUC adjudication",
                        )
                        if dose_c == 0.0:
                            s_bad = invalid_vehicle_endpoints_by_sd.setdefault((strat_c, did_c), set())
                            if primary_k not in s_bad:
                                s_bad.add(primary_k)
                                vehicle_series_quarantined += 1
                    else:
                        _lot_escalate(
                            "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                            f"fab2_deconvolution.{fk}={fv:.3f}% disagrees with primary {primary_k}={pv:.3f}% "
                            f"for {did_c}/{strat_c}/{dose_c}, but linked Fab vehicle for {fab_k} is invalid; "
                            f"linked Fab row remains withheld without quarantining qualified primary {primary_k}",
                        )
                if active_conf:
                    rec_c["_conflicted_linked_endpoints"] = frozenset(active_conf)
                    linked_endpoint_conflicts_quarantined += len(active_conf)

        def _veh_ok(strat_k: str, did_k: str, ep_k: str) -> bool:
            vrec_k = by_sd.get((strat_k, 0.0), {}).get(did_k)
            if not isinstance(vrec_k, dict):
                return False
            if vrec_k.get("_control_valid_for_bio") is not True:
                return False
            if ep_k.startswith("fab2_") and vrec_k.get("_fab_control_valid_for_bio") is not True:
                return False
            return ep_k not in invalid_vehicle_endpoints_by_sd.get((strat_k, did_k), ())

        # R16 M1: Aggregate adjudicable direct F(ab')2 maxima STRICTLY AFTER _veh_ok vehicle qualification,
        # disclosing withheld cross-run AND invalid-vehicle Fab maxima separately so no invalid-vehicle Fab row
        # (e.g., 6.0% Fab C3d at dose 0.0) ever enters derived_direct_fab_maxima_pct!
        for (strat_agg, _dose_agg), cell_agg in sorted(by_sd.items()):
            for did_agg, rec_agg in sorted(cell_agg.items()):
                pfab = rec_agg.get("fab2_deconvolution")
                if isinstance(pfab, dict):
                    if rec_agg.get("_is_cross_run_fab") is True:
                        withheld_cross_run_fab_rows_count += 1
                        for fk, w_list in (
                            ("fab2_c3d_pct", withheld_cross_run_fab_c3d),
                            ("fab2_c5b9_pct", withheld_cross_run_fab_c5b9),
                            ("fab2_lysis_pct", withheld_cross_run_fab_lysis),
                        ):
                            if fk in pfab:
                                w_list.append(pfab[fk])
                    elif rec_agg.get("_fab_control_valid_for_bio") is True:
                        row_had_invalid_veh_fab = False
                        for fk, agg_list, inv_veh_list in (
                            ("fab2_c3d_pct", all_linked_fab_c3d, invalid_vehicle_fab_c3d),
                            ("fab2_c5b9_pct", all_linked_fab_c5b9, invalid_vehicle_fab_c5b9),
                            ("fab2_lysis_pct", all_linked_fab_lysis, invalid_vehicle_fab_lysis),
                        ):
                            if fk in pfab:
                                if _veh_ok(strat_agg, did_agg, fk):
                                    agg_list.append(pfab[fk])
                                else:
                                    inv_veh_list.append(pfab[fk])
                                    row_had_invalid_veh_fab = True
                        if row_had_invalid_veh_fab:
                            withheld_invalid_vehicle_fab_rows_count += 1
                    else:
                        withheld_invalid_fab_rows_count += 1
                else:
                    withheld_invalid_fab_rows_count += 1

        # Adjudicate EVERY distinct endpoint across clinical bracket {1, 5, 15} ug/mL and all required strata
        # R07 B5 + R11 B3: ONLY rows with valid matched normal rabbit IgG controls, passing lot/run positive controls,
        # and validated 0.0 ug/mL vehicle baselines enter biological adjudication; invalid-control/invalid-vehicle rows
        # emit HOLD_INVALID_OR_INCOMPLETE_ASSAY and NEVER trigger permanent biological FAIL!
        cd47_res: dict[str, Any] = {}
        hla_e_res: dict[str, Any] = {}
        disp_res: dict[str, Any] = {}
        c3d_res: dict[str, Any] = {}
        c5b9_res: dict[str, Any] = {}
        lysis_res: dict[str, Any] = {}
        fab2_c3d_res: dict[str, Any] = {}
        fab2_c5b9_res: dict[str, Any] = {}
        fab2_lysis_res: dict[str, Any] = {}
        sc_viab_res: dict[str, Any] = {}
        iec_viab_res: dict[str, Any] = {}
        gsis_res: dict[str, Any] = {}

        for dose in _XREACT_CLINICAL_BRACKET_DOSES_UG_ML:
            for strat in _XREACT_REQUIRED_STRATA:
                cell = by_sd.get((strat, dose), {})
                valid_cell_recs = [r for r in cell.values() if r.get("_control_valid_for_bio") is True]
                valid_fab_recs = [r for r in cell.values() if r.get("_fab_control_valid_for_bio") is True]
                ckey = f"{strat}@{dose:g}"

                cd47_vals = [
                    r["cd47_sirpa_retention_pct"]
                    for r in valid_cell_recs
                    if "cd47_sirpa_retention_pct" in r and _veh_ok(strat, r["donor_id"], "cd47_sirpa_retention_pct")
                ]
                if len(cd47_vals) >= 6:
                    st, info = _eval_cd47(cd47_vals, f"{lot_id}.cd47[{ckey}]")
                    cd47_res[ckey] = info
                    if st != "PASS":
                        _lot_escalate(st, f"CD47 retention [{ckey}] verdict={st} (L95={info['l95_t']}, min={info['min_donor']})")

                # R07 B6 + R16 B1: Direct HLA-E binding retention (absolute >= 80.0% PASS / < 70.0% FAIL AND uncapped paired 100 * ATG / IgG >= 85.0% PASS / < 70.0% FAIL)
                hla_e_vals = [
                    r["hla_e_binding_retention_pct"]
                    for r in valid_cell_recs
                    if "hla_e_binding_retention_pct" in r and _veh_ok(strat, r["donor_id"], "hla_e_binding_retention_pct")
                ]
                hla_e_paired = [
                    100.0 * r["hla_e_binding_retention_pct"] / r["matched_rabbit_igg"]["hla_e_binding_retention_pct"]
                    for r in valid_cell_recs
                    if "hla_e_binding_retention_pct" in r
                    and _veh_ok(strat, r["donor_id"], "hla_e_binding_retention_pct")
                    and isinstance(r.get("matched_rabbit_igg"), dict)
                    and "hla_e_binding_retention_pct" in r["matched_rabbit_igg"]
                    and r["matched_rabbit_igg"]["hla_e_binding_retention_pct"] >= 80.0
                ]
                if len(hla_e_vals) >= 6:
                    st_ha, info_ha = _eval_hla_e_abs(hla_e_vals, f"{lot_id}.hla_e_abs[{ckey}]")
                    hla_e_entry: dict[str, Any] = {"absolute_retention_pct": info_ha}
                    if st_ha != "PASS":
                        _lot_escalate(st_ha, f"HLA-E absolute retention [{ckey}] verdict={st_ha} (L95={info_ha['l95_t']}, min={info_ha['min_donor']})")
                    if len(hla_e_paired) >= 6:
                        st_hp, info_hp = _eval_hla_e_paired(hla_e_paired, f"{lot_id}.hla_e_paired[{ckey}]")
                        hla_e_entry["paired_atg_over_igg_pct"] = info_hp
                        if st_hp != "PASS":
                            _lot_escalate(
                                st_hp,
                                f"HLA-E paired ATG/IgG retention [{ckey}] verdict={st_hp} "
                                f"(L95={info_hp['l95_t']:.4f}% vs 85.0% paired lower-bound criterion, min={info_hp['min_donor']:.4f}%)",
                            )
                    hla_e_res[ckey] = hla_e_entry

                for fkey, bucket, ep_lbl in (
                    ("c3d_pct", c3d_res, "C3d"),
                    ("c5b9_pct", c5b9_res, "C5b-9"),
                    ("lysis_pct", lysis_res, "Direct lysis"),
                ):
                    vals = [
                        r[fkey]
                        for r in valid_cell_recs
                        if fkey in r
                        and fkey not in r.get("_conflicted_linked_endpoints", ())
                        and _veh_ok(strat, r["donor_id"], fkey)
                    ]
                    if len(vals) >= 6:
                        st, info = _eval_upper_5_8(vals, f"{lot_id}.{fkey}[{ckey}]")
                        bucket[ckey] = info
                        if st != "PASS":
                            _lot_escalate(st, f"{ep_lbl} [{ckey}] verdict={st} (L95={info['l95_t']}, U95={info['u95_t']}, max={info['max_donor']})")

                # B2 + R07 B5 + R11 B2/B3: Adjudicate lot-/donor-/run-linked direct F(ab')2 deconvolution measurements biologically
                # strictly on control-valid, vehicle-valid rows!
                for fab_k, fbucket, fep_lbl in (
                    ("fab2_c3d_pct", fab2_c3d_res, "Direct F(ab')2 C3d"),
                    ("fab2_c5b9_pct", fab2_c5b9_res, "Direct F(ab')2 C5b-9"),
                    ("fab2_lysis_pct", fab2_lysis_res, "Direct F(ab')2 lysis"),
                ):
                    fvals = [
                        r["fab2_deconvolution"][fab_k]
                        for r in valid_fab_recs
                        if isinstance(r.get("fab2_deconvolution"), dict)
                        and fab_k in r["fab2_deconvolution"]
                        and _veh_ok(strat, r["donor_id"], fab_k)
                    ]
                    if len(fvals) >= 6:
                        st, info = _eval_upper_5_8(fvals, f"{lot_id}.{fab_k}[{ckey}]")
                        fbucket[ckey] = info
                        if st != "PASS":
                            _lot_escalate(st, f"{fep_lbl} [{ckey}] verdict={st} (L95={info['l95_t']}, U95={info['u95_t']}, max={info['max_donor']})")

                if strat in _XREACT_CD64T_POS_STRATA:
                    d_vals = [
                        r["cd64t_displacement_pct"]
                        for r in valid_cell_recs
                        if "cd64t_displacement_pct" in r and _veh_ok(strat, r["donor_id"], "cd64t_displacement_pct")
                    ]
                    if len(d_vals) >= 6:
                        st, info = _eval_disp(d_vals, f"{lot_id}.cd64t_disp[{ckey}]")
                        disp_res[ckey] = info
                        if st != "PASS":
                            _lot_escalate(st, f"CD64t displacement [{ckey}] verdict={st} (L95={info['l95_t']}, max={info['max_donor']})")

                if strat in _XREACT_SC_ISLET_STRATA:
                    sv_vals = [
                        r["sc_islet_viability_pct"]
                        for r in valid_cell_recs
                        if "sc_islet_viability_pct" in r and _veh_ok(strat, r["donor_id"], "sc_islet_viability_pct")
                    ]
                    if len(sv_vals) >= 6:
                        st, info = _eval_viab(sv_vals, f"{lot_id}.sc_islet_viab[{ckey}]")
                        sc_viab_res[ckey] = info
                        if st != "PASS":
                            _lot_escalate(st, f"SC-islet viability [{ckey}] verdict={st} (L95={info['l95_t']}, U95={info['u95_t']})")
                    gs_vals = [
                        r["gsis_si"]
                        for r in valid_cell_recs
                        if "gsis_si" in r and _veh_ok(strat, r["donor_id"], "gsis_si")
                    ]
                    if len(gs_vals) >= 6:
                        st, info = _eval_gsis(gs_vals, f"{lot_id}.gsis_si[{ckey}]")
                        gsis_res[ckey] = info
                        if st != "PASS":
                            _lot_escalate(st, f"Dynamic GSIS SI [{ckey}] verdict={st} (min_SI={info['min_gsis_si']})")
                    gs_paired_ratios = [
                        r["gsis_si"] / r["matched_rabbit_igg"]["gsis_si"]
                        for r in valid_cell_recs
                        if "gsis_si" in r
                        and _veh_ok(strat, r["donor_id"], "gsis_si")
                        and isinstance(r.get("matched_rabbit_igg"), dict)
                        and "gsis_si" in r["matched_rabbit_igg"]
                        and r["matched_rabbit_igg"]["gsis_si"] >= 2.5
                    ]
                    if len(gs_paired_ratios) >= 6:
                        st_pr, info_pr = _eval_gsis_paired_ratio(gs_paired_ratios, f"{lot_id}.gsis_ratio_vs_igg[{ckey}]")
                        gsis_res[f"{ckey}__paired_ratio_vs_igg"] = info_pr
                        if st_pr != "PASS":
                            _lot_escalate(
                                st_pr,
                                f"Dynamic GSIS paired ATG/IgG ratio [{ckey}] verdict={st_pr} "
                                f"(L95={info_pr['l95_t_ratio']}, min={info_pr['min_donor_ratio']})",
                            )

                if strat in _XREACT_IEC_STRATA:
                    iv_vals = [
                        r["iec_viability_pct"]
                        for r in valid_cell_recs
                        if "iec_viability_pct" in r and _veh_ok(strat, r["donor_id"], "iec_viability_pct")
                    ]
                    if len(iv_vals) >= 6:
                        st, info = _eval_viab(iv_vals, f"{lot_id}.iec_viab[{ckey}]")
                        iec_viab_res[ckey] = info
                        if st != "PASS":
                            _lot_escalate(st, f"iEC viability [{ckey}] verdict={st} (L95={info['l95_t']}, U95={info['u95_t']})")

        # B1(b) + R07 B5/B6 + R11 B3: Exact trapezoidal per-donor dose-response AUC (0..50 & 1..15 ug/mL) vs matched normal rabbit IgG,
        # strictly filtering to control-valid AND vehicle-valid donor dose curves BEFORE biological adjudication!
        auc_res: dict[str, Any] = {}
        if len(common_donors) >= 6:
            ordered_donors = sorted(common_donors)
            for auc_tag, dose_grid in (
                ("auc_0_50", _XREACT_REQUIRED_DOSES_UG_ML),
                ("auc_1_15", _XREACT_CLINICAL_BRACKET_DOSES_UG_ML),
            ):
                for strat in _XREACT_REQUIRED_STRATA:
                    valid_grid_donors = [
                        did
                        for did in ordered_donors
                        if all(by_sd[(strat, d)][did].get("_control_valid_for_bio") is True for d in dose_grid)
                    ]
                    valid_fab_grid_donors = [
                        did
                        for did in ordered_donors
                        if all(by_sd[(strat, d)][did].get("_fab_control_valid_for_bio") is True for d in dose_grid)
                    ]

                    # 1. CD47-SIRPa retention per-donor AUC vs matched rabbit IgG
                    cd47_auc_ratios: list[float] = []
                    for did in valid_grid_donors:
                        if not _veh_ok(strat, did, "cd47_sirpa_retention_pct"):
                            continue
                        recs = [by_sd[(strat, d)][did] for d in dose_grid]
                        if all("cd47_sirpa_retention_pct" in r and isinstance(r.get("matched_rabbit_igg"), dict) and "cd47_sirpa_retention_pct" in r["matched_rabbit_igg"] for r in recs):
                            a_atg = _xreact_trapz_mean(dose_grid, [r["cd47_sirpa_retention_pct"] for r in recs])
                            a_igg = _xreact_trapz_mean(dose_grid, [r["matched_rabbit_igg"]["cd47_sirpa_retention_pct"] for r in recs])
                            if a_igg < 80.0:
                                _lot_escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", f"Invalid matched IgG CD47 AUC={a_igg:.2f}% (< 80.0% baseline) for {did}/{strat}/{auc_tag}")
                            else:
                                cd47_auc_ratios.append(100.0 * a_atg / a_igg)
                    if len(cd47_auc_ratios) >= 6:
                        st, info = _eval_cd47(cd47_auc_ratios, f"{lot_id}.cd47_{auc_tag}[{strat}]")
                        auc_res[f"cd47_{auc_tag}@{strat}"] = info
                        if st != "PASS":
                            _lot_escalate(
                                st,
                                f"Per-donor CD47 {auc_tag} vs matched IgG [{strat}] verdict={st} "
                                f"(L95={info['l95_t']:.4f}% vs 85.0% paired lower-bound criterion, min={info['min_donor']:.4f}%)",
                            )

                    # 1b. R07 B6 + R16 B1: Direct HLA-E binding retention per-donor AUC (absolute + uncapped paired 100 * AUC_ATG / AUC_IgG)
                    hla_e_abs_aucs: list[float] = []
                    hla_e_paired_aucs: list[float] = []
                    for did in valid_grid_donors:
                        if not _veh_ok(strat, did, "hla_e_binding_retention_pct"):
                            continue
                        recs = [by_sd[(strat, d)][did] for d in dose_grid]
                        if all("hla_e_binding_retention_pct" in r and isinstance(r.get("matched_rabbit_igg"), dict) and "hla_e_binding_retention_pct" in r["matched_rabbit_igg"] for r in recs):
                            a_atg = _xreact_trapz_mean(dose_grid, [r["hla_e_binding_retention_pct"] for r in recs])
                            a_igg = _xreact_trapz_mean(dose_grid, [r["matched_rabbit_igg"]["hla_e_binding_retention_pct"] for r in recs])
                            if a_igg < 80.0:
                                _lot_escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", f"Invalid matched IgG HLA-E AUC={a_igg:.2f}% (< 80.0% baseline) for {did}/{strat}/{auc_tag}")
                            else:
                                hla_e_abs_aucs.append(a_atg)
                                hla_e_paired_aucs.append(100.0 * a_atg / a_igg)
                    if len(hla_e_abs_aucs) >= 6:
                        st_ha, info_ha = _eval_hla_e_abs(hla_e_abs_aucs, f"{lot_id}.hla_e_{auc_tag}_abs[{strat}]")
                        st_hp, info_hp = _eval_hla_e_paired(hla_e_paired_aucs, f"{lot_id}.hla_e_{auc_tag}_paired[{strat}]")
                        auc_res[f"hla_e_{auc_tag}@{strat}"] = {"absolute_atg_auc": info_ha, "paired_atg_over_igg_auc": info_hp}
                        if st_ha != "PASS":
                            _lot_escalate(st_ha, f"Per-donor HLA-E {auc_tag} absolute [{strat}] verdict={st_ha} (L95={info_ha['l95_t']}, min={info_ha['min_donor']})")
                        if st_hp != "PASS":
                            _lot_escalate(
                                st_hp,
                                f"Per-donor HLA-E {auc_tag} paired vs matched IgG [{strat}] verdict={st_hp} "
                                f"(L95={info_hp['l95_t']:.4f}% vs 85.0% paired lower-bound criterion, min={info_hp['min_donor']:.4f}%)",
                            )

                    # 2. Complement C3d, C5b-9, lysis, and linked F(ab')2 per-donor dose AUC vs matched IgG
                    for fkey, ep_lbl, from_fab in (
                        ("c3d_pct", "C3d", False),
                        ("c5b9_pct", "C5b-9", False),
                        ("lysis_pct", "Direct lysis", False),
                        ("fab2_c3d_pct", "Direct F(ab')2 C3d", True),
                        ("fab2_c5b9_pct", "Direct F(ab')2 C5b-9", True),
                        ("fab2_lysis_pct", "Direct F(ab')2 lysis", True),
                    ):
                        igg_key = fkey.replace("fab2_", "") if from_fab else fkey
                        raw_aucs: list[float] = []
                        excess_aucs: list[float] = []
                        donor_pool = valid_fab_grid_donors if from_fab else valid_grid_donors
                        for did in donor_pool:
                            if not _veh_ok(strat, did, fkey):
                                continue
                            recs = [by_sd[(strat, d)][did] for d in dose_grid]
                            if from_fab:
                                ok = all(
                                    isinstance(r.get("fab2_deconvolution"), dict)
                                    and fkey in r["fab2_deconvolution"]
                                    and isinstance(r.get("matched_rabbit_igg"), dict)
                                    and igg_key in r["matched_rabbit_igg"]
                                    for r in recs
                                )
                                if ok:
                                    a_atg = _xreact_trapz_mean(dose_grid, [r["fab2_deconvolution"][fkey] for r in recs])
                                    a_igg = _xreact_trapz_mean(dose_grid, [r["matched_rabbit_igg"][igg_key] for r in recs])
                                    raw_aucs.append(a_atg)
                                    excess_aucs.append(max(0.0, a_atg - a_igg))
                            else:
                                ok = all(
                                    fkey in r
                                    and fkey not in r.get("_conflicted_linked_endpoints", ())
                                    and isinstance(r.get("matched_rabbit_igg"), dict)
                                    and igg_key in r["matched_rabbit_igg"]
                                    for r in recs
                                )
                                if ok:
                                    a_atg = _xreact_trapz_mean(dose_grid, [r[fkey] for r in recs])
                                    a_igg = _xreact_trapz_mean(dose_grid, [r["matched_rabbit_igg"][igg_key] for r in recs])
                                    raw_aucs.append(a_atg)
                                    excess_aucs.append(max(0.0, a_atg - a_igg))
                        if len(raw_aucs) >= 6:
                            st_raw, info_raw = _eval_upper_5_8(raw_aucs, f"{lot_id}.{fkey}_{auc_tag}_raw[{strat}]")
                            st_exc, info_exc = _eval_upper_5_8(excess_aucs, f"{lot_id}.{fkey}_{auc_tag}_vs_igg[{strat}]")
                            auc_res[f"{fkey}_{auc_tag}@{strat}"] = {"raw_atg_auc": info_raw, "excess_vs_igg_auc": info_exc}
                            for st_c, tag_c, inf_c in ((st_raw, "raw", info_raw), (st_exc, "excess_vs_igg", info_exc)):
                                if st_c != "PASS":
                                    _lot_escalate(st_c, f"Per-donor {ep_lbl} {auc_tag} ({tag_c}) [{strat}] verdict={st_c} (L95={inf_c['l95_t']}, U95={inf_c['u95_t']}, max={inf_c['max_donor']})")

                    # 3. CD64t displacement per-donor paired AUC on CD64t+ strata (raw ATG + matched IgG baseline <=10% + paired excess AUC_ATG - AUC_IgG)
                    if strat in _XREACT_CD64T_POS_STRATA:
                        disp_raw_aucs: list[float] = []
                        disp_igg_aucs: list[float] = []
                        disp_excess_aucs: list[float] = []
                        for did in valid_grid_donors:
                            if not _veh_ok(strat, did, "cd64t_displacement_pct"):
                                continue
                            recs = [by_sd[(strat, d)][did] for d in dose_grid]
                            if all("cd64t_displacement_pct" in r and isinstance(r.get("matched_rabbit_igg"), dict) and "cd64t_displacement_pct" in r["matched_rabbit_igg"] for r in recs):
                                a_atg = _xreact_trapz_mean(dose_grid, [r["cd64t_displacement_pct"] for r in recs])
                                a_igg = _xreact_trapz_mean(dose_grid, [r["matched_rabbit_igg"]["cd64t_displacement_pct"] for r in recs])
                                if a_igg > 10.0:
                                    _lot_escalate(
                                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                                        f"Matched normal rabbit IgG CD64t displacement AUC={a_igg:.2f}% > 10.0% baseline limit for {did}/{strat}/{auc_tag}",
                                    )
                                else:
                                    disp_raw_aucs.append(a_atg)
                                    disp_igg_aucs.append(a_igg)
                                    disp_excess_aucs.append(max(0.0, a_atg - a_igg))
                        if len(disp_raw_aucs) >= 6:
                            st_raw, info_raw = _eval_disp(disp_raw_aucs, f"{lot_id}.cd64t_disp_{auc_tag}_raw[{strat}]")
                            st_exc, info_exc = _eval_disp(disp_excess_aucs, f"{lot_id}.cd64t_disp_{auc_tag}_vs_igg[{strat}]")
                            auc_res[f"cd64t_disp_{auc_tag}@{strat}"] = {
                                "raw_atg_auc": info_raw,
                                "igg_ctrl_auc_max": round(max(disp_igg_aucs), 4),
                                "excess_vs_igg_auc": info_exc,
                            }
                            for st_c, tag_c, inf_c in ((st_raw, "raw", info_raw), (st_exc, "excess_vs_igg", info_exc)):
                                if st_c != "PASS":
                                    _lot_escalate(st_c, f"Per-donor CD64t displacement {auc_tag} ({tag_c}) [{strat}] verdict={st_c} (L95={inf_c['l95_t']}, max={inf_c['max_donor']})")

                    # 4. Viability & GSIS per-donor paired AUC vs matched IgG (enforcing IgG GSIS >= 2.5 and AUC_ATG / AUC_IgG >= 0.85!)
                    if strat in _XREACT_SC_ISLET_STRATA:
                        scv_aucs: list[float] = []
                        gsis_aucs: list[float] = []
                        gsis_igg_aucs: list[float] = []
                        gsis_auc_ratios: list[float] = []
                        for did in valid_grid_donors:
                            recs = [by_sd[(strat, d)][did] for d in dose_grid]
                            if _veh_ok(strat, did, "sc_islet_viability_pct") and all("sc_islet_viability_pct" in r and isinstance(r.get("matched_rabbit_igg"), dict) and "sc_islet_viability_pct" in r["matched_rabbit_igg"] for r in recs):
                                a_atg = _xreact_trapz_mean(dose_grid, [r["sc_islet_viability_pct"] for r in recs])
                                a_igg = _xreact_trapz_mean(dose_grid, [r["matched_rabbit_igg"]["sc_islet_viability_pct"] for r in recs])
                                if a_igg < 80.0:
                                    _lot_escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", f"Invalid matched IgG SC-islet viability AUC={a_igg:.2f}% (< 80.0% baseline) for {did}/{strat}/{auc_tag}")
                                else:
                                    scv_aucs.append(100.0 * a_atg / a_igg)
                            if _veh_ok(strat, did, "gsis_si") and all("gsis_si" in r and isinstance(r.get("matched_rabbit_igg"), dict) and "gsis_si" in r["matched_rabbit_igg"] for r in recs):
                                g_atg = _xreact_trapz_mean(dose_grid, [r["gsis_si"] for r in recs])
                                g_igg = _xreact_trapz_mean(dose_grid, [r["matched_rabbit_igg"]["gsis_si"] for r in recs])
                                if g_igg < 2.5:
                                    _lot_escalate(
                                        "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                                        f"Invalid matched normal rabbit IgG GSIS SI AUC={g_igg:.3f} (< 2.5 baseline) for {did}/{strat}/{auc_tag}",
                                    )
                                else:
                                    gsis_aucs.append(g_atg)
                                    gsis_igg_aucs.append(g_igg)
                                    gsis_auc_ratios.append(g_atg / g_igg)
                        if len(scv_aucs) >= 6:
                            st, info = _eval_viab(scv_aucs, f"{lot_id}.sc_viab_{auc_tag}[{strat}]")
                            auc_res[f"sc_viab_{auc_tag}@{strat}"] = info
                            if st != "PASS":
                                _lot_escalate(st, f"Per-donor SC-islet viability {auc_tag} vs matched IgG [{strat}] verdict={st} (L95={info['l95_t']}, U95={info['u95_t']})")
                        if len(gsis_aucs) >= 6:
                            st_abs, info_abs = _eval_gsis(gsis_aucs, f"{lot_id}.gsis_{auc_tag}[{strat}]")
                            if st_abs != "PASS":
                                _lot_escalate(st_abs, f"Per-donor GSIS SI {auc_tag} [{strat}] verdict={st_abs} (min_SI={info_abs['min_gsis_si']})")
                            entry_gsis: dict[str, Any] = {
                                "raw_atg_auc": info_abs,
                                "igg_ctrl_auc_min": round(min(gsis_igg_aucs), 4),
                            }
                            if len(gsis_auc_ratios) >= 6:
                                st_rat, info_rat = _eval_gsis_paired_ratio(gsis_auc_ratios, f"{lot_id}.gsis_{auc_tag}_ratio_vs_igg[{strat}]")
                                entry_gsis["paired_ratio_atg_over_igg_auc"] = info_rat
                                if st_rat != "PASS":
                                    _lot_escalate(
                                        st_rat,
                                        f"Per-donor GSIS paired AUC_ATG/AUC_IgG {auc_tag} [{strat}] verdict={st_rat} "
                                        f"(L95={info_rat['l95_t_ratio']}, min={info_rat['min_donor_ratio']})",
                                    )
                            auc_res[f"gsis_{auc_tag}@{strat}"] = entry_gsis

                    if strat in _XREACT_IEC_STRATA:
                        iev_aucs: list[float] = []
                        for did in valid_grid_donors:
                            if not _veh_ok(strat, did, "iec_viability_pct"):
                                continue
                            recs = [by_sd[(strat, d)][did] for d in dose_grid]
                            if all("iec_viability_pct" in r and isinstance(r.get("matched_rabbit_igg"), dict) and "iec_viability_pct" in r["matched_rabbit_igg"] for r in recs):
                                a_atg = _xreact_trapz_mean(dose_grid, [r["iec_viability_pct"] for r in recs])
                                a_igg = _xreact_trapz_mean(dose_grid, [r["matched_rabbit_igg"]["iec_viability_pct"] for r in recs])
                                if a_igg < 80.0:
                                    _lot_escalate("HOLD_INVALID_OR_INCOMPLETE_ASSAY", f"Invalid matched IgG iEC viability AUC={a_igg:.2f}% (< 80.0% baseline) for {did}/{strat}/{auc_tag}")
                                else:
                                    iev_aucs.append(100.0 * a_atg / a_igg)
                        if len(iev_aucs) >= 6:
                            st, info = _eval_viab(iev_aucs, f"{lot_id}.iec_viab_{auc_tag}[{strat}]")
                            auc_res[f"iec_viab_{auc_tag}@{strat}"] = info
                            if st != "PASS":
                                _lot_escalate(st, f"Per-donor iEC viability {auc_tag} vs matched IgG [{strat}] verdict={st} (L95={info['l95_t']}, U95={info['u95_t']})")

        lot_endpoints["XREACT_CD47_SIRPA_RETENTION"] = cd47_res
        lot_endpoints["XREACT_HLA_E_BINDING_RETENTION"] = hla_e_res
        lot_endpoints["XREACT_CD64T_RABBIT_FC_DISPLACEMENT"] = disp_res
        lot_endpoints["XREACT_COMPLEMENT_C3D"] = c3d_res
        lot_endpoints["XREACT_COMPLEMENT_C5B9"] = c5b9_res
        lot_endpoints["XREACT_DIRECT_LYSIS"] = lysis_res
        lot_endpoints["XREACT_LINKED_FAB2_C3D"] = fab2_c3d_res
        lot_endpoints["XREACT_LINKED_FAB2_C5B9"] = fab2_c5b9_res
        lot_endpoints["XREACT_LINKED_FAB2_LYSIS"] = fab2_lysis_res
        lot_endpoints["XREACT_SC_ISLET_VIABILITY"] = sc_viab_res
        lot_endpoints["XREACT_IEC_VIABILITY"] = iec_viab_res
        lot_endpoints["XREACT_DYNAMIC_GSIS_SI"] = gsis_res
        lot_endpoints["XREACT_PER_DONOR_DOSE_AUC_VS_MATCHED_IGG"] = auc_res

        lot_ind_igg_provenance_verified = bool(
            len(verified_ind_igg_run_ids_used) > 0
            and not lot_ind_igg_explicit_bad
            and not lot_ind_igg_reconciliation_conflict
            and not lot_ind_igg_any_row_failed_provenance
            and len(conflicted_or_invalid_ind_igg_run_ids) == 0
        )

        per_lot_verdicts[lot_id] = {
            "lot_verdict": lot_state,
            "lot_positive_controls_verified": lot_pos_ctrl_valid,
            "covered_positive_control_run_ids": sorted(passing_ctrl_run_ids),
            "conflicted_or_invalid_positive_control_run_ids": sorted(conflicted_or_invalid_ctrl_run_ids),
            "independent_matched_igg_provenance_verified": lot_ind_igg_provenance_verified,
            "verified_independent_igg_control_run_ids": sorted(verified_ind_igg_run_ids_used),
            "conflicted_or_invalid_independent_igg_run_ids": sorted(conflicted_or_invalid_ind_igg_run_ids),
            "observed_run_ids": sorted(observed_run_ids | observed_fab_run_ids),
            "invalid_control_rows_excluded_from_bio_adjudication": excluded_invalid_control_rows,
            "linked_endpoint_conflicts_quarantined": linked_endpoint_conflicts_quarantined,
            "vehicle_series_quarantined": vehicle_series_quarantined,
            "paired_donor_panel_continuity": {
                "crossed_donor_count": len(common_donors),
                "union_donor_count": len(union_donors),
                "crossed_panel_exact_match": crossed_panel_exact_match,
                "crossed_donor_ids": sorted(common_donors),
            },
            "distinct_donors_by_stratum_dose": distinct_donors_by_cell,
            "endpoints": lot_endpoints,
        }

    # Log optional cross-lot donor overlap (each lot is adjudicated independently with its own >=6 crossed panel)
    lot_donor_sets = [
        set(v.get("paired_donor_panel_continuity", {}).get("crossed_donor_ids", []))
        for v in per_lot_verdicts.values()
        if isinstance(v.get("paired_donor_panel_continuity"), dict)
    ]
    cross_lot_shared_donors = sorted(set.intersection(*lot_donor_sets)) if len(lot_donor_sets) >= 2 else []

    # B2 + R16 M1: Derive global direct F(ab')2 maxima STRICTLY from adjudicable same-run vehicle-qualified
    # linked observations, keeping withheld cross-run AND invalid-vehicle Fab rows separated and setting
    # linked_fab2_deconvolution_reconciled=False whenever any cross-run, invalid-control, or invalid-vehicle Fab row is withheld!
    fab_reconciled = (
        withheld_cross_run_fab_rows_count == 0
        and withheld_invalid_fab_rows_count == 0
        and withheld_invalid_vehicle_fab_rows_count == 0
    )
    derived_fab_maxima: dict[str, float | None] = {
        "direct_fab_c3d_max_pct": max(all_linked_fab_c3d) if all_linked_fab_c3d else None,
        "direct_fab_c5b9_max_pct": max(all_linked_fab_c5b9) if all_linked_fab_c5b9 else None,
        "direct_fab_lysis_max_pct": max(all_linked_fab_lysis) if all_linked_fab_lysis else None,
    }
    withheld_cross_run_fab_maxima: dict[str, float | None] = {
        "direct_fab_c3d_max_pct": max(withheld_cross_run_fab_c3d) if withheld_cross_run_fab_c3d else None,
        "direct_fab_c5b9_max_pct": max(withheld_cross_run_fab_c5b9) if withheld_cross_run_fab_c5b9 else None,
        "direct_fab_lysis_max_pct": max(withheld_cross_run_fab_lysis) if withheld_cross_run_fab_lysis else None,
    }
    invalid_vehicle_fab_maxima: dict[str, float | None] = {
        "direct_fab_c3d_max_pct": max(invalid_vehicle_fab_c3d) if invalid_vehicle_fab_c3d else None,
        "direct_fab_c5b9_max_pct": max(invalid_vehicle_fab_c5b9) if invalid_vehicle_fab_c5b9 else None,
        "direct_fab_lysis_max_pct": max(invalid_vehicle_fab_lysis) if invalid_vehicle_fab_lysis else None,
    }
    if withheld_cross_run_fab_rows_count > 0:
        _escalate(
            "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
            f"F(ab')2 deconvolution summary reconciliation withheld: {withheld_cross_run_fab_rows_count} cross-run "
            f"Fab row(s) excluded from adjudicable same-run maxima (adjudicable={derived_fab_maxima}, "
            f"withheld_cross_run={withheld_cross_run_fab_maxima})",
        )
    if withheld_invalid_vehicle_fab_rows_count > 0:
        _escalate(
            "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
            f"F(ab')2 deconvolution summary reconciliation withheld: {withheld_invalid_vehicle_fab_rows_count} "
            f"invalid-vehicle Fab row(s) excluded from adjudicable vehicle-qualified maxima "
            f"(adjudicable={derived_fab_maxima}, invalid_vehicle={invalid_vehicle_fab_maxima})",
        )
    for fk, dmax in derived_fab_maxima.items():
        rmax = reported_fab_maxima.get(fk)
        if dmax is None:
            fab_reconciled = False
            _escalate(
                "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                f"No adjudicable same-run lot-/donor-linked F(ab')2 observations available to verify controls.fab2.{fk}",
            )
        elif rmax is not None and abs(rmax - dmax) > 0.05:
            fab_reconciled = False
            _escalate(
                "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                f"Unresolved F(ab')2 deconvolution summary-vs-observation discrepancy on {fk}: "
                f"controls reported {rmax:.3f}% vs derived adjudicable same-run observation max {dmax:.3f}%",
            )
        elif rmax is not None and rmax > 8.0:
            fab_reconciled = False
            _escalate(
                "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
                f"Reported controls.fab2.{fk}={rmax:.3f}% exceeds 8.0% single-donor safety limit without biological FAIL adjudication",
            )

    if len(lot_ids_seen) < 2:
        _escalate(
            "HOLD_INVALID_OR_INCOMPLETE_ASSAY",
            f"Only {len(lot_ids_seen)} distinct commercial ATG lot tested (minimum 2 independent lots required)",
        )

    return {
        "gate_id": "GATE_30_ATG_XREACT",
        "verdict": worst_state,
        "lot_pooling_prohibited": True,
        "anonymous_arrays_rejected": True,
        "lot_specific_positive_controls_enforced": True,
        "run_level_positive_control_coverage_enforced": True,
        "order_independent_positive_control_reconciliation_enforced": True,
        "matched_igg_control_baselines_enforced": True,
        "global_matched_igg_isotype_valid": global_matched_igg_valid,
        "independent_matched_igg_traceable_reconciliation_enforced": True,
        "fab2_same_run_paired_control_required": True,
        "cross_run_fab2_deconvolution_withheld": True,
        "vehicle_validated_before_auc_enforced": True,
        "invalid_control_rows_excluded_from_bio_fail": True,
        "linked_endpoint_conflict_quarantine_enforced": True,
        "rejected_fab_linkage_excluded_from_primary_quarantine": True,
        "vehicle_invalid_fab_excluded_from_primary_quarantine": True,
        "direct_hla_e_binding_retention_enforced": True,
        "crossed_paired_donor_panel_enforced": True,
        "cross_lot_donor_panel_policy": "WITHIN_LOT_COMMON_CROSSED_PANEL_REQUIRED_CROSS_LOT_OVERLAP_OPTIONAL_LOGGED",
        "cross_lot_shared_donor_ids_count": len(cross_lot_shared_donors),
        "per_donor_dose_auc_vs_matched_igg_enforced": True,
        "uncapped_paired_ratios_enforced": True,
        "linked_fab2_deconvolution_reconciled": fab_reconciled,
        "derived_direct_fab_maxima_pct": derived_fab_maxima,
        "withheld_cross_run_fab_maxima": withheld_cross_run_fab_maxima,
        "withheld_cross_run_fab_rows_count": withheld_cross_run_fab_rows_count,
        "invalid_vehicle_fab_maxima_pct": invalid_vehicle_fab_maxima,
        "withheld_invalid_vehicle_fab_rows_count": withheld_invalid_vehicle_fab_rows_count,
        "lots_evaluated": len(lot_ids_seen),
        "controls_valid": controls_valid,
        "per_lot_verdicts": per_lot_verdicts,
        "reasons": reasons,
    }


def run_gate30_atg_xreact_decision_table_self_tests() -> dict[str, Any]:
    """Synthetic decision-table verification for Gate 30-ATG-XREACT covering crossed paired donor
    continuity, per-donor trapezoidal AUC vs matched normal rabbit IgG, lot-/donor-linked F(ab')2
    deconvolution & discrepancy reconciliation, 5-point dose coverage, 4 target strata, separate
    endpoints, physical-domain bounds [0, 100]%, worst-lot precedence, and anonymous counterexamples.
    """
    valid_ctrl = build_valid_xreact_controls()

    # Case 1: Clean 2-lot crossed paired-donor, matched-IgG, Fab2-reconciled PASS
    r1 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), build_valid_xreact_lot("LOT-B")],
    })
    if r1["verdict"] != "PASS":
        raise RuntimeError(f"XREACT self-test 1 (clean 2-lot PASS) failed: {r1}")

    # Case 2: Pooled-average trap — Lot A 100%, Lot B 70% (would average 85% if pooled) MUST FAIL!
    lot_a_100 = build_valid_xreact_lot("LOT-A", cd47_values=[100.0] * 6)
    lot_b_70 = build_valid_xreact_lot("LOT-B", cd47_values=[70.0] * 6)
    r2 = evaluate_gate30_atg_xreact({"controls": valid_ctrl, "lots": [lot_a_100, lot_b_70]})
    if r2["verdict"] != "FAIL":
        raise RuntimeError(f"XREACT self-test 2 (worst-lot 100%/70% trap) must FAIL, got {r2}")

    # Case 3: Missing 2nd commercial lot -> HOLD_INVALID_OR_INCOMPLETE_ASSAY
    r3 = evaluate_gate30_atg_xreact({"controls": valid_ctrl, "lots": [build_valid_xreact_lot("LOT-A")]})
    if r3["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 3 (missing lot) failed: {r3}")

    # Case 4: Failed CD3+ positive control (<80%) -> HOLD_INVALID_OR_INCOMPLETE_ASSAY
    bad_ctrl = dict(valid_ctrl, cd3_pos_ctrl_pct=62.0)
    r4 = evaluate_gate30_atg_xreact({
        "controls": bad_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), build_valid_xreact_lot("LOT-B")],
    })
    if r4["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 4 (failed CD3+ control) failed: {r4}")

    # Case 5: Missing required iec_cd64t_null stratum -> HOLD_INVALID_OR_INCOMPLETE_ASSAY
    lot_miss_s = build_valid_xreact_lot(
        "LOT-B", strata=("sc_islet_cd64t_null", "sc_islet_cd64t_pos", "iec_cd64t_pos")
    )
    r5 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_miss_s],
    })
    if r5["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 5 (missing stratum) failed: {r5}")

    # Case 6: Unclassified single donor < 75% while cohort L95_t >= 85% -> HOLD_UNCLASSIFIED_DONOR_OUTLIER_REQUIRES_INVESTIGATION
    lot_out = build_valid_xreact_lot(
        "LOT-B",
        donor_ids=[f"DONOR-{i:02d}" for i in range(1, 13)],
        cd47_values=[100.0] * 11 + [74.0],
    )
    r6 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_out],
    })
    if r6["verdict"] != "HOLD_UNCLASSIFIED_DONOR_OUTLIER_REQUIRES_INVESTIGATION":
        raise RuntimeError(f"XREACT self-test 6 (unclassified donor outlier) failed: {r6}")

    # Case 7: Biological FAIL dominates missing 2nd lot -> FAIL (fail-closed precedence!)
    r7 = evaluate_gate30_atg_xreact({"controls": valid_ctrl, "lots": [lot_b_70]})
    if r7["verdict"] != "FAIL":
        raise RuntimeError(f"XREACT self-test 7 (FAIL dominates missing lot) failed: {r7}")

    # Case 8: Non-finite observation rejected fail-closed (ValueError)
    lot_nan = build_valid_xreact_lot("LOT-B")
    lot_nan["observations"][0]["cd47_sirpa_retention_pct"] = float("nan")
    nan_rejected = False
    try:
        evaluate_gate30_atg_xreact({"controls": valid_ctrl, "lots": [build_valid_xreact_lot("LOT-A"), lot_nan]})
    except ValueError:
        nan_rejected = True
    if not nan_rejected:
        raise RuntimeError("XREACT self-test 8 (NaN rejection) failed")

    # Case 9: Synthetic anonymous-array + 101% CD3 counterexample -> MUST NOT PASS!
    r9 = evaluate_gate30_atg_xreact({
        "controls": {
            "isotype_control_valid": True,
            "positive_control_cd3_lysis_pct": 101.0,
            "positive_control_cd47_valid": True,
            "fc_vs_fab_deconvolution_valid": True,
        },
        "lots": [
            {
                "lot_id": "LOT-A",
                "cd47_sirpa_retention_pct": [94.0] * 6,
                "cd64t_fc_displacement_pct": [8.0] * 6,
                "complement_lysis_pct_by_stratum": {s: [1.5] * 6 for s in _XREACT_REQUIRED_STRATA},
                "viability_gsis_retention_pct": [96.0] * 6,
                "gsis_si": [3.2] * 6,
            },
            {
                "lot_id": "LOT-B",
                "cd47_sirpa_retention_pct": [94.0] * 6,
                "cd64t_fc_displacement_pct": [8.0] * 6,
                "complement_lysis_pct_by_stratum": {s: [1.5] * 6 for s in _XREACT_REQUIRED_STRATA},
                "viability_gsis_retention_pct": [96.0] * 6,
                "gsis_si": [3.2] * 6,
            },
        ],
    })
    if r9["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 9 (anonymous 101% counterexample) must HOLD_INVALID, got {r9}")

    # Case 10: Impossible 101% CD3 positive control on otherwise valid typed payload -> HOLD_INVALID_OR_INCOMPLETE_ASSAY
    r10 = evaluate_gate30_atg_xreact({
        "controls": dict(valid_ctrl, cd3_pos_ctrl_pct=101.0),
        "lots": [build_valid_xreact_lot("LOT-A"), build_valid_xreact_lot("LOT-B")],
    })
    if r10["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 10 (101% CD3 control) failed: {r10}")

    # Case 11: Negative percentage (-0.5% C3d) -> HOLD_INVALID_OR_INCOMPLETE_ASSAY
    lot_neg = build_valid_xreact_lot("LOT-B")
    lot_neg["observations"][0]["c3d_pct"] = -0.5
    r11 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_neg],
    })
    if r11["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 11 (negative percentage) failed: {r11}")

    # Case 12: Duplicate donor_id collapsing 6 records to 5 distinct donors -> HOLD_INVALID_OR_INCOMPLETE_ASSAY
    lot_dup = build_valid_xreact_lot(
        "LOT-B", donor_ids=["DONOR-01", "DONOR-02", "DONOR-03", "DONOR-04", "DONOR-05", "DONOR-01"]
    )
    r12 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_dup],
    })
    if r12["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 12 (duplicate donor_id) failed: {r12}")

    # Case 13: Missing dose (50 ug/mL omitted) -> HOLD_INVALID_OR_INCOMPLETE_ASSAY
    lot_no50 = build_valid_xreact_lot("LOT-B", doses=(0.0, 1.0, 5.0, 15.0))
    r13 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_no50],
    })
    if r13["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 13 (missing 50 ug/mL dose) failed: {r13}")

    # Case 14: Separate C5b-9 biological FAIL (while C3d and lysis pass!) -> FAIL
    lot_c5b9_fail = build_valid_xreact_lot("LOT-B", c5b9_values=[9.5, 9.8, 9.2, 9.6, 9.4, 9.7])
    r14 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_c5b9_fail],
    })
    if r14["verdict"] != "FAIL":
        raise RuntimeError(f"XREACT self-test 14 (separate C5b-9 fail) failed: {r14}")

    # Case 15: Separate iEC viability biological FAIL (while SC-islet viability & GSIS pass!) -> FAIL
    lot_iec_fail = build_valid_xreact_lot("LOT-B", iec_viab_values=[76.0, 78.0, 77.5, 79.0, 75.5, 77.0])
    r15 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_iec_fail],
    })
    if r15["verdict"] != "FAIL":
        raise RuntimeError(f"XREACT self-test 15 (separate iEC viability fail) failed: {r15}")

    # Case 16: Missing separate c5b9_pct field -> HOLD_INVALID_OR_INCOMPLETE_ASSAY
    lot_no_c5b9 = build_valid_xreact_lot("LOT-B")
    for rec in lot_no_c5b9["observations"]:
        rec.pop("c5b9_pct", None)
    r16 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_no_c5b9],
    })
    if r16["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 16 (missing c5b9_pct) failed: {r16}")

    # Case 17 (R04 B1): Disconnected/unpaired donor panel (different 6 donor_ids in every cell) -> HOLD_INVALID_OR_INCOMPLETE_ASSAY!
    lot_disconn = build_valid_xreact_lot("LOT-B")
    for c_idx, rec in enumerate(lot_disconn["observations"]):
        cell_tag = f"{rec['stratum']}_{int(rec['dose_ug_ml'])}"
        new_did = f"{rec['donor_id']}__{cell_tag}"
        rec["donor_id"] = new_did
        rec["fab2_deconvolution"]["donor_id"] = new_did
    r17 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_disconn],
    })
    if r17["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 17 (disconnected donor panel) must fail closed, got {r17}")

    # Case 18 (R04 B1): Missing matched normal rabbit IgG comparator records -> HOLD_INVALID_OR_INCOMPLETE_ASSAY!
    lot_no_igg = build_valid_xreact_lot("LOT-B")
    for rec in lot_no_igg["observations"]:
        rec.pop("matched_rabbit_igg", None)
    r18 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_no_igg],
    })
    if r18["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 18 (missing matched rabbit IgG) must fail closed, got {r18}")

    # Case 19 (R04 B1): Clinical bracket {1,5,15} passes, but 50 ug/mL C3d spikes -> 0..50 ug/mL per-donor AUC breach -> FAIL!
    lot_auc_fail = build_valid_xreact_lot("LOT-B")
    for rec in lot_auc_fail["observations"]:
        if rec["dose_ug_ml"] == 50.0:
            rec["c3d_pct"] = 25.0
            rec["fab2_deconvolution"]["intact_igg_c3d_pct"] = 25.0
            rec["fab2_deconvolution"]["fab2_c3d_pct"] = 25.0
    r19 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_auc_fail],
    })
    if r19["verdict"] != "FAIL":
        raise RuntimeError(f"XREACT self-test 19 (0..50 ug/mL per-donor AUC breach) must FAIL, got {r19}")

    # Case 20 (R04 B2): Unbound 100% Fab summary maxima alongside benign endpoint records -> HOLD_INVALID_OR_INCOMPLETE_ASSAY!
    ctrl_fab_100 = json.loads(json.dumps(valid_ctrl))
    ctrl_fab_100["fab2_vs_intact_igg_deconvolution"]["direct_fab_c3d_max_pct"] = 100.0
    ctrl_fab_100["fab2_vs_intact_igg_deconvolution"]["direct_fab_c5b9_max_pct"] = 100.0
    ctrl_fab_100["fab2_vs_intact_igg_deconvolution"]["direct_fab_lysis_max_pct"] = 100.0
    r20 = evaluate_gate30_atg_xreact({
        "controls": ctrl_fab_100,
        "lots": [build_valid_xreact_lot("LOT-A"), build_valid_xreact_lot("LOT-B")],
    })
    if r20["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 20 (unbound 100% Fab summary discrepancy) must fail closed, got {r20}")

    # Case 21 (R04 B2): Linked direct F(ab')2 biological breach (11% C3d) -> FAIL!
    lot_fab_fail = build_valid_xreact_lot("LOT-B", fab2_c3d_values=[11.0, 11.2, 10.8, 11.4, 10.9, 11.1])
    r21 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_fab_fail],
    })
    if r21["verdict"] != "FAIL":
        raise RuntimeError(f"XREACT self-test 21 (linked direct F(ab')2 biological fail) must FAIL, got {r21}")

    # Case 22 (R05 B2): Matched normal rabbit IgG GSIS SI set to 0.0 -> HOLD_INVALID_OR_INCOMPLETE_ASSAY!
    lot_igg_gsis0 = build_valid_xreact_lot("LOT-B")
    for rec in lot_igg_gsis0["observations"]:
        if "gsis_si" in rec["matched_rabbit_igg"]:
            rec["matched_rabbit_igg"]["gsis_si"] = 0.0
    r22 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_igg_gsis0],
    })
    if r22["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 22 (matched IgG GSIS=0.0) must HOLD_INVALID, got {r22}")

    # Case 23 (R05 B2): Matched normal rabbit IgG CD64t displacement set to 100.0% -> HOLD_INVALID_OR_INCOMPLETE_ASSAY!
    lot_igg_disp100 = build_valid_xreact_lot("LOT-B")
    for rec in lot_igg_disp100["observations"]:
        if "cd64t_displacement_pct" in rec["matched_rabbit_igg"]:
            rec["matched_rabbit_igg"]["cd64t_displacement_pct"] = 100.0
    r23 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_igg_disp100],
    })
    if r23["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 23 (matched IgG CD64t disp=100%) must HOLD_INVALID, got {r23}")

    # Case 24 (R05 B2): Valid matched IgG GSIS=5.0 vs ATG GSIS=3.0 (ratio 0.60 < 0.65 while abs 3.0 >= 2.5) -> FAIL!
    lot_gsis_paired_fail = build_valid_xreact_lot("LOT-B", gsis_si_values=[3.0, 3.05, 3.0, 3.1, 3.0, 3.05])
    for rec in lot_gsis_paired_fail["observations"]:
        if "gsis_si" in rec["matched_rabbit_igg"]:
            rec["matched_rabbit_igg"]["gsis_si"] = 5.0
    r24 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_gsis_paired_fail],
    })
    if r24["verdict"] != "FAIL":
        raise RuntimeError(f"XREACT self-test 24 (paired GSIS ATG/IgG collapse 3.0/5.0) must FAIL, got {r24}")

    # Case 25 (R06 B2): Missing lot-specific lot_positive_controls on LOT-B -> HOLD_INVALID_OR_INCOMPLETE_ASSAY!
    lot_no_lpc = build_valid_xreact_lot("LOT-B")
    lot_no_lpc.pop("lot_positive_controls", None)
    r25 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_no_lpc],
    })
    if r25["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 25 (missing lot_positive_controls) must HOLD_INVALID, got {r25}")

    # Case 26 (R06 B2): Wrong lot_id inside lot_positive_controls (LOT-A bound to LOT-B) -> HOLD_INVALID_OR_INCOMPLETE_ASSAY!
    lot_wrong_lpc = build_valid_xreact_lot("LOT-B")
    lot_wrong_lpc["lot_positive_controls"]["lot_id"] = "LOT-A"
    r26 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_wrong_lpc],
    })
    if r26["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 26 (wrong lot_id in lot_positive_controls) must HOLD_INVALID, got {r26}")

    # Case 27 (R06 B2): Low (50%) lot-specific cd3_pos_ctrl_pct on LOT-B -> HOLD_INVALID_OR_INCOMPLETE_ASSAY!
    r27 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), build_valid_xreact_lot("LOT-B", lot_cd3_pos_ctrl_pct=50.0)],
    })
    if r27["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 27 (low 50% lot-specific cd3_pos_ctrl_pct) must HOLD_INVALID, got {r27}")

    # Case 28 (R06 B2): Low (50%) lot-specific b6h12_pos_ctrl_pct on LOT-B -> HOLD_INVALID_OR_INCOMPLETE_ASSAY!
    r28 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), build_valid_xreact_lot("LOT-B", lot_b6h12_pos_ctrl_pct=50.0)],
    })
    if r28["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 28 (low 50% lot-specific b6h12_pos_ctrl_pct) must HOLD_INVALID, got {r28}")

    # Case 29 (R06 B3): Unusable 1% matched normal rabbit IgG CD47 retention -> HOLD_INVALID_OR_INCOMPLETE_ASSAY!
    lot_igg_cd47_1 = build_valid_xreact_lot("LOT-B")
    for rec in lot_igg_cd47_1["observations"]:
        rec["matched_rabbit_igg"]["cd47_sirpa_retention_pct"] = 1.0
    r29 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_igg_cd47_1],
    })
    if r29["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 29 (1% matched IgG CD47 retention) must HOLD_INVALID, got {r29}")

    # Case 30 (R06 B3): Unusable 1% matched normal rabbit IgG SC-islet & iEC viability -> HOLD_INVALID_OR_INCOMPLETE_ASSAY!
    lot_igg_viab_1 = build_valid_xreact_lot("LOT-B")
    for rec in lot_igg_viab_1["observations"]:
        if "sc_islet_viability_pct" in rec["matched_rabbit_igg"]:
            rec["matched_rabbit_igg"]["sc_islet_viability_pct"] = 1.0
        if "iec_viability_pct" in rec["matched_rabbit_igg"]:
            rec["matched_rabbit_igg"]["iec_viability_pct"] = 1.0
    r30 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_igg_viab_1],
    })
    if r30["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 30 (1% matched IgG viability) must HOLD_INVALID, got {r30}")

    # Case 31 (R06 B3): Elevated 20% matched normal rabbit IgG C3d / C5b-9 -> HOLD_INVALID_OR_INCOMPLETE_ASSAY!
    lot_igg_comp_20 = build_valid_xreact_lot("LOT-B")
    for rec in lot_igg_comp_20["observations"]:
        rec["matched_rabbit_igg"]["c3d_pct"] = 20.0
        rec["matched_rabbit_igg"]["c5b9_pct"] = 20.0
    r31 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_igg_comp_20],
    })
    if r31["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 31 (20% matched IgG C3d/C5b-9) must HOLD_INVALID, got {r31}")

    # Case 32 (R07 B4a): Lot B positive control carries Lot A's plate_or_run_id while Lot B obs & fab2 carry Lot B's run ID -> HOLD_INVALID!
    lot_b_run_mismatch = build_valid_xreact_lot("LOT-B")
    lot_b_run_mismatch["lot_positive_controls"]["plate_or_run_id"] = "RUN-LOT-A-01"
    r32 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_run_mismatch],
    })
    if r32["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 32 (Lot B positive control mismatched plate_or_run_id) must HOLD_INVALID, got {r32}")

    # Case 33 (R07 B4b): Multi-run lot_positive_controls list covering 2 plates PASSES; omitting 2nd plate's positive control HOLDS_INVALID!
    lot_b_multi = build_valid_xreact_lot("LOT-B")
    for idx_r, rec in enumerate(lot_b_multi["observations"]):
        run_tag = "RUN-LOT-B-P1" if idx_r % 2 == 0 else "RUN-LOT-B-P2"
        rec["plate_or_run_id"] = run_tag
        rec["fab2_deconvolution"]["plate_or_run_id"] = run_tag
    lot_b_multi["lot_positive_controls"] = [
        {"lot_id": "LOT-B", "plate_or_run_id": "RUN-LOT-B-P1", "cd3_pos_ctrl_pct": 94.0, "b6h12_pos_ctrl_pct": 95.0},
        {"lot_id": "LOT-B", "plate_or_run_id": "RUN-LOT-B-P2", "cd3_pos_ctrl_pct": 93.5, "b6h12_pos_ctrl_pct": 94.5},
    ]
    r33_pass = evaluate_gate30_atg_xreact({"controls": valid_ctrl, "lots": [build_valid_xreact_lot("LOT-A"), lot_b_multi]})
    lot_b_multi_miss = json.loads(json.dumps(lot_b_multi))
    lot_b_multi_miss["lot_positive_controls"] = [lot_b_multi_miss["lot_positive_controls"][0]]
    r33_miss = evaluate_gate30_atg_xreact({"controls": valid_ctrl, "lots": [build_valid_xreact_lot("LOT-A"), lot_b_multi_miss]})
    if r33_pass["verdict"] != "PASS" or r33_miss["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 33 (multi-run coverage pass/miss) failed: pass={r33_pass['verdict']}, miss={r33_miss['verdict']}")

    # Case 34 (R07 B4c): fab2_deconvolution carries uncovered plate_or_run_id -> HOLD_INVALID_OR_INCOMPLETE_ASSAY!
    lot_b_fab_run = build_valid_xreact_lot("LOT-B")
    lot_b_fab_run["observations"][0]["fab2_deconvolution"]["plate_or_run_id"] = "RUN-UNCOVERED-FAB-99"
    r34 = evaluate_gate30_atg_xreact({"controls": valid_ctrl, "lots": [build_valid_xreact_lot("LOT-A"), lot_b_fab_run]})
    if r34["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 34 (uncovered fab2 plate_or_run_id) must HOLD_INVALID, got {r34}")

    # Case 35 (R07 B5a): Compromised matched rabbit IgG (equal 20.0% C3d in BOTH ATG & matched IgG) -> HOLD_INVALID (NOT permanent FAIL!)
    lot_b_eq20 = build_valid_xreact_lot("LOT-B")
    for rec in lot_b_eq20["observations"]:
        rec["c3d_pct"] = 20.0
        rec["matched_rabbit_igg"]["c3d_pct"] = 20.0
        rec["fab2_deconvolution"]["intact_igg_c3d_pct"] = 20.0
        rec["fab2_deconvolution"]["fab2_c3d_pct"] = 20.0
    ctrl_eq20 = json.loads(json.dumps(valid_ctrl))
    ctrl_eq20["fab2_vs_intact_igg_deconvolution"]["direct_fab_c3d_max_pct"] = 20.0
    r35 = evaluate_gate30_atg_xreact({"controls": ctrl_eq20, "lots": [build_valid_xreact_lot("LOT-A"), lot_b_eq20]})
    if r35["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 35 (equal 20% C3d in ATG & compromised IgG) must HOLD_INVALID (not bio FAIL), got {r35}")

    # Case 36 (R07 B5b): Invalid-IgG Lot B (equal 20% C3d) + SEPARATE control-valid Lot A with genuine 20% ATG vs 0.4% IgG -> FAIL!
    lot_a_genuine_fail = build_valid_xreact_lot("LOT-A", c3d_values=[20.0] * 6)
    r36 = evaluate_gate30_atg_xreact({"controls": ctrl_eq20, "lots": [lot_a_genuine_fail, lot_b_eq20]})
    if r36["verdict"] != "FAIL":
        raise RuntimeError(f"XREACT self-test 36 (invalid-IgG lot + separate control-valid biological FAIL) must FAIL, got {r36}")

    # Case 37 (R07 B6a): Omitting required direct hla_e_binding_retention_pct -> HOLD_INVALID_OR_INCOMPLETE_ASSAY!
    lot_no_hla_e = build_valid_xreact_lot("LOT-B")
    for rec in lot_no_hla_e["observations"]:
        rec.pop("hla_e_binding_retention_pct", None)
    r37 = evaluate_gate30_atg_xreact({"controls": valid_ctrl, "lots": [build_valid_xreact_lot("LOT-A"), lot_no_hla_e]})
    if r37["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 37 (omitted hla_e_binding_retention_pct) must HOLD_INVALID, got {r37}")

    # Case 38 (R07 B6b): Direct HLA-E retention = 0.0% against 100.0% matched IgG -> FAIL!
    lot_hla_e_0 = build_valid_xreact_lot("LOT-B", hla_e_values=[0.0] * 6)
    for rec in lot_hla_e_0["observations"]:
        rec["matched_rabbit_igg"]["hla_e_binding_retention_pct"] = 100.0
    r38 = evaluate_gate30_atg_xreact({"controls": valid_ctrl, "lots": [build_valid_xreact_lot("LOT-A"), lot_hla_e_0]})
    if r38["verdict"] != "FAIL":
        raise RuntimeError(f"XREACT self-test 38 (0.0% HLA-E vs 100.0% IgG) must FAIL, got {r38}")

    # Case 39 (R07 B6c): Compromised matched-IgG HLA-E retention = 50.0% (< 80.0% baseline), even with ATG 0.0% -> HOLD_INVALID (NOT FAIL!)
    lot_igg_hla_e_50 = build_valid_xreact_lot("LOT-B", hla_e_values=[0.0] * 6)
    for rec in lot_igg_hla_e_50["observations"]:
        rec["matched_rabbit_igg"]["hla_e_binding_retention_pct"] = 50.0
    r39 = evaluate_gate30_atg_xreact({"controls": valid_ctrl, "lots": [build_valid_xreact_lot("LOT-A"), lot_igg_hla_e_50]})
    if r39["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 39 (50% matched IgG HLA-E baseline) must HOLD_INVALID (not bio FAIL), got {r39}")

    # Case 40 (R08 B1a): Contradictory same-run positive controls in BOTH orders ([pass, zero-CD3] and [zero-CD3, pass]) -> BOTH HOLD_INVALID!
    lot_b_conflict_pf = build_valid_xreact_lot("LOT-B", c3d_values=[20.0] * 6)
    pass_ctrl_b = dict(lot_b_conflict_pf["lot_positive_controls"])
    zero_ctrl_b = dict(pass_ctrl_b, cd3_pos_ctrl_pct=0.0)
    lot_b_conflict_pf["lot_positive_controls"] = [pass_ctrl_b, zero_ctrl_b]
    lot_b_conflict_fp = json.loads(json.dumps(lot_b_conflict_pf))
    lot_b_conflict_fp["lot_positive_controls"] = [zero_ctrl_b, pass_ctrl_b]
    r40_pf = evaluate_gate30_atg_xreact({"controls": valid_ctrl, "lots": [build_valid_xreact_lot("LOT-A"), lot_b_conflict_pf]})
    r40_fp = evaluate_gate30_atg_xreact({"controls": valid_ctrl, "lots": [build_valid_xreact_lot("LOT-A"), lot_b_conflict_fp]})
    if (
        r40_pf["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or r40_fp["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or r40_pf["per_lot_verdicts"]["LOT-B"]["covered_positive_control_run_ids"] != []
        or r40_fp["per_lot_verdicts"]["LOT-B"]["covered_positive_control_run_ids"] != []
        or r40_pf["per_lot_verdicts"]["LOT-B"]["conflicted_or_invalid_positive_control_run_ids"] != [pass_ctrl_b["plate_or_run_id"]]
        or r40_fp["per_lot_verdicts"]["LOT-B"]["conflicted_or_invalid_positive_control_run_ids"] != [pass_ctrl_b["plate_or_run_id"]]
    ):
        raise RuntimeError(
            f"XREACT self-test 40 (contradictory same-run positive controls order-independent) failed: pf={r40_pf['verdict']}, fp={r40_fp['verdict']}"
        )

    # Case 41 (R08 B1b): Conflicted LOT-B positive control + SEPARATE valid failing LOT-A -> FAIL preserved!
    r41 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A", c3d_values=[20.0] * 6), lot_b_conflict_pf],
    })
    if r41["verdict"] != "FAIL":
        raise RuntimeError(f"XREACT self-test 41 (conflicted lot + separate valid FAIL lot) must FAIL, got {r41}")

    # Case 42 (R08 B1c): Within-lot multi-run isolation: conflicted P1 (adverse 20% C3d) -> HOLD_INVALID; valid P2 (adverse 20% C3d) -> FAIL!
    lot_b_iso_hold = build_valid_xreact_lot("LOT-B")
    for rec in lot_b_iso_hold["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null" and rec["dose_ug_ml"] == 5.0:
            rec["plate_or_run_id"] = "RUN-LOT-B-P1"
            rec["fab2_deconvolution"]["plate_or_run_id"] = "RUN-LOT-B-P1"
            rec["c3d_pct"] = 20.0
            rec["fab2_deconvolution"]["intact_igg_c3d_pct"] = 20.0
        else:
            rec["plate_or_run_id"] = "RUN-LOT-B-P2"
            rec["fab2_deconvolution"]["plate_or_run_id"] = "RUN-LOT-B-P2"
    lot_b_iso_hold["lot_positive_controls"] = [
        {"lot_id": "LOT-B", "plate_or_run_id": "RUN-LOT-B-P1", "cd3_pos_ctrl_pct": 94.0, "b6h12_pos_ctrl_pct": 95.0},
        {"lot_id": "LOT-B", "plate_or_run_id": "RUN-LOT-B-P1", "cd3_pos_ctrl_pct": 0.0, "b6h12_pos_ctrl_pct": 95.0},
        {"lot_id": "LOT-B", "plate_or_run_id": "RUN-LOT-B-P2", "cd3_pos_ctrl_pct": 94.0, "b6h12_pos_ctrl_pct": 95.0},
    ]
    r42_hold = evaluate_gate30_atg_xreact({"controls": valid_ctrl, "lots": [build_valid_xreact_lot("LOT-A"), lot_b_iso_hold]})
    lot_b_iso_fail = json.loads(json.dumps(lot_b_iso_hold))
    for rec in lot_b_iso_fail["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_pos" and rec["dose_ug_ml"] == 5.0:
            rec["c3d_pct"] = 20.0
            rec["fab2_deconvolution"]["intact_igg_c3d_pct"] = 20.0
    r42_fail = evaluate_gate30_atg_xreact({"controls": valid_ctrl, "lots": [build_valid_xreact_lot("LOT-A"), lot_b_iso_fail]})
    if r42_hold["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY" or r42_fail["verdict"] != "FAIL":
        raise RuntimeError(
            f"XREACT self-test 42 (multi-run conflicted vs valid FAIL isolation) failed: hold={r42_hold['verdict']}, fail={r42_fail['verdict']}"
        )

    # Case 43 (R08 B2a): Global controls.normal_rabbit_igg_isotype_valid=False with adverse LOT-B -> HOLD_INVALID (NEVER bio FAIL!)
    ctrl_igg_false = dict(valid_ctrl, normal_rabbit_igg_isotype_valid=False)
    r43 = evaluate_gate30_atg_xreact({
        "controls": ctrl_igg_false,
        "lots": [build_valid_xreact_lot("LOT-A"), build_valid_xreact_lot("LOT-B", c3d_values=[20.0] * 6)],
    })
    if r43["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY" or r43["global_matched_igg_isotype_valid"] is not False:
        raise RuntimeError(f"XREACT self-test 43 (global normal_rabbit_igg_isotype_valid=False) must HOLD_INVALID, got {r43}")

    # Case 44 (R08 B2b + R09 B1): Global normal_rabbit_igg_isotype_valid=False + adverse LOT-B WITH valid unpadded,
    # non-conflicting, traceable independent matched-IgG control record -> FAIL!
    lot_b_ind_fail = build_valid_xreact_lot("LOT-B", c3d_values=[20.0] * 6)
    lot_b_ind_fail["independent_matched_igg_isotype_valid"] = True
    lot_b_ind_fail["independent_matched_igg_isotype_lot_id"] = "IND-RABBIT-IGG-LOT-B-2026"
    lot_b_ind_fail["independent_matched_igg_controls"] = build_valid_xreact_independent_igg_control(
        "LOT-B", "RUN_LOT-B_PLATE_01", "IND-RABBIT-IGG-LOT-B-2026"
    )
    r44 = evaluate_gate30_atg_xreact({
        "controls": ctrl_igg_false,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_ind_fail],
    })
    if (
        r44["verdict"] != "FAIL"
        or r44["per_lot_verdicts"]["LOT-B"]["independent_matched_igg_provenance_verified"] is not True
        or r44["per_lot_verdicts"]["LOT-B"]["invalid_control_rows_excluded_from_bio_adjudication"] != 0
    ):
        raise RuntimeError(f"XREACT self-test 44 (traceable independent matched IgG provenance bio FAIL) must FAIL, got {r44}")

    # Case 45 (R08 B2c): Global normal_rabbit_igg_isotype_valid=False + incomplete independent provenance (missing lot_id) -> HOLD_INVALID!
    lot_b_ind_incomplete = build_valid_xreact_lot("LOT-B", c3d_values=[20.0] * 6)
    lot_b_ind_incomplete["independent_matched_igg_isotype_valid"] = True
    r45 = evaluate_gate30_atg_xreact({
        "controls": ctrl_igg_false,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_ind_incomplete],
    })
    if r45["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 45 (incomplete independent IgG provenance) must HOLD_INVALID, got {r45}")

    # Case 46 (R08 B1/B3 parity): Duplicate conflicting observation rows in BOTH orders ([benign, 20%] vs [20%, benign]) -> BOTH HOLD_INVALID!
    lot_b_dup_bf = build_valid_xreact_lot("LOT-B")
    dup_adverse_rows = []
    for rec in lot_b_dup_bf["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null" and rec["dose_ug_ml"] == 5.0:
            adv = json.loads(json.dumps(rec))
            adv["c3d_pct"] = 20.0
            adv["fab2_deconvolution"]["intact_igg_c3d_pct"] = 20.0
            dup_adverse_rows.append(adv)
    lot_b_dup_fb = json.loads(json.dumps(lot_b_dup_bf))
    lot_b_dup_bf["observations"].extend(dup_adverse_rows)
    lot_b_dup_fb["observations"] = dup_adverse_rows + lot_b_dup_fb["observations"]
    r46_bf = evaluate_gate30_atg_xreact({"controls": valid_ctrl, "lots": [build_valid_xreact_lot("LOT-A"), lot_b_dup_bf]})
    r46_fb = evaluate_gate30_atg_xreact({"controls": valid_ctrl, "lots": [build_valid_xreact_lot("LOT-A"), lot_b_dup_fb]})
    if r46_bf["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY" or r46_fb["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(
            f"XREACT self-test 46 (duplicate conflicting observation order independence) failed: bf={r46_bf['verdict']}, fb={r46_fb['verdict']}"
        )

    # Case 47 (R09 B1a): Whitespace-padded independent_matched_igg_isotype_lot_id (" CONTROL-LOT-X ") with global isotype invalid -> HOLD_INVALID!
    lot_b_padded = build_valid_xreact_lot("LOT-B", c3d_values=[20.0] * 6)
    lot_b_padded["independent_matched_igg_isotype_valid"] = True
    lot_b_padded["independent_matched_igg_isotype_lot_id"] = " CONTROL-LOT-X "
    lot_b_padded["independent_matched_igg_controls"] = build_valid_xreact_independent_igg_control(
        "LOT-B", "RUN_LOT-B_PLATE_01", "CONTROL-LOT-X"
    )
    r47 = evaluate_gate30_atg_xreact({"controls": ctrl_igg_false, "lots": [build_valid_xreact_lot("LOT-A"), lot_b_padded]})
    if (
        r47["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or r47["per_lot_verdicts"]["LOT-B"]["independent_matched_igg_provenance_verified"] is not False
        or r47["per_lot_verdicts"]["LOT-B"]["invalid_control_rows_excluded_from_bio_adjudication"] != 120
    ):
        raise RuntimeError(f"XREACT self-test 47 (whitespace-padded independent IgG lot ID) must HOLD_INVALID, got {r47}")

    # Case 48 (R09 B1b): Conflicting lot-level (CONTROL-LOT-X) vs observation-level (CONTROL-LOT-Y) independent matched-IgG IDs -> HOLD_INVALID!
    lot_b_conflict_lr = build_valid_xreact_lot("LOT-B", c3d_values=[20.0] * 6)
    lot_b_conflict_lr["independent_matched_igg_isotype_valid"] = True
    lot_b_conflict_lr["independent_matched_igg_isotype_lot_id"] = "CONTROL-LOT-X"
    lot_b_conflict_lr["independent_matched_igg_controls"] = build_valid_xreact_independent_igg_control(
        "LOT-B", "RUN_LOT-B_PLATE_01", "CONTROL-LOT-X"
    )
    for rec in lot_b_conflict_lr["observations"]:
        rec["independent_matched_igg_isotype_valid"] = True
        rec["independent_matched_igg_isotype_lot_id"] = "CONTROL-LOT-Y"
    r48 = evaluate_gate30_atg_xreact({"controls": ctrl_igg_false, "lots": [build_valid_xreact_lot("LOT-A"), lot_b_conflict_lr]})
    if (
        r48["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or r48["per_lot_verdicts"]["LOT-B"]["independent_matched_igg_provenance_verified"] is not False
        or r48["per_lot_verdicts"]["LOT-B"]["invalid_control_rows_excluded_from_bio_adjudication"] != 120
    ):
        raise RuntimeError(f"XREACT self-test 48 (conflicting lot vs observation independent IgG IDs) must HOLD_INVALID, got {r48}")

    # Case 49 (R09 B1c): Conflicting lot-level (CONTROL-LOT-X) vs nested matched_rabbit_igg (CONTROL-LOT-Y) IDs -> HOLD_INVALID!
    lot_b_conflict_ln = build_valid_xreact_lot("LOT-B", c3d_values=[20.0] * 6)
    lot_b_conflict_ln["independent_matched_igg_isotype_valid"] = True
    lot_b_conflict_ln["independent_matched_igg_isotype_lot_id"] = "CONTROL-LOT-X"
    lot_b_conflict_ln["independent_matched_igg_controls"] = build_valid_xreact_independent_igg_control(
        "LOT-B", "RUN_LOT-B_PLATE_01", "CONTROL-LOT-X"
    )
    for rec in lot_b_conflict_ln["observations"]:
        rec["matched_rabbit_igg"]["independent_matched_igg_isotype_valid"] = True
        rec["matched_rabbit_igg"]["independent_matched_igg_isotype_lot_id"] = "CONTROL-LOT-Y"
    r49 = evaluate_gate30_atg_xreact({"controls": ctrl_igg_false, "lots": [build_valid_xreact_lot("LOT-A"), lot_b_conflict_ln]})
    if (
        r49["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or r49["per_lot_verdicts"]["LOT-B"]["independent_matched_igg_provenance_verified"] is not False
    ):
        raise RuntimeError(f"XREACT self-test 49 (conflicting lot vs nested independent IgG IDs) must HOLD_INVALID, got {r49}")

    # Case 50 (R09 B1d): Untraceable independent matched-IgG claim (missing traceable control record) -> HOLD_INVALID!
    lot_b_untrace = build_valid_xreact_lot("LOT-B", c3d_values=[20.0] * 6)
    lot_b_untrace["independent_matched_igg_isotype_valid"] = True
    lot_b_untrace["independent_matched_igg_isotype_lot_id"] = "CONTROL-LOT-UNREGISTERED"
    r50 = evaluate_gate30_atg_xreact({"controls": ctrl_igg_false, "lots": [build_valid_xreact_lot("LOT-A"), lot_b_untrace]})
    if (
        r50["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or r50["per_lot_verdicts"]["LOT-B"]["independent_matched_igg_provenance_verified"] is not False
        or r50["per_lot_verdicts"]["LOT-B"]["invalid_control_rows_excluded_from_bio_adjudication"] != 120
    ):
        raise RuntimeError(f"XREACT self-test 50 (untraceable independent IgG control reference) must HOLD_INVALID, got {r50}")

    # Case 51 (R09 B1e): Order-independent conflicting independent_matched_igg_controls for same run ([valid, invalid] vs [invalid, valid]) -> BOTH HOLD_INVALID!
    ic_ok = build_valid_xreact_independent_igg_control("LOT-B", "RUN_LOT-B_PLATE_01", "CONTROL-LOT-X")
    ic_bad = dict(ic_ok, max_lysis_pct=12.0)
    lot_b_ic_pf = build_valid_xreact_lot("LOT-B", c3d_values=[20.0] * 6)
    lot_b_ic_pf["independent_matched_igg_isotype_valid"] = True
    lot_b_ic_pf["independent_matched_igg_isotype_lot_id"] = "CONTROL-LOT-X"
    lot_b_ic_pf["independent_matched_igg_controls"] = [ic_ok, ic_bad]
    lot_b_ic_fp = json.loads(json.dumps(lot_b_ic_pf))
    lot_b_ic_fp["independent_matched_igg_controls"] = [ic_bad, ic_ok]
    r51_pf = evaluate_gate30_atg_xreact({"controls": ctrl_igg_false, "lots": [build_valid_xreact_lot("LOT-A"), lot_b_ic_pf]})
    r51_fp = evaluate_gate30_atg_xreact({"controls": ctrl_igg_false, "lots": [build_valid_xreact_lot("LOT-A"), lot_b_ic_fp]})
    if r51_pf["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY" or r51_fp["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY":
        raise RuntimeError(f"XREACT self-test 51 (conflicting independent IgG controls order independence) failed: pf={r51_pf['verdict']}, fp={r51_fp['verdict']}")

    # Case 52 (R09 B1f): Row-level-only traceable independent matched-IgG on Run P2 (covering BOTH 0.0 ug/mL vehicle
    # and 5.0 ug/mL exposure for sc_islet_cd64t_null, no lot-level claim; global isotype invalid) -> biological FAIL!
    lot_b_row_ind = build_valid_xreact_lot("LOT-B")
    for rec in lot_b_row_ind["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null" and rec["dose_ug_ml"] in (0.0, 5.0):
            rec["plate_or_run_id"] = "RUN-LOT-B-P2"
            rec["fab2_deconvolution"]["plate_or_run_id"] = "RUN-LOT-B-P2"
            rec["independent_matched_igg_isotype_valid"] = True
            rec["independent_matched_igg_isotype_lot_id"] = "CONTROL-LOT-P2"
            if rec["dose_ug_ml"] == 5.0:
                rec["c3d_pct"] = 20.0
                rec["fab2_deconvolution"]["intact_igg_c3d_pct"] = 20.0
        else:
            rec["plate_or_run_id"] = "RUN-LOT-B-P1"
            rec["fab2_deconvolution"]["plate_or_run_id"] = "RUN-LOT-B-P1"
    lot_b_row_ind["lot_positive_controls"] = [
        {"lot_id": "LOT-B", "plate_or_run_id": "RUN-LOT-B-P1", "cd3_pos_ctrl_pct": 94.0, "b6h12_pos_ctrl_pct": 95.0},
        {"lot_id": "LOT-B", "plate_or_run_id": "RUN-LOT-B-P2", "cd3_pos_ctrl_pct": 94.0, "b6h12_pos_ctrl_pct": 95.0},
    ]
    lot_b_row_ind["independent_matched_igg_controls"] = [
        build_valid_xreact_independent_igg_control("LOT-B", "RUN-LOT-B-P2", "CONTROL-LOT-P2")
    ]
    r52 = evaluate_gate30_atg_xreact({"controls": ctrl_igg_false, "lots": [build_valid_xreact_lot("LOT-A"), lot_b_row_ind]})
    if (
        r52["verdict"] != "FAIL"
        or r52["per_lot_verdicts"]["LOT-B"]["verified_independent_igg_control_run_ids"] != ["RUN-LOT-B-P2"]
    ):
        raise RuntimeError(f"XREACT self-test 52 (row-level traceable independent IgG control bio FAIL) must FAIL, got {r52}")

    # Case 53 (R09 B1g): Strict JSON decoding on XREACT intake rejects duplicate keys, NaN, and Infinity!
    xreact_json_strict_ok = True
    for bad_json_tok in (
        '{"controls": {"cd3_pos_ctrl_pct": 94.0, "cd3_pos_ctrl_pct": 50.0}}',
        '{"controls": {"cd3_pos_ctrl_pct": NaN}}',
        '{"controls": {"cd3_pos_ctrl_pct": Infinity}}',
    ):
        rejected_this = False
        try:
            load_strict_json_text(bad_json_tok, "xreact_strict_json_probe")
        except ValueError:
            rejected_this = True
        if not rejected_this:
            xreact_json_strict_ok = False
    if not xreact_json_strict_ok:
        raise RuntimeError("XREACT self-test 53 (strict JSON duplicate/NaN/Infinity rejection) failed")

    # Case 54 (R10 B3a): Conflicted primary c3d_pct=20.0 vs linked intact_igg_c3d_pct staying at passing fixture value
    # on sc_islet_cd64t_null @ 5 ug/mL -> disputed endpoint quarantined from BOTH point AND AUC bio adjudication -> HOLD_INVALID (NEVER FAIL!)
    lot_b_conflict_intact = build_valid_xreact_lot("LOT-B")
    for rec in lot_b_conflict_intact["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null" and rec["dose_ug_ml"] == 5.0:
            rec["c3d_pct"] = 20.0
    r54 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_conflict_intact],
    })
    if (
        r54["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or r54["per_lot_verdicts"]["LOT-B"]["linked_endpoint_conflicts_quarantined"] != 6
        or any(rs.startswith("[FAIL]") for rs in r54["reasons"])
    ):
        raise RuntimeError(
            f"XREACT self-test 54 (conflicted primary vs linked intact_igg quarantine) must HOLD_INVALID with 0 FAIL reasons, got {r54}"
        )

    # Case 55 (R10 B3b): Consistent c3d_pct=20.0 AND linked intact_igg_c3d_pct=20.0 on sc_islet_cd64t_null @ 5 ug/mL -> FAIL!
    lot_b_consistent_intact = build_valid_xreact_lot("LOT-B")
    for rec in lot_b_consistent_intact["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null" and rec["dose_ug_ml"] == 5.0:
            rec["c3d_pct"] = 20.0
            rec["fab2_deconvolution"]["intact_igg_c3d_pct"] = 20.0
    r55 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_consistent_intact],
    })
    if r55["verdict"] != "FAIL":
        raise RuntimeError(f"XREACT self-test 55 (consistent 20% primary + intact_igg) must FAIL, got {r55}")

    # Case 56 (R10 B3c): Conflicted LOT-B (20% primary vs passing intact) + SEPARATE consistent failing LOT-A -> FAIL preserved!
    lot_a_consistent_fail = build_valid_xreact_lot("LOT-A", c3d_values=[20.0] * 6)
    r56 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [lot_a_consistent_fail, lot_b_conflict_intact],
    })
    if r56["verdict"] != "FAIL":
        raise RuntimeError(f"XREACT self-test 56 (conflicted LOT-B + separate consistent failing LOT-A) must FAIL, got {r56}")

    # Case 57 (R11 B2a + R13 0037-B1 pure subtraction): Invalid global IgG + linked Fab on separate RUN_LOT-B_FAB_02 ->
    # ALL cross-run Fab endpoints (fab_run != obs_run) are UNCONDITIONALLY withheld to HOLD_INVALID_OR_INCOMPLETE_ASSAY
    # with ZERO [FAIL] reasons (even if independent_matched_igg_controls metadata is supplied for RUN_LOT-B_FAB_02,
    # because fab_run lacks donor/stratum/dose-matched quantitative IgG measurements!); moving Fab onto the SAME run
    # RUN_LOT-B_PLATE_01 (sharing paired quantitative matched_rabbit_igg with valid independent IgG provenance) restores FAIL!
    lot_b_fab_2run = build_valid_xreact_lot("LOT-B")
    lot_b_fab_2run["lot_positive_controls"] = [
        {"lot_id": "LOT-B", "plate_or_run_id": "RUN_LOT-B_PLATE_01", "cd3_pos_ctrl_pct": 94.0, "b6h12_pos_ctrl_pct": 95.0},
        {"lot_id": "LOT-B", "plate_or_run_id": "RUN_LOT-B_FAB_02", "cd3_pos_ctrl_pct": 94.0, "b6h12_pos_ctrl_pct": 95.0},
    ]
    lot_b_fab_2run["independent_matched_igg_isotype_valid"] = True
    lot_b_fab_2run["independent_matched_igg_isotype_lot_id"] = "IND-RABBIT-IGG-LOT-B-2026"
    lot_b_fab_2run["independent_matched_igg_controls"] = [
        build_valid_xreact_independent_igg_control("LOT-B", "RUN_LOT-B_PLATE_01", "IND-RABBIT-IGG-LOT-B-2026"),
    ]
    for rec in lot_b_fab_2run["observations"]:
        rec["fab2_deconvolution"]["plate_or_run_id"] = "RUN_LOT-B_FAB_02"
        if rec["stratum"] == "sc_islet_cd64t_null" and rec["dose_ug_ml"] > 0.0:
            rec["fab2_deconvolution"]["fab2_c3d_pct"] = 20.0
    ctrl_igg_false_fab20 = json.loads(json.dumps(ctrl_igg_false))
    ctrl_igg_false_fab20["fab2_vs_intact_igg_deconvolution"]["direct_fab_c3d_max_pct"] = 20.0
    r57_hold = evaluate_gate30_atg_xreact({
        "controls": ctrl_igg_false_fab20,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_fab_2run],
    })
    lot_b_fab_2run_with_meta = json.loads(json.dumps(lot_b_fab_2run))
    lot_b_fab_2run_with_meta["independent_matched_igg_controls"].append(
        build_valid_xreact_independent_igg_control("LOT-B", "RUN_LOT-B_FAB_02", "IND-RABBIT-IGG-LOT-B-2026")
    )
    r57_xrun_meta_still_hold = evaluate_gate30_atg_xreact({
        "controls": ctrl_igg_false_fab20,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_fab_2run_with_meta],
    })
    lot_b_fab_samerun_fail = json.loads(json.dumps(lot_b_fab_2run))
    for rec in lot_b_fab_samerun_fail["observations"]:
        rec["fab2_deconvolution"]["plate_or_run_id"] = "RUN_LOT-B_PLATE_01"
    r57_fail = evaluate_gate30_atg_xreact({
        "controls": ctrl_igg_false_fab20,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_fab_samerun_fail],
    })
    if (
        r57_hold["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or any(rs.startswith("[FAIL]") for rs in r57_hold["reasons"])
        or not any("CROSS_RUN_FAB_DECONVOLUTION_UNSUPPORTED_REQUIRES_SAME_RUN_PAIRED_CONTROL" in rs for rs in r57_hold["reasons"])
        or r57_xrun_meta_still_hold["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or any(rs.startswith("[FAIL]") for rs in r57_xrun_meta_still_hold["reasons"])
        or not any("CROSS_RUN_FAB_DECONVOLUTION_UNSUPPORTED_REQUIRES_SAME_RUN_PAIRED_CONTROL" in rs for rs in r57_xrun_meta_still_hold["reasons"])
        or r57_fail["verdict"] != "FAIL"
        or r57_hold.get("fab2_same_run_paired_control_required") is not True
        or r57_hold.get("cross_run_fab2_deconvolution_withheld") is not True
    ):
        raise RuntimeError(
            f"XREACT self-test 57 (R11 B2 + R13 0037-B1 cross-run Fab withheld & same-run FAIL) failed: "
            f"hold={r57_hold['verdict']}, xrun_meta={r57_xrun_meta_still_hold['verdict']}, fail={r57_fail['verdict']}"
        )

    # Case 58 (R11 B2b): Uncovered cross-run Fab on RUN_LOT-B_FAB_02 + independently valid failing primary endpoint
    # on RUN_LOT-B_PLATE_01 (which HAS valid independent IgG provenance) -> biological FAIL preserved!
    lot_b_fab_2run_plus_obs_fail = json.loads(json.dumps(lot_b_fab_2run))
    for rec in lot_b_fab_2run_plus_obs_fail["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_pos" and rec["dose_ug_ml"] == 5.0:
            rec["c5b9_pct"] = 20.0
            rec["fab2_deconvolution"]["intact_igg_c5b9_pct"] = 20.0
    r58 = evaluate_gate30_atg_xreact({
        "controls": ctrl_igg_false_fab20,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_fab_2run_plus_obs_fail],
    })
    if r58["verdict"] != "FAIL":
        raise RuntimeError(f"XREACT self-test 58 (R11 B2 uncovered Fab + valid obs_run FAIL) must FAIL, got {r58}")

    # Case 59 (R11 B3a): Positive-exposure {1, 5, 15, 50} C3d = 4.9% (passing) with SOLE invalid measurement at
    # 0.0 ug/mL vehicle (c3d_pct = 100.0%, intact_igg_c3d_pct = 100.0%, matched IgG = 0.4%) -> MUST quarantine
    # BEFORE 0-50 AUC adjudication and return HOLD_INVALID (0 FAIL reasons), NOT permanent FAIL!
    # Restoring the 0.0 ug/mL vehicle baseline to 0.5% -> MUST return PASS!
    lot_b_bad_veh = build_valid_xreact_lot("LOT-B")
    for rec in lot_b_bad_veh["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null":
            if rec["dose_ug_ml"] == 0.0:
                rec["c3d_pct"] = 100.0
                rec["fab2_deconvolution"]["intact_igg_c3d_pct"] = 100.0
                rec["matched_rabbit_igg"]["c3d_pct"] = 0.4
            else:
                rec["c3d_pct"] = 4.9
                rec["fab2_deconvolution"]["intact_igg_c3d_pct"] = 4.9
                rec["matched_rabbit_igg"]["c3d_pct"] = 0.4
    r59_hold = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_bad_veh],
    })
    lot_b_fixed_veh = json.loads(json.dumps(lot_b_bad_veh))
    for rec in lot_b_fixed_veh["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null" and rec["dose_ug_ml"] == 0.0:
            rec["c3d_pct"] = 0.5
            rec["fab2_deconvolution"]["intact_igg_c3d_pct"] = 0.5
    r59_pass = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_fixed_veh],
    })
    if (
        r59_hold["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or any(rs.startswith("[FAIL]") for rs in r59_hold["reasons"])
        or r59_hold["per_lot_verdicts"]["LOT-B"]["vehicle_series_quarantined"] < 6
        or r59_hold.get("vehicle_validated_before_auc_enforced") is not True
        or r59_pass["verdict"] != "PASS"
    ):
        raise RuntimeError(
            f"XREACT self-test 59 (R11 B3 vehicle-before-AUC quarantine) failed: hold={r59_hold['verdict']}, pass={r59_pass['verdict']}"
        )

    # Case 60 (R11 B3b): Invalid 0.0 ug/mL vehicle on sc_islet_cd64t_null + SEPARATE validated failing series on
    # sc_islet_cd64t_pos -> biological FAIL preserved; ALSO invalid 0.0 ug/mL fab2_c3d_pct=100% with passing 4.9%
    # positive-exposure Fab -> HOLD_INVALID (0 FAIL reasons)!
    lot_b_bad_veh_plus_sep_fail = json.loads(json.dumps(lot_b_bad_veh))
    for rec in lot_b_bad_veh_plus_sep_fail["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_pos" and rec["dose_ug_ml"] > 0.0:
            rec["c3d_pct"] = 20.0
            rec["fab2_deconvolution"]["intact_igg_c3d_pct"] = 20.0
    r60_sep_fail = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_bad_veh_plus_sep_fail],
    })
    lot_b_bad_fab_veh = build_valid_xreact_lot("LOT-B")
    for rec in lot_b_bad_fab_veh["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null":
            rec["fab2_deconvolution"]["fab2_c3d_pct"] = 100.0 if rec["dose_ug_ml"] == 0.0 else 4.9
    ctrl_fab100 = json.loads(json.dumps(valid_ctrl))
    ctrl_fab100["fab2_vs_intact_igg_deconvolution"]["direct_fab_c3d_max_pct"] = 100.0
    r60_fab_veh_hold = evaluate_gate30_atg_xreact({
        "controls": ctrl_fab100,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_bad_fab_veh],
    })
    if (
        r60_sep_fail["verdict"] != "FAIL"
        or r60_fab_veh_hold["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or any(rs.startswith("[FAIL]") for rs in r60_fab_veh_hold["reasons"])
    ):
        raise RuntimeError(
            f"XREACT self-test 60 (R11 B3 separate validated FAIL + fab2 vehicle quarantine) failed: "
            f"sep_fail={r60_sep_fail['verdict']}, fab_veh_hold={r60_fab_veh_hold['verdict']}"
        )

    # Case 61 (R12 0037-B1a): Sol's exact HLA-E 0.0 ug/mL vehicle positive-control run failure!
    # When one stratum's six 0.0 ug/mL vehicle rows fail positive-control validation, ALL dependent endpoints
    # (point-level, 1-15 AUC, AND 0-50 AUC) for that stratum MUST quarantine to HOLD_INVALID_OR_INCOMPLETE_ASSAY
    # (BOTH with passing clinical-dose HLA-E AND with failing 50% clinical-dose HLA-E -> ZERO [FAIL] reasons!),
    # while a separate valid failing stratum/lot STILL preserves fail-first biological FAIL!
    lot_b_veh_posfail_pass = build_valid_xreact_lot("LOT-B")
    lot_b_veh_posfail_pass["lot_positive_controls"] = [
        {"lot_id": "LOT-B", "plate_or_run_id": "RUN_LOT-B_PLATE_01", "cd3_pos_ctrl_pct": 94.0, "b6h12_pos_ctrl_pct": 95.0},
        {"lot_id": "LOT-B", "plate_or_run_id": "RUN_LOT-B_VEH_FAIL", "cd3_pos_ctrl_pct": 50.0, "b6h12_pos_ctrl_pct": 95.0},
    ]
    for rec in lot_b_veh_posfail_pass["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null" and rec["dose_ug_ml"] == 0.0:
            rec["plate_or_run_id"] = "RUN_LOT-B_VEH_FAIL"
            rec["fab2_deconvolution"]["plate_or_run_id"] = "RUN_LOT-B_VEH_FAIL"
    r61_pass_clin = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_veh_posfail_pass],
    })
    lot_b_veh_posfail_low_hlae = json.loads(json.dumps(lot_b_veh_posfail_pass))
    for rec in lot_b_veh_posfail_low_hlae["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null" and rec["dose_ug_ml"] in (1.0, 5.0, 15.0):
            rec["hla_e_binding_retention_pct"] = 50.0
    r61_low_clin = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_veh_posfail_low_hlae],
    })
    lot_b_veh_posfail_sep_fail = json.loads(json.dumps(lot_b_veh_posfail_low_hlae))
    for rec in lot_b_veh_posfail_sep_fail["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_pos" and rec["dose_ug_ml"] in (1.0, 5.0, 15.0):
            rec["hla_e_binding_retention_pct"] = 50.0
    r61_sep_fail = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_veh_posfail_sep_fail],
    })
    if (
        r61_pass_clin["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or r61_pass_clin["per_lot_verdicts"]["LOT-B"]["vehicle_series_quarantined"] == 0
        or any(k.startswith("sc_islet_cd64t_null@") for k in r61_pass_clin["per_lot_verdicts"]["LOT-B"]["endpoints"]["XREACT_HLA_E_BINDING_RETENTION"])
        or r61_low_clin["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or any(rs.startswith("[FAIL]") for rs in r61_low_clin["reasons"])
        or r61_sep_fail["verdict"] != "FAIL"
    ):
        raise RuntimeError(
            f"XREACT self-test 61 (R12 0037-B1 vehicle positive-control run failure quarantine) failed: "
            f"pass_clin={r61_pass_clin['verdict']}, low_clin={r61_low_clin['verdict']}, sep_fail={r61_sep_fail['verdict']}"
        )

    # Case 62 (R12 0037-B1b): Sol's exact HLA-E 0.0 ug/mL vehicle invalid matched-IgG baseline AND Fab-only 0.0 ug/mL
    # vehicle control failure -> BOTH quarantine to HOLD_INVALID_OR_INCOMPLETE_ASSAY with ZERO [FAIL] reasons!
    lot_b_veh_iggfail = build_valid_xreact_lot("LOT-B")
    for rec in lot_b_veh_iggfail["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null":
            if rec["dose_ug_ml"] == 0.0:
                rec["matched_rabbit_igg"]["hla_e_binding_retention_pct"] = 50.0
            elif rec["dose_ug_ml"] in (1.0, 5.0, 15.0):
                rec["hla_e_binding_retention_pct"] = 50.0
    r62_igg_veh = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_veh_iggfail],
    })
    lot_b_fab_veh_ctrlfail = build_valid_xreact_lot("LOT-B")
    lot_b_fab_veh_ctrlfail["lot_positive_controls"] = [
        {"lot_id": "LOT-B", "plate_or_run_id": "RUN_LOT-B_PLATE_01", "cd3_pos_ctrl_pct": 94.0, "b6h12_pos_ctrl_pct": 95.0},
        {"lot_id": "LOT-B", "plate_or_run_id": "RUN_LOT-B_FAB_VEH_BAD", "cd3_pos_ctrl_pct": 50.0, "b6h12_pos_ctrl_pct": 95.0},
    ]
    for rec in lot_b_fab_veh_ctrlfail["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null":
            if rec["dose_ug_ml"] == 0.0:
                rec["fab2_deconvolution"]["plate_or_run_id"] = "RUN_LOT-B_FAB_VEH_BAD"
            elif rec["dose_ug_ml"] in (1.0, 5.0, 15.0):
                rec["fab2_deconvolution"]["fab2_c3d_pct"] = 20.0
    ctrl_fab20_valid = json.loads(json.dumps(valid_ctrl))
    ctrl_fab20_valid["fab2_vs_intact_igg_deconvolution"]["direct_fab_c3d_max_pct"] = 20.0
    r62_fab_veh = evaluate_gate30_atg_xreact({
        "controls": ctrl_fab20_valid,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_fab_veh_ctrlfail],
    })
    if (
        r62_igg_veh["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or any(rs.startswith("[FAIL]") for rs in r62_igg_veh["reasons"])
        or r62_igg_veh["per_lot_verdicts"]["LOT-B"]["vehicle_series_quarantined"] == 0
        or r62_fab_veh["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or any(rs.startswith("[FAIL]") for rs in r62_fab_veh["reasons"])
    ):
        raise RuntimeError(
            f"XREACT self-test 62 (R12 0037-B1 vehicle invalid IgG & Fab vehicle control failure) failed: "
            f"igg_veh={r62_igg_veh['verdict']}, fab_veh={r62_fab_veh['verdict']}"
        )

    # Case 63 (R12 0037-B4a): Sol's exact global-IgG-valid cross-run Fab (fab_run != obs_run) WITHOUT
    # independent_matched_igg_controls for fab_run -> MUST quarantine to HOLD_INVALID_OR_INCOMPLETE_ASSAY
    # (NEVER PASS on passing Fab AND NEVER biological FAIL on 20% Fab)!
    lot_b_global_valid_xrun_pass = build_valid_xreact_lot("LOT-B")
    lot_b_global_valid_xrun_pass["lot_positive_controls"] = [
        {"lot_id": "LOT-B", "plate_or_run_id": "RUN_LOT-B_PLATE_01", "cd3_pos_ctrl_pct": 94.0, "b6h12_pos_ctrl_pct": 95.0},
        {"lot_id": "LOT-B", "plate_or_run_id": "RUN_LOT-B_FAB_02", "cd3_pos_ctrl_pct": 94.0, "b6h12_pos_ctrl_pct": 95.0},
    ]
    for rec in lot_b_global_valid_xrun_pass["observations"]:
        rec["fab2_deconvolution"]["plate_or_run_id"] = "RUN_LOT-B_FAB_02"
    r63_pass_held = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_global_valid_xrun_pass],
    })
    lot_b_global_valid_xrun_fab20 = json.loads(json.dumps(lot_b_global_valid_xrun_pass))
    for rec in lot_b_global_valid_xrun_fab20["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null" and rec["dose_ug_ml"] > 0.0:
            rec["fab2_deconvolution"]["fab2_c3d_pct"] = 20.0
    r63_fab20_held = evaluate_gate30_atg_xreact({
        "controls": ctrl_fab20_valid,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_global_valid_xrun_fab20],
    })
    if (
        r63_pass_held["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or r63_pass_held["per_lot_verdicts"]["LOT-B"]["verified_independent_igg_control_run_ids"] != []
        or r63_fab20_held["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or any(rs.startswith("[FAIL]") for rs in r63_fab20_held["reasons"])
    ):
        raise RuntimeError(
            f"XREACT self-test 63 (R12 0037-B4 global-IgG-valid uncovered cross-run Fab) failed: "
            f"pass_held={r63_pass_held['verdict']}, fab20_held={r63_fab20_held['verdict']}"
        )

    # Case 64 (R12 0037-B4b + R13 0037-B1 pure subtraction): Global-IgG-valid cross-run Fab EVEN WITH
    # independent_matched_igg_controls metadata for fab_run MUST STILL BE WITHHELD to HOLD_INVALID_OR_INCOMPLETE_ASSAY
    # (0 [FAIL] reasons on 20% cross-run Fab, NEVER PASS on passing cross-run Fab!), while same-run Fab
    # (fab_run == obs_run) passes/fails cleanly AND cross-run Fab + valid obs_run failing primary c5b9_pct=20% -> FAIL!
    lot_b_xrun_covered_pass = json.loads(json.dumps(lot_b_global_valid_xrun_pass))
    lot_b_xrun_covered_pass["independent_matched_igg_controls"] = [
        build_valid_xreact_independent_igg_control("LOT-B", "RUN_LOT-B_FAB_02", "IND-IGG-FAB-02")
    ]
    for rec in lot_b_xrun_covered_pass["observations"]:
        rec["fab2_deconvolution"]["independent_matched_igg_isotype_valid"] = True
        rec["fab2_deconvolution"]["independent_matched_igg_isotype_lot_id"] = "IND-IGG-FAB-02"
    r64_xrun_meta_pass_held = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_xrun_covered_pass],
    })
    lot_b_xrun_covered_fail = json.loads(json.dumps(lot_b_xrun_covered_pass))
    for rec in lot_b_xrun_covered_fail["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null" and rec["dose_ug_ml"] > 0.0:
            rec["fab2_deconvolution"]["fab2_c3d_pct"] = 20.0
    r64_xrun_meta_fail_held = evaluate_gate30_atg_xreact({
        "controls": ctrl_fab20_valid,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_xrun_covered_fail],
    })
    lot_b_samerun_pass = build_valid_xreact_lot("LOT-B")
    r64_samerun_pass = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_samerun_pass],
    })
    lot_b_samerun_fail = build_valid_xreact_lot("LOT-B")
    for rec in lot_b_samerun_fail["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null" and rec["dose_ug_ml"] > 0.0:
            rec["fab2_deconvolution"]["fab2_c3d_pct"] = 20.0
    r64_samerun_fail = evaluate_gate30_atg_xreact({
        "controls": ctrl_fab20_valid,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_samerun_fail],
    })
    lot_b_xrun_uncovered_plus_obs_fail = json.loads(json.dumps(lot_b_global_valid_xrun_pass))
    for rec in lot_b_xrun_uncovered_plus_obs_fail["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_pos" and rec["dose_ug_ml"] == 5.0:
            rec["c5b9_pct"] = 20.0
            rec["fab2_deconvolution"]["intact_igg_c5b9_pct"] = 20.0
    r64_obs_fail = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_xrun_uncovered_plus_obs_fail],
    })
    if (
        r64_xrun_meta_pass_held["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or any(rs.startswith("[FAIL]") for rs in r64_xrun_meta_pass_held["reasons"])
        or not any("CROSS_RUN_FAB_DECONVOLUTION_UNSUPPORTED_REQUIRES_SAME_RUN_PAIRED_CONTROL" in rs for rs in r64_xrun_meta_pass_held["reasons"])
        or r64_xrun_meta_fail_held["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or any(rs.startswith("[FAIL]") for rs in r64_xrun_meta_fail_held["reasons"])
        or r64_samerun_pass["verdict"] != "PASS"
        or r64_samerun_fail["verdict"] != "FAIL"
        or r64_obs_fail["verdict"] != "FAIL"
    ):
        raise RuntimeError(
            f"XREACT self-test 64 (R13 0037-B1 cross-run Fab unconditionally withheld + same-run pass/fail + obs FAIL) failed: "
            f"xrun_pass={r64_xrun_meta_pass_held['verdict']}, xrun_fail={r64_xrun_meta_fail_held['verdict']}, "
            f"samerun_pass={r64_samerun_pass['verdict']}, samerun_fail={r64_samerun_fail['verdict']}, obs_fail={r64_obs_fail['verdict']}"
        )

    # Case 65 (R13 0037-B1 Sol cross-run Fab AUC comparator closure): Verify ZERO Fab point or Fab AUC endpoints
    # are biologically adjudicated on a cross-run lot even when fab_run carries valid positive controls + metadata
    # independent_matched_igg_controls, while a SEPARATE valid same-run failing lot (LOT-A) STILL returns FAIL!
    lot_b_xrun_auc_zero = json.loads(json.dumps(lot_b_xrun_covered_fail))
    r65_xrun_withheld = evaluate_gate30_atg_xreact({
        "controls": ctrl_fab20_valid,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_xrun_auc_zero],
    })
    lot_b_xrun_ep = r65_xrun_withheld["per_lot_verdicts"]["LOT-B"]["endpoints"]
    lot_b_xrun_fab_auc_keys = [
        k for k in lot_b_xrun_ep["XREACT_PER_DONOR_DOSE_AUC_VS_MATCHED_IGG"] if k.startswith("fab2_")
    ]
    lot_a_samerun_fab_fail = build_valid_xreact_lot("LOT-A")
    for rec in lot_a_samerun_fab_fail["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null" and rec["dose_ug_ml"] > 0.0:
            rec["fab2_deconvolution"]["fab2_c3d_pct"] = 20.0
    r65_sep_samerun_fail = evaluate_gate30_atg_xreact({
        "controls": ctrl_fab20_valid,
        "lots": [lot_a_samerun_fab_fail, lot_b_xrun_auc_zero],
    })
    if (
        r65_xrun_withheld["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or any(rs.startswith("[FAIL]") for rs in r65_xrun_withheld["reasons"])
        or len(lot_b_xrun_ep["XREACT_LINKED_FAB2_C3D"]) != 0
        or len(lot_b_xrun_ep["XREACT_LINKED_FAB2_C5B9"]) != 0
        or len(lot_b_xrun_ep["XREACT_LINKED_FAB2_LYSIS"]) != 0
        or len(lot_b_xrun_fab_auc_keys) != 0
        or r65_sep_samerun_fail["verdict"] != "FAIL"
    ):
        raise RuntimeError(
            f"XREACT self-test 65 (R13 0037-B1 cross-run Fab AUC zero-adjudication + sep same-run FAIL) failed: "
            f"withheld={r65_xrun_withheld['verdict']}, fab_auc_keys={lot_b_xrun_fab_auc_keys}, sep_fail={r65_sep_samerun_fail['verdict']}"
        )

    # Case 66 (R16 0037-B1): Uncapped paired ratios (100 * ATG / IgG) across HLA-E (point + 1-15 & 0-50 AUC),
    # CD47 AUC, and SC-islet / iEC viability AUCs! Sol's exact 6-donor HLA-E reproducer: 5 donors at 90/100 and
    # 1 donor at 100/80 in a complete two-lot synthetic panel -> uncapped ratios [90, 90, 90, 90, 90, 125] ->
    # Student-t L95 = 80.8383% < 85.0% -> HOLD across all 3 clinical points and both AUC brackets!
    lot_b_hla_ratio = build_valid_xreact_lot("LOT-B")
    donors_b66 = sorted({rec["donor_id"] for rec in lot_b_hla_ratio["observations"]})
    for rec in lot_b_hla_ratio["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null":
            if rec["donor_id"] == donors_b66[-1]:
                rec["hla_e_binding_retention_pct"] = 100.0
                rec["matched_rabbit_igg"]["hla_e_binding_retention_pct"] = 80.0
            else:
                rec["hla_e_binding_retention_pct"] = 90.0
                rec["matched_rabbit_igg"]["hla_e_binding_retention_pct"] = 100.0
    r66_hla = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_hla_ratio],
    })
    ep66_hla = r66_hla["per_lot_verdicts"]["LOT-B"]["endpoints"]
    hla_pt_l95s = [
        ep66_hla["XREACT_HLA_E_BINDING_RETENTION"][f"sc_islet_cd64t_null@{d}"]["paired_atg_over_igg_pct"]["l95_t"]
        for d in (1, 5, 15)
    ]
    hla_pt_verdicts = [
        ep66_hla["XREACT_HLA_E_BINDING_RETENTION"][f"sc_islet_cd64t_null@{d}"]["paired_atg_over_igg_pct"]["verdict"]
        for d in (1, 5, 15)
    ]
    hla_abs_l95 = ep66_hla["XREACT_HLA_E_BINDING_RETENTION"]["sc_islet_cd64t_null@1"]["absolute_retention_pct"]["l95_t"]
    hla_auc_1_15 = ep66_hla["XREACT_PER_DONOR_DOSE_AUC_VS_MATCHED_IGG"]["hla_e_auc_1_15@sc_islet_cd64t_null"]["paired_atg_over_igg_auc"]
    hla_auc_0_50 = ep66_hla["XREACT_PER_DONOR_DOSE_AUC_VS_MATCHED_IGG"]["hla_e_auc_0_50@sc_islet_cd64t_null"]["paired_atg_over_igg_auc"]

    lot_b_cd47_ratio = build_valid_xreact_lot("LOT-B")
    for rec in lot_b_cd47_ratio["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null":
            if rec["donor_id"] == donors_b66[-1]:
                rec["cd47_sirpa_retention_pct"] = 100.0
                rec["matched_rabbit_igg"]["cd47_sirpa_retention_pct"] = 80.0
            else:
                rec["cd47_sirpa_retention_pct"] = 90.0
                rec["matched_rabbit_igg"]["cd47_sirpa_retention_pct"] = 100.0
    r66_cd47 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_cd47_ratio],
    })
    cd47_auc_1_15 = r66_cd47["per_lot_verdicts"]["LOT-B"]["endpoints"]["XREACT_PER_DONOR_DOSE_AUC_VS_MATCHED_IGG"]["cd47_auc_1_15@sc_islet_cd64t_null"]

    lot_b_viab_ratio = build_valid_xreact_lot("LOT-B")
    for rec in lot_b_viab_ratio["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null":
            if rec["donor_id"] == donors_b66[-1]:
                rec["sc_islet_viability_pct"] = 100.0
                rec["matched_rabbit_igg"]["sc_islet_viability_pct"] = 80.0
            else:
                rec["sc_islet_viability_pct"] = 95.0
                rec["matched_rabbit_igg"]["sc_islet_viability_pct"] = 100.0
    r66_viab = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_viab_ratio],
    })
    viab_auc_1_15 = r66_viab["per_lot_verdicts"]["LOT-B"]["endpoints"]["XREACT_PER_DONOR_DOSE_AUC_VS_MATCHED_IGG"]["sc_viab_auc_1_15@sc_islet_cd64t_null"]

    if (
        r66_hla["verdict"] != "HOLD"
        or r66_hla.get("uncapped_paired_ratios_enforced") is not True
        or any(v != "HOLD" for v in hla_pt_verdicts)
        or any(abs(v - 80.8383) > 1e-4 for v in hla_pt_l95s)
        or abs(hla_abs_l95 - 87.3824) > 1e-4
        or hla_auc_1_15["verdict"] != "HOLD"
        or abs(hla_auc_1_15["l95_t"] - 80.8383) > 1e-4
        or hla_auc_0_50["verdict"] != "HOLD"
        or abs(hla_auc_0_50["l95_t"] - 80.8383) > 1e-4
        or not any("85.0% paired lower-bound criterion" in rs for rs in r66_hla["reasons"])
        or r66_cd47["verdict"] != "HOLD"
        or cd47_auc_1_15["verdict"] != "HOLD"
        or abs(cd47_auc_1_15["l95_t"] - 80.8383) > 1e-4
        or r66_viab["verdict"] == "PASS"
        or viab_auc_1_15["verdict"] == "PASS"
        or viab_auc_1_15["l95_t"] >= 90.0
    ):
        raise RuntimeError(
            f"XREACT self-test 66 (R16 0037-B1 uncapped paired ratios HLA-E/CD47/viability) failed: "
            f"hla={r66_hla['verdict']} pts={hla_pt_l95s} auc1_15={hla_auc_1_15} auc0_50={hla_auc_0_50}, "
            f"cd47={r66_cd47['verdict']} {cd47_auc_1_15}, viab={r66_viab['verdict']} {viab_auc_1_15}"
        )

    # Case 67 (R16 0037-M1): Adjudicable same-run Fab maxima MUST exclude withheld cross-run Fab rows
    # (c3d stays 1.8%, NOT 4.0%), report withheld_cross_run_fab_maxima separately (4.0%), and set
    # linked_fab2_deconvolution_reconciled=False whenever any cross-run Fab row is withheld!
    lot_b_xrun_c3d4 = build_valid_xreact_lot("LOT-B")
    lot_b_xrun_c3d4["lot_positive_controls"] = [
        {"lot_id": "LOT-B", "plate_or_run_id": "RUN_LOT-B_PLATE_01", "cd3_pos_ctrl_pct": 94.0, "b6h12_pos_ctrl_pct": 95.0},
        {"lot_id": "LOT-B", "plate_or_run_id": "RUN_LOT-B_FAB_02", "cd3_pos_ctrl_pct": 94.0, "b6h12_pos_ctrl_pct": 95.0},
    ]
    for rec in lot_b_xrun_c3d4["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null" and rec["dose_ug_ml"] == 15.0:
            rec["fab2_deconvolution"]["plate_or_run_id"] = "RUN_LOT-B_FAB_02"
            rec["fab2_deconvolution"]["fab2_c3d_pct"] = 4.0
    ctrl_fab4_m1 = json.loads(json.dumps(valid_ctrl))
    ctrl_fab4_m1["fab2_vs_intact_igg_deconvolution"]["direct_fab_c3d_max_pct"] = 4.0
    r67_ctrl4 = evaluate_gate30_atg_xreact({
        "controls": ctrl_fab4_m1,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_xrun_c3d4],
    })
    r67_ctrl18 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_xrun_c3d4],
    })
    if (
        r67_ctrl4["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or any(rs.startswith("[FAIL]") for rs in r67_ctrl4["reasons"])
        or r67_ctrl4["derived_direct_fab_maxima_pct"]["direct_fab_c3d_max_pct"] != 1.8
        or r67_ctrl4["withheld_cross_run_fab_maxima"]["direct_fab_c3d_max_pct"] != 4.0
        or r67_ctrl4["withheld_cross_run_fab_rows_count"] != 6
        or r67_ctrl4["linked_fab2_deconvolution_reconciled"] is not False
        or r67_ctrl18["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or r67_ctrl18["derived_direct_fab_maxima_pct"]["direct_fab_c3d_max_pct"] != 1.8
        or r67_ctrl18["withheld_cross_run_fab_maxima"]["direct_fab_c3d_max_pct"] != 4.0
        or r67_ctrl18["linked_fab2_deconvolution_reconciled"] is not False
    ):
        raise RuntimeError(
            f"XREACT self-test 67 (R16 0037-M1 separated adjudicable vs withheld cross-run Fab maxima) failed: "
            f"ctrl4={r67_ctrl4['derived_direct_fab_maxima_pct']} withheld={r67_ctrl4['withheld_cross_run_fab_maxima']} rec={r67_ctrl4['linked_fab2_deconvolution_reconciled']}, "
            f"ctrl18_rec={r67_ctrl18['linked_fab2_deconvolution_reconciled']}"
        )

    # Cases 68-72 (R16 0037-B1 5-way XREACT rejected-Fab-linkage vs primary FAIL regression matrix):
    # Control-valid primary 12.0% C3d FAIL on sc_islet_cd64t_null @ 15 ug/mL across all 6 donors:
    #   (68) valid same-run agreement (intact_igg_c3d_pct=12.0%) -> FAIL
    #   (69) valid same-run discordance (intact_igg_c3d_pct=1.2% on matching lot/donor/stratum/dose & same run) -> HOLD (0 [FAIL], 6 conflicts)
    #   (70) missing linkage (lot_id & donor_id omitted in fab2_deconvolution, intact=1.2%) -> FAIL (primary preserved, 0 conflicts!)
    #   (71) wrong-donor linkage (donor_id='WRONG_DONOR_99' in fab2_deconvolution, intact=1.2%) -> FAIL (primary preserved, 0 conflicts!)
    #   (72) cross-run linkage (plate_or_run_id='RUN_LOT-B_FAB_02' in fab2_deconvolution, intact=1.2%) -> FAIL (primary preserved, 0 conflicts!)
    lot_b_m68_agree = build_valid_xreact_lot("LOT-B")
    for rec in lot_b_m68_agree["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null" and rec["dose_ug_ml"] == 15.0:
            rec["c3d_pct"] = 12.0
            rec["fab2_deconvolution"]["intact_igg_c3d_pct"] = 12.0
    r68_agree = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_m68_agree],
    })
    if (
        r68_agree["verdict"] != "FAIL"
        or r68_agree.get("rejected_fab_linkage_excluded_from_primary_quarantine") is not True
        or r68_agree["per_lot_verdicts"]["LOT-B"]["linked_endpoint_conflicts_quarantined"] != 0
    ):
        raise RuntimeError(f"XREACT self-test 68 (same-run agreement on 12% C3d FAIL) failed: {r68_agree['verdict']}")

    lot_b_m69_discord = build_valid_xreact_lot("LOT-B")
    for rec in lot_b_m69_discord["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null" and rec["dose_ug_ml"] == 15.0:
            rec["c3d_pct"] = 12.0
            rec["fab2_deconvolution"]["intact_igg_c3d_pct"] = 1.2
    r69_discord = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_m69_discord],
    })
    if (
        r69_discord["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or any(rs.startswith("[FAIL]") for rs in r69_discord["reasons"])
        or r69_discord["per_lot_verdicts"]["LOT-B"]["linked_endpoint_conflicts_quarantined"] != 6
    ):
        raise RuntimeError(
            f"XREACT self-test 69 (valid same-run discordance must quarantine primary to HOLD) failed: "
            f"verdict={r69_discord['verdict']}, q={r69_discord['per_lot_verdicts']['LOT-B']['linked_endpoint_conflicts_quarantined']}"
        )

    lot_b_m70_miss_link = json.loads(json.dumps(lot_b_m69_discord))
    for rec in lot_b_m70_miss_link["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null" and rec["dose_ug_ml"] == 15.0:
            rec["fab2_deconvolution"].pop("lot_id", None)
            rec["fab2_deconvolution"].pop("donor_id", None)
    r70_miss_link = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_m70_miss_link],
    })
    if (
        r70_miss_link["verdict"] != "FAIL"
        or r70_miss_link["per_lot_verdicts"]["LOT-B"]["linked_endpoint_conflicts_quarantined"] != 0
        or r70_miss_link["per_lot_verdicts"]["LOT-B"]["endpoints"]["XREACT_COMPLEMENT_C3D"]["sc_islet_cd64t_null@15"]["verdict"] != "FAIL"
    ):
        raise RuntimeError(
            f"XREACT self-test 70 (missing Fab linkage must NEVER quarantine qualified 12% C3d FAIL) failed: "
            f"verdict={r70_miss_link['verdict']}, q={r70_miss_link['per_lot_verdicts']['LOT-B']['linked_endpoint_conflicts_quarantined']}"
        )

    lot_b_m71_wrong_donor = json.loads(json.dumps(lot_b_m69_discord))
    for rec in lot_b_m71_wrong_donor["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null" and rec["dose_ug_ml"] == 15.0:
            rec["fab2_deconvolution"]["donor_id"] = "WRONG_DONOR_99"
    r71_wrong_donor = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_m71_wrong_donor],
    })
    if (
        r71_wrong_donor["verdict"] != "FAIL"
        or r71_wrong_donor["per_lot_verdicts"]["LOT-B"]["linked_endpoint_conflicts_quarantined"] != 0
        or r71_wrong_donor["per_lot_verdicts"]["LOT-B"]["endpoints"]["XREACT_COMPLEMENT_C3D"]["sc_islet_cd64t_null@15"]["verdict"] != "FAIL"
    ):
        raise RuntimeError(
            f"XREACT self-test 71 (wrong-donor Fab linkage must NEVER quarantine qualified 12% C3d FAIL) failed: "
            f"verdict={r71_wrong_donor['verdict']}, q={r71_wrong_donor['per_lot_verdicts']['LOT-B']['linked_endpoint_conflicts_quarantined']}"
        )

    lot_b_m72_cross_run = json.loads(json.dumps(lot_b_m69_discord))
    lot_b_m72_cross_run["lot_positive_controls"] = [
        {"lot_id": "LOT-B", "plate_or_run_id": "RUN_LOT-B_PLATE_01", "cd3_pos_ctrl_pct": 94.0, "b6h12_pos_ctrl_pct": 95.0},
        {"lot_id": "LOT-B", "plate_or_run_id": "RUN_LOT-B_FAB_02", "cd3_pos_ctrl_pct": 94.0, "b6h12_pos_ctrl_pct": 95.0},
    ]
    for rec in lot_b_m72_cross_run["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null" and rec["dose_ug_ml"] == 15.0:
            rec["fab2_deconvolution"]["plate_or_run_id"] = "RUN_LOT-B_FAB_02"
    r72_cross_run = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_m72_cross_run],
    })
    if (
        r72_cross_run["verdict"] != "FAIL"
        or r72_cross_run["per_lot_verdicts"]["LOT-B"]["linked_endpoint_conflicts_quarantined"] != 0
        or r72_cross_run["per_lot_verdicts"]["LOT-B"]["endpoints"]["XREACT_COMPLEMENT_C3D"]["sc_islet_cd64t_null@15"]["verdict"] != "FAIL"
        or r72_cross_run["withheld_cross_run_fab_rows_count"] != 6
    ):
        raise RuntimeError(
            f"XREACT self-test 72 (cross-run Fab linkage must NEVER quarantine qualified 12% C3d FAIL) failed: "
            f"verdict={r72_cross_run['verdict']}, q={r72_cross_run['per_lot_verdicts']['LOT-B']['linked_endpoint_conflicts_quarantined']}"
        )

    # Case 73 (R16 0037-M1 vehicle-qualified Fab maxima): A 6.0% Fab C3d vehicle row (dose 0.0 > 5.0% baseline limit)
    # MUST NOT enter derived_direct_fab_maxima_pct (which stays strictly 1.8%), MUST be disclosed separately under
    # invalid_vehicle_fab_maxima_pct (6.0%), and MUST set linked_fab2_deconvolution_reconciled=False under BOTH
    # controls.fab2=6.0% and controls.fab2=1.8%!
    lot_b_m73_veh6 = build_valid_xreact_lot("LOT-B")
    donors_m73 = sorted({rec["donor_id"] for rec in lot_b_m73_veh6["observations"]})
    for rec in lot_b_m73_veh6["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null" and rec["donor_id"] == donors_m73[0] and rec["dose_ug_ml"] == 0.0:
            rec["fab2_deconvolution"]["fab2_c3d_pct"] = 6.0
    ctrl_fab6_m73 = json.loads(json.dumps(valid_ctrl))
    ctrl_fab6_m73["fab2_vs_intact_igg_deconvolution"]["direct_fab_c3d_max_pct"] = 6.0
    r73_veh6_ctrl6 = evaluate_gate30_atg_xreact({
        "controls": ctrl_fab6_m73,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_m73_veh6],
    })
    r73_veh6_ctrl18 = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_m73_veh6],
    })
    if (
        r73_veh6_ctrl6["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or any(rs.startswith("[FAIL]") for rs in r73_veh6_ctrl6["reasons"])
        or r73_veh6_ctrl6["derived_direct_fab_maxima_pct"]["direct_fab_c3d_max_pct"] != 1.8
        or r73_veh6_ctrl6["invalid_vehicle_fab_maxima_pct"]["direct_fab_c3d_max_pct"] != 6.0
        or r73_veh6_ctrl6["withheld_invalid_vehicle_fab_rows_count"] != 5
        or r73_veh6_ctrl6["linked_fab2_deconvolution_reconciled"] is not False
        or r73_veh6_ctrl18["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or any(rs.startswith("[FAIL]") for rs in r73_veh6_ctrl18["reasons"])
        or r73_veh6_ctrl18["derived_direct_fab_maxima_pct"]["direct_fab_c3d_max_pct"] != 1.8
        or r73_veh6_ctrl18["invalid_vehicle_fab_maxima_pct"]["direct_fab_c3d_max_pct"] != 6.0
        or r73_veh6_ctrl18["linked_fab2_deconvolution_reconciled"] is not False
    ):
        raise RuntimeError(
            f"XREACT self-test 73 (R16 0037-M1 invalid-vehicle Fab excluded from derived maxima) failed: "
            f"ctrl6={r73_veh6_ctrl6['derived_direct_fab_maxima_pct']} inv={r73_veh6_ctrl6['invalid_vehicle_fab_maxima_pct']} "
            f"cnt={r73_veh6_ctrl6['withheld_invalid_vehicle_fab_rows_count']} rec={r73_veh6_ctrl6['linked_fab2_deconvolution_reconciled']}, "
            f"ctrl18_rec={r73_veh6_ctrl18['linked_fab2_deconvolution_reconciled']}"
        )

    # Case 74 (R17 0042-B1 vehicle-invalid Fab link MUST NOT suppress qualified primary XREACT failure):
    # Qualify linked Fab vehicle per endpoint STRICTLY BEFORE applying same-run intact-IgG discordance quarantine:
    #   (a) Invalid Fab C3d vehicle (fab2_c3d_pct=6.0 at dose 0.0) + same-run intact_igg_c3d_pct=1.2 vs qualified
    #       primary c3d_pct=12.0 at dose 15.0 -> RETAINS qualified primary FAIL (0 linked endpoint conflicts quarantined);
    #   (b) Valid Fab C3d vehicle (fab2_c3d_pct=1.0 at dose 0.0) + same-run intact_igg_c3d_pct=1.2 vs primary
    #       c3d_pct=12.0 at dose 15.0 -> quarantines primary C3d to HOLD_INVALID_OR_INCOMPLETE_ASSAY (0 [FAIL], 6 conflicts);
    #   (c) Per-endpoint precision: invalid Fab lysis vehicle ONLY (fab2_lysis_pct=6.0 at dose 0.0, fab2_c3d_pct=1.0 valid)
    #       + same-run C3d discordance -> STILL quarantines C3d to HOLD (0 [FAIL], 6 conflicts);
    #   (d) Invalid Fab vehicle positive control (RUN_LOT-B_FAB_VEH_BAD at dose 0.0) + same-run C3d discordance ->
    #       RETAINS qualified primary FAIL (0 linked endpoint conflicts quarantined)!
    lot_b_m74_valid_veh = build_valid_xreact_lot("LOT-B")
    for rec in lot_b_m74_valid_veh["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null" and rec["dose_ug_ml"] == 15.0:
            rec["c3d_pct"] = 12.0
            rec["fab2_deconvolution"]["intact_igg_c3d_pct"] = 1.2
    r74_valid_veh_hold = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_m74_valid_veh],
    })

    lot_b_m74_inv_c3d_veh = json.loads(json.dumps(lot_b_m74_valid_veh))
    for rec in lot_b_m74_inv_c3d_veh["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null" and rec["dose_ug_ml"] == 0.0:
            rec["fab2_deconvolution"]["fab2_c3d_pct"] = 6.0
    r74_inv_c3d_veh_fail = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_m74_inv_c3d_veh],
    })

    lot_b_m74_inv_lysis_only = json.loads(json.dumps(lot_b_m74_valid_veh))
    for rec in lot_b_m74_inv_lysis_only["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null" and rec["dose_ug_ml"] == 0.0:
            rec["fab2_deconvolution"]["fab2_lysis_pct"] = 6.0
    r74_inv_lysis_only_hold = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_m74_inv_lysis_only],
    })

    lot_b_m74_inv_ctrl_veh = json.loads(json.dumps(lot_b_m74_valid_veh))
    lot_b_m74_inv_ctrl_veh["lot_positive_controls"] = [
        {"lot_id": "LOT-B", "plate_or_run_id": "RUN_LOT-B_PLATE_01", "cd3_pos_ctrl_pct": 94.0, "b6h12_pos_ctrl_pct": 95.0},
        {"lot_id": "LOT-B", "plate_or_run_id": "RUN_LOT-B_FAB_VEH_BAD", "cd3_pos_ctrl_pct": 50.0, "b6h12_pos_ctrl_pct": 95.0},
    ]
    for rec in lot_b_m74_inv_ctrl_veh["observations"]:
        if rec["stratum"] == "sc_islet_cd64t_null" and rec["dose_ug_ml"] == 0.0:
            rec["fab2_deconvolution"]["plate_or_run_id"] = "RUN_LOT-B_FAB_VEH_BAD"
    r74_inv_ctrl_veh_fail = evaluate_gate30_atg_xreact({
        "controls": valid_ctrl,
        "lots": [build_valid_xreact_lot("LOT-A"), lot_b_m74_inv_ctrl_veh],
    })

    if (
        r74_valid_veh_hold["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or any(rs.startswith("[FAIL]") for rs in r74_valid_veh_hold["reasons"])
        or r74_valid_veh_hold["per_lot_verdicts"]["LOT-B"]["linked_endpoint_conflicts_quarantined"] != 6
        or r74_inv_c3d_veh_fail["verdict"] != "FAIL"
        or r74_inv_c3d_veh_fail.get("vehicle_invalid_fab_excluded_from_primary_quarantine") is not True
        or r74_inv_c3d_veh_fail["per_lot_verdicts"]["LOT-B"]["linked_endpoint_conflicts_quarantined"] != 0
        or r74_inv_c3d_veh_fail["per_lot_verdicts"]["LOT-B"]["endpoints"]["XREACT_COMPLEMENT_C3D"]["sc_islet_cd64t_null@15"]["verdict"] != "FAIL"
        or r74_inv_lysis_only_hold["verdict"] != "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        or any(rs.startswith("[FAIL]") for rs in r74_inv_lysis_only_hold["reasons"])
        or r74_inv_lysis_only_hold["per_lot_verdicts"]["LOT-B"]["linked_endpoint_conflicts_quarantined"] != 6
        or r74_inv_ctrl_veh_fail["verdict"] != "FAIL"
        or r74_inv_ctrl_veh_fail["per_lot_verdicts"]["LOT-B"]["linked_endpoint_conflicts_quarantined"] != 0
        or r74_inv_ctrl_veh_fail["per_lot_verdicts"]["LOT-B"]["endpoints"]["XREACT_COMPLEMENT_C3D"]["sc_islet_cd64t_null@15"]["verdict"] != "FAIL"
    ):
        raise RuntimeError(
            f"XREACT self-test 74 (R17 0042-B1 per-endpoint Fab vehicle qualification before intact-IgG discordance) failed: "
            f"valid_veh={r74_valid_veh_hold['verdict']}/{r74_valid_veh_hold['per_lot_verdicts']['LOT-B']['linked_endpoint_conflicts_quarantined']}, "
            f"inv_c3d={r74_inv_c3d_veh_fail['verdict']}/{r74_inv_c3d_veh_fail['per_lot_verdicts']['LOT-B']['linked_endpoint_conflicts_quarantined']}, "
            f"inv_lysis={r74_inv_lysis_only_hold['verdict']}/{r74_inv_lysis_only_hold['per_lot_verdicts']['LOT-B']['linked_endpoint_conflicts_quarantined']}, "
            f"inv_ctrl={r74_inv_ctrl_veh_fail['verdict']}/{r74_inv_ctrl_veh_fail['per_lot_verdicts']['LOT-B']['linked_endpoint_conflicts_quarantined']}"
        )

    cases = {
        "clean_2lot_pass": r1["verdict"],
        "pooled_trap_lotA100_lotB70_fail": r2["verdict"],
        "missing_second_lot_hold": r3["verdict"],
        "failed_cd3_positive_control_hold": r4["verdict"],
        "missing_required_stratum_hold": r5["verdict"],
        "unclassified_single_donor_outlier_hold": r6["verdict"],
        "biological_fail_dominates_missing_lot": r7["verdict"],
        "nan_observation_rejected": nan_rejected,
        "anonymous_101pct_counterexample_rejected": r9["verdict"],
        "impossible_cd3_101pct_rejected": r10["verdict"],
        "negative_percentage_rejected": r11["verdict"],
        "duplicate_donor_id_rejected": r12["verdict"],
        "missing_50ugml_dose_rejected": r13["verdict"],
        "separate_c5b9_fail_caught": r14["verdict"],
        "separate_iec_viability_fail_caught": r15["verdict"],
        "missing_separate_c5b9_rejected": r16["verdict"],
        "disconnected_donor_panel_rejected": r17["verdict"],
        "missing_matched_rabbit_igg_rejected": r18["verdict"],
        "adverse_0_to_50_auc_vs_igg_fail": r19["verdict"],
        "unbound_100pct_fab_summary_discrepancy_rejected": r20["verdict"],
        "direct_fab2_deconvolution_biological_fail": r21["verdict"],
        "matched_igg_gsis_zero_rejected_hold_invalid": r22["verdict"],
        "matched_igg_cd64t_disp_100pct_rejected_hold_invalid": r23["verdict"],
        "paired_gsis_ratio_vs_igg_collapse_fail": r24["verdict"],
        "missing_lot_positive_controls_rejected_hold_invalid": r25["verdict"],
        "wrong_lot_id_positive_controls_rejected_hold_invalid": r26["verdict"],
        "low_50pct_lot_cd3_pos_ctrl_rejected_hold_invalid": r27["verdict"],
        "low_50pct_lot_b6h12_pos_ctrl_rejected_hold_invalid": r28["verdict"],
        "unusable_1pct_igg_cd47_retention_rejected_hold_invalid": r29["verdict"],
        "unusable_1pct_igg_viability_rejected_hold_invalid": r30["verdict"],
        "elevated_20pct_igg_complement_rejected_hold_invalid": r31["verdict"],
        "lot_positive_control_run_id_mismatch_rejected_hold_invalid": r32["verdict"],
        "multi_run_positive_control_coverage_pass_and_omit_hold": (r33_pass["verdict"] == "PASS" and r33_miss["verdict"] == "HOLD_INVALID_OR_INCOMPLETE_ASSAY"),
        "uncovered_fab2_run_id_rejected_hold_invalid": r34["verdict"],
        "equal_20pct_atg_and_compromised_igg_c3d_holds_not_fail": r35["verdict"],
        "compromised_igg_lot_plus_separate_valid_fail_returns_fail": r36["verdict"],
        "omitted_hla_e_binding_retention_rejected_hold_invalid": r37["verdict"],
        "zero_pct_hla_e_vs_100pct_igg_returns_fail": r38["verdict"],
        "compromised_50pct_igg_hla_e_baseline_holds_not_fail": r39["verdict"],
        "contradictory_same_run_pos_ctrl_both_orders_hold_invalid": (
            r40_pf["verdict"] == "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
            and r40_fp["verdict"] == "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        ),
        "conflicted_pos_ctrl_lot_plus_separate_valid_fail_returns_fail": r41["verdict"],
        "multi_run_conflicted_vs_valid_fail_isolation": (
            r42_hold["verdict"] == "HOLD_INVALID_OR_INCOMPLETE_ASSAY" and r42_fail["verdict"] == "FAIL"
        ),
        "global_matched_igg_false_invalidates_inheriting_rows_hold": r43["verdict"],
        "global_matched_igg_false_with_traceable_independent_provenance_fail": r44["verdict"],
        "global_matched_igg_false_with_incomplete_independent_provenance_hold": r45["verdict"],
        "duplicate_conflicting_observation_both_orders_hold_invalid": (
            r46_bf["verdict"] == "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
            and r46_fb["verdict"] == "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        ),
        "padded_independent_igg_lot_id_rejected_hold_invalid": r47["verdict"],
        "conflicting_lot_vs_observation_independent_igg_id_rejected_hold_invalid": r48["verdict"],
        "conflicting_lot_vs_nested_independent_igg_id_rejected_hold_invalid": r49["verdict"],
        "untraceable_independent_igg_claim_rejected_hold_invalid": r50["verdict"],
        "conflicting_independent_igg_controls_both_orders_hold_invalid": (
            r51_pf["verdict"] == "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
            and r51_fp["verdict"] == "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        ),
        "row_level_traceable_independent_igg_provenance_bio_fail": r52["verdict"],
        "xreact_strict_json_duplicate_nan_inf_rejected": xreact_json_strict_ok,
        "r10_conflicted_primary_vs_linked_intact_quarantined_hold_invalid": r54["verdict"],
        "r10_consistent_20pct_primary_and_linked_intact_returns_fail": r55["verdict"],
        "r10_conflicted_lot_plus_separate_consistent_failing_lot_returns_fail": r56["verdict"],
        "r11_b2_cross_run_fab_withheld_and_same_run_fab_fails": (
            r57_hold["verdict"] == "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
            and r57_xrun_meta_still_hold["verdict"] == "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
            and r57_fail["verdict"] == "FAIL"
        ),
        "r11_b2_cross_run_fab_hold_preserves_valid_obs_run_fail": r58["verdict"],
        "r11_b3_invalid_0ugml_vehicle_quarantined_before_auc_holds_and_fixed_passes": (
            r59_hold["verdict"] == "HOLD_INVALID_OR_INCOMPLETE_ASSAY" and r59_pass["verdict"] == "PASS"
        ),
        "r11_b3_invalid_vehicle_preserves_separate_validated_fail_and_quarantines_fab_veh": (
            r60_sep_fail["verdict"] == "FAIL" and r60_fab_veh_hold["verdict"] == "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        ),
        "r12_0037_b1_vehicle_posctrl_failure_quarantines_point_and_auc_preserves_sep_fail": (
            r61_pass_clin["verdict"] == "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
            and r61_low_clin["verdict"] == "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
            and r61_sep_fail["verdict"] == "FAIL"
        ),
        "r12_0037_b1_vehicle_igg_invalid_and_fab_veh_ctrl_failure_quarantined": (
            r62_igg_veh["verdict"] == "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
            and r62_fab_veh["verdict"] == "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        ),
        "r12_0037_b4_global_igg_valid_uncovered_cross_run_fab_quarantined": (
            r63_pass_held["verdict"] == "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
            and r63_fab20_held["verdict"] == "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
        ),
        "r13_0037_b1_cross_run_fab_unconditionally_withheld_and_same_run_preserved": (
            r64_xrun_meta_pass_held["verdict"] == "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
            and r64_xrun_meta_fail_held["verdict"] == "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
            and r64_samerun_pass["verdict"] == "PASS"
            and r64_samerun_fail["verdict"] == "FAIL"
            and r64_obs_fail["verdict"] == "FAIL"
        ),
        "r13_0037_b1_cross_run_fab_zero_auc_adjudication_and_sep_samerun_fail": (
            r65_xrun_withheld["verdict"] == "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
            and len(lot_b_xrun_fab_auc_keys) == 0
            and r65_sep_samerun_fail["verdict"] == "FAIL"
        ),
        "r16_0037_b1_uncapped_paired_ratios_hla_e_cd47_viab_hold": (
            r66_hla["verdict"] == "HOLD"
            and r66_cd47["verdict"] == "HOLD"
            and r66_viab["verdict"] != "PASS"
        ),
        "r16_0037_m1_adjudicable_vs_withheld_cross_run_fab_maxima_separated": (
            r67_ctrl4["derived_direct_fab_maxima_pct"]["direct_fab_c3d_max_pct"] == 1.8
            and r67_ctrl4["withheld_cross_run_fab_maxima"]["direct_fab_c3d_max_pct"] == 4.0
            and r67_ctrl4["linked_fab2_deconvolution_reconciled"] is False
            and r67_ctrl18["linked_fab2_deconvolution_reconciled"] is False
        ),
        "r16_0037_b1_valid_same_run_agreement_failing_primary_returns_fail": r68_agree["verdict"],
        "r16_0037_b1_valid_same_run_discordance_quarantines_to_hold": (
            r69_discord["verdict"] == "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
            and r69_discord["per_lot_verdicts"]["LOT-B"]["linked_endpoint_conflicts_quarantined"] == 6
        ),
        "r16_0037_b1_missing_fab_linkage_preserves_qualified_primary_fail": (
            r70_miss_link["verdict"] == "FAIL"
            and r70_miss_link["per_lot_verdicts"]["LOT-B"]["linked_endpoint_conflicts_quarantined"] == 0
        ),
        "r16_0037_b1_wrong_donor_fab_linkage_preserves_qualified_primary_fail": (
            r71_wrong_donor["verdict"] == "FAIL"
            and r71_wrong_donor["per_lot_verdicts"]["LOT-B"]["linked_endpoint_conflicts_quarantined"] == 0
        ),
        "r16_0037_b1_cross_run_fab_linkage_preserves_qualified_primary_fail": (
            r72_cross_run["verdict"] == "FAIL"
            and r72_cross_run["per_lot_verdicts"]["LOT-B"]["linked_endpoint_conflicts_quarantined"] == 0
        ),
        "r16_0037_m1_invalid_vehicle_fab_excluded_from_derived_maxima": (
            r73_veh6_ctrl6["derived_direct_fab_maxima_pct"]["direct_fab_c3d_max_pct"] == 1.8
            and r73_veh6_ctrl6["invalid_vehicle_fab_maxima_pct"]["direct_fab_c3d_max_pct"] == 6.0
            and r73_veh6_ctrl6["linked_fab2_deconvolution_reconciled"] is False
            and r73_veh6_ctrl18["linked_fab2_deconvolution_reconciled"] is False
        ),
        "r17_0042_b1_invalid_fab_vehicle_preserves_primary_fail_while_valid_fab_vehicle_holds": (
            r74_valid_veh_hold["verdict"] == "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
            and r74_valid_veh_hold["per_lot_verdicts"]["LOT-B"]["linked_endpoint_conflicts_quarantined"] == 6
            and r74_inv_c3d_veh_fail["verdict"] == "FAIL"
            and r74_inv_c3d_veh_fail["per_lot_verdicts"]["LOT-B"]["linked_endpoint_conflicts_quarantined"] == 0
            and r74_inv_lysis_only_hold["verdict"] == "HOLD_INVALID_OR_INCOMPLETE_ASSAY"
            and r74_inv_ctrl_veh_fail["verdict"] == "FAIL"
            and r74_inv_ctrl_veh_fail["per_lot_verdicts"]["LOT-B"]["linked_endpoint_conflicts_quarantined"] == 0
        ),
    }
    return {
        "total_cases": len(cases),
        "all_passed": True,
        "cases": cases,
    }


# =============================================================================
# Mirrored Executable Typed Fail-First Gate 30-SHIELD-SPR Adjudicator (IIP-0042 B3-B4 / IIP-0044 B1-B4)
# Synchronized 100% IDENTICALLY with scripts/verify_iip0044_foundry_v1_3_biologics.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,
    }


_V37_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))?"
)
_V37_PDB_1JK8_PHRASE = r"(?:pdb\s+)?1jk8(?:\s+chain\s+c)?"
_V37_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"
)
_V37_RE_1JK8_CONFLATION = re.compile(
    r"(?i)(?:"
    r"\b1jk8\s+native\s+wt\b"
    r"|\b" + _V37_PDB_1JK8_PHRASE + r"\s+(?:is|was|equals|represents|contains|carries|encodes|(?:co-?)?crystallized|resolved|depicts|shows|models)\s+(?:the\s+)?(?:" + _V37_WT_INSB_PHRASE + r"|shlvealylvcgerg)\b"
    r"|\b(?:" + _V37_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+)?" + _V37_PDB_1JK8_PHRASE + r"(?:\s+(?:epitope|peptide|crystal|structure))?\b"
    r"|\b1jk8\s*(?:=|==)\s*" + _V37_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")"
)
_V37_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 _v37_find_unnegated_1jk8_conflation(text_val: str) -> str | None:
    for m in _V37_RE_1JK8_CONFLATION.finditer(text_val):
        prefix = text_val[max(0, m.start() - 35) : m.start()]
        if _V37_RE_1JK8_NEGATION.search(prefix) or _V37_RE_1JK8_NEGATION.search(m.group(0)):
            continue
        return m.group(0)
    return None


def verify_gate30_protocol_markdown_alignment(protocol_md_text: str, label: str = "GATE-30") -> dict[str, Any]:
    """Bounded deterministic parity check on GATE-30 section ### 2.2 synchronized with verify_iip0044
    (catching < 3 expression-batch contradictions and bidirectional PDB 1JK8 <-> WT InsB:9-23 conflations).
    """
    md_masked = mask_canonical_layer2_disclaimer_only(protocol_md_text)
    m = re.search(r"^###\s+(?:2\.2\s+)?`?Gate 30-SHIELD-SPR`?.*$", md_masked, flags=re.IGNORECASE | re.MULTILINE)
    if not m:
        raise RuntimeError(f"{label}: missing required section ### 2.2 Gate 30-SHIELD-SPR")
    rest = md_masked[m.start():]
    m_end = re.search(r"^(?:###\s+(?!2\.2\b)|##\s+|---\s*$)", rest[len(m.group(0)):], flags=re.MULTILINE)
    sec22 = rest[: len(m.group(0)) + m_end.start()] if m_end else rest
    sec22_nobt = sec22.lower().replace("`", "")
    m_batch = _V37_RE_MD_CONTRADICTORY_BATCH_RULE.search(sec22_nobt)
    if m_batch is not None:
        raise RuntimeError(
            f"{label} section ### 2.2 contains contradictory < 3 expression-batch rule: {m_batch.group(0)!r}"
        )
    conf_hit = _v37_find_unnegated_1jk8_conflation(md_masked)
    if conf_hit is not None:
        raise RuntimeError(
            f"{label} contains prohibited PDB 1JK8 <-> 15-aa WT InsB:9-23 conflation: {conf_hit!r}"
        )
    return {"section_2_2_present": True, "no_lt3_batch_contradiction": True, "no_1jk8_conflation": True}


EXPECTED_IIP0042_TRIAL_COHORT_NCT_MAPPING: dict[str, frozenset[str]] = {
    "NCT02215200": frozenset({"PMID:30012675", "PMID:30967424"}),
    "NCT01030861": frozenset({"PMID:31180194", "PMID:33658358", "PMID:39137044", "PMID:41026533"}),
    "NCT01106157": frozenset({"PMID:33632742"}),
    "NCT04509791": frozenset({"PMID:40976248"}),
}
_RE_NCT_SWAPPED_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (
    (
        "NCT02215200_misattributed_to_TN10_or_teplizumab",
        re.compile(r"(?i)NCT02215200(?:(?!NCT\d+)[^.\n;]){0,65}\b(?:TN-?10|teplizumab)\b"),
    ),
    (
        "NCT01030861_misattributed_to_ATG_or_GCSF",
        re.compile(r"(?i)NCT01030861(?:(?!NCT\d+)[^.\n;]){0,65}\b(?:ATG|G-?CSF)\b"),
    ),
    (
        "NCT01106157_misattributed_to_TN10_or_teplizumab",
        re.compile(r"(?i)NCT01106157(?:(?!NCT\d+)[^.\n;]){0,65}\b(?:TN-?10|teplizumab)\b"),
    ),
)


def _check_nct_prose_no_swaps(text_val: str, label: str) -> None:
    for err_tag, pat in _RE_NCT_SWAPPED_PATTERNS:
        m = pat.search(text_val)
        if m is not None:
            raise RuntimeError(
                f"{label}: published trial-cohort NCT attribution error ({err_tag}): matched {m.group(0)!r}"
            )


def verify_iip0042_published_trial_cohort_nct_mapping(
    side_contract_obj: dict[str, Any],
    protocol_md_text: str | None = None,
    *,
    openislet_root: Path | None = None,
    decision_tree_entry: dict[str, Any] | None = None,
) -> dict[str, Any]:
    """Verify exact publication-to-NCT cohort attribution across the IIP-0042 side contract,
    companion protocol Markdown, optional DEC-121 entry, and Ring-1 extracted metadata files.
    Enforces:
      - NCT02215200 -> TrialNet low-dose ATG / ATG+GCSF new-onset T1D (PMID:30012675, PMID:30967424)
      - NCT01030861 -> TrialNet TN-10 teplizumab prevention trial (PMID:31180194, PMID:33658358, PMID:39137044, PMID:41026533)
      - NCT01106157 -> 5-year established-T1D ATG/GCSF follow-up (PMID:33632742 / PMC8173803)
      - NCT04509791 -> MELD-ATG phase 2 adaptive dose-ranging trial (PMID:40976248)
    """
    ring1_sum = side_contract_obj.get("locked_owner_policy", {}).get("ring1_evidence_increment_summary")
    if not isinstance(ring1_sum, dict):
        raise RuntimeError("IIP-0042 side contract missing locked_owner_policy.ring1_evidence_increment_summary")
    nct_map = ring1_sum.get("published_trial_cohort_nct_mapping")
    if not isinstance(nct_map, dict):
        raise RuntimeError(
            "IIP-0042 side contract missing typed locked_owner_policy.ring1_evidence_increment_summary.published_trial_cohort_nct_mapping"
        )
    if set(nct_map.keys()) != set(EXPECTED_IIP0042_TRIAL_COHORT_NCT_MAPPING.keys()):
        raise RuntimeError(
            f"published_trial_cohort_nct_mapping NCT key mismatch: got {sorted(nct_map.keys())}, "
            f"expected {sorted(EXPECTED_IIP0042_TRIAL_COHORT_NCT_MAPPING.keys())}"
        )
    for nct_id, exp_pmids in EXPECTED_IIP0042_TRIAL_COHORT_NCT_MAPPING.items():
        entry = nct_map.get(nct_id)
        if not isinstance(entry, dict) or not isinstance(entry.get("pmids"), list):
            raise RuntimeError(f"published_trial_cohort_nct_mapping[{nct_id}] must be a dict with pmids list")
        got_pmids = [str(p) for p in entry["pmids"]]
        if len(got_pmids) != len(set(got_pmids)) or frozenset(got_pmids) != exp_pmids:
            raise RuntimeError(
                f"published_trial_cohort_nct_mapping[{nct_id}] PMID mismatch: got {got_pmids}, expected {sorted(exp_pmids)}"
            )
        tname = str(entry.get("trial_name") or "")
        if not tname.strip():
            raise RuntimeError(f"published_trial_cohort_nct_mapping[{nct_id}] missing non-empty trial_name")
        _check_nct_prose_no_swaps(f"{nct_id} {tname}", f"published_trial_cohort_nct_mapping[{nct_id}]")

    # Scan EVERY string in side_contract_obj (including embedded DEC-121 block) for swapped cohort prose!
    sc_blob = json.dumps(side_contract_obj, ensure_ascii=False)
    _check_nct_prose_no_swaps(sc_blob, "iip0042_side_contract")
    for req_nct in ("NCT02215200", "NCT01030861", "NCT01106157", "NCT04509791"):
        if req_nct not in sc_blob:
            raise RuntimeError(f"iip0042_side_contract missing required trial cohort identifier {req_nct}")

    if protocol_md_text is not None:
        _check_nct_prose_no_swaps(protocol_md_text, "GATE-30-PORTFOLIO-AND-TRACKB-CONTINGENCY-PROTOCOL.md")
        for req_nct in ("NCT02215200", "NCT01030861", "NCT01106157", "NCT04509791"):
            if req_nct not in protocol_md_text:
                raise RuntimeError(
                    f"GATE-30-PORTFOLIO-AND-TRACKB-CONTINGENCY-PROTOCOL.md missing required trial cohort {req_nct}"
                )

    if decision_tree_entry is not None:
        dt_blob = json.dumps(decision_tree_entry, ensure_ascii=False)
        _check_nct_prose_no_swaps(dt_blob, "stage0_decision_tree_v1.json::DEC-121")

    extracted_ncts_verified: dict[str, str | None] = {}
    if openislet_root is not None:
        for nct_id, exp_pmids in EXPECTED_IIP0042_TRIAL_COHORT_NCT_MAPPING.items():
            for pmid_str in sorted(exp_pmids):
                pmid_num = pmid_str.replace("PMID:", "")
                ext_p = openislet_root / "data" / "extracted" / f"{pmid_num}.json"
                if not ext_p.is_file():
                    raise FileNotFoundError(f"Missing Ring-1 extracted metadata file: data/extracted/{pmid_num}.json")
                ext_obj = load_strict_json_text(ext_p.read_text(encoding="utf-8"), ext_p.name)
                meta_nct = ext_obj.get("study_metadata", {}).get("nct_id")
                if meta_nct != nct_id:
                    raise RuntimeError(
                        f"data/extracted/{pmid_num}.json study_metadata.nct_id={meta_nct!r} != expected {nct_id!r}"
                    )
                extracted_ncts_verified[pmid_str] = meta_nct

    return {
        "nct_cohort_mapping_verified": True,
        "cohorts_verified": {k: sorted(v) for k, v in EXPECTED_IIP0042_TRIAL_COHORT_NCT_MAPPING.items()},
        "extracted_metadata_ncts_verified": extracted_ncts_verified,
        "zero_swapped_cohort_attributions": True,
    }


def run_iip0042_nct_mapping_self_tests() -> dict[str, Any]:
    """Verify negative probes catching swapped trial-cohort NCT attributions (R09 B4)."""
    valid_sc = {
        "locked_owner_policy": {
            "ring1_evidence_increment_summary": {
                "published_trial_cohort_nct_mapping": {
                    "NCT02215200": {"trial_name": "TrialNet low-dose ATG / ATG+GCSF new-onset T1D", "pmids": ["PMID:30012675", "PMID:30967424"]},
                    "NCT01030861": {"trial_name": "TrialNet TN-10 teplizumab prevention trial", "pmids": ["PMID:31180194", "PMID:33658358", "PMID:39137044", "PMID:41026533"]},
                    "NCT01106157": {"trial_name": "5-year established-T1D ATG/GCSF follow-up", "pmids": ["PMID:33632742"]},
                    "NCT04509791": {"trial_name": "MELD-ATG phase 2 trial", "pmids": ["PMID:40976248"]},
                }
            }
        }
    }
    valid_md = "NCT02215200 (ATG), NCT01030861 (TN-10), NCT01106157 (Lin 2021 ATG/GCSF), NCT04509791 (MELD-ATG)."
    res_ok = verify_iip0042_published_trial_cohort_nct_mapping(valid_sc, valid_md)
    if not res_ok["nct_cohort_mapping_verified"]:
        raise RuntimeError("Valid NCT mapping fixture unexpectedly failed")

    # Probe 1: Sol's exact Round-08 swapped prose inside side contract -> RuntimeError
    swapped_sc = json.loads(json.dumps(valid_sc))
    swapped_sc["summary_note"] = "repeated trial cohorts NCT02215200 x2 [TN-10 follow-up] and NCT01030861 x4 [ATG/GCSF 5-year follow-up]"
    swap_prose_rejected = False
    try:
        verify_iip0042_published_trial_cohort_nct_mapping(swapped_sc, valid_md)
    except RuntimeError:
        swap_prose_rejected = True
    if not swap_prose_rejected:
        raise RuntimeError("NCT self-test 1 (swapped prose) failed to reject")

    # Probe 2: Swapped PMIDs between NCT02215200 and NCT01030861 -> RuntimeError
    swapped_pmids = json.loads(json.dumps(valid_sc))
    swapped_pmids["locked_owner_policy"]["ring1_evidence_increment_summary"]["published_trial_cohort_nct_mapping"]["NCT02215200"]["pmids"] = ["PMID:31180194"]
    swap_pmid_rejected = False
    try:
        verify_iip0042_published_trial_cohort_nct_mapping(swapped_pmids, valid_md)
    except RuntimeError:
        swap_pmid_rejected = True
    if not swap_pmid_rejected:
        raise RuntimeError("NCT self-test 2 (swapped PMIDs) failed to reject")

    # Probe 3: Missing NCT01106157 link to Lin 2021 PMID:33632742 -> RuntimeError
    miss_nct110 = json.loads(json.dumps(valid_sc))
    miss_nct110["locked_owner_policy"]["ring1_evidence_increment_summary"]["published_trial_cohort_nct_mapping"].pop("NCT01106157")
    miss_110_rejected = False
    try:
        verify_iip0042_published_trial_cohort_nct_mapping(miss_nct110, valid_md)
    except RuntimeError:
        miss_110_rejected = True
    if not miss_110_rejected:
        raise RuntimeError("NCT self-test 3 (missing NCT01106157) failed to reject")

    return {
        "total_cases": 4,
        "all_passed": True,
        "valid_mapping_accepted": True,
        "swapped_prose_rejected": swap_prose_rejected,
        "swapped_pmids_rejected": swap_pmid_rejected,
        "missing_nct01106157_rejected": miss_110_rejected,
    }


def evaluate_trackb_policy_option1_ev(
    *,
    p_shield_fail: float,
    p_shield1_only: float,
    p_cocktail_pass: float,
    p_hold_or_pending: float,
    p_xreact_pass_given_fail: float,
    p_xreact_pass_given_s1: float | None = None,
    p_owner_reauth: float,
    p_owner_reauth_given_fail: float | None = None,
    p_owner_reauth_given_s1: float | None = None,
    d_fail_pp: float,
    d_s1_pp: float,
) -> dict[str, Any]:
    """Full joint Track-B Policy Option 1 EV calculator representing HOLD/pending mass,
    branch-specific XREACT pass probabilities, and conditional owner re-authorization probability.
    By default, `p_owner_reauth` applies conditional on qualifying outcomes (XREACT pass AND
    SHIELD fail or SHIELD-1-only interim) and is shared across both Track-B branches; callers
    requiring branch-specific authorization probabilities may supply `p_owner_reauth_given_fail`
    and/or `p_owner_reauth_given_s1` (each defaulting to `p_owner_reauth`).
    Full-cocktail branch and HOLD/pending states carry strictly 0.0000 pp Track-B credit.
    """
    px_s1 = p_xreact_pass_given_fail if p_xreact_pass_given_s1 is None else p_xreact_pass_given_s1
    pr_fail = p_owner_reauth if p_owner_reauth_given_fail is None else p_owner_reauth_given_fail
    pr_s1 = p_owner_reauth if p_owner_reauth_given_s1 is None else p_owner_reauth_given_s1
    probs = (
        ("p_shield_fail", p_shield_fail),
        ("p_shield1_only", p_shield1_only),
        ("p_cocktail_pass", p_cocktail_pass),
        ("p_hold_or_pending", p_hold_or_pending),
        ("p_xreact_pass_given_fail", p_xreact_pass_given_fail),
        ("p_xreact_pass_given_s1", px_s1),
        ("p_owner_reauth", p_owner_reauth),
        ("p_owner_reauth_given_fail", pr_fail),
        ("p_owner_reauth_given_s1", pr_s1),
    )
    for nm, pv in probs:
        f = require_finite_number(pv, nm)
        if not (0.0 <= f <= 1.0):
            raise ValueError(f"Probability {nm}={f} out of [0, 1]")
    df = require_finite_number(d_fail_pp, "d_fail_pp")
    ds1 = require_finite_number(d_s1_pp, "d_s1_pp")
    simplex_sum = p_shield_fail + p_shield1_only + p_cocktail_pass + p_hold_or_pending
    if abs(simplex_sum - 1.0) > 1e-12:
        raise ValueError(
            f"SHIELD outcome simplex must sum to 1.0 (got {simplex_sum:.12f}): "
            f"fail={p_shield_fail}, s1_only={p_shield1_only}, cocktail={p_cocktail_pass}, hold={p_hold_or_pending}"
        )
    # Zero credit on p_cocktail_pass AND zero credit on p_hold_or_pending!
    ev_pp = (
        p_shield_fail * p_xreact_pass_given_fail * pr_fail * df
        + p_shield1_only * px_s1 * pr_s1 * ds1
    )
    return {
        "p_shield_fail": round(p_shield_fail, 6),
        "p_shield1_only": round(p_shield1_only, 6),
        "p_cocktail_pass_zero_credit": round(p_cocktail_pass, 6),
        "p_hold_or_pending_zero_credit": round(p_hold_or_pending, 6),
        "p_xreact_pass_given_fail": round(p_xreact_pass_given_fail, 6),
        "p_xreact_pass_given_s1": round(px_s1, 6),
        "p_owner_reauth": round(p_owner_reauth, 6),
        "p_owner_reauth_given_fail": round(pr_fail, 6),
        "p_owner_reauth_given_s1": round(pr_s1, 6),
        "owner_reauth_assumption_note": (
            "Conditional on qualifying outcomes (XREACT pass AND SHIELD fail or SHIELD-1-only interim); "
            "shared across both branches unless branch-specific overrides p_owner_reauth_given_fail / "
            "p_owner_reauth_given_s1 are supplied."
        ),
        "active_ev_pp": round(ev_pp, 4),
        "active_ev_exact_pp": ev_pp,
    }


def resolve_openislet_root(cli_root: str | None = None) -> Path:
    if cli_root:
        p = Path(cli_root).expanduser().resolve()
        if (p / "scripts" / "rank_islet1_stacks.py").is_file():
            return p
        raise FileNotFoundError(f"Invalid --repo-root: {p}")
    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
    sibling = INV_ROOT.parent / "OpenIslet"
    if (sibling / "scripts" / "rank_islet1_stacks.py").is_file():
        return sibling
    # Also support direct installation under OpenIslet/scripts/
    if (ART_DIR.parent / "scripts" / "rank_islet1_stacks.py").is_file():
        return ART_DIR.parent
    raise FileNotFoundError(
        "Could not locate OpenIslet repository. Pass --repo-root or set OPENISLET_ROOT."
    )


def subadditive_overlap(base: float, delta_a: float, delta_b: float, omega: float) -> float:
    """
    Monotone, bounded, anti-double-counting combination law for two mechanistically
    overlapping interventions on Hurdle 3 Channel (a):

        delta_joint = max(da, db) + (1 - omega) * min(da, db) * (1 - max(da, db) / (1 - base))

    Validates all probability and envelope inputs strictly (finite, in-domain,
    base + delta_a < 1, base + delta_b < 1, omega in [0, 1]).
    """
    for nm, val in (("base", base), ("delta_a", delta_a), ("delta_b", delta_b), ("omega", omega)):
        if not isinstance(val, (int, float)) or not math.isfinite(val):
            raise ValueError(f"Non-finite input {nm}={val!r}")
    if not (0.0 <= base < 1.0):
        raise ValueError(f"Invalid base={base} (must satisfy 0 <= base < 1)")
    if delta_a < 0.0 or delta_b < 0.0:
        raise ValueError(f"Negative deltas not allowed: delta_a={delta_a}, delta_b={delta_b}")
    if base + delta_a >= 1.0 or base + delta_b >= 1.0:
        raise ValueError(
            f"Single-intervention envelope breach: base={base}, delta_a={delta_a}, delta_b={delta_b}"
        )
    if not (0.0 <= omega <= 1.0):
        raise ValueError(f"Invalid overlap omega={omega} (must satisfy 0 <= omega <= 1)")
    hi = max(delta_a, delta_b)
    lo = min(delta_a, delta_b)
    if lo == 0.0:
        return base + hi
    rem_frac = max(0.0, 1.0 - hi / (1.0 - base))
    val = base + hi + (1.0 - omega) * lo * rem_frac
    if not (base <= val < 1.0):
        raise ValueError(f"Out-of-envelope combined value={val}")
    return val


def _solve_lp_min_bpr05(
    c: np.ndarray,
    A: list[np.ndarray] | np.ndarray,
    b: list[float] | np.ndarray,
    *,
    tol: float = 1e-11,
    max_iter: int = 30000,
) -> tuple[float, np.ndarray]:
    """Pure-NumPy two-phase simplex solver (minimize c^T x s.t. A x = b, x >= 0) with zero SciPy dependency."""
    A_mat = np.array(A, dtype=np.float64)
    b_vec = np.array(b, dtype=np.float64)
    c_vec = np.array(c, dtype=np.float64)
    m_raw, n = A_mat.shape
    for i in range(m_raw):
        if b_vec[i] < 0.0:
            A_mat[i] = -A_mat[i]
            b_vec[i] = -b_vec[i]
    # Remove linearly dependent equality rows via Modified Gram-Schmidt
    indep: list[int] = []
    q_list: list[np.ndarray] = []
    for i in range(m_raw):
        v = A_mat[i].copy()
        for q in q_list:
            v = v - float(np.dot(v, q)) * q
        nv = float(np.linalg.norm(v))
        if nv > 1e-10:
            q_list.append(v / nv)
            indep.append(i)
    A_mat = A_mat[indep]
    b_vec = b_vec[indep]
    m, n = A_mat.shape
    for i in range(m):
        if b_vec[i] < 0.0:
            A_mat[i] = -A_mat[i]
            b_vec[i] = -b_vec[i]

    def _pivot(T: np.ndarray, basis: list[int], r: int, col: int) -> None:
        T[r, :] /= T[r, col]
        factors = T[:, col].copy()
        factors[r] = 0.0
        T -= np.outer(factors, T[r, :])
        T[r, col] = 1.0
        basis[r] = col

    def _run_simplex(T: np.ndarray, basis: list[int], nv: int) -> None:
        mm = T.shape[0] - 1
        for it in range(max_iter):
            rc = T[mm, :nv]
            if float(np.min(rc)) >= -tol:
                return
            if it > 2500 and (it % 5 != 0):
                col = int(np.where(rc < -tol)[0][0])
            else:
                col = int(np.argmin(rc))
            cv = T[:mm, col]
            pos = np.where(cv > tol)[0]
            if len(pos) == 0:
                raise RuntimeError("BPR-05 LP unbounded")
            ratios = T[pos, -1] / cv[pos]
            min_r = float(np.min(ratios))
            cands = pos[ratios <= min_r + 1e-12]
            r = int(cands[int(np.argmin([basis[int(i)] for i in cands]))])
            _pivot(T, basis, r, col)
        raise RuntimeError("BPR-05 LP simplex did not converge")

    # Phase 1: minimize sum of artificial variables
    T = np.zeros((m + 1, n + m + 1), dtype=np.float64)
    T[:m, :n] = A_mat
    T[:m, n : n + m] = np.eye(m, dtype=np.float64)
    T[:m, -1] = b_vec
    T[m, n : n + m] = 1.0
    T[m, :] -= np.sum(T[:m, :], axis=0)
    basis = list(range(n, n + m))
    _run_simplex(T, basis, n + m)
    if abs(float(T[m, -1])) > 1e-6:
        raise RuntimeError(f"BPR-05 LP Phase 1 infeasible: residual={abs(float(T[m, -1])):.3e}")

    # Drive out zero-valued artificial variables from basis
    for r in range(m):
        if basis[r] >= n:
            nz = np.where(np.abs(T[r, :n]) > 1e-9)[0]
            if len(nz) > 0:
                _pivot(T, basis, r, int(nz[0]))
    keep = [r for r in range(m) if basis[r] < n]
    m2 = len(keep)
    T2 = np.zeros((m2 + 1, n + 1), dtype=np.float64)
    basis2 = [basis[r] for r in keep]
    T2[:m2, :n] = T[keep, :n]
    T2[:m2, -1] = T[keep, -1]
    T2[m2, :n] = c_vec
    for r in range(m2):
        cb = float(c_vec[basis2[r]])
        if cb != 0.0:
            T2[m2, :] -= cb * T2[r, :]
    _run_simplex(T2, basis2, n)
    x = np.zeros(n, dtype=np.float64)
    for r in range(m2):
        x[basis2[r]] = max(0.0, float(T2[r, -1]))
    return float(np.dot(c_vec, x)), x


def compute_bpr05_dependence_sensitivity_bounds(
    *,
    scenario_id: str,
    arms: list[tuple[float, float, float, float]],
    dists: list[list[float]],
    v_h123: list[float],
    routes: tuple[str, ...],
    compat_map: dict[str, frozenset[str]],
    cell_classes: tuple[str, ...],
    preserve_incumbent_3arm_joint_history: bool = False,
    stage_ceilings: tuple[float, float, float, float] | None = None,
) -> dict[str, Any]:
    """
    BPR-05 cross-stage dependence sensitivity via exact LP over permissible couplings of
    earlier survivors (M_cell = H1&H2&H3) and final-route outcomes (M_h4 = H4) conditioned on
    the stage-level shared ceilings passing:
      - Holds published stage distributions (v_h123, d4), shared ceilings
        (explicit `stage_ceilings` when supplied, e.g. (0.88, 0.87, 0.89, 0.85) for Core 3-arm,
        or stage-positive survival ceilings (1-d1[0])(1-d2[0])(1-d3[0]) and (1-d4[0])), and EVERY
        individual arm's full-path success probability fixed at both extremes.
      - For 5-arm scenarios (`preserve_incumbent_3arm_joint_history=True`), ALSO holds fixed the
        entire 4-stage joint history of the 3 incumbent designs (A, B, X) alongside M_cell.
      - Evaluates both locked and modular feasible ranges AND the paired same-branch
        (modular - locked) policy advantage under the SAME joint distribution.
      - Note: feasible dependence sensitivity ranges carry NO sampling confidence level, do NOT
        measure cure probability, and must NOT replace the independently reproduced point
        estimates with pessimistic endpoints.
    """
    n_arms = len(arms)
    n_states = 1 << n_arms
    d1, d2, d3, dh4 = dists
    if stage_ceilings is not None:
        c1_c, c2_c, c3_c, c4_c = stage_ceilings
        f_s = float(c1_c) * float(c2_c) * float(c3_c)
        f_h = float(c4_c)
    else:
        f_s = (1.0 - d1[0]) * (1.0 - d2[0]) * (1.0 - d3[0])
        f_h = 1.0 - dh4[0]
    scale = f_s * f_h

    ps = [v_h123[s] / f_s for s in range(n_states)]
    ps[0] = max(0.0, 1.0 - sum(ps[1:]))
    ph = [dh4[h] / f_h for h in range(n_states)]
    ph[0] = max(0.0, 1.0 - sum(ph[1:]))

    nz_s = [s for s in range(n_states) if ps[s] > 1e-15]
    nz_h = [h for h in range(n_states) if ph[h] > 1e-15]
    ns, nh = len(nz_s), len(nz_h)
    nv = ns * nh

    def _is_mod_ok(m_cell: int, m_h4: int) -> bool:
        if m_cell == 0 or m_h4 == 0:
            return False
        allowed_r: set[str] = set()
        for i in range(n_arms):
            if m_cell & (1 << i):
                allowed_r |= compat_map[cell_classes[i]]
        return any(routes[j] in allowed_r for j in range(n_arms) if (m_h4 & (1 << j)))

    rows: list[np.ndarray] = []
    rhs: list[float] = []

    # 1. Row marginals: conditional M_cell distribution
    for si, s in enumerate(nz_s):
        r = np.zeros(nv, dtype=np.float64)
        r[si * nh : (si + 1) * nh] = 1.0
        rows.append(r)
        rhs.append(ps[s])

    # 2. Column marginals: conditional M_h4 distribution
    for hi, h in enumerate(nz_h):
        r = np.zeros(nv, dtype=np.float64)
        r[hi::nh] = 1.0
        rows.append(r)
        rhs.append(ph[h])

    # 3. Optional 5-arm constraint: preserve entire 4-stage joint history of the 3 incumbent designs
    if preserve_incumbent_3arm_joint_history:
        ph_inc = [sum(ph[h] for h in nz_h if (h & 7) == h3) for h3 in range(8)]
        for si, s in enumerate(nz_s):
            for h3 in range(8):
                if ph_inc[h3] <= 1e-15:
                    continue
                r = np.zeros(nv, dtype=np.float64)
                for hi, h in enumerate(nz_h):
                    if (h & 7) == h3:
                        r[si * nh + hi] = 1.0
                rows.append(r)
                rhs.append(ps[s] * ph_inc[h3])

    # 4. Fixed individual arm full-path success probabilities
    arm_full_targets = [math.prod(vec) for vec in arms]
    arm_cond_rows: list[np.ndarray] = []
    for arm_i in range(n_arms):
        bit = 1 << arm_i
        r = np.zeros(nv, dtype=np.float64)
        for si, s in enumerate(nz_s):
            if not (s & bit):
                continue
            for hi, h in enumerate(nz_h):
                if h & bit:
                    r[si * nh + hi] = 1.0
        rows.append(r)
        rhs.append(arm_full_targets[arm_i] / scale)
        arm_cond_rows.append(r)

    c_lck = np.array([1.0 if (s & h) != 0 else 0.0 for s in nz_s for h in nz_h], dtype=np.float64)
    c_mod = np.array([1.0 if _is_mod_ok(s, h) else 0.0 for s in nz_s for h in nz_h], dtype=np.float64)
    c_gain = c_mod - c_lck

    # Published independent cross-stage baseline on this exact support
    x_indep = np.array([ps[s] * ph[h] for s in nz_s for h in nz_h], dtype=np.float64)
    pub_lck = scale * float(np.dot(c_lck, x_indep))
    pub_mod = scale * float(np.dot(c_mod, x_indep))

    lck_min_raw, x_lck_min = _solve_lp_min_bpr05(c_lck, rows, rhs)
    lck_max_neg, x_lck_max = _solve_lp_min_bpr05(-c_lck, rows, rhs)
    mod_min_raw, x_mod_min = _solve_lp_min_bpr05(c_mod, rows, rhs)
    mod_max_neg, x_mod_max = _solve_lp_min_bpr05(-c_mod, rows, rhs)
    gain_min_raw, x_gain_min = _solve_lp_min_bpr05(c_gain, rows, rhs)
    gain_max_neg, x_gain_max = _solve_lp_min_bpr05(-c_gain, rows, rhs)

    # Verify every individual arm marginal stays fixed across all 6 extreme-point witnesses
    max_arm_err = 0.0
    for x_sol in (x_lck_min, x_lck_max, x_mod_min, x_mod_max, x_gain_min, x_gain_max):
        for arm_i in range(n_arms):
            rec_p = scale * float(np.dot(arm_cond_rows[arm_i], x_sol))
            err = abs(rec_p - arm_full_targets[arm_i])
            if err > max_arm_err:
                max_arm_err = err
    if max_arm_err > 1e-8:
        raise RuntimeError(f"BPR-05 arm marginal invariance violated on {scenario_id}: {max_arm_err:.3e}")

    lck_min = scale * lck_min_raw
    lck_max = scale * (-lck_max_neg)
    mod_min = scale * mod_min_raw
    mod_max = scale * (-mod_max_neg)
    gain_min = scale * gain_min_raw
    gain_max = scale * (-gain_max_neg)

    return {
        "scenario_id": scenario_id,
        "n_arms": n_arms,
        "constraints_preserved": {
            "stage_distributions_v_h123_and_dh4_fixed": True,
            "stage_shared_ceilings_fixed": True,
            "individual_arm_full_path_successes_fixed_pct": [round(100.0 * p, 4) for p in arm_full_targets],
            "incumbent_3arm_4stage_joint_history_preserved": preserve_incumbent_3arm_joint_history,
            "max_abs_arm_marginal_err_across_all_extremes": max_arm_err,
        },
        "published_independent_cross_stage": {
            "locked_pct": round(100.0 * pub_lck, 4),
            "modular_k100_pct": round(100.0 * pub_mod, 4),
            "paired_modular_gain_pp": round(100.0 * (pub_mod - pub_lck), 4),
        },
        "feasible_locked_range_pct": [round(100.0 * lck_min, 4), round(100.0 * lck_max, 4)],
        "feasible_modular_range_pct": [round(100.0 * mod_min, 4), round(100.0 * mod_max, 4)],
        "paired_same_branch_modular_gain_range_pp": [round(100.0 * gain_min, 4), round(100.0 * gain_max, 4)],
        "paired_modular_strictly_positive_across_feasible_set": gain_min > 0.0,
        "locked_crosses_50pct_under_permissible_cross_stage_coupling": (lck_min < 0.50 < lck_max),
        "interpretation_notice": (
            "Feasible cross-stage dependence sensitivity bounds (NOT sampling confidence intervals and NOT cure "
            "probabilities). Published cross-stage-independent points are retained; do NOT replace them with "
            "pessimistic endpoints as new point estimates. Policy comparisons between modular and locked use "
            "paired outcomes under the same joint distribution."
        ),
    }


def run_all(
    openislet_root: Path,
    *,
    standalone: bool = False,
    cross_track_dir: Path | None = None,
    expected_shipped_sha256: str | None = None,
    expected_exp028_sha256: str | None = None,
    expected_exp029_sha256: str | None = None,
    allow_unpinned_diagnostic: bool = False,
) -> dict[str, Any]:
    if standalone and cross_track_dir is not None:
        raise ValueError("Mutually exclusive modes: cannot pass both standalone=True and cross_track_dir")
    if standalone and (expected_exp028_sha256 is not None or expected_exp029_sha256 is not None):
        raise ValueError("Cannot pass expected EXP-028/029 SHA-256 pins when standalone=True")
    if allow_unpinned_diagnostic and expected_shipped_sha256 is not None:
        raise ValueError("Mutually exclusive options: cannot pass both allow_unpinned_diagnostic=True and expected_shipped_sha256")
    if str(openislet_root / "scripts") not in sys.path:
        sys.path.insert(0, str(openislet_root / "scripts"))

    import rank_islet1_stacks as ris  # noqa: E402

    _bivariate = ris._bivariate_bernoulli_iip0034
    _frechet_joint = ris._frechet_bernoulli_joint_iip0034
    _frechet_couple = ris._frechet_couple_new_arm_iip0034
    _live_2pow12 = ris.compute_common_shock_2pow12_portfolio_tree
    _live_canon_inc = ris._live_canonical_incumbent_dists_iip0034

    # Strict live-registered route compatibility map (IIP-0035 live registry: NO unregistered R3B!)
    compat_strict_live = {
        "UNHARDENED_A_B_X": frozenset({"R1", "R2"}),
        "DESIGN_Y_FULLSTACK_V2": frozenset({"R3P"}),
        "D1B_AUTO_C_V2": frozenset({"R3P"}),
    }
    # Parked counterfactual post-registration maps (ONLY if GY-027 BLOCK lifted + Mode-B R3B registered)
    compat_d1_r3b_counterfactual = {
        "UNHARDENED_A_B_X": frozenset({"R1", "R2"}),
        "DESIGN_Y_FULLSTACK_V2": frozenset({"R3P"}),
        "D1B_AUTO_C_V2": frozenset({"R3B"}),
    }
    compat_d1_r3b_hypo_transfer = {
        "UNHARDENED_A_B_X": frozenset({"R1", "R2"}),
        "DESIGN_Y_FULLSTACK_V2": frozenset({"R3P", "R3B"}),
        "D1B_AUTO_C_V2": frozenset({"R3P", "R3B"}),
    }
    std_classes = (
        "UNHARDENED_A_B_X",
        "UNHARDENED_A_B_X",
        "UNHARDENED_A_B_X",
        "DESIGN_Y_FULLSTACK_V2",
        "D1B_AUTO_C_V2",
    )

    def eval_3arm_baseline() -> dict[str, Any]:
        pa = (0.88, 0.78, 0.57, 0.69)
        pb = (0.88, 0.79, 0.64, 0.70)
        px = (0.88, 0.82, 0.73, 0.69)
        c_base = (0.88, 0.87, 0.89, 0.85)
        live = _live_2pow12(pa, pb, px, c_base)
        p0_l = float(live["locked_2route_shared_ax_pouch_exact"])
        p0_m = float(live["modular_2route_shared_ax_pouch_exact"])
        p0_m90 = 0.90 * p0_m + 0.10 * p0_l
        c0 = math.prod(c_base)

        dists = _live_canon_inc()
        v = [0.0] * 8
        v[7] = 1.0
        v_h123: list[float] = []
        for h in range(4):
            dh = dists[h]
            if abs(sum(dh) - 1.0) > 1e-12:
                raise RuntimeError("Hurdle normalization error")
            vn = [0.0] * 8
            for s, vs in enumerate(v):
                if vs:
                    for m, w in enumerate(dh):
                        if w:
                            vn[s & m] += vs * w
            v = vn
            if h == 2:
                v_h123 = list(v)
        dp_locked = 1.0 - v[0]
        dp_mod100 = (1.0 - v_h123[0]) * (1.0 - dists[3][0])
        if abs(dp_locked - p0_l) > 5e-9 or abs(dp_mod100 - p0_m) > 5e-9:
            raise RuntimeError("3-arm baseline DP parity failed")

        arms_dict = {
            nm: {"route": rt, "hurdles": [round(x, 6) for x in vec], "standalone_pct": round(100.0 * math.prod(vec), 4)}
            for nm, vec, rt in (("A", pa, "R1"), ("B", pb, "R2"), ("X", px, "R1"))
        }
        return {
            "layer_id": "L0_CORE_3ARM",
            "label": "Layer 0: Core 3 Blueprints (A, B, X; 2-Route R1/R2)",
            "epistemic_tier": "Tier-0_Live_OQ016_Baseline",
            "drug_status": "ZERO_DRUG_100PCT_LIVE",
            "n_arms": 3,
            "state_space": 2 ** 12,
            "single_arms": arms_dict,
            "eff_ceilings_pct": [round(100.0 * c, 2) for c in c_base],
            "composite_ceiling_pct": round(100.0 * c0, 4),
            "locked_pct": round(100.0 * p0_l, 4),
            "modular_k90_pct": round(100.0 * p0_m90, 4),
            "modular_k100_pct": round(100.0 * p0_m, 4),
            "locked_exact": p0_l,
            "modular_k100_exact": p0_m,
            "ceiling_exact": c0,
            "delta_locked_vs_l0_pp": 0.0,
            "delta_mod100_vs_l0_pp": 0.0,
            "parity_err_vs_rank_islet1_stacks": max(abs(dp_locked - p0_l), abs(dp_mod100 - p0_m)),
            "_internal_l0_bpr05": {
                "arms": [pa, pb, px],
                "dists": dists,
                "v_h123": v_h123,
                "routes": ("R1", "R2", "R1"),
                "cell_classes": ("UNHARDENED_A_B_X", "UNHARDENED_A_B_X", "UNHARDENED_A_B_X"),
            },
        }

    def build_h1_dist_5arm(c1_allo: float, p_d1: float) -> tuple[list[float], float]:
        if p_d1 > c1_allo + 1e-12:
            raise ValueError(f"p_d1={p_d1} exceeds c1_allo={c1_allo}")
        u_d1 = min(1.0, max(0.0, p_d1 / c1_allo))
        d1 = [0.0] * 32
        d1[0] = 1.0 - c1_allo
        d1[15] = c1_allo * (1.0 - u_d1)
        d1[31] = c1_allo * u_d1
        return d1, c1_allo

    def build_h2_dist_5arm(
        pa2: float, pb2: float, px2: float, py2: float, pd2: float,
        *, c2_inc: float, c2_y: float, c2_univ: float, c2_auto: float,
        phi_yx: float, phi_c: float,
    ) -> tuple[list[float], float]:
        if c2_inc > c2_y + 1e-12 or c2_y > c2_univ + 1e-12 or c2_auto > c2_univ + 1e-12:
            raise ValueError("Invalid H2 ceiling ordering")
        d2_inc = _frechet_joint([pa2 / c2_inc, pb2 / c2_inc, px2 / c2_inc], 0.0)
        r2 = c2_inc / c2_y
        u_y2 = py2 / c2_y
        d2_both = _frechet_couple(d2_inc, u_y2, phi_yx, lambda mi: bool(mi & 4))
        d2_allo4 = [0.0] * 16
        for k in range(16):
            d2_allo4[k] += r2 * d2_both[k]
        d2_allo4[0] += (1.0 - r2) * (1.0 - u_y2)
        d2_allo4[8] += (1.0 - r2) * u_y2

        biv2 = _bivariate(c2_y / c2_univ, c2_auto / c2_univ, phi_c)
        if pd2 > c2_auto + 1e-12:
            raise ValueError(f"pd2={pd2} exceeds c2_auto={c2_auto}")
        u_d2 = pd2 / c2_auto
        d2 = [0.0] * 32
        d2[0] += 1.0 - c2_univ
        for (s0, s1), wp in biv2.items():
            w = c2_univ * wp
            if s0 == 0 and s1 == 0:
                d2[0] += w
            elif s0 == 1 and s1 == 0:
                for m4 in range(16):
                    d2[m4] += w * d2_allo4[m4]
            elif s0 == 0 and s1 == 1:
                d2[0] += w * (1.0 - u_d2)
                d2[16] += w * u_d2
            else:
                for m4 in range(16):
                    d2[m4] += w * d2_allo4[m4] * (1.0 - u_d2)
                    d2[m4 | 16] += w * d2_allo4[m4] * u_d2
        c2_eff = c2_univ * (1.0 - biv2[(0, 0)])
        return d2, c2_eff

    def build_h3_dist_5arm(
        pa3: float, pb3: float, px3: float, py3: float, pd3: float,
        *, c3_a: float, c3_bx: float, c3_y: float, c3_d: float,
        phi_yx: float, phi_c: float,
    ) -> tuple[list[float], float]:
        """Exact nested variance-preserving 5-arm H3 distribution (uniform OR drug-free Design A firewall)."""
        if abs(c3_a - c3_bx) <= 1e-12 and abs(c3_d - c3_y) <= 1e-12 and c3_bx <= c3_y + 1e-12:
            d3_inc = _frechet_joint([pa3 / c3_bx, pb3 / c3_bx, px3 / c3_bx], 0.0)
            r3 = c3_bx / c3_y
            u_y3 = py3 / c3_y
            d3_both = _frechet_couple(d3_inc, u_y3, phi_yx, lambda mi: bool(mi & 4))
            d3_allo4 = [0.0] * 16
            for k in range(16):
                d3_allo4[k] += r3 * d3_both[k]
            d3_allo4[0] += (1.0 - r3) * (1.0 - u_y3)
            d3_allo4[8] += (1.0 - r3) * u_y3
            d3_5cond = _frechet_couple(d3_allo4, pd3 / c3_y, phi_c, lambda m4: m4 != 0)
            d3 = [0.0] * 32
            d3[0] += 1.0 - c3_y
            for k in range(32):
                d3[k] += c3_y * d3_5cond[k]
            return d3, c3_y

        if c3_a < c3_bx and abs(c3_bx - c3_y) <= 1e-12 and abs(c3_d - c3_y) <= 1e-12:
            c3_reset = c3_y
            r_a = c3_a / c3_reset
            u_a = pa3 / c3_a
            u_b = pb3 / c3_reset
            u_x = px3 / c3_reset
            u_y = py3 / c3_reset
            u_d = pd3 / c3_reset

            d_inc_all = _frechet_joint([u_a, u_b, u_x], 0.0)
            d_allo4_all = _frechet_couple(d_inc_all, u_y, phi_yx, lambda mi: bool(mi & 4))
            d_5_all = _frechet_couple(d_allo4_all, u_d, phi_c, lambda m4: m4 != 0)

            d_inc_no_a = _frechet_joint([0.0, u_b, u_x], 0.0)
            d_allo4_no_a = _frechet_couple(d_inc_no_a, u_y, phi_yx, lambda mi: bool(mi & 4))
            d_5_no_a = _frechet_couple(d_allo4_no_a, u_d, phi_c, lambda m4: m4 != 0)

            d3 = [0.0] * 32
            d3[0] += 1.0 - c3_reset
            w_all = c3_reset * r_a
            w_no_a = c3_reset * (1.0 - r_a)
            for k in range(32):
                d3[k] += w_all * d_5_all[k] + w_no_a * d_5_no_a[k]
            return d3, c3_reset

        raise ValueError(f"Unsupported H3 ceiling configuration: {(c3_a, c3_bx, c3_y, c3_d)}")

    def build_h4_dist_5arm(
        pa4: float, pb4: float, px4: float, py4: float, pd4: float,
        *, h4_topology: str, c4_univ: float,
        c4_pouch: float = 0.85, c4_r3p: float = 0.85, c4_r3b: float = 0.85,
        phi_c: float,
    ) -> tuple[list[float], float, tuple[str, ...]]:
        u_a = pa4 / c4_pouch
        u_b = pb4 / c4_pouch
        u_x = px4 / c4_pouch
        d_ax = _frechet_joint([u_a, u_x], 1.0)
        d4_inc = [0.0] * 8
        for m_ax in range(4):
            bit_a = m_ax & 1
            bit_x = (m_ax >> 1) & 1
            base_m = bit_a | (bit_x << 2)
            d4_inc[base_m] += d_ax[m_ax] * (1.0 - u_b)
            d4_inc[base_m | 2] += d_ax[m_ax] * u_b

        if h4_topology == "TWO_PARADIGM_WU3":
            biv4 = _bivariate(c4_pouch / c4_univ, c4_r3p / c4_univ, phi_c)
            d4_r3 = _frechet_joint([py4 / c4_r3p, pd4 / c4_r3p], 1.0)
            d4 = [0.0] * 32
            d4[0] += 1.0 - c4_univ
            for (s0, s1), wp in biv4.items():
                w = c4_univ * wp
                if s0 == 0 and s1 == 0:
                    d4[0] += w
                elif s0 == 1 and s1 == 0:
                    for m3 in range(8):
                        d4[m3] += w * d4_inc[m3]
                elif s0 == 0 and s1 == 1:
                    for mr in range(4):
                        m5 = ((mr & 1) << 3) | (((mr >> 1) & 1) << 4)
                        d4[m5] += w * d4_r3[mr]
                else:
                    for m3 in range(8):
                        for mr in range(4):
                            m5 = m3 | ((mr & 1) << 3) | (((mr >> 1) & 1) << 4)
                            d4[m5] += w * d4_inc[m3] * d4_r3[mr]
            c4_eff = c4_univ * (1.0 - biv4[(0, 0)])
            return d4, c4_eff, ("R1", "R2", "R1", "R3P", "R3P")

        if h4_topology == "THREE_PARADIGM_D1_ON_R3B":
            if pd4 > c4_r3b + 1e-12:
                raise ValueError(f"pd4={pd4} exceeds c4_r3b={c4_r3b}")
            u_y4 = py4 / c4_r3p
            u_d4 = pd4 / c4_r3b
            triv4 = _frechet_joint([c4_pouch / c4_univ, c4_r3p / c4_univ, c4_r3b / c4_univ], phi_c)
            d4 = [0.0] * 32
            d4[0] += 1.0 - c4_univ
            for s_mask in range(8):
                w = c4_univ * triv4[s_mask]
                if w == 0.0:
                    continue
                inc_dist = d4_inc if (s_mask & 1) else [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
                y_dist = [(1.0 - u_y4), u_y4] if (s_mask & 2) else [1.0, 0.0]
                b_dist = [(1.0 - u_d4), u_d4] if (s_mask & 4) else [1.0, 0.0]
                for m3, w3 in enumerate(inc_dist):
                    if w3 == 0.0:
                        continue
                    for my, wy in enumerate(y_dist):
                        if wy == 0.0:
                            continue
                        for mb, wb in enumerate(b_dist):
                            if wb == 0.0:
                                continue
                            d4[m3 | (my << 3) | (mb << 4)] += w * w3 * wy * wb
            c4_eff = c4_univ * (1.0 - triv4[0])
            return d4, c4_eff, ("R1", "R2", "R1", "R3P", "R3B")

        raise ValueError(f"Unknown h4_topology={h4_topology!r}")

    def evaluate_5arm_exact_2pow20(
        *,
        layer_id: str,
        label: str,
        epistemic_tier: str,
        drug_status: str,
        arms: list[tuple[float, float, float, float]],
        dists: list[list[float]],
        eff_ceils: list[float],
        routes: tuple[str, ...],
        compat_counterfactual: dict[str, frozenset[str]] | None,
        compat_hypo_transfer: dict[str, frozenset[str]] | None,
        cell_classes: tuple[str, ...],
        l0_locked: float,
        l0_mod100: float,
        l1_locked: float,
        l1_mod100: float,
        check_4096_incumbent_parity: bool = False,
        return_state_laws: bool = False,
    ) -> dict[str, Any]:
        n_states = 32
        d_inc3 = []
        for h in range(4):
            dh = dists[h]
            if len(dh) != n_states or min(dh) < -1e-12 or abs(sum(dh) - 1.0) > 1e-12:
                raise RuntimeError(f"Invalid probability distribution in {layer_id} H{h+1}")
            for i in range(5):
                rec = sum(dh[m] for m in range(n_states) if (m & (1 << i)))
                if abs(rec - arms[i][h]) > 1e-11:
                    raise RuntimeError(
                        f"Marginal drift {layer_id} arm {ARM_NAMES[i]} H{h+1}: {rec:.12f} vs {arms[i][h]:.12f}"
                    )
            di = [0.0] * 8
            for m in range(n_states):
                di[m & 7] += dh[m]
            d_inc3.append(di)

        max_4096_err = None
        if check_4096_incumbent_parity:
            canon = _live_canon_inc()
            max_4096_err = 0.0
            for m0 in range(8):
                p0a, p0b = d_inc3[0][m0], canon[0][m0]
                for m1 in range(8):
                    p1a, p1b = p0a * d_inc3[1][m1], p0b * canon[1][m1]
                    for m2 in range(8):
                        p2a, p2b = p1a * d_inc3[2][m2], p1b * canon[2][m2]
                        for m3 in range(8):
                            err = abs(p2a * d_inc3[3][m3] - p2b * canon[3][m3])
                            if err > max_4096_err:
                                max_4096_err = err
            if max_4096_err > 1e-12:
                raise RuntimeError(f"4,096-state parity failed on {layer_id}: {max_4096_err}")

        v = [0.0] * n_states
        v[n_states - 1] = 1.0
        v_h123: list[float] = []
        for h in range(4):
            dh = dists[h]
            vn = [0.0] * n_states
            for s, vs in enumerate(v):
                if vs == 0.0:
                    continue
                for m, w in enumerate(dh):
                    if w != 0.0:
                        vn[s & m] += vs * w
            v = vn
            if h == 2:
                v_h123 = list(v)

        # Strict live-registered mask (ALWAYS masks unregistered R3B!)
        strict_mask = 0
        has_unreg = False
        for i in range(5):
            if routes[i] in compat_strict_live[cell_classes[i]]:
                strict_mask |= (1 << i)
            else:
                has_unreg = True
        strict_locked = sum(v[s] for s in range(1, n_states) if (s & strict_mask) != 0)

        dh4 = dists[3]

        def _calc_mod(cmap: dict[str, frozenset[str]]) -> float:
            acc = 0.0
            for m_cell in range(1, n_states):
                wc = v_h123[m_cell]
                if wc == 0.0:
                    continue
                allowed_r: set[str] = set()
                for i in range(5):
                    if m_cell & (1 << i):
                        allowed_r |= cmap[cell_classes[i]]
                for m_h4 in range(1, n_states):
                    wh = dh4[m_h4]
                    if wh != 0.0 and any(routes[j] in allowed_r for j in range(5) if (m_h4 & (1 << j))):
                        acc += wc * wh
            return acc

        strict_mod100 = _calc_mod(compat_strict_live)
        strict_mod90 = 0.90 * strict_mod100 + 0.10 * strict_locked

        if has_unreg:
            if compat_counterfactual is None:
                raise RuntimeError(f"Unregistered route in {layer_id} without explicit counterfactual map")
            cf_mask = 0
            for i in range(5):
                if routes[i] in compat_counterfactual[cell_classes[i]]:
                    cf_mask |= (1 << i)
            cf_locked = sum(v[s] for s in range(1, n_states) if (s & cf_mask) != 0)
            cf_mod100 = _calc_mod(compat_counterfactual)
            cf_mod90 = 0.90 * cf_mod100 + 0.10 * cf_locked
            cf_mod100_hypo = _calc_mod(compat_hypo_transfer) if compat_hypo_transfer is not None else cf_mod100
        else:
            cf_locked = strict_locked
            cf_mod100 = strict_mod100
            cf_mod90 = strict_mod90
            cf_mod100_hypo = strict_mod100

        ceil = math.prod(eff_ceils)

        single_arms = {}
        for idx, nm in enumerate(ARM_NAMES):
            vec = arms[idx]
            single_arms[nm] = {
                "route": routes[idx],
                "route_live_registered": routes[idx] in compat_strict_live[cell_classes[idx]],
                "cell_class": cell_classes[idx],
                "hurdles": [round(x, 6) for x in vec],
                "standalone_pct": round(100.0 * math.prod(vec), 4),
            }

        out: dict[str, Any] = {
            "layer_id": layer_id,
            "label": label,
            "epistemic_tier": epistemic_tier,
            "drug_status": drug_status,
            "n_arms": 5,
            "state_space": 2 ** 20,
            "routes": list(routes),
            "has_unregistered_route_assignment": has_unreg,
            "route_registration_status": (
                "PARKED_COUNTERFACTUAL_UNREGISTERED_R3B_GY027_BLOCK"
                if has_unreg
                else "STRICT_LIVE_REGISTERED_ROUTES_ONLY"
            ),
            "single_arms": single_arms,
            "eff_ceilings_pct": [round(100.0 * c, 2) for c in eff_ceils],
            "composite_ceiling_pct": round(100.0 * ceil, 4),
            "ceiling_exact": ceil,
            # Strict live-eligible metrics (ALWAYS mask unregistered R3B!)
            "strict_live_eligible_locked_pct": round(100.0 * strict_locked, 4),
            "strict_live_eligible_mod90_pct": round(100.0 * strict_mod90, 4),
            "strict_live_eligible_mod100_pct": round(100.0 * strict_mod100, 4),
            "strict_live_eligible_locked_exact": strict_locked,
            "strict_live_eligible_mod100_exact": strict_mod100,
            "incumbent_4096_state_max_abs_err": max_4096_err,
        }
        if not has_unreg:
            out.update({
                "locked_pct": round(100.0 * strict_locked, 4),
                "modular_k90_pct": round(100.0 * strict_mod90, 4),
                "modular_k100_pct": round(100.0 * strict_mod100, 4),
                "locked_exact": strict_locked,
                "modular_k100_exact": strict_mod100,
                "delta_locked_vs_l0_pp": round(100.0 * (strict_locked - l0_locked), 4),
                "delta_mod100_vs_l0_pp": round(100.0 * (strict_mod100 - l0_mod100), 4),
                "delta_locked_vs_l1_pp": round(100.0 * (strict_locked - l1_locked), 4),
                "delta_mod100_vs_l1_pp": round(100.0 * (strict_mod100 - l1_mod100), 4),
                "residual_risk_reduction_vs_l0_locked_pct": round(100.0 * (strict_locked - l0_locked) / (1.0 - l0_locked), 2),
                "residual_risk_reduction_vs_l0_mod100_pct": round(100.0 * (strict_mod100 - l0_mod100) / (1.0 - l0_mod100), 2),
            })
        else:
            out.update({
                "counterfactual_if_r3b_registered_locked_pct": round(100.0 * cf_locked, 4),
                "counterfactual_if_r3b_registered_mod90_pct": round(100.0 * cf_mod90, 4),
                "counterfactual_if_r3b_registered_mod100_pct": round(100.0 * cf_mod100, 4),
                "counterfactual_hypo_transfer_k100_pct": round(100.0 * cf_mod100_hypo, 4),
                "counterfactual_if_r3b_registered_locked_exact": cf_locked,
                "counterfactual_if_r3b_registered_mod100_exact": cf_mod100,
                "counterfactual_hypo_transfer_k100_exact": cf_mod100_hypo,
                "delta_strict_live_locked_vs_l1_pp": round(100.0 * (strict_locked - l1_locked), 4),
                "delta_counterfactual_r3b_locked_vs_l1_pp": round(100.0 * (cf_locked - l1_locked), 4),
                "delta_counterfactual_r3b_mod100_vs_l1_pp": round(100.0 * (cf_mod100 - l1_mod100), 4),
            })
        if return_state_laws:
            out["_internal_v_h123"] = v_h123
            out["_internal_dh4"] = dh4
            out["_internal_dists"] = dists
            out["_internal_arms"] = arms
            out["_internal_routes"] = routes
            out["_internal_cell_classes"] = cell_classes
        return out

    def compute_checkerboard_stress_test(
        *,
        label: str,
        v_h123: list[float],
        dh4: list[float],
        baseline_locked_exact: float,
        target_locked_exact: float,
        eps: float = 0.003,
    ) -> dict[str, Any]:
        """
        Reproduce the legal 0.003 checkerboard mass-transfer witness between
        joint (m_cell, m_h4) cells {(0, 15), (0, 31), (16, 15), (16, 31)} involving
        only the added 5th arm (bit 4 = 16). Preserves every hurdle marginal and
        the full 3-incumbent-arm / 4,096-state projection while shifting locked
        success by exactly -eps (-0.3000 pp).
        """
        cells = ((0, 15), (0, 31), (16, 15), (16, 31))
        before = [v_h123[mc] * dh4[mh] for mc, mh in cells]
        after = [before[0] - eps, before[1] + eps, before[2] + eps, before[3] - eps]
        if min(after) < 0.0:
            raise RuntimeError(f"Checkerboard eps={eps} exceeds support in {label}: {before}")
        # Verify exact marginal and incumbent projection invariance
        m_cell_0_diff = (after[0] + after[1]) - (before[0] + before[1])
        m_cell_16_diff = (after[2] + after[3]) - (before[2] + before[3])
        m_h4_15_diff = (after[0] + after[2]) - (before[0] + before[2])
        m_h4_31_diff = (after[1] + after[3]) - (before[1] + before[3])
        max_inv_err = max(abs(m_cell_0_diff), abs(m_cell_16_diff), abs(m_h4_15_diff), abs(m_h4_31_diff))
        if max_inv_err > 1e-15:
            raise RuntimeError(f"Checkerboard invariance check failed: {max_inv_err}")
        # Only cell (16, 31) satisfies (mc & mh) != 0 (since 16 & 31 = 16, whereas 0&15=0, 0&31=0, 16&15=0)
        coupled_locked_exact = target_locked_exact - eps
        indep_delta_pp = 100.0 * (target_locked_exact - baseline_locked_exact)
        coupled_delta_pp = 100.0 * (coupled_locked_exact - baseline_locked_exact)
        return {
            "label": label,
            "transfer_epsilon": eps,
            "cell_route_masks_mcell_mh4": [list(c) for c in cells],
            "joint_masses_before": [round(x, 8) for x in before],
            "joint_masses_after": [round(x, 8) for x in after],
            "min_mass_after": round(min(after), 8),
            "marginal_and_incumbent_invariance_max_err": max_inv_err,
            "independent_locked_pct": round(100.0 * target_locked_exact, 4),
            "coupled_locked_pct": round(100.0 * coupled_locked_exact, 4),
            "independent_delta_vs_baseline_pp": round(indep_delta_pp, 4),
            "coupled_delta_vs_baseline_pp": round(coupled_delta_pp, 4),
            "flips_sign_negative": coupled_delta_pp < 0.0,
        }

    def build_layer_scenarios(phi_c: float, l0_locked: float, l0_mod100: float) -> dict[str, Any]:
        def _run(
            layer_id: str,
            label: str,
            epistemic_tier: str,
            drug_status: str,
            arms: list[tuple[float, float, float, float]],
            *,
            c1_allo: float,
            c2_inc: float = 0.87,
            c2_y: float = 0.87,
            c2_univ: float = 0.95,
            c2_auto: float = 0.93,
            c3_a: float,
            c3_bx: float,
            c3_y: float,
            c3_d: float,
            h4_topology: str,
            c4_univ: float = 0.92,
            c4_pouch: float = 0.85,
            c4_r3p: float = 0.85,
            c4_r3b: float = 0.85,
            phi_yx: float = 0.75,
            l1_ref: tuple[float, float] | None = None,
            check_4096: bool = False,
            return_state_laws: bool = False,
        ) -> dict[str, Any]:
            pa, pb, px, py, pd = arms
            d1, c1_e = build_h1_dist_5arm(c1_allo, pd[0])
            d2, c2_e = build_h2_dist_5arm(
                pa[1], pb[1], px[1], py[1], pd[1],
                c2_inc=c2_inc, c2_y=c2_y, c2_univ=c2_univ, c2_auto=c2_auto,
                phi_yx=phi_yx, phi_c=phi_c,
            )
            d3, c3_e = build_h3_dist_5arm(
                pa[2], pb[2], px[2], py[2], pd[2],
                c3_a=c3_a, c3_bx=c3_bx, c3_y=c3_y, c3_d=c3_d,
                phi_yx=phi_yx, phi_c=phi_c,
            )
            d4, c4_e, routes = build_h4_dist_5arm(
                pa[3], pb[3], px[3], py[3], pd[3],
                h4_topology=h4_topology, c4_univ=c4_univ,
                c4_pouch=c4_pouch, c4_r3p=c4_r3p, c4_r3b=c4_r3b,
                phi_c=phi_c,
            )
            ccf = compat_d1_r3b_counterfactual if h4_topology == "THREE_PARADIGM_D1_ON_R3B" else None
            ctr = compat_d1_r3b_hypo_transfer if h4_topology == "THREE_PARADIGM_D1_ON_R3B" else None
            l1_l = l1_ref[0] if l1_ref else 0.0
            l1_m = l1_ref[1] if l1_ref else 0.0
            out = evaluate_5arm_exact_2pow20(
                layer_id=layer_id,
                label=label,
                epistemic_tier=epistemic_tier,
                drug_status=drug_status,
                arms=arms,
                dists=[d1, d2, d3, d4],
                eff_ceils=[c1_e, c2_e, c3_e, c4_e],
                routes=routes,
                compat_counterfactual=ccf,
                compat_hypo_transfer=ctr,
                cell_classes=std_classes,
                l0_locked=l0_locked,
                l0_mod100=l0_mod100,
                l1_locked=l1_l,
                l1_mod100=l1_m,
                check_4096_incumbent_parity=check_4096,
                return_state_laws=return_state_laws,
            )
            if l1_ref is None and not out["has_unregistered_route_assignment"]:
                out["delta_locked_vs_l1_pp"] = 0.0
                out["delta_mod100_vs_l1_pp"] = 0.0
            return out

        strict_rows: list[dict[str, Any]] = []
        ineligible_full_cocktail_diag_rows: list[dict[str, Any]] = []
        parked_r3b_rows: list[dict[str, Any]] = []

        # =====================================================================
        # PART A: HEADLINE LIVE-ELIGIBLE STRICT SERIES (ZERO BLOCKED R3B!)
        # =====================================================================
        wu3_arms = [
            (0.88, 0.78, 0.57, 0.69),  # A @ R1
            (0.88, 0.79, 0.64, 0.70),  # B @ R2
            (0.88, 0.82, 0.73, 0.69),  # X @ R1
            (0.88, 0.84, 0.80, 0.72),  # Y @ R3P
            (0.62, 0.92, 0.70, 0.70),  # D @ R3P
        ]
        l1_layer_id = "L1_LIVE_5ARM_WU3" if abs(phi_c - 0.25) < 1e-9 else "L1_LIVE_5ARM_WU4"
        l1_wu_tag = "W_U3" if abs(phi_c - 0.25) < 1e-9 else "W_U4"
        l1 = _run(
            l1_layer_id,
            f"Layer 1: Shipped IIP-0035 5-Arm {l1_wu_tag} Baseline (phi={phi_c:.2f})",
            "Tier-0_Shipped_IIP0035_Baseline",
            "ZERO_DRUG_100PCT_STAGED",
            wu3_arms,
            c1_allo=0.88, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89, c3_bx=0.89, c3_y=0.89, c3_d=0.89,
            h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
            l1_ref=None, check_4096=True,
        )
        l1_ref = (l1["locked_exact"], l1["modular_k100_exact"])
        strict_rows.append(l1)

        # Layer 2A (EXP-028 S3 parity: c2=0.87, c3=0.89)
        l2a_s2a_arms = [
            (0.90, 0.78, 0.57, 0.69),
            (0.90, 0.79, 0.64, 0.70),
            (0.90, 0.82, 0.73, 0.69),
            (0.90, 0.84, 0.80, 0.72),
            (0.62, 0.92, 0.70, 0.70),
        ]
        strict_rows.append(_run(
            "L2A_EXP028_S2a_H1_90_ZERO_H3_LIFT",
            "Layer 2A (EXP-028 S2a): Conditional H1=90% + ABX CD64t/IL1RN Defensive Recovery (Zero H2/H3 Lift)",
            "Tier-A_Conditional_Clinical_H1_and_Stage0_ModeB",
            "ZERO_DRUG_100PCT",
            l2a_s2a_arms,
            c1_allo=0.90, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89, c3_bx=0.89, c3_y=0.89, c3_d=0.89,
            h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
            l1_ref=l1_ref,
        ))

        l2a_s2c_arms = [
            (0.90, 0.78, 0.62, 0.69),
            (0.90, 0.79, 0.68, 0.70),
            (0.90, 0.82, 0.78, 0.69),
            (0.90, 0.84, 0.80, 0.72),
            (0.62, 0.92, 0.70, 0.70),
        ]
        strict_rows.append(_run(
            "L2A_EXP028_S2c_CONDITIONAL_STAGE0",
            "Layer 2A (EXP-028 S2c): Conditional H1=90% + Speculative Stage-0 p3=[62,68,78] (c2=87/c3=89)",
            "Tier-A_Conditional_Clinical_H1_and_Stage0_ModeB",
            "ZERO_DRUG_100PCT",
            l2a_s2c_arms,
            c1_allo=0.90, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89, c3_bx=0.89, c3_y=0.89, c3_d=0.89,
            h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
            l1_ref=l1_ref,
        ))

        # Layer 2B Strict 100% Zero-Drug Passive 65um Bilayer (no blocked R3B, no GW2580)
        l2b_df_arms = [
            (0.88, 0.78, 0.57, 0.72),
            (0.88, 0.79, 0.64, 0.76),
            (0.88, 0.82, 0.73, 0.72),
            (0.88, 0.84, 0.80, 0.72),
            (0.62, 0.92, 0.70, 0.70),
        ]
        strict_rows.append(_run(
            "L2B_DF_PASSIVE_65UM_BILAYER_ZERO_DRUG",
            "Layer 2B Zero-Drug Passive: W_U3 + 65um Bilayer (Zero iEOG, Zero GW2580)",
            "Tier-S0_Passive_Bilayer_Stage0",
            "ZERO_DRUG_100PCT",
            l2b_df_arms,
            c1_allo=0.88, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89, c3_bx=0.89, c3_y=0.89, c3_d=0.89,
            h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
            l1_ref=l1_ref,
        ))

        # Layer 2C: Optional Track-B Finite Reset (Day-1 active 0.5 mg/kg MELD-ATG + Day-2 placebo; Design A drug-free)
        strict_rows.append(_run(
            "L2C_EXP030_FINITE_RESET",
            "Layer 2C (Upside Scenario): W_U3 + Optional Track-B Reset (Day-1 0.5 mg/kg MELD-ATG + Day-2 placebo; A Drug-Free, c3=93%)",
            "Tier-A_NativeT1D_RCTs_Unvalidated_Graft_Scenario",
            "TRACK_B_OPTIONAL_DAY1_ATG_A_DRUG_FREE",
            [
                (0.88, 0.78, 0.57 + D_RESET_ARMS_CENTRAL["A"], 0.69),
                (0.88, 0.79, 0.64 + D_RESET_ARMS_CENTRAL["B"], 0.70),
                (0.88, 0.82, 0.73 + D_RESET_ARMS_CENTRAL["X"], 0.69),
                (0.88, 0.84, 0.80 + D_RESET_ARMS_CENTRAL["Y"], 0.72),
                (0.62, 0.92, 0.70 + D_RESET_ARMS_CENTRAL["D"], 0.70),
            ],
            c1_allo=0.88, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89, c3_bx=0.89 + DC3_RESET_CENTRAL, c3_y=0.89 + DC3_RESET_CENTRAL, c3_d=0.89 + DC3_RESET_CENTRAL,
            h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
            l1_ref=l1_ref,
        ))

        strict_rows.append(_run(
            "L2C_SENS_FINITE_RESET_CONSERVATIVE_C3_0P92",
            "Layer 2C Sensitivity: Finite Reset Conservative Durability (c3_reset=92%, A Drug-Free)",
            "Tier-A_NativeT1D_RCTs_Unvalidated_Graft_Scenario",
            "TRACK_B_OPTIONAL_DAY1_ATG_A_DRUG_FREE",
            [
                (0.88, 0.78, 0.57 + D_RESET_ARMS_CONSERVATIVE["A"], 0.69),
                (0.88, 0.79, 0.64 + D_RESET_ARMS_CONSERVATIVE["B"], 0.70),
                (0.88, 0.82, 0.73 + D_RESET_ARMS_CONSERVATIVE["X"], 0.69),
                (0.88, 0.84, 0.80 + D_RESET_ARMS_CONSERVATIVE["Y"], 0.72),
                (0.62, 0.92, 0.70 + D_RESET_ARMS_CONSERVATIVE["D"], 0.70),
            ],
            c1_allo=0.88, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89, c3_bx=0.89 + DC3_RESET_CONSERVATIVE, c3_y=0.89 + DC3_RESET_CONSERVATIVE, c3_d=0.89 + DC3_RESET_CONSERVATIVE,
            h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
            l1_ref=l1_ref,
        ))

        strict_rows.append(_run(
            "L2C_AE_PENALIZED_FINITE_RESET",
            "Layer 2C-AE (AE/Steroid-Rescue Downside): c3_reset=91% + -1.5pp H4 Haircut on {B,X,Y,D} (A Untouched)",
            "Tier-A_AE_Penalized_Downside_Scenario",
            "TRACK_B_OPTIONAL_DAY1_ATG_A_DRUG_FREE",
            [
                (0.88, 0.78, 0.57 + D_RESET_ARMS_AE_DOWNSIDE["A"], 0.69),
                (0.88, 0.79, 0.64 + D_RESET_ARMS_AE_DOWNSIDE["B"], 0.70 + H4_AE_STEROID_HAIRCUT_NON_A),
                (0.88, 0.82, 0.73 + D_RESET_ARMS_AE_DOWNSIDE["X"], 0.69 + H4_AE_STEROID_HAIRCUT_NON_A),
                (0.88, 0.84, 0.80 + D_RESET_ARMS_AE_DOWNSIDE["Y"], 0.72 + H4_AE_STEROID_HAIRCUT_NON_A),
                (0.62, 0.92, 0.70 + D_RESET_ARMS_AE_DOWNSIDE["D"], 0.70 + H4_AE_STEROID_HAIRCUT_NON_A),
            ],
            c1_allo=0.88, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89, c3_bx=0.89 + DC3_RESET_AE_DOWNSIDE, c3_y=0.89 + DC3_RESET_AE_DOWNSIDE, c3_d=0.89 + DC3_RESET_AE_DOWNSIDE,
            h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
            l1_ref=l1_ref,
        ))

        # ---------------------------------------------------------------------
        # HONEST STAGE-0 ZERO-SORT / ZERO-GUARD FOUNDRY SCENARIOS (S4 audit remediation)
        # 0 credit for Islet-SORT (ITGA2 inversion) and Islet-GUARD (18-Cys/bleeding)
        # Includes 50% PK/delivery-feasibility discount for 6.77/6.49 kDa miniprotein SHIELD!
        # ---------------------------------------------------------------------
        for pk_mult, suffix, pk_note in (
            (1.0, "FULL_ASSUMED_PK", "Assumed Full Target Engagement (No PK Discount)"),
            (MINIPROTEIN_PK_DISCOUNT_FACTOR, "PK_RENAL_DISCOUNT_50PCT", "50% Delivery-Feasibility / PK Discount for 6.77/6.49 kDa Miniproteins"),
        ):
            strict_rows.append(_run(
                f"L3A_SHIELD1_ONLY_ZERO_SORT_GUARD_{suffix}",
                f"Honest Stage-0 Foundry (0 SORT, 0 GUARD): W_U3 + SHIELD-1 Only [{pk_note}]",
                "Tier-B_Stage0_PreLab_Zero_SORT_GUARD",
                "ZERO_DRUG_100PCT",
                [
                    (0.88, 0.78, 0.57 + pk_mult * D_SHIELD1_ARMS["A"], 0.69),
                    (0.88, 0.79, 0.64 + pk_mult * D_SHIELD1_ARMS["B"], 0.70),
                    (0.88, 0.82, 0.73 + pk_mult * D_SHIELD1_ARMS["X"], 0.69),
                    (0.88, 0.84, 0.80 + pk_mult * D_SHIELD1_ARMS["Y"], 0.72),
                    (0.62, 0.92, 0.70 + pk_mult * D_SHIELD1_ARMS["D"], 0.70),
                ],
                c1_allo=0.88, c2_inc=0.87, c2_y=0.87,
                c3_a=0.89 + pk_mult * DC3_SHIELD1,
                c3_bx=0.89 + pk_mult * DC3_SHIELD1,
                c3_y=0.89 + pk_mult * DC3_SHIELD1,
                c3_d=0.89 + pk_mult * DC3_SHIELD1,
                h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
                l1_ref=l1_ref,
            ))
            strict_rows.append(_run(
                f"L3B_COCKTAIL_ONLY_ZERO_SORT_GUARD_{suffix}",
                f"UNSEQUENCED HYPOTHESIS (0 SORT, 0 GUARD): W_U3 + Future SHIELD Cocktail [{pk_note}]",
                "Tier-C_UNSEQUENCED_HYPOTHESIS_Zero_SORT_GUARD",
                "ZERO_DRUG_100PCT",
                [
                    (0.88, 0.78, 0.57 + pk_mult * D_SHIELD_COCKTAIL_ARMS_BASE["A"], 0.69),
                    (0.88, 0.79, 0.64 + pk_mult * D_SHIELD_COCKTAIL_ARMS_BASE["B"], 0.70),
                    (0.88, 0.82, 0.73 + pk_mult * D_SHIELD_COCKTAIL_ARMS_BASE["X"], 0.69),
                    (0.88, 0.84, 0.80 + pk_mult * D_SHIELD_COCKTAIL_ARMS_BASE["Y"], 0.72),
                    (0.62, 0.92, 0.70 + pk_mult * D_SHIELD_COCKTAIL_ARMS_BASE["D"], 0.70),
                ],
                c1_allo=0.88, c2_inc=0.87, c2_y=0.87,
                c3_a=0.89 + pk_mult * DC3_SHIELD_COCKTAIL,
                c3_bx=0.89 + pk_mult * DC3_SHIELD_COCKTAIL,
                c3_y=0.89 + pk_mult * DC3_SHIELD_COCKTAIL,
                c3_d=0.89 + pk_mult * DC3_SHIELD_COCKTAIL,
                h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
                l1_ref=l1_ref,
            ))

        # Strict Zero-Drug + Zero-SORT/Zero-GUARD + Optional Track-B Reset branches
        strict_rows.append(_run(
            "L3_SHIELD_FAIL_STRICT_ZERO_SORT_GUARD",
            "Strict Zero-Drug SHIELD-Fail (0 SORT, 0 GUARD, 0 R3B): EXP-028 S2c + 65um Bilayer",
            "Tier-B_SHIELD_Fail_Zero_SORT_GUARD",
            "ZERO_DRUG_100PCT",
            [
                (0.90, 0.78, 0.62, 0.72),
                (0.90, 0.79, 0.68, 0.76),
                (0.90, 0.82, 0.78, 0.72),
                (0.90, 0.84, 0.80, 0.72),
                (0.62, 0.92, 0.70, 0.70),
            ],
            c1_allo=0.90, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89, c3_bx=0.89, c3_y=0.89, c3_d=0.89,
            h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
            l1_ref=l1_ref,
        ))
        strict_rows.append(_run(
            "L3_SHIELD_FAIL_STRICT_ZERO_SORT_GUARD_PLUS_RESET",
            "Strict SHIELD-Fail (0 SORT/GUARD/R3B) + Track-B Reset Upside (c3=93%, A Drug-Free)",
            "Tier-B_SHIELD_Fail_Plus_Tier-A_Reset_Scenario",
            "TRACK_B_OPTIONAL_DAY1_ATG_ZERO_GW2580_A_DRUG_FREE",
            [
                (0.90, 0.78, 0.62, 0.72),
                (0.90, 0.79, 0.68 + D_RESET_ARMS_CENTRAL["B"], 0.76),
                (0.90, 0.82, 0.78 + D_RESET_ARMS_CENTRAL["X"], 0.72),
                (0.90, 0.84, 0.80 + D_RESET_ARMS_CENTRAL["Y"], 0.72),
                (0.62, 0.92, 0.70 + D_RESET_ARMS_CENTRAL["D"], 0.70),
            ],
            c1_allo=0.90, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89, c3_bx=0.89 + DC3_RESET_CENTRAL, c3_y=0.89 + DC3_RESET_CENTRAL, c3_d=0.89 + DC3_RESET_CENTRAL,
            h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
            l1_ref=l1_ref,
        ))
        strict_rows.append(_run(
            "L3_SHIELD_FAIL_STRICT_ZERO_SORT_GUARD_PLUS_AE_RESET",
            "Strict SHIELD-Fail (0 SORT/GUARD/R3B) + Track-B AE-Penalized Reset (c3=91%, -1.5pp H4, A Drug-Free)",
            "Tier-B_SHIELD_Fail_Plus_Tier-A_AE_Scenario",
            "TRACK_B_OPTIONAL_DAY1_ATG_ZERO_GW2580_A_DRUG_FREE",
            [
                (0.90, 0.78, 0.62, 0.72),
                (0.90, 0.79, 0.68 + D_RESET_ARMS_AE_DOWNSIDE["B"], 0.76 + H4_AE_STEROID_HAIRCUT_NON_A),
                (0.90, 0.82, 0.78 + D_RESET_ARMS_AE_DOWNSIDE["X"], 0.72 + H4_AE_STEROID_HAIRCUT_NON_A),
                (0.90, 0.84, 0.80 + D_RESET_ARMS_AE_DOWNSIDE["Y"], 0.72 + H4_AE_STEROID_HAIRCUT_NON_A),
                (0.62, 0.92, 0.70 + D_RESET_ARMS_AE_DOWNSIDE["D"], 0.70 + H4_AE_STEROID_HAIRCUT_NON_A),
            ],
            c1_allo=0.90, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89, c3_bx=0.89 + DC3_RESET_AE_DOWNSIDE, c3_y=0.89 + DC3_RESET_AE_DOWNSIDE, c3_d=0.89 + DC3_RESET_AE_DOWNSIDE,
            h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
            l1_ref=l1_ref,
        ))

        strict_rows.append(_run(
            "L3A_STRICT_ZERO_SORT_GUARD",
            "Strict Zero-Drug L3A (0 SORT, 0 GUARD, 0 R3B): EXP-028 S2c + 65um Bilayer + SHIELD-1",
            "Tier-B_Stage0_PreLab_Zero_SORT_GUARD",
            "ZERO_DRUG_100PCT",
            [
                (0.90, 0.78, 0.62 + D_SHIELD1_ARMS["A"], 0.72),
                (0.90, 0.79, 0.68 + D_SHIELD1_ARMS["B"], 0.76),
                (0.90, 0.82, 0.78 + D_SHIELD1_ARMS["X"], 0.72),
                (0.90, 0.84, 0.80 + D_SHIELD1_ARMS["Y"], 0.72),
                (0.62, 0.92, 0.70 + D_SHIELD1_ARMS["D"], 0.70),
            ],
            c1_allo=0.90, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89 + DC3_SHIELD1, c3_bx=0.89 + DC3_SHIELD1, c3_y=0.89 + DC3_SHIELD1, c3_d=0.89 + DC3_SHIELD1,
            h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
            l1_ref=l1_ref,
        ))
        c3j_s1_60 = subadditive_overlap(0.89, DC3_SHIELD1, DC3_RESET_CENTRAL, 0.60)
        strict_rows.append(_run(
            "L3A_STRICT_ZERO_SORT_GUARD_PLUS_RESET_OMEGA_0P60",
            "Strict L3A (0 SORT/GUARD/R3B) + Track-B Reset Upside (omega=0.60, A Drug-Free)",
            "Tier-B_Plus_Tier-A_Reset_Scenario",
            "TRACK_B_OPTIONAL_DAY1_ATG_ZERO_GW2580_A_DRUG_FREE",
            [
                (0.90, 0.78, 0.62 + D_SHIELD1_ARMS["A"], 0.72),
                (0.90, 0.79, subadditive_overlap(0.68, D_SHIELD1_ARMS["B"], D_RESET_ARMS_CENTRAL["B"], 0.60), 0.76),
                (0.90, 0.82, subadditive_overlap(0.78, D_SHIELD1_ARMS["X"], D_RESET_ARMS_CENTRAL["X"], 0.60), 0.72),
                (0.90, 0.84, subadditive_overlap(0.80, D_SHIELD1_ARMS["Y"], D_RESET_ARMS_CENTRAL["Y"], 0.60), 0.72),
                (0.62, 0.92, subadditive_overlap(0.70, D_SHIELD1_ARMS["D"], D_RESET_ARMS_CENTRAL["D"], 0.60), 0.70),
            ],
            c1_allo=0.90, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89 + DC3_SHIELD1, c3_bx=c3j_s1_60, c3_y=c3j_s1_60, c3_d=c3j_s1_60,
            h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
            l1_ref=l1_ref,
        ))
        c3j_s1_ae = subadditive_overlap(0.89, DC3_SHIELD1, DC3_RESET_AE_DOWNSIDE, 0.60)
        strict_rows.append(_run(
            "L3A_STRICT_ZERO_SORT_GUARD_PLUS_AE_RESET_OMEGA_0P60",
            "Strict L3A (0 SORT/GUARD/R3B) + Track-B AE-Penalized Reset (omega=0.60, -1.5pp H4, A Drug-Free)",
            "Tier-B_Plus_Tier-A_AE_Scenario",
            "TRACK_B_OPTIONAL_DAY1_ATG_ZERO_GW2580_A_DRUG_FREE",
            [
                (0.90, 0.78, 0.62 + D_SHIELD1_ARMS["A"], 0.72),
                (0.90, 0.79, subadditive_overlap(0.68, D_SHIELD1_ARMS["B"], D_RESET_ARMS_AE_DOWNSIDE["B"], 0.60), 0.76 + H4_AE_STEROID_HAIRCUT_NON_A),
                (0.90, 0.82, subadditive_overlap(0.78, D_SHIELD1_ARMS["X"], D_RESET_ARMS_AE_DOWNSIDE["X"], 0.60), 0.72 + H4_AE_STEROID_HAIRCUT_NON_A),
                (0.90, 0.84, subadditive_overlap(0.80, D_SHIELD1_ARMS["Y"], D_RESET_ARMS_AE_DOWNSIDE["Y"], 0.60), 0.72 + H4_AE_STEROID_HAIRCUT_NON_A),
                (0.62, 0.92, subadditive_overlap(0.70, D_SHIELD1_ARMS["D"], D_RESET_ARMS_AE_DOWNSIDE["D"], 0.60), 0.70 + H4_AE_STEROID_HAIRCUT_NON_A),
            ],
            c1_allo=0.90, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89 + DC3_SHIELD1, c3_bx=c3j_s1_ae, c3_y=c3j_s1_ae, c3_d=c3j_s1_ae,
            h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
            l1_ref=l1_ref,
        ))

        # ---------------------------------------------------------------------
        # STRICT 100% ZERO-DRUG FULL FOUNDRY SENSITIVITIES (SORT/GUARD LABELED SENSITIVITY; ZERO R3B)
        # ---------------------------------------------------------------------
        strict_rows.append(_run(
            "L3A_FOUNDRY_V12_STANDALONE",
            "Layer 3A Sensitivity (Standalone w/ SORT+GUARD[R1 only]): W_U3 + Foundry v1.2",
            "Tier-B_Sensitivity_With_Unvalidated_SORT_GUARD",
            "ZERO_DRUG_100PCT",
            [
                (0.88, 0.78, 0.57 + D_SHIELD1_ARMS["A"] + D_GUARD_H3_ARMS["A"], 0.69 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["A"]),
                (0.88, 0.79, 0.64 + D_SHIELD1_ARMS["B"], 0.70 + D_SORT_H4_ALL),
                (0.88, 0.82, 0.73 + D_SHIELD1_ARMS["X"] + D_GUARD_H3_ARMS["X"], 0.69 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["X"]),
                (0.88, 0.84, 0.80 + D_SHIELD1_ARMS["Y"], 0.72 + D_SORT_H4_ALL),
                (0.62 + D_SORT_H1_D, 0.92, 0.70 + D_SHIELD1_ARMS["D"], 0.70 + D_SORT_H4_ALL),
            ],
            c1_allo=0.88, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89 + DC3_SHIELD1, c3_bx=0.89 + DC3_SHIELD1, c3_y=0.89 + DC3_SHIELD1, c3_d=0.89 + DC3_SHIELD1,
            h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
            l1_ref=l1_ref,
        ))

        strict_rows.append(_run(
            "L3A_STACK_STRICT_100PCT_ZERO_DRUG",
            "Layer 3A Strict Zero-Drug (w/ SORT+GUARD[R1] sensitivity, 0 R3B): EXP-028 S2c + 65um Bilayer + Foundry v1.2",
            "Tier-B_Sensitivity_With_Unvalidated_SORT_GUARD",
            "ZERO_DRUG_100PCT",
            [
                (0.90, 0.78, 0.62 + D_SHIELD1_ARMS["A"] + D_GUARD_H3_ARMS["A"], 0.72 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["A"]),
                (0.90, 0.79, 0.68 + D_SHIELD1_ARMS["B"], 0.76 + D_SORT_H4_ALL),
                (0.90, 0.82, 0.78 + D_SHIELD1_ARMS["X"] + D_GUARD_H3_ARMS["X"], 0.72 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["X"]),
                (0.90, 0.84, 0.80 + D_SHIELD1_ARMS["Y"], 0.72 + D_SORT_H4_ALL),
                (0.62 + D_SORT_H1_D, 0.92, 0.70 + D_SHIELD1_ARMS["D"], 0.70 + D_SORT_H4_ALL),
            ],
            c1_allo=0.90, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89 + DC3_SHIELD1, c3_bx=0.89 + DC3_SHIELD1, c3_y=0.89 + DC3_SHIELD1, c3_d=0.89 + DC3_SHIELD1,
            h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
            l1_ref=l1_ref,
        ))

        for om, lid, lbl in (
            (0.60, "L3A_STRICT_ZERODRUG_PLUS_RESET_OMEGA_0P60", "Layer 3A Strict Zero-Drug + Track-B Reset (omega=0.60, 0 R3B, A Drug-Free)"),
            (0.80, "L3A_STRICT_ZERODRUG_PLUS_RESET_OMEGA_0P80", "Layer 3A Strict Zero-Drug + Track-B Reset (omega=0.80, 0 R3B, A Drug-Free)"),
        ):
            c3j = subadditive_overlap(0.89, DC3_SHIELD1, DC3_RESET_CENTRAL, om)
            _need_bpr05_laws = (lid == "L3A_STRICT_ZERODRUG_PLUS_RESET_OMEGA_0P60" and abs(phi_c - 0.25) < 1e-9)
            res = _run(
                lid, lbl,
                "Tier-B_Sensitivity_Plus_Tier-A_Reset",
                "TRACK_B_OPTIONAL_DAY1_ATG_ZERO_GW2580_A_DRUG_FREE",
                [
                    (0.90, 0.78, 0.62 + D_SHIELD1_ARMS["A"] + D_GUARD_H3_ARMS["A"], 0.72 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["A"]),
                    (0.90, 0.79, subadditive_overlap(0.68, D_SHIELD1_ARMS["B"], D_RESET_ARMS_CENTRAL["B"], om), 0.76 + D_SORT_H4_ALL),
                    (0.90, 0.82, subadditive_overlap(0.78 + D_GUARD_H3_ARMS["X"], D_SHIELD1_ARMS["X"], D_RESET_ARMS_CENTRAL["X"], om), 0.72 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["X"]),
                    (0.90, 0.84, subadditive_overlap(0.80, D_SHIELD1_ARMS["Y"], D_RESET_ARMS_CENTRAL["Y"], om), 0.72 + D_SORT_H4_ALL),
                    (0.62 + D_SORT_H1_D, 0.92, subadditive_overlap(0.70, D_SHIELD1_ARMS["D"], D_RESET_ARMS_CENTRAL["D"], om), 0.70 + D_SORT_H4_ALL),
                ],
                c1_allo=0.90, c2_inc=0.87, c2_y=0.87,
                c3_a=0.89 + DC3_SHIELD1, c3_bx=c3j, c3_y=c3j, c3_d=c3j,
                h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
                l1_ref=l1_ref,
                return_state_laws=_need_bpr05_laws,
            )
            res["overlap_damping_omega"] = om
            res["c3_joint_exact"] = round(c3j, 6)
            strict_rows.append(res)

        res_l3a_df_ae = _run(
            "L3A_STRICT_ZERODRUG_PLUS_AE_RESET_OMEGA_0P60",
            "Layer 3A Strict Zero-Drug + Track-B AE-Penalized Reset (omega=0.60, 0 R3B, A Drug-Free)",
            "Tier-B_Sensitivity_Plus_Tier-A_AE_Downside",
            "TRACK_B_OPTIONAL_DAY1_ATG_ZERO_GW2580_A_DRUG_FREE",
            [
                (0.90, 0.78, 0.62 + D_SHIELD1_ARMS["A"] + D_GUARD_H3_ARMS["A"], 0.72 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["A"]),
                (0.90, 0.79, subadditive_overlap(0.68, D_SHIELD1_ARMS["B"], D_RESET_ARMS_AE_DOWNSIDE["B"], 0.60), 0.76 + D_SORT_H4_ALL + H4_AE_STEROID_HAIRCUT_NON_A),
                (0.90, 0.82, subadditive_overlap(0.78 + D_GUARD_H3_ARMS["X"], D_SHIELD1_ARMS["X"], D_RESET_ARMS_AE_DOWNSIDE["X"], 0.60), 0.72 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["X"] + H4_AE_STEROID_HAIRCUT_NON_A),
                (0.90, 0.84, subadditive_overlap(0.80, D_SHIELD1_ARMS["Y"], D_RESET_ARMS_AE_DOWNSIDE["Y"], 0.60), 0.72 + D_SORT_H4_ALL + H4_AE_STEROID_HAIRCUT_NON_A),
                (0.62 + D_SORT_H1_D, 0.92, subadditive_overlap(0.70, D_SHIELD1_ARMS["D"], D_RESET_ARMS_AE_DOWNSIDE["D"], 0.60), 0.70 + D_SORT_H4_ALL + H4_AE_STEROID_HAIRCUT_NON_A),
            ],
            c1_allo=0.90, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89 + DC3_SHIELD1, c3_bx=c3j_s1_ae, c3_y=c3j_s1_ae, c3_d=c3j_s1_ae,
            h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
            l1_ref=l1_ref,
        )
        res_l3a_df_ae["overlap_damping_omega"] = 0.60
        res_l3a_df_ae["c3_joint_exact"] = round(c3j_s1_ae, 6)
        strict_rows.append(res_l3a_df_ae)

        # SHIELD-Fail (with SORT+GUARD sensitivity, 0 R3B)
        strict_rows.append(_run(
            "L3_SHIELD_FAIL_ZERODRUG_BASE",
            "SHIELD-Fail Branch (100% Zero-Drug, w/ SORT+GUARD[R1] sens, 0 R3B): EXP-028 S2c + 65um Bilayer",
            "Tier-B_SHIELD_Fail_Contingency_Base",
            "ZERO_DRUG_100PCT",
            [
                (0.90, 0.78, 0.62 + D_GUARD_H3_ARMS["A"], 0.72 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["A"]),
                (0.90, 0.79, 0.68, 0.76 + D_SORT_H4_ALL),
                (0.90, 0.82, 0.78 + D_GUARD_H3_ARMS["X"], 0.72 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["X"]),
                (0.90, 0.84, 0.80, 0.72 + D_SORT_H4_ALL),
                (0.62 + D_SORT_H1_D, 0.92, 0.70, 0.70 + D_SORT_H4_ALL),
            ],
            c1_allo=0.90, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89, c3_bx=0.89, c3_y=0.89, c3_d=0.89,
            h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
            l1_ref=l1_ref,
        ))
        strict_rows.append(_run(
            "L3_SHIELD_FAIL_PLUS_FINITE_RESET",
            "SHIELD-Fail + Optional Track-B Reset Upside (c3=93%, Zero GW2580, 0 R3B, A Drug-Free)",
            "Tier-B_SHIELD_Fail_Plus_Tier-A_FiniteReset",
            "TRACK_B_OPTIONAL_DAY1_ATG_ZERO_GW2580_A_DRUG_FREE",
            [
                (0.90, 0.78, 0.62 + D_GUARD_H3_ARMS["A"], 0.72 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["A"]),
                (0.90, 0.79, 0.68 + D_RESET_ARMS_CENTRAL["B"], 0.76 + D_SORT_H4_ALL),
                (0.90, 0.82, 0.78 + D_GUARD_H3_ARMS["X"] + D_RESET_ARMS_CENTRAL["X"], 0.72 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["X"]),
                (0.90, 0.84, 0.80 + D_RESET_ARMS_CENTRAL["Y"], 0.72 + D_SORT_H4_ALL),
                (0.62 + D_SORT_H1_D, 0.92, 0.70 + D_RESET_ARMS_CENTRAL["D"], 0.70 + D_SORT_H4_ALL),
            ],
            c1_allo=0.90, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89, c3_bx=0.89 + DC3_RESET_CENTRAL, c3_y=0.89 + DC3_RESET_CENTRAL, c3_d=0.89 + DC3_RESET_CENTRAL,
            h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
            l1_ref=l1_ref,
        ))
        strict_rows.append(_run(
            "L3_SHIELD_FAIL_PLUS_AE_PENALIZED_RESET",
            "SHIELD-Fail + Optional Track-B AE-Penalized Reset (c3=91%, -1.5pp H4, 0 R3B, A Untouched)",
            "Tier-B_SHIELD_Fail_Plus_Tier-A_AE_Downside",
            "TRACK_B_OPTIONAL_DAY1_ATG_ZERO_GW2580_A_DRUG_FREE",
            [
                (0.90, 0.78, 0.62 + D_GUARD_H3_ARMS["A"], 0.72 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["A"]),
                (0.90, 0.79, 0.68 + D_RESET_ARMS_AE_DOWNSIDE["B"], 0.76 + D_SORT_H4_ALL + H4_AE_STEROID_HAIRCUT_NON_A),
                (0.90, 0.82, 0.78 + D_GUARD_H3_ARMS["X"] + D_RESET_ARMS_AE_DOWNSIDE["X"], 0.72 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["X"] + H4_AE_STEROID_HAIRCUT_NON_A),
                (0.90, 0.84, 0.80 + D_RESET_ARMS_AE_DOWNSIDE["Y"], 0.72 + D_SORT_H4_ALL + H4_AE_STEROID_HAIRCUT_NON_A),
                (0.62 + D_SORT_H1_D, 0.92, 0.70 + D_RESET_ARMS_AE_DOWNSIDE["D"], 0.70 + D_SORT_H4_ALL + H4_AE_STEROID_HAIRCUT_NON_A),
            ],
            c1_allo=0.90, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89, c3_bx=0.89 + DC3_RESET_AE_DOWNSIDE, c3_y=0.89 + DC3_RESET_AE_DOWNSIDE, c3_d=0.89 + DC3_RESET_AE_DOWNSIDE,
            h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
            l1_ref=l1_ref,
        ))

        # Layer 3B Strict Zero-Drug (UNSEQUENCED HYPOTHESIS, 0 R3B)
        strict_rows.append(_run(
            "L3B_FOUNDRY_COCKTAIL_STANDALONE",
            "UNSEQUENCED HYPOTHESIS (Standalone): W_U3 + Future SHIELD Cocktail + SORT + GUARD[R1]",
            "Tier-C_UNSEQUENCED_HYPOTHESIS",
            "ZERO_DRUG_100PCT",
            [
                (0.88, 0.78, 0.57 + D_SHIELD_COCKTAIL_ARMS_BASE["A"] + D_GUARD_H3_ARMS["A"], 0.69 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["A"]),
                (0.88, 0.79, 0.64 + D_SHIELD_COCKTAIL_ARMS_BASE["B"], 0.70 + D_SORT_H4_ALL),
                (0.88, 0.82, 0.73 + D_SHIELD_COCKTAIL_ARMS_BASE["X"] + D_GUARD_H3_ARMS["X"], 0.69 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["X"]),
                (0.88, 0.84, 0.80 + D_SHIELD_COCKTAIL_ARMS_BASE["Y"], 0.72 + D_SORT_H4_ALL),
                (0.62 + D_SORT_H1_D, 0.92, 0.70 + D_SHIELD_COCKTAIL_ARMS_BASE["D"], 0.70 + D_SORT_H4_ALL),
            ],
            c1_allo=0.88, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89 + DC3_SHIELD_COCKTAIL, c3_bx=0.89 + DC3_SHIELD_COCKTAIL, c3_y=0.89 + DC3_SHIELD_COCKTAIL, c3_d=0.89 + DC3_SHIELD_COCKTAIL,
            h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
            l1_ref=l1_ref,
        ))

        l3b_strict_df = _run(
            "L3B_STACK_STRICT_100PCT_ZERO_DRUG",
            "UNSEQUENCED HYPOTHESIS (Strict 100% Zero-Drug, 0 R3B): EXP-028 S2c + 65um Bilayer + Future SHIELD Cocktail",
            "Tier-C_UNSEQUENCED_HYPOTHESIS",
            "ZERO_DRUG_100PCT",
            [
                (0.90, 0.78, 0.62 + D_SHIELD_COCKTAIL_ARMS_POST028["A"] + D_GUARD_H3_ARMS["A"], 0.72 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["A"]),
                (0.90, 0.79, 0.68 + D_SHIELD_COCKTAIL_ARMS_POST028["B"], 0.76 + D_SORT_H4_ALL),
                (0.90, 0.82, 0.78 + D_SHIELD_COCKTAIL_ARMS_POST028["X"] + D_GUARD_H3_ARMS["X"], 0.72 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["X"]),
                (0.90, 0.84, 0.80 + D_SHIELD_COCKTAIL_ARMS_POST028["Y"], 0.72 + D_SORT_H4_ALL),
                (0.62 + D_SORT_H1_D, 0.92, 0.70 + D_SHIELD_COCKTAIL_ARMS_POST028["D"], 0.70 + D_SORT_H4_ALL),
            ],
            c1_allo=0.90, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89 + DC3_SHIELD_COCKTAIL, c3_bx=0.89 + DC3_SHIELD_COCKTAIL, c3_y=0.89 + DC3_SHIELD_COCKTAIL, c3_d=0.89 + DC3_SHIELD_COCKTAIL,
            h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
            l1_ref=l1_ref,
            return_state_laws=(abs(phi_c - 0.25) < 1e-9),
        )
        strict_rows.append(l3b_strict_df)

        def _build_strict_l3b_plus_reset(
            layer_id: str, label: str, omega: float, tier: str, ae_penalized: bool = False, return_laws: bool = False
        ) -> dict[str, Any]:
            dc3_r = DC3_RESET_AE_DOWNSIDE if ae_penalized else DC3_RESET_CENTRAL
            dr_arms = D_RESET_ARMS_AE_DOWNSIDE if ae_penalized else D_RESET_ARMS_CENTRAL
            h4_cut = H4_AE_STEROID_HAIRCUT_NON_A if ae_penalized else 0.0
            c3j = subadditive_overlap(0.89, DC3_SHIELD_COCKTAIL, dc3_r, omega)
            res = _run(
                layer_id, label, tier,
                "TRACK_B_INELIGIBLE_UNDER_LOCKED_OPT1_DIAGNOSTIC_ZERO_GW2580_A_DRUG_FREE",
                [
                    (0.90, 0.78, 0.62 + D_SHIELD_COCKTAIL_ARMS_POST028["A"] + D_GUARD_H3_ARMS["A"], 0.72 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["A"]),
                    (0.90, 0.79, subadditive_overlap(0.68, D_SHIELD_COCKTAIL_ARMS_POST028["B"], dr_arms["B"], omega), 0.76 + D_SORT_H4_ALL + h4_cut),
                    (0.90, 0.82, subadditive_overlap(0.78 + D_GUARD_H3_ARMS["X"], D_SHIELD_COCKTAIL_ARMS_POST028["X"], dr_arms["X"], omega), 0.72 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["X"] + h4_cut),
                    (0.90, 0.84, subadditive_overlap(0.80, D_SHIELD_COCKTAIL_ARMS_POST028["Y"], dr_arms["Y"], omega), 0.72 + D_SORT_H4_ALL + h4_cut),
                    (0.62 + D_SORT_H1_D, 0.92, subadditive_overlap(0.70, D_SHIELD_COCKTAIL_ARMS_POST028["D"], dr_arms["D"], omega), 0.70 + D_SORT_H4_ALL + h4_cut),
                ],
                c1_allo=0.90, c2_inc=0.87, c2_y=0.87,
                c3_a=0.89 + DC3_SHIELD_COCKTAIL, c3_bx=c3j, c3_y=c3j, c3_d=c3j,
                h4_topology="TWO_PARADIGM_WU3", c4_univ=0.92,
                l1_ref=l1_ref,
                return_state_laws=return_laws,
            )
            res["overlap_damping_omega"] = omega
            res["c3_joint_exact"] = round(c3j, 6)
            return res

        for diag_row in (
            _build_strict_l3b_plus_reset(
                "L3B_STRICT_ZERODRUG_PLUS_RESET_OMEGA_0P60",
                "DIAGNOSTIC ONLY (Ineligible under Locked Option 1; 0.0000 pp EV weight): Strict Zero-Drug Cocktail + Reset (omega=0.60, 0 R3B)",
                0.60, "Tier-C_Cocktail_Plus_Tier-A_Ineligible_Diagnostic",
            ),
            _build_strict_l3b_plus_reset(
                "L3B_STRICT_ZERODRUG_PLUS_RESET_OMEGA_0P80",
                "DIAGNOSTIC ONLY (Ineligible under Locked Option 1; 0.0000 pp EV weight): Strict Zero-Drug Cocktail + Reset (omega=0.80, 0 R3B)",
                0.80, "Tier-C_Cocktail_Plus_Tier-A_Ineligible_Diagnostic",
            ),
            _build_strict_l3b_plus_reset(
                "L3B_STRICT_ZERODRUG_PLUS_RESET_OMEGA_1P00",
                "DIAGNOSTIC ONLY (Ineligible under Locked Option 1; 0.0000 pp EV weight): Strict Zero-Drug Cocktail + Reset (omega=1.00, 0 R3B)",
                1.00, "Tier-C_Cocktail_Plus_Tier-A_Ineligible_Diagnostic",
            ),
        ):
            diag_row["option1_eligible"] = False
            diag_row["policy_option1_ev_weight"] = 0.0
            diag_row["eligibility_note"] = "INELIGIBLE_UNDER_LOCKED_POLICY_OPTION_1_FULL_SHIELD_COCKTAIL_RECEIVES_ZERO_TRACKB_CREDIT"
            ineligible_full_cocktail_diag_rows.append(diag_row)

        strict_l3b_ae_with_laws = _build_strict_l3b_plus_reset(
            "L3B_STRICT_ZERODRUG_PLUS_AE_RESET_OMEGA_0P60",
            "DIAGNOSTIC ONLY (Ineligible under Locked Option 1; 0.0000 pp EV weight): Strict Zero-Drug Cocktail + AE-Penalized Reset (omega=0.60, 0 R3B)",
            0.60, "Tier-C_Cocktail_Plus_Tier-A_AE_Ineligible_Diagnostic",
            ae_penalized=True, return_laws=True,
        )
        strict_checkerboard = compute_checkerboard_stress_test(
            label=f"Strict_L3B_ZeroDrug_Plus_AE_Reset_phi{phi_c:.2f}",
            v_h123=strict_l3b_ae_with_laws.pop("_internal_v_h123"),
            dh4=strict_l3b_ae_with_laws.pop("_internal_dh4"),
            baseline_locked_exact=l3b_strict_df["locked_exact"],
            target_locked_exact=strict_l3b_ae_with_laws["locked_exact"],
            eps=0.003,
        )
        strict_l3b_ae_with_laws["option1_eligible"] = False
        strict_l3b_ae_with_laws["policy_option1_ev_weight"] = 0.0
        strict_l3b_ae_with_laws["eligibility_note"] = "INELIGIBLE_UNDER_LOCKED_POLICY_OPTION_1_FULL_SHIELD_COCKTAIL_RECEIVES_ZERO_TRACKB_CREDIT"
        ineligible_full_cocktail_diag_rows.append(strict_l3b_ae_with_laws)

        # =====================================================================
        # PART B: PARKED COUNTERFACTUAL R3B SENSITIVITY (EXP-029 GY-027 BLOCK!)
        # Segregated strictly from live-eligible headlines; masks R3B in strict
        # live-eligible fields (W_U3=57.5945%, W_U4=56.8730%).
        # =====================================================================
        for lid, lbl, tier, p3b, c4r3b, c4u in (
            ("L2B_EXP029_PREQUAL_D1_R3B_P50", "PARKED COUNTERFACTUAL (EXP-029 Pre-Qual): D1@R3B p_3B=0.50/c4_act=0.70, c4_univ=0.92 (NET HARM)", "PARKED_EXP029_GY027_BLOCK", 0.50, 0.70, 0.92),
            ("L2B_EXP029_POST_STAGE1_D1_R3B_P65", "PARKED COUNTERFACTUAL (EXP-029 Post-Stage-1): D1@R3B p_3B=0.65/c4_act=0.80, c4_univ=0.92", "PARKED_EXP029_GY027_BLOCK", 0.65, 0.80, 0.92),
            ("L2B_EXP029_POST_NHP_D1_R3B_P72", "PARKED COUNTERFACTUAL (EXP-029 Post-NHP): D1@R3B p_3B=0.72/c4_act=0.85, c4_univ=0.92", "PARKED_EXP029_GY027_BLOCK", 0.72, 0.85, 0.92),
            ("L2B_EXP029_SENS_C4U95_POST_NHP_P72", "PARKED COUNTERFACTUAL Upper Bound (EXP-029): D1@R3B p_3B=0.72/c4_act=0.85, c4_univ=0.95", "PARKED_EXP029_GY027_BLOCK_SENS", 0.72, 0.85, 0.95),
        ):
            parked_r3b_rows.append(_run(
                lid, lbl, tier,
                "PARKED_COUNTERFACTUAL_LOCAL_GW2580_UNREGISTERED_R3B",
                [
                    (0.88, 0.78, 0.57, 0.69),
                    (0.88, 0.79, 0.64, 0.70),
                    (0.88, 0.82, 0.73, 0.69),
                    (0.88, 0.84, 0.80, 0.72),
                    (0.62, 0.92, 0.70, p3b),
                ],
                c1_allo=0.88, c2_inc=0.87, c2_y=0.87,
                c3_a=0.89, c3_bx=0.89, c3_y=0.89, c3_d=0.89,
                h4_topology="THREE_PARADIGM_D1_ON_R3B",
                c4_univ=c4u, c4_r3b=c4r3b,
                l1_ref=l1_ref, check_4096=True,
            ))

        parked_r3b_rows.append(_run(
            "L3A_STACK_EXP028_029_FOUNDRY_V12",
            "PARKED COUNTERFACTUAL (w/ Blocked R3B): EXP-028 S2c + EXP-029 D1@R3B(c4u=92%) + Foundry v1.2",
            "PARKED_COUNTERFACTUAL_R3B_TIER_B",
            "PARKED_COUNTERFACTUAL_LOCAL_GW2580_UNREGISTERED_R3B",
            [
                (0.90, 0.78, 0.62 + D_SHIELD1_ARMS["A"] + D_GUARD_H3_ARMS["A"], 0.69 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["A"]),
                (0.90, 0.79, 0.68 + D_SHIELD1_ARMS["B"], 0.70 + D_SORT_H4_ALL),
                (0.90, 0.82, 0.78 + D_SHIELD1_ARMS["X"] + D_GUARD_H3_ARMS["X"], 0.69 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["X"]),
                (0.90, 0.84, 0.80 + D_SHIELD1_ARMS["Y"], 0.72 + D_SORT_H4_ALL),
                (0.62 + D_SORT_H1_D, 0.92, 0.70 + D_SHIELD1_ARMS["D"], 0.72 + D_SORT_H4_ALL),
            ],
            c1_allo=0.90, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89 + DC3_SHIELD1, c3_bx=0.89 + DC3_SHIELD1, c3_y=0.89 + DC3_SHIELD1, c3_d=0.89 + DC3_SHIELD1,
            h4_topology="THREE_PARADIGM_D1_ON_R3B", c4_univ=0.92, c4_r3b=0.85,
            l1_ref=l1_ref,
        ))

        for om, lid, lbl in (
            (0.60, "L3A_PLUS_FINITE_RESET_OMEGA_0P60", "PARKED COUNTERFACTUAL (w/ Blocked R3B): L3A + Reset (omega=0.60, A Drug-Free)"),
            (0.80, "L3A_PLUS_FINITE_RESET_OMEGA_0P80", "PARKED COUNTERFACTUAL (w/ Blocked R3B): L3A + Reset (omega=0.80, A Drug-Free)"),
        ):
            c3j = subadditive_overlap(0.89, DC3_SHIELD1, DC3_RESET_CENTRAL, om)
            res = _run(
                lid, lbl,
                "PARKED_COUNTERFACTUAL_R3B_TIER_B_PLUS_A",
                "PARKED_COUNTERFACTUAL_TRACK_B_UNREGISTERED_R3B",
                [
                    (0.90, 0.78, 0.62 + D_SHIELD1_ARMS["A"] + D_GUARD_H3_ARMS["A"], 0.69 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["A"]),
                    (0.90, 0.79, subadditive_overlap(0.68, D_SHIELD1_ARMS["B"], D_RESET_ARMS_CENTRAL["B"], om), 0.70 + D_SORT_H4_ALL),
                    (0.90, 0.82, subadditive_overlap(0.78 + D_GUARD_H3_ARMS["X"], D_SHIELD1_ARMS["X"], D_RESET_ARMS_CENTRAL["X"], om), 0.69 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["X"]),
                    (0.90, 0.84, subadditive_overlap(0.80, D_SHIELD1_ARMS["Y"], D_RESET_ARMS_CENTRAL["Y"], om), 0.72 + D_SORT_H4_ALL),
                    (0.62 + D_SORT_H1_D, 0.92, subadditive_overlap(0.70, D_SHIELD1_ARMS["D"], D_RESET_ARMS_CENTRAL["D"], om), 0.72 + D_SORT_H4_ALL),
                ],
                c1_allo=0.90, c2_inc=0.87, c2_y=0.87,
                c3_a=0.89 + DC3_SHIELD1, c3_bx=c3j, c3_y=c3j, c3_d=c3j,
                h4_topology="THREE_PARADIGM_D1_ON_R3B", c4_univ=0.92, c4_r3b=0.85,
                l1_ref=l1_ref,
            )
            res["overlap_damping_omega"] = om
            res["c3_joint_exact"] = round(c3j, 6)
            parked_r3b_rows.append(res)

        res_l3a_r3b_ae = _run(
            "L3A_PLUS_AE_PENALIZED_RESET_OMEGA_0P60",
            "PARKED COUNTERFACTUAL (w/ Blocked R3B): L3A + AE-Penalized Reset (omega=0.60, A Drug-Free)",
            "PARKED_COUNTERFACTUAL_R3B_TIER_B_PLUS_AE",
            "PARKED_COUNTERFACTUAL_TRACK_B_AE_UNREGISTERED_R3B",
            [
                (0.90, 0.78, 0.62 + D_SHIELD1_ARMS["A"] + D_GUARD_H3_ARMS["A"], 0.69 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["A"]),
                (0.90, 0.79, subadditive_overlap(0.68, D_SHIELD1_ARMS["B"], D_RESET_ARMS_AE_DOWNSIDE["B"], 0.60), 0.70 + D_SORT_H4_ALL + H4_AE_STEROID_HAIRCUT_NON_A),
                (0.90, 0.82, subadditive_overlap(0.78 + D_GUARD_H3_ARMS["X"], D_SHIELD1_ARMS["X"], D_RESET_ARMS_AE_DOWNSIDE["X"], 0.60), 0.69 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["X"] + H4_AE_STEROID_HAIRCUT_NON_A),
                (0.90, 0.84, subadditive_overlap(0.80, D_SHIELD1_ARMS["Y"], D_RESET_ARMS_AE_DOWNSIDE["Y"], 0.60), 0.72 + D_SORT_H4_ALL + H4_AE_STEROID_HAIRCUT_NON_A),
                (0.62 + D_SORT_H1_D, 0.92, subadditive_overlap(0.70, D_SHIELD1_ARMS["D"], D_RESET_ARMS_AE_DOWNSIDE["D"], 0.60), 0.72 + D_SORT_H4_ALL + H4_AE_STEROID_HAIRCUT_NON_A),
            ],
            c1_allo=0.90, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89 + DC3_SHIELD1, c3_bx=c3j_s1_ae, c3_y=c3j_s1_ae, c3_d=c3j_s1_ae,
            h4_topology="THREE_PARADIGM_D1_ON_R3B", c4_univ=0.92, c4_r3b=0.85,
            l1_ref=l1_ref,
        )
        res_l3a_r3b_ae["overlap_damping_omega"] = 0.60
        res_l3a_r3b_ae["c3_joint_exact"] = round(c3j_s1_ae, 6)
        parked_r3b_rows.append(res_l3a_r3b_ae)

        l3b_r3b_stack = _run(
            "L3B_STACK_EXP028_029_FOUNDRY_COCKTAIL",
            "PARKED COUNTERFACTUAL (w/ Blocked R3B): EXP-028 S2c + EXP-029 D1@R3B(c4u=92%) + Future SHIELD Cocktail",
            "PARKED_COUNTERFACTUAL_R3B_TIER_C",
            "PARKED_COUNTERFACTUAL_LOCAL_GW2580_UNREGISTERED_R3B",
            [
                (0.90, 0.78, 0.62 + D_SHIELD_COCKTAIL_ARMS_POST028["A"] + D_GUARD_H3_ARMS["A"], 0.69 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["A"]),
                (0.90, 0.79, 0.68 + D_SHIELD_COCKTAIL_ARMS_POST028["B"], 0.70 + D_SORT_H4_ALL),
                (0.90, 0.82, 0.78 + D_SHIELD_COCKTAIL_ARMS_POST028["X"] + D_GUARD_H3_ARMS["X"], 0.69 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["X"]),
                (0.90, 0.84, 0.80 + D_SHIELD_COCKTAIL_ARMS_POST028["Y"], 0.72 + D_SORT_H4_ALL),
                (0.62 + D_SORT_H1_D, 0.92, 0.70 + D_SHIELD_COCKTAIL_ARMS_POST028["D"], 0.72 + D_SORT_H4_ALL),
            ],
            c1_allo=0.90, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89 + DC3_SHIELD_COCKTAIL, c3_bx=0.89 + DC3_SHIELD_COCKTAIL, c3_y=0.89 + DC3_SHIELD_COCKTAIL, c3_d=0.89 + DC3_SHIELD_COCKTAIL,
            h4_topology="THREE_PARADIGM_D1_ON_R3B", c4_univ=0.92, c4_r3b=0.85,
            l1_ref=l1_ref,
        )
        parked_r3b_rows.append(l3b_r3b_stack)

        def _build_l4_parked(
            layer_id: str, label: str, omega: float, tier: str, ae_penalized: bool = False, return_laws: bool = False
        ) -> dict[str, Any]:
            dc3_r = DC3_RESET_AE_DOWNSIDE if ae_penalized else DC3_RESET_CENTRAL
            dr_arms = D_RESET_ARMS_AE_DOWNSIDE if ae_penalized else D_RESET_ARMS_CENTRAL
            h4_cut = H4_AE_STEROID_HAIRCUT_NON_A if ae_penalized else 0.0
            c3j = subadditive_overlap(0.89, DC3_SHIELD_COCKTAIL, dc3_r, omega)
            res = _run(
                layer_id, label, tier,
                "PARKED_COUNTERFACTUAL_ALL_IN_TRACK_B_UNREGISTERED_R3B",
                [
                    (0.90, 0.78, 0.62 + D_SHIELD_COCKTAIL_ARMS_POST028["A"] + D_GUARD_H3_ARMS["A"], 0.69 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["A"]),
                    (0.90, 0.79, subadditive_overlap(0.68, D_SHIELD_COCKTAIL_ARMS_POST028["B"], dr_arms["B"], omega), 0.70 + D_SORT_H4_ALL + h4_cut),
                    (0.90, 0.82, subadditive_overlap(0.78 + D_GUARD_H3_ARMS["X"], D_SHIELD_COCKTAIL_ARMS_POST028["X"], dr_arms["X"], omega), 0.69 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["X"] + h4_cut),
                    (0.90, 0.84, subadditive_overlap(0.80, D_SHIELD_COCKTAIL_ARMS_POST028["Y"], dr_arms["Y"], omega), 0.72 + D_SORT_H4_ALL + h4_cut),
                    (0.62 + D_SORT_H1_D, 0.92, subadditive_overlap(0.70, D_SHIELD_COCKTAIL_ARMS_POST028["D"], dr_arms["D"], omega), 0.72 + D_SORT_H4_ALL + h4_cut),
                ],
                c1_allo=0.90, c2_inc=0.87, c2_y=0.87,
                c3_a=0.89 + DC3_SHIELD_COCKTAIL, c3_bx=c3j, c3_y=c3j, c3_d=c3j,
                h4_topology="THREE_PARADIGM_D1_ON_R3B", c4_univ=0.92, c4_r3b=0.85,
                l1_ref=l1_ref,
                return_state_laws=return_laws,
            )
            res["overlap_damping_omega"] = omega
            res["c3_joint_exact"] = round(c3j, 6)
            return res

        parked_r3b_rows.append(_build_l4_parked(
            "L4_ALL_IN_OVERLAP_DAMPED_OMEGA_0P60",
            "PARKED COUNTERFACTUAL (w/ Blocked R3B): All-In Cocktail + Reset (omega=0.60, A Drug-Free)",
            0.60, "PARKED_COUNTERFACTUAL_R3B_TIER_C_PLUS_A",
        ))
        parked_r3b_rows.append(_build_l4_parked(
            "L4_SENS_HARSH_OVERLAP_OMEGA_0P80",
            "PARKED COUNTERFACTUAL (w/ Blocked R3B): Harsh Overlap (omega=0.80)",
            0.80, "PARKED_COUNTERFACTUAL_R3B_TIER_C_PLUS_A",
        ))
        parked_r3b_rows.append(_build_l4_parked(
            "L4_SENS_COMPLETE_OVERLAP_OMEGA_1P00",
            "PARKED COUNTERFACTUAL (w/ Blocked R3B): Complete Redundancy (omega=1.00)",
            1.00, "PARKED_COUNTERFACTUAL_R3B_TIER_C_PLUS_A",
        ))
        l4_ae_with_laws = _build_l4_parked(
            "L4_AE_PENALIZED_ALL_IN_OMEGA_0P60",
            "PARKED COUNTERFACTUAL (w/ Blocked R3B): AE-Penalized All-In (omega=0.60, -1.5pp H4)",
            0.60, "PARKED_COUNTERFACTUAL_R3B_TIER_C_PLUS_AE",
            ae_penalized=True, return_laws=True,
        )
        l4_ae_checkerboard = compute_checkerboard_stress_test(
            label=f"Parked_R3B_L4_AE_phi{phi_c:.2f}",
            v_h123=l4_ae_with_laws.pop("_internal_v_h123"),
            dh4=l4_ae_with_laws.pop("_internal_dh4"),
            baseline_locked_exact=l3b_r3b_stack["counterfactual_if_r3b_registered_locked_exact"],
            target_locked_exact=l4_ae_with_laws["counterfactual_if_r3b_registered_locked_exact"],
            eps=0.003,
        )
        parked_r3b_rows.append(l4_ae_with_laws)

        c3_naive = 0.89 + DC3_SHIELD_COCKTAIL + DC3_RESET_CENTRAL
        parked_r3b_rows.append(_run(
            "L4_FORBIDDEN_NAIVE_LINEAR_DOUBLE_COUNT_DIAGNOSTIC",
            "DIAGNOSTIC ONLY (FORBIDDEN): Naive Linear H3 Addition Without Overlap Damping (c3=96.5%)",
            "DIAGNOSTIC_FORBIDDEN_COUNTEREXAMPLE",
            "FORBIDDEN_DOUBLE_COUNT_COUNTEREXAMPLE",
            [
                (0.90, 0.78, 0.62 + D_SHIELD_COCKTAIL_ARMS_POST028["A"] + D_GUARD_H3_ARMS["A"], 0.69 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["A"]),
                (0.90, 0.79, 0.68 + D_SHIELD_COCKTAIL_ARMS_POST028["B"] + D_RESET_ARMS_CENTRAL["B"], 0.70 + D_SORT_H4_ALL),
                (0.90, 0.82, 0.78 + D_GUARD_H3_ARMS["X"] + D_SHIELD_COCKTAIL_ARMS_POST028["X"] + D_RESET_ARMS_CENTRAL["X"], 0.69 + D_SORT_H4_ALL + D_GUARD_H4_ARMS["X"]),
                (0.90, 0.84, 0.80 + D_SHIELD_COCKTAIL_ARMS_POST028["Y"] + D_RESET_ARMS_CENTRAL["Y"], 0.72 + D_SORT_H4_ALL),
                (0.62 + D_SORT_H1_D, 0.92, 0.70 + D_SHIELD_COCKTAIL_ARMS_POST028["D"] + D_RESET_ARMS_CENTRAL["D"], 0.72 + D_SORT_H4_ALL),
            ],
            c1_allo=0.90, c2_inc=0.87, c2_y=0.87,
            c3_a=0.89 + DC3_SHIELD_COCKTAIL, c3_bx=c3_naive, c3_y=c3_naive, c3_d=c3_naive,
            h4_topology="THREE_PARADIGM_D1_ON_R3B", c4_univ=0.92, c4_r3b=0.85,
            l1_ref=l1_ref,
        ))

        # Full omega sweep {0.00, 0.25, 0.50, 0.60, 0.80, 1.00} on BOTH Strict Zero-Drug and Parked R3B
        # Explicitly flags omega <= 0.5510204 as exceeding the c3 < 0.94 budget cap!
        omega_budget_min = 1.0 - (0.94 - (0.89 + DC3_RESET_CENTRAL)) / (
            DC3_SHIELD_COCKTAIL * (1.0 - DC3_RESET_CENTRAL / (1.0 - 0.89))
        )
        omega_sweep_strict: dict[str, Any] = {"min_omega_for_c3_lt_0p94": round(omega_budget_min, 7)}
        omega_sweep_parked_r3b: dict[str, Any] = {"min_omega_for_c3_lt_0p94": round(omega_budget_min, 7)}
        for om in (0.00, 0.25, 0.50, 0.60, 0.80, 1.00):
            rs = _build_strict_l3b_plus_reset(f"OMEGA_STRICT_{om:.2f}", f"Strict Omega={om:.2f}", om, "SWEEP")
            rp = _build_l4_parked(f"OMEGA_R3B_{om:.2f}", f"Parked R3B Omega={om:.2f}", om, "SWEEP")
            exceeds_cap = rs["c3_joint_exact"] >= 0.94
            omega_sweep_strict[f"omega_{om:.2f}"] = {
                "c3_joint": rs["c3_joint_exact"],
                "exceeds_c3_0p94_channel_budget_cap": exceeds_cap,
                "budget_status": "OUTSIDE_C3_0P94_BUDGET_CAP_EXPLORATORY" if exceeds_cap else "WITHIN_C3_0P94_BUDGET_CAP",
                "locked_pct": rs["locked_pct"],
                "mod100_pct": rs["modular_k100_pct"],
                "delta_vs_L3B_strict_locked_pp": round(100.0 * (rs["locked_exact"] - l3b_strict_df["locked_exact"]), 4),
                "delta_vs_L3B_strict_mod100_pp": round(100.0 * (rs["modular_k100_exact"] - l3b_strict_df["modular_k100_exact"]), 4),
            }
            omega_sweep_parked_r3b[f"omega_{om:.2f}"] = {
                "c3_joint": rp["c3_joint_exact"],
                "exceeds_c3_0p94_channel_budget_cap": exceeds_cap,
                "budget_status": "OUTSIDE_C3_0P94_BUDGET_CAP_EXPLORATORY" if exceeds_cap else "WITHIN_C3_0P94_BUDGET_CAP",
                "strict_live_eligible_locked_pct": rp["strict_live_eligible_locked_pct"],
                "counterfactual_if_r3b_registered_locked_pct": rp["counterfactual_if_r3b_registered_locked_pct"],
                "counterfactual_if_r3b_registered_mod100_pct": rp["counterfactual_if_r3b_registered_mod100_pct"],
                "delta_vs_L3B_parked_r3b_locked_pp": round(
                    100.0 * (rp["counterfactual_if_r3b_registered_locked_exact"] - l3b_r3b_stack["counterfactual_if_r3b_registered_locked_exact"]),
                    4,
                ),
            }

        _reset_alone_ids = frozenset({
            "L2C_EXP030_FINITE_RESET",
            "L2C_SENS_FINITE_RESET_CONSERVATIVE_C3_0P92",
            "L2C_AE_PENALIZED_FINITE_RESET",
        })
        for row in strict_rows:
            lid = row["layer_id"]
            is_trackb_row = "TRACK_B" in str(row.get("drug_status", ""))
            if lid in _reset_alone_ids:
                row["option1_eligible"] = False
                row["option1_branch_structurally_eligible"] = False
                row["live_activated_today"] = False
                row["scenario_activation_status"] = "PENDING_SHIELD_DISPOSITION_AND_OWNER_REAUTH"
                row["eligibility_note"] = (
                    "STANDALONE_RESET_SENSITIVITY_ONLY_NO_SERIALIZED_SHIELD_DISPOSITION_NOT_OPTION1_ACTIVE"
                )
            elif is_trackb_row:
                row["option1_eligible"] = False
                row["option1_branch_structurally_eligible"] = True
                row["live_activated_today"] = False
                row["scenario_activation_status"] = "CONDITIONAL_SCENARIO_PENDING_XREACT_PASS_AND_OWNER_REAUTH"
                row["eligibility_note"] = (
                    "CONDITIONAL_TRACKB_BRANCH_INACTIVE_TODAY_REQUIRES_WORST_LOT_XREACT_PASS_AND_OWNER_REAUTH"
                )
            else:
                row["option1_eligible"] = True
                row["option1_branch_structurally_eligible"] = True
                row["live_activated_today"] = (lid in ("L1_LIVE_5ARM_WU3", "L1_LIVE_5ARM_WU4"))
                row["scenario_activation_status"] = "TRACK_A_ZERO_DRUG_ELIGIBLE"
        for row in ineligible_full_cocktail_diag_rows:
            row["option1_branch_structurally_eligible"] = False
            row["live_activated_today"] = False
            row["scenario_activation_status"] = "INELIGIBLE_FULL_COCKTAIL_BRANCH_ZERO_TRACKB_CREDIT"
        for row in parked_r3b_rows:
            row["option1_eligible"] = False
            row["option1_branch_structurally_eligible"] = False
            row["live_activated_today"] = False
            row["scenario_activation_status"] = "PARKED_COUNTERFACTUAL_UNREGISTERED_R3B_GY027_BLOCK"

        bpr05_5arm_sensitivities: dict[str, Any] = {}
        for row in strict_rows:
            if "_internal_v_h123" in row:
                bpr05_5arm_sensitivities[row["layer_id"]] = compute_bpr05_dependence_sensitivity_bounds(
                    scenario_id=row["layer_id"],
                    arms=row.pop("_internal_arms"),
                    dists=row.pop("_internal_dists"),
                    v_h123=row.pop("_internal_v_h123"),
                    routes=row.pop("_internal_routes"),
                    compat_map=compat_strict_live,
                    cell_classes=row.pop("_internal_cell_classes"),
                    preserve_incumbent_3arm_joint_history=True,
                )
                row.pop("_internal_dh4", None)
        for row in ineligible_full_cocktail_diag_rows:
            for _k in ("_internal_v_h123", "_internal_dh4", "_internal_dists", "_internal_arms", "_internal_routes", "_internal_cell_classes"):
                row.pop(_k, None)
        for row in parked_r3b_rows:
            for _k in ("_internal_v_h123", "_internal_dh4", "_internal_dists", "_internal_arms", "_internal_routes", "_internal_cell_classes"):
                row.pop(_k, None)

        return {
            "strict_rows": strict_rows,
            "ineligible_full_cocktail_diag_rows": ineligible_full_cocktail_diag_rows,
            "parked_r3b_rows": parked_r3b_rows,
            "omega_sweep_strict": omega_sweep_strict,
            "omega_sweep_parked_r3b": omega_sweep_parked_r3b,
            "checkerboard_strict_l3b_ae": strict_checkerboard,
            "checkerboard_parked_l4_ae": l4_ae_checkerboard,
            "bpr05_5arm_sensitivities": bpr05_5arm_sensitivities,
        }

    def verify_shipped_and_cross_track_parity(
        l0: dict[str, Any],
        strict_25: list[dict[str, Any]],
        strict_50: list[dict[str, Any]],
        parked_25: list[dict[str, Any]],
        parked_50: list[dict[str, Any]],
    ) -> dict[str, Any]:
        # 1. Shipped IIP-0035 parity across ALL 6 R3P-topology scenarios (L0 + W_U1, W_U2, W_U3, W_U4, W_U6 = 24 scalars!)
        # Pin canonical IIP-0035 SHA-256 BY DEFAULT (fail closed on any byte alteration unless explicit --allow-unpinned-diagnostic)!
        shipped_path = openislet_root / "data" / "extracted" / "islet1_5arm_autologous_portfolio_v0.8.0.json"
        effective_shipped_sha = (
            None
            if allow_unpinned_diagnostic
            else (expected_shipped_sha256 if expected_shipped_sha256 is not None else CANONICAL_SHIPPED_IIP0035_SHA256)
        )
        shipped, shipped_sha256, shipped_bytes = load_verified_json_fixture(
            shipped_path,
            "shipped IIP-0035 portfolio fixture",
            expected_sha256=effective_shipped_sha,
        )
        by_sc = {r["scenario"]: r for r in shipped["stage0_gated_5arm_unified_waveBC_portfolio"]}

        l0_inv = shipped["live_3x2_baseline_invariant"]
        scalar_checks: dict[str, tuple[float, float]] = {
            "L0_locked": (
                require_finite_number(l0["locked_pct"], "computed L0_locked"),
                round(require_finite_number(l0_inv["locked_pct"], "shipped L0_locked"), 4),
            ),
            "L0_mod100": (
                require_finite_number(l0["modular_k100_pct"], "computed L0_mod100"),
                round(require_finite_number(l0_inv["modular_k100_pct"], "shipped L0_mod100"), 4),
            ),
            "L0_mod90": (
                require_finite_number(l0["modular_k90_pct"], "computed L0_mod90"),
                round(require_finite_number(l0_inv["modular_k90_pct"], "shipped L0_mod90"), 4),
            ),
            "L0_ceiling": (
                require_finite_number(l0["composite_ceiling_pct"], "computed L0_ceiling"),
                round(require_finite_number(l0_inv["shared_ceiling_pct"], "shipped L0_ceiling"), 4),
            ),
        }
        for sn in (
            "W_U1_5Arm_ZeroH3Lift_Y@3P_D1(p1=0.70)@3P_c4u0.92_phiYX0.75_25",
            "W_U2_5Arm_ZeroH3Lift_Y@3P_D1(p1=0.70)@3P_c4u0.92_phiYX0.75_50",
            "W_U3_5Arm_ZeroH3Lift_Y@3P_D1(p1=0.62)@3P_c4u0.92_phiYX0.75_25",
            "W_U4_5Arm_ZeroH3Lift_Y@3P_D1(p1=0.62)@3P_c4u0.92_phiYX0.75_50",
            "W_U6_5Arm_ZeroH3Lift_Y@3P_D1(p1=0.62)@3P_c4u0.90_phiYX1.00_50",
        ):
            sc = by_sc[sn]
            phi_c = 0.25 if sn.endswith("_25") else 0.50
            p_d1 = 0.70 if "p1=0.70" in sn else 0.62
            phi_yx = 1.00 if "phiYX1.00" in sn else 0.75
            c4_u = 0.90 if "c4u0.90" in sn else 0.92
            arms = [
                (0.88, 0.78, 0.57, 0.69),
                (0.88, 0.79, 0.64, 0.70),
                (0.88, 0.82, 0.73, 0.69),
                (0.88, 0.84, 0.80, 0.72),
                (p_d1, 0.92, 0.70, 0.70),
            ]
            d1, c1e = build_h1_dist_5arm(0.88, p_d1)
            d2, c2e = build_h2_dist_5arm(0.78, 0.79, 0.82, 0.84, 0.92, c2_inc=0.87, c2_y=0.87, c2_univ=0.95, c2_auto=0.93, phi_yx=phi_yx, phi_c=phi_c)
            d3, c3e = build_h3_dist_5arm(0.57, 0.64, 0.73, 0.80, 0.70, c3_a=0.89, c3_bx=0.89, c3_y=0.89, c3_d=0.89, phi_yx=phi_yx, phi_c=phi_c)
            d4, c4e, rts = build_h4_dist_5arm(0.69, 0.70, 0.69, 0.72, 0.70, h4_topology="TWO_PARADIGM_WU3", c4_univ=c4_u, phi_c=phi_c)
            res = evaluate_5arm_exact_2pow20(
                layer_id=sn[:4], label=sn, epistemic_tier="SHIPPED", drug_status="ZERO_DRUG",
                arms=arms, dists=[d1, d2, d3, d4], eff_ceils=[c1e, c2e, c3e, c4e],
                routes=rts, compat_counterfactual=None, compat_hypo_transfer=None, cell_classes=std_classes,
                l0_locked=l0["locked_exact"], l0_mod100=l0["modular_k100_exact"],
                l1_locked=0.0, l1_mod100=0.0, check_4096_incumbent_parity=True,
            )
            tag = sn.split("_")[0] + "_" + sn.split("_")[1]
            scalar_checks[f"{tag}_locked"] = (
                require_finite_number(res["locked_pct"], f"computed {tag}_locked"),
                require_finite_number(sc["locked_pct"], f"shipped {tag}_locked"),
            )
            scalar_checks[f"{tag}_mod100"] = (
                require_finite_number(res["modular_k100_pct"], f"computed {tag}_mod100"),
                require_finite_number(sc["modular_k100_pct"], f"shipped {tag}_mod100"),
            )
            scalar_checks[f"{tag}_mod90"] = (
                require_finite_number(res["modular_k90_pct"], f"computed {tag}_mod90"),
                require_finite_number(sc["modular_k90_pct"], f"shipped {tag}_mod90"),
            )
            scalar_checks[f"{tag}_ceiling"] = (
                require_finite_number(res["composite_ceiling_pct"], f"computed {tag}_ceiling"),
                require_finite_number(sc["composite_ceiling_pct"], f"shipped {tag}_ceiling"),
            )

        for k, (got, exp) in scalar_checks.items():
            g_val = require_finite_number(got, f"scalar_checks[{k}].got")
            e_val = require_finite_number(exp, f"scalar_checks[{k}].exp")
            diff = abs(g_val - e_val)
            if not math.isfinite(diff) or diff > 1e-12:
                raise RuntimeError(f"Shipped parity mismatch on {k}: got={g_val} vs exp={e_val}")

        by25_s = {r["layer_id"]: r for r in strict_25}
        by50_s = {r["layer_id"]: r for r in strict_50}
        by25_p = {r["layer_id"]: r for r in parked_25}
        by50_p = {r["layer_id"]: r for r in parked_50}

        parity_out: dict[str, Any] = {
            "parity_mode": "STANDALONE_LIVE_IIP0035_ONLY" if standalone else "FULL_CROSS_TRACK_FAIL_CLOSED",
            "parity_tolerance_policy": "numeric_tolerance_le_1e-12_across_cpython_builds",
            "non_finite_input_guard": "STRICT_FAIL_CLOSED_DECODER_DUPLICATE_KEY_NONFINITE_AND_OVERFLOW_GUARD",
            "shipped_fixture_sha256": shipped_sha256,
            "shipped_fixture_bytes": shipped_bytes,
            "shipped_sha256_computed_before_parity_check": True,
            "shipped_pinned_sha256_verified": effective_shipped_sha is not None,
            "shipped_pinned_sha256_expected": effective_shipped_sha,
            "diagnostic_unpinned_mode": allow_unpinned_diagnostic,
            "shipped_parity_scope": (
                "24 scalar parity checks across 6 R3P-topology shipped scenarios (L0, W_U1, W_U2, W_U3, W_U4, W_U6 x 4 metrics; "
                "compared at shipped 4-dp display precision plus unrounded L0 live parity <= 5e-9) + full 4,096-state incumbent "
                "marginalization parity <= 1e-12. Separate IIP-0035 route-placement stress scenarios W_U5/W_U7/W_U8/W_U9 (D1@R2) "
                "and W_U10..W_U12 (Y@Hyb3P) lie outside the W_U3/W_U4 crosswalk base."
            ),
            "all_24_shipped_scalar_parity_checks_passed": True,
            "l0_live_unrounded_max_abs_err": l0["parity_err_vs_rank_islet1_stacks"],
            "l1_phi25_4096_state_max_abs_err": by25_s["L1_LIVE_5ARM_WU3"]["incumbent_4096_state_max_abs_err"],
            "l1_phi50_4096_state_max_abs_err": by50_s["L1_LIVE_5ARM_WU4"]["incumbent_4096_state_max_abs_err"],
            "shipped_verified_pairs": {
                k: {"computed": g, "shipped_iip0035": e, "abs_diff": abs(g - e)} for k, (g, e) in scalar_checks.items()
            },
        }

        if standalone:
            parity_out["cross_track_parity_status"] = "SKIPPED_BY_EXPLICIT_STANDALONE_FLAG"
            parity_out["all_requested_checks_passed"] = True
            return parity_out

        # FAIL-CLOSED Cross-Track Verification (EXP-028 + archived/parked EXP-029)
        ct_root = cross_track_dir.expanduser().resolve() if cross_track_dir else EXP_ROOT
        exp028_path = (
            ct_root / "EXP-028-clinical-h1-reanchor-abx-cd64t-cr1-il1rn-siglec" / "artifacts-carbon" / "exp028_verification_receipt.json"
        )
        exp029_path = (
            ct_root / "EXP-029-active-oxygen-ieog-chronic-gw2580-antifibrosis" / "artifacts-carbon" / "exp029_verification_receipt.json"
        )
        # Load, hash-verify, and strictly reject non-finite values BEFORE parity comparisons!
        r28, exp028_sha256, exp028_bytes = load_verified_json_fixture(
            exp028_path,
            "EXP-028 receipt",
            expected_sha256=expected_exp028_sha256,
        )
        r29, exp029_sha256, exp029_bytes = load_verified_json_fixture(
            exp029_path,
            "archived EXP-029 receipt",
            expected_sha256=expected_exp029_sha256,
        )

        # EXP-028 unrounded parity
        sc28 = {
            x["scenario"]: x
            for x in r28["part_d_oq016_portfolio_odds"]["five_arm_2pow20_registered_route_only_scenarios"]
        }
        pairs28 = [
            ("phi25_S2a", by25_s["L2A_EXP028_S2a_H1_90_ZERO_H3_LIFT"], sc28["W_U3_phi0p25__S2a_H1_90_ABX_CD64t_IL1RN_Fix_ZeroH3Lift_D1bHeld62"]),
            ("phi25_S2c", by25_s["L2A_EXP028_S2c_CONDITIONAL_STAGE0"], sc28["W_U3_phi0p25__S2c_H1_90_ABX_CD64t_IL1RN_ConditionalStage0_p3_62_68_78"]),
            ("phi50_S2a", by50_s["L2A_EXP028_S2a_H1_90_ZERO_H3_LIFT"], sc28["W_U4_phi0p50__S2a_H1_90_ABX_CD64t_IL1RN_Fix_ZeroH3Lift_D1bHeld62"]),
            ("phi50_S2c", by50_s["L2A_EXP028_S2c_CONDITIONAL_STAGE0"], sc28["W_U4_phi0p50__S2c_H1_90_ABX_CD64t_IL1RN_ConditionalStage0_p3_62_68_78"]),
        ]
        exp028_checks: dict[str, Any] = {}
        max_err_028 = 0.0
        for tag, mine, ref in pairs28:
            el = abs(
                require_finite_number(mine["locked_exact"], f"EXP-028 mine {tag}.locked_exact")
                - require_finite_number(ref["locked_exact"], f"EXP-028 ref {tag}.locked_exact")
            )
            em = abs(
                require_finite_number(mine["modular_k100_exact"], f"EXP-028 mine {tag}.modular_k100_exact")
                - require_finite_number(ref["modular_k100_exact"], f"EXP-028 ref {tag}.modular_k100_exact")
            )
            ec = abs(
                require_finite_number(mine["ceiling_exact"], f"EXP-028 mine {tag}.ceiling_exact")
                - require_finite_number(ref["ceiling_exact"], f"EXP-028 ref {tag}.ceiling_exact")
            )
            mx = max(el, em, ec)
            if not math.isfinite(mx) or mx > 1e-12:
                raise RuntimeError(f"EXP-028 unrounded parity failed on {tag}: max_err={mx}")
            if mx > max_err_028:
                max_err_028 = mx
            exp028_checks[tag] = {
                "locked_pct": mine["locked_pct"],
                "mod100_pct": mine["modular_k100_pct"],
                "ceiling_pct": mine["composite_ceiling_pct"],
                "unrounded_max_abs_err": mx,
            }
        if len(exp028_checks) != 4:
            raise RuntimeError("Incomplete EXP-028 parity scenario set")

        # Archived/Parked EXP-029 parity:
        #   - Checks EVERY metric independently against upstream raw unrounded floats when present
        #     (e.g. locked_hypothetical_r3b_registered_raw <= 1e-12) AND against 4-dp display fields.
        #   - NEVER fills a missing upstream raw field (e.g. composite_ceiling_exact) from mine[...];
        #     any absent raw field is explicitly marked UNVERIFIED_UPSTREAM_RAW_FIELD_ABSENT!
        p6 = r29["part6_exact_2pow20_portfolio_odds"]
        sc29 = {
            x["scenario"]: x
            for x in (
                p6["primary_apples_to_apples_c4u_0p92_scenarios"]
                + p6["sensitivity_upper_bound_c4u_lift_0p94_0p95_scenarios"]
            )
        }
        pairs29 = [
            ("phi25_PreQual_c4u92", by25_p["L2B_EXP029_PREQUAL_D1_R3B_P50"], sc29["W_U3_D1_ON_R3B_PreQual_Harsh_c4u92_phi25"]),
            ("phi25_PostStage1_c4u92", by25_p["L2B_EXP029_POST_STAGE1_D1_R3B_P65"], sc29["W_U3_D1_ON_R3B_PostStage1_Qual_c4u92_phi25"]),
            ("phi25_PostNHP_c4u92", by25_p["L2B_EXP029_POST_NHP_D1_R3B_P72"], sc29["W_U3_D1_ON_R3B_PostNHP_Target_c4u92_phi25"]),
            ("phi25_PostNHP_SENS_c4u95", by25_p["L2B_EXP029_SENS_C4U95_POST_NHP_P72"], sc29["W_U3_D1_ON_R3B_PostNHP_Target_SENS_c4u95_phi25"]),
            ("phi50_PreQual_c4u92", by50_p["L2B_EXP029_PREQUAL_D1_R3B_P50"], sc29["W_U4_D1_ON_R3B_PreQual_Harsh_c4u92_phi50"]),
            ("phi50_PostStage1_c4u92", by50_p["L2B_EXP029_POST_STAGE1_D1_R3B_P65"], sc29["W_U4_D1_ON_R3B_PostStage1_Qual_c4u92_phi50"]),
            ("phi50_PostNHP_c4u92", by50_p["L2B_EXP029_POST_NHP_D1_R3B_P72"], sc29["W_U4_D1_ON_R3B_PostNHP_Target_c4u92_phi50"]),
            ("phi50_PostNHP_SENS_c4u95", by50_p["L2B_EXP029_SENS_C4U95_POST_NHP_P72"], sc29["W_U4_D1_ON_R3B_PostNHP_Target_SENS_c4u95_phi50"]),
        ]
        exp029_metric_specs = (
            (
                "locked_hypothetical_r3b_registered",
                "counterfactual_if_r3b_registered_locked_exact",
                "counterfactual_if_r3b_registered_locked_pct",
                ("locked_hypothetical_r3b_registered_raw", "locked_hypothetical_r3b_registered_exact"),
                "locked_hypothetical_r3b_registered_pct",
            ),
            (
                "modular_hypothetical_r3b_registered_k100",
                "counterfactual_if_r3b_registered_mod100_exact",
                "counterfactual_if_r3b_registered_mod100_pct",
                ("modular_hypothetical_r3b_registered_k100_raw", "modular_hypothetical_r3b_registered_k100_exact"),
                "modular_hypothetical_r3b_registered_k100_pct",
            ),
            (
                "modular_hypo_only_transfer_k100",
                "counterfactual_hypo_transfer_k100_exact",
                "counterfactual_hypo_transfer_k100_pct",
                ("modular_hypo_only_transfer_k100_raw", "modular_hypo_only_transfer_k100_exact"),
                "modular_hypo_only_transfer_k100_pct",
            ),
            (
                "strict_live_iip0035_registered_only",
                "strict_live_eligible_locked_exact",
                "strict_live_eligible_locked_pct",
                (
                    "locked_strict_live_iip0035_registered_only_raw",
                    "strict_live_iip0035_registered_only_raw",
                    "strict_live_iip0035_registered_only_exact",
                ),
                "locked_strict_live_iip0035_registered_only_pct",
            ),
            (
                "composite_ceiling",
                "ceiling_exact",
                "composite_ceiling_pct",
                ("composite_ceiling_raw", "composite_ceiling_exact", "ceiling_raw", "ceiling_exact"),
                "composite_ceiling_pct",
            ),
        )
        exp029_checks: dict[str, Any] = {}
        max_display_diff_029 = 0.0
        max_raw_err_029: float | None = None
        raw_metrics_verified: set[str] = set()
        raw_metrics_absent: set[str] = set()
        for tag, mine, ref in pairs29:
            sc_display_max = 0.0
            sc_raw_max: float | None = None
            metric_audit: dict[str, Any] = {}
            for m_name, mine_ex_k, mine_pct_k, ref_raw_candidates, ref_pct_k in exp029_metric_specs:
                mine_pct = require_finite_number(mine[mine_pct_k], f"EXP-029 mine {tag}.{mine_pct_k}")
                ref_pct = require_finite_number(ref[ref_pct_k], f"EXP-029 ref {tag}.{ref_pct_k}")
                d_pct = abs(mine_pct - ref_pct)
                if not math.isfinite(d_pct) or d_pct > 1e-12:
                    raise RuntimeError(
                        f"Archived EXP-029 4-dp display parity failed on {tag}.{m_name}: got={mine_pct} vs ref={ref_pct}"
                    )
                if d_pct > sc_display_max:
                    sc_display_max = d_pct
                if d_pct > max_display_diff_029:
                    max_display_diff_029 = d_pct

                matched_raw_key = next((rk for rk in ref_raw_candidates if rk in ref), None)
                if matched_raw_key is not None:
                    mine_ex = require_finite_number(mine[mine_ex_k], f"EXP-029 mine {tag}.{mine_ex_k}")
                    ref_raw = require_finite_number(ref[matched_raw_key], f"EXP-029 ref {tag}.{matched_raw_key}")
                    d_raw = abs(mine_ex - ref_raw)
                    if not math.isfinite(d_raw) or d_raw > 1e-12:
                        raise RuntimeError(
                            f"Archived EXP-029 raw unrounded parity failed on {tag}.{m_name} ({matched_raw_key}): "
                            f"got={mine_ex} vs ref={ref_raw} (err={d_raw})"
                        )
                    raw_metrics_verified.add(m_name)
                    sc_raw_max = d_raw if sc_raw_max is None else max(sc_raw_max, d_raw)
                    max_raw_err_029 = d_raw if max_raw_err_029 is None else max(max_raw_err_029, d_raw)
                    metric_audit[m_name] = {
                        "precision": "unrounded_raw_le_1e-12",
                        "upstream_raw_field": matched_raw_key,
                        "raw_abs_err": d_raw,
                        "display_4dp_abs_diff": d_pct,
                    }
                else:
                    raw_metrics_absent.add(m_name)
                    metric_audit[m_name] = {
                        "precision": "display_4dp_pct_only",
                        "raw_status": "UNVERIFIED_UPSTREAM_RAW_FIELD_ABSENT",
                        "display_4dp_abs_diff": d_pct,
                    }

            exp029_checks[tag] = {
                "strict_live_eligible_locked_pct": mine["strict_live_eligible_locked_pct"],
                "counterfactual_r3b_locked_pct": mine["counterfactual_if_r3b_registered_locked_pct"],
                "counterfactual_r3b_mod_pct": mine["counterfactual_if_r3b_registered_mod100_pct"],
                "counterfactual_hypo_transfer_pct": mine["counterfactual_hypo_transfer_k100_pct"],
                "ceiling_pct": mine["composite_ceiling_pct"],
                "raw_unrounded_max_abs_err": sc_raw_max,
                "display_4dp_max_abs_diff": sc_display_max,
                "max_abs_diff": sc_display_max,
                "per_metric_precision": metric_audit,
            }
        if len(exp029_checks) != 8:
            raise RuntimeError("Incomplete archived EXP-029 parity scenario set")

        if raw_metrics_verified and not raw_metrics_absent:
            exp029_precision_mode = "all_5_metrics_unrounded_raw_le_1e-12_plus_4dp_display_exact"
        elif raw_metrics_verified and raw_metrics_absent:
            exp029_precision_mode = (
                f"mixed_raw_unrounded_le_1e-12_on_{len(raw_metrics_verified)}_metric_and_"
                f"4dp_display_only_on_{len(raw_metrics_absent)}_metrics"
            )
        else:
            exp029_precision_mode = "display_4dp_pct_only_no_upstream_raw_fields"

        parity_out["cross_track_parity_status"] = "VERIFIED_PASS"
        parity_out["exp028_cross_track_parity"] = {
            "verified": True,
            "passed": max_err_028 <= 1e-12,
            "comparison_precision": "unrounded_raw_le_1e-12_all_3_metrics_x_4_scenarios",
            "source_receipt_sha256": exp028_sha256,
            "source_receipt_bytes": exp028_bytes,
            "sha256_computed_before_parity_check": True,
            "pinned_sha256_verified": expected_exp028_sha256 is not None,
            "unrounded_max_abs_err": max_err_028,
            "scenarios_checked": len(exp028_checks),
            "scenarios": exp028_checks,
        }
        parity_out["exp029_parked_archive_cross_track_parity"] = {
            "verified": True,
            "passed": (
                max_display_diff_029 <= 1e-12
                and (max_raw_err_029 is None or max_raw_err_029 <= 1e-12)
            ),
            "program_status": "PARKED_GY027_GUARDRAIL_ARCHIVE",
            "comparison_precision": exp029_precision_mode,
            "never_self_compares_missing_upstream_fields": True,
            "raw_unrounded_metrics_verified": sorted(raw_metrics_verified),
            "display_4dp_only_metrics_unverified_at_raw": sorted(raw_metrics_absent),
            "raw_unrounded_max_abs_err": max_raw_err_029,
            "display_4dp_max_abs_diff": max_display_diff_029,
            "max_abs_diff": max_display_diff_029,
            "source_receipt_sha256": exp029_sha256,
            "source_receipt_bytes": exp029_bytes,
            "sha256_computed_before_parity_check": True,
            "pinned_sha256_verified": expected_exp029_sha256 is not None,
            "scenarios_checked": len(exp029_checks),
            "scenarios": exp029_checks,
        }
        parity_out["all_requested_checks_passed"] = (
            parity_out["all_24_shipped_scalar_parity_checks_passed"]
            and parity_out["exp028_cross_track_parity"]["verified"]
            and parity_out["exp028_cross_track_parity"]["passed"]
            and parity_out["exp029_parked_archive_cross_track_parity"]["verified"]
            and parity_out["exp029_parked_archive_cross_track_parity"]["passed"]
        )
        if not parity_out["all_requested_checks_passed"]:
            raise RuntimeError("Fail-closed parity verification did not pass")
        return parity_out

    l0 = eval_3arm_baseline()
    l0_bpr05_inputs = l0.pop("_internal_l0_bpr05")
    bpr05_l0_core = compute_bpr05_dependence_sensitivity_bounds(
        scenario_id="L0_CORE_3ARM",
        arms=l0_bpr05_inputs["arms"],
        dists=l0_bpr05_inputs["dists"],
        v_h123=l0_bpr05_inputs["v_h123"],
        routes=l0_bpr05_inputs["routes"],
        compat_map=compat_strict_live,
        cell_classes=l0_bpr05_inputs["cell_classes"],
        preserve_incumbent_3arm_joint_history=False,
        stage_ceilings=(0.88, 0.87, 0.89, 0.85),
    )
    l0_locked = l0["locked_exact"]
    l0_mod100 = l0["modular_k100_exact"]

    sc_25 = build_layer_scenarios(0.25, l0_locked, l0_mod100)
    sc_50 = build_layer_scenarios(0.50, l0_locked, l0_mod100)
    parity = verify_shipped_and_cross_track_parity(
        l0, sc_25["strict_rows"], sc_50["strict_rows"], sc_25["parked_r3b_rows"], sc_50["parked_r3b_rows"]
    )

    by25_s = {r["layer_id"]: r for r in sc_25["strict_rows"]}
    by50_s = {r["layer_id"]: r for r in sc_50["strict_rows"]}
    by25_d = {r["layer_id"]: r for r in sc_25["ineligible_full_cocktail_diag_rows"]}
    by50_d = {r["layer_id"]: r for r in sc_50["ineligible_full_cocktail_diag_rows"]}
    by25_p = {r["layer_id"]: r for r in sc_25["parked_r3b_rows"]}
    by50_p = {r["layer_id"]: r for r in sc_50["parked_r3b_rows"]}

    def _unrounded_deltas(
        bys: dict[str, dict[str, Any]],
        byd: dict[str, dict[str, Any]],
        byp: dict[str, dict[str, Any]],
    ) -> dict[str, Any]:
        """Compute all deltas from UNROUNDED exact probabilities BEFORE display rounding."""
        def _dp(a: float, b: float) -> float:
            return 100.0 * (a - b)

        l1_key = "L1_LIVE_5ARM_WU3" if "L1_LIVE_5ARM_WU3" in bys else "L1_LIVE_5ARM_WU4"
        raw = {
            # Strict Live-Eligible (Zero-R3B) exact deltas
            "reset_alone_upside_on_L1_locked_pp": _dp(bys["L2C_EXP030_FINITE_RESET"]["locked_exact"], bys[l1_key]["locked_exact"]),
            "reset_alone_upside_on_L1_mod100_pp": _dp(bys["L2C_EXP030_FINITE_RESET"]["modular_k100_exact"], bys[l1_key]["modular_k100_exact"]),
            "reset_alone_AE_penalized_on_L1_locked_pp": _dp(bys["L2C_AE_PENALIZED_FINITE_RESET"]["locked_exact"], bys[l1_key]["locked_exact"]),
            "reset_alone_AE_penalized_on_L1_mod100_pp": _dp(bys["L2C_AE_PENALIZED_FINITE_RESET"]["modular_k100_exact"], bys[l1_key]["modular_k100_exact"]),
            "reset_on_SHIELD_fail_strict_zero_sort_guard_upside_pp": _dp(bys["L3_SHIELD_FAIL_STRICT_ZERO_SORT_GUARD_PLUS_RESET"]["locked_exact"], bys["L3_SHIELD_FAIL_STRICT_ZERO_SORT_GUARD"]["locked_exact"]),
            "reset_on_SHIELD_fail_strict_zero_sort_guard_AE_pp": _dp(bys["L3_SHIELD_FAIL_STRICT_ZERO_SORT_GUARD_PLUS_AE_RESET"]["locked_exact"], bys["L3_SHIELD_FAIL_STRICT_ZERO_SORT_GUARD"]["locked_exact"]),
            "reset_on_L3A_strict_zero_sort_guard_upside_pp": _dp(bys["L3A_STRICT_ZERO_SORT_GUARD_PLUS_RESET_OMEGA_0P60"]["locked_exact"], bys["L3A_STRICT_ZERO_SORT_GUARD"]["locked_exact"]),
            "reset_on_L3A_strict_zero_sort_guard_AE_pp": _dp(bys["L3A_STRICT_ZERO_SORT_GUARD_PLUS_AE_RESET_OMEGA_0P60"]["locked_exact"], bys["L3A_STRICT_ZERO_SORT_GUARD"]["locked_exact"]),
            "reset_on_SHIELD_fail_upside_locked_pp": _dp(bys["L3_SHIELD_FAIL_PLUS_FINITE_RESET"]["locked_exact"], bys["L3_SHIELD_FAIL_ZERODRUG_BASE"]["locked_exact"]),
            "reset_on_SHIELD_fail_AE_penalized_locked_pp": _dp(bys["L3_SHIELD_FAIL_PLUS_AE_PENALIZED_RESET"]["locked_exact"], bys["L3_SHIELD_FAIL_ZERODRUG_BASE"]["locked_exact"]),
            "reset_on_L3A_strict_zerodrug_omega0p60_locked_pp": _dp(bys["L3A_STRICT_ZERODRUG_PLUS_RESET_OMEGA_0P60"]["locked_exact"], bys["L3A_STACK_STRICT_100PCT_ZERO_DRUG"]["locked_exact"]),
            "reset_on_L3A_strict_zerodrug_omega0p80_locked_pp": _dp(bys["L3A_STRICT_ZERODRUG_PLUS_RESET_OMEGA_0P80"]["locked_exact"], bys["L3A_STACK_STRICT_100PCT_ZERO_DRUG"]["locked_exact"]),
            "reset_on_L3A_strict_zerodrug_AE_locked_pp": _dp(bys["L3A_STRICT_ZERODRUG_PLUS_AE_RESET_OMEGA_0P60"]["locked_exact"], bys["L3A_STACK_STRICT_100PCT_ZERO_DRUG"]["locked_exact"]),
            # Ineligible Full-Cocktail diagnostic deltas (zero Policy Option 1 EV weight!)
            "ineligible_diag_reset_on_L3B_strict_zerodrug_omega0p60_locked_pp": _dp(byd["L3B_STRICT_ZERODRUG_PLUS_RESET_OMEGA_0P60"]["locked_exact"], bys["L3B_STACK_STRICT_100PCT_ZERO_DRUG"]["locked_exact"]),
            "ineligible_diag_reset_on_L3B_strict_zerodrug_AE_locked_pp": _dp(byd["L3B_STRICT_ZERODRUG_PLUS_AE_RESET_OMEGA_0P60"]["locked_exact"], bys["L3B_STACK_STRICT_100PCT_ZERO_DRUG"]["locked_exact"]),
            # Parked R3B counterfactual comparator deltas (for Stage-S4 auditability)
            "parked_r3b_reset_on_L3A_omega0p60_locked_pp": _dp(byp["L3A_PLUS_FINITE_RESET_OMEGA_0P60"]["counterfactual_if_r3b_registered_locked_exact"], byp["L3A_STACK_EXP028_029_FOUNDRY_V12"]["counterfactual_if_r3b_registered_locked_exact"]),
            "parked_r3b_reset_on_L3A_AE_locked_pp": _dp(byp["L3A_PLUS_AE_PENALIZED_RESET_OMEGA_0P60"]["counterfactual_if_r3b_registered_locked_exact"], byp["L3A_STACK_EXP028_029_FOUNDRY_V12"]["counterfactual_if_r3b_registered_locked_exact"]),
            "parked_r3b_reset_on_L3B_omega0p60_locked_pp": _dp(byp["L4_ALL_IN_OVERLAP_DAMPED_OMEGA_0P60"]["counterfactual_if_r3b_registered_locked_exact"], byp["L3B_STACK_EXP028_029_FOUNDRY_COCKTAIL"]["counterfactual_if_r3b_registered_locked_exact"]),
            "parked_r3b_reset_on_L3B_omega0p80_locked_pp": _dp(byp["L4_SENS_HARSH_OVERLAP_OMEGA_0P80"]["counterfactual_if_r3b_registered_locked_exact"], byp["L3B_STACK_EXP028_029_FOUNDRY_COCKTAIL"]["counterfactual_if_r3b_registered_locked_exact"]),
            "parked_r3b_reset_on_L3B_omega1p00_locked_pp": _dp(byp["L4_SENS_COMPLETE_OVERLAP_OMEGA_1P00"]["counterfactual_if_r3b_registered_locked_exact"], byp["L3B_STACK_EXP028_029_FOUNDRY_COCKTAIL"]["counterfactual_if_r3b_registered_locked_exact"]),
            "parked_r3b_reset_on_L3B_AE_locked_pp": _dp(byp["L4_AE_PENALIZED_ALL_IN_OMEGA_0P60"]["counterfactual_if_r3b_registered_locked_exact"], byp["L3B_STACK_EXP028_029_FOUNDRY_COCKTAIL"]["counterfactual_if_r3b_registered_locked_exact"]),
            "naive_double_count_fake_inflation_locked_pp": _dp(byp["L4_FORBIDDEN_NAIVE_LINEAR_DOUBLE_COUNT_DIAGNOSTIC"]["counterfactual_if_r3b_registered_locked_exact"], byp["L4_ALL_IN_OVERLAP_DAMPED_OMEGA_0P60"]["counterfactual_if_r3b_registered_locked_exact"]),
        }
        return {
            "rounded_4dp": {k: round(v, 4) for k, v in raw.items()},
            "unrounded_exact": raw,
        }

    d25_all = _unrounded_deltas(by25_s, by25_d, by25_p)
    d50_all = _unrounded_deltas(by50_s, by50_d, by50_p)
    d25_raw = d25_all["unrounded_exact"]
    d50_raw = d50_all["unrounded_exact"]

    # =========================================================================
    # FIXED POLICY OPTION 1 ELIGIBILITY EV + HOLD / OWNER-REAUTH + P(XREACT) SWEEP
    # Track-B reset is INELIGIBLE (0.0000 pp credit!) in the full-cocktail branch
    # AND in any HOLD/pending state AND whenever owner re-authorization is withheld.
    # Live current_active_ev_pp = 0.0 today while XREACT, SHIELD, and owner_reauth are pending.
    # =========================================================================
    def _build_ev_table(
        d_fail_up_25: float, d_s1_up_25: float,
        d_fail_ae_25: float, d_s1_ae_25: float,
        d_fail_up_50: float, d_s1_up_50: float,
        d_fail_ae_50: float, d_s1_ae_50: float,
    ) -> list[dict[str, Any]]:
        rows_ev = []
        regimes = [
            ("Stage0_BaseRate_Low_Prior (p_S1=0.03, p_Cocktail=0.005)", "LOW_STAGE0_BASE_RATE", 0.03, 0.005),
            ("Stage0_BaseRate_Central_Prior (p_S1=0.05, p_Cocktail=0.01)", "LOW_STAGE0_BASE_RATE", 0.05, 0.01),
            ("Stage0_BaseRate_Upper_Prior (p_S1=0.10, p_Cocktail=0.03)", "LOW_STAGE0_BASE_RATE", 0.10, 0.03),
            ("Uncited_Judgment_Pessimistic (p_S1=0.15, p_Cocktail=0.05)", "UNCITED_JUDGMENT_SCENARIO", 0.15, 0.05),
            ("Uncited_Judgment_Central_Legacy (p_S1=0.30, p_Cocktail=0.12)", "UNCITED_JUDGMENT_SCENARIO", 0.30, 0.12),
            ("Uncited_Judgment_Optimistic_v13 (p_S1=0.50, p_Cocktail=0.25)", "UNCITED_JUDGMENT_SCENARIO", 0.50, 0.25),
            ("Conditional_Post_Stage0_SHIELD1_PASS (p_S1=1.00, p_Cocktail=0.40)", "CONDITIONAL_POST_STAGE0", 1.00, 0.40),
            ("Conditional_Full_Cocktail_PASS (p_S1=1.00, p_Cocktail=1.00; Track-B Ineligible)", "CONDITIONAL_INELIGIBLE", 1.00, 1.00),
        ]
        for lbl, prior_cls, p_s1, p_cock in regimes:
            p_fail = 1.0 - p_s1
            p_s1_only = p_s1 - p_cock
            p_hold = 0.0
            # Strictly ZERO credit in the ineligible full-cocktail branch (p_cock * 0.0) and in HOLD states (p_hold * 0.0)!
            base_up_25 = evaluate_trackb_policy_option1_ev(
                p_shield_fail=p_fail, p_shield1_only=p_s1_only, p_cocktail_pass=p_cock, p_hold_or_pending=p_hold,
                p_xreact_pass_given_fail=1.0, p_owner_reauth=1.0, d_fail_pp=d_fail_up_25, d_s1_pp=d_s1_up_25,
            )["active_ev_exact_pp"]
            base_ae_25 = evaluate_trackb_policy_option1_ev(
                p_shield_fail=p_fail, p_shield1_only=p_s1_only, p_cocktail_pass=p_cock, p_hold_or_pending=p_hold,
                p_xreact_pass_given_fail=1.0, p_owner_reauth=1.0, d_fail_pp=d_fail_ae_25, d_s1_pp=d_s1_ae_25,
            )["active_ev_exact_pp"]
            base_up_50 = evaluate_trackb_policy_option1_ev(
                p_shield_fail=p_fail, p_shield1_only=p_s1_only, p_cocktail_pass=p_cock, p_hold_or_pending=p_hold,
                p_xreact_pass_given_fail=1.0, p_owner_reauth=1.0, d_fail_pp=d_fail_up_50, d_s1_pp=d_s1_up_50,
            )["active_ev_exact_pp"]
            base_ae_50 = evaluate_trackb_policy_option1_ev(
                p_shield_fail=p_fail, p_shield1_only=p_s1_only, p_cocktail_pass=p_cock, p_hold_or_pending=p_hold,
                p_xreact_pass_given_fail=1.0, p_owner_reauth=1.0, d_fail_pp=d_fail_ae_50, d_s1_pp=d_s1_ae_50,
            )["active_ev_exact_pp"]
            xreact_sweep = {}
            for px in (0.25, 0.50, 0.75, 1.00):
                xreact_sweep[f"p_xreact_{px:.2f}"] = {
                    "ev_upside_phi25_pp": round(px * base_up_25, 4),
                    "ev_AE_penalized_phi25_pp": round(px * base_ae_25, 4),
                    "ev_upside_phi50_pp": round(px * base_up_50, 4),
                    "ev_AE_penalized_phi50_pp": round(px * base_ae_50, 4),
                }
            rows_ev.append({
                "regime": lbl,
                "prior_classification": prior_cls,
                "ev_classification": "CONDITIONAL_SCENARIO_GIVEN_OWNER_REAUTH_AND_NO_HOLD",
                "current_active_ev_pp": 0.0,
                "p_hold_or_pending": p_hold,
                "p_owner_reauth_assumed_in_conditional_scenario": 1.0,
                "p_shield1_pass": p_s1,
                "p_cocktail_pass_trackb_ineligible_zero_credit": p_cock,
                "p_shield_fail": round(p_fail, 4),
                "p_shield1_only_interim": round(p_s1_only, 4),
                "ev_conditional_on_xreact_pass_1p0_upside_phi25_pp": round(base_up_25, 4),
                "ev_conditional_on_xreact_pass_1p0_AE_phi25_pp": round(base_ae_25, 4),
                "ev_conditional_on_xreact_pass_1p0_upside_phi50_pp": round(base_up_50, 4),
                "ev_conditional_on_xreact_pass_1p0_AE_phi50_pp": round(base_ae_50, 4),
                "p_xreact_pass_sensitivity": xreact_sweep,
            })
        return rows_ev

    # Explicit joint HOLD and owner-reauthorization sensitivity table (proving 0.0000 pp active EV while pending!)
    joint_hold_and_owner_reauth_sensitivity = [
        {
            "scenario_id": "LIVE_PENDING_TODAY",
            "description": "Current Stage-0 state: Gate 30-ATG-XREACT pending, Gate 30-SHIELD-SPR pending (p_hold_or_pending=1.0), owner re-authorization pending (p_owner_reauth=0.0)",
            "upside_phi25": evaluate_trackb_policy_option1_ev(
                p_shield_fail=0.0, p_shield1_only=0.0, p_cocktail_pass=0.0, p_hold_or_pending=1.0,
                p_xreact_pass_given_fail=0.25, p_owner_reauth=0.0,
                d_fail_pp=d25_raw["reset_on_SHIELD_fail_strict_zero_sort_guard_upside_pp"],
                d_s1_pp=d25_raw["reset_on_L3A_strict_zero_sort_guard_upside_pp"],
            ),
            "AE_penalized_phi25": evaluate_trackb_policy_option1_ev(
                p_shield_fail=0.0, p_shield1_only=0.0, p_cocktail_pass=0.0, p_hold_or_pending=1.0,
                p_xreact_pass_given_fail=0.25, p_owner_reauth=0.0,
                d_fail_pp=d25_raw["reset_on_SHIELD_fail_strict_zero_sort_guard_AE_pp"],
                d_s1_pp=d25_raw["reset_on_L3A_strict_zero_sort_guard_AE_pp"],
            ),
        },
        {
            "scenario_id": "OWNER_REAUTH_WITHHELD_P0",
            "description": "Resolved SHIELD central priors (p_fail=0.70, p_s1_only=0.18, p_cock=0.12) with p_xreact=0.25 but owner re-authorization withheld (p_owner_reauth=0.0 -> strictly 0.0000 pp)",
            "upside_phi25": evaluate_trackb_policy_option1_ev(
                p_shield_fail=0.70, p_shield1_only=0.18, p_cocktail_pass=0.12, p_hold_or_pending=0.0,
                p_xreact_pass_given_fail=0.25, p_owner_reauth=0.0,
                d_fail_pp=d25_raw["reset_on_SHIELD_fail_strict_zero_sort_guard_upside_pp"],
                d_s1_pp=d25_raw["reset_on_L3A_strict_zero_sort_guard_upside_pp"],
            ),
            "AE_penalized_phi25": evaluate_trackb_policy_option1_ev(
                p_shield_fail=0.70, p_shield1_only=0.18, p_cocktail_pass=0.12, p_hold_or_pending=0.0,
                p_xreact_pass_given_fail=0.25, p_owner_reauth=0.0,
                d_fail_pp=d25_raw["reset_on_SHIELD_fail_strict_zero_sort_guard_AE_pp"],
                d_s1_pp=d25_raw["reset_on_L3A_strict_zero_sort_guard_AE_pp"],
            ),
        },
        {
            "scenario_id": "ALL_SHIELD_OUTCOMES_IN_HOLD",
            "description": "All SHIELD outcomes unresolved in HOLD (p_hold_or_pending=1.0) even with p_owner_reauth=1.0 and p_xreact=0.25 -> strictly 0.0000 pp",
            "upside_phi25": evaluate_trackb_policy_option1_ev(
                p_shield_fail=0.0, p_shield1_only=0.0, p_cocktail_pass=0.0, p_hold_or_pending=1.0,
                p_xreact_pass_given_fail=0.25, p_owner_reauth=1.0,
                d_fail_pp=d25_raw["reset_on_SHIELD_fail_strict_zero_sort_guard_upside_pp"],
                d_s1_pp=d25_raw["reset_on_L3A_strict_zero_sort_guard_upside_pp"],
            ),
            "AE_penalized_phi25": evaluate_trackb_policy_option1_ev(
                p_shield_fail=0.0, p_shield1_only=0.0, p_cocktail_pass=0.0, p_hold_or_pending=1.0,
                p_xreact_pass_given_fail=0.25, p_owner_reauth=1.0,
                d_fail_pp=d25_raw["reset_on_SHIELD_fail_strict_zero_sort_guard_AE_pp"],
                d_s1_pp=d25_raw["reset_on_L3A_strict_zero_sort_guard_AE_pp"],
            ),
        },
        {
            "scenario_id": "PARTIAL_HOLD_30PCT_AND_OWNER_REAUTH_50PCT",
            "description": "Illustrative joint scenario with 30% SHIELD HOLD mass (0 credit), 50% owner re-auth, and branch-specific XREACT probabilities (0.25 fail / 0.25 s1_only)",
            "upside_phi25": evaluate_trackb_policy_option1_ev(
                p_shield_fail=0.49, p_shield1_only=0.126, p_cocktail_pass=0.084, p_hold_or_pending=0.30,
                p_xreact_pass_given_fail=0.25, p_xreact_pass_given_s1=0.25, p_owner_reauth=0.50,
                d_fail_pp=d25_raw["reset_on_SHIELD_fail_strict_zero_sort_guard_upside_pp"],
                d_s1_pp=d25_raw["reset_on_L3A_strict_zero_sort_guard_upside_pp"],
            ),
            "AE_penalized_phi25": evaluate_trackb_policy_option1_ev(
                p_shield_fail=0.49, p_shield1_only=0.126, p_cocktail_pass=0.084, p_hold_or_pending=0.30,
                p_xreact_pass_given_fail=0.25, p_xreact_pass_given_s1=0.25, p_owner_reauth=0.50,
                d_fail_pp=d25_raw["reset_on_SHIELD_fail_strict_zero_sort_guard_AE_pp"],
                d_s1_pp=d25_raw["reset_on_L3A_strict_zero_sort_guard_AE_pp"],
            ),
        },
    ]

    ev_strict_zero_sort_guard = _build_ev_table(
        d25_raw["reset_on_SHIELD_fail_strict_zero_sort_guard_upside_pp"],
        d25_raw["reset_on_L3A_strict_zero_sort_guard_upside_pp"],
        d25_raw["reset_on_SHIELD_fail_strict_zero_sort_guard_AE_pp"],
        d25_raw["reset_on_L3A_strict_zero_sort_guard_AE_pp"],
        d50_raw["reset_on_SHIELD_fail_strict_zero_sort_guard_upside_pp"],
        d50_raw["reset_on_L3A_strict_zero_sort_guard_upside_pp"],
        d50_raw["reset_on_SHIELD_fail_strict_zero_sort_guard_AE_pp"],
        d50_raw["reset_on_L3A_strict_zero_sort_guard_AE_pp"],
    )
    ev_strict_with_sort_guard_sens = _build_ev_table(
        d25_raw["reset_on_SHIELD_fail_upside_locked_pp"],
        d25_raw["reset_on_L3A_strict_zerodrug_omega0p60_locked_pp"],
        d25_raw["reset_on_SHIELD_fail_AE_penalized_locked_pp"],
        d25_raw["reset_on_L3A_strict_zerodrug_AE_locked_pp"],
        d50_raw["reset_on_SHIELD_fail_upside_locked_pp"],
        d50_raw["reset_on_L3A_strict_zerodrug_omega0p60_locked_pp"],
        d50_raw["reset_on_SHIELD_fail_AE_penalized_locked_pp"],
        d50_raw["reset_on_L3A_strict_zerodrug_AE_locked_pp"],
    )
    ev_legacy_r3b_eligibility_audit = _build_ev_table(
        d25_raw["reset_on_SHIELD_fail_upside_locked_pp"],
        d25_raw["parked_r3b_reset_on_L3A_omega0p60_locked_pp"],
        d25_raw["reset_on_SHIELD_fail_AE_penalized_locked_pp"],
        d25_raw["parked_r3b_reset_on_L3A_AE_locked_pp"],
        d50_raw["reset_on_SHIELD_fail_upside_locked_pp"],
        d50_raw["parked_r3b_reset_on_L3A_omega0p60_locked_pp"],
        d50_raw["reset_on_SHIELD_fail_AE_penalized_locked_pp"],
        d50_raw["parked_r3b_reset_on_L3A_AE_locked_pp"],
    )

    # =========================================================================
    # HONEST STAGE-0 FOUNDRY UNCONDITIONAL EV BLOCK (S4 audit remediation)
    # 0 credit for SORT (ITGA2 inversion) and GUARD (18-Cys / bleeding risk)
    # 0 credit for parked R3B (GY-027 BLOCK); low Stage-0 base-rate priors
    # =========================================================================
    def _honest_stage0_unconditional_ev(bys: dict[str, dict[str, Any]], phi_label: str) -> dict[str, Any]:
        l1_key = "L1_LIVE_5ARM_WU3" if "L1_LIVE_5ARM_WU3" in bys else "L1_LIVE_5ARM_WU4"
        l1_l = bys[l1_key]["locked_exact"]
        d_s2a = 100.0 * (bys["L2A_EXP028_S2a_H1_90_ZERO_H3_LIFT"]["locked_exact"] - l1_l)
        d_s2c_extra = 100.0 * (bys["L2A_EXP028_S2c_CONDITIONAL_STAGE0"]["locked_exact"] - bys["L2A_EXP028_S2a_H1_90_ZERO_H3_LIFT"]["locked_exact"])
        d_s2c = 100.0 * (bys["L2A_EXP028_S2c_CONDITIONAL_STAGE0"]["locked_exact"] - l1_l)
        d_bilayer = 100.0 * (bys["L2B_DF_PASSIVE_65UM_BILAYER_ZERO_DRUG"]["locked_exact"] - l1_l)
        d_joint_s2c_bilayer = 100.0 * (bys["L3_SHIELD_FAIL_STRICT_ZERO_SORT_GUARD"]["locked_exact"] - l1_l)
        d_marginal_sum_s2c_bilayer = d_s2c + d_bilayer
        d_s1_full = 100.0 * (bys["L3A_SHIELD1_ONLY_ZERO_SORT_GUARD_FULL_ASSUMED_PK"]["locked_exact"] - l1_l)
        d_s1_pk50 = 100.0 * (bys["L3A_SHIELD1_ONLY_ZERO_SORT_GUARD_PK_RENAL_DISCOUNT_50PCT"]["locked_exact"] - l1_l)
        d_ck_full = 100.0 * (bys["L3B_COCKTAIL_ONLY_ZERO_SORT_GUARD_FULL_ASSUMED_PK"]["locked_exact"] - l1_l)
        d_ck_pk50 = 100.0 * (bys["L3B_COCKTAIL_ONLY_ZERO_SORT_GUARD_PK_RENAL_DISCOUNT_50PCT"]["locked_exact"] - l1_l)

        cases = []
        for nm, p_s1, p_ck, p_h1, p_s2c_cond, p_bil in (
            ("Stage0_BaseRate_Conservative", 0.03, 0.005, 0.35, 0.20, 0.40),
            ("Stage0_BaseRate_Central", 0.05, 0.010, 0.50, 0.25, 0.50),
            ("Stage0_BaseRate_Upper", 0.10, 0.030, 0.60, 0.35, 0.60),
        ):
            p_s1_only = p_s1 - p_ck
            ev_foundry_full = p_s1_only * d_s1_full + p_ck * d_ck_full
            ev_foundry_pk50 = p_s1_only * d_s1_pk50 + p_ck * d_ck_pk50
            ev_wave5_non_foundry = p_h1 * d_s2a + (p_h1 * p_s2c_cond) * d_s2c_extra + p_bil * d_bilayer
            cases.append({
                "regime": nm,
                "approximation_type": "ADDITIVE_MARGINAL_APPROXIMATION_WITHOUT_JOINT_STATE_MODEL",
                "priors_uncited_stage0_base_rate": {
                    "p_SHIELD1_pass": p_s1,
                    "p_SHIELD_cocktail_pass": p_ck,
                    "p_SORT_credit_before_wetlab": 0.0,
                    "p_GUARD_credit_before_wetlab": 0.0,
                    "p_EXP029_R3B_credit_parked_GY027": 0.0,
                    "p_EXP028_H1_flip": p_h1,
                    "p_EXP028_S2c_given_H1": p_s2c_cond,
                    "p_65um_bilayer_pass": p_bil,
                },
                "unconditional_ev_foundry_only_full_pk_pp": round(ev_foundry_full, 4),
                "unconditional_ev_foundry_only_pk_renal_50pct_discount_pp": round(ev_foundry_pk50, 4),
                "unconditional_ev_wave5_zero_drug_total_full_pk_pp": round(ev_wave5_non_foundry + ev_foundry_full, 4),
                "unconditional_ev_wave5_zero_drug_total_pk_renal_50pct_discount_pp": round(ev_wave5_non_foundry + ev_foundry_pk50, 4),
                "implied_unconditional_portfolio_locked_pct_pk_discounted": round(100.0 * l1_l + ev_wave5_non_foundry + ev_foundry_pk50, 4),
                "published_live_headline_delta_pp_today": 0.0,
            })
        return {
            "phi_c": phi_label,
            "estimation_method": "ADDITIVE_MARGINAL_APPROXIMATION_WITHOUT_JOINT_STATE_MODEL",
            "additive_marginal_approximation_disclosure": (
                "Total Wave-5 zero-drug EV sums probability-weighted marginal component increments without a full "
                "joint distribution over multi-component pass/fail states; exact joint portfolio evaluation is "
                "slightly subadditive (see s2c_plus_bilayer_nonadditivity_check)."
            ),
            "s2c_plus_bilayer_nonadditivity_check": {
                "observed_joint_s2c_plus_bilayer_increment_pp": round(d_joint_s2c_bilayer, 6),
                "marginal_sum_s2c_plus_bilayer_increment_pp": round(d_marginal_sum_s2c_bilayer, 6),
                "joint_minus_marginal_sum_interaction_pp": round(d_joint_s2c_bilayer - d_marginal_sum_s2c_bilayer, 6),
                "note": (
                    "Exact 2^20 joint evaluation of EXP-028 S2c + passive 65um bilayer vs sum of the two marginal "
                    "increments over L1, quantifying nonlinear portfolio interaction."
                ),
            },
            "live_staged_L1_baseline_locked_pct": round(100.0 * l1_l, 4),
            "component_conditional_deltas_zero_sort_guard_pp": {
                "SHIELD1_only_full_pk_pp": round(d_s1_full, 4),
                "SHIELD1_only_pk_50pct_renal_discount_pp": round(d_s1_pk50, 4),
                "SHIELD_cocktail_unsequenced_full_pk_pp": round(d_ck_full, 4),
                "SHIELD_cocktail_unsequenced_pk_50pct_renal_discount_pp": round(d_ck_pk50, 4),
                "SORT_credit_until_wetlab_pp": 0.0,
                "GUARD_credit_until_wetlab_pp": 0.0,
                "EXP028_S2a_H1_flip_pp": round(d_s2a, 4),
                "EXP028_S2c_incremental_over_S2a_pp": round(d_s2c_extra, 4),
                "Passive_65um_bilayer_pp": round(d_bilayer, 4),
            },
            "unconditional_ev_regimes": cases,
        }

    honest_stage0_foundry = {
        "estimation_method": "ADDITIVE_MARGINAL_APPROXIMATION_WITHOUT_JOINT_STATE_MODEL",
        "v1_2_qualitative_reality_summary": (
            "Foundry v1.2/v1.3 QF09_pI2 (6.77 kDa) fails 5/10 pre-registered computational gates and Comp2_T006 (6.49 kDa) "
            "fails 4/11 gates; qualitative hosted Tier-2 audit flagged primary DQ2.5+HIP11 non-binding and Islet-SORT ITGA2 "
            "paralog selectivity inversion (zero hosted Tier-2 numerics copied under Gate 30-TOS-QUARANTINE). "
            "Islet-SORT and Islet-GUARD receive 0.00 pp headline credit until wet-lab sibling/mammalian-expression and "
            "surgical bleeding data exist; Islet-SHIELD miniproteins (rounded sequence-derived unmodified average masses "
            "6.77 kDa [6.76672 kDa] QF09_pI2 / 6.49 kDa [6.49247 kDa] Comp2_T006; expected to undergo rapid renal clearance "
            "unless formulated or extended, with actual PK exposure, clearance, and immunogenicity conditional on route, "
            "formulation, and dosing schedule and construct-specific PK unmeasured) carry a 50% "
            "delivery-feasibility / PK discount sensitivity. At phi=0.25 with PK discount, the Foundry-only additive EV is "
            "+0.0225 to +0.0852 pp whereas the full Wave-5 zero-drug additive EV (including EXP-028 and 65um bilayer) is "
            "+0.66 to +1.18 pp. Total Wave-5 EV sums are explicitly labeled additive marginal approximations without a "
            "joint state model. Live published odds stay strictly locked at +0.00 pp (~62% baseline)."
        ),
        "phi_0p25": _honest_stage0_unconditional_ev(by25_s, "0.25"),
        "phi_0p50": _honest_stage0_unconditional_ev(by50_s, "0.50"),
    }

    h3_channel_budget = {
        "epistemic_warning": (
            "UNCITED MODELING JUDGMENT SCENARIO — NOT EMPIRICALLY IDENTIFIED. The 6.5 / 2.5 / 2.0 pp "
            "Channel (a)/(b)/(c) partition and overlap parameter omega in [0, 1] are bookkeeping scenarios, "
            "not measured human transplant-graft quantities. Quote the full omega in [0, 1] band rather than "
            "treating any single omega point as an empirical finding."
        ),
        "live_c3_baseline": 0.89,
        "total_systemic_h3_failure_pp": 11.0,
        "channel_decomposition_scenario_pp": {
            "channel_a_memory_tcell_recurrence_acute_and_reconstitution": 6.5,
            "channel_b_humoral_autoab_igm_igg_complement_escape": 2.5,
            "channel_c_innate_neutrophil_myeloid_cytokine_bystander": 2.0,
        },
        "omega_min_for_c3_lt_0p94": sc_25["omega_sweep_strict"]["min_omega_for_c3_lt_0p94"],
        "meld_atg_primary_clinical_anchor": (
            "MELD-ATG low-dose arm (PMID:40976248, NCT04509791): single active Day-1 0.5 mg/kg IV rabbit ATG "
            "+ Day-2 IV placebo (only higher-dose arms received active drug on Day 2); n=35 assigned, n=34 safety "
            "denominator, 8/34 (24%) CRS, 11/34 (32%) serum sickness, ages 5-25 recent-onset native T1D (no graft). "
            "Native-T1D trial rates do not empirically identify graft H3 response or H4 AE drag."
        ),
    }

    # Run executable Gate 30-ATG-XREACT, mirrored Gate 30-SHIELD-SPR, and NCT cohort mapping self-tests!
    xreact_self_tests = run_gate30_atg_xreact_decision_table_self_tests()
    shield_spr_self_tests = run_gate30_shield_spr_decision_table_self_tests()
    nct_mapping_self_tests = run_iip0042_nct_mapping_self_tests()
    nct_mapping_audit: dict[str, Any] = {
        "nct_cohort_mapping_verified": False,
        "self_tests": nct_mapping_self_tests,
    }

    md_candidate = openislet_root / "docs" / "GATE-30-PORTFOLIO-AND-TRACKB-CONTINGENCY-PROTOCOL.md"
    md_text_loaded: str | None = None
    if md_candidate.is_file():
        md_text_loaded = md_candidate.read_text(encoding="utf-8")
        verify_gate30_protocol_markdown_alignment(md_text_loaded, md_candidate.name)

    # Verify verbatim alignment with side-contract owner re-authorization condition & NCT trial mapping whenever present!
    sc_candidates = [
        openislet_root / "data" / "protocols" / "iip0042_portfolio_and_trackb_side_contract_v0.8.0.json",
    ]
    if ART_DIR.name == "artifacts-carbon":
        sc_candidates.insert(0, ART_DIR / "exp030_iip0043_side_contract.json")
    for sc_candidate in sc_candidates:
        if sc_candidate.is_file():
            sc_raw = sc_candidate.read_text(encoding="utf-8")
            sc_obj = load_strict_json_text(sc_raw, sc_candidate.name)
            sc_rule = sc_obj.get("locked_owner_policy", {}).get("trackb_eligibility_rule")
            if sc_rule != CANONICAL_TRACKB_ELIGIBILITY_RULE:
                raise RuntimeError(
                    f"Eligibility rule mismatch vs side contract {sc_candidate.name}: "
                    f"receipt={CANONICAL_TRACKB_ELIGIBILITY_RULE!r} vs side_contract={sc_rule!r}"
                )
            sc_1jk8 = _v37_find_unnegated_1jk8_conflation(sc_raw) or _v37_find_unnegated_1jk8_conflation(
                json.dumps(sc_obj, ensure_ascii=False)
            )
            if sc_1jk8 is not None:
                raise RuntimeError(
                    f"Side contract {sc_candidate.name} contains prohibited PDB 1JK8 <-> WT InsB:9-23 conflation: {sc_1jk8!r}"
                )
            nct_res = verify_iip0042_published_trial_cohort_nct_mapping(
                sc_obj,
                md_text_loaded,
                openislet_root=openislet_root,
            )
            nct_mapping_audit = {
                **nct_res,
                "self_tests": nct_mapping_self_tests,
            }

    receipt = {
        "schema_version": "exp030_master_2pow20_portfolio_receipt_v3.4_r04",
        "investigation_id": "EXP-030",
        "candidate_id": "CAND-033",
        "target_iip": "IIP-0042",
        "decision_id": "DEC-121",
        "generated_date": GENERATED_DATE,
        "locked_owner_policy": "POLICY_OPTION_1_SPLIT_SHIP_DESIGN_A_EXCLUDES_ATG_INDUCTION_SHIELD_FIRST_GATED_OPTIONAL_TRACKB_AFTER_ATG_XREACT",
        "live_headline_delta_pp_today": 0.0,
        "current_active_trackb_ev_pp": 0.0,
        "runtime_environment": {
            "python_version": sys.version,
            "python_version_info": list(sys.version_info[:3]),
            "byte_exact_scope": "pinned_cpython_3_12_12_build_both_-B_and_-O_-B",
            "parity_tolerance_policy": "24/24_displayed_scalar_parity_and_numeric_tolerance_le_1e-12_across_cpython_builds",
            "portable_comparison_ignored_fields": ["runtime_environment.python_version", "portable_payload_sha256"],
            "portable_check_cli_flag": "--check-portable",
        },
        "epistemic_notice": (
            "SPLIT-SHIP & COMPUTATIONAL #ODDS CONVENTION (BPR-13 DATED SUPERSESSION, 2026-12-02): "
            "Historical IIP-0042 split-ship provenance is preserved intact — the frozen Core 3x2 OQ-016 baseline "
            "(50.7782% locked / 54.1163% modular / 57.9176% ceiling) and shipped IIP-0035 5-arm W_U3 baseline "
            "(60.6439% locked / 61.5921% modular / 66.4117% ceiling; informally ~62% shorthand) remain unchanged "
            "(live_headline_delta_pp_today = +0.00 pp in this IIP-0042 split-ship receipt). "
            "Superseding the obsolete earlier Gate 30 §4 publication prohibition, maintainer public-display policy "
            "(AGENTS.md and TNFA-IFNG-INTRINSIC-APOPTOSIS-QUALIFICATION-NOTE.md §4) explicitly "
            "permits publishing audited staged computational scenarios (e.g. 66.57% zero-drug / 67.21% optional-reset "
            "computational modular scenarios) on openislet.org/blueprint#odds alongside the invariant underlying baselines "
            "and explicit unmeasured-assumption caveats. Public display of a computational scenario does NOT activate "
            "Track-B or alter gate eligibility: Track-B reset rows remain strictly inactive today (all 12 Track-B rows "
            "per sensitivity carry option1_eligible=false, live_activated_today=false, and current_active_ev_pp=0.0 while "
            "Gate 30-ATG-XREACT, Gate 30-SHIELD-SPR, and owner re-authorization remain pending: the 3 reset-alone "
            "sensitivity rows carry scenario_activation_status=PENDING_SHIELD_DISPOSITION_AND_OWNER_REAUTH, while the "
            "other 9 conditional Track-B rows carry scenario_activation_status=CONDITIONAL_SCENARIO_PENDING_XREACT_PASS_AND_OWNER_REAUTH); "
            "the 4 ineligible full-cocktail-plus-reset diagnostic rows (option1_eligible=false, 0.0000 pp EV weight) "
            "are segregated into ineligible_full_cocktail_diagnostics_zero_ev_weight; parked EXP-029 R3B scenarios "
            "are strictly segregated into parked_counterfactual_r3b_sensitivity_exp029_gy027_block with R3B masked "
            "in strict live-eligible totals (W_U3=57.5945%, W_U4=56.8730%). Zero hosted Tier-2 structure-prediction "
            "numeric outputs are copied into this receipt (Gate 30-TOS-QUARANTINE)."
        ),
        "h3_channel_abc_ceiling_budget": h3_channel_budget,
        "parity_verification": parity,
        "gate30_atg_xreact_decision_table_self_tests": xreact_self_tests,
        "gate30_shield_spr_decision_table_self_tests": shield_spr_self_tests,
        "published_trial_cohort_nct_mapping_audit": nct_mapping_audit,
        "layer_0_core_3arm": l0,
        "headline_live_eligible_scenarios_strict_no_r3b": {
            "phi_0p25_central": sc_25["strict_rows"],
            "phi_0p50_harsh_stress": sc_50["strict_rows"],
        },
        "ineligible_full_cocktail_diagnostics_zero_ev_weight": {
            "scope_warning": (
                "DIAGNOSTIC ONLY — INELIGIBLE UNDER LOCKED POLICY OPTION 1 (0.0000 pp EV WEIGHT): "
                "When a full SHIELD cocktail succeeds, Track-B finite host reset is ineligible (option1_eligible=false) "
                "and carries strictly 0.0000 pp Policy Option 1 EV weight. These 4 strict-route (zero-R3B) diagnostic "
                "rows per phi_c are segregated out of headline_live_eligible_scenarios_strict_no_r3b and retained "
                "solely for overlap-damping sensitivity and the legal 0.003 checkerboard fragility proof."
            ),
            "phi_0p25_central": sc_25["ineligible_full_cocktail_diag_rows"],
            "phi_0p50_harsh_stress": sc_50["ineligible_full_cocktail_diag_rows"],
        },
        "parked_counterfactual_r3b_sensitivity_exp029_gy027_block": {
            "scope_warning": (
                "PARKED COUNTERFACTUAL ONLY: EXP-029 (ROUTE_3B_ACTIVE_IEOG) is parked under active GY-027 BLOCK "
                "with unregistered route status. Strict live-eligible totals mask R3B (W_U3=57.5945%, W_U4=56.8730%)."
            ),
            "phi_0p25_central": sc_25["parked_r3b_rows"],
            "phi_0p50_harsh_stress": sc_50["parked_r3b_rows"],
        },
        "omega_sweep_full_band": {
            "strict_live_eligible_no_r3b": {"phi_0p25": sc_25["omega_sweep_strict"], "phi_0p50": sc_50["omega_sweep_strict"]},
            "parked_counterfactual_r3b": {"phi_0p25": sc_25["omega_sweep_parked_r3b"], "phi_0p50": sc_50["omega_sweep_parked_r3b"]},
        },
        "checkerboard_mass_transfer_stress_test": {
            "disclosure": (
                "Scenario-specific adverse stress test on the ineligible full-cocktail comparison: a legal 0.003 "
                "checkerboard mass transfer across 4 joint (m_cell, m_h4) cells involving only the 5th arm preserves "
                "all hurdle marginals and the full 4,096-state incumbent projection while shifting locked success by "
                "-0.3000 pp — flipping L4-AE slightly negative (-0.0569 pp vs L3B)."
            ),
            "parked_r3b_L4_AE_phi25": sc_25["checkerboard_parked_l4_ae"],
            "parked_r3b_L4_AE_phi50": sc_50["checkerboard_parked_l4_ae"],
            "strict_L3B_ZeroDrug_AE_phi25": sc_25["checkerboard_strict_l3b_ae"],
            "strict_L3B_ZeroDrug_AE_phi50": sc_50["checkerboard_strict_l3b_ae"],
        },
        "strategic_finite_reset_overlap_analysis": {
            "computation_precision": "computed_from_unrounded_exact_probabilities_before_4dp_display_rounding",
            "phi_0p25": d25_all["rounded_4dp"],
            "phi_0p50": d50_all["rounded_4dp"],
        },
        "policy_option1_trackb_eligibility_corrected_ev": {
            "eligibility_rule": CANONICAL_TRACKB_ELIGIBILITY_RULE,
            "current_gate_state": {
                "gate30_atg_xreact": "PENDING",
                "gate30_shield_spr": "PENDING",
                "owner_reauthorization": "PENDING_NOT_GRANTED",
            },
            "current_p_owner_reauth": 0.0,
            "current_p_hold_or_pending": 1.0,
            "current_active_ev_pp": 0.0,
            "scenario_ev_classification": "CONDITIONAL_SCENARIO_GIVEN_OWNER_REAUTH_AND_NO_HOLD",
            "joint_hold_and_owner_reauth_sensitivity": joint_hold_and_owner_reauth_sensitivity,
            "strict_live_eligible_zero_sort_guard_primary": ev_strict_zero_sort_guard,
            "strict_live_eligible_with_sort_guard_sensitivity": ev_strict_with_sort_guard_sens,
            "legacy_parked_r3b_comparator_eligibility_audit": ev_legacy_r3b_eligibility_audit,
        },
        "honest_stage0_foundry_unconditional_ev": honest_stage0_foundry,
        "bpr05_cross_stage_dependence_sensitivity": {
            "audit_id": "BPR-05",
            "method": (
                "Exact LP bounds over permissible joint couplings of earlier survivors (M_cell = H1&H2&H3) and "
                "final-route successes (M_h4 = H4) conditioned on stage-level shared ceilings passing, holding "
                "published stage distributions, shared ceilings, and all individual full-path arm successes fixed "
                "(plus full 4-stage 3-incumbent joint history in 5-arm scenarios)."
            ),
            "L0_CORE_3ARM": bpr05_l0_core,
            "L3B_STACK_STRICT_100PCT_ZERO_DRUG_phi_0p25": sc_25["bpr05_5arm_sensitivities"]["L3B_STACK_STRICT_100PCT_ZERO_DRUG"],
            "L3A_STRICT_ZERODRUG_PLUS_RESET_OMEGA_0P60_phi_0p25": sc_25["bpr05_5arm_sensitivities"]["L3A_STRICT_ZERODRUG_PLUS_RESET_OMEGA_0P60"],
        },
    }
    receipt["portable_payload_sha256"] = compute_portable_payload_sha256(receipt)
    return receipt


def build_portable_receipt_payload(receipt: dict[str, Any]) -> dict[str, Any]:
    """Return a cross-build semantic projection of the IIP-0042 receipt omitting ONLY
    runtime_environment.python_version (the CPython build banner/date string) and
    portable_payload_sha256 itself, while retaining python_version_info and every numeric,
    parity, self-test, and quarantine field verbatim.
    """
    proj = dict(receipt)
    proj.pop("portable_payload_sha256", None)
    if isinstance(proj.get("runtime_environment"), dict):
        rt = dict(proj["runtime_environment"])
        rt.pop("python_version", None)
        proj["runtime_environment"] = rt
    return proj


def compute_portable_payload_sha256(receipt: dict[str, Any]) -> str:
    proj = build_portable_receipt_payload(receipt)
    raw = json.dumps(proj, sort_keys=True, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode("utf-8")
    return hashlib.sha256(raw).hexdigest()


def verify_portable_receipt_file(existing_path: Path, fresh_receipt: dict[str, Any]) -> str:
    """Fail-closed cross-build receipt check ignoring ONLY runtime_environment.python_version."""
    if not existing_path.is_file():
        raise FileNotFoundError(
            f"--check-portable failed (fail-closed): expected receipt missing: {existing_path.name}"
        )
    existing_receipt = load_strict_json_text(existing_path.read_text(encoding="utf-8"), existing_path.name)
    if not isinstance(existing_receipt, dict) or not isinstance(existing_receipt.get("runtime_environment"), dict):
        raise RuntimeError(
            f"--check-portable failed (fail-closed): malformed receipt structure in {existing_path.name}"
        )
    existing_pyver = existing_receipt["runtime_environment"].get("python_version")
    if not isinstance(existing_pyver, str) or not existing_pyver.strip():
        raise RuntimeError(
            f"--check-portable failed (fail-closed): missing/non-string runtime_environment.python_version in {existing_path.name}"
        )
    existing_portable_sha = compute_portable_payload_sha256(existing_receipt)
    fresh_portable_sha = compute_portable_payload_sha256(fresh_receipt)
    if (
        build_portable_receipt_payload(existing_receipt) != build_portable_receipt_payload(fresh_receipt)
        or existing_portable_sha != fresh_portable_sha
    ):
        raise RuntimeError(
            f"--check-portable failed (fail-closed): semantic receipt mismatch outside "
            f"runtime_environment.python_version for {existing_path.name} "
            f"(existing_portable_sha={existing_portable_sha}, fresh_portable_sha={fresh_portable_sha})"
        )
    if "portable_payload_sha256" in existing_receipt and existing_receipt["portable_payload_sha256"] != fresh_portable_sha:
        raise RuntimeError(
            f"--check-portable failed (fail-closed): embedded portable_payload_sha256 mismatch in {existing_path.name} "
            f"(embedded={existing_receipt['portable_payload_sha256']}, fresh={fresh_portable_sha})"
        )
    return fresh_portable_sha


def main() -> None:
    parser = argparse.ArgumentParser(
        description="EXP-030 / IIP-0042 Master Exact 2^20 Portfolio & Crosswalk Verifier (Fail-Closed)"
    )
    parser.add_argument("--repo-root", default=None, help="Path to read-only OpenIslet repo")
    mode_group = parser.add_mutually_exclusive_group()
    mode_group.add_argument(
        "--standalone",
        action="store_true",
        help="Verify exact 2^20 engine + pinned live IIP-0035 parity only (mutually exclusive with --cross-track-dir)",
    )
    mode_group.add_argument(
        "--cross-track-dir",
        default=None,
        help="Directory containing EXP-028 and archived EXP-029 folders (mutually exclusive with --standalone)",
    )
    pin_group = parser.add_mutually_exclusive_group()
    pin_group.add_argument(
        "--expected-shipped-sha256",
        default=None,
        help="Optional explicit SHA-256 digest override for live shipped IIP-0035 portfolio fixture (defaults to canonical pinned 31320c0e...)",
    )
    pin_group.add_argument(
        "--allow-unpinned-diagnostic",
        action="store_true",
        help="Explicit diagnostic opt-in permitting unpinned IIP-0035 fixture bytes (disabled by default; fail-closed otherwise)",
    )
    parser.add_argument(
        "--expected-exp028-sha256",
        default=None,
        help="Optional pinned SHA-256 digest for EXP-028 verification receipt (verified before parity)",
    )
    parser.add_argument(
        "--expected-exp029-sha256",
        default=None,
        help="Optional pinned SHA-256 digest for archived EXP-029 verification receipt (verified before parity)",
    )
    parser.add_argument(
        "--out",
        default=None,
        help="Optional output receipt path (defaults to data/extracted/iip0042_master_multilayer_portfolio_crosswalk_v0.8.0.json)",
    )
    parser.add_argument(
        "--check-portable",
        action="store_true",
        help=(
            "Read-only cross-build verification mode: compares freshly computed receipt against --out "
            "(defaulting to the installed receipt) ignoring ONLY runtime_environment.python_version "
            "(verifying exact portable_payload_sha256 and full semantic equality across CPython builds) "
            "without writing."
        ),
    )
    args = parser.parse_args()

    if args.standalone and (args.expected_exp028_sha256 or args.expected_exp029_sha256):
        parser.error("--expected-exp028-sha256 and --expected-exp029-sha256 cannot be combined with --standalone")

    openislet_root = resolve_openislet_root(args.repo_root)
    ct_dir = Path(args.cross_track_dir) if args.cross_track_dir else None
    if args.out:
        out_path = Path(args.out).expanduser().resolve()
    elif args.check_portable and args.repo_root is not None:
        out_path = openislet_root / "data" / "extracted" / "iip0042_master_multilayer_portfolio_crosswalk_v0.8.0.json"
    else:
        out_path = RECEIPT_PATH

    receipt = run_all(
        openislet_root,
        standalone=args.standalone,
        cross_track_dir=ct_dir,
        expected_shipped_sha256=args.expected_shipped_sha256,
        expected_exp028_sha256=args.expected_exp028_sha256,
        expected_exp029_sha256=args.expected_exp029_sha256,
        allow_unpinned_diagnostic=args.allow_unpinned_diagnostic,
    )
    # Run full authenticated public manifest inventory + Wave-5 4-class Gate 30-TOS-QUARANTINE scan (no double-counting!)
    extra_texts: dict[str, str] = {}
    if ART_DIR.name == "artifacts-carbon":
        extra_texts[Path(__file__).name] = Path(__file__).read_text(encoding="utf-8")
        for pub_path in (
            ART_DIR / "exp030_iip0043_side_contract.json",
            ART_DIR / "GATE-30-PORTFOLIO-AND-TRACKB-CONTINGENCY-PROTOCOL.md",
            ART_DIR.parent / "confirmation-carbon-2026-11-28.md",
            INV_ROOT / "candidate-proposals" / "CAND-033-finite-host-reset-and-unified-multilayer-portfolio-carbon.md",
        ):
            if not pub_path.is_file():
                raise FileNotFoundError(f"Gate 30-TOS-QUARANTINE: missing required staging public document {pub_path.name}")
            txt = pub_path.read_text(encoding="utf-8")
            if pub_path.suffix == ".md":
                txt = mask_canonical_layer2_disclaimer_only(txt)
            extra_texts[pub_path.name] = txt

    quarantine_audit = verify_gate30_tos_quarantine_full_inventory(
        openislet_root,
        extra_wave5_texts=extra_texts if extra_texts else None,
    )
    portable_quarantine_audit = dict(quarantine_audit)
    portable_quarantine_audit["inventory_source"] = "manifest_json_verified"
    portable_quarantine_audit["manifest_scan_mode"] = "PUBLIC_ALLOWLIST_MANIFEST"
    portable_quarantine_audit["public_disk_membership_scope"] = "PUBLIC_BUNDLE_ROOT_OR_ALLOWLIST_TREE_VERIFIED"
    portable_quarantine_audit.pop("manifest_file_sha256", None)
    portable_quarantine_audit["manifest_file_sha256_scope"] = (
        "OMITTED_FROM_PORTABLE_RECEIPT_TO_AVOID_MANIFEST_SELF_HASH_CYCLE; "
        "returned directly by verify_gate30_tos_quarantine_full_inventory()"
    )
    receipt["gate30_tos_quarantine_audit"] = portable_quarantine_audit
    receipt["portable_payload_sha256"] = compute_portable_payload_sha256(receipt)
    out_str = json.dumps(receipt, indent=2, ensure_ascii=False, allow_nan=False) + "\n"
    assert_public_hygiene_clean(out_str, out_path.name)

    if args.check_portable:
        fresh_portable_sha = verify_portable_receipt_file(out_path, receipt)
        print(
            f"PASS (--check-portable cross-build semantic match ignoring runtime_environment.python_version): "
            f"receipt={out_path.name} portable_payload_sha256={fresh_portable_sha} "
            f"py={sys.version_info[0]}.{sys.version_info[1]}.{sys.version_info[2]} (optimize={sys.flags.optimize})"
        )
        return

    out_path.write_text(out_str, encoding="utf-8")

    p = receipt["parity_verification"]
    if args.standalone:
        print(
            f"=== STANDALONE PARITY PASS: 24/24 LIVE IIP-0035 EXACT (4-dp display) | "
            f"L0-raw-err={p['l0_live_unrounded_max_abs_err']:.2e} | "
            f"4096-err={p['l1_phi25_4096_state_max_abs_err']:.2e} | py={sys.version_info[0]}.{sys.version_info[1]}.{sys.version_info[2]} ==="
        )
    else:
        p29 = p["exp029_parked_archive_cross_track_parity"]
        raw29_str = f"{p29['raw_unrounded_max_abs_err']:.2e}" if p29["raw_unrounded_max_abs_err"] is not None else "N/A"
        print(
            f"=== FULL CROSS-TRACK PARITY PASS: 24/24 SHIPPED EXACT (4-dp display) | "
            f"L0-raw-err={p['l0_live_unrounded_max_abs_err']:.2e} | "
            f"4096-err={p['l1_phi25_4096_state_max_abs_err']:.2e} | "
            f"EXP-028 verified={p['exp028_cross_track_parity']['verified']} err={p['exp028_cross_track_parity']['unrounded_max_abs_err']:.2e} | "
            f"EXP-029(parked) verified={p29['verified']} raw_err={raw29_str} disp4dp_diff={p29['display_4dp_max_abs_diff']:.2e} | "
            f"py={sys.version_info[0]}.{sys.version_info[1]}.{sys.version_info[2]} ==="
        )
    cb = receipt["checkerboard_mass_transfer_stress_test"]["parked_r3b_L4_AE_phi25"]
    print(
        f"=== CHECKERBOARD (0.003) L4-AE phi=0.25: indep={cb['independent_delta_vs_baseline_pp']:+.4f} pp -> "
        f"coupled={cb['coupled_delta_vs_baseline_pp']:+.4f} pp (flips_negative={cb['flips_sign_negative']}) ==="
    )
    elig_row = next(
        r for r in receipt["policy_option1_trackb_eligibility_corrected_ev"]["legacy_parked_r3b_comparator_eligibility_audit"]
        if r["p_shield1_pass"] == 0.30 and r["p_cocktail_pass_trackb_ineligible_zero_credit"] == 0.12
    )
    print(
        f"=== ELIGIBILITY CHECK (p_S1=0.30, p_cock=0.12, P_XREACT=1.00): "
        f"gross={elig_row['ev_conditional_on_xreact_pass_1p0_upside_phi25_pp']:+.4f} pp | "
        f"AE={elig_row['ev_conditional_on_xreact_pass_1p0_AE_phi25_pp']:+.4f} pp ==="
    )
    sha = hashlib.sha256(out_path.read_bytes()).hexdigest()
    print(f"Wrote {out_path.name} (SHA-256: {sha})")


if __name__ == "__main__":
    main()
