#!/usr/bin/env python3
"""
OpenIslet Wave-6 Round-14 Prospective Candidate W6-C2 (Staged Slot IIP-0047 -> Provisional
IIP-0056 / DEC-137 / GATE-35 / GY-034; Preserving Live IIP-0047/DEC-127, Live GATE-32/DEC-130
Islet-SHIELD Debris Recall, Live GATE-33/DEC-131 hTMPK/AZT PK, and Live GY-032) Verification Engine
====================================================================================================
Prospective Stage-0 Head-to-Head Visceral R4-Omentum Candidate vs Incumbent Route 3P
(GY-027(1) Clean, Canonical Arm Manifest Enforced, GMP Plasma-Thrombin / Resorbable Fibrin,
40-65 um Sieved Clusters in Staggered Bilayer H=100-120 um with |z_c|>=20 um & Live GY-028
Confocal Wall Clearance H/2 - |z_c| - d_max/2 >= 7.5 um Minimum, Actual Max-Leaf Steric Packing,
Per-Leaf Measured Area/IEQ Reconciliation, Scope-Bound scale_mode, & Matrix Coverage,
Tier-1 [<=1,200 IEQ/cm^2 @ min bilateral bed >=35 mmHg & fibrin <=10 um] UNION
Tier-2 [<=1,500 IEQ/cm^2 @ min bilateral bed >=40 mmHg & fibrin <=12 um],
Lot OCR <=1.097x, Face/Core O2 >=15/5 mmHg; +0.00 pp live odds credit pending Stage-0/1 clearance)
+ Demotion of R4-SARS-Free to Secondary Backup (SubARS Clinical Collapse Proof,
  <=1,200 IEQ/cm^2 planar carrier, Dual-FailSafe Y-v3 / Z-EnSC ONLY; D1b barred)
+ Kill of In-Vivo 72-h Diazoxide Under GY-014 & Salvage as H4-6-ExVivo
  (Primary H4 credit = 0.000 pending paired wet-lab; +1.5 pp sensitivity on all
   eligible non-A arms B/X/Y/D/Z; Design A strictly frozen with zero drugs, zero
   ex-vivo rest, and zero additional biologics beyond pre-existing passive
   CaO2-PDMS + >=20 um planar P04040 catalase hydrogel)
+ External Hash-Verified Wave-6 Master Contract & Canonical Arm Manifest Parity
  (<1e-12 unrounded float64 AND exact 4-decimal display; paired discovery; explicit
   separation of conditional C2-given-C1 +4.4782 pp vs combined C1+C2 +6.4772 pp)
+ Fail-Closed Gate-35 Adjudicator with v2_round5_unified Trusted Upstream (GATE-34, GATE-0V,
  Live Blueprint Section 7 GATE-5 OQ-012) & Current-Assay (GATE-35) Archived Receipts:
  - Collision-free gate sources: upstream W6-C1 MUST be GATE-34 (rejecting live GATE-32
    role collision); current-assay record MUST be GATE-35 (rejecting live GATE-33 collision).
  - Live Blueprint Section 7 Gate 5 OQ-012 exact-Decimal stringency: survivor_count_k == 0
    (ANY k >= 1 -> FAIL), explicit tested_cells_n, clonogenic_fraction_f in (0, 1],
    spike_in_detection_efficiency_eta in [0.30, 1.0] (<0.30 -> FAIL), effective_clonogenic_trials_n_eff
    <= floor(n*f*eta), omitted recovery denominator -> HOLD, k==0 & n_eff < 299,573,228 -> HOLD,
    clinical PASS requires k==0, n_eff >= 299,573,228, and exact 75-digit Decimal U95 <= 1e-8.
  - Decoupled partial-responder post-explant C-peptide extinction (paired pre-explant > LLOQ
    dropping to post-explant <= LLOQ within exact Decimal [0, 14] days) vs full insulin
    independence (residual_exogenous_insulin_u_kg_d == 0).
  - Primary live DEC-009 0-NHP primate-free pathway (porcine R4O-04 + Pillars 1-3) alongside
    conditional FDA CBER INTERACT/Pre-IND exception NHP cohort (fail-closed whenever NHP records supplied).
  - End-to-end exact context-independent Decimal arithmetic across ALL policy thresholds (zero float()).

Strictly READ-ONLY on OpenIslet,
OpenIslet-Website, and shared/.
Zero ast.Assert nodes (100% fail-closed under both -B and -O -B).
Zero wetlab_contract / ingest_wetlab_results imports (Zero-LIMS-Touch).
Zero network calls at runtime.

Run examples:
  PYTHONDONTWRITEBYTECODE=1 python3 -B \\
    scripts/verify_iip0056_route4_omentum_and_exvivo_rest.py --standalone
  PYTHONDONTWRITEBYTECODE=1 python3 -O -B \\
    scripts/verify_iip0056_route4_omentum_and_exvivo_rest.py --standalone --check
  PYTHONDONTWRITEBYTECODE=1 python3 -O -B \\
    scripts/verify_iip0056_route4_omentum_and_exvivo_rest.py --standalone --check-portable
"""
from __future__ import annotations

import argparse
from decimal import Context, Decimal, DecimalException, InvalidOperation, MAX_EMAX, localcontext
from fractions import Fraction
import hashlib
import json
import math
import re
import sys
import time
import unicodedata
from pathlib import Path
from typing import Any, Callable, Dict, FrozenSet, List, Mapping, Optional, Sequence, Tuple

import numpy as np

sys.dont_write_bytecode = True

SCRIPT_PATH = Path(__file__).resolve()
PKG_ROOT = SCRIPT_PATH.parents[1]
DEFAULT_OUT_PATH = PKG_ROOT / "data" / "extracted" / "iip0056_route4_omentum_and_exvivo_rest_v0.9.0.json"


def resolve_release_relative_contract_path(filename: str) -> Path:
    """Resolve contract/manifest across staged (../shared) and flattened (data/protocols, shared) checkouts."""
    script_dir = Path(__file__).resolve().parent
    pkg_root = script_dir.parent
    candidates = [
        pkg_root.parent / "shared" / filename,
        pkg_root / "data" / "protocols" / filename,
        pkg_root / "shared" / filename,
    ]
    for cand in candidates:
        if cand.is_file():
            return cand
    return candidates[0]


def resolve_paired_contract_paths(
    master_contract_path: Optional[Path] = None,
    manifest_path: Optional[Path] = None,
) -> Tuple[Path, Path]:
    """Resolve paired master-contract & arm-manifest paths fail-closed (Review Shared #4).

    - When master_contract_path is explicitly provided without manifest_path, resolve
      wave6_canonical_arm_manifest.json STRICTLY as its sibling in master_contract_path.parent
      (fail closed if missing; never fall back to stage-relative).
    - When neither is provided, discover wave6_master_contract.json across supported
      release layouts [../shared, data/protocols, shared] and use its sibling manifest.
    - When manifest_path is explicitly provided, honor it as an explicit override.
    """
    if master_contract_path is not None:
        c_path = master_contract_path.expanduser().resolve()
        m_path = (
            manifest_path.expanduser().resolve()
            if manifest_path is not None
            else c_path.parent / "wave6_canonical_arm_manifest.json"
        )
    else:
        c_path = resolve_release_relative_contract_path("wave6_master_contract.json")
        m_path = (
            manifest_path.expanduser().resolve()
            if manifest_path is not None
            else c_path.parent / "wave6_canonical_arm_manifest.json"
        )
    return c_path, m_path


DEFAULT_MASTER_CONTRACT_PATH, DEFAULT_ARM_MANIFEST_PATH = resolve_paired_contract_paths()

SCHEMA_VERSION = "iip0056_route4_omentum_and_exvivo_rest_v0.9.0_r14"
UPSTREAM_RECEIPT_SCHEMA_REVISION = "v2_round5_unified"
STAGED_SLOT_ID = "IIP-0047"
CONTRIBUTION_ID = "IIP-0056"
DECISION_ID = "DEC-137"
GATE_ID = "GATE-35"
UPSTREAM_W6C1_GATE_SOURCE = "GATE-34"
GRAVEYARD_ID = "GY-034"

EXPECTED_CANONICAL_MANIFEST_SHA256 = "0a051b69687bd791feeaf55e97c07d993e27cdd7c453e6e3b67b599d243a4235"
EXPECTED_CANONICAL_MANIFEST_CANONICAL_JSON_SHA256 = "9e84e0b64925f9fdeb9450b364728a4076fa43cf8b46085ba2215722541f0d50"
EXPECTED_MASTER_CONTRACT_FILE_SHA256 = "2108aa272bfe657c2767ba0f10961443fa280d5f074a84d5578d42c204fff35a"
EXPECTED_MASTER_CONTRACT_PAYLOAD_SHA256 = "53f90447f1f32213adff883f26d30aa1268f4848e6d3d1d946c03d9c7c8a8b42"
EXPECTED_MASTER_CONTRACT_SHA256 = EXPECTED_MASTER_CONTRACT_PAYLOAD_SHA256

MAX_SAFE_INT_ABS = 10 ** 100
MAX_SAFE_FLOAT_ABS = 1e100
MAX_SAFE_DECIMAL_ABS = Decimal("1e100")
MAX_SAFE_DECIMAL_ADJUSTED = 100
MIN_SAFE_DECIMAL_ADJUSTED = -10_000
MIN_GATE5_TESTED_CELLS = 1
MIN_GATE5_EFFECTIVE_TRIALS = 299_573_228
MIN_GATE5_DETECTION_EFFICIENCY_ETA_DEC = Decimal("0.30")
MAX_GATE5_OQ012_U95_DEC = Decimal("1e-8")
MAX_CLONOGENIC_CELLS = 10 ** 12
MIN_GY028_WALL_CLEARANCE_UM_DEC = Decimal("7.5")
MIN_RESIDUAL_SAMPLING_FRACTION = 0.01
SINGLE_LEAF_MAX_TOTAL_IEQ = 100_000.0
ZERO_DEC = Decimal("0")
ONE_DEC = Decimal("1")
MIN_RESIDUAL_SAMPLING_FRACTION_DEC = Decimal("0.01")
SINGLE_LEAF_MAX_TOTAL_IEQ_DEC = Decimal("100000")

# Pinned canonical NW-08 / Layer-4 / IIP-0034 biophysical constants
PINNED_NW08_CONSTANTS: Dict[str, Any] = {
    "alpha_o2_nominal_mol_cm3_mmhg": 1.34e-9,
    "alpha_o2_krbh_mol_cm3_mmhg": 1.27e-9,
    "d_o2_gel_chronic_cm2_s": 1.50e-5,
    "d_o2_gel_acute_cm2_s": 0.940254e-5,
    "d_o2_islet_cm2_s": 1.30e-5,
    "d_o2_fibrin_0p5x_cm2_s": 0.75e-5,
    "vmax_islet_pure_mol_cm3_s": 3.40e-8,
    "km_o2_mmhg": 0.44,
    "po2_gsis_face_floor_mmhg": 15.0,
    "po2_core_floor_mmhg": 5.0,
    "po2_anoxia_floor_mmhg": 0.5,
    "vol_1_ieq_cm3": (4.0 / 3.0) * math.pi * ((75.0e-4) ** 3),
    "ocr_mult_nominal_stimulated": 1.097,
    "ocr_mult_nw08_vasc_stress": 1.097 * 1.20,
    "stromal_ocr_fraction": 0.15,
    "d_insulin_hydrogel_cm2_s": 5.0e-7,
    "d_insulin_free_interstitial_cm2_s": 1.0e-6,
    "insulin_intrinsic_t50_min": 1.75,
    "insulin_target_t50_min": 3.0,
}

# Exact low-D modeled matrix O2 diffusivity floor (SI m^2/s = cm^2/s * 1e-4)
D_O2_LOW_MODELED_CM2_S: float = float(PINNED_NW08_CONSTANTS["d_o2_gel_acute_cm2_s"])
D_O2_LOW_MODELED_M2_S: float = D_O2_LOW_MODELED_CM2_S * 1e-4  # 9.40254e-10 m^2/s
D_O2_MAX_AQUEOUS_M2_S: float = 3.5e-9  # physical upper bound (pure water O2 at 37 C ~2.5-3.0e-9 m^2/s)
D_O2_LOW_MODELED_M2_S_DEC: Decimal = Decimal("9.40254e-10")
D_O2_MAX_AQUEOUS_M2_S_DEC: Decimal = Decimal("3.5e-9")

# Pinned canonical IIP-0034 Route 3P 3D FVM references (nx=28, nz=32)
PINNED_IIP0034_REFS: Dict[str, float] = {
    "Hybrid333_H180_Day0_Clean_65um_PASS": 20.1252,
    "Hybrid333_H180_Day0_10umFibrin_0p5D_65um_FACE_FAIL": 14.7151,
    "Hybrid333_H180_Day0_15umFibrin_0p5D_65um": 12.0792,
    "Hybrid333_H180_Day0_Clean_65um_Bed30mmHg_Alpha1p27e9_FACE_FAIL": 14.4198,
}

# Live-verified PMID registry for IIP-0047
VERIFIED_PMIDS: List[str] = [
    "9535004",   # Grimmsmann & Rustenbeck 1998 Br J Pharmacol (DZ Complex II -29% ATP @ 500 uM, 1 datum)
    "17130499",  # Sweet & Gilbert 2006 Diabetes (Ca2+ influx / diazoxide -30% OCR in rat islets)
    "17503968",  # MacDonald et al. 2007 PLoS Biol (alpha-cell glucagon suppression >=30 uM DZ)
    "19276268",  # Verbrugge et al. 2009 Clin Cancer Res (APO010 hexameric FasL hepatotoxicity)
    "20541525",  # Lee et al. 2010 BBRC (TUDCA porcine islet chemical chaperone)
    "21054943",  # Svensson et al. 2011 Cell Transplant (striated muscle hypoxia/fibrosis vs renal)
    "21183510",  # Eisele et al. 2011 Neuro Oncol (APO010 FasL systemic window)
    "23935835",  # Ma et al. 2013 PLoS One (rat 22 h necrosis/OCR & hypoxia-associated apoptosis not reversed by DZ; human pilot 22 h/325 uM; human xenograft 48 h/325 uM 14 d mice)
    "24225943",  # Engin et al. 2013 Sci Transl Med (mouse TUDCA UPR restoration; author-spelling correction notice)
    "25194818",  # Lyon et al. 2014 Nat Biotechnol (maleimide retro-Michael plasma shedding)
    "28489987",  # Baidal et al. 2017 NEJM (N=1 omentum plasma-thrombin case report, NCT02213003)
    "29789532",  # Bruni et al. 2018 Cell Death Dis (Fer-1 tool compound, zero human IND)
    "32433410",  # Wang Y et al. 2020 Pancreas (8 h / 150 uM DZ whole NHP pancreas preservation -> diabetic mouse efficacy)
    "34735732",  # Van Hulle et al. 2022 AJT (N=7 omentum biopsy: ductal impurity + polyglactin FBR)
    "35227510",  # Saudek et al. 2022 Transplant Proc (N=2 omentum plasma-fibrin low 1-yr C-pep)
    "35241836",  # Balboa et al. 2022 Nat Biotechnol (SC-islet mitochondrial/KATP maturation gap)
    "35559682",  # Lei et al. 2022 Sci Adv (NHP omentum SA-FasL microgels comparator)
    "35676866",  # Verhoeff et al. 2022 Transplantation (N=264: 9 extrahepatic [4 om/3 subQ/2 gas], 1-3 mo pooled stimulated C-pep 0.05 vs 1.2 nmol/L)
    "36624157",  # Liang et al. 2023 Nat Metab (n=4 diabetic NHPs sub-ARS within n=8 total under xenogeneic IS)
    "36863336",  # Deng H et al. 2023 Cell Rep Med (n=3 NHP omentum: insulin through Day 28, 2/3 sustained II under IS)
    "38321214",  # Hu et al. 2024 Cell Death Differ (ISRIB tool compound, zero human IND)
    "38848367",  # Burke et al. 2024 Sci Adv (separate 4-animal PPCN-only ~20% visual residual @ 3 mo vs 2 partial-pancreatectomy+ablation autologous graft NHPs, 0/2 II)
    "39326417",  # Wang et al. 2024 Cell (N=1 sub-ARS CiPSC: 1.49M IEQ + chronic tacrolimus)
    "40544428",  # Reichman et al. 2025 NEJM (zimislecel intraportal benchmark under systemic IS)
]

_SHA256_HEX_RE = re.compile(r"^[0-9a-f]{64}$")
_CANONICAL_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$")
_STRICT_DECIMAL_STR_RE = re.compile(r"^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$")


# =============================================================================
# 0. Fail-Closed Helpers & Strict Duplicate-Key / Finite JSON Parsing
# =============================================================================
def require_cond(cond: bool, message: str) -> None:
    if not cond:
        raise RuntimeError(message)


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


def load_strict_json_text(text: str, source_name: str = "input") -> Any:
    """Fail-closed JSON parser rejecting duplicate keys & non-finite constants and preserving exact lexical
    decimal tokens via parse_float=Decimal (NEVER rounding through IEEE-754 float64; Audit R9-06).
    """
    def _no_dup_pairs(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 key {k!r} rejected (fail-closed) in {source_name}")
            out[k] = v
        return out

    def _no_nonfinite(tok: str) -> Any:
        raise ValueError(f"Non-finite JSON constant {tok!r} rejected (fail-closed) in {source_name}")

    def _parse_exact_decimal(tok: str) -> Decimal:
        try:
            dec = Decimal(tok)
        except (InvalidOperation, DecimalException) as exc:
            raise ValueError(f"Out-of-range or invalid JSON decimal {tok!r} rejected (fail-closed) in {source_name}") from exc
        if not dec.is_finite():
            raise ValueError(f"Non-finite JSON decimal {tok!r} rejected (fail-closed) in {source_name}")
        return dec

    return json.loads(
        text,
        object_pairs_hook=_no_dup_pairs,
        parse_float=_parse_exact_decimal,
        parse_constant=_no_nonfinite,
    )


def _is_strict_bool(val: Any) -> bool:
    return type(val) is bool


def _is_strict_int(val: Any) -> bool:
    return type(val) is int and abs(val) <= MAX_SAFE_INT_ABS


def _is_safe_decimal_magnitude(val: Decimal) -> bool:
    """100% context-independent Decimal finiteness and magnitude guard (Audit R10-05).

    Uses ONLY context-independent Decimal methods (is_finite, is_zero, adjusted, copy_abs)
    BEFORE any comparison so extreme finite exponents (e.g. 1e1000, 1e99999999, -1e99999999,
    1e-99999999, 9.999999999999999e+99999999) NEVER trigger decimal.Overflow/Underflow under
    ANY active Decimal context.
    """
    if not val.is_finite():
        return False
    if val.is_zero():
        return True
    adj = val.adjusted()
    if adj > MAX_SAFE_DECIMAL_ADJUSTED or adj < MIN_SAFE_DECIMAL_ADJUSTED:
        return False
    if adj == MAX_SAFE_DECIMAL_ADJUSTED:
        return val.copy_abs() <= MAX_SAFE_DECIMAL_ABS
    return True


def _is_finite_number(val: Any) -> bool:
    """Safe numeric check for int, float, and decimal.Decimal (never bool/str; context-independent bounds)."""
    if isinstance(val, bool):
        return False
    if type(val) is int:
        return abs(val) <= MAX_SAFE_INT_ABS
    if type(val) is float:
        return math.isfinite(val) and abs(val) <= MAX_SAFE_FLOAT_ABS
    if type(val) is Decimal:
        return _is_safe_decimal_magnitude(val)
    return False


def _to_exact_decimal(val: Any) -> Decimal:
    """Convert a validated finite Decimal, int, float, or exact finite decimal str to exact decimal.Decimal.

    Authoritative precision contract (Audit R9-06 / R10-05):
      - Decimal (including all JSON float tokens loaded via load_strict_json_text): checked with
        context-independent magnitude guard and returned verbatim (ZERO float(); zeros normalized to Decimal(0)).
      - int: bounded exact Decimal(val) (ZERO float()).
      - Exact decimal str (if invoked directly on a lexical token): bounded exact Decimal(val) (ZERO float()).
      - In-memory IEEE-754 float: bounded shortest round-trip Decimal(str(val)) (callers requiring sub-ULP < 1e-14
        precision MUST pass Decimal or parse raw JSON via load_strict_json_text).
    """
    if isinstance(val, bool):
        raise TypeError("bool is not a numeric Decimal value")
    if type(val) is Decimal:
        if not _is_safe_decimal_magnitude(val):
            raise ValueError(f"Non-finite or out-of-range Decimal rejected: {val!r}")
        return Decimal(0) if val.is_zero() else val
    if type(val) is int:
        if abs(val) > MAX_SAFE_INT_ABS:
            raise ValueError(f"Out-of-range int rejected: {val!r}")
        return Decimal(val)
    if type(val) is float:
        if not math.isfinite(val) or abs(val) > MAX_SAFE_FLOAT_ABS:
            raise ValueError(f"Non-finite or out-of-range float rejected: {val!r}")
        return Decimal(str(val))
    if type(val) is str:
        s = val.strip()
        if not s or s != val or not _STRICT_DECIMAL_STR_RE.fullmatch(s):
            raise ValueError(f"Invalid decimal string token rejected: {val!r}")
        try:
            dec = Decimal(s)
        except (InvalidOperation, DecimalException) as exc:
            raise ValueError(f"Unparseable decimal string token rejected: {val!r}") from exc
        if not _is_safe_decimal_magnitude(dec):
            raise ValueError(f"Non-finite or out-of-range decimal string token rejected: {val!r}")
        return Decimal(0) if dec.is_zero() else dec
    raise TypeError(f"Unsupported type for exact Decimal conversion: {type(val).__name__}")


def _dec_add(a: Decimal, b: Decimal) -> Decimal:
    """Exact, context-independent, zero-rounding Decimal sum (zero caller-context leakage)."""
    if not (a.is_finite() and b.is_finite()):
        raise ValueError("Non-finite Decimal operand in _dec_add")
    if a.is_zero():
        return ZERO_DEC if b.is_zero() else b
    if b.is_zero():
        return a
    t_a = a.as_tuple()
    t_b = b.as_tuple()
    exp_a = t_a.exponent if isinstance(t_a.exponent, int) else 0
    exp_b = t_b.exponent if isinstance(t_b.exponent, int) else 0
    hi = max(a.adjusted(), b.adjusted(), 0)
    lo = min(exp_a, exp_b, 0)
    needed = (hi - lo) + 16
    prec_use = max(120, needed)
    emax_use = min(MAX_EMAX, max(999_999, abs(hi) + 1000, abs(lo) + 1000))
    with localcontext(Context(prec=prec_use, Emax=emax_use, Emin=-emax_use)):
        return a + b


def _dec_sub(a: Decimal, b: Decimal) -> Decimal:
    """Exact, context-independent, zero-rounding Decimal difference (zero caller-context leakage)."""
    if not (a.is_finite() and b.is_finite()):
        raise ValueError("Non-finite Decimal operand in _dec_sub")
    if b.is_zero():
        return ZERO_DEC if a.is_zero() else a
    return _dec_add(a, b.copy_negate())


def _dec_mul(a: Decimal, b: Decimal) -> Decimal:
    """Exact, context-independent, zero-rounding Decimal product (zero caller-context leakage)."""
    if not (a.is_finite() and b.is_finite()):
        raise ValueError("Non-finite Decimal operand in _dec_mul")
    if a.is_zero() or b.is_zero():
        return ZERO_DEC
    t_a = a.as_tuple()
    t_b = b.as_tuple()
    exp_a = t_a.exponent if isinstance(t_a.exponent, int) else 0
    exp_b = t_b.exponent if isinstance(t_b.exponent, int) else 0
    needed = len(t_a.digits) + len(t_b.digits) + 16
    prec_use = max(120, needed)
    emax_use = min(MAX_EMAX, max(999_999, abs(a.adjusted()) + abs(b.adjusted()) + abs(exp_a) + abs(exp_b) + 1000))
    with localcontext(Context(prec=prec_use, Emax=emax_use, Emin=-emax_use)):
        return a * b


def _exact_sum3_gt_zero(x: Decimal, y: Decimal, z: Decimal) -> bool:
    """Exact, context-independent, zero-rounding test for (x + y + z) > 0 across ALL finite Decimals (Audit R10-05).

    Never overflows, underflows, or allocates extreme precision even on 1e99999999 / -1e99999999 /
    1e-99999999 or restricted caller contexts, while remaining 100% exact on sub-yoctosecond tokens.
    """
    for v in (x, y, z):
        if not v.is_finite():
            raise ValueError(f"Non-finite Decimal operand: {v!r}")
    nz = [v for v in (x, y, z) if not v.is_zero()]
    if not nz:
        return False
    if len(nz) == 1:
        return not nz[0].is_signed()
    if len(nz) == 2:
        return nz[0] > nz[1].copy_negate()
    nz.sort(key=lambda v: v.adjusted(), reverse=True)
    u, v, w = nz
    u_adj = u.adjusted()
    v_adj = v.adjusted()
    if u_adj - v_adj >= 2:
        return not u.is_signed()
    tu = u.as_tuple()
    tv = v.as_tuple()
    tw = w.as_tuple()
    shift = u_adj
    u_s = Decimal((tu.sign, tu.digits, tu.exponent - shift))
    v_s = Decimal((tv.sign, tv.digits, tv.exponent - shift))
    prec_need = max(len(tu.digits), len(tv.digits)) + 16
    emax_need = min(MAX_EMAX, max(1000, prec_need + 100))
    with localcontext(Context(prec=prec_need, Emax=emax_need, Emin=-emax_need)):
        s_s = u_s + v_s
    if s_s.is_zero():
        return not w.is_signed()
    s_neg = s_s.is_signed()
    w_neg = w.is_signed()
    if s_neg == w_neg:
        return not s_neg
    s_adj = s_s.adjusted() + shift
    w_adj = w.adjusted()
    if s_adj > w_adj:
        return not s_neg
    if s_adj < w_adj:
        return not w_neg
    w_s = Decimal((tw.sign, tw.digits, tw.exponent - shift))
    return s_s > w_s.copy_negate()


def _dec_diff_exceeds(a: Decimal, b: Decimal, bound: Decimal) -> bool:
    """Exact zero-rounding test for (a - b) > bound across arbitrary finite Decimals (even extreme exponents)."""
    if not (a.is_finite() and b.is_finite() and bound.is_finite()):
        raise ValueError("Non-finite Decimal operand in _dec_diff_exceeds")
    return _exact_sum3_gt_zero(a, b.copy_negate(), bound.copy_negate())


def _dec_abs_diff_exceeds(a: Decimal, b: Decimal, bound: Decimal) -> bool:
    """Exact zero-rounding test for |a - b| > bound across arbitrary finite Decimals."""
    hi_v, lo_v = (a, b) if a >= b else (b, a)
    return _dec_diff_exceeds(hi_v, lo_v, bound)


def _ratio_lt_dec(num: Decimal, den: Decimal, bound: Decimal) -> bool:
    """Exact zero-rounding test for (num / den) < bound with den > 0."""
    return num < _dec_mul(bound, den)


def _ratio_le_dec(num: Decimal, den: Decimal, bound: Decimal) -> bool:
    """Exact zero-rounding test for (num / den) <= bound with den > 0."""
    return num <= _dec_mul(bound, den)


def _ratio_gt_dec(num: Decimal, den: Decimal, bound: Decimal) -> bool:
    """Exact zero-rounding test for (num / den) > bound with den > 0."""
    return num > _dec_mul(bound, den)


def _ratio_ge_dec(num: Decimal, den: Decimal, bound: Decimal) -> bool:
    """Exact zero-rounding test for (num / den) >= bound with den > 0."""
    return num >= _dec_mul(bound, den)


def _ratio_gt_ratio(n1: Decimal, d1: Decimal, n2: Decimal, d2: Decimal) -> bool:
    """Exact zero-rounding test for (n1 / d1) > (n2 / d2) with d1 > 0 and d2 > 0."""
    return _dec_mul(n1, d2) > _dec_mul(n2, d1)


def _max_ratio(ratios: Sequence[Tuple[Decimal, Decimal]]) -> Tuple[Decimal, Decimal]:
    """Return exact maximum (num, den) pair from a non-empty sequence of positive-denominator Decimal ratios."""
    best = ratios[0]
    for cand in ratios[1:]:
        if _ratio_gt_ratio(cand[0], cand[1], best[0], best[1]):
            best = cand
    return best


def _ratio_rel_diff_exceeds(num: Decimal, den: Decimal, ref: Decimal, rel_tol: Decimal) -> bool:
    """Exact zero-rounding test for |(num / den) - ref| / ref > rel_tol with den > 0, ref > 0."""
    ref_den = _dec_mul(ref, den)
    return _dec_abs_diff_exceeds(num, ref_den, _dec_mul(rel_tol, ref_den))


def _dec_rel_diff_exceeds_ratio(claimed: Decimal, num: Decimal, den: Decimal, rel_tol: Decimal) -> bool:
    """Exact zero-rounding test for |claimed - (num / den)| / (num / den) > rel_tol with num > 0, den > 0."""
    return _dec_abs_diff_exceeds(_dec_mul(claimed, den), num, _dec_mul(rel_tol, num))


def _dec_to_display_float(val: Optional[Decimal]) -> Optional[float]:
    """Convert an exact Decimal to IEEE-754 float ONLY for metadata/display AFTER policy decisions."""
    if val is None or not val.is_finite():
        return None
    if val.is_zero():
        return 0.0
    adj = val.adjusted()
    if adj > 308:
        return None
    if adj < -324:
        return 0.0
    f = float(val)
    return f if math.isfinite(f) else None


def _dec_div_to_display_float(num: Decimal, den: Decimal) -> Optional[float]:
    """Convert an exact Decimal ratio num / den to IEEE-754 float ONLY for metadata/display AFTER policy decisions."""
    if not (num.is_finite() and den.is_finite()) or den.is_zero():
        return None
    if num.is_zero():
        return 0.0
    emax_use = min(MAX_EMAX, max(999_999, abs(num.adjusted()) + abs(den.adjusted()) + 1000))
    with localcontext(Context(prec=60, Emax=emax_use, Emin=-emax_use)):
        q = num / den
    return _dec_to_display_float(q)


def _is_literal_nonempty_str(val: Any) -> bool:
    return isinstance(val, str) and len(val) > 0 and val == val.strip()


def _is_canonical_id_str(val: Any) -> bool:
    """Strict ASCII canonical identifier: ^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$, isascii, NFKC==raw, zero C*/Z*/M*."""
    if not isinstance(val, str) or len(val) == 0 or len(val) > 64:
        return False
    if not val.isascii():
        return False
    if unicodedata.normalize("NFKC", val) != val:
        return False
    if any(unicodedata.category(ch)[0] in ("C", "Z", "M") for ch in val):
        return False
    return bool(_CANONICAL_ID_RE.fullmatch(val))


def _canonical_id_dedup_key(val: str) -> str:
    """NFKC-normalized, C*/Z*/M*-stripped, casefolded key for canonical subject/procedure duplicate detection."""
    norm = unicodedata.normalize("NFKC", val)
    stripped = "".join(ch for ch in norm if unicodedata.category(ch)[0] not in ("C", "Z", "M"))
    return stripped.casefold()


def _is_valid_sha256_hex(val: Any) -> bool:
    return isinstance(val, str) and bool(_SHA256_HEX_RE.match(val))


def _is_non_all_zero_sha256_hex(val: Any) -> bool:
    return _is_valid_sha256_hex(val) and val != ("0" * 64)


def _format_canonical_json_number(val: Any) -> str:
    """Lossless canonical JSON number token for int, float, and exact Decimal.

    - Exact IEEE-754 float64 values (including Decimals that round-trip losslessly to float64, e.g. 14.0,
      1.5e-05, 14.000000000000000) serialize identically to json.dumps(float, allow_nan=False), preserving
      100% SHA-256 parity with existing canonical manifests, contracts, receipts, and archives.
    - Any sub-ULP or beyond-float64 Decimal (e.g. 104.000000000000001, 14.000000000000001, 1e-400) preserves
      EVERY exact significant digit without rounding or collision (Audit R9-06).
    """
    if type(val) is int:
        return str(val)
    if type(val) is float:
        if not math.isfinite(val):
            raise ValueError(f"Out of range float value is not JSON compliant: {val!r}")
        return json.dumps(val, allow_nan=False)
    if type(val) is Decimal:
        if not val.is_finite():
            raise ValueError(f"Out of range Decimal value is not JSON compliant: {val!r}")
        if val.is_zero():
            return "-0.0" if val.is_signed() else "0.0"
        adj = val.adjusted()
        if -324 <= adj <= 308:
            f = float(val)
            if math.isfinite(f) and Decimal(repr(f)) == val and (val.is_signed() == (math.copysign(1.0, f) < 0.0)):
                return json.dumps(f, allow_nan=False)
        sign, digits, exp = val.as_tuple()
        if not isinstance(exp, int):
            raise ValueError(f"Non-finite Decimal value is not JSON compliant: {val!r}")
        if all(dg == 0 for dg in digits):
            return "-0.0" if sign else "0.0"
        end = len(digits)
        if exp < 0:
            while end > 1 and digits[end - 1] == 0 and exp < 0:
                end -= 1
                exp += 1
        elif exp > 0:
            while end > 1 and digits[end - 1] == 0:
                end -= 1
                exp += 1
        d_norm = Decimal((sign, digits[:end], exp))
        return str(d_norm).lower()
    raise TypeError(f"Object of type {type(val).__name__} is not a JSON number")


def canonical_json_dumps(obj: Any) -> str:
    """Deterministic canonical JSON serializer supporting exact Decimal without precision loss (Audit R9-06)."""
    if obj is None:
        return "null"
    if type(obj) is bool:
        return "true" if obj else "false"
    if type(obj) in (int, float, Decimal):
        return _format_canonical_json_number(obj)
    if type(obj) is str:
        return json.dumps(obj, ensure_ascii=False)
    if isinstance(obj, (list, tuple)):
        return "[" + ",".join(canonical_json_dumps(x) for x in obj) + "]"
    if isinstance(obj, Mapping):
        items: List[str] = []
        for k in sorted(obj.keys()):
            if type(k) is not str:
                raise TypeError(f"Canonical JSON object key must be str, got {type(k).__name__}")
            items.append(json.dumps(k, ensure_ascii=False) + ":" + canonical_json_dumps(obj[k]))
        return "{" + ",".join(items) + "}"
    raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")


def _canonical_json_sha256(obj: Any) -> str:
    raw = canonical_json_dumps(obj).encode("utf-8")
    return sha256_bytes(raw)


def _fmt_sci_float(val: float) -> float:
    return float(f"{float(val):.4e}")


def _strict_json_equal(a: Any, b: Any) -> bool:
    """Strict type- and exact-Decimal-value-aware JSON equality (bool never equals int; rejects non-finite; ZERO float rounding)."""
    if type(a) is bool or type(b) is bool:
        return type(a) is type(b) and a is b
    if isinstance(a, (int, float, Decimal)) and isinstance(b, (int, float, Decimal)):
        if not (_is_finite_number(a) and _is_finite_number(b)):
            return False
        return _to_exact_decimal(a) == _to_exact_decimal(b)
    if type(a) is not type(b):
        return False
    if isinstance(a, list):
        return len(a) == len(b) and all(_strict_json_equal(x, y) for x, y in zip(a, b))
    if isinstance(a, dict):
        return set(a.keys()) == set(b.keys()) and all(_strict_json_equal(a[k], b[k]) for k in a.keys())
    return bool(a == b)


def _init_decimal_gamma_constants() -> Tuple[Tuple[Decimal, ...], Decimal]:
    """Precompute exact Stirling coefficients B_{2j}/(2j*(2j-1)) and 0.5*ln(2*pi) at 80-digit Decimal precision."""
    with localcontext(Context(prec=85, Emax=999_999, Emin=-999_999)):
        a_row: List[Fraction] = []
        coeffs: List[Decimal] = []
        for m in range(51):
            a_row.append(Fraction(1, m + 1))
            for j in range(m, 0, -1):
                a_row[j - 1] = j * (a_row[j - 1] - a_row[j])
            if m >= 2 and m % 2 == 0:
                bm = a_row[0]
                coeffs.append(Decimal(bm.numerator) / Decimal(bm.denominator * m * (m - 1)))

        def _atan_inv(inv_x: int) -> Decimal:
            x2 = Decimal(inv_x * inv_x)
            term = Decimal(1) / Decimal(inv_x)
            total = term
            idx = 1
            while term != 0:
                term = -term / x2
                add = term / (2 * idx + 1)
                if add == 0:
                    break
                total += add
                idx += 1
            return total

        pi_d = Decimal(16) * _atan_inv(5) - Decimal(4) * _atan_inv(239)
        half_ln_2pi = Decimal("0.5") * (Decimal(2) * pi_d).ln()
    return tuple(coeffs), half_ln_2pi


_STIRLING_COEFFS_DEC, _HALF_LN_2PI_DEC = _init_decimal_gamma_constants()


def _lgamma_pos_int_dec(n_int: int) -> Decimal:
    """High-precision ln(Gamma(n_int)) in active Decimal context (accurate to < 1e-55 for all n_int >= 1)."""
    shift_prod = 1
    x_int = n_int
    while x_int < 60:
        shift_prod *= x_int
        x_int += 1
    x = Decimal(x_int)
    inv_x = Decimal(1) / x
    inv_x2 = inv_x * inv_x
    series = Decimal(0)
    p_inv = inv_x
    eps_term = Decimal("1e-62")
    for coeff in _STIRLING_COEFFS_DEC:
        term = coeff * p_inv
        series += term
        p_inv *= inv_x2
        if abs(term) < eps_term:
            break
    res = (x - Decimal("0.5")) * x.ln() - x + _HALF_LN_2PI_DEC + series
    if shift_prod > 1:
        res -= Decimal(shift_prod).ln()
    return res


def _betacf_dec(a: Decimal, b: Decimal, x: Decimal) -> Decimal:
    """Modified Lentz continued fraction for regularized incomplete beta I_x(a, b) in active Decimal context."""
    max_iter = 200_000
    eps = Decimal("1e-45")
    fpmin = Decimal("1e-300")
    one = Decimal(1)
    qab = a + b
    qap = a + one
    qam = a - one
    c = one
    d = one - qab * x / qap
    if abs(d) < fpmin:
        d = fpmin
    d = one / d
    h = d
    for m in range(1, max_iter + 1):
        m2 = 2 * m
        aa = m * (b - m) * x / ((qam + m2) * (a + m2))
        d = one + aa * d
        if abs(d) < fpmin:
            d = fpmin
        c = one + aa / c
        if abs(c) < fpmin:
            c = fpmin
        d = one / d
        h *= d * c
        aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
        d = one + aa * d
        if abs(d) < fpmin:
            d = fpmin
        c = one + aa / c
        if abs(c) < fpmin:
            c = fpmin
        d = one / d
        delta = d * c
        h *= delta
        if abs(delta - one) <= eps:
            return h
    raise RuntimeError(f"Decimal incomplete beta continued fraction did not converge (a={a}, b={b}, x={x})")


def _reg_inc_beta_and_pdf_dec(
    k_plus_1: int, n_minus_k: int, x: Decimal, log_beta_inv: Decimal
) -> Tuple[Decimal, Decimal]:
    """High-precision regularized incomplete beta I_x(k+1, n-k) and d/dx I_x(k+1, n-k) in active Decimal context."""
    one = Decimal(1)
    if x <= 0:
        return Decimal(0), Decimal(0)
    if x >= one:
        return one, Decimal(0)
    a = Decimal(k_plus_1)
    b = Decimal(n_minus_k)
    log_bt = log_beta_inv + a * x.ln() + b * (one - x).ln()
    bt = Decimal(0) if log_bt < Decimal("-50000") else log_bt.exp()
    if x < (a + one) / (a + b + 2):
        ib = bt * _betacf_dec(a, b, x) / a
    else:
        ib = one - bt * _betacf_dec(b, a, one - x) / b
    pdf = bt / (x * (one - x))
    return ib, pdf


def clopper_pearson_u95_decimal(k: int, n: int, alpha: Any = Decimal("0.05")) -> Decimal:
    """Error-controlled pure-stdlib Decimal one-sided (1 - alpha) Clopper-Pearson upper bound.

    Enforces exact integer domain 1 <= n <= 10^12 and 0 <= k <= n, evaluates Stirling ln(Gamma)
    and Lentz continued-fraction I_p(k+1, n-k) at 75-digit Decimal precision (zero float64
    lgamma cancellation at n=10^12), and certifies a conservative upper bracket hi with
    I_lo < 1 - alpha <= I_hi and hi - lo <= 1e-28 * hi.
    """
    require_cond(_is_strict_int(k) and _is_strict_int(n), "clopper_pearson_u95 requires bounded strict integers")
    require_cond(1 <= n <= MAX_CLONOGENIC_CELLS, f"clopper_pearson_u95 n out of domain [1, {MAX_CLONOGENIC_CELLS}]: {n}")
    require_cond(0 <= k <= n, f"clopper_pearson_u95 k out of domain [0, {n}]: {k}")
    require_cond(_is_finite_number(alpha), f"Invalid alpha={alpha}")
    a_d_in = _to_exact_decimal(alpha)
    require_cond(ZERO_DEC < a_d_in < ONE_DEC, f"Invalid alpha={alpha}")
    if k == n:
        return Decimal(1)
    with localcontext(Context(prec=75, Emax=999_999, Emin=-999_999)):
        a_d = +a_d_in
        if k == 0:
            exact = Decimal(1) - (a_d.ln() / Decimal(n)).exp()
            return +exact
        target = Decimal(1) - a_d
        a_int = k + 1
        b_int = n - k
        log_beta_inv = _lgamma_pos_int_dec(n + 1) - _lgamma_pos_int_dec(a_int) - _lgamma_pos_int_dec(b_int)
        p_hat = Decimal(k) / Decimal(n)
        lo = Decimal(0)
        hi = Decimal(1)
        z = Decimal("1.6448536269514722") if a_d <= Decimal("0.5") else Decimal("0")
        se = (p_hat * (Decimal(1) - p_hat) / Decimal(n)).sqrt()
        p = p_hat + z * se + Decimal("0.5") / Decimal(n)
        if not (lo < p < hi):
            p = (lo + hi) / Decimal(2)
        tol = Decimal("1e-28")
        for _ in range(200):
            ib, pdf = _reg_inc_beta_and_pdf_dec(a_int, b_int, p, log_beta_inv)
            err = ib - target
            if err < 0:
                lo = p
            else:
                hi = p
            if hi - lo <= tol * max(hi, Decimal("1e-35")):
                break
            step_ok = False
            if pdf > 0:
                step = err / pdf
                p_new = p - step
                if lo < p_new < hi:
                    if abs(step) <= tol * max(p_new, Decimal("1e-35")):
                        eps_b = max(tol * p_new, Decimal("1e-45"))
                        p_hi = min(hi, p_new + eps_b)
                        p_lo = max(lo, p_new - eps_b)
                        ib_hi, _ = _reg_inc_beta_and_pdf_dec(a_int, b_int, p_hi, log_beta_inv)
                        if ib_hi >= target:
                            hi = p_hi
                            ib_lo, _ = _reg_inc_beta_and_pdf_dec(a_int, b_int, p_lo, log_beta_inv)
                            if ib_lo < target:
                                lo = p_lo
                                break
                    p = p_new
                    step_ok = True
            if not step_ok:
                p = (lo + hi) / Decimal(2)
        require_cond(hi - lo <= Decimal("1e-24") * max(hi, Decimal("1e-35")), f"clopper_pearson_u95 bracket did not converge for k={k}, n={n}")
        return +hi


def clopper_pearson_u95(k: int, n: int, alpha: float = 0.05) -> float:
    """Exact pure-stdlib monotone one-sided (1 - alpha) Clopper-Pearson binomial upper confidence bound.

    Computes the certified 75-digit Decimal bound and rounds UPWARD to IEEE-754 float64
    (via math.nextafter if Decimal.from_float(f) < exact_d) so U95 never understates.
    """
    exact_d = clopper_pearson_u95_decimal(k, n, alpha=alpha)
    if exact_d >= Decimal(1):
        return 1.0
    f = float(exact_d)
    if Decimal.from_float(f) < exact_d:
        f = math.nextafter(f, math.inf)
    return min(1.0, f)


# =============================================================================
# 0B. Fail-Closed Canonical Arm Manifest & Master Contract Verification (S.2)
# =============================================================================
def load_and_verify_canonical_contracts(
    manifest_path: Optional[Path] = None,
    master_contract_path: Optional[Path] = None,
) -> Dict[str, Any]:
    """Fail-closed load & SHA-256 verification of Wave-6 Round-5 canonical manifest & master contract."""
    c_path, m_path = resolve_paired_contract_paths(
        master_contract_path=master_contract_path,
        manifest_path=manifest_path,
    )
    require_cond(m_path.is_file(), f"Missing mandatory canonical arm manifest: {m_path}")
    require_cond(c_path.is_file(), f"Missing mandatory Wave-6 master contract: {c_path}")

    manifest_raw = m_path.read_bytes()
    manifest_sha = sha256_bytes(manifest_raw)
    require_cond(
        manifest_sha == EXPECTED_CANONICAL_MANIFEST_SHA256,
        f"Canonical arm manifest SHA-256 mismatch: observed={manifest_sha}, expected={EXPECTED_CANONICAL_MANIFEST_SHA256}",
    )
    manifest = load_strict_json_text(manifest_raw.decode("utf-8"), m_path.name)
    require_cond(isinstance(manifest, dict) and isinstance(manifest.get("arms"), dict), "Malformed canonical arm manifest")
    manifest_canon_sha = _canonical_json_sha256(manifest)
    require_cond(
        manifest_canon_sha == EXPECTED_CANONICAL_MANIFEST_CANONICAL_JSON_SHA256,
        f"Canonical arm manifest canonical JSON digest mismatch: observed={manifest_canon_sha}",
    )
    schema_v1 = manifest.get("upstream_lot_evidence_record_schema_v1")
    require_cond(
        isinstance(schema_v1, dict) and schema_v1.get("schema_revision") == UPSTREAM_RECEIPT_SCHEMA_REVISION,
        f"Canonical arm manifest missing {UPSTREAM_RECEIPT_SCHEMA_REVISION} upstream_lot_evidence_record_schema_v1",
    )
    cgs = schema_v1.get("canonical_gate_sources", {})
    require_cond(
        isinstance(cgs, dict)
        and cgs.get("live_gate32_shield_debris_recall") == "GATE-32"
        and cgs.get("live_gate33_htmpk_azt_pk") == "GATE-33"
        and cgs.get("gate34") == UPSTREAM_W6C1_GATE_SOURCE
        and cgs.get("gate35") == GATE_ID,
        f"Canonical arm manifest gate source collision/mismatch: {cgs}",
    )
    g5_pol = schema_v1.get("gate5_oq012_live_blueprint_policy", {})
    require_cond(
        isinstance(g5_pol, dict)
        and g5_pol.get("required_observed_survivors_k") == 0
        and g5_pol.get("min_effective_clonogenic_trials_n_eff") == MIN_GATE5_EFFECTIVE_TRIALS
        and g5_pol.get("max_u95_exact") == "1e-8",
        f"Canonical arm manifest missing live Blueprint Section 7 Gate 5 OQ-012 policy: {g5_pol}",
    )

    contract_bytes = c_path.read_bytes()
    contract_file_sha = sha256_bytes(contract_bytes)
    require_cond(
        contract_file_sha == EXPECTED_MASTER_CONTRACT_FILE_SHA256,
        f"Wave-6 master contract file SHA-256 mismatch: observed={contract_file_sha}, expected={EXPECTED_MASTER_CONTRACT_FILE_SHA256}",
    )
    contract = load_strict_json_text(contract_bytes.decode("utf-8"), c_path.name)
    require_cond(isinstance(contract, dict), "Malformed Wave-6 master contract")
    embedded_sha = contract.get("contract_sha256")
    require_cond(_is_non_all_zero_sha256_hex(embedded_sha), "Master contract missing valid contract_sha256")

    contract_no_sha = {k: v for k, v in contract.items() if k != "contract_sha256"}
    recomputed_contract_sha = _canonical_json_sha256(contract_no_sha)
    require_cond(
        recomputed_contract_sha == embedded_sha == EXPECTED_MASTER_CONTRACT_PAYLOAD_SHA256,
        f"Wave-6 master contract SHA-256 mismatch: recomputed={recomputed_contract_sha}, "
        f"embedded={embedded_sha}, expected={EXPECTED_MASTER_CONTRACT_PAYLOAD_SHA256}",
    )
    require_cond(
        contract.get("canonical_arm_manifest_sha256") == manifest_sha,
        "Master contract canonical_arm_manifest_sha256 disagrees with manifest bytes",
    )

    # Verify strict governance invariants from external Round-4 contract
    inv = contract.get("strict_invariants", {})
    require_cond(_strict_json_equal(inv.get("h1_allo_locked_pct"), Decimal("88.0")), "Contract invariant violation: h1_allo_locked_pct != 88.0")
    require_cond(inv.get("design_a_zero_post_transplant_drugs_and_exvivo_rest") is True, "Contract invariant violation: Design A must prohibit drugs and ex-vivo rest")
    require_cond(inv.get("design_a_zero_additional_biologics_beyond_v080_catalase_hydrogel") is True, "Contract invariant violation: Design A must prohibit additional biologics beyond v0.8.0 catalase hydrogel")
    require_cond(inv.get("design_a_contains_preexisting_p04040_catalase_hydrogel") is True, "Contract invariant violation: Design A pre-existing P04040 catalase hydrogel must be declared")
    require_cond(inv.get("design_a_strictly_zero_protein_biologics") is False, "Contract invariant violation: Design A strictly_zero_protein_biologics must be False due to P04040 catalase")
    require_cond(inv.get("design_a_preexisting_catalase_hydrogel_exception_disclosed") is True, "Contract invariant violation: Design A catalase exception must be disclosed")
    require_cond(_strict_json_equal(inv.get("design_a_invariant_tuple"), [Decimal("0.88"), Decimal("0.78"), Decimal("0.57"), Decimal("0.69")]), "Contract invariant violation: Design A tuple drifted")
    require_cond(inv.get("gy_027_1_enforced_unhardened_abx_not_on_r4") is True, "Contract invariant violation: GY-027(1) not enforced")
    require_cond(inv.get("gy_014_enforced_no_invivo_72h_diazoxide_credit") is True, "Contract invariant violation: GY-014 not enforced")
    require_cond(_strict_json_equal(inv.get("exvivo_rest_primary_h4_credit_pp"), Decimal("0.0")), "Contract invariant violation: primary exvivo_rest credit must be 0.0")
    require_cond(inv.get("gy_030_5_lineage_whole_graft_required_all_arms") is True, "Contract invariant violation: GY-030 5-lineage required")
    require_cond(inv.get("c1_prerequisite_enforced_for_r4_and_z_in_24state_ev") is True, "Contract invariant violation: C1 prerequisite must be enforced in 24-state EV")
    require_cond(inv.get("synthetic_fixtures_cannot_authorize_clinical_promotion") is True, "Contract invariant violation: synthetic fixtures must never authorize clinical promotion")

    # Verify canonical arm eligibility & prospective wet-lab flag invariants from Round-4 manifest
    arms = manifest["arms"]
    for k in ("A", "B", "X"):
        require_cond(arms[k]["r4_eligible"] is False, f"Manifest invariant violation: unhardened {k} must be r4_eligible=False")
    require_cond(arms["A"]["product_id"] == "ISLET1_DESIGN_A_V080_REF", "Reference Design A product_id mismatch")
    require_cond(arms["A"]["exvivo_rest_eligible"] is False and arms["A"]["cuff_v2_eligible"] is False, "Design A must forbid ex-vivo rest and Cuff v2.0")
    require_cond(
        arms["Y"]["r4_eligible"] is True
        and arms["Y"]["r4_sars_backup_eligible"] is True
        and arms["Y"]["cell_origin"] == "allogeneic_hiPSC"
        and arms["Y"]["dual_switch_required_for_release"] is True
        and arms["Y"]["dual_switch_wetlab_qualified"] is False,
        "Design Y-v3 R4/Dual-FailSafe manifest mismatch",
    )
    require_cond(
        arms["Z"]["r4_eligible"] is True
        and arms["Z"]["r4_sars_backup_eligible"] is True
        and arms["Z"]["cell_origin"] == "allogeneic_EnSC"
        and arms["Z"]["dual_switch_required_for_release"] is True
        and arms["Z"]["dual_switch_wetlab_qualified"] is False,
        "Arm Z-EnSC R4/Dual-FailSafe/allogeneic_EnSC manifest mismatch",
    )
    require_cond(
        arms["D"]["r4_eligible"] is True
        and arms["D"]["r4_sars_backup_eligible"] is False
        and arms["D"]["cell_origin"] == "autologous_hiPSC"
        and arms["D"]["dual_switch_required_for_release"] is False
        and arms["D"]["dual_switch_wetlab_qualified"] is False,
        "D1b-Lean-K2 must be single-layer ACTB::iCasp8, R4-Omentum only, barred from R4-SARS backup",
    )

    return {
        "manifest": manifest,
        "manifest_sha256": manifest_sha,
        "manifest_canonical_json_sha256": manifest_canon_sha,
        "manifest_schema_version": manifest.get("schema_version"),
        "contract": contract,
        "contract_sha256": recomputed_contract_sha,
        "contract_file_sha256": contract_file_sha,
        "contract_schema_version": contract.get("schema_version"),
    }


# =============================================================================
# 1. Read-Only OpenIslet NW-08 Constant Verification
# =============================================================================
def verify_nw08_constants(repo_root: Path | None) -> Dict[str, Any]:
    """Return pinned NW-08 constants; when repo_root is provided, verify byte-level match read-only."""
    c = dict(PINNED_NW08_CONSTANTS)
    checked_repo = False
    repo_refs_verified = False

    if repo_root is not None:
        p43 = repo_root / "scripts" / "verify_iip0043_wholegraft_gate0v_and_calibration.py"
        pl4 = repo_root / "scripts" / "run_layer4_tissue_and_metabolic_twin.py"
        p34 = repo_root / "scripts" / "verify_iip0034_planar_and_portfolio.py"
        j34 = repo_root / "data" / "extracted" / "iip0034_planar_and_portfolio_verification_v0.8.0.json"
        for p in (p43, pl4, p34, j34):
            require_cond(p.is_file(), f"Missing required OpenIslet read-only file: {p}")

        src43 = p43.read_text(encoding="utf-8")
        srcl4 = pl4.read_text(encoding="utf-8")
        src34 = p34.read_text(encoding="utf-8")

        def _parse_float(txt: str, pat: str, label: str) -> float:
            m = re.search(pat, txt)
            require_cond(m is not None, f"Failed to parse {label} from OpenIslet source")
            return float(m.group(1))

        require_cond(abs(_parse_float(src43, r"vmax_islet_mol_cm3_s\s*=\s*([0-9.eE+-]+)", "vmax") - c["vmax_islet_pure_mol_cm3_s"]) < 1e-18, "vmax mismatch")
        require_cond(abs(_parse_float(src43, r"alpha_bunsen_nominal\s*=\s*([0-9.eE+-]+)", "alpha_nom") - c["alpha_o2_nominal_mol_cm3_mmhg"]) < 1e-18, "alpha_nom mismatch")
        require_cond(abs(_parse_float(src43, r"d_o2_islet\s*=\s*([0-9.eE+-]+)", "d_islet") - c["d_o2_islet_cm2_s"]) < 1e-18, "d_islet mismatch")
        require_cond(abs(_parse_float(src43, r"d_o2_gel_chronic\s*=\s*([0-9.eE+-]+)", "d_gel_chron") - c["d_o2_gel_chronic_cm2_s"]) < 1e-18, "d_gel_chron mismatch")
        require_cond(abs(_parse_float(src43, r"CANONICAL_NW08_PO2_FLOOR_MMHG:\s*float\s*=\s*([0-9.eE+-]+)", "po2_floor") - c["po2_gsis_face_floor_mmhg"]) < 1e-12, "po2_floor mismatch")
        require_cond(abs(_parse_float(srcl4, r"KM_O2_MMHG\s*=\s*([0-9.eE+-]+)", "km") - c["km_o2_mmhg"]) < 1e-12, "km mismatch")
        require_cond(abs(_parse_float(srcl4, r"D_O2_HYDROGEL_CM2_S\s*=\s*([0-9.eE+-]+)", "d_gel_acute") - c["d_o2_gel_acute_cm2_s"]) < 1e-12, "d_gel_acute mismatch")
        require_cond(abs(_parse_float(src34, r"ALPHA_PHYS_BUFFER\s*=\s*([0-9.eE+-]+)", "alpha_krbh") - c["alpha_o2_krbh_mol_cm3_mmhg"]) < 1e-18, "alpha_krbh mismatch")
        require_cond(abs(_parse_float(src34, r"d_ins_cm2_s\s*=\s*([0-9.eE+-]+)", "d_ins") - c["d_insulin_hydrogel_cm2_s"]) < 1e-18, "d_ins mismatch")
        require_cond(abs(_parse_float(src34, r"t50_intrinsic_min\s*=\s*([0-9.eE+-]+)", "t50_int") - c["insulin_intrinsic_t50_min"]) < 1e-12, "t50_int mismatch")

        d34 = load_strict_json_text(j34.read_text(encoding="utf-8"), j34.name)
        ref_map = {r["label"]: float(r["worst_face_mmhg"]) for r in d34["planar_3d_fvm_oxygen_envelopes"]}
        require_cond(abs(ref_map["Hybrid333_H180_Day0_Clean_65um_PASS"] - PINNED_IIP0034_REFS["Hybrid333_H180_Day0_Clean_65um_PASS"]) < 1e-4, "IIP-0034 clean ref mismatch")
        require_cond(abs(ref_map["Hybrid333_H180_Day0_10umFibrin_0p5D_65um_FACE_FAIL"] - PINNED_IIP0034_REFS["Hybrid333_H180_Day0_10umFibrin_0p5D_65um_FACE_FAIL"]) < 1e-4, "IIP-0034 10um ref mismatch")
        require_cond(abs(ref_map["Hybrid333_H180_Day0_15umFibrin_0p5D_65um"] - PINNED_IIP0034_REFS["Hybrid333_H180_Day0_15umFibrin_0p5D_65um"]) < 1e-4, "IIP-0034 15um ref mismatch")
        krbh_val = float(d34["planar_30mmhg_buffer_solubility_sensitivity"]["hybrid333_h180_bed30_clean_phys_buffer"]["worst_face_mmhg"])
        require_cond(abs(krbh_val - PINNED_IIP0034_REFS["Hybrid333_H180_Day0_Clean_65um_Bed30mmHg_Alpha1p27e9_FACE_FAIL"]) < 1e-4, "IIP-0034 KRBH ref mismatch")
        checked_repo = True
        repo_refs_verified = True

    return {
        **c,
        "repo_constants_cross_verified": checked_repo,
        "repo_iip0034_refs_cross_verified": repo_refs_verified,
    }


# =============================================================================
# 2. Standalone 3D Finite-Volume Reaction-Diffusion Solver (Pure NumPy)
# =============================================================================
def _harm_mean(a: np.ndarray, b: np.ndarray) -> np.ndarray:
    s = a + b
    return np.where(s > 0.0, 2.0 * a * b / np.where(s > 0.0, s, 1.0), 0.0)


class Standalone3DFVOperator:
    """
    Matrix-free 3D finite-volume operator:
      - Periodic in X and Y
      - Independent Robin or adiabatic (no-flux) Z-boundaries at bottom (k=0) and top (k=nz-1)
      - Exact harmonic-mean face conductivities across all interior faces.
    """

    def __init__(
        self,
        perm_field: np.ndarray,
        dx: float,
        dy: float,
        dz: float,
        *,
        standoff_bot_cm: float = 0.0,
        standoff_top_cm: float = 0.0,
        p_ext_bot: float | None = None,
        p_ext_top: float | None = None,
        top_adiabatic: bool = False,
    ) -> None:
        self.shape = perm_field.shape
        self.dx = float(dx)
        self.dy = float(dy)
        self.dz = float(dz)

        self.gx = _harm_mean(perm_field, np.roll(perm_field, -1, axis=0)) / (dx * dx)
        self.gx_m = np.roll(self.gx, 1, axis=0)
        self.gy = _harm_mean(perm_field, np.roll(perm_field, -1, axis=1)) / (dy * dy)
        self.gy_m = np.roll(self.gy, 1, axis=1)
        self.gz = _harm_mean(perm_field[:, :, :-1], perm_field[:, :, 1:]) / (dz * dz) if perm_field.shape[2] > 1 else None

        self.b_rob_bot = np.zeros_like(perm_field, dtype=np.float64)
        self.b_rob_top = np.zeros_like(perm_field, dtype=np.float64)
        self.neg_diag = self.gx + self.gx_m + self.gy + self.gy_m
        if self.gz is not None:
            self.neg_diag[:, :, :-1] += self.gz
            self.neg_diag[:, :, 1:] += self.gz

        df_b = perm_field[:, :, 0]
        de_b = df_b if p_ext_bot is None else np.full_like(df_b, float(p_ext_bot))
        r_b = (0.5 * dz) / np.maximum(df_b, 1e-30) + standoff_bot_cm / np.maximum(de_b, 1e-30)
        gf_b = 1.0 / (dz * r_b)
        self.neg_diag[:, :, 0] += gf_b
        self.b_rob_bot[:, :, 0] += gf_b

        if not top_adiabatic:
            df_t = perm_field[:, :, -1]
            de_t = df_t if p_ext_top is None else np.full_like(df_t, float(p_ext_top))
            r_t = (0.5 * dz) / np.maximum(df_t, 1e-30) + standoff_top_cm / np.maximum(de_t, 1e-30)
            gf_t = 1.0 / (dz * r_t)
            self.neg_diag[:, :, -1] += gf_t
            self.b_rob_top[:, :, -1] += gf_t

        self.b_rob = self.b_rob_bot + self.b_rob_top

    def apply_A(self, u: np.ndarray) -> np.ndarray:
        u3 = u.reshape(self.shape)
        out = -self.neg_diag * u3
        out[:-1, :, :] += self.gx[:-1, :, :] * u3[1:, :, :]
        out[-1, :, :] += self.gx[-1, :, :] * u3[0, :, :]
        out[1:, :, :] += self.gx_m[1:, :, :] * u3[:-1, :, :]
        out[0, :, :] += self.gx_m[0, :, :] * u3[-1, :, :]
        out[:, :-1, :] += self.gy[:, :-1, :] * u3[:, 1:, :]
        out[:, -1, :] += self.gy[:, -1, :] * u3[:, 0, :]
        out[:, 1:, :] += self.gy_m[:, 1:, :] * u3[:, :-1, :]
        out[:, 0, :] += self.gy_m[:, 0, :] * u3[:, -1, :]
        if self.gz is not None:
            out[:, :, :-1] += self.gz * u3[:, :, 1:]
            out[:, :, 1:] += self.gz * u3[:, :, :-1]
        return out.ravel()


def pcg_solve_spd(
    op: Standalone3DFVOperator,
    extra_diag: np.ndarray,
    rhs: np.ndarray,
    *,
    rtol: float = 1e-13,
    maxiter: int = 2500,
) -> np.ndarray:
    rhs_norm = float(np.linalg.norm(rhs))
    if rhs_norm <= 1e-30:
        return np.zeros_like(rhs)
    diag_tot = op.neg_diag.ravel() + extra_diag
    op_scale = max(float(np.max(diag_tot)), 1e-30)
    inv_op_scale = 1.0 / op_scale
    m_inv = op_scale / np.maximum(diag_tot, 1e-30)
    r = rhs / rhs_norm
    x = np.zeros_like(r)
    z = m_inv * r
    p_dir = z.copy()
    rz_old = float(np.dot(r, z))
    for _ in range(maxiter):
        ap = ((-op.apply_A(p_dir)) + extra_diag * p_dir) * inv_op_scale
        denom = float(np.dot(p_dir, ap))
        if denom <= 1e-300:
            break
        alpha = rz_old / denom
        x += alpha * p_dir
        r -= alpha * ap
        if float(np.linalg.norm(r)) <= rtol:
            return x * (rhs_norm * inv_op_scale)
        z = m_inv * r
        rz_new = float(np.dot(r, z))
        beta = rz_new / max(rz_old, 1e-300)
        p_dir = z + beta * p_dir
        rz_old = rz_new
    require_cond(float(np.linalg.norm(r)) <= 1e-9, f"PCG failed to converge: rel_res={float(np.linalg.norm(r)):.3e}")
    return x * (rhs_norm * inv_op_scale)


def solve_3d_mm_oxygen_fvm(
    perm: np.ndarray,
    vmax: np.ndarray,
    kp: np.ndarray,
    dx: float,
    dy: float,
    dz: float,
    *,
    p_bed: float,
    km_o2: float,
    alpha_o2: float,
    p_bed_bot: float | None = None,
    p_bed_top: float | None = None,
    standoff_bot_cm: float = 0.0,
    standoff_top_cm: float = 0.0,
    p_ext_bot: float | None = None,
    p_ext_top: float | None = None,
    top_adiabatic: bool = False,
    max_newton_iter: int = 65,
    tol_rel: float = 1e-13,
) -> Dict[str, Any]:
    op = Standalone3DFVOperator(
        perm, dx, dy, dz,
        standoff_bot_cm=standoff_bot_cm,
        standoff_top_cm=standoff_top_cm,
        p_ext_bot=p_ext_bot,
        p_ext_top=p_ext_top,
        top_adiabatic=top_adiabatic,
    )
    pb_b = float(p_bed if p_bed_bot is None else p_bed_bot)
    pb_t = float(p_bed if p_bed_top is None else p_bed_top)
    b_rhs = (op.b_rob_bot * pb_b + op.b_rob_top * pb_t).ravel()
    v_f = vmax.ravel()
    k_f = (kp * alpha_o2).ravel()
    scale = max(float(np.max(v_f)), float(np.max(b_rhs)), 1e-12)

    p = np.full(perm.size, 0.5 * (pb_b + pb_t), dtype=np.float64)
    converged = False
    iters = 0
    for it in range(1, max_newton_iter + 1):
        iters = it
        mm = p / (km_o2 + p)
        dmm = km_o2 / ((km_o2 + p) ** 2)
        f = op.apply_A(p) + b_rhs - v_f * mm + k_f * (p_bed - p)
        if float(np.max(np.abs(f))) / scale <= tol_rel and it >= 2:
            converged = True
            break
        dp = pcg_solve_spd(op, v_f * dmm + k_f, f, rtol=1e-13, maxiter=2500)
        p_cand = p + dp
        if np.any(p_cand < 0.0):
            p = np.where(p_cand > 0.1 * p, p_cand, 0.1 * p)
        else:
            p = p_cand

    mm_fin = p / (km_o2 + p)
    ap_fin = op.apply_A(p)
    f_post = ap_fin + b_rhs - v_f * mm_fin + k_f * (p_bed - p)
    post_rel = float(np.max(np.abs(f_post))) / scale
    require_cond(converged or post_rel <= 1e-9, f"3D FVM Newton non-convergence: {post_rel:.3e}")

    dv = dx * dy * dz
    bnd_in = float(np.sum((ap_fin + b_rhs) * dv))
    perf_in = float(np.sum(k_f * (p_bed - p) * dv))
    sink = float(np.sum(v_f * mm_fin * dv))
    mbe = abs(bnd_in + perf_in - sink) / max(abs(bnd_in), abs(perf_in), abs(sink), 1e-30)
    require_cond(mbe < 1e-10, f"Global flux mass-balance violation: {mbe:.3e}")

    return {
        "p_3d": p.reshape(perm.shape),
        "newton_iterations": iters,
        "post_rel_residual": post_rel,
        "rel_mass_balance_error": mbe,
    }


def compute_exact_fv_interface_stats(p3: np.ndarray, perm: np.ndarray, mask: np.ndarray) -> Dict[str, float]:
    face_vals: List[np.ndarray] = []
    for axis in (0, 1):
        for shift in (-1, 1):
            nbr_mask = np.roll(mask, shift, axis=axis)
            bnd = mask & (~nbr_mask)
            if np.any(bnd):
                d_in = perm[bnd]
                d_out = np.roll(perm, shift, axis=axis)[bnd]
                p_in = p3[bnd]
                p_out = np.roll(p3, shift, axis=axis)[bnd]
                face_vals.append((d_in * p_in + d_out * p_out) / np.maximum(d_in + d_out, 1e-30))
    if mask.shape[2] > 1:
        bnd_up = mask[:, :, :-1] & (~mask[:, :, 1:])
        if np.any(bnd_up):
            d_in, d_out = perm[:, :, :-1][bnd_up], perm[:, :, 1:][bnd_up]
            face_vals.append((d_in * p3[:, :, :-1][bnd_up] + d_out * p3[:, :, 1:][bnd_up]) / np.maximum(d_in + d_out, 1e-30))
        bnd_dn = mask[:, :, 1:] & (~mask[:, :, :-1])
        if np.any(bnd_dn):
            d_in, d_out = perm[:, :, 1:][bnd_dn], perm[:, :, :-1][bnd_dn]
            face_vals.append((d_in * p3[:, :, 1:][bnd_dn] + d_out * p3[:, :, :-1][bnd_dn]) / np.maximum(d_in + d_out, 1e-30))
    all_faces = np.concatenate(face_vals)
    return {
        "fv_harmonic_face_min_mmhg": float(np.min(all_faces)),
        "fv_harmonic_face_mean_mmhg": float(np.mean(all_faces)),
    }


# =============================================================================
# 3. Geometry Solvers: Route 3P, R4-Omentum (Monolayer & Clinical Bilayer), R4-SARS-Free
# =============================================================================
def run_planar_route3p_case(
    c: Dict[str, Any],
    *,
    area_cm2: float = 333.3,
    h_slot_um: float = 180.0,
    cluster_diam_um: float = 65.0,
    bed_po2_mmhg: float = 35.0,
    fibrin_um: float = 0.0,
    fibrin_d_factor: float = 0.5,
    ocr_mult: float = 1.097,
    alpha_o2: float | None = None,
    nx: int = 28,
    nz: int = 32,
) -> Dict[str, Any]:
    alpha_use = c["alpha_o2_nominal_mol_cm3_mmhg"] if alpha_o2 is None else alpha_o2
    d_gel = c["d_o2_gel_chronic_cm2_s"]
    d_islet = c["d_o2_islet_cm2_s"]
    vmax_pure = c["vmax_islet_pure_mol_cm3_s"]
    vol_ieq = c["vol_1_ieq_cm3"]

    loading_ieq_cm2 = 500_000.0 / area_cm2
    r_cm = 0.5 * cluster_diam_um * 1e-4
    v_cl = (4.0 / 3.0) * math.pi * (r_cm ** 3)
    bilayer = cluster_diam_um <= 80.0
    n_layer = (0.5 if bilayer else 1.0) * (loading_ieq_cm2 * vol_ieq / v_cl)
    pitch_cm = math.sqrt(1.0 / n_layer)
    h_cm = h_slot_um * 1e-4
    dx = pitch_cm / nx
    dz = h_cm / nz
    xs = (np.arange(nx) + 0.5) * dx
    zs = (np.arange(nz) + 0.5) * dz - 0.5 * h_cm
    X, Y, Z = np.meshgrid(xs, xs, zs, indexing="ij")
    dv = dx * dx * dz

    def pdist(a: np.ndarray, ctr: float) -> np.ndarray:
        d = np.abs(a - ctr)
        return np.minimum(d, pitch_cm - d)

    in_any = np.zeros_like(X, dtype=bool)
    vmax = np.zeros_like(X, dtype=np.float64)
    masks: List[np.ndarray] = []
    if bilayer:
        z_c = 0.5 * h_cm - r_cm - 15.0e-4
        centers = [(0.5 * pitch_cm, 0.5 * pitch_cm, +z_c), (0.0, 0.0, -z_c)]
    else:
        centers = [(0.5 * pitch_cm, 0.5 * pitch_cm, 0.0)]

    for cx, cy, cz in centers:
        msk = (pdist(X, cx) ** 2 + pdist(Y, cy) ** 2 + (Z - cz) ** 2) <= (r_cm ** 2)
        v_vox = float(np.sum(msk)) * dv
        in_any |= msk
        vmax[msk] = (vmax_pure * ocr_mult) * (v_cl / v_vox)
        masks.append(msk)

    in_gel = ~in_any
    phi_tot = (loading_ieq_cm2 * vol_ieq) / h_cm
    vmax[in_gel] = (phi_tot * vmax_pure * c["stromal_ocr_fraction"] * ocr_mult) / float(np.mean(in_gel))
    perm = np.where(in_any, d_islet * alpha_use, d_gel * alpha_use)
    p_ext = d_gel * (fibrin_d_factor if fibrin_um > 0.0 else 1.0) * alpha_use

    res = solve_3d_mm_oxygen_fvm(
        perm, vmax, np.zeros_like(X), dx, dx, dz,
        p_bed=bed_po2_mmhg, km_o2=c["km_o2_mmhg"], alpha_o2=alpha_use,
        standoff_bot_cm=fibrin_um * 1e-4, standoff_top_cm=fibrin_um * 1e-4,
        p_ext_bot=p_ext, p_ext_top=p_ext, top_adiabatic=False,
    )
    p3 = res["p_3d"]
    worst_face = min(compute_exact_fv_interface_stats(p3, perm, m)["fv_harmonic_face_min_mmhg"] for m in masks)
    worst_core = min(float(np.min(p3[m])) for m in masks)
    return {
        "grid": [nx, nx, nz],
        "area_cm2": area_cm2,
        "loading_ieq_cm2": round(loading_ieq_cm2, 2),
        "pitch_um": round(pitch_cm * 1e4, 3),
        "h_slot_um": h_slot_um,
        "cluster_diam_um": cluster_diam_um,
        "bed_po2_mmhg": bed_po2_mmhg,
        "fibrin_um": fibrin_um,
        "alpha_o2_mol_cm3_mmhg": alpha_use,
        "worst_face_mmhg": round(worst_face, 4),
        "worst_core_mmhg": round(worst_core, 4),
        "passes_15_and_5": bool(worst_face >= 15.0 and worst_core >= 5.0),
        "o2_rel_mass_balance_error": _fmt_sci_float(res["rel_mass_balance_error"]),
        "o2_post_rel_residual": _fmt_sci_float(res["post_rel_residual"]),
    }


def run_r4_monolayer_case(
    c: Dict[str, Any],
    *,
    site_name: str,
    cluster_diam_um: float,
    pitch_um: float,
    bed_po2_mmhg: float,
    fibrin_um: float = 0.0,
    fibrin_d_factor: float = 0.5,
    d_matrix_cm2_s: float | None = None,
    interstitial_margin_each_um: float = 15.0,
    top_adiabatic: bool = False,
    ocr_mult: float = 1.097,
    alpha_o2: float | None = None,
    nx: int = 24,
    nz: int = 20,
) -> Dict[str, Any]:
    alpha_use = c["alpha_o2_nominal_mol_cm3_mmhg"] if alpha_o2 is None else alpha_o2
    d_mat = c["d_o2_gel_chronic_cm2_s"] if d_matrix_cm2_s is None else d_matrix_cm2_s
    d_islet = c["d_o2_islet_cm2_s"]
    vmax_pure = c["vmax_islet_pure_mol_cm3_s"]
    vol_ieq = c["vol_1_ieq_cm3"]

    r_cm = 0.5 * cluster_diam_um * 1e-4
    v_cl = (4.0 / 3.0) * math.pi * (r_cm ** 3)
    pitch_cm = pitch_um * 1e-4
    h_um = cluster_diam_um + 2.0 * interstitial_margin_each_um
    h_cm = h_um * 1e-4
    dx = pitch_cm / nx
    dz = h_cm / nz
    xs = (np.arange(nx) + 0.5) * dx - 0.5 * pitch_cm
    zs = (np.arange(nz) + 0.5) * dz - 0.5 * h_cm
    X, Y, Z = np.meshgrid(xs, xs, zs, indexing="ij")
    dv = dx * dx * dz

    in_cl = (X ** 2 + Y ** 2 + Z ** 2) <= (r_cm ** 2)
    v_vox = float(np.sum(in_cl)) * dv
    require_cond(v_vox > 0.0, f"Empty cluster mask for {site_name}")

    vmax = np.zeros_like(X, dtype=np.float64)
    vmax[in_cl] = (vmax_pure * ocr_mult) * (v_cl / v_vox)
    in_mat = ~in_cl
    loading_ieq_cm2 = (v_cl / vol_ieq) / (pitch_cm * pitch_cm)
    phi_tot = v_cl / (pitch_cm * pitch_cm * h_cm)
    vmax[in_mat] = (phi_tot * vmax_pure * c["stromal_ocr_fraction"] * ocr_mult) / float(np.mean(in_mat))
    perm = np.where(in_cl, d_islet * alpha_use, d_mat * alpha_use)
    p_ext = c["d_o2_gel_chronic_cm2_s"] * (fibrin_d_factor if fibrin_um > 0.0 else 1.0) * alpha_use

    res = solve_3d_mm_oxygen_fvm(
        perm, vmax, np.zeros_like(X), dx, dx, dz,
        p_bed=bed_po2_mmhg, km_o2=c["km_o2_mmhg"], alpha_o2=alpha_use,
        standoff_bot_cm=fibrin_um * 1e-4, standoff_top_cm=fibrin_um * 1e-4,
        p_ext_bot=p_ext, p_ext_top=p_ext, top_adiabatic=top_adiabatic,
    )
    p3 = res["p_3d"]
    fv = compute_exact_fv_interface_stats(p3, perm, in_cl)
    wf = fv["fv_harmonic_face_min_mmhg"]
    wc = float(np.min(p3[in_cl]))
    return {
        "site": site_name,
        "grid": [nx, nx, nz],
        "cluster_diam_um": cluster_diam_um,
        "pitch_um": round(pitch_um, 2),
        "layer_thickness_um": h_um,
        "areal_loading_ieq_cm2": round(loading_ieq_cm2, 2),
        "bed_po2_mmhg": bed_po2_mmhg,
        "fibrin_um": fibrin_um,
        "d_matrix_cm2_s": d_mat,
        "alpha_o2_mol_cm3_mmhg": alpha_use,
        "top_adiabatic": top_adiabatic,
        "worst_face_mmhg": round(wf, 4),
        "worst_core_mmhg": round(wc, 4),
        "passes_15_and_5": bool(wf >= 15.0 and wc >= 5.0),
        "o2_rel_mass_balance_error": _fmt_sci_float(res["rel_mass_balance_error"]),
        "o2_post_rel_residual": _fmt_sci_float(res["post_rel_residual"]),
    }


def run_r4_clinical_bilayer_case(
    c: Dict[str, Any],
    *,
    site_name: str,
    loading_ieq_cm2: float,
    h_um: float = 120.0,
    cluster_diam_um: float = 65.0,
    bed_po2_mmhg: float = 40.0,
    bed_po2_bot_mmhg: float | None = None,
    bed_po2_top_mmhg: float | None = None,
    fibrin_um: float = 0.0,
    d_matrix_cm2_s: float | None = None,
    top_adiabatic: bool = False,
    ocr_mult: float = 1.097,
    alpha_o2: float | None = None,
    z_c_um: float | None = None,
    nx: int = 20,
    nz: int = 20,
) -> Dict[str, Any]:
    """Exact 3D FVM of envelope-free clinical staggered bilayer (combined areal loading over both planes)."""
    alpha_use = c["alpha_o2_nominal_mol_cm3_mmhg"] if alpha_o2 is None else alpha_o2
    d_gel = c["d_o2_gel_chronic_cm2_s"] if d_matrix_cm2_s is None else d_matrix_cm2_s
    d_islet = c["d_o2_islet_cm2_s"]
    vol_ieq = c["vol_1_ieq_cm3"]
    r_cm = 0.5 * cluster_diam_um * 1e-4
    v_cl = (4.0 / 3.0) * math.pi * (r_cm ** 3)
    n_layer = 0.5 * (loading_ieq_cm2 * vol_ieq / v_cl)
    pitch_cm = math.sqrt(1.0 / n_layer)
    h_cm = h_um * 1e-4
    z_c = (0.5 * h_cm - r_cm - 5.0e-4) if z_c_um is None else (float(z_c_um) * 1e-4)
    z_c_used_um = z_c * 1e4
    wall_clearance_um = 0.5 * h_um - (z_c_used_um + 0.5 * cluster_diam_um)
    min_dist = math.sqrt(0.5 * (pitch_cm ** 2) + (2.0 * z_c) ** 2)
    require_cond(
        pitch_cm > 2.0 * r_cm and min_dist > 2.0 * r_cm and wall_clearance_um >= -1e-9,
        f"Steric or slab-protrusion overlap at {loading_ieq_cm2} IEQ/cm^2 (pitch={pitch_cm*1e4:.2f}, min_dist={min_dist*1e4:.2f}, wall_clear={wall_clearance_um:.2f})",
    )

    pb_bot = bed_po2_mmhg if bed_po2_bot_mmhg is None else float(bed_po2_bot_mmhg)
    pb_top = bed_po2_mmhg if bed_po2_top_mmhg is None else float(bed_po2_top_mmhg)

    dx = pitch_cm / nx
    dz = h_cm / nz
    xs = (np.arange(nx) + 0.5) * dx
    zs = (np.arange(nz) + 0.5) * dz - 0.5 * h_cm
    X, Y, Z = np.meshgrid(xs, xs, zs, indexing="ij")
    dv = dx * dx * dz

    def pdist(a: np.ndarray, ctr: float) -> np.ndarray:
        d = np.abs(a - ctr)
        return np.minimum(d, pitch_cm - d)

    in_any = np.zeros_like(X, dtype=bool)
    vmax = np.zeros_like(X, dtype=np.float64)
    masks: List[np.ndarray] = []
    for cx, cy, cz in [(0.5 * pitch_cm, 0.5 * pitch_cm, +z_c), (0.0, 0.0, -z_c)]:
        msk = (pdist(X, cx) ** 2 + pdist(Y, cy) ** 2 + (Z - cz) ** 2) <= (r_cm ** 2)
        in_any |= msk
        vmax[msk] = (c["vmax_islet_pure_mol_cm3_s"] * ocr_mult) * (v_cl / (float(np.sum(msk)) * dv))
        masks.append(msk)
    in_gel = ~in_any
    phi_tot = (loading_ieq_cm2 * vol_ieq) / h_cm
    vmax[in_gel] = (phi_tot * c["vmax_islet_pure_mol_cm3_s"] * c["stromal_ocr_fraction"] * ocr_mult) / float(np.mean(in_gel))
    perm = np.where(in_any, d_islet * alpha_use, d_gel * alpha_use)
    p_ext = c["d_o2_gel_chronic_cm2_s"] * (0.5 if fibrin_um > 0.0 else 1.0) * alpha_use

    res = solve_3d_mm_oxygen_fvm(
        perm, vmax, np.zeros_like(X), dx, dx, dz,
        p_bed=0.5 * (pb_bot + pb_top), km_o2=c["km_o2_mmhg"], alpha_o2=alpha_use,
        p_bed_bot=pb_bot, p_bed_top=pb_top,
        standoff_bot_cm=fibrin_um * 1e-4, standoff_top_cm=fibrin_um * 1e-4,
        p_ext_bot=p_ext, p_ext_top=p_ext, top_adiabatic=top_adiabatic,
    )
    p3 = res["p_3d"]
    wf = min(compute_exact_fv_interface_stats(p3, perm, m)["fv_harmonic_face_min_mmhg"] for m in masks)
    wc = min(float(np.min(p3[m])) for m in masks)
    anoxic_frac = float(np.mean(p3[in_any] < 0.5))
    return {
        "site": site_name,
        "grid": [nx, nx, nz],
        "loading_ieq_cm2": loading_ieq_cm2,
        "pitch_um": round(pitch_cm * 1e4, 2),
        "h_um": h_um,
        "z_c_um": round(z_c_used_um, 3),
        "wall_clearance_um": round(wall_clearance_um, 3),
        "min_cross_plane_center_dist_um": round(min_dist * 1e4, 2),
        "ocr_mult": round(ocr_mult, 4),
        "bed_po2_mmhg": round(0.5 * (pb_bot + pb_top), 2),
        "bed_po2_bot_mmhg": pb_bot,
        "bed_po2_top_mmhg": pb_top,
        "fibrin_um": fibrin_um,
        "d_matrix_cm2_s": d_gel,
        "alpha_o2_mol_cm3_mmhg": alpha_use,
        "top_adiabatic": top_adiabatic,
        "worst_face_mmhg": round(wf, 4),
        "worst_core_mmhg": round(wc, 4),
        "anoxic_islet_frac_lt_0p5mmHg": round(anoxic_frac, 4),
        "passes_15_and_5": bool(wf >= 15.0 and wc >= 5.0),
        "o2_rel_mass_balance_error": _fmt_sci_float(res["rel_mass_balance_error"]),
        "o2_post_rel_residual": _fmt_sci_float(res["post_rel_residual"]),
    }


def analyze_3grid_convergence(
    vals: Sequence[float],
    uniform_ratio: float,
    raw_mbes: Sequence[float],
) -> Dict[str, Any]:
    """Honest equal-ratio 3-mesh convergence diagnostic without negative-order clamping."""
    require_cond(len(vals) == 3 and len(raw_mbes) == 3, "Expected exactly 3 mesh levels")
    require_cond(uniform_ratio > 1.0, f"Invalid uniform refinement ratio: {uniform_ratio}")
    f3, f2, f1 = float(vals[0]), float(vals[1]), float(vals[2])
    e32 = f2 - f3
    e21 = f1 - f2
    v_min, v_max = min(f3, f2, f1), max(f3, f2, f1)
    spread = v_max - v_min
    half_range = 0.5 * spread
    base = {
        "uniform_refinement_ratio_xyz": round(uniform_ratio, 4),
        "coarse_medium_fine_mmhg": [round(f3, 4), round(f2, 4), round(f1, 4)],
        "raw_grid_min_max_mmhg": [round(v_min, 4), round(v_max, 4)],
        "max_spread_mmhg": round(spread, 4),
        "raw_o2_rel_mass_balance_errors": [_fmt_sci_float(x) for x in raw_mbes],
    }
    if abs(e21) < 1e-12 and abs(e32) < 1e-12:
        return {
            **base,
            "convergence_type": "EXACT_ZERO_SPREAD",
            "asymptotic_order_resolved": True,
            "observed_order_p": None,
            "conservative_bracket_covering_all_grids_mmhg": [round(f1, 4), round(f1, 4)],
        }
    if e21 * e32 <= 0.0:
        return {
            **base,
            "convergence_type": "OSCILLATORY_STAIRCASE_BOUND",
            "asymptotic_order_resolved": False,
            "observed_order_p": None,
            "asme_half_range_uncertainty_mmhg": round(half_range, 4),
            "conservative_bracket_covering_all_grids_mmhg": [round(v_min - half_range, 4), round(v_max + half_range, 4)],
            "diagnostic_note": "Voxelized spherical interface shifts discontinuously across Cartesian refinement; oscillatory half-range bracket reported.",
        }
    p_obs = math.log(abs(e32 / e21)) / math.log(uniform_ratio)
    if p_obs <= 0.0:
        return {
            **base,
            "convergence_type": "MONOTONE_NON_ASYMPTOTIC_UNRESOLVED_ORDER",
            "asymptotic_order_resolved": False,
            "observed_order_p": round(p_obs, 3),
            "asme_half_range_uncertainty_mmhg": round(half_range, 4),
            "conservative_bracket_covering_all_grids_mmhg": [round(v_min - half_range, 4), round(v_max + half_range, 4)],
            "diagnostic_note": "Observed order is non-positive (not clamped); grid sequence is outside asymptotic regime due to discrete sphere voxelization.",
        }
    p_gci = min(2.0, p_obs)
    gci_fine = 1.25 * abs(e21) / max((uniform_ratio ** p_gci) - 1.0, 1e-6)
    lo = min(v_min, f1 - gci_fine)
    hi = max(v_max, f1 + gci_fine)
    return {
        **base,
        "convergence_type": "MONOTONE_ASYMPTOTIC",
        "asymptotic_order_resolved": True,
        "observed_order_p": round(p_obs, 3),
        "gci_order_used": round(p_gci, 3),
        "gci_fine_mmhg": round(gci_fine, 4),
        "conservative_bracket_covering_all_grids_mmhg": [round(lo, 4), round(hi, 4)],
    }


# =============================================================================
# 4. 3D Crank-Nicolson FVM Insulin Shut-Off t50 (With Exact Transient Mass Balance)
# =============================================================================
def compute_3d_fvm_insulin_shutoff_t50(
    *,
    h_um: float,
    pitch_um: float,
    cluster_diam_um: float,
    bilayer: bool,
    fibrin_um: float,
    fibrin_d_factor: float,
    d_ins_matrix_cm2_s: float,
    d_ins_islet_cm2_s: float,
    t50_intrinsic_min: float,
    top_adiabatic: bool = False,
    z_c_um: float | None = None,
    nx: int = 18,
    nz: int = 24,
    dt_s: float = 2.0,
) -> Dict[str, Any]:
    r_cm = 0.5 * cluster_diam_um * 1e-4
    pitch_cm = pitch_um * 1e-4
    h_cm = h_um * 1e-4
    dx = pitch_cm / nx
    dz = h_cm / nz
    xs = (np.arange(nx) + 0.5) * dx
    zs = (np.arange(nz) + 0.5) * dz - 0.5 * h_cm
    X, Y, Z = np.meshgrid(xs, xs, zs, indexing="ij")

    def pdist(a: np.ndarray, ctr: float) -> np.ndarray:
        d = np.abs(a - ctr)
        return np.minimum(d, pitch_cm - d)

    in_cl = np.zeros_like(X, dtype=bool)
    if bilayer:
        margin = 15.0e-4 if h_um >= 170.0 else 5.0e-4
        z_c = (0.5 * h_cm - r_cm - margin) if z_c_um is None else (float(z_c_um) * 1e-4)
        centers = [(0.5 * pitch_cm, 0.5 * pitch_cm, +z_c), (0.0, 0.0, -z_c)]
    else:
        centers = [(0.5 * pitch_cm, 0.5 * pitch_cm, 0.0)]
    for cx, cy, cz in centers:
        in_cl |= (pdist(X, cx) ** 2 + pdist(Y, cy) ** 2 + (Z - cz) ** 2) <= (r_cm ** 2)

    d_field = np.where(in_cl, d_ins_islet_cm2_s, d_ins_matrix_cm2_s)
    d_ext = d_ins_matrix_cm2_s * (fibrin_d_factor if fibrin_um > 0.0 else 1.0)
    op = Standalone3DFVOperator(
        d_field, dx, dx, dz,
        standoff_bot_cm=fibrin_um * 1e-4, standoff_top_cm=fibrin_um * 1e-4,
        p_ext_bot=d_ext, p_ext_top=d_ext, top_adiabatic=top_adiabatic,
    )
    b_rob = op.b_rob.ravel()
    src = np.where(in_cl, 1.0 / max(float(np.sum(in_cl)), 1.0), 0.0).ravel()

    c_vec = pcg_solve_spd(op, np.zeros_like(src), src, rtol=1e-13, maxiter=2500)
    j0 = float(np.sum(b_rob * c_vec))
    s0 = float(np.sum(src))
    ss_mbe = abs(j0 - s0) / max(abs(s0), 1e-30)
    require_cond(ss_mbe < 1e-10, f"Transient insulin steady-state mass-balance violation: {ss_mbe:.3e}")

    k_int = math.log(2.0) / (t50_intrinsic_min * 60.0)
    inv_2_dt = 2.0 / dt_s
    extra_cn = np.full_like(src, inv_2_dt)

    m0 = float(np.sum(c_vec))
    s_cum = 0.0
    j_cum = 0.0
    max_step_mbe = 0.0
    t_prev = 0.0
    f_prev = 1.0
    t50_s = None
    for step in range(1, 240):
        t_cur = step * dt_s
        s_avg_2 = src * (math.exp(-k_int * t_prev) + math.exp(-k_int * t_cur))
        rhs = inv_2_dt * c_vec + op.apply_A(c_vec) + s_avg_2
        c_next = pcg_solve_spd(op, extra_cn, rhs, rtol=1e-12, maxiter=1500)

        dm_step = float(np.sum(c_next - c_vec))
        s_step = 0.5 * dt_s * float(np.sum(s_avg_2))
        j_step = 0.5 * dt_s * float(np.sum(b_rob * (c_vec + c_next)))
        step_mbe = abs(dm_step + j_step - s_step) / max(abs(dm_step), abs(j_step), abs(s_step), 1e-30)
        max_step_mbe = max(max_step_mbe, step_mbe)
        s_cum += s_step
        j_cum += j_step
        c_vec = c_next

        f_cur = float(np.sum(b_rob * c_vec)) / j0
        if f_cur <= 0.5:
            frac = (f_prev - 0.5) / max(f_prev - f_cur, 1e-15)
            t50_s = t_prev + frac * dt_s
            break
        t_prev = t_cur
        f_prev = f_cur

    require_cond(t50_s is not None, "3D FVM insulin shut-off failed to cross 50%")
    m_end = float(np.sum(c_vec))
    cum_mbe = abs((m_end - m0) + j_cum - s_cum) / max(abs(m0), abs(j_cum), abs(s_cum), 1e-30)
    require_cond(max_step_mbe < 1e-10 and cum_mbe < 1e-10, f"Transient insulin CN mass-balance violation: step={max_step_mbe:.3e}, cum={cum_mbe:.3e}")

    t50_min = float(t50_s) / 60.0
    return {
        "h_um": h_um,
        "pitch_um": round(pitch_um, 2),
        "fibrin_um": fibrin_um,
        "bilayer": bilayer,
        "top_adiabatic": top_adiabatic,
        "grid": [nx, nx, nz],
        "t50_3d_fvm_min": round(t50_min, 4),
        "margin_below_3min_s": round((3.0 - t50_min) * 60.0, 2),
        "passes_lt_3p0_min": bool(t50_min < 3.0),
        "ss_rel_mass_balance_error": _fmt_sci_float(ss_mbe),
        "max_step_rel_mass_balance_error": _fmt_sci_float(max_step_mbe),
        "cumulative_rel_mass_balance_error": _fmt_sci_float(cum_mbe),
    }


# =============================================================================
# 5. Exact Crank Diazoxide Washout (GY-014 Kill), Systemic PK, & Decoupled Retrieval Audit
# =============================================================================
def _sphere_washout_times(radius_cm: float, d_cm2_s: float, n_modes: int = 200) -> Dict[str, float]:
    def rem(t: float) -> float:
        s = 0.0
        pref = (math.pi ** 2) * d_cm2_s * t / (radius_cm ** 2)
        for n in range(1, n_modes + 1):
            e = pref * n * n
            if e > 700.0:
                break
            s += math.exp(-e) / (n * n)
        return (6.0 / (math.pi ** 2)) * s

    out: Dict[str, float] = {}
    for label, target in [("t50_s", 0.50), ("t90_s", 0.10), ("t99_s", 0.01)]:
        lo, hi = 0.0, 1e6
        for _ in range(80):
            mid = 0.5 * (lo + hi)
            if rem(mid) > target:
                lo = mid
            else:
                hi = mid
        out[label] = round(0.5 * (lo + hi), 5)
    return out


def _slab_washout_times(half_thickness_cm: float, d_cm2_s: float, n_modes: int = 200) -> Dict[str, float]:
    def rem(t: float) -> float:
        s = 0.0
        pref = (math.pi ** 2) * d_cm2_s * t / (4.0 * half_thickness_cm ** 2)
        for k in range(n_modes):
            odd = 2 * k + 1
            e = pref * odd * odd
            if e > 700.0:
                break
            s += math.exp(-e) / (odd * odd)
        return (8.0 / (math.pi ** 2)) * s

    out: Dict[str, float] = {}
    for label, target in [("t50_s", 0.50), ("t90_s", 0.10), ("t99_s", 0.01)]:
        lo, hi = 0.0, 1e6
        for _ in range(80):
            mid = 0.5 * (lo + hi)
            if rem(mid) > target:
                lo = mid
            else:
                hi = mid
        out[label] = round(0.5 * (lo + hi), 4)
    return out


def compute_gy014_diazoxide_kill_and_h46_exvivo(c: Dict[str, Any]) -> Dict[str, Any]:
    diff_regimes = [
        ("free_interstitial_5e-6", 5.0e-6),
        ("hindered_hydrogel_2e-6", 2.0e-6),
        ("cellular_retarded_Kp10_3e-7", 3.0e-7),
        ("hydrophobic_PPCN_Kp50_6e-8", 6.0e-8),
    ]
    sphere_65um = {name: _sphere_washout_times(32.5e-4, dval) for name, dval in diff_regimes}
    slab_85um = {name: _slab_washout_times(42.5e-4, dval) for name, dval in diff_regimes}
    slab_120um = {name: _slab_washout_times(60.0e-4, dval) for name, dval in diff_regimes}
    slab_350um = {name: _slab_washout_times(175.0e-4, dval) for name, dval in diff_regimes}

    require_cond(abs(sphere_65um["free_interstitial_5e-6"]["t50_s"] - 0.06453) <= 0.0005, "Bare 65um t50 drift")
    require_cond(abs(sphere_65um["free_interstitial_5e-6"]["t90_s"] - 0.38656) <= 0.001, "Bare 65um t90 drift")
    require_cond(1.40 <= slab_120um["free_interstitial_5e-6"]["t50_s"] <= 1.45, "120um free slab t50 drift")
    require_cond(3.50 <= slab_120um["hindered_hydrogel_2e-6"]["t50_s"] <= 3.58, "120um gel slab t50 drift")

    # Systemic oral Proglycem free plasma PK (90-94% albumin bound -> fu = 0.06..0.10; NO unsubstantiated toxicity multiplier claim)
    ec50, n_h, max_ocr = 35.0, 1.6, 0.30
    ic50_sdh, n_sdh = 400.0, 1.8
    systemic_pk = []
    for total_ug_ml in (10.0, 20.0, 35.0):
        total_uM = (total_ug_ml / 230.68) * 1000.0
        for fu in (0.06, 0.10):
            free_uM = total_uM * fu
            occ = (free_uM ** n_h) / (free_uM ** n_h + ec50 ** n_h)
            systemic_pk.append({
                "total_plasma_ug_mL": total_ug_ml,
                "total_uM": round(total_uM, 2),
                "free_fraction_fu": fu,
                "free_uM": round(free_uM, 2),
                "katp_occupancy_pct": round(100.0 * occ, 2),
                "modeled_max_ocr_cut_at_20mM_glc_pct": round(100.0 * max_ocr * occ, 2),
            })
    req_total_ug_ml_100free = round((100.0 / 0.08) * 230.68 / 1000.0, 1)

    # Single-point parametric ATP illustration anchored ONLY to Grimmsmann & Rustenbeck 1998 (500 uM -> -29% ATP)
    sdh_ref = (500.0 ** n_sdh) / (500.0 ** n_sdh + ic50_sdh ** n_sdh)
    dose_window = []
    for c0 in (50.0, 100.0, 150.0, 325.0, 500.0):
        occ = (c0 ** n_h) / (c0 ** n_h + ec50 ** n_h)
        atp_drop = 29.0 * ((c0 ** n_sdh) / (c0 ** n_sdh + ic50_sdh ** n_sdh)) / sdh_ref
        dose_window.append({
            "diazoxide_uM": c0,
            "katp_occupancy_frac": round(occ, 4),
            "modeled_exvivo_ocr_drop_pct": round(100.0 * max_ocr * occ, 2),
            "parametric_1pt_illustration_atp_drop_pct": round(atp_drop, 2),
            "within_h46_exvivo_prospective_window": bool(100.0 <= c0 <= 150.0),
        })

    wash_dilution_steps = []
    conc = 150.0
    for step in range(0, 4):
        wash_dilution_steps.append({
            "wash_cycle": step,
            "ideal_supernatant_diazoxide_uM": round(conc, 6),
            "below_lcms_loq_0p05uM": bool(conc <= 0.05),
            "below_alpha_glucagon_threshold_30uM": bool(conc < 30.0),
        })
        conc /= 20.0

    # Decoupled Retrievability Burden Audit (NO division of surgical mass fraction into OQ-012 clonogenic regrowth!)
    total_cells = 933_500_000
    f_clon = 1e-4
    retr_audit = {}
    for pct in (85.0, 95.0, 99.0, 99.9):
        rem_frac = 1.0 - pct / 100.0
        retr_audit[f"surgical_mass_recovery_{pct}pct"] = {
            "residual_mass_fraction": round(rem_frac, 6),
            "residual_IEQ_of_500k": round(500_000.0 * rem_frac, 1),
            "residual_living_cells_of_933p5M": int(round(total_cells * rem_frac)),
            "residual_putative_clonogens_at_1e-4": round(total_cells * f_clon * rem_frac, 2),
            "residual_stored_insulin_IU_at_138p3_cap": round(138.3 * rem_frac, 4),
            "sufficient_alone_to_satisfy_oq012_without_switch": False,
        }

    # Needle fluid bleb homogeneous slab O2 collapse (GY-028(3))
    alpha = c["alpha_o2_nominal_mol_cm3_mmhg"]
    d_eff = 1.4e-5
    q_areal_2500 = 2500.0 * c["vol_1_ieq_cm3"] * c["vmax_islet_pure_mol_cm3_s"] * 1.15 * 1.097
    bleb_audit = []
    for h_um in (120.0, 250.0, 400.0):
        h_cm = h_um * 1e-4
        dp_bi = (q_areal_2500 * h_cm) / (8.0 * d_eff * alpha)
        dp_uni = (q_areal_2500 * h_cm) / (2.0 * d_eff * alpha)
        bleb_audit.append({
            "bleb_thickness_um": h_um,
            "loading_ieq_cm2": 2500.0,
            "slab_center_pO2_35mmHg_bilateral_mmhg": round(max(0.0, 35.0 - dp_bi), 2),
            "slab_worst_pO2_35mmHg_unilateral_mmhg": round(max(0.0, 35.0 - dp_uni), 2),
        })

    return {
        "gy014_status": "IN_VIVO_72H_DIAZOXIDE_KILLED_BLOCK",
        "diazoxide_mw_da": 230.68,
        "sphere_65um_bare_cluster_washout": sphere_65um,
        "slab_85um_washout": slab_85um,
        "slab_120um_washout": slab_120um,
        "slab_350um_route1_matches_gy014_7_to_177s": slab_350um,
        "overestimate_factor_vs_3h_bare_65um": round(10800.0 / sphere_65um["free_interstitial_5e-6"]["t50_s"], 1),
        "overestimate_factor_vs_3h_120um_gel": round(10800.0 / slab_120um["hindered_hydrogel_2e-6"]["t50_s"], 1),
        "systemic_oral_proglycem_free_pk": systemic_pk,
        "required_total_plasma_ug_mL_for_100uM_free_at_fu0p08": req_total_ug_ml_100free,
        "systemic_pk_epistemic_note": (
            "Albumin binding (90-94%, fu=0.06-0.10) limits free plasma diazoxide to 2.60-8.67 uM at 10-20 ug/mL total; "
            "reaching 100 uM free requires ~288.4 ug/mL total (14.4-28.8x the 10-20 ug/mL reference plasma concentration range), "
            "with no unsubstantiated human toxicity threshold multiple claimed."
        ),
        "alpha_cell_glucagon_suppression_threshold_uM": 30.0,
        "alpha_cell_glucagon_suppression_pmid": "17503968",
        "exvivo_dose_selectivity_illustration": {
            "model_scope": "SINGLE_POINT_PARAMETRIC_ILLUSTRATION_ANCHORED_TO_GRIMMSMANN_1998_500UM_MINUS_29PCT_ONLY",
            "warning": "Not a multi-point fitted dose-response curve; Stage-0 FCCP maximal reserve measurement (H46E-01) is mandatory.",
            "rows": dose_window,
        },
        "preclinical_evidence_scope_fidelity": {
            "ma_2013_pmid23935835": (
                "40% hypoxic necrosis reduction and preserved post-rest glucose-stimulated OCR are 22 h rat islet endpoints "
                "(where hypoxia-associated apoptosis was observed and not reversed by diazoxide, and residual diazoxide carryover was not ruled out); "
                "the two-preparation human pilot used 22 h / 325 uM; the human-islet xenograft used 48 h / 325 uM with 14-day follow-up in mice."
            ),
            "wang_2020_pmid32433410": (
                "8 h / 150 uM diazoxide preservation of whole NHP donor pancreata during procurement/cold storage, "
                "with functional efficacy assessed after transplantation into diabetic mice."
            ),
            "tudca_pmid20541525_and_pmid24225943": (
                "Porcine (Lee 2010) and mouse (Engin 2013, which carries a published author-spelling correction notice) preclinical anchors; "
                "human SC-islet paired validation remains prospective under H46E-01..04."
            ),
        },
        "h46_exvivo_clinical_protocol": {
            "preconditioning_duration_h": 22.0,
            "diazoxide_uM_range": [100.0, 150.0],
            "tudca_gmp_uM": 250.0,
            "ferrostatin_1_excluded_from_clinical_lead": True,
            "isrib_excluded_from_clinical_lead": True,
            "design_a_strictly_excluded_from_exvivo_rest": True,
            "design_a_preexisting_catalase_hydrogel_exception_disclosed": (
                "Governed v0.8.0 Design A retains its pre-existing passive CaO2-PDMS + >=20 um planar recombinant human P04040 "
                "catalase barrier hydrogel (GY-013 / live GATE-31), with zero additional immobilized cuff proteins, zero soluble biologics, "
                "zero ex-vivo rest, and zero drugs."
            ),
            "eligible_arms_for_optional_exvivo_rest": ["B", "X", "Y", "D", "Z"],
            "min_washout_cycles": 3,
            "lcms_distinct_supernatant_and_pellet_loq_cap_uM": 0.05,
            "day0_invivo_fvm_ocr_credit_pct": 0.0,
            "primary_h4_credit_pp": 0.0,
            "prospective_sensitivity_h4_credit_pp": 1.5,
            "prospective_sensitivity_scope": "All eligible non-A arms (B/X/Y/D/Z) ONLY pending paired H46E-01..04 wet-lab qualification; zero primary portfolio credit.",
            "paired_perioperative_clamp_gate": "R3P-06 (5-day euglycemic insulin clamp 100-180 mg/dL)",
            "ideal_washout_dilution_illustration": wash_dilution_steps,
        },
        "decoupled_retrievability_and_oq012_audit": {
            "epistemic_status": "PROSPECTIVE_STAGE1_ENDPOINT_NOT_YET_ACHIEVED",
            "prospective_stage1_mass_recovery_target_pct": 99.9,
            "oq012_governing_gate": "BLUEPRINT_GATE_5_LONG_HORIZON_CLONOGENIC_ERADICATION (distinct from acute stressed 5-lineage Gate 0V-Kill under GY-030)",
            "three_separate_non_commensurate_endpoints": [
                "1_surgical_mass_recovery_pct (prospective Stage-1 R4O-04 porcine/NHP partial-omentectomy endpoint >= 99.9%)",
                "2_residual_viable_cell_localization_and_burden (histology/bioluminescence/C-peptide extinction; 99.9% still leaves 500 IEQ / 933,500 cells / 93.35 putative clonogens at 1e-4)",
                "3_post_switch_clonogenic_regrowth_oq012 (<= 1e-8 long-horizon pan-lineage clonogenic eradication owned by Blueprint Gate 5, strictly distinct from acute 24-h/72-h stressed 5-lineage Gate 0V-Kill under GY-030 — never divided by surgical mass fraction)",
            ],
            "residual_burden_by_recovery_fraction": retr_audit,
        },
        "needle_bleb_gy028_3_collapse_audit": bleb_audit,
    }


# =============================================================================
# 6. Exact 2^20 Common-Shock Portfolio Engine & Hash-Verified Master Contract Parity (S.2)
# =============================================================================
def biv_bern(p1: float, p2: float, phi: float) -> Dict[Tuple[int, int], float]:
    require_cond(0.0 <= p1 <= 1.0 and 0.0 <= p2 <= 1.0 and 0.0 <= phi <= 1.0, f"Invalid biv_bern inputs: {p1}, {p2}, {phi}")
    p11 = (1.0 - phi) * (p1 * p2) + phi * min(p1, p2)
    out = {
        (0, 0): 1.0 - p1 - p2 + p11,
        (1, 0): p1 - p11,
        (0, 1): p2 - p11,
        (1, 1): p11,
    }
    for k, v in out.items():
        require_cond(v >= -1e-12, f"Negative biv_bern prob {k}={v}")
        out[k] = max(0.0, v)
    require_cond(abs(sum(out.values()) - 1.0) < 1e-12, "biv_bern sum != 1")
    return out


def frechet_joint(probs: Sequence[float], phi: float) -> List[float]:
    m = len(probs)
    require_cond(0.0 <= phi <= 1.0, f"Invalid phi={phi}")
    for p in probs:
        require_cond(0.0 <= p <= 1.0, f"Invalid marginal p={p}")
    n_states = 1 << m
    d_ind = [0.0] * n_states
    for mask in range(n_states):
        w = 1.0
        for i in range(m):
            w *= probs[i] if (mask & (1 << i)) else (1.0 - probs[i])
        d_ind[mask] = w
    if phi == 0.0:
        return d_ind
    order = sorted(range(m), key=lambda i: probs[i])
    d_pos = [0.0] * n_states
    prev = 0.0
    for idx, i in enumerate(order):
        w = probs[i] - prev
        if w > 0.0:
            d_pos[sum(1 << j for j in order[idx:])] += w
        prev = probs[i]
    d_pos[0] += 1.0 - prev
    out = [(1.0 - phi) * d_ind[s] + phi * d_pos[s] for s in range(n_states)]
    require_cond(all(v >= -1e-12 for v in out) and abs(sum(out) - 1.0) < 1e-12, "frechet_joint sum/sign error")
    return [max(0.0, v) for v in out]


def frechet_couple(base_dist: Sequence[float], u_new: float, phi: float, event_fn: Callable[[int], bool]) -> List[float]:
    n0 = len(base_dist)
    require_cond(abs(sum(base_dist) - 1.0) < 1e-12 and 0.0 <= u_new <= 1.0 and 0.0 <= phi <= 1.0, "Invalid frechet_couple args")
    p_e1 = sum(base_dist[mi] for mi in range(n0) if event_fn(mi))
    p_e0 = 1.0 - p_e1
    d_ind = [0.0] * (2 * n0)
    for mi in range(n0):
        w = base_dist[mi]
        d_ind[mi] = w * (1.0 - u_new)
        d_ind[mi | n0] = w * u_new
    d_pos = [0.0] * (2 * n0)
    p11 = min(p_e1, u_new)
    p10 = p_e1 - p11
    p01 = max(0.0, u_new - p_e1)
    p00 = p_e0 - p01
    for mi in range(n0):
        w = base_dist[mi]
        if w == 0.0:
            continue
        if event_fn(mi):
            frac = w / p_e1 if p_e1 > 0.0 else 0.0
            d_pos[mi] = p10 * frac
            d_pos[mi | n0] = p11 * frac
        else:
            frac = w / p_e0 if p_e0 > 0.0 else 0.0
            d_pos[mi] = p00 * frac
            d_pos[mi | n0] = p01 * frac
    out = [(1.0 - phi) * d_ind[k] + phi * d_pos[k] for k in range(2 * n0)]
    require_cond(all(v >= -1e-12 for v in out) and abs(sum(out) - 1.0) < 1e-12, "frechet_couple sum/sign error")
    return [max(0.0, v) for v in out]


def strassen_bipartite_bounds(
    v_h123: Sequence[float],
    dh4: Sequence[float],
    routes: Tuple[str, ...],
    cell_classes: Tuple[str, ...],
    compat_map: Mapping[str, FrozenSet[str]],
) -> Tuple[float, float]:
    n = len(routes)
    all_routes = sorted(set(routes))
    r_idx = {r: k for k, r in enumerate(all_routes)}
    cell_groups: Dict[int, float] = {}
    for mc, wc in enumerate(v_h123):
        if wc == 0.0:
            continue
        rmask = 0
        for i in range(n):
            if (mc >> i) & 1:
                for r in compat_map[cell_classes[i]]:
                    if r in r_idx:
                        rmask |= 1 << r_idx[r]
        cell_groups[rmask] = cell_groups.get(rmask, 0.0) + wc
    route_groups: Dict[int, float] = {}
    for mh, wh in enumerate(dh4):
        if wh == 0.0:
            continue
        rmask = 0
        for j in range(n):
            if (mh >> j) & 1:
                rmask |= 1 << r_idx[routes[j]]
        route_groups[rmask] = route_groups.get(rmask, 0.0) + wh

    c_keys = list(cell_groups.keys())
    r_keys = list(route_groups.keys())
    c_vals = [cell_groups[k] for k in c_keys]
    r_vals = [route_groups[k] for k in r_keys]
    require_cond(len(c_keys) <= 16, f"Unexpected cell_groups size: {len(c_keys)}")

    max_def_e = 0.0
    max_def_ec = 0.0
    for sm in range(1 << len(c_keys)):
        p_s = 0.0
        neigh_e = [False] * len(r_keys)
        neigh_ec = [False] * len(r_keys)
        for i in range(len(c_keys)):
            if (sm >> i) & 1:
                p_s += c_vals[i]
                cm = c_keys[i]
                for j, rm in enumerate(r_keys):
                    if (cm & rm) != 0:
                        neigh_e[j] = True
                    else:
                        neigh_ec[j] = True
        p_ne = sum(r_vals[j] for j in range(len(r_keys)) if neigh_e[j])
        p_nec = sum(r_vals[j] for j in range(len(r_keys)) if neigh_ec[j])
        if p_s - p_ne > max_def_e:
            max_def_e = p_s - p_ne
        if p_s - p_nec > max_def_ec:
            max_def_ec = p_s - p_nec
    return max(0.0, max_def_ec) * 100.0, min(1.0, 1.0 - max_def_e) * 100.0


def eval_core_3arm_l0() -> Dict[str, Any]:
    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)]
    c1, c2, c3, c4 = 0.88, 0.87, 0.89, 0.85
    d1 = [0.0] * 8
    d1[0], d1[7] = 1.0 - c1, c1
    d2_c = frechet_joint([a[1] / c2 for a in arms], 0.0)
    d2 = [1.0 - c2 + c2 * d2_c[0]] + [c2 * d2_c[m] for m in range(1, 8)]
    d3_c = frechet_joint([a[2] / c3 for a in arms], 0.0)
    d3 = [1.0 - c3 + c3 * d3_c[0]] + [c3 * d3_c[m] for m in range(1, 8)]
    d4 = [0.0] * 8
    d4[0] = 1.0 - c4
    r1_j = frechet_joint([arms[0][3] / c4, arms[2][3] / c4], 1.0)
    u_b = arms[1][3] / c4
    for m_ax, p_ax in enumerate(r1_j):
        m_real = (1 if (m_ax & 1) else 0) | (4 if (m_ax & 2) else 0)
        d4[m_real] += c4 * p_ax * (1.0 - u_b)
        d4[m_real | 2] += c4 * p_ax * u_b

    dists = [d1, d2, d3, d4]
    v = d1
    for h in (1, 2):
        nxt = [0.0] * 8
        for m1, w1 in enumerate(v):
            if w1 == 0.0:
                continue
            for m2, w2 in enumerate(dists[h]):
                if w2 != 0.0:
                    nxt[m1 & m2] += w1 * w2
        v = nxt
    locked = 0.0
    mod = 0.0
    for mc in range(1, 8):
        for mh in range(1, 8):
            w = v[mc] * d4[mh]
            if w == 0.0:
                continue
            if mc & mh:
                locked += w
            mod += w
    return {
        "name": "L0_core_3arm",
        "locked_exact": locked * 100.0,
        "modular_exact": mod * 100.0,
        "ceiling_exact": c1 * c2 * c3 * c4 * 100.0,
        "locked_pct": round(locked * 100.0, 4),
        "modular_pct": round(mod * 100.0, 4),
        "ceiling_pct": round(c1 * c2 * c3 * c4 * 100.0, 4),
        "hurdle_caps_exact_pct": [x * 100.0 for x in (c1, c2, c3, c4)],
        "hurdle_caps_pct": [round(x * 100.0, 4) for x in (c1, c2, c3, c4)],
        "hurdle_any_success_exact_pct": [(1.0 - d[0]) * 100.0 for d in dists],
        "hurdle_any_success_pct": [round((1.0 - d[0]) * 100.0, 4) for d in dists],
    }


def eval_5arm_2pow20_exact(
    name: str,
    arms: List[Tuple[float, float, float, float]],
    *,
    c1_allo: float = 0.88,
    c2_inc: float = 0.87,
    c2_y: float = 0.87,
    c2_univ: float = 0.95,
    c2_d: float = 0.93,
    c3_base: float = 0.89,
    c4_univ: float = 0.92,
    c4_pouch: float = 0.85,
    c4_r3p: float = 0.85,
    c4_r4: float | None = None,
    phi_r4: float = 0.30,
    two_site_nested_subars: bool = False,
    routes: Tuple[str, ...] = ("R1", "R2", "R1", "R3P", "R3P"),
    cell_classes: Tuple[str, ...] = ("INC", "INC", "INC", "STAGED_BASE", "STAGED_BASE"),
    compat_map: Dict[str, FrozenSet[str]] | None = None,
    phi_c: float = 0.25,
    phi_inc: float = 0.0,
    phi_yx: float = 0.75,
    allow_diagnostic_gy027_violation: bool = False,
) -> Dict[str, Any]:
    require_cond(len(arms) == 5, "Expected exactly 5 arms")
    if compat_map is None:
        compat_map = {"INC": frozenset({"R1", "R2"}), "STAGED_BASE": frozenset({"R3P"})}

    # Strict home-route compatibility & GY-027(1) enforcement (closes Audit locked-selector loophole!)
    if not allow_diagnostic_gy027_violation:
        require_cond("R4" not in compat_map.get("INC", frozenset()), "GY-027(1) violation: INC (A/B/X) cannot use R4")
    for i in range(5):
        allowed = compat_map.get(cell_classes[i], frozenset())
        require_cond(
            routes[i] in allowed,
            f"Home-route compatibility violation: arm {i} (class={cell_classes[i]}) assigned route={routes[i]} not in {sorted(allowed)}",
        )

    require_cond(0.0 < c2_inc <= c2_y <= c2_univ <= 1.0, "H2 cap domain error")
    require_cond(0.0 < c2_d <= c2_univ <= 1.0, "H2 auto cap domain error")

    # H1
    d1 = [0.0] * 32
    u_d = arms[4][0] / c1_allo
    d1[0] = 1.0 - c1_allo
    d1[15] = c1_allo * (1.0 - u_d)
    d1[31] = c1_allo * u_d
    c1_eff = c1_allo

    # H2
    d2_inc = frechet_joint([arms[0][1] / c2_inc, arms[1][1] / c2_inc, arms[2][1] / c2_inc], phi_inc)
    r2 = c2_inc / c2_y
    u_y2 = arms[3][1] / c2_y
    d2_both = frechet_couple(d2_inc, u_y2, phi_yx, lambda mi: bool(mi & 4))
    d2_allo4 = [r2 * x for x in d2_both]
    d2_allo4[0] += (1.0 - r2) * (1.0 - u_y2)
    d2_allo4[8] += (1.0 - r2) * u_y2
    biv2 = biv_bern(c2_y / c2_univ, c2_d / c2_univ, phi_c)
    u_d2 = arms[4][1] / c2_d
    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)])

    # H3
    d3_inc = frechet_joint([arms[0][2] / c3_base, arms[1][2] / c3_base, arms[2][2] / c3_base], phi_inc)
    d3_both = frechet_couple(d3_inc, arms[3][2] / c3_base, phi_yx, lambda mi: bool(mi & 4))
    d3_5cond = frechet_couple(d3_both, arms[4][2] / c3_base, phi_c, lambda m4: m4 != 0)
    d3 = [c3_base * x for x in d3_5cond]
    d3[0] += 1.0 - c3_base
    c3_eff = c3_base

    # H4
    if c4_r4 is None:
        sh4 = biv_bern(c4_pouch / c4_univ, c4_r3p / c4_univ, phi_c)
        d4 = [0.0] * 32
        d4[0] = 1.0 - c4_univ
        for (sp, s3), ws in sh4.items():
            wt = c4_univ * ws
            route_masks = []
            for rname, sflag, cr in [("R1", sp, c4_pouch), ("R2", sp, c4_pouch), ("R3P", s3, c4_r3p)]:
                idxs = [i for i in range(5) if routes[i] == rname]
                if not idxs:
                    continue
                if sflag == 0:
                    route_masks.append([(0, 1.0)])
                else:
                    fj = frechet_joint([arms[i][3] / cr for i in idxs], 1.0)
                    route_masks.append([(sum((1 << idxs[k]) for k in range(len(idxs)) if (bm >> k) & 1), pr) for bm, pr in enumerate(fj) if pr > 0.0])
            comb = [(0, wt)]
            for ev in route_masks:
                comb = [(m0 | m1, w0 * w1) for m0, w0 in comb for m1, w1 in ev]
            for mf, wf in comb:
                d4[mf] += wf
        c4_eff = c4_univ * (1.0 - sh4[(0, 0)])
    else:
        if two_site_nested_subars:
            biv_subars = biv_bern(c4_r3p / c4_univ, c4_r4 / c4_univ, phi_r4)
            sub_dist = [biv_subars[(0, 0)], biv_subars[(1, 0)], biv_subars[(0, 1)], biv_subars[(1, 1)]]
            triv_nested = frechet_couple(sub_dist, c4_pouch / c4_univ, phi_c, lambda m: m != 0)
            sh4_list = [0.0] * 8
            for m, w in enumerate(triv_nested):
                sr3, sr4, sp = (m & 1), (m >> 1) & 1, (m >> 2) & 1
                sh4_list[sp | (sr3 << 1) | (sr4 << 2)] += w
        else:
            biv_sub = biv_bern(c4_pouch / c4_univ, c4_r3p / c4_univ, phi_c)
            d_sub = [biv_sub[(0, 0)], biv_sub[(1, 0)], biv_sub[(0, 1)], biv_sub[(1, 1)]]
            sh4_list = frechet_couple(d_sub, c4_r4 / c4_univ, phi_r4, lambda m: m != 0)

        d4 = [0.0] * 32
        d4[0] = 1.0 - c4_univ
        for sm, ws in enumerate(sh4_list):
            wt = c4_univ * ws
            if wt == 0.0:
                continue
            sp, s3, s4 = (sm >> 0) & 1, (sm >> 1) & 1, (sm >> 2) & 1
            route_masks = []
            for rname, sflag, cr in [("R1", sp, c4_pouch), ("R2", sp, c4_pouch), ("R3P", s3, c4_r3p), ("R4", s4, c4_r4)]:
                idxs = [i for i in range(5) if routes[i] == rname]
                if not idxs:
                    continue
                if sflag == 0:
                    route_masks.append([(0, 1.0)])
                else:
                    fj = frechet_joint([arms[i][3] / cr for i in idxs], 1.0)
                    route_masks.append([(sum((1 << idxs[k]) for k in range(len(idxs)) if (bm >> k) & 1), pr) for bm, pr in enumerate(fj) if pr > 0.0])
            comb = [(0, wt)]
            for ev in route_masks:
                comb = [(m0 | m1, w0 * w1) for m0, w0 in comb for m1, w1 in ev]
            for mf, wf in comb:
                d4[mf] += wf
        c4_eff = c4_univ * (1.0 - sh4_list[0])

    dists = [d1, d2, d3, d4]
    eff_ceils = [c1_eff, c2_eff, c3_eff, c4_eff]
    max_marg_err = 0.0
    for h in range(4):
        require_cond(abs(sum(dists[h]) - 1.0) < 1e-12, f"H{h+1} dist sum != 1")
        require_cond(eff_ceils[h] >= (1.0 - dists[h][0]) - 1e-12, f"H{h+1} incoherent ceiling")
        for i in range(5):
            marg = sum(dists[h][m] for m in range(32) if (m >> i) & 1)
            err = abs(marg - arms[i][h])
            max_marg_err = max(max_marg_err, err)
            require_cond(err < 1e-9, f"Arm {i} H{h+1} marginal mismatch: {marg} vs {arms[i][h]}")

    v = d1
    for h in (1, 2):
        nxt = [0.0] * 32
        dh = dists[h]
        for m1, w1 in enumerate(v):
            if w1 == 0.0:
                continue
            for m2, w2 in enumerate(dh):
                if w2 != 0.0:
                    nxt[m1 & m2] += w1 * w2
        v = nxt
    v_h123 = v

    locked = 0.0
    mod100 = 0.0
    for mc in range(1, 32):
        wc = v_h123[mc]
        if wc == 0.0:
            continue
        allowed_r = set()
        for i in range(5):
            if (mc >> i) & 1:
                allowed_r.update(compat_map[cell_classes[i]])
        for mh in range(1, 32):
            wh = d4[mh]
            if wh == 0.0:
                continue
            if (mc & mh) != 0:
                locked += wc * wh
            if any(routes[j] in allowed_r for j in range(5) if (mh >> j) & 1):
                mod100 += wc * wh

    s_min, s_max = strassen_bipartite_bounds(v_h123, d4, routes, cell_classes, compat_map)
    return {
        "name": name,
        "locked_exact": locked * 100.0,
        "modular_exact": mod100 * 100.0,
        "ceiling_exact": math.prod(eff_ceils) * 100.0,
        "locked_pct": round(locked * 100.0, 4),
        "modular_pct": round(mod100 * 100.0, 4),
        "ceiling_pct": round(math.prod(eff_ceils) * 100.0, 4),
        "hurdle_caps_exact_pct": [x * 100.0 for x in eff_ceils],
        "hurdle_caps_pct": [round(x * 100.0, 4) for x in eff_ceils],
        "hurdle_any_success_exact_pct": [(1.0 - d[0]) * 100.0 for d in dists],
        "hurdle_any_success_pct": [round((1.0 - d[0]) * 100.0, 4) for d in dists],
        "strassen_h123_h4_exact": [s_min, s_max],
        "strassen_h123_h4_pct": [round(s_min, 4), round(s_max, 4)],
        "max_marginal_err": _fmt_sci_float(max_marg_err),
    }


def _check_contract_cell_parity(
    computed: Dict[str, Any],
    target: Dict[str, Any],
    label: str,
    honest_exact: float | None = None,
    *,
    exact_tol: float = 1e-12,
) -> Tuple[float, float]:
    """Verify BOTH unrounded float64 (*_exact, <1e-12) AND 4-decimal display (*_pct, ==0.0) parity."""
    max_exact_err = 0.0
    max_disp_err = 0.0

    for exact_key in ("locked_exact", "modular_exact", "ceiling_exact"):
        require_cond(exact_key in target and exact_key in computed, f"Missing {exact_key} in {label}")
        err = abs(float(computed[exact_key]) - float(target[exact_key]))
        max_exact_err = max(max_exact_err, err)
        require_cond(
            err < exact_tol,
            f"Unrounded contract parity fail on {label}.{exact_key}: got {computed[exact_key]!r}, expected {target[exact_key]!r} (err={err:.3e})",
        )

    for disp_key in ("locked_pct", "modular_pct", "ceiling_pct"):
        err = abs(float(computed[disp_key]) - float(target[disp_key]))
        max_disp_err = max(max_disp_err, err)
        require_cond(err == 0.0, f"Display contract parity fail on {label}.{disp_key}: got {computed[disp_key]}, expected {target[disp_key]}")

    for exact_list_key in ("hurdle_caps_exact_pct", "hurdle_any_success_exact_pct", "strassen_h123_h4_exact"):
        if exact_list_key in target:
            require_cond(exact_list_key in computed, f"Missing {exact_list_key} in computed {label}")
            require_cond(len(computed[exact_list_key]) == len(target[exact_list_key]), f"{label}.{exact_list_key} len mismatch")
            for a, b in zip(computed[exact_list_key], target[exact_list_key]):
                err = abs(float(a) - float(b))
                max_exact_err = max(max_exact_err, err)
                require_cond(
                    err < exact_tol,
                    f"Unrounded contract parity fail on {label}.{exact_list_key}: {computed[exact_list_key]} vs {target[exact_list_key]} (err={err:.3e})",
                )

    for disp_list_key in ("hurdle_caps_pct", "hurdle_any_success_pct", "strassen_h123_h4_pct"):
        if disp_list_key in target:
            require_cond(len(computed[disp_list_key]) == len(target[disp_list_key]), f"{label}.{disp_list_key} len mismatch")
            for a, b in zip(computed[disp_list_key], target[disp_list_key]):
                err = abs(float(a) - float(b))
                max_disp_err = max(max_disp_err, err)
                require_cond(err == 0.0, f"Display contract parity fail on {label}.{disp_list_key}: {computed[disp_list_key]} vs {target[disp_list_key]}")

    if honest_exact is not None and "delta_vs_honest_l1_exact_pp" in target:
        calc_delta_exact = float(computed["modular_exact"]) - float(honest_exact)
        err_ex = abs(calc_delta_exact - float(target["delta_vs_honest_l1_exact_pp"]))
        max_exact_err = max(max_exact_err, err_ex)
        require_cond(
            err_ex < exact_tol,
            f"Unrounded contract parity fail on {label}.delta_vs_honest_l1_exact_pp: {calc_delta_exact!r} vs {target['delta_vs_honest_l1_exact_pp']!r}",
        )
        if "delta_vs_honest_l1_pct_pp" in target:
            calc_delta_pct = round(calc_delta_exact, 4)
            err_dp = abs(calc_delta_pct - float(target["delta_vs_honest_l1_pct_pp"]))
            max_disp_err = max(max_disp_err, err_dp)
            require_cond(
                err_dp == 0.0,
                f"Display contract parity fail on {label}.delta_vs_honest_l1_pct_pp: {calc_delta_pct} vs {target['delta_vs_honest_l1_pct_pp']}",
            )
    return max_exact_err, max_disp_err


def compute_portfolio_verification(contracts: Dict[str, Any]) -> Dict[str, Any]:
    mc = contracts["contract"]
    rs = mc["reachable_scenarios"]
    dc = mc["diagnostic_prerequisite_waived_counterfactuals"]

    l0 = eval_core_3arm_l0()
    l1_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), (0.62, 0.92, 0.70, 0.70)]
    w5_arms = [(0.90, 0.78, 0.68, 0.745), (0.90, 0.79, 0.73, 0.775), (0.90, 0.82, 0.83, 0.745), (0.90, 0.84, 0.84, 0.735), (0.66, 0.92, 0.755, 0.715)]

    base_r = ("R1", "R2", "R1", "R3P", "R3P")
    r4_r = ("R1", "R2", "R1", "R3P", "R4")
    base_c = ("INC", "INC", "INC", "STAGED_BASE", "STAGED_BASE")
    hard_c = ("INC", "INC", "INC", "STAGED_HARDENED", "STAGED_HARDENED")
    base_m = {"INC": frozenset({"R1", "R2"}), "STAGED_BASE": frozenset({"R3P"})}
    hard_r4_m = {"INC": frozenset({"R1", "R2"}), "STAGED_HARDENED": frozenset({"R3P", "R4"})}
    isol_r4_m = {"INC": frozenset({"R1", "R2"}), "STAGED_BASE": frozenset({"R3P", "R4"})}

    b_l1 = eval_5arm_2pow20_exact("L1_shipped_IIP0035_phi0", l1_arms, routes=base_r, cell_classes=base_c, compat_map=base_m, phi_inc=0.0)
    b_w5 = eval_5arm_2pow20_exact("Wave5_L3B_audited_caveated", w5_arms, c1_allo=0.90, c3_base=0.925, routes=base_r, cell_classes=base_c, compat_map=base_m, phi_inc=0.0)
    b_honest = eval_5arm_2pow20_exact("L1_honest_monoculture_phi_inc_0.50", l1_arms, routes=base_r, cell_classes=base_c, compat_map=base_m, phi_inc=0.50)
    honest_exact = b_honest["modular_exact"]

    # Reachable W6-C1 standalone baseline (required to separate conditional C2-given-C1 +4.48 pp from combined C1+C2 +6.48 pp!)
    c1_standalone_arms = [
        (0.88, 0.78, 0.57, 0.69),  # A strictly frozen
        (0.88, 0.80, 0.64, 0.70),  # B
        (0.88, 0.83, 0.73, 0.69),  # X
        (0.88, 0.85, 0.80, 0.72),  # Y-v3
        (0.78, 0.92, 0.68, 0.70),  # D1b-Lean-K2 on R3P
    ]
    r_c1_standalone = eval_5arm_2pow20_exact(
        "W6_C1_standalone_over_honest_L1", c1_standalone_arms,
        routes=base_r, cell_classes=hard_c, compat_map={"INC": frozenset({"R1", "R2"}), "STAGED_HARDENED": frozenset({"R3P"})}, phi_inc=0.25,
    )
    c1_standalone_exact = r_c1_standalone["modular_exact"]

    # Primary REACHABLE prerequisite-enforced W6-C2 + W6-C1 (R4-Omentum, zero ex-vivo rest credit, Design A strictly frozen!)
    c2_plus_c1_arms = [
        (0.88, 0.78, 0.57, 0.69),  # A strictly frozen
        (0.88, 0.80, 0.64, 0.70),  # B
        (0.88, 0.83, 0.73, 0.69),  # X
        (0.88, 0.85, 0.80, 0.72),  # Y-v3
        (0.78, 0.92, 0.68, 0.80),  # D1b-Lean-K2 on R4-Omentum
    ]
    r_c2_plus_c1 = eval_5arm_2pow20_exact(
        "W6_C2_plus_C1_R4Omentum_zeroRest", c2_plus_c1_arms,
        c4_univ=0.950, c4_r4=0.870, phi_r4=0.30,
        routes=r4_r, cell_classes=hard_c, compat_map=hard_r4_m, phi_inc=0.25,
    )

    # Diagnostic prerequisite-waived counterfactuals (explicitly disable C1 prerequisite; 0.0% released-state weight!)
    c2_isol_zero_rest_arms = [
        (0.88, 0.78, 0.57, 0.69),  # A strictly frozen
        (0.88, 0.79, 0.64, 0.70),  # B
        (0.88, 0.82, 0.73, 0.69),  # X
        (0.88, 0.84, 0.80, 0.72),  # Y
        (0.62, 0.92, 0.70, 0.80),  # D on R4-Omentum
    ]
    r_diag_c2_isol_zero = eval_5arm_2pow20_exact(
        "Diag_PrereqWaived_C2_isolated_zeroRest", c2_isol_zero_rest_arms,
        c4_univ=0.950, c4_r4=0.870, phi_r4=0.30,
        routes=r4_r, cell_classes=base_c, compat_map=isol_r4_m, phi_inc=0.50,
    )

    # Diagnostic sensitivity: c4_univ held at incumbent 0.92 (site-only isolation)
    r_diag_c2_c4univ92 = eval_5arm_2pow20_exact(
        "Diag_PrereqWaived_C2_c4univ_held_0.92_site_only", c2_isol_zero_rest_arms,
        c4_univ=0.920, c4_r4=0.870, phi_r4=0.30,
        routes=r4_r, cell_classes=base_c, compat_map=isol_r4_m, phi_inc=0.50,
    )

    # Corrected prospective sensitivity: +1.5 pp ex-vivo rest on ALL eligible non-A arms (B, X, Y, AND D on R4; Design A frozen at 0.69!)
    c2_prospective_rest_all_eligible_arms = [
        (0.88, 0.78, 0.57, 0.69),   # A STRICTLY INVARIANT (ZERO ex-vivo rest!)
        (0.88, 0.79, 0.64, 0.715),  # B +1.5 pp prospective
        (0.88, 0.82, 0.73, 0.705),  # X +1.5 pp prospective
        (0.88, 0.84, 0.80, 0.735),  # Y +1.5 pp prospective
        (0.62, 0.92, 0.70, 0.815),  # D +1.5 pp prospective on R4-Omentum (0.80 + 0.015)
    ]
    r_diag_c2_prospective_rest = eval_5arm_2pow20_exact(
        "Diag_PrereqWaived_C2_prospective_rest_1p5pp_all_eligible_BXYD", c2_prospective_rest_all_eligible_arms,
        c4_univ=0.950, c4_r4=0.870, phi_r4=0.30,
        routes=r4_r, cell_classes=base_c, compat_map=isol_r4_m, phi_inc=0.50,
    )

    # Diagnostic demoted R4-SARS-Free Backup sensitivity (Dual-FailSafe Y-v3 ONLY on R4-SARS; D1b barred from R4-SARS!)
    sars_y_only_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.78),  # Y-v3 on R4-SARS-Free backup (Dual-FailSafe required)
        (0.62, 0.92, 0.70, 0.70),  # D1b stays on R3P (single-switch barred from R4-SARS-Free)
    ]
    sars_classes = ("INC", "INC", "INC", "STAGED_DUAL_SWITCH", "STAGED_SINGLE_SWITCH")
    sars_compat = {
        "INC": frozenset({"R1", "R2"}),
        "STAGED_DUAL_SWITCH": frozenset({"R3P", "R4"}),
        "STAGED_SINGLE_SWITCH": frozenset({"R3P"}),
    }
    r_diag_sars_backup = eval_5arm_2pow20_exact(
        "Diag_PrereqWaived_Demoted_R4SARS_Free_DualSwitch_Y_Only", sars_y_only_arms,
        c4_univ=0.935, c4_r4=0.86, phi_r4=0.75, two_site_nested_subars=True,
        routes=("R1", "R2", "R1", "R4", "R3P"), cell_classes=sars_classes, compat_map=sars_compat, phi_inc=0.50,
    )

    # Verify locked-selector loophole is CLOSED: assigning A directly to R4 MUST raise RuntimeError!
    loophole_blocked = False
    try:
        eval_5arm_2pow20_exact(
            "TEST_ILLEGAL_A_HOME_R4", c2_isol_zero_rest_arms,
            c4_univ=0.950, c4_r4=0.870, phi_r4=0.30,
            routes=("R4", "R2", "R1", "R3P", "R4"), cell_classes=base_c, compat_map=isol_r4_m, phi_inc=0.50,
        )
    except RuntimeError:
        loophole_blocked = True
    require_cond(loophole_blocked, "Locked-selector home-route GY-027(1) guard failed to block Design A on R4")

    # Exact unrounded (<1e-12) AND 4-decimal display (0.0) parity against external Round-3 master contract!
    max_exact_err = 0.0
    max_disp_err = 0.0
    for comp, tgt, lbl, h_ref in [
        (l0, rs["L0_core_3arm"], "L0_core_3arm", None),
        (b_l1, rs["L1_shipped_IIP0035_phi0"], "L1_shipped_IIP0035_phi0", None),
        (b_w5, rs["Wave5_L3B_audited_caveated"], "Wave5_L3B_audited_caveated", None),
        (b_honest, rs["L1_honest_monoculture_phi_inc_0.50"], "L1_honest_monoculture_phi_inc_0.50", None),
        (r_c1_standalone, rs["W6_C1_standalone_over_honest_L1"], "W6_C1_standalone_over_honest_L1", honest_exact),
        (r_c2_plus_c1, rs["W6_C2_plus_C1_R4Omentum_zeroRest"], "W6_C2_plus_C1_R4Omentum_zeroRest", honest_exact),
        (r_diag_c2_isol_zero, dc["Diag_PrereqWaived_C2_isolated_zeroRest"], "Diag_PrereqWaived_C2_isolated_zeroRest", honest_exact),
        (r_diag_c2_c4univ92, dc["Diag_PrereqWaived_C2_c4univ_held_0.92_site_only"], "Diag_PrereqWaived_C2_c4univ_held_0.92_site_only", honest_exact),
        (r_diag_c2_prospective_rest, dc["Diag_PrereqWaived_C2_prospective_rest_1p5pp_all_eligible_BXYD"], "Diag_PrereqWaived_C2_prospective_rest_1p5pp_all_eligible_BXYD", honest_exact),
    ]:
        e_ex, e_dp = _check_contract_cell_parity(comp, tgt, lbl, h_ref, exact_tol=1e-12)
        max_exact_err = max(max_exact_err, e_ex)
        max_disp_err = max(max_disp_err, e_dp)

    require_cond(max_exact_err < 1e-12, f"Unrounded master contract parity exceeded 1e-12: {max_exact_err:.3e}")
    require_cond(max_disp_err == 0.0, f"Display master contract parity non-zero: {max_disp_err}")
    require_cond(r_diag_c2_isol_zero["modular_exact"] > r_diag_sars_backup["modular_exact"], "Lead R4-Omentum must strictly beat demoted R4-SARS-Free backup")

    def _with_deltas(d: Dict[str, Any], *, include_delta: bool = False) -> Dict[str, Any]:
        out = dict(d)
        if include_delta:
            d_hon = d["modular_exact"] - honest_exact
            d_shp = d["modular_exact"] - b_l1["modular_exact"]
            out["delta_vs_honest_l1_exact_pp"] = d_hon
            out["delta_vs_honest_l1_pct_pp"] = round(d_hon, 4)
            out["delta_vs_shipped_l1_exact_pp"] = d_shp
            out["delta_vs_shipped_l1_pct_pp"] = round(d_shp, 4)
        return out

    cond_c2_given_c1_exact_pp = r_c2_plus_c1["modular_exact"] - c1_standalone_exact

    return {
        "external_master_contract_verified": True,
        "external_master_contract_sha256": contracts["contract_sha256"],
        "external_master_contract_file_sha256": contracts["contract_file_sha256"],
        "external_arm_manifest_sha256": contracts["manifest_sha256"],
        "exact_master_contract_parity_max_abs_err_unrounded": max_exact_err,
        "display_master_contract_parity_max_abs_err": max_disp_err,
        "exact_parity_lt_1e12": bool(max_exact_err < 1e-12),
        "live_odds_credit_today_pp": 0.0,
        "rounding_policy": "Both unrounded IEEE-754 float64 (*_exact, verified <1e-12) and 4-decimal display (*_pct, verified ==0.0) values are preserved.",
        "c4_r4_route_cap_epistemic_note": "c4_r4 = 0.87 (and c4_univ = 0.95, phi_r4 = 0.30) is an explicit supplied scenario parameter, NOT a statistically identified parameter from small heterogeneous clinical omental cohorts; live OpenIslet odds credit today is +0.00 pp pending Stage-0/1 clearance.",
        "h1_allo_locked_pct": 88.0,
        "design_a_strictly_invariant_tuple": [0.88, 0.78, 0.57, 0.69],
        "home_route_locked_selector_guard_verified": loophole_blocked,
        "core_3arm_baseline_invariant": dict(l0),
        "reachable_scenarios": {
            "L1_shipped_IIP0035_phi0": dict(b_l1),
            "Wave5_L3B_audited_caveated": dict(b_w5),
            "L1_honest_monoculture_phi_inc_0.50": dict(b_honest),
            "W6_C1_standalone_over_honest_L1": {
                **_with_deltas(r_c1_standalone, include_delta=True),
                "scenario_role": "REACHABLE_W6_C1_STANDALONE_PREREQUISITE_BASELINE",
                "released_state_eligible": True,
            },
            "W6_C2_plus_C1_R4Omentum_zeroRest": {
                **_with_deltas(r_c2_plus_c1, include_delta=True),
                "conditional_c2_given_c1_exact_pp": cond_c2_given_c1_exact_pp,
                "conditional_c2_given_c1_pct_pp": round(cond_c2_given_c1_exact_pp, 4),
                "scenario_role": "PRIMARY_REACHABLE_PREREQUISITE_PAIRED_C2_PLUS_C1_ZERO_EXVIVO_REST_CREDIT",
                "released_state_eligible": True,
                "gy027_1_compliant": True,
                "gy014_compliant": True,
                "design_a_invariant_verified": True,
            },
        },
        "diagnostic_prerequisite_waived_counterfactuals": {
            "scope_warning": "Explicitly disables W6-C1 prerequisites for marginal isolation; carries 0.0% released-state weight and is excluded from reachable qualification comparisons.",
            "released_state_weight_pct": 0.0,
            "Diag_PrereqWaived_C2_isolated_zeroRest": {
                **_with_deltas(r_diag_c2_isol_zero, include_delta=True),
                "scenario_role": "DIAGNOSTIC_PREREQ_WAIVED_ISOLATED_C2_ZERO_EXVIVO_REST_CREDIT",
                "released_state_eligible": False,
                "gy027_1_compliant": True,
                "gy014_compliant": True,
                "design_a_invariant_verified": True,
            },
            "Diag_PrereqWaived_C2_c4univ_held_0.92_site_only": {
                **_with_deltas(r_diag_c2_c4univ92, include_delta=True),
                "scenario_role": "DIAGNOSTIC_PREREQ_WAIVED_C4_UNIV_HELD_0P92_SITE_ONLY",
                "released_state_eligible": False,
            },
            "Diag_PrereqWaived_C2_prospective_rest_1p5pp_all_eligible_BXYD": {
                **_with_deltas(r_diag_c2_prospective_rest, include_delta=True),
                "scenario_role": "DIAGNOSTIC_PREREQ_WAIVED_PROSPECTIVE_REST_1P5PP_ALL_ELIGIBLE_NON_A_ARMS_BXYD_ZERO_PRIMARY_CREDIT",
                "released_state_eligible": False,
                "design_a_invariant_verified": True,
            },
            "Diag_PrereqWaived_Demoted_R4SARS_Free_DualSwitch_Y_Only": {
                **_with_deltas(r_diag_sars_backup, include_delta=True),
                "scenario_role": "DIAGNOSTIC_PREREQ_WAIVED_DEMOTED_BACKUP_DUAL_FAILSAFE_Y_ONLY_D1B_BARRED",
                "released_state_eligible": False,
                "advantage_of_isolated_omentum_zeroRest_exact_pp": r_diag_c2_isol_zero["modular_exact"] - r_diag_sars_backup["modular_exact"],
                "advantage_of_isolated_omentum_zeroRest_pct_pp": round(r_diag_c2_isol_zero["modular_exact"] - r_diag_sars_backup["modular_exact"], 4),
            },
        },
    }


# =============================================================================
# 7. Strict Fail-Closed, Manifest-Linked Gate-33 Adjudicator (Round-4)
# =============================================================================
ALLOWED_CUFF_COMPONENTS_ALLOWLIST: FrozenSet[str] = frozenset({
    "sCR1_v2",
    "THBD-M406L",
    "CD200-ECD",
    "CCL22",
    "IL1RN",
    "IL18BP",
})
ALLOWED_CLINICAL_MATRICES_OMENTUM: FrozenSet[str] = frozenset({
    "GMP_AUTOLOGOUS_PLASMA_THROMBIN",
    "GMP_RESORBABLE_FIBRIN",
})
ALLOWED_CLINICAL_MATRICES_SARS_BACKUP: FrozenSet[str] = frozenset({
    "BIODEGRADABLE_THIN_PLANAR_CARRIER_SHEET",
})
REQUIRED_EXVIVO_REST_AGENTS: FrozenSet[str] = frozenset({
    "DIAZOXIDE_GMP",
    "TUDCA_GMP",
})
BANNED_EXVIVO_TOKENS: FrozenSet[str] = frozenset({
    "FERROSTATIN_1",
    "FER_1",
    "ISRIB",
    "INVIVO_DIAZOXIDE_DEPOT",
})
# Exact live GY-030 5-lineage whole-graft panel (matched verbatim across C1/C2/C4)
REQUIRED_GY030_LINEAGES: FrozenSet[str] = frozenset({
    "alpha",
    "beta",
    "delta",
    "pericyte",
    "plvap_iec",
})
ALLOWED_BANK_ORIGINS: FrozenSet[str] = frozenset({
    "allogeneic_hiPSC",
    "autologous_hiPSC",
    "allogeneic_EnSC",
})
ALLOWED_AUTHORITY_SCOPES: FrozenSet[str] = frozenset({
    "CLINICAL_LOT_RELEASE",
    "BANK_QUALIFICATION_ONLY",
    "STAGE_LIMITED_SORT_ONLY",
    "COMPONENT_SORT_QUALIFICATION_ONLY",
    "WAVE7_RESERVE_ONLY",
    "SYNTHETIC_SELF_TEST",
    "REJECTED_OR_HELD",
})
ALLOWED_SCALE_MODES: FrozenSet[str] = frozenset({
    "CLINICAL_HUMAN_SCALE",
    "ANIMAL_PRECLINICAL_SCALE",
})
ALLOWED_REST_ENDPOINT_TYPES: FrozenSet[str] = frozenset({
    "day7_beta_mass",
    "day14_stimulated_c_peptide",
})
# Unified v2_round4_unified 14-field producer-owned evidence record schema
REQUIRED_UPSTREAM_SCHEMA_V2_STRING_FIELDS: Tuple[str, ...] = (
    "record_id",
    "gate_source",
    "product_id",
    "lot_id",
    "bank_id",
    "bank_origin",
    "canonical_arm_manifest_sha256",
    "construct_manifest_sha256",
    "evidence_tier",
    "decision",
    "authority_scope",
    "archive_sha256",
)
REQUIRED_UPSTREAM_SCHEMA_V2_BOOL_FIELDS: Tuple[str, ...] = (
    "bank_qualified",
    "promotion_authorized",
)
REQUIRED_UPSTREAM_SCHEMA_V2_ALL_FIELDS: Tuple[str, ...] = (
    "record_id",
    "gate_source",
    "product_id",
    "lot_id",
    "bank_id",
    "bank_origin",
    "canonical_arm_manifest_sha256",
    "construct_manifest_sha256",
    "evidence_tier",
    "decision",
    "authority_scope",
    "bank_qualified",
    "promotion_authorized",
    "archive_sha256",
)
REQUIRED_PER_LEAF_FIELDS: Tuple[str, ...] = (
    "leaf_id",
    "loaded_ieq",
    "measured_area_cm2",
    "measured_thickness_um",
    "measured_d_o2_matrix_m2_s",
    "measured_face_o2_mmhg",
    "measured_core_o2_mmhg",
    "bed_face_bot_po2_mmhg",
    "bed_face_top_po2_mmhg",
    "direct_o2_sensor_coverage_verified",
)
PORCINE_MIN_FOLLOWUP_DAYS: float = 60.0
NHP_MIN_FOLLOWUP_DAYS: float = 90.0
MAX_POST_OMENTECTOMY_CPEP_EXTINCTION_WINDOW_DAYS: float = 14.0
PORCINE_MIN_FOLLOWUP_DAYS_DEC: Decimal = Decimal("60")
NHP_MIN_FOLLOWUP_DAYS_DEC: Decimal = Decimal("90")
MAX_POST_OMENTECTOMY_CPEP_EXTINCTION_WINDOW_DAYS_DEC: Decimal = Decimal("14")
NHP_MAX_INSULIN_INDEP_DAY_DEC: Decimal = Decimal("45")

# Porcine cohort: per-subject SURGICAL SAFETY, measurement dates, typed monitored complications, & retrieval/residual reconciliation (Review C2 #1 / Audit F5 / Audit R5-04)
REQUIRED_PORCINE_SUBJECT_FIELDS: Tuple[str, ...] = (
    "subject_id",
    "species",
    "lot_id",
    "followup_duration_days",
    "capsule_sampling_day",
    "retrieval_assessment_day",
    "survival_to_endpoint",
    "major_hemorrhage_or_dehiscence",
    "bowel_obstruction_event",
    "omental_torsion_event",
    "grade3_adhesion_event",
    "monitored_complications",
    "surgical_safety_pass",
    "month3_capsule_um",
    "retrieval_mass_pct",
    "total_implanted_cells",
    "residual_viable_cells_measured",
    "residual_sampling_fraction",
    "localization_verified",
)
# NHP cohort: diabetic enrollment eligibility, measurement dates, typed monitored complications, observed independence vs documented Day-90 nonresponder (Review C2 #1 / Audit F5 / Audit R4-04 / Audit R5-04)
REQUIRED_NHP_SUBJECT_FIELDS: Tuple[str, ...] = (
    "subject_id",
    "species",
    "lot_id",
    "preimplant_diabetic_verified",
    "baseline_exogenous_insulin_u_kg_d",
    "baseline_fasting_c_peptide_ng_ml",
    "dose_ieq_per_kg",
    "achieved_insulin_independence",
    "followup_duration_days",
    "capsule_sampling_day",
    "bowel_obstruction_event",
    "omental_torsion_event",
    "grade3_adhesion_event",
    "monitored_complications",
    "month3_capsule_um",
    "residual_exogenous_insulin_u_kg_d",
    "paired_dynamic_gsis_pass",
    "retrieval_mass_pct",
    "total_implanted_cells",
    "residual_viable_cells_measured",
    "residual_sampling_fraction",
    "localization_verified",
)
REQUIRED_NHP_RESPONDER_PROCEDURE_AND_ENDPOINT_FIELDS: Tuple[str, ...] = (
    "insulin_indep_day",
    "omentectomy_performed",
    "omentectomy_procedure_id",
    "omentectomy_day",
    "cpeptide_extinction_subject_id",
    "cpeptide_extinction_procedure_id",
    "cpeptide_extinction_assessment_day",
    "post_omentectomy_cpeptide_extinguished",
    "portal_gradient_assessment_day",
)
SUBJECT_FOLLOWUP_DATE_ALIAS_KEYS: Tuple[str, ...] = (
    "followup_days",
    "follow_up_days",
    "follow_up_duration_days",
    "followup_day",
)
SUBJECT_CAPSULE_DATE_ALIAS_KEYS: Tuple[str, ...] = (
    "capsule_histology_day",
    "capsule_day",
    "capsule_measurement_day",
    "month3_capsule_day",
    "month3_capsule_sampling_day",
    "histology_day",
)
SUBJECT_RETRIEVAL_DATE_ALIAS_KEYS: Tuple[str, ...] = (
    "retrieval_day",
    "explant_day",
    "omentectomy_day",
    "necropsy_day",
)
NHP_OMENTECTOMY_PROCEDURE_DATE_ALIAS_KEYS: Tuple[str, ...] = (
    "procedure_day",
    "explant_day",
    "omentectomy_procedure_day",
    "explant_omentectomy_day",
    "graft_explant_day",
    "partial_omentectomy_day",
    "retrieval_day",
    "retrieval_assessment_day",
)
NHP_TERMINAL_DATE_ALIAS_KEYS: Tuple[str, ...] = (
    "necropsy_day",
    "terminal_day",
    "euthanasia_day",
)
NHP_CPEP_EXTINCTION_DATE_ALIAS_KEYS: Tuple[str, ...] = (
    "cpeptide_extinction_day",
    "post_omentectomy_cpeptide_assessment_day",
    "post_omentectomy_cpeptide_extinction_day",
    "post_omentectomy_cpeptide_extinction_assessment_day",
    "extinction_assessment_day",
    "extinction_day",
)
NHP_PORTAL_GRADIENT_DATE_ALIAS_KEYS: Tuple[str, ...] = (
    "portal_gradient_day",
    "portal_insulin_gradient_day",
)
NHP_OMENTECTOMY_PERFORMED_ALIAS_KEYS: Tuple[str, ...] = (
    "partial_omentectomy_performed",
    "explant_performed",
    "graft_explant_performed",
    "procedure_performed",
)
NHP_PROCEDURE_ID_ALIAS_KEYS: Tuple[str, ...] = (
    "procedure_id",
    "explant_procedure_id",
    "omentectomy_id",
    "partial_omentectomy_procedure_id",
    "graft_explant_procedure_id",
)
NHP_EXTINCTION_SUBJECT_ID_ALIAS_KEYS: Tuple[str, ...] = (
    "extinction_subject_id",
    "cpeptide_subject_id",
    "post_omentectomy_extinction_subject_id",
)
NHP_EXTINCTION_PROCEDURE_ID_ALIAS_KEYS: Tuple[str, ...] = (
    "extinction_procedure_id",
    "cpeptide_procedure_id",
    "post_omentectomy_extinction_procedure_id",
)
NHP_EXTINCTION_OUTCOME_BOOL_ALIAS_KEYS: Tuple[str, ...] = (
    "post_omentectomy_cpeptide_extinguished",
    "cpeptide_extinguished",
    "post_omentectomy_cpeptide_extinction",
    "cpeptide_extinction",
    "cpeptide_extinction_verified",
    "cpeptide_extinction_confirmed",
    "cpeptide_extinction_achieved",
    "cpeptide_extinction_pass",
    "cpeptide_extinction_result",
    "extinction_verified",
    "extinction_confirmed",
    "extinction_achieved",
    "extinction_result",
    "post_omentectomy_extinction",
    "post_omentectomy_extinction_verified",
    "post_omentectomy_cpeptide_extinction_verified",
    "post_omentectomy_cpeptide_extinction_confirmed",
    "post_omentectomy_cpeptide_extinction_pass",
)
SUBJECT_COMPLICATION_BOOL_ALIAS_GROUPS: Tuple[Tuple[str, ...], ...] = (
    (
        "bowel_obstruction_event",
        "bowel_obstruction",
        "intestinal_obstruction",
        "intestinal_obstruction_event",
        "bowel_obstruction_observed",
    ),
    (
        "omental_torsion_event",
        "omental_torsion",
        "torsion",
        "volvulus",
        "omental_volvulus",
        "omental_torsion_observed",
    ),
    (
        "grade3_adhesion_event",
        "grade3_adhesion",
        "grade3_adhesions",
        "grade_3_adhesion",
        "grade_3_adhesions",
        "adhesion_grade3",
        "adhesion_grade_3",
        "grade3_adhesion_observed",
    ),
    (
        "surgical_complication",
        "major_complication",
    ),
)
SUBJECT_COMPLICATION_BOOL_ALIAS_KEYS: Tuple[str, ...] = (
    "bowel_obstruction",
    "intestinal_obstruction",
    "intestinal_obstruction_event",
    "omental_torsion",
    "torsion",
    "volvulus",
    "omental_volvulus",
    "grade3_adhesion",
    "grade3_adhesions",
    "grade_3_adhesion",
    "grade_3_adhesions",
    "adhesion_grade3",
    "adhesion_grade_3",
    "bowel_obstruction_observed",
    "omental_torsion_observed",
    "grade3_adhesion_observed",
    "surgical_complication",
    "major_complication",
)
SUBJECT_COMPLICATION_LIST_ALIAS_KEYS: Tuple[str, ...] = (
    "adverse_events",
    "adverse_event",
    "complications",
    "complication",
    "surgical_complications",
    "monitored_adverse_events",
    "complication_events",
    "bowel_obstruction_events",
)
ALLOWED_EVIDENCE_TIERS: FrozenSet[str] = frozenset({
    "AUTHENTICATED_ARCHIVED_WETLAB",
    "SYNTHETIC_FIXTURE",
})
GATE0V_BANK_ONLY_DECISIONS: FrozenSet[str] = frozenset({
    "PASS_WHOLEGRAFT_BANK_QUALIFICATION",
    "PASS_COMPOSITE_BANK_QUALIFICATION",
})
GATE0V_ALLOGENEIC_CLINICAL_DECISIONS: FrozenSet[str] = frozenset({
    "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE",
    "PASS_COMPOSITE_CLINICAL_RELEASE",
})
GATE0V_AUTOLOGOUS_CLINICAL_DECISIONS: FrozenSet[str] = frozenset({
    "PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL",
    "PASS_COMPOSITE_AUTOLOGOUS_CLINICAL_RELEASE",
})
ALLOWED_UPSTREAM_WETLAB_DECISIONS: Dict[str, FrozenSet[str]] = {
    "GATE-34": frozenset({"PASS", "PASS_GATE34_CLINICAL_LOT_RELEASE", "PASS_GATE34", "PASS_GATE_34"}),
    "GATE-0V": GATE0V_ALLOGENEIC_CLINICAL_DECISIONS | GATE0V_AUTOLOGOUS_CLINICAL_DECISIONS,
    "GATE-5": frozenset({"PASS_GATE5_OQ012_CLONOGENIC_ERADICATION", "PASS_GATE5_OQ012"}),
}
ALLOWED_UPSTREAM_SYNTHETIC_DECISIONS: Dict[str, FrozenSet[str]] = {
    k: frozenset(set(v) | {"SYNTHETIC_SELF_TEST_PASS"}) for k, v in ALLOWED_UPSTREAM_WETLAB_DECISIONS.items()
}
ALLOWED_CURRENT_ASSAY_CLINICAL_DECISIONS: FrozenSet[str] = frozenset({
    "PASS",
    "PASS_GATE35",
    "PASS_GATE_35",
    "PASS_GATE35_CURRENT_ASSAY_VERIFIED",
    "PASS_GATE35_CLINICAL_PROMOTION_AUTHORIZED",
    "PASS_GATE35_CLINICAL_LOT_RELEASE",
})
ALLOWED_CURRENT_ASSAY_NONPROMO_DECISIONS: FrozenSet[str] = (
    ALLOWED_CURRENT_ASSAY_CLINICAL_DECISIONS
    | frozenset({"PASS_STAGE0_CANDIDATE_EXPERIMENT_BOOKING_ONLY", "STAGE_LIMITED_PRECLINICAL_ONLY"})
)
ALLOWED_CURRENT_ASSAY_SYNTHETIC_DECISIONS: FrozenSet[str] = (
    ALLOWED_CURRENT_ASSAY_NONPROMO_DECISIONS
    | frozenset({"SYNTHETIC_SELF_TEST_PASS", "SYNTHETIC_SELF_TEST_BOOKING_PASS"})
)
# Complete governed current-assay measurement fields bound inside current_assay_evidence_record (Review #4)
CURRENT_ASSAY_ALWAYS_BOUND_FIELDS: Tuple[str, ...] = (
    "deployment_site",
    "clinical_matrix_id",
    "needle_microtracks_used",
    "coformulated_immune_cuff_agents",
    "polyglactin_sutures_used",
    "ductal_cytokeratin_impurity_pct",
    "endotoxin_eu_per_ml",
    "sterility_pass",
    "mycoplasma_negative",
    "analytical_fasl_ug",
    "hepatocyte_72h_caspase37_u95_fold",
    "hepatocyte_72h_alt_ldh_u95_fold",
    "cuff_leachate_assay_passed",
    "construct_layout",
    "construct_thickness_um",
    "cluster_min_diam_um",
    "cluster_d_rms3_um",
    "cluster_d_p95_um",
    "cluster_max_diam_um",
    "staggered_bilayer_plane_offset_um",
    "bilateral_vascular_perfusion_verified",
    "back_to_back_unperfused_stacking",
    "scale_mode",
    "total_implanted_ieq",
    "total_loaded_area_cm2",
    "per_leaf_records",
    "bed_face_bot_po2_mmhg",
    "bed_face_top_po2_mmhg",
    "measured_fibrin_capsule_um",
    "measured_worst_face_o2_mmhg",
    "measured_worst_core_o2_mmhg",
    "measured_lot_ocr_mult",
    "route_specific_clean_t50_min",
    "route_specific_fibrin_t50_min",
    "route_specific_gsis_si",
    "invivo_diazoxide_depot_or_credit_claimed",
    "r3p06_5day_glycemic_clamp_enabled",
    "exvivo_rest_applied",
    "exvivo_preconditioning_agents",
)
CURRENT_ASSAY_STAGE1_OMENTUM_BOUND_FIELDS: Tuple[str, ...] = (
    "porcine_r4o04_zero_bowel_obstruction_torsion_grade3_adhesions",
    "porcine_subjects",
    "porcine_portal_peripheral_insulin_gradient",
    "nhp_r4o05_portal_peripheral_insulin_gradient",
    "nhp_r4o05_post_omentectomy_cpeptide_extinction",
)
CURRENT_ASSAY_STAGE1_COMMON_BOUND_FIELDS: Tuple[str, ...] = (
    "dec009_primate_free_pathway",
    "dec009_fda_cber_nhp_exception_authorized",
    "dec009_pillar1_humanized_mouse_efficacy_pass",
    "dec009_pillar2_chandler_loop_50donor_pass",
    "dec009_pillar1_glp_biodistribution_erasure_pass",
    "dec009_post_explant_cpeptide_extinction_verified",
    "nhp_subjects",
)
CURRENT_ASSAY_EXVIVO_REST_STAGE0_BOUND_FIELDS: Tuple[str, ...] = (
    "exvivo_diazoxide_uM",
    "exvivo_tudca_uM",
    "exvivo_preconditioning_hours",
    "h46e01_fccp_max_reserve_pct_ctrl",
    "washout_cycles_n",
    "lcms_supernatant_diazoxide_uM",
    "lcms_pellet_diazoxide_uM",
    "rest_assay_lot_id",
    "rest_challenge_o2_pct",
    "rest_two_pulse_gsis_verified",
    "rest_pulse1_si_rested",
    "rest_pulse1_si_control",
    "rest_pulse2_si_rested",
    "rest_pulse2_si_control",
    "oq018_post_washout_t50_min",
    "oq018_post_washout_t50_fold_ctrl",
    "oq018_post_washout_gsis_si",
    "oq018_post_washout_first_phase_auc_pct_ctrl",
    "oq018_post_washout_first_phase_auc_l95_pct_ctrl",
    "oq018_post_washout_glucagon_pct_ctrl",
    "h46e03_paired_hypoxic_necrosis_reduction_pct",
)
CURRENT_ASSAY_EXVIVO_REST_STAGE1_BOUND_FIELDS: Tuple[str, ...] = (
    "rest_endpoint_type",
    "rest_collection_day",
    "rest_endpoint_rested_value",
    "rest_endpoint_control_value",
    "h46e04_day14_cpeptide_or_mass_fold_ctrl",
    "h46e04_zero_secretory_delay_verified",
)

_CACHED_CANONICAL_MANIFEST: Optional[Dict[str, Any]] = None


def _get_verified_canonical_manifest(arm_manifest: Optional[Dict[str, Any]] = None) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
    """Return authenticated canonical manifest; REJECT any mutated caller-supplied manifest dict."""
    global _CACHED_CANONICAL_MANIFEST
    if arm_manifest is not None:
        if not isinstance(arm_manifest, dict):
            return None, "MUTATED_OR_UNVERIFIED_CALLER_ARM_MANIFEST_REJECTED"
        try:
            caller_sha = _canonical_json_sha256(arm_manifest)
        except (TypeError, ValueError, OverflowError, DecimalException):
            return None, "MUTATED_OR_UNVERIFIED_CALLER_ARM_MANIFEST_REJECTED"
        if caller_sha != EXPECTED_CANONICAL_MANIFEST_CANONICAL_JSON_SHA256:
            return None, "MUTATED_OR_UNVERIFIED_CALLER_ARM_MANIFEST_REJECTED"
        return arm_manifest, None
    if _CACHED_CANONICAL_MANIFEST is None:
        loaded = load_and_verify_canonical_contracts()
        _CACHED_CANONICAL_MANIFEST = loaded["manifest"]
    return _CACHED_CANONICAL_MANIFEST, None


def _is_fasl_or_cd95_token(token: str) -> bool:
    low = token.lower()
    return ("fasl" in low) or ("cd95" in low) or ("apo010" in low) or ("fas_l" in low) or ("fas-l" in low)


def _fixture_construct_manifest_sha256(arm_key: str, product_id: str) -> str:
    """Deterministic non-zero 64-hex lot construct FASTA digest, strictly distinct from arm manifest digest."""
    return sha256_bytes(f"OPENISLET_WAVE6_R5_FIXTURE_CONSTRUCT_FASTA:{arm_key}:{product_id}".encode("utf-8"))


def seal_upstream_evidence_record(record_body: Dict[str, Any]) -> Dict[str, Any]:
    """Compute canonical archive_sha256 over all fields except archive_sha256 (for trusted store fixtures)."""
    body_no_sha = {k: v for k, v in record_body.items() if k != "archive_sha256"}
    return {**body_no_sha, "archive_sha256": _canonical_json_sha256(body_no_sha)}


def _check_no_contradictory_authority_flags(
    rec: Mapping[str, Any],
    prefix: str,
    fail_reasons: List[str],
) -> None:
    """Reject contradictory physical/release/modeled authority flags on any upstream or current record (Audit R4-01)."""
    if "physical_qualification_complete" in rec:
        pqc = rec["physical_qualification_complete"]
        if not _is_strict_bool(pqc) or pqc is False:
            fail_reasons.append(f"{prefix}_PHYSICAL_QUALIFICATION_INCOMPLETE_REJECTED")
    if "release_authorizing" in rec:
        ra = rec["release_authorizing"]
        if not _is_strict_bool(ra) or ra is False:
            fail_reasons.append(f"{prefix}_RELEASE_AUTHORIZING_FALSE_REJECTED")
    if "modeled_qualification_only" in rec:
        mqo = rec["modeled_qualification_only"]
        if not _is_strict_bool(mqo) or mqo is True:
            fail_reasons.append(f"{prefix}_MODELED_QUALIFICATION_ONLY_REJECTED")
    if "qualification_scope" in rec:
        qs = rec["qualification_scope"]
        if not _is_literal_nonempty_str(qs):
            fail_reasons.append(f"{prefix}_MODELED_OR_PENDING_QUALIFICATION_SCOPE_REJECTED")
        else:
            qlow = qs.lower()
            if any(tok in qlow for tok in ("modeled", "pending", "bank_only", "synthetic")):
                fail_reasons.append(f"{prefix}_MODELED_OR_PENDING_QUALIFICATION_SCOPE_REJECTED")


def _resolve_store_entry_with_alias_consistency(
    *,
    rec: Mapping[str, Any],
    record_id: str,
    rec_archive_sha: str,
    prefix: str,
    trusted_evidence_store: Mapping[str, Mapping[str, Any]],
    fail_reasons: List[str],
) -> Optional[Dict[str, Any]]:
    """Resolve record from trusted_evidence_store enforcing alias consistency (Review #5) & full-body SHA-256."""
    has_id = isinstance(record_id, str) and record_id in trusted_evidence_store
    has_sha = isinstance(rec_archive_sha, str) and rec_archive_sha in trusted_evidence_store
    if not has_id and not has_sha:
        fail_reasons.append(f"{prefix}_RECORD_NOT_FOUND_IN_TRUSTED_STORE")
        return None

    stored_by_id = trusted_evidence_store[record_id] if has_id else None
    stored_by_sha = trusted_evidence_store[rec_archive_sha] if has_sha else None

    if has_id and has_sha:
        if not isinstance(stored_by_id, Mapping) or not isinstance(stored_by_sha, Mapping):
            fail_reasons.append(f"{prefix}_CONFLICTING_STORE_INDEX_ALIASES")
            return None
        try:
            canon_by_id = canonical_json_dumps(dict(stored_by_id))
            canon_by_sha = canonical_json_dumps(dict(stored_by_sha))
        except (TypeError, ValueError, OverflowError, DecimalException):
            fail_reasons.append(f"{prefix}_CONFLICTING_STORE_INDEX_ALIASES")
            return None
        if canon_by_id != canon_by_sha:
            fail_reasons.append(f"{prefix}_CONFLICTING_STORE_INDEX_ALIASES")
            return None

    stored = stored_by_id if has_id else stored_by_sha
    if not isinstance(stored, Mapping):
        fail_reasons.append(f"{prefix}_TRUSTED_STORE_ENTRY_MALFORMED")
        return None

    stored_dict = dict(stored)
    stored_sha = stored_dict.get("archive_sha256")
    if not _is_non_all_zero_sha256_hex(stored_sha) or stored_sha != rec_archive_sha:
        fail_reasons.append(f"{prefix}_TRUSTED_ARCHIVE_DIGEST_MISMATCH")
        return stored_dict

    try:
        recomputed_stored_sha = _canonical_json_sha256({k: v for k, v in stored_dict.items() if k != "archive_sha256"})
    except (TypeError, ValueError, OverflowError, DecimalException):
        fail_reasons.append(f"{prefix}_TRUSTED_STORE_UNSERIALIZABLE")
        return stored_dict
    if recomputed_stored_sha != stored_sha:
        fail_reasons.append(f"{prefix}_TRUSTED_ARCHIVE_BODY_TAMPERED")
        return stored_dict

    try:
        recomputed_rec_sha = _canonical_json_sha256({k: v for k, v in rec.items() if k != "archive_sha256"})
        stored_canon = canonical_json_dumps(stored_dict)
        rec_canon = canonical_json_dumps(dict(rec))
    except (TypeError, ValueError, OverflowError, DecimalException):
        fail_reasons.append(f"{prefix}_SUBMITTED_BODY_UNSERIALIZABLE")
        return stored_dict

    if recomputed_rec_sha != rec_archive_sha:
        fail_reasons.append(f"{prefix}_SUBMITTED_BODY_DIGEST_MISMATCH")
    if stored_canon != rec_canon:
        fail_reasons.append(f"{prefix}_TRUSTED_STORE_FULL_BODY_MISMATCH")

    return stored_dict


def _check_retrieval_residual_reconciliation(
    *,
    prefix: str,
    retrieval_mass_pct: Any,
    total_implanted_cells: Any,
    residual_viable_cells_measured: Any,
    residual_sampling_fraction: Any,
    require_ge_99p9: bool,
    fail_reasons: List[str],
) -> bool:
    """Validate retrieval mass %, residual viable cells, >=1% sampling denominator & reconciliation in exact Decimal (Audit F5 / R4-04 / R12-04)."""
    ok = True
    any_missing = False
    r_pct_d: Optional[Decimal] = None
    n_imp_d: Optional[Decimal] = None
    n_res_d: Optional[Decimal] = None
    f_samp_d: Optional[Decimal] = None

    if retrieval_mass_pct is None:
        any_missing = True
    elif not _is_finite_number(retrieval_mass_pct):
        fail_reasons.append(f"INVALID_{prefix}_RETRIEVAL_MASS_PCT")
        ok = False
    else:
        r_pct_d = _to_exact_decimal(retrieval_mass_pct)
        if r_pct_d < ZERO_DEC or r_pct_d > Decimal("100"):
            fail_reasons.append(f"INVALID_{prefix}_RETRIEVAL_MASS_PCT")
            ok = False
        elif require_ge_99p9 and r_pct_d < Decimal("99.9"):
            fail_reasons.append(f"{prefix}_ENBLOC_MASS_RETRIEVAL_LT_99P9PCT_FAIL")
            ok = False

    if total_implanted_cells is None:
        any_missing = True
    elif not _is_finite_number(total_implanted_cells):
        fail_reasons.append(f"INVALID_{prefix}_TOTAL_IMPLANTED_CELLS")
        ok = False
    else:
        n_imp_d = _to_exact_decimal(total_implanted_cells)
        if n_imp_d <= ZERO_DEC or n_imp_d > Decimal("1e12"):
            fail_reasons.append(f"INVALID_{prefix}_TOTAL_IMPLANTED_CELLS")
            ok = False

    if residual_viable_cells_measured is None:
        any_missing = True
    elif not _is_finite_number(residual_viable_cells_measured):
        fail_reasons.append(f"INVALID_{prefix}_RESIDUAL_VIABLE_CELLS_MEASURED")
        ok = False
    else:
        n_res_d = _to_exact_decimal(residual_viable_cells_measured)
        if n_res_d < ZERO_DEC or n_res_d > Decimal("1e12"):
            fail_reasons.append(f"INVALID_{prefix}_RESIDUAL_VIABLE_CELLS_MEASURED")
            ok = False

    if residual_sampling_fraction is None:
        any_missing = True
    elif not _is_finite_number(residual_sampling_fraction):
        fail_reasons.append(f"INVALID_{prefix}_RESIDUAL_SAMPLING_FRACTION_OUT_OF_0P01_TO_1P0")
        ok = False
    else:
        f_samp_d = _to_exact_decimal(residual_sampling_fraction)
        if f_samp_d < MIN_RESIDUAL_SAMPLING_FRACTION_DEC or f_samp_d > ONE_DEC:
            fail_reasons.append(f"INVALID_{prefix}_RESIDUAL_SAMPLING_FRACTION_OUT_OF_0P01_TO_1P0")
            ok = False

    if not ok or any_missing or r_pct_d is None or n_imp_d is None or n_res_d is None or f_samp_d is None:
        return False

    if n_res_d > n_imp_d:
        fail_reasons.append(f"{prefix}_RESIDUAL_CELLS_EXCEED_IMPLANTED_CELLS_FAIL")
        ok = False

    if r_pct_d >= Decimal("99.999999999999"):
        cap_100_d = max(Decimal("1e5"), _dec_mul(Decimal("0.0005"), n_imp_d))
        if n_res_d > cap_100_d or _ratio_gt_dec(n_res_d, f_samp_d, cap_100_d):
            fail_reasons.append(f"{prefix}_RETRIEVAL_100PCT_CONTRADICTS_RESIDUAL_VIABLE_CELLS_FAIL")
            ok = False

    rem_frac_d = max(_dec_mul(_dec_sub(Decimal("100"), r_pct_d), Decimal("0.01")), Decimal("0.001"))
    max_allowed_extrap_d = _dec_add(_dec_mul(_dec_mul(n_imp_d, rem_frac_d), Decimal("2")), Decimal("1e5"))
    if _ratio_gt_dec(n_res_d, f_samp_d, max_allowed_extrap_d):
        fail_reasons.append(f"{prefix}_RETRIEVAL_VS_RESIDUAL_CELL_DENOMINATOR_INCONSISTENT_FAIL")
        ok = False

    return ok


def _check_subject_typed_complications_and_aliases(
    s: Mapping[str, Any],
    *,
    gate_tag: str,
    species_tag: str,
    fail_reasons: List[str],
    hold_reasons: List[str],
) -> Tuple[bool, bool]:
    """Validate typed monitored complication fields and defensive complication aliases on a subject row (Audit R5-04).

    Returns (complications_resolved, has_adverse_or_invalid_complication).
    """
    resolved = True
    has_adverse = False

    for fkey, inv_code, fail_code in (
        ("bowel_obstruction_event", f"INVALID_{species_tag}_BOWEL_OBSTRUCTION_EVENT_BOOL", f"{gate_tag}_{species_tag}_BOWEL_OBSTRUCTION_EVENT_FAIL"),
        ("omental_torsion_event", f"INVALID_{species_tag}_OMENTAL_TORSION_EVENT_BOOL", f"{gate_tag}_{species_tag}_OMENTAL_TORSION_EVENT_FAIL"),
        ("grade3_adhesion_event", f"INVALID_{species_tag}_GRADE3_ADHESION_EVENT_BOOL", f"{gate_tag}_{species_tag}_GRADE3_ADHESION_EVENT_FAIL"),
    ):
        val = s.get(fkey)
        if val is None:
            hold_reasons.append(f"MISSING_{species_tag}_SUBJECT_FIELD:{fkey}")
            resolved = False
        elif not _is_strict_bool(val):
            fail_reasons.append(inv_code)
            has_adverse = True
        elif val is True:
            fail_reasons.append(fail_code)
            has_adverse = True

    mc = s.get("monitored_complications")
    if mc is None:
        hold_reasons.append(f"MISSING_{species_tag}_SUBJECT_FIELD:monitored_complications")
        resolved = False
    elif not isinstance(mc, list) or not all(_is_literal_nonempty_str(x) for x in mc):
        fail_reasons.append(f"INVALID_{species_tag}_MONITORED_COMPLICATIONS_LIST")
        has_adverse = True
    elif len(mc) > 0:
        fail_reasons.append(f"{gate_tag}_{species_tag}_MONITORED_COMPLICATIONS_NONEMPTY_FAIL")
        has_adverse = True

    for akey in SUBJECT_COMPLICATION_BOOL_ALIAS_KEYS:
        if akey in s and s[akey] is not None:
            aval = s[akey]
            if not _is_strict_bool(aval):
                fail_reasons.append(f"INVALID_{species_tag}_COMPLICATION_ALIAS_BOOL:{akey}")
                has_adverse = True
            elif aval is True:
                fail_reasons.append(f"{gate_tag}_{species_tag}_COMPLICATION_ALIAS_TRUE_FAIL:{akey}")
                has_adverse = True

    for akey in SUBJECT_COMPLICATION_LIST_ALIAS_KEYS:
        if akey in s and s[akey] is not None:
            aval = s[akey]
            if isinstance(aval, list):
                if len(aval) > 0:
                    fail_reasons.append(f"{gate_tag}_{species_tag}_COMPLICATION_ALIAS_LIST_NONEMPTY_FAIL:{akey}")
                    has_adverse = True
            else:
                fail_reasons.append(f"INVALID_OR_ADVERSE_{species_tag}_COMPLICATION_ALIAS:{akey}")
                has_adverse = True

    # Round-8 Audit R7-08: Detect pairwise disagreement within any complication bool/list alias group
    for grp in SUBJECT_COMPLICATION_BOOL_ALIAS_GROUPS:
        grp_bools = [s[k] for k in grp if k in s and s[k] is not None and _is_strict_bool(s[k])]
        if len(set(grp_bools)) > 1:
            fail_reasons.append(f"{species_tag}_CONFLICTING_COMPLICATION_ALIAS_GROUP")
            has_adverse = True

    comp_list_vals: List[Tuple[str, ...]] = []
    for k in ("monitored_complications",) + SUBJECT_COMPLICATION_LIST_ALIAS_KEYS:
        if k in s and isinstance(s[k], list) and all(_is_literal_nonempty_str(x) for x in s[k]):
            comp_list_vals.append(tuple(s[k]))
    if len(set(comp_list_vals)) > 1:
        fail_reasons.append(f"{species_tag}_CONFLICTING_COMPLICATION_ALIAS_GROUP")
        has_adverse = True

    return resolved, has_adverse


def _check_subject_date_aliases(
    s: Mapping[str, Any],
    *,
    gate_tag: str,
    species_tag: str,
    min_days: Decimal,
    min_days_tag: str,
    followup_val: Optional[Decimal],
    capsule_day_val: Optional[Decimal],
    retrieval_day_val: Optional[Decimal],
    omentectomy_day_val: Optional[Decimal],
    cpep_day_val: Optional[Decimal],
    portal_day_val: Optional[Decimal],
    fail_reasons: List[str],
) -> bool:
    """Defensively validate optional subject date alias keys using exact decimal.Decimal arithmetic
    (ZERO ungoverned tolerance) against minimum follow-up, canonical dates, intra-group alias
    consistency (even when canonical key is absent), NHP omentectomy/extinction/portal chronology,
    and strict exact [0, 14] day post-omentectomy assessment window (Audit R5-04 / R6-05 / R7-08 / R7-13 / R8-05).
    """
    adverse = False

    def _check_group(
        keys: Tuple[str, ...],
        endpoint_tag: str,
        canonical_val: Optional[Decimal],
        check_le_followup: bool,
    ) -> List[Tuple[str, Decimal]]:
        nonlocal adverse
        parsed_vals: List[Tuple[str, Decimal]] = []
        for akey in keys:
            if akey in s and s[akey] is not None:
                aval = s[akey]
                if not _is_finite_number(aval) or _to_exact_decimal(aval) <= Decimal("0"):
                    fail_reasons.append(f"INVALID_{species_tag}_DATE_ALIAS:{akey}")
                    adverse = True
                else:
                    av = _to_exact_decimal(aval)
                    parsed_vals.append((akey, av))
                    if av < min_days:
                        fail_reasons.append(f"{gate_tag}_{species_tag}_{endpoint_tag}_DATE_ALIAS_LT_{min_days_tag}_FAIL:{akey}")
                        adverse = True
                    if canonical_val is not None and av != canonical_val:
                        fail_reasons.append(f"{gate_tag}_{species_tag}_{endpoint_tag}_DATE_ALIAS_CONTRADICTION:{akey}")
                        adverse = True
                    if check_le_followup and followup_val is not None and av > followup_val:
                        fail_reasons.append(f"{gate_tag}_{species_tag}_{endpoint_tag}_DATE_ALIAS_EXCEEDS_FOLLOWUP:{akey}")
                        adverse = True
        all_group_vals: List[Decimal] = []
        if canonical_val is not None:
            all_group_vals.append(canonical_val)
        all_group_vals.extend(av for _, av in parsed_vals)
        if len(all_group_vals) >= 2:
            ref_v = all_group_vals[0]
            if any(v != ref_v for v in all_group_vals[1:]):
                fail_reasons.append(f"{species_tag}_CONFLICTING_DATE_ALIAS_GROUP")
                fail_reasons.append(f"{gate_tag}_{species_tag}_{endpoint_tag}_CONFLICTING_DATE_ALIAS_GROUP")
                adverse = True
        return parsed_vals

    _check_group(SUBJECT_FOLLOWUP_DATE_ALIAS_KEYS, "FOLLOWUP", followup_val, check_le_followup=False)
    _check_group(SUBJECT_CAPSULE_DATE_ALIAS_KEYS, "CAPSULE", capsule_day_val, check_le_followup=True)
    if species_tag == "PORCINE":
        _check_group(SUBJECT_RETRIEVAL_DATE_ALIAS_KEYS, "RETRIEVAL", retrieval_day_val, check_le_followup=True)
    elif species_tag == "NHP":
        _check_group(NHP_TERMINAL_DATE_ALIAS_KEYS, "RETRIEVAL", None, check_le_followup=True)
        proc_alias_vals = _check_group(
            NHP_OMENTECTOMY_PROCEDURE_DATE_ALIAS_KEYS, "OMENTECTOMY", omentectomy_day_val, check_le_followup=True,
        )
        cpep_alias_vals = _check_group(
            NHP_CPEP_EXTINCTION_DATE_ALIAS_KEYS, "C_PEPTIDE_EXTINCTION", cpep_day_val, check_le_followup=True,
        )
        port_alias_vals = _check_group(
            NHP_PORTAL_GRADIENT_DATE_ALIAS_KEYS, "PORTAL_GRADIENT", portal_day_val, check_le_followup=True,
        )
        for akey, av in proc_alias_vals:
            if cpep_day_val is not None:
                if cpep_day_val < av:
                    fail_reasons.append("NHP_CPEP_EXTINCTION_PRECEDES_OMENTECTOMY_PROCEDURE")
                    fail_reasons.append(f"R4O_05_NHP_CPEP_EXTINCTION_PRECEDES_PROCEDURE_ALIAS_FAIL:{akey}")
                    adverse = True
                elif _dec_diff_exceeds(cpep_day_val, av, MAX_POST_OMENTECTOMY_CPEP_EXTINCTION_WINDOW_DAYS_DEC):
                    fail_reasons.append("NHP_CPEP_EXTINCTION_EXCEEDS_14D_PROMPT_WINDOW")
                    fail_reasons.append(f"R4O_05_NHP_CPEP_EXTINCTION_EXCEEDS_14D_WINDOW_VS_PROCEDURE_ALIAS_FAIL:{akey}")
                    adverse = True
            if portal_day_val is not None and portal_day_val > av:
                fail_reasons.append("NHP_PORTAL_GRADIENT_POST_OMENTECTOMY_INVALID")
                fail_reasons.append(f"R4O_05_NHP_PORTAL_GRADIENT_POST_PROCEDURE_ALIAS_FAIL:{akey}")
                adverse = True
        for akey, av in cpep_alias_vals:
            if omentectomy_day_val is not None:
                if av < omentectomy_day_val:
                    fail_reasons.append("NHP_CPEP_EXTINCTION_PRECEDES_OMENTECTOMY_PROCEDURE")
                    fail_reasons.append(f"R4O_05_NHP_CPEP_EXTINCTION_ALIAS_PRECEDES_OMENTECTOMY_FAIL:{akey}")
                    adverse = True
                elif _dec_diff_exceeds(av, omentectomy_day_val, MAX_POST_OMENTECTOMY_CPEP_EXTINCTION_WINDOW_DAYS_DEC):
                    fail_reasons.append("NHP_CPEP_EXTINCTION_EXCEEDS_14D_PROMPT_WINDOW")
                    fail_reasons.append(f"R4O_05_NHP_CPEP_EXTINCTION_ALIAS_EXCEEDS_14D_WINDOW_FAIL:{akey}")
                    adverse = True
            for pakey, pav in proc_alias_vals:
                if av < pav:
                    fail_reasons.append("NHP_CPEP_EXTINCTION_PRECEDES_OMENTECTOMY_PROCEDURE")
                    fail_reasons.append(f"R4O_05_NHP_CPEP_EXTINCTION_ALIAS_PRECEDES_PROCEDURE_ALIAS_FAIL:{akey}:{pakey}")
                    adverse = True
                elif _dec_diff_exceeds(av, pav, MAX_POST_OMENTECTOMY_CPEP_EXTINCTION_WINDOW_DAYS_DEC):
                    fail_reasons.append("NHP_CPEP_EXTINCTION_EXCEEDS_14D_PROMPT_WINDOW")
                    fail_reasons.append(f"R4O_05_NHP_CPEP_EXTINCTION_ALIAS_EXCEEDS_14D_WINDOW_VS_PROCEDURE_ALIAS_FAIL:{akey}:{pakey}")
                    adverse = True
        for akey, av in port_alias_vals:
            if omentectomy_day_val is not None and av > omentectomy_day_val:
                fail_reasons.append("NHP_PORTAL_GRADIENT_POST_OMENTECTOMY_INVALID")
                fail_reasons.append(f"R4O_05_NHP_PORTAL_GRADIENT_ALIAS_POST_OMENTECTOMY_FAIL:{akey}")
                adverse = True
            for pakey, pav in proc_alias_vals:
                if av > pav:
                    fail_reasons.append("NHP_PORTAL_GRADIENT_POST_OMENTECTOMY_INVALID")
                    fail_reasons.append(f"R4O_05_NHP_PORTAL_GRADIENT_ALIAS_POST_PROCEDURE_ALIAS_FAIL:{akey}:{pakey}")
                    adverse = True
    return adverse


def _validate_gate5_counts_and_u95(
    src: Mapping[str, Any],
    *,
    fail_reasons: List[str],
    hold_reasons: List[str],
) -> Optional[float]:
    """Validate live Blueprint Section 7 Gate 5 OQ-012 (k==0, n, f, eta>=0.30, n_eff>=299,573,228, U95<=1e-8)
    via exact context-independent 75-digit Decimal Clopper-Pearson arithmetic (ZERO float() before policy decision).
    """
    oq012_ok = src.get("oq012_clonogenic_regrowth_pass")
    if oq012_ok is None:
        hold_reasons.append("MISSING_UPSTREAM_GATE5_OQ012_CLONOGENIC_PASS")
    elif not _is_strict_bool(oq012_ok) or not oq012_ok:
        fail_reasons.append("GATE5_OQ012_CLONOGENIC_REGROWTH_FAILED")

    k_surv = src.get("survivor_count_k")
    n_test = src.get("tested_cells_n")
    f_val = src.get("clonogenic_fraction_f")
    eta_val = src.get("spike_in_detection_efficiency_eta")
    n_eff = src.get("effective_clonogenic_trials_n_eff")
    u95_v = src.get("u95_exact")

    k_ok = False
    n_ok = False
    n_eff_ok = False
    f_dec: Optional[Decimal] = None
    eta_dec: Optional[Decimal] = None
    u95_dec: Optional[Decimal] = None

    if k_surv is None:
        hold_reasons.append("MISSING_UPSTREAM_GATE5_FIELD:survivor_count_k")
    elif not _is_strict_int(k_surv) or k_surv < 0:
        fail_reasons.append("INVALID_UPSTREAM_GATE5_SURVIVOR_COUNT_K")
    else:
        k_ok = True
        if k_surv > 0:
            fail_reasons.append("FAIL_GATE5_OQ012_NONZERO_SURVIVOR_OR_U95_GT_1E8")

    if n_test is None:
        hold_reasons.append("MISSING_UPSTREAM_GATE5_FIELD:tested_cells_n")
    elif not _is_strict_int(n_test) or n_test < MIN_GATE5_TESTED_CELLS or n_test > MAX_CLONOGENIC_CELLS:
        fail_reasons.append("INVALID_UPSTREAM_GATE5_TESTED_CELLS_N")
    else:
        n_ok = True

    if k_ok and n_ok and k_surv > n_test:
        fail_reasons.append("INVALID_UPSTREAM_GATE5_SURVIVORS_EXCEED_TESTED_CELLS")
        k_ok = False

    if f_val is None:
        hold_reasons.append("HOLD_GATE5_OQ012_INCOMPLETE_RECOVERY_DENOMINATOR")
        hold_reasons.append("MISSING_UPSTREAM_GATE5_FIELD:clonogenic_fraction_f")
    elif not _is_finite_number(f_val):
        fail_reasons.append("INVALID_UPSTREAM_GATE5_CLONOGENIC_FRACTION_F")
    else:
        cand_f = _to_exact_decimal(f_val)
        if cand_f <= ZERO_DEC or cand_f > ONE_DEC:
            fail_reasons.append("INVALID_UPSTREAM_GATE5_CLONOGENIC_FRACTION_F")
        else:
            f_dec = cand_f

    if eta_val is None:
        hold_reasons.append("HOLD_GATE5_OQ012_INCOMPLETE_RECOVERY_DENOMINATOR")
        hold_reasons.append("MISSING_UPSTREAM_GATE5_FIELD:spike_in_detection_efficiency_eta")
    elif not _is_finite_number(eta_val):
        fail_reasons.append("INVALID_UPSTREAM_GATE5_SPIKE_IN_DETECTION_EFFICIENCY_ETA")
    else:
        cand_eta = _to_exact_decimal(eta_val)
        if cand_eta <= ZERO_DEC or cand_eta > ONE_DEC:
            fail_reasons.append("INVALID_UPSTREAM_GATE5_SPIKE_IN_DETECTION_EFFICIENCY_ETA")
        else:
            eta_dec = cand_eta
            if eta_dec < MIN_GATE5_DETECTION_EFFICIENCY_ETA_DEC:
                fail_reasons.append("FAIL_GATE5_OQ012_DETECTION_EFFICIENCY_ETA_LT_0P30")

    if n_eff is None:
        hold_reasons.append("HOLD_GATE5_OQ012_INCOMPLETE_RECOVERY_DENOMINATOR")
        hold_reasons.append("MISSING_UPSTREAM_GATE5_FIELD:effective_clonogenic_trials_n_eff")
    elif not _is_strict_int(n_eff) or n_eff < 1 or n_eff > MAX_CLONOGENIC_CELLS:
        fail_reasons.append("INVALID_UPSTREAM_GATE5_EFFECTIVE_CLONOGENIC_TRIALS_N_EFF")
    else:
        n_eff_ok = True
        if k_ok and k_surv > n_eff:
            fail_reasons.append("INVALID_UPSTREAM_GATE5_SURVIVORS_EXCEED_EFFECTIVE_TRIALS")
            k_ok = False
        if n_ok and f_dec is not None and eta_dec is not None:
            # For integer n_eff, n_eff <= floor(n_test * f * eta) iff Decimal(n_eff) <= exact n_test * f * eta
            max_n_eff_dec = _dec_mul(_dec_mul(Decimal(n_test), f_dec), eta_dec)
            if Decimal(n_eff) > max_n_eff_dec:
                fail_reasons.append("FAIL_GATE5_OQ012_EFFECTIVE_TRIALS_EXCEEDS_FLOOR_N_F_ETA")

    if u95_v is None:
        hold_reasons.append("MISSING_UPSTREAM_GATE5_FIELD:u95_exact")
    elif not _is_finite_number(u95_v):
        fail_reasons.append("GATE5_U95_EXACT_EXCEEDS_LIMIT_OR_INVALID")
    else:
        cand_u95 = _to_exact_decimal(u95_v)
        if cand_u95 <= ZERO_DEC or cand_u95 > ONE_DEC:
            fail_reasons.append("GATE5_U95_EXACT_EXCEEDS_LIMIT_OR_INVALID")
        else:
            u95_dec = cand_u95

    u95_recomputed: Optional[float] = None
    if k_ok and n_eff_ok:
        u95_recomp_dec = clopper_pearson_u95_decimal(k_surv, n_eff, alpha=Decimal("0.05"))
        if k_surv == 0:
            if n_eff < MIN_GATE5_EFFECTIVE_TRIALS:
                hold_reasons.append("HOLD_GATE5_OQ012_UNDERPOWERED_BELOW_299573228_EFFECTIVE_TRIALS")
            else:
                if u95_recomp_dec > MAX_GATE5_OQ012_U95_DEC:
                    fail_reasons.append("FAIL_GATE5_OQ012_NONZERO_SURVIVOR_OR_U95_GT_1E8")
                if u95_dec is not None and u95_dec > MAX_GATE5_OQ012_U95_DEC:
                    fail_reasons.append("GATE5_U95_EXACT_EXCEEDS_LIMIT_OR_INVALID")
        else:
            if u95_recomp_dec > MAX_GATE5_OQ012_U95_DEC and "FAIL_GATE5_OQ012_NONZERO_SURVIVOR_OR_U95_GT_1E8" not in fail_reasons:
                fail_reasons.append("FAIL_GATE5_OQ012_NONZERO_SURVIVOR_OR_U95_GT_1E8")
        if u95_dec is not None:
            tol_dec = min(Decimal("1e-12"), _dec_mul(Decimal("1e-4"), u95_recomp_dec))
            if _dec_diff_exceeds(u95_recomp_dec, u95_dec, tol_dec):
                fail_reasons.append("GATE5_UNDERSTATED_OR_FORGED_U95_EXACT")
        # Convert to display float ONLY after exact Decimal policy decisions complete
        if u95_recomp_dec >= ONE_DEC:
            u95_recomputed = 1.0
        else:
            u95_f_disp = _dec_to_display_float(u95_recomp_dec)
            if u95_f_disp is not None:
                if Decimal.from_float(u95_f_disp) < u95_recomp_dec:
                    u95_f_disp = math.nextafter(u95_f_disp, math.inf)
                u95_recomputed = min(1.0, u95_f_disp)
    elif k_ok and n_ok and u95_dec is not None:
        # Even if n_eff is omitted (HOLD), check u95_dec is not forged strictly below the optimistic lower bound U95(k, n_test)
        u95_opt_dec = clopper_pearson_u95_decimal(k_surv, n_test, alpha=Decimal("0.05"))
        tol_opt = min(Decimal("1e-12"), _dec_mul(Decimal("1e-4"), u95_opt_dec))
        if u95_dec < u95_opt_dec and _dec_diff_exceeds(u95_opt_dec, u95_dec, tol_opt):
            fail_reasons.append("GATE5_UNDERSTATED_OR_FORGED_U95_EXACT")
    return u95_recomputed


def _validate_upstream_lot_record(
    rec: Any,
    *,
    tag: str,
    expected_gate_source: str,
    expected_product_id: Optional[str],
    expected_lot_id: Optional[str],
    expected_bank_id: Optional[str],
    expected_bank_origin: Optional[str],
    expected_evidence_tier: Optional[str],
    expected_dual_switch_required: Optional[bool],
    trusted_evidence_store: Optional[Mapping[str, Mapping[str, Any]]],
    fail_reasons: List[str],
    hold_reasons: List[str],
) -> Dict[str, Any]:
    """Validate one v2_round5_unified 14-field upstream record against manifest, bank, scope, flags & trusted store."""
    empty: Dict[str, Any] = {
        "construct_sha": None,
        "bank_id": None,
        "record_id": None,
        "archive_sha256": None,
        "prerequisite_archive_sha256s": None,
        "recomputed_gate5_u95": None,
        "stored": None,
    }
    if rec is None:
        hold_reasons.append(f"MISSING_UPSTREAM_{tag}_RECORD")
        return empty
    if not isinstance(rec, dict):
        fail_reasons.append(f"INVALID_UPSTREAM_{tag}_RECORD")
        return empty

    _check_no_contradictory_authority_flags(rec, f"UPSTREAM_{tag}", fail_reasons)

    missing_or_invalid = False
    for field in REQUIRED_UPSTREAM_SCHEMA_V2_STRING_FIELDS:
        val = rec.get(field)
        if val is None:
            hold_reasons.append(f"MISSING_UPSTREAM_{tag}_FIELD:{field}")
            missing_or_invalid = True
        elif not _is_literal_nonempty_str(val):
            fail_reasons.append(f"INVALID_UPSTREAM_{tag}_FIELD:{field}")
            missing_or_invalid = True

    for field in REQUIRED_UPSTREAM_SCHEMA_V2_BOOL_FIELDS:
        val = rec.get(field)
        if val is None:
            hold_reasons.append(f"MISSING_UPSTREAM_{tag}_FIELD:{field}")
            missing_or_invalid = True
        elif not _is_strict_bool(val):
            fail_reasons.append(f"INVALID_UPSTREAM_{tag}_FIELD:{field}")
            missing_or_invalid = True

    if missing_or_invalid:
        return empty

    record_id = rec["record_id"]
    gate_source = rec["gate_source"]
    rec_prod = rec["product_id"]
    rec_lot = rec["lot_id"]
    rec_bank_id = rec["bank_id"]
    rec_bank_origin = rec["bank_origin"]
    rec_arm_manifest_sha = rec["canonical_arm_manifest_sha256"]
    rec_construct_sha = rec["construct_manifest_sha256"]
    rec_tier = rec["evidence_tier"]
    rec_decision = rec["decision"]
    rec_authority_scope = rec["authority_scope"]
    rec_bank_qualified = rec["bank_qualified"]
    rec_promo_auth = rec["promotion_authorized"]
    rec_archive_sha = rec["archive_sha256"]

    if gate_source != expected_gate_source:
        if expected_gate_source == "GATE-34" and gate_source == "GATE-32":
            fail_reasons.append("UPSTREAM_GATE34_LIVE_GATE32_ROLE_COLLISION_REJECTED")
        fail_reasons.append(f"UPSTREAM_{tag}_GATE_SOURCE_MISMATCH")
    if expected_product_id is not None and rec_prod != expected_product_id:
        fail_reasons.append(f"UPSTREAM_{tag}_PRODUCT_ID_MISMATCH")
    if expected_lot_id is not None and rec_lot != expected_lot_id:
        fail_reasons.append(f"UPSTREAM_{tag}_LOT_ID_MISMATCH")
    if expected_bank_id is not None and rec_bank_id != expected_bank_id:
        fail_reasons.append(f"UPSTREAM_{tag}_BANK_ID_MISMATCH")
    if rec_bank_origin not in ALLOWED_BANK_ORIGINS:
        fail_reasons.append(f"UPSTREAM_{tag}_INVALID_BANK_ORIGIN")
    elif expected_bank_origin is not None and rec_bank_origin != expected_bank_origin:
        fail_reasons.append(f"UPSTREAM_{tag}_BANK_ORIGIN_MISMATCH")
    if rec_arm_manifest_sha != EXPECTED_CANONICAL_MANIFEST_SHA256:
        fail_reasons.append(f"UPSTREAM_{tag}_CANONICAL_ARM_MANIFEST_SHA256_MISMATCH")

    valid_construct_sha: Optional[str] = None
    if not _is_non_all_zero_sha256_hex(rec_construct_sha) or rec_construct_sha == EXPECTED_CANONICAL_MANIFEST_SHA256:
        fail_reasons.append(f"UPSTREAM_{tag}_CONSTRUCT_MANIFEST_SHA256_INVALID_OR_CONFLATED")
    else:
        valid_construct_sha = rec_construct_sha

    if not _is_non_all_zero_sha256_hex(rec_archive_sha):
        fail_reasons.append(f"UPSTREAM_{tag}_INVALID_OR_ZERO_ARCHIVE_SHA256")
    if rec_tier not in ALLOWED_EVIDENCE_TIERS:
        fail_reasons.append(f"UPSTREAM_{tag}_INVALID_EVIDENCE_TIER")
    elif expected_evidence_tier is not None and rec_tier != expected_evidence_tier:
        fail_reasons.append(f"UPSTREAM_{tag}_EVIDENCE_TIER_MISMATCH")

    if rec_authority_scope not in ALLOWED_AUTHORITY_SCOPES:
        fail_reasons.append(f"UPSTREAM_{tag}_INVALID_AUTHORITY_SCOPE")

    if rec_tier == "AUTHENTICATED_ARCHIVED_WETLAB":
        if rec_authority_scope != "CLINICAL_LOT_RELEASE":
            fail_reasons.append(f"UPSTREAM_{tag}_AUTHORITY_SCOPE_NOT_CLINICAL_LOT_RELEASE")
        if rec_promo_auth is not True:
            fail_reasons.append(f"UPSTREAM_{tag}_PROMOTION_AUTHORIZATION_WITHHELD")
        if rec_bank_qualified is not True:
            fail_reasons.append(f"UPSTREAM_{tag}_BANK_NOT_QUALIFIED")
    elif rec_tier == "SYNTHETIC_FIXTURE":
        if rec_authority_scope != "SYNTHETIC_SELF_TEST":
            fail_reasons.append(f"UPSTREAM_{tag}_SYNTHETIC_AUTHORITY_SCOPE_MISMATCH")
        if rec_promo_auth is not False:
            fail_reasons.append(f"UPSTREAM_{tag}_SYNTHETIC_CANNOT_AUTHORIZE_PROMOTION")

    if expected_gate_source == "GATE-0V":
        if rec_decision in GATE0V_BANK_ONLY_DECISIONS:
            fail_reasons.append("UPSTREAM_GATE0V_BANK_ONLY_DECISION_REJECTED_FOR_CLINICAL_PROMOTION")
            fail_reasons.append("UPSTREAM_GATE0V_UNAPPROVED_DECISION")
        else:
            if expected_bank_origin == "autologous_hiPSC":
                wet_allowed = GATE0V_AUTOLOGOUS_CLINICAL_DECISIONS
                opp_decisions = GATE0V_ALLOGENEIC_CLINICAL_DECISIONS
            elif expected_bank_origin in ("allogeneic_hiPSC", "allogeneic_EnSC"):
                wet_allowed = GATE0V_ALLOGENEIC_CLINICAL_DECISIONS
                opp_decisions = GATE0V_AUTOLOGOUS_CLINICAL_DECISIONS
            else:
                wet_allowed = ALLOWED_UPSTREAM_WETLAB_DECISIONS["GATE-0V"]
                opp_decisions = frozenset()
            if rec_decision in opp_decisions:
                fail_reasons.append("UPSTREAM_GATE0V_ORIGIN_DECISION_SCOPE_MISMATCH")
                fail_reasons.append("UPSTREAM_GATE0V_UNAPPROVED_DECISION")
            else:
                allowed_dec = wet_allowed if rec_tier == "AUTHENTICATED_ARCHIVED_WETLAB" else (wet_allowed | {"SYNTHETIC_SELF_TEST_PASS"})
                if rec_decision not in allowed_dec:
                    fail_reasons.append("UPSTREAM_GATE0V_UNAPPROVED_DECISION")
    else:
        allowed_dec = (
            ALLOWED_UPSTREAM_WETLAB_DECISIONS[expected_gate_source]
            if rec_tier == "AUTHENTICATED_ARCHIVED_WETLAB"
            else ALLOWED_UPSTREAM_SYNTHETIC_DECISIONS[expected_gate_source]
        )
        if rec_decision not in allowed_dec:
            fail_reasons.append(f"UPSTREAM_{tag}_UNAPPROVED_DECISION")

    gate_specific_keys: List[str] = []
    valid_prereqs: Optional[Dict[str, str]] = None
    recomputed_g5_u95: Optional[float] = None

    if expected_gate_source == "GATE-34":
        gate_specific_keys.append("dual_switch_lot_qualified")
        ds_flag = rec.get("dual_switch_lot_qualified")
        if ds_flag is None:
            hold_reasons.append("MISSING_UPSTREAM_GATE34_DUAL_SWITCH_LOT_QUALIFIED")
        elif not _is_strict_bool(ds_flag):
            fail_reasons.append("INVALID_UPSTREAM_GATE34_DUAL_SWITCH_LOT_QUALIFIED")
        elif expected_dual_switch_required is not None and ds_flag != expected_dual_switch_required:
            fail_reasons.append("UPSTREAM_GATE34_DUAL_SWITCH_MISMATCH")

        prereqs = rec.get("prerequisite_archive_sha256s")
        if prereqs is None:
            if rec_tier == "AUTHENTICATED_ARCHIVED_WETLAB" or rec.get("schema_revision") == UPSTREAM_RECEIPT_SCHEMA_REVISION:
                fail_reasons.append("UPSTREAM_GATE34_MISSING_PREREQUISITE_ARCHIVE_SHA256S")
        else:
            gate_specific_keys.append("prerequisite_archive_sha256s")
            if not isinstance(prereqs, dict):
                fail_reasons.append("UPSTREAM_GATE34_INVALID_PREREQUISITE_ARCHIVE_SHA256S")
            else:
                p_g0v = prereqs.get("GATE-0V")
                p_g5 = prereqs.get("GATE-5")
                if not _is_non_all_zero_sha256_hex(p_g0v) or not _is_non_all_zero_sha256_hex(p_g5):
                    fail_reasons.append("UPSTREAM_GATE34_INVALID_PREREQUISITE_ARCHIVE_SHA256S")
                else:
                    valid_prereqs = {"GATE-0V": p_g0v, "GATE-5": p_g5}
    elif expected_gate_source == "GATE-0V":
        gate_specific_keys.extend(["lineages_verified", "whole_graft_stressed_tested"])
        lin = rec.get("lineages_verified")
        if lin is None:
            hold_reasons.append("MISSING_UPSTREAM_GATE0V_LINEAGES_VERIFIED")
        elif (
            not isinstance(lin, list)
            or not all(_is_literal_nonempty_str(x) for x in lin)
            or {x.lower() for x in lin} != REQUIRED_GY030_LINEAGES
        ):
            fail_reasons.append("GY030_INCOMPLETE_5LINEAGE_WHOLE_GRAFT_PANEL")
        stressed = rec.get("whole_graft_stressed_tested")
        if stressed is None:
            hold_reasons.append("MISSING_UPSTREAM_GATE0V_WHOLE_GRAFT_STRESSED_BOOL")
        elif not _is_strict_bool(stressed) or not stressed:
            fail_reasons.append("GY030_WHOLE_GRAFT_STRESSED_TEST_REQUIRED")
    elif expected_gate_source == "GATE-5":
        gate_specific_keys.extend([
            "oq012_clonogenic_regrowth_pass",
            "survivor_count_k",
            "tested_cells_n",
            "clonogenic_fraction_f",
            "spike_in_detection_efficiency_eta",
            "effective_clonogenic_trials_n_eff",
            "u95_exact",
        ])
        recomputed_g5_u95 = _validate_gate5_counts_and_u95(rec, fail_reasons=fail_reasons, hold_reasons=hold_reasons)

    stored_dict: Optional[Dict[str, Any]] = None
    if rec_tier == "AUTHENTICATED_ARCHIVED_WETLAB":
        if trusted_evidence_store is None:
            hold_reasons.append(f"MISSING_TRUSTED_EVIDENCE_STORE_FOR_{tag}")
        elif not isinstance(trusted_evidence_store, Mapping):
            fail_reasons.append("INVALID_TRUSTED_EVIDENCE_STORE")
        else:
            stored_dict = _resolve_store_entry_with_alias_consistency(
                rec=rec,
                record_id=record_id,
                rec_archive_sha=rec_archive_sha,
                prefix=f"UPSTREAM_{tag}",
                trusted_evidence_store=trusted_evidence_store,
                fail_reasons=fail_reasons,
            )
            if stored_dict is not None:
                _check_no_contradictory_authority_flags(stored_dict, f"UPSTREAM_{tag}_TRUSTED_STORE", fail_reasons)
                for field in REQUIRED_UPSTREAM_SCHEMA_V2_ALL_FIELDS:
                    s_val = stored_dict.get(field)
                    r_val = rec.get(field)
                    if type(s_val) is not type(r_val) or s_val != r_val:
                        fail_reasons.append(f"UPSTREAM_{tag}_TRUSTED_STORE_FIELD_MISMATCH:{field}")
                for gfield in gate_specific_keys:
                    s_val = stored_dict.get(gfield)
                    r_val = rec.get(gfield)
                    if gfield in ("clonogenic_fraction_f", "spike_in_detection_efficiency_eta", "effective_clonogenic_trials_n_eff"):
                        if (gfield in stored_dict) != (gfield in rec) or not _strict_json_equal(s_val, r_val):
                            fail_reasons.append(f"UPSTREAM_{tag}_TRUSTED_STORE_GATE_FIELD_MISMATCH:{gfield}")
                    elif gfield not in stored_dict or not _strict_json_equal(s_val, r_val):
                        fail_reasons.append(f"UPSTREAM_{tag}_TRUSTED_STORE_GATE_FIELD_MISMATCH:{gfield}")

                if stored_dict.get("evidence_tier") != "AUTHENTICATED_ARCHIVED_WETLAB":
                    fail_reasons.append(f"UPSTREAM_{tag}_TRUSTED_STORE_NOT_WETLAB_TIER")
                if stored_dict.get("authority_scope") != "CLINICAL_LOT_RELEASE":
                    fail_reasons.append(f"UPSTREAM_{tag}_TRUSTED_STORE_AUTHORITY_SCOPE_MISMATCH")
                if stored_dict.get("promotion_authorized") is not True:
                    fail_reasons.append(f"UPSTREAM_{tag}_TRUSTED_STORE_PROMOTION_WITHHELD")
                if stored_dict.get("bank_qualified") is not True:
                    fail_reasons.append(f"UPSTREAM_{tag}_TRUSTED_STORE_BANK_NOT_QUALIFIED")

                if expected_gate_source == "GATE-0V":
                    s_lin = stored_dict.get("lineages_verified")
                    if (
                        not isinstance(s_lin, list)
                        or not all(_is_literal_nonempty_str(x) for x in s_lin)
                        or {x.lower() for x in s_lin} != REQUIRED_GY030_LINEAGES
                    ):
                        fail_reasons.append("UPSTREAM_GATE0V_TRUSTED_STORE_LINEAGES_MISMATCH")
                    if stored_dict.get("whole_graft_stressed_tested") is not True:
                        fail_reasons.append("UPSTREAM_GATE0V_TRUSTED_STORE_STRESSED_MISMATCH")
                elif expected_gate_source == "GATE-5":
                    if stored_dict.get("oq012_clonogenic_regrowth_pass") is not True:
                        fail_reasons.append("UPSTREAM_GATE5_TRUSTED_STORE_OQ012_MISMATCH")
                    s_u95 = _validate_gate5_counts_and_u95(stored_dict, fail_reasons=fail_reasons, hold_reasons=hold_reasons)
                    if s_u95 is not None:
                        recomputed_g5_u95 = s_u95
                elif expected_gate_source == "GATE-34":
                    if stored_dict.get("gate_source") == "GATE-32":
                        fail_reasons.append("UPSTREAM_GATE34_LIVE_GATE32_ROLE_COLLISION_REJECTED")
                    s_prereqs = stored_dict.get("prerequisite_archive_sha256s")
                    if not isinstance(s_prereqs, dict) or not _is_non_all_zero_sha256_hex(s_prereqs.get("GATE-0V")) or not _is_non_all_zero_sha256_hex(s_prereqs.get("GATE-5")):
                        fail_reasons.append("UPSTREAM_GATE34_TRUSTED_STORE_INVALID_PREREQUISITE_ARCHIVE_SHA256S")
                    else:
                        valid_prereqs = {"GATE-0V": s_prereqs["GATE-0V"], "GATE-5": s_prereqs["GATE-5"]}

    return {
        "construct_sha": valid_construct_sha,
        "bank_id": rec_bank_id,
        "record_id": record_id,
        "archive_sha256": rec_archive_sha,
        "prerequisite_archive_sha256s": valid_prereqs,
        "recomputed_gate5_u95": recomputed_g5_u95,
        "stored": stored_dict,
    }


def _validate_current_assay_record(
    cur_rec: Any,
    *,
    is_promo: bool,
    expected_product_id: Optional[str],
    expected_lot_id: Optional[str],
    expected_bank_id: Optional[str],
    expected_bank_origin: Optional[str],
    expected_evidence_tier: Optional[str],
    expected_construct_sha: Optional[str],
    upstream_record_ids: Sequence[Optional[str]],
    upstream_archive_shas: Sequence[Optional[str]],
    trusted_evidence_store: Optional[Mapping[str, Mapping[str, Any]]],
    fail_reasons: List[str],
    hold_reasons: List[str],
) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
    """Validate mandatory GATE-35 current_assay_evidence_record in trusted_evidence_store (rejecting colliding live GATE-33)."""
    if cur_rec is None:
        fail_reasons.append("MISSING_CURRENT_ASSAY_EVIDENCE_RECORD")
        return None, None
    if not isinstance(cur_rec, dict):
        fail_reasons.append("INVALID_CURRENT_ASSAY_EVIDENCE_RECORD")
        return None, None

    _check_no_contradictory_authority_flags(cur_rec, "CURRENT_ASSAY_GATE35", fail_reasons)

    missing_or_invalid = False
    for field in REQUIRED_UPSTREAM_SCHEMA_V2_STRING_FIELDS:
        val = cur_rec.get(field)
        if val is None:
            fail_reasons.append(f"MISSING_CURRENT_ASSAY_GATE35_FIELD:{field}")
            missing_or_invalid = True
        elif not _is_literal_nonempty_str(val):
            fail_reasons.append(f"INVALID_CURRENT_ASSAY_GATE35_FIELD:{field}")
            missing_or_invalid = True

    for field in REQUIRED_UPSTREAM_SCHEMA_V2_BOOL_FIELDS:
        val = cur_rec.get(field)
        if val is None:
            fail_reasons.append(f"MISSING_CURRENT_ASSAY_GATE35_FIELD:{field}")
            missing_or_invalid = True
        elif not _is_strict_bool(val):
            fail_reasons.append(f"INVALID_CURRENT_ASSAY_GATE35_FIELD:{field}")
            missing_or_invalid = True

    if missing_or_invalid:
        return dict(cur_rec), None

    record_id = cur_rec["record_id"]
    gate_source = cur_rec["gate_source"]
    rec_prod = cur_rec["product_id"]
    rec_lot = cur_rec["lot_id"]
    rec_bank_id = cur_rec["bank_id"]
    rec_bank_origin = cur_rec["bank_origin"]
    rec_arm_manifest_sha = cur_rec["canonical_arm_manifest_sha256"]
    rec_construct_sha = cur_rec["construct_manifest_sha256"]
    rec_tier = cur_rec["evidence_tier"]
    rec_decision = cur_rec["decision"]
    rec_authority_scope = cur_rec["authority_scope"]
    rec_bank_qualified = cur_rec["bank_qualified"]
    rec_promo_auth = cur_rec["promotion_authorized"]
    rec_archive_sha = cur_rec["archive_sha256"]

    if gate_source != "GATE-35":
        if gate_source == "GATE-33":
            fail_reasons.append("CURRENT_ASSAY_GATE35_LIVE_GATE33_ROLE_COLLISION_REJECTED")
        fail_reasons.append("CURRENT_ASSAY_GATE35_GATE_SOURCE_MISMATCH")
    if expected_product_id is not None and rec_prod != expected_product_id:
        fail_reasons.append("CURRENT_ASSAY_GATE35_PRODUCT_ID_MISMATCH")
    if expected_lot_id is not None and rec_lot != expected_lot_id:
        fail_reasons.append("CURRENT_ASSAY_GATE35_LOT_ID_MISMATCH")
    if expected_bank_id is not None and rec_bank_id != expected_bank_id:
        fail_reasons.append("CURRENT_ASSAY_GATE35_BANK_ID_MISMATCH")
    if rec_bank_origin not in ALLOWED_BANK_ORIGINS:
        fail_reasons.append("CURRENT_ASSAY_GATE35_INVALID_BANK_ORIGIN")
    elif expected_bank_origin is not None and rec_bank_origin != expected_bank_origin:
        fail_reasons.append("CURRENT_ASSAY_GATE35_BANK_ORIGIN_MISMATCH")
    if rec_arm_manifest_sha != EXPECTED_CANONICAL_MANIFEST_SHA256:
        fail_reasons.append("CURRENT_ASSAY_GATE35_CANONICAL_ARM_MANIFEST_SHA256_MISMATCH")

    valid_construct_sha: Optional[str] = None
    if not _is_non_all_zero_sha256_hex(rec_construct_sha) or rec_construct_sha == EXPECTED_CANONICAL_MANIFEST_SHA256:
        fail_reasons.append("CURRENT_ASSAY_GATE35_CONSTRUCT_MANIFEST_SHA256_INVALID_OR_CONFLATED")
    else:
        valid_construct_sha = rec_construct_sha
        if expected_construct_sha is not None and rec_construct_sha != expected_construct_sha:
            fail_reasons.append("CURRENT_ASSAY_GATE35_CONSTRUCT_MANIFEST_SHA256_MISMATCH")

    if not _is_non_all_zero_sha256_hex(rec_archive_sha):
        fail_reasons.append("CURRENT_ASSAY_GATE35_INVALID_OR_ZERO_ARCHIVE_SHA256")
    if rec_tier not in ALLOWED_EVIDENCE_TIERS:
        fail_reasons.append("CURRENT_ASSAY_GATE35_INVALID_EVIDENCE_TIER")
    elif expected_evidence_tier is not None and rec_tier != expected_evidence_tier:
        fail_reasons.append("CURRENT_ASSAY_GATE35_EVIDENCE_TIER_MISMATCH")
    if rec_authority_scope not in ALLOWED_AUTHORITY_SCOPES:
        fail_reasons.append("CURRENT_ASSAY_GATE35_INVALID_AUTHORITY_SCOPE")

    if record_id in [x for x in upstream_record_ids if x is not None]:
        fail_reasons.append("CURRENT_ASSAY_GATE35_RECORD_ID_CONFLATED_WITH_UPSTREAM")
    if rec_archive_sha in [x for x in upstream_archive_shas if x is not None]:
        fail_reasons.append("CURRENT_ASSAY_GATE35_ARCHIVE_SHA256_CONFLATED_WITH_UPSTREAM")

    cur_scale = cur_rec.get("scale_mode")
    needs_clinical_authority = is_promo and (cur_scale != "ANIMAL_PRECLINICAL_SCALE")

    if rec_tier == "AUTHENTICATED_ARCHIVED_WETLAB":
        if needs_clinical_authority:
            if rec_authority_scope != "CLINICAL_LOT_RELEASE":
                fail_reasons.append("CURRENT_ASSAY_GATE35_AUTHORITY_SCOPE_NOT_CLINICAL_LOT_RELEASE")
            if rec_promo_auth is not True:
                fail_reasons.append("CURRENT_ASSAY_GATE35_PROMOTION_AUTHORIZATION_WITHHELD")
            if rec_bank_qualified is not True:
                fail_reasons.append("CURRENT_ASSAY_GATE35_BANK_NOT_QUALIFIED")
            if rec_decision not in ALLOWED_CURRENT_ASSAY_CLINICAL_DECISIONS:
                fail_reasons.append("CURRENT_ASSAY_GATE35_UNAPPROVED_DECISION")
        else:
            if rec_authority_scope not in ("CLINICAL_LOT_RELEASE", "BANK_QUALIFICATION_ONLY"):
                fail_reasons.append("CURRENT_ASSAY_GATE35_AUTHORITY_SCOPE_REJECTED")
            if rec_decision not in ALLOWED_CURRENT_ASSAY_NONPROMO_DECISIONS:
                fail_reasons.append("CURRENT_ASSAY_GATE35_UNAPPROVED_DECISION")
    elif rec_tier == "SYNTHETIC_FIXTURE":
        if rec_authority_scope != "SYNTHETIC_SELF_TEST":
            fail_reasons.append("CURRENT_ASSAY_GATE35_SYNTHETIC_AUTHORITY_SCOPE_MISMATCH")
        if rec_promo_auth is not False:
            fail_reasons.append("CURRENT_ASSAY_GATE35_SYNTHETIC_CANNOT_AUTHORIZE_PROMOTION")
        if rec_decision not in ALLOWED_CURRENT_ASSAY_SYNTHETIC_DECISIONS:
            fail_reasons.append("CURRENT_ASSAY_GATE35_UNAPPROVED_DECISION")
        try:
            recomp_synth = _canonical_json_sha256({k: v for k, v in cur_rec.items() if k != "archive_sha256"})
        except (TypeError, ValueError, OverflowError, DecimalException):
            fail_reasons.append("CURRENT_ASSAY_GATE35_SUBMITTED_BODY_UNSERIALIZABLE")
        else:
            if recomp_synth != rec_archive_sha:
                fail_reasons.append("CURRENT_ASSAY_GATE35_SUBMITTED_BODY_DIGEST_MISMATCH")

    verified_body: Dict[str, Any] = dict(cur_rec)
    if rec_tier == "AUTHENTICATED_ARCHIVED_WETLAB":
        if trusted_evidence_store is None:
            hold_reasons.append("MISSING_TRUSTED_EVIDENCE_STORE_FOR_CURRENT_ASSAY_GATE35")
        elif not isinstance(trusted_evidence_store, Mapping):
            fail_reasons.append("INVALID_TRUSTED_EVIDENCE_STORE")
        else:
            stored_dict = _resolve_store_entry_with_alias_consistency(
                rec=cur_rec,
                record_id=record_id,
                rec_archive_sha=rec_archive_sha,
                prefix="CURRENT_ASSAY_GATE35",
                trusted_evidence_store=trusted_evidence_store,
                fail_reasons=fail_reasons,
            )
            if stored_dict is not None:
                verified_body = stored_dict
                _check_no_contradictory_authority_flags(stored_dict, "CURRENT_ASSAY_GATE35_TRUSTED_STORE", fail_reasons)
                for field in REQUIRED_UPSTREAM_SCHEMA_V2_ALL_FIELDS:
                    s_val = stored_dict.get(field)
                    r_val = cur_rec.get(field)
                    if type(s_val) is not type(r_val) or s_val != r_val:
                        fail_reasons.append(f"CURRENT_ASSAY_GATE35_TRUSTED_STORE_FIELD_MISMATCH:{field}")
                if stored_dict.get("evidence_tier") != "AUTHENTICATED_ARCHIVED_WETLAB":
                    fail_reasons.append("CURRENT_ASSAY_GATE35_TRUSTED_STORE_NOT_WETLAB_TIER")
                if stored_dict.get("gate_source") != "GATE-35":
                    if stored_dict.get("gate_source") == "GATE-33":
                        fail_reasons.append("CURRENT_ASSAY_GATE35_LIVE_GATE33_ROLE_COLLISION_REJECTED")
                    fail_reasons.append("CURRENT_ASSAY_GATE35_TRUSTED_STORE_GATE_SOURCE_MISMATCH")
                s_scale = stored_dict.get("scale_mode")
                s_needs_clin = is_promo and (s_scale != "ANIMAL_PRECLINICAL_SCALE")
                if s_needs_clin:
                    if stored_dict.get("authority_scope") != "CLINICAL_LOT_RELEASE":
                        fail_reasons.append("CURRENT_ASSAY_GATE35_TRUSTED_STORE_AUTHORITY_SCOPE_MISMATCH")
                    if stored_dict.get("promotion_authorized") is not True:
                        fail_reasons.append("CURRENT_ASSAY_GATE35_TRUSTED_STORE_PROMOTION_WITHHELD")
                    if stored_dict.get("bank_qualified") is not True:
                        fail_reasons.append("CURRENT_ASSAY_GATE35_TRUSTED_STORE_BANK_NOT_QUALIFIED")
                    if stored_dict.get("decision") not in ALLOWED_CURRENT_ASSAY_CLINICAL_DECISIONS:
                        fail_reasons.append("CURRENT_ASSAY_GATE35_TRUSTED_STORE_DECISION_REJECTED")
                else:
                    if stored_dict.get("authority_scope") not in ("CLINICAL_LOT_RELEASE", "BANK_QUALIFICATION_ONLY"):
                        fail_reasons.append("CURRENT_ASSAY_GATE35_TRUSTED_STORE_AUTHORITY_SCOPE_MISMATCH")
                    if stored_dict.get("decision") not in ALLOWED_CURRENT_ASSAY_NONPROMO_DECISIONS:
                        fail_reasons.append("CURRENT_ASSAY_GATE35_TRUSTED_STORE_DECISION_REJECTED")

    return verified_body, valid_construct_sha


def _extract_areal_loading_with_alias(
    source: Mapping[str, Any],
    *,
    fail_reasons: List[str],
    mismatch_code: str,
) -> Any:
    """Resolve areal loading from areal_loading_ieq_cm2 / areal_loading_ieq_per_cm2 enforcing exact Decimal alias consistency."""
    v1 = source.get("areal_loading_ieq_cm2")
    v2 = source.get("areal_loading_ieq_per_cm2")
    if v1 is not None and v2 is not None:
        if not _is_finite_number(v1) or not _is_finite_number(v2) or _to_exact_decimal(v1) != _to_exact_decimal(v2):
            fail_reasons.append(mismatch_code)
    return v1 if v1 is not None else v2


def _reconcile_parent_against_current_archive(
    payload: Mapping[str, Any],
    verified_archive: Mapping[str, Any],
    *,
    is_promo: bool,
    fail_reasons: List[str],
) -> bool:
    """Enforce exact strict equality between parent fields and verified current_assay_evidence_record (Review #4).

    Returns True if ANY discrepancy was detected between parent and verified archive.
    """
    any_diff = False
    arch_site = verified_archive.get("deployment_site")
    parent_site = payload.get("deployment_site")
    arch_exv = verified_archive.get("exvivo_rest_applied")
    parent_exv = payload.get("exvivo_rest_applied")

    required_fields: List[str] = list(CURRENT_ASSAY_ALWAYS_BOUND_FIELDS)
    if is_promo:
        required_fields.extend(CURRENT_ASSAY_STAGE1_COMMON_BOUND_FIELDS)
        if arch_site == "R4_OMENTUM_LEAD" or parent_site == "R4_OMENTUM_LEAD":
            required_fields.extend(CURRENT_ASSAY_STAGE1_OMENTUM_BOUND_FIELDS)
    if arch_exv is True or parent_exv is True:
        required_fields.extend(CURRENT_ASSAY_EXVIVO_REST_STAGE0_BOUND_FIELDS)
        if is_promo:
            required_fields.extend(CURRENT_ASSAY_EXVIVO_REST_STAGE1_BOUND_FIELDS)

    for fname in required_fields:
        p_val = payload.get(fname)
        a_val = verified_archive.get(fname)
        if p_val is None and a_val is None:
            continue
        if a_val is None and p_val is not None:
            fail_reasons.append(f"CURRENT_ASSAY_ARCHIVE_MISSING_REQUIRED_FIELD:{fname}")
            any_diff = True
        elif p_val is None and a_val is not None:
            fail_reasons.append(f"CURRENT_ASSAY_PARENT_MISSING_ARCHIVED_FIELD:{fname}")
            any_diff = True
        elif not _strict_json_equal(p_val, a_val):
            fail_reasons.append(f"CURRENT_ASSAY_ARCHIVE_FIELD_MISMATCH:{fname}")
            any_diff = True

    # Alias-aware areal loading reconciliation (areal_loading_ieq_cm2 / areal_loading_ieq_per_cm2)
    p_load = _extract_areal_loading_with_alias(
        payload, fail_reasons=fail_reasons, mismatch_code="INCONSISTENT_AREAL_LOADING_ALIAS_FIELD",
    )
    a_load = _extract_areal_loading_with_alias(
        verified_archive, fail_reasons=fail_reasons, mismatch_code="CURRENT_ASSAY_ARCHIVE_INCONSISTENT_AREAL_LOADING_ALIAS",
    )
    if p_load is None and a_load is None:
        pass
    elif a_load is None and p_load is not None:
        fail_reasons.append("CURRENT_ASSAY_ARCHIVE_MISSING_REQUIRED_FIELD:areal_loading_ieq_per_cm2")
        any_diff = True
    elif p_load is None and a_load is not None:
        fail_reasons.append("CURRENT_ASSAY_PARENT_MISSING_ARCHIVED_FIELD:areal_loading_ieq_cm2")
        any_diff = True
    elif not _strict_json_equal(p_load, a_load):
        fail_reasons.append("CURRENT_ASSAY_ARCHIVE_FIELD_MISMATCH:areal_loading_ieq_cm2")
        any_diff = True

    # Optional measured_bed_po2_mmhg consistency when present in either parent or archive
    p_leg_bed = payload.get("measured_bed_po2_mmhg")
    a_leg_bed = verified_archive.get("measured_bed_po2_mmhg")
    if (p_leg_bed is not None or a_leg_bed is not None) and not _strict_json_equal(p_leg_bed, a_leg_bed):
        fail_reasons.append("CURRENT_ASSAY_ARCHIVE_FIELD_MISMATCH:measured_bed_po2_mmhg")
        any_diff = True

    return any_diff


def _evaluate_gate33_measurements(
    obs: Mapping[str, Any],
    *,
    is_promo: bool,
    valid_lot_id: Optional[str],
    arm_spec: Optional[Dict[str, Any]],
    fail_reasons: List[str],
    hold_reasons: List[str],
) -> Dict[str, Any]:
    """Evaluate all Gate-33 CMC, physical geometry, per-leaf reconciliation, actual-leaf steric packing,
    scope-bound scale_mode, Stage-1 porcine/NHP cohorts, and ex-vivo rest cutoffs on the given observation source.
    """
    site = obs.get("deployment_site")
    valid_site: Optional[str] = None
    if site is None:
        hold_reasons.append("MISSING_DEPLOYMENT_SITE")
    elif not _is_literal_nonempty_str(site) or site not in ("R4_OMENTUM_LEAD", "R4_SARS_FREE_BACKUP"):
        fail_reasons.append("INVALID_OR_UNREGISTERED_DEPLOYMENT_SITE")
    else:
        valid_site = site

    # 4. Clinical matrix, sterility, mycoplasma, PPCN quarantine, needle-track ban, and strict allowlist Cuff safety
    matrix = obs.get("clinical_matrix_id")
    if matrix is None:
        hold_reasons.append("MISSING_CLINICAL_MATRIX_ID")
    elif not _is_literal_nonempty_str(matrix):
        fail_reasons.append("INVALID_CLINICAL_MATRIX_ID")
    elif matrix == "PPCN_CITRATE_PNIPAAM":
        fail_reasons.append("PPCN_QUARANTINED_STAGE0_RESEARCH_COMPARATOR_ONLY")
    elif valid_site == "R4_OMENTUM_LEAD" and matrix not in ALLOWED_CLINICAL_MATRICES_OMENTUM:
        fail_reasons.append("OMENTUM_CLINICAL_LEAD_REQUIRES_GMP_PLASMA_THROMBIN_OR_FIBRIN")
    elif valid_site == "R4_SARS_FREE_BACKUP" and matrix not in ALLOWED_CLINICAL_MATRICES_SARS_BACKUP:
        fail_reasons.append("SARS_BACKUP_REQUIRES_BIODEGRADABLE_THIN_PLANAR_CARRIER_NO_NEEDLE_TRACKS")

    needle_tracks = obs.get("needle_microtracks_used")
    if needle_tracks is None:
        hold_reasons.append("MISSING_NEEDLE_MICROTRACKS_BOOL")
    elif not _is_strict_bool(needle_tracks):
        fail_reasons.append("INVALID_NEEDLE_MICROTRACKS_BOOL")
    elif needle_tracks:
        fail_reasons.append("GY028_3_NEEDLE_MICROTRACK_BOLUS_PROHIBITED")

    cuff_agents = obs.get("coformulated_immune_cuff_agents")
    if cuff_agents is None:
        hold_reasons.append("MISSING_CUFF_AGENT_MANIFEST")
    elif not isinstance(cuff_agents, list) or not all(_is_literal_nonempty_str(x) for x in cuff_agents):
        fail_reasons.append("INVALID_CUFF_AGENT_MANIFEST")
    else:
        for ag in cuff_agents:
            if _is_fasl_or_cd95_token(ag):
                fail_reasons.append(f"R4O_02_HARD_VETO_FASL_PROHIBITED:{ag}")
            elif ag not in ALLOWED_CUFF_COMPONENTS_ALLOWLIST:
                fail_reasons.append(f"UNREGISTERED_CUFF_COMPONENT_REJECTED:{ag}")
        if arm_spec is not None and arm_spec.get("cuff_v2_eligible") is False and len(cuff_agents) > 0:
            fail_reasons.append("DESIGN_A_STRICTLY_PROHIBITS_IMMOBILIZED_CUFF_BIOLOGICS")

    polyglactin_used = obs.get("polyglactin_sutures_used")
    if polyglactin_used is None:
        hold_reasons.append("MISSING_POLYGLACTIN_BOOL")
    elif not _is_strict_bool(polyglactin_used):
        fail_reasons.append("INVALID_POLYGLACTIN_BOOL")
    elif polyglactin_used:
        fail_reasons.append("POLYGLACTIN_SUTURES_PROHIBITED_FBR_RISK")

    ductal_pct = obs.get("ductal_cytokeratin_impurity_pct")
    if ductal_pct is None:
        hold_reasons.append("MISSING_DUCTAL_IMPURITY_PCT")
    elif not _is_finite_number(ductal_pct):
        fail_reasons.append("INVALID_DUCTAL_IMPURITY_PCT")
    else:
        ductal_d = _to_exact_decimal(ductal_pct)
        if ductal_d < ZERO_DEC or ductal_d > Decimal("100"):
            fail_reasons.append("INVALID_DUCTAL_IMPURITY_PCT")
        elif ductal_d >= Decimal("2"):
            fail_reasons.append("DUCTAL_IMPURITY_GE_2PCT_FAIL")

    endotoxin = obs.get("endotoxin_eu_per_ml")
    if endotoxin is None:
        hold_reasons.append("MISSING_ENDOTOXIN_ASSAY")
    elif not _is_finite_number(endotoxin):
        fail_reasons.append("INVALID_ENDOTOXIN_ASSAY")
    else:
        endo_d = _to_exact_decimal(endotoxin)
        if endo_d < ZERO_DEC:
            fail_reasons.append("INVALID_ENDOTOXIN_ASSAY")
        elif endo_d >= Decimal("0.5"):
            fail_reasons.append("R4O_01_ENDOTOXIN_GE_0P5_EU_ML_FAIL")

    sterility_ok = obs.get("sterility_pass")
    if sterility_ok is None:
        hold_reasons.append("MISSING_R4O01_STERILITY_ASSAY")
    elif not _is_strict_bool(sterility_ok):
        fail_reasons.append("INVALID_R4O01_STERILITY_BOOL")
    elif not sterility_ok:
        fail_reasons.append("R4O_01_STERILITY_FAILED")

    myco_neg = obs.get("mycoplasma_negative")
    if myco_neg is None:
        hold_reasons.append("MISSING_R4O01_MYCOPLASMA_ASSAY")
    elif not _is_strict_bool(myco_neg):
        fail_reasons.append("INVALID_R4O01_MYCOPLASMA_BOOL")
    elif not myco_neg:
        fail_reasons.append("R4O_01_MYCOPLASMA_POSITIVE_FAIL")

    fasl_ug = obs.get("analytical_fasl_ug")
    if fasl_ug is None:
        hold_reasons.append("MISSING_ANALYTICAL_FASL_ZERO_CERTIFICATION")
    elif not _is_finite_number(fasl_ug):
        fail_reasons.append("INVALID_ANALYTICAL_FASL_UG")
    else:
        fasl_d = _to_exact_decimal(fasl_ug)
        if fasl_d < ZERO_DEC:
            fail_reasons.append("INVALID_ANALYTICAL_FASL_UG")
        elif fasl_d > ZERO_DEC:
            fail_reasons.append("R4O_02_ANALYTICAL_FASL_NONZERO_VETO")

    hep_casp = obs.get("hepatocyte_72h_caspase37_u95_fold")
    if hep_casp is None:
        hold_reasons.append("MISSING_R4O02_HEPATOCYTE_CASPASE37_ASSAY")
    elif not _is_finite_number(hep_casp):
        fail_reasons.append("INVALID_HEPATOCYTE_CASPASE37_ASSAY")
    else:
        hep_casp_d = _to_exact_decimal(hep_casp)
        if hep_casp_d <= ZERO_DEC:
            fail_reasons.append("INVALID_HEPATOCYTE_CASPASE37_ASSAY")
        elif hep_casp_d > Decimal("1.15"):
            fail_reasons.append("R4O_02_HEPATOCYTE_CASPASE37_EXCEEDS_1P15X_FAIL")

    hep_alt = obs.get("hepatocyte_72h_alt_ldh_u95_fold")
    if hep_alt is None:
        hold_reasons.append("MISSING_R4O02_HEPATOCYTE_ALT_LDH_ASSAY")
    elif not _is_finite_number(hep_alt):
        fail_reasons.append("INVALID_HEPATOCYTE_ALT_LDH_ASSAY")
    else:
        hep_alt_d = _to_exact_decimal(hep_alt)
        if hep_alt_d <= ZERO_DEC:
            fail_reasons.append("INVALID_HEPATOCYTE_ALT_LDH_ASSAY")
        elif hep_alt_d > Decimal("1.15"):
            fail_reasons.append("R4O_02_HEPATOCYTE_ALT_LDH_EXCEEDS_1P15X_FAIL")

    leachate_ok = obs.get("cuff_leachate_assay_passed")
    if leachate_ok is None:
        hold_reasons.append("MISSING_R4O02_CUFF_LEACHATE_ASSAY")
    elif not _is_strict_bool(leachate_ok):
        fail_reasons.append("INVALID_CUFF_LEACHATE_BOOL")
    elif not leachate_ok:
        fail_reasons.append("R4O_02_CUFF_LEACHATE_ASSAY_FAILED")

    # 5. Physical Geometry, Sieving (40..65 um), Layout, Plane Offset (|z_c| >= 20 um)
    layout = obs.get("construct_layout")
    if layout is None:
        hold_reasons.append("MISSING_CONSTRUCT_LAYOUT")
    elif not _is_literal_nonempty_str(layout) or layout != "STAGGERED_BILAYER":
        fail_reasons.append("CONSTRUCT_LAYOUT_MUST_BE_STAGGERED_BILAYER")

    h_um = obs.get("construct_thickness_um")
    h_d: Optional[Decimal] = None
    h_domain_ok = False
    if h_um is None:
        hold_reasons.append("MISSING_CONSTRUCT_THICKNESS_UM")
    elif not _is_finite_number(h_um):
        fail_reasons.append("CONSTRUCT_THICKNESS_OUTSIDE_100_TO_120UM_FAIL")
    else:
        h_d = _to_exact_decimal(h_um)
        if h_d < Decimal("100") or h_d > Decimal("120"):
            fail_reasons.append("CONSTRUCT_THICKNESS_OUTSIDE_100_TO_120UM_FAIL")
        else:
            h_domain_ok = True

    d_min = obs.get("cluster_min_diam_um")
    d_rms3 = obs.get("cluster_d_rms3_um")
    d_p95 = obs.get("cluster_d_p95_um")
    d_max = obs.get("cluster_max_diam_um")
    d_min_d: Optional[Decimal] = None
    d_rms3_d: Optional[Decimal] = None
    d_p95_d: Optional[Decimal] = None
    d_max_d: Optional[Decimal] = None

    if d_min is None:
        hold_reasons.append("MISSING_CLUSTER_MIN_DIAM_UM")
    elif not _is_finite_number(d_min):
        fail_reasons.append("CLUSTER_MIN_DIAM_OUTSIDE_40_TO_65UM_FAIL")
    else:
        d_min_d = _to_exact_decimal(d_min)
        if d_min_d < Decimal("40") or d_min_d > Decimal("65"):
            fail_reasons.append("CLUSTER_MIN_DIAM_OUTSIDE_40_TO_65UM_FAIL")

    if d_rms3 is None:
        hold_reasons.append("MISSING_CLUSTER_D_RMS3_UM")
    elif not _is_finite_number(d_rms3):
        fail_reasons.append("CLUSTER_D_RMS3_OUTSIDE_40_TO_65UM_FAIL")
    else:
        d_rms3_d = _to_exact_decimal(d_rms3)
        if d_rms3_d < Decimal("40") or d_rms3_d > Decimal("65"):
            fail_reasons.append("CLUSTER_D_RMS3_OUTSIDE_40_TO_65UM_FAIL")

    if d_p95 is None:
        hold_reasons.append("MISSING_CLUSTER_D_P95_UM")
    elif not _is_finite_number(d_p95):
        fail_reasons.append("CLUSTER_D_P95_OUTSIDE_40_TO_65UM_FAIL")
    else:
        d_p95_d = _to_exact_decimal(d_p95)
        if d_p95_d < Decimal("40") or d_p95_d > Decimal("65"):
            fail_reasons.append("CLUSTER_D_P95_OUTSIDE_40_TO_65UM_FAIL")

    if d_max is None:
        hold_reasons.append("MISSING_CLUSTER_MAX_DIAM_UM")
    elif not _is_finite_number(d_max):
        fail_reasons.append("CLUSTER_MAX_DIAM_EXCEEDS_65UM_SIEVING_LAW")
    else:
        d_max_d = _to_exact_decimal(d_max)
        if d_max_d < Decimal("40") or d_max_d > Decimal("65"):
            fail_reasons.append("CLUSTER_MAX_DIAM_EXCEEDS_65UM_SIEVING_LAW")

    diam_domain_ok = False
    if d_min_d is not None and d_rms3_d is not None and d_p95_d is not None and d_max_d is not None:
        if Decimal("40") <= d_min_d <= d_rms3_d <= d_p95_d <= d_max_d <= Decimal("65"):
            diam_domain_ok = True
        else:
            fail_reasons.append("CLUSTER_DIAMETER_QUANTILE_ORDER_INVALID")

    z_c_val = obs.get("staggered_bilayer_plane_offset_um")
    z_c_d: Optional[Decimal] = None
    zc_domain_ok = False
    if z_c_val is None:
        hold_reasons.append("MISSING_STAGGERED_BILAYER_PLANE_OFFSET_UM")
    elif not _is_finite_number(z_c_val):
        fail_reasons.append("STAGGERED_BILAYER_PLANE_OFFSET_LT_20UM_FAIL")
    else:
        z_c_d = _to_exact_decimal(z_c_val)
        if z_c_d < Decimal("20") or z_c_d > Decimal("60"):
            fail_reasons.append("STAGGERED_BILAYER_PLANE_OFFSET_LT_20UM_FAIL")
        else:
            zc_domain_ok = True

    if h_domain_ok and diam_domain_ok and zc_domain_ok and h_d is not None and d_max_d is not None and z_c_d is not None:
        half_h_d = _dec_mul(Decimal("0.5"), h_d)
        outer_edge_d = _dec_add(z_c_d, _dec_mul(Decimal("0.5"), d_max_d))
        wall_clear_d = _dec_sub(half_h_d, outer_edge_d)
        if outer_edge_d > half_h_d:
            fail_reasons.append("CLUSTER_PROTRUDES_OUTSIDE_SLAB_THICKNESS_FAIL")
        elif wall_clear_d < MIN_GY028_WALL_CLEARANCE_UM_DEC:
            fail_reasons.append("GY028_WALL_CLEARANCE_LT_7P5UM_FAIL")

    # 6. Bilateral Face Bed pO2, Measured O2, Lot OCR, Per-Leaf Reconciliation (Audit F4),
    #    Actual Max-Leaf Steric Packing (Review #6 / Audit R4-03), Scope-Bound scale_mode, & Tier Union
    bi_perf = obs.get("bilateral_vascular_perfusion_verified")
    if bi_perf is None:
        hold_reasons.append("MISSING_BILATERAL_PERFUSION_VERIFICATION")
    elif not _is_strict_bool(bi_perf):
        fail_reasons.append("INVALID_BILATERAL_PERFUSION_BOOL")
    elif not bi_perf:
        fail_reasons.append("UNILATERAL_PERFUSION_ANOXIA_FAIL")

    stacked = obs.get("back_to_back_unperfused_stacking")
    if stacked is None:
        hold_reasons.append("MISSING_BACK_TO_BACK_STACKING_BOOL")
    elif not _is_strict_bool(stacked):
        fail_reasons.append("INVALID_BACK_TO_BACK_STACKING_BOOL")
    elif stacked:
        fail_reasons.append("BACK_TO_BACK_UNPERFUSED_FOLDED_STACKING_PROHIBITED")

    loading = _extract_areal_loading_with_alias(
        obs, fail_reasons=fail_reasons, mismatch_code="INCONSISTENT_AREAL_LOADING_ALIAS_FIELD",
    )
    loading_d: Optional[Decimal] = None
    loading_domain_ok = False
    if loading is None:
        hold_reasons.append("MISSING_AREAL_LOADING_IEQ_CM2")
    elif not _is_finite_number(loading):
        fail_reasons.append("INVALID_AREAL_LOADING")
    else:
        loading_d = _to_exact_decimal(loading)
        if not (ONE_DEC <= loading_d <= Decimal("1e6")):
            fail_reasons.append("INVALID_AREAL_LOADING")
        else:
            loading_domain_ok = True

    bed_bot = obs.get("bed_face_bot_po2_mmhg")
    bed_top = obs.get("bed_face_top_po2_mmhg")
    bed_bot_d: Optional[Decimal] = None
    bed_top_d: Optional[Decimal] = None
    if bed_bot is None:
        hold_reasons.append("MISSING_BED_FACE_BOT_PO2_MMHG")
    elif not _is_finite_number(bed_bot):
        fail_reasons.append("INVALID_BED_FACE_BOT_PO2_MMHG")
    else:
        bed_bot_d = _to_exact_decimal(bed_bot)
        if bed_bot_d <= ZERO_DEC:
            fail_reasons.append("INVALID_BED_FACE_BOT_PO2_MMHG")
            bed_bot_d = None

    if bed_top is None:
        hold_reasons.append("MISSING_BED_FACE_TOP_PO2_MMHG")
    elif not _is_finite_number(bed_top):
        fail_reasons.append("INVALID_BED_FACE_TOP_PO2_MMHG")
    else:
        bed_top_d = _to_exact_decimal(bed_top)
        if bed_top_d <= ZERO_DEC:
            fail_reasons.append("INVALID_BED_FACE_TOP_PO2_MMHG")
            bed_top_d = None

    min_bed_po2_d: Optional[Decimal] = None
    max_bed_po2_d: Optional[Decimal] = None
    if bed_bot_d is not None and bed_top_d is not None:
        min_bed_po2_d = min(bed_bot_d, bed_top_d)
        max_bed_po2_d = max(bed_bot_d, bed_top_d)
        if min_bed_po2_d < Decimal("35"):
            fail_reasons.append("MIN_BILATERAL_BED_PO2_BELOW_35MMHG_ENVELOPE_FLOOR")

    if "measured_bed_po2_mmhg" in obs and obs["measured_bed_po2_mmhg"] is not None:
        leg_bed = obs["measured_bed_po2_mmhg"]
        if not _is_finite_number(leg_bed):
            fail_reasons.append("INVALID_MEASURED_BED_PO2_MMHG")
        else:
            leg_bed_d = _to_exact_decimal(leg_bed)
            if leg_bed_d <= ZERO_DEC:
                fail_reasons.append("INVALID_MEASURED_BED_PO2_MMHG")
            elif min_bed_po2_d is not None and leg_bed_d > min_bed_po2_d:
                fail_reasons.append("MEASURED_BED_PO2_EXCEEDS_MIN_BILATERAL_FACE_PO2_INCONSISTENT")
            elif min_bed_po2_d is not None:
                min_bed_po2_d = min(min_bed_po2_d, leg_bed_d)

    fibrin_um = obs.get("measured_fibrin_capsule_um")
    fibrin_d: Optional[Decimal] = None
    if fibrin_um is None:
        hold_reasons.append("MISSING_MEASURED_FIBRIN_CAPSULE_UM")
    elif not _is_finite_number(fibrin_um):
        fail_reasons.append("INVALID_MEASURED_FIBRIN_CAPSULE_UM")
    else:
        fibrin_d = _to_exact_decimal(fibrin_um)
        if fibrin_d < ZERO_DEC:
            fail_reasons.append("INVALID_MEASURED_FIBRIN_CAPSULE_UM")
            fibrin_d = None

    face_o2 = obs.get("measured_worst_face_o2_mmhg")
    face_o2_d: Optional[Decimal] = None
    if face_o2 is None:
        hold_reasons.append("MISSING_MEASURED_WORST_FACE_O2_MMHG")
    elif not _is_finite_number(face_o2):
        fail_reasons.append("INVALID_MEASURED_WORST_FACE_O2_MMHG")
    else:
        face_o2_d = _to_exact_decimal(face_o2)
        if face_o2_d < ZERO_DEC:
            fail_reasons.append("INVALID_MEASURED_WORST_FACE_O2_MMHG")
        elif face_o2_d < Decimal("15"):
            fail_reasons.append("MEASURED_WORST_FACE_O2_LT_15MMHG_FAIL")
        elif max_bed_po2_d is not None and face_o2_d > max_bed_po2_d:
            fail_reasons.append("MEASURED_WORST_FACE_O2_EXCEEDS_BED_PO2_INCONSISTENT")

    core_o2 = obs.get("measured_worst_core_o2_mmhg")
    core_o2_d: Optional[Decimal] = None
    if core_o2 is None:
        hold_reasons.append("MISSING_MEASURED_WORST_CORE_O2_MMHG")
    elif not _is_finite_number(core_o2):
        fail_reasons.append("INVALID_MEASURED_WORST_CORE_O2_MMHG")
    else:
        core_o2_d = _to_exact_decimal(core_o2)
        if core_o2_d < ZERO_DEC:
            fail_reasons.append("INVALID_MEASURED_WORST_CORE_O2_MMHG")
        elif core_o2_d < Decimal("5"):
            fail_reasons.append("MEASURED_WORST_CORE_O2_LT_5MMHG_FAIL")
        elif face_o2_d is not None and core_o2_d > face_o2_d:
            fail_reasons.append("MEASURED_WORST_CORE_O2_EXCEEDS_FACE_O2_INCONSISTENT")

    lot_ocr = obs.get("measured_lot_ocr_mult")
    if lot_ocr is None:
        hold_reasons.append("MISSING_MEASURED_LOT_OCR_MULT")
    elif not _is_finite_number(lot_ocr):
        fail_reasons.append("INVALID_MEASURED_LOT_OCR_MULT")
    else:
        lot_ocr_d = _to_exact_decimal(lot_ocr)
        if lot_ocr_d <= ZERO_DEC:
            fail_reasons.append("INVALID_MEASURED_LOT_OCR_MULT")
        elif lot_ocr_d > Decimal("1.097"):
            fail_reasons.append("MEASURED_LOT_OCR_MULT_EXCEEDS_1P097_FAIL")

    # 6B. Per-Leaf Measured Area/IEQ Reconciliation & Matrix Transport Coverage (Audit F4 / Review #6 / Audit R4-03 / Audit R12-04)
    scale_mode = obs.get("scale_mode")
    valid_scale_mode: Optional[str] = None
    if scale_mode is None:
        hold_reasons.append("MISSING_SCALE_MODE")
    elif not _is_literal_nonempty_str(scale_mode) or scale_mode not in ALLOWED_SCALE_MODES:
        fail_reasons.append("INVALID_SCALE_MODE")
    else:
        valid_scale_mode = scale_mode

    total_ieq_v = obs.get("total_implanted_ieq")
    valid_total_ieq_d: Optional[Decimal] = None
    if total_ieq_v is None:
        hold_reasons.append("MISSING_TOTAL_IMPLANTED_IEQ")
    elif not _is_finite_number(total_ieq_v):
        fail_reasons.append("INVALID_TOTAL_IMPLANTED_IEQ")
    else:
        t_ieq_d = _to_exact_decimal(total_ieq_v)
        if not (ONE_DEC <= t_ieq_d <= Decimal("1e9")):
            fail_reasons.append("INVALID_TOTAL_IMPLANTED_IEQ")
        else:
            valid_total_ieq_d = t_ieq_d

    total_area_v = obs.get("total_loaded_area_cm2")
    valid_total_area_d: Optional[Decimal] = None
    if total_area_v is None:
        hold_reasons.append("MISSING_TOTAL_LOADED_AREA_CM2")
    elif not _is_finite_number(total_area_v):
        fail_reasons.append("INVALID_TOTAL_LOADED_AREA_CM2")
    else:
        t_area_d = _to_exact_decimal(total_area_v)
        if not (Decimal("0.01") <= t_area_d <= Decimal("1e6")):
            fail_reasons.append("INVALID_TOTAL_LOADED_AREA_CM2")
        else:
            valid_total_area_d = t_area_d

    implied_total_loading_ratio: Optional[Tuple[Decimal, Decimal]] = None
    implied_total_loading: Optional[float] = None
    if valid_total_ieq_d is not None and valid_total_area_d is not None:
        implied_total_loading_ratio = (valid_total_ieq_d, valid_total_area_d)
        if loading_domain_ok and loading_d is not None and _ratio_rel_diff_exceeds(
            valid_total_ieq_d, valid_total_area_d, loading_d, Decimal("0.02")
        ):
            fail_reasons.append("IMPLIED_TOTAL_LOADING_CONTRADICTS_REPORTED_LOADING_GT_2PCT_FAIL")
        implied_total_loading = _dec_div_to_display_float(valid_total_ieq_d, valid_total_area_d)
        if implied_total_loading is None or not (implied_total_loading > 0.0):
            fail_reasons.append("INVALID_IMPLIED_TOTAL_LOADING_NONFINITE")

    leaves_raw = obs.get("per_leaf_records")
    leaf_loading_ratios: List[Tuple[Decimal, Decimal]] = []
    leaf_min_beds_d: List[Decimal] = []
    leaf_face_o2s_d: List[Decimal] = []
    leaf_core_o2s_d: List[Decimal] = []
    sum_leaf_ieq_d = ZERO_DEC
    sum_leaf_area_d = ZERO_DEC
    all_leaves_numeric_ok = True
    n_leaves_verified = 0

    if leaves_raw is None:
        hold_reasons.append("MISSING_PER_LEAF_RECORDS")
        all_leaves_numeric_ok = False
    elif not isinstance(leaves_raw, list) or len(leaves_raw) == 0:
        fail_reasons.append("INVALID_OR_EMPTY_PER_LEAF_RECORDS")
        all_leaves_numeric_ok = False
    else:
        if valid_scale_mode == "CLINICAL_HUMAN_SCALE" and len(leaves_raw) < 2:
            fail_reasons.append("CLINICAL_SCALE_REQUIRES_AT_LEAST_2_SEPARATED_LEAVES")
        # Review #6 / Audit R4-03: ANY >100,000 IEQ implant with <2 leaves ALWAYS fails regardless of scale_mode!
        if valid_total_ieq_d is not None and valid_total_ieq_d > SINGLE_LEAF_MAX_TOTAL_IEQ_DEC and len(leaves_raw) < 2:
            fail_reasons.append("TOTAL_IEQ_GT_100K_REQUIRES_AT_LEAST_2_SEPARATED_LEAVES")

        seen_leaf_ids: set[str] = set()
        for l_idx, leaf in enumerate(leaves_raw):
            if not isinstance(leaf, dict):
                fail_reasons.append(f"INVALID_PER_LEAF_RECORD:{l_idx}")
                all_leaves_numeric_ok = False
                continue
            missing_lf = False
            for fkey in REQUIRED_PER_LEAF_FIELDS:
                if leaf.get(fkey) is None:
                    hold_reasons.append(f"MISSING_PER_LEAF_FIELD:{fkey}")
                    missing_lf = True
            if missing_lf:
                all_leaves_numeric_ok = False
                continue

            lid = leaf["leaf_id"]
            if not _is_literal_nonempty_str(lid):
                fail_reasons.append("INVALID_LEAF_ID")
                all_leaves_numeric_ok = False
            elif lid in seen_leaf_ids:
                fail_reasons.append("DUPLICATE_LEAF_ID")
                all_leaves_numeric_ok = False
            else:
                seen_leaf_ids.add(lid)

            l_ieq = leaf["loaded_ieq"]
            l_area = leaf["measured_area_cm2"]
            l_h = leaf["measured_thickness_um"]
            l_d = leaf["measured_d_o2_matrix_m2_s"]
            l_face = leaf["measured_face_o2_mmhg"]
            l_core = leaf["measured_core_o2_mmhg"]
            l_bot = leaf["bed_face_bot_po2_mmhg"]
            l_top = leaf["bed_face_top_po2_mmhg"]
            l_cov = leaf["direct_o2_sensor_coverage_verified"]

            l_ieq_d: Optional[Decimal] = _to_exact_decimal(l_ieq) if _is_finite_number(l_ieq) else None
            l_area_d: Optional[Decimal] = _to_exact_decimal(l_area) if _is_finite_number(l_area) else None
            l_h_d: Optional[Decimal] = _to_exact_decimal(l_h) if _is_finite_number(l_h) else None
            l_d_dec: Optional[Decimal] = _to_exact_decimal(l_d) if _is_finite_number(l_d) else None
            l_face_d: Optional[Decimal] = _to_exact_decimal(l_face) if _is_finite_number(l_face) else None
            l_core_d: Optional[Decimal] = _to_exact_decimal(l_core) if _is_finite_number(l_core) else None
            l_bot_d: Optional[Decimal] = _to_exact_decimal(l_bot) if _is_finite_number(l_bot) else None
            l_top_d: Optional[Decimal] = _to_exact_decimal(l_top) if _is_finite_number(l_top) else None

            leaf_ok = True
            if l_ieq_d is None or not (ONE_DEC <= l_ieq_d <= Decimal("1e9")):
                fail_reasons.append("INVALID_LEAF_LOADED_IEQ")
                leaf_ok = False
            if l_area_d is None or not (Decimal("0.01") <= l_area_d <= Decimal("1e6")):
                fail_reasons.append("INVALID_LEAF_MEASURED_AREA_CM2")
                leaf_ok = False
            if l_h_d is None or not (Decimal("100") <= l_h_d <= Decimal("120")):
                fail_reasons.append("LEAF_MEASURED_THICKNESS_OUTSIDE_100_TO_120UM_FAIL")
                leaf_ok = False
            elif diam_domain_ok and zc_domain_ok and d_max_d is not None and z_c_d is not None:
                l_half_h = _dec_mul(Decimal("0.5"), l_h_d)
                l_outer = _dec_add(z_c_d, _dec_mul(Decimal("0.5"), d_max_d))
                l_wall_clear = _dec_sub(l_half_h, l_outer)
                if l_outer > l_half_h:
                    fail_reasons.append("LEAF_CLUSTER_PROTRUDES_OUTSIDE_SLAB_FAIL")
                elif l_wall_clear < MIN_GY028_WALL_CLEARANCE_UM_DEC:
                    fail_reasons.append("LEAF_GY028_WALL_CLEARANCE_LT_7P5UM_FAIL")

            if l_d_dec is None or l_d_dec <= ZERO_DEC or l_d_dec > D_O2_MAX_AQUEOUS_M2_S_DEC:
                fail_reasons.append("INVALID_LEAF_MEASURED_D_O2_MATRIX_M2_S")
                leaf_ok = False
            elif l_d_dec < D_O2_LOW_MODELED_M2_S_DEC:
                fail_reasons.append("LEAF_MEASURED_D_O2_MATRIX_BELOW_LOW_D_FLOOR_FAIL")
                leaf_ok = False

            if l_bot_d is None or l_bot_d <= ZERO_DEC:
                fail_reasons.append("INVALID_LEAF_BED_FACE_BOT_PO2_MMHG")
                leaf_ok = False
            if l_top_d is None or l_top_d <= ZERO_DEC:
                fail_reasons.append("INVALID_LEAF_BED_FACE_TOP_PO2_MMHG")
                leaf_ok = False

            if l_face_d is None or l_face_d < ZERO_DEC:
                fail_reasons.append("INVALID_LEAF_MEASURED_FACE_O2_MMHG")
                leaf_ok = False
            elif l_face_d < Decimal("15"):
                fail_reasons.append("LEAF_MEASURED_FACE_O2_LT_15MMHG_FAIL")
                leaf_ok = False

            if l_core_d is None or l_core_d < ZERO_DEC:
                fail_reasons.append("INVALID_LEAF_MEASURED_CORE_O2_MMHG")
                leaf_ok = False
            elif l_core_d < Decimal("5"):
                fail_reasons.append("LEAF_MEASURED_CORE_O2_LT_5MMHG_FAIL")
                leaf_ok = False

            if not _is_strict_bool(l_cov):
                fail_reasons.append("INVALID_LEAF_DIRECT_O2_SENSOR_COVERAGE_BOOL")
                leaf_ok = False
            elif not l_cov:
                fail_reasons.append("LEAF_DIRECT_O2_SENSOR_COVERAGE_UNVERIFIED_FAIL")
                leaf_ok = False

            if l_face_d is not None and l_core_d is not None and l_core_d > l_face_d:
                fail_reasons.append("LEAF_CORE_O2_EXCEEDS_FACE_O2_INCONSISTENT")
            if l_face_d is not None and l_bot_d is not None and l_top_d is not None and l_face_d > max(l_bot_d, l_top_d):
                fail_reasons.append("LEAF_FACE_O2_EXCEEDS_LEAF_BED_PO2_INCONSISTENT")

            if l_ieq_d is not None and l_ieq_d > ZERO_DEC and l_area_d is not None and l_area_d > ZERO_DEC:
                sum_leaf_ieq_d = _dec_add(sum_leaf_ieq_d, l_ieq_d)
                sum_leaf_area_d = _dec_add(sum_leaf_area_d, l_area_d)
                leaf_loading_ratios.append((l_ieq_d, l_area_d))
                if loading_domain_ok and loading_d is not None and _ratio_rel_diff_exceeds(
                    l_ieq_d, l_area_d, loading_d, Decimal("0.02")
                ):
                    fail_reasons.append("PER_LEAF_LOADING_CONTRADICTS_REPORTED_LOADING_GT_2PCT_FAIL")
                l_load_disp = _dec_div_to_display_float(l_ieq_d, l_area_d)
                if l_load_disp is None:
                    fail_reasons.append("INVALID_PER_LEAF_LOADING_NONFINITE")
                    leaf_ok = False
            else:
                all_leaves_numeric_ok = False

            if l_bot_d is not None and l_bot_d > ZERO_DEC and l_top_d is not None and l_top_d > ZERO_DEC:
                leaf_min_beds_d.append(min(l_bot_d, l_top_d))
            if l_face_d is not None and l_face_d >= ZERO_DEC:
                leaf_face_o2s_d.append(l_face_d)
            if l_core_d is not None and l_core_d >= ZERO_DEC:
                leaf_core_o2s_d.append(l_core_d)
            if leaf_ok:
                n_leaves_verified += 1
            else:
                all_leaves_numeric_ok = False

        if all_leaves_numeric_ok and len(leaf_loading_ratios) == len(leaves_raw):
            if valid_total_ieq_d is not None and _dec_abs_diff_exceeds(
                sum_leaf_ieq_d, valid_total_ieq_d, _dec_mul(Decimal("0.01"), valid_total_ieq_d)
            ):
                fail_reasons.append("PER_LEAF_IEQ_SUM_DISCREPANCY_GT_1PCT_FAIL")
            if valid_total_area_d is not None and _dec_abs_diff_exceeds(
                sum_leaf_area_d, valid_total_area_d, _dec_mul(Decimal("0.01"), valid_total_area_d)
            ):
                fail_reasons.append("PER_LEAF_AREA_SUM_DISCREPANCY_GT_1PCT_FAIL")

        if leaf_face_o2s_d and face_o2_d is not None and face_o2_d > min(leaf_face_o2s_d):
            fail_reasons.append("REPORTED_WORST_FACE_O2_EXCEEDS_PER_LEAF_MIN_INCONSISTENT")
        if leaf_core_o2s_d and core_o2_d is not None and core_o2_d > min(leaf_core_o2s_d):
            fail_reasons.append("REPORTED_WORST_CORE_O2_EXCEEDS_PER_LEAF_MIN_INCONSISTENT")
        if leaf_min_beds_d and min_bed_po2_d is not None and min_bed_po2_d > min(leaf_min_beds_d):
            fail_reasons.append("REPORTED_BED_PO2_EXCEEDS_PER_LEAF_MIN_INCONSISTENT")

    # 6C. Actual Max-Leaf Steric Packing (Review #6 / Audit R4-03 / Audit R12-04):
    #     Runs AFTER per-leaf reconciliation on EVERY leaf's measured loading AND effective_max_load
    #     using exact polynomial Decimal inequalities (pi cancels: vol_1_ieq / v_cl = (150 / d_rms3)^3).
    computed_pitch_um: Optional[float] = None
    computed_min_dist_um: Optional[float] = None
    effective_max_load: Optional[float] = None
    if (
        loading_domain_ok
        and diam_domain_ok
        and zc_domain_ok
        and loading_d is not None
        and d_rms3_d is not None
        and d_max_d is not None
        and z_c_d is not None
    ):
        packing_load_ratios: List[Tuple[Decimal, Decimal]] = [(loading_d, ONE_DEC)]
        if implied_total_loading_ratio is not None:
            imp_n, imp_d = implied_total_loading_ratio
            if _ratio_ge_dec(imp_n, imp_d, ONE_DEC) and _ratio_le_dec(imp_n, imp_d, Decimal("1e6")):
                packing_load_ratios.append(implied_total_loading_ratio)
            else:
                fail_reasons.append("IMPLIED_TOTAL_LOADING_OUT_OF_PACKING_DOMAIN")
        for l_num, l_den in leaf_loading_ratios:
            if _ratio_ge_dec(l_num, l_den, ONE_DEC) and _ratio_le_dec(l_num, l_den, Decimal("1e6")):
                packing_load_ratios.append((l_num, l_den))
            else:
                fail_reasons.append("PER_LEAF_LOADING_OUT_OF_PACKING_DOMAIN")

        eff_max_num, eff_max_den = _max_ratio(packing_load_ratios)
        d_rms3_cubed = _dec_mul(_dec_mul(d_rms3_d, d_rms3_d), d_rms3_d)
        d_max_sq = _dec_mul(d_max_d, d_max_d)
        zc_sq = _dec_mul(z_c_d, z_c_d)
        pitch_overlap_fail = False
        cross_overlap_fail = False
        for p_num, p_den in packing_load_ratios:
            rhs_bound = _dec_mul(_dec_mul(Decimal("27"), p_num), d_max_sq)
            lhs_pitch = _dec_mul(_dec_mul(Decimal("1600"), p_den), d_rms3_cubed)
            if lhs_pitch <= rhs_bound:
                pitch_overlap_fail = True
            lhs_mind = _dec_add(
                _dec_mul(_dec_mul(Decimal("800"), p_den), d_rms3_cubed),
                _dec_mul(_dec_mul(Decimal("108"), p_num), zc_sq),
            )
            if lhs_mind <= rhs_bound:
                cross_overlap_fail = True
        if pitch_overlap_fail:
            fail_reasons.append("STERIC_SAME_PLANE_PITCH_OVERLAP_FAIL")
        if cross_overlap_fail:
            fail_reasons.append("STERIC_CROSS_PLANE_OVERLAP_FAIL")

        # Display-only float conversion AFTER exact Decimal packing policy decisions
        effective_max_load = _dec_div_to_display_float(eff_max_num, eff_max_den)
        emax_pack = min(MAX_EMAX, max(999_999, abs(eff_max_num.adjusted()) + abs(eff_max_den.adjusted()) + 1000))
        with localcontext(Context(prec=60, Emax=emax_pack, Emin=-emax_pack)):
            worst_pitch_sq = (Decimal("1600") * eff_max_den * d_rms3_cubed) / (Decimal("27") * eff_max_num)
            worst_pitch_d = worst_pitch_sq.sqrt()
            worst_mind_sq = worst_pitch_sq / Decimal("2") + Decimal("4") * zc_sq
            worst_mind_d = worst_mind_sq.sqrt()
        computed_pitch_um = _dec_to_display_float(worst_pitch_d)
        computed_min_dist_um = _dec_to_display_float(worst_mind_d)
        if computed_pitch_um is None or computed_min_dist_um is None:
            fail_reasons.append("UNRESOLVED_OR_NONFINITE_PACKING_METRICS_FAIL")

    # Monotone UNION of Tier-1 (load<=1200, min_bed>=35, fib<=10) OR Tier-2 (load<=1500, min_bed>=40, fib<=12)
    envelope_tier = "UNRESOLVED"
    tier_fibrin_max_d: Decimal = Decimal("10")
    max_leaf_loading: Optional[float] = None
    if leaf_loading_ratios:
        ml_num, ml_den = _max_ratio(leaf_loading_ratios)
        max_leaf_loading = _dec_div_to_display_float(ml_num, ml_den)
    if loading_domain_ok and loading_d is not None and min_bed_po2_d is not None and fibrin_d is not None and fibrin_d >= ZERO_DEC:
        eff_load_ratios: List[Tuple[Decimal, Decimal]] = [(loading_d, ONE_DEC)]
        if implied_total_loading_ratio is not None:
            eff_load_ratios.append(implied_total_loading_ratio)
        eff_load_ratios.extend(leaf_loading_ratios)
        lv_num, lv_den = _max_ratio(eff_load_ratios)
        bv_d = min([min_bed_po2_d] + leaf_min_beds_d)
        fv_d = fibrin_d
        if valid_site == "R4_OMENTUM_LEAD":
            tier1_ok = _ratio_le_dec(lv_num, lv_den, Decimal("1200")) and (bv_d >= Decimal("35")) and (fv_d <= Decimal("10"))
            tier2_ok = _ratio_le_dec(lv_num, lv_den, Decimal("1500")) and (bv_d >= Decimal("40")) and (fv_d <= Decimal("12"))
            tier_fibrin_max_d = Decimal("12") if (bv_d >= Decimal("40") and _ratio_le_dec(lv_num, lv_den, Decimal("1500"))) else Decimal("10")
            if tier1_ok and tier2_ok:
                envelope_tier = "R4O_TIER1_AND_TIER2_UNION"
            elif tier1_ok:
                envelope_tier = "R4O_TIER1_PRIMARY_LE1200"
            elif tier2_ok:
                envelope_tier = "R4O_TIER2_HIGH_PERFUSION_GATED_LE1500"
            else:
                added_tier_fail = False
                if _ratio_gt_dec(lv_num, lv_den, Decimal("1500")):
                    fail_reasons.append("AREAL_LOADING_EXCEEDS_OMENTUM_ENVELOPE_CAP_1500_IEQ_CM2")
                    added_tier_fail = True
                if bv_d < Decimal("35"):
                    fail_reasons.append("MIN_BILATERAL_BED_PO2_BELOW_35MMHG_ENVELOPE_FLOOR")
                    added_tier_fail = True
                if fv_d > Decimal("12"):
                    fail_reasons.append("FIBRIN_CAPSULE_EXCEEDS_12UM_MAX_ENVELOPE_CEILING")
                    added_tier_fail = True
                if _ratio_gt_dec(lv_num, lv_den, Decimal("1200")) and _ratio_le_dec(lv_num, lv_den, Decimal("1500")) and bv_d < Decimal("40"):
                    fail_reasons.append("TIER2_LOADING_GT_1200_REQUIRES_MIN_BILATERAL_BED_PO2_GE_40MMHG")
                    added_tier_fail = True
                if _ratio_le_dec(lv_num, lv_den, Decimal("1200")) and Decimal("35") <= bv_d < Decimal("40") and Decimal("10") < fv_d <= Decimal("12"):
                    fail_reasons.append("TIER1_FIBRIN_CAPSULE_EXCEEDS_10UM_CEILING_AT_BED_LT_40MMHG")
                    added_tier_fail = True
                if _ratio_gt_dec(lv_num, lv_den, loading_d):
                    fail_reasons.append("IMPLIED_OR_LEAF_LOADING_EXCEEDS_ACTIVE_TIER_CEILING_FAIL")
                    added_tier_fail = True
                if leaf_min_beds_d and min(leaf_min_beds_d) < (Decimal("40") if (_ratio_gt_dec(lv_num, lv_den, Decimal("1200")) or fv_d > Decimal("10")) else Decimal("35")):
                    fail_reasons.append("LEAF_BED_PO2_BELOW_ACTIVE_TIER_FLOOR_FAIL")
                    added_tier_fail = True
                if not added_tier_fail:
                    fail_reasons.append("OUTSIDE_R4O_TIER1_OR_TIER2_UNION_ENVELOPE")
        elif valid_site == "R4_SARS_FREE_BACKUP":
            envelope_tier = "R4S_BACKUP_LE1200"
            tier_fibrin_max_d = Decimal("10")
            if _ratio_gt_dec(lv_num, lv_den, Decimal("1200")):
                fail_reasons.append("SARS_BACKUP_LOADING_EXCEEDS_1200_IEQ_CM2_ENVELOPE_CAP")
                if _ratio_gt_dec(lv_num, lv_den, loading_d):
                    fail_reasons.append("IMPLIED_OR_LEAF_LOADING_EXCEEDS_ACTIVE_TIER_CEILING_FAIL")
            if bv_d < Decimal("35"):
                fail_reasons.append("SARS_BACKUP_MIN_BILATERAL_BED_PO2_BELOW_35MMHG_FAIL")
                if leaf_min_beds_d and min(leaf_min_beds_d) < Decimal("35"):
                    fail_reasons.append("LEAF_BED_PO2_BELOW_ACTIVE_TIER_FLOOR_FAIL")
            if fv_d > Decimal("10"):
                fail_reasons.append("SARS_BACKUP_FIBRIN_CAPSULE_EXCEEDS_10UM_CEILING")

    r_clean_t50 = obs.get("route_specific_clean_t50_min")
    if r_clean_t50 is None:
        hold_reasons.append("MISSING_ROUTE_SPECIFIC_CLEAN_T50_MIN")
    elif not _is_finite_number(r_clean_t50):
        fail_reasons.append("R4O_03_CLEAN_T50_GE_2P60MIN_FAIL")
    else:
        r_clean_t50_d = _to_exact_decimal(r_clean_t50)
        if r_clean_t50_d <= ZERO_DEC or r_clean_t50_d >= Decimal("2.60"):
            fail_reasons.append("R4O_03_CLEAN_T50_GE_2P60MIN_FAIL")

    r_fib_t50 = obs.get("route_specific_fibrin_t50_min")
    if r_fib_t50 is None:
        hold_reasons.append("MISSING_ROUTE_SPECIFIC_FIBRIN_T50_MIN")
    elif not _is_finite_number(r_fib_t50):
        fail_reasons.append("R4O_03_FIBRIN_T50_GE_3P00MIN_FAIL")
    else:
        r_fib_t50_d = _to_exact_decimal(r_fib_t50)
        if r_fib_t50_d <= ZERO_DEC or r_fib_t50_d >= Decimal("3.00"):
            fail_reasons.append("R4O_03_FIBRIN_T50_GE_3P00MIN_FAIL")

    r_gsis = obs.get("route_specific_gsis_si")
    if r_gsis is None:
        hold_reasons.append("MISSING_ROUTE_SPECIFIC_GSIS_SI")
    elif not _is_finite_number(r_gsis) or _to_exact_decimal(r_gsis) < Decimal("3"):
        fail_reasons.append("R4O_03_GSIS_SI_LT_3P0_FAIL")

    # 7. Subject-Level Stage-1 Endpoints (Porcine R4O-04 + Primary DEC-009 0-NHP Primate-Free Pathway
    #    or Conditional FDA CBER Exception NHP Cohort with Decoupled Paired C-Peptide Extinction vs II)
    large_animal_pathway: Optional[str] = None
    derived_porcine_n: Optional[int] = None
    derived_porcine_eligible_visit_n: Optional[int] = None
    derived_porcine_zero_complications: Optional[bool] = None
    derived_nhp_n: Optional[int] = None
    derived_nhp_eligible_visit_n: Optional[int] = None
    derived_nhp_zero_complications: Optional[bool] = None
    derived_nhp_eligible_diabetic_n: Optional[int] = None
    derived_nhp_ii: Optional[int] = None
    derived_nhp_cpeptide_extinction_verified_count: Optional[int] = None

    if is_promo:
        if valid_site == "R4_OMENTUM_LEAD":
            p_safe = obs.get("porcine_r4o04_zero_bowel_obstruction_torsion_grade3_adhesions")
            if p_safe is None:
                hold_reasons.append("MISSING_STAGE1_PORCINE_R4O04_SURGICAL_SAFETY")
            elif not _is_strict_bool(p_safe):
                fail_reasons.append("INVALID_PORCINE_SAFETY_BOOL")
            elif not p_safe:
                fail_reasons.append("R4O_04_PORCINE_SURGICAL_COMPLICATION_FAIL")

            p_subjs = obs.get("porcine_subjects")
            if p_subjs is None:
                hold_reasons.append("MISSING_STAGE1_PORCINE_SUBJECTS")
            elif not isinstance(p_subjs, list):
                fail_reasons.append("INVALID_PORCINE_SUBJECTS_ARRAY")
            else:
                derived_porcine_n = len(p_subjs)
                if derived_porcine_n < 6:
                    fail_reasons.append("R4O_04_PORCINE_N_LT_6_FAIL")
                seen_p_ids: set[str] = set()
                p_visit_eligible_count = 0
                p_missing_date_evidence = False
                p_any_complication = False
                p_all_complications_resolved = (derived_porcine_n > 0)
                for idx, s in enumerate(p_subjs):
                    if not isinstance(s, dict):
                        fail_reasons.append(f"INVALID_PORCINE_SUBJECT_RECORD:{idx}")
                        p_all_complications_resolved = False
                        continue

                    for fkey in REQUIRED_PORCINE_SUBJECT_FIELDS:
                        if s.get(fkey) is None and fkey not in (
                            "bowel_obstruction_event",
                            "omental_torsion_event",
                            "grade3_adhesion_event",
                            "monitored_complications",
                        ):
                            hold_reasons.append(f"MISSING_PORCINE_SUBJECT_FIELD:{fkey}")

                    sid = s.get("subject_id")
                    p_sid_adverse = False
                    if sid is not None:
                        if not isinstance(sid, str) or len(sid.strip()) == 0:
                            fail_reasons.append("INVALID_PORCINE_SUBJECT_ID")
                            p_sid_adverse = True
                        else:
                            if not _is_canonical_id_str(sid):
                                fail_reasons.append("INVALID_PORCINE_SUBJECT_ID")
                                p_sid_adverse = True
                            sid_canon = _canonical_id_dedup_key(sid)
                            if sid_canon in seen_p_ids:
                                fail_reasons.append("DUPLICATE_PORCINE_SUBJECT_ID")
                                p_sid_adverse = True
                            else:
                                seen_p_ids.add(sid_canon)

                    sp = s.get("species")
                    if sp is not None and (not _is_literal_nonempty_str(sp) or sp != "PORCINE"):
                        fail_reasons.append("R4O_04_PORCINE_SUBJECT_WRONG_SPECIES_FAIL")

                    lot_v = s.get("lot_id")
                    if lot_v is not None and (not _is_literal_nonempty_str(lot_v) or (valid_lot_id is not None and lot_v != valid_lot_id)):
                        fail_reasons.append("R4O_04_PORCINE_SUBJECT_LOT_ID_MISMATCH")

                    # Subject-level measurement dates (Audit R5-04 / R8-05): exact Decimal followup >= 60, capsule & retrieval in [60, followup] (ZERO ungoverned tolerance)
                    p_fu = s.get("followup_duration_days")
                    p_fu_val: Optional[Decimal] = None
                    p_fu_ok = False
                    if p_fu is None:
                        p_missing_date_evidence = True
                    elif not _is_finite_number(p_fu) or _to_exact_decimal(p_fu) <= Decimal("0"):
                        fail_reasons.append("INVALID_PORCINE_FOLLOWUP_DURATION_DAYS")
                    else:
                        p_fu_val = _to_exact_decimal(p_fu)
                        if p_fu_val < PORCINE_MIN_FOLLOWUP_DAYS_DEC:
                            fail_reasons.append("R4O_04_PORCINE_FOLLOWUP_LT_60D_FAIL")
                        else:
                            p_fu_ok = True

                    p_cap_d = s.get("capsule_sampling_day")
                    p_cap_d_val: Optional[Decimal] = None
                    p_cap_d_ok = False
                    if p_cap_d is None:
                        p_missing_date_evidence = True
                    elif not _is_finite_number(p_cap_d) or _to_exact_decimal(p_cap_d) <= Decimal("0"):
                        fail_reasons.append("INVALID_PORCINE_CAPSULE_SAMPLING_DAY")
                    else:
                        p_cap_d_val = _to_exact_decimal(p_cap_d)
                        cap_ok_local = True
                        if p_cap_d_val < PORCINE_MIN_FOLLOWUP_DAYS_DEC:
                            fail_reasons.append("R4O_04_PORCINE_CAPSULE_SAMPLING_DAY_LT_60D_FAIL")
                            cap_ok_local = False
                        if p_fu_val is not None and p_cap_d_val > p_fu_val:
                            fail_reasons.append("R4O_04_PORCINE_CAPSULE_SAMPLING_DAY_EXCEEDS_FOLLOWUP_FAIL")
                            cap_ok_local = False
                        p_cap_d_ok = cap_ok_local

                    p_ret_d = s.get("retrieval_assessment_day")
                    p_ret_d_val: Optional[Decimal] = None
                    p_ret_d_ok = False
                    if p_ret_d is None:
                        p_missing_date_evidence = True
                    elif not _is_finite_number(p_ret_d) or _to_exact_decimal(p_ret_d) <= Decimal("0"):
                        fail_reasons.append("INVALID_PORCINE_RETRIEVAL_ASSESSMENT_DAY")
                    else:
                        p_ret_d_val = _to_exact_decimal(p_ret_d)
                        ret_ok_local = True
                        if p_ret_d_val < PORCINE_MIN_FOLLOWUP_DAYS_DEC:
                            fail_reasons.append("R4O_04_PORCINE_RETRIEVAL_ASSESSMENT_DAY_LT_60D_FAIL")
                            ret_ok_local = False
                        if p_fu_val is not None and p_ret_d_val > p_fu_val:
                            fail_reasons.append("R4O_04_PORCINE_RETRIEVAL_ASSESSMENT_DAY_EXCEEDS_FOLLOWUP_FAIL")
                            ret_ok_local = False
                        p_ret_d_ok = ret_ok_local

                    p_date_alias_adverse = _check_subject_date_aliases(
                        s,
                        gate_tag="R4O_04",
                        species_tag="PORCINE",
                        min_days=PORCINE_MIN_FOLLOWUP_DAYS_DEC,
                        min_days_tag="60D",
                        followup_val=p_fu_val,
                        capsule_day_val=p_cap_d_val,
                        retrieval_day_val=p_ret_d_val,
                        omentectomy_day_val=None,
                        cpep_day_val=None,
                        portal_day_val=None,
                        fail_reasons=fail_reasons,
                    )

                    if (not p_sid_adverse) and p_fu_ok and p_cap_d_ok and p_ret_d_ok and not p_date_alias_adverse:
                        p_visit_eligible_count += 1

                    p_comp_resolved, p_comp_adverse = _check_subject_typed_complications_and_aliases(
                        s,
                        gate_tag="R4O_04",
                        species_tag="PORCINE",
                        fail_reasons=fail_reasons,
                        hold_reasons=hold_reasons,
                    )
                    if p_comp_adverse:
                        p_any_complication = True
                    if not p_comp_resolved:
                        p_all_complications_resolved = False

                    surv_v = s.get("survival_to_endpoint")
                    if surv_v is not None and (not _is_strict_bool(surv_v) or not surv_v):
                        fail_reasons.append("R4O_04_PORCINE_SURVIVAL_TO_ENDPOINT_FAILED")
                    hem_v = s.get("major_hemorrhage_or_dehiscence")
                    if hem_v is not None and (not _is_strict_bool(hem_v) or hem_v):
                        fail_reasons.append("R4O_04_PORCINE_MAJOR_HEMORRHAGE_OR_DEHISCENCE_FAIL")
                    ssafe_v = s.get("surgical_safety_pass")
                    if ssafe_v is not None and (not _is_strict_bool(ssafe_v) or not ssafe_v):
                        fail_reasons.append("R4O_04_PORCINE_SUBJECT_SURGICAL_SAFETY_FAILED")
                    pcap_v = s.get("month3_capsule_um")
                    if pcap_v is not None:
                        if not _is_finite_number(pcap_v):
                            fail_reasons.append("INVALID_PORCINE_MONTH3_CAPSULE_UM")
                        else:
                            pcap_d = _to_exact_decimal(pcap_v)
                            if pcap_d < ZERO_DEC:
                                fail_reasons.append("INVALID_PORCINE_MONTH3_CAPSULE_UM")
                            elif pcap_d > tier_fibrin_max_d:
                                fail_reasons.append("R4O_04_PORCINE_MONTH3_CAPSULE_EXCEEDS_TIER_MAX_FAIL")
                    ploc_v = s.get("localization_verified")
                    if ploc_v is not None and (not _is_strict_bool(ploc_v) or not ploc_v):
                        fail_reasons.append("R4O_04_RESIDUAL_LOCALIZATION_FAILED")
                    _check_retrieval_residual_reconciliation(
                        prefix="PORCINE",
                        retrieval_mass_pct=s.get("retrieval_mass_pct"),
                        total_implanted_cells=s.get("total_implanted_cells"),
                        residual_viable_cells_measured=s.get("residual_viable_cells_measured"),
                        residual_sampling_fraction=s.get("residual_sampling_fraction"),
                        require_ge_99p9=True,
                        fail_reasons=fail_reasons,
                    )

                derived_porcine_eligible_visit_n = p_visit_eligible_count
                if derived_porcine_n >= 6 and not p_missing_date_evidence and p_visit_eligible_count < 6:
                    fail_reasons.append("R4O_04_PORCINE_VISIT_ELIGIBLE_N_LT_6_FAIL")

                if p_any_complication:
                    derived_porcine_zero_complications = False
                elif p_all_complications_resolved:
                    derived_porcine_zero_complications = True
                else:
                    derived_porcine_zero_complications = None

                if p_safe is True and derived_porcine_zero_complications is False:
                    fail_reasons.append("PORCINE_COMPLICATION_CONTRADICTS_AGGREGATE_ATTESTATION")

        dec009_pf = obs.get("dec009_primate_free_pathway")
        if dec009_pf is not None and not _is_strict_bool(dec009_pf):
            fail_reasons.append("INVALID_DEC009_PRIMATE_FREE_PATHWAY_BOOL")
        use_dec009_primate_free = (dec009_pf is True)

        dec009_nhp_exc = obs.get("dec009_fda_cber_nhp_exception_authorized")
        if dec009_nhp_exc is not None and not _is_strict_bool(dec009_nhp_exc):
            fail_reasons.append("INVALID_DEC009_FDA_CBER_NHP_EXCEPTION_BOOL")

        n_subjs = obs.get("nhp_subjects")
        if use_dec009_primate_free:
            large_animal_pathway = "DEC009_0_NHP_PRIMATE_FREE_PRIMARY"
            for p_key, miss_code, fail_code in (
                ("dec009_pillar1_humanized_mouse_efficacy_pass", "MISSING_DEC009_PILLAR1_HUMANIZED_MOUSE_EVIDENCE", "DEC009_PILLAR1_HUMANIZED_MOUSE_FAILED"),
                ("dec009_pillar2_chandler_loop_50donor_pass", "MISSING_DEC009_PILLAR2_CHANDLER_LOOP_EVIDENCE", "DEC009_PILLAR2_CHANDLER_LOOP_FAILED"),
                ("dec009_pillar1_glp_biodistribution_erasure_pass", "MISSING_DEC009_PILLAR1_GLP_ERASURE_EVIDENCE", "DEC009_PILLAR1_GLP_ERASURE_FAILED"),
            ):
                pv = obs.get(p_key)
                if pv is None:
                    hold_reasons.append(miss_code)
                elif not _is_strict_bool(pv) or not pv:
                    fail_reasons.append(fail_code)
            if n_subjs is not None and dec009_nhp_exc is not True:
                fail_reasons.append("DEC009_PRIMATE_FREE_PATHWAY_CONTRADICTS_NHP_COHORT_WITHOUT_FDA_EXCEPTION")
        else:
            large_animal_pathway = "DEC009_FDA_CBER_EXCEPTION_NHP_COHORT"
            if dec009_nhp_exc is False:
                fail_reasons.append("DEC009_UNAUTHORIZED_NHP_COHORT_REJECTED")
            elif dec009_nhp_exc is None and n_subjs is not None:
                hold_reasons.append("MISSING_DEC009_FDA_CBER_NHP_EXCEPTION_AUTHORIZATION")
            if n_subjs is None:
                hold_reasons.append("MISSING_STAGE1_NHP_SUBJECTS")

        if n_subjs is not None and not isinstance(n_subjs, list):
            fail_reasons.append("INVALID_NHP_SUBJECTS_ARRAY")
        elif isinstance(n_subjs, list):
            derived_nhp_n = len(n_subjs)
            if derived_nhp_n < 4:
                fail_reasons.append("R4O_05_NHP_N_LT_4_FAIL")
            seen_n_ids: set[str] = set()
            seen_n_proc_ids: set[str] = set()
            eligible_diabetic_count = 0
            pending_diabetic_eligibility_count = 0
            qual_count = 0
            cpep_extinction_verified_count = 0
            pending_responder_qual_count = 0
            n_visit_eligible_count = 0
            n_any_complication = False
            n_all_complications_resolved = (derived_nhp_n > 0)
            for idx, s in enumerate(n_subjs):
                if not isinstance(s, dict):
                    fail_reasons.append(f"INVALID_NHP_SUBJECT_RECORD:{idx}")
                    n_all_complications_resolved = False
                    continue

                for fkey in REQUIRED_NHP_SUBJECT_FIELDS:
                    if s.get(fkey) is None and fkey not in (
                        "bowel_obstruction_event",
                        "omental_torsion_event",
                        "grade3_adhesion_event",
                        "monitored_complications",
                    ):
                        hold_reasons.append(f"MISSING_NHP_SUBJECT_FIELD:{fkey}")

                sid = s.get("subject_id")
                sid_ok = False
                sid_adverse = False
                if sid is not None:
                    if not isinstance(sid, str) or len(sid.strip()) == 0:
                        fail_reasons.append("INVALID_NHP_SUBJECT_ID")
                        sid_adverse = True
                    else:
                        sid_malformed = not _is_canonical_id_str(sid)
                        if sid_malformed:
                            fail_reasons.append("INVALID_NHP_SUBJECT_ID")
                            sid_adverse = True
                        sid_canon = _canonical_id_dedup_key(sid)
                        if sid_canon in seen_n_ids:
                            fail_reasons.append("DUPLICATE_NHP_SUBJECT_ID")
                            sid_adverse = True
                        else:
                            seen_n_ids.add(sid_canon)
                            if not sid_malformed:
                                sid_ok = True

                sp = s.get("species")
                sp_ok = False
                if sp is not None:
                    sp_ok = _is_literal_nonempty_str(sp) and sp == "NHP"
                    if not sp_ok:
                        fail_reasons.append("R4O_05_NHP_SUBJECT_WRONG_SPECIES_FAIL")

                lot_v = s.get("lot_id")
                lot_ok = False
                if lot_v is not None:
                    lot_ok = _is_literal_nonempty_str(lot_v) and (valid_lot_id is not None and lot_v == valid_lot_id)
                    if not lot_ok:
                        fail_reasons.append("R4O_05_NHP_SUBJECT_LOT_ID_MISMATCH")

                pre_diab = s.get("preimplant_diabetic_verified")
                base_ins = s.get("baseline_exogenous_insulin_u_kg_d")
                base_cpep = s.get("baseline_fasting_c_peptide_ng_ml")
                dose_v = s.get("dose_ieq_per_kg")
                achieved_ii = s.get("achieved_insulin_independence")
                followup_d = s.get("followup_duration_days")
                cap_d = s.get("capsule_sampling_day")
                om_perf = s.get("omentectomy_performed")
                om_proc_id = s.get("omentectomy_procedure_id")
                om_d = s.get("omentectomy_day")
                ext_sid = s.get("cpeptide_extinction_subject_id")
                ext_pid = s.get("cpeptide_extinction_procedure_id")
                cpep_d = s.get("cpeptide_extinction_assessment_day")
                ext_out = s.get("post_omentectomy_cpeptide_extinguished")
                port_d = s.get("portal_gradient_assessment_day")
                day_v = s.get("insulin_indep_day")
                cap_v = s.get("month3_capsule_um")
                ins_v = s.get("residual_exogenous_insulin_u_kg_d")
                gsis_v = s.get("paired_dynamic_gsis_pass")
                retr_v = s.get("retrieval_mass_pct")
                tot_cells_v = s.get("total_implanted_cells")
                res_cells_v = s.get("residual_viable_cells_measured")
                samp_frac_v = s.get("residual_sampling_fraction")
                loc_v = s.get("localization_verified")

                elig_types_ok = True
                base_ins_d: Optional[Decimal] = None
                base_cpep_d: Optional[Decimal] = None
                dose_d: Optional[Decimal] = None
                if pre_diab is not None and not _is_strict_bool(pre_diab):
                    fail_reasons.append("INVALID_NHP_PREIMPLANT_DIABETIC_BOOL")
                    elig_types_ok = False
                if base_ins is not None:
                    if not _is_finite_number(base_ins) or _to_exact_decimal(base_ins) < ZERO_DEC:
                        fail_reasons.append("INVALID_NHP_BASELINE_EXOGENOUS_INSULIN")
                        elig_types_ok = False
                    else:
                        base_ins_d = _to_exact_decimal(base_ins)
                if base_cpep is not None:
                    if not _is_finite_number(base_cpep) or _to_exact_decimal(base_cpep) < ZERO_DEC:
                        fail_reasons.append("INVALID_NHP_BASELINE_FASTING_C_PEPTIDE")
                        elig_types_ok = False
                    else:
                        base_cpep_d = _to_exact_decimal(base_cpep)

                types_ok = elig_types_ok and (not sid_adverse)
                if dose_v is not None:
                    if not _is_finite_number(dose_v) or _to_exact_decimal(dose_v) <= ZERO_DEC:
                        fail_reasons.append("INVALID_NHP_SUBJECT_DOSE_IEQ_PER_KG")
                        types_ok = False
                    else:
                        dose_d = _to_exact_decimal(dose_v)
                if achieved_ii is not None and not _is_strict_bool(achieved_ii):
                    fail_reasons.append("INVALID_NHP_ACHIEVED_INSULIN_INDEPENDENCE_BOOL")
                    types_ok = False

                fu_val: Optional[Decimal] = None
                if followup_d is not None:
                    if not _is_finite_number(followup_d) or _to_exact_decimal(followup_d) <= Decimal("0"):
                        fail_reasons.append("INVALID_NHP_FOLLOWUP_DURATION_DAYS")
                        types_ok = False
                    else:
                        fu_val = _to_exact_decimal(followup_d)

                cap_d_val: Optional[Decimal] = None
                nhp_cap_day_ok = False
                if cap_d is not None:
                    if not _is_finite_number(cap_d) or _to_exact_decimal(cap_d) <= Decimal("0"):
                        fail_reasons.append("INVALID_NHP_CAPSULE_SAMPLING_DAY")
                        types_ok = False
                    else:
                        cap_d_val = _to_exact_decimal(cap_d)
                        cap_d_local = True
                        if cap_d_val < NHP_MIN_FOLLOWUP_DAYS_DEC:
                            fail_reasons.append("R4O_05_NHP_CAPSULE_SAMPLING_DAY_LT_90D_FAIL")
                            cap_d_local = False
                            types_ok = False
                        if fu_val is not None and cap_d_val > fu_val:
                            fail_reasons.append("R4O_05_NHP_CAPSULE_SAMPLING_DAY_EXCEEDS_FOLLOWUP_FAIL")
                            cap_d_local = False
                            types_ok = False
                        nhp_cap_day_ok = cap_d_local

                # Round-7 Audit R6-05 + Round-8 Audit R7-08 / R7-13 + Round-9 Audit R8-04 / R8-05:
                # Require one complete, internally consistent procedure/extinction tuple — INCLUDING an explicit
                # non-None boolean post_omentectomy_cpeptide_extinguished in the verified archived row — whenever
                # achieved_insulin_independence is True OR ANY procedure/extinction field/alias is supplied,
                # enforce exact decimal.Decimal 0 <= (cpeptide_extinction_assessment_day - omentectomy_day) <= 14
                # (ZERO ungoverned tolerance), and reject any intra-group alias conflict across all performed,
                # outcome, ID, and date groups.
                is_responder = (achieved_ii is True)
                nhp_binding_alias_adverse = False

                perf_bools: List[Tuple[str, bool]] = []
                if om_perf is not None and _is_strict_bool(om_perf):
                    perf_bools.append(("omentectomy_performed", om_perf))
                for akey in NHP_OMENTECTOMY_PERFORMED_ALIAS_KEYS:
                    if akey in s and s[akey] is not None:
                        aval = s[akey]
                        if not _is_strict_bool(aval):
                            fail_reasons.append(f"INVALID_NHP_OMENTECTOMY_PERFORMED_ALIAS:{akey}")
                            nhp_binding_alias_adverse = True
                        else:
                            perf_bools.append((akey, aval))
                if len({v for _, v in perf_bools}) > 1:
                    fail_reasons.append("NHP_CONFLICTING_OMENTECTOMY_PERFORMED_ALIAS_GROUP")
                    nhp_binding_alias_adverse = True
                any_performed_true = any(v is True for _, v in perf_bools)
                any_performed_false = any(v is False for _, v in perf_bools)

                ext_outcome_bools: List[Tuple[str, bool]] = []
                any_noncanonical_ext_outcome_present = False
                for akey in NHP_EXTINCTION_OUTCOME_BOOL_ALIAS_KEYS:
                    if akey in s and s[akey] is not None:
                        if akey != "post_omentectomy_cpeptide_extinguished":
                            any_noncanonical_ext_outcome_present = True
                        aval = s[akey]
                        if not _is_strict_bool(aval):
                            fail_reasons.append(f"INVALID_NHP_EXTINCTION_BOOL_ALIAS:{akey}")
                            nhp_binding_alias_adverse = True
                        else:
                            ext_outcome_bools.append((akey, aval))
                if len({v for _, v in ext_outcome_bools}) > 1:
                    fail_reasons.append("NHP_CONFLICTING_EXTINCTION_OUTCOME_ALIAS_GROUP")
                    nhp_binding_alias_adverse = True
                any_ext_outcome_true = any(v is True for _, v in ext_outcome_bools)
                any_ext_outcome_false = any(v is False for _, v in ext_outcome_bools)
                if is_responder and any_ext_outcome_false:
                    fail_reasons.append("R4O_05_NHP_RESPONDER_POST_OMENTECTOMY_CPEP_NOT_EXTINGUISHED_FAIL")
                    nhp_binding_alias_adverse = True
                # Round-14 Review fix: Decouple post-explant C-peptide extinction from full insulin independence.
                # Partial responders on residual exogenous insulin (achieved_insulin_independence == False) CAN
                # legitimately produce graft-derived stimulated C-peptide that extinguishes post-omentectomy,
                # verified independently via paired pre/post stimulated C-peptide against prespecified LLOQ
                # without inflating full insulin-independent responder counts (derived_nhp_qualified_ii_count).

                any_proc_date_present = (om_d is not None) or any(s.get(k) is not None for k in NHP_OMENTECTOMY_PROCEDURE_DATE_ALIAS_KEYS)
                any_proc_id_present = (om_proc_id is not None) or any(s.get(k) is not None for k in NHP_PROCEDURE_ID_ALIAS_KEYS)
                any_ext_sid_present = (ext_sid is not None) or any(s.get(k) is not None for k in NHP_EXTINCTION_SUBJECT_ID_ALIAS_KEYS)
                any_ext_pid_present = (ext_pid is not None) or any(s.get(k) is not None for k in NHP_EXTINCTION_PROCEDURE_ID_ALIAS_KEYS)
                any_ext_date_present = (cpep_d is not None) or any(s.get(k) is not None for k in NHP_CPEP_EXTINCTION_DATE_ALIAS_KEYS)
                any_proc_or_ext_evidence = (
                    any_performed_true
                    or any_proc_date_present
                    or any_proc_id_present
                    or any_ext_sid_present
                    or any_ext_pid_present
                    or any_ext_date_present
                    or any_ext_outcome_true
                )
                require_proc_ext_tuple = is_responder or any_proc_or_ext_evidence

                # Round-9 Audit R8-04 + Round-14 Review decoupled paired C-peptide extinction & LLOQ verification:
                # Require explicit non-None boolean post_omentectomy_cpeptide_extinguished whenever ANY
                # procedure/extinction claim is present (or responder) or any non-canonical outcome alias is set;
                # whenever extinction is claimed (True, whether full or partial responder), require paired
                # pre/post stimulated C-peptide and prespecified LLOQ with exact Decimal pre > LLOQ and post <= LLOQ.
                ext_outcome_ok = True
                if ext_out is None:
                    if require_proc_ext_tuple or any_noncanonical_ext_outcome_present:
                        hold_reasons.append("MISSING_NHP_POST_OMENTECTOMY_EXTINCTION_OUTCOME")
                        hold_reasons.append("NHP_INCOMPLETE_PROCEDURE_OR_EXTINCTION_TUPLE")
                        ext_outcome_ok = False
                elif not _is_strict_bool(ext_out):
                    ext_outcome_ok = False
                    types_ok = False
                elif is_responder and ext_out is not True:
                    ext_outcome_ok = False
                    types_ok = False

                lloq_v = s.get("lloq_c_peptide_ng_ml")
                pre_cpep_v = s.get("pre_explant_stimulated_c_peptide_ng_ml")
                post_cpep_v = s.get("post_explant_stimulated_c_peptide_ng_ml")
                lloq_d: Optional[Decimal] = None
                pre_cpep_d: Optional[Decimal] = None
                post_cpep_d: Optional[Decimal] = None
                paired_cpep_ok = True
                if lloq_v is not None:
                    if not _is_finite_number(lloq_v) or _to_exact_decimal(lloq_v) <= ZERO_DEC:
                        fail_reasons.append("INVALID_NHP_LLOQ_CPEPTIDE_NG_ML")
                        paired_cpep_ok = False
                        types_ok = False
                    else:
                        lloq_d = _to_exact_decimal(lloq_v)
                if pre_cpep_v is not None:
                    if not _is_finite_number(pre_cpep_v) or _to_exact_decimal(pre_cpep_v) < ZERO_DEC:
                        fail_reasons.append("INVALID_NHP_PRE_EXPLANT_STIMULATED_CPEPTIDE")
                        paired_cpep_ok = False
                        types_ok = False
                    else:
                        pre_cpep_d = _to_exact_decimal(pre_cpep_v)
                if post_cpep_v is not None:
                    if not _is_finite_number(post_cpep_v) or _to_exact_decimal(post_cpep_v) < ZERO_DEC:
                        fail_reasons.append("INVALID_NHP_POST_EXPLANT_STIMULATED_CPEPTIDE")
                        paired_cpep_ok = False
                        types_ok = False
                    else:
                        post_cpep_d = _to_exact_decimal(post_cpep_v)
                if (ext_out is True) or any_ext_outcome_true:
                    if lloq_v is None or pre_cpep_v is None or post_cpep_v is None:
                        hold_reasons.append("MISSING_NHP_PAIRED_STIMULATED_CPEPTIDE_OR_LLOQ")
                        hold_reasons.append("NHP_INCOMPLETE_PROCEDURE_OR_EXTINCTION_TUPLE")
                        paired_cpep_ok = False
                    elif lloq_d is not None and pre_cpep_d is not None and post_cpep_d is not None:
                        if pre_cpep_d <= lloq_d:
                            fail_reasons.append("R4O_05_NHP_PRE_EXPLANT_CPEPTIDE_NOT_ABOVE_LLOQ_FAIL")
                            paired_cpep_ok = False
                            types_ok = False
                        if post_cpep_d > lloq_d:
                            fail_reasons.append("R4O_05_NHP_POST_EXPLANT_CPEPTIDE_EXCEEDS_LLOQ_FAIL")
                            paired_cpep_ok = False
                            types_ok = False

                om_perf_ok = True
                if om_perf is None:
                    if require_proc_ext_tuple:
                        hold_reasons.append(
                            "MISSING_NHP_RESPONDER_OMENTECTOMY_PERFORMED"
                            if is_responder
                            else "MISSING_NHP_OMENTECTOMY_PERFORMED"
                        )
                        hold_reasons.append("NHP_INCOMPLETE_PROCEDURE_OR_EXTINCTION_TUPLE")
                        om_perf_ok = False
                elif not _is_strict_bool(om_perf):
                    fail_reasons.append("INVALID_NHP_OMENTECTOMY_PERFORMED_BOOL")
                    om_perf_ok = False
                    types_ok = False
                elif om_perf is False:
                    if is_responder:
                        fail_reasons.append("R4O_05_NHP_RESPONDER_OMENTECTOMY_NOT_PERFORMED_FAIL")
                        om_perf_ok = False
                        types_ok = False
                    elif any_proc_or_ext_evidence:
                        fail_reasons.append("R4O_05_NHP_OMENTECTOMY_PERFORMED_FALSE_CONTRADICTS_PROCEDURE_DATA_FAIL")
                        om_perf_ok = False
                        types_ok = False
                if any_performed_false and om_perf is not False:
                    if is_responder:
                        fail_reasons.append("R4O_05_NHP_RESPONDER_OMENTECTOMY_NOT_PERFORMED_FAIL")
                        om_perf_ok = False
                        types_ok = False
                    elif any_proc_or_ext_evidence:
                        fail_reasons.append("R4O_05_NHP_OMENTECTOMY_PERFORMED_FALSE_CONTRADICTS_PROCEDURE_DATA_FAIL")
                        om_perf_ok = False
                        types_ok = False

                om_proc_id_ok = True
                row_proc_dedup_added: Optional[str] = None
                if om_proc_id is None:
                    if require_proc_ext_tuple:
                        hold_reasons.append(
                            "MISSING_NHP_RESPONDER_OMENTECTOMY_PROCEDURE_ID"
                            if is_responder
                            else "MISSING_NHP_OMENTECTOMY_PROCEDURE_ID"
                        )
                        hold_reasons.append("NHP_INCOMPLETE_PROCEDURE_OR_EXTINCTION_TUPLE")
                        om_proc_id_ok = False
                elif not isinstance(om_proc_id, str) or len(om_proc_id.strip()) == 0:
                    fail_reasons.append("INVALID_NHP_OMENTECTOMY_PROCEDURE_ID")
                    om_proc_id_ok = False
                    types_ok = False
                else:
                    if not _is_canonical_id_str(om_proc_id):
                        fail_reasons.append("INVALID_NHP_OMENTECTOMY_PROCEDURE_ID")
                        om_proc_id_ok = False
                        types_ok = False
                    om_proc_canon = _canonical_id_dedup_key(om_proc_id)
                    if om_proc_canon in seen_n_proc_ids:
                        fail_reasons.append("DUPLICATE_NHP_OMENTECTOMY_PROCEDURE_ID")
                        om_proc_id_ok = False
                        types_ok = False
                    else:
                        seen_n_proc_ids.add(om_proc_canon)
                        row_proc_dedup_added = om_proc_canon

                om_d_val: Optional[Decimal] = None
                om_day_ok = True
                if om_d is None:
                    if require_proc_ext_tuple:
                        hold_reasons.append(
                            "MISSING_NHP_RESPONDER_OMENTECTOMY_DAY"
                            if is_responder
                            else "MISSING_NHP_OMENTECTOMY_DAY"
                        )
                        hold_reasons.append("NHP_INCOMPLETE_PROCEDURE_OR_EXTINCTION_TUPLE")
                        om_day_ok = False
                elif not _is_finite_number(om_d) or _to_exact_decimal(om_d) <= Decimal("0"):
                    fail_reasons.append("INVALID_NHP_OMENTECTOMY_DAY")
                    om_day_ok = False
                    types_ok = False
                else:
                    om_d_val = _to_exact_decimal(om_d)
                    if om_d_val < NHP_MIN_FOLLOWUP_DAYS_DEC:
                        fail_reasons.append("R4O_05_NHP_OMENTECTOMY_DAY_LT_90D_FAIL")
                        om_day_ok = False
                        types_ok = False
                    if fu_val is not None and om_d_val > fu_val:
                        fail_reasons.append("R4O_05_NHP_OMENTECTOMY_DAY_EXCEEDS_FOLLOWUP_FAIL")
                        om_day_ok = False
                        types_ok = False

                ext_sid_ok = True
                if ext_sid is None:
                    if require_proc_ext_tuple:
                        hold_reasons.append(
                            "MISSING_NHP_RESPONDER_C_PEPTIDE_EXTINCTION_SUBJECT_ID"
                            if is_responder
                            else "MISSING_NHP_C_PEPTIDE_EXTINCTION_SUBJECT_ID"
                        )
                        hold_reasons.append("NHP_INCOMPLETE_PROCEDURE_OR_EXTINCTION_TUPLE")
                        ext_sid_ok = False
                elif not _is_canonical_id_str(ext_sid):
                    fail_reasons.append("INVALID_NHP_EXTINCTION_SUBJECT_ID")
                    ext_sid_ok = False
                    types_ok = False
                elif sid is not None and isinstance(sid, str) and ext_sid != sid:
                    fail_reasons.append("NHP_EXTINCTION_SUBJECT_ID_MISMATCH")
                    ext_sid_ok = False
                    types_ok = False

                ext_pid_ok = True
                if ext_pid is None:
                    if require_proc_ext_tuple:
                        hold_reasons.append(
                            "MISSING_NHP_RESPONDER_C_PEPTIDE_EXTINCTION_PROCEDURE_ID"
                            if is_responder
                            else "MISSING_NHP_C_PEPTIDE_EXTINCTION_PROCEDURE_ID"
                        )
                        hold_reasons.append("NHP_INCOMPLETE_PROCEDURE_OR_EXTINCTION_TUPLE")
                        ext_pid_ok = False
                elif not _is_canonical_id_str(ext_pid):
                    fail_reasons.append("INVALID_NHP_EXTINCTION_PROCEDURE_ID")
                    ext_pid_ok = False
                    types_ok = False
                elif om_proc_id is not None and isinstance(om_proc_id, str) and ext_pid != om_proc_id:
                    fail_reasons.append("NHP_EXTINCTION_PROCEDURE_ID_MISMATCH")
                    ext_pid_ok = False
                    types_ok = False

                cpep_d_val: Optional[Decimal] = None
                port_d_val: Optional[Decimal] = None
                cpep_d_ok = True
                port_d_ok = True
                if cpep_d is None:
                    if require_proc_ext_tuple:
                        hold_reasons.append(
                            "MISSING_NHP_RESPONDER_C_PEPTIDE_EXTINCTION_ASSESSMENT_DAY"
                            if is_responder
                            else "MISSING_NHP_C_PEPTIDE_EXTINCTION_ASSESSMENT_DAY"
                        )
                        hold_reasons.append("NHP_INCOMPLETE_PROCEDURE_OR_EXTINCTION_TUPLE")
                        cpep_d_ok = False
                elif not _is_finite_number(cpep_d) or _to_exact_decimal(cpep_d) <= Decimal("0"):
                    fail_reasons.append("INVALID_NHP_C_PEPTIDE_EXTINCTION_ASSESSMENT_DAY")
                    cpep_d_ok = False
                    types_ok = False
                else:
                    cpep_d_val = _to_exact_decimal(cpep_d)
                    if cpep_d_val < NHP_MIN_FOLLOWUP_DAYS_DEC:
                        fail_reasons.append("R4O_05_NHP_C_PEPTIDE_EXTINCTION_DAY_LT_90D_FAIL")
                        cpep_d_ok = False
                        types_ok = False
                    if fu_val is not None and cpep_d_val > fu_val:
                        fail_reasons.append("R4O_05_NHP_C_PEPTIDE_EXTINCTION_DAY_EXCEEDS_FOLLOWUP_FAIL")
                        cpep_d_ok = False
                        types_ok = False
                    if om_d_val is not None:
                        if cpep_d_val < om_d_val:
                            fail_reasons.append("NHP_CPEP_EXTINCTION_PRECEDES_OMENTECTOMY_PROCEDURE")
                            cpep_d_ok = False
                            types_ok = False
                        elif _dec_diff_exceeds(cpep_d_val, om_d_val, MAX_POST_OMENTECTOMY_CPEP_EXTINCTION_WINDOW_DAYS_DEC):
                            fail_reasons.append("NHP_CPEP_EXTINCTION_EXCEEDS_14D_PROMPT_WINDOW")
                            cpep_d_ok = False
                            types_ok = False

                if port_d is None:
                    if is_responder:
                        hold_reasons.append("MISSING_NHP_RESPONDER_PORTAL_GRADIENT_ASSESSMENT_DAY")
                        port_d_ok = False
                elif not _is_finite_number(port_d) or _to_exact_decimal(port_d) <= Decimal("0"):
                    fail_reasons.append("INVALID_NHP_PORTAL_GRADIENT_ASSESSMENT_DAY")
                    port_d_ok = False
                    types_ok = False
                else:
                    port_d_val = _to_exact_decimal(port_d)
                    if port_d_val < NHP_MIN_FOLLOWUP_DAYS_DEC:
                        fail_reasons.append("R4O_05_NHP_PORTAL_GRADIENT_DAY_LT_90D_FAIL")
                        port_d_ok = False
                        types_ok = False
                    if fu_val is not None and port_d_val > fu_val:
                        fail_reasons.append("R4O_05_NHP_PORTAL_GRADIENT_DAY_EXCEEDS_FOLLOWUP_FAIL")
                        port_d_ok = False
                        types_ok = False
                    if om_d_val is not None and port_d_val > om_d_val:
                        fail_reasons.append("NHP_PORTAL_GRADIENT_POST_OMENTECTOMY_INVALID")
                        port_d_ok = False
                        types_ok = False

                # Defensive checks on NHP subject/procedure binding aliases + pairwise alias-group conflict detection (Audit R7-08)
                proc_id_vals: List[Tuple[str, str]] = []
                if om_proc_id is not None and isinstance(om_proc_id, str) and _is_canonical_id_str(om_proc_id):
                    proc_id_vals.append(("omentectomy_procedure_id", om_proc_id))
                for akey in NHP_PROCEDURE_ID_ALIAS_KEYS:
                    if akey in s and s[akey] is not None:
                        aval = s[akey]
                        if not _is_canonical_id_str(aval):
                            fail_reasons.append(f"INVALID_NHP_BINDING_ALIAS:{akey}")
                            nhp_binding_alias_adverse = True
                        else:
                            proc_id_vals.append((akey, aval))
                            if om_proc_id is not None and isinstance(om_proc_id, str) and aval != om_proc_id:
                                fail_reasons.append("NHP_EXTINCTION_PROCEDURE_ID_MISMATCH")
                                fail_reasons.append(f"R4O_05_NHP_BINDING_ALIAS_CONTRADICTION:{akey}")
                                nhp_binding_alias_adverse = True
                            acanon = _canonical_id_dedup_key(aval)
                            if acanon in seen_n_proc_ids and acanon != row_proc_dedup_added:
                                fail_reasons.append("DUPLICATE_NHP_OMENTECTOMY_PROCEDURE_ID")
                                nhp_binding_alias_adverse = True
                            elif row_proc_dedup_added is None:
                                seen_n_proc_ids.add(acanon)
                                row_proc_dedup_added = acanon
                if len({v for _, v in proc_id_vals}) > 1:
                    fail_reasons.append("NHP_CONFLICTING_PROCEDURE_ID_ALIAS_GROUP")
                    fail_reasons.append("NHP_EXTINCTION_PROCEDURE_ID_MISMATCH")
                    nhp_binding_alias_adverse = True

                ext_sid_vals: List[Tuple[str, str]] = []
                if ext_sid is not None and isinstance(ext_sid, str) and _is_canonical_id_str(ext_sid):
                    ext_sid_vals.append(("cpeptide_extinction_subject_id", ext_sid))
                for akey in NHP_EXTINCTION_SUBJECT_ID_ALIAS_KEYS:
                    if akey in s and s[akey] is not None:
                        aval = s[akey]
                        if not _is_canonical_id_str(aval):
                            fail_reasons.append(f"INVALID_NHP_BINDING_ALIAS:{akey}")
                            nhp_binding_alias_adverse = True
                        else:
                            ext_sid_vals.append((akey, aval))
                            if sid is not None and isinstance(sid, str) and aval != sid:
                                fail_reasons.append("NHP_EXTINCTION_SUBJECT_ID_MISMATCH")
                                fail_reasons.append(f"R4O_05_NHP_BINDING_ALIAS_CONTRADICTION:{akey}")
                                nhp_binding_alias_adverse = True
                if len({v for _, v in ext_sid_vals}) > 1:
                    fail_reasons.append("NHP_CONFLICTING_EXTINCTION_SUBJECT_ID_ALIAS_GROUP")
                    fail_reasons.append("NHP_EXTINCTION_SUBJECT_ID_MISMATCH")
                    nhp_binding_alias_adverse = True

                ext_pid_vals: List[Tuple[str, str]] = []
                if ext_pid is not None and isinstance(ext_pid, str) and _is_canonical_id_str(ext_pid):
                    ext_pid_vals.append(("cpeptide_extinction_procedure_id", ext_pid))
                for akey in NHP_EXTINCTION_PROCEDURE_ID_ALIAS_KEYS:
                    if akey in s and s[akey] is not None:
                        aval = s[akey]
                        if not _is_canonical_id_str(aval):
                            fail_reasons.append(f"INVALID_NHP_BINDING_ALIAS:{akey}")
                            nhp_binding_alias_adverse = True
                        else:
                            ext_pid_vals.append((akey, aval))
                            if om_proc_id is not None and isinstance(om_proc_id, str) and aval != om_proc_id:
                                fail_reasons.append("NHP_EXTINCTION_PROCEDURE_ID_MISMATCH")
                                fail_reasons.append(f"R4O_05_NHP_BINDING_ALIAS_CONTRADICTION:{akey}")
                                nhp_binding_alias_adverse = True
                if len({v for _, v in ext_pid_vals}) > 1:
                    fail_reasons.append("NHP_CONFLICTING_EXTINCTION_PROCEDURE_ID_ALIAS_GROUP")
                    fail_reasons.append("NHP_EXTINCTION_PROCEDURE_ID_MISMATCH")
                    nhp_binding_alias_adverse = True

                if len({v for _, v in (proc_id_vals + ext_pid_vals)}) > 1:
                    fail_reasons.append("NHP_EXTINCTION_PROCEDURE_ID_MISMATCH")
                    nhp_binding_alias_adverse = True

                if nhp_binding_alias_adverse:
                    types_ok = False

                nhp_date_alias_adverse = _check_subject_date_aliases(
                    s,
                    gate_tag="R4O_05",
                    species_tag="NHP",
                    min_days=NHP_MIN_FOLLOWUP_DAYS_DEC,
                    min_days_tag="90D",
                    followup_val=fu_val,
                    capsule_day_val=cap_d_val,
                    retrieval_day_val=None,
                    omentectomy_day_val=om_d_val,
                    cpep_day_val=cpep_d_val,
                    portal_day_val=port_d_val,
                    fail_reasons=fail_reasons,
                )
                if nhp_date_alias_adverse:
                    types_ok = False

                nhp_comp_resolved, nhp_comp_adverse = _check_subject_typed_complications_and_aliases(
                    s,
                    gate_tag="R4O_05",
                    species_tag="NHP",
                    fail_reasons=fail_reasons,
                    hold_reasons=hold_reasons,
                )
                if nhp_comp_adverse:
                    n_any_complication = True
                    types_ok = False
                if not nhp_comp_resolved:
                    n_all_complications_resolved = False

                cap_um_d: Optional[Decimal] = None
                if cap_v is not None:
                    if not _is_finite_number(cap_v):
                        fail_reasons.append("INVALID_NHP_SUBJECT_MONTH3_CAPSULE_UM")
                        types_ok = False
                    else:
                        cap_um_d = _to_exact_decimal(cap_v)
                        if cap_um_d < ZERO_DEC:
                            fail_reasons.append("INVALID_NHP_SUBJECT_MONTH3_CAPSULE_UM")
                            types_ok = False
                            cap_um_d = None
                        elif cap_um_d > tier_fibrin_max_d:
                            fail_reasons.append("R4O_05_NHP_MONTH3_CAPSULE_EXCEEDS_TIER_MAX_FAIL")
                ins_d: Optional[Decimal] = None
                if ins_v is not None:
                    if not _is_finite_number(ins_v) or _to_exact_decimal(ins_v) < ZERO_DEC:
                        fail_reasons.append("INVALID_NHP_SUBJECT_RESIDUAL_INSULIN")
                        types_ok = False
                    else:
                        ins_d = _to_exact_decimal(ins_v)
                if gsis_v is not None and not _is_strict_bool(gsis_v):
                    fail_reasons.append("INVALID_NHP_SUBJECT_PAIRED_DYNAMIC_GSIS_BOOL")
                    types_ok = False
                if loc_v is not None and not _is_strict_bool(loc_v):
                    fail_reasons.append("INVALID_NHP_SUBJECT_LOCALIZATION_BOOL")
                    types_ok = False

                retr_all_present = all(x is not None for x in (retr_v, tot_cells_v, res_cells_v, samp_frac_v))
                retr_reconciled = _check_retrieval_residual_reconciliation(
                    prefix="NHP",
                    retrieval_mass_pct=retr_v,
                    total_implanted_cells=tot_cells_v,
                    residual_viable_cells_measured=res_cells_v,
                    residual_sampling_fraction=samp_frac_v,
                    require_ge_99p9=False,
                    fail_reasons=fail_reasons,
                )

                # Review #7 / Audit R4-04 / Audit R5-04 / Audit R8-05: exact Decimal Month-3 follow-up >= 90 d on responders + contradictory nonresponder event ban
                responder_day_ok = False
                responder_day_missing = False
                if _is_strict_bool(achieved_ii):
                    if achieved_ii is True:
                        if day_v is None:
                            hold_reasons.append("MISSING_NHP_RESPONDER_INSULIN_INDEP_DAY")
                            responder_day_missing = True
                        elif not _is_finite_number(day_v) or _to_exact_decimal(day_v) <= Decimal("0"):
                            fail_reasons.append("INVALID_NHP_SUBJECT_INSULIN_INDEP_DAY")
                            types_ok = False
                        else:
                            day_v_dec = _to_exact_decimal(day_v)
                            if fu_val is not None and day_v_dec > fu_val:
                                fail_reasons.append("INVALID_NHP_SUBJECT_INSULIN_INDEP_DAY_EXCEEDS_FOLLOWUP")
                                types_ok = False
                            elif fu_val is not None and fu_val < NHP_MIN_FOLLOWUP_DAYS_DEC:
                                fail_reasons.append("R4O_05_NHP_RESPONDER_FOLLOWUP_LT_90D_MONTH3_INCONSISTENT_FAIL")
                                responder_day_ok = False
                            else:
                                responder_day_ok = (Decimal("0") < day_v_dec <= NHP_MAX_INSULIN_INDEP_DAY_DEC) and (fu_val is not None and fu_val >= NHP_MIN_FOLLOWUP_DAYS_DEC)
                        if day_v is None and fu_val is not None and fu_val < NHP_MIN_FOLLOWUP_DAYS_DEC:
                            fail_reasons.append("R4O_05_NHP_RESPONDER_FOLLOWUP_LT_90D_MONTH3_INCONSISTENT_FAIL")
                            types_ok = False
                    else:
                        if day_v is not None:
                            fail_reasons.append("R4O_05_NHP_NONRESPONDER_CONTRADICTORY_INSULIN_INDEP_DAY_FAIL")
                            types_ok = False
                        if fu_val is not None and fu_val < NHP_MIN_FOLLOWUP_DAYS_DEC:
                            hold_reasons.append("HOLD_NHP_RIGHT_CENSORED_FOLLOWUP_LT_90D")

                if (
                    (not sid_adverse)
                    and fu_val is not None
                    and fu_val >= NHP_MIN_FOLLOWUP_DAYS_DEC
                    and nhp_cap_day_ok
                    and om_perf_ok
                    and om_proc_id_ok
                    and om_day_ok
                    and ext_sid_ok
                    and ext_pid_ok
                    and cpep_d_ok
                    and ext_outcome_ok
                    and paired_cpep_ok
                    and port_d_ok
                    and not nhp_binding_alias_adverse
                    and not nhp_date_alias_adverse
                ):
                    n_visit_eligible_count += 1

                elig_present = (pre_diab is not None and base_ins is not None and base_cpep is not None)
                is_eligible_diabetic = False
                if elig_present and elig_types_ok and base_ins_d is not None and base_cpep_d is not None:
                    is_eligible_diabetic = (
                        (pre_diab is True)
                        and base_ins_d >= Decimal("0.5")
                        and base_cpep_d <= Decimal("0.2")
                    )
                    if is_eligible_diabetic:
                        eligible_diabetic_count += 1
                elif not elig_present and elig_types_ok:
                    pending_diabetic_eligibility_count += 1

                # Independently score graft localization / post-explant C-peptide extinction
                # (allows documented partial responders on exogenous insulin to pass localization
                # without inflating full insulin-independence efficacy count!)
                if (
                    is_eligible_diabetic
                    and sid_ok
                    and sp_ok
                    and lot_ok
                    and fu_val is not None and fu_val >= NHP_MIN_FOLLOWUP_DAYS_DEC
                    and om_perf_ok and (om_perf is True)
                    and om_proc_id_ok
                    and om_day_ok
                    and ext_sid_ok
                    and ext_pid_ok
                    and cpep_d_ok
                    and ext_outcome_ok and (ext_out is True)
                    and paired_cpep_ok
                    and lloq_d is not None and pre_cpep_d is not None and post_cpep_d is not None
                    and pre_cpep_d > lloq_d and post_cpep_d <= lloq_d
                    and not nhp_binding_alias_adverse
                    and not nhp_date_alias_adverse
                ):
                    cpep_extinction_verified_count += 1

                responder_endpoint_fields_present = (
                    (not responder_day_missing)
                    and (om_perf is not None)
                    and (om_proc_id is not None)
                    and (om_d is not None)
                    and (ext_sid is not None)
                    and (ext_pid is not None)
                    and (cpep_d is not None)
                    and (ext_out is not None)
                    and (lloq_v is not None)
                    and (pre_cpep_v is not None)
                    and (post_cpep_v is not None)
                    and (port_d is not None)
                )
                all_qual_fields_present = (
                    (sid is not None)
                    and (sp is not None)
                    and (lot_v is not None)
                    and (achieved_ii is not None)
                    and (followup_d is not None)
                    and (cap_d is not None)
                    and nhp_comp_resolved
                    and (dose_v is not None)
                    and (cap_v is not None)
                    and (ins_v is not None)
                    and (gsis_v is not None)
                    and (loc_v is not None)
                    and retr_all_present
                    and (responder_endpoint_fields_present if achieved_ii is True else True)
                )

                retr_d: Optional[Decimal] = _to_exact_decimal(retr_v) if _is_finite_number(retr_v) else None
                if is_eligible_diabetic:
                    if types_ok and all_qual_fields_present:
                        subj_qualifies = (
                            sid_ok
                            and sp_ok
                            and lot_ok
                            and (achieved_ii is True)
                            and responder_day_ok
                            and fu_val is not None and fu_val >= NHP_MIN_FOLLOWUP_DAYS_DEC
                            and nhp_cap_day_ok
                            and om_perf_ok
                            and (om_perf is True)
                            and om_proc_id_ok
                            and om_day_ok
                            and ext_sid_ok
                            and ext_pid_ok
                            and cpep_d_ok
                            and ext_outcome_ok
                            and (ext_out is True)
                            and paired_cpep_ok
                            and port_d_ok
                            and nhp_comp_resolved
                            and not nhp_comp_adverse
                            and not nhp_binding_alias_adverse
                            and not nhp_date_alias_adverse
                            and dose_d is not None and dose_d <= Decimal("10000")
                            and cap_um_d is not None and cap_um_d <= tier_fibrin_max_d
                            and ins_d is not None and ins_d == ZERO_DEC
                            and (gsis_v is True)
                            and (loc_v is True)
                            and retr_reconciled
                            and (retr_d is not None and retr_d >= Decimal("99.9") if valid_site == "R4_OMENTUM_LEAD" else True)
                        )
                        if subj_qualifies:
                            qual_count += 1
                    elif types_ok and not all_qual_fields_present and (achieved_ii is True or achieved_ii is None):
                        no_adverse_present = (
                            (sid is None or sid_ok)
                            and (sp is None or sp_ok)
                            and (lot_v is None or lot_ok)
                            and (fu_val is None or fu_val >= NHP_MIN_FOLLOWUP_DAYS_DEC)
                            and (cap_d is None or nhp_cap_day_ok)
                            and (om_perf is None or om_perf_ok)
                            and (om_proc_id is None or om_proc_id_ok)
                            and (om_d is None or om_day_ok)
                            and (ext_sid is None or ext_sid_ok)
                            and (ext_pid is None or ext_pid_ok)
                            and (cpep_d is None or cpep_d_ok)
                            and (ext_out is None or ext_outcome_ok)
                            and paired_cpep_ok
                            and (port_d is None or port_d_ok)
                            and not nhp_comp_adverse
                            and not nhp_binding_alias_adverse
                            and not nhp_date_alias_adverse
                            and (day_v is None or (_is_finite_number(day_v) and ZERO_DEC < _to_exact_decimal(day_v) <= NHP_MAX_INSULIN_INDEP_DAY_DEC and (fu_val is None or _to_exact_decimal(day_v) <= fu_val)))
                            and (dose_v is None or (dose_d is not None and dose_d <= Decimal("10000")))
                            and (cap_v is None or (cap_um_d is not None and cap_um_d <= tier_fibrin_max_d))
                            and (ins_v is None or (ins_d is not None and ins_d == ZERO_DEC))
                            and (gsis_v is None or gsis_v is True)
                            and (loc_v is None or loc_v is True)
                            and (retr_v is None or (retr_d is not None and (retr_d >= Decimal("99.9") if valid_site == "R4_OMENTUM_LEAD" else True)))
                            and ((not retr_all_present) or retr_reconciled)
                        )
                        if no_adverse_present:
                            pending_responder_qual_count += 1

            derived_nhp_eligible_visit_n = n_visit_eligible_count
            if n_any_complication:
                derived_nhp_zero_complications = False
            elif n_all_complications_resolved:
                derived_nhp_zero_complications = True
            else:
                derived_nhp_zero_complications = None

            derived_nhp_eligible_diabetic_n = eligible_diabetic_count
            derived_nhp_ii = qual_count
            derived_nhp_cpeptide_extinction_verified_count = cpep_extinction_verified_count
            if derived_nhp_n >= 4 and (eligible_diabetic_count + pending_diabetic_eligibility_count) < 4:
                fail_reasons.append("R4O_05_NHP_ELIGIBLE_DIABETIC_N_LT_4_FAIL")
            if eligible_diabetic_count >= 4:
                if (qual_count + pending_responder_qual_count) < 3 or 4 * (qual_count + pending_responder_qual_count) < 3 * eligible_diabetic_count:
                    fail_reasons.append("R4O_05_NHP_QUALIFIED_INSULIN_INDEPENDENCE_FAIL")
            elif derived_nhp_n >= 4 and (qual_count + pending_responder_qual_count + pending_diabetic_eligibility_count) < 3:
                fail_reasons.append("R4O_05_NHP_QUALIFIED_INSULIN_INDEPENDENCE_FAIL")

        if valid_site == "R4_OMENTUM_LEAD":
            if use_dec009_primate_free:
                grad = obs.get("porcine_portal_peripheral_insulin_gradient")
                if grad is None:
                    grad = obs.get("nhp_r4o05_portal_peripheral_insulin_gradient")
                if grad is None:
                    hold_reasons.append("MISSING_DEC009_PORTAL_INSULIN_GRADIENT")
                elif not _is_finite_number(grad):
                    fail_reasons.append("INVALID_PORTAL_INSULIN_GRADIENT")
                else:
                    grad_d = _to_exact_decimal(grad)
                    if grad_d <= ZERO_DEC:
                        fail_reasons.append("INVALID_PORTAL_INSULIN_GRADIENT")
                    elif grad_d < Decimal("1.5"):
                        fail_reasons.append("R4O_05_PORTAL_INSULIN_GRADIENT_LT_1P5X_FAIL")

                extinct = obs.get("dec009_post_explant_cpeptide_extinction_verified")
                if extinct is None:
                    extinct = obs.get("nhp_r4o05_post_omentectomy_cpeptide_extinction")
                if extinct is None:
                    hold_reasons.append("MISSING_DEC009_POST_EXPLANT_CPEPTIDE_EXTINCTION")
                elif not _is_strict_bool(extinct):
                    fail_reasons.append("INVALID_CPEPTIDE_EXTINCTION_BOOL")
                elif not extinct:
                    fail_reasons.append("R4O_05_POST_OMENTECTOMY_CPEPTIDE_EXTINCTION_FAILED")
            else:
                grad = obs.get("nhp_r4o05_portal_peripheral_insulin_gradient")
                if grad is None:
                    hold_reasons.append("MISSING_STAGE1_NHP_PORTAL_INSULIN_GRADIENT")
                elif not _is_finite_number(grad):
                    fail_reasons.append("INVALID_PORTAL_INSULIN_GRADIENT")
                else:
                    grad_d = _to_exact_decimal(grad)
                    if grad_d <= ZERO_DEC:
                        fail_reasons.append("INVALID_PORTAL_INSULIN_GRADIENT")
                    elif grad_d < Decimal("1.5"):
                        fail_reasons.append("R4O_05_PORTAL_INSULIN_GRADIENT_LT_1P5X_FAIL")

                extinct = obs.get("nhp_r4o05_post_omentectomy_cpeptide_extinction")
                if extinct is None:
                    hold_reasons.append("MISSING_STAGE1_NHP_POST_OMENTECTOMY_CPEPTIDE_EXTINCTION")
                elif not _is_strict_bool(extinct):
                    fail_reasons.append("INVALID_CPEPTIDE_EXTINCTION_BOOL")
                elif not extinct:
                    fail_reasons.append("R4O_05_POST_OMENTECTOMY_CPEPTIDE_EXTINCTION_FAILED")

    # 8. GY-014 & H4-6-ExVivo Preconditioning Discipline + Zero-Div-Safe Derived Ratios (Review #10)
    derived_rest_p1_ratio: Optional[float] = None
    derived_rest_p2_ratio: Optional[float] = None
    derived_rest_endpoint_ratio: Optional[float] = None

    invivo_dz = obs.get("invivo_diazoxide_depot_or_credit_claimed")
    if invivo_dz is None:
        hold_reasons.append("MISSING_INVIVO_DIAZOXIDE_BOOL")
    elif not _is_strict_bool(invivo_dz):
        fail_reasons.append("INVALID_INVIVO_DIAZOXIDE_BOOL")
    elif invivo_dz:
        fail_reasons.append("GY014_BLOCK_INVIVO_DIAZOXIDE_PROHIBITED")

    r3p06_clamp = obs.get("r3p06_5day_glycemic_clamp_enabled")
    if r3p06_clamp is None:
        hold_reasons.append("MISSING_R3P06_GLYCEMIC_CLAMP_BOOL")
    elif not _is_strict_bool(r3p06_clamp) or not r3p06_clamp:
        fail_reasons.append("R3P06_5DAY_GLYCEMIC_CLAMP_REQUIRED")

    exvivo_applied = obs.get("exvivo_rest_applied")
    if exvivo_applied is None:
        hold_reasons.append("MISSING_EXVIVO_REST_APPLIED_BOOL")
    elif not _is_strict_bool(exvivo_applied):
        fail_reasons.append("INVALID_EXVIVO_REST_APPLIED_BOOL")
    elif exvivo_applied:
        if arm_spec is not None and arm_spec.get("exvivo_rest_eligible") is False:
            fail_reasons.append("DESIGN_A_STRICTLY_PROHIBITS_EXVIVO_DIAZOXIDE_TUDCA_REST")

        exvivo_agents = obs.get("exvivo_preconditioning_agents")
        if exvivo_agents is None:
            hold_reasons.append("MISSING_EXVIVO_AGENT_MANIFEST")
        elif not isinstance(exvivo_agents, list) or len(exvivo_agents) == 0 or not all(_is_literal_nonempty_str(x) for x in exvivo_agents):
            fail_reasons.append("EMPTY_OR_MALFORMED_EXVIVO_AGENT_MANIFEST")
        else:
            for ag in exvivo_agents:
                if ag in BANNED_EXVIVO_TOKENS:
                    fail_reasons.append(f"UNAPPROVED_CLINICAL_PRECONDITIONING_AGENT:{ag}")
                elif ag not in REQUIRED_EXVIVO_REST_AGENTS:
                    fail_reasons.append(f"UNRECOGNIZED_EXVIVO_PRECONDITIONING_AGENT:{ag}")
            if set(exvivo_agents) != REQUIRED_EXVIVO_REST_AGENTS:
                fail_reasons.append("EXVIVO_AGENT_MANIFEST_MUST_MATCH_DIAZOXIDE_GMP_AND_TUDCA_GMP")

        dz_conc = obs.get("exvivo_diazoxide_uM")
        tudca_conc = obs.get("exvivo_tudca_uM")
        precond_h = obs.get("exvivo_preconditioning_hours")
        fccp_res = obs.get("h46e01_fccp_max_reserve_pct_ctrl")
        wash_cycles = obs.get("washout_cycles_n")
        lcms_sup = obs.get("lcms_supernatant_diazoxide_uM")
        lcms_pel = obs.get("lcms_pellet_diazoxide_uM")

        if dz_conc is None:
            hold_reasons.append("MISSING_EXVIVO_DIAZOXIDE_UM")
        elif not _is_finite_number(dz_conc) or not (Decimal("100") <= _to_exact_decimal(dz_conc) <= Decimal("150")):
            fail_reasons.append("EXVIVO_DIAZOXIDE_OUTSIDE_100_TO_150UM_WINDOW")

        if tudca_conc is None:
            hold_reasons.append("MISSING_EXVIVO_TUDCA_UM")
        elif not _is_finite_number(tudca_conc) or not (Decimal("100") <= _to_exact_decimal(tudca_conc) <= Decimal("500")):
            fail_reasons.append("EXVIVO_TUDCA_OUTSIDE_100_TO_500UM_WINDOW")

        if precond_h is None:
            hold_reasons.append("MISSING_EXVIVO_PRECONDITIONING_HOURS")
        elif not _is_finite_number(precond_h) or not (Decimal("18") <= _to_exact_decimal(precond_h) <= Decimal("24")):
            fail_reasons.append("EXVIVO_PRECONDITIONING_OUTSIDE_18_TO_24H_WINDOW")

        if fccp_res is None:
            hold_reasons.append("MISSING_H46E01_FCCP_MAX_RESERVE_ASSAY")
        elif not _is_finite_number(fccp_res):
            fail_reasons.append("INVALID_H46E01_FCCP_MAX_RESERVE")
        else:
            fccp_d = _to_exact_decimal(fccp_res)
            if fccp_d < ZERO_DEC or fccp_d > Decimal("300"):
                fail_reasons.append("INVALID_H46E01_FCCP_MAX_RESERVE")
            elif fccp_d < Decimal("85"):
                fail_reasons.append("H46E01_FCCP_MAX_RESERVE_LT_85PCT_COMPLEX_II_TOXICITY_FAIL")

        if wash_cycles is None:
            hold_reasons.append("MISSING_WASHOUT_CYCLES_N")
        elif not _is_strict_int(wash_cycles) or wash_cycles < 3:
            fail_reasons.append("WASHOUT_CYCLES_LT_3_FAIL")

        if lcms_sup is None:
            hold_reasons.append("MISSING_H46E02_LCMS_SUPERNATANT_DIAZOXIDE_UM")
        elif not _is_finite_number(lcms_sup):
            fail_reasons.append("GY014_LCMS_SUPERNATANT_DIAZOXIDE_EXCEEDS_0P05UM_LOQ")
        else:
            lcms_sup_d = _to_exact_decimal(lcms_sup)
            if lcms_sup_d < ZERO_DEC or lcms_sup_d > Decimal("0.05"):
                fail_reasons.append("GY014_LCMS_SUPERNATANT_DIAZOXIDE_EXCEEDS_0P05UM_LOQ")

        if lcms_pel is None:
            hold_reasons.append("MISSING_H46E02_LCMS_PELLET_DIAZOXIDE_UM")
        elif not _is_finite_number(lcms_pel):
            fail_reasons.append("GY014_LCMS_PELLET_DIAZOXIDE_EXCEEDS_0P05UM_LOQ")
        else:
            lcms_pel_d = _to_exact_decimal(lcms_pel)
            if lcms_pel_d < ZERO_DEC or lcms_pel_d > Decimal("0.05"):
                fail_reasons.append("GY014_LCMS_PELLET_DIAZOXIDE_EXCEEDS_0P05UM_LOQ")

        rest_lot = obs.get("rest_assay_lot_id")
        if rest_lot is None:
            hold_reasons.append("MISSING_H46E03_REST_ASSAY_LOT_ID")
        elif not _is_literal_nonempty_str(rest_lot) or (valid_lot_id is not None and rest_lot != valid_lot_id):
            fail_reasons.append("H46E03_REST_ASSAY_LOT_ID_MISMATCH")

        rest_o2 = obs.get("rest_challenge_o2_pct")
        if rest_o2 is None:
            hold_reasons.append("MISSING_H46E03_REST_CHALLENGE_O2_PCT")
        elif not _is_finite_number(rest_o2) or _to_exact_decimal(rest_o2) != Decimal("2"):
            fail_reasons.append("H46E03_REST_CHALLENGE_O2_PCT_NOT_2P0_FAIL")

        rest_2p = obs.get("rest_two_pulse_gsis_verified")
        if rest_2p is None:
            hold_reasons.append("MISSING_H46E03_TWO_PULSE_GSIS_VERIFIED_BOOL")
        elif not _is_strict_bool(rest_2p):
            fail_reasons.append("INVALID_H46E03_TWO_PULSE_GSIS_VERIFIED_BOOL")
        elif not rest_2p:
            fail_reasons.append("H46E03_TWO_PULSE_GSIS_NOT_VERIFIED_FAIL")

        p1_r = obs.get("rest_pulse1_si_rested")
        p1_c = obs.get("rest_pulse1_si_control")
        p2_r = obs.get("rest_pulse2_si_rested")
        p2_c = obs.get("rest_pulse2_si_control")
        p_dec_map: Dict[str, Optional[Decimal]] = {}
        for f_name, f_val in (
            ("rest_pulse1_si_rested", p1_r),
            ("rest_pulse1_si_control", p1_c),
            ("rest_pulse2_si_rested", p2_r),
            ("rest_pulse2_si_control", p2_c),
        ):
            if f_val is None:
                hold_reasons.append(f"MISSING_H46E03_{f_name.upper()}")
                p_dec_map[f_name] = None
            elif not _is_finite_number(f_val) or _to_exact_decimal(f_val) <= ZERO_DEC:
                fail_reasons.append(f"INVALID_H46E03_{f_name.upper()}")
                p_dec_map[f_name] = None
            else:
                p_dec_map[f_name] = _to_exact_decimal(f_val)

        p1_r_d = p_dec_map["rest_pulse1_si_rested"]
        p1_c_d = p_dec_map["rest_pulse1_si_control"]
        p2_r_d = p_dec_map["rest_pulse2_si_rested"]
        p2_c_d = p_dec_map["rest_pulse2_si_control"]

        if p1_r_d is not None and p1_c_d is not None:
            if p1_r_d < Decimal("3"):
                fail_reasons.append("H46E03_REST_PULSE1_SI_LT_3P0_FAIL")
            if _ratio_lt_dec(p1_r_d, p1_c_d, Decimal("0.85")):
                fail_reasons.append("H46E03_REST_PULSE1_DERIVED_RATIO_LT_0P85_FAIL")
            r1_disp = _dec_div_to_display_float(p1_r_d, p1_c_d)
            if r1_disp is not None and math.isfinite(r1_disp) and r1_disp > 0.0:
                derived_rest_p1_ratio = r1_disp
            else:
                fail_reasons.append("INVALID_H46E03_PULSE1_RATIO_NONFINITE_OR_ZERO")

        if p2_r_d is not None and p2_c_d is not None:
            if p2_r_d < Decimal("3"):
                fail_reasons.append("H46E03_REST_PULSE2_SI_LT_3P0_FAIL")
            if _ratio_lt_dec(p2_r_d, p2_c_d, Decimal("0.85")):
                fail_reasons.append("H46E03_REST_PULSE2_DERIVED_RATIO_LT_0P85_FAIL")
            r2_disp = _dec_div_to_display_float(p2_r_d, p2_c_d)
            if r2_disp is not None and math.isfinite(r2_disp) and r2_disp > 0.0:
                derived_rest_p2_ratio = r2_disp
            else:
                fail_reasons.append("INVALID_H46E03_PULSE2_RATIO_NONFINITE_OR_ZERO")

        t50_min = obs.get("oq018_post_washout_t50_min")
        t50_fold = obs.get("oq018_post_washout_t50_fold_ctrl")
        gsis_si = obs.get("oq018_post_washout_gsis_si")
        auc_pct = obs.get("oq018_post_washout_first_phase_auc_pct_ctrl")
        auc_l95 = obs.get("oq018_post_washout_first_phase_auc_l95_pct_ctrl")
        glucagon_pct = obs.get("oq018_post_washout_glucagon_pct_ctrl")
        necr_cut = obs.get("h46e03_paired_hypoxic_necrosis_reduction_pct")

        if t50_min is None:
            hold_reasons.append("MISSING_OQ018_POST_WASHOUT_T50_MIN")
        elif not _is_finite_number(t50_min):
            fail_reasons.append("OQ018_INSULIN_SHUTOFF_T50_GE_3P0MIN_FAIL")
        else:
            t50_min_d = _to_exact_decimal(t50_min)
            if t50_min_d <= ZERO_DEC or t50_min_d >= Decimal("3"):
                fail_reasons.append("OQ018_INSULIN_SHUTOFF_T50_GE_3P0MIN_FAIL")

        if t50_fold is None:
            hold_reasons.append("MISSING_OQ018_POST_WASHOUT_T50_FOLD_CTRL")
        elif not _is_finite_number(t50_fold):
            fail_reasons.append("OQ018_INSULIN_SHUTOFF_T50_FOLD_CTRL_GT_1P10_FAIL")
        else:
            t50_fold_d = _to_exact_decimal(t50_fold)
            if t50_fold_d <= ZERO_DEC or t50_fold_d > Decimal("1.10"):
                fail_reasons.append("OQ018_INSULIN_SHUTOFF_T50_FOLD_CTRL_GT_1P10_FAIL")

        if gsis_si is None:
            hold_reasons.append("MISSING_OQ018_POST_WASHOUT_GSIS_SI")
        elif not _is_finite_number(gsis_si):
            fail_reasons.append("OQ018_GSIS_SI_LT_3P0_FAIL")
        else:
            gsis_si_d = _to_exact_decimal(gsis_si)
            if gsis_si_d < Decimal("3"):
                fail_reasons.append("OQ018_GSIS_SI_LT_3P0_FAIL")
            elif p1_r_d is not None and p2_r_d is not None:
                lo_p_d = min(p1_r_d, p2_r_d)
                hi_p_d = max(p1_r_d, p2_r_d)
                if gsis_si_d < lo_p_d or gsis_si_d > hi_p_d:
                    fail_reasons.append("OQ018_CLAIMED_GSIS_SI_INCONSISTENT_WITH_TWO_PULSE_MEASUREMENTS")

        auc_pct_d: Optional[Decimal] = None
        if auc_pct is None:
            hold_reasons.append("MISSING_OQ018_FIRST_PHASE_AUC_PCT_CTRL")
        elif not _is_finite_number(auc_pct):
            fail_reasons.append("OQ018_FIRST_PHASE_AUC_LT_90PCT_CTRL_FAIL")
        else:
            auc_pct_d = _to_exact_decimal(auc_pct)
            if auc_pct_d < Decimal("90"):
                fail_reasons.append("OQ018_FIRST_PHASE_AUC_LT_90PCT_CTRL_FAIL")

        auc_l95_d: Optional[Decimal] = None
        if auc_l95 is None:
            hold_reasons.append("MISSING_OQ018_FIRST_PHASE_AUC_L95_PCT_CTRL")
        elif not _is_finite_number(auc_l95):
            fail_reasons.append("OQ018_FIRST_PHASE_AUC_L95_LT_85PCT_FAIL")
        else:
            auc_l95_d = _to_exact_decimal(auc_l95)
            if auc_l95_d < Decimal("85"):
                fail_reasons.append("OQ018_FIRST_PHASE_AUC_L95_LT_85PCT_FAIL")

        if auc_pct_d is not None and auc_l95_d is not None and auc_l95_d > auc_pct_d:
            fail_reasons.append("OQ018_FIRST_PHASE_AUC_L95_EXCEEDS_POINT_ESTIMATE_INCONSISTENT")

        if glucagon_pct is None:
            hold_reasons.append("MISSING_OQ018_GLUCAGON_RECOVERY_PCT")
        elif not _is_finite_number(glucagon_pct) or _to_exact_decimal(glucagon_pct) < Decimal("85"):
            fail_reasons.append("OQ018_GLUCAGON_RECOVERY_LT_85PCT_FAIL")

        if necr_cut is None:
            hold_reasons.append("MISSING_H46E03_HYPOXIC_NECROSIS_REDUCTION_PCT")
        elif not _is_finite_number(necr_cut):
            fail_reasons.append("INVALID_H46E03_HYPOXIC_NECROSIS_REDUCTION_PCT")
        else:
            necr_d = _to_exact_decimal(necr_cut)
            if necr_d < ZERO_DEC or necr_d > Decimal("100"):
                fail_reasons.append("INVALID_H46E03_HYPOXIC_NECROSIS_REDUCTION_PCT")
            elif necr_d < Decimal("35"):
                fail_reasons.append("H46E03_HYPOXIC_NECROSIS_REDUCTION_LT_35PCT_FAIL")

        if is_promo:
            rest_ep_type = obs.get("rest_endpoint_type")
            valid_ep_type: Optional[str] = None
            if rest_ep_type is None:
                hold_reasons.append("MISSING_STAGE1_H46E04_REST_ENDPOINT_TYPE")
            elif not _is_literal_nonempty_str(rest_ep_type) or rest_ep_type not in ALLOWED_REST_ENDPOINT_TYPES:
                fail_reasons.append("H46E04_INVALID_REST_ENDPOINT_TYPE")
            else:
                valid_ep_type = rest_ep_type

            rest_col_day = obs.get("rest_collection_day")
            if rest_col_day is None:
                hold_reasons.append("MISSING_STAGE1_H46E04_REST_COLLECTION_DAY")
            elif not _is_finite_number(rest_col_day) or _to_exact_decimal(rest_col_day) <= ZERO_DEC:
                fail_reasons.append("INVALID_H46E04_REST_COLLECTION_DAY")
            elif valid_ep_type == "day7_beta_mass" and _to_exact_decimal(rest_col_day) < Decimal("7"):
                fail_reasons.append("H46E04_COLLECTION_DAY_LT_7_FOR_DAY7_BETA_MASS_FAIL")
            elif valid_ep_type == "day14_stimulated_c_peptide" and _to_exact_decimal(rest_col_day) < Decimal("14"):
                fail_reasons.append("H46E04_COLLECTION_DAY_LT_14_FOR_DAY14_STIMULATED_CPEPTIDE_FAIL")

            ep_rested = obs.get("rest_endpoint_rested_value")
            ep_ctrl = obs.get("rest_endpoint_control_value")
            ep_rested_d: Optional[Decimal] = None
            ep_ctrl_d: Optional[Decimal] = None
            if ep_rested is None:
                hold_reasons.append("MISSING_STAGE1_H46E04_REST_ENDPOINT_RESTED_VALUE")
            elif not _is_finite_number(ep_rested) or _to_exact_decimal(ep_rested) <= ZERO_DEC:
                fail_reasons.append("INVALID_H46E04_REST_ENDPOINT_RESTED_VALUE")
            else:
                ep_rested_d = _to_exact_decimal(ep_rested)
            if ep_ctrl is None:
                hold_reasons.append("MISSING_STAGE1_H46E04_REST_ENDPOINT_CONTROL_VALUE")
            elif not _is_finite_number(ep_ctrl) or _to_exact_decimal(ep_ctrl) <= ZERO_DEC:
                fail_reasons.append("INVALID_H46E04_REST_ENDPOINT_CONTROL_VALUE")
            else:
                ep_ctrl_d = _to_exact_decimal(ep_ctrl)

            # Review #10 / Audit R12-04: Exact Decimal policy check FIRST; also reject float64 display underflow/overflow (e.g. 1e-320 / 1e6)
            if ep_rested_d is not None and ep_ctrl_d is not None:
                if _ratio_lt_dec(ep_rested_d, ep_ctrl_d, Decimal("1.20")):
                    fail_reasons.append("H46E04_DERIVED_ENDPOINT_RATIO_LT_1P20X_FAIL")
                ep_ratio_disp = _dec_div_to_display_float(ep_rested_d, ep_ctrl_d)
                if ep_ratio_disp is not None and math.isfinite(ep_ratio_disp) and ep_ratio_disp > 0.0:
                    derived_rest_endpoint_ratio = ep_ratio_disp
                else:
                    fail_reasons.append("INVALID_H46E04_DERIVED_RATIO_NONFINITE_OR_UNDERFLOW_ZERO")

            d14_fold = obs.get("h46e04_day14_cpeptide_or_mass_fold_ctrl")
            if d14_fold is None:
                hold_reasons.append("MISSING_STAGE1_H46E04_DAY14_EFFICACY_FOLD_CTRL")
            elif not _is_finite_number(d14_fold) or _to_exact_decimal(d14_fold) <= ZERO_DEC:
                fail_reasons.append("INVALID_H46E04_DAY14_FOLD")
            else:
                d14_fold_d = _to_exact_decimal(d14_fold)
                if d14_fold_d < Decimal("1.20"):
                    fail_reasons.append("H46E04_DAY14_EFFICACY_LT_1P20X_DROP_REST_CREDIT")
                if (
                    ep_rested_d is not None
                    and ep_ctrl_d is not None
                    and derived_rest_endpoint_ratio is not None
                    and _dec_rel_diff_exceeds_ratio(d14_fold_d, ep_rested_d, ep_ctrl_d, Decimal("0.01"))
                ):
                    fail_reasons.append("H46E04_CLAIMED_FOLD_CONTRADICTS_DERIVED_MEASURED_RATIO_FAIL")

            zero_delay = obs.get("h46e04_zero_secretory_delay_verified")
            if zero_delay is None:
                hold_reasons.append("MISSING_STAGE1_H46E04_ZERO_SECRETORY_DELAY_BOOL")
            elif not _is_strict_bool(zero_delay):
                fail_reasons.append("INVALID_H46E04_ZERO_SECRETORY_DELAY_BOOL")
            elif not zero_delay:
                fail_reasons.append("H46E04_SECRETORY_DELAY_DETECTED_FAIL")
    else:
        exvivo_agents = obs.get("exvivo_preconditioning_agents")
        if exvivo_agents is None:
            hold_reasons.append("MISSING_EXVIVO_AGENT_MANIFEST")
        elif not isinstance(exvivo_agents, list) or len(exvivo_agents) != 0:
            fail_reasons.append("NONEMPTY_EXVIVO_AGENTS_WHEN_EXVIVO_REST_FALSE")

    return {
        "valid_site": valid_site,
        "valid_scale_mode": valid_scale_mode,
        "envelope_tier": envelope_tier,
        "computed_pitch_um": computed_pitch_um,
        "computed_min_dist_um": computed_min_dist_um,
        "implied_total_loading": implied_total_loading,
        "max_leaf_loading": max_leaf_loading,
        "effective_max_load": effective_max_load,
        "n_leaves_verified": n_leaves_verified,
        "large_animal_pathway": large_animal_pathway,
        "derived_porcine_n": derived_porcine_n,
        "derived_porcine_eligible_visit_n": derived_porcine_eligible_visit_n,
        "derived_porcine_zero_complications": derived_porcine_zero_complications,
        "derived_nhp_n": derived_nhp_n,
        "derived_nhp_eligible_visit_n": derived_nhp_eligible_visit_n,
        "derived_nhp_zero_complications": derived_nhp_zero_complications,
        "derived_nhp_eligible_diabetic_n": derived_nhp_eligible_diabetic_n,
        "derived_nhp_ii": derived_nhp_ii,
        "derived_nhp_cpeptide_extinction_verified_count": derived_nhp_cpeptide_extinction_verified_count,
        "derived_rest_p1_ratio": derived_rest_p1_ratio,
        "derived_rest_p2_ratio": derived_rest_p2_ratio,
        "derived_rest_endpoint_ratio": derived_rest_endpoint_ratio,
    }


def evaluate_gate33_route4_omentum_and_exvivo_rest(
    payload: Dict[str, Any],
    *,
    arm_manifest: Optional[Dict[str, Any]] = None,
    trusted_evidence_store: Optional[Mapping[str, Mapping[str, Any]]] = None,
) -> Dict[str, Any]:
    """
    100% Fail-Closed, Manifest-Linked Gate-35 (provisional IIP-0056 / DEC-137 / GY-034; staged slot IIP-0047, Round-14) Adjudicator.

    Enforces:
      - Cryptographic authentication of caller-supplied arm_manifest (rejecting any mutation).
      - Strict synthetic fixture isolation: ANY SYNTHETIC_FIXTURE record ALWAYS returns
        promotion_authorized=False (decision='SYNTHETIC_SELF_TEST_PASS').
      - Mandatory construct_manifest_sha256 on parent payload & all 4 archived records.
      - Unified v2_round5_unified 14-field upstream & current-assay records in trusted_evidence_store
        with alias-consistency (record_id vs archive_sha256), canonical-body SHA-256 verification,
        collision-free upstream GATE-34 (rejecting live GATE-32 role collision) & current GATE-35
        (rejecting live GATE-33 role collision), prerequisite_archive_sha256s binding inside Gate 34
        (GATE-0V & GATE-5 digests), exact live Blueprint section 7 OQ-012 Gate 5 rules
        (survivor_count_k == 0, clonogenic_fraction_f in (0, 1], spike_in_detection_efficiency_eta in [0.30, 1.0],
        effective_clonogenic_trials_n_eff <= floor(n * f * eta), n_eff >= 299,573,228, and exact 75-digit
        Decimal Clopper-Pearson U95(0, n_eff) <= 1e-8), and rejection of contradictory
        physical_qualification_complete=False / release_authorizing=False / modeled_qualification_only=True flags.
      - Mandatory current_assay_evidence_record (GATE-35) binding & governing ALL current safety,
        physical (including live GY-028 confocal wall clearance >= 7.5 um minimum), per-leaf,
        Stage-1 (DEC-009 0-NHP primate-free primary pathway OR FDA CBER INTERACT/Pre-IND exception NHP cohort
        with decoupled partial-responder paired pre/post-explant C-peptide/LLOQ extinction), and ex-vivo rest
        cutoffs directly from the verified archive.
      - Per-leaf reconciliation BEFORE actual max-leaf steric packing (every leaf + effective_max_load),
        plus scope-bound scale_mode (ANIMAL_PRECLINICAL_SCALE -> STAGE_LIMITED_PRECLINICAL_ONLY with
        promotion_authorized=False; total_implanted_ieq > 100,000 with <2 leaves always fails).
      - End-to-end exact context-independent Decimal comparisons across ALL Gate-35 policy thresholds
        (strict limits, exact-zero limits, inclusive ceilings, lower thresholds, per-leaf & per-subject
        thresholds, exact polynomial steric packing, Gate 5 OQ-012 U95, and Stage-1 chronological bounds;
        ZERO float() conversion before any policy decision; Audit R9-06 / R10-05 / R12-04), with
        zero-division-safe ex-vivo rest ratios and float conversion ONLY for display metadata.
    """
    try:
        return _evaluate_gate33_route4_omentum_and_exvivo_rest_impl(
            payload,
            arm_manifest=arm_manifest,
            trusted_evidence_store=trusted_evidence_store,
        )
    except (DecimalException, OverflowError, ValueError, TypeError) as exc:
        err_code = f"GATE35_NUMERIC_OR_DECIMAL_EVALUATION_ERROR:{type(exc).__name__}"
        return {
            "status": "FAIL",
            "decision": "FAIL_GATE35_ADVERSE_SAFETY_OR_SPEC_VIOLATION",
            "authority_scope": "REJECTED_OR_HELD",
            "promotion_authorized": False,
            "experiment_booking_authorized": False,
            "fail_reasons": [err_code],
            "hold_reasons": [],
            "reasons": [err_code],
        }


def _evaluate_gate33_route4_omentum_and_exvivo_rest_impl(
    payload: Dict[str, Any],
    *,
    arm_manifest: Optional[Dict[str, Any]] = None,
    trusted_evidence_store: Optional[Mapping[str, Mapping[str, Any]]] = None,
) -> Dict[str, Any]:
    """Internal implementation of the fail-closed Gate-35 adjudicator."""
    fail_reasons: List[str] = []
    hold_reasons: List[str] = []

    if not isinstance(payload, dict):
        return {
            "status": "FAIL",
            "decision": "FAIL_GATE35_INVALID_PAYLOAD",
            "promotion_authorized": False,
            "experiment_booking_authorized": False,
            "fail_reasons": ["NON_DICT_PAYLOAD"],
            "hold_reasons": [],
            "reasons": ["NON_DICT_PAYLOAD"],
        }

    manifest, manifest_err = _get_verified_canonical_manifest(arm_manifest)
    if manifest is None or manifest_err is not None:
        err_code = manifest_err or "MUTATED_OR_UNVERIFIED_CALLER_ARM_MANIFEST_REJECTED"
        return {
            "status": "FAIL",
            "decision": "FAIL_GATE35_ADVERSE_SAFETY_OR_SPEC_VIOLATION",
            "promotion_authorized": False,
            "experiment_booking_authorized": False,
            "fail_reasons": [err_code],
            "hold_reasons": [],
            "reasons": [err_code],
        }
    manifest_arms = manifest["arms"]

    # 1. Scope, evidence_tier, lot, bank_id, arm manifest & mandatory parent construct_manifest_sha256 (Review #4)
    scope = payload.get("evaluation_scope")
    if scope is None:
        hold_reasons.append("MISSING_EVALUATION_SCOPE")
        is_promo = True
    elif not _is_literal_nonempty_str(scope) or scope not in ("CLINICAL_PROMOTION", "STAGE0_EXPERIMENT_BOOKING"):
        fail_reasons.append("INVALID_EVALUATION_SCOPE")
        is_promo = True
    else:
        is_promo = (scope == "CLINICAL_PROMOTION")

    evidence_tier = payload.get("evidence_tier")
    valid_evidence_tier: Optional[str] = None
    if evidence_tier is None:
        hold_reasons.append("MISSING_EVIDENCE_TIER")
    elif not _is_literal_nonempty_str(evidence_tier) or evidence_tier not in ALLOWED_EVIDENCE_TIERS:
        fail_reasons.append("INVALID_EVIDENCE_TIER")
    else:
        valid_evidence_tier = evidence_tier

    lot_id = payload.get("lot_id")
    valid_lot_id: Optional[str] = None
    if lot_id is None:
        hold_reasons.append("MISSING_LOT_ID")
    elif not _is_literal_nonempty_str(lot_id):
        fail_reasons.append("INVALID_LOT_ID")
    else:
        valid_lot_id = lot_id

    bank_id = payload.get("bank_id")
    valid_bank_id: Optional[str] = None
    if bank_id is None:
        hold_reasons.append("MISSING_BANK_ID")
    elif not _is_literal_nonempty_str(bank_id):
        fail_reasons.append("INVALID_BANK_ID")
    else:
        valid_bank_id = bank_id

    manifest_sha = payload.get("canonical_arm_manifest_sha256")
    if manifest_sha is None:
        hold_reasons.append("MISSING_CANONICAL_ARM_MANIFEST_SHA256")
    elif not _is_literal_nonempty_str(manifest_sha) or manifest_sha != EXPECTED_CANONICAL_MANIFEST_SHA256:
        fail_reasons.append("CANONICAL_ARM_MANIFEST_SHA256_MISMATCH")

    payload_construct_sha: Optional[str] = None
    c_sha = payload.get("construct_manifest_sha256")
    if c_sha is None:
        hold_reasons.append("MISSING_CONSTRUCT_MANIFEST_SHA256")
    elif not _is_non_all_zero_sha256_hex(c_sha) or c_sha == EXPECTED_CANONICAL_MANIFEST_SHA256:
        fail_reasons.append("INVALID_OR_CONFLATED_CONSTRUCT_MANIFEST_SHA256")
    else:
        payload_construct_sha = c_sha

    # 2. Deployment site & canonical arm identity
    site = payload.get("deployment_site")
    valid_site: Optional[str] = None
    if site is None:
        hold_reasons.append("MISSING_DEPLOYMENT_SITE")
    elif not _is_literal_nonempty_str(site) or site not in ("R4_OMENTUM_LEAD", "R4_SARS_FREE_BACKUP"):
        fail_reasons.append("INVALID_OR_UNREGISTERED_DEPLOYMENT_SITE")
    else:
        valid_site = site

    arm_key = payload.get("arm_key")
    product_id = payload.get("product_id")
    arm_spec: Optional[Dict[str, Any]] = None
    expected_product_id: Optional[str] = None
    expected_bank_origin: Optional[str] = None
    expected_dual_req: Optional[bool] = None
    if arm_key is None:
        hold_reasons.append("MISSING_ARM_KEY")
    elif not isinstance(arm_key, str) or not _is_literal_nonempty_str(arm_key) or arm_key not in manifest_arms:
        fail_reasons.append("UNREGISTERED_CANONICAL_ARM_KEY")
    else:
        arm_spec = manifest_arms[arm_key]
        expected_product_id = arm_spec["product_id"]
        expected_bank_origin = arm_spec["cell_origin"]
        expected_dual_req = bool(arm_spec["dual_switch_required_for_release"])

        if product_id is None:
            hold_reasons.append("MISSING_PRODUCT_ID")
        elif not _is_literal_nonempty_str(product_id) or product_id != expected_product_id:
            fail_reasons.append("PRODUCT_ID_CANONICAL_MANIFEST_MISMATCH")

        if arm_spec.get("r4_eligible") is not True:
            fail_reasons.append("GY027_1_BLOCK_UNHARDENED_ABX_PROHIBITED_ON_R4")
        elif valid_site == "R4_SARS_FREE_BACKUP" and arm_spec.get("r4_sars_backup_eligible") is not True:
            fail_reasons.append("D1B_LEAN_K2_SINGLE_SWITCH_BARRED_FROM_R4_SARS_BACKUP")

        sw_id = payload.get("safety_switch_id")
        if sw_id is None:
            hold_reasons.append("MISSING_SAFETY_SWITCH_ID")
        elif not _is_literal_nonempty_str(sw_id):
            fail_reasons.append("INVALID_SAFETY_SWITCH_ID")
        elif "htmpk" in sw_id.lower():
            fail_reasons.append("RETIRED_MISMATCHED_CDK1_HTMPK_SWITCH_PROHIBITED")
        elif sw_id != arm_spec["safety_switch"]:
            fail_reasons.append("SAFETY_SWITCH_CANONICAL_MANIFEST_MISMATCH")

        dual_flag = payload.get("dual_switch_lot_qualified")
        if dual_flag is None:
            hold_reasons.append("MISSING_DUAL_SWITCH_LOT_QUALIFIED_BOOL")
        elif not _is_strict_bool(dual_flag):
            fail_reasons.append("INVALID_DUAL_SWITCH_LOT_QUALIFIED_BOOL")
        elif dual_flag != expected_dual_req:
            fail_reasons.append("DUAL_SWITCH_FLAG_CANONICAL_MANIFEST_MISMATCH")
        elif valid_site == "R4_SARS_FREE_BACKUP" and not dual_flag:
            fail_reasons.append("SARS_BACKUP_REQUIRES_DUAL_FAILSAFE_QUALIFIED")

    # 3. Unified v2_round5_unified Trusted Upstream Receipts (Collision-free GATE-34, GATE-0V 5-lineage, Live Blueprint GATE-5 OQ-012)
    #    Accepts payload field upstream_gate34_record OR compatible alias upstream_gate32_record while
    #    STRICTLY requiring gate_source == "GATE-34" (explicitly rejecting live GATE-32 role collision!).
    up_g34_new = payload.get("upstream_gate34_record")
    up_g34_compat = payload.get("upstream_gate32_record")
    if up_g34_new is not None and up_g34_compat is not None and not _strict_json_equal(up_g34_new, up_g34_compat):
        fail_reasons.append("UPSTREAM_GATE34_CONFLICTING_RECORD_KEY_ALIAS")
    up_g34_rec = up_g34_new if up_g34_new is not None else up_g34_compat

    upstream_results: Dict[str, Dict[str, Any]] = {}
    observed_construct_shas: List[str] = []
    observed_bank_ids: List[str] = []
    for rec_obj, tag, exp_src in (
        (up_g34_rec, "GATE34", "GATE-34"),
        (payload.get("upstream_gate0v_record"), "GATE0V", "GATE-0V"),
        (payload.get("upstream_gate5_oq012_record"), "GATE5_OQ012", "GATE-5"),
    ):
        u_res = _validate_upstream_lot_record(
            rec_obj,
            tag=tag,
            expected_gate_source=exp_src,
            expected_product_id=expected_product_id,
            expected_lot_id=valid_lot_id,
            expected_bank_id=valid_bank_id,
            expected_bank_origin=expected_bank_origin,
            expected_evidence_tier=valid_evidence_tier,
            expected_dual_switch_required=expected_dual_req,
            trusted_evidence_store=trusted_evidence_store,
            fail_reasons=fail_reasons,
            hold_reasons=hold_reasons,
        )
        upstream_results[exp_src] = u_res
        if u_res["construct_sha"] is not None:
            observed_construct_shas.append(u_res["construct_sha"])
        if u_res["bank_id"] is not None:
            observed_bank_ids.append(u_res["bank_id"])

    # Review #3: Match Gate 34 prerequisite_archive_sha256s against actual Gate 0V and Gate 5 archive digests!
    g34_prereqs = upstream_results["GATE-34"].get("prerequisite_archive_sha256s")
    g0v_sha = upstream_results["GATE-0V"].get("archive_sha256")
    g5_sha = upstream_results["GATE-5"].get("archive_sha256")
    if isinstance(g34_prereqs, dict):
        if g0v_sha is not None and g34_prereqs.get("GATE-0V") != g0v_sha:
            fail_reasons.append("UPSTREAM_GATE34_PREREQUISITE_GATE0V_SHA256_MISMATCH")
        if g5_sha is not None and g34_prereqs.get("GATE-5") != g5_sha:
            fail_reasons.append("UPSTREAM_GATE34_PREREQUISITE_GATE5_SHA256_MISMATCH")

    # 3B. Mandatory Verified Current-Assay Archived Record (GATE-35) Controlling All Current Cutoffs (Review #4)
    verified_cur_archive, cur_construct_sha = _validate_current_assay_record(
        payload.get("current_assay_evidence_record"),
        is_promo=is_promo,
        expected_product_id=expected_product_id,
        expected_lot_id=valid_lot_id,
        expected_bank_id=valid_bank_id,
        expected_bank_origin=expected_bank_origin,
        expected_evidence_tier=valid_evidence_tier,
        expected_construct_sha=payload_construct_sha,
        upstream_record_ids=[upstream_results[k].get("record_id") for k in ("GATE-34", "GATE-0V", "GATE-5")],
        upstream_archive_shas=[upstream_results[k].get("archive_sha256") for k in ("GATE-34", "GATE-0V", "GATE-5")],
        trusted_evidence_store=trusted_evidence_store,
        fail_reasons=fail_reasons,
        hold_reasons=hold_reasons,
    )
    if cur_construct_sha is not None:
        observed_construct_shas.append(cur_construct_sha)

    if len(set(observed_bank_ids)) > 1:
        fail_reasons.append("UPSTREAM_BANK_ID_CROSS_RECORD_MISMATCH")
    if len(set(observed_construct_shas)) > 1:
        fail_reasons.append("UPSTREAM_CONSTRUCT_MANIFEST_SHA256_CROSS_RECORD_MISMATCH")
    if payload_construct_sha is not None and any(s != payload_construct_sha for s in observed_construct_shas):
        fail_reasons.append("UPSTREAM_CONSTRUCT_MANIFEST_SHA256_PAYLOAD_MISMATCH")

    resolved_construct_sha = (
        payload_construct_sha
        if (
            payload_construct_sha is not None
            and len(observed_construct_shas) == 4
            and set(observed_construct_shas) == {payload_construct_sha}
        )
        else None
    )

    # 4..8. Reconcile parent vs verified current_assay_evidence_record and evaluate ALL safety cutoffs
    #       from the verified archive (Review #4)!
    if verified_cur_archive is not None:
        any_arch_diff = _reconcile_parent_against_current_archive(
            payload, verified_cur_archive, is_promo=is_promo, fail_reasons=fail_reasons,
        )
        eval_res = _evaluate_gate33_measurements(
            verified_cur_archive,
            is_promo=is_promo,
            valid_lot_id=valid_lot_id,
            arm_spec=arm_spec,
            fail_reasons=fail_reasons,
            hold_reasons=hold_reasons,
        )
        if any_arch_diff:
            parent_fails: List[str] = []
            parent_holds: List[str] = []
            parent_eval = _evaluate_gate33_measurements(
                payload,
                is_promo=is_promo,
                valid_lot_id=valid_lot_id,
                arm_spec=arm_spec,
                fail_reasons=parent_fails,
                hold_reasons=parent_holds,
            )
            fail_reasons.extend(parent_fails)
            hold_reasons.extend(parent_holds)
            if parent_eval["computed_pitch_um"] is None or parent_eval["computed_min_dist_um"] is None:
                eval_res["computed_pitch_um"] = None
                eval_res["computed_min_dist_um"] = None
    else:
        eval_res = _evaluate_gate33_measurements(
            payload,
            is_promo=is_promo,
            valid_lot_id=valid_lot_id,
            arm_spec=arm_spec,
            fail_reasons=fail_reasons,
            hold_reasons=hold_reasons,
        )

    eff_site = eval_res["valid_site"] or valid_site
    eff_scale_mode = eval_res["valid_scale_mode"]
    computed_pitch_um = eval_res["computed_pitch_um"]
    computed_min_dist_um = eval_res["computed_min_dist_um"]

    if not fail_reasons and not hold_reasons:
        if (
            computed_pitch_um is None
            or computed_min_dist_um is None
            or not math.isfinite(computed_pitch_um)
            or not math.isfinite(computed_min_dist_um)
        ):
            fail_reasons.append("UNRESOLVED_OR_NONFINITE_PACKING_METRICS_FAIL")

    fail_sorted = sorted(set(fail_reasons))
    hold_sorted = sorted(set(hold_reasons))
    all_reasons = sorted(set(fail_sorted + hold_sorted))

    def _safe_round(val: Optional[float], digits: int = 4) -> Optional[float]:
        if val is None or not math.isfinite(val):
            return None
        return round(val, digits)

    meta: Dict[str, Any] = {
        "gate_id": GATE_ID,
        "envelope_tier": eval_res["envelope_tier"],
        "evidence_tier": valid_evidence_tier,
        "scale_mode": eff_scale_mode,
        "large_animal_pathway": eval_res["large_animal_pathway"],
        "bank_id": valid_bank_id,
        "resolved_construct_manifest_sha256": resolved_construct_sha,
        "recomputed_gate5_u95_exact": upstream_results["GATE-5"].get("recomputed_gate5_u95"),
        "computed_pitch_um": _safe_round(computed_pitch_um, 3),
        "computed_min_cross_plane_dist_um": _safe_round(computed_min_dist_um, 3),
        "implied_total_loading_ieq_cm2": _safe_round(eval_res["implied_total_loading"], 4),
        "max_leaf_loading_ieq_cm2": _safe_round(eval_res["max_leaf_loading"], 4),
        "effective_max_loading_ieq_cm2": _safe_round(eval_res["effective_max_load"], 4),
        "verified_leaf_count": eval_res["n_leaves_verified"],
        "derived_porcine_n": eval_res["derived_porcine_n"],
        "derived_porcine_eligible_visit_n": eval_res["derived_porcine_eligible_visit_n"],
        "derived_porcine_zero_complications": eval_res["derived_porcine_zero_complications"],
        "derived_nhp_n": eval_res["derived_nhp_n"],
        "derived_nhp_eligible_visit_n": eval_res["derived_nhp_eligible_visit_n"],
        "derived_nhp_zero_complications": eval_res["derived_nhp_zero_complications"],
        "derived_nhp_eligible_diabetic_n": eval_res["derived_nhp_eligible_diabetic_n"],
        "derived_nhp_qualified_ii_count": eval_res["derived_nhp_ii"],
        "derived_nhp_cpeptide_extinction_verified_count": eval_res["derived_nhp_cpeptide_extinction_verified_count"],
        "derived_rest_pulse1_si_ratio": _safe_round(eval_res["derived_rest_p1_ratio"], 4),
        "derived_rest_pulse2_si_ratio": _safe_round(eval_res["derived_rest_p2_ratio"], 4),
        "derived_rest_endpoint_ratio": _safe_round(eval_res["derived_rest_endpoint_ratio"], 4),
        "primary_exvivo_rest_h4_credit_pp": 0.0,
    }

    if fail_sorted:
        return {
            **meta,
            "status": "FAIL",
            "decision": "FAIL_GATE35_ADVERSE_SAFETY_OR_SPEC_VIOLATION",
            "authority_scope": "REJECTED_OR_HELD",
            "promotion_authorized": False,
            "experiment_booking_authorized": False,
            "fail_reasons": fail_sorted,
            "hold_reasons": hold_sorted,
            "reasons": all_reasons,
        }
    if hold_sorted:
        return {
            **meta,
            "status": "HOLD",
            "decision": "HOLD_GATE35_MISSING_MANDATORY_EVIDENCE",
            "authority_scope": "REJECTED_OR_HELD",
            "promotion_authorized": False,
            "experiment_booking_authorized": False,
            "fail_reasons": [],
            "hold_reasons": hold_sorted,
            "reasons": all_reasons,
        }

    # HARD RULE (R2-01): SYNTHETIC_FIXTURE records MUST NEVER authorize clinical promotion!
    if valid_evidence_tier == "SYNTHETIC_FIXTURE":
        return {
            **meta,
            "status": "SYNTHETIC_SELF_TEST_PASS" if is_promo else "SYNTHETIC_SELF_TEST_BOOKING_PASS",
            "decision": "SYNTHETIC_SELF_TEST_PASS" if is_promo else "SYNTHETIC_SELF_TEST_BOOKING_PASS",
            "authority_scope": "SYNTHETIC_SELF_TEST",
            "promotion_authorized": False,
            "experiment_booking_authorized": False,
            "synthetic_fixture_valid": True,
            "site_tier": "LEAD_VISCERAL_PORTAL" if eff_site == "R4_OMENTUM_LEAD" else "SECONDARY_BACKUP_SUBARS",
            "fail_reasons": [],
            "hold_reasons": [],
            "reasons": [],
        }

    if not is_promo:
        return {
            **meta,
            "status": "PASS_BOOKING_ONLY",
            "decision": "PASS_STAGE0_CANDIDATE_EXPERIMENT_BOOKING_ONLY",
            "authority_scope": "BANK_QUALIFICATION_ONLY",
            "promotion_authorized": False,
            "experiment_booking_authorized": True,
            "site_tier": "LEAD_VISCERAL_PORTAL" if eff_site == "R4_OMENTUM_LEAD" else "SECONDARY_BACKUP_SUBARS",
            "fail_reasons": [],
            "hold_reasons": [],
            "reasons": [],
        }

    # Review #6 / Audit R4-03: ANIMAL_PRECLINICAL_SCALE can NEVER authorize CLINICAL_LOT_RELEASE!
    if eff_scale_mode == "ANIMAL_PRECLINICAL_SCALE":
        return {
            **meta,
            "status": "STAGE_LIMITED_PRECLINICAL_ONLY",
            "decision": "STAGE_LIMITED_PRECLINICAL_ONLY",
            "authority_scope": "STAGE_LIMITED_PRECLINICAL_ONLY",
            "promotion_authorized": False,
            "experiment_booking_authorized": True,
            "site_tier": "LEAD_VISCERAL_PORTAL" if eff_site == "R4_OMENTUM_LEAD" else "SECONDARY_BACKUP_SUBARS",
            "fail_reasons": [],
            "hold_reasons": [],
            "reasons": ["ANIMAL_PRECLINICAL_SCALE_CANNOT_AUTHORIZE_CLINICAL_LOT_RELEASE"],
        }

    return {
        **meta,
        "status": "PASS",
        "decision": "PASS_GATE35_CLINICAL_PROMOTION_AUTHORIZED",
        "authority_scope": "CLINICAL_LOT_RELEASE",
        "promotion_authorized": True,
        "experiment_booking_authorized": True,
        "site_tier": "LEAD_VISCERAL_PORTAL" if eff_site == "R4_OMENTUM_LEAD" else "SECONDARY_BACKUP_SUBARS",
        "fail_reasons": [],
        "hold_reasons": [],
        "reasons": [],
    }


evaluate_gate35_route4_omentum_and_exvivo_rest = evaluate_gate33_route4_omentum_and_exvivo_rest


def _make_upstream_fixture_bundle(
    arm_manifest: Dict[str, Any],
    *,
    arm_key: str,
    lot_id: str,
    evidence_tier: str,
    bank_id: Optional[str] = None,
    construct_manifest_sha256: Optional[str] = None,
) -> Tuple[Dict[str, Dict[str, Any]], Dict[str, Dict[str, Any]]]:
    """Build 3 unified v2_round5_unified upstream records (collision-free GATE-34, GATE-0V, live Blueprint OQ-012 GATE-5) plus store."""
    spec = arm_manifest["arms"][arm_key]
    b_id = bank_id if bank_id is not None else f"BANK-{arm_key}-001"
    c_sha = construct_manifest_sha256 if construct_manifest_sha256 is not None else _fixture_construct_manifest_sha256(arm_key, spec["product_id"])
    is_synth = (evidence_tier == "SYNTHETIC_FIXTURE")
    auth_scope = "SYNTHETIC_SELF_TEST" if is_synth else "CLINICAL_LOT_RELEASE"
    bank_qual = False if is_synth else True
    promo_auth = False if is_synth else True
    g5_n_tested = 1_000_000_000
    g5_f_clon = 0.50
    g5_eta_det = 0.80
    g5_n_eff = 400_000_000
    g5_u95 = clopper_pearson_u95(0, g5_n_eff, alpha=0.05)

    g0v_dec = (
        "SYNTHETIC_SELF_TEST_PASS"
        if is_synth
        else ("PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL" if arm_key == "D" else "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE")
    )
    g0v = seal_upstream_evidence_record({
        "schema_revision": UPSTREAM_RECEIPT_SCHEMA_REVISION,
        "record_id": f"REC-G0V-{arm_key}-{lot_id}",
        "gate_source": "GATE-0V",
        "product_id": spec["product_id"],
        "lot_id": lot_id,
        "bank_id": b_id,
        "bank_origin": spec["cell_origin"],
        "canonical_arm_manifest_sha256": EXPECTED_CANONICAL_MANIFEST_SHA256,
        "construct_manifest_sha256": c_sha,
        "evidence_tier": evidence_tier,
        "decision": g0v_dec,
        "authority_scope": auth_scope,
        "bank_qualified": bank_qual,
        "promotion_authorized": promo_auth,
        "lineages_verified": sorted(REQUIRED_GY030_LINEAGES),
        "whole_graft_stressed_tested": True,
    })
    g5 = seal_upstream_evidence_record({
        "schema_revision": UPSTREAM_RECEIPT_SCHEMA_REVISION,
        "record_id": f"REC-G5-{arm_key}-{lot_id}",
        "gate_source": "GATE-5",
        "product_id": spec["product_id"],
        "lot_id": lot_id,
        "bank_id": b_id,
        "bank_origin": spec["cell_origin"],
        "canonical_arm_manifest_sha256": EXPECTED_CANONICAL_MANIFEST_SHA256,
        "construct_manifest_sha256": c_sha,
        "evidence_tier": evidence_tier,
        "decision": "SYNTHETIC_SELF_TEST_PASS" if is_synth else "PASS_GATE5_OQ012_CLONOGENIC_ERADICATION",
        "authority_scope": auth_scope,
        "bank_qualified": bank_qual,
        "promotion_authorized": promo_auth,
        "oq012_clonogenic_regrowth_pass": True,
        "survivor_count_k": 0,
        "tested_cells_n": g5_n_tested,
        "clonogenic_fraction_f": g5_f_clon,
        "spike_in_detection_efficiency_eta": g5_eta_det,
        "effective_clonogenic_trials_n_eff": g5_n_eff,
        "u95_exact": g5_u95,
    })
    g34 = seal_upstream_evidence_record({
        "schema_revision": UPSTREAM_RECEIPT_SCHEMA_REVISION,
        "record_id": f"REC-G34-{arm_key}-{lot_id}",
        "gate_source": "GATE-34",
        "product_id": spec["product_id"],
        "lot_id": lot_id,
        "bank_id": b_id,
        "bank_origin": spec["cell_origin"],
        "canonical_arm_manifest_sha256": EXPECTED_CANONICAL_MANIFEST_SHA256,
        "construct_manifest_sha256": c_sha,
        "evidence_tier": evidence_tier,
        "decision": "SYNTHETIC_SELF_TEST_PASS" if is_synth else "PASS_GATE34_CLINICAL_LOT_RELEASE",
        "authority_scope": auth_scope,
        "bank_qualified": bank_qual,
        "promotion_authorized": promo_auth,
        "dual_switch_lot_qualified": bool(spec["dual_switch_required_for_release"]),
        "prerequisite_archive_sha256s": {
            "GATE-0V": g0v["archive_sha256"],
            "GATE-5": g5["archive_sha256"],
        },
    })
    records = {
        "upstream_gate32_record": g34,
        "upstream_gate0v_record": g0v,
        "upstream_gate5_oq012_record": g5,
    }
    store = {r["record_id"]: dict(r) for r in records.values()}
    return records, store


def seal_gate33_current_assay_record(
    payload: Mapping[str, Any],
    *,
    arm_manifest: Optional[Dict[str, Any]] = None,
    record_id: Optional[str] = None,
    decision: Optional[str] = None,
    authority_scope: Optional[str] = None,
    bank_qualified: Optional[bool] = None,
    promotion_authorized: Optional[bool] = None,
) -> Dict[str, Any]:
    """Build and SHA-256-seal a v2_round5_unified collision-free GATE-35 current_assay_evidence_record from payload measurements."""
    manifest, err = _get_verified_canonical_manifest(arm_manifest)
    require_cond(manifest is not None and err is None, f"Cannot seal current_assay record without verified manifest: {err}")
    arm_key = str(payload.get("arm_key", "Y"))
    spec = manifest["arms"].get(arm_key)
    bank_origin = spec["cell_origin"] if isinstance(spec, dict) else "allogeneic_hiPSC"
    product_id = str(payload.get("product_id", spec["product_id"] if isinstance(spec, dict) else "UNKNOWN"))
    lot_id = str(payload.get("lot_id", "LOT-UNKNOWN"))
    bank_id = str(payload.get("bank_id", f"BANK-{arm_key}-001"))
    c_sha = str(payload.get("construct_manifest_sha256") or _fixture_construct_manifest_sha256(arm_key, product_id))
    ev_tier = str(payload.get("evidence_tier", "SYNTHETIC_FIXTURE"))
    is_synth = (ev_tier == "SYNTHETIC_FIXTURE")
    is_promo = (payload.get("evaluation_scope") == "CLINICAL_PROMOTION")
    scale_m = payload.get("scale_mode")

    if decision is None:
        if is_synth:
            decision = "SYNTHETIC_SELF_TEST_PASS" if is_promo else "SYNTHETIC_SELF_TEST_BOOKING_PASS"
        elif not is_promo:
            decision = "PASS_STAGE0_CANDIDATE_EXPERIMENT_BOOKING_ONLY"
        elif scale_m == "ANIMAL_PRECLINICAL_SCALE":
            decision = "STAGE_LIMITED_PRECLINICAL_ONLY"
        else:
            decision = "PASS_GATE35_CURRENT_ASSAY_VERIFIED"
    if authority_scope is None:
        if is_synth:
            authority_scope = "SYNTHETIC_SELF_TEST"
        elif (not is_promo) or (scale_m == "ANIMAL_PRECLINICAL_SCALE"):
            authority_scope = "BANK_QUALIFICATION_ONLY"
        else:
            authority_scope = "CLINICAL_LOT_RELEASE"
    if bank_qualified is None:
        bank_qualified = False if is_synth else True
    if promotion_authorized is None:
        promotion_authorized = False if (is_synth or (not is_promo) or (scale_m == "ANIMAL_PRECLINICAL_SCALE")) else True

    body: Dict[str, Any] = {
        "schema_revision": UPSTREAM_RECEIPT_SCHEMA_REVISION,
        "record_id": record_id if record_id is not None else f"REC-G35-CUR-{arm_key}-{lot_id}",
        "gate_source": "GATE-35",
        "product_id": product_id,
        "lot_id": lot_id,
        "bank_id": bank_id,
        "bank_origin": bank_origin,
        "canonical_arm_manifest_sha256": EXPECTED_CANONICAL_MANIFEST_SHA256,
        "construct_manifest_sha256": c_sha,
        "evidence_tier": ev_tier,
        "decision": decision,
        "authority_scope": authority_scope,
        "bank_qualified": bank_qualified,
        "promotion_authorized": promotion_authorized,
    }

    all_candidate_fields: Tuple[str, ...] = (
        CURRENT_ASSAY_ALWAYS_BOUND_FIELDS
        + CURRENT_ASSAY_STAGE1_OMENTUM_BOUND_FIELDS
        + CURRENT_ASSAY_STAGE1_COMMON_BOUND_FIELDS
        + CURRENT_ASSAY_EXVIVO_REST_STAGE0_BOUND_FIELDS
        + CURRENT_ASSAY_EXVIVO_REST_STAGE1_BOUND_FIELDS
        + ("measured_bed_po2_mmhg",)
    )
    for fname in all_candidate_fields:
        if fname in payload and payload[fname] is not None:
            body[fname] = payload[fname]

    load_v = payload.get("areal_loading_ieq_per_cm2")
    if load_v is None:
        load_v = payload.get("areal_loading_ieq_cm2")
    if load_v is not None:
        body["areal_loading_ieq_per_cm2"] = load_v

    return seal_upstream_evidence_record(body)


seal_gate35_current_assay_record = seal_gate33_current_assay_record


def sync_gate33_fixture_current_assay_and_store(
    payload: Dict[str, Any],
    store: Optional[Dict[str, Dict[str, Any]]] = None,
    *,
    arm_manifest: Optional[Dict[str, Any]] = None,
    index_by_sha: bool = False,
) -> Tuple[Dict[str, Any], Dict[str, Dict[str, Any]]]:
    """Return a copy of payload with re-sealed GATE-35 current_assay_evidence_record and an updated trusted store."""
    out_payload = dict(payload)
    cur_rec = seal_gate33_current_assay_record(out_payload, arm_manifest=arm_manifest)
    out_payload["current_assay_evidence_record"] = cur_rec
    out_store: Dict[str, Dict[str, Any]] = dict(store) if store is not None else {}
    if index_by_sha:
        out_store[cur_rec["archive_sha256"]] = dict(cur_rec)
    else:
        out_store[cur_rec["record_id"]] = dict(cur_rec)
    return out_payload, out_store


def _make_per_leaf_records(
    *,
    loading_ieq_cm2: float,
    total_ieq: float,
    bed_bot: float,
    bed_top: float,
    face_o2: float,
    core_o2: float,
    thickness_um: float = 120.0,
    d_o2_matrix_m2_s: float = 1.50e-9,
    n_leaves: int = 2,
) -> Tuple[float, List[Dict[str, Any]]]:
    """Build physically reconciled separated-leaf records with implied loading <= loading_ieq_cm2."""
    total_area_cm2 = math.ceil((total_ieq / loading_ieq_cm2) * 10000.0) / 10000.0
    leaf_ieq = total_ieq / float(n_leaves)
    leaf_area = total_area_cm2 / float(n_leaves)
    leaves = [
        {
            "leaf_id": f"LEAF-{i:02d}",
            "loaded_ieq": leaf_ieq,
            "measured_area_cm2": leaf_area,
            "measured_thickness_um": thickness_um,
            "measured_d_o2_matrix_m2_s": d_o2_matrix_m2_s,
            "measured_face_o2_mmhg": face_o2,
            "measured_core_o2_mmhg": core_o2,
            "bed_face_bot_po2_mmhg": bed_bot,
            "bed_face_top_po2_mmhg": bed_top,
            "direct_o2_sensor_coverage_verified": True,
        }
        for i in range(1, n_leaves + 1)
    ]
    return total_area_cm2, leaves


def _make_subject_cohorts(lot_id: str, *, capsule_um: float = 8.8, retrieval_pct: float = 99.94) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
    porcine = [
        {
            "subject_id": f"PIG-{i:02d}",
            "species": "PORCINE",
            "lot_id": lot_id,
            "followup_duration_days": 90.0,
            "capsule_sampling_day": 90.0,
            "retrieval_assessment_day": 90.0,
            "survival_to_endpoint": True,
            "major_hemorrhage_or_dehiscence": False,
            "bowel_obstruction_event": False,
            "omental_torsion_event": False,
            "grade3_adhesion_event": False,
            "monitored_complications": [],
            "surgical_safety_pass": True,
            "month3_capsule_um": capsule_um,
            "retrieval_mass_pct": retrieval_pct,
            "total_implanted_cells": 450_000_000,
            "residual_viable_cells_measured": 135_000,
            "residual_sampling_fraction": 0.50,
            "localization_verified": True,
        }
        for i in range(1, 7)
    ]
    nhp = [
        {
            "subject_id": f"NHP-{i:02d}",
            "species": "NHP",
            "lot_id": lot_id,
            "preimplant_diabetic_verified": True,
            "baseline_exogenous_insulin_u_kg_d": 0.85,
            "baseline_fasting_c_peptide_ng_ml": 0.05,
            "dose_ieq_per_kg": 9200.0,
            "achieved_insulin_independence": True if i <= 3 else False,
            "followup_duration_days": 91.0 if i <= 3 else 90.0,
            "capsule_sampling_day": 90.0,
            "omentectomy_performed": True if i <= 3 else None,
            "omentectomy_procedure_id": f"OMENT-NHP-{i:02d}" if i <= 3 else None,
            "omentectomy_day": 90.0 if i <= 3 else None,
            "cpeptide_extinction_subject_id": f"NHP-{i:02d}" if i <= 3 else None,
            "cpeptide_extinction_procedure_id": f"OMENT-NHP-{i:02d}" if i <= 3 else None,
            "cpeptide_extinction_assessment_day": 91.0 if i <= 3 else None,
            "post_omentectomy_cpeptide_extinguished": True if i <= 3 else None,
            "lloq_c_peptide_ng_ml": 0.05 if i <= 3 else None,
            "pre_explant_stimulated_c_peptide_ng_ml": 1.85 if i <= 3 else None,
            "post_explant_stimulated_c_peptide_ng_ml": 0.02 if i <= 3 else None,
            "portal_gradient_assessment_day": 90.0 if i <= 3 else None,
            "insulin_indep_day": (28.0 + 4.0 * i) if i <= 3 else None,
            "bowel_obstruction_event": False,
            "omental_torsion_event": False,
            "grade3_adhesion_event": False,
            "monitored_complications": [],
            "month3_capsule_um": capsule_um,
            "residual_exogenous_insulin_u_kg_d": 0.0 if i <= 3 else 0.15,
            "paired_dynamic_gsis_pass": True if i <= 3 else False,
            "retrieval_mass_pct": retrieval_pct,
            "total_implanted_cells": 140_000_000,
            "residual_viable_cells_measured": 42_000,
            "residual_sampling_fraction": 0.50,
            "localization_verified": True,
        }
        for i in range(1, 5)
    ]
    return porcine, nhp


def make_synthetic_valid_gate33_payload(
    arm_manifest: Dict[str, Any],
    *,
    arm_key: str = "D",
    site: str = "R4_OMENTUM_LEAD",
    scope: str = "CLINICAL_PROMOTION",
    exvivo_rest_applied: bool = True,
    evidence_tier: str = "SYNTHETIC_FIXTURE",
    lot_id: Optional[str] = None,
    bank_id: Optional[str] = None,
    construct_manifest_sha256: Optional[str] = None,
    upstream_records: Optional[Dict[str, Dict[str, Any]]] = None,
    dec009_primate_free: bool = False,
) -> Dict[str, Any]:
    """Build a complete Round-14 Gate-35 fixture with sealed current_assay_evidence_record (default SYNTHETIC_FIXTURE)."""
    spec = arm_manifest["arms"][arm_key]
    eff_lot = lot_id if lot_id is not None else (
        f"SYNTH-LOT-{arm_key}-001" if evidence_tier == "SYNTHETIC_FIXTURE" else f"MOCK-WETLAB-LOT-{arm_key}-001"
    )
    eff_bank = bank_id if bank_id is not None else f"BANK-{arm_key}-001"
    eff_csha = construct_manifest_sha256 if construct_manifest_sha256 is not None else _fixture_construct_manifest_sha256(arm_key, spec["product_id"])
    if upstream_records is not None:
        upstream_recs = {k: dict(v) for k, v in upstream_records.items()}
        up_src_rec = upstream_recs.get("upstream_gate34_record") or upstream_recs.get("upstream_gate32_record")
        if isinstance(up_src_rec, dict) and "construct_manifest_sha256" in up_src_rec:
            eff_csha = str(up_src_rec["construct_manifest_sha256"])
    else:
        upstream_recs, _ = _make_upstream_fixture_bundle(
            arm_manifest, arm_key=arm_key, lot_id=eff_lot, evidence_tier=evidence_tier,
            bank_id=eff_bank, construct_manifest_sha256=eff_csha,
        )
    porcine_subjs, nhp_subjs = _make_subject_cohorts(eff_lot, capsule_um=8.8, retrieval_pct=99.94)
    total_ieq = 500_000.0 if site == "R4_OMENTUM_LEAD" else 300_000.0
    total_area_cm2, leaf_recs = _make_per_leaf_records(
        loading_ieq_cm2=1200.0,
        total_ieq=total_ieq,
        bed_bot=36.0,
        bed_top=37.0,
        face_o2=16.12,
        core_o2=14.16,
        thickness_um=120.0,
        d_o2_matrix_m2_s=1.50e-9,
        n_leaves=2,
    )

    stage1_pathway_fields: Dict[str, Any] = {}
    if dec009_primate_free:
        stage1_pathway_fields.update({
            "dec009_primate_free_pathway": True,
            "dec009_pillar1_humanized_mouse_efficacy_pass": True,
            "dec009_pillar2_chandler_loop_50donor_pass": True,
            "dec009_pillar1_glp_biodistribution_erasure_pass": True,
            "dec009_post_explant_cpeptide_extinction_verified": True,
            "porcine_portal_peripheral_insulin_gradient": 1.85,
        })
    else:
        stage1_pathway_fields.update({
            "dec009_primate_free_pathway": False,
            "dec009_fda_cber_nhp_exception_authorized": True,
            "nhp_subjects": nhp_subjs,
            "nhp_r4o05_portal_peripheral_insulin_gradient": 1.85,
            "nhp_r4o05_post_omentectomy_cpeptide_extinction": True,
        })

    base: Dict[str, Any] = {
        "evaluation_scope": scope,
        "evidence_tier": evidence_tier,
        "lot_id": eff_lot,
        "bank_id": eff_bank,
        "canonical_arm_manifest_sha256": EXPECTED_CANONICAL_MANIFEST_SHA256,
        "construct_manifest_sha256": eff_csha,
        "deployment_site": site,
        "arm_key": arm_key,
        "product_id": spec["product_id"],
        "safety_switch_id": spec["safety_switch"],
        "dual_switch_lot_qualified": bool(spec["dual_switch_required_for_release"]),
        **upstream_recs,
        "clinical_matrix_id": (
            "GMP_AUTOLOGOUS_PLASMA_THROMBIN" if site == "R4_OMENTUM_LEAD" else "BIODEGRADABLE_THIN_PLANAR_CARRIER_SHEET"
        ),
        "needle_microtracks_used": False,
        "coformulated_immune_cuff_agents": ["sCR1_v2", "THBD-M406L", "CD200-ECD"],
        "polyglactin_sutures_used": False,
        "ductal_cytokeratin_impurity_pct": 1.1,
        "endotoxin_eu_per_ml": 0.12,
        "sterility_pass": True,
        "mycoplasma_negative": True,
        "analytical_fasl_ug": 0.0,
        "hepatocyte_72h_caspase37_u95_fold": 1.04,
        "hepatocyte_72h_alt_ldh_u95_fold": 1.06,
        "cuff_leachate_assay_passed": True,
        "construct_layout": "STAGGERED_BILAYER",
        "construct_thickness_um": 120.0,
        "cluster_min_diam_um": 54.0,
        "cluster_d_rms3_um": 59.5,
        "cluster_d_p95_um": 62.5,
        "cluster_max_diam_um": 64.5,
        "staggered_bilayer_plane_offset_um": 20.0,
        "bilateral_vascular_perfusion_verified": True,
        "back_to_back_unperfused_stacking": False,
        "scale_mode": "CLINICAL_HUMAN_SCALE",
        "total_implanted_ieq": total_ieq,
        "total_loaded_area_cm2": total_area_cm2,
        "per_leaf_records": leaf_recs,
        "areal_loading_ieq_cm2": 1200.0,
        "bed_face_bot_po2_mmhg": 36.0,
        "bed_face_top_po2_mmhg": 37.0,
        "measured_fibrin_capsule_um": 9.5,
        "measured_worst_face_o2_mmhg": 16.12,
        "measured_worst_core_o2_mmhg": 14.16,
        "measured_lot_ocr_mult": 1.097,
        "route_specific_clean_t50_min": 2.27,
        "route_specific_fibrin_t50_min": 2.73,
        "route_specific_gsis_si": 3.8,
        "porcine_r4o04_zero_bowel_obstruction_torsion_grade3_adhesions": True,
        "porcine_subjects": porcine_subjs,
        **stage1_pathway_fields,
        "invivo_diazoxide_depot_or_credit_claimed": False,
        "r3p06_5day_glycemic_clamp_enabled": True,
        "exvivo_rest_applied": exvivo_rest_applied,
        "exvivo_preconditioning_agents": ["DIAZOXIDE_GMP", "TUDCA_GMP"] if exvivo_rest_applied else [],
        "exvivo_diazoxide_uM": 125.0,
        "exvivo_tudca_uM": 250.0,
        "exvivo_preconditioning_hours": 22.0,
        "h46e01_fccp_max_reserve_pct_ctrl": 91.5,
        "washout_cycles_n": 3,
        "lcms_supernatant_diazoxide_uM": 0.015,
        "lcms_pellet_diazoxide_uM": 0.021,
        "rest_assay_lot_id": eff_lot,
        "rest_challenge_o2_pct": 2.0,
        "rest_two_pulse_gsis_verified": True,
        "rest_pulse1_si_rested": 3.9,
        "rest_pulse1_si_control": 3.7,
        "rest_pulse2_si_rested": 3.7,
        "rest_pulse2_si_control": 3.5,
        "oq018_post_washout_t50_min": 2.33,
        "oq018_post_washout_t50_fold_ctrl": 1.03,
        "oq018_post_washout_gsis_si": 3.8,
        "oq018_post_washout_first_phase_auc_pct_ctrl": 94.0,
        "oq018_post_washout_first_phase_auc_l95_pct_ctrl": 89.0,
        "oq018_post_washout_glucagon_pct_ctrl": 92.0,
        "h46e03_paired_hypoxic_necrosis_reduction_pct": 41.0,
        "rest_endpoint_type": "day14_stimulated_c_peptide",
        "rest_collection_day": 14.0,
        "rest_endpoint_rested_value": 1.92,
        "rest_endpoint_control_value": 1.50,
        "h46e04_day14_cpeptide_or_mass_fold_ctrl": 1.28,
        "h46e04_zero_secretory_delay_verified": True,
    }
    base["current_assay_evidence_record"] = seal_gate33_current_assay_record(base, arm_manifest=arm_manifest)
    return base


def make_mock_authenticated_wetlab_fixture_and_store(
    arm_manifest: Dict[str, Any],
    *,
    arm_key: str = "Y",
    site: str = "R4_OMENTUM_LEAD",
    scope: str = "CLINICAL_PROMOTION",
    exvivo_rest_applied: bool = True,
    lot_id: Optional[str] = None,
    bank_id: Optional[str] = None,
    construct_manifest_sha256: Optional[str] = None,
    upstream_records: Optional[Dict[str, Dict[str, Any]]] = None,
    dec009_primate_free: bool = False,
) -> Tuple[Dict[str, Any], Dict[str, Dict[str, Any]]]:
    """Unit-test helper returning an AUTHENTICATED_ARCHIVED_WETLAB mock payload + matching 4-record sealed trusted store."""
    payload = make_synthetic_valid_gate33_payload(
        arm_manifest,
        arm_key=arm_key,
        site=site,
        scope=scope,
        exvivo_rest_applied=exvivo_rest_applied,
        evidence_tier="AUTHENTICATED_ARCHIVED_WETLAB",
        lot_id=lot_id,
        bank_id=bank_id,
        construct_manifest_sha256=construct_manifest_sha256,
        upstream_records=upstream_records,
        dec009_primate_free=dec009_primate_free,
    )
    store: Dict[str, Dict[str, Any]] = {}
    for rk in (
        "upstream_gate34_record",
        "upstream_gate32_record",
        "upstream_gate0v_record",
        "upstream_gate5_oq012_record",
        "current_assay_evidence_record",
    ):
        rec = payload.get(rk)
        if isinstance(rec, dict) and "record_id" in rec:
            store[rec["record_id"]] = dict(rec)
    return payload, store


def run_gate33_synthetic_adjudicator_self_tests(arm_manifest: Dict[str, Any]) -> Dict[str, Any]:
    """Synthetic self-tests for Gate-35 code correctness (ALL SYNTHETIC_FIXTURE cases return promotion_authorized=False!)."""
    def _resync(p: Dict[str, Any]) -> Dict[str, Any]:
        out = dict(p)
        out["current_assay_evidence_record"] = seal_gate33_current_assay_record(out, arm_manifest=arm_manifest)
        return out

    def _with_leaves(
        base: Dict[str, Any],
        *,
        loading: float,
        bed_bot: float,
        bed_top: float,
        face_o2: float,
        core_o2: float,
        total_ieq: float = 500_000.0,
        thickness_um: float = 120.0,
        d_o2_matrix_m2_s: float = 1.50e-9,
        n_leaves: int = 2,
    ) -> Dict[str, Any]:
        area, leaves = _make_per_leaf_records(
            loading_ieq_cm2=loading,
            total_ieq=total_ieq,
            bed_bot=bed_bot,
            bed_top=bed_top,
            face_o2=face_o2,
            core_o2=core_o2,
            thickness_um=thickness_um,
            d_o2_matrix_m2_s=d_o2_matrix_m2_s,
            n_leaves=n_leaves,
        )
        return _resync({
            **base,
            "areal_loading_ieq_cm2": loading,
            "total_implanted_ieq": total_ieq,
            "total_loaded_area_cm2": area,
            "per_leaf_records": leaves,
            "bed_face_bot_po2_mmhg": bed_bot,
            "bed_face_top_po2_mmhg": bed_top,
            "measured_worst_face_o2_mmhg": face_o2,
            "measured_worst_core_o2_mmhg": core_o2,
        })

    om_d = make_synthetic_valid_gate33_payload(arm_manifest, arm_key="D", site="R4_OMENTUM_LEAD")
    om_d_dec009_pf = make_synthetic_valid_gate33_payload(arm_manifest, arm_key="D", site="R4_OMENTUM_LEAD", dec009_primate_free=True)
    p_t2, n_t2 = _make_subject_cohorts("SYNTH-LOT-Y-001", capsule_um=11.5, retrieval_pct=99.94)
    om_y_t2 = _resync({
        **_with_leaves(
            make_synthetic_valid_gate33_payload(arm_manifest, arm_key="Y", site="R4_OMENTUM_LEAD"),
            loading=1500.0, bed_bot=41.0, bed_top=42.0, face_o2=16.14, core_o2=14.49,
        ),
        "clinical_matrix_id": "GMP_RESORBABLE_FIBRIN",
        "measured_fibrin_capsule_um": 11.5,
        "route_specific_fibrin_t50_min": 2.81,
        "porcine_subjects": p_t2,
        "nhp_subjects": n_t2,
    })
    p_u, n_u = _make_subject_cohorts("SYNTH-LOT-Y-001", capsule_um=12.0, retrieval_pct=99.94)
    om_union_1200 = _resync({
        **_with_leaves(om_y_t2, loading=1200.0, bed_bot=40.0, bed_top=40.0, face_o2=16.14, core_o2=14.49),
        "measured_fibrin_capsule_um": 12.0,
        "porcine_subjects": p_u,
        "nhp_subjects": n_u,
    })
    om_union_1201 = _with_leaves(om_union_1200, loading=1201.0, bed_bot=40.0, bed_top=40.0, face_o2=16.14, core_o2=14.49)

    om_z_no_rest = make_synthetic_valid_gate33_payload(arm_manifest, arm_key="Z", site="R4_OMENTUM_LEAD", exvivo_rest_applied=False)
    sars_y = make_synthetic_valid_gate33_payload(arm_manifest, arm_key="Y", site="R4_SARS_FREE_BACKUP")
    booking_y = make_synthetic_valid_gate33_payload(arm_manifest, arm_key="Y", site="R4_OMENTUM_LEAD", scope="STAGE0_EXPERIMENT_BOOKING")
    for k in (
        "porcine_subjects",
        "nhp_subjects",
        "porcine_r4o04_zero_bowel_obstruction_torsion_grade3_adhesions",
        "porcine_portal_peripheral_insulin_gradient",
        "nhp_r4o05_portal_peripheral_insulin_gradient",
        "nhp_r4o05_post_omentectomy_cpeptide_extinction",
        "dec009_primate_free_pathway",
        "dec009_fda_cber_nhp_exception_authorized",
        "dec009_pillar1_humanized_mouse_efficacy_pass",
        "dec009_pillar2_chandler_loop_50donor_pass",
        "dec009_pillar1_glp_biodistribution_erasure_pass",
        "dec009_post_explant_cpeptide_extinction_verified",
        "rest_endpoint_type",
        "rest_collection_day",
        "rest_endpoint_rested_value",
        "rest_endpoint_control_value",
        "h46e04_day14_cpeptide_or_mass_fold_ctrl",
        "h46e04_zero_secretory_delay_verified",
    ):
        booking_y.pop(k, None)
    booking_y = _resync(booking_y)

    # Positive Round-4/6 surgical-only porcine check (pigs on 0.1 U/kg/d at exact Day-60 boundary MUST PASS!)
    pigs_surgical_day60 = [
        {
            **s,
            "followup_duration_days": 60.0,
            "capsule_sampling_day": 60.0,
            "retrieval_assessment_day": 60.0,
            "insulin_indep_day": 60.0,
            "residual_exogenous_insulin_u_kg_d": 0.1,
        }
        for s in om_d["porcine_subjects"]
    ]
    om_d_pigs_day60_ok = _resync({**om_d, "porcine_subjects": pigs_surgical_day60})

    def _drop_both(base: Dict[str, Any], key: str) -> Dict[str, Any]:
        """Drop a mandatory evidence field from BOTH parent and re-sealed current_assay record (genuine HOLD test)."""
        d = dict(base)
        d.pop(key, None)
        if key not in ("bank_id", "construct_manifest_sha256", "upstream_gate0v_record", "upstream_gate5_oq012_record", "current_assay_evidence_record"):
            d["current_assay_evidence_record"] = seal_gate33_current_assay_record(d, arm_manifest=arm_manifest)
        return d

    def _patch_sync(base: Dict[str, Any], patch: Dict[str, Any]) -> Dict[str, Any]:
        return _resync({**base, **patch})

    def _patch_nhp(base: Dict[str, Any], patch: Dict[str, Any]) -> Dict[str, Any]:
        subjs = [{**s, **patch} for s in base["nhp_subjects"]]
        return _resync({**base, "nhp_subjects": subjs})

    def _patch_nhp_one(base: Dict[str, Any], idx: int, patch: Dict[str, Any], *, drop_keys: Tuple[str, ...] = ()) -> Dict[str, Any]:
        subjs = [dict(s) for s in base["nhp_subjects"]]
        subjs[idx] = {**subjs[idx], **patch}
        for dk in drop_keys:
            subjs[idx].pop(dk, None)
        return _resync({**base, "nhp_subjects": subjs})

    def _patch_porcine(base: Dict[str, Any], patch: Dict[str, Any]) -> Dict[str, Any]:
        subjs = [{**s, **patch} for s in base["porcine_subjects"]]
        return _resync({**base, "porcine_subjects": subjs})

    def _patch_porcine_one(base: Dict[str, Any], idx: int, patch: Dict[str, Any]) -> Dict[str, Any]:
        subjs = [dict(s) for s in base["porcine_subjects"]]
        subjs[idx] = {**subjs[idx], **patch}
        return _resync({**base, "porcine_subjects": subjs})

    def _patch_leaves(base: Dict[str, Any], patch: Dict[str, Any]) -> Dict[str, Any]:
        leaves = [{**lf, **patch} for lf in base["per_leaf_records"]]
        return _resync({**base, "per_leaf_records": leaves})

    def _with_g5(
        base: Dict[str, Any],
        k_surv: int,
        n_test: int,
        u95_reported: Any,
        *,
        f_clon: Any = 0.50,
        eta_det: Any = 0.80,
        n_eff: Any = "AUTO",
        drop_keys: Tuple[str, ...] = (),
    ) -> Dict[str, Any]:
        eff_n_eff = int(n_test * f_clon * eta_det) if n_eff == "AUTO" else n_eff
        g5_body = {
            **{k: v for k, v in base["upstream_gate5_oq012_record"].items() if k != "archive_sha256"},
            "survivor_count_k": k_surv,
            "tested_cells_n": n_test,
            "clonogenic_fraction_f": f_clon,
            "spike_in_detection_efficiency_eta": eta_det,
            "effective_clonogenic_trials_n_eff": eff_n_eff,
            "u95_exact": u95_reported,
        }
        for dk in drop_keys:
            g5_body.pop(dk, None)
        g5_new = seal_upstream_evidence_record(g5_body)
        g34_body = {
            **{k: v for k, v in base["upstream_gate32_record"].items() if k != "archive_sha256"},
            "prerequisite_archive_sha256s": {
                "GATE-0V": base["upstream_gate0v_record"]["archive_sha256"],
                "GATE-5": g5_new["archive_sha256"],
            },
        }
        g34_new = seal_upstream_evidence_record(g34_body)
        return {**base, "upstream_gate5_oq012_record": g5_new, "upstream_gate32_record": g34_new}

    # Review #6 / Audit R4-03 actual max-leaf packing overlap fixtures (within 2% reported-vs-measured tolerance!)
    audit_r403_pack = _resync({
        **om_y_t2,
        "cluster_min_diam_um": 40.0,
        "cluster_d_rms3_um": 47.2981,
        "cluster_d_p95_um": 60.0,
        "cluster_max_diam_um": 65.0,
        "areal_loading_ieq_cm2": 1475.0,
        "total_implanted_ieq": 500_000.0,
        "total_loaded_area_cm2": 500_000.0 / 1500.0,
        "per_leaf_records": [
            {**om_y_t2["per_leaf_records"][0], "loaded_ieq": 250_000.0, "measured_area_cm2": 250_000.0 / 1500.0},
            {**om_y_t2["per_leaf_records"][1], "loaded_ieq": 250_000.0, "measured_area_cm2": 250_000.0 / 1500.0},
        ],
    })
    review_6_pack = _resync({
        **om_d,
        "cluster_min_diam_um": 40.0,
        "cluster_d_rms3_um": 43.9551,
        "cluster_d_p95_um": 60.0,
        "cluster_max_diam_um": 65.0,
        "areal_loading_ieq_cm2": 1180.0,
        "total_implanted_ieq": 500_000.0,
        "total_loaded_area_cm2": 500_000.0 / 1199.9999,
        "per_leaf_records": [
            {**om_d["per_leaf_records"][0], "loaded_ieq": 250_000.0, "measured_area_cm2": 250_000.0 / 1199.9999},
            {**om_d["per_leaf_records"][1], "loaded_ieq": 250_000.0, "measured_area_cm2": 250_000.0 / 1199.9999},
        ],
    })
    single_leaf_500k_animal = _resync({
        **om_d,
        "scale_mode": "ANIMAL_PRECLINICAL_SCALE",
        "total_implanted_ieq": 500_000.0,
        "total_loaded_area_cm2": 500_000.0 / 1200.0,
        "per_leaf_records": [{**om_d["per_leaf_records"][0], "loaded_ieq": 500_000.0, "measured_area_cm2": 500_000.0 / 1200.0}],
    })
    # Review #4: archived endotoxin 3.0 vs parent endotoxin 0.12
    om_d_adv_arch_endo = _resync({**om_d, "endotoxin_eu_per_ml": 3.0})
    om_d_adv_arch_parent_favorable = {**om_d_adv_arch_endo, "endotoxin_eu_per_ml": 0.12}

    # Round-10 Audit R9-06, Round-11 Audit R10-05 & Round-13 Audit R12-04: raw JSON lexical decimal helpers (parse_float=Decimal)
    def _patch_nhp_one_raw_json(base: Dict[str, Any], idx: int, json_fields: Dict[str, str]) -> Dict[str, Any]:
        patched = _patch_nhp_one(base, idx, {k: 999999 + i for i, k in enumerate(json_fields.keys())})
        raw = canonical_json_dumps(patched)
        for i, (k, tok) in enumerate(json_fields.items()):
            sentinel = f'"{k}":{999999 + i}'
            require_cond(sentinel in raw, f"Missing raw-JSON sentinel {sentinel}")
            raw = raw.replace(sentinel, f'"{k}":{tok}')
        parsed = load_strict_json_text(raw, "r10_raw_json_self_test")
        return _resync(parsed)

    def _patch_porcine_one_raw_json(base: Dict[str, Any], idx: int, json_fields: Dict[str, str]) -> Dict[str, Any]:
        patched = _patch_porcine_one(base, idx, {k: 999899 + i for i, k in enumerate(json_fields.keys())})
        raw = canonical_json_dumps(patched)
        for i, (k, tok) in enumerate(json_fields.items()):
            sentinel = f'"{k}":{999899 + i}'
            require_cond(sentinel in raw, f"Missing raw-JSON sentinel {sentinel}")
            raw = raw.replace(sentinel, f'"{k}":{tok}')
        parsed = load_strict_json_text(raw, "r13_porcine_raw_json_self_test")
        return _resync(parsed)

    def _patch_leaf_one_raw_json(base: Dict[str, Any], idx: int, json_fields: Dict[str, str]) -> Dict[str, Any]:
        leaves = [dict(lf) for lf in base["per_leaf_records"]]
        leaves[idx] = {**leaves[idx], **{k: 999799 + i for i, k in enumerate(json_fields.keys())}}
        patched = _resync({**base, "per_leaf_records": leaves})
        raw = canonical_json_dumps(patched)
        for i, (k, tok) in enumerate(json_fields.items()):
            sentinel = f'"{k}":{999799 + i}'
            require_cond(sentinel in raw, f"Missing raw-JSON sentinel {sentinel}")
            raw = raw.replace(sentinel, f'"{k}":{tok}')
        parsed = load_strict_json_text(raw, "r13_leaf_raw_json_self_test")
        return _resync(parsed)

    def _patch_top_raw_json(base: Dict[str, Any], json_fields: Dict[str, str]) -> Dict[str, Any]:
        patched = _patch_sync(base, {k: 999699 + i for i, k in enumerate(json_fields.keys())})
        raw = canonical_json_dumps(patched)
        for i, (k, tok) in enumerate(json_fields.items()):
            sentinel = f'"{k}":{999699 + i}'
            require_cond(sentinel in raw, f"Missing raw-JSON sentinel {sentinel}")
            raw = raw.replace(sentinel, f'"{k}":{tok}')
        parsed = load_strict_json_text(raw, "r13_top_raw_json_self_test")
        return _resync(parsed)

    def _with_g5_raw_u95(base: Dict[str, Any], k_surv: int, n_test: int, raw_u95_tok: str) -> Dict[str, Any]:
        u95_dec = load_strict_json_text(f'{{"u95_exact":{raw_u95_tok}}}', "r11_g5_raw_json")["u95_exact"]
        return _with_g5(base, k_surv, n_test, u95_dec)

    om_d_exact_face15_core5 = _resync(
        load_strict_json_text(
            canonical_json_dumps(
                _patch_leaves(
                    _patch_sync(om_d, {"measured_worst_face_o2_mmhg": 15.0, "measured_worst_core_o2_mmhg": 5.0}),
                    {"measured_face_o2_mmhg": 15.0, "measured_core_o2_mmhg": 5.0},
                )
            ),
            "r13_exact_15_5",
        )
    )

    # Round-14 collision-free GATE-34 / GATE-35 & partial-responder C-peptide extinction fixtures
    om_d_g34_key = {k: v for k, v in om_d.items() if k != "upstream_gate32_record"}
    om_d_g34_key["upstream_gate34_record"] = dict(om_d["upstream_gate32_record"])

    om_d_live_g32_collision = {
        **om_d,
        "upstream_gate32_record": seal_upstream_evidence_record({
            **{k: v for k, v in om_d["upstream_gate32_record"].items() if k != "archive_sha256"},
            "gate_source": "GATE-32",
        }),
    }
    om_d_live_g33_collision = {
        **om_d,
        "current_assay_evidence_record": seal_upstream_evidence_record({
            **{k: v for k, v in om_d["current_assay_evidence_record"].items() if k != "archive_sha256"},
            "gate_source": "GATE-33",
        }),
    }
    om_d_partial_responder_ext = _patch_nhp_one(
        om_d,
        3,
        {
            "achieved_insulin_independence": False,
            "residual_exogenous_insulin_u_kg_d": 0.25,
            "followup_duration_days": 91.0,
            "omentectomy_performed": True,
            "omentectomy_procedure_id": "OMENT-NHP-04",
            "omentectomy_day": 90.0,
            "cpeptide_extinction_subject_id": "NHP-04",
            "cpeptide_extinction_procedure_id": "OMENT-NHP-04",
            "cpeptide_extinction_assessment_day": 91.0,
            "post_omentectomy_cpeptide_extinguished": True,
            "lloq_c_peptide_ng_ml": 0.05,
            "pre_explant_stimulated_c_peptide_ng_ml": 0.45,
            "post_explant_stimulated_c_peptide_ng_ml": 0.02,
        },
    )

    # ALL SYNTHETIC_FIXTURE cases MUST yield promotion_authorized=False!
    cases: List[Tuple[str, Dict[str, Any], str, bool, Optional[str]]] = [
        ("pos_synth_tier1_omentum_d1b_k2_isolated", om_d, "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("pos_synth_r14_dec009_0nhp_primate_free_primary_passes", om_d_dec009_pf, "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("pos_synth_r14_upstream_gate34_record_key_passes", om_d_g34_key, "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("pos_synth_r14_partial_responder_cpeptide_extinction_passes", om_d_partial_responder_ext, "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("pos_synth_r14_gy028_exact_7p5um_wall_clearance_passes", _patch_sync(om_d, {"cluster_max_diam_um": 65.0, "staggered_bilayer_plane_offset_um": 20.0}), "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("pos_synth_tier2_omentum_design_y_v3_isolated", om_y_t2, "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("pos_synth_union_boundary_1200_at_40mmHg_12um", om_union_1200, "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("pos_synth_union_boundary_1201_at_40mmHg_12um", om_union_1201, "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("pos_synth_tier1_omentum_arm_z_zero_rest", om_z_no_rest, "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("pos_synth_sars_backup_design_y_v3", sars_y, "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("pos_synth_stage0_booking_isolated", booking_y, "SYNTHETIC_SELF_TEST_BOOKING_PASS", False, None),
        ("pos_synth_porcine_surgical_only_day60_0p1_insulin_passes", om_d_pigs_day60_ok, "SYNTHETIC_SELF_TEST_PASS", False, None),
        # Round-14 Live Blueprint section 7 OQ-012 Gate 5 exact checks (k=0, n_eff >= 299,573,228, eta >= 0.30, U95 <= 1e-8)
        ("pos_synth_r14_gate5_live_oq012_exact_299573228_passes", _with_g5(om_d, 0, 1_000_000_000, clopper_pearson_u95(0, 299_573_228), f_clon=0.50, eta_det=0.60, n_eff=299_573_228), "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("neg_hold_r14_gate5_live_oq012_299573227_underpowered_hold", _with_g5(om_d, 0, 1_000_000_000, clopper_pearson_u95(0, 299_573_227), f_clon=0.50, eta_det=0.60, n_eff=299_573_227), "HOLD", False, "HOLD_GATE5_OQ012_UNDERPOWERED_BELOW_299573228_EFFECTIVE_TRIALS"),
        ("neg_hold_r14_gate5_live_oq012_0_of_100k_underpowered_hold", _with_g5(om_d, 0, 100_000, clopper_pearson_u95(0, 40_000), f_clon=0.50, eta_det=0.80, n_eff=40_000), "HOLD", False, "HOLD_GATE5_OQ012_UNDERPOWERED_BELOW_299573228_EFFECTIVE_TRIALS"),
        ("neg_fail_r14_gate5_live_oq012_1_of_100k_survivor_fail", _with_g5(om_d, 1, 100_000, clopper_pearson_u95(1, 40_000), f_clon=0.50, eta_det=0.80, n_eff=40_000), "FAIL", False, "FAIL_GATE5_OQ012_NONZERO_SURVIVOR_OR_U95_GT_1E8"),
        ("neg_fail_r14_gate5_live_oq012_1_of_1e9_survivor_fail", _with_g5(om_d, 1, 1_000_000_000, clopper_pearson_u95(1, 400_000_000), f_clon=0.50, eta_det=0.80, n_eff=400_000_000), "FAIL", False, "FAIL_GATE5_OQ012_NONZERO_SURVIVOR_OR_U95_GT_1E8"),
        ("neg_fail_r14_gate5_live_oq012_eta_0p29_below_0p30_fail", _with_g5(om_d, 0, 2_000_000_000, clopper_pearson_u95(0, 290_000_000), f_clon=0.50, eta_det=0.29, n_eff=290_000_000), "FAIL", False, "FAIL_GATE5_OQ012_DETECTION_EFFICIENCY_ETA_LT_0P30"),
        ("neg_fail_r14_gate5_live_oq012_neff_exceeds_floor_n_f_eta_fail", _with_g5(om_d, 0, 1_000_000_000, clopper_pearson_u95(0, 400_000_001), f_clon=0.50, eta_det=0.80, n_eff=400_000_001), "FAIL", False, "FAIL_GATE5_OQ012_EFFECTIVE_TRIALS_EXCEEDS_FLOOR_N_F_ETA"),
        ("neg_hold_r14_gate5_live_oq012_omitted_recovery_denominator_hold", _with_g5(om_d, 0, 1_000_000_000, clopper_pearson_u95(0, 400_000_000), drop_keys=("clonogenic_fraction_f",)), "HOLD", False, "HOLD_GATE5_OQ012_INCOMPLETE_RECOVERY_DENOMINATOR"),
        ("neg_fail_r14_gate5_live_oq012_forged_u95_mismatch_fail", _with_g5(om_d, 0, 1_000_000_000, 1.0e-9, f_clon=0.50, eta_det=0.80, n_eff=400_000_000), "FAIL", False, "GATE5_UNDERSTATED_OR_FORGED_U95_EXACT"),
        # Round-14 live GATE-32 / GATE-33 role collisions, GY-028 >= 7.5 um wall clearance, DEC-009 pathway & decoupled C-peptide extinction
        ("neg_fail_r14_live_gate32_role_collision_rejected", om_d_live_g32_collision, "FAIL", False, "UPSTREAM_GATE34_LIVE_GATE32_ROLE_COLLISION_REJECTED"),
        ("neg_fail_r14_live_gate33_role_collision_rejected", om_d_live_g33_collision, "FAIL", False, "CURRENT_ASSAY_GATE35_LIVE_GATE33_ROLE_COLLISION_REJECTED"),
        ("neg_fail_r14_gy028_wall_clearance_5p25um_lt_7p5um_fail", _patch_sync(om_d, {"staggered_bilayer_plane_offset_um": 22.5, "cluster_max_diam_um": 64.5}), "FAIL", False, "GY028_WALL_CLEARANCE_LT_7P5UM_FAIL"),
        ("neg_fail_r14_gy028_sub_ulp_7p499999999999999um_fail", _patch_top_raw_json(om_d, {"staggered_bilayer_plane_offset_um": "20.000000000000001", "cluster_max_diam_um": "65.0"}), "FAIL", False, "GY028_WALL_CLEARANCE_LT_7P5UM_FAIL"),
        ("neg_hold_r14_partial_responder_missing_paired_cpeptide_lloq", _patch_nhp_one(om_d_partial_responder_ext, 3, {}, drop_keys=("lloq_c_peptide_ng_ml",)), "HOLD", False, "MISSING_NHP_PAIRED_STIMULATED_CPEPTIDE_OR_LLOQ"),
        ("neg_fail_r14_partial_responder_pre_cpeptide_le_lloq_fail", _patch_nhp_one(om_d_partial_responder_ext, 3, {"pre_explant_stimulated_c_peptide_ng_ml": 0.05}), "FAIL", False, "R4O_05_NHP_PRE_EXPLANT_CPEPTIDE_NOT_ABOVE_LLOQ_FAIL"),
        ("neg_fail_r14_partial_responder_post_cpeptide_gt_lloq_fail", _patch_nhp_one(om_d_partial_responder_ext, 3, {"post_explant_stimulated_c_peptide_ng_ml": 0.08}), "FAIL", False, "R4O_05_NHP_POST_EXPLANT_CPEPTIDE_EXCEEDS_LLOQ_FAIL"),
        ("neg_hold_r14_dec009_missing_pillar1_hold", _drop_both(om_d_dec009_pf, "dec009_pillar1_humanized_mouse_efficacy_pass"), "HOLD", False, "MISSING_DEC009_PILLAR1_HUMANIZED_MOUSE_EVIDENCE"),
        ("neg_fail_r14_dec009_unauthorized_nhp_exception_false_fail", _patch_sync(om_d, {"dec009_fda_cber_nhp_exception_authorized": False}), "FAIL", False, "DEC009_UNAUTHORIZED_NHP_COHORT_REJECTED"),
        ("neg_hold_r14_dec009_missing_nhp_exception_auth_hold", _drop_both(om_d, "dec009_fda_cber_nhp_exception_authorized"), "HOLD", False, "MISSING_DEC009_FDA_CBER_NHP_EXCEPTION_AUTHORIZATION"),
        ("neg_fail_r14_dec009_primate_free_with_unapproved_nhp_cohort_fail", _patch_sync(om_d_dec009_pf, {"nhp_subjects": om_d["nhp_subjects"]}), "FAIL", False, "DEC009_PRIMATE_FREE_PATHWAY_CONTRADICTS_NHP_COHORT_WITHOUT_FDA_EXCEPTION"),
        # Canonical arm manifest & switch rules
        ("neg_fail_gy027_1_design_a_on_r4", make_synthetic_valid_gate33_payload(arm_manifest, arm_key="A"), "FAIL", False, "GY027_1_BLOCK_UNHARDENED_ABX_PROHIBITED_ON_R4"),
        ("neg_fail_gy027_1_design_x_on_r4", make_synthetic_valid_gate33_payload(arm_manifest, arm_key="X"), "FAIL", False, "GY027_1_BLOCK_UNHARDENED_ABX_PROHIBITED_ON_R4"),
        ("neg_fail_d1b_single_switch_barred_from_sars_backup", make_synthetic_valid_gate33_payload(arm_manifest, arm_key="D", site="R4_SARS_FREE_BACKUP"), "FAIL", False, "D1B_LEAN_K2_SINGLE_SWITCH_BARRED_FROM_R4_SARS_BACKUP"),
        ("neg_fail_retired_cdk1_htmpk_switch", {**om_y_t2, "safety_switch_id": "Dual-FailSafe (iCasp9 + CDK1p::hTMPK)"}, "FAIL", False, "RETIRED_MISMATCHED_CDK1_HTMPK_SWITCH_PROHIBITED"),
        ("neg_fail_product_id_manifest_mismatch", {**om_d, "product_id": "ISLET1_DESIGN_Y_V3"}, "FAIL", False, "PRODUCT_ID_CANONICAL_MANIFEST_MISMATCH"),
        # Physical placement, geometry, steric packing, OCR, asymmetric bed, face O2, layout
        ("neg_fail_midplane_shift_zc_10um", _patch_sync(om_d, {"staggered_bilayer_plane_offset_um": 10.0}), "FAIL", False, "STAGGERED_BILAYER_PLANE_OFFSET_LT_20UM_FAIL"),
        ("neg_fail_impossible_10um_slab_sol_probe", _patch_sync(om_d, {"construct_thickness_um": 10.0}), "FAIL", False, "CONSTRUCT_THICKNESS_OUTSIDE_100_TO_120UM_FAIL"),
        ("neg_fail_20um_clusters_below_40um_domain", _patch_sync(om_d, {"cluster_min_diam_um": 20.0, "cluster_d_rms3_um": 20.0, "cluster_d_p95_um": 20.0, "cluster_max_diam_um": 20.0}), "FAIL", False, "CLUSTER_D_RMS3_OUTSIDE_40_TO_65UM_FAIL"),
        ("neg_fail_42_65um_1500_steric_overlap", _patch_sync(om_y_t2, {"cluster_min_diam_um": 40.0, "cluster_d_rms3_um": 42.0, "cluster_d_p95_um": 60.0, "cluster_max_diam_um": 65.0}), "FAIL", False, "STERIC_SAME_PLANE_PITCH_OVERLAP_FAIL"),
        ("neg_fail_monolayer_layout_rejected", _patch_sync(om_d, {"construct_layout": "MONOLAYER"}), "FAIL", False, "CONSTRUCT_LAYOUT_MUST_BE_STAGGERED_BILAYER"),
        ("neg_fail_lot_ocr_plus10pct", _patch_sync(om_d, {"measured_lot_ocr_mult": 1.2067}), "FAIL", False, "MEASURED_LOT_OCR_MULT_EXCEEDS_1P097_FAIL"),
        ("neg_fail_asymmetric_bed_25_45_mean35", _patch_sync(om_d, {"bed_face_bot_po2_mmhg": 25.0, "bed_face_top_po2_mmhg": 45.0}), "FAIL", False, "MIN_BILATERAL_BED_PO2_BELOW_35MMHG_ENVELOPE_FLOOR"),
        ("neg_fail_adverse_face_o2_14p6_mmhg", _patch_sync(om_d, {"measured_worst_face_o2_mmhg": 14.6028}), "FAIL", False, "MEASURED_WORST_FACE_O2_LT_15MMHG_FAIL"),
        ("neg_fail_adverse_core_o2_4p5_mmhg", _patch_sync(om_d, {"measured_worst_core_o2_mmhg": 4.5}), "FAIL", False, "MEASURED_WORST_CORE_O2_LT_5MMHG_FAIL"),
        ("neg_fail_tier2_1500_at_35mmHg_bed", _patch_sync(om_y_t2, {"bed_face_bot_po2_mmhg": 35.0, "bed_face_top_po2_mmhg": 35.0}), "FAIL", False, "TIER2_LOADING_GT_1200_REQUIRES_MIN_BILATERAL_BED_PO2_GE_40MMHG"),
        ("neg_fail_retired_1800_loading_cap", _patch_sync(om_y_t2, {"areal_loading_ieq_cm2": 1800.0}), "FAIL", False, "AREAL_LOADING_EXCEEDS_OMENTUM_ENVELOPE_CAP_1500_IEQ_CM2"),
        ("neg_fail_tier1_fibrin_gt_10um_at_36mmHg", _patch_sync(om_d, {"measured_fibrin_capsule_um": 11.0}), "FAIL", False, "TIER1_FIBRIN_CAPSULE_EXCEEDS_10UM_CEILING_AT_BED_LT_40MMHG"),
        ("neg_fail_retired_19um_fibrin", _patch_sync(om_y_t2, {"measured_fibrin_capsule_um": 19.0}), "FAIL", False, "FIBRIN_CAPSULE_EXCEEDS_12UM_MAX_ENVELOPE_CEILING"),
        ("neg_fail_unilateral_perfusion", _patch_sync(om_d, {"bilateral_vascular_perfusion_verified": False}), "FAIL", False, "UNILATERAL_PERFUSION_ANOXIA_FAIL"),
        ("neg_fail_back_to_back_folded_stacking", _patch_sync(om_d, {"back_to_back_unperfused_stacking": True}), "FAIL", False, "BACK_TO_BACK_UNPERFUSED_FOLDED_STACKING_PROHIBITED"),
        ("neg_fail_cluster_max_diam_200um", _patch_sync(om_d, {"cluster_max_diam_um": 200.0}), "FAIL", False, "CLUSTER_MAX_DIAM_EXCEEDS_65UM_SIEVING_LAW"),
        ("neg_fail_sars_backup_loading_1500", _patch_sync(sars_y, {"areal_loading_ieq_cm2": 1500.0}), "FAIL", False, "SARS_BACKUP_LOADING_EXCEEDS_1200_IEQ_CM2_ENVELOPE_CAP"),
        # Round-4 P0 (Audit F4) + Round-5 P0 (Review #6 / Audit R4-03): per-leaf, actual max-leaf packing & scale_mode
        ("neg_fail_sol_f4_500k_over_300cm2_implied_1667", _patch_sync(om_d, {"total_implanted_ieq": 500_000.0, "total_loaded_area_cm2": 300.0}), "FAIL", False, "IMPLIED_TOTAL_LOADING_CONTRADICTS_REPORTED_LOADING_GT_2PCT_FAIL"),
        ("neg_fail_sol_f4_degraded_0p75x_matrix_d_o2", _patch_leaves(om_d, {"measured_d_o2_matrix_m2_s": 0.75 * D_O2_LOW_MODELED_M2_S}), "FAIL", False, "LEAF_MEASURED_D_O2_MATRIX_BELOW_LOW_D_FLOOR_FAIL"),
        ("neg_fail_sol_f4_sensor_coverage_unverified", _patch_leaves(om_d, {"direct_o2_sensor_coverage_verified": False}), "FAIL", False, "LEAF_DIRECT_O2_SENSOR_COVERAGE_UNVERIFIED_FAIL"),
        ("neg_fail_r5_sol_r403_actual_leaf_1500_vs_reported_1475_packing", audit_r403_pack, "FAIL", False, "STERIC_SAME_PLANE_PITCH_OVERLAP_FAIL"),
        ("neg_fail_r5_review6_actual_leaf_1199p9999_vs_reported_1180_packing", review_6_pack, "FAIL", False, "STERIC_SAME_PLANE_PITCH_OVERLAP_FAIL"),
        ("neg_fail_r5_single_leaf_500k_relabeled_animal_scale", single_leaf_500k_animal, "FAIL", False, "TOTAL_IEQ_GT_100K_REQUIRES_AT_LEAST_2_SEPARATED_LEAVES"),
        # Round-4/5/6 Stage-1 (Review #7 / Audit R4-04 / Audit R5-04): subject-level visit dates, typed monitored complications, >=1% sampling
        ("neg_fail_nondiabetic_nhp_cohort_0_of_4_eligible", _patch_nhp(om_d, {"preimplant_diabetic_verified": False, "baseline_exogenous_insulin_u_kg_d": 0.0, "insulin_indep_day": 0.0}), "FAIL", False, "R4O_05_NHP_ELIGIBLE_DIABETIC_N_LT_4_FAIL"),
        ("neg_hold_nhp_nonresponder_short_followup_60d", _patch_nhp_one(om_d, 3, {"followup_duration_days": 60.0, "capsule_sampling_day": None}), "HOLD", False, "HOLD_NHP_RIGHT_CENSORED_FOLLOWUP_LT_90D"),
        ("neg_fail_r5_nhp_responder_followup_day41_lt_90d", _resync({**om_d, "nhp_subjects": [{**s, "followup_duration_days": 41.0} if s["achieved_insulin_independence"] else s for s in om_d["nhp_subjects"]]}), "FAIL", False, "R4O_05_NHP_RESPONDER_FOLLOWUP_LT_90D_MONTH3_INCONSISTENT_FAIL"),
        ("neg_fail_r5_nhp_nonresponder_contradictory_day120_event", _patch_nhp_one(om_d, 3, {"insulin_indep_day": 120.0}), "FAIL", False, "R4O_05_NHP_NONRESPONDER_CONTRADICTORY_INSULIN_INDEP_DAY_FAIL"),
        # Round-6 Audit R5-04: Porcine & NHP subject-level measurement dates + typed monitored complications + aliases
        ("neg_fail_r6_porcine_day1_followup_and_capsule", _patch_porcine_one(om_d, 0, {"followup_duration_days": 1.0, "capsule_sampling_day": 1.0, "retrieval_assessment_day": 1.0}), "FAIL", False, "R4O_04_PORCINE_FOLLOWUP_LT_60D_FAIL"),
        ("neg_fail_r6_porcine_day1_capsule_with_90d_followup", _patch_porcine_one(om_d, 0, {"capsule_sampling_day": 1.0}), "FAIL", False, "R4O_04_PORCINE_CAPSULE_SAMPLING_DAY_LT_60D_FAIL"),
        ("neg_fail_r6_porcine_day1_retrieval_assessment", _patch_porcine_one(om_d, 0, {"retrieval_assessment_day": 1.0}), "FAIL", False, "R4O_04_PORCINE_RETRIEVAL_ASSESSMENT_DAY_LT_60D_FAIL"),
        ("neg_fail_r6_porcine_capsule_day_exceeds_followup", _patch_porcine_one(om_d, 0, {"followup_duration_days": 60.0, "capsule_sampling_day": 90.0, "retrieval_assessment_day": 60.0}), "FAIL", False, "R4O_04_PORCINE_CAPSULE_SAMPLING_DAY_EXCEEDS_FOLLOWUP_FAIL"),
        ("neg_fail_r6_porcine_bowel_obstruction_contradicts_aggregate", _patch_porcine_one(om_d, 0, {"bowel_obstruction_event": True}), "FAIL", False, "PORCINE_COMPLICATION_CONTRADICTS_AGGREGATE_ATTESTATION"),
        ("neg_fail_r6_porcine_bowel_obstruction_alias_contradicts_aggregate", _patch_porcine_one(om_d, 0, {"bowel_obstruction": True}), "FAIL", False, "PORCINE_COMPLICATION_CONTRADICTS_AGGREGATE_ATTESTATION"),
        ("neg_fail_r6_porcine_monitored_complications_nonempty", _patch_porcine_one(om_d, 0, {"monitored_complications": ["bowel_obstruction"]}), "FAIL", False, "PORCINE_COMPLICATION_CONTRADICTS_AGGREGATE_ATTESTATION"),
        ("neg_fail_r6_nhp_day1_capsule_sampling_with_90d_followup", _patch_nhp_one(om_d, 0, {"capsule_sampling_day": 1.0}), "FAIL", False, "R4O_05_NHP_CAPSULE_SAMPLING_DAY_LT_90D_FAIL"),
        ("neg_fail_r6_nhp_day1_capsule_alias_contradiction", _patch_nhp_one(om_d, 0, {"capsule_histology_day": 1.0}), "FAIL", False, "R4O_05_NHP_CAPSULE_DATE_ALIAS_LT_90D_FAIL:capsule_histology_day"),
        ("neg_fail_r6_nhp_day1_cpeptide_extinction_assessment", _patch_nhp_one(om_d, 0, {"cpeptide_extinction_assessment_day": 1.0}), "FAIL", False, "R4O_05_NHP_C_PEPTIDE_EXTINCTION_DAY_LT_90D_FAIL"),
        ("neg_fail_r6_nhp_day1_portal_gradient_assessment", _patch_nhp_one(om_d, 0, {"portal_gradient_assessment_day": 1.0}), "FAIL", False, "R4O_05_NHP_PORTAL_GRADIENT_DAY_LT_90D_FAIL"),
        ("neg_fail_r6_nhp_omental_torsion_event", _patch_nhp_one(om_d, 0, {"omental_torsion_event": True}), "FAIL", False, "R4O_05_NHP_OMENTAL_TORSION_EVENT_FAIL"),
        ("neg_hold_r6_porcine_missing_capsule_sampling_day", _patch_porcine_one(om_d, 0, {"capsule_sampling_day": None}), "HOLD", False, "MISSING_PORCINE_SUBJECT_FIELD:capsule_sampling_day"),
        ("neg_hold_r6_porcine_missing_bowel_obstruction_event", _patch_porcine_one(om_d, 0, {"bowel_obstruction_event": None}), "HOLD", False, "MISSING_PORCINE_SUBJECT_FIELD:bowel_obstruction_event"),
        ("neg_hold_r6_nhp_missing_capsule_sampling_day", _patch_nhp_one(om_d, 0, {"capsule_sampling_day": None}), "HOLD", False, "MISSING_NHP_SUBJECT_FIELD:capsule_sampling_day"),
        ("neg_hold_r6_nhp_missing_responder_cpeptide_extinction_day", _patch_nhp_one(om_d, 0, {"cpeptide_extinction_assessment_day": None}), "HOLD", False, "MISSING_NHP_RESPONDER_C_PEPTIDE_EXTINCTION_ASSESSMENT_DAY"),
        ("neg_hold_r6_nhp_missing_monitored_complications", _patch_nhp_one(om_d, 0, {"monitored_complications": None}), "HOLD", False, "MISSING_NHP_SUBJECT_FIELD:monitored_complications"),
        # Round-7 Audit R6-05: NHP omentectomy procedure/subject binding, strict chronology, procedure aliases & canonical subject_id dedup
        ("pos_synth_r7_chronological_day120_omentectomy_responder_and_day90_nonresponder", _patch_nhp_one(om_d, 0, {"omentectomy_day": 120.0, "portal_gradient_assessment_day": 118.0, "cpeptide_extinction_assessment_day": 121.0, "followup_duration_days": 125.0}), "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("neg_fail_r7_sol_r605_extinction_day90_precedes_omentectomy_day120", _patch_nhp_one(om_d, 0, {"omentectomy_day": 120.0, "cpeptide_extinction_assessment_day": 90.0, "followup_duration_days": 120.0}), "FAIL", False, "NHP_CPEP_EXTINCTION_PRECEDES_OMENTECTOMY_PROCEDURE"),
        ("neg_fail_r7_procedure_day_alias_120_vs_extinction_90", _patch_nhp_one(om_d, 0, {"procedure_day": 120.0, "cpeptide_extinction_assessment_day": 90.0, "followup_duration_days": 120.0}), "FAIL", False, "NHP_CPEP_EXTINCTION_PRECEDES_OMENTECTOMY_PROCEDURE"),
        ("neg_fail_r7_explant_day_alias_120_vs_extinction_90", _patch_nhp_one(om_d, 0, {"explant_day": 120.0, "cpeptide_extinction_assessment_day": 90.0, "followup_duration_days": 120.0}), "FAIL", False, "NHP_CPEP_EXTINCTION_PRECEDES_OMENTECTOMY_PROCEDURE"),
        ("neg_fail_r7_extinction_subject_id_mismatch", _patch_nhp_one(om_d, 0, {"cpeptide_extinction_subject_id": "NHP-02"}), "FAIL", False, "NHP_EXTINCTION_SUBJECT_ID_MISMATCH"),
        ("neg_fail_r7_extinction_procedure_id_mismatch", _patch_nhp_one(om_d, 0, {"cpeptide_extinction_procedure_id": "OMENT-NHP-02"}), "FAIL", False, "NHP_EXTINCTION_PROCEDURE_ID_MISMATCH"),
        ("neg_fail_r7_portal_gradient_post_omentectomy_invalid", _patch_nhp_one(om_d, 0, {"omentectomy_day": 120.0, "portal_gradient_assessment_day": 125.0, "cpeptide_extinction_assessment_day": 125.0, "followup_duration_days": 125.0}), "FAIL", False, "NHP_PORTAL_GRADIENT_POST_OMENTECTOMY_INVALID"),
        ("neg_fail_r7_responder_omentectomy_performed_false", _patch_nhp_one(om_d, 0, {"omentectomy_performed": False}), "FAIL", False, "R4O_05_NHP_RESPONDER_OMENTECTOMY_NOT_PERFORMED_FAIL"),
        ("neg_fail_r7_nhp_whitespace_duplicate_subject_id", _patch_nhp_one(om_d, 1, {"subject_id": "NHP-01 ", "cpeptide_extinction_subject_id": "NHP-01 "}), "FAIL", False, "DUPLICATE_NHP_SUBJECT_ID"),
        ("neg_fail_r7_porcine_whitespace_duplicate_subject_id", _patch_porcine_one(om_d, 1, {"subject_id": "PIG-01 "}), "FAIL", False, "DUPLICATE_PORCINE_SUBJECT_ID"),
        ("neg_hold_r7_nhp_missing_omentectomy_day", _patch_nhp_one(om_d, 0, {"omentectomy_day": None}), "HOLD", False, "MISSING_NHP_RESPONDER_OMENTECTOMY_DAY"),
        ("neg_hold_r7_nhp_missing_omentectomy_procedure_id", _patch_nhp_one(om_d, 0, {"omentectomy_procedure_id": None}), "HOLD", False, "MISSING_NHP_RESPONDER_OMENTECTOMY_PROCEDURE_ID"),
        ("neg_hold_r7_nhp_missing_omentectomy_performed", _patch_nhp_one(om_d, 0, {"omentectomy_performed": None}), "HOLD", False, "MISSING_NHP_RESPONDER_OMENTECTOMY_PERFORMED"),
        ("neg_hold_r7_nhp_missing_extinction_subject_id", _patch_nhp_one(om_d, 0, {"cpeptide_extinction_subject_id": None}), "HOLD", False, "MISSING_NHP_RESPONDER_C_PEPTIDE_EXTINCTION_SUBJECT_ID"),
        ("neg_hold_r7_nhp_missing_extinction_procedure_id", _patch_nhp_one(om_d, 0, {"cpeptide_extinction_procedure_id": None}), "HOLD", False, "MISSING_NHP_RESPONDER_C_PEPTIDE_EXTINCTION_PROCEDURE_ID"),
        # Round-8 Audit R7-08 & R7-13: nonresponder partial procedure/extinction tuples, conflicting alias groups, strict ASCII IDs & 14-day prompt window
        ("pos_synth_r8_prompt_14d_boundary_omentectomy90_extinction104_passes", _patch_nhp_one(om_d, 0, {"omentectomy_day": 90.0, "cpeptide_extinction_assessment_day": 104.0, "followup_duration_days": 104.0}), "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("pos_synth_r8_nonresponder_clean_performed_false_and_extinguished_false", _patch_nhp_one(om_d, 3, {"omentectomy_performed": False, "post_omentectomy_cpeptide_extinguished": False}), "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("neg_hold_r8_sol_r708_nonresponder_only_omentectomy_day", _patch_nhp_one(om_d, 3, {"omentectomy_day": 90.0}), "HOLD", False, "NHP_INCOMPLETE_PROCEDURE_OR_EXTINCTION_TUPLE"),
        ("neg_hold_r8_sol_r708_nonresponder_only_procedure_day_alias", _patch_nhp_one(om_d, 3, {"procedure_day": 90.0}), "HOLD", False, "NHP_INCOMPLETE_PROCEDURE_OR_EXTINCTION_TUPLE"),
        ("neg_hold_r8_sol_r708_nonresponder_only_omentectomy_procedure_id", _patch_nhp_one(om_d, 3, {"omentectomy_procedure_id": "OMENT-NHP-04"}), "HOLD", False, "NHP_INCOMPLETE_PROCEDURE_OR_EXTINCTION_TUPLE"),
        ("neg_hold_r8_sol_r708_nonresponder_only_procedure_id_alias", _patch_nhp_one(om_d, 3, {"procedure_id": "OMENT-NHP-04"}), "HOLD", False, "NHP_INCOMPLETE_PROCEDURE_OR_EXTINCTION_TUPLE"),
        ("neg_hold_r8_sol_r708_nonresponder_only_positive_extinction_without_tuple", _patch_nhp_one(om_d, 3, {"post_omentectomy_cpeptide_extinguished": True}), "HOLD", False, "NHP_INCOMPLETE_PROCEDURE_OR_EXTINCTION_TUPLE"),
        ("neg_hold_r8_sol_r708_nonresponder_only_extinction_subject_id", _patch_nhp_one(om_d, 3, {"cpeptide_extinction_subject_id": "NHP-04"}), "HOLD", False, "NHP_INCOMPLETE_PROCEDURE_OR_EXTINCTION_TUPLE"),
        ("neg_fail_r8_sol_r708_conflicting_nhp_procedure_date_aliases_100_vs_120", _patch_nhp_one(om_d, 3, {"followup_duration_days": 120.0, "procedure_day": 100.0, "explant_day": 120.0}), "FAIL", False, "NHP_CONFLICTING_DATE_ALIAS_GROUP"),
        ("neg_fail_r8_sol_r708_conflicting_porcine_capsule_date_aliases_90_vs_95", _patch_porcine_one(om_d, 0, {"followup_duration_days": 95.0, "capsule_sampling_day": 90.0, "capsule_histology_day": 95.0}), "FAIL", False, "PORCINE_CONFLICTING_DATE_ALIAS_GROUP"),
        ("neg_fail_r8_sol_r708_conflicting_nhp_extinction_outcome_aliases", _patch_nhp_one(om_d, 0, {"post_omentectomy_cpeptide_extinguished": True, "cpeptide_extinguished": False}), "FAIL", False, "NHP_CONFLICTING_EXTINCTION_OUTCOME_ALIAS_GROUP"),
        ("neg_fail_r8_sol_r708_conflicting_nhp_procedure_id_aliases", _patch_nhp_one(om_d, 3, {"procedure_id": "OMENT-NHP-04", "explant_procedure_id": "OMENT-NHP-99"}), "FAIL", False, "NHP_CONFLICTING_PROCEDURE_ID_ALIAS_GROUP"),
        ("neg_fail_r8_sol_r708_nonascii_zwsp_nhp_subject_id", _patch_nhp_one(om_d, 0, {"subject_id": "NHP-01\u200b", "cpeptide_extinction_subject_id": "NHP-01\u200b"}), "FAIL", False, "INVALID_NHP_SUBJECT_ID"),
        ("neg_fail_r8_sol_r708_nonascii_fullwidth_porcine_subject_id", _patch_porcine_one(om_d, 0, {"subject_id": "\uff30\uff29\uff27-01"}), "FAIL", False, "INVALID_PORCINE_SUBJECT_ID"),
        ("neg_fail_r8_sol_r713_prompt_window_exceeded_15d_oment90_ext105", _patch_nhp_one(om_d, 0, {"omentectomy_day": 90.0, "cpeptide_extinction_assessment_day": 105.0, "followup_duration_days": 105.0}), "FAIL", False, "NHP_CPEP_EXTINCTION_EXCEEDS_14D_PROMPT_WINDOW"),
        ("neg_fail_r8_sol_r713_prompt_window_exceeded_90d_oment90_ext180", _patch_nhp_one(om_d, 0, {"omentectomy_day": 90.0, "cpeptide_extinction_assessment_day": 180.0, "followup_duration_days": 180.0}), "FAIL", False, "NHP_CPEP_EXTINCTION_EXCEEDS_14D_PROMPT_WINDOW"),
        # Round-9 Audit R8-04 & R8-05: mandatory archived extinction outcome on claimed procedure tuple & exact Decimal [0, 14] d window (ZERO ungoverned tolerance)
        ("pos_synth_r9_sol_r804_nonresponder_full_proc_tuple_explicit_false_outcome", _patch_nhp_one(om_d, 3, {"followup_duration_days": 91.0, "omentectomy_performed": True, "omentectomy_procedure_id": "OMENT-NHP-04", "omentectomy_day": 90.0, "cpeptide_extinction_subject_id": "NHP-04", "cpeptide_extinction_procedure_id": "OMENT-NHP-04", "cpeptide_extinction_assessment_day": 91.0, "post_omentectomy_cpeptide_extinguished": False}), "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("neg_hold_r9_sol_r804_nonresponder_full_proc_tuple_none_outcome", _patch_nhp_one(om_d, 3, {"followup_duration_days": 91.0, "omentectomy_performed": True, "omentectomy_procedure_id": "OMENT-NHP-04", "omentectomy_day": 90.0, "cpeptide_extinction_subject_id": "NHP-04", "cpeptide_extinction_procedure_id": "OMENT-NHP-04", "cpeptide_extinction_assessment_day": 91.0, "post_omentectomy_cpeptide_extinguished": None}), "HOLD", False, "MISSING_NHP_POST_OMENTECTOMY_EXTINCTION_OUTCOME"),
        ("neg_hold_r9_sol_r804_nonresponder_full_proc_tuple_omitted_outcome_key", _patch_nhp_one(om_d, 3, {"followup_duration_days": 91.0, "omentectomy_performed": True, "omentectomy_procedure_id": "OMENT-NHP-04", "omentectomy_day": 90.0, "cpeptide_extinction_subject_id": "NHP-04", "cpeptide_extinction_procedure_id": "OMENT-NHP-04", "cpeptide_extinction_assessment_day": 91.0}, drop_keys=("post_omentectomy_cpeptide_extinguished",)), "HOLD", False, "MISSING_NHP_POST_OMENTECTOMY_EXTINCTION_OUTCOME"),
        ("neg_hold_r9_sol_r804_responder_omitted_extinction_outcome", _patch_nhp_one(om_d, 0, {}, drop_keys=("post_omentectomy_cpeptide_extinguished",)), "HOLD", False, "MISSING_NHP_POST_OMENTECTOMY_EXTINCTION_OUTCOME"),
        ("pos_synth_r9_sol_r805_exact_0d_window_90_to_90", _patch_nhp_one(om_d, 0, {"omentectomy_day": 90.0, "cpeptide_extinction_assessment_day": 90.0, "followup_duration_days": 90.0}), "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("pos_synth_r9_sol_r805_exact_14d_decimal_window_127p1_to_141p1", _patch_nhp_one(om_d, 0, {"omentectomy_day": 127.1, "portal_gradient_assessment_day": 127.0, "cpeptide_extinction_assessment_day": 141.1, "followup_duration_days": 141.1}), "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("neg_fail_r9_sol_r805_14d_plus_5e10_43p2us_over_window_fail", _patch_nhp_one(om_d, 0, {"omentectomy_day": 90.0, "cpeptide_extinction_assessment_day": 104.0 + 5e-10, "followup_duration_days": 105.0}), "FAIL", False, "NHP_CPEP_EXTINCTION_EXCEEDS_14D_PROMPT_WINDOW"),
        ("neg_fail_r9_sol_r805_14d_plus_2e9_172p8us_over_window_fail", _patch_nhp_one(om_d, 0, {"omentectomy_day": 90.0, "cpeptide_extinction_assessment_day": 104.0 + 2e-9, "followup_duration_days": 105.0}), "FAIL", False, "NHP_CPEP_EXTINCTION_EXCEEDS_14D_PROMPT_WINDOW"),
        ("neg_fail_r9_sol_r805_minus_5e10_43p2us_before_omentectomy_fail", _patch_nhp_one(om_d, 0, {"omentectomy_day": 95.0, "portal_gradient_assessment_day": 94.0, "cpeptide_extinction_assessment_day": 95.0 - 5e-10, "followup_duration_days": 105.0}), "FAIL", False, "NHP_CPEP_EXTINCTION_PRECEDES_OMENTECTOMY_PROCEDURE"),
        # Round-10 Audit R9-06: raw JSON lexical decimal preservation (parse_float=Decimal) blocking 86.4 ps (1e-15 d) sub-ULP drift!
        ("pos_synth_r10_sol_r906_raw_json_exact_14d_104p000000000000000", _patch_nhp_one_raw_json(om_d, 0, {"omentectomy_day": "90", "cpeptide_extinction_assessment_day": "104.000000000000000", "followup_duration_days": "105"}), "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("pos_synth_r10_sol_r906_raw_json_exact_14d_shifted_90p1e15_to_104p1e15", _patch_nhp_one_raw_json(om_d, 0, {"omentectomy_day": "90.000000000000001", "cpeptide_extinction_assessment_day": "104.000000000000001", "followup_duration_days": "105"}), "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("neg_fail_r10_sol_r906_raw_json_86p4ps_over_14d_104p000000000000001", _patch_nhp_one_raw_json(om_d, 0, {"omentectomy_day": "90", "cpeptide_extinction_assessment_day": "104.000000000000001", "followup_duration_days": "105"}), "FAIL", False, "NHP_CPEP_EXTINCTION_EXCEEDS_14D_PROMPT_WINDOW"),
        ("neg_fail_r10_sol_r906_raw_json_86p4ps_over_14d_shifted_90p1e15_to_104p2e15", _patch_nhp_one_raw_json(om_d, 0, {"omentectomy_day": "90.000000000000001", "cpeptide_extinction_assessment_day": "104.000000000000002", "followup_duration_days": "105"}), "FAIL", False, "NHP_CPEP_EXTINCTION_EXCEEDS_14D_PROMPT_WINDOW"),
        ("neg_fail_r10_sol_r906_raw_json_86p4ps_before_omentectomy_89p999999999999999", _patch_nhp_one_raw_json(om_d, 0, {"omentectomy_day": "90", "cpeptide_extinction_assessment_day": "89.999999999999999", "followup_duration_days": "105"}), "FAIL", False, "NHP_CPEP_EXTINCTION_PRECEDES_OMENTECTOMY_PROCEDURE"),
        ("neg_fail_r10_sol_r906_raw_json_86p4ps_before_omentectomy_95_to_94p999999999999999", _patch_nhp_one_raw_json(om_d, 0, {"omentectomy_day": "95", "portal_gradient_assessment_day": "94", "cpeptide_extinction_assessment_day": "94.999999999999999", "followup_duration_days": "105"}), "FAIL", False, "NHP_CPEP_EXTINCTION_PRECEDES_OMENTECTOMY_PROCEDURE"),
        # Round-11 Audit R10-05: context-independent Decimal bounds rejecting extreme finite JSON exponents with structured FAIL (zero decimal.Overflow)
        ("neg_fail_r11_sol_r1005_extreme_omentectomy_1e1000", _patch_nhp_one_raw_json(om_d, 0, {"omentectomy_day": "1e1000"}), "FAIL", False, "INVALID_NHP_OMENTECTOMY_DAY"),
        ("neg_fail_r11_sol_r1005_extreme_omentectomy_1e99999999", _patch_nhp_one_raw_json(om_d, 0, {"omentectomy_day": "1e99999999"}), "FAIL", False, "INVALID_NHP_OMENTECTOMY_DAY"),
        ("neg_fail_r11_sol_r1005_extreme_omentectomy_neg_1e99999999", _patch_nhp_one_raw_json(om_d, 0, {"omentectomy_day": "-1e99999999"}), "FAIL", False, "INVALID_NHP_OMENTECTOMY_DAY"),
        ("neg_fail_r11_sol_r1005_extreme_omentectomy_1e_minus99999999", _patch_nhp_one_raw_json(om_d, 0, {"omentectomy_day": "1e-99999999"}), "FAIL", False, "INVALID_NHP_OMENTECTOMY_DAY"),
        ("neg_fail_r11_sol_r1005_extreme_cpep_9p999e99999999", _patch_nhp_one_raw_json(om_d, 0, {"cpeptide_extinction_assessment_day": "9.999999999999999e+99999999"}), "FAIL", False, "INVALID_NHP_C_PEPTIDE_EXTINCTION_ASSESSMENT_DAY"),
        ("neg_fail_r11_sol_r1005_extreme_alias_post_oment_cpep_1e99999999", _patch_nhp_one_raw_json(om_d, 0, {"post_omentectomy_cpeptide_assessment_day": "1e99999999"}), "FAIL", False, "INVALID_NHP_DATE_ALIAS:post_omentectomy_cpeptide_assessment_day"),
        ("neg_fail_r11_sol_r1005_extreme_alias_proc_day_1e99999999", _patch_nhp_one_raw_json(om_d, 0, {"procedure_day": "1e99999999"}), "FAIL", False, "INVALID_NHP_DATE_ALIAS:procedure_day"),
        ("neg_fail_r11_sol_r1005_extreme_gate5_u95_1e99999999", _with_g5_raw_u95(om_d, 0, 1_000_000_000, "1e99999999"), "FAIL", False, "GATE5_U95_EXACT_EXCEEDS_LIMIT_OR_INVALID"),
        ("neg_fail_r11_sol_r1005_extreme_gate5_u95_neg_1e99999999", _with_g5_raw_u95(om_d, 0, 1_000_000_000, "-1e99999999"), "FAIL", False, "GATE5_U95_EXACT_EXCEEDS_LIMIT_OR_INVALID"),
        ("neg_fail_r11_sol_r1005_extreme_gate5_u95_1e_minus99999999", _with_g5_raw_u95(om_d, 0, 1_000_000_000, "1e-99999999"), "FAIL", False, "GATE5_U95_EXACT_EXCEEDS_LIMIT_OR_INVALID"),
        # Round-13 Audit R12-04: exact Decimal policy comparisons across ALL non-date Gate-35 thresholds (ZERO float() before policy decision!)
        ("pos_synth_r13_sol_r1204_raw_json_ductal_1p99999999999999999_passes", _patch_top_raw_json(om_d, {"ductal_cytokeratin_impurity_pct": "1.99999999999999999"}), "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("neg_fail_r13_sol_r1204_raw_json_ductal_exact_2p0_fails", _patch_top_raw_json(om_d, {"ductal_cytokeratin_impurity_pct": "2.0"}), "FAIL", False, "DUCTAL_IMPURITY_GE_2PCT_FAIL"),
        ("pos_synth_r13_sol_r1204_raw_json_endotoxin_0p49999999999999999_passes", _patch_top_raw_json(om_d, {"endotoxin_eu_per_ml": "0.49999999999999999"}), "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("neg_fail_r13_sol_r1204_raw_json_endotoxin_exact_0p5_fails", _patch_top_raw_json(om_d, {"endotoxin_eu_per_ml": "0.5"}), "FAIL", False, "R4O_01_ENDOTOXIN_GE_0P5_EU_ML_FAIL"),
        ("neg_fail_r13_sol_r1204_raw_json_fasl_1e_minus350_no_underflow_veto", _patch_top_raw_json(om_d, {"analytical_fasl_ug": "1e-350"}), "FAIL", False, "R4O_02_ANALYTICAL_FASL_NONZERO_VETO"),
        ("neg_fail_r13_sol_r1204_raw_json_fasl_neg_1e_minus350_invalid", _patch_top_raw_json(om_d, {"analytical_fasl_ug": "-1e-350"}), "FAIL", False, "INVALID_ANALYTICAL_FASL_UG"),
        ("pos_synth_r13_sol_r1204_raw_json_caspase37_exact_1p15_passes", _patch_top_raw_json(om_d, {"hepatocyte_72h_caspase37_u95_fold": "1.15"}), "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("neg_fail_r13_sol_r1204_raw_json_caspase37_1p15000000000000001_fails", _patch_top_raw_json(om_d, {"hepatocyte_72h_caspase37_u95_fold": "1.15000000000000001"}), "FAIL", False, "R4O_02_HEPATOCYTE_CASPASE37_EXCEEDS_1P15X_FAIL"),
        ("neg_fail_r13_sol_r1204_raw_json_alt_ldh_1p15000000000000001_fails", _patch_top_raw_json(om_d, {"hepatocyte_72h_alt_ldh_u95_fold": "1.15000000000000001"}), "FAIL", False, "R4O_02_HEPATOCYTE_ALT_LDH_EXCEEDS_1P15X_FAIL"),
        ("pos_synth_r13_sol_r1204_raw_json_face_and_core_exact_15_and_5_passes", om_d_exact_face15_core5, "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("neg_fail_r13_sol_r1204_raw_json_worst_face_o2_14p9999999999999999_fails", _patch_top_raw_json(om_d, {"measured_worst_face_o2_mmhg": "14.9999999999999999"}), "FAIL", False, "MEASURED_WORST_FACE_O2_LT_15MMHG_FAIL"),
        ("neg_fail_r13_sol_r1204_raw_json_worst_core_o2_4p9999999999999999_fails", _patch_top_raw_json(om_d, {"measured_worst_core_o2_mmhg": "4.9999999999999999"}), "FAIL", False, "MEASURED_WORST_CORE_O2_LT_5MMHG_FAIL"),
        ("neg_fail_r13_sol_r1204_raw_json_leaf_face_o2_14p9999999999999999_fails", _patch_leaf_one_raw_json(om_d, 0, {"measured_face_o2_mmhg": "14.9999999999999999"}), "FAIL", False, "LEAF_MEASURED_FACE_O2_LT_15MMHG_FAIL"),
        ("neg_fail_r13_sol_r1204_raw_json_leaf_core_o2_4p9999999999999999_fails", _patch_leaf_one_raw_json(om_d, 0, {"measured_core_o2_mmhg": "4.9999999999999999"}), "FAIL", False, "LEAF_MEASURED_CORE_O2_LT_5MMHG_FAIL"),
        ("neg_fail_r13_sol_r1204_raw_json_leaf_d_o2_sub_ulp_below_floor_fails", _patch_leaf_one_raw_json(om_d, 0, {"measured_d_o2_matrix_m2_s": "9.40253999999999999e-10"}), "FAIL", False, "LEAF_MEASURED_D_O2_MATRIX_BELOW_LOW_D_FLOOR_FAIL"),
        ("neg_fail_r13_sol_r1204_raw_json_lot_ocr_1p09700000000000001_fails", _patch_top_raw_json(om_d, {"measured_lot_ocr_mult": "1.09700000000000001"}), "FAIL", False, "MEASURED_LOT_OCR_MULT_EXCEEDS_1P097_FAIL"),
        ("pos_synth_r13_sol_r1204_raw_json_clean_t50_2p5999999999999999_passes", _patch_top_raw_json(om_d, {"route_specific_clean_t50_min": "2.5999999999999999"}), "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("pos_synth_r13_sol_r1204_raw_json_fibrin_t50_2p9999999999999999_passes", _patch_top_raw_json(om_d, {"route_specific_fibrin_t50_min": "2.9999999999999999"}), "SYNTHETIC_SELF_TEST_PASS", False, None),
        ("neg_fail_r13_sol_r1204_raw_json_lcms_pellet_0p050000000000000001_fails", _patch_top_raw_json(om_d, {"lcms_pellet_diazoxide_uM": "0.050000000000000001"}), "FAIL", False, "GY014_LCMS_PELLET_DIAZOXIDE_EXCEEDS_0P05UM_LOQ"),
        ("neg_fail_r13_sol_r1204_raw_json_tier1_fibrin_10p000000000000001_fails", _patch_top_raw_json(om_d, {"measured_fibrin_capsule_um": "10.000000000000001"}), "FAIL", False, "TIER1_FIBRIN_CAPSULE_EXCEEDS_10UM_CEILING_AT_BED_LT_40MMHG"),
        ("neg_fail_r13_sol_r1204_raw_json_nhp_responder_residual_ins_1e_minus350_fails", _patch_nhp_one_raw_json(om_d, 0, {"residual_exogenous_insulin_u_kg_d": "1e-350"}), "FAIL", False, "R4O_05_NHP_QUALIFIED_INSULIN_INDEPENDENCE_FAIL"),
        ("neg_fail_r13_sol_r1204_raw_json_nhp_baseline_ins_0p49999999999999999_fails", _patch_nhp_one_raw_json(om_d, 0, {"baseline_exogenous_insulin_u_kg_d": "0.49999999999999999"}), "FAIL", False, "R4O_05_NHP_ELIGIBLE_DIABETIC_N_LT_4_FAIL"),
        ("neg_fail_r13_sol_r1204_raw_json_nhp_baseline_cpep_0p20000000000000001_fails", _patch_nhp_one_raw_json(om_d, 0, {"baseline_fasting_c_peptide_ng_ml": "0.20000000000000001"}), "FAIL", False, "R4O_05_NHP_ELIGIBLE_DIABETIC_N_LT_4_FAIL"),
        ("neg_fail_r13_sol_r1204_raw_json_porcine_retrieval_99p89999999999999999_fails", _patch_porcine_one_raw_json(om_d, 0, {"retrieval_mass_pct": "99.89999999999999999"}), "FAIL", False, "PORCINE_ENBLOC_MASS_RETRIEVAL_LT_99P9PCT_FAIL"),
        ("neg_fail_r5_porcine_residual_sampling_1e_minus320", _patch_porcine(om_d, {"residual_viable_cells_measured": 0, "residual_sampling_fraction": 1e-320}), "FAIL", False, "INVALID_PORCINE_RESIDUAL_SAMPLING_FRACTION_OUT_OF_0P01_TO_1P0"),
        ("neg_fail_sol_f5_100pct_retrieval_with_933p5M_residual", _patch_porcine(om_d, {"retrieval_mass_pct": 100.0, "total_implanted_cells": 933_500_000, "residual_viable_cells_measured": 933_500_000, "residual_sampling_fraction": 1.0}), "FAIL", False, "PORCINE_RETRIEVAL_100PCT_CONTRADICTS_RESIDUAL_VIABLE_CELLS_FAIL"),
        ("neg_fail_porcine_major_hemorrhage", _patch_porcine(om_d, {"major_hemorrhage_or_dehiscence": True}), "FAIL", False, "R4O_04_PORCINE_MAJOR_HEMORRHAGE_OR_DEHISCENCE_FAIL"),
        ("neg_fail_nhp_day150_late_endpoint", _patch_nhp(om_d, {"followup_duration_days": 180.0, "insulin_indep_day": 150.0}), "FAIL", False, "R4O_05_NHP_QUALIFIED_INSULIN_INDEPENDENCE_FAIL"),
        ("neg_fail_nhp_18000_ieq_kg_overdose", _patch_nhp(om_d, {"dose_ieq_per_kg": 18000.0}), "FAIL", False, "R4O_05_NHP_QUALIFIED_INSULIN_INDEPENDENCE_FAIL"),
        ("neg_fail_nhp_30um_month3_capsule", _patch_nhp(om_d, {"month3_capsule_um": 30.0}), "FAIL", False, "R4O_05_NHP_MONTH3_CAPSULE_EXCEEDS_TIER_MAX_FAIL"),
        ("neg_fail_porcine_19um_month3_capsule", _patch_porcine(om_d, {"month3_capsule_um": 19.0}), "FAIL", False, "R4O_04_PORCINE_MONTH3_CAPSULE_EXCEEDS_TIER_MAX_FAIL"),
        ("neg_fail_nhp_paired_gsis_secretory_delay", _patch_nhp(om_d, {"paired_dynamic_gsis_pass": False}), "FAIL", False, "R4O_05_NHP_QUALIFIED_INSULIN_INDEPENDENCE_FAIL"),
        # Round-4/5 Ex-vivo rest (Review #10 zero-div guard)
        ("neg_fail_exvivo_21pct_normoxic_challenge", _patch_sync(om_d, {"rest_challenge_o2_pct": 21.0}), "FAIL", False, "H46E03_REST_CHALLENGE_O2_PCT_NOT_2P0_FAIL"),
        ("neg_fail_exvivo_day1_collection_rejected", _patch_sync(om_d, {"rest_collection_day": 1.0}), "FAIL", False, "H46E04_COLLECTION_DAY_LT_14_FOR_DAY14_STIMULATED_CPEPTIDE_FAIL"),
        ("neg_fail_exvivo_overstated_claimed_ratio", _patch_sync(om_d, {"rest_endpoint_rested_value": 1.55, "rest_endpoint_control_value": 1.50, "h46e04_day14_cpeptide_or_mass_fold_ctrl": 1.28}), "FAIL", False, "H46E04_CLAIMED_FOLD_CONTRADICTS_DERIVED_MEASURED_RATIO_FAIL"),
        ("neg_fail_r5_exvivo_rest_ratio_underflow_zero_no_zerodiv", _patch_sync(om_d, {"rest_endpoint_rested_value": 1e-320, "rest_endpoint_control_value": 1e6}), "FAIL", False, "INVALID_H46E04_DERIVED_RATIO_NONFINITE_OR_UNDERFLOW_ZERO"),
        ("neg_fail_h46e04_secretory_delay", _patch_sync(om_d, {"h46e04_zero_secretory_delay_verified": False}), "FAIL", False, "H46E04_SECRETORY_DELAY_DETECTED_FAIL"),
        # Round-5/14 P0: Live Blueprint Gate 5 OQ-012 survivor vetoes, prerequisite digest, current-assay archive, flags
        ("neg_fail_r5_gate5_99983553_of_1e12_survivor_veto", _with_g5(om_d, 99_983_553, 10 ** 12, 1.0e-4), "FAIL", False, "FAIL_GATE5_OQ012_NONZERO_SURVIVOR_OR_U95_GT_1E8"),
        ("neg_fail_r5_gate5_100k_of_1005216927_survivor_veto", _with_g5(om_d, 100_000, 1_005_216_927, 1.0e-4), "FAIL", False, "FAIL_GATE5_OQ012_NONZERO_SURVIVOR_OR_U95_GT_1E8"),
        ("neg_fail_r5_gate5_10_of_100k_forged_1e_minus6_survivor_veto", _with_g5(om_d, 10, 100_000, 1.0e-6), "FAIL", False, "FAIL_GATE5_OQ012_NONZERO_SURVIVOR_OR_U95_GT_1E8"),
        ("neg_fail_r5_gate5_100k_of_100k_forged_1e_minus6_survivor_veto", _with_g5(om_d, 100_000, 100_000, 1.0e-6), "FAIL", False, "FAIL_GATE5_OQ012_NONZERO_SURVIVOR_OR_U95_GT_1E8"),
        ("neg_fail_r5_missing_current_assay_record", _drop_both(om_d, "current_assay_evidence_record"), "FAIL", False, "MISSING_CURRENT_ASSAY_EVIDENCE_RECORD"),
        ("neg_fail_r5_archived_endotoxin_3p0_vs_parent_0p12", om_d_adv_arch_parent_favorable, "FAIL", False, "R4O_01_ENDOTOXIN_GE_0P5_EU_ML_FAIL"),
        ("neg_fail_r5_sterility_false", _patch_sync(om_d, {"sterility_pass": False}), "FAIL", False, "R4O_01_STERILITY_FAILED"),
        ("neg_fail_r5_mycoplasma_positive", _patch_sync(om_d, {"mycoplasma_negative": False}), "FAIL", False, "R4O_01_MYCOPLASMA_POSITIVE_FAIL"),
        ("neg_fail_r5_gate0v_physical_qualification_complete_false", {**om_d, "upstream_gate0v_record": {**om_d["upstream_gate0v_record"], "physical_qualification_complete": False}}, "FAIL", False, "UPSTREAM_GATE0V_PHYSICAL_QUALIFICATION_INCOMPLETE_REJECTED"),
        ("neg_fail_upstream_bank_id_mismatch", {**om_d, "upstream_gate32_record": {**om_d["upstream_gate32_record"], "bank_id": "BANK-OTHER-999"}}, "FAIL", False, "UPSTREAM_GATE34_BANK_ID_MISMATCH"),
        ("neg_fail_upstream_zero_digest", {**om_d, "upstream_gate32_record": {**om_d["upstream_gate32_record"], "archive_sha256": "0" * 64}}, "FAIL", False, "UPSTREAM_GATE34_INVALID_OR_ZERO_ARCHIVE_SHA256"),
        ("neg_fail_upstream_contrary_product_id", {**om_d, "upstream_gate0v_record": {**om_d["upstream_gate0v_record"], "product_id": "ISLET1_DESIGN_Y_V3"}}, "FAIL", False, "UPSTREAM_GATE0V_PRODUCT_ID_MISMATCH"),
        ("neg_fail_upstream_gate5_oq012_failed", {**om_d, "upstream_gate5_oq012_record": {**om_d["upstream_gate5_oq012_record"], "oq012_clonogenic_regrowth_pass": False}}, "FAIL", False, "GATE5_OQ012_CLONOGENIC_REGROWTH_FAILED"),
        # Domain short-circuit underflow/overflow + huge int + CI + unhashable IDs
        ("neg_fail_underflow_d_rms3_1e_minus110", _patch_sync(om_d, {"cluster_d_rms3_um": 1e-110}), "FAIL", False, "CLUSTER_D_RMS3_OUTSIDE_40_TO_65UM_FAIL"),
        ("neg_fail_underflow_d_rms3_1e_minus150", _patch_sync(om_d, {"cluster_d_rms3_um": 1e-150}), "FAIL", False, "CLUSTER_D_RMS3_OUTSIDE_40_TO_65UM_FAIL"),
        ("neg_fail_underflow_loading_1e_minus305", _patch_sync(om_d, {"areal_loading_ieq_cm2": 1e-305}), "FAIL", False, "INVALID_AREAL_LOADING"),
        ("neg_fail_underflow_loading_1e_minus310", _patch_sync(om_d, {"areal_loading_ieq_cm2": 1e-310}), "FAIL", False, "INVALID_AREAL_LOADING"),
        ("neg_fail_underflow_loading_1e_minus320", _patch_sync(om_d, {"areal_loading_ieq_cm2": 1e-320}), "FAIL", False, "INVALID_AREAL_LOADING"),
        ("neg_fail_huge_int_10p600_no_overflow", {**om_d, "areal_loading_ieq_cm2": 10 ** 600}, "FAIL", False, "INVALID_AREAL_LOADING"),
        ("neg_fail_auc_l95_120_exceeds_point_90", _patch_sync(om_d, {"oq018_post_washout_first_phase_auc_pct_ctrl": 90.0, "oq018_post_washout_first_phase_auc_l95_pct_ctrl": 120.0}), "FAIL", False, "OQ018_FIRST_PHASE_AUC_L95_EXCEEDS_POINT_ESTIMATE_INCONSISTENT"),
        ("neg_fail_unhashable_list_arm_key", {**om_d, "arm_key": ["D"]}, "FAIL", False, "UNREGISTERED_CANONICAL_ARM_KEY"),
        # Cuff allowlist, portal safety, ex-vivo rest & GY-014
        ("neg_fail_r4o02_portal_fasl_ban", _patch_sync(om_d, {"coformulated_immune_cuff_agents": ["ADIPOQ_HEXA_FASL"]}), "FAIL", False, "R4O_02_HARD_VETO_FASL_PROHIBITED:ADIPOQ_HEXA_FASL"),
        ("neg_fail_unregistered_cuff_component", _patch_sync(om_d, {"coformulated_immune_cuff_agents": ["NOVEL_PORTAL_LIGAND_X"]}), "FAIL", False, "UNREGISTERED_CUFF_COMPONENT_REJECTED:NOVEL_PORTAL_LIGAND_X"),
        ("neg_fail_endotoxin_ge_0p5", _patch_sync(om_d, {"endotoxin_eu_per_ml": 0.8}), "FAIL", False, "R4O_01_ENDOTOXIN_GE_0P5_EU_ML_FAIL"),
        ("neg_fail_hepatocyte_caspase37", _patch_sync(om_d, {"hepatocyte_72h_caspase37_u95_fold": 1.45}), "FAIL", False, "R4O_02_HEPATOCYTE_CASPASE37_EXCEEDS_1P15X_FAIL"),
        ("neg_fail_cuff_leachate_failed", _patch_sync(om_d, {"cuff_leachate_assay_passed": False}), "FAIL", False, "R4O_02_CUFF_LEACHATE_ASSAY_FAILED"),
        ("neg_fail_ppcn_quarantined", _patch_sync(om_d, {"clinical_matrix_id": "PPCN_CITRATE_PNIPAAM"}), "FAIL", False, "PPCN_QUARANTINED_STAGE0_RESEARCH_COMPARATOR_ONLY"),
        ("neg_fail_invivo_diazoxide_claimed", _patch_sync(om_d, {"invivo_diazoxide_depot_or_credit_claimed": True}), "FAIL", False, "GY014_BLOCK_INVIVO_DIAZOXIDE_PROHIBITED"),
        ("neg_fail_lcms_pellet_exceeds_loq", _patch_sync(om_d, {"lcms_pellet_diazoxide_uM": 0.12}), "FAIL", False, "GY014_LCMS_PELLET_DIAZOXIDE_EXCEEDS_0P05UM_LOQ"),
        ("neg_fail_lcms_supernatant_exceeds_loq", _patch_sync(om_d, {"lcms_supernatant_diazoxide_uM": 0.09}), "FAIL", False, "GY014_LCMS_SUPERNATANT_DIAZOXIDE_EXCEEDS_0P05UM_LOQ"),
        # HOLD probes for missing mandatory observations
        ("neg_hold_missing_bank_id", _drop_both(om_d, "bank_id"), "HOLD", False, "MISSING_BANK_ID"),
        ("neg_hold_missing_construct_manifest_sha256", _drop_both(om_d, "construct_manifest_sha256"), "HOLD", False, "MISSING_CONSTRUCT_MANIFEST_SHA256"),
        ("neg_hold_missing_per_leaf_records", _drop_both(om_d, "per_leaf_records"), "HOLD", False, "MISSING_PER_LEAF_RECORDS"),
        ("neg_hold_missing_upstream_gate0v", _drop_both(om_d, "upstream_gate0v_record"), "HOLD", False, "MISSING_UPSTREAM_GATE0V_RECORD"),
        ("neg_hold_missing_upstream_gate5_oq012", _drop_both(om_d, "upstream_gate5_oq012_record"), "HOLD", False, "MISSING_UPSTREAM_GATE5_OQ012_RECORD"),
        ("neg_hold_missing_plane_offset", _drop_both(om_d, "staggered_bilayer_plane_offset_um"), "HOLD", False, "MISSING_STAGGERED_BILAYER_PLANE_OFFSET_UM"),
        ("neg_hold_missing_porcine_subjects", _drop_both(om_d, "porcine_subjects"), "HOLD", False, "MISSING_STAGE1_PORCINE_SUBJECTS"),
        ("neg_hold_missing_nhp_subjects", _drop_both(om_d, "nhp_subjects"), "HOLD", False, "MISSING_STAGE1_NHP_SUBJECTS"),
        ("neg_hold_missing_lcms_pellet_washout", _drop_both(om_d, "lcms_pellet_diazoxide_uM"), "HOLD", False, "MISSING_H46E02_LCMS_PELLET_DIAZOXIDE_UM"),
    ]

    results = []
    for cname, payload, exp_status, exp_auth, exp_reason in cases:
        out = evaluate_gate33_route4_omentum_and_exvivo_rest(payload, arm_manifest=arm_manifest)
        # Strict JSON serialization check (zero NaN/Inf in adjudicator outputs!)
        json.dumps(out, allow_nan=False)
        require_cond(out["status"] == exp_status, f"Gate-35 self-test {cname} status mismatch: got {out['status']}, expected {exp_status} ({out})")
        require_cond(out["promotion_authorized"] is False and exp_auth is False, f"Gate-35 synthetic self-test {cname} must NEVER authorize promotion: {out}")
        if exp_reason is not None:
            require_cond(exp_reason in out["reasons"], f"Gate-35 self-test {cname} missing expected reason {exp_reason}: {out['reasons']}")
        if cname == "pos_synth_r14_partial_responder_cpeptide_extinction_passes":
            require_cond(
                out["derived_nhp_cpeptide_extinction_verified_count"] == 4
                and out["derived_nhp_qualified_ii_count"] == 3,
                f"Partial responder extinction must increment extinction count (4) without inflating II count (3): {out}",
            )
        results.append({
            "case": cname,
            "expected_status": exp_status,
            "observed_status": out["status"],
            "expected_promotion_authorized": False,
            "observed_promotion_authorized": out["promotion_authorized"],
            "passed": True,
        })

    return {
        "epistemic_scope": "SYNTHETIC_ADJUDICATOR_SELF_TESTS_ONLY_NOT_WETLAB_LOT_RELEASE",
        "gate_id": GATE_ID,
        "synthetic_fixture_isolation_verified": True,
        "all_synthetic_cases_promotion_authorized_false": True,
        "total_cases": len(results),
        "passed_cases": len(results),
        "all_passed": True,
        "cases": results,
    }


# =============================================================================
# 8. Portable Receipt Projection & Mandatory portable_payload_sha256 Verification
# =============================================================================
def build_portable_receipt_payload(receipt: Dict[str, Any]) -> Dict[str, Any]:
    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 = canonical_json_dumps(proj).encode("utf-8")
    return sha256_bytes(raw)


def verify_portable_receipt_file(existing_path: Path, fresh_receipt: Dict[str, Any]) -> str:
    require_cond(existing_path.is_file(), f"--check-portable failed: missing receipt {existing_path}")
    existing_receipt = load_strict_json_text(existing_path.read_text(encoding="utf-8"), existing_path.name)
    require_cond(isinstance(existing_receipt, dict) and isinstance(existing_receipt.get("runtime_environment"), dict), "Malformed receipt")
    pyver = existing_receipt["runtime_environment"].get("python_version")
    require_cond(isinstance(pyver, str) and bool(pyver.strip()), "Missing runtime_environment.python_version")

    # Mandatory portable_payload_sha256 presence & validity check (closes Audit P1!)
    embedded_sha = existing_receipt.get("portable_payload_sha256")
    require_cond(
        _is_valid_sha256_hex(embedded_sha),
        "--check-portable failed: mandatory portable_payload_sha256 missing, empty, or malformed",
    )

    existing_sha = compute_portable_payload_sha256(existing_receipt)
    fresh_sha = compute_portable_payload_sha256(fresh_receipt)
    require_cond(
        _strict_json_equal(
            build_portable_receipt_payload(existing_receipt),
            build_portable_receipt_payload(fresh_receipt),
        )
        and existing_sha == fresh_sha
        and embedded_sha == fresh_sha,
        f"--check-portable failed: semantic or digest mismatch "
        f"(embedded={embedded_sha}, existing={existing_sha}, fresh={fresh_sha})",
    )
    return fresh_sha


# =============================================================================
# 9. Full Verification Orchestrator
# =============================================================================
def run_verification(
    repo_root: Path | None,
    standalone: bool,
    *,
    manifest_path: Optional[Path] = None,
    master_contract_path: Optional[Path] = None,
) -> Dict[str, Any]:
    contracts = load_and_verify_canonical_contracts(
        manifest_path=manifest_path,
        master_contract_path=master_contract_path,
    )
    c = verify_nw08_constants(None if standalone else repo_root)
    max_o2_mbe = 0.0
    max_solute_mbe = 0.0

    def _track_o2(res: Dict[str, Any]) -> Dict[str, Any]:
        nonlocal max_o2_mbe
        if "o2_rel_mass_balance_error" in res:
            max_o2_mbe = max(max_o2_mbe, float(res["o2_rel_mass_balance_error"]))
        return res

    def _track_solute(res: Dict[str, Any]) -> Dict[str, Any]:
        nonlocal max_solute_mbe
        for k in ("ss_rel_mass_balance_error", "max_step_rel_mass_balance_error", "cumulative_rel_mass_balance_error"):
            if k in res:
                max_solute_mbe = max(max_solute_mbe, float(res[k]))
        return res

    a_nom = c["alpha_o2_nominal_mol_cm3_mmhg"]
    a_krbh = c["alpha_o2_krbh_mol_cm3_mmhg"]
    d_nom = c["d_o2_gel_chronic_cm2_s"]
    d_low = c["d_o2_gel_acute_cm2_s"]
    vol_ieq = c["vol_1_ieq_cm3"]
    v65 = (4.0 / 3.0) * math.pi * ((32.5e-4) ** 3)
    v100 = (4.0 / 3.0) * math.pi * ((50.0e-4) ** 3)

    def _bilayer_pitch_um(load_ieq_cm2: float) -> float:
        return math.sqrt(1.0 / (0.5 * load_ieq_cm2 * vol_ieq / v65)) * 1e4

    # (1) Part A: Incumbent Route 3P Exact Parity & Failure Verification (nx=28, nz=32)
    r3p_clean = _track_o2(run_planar_route3p_case(c, area_cm2=333.3, h_slot_um=180.0, cluster_diam_um=65.0, bed_po2_mmhg=35.0, fibrin_um=0.0, nx=28, nz=32))
    r3p_fib10 = _track_o2(run_planar_route3p_case(c, area_cm2=333.3, h_slot_um=180.0, cluster_diam_um=65.0, bed_po2_mmhg=35.0, fibrin_um=10.0, nx=28, nz=32))
    r3p_fib15 = _track_o2(run_planar_route3p_case(c, area_cm2=333.3, h_slot_um=180.0, cluster_diam_um=65.0, bed_po2_mmhg=35.0, fibrin_um=15.0, nx=28, nz=32))
    r3p_krbh30 = _track_o2(run_planar_route3p_case(c, area_cm2=333.3, h_slot_um=180.0, cluster_diam_um=65.0, bed_po2_mmhg=30.0, fibrin_um=0.0, alpha_o2=a_krbh, nx=28, nz=32))

    require_cond(abs(r3p_clean["worst_face_mmhg"] - PINNED_IIP0034_REFS["Hybrid333_H180_Day0_Clean_65um_PASS"]) < 1e-3, "R3P clean parity fail")
    require_cond(abs(r3p_fib10["worst_face_mmhg"] - PINNED_IIP0034_REFS["Hybrid333_H180_Day0_10umFibrin_0p5D_65um_FACE_FAIL"]) < 1e-3, "R3P 10um parity fail")
    require_cond(abs(r3p_fib15["worst_face_mmhg"] - PINNED_IIP0034_REFS["Hybrid333_H180_Day0_15umFibrin_0p5D_65um"]) < 1e-3, "R3P 15um parity fail")
    require_cond(abs(r3p_krbh30["worst_face_mmhg"] - PINNED_IIP0034_REFS["Hybrid333_H180_Day0_Clean_65um_Bed30mmHg_Alpha1p27e9_FACE_FAIL"]) < 1e-3, "R3P KRBH parity fail")
    require_cond(not r3p_fib10["passes_15_and_5"] and not r3p_krbh30["passes_15_and_5"], "R3P must fail 10um fibrin and 30mmHg KRBH")

    r3p_t50_clean = _track_solute(compute_3d_fvm_insulin_shutoff_t50(
        h_um=180.0, pitch_um=104.155, cluster_diam_um=65.0, bilayer=True,
        fibrin_um=0.0, fibrin_d_factor=0.5, d_ins_matrix_cm2_s=c["d_insulin_hydrogel_cm2_s"],
        d_ins_islet_cm2_s=c["d_insulin_hydrogel_cm2_s"], t50_intrinsic_min=c["insulin_intrinsic_t50_min"],
        top_adiabatic=False, nx=18, nz=24, dt_s=2.0,
    ))
    r3p_t50_fib10 = _track_solute(compute_3d_fvm_insulin_shutoff_t50(
        h_um=180.0, pitch_um=104.155, cluster_diam_um=65.0, bilayer=True,
        fibrin_um=10.0, fibrin_d_factor=0.5, d_ins_matrix_cm2_s=c["d_insulin_hydrogel_cm2_s"],
        d_ins_islet_cm2_s=c["d_insulin_hydrogel_cm2_s"], t50_intrinsic_min=c["insulin_intrinsic_t50_min"],
        top_adiabatic=False, nx=18, nz=24, dt_s=2.0,
    ))
    require_cond(r3p_t50_fib10["t50_3d_fvm_min"] > 3.0 and not r3p_t50_fib10["passes_lt_3p0_min"], "R3P 10um t50 must fail > 3.0 min")

    # (2) Part 0: Uniform Equal-Ratio (r_x == r_y == r_z == 1.5) 3-Mesh Refinement Checks
    mesh_ladder_r3p = [(16, 20), (24, 30), (36, 45)]
    mesh_ladder_r4 = [(16, 16), (24, 24), (36, 36)]
    r_unif = 1.5

    r3p_m_vals, r3p_m_mbes = [], []
    for nx, nz in mesh_ladder_r3p:
        rr = _track_o2(run_planar_route3p_case(c, area_cm2=333.3, h_slot_um=180.0, cluster_diam_um=65.0, bed_po2_mmhg=35.0, fibrin_um=10.0, nx=nx, nz=nz))
        r3p_m_vals.append(rr["worst_face_mmhg"])
        r3p_m_mbes.append(rr["o2_rel_mass_balance_error"])

    om_mono_vals, om_mono_mbes = [], []
    om_t1_vals, om_t1_mbes = [], []
    om_t2_vals, om_t2_mbes = [], []
    sars_2500_vals, sars_2500_mbes = [], []
    for nx, nz in mesh_ladder_r4:
        rm = _track_o2(run_r4_monolayer_case(c, site_name="R4_Omentum_Mesh", cluster_diam_um=65.0, pitch_um=150.0, bed_po2_mmhg=40.0, fibrin_um=20.0, interstitial_margin_each_um=15.0, nx=nx, nz=nz))
        rt1 = _track_o2(run_r4_clinical_bilayer_case(c, site_name="R4_Omentum_T1_Mesh", loading_ieq_cm2=1200.0, h_um=120.0, bed_po2_mmhg=35.0, fibrin_um=10.0, d_matrix_cm2_s=d_low, alpha_o2=a_krbh, nx=nx, nz=nz))
        rt2 = _track_o2(run_r4_clinical_bilayer_case(c, site_name="R4_Omentum_T2_Mesh", loading_ieq_cm2=1500.0, h_um=120.0, bed_po2_mmhg=40.0, fibrin_um=12.0, d_matrix_cm2_s=d_low, alpha_o2=a_krbh, nx=nx, nz=nz))
        rs = _track_o2(run_r4_clinical_bilayer_case(c, site_name="R4_SARS_2500_Mesh", loading_ieq_cm2=2500.0, h_um=120.0, bed_po2_mmhg=35.0, fibrin_um=10.0, nx=nx, nz=nz))
        om_mono_vals.append(rm["worst_face_mmhg"])
        om_mono_mbes.append(rm["o2_rel_mass_balance_error"])
        om_t1_vals.append(rt1["worst_face_mmhg"])
        om_t1_mbes.append(rt1["o2_rel_mass_balance_error"])
        om_t2_vals.append(rt2["worst_face_mmhg"])
        om_t2_mbes.append(rt2["o2_rel_mass_balance_error"])
        sars_2500_vals.append(rs["worst_face_mmhg"])
        sars_2500_mbes.append(rs["o2_rel_mass_balance_error"])

    three_mesh_convergence = {
        "uniform_refinement_ratio_xyz": r_unif,
        "r3p_ladder_nx_nz": [list(x) for x in mesh_ladder_r3p],
        "r4_ladder_nx_nz": [list(x) for x in mesh_ladder_r4],
        "route3p_65um_35mmHg_10umFibrin_face_ALL_FAIL": analyze_3grid_convergence(r3p_m_vals, r_unif, r3p_m_mbes),
        "r4_omentum_65um_p150_40mmHg_20umBar_face_ALL_PASS": analyze_3grid_convergence(om_mono_vals, r_unif, om_mono_mbes),
        "r4_omentum_tier1_1200IEQ_35mmHg_10umFib_lowD_KRBH_ALL_PASS": analyze_3grid_convergence(om_t1_vals, r_unif, om_t1_mbes),
        "r4_omentum_tier2_1500IEQ_40mmHg_12umFib_lowD_KRBH_ALL_PASS": analyze_3grid_convergence(om_t2_vals, r_unif, om_t2_mbes),
        "r4_sars_65um_2500IEQ_35mmHg_10umFib_face_ALL_FAIL": analyze_3grid_convergence(sars_2500_vals, r_unif, sars_2500_mbes),
    }
    require_cond(all(v < 15.0 for v in r3p_m_vals), "R3P 10um must fail on all 3 grids")
    require_cond(all(v >= 15.0 for v in om_mono_vals) and all(v >= 15.0 for v in om_t1_vals) and all(v >= 15.0 for v in om_t2_vals), "R4-Omentum Tier-1/Tier-2/monolayer must pass on all 3 grids")
    require_cond(all(v < 15.0 for v in sars_2500_vals), "R4-SARS 2500 10um must fail on all 3 grids")

    # (3) Part B: Demoted R4-SARS-Free Clinical Failure Audit & Tightened <=1,200 IEQ/cm^2 Backup
    sars_clinical_audit = []
    for load, p_bed, d_tag, d_val, alpha_tag, alpha_val, top_ad, fib in [
        (2000.0, 35.0, "nom", d_nom, "nom", a_nom, True, 0.0),
        (2500.0, 35.0, "nom", d_nom, "nom", a_nom, True, 0.0),
        (2000.0, 35.0, "nom", d_nom, "nom", a_nom, False, 0.0),
        (2000.0, 35.0, "nom", d_nom, "nom", a_nom, False, 10.0),
        (2500.0, 35.0, "nom", d_nom, "nom", a_nom, False, 0.0),
        (2500.0, 35.0, "nom", d_nom, "nom", a_nom, False, 10.0),
        (2500.0, 30.0, "nom", d_nom, "KRBH", a_krbh, False, 0.0),
        (1500.0, 35.0, "lowD", d_low, "KRBH", a_krbh, False, 10.0),
        (1200.0, 35.0, "lowD", d_low, "KRBH", a_krbh, False, 10.0),
    ]:
        row = _track_o2(run_r4_clinical_bilayer_case(
            c, site_name="R4_SARS_Free_ClinicalAudit", loading_ieq_cm2=load, h_um=120.0,
            bed_po2_mmhg=p_bed, fibrin_um=fib, d_matrix_cm2_s=d_val, top_adiabatic=top_ad, alpha_o2=alpha_val, nx=20, nz=20,
        ))
        row["d_tag"] = d_tag
        row["alpha_tag"] = alpha_tag
        sars_clinical_audit.append(row)

    require_cond(sars_clinical_audit[0]["worst_face_mmhg"] < 0.25 and sars_clinical_audit[1]["worst_face_mmhg"] < 0.05, "SARS unilateral must collapse")
    require_cond(not sars_clinical_audit[3]["passes_15_and_5"] and not sars_clinical_audit[5]["passes_15_and_5"], "SARS 2000-2500 10um must fail")
    require_cond(not sars_clinical_audit[6]["passes_15_and_5"], "SARS 2500 KRBH clean must fail")
    require_cond(not sars_clinical_audit[7]["passes_15_and_5"], "SARS 1500 35mmHg lowD KRBH 10um must fail (forcing <=1200 backup cap)")
    require_cond(sars_clinical_audit[8]["passes_15_and_5"], "SARS tightened backup <=1200 35mmHg lowD KRBH 10um must pass")

    sars_t50_uni_2500 = _track_solute(compute_3d_fvm_insulin_shutoff_t50(
        h_um=120.0, pitch_um=_bilayer_pitch_um(2500.0), cluster_diam_um=65.0, bilayer=True,
        fibrin_um=0.0, fibrin_d_factor=0.5, d_ins_matrix_cm2_s=c["d_insulin_hydrogel_cm2_s"],
        d_ins_islet_cm2_s=c["d_insulin_hydrogel_cm2_s"], t50_intrinsic_min=c["insulin_intrinsic_t50_min"],
        top_adiabatic=True, nx=16, nz=20, dt_s=2.0,
    ))
    require_cond(not sars_t50_uni_2500["passes_lt_3p0_min"], "SARS unilateral clinical bilayer t50 must fail > 3.0 min")

    # (4) Part C: Lead Visceral R4-Omentum Full-Conjunction Admitted Operating Envelope + Explicit FAIL Corners
    # (4a) Tier-1 Primary Envelope (<=1,200 IEQ/cm^2, bed >=35 mmHg, fibrin <=10 um, full low-D + KRBH conjunction; plus 12 um margin)
    tier1_admitted_corners = []
    for p_bed in (35.0, 40.0, 45.0):
        for fib in (0.0, 10.0):
            for d_tag, d_val in (("nom_1p50e5", d_nom), ("lowD_0p94e5", d_low)):
                for a_tag, a_val in (("nom_1p34e9", a_nom), ("KRBH_1p27e9", a_krbh)):
                    if p_bed > 35.0 and (d_tag == "nom_1p50e5" or a_tag == "nom_1p34e9"):
                        continue  # Always test ALL 4 (D x alpha) at bounding 35 mmHg + worst-case lowD+KRBH at 40/45!
                    row = _track_o2(run_r4_clinical_bilayer_case(
                        c, site_name="R4O_Tier1_Admitted_1200", loading_ieq_cm2=1200.0, h_um=120.0,
                        bed_po2_mmhg=p_bed, fibrin_um=fib, d_matrix_cm2_s=d_val, alpha_o2=a_val, top_adiabatic=False, nx=20, nz=20,
                    ))
                    row["d_tag"] = d_tag
                    row["alpha_tag"] = a_tag
                    require_cond(row["passes_15_and_5"], f"Tier-1 admitted corner failed: {row}")
                    tier1_admitted_corners.append(row)
    tier1_margin_12um = _track_o2(run_r4_clinical_bilayer_case(
        c, site_name="R4O_Tier1_Margin_1200_12um", loading_ieq_cm2=1200.0, h_um=120.0,
        bed_po2_mmhg=35.0, fibrin_um=12.0, d_matrix_cm2_s=d_low, alpha_o2=a_krbh, top_adiabatic=False, nx=20, nz=20,
    ))
    require_cond(tier1_margin_12um["passes_15_and_5"], f"Tier-1 12um safety margin failed: {tier1_margin_12um}")

    # (4b) Tier-2 High-Perfusion Gated Envelope (<=1,500 IEQ/cm^2, strictly gated to bed >=40 mmHg, fibrin <=12 um, full low-D + KRBH)
    tier2_admitted_corners = []
    for p_bed in (40.0, 45.0):
        for fib in (0.0, 10.0, 12.0):
            for d_tag, d_val in (("nom_1p50e5", d_nom), ("lowD_0p94e5", d_low)):
                for a_tag, a_val in (("nom_1p34e9", a_nom), ("KRBH_1p27e9", a_krbh)):
                    if p_bed == 45.0 and (d_tag == "nom_1p50e5" or a_tag == "nom_1p34e9"):
                        continue
                    if fib == 0.0 and (d_tag == "nom_1p50e5" or a_tag == "nom_1p34e9"):
                        continue
                    row = _track_o2(run_r4_clinical_bilayer_case(
                        c, site_name="R4O_Tier2_Admitted_1500_Bed40", loading_ieq_cm2=1500.0, h_um=120.0,
                        bed_po2_mmhg=p_bed, fibrin_um=fib, d_matrix_cm2_s=d_val, alpha_o2=a_val, top_adiabatic=False, nx=20, nz=20,
                    ))
                    row["d_tag"] = d_tag
                    row["alpha_tag"] = a_tag
                    require_cond(row["passes_15_and_5"], f"Tier-2 admitted corner failed: {row}")
                    tier2_admitted_corners.append(row)

    # (4c) Explicitly Documented OUT-OF-ENVELOPE FAIL Proofs (Audit & Review P0-3 / C2.1 corners!)
    out_of_envelope_fails = []
    for label, load, p_bed, fib, d_tag, d_val, a_tag, a_val, top_ad in [
        ("FAIL_1500_at_35mmHg_lowD_nom_10um", 1500.0, 35.0, 10.0, "lowD", d_low, "nom", a_nom, False),
        ("FAIL_1500_at_35mmHg_lowD_KRBH_10um", 1500.0, 35.0, 10.0, "lowD", d_low, "KRBH", a_krbh, False),
        ("FAIL_1800_RETIRED_35mmHg_lowD_nom_10um", 1800.0, 35.0, 10.0, "lowD", d_low, "nom", a_nom, False),
        ("FAIL_1800_RETIRED_35mmHg_lowD_KRBH_10um", 1800.0, 35.0, 10.0, "lowD", d_low, "KRBH", a_krbh, False),
        ("FAIL_1800_RETIRED_35mmHg_lowD_nom_19um_BOTH_FAIL", 1800.0, 35.0, 19.0, "lowD", d_low, "nom", a_nom, False),
        ("FAIL_1800_RETIRED_40mmHg_lowD_KRBH_10um", 1800.0, 40.0, 10.0, "lowD", d_low, "KRBH", a_krbh, False),
        ("FAIL_2500_OVERLOADED_35mmHg_lowD_0um", 2500.0, 35.0, 0.0, "lowD", d_low, "nom", a_nom, False),
        ("FAIL_STACKED_BACK_TO_BACK_3000_DOUBLED_TIER2_35mmHg_lowD_0um", 3000.0, 35.0, 0.0, "lowD", d_low, "nom", a_nom, False),
        ("FAIL_STACKED_BACK_TO_BACK_3000_DOUBLED_TIER2_35mmHg_lowD_10um", 3000.0, 35.0, 10.0, "lowD", d_low, "nom", a_nom, False),
        ("FAIL_STACKED_BACK_TO_BACK_3600_RETIRED_OVERLOAD_35mmHg_lowD_0um", 3600.0, 35.0, 0.0, "lowD", d_low, "nom", a_nom, False),
        ("FAIL_STACKED_BACK_TO_BACK_3600_RETIRED_OVERLOAD_35mmHg_lowD_10um", 3600.0, 35.0, 10.0, "lowD", d_low, "nom", a_nom, False),
        ("FAIL_UNILATERAL_1200_35mmHg_lowD_0um", 1200.0, 35.0, 0.0, "lowD", d_low, "nom", a_nom, True),
        ("FAIL_UNILATERAL_1500_35mmHg_lowD_0um", 1500.0, 35.0, 0.0, "lowD", d_low, "nom", a_nom, True),
        ("FAIL_UNILATERAL_1500_40mmHg_lowD_10um", 1500.0, 40.0, 10.0, "lowD", d_low, "nom", a_nom, True),
        ("FAIL_UNILATERAL_1800_40mmHg_lowD_10um", 1800.0, 40.0, 10.0, "lowD", d_low, "nom", a_nom, True),
    ]:
        row = _track_o2(run_r4_clinical_bilayer_case(
            c, site_name=label, loading_ieq_cm2=load, h_um=120.0,
            bed_po2_mmhg=p_bed, fibrin_um=fib, d_matrix_cm2_s=d_val, alpha_o2=a_val, top_adiabatic=top_ad, nx=20, nz=20,
        ))
        row["d_tag"] = d_tag
        row["alpha_tag"] = a_tag
        require_cond(not row["passes_15_and_5"], f"Out-of-envelope case unexpectedly passed: {row}")
        out_of_envelope_fails.append(row)

    # Two-plane overload surrogate proofs for doubled Tier-1 (2,400 IEQ/cm^2) back-to-back stacking (Audit F16 P2):
    # 0 um fibrin face/core = 12.0622 / 11.3664 mmHg; 10 um fibrin face/core = 4.4184 / 3.7651 mmHg
    stacked_doubled_tier1_2400_fails = []
    for label, fib in [
        ("FAIL_TWO_PLANE_OVERLOAD_SURROGATE_2400_DOUBLED_TIER1_35mmHg_lowD_0um", 0.0),
        ("FAIL_TWO_PLANE_OVERLOAD_SURROGATE_2400_DOUBLED_TIER1_35mmHg_lowD_10um", 10.0),
    ]:
        row = _track_o2(run_r4_clinical_bilayer_case(
            c, site_name=label, loading_ieq_cm2=2400.0, h_um=120.0,
            bed_po2_mmhg=35.0, fibrin_um=fib, d_matrix_cm2_s=d_low, alpha_o2=a_nom, top_adiabatic=False, nx=20, nz=20,
        ))
        row["geometry_model_note"] = "Two-plane overload surrogate for doubled Tier-1 (2,400 IEQ/cm^2) unperfused stacking"
        require_cond(not row["passes_15_and_5"], f"Doubled Tier-1 two-plane overload surrogate 2400 unexpectedly passed: {row}")
        stacked_doubled_tier1_2400_fails.append(row)
    require_cond(
        abs(stacked_doubled_tier1_2400_fails[0]["worst_face_mmhg"] - 12.0622) < 1e-3
        and abs(stacked_doubled_tier1_2400_fails[0]["worst_core_mmhg"] - 11.3664) < 1e-3
        and abs(stacked_doubled_tier1_2400_fails[1]["worst_face_mmhg"] - 4.4184) < 1e-3
        and abs(stacked_doubled_tier1_2400_fails[1]["worst_core_mmhg"] - 3.7651) < 1e-3,
        f"2,400 IEQ/cm^2 two-plane overload surrogate face/core mismatch: {stacked_doubled_tier1_2400_fails}",
    )

    # (4c-R4) Round-4 Audit F4 FVM FAIL proofs: implied 500k/300 cm^2 = 1,666.67 IEQ/cm^2 overload & 0.75x low-D matrix
    r4_implied_1667_t1 = _track_o2(run_r4_clinical_bilayer_case(
        c, site_name="FAIL_SOL_F4_IMPLIED_1666P67_IEQ_CM2_TIER1_35mmHg_10um_lowD_KRBH",
        loading_ieq_cm2=500_000.0 / 300.0, h_um=120.0, bed_po2_mmhg=35.0, fibrin_um=10.0,
        d_matrix_cm2_s=d_low, alpha_o2=a_krbh, nx=20, nz=20,
    ))
    r4_implied_1667_t2 = _track_o2(run_r4_clinical_bilayer_case(
        c, site_name="FAIL_SOL_F4_IMPLIED_1666P67_IEQ_CM2_TIER2_40mmHg_12um_lowD_KRBH",
        loading_ieq_cm2=500_000.0 / 300.0, h_um=120.0, bed_po2_mmhg=40.0, fibrin_um=12.0,
        d_matrix_cm2_s=d_low, alpha_o2=a_krbh, nx=20, nz=20,
    ))
    r4_degraded_0p75d_t1 = _track_o2(run_r4_clinical_bilayer_case(
        c, site_name="FAIL_SOL_F4_DEGRADED_0P75X_LOWD_MATRIX_TIER1_1200_35mmHg_10um_KRBH",
        loading_ieq_cm2=1200.0, h_um=120.0, bed_po2_mmhg=35.0, fibrin_um=10.0,
        d_matrix_cm2_s=0.75 * d_low, alpha_o2=a_krbh, nx=20, nz=20,
    ))
    r4_degraded_0p75d_t2 = _track_o2(run_r4_clinical_bilayer_case(
        c, site_name="FAIL_SOL_F4_DEGRADED_0P75X_LOWD_MATRIX_TIER2_1500_40mmHg_12um_KRBH",
        loading_ieq_cm2=1500.0, h_um=120.0, bed_po2_mmhg=40.0, fibrin_um=12.0,
        d_matrix_cm2_s=0.75 * d_low, alpha_o2=a_krbh, nx=20, nz=20,
    ))
    require_cond(not r4_implied_1667_t1["passes_15_and_5"] and not r4_implied_1667_t2["passes_15_and_5"], "Audit F4 1,666.67 implied overload must FAIL both tiers")
    require_cond(not r4_degraded_0p75d_t1["passes_15_and_5"] and not r4_degraded_0p75d_t2["passes_15_and_5"], "Audit F4 0.75x low-D degraded matrix must FAIL both tiers")
    round4_leaf_overload_and_matrix_diffusivity_fail_proofs = {
        "d_o2_low_modeled_floor_m2_s": D_O2_LOW_MODELED_M2_S,
        "implied_1666p67_tier1_FAIL": r4_implied_1667_t1,
        "implied_1666p67_tier2_FAIL": r4_implied_1667_t2,
        "degraded_0p75x_lowD_tier1_FAIL": r4_degraded_0p75d_t1,
        "degraded_0p75x_lowD_tier2_FAIL": r4_degraded_0p75d_t2,
    }

    # (4c-R3) Four Explicit Round-3 Sensitivity/FAIL Proofs (Review C2 P0 & Audit R2-04 / R2-19!)
    p1200_mono65 = math.sqrt((v65 / vol_ieq) / 1200.0) * 1e4
    p1500_mono65 = math.sqrt((v65 / vol_ieq) / 1500.0) * 1e4
    r3_midplane_zc10_t1 = _track_o2(run_r4_clinical_bilayer_case(
        c, site_name="FAIL_MIDPLANE_SHIFT_ZC10_TIER1_1200_35mmHg_10um_lowD_KRBH",
        loading_ieq_cm2=1200.0, h_um=120.0, bed_po2_mmhg=35.0, fibrin_um=10.0,
        d_matrix_cm2_s=d_low, alpha_o2=a_krbh, z_c_um=10.0, nx=20, nz=20,
    ))
    r3_midplane_zc10_t2 = _track_o2(run_r4_clinical_bilayer_case(
        c, site_name="FAIL_MIDPLANE_SHIFT_ZC10_TIER2_1500_40mmHg_12um_lowD_KRBH",
        loading_ieq_cm2=1500.0, h_um=120.0, bed_po2_mmhg=40.0, fibrin_um=12.0,
        d_matrix_cm2_s=d_low, alpha_o2=a_krbh, z_c_um=10.0, nx=20, nz=20,
    ))
    r3_midplane_zc20_t1_pass = _track_o2(run_r4_clinical_bilayer_case(
        c, site_name="PASS_FLOOR_ZC20_TIER1_1200_35mmHg_10um_lowD_KRBH",
        loading_ieq_cm2=1200.0, h_um=120.0, bed_po2_mmhg=35.0, fibrin_um=10.0,
        d_matrix_cm2_s=d_low, alpha_o2=a_krbh, z_c_um=20.0, nx=20, nz=20,
    ))
    r3_midplane_zc20_t2_pass = _track_o2(run_r4_clinical_bilayer_case(
        c, site_name="PASS_FLOOR_ZC20_TIER2_1500_40mmHg_12um_lowD_KRBH",
        loading_ieq_cm2=1500.0, h_um=120.0, bed_po2_mmhg=40.0, fibrin_um=12.0,
        d_matrix_cm2_s=d_low, alpha_o2=a_krbh, z_c_um=20.0, nx=20, nz=20,
    ))
    r3_ocr_plus10_t1 = _track_o2(run_r4_clinical_bilayer_case(
        c, site_name="FAIL_LOT_OCR_PLUS10PCT_TIER1_1200_35mmHg_10um_lowD_KRBH",
        loading_ieq_cm2=1200.0, h_um=120.0, bed_po2_mmhg=35.0, fibrin_um=10.0,
        d_matrix_cm2_s=d_low, alpha_o2=a_krbh, ocr_mult=1.097 * 1.10, nx=24, nz=24,
    ))
    r3_ocr_plus10_t2 = _track_o2(run_r4_clinical_bilayer_case(
        c, site_name="FAIL_LOT_OCR_PLUS10PCT_TIER2_1500_40mmHg_12um_lowD_KRBH",
        loading_ieq_cm2=1500.0, h_um=120.0, bed_po2_mmhg=40.0, fibrin_um=12.0,
        d_matrix_cm2_s=d_low, alpha_o2=a_krbh, ocr_mult=1.097 * 1.10, nx=24, nz=24,
    ))
    r3_asym_25_45_t1 = _track_o2(run_r4_clinical_bilayer_case(
        c, site_name="FAIL_ASYMMETRIC_BILATERAL_BED_25_45_MEAN35_TIER1_1200_10um_lowD_KRBH",
        loading_ieq_cm2=1200.0, h_um=120.0, bed_po2_mmhg=35.0,
        bed_po2_bot_mmhg=25.0, bed_po2_top_mmhg=45.0, fibrin_um=10.0,
        d_matrix_cm2_s=d_low, alpha_o2=a_krbh, nx=24, nz=24,
    ))
    r3_mono65_1200 = _track_o2(run_r4_monolayer_case(
        c, site_name="FAIL_SAME_LOAD_DEPTH_65UM_MONOLAYER_1200_H120_35mmHg_10um_lowD_KRBH",
        cluster_diam_um=65.0, pitch_um=p1200_mono65, bed_po2_mmhg=35.0, fibrin_um=10.0,
        d_matrix_cm2_s=d_low, interstitial_margin_each_um=27.5, alpha_o2=a_krbh, top_adiabatic=False, nx=24, nz=20,
    ))
    r3_mono65_1500 = _track_o2(run_r4_monolayer_case(
        c, site_name="FAIL_SAME_LOAD_DEPTH_65UM_MONOLAYER_1500_H120_40mmHg_12um_lowD_KRBH",
        cluster_diam_um=65.0, pitch_um=p1500_mono65, bed_po2_mmhg=40.0, fibrin_um=12.0,
        d_matrix_cm2_s=d_low, interstitial_margin_each_um=27.5, alpha_o2=a_krbh, top_adiabatic=False, nx=24, nz=20,
    ))
    require_cond(not r3_midplane_zc10_t1["passes_15_and_5"] and abs(r3_midplane_zc10_t1["worst_face_mmhg"] - 14.6028) < 1e-3, "zc=10 T1 FAIL mismatch")
    require_cond(not r3_midplane_zc10_t2["passes_15_and_5"] and abs(r3_midplane_zc10_t2["worst_face_mmhg"] - 13.9908) < 1e-3, "zc=10 T2 FAIL mismatch")
    require_cond(r3_midplane_zc20_t1_pass["passes_15_and_5"] and r3_midplane_zc20_t2_pass["passes_15_and_5"], "zc=20 floor must PASS both tiers")
    require_cond(not r3_ocr_plus10_t1["passes_15_and_5"] and abs(r3_ocr_plus10_t1["worst_face_mmhg"] - 14.6341) < 1e-3, "+10% OCR T1 FAIL mismatch")
    require_cond(not r3_ocr_plus10_t2["passes_15_and_5"] and abs(r3_ocr_plus10_t2["worst_face_mmhg"] - 14.3183) < 1e-3, "+10% OCR T2 FAIL mismatch")
    require_cond(not r3_asym_25_45_t1["passes_15_and_5"] and abs(r3_asym_25_45_t1["worst_face_mmhg"] - 14.9212) < 1e-3, "Asymmetric 25/45 T1 FAIL mismatch")
    require_cond(not r3_mono65_1200["passes_15_and_5"] and abs(r3_mono65_1200["worst_face_mmhg"] - 14.0490) < 1e-3, "Same-load 65um monolayer 1200 FAIL mismatch")
    require_cond(not r3_mono65_1500["passes_15_and_5"] and abs(r3_mono65_1500["worst_face_mmhg"] - 13.1827) < 1e-3, "Same-load 65um monolayer 1500 FAIL mismatch")

    v20 = (math.pi / 6.0) * ((20.0e-4) ** 3)
    steric_20um_pitch_1200 = round(math.sqrt(1.0 / (0.5 * 1200.0 * vol_ieq / v20)) * 1e4, 2)
    steric_20um_pitch_1500 = round(math.sqrt(1.0 / (0.5 * 1500.0 * vol_ieq / v20)) * 1e4, 2)
    require_cond(steric_20um_pitch_1200 < 20.0 and steric_20um_pitch_1500 < 20.0, "20 um clusters must exhibit steric overlap at 1200-1500 IEQ/cm^2")

    round3_placement_ocr_asym_layout_proofs = {
        "proof_1_midplane_shift_zc10_FAIL_vs_zc20_floor_PASS": {
            "gate33_rule_proven": "|z_c| >= 20.0 um AND live GY-028 confocal wall clearance wall_clearance = H/2 - |z_c| - d_max/2 >= 7.5 um minimum mandatory (at H=120 um, d_max=65 um, |z_c|=20.0 um gives exact 7.50 um clearance and passes at 16.1228/14.1638 mmHg Tier-1 and 16.1438/14.4943 mmHg Tier-2); closer midplane placements (|z_c|=10 um) breach the 15.0 mmHg face floor.",
            "tier1_zc10_FAIL": r3_midplane_zc10_t1,
            "tier2_zc10_FAIL": r3_midplane_zc10_t2,
            "tier1_zc20_floor_PASS": r3_midplane_zc20_t1_pass,
            "tier2_zc20_floor_PASS": r3_midplane_zc20_t2_pass,
        },
        "proof_2_lot_ocr_plus10pct_FAIL": {
            "gate33_rule_proven": "Measured lot OCR multiplier <= 1.097x reference is mandatory; +10% lot OCR breaches the 15.0 mmHg face floor in both tiers.",
            "tier1_plus10pct_ocr_FAIL": r3_ocr_plus10_t1,
            "tier2_plus10pct_ocr_FAIL": r3_ocr_plus10_t2,
        },
        "proof_3_asymmetric_bilateral_bed_25_45_mean35_FAIL": {
            "gate33_rule_proven": "Minimum of BOTH perfused faces min(bed_face_bot_po2_mmhg, bed_face_top_po2_mmhg) >= tier_bed_floor is mandatory (mean 35 mmHg from 25/45 mmHg fails face floor at 14.9212 mmHg).",
            "tier1_25_45_mean35_FAIL": r3_asym_25_45_t1,
        },
        "proof_4_same_load_depth_65um_monolayer_H120_FAIL": {
            "gate33_rule_proven": "Staggered bilayer layout (construct_layout == 'STAGGERED_BILAYER') is mandatory; even 65 um clusters fail when placed in a same-load/depth H=120 um monolayer, qualifying the 100 um comparator as an alternate monolayer geometry.",
            "monolayer_65um_1200_H120_FAIL": r3_mono65_1200,
            "monolayer_65um_1500_H120_FAIL": r3_mono65_1500,
        },
        "proof_5_small_cluster_20um_steric_overlap_FAIL": {
            "gate33_rule_proven": "40.0 <= d_min <= d_rms3 <= d_p95 <= d_max <= 65.0 um plus explicit pitch_um > d_max and min_dist_um > d_max checks reject sterically overlapping 20 um clusters.",
            "d_20um_tier1_1200_pitch_um": steric_20um_pitch_1200,
            "d_20um_tier2_1500_pitch_um": steric_20um_pitch_1500,
            "steric_overlap_at_both_tiers": True,
        },
    }

    # (4d) Sparse Monolayer Admitted Envelope (matched pitch p=150 um, barrier <=25 um where BOTH O2 & t50 pass!)
    omentum_monolayer_sweep = []
    for p_bed in (35.0, 40.0, 45.0):
        for bar in (0.0, 20.0, 25.0):
            row = _track_o2(run_r4_monolayer_case(
                c, site_name="R4O_Monolayer_p150_lowD_KRBH", cluster_diam_um=65.0, pitch_um=150.0,
                bed_po2_mmhg=p_bed, fibrin_um=bar, d_matrix_cm2_s=d_low, alpha_o2=a_krbh,
                interstitial_margin_each_um=15.0, top_adiabatic=False, nx=24, nz=20,
            ))
            require_cond(row["passes_15_and_5"], f"Monolayer p=150 lowD KRBH <=25um failed: {row}")
            omentum_monolayer_sweep.append(row)

    # (4e) Alternate Monolayer Geometry Comparator: 100 um vs 65 um at Matched Loading (H=120 um, R2-19 qualified!)
    matched_100um_audit = {
        "geometry_qualification_note": (
            "Alternate monolayer geometry comparison (H=120 um): both 100 um monolayer (13.7115 / 14.3684 mmHg) AND "
            "same-load/depth 65 um monolayer (14.0490 / 13.1827 mmHg) fail at clinical 1,200/1,500 IEQ/cm^2, proving "
            "both <=65 um sieving AND staggered bilayer placement (|z_c| >= 20.0 um) are jointly required."
        ),
    }
    for key_lbl, target_load, p_bed, fib, a_val, exp_pass in [
        ("matched_1200_tier1_corner_35mmHg_10um_lowD_KRBH_FAIL", 1200.0, 35.0, 10.0, a_krbh, False),
        ("matched_1500_tier2_corner_40mmHg_12um_lowD_KRBH_FAIL", 1500.0, 40.0, 12.0, a_krbh, False),
        ("matched_361p65_dilute_monolayer_40mmHg_20um_lowD_nom_PASS", 361.65, 40.0, 20.0, a_nom, True),
    ]:
        p100_um = math.sqrt((v100 / vol_ieq) / target_load) * 1e4
        r100 = _track_o2(run_r4_monolayer_case(
            c, site_name=key_lbl, cluster_diam_um=100.0, pitch_um=p100_um,
            bed_po2_mmhg=p_bed, fibrin_um=fib, d_matrix_cm2_s=d_low, alpha_o2=a_val,
            interstitial_margin_each_um=10.0, top_adiabatic=False, nx=24, nz=20,
        ))
        require_cond(r100["passes_15_and_5"] is exp_pass, f"Matched 100um test {key_lbl} verdict mismatch: {r100}")
        matched_100um_audit[key_lbl] = r100

    # (4f) Matched-Pitch & Exact-Max-Loading/Max-Fibrin 3D FVM Insulin Shut-Off Audit
    p1200 = _bilayer_pitch_um(1200.0)
    p1500 = _bilayer_pitch_um(1500.0)
    p1800 = _bilayer_pitch_um(1800.0)
    ins_shutoff = {
        "monolayer_p150_H95_clean_PASS": _track_solute(compute_3d_fvm_insulin_shutoff_t50(
            h_um=95.0, pitch_um=150.0, cluster_diam_um=65.0, bilayer=False, fibrin_um=0.0, fibrin_d_factor=0.5,
            d_ins_matrix_cm2_s=c["d_insulin_hydrogel_cm2_s"], d_ins_islet_cm2_s=c["d_insulin_hydrogel_cm2_s"],
            t50_intrinsic_min=c["insulin_intrinsic_t50_min"], nx=18, nz=20, dt_s=2.0,
        )),
        "monolayer_p150_H95_20um_PASS": _track_solute(compute_3d_fvm_insulin_shutoff_t50(
            h_um=95.0, pitch_um=150.0, cluster_diam_um=65.0, bilayer=False, fibrin_um=20.0, fibrin_d_factor=0.5,
            d_ins_matrix_cm2_s=c["d_insulin_hydrogel_cm2_s"], d_ins_islet_cm2_s=c["d_insulin_hydrogel_cm2_s"],
            t50_intrinsic_min=c["insulin_intrinsic_t50_min"], nx=18, nz=20, dt_s=2.0,
        )),
        "monolayer_p150_H95_25um_CEILING_PASS": _track_solute(compute_3d_fvm_insulin_shutoff_t50(
            h_um=95.0, pitch_um=150.0, cluster_diam_um=65.0, bilayer=False, fibrin_um=25.0, fibrin_d_factor=0.5,
            d_ins_matrix_cm2_s=c["d_insulin_hydrogel_cm2_s"], d_ins_islet_cm2_s=c["d_insulin_hydrogel_cm2_s"],
            t50_intrinsic_min=c["insulin_intrinsic_t50_min"], nx=18, nz=20, dt_s=2.0,
        )),
        "monolayer_p150_H95_30um_FAIL": _track_solute(compute_3d_fvm_insulin_shutoff_t50(
            h_um=95.0, pitch_um=150.0, cluster_diam_um=65.0, bilayer=False, fibrin_um=30.0, fibrin_d_factor=0.5,
            d_ins_matrix_cm2_s=c["d_insulin_hydrogel_cm2_s"], d_ins_islet_cm2_s=c["d_insulin_hydrogel_cm2_s"],
            t50_intrinsic_min=c["insulin_intrinsic_t50_min"], nx=18, nz=20, dt_s=2.0,
        )),
        "monolayer_p150_H95_50um_FAIL": _track_solute(compute_3d_fvm_insulin_shutoff_t50(
            h_um=95.0, pitch_um=150.0, cluster_diam_um=65.0, bilayer=False, fibrin_um=50.0, fibrin_d_factor=0.5,
            d_ins_matrix_cm2_s=c["d_insulin_hydrogel_cm2_s"], d_ins_islet_cm2_s=c["d_insulin_hydrogel_cm2_s"],
            t50_intrinsic_min=c["insulin_intrinsic_t50_min"], nx=18, nz=20, dt_s=2.0,
        )),
        "tier1_bilayer_1200IEQ_H120_clean_PASS": _track_solute(compute_3d_fvm_insulin_shutoff_t50(
            h_um=120.0, pitch_um=p1200, cluster_diam_um=65.0, bilayer=True, fibrin_um=0.0, fibrin_d_factor=0.5,
            d_ins_matrix_cm2_s=c["d_insulin_hydrogel_cm2_s"], d_ins_islet_cm2_s=c["d_insulin_hydrogel_cm2_s"],
            t50_intrinsic_min=c["insulin_intrinsic_t50_min"], nx=18, nz=24, dt_s=2.0,
        )),
        "tier1_bilayer_1200IEQ_H120_10um_MAX_ADMITTED_PASS": _track_solute(compute_3d_fvm_insulin_shutoff_t50(
            h_um=120.0, pitch_um=p1200, cluster_diam_um=65.0, bilayer=True, fibrin_um=10.0, fibrin_d_factor=0.5,
            d_ins_matrix_cm2_s=c["d_insulin_hydrogel_cm2_s"], d_ins_islet_cm2_s=c["d_insulin_hydrogel_cm2_s"],
            t50_intrinsic_min=c["insulin_intrinsic_t50_min"], nx=18, nz=24, dt_s=2.0,
        )),
        "tier1_bilayer_1200IEQ_H120_10um_GY028_zc20_7p5um_PASS": _track_solute(compute_3d_fvm_insulin_shutoff_t50(
            h_um=120.0, pitch_um=p1200, cluster_diam_um=65.0, bilayer=True, fibrin_um=10.0, fibrin_d_factor=0.5,
            d_ins_matrix_cm2_s=c["d_insulin_hydrogel_cm2_s"], d_ins_islet_cm2_s=c["d_insulin_hydrogel_cm2_s"],
            t50_intrinsic_min=c["insulin_intrinsic_t50_min"], z_c_um=20.0, nx=18, nz=24, dt_s=2.0,
        )),
        "tier2_bilayer_1500IEQ_H120_clean_PASS": _track_solute(compute_3d_fvm_insulin_shutoff_t50(
            h_um=120.0, pitch_um=p1500, cluster_diam_um=65.0, bilayer=True, fibrin_um=0.0, fibrin_d_factor=0.5,
            d_ins_matrix_cm2_s=c["d_insulin_hydrogel_cm2_s"], d_ins_islet_cm2_s=c["d_insulin_hydrogel_cm2_s"],
            t50_intrinsic_min=c["insulin_intrinsic_t50_min"], nx=18, nz=24, dt_s=2.0,
        )),
        "tier2_bilayer_1500IEQ_H120_12um_MAX_ADMITTED_PASS": _track_solute(compute_3d_fvm_insulin_shutoff_t50(
            h_um=120.0, pitch_um=p1500, cluster_diam_um=65.0, bilayer=True, fibrin_um=12.0, fibrin_d_factor=0.5,
            d_ins_matrix_cm2_s=c["d_insulin_hydrogel_cm2_s"], d_ins_islet_cm2_s=c["d_insulin_hydrogel_cm2_s"],
            t50_intrinsic_min=c["insulin_intrinsic_t50_min"], nx=18, nz=24, dt_s=2.0,
        )),
        "tier2_bilayer_1500IEQ_H120_12um_GY028_zc20_7p5um_PASS": _track_solute(compute_3d_fvm_insulin_shutoff_t50(
            h_um=120.0, pitch_um=p1500, cluster_diam_um=65.0, bilayer=True, fibrin_um=12.0, fibrin_d_factor=0.5,
            d_ins_matrix_cm2_s=c["d_insulin_hydrogel_cm2_s"], d_ins_islet_cm2_s=c["d_insulin_hydrogel_cm2_s"],
            t50_intrinsic_min=c["insulin_intrinsic_t50_min"], z_c_um=20.0, nx=18, nz=24, dt_s=2.0,
        )),
        "out_of_envelope_bilayer_1500IEQ_19um_FAIL": _track_solute(compute_3d_fvm_insulin_shutoff_t50(
            h_um=120.0, pitch_um=p1500, cluster_diam_um=65.0, bilayer=True, fibrin_um=19.0, fibrin_d_factor=0.5,
            d_ins_matrix_cm2_s=c["d_insulin_hydrogel_cm2_s"], d_ins_islet_cm2_s=c["d_insulin_hydrogel_cm2_s"],
            t50_intrinsic_min=c["insulin_intrinsic_t50_min"], nx=18, nz=24, dt_s=2.0,
        )),
        "out_of_envelope_bilayer_1800IEQ_19um_FAIL": _track_solute(compute_3d_fvm_insulin_shutoff_t50(
            h_um=120.0, pitch_um=p1800, cluster_diam_um=65.0, bilayer=True, fibrin_um=19.0, fibrin_d_factor=0.5,
            d_ins_matrix_cm2_s=c["d_insulin_hydrogel_cm2_s"], d_ins_islet_cm2_s=c["d_insulin_hydrogel_cm2_s"],
            t50_intrinsic_min=c["insulin_intrinsic_t50_min"], nx=18, nz=24, dt_s=2.0,
        )),
    }
    for k, v_ins in ins_shutoff.items():
        if k.endswith("_PASS"):
            require_cond(v_ins["passes_lt_3p0_min"], f"Admitted insulin shutoff {k} failed: {v_ins}")
        elif k.endswith("_FAIL"):
            require_cond(not v_ins["passes_lt_3p0_min"], f"Out-of-envelope insulin shutoff {k} unexpectedly passed: {v_ins}")

    # (5) Part D: GY-014 Diazoxide Kill, H4-6-ExVivo (0.000 primary credit), & Decoupled Retrieval
    gy014_h46 = compute_gy014_diazoxide_kill_and_h46_exvivo(c)

    # (6) Part E: Corrected Footprint Geometry (total bilateral-perfused area = 500,000 / L cm^2; NO bogus /2!)
    n_cl_500k = 500_000.0 * vol_ieq / v65
    geometry_summary = {
        "packed_500k_ieq_volume_ml": round(500_000.0 * vol_ieq, 4),
        "packed_200k_ieq_volume_ml": round(200_000.0 * vol_ieq, 4),
        "clusters_65um_per_500k_ieq": int(round(n_cl_500k)),
        "sars_monolayer_p150_area_500k_cm2": round(n_cl_500k * (150e-4 ** 2), 1),
        "sars_monolayer_p200_area_500k_cm2": round(n_cl_500k * (200e-4 ** 2), 1),
        "sars_monolayer_p250_area_500k_cm2": round(n_cl_500k * (250e-4 ** 2), 1),
        "adult_human_greater_omentum_area_range_cm2": [300.0, 1500.0],
        "tier1_1200_IEQ_cm2_500k_total_bilateral_omental_area_cm2": round(500_000.0 / 1200.0, 1),
        "tier1_1200_IEQ_cm2_two_separated_vascularized_leaves_each_cm2": round((500_000.0 / 1200.0) / 2.0, 1),
        "tier1_1200_IEQ_cm2_200k_total_bilateral_area_cm2": round(200_000.0 / 1200.0, 1),
        "tier2_1500_IEQ_cm2_500k_total_bilateral_omental_area_cm2": round(500_000.0 / 1500.0, 1),
        "tier2_1500_IEQ_cm2_two_separated_vascularized_leaves_each_cm2": round((500_000.0 / 1500.0) / 2.0, 1),
        "tier2_1500_IEQ_cm2_200k_total_bilateral_area_cm2": round(200_000.0 / 1500.0, 1),
        "sars_backup_1200_IEQ_cm2_max_ieq_in_250cm2_adult_rectus": int(round(1200.0 * 250.0)),
        "folded_leaf_perfusion_invariant": (
            "Combined bilayer loading L counts BOTH cluster planes per unit bilateral-perfused sheet area, so 500,000 IEQ requires a "
            "nominal arithmetic floor of 500,000 / L cm^2 of bilateral-perfused omentum (416.7 cm^2 at 1,200 IEQ/cm^2; 333.3 cm^2 at 1,500 IEQ/cm^2) "
            "BEFORE surgical fold/seam/anatomical wastage (actual patient omental deployment requires extra perimeter/vascular-pedicle margin). "
            "If folded into two leaves (2 x 208.3 cm^2 or 2 x 166.7 cm^2 nominal), EACH leaf MUST be separated by intervening perfused vascularized omentum; "
            "two-plane overload surrogates for unperfused back-to-back stacking double Tier-1/Tier-2 effective loading to 2,400/3,000 IEQ/cm^2 "
            "(2,400 IEQ/cm^2: 0 um fibrin face/core = 12.0622/11.3664 mmHg, 10 um fibrin face/core = 4.4184/3.7651 mmHg; "
            "3,000 IEQ/cm^2: 0 um face/core = 7.6154/7.1684 mmHg, 10 um face/core = 1.1368/0.8304 mmHg), "
            "while retired 3,600 IEQ/cm^2 overload stress fails at 0 um face/core = 4.0060/3.7942 mmHg and 10 um face/core = 0.3295/0.2574 mmHg."
        ),
    }

    # (7) Part F: Exact Hash-Verified 2^20 Portfolio & Strassen Verification
    portfolio = compute_portfolio_verification(contracts)

    # (8) Part G: Strict Fail-Closed, Manifest-Linked Gate-35 Synthetic Self-Tests (promotion_authorized=False)
    gate33_tests = run_gate33_synthetic_adjudicator_self_tests(contracts["manifest"])

    receipt: Dict[str, Any] = {
        "schema_version": SCHEMA_VERSION,
        "staged_slot_id": STAGED_SLOT_ID,
        "contribution_id": CONTRIBUTION_ID,
        "decision_id": DECISION_ID,
        "gate_id": GATE_ID,
        "graveyard_card_id": GRAVEYARD_ID,
        "live_role_disambiguation": {
            "live_iip0047_dec127": "Occupied on live main (historical prior fold-in); W6-C2 uses staged slot IIP-0047 and provisional next-free IIP-0056 / DEC-137 pending atomic live fold-in allocation.",
            "live_gate32_dec130": "Occupied on live main (Islet-SHIELD debris recall); W6-C1 Dual-FailSafe uses collision-free GATE-34.",
            "live_gate33_dec131": "Occupied on live main (hTMPK/AZT PK); W6-C2 R4-Omentum & H4-6-ExVivo uses collision-free GATE-35 and GY-034 (live GY-032 occupied).",
        },
        "verification_mode": "STANDALONE" if standalone else "REPO_CROSS_VERIFIED",
        "zero_lims_touch_compliant": True,
        "canonical_contract_provenance": {
            "arm_manifest_schema_version": contracts["manifest_schema_version"],
            "arm_manifest_sha256": contracts["manifest_sha256"],
            "arm_manifest_canonical_json_sha256": contracts["manifest_canonical_json_sha256"],
            "master_contract_schema_version": contracts["contract_schema_version"],
            "master_contract_sha256": contracts["contract_sha256"],
            "master_contract_file_sha256": contracts["contract_file_sha256"],
            "all_canonical_arm_and_switch_definitions_verified": True,
        },
        "runtime_environment": {
            "python_version": sys.version.splitlines()[0],
            "python_version_info": list(sys.version_info[:3]),
            "numpy_version": np.__version__,
        },
        "global_fvm_mass_balance_audit": {
            "max_raw_o2_rel_mass_balance_error": _fmt_sci_float(max_o2_mbe),
            "max_raw_transient_solute_rel_mass_balance_error": _fmt_sci_float(max_solute_mbe),
            "o2_all_solves_lt_1e10": bool(max_o2_mbe < 1e-10),
            "transient_solute_all_solves_lt_1e10": bool(max_solute_mbe < 1e-10),
            "threshold": 1e-10,
        },
        "nw08_biophysical_constants": c,
        "part_a_incumbent_route3p_failure_and_parity": {
            "clean_35mmHg_65um": r3p_clean,
            "fibrin_10um_0p5D_35mmHg_65um_FAIL": r3p_fib10,
            "fibrin_15um_0p5D_35mmHg_65um_FAIL": r3p_fib15,
            "clean_30mmHg_KRBH_65um_FAIL": r3p_krbh30,
            "insulin_t50_clean_65um": r3p_t50_clean,
            "insulin_t50_10um_fibrin_65um_FAIL": r3p_t50_fib10,
            "exact_iip0034_parity_lt_1e3_mmhg": True,
        },
        "part_0_three_mesh_refinement_checks": three_mesh_convergence,
        "part_b_demoted_r4_sars_free_audit": {
            "disposition": "DEMOTED_TO_SECONDARY_BACKUP_LE_1200_IEQ_CM2_PLANAR_CARRIER_DUAL_FAILSAFE_Y_Z_ONLY_D1B_BARRED",
            "eligible_arms_canonical_manifest": ["ISLET1_DESIGN_Y_V3", "ISLET1_ARM_Z_ENSC_V090"],
            "barred_arms_canonical_manifest": ["ISLET1_DESIGN_A_V080_REF", "ISLET1_DESIGN_B_V090", "ISLET1_DESIGN_X_V090", "ISLET1_DESIGN_D1B_LEAN_K2"],
            "clinical_bilayer_3d_fvm_stress": sars_clinical_audit,
            "unilateral_clinical_2500_insulin_t50_FAIL": sars_t50_uni_2500,
            "liang_2022_pmid36624157_subars_cohort_correction": "n=4 diabetic NHPs received sub-ARS implants within n=8 total (vs intramuscular comparators), under xenogeneic systemic IS.",
            "wang_2024_pmid39326417_confounders": "N=1 recipient on maintenance tacrolimus from prior liver transplant; 1,488,283 IEQ (~19,843 IEQ/kg, ~3x adult 500k dose) in ~6 mL.",
        },
        "part_c_lead_visceral_r4_omentum": {
            "disposition": "PROSPECTIVE_STAGE0_HEAD_TO_HEAD_CANDIDATE_VS_ROUTE3P_PROMOTES_TO_LEAD_R4_ONLY_UPON_STAGE0_AND_LIVE_OQ012_GATES",
            "live_odds_credit_today_pp": 0.0,
            "eligible_arms_canonical_manifest": ["ISLET1_DESIGN_Y_V3", "ISLET1_DESIGN_D1B_LEAN_K2", "ISLET1_ARM_Z_ENSC_V090"],
            "clinical_matrix_lead": "GMP_AUTOLOGOUS_PLASMA_THROMBIN_OR_RESORBABLE_FIBRIN",
            "ppcn_disposition": (
                "STAGE0_RESEARCH_COMPARATOR_ONLY (Burke 2024 PMID:38848367: separate 4-animal PPCN-only biocompatibility cohort showed "
                "~20% visually residual non-hydrolyzable pNIPAAm at 3 mo; distinct 2 autologous graft NHPs underwent partial pancreatectomy "
                "plus chemical beta-cell ablation and averaged 2.8 and 3.0 U/day supplemental insulin after month 1 [0/2 insulin independent]; "
                "28 C LCST catheter-clogging risk, 0 human IND/DMF; post-omentectomy C-peptide extinction establishes assay-level localization in PPCN, "
                "NOT quantitative viable-cell mass retrieval in GMP fibrin)."
            ),
            "clinical_and_nhp_evidence_fidelity": {
                "nct02213003_miami_trial_results_2025_08_12": {
                    "enrollment_n": 3,
                    "hba1c_no_she_composite": "2/3 (66.7%)",
                    "procedural_complications": "3/3 (100%)",
                    "serious_adverse_events": "0/3 (0%)",
                    "primary_endpoint_window_days": [28, 365],
                    "calendar_study_duration_years": 10,
                },
                "verhoeff_2022_pmid35676866": {
                    "total_n": 264,
                    "extrahepatic_n": 9,
                    "extrahepatic_site_breakdown": {"omental": 4, "subcutaneous": 3, "gastric": 2},
                    "stimulated_c_peptide_comparison": "0.05 vs 1.2 nmol/L (P<0.001) pooled extrahepatic vs intraportal stimulated C-peptide at 1-3 months (NOT 1-year omental-specific)",
                },
                "van_hulle_2024_pmid38534981": {
                    "clamp_response": "2-8% of normal hyperglycemic clamp C-peptide in 4/7 recipients; 0/7 insulin-independent",
                    "suture_confounder_caution": "Polyglactin-910 suture subgroup caution; suture material is a plausible confounder, not a randomized causal proof of full efficacy rescue",
                },
                "deng_2023_pmid36863336": {
                    "nhp_n": 3,
                    "exogenous_insulin_continued_through_day": 28,
                    "sustained_insulin_independence_under_immunosuppression": "2/3 NHPs",
                },
                "burke_2024_pmid38848367": {
                    "ppcn_only_biocompatibility_cohort_n": 4,
                    "ppcn_only_3mo_visual_residual_pct": "~20% visually residual material",
                    "autologous_graft_cohort_n": 2,
                    "autologous_graft_model": "partial pancreatectomy + chemical beta-cell ablation (NOT total pancreatectomy)",
                    "autologous_graft_post_month1_insulin_u_day": [2.8, 3.0],
                    "autologous_graft_complete_insulin_independence": "0/2",
                },
                "nct07503028_crg002_registry": "ClinicalTrials.gov registry entry without posted clinical results; not efficacy evidence.",
                "pilot_sample_size_binomial_bounds": {
                    "porcine_0_of_6_one_sided_u95_pct": round(clopper_pearson_u95(0, 6, alpha=0.05) * 100.0, 1),
                    "nhp_3_of_4_exact_one_sided_l95_pct": 24.9,
                    "interpretation": "Pilot 0/6 (U95 = 39.3%) and 3/4 (L95 = 24.9%) gates provide Stage-1 feasibility filters, not powered pivotal statistical proof.",
                },
                "dec009_primate_free_alignment": {
                    "primary_pathway": "DEC-009 0-NHP primate-free strategy: porcine surgical safety (R4O-04) + Pillar 1 humanized mouse efficacy + Pillar 2 50-donor Chandler loop + Pillar 1 Cohort-3 GLP biodistribution/erasure (with DEC-009 Pillar 3 reserved strictly for the separate post-launch companion-dog cIslet-1 track).",
                    "conditional_nhp_exception": "Any NHP cohort (R4O-05) is strictly optional/conditional and requires explicit DEC-009 FDA CBER INTERACT/Pre-IND agreement (dec009_fda_cber_nhp_exception_authorized=True).",
                },
                "gate0s_insulin_inventory_and_glucagon_tail_note": (
                    "Stage-0 ex-vivo rest qualification (H4-6-ExVivo) must pair OQ-018 shutoff t50 and first-phase AUC with Gate 0S total insulin-inventory "
                    "reconciliation and full post-washout glucagon-tail completeness (not solely peak glucagon ratio)."
                ),
                "c4_r4_route_cap_assumption_disclosure": (
                    "The c4_r4 = 0.87 route cap (with c4_univ = 0.95 and phi_r4 = 0.30) is a supplied prospective scenario parameter, "
                    "not a statistically identified parameter from these small heterogeneous clinical cohorts; live Blueprint odds credit today is +0.00 pp."
                ),
            },
            "r4o_02_portal_fasl_ban_and_cuff_allowlist": {
                "fasl_disposition": "UNCONDITIONAL_HARD_VETO_ON_ALL_FASL_AND_CD95_AGONISTS",
                "strict_cuff_component_allowlist": sorted(ALLOWED_CUFF_COMPONENTS_ALLOWLIST),
            },
            "admitted_clinical_bilayer_operating_envelope": {
                "tier_union_rule": "Monotone UNION of Tier-1 (load <= 1,200, min_bilateral_bed >= 35.0, fibrin <= 10.0) OR Tier-2 (load <= 1,500, min_bilateral_bed >= 40.0, fibrin <= 12.0), with mandatory STAGGERED_BILAYER layout, 100 <= H <= 120 um, 40 <= d_min <= d_rms3 <= d_p95 <= d_max <= 65 um, |z_c| >= 20.0 um, live GY-028 confocal wall clearance wall_clearance = H/2 - |z_c| - d_max/2 >= 7.5 um minimum, pitch_um > d_max, min_dist_um > d_max, lot OCR <= 1.097x, face O2 >= 15.0 mmHg, and core O2 >= 5.0 mmHg.",
                "wall_clearance_definition": "wall_clearance = H/2 - |z_c| - d_max/2 >= 7.5 um minimum (live GY-028 confocal outer-cluster-to-slab-wall spacing; at H=120 um, d_max=65 um, |z_c|=20.0 um gives exact 7.50 um clearance).",
                "tier1_primary_unconditional": {
                    "max_loading_ieq_cm2": 1200.0,
                    "min_bed_po2_mmhg": 35.0,
                    "max_fibrin_capsule_um": 10.0,
                    "slab_thickness_range_um": [100.0, 120.0],
                    "cluster_diam_range_um": [40.0, 65.0],
                    "min_staggered_plane_offset_um": 20.0,
                    "min_wall_clearance_um": 7.5,
                    "max_lot_ocr_mult": 1.097,
                    "bilateral_vascular_perfusion_mandatory": True,
                    "worst_admitted_corner_face_core_mmhg": [
                        min(r["worst_face_mmhg"] for r in tier1_admitted_corners),
                        min(r["worst_core_mmhg"] for r in tier1_admitted_corners),
                    ],
                    "gy028_zc20_7p5um_face_core_mmhg": [
                        r3_midplane_zc20_t1_pass["worst_face_mmhg"],
                        r3_midplane_zc20_t1_pass["worst_core_mmhg"],
                    ],
                    "max_admitted_t50_min": ins_shutoff["tier1_bilayer_1200IEQ_H120_10um_MAX_ADMITTED_PASS"]["t50_3d_fvm_min"],
                    "gy028_zc20_7p5um_t50_min": ins_shutoff["tier1_bilayer_1200IEQ_H120_10um_GY028_zc20_7p5um_PASS"]["t50_3d_fvm_min"],
                    "all_admitted_corners_pass_o2_and_t50": True,
                    "corners": tier1_admitted_corners,
                    "safety_margin_12um_check": tier1_margin_12um,
                },
                "tier2_high_perfusion_gated": {
                    "max_loading_ieq_cm2": 1500.0,
                    "min_measured_bed_po2_mmhg": 40.0,
                    "max_fibrin_capsule_um": 12.0,
                    "slab_thickness_range_um": [100.0, 120.0],
                    "cluster_diam_range_um": [40.0, 65.0],
                    "min_staggered_plane_offset_um": 20.0,
                    "min_wall_clearance_um": 7.5,
                    "max_lot_ocr_mult": 1.097,
                    "bilateral_vascular_perfusion_mandatory": True,
                    "worst_admitted_corner_face_core_mmhg": [
                        min(r["worst_face_mmhg"] for r in tier2_admitted_corners),
                        min(r["worst_core_mmhg"] for r in tier2_admitted_corners),
                    ],
                    "gy028_zc20_7p5um_face_core_mmhg": [
                        r3_midplane_zc20_t2_pass["worst_face_mmhg"],
                        r3_midplane_zc20_t2_pass["worst_core_mmhg"],
                    ],
                    "max_admitted_t50_min": ins_shutoff["tier2_bilayer_1500IEQ_H120_12um_MAX_ADMITTED_PASS"]["t50_3d_fvm_min"],
                    "gy028_zc20_7p5um_t50_min": ins_shutoff["tier2_bilayer_1500IEQ_H120_12um_GY028_zc20_7p5um_PASS"]["t50_3d_fvm_min"],
                    "all_admitted_corners_pass_o2_and_t50": True,
                    "corners": tier2_admitted_corners,
                },
                "retired_out_of_envelope_limits": [
                    "1,800 IEQ/cm^2 clinical cap (RETIRED: fails at 35 mmHg/low-D/10 um and 40 mmHg/low-D/KRBH/10 um)",
                    "1,500 IEQ/cm^2 at 35 mmHg (RETIRED: fails low-D/10 um at 14.00/12.90 mmHg -> strictly gated to min bilateral bed >= 40 mmHg)",
                    "19 um fibrin capsule (RETIRED: fails insulin shutoff t50 = 3.0793-3.0806 > 3.0 min)",
                    "Back-to-back unperfused folded stacking (two-plane overload surrogate 2,400 IEQ/cm^2: 0 um face/core = 12.0622/11.3664 mmHg, 10 um face/core = 4.4184/3.7651 mmHg; 3,000 IEQ/cm^2: 0 um 7.6154/7.1684, 10 um 1.1368/0.8304; retired 3,600: 0 um 4.0060/3.7942, 10 um 0.3295/0.2574 mmHg)",
                    "Unilateral acute perfusion (fails at 0.27-0.01 mmHg)",
                    "Midplane-shifted bilayer |z_c| = 10 um (fails at 14.6028/13.9908 mmHg -> |z_c| >= 20.0 um AND live GY-028 wall_clearance >= 7.5 um mandatory)",
                    "+10% lot OCR (fails at 14.6341/14.3183 mmHg -> lot OCR <= 1.097x mandatory)",
                    "Asymmetric bilateral bed 25/45 mmHg mean 35 (fails at 14.9212 mmHg -> min(bot, top) >= tier floor mandatory)",
                    "Same-load/depth 65 um monolayer H=120 um (fails at 14.0490/13.1827 mmHg -> STAGGERED_BILAYER layout mandatory)",
                    "Implied leaf overload 500k/300 cm^2 = 1,666.67 IEQ/cm^2 and degraded 0.75x low-D matrix (both FAIL 15 mmHg face floor -> per-leaf area/IEQ & D_O2 >= 9.40254e-10 m^2/s mandatory)",
                ],
            },
            "out_of_envelope_fail_proofs_ALL_FAIL": out_of_envelope_fails,
            "stacked_doubled_tier1_2400_fail_proofs_ALL_FAIL": stacked_doubled_tier1_2400_fails,
            "round3_physical_placement_ocr_asymmetry_and_layout_fail_proofs": round3_placement_ocr_asym_layout_proofs,
            "round4_leaf_overload_and_matrix_diffusivity_fail_proofs": round4_leaf_overload_and_matrix_diffusivity_fail_proofs,
            "monolayer_p150_lowD_KRBH_0_to_25um_ALL_PASS": omentum_monolayer_sweep,
            "matched_loading_100um_vs_65um_sieving_audit": matched_100um_audit,
            "insulin_shutoff_3d_fvm_matched_pitch_and_envelope_bounds": ins_shutoff,
            "enbloc_retrievability_prospective_stage1_target_pct": 99.9,
        },
        "part_d_gy014_diazoxide_kill_and_h46_exvivo": gy014_h46,
        "part_e_geometry_and_footprint_scaling": geometry_summary,
        "part_f_exact_2pow20_portfolio": portfolio,
        "part_g_gate33_synthetic_adjudicator_self_tests": gate33_tests,
        "verified_pmids": VERIFIED_PMIDS,
        "verified_trials": ["NCT02213003", "NCT07503028"],
    }
    receipt["portable_payload_sha256"] = compute_portable_payload_sha256(receipt)
    return receipt


def build_cli_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description="W6-C2 (staged slot IIP-0047; provisional IIP-0056 / DEC-137 / GATE-35 / GY-034) Visceral R4-Omentum & H4-6-ExVivo Verifier (Round-14 Fail-Closed)"
    )
    parser.add_argument("--standalone", action="store_true", help="Self-contained verification using pinned NW-08/IIP-0034 constants plus external hash-verified Wave-6 contracts")
    parser.add_argument("--repo-root", type=Path, default=None, help="Optional read-only OpenIslet repository root for live NW-08 constant cross-check")
    parser.add_argument("--master-contract", type=Path, default=None, help="Explicit wave6_master_contract.json (pairs strictly with sibling manifest in same directory unless --arm-manifest/--manifest overrides)")
    parser.add_argument("--arm-manifest", "--manifest", dest="arm_manifest", type=Path, default=None, help="Explicit wave6_canonical_arm_manifest.json override")
    parser.add_argument("--out", "--output", dest="out", type=Path, default=None, help="Output receipt JSON path")
    parser.add_argument("--check", action="store_true", help="Read-only byte-exact receipt check (writes nothing)")
    parser.add_argument("--check-portable", action="store_true", help="Read-only cross-build semantic check requiring valid portable_payload_sha256")
    return parser


def main(argv: Sequence[str] | None = None) -> None:
    t0 = time.perf_counter()
    args = build_cli_parser().parse_args(argv)
    standalone = bool(args.standalone or args.repo_root is None)
    repo_root = args.repo_root.expanduser().resolve() if args.repo_root is not None else None
    out_path = args.out.expanduser().resolve() if args.out is not None else DEFAULT_OUT_PATH

    receipt = run_verification(
        repo_root=repo_root,
        standalone=standalone,
        manifest_path=args.arm_manifest,
        master_contract_path=args.master_contract,
    )
    raw_json = json.dumps(receipt, indent=2, ensure_ascii=False, allow_nan=False) + "\n"
    expected_bytes = raw_json.encode("utf-8")
    elapsed_s = time.perf_counter() - t0

    c2_c1 = receipt["part_f_exact_2pow20_portfolio"]["reachable_scenarios"]["W6_C2_plus_C1_R4Omentum_zeroRest"]
    c2_iso = receipt["part_f_exact_2pow20_portfolio"]["diagnostic_prerequisite_waived_counterfactuals"]["Diag_PrereqWaived_C2_isolated_zeroRest"]
    g33 = receipt["part_g_gate33_synthetic_adjudicator_self_tests"]

    if args.check:
        require_cond(out_path.is_file(), f"--check failed: receipt missing at {out_path}")
        existing_bytes = out_path.read_bytes()
        require_cond(
            existing_bytes == expected_bytes,
            f"--check failed: raw byte mismatch for {out_path.name} "
            f"(existing={sha256_bytes(existing_bytes)}, fresh={sha256_bytes(expected_bytes)})",
        )
        print(
            f"PASS (--check byte-exact): mode={receipt['verification_mode']} "
            f"C2+C1={c2_c1['modular_pct']:.4f}% Diag_C2_iso={c2_iso['modular_pct']:.4f}% "
            f"gate33_self_tests={g33['passed_cases']}/{g33['total_cases']} "
            f"sha256={sha256_bytes(existing_bytes)} portable={receipt['portable_payload_sha256'][:12]} "
            f"elapsed={elapsed_s:.2f}s (optimize={sys.flags.optimize})"
        )
        return

    if args.check_portable:
        fresh_portable = verify_portable_receipt_file(out_path, receipt)
        print(
            f"PASS (--check-portable): mode={receipt['verification_mode']} "
            f"receipt={out_path.name} portable_payload_sha256={fresh_portable} "
            f"elapsed={elapsed_s:.2f}s (optimize={sys.flags.optimize})"
        )
        return

    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_bytes(expected_bytes)
    print(
        f"PASS: mode={receipt['verification_mode']} wrote={out_path} "
        f"C2+C1={c2_c1['modular_pct']:.4f}% (+{c2_c1['delta_vs_honest_l1_pct_pp']:.4f}pp) "
        f"Diag_C2_iso={c2_iso['modular_pct']:.4f}% (+{c2_iso['delta_vs_honest_l1_pct_pp']:.4f}pp) "
        f"sha256={sha256_bytes(expected_bytes)} portable={receipt['portable_payload_sha256']} "
        f"elapsed={elapsed_s:.2f}s (optimize={sys.flags.optimize})"
    )


if __name__ == "__main__":
    main()
