#!/usr/bin/env python3
"""
Standalone Zero-LIMS-Touch Verifier & Executable Stage-0 Lot Evaluator for
IIP-0045 / DEC-125 / GATE-31 / GY-031:
  "Bead size and oxygen-release half-life are one coupled gate, not two"
  (Community submission by giufra / @frafra013; GitHub Issue #45)

Capabilities:
  1. Verifies strict Zero-LIMS-Touch SHA-256 invariance (scripts/wetlab_contract.py,
     scripts/ingest_wetlab_results.py, data/protocols/wetlab_endpoint_contract_v0.8.0.json,
     Playbook §4.1.20 canonical body, DEC-132 refreshed Pareto pin 460ebc19...) without importing
     wetlab_contract.py.
  2. Executes live exact Layer-4 3D finite-volume reaction-diffusion replays
     (PureNumpy3DFVOperator, _solve_3d_h2o2_strict_iip_0019, _solve_3d_oxygen_strict_iip_0019)
     in the conserved 791.5 mg patient-CaO2 per-mass frame:
       - Per-bead 20 um conformal shell geometric unbuildability proof (5.832x-12.704x volume)
       - Conserved-inventory Hour-0 / Hour-18 / Hour-36 burst-H2O2 & acute-O2 sweep
         across t_1/2 in {4, 8, 12, 18, 24, 34, 68, 87} h at 100% and 50% catalase
       - Third-coupling barrier-induced O2 lag/attenuation sweep (1.00x down to 0.00x)
  3. Provides fail-closed, strict-JSON executable Stage-0 lot adjudication
     (`evaluate_gate31_coupled_cao2_lot`) across Gate 31-Scope, Gate 31-A, Gate 31-B,
     and Gate 31-C with zero uncaught tracebacks (exit codes: 0 PASS, 2 HOLD, 3 FAIL).
  4. Audits 68.0 h provenance, GY-013 / GY-031 graveyard sync, and stage0_decision_tree_v1.json
     append-only block parity.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import math
import re
import sys
from pathlib import Path
from typing import Any, Dict, List, Mapping, Optional, Tuple

import numpy as np


def _betacf_exact(a: float, b: float, x: float) -> float:
    """Continued fraction (Lentz) for regularized incomplete beta I_x(a, b)."""
    eps = 1e-15
    fpmin = 1e-300
    qab = a + b
    qap = a + 1.0
    qam = a - 1.0
    c = 1.0
    d = 1.0 - qab * x / qap
    if abs(d) < fpmin:
        d = fpmin
    d = 1.0 / d
    h = d
    for m in range(1, 201):
        m2 = 2 * m
        aa = m * (b - m) * x / ((qam + m2) * (a + m2))
        d = 1.0 + aa * d
        if abs(d) < fpmin:
            d = fpmin
        c = 1.0 + aa / c
        if abs(c) < fpmin:
            c = fpmin
        d = 1.0 / d
        h *= d * c
        aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
        d = 1.0 + aa * d
        if abs(d) < fpmin:
            d = fpmin
        c = 1.0 + aa / c
        if abs(c) < fpmin:
            c = fpmin
        d = 1.0 / d
        delta = d * c
        h *= delta
        if abs(delta - 1.0) < eps:
            break
    return h


def _betainc_exact(a: float, b: float, x: float) -> float:
    if x <= 0.0:
        return 0.0
    if x >= 1.0:
        return 1.0
    bt = math.exp(math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log(1.0 - x))
    if x < (a + 1.0) / (a + b + 2.0):
        return bt * _betacf_exact(a, b, x) / a
    return 1.0 - bt * _betacf_exact(b, a, 1.0 - x) / b


def _student_t_ppf_exact(p: float, df: int) -> float:
    """Pure-Python float64-exact Student-t quantile (zero external scipy dependency)."""
    if df < 1:
        raise ValueError(f"df must be >= 1, got {df}")
    if not (0.5 < p < 1.0):
        raise ValueError(f"p must be in (0.5, 1.0), got {p}")
    target_tail = 1.0 - p
    lo, hi = 0.0, 1.0
    while 0.5 * _betainc_exact(0.5 * df, 0.5, df / (df + hi * hi)) > target_tail:
        hi *= 2.0
    for _ in range(100):
        mid = 0.5 * (lo + hi)
        tail = 0.5 * _betainc_exact(0.5 * df, 0.5, df / (df + mid * mid))
        if tail > target_tail:
            lo = mid
        else:
            hi = mid
        if hi - lo <= 1e-13 * max(1.0, hi):
            break
    return 0.5 * (lo + hi)

SCRIPT_PATH = Path(__file__).resolve()
SCRIPT_DIR = SCRIPT_PATH.parent
REPO_ROOT = SCRIPT_DIR.parent

GENERATED_DATE = "2026-12-01"
CONTRIBUTION_ID = "IIP-0045"
DECISION_ID = "DEC-125"
GATE_ID = "GATE-31"
GRAVEYARD_CARD_ID = "GY-031"
GRAVEYARD_GUARDRAIL_ID = "OFFGRID_GUARD_021_DECOUPLED_CAO2_BEAD_SIZE_AND_RELEASE_HALFLIFE_GATING"

SIDE_CONTRACT_REL = "data/protocols/iip0045_cao2_coupled_gate31_side_contract_v0.8.0.json"
VERIFICATION_REL = "data/extracted/iip0045_cao2_coupled_gate31_verification_v0.8.0.json"
PROTOCOL_DOC_REL = "docs/GATE-31-CAO2-BEAD-HALFLIFE-BARRIER-COUPLED-PROTOCOL.md"
DECISION_TREE_REL = "data/protocols/stage0_decision_tree_v1.json"
DECISION_TREE_KEY = "cao2_coupled_bead_halflife_barrier_gate31_iip_0045"
GRAVEYARD_REL = "data/graveyard/idea_graveyard_v0.5.json"
PLAYBOOK_REL = "docs/STAGE-0-EXECUTION-PLAYBOOK.md"

FROZEN_LIMS_SHA256: Dict[str, str] = {
    "scripts/wetlab_contract.py": "331ecd2f2d8602dfceae8b89263d0f360cfadfd0638a46d7d668a376294cfc73",
    "scripts/ingest_wetlab_results.py": "e050593675170515382257ce379449db596c87cc06ffc26d31d128e127630cb1",
    "data/protocols/wetlab_endpoint_contract_v0.8.0.json": "757bc1d9c2722c129cc4fd5962e8995b9f5bc5f7035f8530f5716da9aa2ac26f",
}
EXPECTED_PARETO_SHA256 = "460ebc1939eb98b38627eaa7d6603c086e5a75c127fc1ddeced0d5a325305f40"
EXPECTED_PLAYBOOK_SEC4120_SHA256 = "e3fb5ec701678dfdeb62a77c15866327842b60b6b4c503cb86dfc79885a626a8"

ALLOWED_CAO2_ROUTES = frozenset({
    "SUPRAFASCIAL_350UM_CAO2_CATALASE_POUCH",
    "ROUTE_1_CAO2_390UM_EXPANDED_PLANAR_BARRIER",
    "ROUTE_1_CAO2_350UM_COMPRESSED_PLANAR_BARRIER",
})
ALLOWED_CAO2_DESIGNS = frozenset({"A", "X"})
EXCLUDED_NON_CAO2_DESIGNS = frozenset({"B", "Y", "D1", "Z"})

ALLOWED_BARRIER_MODES = frozenset({"PLANAR_CO_CAST_LAMINA_FACE_HYDROGEL_FILM"})
FORBIDDEN_BARRIER_MODES = frozenset({
    "PER_BEAD_CONFORMAL_SHELL",
    "HYDROPHOBIC_PDMS_RATE_LIMITING_SHELL",
    "UNCOATED_NO_BARRIER",
})
ALLOWED_SLAB_MODES = frozenset({
    "EXPANDED_390UM_2X125UM_BANDS",
    "FIXED_350UM_2X105UM_BANDS",
})

CONSERVED_CAO2_MG_TARGET = 791.49
CONSERVED_CAO2_MG_MIN = 751.9
CONSERVED_CAO2_MG_MAX = 831.1
Z_95_TWO_SIDED = 1.959963984540054


class StrictJsonError(ValueError):
    """Raised on malformed, duplicate-key, or non-finite JSON input."""


def _reject_nonfinite_constant(tok: str) -> Any:
    raise StrictJsonError(f"Non-finite JSON constant rejected: {tok}")


def _reject_duplicate_keys_pairs_hook(pairs: List[Tuple[str, Any]]) -> Dict[str, Any]:
    out: Dict[str, Any] = {}
    for k, v in pairs:
        if k in out:
            raise StrictJsonError(f"Duplicate JSON object key rejected: {k!r}")
        out[k] = v
    return out


def strict_json_loads(raw_text: str) -> Any:
    try:
        return json.loads(
            raw_text,
            parse_constant=_reject_nonfinite_constant,
            object_pairs_hook=_reject_duplicate_keys_pairs_hook,
        )
    except StrictJsonError:
        raise
    except Exception as exc:
        raise StrictJsonError(f"Malformed JSON payload: {exc}") from exc


def sha256_file(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def _is_finite_real(val: Any) -> bool:
    return isinstance(val, (int, float)) and not isinstance(val, bool) and math.isfinite(float(val))


def _extract_playbook_sec4120_sha256(repo_root: Path) -> str:
    pb_norm = (repo_root / PLAYBOOK_REL).read_text(encoding="utf-8").replace("\r\n", "\n").replace("\r", "\n")
    start_marker = "#### 4.1.20 Preregistered Autologous `D1b-Auto-C v2`"
    end_marker = "<!-- END_IIP0035_PLAYBOOK_SECTION_4_1_20 -->"
    start_idx = pb_norm.find(start_marker)
    end_idx = pb_norm.find(end_marker, start_idx if start_idx >= 0 else 0)
    if start_idx == -1 or end_idx == -1:
        raise RuntimeError("Playbook §4.1.20 canonical boundaries not found")
    body = pb_norm[start_idx:end_idx].strip()
    return hashlib.sha256(body.encode("utf-8")).hexdigest()


def compute_per_bead_shell_unbuildability_ledger() -> Dict[str, Any]:
    """Exact volumetric proof that a 20 um conformal shell on <=50 um beads cannot fit in the lamina."""
    rho_cao2 = 2.91
    rho_pdms = 1.03
    m_cao2_mg = CONSERVED_CAO2_MG_TARGET
    v_cao2_cm3 = (m_cao2_mg / 1000.0) / rho_cao2
    rcp_limit = 0.64

    rows: List[Dict[str, Any]] = []
    for form_id, wt_pct, lam_um, lam_vol_cm3 in (
        ("Layout_B_31p25wt_119um_Lamina", 31.25, 119.0, 2.3800),
        ("Design_X_46p39wt_100um_Lamina", 46.3906, 100.0, 2.0000),
    ):
        m_pdms_mg = m_cao2_mg * (100.0 - wt_pct) / wt_pct
        v_pdms_cm3 = (m_pdms_mg / 1000.0) / rho_pdms
        v_beads_cm3 = v_cao2_cm3 + v_pdms_cm3
        phi_bare = v_beads_cm3 / lam_vol_cm3
        for d_bead in (50.0, 40.0, 30.0):
            d_coated = d_bead + 40.0
            vol_mult = (d_coated / d_bead) ** 3
            v_coated = v_beads_cm3 * vol_mult
            phi_coated = v_coated / lam_vol_cm3
            rows.append({
                "formulation_id": form_id,
                "cao2_wt_pct": wt_pct,
                "lamina_thickness_um": lam_um,
                "lamina_volume_200cm2_cm3": lam_vol_cm3,
                "bare_bead_diameter_um": d_bead,
                "conformal_20um_shell_outer_diameter_um": d_coated,
                "volume_expansion_multiplier": round(vol_mult, 4),
                "bare_beads_volume_cm3": round(v_beads_cm3, 4),
                "bare_beads_lamina_volume_fraction": round(phi_bare, 4),
                "coated_beads_volume_cm3": round(v_coated, 4),
                "coated_beads_lamina_volume_fraction": round(phi_coated, 4),
                "ratio_to_random_close_packing_0p64": round(phi_coated / rcp_limit, 4),
                "physically_buildable_in_lamina": bool(phi_coated <= rcp_limit),
            })

    return {
        "conserved_patient_cao2_mg": m_cao2_mg,
        "rho_cao2_g_cm3": rho_cao2,
        "rho_pdms_g_cm3": rho_pdms,
        "planar_2x20um_barrier_film_volume_200cm2_cm3": round(200.0 * 0.0040, 4),
        "planar_2x20um_barrier_film_volume_333p33cm2_cm3": round((1000.0 / 3.0) * 0.0040, 4),
        "all_conformal_per_bead_cases_physically_unbuildable": all(
            not r["physically_buildable_in_lamina"] for r in rows
        ),
        "cases": rows,
    }


def _import_layer4() -> Any:
    if str(SCRIPT_DIR) not in sys.path:
        sys.path.insert(0, str(SCRIPT_DIR))
    import run_layer4_tissue_and_metabolic_twin as l4  # noqa: PLC0415
    return l4


def reconstruct_interface_plane_h2o2_bpr16(
    h3: np.ndarray,
    zs: np.ndarray,
    z_interface_cm: float,
) -> Dict[str, Any]:
    """
    Reconstruct H2O2 at the exact geometric barrier/tissue interface z = z_interface_cm
    by linear geometric-weight interpolation between the two bracketing cell-center planes
    (equal H2O2 diffusivity across the hydrogel barrier/tissue interface; BPR-16 / DEC-133).
    Also returns the nearest cell-center plane max with its explicit z coordinate so both
    observation sites are transparently reported. Exact for constant and linear fields on
    any aligned mesh.
    """
    zs_arr = np.asarray(zs, dtype=float)
    h_arr = np.asarray(h3, dtype=float)
    if zs_arr.ndim != 1 or h_arr.ndim != 3 or h_arr.shape[2] != zs_arr.shape[0]:
        raise ValueError("h3 must have shape (nx, ny, nz) matching 1D zs")
    if zs_arr.shape[0] < 2:
        raise ValueError("zs must contain at least 2 cell centers")

    # Nearest cell center (legacy behavior, explicitly labeled with its true z coordinate)
    nearest_idx = int(np.argmin(np.abs(zs_arr - z_interface_cm)))
    nearest_z_cm = float(zs_arr[nearest_idx])
    nearest_max = float(np.max(h_arr[:, :, nearest_idx]))

    # Bracketing cell centers for exact interface reconstruction
    hi_candidates = np.where(zs_arr >= z_interface_cm)[0]
    lo_candidates = np.where(zs_arr <= z_interface_cm)[0]
    if len(lo_candidates) == 0 or len(hi_candidates) == 0:
        raise ValueError(f"z_interface_cm={z_interface_cm} outside mesh cell-center span [{zs_arr[0]}, {zs_arr[-1]}]")
    i_lo = int(lo_candidates[-1])
    i_hi = int(hi_candidates[0])
    if i_lo == i_hi:
        w_lo, w_hi = 1.0, 0.0
        h_interface_plane = h_arr[:, :, i_lo]
    else:
        z_lo = float(zs_arr[i_lo])
        z_hi = float(zs_arr[i_hi])
        w_hi = (z_interface_cm - z_lo) / (z_hi - z_lo)
        w_lo = 1.0 - w_hi
        h_interface_plane = w_lo * h_arr[:, :, i_lo] + w_hi * h_arr[:, :, i_hi]

    # First cell center strictly inside tissue (z > z_interface_cm)
    tissue_candidates = np.where(zs_arr > z_interface_cm)[0]
    first_tissue_idx = int(tissue_candidates[0]) if len(tissue_candidates) > 0 else nearest_idx

    return {
        "interface_z_um": round(z_interface_cm * 1e4, 6),
        "interface_h2o2_max_uM": float(np.max(h_interface_plane)),
        "nearest_cell_center_z_um": round(nearest_z_cm * 1e4, 6),
        "nearest_cell_center_h2o2_max_uM": nearest_max,
        "first_tissue_cell_center_z_um": round(float(zs_arr[first_tissue_idx]) * 1e4, 6),
        "first_tissue_cell_center_h2o2_max_uM": float(np.max(h_arr[:, :, first_tissue_idx])),
        "bracketing_cell_centers_z_um": [round(float(zs_arr[i_lo]) * 1e4, 6), round(float(zs_arr[i_hi]) * 1e4, 6)],
        "interpolation_weights": [round(float(w_lo), 6), round(float(w_hi), 6)],
        "materials_both_sides": {
            "inner_side": "planar_P04040_catalase_hydrogel_barrier_abs_z_le_70um",
            "outer_side": "islet_tissue_hydrogel_band_abs_z_gt_70um",
            "equal_h2o2_diffusivity_both_sides": True,
        },
    }


def run_live_3d_fvm_conserved_inventory_coupled_sweeps() -> Dict[str, Any]:
    """Execute live 3D FVM replays conserving 791.5 mg CaO2 across t_1/2 and barrier O2-attenuation."""
    l4 = _import_layer4()
    p_krogh_acute = l4.D_O2_HYDROGEL_CM2_S * l4.ALPHA_BUNSEN_MOL_CM3_MMHG
    p_krogh_islet = l4.D_O2_ISLET_TISSUE_CM2_S * l4.ALPHA_BUNSEN_MOL_CM3_MMHG
    iu_per_cm3_per_sinv = 27000.0 / 18.0

    def _solve_case(
        *,
        t_half_h: float,
        t_eval_h: float,
        cat_ret_override: Optional[float] = None,
        o2_attenuation_factor: float = 1.0,
        vascular_midpoint_horizon_h: float = 36.0,
        slab_um: float = 390.0,
        lam_um: float = 100.0,
        buf_um: float = 20.0,
        load_ieq: float = 1500.0,
        diam_um: float = 80.0,
        lam_iu_200: float = 22680.0,
        buf_iu_200: float = 21600.0,
        nx_c: int = 36,
        dz_um: float = 5.0,
    ) -> Dict[str, Any]:
        rad_cm = 0.5 * diam_um * 1e-4
        vol_sph = (4.0 / 3.0) * math.pi * (rad_cm ** 3)
        n_face = 0.5 * ((load_ieq * l4.VOL_1_IEQ_CM3) / vol_sph)
        side_cm = math.sqrt(1.0 / n_face)
        slab_cm = slab_um * 1e-4
        lam_half_cm = 0.5 * lam_um * 1e-4
        buf_cm = buf_um * 1e-4
        band_inner_z = lam_half_cm + buf_cm
        band_outer_z = 0.5 * slab_cm
        nz_c = int(round(slab_um / dz_um))
        dx_c, dz_c = side_cm / nx_c, slab_cm / nz_c
        xs = (np.arange(nx_c) + 0.5) * dx_c - 0.5 * side_cm
        zs = (np.arange(nz_c) + 0.5) * dz_c - 0.5 * slab_cm
        X, Y, Z = np.meshgrid(xs, xs, zs, indexing="ij")
        z_mid = 0.5 * (band_inner_z + band_outer_z)
        z_c = min(band_outer_z - rad_cm - min(0.0002, 0.5 * (band_outer_z - band_inner_z - 2.0 * rad_cm)), z_mid)
        z_c = max(z_c, band_inner_z + rad_cm)
        r_top = np.sqrt(X**2 + Y**2 + (Z - z_c) ** 2)
        r_bot = np.sqrt(X**2 + Y**2 + (Z + z_c) ** 2)
        top_sph = r_top <= rad_cm
        bot_sph = r_bot <= rad_cm
        in_sph = top_sph | bot_sph
        in_lam = np.abs(Z) <= lam_half_cm
        in_buf = (np.abs(Z) > lam_half_cm) & (np.abs(Z) <= band_inner_z)

        areal_o2_0_at_68h = 0.45 * (load_ieq * l4.VOL_1_IEQ_CM3) * l4.VMAX_ISLET_PURE_MOL_CM3_S * 1.15
        m_rem = (68.0 / t_half_h) * math.exp(-math.log(2.0) * t_eval_h / t_half_h) * o2_attenuation_factor
        perf_f = (
            float(
                l4.rk4_integrate(
                    lambda t, y: np.array([(0.97 / (1.0 + math.exp(-(t - vascular_midpoint_horizon_h) / 8.0)) - y[0]) / 3.0]),
                    (0.0, t_eval_h),
                    np.array([0.01]),
                    [0.0, t_eval_h],
                    dt_max=0.25,
                )[0, -1]
            )
            if t_eval_h > 0.0
            else 0.01
        )
        k_perf_t = 0.14 * perf_f
        cat_ret_t = cat_ret_override if cat_ret_override is not None else math.exp(-math.log(2.0) * t_eval_h / 168.0)

        r_b = 0.0025  # 50 um wet-sieved bead touching top face of 100 um central lamina
        z_b = lam_half_cm - r_b
        r_bead = np.sqrt(X**2 + Y**2 + (Z - z_b) ** 2)
        in_bead_core = r_bead <= max(r_b - 0.5 * dz_c, 0.4 * r_b)
        in_bead_shell = (r_bead > max(r_b - 0.5 * dz_c, 0.4 * r_b)) & (r_bead <= r_b + 0.65 * dz_c)

        mean_h2o2_uM_s = (2.0 * areal_o2_0_at_68h * m_rem / slab_cm) * 1e9
        src_h = np.zeros_like(X)
        src_h[in_bead_shell] = mean_h2o2_uM_s / float(np.mean(in_bead_shell))
        diff_h = np.where(in_bead_core, 0.0, l4.D_H2O2_HYDROGEL_CM2_S)
        slab_vol_200 = 200.0 * slab_cm
        kcat = np.full_like(X, 0.008)
        lam_avail = in_lam & (~in_bead_core)
        kcat[lam_avail] = ((lam_iu_200 * cat_ret_t) / (slab_vol_200 * iu_per_cm3_per_sinv)) / float(np.mean(lam_avail))
        if buf_um > 0.0 and buf_iu_200 > 0.0:
            kcat[in_buf] = ((buf_iu_200 * cat_ret_t) / (slab_vol_200 * iu_per_cm3_per_sinv)) / float(np.mean(in_buf))
        kp_h = np.where(in_lam | in_buf, 0.0, k_perf_t)
        res_h = l4._solve_3d_h2o2_strict_iip_0019(diff_h, src_h, kcat, kp_h, dx_c, dx_c, dz_c)
        h3 = res_h["h_3d"]
        plane_recon = reconstruct_interface_plane_h2o2_bpr16(h3, zs, band_inner_z)

        src_o2 = 0.5 * res_h["decomp_uM_s"] * 1e-9
        perm_o2 = np.where(in_lam, p_krogh_acute * (0.42**1.5), p_krogh_acute)
        perm_o2[in_bead_core] = p_krogh_acute * 0.25
        perm_o2[in_sph] = p_krogh_islet
        in_gel = (~in_sph) & (~in_lam) & (~in_buf)
        t_phi = (load_ieq * l4.VOL_1_IEQ_CM3) / slab_cm
        vmax = np.zeros_like(X)
        vmax[in_sph] = l4.VMAX_ISLET_PURE_MOL_CM3_S * (t_phi / float(np.mean(in_sph)))
        vmax[in_gel] = (t_phi * l4.VMAX_ISLET_PURE_MOL_CM3_S * 0.15) / float(np.mean(in_gel))
        kp_o2 = np.where(in_gel, k_perf_t, 0.0)
        res_o2 = l4._solve_3d_oxygen_strict_iip_0019(
            perm_o2, vmax, src_o2, kp_o2, dx_c, dx_c, dz_c, 35.0, standoff_z_cm=0.0, p_ext=None
        )
        p3 = res_o2["p_3d"]
        fv_top = l4._compute_exact_fv_interface_stats_iip_0019(p3, perm_o2, top_sph)
        fv_bot = l4._compute_exact_fv_interface_stats_iip_0019(p3, perm_o2, bot_sph)
        worst_face_min = float(min(fv_top["fv_harmonic_face_min_mmhg"], fv_bot["fv_harmonic_face_min_mmhg"]))
        worst_face_mean = float(min(fv_top["fv_harmonic_face_mean_mmhg"], fv_bot["fv_harmonic_face_mean_mmhg"]))
        h2o2_interface_max = plane_recon["interface_h2o2_max_uM"]
        h2o2_cell_center_max = plane_recon["first_tissue_cell_center_h2o2_max_uM"]
        return {
            "t_half_h": t_half_h,
            "t_eval_h": t_eval_h,
            "vascular_midpoint_horizon_h": vascular_midpoint_horizon_h,
            "dz_um": dz_um,
            "catalase_retention_frac": round(cat_ret_t, 6),
            "o2_attenuation_factor": o2_attenuation_factor,
            "islet_plane_observation_site": "barrier_tissue_interface_z70um_linear_reconstructed",
            "islet_plane_observation_coordinate_um": plane_recon["interface_z_um"],
            "islet_plane_h2o2_max_uM": round(h2o2_interface_max, 4),
            "barrier_tissue_interface_z70um_h2o2_max_uM": round(h2o2_interface_max, 4),
            "first_tissue_cell_center_z_um": plane_recon["first_tissue_cell_center_z_um"],
            "first_tissue_cell_center_h2o2_max_uM": round(h2o2_cell_center_max, 4),
            "cluster_surface_h2o2_max_uM": round(float(np.max(h3[in_sph])), 4),
            "global_pore_h2o2_max_uM": round(float(np.max(h3)), 4),
            "worst_face_po2_min_mmhg": round(worst_face_min, 4),
            "worst_face_po2_mean_mmhg": round(worst_face_mean, 4),
            "min_core_po2_mmhg": round(float(np.min(p3[in_sph])), 4),
            "passes_h2o2_tier1_2p5uM": bool(h2o2_interface_max <= 2.5),
            "passes_h2o2_tier2_5p0uM": bool(h2o2_interface_max <= 5.0),
            "passes_first_tissue_cell_h2o2_tier1_2p5uM": bool(h2o2_cell_center_max <= 2.5),
            "passes_first_tissue_cell_h2o2_tier2_5p0uM": bool(h2o2_cell_center_max <= 5.0),
            "passes_po2_worst_face_15mmhg": bool(worst_face_min >= 15.0),
            "h2o2_rel_mass_balance_error": res_h["rel_mass_balance_error"],
            "o2_rel_mass_balance_error": res_o2["rel_mass_balance_error"],
        }

    burst_t0_100pct = [_solve_case(t_half_h=th, t_eval_h=0.0) for th in (4.0, 8.0, 12.0, 18.0, 24.0, 34.0, 68.0, 87.0)]
    burst_t0_50pct = [
        _solve_case(t_half_h=th, t_eval_h=0.0, cat_ret_override=0.50)
        for th in (12.0, 18.0, 24.0, 34.0, 68.0)
    ]
    acute_t18_100pct = [_solve_case(t_half_h=th, t_eval_h=18.0) for th in (4.0, 12.0, 24.0, 34.0, 68.0, 87.0)]
    third_coupling_o2_lag = [
        _solve_case(t_half_h=68.0, t_eval_h=18.0, o2_attenuation_factor=att)
        for att in (1.0, 0.85, 0.70, 0.50, 0.25, 0.0)
    ]

    # BPR-14: time x vascular timing (36 h vs 60 h) x delivery sensitivity matrix (fixed 791.5 mg inventory)
    bpr14_t50_36_att0p70 = [
        _solve_case(t_half_h=68.0, t_eval_h=te, o2_attenuation_factor=0.70, vascular_midpoint_horizon_h=36.0)
        for te in (0.0, 12.0, 18.0, 24.0, 36.0)
    ]
    bpr14_t50_60_att0p70 = [
        _solve_case(t_half_h=68.0, t_eval_h=te, o2_attenuation_factor=0.70, vascular_midpoint_horizon_h=60.0)
        for te in (0.0, 12.0, 18.0, 24.0, 36.0, 60.0)
    ]
    bpr14_t50_60_att1p00_control = [
        _solve_case(t_half_h=68.0, t_eval_h=te, o2_attenuation_factor=1.00, vascular_midpoint_horizon_h=60.0)
        for te in (0.0, 12.0, 18.0, 24.0, 36.0, 60.0)
    ]
    bpr14_interior_controls = {
        "t_half_64h_att_0p80_t36h_on_60h_branch": _solve_case(
            t_half_h=64.0, t_eval_h=36.0, o2_attenuation_factor=0.80, vascular_midpoint_horizon_h=60.0
        ),
        "t_half_64h_att_0p80_t36h_on_36h_branch": _solve_case(
            t_half_h=64.0, t_eval_h=36.0, o2_attenuation_factor=0.80, vascular_midpoint_horizon_h=36.0
        ),
        "t_half_58h_att_0p80_t36h_on_60h_branch_passing_control": _solve_case(
            t_half_h=58.0, t_eval_h=36.0, o2_attenuation_factor=0.80, vascular_midpoint_horizon_h=60.0
        ),
    }

    # BPR-16: barrier/tissue interface (z=70 um) vs nearest first-tissue cell center (z=72.5 um nominal)
    bpr16_comparison_rows = [
        _solve_case(t_half_h=68.0, t_eval_h=0.0, cat_ret_override=0.50, dz_um=5.0),
        _solve_case(t_half_h=34.0, t_eval_h=0.0, cat_ret_override=0.50, dz_um=5.0),
        _solve_case(t_half_h=36.0, t_eval_h=0.0, cat_ret_override=0.85, dz_um=5.0),
        _solve_case(t_half_h=24.0, t_eval_h=0.0, cat_ret_override=1.00, dz_um=5.0),
    ]

    all_rows = (
        burst_t0_100pct
        + burst_t0_50pct
        + acute_t18_100pct
        + third_coupling_o2_lag
        + bpr14_t50_36_att0p70
        + bpr14_t50_60_att0p70
        + bpr14_t50_60_att1p00_control
        + list(bpr14_interior_controls.values())
        + bpr16_comparison_rows
    )
    max_mb_err = max(max(r["h2o2_rel_mass_balance_error"], r["o2_rel_mass_balance_error"]) for r in all_rows)
    if max_mb_err > 1e-10:
        raise RuntimeError(f"3D FVM mass-balance tolerance violated: {max_mb_err:.3e}")

    k68 = math.log(2.0) / 68.0
    rel_0_24 = 1.0 - math.exp(-k68 * 24.0)
    rel_16_20 = math.exp(-k68 * 16.0) - math.exp(-k68 * 20.0)
    comp_factor = (0.80 * rel_0_24) / (rel_0_24 - rel_16_20)
    f72_const_0p80 = 0.80 * 0.45 * (1.0 - math.exp(-k68 * 72.0)) / (k68 * 72.0)
    f72_interrupted = (
        0.45 * (comp_factor * (rel_0_24 - rel_16_20) + 0.80 * (math.exp(-k68 * 24.0) - math.exp(-k68 * 72.0))) / (k68 * 72.0)
    )

    return {
        "geometry_spec": {
            "slab_thickness_um": 390.0,
            "central_lamina_um": 100.0,
            "planar_barrier_film_per_face_um": 20.0,
            "barrier_tissue_interface_z_um": 70.0,
            "nominal_first_tissue_cell_center_z_um": 72.5,
            "cluster_diam_um": 80.0,
            "areal_loading_ieq_cm2": 1500.0,
            "conserved_patient_cao2_mg": CONSERVED_CAO2_MG_TARGET,
            "full_active_catalase_t0_iu_333cm2": 73800.0,
            "worst_case_edge_bead_diam_um": 50.0,
            "nx_lateral": 36,
            "nz_vertical": 78,
        },
        "max_relative_mass_balance_error": max_mb_err,
        "hour0_burst_h2o2_100pct_catalase_sweep": burst_t0_100pct,
        "hour0_burst_h2o2_50pct_catalase_washout_sweep": burst_t0_50pct,
        "hour18_acute_bridge_coupled_sweep": acute_t18_100pct,
        "third_coupling_barrier_o2_lag_attenuation_t18h_sweep": third_coupling_o2_lag,
        "third_coupling_t18h_scope_note": (
            "Conditional on vascular_midpoint_horizon_h=36.0 at t=18.0 h; does NOT qualify the permitted 60 h delayed vascular branch "
            "(see bpr14_time_by_vascular_timing_by_delivery_matrix)."
        ),
        "bpr14_time_by_vascular_timing_by_delivery_matrix": {
            "scope_note": (
                "Quasi-steady 3D FVM worst-face pO2 (mmHg) across sampled hours at conserved 791.5 mg CaO2 inventory. "
                "Hour-18 clearance at 36 h / 0.70 (15.22 mmHg) does NOT carry over to the 60 h delayed branch (13.68 mmHg at hour 36). "
                "Acceptable sub-15 mmHg exposure duration and physical qualification require device-owner decision and measured whole-assembly traces."
            ),
            "branch_36h_delivery_0p70_t_half_68h": bpr14_t50_36_att0p70,
            "branch_60h_delivery_0p70_t_half_68h": bpr14_t50_60_att0p70,
            "branch_60h_delivery_1p00_t_half_68h_passing_control": bpr14_t50_60_att1p00_control,
            "interior_gate31_passing_controls": bpr14_interior_controls,
            "interrupted_delivery_aggregate_ambiguity": {
                "constant_delivery_factor": 0.80,
                "interruption_window_h": [16.0, 20.0],
                "day1_compensated_delivery_factor": round(comp_factor, 6),
                "constant_0_to_72h_demand_fraction": round(f72_const_0p80, 6),
                "interrupted_0_to_72h_demand_fraction": round(f72_interrupted, 6),
                "hour18_constant_0p80_po2_mmhg": _solve_case(t_half_h=68.0, t_eval_h=18.0, o2_attenuation_factor=0.80)["worst_face_po2_min_mmhg"],
                "hour18_interrupted_0p00_po2_mmhg": _solve_case(t_half_h=68.0, t_eval_h=18.0, o2_attenuation_factor=0.00)["worst_face_po2_min_mmhg"],
            },
        },
        "bpr16_interface_vs_cell_center_h2o2_audit": {
            "declared_primary_coordinate": "z = 70.0 um barrier/tissue interface (linear geometric reconstruction across equal-diffusivity bracketing cell centers)",
            "comparison_cases": bpr16_comparison_rows,
        },
    }


def _extract_ci(
    payload: Mapping[str, Any],
    mean_key: str,
    se_key: str,
    *,
    allow_zero_se: bool = False,
) -> Tuple[Optional[float], Optional[float], Optional[float], Optional[str]]:
    if mean_key not in payload or se_key not in payload:
        return None, None, None, f"MISSING_MEASUREMENT:{mean_key}/{se_key}"
    mv = payload.get(mean_key)
    sv = payload.get(se_key)
    if not _is_finite_real(mv) or not _is_finite_real(sv):
        return None, None, None, f"INVALID_NONFINITE_OR_TYPE:{mean_key}/{se_key}"
    m = float(mv)
    s = float(sv)
    if s < 0.0 or (s == 0.0 and not allow_zero_se):
        return None, None, None, f"INVALID_SE_NONPOSITIVE:{se_key}"
    lo = m - Z_95_TWO_SIDED * s
    hi = m + Z_95_TWO_SIDED * s
    return m, lo, hi, None


def evaluate_gate31c_paired_ratio_contrast_bpr17(
    payload: Mapping[str, Any],
    *,
    th_m: Optional[float],
    th_se: Optional[float],
    os_th_m: Optional[float],
    os_th_se: Optional[float],
    ratio_threshold: float = 0.50,
    confidence_mode: str = "two_sided_95",
) -> Dict[str, Any]:
    """
    Propagate uncertainty from BOTH open-sink numerator and limited-exchange denominator
    for Gate 31-C's ratio criterion (open_sink / limited_exchange >= 0.50) via the equivalent
    linear contrast d = open - 0.50 * limited >= 0 for positive denominators (BPR-17 / DEC-133).

    Supports three explicit modes:
      1. Raw paired blocks (`obs_paired_blocks`: list of {limited_h, open_sink_h}, n >= 2):
         exact Student-t two-sided & one-sided 95% lower bounds on block contrasts d_i.
      2. Summary moments with explicit pairing metadata (`obs_paired_blocks_n` >= 2 and
         `obs_open_limited_paired_corr` in [-1, 1]): exact paired Student-t lower bounds
         using SE_d = sqrt(SE_open^2 + 0.25*SE_lim^2 - 2*0.5*r*SE_open*SE_lim).
      3. Summary-only without pairing covariance: conservative worst-case Cauchy-Schwarz
         propagation (r = -1 => SE_d_worst = SE_open + 0.5*SE_lim) so an unavailable
         correlation never silently admits an inconclusive lot.
    """
    holds_out: List[str] = []
    if th_m is None or th_se is None or os_th_m is None or os_th_se is None:
        return {
            "mode": "UNAVAILABLE_MISSING_HALFLIFE_SUMMARY",
            "contrast_threshold": ratio_threshold,
            "clears_95pct_two_sided": False,
            "holds": [],
        }
    if th_m <= 0.0:
        holds_out.append(f"INVALID_NONPOSITIVE_LIMITED_HALFLIFE_MEAN:{th_m}")
        return {
            "mode": "INVALID_DENOMINATOR",
            "contrast_threshold": ratio_threshold,
            "clears_95pct_two_sided": False,
            "holds": holds_out,
        }

    legacy_shortcut_ratio = (os_th_m - Z_95_TWO_SIDED * os_th_se) / th_m

    # Mode 1: Raw paired block observations
    if "obs_paired_blocks" in payload and payload.get("obs_paired_blocks") is not None:
        raw_blocks = payload.get("obs_paired_blocks")
        if not isinstance(raw_blocks, list) or len(raw_blocks) < 2:
            holds_out.append("INVALID_OBS_PAIRED_BLOCKS_REQUIRES_LIST_LEN_GE_2")
            return {
                "mode": "PAIRED_BLOCKS_INVALID",
                "contrast_threshold": ratio_threshold,
                "clears_95pct_two_sided": False,
                "holds": holds_out,
            }
        lim_vals: List[float] = []
        op_vals: List[float] = []
        for idx, blk in enumerate(raw_blocks):
            if not isinstance(blk, Mapping):
                holds_out.append(f"INVALID_PAIRED_BLOCK_TYPE_AT_{idx}")
                return {"mode": "PAIRED_BLOCKS_INVALID", "clears_95pct_two_sided": False, "holds": holds_out}
            lv = blk.get("limited_h")
            ov = blk.get("open_sink_h")
            if not _is_finite_real(lv) or not _is_finite_real(ov) or float(lv) <= 0.0 or float(ov) <= 0.0:
                holds_out.append(f"INVALID_PAIRED_BLOCK_VALUE_AT_{idx}")
                return {"mode": "PAIRED_BLOCKS_INVALID", "clears_95pct_two_sided": False, "holds": holds_out}
            lim_vals.append(float(lv))
            op_vals.append(float(ov))
        arr_l = np.asarray(lim_vals, dtype=float)
        arr_o = np.asarray(op_vals, dtype=float)
        diffs = arr_o - ratio_threshold * arr_l
        n_blk = len(diffs)
        df = n_blk - 1
        d_mean = float(np.mean(diffs))
        d_sd = float(np.std(diffs, ddof=1))
        d_se = d_sd / math.sqrt(n_blk)
        t_two = _student_t_ppf_exact(0.975, df)
        t_one = _student_t_ppf_exact(0.95, df)
        d_l95_two = d_mean - t_two * d_se
        d_l95_one = d_mean - t_one * d_se
        corr = (
            float(np.corrcoef(arr_l, arr_o)[0, 1])
            if (np.std(arr_l, ddof=1) > 0.0 and np.std(arr_o, ddof=1) > 0.0)
            else None
        )
        clears_two = bool(d_l95_two >= 0.0)
        clears_one = bool(d_l95_one >= 0.0)
        clears = clears_one if confidence_mode == "one_sided_95" else clears_two
        if not clears:
            if confidence_mode == "one_sided_95":
                holds_out.append(
                    f"DEC134_OPEN_SINK_PAIRED_CONTRAST_ONE_SIDED_L95_BELOW_ZERO:d_mean={d_mean:.4f}h,d_se={d_se:.4f}h,l95_one={d_l95_one:.4f}h,df={df}"
                )
            else:
                holds_out.append(
                    f"OPEN_SINK_PAIRED_CONTRAST_95CI_BELOW_ZERO:d_mean={d_mean:.4f}h,d_se={d_se:.4f}h,l95_two={d_l95_two:.4f}h,df={df}"
                )
        return {
            "mode": "PAIRED_BLOCKS_STUDENT_T",
            "n_blocks": n_blk,
            "df": df,
            "paired_correlation": round(corr, 6) if corr is not None else None,
            "contrast_mean_h": round(d_mean, 6),
            "contrast_se_h": round(d_se, 6),
            "contrast_l95_two_sided_h": round(d_l95_two, 6),
            "contrast_l95_one_sided_h": round(d_l95_one, 6),
            "legacy_numerator_only_ratio_diagnostic": round(legacy_shortcut_ratio, 6),
            "clears_95pct_two_sided": clears_two,
            "clears_95pct_one_sided": clears_one,
            "holds": holds_out,
        }

    # Mode 2: Summary moments with explicit pairing metadata (n_blocks + correlation)
    has_corr = "obs_open_limited_paired_corr" in payload and payload.get("obs_open_limited_paired_corr") is not None
    has_n = "obs_paired_blocks_n" in payload and payload.get("obs_paired_blocks_n") is not None
    if has_corr or has_n:
        raw_r = payload.get("obs_open_limited_paired_corr")
        raw_n = payload.get("obs_paired_blocks_n")
        if not has_corr or not _is_finite_real(raw_r) or not (-1.0 <= float(raw_r) <= 1.0):
            holds_out.append(f"INVALID_OR_MISSING_PAIRED_CORRELATION:{raw_r!r}")
            return {"mode": "PAIRED_SUMMARY_INVALID", "clears_95pct_two_sided": False, "holds": holds_out}
        if not has_n or not isinstance(raw_n, int) or isinstance(raw_n, bool) or raw_n < 2:
            holds_out.append(f"INVALID_OR_MISSING_PAIRED_BLOCKS_N:{raw_n!r}")
            return {"mode": "PAIRED_SUMMARY_INVALID", "clears_95pct_two_sided": False, "holds": holds_out}
        r_val = float(raw_r)
        df = raw_n - 1
        d_mean = os_th_m - ratio_threshold * th_m
        d_var = max(0.0, os_th_se**2 + (ratio_threshold * th_se) ** 2 - 2.0 * ratio_threshold * r_val * os_th_se * th_se)
        d_se = math.sqrt(d_var)
        t_two = _student_t_ppf_exact(0.975, df)
        t_one = _student_t_ppf_exact(0.95, df)
        d_l95_two = d_mean - t_two * d_se
        d_l95_one = d_mean - t_one * d_se
        clears_two = bool(d_l95_two >= 0.0)
        clears_one = bool(d_l95_one >= 0.0)
        clears = clears_one if confidence_mode == "one_sided_95" else clears_two
        if not clears:
            if confidence_mode == "one_sided_95":
                holds_out.append(
                    f"DEC134_OPEN_SINK_PAIRED_CONTRAST_ONE_SIDED_L95_BELOW_ZERO:d_mean={d_mean:.4f}h,d_se={d_se:.4f}h,l95_one={d_l95_one:.4f}h,r={r_val:.3f},df={df}"
                )
            else:
                holds_out.append(
                    f"OPEN_SINK_PAIRED_CONTRAST_95CI_BELOW_ZERO:d_mean={d_mean:.4f}h,d_se={d_se:.4f}h,l95_two={d_l95_two:.4f}h,r={r_val:.3f},df={df}"
                )
        return {
            "mode": "PAIRED_SUMMARY_STUDENT_T",
            "n_blocks": raw_n,
            "df": df,
            "paired_correlation": round(r_val, 6),
            "contrast_mean_h": round(d_mean, 6),
            "contrast_se_h": round(d_se, 6),
            "contrast_l95_two_sided_h": round(d_l95_two, 6),
            "contrast_l95_one_sided_h": round(d_l95_one, 6),
            "legacy_numerator_only_ratio_diagnostic": round(legacy_shortcut_ratio, 6),
            "clears_95pct_two_sided": clears_two,
            "clears_95pct_one_sided": clears_one,
            "holds": holds_out,
        }

    # Mode 3: Summary-only without pairing covariance -> propagate denominator uncertainty conservatively (worst-case r = -1)
    d_mean = os_th_m - ratio_threshold * th_m
    d_se_worst = os_th_se + ratio_threshold * th_se
    d_se_indep = math.sqrt(os_th_se**2 + (ratio_threshold * th_se) ** 2)
    d_l95_worst = d_mean - Z_95_TWO_SIDED * d_se_worst
    d_l95_indep = d_mean - Z_95_TWO_SIDED * d_se_indep
    clears = bool(d_l95_worst >= 0.0)
    if not clears:
        holds_out.append(
            f"OPEN_SINK_RATIO_UNPAIRED_DENOMINATOR_UNCERTAINTY_INCONCLUSIVE:d_mean={d_mean:.4f}h,se_worst={d_se_worst:.4f}h,l95_worst={d_l95_worst:.4f}h"
        )
    return {
        "mode": "UNPAIRED_CONSERVATIVE_DENOMINATOR_PROPAGATION",
        "contrast_mean_h": round(d_mean, 6),
        "contrast_se_worst_case_h": round(d_se_worst, 6),
        "contrast_se_uncorrelated_h": round(d_se_indep, 6),
        "contrast_l95_worst_case_h": round(d_l95_worst, 6),
        "contrast_l95_uncorrelated_h": round(d_l95_indep, 6),
        "legacy_numerator_only_ratio_diagnostic": round(legacy_shortcut_ratio, 6),
        "clears_95pct_two_sided": clears,
        "holds": holds_out,
    }


def evaluate_gate31_coupled_cao2_lot(payload: Any) -> Dict[str, Any]:
    """
    Fail-closed executable Stage-0 Gate 31 lot evaluator.
    Returns structured dict with:
      - verdict: 'PASS_GATE_31_COUPLED_CAO2_LOT' | 'HOLD_...' | 'FAIL_HARD_STOP_...'
      - exit_code: 0 (PASS), 2 (HOLD), 3 (FAIL_HARD_STOP)
      - release_authorizing: bool (True ONLY on PASS_GATE_31_COUPLED_CAO2_LOT)
    """
    hard_stops: List[str] = []
    holds: List[str] = []
    diagnostics: Dict[str, Any] = {}

    if not isinstance(payload, dict):
        return {
            "gate_id": GATE_ID,
            "contribution_id": CONTRIBUTION_ID,
            "decision_id": DECISION_ID,
            "verdict": "HOLD_GATE31_INVALID_PAYLOAD_TYPE",
            "exit_code": 2,
            "release_authorizing": False,
            "hard_stops": [],
            "holds": ["PAYLOAD_MUST_BE_JSON_OBJECT"],
            "diagnostics": {},
        }

    # --- 1. Gate 31-Scope (Strictly CaO2-bearing Route 1 in Designs A & X; exclude Design B / Z / Y / D1) ---
    design = payload.get("design_family")
    route = payload.get("product_route_id")
    if design in EXCLUDED_NON_CAO2_DESIGNS or (isinstance(route, str) and "ZERO_CAO2" in route.upper()):
        return {
            "gate_id": GATE_ID,
            "contribution_id": CONTRIBUTION_ID,
            "decision_id": DECISION_ID,
            "verdict": "HOLD_GATE31_OUT_OF_SCOPE_NON_CAO2_ROUTE",
            "exit_code": 2,
            "release_authorizing": False,
            "hard_stops": [],
            "holds": [f"OUT_OF_SCOPE_NON_CAO2_ROUTE:design={design!r},route={route!r}"],
            "diagnostics": {"design_family": design, "product_route_id": route},
        }
    if design not in ALLOWED_CAO2_DESIGNS or route not in ALLOWED_CAO2_ROUTES:
        holds.append(f"MISSING_OR_UNRECOGNIZED_CAO2_ROUTE_SCOPE:design={design!r},route={route!r}")

    # --- 2. Same-Lot Identity Binding across Bead PSD, Planar Barrier, Kinetics, and Open-Sink ---
    lot_id = payload.get("lot_id")
    sub_lot_ids = {
        "bead_psd_lot_id": payload.get("bead_psd_lot_id"),
        "barrier_film_lot_id": payload.get("barrier_film_lot_id"),
        "kinetics_336h_lot_id": payload.get("kinetics_336h_lot_id"),
        "open_sink_lot_id": payload.get("open_sink_lot_id"),
    }
    if not isinstance(lot_id, str) or not lot_id.strip():
        holds.append("MISSING_OR_INVALID_LOT_ID")
    else:
        for k, v in sub_lot_ids.items():
            if not isinstance(v, str) or not v.strip():
                holds.append(f"MISSING_SAME_LOT_BINDING:{k}")
            elif v != lot_id:
                hard_stops.append(f"DECOUPLED_LOT_MISMATCH:{k}={v!r}!=lot_id={lot_id!r}")

    # --- 3. Gate 31-A: Bead/Crystal PSD & Planar Barrier Film Geometry ---
    barrier_mode = payload.get("barrier_geometry_mode")
    if barrier_mode in FORBIDDEN_BARRIER_MODES:
        hard_stops.append(f"FORBIDDEN_BARRIER_GEOMETRY_MODE:{barrier_mode}")
    elif barrier_mode not in ALLOWED_BARRIER_MODES:
        holds.append(f"MISSING_OR_UNRECOGNIZED_BARRIER_GEOMETRY_MODE:{barrier_mode!r}")

    slab_mode = payload.get("reconciled_slab_geometry_mode")
    if slab_mode not in ALLOWED_SLAB_MODES:
        holds.append(f"INVALID_OR_MISSING_RECONCILED_SLAB_MODE:{slab_mode!r}")

    cat_acc = payload.get("catalase_uniprot_accession")
    if cat_acc != "P04040":
        if isinstance(cat_acc, str) and cat_acc.strip():
            hard_stops.append(f"NON_HUMAN_CATALASE_DISQUALIFIED:{cat_acc}")
        else:
            holds.append("MISSING_CATALASE_UNIPROT_ACCESSION")

    d99_m, _, d99_u95, err = _extract_ci(payload, "obs_microbead_volume_d99_um", "obs_microbead_volume_d99_se")
    if err:
        holds.append(err)
    elif d99_u95 is not None and d99_u95 > 50.0:
        hard_stops.append(f"MICROBEAD_D99_EXCEEDS_50UM:u95={d99_u95:.4f}")

    d50_m, d50_l95, _, err = _extract_ci(payload, "obs_microbead_volume_d50_um", "obs_microbead_volume_d50_se")
    if err:
        holds.append(err)

    crys_m, _, crys_u95, err = _extract_ci(payload, "obs_cao2_crystal_d99_um", "obs_cao2_crystal_d99_se")
    if err:
        holds.append(err)
    elif crys_u95 is not None and d50_l95 is not None and crys_u95 >= d50_l95:
        hard_stops.append(
            f"CAO2_CRYSTAL_D99_NOT_ENCAPSULATED_IN_BEAD_D50:crystal_u95={crys_u95:.4f}>=bead_d50_l95={d50_l95:.4f}"
        )

    film_m, film_l95, _, err = _extract_ci(
        payload, "obs_planar_barrier_film_um_per_face", "obs_planar_barrier_film_se_um"
    )
    if err:
        holds.append(err)
    elif film_l95 is not None and film_l95 < 20.0:
        hard_stops.append(f"PLANAR_BARRIER_FILM_LT_20UM:l95={film_l95:.4f}")

    # --- 4. Gate 31-B: Same-Lot Conserved Inventory, t_1/2, Kinetic Law, Anti-Lag O2, H2O2 & Catalase ---
    inv_mg = payload.get("conserved_patient_cao2_inventory_mg")
    if not _is_finite_real(inv_mg):
        holds.append("MISSING_OR_INVALID_CONSERVED_CAO2_INVENTORY_MG")
    else:
        inv_f = float(inv_mg)
        if not (CONSERVED_CAO2_MG_MIN <= inv_f <= CONSERVED_CAO2_MG_MAX):
            hard_stops.append(
                f"CAO2_INVENTORY_OUTSIDE_CONSERVED_791P5MG_BAND:mg={inv_f:.2f}_not_in_[{CONSERVED_CAO2_MG_MIN},{CONSERVED_CAO2_MG_MAX}]"
            )

    t50_valid = False
    t50_horizon: Optional[float] = None
    t_half_upper_limit: Optional[float] = None
    if "vascular_midpoint_horizon_h" not in payload:
        holds.append("MISSING_VASCULAR_MIDPOINT_HORIZON_H")
    else:
        raw_t50 = payload.get("vascular_midpoint_horizon_h")
        if not _is_finite_real(raw_t50) or float(raw_t50) not in (36.0, 60.0):
            holds.append(f"INVALID_VASCULAR_MIDPOINT_HORIZON_H:{raw_t50!r}")
        else:
            t50_valid = True
            t50_horizon = float(raw_t50)
            t_half_upper_limit = 87.0 if t50_horizon == 36.0 else 68.0

    th_m, th_l95, th_u95, err = _extract_ci(payload, "obs_cao2_release_half_life_h", "obs_cao2_release_half_life_se_h")
    if err:
        holds.append(err)
    else:
        assert th_l95 is not None and th_u95 is not None
        if th_l95 < 34.0:
            hard_stops.append(f"CAO2_HALFLIFE_BURST_BELOW_34H_FLOOR:l95={th_l95:.4f}")
        if t50_valid and t_half_upper_limit is not None and t50_horizon is not None:
            if th_u95 > t_half_upper_limit:
                hard_stops.append(
                    f"CAO2_HALFLIFE_EXCEEDS_UPPER_WINDOW:u95={th_u95:.4f}>limit={t_half_upper_limit:.1f}_at_t50={t50_horizon:.0f}h"
                )
        elif th_u95 > 87.0:
            # Exceeds maximum allowed window under BOTH explicit timings (36 h and 60 h) -> hard stop keeps precedence.
            hard_stops.append(
                f"CAO2_HALFLIFE_EXCEEDS_UPPER_WINDOW_BOTH_TIMINGS:u95={th_u95:.4f}>max_limit=87.0"
            )

    kl_code = payload.get("obs_cao2_kinetic_law_code")
    if not isinstance(kl_code, int) or isinstance(kl_code, bool) or kl_code not in (0, 1, 2):
        holds.append(f"MISSING_OR_INVALID_KINETIC_LAW_CODE:{kl_code!r}")
    elif kl_code == 2 and t50_valid and t50_horizon == 60.0:
        hard_stops.append("GINSTLING_BROUNSHTEIN_DIFFUSION_LAW_NO_PASSING_WINDOW_AT_T50_60H")
    elif kl_code == 2 and not t50_valid:
        holds.append("GINSTLING_BROUNSHTEIN_REQUIRES_EXPLICIT_VASCULAR_HORIZON_AND_60H_RESCUE")
    elif kl_code == 2:
        holds.append("GINSTLING_BROUNSHTEIN_REQUIRES_S9_ESCALATION_AND_60H_RESCUE")

    # Third coupling: anti-lag Hour 0-24 O2 delivery & 0-72 h cumulative O2 yield
    o2_24_m, o2_24_l95, _, err = _extract_ci(
        payload, "obs_hour0_to_24h_o2_delivery_ratio", "obs_hour0_to_24h_o2_delivery_ratio_se"
    )
    if err:
        holds.append(err)
    elif o2_24_l95 is not None and o2_24_l95 < 0.70:
        hard_stops.append(f"BARRIER_INDUCED_EARLY_O2_LAG_BELOW_0P70_FLOOR:l95={o2_24_l95:.4f}")

    o2_72_m, o2_72_l95, _, err = _extract_ci(
        payload, "obs_cumulative_0_to_72h_o2_demand_fraction", "obs_cumulative_0_to_72h_o2_demand_fraction_se"
    )
    if err:
        holds.append(err)
    elif o2_72_l95 is not None and o2_72_l95 < 0.25:
        hard_stops.append(f"CUMULATIVE_72H_O2_DELIVERY_BELOW_0P25_FLOOR:l95={o2_72_l95:.4f}")

    h2o2_m, _, h2o2_u95, err = _extract_ci(payload, "obs_islet_plane_h2o2_max_uM", "obs_islet_plane_h2o2_max_se_uM")
    if err:
        holds.append(err)
    elif h2o2_u95 is not None:
        if h2o2_u95 > 5.0:
            hard_stops.append(f"ISLET_PLANE_H2O2_BREACHES_5P0UM_TIER2_HARD_STOP:u95={h2o2_u95:.4f}")
        elif h2o2_u95 > 2.5:
            holds.append(f"ISLET_PLANE_H2O2_EXCEEDS_2P5UM_TIER1_TARGET:u95={h2o2_u95:.4f}")

    d7_m, d7_l95, _, err = _extract_ci(payload, "obs_day7_catalase_retention_pct", "obs_day7_catalase_retention_se_pct")
    if err:
        holds.append(err)
    elif d7_l95 is not None and d7_l95 < 70.0:
        hard_stops.append(f"DAY7_CATALASE_RETENTION_BELOW_70PCT:l95={d7_l95:.4f}")

    d14_m, d14_l95, _, err = _extract_ci(
        payload, "obs_day14_retained_catalase_iu_333cm2", "obs_day14_retained_catalase_se_iu"
    )
    if err:
        holds.append(err)
    elif d14_l95 is not None and d14_l95 < 73800.0:
        hard_stops.append(f"DAY14_RETAINED_CATALASE_BELOW_73800IU:l95={d14_l95:.2f}")

    precure_iu = payload.get("pre_cure_catalase_load_iu_333cm2")
    if not _is_finite_real(precure_iu):
        holds.append("MISSING_OR_INVALID_PRE_CURE_CATALASE_LOAD_IU")
    elif float(precure_iu) > 158300.0:
        hard_stops.append(f"PRE_CURE_CATALASE_EXCEEDS_158300IU_CAP:val={float(precure_iu):.1f}")

    # --- 5. Gate 31-C: Sealed-Chamber vs Dynamic Open-Sink Physiological Transfer ---
    assay_regime = payload.get("kinetics_assay_regime")
    if assay_regime == "SEALED_CHAMBER_ONLY":
        holds.append("HOLD_SEALED_CHAMBER_ONLY_OPEN_SINK_REQUIRED")
    elif assay_regime != "PAIRED_LIMITED_EXCHANGE_AND_OPEN_SINK":
        holds.append(f"MISSING_OR_INVALID_KINETICS_ASSAY_REGIME:{assay_regime!r}")

    os_th_m, os_th_l95, os_th_u95, err = _extract_ci(
        payload, "obs_open_sink_cao2_half_life_h", "obs_open_sink_cao2_half_life_se_h"
    )
    th_se_val = float(payload["obs_cao2_release_half_life_se_h"]) if (th_m is not None and _is_finite_real(payload.get("obs_cao2_release_half_life_se_h"))) else None
    os_th_se_val = float(payload["obs_open_sink_cao2_half_life_se_h"]) if (os_th_m is not None and _is_finite_real(payload.get("obs_open_sink_cao2_half_life_se_h"))) else None
    paired_contrast_eval: Dict[str, Any] = {}
    if err:
        holds.append(err)
    else:
        assert os_th_l95 is not None and os_th_u95 is not None
        if os_th_l95 < 34.0:
            hard_stops.append(f"OPEN_SINK_HALFLIFE_BURST_BELOW_34H_FLOOR:l95={os_th_l95:.4f}")
        if t50_valid and t_half_upper_limit is not None:
            if os_th_u95 > t_half_upper_limit:
                hard_stops.append(f"OPEN_SINK_HALFLIFE_EXCEEDS_UPPER_WINDOW:u95={os_th_u95:.4f}")
        elif os_th_u95 > 87.0:
            hard_stops.append(f"OPEN_SINK_HALFLIFE_EXCEEDS_UPPER_WINDOW_BOTH_TIMINGS:u95={os_th_u95:.4f}>87.0")
        paired_contrast_eval = evaluate_gate31c_paired_ratio_contrast_bpr17(
            payload,
            th_m=th_m,
            th_se=th_se_val,
            os_th_m=os_th_m,
            os_th_se=os_th_se_val,
            ratio_threshold=0.50,
        )
        holds.extend(paired_contrast_eval.get("holds", []))

    os_h2_m, _, os_h2_u95, err = _extract_ci(
        payload, "obs_open_sink_islet_plane_h2o2_max_uM", "obs_open_sink_islet_plane_h2o2_max_se_uM"
    )
    if err:
        holds.append(err)
    elif os_h2_u95 is not None:
        if os_h2_u95 > 5.0:
            hard_stops.append(f"OPEN_SINK_H2O2_BREACHES_5P0UM_TIER2_HARD_STOP:u95={os_h2_u95:.4f}")
        elif os_h2_u95 > 2.5:
            holds.append(f"OPEN_SINK_H2O2_EXCEEDS_2P5UM_TIER1_TARGET:u95={os_h2_u95:.4f}")

    diagnostics.update({
        "design_family": design,
        "product_route_id": route,
        "lot_id": lot_id,
        "vascular_midpoint_horizon_h": t50_horizon if t50_valid else None,
        "vascular_midpoint_horizon_valid": t50_valid,
        "t_half_passing_window_h": [34.0, t_half_upper_limit] if (t50_valid and t_half_upper_limit is not None) else None,
        "obs_microbead_d99_u95_um": round(d99_u95, 4) if d99_u95 is not None else None,
        "obs_t_half_95ci_h": [round(th_l95, 4), round(th_u95, 4)] if (th_l95 is not None and th_u95 is not None) else None,
        "obs_open_sink_t_half_95ci_h": (
            [round(os_th_l95, 4), round(os_th_u95, 4)] if (os_th_l95 is not None and os_th_u95 is not None) else None
        ),
        "obs_hour0_to_24h_o2_l95": round(o2_24_l95, 4) if o2_24_l95 is not None else None,
        "obs_cumulative_72h_o2_l95": round(o2_72_l95, 4) if o2_72_l95 is not None else None,
        "obs_islet_plane_h2o2_u95_uM": round(h2o2_u95, 4) if h2o2_u95 is not None else None,
        "obs_open_sink_h2o2_u95_uM": round(os_h2_u95, 4) if os_h2_u95 is not None else None,
        "gate31c_paired_ratio_contrast_bpr17": paired_contrast_eval,
    })

    # Fail-first precedence: hard stops always override holds
    if hard_stops:
        return {
            "gate_id": GATE_ID,
            "contribution_id": CONTRIBUTION_ID,
            "decision_id": DECISION_ID,
            "verdict": "FAIL_HARD_STOP_GATE_31_COUPLED_CAO2_LOT",
            "exit_code": 3,
            "release_authorizing": False,
            "hard_stops": hard_stops,
            "holds": holds,
            "diagnostics": diagnostics,
        }
    if holds:
        return {
            "gate_id": GATE_ID,
            "contribution_id": CONTRIBUTION_ID,
            "decision_id": DECISION_ID,
            "verdict": "HOLD_GATE_31_INCOMPLETE_OR_TIER1_MARGIN",
            "exit_code": 2,
            "release_authorizing": False,
            "hard_stops": [],
            "holds": holds,
            "diagnostics": diagnostics,
        }
    return {
        "gate_id": GATE_ID,
        "contribution_id": CONTRIBUTION_ID,
        "decision_id": DECISION_ID,
        "verdict": "PASS_GATE_31_COUPLED_CAO2_LOT",
        "exit_code": 0,
        "release_authorizing": True,
        "hard_stops": [],
        "holds": [],
        "diagnostics": diagnostics,
    }


def _reference_passing_lot_fixture() -> Dict[str, Any]:
    return {
        "design_family": "X",
        "product_route_id": "ROUTE_1_CAO2_390UM_EXPANDED_PLANAR_BARRIER",
        "lot_id": "LOT-GATE31-REF-001",
        "bead_psd_lot_id": "LOT-GATE31-REF-001",
        "barrier_film_lot_id": "LOT-GATE31-REF-001",
        "kinetics_336h_lot_id": "LOT-GATE31-REF-001",
        "open_sink_lot_id": "LOT-GATE31-REF-001",
        "barrier_geometry_mode": "PLANAR_CO_CAST_LAMINA_FACE_HYDROGEL_FILM",
        "reconciled_slab_geometry_mode": "EXPANDED_390UM_2X125UM_BANDS",
        "catalase_uniprot_accession": "P04040",
        "obs_microbead_volume_d99_um": 46.2,
        "obs_microbead_volume_d99_se": 1.1,
        "obs_microbead_volume_d50_um": 31.5,
        "obs_microbead_volume_d50_se": 0.8,
        "obs_cao2_crystal_d99_um": 14.0,
        "obs_cao2_crystal_d99_se": 0.6,
        "obs_planar_barrier_film_um_per_face": 22.4,
        "obs_planar_barrier_film_se_um": 0.5,
        "conserved_patient_cao2_inventory_mg": 791.5,
        "vascular_midpoint_horizon_h": 36.0,
        "obs_cao2_release_half_life_h": 58.0,
        "obs_cao2_release_half_life_se_h": 2.5,
        "obs_cao2_kinetic_law_code": 0,
        "obs_hour0_to_24h_o2_delivery_ratio": 0.94,
        "obs_hour0_to_24h_o2_delivery_ratio_se": 0.03,
        "obs_cumulative_0_to_72h_o2_demand_fraction": 0.31,
        "obs_cumulative_0_to_72h_o2_demand_fraction_se": 0.015,
        "obs_islet_plane_h2o2_max_uM": 1.25,
        "obs_islet_plane_h2o2_max_se_uM": 0.15,
        "obs_day7_catalase_retention_pct": 82.0,
        "obs_day7_catalase_retention_se_pct": 2.0,
        "obs_day14_retained_catalase_iu_333cm2": 79500.0,
        "obs_day14_retained_catalase_se_iu": 1500.0,
        "pre_cure_catalase_load_iu_333cm2": 148000.0,
        "kinetics_assay_regime": "PAIRED_LIMITED_EXCHANGE_AND_OPEN_SINK",
        "obs_open_sink_cao2_half_life_h": 46.5,
        "obs_open_sink_cao2_half_life_se_h": 2.2,
        "obs_open_sink_islet_plane_h2o2_max_uM": 1.65,
        "obs_open_sink_islet_plane_h2o2_max_se_uM": 0.18,
    }


def _reference_dec134_stage0_release_lot_fixture() -> Dict[str, Any]:
    """Reference Stage-0 release fixture complying with all DEC-134 locked bench specs (BPR-14..18)."""
    base = _reference_passing_lot_fixture()
    base.update({
        "vascular_midpoint_horizon_h": 60.0,
        "obs_cao2_release_half_life_h": 56.0,
        "obs_cao2_release_half_life_se_h": 2.0,
        "obs_po2_below_15mmhg_cumulative_h": 0.0,
        "obs_po2_min_mmhg": 16.15,
        "obs_h2o2_measurement_site": "BARRIER_TISSUE_INTERFACE_Z_70P0_UM",
        "obs_h2o2_z_um": 70.0,
        "obs_open_sink_h2o2_measurement_site": "BARRIER_TISSUE_INTERFACE_Z_70P0_UM",
        "obs_open_sink_h2o2_z_um": 70.0,
        "obs_open_sink_cao2_half_life_h": 46.5,
        "obs_open_sink_cao2_half_life_se_h": 1.8,
        "obs_paired_blocks": [
            {"limited_h": 54.0, "open_sink_h": 44.5},
            {"limited_h": 55.2, "open_sink_h": 45.8},
            {"limited_h": 56.0, "open_sink_h": 46.4},
            {"limited_h": 56.5, "open_sink_h": 47.0},
            {"limited_h": 57.1, "open_sink_h": 47.4},
            {"limited_h": 57.2, "open_sink_h": 47.9},
        ],
    })
    return base


def evaluate_gate31_stage0_release_dec134(payload: Any) -> Dict[str, Any]:
    """
    DEC-134 locked Stage-0 bench release evaluator for Gate 31 (BPR-14, BPR-16, BPR-17, BPR-18).

    Enforces all baseline Gate 31 coupled checks plus maintainer-locked DEC-134 bench rules:
      - BPR-14: Requires conservative 60.0 h vascular-midpoint branch for release authorization
        (36.0 h is logged strictly as an optimistic sensitivity reference -> HOLD); caps cumulative
        sub-15.0 mmHg excursion at <= 4.0 h and enforces a hard hypoxia floor >= 10.0 mmHg.
      - BPR-16: Designates the barrier/tissue interface plane (z = 70.0 um,
        BARRIER_TISSUE_INTERFACE_Z_70P0_UM) as the authoritative peroxide release coordinate.
      - BPR-17: Requires n >= 6 paired open-vs-limited blocks (raw blocks or paired summary with
        explicit correlation) clearing the one-sided 95% Student-t lower confidence bound >= 0.0 h
        on open - 0.50 * limited (unpaired Cauchy-Schwarz remains fail-safe only, non-releasing).
      - BPR-18: Records zero legacy physical wet-lab lots admitted under the removed 36 h default.
    """
    if not isinstance(payload, dict):
        res = evaluate_gate31_coupled_cao2_lot(payload)
        res["policy_decision_id"] = "DEC-134"
        return res

    base = evaluate_gate31_coupled_cao2_lot(payload)
    if base["verdict"] == "HOLD_GATE31_OUT_OF_SCOPE_NON_CAO2_ROUTE":
        base["policy_decision_id"] = "DEC-134"
        return base

    hard_stops = list(base["hard_stops"])
    # Drop the two-sided Gate 31-C hold from base and re-evaluate under locked DEC-134 one-sided 95% n>=6 rule
    holds = [h for h in base["holds"] if not h.startswith("OPEN_SINK_PAIRED_CONTRAST_95CI_BELOW_ZERO:") and not h.startswith("OPEN_SINK_RATIO_UNPAIRED_DENOMINATOR_UNCERTAINTY_INCONCLUSIVE:")]
    diag = dict(base["diagnostics"])

    # BPR-14: Locked 60 h primary release branch + sub-15 mmHg duration & 10 mmHg floor
    raw_t50 = payload.get("vascular_midpoint_horizon_h")
    if _is_finite_real(raw_t50) and float(raw_t50) == 36.0:
        holds.append("DEC134_36H_IS_SENSITIVITY_ONLY_60H_PRIMARY_REQUIRED")

    sub15_h = payload.get("obs_po2_below_15mmhg_cumulative_h")
    if not _is_finite_real(sub15_h) or float(sub15_h) < 0.0:
        holds.append(f"DEC134_MISSING_OR_INVALID_PO2_BELOW_15MMHG_CUMULATIVE_H:{sub15_h!r}")
    elif float(sub15_h) > 4.0:
        hard_stops.append(f"DEC134_PO2_BELOW_15MMHG_EXCURSION_EXCEEDS_4H_CAP:hours={float(sub15_h):.3f}")

    po2_min = payload.get("obs_po2_min_mmhg")
    if not _is_finite_real(po2_min) or float(po2_min) < 0.0:
        holds.append(f"DEC134_MISSING_OR_INVALID_PO2_MIN_MMHG:{po2_min!r}")
    elif float(po2_min) < 10.0:
        hard_stops.append(f"DEC134_PO2_MIN_BREACHES_10MMHG_HARD_FLOOR:po2_min={float(po2_min):.3f}")

    # BPR-16: Authoritative peroxide coordinate at z = 70.0 um barrier/tissue interface plane
    for site_key, z_key, lbl in (
        ("obs_h2o2_measurement_site", "obs_h2o2_z_um", "LIMITED_EXCHANGE"),
        ("obs_open_sink_h2o2_measurement_site", "obs_open_sink_h2o2_z_um", "OPEN_SINK"),
    ):
        site_val = payload.get(site_key)
        z_val = payload.get(z_key)
        if site_val != "BARRIER_TISSUE_INTERFACE_Z_70P0_UM" or not _is_finite_real(z_val) or not math.isclose(float(z_val), 70.0, abs_tol=1e-6):
            holds.append(f"DEC134_H2O2_NOT_AT_Z70P0_INTERFACE:{lbl}:site={site_val!r},z_um={z_val!r}")

    # BPR-17: Paired open-vs-limited blocks n >= 6 with one-sided 95% Student-t LCB >= 0.0 h
    th_m = float(payload["obs_cao2_release_half_life_h"]) if _is_finite_real(payload.get("obs_cao2_release_half_life_h")) else None
    th_se = float(payload["obs_cao2_release_half_life_se_h"]) if _is_finite_real(payload.get("obs_cao2_release_half_life_se_h")) else None
    os_m = float(payload["obs_open_sink_cao2_half_life_h"]) if _is_finite_real(payload.get("obs_open_sink_cao2_half_life_h")) else None
    os_se = float(payload["obs_open_sink_cao2_half_life_se_h"]) if _is_finite_real(payload.get("obs_open_sink_cao2_half_life_se_h")) else None
    dec134_g31c = evaluate_gate31c_paired_ratio_contrast_bpr17(
        payload,
        th_m=th_m,
        th_se=th_se,
        os_th_m=os_m,
        os_th_se=os_se,
        ratio_threshold=0.50,
        confidence_mode="one_sided_95",
    )
    if dec134_g31c.get("mode") not in ("PAIRED_BLOCKS_STUDENT_T", "PAIRED_SUMMARY_STUDENT_T"):
        holds.append(f"DEC134_GATE31C_REQUIRES_PAIRED_BLOCKS_N_GE_6:mode={dec134_g31c.get('mode')}")
    else:
        n_blk = int(dec134_g31c.get("n_blocks", 0))
        if n_blk < 6:
            holds.append(f"DEC134_GATE31C_REQUIRES_PAIRED_BLOCKS_N_GE_6:n_blocks={n_blk}")
        holds.extend(dec134_g31c.get("holds", []))

    diag["dec134_stage0_bench_policy"] = {
        "policy_decision_id": "DEC-134",
        "authoritative_vascular_midpoint_h": 60.0,
        "sub_15mmhg_excursion_cap_h": 4.0,
        "hard_hypoxia_floor_mmhg": 10.0,
        "obs_po2_below_15mmhg_cumulative_h": float(sub15_h) if _is_finite_real(sub15_h) else None,
        "obs_po2_min_mmhg": float(po2_min) if _is_finite_real(po2_min) else None,
        "authoritative_h2o2_coordinate": "BARRIER_TISSUE_INTERFACE_Z_70P0_UM",
        "gate31c_one_sided_95_paired_contrast": dec134_g31c,
        "dec134_legacy_36h_default_physical_lots_count": 0,
    }

    if hard_stops:
        return {
            "gate_id": GATE_ID,
            "contribution_id": CONTRIBUTION_ID,
            "decision_id": DECISION_ID,
            "policy_decision_id": "DEC-134",
            "verdict": "FAIL_HARD_STOP_GATE_31_COUPLED_CAO2_LOT",
            "exit_code": 3,
            "release_authorizing": False,
            "hard_stops": hard_stops,
            "holds": holds,
            "diagnostics": diag,
        }
    if holds:
        return {
            "gate_id": GATE_ID,
            "contribution_id": CONTRIBUTION_ID,
            "decision_id": DECISION_ID,
            "policy_decision_id": "DEC-134",
            "verdict": "HOLD_GATE_31_INCOMPLETE_OR_TIER1_MARGIN",
            "exit_code": 2,
            "release_authorizing": False,
            "hard_stops": [],
            "holds": holds,
            "diagnostics": diag,
        }
    return {
        "gate_id": GATE_ID,
        "contribution_id": CONTRIBUTION_ID,
        "decision_id": DECISION_ID,
        "policy_decision_id": "DEC-134",
        "verdict": "PASS_GATE_31_COUPLED_CAO2_LOT",
        "exit_code": 0,
        "release_authorizing": True,
        "hard_stops": [],
        "holds": [],
        "diagnostics": diag,
    }


def run_zero_lims_touch_invariance_checks(repo_root: Path) -> Dict[str, Any]:
    if "wetlab_contract" in sys.modules:
        raise RuntimeError("Zero-LIMS-Touch violation: wetlab_contract imported")
    lims_verified: Dict[str, Dict[str, Any]] = {}
    for rel, expected in FROZEN_LIMS_SHA256.items():
        actual = sha256_file(repo_root / rel)
        if actual != expected:
            raise RuntimeError(f"Frozen LIMS SHA-256 mismatch on {rel}: {actual} != {expected}")
        lims_verified[rel] = {"sha256": actual, "matches_pin": True}

    pareto_sha = sha256_file(repo_root / "data/extracted/islet1_combinatorial_pareto_and_ladder_v0.8.0.json")
    if pareto_sha != EXPECTED_PARETO_SHA256:
        raise RuntimeError(f"Frozen Pareto SHA-256 mismatch: {pareto_sha} != {EXPECTED_PARETO_SHA256}")

    pb_sec4120_sha = _extract_playbook_sec4120_sha256(repo_root)
    if pb_sec4120_sha != EXPECTED_PLAYBOOK_SEC4120_SHA256:
        raise RuntimeError(f"Playbook §4.1.20 SHA-256 mismatch: {pb_sec4120_sha} != {EXPECTED_PLAYBOOK_SEC4120_SHA256}")

    return {
        "wetlab_contract_not_imported": True,
        "frozen_lims_files": lims_verified,
        "frozen_pareto_sha256": pareto_sha,
        "playbook_sec4120_sha256": pb_sec4120_sha,
        "all_invariants_passed": True,
    }


def build_verification_artifact(repo_root: Path) -> Dict[str, Any]:
    lims_audit = run_zero_lims_touch_invariance_checks(repo_root)
    shell_ledger = compute_per_bead_shell_unbuildability_ledger()
    fvm_sweeps = run_live_3d_fvm_conserved_inventory_coupled_sweeps()

    ref_pass = evaluate_gate31_coupled_cao2_lot(_reference_passing_lot_fixture())
    if ref_pass["exit_code"] != 0:
        raise RuntimeError(f"Reference Gate 31 fixture unexpectedly failed: {ref_pass}")

    # Deterministic negative controls verifying fail-closed coupling
    neg_cases: Dict[str, Dict[str, Any]] = {}
    base = _reference_passing_lot_fixture()

    neg_specs = {
        "decoupled_lot_id_fail": {**base, "kinetics_336h_lot_id": "LOT-OTHER-999"},
        "per_bead_conformal_shell_fail": {**base, "barrier_geometry_mode": "PER_BEAD_CONFORMAL_SHELL"},
        "short_burst_t12_20h_fail": {**base, "obs_cao2_release_half_life_h": 20.0, "obs_cao2_release_half_life_se_h": 1.0},
        "third_coupling_o2_lag_0p50_fail": {**base, "obs_hour0_to_24h_o2_delivery_ratio": 0.50, "obs_hour0_to_24h_o2_delivery_ratio_se": 0.02},
        "sealed_chamber_only_hold": {**base, "kinetics_assay_regime": "SEALED_CHAMBER_ONLY"},
        "design_b_non_cao2_out_of_scope_hold": {**base, "design_family": "B"},
        "ginstling_brounshtein_at_60h_fail": {**base, "vascular_midpoint_horizon_h": 60.0, "obs_cao2_kinetic_law_code": 2},
    }
    for name, fx in neg_specs.items():
        res = evaluate_gate31_coupled_cao2_lot(fx)
        if res["release_authorizing"] is not False or res["exit_code"] == 0:
            raise RuntimeError(f"Negative control {name} unexpectedly authorized release!")
        neg_cases[name] = {
            "verdict": res["verdict"],
            "exit_code": res["exit_code"],
            "release_authorizing": res["release_authorizing"],
            "hard_stops": res["hard_stops"],
            "holds": res["holds"],
        }

    dec134_ref_pass = evaluate_gate31_stage0_release_dec134(_reference_dec134_stage0_release_lot_fixture())
    if dec134_ref_pass["exit_code"] != 0 or not dec134_ref_pass["release_authorizing"]:
        raise RuntimeError(f"DEC-134 reference Stage-0 release fixture failed: {dec134_ref_pass}")
    dec134_base = _reference_dec134_stage0_release_lot_fixture()
    dec134_neg_specs = {
        "sensitivity_36h_hold": {**dec134_base, "vascular_midpoint_horizon_h": 36.0},
        "excursion_over_4h_fail": {**dec134_base, "obs_po2_below_15mmhg_cumulative_h": 4.5},
        "hypoxia_below_10mmhg_fail": {**dec134_base, "obs_po2_min_mmhg": 9.5},
        "h2o2_cell_center_72p5um_hold": {
            **dec134_base,
            "obs_h2o2_measurement_site": "FIRST_TISSUE_CELL_CENTER_Z_72P5_UM",
            "obs_h2o2_z_um": 72.5,
        },
        "paired_blocks_n4_lt_6_hold": {
            **dec134_base,
            "obs_paired_blocks": dec134_base["obs_paired_blocks"][:4],
        },
        "unpaired_summary_only_hold": {
            k: v for k, v in dec134_base.items() if k != "obs_paired_blocks"
        },
    }
    dec134_neg_cases: Dict[str, Dict[str, Any]] = {}
    for name, fx in dec134_neg_specs.items():
        r_d = evaluate_gate31_stage0_release_dec134(fx)
        if r_d["release_authorizing"] is not False or r_d["exit_code"] == 0:
            raise RuntimeError(f"DEC-134 negative control {name} unexpectedly authorized release!")
        dec134_neg_cases[name] = {
            "verdict": r_d["verdict"],
            "exit_code": r_d["exit_code"],
            "release_authorizing": r_d["release_authorizing"],
            "hard_stops": r_d["hard_stops"],
            "holds": r_d["holds"],
        }

    side_contract_sha = sha256_file(repo_root / SIDE_CONTRACT_REL)
    return {
        "schema_version": "iip0045_cao2_coupled_gate31_verification_v0.8.0",
        "contribution_id": CONTRIBUTION_ID,
        "decision_id": DECISION_ID,
        "gate_id": GATE_ID,
        "graveyard_card_id": GRAVEYARD_CARD_ID,
        "generated_date": GENERATED_DATE,
        "live_odds_delta_pp": 0.0,
        "side_contract_path": SIDE_CONTRACT_REL,
        "side_contract_sha256": side_contract_sha,
        "zero_lims_touch_invariance": lims_audit,
        "per_bead_20um_conformal_shell_unbuildability_ledger": shell_ledger,
        "live_3d_fvm_conserved_791p5mg_coupled_sweeps": fvm_sweeps,
        "gate31_reference_lot_evaluation": ref_pass,
        "gate31_negative_control_matrix": neg_cases,
        "dec134_stage0_release_policy_verification": {
            "policy_decision_id": "DEC-134",
            "legacy_36h_default_physical_lots_count": 0,
            "reference_release_lot_evaluation": dec134_ref_pass,
            "negative_control_matrix": dec134_neg_cases,
        },
    }


def main(argv: Optional[List[str]] = None) -> int:
    parser = argparse.ArgumentParser(description="IIP-0045 / DEC-125 / Gate 31 Coupled CaO2 Verifier")
    parser.add_argument("--repo-root", type=Path, default=REPO_ROOT)
    parser.add_argument("--write-verification", action="store_true")
    parser.add_argument("--check", action="store_true")
    parser.add_argument("--evaluate-lot", type=Path, default=None)
    parser.add_argument("--evaluate-stage0-release", type=Path, default=None)
    args = parser.parse_args(argv)

    eval_path = args.evaluate_stage0_release or args.evaluate_lot
    if eval_path is not None:
        try:
            raw = eval_path.read_text(encoding="utf-8")
            parsed = strict_json_loads(raw)
        except Exception as exc:
            err_out = {
                "gate_id": GATE_ID,
                "contribution_id": CONTRIBUTION_ID,
                "decision_id": DECISION_ID,
                "verdict": "HOLD_GATE31_STRICT_JSON_PARSE_ERROR",
                "exit_code": 2,
                "release_authorizing": False,
                "hard_stops": [],
                "holds": [str(exc)],
                "diagnostics": {},
            }
            print(json.dumps(err_out, indent=2, allow_nan=False))
            return 2
        res = (
            evaluate_gate31_stage0_release_dec134(parsed)
            if args.evaluate_stage0_release is not None
            else evaluate_gate31_coupled_cao2_lot(parsed)
        )
        print(json.dumps(res, indent=2, allow_nan=False))
        return int(res["exit_code"])

    payload = build_verification_artifact(args.repo_root)
    serialized = json.dumps(payload, indent=2, allow_nan=False) + "\n"
    out_path = args.repo_root / VERIFICATION_REL

    if args.write_verification:
        out_path.write_text(serialized, encoding="utf-8")
        print(f"Wrote {out_path} ({len(serialized)} bytes, sha256={hashlib.sha256(serialized.encode('utf-8')).hexdigest()})")
        return 0

    if args.check:
        if not out_path.is_file():
            print(f"MISSING verification artifact: {out_path}", file=sys.stderr)
            return 1
        existing = out_path.read_text(encoding="utf-8")
        if existing != serialized:
            print(f"DRIFT detected in {out_path}", file=sys.stderr)
            return 1
        print(f"OK: {out_path} byte-identical (sha256={hashlib.sha256(existing.encode('utf-8')).hexdigest()})")
        return 0

    print(serialized)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
