#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""
Wave-7 CellGemma-Islet (IIP-0062 to IIP-0065 / GATE-40 to GATE-43) Pure-CPU
Rebase Verifier, Exact 2^24 Portfolio Crosswalk & Executable Stage-0 Gate Suite.

(Note: IIP-0059 / DEC-140 / GATE-38 [Issue #59], IIP-0060 / DEC-141 / GATE-39 [Issue #60], and IIP-0061 / DEC-142 [Issue #61, Layer-1 normative prose sync] occupy #59-#61 and GATE-38..GATE-39; Wave-7 occupies IIP-0062..IIP-0065 / DEC-143..DEC-146 / GATE-40..GATE-43.)

Rebases the frozen CellGemma-Islet v0.9.0 provenance package
(`cellgemma_islet_v0_1_receipt.json`, `portable_payload_sha256:
ba72c6eb81f29be7ab1f0b2ef17ca6397eb342f1a2788913475919f48f89e2ab`) onto the
landed Wave-6 (`IIP-0055`..`IIP-0058`) 6-arm `2^24` portfolio engine
(`wave6_master_contract.json`, `71.7864%` modular / `70.5959%` locked /
`74.9586%` ceiling) with:
  - Canonical Wave-6 `v0.9.0` product & native safety-switch binding
    (`wave6_canonical_arm_manifest.json`: `ISLET1_DESIGN_B_V090`,
    `ISLET1_DESIGN_Y_V3`, `ISLET1_DESIGN_X_V090`, `ISLET1_DESIGN_D1B_LEAN_K2`,
    `ISLET1_ARM_Z_ENSC_V090`), strictly prohibiting transfer of legacy `v0.8.0`
    passes onto Wave-6 `v0.9.0` arms and enforcing active gate product/route scope.
  - Zero double-counting via proportional remaining-failure-headroom compression
    on Wave-6's `c4_univ = 0.950` (`scale = 0.625`) and `c3_base = 0.942`
    (`scale = 0.773333`, lifted central `0.948573`), keeping `Route 4` naked
    omental fold-back untouched (`c4_r4 = 0.870`) in primary scope.
  - Strict physical AND numerical Design-A drug-free firewall:
    * All Design-A aliases (`A`, `DESIGN_A`, `ISLET1_A4_ARM1B`,
      `ISLET1_DESIGN_A_V080_REF`, `ISLET1_DESIGN_A_V090_TBP_CANDIDATE`) hard-blocked
      on both `target_arm` and `product_id`.
    * `INC_A_DRUGFREE` cell class restricts Design A exclusively to uncoated
      `R1` whenever `R2` is drug-coated (`p_design_a_only_with_coated_route == 0.0`).
    * Design-A 4 marginals `(0.88, 0.78, 0.57, 0.69)`, standalone (`26.9961%`),
      and `(A, D)` H2 4-cell joint verified invariant to `<= 1e-12`.
  - Exact `192`-state (`24 Wave-6 states x 8 Wave-7 (A, B, C) states`) state-by-state
    pre-wet-lab scenario average plus Foundry-conditional sensitivities.
  - Hardened fail-closed Stage-0 gate adjudicators (`GATE-40`..`GATE-43`) with
    structured scope-bound same-lot evidence receipts, strict schema unknown-key
    rejection, bench-only vs exact-product phase separation, manifest-derived
    construct density applicability, explicit `release_authorizing = False`,
    and 280 deterministic regression tests (zero `assert` statements; 100%
    fail-closed under `python3 -W error -O -B`).

Usage:
  PYTHONDONTWRITEBYTECODE=1 python3 -W error -O -B verify_wave7_cellgemma_2p24_rebase.py --generate
  PYTHONDONTWRITEBYTECODE=1 python3 -W error -O -B verify_wave7_cellgemma_2p24_rebase.py --check
"""

from __future__ import annotations

import argparse
import hashlib
import json
import math
from pathlib import Path
from typing import Any, Callable, FrozenSet, Mapping, Optional, Sequence

EXPECTED_CELLGEMMA_PAYLOAD_SHA256 = "ba72c6eb81f29be7ab1f0b2ef17ca6397eb342f1a2788913475919f48f89e2ab"
EXPECTED_CELLGEMMA_FILE_SHA256 = "33e6f8a8ee7a0d0a51c3bcd1718a6d0f2364f94d55d585eafc39214136273cb8"
EXPECTED_WAVE6_CONTRACT_SHA256 = "53f90447f1f32213adff883f26d30aa1268f4848e6d3d1d946c03d9c7c8a8b42"

PINNED_WAVE6_EXACT = {
    "L0_core_3arm_modular": 54.116275172928866,
    "L0_core_3arm_locked": 50.778198035232116,
    "L1_shipped_5arm_modular": 61.592086541953336,
    "L1_shipped_5arm_locked": 60.64389039505886,
    "Wave5_L3B_modular": 66.57313735189612,
    "Wave5_L3B_locked": 66.00787450699171,
    "Wave6_5Arm_Central_modular": 70.1592137514282,
    "Wave6_5Arm_Central_locked": 68.461471997588,
    "Wave6_6Arm_Central_modular": 71.78644962735174,
    "Wave6_6Arm_Central_locked": 70.59588306296519,
    "Wave6_6Arm_Central_ceiling": 74.95863978207102,
}

# Canonical Wave-6 v0.9.0 arm registry (matching data/protocols/wave6_canonical_arm_manifest.json)
DESIGN_A_ALIASES: FrozenSet[str] = frozenset({
    "A", "DESIGN_A", "ISLET1_A4_ARM1B", "ISLET1_DESIGN_A_V080_REF", "ISLET1_DESIGN_A_V090_TBP_CANDIDATE",
})

ACTIVE_COATING_PRODUCT_ROUTES: FrozenSet[tuple[str, str]] = frozenset({
    ("ISLET1_DESIGN_Y_V3", "R3P"),
    ("ISLET1_DESIGN_B_V090", "R2"),
})

CANONICAL_WAVE6_PRODUCTS: Mapping[str, Mapping[str, Any]] = {
    "ISLET1_DESIGN_A_V080_REF": {
        "arm": "A", "version": "v0.8.0_ref", "required_switch": "AAVS1::iCasp9",
        "home_route": "R1", "allowed_routes": frozenset({"R1", "R2"}), "drug_coating_allowed": False,
        "hla_e_engineered": True, "cd47_engineered": True, "autologous_self_hla": False,
        "foundry_v2_biologics_eligible": False, "execution_supported_in_registry": False,
    },
    "ISLET1_DESIGN_B_V090": {
        "arm": "B", "version": "v0.9.0", "required_switch": "TBP::iCasp9",
        "home_route": "R2", "allowed_routes": frozenset({"R1", "R2"}), "drug_coating_allowed": True,
        "hla_e_engineered": False, "cd47_engineered": True, "autologous_self_hla": False,
        "foundry_v2_biologics_eligible": True, "execution_supported_in_registry": False,
    },
    "ISLET1_DESIGN_X_V090": {
        "arm": "X", "version": "v0.9.0", "required_switch": "TBP::iCasp9",
        "home_route": "R1", "allowed_routes": frozenset({"R1", "R2"}), "drug_coating_allowed": True,
        "hla_e_engineered": False, "cd47_engineered": True, "autologous_self_hla": False,
        "foundry_v2_biologics_eligible": True, "requires_gate31_same_lot": True,
        "execution_supported_in_registry": False,
    },
    "ISLET1_DESIGN_Y_V3": {
        "arm": "Y", "version": "v0.9.0", "required_switch": "DUAL_TBP_ICASP9_PLUS_CDK1_HSVTK",
        "home_route": "R3P", "allowed_routes": frozenset({"R3P", "R4"}), "drug_coating_allowed": True,
        "hla_e_engineered": True, "cd47_engineered": True, "autologous_self_hla": False,
        "foundry_v2_biologics_eligible": True, "execution_supported_in_registry": False,
    },
    "ISLET1_DESIGN_D1B_LEAN_K2": {
        "arm": "D", "version": "v0.9.0", "required_switch": "ACTB::iCasp8",
        "home_route": "R4", "allowed_routes": frozenset({"R3P", "R4"}), "drug_coating_allowed": True,
        "hla_e_engineered": False, "cd47_engineered": False, "autologous_self_hla": True,
        "foundry_v2_biologics_eligible": True, "execution_supported_in_registry": False,
    },
    "ISLET1_ARM_Z_ENSC_V090": {
        "arm": "Z", "version": "v0.9.0", "required_switch": "DUAL_TBP_ICASP9_PLUS_CDK1_HSVTK",
        "home_route": "R4", "allowed_routes": frozenset({"R3P", "R4"}), "drug_coating_allowed": True,
        "hla_e_engineered": True, "cd47_engineered": True, "autologous_self_hla": False,
        "foundry_v2_biologics_eligible": True, "execution_supported_in_registry": False,
    },
}

LEGACY_V080_PRODUCTS: Mapping[str, Mapping[str, Any]] = {
    "ISLET1_A4_ARM1B": {"arm": "A", "required_switch": "AAVS1::iCasp9", "execution_supported_in_registry": True},
    "ISLET1_A4_X_MOL_RNLS_WT": {"arm": "X", "required_switch": "AAVS1::iCasp9", "execution_supported_in_registry": True},
    "ISLET1_B2_5LOCUS_BASE": {"arm": "B", "required_switch": "AAVS1::iCasp9", "execution_supported_in_registry": False},
    "ISLET1_B2_5LOCUS_TYK2_PE": {"arm": "B", "required_switch": "AAVS1::iCasp9", "execution_supported_in_registry": False},
    "ISLET1_Y_FULLSTACK_V2_B2M_11TU": {"arm": "Y", "required_switch": "B2M_ICASP9_PLUS_GATE33_HTMPK", "execution_supported_in_registry": False},
    "ISLET1_D1_AUTO_V2_L1A_CIITA_CD64T_IL1RN": {"arm": "D", "required_switch": "AAVS1_ICASP9_PLUS_GATE33_HTMPK_PLUS_D1_08", "execution_supported_in_registry": False},
}

SCALE_C4_UNIV = (1.0 - 0.950) / (1.0 - 0.920)  # 0.625
SCALE_C3_BASE = (1.0 - 0.942) / (1.0 - 0.925)  # 0.7733333333333333


def require(cond: bool, msg: str) -> None:
    if not cond:
        raise RuntimeError(f"FAIL-CLOSED WAVE-7 ERROR: {msg}")


def is_strict_bool(v: Any) -> bool:
    return isinstance(v, bool)


def is_strict_int(v: Any) -> bool:
    return isinstance(v, int) and not isinstance(v, bool)


def is_finite_num(v: Any) -> bool:
    if isinstance(v, bool) or v is None:
        return False
    if isinstance(v, Decimal):
        return v.is_finite()
    return isinstance(v, (int, float)) and math.isfinite(float(v))


def is_nonempty_str(v: Any) -> bool:
    return isinstance(v, str) and bool(v.strip())


def is_sha256_hex(v: Any) -> bool:
    return isinstance(v, str) and len(v) == 64 and all(ch in "0123456789abcdef" for ch in v.lower())


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


def _canonical_json_default(obj: Any) -> Any:
    if isinstance(obj, Decimal):
        require(obj.is_finite(), f"Non-finite Decimal in canonical JSON: {obj!r}")
        return format(obj.normalize(), "f")
    raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")


def canonical_json_bytes(obj: Any) -> bytes:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=_canonical_json_default).encode("utf-8")


def check_all_finite(obj: Any, path: str = "root") -> None:
    if isinstance(obj, float):
        require(math.isfinite(obj), f"Non-finite float at {path}: {obj!r}")
    elif isinstance(obj, Decimal):
        require(obj.is_finite(), f"Non-finite Decimal at {path}: {obj!r}")
    elif isinstance(obj, dict):
        for k, v in obj.items():
            check_all_finite(v, f"{path}.{k}")
    elif isinstance(obj, list):
        for idx, v in enumerate(obj):
            check_all_finite(v, f"{path}[{idx}]")


def load_strict_json(raw_text: str, label: str = "json", *, parse_float_as_decimal: bool = False) -> Any:
    def _no_dup(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
        out: dict[str, Any] = {}
        for k, v in pairs:
            if k in out:
                raise RuntimeError(f"Duplicate JSON key in {label}: {k!r}")
            out[k] = v
        return out

    def _no_const(tok: str) -> Any:
        raise RuntimeError(f"Non-finite JSON constant in {label}: {tok!r}")

    kwargs: dict[str, Any] = {"object_pairs_hook": _no_dup, "parse_constant": _no_const}
    if parse_float_as_decimal:
        kwargs["parse_float"] = Decimal
    obj = json.loads(raw_text, **kwargs)
    check_all_finite(obj, label)
    return obj


def load_exact_receipt_json(raw_text: str, label: str = "receipt") -> Any:
    """Decode receipt JSON preserving exact finite decimal tokens as Decimal (zero binary-float rounding)."""
    return load_strict_json(raw_text, label=label, parse_float_as_decimal=True)


def subadditive_overlap(base: float, delta_a: float, delta_b: float, omega: float) -> float:
    for nm, val in (("base", base), ("delta_a", delta_a), ("delta_b", delta_b), ("omega", omega)):
        require(is_finite_num(val), f"Non-finite overlap input {nm}={val!r}")
    require(0.0 <= base < 1.0, f"Invalid base={base}")
    require(delta_a >= 0.0 and delta_b >= 0.0, f"Negative deltas: {delta_a}, {delta_b}")
    require(base + delta_a < 1.0 and base + delta_b < 1.0, f"Envelope breach: {base}, {delta_a}, {delta_b}")
    require(0.0 <= omega <= 1.0, f"Invalid omega={omega}")
    hi, lo = max(delta_a, delta_b), min(delta_a, delta_b)
    if lo == 0.0:
        return base + hi
    rem_frac = max(0.0, 1.0 - hi / (1.0 - base))
    val = base + hi + (1.0 - omega) * lo * rem_frac
    require(base <= val < 1.0, f"Out-of-envelope combined value={val}")
    return val


# ---------------------------------------------------------------------------
# Pure-Stdlib Exact 2^20 / 2^24 Probability & LP Primitives
# ---------------------------------------------------------------------------

def biv_bern(p1: float, p2: float, phi: float) -> dict[tuple[int, int], float]:
    require(-1e-12 <= p1 <= 1.0 + 1e-12 and -1e-12 <= p2 <= 1.0 + 1e-12, f"biv_bern domain: {p1}, {p2}")
    require(0.0 <= phi <= 1.0, f"biv_bern phi={phi}")
    p1 = min(1.0, max(0.0, p1))
    p2 = min(1.0, max(0.0, p2))
    p11 = (1.0 - phi) * (p1 * p2) + phi * min(p1, p2)
    return {
        (0, 0): max(0.0, 1.0 - p1 - p2 + p11),
        (1, 0): max(0.0, p1 - p11),
        (0, 1): max(0.0, p2 - p11),
        (1, 1): max(0.0, p11),
    }


def frechet_joint(probs: Sequence[float], phi: float) -> list[float]:
    m = len(probs)
    n = 1 << m
    p_clamped = []
    for p in probs:
        require(-1e-12 <= p <= 1.0 + 1e-12, f"frechet_joint prob out of [0,1]: {p}")
        p_clamped.append(min(1.0, max(0.0, float(p))))
    d_ind = [0.0] * n
    for mask in range(n):
        w = 1.0
        for i in range(m):
            w *= p_clamped[i] if (mask & (1 << i)) else (1.0 - p_clamped[i])
        d_ind[mask] = w
    if phi == 0.0:
        return d_ind
    order = sorted(range(m), key=lambda i: p_clamped[i])
    d_pos = [0.0] * n
    prev = 0.0
    for idx, i in enumerate(order):
        w = p_clamped[i] - prev
        if w > 0.0:
            d_pos[sum(1 << j for j in order[idx:])] += w
        prev = p_clamped[i]
    d_pos[0] += 1.0 - prev
    return [(1.0 - phi) * d_ind[s] + phi * d_pos[s] for s in range(n)]


def frechet_couple(inc: Sequence[float], u_new: float, phi: float, target_fn: Callable[[int], bool]) -> list[float]:
    n0 = len(inc)
    require(-1e-12 <= u_new <= 1.0 + 1e-12, f"frechet_couple u_new out of [0,1]: {u_new}")
    u_new = min(1.0, max(0.0, float(u_new)))
    p_e1 = sum(inc[mi] for mi in range(n0) if target_fn(mi))
    p_e0 = 1.0 - p_e1
    d_ind = [0.0] * (2 * n0)
    for mi in range(n0):
        d_ind[mi] = inc[mi] * (1.0 - u_new)
        d_ind[mi | n0] = inc[mi] * u_new
    d_pos = [0.0] * (2 * n0)
    p_11 = min(p_e1, u_new)
    p_10 = p_e1 - p_11
    p_01 = max(0.0, u_new - p_e1)
    p_00 = p_e0 - p_01
    for mi in range(n0):
        w = inc[mi]
        if w == 0.0:
            continue
        if target_fn(mi):
            d_pos[mi] = p_10 * (w / p_e1) if p_e1 > 0.0 else 0.0
            d_pos[mi | n0] = p_11 * (w / p_e1) if p_e1 > 0.0 else 0.0
        else:
            d_pos[mi] = p_00 * (w / p_e0) if p_e0 > 0.0 else 0.0
            d_pos[mi | n0] = p_01 * (w / p_e0) if p_e0 > 0.0 else 0.0
    return [(1.0 - phi) * d_ind[s] + phi * d_pos[s] for s in range(2 * n0)]


def _max_flow_dinic(n_nodes: int, edges: list[tuple[int, int, float]], src: int, snk: int) -> float:
    adj: list[list[list[Any]]] = [[] for _ in range(n_nodes)]
    for u, v, cap in edges:
        fwd = [v, float(cap), len(adj[v])]
        rev = [u, 0.0, len(adj[u])]
        adj[u].append(fwd)
        adj[v].append(rev)
    eps = 1e-14
    total = 0.0
    while True:
        level = [-1] * n_nodes
        level[src] = 0
        q = [src]
        qi = 0
        while qi < len(q):
            u = q[qi]
            qi += 1
            for v, cap, _ in adj[u]:
                if cap > eps and level[v] < 0:
                    level[v] = level[u] + 1
                    q.append(v)
        if level[snk] < 0:
            break
        it = [0] * n_nodes

        def dfs(u: int, pushed: float) -> float:
            if u == snk:
                return pushed
            while it[u] < len(adj[u]):
                e = adj[u][it[u]]
                v, cap, rev_i = e
                if cap > eps and level[v] == level[u] + 1:
                    tr = dfs(v, min(pushed, cap))
                    if tr > eps:
                        e[1] -= tr
                        adj[v][rev_i][1] += tr
                        return tr
                it[u] += 1
            return 0.0

        while True:
            p = dfs(src, 1e18)
            if p <= eps:
                break
            total += p
    return total


def bipartite_strassen_bounds(
    p_left: Mapping[Any, float],
    p_right: Mapping[Any, float],
    compat_fn: Callable[[Any, Any], bool],
) -> tuple[float, float]:
    l_keys = [k for k, v in p_left.items() if v > 1e-15]
    r_keys = [k for k, v in p_right.items() if v > 1e-15]
    nl, nr = len(l_keys), len(r_keys)
    src, snk = 0, 1 + nl + nr

    def solve(match_good: bool) -> float:
        edges: list[tuple[int, int, float]] = []
        for i, lk in enumerate(l_keys):
            edges.append((src, 1 + i, float(p_left[lk])))
        for j, rk in enumerate(r_keys):
            edges.append((1 + nl + j, snk, float(p_right[rk])))
        for i, lk in enumerate(l_keys):
            for j, rk in enumerate(r_keys):
                if compat_fn(lk, rk) == match_good:
                    edges.append((1 + i, 1 + nl + j, 1.0))
        return _max_flow_dinic(snk + 1, edges, src, snk)

    return max(0.0, 1.0 - solve(False)), min(1.0, solve(True))


def solve_transportation_min_cost(
    supply: Sequence[float],
    demand: Sequence[float],
    costs: Sequence[Sequence[float]],
) -> float:
    m, n = len(supply), len(demand)
    tot_s, tot_d = sum(supply), sum(demand)
    require(abs(tot_s - tot_d) < 1e-9, f"Unbalanced transport: {tot_s} vs {tot_d}")
    s = [float(x) for x in supply]
    d = [float(x) for x in demand]
    d[-1] += tot_s - tot_d

    alloc: dict[tuple[int, int], float] = {}
    rem_s = list(s)
    rem_d = list(d)
    i = j = 0
    while i < m and j < n:
        take = min(rem_s[i], rem_d[j])
        alloc[(i, j)] = take
        rem_s[i] -= take
        rem_d[j] -= take
        if i == m - 1 and j == n - 1:
            break
        if i == m - 1:
            j += 1
        elif j == n - 1:
            i += 1
        elif rem_s[i] <= rem_d[j]:
            i += 1
        else:
            j += 1
    require(len(alloc) == m + n - 1, f"Basis size mismatch: {len(alloc)} != {m + n - 1}")

    eps = 1e-13
    for _iter in range(50000):
        row_adj: list[list[int]] = [[] for _ in range(m)]
        col_adj: list[list[int]] = [[] for _ in range(n)]
        for ri, cj in alloc:
            row_adj[ri].append(cj)
            col_adj[cj].append(ri)
        u: list[Optional[float]] = [None] * m
        v: list[Optional[float]] = [None] * n
        u[0] = 0.0
        stack: list[tuple[str, int]] = [("r", 0)]
        while stack:
            kind, idx = stack.pop()
            if kind == "r":
                ui = u[idx]
                require(ui is not None, "Transport simplex u[idx] missing")
                for cj in row_adj[idx]:
                    if v[cj] is None:
                        v[cj] = costs[idx][cj] - float(ui)
                        stack.append(("c", cj))
            else:
                vj = v[idx]
                require(vj is not None, "Transport simplex v[idx] missing")
                for ri in col_adj[idx]:
                    if u[ri] is None:
                        u[ri] = costs[ri][idx] - float(vj)
                        stack.append(("r", ri))

        best_rc = -1e-12
        enter: Optional[tuple[int, int]] = None
        for ri in range(m):
            ui = u[ri]
            require(ui is not None, "Transport simplex u[ri] missing")
            crow = costs[ri]
            for cj in range(n):
                if (ri, cj) in alloc:
                    continue
                vj = v[cj]
                require(vj is not None, "Transport simplex v[cj] missing")
                rc = crow[cj] - float(ui) - float(vj)
                if rc < best_rc:
                    best_rc = rc
                    enter = (ri, cj)
        if enter is None:
            break

        er, ec = enter
        parent: dict[tuple[str, int], Optional[tuple[str, int]]] = {("r", er): None}
        q: list[tuple[str, int]] = [("r", er)]
        qi = 0
        target = ("c", ec)
        while qi < len(q):
            cur = q[qi]
            qi += 1
            if cur == target:
                break
            kind, idx = cur
            if kind == "r":
                for cj in row_adj[idx]:
                    nxt = ("c", cj)
                    if nxt not in parent:
                        parent[nxt] = cur
                        q.append(nxt)
            else:
                for ri in col_adj[idx]:
                    nxt = ("r", ri)
                    if nxt not in parent:
                        parent[nxt] = cur
                        q.append(nxt)
        require(target in parent, "Transport simplex cycle not found")

        nodes: list[tuple[str, int]] = []
        cur_n: Optional[tuple[str, int]] = target
        while cur_n is not None:
            nodes.append(cur_n)
            cur_n = parent[cur_n]
        nodes.reverse()
        cycle_cells: list[tuple[int, int]] = [enter]
        for k in range(len(nodes) - 1):
            a_n, b_n = nodes[k], nodes[k + 1]
            if a_n[0] == "r":
                cycle_cells.append((a_n[1], b_n[1]))
            else:
                cycle_cells.append((b_n[1], a_n[1]))

        minus_cells = cycle_cells[1::2]
        theta = min(alloc[c] for c in minus_cells)
        leave = min(minus_cells, key=lambda c: (alloc[c], c))
        alloc[enter] = 0.0
        for idx_c, cell in enumerate(cycle_cells):
            if idx_c % 2 == 0:
                alloc[cell] += theta
            else:
                alloc[cell] -= theta
        del alloc[leave]
        for cell in alloc:
            if -eps < alloc[cell] < 0.0:
                alloc[cell] = 0.0

    return sum(val * costs[ri][cj] for (ri, cj), val in alloc.items())


def build_h2_5arm(
    pa: float, pb: float, px: float, py: float, pd: float,
    *,
    c2_a: float = 0.87, c2_bx: float = 0.87, c2_y: float = 0.87,
    c2_univ: float = 0.95, c2_univ_a: float = 0.95, c2_auto: float = 0.93,
    phi_yx: float = 0.75, phi_c: float = 0.25, phi_inc: float = 0.25,
) -> tuple[list[float], float]:
    require(c2_a <= c2_bx + 1e-12 and c2_bx <= c2_y + 1e-12 and c2_y <= c2_univ + 1e-12, "H2 ceiling order invalid")
    u_d = pd / c2_auto
    if abs(c2_a - c2_bx) <= 1e-12 and abs(c2_univ - c2_univ_a) <= 1e-12:
        biv2 = biv_bern(c2_y / c2_univ, c2_auto / c2_univ, phi_c)
        d2_inc = frechet_joint([pa / c2_bx, pb / c2_bx, px / c2_bx], phi_inc)
        r2, u_y = c2_bx / c2_y, py / c2_y
        d2_both = frechet_couple(d2_inc, u_y, phi_yx, lambda mi: bool(mi & 4))
        d2_allo4 = [r2 * d2_both[k] for k in range(16)]
        d2_allo4[0] += (1.0 - r2) * (1.0 - u_y)
        d2_allo4[8] += (1.0 - r2) * u_y
        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_d)
                d2[16] += w * u_d
            else:
                for m4 in range(16):
                    d2[m4] += w * d2_allo4[m4] * (1.0 - u_d)
                    d2[m4 | 16] += w * d2_allo4[m4] * u_d
        return d2, c2_univ * (1.0 - biv2[(0, 0)])

    require(abs(c2_bx - c2_y) <= 1e-12, "Nested H2 Design-A firewall requires c2_bx == c2_y")
    biv_a = biv_bern(c2_a / c2_univ_a, c2_auto / c2_univ_a, phi_c)
    biv_y = biv_bern(c2_y / c2_univ, c2_auto / c2_univ, phi_c)
    p_a1_d1, p_a1_d0 = c2_univ_a * biv_a[(1, 1)], c2_univ_a * biv_a[(1, 0)]
    p_y1_d1, p_y1_d0 = c2_univ * biv_y[(1, 1)], c2_univ * biv_y[(1, 0)]
    require(p_a1_d1 <= p_y1_d1 + 1e-12 and p_a1_d0 <= p_y1_d0 + 1e-12, "Nested H2 firewall ordering violated")
    q11 = p_a1_d1 / p_y1_d1 if p_y1_d1 > 0.0 else 0.0
    q10 = p_a1_d0 / p_y1_d0 if p_y1_d0 > 0.0 else 0.0
    d2_with_a = frechet_couple(
        frechet_joint([pa / c2_a, pb / c2_bx, px / c2_bx], phi_inc), py / c2_y, phi_yx, lambda mi: bool(mi & 4)
    )
    d2_no_a = frechet_couple(
        frechet_joint([0.0, pb / c2_bx, px / c2_bx], phi_inc), py / c2_y, phi_yx, lambda mi: bool(mi & 4)
    )
    d2 = [0.0] * 32
    d2[0] += 1.0 - c2_univ + c2_univ * biv_y[(0, 0)]
    w01 = c2_univ * biv_y[(0, 1)]
    d2[0] += w01 * (1.0 - u_d)
    d2[16] += w01 * u_d
    for m4 in range(16):
        d2[m4] += p_y1_d0 * (q10 * d2_with_a[m4] + (1.0 - q10) * d2_no_a[m4])
        mix = q11 * d2_with_a[m4] + (1.0 - q11) * d2_no_a[m4]
        d2[m4] += p_y1_d1 * mix * (1.0 - u_d)
        d2[m4 | 16] += p_y1_d1 * mix * u_d
    return d2, c2_univ * (1.0 - biv_y[(0, 0)])


def build_h3_5arm(
    pa: float, pb: float, px: float, py: float, pd: float,
    *,
    c3: float = 0.942, phi_yx: float = 0.75, phi_c: float = 0.25, phi_inc: float = 0.25,
) -> tuple[list[float], float]:
    d3_inc = frechet_joint([pa / c3, pb / c3, px / c3], phi_inc)
    d3_4 = frechet_couple(d3_inc, py / c3, phi_yx, lambda mi: bool(mi & 4))
    d3_5 = frechet_couple(d3_4, pd / c3, phi_c, lambda mi: mi != 0)
    d3 = [1.0 - c3 + c3 * d3_5[0]] + [c3 * d3_5[k] for k in range(1, 32)]
    return d3, c3


def couple_coated_overlay_2arm(
    d_unc: Sequence[float],
    idx_b: int,
    idx_y: int,
    delta_b: float,
    delta_y: float,
    delta_univ: float,
    phi_by: float,
    n_base_bits: int,
) -> list[float]:
    """
    Monotonically lifts an n_base_bits uncoated distribution d_unc to (n_base_bits + 2) bits:
      - bits 0..n_base_bits-1: EXACT unmodified Wave-6 uncoated joint law d_unc
        (marginalizing out coated bits recovers d_unc bit-for-bit to <= 1e-13!).
      - bit n_base_bits:     B_COAT (= 1 whenever bit idx_b == 1, plus exact +delta_b on idx_b == 0)
      - bit n_base_bits + 1: Y_COAT (= 1 whenever bit idx_y == 1, plus exact +delta_y on idx_y == 0)
    Universal failure state m == 0 gets exact union rescue mass:
      U0 = min(max(0.0, delta_univ), delta_b + delta_y, d_unc[0])
    strictly zero in fixed-ceiling mode (delta_univ == 0.0), so zero uncoated-pathway spillover
    is guaranteed across ALL uncoated subsets, including (X, D, Z)-only and B/R1!
    """
    require(delta_b >= -1e-15 and delta_y >= -1e-15 and delta_univ >= -1e-15, "Negative coated overlay delta")
    delta_b = max(0.0, delta_b)
    delta_y = max(0.0, delta_y)
    delta_univ = max(0.0, delta_univ)
    n_base = 1 << n_base_bits
    require(len(d_unc) == n_base, f"Expected {n_base} states in d_unc, got {len(d_unc)}")

    d_out = [0.0] * (1 << (n_base_bits + 2))
    bit_bc = 1 << n_base_bits
    bit_yc = 1 << (n_base_bits + 1)
    p_m0 = float(d_unc[0])
    p_b0_nz = sum(float(p) for m, p in enumerate(d_unc) if m != 0 and not ((m >> idx_b) & 1))
    p_y0_nz = sum(float(p) for m, p in enumerate(d_unc) if m != 0 and not ((m >> idx_y) & 1))

    u0 = min(delta_univ, delta_b + delta_y, p_m0)
    if u0 > 0.0 and (delta_b + delta_y) > 0.0:
        ov_max = max(0.0, min(delta_b, delta_y, u0, delta_b + delta_y - u0))
        ov = phi_by * ov_max
        rem_u = u0 - ov
        cap_b = max(0.0, delta_b - ov)
        cap_y = max(0.0, delta_y - ov)
        if cap_b + cap_y <= 1e-15:
            p0_10 = p0_01 = 0.0
        else:
            p0_10 = min(cap_b, rem_u * (cap_b / (cap_b + cap_y)))
            p0_01 = rem_u - p0_10
            if p0_01 > cap_y + 1e-15:
                p0_01 = cap_y
                p0_10 = rem_u - p0_01
        p0_11 = ov
        p0_00 = p_m0 - u0
    else:
        p0_00, p0_10, p0_01, p0_11 = p_m0, 0.0, 0.0, 0.0

    d_out[0] = p0_00
    d_out[bit_bc] = p0_10
    d_out[bit_yc] = p0_01
    d_out[bit_bc | bit_yc] = p0_11

    rem_b = max(0.0, delta_b - (p0_10 + p0_11))
    rem_y = max(0.0, delta_y - (p0_01 + p0_11))
    require(rem_b <= p_b0_nz + 1e-12, f"B_COAT lift {rem_b} exceeds remaining failure mass {p_b0_nz}")
    require(rem_y <= p_y0_nz + 1e-12, f"Y_COAT lift {rem_y} exceeds remaining failure mass {p_y0_nz}")
    qb = min(1.0, rem_b / p_b0_nz) if p_b0_nz > 0.0 else 0.0
    qy = min(1.0, rem_y / p_y0_nz) if p_y0_nz > 0.0 else 0.0

    for m, p in enumerate(d_unc):
        pf = float(p)
        if m == 0 or pf == 0.0:
            continue
        b_on = bool((m >> idx_b) & 1)
        y_on = bool((m >> idx_y) & 1)
        if b_on and y_on:
            d_out[m | bit_bc | bit_yc] += pf
        elif b_on and not y_on:
            d_out[m | bit_bc | bit_yc] += pf * qy
            d_out[m | bit_bc] += pf * (1.0 - qy)
        elif not b_on and y_on:
            d_out[m | bit_bc | bit_yc] += pf * qb
            d_out[m | bit_yc] += pf * (1.0 - qb)
        else:
            biv = biv_bern(qb, qy, phi_by)
            for (bb, by), wb in biv.items():
                if wb > 0.0:
                    d_out[m | (bit_bc if bb else 0) | (bit_yc if by else 0)] += pf * wb

    # Fail-closed exact uncoated projection + marginal invariance verification
    for m in range(n_base):
        proj = d_out[m] + d_out[m | bit_bc] + d_out[m | bit_yc] + d_out[m | bit_bc | bit_yc]
        require(abs(proj - float(d_unc[m])) <= 1e-12, f"Uncoated projection drift at m={m}: {proj} vs {d_unc[m]}")
    mb = sum(p for m, p in enumerate(d_out) if (m & bit_bc))
    my = sum(p for m, p in enumerate(d_out) if (m & bit_yc))
    mb_u = sum(float(p) for m, p in enumerate(d_unc) if (m >> idx_b) & 1)
    my_u = sum(float(p) for m, p in enumerate(d_unc) if (m >> idx_y) & 1)
    require(abs(mb - (mb_u + delta_b)) <= 1e-11, f"B_COAT marginal mismatch: {mb} vs {mb_u + delta_b}")
    require(abs(my - (my_u + delta_y)) <= 1e-11, f"Y_COAT marginal mismatch: {my} vs {my_u + delta_y}")
    return d_out

def couple_h3_uncoated_c_vs_coated_base(
    d3_base: Sequence[float],
    d3_c: Sequence[float],
    idx_b: int,
    idx_y: int,
    n_base_bits: int,
) -> list[float]:
    """
    Exact Strassen monotone (n_base_bits + 2)-bit exposure-specific H3 joint law:
      - bits 0..n_base_bits-1: exact uncoated H3 distribution d3_c (with IIP-0064 C ON)
      - bit n_base_bits:     B_COAT H3 (exact Wave-6 baseline marginal/joint from d3_base, C OFF)
      - bit n_base_bits + 1: Y_COAT H3 (exact Wave-6 baseline marginal/joint from d3_base, C OFF)
    Guarantees B_COAT <= B_c and Y_COAT <= Y_c statewise, recovers d3_c bit-for-bit on uncoated
    bits, and recovers the exact 4-cell (B, Y) joint law of d3_base (zero C marginal or ceiling
    spillover onto coated B_COAT/R2_COAT and Y_COAT/R3P_COAT paths) to <= 1e-12.
    """
    n_base = 1 << n_base_bits
    require(len(d3_base) == n_base and len(d3_c) == n_base, "H3 length mismatch in exposure-specific coupling")
    q = {(0, 0): 0.0, (1, 0): 0.0, (0, 1): 0.0, (1, 1): 0.0}
    p = {(0, 0): 0.0, (1, 0): 0.0, (0, 1): 0.0, (1, 1): 0.0}
    for m, pr in enumerate(d3_base):
        q[((m >> idx_b) & 1, (m >> idx_y) & 1)] += float(pr)
    for m, pr in enumerate(d3_c):
        p[((m >> idx_b) & 1, (m >> idx_y) & 1)] += float(pr)
    # Strassen 4 upper-set monotonicity conditions on {0,1}^2
    require(p[(1, 1)] >= q[(1, 1)] - 1e-12, "Strassen H3 upper-set (1,1) violated")
    require(p[(1, 0)] + p[(1, 1)] >= q[(1, 0)] + q[(1, 1)] - 1e-12, "Strassen H3 upper-set B violated")
    require(p[(0, 1)] + p[(1, 1)] >= q[(0, 1)] + q[(1, 1)] - 1e-12, "Strassen H3 upper-set Y violated")
    require(q[(0, 0)] >= p[(0, 0)] - 1e-12, "Strassen H3 upper-set B|Y violated")

    t: dict[tuple[int, int], dict[tuple[int, int], float]] = {}
    t[(0, 0)] = {(0, 0): p[(0, 0)]}
    t10_10 = min(p[(1, 0)], q[(1, 0)])
    t[(1, 0)] = {(1, 0): t10_10, (0, 0): max(0.0, p[(1, 0)] - t10_10)}
    t01_01 = min(p[(0, 1)], q[(0, 1)])
    t[(0, 1)] = {(0, 1): t01_01, (0, 0): max(0.0, p[(0, 1)] - t01_01)}
    t11_11 = q[(1, 1)]
    t11_10 = max(0.0, q[(1, 0)] - p[(1, 0)])
    t11_01 = max(0.0, q[(0, 1)] - p[(0, 1)])
    t11_00 = max(0.0, p[(1, 1)] - t11_11 - t11_10 - t11_01)
    t[(1, 1)] = {(1, 1): t11_11, (1, 0): t11_10, (0, 1): t11_01, (0, 0): t11_00}

    bit_bc = 1 << n_base_bits
    bit_yc = 1 << (n_base_bits + 1)
    d_out = [0.0] * (1 << (n_base_bits + 2))
    for m, pr in enumerate(d3_c):
        pf = float(pr)
        if pf == 0.0:
            continue
        st = ((m >> idx_b) & 1, (m >> idx_y) & 1)
        denom = p[st]
        if denom <= 0.0:
            continue
        for (bc, yc), wt in t[st].items():
            if wt > 0.0:
                d_out[m | (bit_bc if bc else 0) | (bit_yc if yc else 0)] += pf * (wt / denom)

    # Exact bilateral marginal verification
    for m in range(n_base):
        proj = d_out[m] + d_out[m | bit_bc] + d_out[m | bit_yc] + d_out[m | bit_bc | bit_yc]
        require(abs(proj - float(d3_c[m])) <= 1e-12, f"H3 uncoated projection drift at m={m}")
    for bc in (0, 1):
        for yc in (0, 1):
            got_q = sum(
                pr for m, pr in enumerate(d_out)
                if bool(m & bit_bc) == bool(bc) and bool(m & bit_yc) == bool(yc)
            )
            require(abs(got_q - q[(bc, yc)]) <= 1e-12, f"H3 coated baseline 4-cell drift at ({bc},{yc})")
    return d_out


def eval_exact_n_arm(
    arms: Sequence[tuple[float, float, float, float]],
    dists: Sequence[Sequence[float]],
    caps: Sequence[float],
    routes: Sequence[str],
    cell_classes: Sequence[str],
    compat_map: Mapping[str, FrozenSet[str]],
    *,
    coated_overlay_active: bool = False,
    coated_b_active: bool = False,
    coated_y_active: bool = False,
    coated_routes: FrozenSet[str] = frozenset(),
    coated_eligible_arm_mask: int = 0,
    compute_strassen: bool = True,
    compute_h23_lp: bool = False,
) -> dict[str, Any]:
    """
    Exact 2^(4n) [and (n+2)-bit exposure-specific coated-overlay] portfolio evaluator.
    When coated_overlay_active=True:
      - d2 has (n+2) bits: bits 0..n-1 are EXACT unmodified uncoated H2 states;
        bit n = B_COAT (only pairs with R2_COAT); bit n+1 = Y_COAT (only pairs with R3P_COAT).
      - d4 has (n+2) bits: bits 0..n-1 are EXACT unmodified uncoated H4 routes;
        bit n = R2_COAT; bit n+1 = R3P_COAT.
      - cell_classes has (n+2) entries: 0..n-1 uncoated cell classes + n="COAT_B_ONLY" + n+1="COAT_Y_ONLY".
      - routes has (n+2) entries: 0..n-1 uncoated routes + n="ADV_COAT" + n+1="R3P_COAT".
    Guarantees ZERO spillover onto any uncoated pathway (Design A, X/D/Z, B/R1, Y/R4, R1&R4 joint)!
    """
    n = len(arms)
    d1, d2, d3, d4 = dists
    n_arm_mask = (1 << n) - 1
    for hi, dist in enumerate(dists):
        require(abs(sum(dist) - 1.0) <= 1e-11, f"H{hi+1} distribution sum != 1: {sum(dist)}")
        for i in range(n):
            got_m = sum(dist[m] for m in range(len(dist)) if (m >> i) & 1)
            require(abs(got_m - arms[i][hi]) <= 1e-11, f"Arm {i} H{hi+1} marginal mismatch: {got_m} vs {arms[i][hi]}")

    n_cbits = (n + 2) if coated_overlay_active else n
    n_rbits = len(routes)
    require(len(cell_classes) == n_cbits, f"cell_classes len {len(cell_classes)} != {n_cbits}")

    d12: dict[int, float] = {}
    bit_bc = 1 << n
    bit_yc = 1 << (n + 1)
    for m1, p1 in enumerate(d1):
        if p1 == 0.0:
            continue
        for m2, p2 in enumerate(d2):
            if p2 == 0.0:
                continue
            m = m1 & (m2 & n_arm_mask)
            if coated_overlay_active:
                if coated_b_active and (m1 & (1 << 1)) and (m2 & bit_bc):
                    m |= bit_bc
                if coated_y_active and (m1 & (1 << 3)) and (m2 & bit_yc):
                    m |= bit_yc
            if m:
                d12[m] = d12.get(m, 0.0) + p1 * p2

    d3_has_coated_bits = coated_overlay_active and (len(d3) == (1 << (n + 2)))
    d123: dict[int, float] = {}
    for m12, p12 in d12.items():
        for m3, p3 in enumerate(d3):
            if p3 == 0.0:
                continue
            m = (m12 & n_arm_mask) & (m3 & n_arm_mask)
            if coated_overlay_active:
                bc_m3 = bool(m3 & bit_bc) if d3_has_coated_bits else bool(m3 & (1 << 1))
                yc_m3 = bool(m3 & bit_yc) if d3_has_coated_bits else bool(m3 & (1 << 3))
                if (m12 & bit_bc) and bc_m3:
                    m |= bit_bc
                if (m12 & bit_yc) and yc_m3:
                    m |= bit_yc
            if m:
                d123[m] = d123.get(m, 0.0) + p12 * p3

    p_cell_cls: dict[FrozenSet[str], float] = {}
    p_123_sum = 0.0
    for m123, p123 in d123.items():
        cls_set = frozenset(cell_classes[i] for i in range(n_cbits) if (m123 >> i) & 1)
        p_cell_cls[cls_set] = p_cell_cls.get(cls_set, 0.0) + p123
        p_123_sum += p123
    p_cell_cls[frozenset()] = max(0.0, 1.0 - p_123_sum)

    p_route_set: dict[FrozenSet[str], float] = {}
    d4_nz_rsets: list[tuple[int, float, FrozenSet[str]]] = []
    for m4, p4 in enumerate(d4):
        if p4 == 0.0:
            continue
        r_set = frozenset(routes[k] for k in range(n_rbits) if (m4 >> k) & 1)
        p_route_set[r_set] = p_route_set.get(r_set, 0.0) + p4
        d4_nz_rsets.append((m4, p4, r_set))

    def is_mod_compat(cls_set: FrozenSet[str], r_set: FrozenSet[str]) -> bool:
        for cc in cls_set:
            if compat_map.get(cc, frozenset()) & r_set:
                return True
        return False

    p_locked = 0.0
    p_modular = 0.0
    p_modular_no_coated = 0.0
    p_coated_only_by = 0.0
    p_xdz_uncoated = 0.0
    p_b_r1_uncoated = 0.0
    p_a_only_with_coated_route = 0.0
    p_non_eligible_coated_route_leak = 0.0
    p_r1_and_r4_uncoated = 0.0
    for m4, p4, r_set in d4_nz_rsets:
        if ("R1" in r_set) and ("R4" in r_set):
            p_r1_and_r4_uncoated += p4

    xdz_mask = (1 << 2) | (1 << 4) | ((1 << 5) if n == 6 else 0)
    for m123, p123 in d123.items():
        cls_set = frozenset(cell_classes[i] for i in range(n_cbits) if (m123 >> i) & 1)
        xdz_cls = frozenset(cell_classes[i] for i in range(n) if ((m123 & xdz_mask) >> i) & 1)
        b_unc_on = bool(m123 & (1 << 1))
        for m4, p4, r_set in d4_nz_rsets:
            w = p123 * p4
            locked_hit = bool((m123 & n_arm_mask) & (m4 & n_arm_mask))
            if coated_overlay_active:
                if coated_b_active and (m123 & bit_bc) and (m4 & bit_bc):
                    locked_hit = True
                if coated_y_active and (m123 & bit_yc) and (m4 & bit_yc):
                    locked_hit = True
            if locked_hit:
                p_locked += w
            uncoated_r = r_set - coated_routes
            if is_mod_compat(cls_set, uncoated_r):
                p_modular_no_coated += w
            if coated_overlay_active:
                if (coated_b_active and (m123 & bit_bc) and ("ADV_COAT" in r_set)) or (coated_y_active and (m123 & bit_yc) and ("R3P_COAT" in r_set)):
                    p_coated_only_by += w
            if xdz_cls and is_mod_compat(xdz_cls, uncoated_r):
                p_xdz_uncoated += w
            if b_unc_on and ("R1" in uncoated_r):
                p_b_r1_uncoated += w
            if is_mod_compat(cls_set, r_set):
                p_modular += w
                if coated_routes:
                    if (m123 & n_arm_mask) == 1 and not (m123 & ~n_arm_mask) and not is_mod_compat(cls_set, uncoated_r):
                        p_a_only_with_coated_route += w
                    if not (m123 & coated_eligible_arm_mask) and not is_mod_compat(cls_set, uncoated_r):
                        p_non_eligible_coated_route_leak += w

    require(
        p_a_only_with_coated_route == 0.0,
        f"Physical Design-A modular coated-route leak detected: {p_a_only_with_coated_route}",
    )
    require(
        p_non_eligible_coated_route_leak == 0.0,
        f"Non-whitelisted product coated-route modular leak detected: {p_non_eligible_coated_route_leak}",
    )

    p_ceiling = caps[0] * caps[1] * caps[2] * caps[3]
    a_m = [sum(dist[m] for m in range(len(dist)) if (m & 1)) for dist in dists]
    ad_h2 = [0.0, 0.0, 0.0, 0.0]
    for m, p in enumerate(d2):
        ad_h2[((m & 1) << 1) | ((m >> 4) & 1)] += p

    out: dict[str, Any] = {
        "locked_exact": p_locked * 100.0,
        "modular_exact": p_modular * 100.0,
        "ceiling_exact": p_ceiling * 100.0,
        "locked_pct": round(p_locked * 100.0, 4),
        "modular_pct": round(p_modular * 100.0, 4),
        "ceiling_pct": round(p_ceiling * 100.0, 4),
        "no_coated_routes_modular_exact": p_modular_no_coated * 100.0,
        "no_coated_routes_modular_pct": round(p_modular_no_coated * 100.0, 4),
        "coated_only_by_modular_exact": p_coated_only_by * 100.0,
        "coated_only_by_modular_pct": round(p_coated_only_by * 100.0, 4),
        "uncoated_xdz_only_modular_exact": p_xdz_uncoated * 100.0,
        "uncoated_xdz_only_modular_pct": round(p_xdz_uncoated * 100.0, 4),
        "uncoated_b_r1_marginal_exact": p_b_r1_uncoated * 100.0,
        "uncoated_b_r1_marginal_pct": round(p_b_r1_uncoated * 100.0, 4),
        "uncoated_r1_and_r4_joint_exact": p_r1_and_r4_uncoated * 100.0,
        "uncoated_r1_and_r4_joint_pct": round(p_r1_and_r4_uncoated * 100.0, 4),
        "hurdle_caps_exact_pct": [c * 100.0 for c in caps],
        "hurdle_caps_pct": [round(c * 100.0, 4) for c in caps],
        "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],
        "design_a_4_marginals_exact": a_m,
        "design_a_standalone_exact": a_m[0] * a_m[1] * a_m[2] * a_m[3],
        "design_a_d_h2_joint_4cell_exact": ad_h2,
        "design_a_only_coated_route_modular_mass_pp": 0.0,
        "non_eligible_product_coated_route_modular_leak_pp": 0.0,
    }

    if compute_strassen:
        s_min, s_max = bipartite_strassen_bounds(p_cell_cls, p_route_set, is_mod_compat)
        out["strassen_h123_h4_exact"] = [s_min * 100.0, s_max * 100.0]
        out["strassen_h123_h4_pct"] = [round(s_min * 100.0, 4), round(s_max * 100.0, 4)]

    if compute_h23_lp:
        # Build exact class-level H2 and H3 projections for sharp H2-H3 transportation LP
        d1_nz = [(m1, p1) for m1, p1 in enumerate(d1) if p1 > 1e-15]
        # Reduce d2 and d3 over nonzero states
        nz2 = [(m, p) for m, p in enumerate(d2) if p > 1e-15]
        nz3 = [(m, p) for m, p in enumerate(d3) if p > 1e-15]
        payoff_cache: dict[tuple[int, int], float] = {}
        c_min: list[list[float]] = []
        c_max: list[list[float]] = []
        for m2, _ in nz2:
            row_min: list[float] = []
            row_max: list[float] = []
            for m3, _ in nz3:
                key23 = (m2, m3)
                val = payoff_cache.get(key23)
                if val is None:
                    val = 0.0
                    for m1, p1 in d1_nz:
                        m123 = m1 & (m2 & n_arm_mask) & (m3 & n_arm_mask)
                        if coated_overlay_active:
                            bc_m3_lp = bool(m3 & bit_bc) if d3_has_coated_bits else bool(m3 & 2)
                            yc_m3_lp = bool(m3 & bit_yc) if d3_has_coated_bits else bool(m3 & 8)
                            if coated_b_active and (m1 & 2) and (m2 & bit_bc) and bc_m3_lp:
                                m123 |= bit_bc
                            if coated_y_active and (m1 & 8) and (m2 & bit_yc) and yc_m3_lp:
                                m123 |= bit_yc
                        if m123 == 0:
                            continue
                        cls_set = frozenset(cell_classes[i] for i in range(n_cbits) if (m123 >> i) & 1)
                        p_r_ok = sum(pr for r_set, pr in p_route_set.items() if is_mod_compat(cls_set, r_set))
                        val += p1 * p_r_ok
                    payoff_cache[key23] = val
                row_min.append(val)
                row_max.append(-val)
            c_min.append(row_min)
            c_max.append(row_max)
        sup = [p for _, p in nz2]
        dem = [p for _, p in nz3]
        h23_min = solve_transportation_min_cost(sup, dem, c_min)
        h23_max = -solve_transportation_min_cost(sup, dem, c_max)
        out["sharp_h23_lp_exact"] = [h23_min * 100.0, h23_max * 100.0]
        out["sharp_h23_lp_pct"] = [round(h23_min * 100.0, 4), round(h23_max * 100.0, 4)]

    return out


def eval_wave7_portfolio(
    name: str,
    arms_uncoated: Sequence[tuple[float, float, float, float]],
    *,
    c1_allo: float = 0.88,
    c1_univ: Optional[float] = 0.925,
    c1_z: Optional[float] = 0.84,
    c2_a: float = 0.87,
    c2_bx_unc: float = 0.87,
    c2_y_unc: float = 0.87,
    c2_d: float = 0.93,
    c2_univ_unc: float = 0.95,
    c3_base: float = 0.942,
    c4_univ_unc: float = 0.950,
    c4_r1: float = 0.850,
    c4_r2_unc: float = 0.850,
    c4_r3p_unc: float = 0.850,
    c4_r4: Optional[float] = 0.870,
    # Coating overlay deltas (strictly isolated to B_COAT/R2_COAT and Y_COAT/R3P_COAT!)
    coated_overlay_active: bool = False,
    coated_b_active: bool = False,
    coated_y_active: bool = False,
    delta_b_h2: float = 0.0,
    delta_y_h2: float = 0.0,
    delta_c2_univ: float = 0.0,
    delta_b_h4: float = 0.0,
    delta_y_h4: float = 0.0,
    delta_c4_univ: float = 0.0,
    # Exposure-specific H3 baseline for coated paths (GATE-42 requires DRUG_FREE_EXPOSURE!)
    arms_h3_coated_base: Optional[Sequence[float]] = None,
    c3_coated_base: Optional[float] = None,
    allow_c_on_coated_paths: bool = False,
    # Counterfactual / sensitivity flags (non-primary only!)
    include_r4_vehicle_gated_cf: bool = False,
    c4_r4_cf_lifted: Optional[float] = None,
    c4_univ_cf_lifted: Optional[float] = None,
    include_z_r3p_sensitivity: bool = False,
    z_h2_sens_lift: float = 0.0,
    z_h4_sens_lift: float = 0.0,
    phi_z_h1: float = 0.55,
    phi_z_h2: float = 0.80,
    phi_z_h3: float = 0.80,
    phi_r4: float = 0.30,
    phi_yx: float = 0.75,
    phi_c: float = 0.25,
    phi_inc: float = 0.25,
    c1_pass: bool = True,
    design_a_r1_only_when_coated: bool = True,
    compute_strassen: bool = True,
    compute_h23_lp: bool = False,
) -> dict[str, Any]:
    """
    True Zero-Spillover Wave-7 Portfolio Evaluator.
    In primary coated mode (coated_overlay_active=True):
      - Uncoated H2 and H4 joint laws remain 100% BIT-IDENTICAL to Wave-6!
      - B_COAT (bit n) pairs EXCLUSIVELY with R2_COAT (bit n); Y_COAT (bit n+1) pairs EXCLUSIVELY with R3P_COAT (bit n+1).
      - Design A (INC_A_DRUGFREE) is restricted to uncoated R1 whenever R2 is drug-coated.
      - Zero spillover onto X, D, Z, B/R1, Y/R4, and R1&R4 joint is mathematically guaranteed and asserted!
    """
    n = len(arms_uncoated)
    require(n in (5, 6), f"Only 5-arm or 6-arm portfolios supported, got {n}")
    r4_set = frozenset({"R4"}) if c4_r4 is not None else frozenset()

    # H1 (unmodified Wave-6)
    if n == 5 or c1_univ is None:
        d1 = [0.0] * (1 << n)
        u_d = arms_uncoated[4][0] / c1_allo
        if n == 5:
            d1[0], d1[15], d1[31] = 1.0 - c1_allo, c1_allo * (1.0 - u_d), c1_allo * u_d
        else:
            u_z = arms_uncoated[5][0] / c1_allo
            sub = biv_bern(u_d, u_z, phi_z_h1)
            d1[0] = 1.0 - c1_allo
            for (bd, bz), w in sub.items():
                d1[15 | (bd << 4) | (bz << 5)] += c1_allo * w
        c1_eff = c1_allo
    else:
        sh1 = biv_bern(c1_allo / c1_univ, float(c1_z) / c1_univ, phi_z_h1)
        d1 = [0.0] * 64
        d1[0] = 1.0 - c1_univ
        u_d, u_z = arms_uncoated[4][0] / c1_allo, arms_uncoated[5][0] / float(c1_z)
        for (s_sc, s_z), ws in sh1.items():
            wt = c1_univ * ws
            if s_sc == 0 and s_z == 0:
                d1[0] += wt
            elif s_sc == 1 and s_z == 0:
                d1[15] += wt * (1.0 - u_d)
                d1[31] += wt * u_d
            elif s_sc == 0 and s_z == 1:
                d1[0] += wt * (1.0 - u_z)
                d1[32] += wt * u_z
            else:
                for (bd, bz), wb in biv_bern(u_d, u_z, 0.0).items():
                    d1[15 | (bd << 4) | (bz << 5)] += wt * wb
        c1_eff = c1_univ * (1.0 - sh1[(0, 0)])

    # H2: Exact Wave-6 uncoated law + optional monotonic (n+2)-bit exposure-specific coated overlay!
    z_h2_eff = arms_uncoated[5][1] + (z_h2_sens_lift if (n == 6 and (include_z_r3p_sensitivity or include_r4_vehicle_gated_cf)) else 0.0) if n == 6 else 0.0
    d2_5, c2_eff_5 = build_h2_5arm(
        arms_uncoated[0][1], arms_uncoated[1][1], arms_uncoated[2][1], arms_uncoated[3][1], arms_uncoated[4][1],
        c2_a=c2_a, c2_bx=c2_bx_unc, c2_y=c2_y_unc, c2_univ=c2_univ_unc, c2_univ_a=c2_univ_unc, c2_auto=c2_d,
        phi_yx=phi_yx, phi_c=phi_c, phi_inc=phi_inc,
    )
    if n == 5:
        d2_unc, c2_eff_unc = d2_5, c2_eff_5
    else:
        d2_unc = [0.0] * 64
        d2_unc[0] = 1.0 - c2_univ_unc
        sub5 = [d2_5[m] / c2_univ_unc for m in range(32)]
        sub5[0] = max(0.0, (d2_5[0] - (1.0 - c2_univ_unc)) / c2_univ_unc)
        coupled2 = frechet_couple(sub5, z_h2_eff / c2_univ_unc, phi_z_h2, lambda m: (m & 15) != 0)
        for k in range(64):
            d2_unc[k] += c2_univ_unc * coupled2[k]
        c2_eff_unc = max(c2_eff_5, 1.0 - d2_unc[0])

    if coated_overlay_active:
        # Always construct the full (B_COAT, Y_COAT) joint overlay so single-pair evaluations
        # (coated_y_only / coated_b_only) are EXACT marginal projections of the joint coated law!
        d2 = couple_coated_overlay_2arm(d2_unc, 1, 3, delta_b_h2, delta_y_h2, delta_c2_univ, phi_c, n)
        c2_eff = 1.0 - d2[0]
    else:
        d2 = d2_unc
        c2_eff = c2_eff_unc

    # H3: Exposure-specific! Uncoated paths get IIP-0064 C (drug-free GATE-42 scope);
    # coated paths (B_COAT, Y_COAT) stay strictly at Wave-6 baseline H3 unless non-primary sensitivity flag set!
    def _build_d3_n(h3_vec: Sequence[float], c3_cap: float) -> tuple[list[float], float]:
        d3_5_l, c3_5_l = build_h3_5arm(
            h3_vec[0], h3_vec[1], h3_vec[2], h3_vec[3], h3_vec[4],
            c3=c3_cap, phi_yx=phi_yx, phi_c=phi_c, phi_inc=phi_inc,
        )
        if n == 5:
            return d3_5_l, c3_5_l
        d3_6 = [0.0] * 64
        d3_6[0] = 1.0 - c3_cap
        sub5_l = [d3_5_l[m] / c3_cap for m in range(32)]
        sub5_l[0] = max(0.0, (d3_5_l[0] - (1.0 - c3_cap)) / c3_cap)
        coupled3_l = frechet_couple(sub5_l, h3_vec[5] / c3_cap, phi_z_h3, lambda m: (m & 8) != 0)
        for k in range(64):
            d3_6[k] += c3_cap * coupled3_l[k]
        return d3_6, c3_cap

    d3_unc, c3_eff = _build_d3_n([a[2] for a in arms_uncoated], c3_base)
    if coated_overlay_active and (not allow_c_on_coated_paths) and arms_h3_coated_base is not None and c3_coated_base is not None:
        d3_coat_base, _ = _build_d3_n(arms_h3_coated_base, float(c3_coated_base))
        d3 = couple_h3_uncoated_c_vs_coated_base(d3_coat_base, d3_unc, 1, 3, n)
    else:
        d3 = d3_unc

    # H4: Exact Wave-6 uncoated law (100% invariant!) + optional monotonic (n+2)-bit coated overlay!
    c4_r4_use = c4_r4_cf_lifted if (include_r4_vehicle_gated_cf and c4_r4_cf_lifted is not None) else c4_r4
    c4_univ_use = c4_univ_cf_lifted if (include_r4_vehicle_gated_cf and c4_univ_cf_lifted is not None) else c4_univ_unc
    arms_h4_eval = list(arms_uncoated)
    if n == 6 and (include_z_r3p_sensitivity or include_r4_vehicle_gated_cf):
        arms_h4_eval[5] = (
            arms_h4_eval[5][0],
            z_h2_eff,
            arms_h4_eval[5][2],
            arms_h4_eval[5][3] + (z_h4_sens_lift if (include_z_r3p_sensitivity and c4_r4 is None) else 0.0),
        )

    d4_unc = [0.0] * (1 << n)
    d4_unc[0] = 1.0 - c4_univ_use
    if c4_r4_use is None:
        sh4 = biv_bern(c4_r2_unc / c4_univ_use, c4_r3p_unc / c4_univ_use, phi_c)
        sh_items = [((sp, s3, 0), ws) for (sp, s3), ws in sh4.items()]
        c4_eff_unc = c4_univ_use * (1.0 - sh4[(0, 0)])
    else:
        biv_sub = biv_bern(c4_r2_unc / c4_univ_use, c4_r3p_unc / c4_univ_use, phi_c)
        d_sub = [biv_sub[(0, 0)], biv_sub[(1, 0)], biv_sub[(0, 1)], biv_sub[(1, 1)]]
        sh4_l = frechet_couple(d_sub, c4_r4_use / c4_univ_use, phi_r4, lambda m: m != 0)
        sh_items = [(((sm >> 0) & 1, (sm >> 1) & 1, (sm >> 2) & 1), ws) for sm, ws in enumerate(sh4_l)]
        c4_eff_unc = c4_univ_use * (1.0 - sh4_l[0])

    fj_r1 = frechet_joint([arms_h4_eval[0][3] / c4_r1, arms_h4_eval[2][3] / c4_r1], 1.0)
    r1_ev = [((1 if (bm & 1) else 0) | (4 if (bm & 2) else 0), pr) for bm, pr in enumerate(fj_r1) if pr > 0.0]
    p_b_in_r2u = arms_h4_eval[1][3] / c4_r2_unc
    ev12_on: list[tuple[int, float]] = []
    for m_r1, w_r1 in r1_ev:
        ev12_on.append((m_r1 | 2, w_r1 * p_b_in_r2u))
        ev12_on.append((m_r1, w_r1 * (1.0 - p_b_in_r2u)))

    if c4_r4_use is None:
        r3_idxs = [3, 4] + ([5] if n == 6 else [])
        fj3 = frechet_joint([arms_h4_eval[i][3] / c4_r3p_unc for i in r3_idxs], 1.0)
        ev3_on = [(sum((1 << r3_idxs[k]) for k in range(len(r3_idxs)) if (bm >> k) & 1), pr) for bm, pr in enumerate(fj3) if pr > 0.0]
        ev4_on = [(0, 1.0)]
    else:
        p_y_in_r3u = arms_h4_eval[3][3] / c4_r3p_unc
        ev3_on = [(0, 1.0 - p_y_in_r3u), (8, p_y_in_r3u)]
        r4_idxs = [4] + ([5] if n == 6 else [])
        fj4 = frechet_joint([arms_h4_eval[i][3] / c4_r4_use for i in r4_idxs], 1.0)
        ev4_on = [(sum((1 << r4_idxs[k]) for k in range(len(r4_idxs)) if (bm >> k) & 1), pr) for bm, pr in enumerate(fj4) if pr > 0.0]

    for (sp, s3, s4), ws in sh_items:
        wt = c4_univ_use * ws
        if wt == 0.0:
            continue
        e12 = ev12_on if sp else [(0, 1.0)]
        e3 = ev3_on if s3 else [(0, 1.0)]
        e4 = ev4_on if (c4_r4_use is not None and s4) else [(0, 1.0)]
        for m12, w12 in e12:
            for m3, w3 in e3:
                for m4, w4 in e4:
                    d4_unc[m12 | m3 | m4] += wt * w12 * w3 * w4

    if coated_overlay_active:
        d4 = couple_coated_overlay_2arm(d4_unc, 1, 3, delta_b_h4, delta_y_h4, delta_c4_univ, phi_c, n)
        c4_eff = 1.0 - d4[0]
        # Build exact zero-spillover compatibility map:
        # Uncoated arms 0..n-1 ONLY match uncoated routes; COAT_B_ONLY matches ONLY R2_COAT; COAT_Y_ONLY matches ONLY R3P_COAT!
        r_base = (("R1", "ADV_UNC", "R1", "R3P_UNC", "R4", "R4") if c4_r4_use is not None else ("R1", "ADV_UNC", "R1", "R3P_UNC", "R3P_UNC", "R3P_UNC"))[:n]
        routes_vec = r_base + ("ADV_COAT", "R3P_COAT")
        a_routes = frozenset({"R1"}) if (coated_b_active and design_a_r1_only_when_coated) else frozenset({"R1", "ADV_UNC"})
        yd_unc_cls = "STAGED_HARDENED_UNC" if c1_pass else "STAGED_BASE_UNC"
        cell_classes = ("INC_A_DRUGFREE", "INC_UNC", "INC_UNC", yd_unc_cls, yd_unc_cls, "Z_UNC")[:n] + ("COAT_B_ONLY", "COAT_Y_ONLY")
        compat_map: dict[str, FrozenSet[str]] = {
            "INC_A_DRUGFREE": a_routes,
            "INC_UNC": frozenset({"R1", "ADV_UNC"}),
            "STAGED_HARDENED_UNC": frozenset({"R3P_UNC"}) | r4_set,
            "STAGED_BASE_UNC": frozenset({"R3P_UNC"}),
            "Z_UNC": (frozenset({"R3P_UNC", "R3P_COAT"}) if include_z_r3p_sensitivity else frozenset({"R3P_UNC"})) | r4_set,
            "COAT_B_ONLY": frozenset({"ADV_COAT"}) if coated_b_active else frozenset(),
            "COAT_Y_ONLY": frozenset({"R3P_COAT"}) if coated_y_active else frozenset(),
        }
        coated_routes_set = frozenset({"ADV_COAT", "R3P_COAT"})
        elig_mask = ((1 << n) if coated_b_active else 0) | ((1 << (n + 1)) if coated_y_active else 0) | ((1 << 5) if (n == 6 and include_z_r3p_sensitivity) else 0)
    else:
        d4 = d4_unc
        c4_eff = c4_eff_unc
        routes_vec = (("R1", "R2", "R1", "R3P", "R4", "R4") if c4_r4_use is not None else ("R1", "R2", "R1", "R3P", "R3P", "R3P"))[:n]
        yd_cls = "STAGED_HARDENED" if c1_pass else "STAGED_BASE"
        cell_classes = ("INC", "INC", "INC", yd_cls, yd_cls, "Z_HARDENED")[:n]
        compat_map = {
            "INC": frozenset({"R1", "R2"}),
            "STAGED_HARDENED": frozenset({"R3P"}) | r4_set,
            "STAGED_BASE": frozenset({"R3P"}),
            "Z_HARDENED": frozenset({"R3P"}) | r4_set,
        }
        coated_routes_set = frozenset()
        elig_mask = 0

    require("R4" not in compat_map.get("INC", frozenset()), "GY-027(1): unhardened INC cannot use R4")
    require("R4" not in compat_map.get("INC_A_DRUGFREE", frozenset()), "GY-027(1): Design A cannot use R4")
    if coated_routes_set:
        require(
            not (compat_map.get(cell_classes[0], frozenset()) & coated_routes_set),
            "Physical firewall violation: Design A overlaps coated routes",
        )

    res = eval_exact_n_arm(
        arms_h4_eval, [d1, d2, d3, d4], [c1_eff, c2_eff, c3_eff, c4_eff], routes_vec, cell_classes, compat_map,
        coated_overlay_active=coated_overlay_active,
        coated_b_active=coated_b_active,
        coated_y_active=coated_y_active,
        coated_routes=coated_routes_set,
        coated_eligible_arm_mask=elig_mask,
        compute_strassen=compute_strassen,
        compute_h23_lp=compute_h23_lp,
    )
    return {"name": name, **res}


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 = [0.0] * 8
    d2[0] = 1.0 - c2
    fj2 = frechet_joint([a[1] / c2 for a in arms], 0.0)
    for k in range(8):
        d2[k] += c2 * fj2[k]
    d3 = [0.0] * 8
    d3[0] = 1.0 - c3
    fj3 = frechet_joint([a[2] / c3 for a in arms], 0.0)
    for k in range(8):
        d3[k] += c3 * fj3[k]
    d4 = [0.0] * 8
    d4[0] = 1.0 - c4
    u_ax = 0.69 / c4
    u_b = 0.70 / c4
    for m_ax, w_ax in ((0, 1.0 - u_ax), (5, u_ax)):
        for m_b, w_b in ((0, 1.0 - u_b), (2, u_b)):
            d4[m_ax | m_b] += c4 * w_ax * w_b
    d123: dict[int, float] = {}
    for m1, p1 in enumerate(d1):
        for m2, p2 in enumerate(d2):
            for m3, p3 in enumerate(d3):
                m = m1 & m2 & m3
                if m and p1 * p2 * p3 > 0.0:
                    d123[m] = d123.get(m, 0.0) + p1 * p2 * p3
    p_locked = sum(p123 * p4 for m123, p123 in d123.items() for m4, p4 in enumerate(d4) if (m123 & m4))
    p_mod = sum(p123 * p4 for m123, p123 in d123.items() for m4, p4 in enumerate(d4) if m4 != 0)
    return {
        "name": "L0_core_3arm",
        "locked_exact": p_locked * 100.0,
        "modular_exact": p_mod * 100.0,
        "locked_pct": round(p_locked * 100.0, 4),
        "modular_pct": round(p_mod * 100.0, 4),
    }


def _tier_params(tier: str) -> dict[str, float]:
    table = {
        "LOW": {
            "da_h4": 0.020, "da_c4r": 0.020, "da_c4u": 0.015 * SCALE_C4_UNIV,
            "db_b2": 0.0025, "db_y2": 0.005, "db_b4": 0.005, "db_y4": 0.010,
            "db_c2": 0.010, "db_c2u": 0.003, "db_c4r": 0.010, "db_c4u": 0.008 * SCALE_C4_UNIV,
            "dc_abx": 0.008 * SCALE_C3_BASE, "dc_ydz": 0.005 * SCALE_C3_BASE, "dc_c3": 0.005 * SCALE_C3_BASE,
        },
        "HIGH": {
            "da_h4": 0.035, "da_c4r": 0.035, "da_c4u": 0.025 * SCALE_C4_UNIV,
            "db_b2": 0.005, "db_y2": 0.010, "db_b4": 0.010, "db_y4": 0.020,
            "db_c2": 0.020, "db_c2u": 0.006, "db_c4r": 0.020, "db_c4u": 0.015 * SCALE_C4_UNIV,
            "dc_abx": 0.018 * SCALE_C3_BASE, "dc_ydz": 0.011 * SCALE_C3_BASE, "dc_c3": 0.012 * SCALE_C3_BASE,
        },
    }
    if tier in table:
        return table[tier]
    require(tier == "CENTRAL", f"Unknown tier: {tier}")
    return {k: 0.5 * (table["LOW"][k] + table["HIGH"][k]) for k in table["LOW"]}


def _decorate_delta(
    res: dict[str, Any],
    ref: dict[str, Any],
    *,
    firewall_ref: Optional[dict[str, Any]] = None,
    verify_zero_uncoated_spillover: bool = False,
) -> dict[str, Any]:
    out = dict(res)
    out["delta_modular_vs_wave6_exact_pp"] = res["modular_exact"] - ref["modular_exact"]
    out["delta_modular_vs_wave6_pct_pp"] = round(out["delta_modular_vs_wave6_exact_pp"], 4)
    out["delta_locked_vs_wave6_exact_pp"] = res["locked_exact"] - ref["locked_exact"]
    out["delta_locked_vs_wave6_pct_pp"] = round(out["delta_locked_vs_wave6_exact_pp"], 4)
    if firewall_ref is not None:
        for h in range(4):
            require(
                abs(res["design_a_4_marginals_exact"][h] - firewall_ref["design_a_4_marginals_exact"][h]) <= 1e-12,
                f"Design-A H{h+1} marginal firewall breach in {res['name']}",
            )
        require(
            abs(res["design_a_standalone_exact"] - firewall_ref["design_a_standalone_exact"]) <= 1e-12,
            f"Design-A standalone firewall breach in {res['name']}",
        )
        for c in range(4):
            require(
                abs(res["design_a_d_h2_joint_4cell_exact"][c] - firewall_ref["design_a_d_h2_joint_4cell_exact"][c]) <= 1e-12,
                f"Design-(A,D) H2 4-cell firewall breach in {res['name']}",
            )
        require(res["design_a_only_coated_route_modular_mass_pp"] == 0.0, "Design-A coated-route modular leak")
        require(res["non_eligible_product_coated_route_modular_leak_pp"] == 0.0, "Non-eligible product coated-route modular leak")
        out["design_a_firewall_verified"] = True
        if verify_zero_uncoated_spillover:
            xdz_diff = abs(res["uncoated_xdz_only_modular_exact"] - firewall_ref["uncoated_xdz_only_modular_exact"])
            br1_diff = abs(res["uncoated_b_r1_marginal_exact"] - firewall_ref["uncoated_b_r1_marginal_exact"])
            r14_diff = abs(res["uncoated_r1_and_r4_joint_exact"] - firewall_ref["uncoated_r1_and_r4_joint_exact"])
            require(xdz_diff <= 1e-11, f"Uncoated X/D/Z spillover in {res['name']}: {xdz_diff}")
            require(br1_diff <= 1e-11, f"Uncoated B/R1 spillover in {res['name']}: {br1_diff}")
            require(r14_diff <= 1e-11, f"Uncoated R1&R4 spillover in {res['name']}: {r14_diff}")
            out["uncoated_xdz_spillover_pp"] = 0.0
            out["uncoated_b_r1_spillover_pp"] = 0.0
            out["uncoated_r1_and_r4_drift_pp"] = 0.0
    return out


def _eval_wave7_in_wave6_state(
    name: str,
    *,
    c1_pass: bool = True,
    c2_pass: bool = True,
    c3_level: str = "full",
    c4_pass: bool = True,
    a_on: bool = False,
    b_on: bool = False,
    c_on: bool = False,
    coated_b_only: bool = False,
    coated_y_only: bool = False,
    tier: str = "CENTRAL",
    ceiling_lift: bool = True,
    allow_h2_ceiling_lift: bool = True,
    phi_c: float = 0.25,
    phi_inc_override: Optional[float] = None,
    omega_h4: float = 0.50,
    design_b_tyk2_discount: float = 0.0,
    freeze_a_on_c: bool = True,
    design_a_r1_only_when_coated: bool = True,
    include_r4_vehicle_gated: bool = False,
    include_z_r3p_sensitivity: bool = False,
    allow_c_on_coated_paths: bool = False,
    compute_strassen: bool = True,
    compute_h23_lp: bool = False,
) -> dict[str, Any]:
    """True Zero-Spillover Wave-6 x Wave-7 state evaluator isolating coated B/R2 & Y/R3P in BOTH H2 and H4."""
    require(c3_level in ("none", "partial", "full"), f"Bad c3_level={c3_level}")
    require(not (coated_b_only and coated_y_only), "Cannot set both coated_b_only and coated_y_only")
    p = _tier_params(tier)
    b_mult = 1.0 - design_b_tyk2_discount
    require(0.0 <= b_mult <= 1.0, f"Invalid design_b_tyk2_discount={design_b_tyk2_discount}")

    r4_active = c2_pass and c1_pass
    z_active = c4_pass and c1_pass
    n_arms = 6 if z_active else 5
    phi_inc = phi_inc_override if phi_inc_override is not None else (0.25 if c1_pass else 0.50)

    d_h1 = 0.78 if c1_pass else 0.62
    a_h2 = 0.78
    b_h2 = 0.80 if c1_pass else 0.79
    x_h2 = 0.83 if c1_pass else 0.82
    y_h2 = 0.85 if c1_pass else 0.84
    d_h2 = 0.92
    z_h2 = 0.83

    a_h3 = 0.57
    if c3_level == "none":
        base_c3 = 0.890
        b_h3, x_h3, y_h3 = 0.64, 0.73, 0.80
        d_h3 = 0.68 if c1_pass else 0.70
        z_h3 = 0.76
    elif c3_level == "partial":
        base_c3 = 0.930
        b_h3, x_h3, y_h3 = 0.70, 0.78, 0.83
        d_h3 = 0.74 if c1_pass else 0.75
        z_h3 = 0.79
    else:
        base_c3 = 0.942
        b_h3, x_h3, y_h3 = 0.73, 0.80, 0.85
        d_h3 = 0.78 if c1_pass else 0.77
        z_h3 = 0.82

    a_h4 = 0.69
    b_h4 = 0.70
    x_h4 = 0.69
    y_h4 = 0.72
    d_h4 = 0.80 if r4_active else 0.70
    z_h4 = 0.80 if r4_active else 0.72
    base_c4_univ = 0.950 if r4_active else 0.920

    state_c4u_scale = (1.0 - base_c4_univ) / (1.0 - 0.920)
    state_c3_scale = (1.0 - base_c3) / (1.0 - 0.925)

    da_h4 = p["da_h4"] if a_on else 0.0
    da_c4r = p["da_c4r"] if (a_on and ceiling_lift) else 0.0
    da_c4u = ((p["da_c4u"] / SCALE_C4_UNIV) * state_c4u_scale) if (a_on and ceiling_lift) else 0.0

    db_b2 = p["db_b2"] * b_mult if b_on else 0.0
    db_y2 = p["db_y2"] if b_on else 0.0
    db_b4 = p["db_b4"] * b_mult if b_on else 0.0
    db_y4 = p["db_y4"] if b_on else 0.0
    db_c2u = p["db_c2u"] if (b_on and ceiling_lift and allow_h2_ceiling_lift) else 0.0
    db_c4r = p["db_c4r"] if (b_on and ceiling_lift) else 0.0
    db_c4u = ((p["db_c4u"] / SCALE_C4_UNIV) * state_c4u_scale) if (b_on and ceiling_lift) else 0.0

    dc_abx_eff = ((p["dc_abx"] / SCALE_C3_BASE) * state_c3_scale) if c_on else 0.0
    dc_ydz_eff = ((p["dc_ydz"] / SCALE_C3_BASE) * state_c3_scale) if c_on else 0.0
    dc_a = 0.0 if freeze_a_on_c else dc_abx_eff
    dc_c3 = ((p["dc_c3"] / SCALE_C3_BASE) * state_c3_scale) if (c_on and ceiling_lift) else 0.0

    b4_coat = subadditive_overlap(b_h4, da_h4, db_b4, omega_h4)
    y4_coat = subadditive_overlap(y_h4, da_h4, db_y4, omega_h4)
    c4_univ_coat = subadditive_overlap(base_c4_univ, da_c4u, db_c4u, omega_h4)

    coating_active = a_on or b_on
    coated_b_active = coating_active and (not coated_y_only)
    coated_y_active = coating_active and (not coated_b_only)

    # Non-primary R4 counterfactual lifts D & Z on R4 explicitly (never used in primary headline!)
    d_h4_in = subadditive_overlap(d_h4, da_h4, db_y4, omega_h4) if (include_r4_vehicle_gated and r4_active) else d_h4
    z_h4_in = subadditive_overlap(z_h4, da_h4, db_y4, omega_h4) if (include_r4_vehicle_gated and r4_active) else z_h4
    r4_scale = (1.0 - 0.870) / (1.0 - 0.850)
    c4_r4_cf = subadditive_overlap(0.870, da_c4r * r4_scale, db_c4r * r4_scale, omega_h4) if (include_r4_vehicle_gated and r4_active) else None
    z_h4_sens = (y4_coat - y_h4) if (include_z_r3p_sensitivity and not r4_active) else 0.0
    z_h2_sens = db_y2 if ((include_z_r3p_sensitivity and not r4_active) or (include_r4_vehicle_gated and r4_active)) else 0.0

    arms_uncoated: list[tuple[float, float, float, float]] = [
        (0.88, a_h2, a_h3 + dc_a, a_h4),
        (0.88, b_h2, b_h3 + dc_abx_eff, b_h4),
        (0.88, x_h2, x_h3 + dc_abx_eff, x_h4),
        (0.88, y_h2, y_h3 + dc_ydz_eff, y_h4),
        (d_h1, d_h2, d_h3 + dc_ydz_eff, d_h4_in),
    ]
    arms_h3_base: list[float] = [a_h3, b_h3, x_h3, y_h3, d_h3]
    if z_active:
        arms_uncoated.append((0.84, z_h2, z_h3 + dc_ydz_eff, z_h4_in))
        arms_h3_base.append(z_h3)

    return eval_wave7_portfolio(
        name,
        arms_uncoated,
        c1_allo=0.88,
        c1_univ=0.925 if z_active else None,
        c1_z=0.84 if z_active else None,
        c2_a=0.87,
        c2_bx_unc=0.87,
        c2_y_unc=0.87,
        c2_d=0.93,
        c2_univ_unc=0.95,
        c3_base=base_c3 + dc_c3,
        c4_univ_unc=base_c4_univ,
        c4_r1=0.850,
        c4_r2_unc=0.850,
        c4_r3p_unc=0.850,
        c4_r4=0.870 if r4_active else None,
        coated_overlay_active=coating_active,
        coated_b_active=coated_b_active,
        coated_y_active=coated_y_active,
        delta_b_h2=db_b2,
        delta_y_h2=db_y2,
        delta_c2_univ=db_c2u,
        delta_b_h4=b4_coat - b_h4,
        delta_y_h4=y4_coat - y_h4,
        delta_c4_univ=c4_univ_coat - base_c4_univ,
        arms_h3_coated_base=arms_h3_base,
        c3_coated_base=base_c3,
        allow_c_on_coated_paths=allow_c_on_coated_paths,
        include_r4_vehicle_gated_cf=include_r4_vehicle_gated and r4_active,
        c4_r4_cf_lifted=c4_r4_cf,
        c4_univ_cf_lifted=c4_univ_coat if (include_r4_vehicle_gated and r4_active) else None,
        include_z_r3p_sensitivity=include_z_r3p_sensitivity and (not r4_active),
        z_h2_sens_lift=z_h2_sens,
        z_h4_sens_lift=z_h4_sens,
        phi_r4=0.30,
        phi_c=phi_c,
        phi_inc=phi_inc,
        c1_pass=c1_pass,
        design_a_r1_only_when_coated=design_a_r1_only_when_coated,
        compute_strassen=compute_strassen,
        compute_h23_lp=compute_h23_lp,
    )


def build_wave7_crosswalk(
    wave6_contract_path: Optional[Path] = None,
    cellgemma_receipt_path: Optional[Path] = None,
) -> dict[str, Any]:
    w6_contract = load_strict_json(wave6_contract_path.read_text(encoding="utf-8"), wave6_contract_path.name) if wave6_contract_path else None
    cg_receipt = load_strict_json(cellgemma_receipt_path.read_text(encoding="utf-8"), cellgemma_receipt_path.name) if cellgemma_receipt_path else None

    w6_sha = sha256_bytes(wave6_contract_path.read_bytes()) if wave6_contract_path else None
    cg_file_sha = sha256_bytes(cellgemma_receipt_path.read_bytes()) if cellgemma_receipt_path else None
    cg_payload_sha = cg_receipt["portable_payload_sha256"] if cg_receipt else None

    if cg_receipt is not None:
        require(cg_payload_sha == "ba72c6eb81f29be7ab1f0b2ef17ca6397eb342f1a2788913475919f48f89e2ab", f"CellGemma receipt payload SHA drift: {cg_payload_sha}")
        require(cg_receipt["evidence_tier"] == "cellgemma_e4b_in_silico_prior", "Unexpected CellGemma evidence tier")
        require(cg_receipt["live_headline_delta_pp_today"] == 0.0, "Non-zero live delta in CellGemma receipt")

    # 1. Exact Shipped Baselines + 24/24 Wave-6 State Parity Audit
    l0 = eval_core_3arm_l0()
    require(abs(l0["modular_exact"] - PINNED_WAVE6_EXACT["L0_core_3arm_modular"]) <= 1e-11, "L0 modular parity drift")
    require(abs(l0["locked_exact"] - PINNED_WAVE6_EXACT["L0_core_3arm_locked"]) <= 1e-11, "L0 locked parity drift")

    w6_5 = _eval_wave7_in_wave6_state("Wave6_5Arm_Central", c4_pass=False, compute_strassen=True)
    require(abs(w6_5["modular_exact"] - PINNED_WAVE6_EXACT["Wave6_5Arm_Central_modular"]) <= 1e-11, "Wave-6 5-arm modular drift")
    require(abs(w6_5["locked_exact"] - PINNED_WAVE6_EXACT["Wave6_5Arm_Central_locked"]) <= 1e-11, "Wave-6 5-arm locked drift")

    w6_6 = _eval_wave7_in_wave6_state("Wave6_6Arm_Central", compute_strassen=True, compute_h23_lp=True)
    require(abs(w6_6["modular_exact"] - PINNED_WAVE6_EXACT["Wave6_6Arm_Central_modular"]) <= 1e-11, "Wave-6 6-arm modular drift")
    require(abs(w6_6["locked_exact"] - PINNED_WAVE6_EXACT["Wave6_6Arm_Central_locked"]) <= 1e-11, "Wave-6 6-arm locked drift")
    require(abs(w6_6["ceiling_exact"] - PINNED_WAVE6_EXACT["Wave6_6Arm_Central_ceiling"]) <= 1e-11, "Wave-6 6-arm ceiling drift")

    if w6_contract is not None:
        m6_c = w6_contract["reachable_scenarios"]["Wave6_6Arm_Central_EnSC_H1_88_LOCKED"]
        require(abs(w6_6["modular_exact"] - m6_c["modular_exact"]) <= 1e-11, "Live wave6_master_contract modular mismatch")
        require(abs(w6_6["locked_exact"] - m6_c["locked_exact"]) <= 1e-11, "Live wave6_master_contract locked mismatch")

    # 2. Primary Wave-7 6-Arm Scenarios (phi_c = 0.25 central & phi_c = 0.50 stress)
    primary_6arm: dict[str, Any] = {}
    for phi_tag, phi_val in [("phi_0p25_central", 0.25), ("phi_0p50_harsh_stress", 0.50)]:
        ref_row = w6_6 if phi_val == 0.25 else _eval_wave7_in_wave6_state(
            f"WAVE6_6ARM_BASE_{phi_tag}", phi_c=phi_val, phi_inc_override=phi_val, compute_strassen=True,
        )
        block: dict[str, Any] = {"WAVE6_6ARM_BASELINE": _decorate_delta(ref_row, ref_row, firewall_ref=ref_row, verify_zero_uncoated_spillover=True)}
        for sc_name, flags in [
            ("IIP0062_A_PIRFENIDONE", (True, False, False)),
            ("IIP0063_B_DEUCRAVACITINIB", (False, True, False)),
            ("IIP0064_C_GY032_CHANNEL_C", (False, False, True)),
            ("IIP0065_D_GUARDRAILS_PILOTS", (False, False, False)),
            ("COMBINED_ABC_OMEGA_0P50", (True, True, True)),
        ]:
            a_on, b_on, c_on = flags
            if sc_name == "IIP0065_D_GUARDRAILS_PILOTS":
                block[sc_name] = _decorate_delta(ref_row, ref_row, firewall_ref=ref_row, verify_zero_uncoated_spillover=True)
                continue
            for mode_tag, cl in [("CEIL_LIFT", True), ("FIXED_CEIL", False)]:
                for tier in ("LOW", "CENTRAL", "HIGH"):
                    key = f"{sc_name}_{mode_tag}_{tier}"
                    want_lp = (phi_tag == "phi_0p25_central" and sc_name == "COMBINED_ABC_OMEGA_0P50" and cl)
                    r = _eval_wave7_in_wave6_state(
                        key, a_on=a_on, b_on=b_on, c_on=c_on, tier=tier, ceiling_lift=cl,
                        phi_c=phi_val, phi_inc_override=phi_val, freeze_a_on_c=True,
                        compute_strassen=True, compute_h23_lp=want_lp,
                    )
                    # For pure coating scenarios (c_on=False), verify ZERO uncoated X/D/Z, B/R1, and R1&R4 spillover!
                    block[key] = _decorate_delta(r, ref_row, firewall_ref=ref_row, verify_zero_uncoated_spillover=(not c_on))
        primary_6arm[phi_tag] = block

    # 3. Audit Sensitivities (including Single-Coated-Pair Decomposition + Design-A R1-Only Segregation Accounting!)
    sens_single_pair: dict[str, Any] = {}
    for sc_lbl, a_on, b_on in [("IIP0062_A", True, False), ("IIP0063_B", False, True), ("COMBINED_AB", True, True)]:
        r_y = _eval_wave7_in_wave6_state(f"{sc_lbl}_Y_R3P_ONLY_CENTRAL", a_on=a_on, b_on=b_on, coated_y_only=True, tier="CENTRAL", ceiling_lift=True)
        r_b = _eval_wave7_in_wave6_state(f"{sc_lbl}_B_R2_ONLY_CENTRAL", a_on=a_on, b_on=b_on, coated_b_only=True, tier="CENTRAL", ceiling_lift=True)
        r_both = _eval_wave7_in_wave6_state(f"{sc_lbl}_BOTH_BY_CENTRAL", a_on=a_on, b_on=b_on, tier="CENTRAL", ceiling_lift=True)
        r_both_r2u = _eval_wave7_in_wave6_state(f"{sc_lbl}_BOTH_BY_A_KEEP_R2UNC", a_on=a_on, b_on=b_on, tier="CENTRAL", ceiling_lift=True, design_a_r1_only_when_coated=False)
        sens_single_pair[sc_lbl] = {
            "y_r3p_coated_only": _decorate_delta(r_y, w6_6, firewall_ref=w6_6, verify_zero_uncoated_spillover=True),
            "b_r2_coated_only": _decorate_delta(r_b, w6_6, firewall_ref=w6_6, verify_zero_uncoated_spillover=True),
            "both_y_r3p_and_b_r2": _decorate_delta(r_both, w6_6, firewall_ref=w6_6, verify_zero_uncoated_spillover=True),
            "design_a_r1_only_segregation_cost_pp": round(r_both["modular_exact"] - r_both_r2u["modular_exact"], 4),
        }

    sens_h2_held: dict[str, Any] = {}
    for tier in ("LOW", "CENTRAL", "HIGH"):
        rb_h2 = _eval_wave7_in_wave6_state(f"SENS_B_H2_CEIL_HELD_{tier}", b_on=True, tier=tier, ceiling_lift=True, allow_h2_ceiling_lift=False)
        rabc_h2 = _eval_wave7_in_wave6_state(f"SENS_ABC_H2_CEIL_HELD_{tier}", a_on=True, b_on=True, c_on=True, tier=tier, ceiling_lift=True, allow_h2_ceiling_lift=False)
        sens_h2_held[f"IIP0063_B_{tier}"] = _decorate_delta(rb_h2, w6_6, firewall_ref=w6_6, verify_zero_uncoated_spillover=True)
        sens_h2_held[f"COMBINED_ABC_{tier}"] = _decorate_delta(rabc_h2, w6_6, firewall_ref=w6_6)

    sens_c_incl_a: dict[str, Any] = {}
    for tier in ("LOW", "CENTRAL", "HIGH"):
        rc = _eval_wave7_in_wave6_state(f"SENS_C_INCL_A_{tier}", c_on=True, tier=tier, ceiling_lift=True, freeze_a_on_c=False)
        rabc = _eval_wave7_in_wave6_state(f"SENS_ABC_INCL_A_{tier}", a_on=True, b_on=True, c_on=True, tier=tier, ceiling_lift=True, freeze_a_on_c=False)
        sens_c_incl_a[f"IIP0064_C_CL_{tier}"] = _decorate_delta(rc, w6_6)
        sens_c_incl_a[f"COMBINED_ABC_CL_{tier}"] = _decorate_delta(rabc, w6_6)

    w6_r4_off = _eval_wave7_in_wave6_state("WAVE6_R4_INACTIVE_BASE", c2_pass=False, compute_strassen=False)
    sens_r3p_direct: dict[str, Any] = {"BASELINE_R4_INACTIVE": _decorate_delta(w6_r4_off, w6_r4_off, firewall_ref=w6_r4_off)}
    for tier in ("LOW", "CENTRAL", "HIGH"):
        r = _eval_wave7_in_wave6_state(
            f"SENS_R3P_DIRECT_ARMZ_{tier}", c2_pass=False, a_on=True, b_on=True, c_on=True,
            tier=tier, ceiling_lift=True, include_z_r3p_sensitivity=True, compute_strassen=False,
        )
        sens_r3p_direct[f"COMBINED_ABC_CL_{tier}"] = _decorate_delta(r, w6_r4_off, firewall_ref=w6_r4_off)

    # Verify exact 0.000000 pp IIP-0064 (C) spillover onto coated B_COAT/R2_COAT and Y_COAT/R3P_COAT paths!
    ab_ref_c = sens_single_pair["COMBINED_AB"]["both_y_r3p_and_b_r2"]
    abc_prim_c = primary_6arm["phi_0p25_central"]["COMBINED_ABC_OMEGA_0P50_CEIL_LIFT_CENTRAL"]
    c_to_coated_drift = abs(abc_prim_c["coated_only_by_modular_exact"] - ab_ref_c["coated_only_by_modular_exact"])
    require(c_to_coated_drift <= 1e-12, f"IIP-0064 C H3 spillover onto coated B/Y paths detected: {c_to_coated_drift}")

    sens_c_on_coated_cf: dict[str, Any] = {"scope_warning": "UNVERIFIED_COATED_H3_COUNTERFACTUAL_NOT_IN_PRIMARY_HEADLINE"}
    for tier in ("LOW", "CENTRAL", "HIGH"):
        r_cc = _eval_wave7_in_wave6_state(
            f"SENS_C_ON_COATED_CF_{tier}", a_on=True, b_on=True, c_on=True,
            tier=tier, ceiling_lift=True, allow_c_on_coated_paths=True, compute_strassen=False,
        )
        sens_c_on_coated_cf[f"COMBINED_ABC_CL_{tier}"] = _decorate_delta(r_cc, w6_6, firewall_ref=w6_6)

    sens_r4_cf: dict[str, Any] = {"scope_warning": "VEHICLE_GATED_COUNTERFACTUAL_NOT_IN_PRIMARY_HEADLINE"}
    for tier in ("LOW", "CENTRAL", "HIGH"):
        r = _eval_wave7_in_wave6_state(
            f"SENS_R4_VEHICLE_GATED_CF_{tier}", a_on=True, b_on=True, c_on=True,
            tier=tier, ceiling_lift=True, include_r4_vehicle_gated=True, compute_strassen=False,
        )
        sens_r4_cf[f"COMBINED_ABC_CL_{tier}"] = _decorate_delta(r, w6_6, firewall_ref=w6_6)

    sens_5arm: dict[str, Any] = {"WAVE6_5ARM_BASELINE": _decorate_delta(w6_5, w6_5, firewall_ref=w6_5)}
    for tier in ("LOW", "CENTRAL", "HIGH"):
        r_cl = _eval_wave7_in_wave6_state(f"W7_5ARM_ABC_CL_{tier}", c4_pass=False, a_on=True, b_on=True, c_on=True, tier=tier, ceiling_lift=True, compute_strassen=False)
        r_fc = _eval_wave7_in_wave6_state(f"W7_5ARM_ABC_FC_{tier}", c4_pass=False, a_on=True, b_on=True, c_on=True, tier=tier, ceiling_lift=False, compute_strassen=False)
        sens_5arm[f"COMBINED_ABC_CEIL_LIFT_{tier}"] = _decorate_delta(r_cl, w6_5, firewall_ref=w6_5)
        sens_5arm[f"COMBINED_ABC_FIXED_CEIL_{tier}"] = _decorate_delta(r_fc, w6_5, firewall_ref=w6_5)

    sens_omega: dict[str, Any] = {}
    for phi_tag, phi_val in [("phi_0p25_central", 0.25), ("phi_0p50_harsh_stress", 0.50)]:
        ref_r = primary_6arm[phi_tag]["WAVE6_6ARM_BASELINE"]
        om_blk: dict[str, Any] = {}
        for om in (0.0, 0.25, 0.5, 0.75, 1.0):
            for tier in ("LOW", "CENTRAL", "HIGH"):
                key = f"omega_{str(om).replace('.', 'p')}_{tier}"
                r = _eval_wave7_in_wave6_state(
                    key, a_on=True, b_on=True, c_on=True, tier=tier, ceiling_lift=True,
                    phi_c=phi_val, phi_inc_override=phi_val, omega_h4=om, compute_strassen=True,
                )
                om_blk[key] = _decorate_delta(r, ref_r, firewall_ref=ref_r)
        sens_omega[phi_tag] = om_blk

    sens_b_disc: dict[str, Any] = {}
    for disc, d_tag in [(0.0, "discount_0pct_B2_base_WT_TYK2"), (0.5, "discount_50pct_partial_overlap"), (1.0, "discount_100pct_full_redundancy")]:
        for tier in ("LOW", "CENTRAL", "HIGH"):
            key = f"{d_tag}_{tier}"
            r = _eval_wave7_in_wave6_state(key, b_on=True, tier=tier, ceiling_lift=True, design_b_tyk2_discount=disc, compute_strassen=False)
            sens_b_disc[key] = _decorate_delta(r, w6_6, firewall_ref=w6_6, verify_zero_uncoated_spillover=True)

    # 4. Exact 192-State Pre-Wet-Lab Scenario Average (24 Wave-6 states x 8 Wave-7 (A, B, C) states, Z strictly uncoated!)
    base_24_cache: dict[tuple[bool, bool, str, bool], dict[str, Any]] = {}
    state_192_cache: dict[tuple[bool, bool, str, bool, bool, bool, bool], dict[str, Any]] = {}
    for c1_p in (False, True):
        for c2_p in (False, True):
            for c3_lvl in ("none", "partial", "full"):
                for c4_p in (False, True):
                    b_st = _eval_wave7_in_wave6_state(
                        f"W6_{int(c1_p)}{int(c2_p)}_{c3_lvl}_{int(c4_p)}",
                        c1_pass=c1_p, c2_pass=c2_p, c3_level=c3_lvl, c4_pass=c4_p,
                        compute_strassen=False,
                    )
                    base_24_cache[(c1_p, c2_p, c3_lvl, c4_p)] = b_st
                    for a_p in (False, True):
                        for b_p in (False, True):
                            for c_p in (False, True):
                                if not (a_p or b_p or c_p):
                                    st = b_st
                                else:
                                    st = _eval_wave7_in_wave6_state(
                                        f"W7_{int(c1_p)}{int(c2_p)}_{c3_lvl}_{int(c4_p)}_{int(a_p)}{int(b_p)}{int(c_p)}",
                                        c1_pass=c1_p, c2_pass=c2_p, c3_level=c3_lvl, c4_pass=c4_p,
                                        a_on=a_p, b_on=b_p, c_on=c_p,
                                        tier="CENTRAL", ceiling_lift=True,
                                        include_z_r3p_sensitivity=False,
                                        compute_strassen=False,
                                    )
                                state_192_cache[(c1_p, c2_p, c3_lvl, c4_p, a_p, b_p, c_p)] = st

    if w6_contract is not None:
        w6_states_map = w6_contract["states_24"]
        require(len(w6_states_map) == 24, "Expected 24 Wave-6 states")
        for (c1_p, c2_p, c3_lvl, c4_p), got_st in base_24_cache.items():
            sk = f"c1={int(c1_p)}|c2={int(c2_p)}|c3={c3_lvl}|c4={int(c4_p)}"
            require(sk in w6_states_map, f"Missing 24-state key {sk}")
            row = w6_states_map[sk]
            require(abs(got_st["modular_exact"] - row["modular_exact"]) <= 1e-11, f"24-state modular drift at {sk}")
            require(abs(got_st["locked_exact"] - row["locked_exact"]) <= 1e-11, f"24-state locked drift at {sk}")

    w6_priors = {
        "Conservative": {"c1": 0.35, "c2": 0.35, "c3": {"none": 0.60, "partial": 0.30, "full": 0.10}, "c4": 0.25, "w7": (0.25, 0.25, 0.35)},
        "Central": {"c1": 0.50, "c2": 0.50, "c3": {"none": 0.45, "partial": 0.415, "full": 0.135}, "c4": 0.40, "w7": (0.35, 0.35, 0.45)},
        "Upper": {"c1": 0.65, "c2": 0.65, "c3": {"none": 0.35, "partial": 0.48, "full": 0.17}, "c4": 0.55, "w7": (0.45, 0.45, 0.55)},
    }
    exact_192_avg: dict[str, Any] = {}
    for prof, pr in w6_priors.items():
        pa_p, pb_p, pc_p = pr["w7"]
        w6_mod_ev = w6_lck_ev = w7_mod_ev = w7_lck_ev = 0.0
        w7_mod_fpf = w7_mod_ffull = 0.0
        w_sum = 0.0
        for c1_p in (False, True):
            p1 = pr["c1"] if c1_p else (1.0 - pr["c1"])
            for c2_p in (False, True):
                p2 = pr["c2"] if c2_p else (1.0 - pr["c2"])
                for c3_lvl in ("none", "partial", "full"):
                    p3 = pr["c3"][c3_lvl]
                    for c4_p in (False, True):
                        p4 = pr["c4"] if c4_p else (1.0 - pr["c4"])
                        w24 = p1 * p2 * p3 * p4
                        b_st = base_24_cache[(c1_p, c2_p, c3_lvl, c4_p)]
                        w6_mod_ev += w24 * b_st["modular_exact"]
                        w6_lck_ev += w24 * b_st["locked_exact"]
                        for a_p in (False, True):
                            qa = pa_p if a_p else (1.0 - pa_p)
                            for b_p in (False, True):
                                qb = pb_p if b_p else (1.0 - pb_p)
                                for c_p in (False, True):
                                    qc = pc_p if c_p else (1.0 - pc_p)
                                    w192 = w24 * qa * qb * qc
                                    w_sum += w192
                                    st_ind = state_192_cache[(c1_p, c2_p, c3_lvl, c4_p, a_p, b_p, c_p)]
                                    st_fpf = state_192_cache[(c1_p, c2_p, c3_lvl, c4_p, a_p, b_p, c_p and (c3_lvl in ("partial", "full")))]
                                    st_ffull = state_192_cache[(c1_p, c2_p, c3_lvl, c4_p, a_p, b_p, c_p and (c3_lvl == "full"))]
                                    w7_mod_ev += w192 * st_ind["modular_exact"]
                                    w7_lck_ev += w192 * st_ind["locked_exact"]
                                    w7_mod_fpf += w192 * st_fpf["modular_exact"]
                                    w7_mod_ffull += w192 * st_ffull["modular_exact"]
        require(abs(w_sum - 1.0) <= 1e-12, f"192-state weight sum drift for {prof}: {w_sum}")
        exact_192_avg[prof] = {
            "states_evaluated": 192,
            "wave6_24state_modular_exact": w6_mod_ev,
            "wave6_24state_modular_pct": round(w6_mod_ev, 4),
            "wave6_24state_locked_pct": round(w6_lck_ev, 4),
            "wave7_stage0_priors_abc": [pa_p, pb_p, pc_p],
            "wave7_192state_exact_modular_exact": w7_mod_ev,
            "wave7_192state_exact_modular_pct": round(w7_mod_ev, 4),
            "wave7_192state_exact_locked_pct": round(w7_lck_ev, 4),
            "exact_192state_incremental_delta_pp": round(w7_mod_ev - w6_mod_ev, 4),
            "foundry_conditional_c_partial_or_full_modular_pct": round(w7_mod_fpf, 4),
            "foundry_conditional_c_partial_or_full_delta_pp": round(w7_mod_fpf - w6_mod_ev, 4),
            "foundry_conditional_c_full_only_modular_pct": round(w7_mod_ffull, 4),
            "foundry_conditional_c_full_only_delta_pp": round(w7_mod_ffull - w6_mod_ev, 4),
        }

    # 5. Executable Gate Self-Tests (200/200)
    gate_tests = run_wave7_gate_self_tests()

    p25 = primary_6arm["phi_0p25_central"]
    c_lo = p25["COMBINED_ABC_OMEGA_0P50_CEIL_LIFT_LOW"]
    c_ct = p25["COMBINED_ABC_OMEGA_0P50_CEIL_LIFT_CENTRAL"]
    c_hi = p25["COMBINED_ABC_OMEGA_0P50_CEIL_LIFT_HIGH"]
    f_lo = p25["COMBINED_ABC_OMEGA_0P50_FIXED_CEIL_LOW"]
    f_hi = p25["COMBINED_ABC_OMEGA_0P50_FIXED_CEIL_HIGH"]
    c3_lifted_central = round(0.942 + _tier_params("CENTRAL")["dc_c3"], 6)

    headline = {
        "booking_convention": "FULL_STAGED_CEILING_LIFT_ZERO_SPILLOVER_PRODUCT_ROUTE_EXACT_MODULAR_REBASED_ON_WAVE6_2P24",
        "live_wetlab_credit_pp": 0.0,
        "h1_allo_locked_pct": 88.0,
        "design_a_strictly_drug_free_and_invariant_pct": round(w6_6["design_a_standalone_exact"] * 100.0, 4),
        "design_a_physical_coated_route_modular_leak_pp": 0.0,
        "non_whitelisted_product_coated_route_modular_leak_pp": 0.0,
        "uncoated_xdz_spillover_pp": 0.0,
        "uncoated_b_r1_spillover_pp": 0.0,
        "uncoated_r1_and_r4_drift_pp": 0.0,
        "c_to_coated_h3_spillover_pp": 0.0,
        "wave6_6arm_central_baseline_modular_pct": w6_6["modular_pct"],
        "wave7_6arm_central_modular_pct": c_ct["modular_pct"],
        "wave7_6arm_central_locked_pct": c_ct["locked_pct"],
        "wave7_6arm_central_ceiling_pct": c_ct["ceiling_pct"],
        "wave7_6arm_central_delta_vs_wave6_pp": c_ct["delta_modular_vs_wave6_pct_pp"],
        "wave7_6arm_ceil_lift_band_modular_pct": [c_lo["modular_pct"], c_hi["modular_pct"]],
        "wave7_6arm_h2_ceil_held_central_modular_pct": sens_h2_held["COMBINED_ABC_CENTRAL"]["modular_pct"],
        "wave7_6arm_fixed_ceil_band_modular_pct": [f_lo["modular_pct"], f_hi["modular_pct"]],
        "wave7_6arm_strassen_central_pct": c_ct["strassen_h123_h4_pct"],
        "wave7_6arm_h23_lp_central_pct": c_ct["sharp_h23_lp_pct"],
        "wave7_5arm_central_modular_pct": sens_5arm["COMBINED_ABC_CEIL_LIFT_CENTRAL"]["modular_pct"],
        "wave7_192state_prelab_avg_central_modular_pct": exact_192_avg["Central"]["wave7_192state_exact_modular_pct"],
        "wave7_192state_c_foundry_conditional_band_central_pct": [
            exact_192_avg["Central"]["foundry_conditional_c_full_only_modular_pct"],
            exact_192_avg["Central"]["foundry_conditional_c_partial_or_full_modular_pct"],
        ],
        "per_iip_ceil_lift_modular_bands_pct": {
            "IIP-0062_A_pirfenidone": [
                p25["IIP0062_A_PIRFENIDONE_CEIL_LIFT_LOW"]["modular_pct"],
                p25["IIP0062_A_PIRFENIDONE_CEIL_LIFT_CENTRAL"]["modular_pct"],
                p25["IIP0062_A_PIRFENIDONE_CEIL_LIFT_HIGH"]["modular_pct"],
            ],
            "IIP-0063_B_deucravacitinib": [
                p25["IIP0063_B_DEUCRAVACITINIB_CEIL_LIFT_LOW"]["modular_pct"],
                p25["IIP0063_B_DEUCRAVACITINIB_CEIL_LIFT_CENTRAL"]["modular_pct"],
                p25["IIP0063_B_DEUCRAVACITINIB_CEIL_LIFT_HIGH"]["modular_pct"],
            ],
            "IIP-0064_C_gy032_channel_c": [
                p25["IIP0064_C_GY032_CHANNEL_C_CEIL_LIFT_LOW"]["modular_pct"],
                p25["IIP0064_C_GY032_CHANNEL_C_CEIL_LIFT_CENTRAL"]["modular_pct"],
                p25["IIP0064_C_GY032_CHANNEL_C_CEIL_LIFT_HIGH"]["modular_pct"],
            ],
            "IIP-0065_D_guardrails_pilots": [w6_6["modular_pct"], w6_6["modular_pct"], w6_6["modular_pct"]],
        },
    }

    payload: dict[str, Any] = {
        "schema_version": "wave7_cellgemma_2p24_rebase_v0.9.33",
        "wave": "Wave-7-CellGemma-Islet",
        "iip_ids": ["IIP-0062", "IIP-0063", "IIP-0064", "IIP-0065"],
        "iip_numbering_note": "IIP-0059 / DEC-140 / GATE-38 (Issue #59), IIP-0060 / DEC-141 / GATE-39 (Issue #60), and IIP-0061 / DEC-142 (Issue #61, Layer-1 normative prose sync; zero GATE/GY slots) occupy #59-#61 and GATE-38..GATE-39; Wave-7 CellGemma occupies IIP-0062..IIP-0065 / DEC-143..DEC-146 / GATE-40..GATE-43 / GY-037 / OFFGRID_GUARD_027.",
        "decision_ids": ["DEC-143", "DEC-144", "DEC-145", "DEC-146"],
        "gate_ids": ["GATE-40", "GATE-41", "GATE-42", "GATE-43"],
        "graveyard_guardrail_ids": ["GY-037", "OFFGRID_GUARD_027"],
        "canonical_wave6_product_bindings": {
            pid: {
                "arm": sp["arm"],
                "version": sp["version"],
                "required_switch": sp["required_switch"],
                "home_route": sp["home_route"],
                "allowed_routes": sorted(sp["allowed_routes"]),
                "drug_coating_allowed": sp["drug_coating_allowed"],
                "hla_e_engineered": sp["hla_e_engineered"],
                "cd47_engineered": sp["cd47_engineered"],
                "autologous_self_hla": sp["autologous_self_hla"],
                "execution_supported_in_registry": sp["execution_supported_in_registry"],
            }
            for pid, sp in CANONICAL_WAVE6_PRODUCTS.items()
        },
        "active_coating_product_routes": [
            {"product_id": "ISLET1_DESIGN_Y_V3", "route_id": "R3P"},
            {"product_id": "ISLET1_DESIGN_B_V090", "route_id": "R2"},
        ],
        "evidence_tier": "cellgemma_e4b_in_silico_prior",
        "epistemic_disclosure": {
            "step0_track1_pass": False,
            "step0_track2_pass": False,
            "hard_stop_triggered": True,
            "live_wetlab_credit_pp": 0.0,
            "statement": (
                "All headline #odds numbers are transparently computational engineering judgements assuming staged designs "
                "pass every Stage-0 safety check before human trials. CellGemma-e4b failed preregistered Step-0 G1 checks on "
                "both Track 1 and Track 2; its outputs serve strictly as retrospective exploratory priors alongside independent "
                "peer-reviewed literature. Offline gate checks return PASS_STAGE0_OFFLINE_VERIFIED_PENDING_LIVE_LEDGER with "
                "release_authorizing=False and live_ledger_authenticated=False."
            ),
        },
        "upstream_pins": {
            "wave6_master_contract_sha256": w6_sha,
            "cellgemma_receipt_file_sha256": cg_file_sha,
            "cellgemma_receipt_portable_payload_sha256": cg_payload_sha,
            "wave6_6arm_central_baseline_modular_exact": PINNED_WAVE6_EXACT["Wave6_6Arm_Central_modular"],
        },
        "headroom_compression_factors": {
            "scale_c4_univ_on_0p950": SCALE_C4_UNIV,
            "scale_c3_base_on_0p942": SCALE_C3_BASE,
            "c3_base_lifted_central_iip0064": c3_lifted_central,
            "route4_c4_r4_kept_untouched": 0.870,
            "uncoated_h2_and_h4_joint_laws_strictly_invariant": True,
            "coated_h3_strictly_isolated_from_drug_free_iip0064": True,
        },
        "headline_summary": headline,
        "shipped_baselines": {
            "L0_core_3arm": l0,
            "L1_shipped_5arm_pinned": {
                "modular_pct": round(PINNED_WAVE6_EXACT["L1_shipped_5arm_modular"], 4),
                "locked_pct": round(PINNED_WAVE6_EXACT["L1_shipped_5arm_locked"], 4),
            },
            "Wave5_L3B_pinned": {
                "modular_pct": round(PINNED_WAVE6_EXACT["Wave5_L3B_modular"], 4),
                "locked_pct": round(PINNED_WAVE6_EXACT["Wave5_L3B_locked"], 4),
            },
            "Wave6_5Arm_Central": w6_5,
            "Wave6_6Arm_Central": w6_6,
        },
        "primary_6arm_2p24_rebased": primary_6arm,
        "audit_sensitivities": {
            "single_coated_pair_decomposition": sens_single_pair,
            "h2_ceiling_held_diagnostic": sens_h2_held,
            "genetic_c_including_design_a": sens_c_incl_a,
            "route3p_direct_arm_z_r4_inactive": sens_r3p_direct,
            "c_on_coated_paths_counterfactual_not_primary": sens_c_on_coated_cf,
            "vehicle_gated_route4_counterfactual": sens_r4_cf,
            "wave6_5arm_central_rebase": sens_5arm,
            "omega_h4_overlap_sweep": sens_omega,
            "design_b_tyk2_discount_sweep": sens_b_disc,
            "exact_192state_prelab_scenario_average": exact_192_avg,
        },
        "executable_gate_self_tests": gate_tests,
    }
    check_all_finite(payload, "wave7_payload")
    payload["portable_payload_sha256"] = sha256_bytes(canonical_json_bytes(payload))
    return payload


# ---------------------------------------------------------------------------
# Hardened Fail-Closed Stage-0 Gate Adjudicators (GATE-40 .. GATE-43, v0.9.8)
# Full Canonical Parity: GATE-34/OQ-012, GATE-0V-KILL (Estimands 1 & 2 + Full
# Per-Estimand Multi-Well Partitions), Playbook Readout-2/3B (Per-Block &
# Donor-Linked), GATE-31 (DEC-134 Paired Blocks), Coating Article Identity,
# B-0a-exact Derived Operative Ceiling, Meet-in-the-Middle Exact Sign-Flip,
# 5-Arm Sibling Raw Vectors, & Timed Prerequisite-Bound Receipt Chains
# ---------------------------------------------------------------------------

from bisect import bisect_left, bisect_right
from datetime import datetime, timedelta, timezone
from decimal import Decimal, InvalidOperation, ROUND_FLOOR, getcontext
from fractions import Fraction
from functools import lru_cache

REQUIRED_5_LINEAGES: FrozenSet[str] = frozenset({
    "INS_beta", "GCG_alpha", "SST_delta", "PLVAP_iEC", "pericyte",
})
REQUIRED_5_REGIMES: FrozenSet[str] = frozenset({
    "normoxia", "hypoxia_1pct_o2_cytokines", "er_stress",
    "active_persistent_cvb4", "active_persistent_hcmv",
})
VIRAL_REGIMES: FrozenSet[str] = frozenset({
    "active_persistent_cvb4", "active_persistent_hcmv",
})
REQUIRED_3_MATRICES: FrozenSet[str] = frozenset({
    "low_serum_media", "human_serum_100pct", "whole_blood",
})
REQUIRED_HOUR0_LINEAGES_FULL: FrozenSet[str] = frozenset({"INS_beta", "GCG_alpha", "SST_delta", "PLVAP_iEC"})
REQUIRED_HOUR0_LINEAGES_IEC: FrozenSet[str] = frozenset({"PLVAP_iEC"})
C1_FAMILY_GENES: FrozenSet[str] = frozenset({
    "BCL2L11", "PMAIP1", "PMAIP1+BCL2L11", "BBC3", "JAK2",
})
COATING_IDENTITY_KEYS: FrozenSet[str] = frozenset({
    "coating_article_id", "coating_formulation_rev", "coating_lot_id",
    "matched_blank_vehicle_lot_id", "exposure_protocol_id", "api_batch_id",
})
DESIGN_A_FORBIDDEN_ALIASES: FrozenSet[str] = DESIGN_A_ALIASES
LEGACY_NON_TRANSFERABLE_PRODUCTS: FrozenSet[str] = frozenset(LEGACY_V080_PRODUCTS.keys())
ACTIVE_PRIMARY_COATING_PAIRS: FrozenSet[tuple[str, str]] = ACTIVE_COATING_PRODUCT_ROUTES
DEFERRED_COATING_PAIRS: FrozenSet[tuple[str, str]] = frozenset({
    ("ISLET1_DESIGN_X_V090", "R1"),
})
SENSITIVITY_COATING_PAIRS: FrozenSet[tuple[str, str]] = frozenset({
    ("ISLET1_ARM_Z_ENSC_V090", "R3P"),
})
SEPARATE_ROUTE4_COATING_PAIRS: FrozenSet[tuple[str, str]] = frozenset({
    ("ISLET1_DESIGN_Y_V3", "R4"),
    ("ISLET1_DESIGN_D1B_LEAN_K2", "R4"),
    ("ISLET1_ARM_Z_ENSC_V090", "R4"),
})
CANONICAL_READOUT2_Z_MIN_BY_UNIT: dict[str, float] = {
    "uIU_per_1000_IEQ_min": 1.0,
    "ng_Cpep_per_1000_IEQ_min": 0.5,
}
GATE5_OQ012_MIN_EFFECTIVE_TRIALS: int = 299_573_228
MAX_CLONOGENIC_CELLS: int = 10 ** 12
EXACT_SIGN_FLIP_MAX_N: int = 20
ALLOWED_EXCLUSION_REASONS: FrozenSet[str] = frozenset({
    "HEMOLYSIS_PRE_ANALYTICAL", "CONTROL_ASSAY_FAILURE", "TECHNICAL_CLOT_BEFORE_LOOP",
    "SURGICAL_COMPLICATION_PRE_RANDOMIZATION", "SAMPLE_LOSS_PRE_ADJUDICATION",
    "CONTAMINATED_CULTURE_PRE_READOUT",
})

OFFLINE_VERDICT_PRIMARY = "PASS_STAGE0_OFFLINE_VERIFIED_PENDING_LIVE_LEDGER"
OFFLINE_ARCHIVE_NOTE = "CONTENT_HASH_AND_SCHEMA_VERIFIED_OFFLINE_REQUIRES_LIVE_REPO_LEDGER_AT_RELEASE"

SHIELD_COMPONENTS_BY_PRODUCT: dict[str, FrozenSet[str]] = {
    "ISLET1_DESIGN_Y_V3": frozenset({"SERPINB9", "PDL1_SYN6", "CD274p_IL1RN", "HLAE", "CD47_IgV_GPI"}),
    "ISLET1_DESIGN_B_V090": frozenset({"CXCL10_SERPINB9", "PDL1_SYN6", "HLA_C", "CD47_IgV_GPI"}),
    "ISLET1_DESIGN_X_V090": frozenset({"CXCL10_SERPINB9", "PDL1_SYN6", "CD47_IgV_GPI"}),
    "ISLET1_DESIGN_D1B_LEAN_K2": frozenset({"CXCL10_SERPINB9", "PDL1_SYN6", "AUTOLOGOUS_HLA_ABC"}),
    "ISLET1_ARM_Z_ENSC_V090": frozenset({"SERPINB9", "PDL1_SYN6", "CD274p_IL1RN", "HLAE", "CD47_IgV_GPI"}),
    "ISLET1_DESIGN_A_V080_REF": frozenset({"CXCL10_SERPINB9", "PDL1", "HLAE", "CD47_IgV_GPI"}),
}


def is_valid_sha256_hex(val: Any) -> bool:
    return isinstance(val, str) and len(val) == 64 and all(c in "0123456789abcdefABCDEF" for c in val)


def compute_receipt_sha256(ev: Mapping[str, Any]) -> str:
    """Canonical SHA-256 of receipt content excluding receipt_sha256 itself (tamper-evident offline integrity)."""
    body = {k: v for k, v in ev.items() if k != "receipt_sha256"}
    return sha256_bytes(canonical_json_bytes(body))


def parse_utc_iso_ts(val: Any) -> Optional[datetime]:
    """Strict ISO-8601 UTC timestamp parser (requires YYYY-MM-DDTHH:MM:SSZ or +00:00, real calendar date)."""
    if not is_nonempty_str(val):
        return None
    s = str(val).strip()
    if s.endswith("Z"):
        s = s[:-1] + "+00:00"
    if len(s) < 25 or "T" not in s:
        return None
    try:
        dt = datetime.fromisoformat(s)
    except ValueError:
        return None
    if dt.tzinfo is None or dt.utcoffset() != timezone.utc.utcoffset(dt):
        return None
    return dt.astimezone(timezone.utc)


def _to_exact_decimal(val: Any) -> Optional[Decimal]:
    """Convert int/Decimal/finite-float/numeric-str (never bool) to exact finite Decimal without big-int float coercion."""
    if isinstance(val, bool) or val is None:
        return None
    if isinstance(val, Decimal):
        return val if val.is_finite() else None
    if isinstance(val, int):
        return Decimal(val)
    if isinstance(val, float):
        if not math.isfinite(val):
            return None
        return Decimal(str(val))
    if isinstance(val, str):
        s = val.strip()
        if not s:
            return None
        try:
            d = Decimal(s)
        except InvalidOperation:
            return None
        return d if d.is_finite() else None
    return None


# --- Pure-stdlib exact statistical helpers (zero scipy/numpy dependency!) ---

def _betainc_cf(a: float, b: float, x: float) -> float:
    """Modified Lentz continued fraction for regularized incomplete beta I_x(a, b)."""
    max_iter = 400
    eps = 3.0e-15
    fpmin = 1.0e-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, max_iter + 1):
        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 regularized_incomplete_beta(a: float, b: float, x: float) -> float:
    """Exact pure-stdlib regularized incomplete beta function I_x(a, b)."""
    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 * _betainc_cf(a, b, x) / a
    return 1.0 - bt * _betainc_cf(b, a, 1.0 - x) / b


def student_t_two_sided_p(t_abs: float, df: float) -> float:
    """Exact pure-stdlib two-sided Student-t p-value P(|T_df| >= t_abs) for arbitrary real df > 0."""
    if t_abs <= 0.0:
        return 1.0
    df_f = float(df)
    x = df_f / (df_f + t_abs * t_abs)
    return regularized_incomplete_beta(0.5 * df_f, 0.5, x)


@lru_cache(maxsize=512)
def student_t_one_sided_crit(alpha: float, df: float) -> float:
    """Exact pure-stdlib one-sided Student-t quantile t_{1-alpha, df} for arbitrary real df > 0."""
    df_f = float(df)
    target_two_sided = 2.0 * alpha
    lo = 0.0
    hi = 2.0
    while student_t_two_sided_p(hi, df_f) > target_two_sided:
        hi *= 2.0
    for _ in range(90):
        mid = 0.5 * (lo + hi)
        if student_t_two_sided_p(mid, df_f) > target_two_sided:
            lo = mid
        else:
            hi = mid
    return hi


def _binom_cdf_le_decimal(k: int, n: int, p: Decimal) -> Decimal:
    """Exact high-precision Decimal P(Bin(n, p) <= k) using shortest tail."""
    one = Decimal(1)
    q = one - p
    if k < 0:
        return Decimal(0)
    if k >= n:
        return one
    if p <= Decimal(0):
        return one
    if p >= one:
        return Decimal(0)
    # Use log-space starting term + exact recurrence for numerical stability at any n
    if k <= n - k:
        # Sum j = 0 .. k
        if k == 0:
            return (Decimal(n) * q.ln()).exp()
        # Start at mode or j=0 safely via ln
        term = (Decimal(n) * q.ln()).exp()
        if term == 0:
            # Start at j=k and sum downward
            ln_c = Decimal(0)
            for j in range(1, k + 1):
                ln_c += Decimal(n - j + 1).ln() - Decimal(j).ln()
            term = (ln_c + Decimal(k) * p.ln() + Decimal(n - k) * q.ln()).exp()
            s = term
            for j in range(k, 0, -1):
                term = term * Decimal(j) * q / (Decimal(n - j + 1) * p)
                s += term
                if term == 0:
                    break
            return min(one, s)
        s = term
        for j in range(1, k + 1):
            term = term * Decimal(n - j + 1) * p / (Decimal(j) * q)
            s += term
        return min(one, s)
    # Complement: 1 - P(Bin(n, q) <= n - k - 1)
    return max(Decimal(0), one - _binom_cdf_le_decimal(n - k - 1, n, q))


@lru_cache(maxsize=4096)
def clopper_pearson_upper_decimal(k: int, n: int, alpha_str: str) -> Decimal:
    """Exact 70-digit outward-rounded (ceiling) Decimal one-sided Clopper-Pearson upper bound."""
    from decimal import localcontext, ROUND_CEILING
    with localcontext() as ctx:
        ctx.prec = 75
        one = Decimal(1)
        alpha = Decimal(alpha_str)
        if k >= n:
            return one
        if k == 0:
            val = one - (alpha.ln() / Decimal(n)).exp()
            return min(one, val + Decimal("1e-60"))
        # Solve P(Bin(n, p) <= k) == alpha (decreasing in p): hi satisfies CDF <= alpha
        lo = Decimal(0)
        hi = one
        for _ in range(210):
            mid = (lo + hi) / Decimal(2)
            if _binom_cdf_le_decimal(k, n, mid) > alpha:
                lo = mid
            else:
                hi = mid
        ctx.rounding = ROUND_CEILING
        return min(one, (hi + Decimal("1e-55")).quantize(Decimal("1e-50")))


@lru_cache(maxsize=4096)
def clopper_pearson_lower_decimal(k: int, n: int, alpha_str: str) -> Decimal:
    """Exact 70-digit outward-rounded (floor) Decimal one-sided Clopper-Pearson lower bound."""
    from decimal import localcontext, ROUND_FLOOR
    with localcontext() as ctx:
        ctx.prec = 75
        zero = Decimal(0)
        one = Decimal(1)
        alpha = Decimal(alpha_str)
        if k <= 0:
            return zero
        if k >= n:
            val = (alpha.ln() / Decimal(n)).exp()
            return max(zero, val - Decimal("1e-60"))
        # Solve P(Bin(n, p) >= k) == alpha <=> P(Bin(n, p) <= k - 1) == 1 - alpha (decreasing in p)
        target = one - alpha
        lo = zero
        hi = one
        for _ in range(210):
            mid = (lo + hi) / Decimal(2)
            if _binom_cdf_le_decimal(k - 1, n, mid) > target:
                lo = mid
            else:
                hi = mid
        ctx.rounding = ROUND_FLOOR
        return max(zero, (lo - Decimal("1e-55")).quantize(Decimal("1e-50")))


def clopper_pearson_upper(k: int, n: int, alpha: float) -> float:
    return float(clopper_pearson_upper_decimal(k, n, str(alpha)))


def clopper_pearson_lower(k: int, n: int, alpha: float) -> float:
    return float(clopper_pearson_lower_decimal(k, n, str(alpha)))


def holm_bonferroni_adjust(p_map: Mapping[str, float]) -> dict[str, float]:
    """Exact step-down Holm-Bonferroni adjusted p-values across a full candidate family."""
    items = sorted(((k, float(v)) for k, v in p_map.items()), key=lambda kv: (kv[1], kv[0]))
    m = len(items)
    adj: dict[str, float] = {}
    running_max = 0.0
    for idx, (k, p_raw) in enumerate(items):
        val = min(1.0, (m - idx) * p_raw)
        if val < running_max:
            val = running_max
        running_max = val
        adj[k] = val
    return adj


def paired_t_summary(diffs: Sequence[float]) -> Optional[tuple[float, float, float, float]]:
    """Return (mean, t_stat, two_sided_p, one_sided_l95) for paired differences, or None if degenerate."""
    n = len(diffs)
    if n < 2:
        return None
    mean_d = sum(diffs) / n
    var_d = sum((d - mean_d) ** 2 for d in diffs) / (n - 1)
    if var_d <= 0.0:
        return None
    se = math.sqrt(var_d / n)
    t_stat = mean_d / se
    p_two = student_t_two_sided_p(abs(t_stat), n - 1)
    l95 = mean_d - student_t_one_sided_crit(0.05, n - 1) * se
    return mean_d, t_stat, p_two, l95


def two_sample_welch_summary(x: Sequence[float], y: Sequence[float]) -> Optional[tuple[float, float, float, float]]:
    """Return (mean_x - mean_y, t_stat, two_sided_p, one_sided_l95) via Welch's t-test, or None if degenerate."""
    nx, ny = len(x), len(y)
    if nx < 2 or ny < 2:
        return None
    mx = sum(x) / nx
    my = sum(y) / ny
    vx = sum((v - mx) ** 2 for v in x) / (nx - 1)
    vy = sum((v - my) ** 2 for v in y) / (ny - 1)
    s2 = vx / nx + vy / ny
    if s2 <= 0.0:
        return None
    se = math.sqrt(s2)
    denom = ((vx / nx) ** 2) / (nx - 1) + ((vy / ny) ** 2) / (ny - 1)
    df = max(1.0, (s2 * s2) / denom)
    diff = mx - my
    t_stat = diff / se
    p_two = student_t_two_sided_p(abs(t_stat), df)
    l95 = diff - student_t_one_sided_crit(0.05, df) * se
    return diff, t_stat, p_two, l95


def fieller_ratio_one_sided_lower(
    num: Sequence[float],
    den: Sequence[float],
    *,
    paired: bool = True,
    alpha: float = 0.05,
) -> Optional[tuple[float, float]]:
    """
    Exact one-sided (1-alpha) Fieller lower bound for ratio R = E[num] / E[den] (mean(den) > 0).
    Returns (point_ratio, fieller_lower) or None if denominator precision fails (g >= 1) or degenerate.
    """
    nx, ny = len(num), len(den)
    if nx < 2 or ny < 2 or (paired and nx != ny):
        return None
    mx = sum(num) / nx
    my = sum(den) / ny
    if my <= 0.0:
        return None
    vx = sum((v - mx) ** 2 for v in num) / (nx - 1)
    vy = sum((v - my) ** 2 for v in den) / (ny - 1)
    if paired:
        v_mx = vx / nx
        v_my = vy / nx
        cov_m = sum((num[i] - mx) * (den[i] - my) for i in range(nx)) / (nx * (nx - 1))
        df = nx - 1
    else:
        v_mx = vx / nx
        v_my = vy / ny
        cov_m = 0.0
        df = min(nx, ny) - 1
    tcrit = student_t_one_sided_crit(alpha, df)
    t2 = tcrit * tcrit
    g = t2 * v_my / (my * my)
    if g >= 1.0:
        return None
    # Quadratic: (my^2 - t2*v_my)*R^2 - 2*(mx*my - t2*cov_m)*R + (mx^2 - t2*v_mx) <= 0
    a = my * my - t2 * v_my
    b = mx * my - t2 * cov_m
    c = mx * mx - t2 * v_mx
    disc = b * b - a * c
    if disc < 0.0:
        return None
    r_lo = (b - math.sqrt(disc)) / a
    return (mx / my), r_lo


def sample_t_one_sided_bounds(
    vals: Sequence[float], alpha: float = 0.05, *, extra_within_var: float = 0.0,
) -> Optional[tuple[float, float, float]]:
    """Return (mean, one_sided_l, one_sided_u) at tail alpha for n >= 2 values (with optional extra within-lot variance)."""
    n = len(vals)
    if n < 2:
        return None
    if all(v == vals[0] for v in vals):
        return None
    mean_v = sum(vals) / n
    var_v = sum((v - mean_v) ** 2 for v in vals) / (n - 1)
    # Match live wetlab_contract.py:_one_sided_t_bounds_iip0029: zero between-block variance
    # is ALWAYS unestimable (returns None) BEFORE adding extra_within_var!
    if var_v <= 0.0:
        return None
    tot_se_sq = (var_v / n) + max(0.0, float(extra_within_var))
    if tot_se_sq <= 0.0:
        return None
    se = math.sqrt(tot_se_sq)
    tcrit = student_t_one_sided_crit(alpha, n - 1)
    return mean_v, mean_v - tcrit * se, mean_v + tcrit * se


def _eval_t_bound_from_vec(vals: Sequence[float], tcrit: float, *, upper: bool) -> float:
    n = len(vals)
    m = sum(vals) / n
    v = sum((x - m) ** 2 for x in vals) / (n - 1)
    se = math.sqrt(v / n) if v > 0.0 else 0.0
    return m + tcrit * se if upper else m - tcrit * se


def censor_aware_t_bound(
    intervals: Sequence[tuple[float, float]],
    alpha: float = 0.05,
    *,
    upper: bool = True,
) -> Optional[float]:
    """
    Mathematically EXACT worst-case censor-aware one-sided Student-t confidence bound over
    x_i in [lo_i, hi_i] (Bauer's Maximum Principle):
      - U_alpha(x) = mean(x) + t_{1-alpha,n-1} * sd(x) / sqrt(n) is CONVEX on prod_i [lo_i, hi_i],
        so its global supremum over ALL admissible completions is attained at a vertex.
      - L_alpha(x) = mean(x) - t_{1-alpha,n-1} * sd(x) / sqrt(n) is CONCAVE on prod_i [lo_i, hi_i],
        so its global infimum over ALL admissible completions is attained at a vertex.
    Uses exact symmetry grouping by identical uncertain intervals (O(n) for single-analyte censoring,
    exact product/bitmask for multi-analyte censoring). Returns None if n < 2 or combinatorial bound exceeded.
    """
    n = len(intervals)
    if n < 2:
        return None
    tcrit = student_t_one_sided_crit(alpha, n - 1)
    fixed_vals: list[float] = []
    groups: dict[tuple[float, float], list[tuple[float, float]]] = {}
    uncert_count = 0
    for lo, hi in intervals:
        if hi < lo - 1e-12:
            return None
        if hi <= lo + 1e-15:
            fixed_vals.append(lo)
        else:
            key = (round(lo, 12), round(hi, 12))
            groups.setdefault(key, []).append((lo, hi))
            uncert_count += 1
    if uncert_count == 0:
        return _eval_t_bound_from_vec(fixed_vals, tcrit, upper=upper)
    group_items = list(groups.values())
    total_states = 1
    for grp in group_items:
        total_states *= (len(grp) + 1)
    if total_states > 16384:
        return None
    best: Optional[float] = None

    def _recurse(g_idx: int, acc: list[float]) -> None:
        nonlocal best
        if g_idx == len(group_items):
            val = _eval_t_bound_from_vec(acc, tcrit, upper=upper)
            if best is None or (upper and val > best) or ((not upper) and val < best):
                best = val
            return
        grp = group_items[g_idx]
        k = len(grp)
        lo_g, hi_g = grp[0]
        for m_lo in range(k + 1):
            acc.extend([lo_g] * m_lo)
            acc.extend([hi_g] * (k - m_lo))
            _recurse(g_idx + 1, acc)
            del acc[-k:]

    _recurse(0, list(fixed_vals))
    return best


def _std_normal_inv_cdf(p: float) -> float:
    """Exact standard normal inverse CDF via monotone bisection on math.erfc (1e-13 accuracy, zero external deps)."""
    lo, hi = -10.0, 10.0
    for _ in range(70):
        mid = 0.5 * (lo + hi)
        cdf = 0.5 * math.erfc(-mid / math.sqrt(2.0))
        if cdf < p:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)


def paired_diff_normality_qq_r(diffs: Sequence[float]) -> Optional[float]:
    """Compute Blom normal-quantile correlation r_QQ (Shapiro-Francia/Filliben normality diagnostic) for n >= 3."""
    n = len(diffs)
    if n < 3:
        return None
    ys = sorted(float(x) for x in diffs)
    qs = [_std_normal_inv_cdf((i + 1.0 - 0.375) / (n + 0.25)) for i in range(n)]
    my = sum(ys) / n
    mq = sum(qs) / n
    vy = sum((y - my) ** 2 for y in ys)
    vq = sum((q - mq) ** 2 for q in qs)
    if vy <= 0.0 or vq <= 0.0:
        return None
    cov = sum((ys[i] - my) * (qs[i] - mq) for i in range(n))
    return cov / math.sqrt(vy * vq)


def _eval_horner_poly(coeffs: Sequence[float], x: float) -> float:
    acc = 0.0
    for c in coeffs:
        acc = acc * x + c
    return acc


def shapiro_wilk_test(xs: Sequence[float]) -> Optional[tuple[float, float]]:
    """
    Pure-Python Algorithm AS R94 Shapiro-Wilk normality test (Royston 1992, Applied Statistics 41:117-133)
    for 3 <= n <= 50. Matches R stats::shapiro.test / SciPy to < 1e-4; returns (W, p_value) or None.
    """
    n = len(xs)
    if n < 3 or n > 50:
        return None
    s = sorted(float(x) for x in xs)
    mean = sum(s) / n
    ss = sum((x - mean) ** 2 for x in s)
    if ss <= 1e-18:
        return None
    m = [_std_normal_inv_cdf((i + 1.0 - 0.375) / (n + 0.25)) for i in range(n)]
    m_ss = sum(v * v for v in m)
    u = 1.0 / math.sqrt(n)
    a = [0.0] * n
    if n == 3:
        a[2] = math.sqrt(0.5)
        a[0] = -a[2]
        a[1] = 0.0
    else:
        an = _eval_horner_poly([-2.706056, 4.434685, -2.071190, -0.147981, 0.221157, m[-1] / math.sqrt(m_ss)], u)
        a[-1] = an
        a[0] = -an
        if n <= 5:
            phi = (m_ss - 2.0 * m[-1] ** 2) / (1.0 - 2.0 * an ** 2)
            sp = math.sqrt(phi)
            for i in range(1, n - 1):
                a[i] = m[i] / sp
        else:
            an1 = _eval_horner_poly([-3.582633, 5.682633, -1.752461, -0.293762, 0.042981, m[-2] / math.sqrt(m_ss)], u)
            a[-2] = an1
            a[1] = -an1
            phi = (m_ss - 2.0 * m[-1] ** 2 - 2.0 * m[-2] ** 2) / (1.0 - 2.0 * an ** 2 - 2.0 * an1 ** 2)
            sp = math.sqrt(phi)
            for i in range(2, n - 2):
                a[i] = m[i] / sp
    num = sum(ai * xi for ai, xi in zip(a, s))
    w = min(1.0, max(0.0, (num * num) / ss))
    if w >= 1.0 - 1e-15:
        return (w, 1.0)
    if n == 3:
        p = (6.0 / math.pi) * (math.asin(math.sqrt(w)) - math.asin(math.sqrt(0.75)))
        return (w, max(0.0, min(1.0, p)))
    lw = math.log(1.0 - w)
    if n <= 11:
        gam = 0.459 * n - 2.273
        if lw >= gam - 1e-12:
            return (w, 0.0)
        y = -math.log(gam - lw)
        mu = -0.0006714 * (n ** 3) + 0.025054 * (n ** 2) - 0.39978 * n + 0.5440
        sig = math.exp(-0.0020322 * (n ** 3) + 0.062767 * (n ** 2) - 0.77857 * n + 1.3822)
    else:
        lx = math.log(n)
        y = lw
        mu = 0.0038915 * (lx ** 3) - 0.083751 * (lx ** 2) - 0.31082 * lx - 1.5861
        sig = math.exp(0.0030302 * (lx ** 2) - 0.082676 * lx - 0.4803)
    z = (y - mu) / sig
    p = 0.5 * math.erfc(z / math.sqrt(2.0))
    return (w, max(0.0, min(1.0, p)))


def _to_exact_fraction(val: Any) -> Optional[Fraction]:
    if isinstance(val, Fraction):
        return val
    d = _to_exact_decimal(val)
    if d is None:
        return None
    return Fraction(d)


def _all_signed_subset_sums_int(vals: Sequence[int]) -> list[int]:
    sums = [0]
    for v in vals:
        sums = [s + v for s in sums] + [s - v for s in sums]
    return sums


def _exact_sign_flip_p_from_fractions(fracs: Sequence[Fraction]) -> Optional[float]:
    """
    Exact arbitrary-precision scaled-integer two-sided paired Fisher sign-flip p-value.
    Eliminates ALL float subtraction drift and ALL ambient Decimal precision limits on boundary ties!
    """
    n = len(fracs)
    if n == 0:
        return 1.0
    if n > EXACT_SIGN_FLIP_MAX_N:
        return None
    lcm_den = 1
    for f in fracs:
        lcm_den = math.lcm(lcm_den, f.denominator)
    ivals = [int(f * lcm_den) for f in fracs]
    obs = abs(sum(ivals))
    if obs == 0:
        return 1.0
    if all(v > 0 for v in ivals) or all(v < 0 for v in ivals):
        return 2.0 / float(1 << n)
    mid = n // 2
    left_sums = _all_signed_subset_sums_int(ivals[:mid])
    right_sums = sorted(_all_signed_subset_sums_int(ivals[mid:]))
    nr = len(right_sums)
    neg_obs = -obs
    extreme = 0
    for a in left_sums:
        extreme += (nr - bisect_left(right_sums, obs - a)) + bisect_right(right_sums, neg_obs - a)
    return min(1.0, extreme / float(1 << n))


def exact_two_sided_sign_flip_p(diffs: Sequence[Any]) -> Optional[float]:
    """Exact rational/scaled-integer two-sided Fisher sign-flip p-value for 1 <= n <= 20."""
    fracs = [_to_exact_fraction(x) for x in diffs]
    if any(f is None for f in fracs):
        return None
    return _exact_sign_flip_p_from_fractions([f for f in fracs if f is not None])


def exact_two_sided_sign_flip_paired_p(treated: Sequence[Any], control: Sequence[Any]) -> Optional[float]:
    """Exact rational/scaled-integer paired Fisher sign-flip forming (treated[i] - control[i]) in exact Fraction arithmetic."""
    if len(treated) != len(control):
        return None
    fracs: list[Fraction] = []
    for a, b in zip(treated, control):
        fa = _to_exact_fraction(a)
        fb = _to_exact_fraction(b)
        if fa is None or fb is None:
            return None
        fracs.append(fa - fb)
    return _exact_sign_flip_p_from_fractions(fracs)


def exact_hodges_lehmann_median(diff_fracs: Sequence[Fraction]) -> Fraction:
    """Exact rational Hodges-Lehmann one-sample estimator (median of all n(n+1)/2 Walsh averages)."""
    n = len(diff_fracs)
    require(n >= 1, "exact_hodges_lehmann_median requires at least one difference")
    walsh_avgs = sorted((diff_fracs[i] + diff_fracs[j]) / 2 for i in range(n) for j in range(i, n))
    nw = len(walsh_avgs)
    if nw % 2 == 1:
        return walsh_avgs[nw // 2]
    return (walsh_avgs[nw // 2 - 1] + walsh_avgs[nw // 2]) / 2


def recompute_clopper_pearson_u95_decimal_n_eff(n_eff: int) -> Decimal:
    """Exact 75-digit Decimal Clopper-Pearson one-sided 95% upper bound for k=0 survivors at integer n_eff."""
    return clopper_pearson_upper_decimal(0, n_eff, "0.05")


def _recompute_pirfenidone_peak_systemic_cmax_ug_ml(
    times_h: Sequence[float],
    cum_mg: Sequence[float],
    *,
    t_half_h: float,
    vd_l: float,
) -> float:
    """
    Mathematically tight supremum 1-compartment peak systemic plasma C_max (ug/mL = mg/L) over ALL
    non-decreasing cumulative release schedules compatible with (times_h, cum_mg):
      - Max carry-over at t_{i-1} occurs when all prior increments arrive as late as possible (amount_end)
      - Max intra-interval peak occurs immediately after t_{i-1}+ when full dm_i arrives instantaneously
        (amount_end + dm_i), strictly upper-bounding adjacent-boundary double bursts!
    """
    ke = math.log(2.0) / t_half_h
    amount_end = 0.0
    max_mg = 0.0
    for i in range(1, len(times_h)):
        dt = times_h[i] - times_h[i - 1]
        dm = cum_mg[i] - cum_mg[i - 1]
        # Supremum peak at t_{i-1}+: prior carried-over mass + instantaneous full next-interval burst dm
        peak_at_left = amount_end + dm
        if peak_at_left > max_mg:
            max_mg = peak_at_left
        # Advance maximum possible carried-over mass at t_i (prior mass decays over dt, dm arrives at t_i-)
        amount_end = amount_end * math.exp(-ke * dt) + dm
        if amount_end > max_mg:
            max_mg = amount_end
    return max_mg / vd_l  # mg/L == ug/mL


def _recompute_max_24h_cumulative_mg(times_h: Sequence[float], cum_mg: Sequence[float]) -> float:
    """
    Exact mathematical supremum of C(s + 24) - C(s) over ALL start times s >= 0 and ALL
    monotone non-decreasing cumulative release curves C(t) passing through (times_h[k], cum_mg[k]):
      - Any single-interval release cum[i+1] - cum[i] can occur instantaneously inside a 24-h window.
      - Any multi-interval pair (i, j) with j >= i + 2 can have s in [t_i, t_{i+1}) and s+24 in (t_{j-1}, t_j]
        iff t_{j-1} - t_{i+1} < 24.0 (or t_j - t_i <= 24.0), achieving exact supremum cum[j] - cum[i].
    Makes ZERO linear-interpolation assumptions (never undercounts step or non-grid 24-h windows!).
    """
    n = len(times_h)
    max_24 = 0.0
    for i in range(n):
        for j in range(i + 1, n):
            dm = cum_mg[j] - cum_mg[i]
            if j == i + 1 or (times_h[j] - times_h[i]) <= 24.0 + 1e-9 or (times_h[j - 1] - times_h[i + 1]) <= 24.0 + 1e-9:
                if dm > max_24:
                    max_24 = dm
            else:
                break
    return max_24


def _validate_dec134_washout_trace(
    w_ts: Any, w_rem: Any, w_sha: Any,
    w_span: Any, w_tail: Any, w_mass: Any,
    w_t50: Any, w_mean: Any, w_t90: Any,
) -> bool:
    """
    Shared fail-closed DEC-134 washout trace reconciler used by BOTH Readout-2 AND GATE-31:
      - Verifies content SHA-256 against canonical JSON of the embedded raw trace
      - Recomputes exact t50 (50% crossing) and t90 (10% crossing) brackets directly from raw series
        (requiring full bracket upper edge <= 4.50 min for t50 and <= 11.0 min for t90, with no rebound!)
      - Recomputes trapezoidal mean transit time (MTT = integral / r[0]) <= 5.50 min and reconciles to summary!
    """
    if not (
        isinstance(w_ts, list) and isinstance(w_rem, list) and len(w_ts) == len(w_rem) and len(w_ts) >= 5
        and all(is_finite_num(x) for x in w_ts + w_rem)
        and all(is_finite_num(x) for x in (w_span, w_tail, w_mass, w_t50, w_mean, w_t90))
        and is_valid_sha256_hex(w_sha)
    ):
        return False
    expected_sha = sha256_bytes(canonical_json_bytes({"time_min": w_ts, "remaining_peak_pct": w_rem}))
    if str(w_sha) != expected_sha:
        return False
    wtf = [float(x) for x in w_ts]
    wrf = [float(x) for x in w_rem]
    if (
        wtf[0] != 0.0 or any(wtf[i] >= wtf[i + 1] for i in range(len(wtf) - 1))
        or wtf[-1] < 15.0 or not (95.0 <= wrf[0] <= 105.0) or min(wrf) < 0.0 or wrf[-1] > 10.0
        or abs(wtf[-1] - float(w_span)) > 0.25 or abs(wrf[-1] - float(w_tail)) > 0.5
        or not (float(w_span) >= 15.0 and 0.0 <= float(w_tail) <= 10.0 and 80.0 <= float(w_mass) <= 120.0)
    ):
        return False
    # Exact raw crossing brackets for 50% (t50) and 10% (t90), enforcing no subsequent rebound!
    t50_lo = t50_hi = None
    t90_lo = t90_hi = None
    for i in range(len(wtf)):
        if t50_lo is None and wrf[i] <= 50.0 + 1e-9:
            if abs(wrf[i] - 50.0) <= 1e-9:
                t50_lo = t50_hi = wtf[i]
            elif i > 0:
                t50_lo, t50_hi = wtf[i - 1], wtf[i]
        if t90_lo is None and wrf[i] <= 10.0 + 1e-9:
            if abs(wrf[i] - 10.0) <= 1e-9:
                t90_lo = t90_hi = wtf[i]
            elif i > 0:
                t90_lo, t90_hi = wtf[i - 1], wtf[i]
    if t50_lo is None or t50_hi is None or t90_lo is None or t90_hi is None:
        return False
    # Reject any rebound back above 50% after t50_hi or above 10% after t90_hi
    if any(wrf[i] > 50.0 + 1e-9 for i in range(len(wtf)) if wtf[i] > t50_hi + 1e-9):
        return False
    if any(wrf[i] > 10.0 + 1e-9 for i in range(len(wtf)) if wtf[i] > t90_hi + 1e-9):
        return False
    if t50_hi > 4.50 + 1e-9 or t90_hi > 11.0 + 1e-9:
        return False
    if not (t50_lo - 1e-6 <= float(w_t50) <= t50_hi + 1e-6) or not (t90_lo - 1e-6 <= float(w_t90) <= t90_hi + 1e-6):
        return False
    if not (0.0 < float(w_t50) <= 4.50 and float(w_t50) <= float(w_t90) <= 11.0):
        return False
    # Trapezoidal mean transit time (area under normalized remaining-peak curve)
    area = sum(0.5 * (wrf[i - 1] + wrf[i]) * (wtf[i] - wtf[i - 1]) for i in range(1, len(wtf)))
    mtt_recomp = area / wrf[0]
    if not (0.0 < mtt_recomp <= 5.50 and 0.0 < float(w_mean) <= 5.50 and abs(float(w_mean) - mtt_recomp) <= 0.30):
        return False
    return True


def _check_allowed_keys(rec: Mapping[str, Any], allowed: FrozenSet[str], fails: list[str], tag: str) -> None:
    extra = sorted(k for k in rec.keys() if k not in allowed)
    if extra:
        fails.append(f"FAIL_{tag}_UNKNOWN_OR_UNRECONCILED_FIELDS:{','.join(extra[:4])}")


def _check_forbidden_keys(rec: Mapping[str, Any], forbidden: FrozenSet[str], fails: list[str], code: str) -> None:
    present = sorted(k for k in forbidden if k in rec)
    if present:
        fails.append(f"{code}:{','.join(present[:4])}")


def _validate_structured_exclusions(
    excl_log: Any,
    *,
    expected_n: int,
    analyzed_ids_norm: set[str],
    id_key: str,
    fails: list[str],
    prefix: str,
    require_arm: bool = False,
    require_timing_and_ae: bool = False,
    forbid_adverse_event_related: bool = False,
    min_ts: Optional[datetime] = None,
    max_ts: Optional[datetime] = None,
) -> bool:
    """Validate structured exclusion records (no nulls, allowed reason, pre-adjudication, timing, AE linkage, disjoint IDs)."""
    if not isinstance(excl_log, list) or len(excl_log) != expected_n:
        fails.append(f"FAIL_{prefix}_EXCLUSION_LOG_LENGTH_MISMATCH"); return False
    ok = True
    seen_exc: set[str] = set()
    allowed = frozenset({id_key, "reason", "pre_adjudication_decision"})
    if require_arm:
        allowed = allowed | frozenset({"arm"})
    if require_timing_and_ae:
        allowed = allowed | frozenset({"excluded_at_utc", "adverse_event_related", "adverse_event_code"})
    for idx, erow in enumerate(excl_log):
        if not isinstance(erow, Mapping):
            fails.append(f"FAIL_{prefix}_MALFORMED_OR_NULL_EXCLUSION_ROW:{idx}"); ok = False; continue
        _check_allowed_keys(erow, allowed, fails, f"{prefix}_EXCL_{idx}")
        raw_id = erow.get(id_key)
        if not is_nonempty_str(raw_id):
            fails.append(f"FAIL_{prefix}_EXCLUSION_MISSING_ID:{idx}"); ok = False; continue
        nid = str(raw_id).strip().upper()
        if nid in seen_exc or nid in analyzed_ids_norm:
            fails.append(f"FAIL_{prefix}_EXCLUSION_DUPLICATE_OR_OVERLAPPING_ID:{nid}"); ok = False
        seen_exc.add(nid)
        if erow.get("reason") not in ALLOWED_EXCLUSION_REASONS:
            fails.append(f"FAIL_{prefix}_EXCLUSION_UNALLOWED_REASON:{nid}"); ok = False
        if not (is_strict_bool(erow.get("pre_adjudication_decision")) and erow["pre_adjudication_decision"]):
            fails.append(f"FAIL_{prefix}_EXCLUSION_NOT_PRE_ADJUDICATED:{nid}"); ok = False
        if require_arm and erow.get("arm") not in ("COATED", "BLANK_VEHICLE"):
            fails.append(f"FAIL_{prefix}_EXCLUSION_INVALID_ARM:{nid}"); ok = False
        if require_timing_and_ae:
            t_ex = parse_utc_iso_ts(erow.get("excluded_at_utc"))
            if t_ex is None or (min_ts is not None and t_ex < min_ts) or (max_ts is not None and t_ex > max_ts):
                fails.append(f"FAIL_{prefix}_EXCLUSION_TIMESTAMP_INVALID:{nid}"); ok = False
            ae_rel = erow.get("adverse_event_related")
            ae_code = erow.get("adverse_event_code")
            if not is_strict_bool(ae_rel) or not is_nonempty_str(ae_code):
                fails.append(f"FAIL_{prefix}_EXCLUSION_MISSING_AE_LINKAGE:{nid}"); ok = False
            elif ae_rel is True:
                if str(ae_code).strip().upper() == "NONE":
                    fails.append(f"FAIL_{prefix}_EXCLUSION_AE_TRUE_REQUIRES_NON_NONE_CODE:{nid}"); ok = False
                if forbid_adverse_event_related:
                    fails.append(f"FAIL_{prefix}_ADVERSE_EVENT_RELATED_EXCLUSION:{nid}"); ok = False
    return ok


def _extract_and_validate_coating_identity(
    ev: Mapping[str, Any],
    *,
    expected: Optional[Mapping[str, str]],
    fails: list[str],
    stage: str,
) -> Optional[dict[str, str]]:
    """Verify shared coating article, formulation revision, coating lot, blank vehicle, exposure protocol, & API batch."""
    out: dict[str, str] = {}
    for k in sorted(COATING_IDENTITY_KEYS):
        v = ev.get(k)
        if not is_nonempty_str(v):
            fails.append(f"FAIL_{stage}_MISSING_COATING_IDENTITY:{k}")
            return None
        out[k] = str(v).strip()
    if out["coating_lot_id"] == out["matched_blank_vehicle_lot_id"]:
        fails.append(f"FAIL_{stage}_COATING_AND_BLANK_VEHICLE_LOT_IDENTICAL")
    if expected is not None:
        for k, exp_v in expected.items():
            if out.get(k) != exp_v:
                fails.append(f"FAIL_{stage}_COATING_IDENTITY_MISMATCH:{k}")
    return out


def _validate_oq012_gate34_clonogenic_block(
    ev: Any,
    *,
    fails: list[str],
    holds: list[str],
    prefix: str,
) -> bool:
    """
    Canonical GATE-34 / OQ-012 rare-escape clonogenic switch block:
      - strict integer survivors_k == 0
      - strict integer raw_cells_tested (1 <= n <= 1e12)
      - measured clonogenic_fraction_f in (0, 1] and detection_efficiency_eta in [0.30, 1.0]
        (missing recovery terms -> HOLD)
      - strict integer effective_trials_n_eff <= floor(raw_cells_tested * f * eta)
      - n_eff >= 299,573,228 (underpowered -> HOLD)
      - regrowth_assay_verified == True
      - exact 75-digit Decimal U95(0, n_eff) <= 1e-8 reconciled against clonogenic_escape_u95
    """
    if not isinstance(ev, Mapping):
        holds.append(f"HOLD_{prefix}_OQ012_BLOCK_MISSING")
        return False
    allowed = frozenset({
        "survivors_k", "raw_cells_tested", "clonogenic_fraction_f",
        "detection_efficiency_eta", "effective_trials_n_eff",
        "regrowth_assay_verified", "clonogenic_escape_u95",
    })
    _check_allowed_keys(ev, allowed, fails, f"{prefix}_OQ012")
    k = ev.get("survivors_k")
    raw_n = ev.get("raw_cells_tested")
    f_clon = ev.get("clonogenic_fraction_f")
    eta = ev.get("detection_efficiency_eta")
    n_eff = ev.get("effective_trials_n_eff")
    regrowth = ev.get("regrowth_assay_verified")
    u95_sub = ev.get("clonogenic_escape_u95")
    ok = True

    if not is_strict_int(k) or int(k) < 0:
        fails.append(f"FAIL_{prefix}_OQ012_INVALID_SURVIVOR_COUNT"); return False
    if int(k) > 0:
        fails.append(f"FAIL_{prefix}_OQ012_NONZERO_SURVIVORS"); ok = False
    if not is_strict_int(raw_n) or not (1 <= int(raw_n) <= MAX_CLONOGENIC_CELLS):
        fails.append(f"FAIL_{prefix}_OQ012_INVALID_RAW_CELLS_TESTED"); return False
    if not is_strict_bool(regrowth) or not regrowth:
        fails.append(f"FAIL_{prefix}_OQ012_REGROWTH_ASSAY_UNVERIFIED"); ok = False

    f_dec = _to_exact_decimal(f_clon)
    eta_dec = _to_exact_decimal(eta)
    if f_dec is None or eta_dec is None:
        holds.append(f"HOLD_{prefix}_OQ012_INCOMPLETE_RECOVERY_DENOMINATOR"); return False
    if not (Decimal(0) < f_dec <= Decimal(1)):
        fails.append(f"FAIL_{prefix}_OQ012_CLONOGENIC_FRACTION_OUT_OF_RANGE"); return False
    if not (Decimal("0.30") <= eta_dec <= Decimal(1)):
        fails.append(f"FAIL_{prefix}_OQ012_DETECTION_ETA_OUT_OF_RANGE"); return False
    if not is_strict_int(n_eff) or int(n_eff) < 1:
        fails.append(f"FAIL_{prefix}_OQ012_INVALID_INTEGER_EFFECTIVE_TRIALS"); return False

    # Exact rational product before flooring (eliminates ambient 28-digit Decimal rounding drift at boundary!)
    max_n_eff = math.floor(Fraction(int(raw_n)) * Fraction(f_dec) * Fraction(eta_dec))
    if int(n_eff) > max_n_eff:
        fails.append(f"FAIL_{prefix}_OQ012_NEFF_EXCEEDS_FLOOR_N_F_ETA"); return False
    if int(n_eff) < GATE5_OQ012_MIN_EFFECTIVE_TRIALS:
        holds.append(f"HOLD_{prefix}_OQ012_UNDERPOWERED_NEFF_LT_299573228"); return False

    u95_dec = recompute_clopper_pearson_u95_decimal_n_eff(int(n_eff))
    sub_dec = _to_exact_decimal(u95_sub)
    if sub_dec is None or abs(sub_dec - u95_dec) > Decimal("1e-12"):
        fails.append(f"FAIL_{prefix}_OQ012_U95_MISMATCH_VS_EXACT_DECIMAL"); ok = False
    if u95_dec > Decimal("1e-8"):
        fails.append(f"FAIL_{prefix}_OQ012_U95_EXCEEDS_1E_8"); ok = False
    return ok


def _validate_matched_control_switch_parity(
    parity_ev: Any,
    *,
    expected_control_lot_id: Optional[str],
    fails: list[str],
    holds: list[str],
    prefix: str,
) -> bool:
    """
    Content-hashed, data-backed matched-control native safety-switch non-inferiority block
    (supersedes bare Boolean switch-parity checkboxes across GATE-40 A-3, GATE-41 B-4, GATE-42, GATE-43):
      - Bound to comparator_control_lot_id (matched NT or blank-vehicle lot)
      - Raw paired 24-h AND 72-h bulk-kill vectors (n >= 6 blocks)
      - Recomputes exact paired Student-t one-sided 95% lower bound L95(treated - control):
          L95_24h >= -0.05 pp AND L95_72h >= -0.01 pp
      - Reconciles reported l95_24h_pp / l95_72h_pp against recomputed values
      - Requires valid matched control OQ-012 block (confirming control arm kill assay operated cleanly)
    """
    if parity_ev is None:
        holds.append(f"HOLD_{prefix}_MATCHED_CONTROL_SWITCH_PARITY_MISSING")
        return False
    if not isinstance(parity_ev, Mapping):
        fails.append(f"FAIL_{prefix}_MATCHED_CONTROL_SWITCH_PARITY_MALFORMED")
        return False
    allowed = frozenset({
        "receipt_sha256", "comparator_control_lot_id", "block_ids",
        "treated_24h_kill_pct_by_block", "control_24h_kill_pct_by_block",
        "treated_72h_kill_pct_by_block", "control_72h_kill_pct_by_block",
        "reported_l95_24h_delta_pp", "reported_l95_72h_delta_pp",
        "control_oq012_clonogenic_block",
    })
    _check_allowed_keys(parity_ev, allowed, fails, f"{prefix}_SW_PARITY")
    ok = True
    rsha = parity_ev.get("receipt_sha256")
    if not is_valid_sha256_hex(rsha) or compute_receipt_sha256(parity_ev) != rsha:
        fails.append(f"FAIL_{prefix}_SW_PARITY_CONTENT_HASH_TAMPER"); ok = False
    cid = str(parity_ev.get("comparator_control_lot_id", "")).strip()
    if not cid or (expected_control_lot_id is not None and cid != expected_control_lot_id):
        fails.append(f"FAIL_{prefix}_SW_PARITY_COMPARATOR_LOT_MISMATCH"); ok = False
    bids = parity_ev.get("block_ids")
    if not (isinstance(bids, list) and len(bids) >= 6 and all(is_nonempty_str(b) for b in bids) and len(set(str(b).strip().upper() for b in bids)) == len(bids)):
        fails.append(f"FAIL_{prefix}_SW_PARITY_BLOCKS_LT_6_OR_DUPLICATE"); return False
    n = len(bids)
    for tag_h, tk, ck, rk, margin in (
        ("24H", "treated_24h_kill_pct_by_block", "control_24h_kill_pct_by_block", "reported_l95_24h_delta_pp", -0.05),
        ("72H", "treated_72h_kill_pct_by_block", "control_72h_kill_pct_by_block", "reported_l95_72h_delta_pp", -0.01),
    ):
        tv = parity_ev.get(tk)
        cv = parity_ev.get(ck)
        rv = parity_ev.get(rk)
        if not (isinstance(tv, list) and isinstance(cv, list) and len(tv) == n and len(cv) == n and all(is_finite_num(x) and 0.0 <= float(x) <= 100.0 for x in tv + cv)):
            fails.append(f"FAIL_{prefix}_SW_PARITY_{tag_h}_VECTORS_INVALID"); ok = False; continue
        diffs = [float(tv[i]) - float(cv[i]) for i in range(n)]
        st = paired_t_summary(diffs)
        if st is None:
            # All-equal zero-variance diffs: L95 equals exact mean diff if mean >= margin
            l95_calc = diffs[0]
        else:
            l95_calc = st[3]
        if not is_finite_num(rv) or abs(float(rv) - l95_calc) > 1e-4:
            fails.append(f"FAIL_{prefix}_SW_PARITY_{tag_h}_L95_MISMATCH"); ok = False
        if l95_calc < margin:
            fails.append(f"FAIL_{prefix}_SW_PARITY_{tag_h}_NONINFERIORITY_MARGIN_FAILED"); ok = False
    if not _validate_oq012_gate34_clonogenic_block(parity_ev.get("control_oq012_clonogenic_block"), fails=fails, holds=holds, prefix=f"{prefix}_CTRL"):
        ok = False
    return ok


def _validate_content_receipt(
    ev: Any,
    *,
    expected_stage: str,
    expected_prod: Optional[str],
    expected_bank: Optional[str],
    expected_lot: Optional[str],
    expected_route: Optional[str],
    forbid_route: bool = False,
    expected_scope: Optional[str] = None,
    expected_candidate_gene: Optional[str] = None,
    expected_comparator_nt_lot_id: Optional[str] = None,
    expected_coating_identity: Optional[Mapping[str, str]] = None,
    expected_parent: Optional[Mapping[str, Any]] = None,
    min_prereq_receipts: Sequence[tuple[str, Optional[Mapping[str, Any]]]] = (),
    allowed_extra_keys: FrozenSet[str] = frozenset(),
    fails: list[str],
    holds: list[str],
    missing_hold: str,
    fail_code: str,
    mismatch_code: str,
) -> Optional[Mapping[str, Any]]:
    if ev is None:
        holds.append(missing_hold)
        return None
    if not isinstance(ev, Mapping):
        fails.append(f"{mismatch_code}_MALFORMED")
        return None

    base_keys = frozenset({
        "stage", "verdict", "receipt_sha256", "recorded_at_utc",
        "product_id", "bank_id", "lot_id", "route_id", "evidence_scope",
        "parent_receipt_sha256", "prerequisite_receipt_sha256s",
        "candidate_gene", "comparator_nt_lot_id",
    }) | (COATING_IDENTITY_KEYS if expected_coating_identity is not None else frozenset())
    _check_allowed_keys(ev, base_keys | allowed_extra_keys, fails, expected_stage.replace("-", "_"))

    rsha = ev.get("receipt_sha256")
    if not is_valid_sha256_hex(rsha):
        fails.append(f"FAIL_INVALID_RECEIPT_SHA256:{expected_stage}")
    else:
        if compute_receipt_sha256(ev) != rsha:
            fails.append(f"FAIL_RECEIPT_CONTENT_HASH_TAMPER:{expected_stage}")

    ts = parse_utc_iso_ts(ev.get("recorded_at_utc"))
    if ts is None:
        fails.append(f"FAIL_INVALID_RECORDED_AT_UTC:{expected_stage}")

    if ev.get("stage") != expected_stage:
        fails.append(f"{mismatch_code}_STAGE")
    if expected_scope is not None and ev.get("evidence_scope") != expected_scope:
        fails.append(f"FAIL_EVIDENCE_SCOPE_MISMATCH:{expected_stage}")
    if expected_prod is not None and ev.get("product_id") != expected_prod:
        fails.append(f"{mismatch_code}_PRODUCT")
    if expected_bank is not None and ev.get("bank_id") != expected_bank:
        fails.append(f"{mismatch_code}_BANK")
    if expected_lot is not None and ev.get("lot_id") != expected_lot:
        fails.append(f"{mismatch_code}_LOT")
    if forbid_route:
        if "route_id" in ev and ev["route_id"] is not None:
            fails.append(f"FAIL_ROUTE_AGNOSTIC_RECEIPT_MUST_NOT_BIND_ROUTE:{expected_stage}")
    elif expected_route is not None and str(ev.get("route_id", "")).strip().upper() != expected_route:
        fails.append(f"{mismatch_code}_ROUTE")

    if expected_candidate_gene is not None and ev.get("candidate_gene") != expected_candidate_gene:
        fails.append(f"FAIL_INTERVENTION_CANDIDATE_MISMATCH:{expected_stage}")
    if expected_comparator_nt_lot_id is not None:
        if not is_nonempty_str(ev.get("comparator_nt_lot_id")) or str(ev["comparator_nt_lot_id"]).strip() != expected_comparator_nt_lot_id:
            fails.append(f"FAIL_COMPARATOR_NT_LOT_MISMATCH:{expected_stage}")

    if expected_coating_identity is not None:
        _extract_and_validate_coating_identity(ev, expected=expected_coating_identity, fails=fails, stage=expected_stage)

    if expected_parent is not None:
        p_sha = expected_parent.get("receipt_sha256")
        if ev.get("parent_receipt_sha256") != p_sha:
            fails.append(f"FAIL_PARENT_RECEIPT_CHAIN_MISMATCH:{expected_stage}")
        p_ts = parse_utc_iso_ts(expected_parent.get("recorded_at_utc"))
        if ts is not None and p_ts is not None and ts < p_ts:
            fails.append(f"FAIL_CHRONOLOGICAL_TIMESTAMP_ORDER_VIOLATION:{expected_stage}")

    if min_prereq_receipts:
        prereq_map = ev.get("prerequisite_receipt_sha256s")
        if not isinstance(prereq_map, Mapping):
            fails.append(f"FAIL_MISSING_PREREQUISITE_RECEIPT_DIGEST_MAP:{expected_stage}")
        else:
            for pr_name, pr_ev in min_prereq_receipts:
                if pr_ev is None:
                    continue
                if prereq_map.get(pr_name) != pr_ev.get("receipt_sha256"):
                    fails.append(f"FAIL_PREREQ_RECEIPT_DIGEST_BINDING_MISMATCH:{pr_name}_IN_{expected_stage}")
                pr_ts = parse_utc_iso_ts(pr_ev.get("recorded_at_utc"))
                if ts is not None and pr_ts is not None and ts < pr_ts:
                    fails.append(f"FAIL_CHRONOLOGICAL_PREREQ_POSTDATES_STAGE:{pr_name}_AFTER_{expected_stage}")

    v = ev.get("verdict")
    if v == "FAIL":
        fails.append(fail_code)
    elif v == "HOLD":
        holds.append(f"HOLD_{expected_stage}_IN_HOLD")
    elif v != "PASS":
        fails.append(f"{mismatch_code}_INVALID_VERDICT")
    return ev


def _validate_readout2_gsis(
    r2: Any,
    *,
    fails: list[str],
    holds: list[str],
    prefix: str,
    expected_comparator_id: Optional[str] = None,
    min_comparator_output_ratio: Optional[float] = None,
    parent_recorded_at_utc: Optional[datetime] = None,
    min_exposure_start_utc: Optional[datetime] = None,
    expected_prod: Optional[str] = None,
    expected_bank: Optional[str] = None,
    expected_lot: Optional[str] = None,
    expected_route: Optional[str] = None,
    expected_specimen_id: Optional[str] = None,
    expected_cohort_id: Optional[str] = None,
    expected_candidate_gene: Optional[str] = None,
    expected_engagement_window_utc: Optional[tuple[Optional[datetime], Optional[datetime]]] = None,
) -> bool:
    """
    Full canonical Playbook Readout-2 + separate Gate 0M + canonical Rule S8 + Gate 0S receipt + Gate Resp-1 + DEC-134 washout
    (docs/STAGE-0-EXECUTION-PLAYBOOK.md:122-126, 339-340; scripts/wetlab_contract.py:12826-12867):
      - Binds dual_clocks_utc.assay_harvest_utc <= parent_recorded_at_utc (rejects future-dated GSIS!)
      - Separates ordinary Readout-2 (t50 <= 3.0 min, 0 < t50 < t90) from Gate 0M (t90 <= 3.0 min when gate0m_applicable/Rule S8 active)
      - Enforces canonical Rule S8 locked analysis plan, explicit window_selection_design, Bonferroni alpha/k or disjoint pilot blocks, & immutable comparator receipt SHA-256
      - Enforces content-hashed scope-matched gate0s_escalation_receipt whenever stored insulin > 138.3 IU (rejects bare boolean bypass!)
      - Recomputes Student-t L95(Z1/Z2/RefAdult/Z2-0.5*RefAdult), U95(tau), & paired Fieller matched-comparator ratio
    """
    if not isinstance(r2, Mapping):
        fails.append(f"FAIL_{prefix}_READOUT2_MISSING_OR_MALFORMED")
        return False
    canonical_mixtures: dict[str, dict[str, Any]] = {
        "REF_60_30_10": {"beta": 0.60, "alpha": 0.30, "delta": 0.10, "is_reference": True},
        "DEC084_M1_70_20_10": {"beta": 0.70, "alpha": 0.20, "delta": 0.10, "is_reference": False},
        "DEC084_M2_70_25_5": {"beta": 0.70, "alpha": 0.25, "delta": 0.05, "is_reference": False},
        "DEC084_M3_80_15_5": {"beta": 0.80, "alpha": 0.15, "delta": 0.05, "is_reference": False},
        "DEC084_M4_80_10_10": {"beta": 0.80, "alpha": 0.10, "delta": 0.10, "is_reference": False},
    }
    allowed_r2 = frozenset({
        "canonical_readout2_producer_sha256", "shared_measurement_record_id",
        "independent_blocks_n", "is_non_reference_mixture",
        "registered_mixture_id", "beta_cell_fraction", "alpha_cell_fraction", "delta_cell_fraction",
        "dec084_matched_age_mixture_receipt",
        "preparation_process_mode", "sorting_performed",
        "dual_clocks_utc", "alk5i_free_maturation_applied",
        "stage7_t3_10nM_and_nac_1mM_retained",
        "post_sort_endocrine_zm447439_regimen", "post_sort_zm447439_uM",
        "vascular_iec_coassembled", "pre_coassembly_iec_vascular_function_verified",
        "zm447439_washout_lcms_uM", "zm447439_wash_cycles", "zm447439_spike_recovery_pct",
        "eta_sort_viable_recovery_pct", "implanted_dose_ieq", "mature_insulin_inventory_iu_per_dose",
        "insulin_inventory_assay_specificity", "assay_cumulative_secreted_iu_equiv",
        "stored_insulin_per_lot_iu", "proinsulin_to_cpeptide_content_ratio_per_lot",
        "within_lot_technical_var_z2",
        "stored_insulin_u95_iu", "stored_insulin_max_lot_iu",
        "gate0s_escalation_cleared", "gate0s_escalation_receipt",
        "z_increment_units", "z_min_floor",
        "matched_comparator_id", "gate0m_applicable",
        "rule_s8_extended_clock_applicable",
        "rule_s8_locked_analysis_plan_id", "rule_s8_candidate_windows_k",
        "rule_s8_window_selection_design", "rule_s8_pilot_block_ids",
        "rule_s8_comparator_receipt_sha256", "rule_s8_earlier_window_records",
        "o2_40_mmhg", "o2_100_mmhg",
        "gate_resp1_inlet_po2_mmhg", "gate_resp1_flow_ul_min", "gate_resp1_dose_ieq",
        "gate_resp1_ocr_pmol_min_ieq", "gate_resp1_flow_dose_record_sha256",
        "gate_resp1_snr", "gate_resp1_po2_drop_mmhg",
        "gate_resp1_blank_drift_mmhg", "gate_resp1_dna_recovery_pct",
        "gate_resp1_ocr_ratio", "gate_resp1_ocr_cv_pct", "gate_resp1_replicates_n",
        "gate_resp1_whole_prep_ocr_record", "gate_resp1_pure_endocrine_ocr_record",
        "cluster_surface_o2_and_morphometry_record",
        "dec134_washout_time_min_series", "dec134_washout_remaining_peak_pct_series",
        "dec134_washout_raw_trace_sha256",
        "dec134_washout_trace_span_min", "dec134_washout_tail_remaining_pct",
        "dec134_washout_mass_recovery_pct", "dec134_washout_t50_min",
        "dec134_washout_mean_transit_min", "dec134_washout_t90_min",
    })
    require_r2_spec_prov = any(x is not None for x in (expected_specimen_id, expected_cohort_id, expected_candidate_gene))
    if require_r2_spec_prov:
        allowed_r2 = allowed_r2 | frozenset({"readout2_specimen_provenance"})
    _check_allowed_keys(r2, allowed_r2, fails, f"{prefix}_READOUT2")
    ok = True

    if not is_valid_sha256_hex(r2.get("canonical_readout2_producer_sha256")):
        fails.append(f"FAIL_{prefix}_READOUT2_MISSING_CANONICAL_PRODUCER_SHA256"); ok = False
    if not is_nonempty_str(r2.get("shared_measurement_record_id")):
        fails.append(f"FAIL_{prefix}_READOUT2_MISSING_SHARED_MEASUREMENT_RECORD_ID"); ok = False

    # Live wetlab_contract.py:12754-12816 Registered Mixture + Measured Composition + DEC-084 Linkage!
    is_mix = r2.get("is_non_reference_mixture")
    reg_mix_id = r2.get("registered_mixture_id")
    if not is_strict_bool(is_mix):
        fails.append(f"FAIL_{prefix}_READOUT2_MISSING_MIXTURE_BOOL"); ok = False
    mix_spec = canonical_mixtures.get(str(reg_mix_id)) if is_nonempty_str(reg_mix_id) else None
    if mix_spec is None:
        fails.append(f"FAIL_{prefix}_READOUT2_UNREGISTERED_OR_MISSING_MIXTURE_ID"); ok = False
    else:
        expected_non_ref = not bool(mix_spec["is_reference"])
        if is_strict_bool(is_mix) and is_mix != expected_non_ref:
            fails.append(f"FAIL_{prefix}_READOUT2_MIXTURE_ID_VS_NONREF_BOOL_MISMATCH"); ok = False
        bf_c, af_c, df_c = r2.get("beta_cell_fraction"), r2.get("alpha_cell_fraction"), r2.get("delta_cell_fraction")
        if not (
            all(is_finite_num(x) for x in (bf_c, af_c, df_c))
            and 0.0 < float(bf_c) <= 1.0 and 0.0 <= float(af_c) <= 1.0 and 0.0 <= float(df_c) <= 1.0
            and 0.95 <= (float(bf_c) + float(af_c) + float(df_c)) <= 1.0 + 1e-6
        ):
            fails.append(f"FAIL_{prefix}_READOUT2_INVALID_MEASURED_ENDOCRINE_COMPOSITION"); ok = False
        else:
            in_band = (
                abs(float(bf_c) - float(mix_spec["beta"])) <= 0.05 + 1e-9
                and abs(float(af_c) - float(mix_spec["alpha"])) <= 0.05 + 1e-9
                and abs(float(df_c) - float(mix_spec["delta"])) <= 0.03 + 1e-9
            )
            if mix_spec["is_reference"]:
                ad_rat = float(af_c) / max(1e-9, float(df_c))
                if not in_band or not (2.0 <= ad_rat <= 4.5):
                    holds.append(f"HOLD_{prefix}_READOUT2_COMPOSITION_DRIFT_REQUIRES_DEC084"); ok = False
            elif not in_band:
                holds.append(f"HOLD_{prefix}_READOUT2_COMPOSITION_OUTSIDE_DEC084_TOLERANCE"); ok = False
        if expected_non_ref:
            d84_ev = _validate_content_receipt(
                r2.get("dec084_matched_age_mixture_receipt"),
                expected_stage="DEC-084-MIXTURE",
                expected_prod=expected_prod, expected_bank=expected_bank,
                expected_lot=expected_lot, expected_route=expected_route,
                forbid_route=(expected_route is None),
                expected_scope="exact_product",
                allowed_extra_keys=frozenset({
                    "registered_mixture_id", "canonical_dec084_producer_sha256", "canonical_dec084_verdict",
                }),
                fails=fails, holds=holds,
                missing_hold=f"HOLD_{prefix}_READOUT2_DEC084_MATCHED_AGE_MIXTURE_RECEIPT_MISSING",
                fail_code=f"FAIL_{prefix}_READOUT2_DEC084_MIXTURE_RECEIPT_FAILED",
                mismatch_code=f"FAIL_{prefix}_READOUT2_DEC084_MIXTURE_SCOPE_MISMATCH",
            )
            if d84_ev is None:
                ok = False
            else:
                t_d84 = parse_utc_iso_ts(d84_ev.get("recorded_at_utc"))
                if parent_recorded_at_utc is not None and t_d84 is not None and t_d84 > parent_recorded_at_utc:
                    fails.append(f"FAIL_{prefix}_READOUT2_DEC084_RECEIPT_POSTDATES_PARENT"); ok = False
                if (
                    d84_ev.get("registered_mixture_id") != reg_mix_id
                    or not is_valid_sha256_hex(d84_ev.get("canonical_dec084_producer_sha256"))
                    or d84_ev.get("canonical_dec084_verdict") != "PASS"
                ):
                    fails.append(f"FAIL_{prefix}_READOUT2_DEC084_MIXTURE_VERDICT_OR_ID_MISMATCH"); ok = False

    n_blk = r2.get("independent_blocks_n")
    min_blk = 8 if (is_mix is True or (mix_spec is not None and not mix_spec["is_reference"])) else 6
    if not is_strict_int(n_blk) or int(n_blk) < min_blk:
        fails.append(f"FAIL_{prefix}_READOUT2_INDEPENDENT_BLOCKS_LT_{min_blk}"); ok = False
    n_expected = int(n_blk) if is_strict_int(n_blk) and int(n_blk) >= min_blk else min_blk

    # Live wetlab_contract.py:12512-12513, 13043-13085, & 13232-13234 Process Mode, Dual-Clock Minima & Extended Classifier!
    proc_mode = r2.get("preparation_process_mode")
    sorting_perf = r2.get("sorting_performed")
    if proc_mode not in ("SORTED_REAGGREGATED", "UNSORTED_CONTROL") or not is_strict_bool(sorting_perf):
        holds.append(f"HOLD_{prefix}_READOUT2_MISSING_OR_INVALID_PROCESS_SORTING_MODE"); ok = False
    elif (proc_mode == "SORTED_REAGGREGATED" and sorting_perf is not True) or (
        proc_mode == "UNSORTED_CONTROL" and sorting_perf is not False
    ):
        fails.append(f"FAIL_{prefix}_READOUT2_SORTING_MODE_BOOLEAN_CONTRADICTION"); ok = False

    clks = r2.get("dual_clocks_utc")
    extended_clock_detected = False
    t_hv: Optional[datetime] = None
    if not isinstance(clks, Mapping) or set(clks.keys()) != {"stage7_start_utc", "sort_reaggregation_utc", "assay_harvest_utc"}:
        fails.append(f"FAIL_{prefix}_READOUT2_MISSING_DUAL_CLOCKS_UTC"); ok = False
    else:
        t_s7 = parse_utc_iso_ts(clks.get("stage7_start_utc"))
        t_sr = parse_utc_iso_ts(clks.get("sort_reaggregation_utc"))
        t_hv = parse_utc_iso_ts(clks.get("assay_harvest_utc"))
        if t_s7 is None or t_sr is None or t_hv is None or not (t_s7 <= t_sr <= t_hv):
            fails.append(f"FAIL_{prefix}_READOUT2_INVALID_DUAL_CLOCKS_ORDER"); ok = False
        else:
            if parent_recorded_at_utc is not None and t_hv > parent_recorded_at_utc:
                fails.append(f"FAIL_{prefix}_READOUT2_ASSAY_HARVEST_POSTDATES_RECEIPT"); ok = False
            if min_exposure_start_utc is not None and t_hv < min_exposure_start_utc:
                fails.append(f"FAIL_{prefix}_READOUT2_ASSAY_HARVEST_PREDATES_EXPOSURE_START"); ok = False
            s7_total_days = (t_hv - t_s7).total_seconds() / 86400.0
            s7_sort_days = (t_sr - t_s7).total_seconds() / 86400.0
            post_sort_days = (t_hv - t_sr).total_seconds() / 86400.0
            if not (7.0 - 1e-9 <= s7_total_days <= 49.0 + 1e-9):
                fails.append(f"FAIL_{prefix}_READOUT2_STAGE7_DURATION_OUT_OF_7_49D"); ok = False
            if proc_mode == "SORTED_REAGGREGATED":
                if s7_sort_days < 7.0 - 1e-9 or post_sort_days < 5.0 - 1e-9:
                    holds.append(f"HOLD_{prefix}_READOUT2_SORTED_CLOCK_BELOW_MINIMUM_MATURATION_DAYS"); ok = False
            elif proc_mode == "UNSORTED_CONTROL":
                if abs(post_sort_days) > 1e-6 or abs(s7_sort_days - s7_total_days) > 1e-6:
                    holds.append(f"HOLD_{prefix}_READOUT2_UNSORTED_CONTROL_CLOCK_OR_ETA_MISMATCH"); ok = False
            if s7_total_days > 28.0 + 1e-9 or post_sort_days > 14.0 + 1e-9:
                extended_clock_detected = True

    rule_s8_flag = r2.get("rule_s8_extended_clock_applicable")
    if rule_s8_flag is not None and not is_strict_bool(rule_s8_flag):
        fails.append(f"FAIL_{prefix}_READOUT2_INVALID_RULE_S8_FLAG"); ok = False
    need_rule_s8 = extended_clock_detected or (rule_s8_flag is True)
    g0m_flag = r2.get("gate0m_applicable")
    if g0m_flag is not None and not is_strict_bool(g0m_flag):
        fails.append(f"FAIL_{prefix}_READOUT2_INVALID_GATE0M_FLAG"); ok = False
    # Matches live wetlab_contract.py:13143-13175: full Gate 0M (t90 <= 3.0 min, Basal1/Peak1 <= 0.15, Low2 washout,
    # and paracrine L95s) is ALWAYS enforced on dynamic perifusion Readout-2 without a gate0m_applicable=False bypass!
    gate0m_active = True

    # Canonical Rule S8 locked plan, multiplicity design, & disjoint pilot check (wetlab_contract.py:12826-12867)
    alpha_s8 = 0.05
    s8_pilot_ids_norm: set[str] = set()
    if need_rule_s8:
        lp_id = r2.get("rule_s8_locked_analysis_plan_id")
        k_win = r2.get("rule_s8_candidate_windows_k")
        w_des = r2.get("rule_s8_window_selection_design")
        c_sha = r2.get("rule_s8_comparator_receipt_sha256")
        if not (is_nonempty_str(lp_id) and len(str(lp_id).strip()) >= 4):
            holds.append(f"HOLD_{prefix}_READOUT2_RULE_S8_MISSING_LOCKED_ANALYSIS_PLAN"); ok = False
        if not is_valid_sha256_hex(c_sha):
            holds.append(f"HOLD_{prefix}_READOUT2_RULE_S8_MISSING_COMPARATOR_PROVENANCE_SHA256"); ok = False
        if not (is_strict_int(k_win) and 1 <= int(k_win) <= 5):
            holds.append(f"HOLD_{prefix}_READOUT2_RULE_S8_INVALID_CANDIDATE_WINDOWS_K"); ok = False
        elif w_des == "SINGLE_PRESPECIFIED_PRIMARY":
            if int(k_win) != 1:
                holds.append(f"HOLD_{prefix}_READOUT2_RULE_S8_WINNERS_CURSE_MULTIWINDOW_UNADJUSTED"); ok = False
            alpha_s8 = 0.05
        elif w_des == "PILOT_SCREEN_THEN_DISJOINT_CONFIRMATION":
            p_ids = r2.get("rule_s8_pilot_block_ids")
            if not (isinstance(p_ids, list) and len(p_ids) >= 3 and all(is_nonempty_str(x) for x in p_ids) and len({str(x).strip().upper() for x in p_ids}) == len(p_ids)):
                holds.append(f"HOLD_{prefix}_READOUT2_RULE_S8_MISSING_DISJOINT_PILOT_BLOCKS"); ok = False
            else:
                s8_pilot_ids_norm = {str(x).strip().upper() for x in p_ids}
            alpha_s8 = 0.05
        elif w_des == "MULTI_WINDOW_CONFIRMATION_BONFERRONI":
            if int(k_win) < 2:
                holds.append(f"HOLD_{prefix}_READOUT2_RULE_S8_INVALID_BONFERRONI_K_LT_2"); ok = False
            else:
                alpha_s8 = 0.05 / float(k_win)
        else:
            holds.append(f"HOLD_{prefix}_READOUT2_RULE_S8_UNDECLARED_WINDOW_SELECTION_DESIGN"); ok = False

    # Live wetlab_contract.py:13086-13125 Stage-7 Pharmacology (ALK5i-free + T3/NAC + ZM447439 Regimen + Pre-iEC Washout & Vascular Check!)
    if not (is_strict_bool(r2.get("alk5i_free_maturation_applied")) and r2["alk5i_free_maturation_applied"]):
        fails.append(f"FAIL_{prefix}_READOUT2_ALK5I_FREE_NOT_VERIFIED"); ok = False
    if not (is_strict_bool(r2.get("stage7_t3_10nM_and_nac_1mM_retained")) and r2["stage7_t3_10nM_and_nac_1mM_retained"]):
        fails.append(f"FAIL_{prefix}_READOUT2_MISSING_STAGE7_T3_NAC_RETENTION"); ok = False
    zm_reg = r2.get("post_sort_endocrine_zm447439_regimen")
    zm_ps_u = r2.get("post_sort_zm447439_uM")
    if zm_reg not in ("S7W0_ONLY_0UM_POST_SORT", "CONTINUOUS_0P5UM_BALBOA_S7") or not is_finite_num(zm_ps_u):
        fails.append(f"FAIL_{prefix}_READOUT2_MISSING_OR_INVALID_POST_SORT_ZM447439_REGIMEN"); ok = False
    elif zm_reg == "S7W0_ONLY_0UM_POST_SORT" and abs(float(zm_ps_u)) > 1e-9:
        fails.append(f"FAIL_{prefix}_READOUT2_ZM447439_CONCENTRATION_REGIMEN_MISMATCH"); ok = False
    elif zm_reg == "CONTINUOUS_0P5UM_BALBOA_S7" and not (0.45 <= float(zm_ps_u) <= 0.55):
        fails.append(f"FAIL_{prefix}_READOUT2_ZM447439_CONCENTRATION_REGIMEN_MISMATCH"); ok = False
    iec_co = r2.get("vascular_iec_coassembled")
    if not is_strict_bool(iec_co):
        fails.append(f"FAIL_{prefix}_READOUT2_MISSING_VASCULAR_IEC_COASSEMBLY_BOOL"); ok = False
    elif iec_co is True:
        if not (is_strict_bool(r2.get("pre_coassembly_iec_vascular_function_verified")) and r2["pre_coassembly_iec_vascular_function_verified"]):
            fails.append(f"FAIL_{prefix}_READOUT2_MISSING_PRE_COASSEMBLY_IEC_VASCULAR_FUNCTION"); ok = False
    zm_u = r2.get("zm447439_washout_lcms_uM")
    zm_w = r2.get("zm447439_wash_cycles")
    zm_sp = r2.get("zm447439_spike_recovery_pct")
    if not (is_finite_num(zm_u) and 0.0 <= float(zm_u) <= 0.005):
        fails.append(f"FAIL_{prefix}_READOUT2_ZM447439_WASHOUT_GT_0P005UM"); ok = False
    if not (is_strict_int(zm_w) and int(zm_w) >= 3):
        fails.append(f"FAIL_{prefix}_READOUT2_ZM447439_WASH_CYCLES_LT_3"); ok = False
    if not (is_finite_num(zm_sp) and 80.0 <= float(zm_sp) <= 120.0):
        fails.append(f"FAIL_{prefix}_READOUT2_ZM447439_SPIKE_OUT_OF_80_120"); ok = False

    eta_s = r2.get("eta_sort_viable_recovery_pct")
    imp_ieq = r2.get("implanted_dose_ieq")
    inv_iu = r2.get("mature_insulin_inventory_iu_per_dose")
    u95_iu = r2.get("stored_insulin_u95_iu")
    max_iu = r2.get("stored_insulin_max_lot_iu")
    inv_spec = r2.get("insulin_inventory_assay_specificity")
    cum_sec_iu = r2.get("assay_cumulative_secreted_iu_equiv")
    lot_store_iu = r2.get("stored_insulin_per_lot_iu")
    proins_lot = r2.get("proinsulin_to_cpeptide_content_ratio_per_lot")
    tech_var_z2 = r2.get("within_lot_technical_var_z2")
    if not (is_finite_num(eta_s) and 50.0 <= float(eta_s) <= 100.0):
        fails.append(f"FAIL_{prefix}_READOUT2_ETA_SORT_RECOVERY_INVALID_OR_LT_50PCT"); ok = False
    if not (is_finite_num(imp_ieq) and float(imp_ieq) > 0.0):
        holds.append(f"HOLD_{prefix}_READOUT2_MISSING_IMPLANTED_DOSE_IEQ"); ok = False
    if inv_spec != "MATURE_INSULIN_SPECIFIC_LOW_PROINSULIN_CROSSREACTIVITY":
        holds.append(f"HOLD_{prefix}_READOUT2_UNVERIFIED_MATURE_INSULIN_ASSAY_SPECIFICITY"); ok = False
    if not (is_finite_num(cum_sec_iu) and float(cum_sec_iu) >= 0.0):
        holds.append(f"HOLD_{prefix}_READOUT2_MISSING_ASSAY_CUMULATIVE_SECRETED_IU"); ok = False
    if not (is_finite_num(tech_var_z2) and float(tech_var_z2) >= 0.0):
        holds.append(f"HOLD_{prefix}_READOUT2_MISSING_WITHIN_LOT_TECHNICAL_VARIANCE_Z2"); ok = False
    recomp_u95_iu = None
    recomp_max_iu = None
    if not (isinstance(lot_store_iu, list) and len(lot_store_iu) == n_expected and all(is_finite_num(x) and float(x) > 0.0 for x in lot_store_iu)):
        holds.append(f"HOLD_{prefix}_READOUT2_MISSING_PER_LOT_STORED_INSULIN_ARRAY"); ok = False
    else:
        ls_f = [float(x) for x in lot_store_iu]
        sb_st = sample_t_one_sided_bounds(ls_f, alpha=0.05)
        recomp_max_iu = max(ls_f)
        if sb_st is None:
            holds.append(f"HOLD_{prefix}_READOUT2_STORED_INSULIN_ZERO_VARIANCE_UNESTIMABLE"); ok = False
            st_l95 = float("-inf")
            recomp_u95_iu = float("inf")
        else:
            st_l95, recomp_u95_iu = sb_st[1], sb_st[2]
        # Live wetlab_contract.py:12561,13301-13305 exact stored-insulin mass floor (41.5 IU at 300k beta IEQ):
        beta_f_val = float(bf_c) if is_finite_num(bf_c) else 0.60
        imp_ieq_val = float(imp_ieq) if is_finite_num(imp_ieq) and float(imp_ieq) > 0.0 else 500_000.0
        beta_scale = (beta_f_val / 0.60) * (imp_ieq_val / 500_000.0)
        min_phys_iu = max(41.5 * beta_scale, float(cum_sec_iu) if is_finite_num(cum_sec_iu) else 0.0)
        if st_l95 < min_phys_iu:
            holds.append(f"HOLD_{prefix}_READOUT2_STORED_INSULIN_L95_BELOW_MASS_FLOOR"); ok = False
        if is_finite_num(u95_iu) and float(u95_iu) + 0.1 < recomp_u95_iu:
            fails.append(f"FAIL_{prefix}_READOUT2_STORED_INSULIN_U95_UNDERSTATES_RAW_LOTS"); ok = False
        if is_finite_num(max_iu) and float(max_iu) + 1e-6 < recomp_max_iu:
            fails.append(f"FAIL_{prefix}_READOUT2_STORED_INSULIN_MAX_UNDERSTATES_RAW_LOTS"); ok = False
    # Live wetlab_contract.py:12563,13307-13313 exploratory per-lot proinsulin:C-peptide content molar U95 <= 0.10!
    if not (isinstance(proins_lot, list) and len(proins_lot) == n_expected and all(is_finite_num(x) and float(x) >= 0.0 for x in proins_lot)):
        holds.append(f"HOLD_{prefix}_READOUT2_MISSING_PROINSULIN_TO_CPEPTIDE_ARRAY"); ok = False
    else:
        pr_f = [float(x) for x in proins_lot]
        sb_pr = sample_t_one_sided_bounds(pr_f, alpha=0.05)
        if sb_pr is None:
            holds.append(f"HOLD_{prefix}_READOUT2_PROINSULIN_ZERO_VARIANCE_UNESTIMABLE"); ok = False
            pr_u95 = float("inf")
        else:
            pr_u95 = sb_pr[2]
        if pr_u95 > 0.10:
            holds.append(f"HOLD_{prefix}_READOUT2_ELEVATED_PROINSULIN_TO_CPEPTIDE_CONTENT_RATIO"); ok = False
    eff_u95_iu = max(float(u95_iu) if is_finite_num(u95_iu) else 0.0, recomp_u95_iu or 0.0)
    eff_max_iu = max(float(max_iu) if is_finite_num(max_iu) else 0.0, recomp_max_iu or 0.0)
    if not (is_finite_num(inv_iu) and float(inv_iu) > 0.0 and is_finite_num(u95_iu) and float(u95_iu) > 0.0 and is_finite_num(max_iu) and float(max_iu) > 0.0):
        fails.append(f"FAIL_{prefix}_READOUT2_MATURE_INSULIN_INVENTORY_MISSING"); ok = False
    elif float(inv_iu) > 138.3 or eff_u95_iu > 138.3 or eff_max_iu > 138.3:
        # Bare boolean gate0s_escalation_cleared NEVER suffices; require content-hashed scope-matched Gate 0S receipt!
        g0s_raw = r2.get("gate0s_escalation_receipt")
        g0s_ev = _validate_content_receipt(
            g0s_raw,
            expected_stage="GATE-0S-ESCALATION",
            expected_prod=expected_prod, expected_bank=expected_bank,
            expected_lot=expected_lot, expected_route=expected_route,
            forbid_route=(expected_route is None),
            expected_scope="exact_product",
            allowed_extra_keys=frozenset({
                "canonical_gate0s_producer_sha256", "canonical_gate0s_verdict",
                "burst_1h_iu", "dump_24h_fraction", "en_bloc_retrieval_fraction",
            }),
            fails=fails, holds=holds,
            missing_hold=f"HOLD_{prefix}_READOUT2_GATE0S_ESCALATION_REQUIRED_GT_138P3_IU",
            fail_code=f"FAIL_{prefix}_READOUT2_GATE0S_ESCALATION_FAILED",
            mismatch_code=f"FAIL_{prefix}_READOUT2_GATE0S_SCOPE_MISMATCH",
        )
        if g0s_ev is None:
            ok = False
        else:
            t_g0s = parse_utc_iso_ts(g0s_ev.get("recorded_at_utc"))
            if parent_recorded_at_utc is not None and t_g0s is not None and t_g0s > parent_recorded_at_utc:
                fails.append(f"FAIL_{prefix}_READOUT2_GATE0S_RECEIPT_POSTDATES_PARENT"); ok = False
            b1h, d24, enb = g0s_ev.get("burst_1h_iu"), g0s_ev.get("dump_24h_fraction"), g0s_ev.get("en_bloc_retrieval_fraction")
            if not (
                is_valid_sha256_hex(g0s_ev.get("canonical_gate0s_producer_sha256"))
                and g0s_ev.get("canonical_gate0s_verdict") == "PASS"
                and is_finite_num(b1h) and 0.0 <= float(b1h) <= 2.8
                and is_finite_num(d24) and 0.0 <= float(d24) <= 0.15
                and is_finite_num(enb) and 0.99 <= float(enb) <= 1.0
            ):
                fails.append(f"FAIL_{prefix}_READOUT2_GATE0S_QUANTITATIVE_CRITERIA_FAILED"); ok = False

    z_unit = r2.get("z_increment_units")
    z_min_sub = r2.get("z_min_floor")
    locked_zmin = CANONICAL_READOUT2_Z_MIN_BY_UNIT.get(str(z_unit)) if is_nonempty_str(z_unit) else None
    if locked_zmin is None or not is_finite_num(z_min_sub) or abs(float(z_min_sub) - locked_zmin) > 1e-12:
        fails.append(f"FAIL_{prefix}_READOUT2_UNRECOGNIZED_OR_TAMPERED_CANONICAL_Z_MIN_FLOOR"); ok = False

    if expected_comparator_id is not None:
        if r2.get("matched_comparator_id") != expected_comparator_id:
            fails.append(f"FAIL_{prefix}_READOUT2_MATCHED_COMPARATOR_ID_MISMATCH"); ok = False

    blk_allowed = frozenset({
        "block_id", "trace_id", "pulse1_si", "pulse1_peak_to_basal_ratio", "pulse1_peak_time_min",
        "basal1_value", "peak1_value", "low1_value", "high1_value", "low2_value", "high2_value",
        "kcl_value", "eta_sort_viable_recovery",
        "pulse2_si", "z1_increment", "z2_increment", "ref_adult_z2_increment",
        "chamber_tau_min", "tracer_response_valid", "tracer_time_aligned",
        "stepdown_low2_window_min", "stepdown_t50_min", "stepdown_t90_min",
        "glucagon_fold", "glucose_threshold_mM", "ucn3_fraction", "counterregulation_index",
        "matched_control_z2_increment", "matched_control_output_ratio",
        "rule_s8_comparator_z2_increment",
    })
    seen_conf_trace_ids: set[str] = set()
    conf_block_ids_by_o2: dict[str, list[str]] = {}
    s8_comp_by_o2_block: dict[str, dict[str, float]] = {"O2_40": {}, "O2_100": {}}
    o2_40 = r2.get("o2_40_mmhg")
    o2_100 = r2.get("o2_100_mmhg")
    for o2_name, o2_blk in (("O2_40", o2_40), ("O2_100", o2_100)):
        if not isinstance(o2_blk, Mapping) or set(o2_blk.keys()) != {"blocks"}:
            fails.append(f"FAIL_{prefix}_READOUT2_MISSING_OR_MALFORMED_{o2_name}"); ok = False; continue
        blks = o2_blk.get("blocks")
        if not isinstance(blks, list) or len(blks) != n_expected:
            fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_BLOCK_COUNT_MISMATCH"); ok = False; continue
        seen_bids_norm: set[str] = set()
        z1_v: list[float] = []
        z2_v: list[float] = []
        zref_v: list[float] = []
        zdiff_v: list[float] = []
        tau_v: list[float] = []
        t50_v: list[float] = []
        t90_v: list[float] = []
        pkt_v: list[float] = []
        b1_v: list[float] = []
        p1_v: list[float] = []
        l1_v: list[float] = []
        h1_v: list[float] = []
        l2_v: list[float] = []
        h2_v: list[float] = []
        kcl_v: list[float] = []
        eta_v: list[float] = []
        gcg_v: list[float] = []
        gthr_v: list[float] = []
        ucn3_v: list[float] = []
        creg_v: list[float] = []
        mctrl_z2_v: list[float] = []
        s8_comp_v: list[float] = []
        bad_blk = False
        for idx, b in enumerate(blks):
            if not isinstance(b, Mapping):
                fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_MALFORMED_BLOCK:{idx}"); ok = False; bad_blk = True; continue
            _check_allowed_keys(b, blk_allowed, fails, f"{prefix}_READOUT2_{o2_name}_BLK{idx}")
            bid_raw = str(b.get("block_id", "")).strip()
            bid_norm = bid_raw.upper()
            if not bid_norm or bid_norm in seen_bids_norm:
                fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_DUPLICATE_OR_EMPTY_BLOCK_ID"); ok = False; bad_blk = True; continue
            seen_bids_norm.add(bid_norm)
            p1 = b.get("pulse1_si")
            pkb = b.get("pulse1_peak_to_basal_ratio")
            pkt = b.get("pulse1_peak_time_min")
            b1_val = b.get("basal1_value")
            pk1_val = b.get("peak1_value")
            l1_val = b.get("low1_value")
            h1_val = b.get("high1_value")
            l2_val = b.get("low2_value")
            h2_val = b.get("high2_value")
            kcl_val = b.get("kcl_value")
            eta_val = b.get("eta_sort_viable_recovery")
            p2 = b.get("pulse2_si")
            z1 = b.get("z1_increment")
            z2 = b.get("z2_increment")
            zr = b.get("ref_adult_z2_increment")
            tau = b.get("chamber_tau_min")
            trv = b.get("tracer_response_valid")
            tra = b.get("tracer_time_aligned")
            wlow = b.get("stepdown_low2_window_min")
            t50 = b.get("stepdown_t50_min")
            t90 = b.get("stepdown_t90_min")
            gcg = b.get("glucagon_fold")
            gthr = b.get("glucose_threshold_mM")
            ucn3 = b.get("ucn3_fraction")
            creg = b.get("counterregulation_index")
            if not (is_finite_num(p1) and float(p1) >= 3.0):
                fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_PULSE1_SI_LT_3P0"); ok = False
            if not (is_finite_num(pkb) and float(pkb) >= 4.5):
                fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_PEAK_TO_BASAL_LT_4P5"); ok = False
            if not (is_finite_num(pkt) and 0.0 < float(pkt) <= 8.0):
                fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_PEAK_TIME_GT_8MIN"); ok = False
            else:
                pkt_v.append(float(pkt))
            recomp_z1: Optional[float] = None
            recomp_z2: Optional[float] = None
            if not all(is_finite_num(x) and float(x) > 0.0 for x in (b1_val, pk1_val, l1_val, h1_val, l2_val, h2_val, kcl_val, eta_val)):
                fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_MISSING_RAW_PULSE_KCL_OR_ETA_FIELDS"); ok = False; bad_blk = True
            else:
                b1f, pk1f, l1f, h1f, l2f, h2f, kclf, etaf = (
                    float(b1_val), float(pk1_val), float(l1_val), float(h1_val),
                    float(l2_val), float(h2_val), float(kcl_val), float(eta_val),
                )
                if proc_mode == "SORTED_REAGGREGATED" and not (0.05 <= etaf < 0.95):
                    holds.append(f"HOLD_{prefix}_READOUT2_{o2_name}_UNQUALIFIED_SORTED_ETA_RECOVERY"); ok = False
                elif proc_mode == "UNSORTED_CONTROL" and abs(etaf - 1.0) > 1e-9:
                    holds.append(f"HOLD_{prefix}_READOUT2_{o2_name}_UNSORTED_ETA_NEQ_1P0"); ok = False
                if is_finite_num(pkb) and abs((pk1f / b1f) - float(pkb)) > 0.05:
                    fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_PEAK1_OVER_BASAL1_MISMATCH"); ok = False
                recomp_si1 = h1f / l1f
                recomp_si2 = h2f / l2f
                recomp_z1 = etaf * (h1f - l1f)
                recomp_z2 = etaf * (h2f - l2f)
                if is_finite_num(p1) and abs(recomp_si1 - float(p1)) > 0.05:
                    fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_PULSE1_SI_CONTRADICTS_RAW_HIGH1_LOW1"); ok = False
                if recomp_si1 < 3.0:
                    fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_PULSE1_SI_LT_3P0"); ok = False
                if is_finite_num(p2) and abs(recomp_si2 - float(p2)) > 0.05:
                    fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_PULSE2_SI_CONTRADICTS_RAW_HIGH2_LOW2"); ok = False
                if recomp_si2 < 2.0:
                    fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_PULSE2_SI_LT_2P0"); ok = False
                if is_finite_num(z1) and abs(recomp_z1 - float(z1)) > 0.05:
                    fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_Z1_CONTRADICTS_RAW_ETA_HIGH1_LOW1"); ok = False
                if is_finite_num(z2) and abs(recomp_z2 - float(z2)) > 0.05:
                    fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_Z2_CONTRADICTS_RAW_ETA_HIGH2_LOW2"); ok = False
                if gate0m_active:
                    # Live Playbook:125 & wetlab_contract.py:13158-13162 Gate 0M low-basal & washout rules!
                    if (b1f / pk1f) > 0.15 + 1e-9 or (is_finite_num(pkb) and (1.0 / float(pkb)) > 0.15 + 1e-9):
                        fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_GATE0M_BASAL1_OVER_PEAK1_GT_0P15"); ok = False
                    if (l2f / pk1f) > 0.15 + 1e-9 or (l2f / l1f) > 1.50 + 1e-9:
                        fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_GATE0M_LOW2_WASHOUT_FAILED"); ok = False
                b1_v.append(b1f); p1_v.append(pk1f); l1_v.append(l1f); h1_v.append(h1f)
                l2_v.append(l2f); h2_v.append(h2f); kcl_v.append(kclf); eta_v.append(etaf)
            if not (is_finite_num(p2) and float(p2) >= 2.0):
                fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_PULSE2_SI_LT_2P0"); ok = False
            if not (is_finite_num(tau) and 0.0 < float(tau) <= 0.50 and is_strict_bool(trv) and trv and is_strict_bool(tra) and tra):
                fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_CHAMBER_TRACER_OR_DISPERSION_FAILED"); ok = False
            else:
                tau_v.append(float(tau))
            if not (is_finite_num(wlow) and float(wlow) >= 10.0):
                fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_STEPDOWN_WINDOW_CENSORED_LT_10MIN"); ok = False
            if not (is_finite_num(t50) and is_finite_num(t90) and 0.0 < float(t50) < float(t90) and float(t50) <= 3.0):
                fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_SHUTOFF_T50_LE_3MIN_OR_ORDER_FAILED"); ok = False
            else:
                t50_v.append(float(t50)); t90_v.append(float(t90))
            if gate0m_active and is_finite_num(t90) and float(t90) > 3.0:
                fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_GATE0M_SHUTOFF_T90_GT_3MIN_FAILED"); ok = False
            if not (is_finite_num(gcg) and float(gcg) >= 2.0):
                fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_GLUCAGON_FOLD_LT_2P0"); ok = False
            else:
                gcg_v.append(float(gcg))
            if not (is_finite_num(gthr) and float(gthr) >= 4.5):
                fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_GLUCOSE_THRESHOLD_LT_4P5MM"); ok = False
            else:
                gthr_v.append(float(gthr))
            if not (is_finite_num(ucn3) and 0.70 <= float(ucn3) <= 1.0):
                fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_UCN3_FRACTION_LT_0P70"); ok = False
            else:
                ucn3_v.append(float(ucn3))
            if not (is_finite_num(creg) and 0.80 <= float(creg) <= 2.0):
                fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_COUNTERREGULATION_LT_0P80"); ok = False
            else:
                creg_v.append(float(creg))
            if recomp_z1 is not None and recomp_z2 is not None and is_finite_num(zr):
                # Live wetlab_contract.py:13204-13214 parity: ALL L95/adult-ref/Fieller bounds use RAW recomputed Z1/Z2!
                z1_v.append(recomp_z1); z2_v.append(recomp_z2); zref_v.append(float(zr))
                zdiff_v.append(recomp_z2 - 0.50 * float(zr))
            else:
                fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_MISSING_BLOCK_INCREMENTS"); ok = False; bad_blk = True
            if min_comparator_output_ratio is not None:
                mcz2 = b.get("matched_control_z2_increment")
                cr = b.get("matched_control_output_ratio")
                if not (is_finite_num(mcz2) and float(mcz2) > 0.0 and recomp_z2 is not None):
                    fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_MISSING_RAW_MATCHED_CTRL_Z2"); ok = False
                else:
                    recomp_r = recomp_z2 / float(mcz2)
                    if cr is not None and (not is_finite_num(cr) or abs(float(cr) - recomp_r) > 5e-3):
                        fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_MATCHED_CTRL_RATIO_MISMATCH"); ok = False
                    if recomp_r < min_comparator_output_ratio:
                        fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_MATCHED_CTRL_OUTPUT_RATIO_BELOW_{int(round(min_comparator_output_ratio*100))}PCT"); ok = False
                    mctrl_z2_v.append(float(mcz2))
            # Unconditional unique trace_id across ALL 2*n_blocks confirmation traces (wetlab_contract.py:13036-13038)!
            tr_id_raw = b.get("trace_id")
            if tr_id_raw is None:
                holds.append(f"HOLD_{prefix}_READOUT2_{o2_name}_MISSING_CONFIRMATION_TRACE_ID"); ok = False
            elif not is_nonempty_str(tr_id_raw) or str(tr_id_raw).strip().upper() in seen_conf_trace_ids:
                fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_DUPLICATE_OR_INVALID_TRACE_ID"); ok = False
            else:
                seen_conf_trace_ids.add(str(tr_id_raw).strip().upper())
            if need_rule_s8:
                s8c = b.get("rule_s8_comparator_z2_increment")
                if not (is_finite_num(s8c) and float(s8c) > 0.0):
                    fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_MISSING_RULE_S8_COMPARATOR_Z2"); ok = False
                else:
                    s8_comp_v.append(float(s8c))
                    s8_comp_by_o2_block[o2_name][bid_norm] = float(s8c)
        conf_block_ids_by_o2[o2_name] = list(seen_bids_norm)

        if eta_v and is_finite_num(eta_s):
            mean_eta_pct = 100.0 * (sum(eta_v) / len(eta_v))
            if abs(mean_eta_pct - float(eta_s)) > 2.0:
                fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_ETA_PCT_MISMATCH_VS_PER_LOT_RECOVERY"); ok = False

        if not bad_blk and locked_zmin is not None and len(z1_v) == n_expected and len(tau_v) == n_expected:
            extra_z2_v = (float(tech_var_z2) / float(n_expected)) if is_finite_num(tech_var_z2) and float(tech_var_z2) >= 0.0 else 0.0
            for nm, vec, evar in (("Z1", z1_v, 0.0), ("Z2", z2_v, extra_z2_v), ("REF_ADULT_Z2", zref_v, 0.0)):
                tb = sample_t_one_sided_bounds(vec, extra_within_var=evar)
                if tb is None or tb[1] < locked_zmin:
                    fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_RECOMPUTED_L95_{nm}_BELOW_ZMIN"); ok = False
            db = sample_t_one_sided_bounds(zdiff_v)
            if db is None or db[1] < 0.0:
                fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_RECOMPUTED_ADULT_REF_HALF_L95_FAILED"); ok = False
            # Live wetlab_contract.py:13128-13133 Integrated SI_1 & KCl Reserve Student-t bounds!
            if len(l1_v) == n_expected and len(h1_v) == n_expected and len(h2_v) == n_expected and len(kcl_v) == n_expected:
                tb_l1 = sample_t_one_sided_bounds(l1_v)
                tb_si1 = sample_t_one_sided_bounds([h1 - 3.0 * lo1 for h1, lo1 in zip(h1_v, l1_v)])
                tb_kh2 = sample_t_one_sided_bounds([kv - h2 for kv, h2 in zip(kcl_v, h2_v)])
                tb_kl2 = sample_t_one_sided_bounds([kv - lo2 for kv, lo2 in zip(kcl_v, l2_v)])
                if tb_l1 is None or tb_l1[1] <= 0.0 or tb_si1 is None or tb_si1[1] < 0.0:
                    fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_INTEGRATED_SI1_L95_BELOW_3P0"); ok = False
                if tb_kh2 is None or tb_kh2[1] <= 0.0 or tb_kl2 is None or tb_kl2[1] <= 0.0:
                    fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_KCL_RESERVE_L95_FAILED"); ok = False
            # Live wetlab_contract.py:13144-13156 Dynamic T50 U95, Peak1/Basal1 L95 >= 4.5, & Peak1 Latency U95 <= 8.0 min!
            if len(t50_v) == n_expected:
                tb_t50 = sample_t_one_sided_bounds(t50_v)
                if tb_t50 is None or tb_t50[2] > 3.0:
                    fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_SHUTOFF_T50_U95_GT_3MIN"); ok = False
            if len(p1_v) == n_expected and len(b1_v) == n_expected:
                tb_p1b = sample_t_one_sided_bounds([pk - 4.5 * b0 for pk, b0 in zip(p1_v, b1_v)])
                if tb_p1b is None or tb_p1b[1] < 0.0:
                    fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_PEAK1_OVER_BASAL1_L95_BELOW_4P5"); ok = False
            if len(pkt_v) == n_expected:
                tb_pkt = sample_t_one_sided_bounds(pkt_v)
                if tb_pkt is None or tb_pkt[2] > 8.0:
                    fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_PEAK1_LATENCY_U95_GT_8MIN"); ok = False
            tb_tau = sample_t_one_sided_bounds(tau_v)
            if tb_tau is None or tb_tau[2] > 0.50:
                fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_RECOMPUTED_TAU_U95_GT_0P50"); ok = False
            if gate0m_active and len(b1_v) == n_expected:
                # Recompute Student-t L95 Gate 0M bounds matching live wetlab_contract.py:13158-13175!
                _g0m_zvar = False
                for gm_vec, gm_code in (
                    ([0.15 * p - b0 for p, b0 in zip(p1_v, b1_v)], f"FAIL_{prefix}_READOUT2_{o2_name}_GATE0M_BASAL1_OVER_PEAK1_L95_FAILED"),
                    ([0.15 * p - lo2 for p, lo2 in zip(p1_v, l2_v)], f"FAIL_{prefix}_READOUT2_{o2_name}_GATE0M_LOW2_OVER_PEAK1_L95_FAILED"),
                    ([1.50 * lo1 - lo2 for lo1, lo2 in zip(l1_v, l2_v)], f"FAIL_{prefix}_READOUT2_{o2_name}_GATE0M_LOW2_OVER_LOW1_L95_FAILED"),
                ):
                    gb = sample_t_one_sided_bounds(gm_vec)
                    if gb is None:
                        _g0m_zvar = True
                        fails.append(gm_code); ok = False
                    elif gb[1] < 0.0:
                        fails.append(gm_code); ok = False
                if len(t90_v) == n_expected:
                    t90_b = sample_t_one_sided_bounds(t90_v)
                    if t90_b is None:
                        _g0m_zvar = True
                        fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_GATE0M_SHUTOFF_T90_U95_GT_3MIN_FAILED"); ok = False
                    elif t90_b[2] > 3.0:
                        fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_GATE0M_SHUTOFF_T90_U95_GT_3MIN_FAILED"); ok = False
                for pvec, pfloor, pcode in (
                    (gcg_v, 2.0, f"FAIL_{prefix}_READOUT2_{o2_name}_GATE0M_PARACRINE_GLUCAGON_L95_FAILED"),
                    (gthr_v, 4.5, f"FAIL_{prefix}_READOUT2_{o2_name}_GATE0M_PARACRINE_THRESHOLD_L95_FAILED"),
                    (ucn3_v, 0.70, f"FAIL_{prefix}_READOUT2_{o2_name}_GATE0M_PARACRINE_UCN3_L95_FAILED"),
                    (creg_v, 0.80, f"FAIL_{prefix}_READOUT2_{o2_name}_GATE0M_PARACRINE_COUNTERREG_L95_FAILED"),
                ):
                    if len(pvec) == n_expected:
                        pb = sample_t_one_sided_bounds(pvec)
                        if pb is None:
                            _g0m_zvar = True
                            fails.append(pcode); ok = False
                        elif pb[1] < pfloor:
                            fails.append(pcode); ok = False
                if _g0m_zvar:
                    holds.append(f"HOLD_{prefix}_READOUT2_{o2_name}_DEGENERATE_ZERO_VARIANCE_UNESTIMABLE")
            if min_comparator_output_ratio is not None and len(mctrl_z2_v) == n_expected:
                fl = fieller_ratio_one_sided_lower(z2_v, mctrl_z2_v, paired=True, alpha=0.05)
                if fl is None or fl[0] < min_comparator_output_ratio or fl[1] < min_comparator_output_ratio:
                    fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_RECOMPUTED_CTRL_FIELLER_L95_BELOW_FLOOR"); ok = False
            # Case-insensitive normalized disjoint pilot intersection (blocks lowercase/uppercase bypass!)
            if need_rule_s8 and s8_pilot_ids_norm and (seen_bids_norm & s8_pilot_ids_norm):
                holds.append(f"HOLD_{prefix}_READOUT2_{o2_name}_RULE_S8_PILOT_CONFIRMATION_OVERLAP"); ok = False
            if need_rule_s8 and len(s8_comp_v) == n_expected:
                tb_e_pos = sample_t_one_sided_bounds(s8_comp_v, alpha=0.05)
                if tb_e_pos is None or (locked_zmin is not None and tb_e_pos[1] < locked_zmin):
                    fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_RULE_S8_EARLIER_WINDOW_BELOW_ZMIN"); ok = False
                fl_s8 = fieller_ratio_one_sided_lower(z2_v, s8_comp_v, paired=True, alpha=alpha_s8)
                if fl_s8 is None or fl_s8[1] < 0.85:
                    fails.append(f"FAIL_{prefix}_READOUT2_{o2_name}_RULE_S8_FIELLER_L95_LT_0P85"); ok = False

    if need_rule_s8:
        # Live wetlab_contract.py:13237-13270 per-lot earlier-window timing & unique trace identity binding!
        e_recs = r2.get("rule_s8_earlier_window_records")
        if not isinstance(e_recs, list) or len(e_recs) != n_expected:
            holds.append(f"HOLD_{prefix}_READOUT2_RULE_S8_MISSING_PER_LOT_EARLIER_WINDOW_RECORDS"); ok = False
        else:
            seen_e_traces: set[str] = set()
            seen_e_b40: set[str] = set()
            seen_e_b100: set[str] = set()
            e_allowed = frozenset({
                "block_id_40mmhg", "block_id_100mmhg", "trace_id_40mmhg", "trace_id_100mmhg",
                "early_harvest_utc", "z2_40mmhg", "z2_100mmhg",
            })
            for idx_e, er in enumerate(e_recs):
                if not isinstance(er, Mapping) or set(er.keys()) != e_allowed:
                    fails.append(f"FAIL_{prefix}_READOUT2_RULE_S8_MALFORMED_EARLIER_RECORD:{idx_e}"); ok = False; continue
                eb40 = str(er.get("block_id_40mmhg", "")).strip().upper()
                eb100 = str(er.get("block_id_100mmhg", "")).strip().upper()
                et40 = str(er.get("trace_id_40mmhg", "")).strip().upper()
                et100 = str(er.get("trace_id_100mmhg", "")).strip().upper()
                t_eh = parse_utc_iso_ts(er.get("early_harvest_utc"))
                ez40, ez100 = er.get("z2_40mmhg"), er.get("z2_100mmhg")
                if (
                    not eb40 or not eb100 or eb40 in seen_e_b40 or eb100 in seen_e_b100
                    or not et40 or not et100 or et40 == et100
                    or et40 in seen_conf_trace_ids or et100 in seen_conf_trace_ids
                    or et40 in seen_e_traces or et100 in seen_e_traces
                    or t_eh is None or (t_hv is not None and t_eh >= t_hv)
                    or not (is_finite_num(ez40) and float(ez40) > 0.0 and is_finite_num(ez100) and float(ez100) > 0.0)
                ):
                    fails.append(f"FAIL_{prefix}_READOUT2_RULE_S8_EARLIER_WINDOW_TIMING_OR_TRACE_INVALID:{idx_e}"); ok = False; continue
                seen_e_b40.add(eb40); seen_e_b100.add(eb100)
                seen_e_traces.add(et40); seen_e_traces.add(et100)
                if eb40 not in s8_comp_by_o2_block["O2_40"] or abs(float(ez40) - s8_comp_by_o2_block["O2_40"][eb40]) > 1e-6:
                    fails.append(f"FAIL_{prefix}_READOUT2_RULE_S8_EARLIER_Z2_40_MISMATCH:{idx_e}"); ok = False
                if eb100 not in s8_comp_by_o2_block["O2_100"] or abs(float(ez100) - s8_comp_by_o2_block["O2_100"][eb100]) > 1e-6:
                    fails.append(f"FAIL_{prefix}_READOUT2_RULE_S8_EARLIER_Z2_100_MISMATCH:{idx_e}"); ok = False

    if isinstance(o2_40, Mapping) and isinstance(o2_100, Mapping) and o2_40.get("blocks") == o2_100.get("blocks"):
        fails.append(f"FAIL_{prefix}_READOUT2_IDENTICAL_COPY_PASTE_40_AND_100MMHG"); ok = False

    if require_r2_spec_prov:
        r2_prov = r2.get("readout2_specimen_provenance")
        r2_prov_keys = frozenset({
            "specimen_id", "specimen_lot_id", "intervention_cohort_id", "candidate_gene",
            "registered_aliquot_ids", "trace_aliquot_links", "provenance_sha256",
        })
        if r2_prov is None:
            holds.append(f"HOLD_{prefix}_READOUT2_MISSING_INTERVENTION_SPECIMEN_LINKAGE"); ok = False
        elif not isinstance(r2_prov, Mapping) or set(r2_prov.keys()) != r2_prov_keys:
            fails.append(f"FAIL_{prefix}_READOUT2_INTERVENTION_SPECIMEN_OR_TRACE_LINK_MISMATCH"); ok = False
        else:
            r2_psha = r2_prov.get("provenance_sha256")
            r2_sp = r2_prov.get("specimen_id")
            r2_lt = r2_prov.get("specimen_lot_id")
            r2_co = r2_prov.get("intervention_cohort_id")
            r2_cg = r2_prov.get("candidate_gene")
            r2_al = r2_prov.get("registered_aliquot_ids")
            r2_tl = r2_prov.get("trace_aliquot_links")
            r2_prov_ok = True
            if (
                not is_valid_sha256_hex(r2_psha)
                or sha256_bytes(canonical_json_bytes({k: v for k, v in r2_prov.items() if k != "provenance_sha256"})) != str(r2_psha)
                or not all(is_nonempty_str(x) for x in (r2_sp, r2_lt, r2_co, r2_cg))
                or not (isinstance(r2_al, list) and len(r2_al) >= 1 and all(is_nonempty_str(a) for a in r2_al))
                or not (isinstance(r2_tl, list) and len(r2_tl) >= 1)
            ):
                r2_prov_ok = False
            else:
                r2_sp_n = str(r2_sp).strip().upper()
                r2_lt_n = str(r2_lt).strip().upper()
                r2_co_n = str(r2_co).strip().upper()
                r2_cg_n = str(r2_cg).strip().upper()
                al_norms_r2 = [str(a).strip().upper() for a in r2_al]
                if (
                    len(set(al_norms_r2)) != len(al_norms_r2)
                    or (is_nonempty_str(expected_specimen_id) and r2_sp_n != str(expected_specimen_id).strip().upper())
                    or (is_nonempty_str(expected_lot) and r2_lt_n != str(expected_lot).strip().upper())
                    or (is_nonempty_str(expected_cohort_id) and r2_co_n != str(expected_cohort_id).strip().upper())
                    or (is_nonempty_str(expected_candidate_gene) and r2_cg_n != str(expected_candidate_gene).strip().upper())
                    or any(not (an == r2_sp_n or an.startswith(f"{r2_sp_n}-")) for an in al_norms_r2)
                ):
                    r2_prov_ok = False
                else:
                    reg_al_set = set(al_norms_r2) | {r2_sp_n}
                    seen_link_tids: set[str] = set()
                    ew_s = expected_engagement_window_utc[0] if expected_engagement_window_utc is not None else None
                    ew_e = expected_engagement_window_utc[1] if expected_engagement_window_utc is not None else None
                    if ew_s is not None and ew_e is not None and ew_s > ew_e:
                        r2_prov_ok = False
                    for tl_row in r2_tl:
                        if not isinstance(tl_row, Mapping) or set(tl_row.keys()) != {"trace_id", "aliquot_id", "collected_at_utc"}:
                            r2_prov_ok = False; break
                        ltid = tl_row.get("trace_id")
                        laid = tl_row.get("aliquot_id")
                        t_col = parse_utc_iso_ts(tl_row.get("collected_at_utc"))
                        if not (is_nonempty_str(ltid) and is_nonempty_str(laid)) or t_col is None:
                            r2_prov_ok = False; break
                        ltid_n = str(ltid).strip().upper()
                        laid_n = str(laid).strip().upper()
                        if ltid_n in seen_link_tids or laid_n not in reg_al_set:
                            r2_prov_ok = False; break
                        if (ew_s is not None and t_col < ew_s) or (ew_e is not None and t_col > ew_e):
                            r2_prov_ok = False; break
                        seen_link_tids.add(ltid_n)
                    if r2_prov_ok and seen_conf_trace_ids and seen_link_tids != seen_conf_trace_ids:
                        r2_prov_ok = False
            if not r2_prov_ok:
                fails.append(f"FAIL_{prefix}_READOUT2_INTERVENTION_SPECIMEN_OR_TRACE_LINK_MISMATCH"); ok = False

    inlet = r2.get("gate_resp1_inlet_po2_mmhg")
    r_flow = r2.get("gate_resp1_flow_ul_min")
    r_ieq = r2.get("gate_resp1_dose_ieq")
    r_ocr_pmol = r2.get("gate_resp1_ocr_pmol_min_ieq")
    r_fd_sha = r2.get("gate_resp1_flow_dose_record_sha256")
    snr = r2.get("gate_resp1_snr")
    drop = r2.get("gate_resp1_po2_drop_mmhg")
    drift = r2.get("gate_resp1_blank_drift_mmhg")
    dna_r = r2.get("gate_resp1_dna_recovery_pct")
    ocr_r = r2.get("gate_resp1_ocr_ratio")
    ocr_cv = r2.get("gate_resp1_ocr_cv_pct")
    ocr_n = r2.get("gate_resp1_replicates_n")
    def _ocr_ratio_u95(ratio_v: float, cv_pct_v: float, n_rep_v: int) -> float:
        # Live wetlab_contract.py:970,3541-3546,4508 Student-t one-sided 95% upper bound with SE >= 0.015 floor!
        se_v = max(0.015, (ratio_v * (cv_pct_v / 100.0)) / math.sqrt(float(n_rep_v)))
        return ratio_v + student_t_one_sided_crit(0.05, float(n_rep_v - 1)) * se_v

    if not (
        is_finite_num(inlet) and 34.0 <= float(inlet) <= 37.5
        and is_finite_num(r_flow) and 100.0 <= float(r_flow) <= 400.0
        and is_finite_num(r_ieq) and 100.0 <= float(r_ieq) <= 500.0
        and is_finite_num(r_ocr_pmol) and 0.0 < float(r_ocr_pmol) <= 4.5479
        and is_valid_sha256_hex(r_fd_sha)
        and is_finite_num(snr) and float(snr) >= 5.0
        and is_finite_num(drop) and float(drop) >= 1.0
        and is_finite_num(drift) and 0.0 <= float(drift) <= 0.5
        and is_finite_num(dna_r) and 85.0 <= float(dna_r) <= 120.0
        and is_finite_num(ocr_r) and 0.0 < float(ocr_r) <= 1.097
        and is_finite_num(ocr_cv) and 0.0 <= float(ocr_cv) <= 3.0
        and is_strict_int(ocr_n) and int(ocr_n) >= 6
    ):
        fails.append(f"FAIL_{prefix}_READOUT2_GATE_RESP1_OCR_FAILED"); ok = False
    else:
        top_ocr_u95 = _ocr_ratio_u95(float(ocr_r), float(ocr_cv), int(ocr_n))
        if top_ocr_u95 > 1.50:
            fails.append(f"FAIL_{prefix}_READOUT2_LOT_OCR_UPPER95_EXCEEDS_1P50X_CEILING"); ok = False
        elif top_ocr_u95 > 1.097:
            holds.append(f"HOLD_{prefix}_READOUT2_LOT_OCR_UPPER95_EXCEEDS_1P097_REQUIRES_S4_DERATING"); ok = False

    # Live Playbook:126 dual specimen-keyed OCR qualification:
    #   whole-preparation OCR <= 4.5479 AND pure-endocrine OCR <= 3.9547 pmol/(min*IEQ),
    #   both bound to tested lot_id + exposure_id with distinct specimen_ids & content hashes!
    ocr_rec_keys = frozenset({
        "specimen_id", "lot_id", "exposure_id",
        "inlet_po2_mmhg", "flow_ul_min", "dose_ieq",
        "ocr_pmol_min_ieq", "ocr_ratio", "ocr_cv_pct", "replicates_n", "record_sha256",
    })
    wp_rec = r2.get("gate_resp1_whole_prep_ocr_record")
    pe_rec = r2.get("gate_resp1_pure_endocrine_ocr_record")
    wp_spec_id: Optional[str] = None
    wp_exp_id: Optional[str] = None
    if wp_rec is None:
        holds.append(f"HOLD_{prefix}_READOUT2_WHOLE_PREP_OCR_RECORD_MISSING"); ok = False
    elif not isinstance(wp_rec, Mapping) or set(wp_rec.keys()) != ocr_rec_keys:
        fails.append(f"FAIL_{prefix}_READOUT2_WHOLE_PREP_OCR_RECORD_MALFORMED"); ok = False
    else:
        wsha = wp_rec.get("record_sha256")
        if not is_valid_sha256_hex(wsha) or sha256_bytes(canonical_json_bytes({k: v for k, v in wp_rec.items() if k != "record_sha256"})) != wsha:
            fails.append(f"FAIL_{prefix}_READOUT2_WHOLE_PREP_OCR_HASH_INVALID"); ok = False
        if not (is_nonempty_str(wp_rec.get("specimen_id")) and is_nonempty_str(wp_rec.get("lot_id")) and is_nonempty_str(wp_rec.get("exposure_id"))):
            fails.append(f"FAIL_{prefix}_READOUT2_WHOLE_PREP_OCR_TRACEABILITY_MISSING"); ok = False
        else:
            wp_spec_id = str(wp_rec["specimen_id"]).strip().upper()
            wp_exp_id = str(wp_rec["exposure_id"]).strip().upper()
            if expected_lot is not None and str(wp_rec["lot_id"]).strip() != expected_lot:
                fails.append(f"FAIL_{prefix}_READOUT2_WHOLE_PREP_OCR_LOT_MISMATCH"); ok = False
        w_ocr = wp_rec.get("ocr_pmol_min_ieq")
        if not (is_finite_num(w_ocr) and 0.0 < float(w_ocr) <= 4.5479):
            fails.append(f"FAIL_{prefix}_READOUT2_WHOLE_PREP_OCR_EXCEEDS_4P5479"); ok = False
        elif is_finite_num(r_ocr_pmol) and abs(float(w_ocr) - float(r_ocr_pmol)) > 1e-4:
            fails.append(f"FAIL_{prefix}_READOUT2_WHOLE_PREP_OCR_SCALAR_MISMATCH"); ok = False
        if not (
            is_finite_num(wp_rec.get("inlet_po2_mmhg")) and 34.0 <= float(wp_rec["inlet_po2_mmhg"]) <= 37.5
            and is_finite_num(wp_rec.get("flow_ul_min")) and 100.0 <= float(wp_rec["flow_ul_min"]) <= 400.0
            and is_finite_num(wp_rec.get("dose_ieq")) and 100.0 <= float(wp_rec["dose_ieq"]) <= 500.0
            and is_finite_num(wp_rec.get("ocr_ratio")) and 0.0 < float(wp_rec["ocr_ratio"]) <= 1.097
            and is_finite_num(wp_rec.get("ocr_cv_pct")) and 0.0 <= float(wp_rec["ocr_cv_pct"]) <= 3.0
            and is_strict_int(wp_rec.get("replicates_n")) and int(wp_rec["replicates_n"]) >= 6
        ):
            fails.append(f"FAIL_{prefix}_READOUT2_WHOLE_PREP_OCR_ASSAY_QC_FAILED"); ok = False
        else:
            wp_u95 = _ocr_ratio_u95(float(wp_rec["ocr_ratio"]), float(wp_rec["ocr_cv_pct"]), int(wp_rec["replicates_n"]))
            if wp_u95 > 1.50:
                fails.append(f"FAIL_{prefix}_READOUT2_WHOLE_PREP_OCR_UPPER95_EXCEEDS_1P50X_CEILING"); ok = False
            elif wp_u95 > 1.097:
                holds.append(f"HOLD_{prefix}_READOUT2_WHOLE_PREP_OCR_UPPER95_EXCEEDS_1P097_REQUIRES_S4_DERATING"); ok = False

    if pe_rec is None:
        holds.append(f"HOLD_{prefix}_READOUT2_PURE_ENDOCRINE_OCR_MISSING"); ok = False
    elif not isinstance(pe_rec, Mapping) or set(pe_rec.keys()) != ocr_rec_keys:
        fails.append(f"FAIL_{prefix}_READOUT2_PURE_ENDOCRINE_OCR_RECORD_MALFORMED"); ok = False
    else:
        psha = pe_rec.get("record_sha256")
        if not is_valid_sha256_hex(psha) or sha256_bytes(canonical_json_bytes({k: v for k, v in pe_rec.items() if k != "record_sha256"})) != psha:
            fails.append(f"FAIL_{prefix}_READOUT2_PURE_ENDOCRINE_OCR_HASH_INVALID"); ok = False
        if not (is_nonempty_str(pe_rec.get("specimen_id")) and is_nonempty_str(pe_rec.get("lot_id")) and is_nonempty_str(pe_rec.get("exposure_id"))):
            fails.append(f"FAIL_{prefix}_READOUT2_PURE_ENDOCRINE_OCR_TRACEABILITY_MISSING"); ok = False
        else:
            pe_spec_id = str(pe_rec["specimen_id"]).strip().upper()
            pe_exp_id = str(pe_rec["exposure_id"]).strip().upper()
            if expected_lot is not None and str(pe_rec["lot_id"]).strip() != expected_lot:
                fails.append(f"FAIL_{prefix}_READOUT2_PURE_ENDOCRINE_OCR_LOT_MISMATCH"); ok = False
            if wp_spec_id is not None and pe_spec_id == wp_spec_id:
                fails.append(f"FAIL_{prefix}_READOUT2_PURE_ENDOCRINE_SPECIMEN_IDENTICAL_TO_WHOLE_PREP"); ok = False
            if wp_exp_id is not None and pe_exp_id != wp_exp_id:
                fails.append(f"FAIL_{prefix}_READOUT2_PURE_ENDOCRINE_EXPOSURE_MISMATCH"); ok = False
        p_ocr = pe_rec.get("ocr_pmol_min_ieq")
        if not (is_finite_num(p_ocr) and 0.0 < float(p_ocr) <= 3.9547):
            fails.append(f"FAIL_{prefix}_READOUT2_PURE_ENDOCRINE_OCR_EXCEEDS_3P9547"); ok = False
        if not (
            is_finite_num(pe_rec.get("inlet_po2_mmhg")) and 34.0 <= float(pe_rec["inlet_po2_mmhg"]) <= 37.5
            and is_finite_num(pe_rec.get("flow_ul_min")) and 100.0 <= float(pe_rec["flow_ul_min"]) <= 400.0
            and is_finite_num(pe_rec.get("dose_ieq")) and 100.0 <= float(pe_rec["dose_ieq"]) <= 500.0
            and is_finite_num(pe_rec.get("ocr_ratio")) and 0.0 < float(pe_rec["ocr_ratio"]) <= 1.097
            and is_finite_num(pe_rec.get("ocr_cv_pct")) and 0.0 <= float(pe_rec["ocr_cv_pct"]) <= 3.0
            and is_strict_int(pe_rec.get("replicates_n")) and int(pe_rec["replicates_n"]) >= 6
        ):
            fails.append(f"FAIL_{prefix}_READOUT2_PURE_ENDOCRINE_OCR_ASSAY_QC_FAILED"); ok = False
        else:
            pe_u95 = _ocr_ratio_u95(float(pe_rec["ocr_ratio"]), float(pe_rec["ocr_cv_pct"]), int(pe_rec["replicates_n"]))
            if pe_u95 > 1.50:
                fails.append(f"FAIL_{prefix}_READOUT2_PURE_ENDOCRINE_OCR_UPPER95_EXCEEDS_1P50X_CEILING"); ok = False
            elif pe_u95 > 1.097:
                holds.append(f"HOLD_{prefix}_READOUT2_PURE_ENDOCRINE_OCR_UPPER95_EXCEEDS_1P097_REQUIRES_S4_DERATING"); ok = False

    # Live Playbook:126 cluster-surface oxygen (pO2 >= 15.0 mmHg, f_GSIS >= 0.858) &
    # post-encapsulation outer-band (z in [50, 175] um) confocal morphometry (D_p90 <= 100 um, sphericity >= 0.78)!
    morph_keys = frozenset({
        "lot_id", "cluster_surface_po2_mmhg", "cluster_surface_f_gsis",
        "outer_band_z_min_um", "outer_band_z_max_um",
        "outer_band_d_p90_um", "outer_band_sphericity_3d", "record_sha256",
    })
    m_rec = r2.get("cluster_surface_o2_and_morphometry_record")
    if m_rec is None:
        holds.append(f"HOLD_{prefix}_READOUT2_MISSING_CLUSTER_SURFACE_O2_MORPHOMETRY"); ok = False
    elif not isinstance(m_rec, Mapping) or set(m_rec.keys()) != morph_keys:
        fails.append(f"FAIL_{prefix}_READOUT2_CLUSTER_SURFACE_O2_MORPHOMETRY_MALFORMED"); ok = False
    else:
        msha = m_rec.get("record_sha256")
        if not is_valid_sha256_hex(msha) or sha256_bytes(canonical_json_bytes({k: v for k, v in m_rec.items() if k != "record_sha256"})) != msha:
            fails.append(f"FAIL_{prefix}_READOUT2_CLUSTER_SURFACE_O2_MORPHOMETRY_HASH_INVALID"); ok = False
        if expected_lot is not None and str(m_rec.get("lot_id", "")).strip() != expected_lot:
            fails.append(f"FAIL_{prefix}_READOUT2_CLUSTER_SURFACE_O2_MORPHOMETRY_LOT_MISMATCH"); ok = False
        if not (
            is_finite_num(m_rec.get("cluster_surface_po2_mmhg")) and float(m_rec["cluster_surface_po2_mmhg"]) >= 15.0
            and is_finite_num(m_rec.get("cluster_surface_f_gsis")) and 0.858 <= float(m_rec["cluster_surface_f_gsis"]) <= 1.0
            and is_finite_num(m_rec.get("outer_band_z_min_um")) and abs(float(m_rec["outer_band_z_min_um"]) - 50.0) <= 1e-6
            and is_finite_num(m_rec.get("outer_band_z_max_um")) and abs(float(m_rec["outer_band_z_max_um"]) - 175.0) <= 1e-6
            and is_finite_num(m_rec.get("outer_band_d_p90_um")) and 0.0 < float(m_rec["outer_band_d_p90_um"]) <= 100.0
            and is_finite_num(m_rec.get("outer_band_sphericity_3d")) and 0.78 <= float(m_rec["outer_band_sphericity_3d"]) <= 1.0
        ):
            fails.append(f"FAIL_{prefix}_READOUT2_CLUSTER_SURFACE_O2_OR_MORPHOMETRY_FAILED"); ok = False

    if not _validate_dec134_washout_trace(
        r2.get("dec134_washout_time_min_series"),
        r2.get("dec134_washout_remaining_peak_pct_series"),
        r2.get("dec134_washout_raw_trace_sha256"),
        r2.get("dec134_washout_trace_span_min"),
        r2.get("dec134_washout_tail_remaining_pct"),
        r2.get("dec134_washout_mass_recovery_pct"),
        r2.get("dec134_washout_t50_min"),
        r2.get("dec134_washout_mean_transit_min"),
        r2.get("dec134_washout_t90_min"),
    ):
        fails.append(f"FAIL_{prefix}_READOUT2_DEC134_WASHOUT_TAIL_FAILED"); ok = False
    return ok


def _validate_readout3b_nk(
    r3b: Any,
    *,
    fails: list[str],
    prefix: str,
    require_sirpa_low: bool = False,
    expected_vehicle_lot_id: Optional[str] = None,
    max_vehicle_delta_pp: Optional[float] = None,
    require_hla_e_spr: bool = True,
    expected_specimen_id: Optional[str] = None,
    expected_lot_id: Optional[str] = None,
    expected_cohort_id: Optional[str] = None,
    holds: Optional[list[str]] = None,
) -> bool:
    """
    Full donor-linked canonical Playbook Readout-3B panel (docs/STAGE-0-EXECUTION-PLAYBOOK.md:160-170):
      - >= 6 unique donors spanning >= 3 CMV_POS and >= 3 CMV_NEG cohorts
      - Each donor carries BOTH Regime I (24-h IFN-gamma) AND Regime II (t=0 un-preinduced + 0-24h kinetic + allogeneic CD8+ CTL)
      - Per-donor numeric positive (>= 25%) & negative (<= 5%) controls
      - Per-donor AND recomputed across-donor Student-t U95_t caps
      - Optional matched blank-vehicle delta check (expected_vehicle_lot_id + per-donor vehicle lysis recomputing
        paired U95(coated - vehicle) <= +2.0 pp per Dossier §5!)
    """
    if not isinstance(r3b, Mapping):
        fails.append(f"FAIL_{prefix}_READOUT3B_MISSING_OR_MALFORMED")
        return False
    require_spec_prov = any(x is not None for x in (expected_specimen_id, expected_lot_id, expected_cohort_id))
    allowed_3b = frozenset({
        "canonical_readout3b_producer_sha256", "hla_e_spr_affinity_evidence",
        "covalent_hla_e_sct_comparator", "donor_records",
    }) | (
        frozenset({"matched_vehicle_lot_id"}) if expected_vehicle_lot_id is not None else frozenset()
    ) | (
        frozenset({"assay_specimen_provenance"}) if require_spec_prov else frozenset()
    )
    _check_allowed_keys(r3b, allowed_3b, fails, f"{prefix}_READOUT3B")
    ok = True

    if not is_valid_sha256_hex(r3b.get("canonical_readout3b_producer_sha256")):
        fails.append(f"FAIL_{prefix}_READOUT3B_MISSING_CANONICAL_PRODUCER_SHA256"); ok = False
    spr = r3b.get("hla_e_spr_affinity_evidence")
    if require_hla_e_spr:
        if not isinstance(spr, Mapping) or set(spr.keys()) != {
            "kd_nkg2a_u95_uM", "kd_nkg2a_se_uM", "kd_nkg2c_mean_uM", "kd_nkg2c_se_uM", "spr_artifact_sha256",
        }:
            fails.append(f"FAIL_{prefix}_READOUT3B_MISSING_HLAE_SPR_AFFINITY_EVIDENCE"); ok = False
        elif not (
            is_finite_num(spr["kd_nkg2a_u95_uM"]) and 0.0 < float(spr["kd_nkg2a_u95_uM"]) <= 10.0
            and is_finite_num(spr["kd_nkg2a_se_uM"]) and float(spr["kd_nkg2a_se_uM"]) >= 0.0
            and is_finite_num(spr["kd_nkg2c_mean_uM"]) and float(spr["kd_nkg2c_mean_uM"]) > 0.0
            and is_finite_num(spr["kd_nkg2c_se_uM"]) and float(spr["kd_nkg2c_se_uM"]) >= 0.0
            and is_valid_sha256_hex(spr["spr_artifact_sha256"])
        ):
            fails.append(f"FAIL_{prefix}_READOUT3B_HLAE_SPR_KD_EXCEEDS_10UM_OR_INVALID"); ok = False
    elif spr != "N/A_NO_HLAE_MODULE" and not isinstance(spr, Mapping):
        fails.append(f"FAIL_{prefix}_READOUT3B_MISSING_HLAE_SPR_DECLARATION"); ok = False
    sct = r3b.get("covalent_hla_e_sct_comparator")
    sct_req_keys = frozenset({
        "comparator_construct_id", "hcmv_pos_donor_count",
        "nkg2a_pos_lysis_u95_pct", "adaptive_kir_pos_lysis_u95_pct",
        "adaptive_kir_neg_lysis_u95_pct", "cd107a_fold_u95",
        "ul40_ctl_lysis_u95_pct", "comparator_verdict", "comparator_receipt_sha256",
    })
    if require_hla_e_spr:
        if not isinstance(sct, Mapping) or set(sct.keys()) != sct_req_keys:
            fails.append(f"FAIL_{prefix}_READOUT3B_MISSING_COVALENT_HLAE_SCT_COMPARATOR"); ok = False
        elif not (
            is_nonempty_str(sct.get("comparator_construct_id"))
            and is_strict_int(sct.get("hcmv_pos_donor_count")) and int(sct["hcmv_pos_donor_count"]) >= 6
            and is_finite_num(sct.get("nkg2a_pos_lysis_u95_pct")) and 0.0 <= float(sct["nkg2a_pos_lysis_u95_pct"]) <= 8.0
            and is_finite_num(sct.get("adaptive_kir_pos_lysis_u95_pct")) and 0.0 <= float(sct["adaptive_kir_pos_lysis_u95_pct"]) <= 8.0
            and is_finite_num(sct.get("adaptive_kir_neg_lysis_u95_pct")) and 0.0 <= float(sct["adaptive_kir_neg_lysis_u95_pct"]) <= 8.0
            and is_finite_num(sct.get("cd107a_fold_u95")) and 0.0 < float(sct["cd107a_fold_u95"]) <= 1.25
            and is_finite_num(sct.get("ul40_ctl_lysis_u95_pct")) and 0.0 <= float(sct["ul40_ctl_lysis_u95_pct"]) <= 5.0
            and sct.get("comparator_verdict") == "PASS"
            and is_valid_sha256_hex(sct.get("comparator_receipt_sha256"))
            and sha256_bytes(canonical_json_bytes({k: v for k, v in sct.items() if k != "comparator_receipt_sha256"})) == str(sct["comparator_receipt_sha256"])
        ):
            fails.append(f"FAIL_{prefix}_READOUT3B_COVALENT_HLAE_SCT_COMPARATOR_FAILED"); ok = False
    elif sct != "N/A_NO_HLAE_MODULE":
        fails.append(f"FAIL_{prefix}_READOUT3B_MISSING_COVALENT_HLAE_SCT_DECLARATION"); ok = False
    if expected_vehicle_lot_id is not None:
        if r3b.get("matched_vehicle_lot_id") != expected_vehicle_lot_id:
            fails.append(f"FAIL_{prefix}_READOUT3B_MATCHED_VEHICLE_LOT_MISMATCH"); ok = False
    registered_aliquots_norm: Optional[set[str]] = None
    expected_sp_norm = str(expected_specimen_id).strip().upper() if is_nonempty_str(expected_specimen_id) else None
    if require_spec_prov:
        prov = r3b.get("assay_specimen_provenance")
        prov_keys = frozenset({"specimen_id", "specimen_lot_id", "intervention_cohort_id", "registered_aliquot_ids", "provenance_sha256"})
        if prov is None:
            if holds is not None:
                holds.append(f"HOLD_{prefix}_READOUT3B_MISSING_SPECIMEN_PROVENANCE")
            else:
                fails.append(f"FAIL_{prefix}_READOUT3B_MISSING_SPECIMEN_PROVENANCE")
            ok = False
        elif not isinstance(prov, Mapping) or set(prov.keys()) != prov_keys:
            fails.append(f"FAIL_{prefix}_READOUT3B_SPECIMEN_LOT_OR_COHORT_MISMATCH"); ok = False
        else:
            psha = prov.get("provenance_sha256")
            p_sp = prov.get("specimen_id")
            p_lt = prov.get("specimen_lot_id")
            p_co = prov.get("intervention_cohort_id")
            p_al = prov.get("registered_aliquot_ids")
            if (
                not is_valid_sha256_hex(psha)
                or sha256_bytes(canonical_json_bytes({k: v for k, v in prov.items() if k != "provenance_sha256"})) != str(psha)
                or not (is_nonempty_str(p_sp) and is_nonempty_str(p_lt) and is_nonempty_str(p_co))
                or not (isinstance(p_al, list) and len(p_al) >= 1 and all(is_nonempty_str(a) for a in p_al))
            ):
                fails.append(f"FAIL_{prefix}_READOUT3B_SPECIMEN_LOT_OR_COHORT_MISMATCH"); ok = False
            else:
                p_sp_n = str(p_sp).strip().upper()
                p_lt_n = str(p_lt).strip().upper()
                p_co_n = str(p_co).strip().upper()
                al_norms = [str(a).strip().upper() for a in p_al]
                if (
                    len(set(al_norms)) != len(al_norms)
                    or (expected_sp_norm is not None and p_sp_n != expected_sp_norm)
                    or (is_nonempty_str(expected_lot_id) and p_lt_n != str(expected_lot_id).strip().upper())
                    or (is_nonempty_str(expected_cohort_id) and p_co_n != str(expected_cohort_id).strip().upper())
                    or any(not (an == p_sp_n or an.startswith(f"{p_sp_n}-")) for an in al_norms)
                ):
                    fails.append(f"FAIL_{prefix}_READOUT3B_SPECIMEN_LOT_OR_COHORT_MISMATCH"); ok = False
                else:
                    registered_aliquots_norm = set(al_norms) | {p_sp_n}
    drecs = r3b.get("donor_records")
    if not isinstance(drecs, list) or len(drecs) < 6:
        fails.append(f"FAIL_{prefix}_READOUT3B_DONORS_LT_6"); return False

    need_vdelta = max_vehicle_delta_pp is not None
    base_subsets = [
        ("nkg2a_pos_nkg2c_neg_kir_neg_lysis_pct", "veh_nkg2a_pos_lysis_pct", "NKG2A", 8.0),
        ("nkg2a_pos_cd107a_degranulation_pct", "veh_cd107a_pct", "CD107A", 10.0),
        ("nkg2c_pos_nkg2a_neg_cd57_pos_lysis_pct", "veh_nkg2c_pos_lysis_pct", "NKG2C", 10.0),
        ("adaptive_nkg2c_kir_pos_lysis_pct", "veh_adaptive_kir_pos_lysis_pct", "ADAPTIVE_KIR_POS", 10.0),
        ("adaptive_nkg2c_kir_neg_lysis_pct", "veh_adaptive_kir_neg_lysis_pct", "ADAPTIVE_KIR_NEG", 10.0),
        ("nkg2a_neg_nkg2c_neg_kir_pos_lysis_pct", "veh_kir_pos_lysis_pct", "KIR", 10.0),
    ]
    if require_sirpa_low:
        base_subsets.append(("il12_il18_sirpa_low_lysis_pct", "veh_sirpa_low_lysis_pct", "SIRPA", 10.0))

    reg1_allowed = frozenset({k for k, _, _, _ in base_subsets} | {"positive_control_lysis_pct", "negative_control_lysis_pct"})
    if need_vdelta:
        reg1_allowed = reg1_allowed | frozenset({vk for _, vk, _, _ in base_subsets})
    reg2_allowed = reg1_allowed | frozenset({"allogeneic_cd8_ctl_lysis_pct", "continuous_0_24h_kinetic_trace_verified", "continuous_0_24h_kinetic_trace"})
    if need_vdelta:
        reg2_allowed = reg2_allowed | frozenset({"veh_allogeneic_cd8_ctl_lysis_pct"})
    d_allowed = frozenset({"donor_id", "cmv_status", "regime_i_ifng_24h", "regime_ii_t0_unpreinduced"})

    seen_dids: set[str] = set()
    cmv_pos = 0
    cmv_neg = 0
    vecs: dict[str, list[float]] = {f"{r}_{nm}": [] for r in ("R1", "R2") for _, _, nm, _ in base_subsets}
    vecs["ADV_CD8"] = []
    dvecs: dict[str, list[float]] = {k: [] for k in vecs} if need_vdelta else {}
    ident_count = 0

    for idx, drow in enumerate(drecs):
        if not isinstance(drow, Mapping):
            fails.append(f"FAIL_{prefix}_READOUT3B_MALFORMED_DONOR:{idx}"); ok = False; continue
        _check_allowed_keys(drow, d_allowed, fails, f"{prefix}_READOUT3B_D{idx}")
        raw_did = drow.get("donor_id")
        if not is_nonempty_str(raw_did):
            fails.append(f"FAIL_{prefix}_READOUT3B_DUPLICATE_OR_EMPTY_DONOR_ID"); ok = False; continue
        did = str(raw_did).strip()
        did_norm = did.upper()
        if did_norm in seen_dids:
            fails.append(f"FAIL_{prefix}_READOUT3B_DUPLICATE_OR_EMPTY_DONOR_ID"); ok = False; continue
        seen_dids.add(did_norm)
        cmv = drow.get("cmv_status")
        if cmv == "CMV_POS":
            cmv_pos += 1
        elif cmv == "CMV_NEG":
            cmv_neg += 1
        else:
            fails.append(f"FAIL_{prefix}_READOUT3B_INVALID_CMV_STATUS:{did}"); ok = False

        r1 = drow.get("regime_i_ifng_24h")
        r2 = drow.get("regime_ii_t0_unpreinduced")
        if not isinstance(r1, Mapping) or not isinstance(r2, Mapping):
            fails.append(f"FAIL_{prefix}_READOUT3B_MISSING_REGIME_FOR_DONOR:{did}"); ok = False; continue
        _check_allowed_keys(r1, reg1_allowed, fails, f"{prefix}_READOUT3B_{did}_R1")
        _check_allowed_keys(r2, reg2_allowed, fails, f"{prefix}_READOUT3B_{did}_R2")
        if all(r1.get(k) == r2.get(k) for k in reg1_allowed):
            ident_count += 1

        for rtag, rblk in (("R1", r1), ("R2", r2)):
            pos_c = rblk.get("positive_control_lysis_pct")
            neg_c = rblk.get("negative_control_lysis_pct")
            if not (is_finite_num(pos_c) and float(pos_c) >= 25.0 and is_finite_num(neg_c) and 0.0 <= float(neg_c) <= 5.0):
                fails.append(f"FAIL_{prefix}_READOUT3B_{rtag}_CONTROLS_INVALID:{did}"); ok = False
            for fkey, vkey, sname, cap in base_subsets:
                val = rblk.get(fkey)
                cap_str = f"{cap:g}PCT"
                if sname == "CD107A":
                    code = f"FAIL_{prefix}_READOUT3B_{rtag}_CD107A_GT_10PCT:{did}"
                elif sname == "SIRPA":
                    code = f"FAIL_{prefix}_READOUT3B_{rtag}_SIRPA_LOW_LYSIS_GT_10PCT:{did}"
                else:
                    code = f"FAIL_{prefix}_READOUT3B_{rtag}_{sname}_LYSIS_GT_{cap_str}:{did}"
                if not (is_finite_num(val) and 0.0 <= float(val) <= cap):
                    fails.append(code); ok = False
                else:
                    vecs[f"{rtag}_{sname}"].append(float(val))
                    if need_vdelta:
                        vval = rblk.get(vkey)
                        if not (is_finite_num(vval) and 0.0 <= float(vval) <= 100.0):
                            fails.append(f"FAIL_{prefix}_READOUT3B_{rtag}_MISSING_MATCHED_VEH_{sname}:{did}"); ok = False
                        else:
                            dvecs[f"{rtag}_{sname}"].append(float(val) - float(vval))
        cd8 = r2.get("allogeneic_cd8_ctl_lysis_pct")
        if not (is_finite_num(cd8) and 0.0 <= float(cd8) <= 5.0):
            fails.append(f"FAIL_{prefix}_READOUT3B_R2_ALLO_CD8_CTL_GT_5PCT:{did}"); ok = False
        else:
            vecs["ADV_CD8"].append(float(cd8))
            if need_vdelta:
                vcd8 = r2.get("veh_allogeneic_cd8_ctl_lysis_pct")
                if not (is_finite_num(vcd8) and 0.0 <= float(vcd8) <= 100.0):
                    fails.append(f"FAIL_{prefix}_READOUT3B_R2_MISSING_MATCHED_VEH_CD8:{did}"); ok = False
                else:
                    dvecs["ADV_CD8"].append(float(cd8) - float(vcd8))
        ktr = r2.get("continuous_0_24h_kinetic_trace")
        ktr_keys = frozenset({"assay_platform", "specimen_id", "timepoints_h", "target_lysis_pct_series", "trace_sha256"})
        ktr_ok = False
        if (
            is_strict_bool(r2.get("continuous_0_24h_kinetic_trace_verified")) and r2["continuous_0_24h_kinetic_trace_verified"]
            and isinstance(ktr, Mapping) and set(ktr.keys()) == ktr_keys
            and is_nonempty_str(ktr.get("assay_platform"))
            and is_nonempty_str(ktr.get("specimen_id"))
            and is_valid_sha256_hex(ktr.get("trace_sha256"))
            and sha256_bytes(canonical_json_bytes({k: v for k, v in ktr.items() if k != "trace_sha256"})) == str(ktr["trace_sha256"])
        ):
            th = ktr.get("timepoints_h")
            ly_s = ktr.get("target_lysis_pct_series")
            if (
                isinstance(th, list) and isinstance(ly_s, list) and len(th) >= 5 and len(th) == len(ly_s)
                and all(is_finite_num(x) for x in th) and all(is_finite_num(x) and 0.0 <= float(x) <= 100.0 for x in ly_s)
            ):
                th_f = [float(x) for x in th]
                ly_f = [float(x) for x in ly_s]
                if (
                    abs(th_f[0]) <= 1e-9 and th_f[-1] >= 24.0 - 1e-9
                    and all(th_f[k] < th_f[k + 1] and (th_f[k + 1] - th_f[k]) <= 6.0 + 1e-9 for k in range(len(th_f) - 1))
                    and max(ly_f) <= 10.0 + 1e-9
                ):
                    ktr_ok = True
        if not ktr_ok:
            fails.append(f"FAIL_{prefix}_READOUT3B_R2_MISSING_0_24H_KINETIC_TRACE:{did}"); ok = False
        elif require_spec_prov:
            ktr_sp_n = str(ktr.get("specimen_id", "")).strip().upper()
            if registered_aliquots_norm is not None:
                if ktr_sp_n not in registered_aliquots_norm:
                    fails.append(f"FAIL_{prefix}_READOUT3B_SPECIMEN_LOT_OR_COHORT_MISMATCH:{did}"); ok = False
            elif expected_sp_norm is not None and not (ktr_sp_n == expected_sp_norm or ktr_sp_n.startswith(f"{expected_sp_norm}-")):
                fails.append(f"FAIL_{prefix}_READOUT3B_SPECIMEN_LOT_OR_COHORT_MISMATCH:{did}"); ok = False

    if cmv_pos < 3 or cmv_neg < 3:
        fails.append(f"FAIL_{prefix}_READOUT3B_CMV_STRATIFICATION_REQUIRES_3_POS_AND_3_NEG"); ok = False
    if ident_count == len(drecs):
        fails.append(f"FAIL_{prefix}_READOUT3B_IDENTICAL_COPY_PASTE_REGIME_I_AND_II"); ok = False

    nd = len(drecs)
    cap_specs = [(f"{r}_{nm}", cap) for r in ("R1", "R2") for _, _, nm, cap in base_subsets] + [("ADV_CD8", 5.0)]
    for vname, cap in cap_specs:
        arr = vecs[vname]
        if len(arr) == nd:
            tb = sample_t_one_sided_bounds(arr)
            if tb is None or tb[2] > cap:
                fails.append(f"FAIL_{prefix}_READOUT3B_{vname}_RECOMPUTED_U95_EXCEEDS_{cap:g}PCT"); ok = False
        if need_vdelta and len(dvecs[vname]) == nd:
            dt = sample_t_one_sided_bounds(dvecs[vname])
            u95_d = dvecs[vname][0] if dt is None else dt[2]
            if (sum(dvecs[vname]) / nd) > max_vehicle_delta_pp or u95_d > max_vehicle_delta_pp:
                fails.append(f"FAIL_{prefix}_READOUT3B_{vname}_EXCEEDS_MATCHED_VEH_BY_GT_{max_vehicle_delta_pp:g}PP"); ok = False
    return ok


def _validate_gate31_quantitative(
    g31: Mapping[str, Any],
    *,
    require_coating_stability: bool,
    fails: list[str],
    holds: list[str],
    prefix: str,
) -> bool:
    """Full 1:1 live canonical GATE-31 parity (DEC-134 60-h branch, scripts/verify_iip0045_cao2_coupled_gate31.py:839-1260)."""
    ok = True
    if not is_valid_sha256_hex(g31.get("canonical_gate31_producer_sha256")):
        fails.append(f"FAIL_{prefix}_GATE31_MISSING_PRODUCER_SHA256"); ok = False

    # Same-lot binding across all 4 sub-assays (live verify_iip0045_cao2_coupled_gate31.py:839-853)
    lot_id = str(g31.get("lot_id", "")).strip()
    for sub_k in ("bead_psd_lot_id", "barrier_film_lot_id", "kinetics_336h_lot_id", "open_sink_lot_id"):
        sv = g31.get(sub_k)
        if not is_nonempty_str(sv):
            holds.append(f"HOLD_{prefix}_GATE31_MISSING_SAME_LOT_BINDING:{sub_k}"); ok = False
        elif lot_id and str(sv).strip() != lot_id:
            fails.append(f"FAIL_{prefix}_GATE31_DECOUPLED_LOT_MISMATCH:{sub_k}"); ok = False

    if g31.get("reconciled_slab_geometry_mode") != "EXPANDED_390UM_2X125UM_BANDS":
        holds.append(f"HOLD_{prefix}_GATE31_INVALID_OR_MISSING_RECONCILED_SLAB_MODE"); ok = False

    k_reg = g31.get("kinetics_assay_regime")
    if k_reg == "SEALED_CHAMBER_ONLY":
        holds.append(f"HOLD_{prefix}_GATE31_SEALED_CHAMBER_ONLY_OPEN_SINK_REQUIRED"); ok = False
    elif k_reg != "PAIRED_LIMITED_EXCHANGE_AND_OPEN_SINK":
        holds.append(f"HOLD_{prefix}_GATE31_MISSING_OR_INVALID_KINETICS_ASSAY_REGIME"); ok = False

    bd99 = g31.get("bead_d99_u95_um")
    bd50 = g31.get("bead_d50_um")
    cd99 = g31.get("crystal_d99_um")
    bmode = g31.get("barrier_geometry_mode")
    bth = g31.get("barrier_thickness_l95_um")
    cat_u = g31.get("catalase_uniprot_id")
    cao2_mg = g31.get("conserved_cao2_loading_mg")
    sub15_h = g31.get("cumulative_sub15_mmhg_duration_h")
    min_po2 = g31.get("hard_hypoxia_floor_min_po2_mmhg")
    wdev = g31.get("whole_device_washout_dec134")
    if not (is_finite_num(bd99) and is_finite_num(bd50) and 0.0 < float(bd50) <= float(bd99) <= 50.0):
        fails.append(f"FAIL_{prefix}_GATE31_BEAD_DIAMETER_GT_50UM"); ok = False
    if not (is_finite_num(cd99) and float(cd99) > 0.0 and is_finite_num(bd50) and float(cd99) < float(bd50)):
        fails.append(f"FAIL_{prefix}_GATE31_CRYSTAL_D99_NOT_LT_BEAD_D50"); ok = False
    if bmode != "PLANAR_CO_CAST_LAMINA_FACE_HYDROGEL_FILM":
        fails.append(f"FAIL_{prefix}_GATE31_CONFORMAL_OR_INVALID_BARRIER_GEOMETRY_HARD_STOP"); ok = False
    if not (is_finite_num(bth) and float(bth) >= 20.0):
        fails.append(f"FAIL_{prefix}_GATE31_BARRIER_THICKNESS_LT_20UM"); ok = False
    if cat_u != "P04040":
        fails.append(f"FAIL_{prefix}_GATE31_CATALASE_MUST_BE_HUMAN_P04040"); ok = False
    if not (is_finite_num(cao2_mg) and 751.925 <= float(cao2_mg) <= 831.075):
        fails.append(f"FAIL_{prefix}_GATE31_CONSERVED_CAO2_LOADING_OUT_OF_791P5MG_5PCT"); ok = False
    if not (is_finite_num(sub15_h) and 0.0 <= float(sub15_h) <= 4.0):
        fails.append(f"FAIL_{prefix}_GATE31_SUB15_MMHG_DURATION_GT_4H"); ok = False
    if not (is_finite_num(min_po2) and float(min_po2) >= 10.0):
        fails.append(f"FAIL_{prefix}_GATE31_HARD_HYPOXIA_FLOOR_LT_10MMHG"); ok = False
    if not isinstance(wdev, Mapping) or set(wdev.keys()) != {
        "time_min_series", "remaining_peak_pct_series", "raw_trace_sha256",
        "trace_span_min", "tail_remaining_pct", "mass_recovery_pct",
        "t50_min", "mean_transit_min", "t90_min",
    }:
        fails.append(f"FAIL_{prefix}_GATE31_MISSING_DEC134_WHOLE_DEVICE_WASHOUT"); ok = False
    else:
        if not _validate_dec134_washout_trace(
            wdev["time_min_series"], wdev["remaining_peak_pct_series"], wdev["raw_trace_sha256"],
            wdev["trace_span_min"], wdev["tail_remaining_pct"], wdev["mass_recovery_pct"],
            wdev["t50_min"], wdev["mean_transit_min"], wdev["t90_min"],
        ):
            fails.append(f"FAIL_{prefix}_GATE31_DEC134_WASHOUT_FAILED"); ok = False

    vh = g31.get("vascular_midpoint_horizon_h")
    hl_l = g31.get("halflife_l95_h")
    hl_u = g31.get("halflife_u95_h")
    klaw = g31.get("kinetic_law_code")
    r24 = g31.get("hour0_24_o2_ratio_l95")
    c72 = g31.get("hour0_72_o2_cum_frac_l95")
    h2o2 = g31.get("h2o2_z70_u95_uM")
    cat7 = g31.get("day7_catalase_retention_l95_pct")
    cat14 = g31.get("day14_catalase_retained_l95_iu")
    precure_cat = g31.get("pre_cure_catalase_load_iu_333cm2")
    if is_finite_num(vh) and float(vh) == 36.0:
        holds.append(f"HOLD_{prefix}_GATE31_DEC134_36H_IS_SENSITIVITY_ONLY_60H_PRIMARY_REQUIRED"); ok = False
    elif not (is_finite_num(vh) and float(vh) == 60.0):
        fails.append(f"FAIL_{prefix}_GATE31_HORIZON_MUST_BE_60H_DEC134"); ok = False
    # Exact live verify_iip0045_cao2_coupled_gate31.py:929-996 parity:
    #   34.0-68.0 h (60-h branch), <=2.5 uM Tier-1 / >5.0 uM Tier-2, pre-cure catalase <= 158,300 IU!
    if not (is_finite_num(hl_l) and is_finite_num(hl_u) and 34.0 <= float(hl_l) <= float(hl_u) <= 68.0):
        fails.append(f"FAIL_{prefix}_GATE31_HALFLIFE_OUT_OF_34_68H"); ok = False
    if klaw not in (0, 1):
        fails.append(f"FAIL_{prefix}_GATE31_INVALID_KINETIC_LAW_CODE"); ok = False
    if not (is_finite_num(r24) and float(r24) >= 0.70 and is_finite_num(c72) and float(c72) >= 0.25):
        fails.append(f"FAIL_{prefix}_GATE31_O2_RELEASE_RATIO_BELOW_FLOOR"); ok = False
    if not is_finite_num(h2o2) or float(h2o2) < 0.0 or float(h2o2) > 5.0:
        fails.append(f"FAIL_{prefix}_GATE31_H2O2_Z70_BREACHES_5P0UM_TIER2_HARD_STOP"); ok = False
    elif float(h2o2) > 2.5:
        holds.append(f"HOLD_{prefix}_GATE31_H2O2_Z70_EXCEEDS_2P5UM_TIER1_TARGET"); ok = False
    if not (is_finite_num(cat7) and float(cat7) >= 70.0 and is_finite_num(cat14) and float(cat14) >= 73800.0):
        fails.append(f"FAIL_{prefix}_GATE31_CATALASE_RETENTION_BELOW_73800IU_OR_70PCT"); ok = False
    if not is_finite_num(precure_cat):
        holds.append(f"HOLD_{prefix}_GATE31_MISSING_PRE_CURE_CATALASE_LOAD_IU"); ok = False
    elif float(precure_cat) < 0.0 or float(precure_cat) > 158300.0:
        fails.append(f"FAIL_{prefix}_GATE31_PRE_CURE_CATALASE_EXCEEDS_158300IU_CAP"); ok = False

    # Live DEC-134 BPR-16 peroxide coordinate provenance for BOTH limited-exchange AND open-sink (missing/wrong -> HOLD!)
    for site_k, z_k, 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"),
    ):
        s_val = g31.get(site_k)
        z_val = g31.get(z_k)
        if s_val != "BARRIER_TISSUE_INTERFACE_Z_70P0_UM" or not is_finite_num(z_val) or abs(float(z_val) - 70.0) > 1e-6:
            holds.append(f"HOLD_{prefix}_GATE31_H2O2_NOT_AT_Z70P0_INTERFACE:{lbl}"); ok = False

    # Live Gate 31-C open-sink 95% CI window [34.0, 68.0 h] (BOTH L95 >= 34.0 AND U95 <= 68.0!) + paired contrast!
    os_l95_rep = g31.get("gate31c_open_sink_halflife_l95_h")
    os_u95_rep = g31.get("gate31c_open_sink_halflife_u95_h")
    if not (is_finite_num(os_l95_rep) and is_finite_num(os_u95_rep)):
        holds.append(f"HOLD_{prefix}_GATE31C_MISSING_OPEN_SINK_HALFLIFE_95CI"); ok = False
    elif not (34.0 <= float(os_l95_rep) <= float(os_u95_rep) <= 68.0):
        fails.append(f"FAIL_{prefix}_GATE31C_OPEN_SINK_HALFLIFE_OUT_OF_34_68H"); ok = False

    g31c_blocks = g31.get("gate31c_paired_blocks")
    g31c_l95 = g31.get("gate31c_open_minus_half_limited_l95_h")
    g31c_h2o2 = g31.get("gate31c_open_sink_h2o2_u95_uM")
    if not isinstance(g31c_blocks, list) or len(g31c_blocks) < 6:
        fails.append(f"FAIL_{prefix}_GATE31C_PAIRED_BLOCKS_LT_6"); ok = False
    else:
        seen_gb: set[str] = set()
        open_v: list[float] = []
        diff_v: list[float] = []
        for idx, brow in enumerate(g31c_blocks):
            if not isinstance(brow, Mapping) or set(brow.keys()) != {"block_id", "open_sink_t_half_h", "limited_exchange_t_half_h"}:
                fails.append(f"FAIL_{prefix}_GATE31C_MALFORMED_BLOCK:{idx}"); ok = False; continue
            bid = str(brow.get("block_id", "")).strip()
            oh = brow.get("open_sink_t_half_h")
            lh = brow.get("limited_exchange_t_half_h")
            if not bid or bid in seen_gb or not (is_finite_num(oh) and is_finite_num(lh) and float(oh) > 0.0 and float(lh) > 0.0):
                fails.append(f"FAIL_{prefix}_GATE31C_INVALID_BLOCK:{idx}"); ok = False; continue
            seen_gb.add(bid)
            open_v.append(float(oh))
            diff_v.append(float(oh) - 0.50 * float(lh))
        if len(diff_v) == len(g31c_blocks):
            ds = paired_t_summary(diff_v)
            ob_two = sample_t_one_sided_bounds(open_v, alpha=0.025)
            ob_one = sample_t_one_sided_bounds(open_v, alpha=0.05)
            if ds is None or ds[3] < 0.0 or ob_one is None or ob_one[1] < 34.0:
                fails.append(f"FAIL_{prefix}_GATE31C_RECOMPUTED_PAIRED_L95_FAILED"); ok = False
            elif not is_finite_num(g31c_l95) or abs(float(g31c_l95) - ds[3]) > 1e-4:
                fails.append(f"FAIL_{prefix}_GATE31C_REPORTED_L95_MISMATCH"); ok = False
            if ob_two is None or ob_two[1] < 34.0 or ob_two[2] > 68.0:
                fails.append(f"FAIL_{prefix}_GATE31C_OPEN_SINK_HALFLIFE_OUT_OF_34_68H"); ok = False
            elif is_finite_num(os_l95_rep) and is_finite_num(os_u95_rep):
                m_o = sum(open_v) / len(open_v)
                se_o = math.sqrt(sum((x - m_o) ** 2 for x in open_v) / (len(open_v) - 1) / len(open_v))
                if float(os_l95_rep) > (m_o - 1.95996 * se_o) + 1e-2 or float(os_u95_rep) < (m_o + 1.95996 * se_o) - 1e-2:
                    fails.append(f"FAIL_{prefix}_GATE31C_REPORTED_OPEN_SINK_CI_NARROWER_THAN_RAW_BLOCKS"); ok = False
    if not is_finite_num(g31c_h2o2) or float(g31c_h2o2) < 0.0 or float(g31c_h2o2) > 5.0:
        fails.append(f"FAIL_{prefix}_GATE31C_OPEN_SINK_H2O2_BREACHES_5P0UM_TIER2_HARD_STOP"); ok = False
    elif float(g31c_h2o2) > 2.5:
        holds.append(f"HOLD_{prefix}_GATE31C_OPEN_SINK_H2O2_EXCEEDS_2P5UM_TIER1_TARGET"); ok = False

    cstab = g31.get("coating_stability_verified")
    cstab_ev = g31.get("coating_stability_evidence")
    if require_coating_stability:
        if not (is_strict_bool(cstab) and cstab):
            fails.append(f"FAIL_{prefix}_GATE31_COATING_STABILITY_UNVERIFIED"); ok = False
        if not isinstance(cstab_ev, Mapping) or set(cstab_ev.keys()) != {
            "day14_barrier_thickness_retention_pct",
            "day14_catalase_retention_ratio_vs_uncoated",
            "o2_permeability_ratio_vs_uncoated",
            "coating_delamination_events",
        }:
            fails.append(f"FAIL_{prefix}_GATE31_MISSING_QUANTITATIVE_COATING_STABILITY_EVIDENCE"); ok = False
        elif not (
            is_finite_num(cstab_ev["day14_barrier_thickness_retention_pct"]) and 95.0 <= float(cstab_ev["day14_barrier_thickness_retention_pct"]) <= 105.0
            and is_finite_num(cstab_ev["day14_catalase_retention_ratio_vs_uncoated"]) and 0.95 <= float(cstab_ev["day14_catalase_retention_ratio_vs_uncoated"]) <= 1.20
            and is_finite_num(cstab_ev["o2_permeability_ratio_vs_uncoated"]) and 0.95 <= float(cstab_ev["o2_permeability_ratio_vs_uncoated"]) <= 1.20
            and is_strict_int(cstab_ev["coating_delamination_events"]) and int(cstab_ev["coating_delamination_events"]) == 0
        ):
            fails.append(f"FAIL_{prefix}_GATE31_QUANTITATIVE_COATING_STABILITY_FAILED"); ok = False
    elif cstab is False:
        fails.append(f"FAIL_{prefix}_GATE31_COATING_STABILITY_EXPLICITLY_FAILED"); ok = False
    return ok


GATE31_QUANT_EXTRAS: FrozenSet[str] = frozenset({
    "canonical_gate31_producer_sha256",
    "bead_psd_lot_id", "barrier_film_lot_id", "kinetics_336h_lot_id", "open_sink_lot_id",
    "reconciled_slab_geometry_mode", "kinetics_assay_regime",
    "bead_d99_u95_um", "bead_d50_um", "crystal_d99_um",
    "barrier_geometry_mode", "barrier_thickness_l95_um", "catalase_uniprot_id",
    "conserved_cao2_loading_mg", "cumulative_sub15_mmhg_duration_h",
    "hard_hypoxia_floor_min_po2_mmhg", "whole_device_washout_dec134",
    "vascular_midpoint_horizon_h", "halflife_l95_h", "halflife_u95_h",
    "kinetic_law_code", "hour0_24_o2_ratio_l95", "hour0_72_o2_cum_frac_l95",
    "h2o2_z70_u95_uM", "obs_h2o2_measurement_site", "obs_h2o2_z_um",
    "day7_catalase_retention_l95_pct", "day14_catalase_retained_l95_iu",
    "pre_cure_catalase_load_iu_333cm2",
    "gate31c_paired_blocks", "gate31c_open_minus_half_limited_l95_h",
    "gate31c_open_sink_halflife_l95_h", "gate31c_open_sink_halflife_u95_h",
    "gate31c_open_sink_h2o2_u95_uM", "obs_open_sink_h2o2_measurement_site", "obs_open_sink_h2o2_z_um",
    "coating_stability_verified", "coating_stability_evidence",
})


def _parse_unit_partition(
    raw: Any,
    *,
    n_units: Optional[int],
    expected_k: int,
    expected_n: int,
    is_viral_escape: bool = False,
) -> tuple[Optional[dict[str, tuple[int, int]]], bool, bool]:
    """
    Parse & reconcile a multi-well per-unit partition [{unit_id, k, n}, ...].
    Returns (unit_map_or_None, adverse_hard_stop, schema_or_sum_mismatch).
    NEVER returns early before scanning ALL rows for adverse hard-stop events (canonical Gate 0V rule)!
    """
    if not isinstance(raw, list) or len(raw) == 0:
        return None, False, True
    um: dict[str, tuple[int, int]] = {}
    sum_k = 0
    sum_n = 0
    adverse = False
    mismatch = False
    for row in raw:
        if not isinstance(row, Mapping) or set(row.keys()) != {"unit_id", "k", "n"}:
            mismatch = True; continue
        uid = str(row.get("unit_id", "")).strip()
        uk = row.get("k")
        un = row.get("n")
        if not uid or uid in um or not (is_strict_int(uk) and is_strict_int(un)):
            mismatch = True; continue
        ik, in_ = int(uk), int(un)
        if in_ <= 0 or ik < 0 or ik > in_:
            adverse = True
            continue
        if is_viral_escape and ik >= 1:
            adverse = True
        um[uid] = (ik, in_)
        sum_k += ik
        sum_n += in_
    if n_units is not None and len(um) != n_units:
        mismatch = True
    if sum_k > expected_k:
        adverse = True
    if sum_k != expected_k or sum_n != expected_n:
        mismatch = True
    return (um if not mismatch and not adverse else None), adverse, mismatch


def _validate_gate0v_kill_receipt(
    g0v_ev: Mapping[str, Any],
    *,
    prod_id: str,
    fails: list[str],
    holds: list[str],
) -> None:
    """
    Full Canonical GATE-0V-KILL 5-regime x 5-lineage raw-count adjudicator
    (docs/GATE-0V-WHOLEGRAFT-PROTOCOL.md:42-48, 76-88):
      1. Canonical Product-Family-to-Tier Binding:
         - Autologous ISLET1_DESIGN_D1B_LEAN_K2 -> ONLY PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL
         - Allogeneic MCB products (A, B, X, Y, Z) -> ONLY PASS_WHOLEGRAFT_BANK_QUALIFICATION or
           PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE (never autologous tier! Wrong family -> HOLD_INAPPLICABLE_QUALIFICATION_TIER_FOR_PRODUCT_FAMILY).
      2. Deterministic Hard-Stop Precedence (GATE-0V:78, 82):
         - NEVER returns early on missing sampling metadata, n_units < 6, or deff > 1.0!
         - ALWAYS scans ALL 25 cells and ALL per-unit rows for deterministic adverse biological hard stops
           (k_viral >= 1, caspase < 5.0, k > n, adverse per-unit rows, empirical 24h/72h kill breach)
           so FAIL ALWAYS overrides HOLD when an adverse safety observation is recorded!
      3. Exact Outward-Rounded 75-Digit Decimal Clopper-Pearson Ratio Bounds:
         - 24-h (u_ratio <= 0.001) & 72-h (u_ratio <= 0.0001) at alpha_t=0.025, alpha_v=0.025, s_veh_L975 >= 0.10.
         - Infected-Arm Estimand 1 (U_esc,total <= 1.0e-4) & Estimand 2 (DIRECT_INFECTED_VEHICLE_DENOMINATOR, U_esc,cond <= 1.0e-3)
           with dual healthy+fragile spike calibrants at alpha_eta = 0.005 (eta_eff_L >= 0.80).
    """
    from decimal import localcontext, ROUND_CEILING, ROUND_FLOOR

    if not is_valid_sha256_hex(g0v_ev.get("canonical_gate0v_producer_sha256")):
        fails.append("FAIL_GATE0V_MISSING_CANONICAL_PRODUCER_SHA256")
    tier = g0v_ev.get("canonical_gate0v_tier")
    valid_tiers = {
        "PASS_WHOLEGRAFT_BANK_QUALIFICATION",
        "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE",
        "PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL",
    }
    if tier not in valid_tiers:
        fails.append("FAIL_GATE0V_INVALID_CANONICAL_TIER")
    else:
        is_auto = (prod_id == "ISLET1_DESIGN_D1B_LEAN_K2")
        if is_auto and tier != "PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL":
            holds.append("HOLD_INAPPLICABLE_QUALIFICATION_TIER_FOR_PRODUCT_FAMILY")
        elif (not is_auto) and tier == "PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL":
            holds.append("HOLD_INAPPLICABLE_QUALIFICATION_TIER_FOR_PRODUCT_FAMILY")
        elif (not is_auto) and tier == "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE":
            # Surrogate release requires verified prior MCB bank archive digest (never interchangeable with bank qual!)
            if not (is_valid_sha256_hex(g0v_ev.get("prior_bank_qualification_sha256")) and is_strict_bool(g0v_ev.get("archived_bank_payload_verified")) and g0v_ev["archived_bank_payload_verified"]):
                holds.append("HOLD_GATE0V_LOT_SURROGATE_REQUIRES_VERIFIED_PRIOR_BANK_ARCHIVE")

    if not (is_strict_bool(g0v_ev.get("exposed_product_tested")) and g0v_ev["exposed_product_tested"]):
        fails.append("FAIL_GATE0V_EXPOSED_PRODUCT_NOT_TESTED")

    # Record sampling/clustering holds WITHOUT returning early so deterministic hard stops ALWAYS run!
    uclass = g0v_ev.get("independent_sampling_unit_class")
    sampling_ok = True
    if uclass not in ("INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT", "RECONCILED_MULTI_WELL_CELL_ASSAY_WITH_UNIT_PARTITION"):
        holds.append("HOLD_GATE0V_INVALID_SAMPLING_UNIT_CLASS")
        sampling_ok = False

    n_units_raw = g0v_ev.get("independent_biological_units_n")
    n_units_int: Optional[int] = None
    if not is_strict_int(n_units_raw) or int(n_units_raw) < 6:
        holds.append("HOLD_GATE0V_INSUFFICIENT_INDEPENDENT_BIOLOGICAL_UNITS")
        sampling_ok = False
    else:
        n_units_int = int(n_units_raw)

    deff_dec = _to_exact_decimal(g0v_ev.get("clustering_design_effect_deff"))
    certify_exact_ci = False
    if deff_dec is None:
        holds.append("HOLD_GATE0V_MISSING_CLUSTERING_DEFF")
        sampling_ok = False
    elif deff_dec < Decimal(1):
        fails.append("FAIL_GATE0V_INVALID_DEFF_LT_1")
        sampling_ok = False
    elif deff_dec > Decimal(1):
        holds.append("HOLD_GATE0V_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE")
        sampling_ok = False
    else:
        certify_exact_ci = sampling_ok

    rmap = g0v_ev.get("regime_by_lineage_raw_counts")
    if not isinstance(rmap, Mapping) or set(rmap.keys()) != REQUIRED_5_REGIMES:
        fails.append("FAIL_GATE0V_INCOMPLETE_FIVE_REGIME_MATRIX")
        return

    cell_allowed_base = frozenset({
        "treated_24h_survivors_k", "treated_24h_input_n", "veh_24h_alive_k", "veh_24h_input_n",
        "treated_72h_survivors_k", "treated_72h_input_n", "veh_72h_alive_k", "veh_72h_input_n",
        "per_unit_counts_treated_24h", "per_unit_counts_veh_24h",
        "per_unit_counts_treated_72h", "per_unit_counts_veh_72h",
    })
    cell_allowed_viral = cell_allowed_base | frozenset({
        "aliquot_linkage_mode", "aliquot_linkage_id",
        "pre_ap1903_lineage_input_cells_n", "post_ap1903_viable_survivors_total_n",
        "post_ap1903_viable_viral_pos_k", "caspase9_3_fold_over_veh",
        "infected_cell_escape_mode", "pretreat_infected_veh_survivor_k",
        "spike_healthy_recovered_k", "spike_healthy_input_n",
        "spike_fragile_recovered_k", "spike_fragile_input_n",
        "per_unit_counts_direct_infected_veh_72h", "per_unit_counts_viral_pos_72h",
        "per_unit_counts_spike_healthy", "per_unit_counts_spike_fragile",
    })

    is_mw = (uclass == "RECONCILED_MULTI_WELL_CELL_ASSAY_WITH_UNIT_PARTITION")
    is_sc = (uclass == "INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT")
    max_denom = 0
    cap_24_dec = Decimal("0.001")
    cap_72_dec = Decimal("0.0001")
    cap_e1_dec = Decimal("0.0001")
    cap_e2_dec = Decimal("0.001")
    floor_veh_dec = Decimal("0.10")
    floor_eta_dec = Decimal("0.80")

    for rname in sorted(REQUIRED_5_REGIMES):
        lmap = rmap.get(rname)
        if not isinstance(lmap, Mapping) or set(lmap.keys()) != REQUIRED_5_LINEAGES:
            fails.append(f"FAIL_GATE0V_INCOMPLETE_FIVE_LINEAGE_MAP:{rname}")
            continue
        is_viral = rname in VIRAL_REGIMES
        for lname in sorted(REQUIRED_5_LINEAGES):
            cell = lmap.get(lname)
            tag = f"{rname}:{lname}"
            if not isinstance(cell, Mapping):
                fails.append(f"FAIL_GATE0V_MALFORMED_CELL:{tag}")
                continue
            _check_allowed_keys(cell, cell_allowed_viral if is_viral else cell_allowed_base, fails, f"GATE0V_{rname}_{lname}")
            t24_k = cell.get("treated_24h_survivors_k")
            t24_n = cell.get("treated_24h_input_n")
            v24_k = cell.get("veh_24h_alive_k")
            v24_n = cell.get("veh_24h_input_n")
            t72_k = cell.get("treated_72h_survivors_k")
            t72_n = cell.get("treated_72h_input_n")
            v72_k = cell.get("veh_72h_alive_k")
            v72_n = cell.get("veh_72h_input_n")
            if not all(is_strict_int(x) for x in (t24_k, t24_n, v24_k, v24_n, t72_k, t72_n, v72_k, v72_n)):
                fails.append(f"FAIL_GATE0V_NON_INTEGER_RAW_COUNTS:{tag}")
                continue
            if not (0 <= int(t24_k) <= int(t24_n) and int(t24_n) >= 1 and 0 <= int(v24_k) <= int(v24_n) and int(v24_n) >= 1):
                fails.append(f"FAIL_GATE0V_INVALID_24H_COUNTS:{tag}")
                continue
            if not (0 <= int(t72_k) <= int(t72_n) and int(t72_n) >= 1 and 0 <= int(v72_k) <= int(v72_n) and int(v72_n) >= 1):
                fails.append(f"FAIL_GATE0V_INVALID_72H_COUNTS:{tag}")
                continue
            max_denom = max(max_denom, int(t24_n), int(v24_n), int(t72_n), int(v72_n))

            # Deterministic empirical kill-floor hard stop (ALWAYS evaluated even when deff > 1 or sampling metadata missing!)
            # At 24h: empirical treated/veh > 0.001 (or treated > 0 with veh == 0) is a direct adverse kill-failure observation
            if int(t24_k) > 0 and (int(v24_k) == 0 or Decimal(int(t24_k)) * Decimal(int(v24_n)) > cap_24_dec * Decimal(int(t24_n)) * Decimal(int(v24_k))):
                fails.append(f"FAIL_GATE0V_DIRECT_ADVERSE_24H_KILL_FLOOR_BREACH:{tag}")
            if int(t72_k) > 0 and (int(v72_k) == 0 or Decimal(int(t72_k)) * Decimal(int(v72_n)) > cap_72_dec * Decimal(int(t72_n)) * Decimal(int(v72_k))):
                fails.append(f"FAIL_GATE0V_DIRECT_ADVERSE_72H_KILL_FLOOR_BREACH:{tag}")

            # Exact outward-rounded Decimal Clopper-Pearson 24-h & 72-h Bonferroni ratios (only certify when deff == 1 & sampling_ok!)
            s_veh_24 = clopper_pearson_lower_decimal(int(v24_k), int(v24_n), "0.025")
            u_tr_24 = clopper_pearson_upper_decimal(int(t24_k), int(t24_n), "0.025")
            s_veh_72 = clopper_pearson_lower_decimal(int(v72_k), int(v72_n), "0.025")
            u_tr_72 = clopper_pearson_upper_decimal(int(t72_k), int(t72_n), "0.025")

            if certify_exact_ci:
                with localcontext() as ctx:
                    ctx.prec = 75
                    ctx.rounding = ROUND_CEILING
                    if s_veh_24 < floor_veh_dec:
                        fails.append(f"FAIL_GATE0V_24H_VEHICLE_SURVIVAL_L975_LT_0P10:{tag}")
                    elif (u_tr_24 / s_veh_24) > cap_24_dec:
                        fails.append(f"FAIL_GATE0V_24H_RATIO_U95_GT_0P001:{tag}")
                    if s_veh_72 < floor_veh_dec:
                        fails.append(f"FAIL_GATE0V_72H_VEHICLE_SURVIVAL_L975_LT_0P10:{tag}")
                    elif (u_tr_72 / s_veh_72) > cap_72_dec:
                        fails.append(f"FAIL_GATE0V_72H_RATIO_U95_GT_0P0001:{tag}")

            # Pre-schema & reconciled per-estimand sampling-unit partitions (ALWAYS scan for adverse rows even when sampling_ok is False!)
            base_part_specs = [
                ("per_unit_counts_treated_24h", int(t24_k), int(t24_n)),
                ("per_unit_counts_veh_24h", int(v24_k), int(v24_n)),
                ("per_unit_counts_treated_72h", int(t72_k), int(t72_n)),
                ("per_unit_counts_veh_72h", int(v72_k), int(v72_n)),
            ]
            parsed_parts: dict[str, Optional[dict[str, tuple[int, int]]]] = {}
            if is_mw or (not is_sc):
                for pk, ek, en in base_part_specs:
                    if cell.get(pk) is not None or is_mw:
                        pmap, adv, mm = _parse_unit_partition(cell.get(pk), n_units=n_units_int, expected_k=ek, expected_n=en)
                        if adv:
                            fails.append(f"FAIL_GATE0V_ADVERSE_PER_UNIT_COUNTS:{tag}:{pk}")
                        if is_mw and mm:
                            holds.append(f"HOLD_GATE0V_SAMPLING_UNIT_PARTITION_MISMATCH:{tag}:{pk}")
                        parsed_parts[pk] = pmap
                if is_mw:
                    ref_uids = set(parsed_parts["per_unit_counts_treated_72h"].keys()) if parsed_parts.get("per_unit_counts_treated_72h") else None
                    if ref_uids is not None:
                        for pk in ("per_unit_counts_treated_24h", "per_unit_counts_veh_24h", "per_unit_counts_veh_72h"):
                            if parsed_parts.get(pk) is not None and set(parsed_parts[pk].keys()) != ref_uids:
                                holds.append(f"HOLD_GATE0V_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION:{tag}:{pk}")
            else:
                for pk, ek, en in base_part_specs:
                    if cell.get(pk) is not None:
                        _, adv, _ = _parse_unit_partition(cell.get(pk), n_units=n_units_int, expected_k=ek, expected_n=en)
                        if adv:
                            fails.append(f"FAIL_GATE0V_ADVERSE_PER_UNIT_COUNTS:{tag}:{pk}")
                        holds.append(f"HOLD_GATE0V_UNEXPECTED_PER_UNIT_COUNTS_IN_SINGLE_CELL_MODE:{tag}")

            if is_viral:
                amode = cell.get("aliquot_linkage_mode")
                aid = cell.get("aliquot_linkage_id")
                pre_n = cell.get("pre_ap1903_lineage_input_cells_n")
                post_tot_k = cell.get("post_ap1903_viable_survivors_total_n")
                vk = cell.get("post_ap1903_viable_viral_pos_k")
                casp = cell.get("caspase9_3_fold_over_veh")
                emode = cell.get("infected_cell_escape_mode")
                d_inf_k = cell.get("pretreat_infected_veh_survivor_k")
                sh_k = cell.get("spike_healthy_recovered_k")
                sh_n = cell.get("spike_healthy_input_n")
                sf_k = cell.get("spike_fragile_recovered_k")
                sf_n = cell.get("spike_fragile_input_n")

                # Unconditional deterministic viral & caspase hard stops (ALWAYS run before any HOLD return!)
                if not is_strict_int(vk) or int(vk) < 0:
                    fails.append(f"FAIL_GATE0V_INVALID_VIRAL_ESCAPE_COUNT:{tag}")
                elif int(vk) >= 1:
                    fails.append(f"FAIL_GATE0V_VIRAL_ESCAPE_NONZERO:{tag}")
                if not (is_finite_num(casp) and float(casp) >= 5.0):
                    fails.append(f"FAIL_GATE0V_CASPASE_FOLD_LT_5X:{tag}")

                if amode != "SAME_72H_ALIQUOT" or not is_nonempty_str(aid):
                    holds.append(f"HOLD_GATE0V_NON_SAME_72H_ALIQUOT:{tag}")
                elif not (is_strict_int(pre_n) and is_strict_int(post_tot_k) and int(pre_n) == int(t72_n) and int(post_tot_k) == int(t72_k)):
                    holds.append(f"HOLD_GATE0V_ALIQUOT_COUNT_RECONCILIATION_MISMATCH:{tag}")
                elif is_strict_int(vk) and int(vk) > int(t72_k):
                    fails.append(f"FAIL_GATE0V_VIRAL_ESCAPE_EXCEEDS_TOTAL_SURVIVORS:{tag}")

                eta_eff_l: Optional[Decimal] = None
                if not all(is_strict_int(x) for x in (sh_k, sh_n, sf_k, sf_n)):
                    fails.append(f"FAIL_GATE0V_MISSING_RAW_SPIKE_CALIBRANT_COUNTS:{tag}")
                elif not (0 <= int(sh_k) <= int(sh_n) and int(sh_n) >= 1 and 0 <= int(sf_k) <= int(sf_n) and int(sf_n) >= 1):
                    fails.append(f"FAIL_GATE0V_INVALID_SPIKE_CALIBRANT_COUNTS:{tag}")
                else:
                    max_denom = max(max_denom, int(sh_n), int(sf_n))
                    eta_h = clopper_pearson_lower_decimal(int(sh_k), int(sh_n), "0.005")
                    eta_f = clopper_pearson_lower_decimal(int(sf_k), int(sf_n), "0.005")
                    eta_eff_l = min(eta_h, eta_f)
                    if certify_exact_ci and eta_eff_l < floor_eta_dec:
                        fails.append(f"FAIL_GATE0V_RECOMPUTED_DUAL_SPIKE_ETA_LT_0P80:{tag}")

                if certify_exact_ci and eta_eff_l is not None and s_veh_72 >= floor_veh_dec and is_strict_int(vk) and int(vk) >= 0 and is_strict_int(pre_n) and int(pre_n) >= 1:
                    with localcontext() as ctx:
                        ctx.prec = 75
                        ctx.rounding = ROUND_FLOOR
                        den1 = s_veh_72 * eta_eff_l
                        ctx.rounding = ROUND_CEILING
                        u_esc_tot = clopper_pearson_upper_decimal(int(vk), int(pre_n), "0.005") / den1
                    if u_esc_tot > cap_e1_dec:
                        if int(vk) == 0:
                            holds.append(f"HOLD_GATE0V_ESTIMAND1_TOTAL_ESCAPE_U_GT_1E_4:{tag}")
                        else:
                            fails.append(f"FAIL_GATE0V_ESTIMAND1_TOTAL_ESCAPE_U_GT_1E_4:{tag}")

                if emode != "DIRECT_INFECTED_VEHICLE_DENOMINATOR":
                    holds.append(f"HOLD_GATE0V_INDIRECT_CONDITIONAL_ESCAPE_UNSUPPORTED_FOR_RELEASE:{tag}")
                elif not is_strict_int(d_inf_k) or not (1 <= int(d_inf_k) <= int(v72_k) <= int(v72_n)):
                    fails.append(f"FAIL_GATE0V_INVALID_DIRECT_INFECTED_VEH_SURVIVOR_COUNT:{tag}")
                elif certify_exact_ci and eta_eff_l is not None and is_strict_int(vk) and int(vk) >= 0 and is_strict_int(pre_n) and int(pre_n) >= 1:
                    q_inf_veh_l = clopper_pearson_lower_decimal(int(d_inf_k), int(v72_n), "0.025")
                    if q_inf_veh_l <= Decimal(0):
                        holds.append(f"HOLD_GATE0V_DIRECT_INFECTED_VEH_L975_ZERO:{tag}")
                    else:
                        with localcontext() as ctx:
                            ctx.prec = 75
                            ctx.rounding = ROUND_FLOOR
                            den2 = q_inf_veh_l * eta_eff_l
                            ctx.rounding = ROUND_CEILING
                            u_esc_cond = clopper_pearson_upper_decimal(int(vk), int(pre_n), "0.020") / den2
                        if u_esc_cond > cap_e2_dec:
                            if int(vk) == 0:
                                holds.append(f"HOLD_GATE0V_ESTIMAND2_COND_ESCAPE_U_GT_1E_3:{tag}")
                            else:
                                fails.append(f"FAIL_GATE0V_ESTIMAND2_COND_ESCAPE_U_GT_1E_3:{tag}")

                if is_strict_int(vk) and is_strict_int(d_inf_k) and is_strict_int(sh_k) and is_strict_int(sh_n) and is_strict_int(sf_k) and is_strict_int(sf_n):
                    viral_parts = [
                        ("per_unit_counts_direct_infected_veh_72h", int(d_inf_k), int(v72_n), False),
                        ("per_unit_counts_viral_pos_72h", int(vk), int(t72_n), True),
                        ("per_unit_counts_spike_healthy", int(sh_k), int(sh_n), False),
                        ("per_unit_counts_spike_fragile", int(sf_k), int(sf_n), False),
                    ]
                    if is_mw or (not is_sc):
                        v_parsed: dict[str, Optional[dict[str, tuple[int, int]]]] = {}
                        for pk, ek, en, is_ve in viral_parts:
                            if cell.get(pk) is not None or is_mw:
                                pmap, adv, mm = _parse_unit_partition(cell.get(pk), n_units=n_units_int, expected_k=ek, expected_n=en, is_viral_escape=is_ve)
                                if adv:
                                    fails.append(f"FAIL_GATE0V_ADVERSE_PER_UNIT_COUNTS:{tag}:{pk}")
                                if is_mw and mm:
                                    holds.append(f"HOLD_GATE0V_SAMPLING_UNIT_PARTITION_MISMATCH:{tag}:{pk}")
                                v_parsed[pk] = pmap
                        if is_mw:
                            p_t72 = parsed_parts.get("per_unit_counts_treated_72h")
                            p_v72 = parsed_parts.get("per_unit_counts_veh_72h")
                            ref_u = set(p_t72.keys()) if p_t72 else None
                            for pk in ("per_unit_counts_direct_infected_veh_72h", "per_unit_counts_viral_pos_72h", "per_unit_counts_spike_healthy", "per_unit_counts_spike_fragile"):
                                if ref_u is not None and v_parsed.get(pk) is not None and set(v_parsed[pk].keys()) != ref_u:
                                    holds.append(f"HOLD_GATE0V_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION:{tag}:{pk}")
                            p_dinf = v_parsed.get("per_unit_counts_direct_infected_veh_72h")
                            if p_dinf is not None and p_v72 is not None and set(p_dinf.keys()) == set(p_v72.keys()):
                                for uid in p_v72:
                                    dk, dn = p_dinf[uid]
                                    vk72, vn72 = p_v72[uid]
                                    if dn != vn72 or not (0 <= dk <= vk72 <= vn72):
                                        holds.append(f"HOLD_GATE0V_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION:{tag}:direct_inf:{uid}")
                                        break
                            p_vir = v_parsed.get("per_unit_counts_viral_pos_72h")
                            if p_vir is not None and p_t72 is not None and set(p_vir.keys()) == set(p_t72.keys()):
                                for uid in p_t72:
                                    vrk, vrn = p_vir[uid]
                                    tk72, tn72 = p_t72[uid]
                                    if vrn != tn72 or not (0 <= vrk <= tk72 <= tn72):
                                        holds.append(f"HOLD_GATE0V_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION:{tag}:viral:{uid}")
                                        break
                    else:
                        for pk, ek, en, is_ve in viral_parts:
                            if cell.get(pk) is not None:
                                _, adv, _ = _parse_unit_partition(cell.get(pk), n_units=n_units_int, expected_k=ek, expected_n=en, is_viral_escape=is_ve)
                                if adv:
                                    fails.append(f"FAIL_GATE0V_ADVERSE_PER_UNIT_COUNTS:{tag}:{pk}")
                                holds.append(f"HOLD_GATE0V_UNEXPECTED_PER_UNIT_COUNTS_IN_SINGLE_CELL_MODE:{tag}")

    if is_sc and n_units_int is not None and n_units_int < max_denom:
        holds.append("HOLD_GATE0V_SINGLE_CELL_UNITS_LT_MAX_DENOMINATOR")


def _validate_lineage_hour0_density(
    spec: Mapping[str, Any],
    density_map: Any,
    *,
    required_lineages: FrozenSet[str],
    fails: list[str],
    prefix: str,
) -> bool:
    if not isinstance(density_map, Mapping):
        fails.append(f"FAIL_{prefix}_MISSING_LINEAGE_HOUR0_DENSITY_MAP")
        return False
    missing_lin = sorted(required_lineages - set(density_map.keys()))
    extra_lin = sorted(set(density_map.keys()) - REQUIRED_5_LINEAGES)
    if missing_lin:
        fails.append(f"FAIL_{prefix}_INCOMPLETE_LINEAGE_HOUR0_DENSITY:{','.join(missing_lin)}")
        return False
    if extra_lin:
        fails.append(f"FAIL_{prefix}_UNRECOGNIZED_HOUR0_LINEAGE:{','.join(extra_lin)}")
        return False

    ok = True
    allowed_lin = frozenset({
        "hlae_molecules_per_cell", "cd47_median_molecules_per_cell",
        "cd47_p10_molecules_per_cell", "autologous_hla_abc_preservation_pct",
    })
    for lin in sorted(density_map.keys()):
        d = density_map[lin]
        if not isinstance(d, Mapping):
            fails.append(f"FAIL_{prefix}_MALFORMED_HOUR0_LINEAGE:{lin}"); ok = False; continue
        _check_allowed_keys(d, allowed_lin, fails, f"{prefix}_HOUR0_{lin}")
        hlae = d.get("hlae_molecules_per_cell")
        cd47_m = d.get("cd47_median_molecules_per_cell")
        cd47_p10 = d.get("cd47_p10_molecules_per_cell")
        if spec["hla_e_engineered"]:
            if not (is_finite_num(hlae) and float(hlae) >= 15000.0):
                fails.append(f"FAIL_{prefix}_HLAE_HOUR0_BELOW_15000:{lin}"); ok = False
        else:
            if not (is_nonempty_str(hlae) and str(hlae).upper().startswith("N/A")):
                fails.append(f"FAIL_{prefix}_NON_HLAE_CONSTRUCT_MUST_DECLARE_NA_HLAE:{lin}"); ok = False

        if spec["cd47_engineered"]:
            if not (is_finite_num(cd47_m) and is_finite_num(cd47_p10)):
                fails.append(f"FAIL_{prefix}_CD47_HOUR0_MISSING:{lin}"); ok = False
            elif float(cd47_m) < 200000.0 or float(cd47_p10) < 180000.0 or float(cd47_p10) > float(cd47_m):
                fails.append(f"FAIL_{prefix}_CD47_HOUR0_GY009_BELOW_200K_180K:{lin}"); ok = False
        else:
            if not (
                is_nonempty_str(cd47_m) and str(cd47_m).upper().startswith("N/A")
                and is_nonempty_str(cd47_p10) and str(cd47_p10).upper().startswith("N/A")
            ):
                fails.append(f"FAIL_{prefix}_NON_CD47_CONSTRUCT_MUST_DECLARE_NA_CD47:{lin}"); ok = False

        if spec["autologous_self_hla"]:
            ahla = d.get("autologous_hla_abc_preservation_pct")
            if not (is_finite_num(ahla) and 85.0 <= float(ahla) <= 100.0):
                fails.append(f"FAIL_{prefix}_AUTOLOGOUS_HLA_ABC_BELOW_85PCT:{lin}"); ok = False
    return ok


def _validate_canonical_binding_v6(
    rec: Mapping[str, Any],
    *,
    allow_design_a: bool,
    coating_gate: bool,
    phase: str,
    require_materialization: bool = True,
    require_switches: bool = True,
    expected_candidate_gene: Optional[str] = None,
    expected_comparator_nt_lot_id: Optional[str] = None,
    expected_coating_identity: Optional[Mapping[str, str]] = None,
    require_gate31_on_design_a_r1: bool = False,
) -> tuple[
    Optional[Mapping[str, Any]], str, list[str], list[str],
    Optional[Mapping[str, Any]], Optional[Mapping[str, Any]], Optional[Mapping[str, Any]], Optional[Mapping[str, Any]],
]:
    fails: list[str] = []
    holds: list[str] = []
    scope_track = "PRIMARY"
    mat_ev: Optional[Mapping[str, Any]] = None
    sw_ev: Optional[Mapping[str, Any]] = None
    g0v_ev: Optional[Mapping[str, Any]] = None
    g31_ev: Optional[Mapping[str, Any]] = None

    raw_arm = str(rec.get("target_arm", "")).strip().upper()
    raw_prod = str(rec.get("product_id", "")).strip()
    raw_route = str(rec.get("route_id", "")).strip().upper()
    raw_bank = str(rec.get("bank_id", "")).strip()
    raw_lot = str(rec.get("lot_id", "")).strip()

    if not allow_design_a:
        if raw_arm in DESIGN_A_FORBIDDEN_ALIASES or raw_prod.upper() in DESIGN_A_FORBIDDEN_ALIASES:
            fails.append("FAIL_DESIGN_A_DRUG_FIREWALL_VIOLATION")
            return None, "BLOCKED_DESIGN_A", fails, holds, None, None, None, None

    if raw_prod in LEGACY_NON_TRANSFERABLE_PRODUCTS:
        fails.append("FAIL_LEGACY_PRODUCT_NON_TRANSFERABLE_TO_V090")
        return None, "BLOCKED_LEGACY", fails, holds, None, None, None, None

    spec = CANONICAL_WAVE6_PRODUCTS.get(raw_prod)
    if spec is None:
        fails.append("FAIL_UNRECOGNIZED_CANONICAL_PRODUCT_ID")
        return None, "INVALID", fails, holds, None, None, None, None

    if raw_arm != spec["arm"]:
        fails.append("FAIL_ARM_PRODUCT_MISMATCH")
    if raw_route not in spec["allowed_routes"]:
        fails.append("FAIL_ROUTE_NOT_ALLOWED_FOR_CANONICAL_PRODUCT")
    if not raw_bank or not raw_lot:
        fails.append("FAIL_MISSING_BANK_OR_LOT_ID")

    prod_s, bank_s, lot_s, route_s = raw_prod, raw_bank, raw_lot, raw_route

    if require_materialization and phase != "BENCH_UNEDITED":
        mat_ev = _validate_content_receipt(
            rec.get("materialization_evidence"),
            expected_stage="BANK_MATERIALIZATION", expected_prod=prod_s, expected_bank=bank_s,
            expected_lot=lot_s, expected_route=None, forbid_route=True,
            expected_scope="exact_product",
            allowed_extra_keys=frozenset({"edited_allele_qc_passed"}),
            fails=fails, holds=holds,
            missing_hold="HOLD_CANONICAL_BANK_MATERIALIZATION_MISSING",
            fail_code="FAIL_CANONICAL_BANK_MATERIALIZATION_FAILED",
            mismatch_code="FAIL_BANK_MATERIALIZATION_SCOPE_MISMATCH",
        )
        if mat_ev is not None and not (is_strict_bool(mat_ev.get("edited_allele_qc_passed")) and mat_ev["edited_allele_qc_passed"]):
            fails.append("FAIL_BANK_MATERIALIZATION_ALLELE_QC_FAILED")

    if coating_gate:
        pair = (raw_prod, raw_route)
        track_mode = str(rec.get("track_mode", "PRIMARY")).strip().upper()
        credit_scope = str(rec.get("credit_scope", "PRIMARY")).strip().upper()
        if pair in ACTIVE_PRIMARY_COATING_PAIRS:
            scope_track = "PRIMARY"
            if track_mode != "PRIMARY" or credit_scope != "PRIMARY":
                fails.append("FAIL_PRIMARY_PAIR_REQUIRES_PRIMARY_TRACK_AND_CREDIT_SCOPE")
        elif pair in DEFERRED_COATING_PAIRS:
            scope_track = "DEFERRED_NON_PRIMARY"
            if track_mode != "DEFERRED_NON_PRIMARY" or credit_scope != "NON_PRIMARY_TRACK_ONLY":
                fails.append("FAIL_DEFERRED_TRACK_CANNOT_CLAIM_PRIMARY_CREDIT")
            if raw_prod == "ISLET1_DESIGN_X_V090" and raw_route == "R1" and phase != "BENCH_UNEDITED":
                g31_ev = _validate_content_receipt(
                    rec.get("gate31_evidence"),
                    expected_stage="GATE-31", expected_prod=prod_s, expected_bank=bank_s,
                    expected_lot=lot_s, expected_route="R1",
                    expected_parent=mat_ev,
                    allowed_extra_keys=GATE31_QUANT_EXTRAS,
                    fails=fails, holds=holds,
                    missing_hold="HOLD_DEFERRED_X_R1_MISSING_GATE31_EVIDENCE",
                    fail_code="FAIL_DEFERRED_X_R1_GATE31_FAILED",
                    mismatch_code="FAIL_DEFERRED_X_R1_GATE31_SCOPE_MISMATCH",
                )
                if g31_ev is not None:
                    _validate_gate31_quantitative(g31_ev, require_coating_stability=True, fails=fails, holds=holds, prefix="DEFERRED_X_R1")
        elif pair in SENSITIVITY_COATING_PAIRS:
            scope_track = "SENSITIVITY_Z_R3P"
            if track_mode != "SENSITIVITY_Z_R3P" or credit_scope != "SENSITIVITY_ONLY":
                fails.append("FAIL_SENSITIVITY_Z_CANNOT_CLAIM_PRIMARY_CREDIT")
        elif pair in SEPARATE_ROUTE4_COATING_PAIRS:
            scope_track = "SEPARATE_ROUTE4_VEHICLE"
            if track_mode != "SEPARATE_ROUTE4_VEHICLE" or credit_scope != "NON_PRIMARY_TRACK_ONLY":
                fails.append("FAIL_ROUTE4_MUST_USE_SEPARATE_VEHICLE_TRACK")
            r4_ev = _validate_content_receipt(
                rec.get("route4_vehicle_evidence"),
                expected_stage="ROUTE4_VEHICLE", expected_prod=prod_s, expected_bank=bank_s,
                expected_lot=lot_s, expected_route="R4",
                allowed_extra_keys=frozenset({"route4_vehicle_id"}),
                fails=fails, holds=holds,
                missing_hold="HOLD_ROUTE4_REQUIRES_SEPARATE_VEHICLE_RECEIPT",
                fail_code="FAIL_ROUTE4_VEHICLE_FAILED",
                mismatch_code="FAIL_ROUTE4_VEHICLE_SCOPE_MISMATCH",
            )
            if r4_ev is not None and not is_nonempty_str(r4_ev.get("route4_vehicle_id")):
                fails.append("FAIL_ROUTE4_MISSING_VEHICLE_ID")
        else:
            fails.append("FAIL_OUT_OF_ACTIVE_GATE_SCOPE_PRODUCT_ROUTE")
            scope_track = "OUT_OF_SCOPE"
    else:
        need_g31_x = (prod_s == "ISLET1_DESIGN_X_V090")
        need_g31_a = (prod_s == "ISLET1_DESIGN_A_V080_REF" and route_s == "R1" and require_gate31_on_design_a_r1)
        if need_g31_x and route_s != "R1":
            fails.append("FAIL_DEFERRED_X_REQUIRES_R1_COUPLED_GATE31_SCOPE")
        elif need_g31_x or need_g31_a:
            g31_ev = _validate_content_receipt(
                rec.get("gate31_evidence"),
                expected_stage="GATE-31", expected_prod=prod_s, expected_bank=bank_s,
                expected_lot=lot_s, expected_route="R1",
                expected_parent=mat_ev,
                allowed_extra_keys=GATE31_QUANT_EXTRAS,
                fails=fails, holds=holds,
                missing_hold="HOLD_MISSING_R1_GATE31_EVIDENCE",
                fail_code="FAIL_R1_GATE31_FAILED",
                mismatch_code="FAIL_R1_GATE31_SCOPE_MISMATCH",
            )
            if g31_ev is not None:
                _validate_gate31_quantitative(g31_ev, require_coating_stability=False, fails=fails, holds=holds, prefix="R1")

    if require_switches and phase != "BENCH_UNEDITED":
        sw_extras = frozenset({
            "switch_name", "canonical_gate34_producer_sha256", "canonical_gate34_verdict",
            "gate34_passed", "oq012_clonogenic_block",
            "matched_control_switch_parity_evidence",
            "primary_tbp_icasp9_oq012", "backup_cdk1_hsvtk_oq012",
            "orthogonal_gcv_cid_non_interference",
            "transient_target_engagement_record",
            "assay_started_at_utc", "assay_completed_at_utc", "specimen_id",
            "assay_24h_collection_utc", "assay_72h_collection_utc",
        })
        sw_ev = _validate_content_receipt(
            rec.get("native_switch_evidence"),
            expected_stage="NATIVE_SAFETY_SWITCH", expected_prod=prod_s, expected_bank=bank_s,
            expected_lot=lot_s, expected_route=route_s, expected_scope="exact_product",
            expected_candidate_gene=expected_candidate_gene,
            expected_comparator_nt_lot_id=expected_comparator_nt_lot_id,
            expected_coating_identity=expected_coating_identity,
            expected_parent=mat_ev,
            allowed_extra_keys=sw_extras, fails=fails, holds=holds,
            missing_hold="HOLD_NATIVE_SAFETY_SWITCH_EVIDENCE_MISSING",
            fail_code="FAIL_NATIVE_SAFETY_SWITCH_FAILED",
            mismatch_code="FAIL_NATIVE_SAFETY_SWITCH_SCOPE_MISMATCH",
        )
        if sw_ev is not None:
            if sw_ev.get("switch_name") != spec["required_switch"]:
                fails.append("FAIL_NATIVE_SAFETY_SWITCH_MISMATCH_FOR_PRODUCT")
            if not is_valid_sha256_hex(sw_ev.get("canonical_gate34_producer_sha256")):
                fails.append("FAIL_NATIVE_SAFETY_SWITCH_MISSING_CANONICAL_GATE34_SHA256")
            if sw_ev.get("canonical_gate34_verdict") != "PASS" or not (is_strict_bool(sw_ev.get("gate34_passed")) and sw_ev["gate34_passed"]):
                fails.append("FAIL_NATIVE_SAFETY_SWITCH_GATE34_NOT_PASSED")
            _validate_oq012_gate34_clonogenic_block(
                sw_ev.get("oq012_clonogenic_block"), fails=fails, holds=holds, prefix="NATIVE_SWITCH",
            )
            exp_ctrl_lot = (
                expected_comparator_nt_lot_id
                if expected_comparator_nt_lot_id is not None
                else (expected_coating_identity.get("matched_blank_vehicle_lot_id") if expected_coating_identity is not None else None)
            )
            _validate_matched_control_switch_parity(
                sw_ev.get("matched_control_switch_parity_evidence"),
                expected_control_lot_id=exp_ctrl_lot,
                fails=fails, holds=holds, prefix="NATIVE_SWITCH",
            )
            if spec["required_switch"] == "DUAL_TBP_ICASP9_PLUS_CDK1_HSVTK":
                _validate_oq012_gate34_clonogenic_block(
                    sw_ev.get("primary_tbp_icasp9_oq012"), fails=fails, holds=holds, prefix="DUAL_PRIMARY_ICASP9",
                )
                _validate_oq012_gate34_clonogenic_block(
                    sw_ev.get("backup_cdk1_hsvtk_oq012"), fails=fails, holds=holds, prefix="DUAL_BACKUP_HSVTK",
                )
                if not (is_strict_bool(sw_ev.get("orthogonal_gcv_cid_non_interference")) and sw_ev["orthogonal_gcv_cid_non_interference"]):
                    fails.append("FAIL_DUAL_SWITCH_ORTHOGONAL_NON_INTERFERENCE_UNVERIFIED")

        g0v_extras = frozenset({
            "canonical_gate0v_producer_sha256", "canonical_gate0v_tier",
            "prior_bank_qualification_sha256", "archived_bank_payload_verified",
            "independent_sampling_unit_class", "independent_biological_units_n",
            "clustering_design_effect_deff", "exposed_product_tested",
            "regime_by_lineage_raw_counts",
            "transient_target_engagement_record",
            "assay_started_at_utc", "assay_completed_at_utc", "specimen_id",
            "assay_24h_collection_utc", "assay_72h_collection_utc",
        })
        g0v_ev = _validate_content_receipt(
            rec.get("gate0v_evidence"),
            expected_stage="GATE-0V-KILL", expected_prod=prod_s, expected_bank=bank_s,
            expected_lot=lot_s, expected_route=route_s, expected_scope="exact_product",
            expected_candidate_gene=expected_candidate_gene,
            expected_comparator_nt_lot_id=expected_comparator_nt_lot_id,
            expected_coating_identity=expected_coating_identity,
            expected_parent=mat_ev,
            allowed_extra_keys=g0v_extras, fails=fails, holds=holds,
            missing_hold="HOLD_GATE0V_KILL_EVIDENCE_MISSING",
            fail_code="FAIL_GATE0V_KILL_FAILED",
            mismatch_code="FAIL_GATE0V_KILL_SCOPE_MISMATCH",
        )
        if g0v_ev is not None:
            _validate_gate0v_kill_receipt(g0v_ev, prod_id=prod_s, fails=fails, holds=holds)

    return spec, scope_track, fails, holds, mat_ev, sw_ev, g0v_ev, g31_ev


# ---------------------------------------------------------------------------
# GATE-40 (IIP-0062 / DEC-143): Optional Non-Design-A 14-Day Pirfenidone Coating
# ---------------------------------------------------------------------------

def _compute_pfd_continuous_envelope_24_336(
    hrs: Sequence[float],
    u_ser: Sequence[float],
    l_ser: Sequence[float],
    ke_a: float,
    kr_a: float,
    ke_w: float,
) -> tuple[float, float]:
    """Compute continuous [0, hrs[-1]] peak and exact clipped [24.0, 336.0] trough (incl. boundary-straddling intervals!)."""
    if not hrs or hrs[0] > 24.0 + 1e-9 or hrs[-1] < 336.0 - 1e-9:
        return float("inf"), 0.0
    cont_pk = u_ser[0] * math.exp(ke_a * hrs[0])
    cont_tr = float("inf")
    for idx_e in range(1, len(hrs)):
        t1, t2 = hrs[idx_e - 1], hrs[idx_e]
        dt_e = t2 - t1
        ke_use = ke_a if t2 <= 336.0 + 1e-9 else ke_w
        u1, u2 = u_ser[idx_e - 1], u_ser[idx_e]
        if u1 > 0.0 and u2 > 0.0:
            t_u = max(0.0, min(dt_e, (math.log(u2 / u1) + ke_use * dt_e) / (kr_a + ke_use)))
            pk_seg = min(u1 * math.exp(kr_a * t_u), u2 * math.exp(ke_use * (dt_e - t_u)))
        else:
            pk_seg = max(u1, u2)
        cont_pk = max(cont_pk, pk_seg)
        # Clip EVERY interval [t1, t2] to [a, b] = [max(t1, 24.0), min(t2, 336.0)]!
        a = max(t1, 24.0)
        b = min(t2, 336.0)
        if a <= b + 1e-9:
            b_eff = max(a, b)
            l1, l2 = l_ser[idx_e - 1], l_ser[idx_e]
            if l1 <= 0.0 and l2 <= 0.0:
                tr_seg = 0.0
            elif l1 <= 0.0:
                tr_seg = l2 * math.exp(-kr_a * (t2 - a))
            elif l2 <= 0.0:
                tr_seg = l1 * math.exp(-ke_a * (b_eff - t1))
            else:
                t_cross = (math.log(l1) - math.log(l2) + ke_a * t1 + kr_a * t2) / (ke_a + kr_a)
                t_star = max(a, min(b_eff, t_cross))
                tr_seg = max(l1 * math.exp(-ke_a * (t_star - t1)), l2 * math.exp(-kr_a * (t2 - t_star)))
            cont_tr = min(cont_tr, tr_seg)
    if cont_tr == float("inf"):
        cont_tr = 0.0
    return cont_pk, cont_tr


GATE40_A0A_KEYS: FrozenSet[str] = frozenset({"phase", "a0a_evidence"})
GATE40_BENCH_KEYS: FrozenSet[str] = GATE40_A0A_KEYS | frozenset({
    "track_mode", "credit_scope", "target_arm", "product_id", "bank_id", "lot_id", "route_id",
    "gate31_evidence", "route4_vehicle_evidence",
    "a0b_evidence", "a1_bench_evidence",
})
GATE40_EXACT_ONLY_KEYS: FrozenSet[str] = frozenset({
    "materialization_evidence", "native_switch_evidence", "gate0v_evidence",
    "a1_evidence", "a2_evidence", "a3_evidence", "a4a_evidence",
    "a4b_preregistration_receipt", "a4b_evidence",
})
GATE40_EXACT_KEYS: FrozenSet[str] = GATE40_BENCH_KEYS | GATE40_EXACT_ONLY_KEYS


def evaluate_gate40_pirfenidone_h4(rec: Mapping[str, Any]) -> dict[str, Any]:
    """GATE-40 (IIP-0062): Fail-closed 3-phase pirfenidone adjudicator with burst Cmax convolution, matched-vehicle Readout-2/3B, & raw two-cohort A-4b."""
    phase = str(rec.get("phase", "EXACT_PRODUCT")).strip().upper()
    if phase not in ("ROUTE_FREE_A0A", "BENCH_UNEDITED", "EXACT_PRODUCT"):
        return {
            "gate": "GATE-40", "verdict": "FAIL", "release_authorizing": False,
            "live_ledger_authenticated": False, "upstream_archive_verification": OFFLINE_ARCHIVE_NOTE,
            "product_id": rec.get("product_id"), "required_switch": None,
            "failures": ["FAIL_INVALID_PHASE"], "holds": [],
        }

    fails: list[str] = []
    holds: list[str] = []
    spec: Optional[Mapping[str, Any]] = None
    scope_track = "ROUTE_FREE_A0A"
    mat_ev = sw_ev = g0v_ev = g31_ev = None

    a0b_raw = rec.get("a0b_evidence")
    coat_id: Optional[dict[str, str]] = None
    if phase != "ROUTE_FREE_A0A" and isinstance(a0b_raw, Mapping):
        if all(is_nonempty_str(a0b_raw.get(k)) for k in COATING_IDENTITY_KEYS):
            coat_id = {k: str(a0b_raw[k]).strip() for k in sorted(COATING_IDENTITY_KEYS)}

    if phase == "ROUTE_FREE_A0A":
        _check_allowed_keys(rec, GATE40_A0A_KEYS, fails, "GATE40_A0A")
    else:
        spec, scope_track, b_fails, b_holds, mat_ev, sw_ev, g0v_ev, g31_ev = _validate_canonical_binding_v6(
            rec, allow_design_a=False, coating_gate=True, phase=phase,
            expected_coating_identity=coat_id,
        )
        fails.extend(b_fails)
        holds.extend(b_holds)
        if phase == "BENCH_UNEDITED":
            _check_forbidden_keys(rec, GATE40_EXACT_ONLY_KEYS, fails, "FAIL_BENCH_PHASE_FORBIDS_EXACT_OR_ANIMAL_FIELDS")
            _check_allowed_keys(rec, GATE40_BENCH_KEYS, fails, "GATE40_BENCH")
        else:
            _check_allowed_keys(rec, GATE40_EXACT_KEYS, fails, "GATE40")

    # Gate A-0a (route-free, >= 7 d elapsed observation + raw concentration-response bracket verification!)
    a0a_extras = frozenset({
        "study_start_utc", "analysis_record_sha256", "a0a_assay_matrix", "a0a_dialysis_fu_replicates",
        "a0a_matrix_fu_by_assay", "a0a_limits_already_fu_adjusted",
        "fu_measured", "emax_alpha_sma_pct", "emax_col1a1_pct",
        "ic50_free_alpha_sma_uM", "ic50_free_col1a1_uM", "ic50_free_max_u95_uM",
        "cc10_free_7d_l95_uM", "c_sprout_max_free_7d_l95_uM",
        "c_upper_provisional_7d_l95_uM", "endpoints_bracketed",
        "tested_free_conc_uM_grid", "alpha_sma_inhibition_pct_grid", "col1a1_inhibition_pct_grid",
        "viability_7d_pct_grid", "sprouting_7d_pct_grid", "sprouting_delayed_7d_pct_grid",
        "a0a_donor_replicates_by_conc", "a0a_fit_artifact_receipt",
    })
    a0a_ev = _validate_content_receipt(
        rec.get("a0a_evidence"),
        expected_stage="A-0a", expected_prod=None, expected_bank=None,
        expected_lot=None, expected_route=None, forbid_route=True,
        expected_scope="route_free", allowed_extra_keys=a0a_extras,
        fails=fails, holds=holds,
        missing_hold="HOLD_GATE_A0A_RECEIPT_MISSING",
        fail_code="FAIL_GATE_A0A_FAILED",
        mismatch_code="FAIL_GATE_A0A_SCOPE_MISMATCH",
    )
    a0a_ok = a0a_ev is not None and a0a_ev.get("verdict") == "PASS"
    ic50_u95_val: Optional[float] = None
    c_up_7d_val: Optional[float] = None
    ic50_u95_op: Optional[float] = None
    ic50_u95_wash_op: Optional[float] = None
    c_up_7d_op: Optional[float] = None
    a0a_fu_ratios: Optional[tuple[float, float, float]] = None  # (eff_u95/mean, vasc_l95/mean, eff_l95/mean)
    a0a_already_fu_adj = False
    if a0a_ev is not None:
        t_a0a_st = parse_utc_iso_ts(a0a_ev.get("study_start_utc"))
        t_a0a_end = parse_utc_iso_ts(a0a_ev.get("recorded_at_utc"))
        if t_a0a_st is None or t_a0a_end is None or (t_a0a_end - t_a0a_st) < timedelta(days=7):
            fails.append("FAIL_GATE_A0A_ELAPSED_STUDY_DURATION_LT_7_DAYS"); a0a_ok = False
        fu = a0a_ev.get("fu_measured")
        em_s = a0a_ev.get("emax_alpha_sma_pct")
        em_c = a0a_ev.get("emax_col1a1_pct")
        ic_s = a0a_ev.get("ic50_free_alpha_sma_uM")
        ic_c = a0a_ev.get("ic50_free_col1a1_uM")
        ic_u95 = a0a_ev.get("ic50_free_max_u95_uM")
        cc7 = a0a_ev.get("cc10_free_7d_l95_uM")
        sp7 = a0a_ev.get("c_sprout_max_free_7d_l95_uM")
        c_up = a0a_ev.get("c_upper_provisional_7d_l95_uM")
        if not all(is_finite_num(x) for x in (fu, em_s, em_c, ic_s, ic_c, ic_u95, cc7, sp7, c_up)):
            holds.append("HOLD_GATE_A0A_MISSING_METRICS"); a0a_ok = False
        else:
            if not (0.0 <= float(em_s) <= 100.0 and 0.0 <= float(em_c) <= 100.0):
                fails.append("FAIL_GATE_A0A_EMAX_OUT_OF_DOMAIN_0_100"); a0a_ok = False
            elif float(em_s) < 50.0 or float(em_c) < 50.0:
                fails.append("FAIL_GATE_A0A_EMAX_BELOW_50PCT"); a0a_ok = False
            # Populate outer a0a_fu_ratios = (eff_u95/mean, vasc_l95/mean, eff_l95/mean)
            if not (0.0 < float(fu) <= 1.0):
                fails.append("FAIL_GATE_A0A_FU_OUT_OF_DOMAIN"); a0a_ok = False
            else:
                a0a_mat = a0a_ev.get("a0a_assay_matrix")
                a0a_fu_reps = a0a_ev.get("a0a_dialysis_fu_replicates")
                a0a_mfu = a0a_ev.get("a0a_matrix_fu_by_assay")
                req_assays = ("fibrosis_efficacy_assay", "vascular_viability_assay")
                mfu_item_keys = frozenset({"matrix_id", "nominal_conc_uM_grid", "dialysis_fu_replicates", "measured_fu_mean", "analytical_sample_record_sha256"})
                if (
                    not is_nonempty_str(a0a_mat)
                    or not (isinstance(a0a_fu_reps, list) and len(a0a_fu_reps) >= 3 and all(is_finite_num(x) and 0.0 < float(x) <= 1.0 for x in a0a_fu_reps))
                    or not (isinstance(a0a_mfu, Mapping) and set(a0a_mfu.keys()) == set(req_assays))
                ):
                    holds.append("HOLD_GATE_A0A_MISSING_DIALYSIS_FU_MATRIX_REPLICATES"); a0a_ok = False
                else:
                    fu_rf = [float(x) for x in a0a_fu_reps]
                    fu_rf_mu = sum(fu_rf) / len(fu_rf)
                    if abs(fu_rf_mu - float(fu)) > min(0.005, 0.01 * fu_rf_mu):
                        fails.append("FAIL_GATE_A0A_FU_MISMATCH_VS_DIALYSIS_REPLICATES"); a0a_ok = False
                    elif sample_t_one_sided_bounds(fu_rf, alpha=0.05) is None:
                        holds.append("HOLD_GATE_A0A_FU_DIALYSIS_ZERO_DISPERSION"); a0a_ok = False
                    mfu_bounds: dict[str, tuple[float, float, float, list[float]]] = {}
                    for ak_m in req_assays:
                        mitem = a0a_mfu[ak_m]
                        if (
                            not isinstance(mitem, Mapping) or set(mitem.keys()) != mfu_item_keys
                            or not is_nonempty_str(mitem.get("matrix_id"))
                            or not is_valid_sha256_hex(mitem.get("analytical_sample_record_sha256"))
                            or not (is_finite_num(mitem.get("measured_fu_mean")) and 0.0 < float(mitem["measured_fu_mean"]) <= 1.0)
                            or not (isinstance(mitem.get("dialysis_fu_replicates"), list) and len(mitem["dialysis_fu_replicates"]) >= 3 and all(is_finite_num(x) and 0.0 < float(x) <= 1.0 for x in mitem["dialysis_fu_replicates"]))
                            or not (isinstance(mitem.get("nominal_conc_uM_grid"), list) and len(mitem["nominal_conc_uM_grid"]) >= 7 and all(is_finite_num(x) and float(x) >= 0.0 for x in mitem["nominal_conc_uM_grid"]))
                        ):
                            holds.append("HOLD_GATE_A0A_MISSING_DIALYSIS_FU_MATRIX_REPLICATES"); a0a_ok = False; break
                        m_rf = [float(x) for x in mitem["dialysis_fu_replicates"]]
                        m_mu = sum(m_rf) / len(m_rf)
                        if abs(m_mu - float(mitem["measured_fu_mean"])) > min(0.005, 0.01 * m_mu):
                            fails.append("FAIL_GATE_A0A_FU_MISMATCH_VS_DIALYSIS_REPLICATES"); a0a_ok = False; break
                        tb_mfu = sample_t_one_sided_bounds(m_rf, alpha=0.025)
                        if tb_mfu is None:
                            holds.append("HOLD_GATE_A0A_FU_DIALYSIS_ZERO_DISPERSION"); a0a_ok = False; break
                        mfu_bounds[ak_m] = (m_mu, max(1e-6, tb_mfu[1]), min(1.0, tb_mfu[2]), [float(x) for x in mitem["nominal_conc_uM_grid"]])
                    if len(mfu_bounds) == 2:
                        eff_mu, eff_l95, eff_u95, _ = mfu_bounds["fibrosis_efficacy_assay"]
                        vasc_mu, vasc_l95, _, _ = mfu_bounds["vascular_viability_assay"]
                        a0a_fu_ratios = (eff_u95 / eff_mu, vasc_l95 / vasc_mu, eff_l95 / eff_mu)
            if min(float(ic_s), float(ic_c), float(ic_u95), float(cc7), float(sp7), float(c_up)) <= 0.0:
                fails.append("FAIL_GATE_A0A_NONPOSITIVE_CONCENTRATION"); a0a_ok = False
            else:
                expected_7d_min = min(float(cc7), float(sp7))
                if abs(float(c_up) - expected_7d_min) > 1e-9:
                    fails.append("FAIL_GATE_A0A_7D_CEILING_NOT_MIN_OF_VIABILITY_AND_SPROUTING"); a0a_ok = False
                if float(ic_u95) < max(float(ic_s), float(ic_c)) - 1e-12:
                    fails.append("FAIL_GATE_A0A_U95_BELOW_FITTED_IC50"); a0a_ok = False
                if max(float(ic_s), float(ic_c)) / min(float(ic_s), float(ic_c)) > 3.0:
                    fails.append("FAIL_GATE_A0A_ENDPOINT_SPLIT_GT_3X"); a0a_ok = False
                if expected_7d_min / float(ic_u95) < 1.5:
                    fails.append("FAIL_GATE_A0A_MARGIN_BELOW_1P5X"); a0a_ok = False
                ic50_u95_val = float(ic_u95)
                c_up_7d_val = expected_7d_min
                if "a0a_limits_already_fu_adjusted" in a0a_ev:
                    if not is_strict_bool(a0a_ev["a0a_limits_already_fu_adjusted"]):
                        fails.append("FAIL_GATE_A0A_INVALID_FU_ADJUSTED_FLAG"); a0a_ok = False
                    else:
                        a0a_already_fu_adj = bool(a0a_ev["a0a_limits_already_fu_adjusted"])
                if a0a_fu_ratios is not None:
                    eff_fu_f, vasc_fu_f, eff_fu_lo_f = a0a_fu_ratios
                    if a0a_already_fu_adj:
                        ic50_u95_op = ic50_u95_val
                        c_up_7d_op = c_up_7d_val
                        ic50_u95_wash_op = ic50_u95_val * (eff_fu_lo_f / eff_fu_f)
                    else:
                        ic50_u95_op = ic50_u95_val * eff_fu_f
                        c_up_7d_op = c_up_7d_val * vasc_fu_f
                        ic50_u95_wash_op = ic50_u95_val * eff_fu_lo_f
                else:
                    ic50_u95_op = ic50_u95_val
                    c_up_7d_op = c_up_7d_val
                    ic50_u95_wash_op = ic50_u95_val
        if not (is_strict_bool(a0a_ev.get("endpoints_bracketed")) and a0a_ev["endpoints_bracketed"]):
            fails.append("FAIL_GATE_A0A_ENDPOINTS_UNBRACKETED"); a0a_ok = False
        if not is_valid_sha256_hex(a0a_ev.get("analysis_record_sha256")):
            fails.append("FAIL_GATE_A0A_MISSING_ANALYSIS_RECORD_SHA256"); a0a_ok = False
        ag_c = a0a_ev.get("tested_free_conc_uM_grid")
        ag_s = a0a_ev.get("alpha_sma_inhibition_pct_grid")
        ag_k = a0a_ev.get("col1a1_inhibition_pct_grid")
        ag_v = a0a_ev.get("viability_7d_pct_grid")
        ag_p = a0a_ev.get("sprouting_7d_pct_grid")
        ag_pd = a0a_ev.get("sprouting_delayed_7d_pct_grid")
        if not (
            isinstance(ag_c, list) and len(ag_c) >= 7
            and all(isinstance(g, list) and len(g) == len(ag_c) and all(is_finite_num(x) for x in g) for g in (ag_c, ag_s, ag_k, ag_v, ag_p, ag_pd))
        ):
            fails.append("FAIL_GATE_A0A_MISSING_RAW_CONC_RESPONSE_GRID"); a0a_ok = False
        elif ic50_u95_val is not None and c_up_7d_val is not None:
            cg = [float(x) for x in ag_c]
            sg = [float(x) for x in ag_s]
            kg = [float(x) for x in ag_k]
            vg = [float(x) for x in ag_v]
            pg = [float(x) for x in ag_p]
            pgd = [float(x) for x in ag_pd]
            if cg[0] != 0.0 or any(cg[i] >= cg[i + 1] for i in range(len(cg) - 1)):
                fails.append("FAIL_GATE_A0A_INVALID_CONC_GRID_ORDER"); a0a_ok = False
            else:
                # Verify BOTH assay matrices reproduce tested_free_conc_uM_grid from nominal x RECOMPUTED dialysis replicate mean m_mu
                # (exact same baseline as eff_u95/eff_mu & vasc_l95/vasc_mu so nominal->free and uncertainty cancel exactly!)
                a0a_mfu_g = a0a_ev.get("a0a_matrix_fu_by_assay")
                if isinstance(a0a_mfu_g, Mapping) and set(a0a_mfu_g.keys()) == {"fibrosis_efficacy_assay", "vascular_viability_assay"}:
                    for ak_g in ("fibrosis_efficacy_assay", "vascular_viability_assay"):
                        mg_it = a0a_mfu_g[ak_g]
                        if isinstance(mg_it, Mapping) and isinstance(mg_it.get("nominal_conc_uM_grid"), list) and isinstance(mg_it.get("dialysis_fu_replicates"), list) and len(mg_it["dialysis_fu_replicates"]) >= 3 and all(is_finite_num(x) and 0.0 < float(x) <= 1.0 for x in mg_it["dialysis_fu_replicates"]):
                            ng_f = [float(x) for x in mg_it["nominal_conc_uM_grid"]]
                            recomp_fmu_g = sum(float(x) for x in mg_it["dialysis_fu_replicates"]) / len(mg_it["dialysis_fu_replicates"])
                            if len(ng_f) != len(cg) or ng_f[0] != 0.0 or any(abs((ng_f[i] * recomp_fmu_g) - cg[i]) > max(0.05, 0.01 * cg[i]) for i in range(len(cg))):
                                fails.append(f"FAIL_GATE_A0A_FREE_GRID_MISMATCH_VS_NOMINAL_AND_FU:{ak_g}"); a0a_ok = False
                if a0a_fu_ratios is not None and ic50_u95_op is not None and c_up_7d_op is not None:
                    if c_up_7d_op / ic50_u95_op < 1.5:
                        fails.append("FAIL_GATE_A0A_FU_PROPAGATED_MARGIN_BELOW_1P5X"); a0a_ok = False
                veh_ok = (sg[0] <= 15.0 and kg[0] <= 15.0 and vg[0] >= 95.0 and pg[0] >= 95.0 and pgd[0] >= 95.0)
                sma_cross = any(sg[i] < 50.0 for i in range(len(cg)) if cg[i] <= ic50_u95_val + 1e-9) and any(sg[i] >= 50.0 for i in range(len(cg)) if cg[i] <= ic50_u95_val + 1e-9)
                col_cross = any(kg[i] < 50.0 for i in range(len(cg)) if cg[i] <= ic50_u95_val + 1e-9) and any(kg[i] >= 50.0 for i in range(len(cg)) if cg[i] <= ic50_u95_val + 1e-9)
                max_safe_c = max((cg[i] for i in range(len(cg)) if vg[i] >= 90.0 and pg[i] >= 90.0 and pgd[i] >= 90.0 and all(vg[k] >= 90.0 and pg[k] >= 90.0 and pgd[k] >= 90.0 for k in range(i + 1))), default=0.0)
                unsafe_above = any(vg[i] < 90.0 or pg[i] < 90.0 or pgd[i] < 90.0 for i in range(len(cg)) if cg[i] > max_safe_c + 1e-9)
                if not (veh_ok and sma_cross and col_cross and c_up_7d_val <= max_safe_c + 1e-9 and unsafe_above):
                    fails.append("FAIL_GATE_A0A_RAW_CONC_RESPONSE_CONTRADICTS_BRACKET_OR_CEILING"); a0a_ok = False
                # Donor-level replicate verification + content-hashed source fit artifact (recomputes L95_t safety & potency bounds!)
                a0a_reps = a0a_ev.get("a0a_donor_replicates_by_conc")
                a0a_fit = a0a_ev.get("a0a_fit_artifact_receipt")
                if a0a_reps is None or a0a_fit is None:
                    holds.append("HOLD_GATE_A0A_MISSING_DONOR_REPLICATES_OR_FIT_ARTIFACT"); a0a_ok = False
                elif not isinstance(a0a_reps, list) or len(a0a_reps) != len(cg):
                    fails.append("FAIL_GATE_A0A_MALFORMED_DONOR_REPLICATES"); a0a_ok = False
                else:
                    fit_keys = frozenset({
                        "analysis_method", "donor_ids", "raw_replicates_sha256", "analysis_record_sha256",
                        "ic50_free_alpha_sma_uM", "ic50_free_col1a1_uM", "ic50_free_max_u95_uM",
                        "cc10_free_7d_l95_uM", "c_sprout_max_free_7d_l95_uM", "receipt_sha256",
                    })
                    if not isinstance(a0a_fit, Mapping) or set(a0a_fit.keys()) != fit_keys:
                        fails.append("FAIL_GATE_A0A_MALFORMED_FIT_ARTIFACT_RECEIPT"); a0a_ok = False
                    else:
                        fsha = a0a_fit.get("receipt_sha256")
                        fdids = a0a_fit.get("donor_ids")
                        if (
                            not is_valid_sha256_hex(fsha) or compute_receipt_sha256(a0a_fit) != fsha
                            or a0a_fit.get("analysis_method") != "SIMULTANEOUS_BONFERRONI_GRID_BRACKET_STUDENT_T"
                            or a0a_fit.get("raw_replicates_sha256") != sha256_bytes(canonical_json_bytes(a0a_reps))
                            or a0a_fit.get("analysis_record_sha256") != a0a_ev.get("analysis_record_sha256")
                            or not (isinstance(fdids, list) and len(fdids) >= 3 and all(is_nonempty_str(d) for d in fdids) and len({str(d).strip().upper() for d in fdids}) == len(fdids))
                            or any(not is_finite_num(a0a_fit.get(k)) or abs(float(a0a_fit[k]) - float(a0a_ev[k])) > 1e-6 for k in ("ic50_free_alpha_sma_uM", "ic50_free_col1a1_uM", "ic50_free_max_u95_uM", "cc10_free_7d_l95_uM", "c_sprout_max_free_7d_l95_uM"))
                        ):
                            fails.append("FAIL_GATE_A0A_FIT_ARTIFACT_DIGEST_OR_SUMMARY_MISMATCH"); a0a_ok = False
                        else:
                            exp_dids = [str(d).strip().upper() for d in fdids]
                            n_don = len(exp_dids)
                            # Exact simultaneous grid-wide Bonferroni alpha across all (G - 1) treated doses x 2 efficacy / 10 safety endpoints
                            # (vascular spheroid viability + macrophage-fibroblast efficacy-culture viability + 8 Day-0/delayed vascular endpoints;
                            # i_c == 0 is the defined 0 uM self-normalized vehicle control baseline; FWER <= 0.05 across all treated doses)
                            n_treated_a0a = max(1, len(cg) - 1)
                            alpha_eff_a0a = 0.05 / float(2 * n_treated_a0a)
                            alpha_safe_a0a = 0.05 / float(10 * n_treated_a0a)
                            qual_safe_i = -1
                            qual_vasc_safe_i = -1
                            qual_eff_viab_i = -1
                            qual_sprout_i = -1
                            reps_ok = True
                            sma_l95_by_i: list[float] = []
                            col_l95_by_i: list[float] = []
                            eff_viab_l95_by_i: list[float] = []
                            sma_by_conc_donors: list[list[float]] = []
                            col_by_conc_donors: list[list[float]] = []
                            a0a_d0_vasc = ("day0_sprout_length_7d_pct", "day0_branching_7d_pct", "day0_lumen_formation_7d_pct")
                            a0a_del_vasc = ("delayed_sprout_length_7d_pct", "delayed_branching_7d_pct", "delayed_lumen_formation_7d_pct")
                            a0a_eff_viab_keys = (
                                "efficacy_matched_vehicle_record_id",
                                "efficacy_treated_viable_cells_by_donor",
                                "efficacy_vehicle_viable_cells_by_donor",
                                "efficacy_culture_viability_7d_pct",
                            )
                            rep_row_keys = frozenset({
                                "donor_ids", "matched_vehicle_record_id",
                                "alpha_sma_inhibition_pct", "col1a1_inhibition_pct",
                                "viability_7d_pct", "sprouting_7d_pct", "sprouting_delayed_7d_pct",
                            }) | frozenset(a0a_d0_vasc) | frozenset(a0a_del_vasc) | frozenset(a0a_eff_viab_keys)
                            for i_c, rrow in enumerate(a0a_reps):
                                if isinstance(rrow, Mapping) and (
                                    rrow.get("day0_lumen_formation_7d_pct") is None
                                    or rrow.get("delayed_lumen_formation_7d_pct") is None
                                ):
                                    holds.append("HOLD_GATE_A0A_MISSING_LUMEN_FORMATION_DATA"); reps_ok = False; a0a_ok = False; break
                                if isinstance(rrow, Mapping) and any(rrow.get(ek_v) is None for ek_v in a0a_eff_viab_keys):
                                    holds.append("HOLD_GATE_A0A_MISSING_EFFICACY_CULTURE_VIABILITY"); reps_ok = False; a0a_ok = False; break
                                if (
                                    not isinstance(rrow, Mapping) or set(rrow.keys()) != rep_row_keys
                                    or not is_nonempty_str(rrow.get("matched_vehicle_record_id"))
                                    or not is_nonempty_str(rrow.get("efficacy_matched_vehicle_record_id"))
                                    or str(rrow["matched_vehicle_record_id"]).strip().upper() == str(rrow["efficacy_matched_vehicle_record_id"]).strip().upper()
                                ):
                                    fails.append(f"FAIL_GATE_A0A_MALFORMED_DONOR_REPLICATES:{i_c}"); reps_ok = False; a0a_ok = False; break
                                rdids = rrow.get("donor_ids")
                                if not (isinstance(rdids, list) and [str(d).strip().upper() for d in rdids] == exp_dids):
                                    fails.append(f"FAIL_GATE_A0A_DONOR_ID_MISMATCH:{i_c}"); reps_ok = False; a0a_ok = False; break
                                ep_vals: dict[str, list[float]] = {}
                                for ek, gvec in (
                                    ("alpha_sma_inhibition_pct", sg),
                                    ("col1a1_inhibition_pct", kg),
                                    ("viability_7d_pct", vg),
                                    ("sprouting_7d_pct", pg),
                                    ("sprouting_delayed_7d_pct", pgd),
                                ):
                                    ev_arr = rrow.get(ek)
                                    if not (isinstance(ev_arr, list) and len(ev_arr) == n_don and all(is_finite_num(x) for x in ev_arr)):
                                        fails.append(f"FAIL_GATE_A0A_INVALID_DONOR_VALUES:{i_c}:{ek}"); reps_ok = False; a0a_ok = False; break
                                    ef = [float(x) for x in ev_arr]
                                    if abs((sum(ef) / n_don) - gvec[i_c]) > 0.5:
                                        fails.append(f"FAIL_GATE_A0A_GRID_MEAN_MISMATCH_VS_DONORS:{i_c}:{ek}"); reps_ok = False; a0a_ok = False
                                    ep_vals[ek] = ef
                                if not reps_ok:
                                    break
                                for vk in a0a_d0_vasc + a0a_del_vasc:
                                    va = rrow.get(vk)
                                    if not (isinstance(va, list) and len(va) == n_don and all(is_finite_num(x) and 0.0 <= float(x) <= 130.0 for x in va)):
                                        fails.append(f"FAIL_GATE_A0A_INVALID_DONOR_VALUES:{i_c}:{vk}"); reps_ok = False; a0a_ok = False; break
                                    ep_vals[vk] = [float(x) for x in va]
                                if not reps_ok:
                                    break
                                # Separate macrophage-fibroblast efficacy-culture viability & raw viable-cell denominators!
                                et_cells = rrow.get("efficacy_treated_viable_cells_by_donor")
                                ev_cells = rrow.get("efficacy_vehicle_viable_cells_by_donor")
                                ec_viab = rrow.get("efficacy_culture_viability_7d_pct")
                                if not (
                                    isinstance(et_cells, list) and len(et_cells) == n_don and all(is_finite_num(x) and float(x) >= 0.0 for x in et_cells)
                                    and isinstance(ev_cells, list) and len(ev_cells) == n_don and all(is_finite_num(x) and float(x) > 0.0 for x in ev_cells)
                                    and isinstance(ec_viab, list) and len(ec_viab) == n_don and all(is_finite_num(x) and 0.0 <= float(x) <= 130.0 for x in ec_viab)
                                ):
                                    fails.append(f"FAIL_GATE_A0A_INVALID_DONOR_VALUES:{i_c}:efficacy_culture_viability_7d_pct"); reps_ok = False; a0a_ok = False; break
                                ec_viab_recomp = [100.0 * float(et_cells[di]) / float(ev_cells[di]) for di in range(n_don)]
                                if any(abs(ec_viab_recomp[di] - float(ec_viab[di])) > 0.5 for di in range(n_don)):
                                    fails.append(f"FAIL_GATE_A0A_EFFICACY_VIABILITY_MISMATCH_VS_RAW_CELL_COUNTS:{i_c}"); reps_ok = False; a0a_ok = False; break
                                ep_vals["efficacy_culture_viability_7d_pct"] = ec_viab_recomp
                                # Aggregate sprouting series cannot overstate the worst individual vascular component per donor!
                                if any(ep_vals["sprouting_7d_pct"][di] > min(ep_vals[k][di] for k in a0a_d0_vasc) + 0.5 for di in range(n_don)):
                                    fails.append(f"FAIL_GATE_A0A_VASCULAR_COMPOSITE_OVERSTATES_COMPONENT:{i_c}:DAY0"); reps_ok = False; a0a_ok = False; break
                                if any(ep_vals["sprouting_delayed_7d_pct"][di] > min(ep_vals[k][di] for k in a0a_del_vasc) + 0.5 for di in range(n_don)):
                                    fails.append(f"FAIL_GATE_A0A_VASCULAR_COMPOSITE_OVERSTATES_COMPONENT:{i_c}:DELAYED"); reps_ok = False; a0a_ok = False; break
                                def _lsim_of(v: list[float], alpha_v: float) -> float:
                                    tb = sample_t_one_sided_bounds(v, alpha=alpha_v)
                                    if tb is None:
                                        holds.append("HOLD_GATE_A0A_DEGENERATE_ZERO_VARIANCE_UNESTIMABLE")
                                        return float("-inf")
                                    return tb[1]
                                sma_by_conc_donors.append(list(ep_vals["alpha_sma_inhibition_pct"]))
                                col_by_conc_donors.append(list(ep_vals["col1a1_inhibition_pct"]))
                                if i_c == 0:
                                    # 0 uM self-normalized vehicle control: allow identical 0%/100% donor normalization without spurious zero-variance HOLD!
                                    sma_l95_by_i.append(min(ep_vals["alpha_sma_inhibition_pct"]))
                                    col_l95_by_i.append(min(ep_vals["col1a1_inhibition_pct"]))
                                    eff_viab_l95_by_i.append(min(ep_vals["efficacy_culture_viability_7d_pct"]))
                                    veh_spr_ok = all(
                                        min(ep_vals[k]) >= 95.0
                                        for k in ("sprouting_7d_pct", "sprouting_delayed_7d_pct") + a0a_d0_vasc + a0a_del_vasc
                                    )
                                    if veh_spr_ok and qual_sprout_i == -1:
                                        qual_sprout_i = 0
                                    if min(ep_vals["viability_7d_pct"]) >= 95.0 and veh_spr_ok and qual_vasc_safe_i == -1:
                                        qual_vasc_safe_i = 0
                                    if min(ep_vals["efficacy_culture_viability_7d_pct"]) >= 95.0 and qual_eff_viab_i == -1:
                                        qual_eff_viab_i = 0
                                    if min(ep_vals["viability_7d_pct"]) >= 95.0 and min(ep_vals["efficacy_culture_viability_7d_pct"]) >= 95.0 and veh_spr_ok and qual_safe_i == -1:
                                        qual_safe_i = 0
                                else:
                                    sma_l95_by_i.append(_lsim_of(ep_vals["alpha_sma_inhibition_pct"], alpha_eff_a0a))
                                    col_l95_by_i.append(_lsim_of(ep_vals["col1a1_inhibition_pct"], alpha_eff_a0a))
                                    eff_v_lsim = _lsim_of(ep_vals["efficacy_culture_viability_7d_pct"], alpha_safe_a0a)
                                    eff_viab_l95_by_i.append(eff_v_lsim)
                                    both_spr_ok = all(
                                        _lsim_of(ep_vals[k], alpha_safe_a0a) >= 90.0
                                        for k in ("sprouting_7d_pct", "sprouting_delayed_7d_pct") + a0a_d0_vasc + a0a_del_vasc
                                    )
                                    if both_spr_ok and qual_sprout_i == i_c - 1:
                                        qual_sprout_i = i_c
                                    vasc_v_lsim = _lsim_of(ep_vals["viability_7d_pct"], alpha_safe_a0a)
                                    if vasc_v_lsim >= 90.0 and both_spr_ok and qual_vasc_safe_i == i_c - 1:
                                        qual_vasc_safe_i = i_c
                                    if eff_v_lsim >= 90.0 and qual_eff_viab_i == i_c - 1:
                                        qual_eff_viab_i = i_c
                                    if vasc_v_lsim >= 90.0 and eff_v_lsim >= 90.0 and both_spr_ok and qual_safe_i == i_c - 1:
                                        qual_safe_i = i_c
                            if reps_ok:
                                max_qual_safe_c = cg[qual_safe_i] if qual_safe_i >= 0 else -1.0
                                max_qual_vasc_safe_c = cg[qual_vasc_safe_i] if qual_vasc_safe_i >= 0 else -1.0
                                max_qual_eff_viab_c = cg[qual_eff_viab_i] if qual_eff_viab_i >= 0 else -1.0
                                max_qual_spr_c = cg[qual_sprout_i] if qual_sprout_i >= 0 else -1.0
                                # Recompute matrix-specific 7-day f_u-adjusted safety ceiling unconditionally
                                # (vascular endpoints x vasc_l95/mean, efficacy-culture viability x eff_l95/mean, then min)!
                                recomp_c_up_7d_op: Optional[float] = None
                                if a0a_fu_ratios is not None and max_qual_vasc_safe_c >= 0.0 and max_qual_eff_viab_c >= 0.0:
                                    recomp_vasc_7d_adj = max_qual_vasc_safe_c * a0a_fu_ratios[1]
                                    recomp_eff_viab_7d_adj = max_qual_eff_viab_c * a0a_fu_ratios[2]
                                    recomp_c_up_7d_op = min(recomp_vasc_7d_adj, recomp_eff_viab_7d_adj)
                                    recomp_spr_7d_adj = max(0.0, max_qual_spr_c) * a0a_fu_ratios[1]
                                    if a0a_already_fu_adj:
                                        if c_up_7d_val > recomp_c_up_7d_op + 1e-6 or (is_finite_num(sp7) and float(sp7) > recomp_spr_7d_adj + 1e-6):
                                            if "FAIL_GATE_A0A_CLAIMED_FU_ADJUSTED_LIMITS_UNDERSTATED" not in fails:
                                                fails.append("FAIL_GATE_A0A_CLAIMED_FU_ADJUSTED_LIMITS_UNDERSTATED"); a0a_ok = False
                                        c_up_7d_op = min(c_up_7d_val, recomp_c_up_7d_op)
                                    else:
                                        c_up_cap = c_up_7d_val * a0a_fu_ratios[1]
                                        if c_up_7d_val < max_qual_vasc_safe_c - 1e-9 and c_up_7d_val < max_qual_eff_viab_c - 1e-9:
                                            c_up_cap = min(c_up_cap, c_up_7d_val * a0a_fu_ratios[2])
                                        c_up_7d_op = min(c_up_cap, recomp_c_up_7d_op)
                                if c_up_7d_val > max_qual_safe_c + 1e-9:
                                    fails.append("FAIL_GATE_A0A_7D_CEILING_EXCEEDS_DONOR_L95_SAFE_CONC"); a0a_ok = False
                                if is_finite_num(sp7) and float(sp7) > max_qual_spr_c + 1e-9:
                                    fails.append("FAIL_GATE_A0A_SPROUTING_CEILING_EXCEEDS_DAY0_OR_DELAYED_DONOR_L95"); a0a_ok = False
                                idxs_le_ic50 = [i for i in range(len(cg)) if cg[i] <= ic50_u95_val + 1e-9]
                                if not idxs_le_ic50 or sma_l95_by_i[idxs_le_ic50[-1]] < 50.0 or col_l95_by_i[idxs_le_ic50[-1]] < 50.0:
                                    holds.append("HOLD_GATE_A0A_IC50_U95_UNSUBSTANTIATED_BY_DONOR_REPLICATES"); a0a_ok = False
                                elif any(eff_viab_l95_by_i[k] < 90.0 for k in idxs_le_ic50):
                                    fails.append("FAIL_GATE_A0A_EFFICACY_CULTURE_CYTOTOXICITY_CONFOUNDING"); a0a_ok = False
                                # Reconstruct per-donor linear-interpolated 50% crossing concentrations for BOTH alpha-SMA and COL1A1,
                                # verify each claimed IC50 lies inside its own curve's crossing bracket, & enforce uncertainty-propagated <= 3x split!
                                def _curve_ic50_bounds(mean_vec: Sequence[float], donor_mat: Sequence[Sequence[float]]) -> Optional[tuple[float, float, float, float, float]]:
                                    br_i = next((i for i in range(len(cg) - 1) if mean_vec[i] < 50.0 <= mean_vec[i + 1] and mean_vec[i + 1] > mean_vec[i]), None)
                                    if br_i is None:
                                        return None
                                    c_lo_b, c_hi_b = cg[br_i], cg[br_i + 1]
                                    d_ic50s: list[float] = []
                                    for di in range(n_don):
                                        d_br = next((j for j in range(len(cg) - 1) if donor_mat[j][di] < 50.0 <= donor_mat[j + 1][di] and donor_mat[j + 1][di] > donor_mat[j][di]), None)
                                        if d_br is None:
                                            return None
                                        y0, y1 = donor_mat[d_br][di], donor_mat[d_br + 1][di]
                                        d_ic50s.append(cg[d_br] + ((50.0 - y0) / (y1 - y0)) * (cg[d_br + 1] - cg[d_br]))
                                    tb_ic = sample_t_one_sided_bounds(d_ic50s, alpha=0.025)
                                    if tb_ic is None:
                                        return None
                                    return (c_lo_b, c_hi_b, tb_ic[0], max(1e-9, tb_ic[1]), tb_ic[2])
                                sma_ic_b = _curve_ic50_bounds(sg, sma_by_conc_donors)
                                col_ic_b = _curve_ic50_bounds(kg, col_by_conc_donors)
                                if sma_ic_b is None or col_ic_b is None:
                                    holds.append("HOLD_GATE_A0A_ENDPOINT_IC50_CROSSING_UNESTIMABLE"); a0a_ok = False
                                else:
                                    s_lo, s_hi, s_mean, s_l95, s_u95 = sma_ic_b
                                    k_lo, k_hi, k_mean, k_l95, k_u95 = col_ic_b
                                    if not (s_lo - 1e-6 <= float(ic_s) <= s_hi + 1e-6 and k_lo - 1e-6 <= float(ic_c) <= k_hi + 1e-6):
                                        fails.append("FAIL_GATE_A0A_ENDPOINT_IC50_OUTSIDE_CURVE_CROSSING_BRACKET"); a0a_ok = False
                                    elif abs(float(ic_s) - s_mean) > max(5.0, 0.20 * s_mean) or abs(float(ic_c) - k_mean) > max(5.0, 0.20 * k_mean):
                                        fails.append("FAIL_GATE_A0A_ENDPOINT_IC50_OUTSIDE_CURVE_CROSSING_BRACKET"); a0a_ok = False
                                    if max(s_u95, k_u95) > ic50_u95_val + 1e-6:
                                        fails.append("FAIL_GATE_A0A_U95_BELOW_RECONSTRUCTED_DONOR_IC50_U95"); a0a_ok = False
                                    if a0a_fu_ratios is not None:
                                        recomp_ic50_u95_op = max(s_u95, k_u95) * a0a_fu_ratios[0]
                                        if a0a_already_fu_adj:
                                            if ic50_u95_val < recomp_ic50_u95_op - 1e-6 or (recomp_c_up_7d_op is not None and c_up_7d_val > recomp_c_up_7d_op + 1e-6):
                                                if "FAIL_GATE_A0A_CLAIMED_FU_ADJUSTED_LIMITS_UNDERSTATED" not in fails:
                                                    fails.append("FAIL_GATE_A0A_CLAIMED_FU_ADJUSTED_LIMITS_UNDERSTATED"); a0a_ok = False
                                            ic50_u95_op = max(ic50_u95_val, recomp_ic50_u95_op)
                                            ic50_u95_wash_op = ic50_u95_op * (a0a_fu_ratios[2] / a0a_fu_ratios[0])
                                        else:
                                            ic50_u95_op = max(ic50_u95_op if ic50_u95_op is not None else 0.0, recomp_ic50_u95_op)
                                        if ic50_u95_op is not None and c_up_7d_op is not None and ic50_u95_op > 0.0 and (c_up_7d_op / ic50_u95_op) < 1.5:
                                            if "FAIL_GATE_A0A_FU_PROPAGATED_MARGIN_BELOW_1P5X" not in fails:
                                                fails.append("FAIL_GATE_A0A_FU_PROPAGATED_MARGIN_BELOW_1P5X"); a0a_ok = False
                                    if max(s_u95, k_u95) / min(s_l95, k_l95) > 3.0 + 1e-9:
                                        fails.append("FAIL_GATE_A0A_UNCERTAINTY_ENDPOINT_SPLIT_GT_3X"); a0a_ok = False

    a0a_op_payload = {
        "ic50_u95_raw_uM": ic50_u95_val,
        "ic50_u95_fu_adjusted_uM": ic50_u95_op,
        "ic50_u95_washout_fu_adjusted_uM": ic50_u95_wash_op,
        "c_up_7d_raw_uM": c_up_7d_val,
        "c_up_7d_fu_adjusted_uM": c_up_7d_op,
        "eff_fu_upper_factor": a0a_fu_ratios[0] if a0a_fu_ratios is not None else None,
        "vasc_fu_lower_factor": a0a_fu_ratios[1] if a0a_fu_ratios is not None else None,
        "eff_fu_lower_factor": a0a_fu_ratios[2] if a0a_fu_ratios is not None else None,
        "a0a_limits_already_fu_adjusted": a0a_already_fu_adj,
    }
    if phase == "ROUTE_FREE_A0A":
        verdict = "FAIL" if fails else ("HOLD" if holds else "PASS_ROUTE_FREE_A0A_ONLY")
        return {
            "gate": "GATE-40", "phase": phase, "scope_track": scope_track, "verdict": verdict,
            "release_authorizing": False, "live_ledger_authenticated": False,
            "upstream_archive_verification": OFFLINE_ARCHIVE_NOTE,
            "a0a_operative_limits_uM": a0a_op_payload,
            "product_id": None, "required_switch": None, "failures": fails, "holds": holds,
        }

    prod_s = str(rec.get("product_id", "")).strip()
    bank_s = str(rec.get("bank_id", "")).strip()
    lot_s = str(rec.get("lot_id", "")).strip()
    route_s = str(rec.get("route_id", "")).strip().upper()

    def _interp_cum_at_hour(tf: Sequence[float], cf: Sequence[float], target_h: float) -> Optional[float]:
        if target_h < tf[0] or target_h > tf[-1]:
            return None
        for i in range(len(tf)):
            if abs(tf[i] - target_h) <= 1e-9:
                return cf[i]
            if i + 1 < len(tf) and tf[i] < target_h < tf[i + 1]:
                frac = (target_h - tf[i]) / (tf[i + 1] - tf[i])
                return cf[i] + frac * (cf[i + 1] - cf[i])
        return None

    def _validate_pfd_release_trace_and_peak(
        ev: Mapping[str, Any], *, min_horizon_h: float, tag: str,
    ) -> Optional[tuple[float, list[float], list[float], float]]:
        """Validate unified loading + time-resolved intact-parent trace & recompute supremum burst 1-compartment C_max."""
        load_mg = ev.get("initial_pirfenidone_loading_mg")
        th = ev.get("elution_time_hours")
        cm = ev.get("cumulative_intact_parent_released_mg")
        thalf = ev.get("assumed_human_t_half_h")
        vdl = ev.get("assumed_human_vd_l")
        if not (
            is_finite_num(load_mg) and float(load_mg) > 0.0
            and isinstance(th, list) and isinstance(cm, list) and len(th) == len(cm) and len(th) >= 7
            and all(is_finite_num(x) for x in th + cm)
            and is_finite_num(thalf) and is_finite_num(vdl)
        ):
            fails.append(f"FAIL_{tag}_MISSING_TIME_RESOLVED_RELEASE_TRACE_OR_PK_PARAMS"); return None
        tf = [float(x) for x in th]
        cf = [float(x) for x in cm]
        lf = float(load_mg)
        if tf[0] != 0.0 or cf[0] != 0.0 or any(tf[i] >= tf[i + 1] for i in range(len(tf) - 1)) or any(cf[i + 1] < cf[i] for i in range(len(cf) - 1)):
            fails.append(f"FAIL_{tag}_INVALID_RELEASE_TRACE_MONOTONICITY"); return None
        if cf[-1] <= 0.0 or cf[-1] > 1.10 * lf:
            fails.append(f"FAIL_{tag}_ZERO_OR_CONTRADICTORY_RELEASE_TRACE"); return None
        # Dense burst sampling required (<= 1 h, <= 3 h, <= 6 h, <= 24 h) through min_horizon_h
        if not (any(0.0 < t <= 1.0 for t in tf) and any(1.0 < t <= 3.0 for t in tf) and any(3.0 < t <= 6.0 for t in tf) and any(12.0 <= t <= 24.0 for t in tf) and tf[-1] >= min_horizon_h):
            fails.append(f"FAIL_{tag}_RELEASE_TRACE_INSUFFICIENT_BURST_OR_HORIZON_COVERAGE"); return None
        # Require explicit endpoint timestamps at 24.0 h and min_horizon_h (336.0 h or 840.0 h) for exact mass balance!
        if not any(abs(t - 24.0) <= 1e-9 for t in tf) or not any(abs(t - min_horizon_h) <= 1e-9 for t in tf):
            fails.append(f"FAIL_{tag}_RELEASE_TRACE_MISSING_EXPLICIT_24H_OR_HORIZON_ENDPOINT"); return None
        # Conservative human pirfenidone PK bounds (FDA/PMDA label: t_half 2.4-4.0 h, Vd 35-65 L)
        if not (2.4 <= float(thalf) <= 4.0 and 35.0 <= float(vdl) <= 65.0):
            fails.append(f"FAIL_{tag}_INVALID_HUMAN_PK_ENVELOPE_THALF_OR_VD"); return None
        # Evaluate BOTH stated (t_half, Vd) AND worst-case conservative joint PK corner (t_half=4.0 h, Vd=35.0 L)!
        cmax_stated = _recompute_pirfenidone_peak_systemic_cmax_ug_ml(tf, cf, t_half_h=float(thalf), vd_l=float(vdl))
        cmax_worst = _recompute_pirfenidone_peak_systemic_cmax_ug_ml(tf, cf, t_half_h=4.0, vd_l=35.0)
        cmax = max(cmax_stated, cmax_worst)
        if cmax >= 0.20:
            fails.append(f"FAIL_{tag}_RECOMPUTED_PEAK_SYSTEMIC_CMAX_CAP_BREACH")
        # Dossier §5 lines 116 & 118: require >= 3 distinct manufacturing lots with lot-specific validated release traces!
        mlots = ev.get("manufacturing_lot_release_records")
        mlot_keys = frozenset({
            "coating_lot_id", "initial_pirfenidone_loading_mg",
            "elution_time_hours", "cumulative_intact_parent_released_mg", "lot_trace_sha256",
        })
        if mlots is None:
            holds.append(f"HOLD_{tag}_MISSING_3_MANUFACTURING_LOT_RELEASE_RECORDS"); return None
        if not isinstance(mlots, list) or len(mlots) < 3:
            fails.append(f"FAIL_{tag}_REQUIRES_AT_LEAST_3_DISTINCT_MANUFACTURING_LOTS"); return None
        seen_mlots: set[str] = set()
        active_lot_present = False
        for m_i, mlr in enumerate(mlots):
            if (
                not isinstance(mlr, Mapping) or set(mlr.keys()) != mlot_keys
                or not is_nonempty_str(mlr.get("coating_lot_id"))
                or not is_valid_sha256_hex(mlr.get("lot_trace_sha256"))
                or sha256_bytes(canonical_json_bytes({k: v for k, v in mlr.items() if k != "lot_trace_sha256"})) != str(mlr["lot_trace_sha256"])
            ):
                fails.append(f"FAIL_{tag}_MALFORMED_MANUFACTURING_LOT_RELEASE_RECORD:{m_i}"); return None
            mlid = str(mlr["coating_lot_id"]).strip()
            if mlid.upper() in seen_mlots:
                fails.append(f"FAIL_{tag}_DUPLICATE_MANUFACTURING_LOT_ID:{mlid}"); return None
            seen_mlots.add(mlid.upper())
            if coat_id is not None and mlid == coat_id.get("coating_lot_id"):
                active_lot_present = True
            ml_load = mlr.get("initial_pirfenidone_loading_mg")
            ml_t = mlr.get("elution_time_hours")
            ml_c = mlr.get("cumulative_intact_parent_released_mg")
            if not (
                is_finite_num(ml_load) and float(ml_load) > 0.0
                and isinstance(ml_t, list) and isinstance(ml_c, list) and len(ml_t) == len(ml_c) and len(ml_t) >= 7
                and all(is_finite_num(x) for x in ml_t + ml_c)
            ):
                fails.append(f"FAIL_{tag}_INVALID_LOT_RELEASE_TRACE:{mlid}"); return None
            ml_tf = [float(x) for x in ml_t]
            ml_cf = [float(x) for x in ml_c]
            if (
                ml_tf[0] != 0.0 or ml_cf[0] != 0.0
                or any(ml_tf[k] >= ml_tf[k + 1] for k in range(len(ml_tf) - 1))
                or any(ml_cf[k + 1] < ml_cf[k] for k in range(len(ml_cf) - 1))
                or ml_cf[-1] <= 0.0 or ml_cf[-1] > 1.10 * float(ml_load)
                or ml_tf[-1] < min_horizon_h
                or not any(abs(t - 24.0) <= 1e-9 for t in ml_tf)
                or not any(abs(t - min_horizon_h) <= 1e-9 for t in ml_tf)
            ):
                fails.append(f"FAIL_{tag}_INVALID_LOT_RELEASE_TRACE:{mlid}"); return None
            ml_c24 = _interp_cum_at_hour(ml_tf, ml_cf, 24.0)
            if ml_c24 is None or (100.0 * ml_c24 / float(ml_load)) > 15.0 + 1e-9:
                fails.append(f"FAIL_{tag}_LOT_DAY1_BURST_GT_15PCT:{mlid}"); return None
            ml_cmax = max(
                _recompute_pirfenidone_peak_systemic_cmax_ug_ml(ml_tf, ml_cf, t_half_h=float(thalf), vd_l=float(vdl)),
                _recompute_pirfenidone_peak_systemic_cmax_ug_ml(ml_tf, ml_cf, t_half_h=4.0, vd_l=35.0),
            )
            if ml_cmax >= 0.20:
                fails.append(f"FAIL_{tag}_LOT_PEAK_SYSTEMIC_CMAX_CAP_BREACH:{mlid}"); return None
        if coat_id is not None and not active_lot_present:
            fails.append(f"FAIL_{tag}_ACTIVE_COATING_LOT_MISSING_FROM_3LOT_PANEL"); return None
        return cmax, tf, cf, lf

    # Gate A-0b: coating identity + >= 14 d + unified loading/trace burst reconciliation & supremum C_max < 0.20 ug/mL!
    a0b_extras = COATING_IDENTITY_KEYS | frozenset({
        "study_start_utc", "initial_pirfenidone_loading_mg",
        "coating_thickness_um", "day1_burst_pct", "modeled_systemic_plasma_ug_ml",
        "elution_time_hours", "cumulative_intact_parent_released_mg",
        "assumed_human_t_half_h", "assumed_human_vd_l",
        "worst_face_o2_mmhg", "day14_viability_pct", "day14_sprouting_pct",
        "cc10_free_14d_l95_uM", "c_sprout_max_free_14d_l95_uM",
        "c_upper_provisional_14d_l95_uM", "sustained_free_parent_lower_uM",
        "peak_free_parent_u95_uM", "day14_sustained_free_parent_u95_uM",
        "added_coating_water_equiv_diff_path_um", "water_equiv_diff_path_um",
        "local_ph_min", "local_ph_max",
        "a0b_14d_safety_replicates_by_conc", "a0b_fit_artifact_receipt",
        "a0b_matrix_fu_by_assay",
        "a0b_local_exposure_timepoints", "a0b_local_pk_envelope",
        "a0b_local_ph_timepoints",
        "manufacturing_lot_release_records", "a0b_limits_already_fu_adjusted",
    })
    a0b_ev = _validate_content_receipt(
        a0b_raw,
        expected_stage="A-0b", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="bench_unedited",
        expected_parent=a0a_ev, allowed_extra_keys=a0b_extras, fails=fails, holds=holds,
        missing_hold="HOLD_GATE_A0B_RECEIPT_MISSING",
        fail_code="FAIL_GATE_A0B_FAILED",
        mismatch_code="FAIL_GATE_A0B_SCOPE_MISMATCH",
    )
    a0b_ok = a0b_ev is not None and a0b_ev.get("verdict") == "PASS"
    all4_ceiling_val: Optional[float] = None
    if a0b_ev is not None:
        coat_id = _extract_and_validate_coating_identity(a0b_ev, expected=None, fails=fails, stage="A-0b")
        if coat_id is None:
            a0b_ok = False
        t_a0b_st = parse_utc_iso_ts(a0b_ev.get("study_start_utc"))
        t_a0b_end = parse_utc_iso_ts(a0b_ev.get("recorded_at_utc"))
        t_a0a_end = parse_utc_iso_ts(a0a_ev.get("recorded_at_utc")) if a0a_ev is not None else None
        if t_a0b_st is None or t_a0b_end is None:
            fails.append("FAIL_GATE_A0B_MISSING_STUDY_START_UTC"); a0b_ok = False
        else:
            if t_a0a_end is not None and t_a0b_st < t_a0a_end:
                fails.append("FAIL_GATE_A0B_STARTED_BEFORE_A0A_COMPLETION"); a0b_ok = False
            if (t_a0b_end - t_a0b_st) < timedelta(days=14):
                fails.append("FAIL_GATE_A0B_ELAPSED_OBSERVATION_LT_14_DAYS"); a0b_ok = False
        th = a0b_ev.get("coating_thickness_um")
        burst = a0b_ev.get("day1_burst_pct")
        plasma = a0b_ev.get("modeled_systemic_plasma_ug_ml")
        o2_b = a0b_ev.get("worst_face_o2_mmhg")
        v14 = a0b_ev.get("day14_viability_pct")
        s14 = a0b_ev.get("day14_sprouting_pct")
        cc14 = a0b_ev.get("cc10_free_14d_l95_uM")
        sp14 = a0b_ev.get("c_sprout_max_free_14d_l95_uM")
        c14_up = a0b_ev.get("c_upper_provisional_14d_l95_uM")
        sust_lo = a0b_ev.get("sustained_free_parent_lower_uM")
        pk_u95 = a0b_ev.get("peak_free_parent_u95_uM")
        d14_u95 = a0b_ev.get("day14_sustained_free_parent_u95_uM")
        added_wp = a0b_ev.get("added_coating_water_equiv_diff_path_um")
        wpath = a0b_ev.get("water_equiv_diff_path_um")
        ph_lo = a0b_ev.get("local_ph_min")
        ph_hi = a0b_ev.get("local_ph_max")
        if not (is_finite_num(th) and 0.0 < float(th) <= 10.0):
            fails.append("FAIL_GATE_A0B_COATING_THICKNESS_INVALID"); a0b_ok = False
        if not (is_finite_num(burst) and 0.0 <= float(burst) <= 15.0):
            fails.append("FAIL_GATE_A0B_DAY1_BURST_INVALID_OR_GT_15PCT"); a0b_ok = False
        if not (is_finite_num(plasma) and 0.0 <= float(plasma) < 0.20):
            fails.append("FAIL_GATE_A0B_SYSTEMIC_PLASMA_CAP_BREACH"); a0b_ok = False
        tr_0b = _validate_pfd_release_trace_and_peak(a0b_ev, min_horizon_h=336.0, tag="GATE_A0B")
        if tr_0b is None:
            a0b_ok = False
        else:
            cmax_0b, tf_0b, cf_0b, lf_0b = tr_0b
            if cmax_0b >= 0.20:
                a0b_ok = False
            elif is_finite_num(plasma) and float(plasma) + 1e-6 < cmax_0b:
                fails.append("FAIL_GATE_A0B_MODELED_PLASMA_UNDERSTATES_BURST_CMAX"); a0b_ok = False
            cum24 = _interp_cum_at_hour(tf_0b, cf_0b, 24.0)
            if cum24 is None or cum24 <= 0.0:
                fails.append("FAIL_GATE_A0B_ZERO_OR_CONTRADICTORY_DAY1_TRACE"); a0b_ok = False
            else:
                recomp_burst_pct = 100.0 * cum24 / lf_0b
                if recomp_burst_pct > 15.0 or (is_finite_num(burst) and abs(float(burst) - recomp_burst_pct) > 0.5):
                    fails.append("FAIL_GATE_A0B_DAY1_BURST_MISMATCH_WITH_RELEASE_TRACE"); a0b_ok = False
        if not all(is_finite_num(x) for x in (o2_b, v14, s14, cc14, sp14, c14_up, sust_lo, pk_u95, d14_u95, added_wp, wpath, ph_lo, ph_hi)):
            holds.append("HOLD_GATE_A0B_MISSING_EXPOSURE_VASCULAR_PATH_OR_PH_METRICS"); a0b_ok = False
        else:
            if float(o2_b) < 40.0:
                fails.append("FAIL_GATE_A0B_WORST_FACE_O2_BELOW_40MMHG"); a0b_ok = False
            if float(v14) < 90.0 or float(v14) > 100.0:
                fails.append("FAIL_GATE_A0B_DAY14_VIABILITY_BELOW_90PCT"); a0b_ok = False
            if float(s14) < 90.0:
                fails.append("FAIL_GATE_A0B_DAY14_SPROUTING_BELOW_90PCT"); a0b_ok = False
            if float(added_wp) <= 0.0 or float(added_wp) > 5.0:
                fails.append("FAIL_GATE_A0B_ADDED_COATING_DIFF_PATH_GT_5UM"); a0b_ok = False
            if float(wpath) <= 0.0 or float(wpath) > 50.0 or float(added_wp) > float(wpath) + 1e-12:
                fails.append("FAIL_GATE_A0B_WATER_EQUIV_DIFF_PATH_GT_50UM"); a0b_ok = False
            if float(ph_lo) < 7.25 or float(ph_hi) > 7.45 or float(ph_lo) > float(ph_hi):
                fails.append("FAIL_GATE_A0B_LOCAL_PH_OUTSIDE_7P25_7P45"); a0b_ok = False
            a0b_ph_tps = a0b_ev.get("a0b_local_ph_timepoints")
            if a0b_ph_tps is None:
                holds.append("HOLD_GATE_A0B_MISSING_14D_TIME_RESOLVED_PH"); a0b_ok = False
            elif not isinstance(a0b_ph_tps, list) or len(a0b_ph_tps) < 3:
                fails.append("FAIL_GATE_A0B_TIME_RESOLVED_PH_INVALID_OR_OUT_OF_RANGE"); a0b_ok = False
            else:
                _ph_rk = frozenset({"hour_h", "coating_lot_id", "ph_min", "ph_max"})
                _ph_prev = -1.0
                _ph_obs_min = float("inf")
                _ph_obs_max = float("-inf")
                _ph0b_ok = True
                _exp_clot0b = str(coat_id.get("coating_lot_id", "")).strip() if coat_id is not None else ""
                for _pr in a0b_ph_tps:
                    if not (
                        isinstance(_pr, Mapping) and set(_pr.keys()) == _ph_rk
                        and is_finite_num(_pr.get("hour_h")) and float(_pr["hour_h"]) > _ph_prev and float(_pr["hour_h"]) > 0.0
                        and is_nonempty_str(_pr.get("coating_lot_id"))
                        and (not _exp_clot0b or str(_pr["coating_lot_id"]).strip() == _exp_clot0b)
                        and is_finite_num(_pr.get("ph_min")) and is_finite_num(_pr.get("ph_max"))
                        and 7.25 <= float(_pr["ph_min"]) <= float(_pr["ph_max"]) <= 7.45
                    ):
                        _ph0b_ok = False; break
                    if _ph_prev >= 0.0 and (float(_pr["hour_h"]) - _ph_prev) > 168.0 + 1e-9:
                        _ph0b_ok = False; break
                    _ph_prev = float(_pr["hour_h"])
                    _ph_obs_min = min(_ph_obs_min, float(_pr["ph_min"]))
                    _ph_obs_max = max(_ph_obs_max, float(_pr["ph_max"]))
                if (
                    not _ph0b_ok
                    or float(a0b_ph_tps[0]["hour_h"]) > 24.0 + 1e-9
                    or float(a0b_ph_tps[-1]["hour_h"]) < 336.0 - 1e-9
                    or float(ph_lo) > _ph_obs_min + 1e-6
                    or float(ph_hi) < _ph_obs_max - 1e-6
                ):
                    fails.append("FAIL_GATE_A0B_TIME_RESOLVED_PH_INVALID_OR_OUT_OF_RANGE"); a0b_ok = False
            if float(pk_u95) < float(d14_u95) - 1e-12 or float(d14_u95) < float(sust_lo) - 1e-12:
                fails.append("FAIL_GATE_A0B_INVALID_EXPOSURE_ORDERING"); a0b_ok = False
            eff_floor_0b = ic50_u95_op if ic50_u95_op is not None else ic50_u95_val
            c7d_ceil_0b = c_up_7d_op if c_up_7d_op is not None else c_up_7d_val
            a0b_already_fu_adj = False
            if "a0b_limits_already_fu_adjusted" in a0b_ev:
                if not is_strict_bool(a0b_ev["a0b_limits_already_fu_adjusted"]):
                    fails.append("FAIL_GATE_A0B_INVALID_FU_ADJUSTED_FLAG"); a0b_ok = False
                else:
                    a0b_already_fu_adj = bool(a0b_ev["a0b_limits_already_fu_adjusted"])
            if eff_floor_0b is not None and float(sust_lo) < eff_floor_0b:
                fails.append("FAIL_GATE_A0B_SUSTAINED_FREE_BELOW_IC50_U95"); a0b_ok = False
            exp_14d_min = min(float(cc14), float(sp14))
            if exp_14d_min <= 0.0 or abs(float(c14_up) - exp_14d_min) > 1e-9:
                fails.append("FAIL_GATE_A0B_14D_CEILING_NOT_MIN_OF_VIABILITY_AND_SPROUTING"); a0b_ok = False
            # Assay-specific 14-day equilibrium-dialysis f_u & nominal-to-free exposure reconciliation on A-0b!
            a0b_mfu = a0b_ev.get("a0b_matrix_fu_by_assay")
            a0b_fu_vasc_l95_ratio: Optional[float] = None
            a0b_fu_eff_l95_ratio: Optional[float] = None
            a0b_mfu_checked: Optional[dict[str, tuple[list[float], float]]] = None
            if a0b_mfu is None:
                holds.append("HOLD_GATE_A0B_MISSING_14D_ASSAY_MATRIX_FU_RECONCILIATION"); a0b_ok = False
            elif not isinstance(a0b_mfu, Mapping) or set(a0b_mfu.keys()) != {"fibrosis_efficacy_assay", "vascular_viability_assay"}:
                fails.append("FAIL_GATE_A0B_INVALID_14D_ASSAY_MATRIX_FU"); a0b_ok = False
            else:
                _mfu_keys_0b = frozenset({
                    "matrix_id", "nominal_conc_uM_grid", "dialysis_fu_replicates",
                    "measured_fu_mean", "analytical_sample_record_sha256",
                })
                _mfu_parsed: dict[str, tuple[list[float], float]] = {}
                _mfu_ok = True
                for _ak0b in ("fibrosis_efficacy_assay", "vascular_viability_assay"):
                    _am0b = a0b_mfu[_ak0b]
                    if not (
                        isinstance(_am0b, Mapping) and set(_am0b.keys()) == _mfu_keys_0b
                        and is_nonempty_str(_am0b.get("matrix_id"))
                        and is_valid_sha256_hex(_am0b.get("analytical_sample_record_sha256"))
                        and isinstance(_am0b.get("nominal_conc_uM_grid"), list) and len(_am0b["nominal_conc_uM_grid"]) >= 7
                        and all(is_finite_num(x) and float(x) >= 0.0 for x in _am0b["nominal_conc_uM_grid"])
                        and isinstance(_am0b.get("dialysis_fu_replicates"), list) and len(_am0b["dialysis_fu_replicates"]) >= 3
                        and all(is_finite_num(x) and 0.0 < float(x) <= 1.0 for x in _am0b["dialysis_fu_replicates"])
                        and is_finite_num(_am0b.get("measured_fu_mean")) and 0.0 < float(_am0b["measured_fu_mean"]) <= 1.0
                    ):
                        fails.append(f"FAIL_GATE_A0B_INVALID_14D_ASSAY_MATRIX_FU:{_ak0b}"); a0b_ok = False; _mfu_ok = False; break
                    _fu_r0b = [float(x) for x in _am0b["dialysis_fu_replicates"]]
                    _fu_m0b = sum(_fu_r0b) / len(_fu_r0b)
                    if abs(_fu_m0b - float(_am0b["measured_fu_mean"])) > min(0.005, 0.01 * _fu_m0b):
                        fails.append(f"FAIL_GATE_A0B_14D_DIALYSIS_FU_MEAN_MISMATCH:{_ak0b}"); a0b_ok = False; _mfu_ok = False; break
                    _fu_tb0b = sample_t_one_sided_bounds(_fu_r0b, alpha=0.025)
                    if _fu_tb0b is None:
                        holds.append(f"HOLD_GATE_A0B_14D_DIALYSIS_FU_ZERO_DISPERSION:{_ak0b}"); a0b_ok = False; _mfu_ok = False; break
                    if _ak0b == "vascular_viability_assay":
                        a0b_fu_vasc_l95_ratio = max(1e-6, _fu_tb0b[1]) / _fu_m0b
                    elif _ak0b == "fibrosis_efficacy_assay":
                        a0b_fu_eff_l95_ratio = max(1e-6, _fu_tb0b[1]) / _fu_m0b
                    _mfu_parsed[_ak0b] = ([float(x) for x in _am0b["nominal_conc_uM_grid"]], _fu_m0b)
                if _mfu_ok:
                    a0b_mfu_checked = _mfu_parsed
            _r_14d_vasc_cands = [x for x in (a0a_fu_ratios[1] if a0a_fu_ratios is not None else None, a0b_fu_vasc_l95_ratio) if x is not None]
            _r_14d_eff_cands = [x for x in (a0a_fu_ratios[2] if a0a_fu_ratios is not None else None, a0b_fu_eff_l95_ratio) if x is not None]
            _r_fu_14d_vasc = min(_r_14d_vasc_cands) if _r_14d_vasc_cands else None
            _r_fu_14d_eff = min(_r_14d_eff_cands) if _r_14d_eff_cands else None
            exp_14d_op = exp_14d_min if (a0b_already_fu_adj or _r_fu_14d_vasc is None) else (exp_14d_min * _r_fu_14d_vasc)
            all4_min = min(c7d_ceil_0b, exp_14d_op) if c7d_ceil_0b is not None else exp_14d_op
            all4_ceiling_val = all4_min
            if c7d_ceil_0b is not None and exp_14d_op > c7d_ceil_0b + 1e-12:
                fails.append("FAIL_GATE_A0B_14D_CEILING_EXCEEDS_7D_CEILING"); a0b_ok = False
            if float(pk_u95) >= all4_min:
                fails.append("FAIL_GATE_A0B_PEAK_FREE_NOT_BELOW_ALL4_CEILINGS"); a0b_ok = False
            if float(d14_u95) >= all4_min:
                fails.append("FAIL_GATE_A0B_14D_SUSTAINED_NOT_BELOW_ALL4_CEILINGS"); a0b_ok = False
            # Raw donor-level 14-day safety & Day-0 + Day-4 delayed vascular sprouting replicates + fit receipt!
            a0b_reps = a0b_ev.get("a0b_14d_safety_replicates_by_conc")
            a0b_fit = a0b_ev.get("a0b_fit_artifact_receipt")
            if a0b_reps is None or a0b_fit is None:
                holds.append("HOLD_GATE_A0B_MISSING_RAW_14D_SAFETY_OR_VASCULAR_REPLICATES"); a0b_ok = False
            elif not (isinstance(a0b_reps, list) and len(a0b_reps) >= 7 and isinstance(a0b_fit, Mapping)):
                fails.append("FAIL_GATE_A0B_MALFORMED_14D_SAFETY_REPLICATES_OR_FIT"); a0b_ok = False
            else:
                f0b_keys = frozenset({
                    "donor_ids", "raw_replicates_sha256", "cc10_free_14d_l95_uM",
                    "c_sprout_max_free_14d_l95_uM", "day14_viability_pct", "day14_sprouting_pct", "receipt_sha256",
                })
                a0b_raw_ep_map = (
                    ("viability_14d", "viability_14d_pct", "viability_raw"),
                    ("efficacy_culture_viability_14d", "efficacy_culture_viability_14d_pct", "efficacy_viability_raw"),
                    ("day0_sprout_length_14d", "day0_sprout_length_14d_pct", "day0_sprout_length_um"),
                    ("day0_branching_14d", "day0_branching_14d_pct", "day0_branching_junctions"),
                    ("day0_network_persistence_14d", "day0_network_persistence_14d_pct", "day0_network_persistence_idx"),
                    ("day4_sprout_length_14d", "day4_sprout_length_14d_pct", "day4_sprout_length_um"),
                    ("day4_branching_14d", "day4_branching_14d_pct", "day4_branching_junctions"),
                    ("day4_network_persistence_14d", "day4_network_persistence_14d_pct", "day4_network_persistence_idx"),
                )
                a0b_raw_ep_keys = frozenset(k for k, _, _ in a0b_raw_ep_map)
                r0b_keys = frozenset({
                    "conc_uM", "donor_ids", "matched_vehicle_record_id", "efficacy_matched_vehicle_record_id",
                    "matched_vehicle_raw_baselines", "raw_donor_measurements",
                    "viability_14d_pct", "efficacy_culture_viability_14d_pct",
                    "day0_sprout_length_14d_pct", "day0_branching_14d_pct", "day0_network_persistence_14d_pct",
                    "day4_sprout_length_14d_pct", "day4_branching_14d_pct", "day4_network_persistence_14d_pct",
                    "day0_sprouting_14d_pct", "day4_delayed_sprouting_14d_pct",
                })
                veh_raw_keys = frozenset({
                    "viability_raw", "efficacy_viability_raw",
                    "day0_sprout_length_um", "day0_branching_junctions", "day0_network_persistence_idx",
                    "day4_sprout_length_um", "day4_branching_junctions", "day4_network_persistence_idx",
                })
                raw0b_sha = sha256_bytes(canonical_json_bytes(a0b_reps))
                f0b_ok = (
                    set(a0b_fit.keys()) == f0b_keys
                    and is_valid_sha256_hex(a0b_fit.get("receipt_sha256"))
                    and compute_receipt_sha256(a0b_fit) == a0b_fit["receipt_sha256"]
                    and a0b_fit.get("raw_replicates_sha256") == raw0b_sha
                    and isinstance(a0b_fit.get("donor_ids"), list) and len(a0b_fit["donor_ids"]) >= 3
                    and len({str(d).strip().upper() for d in a0b_fit["donor_ids"] if is_nonempty_str(d)}) == len(a0b_fit["donor_ids"])
                    and is_finite_num(a0b_fit.get("cc10_free_14d_l95_uM")) and abs(float(a0b_fit["cc10_free_14d_l95_uM"]) - float(cc14)) <= 1e-6
                    and is_finite_num(a0b_fit.get("c_sprout_max_free_14d_l95_uM")) and abs(float(a0b_fit["c_sprout_max_free_14d_l95_uM"]) - float(sp14)) <= 1e-6
                    and is_finite_num(a0b_fit.get("day14_viability_pct")) and abs(float(a0b_fit["day14_viability_pct"]) - float(v14)) <= 1e-6
                    and is_finite_num(a0b_fit.get("day14_sprouting_pct")) and abs(float(a0b_fit["day14_sprouting_pct"]) - float(s14)) <= 1e-6
                )
                if not f0b_ok:
                    fails.append("FAIL_GATE_A0B_FIT_ARTIFACT_RECEIPT_INVALID_OR_MISMATCHED"); a0b_ok = False
                else:
                    exp_d0b = [str(d).strip().upper() for d in a0b_fit["donor_ids"]]
                    prev_c0b = -1.0
                    max_safe_viab_c = -1.0
                    max_safe_vasc_viab_c = -1.0
                    max_safe_eff_viab_c = -1.0
                    max_safe_spr_c = -1.0
                    viab_prefix_open = True
                    vasc_viab_prefix_open = True
                    eff_viab_prefix_open = True
                    spr_prefix_open = True
                    tox_viab_above = False
                    tox_spr_above = False
                    target_v14_means: list[float] = []
                    target_s14_means: list[float] = []
                    target_l95_failed = False
                    zero_disp_0b = False
                    missing_raw_or_eff_0b = False
                    raw_mismatch_0b = False
                    veh_base_mismatch_0b = False
                    nom_free_mismatch_0b = False
                    rows0b_ok = True
                    vasc_d0_keys = ("day0_sprout_length_14d_pct", "day0_branching_14d_pct", "day0_network_persistence_14d_pct")
                    vasc_d4_keys = ("day4_sprout_length_14d_pct", "day4_branching_14d_pct", "day4_network_persistence_14d_pct")
                    for r_idx, rr in enumerate(a0b_reps):
                        if isinstance(rr, Mapping) and (
                            rr.get("raw_donor_measurements") is None
                            or rr.get("efficacy_culture_viability_14d_pct") is None
                            or rr.get("efficacy_matched_vehicle_record_id") is None
                        ):
                            missing_raw_or_eff_0b = True; break
                        if not isinstance(rr, Mapping) or set(rr.keys()) != r0b_keys:
                            rows0b_ok = False; break
                        cc_v = rr.get("conc_uM")
                        rd_ids = rr.get("donor_ids")
                        mv_id = rr.get("matched_vehicle_record_id")
                        ev_id = rr.get("efficacy_matched_vehicle_record_id")
                        mv_raw = rr.get("matched_vehicle_raw_baselines")
                        raw_dm = rr.get("raw_donor_measurements")
                        vv = rr.get("viability_14d_pct")
                        evv = rr.get("efficacy_culture_viability_14d_pct")
                        s0 = rr.get("day0_sprouting_14d_pct")
                        s4 = rr.get("day4_delayed_sprouting_14d_pct")
                        d0_comps = [rr.get(k) for k in vasc_d0_keys]
                        d4_comps = [rr.get(k) for k in vasc_d4_keys]
                        all_arrs = [vv, evv, s0, s4] + d0_comps + d4_comps
                        if not (
                            is_finite_num(cc_v) and float(cc_v) > prev_c0b
                            and (r_idx > 0 or abs(float(cc_v)) <= 1e-12)
                            and is_nonempty_str(mv_id) and is_nonempty_str(ev_id)
                            and str(mv_id).strip().upper() != str(ev_id).strip().upper()
                            and isinstance(mv_raw, Mapping) and set(mv_raw.keys()) == veh_raw_keys
                            and all(is_finite_num(mv_raw[k]) and float(mv_raw[k]) > 0.0 for k in veh_raw_keys)
                            and isinstance(raw_dm, Mapping) and set(raw_dm.keys()) == a0b_raw_ep_keys
                            and isinstance(rd_ids, list) and [str(d).strip().upper() for d in rd_ids] == exp_d0b
                            and all(isinstance(arr, list) and len(arr) == len(exp_d0b) and all(is_finite_num(x) and 0.0 <= float(x) <= 130.0 for x in arr) for arr in all_arrs)
                        ):
                            rows0b_ok = False; break
                        # Reconcile 14-day tested free concentration against assay-specific nominal * recomputed_fu_mean!
                        if a0b_mfu_checked is not None:
                            for _ak0b, (_nom_g0b, _fm0b) in a0b_mfu_checked.items():
                                if len(_nom_g0b) != len(a0b_reps):
                                    nom_free_mismatch_0b = True; break
                                if abs(_nom_g0b[r_idx] * _fm0b - float(cc_v)) > max(0.05, 0.01 * float(cc_v)):
                                    nom_free_mismatch_0b = True; break
                            if nom_free_mismatch_0b:
                                break
                        # Derive every normalized percentage directly from donor-keyed raw treated / raw vehicle
                        # AND bind matched_vehicle_raw_baselines directly to donor vehicle denominator means!
                        derived_0b: dict[str, list[float]] = {}
                        for raw_k, pct_k, veh_base_k in a0b_raw_ep_map:
                            ep_raw = raw_dm[raw_k]
                            if not (
                                isinstance(ep_raw, Mapping) and set(ep_raw.keys()) == {"treated", "vehicle"}
                                and isinstance(ep_raw["treated"], list) and len(ep_raw["treated"]) == len(exp_d0b)
                                and isinstance(ep_raw["vehicle"], list) and len(ep_raw["vehicle"]) == len(exp_d0b)
                                and all(is_finite_num(x) and float(x) >= 0.0 for x in ep_raw["treated"])
                                and all(is_finite_num(x) and float(x) > 0.0 for x in ep_raw["vehicle"])
                            ):
                                rows0b_ok = False; break
                            mean_v_don = sum(float(x) for x in ep_raw["vehicle"]) / len(exp_d0b)
                            base_v_decl = float(mv_raw[veh_base_k])
                            if abs(mean_v_don - base_v_decl) > 0.02 * base_v_decl:
                                veh_base_mismatch_0b = True; break
                            recomp_arr = [100.0 * float(ep_raw["treated"][di]) / float(ep_raw["vehicle"][di]) for di in range(len(exp_d0b))]
                            sub_arr = [float(x) for x in rr[pct_k]]
                            if any(abs(recomp_arr[di] - sub_arr[di]) > 0.5 for di in range(len(exp_d0b))):
                                raw_mismatch_0b = True; break
                            derived_0b[pct_k] = recomp_arr
                        if not rows0b_ok or raw_mismatch_0b or veh_base_mismatch_0b:
                            break
                        prev_c0b = float(cc_v)
                        vv_f = derived_0b["viability_14d_pct"]
                        evv_f = derived_0b["efficacy_culture_viability_14d_pct"]
                        d0_f = [derived_0b[k] for k in vasc_d0_keys]
                        d4_f = [derived_0b[k] for k in vasc_d4_keys]
                        s0_f = [float(x) for x in s0]
                        s4_f = [float(x) for x in s4]
                        # Composite summaries cannot overstate the worst derived individual vascular component per donor!
                        if any(s0_f[di] > min(c[di] for c in d0_f) + 0.5 for di in range(len(exp_d0b))):
                            rows0b_ok = False; break
                        if any(s4_f[di] > min(c[di] for c in d4_f) + 0.5 for di in range(len(exp_d0b))):
                            rows0b_ok = False; break
                        if r_idx == 0:
                            # 0 uM paired self-normalized vehicle control: verify >= 95% without spurious zero-dispersion HOLD!
                            vasc_v_l95 = min(vv_f)
                            eff_v_l95 = min(evv_f)
                            v_l95 = min(vasc_v_l95, eff_v_l95)
                            min_vasc_l95 = min(min(arr) for arr in ([s0_f, s4_f] + d0_f + d4_f))
                        else:
                            vb = sample_t_one_sided_bounds(vv_f)
                            evb = sample_t_one_sided_bounds(evv_f)
                            s0b = sample_t_one_sided_bounds(s0_f)
                            s4b = sample_t_one_sided_bounds(s4_f)
                            d0_bs = [sample_t_one_sided_bounds(c) for c in d0_f]
                            d4_bs = [sample_t_one_sided_bounds(c) for c in d4_f]
                            if vb is None or evb is None or s0b is None or s4b is None or any(b is None for b in d0_bs + d4_bs):
                                zero_disp_0b = True
                                vasc_v_l95 = float("-inf")
                                eff_v_l95 = float("-inf")
                                v_l95 = float("-inf")
                                min_vasc_l95 = float("-inf")
                            else:
                                vasc_v_l95 = vb[1]
                                eff_v_l95 = evb[1]
                                v_l95 = min(vasc_v_l95, eff_v_l95)
                                min_vasc_l95 = min([s0b[1], s4b[1]] + [b[1] for b in d0_bs + d4_bs])
                        v_m = min(sum(vv_f) / len(vv_f), sum(evv_f) / len(evv_f))
                        vasc_means = [sum(arr) / len(arr) for arr in ([s0_f, s4_f] + d0_f + d4_f)]
                        min_vasc_m = min(vasc_means)
                        if r_idx == 0 and (v_l95 < 95.0 or min_vasc_l95 < 95.0):
                            rows0b_ok = False; break
                        # Strict contiguous passing prefix from 0 uM across vascular & efficacy-culture viability AND all 6 vascular components!
                        if vasc_viab_prefix_open and vasc_v_l95 >= 90.0:
                            max_safe_vasc_viab_c = prev_c0b
                        else:
                            vasc_viab_prefix_open = False
                        if eff_viab_prefix_open and eff_v_l95 >= 90.0:
                            max_safe_eff_viab_c = prev_c0b
                        else:
                            eff_viab_prefix_open = False
                        if viab_prefix_open and v_l95 >= 90.0:
                            max_safe_viab_c = prev_c0b
                        else:
                            viab_prefix_open = False
                        if spr_prefix_open and min_vasc_l95 >= 90.0:
                            max_safe_spr_c = prev_c0b
                        else:
                            spr_prefix_open = False
                        if prev_c0b > float(cc14) + 1e-9 and v_m < 90.0:
                            tox_viab_above = True
                        if prev_c0b > float(sp14) + 1e-9 and min_vasc_m < 90.0:
                            tox_spr_above = True
                        if float(sust_lo) - 1e-9 <= prev_c0b <= float(pk_u95) + 1e-9:
                            target_v14_means.append(v_m)
                            target_s14_means.append(min_vasc_m)
                            if v_l95 < 90.0 or min_vasc_l95 < 90.0:
                                target_l95_failed = True
                    if missing_raw_or_eff_0b:
                        holds.append("HOLD_GATE_A0B_MISSING_RAW_DONOR_OR_EFFICACY_VIABILITY"); a0b_ok = False
                    elif nom_free_mismatch_0b:
                        fails.append("FAIL_GATE_A0B_14D_NOMINAL_TO_FREE_RECONCILIATION_FAILED"); a0b_ok = False
                    elif veh_base_mismatch_0b:
                        fails.append("FAIL_GATE_A0B_VEHICLE_BASELINE_MISMATCH_VS_DONOR_DENOMINATORS"); a0b_ok = False
                    elif raw_mismatch_0b:
                        fails.append("FAIL_GATE_A0B_NORMALIZED_PCT_MISMATCH_VS_RAW_DONOR_VALUES"); a0b_ok = False
                    elif not rows0b_ok:
                        fails.append("FAIL_GATE_A0B_INVALID_14D_DONOR_REPLICATES"); a0b_ok = False
                    elif zero_disp_0b:
                        holds.append("HOLD_GATE_A0B_14D_SAFETY_ZERO_DISPERSION_UNESTIMABLE"); a0b_ok = False
                    else:
                        if float(cc14) > max_safe_viab_c + 1e-9 or float(sp14) > max_safe_spr_c + 1e-9 or target_l95_failed:
                            holds.append("HOLD_GATE_A0B_14D_CEILING_UNSUBSTANTIATED_BY_DONOR_REPLICATES"); a0b_ok = False
                        if _r_fu_14d_vasc is not None and _r_fu_14d_eff is not None and max_safe_vasc_viab_c >= 0.0 and max_safe_eff_viab_c >= 0.0 and max_safe_spr_c >= 0.0:
                            recomp_14d_viab_adj = min(max_safe_vasc_viab_c * _r_fu_14d_vasc, max_safe_eff_viab_c * _r_fu_14d_eff)
                            recomp_14d_spr_adj = max_safe_spr_c * _r_fu_14d_vasc
                            recomp_14d_op = min(recomp_14d_viab_adj, recomp_14d_spr_adj)
                            if a0b_already_fu_adj:
                                if float(cc14) > recomp_14d_viab_adj + 1e-6 or float(sp14) > recomp_14d_spr_adj + 1e-6:
                                    fails.append("FAIL_GATE_A0B_CLAIMED_FU_ADJUSTED_CEILING_OVERSTATED"); a0b_ok = False
                                exp_14d_op = min(exp_14d_min, recomp_14d_op)
                            else:
                                exp_14d_cap = exp_14d_min * _r_fu_14d_vasc
                                if float(cc14) < max_safe_vasc_viab_c - 1e-9 and float(cc14) < max_safe_eff_viab_c - 1e-9:
                                    exp_14d_cap = min(exp_14d_cap, float(cc14) * _r_fu_14d_eff)
                                exp_14d_op = min(exp_14d_cap, recomp_14d_op)
                            all4_min = min(c7d_ceil_0b, exp_14d_op) if c7d_ceil_0b is not None else exp_14d_op
                            all4_ceiling_val = all4_min
                            if c7d_ceil_0b is not None and exp_14d_op > c7d_ceil_0b + 1e-12 and "FAIL_GATE_A0B_14D_CEILING_EXCEEDS_7D_CEILING" not in fails:
                                fails.append("FAIL_GATE_A0B_14D_CEILING_EXCEEDS_7D_CEILING"); a0b_ok = False
                            if float(pk_u95) >= all4_min and "FAIL_GATE_A0B_PEAK_FREE_NOT_BELOW_ALL4_CEILINGS" not in fails:
                                fails.append("FAIL_GATE_A0B_PEAK_FREE_NOT_BELOW_ALL4_CEILINGS"); a0b_ok = False
                            if float(d14_u95) >= all4_min and "FAIL_GATE_A0B_14D_SUSTAINED_NOT_BELOW_ALL4_CEILINGS" not in fails:
                                fails.append("FAIL_GATE_A0B_14D_SUSTAINED_NOT_BELOW_ALL4_CEILINGS"); a0b_ok = False
                        if not (tox_viab_above and tox_spr_above):
                            fails.append("FAIL_GATE_A0B_14D_TOXICITY_CEILING_UNBRACKETED_IN_REPLICATES"); a0b_ok = False
                        elif not target_v14_means or float(v14) > min(target_v14_means) + 0.5 or float(s14) > min(target_s14_means) + 0.5:
                            fails.append("FAIL_GATE_A0B_DAY14_SUMMARY_OVERSTATES_RAW_VASCULAR_REPLICATES"); a0b_ok = False

            def _verify_pfd_dense_pilot_trace(
                env_obj: Mapping[str, Any], *, exp_comp: str, pmg_val: float, ke_a: float, kr_a: float, ke_w: float, tag_p: str,
            ) -> bool:
                dpt = env_obj.get("dense_pilot_trace")
                if dpt is None:
                    holds.append(f"HOLD_{tag_p}_MISSING_DENSE_PILOT_ENVELOPE_EVIDENCE"); return False
                dpt_keys = frozenset({
                    "pilot_coating_lot_id", "pilot_compartment_id",
                    "burst_segment_hours_h", "burst_segment_free_parent_uM",
                    "washout_segment_hours_h", "washout_segment_free_parent_uM",
                    "pilot_trace_sha256",
                })
                if not isinstance(dpt, Mapping) or set(dpt.keys()) != dpt_keys:
                    fails.append(f"FAIL_{tag_p}_INVALID_DENSE_PILOT_TRACE"); return False
                psha = dpt.get("pilot_trace_sha256")
                plot_id = dpt.get("pilot_coating_lot_id")
                pcomp = dpt.get("pilot_compartment_id")
                bh = dpt.get("burst_segment_hours_h")
                bc = dpt.get("burst_segment_free_parent_uM")
                wh = dpt.get("washout_segment_hours_h")
                wc = dpt.get("washout_segment_free_parent_uM")
                exp_lot_n = str(coat_id.get("coating_lot_id", "")).strip().upper() if coat_id is not None else ""
                plot_n = str(plot_id or "").strip().upper()
                if (
                    not is_valid_sha256_hex(psha)
                    or sha256_bytes(canonical_json_bytes({k: v for k, v in dpt.items() if k != "pilot_trace_sha256"})) != str(psha)
                    or str(env_obj.get("envelope_model_sha256", "")) != str(psha)
                    or not is_nonempty_str(plot_id)
                    or (exp_lot_n and not (plot_n == exp_lot_n or plot_n.startswith(f"{exp_lot_n}-")))
                    or pcomp != exp_comp
                    or not (isinstance(bh, list) and isinstance(bc, list) and len(bh) >= 4 and len(bh) == len(bc))
                    or not (isinstance(wh, list) and isinstance(wc, list) and len(wh) >= 4 and len(wh) == len(wc))
                    or not all(is_finite_num(x) and float(x) > 0.0 for x in bh + bc + wh + wc)
                ):
                    fails.append(f"FAIL_{tag_p}_INVALID_DENSE_PILOT_TRACE"); return False
                bh_f, bc_f = [float(x) for x in bh], [float(x) for x in bc]
                wh_f, wc_f = [float(x) for x in wh], [float(x) for x in wc]
                if (
                    bh_f[0] > 2.0 + 1e-9 or wh_f[0] < 336.0 - 1e-9
                    or any(bh_f[i] <= bh_f[i - 1] or (bh_f[i] - bh_f[i - 1]) > pmg_val + 1e-9 for i in range(1, len(bh_f)))
                    or any(wh_f[i] <= wh_f[i - 1] or (wh_f[i] - wh_f[i - 1]) > pmg_val + 1e-9 for i in range(1, len(wh_f)))
                ):
                    fails.append(f"FAIL_{tag_p}_DENSE_PILOT_TRACE_SPACING_OR_PHASE_INVALID"); return False
                obs_kr_b = 0.0
                obs_ke_b = 0.0
                for i in range(1, len(bh_f)):
                    sl_b = math.log(bc_f[i] / bc_f[i - 1]) / (bh_f[i] - bh_f[i - 1])
                    obs_kr_b = max(obs_kr_b, sl_b)
                    obs_ke_b = max(obs_ke_b, -sl_b)
                obs_ke_w = 0.0
                for i in range(1, len(wh_f)):
                    sl_w = math.log(wc_f[i] / wc_f[i - 1]) / (wh_f[i] - wh_f[i - 1])
                    obs_ke_w = max(obs_ke_w, -sl_w)
                if kr_a + 1e-9 < 1.10 * obs_kr_b or ke_a + 1e-9 < 1.10 * obs_ke_b or ke_w + 1e-9 < 1.10 * obs_ke_w:
                    fails.append(f"FAIL_{tag_p}_LOCAL_PK_ENVELOPE_RATE_UNDERSTATES_DENSE_PILOT"); return False
                return True

            def _validate_pfd_local_pk_envelope(
                env_obj: Any, *, hrs: Sequence[float], u_ser: Sequence[float], l_ser: Sequence[float],
                exp_scope: str, exp_comp: str, tag_p: str,
            ) -> Optional[tuple[float, float]]:
                if env_obj is None:
                    holds.append(f"HOLD_{tag_p}_MISSING_CONTINUOUS_LOCAL_PK_ENVELOPE"); return None
                if isinstance(env_obj, Mapping) and env_obj.get("dense_pilot_trace") is None:
                    holds.append(f"HOLD_{tag_p}_MISSING_DENSE_PILOT_ENVELOPE_EVIDENCE"); return None
                e_keys = frozenset({
                    "k_elim_active_max_per_h", "k_rise_active_max_per_h", "k_elim_washout_max_per_h",
                    "coating_article_id", "evidence_scope", "compartment_id",
                    "envelope_qualification_method", "pilot_sampling_max_gap_h",
                    "burst_phase_covered", "washout_phase_covered", "source_study_ids",
                    "dense_pilot_trace",
                    "envelope_model_sha256", "envelope_receipt_sha256",
                })
                if not isinstance(env_obj, Mapping) or set(env_obj.keys()) != e_keys:
                    fails.append(f"FAIL_{tag_p}_MALFORMED_LOCAL_PK_ENVELOPE"); return None
                esha = env_obj.get("envelope_receipt_sha256")
                ke_act = env_obj.get("k_elim_active_max_per_h")
                kr_act = env_obj.get("k_rise_active_max_per_h")
                ke_wash = env_obj.get("k_elim_washout_max_per_h")
                pmg = env_obj.get("pilot_sampling_max_gap_h")
                sids = env_obj.get("source_study_ids")
                if (
                    not is_valid_sha256_hex(esha)
                    or sha256_bytes(canonical_json_bytes({k: v for k, v in env_obj.items() if k != "envelope_receipt_sha256"})) != str(esha)
                    or not is_valid_sha256_hex(env_obj.get("envelope_model_sha256"))
                    or not all(is_finite_num(x) and 0.0 < float(x) <= 0.5 for x in (ke_act, kr_act, ke_wash))
                    or not (is_strict_bool(env_obj.get("burst_phase_covered")) and env_obj["burst_phase_covered"])
                    or not (is_strict_bool(env_obj.get("washout_phase_covered")) and env_obj["washout_phase_covered"])
                    or not (isinstance(sids, list) and len(sids) >= 1 and all(is_nonempty_str(x) for x in sids))
                ):
                    fails.append(f"FAIL_{tag_p}_INVALID_LOCAL_PK_ENVELOPE"); return None
                if (
                    (coat_id is not None and env_obj.get("coating_article_id") != coat_id.get("coating_article_id"))
                    or env_obj.get("evidence_scope") != exp_scope
                    or env_obj.get("compartment_id") != exp_comp
                    or env_obj.get("envelope_qualification_method") not in ("DENSE_PILOT_TIMECOURSE_BOUND", "PHYSICAL_DEPOT_MASS_BALANCE_UPPER_BOUND")
                    or not (is_finite_num(pmg) and 0.0 < float(pmg) <= 2.0)
                ):
                    fails.append(f"FAIL_{tag_p}_LOCAL_PK_ENVELOPE_ARTICLE_PHASE_OR_GAP_MISMATCH"); return None
                ke_a, kr_a, ke_w = float(ke_act), float(kr_act), float(ke_wash)
                if not _verify_pfd_dense_pilot_trace(env_obj, exp_comp=exp_comp, pmg_val=float(pmg), ke_a=ke_a, kr_a=kr_a, ke_w=ke_w, tag_p=tag_p):
                    return None
                # Empirical inter-sample log-slope consistency against observed u_ser / l_ser!
                for idx_e in range(1, len(hrs)):
                    dt_e = hrs[idx_e] - hrs[idx_e - 1]
                    if dt_e <= 0.0:
                        continue
                    ke_use = ke_a if hrs[idx_e] <= 336.0 + 1e-9 else ke_w
                    if u_ser[idx_e - 1] > 0.0 and u_ser[idx_e] > 0.0:
                        su = math.log(u_ser[idx_e] / u_ser[idx_e - 1]) / dt_e
                        if (-su) > ke_use + 1e-6 or su > kr_a + 1e-6:
                            fails.append(f"FAIL_{tag_p}_LOCAL_PK_ENVELOPE_RATE_CONTRADICTS_OBSERVED_SLOPE"); return None
                    if hrs[idx_e] <= 336.0 + 1e-9 and l_ser[idx_e - 1] > 0.0 and l_ser[idx_e] > 0.0:
                        sl = math.log(l_ser[idx_e] / l_ser[idx_e - 1]) / dt_e
                        if (-sl) > ke_a + 1e-6 or sl > kr_a + 1e-6:
                            fails.append(f"FAIL_{tag_p}_LOCAL_PK_ENVELOPE_RATE_CONTRADICTS_OBSERVED_SLOPE"); return None
                # Exact continuous peak across [0, t_0]..[t_{i-1}, t_i] AND clipped [24.0, 336.0] trough!
                return _compute_pfd_continuous_envelope_24_336(hrs, u_ser, l_ser, ke_a, kr_a, ke_w)

            # Time-resolved local unbound exposure + continuous Lipschitz envelope in A-0b (t0 <= 6 h..336 h)!
            a0b_tp = a0b_ev.get("a0b_local_exposure_timepoints")
            if a0b_tp is None:
                holds.append("HOLD_GATE_A0B_MISSING_LOCAL_EXPOSURE_TIMEPOINTS"); a0b_ok = False
            elif not (isinstance(a0b_tp, list) and len(a0b_tp) >= 6):
                fails.append("FAIL_GATE_A0B_INSUFFICIENT_LOCAL_EXPOSURE_TIMEPOINTS"); a0b_ok = False
            else:
                tp0b_ok = True
                hrs0b: list[float] = []
                u_0b_ser: list[float] = []
                l_0b_ser: list[float] = []
                act_u_0b_ser: list[float] = []
                act_l_0b_ser: list[float] = []
                u95_0b_max = 0.0
                l95_0b_min = float("inf")
                act_u95_0b_max = 0.0
                act_l95_0b_min = float("inf")
                d14_u95_0b: Optional[float] = None
                act_d14_u95_0b: Optional[float] = None
                # Separate active-lot exact acceptance AND lot-mean reproducibility (1 mean per lot, zero cross-lot pooling bias!)
                alpha_0b_tp = 0.05 / float(4 * len(a0b_tp))
                zero_disp_0b_pk = False
                active_lot_norm_0b = str(coat_id.get("coating_lot_id", "")).strip().upper() if coat_id is not None else ""
                unit_rec_keys = frozenset({"coating_lot_id", "independent_unit_id", "specimen_id", "technical_well_readings_uM", "unit_mean_uM"})
                for r_tp in a0b_tp:
                    if not isinstance(r_tp, Mapping) or set(r_tp.keys()) != {"hour_h", "independent_unit_records", "free_parent_uM_replicates"}:
                        tp0b_ok = False; break
                    hh = r_tp.get("hour_h")
                    urecs = r_tp.get("independent_unit_records")
                    rr = r_tp.get("free_parent_uM_replicates")
                    if not (
                        is_finite_num(hh) and float(hh) > (hrs0b[-1] if hrs0b else 0.0)
                        and isinstance(urecs, list) and len(urecs) >= 3
                        and isinstance(rr, list) and len(rr) == len(urecs) and all(is_finite_num(x) and float(x) >= 0.0 for x in rr)
                    ):
                        tp0b_ok = False; break
                    seen_uid: set[str] = set()
                    seen_spid: set[str] = set()
                    by_lot_0b: dict[str, list[float]] = {}
                    unit_means: list[float] = []
                    for urow in urecs:
                        if not isinstance(urow, Mapping) or set(urow.keys()) != unit_rec_keys:
                            tp0b_ok = False; break
                        ulot = urow.get("coating_lot_id")
                        uid = urow.get("independent_unit_id")
                        spid = urow.get("specimen_id")
                        tw = urow.get("technical_well_readings_uM")
                        um = urow.get("unit_mean_uM")
                        if not (
                            is_nonempty_str(ulot) and is_nonempty_str(uid) and is_nonempty_str(spid)
                            and isinstance(tw, list) and len(tw) >= 1 and all(is_finite_num(x) and float(x) >= 0.0 for x in tw)
                            and is_finite_num(um) and abs((sum(float(x) for x in tw) / len(tw)) - float(um)) <= 1e-4
                        ):
                            tp0b_ok = False; break
                        un, sn, ln_u = str(uid).strip().upper(), str(spid).strip().upper(), str(ulot).strip().upper()
                        if un in seen_uid or sn in seen_spid:
                            tp0b_ok = False; break
                        seen_uid.add(un); seen_spid.add(sn)
                        by_lot_0b.setdefault(ln_u, []).append(float(um))
                        unit_means.append(float(um))
                    if (
                        not tp0b_ok
                        or len(by_lot_0b) < 3
                        or (active_lot_norm_0b and len(by_lot_0b.get(active_lot_norm_0b, [])) < 3)
                        or any(abs(unit_means[i] - float(rr[i])) > 1e-4 for i in range(len(unit_means)))
                    ):
                        tp0b_ok = False; break
                    hf_v = float(hh)
                    hrs0b.append(hf_v)
                    lot_level_means = [sum(vals) / len(vals) for vals in by_lot_0b.values()]
                    act_vals = by_lot_0b[active_lot_norm_0b] if active_lot_norm_0b else lot_level_means
                    tb_lot = sample_t_one_sided_bounds(lot_level_means, alpha=alpha_0b_tp)
                    tb_act = sample_t_one_sided_bounds(act_vals, alpha=alpha_0b_tp)
                    if tb_lot is None or tb_act is None:
                        zero_disp_0b_pk = True
                        l_t = u_t = act_l = act_u = float("nan")
                        l_t = act_l = float("-inf"); u_t = act_u = float("inf")
                    else:
                        l_t, u_t = tb_lot[1], tb_lot[2]
                        act_l, act_u = tb_act[1], tb_act[2]
                    u_0b_ser.append(u_t)
                    l_0b_ser.append(max(0.0, l_t))
                    act_u_0b_ser.append(act_u)
                    act_l_0b_ser.append(max(0.0, act_l))
                    u95_0b_max = max(u95_0b_max, u_t)
                    act_u95_0b_max = max(act_u95_0b_max, act_u)
                    if 24.0 - 1e-9 <= hf_v <= 336.0 + 1e-9:
                        l95_0b_min = min(l95_0b_min, l_t)
                        act_l95_0b_min = min(act_l95_0b_min, act_l)
                    if abs(hf_v - 336.0) <= 1e-6:
                        d14_u95_0b = u_t
                        act_d14_u95_0b = act_u
                if not tp0b_ok or hrs0b[0] > 6.0 + 1e-9 or not any(abs(h - 24.0) <= 1e-6 for h in hrs0b) or abs(hrs0b[-1] - 336.0) > 1e-6 or any((hrs0b[i] - hrs0b[i - 1]) > 72.0 + 1e-9 for i in range(1, len(hrs0b))):
                    fails.append("FAIL_GATE_A0B_LOCAL_EXPOSURE_SCHEDULE_GAP_OR_MALFORMED"); a0b_ok = False
                elif zero_disp_0b_pk:
                    holds.append("HOLD_GATE_A0B_LOCAL_PK_ZERO_DISPERSION_UNESTIMABLE"); a0b_ok = False
                else:
                    env0b = _validate_pfd_local_pk_envelope(
                        a0b_ev.get("a0b_local_pk_envelope"), hrs=hrs0b, u_ser=u_0b_ser, l_ser=l_0b_ser,
                        exp_scope="bench_unedited", exp_comp="BENCH_LOCAL_PERI_GRAFT", tag_p="GATE_A0B",
                    )
                    env0b_act = _validate_pfd_local_pk_envelope(
                        a0b_ev.get("a0b_local_pk_envelope"), hrs=hrs0b, u_ser=act_u_0b_ser, l_ser=act_l_0b_ser,
                        exp_scope="bench_unedited", exp_comp="BENCH_LOCAL_PERI_GRAFT", tag_p="GATE_A0B_ACTIVE_LOT",
                    ) if env0b is not None else None
                    if env0b is None or env0b_act is None:
                        a0b_ok = False
                    else:
                        u95_0b_max = max(u95_0b_max, env0b[0])
                        l95_0b_min = min(l95_0b_min, env0b[1])
                        act_u95_0b_max = max(act_u95_0b_max, env0b_act[0])
                        act_l95_0b_min = min(act_l95_0b_min, env0b_act[1])
                    if act_u95_0b_max >= all4_min or (eff_floor_0b is not None and act_l95_0b_min < eff_floor_0b):
                        fails.append("FAIL_GATE_A0B_ACTIVE_LOT_EXPOSURE_OUT_OF_WINDOW"); a0b_ok = False
                    if max(u95_0b_max, act_u95_0b_max) >= all4_min or float(pk_u95) + 0.5 < max(u95_0b_max, act_u95_0b_max):
                        fails.append("FAIL_GATE_A0B_LOCAL_TIMECOURSE_PEAK_BREACHES_CEILING_OR_CLAIMED"); a0b_ok = False
                    if (eff_floor_0b is not None and min(l95_0b_min, act_l95_0b_min) < eff_floor_0b) or float(sust_lo) - 0.5 > min(l95_0b_min, act_l95_0b_min):
                        fails.append("FAIL_GATE_A0B_LOCAL_TIMECOURSE_TROUGH_BELOW_IC50_OR_CLAIMED"); a0b_ok = False
                    if d14_u95_0b is None or act_d14_u95_0b is None or float(d14_u95) + 0.5 < max(d14_u95_0b, act_d14_u95_0b):
                        fails.append("FAIL_GATE_A0B_DAY14_LOCAL_U95_UNDERSTATES_TIMECOURSE"); a0b_ok = False

    def _validate_a1_elution_fields(ev: Mapping[str, Any], tag: str) -> bool:
        ok_el = True
        t50_d = ev.get("elution_t50_days")
        u14 = ev.get("day14_usable_delivery_fraction_pct")
        exh = ev.get("day35_depot_exhaustion_pct")
        res = ev.get("day35_residual_parent_pct")
        mr = ev.get("day35_terminal_mass_recovery_pct")
        d1_fr = ev.get("day1_intact_parent_free_uM")
        d14_fr = ev.get("day14_intact_parent_free_uM")
        d35_fr = ev.get("day35_intact_parent_free_uM")
        pk_mg = ev.get("peak_daily_eluted_mg")
        cl_l = ev.get("assumed_human_clearance_l_per_day")
        if not (is_strict_bool(ev.get("day14_elution_verified")) and ev["day14_elution_verified"]):
            fails.append(f"FAIL_{tag}_DAY14_ELUTION_NOT_VERIFIED"); ok_el = False
        if not (is_finite_num(t50_d) and 7.0 <= float(t50_d) <= 14.0):
            fails.append(f"FAIL_{tag}_ELUTION_T50_OUT_OF_7_14_DAYS"); ok_el = False
        if not (is_finite_num(u14) and 0.0 < float(u14) <= 85.0):
            fails.append(f"FAIL_{tag}_DAY14_USABLE_FRACTION_GT_85PCT"); ok_el = False
        if not (is_finite_num(exh) and is_finite_num(res) and float(exh) > 90.0 and 0.0 <= float(res) < 10.0 and abs((float(exh) + float(res)) - 100.0) <= 0.1):
            fails.append(f"FAIL_{tag}_DAY35_EXHAUSTION_OR_RESIDUAL_FAILED"); ok_el = False
        if not is_finite_num(mr) or not (90.0 <= float(mr) <= 110.0):
            fails.append(f"FAIL_{tag}_DAY35_MASS_RECOVERY_OUT_OF_90_110"); ok_el = False
        tr_a1 = _validate_pfd_release_trace_and_peak(ev, min_horizon_h=840.0, tag=tag)
        res_mg = ev.get("day35_residual_parent_mg")
        deg_mg = ev.get("day35_degradant_mass_mg")
        if tr_a1 is None:
            ok_el = False
        else:
            cmax_a1, tf_a1, cf_a1, lf_a1 = tr_a1
            if cmax_a1 >= 0.20:
                ok_el = False
            # Reconcile Day-1 burst (<= 15% on BOTH A-1 traces!), post-Day-1-burst Day-14 usable fraction (IIP_DRAFT_A:117-122),
            # t50 crossing of 0.5 * cum_at_840h, strict Day-35 (840 h!) mass balance, & TRUE sliding 24-h cumulative release!
            cum24_a1 = _interp_cum_at_hour(tf_a1, cf_a1, 24.0)
            cum336_a1 = _interp_cum_at_hour(tf_a1, cf_a1, 336.0)
            cum840_a1 = _interp_cum_at_hour(tf_a1, cf_a1, 840.0)
            if cum24_a1 is None or cum24_a1 <= 0.0 or (100.0 * cum24_a1 / lf_a1) > 15.0 + 1e-9:
                fails.append(f"FAIL_{tag}_DAY1_BURST_EXCEEDS_15PCT_ON_A1_TRACE"); ok_el = False
            if cum336_a1 is None or cum24_a1 is None or cum336_a1 <= cum24_a1:
                fails.append(f"FAIL_{tag}_ZERO_OR_CONTRADICTORY_DAY14_RELEASE"); ok_el = False
            else:
                # Dossier IIP_DRAFT_A:117-122 definition: usable Day-14 delivery strictly AFTER Day-1 burst = (cum_336h - cum_24h) / load!
                recomp_u14 = 100.0 * (cum336_a1 - cum24_a1) / lf_a1
                if recomp_u14 > 85.0 or (is_finite_num(u14) and abs(float(u14) - recomp_u14) > 0.5):
                    fails.append(f"FAIL_{tag}_DAY14_USABLE_FRACTION_MISMATCH_WITH_TRACE"); ok_el = False
            # Reconcile t50 strictly against 0.5 * cum_at_840h: ENTIRE monotone crossing bracket [t50_lo_d, t50_hi_d]
            # must stay inside [7.0, 14.0] days (straddling bracket -> HOLD, outside -> FAIL)!
            if cum840_a1 is None or cum840_a1 <= 0.0:
                fails.append(f"FAIL_{tag}_MISSING_EXACT_DAY35_840H_CUMULATIVE"); ok_el = False
            else:
                half_rel = 0.5 * cum840_a1
                t50_lo_d = t50_hi_d = None
                for idx_t in range(1, len(tf_a1)):
                    if tf_a1[idx_t] > 840.0 + 1e-9:
                        break
                    if cf_a1[idx_t - 1] <= half_rel <= cf_a1[idx_t] and cf_a1[idx_t] > cf_a1[idx_t - 1]:
                        t50_lo_d = tf_a1[idx_t - 1] / 24.0
                        t50_hi_d = tf_a1[idx_t] / 24.0
                        break
                if t50_lo_d is None or t50_hi_d is None or (is_finite_num(t50_d) and not (t50_lo_d - 1e-6 <= float(t50_d) <= t50_hi_d + 1e-6)):
                    fails.append(f"FAIL_{tag}_T50_CONTRADICTS_RELEASE_TRACE"); ok_el = False
                elif t50_hi_d < 7.0 - 1e-9 or t50_lo_d > 14.0 + 1e-9:
                    fails.append(f"FAIL_{tag}_T50_OUT_OF_7_14D_WINDOW"); ok_el = False
                elif t50_lo_d < 7.0 - 1e-9 or t50_hi_d > 14.0 + 1e-9:
                    holds.append(f"HOLD_{tag}_T50_CROSSING_BRACKET_STRADDLES_7_TO_14D_WINDOW"); ok_el = False
                if not (is_finite_num(res_mg) and float(res_mg) >= 0.0 and is_finite_num(deg_mg) and float(deg_mg) >= 0.0):
                    fails.append(f"FAIL_{tag}_MISSING_TERMINAL_RESIDUAL_OR_DEGRADANT_MASS_MG"); ok_el = False
                else:
                    recomp_res_pct = 100.0 * float(res_mg) / lf_a1
                    recomp_exh_pct = 100.0 - recomp_res_pct
                    recomp_mr_pct = 100.0 * (cum840_a1 + float(res_mg) + float(deg_mg)) / lf_a1
                    # Apply Day-35 advancement thresholds DIRECTLY to raw recomputed mass fractions (zero tolerance bypass!)
                    if recomp_res_pct >= 10.0 or recomp_exh_pct <= 90.0:
                        fails.append(f"FAIL_{tag}_RAW_RECOMPUTED_DAY35_EXHAUSTION_LE_90PCT"); ok_el = False
                    if is_finite_num(res) and abs(float(res) - recomp_res_pct) > 0.5:
                        fails.append(f"FAIL_{tag}_DAY35_RESIDUAL_MISMATCH_WITH_MASS_RECORD"); ok_el = False
                    if is_finite_num(exh) and abs(float(exh) - recomp_exh_pct) > 0.5:
                        fails.append(f"FAIL_{tag}_DAY35_EXHAUSTION_MISMATCH_WITH_MASS_RECORD"); ok_el = False
                    if not (90.0 <= recomp_mr_pct <= 110.0) or (is_finite_num(mr) and abs(float(mr) - recomp_mr_pct) > 0.5):
                        fails.append(f"FAIL_{tag}_TERMINAL_MASS_RECOVERY_MISMATCH_WITH_MASS_RECORD"); ok_el = False
            # TRUE sliding 24-hour cumulative release upper bound (sums multi-interval bursts within any 24-h window!)
            max_24h_mg = _recompute_max_24h_cumulative_mg(tf_a1, cf_a1)
            if is_finite_num(pk_mg) and float(pk_mg) + 1e-6 < max_24h_mg:
                fails.append(f"FAIL_{tag}_PEAK_DAILY_ELUTED_UNDERSTATES_TRACE"); ok_el = False
        if not all(is_finite_num(x) for x in (d1_fr, d14_fr, d35_fr, pk_mg, cl_l)):
            fails.append(f"FAIL_{tag}_MISSING_MEASURED_PARENT_OR_SYSTEMIC_ELUTION_DATA"); ok_el = False
        else:
            if float(d1_fr) <= 0.0 or float(d14_fr) <= 0.0 or float(d35_fr) < 0.0 or float(d1_fr) < float(d14_fr) - 1e-12:
                fails.append(f"FAIL_{tag}_INVALID_INTACT_PARENT_PROFILE"); ok_el = False
            eff_floor_a1 = ic50_u95_op if ic50_u95_op is not None else ic50_u95_val
            wash_floor_a1 = ic50_u95_wash_op if ic50_u95_wash_op is not None else ic50_u95_val
            if eff_floor_a1 is not None:
                if float(d14_fr) < eff_floor_a1:
                    fails.append(f"FAIL_{tag}_DAY14_INTACT_PARENT_BELOW_IC50_U95"); ok_el = False
            if wash_floor_a1 is not None:
                if float(d35_fr) >= 0.10 * wash_floor_a1:
                    fails.append(f"FAIL_{tag}_DAY35_INTACT_PARENT_NOT_EXHAUSTED"); ok_el = False
            if all4_ceiling_val is not None and float(d1_fr) >= all4_ceiling_val:
                fails.append(f"FAIL_{tag}_DAY1_INTACT_PARENT_EXCEEDS_CEILING"); ok_el = False
            # 1-compartment PK consistency: CL = (ln(2)/t_half)*24*Vd AND conservative joint corner CL_min = ln(2)/4.0*24*35.0 (~145.56 L/day)!
            th_v = ev.get("assumed_human_t_half_h")
            vd_v = ev.get("assumed_human_vd_l")
            cl_min_corner = (math.log(2.0) / 4.0) * 24.0 * 35.0
            if not (100.0 <= float(cl_l) <= 500.0) or float(pk_mg) <= 0.0:
                fails.append(f"FAIL_{tag}_INVALID_CLEARANCE_OR_PEAK_ELUTED_MG"); ok_el = False
            else:
                if is_finite_num(th_v) and is_finite_num(vd_v) and float(th_v) > 0.0 and float(vd_v) > 0.0:
                    cl_1c = (math.log(2.0) / float(th_v)) * 24.0 * float(vd_v)
                    if abs(float(cl_l) - cl_1c) > max(2.0, 0.02 * cl_1c):
                        fails.append(f"FAIL_{tag}_PK_CLEARANCE_INCONSISTENT_WITH_THALF_AND_VD"); ok_el = False
                eff_cl = min(float(cl_l), cl_min_corner)
                recomp_sys_ug_ml = float(pk_mg) / eff_cl
                if recomp_sys_ug_ml >= 0.20:
                    fails.append(f"FAIL_{tag}_RECOMPUTED_SYSTEMIC_PLASMA_CAP_BREACH"); ok_el = False
        # Time-resolved local free-parent exposure (t0 <= 6 h..336 h..840 h) + continuous Lipschitz envelope!
        a1_tp = ev.get("a1_local_free_parent_timepoints")
        if a1_tp is None:
            holds.append(f"HOLD_{tag}_MISSING_LOCAL_FREE_PARENT_TIMEPOINTS"); ok_el = False
        elif not (isinstance(a1_tp, list) and len(a1_tp) >= 7):
            fails.append(f"FAIL_{tag}_INSUFFICIENT_LOCAL_FREE_PARENT_TIMEPOINTS"); ok_el = False
        else:
            tp1_ok = True
            hrs1: list[float] = []
            u1_ser: list[float] = []
            l1_ser: list[float] = []
            act_u1_ser: list[float] = []
            act_l1_ser: list[float] = []
            u_act_max = 0.0
            l_act_min = float("inf")
            act_lot_u_max = 0.0
            act_lot_l_min = float("inf")
            d1_u = d14_l = d35_u = None
            act_d1_u = act_d14_l = act_d35_u = None
            alpha_a1 = 0.05 / float(4 * len(a1_tp))
            zero_disp_a1 = False
            active_lot_norm_a1 = str(coat_id.get("coating_lot_id", "")).strip().upper() if coat_id is not None else ""
            a1_unit_keys = frozenset({"coating_lot_id", "independent_unit_id", "specimen_id", "technical_well_readings_uM", "unit_mean_uM"})
            for r1 in a1_tp:
                if not isinstance(r1, Mapping) or set(r1.keys()) != {"hour_h", "independent_unit_records", "free_parent_uM_replicates"}:
                    tp1_ok = False; break
                hh = r1.get("hour_h")
                urecs = r1.get("independent_unit_records")
                rr = r1.get("free_parent_uM_replicates")
                if not (
                    is_finite_num(hh) and float(hh) > (hrs1[-1] if hrs1 else 0.0)
                    and isinstance(urecs, list) and len(urecs) >= 3
                    and isinstance(rr, list) and len(rr) == len(urecs) and all(is_finite_num(x) and float(x) >= 0.0 for x in rr)
                ):
                    tp1_ok = False; break
                seen_u1: set[str] = set()
                seen_s1: set[str] = set()
                by_lot_a1: dict[str, list[float]] = {}
                u_means1: list[float] = []
                for urow in urecs:
                    if not isinstance(urow, Mapping) or set(urow.keys()) != a1_unit_keys:
                        tp1_ok = False; break
                    ulot = urow.get("coating_lot_id")
                    uid = urow.get("independent_unit_id")
                    spid = urow.get("specimen_id")
                    tw = urow.get("technical_well_readings_uM")
                    um = urow.get("unit_mean_uM")
                    if not (
                        is_nonempty_str(ulot) and is_nonempty_str(uid) and is_nonempty_str(spid)
                        and isinstance(tw, list) and len(tw) >= 1 and all(is_finite_num(x) and float(x) >= 0.0 for x in tw)
                        and is_finite_num(um) and abs((sum(float(x) for x in tw) / len(tw)) - float(um)) <= 1e-4
                    ):
                        tp1_ok = False; break
                    un, sn, ln_u = str(uid).strip().upper(), str(spid).strip().upper(), str(ulot).strip().upper()
                    if un in seen_u1 or sn in seen_s1:
                        tp1_ok = False; break
                    seen_u1.add(un); seen_s1.add(sn)
                    by_lot_a1.setdefault(ln_u, []).append(float(um))
                    u_means1.append(float(um))
                if (
                    not tp1_ok
                    or len(by_lot_a1) < 3
                    or (active_lot_norm_a1 and len(by_lot_a1.get(active_lot_norm_a1, [])) < 3)
                    or any(abs(u_means1[i] - float(rr[i])) > 1e-4 for i in range(len(u_means1)))
                ):
                    tp1_ok = False; break
                hf_v = float(hh)
                hrs1.append(hf_v)
                lot_means1 = [sum(vals) / len(vals) for vals in by_lot_a1.values()]
                act_vals1 = by_lot_a1[active_lot_norm_a1] if active_lot_norm_a1 else lot_means1
                tb_lot = sample_t_one_sided_bounds(lot_means1, alpha=alpha_a1)
                tb_act = sample_t_one_sided_bounds(act_vals1, alpha=alpha_a1)
                if tb_lot is None or tb_act is None:
                    zero_disp_a1 = True
                    l_t = act_l = float("-inf")
                    u_t = act_u = float("inf")
                else:
                    l_t, u_t = tb_lot[1], tb_lot[2]
                    act_l, act_u = tb_act[1], tb_act[2]
                u1_ser.append(u_t)
                l1_ser.append(max(0.0, l_t))
                act_u1_ser.append(act_u)
                act_l1_ser.append(max(0.0, act_l))
                if hf_v <= 336.0 + 1e-9:
                    u_act_max = max(u_act_max, u_t)
                    act_lot_u_max = max(act_lot_u_max, act_u)
                if 24.0 - 1e-9 <= hf_v <= 336.0 + 1e-9:
                    l_act_min = min(l_act_min, l_t)
                    act_lot_l_min = min(act_lot_l_min, act_l)
                if abs(hf_v - 24.0) <= 1e-6:
                    d1_u = u_t; act_d1_u = act_u
                if abs(hf_v - 336.0) <= 1e-6:
                    d14_l = l_t; act_d14_l = act_l
                if abs(hf_v - 840.0) <= 1e-6:
                    d35_u = u_t; act_d35_u = act_u
            act_hrs = [h for h in hrs1 if 24.0 - 1e-9 <= h <= 336.0 + 1e-9]
            if (
                not tp1_ok or hrs1[0] > 6.0 + 1e-9 or d1_u is None or d14_l is None or d35_u is None
                or len(act_hrs) < 5
                or any((act_hrs[i] - act_hrs[i - 1]) > 72.0 + 1e-9 for i in range(1, len(act_hrs)))
            ):
                fails.append(f"FAIL_{tag}_LOCAL_FREE_PARENT_SCHEDULE_GAP_OR_MALFORMED"); ok_el = False
            elif zero_disp_a1:
                holds.append(f"HOLD_{tag}_LOCAL_PK_ZERO_DISPERSION_UNESTIMABLE"); ok_el = False
            else:
                env_a1 = ev.get("a1_local_pk_envelope")
                exp_sc1 = str(ev.get("evidence_scope", "bench_unedited"))
                if env_a1 is None:
                    holds.append(f"HOLD_{tag}_MISSING_CONTINUOUS_LOCAL_PK_ENVELOPE"); ok_el = False
                elif isinstance(env_a1, Mapping) and env_a1.get("dense_pilot_trace") is None:
                    holds.append(f"HOLD_{tag}_MISSING_DENSE_PILOT_ENVELOPE_EVIDENCE"); ok_el = False
                else:
                    e1_keys = frozenset({
                        "k_elim_active_max_per_h", "k_rise_active_max_per_h", "k_elim_washout_max_per_h",
                        "coating_article_id", "evidence_scope", "compartment_id",
                        "envelope_qualification_method", "pilot_sampling_max_gap_h",
                        "burst_phase_covered", "washout_phase_covered", "source_study_ids",
                        "dense_pilot_trace",
                        "envelope_model_sha256", "envelope_receipt_sha256",
                    })
                    if (
                        not isinstance(env_a1, Mapping) or set(env_a1.keys()) != e1_keys
                        or not is_valid_sha256_hex(env_a1.get("envelope_receipt_sha256"))
                        or sha256_bytes(canonical_json_bytes({k: v for k, v in env_a1.items() if k != "envelope_receipt_sha256"})) != str(env_a1["envelope_receipt_sha256"])
                        or not is_valid_sha256_hex(env_a1.get("envelope_model_sha256"))
                        or not all(is_finite_num(env_a1.get(k)) and 0.0 < float(env_a1[k]) <= 0.5 for k in ("k_elim_active_max_per_h", "k_rise_active_max_per_h", "k_elim_washout_max_per_h"))
                        or not (is_strict_bool(env_a1.get("burst_phase_covered")) and env_a1["burst_phase_covered"])
                        or not (is_strict_bool(env_a1.get("washout_phase_covered")) and env_a1["washout_phase_covered"])
                        or not (isinstance(env_a1.get("source_study_ids"), list) and len(env_a1["source_study_ids"]) >= 1 and all(is_nonempty_str(x) for x in env_a1["source_study_ids"]))
                    ):
                        fails.append(f"FAIL_{tag}_INVALID_LOCAL_PK_ENVELOPE"); ok_el = False
                    elif (
                        (coat_id is not None and env_a1.get("coating_article_id") != coat_id.get("coating_article_id"))
                        or env_a1.get("evidence_scope") != exp_sc1
                        or env_a1.get("compartment_id") != "BENCH_ELUTION_LOCAL_PERI_GRAFT"
                        or env_a1.get("envelope_qualification_method") not in ("DENSE_PILOT_TIMECOURSE_BOUND", "PHYSICAL_DEPOT_MASS_BALANCE_UPPER_BOUND")
                        or not (is_finite_num(env_a1.get("pilot_sampling_max_gap_h")) and 0.0 < float(env_a1["pilot_sampling_max_gap_h"]) <= 2.0)
                    ):
                        fails.append(f"FAIL_{tag}_LOCAL_PK_ENVELOPE_ARTICLE_PHASE_OR_GAP_MISMATCH"); ok_el = False
                    else:
                        ke_a1 = float(env_a1["k_elim_active_max_per_h"])
                        kr_a1 = float(env_a1["k_rise_active_max_per_h"])
                        ke_w1 = float(env_a1["k_elim_washout_max_per_h"])
                        dpt1 = env_a1.get("dense_pilot_trace")
                        dpt1_keys = frozenset({
                            "pilot_coating_lot_id", "pilot_compartment_id",
                            "burst_segment_hours_h", "burst_segment_free_parent_uM",
                            "washout_segment_hours_h", "washout_segment_free_parent_uM",
                            "pilot_trace_sha256",
                        })
                        exp_lot_a1 = str(coat_id.get("coating_lot_id", "")).strip().upper() if coat_id is not None else ""
                        dpt1_ok = False
                        if isinstance(dpt1, Mapping) and set(dpt1.keys()) == dpt1_keys:
                            p1sha = dpt1.get("pilot_trace_sha256")
                            p1lot = str(dpt1.get("pilot_coating_lot_id") or "").strip().upper()
                            bh1, bc1 = dpt1.get("burst_segment_hours_h"), dpt1.get("burst_segment_free_parent_uM")
                            wh1, wc1 = dpt1.get("washout_segment_hours_h"), dpt1.get("washout_segment_free_parent_uM")
                            if (
                                is_valid_sha256_hex(p1sha)
                                and sha256_bytes(canonical_json_bytes({k: v for k, v in dpt1.items() if k != "pilot_trace_sha256"})) == str(p1sha)
                                and str(env_a1.get("envelope_model_sha256", "")) == str(p1sha)
                                and is_nonempty_str(dpt1.get("pilot_coating_lot_id"))
                                and (not exp_lot_a1 or p1lot == exp_lot_a1 or p1lot.startswith(f"{exp_lot_a1}-"))
                                and dpt1.get("pilot_compartment_id") == "BENCH_ELUTION_LOCAL_PERI_GRAFT"
                                and isinstance(bh1, list) and isinstance(bc1, list) and len(bh1) >= 4 and len(bh1) == len(bc1)
                                and isinstance(wh1, list) and isinstance(wc1, list) and len(wh1) >= 4 and len(wh1) == len(wc1)
                                and all(is_finite_num(x) and float(x) > 0.0 for x in bh1 + bc1 + wh1 + wc1)
                            ):
                                bh1f, bc1f = [float(x) for x in bh1], [float(x) for x in bc1]
                                wh1f, wc1f = [float(x) for x in wh1], [float(x) for x in wc1]
                                pm1 = float(env_a1["pilot_sampling_max_gap_h"])
                                if (
                                    bh1f[0] <= 2.0 + 1e-9 and wh1f[0] >= 336.0 - 1e-9
                                    and all(bh1f[i] > bh1f[i - 1] and (bh1f[i] - bh1f[i - 1]) <= pm1 + 1e-9 for i in range(1, len(bh1f)))
                                    and all(wh1f[i] > wh1f[i - 1] and (wh1f[i] - wh1f[i - 1]) <= pm1 + 1e-9 for i in range(1, len(wh1f)))
                                ):
                                    okr1 = max((math.log(bc1f[i] / bc1f[i - 1]) / (bh1f[i] - bh1f[i - 1]) for i in range(1, len(bh1f))), default=0.0)
                                    oke1 = max((-math.log(bc1f[i] / bc1f[i - 1]) / (bh1f[i] - bh1f[i - 1]) for i in range(1, len(bh1f))), default=0.0)
                                    okw1 = max((-math.log(wc1f[i] / wc1f[i - 1]) / (wh1f[i] - wh1f[i - 1]) for i in range(1, len(wh1f))), default=0.0)
                                    if kr_a1 + 1e-9 < 1.10 * max(0.0, okr1) or ke_a1 + 1e-9 < 1.10 * max(0.0, oke1) or ke_w1 + 1e-9 < 1.10 * max(0.0, okw1):
                                        fails.append(f"FAIL_{tag}_LOCAL_PK_ENVELOPE_RATE_UNDERSTATES_DENSE_PILOT"); ok_el = False
                                    else:
                                        dpt1_ok = True
                                else:
                                    fails.append(f"FAIL_{tag}_DENSE_PILOT_TRACE_SPACING_OR_PHASE_INVALID"); ok_el = False
                            else:
                                fails.append(f"FAIL_{tag}_INVALID_DENSE_PILOT_TRACE"); ok_el = False
                        else:
                            fails.append(f"FAIL_{tag}_INVALID_DENSE_PILOT_TRACE"); ok_el = False
                        if dpt1_ok:
                            slope_ok1 = True
                            for idx_e in range(1, len(hrs1)):
                                dt_e = hrs1[idx_e] - hrs1[idx_e - 1]
                                if dt_e <= 0.0:
                                    continue
                                ke_use = ke_a1 if hrs1[idx_e] <= 336.0 + 1e-9 else ke_w1
                                if u1_ser[idx_e - 1] > 0.0 and u1_ser[idx_e] > 0.0:
                                    su = math.log(u1_ser[idx_e] / u1_ser[idx_e - 1]) / dt_e
                                    if (-su) > ke_use + 1e-6 or su > kr_a1 + 1e-6:
                                        slope_ok1 = False; break
                                if hrs1[idx_e] <= 336.0 + 1e-9 and l1_ser[idx_e - 1] > 0.0 and l1_ser[idx_e] > 0.0:
                                    sl = math.log(l1_ser[idx_e] / l1_ser[idx_e - 1]) / dt_e
                                    if (-sl) > ke_a1 + 1e-6 or sl > kr_a1 + 1e-6:
                                        slope_ok1 = False; break
                            if not slope_ok1:
                                fails.append(f"FAIL_{tag}_LOCAL_PK_ENVELOPE_RATE_CONTRADICTS_OBSERVED_SLOPE"); ok_el = False
                            else:
                                cont_pk1, cont_tr1 = _compute_pfd_continuous_envelope_24_336(
                                    hrs1, u1_ser, l1_ser, ke_a1, kr_a1, ke_w1,
                                )
                                cont_pk1_act, cont_tr1_act = _compute_pfd_continuous_envelope_24_336(
                                    hrs1, act_u1_ser, act_l1_ser, ke_a1, kr_a1, ke_w1,
                                )
                                u_act_max = max(u_act_max, cont_pk1)
                                l_act_min = min(l_act_min, cont_tr1)
                                act_lot_u_max = max(act_lot_u_max, cont_pk1_act)
                                act_lot_l_min = min(act_lot_l_min, cont_tr1_act)
                eff_floor_a1_tp = ic50_u95_op if ic50_u95_op is not None else ic50_u95_val
                wash_floor_a1_tp = ic50_u95_wash_op if ic50_u95_wash_op is not None else ic50_u95_val
                if (all4_ceiling_val is not None and act_lot_u_max >= all4_ceiling_val) or (eff_floor_a1_tp is not None and act_lot_l_min < eff_floor_a1_tp):
                    fails.append(f"FAIL_{tag}_ACTIVE_LOT_EXPOSURE_OUT_OF_WINDOW"); ok_el = False
                if eff_floor_a1_tp is not None and min(l_act_min, act_lot_l_min) < eff_floor_a1_tp:
                    fails.append(f"FAIL_{tag}_DAYS1_14_INTERIOR_FREE_PARENT_DIP_BELOW_IC50_U95"); ok_el = False
                if all4_ceiling_val is not None and max(u_act_max, act_lot_u_max) >= all4_ceiling_val:
                    fails.append(f"FAIL_{tag}_DAYS1_14_LOCAL_FREE_PARENT_EXCEEDS_CEILING"); ok_el = False
                if wash_floor_a1_tp is not None and max(d35_u, act_d35_u if act_d35_u is not None else d35_u) >= 0.10 * wash_floor_a1_tp:
                    fails.append(f"FAIL_{tag}_DAY35_LOCAL_FREE_PARENT_U95_NOT_EXHAUSTED"); ok_el = False
                if is_finite_num(d1_fr) and float(d1_fr) + 0.5 < max(d1_u, act_d1_u if act_d1_u is not None else d1_u):
                    fails.append(f"FAIL_{tag}_DAY1_SCALAR_UNDERSTATES_RECOMPUTED_LOCAL_U95"); ok_el = False
                if is_finite_num(d14_fr) and float(d14_fr) - 0.5 > min(d14_l, act_d14_l if act_d14_l is not None else d14_l):
                    fails.append(f"FAIL_{tag}_DAY14_SCALAR_OVERSTATES_RECOMPUTED_LOCAL_L95"); ok_el = False
        # Days 0-35 time-resolved local pH verification (7.25-7.45 across full 840-h elution window per Draft A s5)!
        a1_ph_tps = ev.get("a1_local_ph_timepoints")
        if a1_ph_tps is None:
            holds.append(f"HOLD_{tag}_MISSING_35D_TIME_RESOLVED_PH"); ok_el = False
        elif not isinstance(a1_ph_tps, list) or len(a1_ph_tps) < 6:
            fails.append(f"FAIL_{tag}_LOCAL_PH_OUTSIDE_7P25_7P45_OR_INCOMPLETE_35D"); ok_el = False
        else:
            _ph1_rk = frozenset({"hour_h", "coating_lot_id", "ph_min", "ph_max"})
            _ph1_prev = -1.0
            _ph1_ok = True
            _exp_clot1 = str(coat_id.get("coating_lot_id", "")).strip() if coat_id is not None else ""
            for _pr1 in a1_ph_tps:
                if not (
                    isinstance(_pr1, Mapping) and set(_pr1.keys()) == _ph1_rk
                    and is_finite_num(_pr1.get("hour_h")) and float(_pr1["hour_h"]) > _ph1_prev and float(_pr1["hour_h"]) > 0.0
                    and is_nonempty_str(_pr1.get("coating_lot_id"))
                    and (not _exp_clot1 or str(_pr1["coating_lot_id"]).strip() == _exp_clot1)
                    and is_finite_num(_pr1.get("ph_min")) and is_finite_num(_pr1.get("ph_max"))
                    and 7.25 <= float(_pr1["ph_min"]) <= float(_pr1["ph_max"]) <= 7.45
                ):
                    _ph1_ok = False; break
                if _ph1_prev >= 0.0 and (float(_pr1["hour_h"]) - _ph1_prev) > 168.0 + 1e-9:
                    _ph1_ok = False; break
                _ph1_prev = float(_pr1["hour_h"])
            if (
                not _ph1_ok
                or float(a1_ph_tps[0]["hour_h"]) > 24.0 + 1e-9
                or float(a1_ph_tps[-1]["hour_h"]) < 840.0 - 1e-9
            ):
                fails.append(f"FAIL_{tag}_LOCAL_PH_OUTSIDE_7P25_7P45_OR_INCOMPLETE_35D"); ok_el = False
        return ok_el

    a1_extras = frozenset({
        "initial_pirfenidone_loading_mg", "day35_residual_parent_mg", "day35_degradant_mass_mg",
        "elution_started_at_utc", "elution_t50_days", "day14_usable_delivery_fraction_pct",
        "day35_depot_exhaustion_pct", "day35_residual_parent_pct",
        "day35_terminal_mass_recovery_pct", "day14_elution_verified",
        "elution_time_hours", "cumulative_intact_parent_released_mg",
        "assumed_human_t_half_h", "assumed_human_vd_l",
        "day1_intact_parent_free_uM", "day14_intact_parent_free_uM", "day35_intact_parent_free_uM",
        "peak_daily_eluted_mg", "assumed_human_clearance_l_per_day",
        "a1_local_free_parent_timepoints", "a1_local_pk_envelope",
        "a1_local_ph_timepoints",
        "manufacturing_lot_release_records",
    })

    a1_bench_ev = _validate_content_receipt(
        rec.get("a1_bench_evidence"),
        expected_stage="A-1-BENCH", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="bench_unedited",
        expected_coating_identity=coat_id,
        expected_parent=a0b_ev, allowed_extra_keys=a1_extras, fails=fails, holds=holds,
        missing_hold="HOLD_GATE_A1_BENCH_ELUTION_MISSING",
        fail_code="FAIL_GATE_A1_BENCH_ELUTION_FAILED",
        mismatch_code="FAIL_GATE_A1_BENCH_SCOPE_MISMATCH",
    )
    a1_bench_ok = a1_bench_ev is not None and a1_bench_ev.get("verdict") == "PASS"
    if a1_bench_ev is not None:
        t_el_st = parse_utc_iso_ts(a1_bench_ev.get("elution_started_at_utc"))
        t_a1b = parse_utc_iso_ts(a1_bench_ev.get("recorded_at_utc"))
        t_a0b = parse_utc_iso_ts(a0b_ev.get("recorded_at_utc")) if a0b_ev is not None else None
        if t_el_st is None or t_a1b is None:
            fails.append("FAIL_GATE_A1_BENCH_MISSING_ELUTION_START_UTC"); a1_bench_ok = False
        else:
            if t_a0b is not None and t_el_st < t_a0b:
                fails.append("FAIL_GATE_A1_BENCH_ELUTION_STARTED_BEFORE_A0B"); a1_bench_ok = False
            if (t_a1b - t_el_st) < timedelta(days=35):
                fails.append("FAIL_GATE_A1_BENCH_ELAPSED_ELUTION_DURATION_LT_35_DAYS"); a1_bench_ok = False
        if not _validate_a1_elution_fields(a1_bench_ev, "GATE_A1_BENCH"):
            a1_bench_ok = False

    if phase == "BENCH_UNEDITED":
        verdict = "FAIL" if fails else ("HOLD" if holds else "PASS_BENCH_ONLY_UNEDITED_PRE_MATERIALIZATION")
        return {
            "gate": "GATE-40", "phase": phase, "scope_track": scope_track, "verdict": verdict,
            "release_authorizing": False, "live_ledger_authenticated": False,
            "upstream_archive_verification": OFFLINE_ARCHIVE_NOTE,
            "a0a_operative_limits_uM": {**a0a_op_payload, "all4_ceiling_fu_adjusted_uM": all4_ceiling_val},
            "product_id": rec.get("product_id"), "required_switch": spec["required_switch"] if spec else None,
            "failures": fails, "holds": holds,
        }

    a1_prereqs: list[tuple[str, Optional[Mapping[str, Any]]]] = [("BANK_MATERIALIZATION", mat_ev)]
    if g31_ev is not None:
        a1_prereqs.append(("GATE-31", g31_ev))
    a1_ev = _validate_content_receipt(
        rec.get("a1_evidence"),
        expected_stage="A-1", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="exact_product",
        expected_coating_identity=coat_id,
        expected_parent=a1_bench_ev,
        min_prereq_receipts=a1_prereqs,
        allowed_extra_keys=a1_extras, fails=fails, holds=holds,
        missing_hold="HOLD_GATE_A1_ELUTION_MISSING",
        fail_code="FAIL_GATE_A1_ELUTION_FAILED",
        mismatch_code="FAIL_GATE_A1_SCOPE_MISMATCH",
    )
    a1_ok = a1_ev is not None and a1_ev.get("verdict") == "PASS"
    if a1_ev is not None:
        t_el_st = parse_utc_iso_ts(a1_ev.get("elution_started_at_utc"))
        t_a1 = parse_utc_iso_ts(a1_ev.get("recorded_at_utc"))
        t_a1b = parse_utc_iso_ts(a1_bench_ev.get("recorded_at_utc")) if a1_bench_ev is not None else None
        t_mat = parse_utc_iso_ts(mat_ev.get("recorded_at_utc")) if mat_ev is not None else None
        if t_el_st is None or t_a1 is None:
            fails.append("FAIL_GATE_A1_MISSING_ELUTION_START_UTC"); a1_ok = False
        else:
            if t_a1b is not None and t_el_st < t_a1b:
                fails.append("FAIL_GATE_A1_EXACT_STARTED_BEFORE_BENCH_A1_COMPLETION"); a1_ok = False
            if t_mat is not None and t_el_st < t_mat:
                fails.append("FAIL_GATE_A1_EXACT_ELUTION_STARTED_BEFORE_MATERIALIZATION"); a1_ok = False
            if (t_a1 - t_el_st) < timedelta(days=35):
                fails.append("FAIL_GATE_A1_ELAPSED_ELUTION_DURATION_LT_35_DAYS"); a1_ok = False
        if not _validate_a1_elution_fields(a1_ev, "GATE_A1"):
            a1_ok = False

    # Gate A-2: matched blank-vehicle Readout-2 (>= 90% Fieller!) + Readout-3B (<= +2 pp!) + INS+ viability & unpooled proliferation!
    a2_extras = frozenset({
        "study_start_utc", "a2_specimen_id", "a2_cohort_id",
        "shield_retention_by_component", "worst_face_o2_mmhg", "hour0_density_by_lineage",
        "ins_positive_beta_viability_pct", "a2_per_lot_proliferation_records",
        "day14_iec_sprouting_pct_ctrl", "day14_iec_sprout_length_pct_ctrl",
        "day14_iec_branching_pct_ctrl", "day14_iec_network_persistence_pct_ctrl",
        "a2_vascular_vehicle_record_id", "a2_vascular_raw_measurements",
        "day14_iec_teer_pct_ctrl", "day14_iec_cdh5_pct_ctrl",
        "day14_iec_col4a2_pct_ctrl", "day14_iec_klf2_fold", "day14_iec_vcam1_adhesion_fold",
        "readout2_evidence", "readout3b_evidence",
    })
    a2_ev = _validate_content_receipt(
        rec.get("a2_evidence"),
        expected_stage="A-2", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="exact_product",
        expected_coating_identity=coat_id,
        expected_parent=a1_ev, min_prereq_receipts=[("BANK_MATERIALIZATION", mat_ev)],
        allowed_extra_keys=a2_extras, fails=fails, holds=holds,
        missing_hold="HOLD_GATE_A2_SHIELD_GSIS_MISSING",
        fail_code="FAIL_GATE_A2_SHIELD_GSIS_FAILED",
        mismatch_code="FAIL_GATE_A2_SCOPE_MISMATCH",
    )
    a2_ok = a2_ev is not None and a2_ev.get("verdict") == "PASS"
    blank_veh_id = coat_id["matched_blank_vehicle_lot_id"] if coat_id is not None else None
    if a2_ev is not None:
        t_a2_st = parse_utc_iso_ts(a2_ev.get("study_start_utc"))
        t_a2_end = parse_utc_iso_ts(a2_ev.get("recorded_at_utc"))
        t_a1_end = parse_utc_iso_ts(a1_ev.get("recorded_at_utc")) if a1_ev is not None else None
        if t_a2_st is None or t_a2_end is None or (t_a2_end - t_a2_st) < timedelta(days=14):
            fails.append("FAIL_GATE_A2_ELAPSED_STUDY_DURATION_LT_14_DAYS"); a2_ok = False
        elif t_a1_end is not None and t_a2_st < t_a1_end:
            fails.append("FAIL_GATE_A2_STARTED_BEFORE_A1_COMPLETION"); a2_ok = False
        smap = a2_ev.get("shield_retention_by_component")
        req_comp = SHIELD_COMPONENTS_BY_PRODUCT.get(prod_s, frozenset())
        if not isinstance(smap, Mapping) or set(smap.keys()) != req_comp:
            fails.append("FAIL_GATE_A2_INCOMPLETE_COMPONENT_SHIELD_MAP"); a2_ok = False
        else:
            for cname in sorted(req_comp):
                cv = smap.get(cname)
                if not (is_finite_num(cv) and 85.0 <= float(cv) <= 100.0):
                    fails.append(f"FAIL_GATE_A2_SHIELD_COMPONENT_BELOW_85PCT:{cname}"); a2_ok = False
        ins_v = a2_ev.get("ins_positive_beta_viability_pct")
        if not (is_finite_num(ins_v) and 90.0 <= float(ins_v) <= 100.0):
            fails.append("FAIL_GATE_A2_INS_POSITIVE_BETA_VIABILITY_BELOW_90PCT"); a2_ok = False
        a2_prolif = a2_ev.get("a2_per_lot_proliferation_records")
        if not isinstance(a2_prolif, list) or len(a2_prolif) < 3:
            fails.append("FAIL_GATE_A2_REQUIRES_AT_LEAST_3_PER_LOT_PROLIFERATION_RECORDS"); a2_ok = False
        else:
            seen_a2p: set[str] = set()
            seen_a2a: set[str] = set()
            p_allowed = frozenset({"lot_id", "assay_record_id", "ki67_fold_vs_ctrl", "edu_fold_vs_ctrl", "ki67_edu_referred"})
            for idx, prow in enumerate(a2_prolif):
                if not isinstance(prow, Mapping):
                    fails.append(f"FAIL_GATE_A2_PROLIF_LOT_MALFORMED:{idx}"); a2_ok = False; continue
                _check_allowed_keys(prow, p_allowed, fails, f"GATE_A2_PROLIF_{idx}")
                if not is_nonempty_str(prow.get("lot_id")) or not is_nonempty_str(prow.get("assay_record_id")):
                    fails.append("FAIL_GATE_A2_PROLIF_MISSING_LOT_OR_ASSAY_ID"); a2_ok = False; continue
                plid = str(prow["lot_id"]).strip().upper()
                paid = str(prow["assay_record_id"]).strip().upper()
                if plid in seen_a2p or paid in seen_a2a:
                    fails.append("FAIL_GATE_A2_PROLIF_DUPLICATE_LOT_OR_ASSAY_ID"); a2_ok = False; continue
                seen_a2p.add(plid); seen_a2a.add(paid)
                kf, ef = prow.get("ki67_fold_vs_ctrl"), prow.get("edu_fold_vs_ctrl")
                if not (is_finite_num(kf) and is_finite_num(ef) and float(kf) > 0.0 and float(ef) > 0.0):
                    fails.append(f"FAIL_GATE_A2_PROLIF_INVALID_FOLD:{plid}"); a2_ok = False
                elif float(kf) > 1.0 or float(ef) > 1.0:
                    if is_strict_bool(prow.get("ki67_edu_referred")) and prow["ki67_edu_referred"]:
                        holds.append(f"HOLD_GATE_A2_PROLIFERATION_ELEVATION_REFERRED:{plid}")
                    else:
                        fails.append(f"FAIL_GATE_A2_UNREFERRED_PROLIFERATION_ELEVATION:{plid}"); a2_ok = False
        for bkey, bmin, bmax, bcode in (
            ("day14_iec_sprouting_pct_ctrl", 90.0, 200.0, "FAIL_GATE_A2_DAY14_IEC_SPROUTING_BELOW_90PCT"),
            ("day14_iec_sprout_length_pct_ctrl", 90.0, 200.0, "FAIL_GATE_A2_DAY14_IEC_SPROUT_LENGTH_BELOW_90PCT"),
            ("day14_iec_branching_pct_ctrl", 90.0, 200.0, "FAIL_GATE_A2_DAY14_IEC_BRANCHING_BELOW_90PCT"),
            ("day14_iec_network_persistence_pct_ctrl", 90.0, 200.0, "FAIL_GATE_A2_DAY14_IEC_NETWORK_PERSISTENCE_BELOW_90PCT"),
            ("day14_iec_teer_pct_ctrl", 90.0, 200.0, "FAIL_GATE_A2_DAY14_IEC_TEER_BELOW_90PCT"),
            ("day14_iec_cdh5_pct_ctrl", 90.0, 200.0, "FAIL_GATE_A2_DAY14_IEC_CDH5_BELOW_90PCT"),
            ("day14_iec_col4a2_pct_ctrl", 85.0, 200.0, "FAIL_GATE_A2_DAY14_IEC_COL4A2_BELOW_85PCT"),
            ("day14_iec_klf2_fold", 0.75, 10.0, "FAIL_GATE_A2_DAY14_IEC_KLF2_BELOW_0P75"),
            ("day14_iec_vcam1_adhesion_fold", 0.0, 1.25, "FAIL_GATE_A2_DAY14_IEC_VCAM1_GT_1P25"),
        ):
            bv = a2_ev.get(bkey)
            if not (is_finite_num(bv) and bmin <= float(bv) <= bmax):
                fails.append(bcode); a2_ok = False
        a2_vraw = a2_ev.get("a2_vascular_raw_measurements")
        a2_vrec = a2_ev.get("a2_vascular_vehicle_record_id")
        a2_sp_pre = a2_ev.get("a2_specimen_id")
        a2_vraw_prov_keys = frozenset({
            "specimen_id", "coating_lot_id", "exposure_started_at_utc",
            "assessed_at_utc", "vascular_assay_receipt_sha256",
        })
        a2_vraw_num_keys = frozenset({
            "treated_sprout_length_um", "vehicle_sprout_length_um",
            "treated_branching_junctions", "vehicle_branching_junctions",
            "treated_network_persistence_idx", "vehicle_network_persistence_idx",
        })
        a2_vraw_keys = a2_vraw_num_keys | a2_vraw_prov_keys | frozenset({"matched_vehicle_lot_id"})
        if isinstance(a2_vraw, Mapping) and any(a2_vraw.get(pk) is None for pk in a2_vraw_prov_keys):
            holds.append("HOLD_GATE_A2_VASCULAR_MISSING_EXPOSURE_TIMING_OR_SPECIMEN"); a2_ok = False
        elif not (
            is_nonempty_str(a2_vrec) and isinstance(a2_vraw, Mapping) and set(a2_vraw.keys()) == a2_vraw_keys
            and is_nonempty_str(a2_vraw.get("specimen_id"))
            and (not is_nonempty_str(a2_sp_pre) or str(a2_vraw["specimen_id"]).strip() == str(a2_sp_pre).strip())
            and is_nonempty_str(a2_vraw.get("coating_lot_id"))
            and (coat_id is None or str(a2_vraw["coating_lot_id"]).strip() == str(coat_id["coating_lot_id"]).strip())
            and (blank_veh_id is None or a2_vraw.get("matched_vehicle_lot_id") == blank_veh_id)
            and is_valid_sha256_hex(a2_vraw.get("vascular_assay_receipt_sha256"))
            and sha256_bytes(canonical_json_bytes({k: v for k, v in a2_vraw.items() if k != "vascular_assay_receipt_sha256"})) == str(a2_vraw["vascular_assay_receipt_sha256"])
            and all(is_finite_num(a2_vraw[k]) and float(a2_vraw[k]) > 0.0 for k in a2_vraw_num_keys)
        ):
            fails.append("FAIL_GATE_A2_VASCULAR_RAW_MEASUREMENTS_OR_VEHICLE_UNBOUND"); a2_ok = False
        else:
            t_vasc_st = parse_utc_iso_ts(a2_vraw.get("exposure_started_at_utc"))
            t_vasc_end = parse_utc_iso_ts(a2_vraw.get("assessed_at_utc"))
            if (
                t_vasc_st is None or t_vasc_end is None
                or (t_vasc_end - t_vasc_st) < timedelta(days=14)
                or (t_a2_st is not None and t_vasc_st < t_a2_st)
                or (t_a2_end is not None and t_vasc_end > t_a2_end)
            ):
                fails.append("FAIL_GATE_A2_VASCULAR_EXPOSURE_DURATION_LT_14_DAYS"); a2_ok = False
            r_len = 100.0 * float(a2_vraw["treated_sprout_length_um"]) / float(a2_vraw["vehicle_sprout_length_um"])
            r_br = 100.0 * float(a2_vraw["treated_branching_junctions"]) / float(a2_vraw["vehicle_branching_junctions"])
            r_np = 100.0 * float(a2_vraw["treated_network_persistence_idx"]) / float(a2_vraw["vehicle_network_persistence_idx"])
            sl_v = a2_ev.get("day14_iec_sprout_length_pct_ctrl")
            br_v = a2_ev.get("day14_iec_branching_pct_ctrl")
            np_v = a2_ev.get("day14_iec_network_persistence_pct_ctrl")
            sp_v = a2_ev.get("day14_iec_sprouting_pct_ctrl")
            if (
                not all(is_finite_num(x) for x in (sl_v, br_v, np_v, sp_v))
                or abs(float(sl_v) - r_len) > 0.5 or abs(float(br_v) - r_br) > 0.5 or abs(float(np_v) - r_np) > 0.5
                or float(sp_v) > min(r_len, r_br, r_np) + 0.5
                or min(r_len, r_br, r_np) < 90.0
            ):
                fails.append("FAIL_GATE_A2_VASCULAR_COMPONENT_RAW_RECONCILIATION_OR_FLOOR_FAILED"); a2_ok = False
        if not _validate_readout2_gsis(
            a2_ev.get("readout2_evidence"), fails=fails, holds=holds, prefix="GATE_A2",
            expected_comparator_id=blank_veh_id, min_comparator_output_ratio=0.90,
            parent_recorded_at_utc=t_a2_end, min_exposure_start_utc=t_a2_st,
            expected_prod=prod_s, expected_bank=bank_s, expected_lot=lot_s, expected_route=route_s,
        ):
            a2_ok = False
        a2_sp = a2_ev.get("a2_specimen_id")
        a2_coh = a2_ev.get("a2_cohort_id")
        if not (is_nonempty_str(a2_sp) and is_nonempty_str(a2_coh)):
            holds.append("HOLD_GATE_A2_MISSING_SPECIMEN_OR_COHORT_ID"); a2_ok = False
        if not _validate_readout3b_nk(
            a2_ev.get("readout3b_evidence"), fails=fails, holds=holds, prefix="GATE_A2",
            expected_vehicle_lot_id=blank_veh_id, max_vehicle_delta_pp=2.0,
            require_hla_e_spr=bool(spec["hla_e_engineered"]) if spec is not None else True,
            expected_specimen_id=str(a2_sp).strip() if is_nonempty_str(a2_sp) else None,
            expected_lot_id=lot_s or None,
            expected_cohort_id=str(a2_coh).strip() if is_nonempty_str(a2_coh) else None,
        ):
            a2_ok = False
        o2_2 = a2_ev.get("worst_face_o2_mmhg")
        if not (is_finite_num(o2_2) and float(o2_2) >= 40.0):
            fails.append("FAIL_GATE_A2_WORST_FACE_O2_BELOW_40MMHG"); a2_ok = False
        if spec is not None and not _validate_lineage_hour0_density(
            spec, a2_ev.get("hour0_density_by_lineage"),
            required_lineages=REQUIRED_HOUR0_LINEAGES_FULL, fails=fails, prefix="GATE_A2",
        ):
            a2_ok = False

    # Gate A-3: data-backed matched-vehicle kill parity + canonical OQ-012!
    a3_extras = frozenset({
        "matched_control_switch_parity_evidence", "oq012_clonogenic_block",
    })
    a3_ev = _validate_content_receipt(
        rec.get("a3_evidence"),
        expected_stage="A-3", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="exact_product",
        expected_coating_identity=coat_id,
        expected_parent=a2_ev, min_prereq_receipts=[("BANK_MATERIALIZATION", mat_ev)],
        allowed_extra_keys=a3_extras, fails=fails, holds=holds,
        missing_hold="HOLD_GATE_A3_SWITCH_PARITY_MISSING",
        fail_code="FAIL_GATE_A3_SWITCH_PARITY_FAILED",
        mismatch_code="FAIL_GATE_A3_SCOPE_MISMATCH",
    )
    a3_ok = a3_ev is not None and a3_ev.get("verdict") == "PASS"
    if a3_ev is not None:
        if not _validate_matched_control_switch_parity(
            a3_ev.get("matched_control_switch_parity_evidence"),
            expected_control_lot_id=blank_veh_id, fails=fails, holds=holds, prefix="GATE_A3",
        ):
            a3_ok = False
        if not _validate_oq012_gate34_clonogenic_block(a3_ev.get("oq012_clonogenic_block"), fails=fails, holds=holds, prefix="GATE_A3"):
            a3_ok = False

    # Gate A-4a: coating identity + >= 14d elapsed + prereq digests pinned + >= 3 matched donor-pair records!
    a4a_extras = frozenset({
        "coupon_started_at_utc", "donor_pair_records",
        "day7_col1a1_reduction_pct", "day7_alpha_sma_reduction_pct",
        "day14_col1a1_reduction_pct", "day14_alpha_sma_reduction_pct",
        "day14_viability_pct", "worst_face_o2_mmhg",
    })
    a4a_ev = _validate_content_receipt(
        rec.get("a4a_evidence"),
        expected_stage="A-4a", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="exact_product",
        expected_coating_identity=coat_id,
        expected_parent=a3_ev,
        min_prereq_receipts=[("BANK_MATERIALIZATION", mat_ev), ("NATIVE_SAFETY_SWITCH", sw_ev), ("GATE-0V-KILL", g0v_ev)],
        allowed_extra_keys=a4a_extras, fails=fails, holds=holds,
        missing_hold="HOLD_GATE_A4A_COATED_COUPON_MISSING",
        fail_code="FAIL_GATE_A4A_COATED_COUPON_FAILED",
        mismatch_code="FAIL_GATE_A4A_SCOPE_MISMATCH",
    )
    a4a_ok = a4a_ev is not None and a4a_ev.get("verdict") == "PASS"
    if a4a_ev is not None:
        t_cst = parse_utc_iso_ts(a4a_ev.get("coupon_started_at_utc"))
        t_a4a = parse_utc_iso_ts(a4a_ev.get("recorded_at_utc"))
        t_a3 = parse_utc_iso_ts(a3_ev.get("recorded_at_utc")) if a3_ev is not None else None
        t_sw = parse_utc_iso_ts(sw_ev.get("recorded_at_utc")) if sw_ev is not None else None
        t_g0 = parse_utc_iso_ts(g0v_ev.get("recorded_at_utc")) if g0v_ev is not None else None
        if t_cst is None or t_a4a is None:
            fails.append("FAIL_GATE_A4A_MISSING_COUPON_START_UTC"); a4a_ok = False
        else:
            for lbl, pt in (("A3", t_a3), ("SWITCH", t_sw), ("GATE0V", t_g0)):
                if pt is not None and t_cst < pt:
                    fails.append(f"FAIL_GATE_A4A_COUPON_STARTED_BEFORE_{lbl}"); a4a_ok = False
            if (t_a4a - t_cst) < timedelta(days=14):
                fails.append("FAIL_GATE_A4A_ELAPSED_COUPON_DURATION_LT_14_DAYS"); a4a_ok = False
        d7_c = a4a_ev.get("day7_col1a1_reduction_pct")
        d7_s = a4a_ev.get("day7_alpha_sma_reduction_pct")
        d14_c = a4a_ev.get("day14_col1a1_reduction_pct")
        d14_s = a4a_ev.get("day14_alpha_sma_reduction_pct")
        v14_4a = a4a_ev.get("day14_viability_pct")
        o2_4a = a4a_ev.get("worst_face_o2_mmhg")
        if not all(is_finite_num(x) for x in (d7_c, d7_s, d14_c, d14_s, v14_4a, o2_4a)):
            fails.append("FAIL_GATE_A4A_INCOMPLETE_QUANTITATIVE_METRICS"); a4a_ok = False
        else:
            for mk_nm, mk_val in (("day7_col1a1", d7_c), ("day7_alpha_sma", d7_s), ("day14_col1a1", d14_c), ("day14_alpha_sma", d14_s)):
                if not (0.0 <= float(mk_val) <= 100.0):
                    fails.append(f"FAIL_GATE_A4A_REDUCTION_OUT_OF_DOMAIN_0_100:{mk_nm}"); a4a_ok = False
                elif float(mk_val) < 50.0:
                    fails.append(f"FAIL_GATE_A4A_COUPON_EFFICACY_BELOW_50PCT:{mk_nm}"); a4a_ok = False
            if float(v14_4a) < 90.0 or float(v14_4a) > 100.0:
                fails.append("FAIL_GATE_A4A_DAY14_VIABILITY_BELOW_90PCT"); a4a_ok = False
            if float(o2_4a) < 40.0:
                fails.append("FAIL_GATE_A4A_WORST_FACE_O2_BELOW_40MMHG"); a4a_ok = False
            dp_recs = a4a_ev.get("donor_pair_records")
            dp_allowed = frozenset({
                "donor_pair_id", "day7_col1a1_reduction_pct", "day7_alpha_sma_reduction_pct",
                "day14_col1a1_reduction_pct", "day14_alpha_sma_reduction_pct",
                "day14_viability_pct", "worst_face_o2_mmhg",
            })
            if not isinstance(dp_recs, list) or len(dp_recs) < 3:
                fails.append("FAIL_GATE_A4A_REQUIRES_AT_LEAST_3_DONOR_PAIRS"); a4a_ok = False
            else:
                seen_dp: set[str] = set()
                dp_cols = {"d7c": [], "d7s": [], "d14c": [], "d14s": [], "v14": [], "o2": []}
                dp_valid = True
                for idx_d, dpr in enumerate(dp_recs):
                    if not isinstance(dpr, Mapping) or set(dpr.keys()) != dp_allowed:
                        fails.append(f"FAIL_GATE_A4A_MALFORMED_DONOR_PAIR:{idx_d}"); dp_valid = False; a4a_ok = False; continue
                    dpid = str(dpr.get("donor_pair_id", "")).strip().upper()
                    if not dpid or dpid in seen_dp:
                        fails.append("FAIL_GATE_A4A_DUPLICATE_OR_EMPTY_DONOR_PAIR_ID"); dp_valid = False; a4a_ok = False; continue
                    seen_dp.add(dpid)
                    vals_dp = [dpr[k] for k in ("day7_col1a1_reduction_pct", "day7_alpha_sma_reduction_pct", "day14_col1a1_reduction_pct", "day14_alpha_sma_reduction_pct", "day14_viability_pct", "worst_face_o2_mmhg")]
                    if not all(is_finite_num(x) for x in vals_dp):
                        fails.append(f"FAIL_GATE_A4A_INVALID_DONOR_PAIR_METRICS:{dpid}"); dp_valid = False; a4a_ok = False; continue
                    f_d7c, f_d7s, f_d14c, f_d14s, f_v14, f_o2 = [float(x) for x in vals_dp]
                    if not (0.0 <= f_d7c <= 100.0 and 0.0 <= f_d7s <= 100.0 and 0.0 <= f_d14c <= 100.0 and 0.0 <= f_d14s <= 100.0 and 90.0 <= f_v14 <= 100.0 and f_o2 >= 40.0):
                        fails.append(f"FAIL_GATE_A4A_DONOR_PAIR_BELOW_SAFETY_FLOOR:{dpid}"); dp_valid = False; a4a_ok = False
                    dp_cols["d7c"].append(f_d7c); dp_cols["d7s"].append(f_d7s)
                    dp_cols["d14c"].append(f_d14c); dp_cols["d14s"].append(f_d14s)
                    dp_cols["v14"].append(f_v14); dp_cols["o2"].append(f_o2)
                if dp_valid and len(dp_cols["d7c"]) >= 3:
                    for key_m, decl_m in (("d7c", d7_c), ("d7s", d7_s), ("d14c", d14_c), ("d14s", d14_s), ("v14", v14_4a), ("o2", o2_4a)):
                        m_calc = sum(dp_cols[key_m]) / len(dp_cols[key_m])
                        if abs(float(decl_m) - m_calc) > 0.5:
                            fails.append(f"FAIL_GATE_A4A_SUMMARY_MISMATCH_VS_DONOR_PAIRS:{key_m}"); a4a_ok = False
                    for key_m in ("d7c", "d7s", "d14c", "d14s"):
                        if (sum(dp_cols[key_m]) / len(dp_cols[key_m])) < 50.0:
                            fails.append(f"FAIL_GATE_A4A_RECOMPUTED_DONOR_PAIR_MEAN_BELOW_50PCT:{key_m}"); a4a_ok = False

    # Pre-enrollment A-4b Preregistration Receipt (independently timed BEFORE animal_work_started_at_utc, locking roster & endpoint!)
    a4b_prereg_ev = None
    if rec.get("a4b_evidence") is not None or rec.get("a4b_preregistration_receipt") is not None:
        a4b_prereg_ev = _validate_content_receipt(
            rec.get("a4b_preregistration_receipt"),
            expected_stage="A-4b-PREREGISTRATION", expected_prod=prod_s, expected_bank=bank_s,
            expected_lot=lot_s, expected_route=route_s, expected_scope="exact_product",
            expected_coating_identity=coat_id,
            expected_parent=a4a_ev,
            allowed_extra_keys=frozenset({
                "early_assay_mode", "primary_collagen_endpoint",
                "randomized_animal_roster", "early_cohort_assigned_ids", "day28_cohort_assigned_ids",
                "max_attrition_rate_pct", "max_arm_attrition_diff_pp",
                "exclusion_timing_cutoff_rule", "missing_data_sensitivity_rule",
                "perfusion_normalization_scale",
                "tipping_point_collagen_bounds_um", "tipping_point_perfusion_bounds_pct",
            }),
            fails=fails, holds=holds,
            missing_hold="HOLD_GATE_A4B_PREREGISTRATION_RECEIPT_MISSING",
            fail_code="FAIL_GATE_A4B_PREREGISTRATION_FAILED",
            mismatch_code="FAIL_GATE_A4B_PREREGISTRATION_SCOPE_MISMATCH",
        )

    # Gate A-4b: pre-enrollment locked roster + 100% animal accounting + pericapsular collagen thickness (IIP_DRAFT_A:138-140) + per-animal implant/Day-28 window!
    a4b_extras = frozenset({
        "animal_work_started_at_utc", "histology_unblinding_utc",
        "early_assay_mode", "blinded_allocation", "implant_extrusions",
        "early_cohort_enrolled_coated_n", "early_cohort_enrolled_vehicle_n", "early_cohort_exclusions", "early_cohort_records",
        "day28_cohort_enrolled_coated_n", "day28_cohort_enrolled_vehicle_n", "day28_cohort_exclusions", "day28_cohort_records",
    })
    a4b_prereqs = [("BANK_MATERIALIZATION", mat_ev), ("NATIVE_SAFETY_SWITCH", sw_ev), ("GATE-0V-KILL", g0v_ev)]
    if a4b_prereg_ev is not None:
        a4b_prereqs.append(("A-4b-PREREGISTRATION", a4b_prereg_ev))
    a4b_ev = _validate_content_receipt(
        rec.get("a4b_evidence"),
        expected_stage="A-4b", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="exact_product",
        expected_coating_identity=coat_id,
        expected_parent=a4a_ev,
        min_prereq_receipts=a4b_prereqs,
        allowed_extra_keys=a4b_extras, fails=fails, holds=holds,
        missing_hold="HOLD_GATE_A4B_RODENT_NOT_YET_COMPLETED",
        fail_code="FAIL_GATE_A4B_RODENT_FAILED",
        mismatch_code="FAIL_GATE_A4B_SCOPE_MISMATCH",
    )
    if a4b_ev is not None:
        if not (a0a_ok and a0b_ok and a1_bench_ok and a1_ok and a2_ok and a3_ok and a4a_ok):
            fails.append("FAIL_GATE_A4B_ATTEMPTED_WITHOUT_ALL_PREDECESSORS")
        t_start = parse_utc_iso_ts(a4b_ev.get("animal_work_started_at_utc"))
        t_unblind = parse_utc_iso_ts(a4b_ev.get("histology_unblinding_utc"))
        t_end = parse_utc_iso_ts(a4b_ev.get("recorded_at_utc"))
        t_a4a = parse_utc_iso_ts(a4a_ev.get("recorded_at_utc")) if a4a_ev is not None else None
        t_prereg = parse_utc_iso_ts(a4b_prereg_ev.get("recorded_at_utc")) if a4b_prereg_ev is not None else None
        if t_start is None:
            fails.append("FAIL_GATE_A4B_MISSING_OR_INVALID_ANIMAL_WORK_START_UTC")
        else:
            if t_a4a is not None and t_start < t_a4a:
                fails.append("FAIL_GATE_A4B_ANIMAL_WORK_STARTED_BEFORE_A4A_AUTHORIZATION")
            if t_prereg is not None and t_prereg > t_start:
                fails.append("FAIL_GATE_A4B_PREREGISTRATION_POSTDATES_ANIMAL_WORK_START")
            if t_end is not None and t_end < t_start:
                fails.append("FAIL_GATE_A4B_RECORDED_BEFORE_ANIMAL_WORK_START")
            elif t_end is not None and (t_end - t_start) < timedelta(days=28):
                fails.append("FAIL_GATE_A4B_ELAPSED_STUDY_DURATION_LT_28_DAYS")
        if t_unblind is None or (t_start is not None and t_unblind < t_start) or (t_end is not None and t_unblind > t_end):
            fails.append("FAIL_GATE_A4B_MISSING_OR_INVALID_HISTOLOGY_UNBLINDING_UTC")
        emode = a4b_ev.get("early_assay_mode")
        if emode not in ("TERMINAL_HISTOLOGY", "VALIDATED_NONTERMINAL_LONGITUDINAL_IMAGING"):
            fails.append("FAIL_GATE_A4B_UNDECLARED_EARLY_ASSAY_MODE")
        if not (is_strict_bool(a4b_ev.get("blinded_allocation")) and a4b_ev["blinded_allocation"]):
            fails.append("FAIL_GATE_A4B_BLINDED_ALLOCATION_REQUIRED")
        a4b_allowed_ae_codes = frozenset({
            "NONE", "MINOR_LOCAL_EDEMA", "SEROMA", "LOCAL_ERYTHEMA", "INFECTION",
            "HEMORRHAGE", "NECROSIS", "IMPLANT_EXTRUSION", "DEVICE_RUPTURE", "UNRELATED_HUSBANDRY",
        })
        recomp_extrusion_rows = 0
        recomp_rupture_rows = 0
        extr = a4b_ev.get("implant_extrusions")
        if not is_strict_int(extr) or int(extr) != 0:
            fails.append("FAIL_GATE_A4B_IMPLANT_EXTRUSION_DETECTED")

        # Parse pre-enrollment preregistered roster, missing-data rule, & assigned cohort IDs
        roster_map: dict[str, str] = {}
        prereg_early_set: set[str] = set()
        prereg_d28_set: set[str] = set()
        prereg_max_attr_pct: float = 20.0
        prereg_max_diff_pp: float = 10.0
        tp_col_min_um: float = 20.0
        tp_col_max_um: float = 1500.0
        tp_perf_min_pct: float = 0.0
        tp_perf_max_pct: float = 200.0
        if a4b_prereg_ev is not None:
            if a4b_prereg_ev.get("early_assay_mode") != emode:
                fails.append("FAIL_GATE_A4B_PREREG_ASSAY_MODE_MISMATCH")
            if a4b_prereg_ev.get("primary_collagen_endpoint") != "PERICAPSULAR_COLLAGEN_THICKNESS_UM":
                fails.append("FAIL_GATE_A4B_PREREG_PRIMARY_ENDPOINT_NOT_PERICAPSULAR_COLLAGEN_THICKNESS_UM")
            if a4b_prereg_ev.get("perfusion_normalization_scale") != "VEHICLE_CONTROL_MEAN_PCT":
                fails.append("FAIL_GATE_A4B_PREREG_MISSING_PERFUSION_NORMALIZATION_SCALE")
            ma_pct = a4b_prereg_ev.get("max_attrition_rate_pct")
            md_pp = a4b_prereg_ev.get("max_arm_attrition_diff_pp")
            c_bnds = a4b_prereg_ev.get("tipping_point_collagen_bounds_um")
            p_bnds = a4b_prereg_ev.get("tipping_point_perfusion_bounds_pct")
            bnds_ok = (
                isinstance(c_bnds, list) and len(c_bnds) == 2 and all(is_finite_num(x) for x in c_bnds)
                and 0.0 < float(c_bnds[0]) <= 50.0 and float(c_bnds[1]) >= 1000.0
                and isinstance(p_bnds, list) and len(p_bnds) == 2 and all(is_finite_num(x) for x in p_bnds)
                and abs(float(p_bnds[0])) <= 1e-12 and float(p_bnds[1]) >= 200.0
            )
            if not (
                is_finite_num(ma_pct) and 0.0 <= float(ma_pct) <= 20.0
                and is_finite_num(md_pp) and 0.0 <= float(md_pp) <= 10.0
                and a4b_prereg_ev.get("exclusion_timing_cutoff_rule") == "LOCKED_BEFORE_HISTOLOGY_UNBLINDING"
                and a4b_prereg_ev.get("missing_data_sensitivity_rule") == "WORST_CASE_TIPPING_POINT_BOUND"
                and bnds_ok
            ):
                fails.append("FAIL_GATE_A4B_PREREG_MISSING_LOCKED_MISSING_DATA_RULE")
            else:
                prereg_max_attr_pct = float(ma_pct)
                prereg_max_diff_pp = float(md_pp)
                tp_col_min_um, tp_col_max_um = float(c_bnds[0]), float(c_bnds[1])
                tp_perf_min_pct, tp_perf_max_pct = float(p_bnds[0]), float(p_bnds[1])
            raw_r = a4b_prereg_ev.get("randomized_animal_roster")
            raw_pe = a4b_prereg_ev.get("early_cohort_assigned_ids")
            raw_pd = a4b_prereg_ev.get("day28_cohort_assigned_ids")
            if not (isinstance(raw_r, Mapping) and len(raw_r) >= 16 and isinstance(raw_pe, list) and isinstance(raw_pd, list)):
                fails.append("FAIL_GATE_A4B_PREREG_MISSING_ROSTER_OR_COHORT_ASSIGNMENTS")
            else:
                for rk, rv in raw_r.items():
                    if not is_nonempty_str(rk) or rv not in ("COATED", "BLANK_VEHICLE"):
                        fails.append("FAIL_GATE_A4B_PREREG_MALFORMED_ROSTER"); break
                    rn = str(rk).strip().upper()
                    if rn in roster_map:
                        fails.append("FAIL_GATE_A4B_PREREG_DUPLICATE_ROSTER_ID"); break
                    roster_map[rn] = str(rv)
                prereg_early_set = {str(x).strip().upper() for x in raw_pe if is_nonempty_str(x)}
                prereg_d28_set = {str(x).strip().upper() for x in raw_pd if is_nonempty_str(x)}
                if len(prereg_early_set) != len(raw_pe) or len(prereg_d28_set) != len(raw_pd):
                    fails.append("FAIL_GATE_A4B_PREREG_DUPLICATE_ASSIGNED_COHORT_IDS")
                if not (prereg_early_set <= set(roster_map.keys()) and prereg_d28_set <= set(roster_map.keys())):
                    fails.append("FAIL_GATE_A4B_PREREG_ASSIGNED_ID_NOT_IN_ROSTER")
                if (prereg_early_set | prereg_d28_set) != set(roster_map.keys()):
                    fails.append("FAIL_GATE_A4B_PREREG_UNASSIGNED_ROSTER_ANIMALS")
                if emode == "TERMINAL_HISTOLOGY" and (prereg_early_set & prereg_d28_set):
                    fails.append("FAIL_GATE_A4B_TERMINAL_PREREG_COHORTS_NOT_DISJOINT")
                elif emode == "VALIDATED_NONTERMINAL_LONGITUDINAL_IMAGING" and prereg_early_set != prereg_d28_set:
                    fails.append("FAIL_GATE_A4B_LONGITUDINAL_PREREG_COHORTS_MUST_MATCH")

        early_ids: set[str] = set()
        day28_ids: set[str] = set()
        early_exc_ids: set[str] = set()
        day28_exc_ids: set[str] = set()
        early_arm_by_id: dict[str, str] = {}
        day28_arm_by_id: dict[str, str] = {}
        early_imp_by_id: dict[str, datetime] = {}
        early_assess_by_id: dict[str, datetime] = {}
        day28_imp_by_id: dict[str, datetime] = {}
        day28_assess_by_id: dict[str, datetime] = {}

        # Early 36-72h cohort (per-animal implanted_at_utc -> assessed_at_utc in [36 h, 72 h])
        e_enr_c = a4b_ev.get("early_cohort_enrolled_coated_n")
        e_enr_v = a4b_ev.get("early_cohort_enrolled_vehicle_n")
        e_excl = a4b_ev.get("early_cohort_exclusions")
        e_recs = a4b_ev.get("early_cohort_records")
        if not (is_strict_int(e_enr_c) and is_strict_int(e_enr_v) and int(e_enr_c) >= 8 and int(e_enr_v) >= 8 and isinstance(e_recs, list)):
            fails.append("FAIL_GATE_A4B_EARLY_COHORT_UNDERPOWERED_OR_MALFORMED")
        else:
            e_coat_v: list[float] = []
            e_veh_v: list[float] = []
            e_allowed = frozenset({"animal_id", "arm", "implanted_at_utc", "assessed_at_utc", "raw_lectin_perfusion_signal", "adverse_event_code"})
            for idx, r in enumerate(e_recs):
                if not isinstance(r, Mapping):
                    fails.append(f"FAIL_GATE_A4B_EARLY_MALFORMED_ROW:{idx}"); continue
                _check_allowed_keys(r, e_allowed, fails, f"GATE_A4B_EARLY_{idx}")
                if not is_nonempty_str(r.get("animal_id")):
                    fails.append("FAIL_GATE_A4B_EARLY_DUPLICATE_OR_EMPTY_ANIMAL_ID"); continue
                aid_n = str(r["animal_id"]).strip().upper()
                if aid_n in early_ids:
                    fails.append("FAIL_GATE_A4B_EARLY_DUPLICATE_OR_EMPTY_ANIMAL_ID"); continue
                early_ids.add(aid_n)
                arm = r.get("arm")
                sig = r.get("raw_lectin_perfusion_signal")
                ts_imp = parse_utc_iso_ts(r.get("implanted_at_utc"))
                ts_a = parse_utc_iso_ts(r.get("assessed_at_utc"))
                ae_c_e = r.get("adverse_event_code")
                if not is_nonempty_str(ae_c_e):
                    fails.append(f"FAIL_GATE_A4B_EARLY_MISSING_AE_CODE:{aid_n}")
                else:
                    ae_u_e = str(ae_c_e).strip().upper()
                    if ae_u_e not in a4b_allowed_ae_codes:
                        fails.append(f"FAIL_GATE_A4B_UNRECOGNIZED_ADVERSE_EVENT_CODE:{aid_n}")
                    elif ae_u_e == "IMPLANT_EXTRUSION":
                        recomp_extrusion_rows += 1
                    elif ae_u_e == "DEVICE_RUPTURE":
                        recomp_rupture_rows += 1
                if arm not in ("COATED", "BLANK_VEHICLE") or not (is_finite_num(sig) and float(sig) > 0.0):
                    fails.append(f"FAIL_GATE_A4B_EARLY_INVALID_ARM_OR_SIGNAL:{aid_n}"); continue
                if ts_imp is None or ts_a is None or t_start is None or ts_imp < t_start or not (36.0 <= (ts_a - ts_imp).total_seconds() / 3600.0 <= 72.0) or (t_end is not None and ts_a > t_end):
                    fails.append(f"FAIL_GATE_A4B_EARLY_PERFUSION_OUTSIDE_36_72H:{aid_n}")
                early_arm_by_id[aid_n] = str(arm)
                if ts_imp is not None and ts_a is not None:
                    early_imp_by_id[aid_n] = ts_imp
                    early_assess_by_id[aid_n] = ts_a
                if arm == "COATED":
                    e_coat_v.append(float(sig))
                else:
                    e_veh_v.append(float(sig))
            exp_e_exc = (int(e_enr_c) - len(e_coat_v)) + (int(e_enr_v) - len(e_veh_v))
            if len(e_coat_v) < 8 or len(e_veh_v) < 8 or exp_e_exc < 0:
                fails.append("FAIL_GATE_A4B_EARLY_COHORT_ARM_DENOMINATOR_MISMATCH")
            else:
                _validate_structured_exclusions(
                    e_excl, expected_n=exp_e_exc, analyzed_ids_norm=early_ids, id_key="animal_id",
                    fails=fails, prefix="GATE_A4B_EARLY", require_arm=True,
                    require_timing_and_ae=True, forbid_adverse_event_related=True,
                    min_ts=t_start, max_ts=(t_unblind if t_unblind is not None else t_end),
                )
                exc_e_c = 0
                exc_e_v = 0
                if isinstance(e_excl, list):
                    for x in e_excl:
                        if isinstance(x, Mapping) and is_nonempty_str(x.get("animal_id")):
                            early_exc_ids.add(str(x["animal_id"]).strip().upper())
                    exc_e_c = sum(1 for x in e_excl if isinstance(x, Mapping) and x.get("arm") == "COATED")
                    exc_e_v = sum(1 for x in e_excl if isinstance(x, Mapping) and x.get("arm") == "BLANK_VEHICLE")
                    if len(e_coat_v) + exc_e_c != int(e_enr_c) or len(e_veh_v) + exc_e_v != int(e_enr_v):
                        fails.append("FAIL_GATE_A4B_EARLY_ARM_SPECIFIC_EXCLUSION_MISMATCH")
                if abs((sum(e_veh_v) / len(e_veh_v)) - 100.0) > 15.0:
                    fails.append("FAIL_GATE_A4B_EARLY_PERFUSION_SCALE_NOT_CONTROL_NORMALIZED")
                fl_e = fieller_ratio_one_sided_lower(e_coat_v, e_veh_v, paired=False, alpha=0.05)
                if fl_e is None or fl_e[0] < 1.00 or fl_e[1] < 0.90:
                    fails.append("FAIL_GATE_A4B_EARLY_36_72H_LECTIN_PERFUSION_FAILED")
                if exp_e_exc > 0:
                    e_tot_enr = int(e_enr_c) + int(e_enr_v)
                    e_attr_pct = 100.0 * exp_e_exc / e_tot_enr
                    e_diff_pp = abs((100.0 * exc_e_c / int(e_enr_c)) - (100.0 * exc_e_v / int(e_enr_v)))
                    if e_attr_pct > prereg_max_attr_pct + 1e-9 or e_diff_pp > prereg_max_diff_pp + 1e-9:
                        holds.append("HOLD_GATE_A4B_EARLY_EXCESSIVE_OR_DIFFERENTIAL_ATTRITION")
                    # Executable worst-case tipping-point sensitivity bound over PREREGISTERED physical outcome bounds!
                    e_worst = min(tp_perf_min_pct, min(e_coat_v + e_veh_v))
                    e_best = max(tp_perf_max_pct, max(e_coat_v + e_veh_v))
                    fl_e_sens = fieller_ratio_one_sided_lower(
                        e_coat_v + [e_worst] * exc_e_c, e_veh_v + [e_best] * exc_e_v, paired=False, alpha=0.05
                    )
                    if fl_e_sens is None or fl_e_sens[0] < 1.00 or fl_e_sens[1] < 0.90:
                        holds.append("HOLD_GATE_A4B_EARLY_INFORMATIVE_ATTRITION_SENSITIVITY_NOT_ROBUST")

        # Day-28 terminal cohort (explicit pericapsular_collagen_thickness_um per IIP_DRAFT_A:138-140 + [27d, 29d] window vs animal implant!)
        d_enr_c = a4b_ev.get("day28_cohort_enrolled_coated_n")
        d_enr_v = a4b_ev.get("day28_cohort_enrolled_vehicle_n")
        d_excl = a4b_ev.get("day28_cohort_exclusions")
        d_recs = a4b_ev.get("day28_cohort_records")
        if not (is_strict_int(d_enr_c) and is_strict_int(d_enr_v) and int(d_enr_c) >= 8 and int(d_enr_v) >= 8 and isinstance(d_recs, list)):
            fails.append("FAIL_GATE_A4B_DAY28_COHORT_UNDERPOWERED_OR_MALFORMED")
        else:
            d_col_c: list[float] = []
            d_col_v: list[float] = []
            d_lec_c: list[float] = []
            d_lec_v: list[float] = []
            d_allowed = frozenset({"animal_id", "arm", "implanted_at_utc", "assessed_at_utc", "pericapsular_collagen_thickness_um", "raw_lectin_vessel_density", "adverse_event_code"})
            for idx, r in enumerate(d_recs):
                if not isinstance(r, Mapping):
                    fails.append(f"FAIL_GATE_A4B_DAY28_MALFORMED_ROW:{idx}"); continue
                _check_allowed_keys(r, d_allowed, fails, f"GATE_A4B_D28_{idx}")
                if not is_nonempty_str(r.get("animal_id")):
                    fails.append("FAIL_GATE_A4B_DAY28_DUPLICATE_OR_EMPTY_ANIMAL_ID"); continue
                aid_n = str(r["animal_id"]).strip().upper()
                if aid_n in day28_ids:
                    fails.append("FAIL_GATE_A4B_DAY28_DUPLICATE_OR_EMPTY_ANIMAL_ID"); continue
                day28_ids.add(aid_n)
                arm = r.get("arm")
                col_s = r.get("pericapsular_collagen_thickness_um")
                lec_s = r.get("raw_lectin_vessel_density")
                ts_imp = parse_utc_iso_ts(r.get("implanted_at_utc"))
                ts_d = parse_utc_iso_ts(r.get("assessed_at_utc"))
                ae_c_d = r.get("adverse_event_code")
                if not is_nonempty_str(ae_c_d):
                    fails.append(f"FAIL_GATE_A4B_DAY28_MISSING_AE_CODE:{aid_n}")
                else:
                    ae_u_d = str(ae_c_d).strip().upper()
                    if ae_u_d not in a4b_allowed_ae_codes:
                        fails.append(f"FAIL_GATE_A4B_UNRECOGNIZED_ADVERSE_EVENT_CODE:{aid_n}")
                    elif ae_u_d == "IMPLANT_EXTRUSION":
                        recomp_extrusion_rows += 1
                    elif ae_u_d == "DEVICE_RUPTURE":
                        recomp_rupture_rows += 1
                if arm not in ("COATED", "BLANK_VEHICLE") or not (is_finite_num(col_s) and float(col_s) > 0.0 and is_finite_num(lec_s) and float(lec_s) > 0.0):
                    fails.append(f"FAIL_GATE_A4B_DAY28_INVALID_ARM_OR_SIGNAL:{aid_n}"); continue
                if ts_imp is None or ts_d is None or t_start is None or ts_imp < t_start or not (timedelta(days=27) <= (ts_d - ts_imp) <= timedelta(days=29)) or (t_end is not None and ts_d > t_end):
                    fails.append(f"FAIL_GATE_A4B_DAY28_PERFUSION_TIMESTAMP_INVALID:{aid_n}")
                day28_arm_by_id[aid_n] = str(arm)
                if ts_imp is not None and ts_d is not None:
                    day28_imp_by_id[aid_n] = ts_imp
                    day28_assess_by_id[aid_n] = ts_d
                if arm == "COATED":
                    d_col_c.append(float(col_s)); d_lec_c.append(float(lec_s))
                else:
                    d_col_v.append(float(col_s)); d_lec_v.append(float(lec_s))
            exp_d_exc = (int(d_enr_c) - len(d_col_c)) + (int(d_enr_v) - len(d_col_v))
            if len(d_col_c) < 8 or len(d_col_v) < 8 or exp_d_exc < 0:
                fails.append("FAIL_GATE_A4B_DAY28_COHORT_ARM_DENOMINATOR_MISMATCH")
            else:
                if t_unblind is not None:
                    all_assess = list(early_assess_by_id.values()) + list(day28_assess_by_id.values())
                    if all_assess and max(all_assess) > t_unblind:
                        fails.append("FAIL_GATE_A4B_HISTOLOGY_UNBLINDED_BEFORE_ASSESSMENTS_COMPLETE")
                _validate_structured_exclusions(
                    d_excl, expected_n=exp_d_exc, analyzed_ids_norm=day28_ids, id_key="animal_id",
                    fails=fails, prefix="GATE_A4B_DAY28", require_arm=True,
                    require_timing_and_ae=True, forbid_adverse_event_related=True,
                    min_ts=t_start, max_ts=(t_unblind if t_unblind is not None else t_end),
                )
                exc_c = 0
                exc_v = 0
                if isinstance(d_excl, list):
                    for x in d_excl:
                        if isinstance(x, Mapping) and is_nonempty_str(x.get("animal_id")):
                            day28_exc_ids.add(str(x["animal_id"]).strip().upper())
                    exc_c = sum(1 for x in d_excl if isinstance(x, Mapping) and x.get("arm") == "COATED")
                    exc_v = sum(1 for x in d_excl if isinstance(x, Mapping) and x.get("arm") == "BLANK_VEHICLE")
                    if len(d_col_c) + exc_c != int(d_enr_c) or len(d_col_v) + exc_v != int(d_enr_v):
                        fails.append("FAIL_GATE_A4B_DAY28_ARM_SPECIFIC_EXCLUSION_MISMATCH")
                # 100% animal accounting across measured + excluded vs preregistered roster (NO ghost animals, NO excluded cross-cohort reuse!)
                early_all = early_ids | early_exc_ids
                day28_all = day28_ids | day28_exc_ids
                if emode == "TERMINAL_HISTOLOGY" and (early_all & day28_all):
                    fails.append("FAIL_GATE_A4B_TERMINAL_EARLY_AND_DAY28_ANIMALS_NOT_DISJOINT")
                elif emode == "VALIDATED_NONTERMINAL_LONGITUDINAL_IMAGING":
                    for aid_shared in sorted(early_ids & day28_ids):
                        if early_arm_by_id.get(aid_shared) != day28_arm_by_id.get(aid_shared):
                            fails.append(f"FAIL_GATE_A4B_LONGITUDINAL_ANIMAL_ARM_REASSIGNMENT:{aid_shared}")
                        if early_imp_by_id.get(aid_shared) != day28_imp_by_id.get(aid_shared):
                            fails.append(f"FAIL_GATE_A4B_LONGITUDINAL_IMPLANT_EVENT_MISMATCH:{aid_shared}")
                        if early_assess_by_id.get(aid_shared) is not None and day28_assess_by_id.get(aid_shared) is not None and early_assess_by_id[aid_shared] >= day28_assess_by_id[aid_shared]:
                            fails.append(f"FAIL_GATE_A4B_LONGITUDINAL_ASSESSMENT_ORDER_INVALID:{aid_shared}")
                if roster_map:
                    if early_all != prereg_early_set:
                        fails.append("FAIL_GATE_A4B_EARLY_COHORT_UNACCOUNTED_OR_EXTRA_ROSTER_ANIMALS")
                    if day28_all != prereg_d28_set:
                        fails.append("FAIL_GATE_A4B_DAY28_COHORT_UNACCOUNTED_OR_EXTRA_ROSTER_ANIMALS")
                    for aid_chk, arm_chk in list(early_arm_by_id.items()) + list(day28_arm_by_id.items()):
                        if roster_map.get(aid_chk) != arm_chk:
                            fails.append(f"FAIL_GATE_A4B_ROSTER_ARM_MISMATCH:{aid_chk}")
                    for ex_list in (e_excl, d_excl):
                        if isinstance(ex_list, list):
                            for exr in ex_list:
                                if isinstance(exr, Mapping) and is_nonempty_str(exr.get("animal_id")):
                                    ex_id = str(exr["animal_id"]).strip().upper()
                                    if roster_map.get(ex_id) != exr.get("arm"):
                                        fails.append(f"FAIL_GATE_A4B_EXCLUSION_ROSTER_ARM_MISMATCH:{ex_id}")
                                    ex_ae = exr.get("adverse_event_code")
                                    if is_nonempty_str(ex_ae):
                                        ex_ae_u = str(ex_ae).strip().upper()
                                        if ex_ae_u not in a4b_allowed_ae_codes:
                                            fails.append(f"FAIL_GATE_A4B_UNRECOGNIZED_ADVERSE_EVENT_CODE:{ex_id}")
                                        elif ex_ae_u == "IMPLANT_EXTRUSION":
                                            recomp_extrusion_rows += 1
                                        elif ex_ae_u == "DEVICE_RUPTURE":
                                            recomp_rupture_rows += 1
                if recomp_extrusion_rows > 0:
                    if "FAIL_GATE_A4B_IMPLANT_EXTRUSION_DETECTED" not in fails:
                        fails.append("FAIL_GATE_A4B_IMPLANT_EXTRUSION_DETECTED")
                    if is_strict_int(extr) and int(extr) != recomp_extrusion_rows:
                        fails.append("FAIL_GATE_A4B_EXTRUSION_COUNT_MISMATCH_VS_ANIMAL_RECORDS")
                if recomp_rupture_rows > 0:
                    fails.append("FAIL_GATE_A4B_DEVICE_RUPTURE_DETECTED")
                # Raw vehicle minus coated pericapsular collagen thickness reduction >= 35% of vehicle mean + Welch p < 0.05 & L95 > 0!
                wt = two_sample_welch_summary(d_col_v, d_col_c)
                mean_v_col = sum(d_col_v) / len(d_col_v)
                mean_c_col = sum(d_col_c) / len(d_col_c)
                red_pct = 100.0 * (mean_v_col - mean_c_col) / mean_v_col
                if wt is None or red_pct < 35.0 or wt[2] >= 0.05 or wt[3] <= 0.0:
                    fails.append("FAIL_GATE_A4B_RECOMPUTED_COLLAGEN_EFFICACY_OR_PVALUE_FAILED")
                if abs((sum(d_lec_v) / len(d_lec_v)) - 100.0) > 15.0:
                    fails.append("FAIL_GATE_A4B_DAY28_VESSEL_DENSITY_SCALE_NOT_CONTROL_NORMALIZED")
                fl_d = fieller_ratio_one_sided_lower(d_lec_c, d_lec_v, paired=False, alpha=0.05)
                if fl_d is None or fl_d[0] < 1.00 or fl_d[1] < 0.90:
                    fails.append("FAIL_GATE_A4B_DAY28_LECTIN_VESSEL_DENSITY_FAILED")
                if exp_d_exc > 0:
                    d_tot_enr = int(d_enr_c) + int(d_enr_v)
                    d_attr_pct = 100.0 * exp_d_exc / d_tot_enr
                    d_diff_pp = abs((100.0 * exc_c / int(d_enr_c)) - (100.0 * exc_v / int(d_enr_v)))
                    if d_attr_pct > prereg_max_attr_pct + 1e-9 or d_diff_pp > prereg_max_diff_pp + 1e-9:
                        holds.append("HOLD_GATE_A4B_DAY28_EXCESSIVE_OR_DIFFERENTIAL_ATTRITION")
                    # Executable worst-case tipping-point sensitivity bound over PREREGISTERED physical outcome bounds!
                    col_worst = max(tp_col_max_um, max(d_col_c + d_col_v))
                    col_best = min(tp_col_min_um, min(d_col_c + d_col_v))
                    lec_worst = min(tp_perf_min_pct, min(d_lec_c + d_lec_v))
                    lec_best = max(tp_perf_max_pct, max(d_lec_c + d_lec_v))
                    d_col_c_s = d_col_c + [col_worst] * exc_c
                    d_col_v_s = d_col_v + [col_best] * exc_v
                    wt_s = two_sample_welch_summary(d_col_v_s, d_col_c_s)
                    mv_s = sum(d_col_v_s) / len(d_col_v_s)
                    mc_s = sum(d_col_c_s) / len(d_col_c_s)
                    red_s = 100.0 * (mv_s - mc_s) / mv_s
                    fl_d_s = fieller_ratio_one_sided_lower(
                        d_lec_c + [lec_worst] * exc_c, d_lec_v + [lec_best] * exc_v, paired=False, alpha=0.05
                    )
                    if (
                        wt_s is None or red_s < 35.0 or wt_s[2] >= 0.05 or wt_s[3] <= 0.0
                        or fl_d_s is None or fl_d_s[0] < 1.00 or fl_d_s[1] < 0.90
                    ):
                        holds.append("HOLD_GATE_A4B_DAY28_INFORMATIVE_ATTRITION_SENSITIVITY_NOT_ROBUST")

    if fails:
        verdict = "FAIL"
    elif holds:
        verdict = "HOLD"
    elif scope_track == "PRIMARY":
        verdict = OFFLINE_VERDICT_PRIMARY
    elif scope_track == "SENSITIVITY_Z_R3P":
        verdict = "SENSITIVITY_TRACK_ONLY_NON_PRIMARY"
    elif scope_track == "SEPARATE_ROUTE4_VEHICLE":
        verdict = "SEPARATE_ROUTE4_VEHICLE_TRACK_NON_PRIMARY"
    else:
        verdict = "DEFERRED_TRACK_QUALIFICATION_NON_PRIMARY"

    return {
        "gate": "GATE-40", "phase": phase, "scope_track": scope_track, "verdict": verdict,
        "release_authorizing": False, "live_ledger_authenticated": False,
        "upstream_archive_verification": OFFLINE_ARCHIVE_NOTE,
        "a0a_operative_limits_uM": {**a0a_op_payload, "all4_ceiling_fu_adjusted_uM": all4_ceiling_val},
        "product_id": rec.get("product_id"),
        "required_switch": spec["required_switch"] if spec else None,
        "failures": fails, "holds": holds,
    }


# ---------------------------------------------------------------------------
# GATE-41 (IIP-0063 / DEC-144): Optional Non-Design-A 10-Day Deucravacitinib Coating
# ---------------------------------------------------------------------------

GATE41_B0A_KEYS: FrozenSet[str] = frozenset({"phase", "b0a_evidence"})
GATE41_BENCH_KEYS: FrozenSet[str] = GATE41_B0A_KEYS | frozenset({
    "track_mode", "credit_scope", "target_arm", "product_id", "bank_id", "lot_id", "route_id",
    "gate31_evidence", "route4_vehicle_evidence",
    "b0b_evidence", "b1_evidence", "b2_evidence", "b2b_bench_evidence",
})
GATE41_EXACT_ONLY_KEYS: FrozenSet[str] = frozenset({
    "materialization_evidence", "native_switch_evidence", "gate0v_evidence",
    "b0a_exact_evidence", "b2b_exact_evidence", "b3_evidence", "b4_evidence",
})
GATE41_EXACT_KEYS: FrozenSet[str] = GATE41_BENCH_KEYS | GATE41_EXACT_ONLY_KEYS


def _validate_and_apply_continuous_pk_envelope(
    env_raw: Any,
    *,
    hours_seen: Sequence[float],
    u_local_series: Sequence[float],
    l_parent_all_series: Sequence[float],
    u_sys_series: Sequence[float],
    max_efficacy_start_h: float,
    expected_coating_article_id: Optional[str] = None,
    expected_evidence_scope: Optional[str] = None,
    expected_compartment_id: Optional[str] = None,
    fails: list[str],
    holds: list[str],
    prefix: str,
) -> Optional[tuple[float, float, float]]:
    """
    Exact continuous inter-sample PK envelope (Lipschitz in log-concentration; conditional on bound rate caps):
      - Binds coating_article_id, evidence_scope (phase), compartment_id, envelope_qualification_method
        (DENSE_PILOT_TIMECOURSE_BOUND or PHYSICAL_DEPOT_MASS_BALANCE_UPPER_BOUND), and pilot_sampling_max_gap_h <= 2.0 h.
      - Enforces empirical inter-sample log-slope consistency against observed timepoints AND exact continuous peak/trough bounds.
    """
    env_allowed = {
        "k_elim_local_max_per_h", "k_rise_local_max_per_h",
        "k_elim_parent_max_per_h", "k_rise_parent_max_per_h",
        "k_elim_bmt_max_per_h", "k_rise_bmt_max_per_h",
        "k_elim_sys_max_per_h", "k_rise_sys_max_per_h",
        "efficacy_window_start_h", "envelope_model_sha256",
        "coating_article_id", "evidence_scope", "compartment_id",
        "envelope_qualification_method", "pilot_sampling_max_gap_h",
        "burst_phase_covered", "washout_phase_covered",
        "source_study_ids", "envelope_receipt_sha256",
    }
    if not isinstance(env_raw, Mapping) or set(env_raw.keys()) != env_allowed:
        fails.append(f"FAIL_{prefix}_MISSING_QUANTITATIVE_INTERSAMPLE_ENVELOPE"); return None
    ke_l = env_raw.get("k_elim_local_max_per_h")
    kr_l = env_raw.get("k_rise_local_max_per_h")
    ke_p = env_raw.get("k_elim_parent_max_per_h")
    kr_p = env_raw.get("k_rise_parent_max_per_h")
    ke_b = env_raw.get("k_elim_bmt_max_per_h")
    kr_b = env_raw.get("k_rise_bmt_max_per_h")
    ke_s = env_raw.get("k_elim_sys_max_per_h")
    kr_s = env_raw.get("k_rise_sys_max_per_h")
    t_eff0 = env_raw.get("efficacy_window_start_h")
    sha = env_raw.get("envelope_model_sha256")
    r_sha = env_raw.get("envelope_receipt_sha256")
    s_ids = env_raw.get("source_study_ids")
    e_art = env_raw.get("coating_article_id")
    e_scp = env_raw.get("evidence_scope")
    e_cmp = env_raw.get("compartment_id")
    e_mth = env_raw.get("envelope_qualification_method")
    e_gap = env_raw.get("pilot_sampling_max_gap_h")
    scope_bind_ok = (
        is_nonempty_str(e_art)
        and (expected_coating_article_id is None or e_art == expected_coating_article_id)
        and e_scp in ("bench_unedited", "exact_product")
        and (expected_evidence_scope is None or e_scp == expected_evidence_scope)
        and e_cmp in ("BENCH_ELUTION_RECIRCULATION", "INVIVO_PERIGRAFT_AND_SYSTEMIC")
        and (expected_compartment_id is None or e_cmp == expected_compartment_id)
        and e_mth in ("DENSE_PILOT_TIMECOURSE_BOUND", "PHYSICAL_DEPOT_MASS_BALANCE_UPPER_BOUND")
        and is_finite_num(e_gap) and 0.0 < float(e_gap) <= 2.0
    )
    if not scope_bind_ok:
        fails.append(f"FAIL_{prefix}_ENVELOPE_ARTICLE_PHASE_OR_COMPARTMENT_MISMATCH"); return None
    if not (
        is_finite_num(ke_l) and 0.0001 <= float(ke_l) <= 1.0
        and is_finite_num(kr_l) and 0.0001 <= float(kr_l) <= 1.0
        and is_finite_num(ke_p) and 0.0001 <= float(ke_p) <= 1.0
        and is_finite_num(kr_p) and 0.0001 <= float(kr_p) <= 1.0
        and is_finite_num(ke_b) and 0.0001 <= float(ke_b) <= 1.0
        and is_finite_num(kr_b) and 0.0001 <= float(kr_b) <= 1.0
        and is_finite_num(ke_s) and 0.0001 <= float(ke_s) <= 1.0
        and is_finite_num(kr_s) and 0.0001 <= float(kr_s) <= 1.0
        and is_finite_num(t_eff0) and 0.0 <= float(t_eff0) <= max_efficacy_start_h + 1e-9
        and is_valid_sha256_hex(sha)
        and is_strict_bool(env_raw.get("burst_phase_covered")) and env_raw["burst_phase_covered"]
        and is_strict_bool(env_raw.get("washout_phase_covered")) and env_raw["washout_phase_covered"]
        and isinstance(s_ids, list) and len(s_ids) >= 1 and all(is_nonempty_str(x) for x in s_ids)
        and is_valid_sha256_hex(r_sha)
        and sha256_bytes(canonical_json_bytes({k: v for k, v in env_raw.items() if k != "envelope_receipt_sha256"})) == str(r_sha)
    ):
        fails.append(f"FAIL_{prefix}_INVALID_INTERSAMPLE_ENVELOPE_PARAMS"); return None
    if not hours_seen or len(hours_seen) != len(u_local_series) or len(hours_seen) != len(u_sys_series) or len(hours_seen) != len(l_parent_all_series):
        return None
    kel, krl, kep, krp, kes, krs = float(ke_l), float(kr_l), float(ke_p), float(kr_p), float(ke_s), float(kr_s)
    t_start_eff = float(t_eff0)
    t_end_eff = 240.0

    def _seg_peak(u_prev: float, u_curr: float, dt: float, ke: float, kr: float) -> float:
        up = max(u_prev, 1e-12)
        uc = max(u_curr, 1e-12)
        return math.exp((ke * math.log(up) + kr * math.log(uc) + ke * kr * dt) / (ke + kr))

    def _seg_trough_on_subinterval(t1: float, l1: float, t2: float, l2: float, a: float, b: float, ke: float, kr: float) -> float:
        """Exact inf_{t in [a, b]} max(l1*exp(-ke*(t-t1)), l2*exp(-kr*(t2-t))) for t1 <= a <= b <= t2."""
        if l1 <= 0.0 and l2 <= 0.0:
            return 0.0
        if l1 <= 0.0:
            return l2 * math.exp(-kr * (t2 - a))
        if l2 <= 0.0:
            return l1 * math.exp(-ke * (b - t1))
        t_cross = (math.log(l1) - math.log(l2) + ke * t1 + kr * t2) / (ke + kr)
        t_star = max(a, min(b, t_cross))
        return max(l1 * math.exp(-ke * (t_star - t1)), l2 * math.exp(-kr * (t2 - t_star)))

    # Empirical inter-sample log-slope consistency: declared rate bounds CANNOT be slower than observed data slopes!
    slope_breach = False
    for i in range(1, len(hours_seen)):
        dt = hours_seen[i] - hours_seen[i - 1]
        if dt <= 0.0:
            continue
        if u_local_series[i - 1] > 0.0 and u_local_series[i] > 0.0:
            s_loc = math.log(u_local_series[i] / u_local_series[i - 1]) / dt
            if (-s_loc) > kel + 1e-6 or s_loc > krl + 1e-6:
                slope_breach = True
        if u_sys_series[i - 1] > 0.0 and u_sys_series[i] > 0.0:
            s_sys = math.log(u_sys_series[i] / u_sys_series[i - 1]) / dt
            if (-s_sys) > kes + 1e-6 or s_sys > krs + 1e-6:
                slope_breach = True
        if hours_seen[i] <= t_end_eff + 1e-9 and l_parent_all_series[i - 1] > 0.0 and l_parent_all_series[i] > 0.0:
            s_par = math.log(l_parent_all_series[i] / l_parent_all_series[i - 1]) / dt
            if (-s_par) > kep + 1e-6 or s_par > krp + 1e-6:
                slope_breach = True
    if slope_breach:
        fails.append(f"FAIL_{prefix}_ENVELOPE_RATE_CONTRADICTS_OBSERVED_SLOPE")

    # Continuous peaks across [0, t_0] AND every interior interval [t_{i-1}, t_i] over ALL 21 days!
    cont_pk_loc = u_local_series[0] * math.exp(kel * hours_seen[0])
    cont_pk_sys = u_sys_series[0] * math.exp(kes * hours_seen[0])
    for i in range(1, len(hours_seen)):
        dt = hours_seen[i] - hours_seen[i - 1]
        cont_pk_loc = max(cont_pk_loc, u_local_series[i], _seg_peak(u_local_series[i - 1], u_local_series[i], dt, kel, krl))
        cont_pk_sys = max(cont_pk_sys, u_sys_series[i], _seg_peak(u_sys_series[i - 1], u_sys_series[i], dt, kes, krs))

    # Full parent efficacy window [t_start_eff, 240.0 h] coverage check:
    # When efficacy starts at Day-0 first blood contact (max_efficacy_start_h == 0.0), require an early
    # initial sample (hours_seen[0] <= 2.0 h) so a late first sample cannot extrapolate backward ungrounded!
    if max_efficacy_start_h <= 1e-9 and hours_seen[0] > 2.0 + 1e-9:
        holds.append(f"HOLD_{prefix}_MISSING_EARLY_INITIAL_EXPOSURE_SAMPLE_FOR_T0_BOUNDARY")
        return cont_pk_loc, -1.0, cont_pk_sys
    if hours_seen[-1] < t_end_eff - 1e-9:
        holds.append(f"HOLD_{prefix}_PARENT_EFFICACY_WINDOW_UNCOVERED_THROUGH_240H")
        return cont_pk_loc, -1.0, cont_pk_sys

    trough_candidates: list[float] = []
    # Left head [t_start_eff, min(t_0, 240.0)] if first sample is strictly after t_start_eff
    if hours_seen[0] > t_start_eff + 1e-9:
        t0 = hours_seen[0]
        l0 = l_parent_all_series[0]
        trough_candidates.append(0.0 if l0 <= 0.0 else l0 * math.exp(-krp * (t0 - t_start_eff)))
    # Every observed sample inside [t_start_eff, 240.0]
    for h_i, l_i in zip(hours_seen, l_parent_all_series):
        if t_start_eff - 1e-9 <= h_i <= t_end_eff + 1e-9:
            trough_candidates.append(max(0.0, l_i))
    # Every interior segment [t_{i-1}, t_i] intersecting [t_start_eff, 240.0] (including right-straddle across 240.0 h!)
    for i in range(1, len(hours_seen)):
        t1, t2 = hours_seen[i - 1], hours_seen[i]
        a = max(t1, t_start_eff)
        b = min(t2, t_end_eff)
        if a <= b + 1e-9:
            trough_candidates.append(
                _seg_trough_on_subinterval(t1, l_parent_all_series[i - 1], t2, l_parent_all_series[i], a, max(a, b), kep, krp)
            )
    cont_tr_parent = min(trough_candidates) if trough_candidates else -1.0
    return cont_pk_loc, cont_tr_parent, cont_pk_sys


def _compute_continuous_bmt_parent_ratio_bounds(
    hours_seen: Sequence[float],
    u_bmt_free_series: Sequence[float],
    l_bmt_free_series: Sequence[float],
    l_parent_all_series: Sequence[float],
    u_parent_all_series: Sequence[float],
    env_raw: Any,
    *,
    fails: list[str],
    prefix: str,
) -> tuple[float, float, bool]:
    """
    Exact TWO-SIDED interval-wide continuous free BMT/parent ratio envelope [min_ratio, max_ratio]
    across [0, t_0] and every [t_{i-1}, t_i], using unified familywise Bonferroni concentration bounds:
      - Upper supremum: max_t B_upper(t) / P_lower(t) (concave piecewise-linear in log space -> exact max at {t1, t2, t_Bu, t_Pl})
      - Lower infimum:  min_t B_lower(t) / P_upper(t) (convex piecewise-linear in log space  -> exact min at {t1, t2, t_Bl, t_Pu})
    """
    n_h = len(hours_seen)
    if (
        not isinstance(env_raw, Mapping) or not hours_seen
        or any(len(s) != n_h for s in (u_bmt_free_series, l_bmt_free_series, l_parent_all_series, u_parent_all_series))
    ):
        return 0.0, 0.0, False
    ke_l, kr_l = env_raw.get("k_elim_local_max_per_h"), env_raw.get("k_rise_local_max_per_h")
    ke_p, kr_p = env_raw.get("k_elim_parent_max_per_h"), env_raw.get("k_rise_parent_max_per_h")
    ke_b, kr_b = env_raw.get("k_elim_bmt_max_per_h"), env_raw.get("k_rise_bmt_max_per_h")
    if not all(is_finite_num(x) and float(x) > 0.0 for x in (ke_l, kr_l, ke_p, kr_p, ke_b, kr_b)):
        return 0.0, 0.0, False
    kel, krl, kep, krp, keb, krb = float(ke_l), float(kr_l), float(ke_p), float(kr_p), float(ke_b), float(kr_b)

    # Verify empirical BMT log-slope consistency against dedicated metabolite-specific rate bounds (keb, krb)!
    bmt_slope_breach = False
    for i in range(1, n_h):
        dt = hours_seen[i] - hours_seen[i - 1]
        if dt > 0.0 and u_bmt_free_series[i - 1] > 0.0 and u_bmt_free_series[i] > 0.0:
            s_bmt = math.log(u_bmt_free_series[i] / u_bmt_free_series[i - 1]) / dt
            if (-s_bmt) > keb + 1e-6 or s_bmt > krb + 1e-6:
                bmt_slope_breach = True
    if bmt_slope_breach:
        fails.append(f"FAIL_{prefix}_ENVELOPE_RATE_CONTRADICTS_OBSERVED_BMT_SLOPE")

    min_ratio = float("inf")
    max_ratio = 0.0
    unbounded = False

    # Pre-first-sample interval [0, t_0] using dedicated BMT rates (keb, krb) & parent rates (kep, krp)!
    t0 = max(0.0, hours_seen[0])
    ub0, lb0 = u_bmt_free_series[0], l_bmt_free_series[0]
    lp0, up0 = l_parent_all_series[0], u_parent_all_series[0]
    if lp0 <= 0.0:
        if ub0 > 0.0:
            unbounded = True
    elif ub0 > 0.0:
        max_ratio = max(max_ratio, (ub0 / lp0) * math.exp((keb + krp) * t0))
    if lb0 <= 0.0:
        min_ratio = 0.0
    elif up0 > 0.0:
        min_ratio = min(min_ratio, (lb0 / up0) * math.exp(-(krb + max(kep, kel)) * t0))

    for i in range(1, n_h):
        t1, t2 = hours_seen[i - 1], hours_seen[i]
        ub1, ub2 = u_bmt_free_series[i - 1], u_bmt_free_series[i]
        lb1, lb2 = l_bmt_free_series[i - 1], l_bmt_free_series[i]
        lp1, lp2 = l_parent_all_series[i - 1], l_parent_all_series[i]
        up1, up2 = u_parent_all_series[i - 1], u_parent_all_series[i]
        dt = max(1e-12, t2 - t1)

        # Upper ratio envelope B_upper(t) / P_lower(t) governed strictly by metabolite-specific (keb, krb)!
        if lp1 <= 0.0 or lp2 <= 0.0:
            if ub1 > 0.0 or ub2 > 0.0:
                unbounded = True
        elif ub1 > 0.0 or ub2 > 0.0:
            ub1_p, ub2_p = max(ub1, 1e-12), max(ub2, 1e-12)
            obs_p_dec = max(0.0, math.log(lp1 / lp2) / dt)
            obs_p_ris = max(0.0, math.log(lp2 / lp1) / dt)
            kep_i = max(kep, kel if t2 > 240.0 + 1e-9 else 0.0, obs_p_dec)
            krp_i = max(krp, krl if t2 > 240.0 + 1e-9 else 0.0, obs_p_ris)
            t_bu = (math.log(ub2_p) - math.log(ub1_p) + krb * t1 + keb * t2) / (krb + keb)
            t_pl = (math.log(lp1) - math.log(lp2) + kep_i * t1 + krp_i * t2) / (kep_i + krp_i)
            for tc in (t1, t2, max(t1, min(t2, t_bu)), max(t1, min(t2, t_pl))):
                b_u = min(ub1_p * math.exp(krb * (tc - t1)), ub2_p * math.exp(keb * (t2 - tc)))
                p_l = max(lp1 * math.exp(-kep_i * (tc - t1)), lp2 * math.exp(-krp_i * (t2 - tc)))
                if p_l <= 0.0:
                    unbounded = True
                else:
                    max_ratio = max(max_ratio, b_u / p_l)

        # Lower ratio envelope B_lower(t) / P_upper(t) governed strictly by metabolite-specific (keb, krb)!
        if lb1 <= 0.0 or lb2 <= 0.0:
            min_ratio = 0.0
        elif up1 > 0.0 and up2 > 0.0:
            obs_b_dec = max(0.0, math.log(lb1 / lb2) / dt)
            obs_b_ris = max(0.0, math.log(lb2 / lb1) / dt)
            keb_i = max(keb, obs_b_dec)
            krb_i = max(krb, obs_b_ris)
            obs_pu_dec = max(0.0, math.log(up1 / up2) / dt)
            obs_pu_ris = max(0.0, math.log(up2 / up1) / dt)
            kep_u = max(kep, kel if t2 > 240.0 + 1e-9 else 0.0, obs_pu_dec)
            krp_u = max(krp, krl if t2 > 240.0 + 1e-9 else 0.0, obs_pu_ris)
            t_bl = (math.log(lb1) - math.log(lb2) + keb_i * t1 + krb_i * t2) / (keb_i + krb_i)
            t_pu = (math.log(up2) - math.log(up1) + krp_u * t1 + kep_u * t2) / (krp_u + kep_u)
            for tc in (t1, t2, max(t1, min(t2, t_bl)), max(t1, min(t2, t_pu))):
                b_l = max(lb1 * math.exp(-keb_i * (tc - t1)), lb2 * math.exp(-krb_i * (t2 - tc)))
                p_u = min(up1 * math.exp(krp_u * (tc - t1)), up2 * math.exp(kep_u * (t2 - tc)))
                if p_u > 0.0:
                    min_ratio = min(min_ratio, b_l / p_u)

    if min_ratio == float("inf"):
        min_ratio = 0.0
    return min_ratio, max_ratio, unbounded


def _validate_mixture_requal_receipt(
    mix_raw: Any,
    *,
    expected_prod: str,
    expected_bank: str,
    expected_lot: str,
    expected_route: str,
    expected_scope: str,
    expected_coating_identity: Optional[Mapping[str, str]],
    parent_recorded_at_utc: Optional[datetime],
    observed_bmt_to_parent_ratio_min: float,
    observed_bmt_to_parent_ratio_max: float,
    unbounded_ratio_under_parent_blq: bool = False,
    fails: list[str],
    holds: list[str],
    prefix: str,
) -> tuple[bool, Optional[float], Optional[float]]:
    """
    Validate phase-scoped content-hashed parent+BMT-153261 mixture requalification receipt:
      - Enforces matching scope ("bench_unedited" on B-2b-bench, "exact_product" on B-2b-exact / B-4)
      - Enforces tested_bmt_to_parent_ratio_min <= observed_free_ratio_min <= observed_free_ratio_max <= tested_bmt_to_parent_ratio_max
      - Returns (ok, mixture_ec50_eff_u95_free_nM, mixture_c_safe_max_l95_free_nM) so downstream exposure
        bounds are DIRECTLY adjudicated against the mixture-specific therapeutic window!
    """
    mix_ev = _validate_content_receipt(
        mix_raw,
        expected_stage="MIXTURE_REQUALIFICATION",
        expected_prod=expected_prod, expected_bank=expected_bank,
        expected_lot=expected_lot, expected_route=expected_route,
        expected_scope=expected_scope,
        expected_coating_identity=expected_coating_identity,
        allowed_extra_keys=frozenset({
            "analysis_record_sha256",
            "tested_bmt_to_parent_ratio_min", "tested_bmt_to_parent_ratio_max",
            "mixture_ec50_eff_u95_free_nM", "mixture_c_safe_max_l95_free_nM",
            "mixture_dose_response_evidence",
            "metabolite_dominant_unbounded_ratio_qualified",
            "bmt_alone_qualification_evidence",
        }),
        fails=fails, holds=holds,
        missing_hold=f"HOLD_{prefix}_METABOLITE_TRIGGERED_MIXTURE_REQUAL_REQUIRED",
        fail_code=f"FAIL_{prefix}_MIXTURE_REQUAL_RECEIPT_FAILED",
        mismatch_code=f"FAIL_{prefix}_MIXTURE_REQUAL_SCOPE_MISMATCH",
    )
    if mix_ev is None:
        return False, None, None
    t_m = parse_utc_iso_ts(mix_ev.get("recorded_at_utc"))
    if parent_recorded_at_utc is not None and t_m is not None and t_m > parent_recorded_at_utc:
        fails.append(f"FAIL_{prefix}_MIXTURE_REQUAL_POSTDATES_PARENT"); return False, None, None
    e50_m = mix_ev.get("mixture_ec50_eff_u95_free_nM")
    cs_m = mix_ev.get("mixture_c_safe_max_l95_free_nM")
    r_lo = mix_ev.get("tested_bmt_to_parent_ratio_min")
    r_hi = mix_ev.get("tested_bmt_to_parent_ratio_max")
    if not (
        is_valid_sha256_hex(mix_ev.get("analysis_record_sha256"))
        and is_finite_num(r_lo) and is_finite_num(r_hi) and 0.0 <= float(r_lo) <= float(r_hi) and float(r_hi) > 0.0
        and is_finite_num(e50_m) and float(e50_m) > 0.0
        and is_finite_num(cs_m) and float(cs_m) >= 2.0 * float(e50_m)
    ):
        fails.append(f"FAIL_{prefix}_MIXTURE_REQUAL_MARGIN_BELOW_2X_OR_INVALID"); return False, None, None
    mix_safe_specs = (
        ("sprouting_pct", 90.0),
        ("nkg2a_pct", 85.0),
        ("cd94_pct", 85.0),
        ("il10_retention_pct", 80.0),
    )
    mix_safe_keys = frozenset(k for k, _ in mix_safe_specs)
    mix_eff_keys = frozenset({
        "beta_cytokine_protection_pct",
        "nk_cytokine_suppression_pct",
        "iec_ibmir_marker_suppression_pct",
    })

    def _eval_7ep_panel_curve(
        grid_f: Sequence[float],
        s_rows: Any,
        e_rows: Any,
        *,
        c_safe_claim: float,
        ec50_claim: float,
        alpha_safe: float,
        alpha_eff: float,
    ) -> tuple[str, Optional[str]]:
        if not (
            isinstance(s_rows, list) and len(s_rows) == len(grid_f)
            and isinstance(e_rows, list) and len(e_rows) == len(grid_f)
            and all(isinstance(r, Mapping) and set(r.keys()) == mix_safe_keys for r in s_rows)
            and all(isinstance(r, Mapping) and set(r.keys()) == mix_eff_keys for r in e_rows)
        ):
            return "FAIL", "SCHEMA"
        for sr in s_rows:
            for sk in mix_safe_keys:
                arr = sr[sk]
                if not (isinstance(arr, list) and len(arr) >= 3 and all(is_finite_num(x) and 0.0 <= float(x) <= 150.0 for x in arr)):
                    return "FAIL", "SCHEMA"
        for er in e_rows:
            for ek in mix_eff_keys:
                arr = er[ek]
                if not (isinstance(arr, list) and len(arr) >= 3 and all(is_finite_num(x) and -20.0 <= float(x) <= 120.0 for x in arr)):
                    return "FAIL", "SCHEMA"

        prefix_ok = True
        safe_reached = False
        tox_above = False
        eff_at_ec50_ok = False
        zero_eff_ok = all((sum(float(x) for x in e_rows[0][ek]) / len(e_rows[0][ek])) < 20.0 for ek in mix_eff_keys)
        zero_disp = False

        idx_le_ec = [i for i, cv in enumerate(grid_f) if cv <= ec50_claim + 1e-9]
        target_ec_idx = idx_le_ec[-1] if idx_le_ec else -1

        for idx_g, (c_val, sr, er) in enumerate(zip(grid_f, s_rows, e_rows)):
            all_safe_pass = True
            any_safe_fail = False
            for sk, sfloor in mix_safe_specs:
                rf = [float(x) for x in sr[sk]]
                sb = sample_t_one_sided_bounds(rf, alpha=alpha_safe)
                if sb is None:
                    zero_disp = True
                    all_safe_pass = False
                else:
                    if sb[1] < sfloor:
                        all_safe_pass = False
                        any_safe_fail = True
            all_eff_pass = True
            for ek in mix_eff_keys:
                rf = [float(x) for x in er[ek]]
                eb = sample_t_one_sided_bounds(rf, alpha=alpha_eff)
                if eb is None:
                    zero_disp = True
                    all_eff_pass = False
                elif eb[1] < 50.0:
                    all_eff_pass = False

            if c_val <= c_safe_claim + 1e-9:
                if not all_safe_pass:
                    prefix_ok = False
                if c_val >= c_safe_claim - 1e-9 and all_safe_pass:
                    safe_reached = True
            elif any_safe_fail:
                tox_above = True

            if idx_g == target_ec_idx and all_eff_pass:
                eff_at_ec50_ok = True

        if zero_disp:
            return "HOLD", "ZERO_DISP"
        if not (prefix_ok and safe_reached and tox_above and eff_at_ec50_ok and zero_eff_ok):
            return "HOLD", "WINDOW"
        return "OK", None

    if unbounded_ratio_under_parent_blq:
        if not (is_strict_bool(mix_ev.get("metabolite_dominant_unbounded_ratio_qualified")) and mix_ev["metabolite_dominant_unbounded_ratio_qualified"]):
            holds.append(f"HOLD_{prefix}_UNBOUNDED_BMT_TO_PARENT_RATIO_UNDER_PARENT_BLQ"); return False, None, None
        bmt_ev = mix_ev.get("bmt_alone_qualification_evidence")
        bmt_req = frozenset({
            "analysis_method", "tested_product_id",
            "tested_free_bmt_conc_grid_nM", "bmt_alone_safety_replicates_by_conc",
            "bmt_alone_efficacy_replicates_by_conc", "bmt_alone_c_safe_max_l95_free_nM",
            "bmt_alone_ec50_eff_u95_free_nM", "evidence_sha256",
        })
        if bmt_ev is None:
            holds.append(f"HOLD_{prefix}_MISSING_BMT_ALONE_BIOLOGICAL_QUALIFICATION_EVIDENCE"); return False, None, None
        if (
            not isinstance(bmt_ev, Mapping) or set(bmt_ev.keys()) != bmt_req
            or bmt_ev.get("analysis_method") != "SIMULTANEOUS_BONFERRONI_GRID_BRACKET_STUDENT_T"
            or (expected_scope == "exact_product" and bmt_ev.get("tested_product_id") != expected_prod)
            or (expected_scope != "exact_product" and not is_nonempty_str(bmt_ev.get("tested_product_id")))
            or not is_valid_sha256_hex(bmt_ev.get("evidence_sha256"))
            or sha256_bytes(canonical_json_bytes({k: v for k, v in bmt_ev.items() if k != "evidence_sha256"})) != str(bmt_ev["evidence_sha256"])
        ):
            fails.append(f"FAIL_{prefix}_INVALID_BMT_ALONE_QUALIFICATION_EVIDENCE"); return False, None, None
        bg = bmt_ev.get("tested_free_bmt_conc_grid_nM")
        bsr = bmt_ev.get("bmt_alone_safety_replicates_by_conc")
        ber = bmt_ev.get("bmt_alone_efficacy_replicates_by_conc")
        b_cs = bmt_ev.get("bmt_alone_c_safe_max_l95_free_nM")
        b_ec = bmt_ev.get("bmt_alone_ec50_eff_u95_free_nM")
        if not (
            isinstance(bg, list) and len(bg) >= 5 and all(is_finite_num(x) and float(x) >= 0.0 for x in bg)
            and float(bg[0]) == 0.0 and all(float(bg[i]) < float(bg[i + 1]) for i in range(len(bg) - 1))
            and is_finite_num(b_cs) and is_finite_num(b_ec)
            and float(b_ec) > 0.0 and float(b_cs) >= 2.0 * float(b_ec)
            and float(b_cs) >= float(cs_m) - 1e-9 and float(b_ec) <= float(e50_m) + 1e-9
        ):
            fails.append(f"FAIL_{prefix}_BMT_ALONE_WINDOW_INVALID_OR_WEAKER_THAN_MIXTURE"); return False, None, None
        bg_f = [float(x) for x in bg]
        st_bmt, why_bmt = _eval_7ep_panel_curve(
            bg_f, bsr, ber,
            c_safe_claim=float(b_cs), ec50_claim=float(b_ec),
            alpha_safe=0.05 / float(4 * len(bg_f)), alpha_eff=0.05 / float(3 * len(bg_f)),
        )
        if st_bmt == "FAIL":
            fails.append(f"FAIL_{prefix}_INVALID_BMT_ALONE_QUALIFICATION_EVIDENCE"); return False, None, None
        if st_bmt == "HOLD":
            code = f"HOLD_{prefix}_BMT_ALONE_ZERO_DISPERSION_UNESTIMABLE" if why_bmt == "ZERO_DISP" else f"HOLD_{prefix}_BMT_ALONE_REPLICATES_DO_NOT_SUBSTANTIATE_WINDOW"
            holds.append(code); return False, None, None

    # ALWAYS enforce compact metabolite-fraction f_BMT = BMT/(parent+BMT) in [0, 1] composition coverage
    # (NEVER skipped under parent BLQ! When parent is BLQ, compatible fraction range extends to f_obs_max = 1.0
    # and MUST be densely covered across high-finite intermediate mixtures with max_f_gap <= 0.25 up to 1.0!).
    if observed_bmt_to_parent_ratio_max > 0.0 or not unbounded_ratio_under_parent_blq:
        if not (float(r_lo) - 1e-9 <= observed_bmt_to_parent_ratio_min and observed_bmt_to_parent_ratio_max <= float(r_hi) + 1e-9):
            fails.append(f"FAIL_{prefix}_MIXTURE_REQUAL_RATIO_DOES_NOT_COVER_OBSERVED_BMT_PARENT"); return False, None, None
    f_obs_min = 0.0 if observed_bmt_to_parent_ratio_min <= 0.0 else (observed_bmt_to_parent_ratio_min / (1.0 + observed_bmt_to_parent_ratio_min))
    f_obs_max = 1.0 if unbounded_ratio_under_parent_blq else (0.0 if observed_bmt_to_parent_ratio_max <= 0.0 else (observed_bmt_to_parent_ratio_max / (1.0 + observed_bmt_to_parent_ratio_max)))

    mdr = mix_ev.get("mixture_dose_response_evidence")
    mdr_req = frozenset({
        "analysis_method", "tested_product_id",
        "tested_bmt_to_parent_ratio_min", "tested_bmt_to_parent_ratio_max",
        "tested_bmt_fraction_min", "tested_bmt_fraction_max",
        "composition_interpolation_rule",
        "mixture_composition_curves",
        "evidence_sha256",
    })
    if mdr is None:
        holds.append(f"HOLD_{prefix}_MISSING_MIXTURE_DOSE_RESPONSE_EVIDENCE"); return False, None, None
    if (
        not isinstance(mdr, Mapping) or set(mdr.keys()) != mdr_req
        or mdr.get("analysis_method") != "SIMULTANEOUS_BONFERRONI_GRID_BRACKET_STUDENT_T"
        or (expected_scope == "exact_product" and mdr.get("tested_product_id") != expected_prod)
        or (expected_scope != "exact_product" and not is_nonempty_str(mdr.get("tested_product_id")))
        or not is_valid_sha256_hex(mdr.get("evidence_sha256"))
        or sha256_bytes(canonical_json_bytes({k: v for k, v in mdr.items() if k != "evidence_sha256"})) != str(mdr["evidence_sha256"])
    ):
        fails.append(f"FAIL_{prefix}_INVALID_MIXTURE_DOSE_RESPONSE_EVIDENCE"); return False, None, None
    mr_lo, mr_hi = mdr.get("tested_bmt_to_parent_ratio_min"), mdr.get("tested_bmt_to_parent_ratio_max")
    mf_lo, mf_hi = mdr.get("tested_bmt_fraction_min"), mdr.get("tested_bmt_fraction_max")
    interp_rule = mdr.get("composition_interpolation_rule")
    curves = mdr.get("mixture_composition_curves")
    curve_req = frozenset({
        "measured_bmt_fraction",
        "measured_bmt_to_parent_ratio",
        "tested_free_combined_conc_grid_nM",
        "mixture_safety_replicates_by_conc",
        "mixture_efficacy_replicates_by_conc",
    })
    min_curves = 2 if (float(r_hi) > float(r_lo) + 1e-9 or unbounded_ratio_under_parent_blq) else 1
    if not (
        is_finite_num(mr_lo) and is_finite_num(mr_hi)
        and is_finite_num(mf_lo) and is_finite_num(mf_hi)
        and 0.0 <= float(mf_lo) <= float(mf_hi) <= 1.0
        and abs(float(mr_lo) - float(r_lo)) <= 1e-9 and abs(float(mr_hi) - float(r_hi)) <= 1e-9
        and abs(float(mf_lo) - (float(r_lo) / (1.0 + float(r_lo)))) <= 1e-6
        and interp_rule == "CONSERVATIVE_MIN_CEILING_MAX_EC50_ACROSS_BRACKETED_RATIOS"
        and isinstance(curves, list) and len(curves) >= min_curves
        and all(isinstance(c, Mapping) and set(c.keys()) == curve_req for c in curves)
    ):
        fails.append(f"FAIL_{prefix}_INVALID_MIXTURE_DOSE_RESPONSE_EVIDENCE"); return False, None, None
    if float(mf_lo) > f_obs_min + 1e-9 or float(mf_hi) < f_obs_max - 1e-9:
        if unbounded_ratio_under_parent_blq and float(mf_hi) < 1.0 - 1e-9:
            holds.append(f"HOLD_{prefix}_UNBOUNDED_HIGH_FINITE_MIXTURE_GAP_UNQUALIFIED"); return False, None, None
        fails.append(f"FAIL_{prefix}_MIXTURE_REQUAL_RATIO_DOES_NOT_COVER_OBSERVED_BMT_PARENT"); return False, None, None
    curve_fracs: list[float] = []
    curve_fin_ratios: list[float] = []
    total_grid_pts = 0
    for c_obj in curves:
        cf = c_obj.get("measured_bmt_fraction")
        cr = c_obj.get("measured_bmt_to_parent_ratio")
        mg = c_obj.get("tested_free_combined_conc_grid_nM")
        if not (
            is_finite_num(cf) and 0.0 <= float(cf) <= 1.0
            and isinstance(mg, list) and len(mg) >= 5 and all(is_finite_num(x) and float(x) >= 0.0 for x in mg)
            and float(mg[0]) == 0.0 and all(float(mg[i]) < float(mg[i + 1]) for i in range(len(mg) - 1))
        ):
            fails.append(f"FAIL_{prefix}_INVALID_MIXTURE_DOSE_RESPONSE_EVIDENCE"); return False, None, None
        cf_v = float(cf)
        if abs(cf_v - 1.0) <= 1e-9:
            if cr != "INF_PURE_BMT":
                fails.append(f"FAIL_{prefix}_INVALID_MIXTURE_DOSE_RESPONSE_EVIDENCE"); return False, None, None
        else:
            if not (is_finite_num(cr) and float(cr) >= 0.0 and abs((float(cr) / (1.0 + float(cr))) - cf_v) <= 1e-5):
                fails.append(f"FAIL_{prefix}_INVALID_MIXTURE_DOSE_RESPONSE_EVIDENCE"); return False, None, None
            curve_fin_ratios.append(float(cr))
        curve_fracs.append(cf_v)
        total_grid_pts += len(mg)
    if (
        any(curve_fracs[i] >= curve_fracs[i + 1] - 1e-12 for i in range(len(curve_fracs) - 1))
        or abs(curve_fracs[0] - float(mf_lo)) > 1e-6
        or abs(curve_fracs[-1] - float(mf_hi)) > 1e-6
    ):
        fails.append(f"FAIL_{prefix}_INVALID_MIXTURE_DOSE_RESPONSE_EVIDENCE"); return False, None, None
    if (not unbounded_ratio_under_parent_blq) and (not curve_fin_ratios or abs(curve_fin_ratios[-1] - float(r_hi)) > 1e-6):
        fails.append(f"FAIL_{prefix}_INVALID_MIXTURE_DOSE_RESPONSE_EVIDENCE"); return False, None, None
    # Dense composition-fraction spacing across [mf_lo, mf_hi] (max_f_gap <= 0.25!) + legacy finite ratio-gap guard
    f_span = float(mf_hi) - float(mf_lo)
    if f_span > 0.04 + 1e-9:
        max_f_gap = max(curve_fracs[i + 1] - curve_fracs[i] for i in range(len(curve_fracs) - 1))
        if len(curve_fracs) < 3 or max_f_gap > min(0.25, max(0.15, 0.65 * f_span)) + 1e-6:
            if unbounded_ratio_under_parent_blq:
                holds.append(f"HOLD_{prefix}_UNBOUNDED_HIGH_FINITE_MIXTURE_GAP_UNQUALIFIED"); return False, None, None
            fails.append(f"FAIL_{prefix}_MIXTURE_COMPOSITION_RATIO_GRID_TOO_SPARSE"); return False, None, None
    if (not unbounded_ratio_under_parent_blq) and len(curve_fin_ratios) >= 2:
        r_span = float(r_hi) - float(r_lo)
        if r_span > 0.05 + 1e-9:
            max_r_gap = max(curve_fin_ratios[i + 1] - curve_fin_ratios[i] for i in range(len(curve_fin_ratios) - 1))
            max_allowed_gap = 0.50 if r_span > 0.50 + 1e-9 else max(0.25, 0.55 * r_span)
            if len(curve_fin_ratios) < 3 or max_r_gap > max_allowed_gap + 1e-9:
                fails.append(f"FAIL_{prefix}_MIXTURE_COMPOSITION_RATIO_GRID_TOO_SPARSE"); return False, None, None
    alpha_mix_safe = 0.05 / float(4 * total_grid_pts)
    alpha_mix_eff = 0.05 / float(3 * total_grid_pts)
    for c_obj in curves:
        mg_f = [float(x) for x in c_obj["tested_free_combined_conc_grid_nM"]]
        st_m, why_m = _eval_7ep_panel_curve(
            mg_f, c_obj["mixture_safety_replicates_by_conc"], c_obj["mixture_efficacy_replicates_by_conc"],
            c_safe_claim=float(cs_m), ec50_claim=float(e50_m),
            alpha_safe=alpha_mix_safe, alpha_eff=alpha_mix_eff,
        )
        if st_m == "FAIL":
            fails.append(f"FAIL_{prefix}_INVALID_MIXTURE_DOSE_RESPONSE_EVIDENCE"); return False, None, None
        if st_m == "HOLD":
            code = f"HOLD_{prefix}_MIXTURE_ZERO_DISPERSION_UNESTIMABLE" if why_m == "ZERO_DISP" else f"HOLD_{prefix}_MIXTURE_REPLICATES_DO_NOT_SUBSTANTIATE_WINDOW"
            holds.append(code); return False, None, None
    return True, float(e50_m), float(cs_m)


def _validate_b2b_exposure_block(
    ev: Optional[Mapping[str, Any]],
    *,
    ec50_u95: float,
    lloq_parent_by_matrix: Mapping[str, float],
    lloq_bmt_by_matrix: Mapping[str, float],
    fu_parent_by_matrix: Mapping[str, float],
    fu_bmt_by_matrix: Mapping[str, float],
    ceiling_l95: float,
    expected_prod: str,
    expected_bank: str,
    expected_lot: str,
    expected_route: str,
    expected_scope: str,
    expected_coating_identity: Optional[Mapping[str, str]],
    fails: list[str],
    holds: list[str],
    prefix: str,
    upstream_sample_ledger: Optional[Mapping[str, tuple[float, str, str, str, str]]] = None,
) -> bool:
    """Data-backed time-indexed simultaneous exposure, full two-analyte censoring, quantitative inter-sample envelope, Day-21 washout, & mixture-window enforcement."""
    if ev is None:
        return False
    ok = ev.get("verdict") == "PASS"
    used_marg = ev.get("used_marginal_u95_sum")
    if not is_strict_bool(used_marg):
        fails.append(f"FAIL_{prefix}_MISSING_MARGINAL_SUM_DECLARATION"); ok = False
    elif used_marg is True:
        fails.append(f"FAIL_{prefix}_MARGINAL_SUM_FORBIDDEN"); ok = False

    a_conc = ev.get("alpha_conc")
    a_fu_p = ev.get("alpha_fu_parent")
    a_fu_b = ev.get("alpha_fu_bmt")
    u95_joint = ev.get("u95_joint_peak_free_nM")
    parent_lo = ev.get("days0_10_parent_lower_free_nM")
    bmt_loc_tot = ev.get("c_bmt_local_total_u_alloc_nM")
    bmt_loc_free = ev.get("c_bmt_local_free_u_alloc_nM")
    bmt_rec_tot = ev.get("c_bmt_recirc_total_u_alloc_nM")
    bmt_rec_free = ev.get("c_bmt_recirc_free_u_alloc_nM")
    loc_mat = ev.get("local_assay_matrix")
    rec_mat = ev.get("recirc_assay_matrix")
    if not all(is_finite_num(x) for x in (a_conc, a_fu_p, a_fu_b, u95_joint, parent_lo, bmt_loc_tot, bmt_loc_free, bmt_rec_tot, bmt_rec_free)):
        holds.append(f"HOLD_{prefix}_MISSING_SIMULTANEOUS_PK_OR_METABOLITE_FIELDS"); return False
    if loc_mat not in REQUIRED_3_MATRICES or rec_mat not in REQUIRED_3_MATRICES:
        fails.append(f"FAIL_{prefix}_MISSING_OR_INVALID_ASSAY_MATRIX"); return False
    tp_recs = ev.get("timepoint_replicate_records")
    fp_rep = ev.get("fu_parent_replicates")
    fb_rep = ev.get("fu_bmt_replicates")

    # Discover all per-timepoint matrices (allowing faithful mixed B-1 serum + B-2 whole-blood ledgers!)
    used_loc_mats: set[str] = {str(loc_mat)}
    used_rec_mats: set[str] = {str(rec_mat)}
    row_mat_invalid = False
    if isinstance(tp_recs, list):
        for _r_scan in tp_recs:
            if isinstance(_r_scan, Mapping):
                _rl = _r_scan.get("local_assay_matrix", loc_mat)
                _rr = _r_scan.get("recirc_assay_matrix", rec_mat)
                if _rl not in REQUIRED_3_MATRICES or _rr not in REQUIRED_3_MATRICES:
                    row_mat_invalid = True
                else:
                    used_loc_mats.add(str(_rl))
                    used_rec_mats.add(str(_rr))
    if row_mat_invalid:
        fails.append(f"FAIL_{prefix}_MISSING_OR_INVALID_ASSAY_MATRIX"); return False

    lloq_b_loc_min = min(float(lloq_bmt_by_matrix[m]) for m in used_loc_mats)
    lloq_b_rec_min = min(float(lloq_bmt_by_matrix[m]) for m in used_rec_mats)

    # Whole-blood systemic recirculation (either receipt-wide OR on any mixed-source B-2 timepoint row)
    # MUST provide validated blood-to-plasma K_bp calibration (1:1 parity with B-4) so < 0.5 nM is on plasma equivalents!
    kbp_cal = ev.get("systemic_kbp_calibration")
    is_rec_wb = ("whole_blood" in used_rec_mats)
    kbp_keys = frozenset({
        "kbp_assay_method_id", "blood_to_plasma_ratio_parent_replicates",
        "blood_to_plasma_ratio_bmt_replicates", "alpha_kbp_parent", "alpha_kbp_bmt", "calibration_sha256",
    })
    kbp_valid = (
        isinstance(kbp_cal, Mapping) and set(kbp_cal.keys()) == kbp_keys
        and is_nonempty_str(kbp_cal.get("kbp_assay_method_id"))
        and is_finite_num(kbp_cal.get("alpha_kbp_parent")) and float(kbp_cal["alpha_kbp_parent"]) > 0.0
        and is_finite_num(kbp_cal.get("alpha_kbp_bmt")) and float(kbp_cal["alpha_kbp_bmt"]) > 0.0
        and all(
            isinstance(kbp_cal.get(k), list) and len(kbp_cal[k]) >= 3
            and all(is_finite_num(x) and 0.05 <= float(x) <= 20.0 for x in kbp_cal[k])
            for k in ("blood_to_plasma_ratio_parent_replicates", "blood_to_plasma_ratio_bmt_replicates")
        )
        and is_valid_sha256_hex(kbp_cal.get("calibration_sha256"))
        and sha256_bytes(canonical_json_bytes({k: v for k, v in kbp_cal.items() if k != "calibration_sha256"})) == str(kbp_cal["calibration_sha256"])
    )
    if is_rec_wb and not kbp_valid:
        fails.append(f"FAIL_{prefix}_MISSING_OR_INVALID_WHOLE_BLOOD_KBP_CALIBRATION"); ok = False
    elif (not is_rec_wb) and (kbp_cal is not None) and not kbp_valid:
        fails.append(f"FAIL_{prefix}_MISSING_OR_INVALID_WHOLE_BLOOD_KBP_CALIBRATION"); ok = False
    a_kbp_b2b = (float(kbp_cal["alpha_kbp_parent"]) + float(kbp_cal["alpha_kbp_bmt"])) if (is_rec_wb and kbp_valid) else 0.0
    l_kbp_p_b2b = 1.0
    l_kbp_b_b2b = 1.0
    kbp_bounds_ok_b2b = True
    if is_rec_wb and kbp_valid:
        kp_b2 = sample_t_one_sided_bounds([float(x) for x in kbp_cal["blood_to_plasma_ratio_parent_replicates"]], alpha=float(kbp_cal["alpha_kbp_parent"]))
        kb_b2 = sample_t_one_sided_bounds([float(x) for x in kbp_cal["blood_to_plasma_ratio_bmt_replicates"]], alpha=float(kbp_cal["alpha_kbp_bmt"]))
        if kp_b2 is None or kb_b2 is None or kp_b2[1] <= 0.0 or kb_b2[1] <= 0.0:
            holds.append(f"HOLD_{prefix}_WHOLE_BLOOD_KBP_LOWER_BOUND_NONPOSITIVE"); ok = False
            kbp_bounds_ok_b2b = False
        else:
            l_kbp_p_b2b, l_kbp_b_b2b = kp_b2[1], kb_b2[1]

    rec_fb_rep = ev.get("recirc_fu_bmt_replicates")
    a_fu_b_rec_raw = ev.get("alpha_fu_bmt_recirc")
    need_sep_rec_fu = (str(rec_mat) != str(loc_mat))
    has_sep_rec_fu = (rec_fb_rep is not None or a_fu_b_rec_raw is not None)
    sep_rec_fu_valid = True
    a_fu_b_rec = 0.0
    if need_sep_rec_fu or has_sep_rec_fu:
        if not (
            isinstance(rec_fb_rep, list) and len(rec_fb_rep) >= 3
            and all(is_finite_num(x) and 0.0 < float(x) <= 1.0 for x in rec_fb_rep)
            and is_finite_num(a_fu_b_rec_raw) and float(a_fu_b_rec_raw) > 0.0
        ):
            fails.append(f"FAIL_{prefix}_MISSING_OR_INVALID_RECIRC_MATRIX_FU_BMT_CALIBRATION"); ok = False; sep_rec_fu_valid = False
        else:
            a_fu_b_rec = float(a_fu_b_rec_raw)
            rec_fb_mean = sum(float(x) for x in rec_fb_rep) / len(rec_fb_rep)
            if abs(rec_fb_mean - float(fu_bmt_by_matrix[str(rec_mat)])) > 0.03:
                fails.append(f"FAIL_{prefix}_RECIRC_FU_BMT_MISMATCH_VS_B0A_MATRIX"); ok = False; sep_rec_fu_valid = False

    # Validate additional_matrix_calibrations for any extra per-timepoint matrices (e.g. B-2 whole_blood alongside B-1 serum!)
    needed_extra_mats = (used_loc_mats - {str(loc_mat)}) | (used_rec_mats - {str(loc_mat), str(rec_mat)})
    add_cal = ev.get("additional_matrix_calibrations")
    common_basis = ev.get("common_exposure_basis")
    extra_mat_valid = True
    a_fu_extra = 0.0
    extra_mat_bounds: dict[str, tuple[float, float, float, float]] = {}
    if needed_extra_mats:
        if common_basis != "UNBOUND_FREE_CONC_NM_AND_PLASMA_EQUIV_SYSTEMIC_NM":
            holds.append(f"HOLD_{prefix}_MISSING_COMMON_EXPOSURE_BASIS"); ok = False; extra_mat_valid = False
        if add_cal is None:
            for _em in sorted(needed_extra_mats):
                holds.append(f"HOLD_{prefix}_MISSING_PER_MATRIX_FU_CALIBRATION:{_em}")
            ok = False; extra_mat_valid = False
    elif common_basis is not None and common_basis != "UNBOUND_FREE_CONC_NM_AND_PLASMA_EQUIV_SYSTEMIC_NM":
        fails.append(f"FAIL_{prefix}_INVALID_COMMON_EXPOSURE_BASIS"); ok = False; extra_mat_valid = False
    if add_cal is not None:
        if not isinstance(add_cal, Mapping) or any(k not in REQUIRED_3_MATRICES or k == str(loc_mat) for k in add_cal.keys()):
            fails.append(f"FAIL_{prefix}_INVALID_ADDITIONAL_MATRIX_CALIBRATION"); ok = False; extra_mat_valid = False
        else:
            for _em in sorted(needed_extra_mats):
                if _em not in add_cal:
                    holds.append(f"HOLD_{prefix}_MISSING_PER_MATRIX_FU_CALIBRATION:{_em}"); ok = False; extra_mat_valid = False
            _ec_keys = frozenset({"fu_parent_replicates", "fu_bmt_replicates", "alpha_fu_parent", "alpha_fu_bmt"})
            for _em, _ecal in sorted(add_cal.items()):
                if not (
                    isinstance(_ecal, Mapping) and set(_ecal.keys()) == _ec_keys
                    and isinstance(_ecal.get("fu_parent_replicates"), list) and len(_ecal["fu_parent_replicates"]) >= 3
                    and all(is_finite_num(x) and 0.0 < float(x) <= 1.0 for x in _ecal["fu_parent_replicates"])
                    and isinstance(_ecal.get("fu_bmt_replicates"), list) and len(_ecal["fu_bmt_replicates"]) >= 3
                    and all(is_finite_num(x) and 0.0 < float(x) <= 1.0 for x in _ecal["fu_bmt_replicates"])
                    and is_finite_num(_ecal.get("alpha_fu_parent")) and float(_ecal["alpha_fu_parent"]) > 0.0
                    and is_finite_num(_ecal.get("alpha_fu_bmt")) and float(_ecal["alpha_fu_bmt"]) > 0.0
                ):
                    fails.append(f"FAIL_{prefix}_INVALID_ADDITIONAL_MATRIX_CALIBRATION:{_em}"); ok = False; extra_mat_valid = False; continue
                _afp_e = float(_ecal["alpha_fu_parent"])
                _afb_e = float(_ecal["alpha_fu_bmt"])
                a_fu_extra += (_afp_e + _afb_e)
                _fpr_e = [float(x) for x in _ecal["fu_parent_replicates"]]
                _fbr_e = [float(x) for x in _ecal["fu_bmt_replicates"]]
                if abs((sum(_fpr_e) / len(_fpr_e)) - float(fu_parent_by_matrix[str(_em)])) > 0.03:
                    fails.append(f"FAIL_{prefix}_EXTRA_MATRIX_FU_MISMATCH_VS_B0A:{_em}"); ok = False; extra_mat_valid = False
                if abs((sum(_fbr_e) / len(_fbr_e)) - float(fu_bmt_by_matrix[str(_em)])) > 0.03:
                    fails.append(f"FAIL_{prefix}_EXTRA_MATRIX_FU_MISMATCH_VS_B0A:{_em}"); ok = False; extra_mat_valid = False
                _fpb_e = sample_t_one_sided_bounds(_fpr_e, alpha=_afp_e / 2.0)
                _fbb_e = sample_t_one_sided_bounds(_fbr_e, alpha=_afb_e / 2.0)
                if _fpb_e is None or _fbb_e is None:
                    holds.append(f"HOLD_{prefix}_EXTRA_MATRIX_FU_DEGENERATE_ZERO_VARIANCE:{_em}"); ok = False; extra_mat_valid = False
                else:
                    extra_mat_bounds[str(_em)] = (min(1.0, _fpb_e[2]), max(0.0, _fpb_e[1]), min(1.0, _fbb_e[2]), max(0.0, _fbb_e[1]))

    total_alpha_b2b = float(a_conc) + float(a_fu_p) + float(a_fu_b) + a_fu_b_rec + a_fu_extra + a_kbp_b2b
    if float(a_conc) <= 0.0 or float(a_fu_p) <= 0.0 or float(a_fu_b) <= 0.0 or total_alpha_b2b > 0.05 + 1e-12:
        fails.append(f"FAIL_{prefix}_GLOBAL_ALPHA_EXCEEDS_0P05"); ok = False
    if min(float(u95_joint), float(bmt_loc_tot), float(bmt_loc_free), float(bmt_rec_tot), float(bmt_rec_free)) < 0.0:
        fails.append(f"FAIL_{prefix}_NEGATIVE_CONCENTRATION"); ok = False
    if float(bmt_loc_free) > float(bmt_loc_tot) + 1e-12 or float(bmt_rec_free) > float(bmt_rec_tot) + 1e-12:
        fails.append(f"FAIL_{prefix}_FREE_METABOLITE_EXCEEDS_TOTAL"); ok = False
    if float(u95_joint) < float(parent_lo) - 1e-12:
        fails.append(f"FAIL_{prefix}_JOINT_PEAK_BELOW_PARENT_FLOOR"); ok = False
    if float(u95_joint) >= ceiling_l95:
        fails.append(f"FAIL_{prefix}_JOINT_PEAK_NOT_STRICTLY_BELOW_CSAFE"); ok = False
    if float(parent_lo) <= 0.0 or float(parent_lo) < ec50_u95:
        fails.append(f"FAIL_{prefix}_PARENT_EFFICACY_FLOOR_BELOW_EC50"); ok = False
    raw_max_loc_bmt_tot = 0.0
    raw_max_loc_bmt_free = 0.0
    raw_max_rec_bmt_tot = 0.0
    raw_max_rec_bmt_free = 0.0
    recomp_u_loc_bmt_tot = 0.0
    recomp_u_loc_bmt_free = 0.0
    recomp_u_rec_bmt_tot = 0.0
    recomp_u_rec_bmt_free = 0.0
    u_local_series: list[float] = []
    u_bmt_free_series: list[float] = []
    l_bmt_free_series: list[float] = []
    l_parent_all_series: list[float] = []
    u_parent_all_series: list[float] = []
    u_sys_series: list[float] = []
    washout_u_joint: Optional[float] = None
    obs_free_ratio_min = float("inf")
    obs_free_ratio_max = 0.0
    unbounded_bmt_ratio = False
    any_quant_loc_bmt = False
    any_quant_rec_bmt = False
    hours_seen: list[float] = []
    tp_valid = False
    loc_inc_rec = ev.get("local_measurement_includes_recirculation")
    if not is_strict_bool(loc_inc_rec):
        fails.append(f"FAIL_{prefix}_MISSING_RECIRCULATION_ACCOUNTING_FLAG"); ok = False
        loc_inc_rec = True

    if not (
        isinstance(tp_recs, list) and len(tp_recs) >= 4
        and isinstance(fp_rep, list) and len(fp_rep) >= 3 and all(is_finite_num(x) and 0.0 < float(x) <= 1.0 for x in fp_rep)
        and isinstance(fb_rep, list) and len(fb_rep) >= 3 and all(is_finite_num(x) and 0.0 < float(x) <= 1.0 for x in fb_rep)
    ):
        fails.append(f"FAIL_{prefix}_MISSING_OR_INVALID_RAW_EXPOSURE_REPLICATES"); ok = False
    elif float(a_conc) > 0.0 and float(a_fu_p) > 0.0 and float(a_fu_b) > 0.0 and total_alpha_b2b <= 0.05 + 1e-12 and kbp_bounds_ok_b2b and ((not is_rec_wb) or kbp_valid) and sep_rec_fu_valid and extra_mat_valid:
        fp_mean = sum(float(x) for x in fp_rep) / len(fp_rep)
        fb_mean = sum(float(x) for x in fb_rep) / len(fb_rep)
        if abs(fp_mean - float(fu_parent_by_matrix[str(loc_mat)])) > 0.03:
            fails.append(f"FAIL_{prefix}_LOCAL_FU_PARENT_MISMATCH_VS_B0A_MATRIX"); ok = False
        if abs(fb_mean - float(fu_bmt_by_matrix[str(loc_mat)])) > 0.03:
            fails.append(f"FAIL_{prefix}_LOCAL_FU_BMT_MISMATCH_VS_B0A_MATRIX"); ok = False
        # Both local fu_parent AND local fu_bmt use two-tailed alpha / 2 so BOTH (U_fp, L_fp) and (U_fb, L_fb)
        # are allocated inside the <= 0.05 global familywise budget; distinct recirc matrix uses dedicated u_fb_rec!
        fp_b = sample_t_one_sided_bounds([float(x) for x in fp_rep], alpha=float(a_fu_p) / 2.0)
        fb_b = sample_t_one_sided_bounds([float(x) for x in fb_rep], alpha=float(a_fu_b) / 2.0)
        if fp_b is None or fb_b is None:
            holds.append(f"HOLD_{prefix}_FU_REPLICATES_DEGENERATE_ZERO_VARIANCE"); ok = False
        u_fp = min(1.0, float(fp_rep[0]) if fp_b is None else fp_b[2])
        l_fp = max(0.0, float(fp_rep[0]) if fp_b is None else fp_b[1])
        u_fb = min(1.0, float(fb_rep[0]) if fb_b is None else fb_b[2])
        l_fb = max(0.0, float(fb_rep[0]) if fb_b is None else fb_b[1])
        if need_sep_rec_fu or has_sep_rec_fu:
            fb_rec_b = sample_t_one_sided_bounds([float(x) for x in rec_fb_rep], alpha=a_fu_b_rec)
            if fb_rec_b is None:
                holds.append(f"HOLD_{prefix}_RECIRC_FU_REPLICATES_DEGENERATE_ZERO_VARIANCE"); ok = False
                u_fb_rec = min(1.0, max(float(x) for x in rec_fb_rep))
            else:
                u_fb_rec = min(1.0, fb_rec_b[2])
        else:
            u_fb_rec = u_fb
        k_tp = len(tp_recs)
        # Unified familywise <= 0.05 Bonferroni budget covering ALL 7 one-sided concentration bounds per timepoint:
        # (1) u_loc_only, (2) l_parent, (3) u_parent, (4) u_local_bmt, (5) l_local_bmt, (6) u_sys, (7) u_recirc_bmt!
        m_total = max(1, 7 * k_tp)
        alpha_tp = float(a_conc) / float(m_total)
        per_mat_fu_map: dict[str, tuple[float, float, float, float]] = {
            str(loc_mat): (u_fp, l_fp, u_fb, l_fb),
            **extra_mat_bounds,
        }
        tp_allowed = frozenset({
            "hour_h",
            "local_assay_matrix", "recirc_assay_matrix",
            "source_sample_ids", "biological_unit_ids",
            "local_parent_total_replicates_nM", "local_parent_blq_flags",
            "local_bmt_total_replicates_nM", "local_bmt_blq_flags",
            "recirc_bmt_total_replicates_nM", "recirc_bmt_blq_flags",
            "systemic_parent_total_replicates_nM", "systemic_parent_blq_flags",
            "systemic_bmt_total_replicates_nM", "systemic_bmt_blq_flags",
        })
        prev_h = -1.0
        tp_valid = True
        seen_b2b_sample_hours: dict[str, float] = {}
        seen_b2b_sample_digests: dict[str, str] = {}
        seen_b2b_sample_matrices: dict[str, str] = {}
        seen_b2b_sample_rec_matrices: dict[str, str] = {}
        seen_b2b_sample_units: dict[str, str] = {}
        ledger_issue = False
        for idx_tp, row in enumerate(tp_recs):
            if not isinstance(row, Mapping):
                fails.append(f"FAIL_{prefix}_MALFORMED_TIMEPOINT_ROW:{idx_tp}"); tp_valid = False; ok = False; continue
            _check_allowed_keys(row, tp_allowed, fails, f"{prefix}_TP_{idx_tp}")
            hh = row.get("hour_h")
            sids = row.get("source_sample_ids")
            buids = row.get("biological_unit_ids")
            lp_r, lp_blq = row.get("local_parent_total_replicates_nM"), row.get("local_parent_blq_flags")
            lb_r, lb_blq = row.get("local_bmt_total_replicates_nM"), row.get("local_bmt_blq_flags")
            rb_r, rb_blq = row.get("recirc_bmt_total_replicates_nM"), row.get("recirc_bmt_blq_flags")
            sp_r, sp_blq = row.get("systemic_parent_total_replicates_nM"), row.get("systemic_parent_blq_flags")
            sb_r, sb_blq = row.get("systemic_bmt_total_replicates_nM"), row.get("systemic_bmt_blq_flags")
            if not (
                is_finite_num(hh) and float(hh) > prev_h and float(hh) > 0.0
                and all(isinstance(v, list) and len(v) >= 3 and all(is_finite_num(x) and float(x) >= 0.0 for x in v) for v in (lp_r, lb_r, rb_r, sp_r, sb_r))
                and all(isinstance(bf, list) and len(bf) == len(rv) and all(is_strict_bool(b) for b in bf) for bf, rv in ((lp_blq, lp_r), (lb_blq, lb_r), (rb_blq, rb_r), (sp_blq, sp_r), (sb_blq, sb_r)))
            ):
                fails.append(f"FAIL_{prefix}_INVALID_TIMEPOINT_REPLICATES:{idx_tp}"); tp_valid = False; ok = False; continue
            if not (len(lp_r) == len(lb_r) == len(rb_r) == len(sp_r) == len(sb_r)):
                fails.append(f"FAIL_{prefix}_STREAM_LENGTH_MISMATCH_VS_SAMPLE_LEDGER:{idx_tp}"); tp_valid = False; ok = False; continue
            if not (
                isinstance(sids, list) and len(sids) == len(lp_r) and all(is_nonempty_str(s) for s in sids)
                and isinstance(buids, list) and len(buids) == len(lp_r) and all(is_nonempty_str(u) for u in buids)
                and len({str(u).strip().upper() for u in buids}) == len(buids)
            ):
                ledger_issue = True
            else:
                for _ri_s, raw_sid in enumerate(sids):
                    sid_n = str(raw_sid).strip().upper()
                    buid_n = str(buids[_ri_s]).strip().upper()
                    if sid_n in seen_b2b_sample_hours:
                        ledger_issue = True
                    else:
                        row_loc_m = str(row.get("local_assay_matrix", loc_mat))
                        row_rec_m = str(row.get("recirc_assay_matrix", rec_mat))
                        seen_b2b_sample_hours[sid_n] = float(hh)
                        seen_b2b_sample_matrices[sid_n] = row_loc_m
                        seen_b2b_sample_rec_matrices[sid_n] = row_rec_m
                        seen_b2b_sample_units[sid_n] = buid_n
                        _an_row_obj = {
                            "sample_id": sid_n,
                            "hour_h": float(hh),
                            "assay_matrix": row_loc_m,
                            "recirc_assay_matrix": row_rec_m,
                            "biological_unit_id": buid_n,
                            "local_parent_total_nM": float(lp_r[_ri_s]), "local_parent_blq": bool(lp_blq[_ri_s]),
                            "local_bmt_total_nM": float(lb_r[_ri_s]), "local_bmt_blq": bool(lb_blq[_ri_s]),
                            "recirc_bmt_total_nM": float(rb_r[_ri_s]), "recirc_bmt_blq": bool(rb_blq[_ri_s]),
                            "systemic_parent_total_nM": float(sp_r[_ri_s]), "systemic_parent_blq": bool(sp_blq[_ri_s]),
                            "systemic_bmt_total_nM": float(sb_r[_ri_s]), "systemic_bmt_blq": bool(sb_blq[_ri_s]),
                        }
                        seen_b2b_sample_digests[sid_n] = sha256_bytes(canonical_json_bytes(_an_row_obj))
            row_loc_m = str(row.get("local_assay_matrix", loc_mat))
            row_rec_m = str(row.get("recirc_assay_matrix", rec_mat))
            lloq_p_loc_r = float(lloq_parent_by_matrix[row_loc_m])
            lloq_b_loc_r = float(lloq_bmt_by_matrix[row_loc_m])
            lloq_p_rec_r = float(lloq_parent_by_matrix[row_rec_m])
            lloq_b_rec_r = float(lloq_bmt_by_matrix[row_rec_m])
            u_fp_r, l_fp_r, u_fb_r, l_fb_r = per_mat_fu_map[row_loc_m]
            if row_rec_m == str(loc_mat):
                u_fb_rec_r = u_fb
            elif row_rec_m == str(rec_mat):
                u_fb_rec_r = u_fb_rec
            else:
                u_fb_rec_r = per_mat_fu_map[row_rec_m][2]
            l_kbp_p_r = l_kbp_p_b2b if row_rec_m == "whole_blood" else 1.0
            l_kbp_b_r = l_kbp_b_b2b if row_rec_m == "whole_blood" else 1.0
            prev_h = float(hh)
            hours_seen.append(prev_h)
            lpf_r = [float(x) for x in lp_r]
            lbf_r = [float(x) for x in lb_r]
            rbf_r = [float(x) for x in rb_r]
            spf_r = [float(x) for x in sp_r]
            sbf_r = [float(x) for x in sb_r]
            for stream_nm, vals_s, flags_s, lloq_s in (
                ("LOCAL_PARENT", lpf_r, lp_blq, lloq_p_loc_r),
                ("LOCAL_BMT", lbf_r, lb_blq, lloq_b_loc_r),
                ("RECIRC_BMT", rbf_r, rb_blq, lloq_b_rec_r),
                ("SYS_PARENT", spf_r, sp_blq, lloq_p_rec_r),
                ("SYS_BMT", sbf_r, sb_blq, lloq_b_rec_r),
            ):
                for _bi, _bv in enumerate(vals_s):
                    if flags_s[_bi] and _bv >= lloq_s - 1e-12:
                        fails.append(f"FAIL_{prefix}_BLQ_FLAG_CONTRADICTS_QUANTIFIABLE_{stream_nm}:{idx_tp}"); ok = False
                    elif (not flags_s[_bi]) and _bv < lloq_s - 1e-12:
                        fails.append(f"FAIL_{prefix}_UNFLAGGED_BLQ_{stream_nm}_REPLICATE:{idx_tp}"); ok = False
            # Exact censor-aware Student-t bounds over [0, LLOQ] admissible intervals using THIS row's calibrated matrix!
            lb_intervals = [(0.0, lloq_b_loc_r) if lb_blq[i] else (lbf_r[i], lbf_r[i]) for i in range(len(lbf_r))]
            rb_intervals = [(0.0, lloq_b_rec_r) if rb_blq[i] else (rbf_r[i], rbf_r[i]) for i in range(len(rbf_r))]
            u_lbt_c = censor_aware_t_bound(lb_intervals, alpha=alpha_tp, upper=True)
            l_lbt_c = censor_aware_t_bound(lb_intervals, alpha=alpha_tp, upper=False)
            u_rbt_c = censor_aware_t_bound(rb_intervals, alpha=alpha_tp, upper=True)
            if u_rbt_c is None and not loc_inc_rec:
                holds.append(f"HOLD_{prefix}_CENSOR_AWARE_RECIRC_BOUND_UNESTIMABLE:{idx_tp}"); ok = False
            u_lbt_cens = max(hi for _, hi in lb_intervals) if u_lbt_c is None else u_lbt_c
            l_lbt_cens = 0.0 if (l_lbt_c is None or any(lb_blq)) else max(0.0, l_lbt_c)
            u_rbt_cens = max(hi for _, hi in rb_intervals) if u_rbt_c is None else u_rbt_c
            recirc_free_upper = (u_rbt_cens * u_fb_rec_r) if not loc_inc_rec else 0.0
            comb_intervals = [
                (
                    (0.0 if lp_blq[i] else lpf_r[i]) * u_fp_r + (0.0 if lb_blq[i] else lbf_r[i]) * u_fb_r,
                    (lloq_p_loc_r if lp_blq[i] else lpf_r[i]) * u_fp_r + (lloq_b_loc_r if lb_blq[i] else lbf_r[i]) * u_fb_r,
                )
                for i in range(len(lpf_r))
            ]
            u_loc_only = censor_aware_t_bound(comb_intervals, alpha=alpha_tp, upper=True)
            if u_loc_only is None:
                holds.append(f"HOLD_{prefix}_CENSOR_AWARE_BOUND_UNESTIMABLE:{idx_tp}"); ok = False
                u_loc_only = max(hi for _, hi in comb_intervals)
            u_jk = u_loc_only + recirc_free_upper
            u_local_series.append(u_jk)
            u_bmt_free_series.append(u_lbt_cens * u_fb_r + recirc_free_upper)
            l_bmt_free_series.append(l_lbt_cens * l_fb_r)
            if 504.0 <= prev_h <= 528.0:
                washout_u_joint = u_jk if washout_u_joint is None else max(washout_u_joint, u_jk)
            p_intervals = [
                ((0.0 if lp_blq[i] else lpf_r[i]) * l_fp_r, (lloq_p_loc_r if lp_blq[i] else lpf_r[i]) * l_fp_r)
                for i in range(len(lpf_r))
            ]
            l_pk = censor_aware_t_bound(p_intervals, alpha=alpha_tp, upper=False)
            if l_pk is None:
                holds.append(f"HOLD_{prefix}_CENSOR_AWARE_PARENT_BOUND_UNESTIMABLE:{idx_tp}"); ok = False
                l_pk = 0.0
            l_parent_all_series.append(max(0.0, l_pk))
            p_up_intervals = [
                ((0.0 if lp_blq[i] else lpf_r[i]) * u_fp_r, (lloq_p_loc_r if lp_blq[i] else lpf_r[i]) * u_fp_r)
                for i in range(len(lpf_r))
            ]
            u_pk = censor_aware_t_bound(p_up_intervals, alpha=alpha_tp, upper=True)
            u_parent_all_series.append(max(hi for _, hi in p_up_intervals) if u_pk is None else max(0.0, u_pk))
            # Full-window free BMT/parent ratio over admissible censor intervals on common unbound nM basis:
            for i in range(len(lpf_r)):
                bmt_admissible_pos = (lloq_b_loc_r > 0.0) or (not lb_blq[i] and lbf_r[i] > 0.0) or (not loc_inc_rec and (lloq_b_rec_r > 0.0 or any(v > 0.0 for v in rbf_r)))
                if lp_blq[i] or lpf_r[i] <= 0.0:
                    if bmt_admissible_pos:
                        unbounded_bmt_ratio = True
                elif l_fp_r > 0.0 and u_fp_r > 0.0:
                    r_hi_i = ((lloq_b_loc_r if lb_blq[i] else lbf_r[i]) * u_fb_r + recirc_free_upper) / (lpf_r[i] * l_fp_r)
                    r_lo_i = ((0.0 if lb_blq[i] else lbf_r[i]) * l_fb_r) / (lpf_r[i] * u_fp_r)
                    obs_free_ratio_max = max(obs_free_ratio_max, r_hi_i)
                    obs_free_ratio_min = min(obs_free_ratio_min, r_lo_i)
            sys_intervals = [
                (
                    (0.0 if sp_blq[i] else spf_r[i]) / l_kbp_p_r + (0.0 if sb_blq[i] else sbf_r[i]) / l_kbp_b_r,
                    (lloq_p_rec_r if sp_blq[i] else spf_r[i]) / l_kbp_p_r + (lloq_b_rec_r if sb_blq[i] else sbf_r[i]) / l_kbp_b_r,
                )
                for i in range(len(spf_r))
            ]
            u_sk = censor_aware_t_bound(sys_intervals, alpha=alpha_tp, upper=True)
            if u_sk is None:
                holds.append(f"HOLD_{prefix}_CENSOR_AWARE_SYS_BOUND_UNESTIMABLE:{idx_tp}"); ok = False
                u_sk = max(hi for _, hi in sys_intervals)
            u_sys_series.append(u_sk)
            if any(not b for b in lb_blq):
                any_quant_loc_bmt = True
                recomp_u_loc_bmt_tot = max(recomp_u_loc_bmt_tot, u_lbt_cens)
            if any(not b for b in rb_blq):
                any_quant_rec_bmt = True
                recomp_u_rec_bmt_tot = max(recomp_u_rec_bmt_tot, u_rbt_cens)
            raw_max_loc_bmt_tot = max(raw_max_loc_bmt_tot, max(lbf_r))
            raw_max_rec_bmt_tot = max(raw_max_rec_bmt_tot, max(rbf_r))
            recomp_u_loc_bmt_free = max(recomp_u_loc_bmt_free, u_lbt_cens * u_fb_r)
            recomp_u_rec_bmt_free = max(recomp_u_rec_bmt_free, u_rbt_cens * u_fb_rec_r)
            raw_max_loc_bmt_free = max(raw_max_loc_bmt_free, max(lbf_r) * u_fb_r)
            raw_max_rec_bmt_free = max(raw_max_rec_bmt_free, max(rbf_r) * u_fb_rec_r)
        digest_mismatch = False
        if upstream_sample_ledger is None or not upstream_sample_ledger:
            ledger_issue = True
        else:
            if set(seen_b2b_sample_hours.keys()) != set(upstream_sample_ledger.keys()):
                ledger_issue = True
            elif any(abs(seen_b2b_sample_hours[k] - float(upstream_sample_ledger[k][0])) > 1e-6 for k in upstream_sample_ledger):
                ledger_issue = True
            elif any(
                seen_b2b_sample_matrices.get(k) != str(upstream_sample_ledger[k][2])
                or seen_b2b_sample_rec_matrices.get(k) != str(upstream_sample_ledger[k][3])
                or seen_b2b_sample_units.get(k) != str(upstream_sample_ledger[k][4])
                for k in upstream_sample_ledger
            ):
                ledger_issue = True
            else:
                for k_sid, (_, exp_row_sha, _, _, _) in upstream_sample_ledger.items():
                    if seen_b2b_sample_digests.get(k_sid) != str(exp_row_sha).lower():
                        digest_mismatch = True; break
        if ledger_issue:
            holds.append(f"HOLD_{prefix}_UPSTREAM_SAMPLE_LEDGER_INCOMPLETE_OR_DUPLICATE"); ok = False
        if digest_mismatch:
            holds.append(f"HOLD_{prefix}_UPSTREAM_ANALYTICAL_ROW_DIGEST_MISMATCH"); ok = False

    if not (is_strict_bool(ev.get("censoring_audit_passed")) and ev["censoring_audit_passed"]):
        fails.append(f"FAIL_{prefix}_CENSORING_AUDIT_MISSING"); ok = False
    if not (is_strict_bool(ev.get("intersample_peak_envelope_justified")) and ev["intersample_peak_envelope_justified"]):
        fails.append(f"FAIL_{prefix}_INTERSAMPLE_PEAK_UNJUSTIFIED"); ok = False
    env_res = _validate_and_apply_continuous_pk_envelope(
        ev.get("intersample_pk_envelope"),
        hours_seen=hours_seen, u_local_series=u_local_series,
        l_parent_all_series=l_parent_all_series,
        u_sys_series=u_sys_series, max_efficacy_start_h=0.0,
        expected_coating_article_id=(expected_coating_identity.get("coating_article_id") if expected_coating_identity else None),
        expected_evidence_scope=expected_scope,
        expected_compartment_id="BENCH_ELUTION_RECIRCULATION",
        fails=fails, holds=holds, prefix=prefix,
    )
    cont_ratio_min = float("inf")
    cont_ratio_max = 0.0
    cont_unbounded = False
    if env_res is None:
        ok = False
        enveloped_peak, enveloped_floor, enveloped_sys = float("inf"), -1.0, float("inf")
    else:
        enveloped_peak, enveloped_floor, enveloped_sys = env_res
        if tp_valid:
            cont_ratio_min, cont_ratio_max, cont_unbounded = _compute_continuous_bmt_parent_ratio_bounds(
                hours_seen, u_bmt_free_series, l_bmt_free_series, l_parent_all_series, u_parent_all_series,
                ev.get("intersample_pk_envelope"), fails=fails, prefix=prefix,
            )
    eff_unbounded_bmt_ratio = unbounded_bmt_ratio or cont_unbounded
    eff_obs_free_ratio_min = min(0.0 if obs_free_ratio_min == float("inf") else obs_free_ratio_min, cont_ratio_min)
    eff_obs_free_ratio_max = max(obs_free_ratio_max, cont_ratio_max)
    if not (is_strict_bool(ev.get("systemic_exposure_below_cap")) and ev["systemic_exposure_below_cap"]):
        fails.append(f"FAIL_{prefix}_SYSTEMIC_EXPOSURE_UNVERIFIED"); ok = False

    # Evaluate ALL 4 BMT triggers & bind mixture-specific therapeutic window covering full observed free ratio range!
    eff_loc_tot = max(float(bmt_loc_tot), raw_max_loc_bmt_tot, recomp_u_loc_bmt_tot)
    eff_loc_free = max(float(bmt_loc_free), raw_max_loc_bmt_free, recomp_u_loc_bmt_free)
    eff_rec_tot = max(float(bmt_rec_tot), raw_max_rec_bmt_tot, recomp_u_rec_bmt_tot)
    eff_rec_free = max(float(bmt_rec_free), raw_max_rec_bmt_free, recomp_u_rec_bmt_free)
    local_trig = any_quant_loc_bmt or (eff_loc_tot >= lloq_b_loc_min) or (eff_loc_free >= 0.10 * ceiling_l95)
    recirc_trig = any_quant_rec_bmt or (eff_rec_tot >= lloq_b_rec_min) or (eff_rec_free >= 0.10 * ceiling_l95)
    eff_ec50 = ec50_u95
    eff_ceiling = ceiling_l95
    if eff_unbounded_bmt_ratio and not (local_trig or recirc_trig):
        if ev.get("mixture_requalification_receipt") is None:
            holds.append(f"HOLD_{prefix}_UNBOUNDED_BMT_TO_PARENT_RATIO_UNDER_PARENT_BLQ"); ok = False
    if local_trig or recirc_trig or (eff_unbounded_bmt_ratio and ev.get("mixture_requalification_receipt") is not None):
        mix_ok, m_ec50, m_csafe = _validate_mixture_requal_receipt(
            ev.get("mixture_requalification_receipt"),
            expected_prod=expected_prod, expected_bank=expected_bank,
            expected_lot=expected_lot, expected_route=expected_route,
            expected_scope=expected_scope,
            expected_coating_identity=expected_coating_identity,
            parent_recorded_at_utc=parse_utc_iso_ts(ev.get("recorded_at_utc")),
            observed_bmt_to_parent_ratio_min=eff_obs_free_ratio_min,
            observed_bmt_to_parent_ratio_max=eff_obs_free_ratio_max,
            unbounded_ratio_under_parent_blq=eff_unbounded_bmt_ratio,
            fails=fails, holds=holds, prefix=prefix,
        )
        if not mix_ok or m_ec50 is None or m_csafe is None:
            ok = False
        else:
            eff_ec50 = max(eff_ec50, m_ec50)
            eff_ceiling = min(eff_ceiling, m_csafe)
            if float(u95_joint) >= eff_ceiling or float(parent_lo) < eff_ec50:
                fails.append(f"FAIL_{prefix}_EXPOSURE_BREACHES_TRIGGERED_MIXTURE_WINDOW"); ok = False

    if tp_valid and env_res is not None:
        if not (hours_seen[0] <= 24.0 and any(abs(h - 240.0) <= 12.0 for h in hours_seen) and washout_u_joint is not None):
            fails.append(f"FAIL_{prefix}_TIMEPOINT_WINDOW_MISSES_BURST_DAY10_OR_DAY21_WASHOUT"); ok = False
        if float(u95_joint) + 1e-4 < enveloped_peak or enveloped_peak >= eff_ceiling:
            fails.append(f"FAIL_{prefix}_RECOMPUTED_SIMULTANEOUS_PEAK_EXCEEDS_CLAIMED_OR_CSAFE"); ok = False
        if enveloped_floor < 0.0 or float(parent_lo) - 1e-4 > enveloped_floor or enveloped_floor < eff_ec50:
            fails.append(f"FAIL_{prefix}_RECOMPUTED_PARENT_FLOOR_MISMATCH_OR_BELOW_EC50"); ok = False
        if washout_u_joint is not None and (washout_u_joint >= 2.0 or washout_u_joint >= eff_ec50):
            fails.append(f"FAIL_{prefix}_DAY21_REPLICATE_WASHOUT_NOT_EXHAUSTED"); ok = False
        if enveloped_sys >= 0.5:
            fails.append(f"FAIL_{prefix}_RECOMPUTED_SYSTEMIC_U95_GE_0P5NM"); ok = False
        if float(bmt_loc_tot) + 1e-4 < recomp_u_loc_bmt_tot or float(bmt_loc_free) + 1e-4 < recomp_u_loc_bmt_free:
            fails.append(f"FAIL_{prefix}_CLAIMED_LOCAL_BMT_UNDERSTATES_RAW_REPLICATES"); ok = False
        if float(bmt_rec_tot) + 1e-4 < recomp_u_rec_bmt_tot or float(bmt_rec_free) + 1e-4 < recomp_u_rec_bmt_free:
            fails.append(f"FAIL_{prefix}_CLAIMED_RECIRC_BMT_UNDERSTATES_RAW_REPLICATES"); ok = False
    return ok


def evaluate_gate41_deucravacitinib_tyk2(rec: Mapping[str, Any]) -> dict[str, Any]:
    """GATE-41 (IIP-0063): Fail-closed 3-phase deucravacitinib adjudicator with raw analytical B-0a/B-2b, raw paired B-2, coating-bound B-0a-exact, matched-vehicle B-3, & gap-checked B-4."""
    phase = str(rec.get("phase", "EXACT_PRODUCT")).strip().upper()
    if phase not in ("ROUTE_FREE_B0A", "BENCH_UNEDITED", "EXACT_PRODUCT"):
        return {
            "gate": "GATE-41", "verdict": "FAIL", "release_authorizing": False,
            "live_ledger_authenticated": False, "upstream_archive_verification": OFFLINE_ARCHIVE_NOTE,
            "product_id": rec.get("product_id"), "required_switch": None,
            "failures": ["FAIL_INVALID_PHASE"], "holds": [],
        }

    fails: list[str] = []
    holds: list[str] = []
    spec: Optional[Mapping[str, Any]] = None
    scope_track = "ROUTE_FREE_B0A"
    mat_ev = sw_ev = g0v_ev = g31_ev = None

    b0b_raw = rec.get("b0b_evidence")
    coat_id: Optional[dict[str, str]] = None
    if phase != "ROUTE_FREE_B0A" and isinstance(b0b_raw, Mapping):
        if all(is_nonempty_str(b0b_raw.get(k)) for k in COATING_IDENTITY_KEYS):
            coat_id = {k: str(b0b_raw[k]).strip() for k in sorted(COATING_IDENTITY_KEYS)}

    if phase == "ROUTE_FREE_B0A":
        _check_allowed_keys(rec, GATE41_B0A_KEYS, fails, "GATE41_B0A")
    else:
        spec, scope_track, b_fails, b_holds, mat_ev, sw_ev, g0v_ev, g31_ev = _validate_canonical_binding_v6(
            rec, allow_design_a=False, coating_gate=True, phase=phase,
            expected_coating_identity=coat_id,
        )
        fails.extend(b_fails)
        holds.extend(b_holds)
        if phase == "BENCH_UNEDITED":
            _check_forbidden_keys(rec, GATE41_EXACT_ONLY_KEYS, fails, "FAIL_BENCH_PHASE_FORBIDS_EXACT_OR_INVIVO_FIELDS")
            _check_allowed_keys(rec, GATE41_BENCH_KEYS, fails, "GATE41_BENCH")
        else:
            _check_allowed_keys(rec, GATE41_EXACT_KEYS, fails, "GATE41")

    # Gate B-0a: raw measured f_u maps + raw 7-point concentration-response bracketing + analysis_record_sha256!
    b0a_extras = frozenset({
        "endpoints_bracketed", "analysis_record_sha256",
        "lloq_parent_by_matrix_nM", "lloq_bmt_by_matrix_nM",
        "fu_parent_by_matrix", "fu_bmt_by_matrix",
        "tested_free_conc_grid_nM", "efficacy_inhibition_pct_grid",
        "efficacy_beta_protection_pct_grid", "efficacy_nk_suppression_pct_grid", "efficacy_iec_ibmir_pct_grid",
        "safety_sprouting_pct_grid", "safety_nkg2a_pct_grid",
        "safety_cd94_pct_grid", "safety_il10_retention_pct_grid",
        "safety_replicates_by_conc",
        "efficacy_replicates_by_conc", "b0a_analysis_receipt",
        "ec50_eff_u95_free_nM", "c_safe_max_bench_l95_free_nM",
    })
    b0a_ev = _validate_content_receipt(
        rec.get("b0a_evidence"),
        expected_stage="B-0a", expected_prod=None, expected_bank=None,
        expected_lot=None, expected_route=None, forbid_route=True,
        expected_scope="route_free", allowed_extra_keys=b0a_extras,
        fails=fails, holds=holds,
        missing_hold="HOLD_GATE_B0A_RECEIPT_MISSING",
        fail_code="FAIL_GATE_B0A_FAILED",
        mismatch_code="FAIL_GATE_B0A_SCOPE_MISMATCH",
    )
    b0a_ok = b0a_ev is not None and b0a_ev.get("verdict") == "PASS"
    ec50_u95: Optional[float] = None
    csafe_bench: Optional[float] = None
    lloq_bmt_min: Optional[float] = None
    lloq_parent_map_f: Optional[dict[str, float]] = None
    lloq_bmt_map_f: Optional[dict[str, float]] = None
    fu_parent_map_f: Optional[dict[str, float]] = None
    fu_bmt_map_f: Optional[dict[str, float]] = None
    if b0a_ev is not None:
        if not (is_strict_bool(b0a_ev.get("endpoints_bracketed")) and b0a_ev["endpoints_bracketed"]):
            fails.append("FAIL_GATE_B0A_ENDPOINTS_UNBRACKETED"); b0a_ok = False
        if not is_valid_sha256_hex(b0a_ev.get("analysis_record_sha256")):
            fails.append("FAIL_GATE_B0A_MISSING_ANALYSIS_RECORD_SHA256"); b0a_ok = False
        lp_map = b0a_ev.get("lloq_parent_by_matrix_nM")
        lb_map = b0a_ev.get("lloq_bmt_by_matrix_nM")
        fp_map = b0a_ev.get("fu_parent_by_matrix")
        fb_map = b0a_ev.get("fu_bmt_by_matrix")
        if not (isinstance(lp_map, Mapping) and set(lp_map.keys()) == REQUIRED_3_MATRICES and isinstance(lb_map, Mapping) and set(lb_map.keys()) == REQUIRED_3_MATRICES):
            fails.append("FAIL_GATE_B0A_MISSING_PER_MATRIX_LLOQ_MAP"); b0a_ok = False
        else:
            vals_p = list(lp_map.values())
            vals_b = list(lb_map.values())
            if not all(is_finite_num(x) and 0.0 < float(x) <= 0.2 for x in vals_p + vals_b):
                fails.append("FAIL_GATE_B0A_LLOQ_INVALID_OR_GT_0P2NM"); b0a_ok = False
            else:
                lloq_parent_map_f = {str(k): float(v) for k, v in lp_map.items()}
                lloq_bmt_map_f = {str(k): float(v) for k, v in lb_map.items()}
                lloq_bmt_min = min(lloq_bmt_map_f.values())
        if not (isinstance(fp_map, Mapping) and set(fp_map.keys()) == REQUIRED_3_MATRICES and isinstance(fb_map, Mapping) and set(fb_map.keys()) == REQUIRED_3_MATRICES and all(is_finite_num(x) and 0.0 < float(x) <= 1.0 for x in list(fp_map.values()) + list(fb_map.values()))):
            fails.append("FAIL_GATE_B0A_MISSING_OR_INVALID_MEASURED_FU_BY_MATRIX"); b0a_ok = False
        else:
            fu_parent_map_f = {str(k): float(v) for k, v in fp_map.items()}
            fu_bmt_map_f = {str(k): float(v) for k, v in fb_map.items()}
        e50 = b0a_ev.get("ec50_eff_u95_free_nM")
        csb = b0a_ev.get("c_safe_max_bench_l95_free_nM")
        if not (is_finite_num(e50) and is_finite_num(csb)):
            holds.append("HOLD_GATE_B0A_MISSING_BENCH_WINDOW"); b0a_ok = False
        elif float(e50) <= 0.0 or float(csb) <= 0.0:
            fails.append("FAIL_GATE_B0A_NONPOSITIVE_CONCENTRATION"); b0a_ok = False
        else:
            ec50_u95, csafe_bench = float(e50), float(csb)
            if csafe_bench / ec50_u95 < 2.0:
                fails.append("FAIL_GATE_B0A_MARGIN_BELOW_2X"); b0a_ok = False
            # Verify raw concentration-response observations actually bracket BOTH EC50_eff_U95 AND C_safe_max_L95!
            cgrid = b0a_ev.get("tested_free_conc_grid_nM")
            egrid = b0a_ev.get("efficacy_inhibition_pct_grid")
            eb_g = b0a_ev.get("efficacy_beta_protection_pct_grid")
            en_g = b0a_ev.get("efficacy_nk_suppression_pct_grid")
            ei_g = b0a_ev.get("efficacy_iec_ibmir_pct_grid")
            s_sp = b0a_ev.get("safety_sprouting_pct_grid")
            s_nk = b0a_ev.get("safety_nkg2a_pct_grid")
            s_cd94 = b0a_ev.get("safety_cd94_pct_grid")
            s_il = b0a_ev.get("safety_il10_retention_pct_grid")
            if not (
                isinstance(cgrid, list) and len(cgrid) >= 7
                and all(isinstance(g, list) and len(g) == len(cgrid) and all(is_finite_num(x) for x in g) for g in (cgrid, egrid, eb_g, en_g, ei_g, s_sp, s_nk, s_cd94, s_il))
            ):
                fails.append("FAIL_GATE_B0A_MISSING_RAW_CONC_RESPONSE_GRID"); b0a_ok = False
            else:
                cg = [float(x) for x in cgrid]
                eg = [float(x) for x in egrid]
                ebg = [float(x) for x in eb_g]
                eng = [float(x) for x in en_g]
                eig = [float(x) for x in ei_g]
                ss = [float(x) for x in s_sp]
                sn = [float(x) for x in s_nk]
                sc94 = [float(x) for x in s_cd94]
                si = [float(x) for x in s_il]
                pos_c = [c for c in cg if c > 0.0]
                if cg[0] != 0.0 or any(cg[i] >= cg[i + 1] for i in range(len(cg) - 1)) or not pos_c:
                    fails.append("FAIL_GATE_B0A_INVALID_CONC_GRID_ORDER"); b0a_ok = False
                elif not (min(pos_c) < ec50_u95 < csafe_bench < max(cg)):
                    fails.append("FAIL_GATE_B0A_BOUNDS_NOT_OBSERVATION_BRACKETED"); b0a_ok = False
                else:
                    # Statistically qualified two-sided bracketing across ALL 3 Draft B s5 biological efficacy endpoints
                    # (beta cytokine protection, NK cytokine suppression, endothelial IBMIR marker suppression):
                    if any(abs(eg[i] - min(ebg[i], eng[i], eig[i])) > 0.5 for i in range(len(cg))):
                        fails.append("FAIL_GATE_B0A_OPERATIVE_EFFICACY_GRID_NOT_CONJUNCTIVE_MIN_OF_3_ENDPOINTS"); b0a_ok = False
                    veh_ok = (max(eg[0], ebg[0], eng[0], eig[0]) <= 15.0 and ss[0] >= 95.0 and sn[0] >= 95.0 and sc94[0] >= 95.0 and si[0] >= 95.0)
                    eff_at_or_below = [eg[i] for i in range(len(cg)) if cg[i] <= ec50_u95 + 1e-9]
                    max_below_50_c = max((cg[i] for i in range(len(cg)) if eg[i] < 50.0), default=0.0)
                    eff_crossed = any(v < 50.0 for v in eff_at_or_below) and any(v >= 50.0 for v in eff_at_or_below) and (eg[-1] >= 50.0) and (ec50_u95 >= max_below_50_c - 1e-9)
                    s_reps = b0a_ev.get("safety_replicates_by_conc")
                    rep_keys = ("sprouting_pct", "nkg2a_pct", "cd94_pct", "il10_retention_pct")
                    rep_floors = (90.0, 85.0, 85.0, 80.0001)
                    rep_grids = (ss, sn, sc94, si)
                    if not isinstance(s_reps, list) or len(s_reps) != len(cg):
                        fails.append("FAIL_GATE_B0A_MISSING_SAFETY_REPLICATES_BY_CONC"); b0a_ok = False
                    else:
                        qual_safe_idx = -1
                        reps_ok = True
                        s_row_req_keys = set(rep_keys) | {"unit_ids", "matched_vehicle_record_id", "raw_unit_measurements"}
                        s_first_uids: Optional[list[str]] = None
                        for i_c, rmap in enumerate(s_reps):
                            if isinstance(rmap, Mapping) and rmap.get("raw_unit_measurements") is None:
                                holds.append("HOLD_GATE_B0A_MISSING_MATCHED_VEHICLE_RAW_DATA"); reps_ok = False; b0a_ok = False; break
                            if not isinstance(rmap, Mapping) or set(rmap.keys()) != s_row_req_keys or not is_nonempty_str(rmap.get("matched_vehicle_record_id")):
                                fails.append(f"FAIL_GATE_B0A_MALFORMED_SAFETY_REPLICATES:{i_c}"); reps_ok = False; b0a_ok = False; break
                            mv_rec_s = str(rmap["matched_vehicle_record_id"]).strip().upper()
                            raw_s_map = rmap.get("raw_unit_measurements")
                            if not isinstance(raw_s_map, Mapping) or set(raw_s_map.keys()) != set(rep_keys):
                                fails.append(f"FAIL_GATE_B0A_MALFORMED_SAFETY_REPLICATES:{i_c}"); reps_ok = False; b0a_ok = False; break
                            su_raw = rmap.get("unit_ids")
                            if not (isinstance(su_raw, list) and len(su_raw) >= 6 and all(is_nonempty_str(u) for u in su_raw)):
                                fails.append(f"FAIL_GATE_B0A_UNDERPOWERED_OR_INVALID_SAFETY_UNITS:{i_c}"); reps_ok = False; b0a_ok = False; break
                            su_norm = [str(u).strip().upper() for u in su_raw]
                            if len(set(su_norm)) != len(su_norm):
                                fails.append(f"FAIL_GATE_B0A_DUPLICATE_SAFETY_UNIT_IDS:{i_c}"); reps_ok = False; b0a_ok = False; break
                            if s_first_uids is None:
                                s_first_uids = su_norm
                            elif su_norm != s_first_uids:
                                fails.append(f"FAIL_GATE_B0A_SAFETY_UNIT_IDS_MISMATCH:{i_c}"); reps_ok = False; b0a_ok = False; break
                            all_ep_l95_safe = True
                            for rk, rfl, rgr in zip(rep_keys, rep_floors, rep_grids):
                                arr = rmap.get(rk)
                                ep_raw_s = raw_s_map.get(rk)
                                if not (
                                    isinstance(arr, list) and len(arr) == len(su_norm) and all(is_finite_num(x) for x in arr)
                                    and isinstance(ep_raw_s, Mapping) and set(ep_raw_s.keys()) == {"vehicle_record_id", "treated", "vehicle"}
                                    and is_nonempty_str(ep_raw_s.get("vehicle_record_id"))
                                    and str(ep_raw_s["vehicle_record_id"]).strip().upper() == mv_rec_s
                                    and isinstance(ep_raw_s.get("treated"), list) and len(ep_raw_s["treated"]) == len(su_norm)
                                    and isinstance(ep_raw_s.get("vehicle"), list) and len(ep_raw_s["vehicle"]) == len(su_norm)
                                    and all(is_finite_num(x) and float(x) >= 0.0 for x in ep_raw_s["treated"])
                                    and all(is_finite_num(x) and float(x) > 0.0 for x in ep_raw_s["vehicle"])
                                ):
                                    fails.append(f"FAIL_GATE_B0A_INVALID_SAFETY_REPLICATES:{i_c}:{rk}"); reps_ok = False; b0a_ok = False; all_ep_l95_safe = False; break
                                recomp_s = [100.0 * float(ep_raw_s["treated"][uj]) / float(ep_raw_s["vehicle"][uj]) for uj in range(len(su_norm))]
                                sub_s = [float(x) for x in arr]
                                if any(abs(recomp_s[uj] - sub_s[uj]) > 0.5 for uj in range(len(su_norm))):
                                    fails.append(f"FAIL_GATE_B0A_NORMALIZED_PCT_MISMATCH_VS_MATCHED_VEHICLE:{i_c}:{rk}"); reps_ok = False; b0a_ok = False; all_ep_l95_safe = False; break
                                af = recomp_s
                                m_af = sum(af) / len(af)
                                if abs(m_af - rgr[i_c]) > 0.5:
                                    fails.append(f"FAIL_GATE_B0A_GRID_MEAN_MISMATCH_VS_REPLICATES:{i_c}:{rk}"); reps_ok = False; b0a_ok = False
                                alpha_safe_b0a = 0.05 / float(4 * len(cg))
                                sb = sample_t_one_sided_bounds(af, alpha=alpha_safe_b0a)
                                if sb is None:
                                    holds.append("HOLD_GATE_B0A_DEGENERATE_ZERO_VARIANCE_UNESTIMABLE")
                                    l95_af = float("-inf")
                                else:
                                    # Audit Gaussian/unimodal Student-t precondition at n >= 6 (Q-Q r >= 0.88 & Shapiro-Wilk p >= 0.05)
                                    # AND enforce unconditional single-unit safety floor (no individual unit below floor)!
                                    qq_s = paired_diff_normality_qq_r(af)
                                    sw_s = shapiro_wilk_test(af)
                                    if qq_s is None or qq_s < 0.88 or sw_s is None or sw_s[1] < 0.05:
                                        if cg[i_c] <= csafe_bench + 1e-9:
                                            holds.append(f"HOLD_GATE_B0A_NONNORMAL_OR_SKEWED_SAFETY_REPLICATES:{i_c}:{rk}")
                                        l95_af = float("-inf")
                                    else:
                                        l95_af = sb[1]
                                if l95_af < rfl or min(af) < rfl:
                                    all_ep_l95_safe = False
                            if all_ep_l95_safe and qual_safe_idx == i_c - 1:
                                qual_safe_idx = i_c
                        if reps_ok:
                            max_qual_safe_c = cg[qual_safe_idx] if qual_safe_idx >= 0 else -1.0
                            safe_breached_above = any(
                                (ss[i] < 90.0 or sn[i] < 85.0 or sc94[i] < 85.0 or si[i] <= 80.0)
                                for i in range(len(cg)) if cg[i] > max_qual_safe_c + 1e-9
                            )
                            if csafe_bench > max_qual_safe_c + 1e-9:
                                fails.append("FAIL_GATE_B0A_CSAFE_EXCEEDS_QUALIFIED_TESTED_SAFE_CONC"); b0a_ok = False
                            elif not (veh_ok and eff_crossed and safe_breached_above):
                                fails.append("FAIL_GATE_B0A_RAW_CONC_RESPONSE_CONTRADICTS_WINDOW"); b0a_ok = False
                    # Independent efficacy unit replicates + content-hashed analysis receipt verifying EC50_eff_U95!
                    e_reps = b0a_ev.get("efficacy_replicates_by_conc")
                    b0a_an = b0a_ev.get("b0a_analysis_receipt")
                    if e_reps is None or b0a_an is None:
                        holds.append("HOLD_GATE_B0A_MISSING_EFFICACY_REPLICATES_OR_ANALYSIS_RECEIPT"); b0a_ok = False
                    elif not isinstance(e_reps, list) or len(e_reps) != len(cg):
                        fails.append("FAIL_GATE_B0A_MALFORMED_EFFICACY_REPLICATES"); b0a_ok = False
                    else:
                        an_keys = frozenset({
                            "analysis_method", "efficacy_combination_rule", "efficacy_endpoints_tested",
                            "efficacy_unit_ids", "safety_unit_ids",
                            "raw_efficacy_replicates_sha256", "raw_safety_replicates_sha256",
                            "analysis_record_sha256",
                            "ec50_eff_u95_free_nM", "c_safe_max_bench_l95_free_nM", "receipt_sha256",
                        })
                        req_eff_eps = [
                            "beta_cytokine_protection_pct",
                            "iec_ibmir_marker_suppression_pct",
                            "nk_cytokine_suppression_pct",
                        ]
                        if not isinstance(b0a_an, Mapping) or set(b0a_an.keys()) != an_keys:
                            fails.append("FAIL_GATE_B0A_MALFORMED_ANALYSIS_RECEIPT"); b0a_ok = False
                        else:
                            asha = b0a_an.get("receipt_sha256")
                            euids = b0a_an.get("efficacy_unit_ids")
                            suids_an = b0a_an.get("safety_unit_ids")
                            eps_t = b0a_an.get("efficacy_endpoints_tested")
                            if (
                                not is_valid_sha256_hex(asha) or compute_receipt_sha256(b0a_an) != asha
                                or b0a_an.get("analysis_method") != "SIMULTANEOUS_BONFERRONI_GRID_BRACKET_STUDENT_T"
                                or b0a_an.get("efficacy_combination_rule") != "CONJUNCTIVE_MAX_EC50_U95_ACROSS_ALL_3_ENDPOINTS"
                                or not (isinstance(eps_t, list) and sorted(str(x) for x in eps_t) == req_eff_eps)
                                or b0a_an.get("raw_efficacy_replicates_sha256") != sha256_bytes(canonical_json_bytes(e_reps))
                                or (s_reps is not None and b0a_an.get("raw_safety_replicates_sha256") != sha256_bytes(canonical_json_bytes(s_reps)))
                                or b0a_an.get("analysis_record_sha256") != b0a_ev.get("analysis_record_sha256")
                                or not (isinstance(euids, list) and len(euids) >= 6 and all(is_nonempty_str(u) for u in euids) and len({str(u).strip().upper() for u in euids}) == len(euids))
                                or not (isinstance(suids_an, list) and len(suids_an) >= 6 and all(is_nonempty_str(u) for u in suids_an) and len({str(u).strip().upper() for u in suids_an}) == len(suids_an))
                                or (s_reps is not None and isinstance(s_reps, list) and s_reps and isinstance(s_reps[0], Mapping) and isinstance(s_reps[0].get("unit_ids"), list) and [str(u).strip().upper() for u in suids_an] != [str(u).strip().upper() for u in s_reps[0]["unit_ids"]])
                                or not (is_finite_num(b0a_an.get("ec50_eff_u95_free_nM")) and abs(float(b0a_an["ec50_eff_u95_free_nM"]) - ec50_u95) <= 1e-6)
                                or not (is_finite_num(b0a_an.get("c_safe_max_bench_l95_free_nM")) and abs(float(b0a_an["c_safe_max_bench_l95_free_nM"]) - csafe_bench) <= 1e-6)
                            ):
                                fails.append("FAIL_GATE_B0A_ANALYSIS_RECEIPT_MISMATCH"); b0a_ok = False
                            else:
                                exp_eu = [str(u).strip().upper() for u in euids]
                                eff_l95_min_by_i: list[float] = []
                                ereps_ok = True
                                ep_grid_pairs = (
                                    ("beta_cytokine_protection_pct", ebg),
                                    ("nk_cytokine_suppression_pct", eng),
                                    ("iec_ibmir_marker_suppression_pct", eig),
                                )
                                for i_c, erow in enumerate(e_reps):
                                    if isinstance(erow, Mapping) and (erow.get("matched_vehicle_record_id") is None or erow.get("raw_unit_measurements") is None):
                                        holds.append("HOLD_GATE_B0A_MISSING_MATCHED_VEHICLE_RAW_DATA"); ereps_ok = False; b0a_ok = False; break
                                    if not isinstance(erow, Mapping) or set(erow.keys()) != {"unit_ids", "matched_vehicle_record_id", "raw_unit_measurements", "beta_cytokine_protection_pct", "nk_cytokine_suppression_pct", "iec_ibmir_marker_suppression_pct"} or not is_nonempty_str(erow.get("matched_vehicle_record_id")):
                                        fails.append(f"FAIL_GATE_B0A_MALFORMED_EFFICACY_REPLICATES:{i_c}"); ereps_ok = False; b0a_ok = False; break
                                    mv_rec_e = str(erow["matched_vehicle_record_id"]).strip().upper()
                                    raw_e_map = erow.get("raw_unit_measurements")
                                    if not isinstance(raw_e_map, Mapping) or set(raw_e_map.keys()) != {k for k, _ in ep_grid_pairs}:
                                        fails.append(f"FAIL_GATE_B0A_MALFORMED_EFFICACY_REPLICATES:{i_c}"); ereps_ok = False; b0a_ok = False; break
                                    ru = erow.get("unit_ids")
                                    if not (isinstance(ru, list) and [str(u).strip().upper() for u in ru] == exp_eu):
                                        fails.append(f"FAIL_GATE_B0A_INVALID_EFFICACY_REPLICATES:{i_c}"); ereps_ok = False; b0a_ok = False; break
                                    ep_l95s: list[float] = []
                                    for epk, ep_grid in ep_grid_pairs:
                                        rv = erow.get(epk)
                                        ep_raw_e = raw_e_map.get(epk)
                                        if not (
                                            isinstance(rv, list) and len(rv) == len(exp_eu) and all(is_finite_num(x) for x in rv)
                                            and isinstance(ep_raw_e, Mapping) and set(ep_raw_e.keys()) == {"vehicle_record_id", "treated", "vehicle"}
                                            and is_nonempty_str(ep_raw_e.get("vehicle_record_id"))
                                            and str(ep_raw_e["vehicle_record_id"]).strip().upper() == mv_rec_e
                                            and isinstance(ep_raw_e.get("treated"), list) and len(ep_raw_e["treated"]) == len(exp_eu)
                                            and isinstance(ep_raw_e.get("vehicle"), list) and len(ep_raw_e["vehicle"]) == len(exp_eu)
                                            and all(is_finite_num(x) and float(x) >= 0.0 for x in ep_raw_e["treated"])
                                            and all(is_finite_num(x) and float(x) > 0.0 for x in ep_raw_e["vehicle"])
                                        ):
                                            fails.append(f"FAIL_GATE_B0A_INVALID_EFFICACY_REPLICATES:{i_c}"); ereps_ok = False; b0a_ok = False; break
                                        recomp_e = [100.0 * (1.0 - float(ep_raw_e["treated"][uj]) / float(ep_raw_e["vehicle"][uj])) for uj in range(len(exp_eu))]
                                        sub_e = [float(x) for x in rv]
                                        if any(abs(recomp_e[uj] - sub_e[uj]) > 0.5 for uj in range(len(exp_eu))):
                                            fails.append(f"FAIL_GATE_B0A_EFFICACY_NORMALIZED_PCT_MISMATCH_VS_MATCHED_VEHICLE:{i_c}:{epk}"); ereps_ok = False; b0a_ok = False; break
                                        rf = recomp_e
                                        if abs((sum(rf) / len(rf)) - ep_grid[i_c]) > 0.5:
                                            fails.append(f"FAIL_GATE_B0A_EFFICACY_GRID_MISMATCH_VS_REPLICATES:{i_c}"); ereps_ok = False; b0a_ok = False
                                        alpha_eff_b0a = 0.05 / float(3 * len(cg))
                                        eb = sample_t_one_sided_bounds(rf, alpha=alpha_eff_b0a)
                                        if eb is None:
                                            holds.append("HOLD_GATE_B0A_DEGENERATE_ZERO_VARIANCE_UNESTIMABLE")
                                            ep_l95s.append(float("-inf"))
                                        else:
                                            qq_e = paired_diff_normality_qq_r(rf)
                                            sw_e = shapiro_wilk_test(rf)
                                            if qq_e is None or qq_e < 0.88 or sw_e is None or sw_e[1] < 0.05:
                                                if cg[i_c] <= ec50_u95 + 1e-9:
                                                    holds.append(f"HOLD_GATE_B0A_NONNORMAL_OR_SKEWED_EFFICACY_REPLICATES:{i_c}:{epk}")
                                                ep_l95s.append(float("-inf"))
                                            else:
                                                ep_l95s.append(eb[1])
                                    if not ereps_ok:
                                        break
                                    eff_l95_min_by_i.append(min(ep_l95s))
                                if ereps_ok:
                                    idxs_le_ec = [i for i in range(len(cg)) if cg[i] <= ec50_u95 + 1e-9]
                                    if not idxs_le_ec or eff_l95_min_by_i[idxs_le_ec[-1]] < 50.0:
                                        holds.append("HOLD_GATE_B0A_EC50_U95_UNSUBSTANTIATED_BY_EFFICACY_REPLICATES"); b0a_ok = False
                                    elif any(eff_l95_min_by_i[i_w] < 50.0 for i_w in range(idxs_le_ec[-1], len(cg)) if cg[i_w] <= csafe_bench + 1e-9):
                                        holds.append("HOLD_GATE_B0A_NONMONOTONIC_INTERIOR_EFFICACY_DIP"); b0a_ok = False

    if phase == "ROUTE_FREE_B0A":
        verdict = "FAIL" if fails else ("HOLD" if holds else "PASS_ROUTE_FREE_B0A_ONLY")
        return {
            "gate": "GATE-41", "phase": phase, "scope_track": scope_track, "verdict": verdict,
            "release_authorizing": False, "live_ledger_authenticated": False,
            "upstream_archive_verification": OFFLINE_ARCHIVE_NOTE,
            "product_id": None, "required_switch": None, "failures": fails, "holds": holds,
        }

    prod_s = str(rec.get("product_id", "")).strip()
    bank_s = str(rec.get("bank_id", "")).strip()
    lot_s = str(rec.get("lot_id", "")).strip()
    route_s = str(rec.get("route_id", "")).strip().upper()

    b0b_ev = _validate_content_receipt(
        b0b_raw,
        expected_stage="B-0b", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="bench_unedited",
        expected_parent=b0a_ev,
        allowed_extra_keys=COATING_IDENTITY_KEYS | frozenset({
            "coating_thickness_um", "worst_face_o2_mmhg", "local_ph_min", "local_ph_max",
            "mass_balance_margin_verified",
            "route_clearance_l_per_day", "target_total_conc_nM", "active_duration_days",
            "loaded_api_mass_mg", "usable_recovery_fraction",
            "provisional_pk_model_receipt",
        }),
        fails=fails, holds=holds,
        missing_hold="HOLD_GATE_B0B_SIZING_O2_MISSING",
        fail_code="FAIL_GATE_B0B_SIZING_O2_FAILED",
        mismatch_code="FAIL_GATE_B0B_SCOPE_MISMATCH",
    )
    b0b_ok = b0b_ev is not None and b0b_ev.get("verdict") == "PASS"
    if b0b_ev is not None:
        coat_id = _extract_and_validate_coating_identity(b0b_ev, expected=None, fails=fails, stage="B-0b")
        if coat_id is None:
            b0b_ok = False
        th = b0b_ev.get("coating_thickness_um")
        o2 = b0b_ev.get("worst_face_o2_mmhg")
        ph_lo = b0b_ev.get("local_ph_min")
        ph_hi = b0b_ev.get("local_ph_max")
        if not (is_finite_num(th) and 0.0 < float(th) <= 5.0):
            fails.append("FAIL_GATE_B0B_COATING_THICKNESS_GT_5UM"); b0b_ok = False
        if not (is_finite_num(o2) and float(o2) >= 40.0):
            fails.append("FAIL_GATE_B0B_WORST_FACE_O2_BELOW_40MMHG"); b0b_ok = False
        if not (is_finite_num(ph_lo) and is_finite_num(ph_hi) and 7.25 <= float(ph_lo) <= float(ph_hi) <= 7.45):
            fails.append("FAIL_GATE_B0B_LOCAL_PH_OUTSIDE_7P25_7P45"); b0b_ok = False
        if not (is_strict_bool(b0b_ev.get("mass_balance_margin_verified")) and b0b_ev["mass_balance_margin_verified"]):
            fails.append("FAIL_GATE_B0B_MASS_BALANCE_MARGIN_UNVERIFIED"); b0b_ok = False
        rc_l = b0b_ev.get("route_clearance_l_per_day")
        tc_nm = b0b_ev.get("target_total_conc_nM")
        dur_d = b0b_ev.get("active_duration_days")
        ld_mg = b0b_ev.get("loaded_api_mass_mg")
        u_rec = b0b_ev.get("usable_recovery_fraction")
        rc_bounds_by_route = {"R3P": (3.0, 12.0), "R1": (3.0, 12.0), "R2": (10.0, 50.0)}
        rc_lo_r, rc_hi_r = rc_bounds_by_route.get(route_s, (3.0, 50.0))
        if not (
            all(is_finite_num(x) for x in (rc_l, tc_nm, dur_d, ld_mg, u_rec))
            and float(rc_l) > 0.0 and float(tc_nm) > 0.0 and float(dur_d) >= 10.0
            and float(ld_mg) > 0.0 and 0.0 < float(u_rec) <= 1.0
        ):
            fails.append("FAIL_GATE_B0B_MISSING_QUANTITATIVE_MASS_BALANCE_INPUTS"); b0b_ok = False
        else:
            if not (rc_lo_r <= float(rc_l) <= rc_hi_r):
                fails.append("FAIL_GATE_B0B_ROUTE_CLEARANCE_OUT_OF_RANGE"); b0b_ok = False
            if float(u_rec) > 0.85 + 1e-12:
                fails.append("FAIL_GATE_B0B_USABLE_RECOVERY_EXCEEDS_85PCT"); b0b_ok = False
            # Deucravacitinib MW = 425.47 g/mol -> req_mg = L/d * nmol/L * 1e-9 * 425470 mg/mol * days
            req_api_mg = float(rc_l) * float(tc_nm) * 1e-9 * 425470.0 * float(dur_d)
            if float(ld_mg) * float(u_rec) + 1e-9 < req_api_mg:
                fails.append("FAIL_GATE_B0B_LOADED_API_BELOW_QUANTITATIVE_MASS_REQUIREMENT"); b0b_ok = False

        # B-0a-bound provisional PK & exposure feasibility gate (must pass before authorizing bench B-1/B-2!)
        pk_mod = b0b_ev.get("provisional_pk_model_receipt")
        pk_mod_keys = frozenset({
            "b0a_receipt_sha256", "pk_model_protocol_sha256",
            "modeled_day1_burst_pct",
            "modeled_days0_10_parent_l95_free_nM",
            "modeled_days0_21_combined_peak_u95_free_nM",
            "modeled_systemic_combined_cmax_u95_total_nM",
            "alpha_conc", "alpha_fu_parent", "alpha_fu_bmt",
            "used_marginal_u95_sum", "lloq_censoring_allocated",
            "model_receipt_sha256",
        })
        if pk_mod is None:
            holds.append("HOLD_GATE_B0B_PROVISIONAL_PK_MODEL_MISSING"); b0b_ok = False
        elif not isinstance(pk_mod, Mapping) or set(pk_mod.keys()) != pk_mod_keys:
            fails.append("FAIL_GATE_B0B_PROVISIONAL_PK_MODEL_INVALID"); b0b_ok = False
        else:
            pm_sha = pk_mod.get("model_receipt_sha256")
            b0a_pin = pk_mod.get("b0a_receipt_sha256")
            prot_sha = pk_mod.get("pk_model_protocol_sha256")
            m_burst = pk_mod.get("modeled_day1_burst_pct")
            m_d10_l95 = pk_mod.get("modeled_days0_10_parent_l95_free_nM")
            m_d21_pk = pk_mod.get("modeled_days0_21_combined_peak_u95_free_nM")
            m_sys_pk = pk_mod.get("modeled_systemic_combined_cmax_u95_total_nM")
            m_ac = pk_mod.get("alpha_conc")
            m_afp = pk_mod.get("alpha_fu_parent")
            m_afb = pk_mod.get("alpha_fu_bmt")
            if (
                not is_valid_sha256_hex(pm_sha)
                or sha256_bytes(canonical_json_bytes({k: v for k, v in pk_mod.items() if k != "model_receipt_sha256"})) != str(pm_sha)
                or not is_valid_sha256_hex(prot_sha)
                or not is_valid_sha256_hex(b0a_pin)
                or (b0a_ev is not None and str(b0a_pin) != str(b0a_ev.get("receipt_sha256")))
                or not (is_strict_bool(pk_mod.get("used_marginal_u95_sum")) and pk_mod["used_marginal_u95_sum"] is False)
                or not (is_strict_bool(pk_mod.get("lloq_censoring_allocated")) and pk_mod["lloq_censoring_allocated"] is True)
                or not all(is_finite_num(x) for x in (m_burst, m_d10_l95, m_d21_pk, m_sys_pk, m_ac, m_afp, m_afb))
                or not (float(m_ac) > 0.0 and float(m_afp) > 0.0 and float(m_afb) > 0.0 and float(m_ac) + float(m_afp) + float(m_afb) <= 0.05 + 1e-12)
                or float(m_d10_l95) <= 0.0 or float(m_d21_pk) < float(m_d10_l95) or float(m_sys_pk) < 0.0
            ):
                fails.append("FAIL_GATE_B0B_PROVISIONAL_PK_MODEL_INVALID"); b0b_ok = False
            else:
                if not (0.0 < float(m_burst) <= 20.0):
                    fails.append("FAIL_GATE_B0B_MODELED_DAY1_BURST_GT_20PCT"); b0b_ok = False
                if float(m_sys_pk) >= 0.5:
                    fails.append("FAIL_GATE_B0B_MODELED_SYSTEMIC_CMAX_GE_0P5NM"); b0b_ok = False
                if ec50_u95 is not None and float(m_d10_l95) < ec50_u95:
                    fails.append("FAIL_GATE_B0B_MODELED_DAYS0_10_PARENT_BELOW_B0A_EC50_U95"); b0b_ok = False
                if csafe_bench is not None and float(m_d21_pk) >= csafe_bench:
                    fails.append("FAIL_GATE_B0B_MODELED_DAYS0_21_PEAK_GE_B0A_CSAFE_BENCH"); b0b_ok = False
                if (
                    b0a_ev is not None and isinstance(b0a_ev.get("fu_parent_by_matrix"), Mapping)
                    and is_finite_num(b0a_ev["fu_parent_by_matrix"].get("human_serum_100pct"))
                    and all(is_finite_num(x) for x in (rc_l, dur_d, ld_mg, u_rec))
                ):
                    fu_s = float(b0a_ev["fu_parent_by_matrix"]["human_serum_100pct"])
                    if fu_s > 0.0:
                        req_from_modeled_mg = float(rc_l) * (float(m_d10_l95) / fu_s) * 1e-9 * 425470.0 * float(dur_d)
                        if float(ld_mg) * float(u_rec) + 1e-9 < req_from_modeled_mg:
                            fails.append("FAIL_GATE_B0B_LOADED_API_BELOW_QUANTITATIVE_MASS_REQUIREMENT"); b0b_ok = False

    b1_extras = frozenset({
        "elution_started_at_utc", "day1_burst_pct", "day21_effluent_total_nM",
        "day21_effluent_free_nM", "day21_depot_depletion_pct",
        "day21_elution_verified", "terminal_mass_recovery_pct",
        "analytical_sample_ledger",
    })
    b1_ev = _validate_content_receipt(
        rec.get("b1_evidence"),
        expected_stage="B-1", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="bench_unedited",
        expected_coating_identity=coat_id,
        expected_parent=b0b_ev, allowed_extra_keys=b1_extras,
        fails=fails, holds=holds,
        missing_hold="HOLD_GATE_B1_21D_ELUTION_MISSING",
        fail_code="FAIL_GATE_B1_21D_ELUTION_FAILED",
        mismatch_code="FAIL_GATE_B1_SCOPE_MISMATCH",
    )
    b1_ok = b1_ev is not None and b1_ev.get("verdict") == "PASS"
    if b1_ev is not None:
        t_el = parse_utc_iso_ts(b1_ev.get("elution_started_at_utc"))
        t_b1 = parse_utc_iso_ts(b1_ev.get("recorded_at_utc"))
        t_b0b = parse_utc_iso_ts(b0b_ev.get("recorded_at_utc")) if b0b_ev is not None else None
        if t_el is None or t_b1 is None:
            fails.append("FAIL_GATE_B1_MISSING_ELUTION_START_UTC"); b1_ok = False
        else:
            if t_b0b is not None and t_el < t_b0b:
                fails.append("FAIL_GATE_B1_ELUTION_STARTED_BEFORE_B0B"); b1_ok = False
            if (t_b1 - t_el) < timedelta(days=21):
                fails.append("FAIL_GATE_B1_ELAPSED_ELUTION_DURATION_LT_21_DAYS"); b1_ok = False
        burst = b1_ev.get("day1_burst_pct")
        d21_tot = b1_ev.get("day21_effluent_total_nM")
        d21_fr = b1_ev.get("day21_effluent_free_nM")
        depl = b1_ev.get("day21_depot_depletion_pct")
        mr = b1_ev.get("terminal_mass_recovery_pct")
        if not (is_strict_bool(b1_ev.get("day21_elution_verified")) and b1_ev["day21_elution_verified"]):
            fails.append("FAIL_GATE_B1_DAY21_ELUTION_UNVERIFIED"); b1_ok = False
        if not (is_finite_num(burst) and 0.0 <= float(burst) <= 20.0):
            fails.append("FAIL_GATE_B1_DAY1_BURST_GT_20PCT"); b1_ok = False
        if not (is_finite_num(d21_tot) and is_finite_num(d21_fr) and 0.0 <= float(d21_fr) <= float(d21_tot) and float(d21_tot) < 10.0 and float(d21_fr) < 2.0):
            fails.append("FAIL_GATE_B1_DAY21_EFFLUENT_EXHAUSTION_FAILED"); b1_ok = False
        if not (is_finite_num(depl) and 85.0 <= float(depl) <= 100.0):
            fails.append("FAIL_GATE_B1_DAY21_DEPOT_DEPLETION_LT_85PCT"); b1_ok = False
        if not is_finite_num(mr) or not (90.0 <= float(mr) <= 110.0):
            fails.append("FAIL_GATE_B1_MASS_RECOVERY_OUT_OF_90_110"); b1_ok = False
        b1_ledger = b1_ev.get("analytical_sample_ledger")
        b1_ledger_map: dict[str, tuple[float, str, str, str, str]] = {}
        ledger_entry_keys = frozenset({"sample_id", "hour_h", "source_stage", "assay_matrix", "recirc_assay_matrix", "biological_unit_id", "raw_analytical_row_sha256"})
        if not isinstance(b1_ledger, list) or len(b1_ledger) < 3:
            holds.append("HOLD_GATE_B1_MISSING_ANALYTICAL_SAMPLE_LEDGER"); b1_ok = False
        else:
            for _lrow in b1_ledger:
                if (
                    not isinstance(_lrow, Mapping) or set(_lrow.keys()) != ledger_entry_keys
                    or not is_nonempty_str(_lrow.get("sample_id"))
                    or _lrow.get("assay_matrix") not in REQUIRED_3_MATRICES
                    or _lrow.get("recirc_assay_matrix") not in REQUIRED_3_MATRICES
                    or not is_nonempty_str(_lrow.get("biological_unit_id"))
                    or _lrow.get("source_stage") != "B-1"
                    or not (is_finite_num(_lrow.get("hour_h")) and float(_lrow["hour_h"]) > 0.0)
                    or not is_valid_sha256_hex(_lrow.get("raw_analytical_row_sha256"))
                ):
                    fails.append("FAIL_GATE_B1_INVALID_ANALYTICAL_SAMPLE_LEDGER"); b1_ok = False; break
                _sid = str(_lrow["sample_id"]).strip().upper()
                if _sid in b1_ledger_map:
                    fails.append("FAIL_GATE_B1_INVALID_ANALYTICAL_SAMPLE_LEDGER"); b1_ok = False; break
                b1_ledger_map[_sid] = (float(_lrow["hour_h"]), str(_lrow["raw_analytical_row_sha256"]).lower(), str(_lrow["assay_matrix"]).strip(), str(_lrow["recirc_assay_matrix"]).strip(), str(_lrow["biological_unit_id"]).strip().upper())
    else:
        b1_ledger_map = {}

    # Gate B-2: RAW paired vehicle-vs-coated donor_records (recomputing physically bounded % reductions!),
    # whitespace/case-normalized unique donor IDs, derived control validity, structured exclusions, LOO sensitivity!
    b2_extras = frozenset({
        "enrolled_donors_n", "excluded_invalid_donors_n", "invalid_donor_exclusion_log",
        "donor_records", "analytical_sample_ledger",
        "iec_sprouting_pct_ctrl", "iec_birc5_viability_pct", "iec_txnip_fold",
        "iec_ros_fold", "iec_cd274_pct_ctrl", "iec_hlae_pct_ctrl",
        "iec_pgf_pct_ctrl", "iec_c3_fold_vs_ctrl",
    })
    b2_ev = _validate_content_receipt(
        rec.get("b2_evidence"),
        expected_stage="B-2", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="bench_unedited",
        expected_coating_identity=coat_id,
        expected_parent=b1_ev, allowed_extra_keys=b2_extras, fails=fails, holds=holds,
        missing_hold="HOLD_GATE_B2_CHANDLER_LOOP_MISSING",
        fail_code="FAIL_GATE_B2_CHANDLER_LOOP_FAILED",
        mismatch_code="FAIL_GATE_B2_SCOPE_MISMATCH",
    )
    b2_ok = b2_ev is not None and b2_ev.get("verdict") == "PASS"
    if b2_ev is not None:
        enr_d = b2_ev.get("enrolled_donors_n")
        exc_d = b2_ev.get("excluded_invalid_donors_n")
        exc_log = b2_ev.get("invalid_donor_exclusion_log")
        drecs = b2_ev.get("donor_records")
        if not (is_strict_int(enr_d) and is_strict_int(exc_d) and int(exc_d) >= 0):
            fails.append("FAIL_GATE_B2_ENROLLMENT_OR_EXCLUSION_LOG_INVALID"); b2_ok = False
        if not isinstance(drecs, list) or len(drecs) < 6:
            fails.append("FAIL_GATE_B2_UNDERPOWERED_OR_DUPLICATE_DONORS_LT_6"); b2_ok = False
        else:
            seen_d_norm: set[str] = set()
            tat_reds: list[float] = []
            c3a_reds: list[float] = []
            plt_recs: list[float] = []
            d_allowed = frozenset({
                "donor_id",
                "pos_ctrl_tat_fold", "pos_ctrl_c3a_fold", "pos_ctrl_plt_drop_pct",
                "neg_ctrl_tat_fold", "neg_ctrl_plt_retention_pct",
                "tat_vehicle_ng_ml", "tat_coated_ng_ml",
                "c3a_vehicle_ng_ml", "c3a_coated_ng_ml",
                "platelet_baseline_k_ul", "platelet_vehicle_k_ul", "platelet_coated_k_ul",
            })
            for idx, drow in enumerate(drecs):
                if not isinstance(drow, Mapping):
                    fails.append(f"FAIL_GATE_B2_MALFORMED_DONOR_ROW:{idx}"); b2_ok = False; continue
                _check_allowed_keys(drow, d_allowed, fails, f"GATE_B2_DONOR_{idx}")
                raw_did = drow.get("donor_id")
                if not is_nonempty_str(raw_did):
                    fails.append("FAIL_GATE_B2_UNDERPOWERED_OR_DUPLICATE_DONORS_LT_6"); b2_ok = False; continue
                did_n = str(raw_did).strip().upper()
                if did_n in seen_d_norm:
                    fails.append("FAIL_GATE_B2_UNDERPOWERED_OR_DUPLICATE_DONORS_LT_6"); b2_ok = False; continue
                seen_d_norm.add(did_n)

                # Derived per-donor control validity (no redundant unverified boolean!)
                for ck, clo, chi in (
                    ("pos_ctrl_tat_fold", 3.0, 1e6),
                    ("pos_ctrl_c3a_fold", 2.0, 1e6),
                    ("pos_ctrl_plt_drop_pct", 25.0, 100.0),
                    ("neg_ctrl_tat_fold", 0.0, 1.5),
                    ("neg_ctrl_plt_retention_pct", 85.0, 120.0),
                ):
                    cv = drow.get(ck)
                    if not (is_finite_num(cv) and clo <= float(cv) <= chi):
                        fails.append(f"FAIL_GATE_B2_NUMERIC_DONOR_CONTROL_INVALID:{ck}"); b2_ok = False

                tv, tc = drow.get("tat_vehicle_ng_ml"), drow.get("tat_coated_ng_ml")
                cv_, cc_ = drow.get("c3a_vehicle_ng_ml"), drow.get("c3a_coated_ng_ml")
                pb_, pv_, pc_ = drow.get("platelet_baseline_k_ul"), drow.get("platelet_vehicle_k_ul"), drow.get("platelet_coated_k_ul")
                if not (is_finite_num(tv) and is_finite_num(tc) and float(tv) > 0.0 and float(tc) >= 0.0):
                    fails.append(f"FAIL_GATE_B2_TAT_RAW_VALUES_INVALID:{did_n}"); b2_ok = False
                else:
                    red_t = 100.0 * (float(tv) - float(tc)) / float(tv)
                    if red_t > 100.0 + 1e-9:
                        fails.append(f"FAIL_GATE_B2_TAT_REDUCTION_EXCEEDS_100PCT:{did_n}"); b2_ok = False
                    else:
                        tat_reds.append(red_t)
                if not (is_finite_num(cv_) and is_finite_num(cc_) and float(cv_) > 0.0 and float(cc_) >= 0.0):
                    fails.append(f"FAIL_GATE_B2_C3A_RAW_VALUES_INVALID:{did_n}"); b2_ok = False
                else:
                    red_c = 100.0 * (float(cv_) - float(cc_)) / float(cv_)
                    if red_c > 100.0 + 1e-9:
                        fails.append(f"FAIL_GATE_B2_C3A_REDUCTION_EXCEEDS_100PCT:{did_n}"); b2_ok = False
                    else:
                        c3a_reds.append(red_c)
                if not (
                    is_finite_num(pb_) and is_finite_num(pv_) and is_finite_num(pc_)
                    and float(pb_) > 0.0 and 0.0 <= float(pv_) <= float(pb_) * 1.10 and 0.0 <= float(pc_) <= float(pb_) * 1.10
                ):
                    fails.append(f"FAIL_GATE_B2_PLATELET_RAW_VALUES_INVALID:{did_n}"); b2_ok = False
                else:
                    rec_p = 100.0 * (float(pc_) - float(pv_)) / float(pb_)
                    if not (-100.0 <= rec_p <= 100.0):
                        fails.append(f"FAIL_GATE_B2_PLATELET_RECOVERY_OUT_OF_BOUNDS:{did_n}"); b2_ok = False
                    else:
                        plt_recs.append(rec_p)

            nd = len(seen_d_norm)
            if is_strict_int(enr_d) and is_strict_int(exc_d):
                if (len(drecs) + int(exc_d)) != int(enr_d):
                    fails.append("FAIL_GATE_B2_DONOR_DENOMINATOR_RECONCILIATION_MISMATCH"); b2_ok = False
                if not _validate_structured_exclusions(exc_log, expected_n=int(exc_d), analyzed_ids_norm=seen_d_norm, id_key="donor_id", fails=fails, prefix="GATE_B2"):
                    b2_ok = False

            for ename, vals, min_mean in (
                ("TAT", tat_reds, 25.0), ("C3A", c3a_reds, 25.0), ("PLATELET", plt_recs, 20.0),
            ):
                if len(vals) == len(drecs) and nd == len(drecs):
                    stat = paired_t_summary(vals)
                    if stat is None:
                        fails.append(f"FAIL_GATE_B2_{ename}_DEGENERATE_VARIANCE"); b2_ok = False
                    else:
                        mean_v, _, p_v, l95_v = stat
                        if mean_v < min_mean or p_v >= 0.05 or l95_v <= 0.0:
                            fails.append(f"FAIL_GATE_B2_{ename}_PAIRED_DONOR_BENEFIT_FAILED"); b2_ok = False
                        else:
                            for j in range(nd):
                                loo_s = paired_t_summary(vals[:j] + vals[j + 1:])
                                if loo_s is None or loo_s[3] <= 0.0:
                                    fails.append(f"FAIL_GATE_B2_{ename}_LEAVE_ONE_DONOR_OUT_FRAGILE"); b2_ok = False; break
        for ikey, ilo, ihi, icode in (
            ("iec_sprouting_pct_ctrl", 90.0, 200.0, "FAIL_GATE_B2_IEC_SPROUTING_LT_90PCT"),
            ("iec_birc5_viability_pct", 90.0, 100.0, "FAIL_GATE_B2_IEC_VIABILITY_LT_90PCT"),
            ("iec_txnip_fold", 0.0, 1.5, "FAIL_GATE_B2_IEC_TXNIP_GT_1P5"),
            ("iec_ros_fold", 0.0, 1.2, "FAIL_GATE_B2_IEC_ROS_GT_1P2"),
            ("iec_cd274_pct_ctrl", 85.0, 200.0, "FAIL_GATE_B2_IEC_CD274_LT_85PCT"),
            ("iec_hlae_pct_ctrl", 85.0, 200.0, "FAIL_GATE_B2_IEC_HLAE_LT_85PCT"),
            ("iec_pgf_pct_ctrl", 80.0, 200.0, "FAIL_GATE_B2_IEC_PGF_LT_80PCT"),
            ("iec_c3_fold_vs_ctrl", 0.0, 1.2, "FAIL_GATE_B2_IEC_C3_GT_1P2"),
        ):
            iv = b2_ev.get(ikey)
            if not (is_finite_num(iv) and ilo <= float(iv) <= ihi):
                fails.append(icode); b2_ok = False
        b2_ledger = b2_ev.get("analytical_sample_ledger")
        b2_ledger_map: dict[str, tuple[float, str, str, str, str]] = {}
        b2_lkeys = frozenset({"sample_id", "hour_h", "source_stage", "assay_matrix", "recirc_assay_matrix", "biological_unit_id", "raw_analytical_row_sha256"})
        if not isinstance(b2_ledger, list) or len(b2_ledger) < 3:
            holds.append("HOLD_GATE_B2_MISSING_ANALYTICAL_SAMPLE_LEDGER"); b2_ok = False
        else:
            for _lrow in b2_ledger:
                if (
                    not isinstance(_lrow, Mapping) or set(_lrow.keys()) != b2_lkeys
                    or not is_nonempty_str(_lrow.get("sample_id"))
                    or _lrow.get("assay_matrix") not in REQUIRED_3_MATRICES
                    or _lrow.get("recirc_assay_matrix") not in REQUIRED_3_MATRICES
                    or not is_nonempty_str(_lrow.get("biological_unit_id"))
                    or _lrow.get("source_stage") != "B-2"
                    or not (is_finite_num(_lrow.get("hour_h")) and float(_lrow["hour_h"]) > 0.0)
                    or not is_valid_sha256_hex(_lrow.get("raw_analytical_row_sha256"))
                ):
                    fails.append("FAIL_GATE_B2_INVALID_ANALYTICAL_SAMPLE_LEDGER"); b2_ok = False; break
                _sid = str(_lrow["sample_id"]).strip().upper()
                if _sid in b2_ledger_map or _sid in b1_ledger_map:
                    fails.append("FAIL_GATE_B2_INVALID_ANALYTICAL_SAMPLE_LEDGER"); b2_ok = False; break
                b2_ledger_map[_sid] = (float(_lrow["hour_h"]), str(_lrow["raw_analytical_row_sha256"]).lower(), str(_lrow["assay_matrix"]).strip(), str(_lrow["recirc_assay_matrix"]).strip(), str(_lrow["biological_unit_id"]).strip().upper())
    else:
        b2_ledger_map = {}
    b12_combined_ledger: Optional[dict[str, tuple[float, str, str, str, str]]] = ({**b1_ledger_map, **b2_ledger_map} if (b1_ledger_map and b2_ledger_map) else None)

    b2b_common_extras = frozenset({
        "used_marginal_u95_sum", "alpha_conc", "alpha_fu_parent", "alpha_fu_bmt",
        "local_assay_matrix", "recirc_assay_matrix",
        "u95_joint_peak_free_nM", "days0_10_parent_lower_free_nM",
        "timepoint_replicate_records",
        "fu_parent_replicates", "fu_bmt_replicates",
        "recirc_fu_bmt_replicates", "alpha_fu_bmt_recirc",
        "additional_matrix_calibrations", "common_exposure_basis",
        "c_bmt_local_total_u_alloc_nM", "c_bmt_local_free_u_alloc_nM",
        "c_bmt_recirc_total_u_alloc_nM", "c_bmt_recirc_free_u_alloc_nM",
        "local_measurement_includes_recirculation",
        "censoring_audit_passed", "intersample_peak_envelope_justified",
        "intersample_pk_envelope",
        "systemic_exposure_below_cap", "systemic_kbp_calibration",
        "mixture_requalified", "mixture_requalification_receipt",
    })
    b2bb_ev = _validate_content_receipt(
        rec.get("b2b_bench_evidence"),
        expected_stage="B-2b-bench", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="bench_unedited",
        expected_coating_identity=coat_id,
        expected_parent=b2_ev, min_prereq_receipts=[("B-1", b1_ev), ("B-2", b2_ev)],
        allowed_extra_keys=b2b_common_extras,
        fails=fails, holds=holds,
        missing_hold="HOLD_GATE_B2B_BENCH_MISSING",
        fail_code="FAIL_GATE_B2B_BENCH_FAILED",
        mismatch_code="FAIL_GATE_B2B_BENCH_SCOPE_MISMATCH",
    )
    b2bb_ok = False
    if b2bb_ev is not None and ec50_u95 is not None and csafe_bench is not None and lloq_parent_map_f is not None and lloq_bmt_map_f is not None and fu_parent_map_f is not None and fu_bmt_map_f is not None:
        b2bb_ok = _validate_b2b_exposure_block(
            b2bb_ev, ec50_u95=ec50_u95, lloq_parent_by_matrix=lloq_parent_map_f,
            lloq_bmt_by_matrix=lloq_bmt_map_f, fu_parent_by_matrix=fu_parent_map_f,
            fu_bmt_by_matrix=fu_bmt_map_f, ceiling_l95=csafe_bench,
            expected_prod=prod_s, expected_bank=bank_s, expected_lot=lot_s, expected_route=route_s,
            expected_scope="bench_unedited", expected_coating_identity=coat_id,
            fails=fails, holds=holds, prefix="GATE_B2B_BENCH",
            upstream_sample_ledger=b12_combined_ledger,
        )

    if phase == "BENCH_UNEDITED":
        verdict = "FAIL" if fails else ("HOLD" if holds else "PASS_BENCH_ONLY_UNEDITED_PRE_MATERIALIZATION")
        return {
            "gate": "GATE-41", "phase": phase, "scope_track": scope_track, "verdict": verdict,
            "release_authorizing": False, "live_ledger_authenticated": False,
            "upstream_archive_verification": OFFLINE_ARCHIVE_NOTE,
            "product_id": rec.get("product_id"), "required_switch": spec["required_switch"] if spec else None,
            "failures": fails, "holds": holds,
        }

    # Dedicated measured exact-product cassette ceiling receipt (B-0a-exact) — NOW BINDS COATING_IDENTITY_KEYS + API_BATCH_ID!
    b0a_exact_extras = frozenset({
        "endpoints_bracketed", "analysis_record_sha256",
        "tested_free_conc_grid_nM", "cassette_retention_pct_grid",
        "cassette_retention_replicates_by_conc",
        "c_safe_max_exact_l95_free_nM",
        "exact_cassette_retention_at_csafe_pct", "hour0_density_at_csafe_by_lineage",
    })
    b0a_ex_ev = _validate_content_receipt(
        rec.get("b0a_exact_evidence"),
        expected_stage="B-0a-exact", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="exact_product",
        expected_coating_identity=coat_id,
        expected_parent=mat_ev, min_prereq_receipts=[("B-0a", b0a_ev), ("B-2b-bench", b2bb_ev), ("BANK_MATERIALIZATION", mat_ev)],
        allowed_extra_keys=b0a_exact_extras, fails=fails, holds=holds,
        missing_hold="HOLD_GATE_B0A_EXACT_CASSETTE_CEILING_MISSING",
        fail_code="FAIL_GATE_B0A_EXACT_CASSETTE_CEILING_FAILED",
        mismatch_code="FAIL_GATE_B0A_EXACT_SCOPE_MISMATCH",
    )
    b0a_ex_ok = b0a_ex_ev is not None and b0a_ex_ev.get("verdict") == "PASS"
    csafe_exact: Optional[float] = None
    if b0a_ex_ev is not None:
        if not (is_strict_bool(b0a_ex_ev.get("endpoints_bracketed")) and b0a_ex_ev["endpoints_bracketed"]):
            fails.append("FAIL_GATE_B0A_EXACT_ENDPOINTS_UNBRACKETED"); b0a_ex_ok = False
        if not is_valid_sha256_hex(b0a_ex_ev.get("analysis_record_sha256")):
            fails.append("FAIL_GATE_B0A_EXACT_MISSING_ANALYSIS_RECORD_SHA256"); b0a_ex_ok = False
        cse = b0a_ex_ev.get("c_safe_max_exact_l95_free_nM")
        ret = b0a_ex_ev.get("exact_cassette_retention_at_csafe_pct")
        if not (is_finite_num(cse) and float(cse) > 0.0):
            fails.append("FAIL_GATE_B0A_EXACT_INVALID_CSAFE"); b0a_ex_ok = False
        else:
            csafe_exact = float(cse)
            eg_c = b0a_ex_ev.get("tested_free_conc_grid_nM")
            eg_r = b0a_ex_ev.get("cassette_retention_pct_grid")
            if not (isinstance(eg_c, list) and isinstance(eg_r, list) and len(eg_c) == len(eg_r) and len(eg_c) >= 5 and all(is_finite_num(x) for x in eg_c + eg_r)):
                fails.append("FAIL_GATE_B0A_EXACT_MISSING_CONC_RESPONSE_GRID"); b0a_ex_ok = False
            else:
                cg_e = [float(x) for x in eg_c]
                rg_e = [float(x) for x in eg_r]
                if cg_e[0] != 0.0 or any(cg_e[i] >= cg_e[i + 1] for i in range(len(cg_e) - 1)) or not (cg_e[1] <= csafe_exact < cg_e[-1]):
                    fails.append("FAIL_GATE_B0A_EXACT_CSAFE_NOT_BRACKETED_BY_GRID"); b0a_ex_ok = False
                else:
                    creps = b0a_ex_ev.get("cassette_retention_replicates_by_conc")
                    ex_row_keys = frozenset({"unit_ids", "matched_vehicle_record_id", "technical_replicates_per_unit_pct", "cassette_retention_pct", "raw_unit_measurements"})
                    if not (isinstance(creps, list) and len(creps) == len(cg_e)):
                        fails.append("FAIL_GATE_B0A_EXACT_MISSING_CASSETTE_REPLICATES"); b0a_ex_ok = False
                    elif any(not isinstance(r, Mapping) or not {"unit_ids", "matched_vehicle_record_id"}.issubset(set(r.keys())) for r in creps):
                        holds.append("HOLD_GATE_B0A_EXACT_MISSING_BIOLOGICAL_UNIT_DENOMINATOR"); b0a_ex_ok = False
                    elif any(r.get("raw_unit_measurements") is None for r in creps):
                        holds.append("HOLD_GATE_B0A_EXACT_MISSING_MATCHED_VEHICLE_RAW_DATA"); b0a_ex_ok = False
                    else:
                        q_idx_e = -1
                        ex_first_uids: Optional[list[str]] = None
                        ex_rows_ok = True
                        for i_e, rmap_e in enumerate(creps):
                            if set(rmap_e.keys()) != ex_row_keys or not is_nonempty_str(rmap_e.get("matched_vehicle_record_id")):
                                fails.append(f"FAIL_GATE_B0A_EXACT_MALFORMED_UNIT_REPLICATES:{i_e}"); ex_rows_ok = False; b0a_ex_ok = False; break
                            mv_rec_ex = str(rmap_e["matched_vehicle_record_id"]).strip().upper()
                            raw_ex = rmap_e.get("raw_unit_measurements")
                            eu_raw = rmap_e.get("unit_ids")
                            tr_e = rmap_e.get("technical_replicates_per_unit_pct")
                            arr_e = rmap_e.get("cassette_retention_pct")
                            if not (isinstance(eu_raw, list) and len(eu_raw) >= 3 and all(is_nonempty_str(u) for u in eu_raw)):
                                fails.append(f"FAIL_GATE_B0A_EXACT_INVALID_OR_MISMATCHED_UNIT_IDS:{i_e}"); ex_rows_ok = False; b0a_ex_ok = False; break
                            eu_norm = [str(u).strip().upper() for u in eu_raw]
                            if len(set(eu_norm)) != len(eu_norm):
                                fails.append(f"FAIL_GATE_B0A_EXACT_INVALID_OR_MISMATCHED_UNIT_IDS:{i_e}"); ex_rows_ok = False; b0a_ex_ok = False; break
                            if ex_first_uids is None:
                                ex_first_uids = eu_norm
                            elif eu_norm != ex_first_uids:
                                fails.append(f"FAIL_GATE_B0A_EXACT_INVALID_OR_MISMATCHED_UNIT_IDS:{i_e}"); ex_rows_ok = False; b0a_ex_ok = False; break
                            if not (
                                isinstance(arr_e, list) and len(arr_e) == len(eu_norm) and all(is_finite_num(x) for x in arr_e)
                                and isinstance(tr_e, list) and len(tr_e) == len(eu_norm)
                                and all(isinstance(tw, list) and len(tw) >= 1 and all(is_finite_num(x) for x in tw) for tw in tr_e)
                                and isinstance(raw_ex, Mapping) and set(raw_ex.keys()) == {"vehicle_record_id", "treated_by_unit_tech", "vehicle_by_unit_tech"}
                                and is_nonempty_str(raw_ex.get("vehicle_record_id"))
                                and str(raw_ex["vehicle_record_id"]).strip().upper() == mv_rec_ex
                                and isinstance(raw_ex.get("treated_by_unit_tech"), list) and len(raw_ex["treated_by_unit_tech"]) == len(eu_norm)
                                and isinstance(raw_ex.get("vehicle_by_unit_tech"), list) and len(raw_ex["vehicle_by_unit_tech"]) == len(eu_norm)
                                and all(
                                    isinstance(raw_ex["treated_by_unit_tech"][uj], list) and isinstance(raw_ex["vehicle_by_unit_tech"][uj], list)
                                    and len(raw_ex["treated_by_unit_tech"][uj]) == len(tr_e[uj]) and len(raw_ex["vehicle_by_unit_tech"][uj]) == len(tr_e[uj])
                                    and all(is_finite_num(x) and float(x) >= 0.0 for x in raw_ex["treated_by_unit_tech"][uj])
                                    and all(is_finite_num(x) and float(x) > 0.0 for x in raw_ex["vehicle_by_unit_tech"][uj])
                                    for uj in range(len(eu_norm))
                                )
                            ):
                                fails.append(f"FAIL_GATE_B0A_EXACT_MALFORMED_UNIT_REPLICATES:{i_e}"); ex_rows_ok = False; b0a_ex_ok = False; break
                            af_e: list[float] = []
                            for uj, tw in enumerate(tr_e):
                                recomp_tw = [
                                    100.0 * float(raw_ex["treated_by_unit_tech"][uj][tk]) / float(raw_ex["vehicle_by_unit_tech"][uj][tk])
                                    for tk in range(len(tw))
                                ]
                                if any(abs(recomp_tw[tk] - float(tw[tk])) > 0.5 for tk in range(len(tw))):
                                    fails.append(f"FAIL_GATE_B0A_EXACT_NORMALIZED_PCT_MISMATCH_VS_MATCHED_VEHICLE:{i_e}:{eu_norm[uj]}"); ex_rows_ok = False; b0a_ex_ok = False; break
                                tw_mean = sum(recomp_tw) / len(recomp_tw)
                                if abs(tw_mean - float(arr_e[uj])) > 0.05:
                                    fails.append(f"FAIL_GATE_B0A_EXACT_BLOCK_AGGREGATION_MISMATCH:{i_e}:{eu_norm[uj]}"); ex_rows_ok = False; b0a_ex_ok = False; break
                                af_e.append(tw_mean)
                            if not ex_rows_ok:
                                break
                            if abs((sum(af_e) / len(af_e)) - rg_e[i_e]) > 0.5:
                                fails.append(f"FAIL_GATE_B0A_EXACT_GRID_MEAN_MISMATCH:{i_e}"); b0a_ex_ok = False
                            sb_e = sample_t_one_sided_bounds(af_e, alpha=0.05 / float(len(cg_e)))
                            if sb_e is None:
                                holds.append("HOLD_GATE_B0A_EXACT_DEGENERATE_ZERO_VARIANCE_UNESTIMABLE")
                                l95_e = float("-inf")
                            else:
                                l95_e = sb_e[1]
                            if l95_e >= 85.0 and q_idx_e == i_e - 1:
                                q_idx_e = i_e
                        if ex_rows_ok:
                            max_q_safe_e = cg_e[q_idx_e] if q_idx_e >= 0 else -1.0
                            if csafe_exact > max_q_safe_e + 1e-9:
                                fails.append("FAIL_GATE_B0A_EXACT_CSAFE_EXCEEDS_QUALIFIED_TESTED_SAFE_CONC"); b0a_ex_ok = False
                            elif rg_e[0] < 95.0 or not any(rg_e[i] < 85.0 for i in range(len(cg_e)) if cg_e[i] > max_q_safe_e + 1e-9):
                                fails.append("FAIL_GATE_B0A_EXACT_GRID_NOT_TWO_SIDED_BRACKETED"); b0a_ex_ok = False
        if not (is_finite_num(ret) and 85.0 <= float(ret) <= 100.0):
            fails.append("FAIL_GATE_B0A_EXACT_CASSETTE_RETENTION_BELOW_85PCT"); b0a_ex_ok = False
        if spec is not None and not _validate_lineage_hour0_density(
            spec, b0a_ex_ev.get("hour0_density_at_csafe_by_lineage"),
            required_lineages=REQUIRED_HOUR0_LINEAGES_FULL, fails=fails, prefix="GATE_B0A_EXACT",
        ):
            b0a_ex_ok = False

    b2be_ev = _validate_content_receipt(
        rec.get("b2b_exact_evidence"),
        expected_stage="B-2b-exact", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="exact_product",
        expected_coating_identity=coat_id,
        expected_parent=b2bb_ev,
        min_prereq_receipts=[("BANK_MATERIALIZATION", mat_ev), ("B-0a-exact", b0a_ex_ev), ("B-1", b1_ev), ("B-2", b2_ev)],
        allowed_extra_keys=b2b_common_extras | frozenset({"c_safe_max_operative_l95_free_nM"}),
        fails=fails, holds=holds,
        missing_hold="HOLD_GATE_B2B_EXACT_MISSING",
        fail_code="FAIL_GATE_B2B_EXACT_FAILED",
        mismatch_code="FAIL_GATE_B2B_EXACT_SCOPE_MISMATCH",
    )
    b2be_ok = False
    csafe_op_val: Optional[float] = None
    if b2be_ev is not None:
        cs_op = b2be_ev.get("c_safe_max_operative_l95_free_nM")
        if not is_finite_num(cs_op) or float(cs_op) <= 0.0:
            fails.append("FAIL_GATE_B2B_EXACT_MISSING_OPERATIVE_CSAFE")
        elif csafe_bench is not None and csafe_exact is not None:
            derived_op = min(csafe_bench, csafe_exact)
            if abs(float(cs_op) - derived_op) > 1e-9:
                fails.append("FAIL_GATE_B2B_EXACT_OPERATIVE_NOT_EQUAL_TO_MIN_BENCH_AND_EXACT")
            else:
                csafe_op_val = derived_op
                if ec50_u95 is not None and csafe_op_val / ec50_u95 < 2.0:
                    fails.append("FAIL_GATE_B2B_EXACT_OPERATIVE_MARGIN_BELOW_2X")
                elif ec50_u95 is not None and lloq_parent_map_f is not None and lloq_bmt_map_f is not None and fu_parent_map_f is not None and fu_bmt_map_f is not None:
                    b2be_ok = _validate_b2b_exposure_block(
                        b2be_ev, ec50_u95=ec50_u95, lloq_parent_by_matrix=lloq_parent_map_f,
                        lloq_bmt_by_matrix=lloq_bmt_map_f, fu_parent_by_matrix=fu_parent_map_f,
                        fu_bmt_by_matrix=fu_bmt_map_f, ceiling_l95=csafe_op_val,
                        expected_prod=prod_s, expected_bank=bank_s, expected_lot=lot_s, expected_route=route_s,
                        expected_scope="exact_product", expected_coating_identity=coat_id,
                        fails=fails, holds=holds, prefix="GATE_B2B_EXACT",
                        upstream_sample_ledger=b12_combined_ledger,
                    )

    # Gate B-3: construct-specific component shields + matched blank-vehicle Readout-2 (>= 90% Fieller!) + Readout-3B (SIRPa-low + <= +2 pp delta!)
    b3_extras = frozenset({
        "transgene_cassette_retention_pct", "shield_retention_by_component",
        "b3_cytokine_challenge_shield_panel",
        "il10_suppression_pct", "post_washout_72h_il10_recovery_pct",
        "il10_washout_recovery_assay",
        "nkg2a_mfi_pct_ctrl", "cd94_mfi_pct_ctrl",
        "readout3b_evidence", "readout2_evidence", "hour0_density_by_lineage",
    })
    b3_ev = _validate_content_receipt(
        rec.get("b3_evidence"),
        expected_stage="B-3", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="exact_product",
        expected_coating_identity=coat_id,
        expected_parent=b2be_ev, min_prereq_receipts=[("BANK_MATERIALIZATION", mat_ev)],
        allowed_extra_keys=b3_extras, fails=fails, holds=holds,
        missing_hold="HOLD_GATE_B3_EXACT_MATRIX_MISSING",
        fail_code="FAIL_GATE_B3_EXACT_MATRIX_FAILED",
        mismatch_code="FAIL_GATE_B3_SCOPE_MISMATCH",
    )
    b3_ok = b3_ev is not None and b3_ev.get("verdict") == "PASS"
    blank_veh_40 = coat_id["matched_blank_vehicle_lot_id"] if coat_id is not None else None
    if b3_ev is not None:
        cas = b3_ev.get("transgene_cassette_retention_pct")
        smap = b3_ev.get("shield_retention_by_component")
        il10 = b3_ev.get("il10_suppression_pct")
        il10_rec = b3_ev.get("post_washout_72h_il10_recovery_pct")
        nkg_mfi = b3_ev.get("nkg2a_mfi_pct_ctrl")
        cd94_mfi = b3_ev.get("cd94_mfi_pct_ctrl")
        if not (is_finite_num(cas) and 85.0 <= float(cas) <= 100.0):
            fails.append("FAIL_GATE_B3_CASSETTE_RETENTION_BELOW_85PCT"); b3_ok = False
        req_comp = SHIELD_COMPONENTS_BY_PRODUCT.get(prod_s, frozenset())
        if not isinstance(smap, Mapping) or set(smap.keys()) != req_comp:
            fails.append("FAIL_GATE_B3_INCOMPLETE_COMPONENT_SHIELD_MAP"); b3_ok = False
        else:
            for cname in sorted(req_comp):
                cv = smap.get(cname)
                if not (is_finite_num(cv) and 85.0 <= float(cv) <= 100.0):
                    fails.append(f"FAIL_GATE_B3_SHIELD_COMPONENT_BELOW_85PCT:{cname}"); b3_ok = False
        # Exact-product per-challenge matched-control block shield retention panel (Draft B s5: IFNG+TNFA, IFNG+IL1B, IFNA+low_IFNG)
        # quantitatively linked to B-2b-exact exposure window [days0_10_parent_lower_free_nM, u95_joint_peak_free_nM]!
        b3_cpanel = b3_ev.get("b3_cytokine_challenge_shield_panel")
        b3_req_challenges = frozenset({"IFNG_PLUS_TNFA", "IFNG_PLUS_IL1B", "IFNA_PLUS_LOW_IFNG"})
        b3_panel_keys = frozenset({
            "lot_id", "matched_blank_vehicle_lot_id", "b2b_exact_receipt_sha256",
            "exposure_started_at_utc", "assessed_at_utc",
            "measured_free_parent_nM", "measured_free_bmt_nM",
            "challenges", "panel_receipt_sha256",
        })
        b2be_p_lo = float(b2be_ev["days0_10_parent_lower_free_nM"]) if (b2be_ev is not None and is_finite_num(b2be_ev.get("days0_10_parent_lower_free_nM"))) else None
        b2be_j_hi = float(b2be_ev["u95_joint_peak_free_nM"]) if (b2be_ev is not None and is_finite_num(b2be_ev.get("u95_joint_peak_free_nM"))) else None
        t_b3_end_c = parse_utc_iso_ts(b3_ev.get("recorded_at_utc"))
        t_b2be_end_c = parse_utc_iso_ts(b2be_ev.get("recorded_at_utc")) if b2be_ev is not None else None
        if b3_cpanel is None:
            holds.append("HOLD_GATE_B3_MISSING_CYTOKINE_CHALLENGE_SHIELD_PANEL"); b3_ok = False
        elif not isinstance(b3_cpanel, Mapping) or set(b3_cpanel.keys()) != b3_panel_keys:
            fails.append("FAIL_GATE_B3_CYTOKINE_CHALLENGE_SHIELD_PANEL_INVALID"); b3_ok = False
        else:
            psha_b3 = b3_cpanel.get("panel_receipt_sha256")
            t_pexp = parse_utc_iso_ts(b3_cpanel.get("exposure_started_at_utc"))
            t_pass = parse_utc_iso_ts(b3_cpanel.get("assessed_at_utc"))
            mfp = b3_cpanel.get("measured_free_parent_nM")
            mfb = b3_cpanel.get("measured_free_bmt_nM")
            chals = b3_cpanel.get("challenges")
            if (
                not is_valid_sha256_hex(psha_b3)
                or sha256_bytes(canonical_json_bytes({k: v for k, v in b3_cpanel.items() if k != "panel_receipt_sha256"})) != str(psha_b3)
                or str(b3_cpanel.get("lot_id", "")).strip() != lot_s
                or (blank_veh_40 is not None and str(b3_cpanel.get("matched_blank_vehicle_lot_id", "")).strip() != blank_veh_40)
                or (b2be_ev is not None and str(b3_cpanel.get("b2b_exact_receipt_sha256", "")) != str(b2be_ev.get("receipt_sha256", "")))
                or t_pexp is None or t_pass is None
                or (t_pass - t_pexp) < timedelta(hours=24)
                or (t_b2be_end_c is not None and t_pexp < t_b2be_end_c)
                or (t_b3_end_c is not None and t_pass > t_b3_end_c)
                or not isinstance(chals, Mapping)
            ):
                fails.append("FAIL_GATE_B3_CYTOKINE_CHALLENGE_SHIELD_PANEL_INVALID"); b3_ok = False
            elif set(chals.keys()) != b3_req_challenges:
                holds.append("HOLD_GATE_B3_INCOMPLETE_REQUIRED_CYTOKINE_CHALLENGES"); b3_ok = False
            elif not (
                is_finite_num(mfp) and is_finite_num(mfb) and float(mfp) > 0.0 and float(mfb) >= 0.0
                and (b2be_p_lo is None or float(mfp) >= b2be_p_lo - 1e-9)
                and (b2be_j_hi is None or float(mfp) + float(mfb) <= b2be_j_hi + 1e-9)
                and (csafe_op_val is None or float(mfp) + float(mfb) < csafe_op_val)
            ):
                fails.append("FAIL_GATE_B3_CYTOKINE_CHALLENGE_EXPOSURE_UNLINKED_TO_B2B_EXACT"); b3_ok = False
            else:
                chal_req_k = frozenset({"block_ids", "matched_vehicle_record_id", "cassette_retention_raw", "components"})
                min_cas_across = float("inf")
                min_comp_across: dict[str, float] = {cn: float("inf") for cn in req_comp}
                cpanel_struct_ok = True
                for chal_nm in sorted(b3_req_challenges):
                    crow = chals[chal_nm]
                    if not isinstance(crow, Mapping) or set(crow.keys()) != chal_req_k or not is_nonempty_str(crow.get("matched_vehicle_record_id")):
                        fails.append(f"FAIL_GATE_B3_CYTOKINE_CHALLENGE_MALFORMED:{chal_nm}"); b3_ok = False; cpanel_struct_ok = False; break
                    bids_c = crow.get("block_ids")
                    cas_raw = crow.get("cassette_retention_raw")
                    comps_c = crow.get("components")
                    if not (
                        isinstance(bids_c, list) and len(bids_c) >= 3 and all(is_nonempty_str(b) for b in bids_c)
                        and len({str(b).strip().upper() for b in bids_c}) == len(bids_c)
                        and isinstance(cas_raw, Mapping) and set(cas_raw.keys()) == {"treated", "vehicle"}
                        and isinstance(cas_raw["treated"], list) and len(cas_raw["treated"]) == len(bids_c)
                        and isinstance(cas_raw["vehicle"], list) and len(cas_raw["vehicle"]) == len(bids_c)
                        and all(is_finite_num(x) and float(x) >= 0.0 for x in cas_raw["treated"])
                        and all(is_finite_num(x) and float(x) > 0.0 for x in cas_raw["vehicle"])
                        and isinstance(comps_c, Mapping) and set(comps_c.keys()) == req_comp
                    ):
                        fails.append(f"FAIL_GATE_B3_CYTOKINE_CHALLENGE_MALFORMED:{chal_nm}"); b3_ok = False; cpanel_struct_ok = False; break
                    cas_pcts = [100.0 * float(cas_raw["treated"][bi]) / float(cas_raw["vehicle"][bi]) for bi in range(len(bids_c))]
                    cas_m = sum(cas_pcts) / len(cas_pcts)
                    min_cas_across = min(min_cas_across, cas_m)
                    if cas_m < 85.0:
                        fails.append(f"FAIL_GATE_B3_CHALLENGE_CASSETTE_BELOW_85PCT:{chal_nm}"); b3_ok = False
                    for cname in sorted(req_comp):
                        cm_raw = comps_c[cname]
                        if not (
                            isinstance(cm_raw, Mapping) and set(cm_raw.keys()) == {"treated", "vehicle"}
                            and isinstance(cm_raw["treated"], list) and len(cm_raw["treated"]) == len(bids_c)
                            and isinstance(cm_raw["vehicle"], list) and len(cm_raw["vehicle"]) == len(bids_c)
                            and all(is_finite_num(x) and float(x) >= 0.0 for x in cm_raw["treated"])
                            and all(is_finite_num(x) and float(x) > 0.0 for x in cm_raw["vehicle"])
                        ):
                            fails.append(f"FAIL_GATE_B3_CYTOKINE_CHALLENGE_MALFORMED:{chal_nm}:{cname}"); b3_ok = False; cpanel_struct_ok = False; break
                        c_pcts = [100.0 * float(cm_raw["treated"][bi]) / float(cm_raw["vehicle"][bi]) for bi in range(len(bids_c))]
                        c_m = sum(c_pcts) / len(c_pcts)
                        min_comp_across[cname] = min(min_comp_across[cname], c_m)
                        if c_m < 85.0:
                            fails.append(f"FAIL_GATE_B3_CHALLENGE_SHIELD_COMPONENT_BELOW_85PCT:{chal_nm}:{cname}"); b3_ok = False
                    if not cpanel_struct_ok:
                        break
                if cpanel_struct_ok:
                    if is_finite_num(cas) and float(cas) > min_cas_across + 0.5:
                        fails.append("FAIL_GATE_B3_SUMMARY_OVERSTATES_CHALLENGE_MIN"); b3_ok = False
                    if isinstance(smap, Mapping):
                        for cname in sorted(req_comp):
                            if is_finite_num(smap.get(cname)) and float(smap[cname]) > min_comp_across[cname] + 0.5:
                                fails.append(f"FAIL_GATE_B3_SUMMARY_OVERSTATES_CHALLENGE_MIN:{cname}"); b3_ok = False
        if not (is_finite_num(il10) and 0.0 <= float(il10) < 20.0):
            fails.append("FAIL_GATE_B3_IL10_SUPPRESSION_GE_20PCT"); b3_ok = False
        if not (is_finite_num(il10_rec) and 90.0 <= float(il10_rec) <= 120.0):
            fails.append("FAIL_GATE_B3_POST_WASHOUT_72H_IL10_RECOVERY_LT_90PCT"); b3_ok = False
        il10_assay = b3_ev.get("il10_washout_recovery_assay")
        il10_assay_keys = frozenset({
            "assay_id", "lot_id", "matched_blank_vehicle_lot_id",
            "exposure_started_at_utc", "washout_started_at_utc",
            "recovery_collected_at_utc", "recorded_at_utc",
            "exposure_measured_free_parent_nM",
            "donor_records", "assay_receipt_sha256",
        })
        if il10_assay is None:
            holds.append("HOLD_GATE_B3_IL10_WASHOUT_RECOVERY_ASSAY_MISSING"); b3_ok = False
        elif isinstance(il10_assay, Mapping) and il10_assay.get("exposure_measured_free_parent_nM") is None:
            holds.append("HOLD_GATE_B3_IL10_WASHOUT_MISSING_MEASURED_EXPOSURE"); b3_ok = False
        elif not isinstance(il10_assay, Mapping) or set(il10_assay.keys()) != il10_assay_keys:
            fails.append("FAIL_GATE_B3_IL10_WASHOUT_RECOVERY_ASSAY_INVALID"); b3_ok = False
        else:
            isha = il10_assay.get("assay_receipt_sha256")
            t_iexp = parse_utc_iso_ts(il10_assay.get("exposure_started_at_utc"))
            t_iwash = parse_utc_iso_ts(il10_assay.get("washout_started_at_utc"))
            t_irecov = parse_utc_iso_ts(il10_assay.get("recovery_collected_at_utc"))
            t_irec = parse_utc_iso_ts(il10_assay.get("recorded_at_utc"))
            t_b3_r = parse_utc_iso_ts(b3_ev.get("recorded_at_utc"))
            t_b2be_r = parse_utc_iso_ts(b2be_ev.get("recorded_at_utc")) if b2be_ev is not None else None
            il10_donors = il10_assay.get("donor_records")
            if (
                not is_valid_sha256_hex(isha)
                or sha256_bytes(canonical_json_bytes({k: v for k, v in il10_assay.items() if k != "assay_receipt_sha256"})) != str(isha)
                or not is_nonempty_str(il10_assay.get("assay_id"))
                or str(il10_assay.get("lot_id", "")).strip() != lot_s
                or (blank_veh_40 is not None and str(il10_assay.get("matched_blank_vehicle_lot_id", "")).strip() != blank_veh_40)
                or t_iexp is None or t_iwash is None or t_irecov is None or t_irec is None
                or not (t_iexp < t_iwash < t_irecov <= t_irec)
                or (t_b3_r is not None and t_irec > t_b3_r)
                or (t_b2be_r is not None and t_iexp < t_b2be_r)
                or not isinstance(il10_donors, list) or len(il10_donors) < 3
            ):
                fails.append("FAIL_GATE_B3_IL10_WASHOUT_RECOVERY_ASSAY_INVALID"); b3_ok = False
            elif not (
                is_finite_num(il10_assay.get("exposure_measured_free_parent_nM"))
                and float(il10_assay["exposure_measured_free_parent_nM"]) > 0.0
                and (b2be_p_lo is None or float(il10_assay["exposure_measured_free_parent_nM"]) >= b2be_p_lo - 1e-9)
                and (b2be_j_hi is None or float(il10_assay["exposure_measured_free_parent_nM"]) <= b2be_j_hi + 1e-9)
            ):
                fails.append("FAIL_GATE_B3_IL10_WASHOUT_EXPOSURE_UNLINKED_TO_B2B_EXACT"); b3_ok = False
            else:
                wash_h = (t_irecov - t_iwash).total_seconds() / 3600.0
                if not (70.0 <= wash_h <= 76.0):
                    fails.append("FAIL_GATE_B3_IL10_WASHOUT_INTERVAL_NOT_72H"); b3_ok = False
                d_req_k = frozenset({
                    "donor_id", "raw_record_id",
                    "treated_post_washout_il10_suppression_pct",
                    "matched_vehicle_il10_suppression_pct",
                    "record_sha256",
                })
                seen_id_d: set[str] = set()
                seen_id_r: set[str] = set()
                rec_pcts: list[float] = []
                donors_valid = True
                for drow in il10_donors:
                    if not isinstance(drow, Mapping) or set(drow.keys()) != d_req_k:
                        donors_valid = False; break
                    did = drow.get("donor_id")
                    rid = drow.get("raw_record_id")
                    tr_p = drow.get("treated_post_washout_il10_suppression_pct")
                    vh_p = drow.get("matched_vehicle_il10_suppression_pct")
                    dsha = drow.get("record_sha256")
                    if (
                        not is_nonempty_str(did) or not is_nonempty_str(rid)
                        or not (is_finite_num(tr_p) and float(tr_p) >= 0.0 and is_finite_num(vh_p) and float(vh_p) > 0.0)
                        or not is_valid_sha256_hex(dsha)
                        or sha256_bytes(canonical_json_bytes({k: v for k, v in drow.items() if k != "record_sha256"})) != str(dsha)
                    ):
                        donors_valid = False; break
                    dn = str(did).strip().upper(); rn = str(rid).strip().upper()
                    if dn in seen_id_d or rn in seen_id_r:
                        donors_valid = False; break
                    seen_id_d.add(dn); seen_id_r.add(rn)
                    rec_pcts.append(100.0 * float(tr_p) / float(vh_p))
                if not donors_valid or len(rec_pcts) < 3:
                    fails.append("FAIL_GATE_B3_IL10_WASHOUT_RECOVERY_ASSAY_INVALID"); b3_ok = False
                else:
                    recomp_il10_mean = sum(rec_pcts) / len(rec_pcts)
                    if min(rec_pcts) < 80.0 or recomp_il10_mean < 90.0:
                        fails.append("FAIL_GATE_B3_POST_WASHOUT_72H_IL10_RECOVERY_LT_90PCT"); b3_ok = False
                    if is_finite_num(il10_rec) and abs(recomp_il10_mean - float(il10_rec)) > 0.1:
                        fails.append("FAIL_GATE_B3_IL10_RECOVERY_MISMATCH_VS_RAW_DONORS"); b3_ok = False
        if not (is_finite_num(nkg_mfi) and 85.0 <= float(nkg_mfi) <= 150.0 and is_finite_num(cd94_mfi) and 85.0 <= float(cd94_mfi) <= 150.0):
            fails.append("FAIL_GATE_B3_NKG2A_CD94_MFI_BELOW_85PCT"); b3_ok = False
        if not _validate_readout3b_nk(
            b3_ev.get("readout3b_evidence"), fails=fails, prefix="GATE_B3",
            require_sirpa_low=True, expected_vehicle_lot_id=blank_veh_40, max_vehicle_delta_pp=2.0,
            require_hla_e_spr=bool(spec["hla_e_engineered"]) if spec is not None else True,
        ):
            b3_ok = False
        if not _validate_readout2_gsis(
            b3_ev.get("readout2_evidence"), fails=fails, holds=holds, prefix="GATE_B3",
            expected_comparator_id=blank_veh_40, min_comparator_output_ratio=0.90,
            parent_recorded_at_utc=parse_utc_iso_ts(b3_ev.get("recorded_at_utc")),
            min_exposure_start_utc=parse_utc_iso_ts(b2be_ev.get("recorded_at_utc")) if b2be_ev is not None else None,
            expected_prod=prod_s, expected_bank=bank_s, expected_lot=lot_s, expected_route=route_s,
        ):
            b3_ok = False
        if spec is not None and not _validate_lineage_hour0_density(
            spec, b3_ev.get("hour0_density_by_lineage"),
            required_lineages=REQUIRED_HOUR0_LINEAGES_FULL, fails=fails, prefix="GATE_B3",
        ):
            b3_ok = False

    # Gate B-4: max inter-sample gap <= 72 h across [0, 240 h] (HOLD if gappy!) + matched-vehicle switch parity data!
    b4_extras = frozenset({
        "invivo_study_started_at_utc", "invivo_time_resolved_pk_gate_retained",
        "b4_local_compartment_calibration", "b4_systemic_compartment_calibration",
        "serial_pk_schedule_hours",
        "serial_pk_local_parent_free_nM", "serial_pk_local_bmt_free_nM",
        "serial_pk_systemic_parent_total_nM", "serial_pk_systemic_bmt_total_nM",
        "timepoint_replicate_records",
        "censoring_audit_passed", "blq_imputation_rule",
        "alpha_conc", "alpha_fu_parent", "alpha_fu_bmt",
        "intersample_peak_envelope_justified", "intersample_pk_envelope",
        "invivo_u95_joint_peak_free_nM", "invivo_days0_10_parent_lower_free_nM",
        "invivo_systemic_plasma_u95_nM", "matched_control_switch_parity_evidence",
        "mixture_requalification_receipt",
    })
    b4_ev = _validate_content_receipt(
        rec.get("b4_evidence"),
        expected_stage="B-4", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="exact_product",
        expected_coating_identity=coat_id,
        expected_parent=b3_ev,
        min_prereq_receipts=[("BANK_MATERIALIZATION", mat_ev), ("NATIVE_SAFETY_SWITCH", sw_ev), ("GATE-0V-KILL", g0v_ev)],
        allowed_extra_keys=b4_extras, fails=fails, holds=holds,
        missing_hold="HOLD_PRE_INVIVO_B4_PENDING",
        fail_code="FAIL_GATE_B4_INVIVO_PK_SWITCH_FAILED",
        mismatch_code="FAIL_GATE_B4_SCOPE_MISMATCH",
    )
    if b4_ev is not None:
        if not (is_strict_bool(b4_ev.get("invivo_time_resolved_pk_gate_retained")) and b4_ev["invivo_time_resolved_pk_gate_retained"]):
            fails.append("FAIL_MANDATORY_INVIVO_PK_GATE_WAIVED")
        t_st = parse_utc_iso_ts(b4_ev.get("invivo_study_started_at_utc"))
        t_b4 = parse_utc_iso_ts(b4_ev.get("recorded_at_utc"))
        t_b3 = parse_utc_iso_ts(b3_ev.get("recorded_at_utc")) if b3_ev is not None else None
        t_sw = parse_utc_iso_ts(sw_ev.get("recorded_at_utc")) if sw_ev is not None else None
        t_g0 = parse_utc_iso_ts(g0v_ev.get("recorded_at_utc")) if g0v_ev is not None else None
        if t_st is None or t_b4 is None:
            fails.append("FAIL_GATE_B4_MISSING_INVIVO_STUDY_START_UTC")
        else:
            for lbl, pt in (("B3", t_b3), ("SWITCH", t_sw), ("GATE0V", t_g0)):
                if pt is not None and t_st < pt:
                    fails.append(f"FAIL_GATE_B4_STUDY_STARTED_BEFORE_{lbl}")
            if (t_b4 - t_st) < timedelta(days=21):
                fails.append("FAIL_GATE_B4_ELAPSED_STUDY_DURATION_LT_21_DAYS")

        hrs = b4_ev.get("serial_pk_schedule_hours")
        lp_arr = b4_ev.get("serial_pk_local_parent_free_nM")
        lb_arr = b4_ev.get("serial_pk_local_bmt_free_nM")
        sp_arr = b4_ev.get("serial_pk_systemic_parent_total_nM")
        sb_arr = b4_ev.get("serial_pk_systemic_bmt_total_nM")
        a_c = b4_ev.get("alpha_conc")
        a_fp = b4_ev.get("alpha_fu_parent")
        a_fb = b4_ev.get("alpha_fu_bmt")
        b4_alpha_ok = (
            is_finite_num(a_c) and is_finite_num(a_fp) and is_finite_num(a_fb)
            and float(a_c) > 0.0 and float(a_fp) > 0.0 and float(a_fb) > 0.0
            and (float(a_c) + float(a_fp) + float(a_fb)) <= 0.05 + 1e-12
        )
        iv_pk = b4_ev.get("invivo_u95_joint_peak_free_nM")
        iv_lo = b4_ev.get("invivo_days0_10_parent_lower_free_nM")
        iv_sys = b4_ev.get("invivo_systemic_plasma_u95_nM")

        if not (is_strict_bool(b4_ev.get("censoring_audit_passed")) and b4_ev["censoring_audit_passed"]):
            fails.append("FAIL_GATE_B4_CENSORING_AUDIT_MISSING")
        if b4_ev.get("blq_imputation_rule") != "LLOQ_TIMES_FU_U_ALLOC_SAFETY_AND_ZERO_EFFICACY":
            fails.append("FAIL_GATE_B4_BLQ_IMPUTATION_RULE_INVALID")
        b4_eff_csafe = csafe_op_val
        b4_eff_ec50 = ec50_u95

        if not (
            isinstance(hrs, list) and len(hrs) >= 7
            and all(isinstance(arr, list) and len(arr) == len(hrs) for arr in (lp_arr, lb_arr, sp_arr, sb_arr))
            and all(is_finite_num(x) for x in hrs + lp_arr + lb_arr + sp_arr + sb_arr)
        ):
            fails.append("FAIL_GATE_B4_INVALID_OR_INCOMPLETE_SERIAL_PK_ARRAYS")
        else:
            hf = [float(x) for x in hrs]
            lpf = [float(x) for x in lp_arr]
            lbf = [float(x) for x in lb_arr]
            spf = [float(x) for x in sp_arr]
            sbf = [float(x) for x in sb_arr]
            if any(hf[i] >= hf[i + 1] for i in range(len(hf) - 1)) or hf[0] <= 0.0:
                fails.append("FAIL_GATE_B4_SERIAL_PK_TIMESTAMPS_NOT_STRICTLY_INCREASING")
            if t_st is not None and t_b4 is not None:
                elapsed_h = (t_b4 - t_st).total_seconds() / 3600.0
                if hf[-1] > elapsed_h + 1e-9:
                    fails.append("FAIL_GATE_B4_SERIAL_PK_SAMPLE_POSTDATES_RECEIPT")
            day21_indices = [i for i, h in enumerate(hf) if 504.0 <= h <= 528.0]
            if hf[0] > 6.0 or not any(6.0 < h <= 24.0 for h in hf) or not any(abs(h - 240.0) <= 12.0 for h in hf) or not day21_indices:
                fails.append("FAIL_GATE_B4_SERIAL_PK_WINDOW_MISSES_BURST_DAY10_OR_DAY21_WINDOW")
            # Enforce maximum inter-sample gap <= 72 h across the ENTIRE Day 0-21 window [0, 504 h] (zero post-Day-10 blind spots!)
            all_gaps = [hf[i + 1] - hf[i] for i in range(len(hf) - 1)]
            if all_gaps and max(all_gaps) > 72.0 + 1e-9:
                holds.append("HOLD_GATE_B4_INSUFFICIENT_TEMPORAL_COVERAGE_GAP_GT_72H")
            if min(lpf + lbf + spf + sbf) < 0.0:
                fails.append("FAIL_GATE_B4_NEGATIVE_SERIAL_PK_CONCENTRATION")
            local_comb = [lpf[i] + lbf[i] for i in range(len(hf))]
            sys_comb = [spf[i] + sbf[i] for i in range(len(hf))]
            if is_finite_num(iv_pk) and max(local_comb) > float(iv_pk) + 1e-9:
                fails.append("FAIL_GATE_B4_COMBINED_LOCAL_PEAK_EXCEEDS_REPORTED_U95_JOINT_PEAK")
            if is_finite_num(iv_sys) and max(sys_comb) > float(iv_sys) + 1e-9:
                fails.append("FAIL_GATE_B4_COMBINED_SYSTEMIC_PEAK_EXCEEDS_REPORTED_U95_SYSTEMIC")
            d0_10_lp = [lpf[i] for i in range(len(hf)) if hf[i] <= 240.0 + 1e-9]
            if d0_10_lp and is_finite_num(iv_lo) and float(iv_lo) > min(d0_10_lp) + 1e-9:
                fails.append("FAIL_GATE_B4_REPORTED_LOWER_BOUND_EXCEEDS_OBSERVED_MIN")
            check_wash_idxs = set(day21_indices) | {len(hf) - 1}
            if any(local_comb[idx] >= 2.0 or (ec50_u95 is not None and local_comb[idx] >= ec50_u95) for idx in check_wash_idxs):
                fails.append("FAIL_GATE_B4_DAY21_WASHOUT_NOT_EXHAUSTED")
            b4_tps = b4_ev.get("timepoint_replicate_records")
            loc_cal = b4_ev.get("b4_local_compartment_calibration")
            sys_cal = b4_ev.get("b4_systemic_compartment_calibration")
            b4_raw_bmt_trig = False
            b4_unbounded_bmt_ratio = False
            b4_obs_free_min = float("inf")
            b4_obs_free_max = 0.0
            u_local4_series: list[float] = []
            u_bmt4_free_series: list[float] = []
            l_bmt4_free_series: list[float] = []
            l_parent4_all_s: list[float] = []
            u_parent4_all_s: list[float] = []
            u_sys4_series: list[float] = []
            day21_u_joint4: Optional[float] = None
            b4_tp_ok = False
            loc_cal_keys = frozenset({
                "compartment_matrix_id", "concentration_basis", "pre_submission_recovery_correction_applied",
                "species_id", "analytical_method_id",
                "lloq_parent_nM", "lloq_bmt_nM", "probe_or_extraction_recovery_pct",
                "spike_accuracy_pct", "method_validated",
                "fu_parent_replicates", "fu_bmt_replicates", "calibration_sha256",
            })
            sys_cal_plasma_keys = frozenset({
                "compartment_matrix_id", "species_id", "analytical_method_id",
                "lloq_parent_nM", "lloq_bmt_nM", "spike_accuracy_pct", "method_validated",
                "fu_parent_replicates", "fu_bmt_replicates", "calibration_sha256",
            })
            sys_cal_wb_keys = sys_cal_plasma_keys | frozenset({
                "kbp_assay_method_id", "blood_to_plasma_ratio_parent_replicates",
                "blood_to_plasma_ratio_bmt_replicates", "alpha_kbp_parent", "alpha_kbp_bmt",
            })
            is_sys_wb = isinstance(sys_cal, Mapping) and sys_cal.get("compartment_matrix_id") == "SYSTEMIC_WHOLE_BLOOD"
            wb_cal_valid = (not is_sys_wb) or (
                set(sys_cal.keys()) == sys_cal_wb_keys
                and is_nonempty_str(sys_cal.get("kbp_assay_method_id"))
                and is_finite_num(sys_cal.get("alpha_kbp_parent")) and float(sys_cal["alpha_kbp_parent"]) > 0.0
                and is_finite_num(sys_cal.get("alpha_kbp_bmt")) and float(sys_cal["alpha_kbp_bmt"]) > 0.0
                and all(
                    isinstance(sys_cal.get(k), list) and len(sys_cal[k]) >= 3
                    and all(is_finite_num(x) and 0.05 <= float(x) <= 20.0 for x in sys_cal[k])
                    for k in ("blood_to_plasma_ratio_parent_replicates", "blood_to_plasma_ratio_bmt_replicates")
                )
            )
            cal_ok = (
                isinstance(loc_cal, Mapping) and set(loc_cal.keys()) == loc_cal_keys
                and isinstance(sys_cal, Mapping)
                and ((sys_cal.get("compartment_matrix_id") == "SYSTEMIC_PLASMA" and set(sys_cal.keys()) == sys_cal_plasma_keys) or (is_sys_wb and wb_cal_valid))
                and loc_cal.get("compartment_matrix_id") in ("PERI_GRAFT_MICRODIALYSIS_DIALYSATE", "PERI_GRAFT_INTERSTITIAL_FLUID", "EXPLANT_TISSUE_HOMOGENATE")
                and is_strict_bool(loc_cal.get("pre_submission_recovery_correction_applied")) and loc_cal["pre_submission_recovery_correction_applied"]
                and is_nonempty_str(loc_cal.get("species_id")) and loc_cal.get("species_id") == sys_cal.get("species_id")
                and is_nonempty_str(loc_cal.get("analytical_method_id")) and is_nonempty_str(sys_cal.get("analytical_method_id"))
                and is_strict_bool(loc_cal.get("method_validated")) and loc_cal["method_validated"]
                and is_strict_bool(sys_cal.get("method_validated")) and sys_cal["method_validated"]
                and is_finite_num(loc_cal.get("probe_or_extraction_recovery_pct")) and 70.0 <= float(loc_cal["probe_or_extraction_recovery_pct"]) <= 115.0
                and is_finite_num(loc_cal.get("spike_accuracy_pct")) and 80.0 <= float(loc_cal["spike_accuracy_pct"]) <= 120.0
                and is_finite_num(sys_cal.get("spike_accuracy_pct")) and 80.0 <= float(sys_cal["spike_accuracy_pct"]) <= 120.0
                and all(is_finite_num(c.get(k)) and 0.0 < float(c[k]) <= 0.2 for c in (loc_cal, sys_cal) for k in ("lloq_parent_nM", "lloq_bmt_nM"))
                and all(isinstance(c.get(k), list) and len(c[k]) >= 3 and all(is_finite_num(x) and 0.0 < float(x) <= 1.0 for x in c[k]) for c in (loc_cal, sys_cal) for k in ("fu_parent_replicates", "fu_bmt_replicates"))
                and all(is_valid_sha256_hex(c.get("calibration_sha256")) and sha256_bytes(canonical_json_bytes({k: v for k, v in c.items() if k != "calibration_sha256"})) == str(c["calibration_sha256"]) for c in (loc_cal, sys_cal))
                and (
                    (
                        loc_cal.get("compartment_matrix_id") == "PERI_GRAFT_MICRODIALYSIS_DIALYSATE"
                        and loc_cal.get("concentration_basis") == "RECOVERY_CORRECTED_UNBOUND_INTERSTITIAL_DIALYSATE"
                        and all(abs(float(x) - 1.0) <= 1e-6 for x in loc_cal["fu_parent_replicates"] + loc_cal["fu_bmt_replicates"])
                    )
                    or (
                        loc_cal.get("compartment_matrix_id") in ("PERI_GRAFT_INTERSTITIAL_FLUID", "EXPLANT_TISSUE_HOMOGENATE")
                        and loc_cal.get("concentration_basis") == "RECOVERY_CORRECTED_TOTAL_MATRIX_CONVERTED_BY_LOCAL_FU"
                    )
                )
            )
            a_kbp_tot = (float(sys_cal["alpha_kbp_parent"]) + float(sys_cal["alpha_kbp_bmt"])) if (is_sys_wb and wb_cal_valid) else 0.0
            b4_alpha_ok = (
                is_finite_num(a_c) and is_finite_num(a_fp) and is_finite_num(a_fb)
                and float(a_c) > 0.0 and float(a_fp) > 0.0 and float(a_fb) > 0.0
                and (float(a_c) + float(a_fp) + float(a_fb) + a_kbp_tot) <= 0.05 + 1e-12
            )
            l_kbp_p = 1.0
            l_kbp_b = 1.0
            kbp_bounds_ok = True
            if is_sys_wb and cal_ok:
                kp_b = sample_t_one_sided_bounds([float(x) for x in sys_cal["blood_to_plasma_ratio_parent_replicates"]], alpha=float(sys_cal["alpha_kbp_parent"]))
                kb_b = sample_t_one_sided_bounds([float(x) for x in sys_cal["blood_to_plasma_ratio_bmt_replicates"]], alpha=float(sys_cal["alpha_kbp_bmt"]))
                if kp_b is None or kb_b is None or kp_b[1] <= 0.0 or kb_b[1] <= 0.0:
                    holds.append("HOLD_GATE_B4_WHOLE_BLOOD_KBP_LOWER_BOUND_NONPOSITIVE")
                    kbp_bounds_ok = False
                else:
                    l_kbp_p, l_kbp_b = kp_b[1], kb_b[1]
            if not cal_ok:
                fails.append("FAIL_GATE_B4_MISSING_OR_INVALID_COMPARTMENT_CALIBRATION")
            elif not (isinstance(b4_tps, list) and len(b4_tps) == len(hf)):
                fails.append("FAIL_GATE_B4_MISSING_OR_INVALID_TIMEPOINT_REPLICATES")
            elif b4_alpha_ok and kbp_bounds_ok:
                b4_is_dialysate = (
                    loc_cal.get("compartment_matrix_id") == "PERI_GRAFT_MICRODIALYSIS_DIALYSATE"
                    and loc_cal.get("concentration_basis") == "RECOVERY_CORRECTED_UNBOUND_INTERSTITIAL_DIALYSATE"
                )
                b4_fp = loc_cal["fu_parent_replicates"]
                b4_fb = loc_cal["fu_bmt_replicates"]
                if b4_is_dialysate:
                    u_fp4 = l_fp4 = 1.0
                    u_fb4 = l_fb4 = 1.0
                else:
                    fp_b4 = sample_t_one_sided_bounds([float(x) for x in b4_fp], alpha=float(a_fp) / 2.0)
                    fb_b4 = sample_t_one_sided_bounds([float(x) for x in b4_fb], alpha=float(a_fb) / 2.0)
                    if fp_b4 is None or fb_b4 is None:
                        holds.append("HOLD_GATE_B4_LOCAL_FU_ZERO_DISPERSION_UNESTIMABLE")
                        u_fp4 = min(1.0, float(b4_fp[0]))
                        l_fp4 = max(0.0, float(b4_fp[0]))
                        u_fb4 = min(1.0, float(b4_fb[0]))
                        l_fb4 = max(0.0, float(b4_fb[0]))
                    else:
                        u_fp4, l_fp4 = min(1.0, fp_b4[2]), max(0.0, fp_b4[1])
                        u_fb4, l_fb4 = min(1.0, fb_b4[2]), max(0.0, fb_b4[1])
                m_fp4 = sum(float(x) for x in b4_fp) / len(b4_fp)
                m_fb4 = sum(float(x) for x in b4_fb) / len(b4_fb)
                # Unified familywise <= 0.05 Bonferroni budget covering ALL 6 one-sided concentration bounds per timepoint:
                # (1) u_local_joint, (2) l_parent, (3) u_parent, (4) u_local_bmt, (5) l_local_bmt, (6) u_sys_plasma_equiv!
                m4_total = max(1, 6 * len(hf))
                alpha_tp4 = float(a_c) / float(m4_total)
                b4_tp_allowed = frozenset({
                    "hour_h", "animal_ids", "analyte_pairing_mode",
                    "local_parent_total_replicates_nM", "local_parent_blq_flags",
                    "local_bmt_total_replicates_nM", "local_bmt_blq_flags",
                    "systemic_parent_total_replicates_nM", "systemic_parent_blq_flags",
                    "systemic_bmt_total_replicates_nM", "systemic_bmt_blq_flags",
                })
                b4_tp_ok = True
                lloq_p4_loc = float(loc_cal["lloq_parent_nM"])
                lloq_b4_loc = float(loc_cal["lloq_bmt_nM"])
                lloq_p4_sys = float(sys_cal["lloq_parent_nM"])
                lloq_b4_sys = float(sys_cal["lloq_bmt_nM"])
                for idx4, row4 in enumerate(b4_tps):
                    if not isinstance(row4, Mapping):
                        fails.append(f"FAIL_GATE_B4_MALFORMED_TP_ROW:{idx4}"); b4_tp_ok = False; continue
                    _check_allowed_keys(row4, b4_tp_allowed, fails, f"GATE_B4_TP_{idx4}")
                    hh4 = row4.get("hour_h")
                    an_ids = row4.get("animal_ids")
                    pair_m = row4.get("analyte_pairing_mode")
                    lp4, lp4_blq = row4.get("local_parent_total_replicates_nM"), row4.get("local_parent_blq_flags")
                    lb4, lb4_blq = row4.get("local_bmt_total_replicates_nM"), row4.get("local_bmt_blq_flags")
                    sp4, sp4_blq = row4.get("systemic_parent_total_replicates_nM"), row4.get("systemic_parent_blq_flags")
                    sb4, sb4_blq = row4.get("systemic_bmt_total_replicates_nM"), row4.get("systemic_bmt_blq_flags")
                    if not (
                        is_finite_num(hh4) and abs(float(hh4) - hf[idx4]) <= 1e-9
                        and pair_m == "PAIRED_WITHIN_SAME_ANIMAL_SAMPLE"
                        and all(isinstance(v, list) and len(v) >= 3 and all(is_finite_num(x) and float(x) >= 0.0 for x in v) for v in (lp4, lb4, sp4, sb4))
                        and len(lp4) == len(lb4) and len(sp4) == len(sb4) and len(lp4) == len(sp4)
                        and isinstance(an_ids, list) and len(an_ids) == len(lp4)
                        and all(is_nonempty_str(a) for a in an_ids)
                        and len({str(a).strip().upper() for a in an_ids}) == len(an_ids)
                        and all(isinstance(bf, list) and len(bf) == len(rv) and all(is_strict_bool(b) for b in bf) for bf, rv in ((lp4_blq, lp4), (lb4_blq, lb4), (sp4_blq, sp4), (sb4_blq, sb4)))
                    ):
                        fails.append(f"FAIL_GATE_B4_INVALID_TP_REPLICATES:{idx4}"); b4_tp_ok = False; continue
                    lp4f = [float(x) for x in lp4]
                    lb4f = [float(x) for x in lb4]
                    sp4f = [float(x) for x in sp4]
                    sb4f = [float(x) for x in sb4]
                    if abs((sum(lp4f) / len(lp4f)) * m_fp4 - lpf[idx4]) > 0.25 or abs((sum(lb4f) / len(lb4f)) * m_fb4 - lbf[idx4]) > 0.05:
                        fails.append(f"FAIL_GATE_B4_SUMMARY_SERIES_MISMATCH_VS_REPLICATES:{idx4}"); b4_tp_ok = False
                    for snm, vals4, flgs4, lloq4 in (
                        ("LOCAL_PARENT", lp4f, lp4_blq, lloq_p4_loc),
                        ("LOCAL_BMT", lb4f, lb4_blq, lloq_b4_loc),
                        ("SYS_PARENT", sp4f, sp4_blq, lloq_p4_sys),
                        ("SYS_BMT", sb4f, sb4_blq, lloq_b4_sys),
                    ):
                        for _bi4, _bv4 in enumerate(vals4):
                            if flgs4[_bi4] and _bv4 >= lloq4 - 1e-12:
                                fails.append(f"FAIL_GATE_B4_BLQ_FLAG_CONTRADICTS_QUANTIFIABLE_{snm}:{idx4}")
                            elif (not flgs4[_bi4]) and _bv4 < lloq4 - 1e-12:
                                fails.append(f"FAIL_GATE_B4_UNFLAGGED_BLQ_{snm}_REPLICATE:{idx4}")
                    cf4_int = [
                        (
                            (0.0 if lp4_blq[i] else lp4f[i]) * u_fp4 + (0.0 if lb4_blq[i] else lb4f[i]) * u_fb4,
                            (lloq_p4_loc if lp4_blq[i] else lp4f[i]) * u_fp4 + (lloq_b4_loc if lb4_blq[i] else lb4f[i]) * u_fb4,
                        )
                        for i in range(len(lp4f))
                    ]
                    u_j4 = censor_aware_t_bound(cf4_int, alpha=alpha_tp4, upper=True)
                    if u_j4 is None:
                        holds.append(f"HOLD_GATE_B4_CENSOR_AWARE_BOUND_UNESTIMABLE:{idx4}")
                        u_j4 = max(hi for _, hi in cf4_int)
                    u_local4_series.append(u_j4)
                    lb4_int = [(0.0, lloq_b4_loc) if lb4_blq[i] else (lb4f[i], lb4f[i]) for i in range(len(lb4f))]
                    u_lb4_c = censor_aware_t_bound(lb4_int, alpha=alpha_tp4, upper=True)
                    l_lb4_c = censor_aware_t_bound(lb4_int, alpha=alpha_tp4, upper=False)
                    u_bmt4_free_series.append((max(hi for _, hi in lb4_int) if u_lb4_c is None else u_lb4_c) * u_fb4)
                    l_bmt4_free_series.append((0.0 if (l_lb4_c is None or any(lb4_blq)) else max(0.0, l_lb4_c)) * l_fb4)
                    if idx4 in check_wash_idxs:
                        day21_u_joint4 = u_j4 if day21_u_joint4 is None else max(day21_u_joint4, u_j4)
                    p4_int = [
                        ((0.0 if lp4_blq[i] else lp4f[i]) * l_fp4, (lloq_p4_loc if lp4_blq[i] else lp4f[i]) * l_fp4)
                        for i in range(len(lp4f))
                    ]
                    l_p4 = censor_aware_t_bound(p4_int, alpha=alpha_tp4, upper=False)
                    if l_p4 is None:
                        holds.append(f"HOLD_GATE_B4_CENSOR_AWARE_PARENT_BOUND_UNESTIMABLE:{idx4}")
                        l_p4 = 0.0
                    l_parent4_all_s.append(max(0.0, l_p4))
                    p4_up_int = [
                        ((0.0 if lp4_blq[i] else lp4f[i]) * u_fp4, (lloq_p4_loc if lp4_blq[i] else lp4f[i]) * u_fp4)
                        for i in range(len(lp4f))
                    ]
                    u_p4 = censor_aware_t_bound(p4_up_int, alpha=alpha_tp4, upper=True)
                    u_parent4_all_s.append(max(hi for _, hi in p4_up_int) if u_p4 is None else max(0.0, u_p4))
                    for i in range(len(lp4f)):
                        if lp4_blq[i] or lp4f[i] <= 0.0:
                            if lloq_b4_loc > 0.0 or (not lb4_blq[i] and lb4f[i] > 0.0):
                                b4_unbounded_bmt_ratio = True
                        elif l_fp4 > 0.0 and u_fp4 > 0.0:
                            b4_obs_free_max = max(b4_obs_free_max, ((lloq_b4_loc if lb4_blq[i] else lb4f[i]) * u_fb4) / (lp4f[i] * l_fp4))
                            b4_obs_free_min = min(b4_obs_free_min, ((0.0 if lb4_blq[i] else lb4f[i]) * l_fb4) / (lp4f[i] * u_fp4))
                    # Convert whole-blood concentrations conservatively to plasma equivalents via 1/L_kbp before < 0.5 nM plasma cap!
                    sys4_int = [
                        (
                            (0.0 if sp4_blq[i] else sp4f[i]) / l_kbp_p + (0.0 if sb4_blq[i] else sb4f[i]) / l_kbp_b,
                            (lloq_p4_sys if sp4_blq[i] else sp4f[i]) / l_kbp_p + (lloq_b4_sys if sb4_blq[i] else sb4f[i]) / l_kbp_b,
                        )
                        for i in range(len(sp4f))
                    ]
                    u_s4 = censor_aware_t_bound(sys4_int, alpha=alpha_tp4, upper=True)
                    if u_s4 is None:
                        holds.append(f"HOLD_GATE_B4_CENSOR_AWARE_SYS_BOUND_UNESTIMABLE:{idx4}")
                        u_s4 = max(hi for _, hi in sys4_int)
                    u_sys4_series.append(u_s4)
                    if max(lb4f) >= lloq_b4_loc or max(sb4f) >= lloq_b4_sys:
                        b4_raw_bmt_trig = True

            # Validate continuous PK envelope & compute interval-wide worst-case BMT/parent ratio BEFORE mixture requalification!
            b4_env_res = None
            b4_cont_ratio_min = float("inf")
            b4_cont_ratio_max = 0.0
            b4_cont_unbounded = False
            if b4_tp_ok:
                b4_env_res = _validate_and_apply_continuous_pk_envelope(
                    b4_ev.get("intersample_pk_envelope"),
                    hours_seen=hf, u_local_series=u_local4_series,
                    l_parent_all_series=l_parent4_all_s,
                    u_sys_series=u_sys4_series, max_efficacy_start_h=0.0,
                    expected_coating_article_id=(coat_id.get("coating_article_id") if coat_id else None),
                    expected_evidence_scope="exact_product",
                    expected_compartment_id="INVIVO_PERIGRAFT_AND_SYSTEMIC",
                    fails=fails, holds=holds, prefix="GATE_B4",
                )
                if b4_env_res is not None:
                    b4_cont_ratio_min, b4_cont_ratio_max, b4_cont_unbounded = _compute_continuous_bmt_parent_ratio_bounds(
                        hf, u_bmt4_free_series, l_bmt4_free_series, l_parent4_all_s, u_parent4_all_s,
                        b4_ev.get("intersample_pk_envelope"), fails=fails, prefix="GATE_B4",
                    )
            b4_eff_unbounded = b4_unbounded_bmt_ratio or b4_cont_unbounded
            b4_eff_ratio_min = min(0.0 if b4_obs_free_min == float("inf") else b4_obs_free_min, b4_cont_ratio_min)
            b4_eff_ratio_max = max(b4_obs_free_max, b4_cont_ratio_max)

            # ZERO silent fallback from b2be_ev! B-4 MUST validate its own mixture_requalification_receipt
            # covering the full interval-wide continuous BMT/parent ratio envelope!
            bmt_local_trig = csafe_op_val is not None and max(lbf) >= 0.10 * csafe_op_val
            bmt_sys_trig = lloq_bmt_min is not None and max(sbf) >= lloq_bmt_min
            b4_mix_rec = b4_ev.get("mixture_requalification_receipt")
            if b4_eff_unbounded or bmt_local_trig or bmt_sys_trig or b4_raw_bmt_trig or (b4_mix_rec is not None):
                if b4_mix_rec is None:
                    if b4_eff_unbounded:
                        holds.append("HOLD_GATE_B4_UNBOUNDED_BMT_TO_PARENT_RATIO_UNDER_PARENT_BLQ")
                    if bmt_local_trig or bmt_sys_trig or b4_raw_bmt_trig:
                        fails.append("FAIL_GATE_B4_INVIVO_BMT_SPIKE_WITHOUT_MIXTURE_REQUAL")
                else:
                    m_ok4, m_e4, m_c4 = _validate_mixture_requal_receipt(
                        b4_mix_rec, expected_prod=prod_s, expected_bank=bank_s,
                        expected_lot=lot_s, expected_route=route_s, expected_scope="exact_product",
                        expected_coating_identity=coat_id,
                        parent_recorded_at_utc=t_b4,
                        observed_bmt_to_parent_ratio_min=b4_eff_ratio_min,
                        observed_bmt_to_parent_ratio_max=b4_eff_ratio_max,
                        unbounded_ratio_under_parent_blq=b4_eff_unbounded,
                        fails=fails, holds=holds, prefix="GATE_B4",
                    )
                    if not m_ok4 or m_e4 is None or m_c4 is None:
                        if bmt_local_trig or bmt_sys_trig or b4_raw_bmt_trig:
                            fails.append("FAIL_GATE_B4_INVIVO_BMT_SPIKE_WITHOUT_MIXTURE_REQUAL")
                    else:
                        b4_eff_ec50 = max(b4_eff_ec50, m_e4) if b4_eff_ec50 is not None else m_e4
                        b4_eff_csafe = min(b4_eff_csafe, m_c4) if b4_eff_csafe is not None else m_c4

            if b4_tp_ok:
                if b4_env_res is not None:
                    env_u_j4, env_l_p4, env_u_s4 = b4_env_res
                    if is_finite_num(iv_pk) and float(iv_pk) + 1e-4 < env_u_j4:
                        fails.append("FAIL_GATE_B4_CLAIMED_PEAK_UNDERSTATES_RECOMPUTED_SIMULTANEOUS_U95")
                    if b4_eff_csafe is not None and env_u_j4 >= b4_eff_csafe:
                        fails.append("FAIL_GATE_B4_CONTINUOUS_PEAK_EXCEEDS_CSAFE")
                    if is_finite_num(iv_lo) and env_l_p4 >= 0.0 and float(iv_lo) - 1e-4 > env_l_p4:
                        fails.append("FAIL_GATE_B4_CLAIMED_FLOOR_OVERSTATES_RECOMPUTED_SIMULTANEOUS_L95")
                    if b4_eff_ec50 is not None and env_l_p4 < b4_eff_ec50:
                        fails.append("FAIL_GATE_B4_CONTINUOUS_TROUGH_BELOW_EC50")
                    if is_finite_num(iv_sys) and float(iv_sys) + 1e-4 < env_u_s4:
                        fails.append("FAIL_GATE_B4_CLAIMED_SYSTEMIC_UNDERSTATES_RECOMPUTED_SIMULTANEOUS_U95")
                    if env_u_s4 >= 0.5:
                        fails.append("FAIL_GATE_B4_CONTINUOUS_SYSTEMIC_PEAK_GE_0P5NM")
                if day21_u_joint4 is not None and (day21_u_joint4 >= 2.0 or (b4_eff_ec50 is not None and day21_u_joint4 >= b4_eff_ec50)):
                    fails.append("FAIL_GATE_B4_DAY21_REPLICATE_WASHOUT_U95_NOT_EXHAUSTED")

        if not b4_alpha_ok:
            fails.append("FAIL_GATE_B4_GLOBAL_ALPHA_EXCEEDS_0P05")
        if not (is_strict_bool(b4_ev.get("intersample_peak_envelope_justified")) and b4_ev["intersample_peak_envelope_justified"]):
            fails.append("FAIL_GATE_B4_INTERSAMPLE_PEAK_UNJUSTIFIED")
        if not all(is_finite_num(x) for x in (iv_pk, iv_lo, iv_sys)):
            fails.append("FAIL_GATE_B4_MISSING_MEASURED_INVIVO_PK_VALUES")
        else:
            if float(iv_pk) < float(iv_lo) - 1e-12 or float(iv_sys) < 0.0:
                fails.append("FAIL_GATE_B4_INVALID_INVIVO_PK_ORDERING")
            if b4_eff_csafe is not None and float(iv_pk) >= b4_eff_csafe:
                fails.append("FAIL_GATE_B4_INVIVO_PEAK_NOT_STRICTLY_BELOW_CSAFE")
            if b4_eff_ec50 is not None and float(iv_lo) < b4_eff_ec50:
                fails.append("FAIL_GATE_B4_INVIVO_PARENT_FLOOR_BELOW_EC50")
            if float(iv_sys) >= 0.5:
                fails.append("FAIL_GATE_B4_INVIVO_SYSTEMIC_PLASMA_GE_0P5NM")
        _validate_matched_control_switch_parity(
            b4_ev.get("matched_control_switch_parity_evidence"),
            expected_control_lot_id=blank_veh_40, fails=fails, holds=holds, prefix="GATE_B4",
        )
        if not (b0a_ok and b0b_ok and b1_ok and b2_ok and b2bb_ok and b0a_ex_ok and b2be_ok and b3_ok):
            fails.append("FAIL_GATE_B4_ATTEMPTED_WITHOUT_ALL_PREDECESSORS")

    if fails:
        verdict = "FAIL"
    elif holds:
        verdict = "HOLD"
    elif scope_track == "PRIMARY":
        verdict = OFFLINE_VERDICT_PRIMARY
    elif scope_track == "SENSITIVITY_Z_R3P":
        verdict = "SENSITIVITY_TRACK_ONLY_NON_PRIMARY"
    elif scope_track == "SEPARATE_ROUTE4_VEHICLE":
        verdict = "SEPARATE_ROUTE4_VEHICLE_TRACK_NON_PRIMARY"
    else:
        verdict = "DEFERRED_TRACK_QUALIFICATION_NON_PRIMARY"

    return {
        "gate": "GATE-41", "phase": phase, "scope_track": scope_track, "verdict": verdict,
        "release_authorizing": False, "live_ledger_authenticated": False,
        "upstream_archive_verification": OFFLINE_ARCHIVE_NOTE,
        "product_id": rec.get("product_id"),
        "required_switch": spec["required_switch"] if spec else None,
        "failures": fails, "holds": holds,
    }


# ---------------------------------------------------------------------------
# GATE-42 (IIP-0064 / DEC-145): 100% Drug-Free GY-032 Channel c Transient Screen
# ---------------------------------------------------------------------------

GATE42_ALLOWED_KEYS: FrozenSet[str] = frozenset({
    "target_arm", "product_id", "bank_id", "lot_id", "route_id",
    "drug_free_exposure_evidence", "materialization_evidence", "gate31_evidence",
    "foundry_v2_gate36_evidence",
    "native_switch_evidence", "gate0v_evidence",
    "zero_fasta_minted", "iip0049_foundry_attribution_evidence", "target_gene",
    "c1_preregistered_plan_receipt", "c1_evidence", "c2_evidence", "c3_nk_evidence", "c3_gsis_evidence",
})

REQUIRED_IIP0049_REFERENCE_BACKGROUNDS: FrozenSet[str] = frozenset({
    "PARENTAL_UNEDITED",
    "DESIGN_A_CHASSIS_REFERENCE",
    "MULTI_MIR_IL1R1_FAS_REFERENCE",
    "STANDALONE_IL1R1_FAS_CBE_REFERENCE",
    "CD64T_IL1RN_REFERENCE",
})

C1_FAMILY_GENES: FrozenSet[str] = frozenset({"BCL2L11", "PMAIP1", "PMAIP1+BCL2L11", "BBC3", "JAK2"})

C1_OXYGEN_ALLOWED_KEYS: FrozenSet[str] = frozenset({
    "assay_record_id", "assay_acquired_at_utc", "block_ids",
    "differentiation_batch_ids", "randomized_arm_orders_by_block", "target_kd_pct",
    "mrna_kd_pct", "protein_kd_pct", "mrna_assay_record_id", "protein_assay_record_id", "molecular_kd_provenance",
    "pmaip1_kd_pct", "bcl2l11_kd_pct",
    "pmaip1_mrna_kd_pct", "pmaip1_protein_kd_pct", "bcl2l11_mrna_kd_pct", "bcl2l11_protein_kd_pct",
    "casp9_stressed_ctrl_raw_by_block", "casp9_treated_raw_by_block",
    "casp9_reduction_pct_by_block", "family_raw_p_values_casp9", "holm_adjusted_casp9_p_value",
    "stressed_ctrl_beta_plated_t0_by_block", "stressed_ctrl_beta_surviving_by_block",
    "treated_beta_plated_t0_by_block", "treated_beta_surviving_by_block",
    "unstressed_vehicle_beta_plated_t0_by_block", "unstressed_vehicle_beta_surviving_by_block",
    "stressed_ctrl_beta_t0_pct_by_block", "treated_beta_t0_pct_by_block",
    "unstressed_vehicle_beta_t0_pct_by_block", "family_raw_p_values_beta", "holm_adjusted_beta_p_value",
    "all_five_arms_paired_data", "normality_diagnostic_record",
    "bcl2l11_comparator_beta_t0_pct_by_block", "head_to_head_vs_bcl2l11_l95_delta_pp",
    "gy001_cxcl10_inducible_shield_pct_ctrl",
    "nonbeta_lineage_min_surv_pct_ctrl", "stressed_ctrl_nonbeta_t0_survival_pct",
    "t0_original_plated_denominators_used", "pmlkl_flag_triggered",
    "gy016_nec1s_gsk872_orthogonal_rescue_cleared",
    "lineage_timecourse_counts", "death_pathway_diversion_assay",
    "mock_transfection_control_by_block",
})

C1_REQUIRED_5_LINEAGES: FrozenSet[str] = frozenset({
    "INS_beta", "GCG_alpha", "SST_delta", "PLVAP_iEC", "pericyte_stromal",
})


def _validate_transient_engagement_record(
    rec_obj: Optional[Mapping[str, Any]],
    *,
    target_gene: str,
    expected_cohort_id: Optional[str],
    expected_lot_id: Optional[str],
    expected_specimen_id: Optional[str],
    min_stage_ts: Optional[datetime],
    required_start_ts: Optional[datetime],
    required_end_ts: Optional[datetime],
    stage_tag: str,
    fails: list[str],
    holds: list[str],
    require_longitudinal_mode: bool = False,
    required_covering_ts: Sequence[datetime] = (),
) -> None:
    """Verify paired start+end OR longitudinal producer-linked target engagement
    spans the ENTIRE [assay_started, assay_completed] window on the exact specimen (requiring validated longitudinal
    timepoints spanning 0 h / 24 h / 72 h on 72-h safety switches), cleanly distinguishing missing temporal coverage
    from biological recovery/decay!"""
    if rec_obj is None:
        return
    eng = rec_obj.get("transient_target_engagement_record")
    if eng is None:
        holds.append(f"HOLD_GATE_C_MISSING_TRANSIENT_ENGAGEMENT_RECORD:{stage_tag}"); return
    if not isinstance(eng, Mapping):
        fails.append(f"FAIL_GATE_C_MALFORMED_TRANSIENT_ENGAGEMENT_RECORD:{stage_tag}"); return
    emode = eng.get("engagement_measurement_mode")
    if require_longitudinal_mode and emode != "VALIDATED_LONGITUDINAL_KINETICS":
        fails.append(f"FAIL_GATE_C_SAFETY_SWITCH_REQUIRES_VALIDATED_LONGITUDINAL_KINETICS:{stage_tag}"); return
    req_k = {
        "intervention_cohort_id", "stage_name", "specimen_lot_id", "specimen_id",
        "engagement_measurement_mode",
        "start_aliquot_assay_record_id", "end_aliquot_assay_record_id",
        "assay_window_start_utc", "assay_window_end_utc",
        "start_measured_at_utc", "end_measured_at_utc",
        "start_of_window_kd_pct", "end_of_window_kd_pct",
        "target_kd_pct", "recovered_to_control", "engagement_record_sha256",
    }
    if target_gene == "PMAIP1+BCL2L11":
        req_k |= {"pmaip1_start_kd_pct", "pmaip1_end_kd_pct", "bcl2l11_start_kd_pct", "bcl2l11_end_kd_pct"}
    if emode == "VALIDATED_LONGITUDINAL_KINETICS":
        req_k |= {"validated_kinetics_protocol_sha256", "longitudinal_kinetics_timepoints"}
    if set(eng.keys()) != req_k:
        fails.append(f"FAIL_GATE_C_MALFORMED_TRANSIENT_ENGAGEMENT_RECORD:{stage_tag}"); return
    esha = eng.get("engagement_record_sha256")
    s_aid = eng.get("start_aliquot_assay_record_id")
    e_aid = eng.get("end_aliquot_assay_record_id")
    t_ws = parse_utc_iso_ts(eng.get("assay_window_start_utc"))
    t_we = parse_utc_iso_ts(eng.get("assay_window_end_utc"))
    t_sm = parse_utc_iso_ts(eng.get("start_measured_at_utc"))
    t_em = parse_utc_iso_ts(eng.get("end_measured_at_utc"))
    t_rec = parse_utc_iso_ts(rec_obj.get("recorded_at_utc"))
    kd_st = eng.get("start_of_window_kd_pct")
    kd_en = eng.get("end_of_window_kd_pct")
    kd_min = eng.get("target_kd_pct")
    if (
        not is_valid_sha256_hex(esha)
        or sha256_bytes(canonical_json_bytes({k: v for k, v in eng.items() if k != "engagement_record_sha256"})) != str(esha)
        or emode not in ("PAIRED_START_AND_END_ALIQUOT_ASSAY", "VALIDATED_LONGITUDINAL_KINETICS")
        or not is_nonempty_str(s_aid) or not is_nonempty_str(e_aid)
        or not is_nonempty_str(eng.get("intervention_cohort_id"))
        or (expected_cohort_id is not None and str(eng["intervention_cohort_id"]).strip() != expected_cohort_id)
        or eng.get("stage_name") != stage_tag
        or not is_nonempty_str(eng.get("specimen_lot_id"))
        or (expected_lot_id is not None and str(eng["specimen_lot_id"]).strip() != expected_lot_id)
        or not is_nonempty_str(eng.get("specimen_id"))
        or (expected_specimen_id is not None and str(eng["specimen_id"]).strip() != expected_specimen_id)
        or t_ws is None or t_we is None or t_sm is None or t_em is None
        or t_ws > t_sm or t_sm > t_em or t_em > t_we
        or (t_we > t_ws and str(s_aid).strip().upper() == str(e_aid).strip().upper())
        or (t_rec is not None and t_we > t_rec)
        or (min_stage_ts is not None and t_ws < min_stage_ts)
        or (required_start_ts is not None and t_ws > required_start_ts)
        or (required_end_ts is not None and t_we < required_end_ts)
        or not is_strict_bool(eng.get("recovered_to_control"))
        or not (is_finite_num(kd_st) and is_finite_num(kd_en) and is_finite_num(kd_min))
    ):
        fails.append(f"FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:{stage_tag}"); return
    all_kd_vals = [float(kd_st), float(kd_en)]
    all_dual_vals: list[float] = []
    if target_gene == "PMAIP1+BCL2L11":
        for dk in ("pmaip1_start_kd_pct", "pmaip1_end_kd_pct", "bcl2l11_start_kd_pct", "bcl2l11_end_kd_pct"):
            if not is_finite_num(eng.get(dk)):
                fails.append(f"FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:{stage_tag}"); return
            all_dual_vals.append(float(eng[dk]))
    t_ks: list[datetime] = []
    if emode == "VALIDATED_LONGITUDINAL_KINETICS":
        if not is_valid_sha256_hex(eng.get("validated_kinetics_protocol_sha256")):
            fails.append(f"FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:{stage_tag}"); return
        ltps = eng.get("longitudinal_kinetics_timepoints")
        tp_req_k = {
            "aliquot_assay_record_id", "specimen_lot_id", "specimen_id",
            "producer_record_sha256", "measured_at_utc", "target_kd_pct",
        }
        if target_gene == "PMAIP1+BCL2L11":
            tp_req_k |= {"pmaip1_kd_pct", "bcl2l11_kd_pct"}
        if not isinstance(ltps, list) or len(ltps) < 3:
            fails.append(f"FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:{stage_tag}"); return
        seen_t_aids: set[str] = set()
        tp_kds: list[float] = []
        for t_idx, trow in enumerate(ltps):
            if not isinstance(trow, Mapping) or set(trow.keys()) != tp_req_k:
                fails.append(f"FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:{stage_tag}"); return
            taid = trow.get("aliquot_assay_record_id")
            tts = parse_utc_iso_ts(trow.get("measured_at_utc"))
            tkd = trow.get("target_kd_pct")
            tlot = trow.get("specimen_lot_id")
            tsp = trow.get("specimen_id")
            tpsha = trow.get("producer_record_sha256")
            if (
                not is_nonempty_str(taid) or tts is None or not is_finite_num(tkd)
                or not is_nonempty_str(tlot) or not is_nonempty_str(tsp)
                or not is_valid_sha256_hex(tpsha)
                or (expected_lot_id is not None and str(tlot).strip() != expected_lot_id)
                or (expected_specimen_id is not None and str(tsp).strip() != expected_specimen_id)
            ):
                fails.append(f"FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:{stage_tag}"); return
            taid_n = str(taid).strip().upper()
            if taid_n in seen_t_aids:
                fails.append(f"FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:{stage_tag}"); return
            seen_t_aids.add(taid_n)
            if t_ks and (tts <= t_ks[-1] or (tts - t_ks[-1]).total_seconds() > 48.0 * 3600.0 + 1e-6):
                fails.append(f"FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:{stage_tag}"); return
            t_ks.append(tts)
            tp_kds.append(float(tkd))
            if target_gene == "PMAIP1+BCL2L11":
                if not (is_finite_num(trow.get("pmaip1_kd_pct")) and is_finite_num(trow.get("bcl2l11_kd_pct"))):
                    fails.append(f"FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:{stage_tag}"); return
                all_dual_vals.extend([float(trow["pmaip1_kd_pct"]), float(trow["bcl2l11_kd_pct"])])
        if (
            str(ltps[0]["aliquot_assay_record_id"]).strip().upper() != str(s_aid).strip().upper()
            or str(ltps[-1]["aliquot_assay_record_id"]).strip().upper() != str(e_aid).strip().upper()
            or t_ks[0] != t_sm or t_ks[-1] != t_em
            or abs(tp_kds[0] - float(kd_st)) > 1e-6 or abs(tp_kds[-1] - float(kd_en)) > 1e-6
        ):
            fails.append(f"FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:{stage_tag}"); return
        all_kd_vals.extend(tp_kds)
    if abs(float(kd_min) - min(all_kd_vals)) > 1e-6:
        fails.append(f"FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:{stage_tag}"); return
    # Distinct temporal-coverage HOLDs anchored strictly to ACTUAL assay boundaries (never hidden by a wide declared window!)
    if required_start_ts is not None:
        if require_longitudinal_mode:
            # Must have a producer-bound start observation at actual assay t=0 within [-1.0 h, +0.5 h] AND t_sm <= assay_start + 0.5 h
            if (t_sm - required_start_ts).total_seconds() > 1800.0 + 1e-6 or (required_start_ts - t_sm).total_seconds() > 7200.0 + 1e-6:
                holds.append(f"HOLD_GATE_C_TRANSIENT_ENGAGEMENT_MISSING_START_COVERAGE:{stage_tag}"); return
            if not any(-3600.0 - 1e-6 <= (tk - required_start_ts).total_seconds() <= 1800.0 + 1e-6 for tk in t_ks):
                holds.append(f"HOLD_GATE_C_TRANSIENT_ENGAGEMENT_MISSING_START_COVERAGE:{stage_tag}"); return
        else:
            if (t_sm - required_start_ts).total_seconds() > 3600.0 + 1e-6:
                holds.append(f"HOLD_GATE_C_TRANSIENT_ENGAGEMENT_MISSING_START_COVERAGE:{stage_tag}"); return
    if (t_sm - t_ws).total_seconds() > 86400.0 + 1e-6:
        holds.append(f"HOLD_GATE_C_TRANSIENT_ENGAGEMENT_MISSING_START_COVERAGE:{stage_tag}"); return
    if required_end_ts is not None:
        if require_longitudinal_mode:
            if (required_end_ts - t_em).total_seconds() > 3600.0 + 1e-6:
                holds.append(f"HOLD_GATE_C_TRANSIENT_ENGAGEMENT_STALE_BEFORE_ASSAY_END:{stage_tag}"); return
            if not any(abs((tk - required_end_ts).total_seconds()) <= 3600.0 + 1e-6 for tk in t_ks):
                holds.append(f"HOLD_GATE_C_TRANSIENT_ENGAGEMENT_STALE_BEFORE_ASSAY_END:{stage_tag}"); return
        else:
            if (required_end_ts - t_em).total_seconds() > 3600.0 + 1e-6:
                holds.append(f"HOLD_GATE_C_TRANSIENT_ENGAGEMENT_STALE_BEFORE_ASSAY_END:{stage_tag}"); return
    if (t_we - t_em).total_seconds() > 86400.0 + 1e-6:
        holds.append(f"HOLD_GATE_C_TRANSIENT_ENGAGEMENT_STALE_BEFORE_ASSAY_END:{stage_tag}"); return
    if emode == "VALIDATED_LONGITUDINAL_KINETICS":
        for t_cov in required_covering_ts:
            if not any(abs((tk - t_cov).total_seconds()) <= 2.0 * 3600.0 + 1e-6 for tk in t_ks):
                holds.append(f"HOLD_GATE_C_TRANSIENT_ENGAGEMENT_MISSING_LONGITUDINAL_ENDPOINT_COVERAGE:{stage_tag}"); return
    if eng["recovered_to_control"] is True:
        holds.append(f"HOLD_GATE_C_TRANSIENT_ENGAGEMENT_DECAYED_BEFORE_ASSAY:{stage_tag}"); return
    if target_gene == "JAK2":
        if not all(50.0 <= kv <= 65.0 for kv in all_kd_vals):
            holds.append(f"HOLD_GATE_C_TRANSIENT_ENGAGEMENT_DECAYED_BEFORE_ASSAY:{stage_tag}")
    else:
        if not all(60.0 <= kv <= 100.0 for kv in all_kd_vals):
            holds.append(f"HOLD_GATE_C_TRANSIENT_ENGAGEMENT_DECAYED_BEFORE_ASSAY:{stage_tag}"); return
        if target_gene == "PMAIP1+BCL2L11" and not all(60.0 <= kv <= 100.0 for kv in all_dual_vals):
            holds.append(f"HOLD_GATE_C_TRANSIENT_ENGAGEMENT_DECAYED_BEFORE_ASSAY:{stage_tag}")


def _compute_c1_arm_raw_p(
    vals: Sequence[Any], stat_method: str, *, paired_control: Optional[Sequence[Any]] = None,
) -> tuple[Optional[float], Optional[str]]:
    if stat_method == "PAIRED_T_TEST_NORMALITY_VERIFIED":
        d_f = [float(a) - float(b) for a, b in zip(vals, paired_control)] if paired_control is not None else [float(x) for x in vals]
        st = paired_t_summary(d_f)
        if st is None:
            return None, "DEGENERATE_ZERO_VARIANCE"
        return st[2], None
    p_sf = exact_two_sided_sign_flip_paired_p(vals, paired_control) if paired_control is not None else exact_two_sided_sign_flip_p(vals)
    if p_sf is None:
        return None, "SIGN_FLIP_N_GT_20"
    return p_sf, None


def _validate_c1_oxygen_block(
    blk: Any,
    *,
    o2_tag: str,
    target: str,
    stat_method: str,
    expected_n: int,
    min_acq_ts: Optional[datetime] = None,
    max_acq_ts: Optional[datetime] = None,
    expected_block_ids_norm: Optional[list[str]] = None,
    expected_batch_ids_norm: Optional[list[str]] = None,
    expected_arm_orders: Optional[list[list[str]]] = None,
    expected_prod_id: Optional[str] = None,
    expected_lot_id: Optional[str] = None,
    expected_cohort_id: Optional[str] = None,
    fails: list[str],
    holds: list[str],
) -> Optional[tuple[str, list[float], list[float], list[float], list[float], dict[str, float], dict[str, float]]]:
    if blk is None:
        holds.append(f"HOLD_GATE_C1_{o2_tag}_MISSING"); return None
    if not isinstance(blk, Mapping):
        fails.append(f"FAIL_GATE_C1_{o2_tag}_MALFORMED"); return None
    _check_allowed_keys(blk, C1_OXYGEN_ALLOWED_KEYS, fails, f"GATE_C1_{o2_tag}")

    aid = blk.get("assay_record_id")
    if not is_nonempty_str(aid):
        fails.append(f"FAIL_GATE_C1_{o2_tag}_MISSING_ASSAY_RECORD_ID"); return None
    t_blk_acq = parse_utc_iso_ts(blk.get("assay_acquired_at_utc"))
    if t_blk_acq is None or (min_acq_ts is not None and t_blk_acq < min_acq_ts) or (max_acq_ts is not None and t_blk_acq > max_acq_ts):
        fails.append(f"FAIL_GATE_C1_{o2_tag}_INVALID_OR_OUT_OF_ORDER_ASSAY_ACQUISITION_UTC")

    bids = blk.get("block_ids")
    kd = blk.get("target_kd_pct")
    c9_ctrl_raw = blk.get("casp9_stressed_ctrl_raw_by_block")
    c9_tr_raw = blk.get("casp9_treated_raw_by_block")
    c9_vec = blk.get("casp9_reduction_pct_by_block")
    c9_fam = blk.get("family_raw_p_values_casp9")
    c9_p = blk.get("holm_adjusted_casp9_p_value")
    ctrl_p0 = blk.get("stressed_ctrl_beta_plated_t0_by_block")
    ctrl_sv = blk.get("stressed_ctrl_beta_surviving_by_block")
    tr_p0 = blk.get("treated_beta_plated_t0_by_block")
    tr_sv = blk.get("treated_beta_surviving_by_block")
    veh_p0 = blk.get("unstressed_vehicle_beta_plated_t0_by_block")
    veh_sv = blk.get("unstressed_vehicle_beta_surviving_by_block")
    ctrl_vec = blk.get("stressed_ctrl_beta_t0_pct_by_block")
    tr_vec = blk.get("treated_beta_t0_pct_by_block")
    veh_vec = blk.get("unstressed_vehicle_beta_t0_pct_by_block")
    beta_fam = blk.get("family_raw_p_values_beta")
    beta_p = blk.get("holm_adjusted_beta_p_value")
    nonbeta_surv = blk.get("nonbeta_lineage_min_surv_pct_ctrl")
    ctrl_nonbeta_t0 = blk.get("stressed_ctrl_nonbeta_t0_survival_pct")
    five_arms = blk.get("all_five_arms_paired_data")

    if not (
        isinstance(bids, list) and len(bids) == expected_n
        and all(is_nonempty_str(x) for x in bids)
        and len(set(str(x).strip().upper() for x in bids)) == expected_n
    ):
        fails.append(f"FAIL_GATE_C1_{o2_tag}_INVALID_OR_DUPLICATE_BLOCK_IDS"); return None
    if expected_block_ids_norm is not None and [str(x).strip().upper() for x in bids] != expected_block_ids_norm:
        fails.append(f"FAIL_GATE_C1_{o2_tag}_BLOCK_IDS_MISMATCH_PREREGISTERED_ALLOCATION")
    if expected_batch_ids_norm is not None or expected_arm_orders is not None:
        blk_batches = blk.get("differentiation_batch_ids")
        blk_orders = blk.get("randomized_arm_orders_by_block")
        if not (isinstance(blk_batches, list) and len(blk_batches) == expected_n and all(is_nonempty_str(b) for b in blk_batches)):
            fails.append(f"FAIL_GATE_C1_{o2_tag}_BATCH_OR_ARM_ORDER_MISMATCH_PREREG")
        elif expected_batch_ids_norm is not None and [str(b).strip().upper() for b in blk_batches] != expected_batch_ids_norm:
            fails.append(f"FAIL_GATE_C1_{o2_tag}_BATCH_OR_ARM_ORDER_MISMATCH_PREREG")
        if not (isinstance(blk_orders, list) and len(blk_orders) == expected_n and all(isinstance(o, list) and all(is_nonempty_str(x) for x in o) for o in blk_orders)):
            fails.append(f"FAIL_GATE_C1_{o2_tag}_BATCH_OR_ARM_ORDER_MISMATCH_PREREG")
        elif expected_arm_orders is not None and [[str(x) for x in o] for o in blk_orders] != expected_arm_orders:
            fails.append(f"FAIL_GATE_C1_{o2_tag}_BATCH_OR_ARM_ORDER_MISMATCH_PREREG")

    def _is_exact_num_or_str(x: Any) -> bool:
        return _to_exact_decimal(x) is not None

    vecs = (c9_ctrl_raw, c9_tr_raw, c9_vec, ctrl_vec, tr_vec, veh_vec)
    if not all(isinstance(v, list) and len(v) == expected_n and all(_is_exact_num_or_str(x) for x in v) for v in vecs):
        holds.append(f"HOLD_GATE_C1_{o2_tag}_INCOMPLETE_PER_BLOCK_ARRAYS"); return None
    if not all(is_finite_num(x) for x in (kd, c9_p, beta_p, nonbeta_surv, ctrl_nonbeta_t0)):
        holds.append(f"HOLD_GATE_C1_{o2_tag}_MISSING_REQUIRED_SCALARS"); return None

    c9_ctrl_fracs = [_to_exact_fraction(x) for x in c9_ctrl_raw]
    c9_tr_fracs = [_to_exact_fraction(x) for x in c9_tr_raw]
    c9_pct_fracs = [_to_exact_fraction(x) for x in c9_vec]
    tr_pct_fracs = [_to_exact_fraction(x) for x in tr_vec]
    c9_ctrl_f = [float(x) for x in c9_ctrl_fracs]
    c9_tr_f = [float(x) for x in c9_tr_fracs]
    c9_f = [float(x) for x in c9_pct_fracs]
    ctrl_f = [float(_to_exact_decimal(x)) for x in ctrl_vec]
    tr_f = [float(x) for x in tr_pct_fracs]
    veh_f = [float(_to_exact_decimal(x)) for x in veh_vec]
    if any(x <= Fraction(0, 1) for x in c9_ctrl_fracs) or any(x < Fraction(0, 1) for x in c9_tr_fracs):
        fails.append(f"FAIL_GATE_C1_{o2_tag}_INVALID_RAW_CASP9_MEASUREMENTS"); return None
    # Derive exact rational caspase-9 % reductions directly from raw pairs; caller array is <= 0.05% display check!
    raw_c9_fracs: list[Fraction] = []
    for _ci in range(expected_n):
        c_ctrl_fr = c9_ctrl_fracs[_ci]
        c_tr_fr = c9_tr_fracs[_ci]
        recomp_fr = Fraction(100, 1) * (c_ctrl_fr - c_tr_fr) / c_ctrl_fr
        raw_c9_fracs.append(recomp_fr)
        if abs(float(recomp_fr - c9_pct_fracs[_ci])) > 0.05:
            fails.append(f"FAIL_GATE_C1_{o2_tag}_CASP9_REDUCTION_MISMATCH_VS_RAW_PAIRS"); break

    mrna_kd = blk.get("mrna_kd_pct")
    prot_kd = blk.get("protein_kd_pct")
    mrna_aid = blk.get("mrna_assay_record_id")
    prot_aid = blk.get("protein_assay_record_id")
    if (
        not (is_finite_num(mrna_kd) and is_finite_num(prot_kd))
        or not (is_nonempty_str(mrna_aid) and is_nonempty_str(prot_aid))
        or str(mrna_aid).strip().upper() == str(prot_aid).strip().upper()
        or not (0.0 <= float(mrna_kd) <= 100.0 and 0.0 <= float(prot_kd) <= 100.0)
    ):
        fails.append(f"FAIL_GATE_C1_{o2_tag}_MISSING_SEPARATE_MRNA_AND_PROTEIN_KD")
    else:
        if abs(float(kd) - min(float(mrna_kd), float(prot_kd))) > 1e-6:
            fails.append(f"FAIL_GATE_C1_{o2_tag}_TARGET_KD_MISMATCH_VS_MRNA_AND_PROTEIN")
        if target == "JAK2":
            if not (50.0 <= float(mrna_kd) <= 65.0 and 50.0 <= float(prot_kd) <= 65.0):
                fails.append(f"FAIL_GATE_C1_{o2_tag}_JAK2_HYPOMORPH_RANGE_50_65")
        else:
            if float(mrna_kd) < 70.0 or float(prot_kd) < 70.0:
                fails.append(f"FAIL_GATE_C1_{o2_tag}_KD_BELOW_70PCT")
    if not (0.0 <= float(kd) <= 100.0):
        fails.append(f"FAIL_GATE_C1_{o2_tag}_KD_OUT_OF_DOMAIN_0_100")
    elif target == "JAK2":
        if not (50.0 <= float(kd) <= 65.0) and f"FAIL_GATE_C1_{o2_tag}_JAK2_HYPOMORPH_RANGE_50_65" not in fails:
            fails.append(f"FAIL_GATE_C1_{o2_tag}_JAK2_HYPOMORPH_RANGE_50_65")
        j_sh = blk.get("gy001_cxcl10_inducible_shield_pct_ctrl")
        if not (is_finite_num(j_sh) and 85.0 <= float(j_sh) <= 120.0):
            fails.append(f"FAIL_GATE_C1_{o2_tag}_JAK2_GY001_SHIELD_BELOW_85PCT")
    elif float(kd) < 70.0 and f"FAIL_GATE_C1_{o2_tag}_KD_BELOW_70PCT" not in fails:
        fails.append(f"FAIL_GATE_C1_{o2_tag}_KD_BELOW_70PCT")

    # Producer-backed specimen provenance linking C-1 mRNA and protein KD assays to exact product/lot/cohort/candidate
    # AND binding each individual target & analyte observation (2 obs for single-target; 4 obs for dual PMAIP1+BCL2L11)!
    kd_prov = blk.get("molecular_kd_provenance")
    kd_prov_keys = frozenset({
        "product_id", "specimen_id", "specimen_lot_id", "intervention_cohort_id", "candidate_gene",
        "mrna_assay_record_id", "protein_assay_record_id",
        "mrna_kd_pct", "protein_kd_pct", "measured_at_utc",
        "target_observations", "producer_record_sha256",
    })
    kd_obs_keys = frozenset({
        "target_gene", "analyte_type", "assay_record_id", "product_id",
        "specimen_id", "specimen_lot_id", "intervention_cohort_id",
        "kd_pct", "measured_at_utc", "producer_observation_sha256",
    })
    if kd_prov is None:
        holds.append(f"HOLD_GATE_C1_{o2_tag}_MISSING_MOLECULAR_KD_PROVENANCE")
    elif not isinstance(kd_prov, Mapping) or set(kd_prov.keys()) != kd_prov_keys:
        fails.append(f"FAIL_GATE_C1_{o2_tag}_MOLECULAR_KD_PROVENANCE_MISMATCH")
    else:
        kd_psha = kd_prov.get("producer_record_sha256")
        t_kdm = parse_utc_iso_ts(kd_prov.get("measured_at_utc"))
        t_obs = kd_prov.get("target_observations")
        kd_prov_ok = not (
            not is_valid_sha256_hex(kd_psha)
            or sha256_bytes(canonical_json_bytes({k: v for k, v in kd_prov.items() if k != "producer_record_sha256"})) != str(kd_psha)
            or not all(is_nonempty_str(kd_prov.get(k)) for k in ("product_id", "specimen_id", "specimen_lot_id", "intervention_cohort_id", "candidate_gene", "mrna_assay_record_id", "protein_assay_record_id"))
            or t_kdm is None
            or (min_acq_ts is not None and t_kdm < min_acq_ts)
            or (max_acq_ts is not None and t_kdm > max_acq_ts)
            or (is_nonempty_str(expected_prod_id) and str(kd_prov["product_id"]).strip() != str(expected_prod_id).strip())
            or (is_nonempty_str(expected_lot_id) and str(kd_prov["specimen_lot_id"]).strip().upper() != str(expected_lot_id).strip().upper())
            or (is_nonempty_str(expected_cohort_id) and str(kd_prov["intervention_cohort_id"]).strip().upper() != str(expected_cohort_id).strip().upper())
            or str(kd_prov["candidate_gene"]).strip().upper() != target
            or (is_nonempty_str(mrna_aid) and str(kd_prov["mrna_assay_record_id"]).strip().upper() != str(mrna_aid).strip().upper())
            or (is_nonempty_str(prot_aid) and str(kd_prov["protein_assay_record_id"]).strip().upper() != str(prot_aid).strip().upper())
            or not (is_finite_num(kd_prov.get("mrna_kd_pct")) and is_finite_num(kd_prov.get("protein_kd_pct")))
            or (is_finite_num(mrna_kd) and abs(float(kd_prov["mrna_kd_pct"]) - float(mrna_kd)) > 1e-6)
            or (is_finite_num(prot_kd) and abs(float(kd_prov["protein_kd_pct"]) - float(prot_kd)) > 1e-6)
            or not isinstance(t_obs, list)
        )
        if kd_prov_ok:
            req_pairs = (
                {("PMAIP1", "mRNA"), ("PMAIP1", "protein"), ("BCL2L11", "mRNA"), ("BCL2L11", "protein")}
                if target == "PMAIP1+BCL2L11"
                else {(target, "mRNA"), (target, "protein")}
            )
            obs_map: dict[tuple[str, str], tuple[str, float]] = {}
            seen_obs_aids: set[str] = set()
            if len(t_obs) != len(req_pairs):
                kd_prov_ok = False
            else:
                for orow in t_obs:
                    if not isinstance(orow, Mapping) or set(orow.keys()) != kd_obs_keys:
                        kd_prov_ok = False; break
                    osha = orow.get("producer_observation_sha256")
                    t_om = parse_utc_iso_ts(orow.get("measured_at_utc"))
                    if (
                        not is_valid_sha256_hex(osha)
                        or sha256_bytes(canonical_json_bytes({k: v for k, v in orow.items() if k != "producer_observation_sha256"})) != str(osha)
                        or not all(is_nonempty_str(orow.get(k)) for k in ("target_gene", "analyte_type", "assay_record_id", "product_id", "specimen_id", "specimen_lot_id", "intervention_cohort_id"))
                        or t_om is None
                        or (min_acq_ts is not None and t_om < min_acq_ts)
                        or (max_acq_ts is not None and t_om > max_acq_ts)
                        or not (is_finite_num(orow.get("kd_pct")) and 0.0 <= float(orow["kd_pct"]) <= 100.0)
                        or (is_nonempty_str(expected_prod_id) and str(orow["product_id"]).strip() != str(expected_prod_id).strip())
                        or str(orow["specimen_id"]).strip().upper() != str(kd_prov["specimen_id"]).strip().upper()
                        or str(orow["specimen_lot_id"]).strip().upper() != str(kd_prov["specimen_lot_id"]).strip().upper()
                        or str(orow["intervention_cohort_id"]).strip().upper() != str(kd_prov["intervention_cohort_id"]).strip().upper()
                    ):
                        kd_prov_ok = False; break
                    pair_k = (str(orow["target_gene"]).strip().upper(), str(orow["analyte_type"]).strip())
                    o_aid_n = str(orow["assay_record_id"]).strip().upper()
                    if pair_k not in req_pairs or pair_k in obs_map or o_aid_n in seen_obs_aids:
                        kd_prov_ok = False; break
                    seen_obs_aids.add(o_aid_n)
                    obs_map[pair_k] = (o_aid_n, float(orow["kd_pct"]))
            if kd_prov_ok:
                if target == "PMAIP1+BCL2L11":
                    exp_dual_obs = {
                        ("PMAIP1", "mRNA"): blk.get("pmaip1_mrna_kd_pct"),
                        ("PMAIP1", "protein"): blk.get("pmaip1_protein_kd_pct"),
                        ("BCL2L11", "mRNA"): blk.get("bcl2l11_mrna_kd_pct"),
                        ("BCL2L11", "protein"): blk.get("bcl2l11_protein_kd_pct"),
                    }
                    if any(not is_finite_num(ev) or abs(obs_map[pk][1] - float(ev)) > 1e-6 for pk, ev in exp_dual_obs.items()):
                        kd_prov_ok = False
                    elif is_finite_num(mrna_kd) and abs(min(obs_map[("PMAIP1", "mRNA")][1], obs_map[("BCL2L11", "mRNA")][1]) - float(mrna_kd)) > 1e-6:
                        kd_prov_ok = False
                    elif is_finite_num(prot_kd) and abs(min(obs_map[("PMAIP1", "protein")][1], obs_map[("BCL2L11", "protein")][1]) - float(prot_kd)) > 1e-6:
                        kd_prov_ok = False
                else:
                    if (
                        (is_nonempty_str(mrna_aid) and obs_map[(target, "mRNA")][0] != str(mrna_aid).strip().upper())
                        or (is_nonempty_str(prot_aid) and obs_map[(target, "protein")][0] != str(prot_aid).strip().upper())
                        or (is_finite_num(mrna_kd) and abs(obs_map[(target, "mRNA")][1] - float(mrna_kd)) > 1e-6)
                        or (is_finite_num(prot_kd) and abs(obs_map[(target, "protein")][1] - float(prot_kd)) > 1e-6)
                    ):
                        kd_prov_ok = False
        if not kd_prov_ok:
            fails.append(f"FAIL_GATE_C1_{o2_tag}_MOLECULAR_KD_PROVENANCE_MISMATCH")

    if any(not (-100.0 <= x <= 100.0) for x in c9_f):
        fails.append(f"FAIL_GATE_C1_{o2_tag}_CASP9_OUT_OF_DOMAIN_NEG100_100")
    mean_c9_raw_frac = sum(raw_c9_fracs, Fraction(0, 1)) / expected_n
    mean_c9_raw_diff_frac = sum(
        (_to_exact_fraction(c9_ctrl_raw[i]) - _to_exact_fraction(c9_tr_raw[i]) for i in range(expected_n)),
        Fraction(0, 1),
    ) / expected_n
    if mean_c9_raw_diff_frac <= Fraction(0, 1):
        fails.append(f"FAIL_GATE_C1_{o2_tag}_ADVERSE_OR_ZERO_RAW_CASP9_DIRECTION")
    if mean_c9_raw_frac < Fraction(40, 1):
        fails.append(f"FAIL_GATE_C1_{o2_tag}_MEAN_CASP9_REDUCTION_BELOW_40PCT")

    # Derive exact rational Fraction(sv*100, p0) vectors directly from observed integer plated/surviving counts!
    # Caller-submitted percentage arrays are retained strictly as <= 0.05 pp display consistency checks.
    recomp_beta_p: dict[str, float] = {}
    recomp_c9_p: dict[str, float] = {}
    def _derive_exact_beta_fracs(p0_arr: Any, sv_arr: Any, pct_arr: Sequence[float], tag_c: str) -> Optional[list[Fraction]]:
        if not (
            isinstance(p0_arr, list) and isinstance(sv_arr, list)
            and len(p0_arr) == expected_n and len(sv_arr) == expected_n
            and all(is_strict_int(a) and int(a) > 0 and is_strict_int(b) and 0 <= int(b) <= int(a) for a, b in zip(p0_arr, sv_arr))
        ):
            holds.append(f"HOLD_GATE_C1_{o2_tag}_MISSING_RAW_BETA_PLATED_COUNTS:{tag_c}")
            return None
        fracs_out: list[Fraction] = []
        for a, b, pv in zip(p0_arr, sv_arr, pct_arr):
            fr = Fraction(int(b) * 100, int(a))
            if abs(float(fr) - float(pv)) > 0.05:
                fails.append(f"FAIL_GATE_C1_{o2_tag}_BETA_PCT_CONTRADICTS_RAW_PLATED_COUNTS:{tag_c}")
                return None
            fracs_out.append(fr)
        return fracs_out

    ctrl_fracs = _derive_exact_beta_fracs(ctrl_p0, ctrl_sv, ctrl_f, "STRESSED_CTRL")
    tr_fracs = _derive_exact_beta_fracs(tr_p0, tr_sv, tr_f, "ACTIVE_TREATED")
    veh_fracs = _derive_exact_beta_fracs(veh_p0, veh_sv, veh_f, "UNSTRESSED_VEHICLE")
    bcl2l11_comp_fracs: Optional[list[Fraction]] = None

    # Use exact count-derived rational vectors whenever available (display arrays verified above!)
    eff_ctrl_f = [float(x) for x in ctrl_fracs] if ctrl_fracs is not None else ctrl_f
    eff_tr_f = [float(x) for x in tr_fracs] if tr_fracs is not None else tr_f
    eff_veh_f = [float(x) for x in veh_fracs] if veh_fracs is not None else veh_f

    if any(not (0.0 < x <= 100.0) for x in eff_ctrl_f + eff_tr_f + eff_veh_f):
        fails.append(f"FAIL_GATE_C1_{o2_tag}_BETA_SURVIVAL_OUT_OF_DOMAIN")
    else:
        if ctrl_fracs is not None and tr_fracs is not None and veh_fracs is not None:
            diff_fracs = [tr_fracs[i] - ctrl_fracs[i] for i in range(expected_n)]
            mean_lift_frac = sum(diff_fracs, Fraction(0, 1)) / expected_n
            mean_pct_veh_frac = Fraction(100, 1) * sum(tr_fracs, Fraction(0, 1)) / sum(veh_fracs, Fraction(0, 1))
            if mean_lift_frac <= 0:
                fails.append(f"FAIL_GATE_C1_{o2_tag}_NONPOSITIVE_NET_BETA_RESCUE")
            elif not (mean_lift_frac >= Fraction(15, 1) or mean_pct_veh_frac >= Fraction(85, 1)):
                fails.append(f"FAIL_GATE_C1_{o2_tag}_BETA_EFFECT_THRESHOLD_NOT_MET")
            diffs = [float(d) for d in diff_fracs]
        else:
            diffs = [eff_tr_f[i] - eff_ctrl_f[i] for i in range(expected_n)]
            mean_lift = sum(diffs) / expected_n
            mean_pct_veh = 100.0 * (sum(eff_tr_f) / expected_n) / (sum(eff_veh_f) / expected_n)
            if mean_lift <= 0.0:
                fails.append(f"FAIL_GATE_C1_{o2_tag}_NONPOSITIVE_NET_BETA_RESCUE")
            elif not (mean_lift >= 15.0 or mean_pct_veh >= 85.0):
                fails.append(f"FAIL_GATE_C1_{o2_tag}_BETA_EFFECT_THRESHOLD_NOT_MET")

        if stat_method == "PAIRED_T_TEST_NORMALITY_VERIFIED" and expected_n >= 6:
            nd = blk.get("normality_diagnostic_record")
            nd_keys = frozenset({"beta_qq_r", "casp9_qq_r", "beta_shapiro_wilk_p", "casp9_shapiro_wilk_p", "diagnostic_sha256"})
            if nd is None:
                holds.append(f"HOLD_GATE_C1_{o2_tag}_MISSING_PAIRED_T_NORMALITY_DIAGNOSTIC")
            elif not isinstance(nd, Mapping) or set(nd.keys()) != nd_keys:
                fails.append(f"FAIL_GATE_C1_{o2_tag}_MALFORMED_NORMALITY_DIAGNOSTIC")
            else:
                dsha = nd.get("diagnostic_sha256")
                b_qq = paired_diff_normality_qq_r(diffs)
                c9_raw_diffs = [c9_ctrl_f[i] - c9_tr_f[i] for i in range(expected_n)]
                c_qq = paired_diff_normality_qq_r(c9_raw_diffs)
                b_sw = shapiro_wilk_test(diffs)
                c_sw = shapiro_wilk_test(c9_raw_diffs)
                if (
                    not is_valid_sha256_hex(dsha)
                    or sha256_bytes(canonical_json_bytes({k: v for k, v in nd.items() if k != "diagnostic_sha256"})) != dsha
                    or not all(is_finite_num(nd.get(k)) for k in ("beta_qq_r", "casp9_qq_r", "beta_shapiro_wilk_p", "casp9_shapiro_wilk_p"))
                ):
                    fails.append(f"FAIL_GATE_C1_{o2_tag}_INVALID_NORMALITY_DIAGNOSTIC")
                elif b_qq is None or c_qq is None or abs(float(nd["beta_qq_r"]) - b_qq) > 1e-3 or abs(float(nd["casp9_qq_r"]) - c_qq) > 1e-3:
                    fails.append(f"FAIL_GATE_C1_{o2_tag}_NORMALITY_QQ_R_MISMATCH_VS_RAW_DIFFS")
                elif b_sw is None or c_sw is None or abs(float(nd["beta_shapiro_wilk_p"]) - b_sw[1]) > 0.01 or abs(float(nd["casp9_shapiro_wilk_p"]) - c_sw[1]) > 0.01:
                    fails.append(f"FAIL_GATE_C1_{o2_tag}_SHAPIRO_WILK_P_MISMATCH_VS_RAW_DIFFS")
                elif b_qq < 0.88 or c_qq < 0.88 or b_sw[1] < 0.05 or c_sw[1] < 0.05:
                    holds.append(f"HOLD_GATE_C1_{o2_tag}_PAIRED_T_NORMALITY_NOT_MET_USE_EXACT_SIGN_FLIP")

        if stat_method == "EXACT_TWO_SIDED_SIGN_FLIP" and expected_n > EXACT_SIGN_FLIP_MAX_N:
            holds.append(f"HOLD_GATE_C1_{o2_tag}_EXACT_SIGN_FLIP_N_GT_20_REQUIRES_PAIRED_T")
        elif expected_n >= 6:
            if not isinstance(five_arms, Mapping) or set(five_arms.keys()) != C1_FAMILY_GENES:
                fails.append(f"FAIL_GATE_C1_{o2_tag}_MISSING_ALL_5_SIBLING_ARM_RAW_VECTORS")
            else:
                arms_ok = True
                for gname in sorted(C1_FAMILY_GENES):
                    adata = five_arms.get(gname)
                    if not isinstance(adata, Mapping) or set(adata.keys()) != {
                        "treated_beta_plated_t0_by_block", "treated_beta_surviving_by_block",
                        "treated_beta_t0_pct_by_block", "casp9_treated_raw_by_block", "casp9_reduction_pct_by_block",
                    }:
                        fails.append(f"FAIL_GATE_C1_{o2_tag}_MALFORMED_SIBLING_ARM_DATA:{gname}"); arms_ok = False; continue
                    ab_p0 = adata.get("treated_beta_plated_t0_by_block")
                    ab_sv = adata.get("treated_beta_surviving_by_block")
                    ab = adata.get("treated_beta_t0_pct_by_block")
                    ac_raw = adata.get("casp9_treated_raw_by_block")
                    ac = adata.get("casp9_reduction_pct_by_block")
                    if not (
                        isinstance(ab, list) and len(ab) == expected_n and all(_is_exact_num_or_str(x) and Fraction(0, 1) < _to_exact_fraction(x) <= Fraction(100, 1) for x in ab)
                        and isinstance(ac_raw, list) and len(ac_raw) == expected_n and all(_is_exact_num_or_str(x) and _to_exact_fraction(x) >= Fraction(0, 1) for x in ac_raw)
                        and isinstance(ac, list) and len(ac) == expected_n and all(_is_exact_num_or_str(x) and Fraction(-100, 1) <= _to_exact_fraction(x) <= Fraction(100, 1) for x in ac)
                    ):
                        fails.append(f"FAIL_GATE_C1_{o2_tag}_INVALID_SIBLING_ARM_VECTORS:{gname}"); arms_ok = False; continue
                    ab_pct_fracs = [_to_exact_fraction(x) for x in ab]
                    ac_raw_fracs = [_to_exact_fraction(x) for x in ac_raw]
                    ac_pct_fracs = [_to_exact_fraction(x) for x in ac]
                    ab_f = [float(x) for x in ab_pct_fracs]
                    ab_fracs = _derive_exact_beta_fracs(ab_p0, ab_sv, ab_f, f"ARM_{gname}")
                    if ab_fracs is None:
                        arms_ok = False
                    elif gname == "BCL2L11":
                        bcl2l11_comp_fracs = ab_fracs
                    for _ci2 in range(expected_n):
                        recomp_g_c9_fr = Fraction(100, 1) * (c9_ctrl_fracs[_ci2] - ac_raw_fracs[_ci2]) / c9_ctrl_fracs[_ci2]
                        if abs(float(recomp_g_c9_fr - ac_pct_fracs[_ci2])) > 0.05:
                            fails.append(f"FAIL_GATE_C1_{o2_tag}_SIBLING_CASP9_RAW_MISMATCH:{gname}"); arms_ok = False; break
                    if gname == target and (ab_pct_fracs != tr_pct_fracs or ac_raw_fracs != c9_tr_fracs or ac_pct_fracs != c9_pct_fracs or ab_p0 != tr_p0 or ab_sv != tr_sv):
                        fails.append(f"FAIL_GATE_C1_{o2_tag}_ACTIVE_ARM_MISMATCH_WITH_5ARM_TABLE"); arms_ok = False
                    if target == "PMAIP1+BCL2L11" and gname == "BCL2L11":
                        comp_v = blk.get("bcl2l11_comparator_beta_t0_pct_by_block")
                        if isinstance(comp_v, list) and [_to_exact_fraction(x) for x in comp_v] != ab_pct_fracs:
                            fails.append(f"FAIL_GATE_C1_{o2_tag}_BCL2L11_COMPARATOR_MISMATCH_WITH_5ARM_TABLE"); arms_ok = False
                    if ab_fracs is None or ctrl_fracs is None:
                        arms_ok = False
                        continue
                    # Family-wide paired-t normality & exact count-derived rational sign-flip across ALL 5 sibling arms!
                    ab_diff_fracs = [ab_fracs[i] - ctrl_fracs[i] for i in range(expected_n)]
                    ac_diff_fracs = [c9_ctrl_fracs[i] - ac_raw_fracs[i] for i in range(expected_n)]
                    ab_diffs = [float(d) for d in ab_diff_fracs]
                    ac_diffs = [float(d) for d in ac_diff_fracs]
                    if stat_method == "PAIRED_T_TEST_NORMALITY_VERIFIED" and expected_n >= 6:
                        sb_qq = paired_diff_normality_qq_r(ab_diffs)
                        sc_qq = paired_diff_normality_qq_r(ac_diffs)
                        sb_sw = shapiro_wilk_test(ab_diffs)
                        sc_sw = shapiro_wilk_test(ac_diffs)
                        if (
                            sb_qq is None or sc_qq is None or sb_sw is None or sc_sw is None
                            or sb_qq < 0.88 or sc_qq < 0.88 or sb_sw[1] < 0.05 or sc_sw[1] < 0.05
                        ):
                            holds.append(f"HOLD_GATE_C1_{o2_tag}_PAIRED_T_FAMILY_NORMALITY_NOT_MET_USE_EXACT_SIGN_FLIP:{gname}")
                    # Directional assignment-symmetric paired contrasts from EXACT rational Fractions!
                    if sum(ab_diff_fracs, Fraction(0, 1)) <= Fraction(0, 1):
                        recomp_beta_p[gname] = 1.0
                    else:
                        pb_val, pb_err = _compute_c1_arm_raw_p(ab_fracs, stat_method, paired_control=ctrl_fracs)
                        if pb_err is not None or pb_val is None:
                            fails.append(f"FAIL_GATE_C1_{o2_tag}_ARM_BETA_STAT_ERROR:{gname}:{pb_err}"); arms_ok = False
                        else:
                            recomp_beta_p[gname] = pb_val
                    if sum(ac_diff_fracs, Fraction(0, 1)) <= Fraction(0, 1):
                        recomp_c9_p[gname] = 1.0
                    else:
                        pc_val, pc_err = _compute_c1_arm_raw_p(c9_ctrl_fracs, stat_method, paired_control=ac_raw_fracs)
                        if pc_err is not None or pc_val is None:
                            fails.append(f"FAIL_GATE_C1_{o2_tag}_ARM_CASP9_STAT_ERROR:{gname}:{pc_err}"); arms_ok = False
                        else:
                            recomp_c9_p[gname] = pc_val

                if arms_ok:
                    for ep_name, fam_map, recomp_map, sub_holm in (
                        ("BETA", beta_fam, recomp_beta_p, beta_p),
                        ("CASP9", c9_fam, recomp_c9_p, c9_p),
                    ):
                        if not (
                            isinstance(fam_map, Mapping)
                            and set(fam_map.keys()) == C1_FAMILY_GENES
                            and all(is_finite_num(v) and 0.0 < float(v) <= 1.0 for v in fam_map.values())
                        ):
                            fails.append(f"FAIL_GATE_C1_{o2_tag}_MISSING_5ARM_FAMILY_RAW_PVALUES_{ep_name}")
                        elif target in C1_FAMILY_GENES:
                            for gname in sorted(C1_FAMILY_GENES):
                                if abs(float(fam_map[gname]) - recomp_map[gname]) > max(1e-9, 1e-4 * abs(recomp_map[gname])):
                                    fails.append(f"FAIL_GATE_C1_{o2_tag}_SIBLING_RAW_PVALUE_MISMATCH_{ep_name}:{gname}")
                            holm_map = holm_bonferroni_adjust(recomp_map)
                            holm_calc = holm_map[target]
                            if abs(float(sub_holm) - holm_calc) > max(1e-9, 1e-4 * abs(holm_calc)):
                                fails.append(f"FAIL_GATE_C1_{o2_tag}_HOLM5_ADJUSTED_PVALUE_MISMATCH_{ep_name}")
                            if holm_calc >= 0.01:
                                fails.append(f"FAIL_GATE_C1_{o2_tag}_HOLM_{ep_name}_PVALUE_GE_0P01")

    if target == "PMAIP1+BCL2L11":
        kd_p = blk.get("pmaip1_kd_pct")
        kd_b = blk.get("bcl2l11_kd_pct")
        kd_pm = blk.get("pmaip1_mrna_kd_pct")
        kd_pp = blk.get("pmaip1_protein_kd_pct")
        kd_bm = blk.get("bcl2l11_mrna_kd_pct")
        kd_bp = blk.get("bcl2l11_protein_kd_pct")
        comp_vec = blk.get("bcl2l11_comparator_beta_t0_pct_by_block")
        h2h_l95 = blk.get("head_to_head_vs_bcl2l11_l95_delta_pp")
        if (
            not all(is_finite_num(x) and 70.0 <= float(x) <= 100.0 for x in (kd_p, kd_b, kd_pm, kd_pp, kd_bm, kd_bp))
            or abs(float(kd_p) - min(float(kd_pm), float(kd_pp))) > 1e-6
            or abs(float(kd_b) - min(float(kd_bm), float(kd_bp))) > 1e-6
        ):
            fails.append(f"FAIL_GATE_C1_{o2_tag}_DUAL_TARGET_COMPONENT_KD_FAILED")
        if not (isinstance(comp_vec, list) and len(comp_vec) == expected_n and all(is_finite_num(x) and 0.0 < float(x) <= 100.0 for x in comp_vec)):
            fails.append(f"FAIL_GATE_C1_{o2_tag}_DUAL_MISSING_PAIRED_BCL2L11_COMPARATOR")
        else:
            comp_fracs_eff = bcl2l11_comp_fracs if bcl2l11_comp_fracs is not None else [_to_exact_fraction(x) for x in comp_vec]
            tr_fracs_eff = tr_fracs if tr_fracs is not None else [_to_exact_fraction(x) for x in tr_f]
            if all(x is not None for x in comp_fracs_eff) and all(x is not None for x in tr_fracs_eff):
                h2h_diff_fracs = [tr_fracs_eff[i] - comp_fracs_eff[i] for i in range(expected_n)]
                h2h_diffs = [float(d) for d in h2h_diff_fracs]
                if stat_method == "EXACT_TWO_SIDED_SIGN_FLIP" and expected_n >= 6:
                    if expected_n <= EXACT_SIGN_FLIP_MAX_N:
                        # Distribution-free exact rational Fisher sign-flip superiority for dual vs BCL2L11!
                        p_h2h_sf = exact_two_sided_sign_flip_paired_p(tr_fracs_eff, comp_fracs_eff)
                        hl_med = exact_hodges_lehmann_median(h2h_diff_fracs)
                        if sum(h2h_diff_fracs, Fraction(0, 1)) <= 0 or hl_med <= 0 or p_h2h_sf is None or p_h2h_sf >= 0.05:
                            fails.append(f"FAIL_GATE_C1_{o2_tag}_DUAL_SIGN_FLIP_SUPERIORITY_VS_BCL2L11_FAILED")
                else:
                    if stat_method == "PAIRED_T_TEST_NORMALITY_VERIFIED" and expected_n >= 6:
                        h2h_qq = paired_diff_normality_qq_r(h2h_diffs)
                        h2h_sw = shapiro_wilk_test(h2h_diffs)
                        if h2h_qq is None or h2h_sw is None or h2h_qq < 0.88 or h2h_sw[1] < 0.05:
                            holds.append(f"HOLD_GATE_C1_{o2_tag}_DUAL_H2H_NORMALITY_NOT_MET_USE_EXACT_SIGN_FLIP")
                    h2h_stat = paired_t_summary(h2h_diffs)
                    if h2h_stat is None:
                        fails.append(f"FAIL_GATE_C1_{o2_tag}_DUAL_H2H_DEGENERATE_VARIANCE")
                    else:
                        _, _, _, l95_calc = h2h_stat
                        if l95_calc <= 0.0 or not is_finite_num(h2h_l95) or float(h2h_l95) <= 0.0 or abs(float(h2h_l95) - l95_calc) > 1e-4:
                            fails.append(f"FAIL_GATE_C1_{o2_tag}_DUAL_L95_SUPERIORITY_VS_BCL2L11_FAILED")

    if not (0.0 <= float(ctrl_nonbeta_t0) <= 100.0) or float(ctrl_nonbeta_t0) < 50.0:
        fails.append(f"FAIL_GATE_C1_{o2_tag}_STRESSED_CONTROL_ASSAY_VALIDITY_FLOOR")
    if float(nonbeta_surv) < 90.0:
        fails.append(f"FAIL_GATE_C1_{o2_tag}_NONBETA_LINEAGE_DAMAGE")
    if not (is_strict_bool(blk.get("t0_original_plated_denominators_used")) and blk["t0_original_plated_denominators_used"]):
        fails.append(f"FAIL_GATE_C1_{o2_tag}_MISSING_T0_DENOMINATOR_RULE")

    # Block-resolved 5-lineage timecourse plated-t0 & surviving counts (reconciling EVERY individual
    # block for INS_beta AND evaluating EVERY post-0h timepoint & per-block floor for all 4 non-beta lineages)!
    ltc = blk.get("lineage_timecourse_counts")
    if ltc is None:
        holds.append(f"HOLD_GATE_C1_{o2_tag}_MISSING_LINEAGE_TIMECOURSE_COUNTS")
    elif not isinstance(ltc, Mapping) or set(ltc.keys()) != C1_REQUIRED_5_LINEAGES:
        fails.append(f"FAIL_GATE_C1_{o2_tag}_INCOMPLETE_5_LINEAGE_TIMECOURSE_COUNTS")
    else:
        ltc_ok = True
        recomp_nonbeta_min_mean = 100.0
        recomp_nonbeta_min_blk = 100.0
        bids_norm_ltc = [str(x).strip().upper() for x in bids]
        ins_beta_blk_mismatch = False
        for lin_nm in sorted(C1_REQUIRED_5_LINEAGES):
            b_entries = ltc.get(lin_nm)
            if not isinstance(b_entries, list) or len(b_entries) != expected_n:
                ltc_ok = False; break
            ref_hrs_lin: Optional[list[float]] = None
            nonbeta_rels_by_tp: list[list[float]] = []
            for b_i, b_obj in enumerate(b_entries):
                if (
                    not isinstance(b_obj, Mapping) or set(b_obj.keys()) != {"block_id", "timepoints"}
                    or not is_nonempty_str(b_obj.get("block_id"))
                    or str(b_obj["block_id"]).strip().upper() != bids_norm_ltc[b_i]
                    or not isinstance(b_obj.get("timepoints"), list) or len(b_obj["timepoints"]) < 2
                ):
                    ltc_ok = False; break
                l_rows = b_obj["timepoints"]
                prev_h_l = -1.0
                t0_tr = t0_ct = None
                hrs_b: list[float] = []
                term_tr_pct = term_ct_pct = None
                for r_i, lr in enumerate(l_rows):
                    if not isinstance(lr, Mapping) or set(lr.keys()) != {
                        "hour_h", "treated_plated_t0_n", "treated_surviving_n", "ctrl_plated_t0_n", "ctrl_surviving_n",
                    }:
                        ltc_ok = False; break
                    hh_l = lr.get("hour_h")
                    tp0, ts, cp0, cs = lr.get("treated_plated_t0_n"), lr.get("treated_surviving_n"), lr.get("ctrl_plated_t0_n"), lr.get("ctrl_surviving_n")
                    if not (
                        is_finite_num(hh_l) and float(hh_l) > prev_h_l and (r_i > 0 or abs(float(hh_l)) <= 1e-12)
                        and all(is_strict_int(x) for x in (tp0, ts, cp0, cs))
                        and int(tp0) > 0 and int(cp0) > 0 and 0 <= int(ts) <= int(tp0) and 0 <= int(cs) <= int(cp0)
                    ):
                        ltc_ok = False; break
                    prev_h_l = float(hh_l)
                    hrs_b.append(prev_h_l)
                    if r_i == 0:
                        t0_tr, t0_ct = int(tp0), int(cp0)
                        if int(ts) != int(tp0) or int(cs) != int(cp0):
                            ltc_ok = False; break
                    else:
                        if int(tp0) != t0_tr or int(cp0) != t0_ct:
                            ltc_ok = False; break
                    tr_p = 100.0 * float(int(ts)) / float(int(tp0))
                    ct_p = 100.0 * float(int(cs)) / float(int(cp0))
                    term_tr_pct, term_ct_pct = tr_p, ct_p
                    if lin_nm != "INS_beta" and r_i > 0:
                        if ct_p <= 0.0:
                            ltc_ok = False; break
                        rel_p = 100.0 * tr_p / ct_p
                        while len(nonbeta_rels_by_tp) < r_i:
                            nonbeta_rels_by_tp.append([])
                        nonbeta_rels_by_tp[r_i - 1].append(rel_p)
                        recomp_nonbeta_min_blk = min(recomp_nonbeta_min_blk, rel_p)
                if not ltc_ok or prev_h_l < 24.0 - 1e-9 or term_tr_pct is None or term_ct_pct is None:
                    ltc_ok = False; break
                if ref_hrs_lin is None:
                    ref_hrs_lin = hrs_b
                elif len(hrs_b) != len(ref_hrs_lin) or any(abs(a - b) > 1e-9 for a, b in zip(hrs_b, ref_hrs_lin)):
                    ltc_ok = False; break
                if lin_nm == "INS_beta":
                    if abs(term_tr_pct - eff_tr_f[b_i]) > 0.5 or abs(term_ct_pct - eff_ctrl_f[b_i]) > 0.5:
                        ins_beta_blk_mismatch = True
            if not ltc_ok:
                break
            if lin_nm != "INS_beta":
                for tp_rels in nonbeta_rels_by_tp:
                    if len(tp_rels) != expected_n:
                        ltc_ok = False; break
                    recomp_nonbeta_min_mean = min(recomp_nonbeta_min_mean, sum(tp_rels) / expected_n)
                if not ltc_ok:
                    break
        if ins_beta_blk_mismatch:
            fails.append(f"FAIL_GATE_C1_{o2_tag}_INS_BETA_TIMECOURSE_MISMATCH_VS_PRIMARY")
        if not ltc_ok:
            fails.append(f"FAIL_GATE_C1_{o2_tag}_INVALID_5_LINEAGE_TIMECOURSE_COUNTS")
        elif recomp_nonbeta_min_mean < 90.0 or recomp_nonbeta_min_blk < 80.0 or float(nonbeta_surv) > recomp_nonbeta_min_mean + 0.5:
            fails.append(f"FAIL_GATE_C1_{o2_tag}_NONBETA_TIMECOURSE_COUNTS_BELOW_FLOOR_OR_MISMATCH")

    div = blk.get("death_pathway_diversion_assay")
    pmlkl = blk.get("pmlkl_flag_triggered")
    if not is_strict_bool(pmlkl):
        fails.append(f"FAIL_GATE_C1_{o2_tag}_MISSING_PMLKL_BOOL")
    div_req_scalars = (
        "pmlkl_fold_vs_ctrl", "ripk3_fold_vs_ctrl", "cleaved_casp3_fold_vs_ctrl",
        "zvad_rescue_delta_pp", "necrostatin1s_rescue_delta_pp", "gsk872_rescue_delta_pp",
    )
    div_req_keys = set(div_req_scalars) | {
        "diversion_assay_record_id", "locked_timecourse_schedule_h",
        "lytic_ldh_or_sytox_timecourse_pct", "lineage_block_diversion_records",
    }
    if div is None:
        holds.append(f"HOLD_GATE_C1_{o2_tag}_MISSING_UNCONDITIONAL_DIVERSION_ASSAY")
    elif (
        not isinstance(div, Mapping) or set(div.keys()) != div_req_keys
        or not is_nonempty_str(div.get("diversion_assay_record_id"))
        or not all(is_finite_num(div.get(k)) for k in div_req_scalars)
        or not isinstance(div.get("lytic_ldh_or_sytox_timecourse_pct"), list)
        or not isinstance(div.get("locked_timecourse_schedule_h"), list)
    ):
        fails.append(f"FAIL_GATE_C1_{o2_tag}_MALFORMED_DIVERSION_ASSAY")
    else:
        pm_f, r3_f = float(div["pmlkl_fold_vs_ctrl"]), float(div["ripk3_fold_vs_ctrl"])
        c3_f = float(div["cleaved_casp3_fold_vs_ctrl"])
        n1_d, g8_d = float(div["necrostatin1s_rescue_delta_pp"]), float(div["gsk872_rescue_delta_pp"])
        sched_raw = div["locked_timecourse_schedule_h"]
        lytic_tc = div["lytic_ldh_or_sytox_timecourse_pct"]
        lb_div = div["lineage_block_diversion_records"]

        # Locked GY-016 timecourse coverage: >= 4 points (0 h, intermediate <= 12 h, 24 h, terminal >= 48 h, max gap <= 24 h)!
        sched_valid_nums = isinstance(sched_raw, list) and len(sched_raw) >= 2 and all(is_finite_num(x) for x in sched_raw)
        sched_f = [float(x) for x in sched_raw] if sched_valid_nums else []
        sched_covered = (
            sched_valid_nums
            and len(sched_f) >= 4
            and abs(sched_f[0]) <= 1e-9
            and any(0.0 < h <= 12.0 + 1e-9 for h in sched_f)
            and any(abs(h - 24.0) <= 1e-6 for h in sched_f)
            and sched_f[-1] >= 48.0 - 1e-9
            and all(sched_f[k] < sched_f[k + 1] and (sched_f[k + 1] - sched_f[k]) <= 24.0 + 1e-9 for k in range(len(sched_f) - 1))
        )
        if not sched_covered:
            holds.append(f"HOLD_GATE_C1_{o2_tag}_DIVERSION_TIMECOURSE_COVERAGE_INCOMPLETE")

        lytic_valid = True
        lytic_elevated = False
        prev_lh = -1.0
        for lrow in lytic_tc:
            if (
                not isinstance(lrow, Mapping)
                or set(lrow.keys()) != {"hour_h", "treated_lytic_pct", "ctrl_lytic_pct"}
                or not all(is_finite_num(lrow.get(k)) for k in ("hour_h", "treated_lytic_pct", "ctrl_lytic_pct"))
            ):
                lytic_valid = False; break
            lh, lt, lc = float(lrow["hour_h"]), float(lrow["treated_lytic_pct"]), float(lrow["ctrl_lytic_pct"])
            if lh <= prev_lh or not (0.0 <= lt <= 100.0 and 0.0 <= lc <= 100.0):
                lytic_valid = False; break
            prev_lh = lh
            if lh > 0.0 and (lt > 20.0 or lt > lc + 5.0):
                lytic_elevated = True
        if lytic_valid and (not lytic_tc or float(lytic_tc[0]["hour_h"]) != 0.0 or prev_lh < 24.0):
            lytic_valid = False
        if sched_covered and lytic_valid and [float(r["hour_h"]) for r in lytic_tc] != sched_f:
            holds.append(f"HOLD_GATE_C1_{o2_tag}_DIVERSION_TIMECOURSE_COVERAGE_INCOMPLETE")

        # Live GY-016 mandatory lineage-gated (INS_beta & PLVAP_iEC), block- & specimen-linked diversion + rescue!
        gy016_req_lineages = ("INS_beta", "PLVAP_iEC")
        lb_row_keys = frozenset({
            "block_id", "specimen_id", "rescue_assay_record_id",
            "pmlkl_fold_vs_ctrl", "ripk3_fold_vs_ctrl", "cleaved_casp3_fold_vs_ctrl",
            "zvad_rescue_delta_pp", "necrostatin1s_rescue_delta_pp", "gsk872_rescue_delta_pp",
            "paired_viability_timecourse_pct", "lytic_ldh_or_sytox_timecourse_pct",
        })
        worst_pm, worst_r3, worst_n1, worst_g8 = pm_f, r3_f, n1_d, g8_d
        worst_beta_c3 = c3_f
        lb_schema_ok = True
        if not isinstance(lb_div, Mapping) or not all(lin in lb_div for lin in gy016_req_lineages):
            holds.append(f"HOLD_GATE_C1_{o2_tag}_DIVERSION_MISSING_REQUIRED_LINEAGE")
        else:
            bids_norm_d = [str(x).strip().upper() for x in bids]
            seen_d_sp: set[str] = set()
            seen_d_aid: set[str] = set()
            for lin_nm in gy016_req_lineages:
                rows_l = lb_div.get(lin_nm)
                if not isinstance(rows_l, list) or len(rows_l) != expected_n:
                    lb_schema_ok = False; break
                for bi_d, brow in enumerate(rows_l):
                    if (
                        not isinstance(brow, Mapping) or set(brow.keys()) != lb_row_keys
                        or not is_nonempty_str(brow.get("block_id"))
                        or str(brow["block_id"]).strip().upper() != bids_norm_d[bi_d]
                        or not is_nonempty_str(brow.get("specimen_id"))
                        or not is_nonempty_str(brow.get("rescue_assay_record_id"))
                        or not all(is_finite_num(brow.get(k)) for k in div_req_scalars)
                        or not isinstance(brow.get("paired_viability_timecourse_pct"), list)
                        or not isinstance(brow.get("lytic_ldh_or_sytox_timecourse_pct"), list)
                    ):
                        lb_schema_ok = False; break
                    sp_d = str(brow["specimen_id"]).strip().upper()
                    aid_d = str(brow["rescue_assay_record_id"]).strip().upper()
                    if sp_d in seen_d_sp or aid_d in seen_d_aid:
                        lb_schema_ok = False; break
                    seen_d_sp.add(sp_d); seen_d_aid.add(aid_d)
                    bpm, br3, bc3 = float(brow["pmlkl_fold_vs_ctrl"]), float(brow["ripk3_fold_vs_ctrl"]), float(brow["cleaved_casp3_fold_vs_ctrl"])
                    bn1, bg8 = float(brow["necrostatin1s_rescue_delta_pp"]), float(brow["gsk872_rescue_delta_pp"])
                    if bpm <= 0.0 or br3 <= 0.0 or bc3 <= 0.0:
                        lb_schema_ok = False; break
                    worst_pm = max(worst_pm, bpm)
                    worst_r3 = max(worst_r3, br3)
                    worst_n1 = max(worst_n1, bn1)
                    worst_g8 = max(worst_g8, bg8)
                    if lin_nm == "INS_beta":
                        worst_beta_c3 = max(worst_beta_c3, bc3)
                    # Check per-lineage paired viability timecourse reconciled to lineage_timecourse_counts!
                    pv_tc = brow["paired_viability_timecourse_pct"]
                    bl_tc = brow["lytic_ldh_or_sytox_timecourse_pct"]
                    if not (
                        len(pv_tc) == len(sched_f) and len(bl_tc) == len(sched_f)
                        and all(isinstance(pvr, Mapping) and set(pvr.keys()) == {"hour_h", "treated_viab_pct", "ctrl_viab_pct"} and all(is_finite_num(pvr[k]) for k in pvr) for pvr in pv_tc)
                        and all(isinstance(blr, Mapping) and set(blr.keys()) == {"hour_h", "treated_lytic_pct", "ctrl_lytic_pct"} and all(is_finite_num(blr[k]) for k in blr) for blr in bl_tc)
                    ):
                        lb_schema_ok = False; break
                    if [float(r["hour_h"]) for r in pv_tc] != sched_f or [float(r["hour_h"]) for r in bl_tc] != sched_f:
                        lb_schema_ok = False; break
                    for blr in bl_tc:
                        bh_l, bl_t, bl_c = float(blr["hour_h"]), float(blr["treated_lytic_pct"]), float(blr["ctrl_lytic_pct"])
                        if not (0.0 <= bl_t <= 100.0 and 0.0 <= bl_c <= 100.0):
                            lb_schema_ok = False; break
                        if bh_l > 0.0 and (bl_t > 20.0 or bl_t > bl_c + 5.0):
                            lytic_elevated = True
                    if not lb_schema_ok:
                        break
                    # Link directly against lineage_timecourse_counts[lin_nm][bi_d] at every shared timepoint!
                    if isinstance(ltc, Mapping) and isinstance(ltc.get(lin_nm), list) and len(ltc[lin_nm]) == expected_n:
                        ltc_tp_map = {
                            float(tp["hour_h"]): (
                                100.0 * float(int(tp["treated_surviving_n"])) / float(int(tp["treated_plated_t0_n"])),
                                100.0 * float(int(tp["ctrl_surviving_n"])) / float(int(tp["ctrl_plated_t0_n"])),
                            )
                            for tp in ltc[lin_nm][bi_d].get("timepoints", [])
                            if isinstance(tp, Mapping) and is_finite_num(tp.get("hour_h")) and is_strict_int(tp.get("treated_plated_t0_n")) and int(tp["treated_plated_t0_n"]) > 0
                        }
                        for pvr in pv_tc:
                            ph_v = float(pvr["hour_h"])
                            if ph_v in ltc_tp_map:
                                exp_tr_v, exp_ct_v = ltc_tp_map[ph_v]
                                if abs(float(pvr["treated_viab_pct"]) - exp_tr_v) > 0.5 or abs(float(pvr["ctrl_viab_pct"]) - exp_ct_v) > 0.5:
                                    lb_schema_ok = False; break
                    if not lb_schema_ok:
                        break
                if not lb_schema_ok:
                    break

        if pm_f <= 0.0 or r3_f <= 0.0 or c3_f <= 0.0 or not lytic_valid or not lb_schema_ok:
            fails.append(f"FAIL_GATE_C1_{o2_tag}_INVALID_DIVERSION_ASSAY_VALUES")
        elif worst_beta_c3 > 0.85:
            fails.append(f"FAIL_GATE_C1_{o2_tag}_CLEAVED_CASP3_NOT_REDUCED_VS_CTRL")
        elif pmlkl is False and (worst_pm > 1.25 or worst_r3 > 1.25 or worst_n1 >= 5.0 or worst_g8 >= 5.0 or lytic_elevated):
            fails.append(f"FAIL_GATE_C1_{o2_tag}_UNDECLARED_NECROPTOSIS_DIVERSION")
        elif pmlkl is True:
            if not (is_strict_bool(blk.get("gy016_nec1s_gsk872_orthogonal_rescue_cleared")) and blk["gy016_nec1s_gsk872_orthogonal_rescue_cleared"]):
                fails.append(f"FAIL_GATE_C1_{o2_tag}_PMLKL_GY016_ORTHOGONAL_DIVERSION_REQUIRED")
            elif worst_n1 >= 5.0 or worst_g8 >= 5.0 or lytic_elevated:
                fails.append(f"FAIL_GATE_C1_{o2_tag}_UNRESOLVED_NECROPTOSIS_RESCUE_SIGNAL")

    # Mandatory specimen-linked delivery-only mock-transfection control per block (Dossier C §5 C-1)!
    mock_blks = blk.get("mock_transfection_control_by_block")
    mock_req_keys = frozenset({
        "block_id", "specimen_id", "delivery_reagent_lot_id",
        "unstressed_mock_plated_t0", "unstressed_mock_surviving",
        "stressed_mock_plated_t0", "stressed_mock_surviving",
        "stressed_mock_casp9_raw",
    })
    if mock_blks is None or (isinstance(mock_blks, list) and len(mock_blks) == 0):
        holds.append(f"HOLD_GATE_C1_{o2_tag}_MISSING_MOCK_TRANSFECTION_CONTROL")
    elif not isinstance(mock_blks, list) or len(mock_blks) != expected_n:
        fails.append(f"FAIL_GATE_C1_{o2_tag}_INVALID_MOCK_TRANSFECTION_CONTROL")
    else:
        bids_norm_m = [str(x).strip().upper() for x in bids]
        seen_msp: set[str] = set()
        um_pcts: list[float] = []
        sm_pcts: list[float] = []
        sm_c9: list[float] = []
        mock_ok = True
        for mi, mrow in enumerate(mock_blks):
            if (
                not isinstance(mrow, Mapping) or set(mrow.keys()) != mock_req_keys
                or not is_nonempty_str(mrow.get("block_id"))
                or str(mrow["block_id"]).strip().upper() != bids_norm_m[mi]
                or not is_nonempty_str(mrow.get("specimen_id"))
                or not is_nonempty_str(mrow.get("delivery_reagent_lot_id"))
            ):
                mock_ok = False; break
            msp = str(mrow["specimen_id"]).strip().upper()
            if msp in seen_msp:
                mock_ok = False; break
            seen_msp.add(msp)
            up0, usv = mrow.get("unstressed_mock_plated_t0"), mrow.get("unstressed_mock_surviving")
            sp0, ssv = mrow.get("stressed_mock_plated_t0"), mrow.get("stressed_mock_surviving")
            mc9 = mrow.get("stressed_mock_casp9_raw")
            if not (
                all(is_strict_int(x) for x in (up0, usv, sp0, ssv))
                and int(up0) > 0 and 0 <= int(usv) <= int(up0)
                and int(sp0) > 0 and 0 <= int(ssv) <= int(sp0)
                and is_finite_num(mc9) and float(mc9) > 0.0
            ):
                mock_ok = False; break
            um_pcts.append(100.0 * float(int(usv)) / float(int(up0)))
            sm_pcts.append(100.0 * float(int(ssv)) / float(int(sp0)))
            sm_c9.append(float(mc9))
        if not mock_ok:
            fails.append(f"FAIL_GATE_C1_{o2_tag}_INVALID_MOCK_TRANSFECTION_CONTROL")
        else:
            mean_veh = sum(eff_veh_f) / expected_n
            mean_um = sum(um_pcts) / expected_n
            if mean_um < 0.85 * mean_veh or any(um_pcts[i] < 0.75 * eff_veh_f[i] for i in range(expected_n)):
                fails.append(f"FAIL_GATE_C1_{o2_tag}_MOCK_DELIVERY_TOXICITY_EXCESSIVE")
            mean_ctrl = sum(eff_ctrl_f) / expected_n
            mean_tr = sum(eff_tr_f) / expected_n
            mean_sm = sum(sm_pcts) / expected_n
            mean_sm_c9 = sum(sm_c9) / expected_n
            mean_tr_c9 = sum(c9_tr_f) / expected_n
            if (
                abs(mean_sm - mean_ctrl) > 10.0
                or mean_tr <= mean_sm
                or not ((mean_tr - mean_sm) >= 15.0 or (100.0 * mean_tr / mean_veh) >= 85.0)
                or mean_tr_c9 >= mean_sm_c9
            ):
                fails.append(f"FAIL_GATE_C1_{o2_tag}_MOCK_CONTROL_CONCORDANCE_OR_SPECIFICITY_FAILED")

    return (str(aid).strip(), c9_f, ctrl_f, tr_f, veh_f, recomp_beta_p, recomp_c9_p)


def evaluate_gate42_gy032_channel_c_screen(rec: Mapping[str, Any]) -> dict[str, Any]:
    """GATE-42 (IIP-0064): Full 5x2 IIP-0049 causal attribution, exact Holm-5 + composite IUT, cross-lot unique C-2, & data-backed switch parity."""
    fails: list[str] = []
    holds: list[str] = []
    _check_allowed_keys(rec, GATE42_ALLOWED_KEYS, fails, "GATE42")

    target = str(rec.get("target_gene", "")).strip().upper()
    if target in ("MAP3K7", "BACH2"):
        fails.append(f"FAIL_EXCLUDED_CANDIDATE_BLOCKED:{target}")
    elif target not in C1_FAMILY_GENES:
        fails.append("FAIL_UNRECOGNIZED_TARGET_GENE")

    c1_raw = rec.get("c1_evidence")
    expected_nt = str(c1_raw.get("comparator_nt_lot_id", "")).strip() if isinstance(c1_raw, Mapping) and is_nonempty_str(c1_raw.get("comparator_nt_lot_id")) else None
    if isinstance(c1_raw, Mapping) and expected_nt is None:
        fails.append("FAIL_GATE42_MISSING_MANDATORY_COMPARATOR_NT_LOT_ID")
    sentinel_nt = expected_nt if expected_nt is not None else "__MISSING_REQUIRED_NT_LOT_ID__"

    spec, _, b_fails, b_holds, mat_ev, sw_ev, g0v_ev, g31_ev = _validate_canonical_binding_v6(
        rec, allow_design_a=True, coating_gate=False, phase="EXACT_PRODUCT",
        require_materialization=True, require_switches=True,
        expected_candidate_gene=target if target in C1_FAMILY_GENES else None,
        expected_comparator_nt_lot_id=sentinel_nt if isinstance(c1_raw, Mapping) else None,
    )
    fails.extend(b_fails)
    holds.extend(b_holds)

    prod_s = str(rec.get("product_id", "")).strip()
    bank_s = str(rec.get("bank_id", "")).strip()
    lot_s = str(rec.get("lot_id", "")).strip()
    route_s = str(rec.get("route_id", "")).strip().upper()
    is_design_a = (prod_s == "ISLET1_DESIGN_A_V080_REF")
    if is_design_a and route_s != "R1":
        fails.append("FAIL_DESIGN_A_DIAGNOSTIC_MUST_USE_UNCOATED_R1")

    df_ev = _validate_content_receipt(
        rec.get("drug_free_exposure_evidence"),
        expected_stage="DRUG_FREE_EXPOSURE", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="exact_product",
        expected_parent=mat_ev,
        allowed_extra_keys=frozenset({"route_coated", "added_drugs_count"}),
        fails=fails, holds=holds,
        missing_hold="HOLD_DRUG_FREE_EXPOSURE_RECEIPT_MISSING",
        fail_code="FAIL_DRUG_FREE_EXPOSURE_FAILED",
        mismatch_code="FAIL_DRUG_FREE_EXPOSURE_SCOPE_MISMATCH",
    )
    if df_ev is not None:
        if df_ev.get("route_coated") is not False or df_ev.get("added_drugs_count") != 0:
            fails.append("FAIL_GATE42_REQUIRES_100PCT_DRUG_FREE_UNCOATED_EXPOSURE")

    if not (is_strict_bool(rec.get("zero_fasta_minted")) and rec["zero_fasta_minted"]):
        fails.append("FAIL_ZERO_FASTA_MINTED_BOUNDARY_VIOLATED")

    g36_ev: Optional[Mapping[str, Any]] = None
    if is_design_a:
        if "foundry_v2_gate36_evidence" in rec and rec["foundry_v2_gate36_evidence"] is not None:
            fails.append("FAIL_DESIGN_A_FORBIDS_FOUNDRY_V2_GATE36_RECEIPT")
    elif spec is not None and spec["foundry_v2_biologics_eligible"]:
        g36_ev = _validate_content_receipt(
            rec.get("foundry_v2_gate36_evidence"),
            expected_stage="GATE-36-FOUNDRY-V2", expected_prod=prod_s, expected_bank=bank_s,
            expected_lot=lot_s, expected_route=route_s, expected_scope="exact_product",
            expected_parent=mat_ev,
            min_prereq_receipts=[("DRUG_FREE_EXPOSURE", df_ev)],
            allowed_extra_keys=frozenset({
                "canonical_gate36_producer_sha256", "canonical_gate36_verdict",
                "foundry_v2_module_scope", "active_drug_free_modules",
                "module_producer_receipt_sha256s", "exogenous_shield_excluded_from_drug_free_scope",
                "live_gate32_debris_recall_receipt", "matched_foundry_exposure_verified",
            }),
            fails=fails, holds=holds,
            missing_hold="HOLD_FOUNDRY_V2_GATE36_RECEIPT_MISSING",
            fail_code="FAIL_FOUNDRY_V2_GATE36_FAILED",
            mismatch_code="FAIL_FOUNDRY_V2_GATE36_SCOPE_MISMATCH",
        )
        if g36_ev is not None:
            if not is_valid_sha256_hex(g36_ev.get("canonical_gate36_producer_sha256")):
                fails.append("FAIL_FOUNDRY_V2_GATE36_MISSING_PRODUCER_SHA256")
            if g36_ev.get("canonical_gate36_verdict") != "PASS":
                fails.append("FAIL_FOUNDRY_V2_GATE36_NOT_PASSED")
            if g36_ev.get("foundry_v2_module_scope") != "INTRINSIC_CUFF_BIOLOGICS_NO_EXOGENOUS_SHIELD":
                fails.append("FAIL_FOUNDRY_V2_GATE36_EXOGENOUS_SHIELD_OUTSIDE_DRUG_FREE_SCOPE")
            if not (is_strict_bool(g36_ev.get("exogenous_shield_excluded_from_drug_free_scope")) and g36_ev["exogenous_shield_excluded_from_drug_free_scope"]):
                fails.append("FAIL_FOUNDRY_V2_GATE36_EXOGENOUS_SHIELD_NOT_EXCLUDED")
            # Strict zero-administered-agent drug-free path excludes pre-transplant administered GATE-36-INVVAX
            # (GATE-36:89,97), permitting ONLY graft-intrinsic / cuff modules {"GATE-36-CUFF", "GATE-36-INS"}!
            allowed_df_mods = frozenset({"GATE-36-CUFF", "GATE-36-INS"})
            act_mods = g36_ev.get("active_drug_free_modules")
            mod_shas = g36_ev.get("module_producer_receipt_sha256s")
            act_mods_str_ok = isinstance(act_mods, list) and all(isinstance(m, str) for m in act_mods)
            if not (
                act_mods_str_ok and len(act_mods) >= 1 and set(act_mods) <= allowed_df_mods and len(set(act_mods)) == len(act_mods)
                and isinstance(mod_shas, Mapping) and set(mod_shas.keys()) == set(act_mods)
                and all(is_valid_sha256_hex(v) for v in mod_shas.values())
            ):
                fails.append("FAIL_FOUNDRY_V2_GATE36_INVALID_DRUG_FREE_MODULE_PRODUCERS")
            if not (is_strict_bool(g36_ev.get("matched_foundry_exposure_verified")) and g36_ev["matched_foundry_exposure_verified"]):
                fails.append("FAIL_FOUNDRY_V2_GATE36_EXPOSURE_UNVERIFIED")
            # Explicit GATE-32 disposition for drug-free Foundry subset:
            # - GATE-36-CUFF active -> MUST provide validated passing live GATE-32 debris-recall receipt.
            # - ONLY GATE-36-INS active (no exogenous SHIELD & no CUFF) -> accepts validated GATE-32 receipt OR
            #   explicit sentinel "NOT_APPLICABLE_NO_EXOGENOUS_SHIELD_OR_CUFF_DEBRIS_CLAIM".
            g32_raw = g36_ev.get("live_gate32_debris_recall_receipt")
            cuff_active = act_mods_str_ok and ("GATE-36-CUFF" in act_mods)
            ins_only_active = act_mods_str_ok and set(act_mods) == {"GATE-36-INS"}
            if g32_raw == "NOT_APPLICABLE_NO_EXOGENOUS_SHIELD_OR_CUFF_DEBRIS_CLAIM":
                if cuff_active or not ins_only_active:
                    fails.append("FAIL_FOUNDRY_V2_GATE36_CUFF_REQUIRES_LIVE_GATE32_RECEIPT")
                g32_ev = None
            else:
                g32_ev = _validate_content_receipt(
                    g32_raw,
                    expected_stage="GATE-32-DEBRIS-RECALL", expected_prod=prod_s, expected_bank=bank_s,
                    expected_lot=lot_s, expected_route=route_s, expected_scope="exact_product",
                    expected_parent=mat_ev,
                    allowed_extra_keys=frozenset({
                        "canonical_gate32_producer_sha256", "debris_recall_verdict",
                        "debris_recall_l95_suppressed_frac", "residual_class2_recall_u95_frac",
                        "unrelated_recall_preserved",
                    }),
                    fails=fails, holds=holds,
                    missing_hold="HOLD_FOUNDRY_V2_GATE36_LIVE_GATE32_RECEIPT_MISSING",
                    fail_code="FAIL_FOUNDRY_V2_GATE36_LIVE_GATE32_FAILED",
                    mismatch_code="FAIL_FOUNDRY_V2_GATE36_LIVE_GATE32_SCOPE_MISMATCH",
                )
            if g32_ev is not None:
                if not is_valid_sha256_hex(g32_ev.get("canonical_gate32_producer_sha256")):
                    fails.append("FAIL_FOUNDRY_V2_GATE36_LIVE_GATE32_MISSING_PRODUCER_SHA256")
                if g32_ev.get("debris_recall_verdict") != "PASS_DEBRIS_RECALL_FULL_CREDIT":
                    fails.append("FAIL_FOUNDRY_V2_GATE36_LIVE_GATE32_DEBRIS_RECALL_NOT_PASSED")
                # Exact live GATE-36:34 GATE-32 thresholds: l95 >= 0.70, residual_class2_u95 <= 0.30, unrelated_recall_preserved == True!
                dr_l95 = g32_ev.get("debris_recall_l95_suppressed_frac")
                rc2_u95 = g32_ev.get("residual_class2_recall_u95_frac")
                unrel = g32_ev.get("unrelated_recall_preserved")
                if not (is_finite_num(dr_l95) and 0.70 <= float(dr_l95) <= 1.0):
                    fails.append("FAIL_FOUNDRY_V2_GATE36_LIVE_GATE32_RECALL_L95_BELOW_0P70")
                if not (is_finite_num(rc2_u95) and 0.0 <= float(rc2_u95) <= 0.30):
                    fails.append("FAIL_FOUNDRY_V2_GATE36_LIVE_GATE32_RESIDUAL_CLASS2_EXCEEDS_0P30")
                if not (is_strict_bool(unrel) and unrel):
                    fails.append("FAIL_FOUNDRY_V2_GATE36_LIVE_GATE32_UNRELATED_RECALL_COMPROMISED")
                t32 = parse_utc_iso_ts(g32_ev.get("recorded_at_utc"))
                t36 = parse_utc_iso_ts(g36_ev.get("recorded_at_utc"))
                if t32 is not None and t36 is not None and t32 > t36:
                    fails.append("FAIL_CHRONOLOGICAL_PREREQ_POSTDATES_STAGE:GATE-32_AFTER_GATE-36")

    # Complete canonical 5 x 2 IIP-0049 Stage-2 Attribution Matrix (docs/TNFA-IFNG-INTRINSIC-APOPTOSIS-QUALIFICATION-NOTE.md:54-60)!
    att_prereqs: list[tuple[str, Optional[Mapping[str, Any]]]] = [("BANK_MATERIALIZATION", mat_ev), ("DRUG_FREE_EXPOSURE", df_ev)]
    if g36_ev is not None:
        att_prereqs.append(("GATE-36-FOUNDRY-V2", g36_ev))
    att_extras = frozenset({
        "reference_comparator_backgrounds", "reference_comparator_measurements",
        "stage1_gatekeeper_record", "stage2_block_manifest",
        "stage1_cytokine_window_positive", "stage1_cytokine_drop_pp",
        "stage2_il1_independent_apoptosis_persists", "residual_viable_beta_drop_pp",
        "concurrent_controls_valid", "t0_original_plated_denominators_used",
        "biological_blocks_n", "background_class", "foundry_v2_gate36_receipt_sha256",
        "stage2_normoxia_mechanism_panel", "stage2_hypoxia_15mmhg_mechanism_panel",
    })
    att_ev = _validate_content_receipt(
        rec.get("iip0049_foundry_attribution_evidence"),
        expected_stage="IIP0049_ATTRIBUTION", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="exact_product",
        min_prereq_receipts=att_prereqs, allowed_extra_keys=att_extras,
        fails=fails, holds=holds,
        missing_hold="HOLD_IIP0049_STAGE1_STAGE2_ATTRIBUTION_MISSING",
        fail_code="FAIL_IIP0049_ATTRIBUTION_FAILED",
        mismatch_code="FAIL_IIP0049_ATTRIBUTION_SCOPE_MISMATCH",
    )
    if att_ev is not None:
        if not (is_strict_bool(att_ev.get("stage1_cytokine_window_positive")) and att_ev["stage1_cytokine_window_positive"]):
            fails.append("FAIL_IIP0049_STAGE1_WINDOW_NOT_POSITIVE")
        s1_drop = att_ev.get("stage1_cytokine_drop_pp")
        if not (is_finite_num(s1_drop) and 10.0 <= float(s1_drop) <= 100.0):
            fails.append("FAIL_IIP0049_STAGE1_CYTOKINE_DROP_BELOW_10PP")
        s2_persists = att_ev.get("stage2_il1_independent_apoptosis_persists")
        if s2_persists is False:
            fails.append("FAIL_NO_RESIDUAL_APOPTOSIS_ON_MATCHED_BACKGROUND")
        elif s2_persists is not True:
            fails.append("FAIL_IIP0049_STAGE2_OUTCOME_MISSING")
        drop_pp = att_ev.get("residual_viable_beta_drop_pp")
        if not (is_finite_num(drop_pp) and 10.0 <= float(drop_pp) <= 100.0):
            fails.append("FAIL_IIP0049_RESIDUAL_DROP_BELOW_10PP_OR_OUT_OF_DOMAIN")
        if not (is_strict_bool(att_ev.get("concurrent_controls_valid")) and att_ev["concurrent_controls_valid"]):
            fails.append("FAIL_IIP0049_CONCURRENT_CONTROLS_INVALID")
        if not (is_strict_bool(att_ev.get("t0_original_plated_denominators_used")) and att_ev["t0_original_plated_denominators_used"]):
            fails.append("FAIL_IIP0049_T0_DENOMINATORS_MISSING")
        # Full canonical IIP-0049 Stage-1 raw viability+caspase-3/7 + Stage-2 5-background x 5-condition x 2-O2 matrix!
        # (docs/TNFA-IFNG-INTRINSIC-APOPTOSIS-QUALIFICATION-NOTE.md:50-61)
        ref_bgs = att_ev.get("reference_comparator_backgrounds")
        ref_bg_clean: list[str] = []
        if not (isinstance(ref_bgs, list) and len(ref_bgs) >= 5 and all(is_nonempty_str(x) for x in ref_bgs)):
            fails.append("FAIL_IIP0049_MISSING_REFERENCE_COMPARATOR_BACKGROUNDS")
        else:
            ref_bg_clean = [str(x).strip() for x in ref_bgs]
            if len(set(ref_bg_clean)) != len(ref_bg_clean) or not (REQUIRED_IIP0049_REFERENCE_BACKGROUNDS <= set(ref_bg_clean)):
                fails.append("FAIL_IIP0049_MISSING_REFERENCE_COMPARATOR_BACKGROUNDS")
        s1_rec = att_ev.get("stage1_gatekeeper_record")
        t_s1_dec: Optional[datetime] = None
        s1_dec_id: Optional[str] = None
        t_att = parse_utc_iso_ts(att_ev.get("recorded_at_utc"))
        t_att_floor_list = [
            parse_utc_iso_ts(pr.get("recorded_at_utc"))
            for _, pr in att_prereqs if pr is not None
        ]
        t_att_floor = max((t for t in t_att_floor_list if t is not None), default=None)
        s1_cond_keys = frozenset({"vehicle", "il1b_ifng", "isolated_tnfa_ifng"})
        foundry_s1_req = (not is_design_a) and (spec is not None and bool(spec["foundry_v2_biologics_eligible"]))
        s1_req_keys = {
            "batch_id", "decision_id", "assay_acquired_at_utc", "decision_recorded_at_utc",
            "parental_il1b_ifng_drop_pp", "edited_il1b_ifng_drop_pp", "edited_isolated_tnfa_ifng_drop_pp",
            "unmodified_isogenic_viability_pct_by_cond", "unmodified_isogenic_caspase3_7_fold_by_cond",
            "edited_chassis_viability_pct_by_cond", "edited_chassis_caspase3_7_fold_by_cond",
        }
        if foundry_s1_req:
            s1_req_keys |= {
                "edited_chassis_plus_foundry_v2_viability_pct_by_cond",
                "edited_chassis_plus_foundry_v2_caspase3_7_fold_by_cond",
            }
        if not isinstance(s1_rec, Mapping) or set(s1_rec.keys()) != s1_req_keys:
            fails.append("FAIL_IIP0049_MISSING_STAGE1_GATEKEEPER_RECORD")
        else:
            t_s1_acq = parse_utc_iso_ts(s1_rec.get("assay_acquired_at_utc"))
            t_s1_dec = parse_utc_iso_ts(s1_rec.get("decision_recorded_at_utc"))
            s1_dec_id = str(s1_rec.get("decision_id", "")).strip() if is_nonempty_str(s1_rec.get("decision_id")) else None
            pv = s1_rec.get("unmodified_isogenic_viability_pct_by_cond")
            pc37 = s1_rec.get("unmodified_isogenic_caspase3_7_fold_by_cond")
            ev_ch = s1_rec.get("edited_chassis_viability_pct_by_cond")
            ec37_ch = s1_rec.get("edited_chassis_caspase3_7_fold_by_cond")
            ev_act = s1_rec.get("edited_chassis_plus_foundry_v2_viability_pct_by_cond") if foundry_s1_req else ev_ch
            ec37_act = s1_rec.get("edited_chassis_plus_foundry_v2_caspase3_7_fold_by_cond") if foundry_s1_req else ec37_ch
            s1_v_maps = (pv, ev_ch, ev_act) if foundry_s1_req else (pv, ev_ch)
            s1_c_maps = (pc37, ec37_ch, ec37_act) if foundry_s1_req else (pc37, ec37_ch)
            raw_s1_ok = (
                all(isinstance(m, Mapping) and set(m.keys()) == s1_cond_keys for m in s1_v_maps + s1_c_maps)
                and all(is_finite_num(m[k]) and 0.0 <= float(m[k]) <= 100.0 for m in s1_v_maps for k in s1_cond_keys)
                and all(is_finite_num(m[k]) and float(m[k]) > 0.0 for m in s1_c_maps for k in s1_cond_keys)
            )
            if (
                not raw_s1_ok
                or not is_nonempty_str(s1_rec.get("batch_id")) or s1_dec_id is None
                or t_s1_acq is None or t_s1_dec is None
                or t_s1_acq > t_s1_dec
                or (t_att is not None and t_s1_dec > t_att)
                or not (is_finite_num(s1_rec["parental_il1b_ifng_drop_pp"]) and float(s1_rec["parental_il1b_ifng_drop_pp"]) >= 15.0)
                or not (is_finite_num(s1_rec["edited_il1b_ifng_drop_pp"]) and 0.0 <= float(s1_rec["edited_il1b_ifng_drop_pp"]) < 10.0)
                or not (is_finite_num(s1_rec["edited_isolated_tnfa_ifng_drop_pp"]) and float(s1_rec["edited_isolated_tnfa_ifng_drop_pp"]) >= 10.0)
            ):
                fails.append("FAIL_IIP0049_STAGE1_GATEKEEPER_CONTROLS_FAILED")
            else:
                # Derive Stage-1 escalation drop directly from the EXACT active arm (edited_chassis_plus_foundry_v2 when Foundry-eligible!)
                derived_act_il1_drop = float(ev_act["vehicle"]) - float(ev_act["il1b_ifng"])
                derived_act_tnf_drop = float(ev_act["vehicle"]) - float(ev_act["isolated_tnfa_ifng"])
                if (
                    abs((float(pv["vehicle"]) - float(pv["il1b_ifng"])) - float(s1_rec["parental_il1b_ifng_drop_pp"])) > 0.1
                    or abs(derived_act_il1_drop - float(s1_rec["edited_il1b_ifng_drop_pp"])) > 0.1
                    or abs(derived_act_tnf_drop - float(s1_rec["edited_isolated_tnfa_ifng_drop_pp"])) > 0.1
                    or (is_finite_num(s1_drop) and abs(derived_act_tnf_drop - float(s1_drop)) > 0.1)
                    or derived_act_tnf_drop < 10.0
                    or float(pc37["il1b_ifng"]) < 2.0
                    or float(ec37_act["il1b_ifng"]) > 1.5
                    or float(ec37_act["isolated_tnfa_ifng"]) < 2.0
                ):
                    fails.append("FAIL_IIP0049_STAGE1_RAW_VIABILITY_OR_CASP37_CONTRADICTS_ESCALATION")
            if t_s1_acq is not None and t_att_floor is not None and t_s1_acq < t_att_floor:
                fails.append("FAIL_IIP0049_STAGE1_ACQUIRED_BEFORE_EXPOSURE_OR_FOUNDRY")

        ab_n = att_ev.get("biological_blocks_n")
        if not (is_strict_int(ab_n) and int(ab_n) >= 3):
            fails.append("FAIL_IIP0049_ATTRIBUTION_BLOCKS_LT_3")
        else:
            n_ab = int(ab_n)
            s2_man = att_ev.get("stage2_block_manifest")
            s2_manifest_bids: list[str] = []
            if not isinstance(s2_man, list) or len(s2_man) != n_ab:
                fails.append("FAIL_IIP0049_MISSING_STAGE2_BLOCK_MANIFEST")
            else:
                seen_s2b: set[str] = set()
                seen_s2batch: set[str] = set()
                for idx_m, mrow in enumerate(s2_man):
                    if not isinstance(mrow, Mapping) or set(mrow.keys()) != {
                        "block_id", "differentiation_batch_id", "stage1_decision_id", "study_start_utc", "harvest_utc",
                    }:
                        fails.append(f"FAIL_IIP0049_MALFORMED_BLOCK_MANIFEST:{idx_m}"); break
                    bid_m = str(mrow.get("block_id", "")).strip().upper()
                    bat_m = str(mrow.get("differentiation_batch_id", "")).strip().upper()
                    dec_m = str(mrow.get("stage1_decision_id", "")).strip()
                    t_sm = parse_utc_iso_ts(mrow.get("study_start_utc"))
                    t_hm = parse_utc_iso_ts(mrow.get("harvest_utc"))
                    if (
                        not bid_m or not bat_m or bid_m in seen_s2b or bat_m in seen_s2batch
                        or t_sm is None or t_hm is None or t_sm > t_hm
                        or (t_att is not None and t_hm > t_att)
                    ):
                        fails.append(f"FAIL_IIP0049_INVALID_OR_NONINDEPENDENT_BLOCK_MANIFEST:{idx_m}"); break
                    if s1_dec_id is not None and dec_m != s1_dec_id:
                        fails.append(f"FAIL_IIP0049_STAGE2_MISSING_STAGE1_DECISION_BINDING:{idx_m}")
                    if t_s1_dec is not None and t_sm < t_s1_dec:
                        fails.append(f"FAIL_IIP0049_STAGE2_STARTED_BEFORE_STAGE1_DECISION:{idx_m}")
                    if t_att_floor is not None and t_sm < t_att_floor:
                        fails.append(f"FAIL_IIP0049_STAGE2_STARTED_BEFORE_EXPOSURE_OR_FOUNDRY:{idx_m}")
                    seen_s2b.add(bid_m); seen_s2batch.add(bat_m)
                    s2_manifest_bids.append(bid_m)

            # Validate full canonical 5-condition x 2-oxygen (normoxia + hypoxia_15mmhg) measurements for EVERY reference comparator!
            ref_meas = att_ev.get("reference_comparator_measurements")
            parental_il1_drops_by_o2: dict[str, list[float]] = {}
            if not isinstance(ref_meas, Mapping) or not ref_bg_clean or set(ref_meas.keys()) != set(ref_bg_clean):
                fails.append("FAIL_IIP0049_MISSING_KEYED_REFERENCE_COMPARATOR_MEASUREMENTS")
            else:
                rc_o2_allowed = frozenset({
                    "block_ids",
                    "cond1_vehicle_beta_t0_pct_by_block",
                    "cond2_ifng_alone_beta_t0_pct_by_block",
                    "cond3_isolated_tnfa_ifng_beta_t0_pct_by_block",
                    "cond4_il1b_ifng_beta_t0_pct_by_block",
                    "cond5_pooled_triple_cytokine_beta_t0_pct_by_block",
                })
                for bg_k, bg_m in ref_meas.items():
                    if (
                        not isinstance(bg_m, Mapping) or set(bg_m.keys()) != {"normoxia", "hypoxia_15mmhg"}
                        or not isinstance(bg_m["normoxia"], Mapping) or not isinstance(bg_m["hypoxia_15mmhg"], Mapping)
                    ):
                        fails.append(f"FAIL_IIP0049_MALFORMED_COMPARATOR_MEASUREMENTS:{bg_k}"); continue
                    if dict(bg_m["normoxia"]) == dict(bg_m["hypoxia_15mmhg"]):
                        fails.append(f"FAIL_IIP0049_COMPARATOR_IDENTICAL_NORMOXIA_HYPOXIA:{bg_k}"); continue
                    for o2k in ("normoxia", "hypoxia_15mmhg"):
                        om = bg_m[o2k]
                        if not isinstance(om, Mapping) or set(om.keys()) != rc_o2_allowed:
                            fails.append(f"FAIL_IIP0049_MALFORMED_COMPARATOR_O2_PANEL:{bg_k}:{o2k}"); continue
                        obids = om.get("block_ids")
                        if not (isinstance(obids, list) and len(obids) == n_ab and all(is_nonempty_str(x) for x in obids)) or (s2_manifest_bids and [str(x).strip().upper() for x in obids] != s2_manifest_bids):
                            fails.append(f"FAIL_IIP0049_COMPARATOR_BLOCK_IDS_MISMATCH:{bg_k}:{o2k}"); continue
                        c_vecs = [om[ck] for ck in (
                            "cond1_vehicle_beta_t0_pct_by_block",
                            "cond2_ifng_alone_beta_t0_pct_by_block",
                            "cond3_isolated_tnfa_ifng_beta_t0_pct_by_block",
                            "cond4_il1b_ifng_beta_t0_pct_by_block",
                            "cond5_pooled_triple_cytokine_beta_t0_pct_by_block",
                        )]
                        if not all(isinstance(v, list) and len(v) == n_ab and all(is_finite_num(x) and 0.0 <= float(x) <= 100.0 for x in v) for v in c_vecs):
                            fails.append(f"FAIL_IIP0049_INVALID_COMPARATOR_ARRAYS:{bg_k}:{o2k}"); continue
                        f1, f2, f3, f4, f5 = ([float(x) for x in v] for v in c_vecs)
                        if bg_k == "PARENTAL_UNEDITED":
                            p_drops = [f1[i] - f4[i] for i in range(n_ab)]
                            parental_il1_drops_by_o2[o2k] = p_drops
                            if (sum(p_drops) / n_ab) < 15.0 or any(d < 15.0 for d in p_drops):
                                fails.append(f"FAIL_IIP0049_PARENTAL_COMPARATOR_IL1_SENSITIVITY_BELOW_15PP:{o2k}")
                        elif bg_k in ("MULTI_MIR_IL1R1_FAS_REFERENCE", "CD64T_IL1RN_REFERENCE"):
                            if (sum(f1[i] - f4[i] for i in range(n_ab)) / n_ab) >= 10.0 or (sum(f1[i] - f3[i] for i in range(n_ab)) / n_ab) < 10.0:
                                fails.append(f"FAIL_IIP0049_IL1_SHIELD_COMPARATOR_ATTRIBUTION_INCONSISTENT:{bg_k}:{o2k}")
            mp_allowed = frozenset({
                "block_ids",
                "cond1_vehicle_beta_t0_pct_by_block",
                "cond2_ifng_alone_beta_t0_pct_by_block",
                "cond3_isolated_tnfa_ifng_beta_t0_pct_by_block",
                "cond4_il1b_ifng_beta_t0_pct_by_block",
                "cond5_pooled_triple_cytokine_beta_t0_pct_by_block",
                "cleaved_caspase8_fold_by_block", "cleaved_caspase9_fold_by_block",
                "cytochrome_c_release_pct_by_block", "pmlkl_ratio_by_block",
                "bim_dp5_puma_induction_fold_by_block",
                "il1_pathway_positive_control_verified",
                "il1_positive_control_parental_drop_pp_by_block",
                "cxcl10_assay_lod_mfi", "cxcl10_matched_ctrl_24h_mfi_by_block",
                "cxcl10_0h_mfi_by_block", "cxcl10_24h_mfi_by_block",
                "cxcl10_0h_vs_24h_shield_retention_pct_by_block",
                "serpinb9_pct_matched_ctrl_by_block", "pdl1_pct_matched_ctrl_by_block",
                "post_washout_gsis_si_by_block",
                "post_washout_gsis_z2_by_block",
                "post_washout_gsis_stepdown_t50_min_by_block",
                "lineage_survival_pct_by_lineage",
            })
            p_norm = att_ev.get("stage2_normoxia_mechanism_panel")
            p_hyp = att_ev.get("stage2_hypoxia_15mmhg_mechanism_panel")
            norm_tnf_drop_mean: Optional[float] = None
            for ptag, panel in (("NORMOXIA", p_norm), ("HYPOXIA15", p_hyp)):
                if not isinstance(panel, Mapping):
                    fails.append(f"FAIL_IIP0049_MISSING_SEPARATED_MECHANISM_PANEL:{ptag}"); continue
                _check_allowed_keys(panel, mp_allowed, fails, f"IIP0049_{ptag}")
                pbids = panel.get("block_ids")
                if not (isinstance(pbids, list) and len(pbids) == n_ab and all(is_nonempty_str(x) for x in pbids)) or (s2_manifest_bids and [str(x).strip().upper() for x in pbids] != s2_manifest_bids):
                    fails.append(f"FAIL_IIP0049_PANEL_BLOCK_IDS_MISMATCH:{ptag}")
                c1v = panel.get("cond1_vehicle_beta_t0_pct_by_block")
                c2v = panel.get("cond2_ifng_alone_beta_t0_pct_by_block")
                c3v = panel.get("cond3_isolated_tnfa_ifng_beta_t0_pct_by_block")
                c4v = panel.get("cond4_il1b_ifng_beta_t0_pct_by_block")
                c5v = panel.get("cond5_pooled_triple_cytokine_beta_t0_pct_by_block")
                c8v = panel.get("cleaved_caspase8_fold_by_block")
                c9v = panel.get("cleaved_caspase9_fold_by_block")
                bh3v = panel.get("bim_dp5_puma_induction_fold_by_block")
                shv = panel.get("cxcl10_0h_vs_24h_shield_retention_pct_by_block")
                gsisv = panel.get("post_washout_gsis_si_by_block")
                lmap = panel.get("lineage_survival_pct_by_lineage")
                all_vecs = (c1v, c2v, c3v, c4v, c5v, c8v, c9v, bh3v, shv, gsisv)
                if not all(isinstance(v, list) and len(v) == n_ab and all(is_finite_num(x) for x in v) for v in all_vecs):
                    fails.append(f"FAIL_IIP0049_INCOMPLETE_5COND_OR_MECHANISM_VECTORS:{ptag}"); continue
                c1f = [float(x) for x in c1v]
                c2f = [float(x) for x in c2v]
                c3f = [float(x) for x in c3v]
                c4f = [float(x) for x in c4v]
                c5f = [float(x) for x in c5v]
                if any(not (0.0 <= x <= 100.0) for x in c1f + c2f + c3f + c4f + c5f):
                    fails.append(f"FAIL_IIP0049_BETA_SURVIVAL_OUT_OF_0_100:{ptag}"); continue
                tnf_drops = [c1f[i] - c3f[i] for i in range(n_ab)]
                tnf_over_ifng = [c2f[i] - c3f[i] for i in range(n_ab)]
                il1_drops = [c1f[i] - c4f[i] for i in range(n_ab)]
                triple_drops = [c1f[i] - c5f[i] for i in range(n_ab)]
                # Reconcile causal attribution directly from the 5-condition controls:
                # (1) Isolated TNFa+IFNg causes >= 10 pp drop vs vehicle (L95 > 0) AND >= 10 pp incremental loss OVER paired IFNg-only control (L95 > 0)!
                # (2) IL-1b+IFNg drop is protected (< 10 pp & materially lower than TNFa+IFNg) with positive IL-1 pathway control verified!
                # (3) Pooled triple also reflects >= 10 pp drop.
                ts_tnf = paired_t_summary(tnf_drops)
                ts_tnf_vs_ifng = paired_t_summary(tnf_over_ifng)
                mean_tnf = sum(tnf_drops) / n_ab
                mean_tnf_over_ifng = sum(tnf_over_ifng) / n_ab
                mean_il1 = sum(il1_drops) / n_ab
                mean_trip = sum(triple_drops) / n_ab
                if ptag == "NORMOXIA":
                    norm_tnf_drop_mean = mean_tnf
                if ts_tnf is None or mean_tnf < 10.0 or ts_tnf[3] <= 0.0:
                    fails.append(f"FAIL_IIP0049_ISOLATED_TNFA_IFNG_DROP_UNPROVEN:{ptag}")
                if ts_tnf_vs_ifng is None or mean_tnf_over_ifng < 10.0 or ts_tnf_vs_ifng[3] <= 0.0:
                    fails.append(f"FAIL_IIP0049_ZERO_OR_UNPROVEN_INCREMENTAL_TNF_OVER_IFNG_ONLY:{ptag}")
                il1_pos_v = panel.get("il1_positive_control_parental_drop_pp_by_block")
                o2_map_k = "normoxia" if ptag == "NORMOXIA" else "hypoxia_15mmhg"
                if not (
                    is_strict_bool(panel.get("il1_pathway_positive_control_verified")) and panel["il1_pathway_positive_control_verified"]
                    and isinstance(il1_pos_v, list) and len(il1_pos_v) == n_ab
                    and all(is_finite_num(x) and float(x) >= 15.0 for x in il1_pos_v)
                ):
                    fails.append(f"FAIL_IIP0049_IL1_PATHWAY_POSITIVE_CONTROL_MISSING:{ptag}")
                elif o2_map_k in parental_il1_drops_by_o2 and any(
                    abs(float(il1_pos_v[bi]) - parental_il1_drops_by_o2[o2_map_k][bi]) > 1e-6
                    for bi in range(n_ab)
                ):
                    fails.append(f"FAIL_IIP0049_PARENTAL_IL1_CONTROL_BLOCK_MISMATCH:{ptag}")
                if mean_il1 >= 10.0 or mean_il1 >= mean_tnf - 5.0:
                    fails.append(f"FAIL_IIP0049_IL1_CONTROL_NOT_PROTECTED_OR_CONFOUNDED:{ptag}")
                if mean_trip < 10.0:
                    fails.append(f"FAIL_IIP0049_POOLED_TRIPLE_DROP_BELOW_10PP:{ptag}")
                # Intrinsic (caspase-9, cytochrome c, BH3) vs extrinsic (caspase-8) & necroptosis (pMLKL) causal split!
                cytc_v = panel.get("cytochrome_c_release_pct_by_block")
                pmlkl_v = panel.get("pmlkl_ratio_by_block")
                c8_m = sum(float(x) for x in c8v) / n_ab
                c9_m = sum(float(x) for x in c9v) / n_ab
                bh3_m = sum(float(x) for x in bh3v) / n_ab
                if (
                    c9_m < 2.0 or bh3_m < 2.0 or c9_m <= c8_m
                    or not (isinstance(cytc_v, list) and len(cytc_v) == n_ab and all(is_finite_num(x) and float(x) >= 25.0 for x in cytc_v))
                    or not (isinstance(pmlkl_v, list) and len(pmlkl_v) == n_ab and all(is_finite_num(x) and 0.0 <= float(x) <= 1.25 for x in pmlkl_v))
                ):
                    fails.append(f"FAIL_IIP0049_INTRINSIC_CASP9_BH3_MECHANISM_UNPROVEN:{ptag}")
                # Calibrated matched-control CXCL10 (above 3x LOD + matched ctrl) AND separate SERPINB9 + PD-L1 shield kinetics!
                lod_mfi = panel.get("cxcl10_assay_lod_mfi")
                ctrl24 = panel.get("cxcl10_matched_ctrl_24h_mfi_by_block")
                mfi0 = panel.get("cxcl10_0h_mfi_by_block")
                mfi24 = panel.get("cxcl10_24h_mfi_by_block")
                sb9_v = panel.get("serpinb9_pct_matched_ctrl_by_block")
                pdl1_v = panel.get("pdl1_pct_matched_ctrl_by_block")
                if not (
                    is_finite_num(lod_mfi) and float(lod_mfi) > 0.0
                    and isinstance(ctrl24, list) and len(ctrl24) == n_ab
                    and isinstance(mfi0, list) and isinstance(mfi24, list) and len(mfi0) == n_ab and len(mfi24) == n_ab
                    and all(is_finite_num(x) and float(x) > 0.0 for x in mfi0 + mfi24 + ctrl24)
                ):
                    fails.append(f"FAIL_IIP0049_MISSING_RAW_0H_24H_SHIELD_MFI:{ptag}")
                else:
                    lod_f = float(lod_mfi)
                    for bi in range(n_ab):
                        recomp_ret = 100.0 * float(mfi24[bi]) / float(mfi0[bi])
                        if (
                            float(mfi0[bi]) < 3.0 * lod_f or float(mfi24[bi]) < 3.0 * lod_f
                            or float(mfi24[bi]) < 0.85 * float(ctrl24[bi])
                            or abs(recomp_ret - float(shv[bi])) > 0.5 or not (85.0 <= recomp_ret <= 120.0)
                        ):
                            fails.append(f"FAIL_IIP0049_SHIELD_KINETICS_COMPROMISED_ON_BACKGROUND:{ptag}"); break
                if not (
                    isinstance(sb9_v, list) and len(sb9_v) == n_ab and all(is_finite_num(x) and 85.0 <= float(x) <= 200.0 for x in sb9_v)
                    and isinstance(pdl1_v, list) and len(pdl1_v) == n_ab and all(is_finite_num(x) and 85.0 <= float(x) <= 200.0 for x in pdl1_v)
                ):
                    fails.append(f"FAIL_IIP0049_SERPINB9_OR_PDL1_SHIELD_BELOW_85PCT:{ptag}")
                if any(not (85.0 <= float(x) <= 120.0) for x in shv):
                    fails.append(f"FAIL_IIP0049_SHIELD_KINETICS_COMPROMISED_ON_BACKGROUND:{ptag}")
                gz2_v = panel.get("post_washout_gsis_z2_by_block")
                gt50_v = panel.get("post_washout_gsis_stepdown_t50_min_by_block")
                if (
                    any(float(x) < 3.0 for x in gsisv)
                    or not (isinstance(gz2_v, list) and len(gz2_v) == n_ab and all(is_finite_num(x) and float(x) >= 1.0 for x in gz2_v))
                    or not (isinstance(gt50_v, list) and len(gt50_v) == n_ab and all(is_finite_num(x) and 0.0 < float(x) <= 3.0 for x in gt50_v))
                ):
                    fails.append(f"FAIL_IIP0049_POST_WASHOUT_GSIS_FAILED_ON_BACKGROUND:{ptag}")
                if not (isinstance(lmap, Mapping) and set(lmap.keys()) == REQUIRED_5_LINEAGES and all(is_finite_num(v) and 0.0 <= float(v) <= 100.0 for v in lmap.values())):
                    fails.append(f"FAIL_IIP0049_INCOMPLETE_5LINEAGE_ATTRIBUTION:{ptag}")
            # Single-source-of-truth unification: Stage-2 mechanism panels MUST match the exact active product row
            # in reference_comparator_measurements ("EXACT_PRODUCT_FOUNDRY_V2" or "DESIGN_A_CHASSIS_REFERENCE" for Design A)!
            active_s2_bg = "DESIGN_A_CHASSIS_REFERENCE" if is_design_a else "EXACT_PRODUCT_FOUNDRY_V2"
            if not isinstance(ref_meas, Mapping) or active_s2_bg not in ref_meas or not isinstance(ref_meas.get(active_s2_bg), Mapping):
                fails.append("FAIL_IIP0049_STAGE2_MISSING_EXACT_PRODUCT_COMPARATOR_ROW")
            else:
                act_row = ref_meas[active_s2_bg]
                for o2k, pan_obj in (("normoxia", p_norm), ("hypoxia_15mmhg", p_hyp)):
                    om_act = act_row.get(o2k)
                    if not isinstance(om_act, Mapping) or not isinstance(pan_obj, Mapping):
                        fails.append(f"FAIL_IIP0049_STAGE2_EXACT_PRODUCT_MATRIX_VS_PANEL_MISMATCH:{o2k}")
                    else:
                        same_5c = (
                            om_act.get("block_ids") == pan_obj.get("block_ids")
                            and all(
                                isinstance(om_act.get(ck), list) and isinstance(pan_obj.get(ck), list)
                                and len(om_act[ck]) == len(pan_obj[ck])
                                and all(abs(float(a) - float(b)) <= 1e-9 for a, b in zip(om_act[ck], pan_obj[ck]))
                                for ck in (
                                    "cond1_vehicle_beta_t0_pct_by_block",
                                    "cond2_ifng_alone_beta_t0_pct_by_block",
                                    "cond3_isolated_tnfa_ifng_beta_t0_pct_by_block",
                                    "cond4_il1b_ifng_beta_t0_pct_by_block",
                                    "cond5_pooled_triple_cytokine_beta_t0_pct_by_block",
                                )
                            )
                        )
                        if not same_5c:
                            fails.append(f"FAIL_IIP0049_STAGE2_EXACT_PRODUCT_MATRIX_VS_PANEL_MISMATCH:{o2k}")
            if norm_tnf_drop_mean is not None and is_finite_num(drop_pp) and abs(float(drop_pp) - norm_tnf_drop_mean) > 1e-4:
                fails.append("FAIL_IIP0049_REPORTED_RESIDUAL_DROP_MISMATCH_VS_5COND_RAW")
            if isinstance(p_norm, Mapping) and isinstance(p_hyp, Mapping) and dict(p_norm) == dict(p_hyp):
                fails.append("FAIL_IIP0049_IDENTICAL_COPY_PASTE_NORMOXIA_HYPOXIA_ATTRIBUTION")

        bg = att_ev.get("background_class")
        if is_design_a:
            if bg != "UNMODIFIED_DESIGN_A_REFERENCE":
                fails.append("FAIL_DESIGN_A_MUST_USE_UNMODIFIED_REFERENCE_BACKGROUND")
        elif spec is not None and spec["foundry_v2_biologics_eligible"]:
            if bg != "MATCHED_FOUNDRY_V2":
                fails.append("FAIL_MATCHED_FOUNDRY_V2_BACKGROUND_NOT_VERIFIED")
            if g36_ev is not None and att_ev.get("foundry_v2_gate36_receipt_sha256") != g36_ev.get("receipt_sha256"):
                fails.append("FAIL_FOUNDRY_V2_GATE36_RECEIPT_DIGEST_MISMATCH")

    # Pre-study CANDIDATE-NEUTRAL family C-1 Preregistered Analysis Plan Receipt (shared across ALL 5 arms of the study!)
    c1_prereg_ev = None
    if c1_raw is not None or rec.get("c1_preregistered_plan_receipt") is not None:
        c1_prereg_ev = _validate_content_receipt(
            rec.get("c1_preregistered_plan_receipt"),
            expected_stage="C-1-PREREGISTRATION", expected_prod=prod_s, expected_bank=bank_s,
            expected_lot=lot_s, expected_route=route_s, expected_scope="exact_product",
            expected_candidate_gene=None,
            expected_comparator_nt_lot_id=sentinel_nt if isinstance(c1_raw, Mapping) else None,
            expected_parent=att_ev,
            allowed_extra_keys=frozenset({
                "preregistered_family_genes",
                "shared_study_id", "locked_analysis_plan_id", "block_randomization_seed_sha256",
                "planned_biological_blocks_n", "statistical_test_method", "multiplicity_method",
                "exchangeability_design_statement", "block_to_batch_allocations",
            }),
            fails=fails, holds=holds,
            missing_hold="HOLD_GATE_C1_PREREGISTERED_PLAN_RECEIPT_MISSING",
            fail_code="FAIL_GATE_C1_PREREGISTERED_PLAN_FAILED",
            mismatch_code="FAIL_GATE_C1_PREREGISTERED_PLAN_SCOPE_MISMATCH",
        )
        if c1_prereg_ev is not None:
            if "candidate_gene" in c1_prereg_ev and c1_prereg_ev["candidate_gene"] is not None:
                fails.append("FAIL_GATE_C1_PREREG_MUST_BE_CANDIDATE_NEUTRAL")
            if c1_prereg_ev.get("preregistered_family_genes") != sorted(C1_FAMILY_GENES):
                fails.append("FAIL_GATE_C1_PREREG_MUST_DECLARE_ALL_5_FAMILY_GENES")

    # Gate C-1: per-family Holm-5 AND global composite IUT Holm-5 (< 0.01 across all 4 endpoints!)
    c1_prereqs: list[tuple[str, Optional[Mapping[str, Any]]]] = [("BANK_MATERIALIZATION", mat_ev), ("DRUG_FREE_EXPOSURE", df_ev)]
    if g31_ev is not None:
        c1_prereqs.append(("GATE-31", g31_ev))
    if c1_prereg_ev is not None:
        c1_prereqs.append(("C-1-PREREGISTRATION", c1_prereg_ev))
    c1_extras = frozenset({
        "study_start_utc", "assay_acquired_at_utc",
        "shared_study_id", "locked_analysis_plan_id", "block_randomization_seed_sha256",
        "intervention_cohort_id", "five_arm_family_matrix_sha256",
        "c1_common_family_acquisition_record",
        "biological_blocks_n", "statistical_test_method", "multiplicity_method",
        "c1_normoxia", "c1_hypoxia_2pct_o2",
    })
    c1_ev = _validate_content_receipt(
        c1_raw,
        expected_stage="C-1", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="exact_product",
        expected_candidate_gene=target,
        expected_comparator_nt_lot_id=sentinel_nt if isinstance(c1_raw, Mapping) else None,
        expected_parent=att_ev,
        min_prereq_receipts=c1_prereqs,
        allowed_extra_keys=c1_extras, fails=fails, holds=holds,
        missing_hold="HOLD_GATE_C1_RECEIPT_MISSING",
        fail_code="FAIL_GATE_C1_FAILED",
        mismatch_code="FAIL_GATE_C1_SCOPE_MISMATCH",
    )
    is_pilot_only = False
    nt_lot_id: Optional[str] = expected_nt
    c1_cohort_id: Optional[str] = None
    if c1_ev is not None:
        t_c1_start = parse_utc_iso_ts(c1_ev.get("study_start_utc"))
        t_c1_acq = parse_utc_iso_ts(c1_ev.get("assay_acquired_at_utc"))
        t_c1_rec = parse_utc_iso_ts(c1_ev.get("recorded_at_utc"))
        t_c1_prereg = parse_utc_iso_ts(c1_prereg_ev.get("recorded_at_utc")) if c1_prereg_ev is not None else None
        t_att_ts = parse_utc_iso_ts(att_ev.get("recorded_at_utc")) if att_ev is not None else None
        if t_c1_start is None or t_c1_acq is None or t_c1_rec is None or not (t_c1_start <= t_c1_acq <= t_c1_rec):
            fails.append("FAIL_GATE_C1_INVALID_OR_MISSING_STUDY_ACQUISITION_TIMESTAMPS")
        else:
            if t_att_ts is not None and t_c1_start < t_att_ts:
                fails.append("FAIL_GATE_C1_STUDY_STARTED_BEFORE_IIP0049_ATTRIBUTION")
            if t_c1_prereg is not None and t_c1_prereg > t_c1_start:
                fails.append("FAIL_GATE_C1_PREREGISTERED_PLAN_POSTDATES_STUDY_START")
            for plbl_c, prec_c in c1_prereqs:
                if prec_c is not None:
                    tp_c = parse_utc_iso_ts(prec_c.get("recorded_at_utc"))
                    if tp_c is not None and t_c1_start < tp_c:
                        fails.append(f"FAIL_GATE_C1_STUDY_STARTED_BEFORE_{plbl_c}")
        if not is_nonempty_str(c1_ev.get("shared_study_id")):
            fails.append("FAIL_GATE_C1_MISSING_SHARED_STUDY_ID")
        if not (is_nonempty_str(c1_ev.get("locked_analysis_plan_id")) and len(str(c1_ev["locked_analysis_plan_id"]).strip()) >= 4):
            fails.append("FAIL_GATE_C1_MISSING_LOCKED_ANALYSIS_PLAN_ID")
        if not is_valid_sha256_hex(c1_ev.get("block_randomization_seed_sha256")):
            fails.append("FAIL_GATE_C1_MISSING_BLOCK_RANDOMIZATION_SEED_SHA256")
        c1_cohort_id = str(c1_ev["intervention_cohort_id"]).strip() if is_nonempty_str(c1_ev.get("intervention_cohort_id")) else None
        if c1_cohort_id is None:
            fails.append("FAIL_GATE_C1_MISSING_INTERVENTION_COHORT_ID")
        n_blocks = c1_ev.get("biological_blocks_n")
        stat_m = c1_ev.get("statistical_test_method")
        mult_m = c1_ev.get("multiplicity_method")
        if stat_m not in ("PAIRED_T_TEST_NORMALITY_VERIFIED", "EXACT_TWO_SIDED_SIGN_FLIP"):
            fails.append("FAIL_GATE_C1_UNDECLARED_STATISTICAL_METHOD")
        if mult_m != "HOLM_BONFERRONI_5_ARM":
            fails.append("FAIL_GATE_C1_MISSING_HOLM_BONFERRONI_5_ARM_MULTIPLICITY")
        prereg_norm_bids: Optional[list[str]] = None
        prereg_hyp_bids: Optional[list[str]] = None
        prereg_norm_batches: Optional[list[str]] = None
        prereg_hyp_batches: Optional[list[str]] = None
        prereg_norm_orders: Optional[list[list[str]]] = None
        prereg_hyp_orders: Optional[list[list[str]]] = None
        prereg_norm_alloc_clean: Optional[list[dict[str, Any]]] = None
        prereg_hyp_alloc_clean: Optional[list[dict[str, Any]]] = None
        c1_common_acq_sha_out: Optional[str] = None
        if c1_prereg_ev is not None:
            if (
                c1_prereg_ev.get("shared_study_id") != c1_ev.get("shared_study_id")
                or c1_prereg_ev.get("locked_analysis_plan_id") != c1_ev.get("locked_analysis_plan_id")
                or c1_prereg_ev.get("block_randomization_seed_sha256") != c1_ev.get("block_randomization_seed_sha256")
                or c1_prereg_ev.get("planned_biological_blocks_n") != n_blocks
                or c1_prereg_ev.get("statistical_test_method") != stat_m
                or c1_prereg_ev.get("multiplicity_method") != mult_m
                or c1_prereg_ev.get("exchangeability_design_statement") != "WITHIN_BLOCK_SIBLING_RANDOMIZED_TREATMENT_ASSIGNMENT"
            ):
                fails.append("FAIL_GATE_C1_PREREGISTERED_PLAN_MISMATCH")
            alloc = c1_prereg_ev.get("block_to_batch_allocations")
            if not isinstance(alloc, Mapping) or set(alloc.keys()) != {"normoxia", "hypoxia_2pct_o2"}:
                fails.append("FAIL_GATE_C1_PREREG_MISSING_BLOCK_TO_BATCH_ALLOCATIONS")
            elif is_strict_int(n_blocks) and int(n_blocks) >= 3:
                exp_arms_set = C1_FAMILY_GENES | {"NT_CTRL"}
                for ak, target_slot in (("normoxia", "norm"), ("hypoxia_2pct_o2", "hyp")):
                    alist = alloc.get(ak)
                    if not isinstance(alist, list) or len(alist) != int(n_blocks):
                        fails.append(f"FAIL_GATE_C1_PREREG_ALLOCATION_LENGTH_MISMATCH:{ak}"); continue
                    abids_seen: list[str] = []
                    abatches_list: list[str] = []
                    aorders_list: list[list[str]] = []
                    aclean_rows: list[dict[str, Any]] = []
                    abatches_seen: set[str] = set()
                    alloc_ok = True
                    for arow in alist:
                        if not isinstance(arow, Mapping) or set(arow.keys()) != {"block_id", "differentiation_batch_id", "randomized_arm_order"}:
                            fails.append(f"FAIL_GATE_C1_PREREG_MALFORMED_ALLOCATION:{ak}"); alloc_ok = False; break
                        ab_id = str(arow.get("block_id", "")).strip().upper()
                        ab_bat = str(arow.get("differentiation_batch_id", "")).strip().upper()
                        a_ord = arow.get("randomized_arm_order")
                        if (
                            not ab_id or not ab_bat or ab_id in abids_seen or ab_bat in abatches_seen
                            or not (
                                isinstance(a_ord, list) and len(a_ord) == len(exp_arms_set)
                                and all(isinstance(x, str) for x in a_ord) and set(a_ord) == exp_arms_set
                            )
                        ):
                            fails.append(f"FAIL_GATE_C1_PREREG_INVALID_BATCH_OR_ARM_ORDER:{ak}"); alloc_ok = False; break
                        a_ord_s = [str(x) for x in a_ord]
                        abids_seen.append(ab_id); abatches_seen.add(ab_bat)
                        abatches_list.append(ab_bat); aorders_list.append(a_ord_s)
                        aclean_rows.append({"block_id": ab_id, "differentiation_batch_id": ab_bat, "randomized_arm_order": a_ord_s})
                    if alloc_ok:
                        if target_slot == "norm":
                            prereg_norm_bids = abids_seen
                            prereg_norm_batches = abatches_list
                            prereg_norm_orders = aorders_list
                            prereg_norm_alloc_clean = aclean_rows
                        else:
                            prereg_hyp_bids = abids_seen
                            prereg_hyp_batches = abatches_list
                            prereg_hyp_orders = aorders_list
                            prereg_hyp_alloc_clean = aclean_rows
        if not is_strict_int(n_blocks) or int(n_blocks) < 3:
            fails.append("FAIL_GATE_C1_UNDERPOWERED_BLOCKS_LT_3")
        else:
            n_b = int(n_blocks)
            if n_b < 6:
                is_pilot_only = True
            elif stat_m == "EXACT_TWO_SIDED_SIGN_FLIP" and n_b < 10:
                fails.append("FAIL_GATE_C1_EXACT_SIGN_FLIP_REQUIRES_AT_LEAST_10_BLOCKS_FOR_HOLM5")
            norm_res = _validate_c1_oxygen_block(
                c1_ev.get("c1_normoxia"), o2_tag="NORMOXIA", target=target,
                stat_method=str(stat_m), expected_n=n_b,
                min_acq_ts=t_c1_start, max_acq_ts=t_c1_acq,
                expected_block_ids_norm=prereg_norm_bids,
                expected_batch_ids_norm=prereg_norm_batches,
                expected_arm_orders=prereg_norm_orders,
                expected_prod_id=prod_s, expected_lot_id=lot_s, expected_cohort_id=c1_cohort_id,
                fails=fails, holds=holds,
            )
            hyp_res = _validate_c1_oxygen_block(
                c1_ev.get("c1_hypoxia_2pct_o2"), o2_tag="HYPOXIA_2PCT", target=target,
                stat_method=str(stat_m), expected_n=n_b,
                min_acq_ts=t_c1_start, max_acq_ts=t_c1_acq,
                expected_block_ids_norm=prereg_hyp_bids,
                expected_batch_ids_norm=prereg_hyp_batches,
                expected_arm_orders=prereg_hyp_orders,
                expected_prod_id=prod_s, expected_lot_id=lot_s, expected_cohort_id=c1_cohort_id,
                fails=fails, holds=holds,
            )
            if norm_res is not None and hyp_res is not None:
                if norm_res[0] == hyp_res[0]:
                    fails.append("FAIL_GATE_C1_DUPLICATE_ASSAY_RECORD_ID_ACROSS_OXYGEN_REGIMES")
                if norm_res[1] == hyp_res[1]:
                    fails.append("FAIL_GATE_C1_IDENTICAL_COPY_PASTE_CASP9_ACROSS_OXYGEN_REGIMES")
                if (norm_res[2], norm_res[3], norm_res[4]) == (hyp_res[2], hyp_res[3], hyp_res[4]):
                    fails.append("FAIL_GATE_C1_IDENTICAL_COPY_PASTE_BETA_ACROSS_OXYGEN_REGIMES")
                # Immutable shared 5-arm x 2-oxygen family matrix SHA-256 incl. study/plan/blocks/common controls!
                if n_b >= 6 and isinstance(c1_ev.get("c1_normoxia"), Mapping) and isinstance(c1_ev.get("c1_hypoxia_2pct_o2"), Mapping):
                    def _fam_o2_slice(ob: Mapping[str, Any]) -> dict[str, Any]:
                        return {
                            "block_ids": ob.get("block_ids"),
                            "stressed_ctrl_beta_plated_t0_by_block": ob.get("stressed_ctrl_beta_plated_t0_by_block"),
                            "stressed_ctrl_beta_surviving_by_block": ob.get("stressed_ctrl_beta_surviving_by_block"),
                            "stressed_ctrl_beta_t0_pct_by_block": ob.get("stressed_ctrl_beta_t0_pct_by_block"),
                            "casp9_stressed_ctrl_raw_by_block": ob.get("casp9_stressed_ctrl_raw_by_block"),
                            "all_five_arms_paired_data": ob.get("all_five_arms_paired_data"),
                        }
                    fam_mat = {
                        "shared_study_id": c1_ev.get("shared_study_id"),
                        "locked_analysis_plan_id": c1_ev.get("locked_analysis_plan_id"),
                        "normoxia": _fam_o2_slice(c1_ev["c1_normoxia"]),
                        "hypoxia_2pct_o2": _fam_o2_slice(c1_ev["c1_hypoxia_2pct_o2"]),
                    }
                    fam_sha_calc = sha256_bytes(canonical_json_bytes(fam_mat))
                    fam_sha_sub = c1_ev.get("five_arm_family_matrix_sha256")
                    if not is_valid_sha256_hex(fam_sha_sub) or str(fam_sha_sub) != fam_sha_calc:
                        fails.append("FAIL_GATE_C1_FIVE_ARM_FAMILY_MATRIX_SHA256_MISMATCH")
                    # Candidate-agnostic producer common family acquisition record binding preregistration + batch/arm assignments + 5-arm x 2-O2 matrix!
                    cacq = c1_ev.get("c1_common_family_acquisition_record")
                    cacq_keys = frozenset({
                        "producer_acquisition_record_id", "shared_study_id", "locked_analysis_plan_id",
                        "preregistration_receipt_sha256", "block_randomization_seed_sha256",
                        "normoxia_block_allocations", "hypoxia_2pct_o2_block_allocations",
                        "normoxia_family_matrix", "hypoxia_2pct_o2_family_matrix",
                        "common_family_acquisition_sha256",
                    })
                    if cacq is None:
                        holds.append("HOLD_GATE_C1_MISSING_COMMON_FAMILY_ACQUISITION_RECORD")
                    elif not isinstance(cacq, Mapping) or set(cacq.keys()) != cacq_keys or not is_nonempty_str(cacq.get("producer_acquisition_record_id")):
                        fails.append("FAIL_GATE_C1_COMMON_FAMILY_ACQUISITION_MISMATCH")
                    else:
                        csha = cacq.get("common_family_acquisition_sha256")
                        def _norm_alloc_rows(rows: Any) -> Optional[list[dict[str, Any]]]:
                            if not isinstance(rows, list):
                                return None
                            out_r: list[dict[str, Any]] = []
                            for r_a in rows:
                                if not isinstance(r_a, Mapping) or set(r_a.keys()) != {"block_id", "differentiation_batch_id", "randomized_arm_order"}:
                                    return None
                                if not (is_nonempty_str(r_a.get("block_id")) and is_nonempty_str(r_a.get("differentiation_batch_id")) and isinstance(r_a.get("randomized_arm_order"), list)):
                                    return None
                                out_r.append({
                                    "block_id": str(r_a["block_id"]).strip().upper(),
                                    "differentiation_batch_id": str(r_a["differentiation_batch_id"]).strip().upper(),
                                    "randomized_arm_order": [str(x) for x in r_a["randomized_arm_order"]],
                                })
                            return out_r
                        ca_na = _norm_alloc_rows(cacq.get("normoxia_block_allocations"))
                        ca_ha = _norm_alloc_rows(cacq.get("hypoxia_2pct_o2_block_allocations"))
                        if (
                            not is_valid_sha256_hex(csha)
                            or sha256_bytes(canonical_json_bytes({k: v for k, v in cacq.items() if k != "common_family_acquisition_sha256"})) != str(csha)
                            or cacq.get("shared_study_id") != c1_ev.get("shared_study_id")
                            or cacq.get("locked_analysis_plan_id") != c1_ev.get("locked_analysis_plan_id")
                            or cacq.get("block_randomization_seed_sha256") != c1_ev.get("block_randomization_seed_sha256")
                            or (c1_prereg_ev is not None and cacq.get("preregistration_receipt_sha256") != c1_prereg_ev.get("receipt_sha256"))
                            or (prereg_norm_alloc_clean is not None and ca_na != prereg_norm_alloc_clean)
                            or (prereg_hyp_alloc_clean is not None and ca_ha != prereg_hyp_alloc_clean)
                            or cacq.get("normoxia_family_matrix") != fam_mat["normoxia"]
                            or cacq.get("hypoxia_2pct_o2_family_matrix") != fam_mat["hypoxia_2pct_o2"]
                        ):
                            fails.append("FAIL_GATE_C1_COMMON_FAMILY_ACQUISITION_MISMATCH")
                        else:
                            c1_common_acq_sha_out = str(csha)
                # Composite Intersection-Union Test (IUT) Holm-5 guaranteeing <= 1% FWER on selecting ANY candidate!
                nb_p, nc_p = norm_res[5], norm_res[6]
                hb_p, hc_p = hyp_res[5], hyp_res[6]
                if len(nb_p) == 5 and len(nc_p) == 5 and len(hb_p) == 5 and len(hc_p) == 5 and target in C1_FAMILY_GENES:
                    iut_raw = {g: max(nb_p[g], nc_p[g], hb_p[g], hc_p[g]) for g in C1_FAMILY_GENES}
                    iut_holm = holm_bonferroni_adjust(iut_raw)[target]
                    if iut_holm >= 0.01:
                        fails.append("FAIL_GATE_C1_COMPOSITE_IUT_HOLM5_PVALUE_GE_0P01")

    # Gate C-2: globally unique resting/post-recovery assay record IDs + content-hashed per-lot proliferation receipts!
    c2_extras = frozenset({
        "assay_started_at_utc", "assay_completed_at_utc", "specimen_id",
        "basal_shield_retention_pct", "basal_shield_retention_by_component", "hour0_density_by_lineage",
        "granule_processing_preserved",
        "proinsulin_to_insulin_fold_vs_ctrl", "pcsk1_pct_ctrl", "pcsk2_pct_ctrl", "cpe_pct_ctrl",
        "chgb_pct_ctrl", "scg2_pct_ctrl",
        "soluble_iapp_pg_per_ieq", "soluble_iapp_matched_ctrl_assay",
        "iapp_amyloid_ratio_vs_ctrl", "resting_survival_protein_panel",
        "c2_per_lot_proliferation_records",
        "transient_target_engagement_record",
    })
    c2_ev = _validate_content_receipt(
        rec.get("c2_evidence"),
        expected_stage="C-2", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="exact_product",
        expected_candidate_gene=target, expected_comparator_nt_lot_id=nt_lot_id,
        expected_parent=c1_ev, min_prereq_receipts=[("BANK_MATERIALIZATION", mat_ev), ("DRUG_FREE_EXPOSURE", df_ev)],
        allowed_extra_keys=c2_extras, fails=fails, holds=holds,
        missing_hold="HOLD_GATE_C2_BASAL_SHIELD_GRANULE_MISSING",
        fail_code="FAIL_GATE_C2_BASAL_SHIELD_GRANULE_FAILED",
        mismatch_code="FAIL_GATE_C2_SCOPE_MISMATCH",
    )
    if c2_ev is not None:
        bs = c2_ev.get("basal_shield_retention_pct")
        iapp_pg = c2_ev.get("soluble_iapp_pg_per_ieq")
        iapp_rat = c2_ev.get("iapp_amyloid_ratio_vs_ctrl")
        if not (is_finite_num(bs) and 85.0 <= float(bs) <= 200.0):
            fails.append("FAIL_GATE_C2_BASAL_SHIELD_BELOW_85PCT")
        c2_smap = c2_ev.get("basal_shield_retention_by_component")
        req_c2_comp = SHIELD_COMPONENTS_BY_PRODUCT.get(prod_s, frozenset())
        if not isinstance(c2_smap, Mapping) or set(c2_smap.keys()) != req_c2_comp:
            fails.append("FAIL_GATE_C2_INCOMPLETE_COMPONENT_SHIELD_MAP")
        else:
            c2_comp_vals: list[float] = []
            for cname in sorted(req_c2_comp):
                cv = c2_smap.get(cname)
                if not (is_finite_num(cv) and 85.0 <= float(cv) <= 200.0):
                    fails.append(f"FAIL_GATE_C2_SHIELD_COMPONENT_BELOW_85PCT:{cname}")
                else:
                    c2_comp_vals.append(float(cv))
            if len(c2_comp_vals) == len(req_c2_comp) and is_finite_num(bs) and abs(float(bs) - min(c2_comp_vals)) > 1e-6:
                fails.append("FAIL_GATE_C2_BASAL_SHIELD_SCALAR_MISMATCH_VS_COMPONENTS")
        if spec is not None:
            _validate_lineage_hour0_density(
                spec, c2_ev.get("hour0_density_by_lineage"),
                required_lineages=REQUIRED_HOUR0_LINEAGES_FULL, fails=fails, prefix="GATE_C2",
            )
        pi_fold = c2_ev.get("proinsulin_to_insulin_fold_vs_ctrl")
        pcsk1 = c2_ev.get("pcsk1_pct_ctrl")
        pcsk2 = c2_ev.get("pcsk2_pct_ctrl")
        cpe = c2_ev.get("cpe_pct_ctrl")
        chgb = c2_ev.get("chgb_pct_ctrl")
        scg2 = c2_ev.get("scg2_pct_ctrl")
        if (
            not (is_strict_bool(c2_ev.get("granule_processing_preserved")) and c2_ev["granule_processing_preserved"])
            or not (is_finite_num(pi_fold) and 0.0 < float(pi_fold) <= 1.15)
            or not (is_finite_num(pcsk1) and 85.0 <= float(pcsk1) <= 200.0)
            or not (is_finite_num(pcsk2) and 85.0 <= float(pcsk2) <= 200.0)
            or not (is_finite_num(cpe) and 85.0 <= float(cpe) <= 200.0)
            or not (is_finite_num(chgb) and 85.0 <= float(chgb) <= 200.0)
            or not (is_finite_num(scg2) and 85.0 <= float(scg2) <= 200.0)
        ):
            fails.append("FAIL_GATE_C2_GRANULE_PROCESSING_DEGRADED")
        if not (is_finite_num(iapp_pg) and float(iapp_pg) >= 0.0):
            fails.append("FAIL_GATE_C2_SOLUBLE_IAPP_MEASUREMENT_MISSING")
        # Draft C §5 matched-control soluble/oligomeric IAPP early screening bound (<= 1.25x matched NT control),
        # kept distinct from iapp_amyloid_ratio_vs_ctrl (<= 1.15x early amyloid aggregation signal)!
        sol_iapp_rec = c2_ev.get("soluble_iapp_matched_ctrl_assay")
        sol_iapp_keys = frozenset({
            "assay_species", "assay_record_id", "specimen_id", "specimen_lot_id",
            "comparator_nt_lot_id", "treated_soluble_iapp_pg_per_ieq",
            "matched_ctrl_soluble_iapp_pg_per_ieq", "soluble_iapp_ratio_vs_ctrl",
            "assay_receipt_sha256",
        })
        if sol_iapp_rec is None:
            holds.append("HOLD_GATE_C2_MISSING_SOLUBLE_IAPP_MATCHED_CONTROL_ASSAY")
        elif not isinstance(sol_iapp_rec, Mapping) or set(sol_iapp_rec.keys()) != sol_iapp_keys:
            fails.append("FAIL_GATE_C2_SOLUBLE_IAPP_MATCHED_CONTROL_MISMATCH")
        else:
            si_sha = sol_iapp_rec.get("assay_receipt_sha256")
            c2_sp_si = str(c2_ev.get("specimen_id")).strip().upper() if is_nonempty_str(c2_ev.get("specimen_id")) else None
            tr_si = sol_iapp_rec.get("treated_soluble_iapp_pg_per_ieq")
            ct_si = sol_iapp_rec.get("matched_ctrl_soluble_iapp_pg_per_ieq")
            rt_si = sol_iapp_rec.get("soluble_iapp_ratio_vs_ctrl")
            if (
                not is_valid_sha256_hex(si_sha)
                or sha256_bytes(canonical_json_bytes({k: v for k, v in sol_iapp_rec.items() if k != "assay_receipt_sha256"})) != str(si_sha)
                or sol_iapp_rec.get("assay_species") != "SOLUBLE_OLIGOMERIC_IAPP_ELISA_MATCHED_CTRL"
                or not all(is_nonempty_str(sol_iapp_rec.get(k)) for k in ("assay_record_id", "specimen_id", "specimen_lot_id", "comparator_nt_lot_id"))
                or (c2_sp_si is not None and str(sol_iapp_rec["specimen_id"]).strip().upper() != c2_sp_si)
                or (lot_s and str(sol_iapp_rec["specimen_lot_id"]).strip().upper() != lot_s.upper())
                or (is_nonempty_str(nt_lot_id) and str(sol_iapp_rec["comparator_nt_lot_id"]).strip().upper() != str(nt_lot_id).strip().upper())
                or not (is_finite_num(tr_si) and float(tr_si) >= 0.0 and is_finite_num(ct_si) and float(ct_si) > 0.0 and is_finite_num(rt_si))
                or (is_finite_num(iapp_pg) and abs(float(tr_si) - float(iapp_pg)) > 1e-6)
                or abs((float(tr_si) / float(ct_si)) - float(rt_si)) > 1e-4
            ):
                fails.append("FAIL_GATE_C2_SOLUBLE_IAPP_MATCHED_CONTROL_MISMATCH")
            elif (float(tr_si) / float(ct_si)) > 1.25:
                fails.append("FAIL_GATE_C2_SOLUBLE_IAPP_RATIO_EXCEEDS_1P25")
        if not (is_finite_num(iapp_rat) and 0.0 < float(iapp_rat) <= 1.15):
            fails.append("FAIL_GATE_C2_IAPP_AMYLOID_RATIO_EXCEEDS_1P15")
        # Independent resting survival protein panel (Draft C §5: BCL2L1, MCL1, CD59 >= 80% matched NT control)!
        surv_panel = c2_ev.get("resting_survival_protein_panel")
        surv_panel_keys = frozenset({
            "specimen_id", "specimen_lot_id", "comparator_nt_lot_id", "assay_record_id",
            "bcl2l1_pct_ctrl", "mcl1_pct_ctrl", "cd59_pct_ctrl", "panel_receipt_sha256",
        })
        if surv_panel is None:
            holds.append("HOLD_GATE_C2_MISSING_RESTING_SURVIVAL_PROTEIN_PANEL")
        elif not isinstance(surv_panel, Mapping) or set(surv_panel.keys()) != surv_panel_keys:
            fails.append("FAIL_GATE_C2_RESTING_SURVIVAL_PROTEIN_PANEL_MISMATCH")
        else:
            sp_sha = surv_panel.get("panel_receipt_sha256")
            c2_sp_s = str(c2_ev.get("specimen_id")).strip().upper() if is_nonempty_str(c2_ev.get("specimen_id")) else None
            if (
                not is_valid_sha256_hex(sp_sha)
                or sha256_bytes(canonical_json_bytes({k: v for k, v in surv_panel.items() if k != "panel_receipt_sha256"})) != str(sp_sha)
                or not all(is_nonempty_str(surv_panel.get(k)) for k in ("specimen_id", "specimen_lot_id", "comparator_nt_lot_id", "assay_record_id"))
                or (c2_sp_s is not None and str(surv_panel["specimen_id"]).strip().upper() != c2_sp_s)
                or (lot_s and str(surv_panel["specimen_lot_id"]).strip().upper() != lot_s.upper())
                or (is_nonempty_str(nt_lot_id) and str(surv_panel["comparator_nt_lot_id"]).strip().upper() != str(nt_lot_id).strip().upper())
            ):
                fails.append("FAIL_GATE_C2_RESTING_SURVIVAL_PROTEIN_PANEL_MISMATCH")
            elif not all(
                is_finite_num(surv_panel.get(k)) and 80.0 <= float(surv_panel[k]) <= 200.0
                for k in ("bcl2l1_pct_ctrl", "mcl1_pct_ctrl", "cd59_pct_ctrl")
            ):
                fails.append("FAIL_GATE_C2_RESTING_SURVIVAL_PROTEINS_BELOW_80PCT")
        prolif_lots = c2_ev.get("c2_per_lot_proliferation_records")
        if not isinstance(prolif_lots, list) or len(prolif_lots) < 3:
            fails.append("FAIL_GATE_C2_REQUIRES_AT_LEAST_3_PER_LOT_PROLIFERATION_RECORDS")
        else:
            seen_pl: set[str] = set()
            seen_pl_nt: set[str] = set()
            seen_pl_samples: set[str] = set()
            seen_all_assay_ids: set[str] = set()
            pl_allowed = frozenset({
                "lot_id", "product_id", "candidate_gene", "comparator_nt_lot_id",
                "treated_sample_id", "matched_control_sample_id",
                "lot_record_sha256", "resting_assay_record_id", "post_recovery_assay_record_id",
                "resting_ki67_fold_vs_ctrl", "resting_edu_fold_vs_ctrl",
                "post_recovery_ki67_fold_vs_ctrl", "post_recovery_edu_fold_vs_ctrl",
                "ki67_edu_referred",
            })
            for idx, lrec in enumerate(prolif_lots):
                if not isinstance(lrec, Mapping):
                    fails.append(f"FAIL_GATE_C2_PROLIF_LOT_MALFORMED:{idx}"); continue
                _check_allowed_keys(lrec, pl_allowed, fails, f"GATE_C2_PROLIF_{idx}")
                if not is_nonempty_str(lrec.get("lot_id")):
                    fails.append("FAIL_GATE_C2_PROLIF_DUPLICATE_OR_EMPTY_LOT_ID"); continue
                lid = str(lrec["lot_id"]).strip()
                lid_n = lid.upper()
                if lid_n in seen_pl:
                    fails.append("FAIL_GATE_C2_PROLIF_DUPLICATE_OR_EMPTY_LOT_ID"); continue
                seen_pl.add(lid_n)
                l_prod = str(lrec.get("product_id", "")).strip()
                l_gene = str(lrec.get("candidate_gene", "")).strip().upper()
                l_nt = lrec.get("comparator_nt_lot_id")
                if l_prod != prod_s or l_gene != target:
                    fails.append(f"FAIL_GATE_C2_PROLIF_LOT_CANDIDATE_OR_PRODUCT_MISMATCH:{lid}")
                if not is_nonempty_str(l_nt):
                    fails.append(f"FAIL_GATE_C2_PROLIF_LOT_COMPARATOR_MISMATCH:{lid}")
                else:
                    l_nt_s = str(l_nt).strip()
                    l_nt_n = l_nt_s.upper()
                    if l_nt_n == lid_n or l_nt_n in seen_pl_nt or (lid_n == lot_s.upper() and l_nt_s != nt_lot_id):
                        fails.append(f"FAIL_GATE_C2_PROLIF_LOT_COMPARATOR_MISMATCH:{lid}")
                    seen_pl_nt.add(l_nt_n)
                tsid = lrec.get("treated_sample_id")
                csid = lrec.get("matched_control_sample_id")
                if not (is_nonempty_str(tsid) and is_nonempty_str(csid)):
                    fails.append(f"FAIL_GATE_C2_PROLIF_SAMPLE_IDS_INVALID:{lid}")
                else:
                    tsn, csn = str(tsid).strip().upper(), str(csid).strip().upper()
                    if tsn == csn or tsn in seen_pl_samples or csn in seen_pl_samples:
                        fails.append(f"FAIL_GATE_C2_PROLIF_SAMPLE_IDS_INVALID:{lid}")
                    seen_pl_samples.add(tsn); seen_pl_samples.add(csn)
                lsha = lrec.get("lot_record_sha256")
                if not is_valid_sha256_hex(lsha) or sha256_bytes(canonical_json_bytes({k: v for k, v in lrec.items() if k != "lot_record_sha256"})) != lsha:
                    fails.append(f"FAIL_GATE_C2_PROLIF_LOT_RECORD_HASH_INVALID:{lid}")
                rid = lrec.get("resting_assay_record_id")
                pid = lrec.get("post_recovery_assay_record_id")
                if not (is_nonempty_str(rid) and is_nonempty_str(pid)):
                    fails.append(f"FAIL_GATE_C2_PROLIF_ASSAY_RECORDS_MISSING_OR_IDENTICAL:{lid}")
                else:
                    rn, pn = str(rid).strip().upper(), str(pid).strip().upper()
                    if rn == pn or rn in seen_all_assay_ids or pn in seen_all_assay_ids:
                        fails.append(f"FAIL_GATE_C2_PROLIF_ASSAY_RECORDS_MISSING_OR_IDENTICAL:{lid}")
                    seen_all_assay_ids.add(rn); seen_all_assay_ids.add(pn)
                rk = lrec.get("resting_ki67_fold_vs_ctrl")
                re_ = lrec.get("resting_edu_fold_vs_ctrl")
                pk = lrec.get("post_recovery_ki67_fold_vs_ctrl")
                pe = lrec.get("post_recovery_edu_fold_vs_ctrl")
                if not all(is_finite_num(x) and float(x) > 0.0 for x in (rk, re_, pk, pe)):
                    fails.append(f"FAIL_GATE_C2_MISSING_PER_LOT_PROLIFERATION:{lid}")
                elif max(float(rk), float(re_), float(pk), float(pe)) > 1.0:
                    if not (is_strict_bool(lrec.get("ki67_edu_referred")) and lrec["ki67_edu_referred"]):
                        fails.append(f"FAIL_GATE_C2_UNREFERRED_PROLIFERATION_ELEVATION:{lid}")
                    else:
                        holds.append(f"HOLD_GATE_C2_PROLIFERATION_ELEVATION_REFERRED:{lid}")
            if not seen_pl.isdisjoint(seen_pl_nt):
                fails.append("FAIL_GATE_C2_PROLIF_LOT_TREATED_COMPARATOR_OVERLAP")
            if lot_s and lot_s.upper() not in seen_pl:
                fails.append("FAIL_GATE_C2_ACTIVE_LOT_MISSING_FROM_PROLIFERATION_RECORDS")

    c3_prereqs: list[tuple[str, Optional[Mapping[str, Any]]]] = [
        ("BANK_MATERIALIZATION", mat_ev), ("DRUG_FREE_EXPOSURE", df_ev),
        ("NATIVE_SAFETY_SWITCH", sw_ev), ("GATE-0V-KILL", g0v_ev),
    ]
    if g31_ev is not None:
        c3_prereqs.append(("GATE-31", g31_ev))
    c3_nk = _validate_content_receipt(
        rec.get("c3_nk_evidence"),
        expected_stage="C-3-NK", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="exact_product",
        expected_candidate_gene=target, expected_comparator_nt_lot_id=nt_lot_id,
        expected_parent=c2_ev, min_prereq_receipts=c3_prereqs,
        allowed_extra_keys=frozenset({"assay_started_at_utc", "assay_completed_at_utc", "specimen_id", "readout3b_evidence", "transient_target_engagement_record"}), fails=fails, holds=holds,
        missing_hold="HOLD_GATE_C3_NK_MISSING",
        fail_code="FAIL_GATE_C3_NK_FAILED",
        mismatch_code="FAIL_GATE_C3_NK_SCOPE_MISMATCH",
    )
    if c3_nk is not None:
        _validate_readout3b_nk(
            c3_nk.get("readout3b_evidence"), fails=fails, holds=holds, prefix="GATE_C3_NK",
            require_sirpa_low=True,
            require_hla_e_spr=bool(spec["hla_e_engineered"]) if spec is not None else True,
            expected_specimen_id=str(c3_nk.get("specimen_id")).strip() if is_nonempty_str(c3_nk.get("specimen_id")) else None,
            expected_lot_id=lot_s or None,
            expected_cohort_id=c1_cohort_id,
        )

    c3_gsis = _validate_content_receipt(
        rec.get("c3_gsis_evidence"),
        expected_stage="C-3-GSIS", expected_prod=prod_s, expected_bank=bank_s,
        expected_lot=lot_s, expected_route=route_s, expected_scope="exact_product",
        expected_candidate_gene=target, expected_comparator_nt_lot_id=nt_lot_id,
        expected_parent=c3_nk, min_prereq_receipts=c3_prereqs,
        allowed_extra_keys=frozenset({"assay_started_at_utc", "assay_completed_at_utc", "specimen_id", "readout2_evidence", "transient_target_engagement_record"}), fails=fails, holds=holds,
        missing_hold="HOLD_GATE_C3_GSIS_MISSING",
        fail_code="FAIL_GATE_C3_GSIS_FAILED",
        mismatch_code="FAIL_GATE_C3_GSIS_SCOPE_MISMATCH",
    )
    if c2_ev is not None:
        t_c2 = parse_utc_iso_ts(c2_ev.get("recorded_at_utc"))
        c2_sha = c2_ev.get("receipt_sha256")
        for sw_lbl, sw_rec in (("NATIVE_SAFETY_SWITCH", sw_ev), ("GATE-0V-KILL", g0v_ev)):
            if sw_rec is not None:
                t_swr = parse_utc_iso_ts(sw_rec.get("recorded_at_utc"))
                if t_c2 is not None and t_swr is not None and t_swr < t_c2:
                    fails.append(f"FAIL_GATE42_CHRONOLOGY_{sw_lbl}_PREDATES_C2")
                # Cryptographic C-2 prerequisite digest pin inside BOTH safety switch receipts!
                sw_pr = sw_rec.get("prerequisite_receipt_sha256s")
                if not isinstance(sw_pr, Mapping) or sw_pr.get("C-2") != c2_sha:
                    fails.append(f"FAIL_GATE42_MISSING_C2_PREREQ_DIGEST_IN_{sw_lbl}")
    if c3_gsis is not None:
        _gs_eng_m = c3_gsis.get("transient_target_engagement_record")
        _gs_meas_s = parse_utc_iso_ts(_gs_eng_m.get("start_measured_at_utc")) if isinstance(_gs_eng_m, Mapping) else None
        _gs_meas_e = parse_utc_iso_ts(_gs_eng_m.get("end_measured_at_utc")) if isinstance(_gs_eng_m, Mapping) else None
        _gs_acq_s = parse_utc_iso_ts(c3_gsis.get("assay_started_at_utc"))
        _gs_acq_e = parse_utc_iso_ts(c3_gsis.get("assay_completed_at_utc"))
        _gs_eff_s = max([t for t in (_gs_meas_s, _gs_acq_s) if t is not None], default=None)
        _gs_eff_e = min([t for t in (_gs_meas_e, _gs_acq_e) if t is not None], default=None)
        _validate_readout2_gsis(
            c3_gsis.get("readout2_evidence"), fails=fails, holds=holds, prefix="GATE_C3_GSIS",
            expected_comparator_id=nt_lot_id or sentinel_nt, min_comparator_output_ratio=0.90,
            parent_recorded_at_utc=parse_utc_iso_ts(c3_gsis.get("recorded_at_utc")),
            min_exposure_start_utc=parse_utc_iso_ts(c2_ev.get("recorded_at_utc")) if c2_ev is not None else None,
            expected_prod=prod_s, expected_bank=bank_s, expected_lot=lot_s, expected_route=route_s,
            expected_specimen_id=str(c3_gsis.get("specimen_id")).strip() if is_nonempty_str(c3_gsis.get("specimen_id")) else None,
            expected_cohort_id=c1_cohort_id,
            expected_candidate_gene=target if target in C1_FAMILY_GENES else None,
            expected_engagement_window_utc=(_gs_eff_s, _gs_eff_e),
        )
    # Bind producer-acquired (assay_started_at_utc, assay_completed_at_utc, specimen_id)
    # on EVERY downstream assay, enforce strict inter-stage acquisition chronology, AND verify active transient knockdown
    # spans the ENTIRE [assay_started_at_utc, assay_completed_at_utc] measurement window on the exact specimen!
    t_c1_acq_ts = parse_utc_iso_ts(c1_ev.get("assay_acquired_at_utc")) if c1_ev is not None else None
    t_c1_rec_ts = parse_utc_iso_ts(c1_ev.get("recorded_at_utc")) if c1_ev is not None else None
    t_r2_harv_ts = None
    if c3_gsis is not None and isinstance(c3_gsis.get("readout2_evidence"), Mapping) and isinstance(c3_gsis["readout2_evidence"].get("dual_clocks_utc"), Mapping):
        t_r2_harv_ts = parse_utc_iso_ts(c3_gsis["readout2_evidence"]["dual_clocks_utc"].get("assay_harvest_utc"))

    stage_acq: dict[str, tuple[Optional[datetime], Optional[datetime], Optional[str]]] = {}
    sw_cov_ts: dict[str, list[datetime]] = {}
    for _st_tag, _st_rec in (
        ("C-2", c2_ev), ("NATIVE_SAFETY_SWITCH", sw_ev), ("GATE-0V-KILL", g0v_ev),
        ("C-3-NK", c3_nk), ("C-3-GSIS", c3_gsis),
    ):
        if _st_rec is None:
            stage_acq[_st_tag] = (None, None, None)
            continue
        _t_st = parse_utc_iso_ts(_st_rec.get("assay_started_at_utc"))
        _t_en = parse_utc_iso_ts(_st_rec.get("assay_completed_at_utc"))
        _t_rc = parse_utc_iso_ts(_st_rec.get("recorded_at_utc"))
        _sp_id = _st_rec.get("specimen_id")
        if _t_st is None or _t_en is None or not is_nonempty_str(_sp_id):
            holds.append(f"HOLD_GATE_C_MISSING_ASSAY_ACQUISITION_WINDOW_OR_SPECIMEN:{_st_tag}")
            stage_acq[_st_tag] = (None, None, None)
        elif _t_st > _t_en or (_t_rc is not None and _t_en > _t_rc):
            fails.append(f"FAIL_GATE_C_INVALID_ASSAY_ACQUISITION_WINDOW:{_st_tag}")
            stage_acq[_st_tag] = (_t_st, _t_en, str(_sp_id).strip())
        else:
            stage_acq[_st_tag] = (_t_st, _t_en, str(_sp_id).strip())
            if _st_tag in ("NATIVE_SAFETY_SWITCH", "GATE-0V-KILL"):
                _t_24 = parse_utc_iso_ts(_st_rec.get("assay_24h_collection_utc"))
                _t_72 = parse_utc_iso_ts(_st_rec.get("assay_72h_collection_utc"))
                if _t_24 is None or _t_72 is None:
                    holds.append(f"HOLD_GATE_C_MISSING_ASSAY_ACQUISITION_WINDOW_OR_SPECIMEN:{_st_tag}")
                else:
                    h24 = (_t_24 - _t_st).total_seconds() / 3600.0
                    h72 = (_t_72 - _t_st).total_seconds() / 3600.0
                    span_h = (_t_en - _t_st).total_seconds() / 3600.0
                    if not (23.0 <= h24 <= 25.0 and 71.0 <= h72 <= 73.5 and _t_72 <= _t_en and span_h >= 72.0 - 1e-6):
                        fails.append(f"FAIL_GATE_C_SAFETY_SWITCH_24H_72H_ENDPOINT_TIMING_INVALID:{_st_tag}")
                    sw_cov_ts[_st_tag] = [_t_st, _t_24, _t_72, _t_en]

    # True physical acquisition chronology: C-1 <= C-2 <= {SWITCH, GATE-0V} <= C-3-NK <= C-3-GSIS (with R2 harvest inside C-3-GSIS window)!
    t_c2_st, t_c2_en, sp_c2 = stage_acq["C-2"]
    t_sw_st, t_sw_en, sp_sw = stage_acq["NATIVE_SAFETY_SWITCH"]
    t_gv_st, t_gv_en, sp_gv = stage_acq["GATE-0V-KILL"]
    t_nk_st, t_nk_en, sp_nk = stage_acq["C-3-NK"]
    t_gs_st, t_gs_en, sp_gs = stage_acq["C-3-GSIS"]
    for _p_lbl, _p_ts, _c_lbl, _c_ts in (
        ("C-1", t_c1_acq_ts, "C-2", t_c2_st),
        ("C-2", t_c2_en, "NATIVE_SAFETY_SWITCH", t_sw_st),
        ("C-2", t_c2_en, "GATE-0V-KILL", t_gv_st),
        ("NATIVE_SAFETY_SWITCH", t_sw_en, "C-3-NK", t_nk_st),
        ("GATE-0V-KILL", t_gv_en, "C-3-NK", t_nk_st),
        ("C-3-NK", t_nk_en, "C-3-GSIS", t_gs_st),
    ):
        if _p_ts is not None and _c_ts is not None and _c_ts < _p_ts:
            fails.append(f"FAIL_GATE_C_ACQUISITION_CHRONOLOGY_VIOLATION:{_p_lbl}_AFTER_{_c_lbl}")
    if t_r2_harv_ts is not None and t_gs_st is not None and t_gs_en is not None:
        if not (t_gs_st <= t_r2_harv_ts <= t_gs_en):
            fails.append("FAIL_GATE_C_C3_GSIS_READOUT2_HARVEST_OUTSIDE_ASSAY_WINDOW")

    t_c2_rec_ts = parse_utc_iso_ts(c2_ev.get("recorded_at_utc")) if c2_ev is not None else None
    t_c3nk_rec_ts = parse_utc_iso_ts(c3_nk.get("recorded_at_utc")) if c3_nk is not None else None
    t_safety_max_end = max([t for t in (t_sw_en, t_gv_en) if t is not None], default=t_c2_rec_ts)
    for _st_tag, _st_rec, _min_ts, _req_st_ts, _req_end_ts, _exp_sp in (
        ("C-2", c2_ev, t_c1_rec_ts, t_c2_st, t_c2_en, sp_c2),
        ("NATIVE_SAFETY_SWITCH", sw_ev, t_c2_rec_ts, t_sw_st, t_sw_en, sp_sw),
        ("GATE-0V-KILL", g0v_ev, t_c2_rec_ts, t_gv_st, t_gv_en, sp_gv),
        ("C-3-NK", c3_nk, t_safety_max_end, t_nk_st, t_nk_en, sp_nk),
        ("C-3-GSIS", c3_gsis, t_c3nk_rec_ts, t_gs_st, max([t for t in (t_gs_en, t_r2_harv_ts) if t is not None], default=None), sp_gs),
    ):
        _is_sw_st = _st_tag in ("NATIVE_SAFETY_SWITCH", "GATE-0V-KILL")
        _cov_list = sw_cov_ts.get(_st_tag, [])
        _eff_req_end = max([t for t in (_req_end_ts, *_cov_list) if t is not None], default=None)
        _validate_transient_engagement_record(
            _st_rec, target_gene=target, expected_cohort_id=c1_cohort_id,
            expected_lot_id=lot_s, expected_specimen_id=_exp_sp,
            min_stage_ts=_min_ts, required_start_ts=_req_st_ts, required_end_ts=_eff_req_end,
            stage_tag=_st_tag, fails=fails, holds=holds,
            require_longitudinal_mode=_is_sw_st,
            required_covering_ts=_cov_list,
        )

    _pilot_downstream_missing_holds = frozenset({
        "HOLD_GATE_C2_BASAL_SHIELD_GRANULE_MISSING",
        "HOLD_GATE_C3_NK_MISSING",
        "HOLD_GATE_C3_GSIS_MISSING",
        "HOLD_NATIVE_SAFETY_SWITCH_EVIDENCE_MISSING",
        "HOLD_GATE0V_KILL_EVIDENCE_MISSING",
    })
    if fails:
        verdict = "FAIL"
    elif is_pilot_only and all(h in _pilot_downstream_missing_holds for h in holds):
        verdict = "DESCRIPTIVE_PILOT_ONLY_NON_ADVANCING"
    elif holds:
        verdict = "HOLD"
    elif is_design_a:
        verdict = "DIAGNOSTIC_SENSITIVITY_ONLY_DESIGN_A_NON_ADVANCING"
    else:
        verdict = OFFLINE_VERDICT_PRIMARY

    return {
        "gate": "GATE-42", "verdict": verdict,
        "release_authorizing": False, "live_ledger_authenticated": False,
        "upstream_archive_verification": OFFLINE_ARCHIVE_NOTE,
        "product_id": rec.get("product_id"),
        "required_switch": spec["required_switch"] if spec else None,
        "zero_fasta_minted": rec.get("zero_fasta_minted"),
        "c1_preregistration_sha256": c1_prereg_ev.get("receipt_sha256") if c1_prereg_ev is not None else None,
        "c1_common_family_acquisition_sha256": c1_common_acq_sha_out if c1_ev is not None else None,
        "failures": fails, "holds": holds,
    }


# ---------------------------------------------------------------------------
# GATE-43 (IIP-0065 / DEC-146 / GY-037): Revocable WARN Guardrails & Pilots
# ---------------------------------------------------------------------------

D2_EVAL_KEYS: FrozenSet[str] = frozenset({
    "check_d2_challenger_gene", "check_d2_product_id", "check_d2_bank_id", "check_d2_per_lot_records",
})
D3A_EVAL_KEYS: FrozenSet[str] = frozenset({"check_d3a_per_lot_records"})
D3B_EVAL_KEYS: FrozenSet[str] = frozenset({
    "d3b_assay_scope", "target_arm", "product_id", "bank_id", "lot_id", "route_id",
    "materialization_evidence", "native_switch_evidence", "gate0v_evidence", "gate31_evidence",
    "d3b_pilot_receipt",
})
GATE43_ALLOWED_KEYS: FrozenSet[str] = frozenset({
    "evidence_tier", "live_odds_delta_pp", "prospective_odds_delta_pp", "graveyard_severity",
    "check_d1_claims_adoption_authority", "check_d1_arm_a_washes", "check_d1_arm_b_washes",
    "check_d1_starting_zm_regimen", "check_d1_zm447439_lloq_uM",
    "check_d1_arm_a_zm447439_lcms_uM", "check_d1_arm_b_zm447439_lcms_uM",
    "check_d1_arm_a_spike_recovery_pct", "check_d1_arm_b_spike_recovery_pct",
    "check_d1_both_arms_matched_24h_nac", "check_d1_t3_lloq_nM",
    "check_d1_residual_t3_arm_a_nM", "check_d1_residual_t3_arm_b_nM", "check_d1_arm_b_below_lloq",
    "check_d1_pre_coassembly_vascular_function_pass",
    "check_d1_paired_gsis_40_100mmhg_recorded", "check_d1_paired_icam1_vcam1_facs_recorded",
    "check_d1_paired_gsis_record", "check_d1_paired_facs_record", "check_d1_vascular_adhesion_sprouting_record",
    "check_d1_paired_assay_receipt",
    "check_d2_status", "check_d3_c3_explicitly_untested", "check_d3a_status", "check_d3b_status",
}) | D2_EVAL_KEYS | D3A_EVAL_KEYS | D3B_EVAL_KEYS


def evaluate_gate43_cellgemma_guardrails_and_pilots(rec: Mapping[str, Any]) -> dict[str, Any]:
    """GATE-43 (IIP-0065): Hardened revocable WARN guardrails with exact verbatim statuses, independent content-hashed D-2/D-3(a), & internal-scope D-3(b)."""
    fails: list[str] = []
    holds: list[str] = []
    _check_allowed_keys(rec, GATE43_ALLOWED_KEYS, fails, "GATE43")

    if rec.get("evidence_tier") != "cellgemma_e4b_in_silico_prior":
        fails.append("FAIL_EPISTEMIC_TIER_MUST_BE_CELLGEMMA_IN_SILICO_PRIOR")
    if not (is_finite_num(rec.get("live_odds_delta_pp")) and float(rec["live_odds_delta_pp"]) == 0.0):
        fails.append("FAIL_DRAFT_D_NONZERO_LIVE_ODDS")
    if not (is_finite_num(rec.get("prospective_odds_delta_pp")) and float(rec["prospective_odds_delta_pp"]) == 0.0):
        fails.append("FAIL_DRAFT_D_NONZERO_PROSPECTIVE_ODDS")
    if rec.get("graveyard_severity") != "WARN":
        fails.append("FAIL_GY037_MUST_USE_REVOCABLE_WARN_SEVERITY")

    adopt = rec.get("check_d1_claims_adoption_authority")
    if not is_strict_bool(adopt) or adopt is not False:
        fails.append("FAIL_CHECK_D1_ZERO_ADOPTION_AUTHORITY_VIOLATED_OR_MISSING")

    # Check D-1
    wa = rec.get("check_d1_arm_a_washes")
    wb = rec.get("check_d1_arm_b_washes")
    zm_lloq = rec.get("check_d1_zm447439_lloq_uM")
    zm_a = rec.get("check_d1_arm_a_zm447439_lcms_uM")
    zm_b = rec.get("check_d1_arm_b_zm447439_lcms_uM")
    sp_a = rec.get("check_d1_arm_a_spike_recovery_pct")
    sp_b = rec.get("check_d1_arm_b_spike_recovery_pct")
    zm_regimen = rec.get("check_d1_starting_zm_regimen")
    t3_lloq = rec.get("check_d1_t3_lloq_nM")
    t3_a = rec.get("check_d1_residual_t3_arm_a_nM")
    has_t3_b = "check_d1_residual_t3_arm_b_nM" in rec
    t3_b = rec.get("check_d1_residual_t3_arm_b_nM")
    arm_b_bloq = rec.get("check_d1_arm_b_below_lloq")

    if not (is_strict_int(wa) and is_strict_int(wb) and int(wa) >= 3 and int(wa) == int(wb)):
        fails.append("FAIL_CHECK_D1_ARM_WASHES_MUST_BE_IDENTICAL_INT_GE_3")
    if zm_regimen not in ("S7W0_ONLY_0UM_POST_SORT", "CONTINUOUS_0P5UM_BALBOA_S7"):
        fails.append("FAIL_CHECK_D1_UNDECLARED_ZM447439_REGIMEN")
    if not (is_finite_num(zm_lloq) and 0.0 < float(zm_lloq) <= 0.005):
        fails.append("FAIL_CHECK_D1_ZM447439_LLOQ_EXCEEDS_0P005UM")
    elif not (is_finite_num(zm_a) and is_finite_num(zm_b) and 0.0 <= float(zm_a) <= float(zm_lloq) and 0.0 <= float(zm_b) <= float(zm_lloq)):
        fails.append("FAIL_CHECK_D1_ZM447439_ABOVE_LLOQ_OR_0P005UM")
    if not (is_finite_num(sp_a) and is_finite_num(sp_b) and 80.0 <= float(sp_a) <= 120.0 and 80.0 <= float(sp_b) <= 120.0):
        fails.append("FAIL_CHECK_D1_SPIKE_RECOVERY_OUT_OF_80_120")
    if not (is_strict_bool(rec.get("check_d1_both_arms_matched_24h_nac")) and rec["check_d1_both_arms_matched_24h_nac"]):
        fails.append("FAIL_CHECK_D1_UNMATCHED_HANDLING_ARMS")
    if not (is_finite_num(t3_lloq) and float(t3_lloq) > 0.0 and is_finite_num(t3_a) and is_strict_bool(arm_b_bloq)):
        fails.append("FAIL_CHECK_D1_MISSING_T3_QUANTIFICATION_OR_CENSORING_FLAG")
    elif float(t3_a) < 7.0 or float(t3_a) > 13.0 or float(t3_a) < float(t3_lloq):
        fails.append("FAIL_CHECK_D1_RETAINED_ARM_T3_OUTSIDE_7_13NM_WINDOW")
    elif float(t3_lloq) > min(0.5, 0.05 * float(t3_a)):
        fails.append("FAIL_CHECK_D1_T3_LLOQ_INSUFFICIENT_TO_RESOLVE_RESIDUAL_LIMIT")
    else:
        if arm_b_bloq is True:
            if not has_t3_b:
                fails.append("FAIL_CHECK_D1_OMITTED_T3_ARM_B_KEY_MUST_BE_EXPLICIT_NULL")
            elif t3_b is not None:
                fails.append("FAIL_CHECK_D1_BLOQ_MUST_USE_NULL_CONCENTRATION_NOT_NUMERIC")
            else:
                if float(t3_lloq) > min(0.10 * float(t3_a), 1.0):
                    holds.append("HOLD_CHECK_D1_T3_EXPOSURE_NOT_SEPARATED")
        else:
            if not has_t3_b or not is_finite_num(t3_b) or float(t3_b) < float(t3_lloq):
                fails.append("FAIL_CHECK_D1_NON_BLOQ_CONCENTRATION_MISSING_OR_BELOW_LLOQ")
            elif float(t3_b) > min(0.10 * float(t3_a), 1.0):
                holds.append("HOLD_CHECK_D1_T3_EXPOSURE_NOT_SEPARATED")

    vasc_ok = rec.get("check_d1_pre_coassembly_vascular_function_pass")
    if vasc_ok is False:
        fails.append("FAIL_CHECK_D1_PRE_COASSEMBLY_VASCULAR_FUNCTION_FAILED")
    elif vasc_ok is not True:
        holds.append("HOLD_CHECK_D1_PRE_COASSEMBLY_VASCULAR_FUNCTION_UNVERIFIED")
    if not (is_strict_bool(rec.get("check_d1_paired_gsis_40_100mmhg_recorded")) and rec["check_d1_paired_gsis_40_100mmhg_recorded"]):
        holds.append("HOLD_CHECK_D1_PAIRED_GSIS_NOT_RECORDED")
    if not (is_strict_bool(rec.get("check_d1_paired_icam1_vcam1_facs_recorded")) and rec["check_d1_paired_icam1_vcam1_facs_recorded"]):
        holds.append("HOLD_CHECK_D1_PAIRED_ICAM1_VCAM1_FACS_NOT_RECORDED")
    # Typed, content-hashed D-1 paired descriptive records (GSIS, FACS, adhesion/sprouting) with specimen/plate provenance!
    d1_ep_shas: dict[str, str] = {}
    d1_ep_id_keys = {"lot_id", "plate_id", "sibling_aliquot_pair_id", "arm_a_acquired_at_utc", "arm_b_acquired_at_utc"}
    d1_ep_meta: dict[str, tuple[str, str, str]] = {}
    d1_ep_times: dict[str, tuple[datetime, datetime]] = {}
    d1_gsis_abs_keys = {
        "arm_a_basal_40", "arm_a_stim_40", "arm_b_basal_40", "arm_b_stim_40",
        "arm_a_basal_100", "arm_a_stim_100", "arm_b_basal_100", "arm_b_stim_100",
    }
    for d1_key, d1_num_keys, d1_extra_str_keys, d1_code in (
        (
            "check_d1_paired_gsis_record",
            {"arm_a_si_40", "arm_b_si_40", "arm_a_si_100", "arm_b_si_100"} | d1_gsis_abs_keys,
            {"insulin_normalization_basis", "raw_trace_sha256"},
            "HOLD_CHECK_D1_MISSING_TYPED_GSIS_RECORD",
        ),
        ("check_d1_paired_facs_record", {"icam1_mfi_ratio_b_over_a", "vcam1_mfi_ratio_b_over_a"}, set(), "HOLD_CHECK_D1_MISSING_TYPED_FACS_RECORD"),
        ("check_d1_vascular_adhesion_sprouting_record", {"neutrophil_adhesion_ratio_b_over_a", "iec_sprouting_pct_ctrl"}, set(), "HOLD_CHECK_D1_MISSING_TYPED_VASCULAR_RECORD"),
    ):
        d1_req_keys = d1_num_keys | d1_ep_id_keys | d1_extra_str_keys | {"record_sha256"}
        d1_obj = rec.get(d1_key)
        if not isinstance(d1_obj, Mapping) or set(d1_obj.keys()) != d1_req_keys:
            holds.append(d1_code)
        else:
            rsha_d1 = d1_obj.get("record_sha256")
            num_d1 = [d1_obj[k] for k in d1_num_keys]
            t_ep_a = parse_utc_iso_ts(d1_obj.get("arm_a_acquired_at_utc"))
            t_ep_b = parse_utc_iso_ts(d1_obj.get("arm_b_acquired_at_utc"))
            gsis_extra_ok = True
            if d1_key == "check_d1_paired_gsis_record":
                gsis_extra_ok = (
                    d1_obj.get("insulin_normalization_basis") == "PER_IEQ_PER_HOUR"
                    and is_valid_sha256_hex(d1_obj.get("raw_trace_sha256"))
                )
            if (
                not all(is_finite_num(x) and float(x) > 0.0 for x in num_d1)
                or not all(is_nonempty_str(d1_obj.get(k)) for k in d1_ep_id_keys)
                or not gsis_extra_ok
                or t_ep_a is None or t_ep_b is None
                or not is_valid_sha256_hex(rsha_d1)
                or sha256_bytes(canonical_json_bytes({k: v for k, v in d1_obj.items() if k != "record_sha256"})) != rsha_d1
            ):
                fails.append(f"FAIL_{d1_code.replace('HOLD_', '')}_INVALID")
            else:
                if d1_key == "check_d1_paired_gsis_record":
                    si_mm = False
                    recomp_si: dict[str, float] = {}
                    for bk, sk, sik in (
                        ("arm_a_basal_40", "arm_a_stim_40", "arm_a_si_40"),
                        ("arm_b_basal_40", "arm_b_stim_40", "arm_b_si_40"),
                        ("arm_a_basal_100", "arm_a_stim_100", "arm_a_si_100"),
                        ("arm_b_basal_100", "arm_b_stim_100", "arm_b_si_100"),
                    ):
                        calc_si = float(d1_obj[sk]) / float(d1_obj[bk])
                        recomp_si[sik] = calc_si
                        if abs(calc_si - float(d1_obj[sik])) > 0.05:
                            si_mm = True
                    if si_mm:
                        fails.append("FAIL_CHECK_D1_GSIS_SI_BASAL_STIM_MISMATCH")
                    if recomp_si["arm_a_si_40"] < 2.0 or recomp_si["arm_a_si_100"] < 2.0:
                        holds.append("HOLD_CHECK_D1_UNRESPONSIVE_RETAINED_T3_CONTROL")
                    if (
                        recomp_si["arm_b_si_40"] < 2.0 or recomp_si["arm_b_si_100"] < 2.0
                        or float(d1_obj["arm_b_basal_40"]) > 1.25 * float(d1_obj["arm_a_basal_40"])
                        or float(d1_obj["arm_b_basal_100"]) > 1.25 * float(d1_obj["arm_a_basal_100"])
                    ):
                        holds.append("HOLD_CHECK_D1_WITHDRAWAL_ARM_LOSS_OF_GLUCOSE_RESPONSIVENESS")
                    if (
                        float(d1_obj["arm_b_stim_40"]) < 0.80 * float(d1_obj["arm_a_stim_40"])
                        or float(d1_obj["arm_b_stim_100"]) < 0.80 * float(d1_obj["arm_a_stim_100"])
                    ):
                        holds.append("HOLD_CHECK_D1_GSIS_ABSOLUTE_STIMULATED_OUTPUT_DROP")
                elif d1_key == "check_d1_vascular_adhesion_sprouting_record":
                    adh_rat = float(d1_obj["neutrophil_adhesion_ratio_b_over_a"])
                    spr_pct = float(d1_obj["iec_sprouting_pct_ctrl"])
                    if adh_rat > 1.25 or spr_pct < 90.0:
                        if vasc_ok is True:
                            fails.append("FAIL_CHECK_D1_VASCULAR_FLAG_CONTRADICTS_ADVERSE_MEASUREMENTS")
                        else:
                            holds.append("HOLD_CHECK_D1_ADVERSE_VASCULAR_ENDPOINT_MEASURED")
                d1_ep_shas[d1_key] = str(rsha_d1)
                d1_ep_meta[d1_key] = (
                    str(d1_obj["lot_id"]).strip(),
                    str(d1_obj["plate_id"]).strip(),
                    str(d1_obj["sibling_aliquot_pair_id"]).strip(),
                )
                d1_ep_times[d1_key] = (t_ep_a, t_ep_b)

    # Unified content-hashed D-1 assay receipt binding lot, plate, sibling aliquot pair, acquisition time,
    # ALL matched-handling/analytical/vascular facts, and the 3 endpoint record digests!
    d1_rcpt = rec.get("check_d1_paired_assay_receipt")
    d1_rcpt_keys = frozenset({
        "lot_id", "plate_id", "sibling_aliquot_pair_id",
        "arm_a_exposure_start_utc", "arm_a_exposure_end_utc",
        "arm_b_exposure_start_utc", "arm_b_exposure_end_utc",
        "assay_acquired_at_utc", "recorded_at_utc",
        "arm_a_washes", "arm_b_washes", "starting_zm_regimen", "both_arms_matched_24h_nac",
        "zm447439_lloq_uM", "arm_a_zm447439_lcms_uM", "arm_b_zm447439_lcms_uM",
        "arm_a_spike_recovery_pct", "arm_b_spike_recovery_pct",
        "t3_lloq_nM", "residual_t3_arm_a_nM", "residual_t3_arm_b_nM", "arm_b_below_lloq",
        "arm_a_chemistry_sample", "arm_b_chemistry_sample",
        "pre_coassembly_vascular_function_pass",
        "paired_gsis_record_sha256", "paired_facs_record_sha256", "vascular_adhesion_sprouting_record_sha256",
        "receipt_sha256",
    })
    if d1_rcpt is None:
        holds.append("HOLD_CHECK_D1_MISSING_UNIFIED_PAIRED_ASSAY_RECEIPT")
    elif not isinstance(d1_rcpt, Mapping) or set(d1_rcpt.keys()) != d1_rcpt_keys:
        fails.append("FAIL_CHECK_D1_UNIFIED_ASSAY_RECEIPT_MALFORMED")
    else:
        d1_rsha = d1_rcpt.get("receipt_sha256")
        t_d1_acq = parse_utc_iso_ts(d1_rcpt.get("assay_acquired_at_utc"))
        t_d1_rec = parse_utc_iso_ts(d1_rcpt.get("recorded_at_utc"))
        t_a_st = parse_utc_iso_ts(d1_rcpt.get("arm_a_exposure_start_utc"))
        t_a_en = parse_utc_iso_ts(d1_rcpt.get("arm_a_exposure_end_utc"))
        t_b_st = parse_utc_iso_ts(d1_rcpt.get("arm_b_exposure_start_utc"))
        t_b_en = parse_utc_iso_ts(d1_rcpt.get("arm_b_exposure_end_utc"))
        if (
            not is_valid_sha256_hex(d1_rsha) or compute_receipt_sha256(d1_rcpt) != d1_rsha
            or not (is_nonempty_str(d1_rcpt.get("lot_id")) and is_nonempty_str(d1_rcpt.get("plate_id")) and is_nonempty_str(d1_rcpt.get("sibling_aliquot_pair_id")))
            or t_d1_acq is None or t_d1_rec is None or t_d1_acq > t_d1_rec
        ):
            fails.append("FAIL_CHECK_D1_UNIFIED_ASSAY_RECEIPT_HASH_OR_METADATA_INVALID")
        else:
            if t_a_st is None or t_a_en is None or t_b_st is None or t_b_en is None or t_a_en > t_d1_acq or t_b_en > t_d1_acq:
                fails.append("FAIL_CHECK_D1_EXPOSURE_WINDOW_UNMATCHED_OR_INVALID")
            else:
                dur_a_h = (t_a_en - t_a_st).total_seconds() / 3600.0
                dur_b_h = (t_b_en - t_b_st).total_seconds() / 3600.0
                if not (
                    23.5 <= dur_a_h <= 24.5 and 23.5 <= dur_b_h <= 24.5
                    and abs(dur_a_h - dur_b_h) <= 0.25
                    and abs((t_a_st - t_b_st).total_seconds()) <= 3600.0
                ):
                    fails.append("FAIL_CHECK_D1_EXPOSURE_WINDOW_UNMATCHED_OR_INVALID")
                chem_req_k = frozenset({"sample_id", "sibling_aliquot_pair_id", "collected_at_utc", "instrument_record_sha256", "instrument_row_or_injection_id"})
                ca_obj = d1_rcpt.get("arm_a_chemistry_sample")
                cb_obj = d1_rcpt.get("arm_b_chemistry_sample")
                chem_ok = (
                    isinstance(ca_obj, Mapping) and set(ca_obj.keys()) == chem_req_k
                    and isinstance(cb_obj, Mapping) and set(cb_obj.keys()) == chem_req_k
                    and is_nonempty_str(ca_obj.get("sample_id")) and is_nonempty_str(cb_obj.get("sample_id"))
                    and str(ca_obj["sample_id"]).strip().upper() != str(cb_obj["sample_id"]).strip().upper()
                    and is_nonempty_str(ca_obj.get("instrument_row_or_injection_id")) and is_nonempty_str(cb_obj.get("instrument_row_or_injection_id"))
                    and str(ca_obj.get("sibling_aliquot_pair_id", "")).strip() == str(d1_rcpt["sibling_aliquot_pair_id"]).strip()
                    and str(cb_obj.get("sibling_aliquot_pair_id", "")).strip() == str(d1_rcpt["sibling_aliquot_pair_id"]).strip()
                    and is_valid_sha256_hex(ca_obj.get("instrument_record_sha256"))
                    and is_valid_sha256_hex(cb_obj.get("instrument_record_sha256"))
                    and (
                        str(ca_obj["instrument_record_sha256"]).lower(),
                        str(ca_obj["instrument_row_or_injection_id"]).strip().upper(),
                    ) != (
                        str(cb_obj["instrument_record_sha256"]).lower(),
                        str(cb_obj["instrument_row_or_injection_id"]).strip().upper(),
                    )
                )
                if chem_ok:
                    t_ca = parse_utc_iso_ts(ca_obj["collected_at_utc"])
                    t_cb = parse_utc_iso_ts(cb_obj["collected_at_utc"])
                    if (
                        t_ca is None or t_cb is None
                        or not (t_a_en - timedelta(hours=1) <= t_ca <= t_a_en + timedelta(hours=1))
                        or not (t_b_en - timedelta(hours=1) <= t_cb <= t_b_en + timedelta(hours=1))
                        or abs((t_ca - t_a_en).total_seconds() - (t_cb - t_b_en).total_seconds()) > 1800.0 + 1e-6
                        or t_ca > t_d1_acq or t_cb > t_d1_acq
                    ):
                        chem_ok = False
                if not chem_ok:
                    fails.append("FAIL_CHECK_D1_CHEMISTRY_SAMPLE_PROVENANCE_OR_TIMING_INVALID")
                for ep_k, (t_ep_a, t_ep_b) in d1_ep_times.items():
                    wait_a_h = (t_ep_a - t_a_en).total_seconds() / 3600.0
                    wait_b_h = (t_ep_b - t_b_en).total_seconds() / 3600.0
                    if not (
                        t_a_en <= t_ep_a <= t_d1_acq and t_b_en <= t_ep_b <= t_d1_acq
                        and wait_a_h <= 4.0 + 1e-6 and wait_b_h <= 4.0 + 1e-6
                        and abs(wait_a_h - wait_b_h) <= 0.5 + 1e-6
                    ):
                        fails.append(f"FAIL_CHECK_D1_ENDPOINT_ACQUISITION_TIMING_UNMATCHED_OR_INVALID:{ep_k}")
            d1_bind_pairs = (
                ("arm_a_washes", "check_d1_arm_a_washes"),
                ("arm_b_washes", "check_d1_arm_b_washes"),
                ("starting_zm_regimen", "check_d1_starting_zm_regimen"),
                ("both_arms_matched_24h_nac", "check_d1_both_arms_matched_24h_nac"),
                ("zm447439_lloq_uM", "check_d1_zm447439_lloq_uM"),
                ("arm_a_zm447439_lcms_uM", "check_d1_arm_a_zm447439_lcms_uM"),
                ("arm_b_zm447439_lcms_uM", "check_d1_arm_b_zm447439_lcms_uM"),
                ("arm_a_spike_recovery_pct", "check_d1_arm_a_spike_recovery_pct"),
                ("arm_b_spike_recovery_pct", "check_d1_arm_b_spike_recovery_pct"),
                ("t3_lloq_nM", "check_d1_t3_lloq_nM"),
                ("residual_t3_arm_a_nM", "check_d1_residual_t3_arm_a_nM"),
                ("residual_t3_arm_b_nM", "check_d1_residual_t3_arm_b_nM"),
                ("arm_b_below_lloq", "check_d1_arm_b_below_lloq"),
                ("pre_coassembly_vascular_function_pass", "check_d1_pre_coassembly_vascular_function_pass"),
            )
            def _strict_json_eq(a_v: Any, b_v: Any) -> bool:
                # Reject Python bool/int coercion (1 == True, 0 == False)!
                if isinstance(a_v, bool) or isinstance(b_v, bool):
                    return type(a_v) is type(b_v) and a_v is b_v
                if isinstance(a_v, int) and isinstance(b_v, int):
                    return a_v == b_v
                if is_finite_num(a_v) and is_finite_num(b_v):
                    return float(a_v) == float(b_v)
                return type(a_v) is type(b_v) and a_v == b_v

            if (
                not is_strict_int(d1_rcpt.get("arm_a_washes"))
                or not is_strict_int(d1_rcpt.get("arm_b_washes"))
                or any(not _strict_json_eq(d1_rcpt.get(rk), rec.get(ok_k)) for rk, ok_k in d1_bind_pairs)
            ):
                fails.append("FAIL_CHECK_D1_UNIFIED_ASSAY_RECEIPT_FIELD_MISMATCH")
            d1_rcpt_meta = (
                str(d1_rcpt["lot_id"]).strip(),
                str(d1_rcpt["plate_id"]).strip(),
                str(d1_rcpt["sibling_aliquot_pair_id"]).strip(),
            )
            if any(ep_m != d1_rcpt_meta for ep_m in d1_ep_meta.values()):
                fails.append("FAIL_CHECK_D1_ENDPOINT_SPECIMEN_OR_PLATE_IDENTITY_MISMATCH")
            if (
                (d1_ep_shas.get("check_d1_paired_gsis_record") is not None and d1_rcpt.get("paired_gsis_record_sha256") != d1_ep_shas["check_d1_paired_gsis_record"])
                or (d1_ep_shas.get("check_d1_paired_facs_record") is not None and d1_rcpt.get("paired_facs_record_sha256") != d1_ep_shas["check_d1_paired_facs_record"])
                or (d1_ep_shas.get("check_d1_vascular_adhesion_sprouting_record") is not None and d1_rcpt.get("vascular_adhesion_sprouting_record_sha256") != d1_ep_shas["check_d1_vascular_adhesion_sprouting_record"])
            ):
                fails.append("FAIL_CHECK_D1_UNIFIED_ASSAY_RECEIPT_ENDPOINT_DIGEST_MISMATCH")

    # Check D-2: EXACT verbatim status required (no missing default, no lowercase/whitespace variants!),
    # content-hashed per-lot safety+Readout-2 receipt, independent measurement/block IDs across all >= 3 lots!
    d2_status = rec.get("check_d2_status")
    if d2_status == "NOT_APPLICABLE":
        _check_forbidden_keys(rec, D2_EVAL_KEYS, fails, "FAIL_CHECK_D2_NOT_APPLICABLE_FORBIDS_EVAL_FIELDS")
    elif d2_status == "EVALUATED":
        cg = str(rec.get("check_d2_challenger_gene", "")).strip().upper()
        d2_prod = str(rec.get("check_d2_product_id", "")).strip()
        d2_bank = str(rec.get("check_d2_bank_id", "")).strip()
        d2_lots = rec.get("check_d2_per_lot_records")
        if cg not in ("ICAM1", "CD58", "CD276", "NLRC5_CONSTITUTIVE_KO"):
            fails.append("FAIL_CHECK_D2_UNRECOGNIZED_CHALLENGER_GENE")
        if d2_prod not in CANONICAL_WAVE6_PRODUCTS:
            fails.append("FAIL_CHECK_D2_NON_CANONICAL_PRODUCT_ID")
        if not d2_bank:
            fails.append("FAIL_CHECK_D2_MISSING_BANK_ID")
        if not isinstance(d2_lots, list) or len(d2_lots) < 3:
            fails.append("FAIL_CHECK_D2_REQUIRES_AT_LEAST_3_ISOGENIC_LOT_RECORDS")
        else:
            seen_d2_lots: set[str] = set()
            seen_d2_ctrls: set[str] = set()
            seen_d2_meas: set[str] = set()
            seen_d2_r2_hashes: set[str] = set()
            seen_d2_numeric_sigs: set[tuple[Any, ...]] = set()
            seen_d2_block_owner: dict[str, str] = {}
            seen_d2_trace_owner: dict[str, str] = {}
            d2_r2_extras = frozenset({
                "readout2_evidence",
                "proinsulin_to_insulin_fold_vs_ctrl", "basal_cleaved_casp3_fold_vs_ctrl",
                "basal_cleaved_casp9_fold_vs_ctrl", "bcl2l1_protein_pct_ctrl",
                "mcl1_protein_pct_ctrl", "cd59_protein_pct_ctrl",
                "ki67_fold_vs_ctrl", "edu_fold_vs_ctrl", "ki67_edu_referred",
            })
            lot_allowed = frozenset({"lot_id", "matched_control_lot_id", "readout2_receipt"})
            for idx, lrec in enumerate(d2_lots):
                if not isinstance(lrec, Mapping):
                    fails.append(f"FAIL_CHECK_D2_MALFORMED_LOT_RECORD:{idx}"); continue
                _check_allowed_keys(lrec, lot_allowed, fails, f"CHECK_D2_LOT_{idx}")
                if not is_nonempty_str(lrec.get("lot_id")) or not is_nonempty_str(lrec.get("matched_control_lot_id")):
                    fails.append("FAIL_CHECK_D2_DUPLICATE_OR_EMPTY_LOT_ID"); continue
                lid = str(lrec["lot_id"]).strip()
                mctrl = str(lrec["matched_control_lot_id"]).strip()
                if lid.upper() in seen_d2_lots:
                    fails.append("FAIL_CHECK_D2_DUPLICATE_OR_EMPTY_LOT_ID"); continue
                seen_d2_lots.add(lid.upper())
                if mctrl.upper() == lid.upper():
                    fails.append(f"FAIL_CHECK_D2_INVALID_MATCHED_CONTROL_LOT_ID:{lid}"); continue
                if mctrl.upper() in seen_d2_ctrls:
                    fails.append(f"FAIL_CHECK_D2_REUSED_MATCHED_CONTROL_LOT_ACROSS_LOTS:{lid}")
                seen_d2_ctrls.add(mctrl.upper())
                # Enforce globally disjoint treated and control lot ID sets across all >= 3 D-2 lots!
                if not seen_d2_lots.isdisjoint(seen_d2_ctrls):
                    fails.append(f"FAIL_CHECK_D2_TREATED_AND_CONTROL_LOT_IDS_OVERLAP:{lid}")
                r2_ev = _validate_content_receipt(
                    lrec.get("readout2_receipt"),
                    expected_stage="READOUT_2_CHALLENGER", expected_prod=d2_prod, expected_bank=d2_bank,
                    expected_lot=lid, expected_route=None, forbid_route=True,
                    expected_scope="exact_product", expected_candidate_gene=cg,
                    expected_comparator_nt_lot_id=mctrl,
                    allowed_extra_keys=d2_r2_extras,
                    fails=fails, holds=holds,
                    missing_hold=f"HOLD_CHECK_D2_LOT_READOUT2_MISSING:{lid}",
                    fail_code="FAIL_CHECK_D2_READOUT2_FAILED",
                    mismatch_code="FAIL_CHECK_D2_READOUT2_SCOPE_MISMATCH",
                )
                if r2_ev is not None:
                    r2_obj = r2_ev.get("readout2_evidence")
                    _validate_readout2_gsis(
                        r2_obj, fails=fails, holds=holds,
                        prefix=f"CHECK_D2_{lid}",
                        expected_comparator_id=mctrl,
                        min_comparator_output_ratio=0.90,
                        parent_recorded_at_utc=parse_utc_iso_ts(r2_ev.get("recorded_at_utc")),
                        expected_prod=d2_prod, expected_bank=d2_bank, expected_lot=lid, expected_route=None,
                    )
                    # Enforce genuine per-lot measurement independence across all >= 3 lots (including cross-oxygen cross-lot block ID reuse!)
                    if isinstance(r2_obj, Mapping):
                        mid = str(r2_obj.get("shared_measurement_record_id", "")).strip().upper()
                        r2_d = sha256_bytes(canonical_json_bytes(r2_obj))
                        if not mid or mid in seen_d2_meas or r2_d in seen_d2_r2_hashes:
                            fails.append(f"FAIL_CHECK_D2_REUSED_READOUT2_MEASUREMENT_ACROSS_LOTS:{lid}")
                        seen_d2_meas.add(mid); seen_d2_r2_hashes.add(r2_d)
                        for o2k in ("o2_40_mmhg", "o2_100_mmhg"):
                            ob = r2_obj.get(o2k)
                            if isinstance(ob, Mapping) and isinstance(ob.get("blocks"), list):
                                for b in ob["blocks"]:
                                    if isinstance(b, Mapping) and is_nonempty_str(b.get("block_id")):
                                        raw_bk = str(b["block_id"]).strip().upper()
                                        owner = seen_d2_block_owner.get(raw_bk)
                                        if owner is not None and owner != lid.upper():
                                            fails.append(f"FAIL_CHECK_D2_REUSED_BLOCK_ID_ACROSS_LOTS:{lid}")
                                        seen_d2_block_owner[raw_bk] = lid.upper()
                                    if isinstance(b, Mapping) and is_nonempty_str(b.get("trace_id")):
                                        raw_tr = str(b["trace_id"]).strip().upper()
                                        t_own = seen_d2_trace_owner.get(raw_tr)
                                        if t_own is not None and t_own != lid.upper():
                                            fails.append(f"FAIL_CHECK_D2_REUSED_TRACE_ID_ACROSS_LOTS:{lid}")
                                        seen_d2_trace_owner[raw_tr] = lid.upper()
                        e_s8_recs = r2_obj.get("rule_s8_earlier_window_records")
                        if isinstance(e_s8_recs, list):
                            for er_s8 in e_s8_recs:
                                if isinstance(er_s8, Mapping):
                                    for tk_s8 in ("trace_id_40mmhg", "trace_id_100mmhg"):
                                        if is_nonempty_str(er_s8.get(tk_s8)):
                                            raw_etr = str(er_s8[tk_s8]).strip().upper()
                                            t_own = seen_d2_trace_owner.get(raw_etr)
                                            if t_own is not None and t_own != lid.upper():
                                                fails.append(f"FAIL_CHECK_D2_REUSED_TRACE_ID_ACROSS_LOTS:{lid}")
                                            seen_d2_trace_owner[raw_etr] = lid.upper()
                        # Order-insensitive per-oxygen numeric block multiset copy-paste detection (reversing/permuting blocks CANNOT evade!)
                        num_sig_parts: list[Any] = []
                        for o2k in ("o2_40_mmhg", "o2_100_mmhg"):
                            ob = r2_obj.get(o2k)
                            o2_rows: list[tuple[Any, ...]] = []
                            if isinstance(ob, Mapping) and isinstance(ob.get("blocks"), list):
                                for b in ob["blocks"]:
                                    if isinstance(b, Mapping):
                                        o2_rows.append(tuple(
                                            round(float(b[k]), 6) if is_finite_num(b.get(k)) else -1e30
                                            for k in ("pulse1_si", "z1_increment", "z2_increment", "ref_adult_z2_increment", "stepdown_t50_min")
                                        ))
                            num_sig_parts.append((o2k, tuple(sorted(o2_rows))))
                        nsig = tuple(num_sig_parts)
                        if nsig and nsig in seen_d2_numeric_sigs:
                            fails.append(f"FAIL_CHECK_D2_IDENTICAL_NUMERICAL_ARRAYS_ACROSS_LOTS:{lid}")
                        elif nsig:
                            seen_d2_numeric_sigs.add(nsig)
                    # All 6 safety markers + Ki-67/EdU live INSIDE the content-hashed readout2_receipt!
                    for sk, slo, shi, scode in (
                        ("proinsulin_to_insulin_fold_vs_ctrl", 0.0, 1.15, f"FAIL_CHECK_D2_PROINSULIN_RATIO_GT_1P15:{lid}"),
                        ("basal_cleaved_casp3_fold_vs_ctrl", 0.0, 1.20, f"FAIL_CHECK_D2_BASAL_CASP3_GT_1P20:{lid}"),
                        ("basal_cleaved_casp9_fold_vs_ctrl", 0.0, 1.20, f"FAIL_CHECK_D2_BASAL_CASP9_GT_1P20:{lid}"),
                        ("bcl2l1_protein_pct_ctrl", 80.0, 200.0, f"FAIL_CHECK_D2_BCL2L1_PROTEIN_LT_80PCT:{lid}"),
                        ("mcl1_protein_pct_ctrl", 80.0, 200.0, f"FAIL_CHECK_D2_MCL1_PROTEIN_LT_80PCT:{lid}"),
                        ("cd59_protein_pct_ctrl", 80.0, 200.0, f"FAIL_CHECK_D2_CD59_PROTEIN_LT_80PCT:{lid}"),
                    ):
                        sv = r2_ev.get(sk)
                        if not (is_finite_num(sv) and slo <= float(sv) <= shi):
                            fails.append(scode)
                    kf = r2_ev.get("ki67_fold_vs_ctrl")
                    ef = r2_ev.get("edu_fold_vs_ctrl")
                    if not (is_finite_num(kf) and is_finite_num(ef) and float(kf) >= 0.0 and float(ef) >= 0.0):
                        fails.append(f"FAIL_CHECK_D2_MISSING_PER_LOT_PROLIFERATION:{lid}")
                    elif float(kf) > 1.0 or float(ef) > 1.0:
                        if not (is_strict_bool(r2_ev.get("ki67_edu_referred")) and r2_ev["ki67_edu_referred"]):
                            fails.append(f"FAIL_CHECK_D2_UNREFERRED_PROLIFERATION_ELEVATION:{lid}")
                        else:
                            holds.append(f"HOLD_CHECK_D2_PROLIFERATION_REFERRED:{lid}")
    else:
        fails.append("FAIL_CHECK_D2_INVALID_STATUS")

    # Check D-3(a/b): exact verbatim statuses!
    if not (is_strict_bool(rec.get("check_d3_c3_explicitly_untested")) and rec["check_d3_c3_explicitly_untested"]):
        fails.append("FAIL_CHECK_D3_C3_MUST_REMAIN_UNTESTED")

    d3a_status = rec.get("check_d3a_status")
    d3a_verified_hashes: list[str] = []
    d3a_max_recorded_ts: Optional[datetime] = None
    if d3a_status == "NOT_ATTEMPTED":
        _check_forbidden_keys(rec, D3A_EVAL_KEYS, fails, "FAIL_CHECK_D3A_NOT_ATTEMPTED_FORBIDS_EVAL_FIELDS")
    elif d3a_status == "EVALUATED":
        d3a_lots = rec.get("check_d3a_per_lot_records")
        if not isinstance(d3a_lots, list) or len(d3a_lots) < 3:
            fails.append("FAIL_CHECK_D3A_REQUIRES_AT_LEAST_3_INDEPENDENT_LOT_RECORDS")
        else:
            seen_3a: set[str] = set()
            seen_3a_nt: set[str] = set()
            seen_3a_aid: set[str] = set()
            seen_3a_blood_donors: set[str] = set()
            seen_3a_blood_splits: set[str] = set()
            seen_3a_source_preps: set[str] = set()
            seen_3a_meas_sigs: set[tuple[Any, ...]] = set()
            seen_3a_hashes: set[str] = set()
            seen_3a_runs: set[str] = set()
            seen_3a_elisa_rows: set[tuple[str, str]] = set()
            seen_3a_inflam: set[str] = set()
            d3a_lot_allowed = frozenset({
                "receipt_sha256", "source_iec_preparation_id", "lot_id", "comparator_nt_lot_id", "assay_record_id",
                "paired_assay_run_id", "raw_elisa_record_sha256", "raw_elisa_well_or_row_id", "inflammatory_challenge_condition",
                "blood_donor_id", "matched_blood_split_id",
                "assay_acquired_at_utc", "recorded_at_utc",
                "iec_ptprc_pct", "cd31_pecam1_pct", "plvap_pos_pct", "cdh5_ve_cadherin_pct",
                "f3_kd_pct", "cxcl10_retention_pct", "cd274_retention_pct",
                "cleaved_casp3_fold",
                "pos_ctrl_tat_fold", "neg_ctrl_tat_fold",
                "tat_assay_lloq_ng_ml", "tat_f3_below_lloq",
                "chandler_tat_nt_ctrl_ng_ml", "chandler_tat_f3_sirna_ng_ml",
            })
            for idx, lrec in enumerate(d3a_lots):
                if not isinstance(lrec, Mapping):
                    fails.append(f"FAIL_CHECK_D3A_MALFORMED_LOT:{idx}"); continue
                _check_allowed_keys(lrec, d3a_lot_allowed, fails, f"CHECK_D3A_LOT_{idx}")
                raw_lid = lrec.get("lot_id")
                raw_nt = lrec.get("comparator_nt_lot_id")
                raw_aid = lrec.get("assay_record_id")
                if not is_nonempty_str(raw_lid) or not is_nonempty_str(raw_nt):
                    fails.append("FAIL_CHECK_D3A_DUPLICATE_OR_EMPTY_LOT_ID"); continue
                lid = str(raw_lid).strip()
                nt_l = str(raw_nt).strip()
                if lid.upper() in seen_3a or lid.upper() == nt_l.upper():
                    fails.append("FAIL_CHECK_D3A_DUPLICATE_OR_EMPTY_LOT_ID"); continue
                if nt_l.upper() in seen_3a_nt:
                    fails.append(f"FAIL_CHECK_D3A_REUSED_COMPARATOR_NT_LOT_ACROSS_LOTS:{lid}")
                if not is_nonempty_str(raw_aid) or str(raw_aid).strip().upper() in seen_3a_aid:
                    fails.append(f"FAIL_CHECK_D3A_DUPLICATE_OR_MISSING_ASSAY_RECORD_ID:{lid}")
                else:
                    seen_3a_aid.add(str(raw_aid).strip().upper())
                raw_prep = lrec.get("source_iec_preparation_id")
                if not is_nonempty_str(raw_prep):
                    fails.append(f"FAIL_CHECK_D3A_DUPLICATE_OR_MISSING_SOURCE_IEC_PREP_ID:{lid}")
                else:
                    prep_u = str(raw_prep).strip().upper()
                    if prep_u in seen_3a_source_preps or prep_u == lid.upper() or prep_u == nt_l.upper():
                        fails.append(f"FAIL_CHECK_D3A_DUPLICATE_OR_MISSING_SOURCE_IEC_PREP_ID:{lid}")
                    else:
                        seen_3a_source_preps.add(prep_u)
                raw_bd = lrec.get("blood_donor_id")
                raw_bs = lrec.get("matched_blood_split_id")
                if not is_nonempty_str(raw_bd):
                    fails.append(f"FAIL_CHECK_D3A_MISSING_BLOOD_DONOR_ID:{lid}")
                else:
                    seen_3a_blood_donors.add(str(raw_bd).strip().upper())
                if not is_nonempty_str(raw_bs) or str(raw_bs).strip().upper() in seen_3a_blood_splits:
                    fails.append(f"FAIL_CHECK_D3A_DUPLICATE_OR_MISSING_BLOOD_SPLIT_ID:{lid}")
                else:
                    seen_3a_blood_splits.add(str(raw_bs).strip().upper())
                seen_3a.add(lid.upper())
                seen_3a_nt.add(nt_l.upper())
                if not seen_3a.isdisjoint(seen_3a_nt):
                    fails.append(f"FAIL_CHECK_D3A_TREATED_COMPARATOR_LOT_ID_OVERLAP_OR_CYCLE:{lid}")
                rsha = lrec.get("receipt_sha256")
                if not is_valid_sha256_hex(rsha) or compute_receipt_sha256(lrec) != rsha or rsha in seen_3a_hashes:
                    fails.append(f"FAIL_CHECK_D3A_LOT_CONTENT_HASH_INVALID:{lid}")
                else:
                    seen_3a_hashes.add(rsha)
                    d3a_verified_hashes.append(str(rsha))
                t_3a_acq = parse_utc_iso_ts(lrec.get("assay_acquired_at_utc"))
                t_3a_rec = parse_utc_iso_ts(lrec.get("recorded_at_utc"))
                if t_3a_acq is None or t_3a_rec is None or t_3a_acq > t_3a_rec:
                    fails.append(f"FAIL_CHECK_D3A_INVALID_OR_MISSING_TIMESTAMPS:{lid}")
                elif d3a_max_recorded_ts is None or t_3a_rec > d3a_max_recorded_ts:
                    d3a_max_recorded_ts = t_3a_rec
                ptprc = lrec.get("iec_ptprc_pct")
                cd31 = lrec.get("cd31_pecam1_pct")
                plv = lrec.get("plvap_pos_pct")
                cdh5 = lrec.get("cdh5_ve_cadherin_pct")
                kd = lrec.get("f3_kd_pct")
                cx = lrec.get("cxcl10_retention_pct")
                cd = lrec.get("cd274_retention_pct")
                c3_f = lrec.get("cleaved_casp3_fold")
                pct = lrec.get("pos_ctrl_tat_fold")
                nct = lrec.get("neg_ctrl_tat_fold")
                raw_run = lrec.get("paired_assay_run_id")
                elisa_sha = lrec.get("raw_elisa_record_sha256")
                elisa_row = lrec.get("raw_elisa_well_or_row_id")
                inflam_c = lrec.get("inflammatory_challenge_condition")
                if (
                    not is_nonempty_str(raw_run) or str(raw_run).strip().upper() in seen_3a_runs
                    or not is_valid_sha256_hex(elisa_sha) or not is_nonempty_str(elisa_row)
                ):
                    fails.append(f"FAIL_CHECK_D3A_PAIRED_ASSAY_PROVENANCE_INVALID:{lid}")
                else:
                    seen_3a_runs.add(str(raw_run).strip().upper())
                    elisa_key = (str(elisa_sha).lower(), str(elisa_row).strip().upper())
                    if elisa_key in seen_3a_elisa_rows:
                        fails.append(f"FAIL_CHECK_D3A_OVERLAPPING_ELISA_SOURCE_ROW:{lid}")
                    else:
                        seen_3a_elisa_rows.add(elisa_key)
                if inflam_c not in ("BASAL_UNSTIMULATED", "TNFA_IFNG_PRIMED"):
                    fails.append("FAIL_CHECK_D3A_INCONSISTENT_OR_INVALID_INFLAMMATORY_CONDITION")
                else:
                    seen_3a_inflam.add(str(inflam_c))
                tat_lloq = lrec.get("tat_assay_lloq_ng_ml")
                tat_blq = lrec.get("tat_f3_below_lloq")
                tat_nt = lrec.get("chandler_tat_nt_ctrl_ng_ml")
                tat_f3 = lrec.get("chandler_tat_f3_sirna_ng_ml")
                if not (is_finite_num(ptprc) and float(ptprc) == 0.0):
                    fails.append(f"FAIL_CHECK_D3A_NON_ZERO_PTPRC_CONTAMINATION:{lid}")
                if not (is_finite_num(cd31) and 90.0 <= float(cd31) <= 100.0 and is_finite_num(plv) and 85.0 <= float(plv) <= 100.0 and is_finite_num(cdh5) and 90.0 <= float(cdh5) <= 100.0):
                    fails.append(f"FAIL_CHECK_D3A_POSITIVE_ENDOTHELIAL_IDENTITY_BELOW_FLOOR:{lid}")
                if not (is_finite_num(kd) and 60.0 <= float(kd) <= 100.0):
                    fails.append(f"FAIL_CHECK_D3A_F3_KD_BELOW_60PCT:{lid}")
                if not (is_finite_num(cx) and 85.0 <= float(cx) <= 200.0):
                    fails.append(f"FAIL_CHECK_D3A_CXCL10_RETENTION_BELOW_85PCT:{lid}")
                if not (is_finite_num(cd) and 85.0 <= float(cd) <= 200.0):
                    fails.append(f"FAIL_CHECK_D3A_CD274_RETENTION_BELOW_85PCT:{lid}")
                if not (is_finite_num(c3_f) and 0.0 < float(c3_f) <= 1.2):
                    fails.append(f"FAIL_CHECK_D3A_APOPTOSIS_INCREASE:{lid}")
                if not (is_finite_num(pct) and float(pct) >= 3.0 and is_finite_num(nct) and 0.0 <= float(nct) <= 1.5):
                    fails.append(f"FAIL_CHECK_D3A_CHANDLER_CONTROLS_INVALID:{lid}")
                if not (is_finite_num(tat_lloq) and 0.0 < float(tat_lloq) <= 10.0 and is_strict_bool(tat_blq) and "chandler_tat_f3_sirna_ng_ml" in lrec):
                    fails.append(f"FAIL_CHECK_D3A_TAT_LLOQ_OR_CENSORING_INVALID:{lid}")
                elif not (is_finite_num(tat_nt) and float(tat_nt) > 0.0):
                    fails.append(f"FAIL_CHECK_D3A_NO_FUNCTIONAL_TAT_REDUCTION:{lid}")
                elif float(tat_nt) < 3.0 * float(tat_lloq):
                    holds.append(f"HOLD_CHECK_D3A_TAT_COMPARATOR_NEAR_OR_BELOW_LLOQ:{lid}")
                elif tat_blq is True:
                    if tat_f3 is not None:
                        fails.append(f"FAIL_CHECK_D3A_TAT_LLOQ_OR_CENSORING_INVALID:{lid}")
                    else:
                        eff_tat_f3 = float(tat_lloq)
                        red_pct = 100.0 * (float(tat_nt) - eff_tat_f3) / float(tat_nt)
                        if not (20.0 <= red_pct <= 100.0):
                            fails.append(f"FAIL_CHECK_D3A_NO_FUNCTIONAL_TAT_REDUCTION:{lid}")
                        msig = tuple(
                            round(float(x), 6) if is_finite_num(x) else None
                            for x in (cd31, plv, cdh5, kd, cx, cd, c3_f, pct, nct, tat_nt, eff_tat_f3)
                        )
                        if msig in seen_3a_meas_sigs:
                            fails.append(f"FAIL_CHECK_D3A_IDENTICAL_COPY_PASTE_ACROSS_LOTS:{lid}")
                        seen_3a_meas_sigs.add(msig)
                else:
                    if not (is_finite_num(tat_f3) and float(tat_f3) >= 0.0):
                        fails.append(f"FAIL_CHECK_D3A_NO_FUNCTIONAL_TAT_REDUCTION:{lid}")
                    elif float(tat_f3) < float(tat_lloq):
                        fails.append(f"FAIL_CHECK_D3A_TAT_QUANTIFIED_BELOW_LLOQ:{lid}")
                    else:
                        eff_tat_f3 = float(tat_f3)
                        red_pct = 100.0 * (float(tat_nt) - eff_tat_f3) / float(tat_nt)
                        if not (20.0 <= red_pct <= 100.0):
                            fails.append(f"FAIL_CHECK_D3A_NO_FUNCTIONAL_TAT_REDUCTION:{lid}")
                        msig = tuple(
                            round(float(x), 6) if is_finite_num(x) else None
                            for x in (cd31, plv, cdh5, kd, cx, cd, c3_f, pct, nct, tat_nt, eff_tat_f3)
                        )
                        if msig in seen_3a_meas_sigs:
                            fails.append(f"FAIL_CHECK_D3A_IDENTICAL_COPY_PASTE_ACROSS_LOTS:{lid}")
                        seen_3a_meas_sigs.add(msig)
            if len(seen_3a_inflam) > 1:
                fails.append("FAIL_CHECK_D3A_INCONSISTENT_OR_INVALID_INFLAMMATORY_CONDITION")
            if len(seen_3a_blood_donors) < 3:
                fails.append("FAIL_CHECK_D3A_INSUFFICIENT_INDEPENDENT_BLOOD_DONORS")
    else:
        fails.append("FAIL_CHECK_D3A_INVALID_STATUS")

    d3b_status = rec.get("check_d3b_status")
    if d3b_status == "NOT_ATTEMPTED":
        _check_forbidden_keys(rec, D3B_EVAL_KEYS, fails, "FAIL_CHECK_D3B_NOT_ATTEMPTED_FORBIDS_EVAL_FIELDS")
    elif d3b_status == "EVALUATED":
        d3b_scope = rec.get("d3b_assay_scope")
        if d3b_scope not in ("IEC_ONLY_NON_ASSEMBLED", "ASSEMBLED_ROUTE_QUALIFICATION"):
            fails.append("FAIL_CHECK_D3B_UNDECLARED_ASSAY_SCOPE")
        need_g31_a = (d3b_scope == "ASSEMBLED_ROUTE_QUALIFICATION")
        if need_g31_a and d3a_status != "EVALUATED":
            fails.append("FAIL_CHECK_D3B_ASSEMBLED_REQUIRES_D3A_EVALUATED_FIRST")
        d3b_raw_p = rec.get("d3b_pilot_receipt")
        d3b_exp_nt = str(d3b_raw_p.get("nt_control_lot_id", "")).strip() if isinstance(d3b_raw_p, Mapping) and is_nonempty_str(d3b_raw_p.get("nt_control_lot_id")) else None
        spec_3b, _, b_fails, b_holds, mat_3b, sw_3b, g0v_3b, g31_3b = _validate_canonical_binding_v6(
            rec, allow_design_a=True, coating_gate=False, phase="EXACT_PRODUCT",
            require_materialization=True, require_switches=True,
            require_gate31_on_design_a_r1=need_g31_a,
            expected_comparator_nt_lot_id=d3b_exp_nt,
        )
        fails.extend(b_fails)
        holds.extend(b_holds)
        prod_3b = str(rec.get("product_id", "")).strip()
        bank_3b = str(rec.get("bank_id", "")).strip()
        lot_3b = str(rec.get("lot_id", "")).strip()
        route_3b = str(rec.get("route_id", "")).strip().upper()
        d3b_prereqs: list[tuple[str, Optional[Mapping[str, Any]]]] = [
            ("BANK_MATERIALIZATION", mat_3b), ("NATIVE_SAFETY_SWITCH", sw_3b), ("GATE-0V-KILL", g0v_3b),
        ]
        if g31_3b is not None:
            d3b_prereqs.append(("GATE-31", g31_3b))
        d3b_rcpt_extras = frozenset({
            "d3b_assay_scope", "assay_acquired_at_utc", "f3_kd_pct_in_pilot",
            "d3a_lot_receipt_sha256s",
            "treated_lot_id", "nt_control_lot_id", "same_product_nt_sirna",
            "parental_attribution_included",
            "f3_sirna_shield_by_component", "nt_sirna_shield_by_component", "parental_shield_by_component",
            "hour0_density_by_lineage",
        })
        d3b_ev = _validate_content_receipt(
            rec.get("d3b_pilot_receipt"),
            expected_stage="CHECK_D3B_PILOT", expected_prod=prod_3b, expected_bank=bank_3b,
            expected_lot=lot_3b, expected_route=route_3b, expected_scope="exact_product",
            expected_parent=mat_3b, min_prereq_receipts=d3b_prereqs,
            allowed_extra_keys=d3b_rcpt_extras, fails=fails, holds=holds,
            missing_hold="HOLD_CHECK_D3B_TIMED_PILOT_RECEIPT_MISSING",
            fail_code="FAIL_CHECK_D3B_PILOT_RECEIPT_FAILED",
            mismatch_code="FAIL_CHECK_D3B_PILOT_RECEIPT_SCOPE_MISMATCH",
        )
        if d3b_ev is not None:
            if d3b_ev.get("d3b_assay_scope") != d3b_scope:
                fails.append("FAIL_CHECK_D3B_ASSAY_SCOPE_NOT_BOUND_IN_RECEIPT_HASH")
            f3_kd_3b = d3b_ev.get("f3_kd_pct_in_pilot")
            if not (is_finite_num(f3_kd_3b) and 60.0 <= float(f3_kd_3b) <= 100.0):
                fails.append("FAIL_CHECK_D3B_TARGET_ENGAGEMENT_F3_KD_BELOW_60PCT")
            t_acq = parse_utc_iso_ts(d3b_ev.get("assay_acquired_at_utc"))
            t_3b = parse_utc_iso_ts(d3b_ev.get("recorded_at_utc"))
            if t_acq is None or (t_3b is not None and t_acq > t_3b):
                fails.append("FAIL_CHECK_D3B_INVALID_ASSAY_ACQUISITION_TIMESTAMP")
            else:
                for plbl, prec in d3b_prereqs:
                    if prec is not None:
                        tp = parse_utc_iso_ts(prec.get("recorded_at_utc"))
                        if tp is not None and t_acq < tp:
                            fails.append(f"FAIL_CHECK_D3B_ASSAY_ACQUIRED_BEFORE_{plbl}")
                if need_g31_a:
                    bound_3a = d3b_ev.get("d3a_lot_receipt_sha256s")
                    if not (
                        isinstance(bound_3a, list) and len(bound_3a) >= 3
                        and all(is_valid_sha256_hex(h) for h in bound_3a)
                        and d3a_verified_hashes and set(bound_3a) == set(d3a_verified_hashes)
                    ):
                        fails.append("FAIL_CHECK_D3B_ASSEMBLED_MISSING_D3A_RECEIPT_DIGEST_BINDING")
                    if d3a_max_recorded_ts is not None and t_acq < d3a_max_recorded_ts:
                        fails.append("FAIL_CHECK_D3B_ASSAY_ACQUIRED_BEFORE_D3A_COMPLETION")
            tr_lot = str(d3b_ev.get("treated_lot_id", "")).strip()
            nt_lot = str(d3b_ev.get("nt_control_lot_id", "")).strip()
            if not tr_lot or not nt_lot or tr_lot != nt_lot or (lot_3b and tr_lot != lot_3b):
                fails.append("FAIL_CHECK_D3B_UNMATCHED_TREATED_VS_NT_LOT_ID")
            if not (is_strict_bool(d3b_ev.get("same_product_nt_sirna")) and d3b_ev["same_product_nt_sirna"]):
                fails.append("FAIL_CHECK_D3B_MISSING_SAME_PRODUCT_NT_SIRNA")
            if not (is_strict_bool(d3b_ev.get("parental_attribution_included")) and d3b_ev["parental_attribution_included"]):
                fails.append("FAIL_CHECK_D3B_MISSING_PARENTAL_ATTRIBUTION_ARM")
            req_c = SHIELD_COMPONENTS_BY_PRODUCT.get(prod_3b, frozenset())
            f3_sh = d3b_ev.get("f3_sirna_shield_by_component")
            nt_sh = d3b_ev.get("nt_sirna_shield_by_component")
            par_sh = d3b_ev.get("parental_shield_by_component")
            if not (isinstance(f3_sh, Mapping) and isinstance(nt_sh, Mapping) and isinstance(par_sh, Mapping) and set(f3_sh.keys()) == req_c and set(nt_sh.keys()) == req_c and set(par_sh.keys()) == req_c):
                fails.append("FAIL_CHECK_D3B_INCOMPLETE_INTERVENTION_SHIELD_RECORDS")
            else:
                for cname in sorted(req_c):
                    fv, nv, pv = f3_sh.get(cname), nt_sh.get(cname), par_sh.get(cname)
                    if not (is_finite_num(fv) and is_finite_num(nv) and is_finite_num(pv) and float(nv) > 0.0 and float(pv) > 0.0):
                        fails.append(f"FAIL_CHECK_D3B_INVALID_SHIELD_VALUE:{cname}")
                    elif (100.0 * float(fv) / float(nv)) < 85.0:
                        fails.append(f"FAIL_CHECK_D3B_SHIELD_PRESERVATION_BELOW_85PCT:{cname}")
            if spec_3b is not None:
                req_lin = REQUIRED_HOUR0_LINEAGES_IEC if d3b_scope == "IEC_ONLY_NON_ASSEMBLED" else REQUIRED_HOUR0_LINEAGES_FULL
                _validate_lineage_hour0_density(
                    spec_3b, d3b_ev.get("hour0_density_by_lineage"),
                    required_lineages=req_lin, fails=fails, prefix="CHECK_D3B",
                )
    else:
        fails.append("FAIL_CHECK_D3B_INVALID_STATUS")

    verdict = "FAIL" if fails else ("HOLD" if holds else "PASS_DESCRIPTIVE_PILOT_ZERO_ODDS_GY037_WARN_RETAINED")
    return {
        "gate": "GATE-43", "verdict": verdict,
        "release_authorizing": False, "adoption_authority": False,
        "live_ledger_authenticated": False,
        "bank_registry_verified_live": False,
        "gy037_warn_retained": True, "gy037_revocation_eligible": False,
        "upstream_archive_verification": OFFLINE_ARCHIVE_NOTE,
        "live_odds_delta_pp": 0.0, "prospective_odds_delta_pp": 0.0,
        "failures": fails, "holds": holds,
    }


# ---------------------------------------------------------------------------
# Deterministic Positive Fixture Builders & 320/320 Adversarial Self-Tests
# ---------------------------------------------------------------------------

def _sign_receipt(body: dict[str, Any]) -> dict[str, Any]:
    out = dict(body)
    out["receipt_sha256"] = compute_receipt_sha256(out)
    return out


def _mk_r8_coating(tag: str = "PFD-R3P") -> dict[str, str]:
    return {
        "coating_article_id": f"ART-{tag}-01",
        "coating_formulation_rev": "REV-1.0",
        "coating_lot_id": f"COAT-LOT-{tag}-001",
        "matched_blank_vehicle_lot_id": f"BLANK-VEH-{tag}-001",
        "exposure_protocol_id": f"EXP-SOP-{tag}-V1",
        "api_batch_id": f"API-BATCH-{tag}-2026A",
    }


def _mk_r8_oq012(
    raw_cells: int = 1_000_000_000,
    f_clon: float = 0.50,
    eta: float = 0.80,
    n_eff: int = 400_000_000,
    k: int = 0,
    regrowth_ok: bool = True,
) -> dict[str, Any]:
    u95_f = float(recompute_clopper_pearson_u95_decimal_n_eff(max(1, n_eff)))
    return {
        "survivors_k": k,
        "raw_cells_tested": raw_cells,
        "clonogenic_fraction_f": f_clon,
        "detection_efficiency_eta": eta,
        "effective_trials_n_eff": n_eff,
        "regrowth_assay_verified": regrowth_ok,
        "clonogenic_escape_u95": u95_f,
    }


def _mk_r8_switch_parity(ctrl_lot_id: str = "CTRL-LOT-001") -> dict[str, Any]:
    t24 = [99.94, 99.95, 99.93, 99.95, 99.94, 99.96]
    c24 = [99.93, 99.94, 99.93, 99.94, 99.93, 99.95]
    t72 = [99.994, 99.995, 99.994, 99.995, 99.994, 99.996]
    c72 = [99.993, 99.994, 99.994, 99.994, 99.993, 99.995]
    d24 = [t24[i] - c24[i] for i in range(6)]
    d72 = [t72[i] - c72[i] for i in range(6)]
    l24 = paired_t_summary(d24)[3]
    l72 = paired_t_summary(d72)[3]
    return _sign_receipt({
        "comparator_control_lot_id": ctrl_lot_id,
        "block_ids": [f"SWB-{i+1}" for i in range(6)],
        "treated_24h_kill_pct_by_block": t24,
        "control_24h_kill_pct_by_block": c24,
        "treated_72h_kill_pct_by_block": t72,
        "control_72h_kill_pct_by_block": c72,
        "reported_l95_24h_delta_pp": round(l24, 8),
        "reported_l95_72h_delta_pp": round(l72, 8),
        "control_oq012_clonogenic_block": _mk_r8_oq012(),
    })


def _mk_r8_readout2(
    *,
    matched_comparator_id: Optional[str] = None,
    block_prefix: str = "BLK",
    meas_id: Optional[str] = None,
    lot_id: str = "LOT-Y-001",
    stored_u95_iu: float = 115.0,
    stored_max_iu: float = 122.0,
    gate0s_cleared: bool = False,
    gate0s_receipt: Optional[dict[str, Any]] = None,
    rule_s8: bool = False,
    rule_s8_k: int = 1,
    rule_s8_design: str = "SINGLE_PRESPECIFIED_PRIMARY",
    gate0m_applicable: bool = False,
    stage7_start_utc: str = "2026-10-01T00:00:00Z",
    sort_reaggregation_utc: str = "2026-10-15T00:00:00Z",
    assay_harvest_utc: Optional[str] = None,
    lot_jitter: float = 0.0,
    pure_endocrine_ocr: float = 3.15,
    registered_mixture_id: str = "REF_60_30_10",
    beta_cell_fraction: float = 0.60,
    alpha_cell_fraction: float = 0.30,
    delta_cell_fraction: float = 0.10,
    n_blocks: int = 6,
    dec084_receipt: Optional[dict[str, Any]] = None,
    post_sort_zm_regimen: str = "S7W0_ONLY_0UM_POST_SORT",
    post_sort_zm_uM: float = 0.0,
    vascular_iec_coassembled: bool = True,
    pre_coassembly_vasc_ok: bool = True,
    specimen_id: Optional[str] = None,
    intervention_cohort_id: Optional[str] = None,
    candidate_gene: Optional[str] = None,
    trace_collected_at_utc: Optional[str] = None,
) -> dict[str, Any]:
    def _mk_blocks(offset: float) -> list[dict[str, Any]]:
        blks: list[dict[str, Any]] = []
        for i in range(n_blocks):
            d = 0.04 * (i - 2.5)
            eta_i = 0.84
            z1_v = round(2.1 + offset * 0.25 + 0.12 * d + 0.02 * lot_jitter, 4)
            z2_v = round(1.8 + offset * 0.20 + 0.10 * d + 0.03 * lot_jitter, 4)
            # Peak1/Basal1 ~ 7.5-8.2x (Basal1/Peak1 ~ 0.125 <= 0.15) so Gate 0M fixtures cleanly clear Basal1/Peak1 <= 0.15!
            b1_val = round(0.40 + 0.005 * i + 0.004 * lot_jitter, 4)
            pk_ratio = round(7.6 + offset * 0.4 + d + 0.05 * lot_jitter, 4)
            pk1_val = round(b1_val * pk_ratio, 4)
            l1_val = round(0.42 + 0.005 * i + 0.004 * lot_jitter, 4)
            h1_val = round(l1_val + z1_v / eta_i, 6)
            l2_val = round(0.44 + 0.005 * i + 0.004 * lot_jitter, 4)
            h2_val = round(l2_val + z2_v / eta_i, 6)
            kcl_val = round(h2_val + 1.40 + 0.04 * i + 0.02 * lot_jitter, 6)
            row: dict[str, Any] = {
                "block_id": f"{block_prefix}-{offset:.0f}-{i+1}",
                "trace_id": f"TR-{block_prefix}-{lot_id}-{offset:.0f}-{i+1}",
                "pulse1_si": round(h1_val / l1_val, 4),
                "pulse1_peak_to_basal_ratio": pk_ratio,
                "pulse1_peak_time_min": round(5.2 - offset * 0.3 + 0.1 * i, 4),
                "basal1_value": b1_val,
                "peak1_value": pk1_val,
                "low1_value": l1_val,
                "high1_value": h1_val,
                "low2_value": l2_val,
                "high2_value": h2_val,
                "kcl_value": kcl_val,
                "eta_sort_viable_recovery": eta_i,
                "pulse2_si": round(h2_val / l2_val, 4),
                "z1_increment": round(eta_i * (h1_val - l1_val), 4),
                "z2_increment": round(eta_i * (h2_val - l2_val), 4),
                "ref_adult_z2_increment": round(2.3 + offset * 0.20 + 0.08 * d + 0.015 * lot_jitter, 4),
                "chamber_tau_min": round(0.36 - offset * 0.02 + 0.01 * i, 4),
                "tracer_response_valid": True,
                "tracer_time_aligned": True,
                "stepdown_low2_window_min": 15.0,
                "stepdown_t50_min": round(1.3 - offset * 0.1 + 0.02 * i, 4),
                "stepdown_t90_min": round(2.6 - offset * 0.1 + 0.03 * i, 4),
                "glucagon_fold": round(2.5 + offset * 0.2 + d, 4),
                "glucose_threshold_mM": round(4.9 + 0.05 * i, 4),
                "ucn3_fraction": round(0.82 + 0.01 * i, 4),
                "counterregulation_index": round(0.90 + 0.01 * i, 4),
            }
            if matched_comparator_id is not None:
                mcz2 = round(z2_v / (0.97 + 0.004 * (i - 2.5)), 4)
                row["matched_control_z2_increment"] = mcz2
                row["matched_control_output_ratio"] = round(z2_v / mcz2, 6)
            if rule_s8:
                row["rule_s8_comparator_z2_increment"] = round(z2_v / (0.94 + 0.005 * (i - 2.5)), 4)
            blks.append(row)
        return blks

    out: dict[str, Any] = {
        "canonical_readout2_producer_sha256": "1" * 64,
        "shared_measurement_record_id": meas_id or f"MEAS-R2-{block_prefix}-{matched_comparator_id or 'STD'}",
        "independent_blocks_n": n_blocks,
        "is_non_reference_mixture": (registered_mixture_id != "REF_60_30_10"),
        "registered_mixture_id": registered_mixture_id,
        "beta_cell_fraction": beta_cell_fraction,
        "alpha_cell_fraction": alpha_cell_fraction,
        "delta_cell_fraction": delta_cell_fraction,
        "preparation_process_mode": "SORTED_REAGGREGATED",
        "sorting_performed": True,
        "dual_clocks_utc": {
            "stage7_start_utc": stage7_start_utc,
            "sort_reaggregation_utc": sort_reaggregation_utc,
            "assay_harvest_utc": assay_harvest_utc or ("2026-11-05T00:00:00Z" if rule_s8 else "2026-10-22T00:00:00Z"),
        },
        "alk5i_free_maturation_applied": True,
        "stage7_t3_10nM_and_nac_1mM_retained": True,
        "post_sort_endocrine_zm447439_regimen": post_sort_zm_regimen,
        "post_sort_zm447439_uM": post_sort_zm_uM,
        "vascular_iec_coassembled": vascular_iec_coassembled,
        "pre_coassembly_iec_vascular_function_verified": pre_coassembly_vasc_ok,
        "zm447439_washout_lcms_uM": 0.002,
        "zm447439_wash_cycles": 3,
        "zm447439_spike_recovery_pct": 96.0,
        "eta_sort_viable_recovery_pct": 84.0,
        "implanted_dose_ieq": 500_000.0,
        "mature_insulin_inventory_iu_per_dose": 108.0,
        "insulin_inventory_assay_specificity": "MATURE_INSULIN_SPECIFIC_LOW_PROINSULIN_CROSSREACTIVITY",
        "assay_cumulative_secreted_iu_equiv": 12.5,
        "stored_insulin_per_lot_iu": [round(min(stored_u95_iu, stored_max_iu) - 9.0 + 0.5 * i, 3) for i in range(n_blocks)],
        "proinsulin_to_cpeptide_content_ratio_per_lot": [round(0.042 + 0.002 * i, 4) for i in range(n_blocks)],
        "within_lot_technical_var_z2": 0.008,
        "stored_insulin_u95_iu": stored_u95_iu,
        "stored_insulin_max_lot_iu": stored_max_iu,
        "gate0s_escalation_cleared": gate0s_cleared,
        "gate0m_applicable": gate0m_applicable,
        "z_increment_units": "uIU_per_1000_IEQ_min",
        "z_min_floor": 1.0,
        "o2_40_mmhg": {"blocks": _mk_blocks(0.0)},
        "o2_100_mmhg": {"blocks": _mk_blocks(1.0)},
        "gate_resp1_inlet_po2_mmhg": 35.65,
        "gate_resp1_flow_ul_min": 200.0,
        "gate_resp1_dose_ieq": 200.0,
        "gate_resp1_ocr_pmol_min_ieq": 3.45,
        "gate_resp1_flow_dose_record_sha256": "8" * 64,
        "gate_resp1_snr": 16.5,
        "gate_resp1_po2_drop_mmhg": 3.4,
        "gate_resp1_blank_drift_mmhg": 0.18,
        "gate_resp1_dna_recovery_pct": 93.0,
        "gate_resp1_ocr_ratio": 1.02,
        "gate_resp1_ocr_cv_pct": 2.1,
        "gate_resp1_replicates_n": 6,
        "gate_resp1_whole_prep_ocr_record": (lambda _b: {**_b, "record_sha256": sha256_bytes(canonical_json_bytes(_b))})({
            "specimen_id": f"SPEC-WP-{block_prefix}-{lot_id}", "lot_id": lot_id, "exposure_id": f"EXP-{block_prefix}-{lot_id}",
            "inlet_po2_mmhg": 35.65, "flow_ul_min": 200.0, "dose_ieq": 200.0,
            "ocr_pmol_min_ieq": 3.45, "ocr_ratio": 1.02, "ocr_cv_pct": 2.1, "replicates_n": 6,
        }),
        "gate_resp1_pure_endocrine_ocr_record": (lambda _b: {**_b, "record_sha256": sha256_bytes(canonical_json_bytes(_b))})({
            "specimen_id": f"SPEC-PE-{block_prefix}-{lot_id}", "lot_id": lot_id, "exposure_id": f"EXP-{block_prefix}-{lot_id}",
            "inlet_po2_mmhg": 35.65, "flow_ul_min": 200.0, "dose_ieq": 200.0,
            "ocr_pmol_min_ieq": pure_endocrine_ocr, "ocr_ratio": 0.98, "ocr_cv_pct": 1.9, "replicates_n": 6,
        }),
        "cluster_surface_o2_and_morphometry_record": (lambda _b: {**_b, "record_sha256": sha256_bytes(canonical_json_bytes(_b))})({
            "lot_id": lot_id, "cluster_surface_po2_mmhg": 18.4, "cluster_surface_f_gsis": 0.912,
            "outer_band_z_min_um": 50.0, "outer_band_z_max_um": 175.0,
            "outer_band_d_p90_um": 92.0, "outer_band_sphericity_3d": 0.84,
        }),
        "dec134_washout_time_min_series": [0.0, 1.8, 3.4, 5.8, 9.0, 15.0, 20.0],
        "dec134_washout_remaining_peak_pct_series": [100.0, 70.0, 50.0, 24.0, 10.0, 4.5, 2.5],
        "dec134_washout_raw_trace_sha256": sha256_bytes(canonical_json_bytes({"time_min": [0.0, 1.8, 3.4, 5.8, 9.0, 15.0, 20.0], "remaining_peak_pct": [100.0, 70.0, 50.0, 24.0, 10.0, 4.5, 2.5]})),
        "dec134_washout_trace_span_min": 20.0,
        "dec134_washout_tail_remaining_pct": 2.5,
        "dec134_washout_mass_recovery_pct": 98.0,
        "dec134_washout_t50_min": 3.4,
        "dec134_washout_mean_transit_min": 4.53,
        "dec134_washout_t90_min": 9.0,
    }
    if matched_comparator_id is not None:
        out["matched_comparator_id"] = matched_comparator_id
    if gate0s_receipt is not None:
        out["gate0s_escalation_receipt"] = gate0s_receipt
    if dec084_receipt is not None:
        out["dec084_matched_age_mixture_receipt"] = dec084_receipt
    if rule_s8:
        out["rule_s8_extended_clock_applicable"] = True
        out["rule_s8_locked_analysis_plan_id"] = "PLAN-S8-LOCKED-001"
        out["rule_s8_candidate_windows_k"] = rule_s8_k
        out["rule_s8_window_selection_design"] = rule_s8_design
        out["rule_s8_comparator_receipt_sha256"] = "c" * 64
        t_hv_dt = parse_utc_iso_ts(out["dual_clocks_utc"]["assay_harvest_utc"])
        t_eh_str = (t_hv_dt - timedelta(days=7)).strftime("%Y-%m-%dT%H:%M:%SZ") if t_hv_dt is not None else "2026-10-20T00:00:00Z"
        b40_l = out["o2_40_mmhg"]["blocks"]
        b100_l = out["o2_100_mmhg"]["blocks"]
        out["rule_s8_earlier_window_records"] = [
            {
                "block_id_40mmhg": b40_l[i]["block_id"],
                "block_id_100mmhg": b100_l[i]["block_id"],
                "trace_id_40mmhg": f"TR-EARLY-{block_prefix}-{lot_id}-40-{i+1}",
                "trace_id_100mmhg": f"TR-EARLY-{block_prefix}-{lot_id}-100-{i+1}",
                "early_harvest_utc": t_eh_str,
                "z2_40mmhg": b40_l[i]["rule_s8_comparator_z2_increment"],
                "z2_100mmhg": b100_l[i]["rule_s8_comparator_z2_increment"],
            }
            for i in range(n_blocks)
        ]
        if rule_s8_design == "PILOT_SCREEN_THEN_DISJOINT_CONFIRMATION":
            out["rule_s8_pilot_block_ids"] = ["S8P-1", "S8P-2", "S8P-3"]
    if specimen_id is not None:
        all_tids = [b["trace_id"] for b in out["o2_40_mmhg"]["blocks"]] + [b["trace_id"] for b in out["o2_100_mmhg"]["blocks"]]
        reg_alq = [f"{specimen_id}-ALQ-{i+1}" for i in range(len(all_tids))]
        col_ts = trace_collected_at_utc or out["dual_clocks_utc"]["assay_harvest_utc"]
        r2_pb = {
            "specimen_id": specimen_id,
            "specimen_lot_id": lot_id,
            "intervention_cohort_id": intervention_cohort_id or "COHORT-UNKNOWN",
            "candidate_gene": candidate_gene or "PMAIP1+BCL2L11",
            "registered_aliquot_ids": reg_alq,
            "trace_aliquot_links": [
                {"trace_id": tid, "aliquot_id": alq, "collected_at_utc": col_ts}
                for tid, alq in zip(all_tids, reg_alq)
            ],
        }
        out["readout2_specimen_provenance"] = {**r2_pb, "provenance_sha256": sha256_bytes(canonical_json_bytes(r2_pb))}
    return out


def _mk_r8_readout3b(
    *,
    include_sirpa_low: bool = False,
    matched_vehicle_lot_id: Optional[str] = None,
    include_hla_e_spr: bool = True,
    specimen_id: Optional[str] = None,
    specimen_lot_id: Optional[str] = None,
    intervention_cohort_id: Optional[str] = None,
) -> dict[str, Any]:
    donors: list[dict[str, Any]] = []
    aliquot_ids: list[str] = []
    for i in range(6):
        d = 0.25 * (i - 2.5)
        r1: dict[str, Any] = {
            "nkg2a_pos_nkg2c_neg_kir_neg_lysis_pct": round(4.6 + d, 3),
            "nkg2a_pos_cd107a_degranulation_pct": round(5.8 + d, 3),
            "nkg2c_pos_nkg2a_neg_cd57_pos_lysis_pct": round(6.5 + d, 3),
            "adaptive_nkg2c_kir_pos_lysis_pct": round(6.2 + d, 3),
            "adaptive_nkg2c_kir_neg_lysis_pct": round(6.8 + d, 3),
            "nkg2a_neg_nkg2c_neg_kir_pos_lysis_pct": round(6.1 + d, 3),
            "positive_control_lysis_pct": round(48.0 + i, 3),
            "negative_control_lysis_pct": round(2.1 + 0.1 * i, 3),
        }
        r2: dict[str, Any] = {
            "nkg2a_pos_nkg2c_neg_kir_neg_lysis_pct": round(5.2 + d, 3),
            "nkg2a_pos_cd107a_degranulation_pct": round(6.4 + d, 3),
            "nkg2c_pos_nkg2a_neg_cd57_pos_lysis_pct": round(7.0 + d, 3),
            "adaptive_nkg2c_kir_pos_lysis_pct": round(6.7 + d, 3),
            "adaptive_nkg2c_kir_neg_lysis_pct": round(7.2 + d, 3),
            "nkg2a_neg_nkg2c_neg_kir_pos_lysis_pct": round(6.6 + d, 3),
            "positive_control_lysis_pct": round(52.0 + i, 3),
            "negative_control_lysis_pct": round(2.4 + 0.1 * i, 3),
            "allogeneic_cd8_ctl_lysis_pct": round(2.8 + 0.15 * (i - 2.5), 3),
            "continuous_0_24h_kinetic_trace_verified": True,
            "continuous_0_24h_kinetic_trace": (lambda _tb: {**_tb, "trace_sha256": sha256_bytes(canonical_json_bytes(_tb))})({
                "assay_platform": "INCUCYTE_LIVE_0_24H_IMPEDANCE",
                "specimen_id": (aliquot_ids.append(f"{specimen_id}-ALIQ-D{i+1}") or f"{specimen_id}-ALIQ-D{i+1}") if specimen_id is not None else f"R3B-SPEC-D{i+1}",
                "timepoints_h": [0.0, 4.0, 8.0, 12.0, 18.0, 24.0],
                "target_lysis_pct_series": [0.0, round(1.8 + 0.1 * i, 3), round(3.1 + 0.1 * i, 3), round(4.2 + 0.1 * i, 3), round(4.8 + 0.1 * i, 3), round(5.2 + d, 3)],
            }),
        }
        if include_sirpa_low:
            r1["il12_il18_sirpa_low_lysis_pct"] = round(6.0 + d, 3)
            r2["il12_il18_sirpa_low_lysis_pct"] = round(6.7 + d, 3)
        if matched_vehicle_lot_id is not None:
            r1["veh_nkg2a_pos_lysis_pct"] = round(4.4 + d, 3)
            r1["veh_cd107a_pct"] = round(5.5 + d, 3)
            r1["veh_nkg2c_pos_lysis_pct"] = round(6.2 + d, 3)
            r1["veh_adaptive_kir_pos_lysis_pct"] = round(6.0 + d, 3)
            r1["veh_adaptive_kir_neg_lysis_pct"] = round(6.5 + d, 3)
            r1["veh_kir_pos_lysis_pct"] = round(5.9 + d, 3)
            r2["veh_nkg2a_pos_lysis_pct"] = round(5.0 + d, 3)
            r2["veh_cd107a_pct"] = round(6.1 + d, 3)
            r2["veh_nkg2c_pos_lysis_pct"] = round(6.7 + d, 3)
            r2["veh_adaptive_kir_pos_lysis_pct"] = round(6.4 + d, 3)
            r2["veh_adaptive_kir_neg_lysis_pct"] = round(6.9 + d, 3)
            r2["veh_kir_pos_lysis_pct"] = round(6.4 + d, 3)
            r2["veh_allogeneic_cd8_ctl_lysis_pct"] = round(2.6 + 0.15 * (i - 2.5), 3)
            if include_sirpa_low:
                r1["veh_sirpa_low_lysis_pct"] = round(5.7 + d, 3)
                r2["veh_sirpa_low_lysis_pct"] = round(6.4 + d, 3)
        donors.append({
            "donor_id": f"NK-D{i+1}",
            "cmv_status": "CMV_POS" if i < 3 else "CMV_NEG",
            "regime_i_ifng_24h": r1,
            "regime_ii_t0_unpreinduced": r2,
        })
    out: dict[str, Any] = {
        "canonical_readout3b_producer_sha256": "2" * 64,
        "hla_e_spr_affinity_evidence": (
            {"kd_nkg2a_u95_uM": 2.45, "kd_nkg2a_se_uM": 0.18, "kd_nkg2c_mean_uM": 6.52, "kd_nkg2c_se_uM": 0.42, "spr_artifact_sha256": "7" * 64}
            if include_hla_e_spr else "N/A_NO_HLAE_MODULE"
        ),
        "covalent_hla_e_sct_comparator": (
            (lambda _sb: {**_sb, "comparator_receipt_sha256": sha256_bytes(canonical_json_bytes(_sb))})({
                "comparator_construct_id": "MODEB_COVALENT_HLAE_0103_VMAPRTLVL_REF",
                "hcmv_pos_donor_count": 6,
                "nkg2a_pos_lysis_u95_pct": 5.8,
                "adaptive_kir_pos_lysis_u95_pct": 6.9,
                "adaptive_kir_neg_lysis_u95_pct": 7.1,
                "cd107a_fold_u95": 1.12,
                "ul40_ctl_lysis_u95_pct": 3.2,
                "comparator_verdict": "PASS",
            })
            if include_hla_e_spr else "N/A_NO_HLAE_MODULE"
        ),
        "donor_records": donors,
    }
    if matched_vehicle_lot_id is not None:
        out["matched_vehicle_lot_id"] = matched_vehicle_lot_id
    if specimen_id is not None:
        prov_b = {
            "specimen_id": specimen_id,
            "specimen_lot_id": specimen_lot_id or "LOT-UNKNOWN",
            "intervention_cohort_id": intervention_cohort_id or "COHORT-UNKNOWN",
            "registered_aliquot_ids": aliquot_ids,
        }
        out["assay_specimen_provenance"] = {**prov_b, "provenance_sha256": sha256_bytes(canonical_json_bytes(prov_b))}
    return out


def _mk_r8_mat(prod: str, bank: str, lot: str, ts: str = "2026-10-08T08:00:00Z") -> dict[str, Any]:
    return _sign_receipt({
        "stage": "BANK_MATERIALIZATION", "verdict": "PASS",
        "product_id": prod, "bank_id": bank, "lot_id": lot,
        "evidence_scope": "exact_product", "recorded_at_utc": ts,
        "edited_allele_qc_passed": True,
    })


def _mk_r8_switch(
    prod: str, bank: str, lot: str, route: str, mat_ev: Mapping[str, Any],
    ts: str = "2026-10-12T09:00:00Z",
    *, candidate_gene: Optional[str] = None, comparator_nt_lot_id: Optional[str] = None,
    coating_identity: Optional[Mapping[str, str]] = None,
    prereq_receipts: Optional[Mapping[str, str]] = None,
    transient_engagement: Optional[Mapping[str, Any]] = None,
) -> dict[str, Any]:
    sw_nm = CANONICAL_WAVE6_PRODUCTS[prod]["required_switch"]
    ctrl_lot = comparator_nt_lot_id or (coating_identity["matched_blank_vehicle_lot_id"] if coating_identity else f"CTRL-{lot}")
    body: dict[str, Any] = {
        "stage": "NATIVE_SAFETY_SWITCH", "verdict": "PASS",
        "product_id": prod, "bank_id": bank, "lot_id": lot, "route_id": route,
        "evidence_scope": "exact_product", "recorded_at_utc": ts,
        "parent_receipt_sha256": mat_ev["receipt_sha256"],
        "switch_name": sw_nm,
        "canonical_gate34_producer_sha256": "3" * 64,
        "canonical_gate34_verdict": "PASS",
        "gate34_passed": True,
        "oq012_clonogenic_block": _mk_r8_oq012(),
        "matched_control_switch_parity_evidence": _mk_r8_switch_parity(ctrl_lot),
    }
    if candidate_gene is not None:
        body["candidate_gene"] = candidate_gene
    if comparator_nt_lot_id is not None:
        body["comparator_nt_lot_id"] = comparator_nt_lot_id
    if coating_identity is not None:
        body.update(coating_identity)
    if prereq_receipts is not None:
        body["prerequisite_receipt_sha256s"] = dict(prereq_receipts)
    if transient_engagement is not None:
        body["transient_target_engagement_record"] = dict(transient_engagement)
        body["specimen_id"] = transient_engagement["specimen_id"]
        _t_es = parse_utc_iso_ts(transient_engagement["assay_window_start_utc"])
        _t_ee = parse_utc_iso_ts(transient_engagement["assay_window_end_utc"])
        _t_st_sw = (_t_es + timedelta(minutes=30)) if _t_es else None
        _t_en_sw = (_t_ee - timedelta(minutes=15)) if _t_ee else None
        body["assay_started_at_utc"] = _t_st_sw.strftime("%Y-%m-%dT%H:%M:%SZ") if _t_st_sw else transient_engagement["assay_window_start_utc"]
        body["assay_completed_at_utc"] = _t_en_sw.strftime("%Y-%m-%dT%H:%M:%SZ") if _t_en_sw else transient_engagement["assay_window_end_utc"]
        if _t_st_sw is not None:
            body["assay_24h_collection_utc"] = (_t_st_sw + timedelta(hours=24)).strftime("%Y-%m-%dT%H:%M:%SZ")
            body["assay_72h_collection_utc"] = (_t_st_sw + timedelta(hours=72)).strftime("%Y-%m-%dT%H:%M:%SZ")
    if sw_nm == "DUAL_TBP_ICASP9_PLUS_CDK1_HSVTK":
        body.update({
            "primary_tbp_icasp9_oq012": _mk_r8_oq012(),
            "backup_cdk1_hsvtk_oq012": _mk_r8_oq012(),
            "orthogonal_gcv_cid_non_interference": True,
        })
    return _sign_receipt(body)


def _mk_r8_unit_part(k_total: int, n_total: int, n_units: int = 6) -> list[dict[str, Any]]:
    base_n, rem_n = divmod(n_total, n_units)
    base_k, rem_k = divmod(k_total, n_units)
    return [
        {"unit_id": f"W{i+1}", "k": base_k + (1 if i < rem_k else 0), "n": base_n + (1 if i < rem_n else 0)}
        for i in range(n_units)
    ]


def _mk_r8_gate0v(
    prod: str, bank: str, lot: str, route: str, mat_ev: Mapping[str, Any],
    ts: str = "2026-10-12T09:30:00Z",
    *, candidate_gene: Optional[str] = None, comparator_nt_lot_id: Optional[str] = None,
    coating_identity: Optional[Mapping[str, str]] = None,
    prereq_receipts: Optional[Mapping[str, str]] = None,
    treated_72h_n: int = 120000, veh_72h_k: int = 180, veh_72h_n: int = 200,
    direct_inf_veh_k: int = 120, spike_k: int = 36, spike_n: int = 36,
    tier_override: Optional[str] = None,
    transient_engagement: Optional[Mapping[str, Any]] = None,
) -> dict[str, Any]:
    p_t24 = _mk_r8_unit_part(0, 6000)
    p_v24 = _mk_r8_unit_part(180, 200)
    p_t72 = _mk_r8_unit_part(0, treated_72h_n)
    p_v72 = _mk_r8_unit_part(veh_72h_k, veh_72h_n)
    p_dinf = _mk_r8_unit_part(direct_inf_veh_k, veh_72h_n)
    p_vir = _mk_r8_unit_part(0, treated_72h_n)
    p_sp = _mk_r8_unit_part(spike_k, spike_n)
    rmap: dict[str, dict[str, dict[str, Any]]] = {}
    for rname in sorted(REQUIRED_5_REGIMES):
        lmap: dict[str, dict[str, Any]] = {}
        for lname in sorted(REQUIRED_5_LINEAGES):
            cell: dict[str, Any] = {
                "treated_24h_survivors_k": 0, "treated_24h_input_n": 6000,
                "veh_24h_alive_k": 180, "veh_24h_input_n": 200,
                "treated_72h_survivors_k": 0, "treated_72h_input_n": treated_72h_n,
                "veh_72h_alive_k": veh_72h_k, "veh_72h_input_n": veh_72h_n,
                "per_unit_counts_treated_24h": [dict(u) for u in p_t24],
                "per_unit_counts_veh_24h": [dict(u) for u in p_v24],
                "per_unit_counts_treated_72h": [dict(u) for u in p_t72],
                "per_unit_counts_veh_72h": [dict(u) for u in p_v72],
            }
            if rname in VIRAL_REGIMES:
                cell.update({
                    "aliquot_linkage_mode": "SAME_72H_ALIQUOT",
                    "aliquot_linkage_id": f"ALQ-{lot}-{rname[:4]}-{lname[:4]}",
                    "pre_ap1903_lineage_input_cells_n": treated_72h_n,
                    "post_ap1903_viable_survivors_total_n": 0,
                    "post_ap1903_viable_viral_pos_k": 0,
                    "caspase9_3_fold_over_veh": 8.2,
                    "infected_cell_escape_mode": "DIRECT_INFECTED_VEHICLE_DENOMINATOR",
                    "pretreat_infected_veh_survivor_k": direct_inf_veh_k,
                    "spike_healthy_recovered_k": spike_k, "spike_healthy_input_n": spike_n,
                    "spike_fragile_recovered_k": spike_k, "spike_fragile_input_n": spike_n,
                    "per_unit_counts_direct_infected_veh_72h": [dict(u) for u in p_dinf],
                    "per_unit_counts_viral_pos_72h": [dict(u) for u in p_vir],
                    "per_unit_counts_spike_healthy": [dict(u) for u in p_sp],
                    "per_unit_counts_spike_fragile": [dict(u) for u in p_sp],
                })
            lmap[lname] = cell
        rmap[rname] = lmap
    default_tier = "PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL" if prod == "ISLET1_DESIGN_D1B_LEAN_K2" else "PASS_WHOLEGRAFT_BANK_QUALIFICATION"
    body: dict[str, Any] = {
        "stage": "GATE-0V-KILL", "verdict": "PASS",
        "product_id": prod, "bank_id": bank, "lot_id": lot, "route_id": route,
        "evidence_scope": "exact_product", "recorded_at_utc": ts,
        "parent_receipt_sha256": mat_ev["receipt_sha256"],
        "canonical_gate0v_producer_sha256": "4" * 64,
        "canonical_gate0v_tier": tier_override or default_tier,
        "independent_sampling_unit_class": "RECONCILED_MULTI_WELL_CELL_ASSAY_WITH_UNIT_PARTITION",
        "independent_biological_units_n": 6,
        "clustering_design_effect_deff": 1,
        "exposed_product_tested": True,
        "regime_by_lineage_raw_counts": rmap,
    }
    if candidate_gene is not None:
        body["candidate_gene"] = candidate_gene
    if comparator_nt_lot_id is not None:
        body["comparator_nt_lot_id"] = comparator_nt_lot_id
    if coating_identity is not None:
        body.update(coating_identity)
    if prereq_receipts is not None:
        body["prerequisite_receipt_sha256s"] = dict(prereq_receipts)
    if transient_engagement is not None:
        body["transient_target_engagement_record"] = dict(transient_engagement)
        body["specimen_id"] = transient_engagement["specimen_id"]
        _t_es = parse_utc_iso_ts(transient_engagement["assay_window_start_utc"])
        _t_ee = parse_utc_iso_ts(transient_engagement["assay_window_end_utc"])
        _t_st_sw = (_t_es + timedelta(minutes=30)) if _t_es else None
        _t_en_sw = (_t_ee - timedelta(minutes=15)) if _t_ee else None
        body["assay_started_at_utc"] = _t_st_sw.strftime("%Y-%m-%dT%H:%M:%SZ") if _t_st_sw else transient_engagement["assay_window_start_utc"]
        body["assay_completed_at_utc"] = _t_en_sw.strftime("%Y-%m-%dT%H:%M:%SZ") if _t_en_sw else transient_engagement["assay_window_end_utc"]
        if _t_st_sw is not None:
            body["assay_24h_collection_utc"] = (_t_st_sw + timedelta(hours=24)).strftime("%Y-%m-%dT%H:%M:%SZ")
            body["assay_72h_collection_utc"] = (_t_st_sw + timedelta(hours=72)).strftime("%Y-%m-%dT%H:%M:%SZ")
    return _sign_receipt(body)


def _mk_r8_gate31(
    prod: str, bank: str, lot: str, mat_ev: Optional[Mapping[str, Any]] = None,
    *, coating_stab: Optional[bool] = True, ts: str = "2026-10-12T09:45:00Z",
) -> dict[str, Any]:
    pblks = [
        {"block_id": f"G31-B{i+1}", "open_sink_t_half_h": oh, "limited_exchange_t_half_h": lh}
        for i, (lh, oh) in enumerate([(54.0, 44.5), (55.2, 45.8), (56.0, 46.4), (56.5, 47.0), (57.1, 47.4), (57.2, 47.9)])
    ]
    diffs = [b["open_sink_t_half_h"] - 0.50 * b["limited_exchange_t_half_h"] for b in pblks]
    l95_c = paired_t_summary(diffs)[3]
    os_vals = [b["open_sink_t_half_h"] for b in pblks]
    os_b = sample_t_one_sided_bounds(os_vals, alpha=0.025)
    body: dict[str, Any] = {
        "stage": "GATE-31", "verdict": "PASS",
        "product_id": prod, "bank_id": bank, "lot_id": lot, "route_id": "R1",
        "evidence_scope": "exact_product", "recorded_at_utc": ts,
        "canonical_gate31_producer_sha256": "5" * 64,
        "bead_psd_lot_id": lot, "barrier_film_lot_id": lot,
        "kinetics_336h_lot_id": lot, "open_sink_lot_id": lot,
        "reconciled_slab_geometry_mode": "EXPANDED_390UM_2X125UM_BANDS",
        "kinetics_assay_regime": "PAIRED_LIMITED_EXCHANGE_AND_OPEN_SINK",
        "bead_d99_u95_um": 46.0, "bead_d50_um": 32.0, "crystal_d99_um": 12.0,
        "barrier_geometry_mode": "PLANAR_CO_CAST_LAMINA_FACE_HYDROGEL_FILM",
        "barrier_thickness_l95_um": 22.0, "catalase_uniprot_id": "P04040",
        "conserved_cao2_loading_mg": 791.5,
        "cumulative_sub15_mmhg_duration_h": 1.8,
        "hard_hypoxia_floor_min_po2_mmhg": 13.6,
        "whole_device_washout_dec134": {
            "time_min_series": [0.0, 1.8, 3.4, 5.8, 9.0, 15.0, 20.0],
            "remaining_peak_pct_series": [100.0, 70.0, 50.0, 24.0, 10.0, 4.5, 2.5],
            "raw_trace_sha256": sha256_bytes(canonical_json_bytes({"time_min": [0.0, 1.8, 3.4, 5.8, 9.0, 15.0, 20.0], "remaining_peak_pct": [100.0, 70.0, 50.0, 24.0, 10.0, 4.5, 2.5]})),
            "trace_span_min": 20.0, "tail_remaining_pct": 2.5, "mass_recovery_pct": 98.5,
            "t50_min": 3.4, "mean_transit_min": 4.53, "t90_min": 9.0,
        },
        "vascular_midpoint_horizon_h": 60.0, "halflife_l95_h": 52.08, "halflife_u95_h": 59.92,
        "kinetic_law_code": 0, "hour0_24_o2_ratio_l95": 0.85, "hour0_72_o2_cum_frac_l95": 0.30,
        "h2o2_z70_u95_uM": 1.4,
        "obs_h2o2_measurement_site": "BARRIER_TISSUE_INTERFACE_Z_70P0_UM", "obs_h2o2_z_um": 70.0,
        "day7_catalase_retention_l95_pct": 82.0, "day14_catalase_retained_l95_iu": 80000.0,
        "pre_cure_catalase_load_iu_333cm2": 148000.0,
        "gate31c_paired_blocks": pblks,
        "gate31c_open_minus_half_limited_l95_h": round(l95_c, 8),
        "gate31c_open_sink_halflife_l95_h": round(os_b[1], 4),
        "gate31c_open_sink_halflife_u95_h": round(os_b[2], 4),
        "gate31c_open_sink_h2o2_u95_uM": 1.6,
        "obs_open_sink_h2o2_measurement_site": "BARRIER_TISSUE_INTERFACE_Z_70P0_UM", "obs_open_sink_h2o2_z_um": 70.0,
    }
    if mat_ev is not None:
        body["parent_receipt_sha256"] = mat_ev["receipt_sha256"]
    if coating_stab is not None:
        body["coating_stability_verified"] = coating_stab
        if coating_stab is True:
            body["coating_stability_evidence"] = {
                "day14_barrier_thickness_retention_pct": 98.5,
                "day14_catalase_retention_ratio_vs_uncoated": 0.98,
                "o2_permeability_ratio_vs_uncoated": 0.99,
                "coating_delamination_events": 0,
            }
    return _sign_receipt(body)


def _mk_r8_hour0(prod: str, lineages: FrozenSet[str] = REQUIRED_HOUR0_LINEAGES_FULL) -> dict[str, dict[str, Any]]:
    sp = CANONICAL_WAVE6_PRODUCTS[prod]
    out: dict[str, dict[str, Any]] = {}
    for lin in sorted(lineages):
        row: dict[str, Any] = {
            "hlae_molecules_per_cell": 22000.0 if sp["hla_e_engineered"] else "N/A_CONSTRUCT_LACKS_HLAE_MODULE",
            "cd47_median_molecules_per_cell": 240000.0 if sp["cd47_engineered"] else "N/A_CONSTRUCT_LACKS_CD47_MODULE",
            "cd47_p10_molecules_per_cell": 195000.0 if sp["cd47_engineered"] else "N/A_CONSTRUCT_LACKS_CD47_MODULE",
        }
        if sp["autologous_self_hla"]:
            row["autologous_hla_abc_preservation_pct"] = 94.0
        out[lin] = row
    return out


def _mk_r8_shields(prod: str, val: float = 92.5) -> dict[str, float]:
    return {c: val for c in sorted(SHIELD_COMPONENTS_BY_PRODUCT[prod])}


def _mk_r8_pfd_trace(horizon_h: float = 840.0) -> tuple[list[float], list[float]]:
    # Unified mass balance on initial_pirfenidone_loading_mg = 18.75 mg:
    # 24h = 1.80 mg (9.6% burst <= 15%), 336h = 13.50 mg (72.0% usable <= 85%),
    # 840h = 17.60 mg (t50 crosses 8.80 mg inside [216h, 264h] = [9.0d, 11.0d], linear t50 = 9.75 d),
    # supremum burst Cmax <= 0.08 ug/mL (< 0.20), max 24-h rate <= 1.80 mg/d!
    if horizon_h <= 336.0:
        times = [0.0, 1.0, 3.0, 6.0, 12.0, 24.0, 48.0, 72.0, 120.0, 168.0, 216.0, 264.0, 336.0]
        cum = [0.0, 0.20, 0.45, 0.75, 1.20, 1.80, 3.00, 4.10, 5.70, 7.10, 8.30, 10.10, 13.50]
    else:
        times = [0.0, 1.0, 3.0, 6.0, 12.0, 24.0, 48.0, 72.0, 120.0, 168.0, 216.0, 264.0, 336.0, 432.0, 528.0, 672.0, 840.0]
        cum = [0.0, 0.20, 0.45, 0.75, 1.20, 1.80, 3.00, 4.10, 5.70, 7.10, 8.30, 10.10, 13.50, 15.20, 16.30, 17.20, 17.60]
    return times, cum


def _mk_r8_a4b_prereg_and_cohorts(
    prod: str, bank: str, lot: str, route: str, a4a_ev: Mapping[str, Any], coat: Mapping[str, str],
    *, start_dt_str: str = "2026-12-20T08:00:00Z", prereg_ts: str = "2026-12-18T08:00:00Z",
    mode: str = "TERMINAL_HISTOLOGY",
) -> tuple[dict[str, Any], dict[str, Any]]:
    st = parse_utc_iso_ts(start_dt_str)
    early_recs: list[dict[str, Any]] = []
    d28_recs: list[dict[str, Any]] = []
    roster: dict[str, str] = {}
    early_assigned: list[str] = []
    d28_assigned: list[str] = []
    for i in range(8):
        imp_ts = (st + timedelta(hours=i)).strftime("%Y-%m-%dT%H:%M:%SZ")
        ep = (st + timedelta(hours=48 + i)).strftime("%Y-%m-%dT%H:%M:%SZ")
        dp = (st + timedelta(days=28, hours=i)).strftime("%Y-%m-%dT%H:%M:%SZ")
        ec_id = f"L-COAT-{i+1:02d}" if mode == "VALIDATED_NONTERMINAL_LONGITUDINAL_IMAGING" else f"E-COAT-{i+1:02d}"
        ev_id = f"L-VEH-{i+1:02d}" if mode == "VALIDATED_NONTERMINAL_LONGITUDINAL_IMAGING" else f"E-VEH-{i+1:02d}"
        dc_id = ec_id if mode == "VALIDATED_NONTERMINAL_LONGITUDINAL_IMAGING" else f"D28-COAT-{i+1:02d}"
        dv_id = ev_id if mode == "VALIDATED_NONTERMINAL_LONGITUDINAL_IMAGING" else f"D28-VEH-{i+1:02d}"
        roster[ec_id] = "COATED"; roster[ev_id] = "BLANK_VEHICLE"
        roster[dc_id] = "COATED"; roster[dv_id] = "BLANK_VEHICLE"
        early_assigned.extend([ec_id, ev_id])
        d28_assigned.extend([dc_id, dv_id])
        early_recs.append({"animal_id": ec_id, "arm": "COATED", "implanted_at_utc": imp_ts, "assessed_at_utc": ep, "raw_lectin_perfusion_signal": round(104.0 + 1.0 * (i - 3.5), 3), "adverse_event_code": "NONE"})
        early_recs.append({"animal_id": ev_id, "arm": "BLANK_VEHICLE", "implanted_at_utc": imp_ts, "assessed_at_utc": ep, "raw_lectin_perfusion_signal": round(100.0 + 0.9 * (i - 3.5), 3), "adverse_event_code": "NONE"})
        d28_recs.append({"animal_id": dc_id, "arm": "COATED", "implanted_at_utc": imp_ts, "assessed_at_utc": dp, "pericapsular_collagen_thickness_um": round(58.0 + 1.5 * (i - 3.5), 3), "raw_lectin_vessel_density": round(106.0 + 1.0 * (i - 3.5), 3), "adverse_event_code": "NONE"})
        d28_recs.append({"animal_id": dv_id, "arm": "BLANK_VEHICLE", "implanted_at_utc": imp_ts, "assessed_at_utc": dp, "pericapsular_collagen_thickness_um": round(100.0 + 1.8 * (i - 3.5), 3), "raw_lectin_vessel_density": round(100.0 + 0.9 * (i - 3.5), 3), "adverse_event_code": "NONE"})
    prereg = _sign_receipt({
        "stage": "A-4b-PREREGISTRATION", "verdict": "PASS",
        "product_id": prod, "bank_id": bank, "lot_id": lot, "route_id": route,
        "evidence_scope": "exact_product", "recorded_at_utc": prereg_ts,
        "parent_receipt_sha256": a4a_ev["receipt_sha256"], **coat,
        "early_assay_mode": mode,
        "primary_collagen_endpoint": "PERICAPSULAR_COLLAGEN_THICKNESS_UM",
        "randomized_animal_roster": roster,
        "early_cohort_assigned_ids": early_assigned,
        "day28_cohort_assigned_ids": d28_assigned,
        "max_attrition_rate_pct": 15.0,
        "max_arm_attrition_diff_pp": 10.0,
        "exclusion_timing_cutoff_rule": "LOCKED_BEFORE_HISTOLOGY_UNBLINDING",
        "missing_data_sensitivity_rule": "WORST_CASE_TIPPING_POINT_BOUND",
        "perfusion_normalization_scale": "VEHICLE_CONTROL_MEAN_PCT",
        "tipping_point_collagen_bounds_um": [20.0, 1500.0],
        "tipping_point_perfusion_bounds_pct": [0.0, 200.0],
    })
    unblind_ts = (st + timedelta(days=30)).strftime("%Y-%m-%dT%H:%M:%SZ")
    cohorts = {
        "histology_unblinding_utc": unblind_ts,
        "early_assay_mode": mode,
        "early_cohort_enrolled_coated_n": 8, "early_cohort_enrolled_vehicle_n": 8,
        "early_cohort_exclusions": [], "early_cohort_records": early_recs,
        "day28_cohort_enrolled_coated_n": 8, "day28_cohort_enrolled_vehicle_n": 8,
        "day28_cohort_exclusions": [], "day28_cohort_records": d28_recs,
    }
    return prereg, cohorts


def _mk_r8_a4b_cohorts(start_dt_str: str = "2026-12-20T08:00:00Z") -> dict[str, Any]:
    st = parse_utc_iso_ts(start_dt_str)
    early_recs: list[dict[str, Any]] = []
    d28_recs: list[dict[str, Any]] = []
    for i in range(8):
        imp_ts = (st + timedelta(hours=i)).strftime("%Y-%m-%dT%H:%M:%SZ")
        ep = (st + timedelta(hours=48 + i)).strftime("%Y-%m-%dT%H:%M:%SZ")
        dp = (st + timedelta(days=28, hours=i)).strftime("%Y-%m-%dT%H:%M:%SZ")
        early_recs.append({"animal_id": f"E-COAT-{i+1:02d}", "arm": "COATED", "implanted_at_utc": imp_ts, "assessed_at_utc": ep, "raw_lectin_perfusion_signal": round(104.0 + 1.0 * (i - 3.5), 3), "adverse_event_code": "NONE"})
        early_recs.append({"animal_id": f"E-VEH-{i+1:02d}", "arm": "BLANK_VEHICLE", "implanted_at_utc": imp_ts, "assessed_at_utc": ep, "raw_lectin_perfusion_signal": round(100.0 + 0.9 * (i - 3.5), 3), "adverse_event_code": "NONE"})
        d28_recs.append({"animal_id": f"D28-COAT-{i+1:02d}", "arm": "COATED", "implanted_at_utc": imp_ts, "assessed_at_utc": dp, "pericapsular_collagen_thickness_um": round(58.0 + 1.5 * (i - 3.5), 3), "raw_lectin_vessel_density": round(106.0 + 1.0 * (i - 3.5), 3), "adverse_event_code": "NONE"})
        d28_recs.append({"animal_id": f"D28-VEH-{i+1:02d}", "arm": "BLANK_VEHICLE", "implanted_at_utc": imp_ts, "assessed_at_utc": dp, "pericapsular_collagen_thickness_um": round(100.0 + 1.8 * (i - 3.5), 3), "raw_lectin_vessel_density": round(100.0 + 0.9 * (i - 3.5), 3), "adverse_event_code": "NONE"})
    return {
        "early_assay_mode": "TERMINAL_HISTOLOGY",
        "early_cohort_enrolled_coated_n": 8, "early_cohort_enrolled_vehicle_n": 8,
        "early_cohort_exclusions": [], "early_cohort_records": early_recs,
        "day28_cohort_enrolled_coated_n": 8, "day28_cohort_enrolled_vehicle_n": 8,
        "day28_cohort_exclusions": [], "day28_cohort_records": d28_recs,
    }


def _mk_r8_b2_donors() -> list[dict[str, Any]]:
    rows: list[dict[str, Any]] = []
    for i in range(6):
        # Raw paired values giving TAT red ~34%, C3a red ~32%, Plt rec ~26 pp with robust LOO!
        rows.append({
            "donor_id": f"D{i+1}",
            "pos_ctrl_tat_fold": round(4.0 + 0.1 * i, 3),
            "pos_ctrl_c3a_fold": round(3.0 + 0.1 * i, 3),
            "pos_ctrl_plt_drop_pct": round(42.0 + 1.5 * i, 3),
            "neg_ctrl_tat_fold": round(1.02 + 0.03 * i, 3),
            "neg_ctrl_plt_retention_pct": round(95.0 - 0.5 * i, 3),
            "tat_vehicle_ng_ml": round(100.0 + 4.0 * i, 3),
            "tat_coated_ng_ml": round((100.0 + 4.0 * i) * (0.66 - 0.015 * (i - 2.5)), 3),
            "c3a_vehicle_ng_ml": round(200.0 + 8.0 * i, 3),
            "c3a_coated_ng_ml": round((200.0 + 8.0 * i) * (0.68 - 0.015 * (i - 2.5)), 3),
            "platelet_baseline_k_ul": 250.0,
            "platelet_vehicle_k_ul": round(125.0 + 3.0 * (i - 2.5), 3),
            "platelet_coated_k_ul": round(192.0 + 5.0 * (i - 2.5), 3),
        })
    return rows


def _mk_r8_b2b_replicates(
    *, coating_article_id: str = "ART-DEUC-R3P-01", evidence_scope: str = "bench_unedited",
) -> dict[str, Any]:
    # Time-indexed independent replicates across Burst -> Day 10 -> Day 21 washout (K=7, n=6 each) + parent-specific envelope!
    def _tp(h: float, lp: float, lb: float, rb: float, sp: float, sb: float) -> dict[str, Any]:
        lp_r = [round(lp * (1.0 + d), 4) for d in (-0.012, -0.007, -0.002, 0.002, 0.007, 0.012)]
        lb_r = [round(lb * (1.0 + d), 5) for d in (-0.02, -0.01, 0.0, 0.0, 0.01, 0.02)]
        rb_r = [round(rb * (1.0 + d), 5) for d in (-0.02, -0.01, 0.0, 0.0, 0.01, 0.02)]
        sp_r = [round(sp * (1.0 + d), 5) for d in (-0.02, -0.01, 0.0, 0.0, 0.01, 0.02)]
        sb_r = [round(sb * (1.0 + d), 5) for d in (-0.02, -0.01, 0.0, 0.0, 0.01, 0.02)]
        _stage_pfx = "B2-BLD" if abs(h - 2.0) <= 1e-6 else "B1-ELU"
        return {
            "hour_h": h,
            "source_sample_ids": [f"{_stage_pfx}-H{int(h)}-R{ri}" for ri in range(1, len(lp_r) + 1)],
            "biological_unit_ids": [f"{_stage_pfx}-UNIT-{ri}" for ri in range(1, len(lp_r) + 1)],
            "local_parent_total_replicates_nM": lp_r, "local_parent_blq_flags": [v < 0.05 for v in lp_r],
            "local_bmt_total_replicates_nM": lb_r, "local_bmt_blq_flags": [v < 0.05 for v in lb_r],
            "recirc_bmt_total_replicates_nM": rb_r, "recirc_bmt_blq_flags": [v < 0.05 for v in rb_r],
            "systemic_parent_total_replicates_nM": sp_r, "systemic_parent_blq_flags": [v < 0.05 for v in sp_r],
            "systemic_bmt_total_replicates_nM": sb_r, "systemic_bmt_blq_flags": [v < 0.05 for v in sb_r],
        }
    return {
        "local_assay_matrix": "human_serum_100pct",
        "recirc_assay_matrix": "human_serum_100pct",
        "local_measurement_includes_recirculation": True,
        "fu_parent_replicates": [0.138, 0.139, 0.140, 0.140, 0.141, 0.142],
        "fu_bmt_replicates": [0.148, 0.149, 0.150, 0.150, 0.151, 0.152],
        "intersample_pk_envelope": (lambda _eb: {**_eb, "envelope_receipt_sha256": sha256_bytes(canonical_json_bytes(_eb))})({
            "k_elim_local_max_per_h": 0.018,
            "k_rise_local_max_per_h": 0.003,
            "k_elim_parent_max_per_h": 0.004,
            "k_rise_parent_max_per_h": 0.002,
            "k_elim_bmt_max_per_h": 0.018,
            "k_rise_bmt_max_per_h": 0.003,
            "k_elim_sys_max_per_h": 0.025,
            "k_rise_sys_max_per_h": 0.003,
            "efficacy_window_start_h": 0.0,
            "envelope_model_sha256": "e" * 64,
            "coating_article_id": coating_article_id,
            "evidence_scope": evidence_scope,
            "compartment_id": "BENCH_ELUTION_RECIRCULATION",
            "envelope_qualification_method": "DENSE_PILOT_TIMECOURSE_BOUND",
            "pilot_sampling_max_gap_h": 1.0,
            "burst_phase_covered": True,
            "washout_phase_covered": True,
            "source_study_ids": ["PK-BENCH-ELUTION-001", "PK-BENCH-WASHOUT-001"],
        }),
        "timepoint_replicate_records": [
            _tp(2.0, 110.0, 0.022, 0.018, 0.032, 0.012),
            _tp(72.0, 90.0, 0.020, 0.016, 0.026, 0.010),
            _tp(144.0, 76.0, 0.018, 0.015, 0.022, 0.010),
            _tp(240.0, 63.0, 0.016, 0.014, 0.018, 0.009),
            _tp(336.0, 26.8, 0.014, 0.012, 0.014, 0.008),
            _tp(432.0, 10.4, 0.012, 0.011, 0.010, 0.008),
            _tp(504.0, 3.3, 0.010, 0.010, 0.009, 0.008),
        ],
    }


def _mk_r8_b4_replicates(
    hours: Sequence[float],
    lp_free: Sequence[float],
    lb_free: Sequence[float],
    sp_tot: Sequence[float],
    sb_tot: Sequence[float],
) -> dict[str, Any]:
    fp_r = [0.138, 0.139, 0.140, 0.140, 0.141, 0.142]
    fb_r = [0.148, 0.149, 0.150, 0.150, 0.151, 0.152]
    m_fp = sum(fp_r) / len(fp_r)
    m_fb = sum(fb_r) / len(fb_r)
    tps: list[dict[str, Any]] = []
    for h, lpf, lbf, spt, sbt in zip(hours, lp_free, lb_free, sp_tot, sb_tot):
        base_lp = lpf / m_fp
        base_lb = lbf / m_fb
        lp_reps = [round(base_lp * (1.0 + d), 4) for d in (-0.012, -0.007, -0.002, 0.002, 0.007, 0.012)]
        lb_reps = [round(base_lb * (1.0 + d), 5) for d in (-0.02, -0.01, 0.0, 0.0, 0.01, 0.02)]
        sp_reps = [round(spt * (1.0 + d), 5) for d in (-0.02, -0.01, 0.0, 0.0, 0.01, 0.02)]
        sb_reps = [round(sbt * (1.0 + d), 5) for d in (-0.02, -0.01, 0.0, 0.0, 0.01, 0.02)]
        tps.append({
            "hour_h": float(h),
            "animal_ids": [f"NSG-PK-{j+1:02d}" for j in range(len(lp_reps))],
            "analyte_pairing_mode": "PAIRED_WITHIN_SAME_ANIMAL_SAMPLE",
            "local_parent_total_replicates_nM": lp_reps,
            "local_parent_blq_flags": [v < 0.05 for v in lp_reps],
            "local_bmt_total_replicates_nM": lb_reps,
            "local_bmt_blq_flags": [v < 0.05 for v in lb_reps],
            "systemic_parent_total_replicates_nM": sp_reps,
            "systemic_parent_blq_flags": [v < 0.05 for v in sp_reps],
            "systemic_bmt_total_replicates_nM": sb_reps,
            "systemic_bmt_blq_flags": [v < 0.05 for v in sb_reps],
        })
    loc_cal_b = {
        "compartment_matrix_id": "PERI_GRAFT_INTERSTITIAL_FLUID",
        "concentration_basis": "RECOVERY_CORRECTED_TOTAL_MATRIX_CONVERTED_BY_LOCAL_FU",
        "pre_submission_recovery_correction_applied": True,
        "species_id": "NSG_MOUSE",
        "analytical_method_id": "LCMSMS-DEUC-ISF-V1",
        "lloq_parent_nM": 0.05,
        "lloq_bmt_nM": 0.05,
        "probe_or_extraction_recovery_pct": 88.5,
        "spike_accuracy_pct": 97.0,
        "method_validated": True,
        "fu_parent_replicates": fp_r,
        "fu_bmt_replicates": fb_r,
    }
    sys_cal_b = {
        "compartment_matrix_id": "SYSTEMIC_PLASMA",
        "species_id": "NSG_MOUSE",
        "analytical_method_id": "LCMSMS-DEUC-PLASMA-V1",
        "lloq_parent_nM": 0.05,
        "lloq_bmt_nM": 0.05,
        "spike_accuracy_pct": 98.5,
        "method_validated": True,
        "fu_parent_replicates": [0.135, 0.138, 0.140, 0.141, 0.143, 0.145],
        "fu_bmt_replicates": [0.145, 0.148, 0.150, 0.151, 0.153, 0.155],
    }
    env_b4 = {
        "k_elim_local_max_per_h": 0.018,
        "k_rise_local_max_per_h": 0.003,
        "k_elim_parent_max_per_h": 0.012,
        "k_rise_parent_max_per_h": 0.002,
        "k_elim_bmt_max_per_h": 0.018,
        "k_rise_bmt_max_per_h": 0.003,
        "k_elim_sys_max_per_h": 0.0693,
        "k_rise_sys_max_per_h": 0.003,
        "efficacy_window_start_h": 0.0,
        "envelope_model_sha256": "f" * 64,
        "coating_article_id": "ART-DEUC-R3P-01",
        "evidence_scope": "exact_product",
        "compartment_id": "INVIVO_PERIGRAFT_AND_SYSTEMIC",
        "envelope_qualification_method": "DENSE_PILOT_TIMECOURSE_BOUND",
        "pilot_sampling_max_gap_h": 1.0,
        "burst_phase_covered": True,
        "washout_phase_covered": True,
        "source_study_ids": ["PK-INVIVO-NSG-001", "PK-INVIVO-WASHOUT-001"],
    }
    return {
        "b4_local_compartment_calibration": {**loc_cal_b, "calibration_sha256": sha256_bytes(canonical_json_bytes(loc_cal_b))},
        "b4_systemic_compartment_calibration": {**sys_cal_b, "calibration_sha256": sha256_bytes(canonical_json_bytes(sys_cal_b))},
        "intersample_pk_envelope": {**env_b4, "envelope_receipt_sha256": sha256_bytes(canonical_json_bytes(env_b4))},
        "timepoint_replicate_records": tps,
    }


def _mk_r8_c1_block(
    *,
    assay_record_id: str,
    bids: list[str],
    c9_vec: list[float],
    ctrl_vec: list[float],
    tr_vec: list[float],
    veh_vec: list[float],
    comp_vec: list[float],
    target: str = "PMAIP1+BCL2L11",
    stat_method: str = "PAIRED_T_TEST_NORMALITY_VERIFIED",
    target_kd: float = 82.0,
    nonbeta_surv: float = 95.0,
    ctrl_nonbeta: float = 72.0,
    jak2_shield_pct: Optional[float] = None,
    assay_acquired_at_utc: str = "2026-09-19T12:00:00Z",
    batch_prefix: str = "C1-NBAT",
    product_id: str = "ISLET1_DESIGN_Y_V3",
    specimen_lot_id: str = "LOT-Y-001",
    intervention_cohort_id: str = "COHORT-GY032-Y-001",
) -> dict[str, Any]:
    n = len(bids)
    c9_ctrl_raw = [round(100.0 + 2.0 * (i % 4), 4) for i in range(n)]
    c9_tr_raw = [round(c9_ctrl_raw[i] * (1.0 - c9_vec[i] / 100.0), 4) for i in range(n)]
    c9_red_exact = [round(100.0 * (c9_ctrl_raw[i] - c9_tr_raw[i]) / c9_ctrl_raw[i], 4) for i in range(n)]
    def _pct_to_counts(pvec: Sequence[float], plated: int = 10000) -> tuple[list[int], list[int]]:
        return [plated for _ in pvec], [int(round(plated * float(x) / 100.0)) for x in pvec]

    ctrl_p0_b, ctrl_sv_b = _pct_to_counts(ctrl_vec)
    tr_p0_b, tr_sv_b = _pct_to_counts(tr_vec)
    veh_p0_b, veh_sv_b = _pct_to_counts(veh_vec)
    five_arms: dict[str, dict[str, Any]] = {}
    for idx, gname in enumerate(sorted(C1_FAMILY_GENES)):
        if gname == target:
            five_arms[gname] = {
                "treated_beta_plated_t0_by_block": list(tr_p0_b),
                "treated_beta_surviving_by_block": list(tr_sv_b),
                "treated_beta_t0_pct_by_block": list(tr_vec),
                "casp9_treated_raw_by_block": list(c9_tr_raw),
                "casp9_reduction_pct_by_block": list(c9_red_exact),
            }
        elif gname == "BCL2L11" and target == "PMAIP1+BCL2L11":
            q_prof = [_std_normal_inv_cdf((i + 1.0 - 0.375) / (n + 0.25)) for i in range(n)]
            red_b = [round(24.0 + 5.2 * q_prof[i], 3) for i in range(n)]
            raw_b = [round(c9_ctrl_raw[i] * (1.0 - red_b[i] / 100.0), 4) for i in range(n)]
            cp0, csv = _pct_to_counts(comp_vec)
            five_arms[gname] = {
                "treated_beta_plated_t0_by_block": cp0,
                "treated_beta_surviving_by_block": csv,
                "treated_beta_t0_pct_by_block": list(comp_vec),
                "casp9_treated_raw_by_block": raw_b,
                "casp9_reduction_pct_by_block": [round(100.0 * (c9_ctrl_raw[i] - raw_b[i]) / c9_ctrl_raw[i], 4) for i in range(n)],
            }
        else:
            shift = 1.5 + 0.5 * idx
            q_prof = [_std_normal_inv_cdf((i + 1.0 - 0.375) / (n + 0.25)) for i in range(n)]
            red_o = [round(10.0 + 2.5 * idx + 9.0 * q_prof[(i + idx) % n], 3) for i in range(n)]
            raw_o = [round(c9_ctrl_raw[i] * (1.0 - red_o[i] / 100.0), 4) for i in range(n)]
            ab_o = [min(100.0, max(0.0, round(ctrl_vec[i] + shift + 2.6 * q_prof[(i + idx) % n], 3))) for i in range(n)]
            op0, osv = _pct_to_counts(ab_o)
            five_arms[gname] = {
                "treated_beta_plated_t0_by_block": op0,
                "treated_beta_surviving_by_block": osv,
                "treated_beta_t0_pct_by_block": ab_o,
                "casp9_treated_raw_by_block": raw_o,
                "casp9_reduction_pct_by_block": [round(100.0 * (c9_ctrl_raw[i] - raw_o[i]) / c9_ctrl_raw[i], 4) for i in range(n)],
            }
    fam_b: dict[str, float] = {}
    fam_c: dict[str, float] = {}
    ctrl_fracs_m = [Fraction(int(sv) * 100, int(p0)) for p0, sv in zip(ctrl_p0_b, ctrl_sv_b)]
    for gname, adata in five_arms.items():
        ab_fracs_m = [Fraction(int(sv) * 100, int(p0)) for p0, sv in zip(adata["treated_beta_plated_t0_by_block"], adata["treated_beta_surviving_by_block"])]
        ac_g = adata["casp9_treated_raw_by_block"]
        if sum((ab_fracs_m[i] - ctrl_fracs_m[i] for i in range(n)), Fraction(0, 1)) <= 0:
            fam_b[gname] = 1.0
        else:
            pb, _ = _compute_c1_arm_raw_p(ab_fracs_m, stat_method, paired_control=ctrl_fracs_m)
            fam_b[gname] = 1.0 if pb is None else pb
        if sum(c9_ctrl_raw[i] - ac_g[i] for i in range(n)) <= 0.0:
            fam_c[gname] = 1.0
        else:
            pc, _ = _compute_c1_arm_raw_p(c9_ctrl_raw, stat_method, paired_control=ac_g)
            fam_c[gname] = 1.0 if pc is None else pc
    holm_b = holm_bonferroni_adjust(fam_b)[target]
    holm_c = holm_bonferroni_adjust(fam_c)[target]
    blk: dict[str, Any] = {
        "assay_record_id": assay_record_id,
        "assay_acquired_at_utc": assay_acquired_at_utc,
        "block_ids": bids,
        "differentiation_batch_ids": [f"{batch_prefix}-{i+1}" for i in range(n)],
        "randomized_arm_orders_by_block": [sorted(C1_FAMILY_GENES | {"NT_CTRL"}) for _ in range(n)],
        "target_kd_pct": target_kd,
        "mrna_kd_pct": round(min(100.0, target_kd + 2.0), 2) if target != "JAK2" else target_kd,
        "protein_kd_pct": target_kd,
        "mrna_assay_record_id": f"{assay_record_id}-QPCR",
        "protein_assay_record_id": f"{assay_record_id}-PROT",
        "molecular_kd_provenance": (lambda _kb: {**_kb, "producer_record_sha256": sha256_bytes(canonical_json_bytes(_kb))})({
            "product_id": product_id,
            "specimen_id": f"SPEC-C1-KD-{assay_record_id}-{specimen_lot_id}",
            "specimen_lot_id": specimen_lot_id,
            "intervention_cohort_id": intervention_cohort_id,
            "candidate_gene": target,
            "mrna_assay_record_id": f"{assay_record_id}-QPCR",
            "protein_assay_record_id": f"{assay_record_id}-PROT",
            "mrna_kd_pct": round(min(100.0, target_kd + 2.0), 2) if target != "JAK2" else target_kd,
            "protein_kd_pct": target_kd,
            "measured_at_utc": assay_acquired_at_utc,
            "target_observations": [
                (lambda _ob: {**_ob, "producer_observation_sha256": sha256_bytes(canonical_json_bytes(_ob))})({
                    "target_gene": _tg, "analyte_type": _an, "assay_record_id": _aid,
                    "product_id": product_id,
                    "specimen_id": f"SPEC-C1-KD-{assay_record_id}-{specimen_lot_id}",
                    "specimen_lot_id": specimen_lot_id,
                    "intervention_cohort_id": intervention_cohort_id,
                    "kd_pct": _kv, "measured_at_utc": assay_acquired_at_utc,
                })
                for _tg, _an, _aid, _kv in (
                    [
                        ("PMAIP1", "mRNA", f"{assay_record_id}-PMAIP1-QPCR", round(min(100.0, target_kd + 2.0), 2)),
                        ("PMAIP1", "protein", f"{assay_record_id}-PMAIP1-PROT", target_kd),
                        ("BCL2L11", "mRNA", f"{assay_record_id}-BCL2L11-QPCR", round(min(100.0, target_kd + 4.0), 2)),
                        ("BCL2L11", "protein", f"{assay_record_id}-BCL2L11-PROT", round(min(100.0, target_kd + 2.0), 2)),
                    ]
                    if target == "PMAIP1+BCL2L11"
                    else [
                        (target, "mRNA", f"{assay_record_id}-QPCR", round(min(100.0, target_kd + 2.0), 2) if target != "JAK2" else target_kd),
                        (target, "protein", f"{assay_record_id}-PROT", target_kd),
                    ]
                )
            ],
        }),
        "casp9_stressed_ctrl_raw_by_block": c9_ctrl_raw,
        "casp9_treated_raw_by_block": c9_tr_raw,
        "casp9_reduction_pct_by_block": c9_red_exact,
        "family_raw_p_values_casp9": fam_c,
        "holm_adjusted_casp9_p_value": holm_c,
        "stressed_ctrl_beta_plated_t0_by_block": ctrl_p0_b,
        "stressed_ctrl_beta_surviving_by_block": ctrl_sv_b,
        "treated_beta_plated_t0_by_block": tr_p0_b,
        "treated_beta_surviving_by_block": tr_sv_b,
        "unstressed_vehicle_beta_plated_t0_by_block": veh_p0_b,
        "unstressed_vehicle_beta_surviving_by_block": veh_sv_b,
        "stressed_ctrl_beta_t0_pct_by_block": list(ctrl_vec),
        "treated_beta_t0_pct_by_block": list(tr_vec),
        "unstressed_vehicle_beta_t0_pct_by_block": list(veh_vec),
        "family_raw_p_values_beta": fam_b,
        "holm_adjusted_beta_p_value": holm_b,
        "all_five_arms_paired_data": five_arms,
        "mock_transfection_control_by_block": [
            {
                "block_id": bids[i],
                "specimen_id": f"{assay_record_id}-MOCK-{bids[i]}",
                "delivery_reagent_lot_id": "DELIV-MOCK-LOT-01",
                "unstressed_mock_plated_t0": veh_p0_b[i],
                "unstressed_mock_surviving": max(1, int(round(veh_sv_b[i] * 0.97))),
                "stressed_mock_plated_t0": ctrl_p0_b[i],
                "stressed_mock_surviving": max(1, int(round(ctrl_sv_b[i] * 1.01))),
                "stressed_mock_casp9_raw": round(c9_ctrl_raw[i] * 0.99, 4),
            }
            for i in range(n)
        ],
        "nonbeta_lineage_min_surv_pct_ctrl": nonbeta_surv,
        "stressed_ctrl_nonbeta_t0_survival_pct": ctrl_nonbeta,
        "t0_original_plated_denominators_used": True,
        "pmlkl_flag_triggered": False,
        "gy016_nec1s_gsk872_orthogonal_rescue_cleared": False,
        "lineage_timecourse_counts": {
            "INS_beta": [
                {
                    "block_id": bids[bi],
                    "timepoints": [
                        {"hour_h": 0.0, "treated_plated_t0_n": 1000, "treated_surviving_n": 1000, "ctrl_plated_t0_n": 1000, "ctrl_surviving_n": 1000},
                        {"hour_h": 12.0, "treated_plated_t0_n": 1000, "treated_surviving_n": min(1000, int(round(10.0 * (0.75 * 100.0 + 0.25 * tr_vec[bi])))), "ctrl_plated_t0_n": 1000, "ctrl_surviving_n": min(1000, int(round(10.0 * (0.75 * 100.0 + 0.25 * ctrl_vec[bi]))))},
                        {"hour_h": 24.0, "treated_plated_t0_n": 1000, "treated_surviving_n": min(1000, int(round(10.0 * (0.5 * (100.0 + tr_vec[bi]))))), "ctrl_plated_t0_n": 1000, "ctrl_surviving_n": min(1000, int(round(10.0 * (0.5 * (100.0 + ctrl_vec[bi])))))},
                        {"hour_h": 48.0, "treated_plated_t0_n": 1000, "treated_surviving_n": int(round(10.0 * tr_vec[bi])), "ctrl_plated_t0_n": 1000, "ctrl_surviving_n": int(round(10.0 * ctrl_vec[bi]))},
                    ],
                }
                for bi in range(n)
            ],
            **{
                _ln: [
                    {
                        "block_id": bids[bi],
                        "timepoints": [
                            {"hour_h": 0.0, "treated_plated_t0_n": _pn, "treated_surviving_n": _pn, "ctrl_plated_t0_n": _pn, "ctrl_surviving_n": _pn},
                            {"hour_h": 12.0, "treated_plated_t0_n": _pn, "treated_surviving_n": min(_pn, int(round((_pn / 100.0) * (0.75 * 100.0 + 0.25 * ctrl_nonbeta) * min(100.0, nonbeta_surv + 3.0) / 100.0))), "ctrl_plated_t0_n": _pn, "ctrl_surviving_n": min(_pn, int(round((_pn / 100.0) * (0.75 * 100.0 + 0.25 * ctrl_nonbeta))))},
                            {"hour_h": 24.0, "treated_plated_t0_n": _pn, "treated_surviving_n": min(_pn, int(round((_pn / 100.0) * (0.5 * (100.0 + ctrl_nonbeta)) * min(100.0, nonbeta_surv + 2.0) / 100.0))), "ctrl_plated_t0_n": _pn, "ctrl_surviving_n": min(_pn, int(round((_pn / 100.0) * (0.5 * (100.0 + ctrl_nonbeta)))))},
                            {"hour_h": 48.0, "treated_plated_t0_n": _pn, "treated_surviving_n": min(_pn, int(round((_pn / 100.0) * ctrl_nonbeta * nonbeta_surv / 100.0)) + _pad), "ctrl_plated_t0_n": _pn, "ctrl_surviving_n": min(_pn, int(round((_pn / 100.0) * ctrl_nonbeta)))},
                        ],
                    }
                    for bi in range(n)
                ]
                for _ln, _pn, _pad in (("GCG_alpha", 500, 2), ("SST_delta", 200, 1), ("PLVAP_iEC", 400, 0), ("pericyte_stromal", 300, 2))
            },
        },
        "death_pathway_diversion_assay": {
            "diversion_assay_record_id": f"{assay_record_id}-GY016-DIV",
            "locked_timecourse_schedule_h": [0.0, 12.0, 24.0, 48.0],
            "pmlkl_fold_vs_ctrl": 1.06, "ripk3_fold_vs_ctrl": 1.04, "cleaved_casp3_fold_vs_ctrl": 0.62,
            "zvad_rescue_delta_pp": 14.5, "necrostatin1s_rescue_delta_pp": 1.2, "gsk872_rescue_delta_pp": 0.9,
            "lytic_ldh_or_sytox_timecourse_pct": [
                {"hour_h": 0.0, "treated_lytic_pct": 1.8, "ctrl_lytic_pct": 1.9},
                {"hour_h": 12.0, "treated_lytic_pct": 3.4, "ctrl_lytic_pct": 4.8},
                {"hour_h": 24.0, "treated_lytic_pct": 5.2, "ctrl_lytic_pct": 8.4},
                {"hour_h": 48.0, "treated_lytic_pct": 8.6, "ctrl_lytic_pct": 12.1},
            ],
            "lineage_block_diversion_records": {
                "INS_beta": [
                    {
                        "block_id": bids[bi],
                        "specimen_id": f"{assay_record_id}-DIV-BETA-{bids[bi]}",
                        "rescue_assay_record_id": f"{assay_record_id}-RESC-BETA-{bids[bi]}",
                        "pmlkl_fold_vs_ctrl": 1.05, "ripk3_fold_vs_ctrl": 1.03, "cleaved_casp3_fold_vs_ctrl": 0.62,
                        "zvad_rescue_delta_pp": 14.5, "necrostatin1s_rescue_delta_pp": 1.1, "gsk872_rescue_delta_pp": 0.8,
                        "paired_viability_timecourse_pct": [
                            {"hour_h": 0.0, "treated_viab_pct": 100.0, "ctrl_viab_pct": 100.0},
                            {"hour_h": 12.0, "treated_viab_pct": round(0.75 * 100.0 + 0.25 * tr_vec[bi], 2), "ctrl_viab_pct": round(0.75 * 100.0 + 0.25 * ctrl_vec[bi], 2)},
                            {"hour_h": 24.0, "treated_viab_pct": round(0.5 * (100.0 + tr_vec[bi]), 2), "ctrl_viab_pct": round(0.5 * (100.0 + ctrl_vec[bi]), 2)},
                            {"hour_h": 48.0, "treated_viab_pct": round(tr_vec[bi], 2), "ctrl_viab_pct": round(ctrl_vec[bi], 2)},
                        ],
                        "lytic_ldh_or_sytox_timecourse_pct": [
                            {"hour_h": 0.0, "treated_lytic_pct": 1.8, "ctrl_lytic_pct": 1.9},
                            {"hour_h": 12.0, "treated_lytic_pct": 3.4, "ctrl_lytic_pct": 4.8},
                            {"hour_h": 24.0, "treated_lytic_pct": 5.2, "ctrl_lytic_pct": 8.4},
                            {"hour_h": 48.0, "treated_lytic_pct": 8.6, "ctrl_lytic_pct": 12.1},
                        ],
                    }
                    for bi in range(n)
                ],
                "PLVAP_iEC": [
                    {
                        "block_id": bids[bi],
                        "specimen_id": f"{assay_record_id}-DIV-IEC-{bids[bi]}",
                        "rescue_assay_record_id": f"{assay_record_id}-RESC-IEC-{bids[bi]}",
                        "pmlkl_fold_vs_ctrl": 1.06, "ripk3_fold_vs_ctrl": 1.04, "cleaved_casp3_fold_vs_ctrl": 0.80,
                        "zvad_rescue_delta_pp": 3.5, "necrostatin1s_rescue_delta_pp": 1.2, "gsk872_rescue_delta_pp": 0.9,
                        "paired_viability_timecourse_pct": [
                            {"hour_h": 0.0, "treated_viab_pct": 100.0, "ctrl_viab_pct": 100.0},
                            {"hour_h": 12.0, "treated_viab_pct": round(min(100.0, (0.75 * 100.0 + 0.25 * ctrl_nonbeta) * min(100.0, nonbeta_surv + 3.0) / 100.0), 2), "ctrl_viab_pct": round(0.75 * 100.0 + 0.25 * ctrl_nonbeta, 2)},
                            {"hour_h": 24.0, "treated_viab_pct": round(min(100.0, (0.5 * (100.0 + ctrl_nonbeta)) * min(100.0, nonbeta_surv + 2.0) / 100.0), 2), "ctrl_viab_pct": round(0.5 * (100.0 + ctrl_nonbeta), 2)},
                            {"hour_h": 48.0, "treated_viab_pct": round(min(100.0, ctrl_nonbeta * nonbeta_surv / 100.0), 2), "ctrl_viab_pct": round(ctrl_nonbeta, 2)},
                        ],
                        "lytic_ldh_or_sytox_timecourse_pct": [
                            {"hour_h": 0.0, "treated_lytic_pct": 1.5, "ctrl_lytic_pct": 1.6},
                            {"hour_h": 12.0, "treated_lytic_pct": 2.8, "ctrl_lytic_pct": 3.2},
                            {"hour_h": 24.0, "treated_lytic_pct": 4.2, "ctrl_lytic_pct": 4.9},
                            {"hour_h": 48.0, "treated_lytic_pct": 6.4, "ctrl_lytic_pct": 7.1},
                        ],
                    }
                    for bi in range(n)
                ],
            },
        },
    }
    if target == "PMAIP1+BCL2L11":
        h2h_diffs = [tr_vec[i] - comp_vec[i] for i in range(n)]
        h2h_l95 = paired_t_summary(h2h_diffs)[3]
        blk.update({
            "pmaip1_kd_pct": target_kd, "bcl2l11_kd_pct": round(min(100.0, target_kd + 2.0), 2),
            "pmaip1_mrna_kd_pct": round(min(100.0, target_kd + 2.0), 2), "pmaip1_protein_kd_pct": target_kd,
            "bcl2l11_mrna_kd_pct": round(min(100.0, target_kd + 4.0), 2), "bcl2l11_protein_kd_pct": round(min(100.0, target_kd + 2.0), 2),
            "bcl2l11_comparator_beta_t0_pct_by_block": list(comp_vec),
            "head_to_head_vs_bcl2l11_l95_delta_pp": round(h2h_l95, 8),
        })
    if stat_method == "PAIRED_T_TEST_NORMALITY_VERIFIED":
        b_diffs = [tr_vec[i] - ctrl_vec[i] for i in range(n)]
        c_diffs = [c9_ctrl_raw[i] - c9_tr_raw[i] for i in range(n)]
        b_qq = paired_diff_normality_qq_r(b_diffs) or 0.96
        c_qq = paired_diff_normality_qq_r(c_diffs) or 0.96
        b_sw = shapiro_wilk_test(b_diffs)
        c_sw = shapiro_wilk_test(c_diffs)
        nd_body = {
            "beta_qq_r": round(b_qq, 6),
            "casp9_qq_r": round(c_qq, 6),
            "beta_shapiro_wilk_p": round(0.50 if b_sw is None else b_sw[1], 6),
            "casp9_shapiro_wilk_p": round(0.50 if c_sw is None else c_sw[1], 6),
        }
        blk["normality_diagnostic_record"] = {**nd_body, "diagnostic_sha256": sha256_bytes(canonical_json_bytes(nd_body))}
    if target == "JAK2" and jak2_shield_pct is not None:
        blk["gy001_cxcl10_inducible_shield_pct_ctrl"] = jak2_shield_pct
    return blk


def run_wave7_gate_self_tests() -> dict[str, Any]:
    """320 deterministic positive & adversarial fail-closed regression tests across GATE-40..GATE-43 (80 per gate)."""
    passed = 0
    total = 0

    def chk(cond: bool, label: str) -> None:
        nonlocal passed, total
        total += 1
        require(cond, f"Gate self-test failed: {label}")
        passed += 1

    py, by, ly, ry = "ISLET1_DESIGN_Y_V3", "MCB-Y-V3-001", "LOT-Y-001", "R3P"
    pb, bb, lb, rb = "ISLET1_DESIGN_B_V090", "MCB-B-V090-001", "LOT-B-001", "R2"
    px, bx, lx, rx = "ISLET1_DESIGN_X_V090", "MCB-X-V090-001", "LOT-X-001", "R1"
    pa, ba, la, ra = "ISLET1_DESIGN_A_V080_REF", "MCB-A-V080-001", "LOT-A-001", "R1"
    pd_, bd_, ld_, rd_ = "ISLET1_DESIGN_D1B_LEAN_K2", "AUTO-D1B-001", "LOT-D-001", "R3P"

    # ========================================================================
    # GATE-40 (80 tests: 70 prior + 10 adversarial closures)
    # ========================================================================
    coat_a = _mk_r8_coating("PFD-R3P")
    bv_a = coat_a["matched_blank_vehicle_lot_id"]
    tr14_t, tr14_m = _mk_r8_pfd_trace(336.0)
    tr35_t, tr35_m = _mk_r8_pfd_trace(840.0)
    a0a_donors = ["DON-A0A-1", "DON-A0A-2", "DON-A0A-3", "DON-A0A-4", "DON-A0A-5"]
    a0a_reps_ok = [
        {
            "donor_ids": a0a_donors,
            "matched_vehicle_record_id": f"A0A-VASC-VEH-CONC-{idx_a}",
            "efficacy_matched_vehicle_record_id": f"A0A-EFF-VEH-CONC-{idx_a}",
            "efficacy_vehicle_viable_cells_by_donor": [10000, 10000, 10000, 10000, 10000],
            "efficacy_treated_viable_cells_by_donor": [int(round(100.0 * (ev_c + d))) for d in (-0.3, -0.15, 0.0, 0.15, 0.3)],
            "efficacy_culture_viability_7d_pct": [round(ev_c + d, 2) for d in (-0.3, -0.15, 0.0, 0.15, 0.3)],
            "alpha_sma_inhibition_pct": [round(s + d, 2) for d in (-0.3, -0.15, 0.0, 0.15, 0.3)],
            "col1a1_inhibition_pct": [round(c + d, 2) for d in (-0.3, -0.15, 0.0, 0.15, 0.3)],
            "viability_7d_pct": [round(v + d, 2) for d in (-0.3, -0.15, 0.0, 0.15, 0.3)],
            "day0_sprout_length_7d_pct": [round(p + 0.4 + d, 2) for d in (-0.3, -0.15, 0.0, 0.15, 0.3)],
            "day0_branching_7d_pct": [round(p + 0.2 + d, 2) for d in (-0.3, -0.15, 0.0, 0.15, 0.3)],
            "day0_lumen_formation_7d_pct": [round(p + 0.3 + d, 2) for d in (-0.3, -0.15, 0.0, 0.15, 0.3)],
            "delayed_sprout_length_7d_pct": [round(pd + 0.4 + d, 2) for d in (-0.3, -0.15, 0.0, 0.15, 0.3)],
            "delayed_branching_7d_pct": [round(pd + 0.2 + d, 2) for d in (-0.3, -0.15, 0.0, 0.15, 0.3)],
            "delayed_lumen_formation_7d_pct": [round(pd + 0.3 + d, 2) for d in (-0.3, -0.15, 0.0, 0.15, 0.3)],
            "sprouting_7d_pct": [round(p + d, 2) for d in (-0.3, -0.15, 0.0, 0.15, 0.3)],
            "sprouting_delayed_7d_pct": [round(pd + d, 2) for d in (-0.3, -0.15, 0.0, 0.15, 0.3)],
        }
        for idx_a, (s, c, v, ev_c, p, pd) in enumerate(zip(
            [0.0, 18.0, 38.0, 54.0, 60.0, 62.0, 64.0],
            [0.0, 15.0, 35.0, 52.0, 57.0, 58.0, 60.0],
            [100.0, 99.0, 98.0, 97.0, 95.0, 93.0, 81.0],
            [100.0, 99.2, 98.4, 97.5, 95.8, 94.0, 82.0],
            [100.0, 99.0, 97.0, 96.0, 94.0, 92.0, 76.0],
            [100.0, 99.0, 97.5, 96.5, 94.5, 92.5, 78.0],
        ))
    ]
    a0a_fit_ok = _sign_receipt({
        "analysis_method": "SIMULTANEOUS_BONFERRONI_GRID_BRACKET_STUDENT_T",
        "donor_ids": a0a_donors,
        "raw_replicates_sha256": sha256_bytes(canonical_json_bytes(a0a_reps_ok)),
        "analysis_record_sha256": "a" * 64,
        "ic50_free_alpha_sma_uM": 66.25, "ic50_free_col1a1_uM": 70.88, "ic50_free_max_u95_uM": 75.0,
        "cc10_free_7d_l95_uM": 280.0, "c_sprout_max_free_7d_l95_uM": 260.0,
    })
    a0a_ok = _sign_receipt({
        "stage": "A-0a", "verdict": "PASS", "evidence_scope": "route_free",
        "study_start_utc": "2026-06-20T08:00:00Z", "recorded_at_utc": "2026-07-01T08:00:00Z",
        "analysis_record_sha256": "a" * 64,
        "a0a_assay_matrix": "human_fibroblast_serum_media",
        "a0a_dialysis_fu_replicates": [0.415, 0.418, 0.420, 0.422, 0.425],
        "a0a_matrix_fu_by_assay": {
            "fibrosis_efficacy_assay": {
                "matrix_id": "human_fibroblast_serum_media",
                "nominal_conc_uM_grid": [round(x / 0.42, 4) for x in (0.0, 20.0, 40.0, 75.0, 150.0, 260.0, 500.0)],
                "dialysis_fu_replicates": [0.415, 0.418, 0.420, 0.422, 0.425],
                "measured_fu_mean": 0.42,
                "analytical_sample_record_sha256": sha256_bytes(b"A0A-FIBROSIS-FU-DIALYSIS-01"),
            },
            "vascular_viability_assay": {
                "matrix_id": "human_iec_sprouting_media",
                "nominal_conc_uM_grid": [round(x / 0.50, 4) for x in (0.0, 20.0, 40.0, 75.0, 150.0, 260.0, 500.0)],
                "dialysis_fu_replicates": [0.494, 0.497, 0.500, 0.503, 0.506],
                "measured_fu_mean": 0.50,
                "analytical_sample_record_sha256": sha256_bytes(b"A0A-VASCULAR-FU-DIALYSIS-01"),
            },
        },
        "fu_measured": 0.42, "emax_alpha_sma_pct": 62.0, "emax_col1a1_pct": 58.0,
        "ic50_free_alpha_sma_uM": 66.25, "ic50_free_col1a1_uM": 70.88, "ic50_free_max_u95_uM": 75.0,
        "cc10_free_7d_l95_uM": 280.0, "c_sprout_max_free_7d_l95_uM": 260.0,
        "c_upper_provisional_7d_l95_uM": 260.0, "endpoints_bracketed": True,
        "tested_free_conc_uM_grid": [0.0, 20.0, 40.0, 75.0, 150.0, 260.0, 500.0],
        "alpha_sma_inhibition_pct_grid": [0.0, 18.0, 38.0, 54.0, 60.0, 62.0, 64.0],
        "col1a1_inhibition_pct_grid": [0.0, 15.0, 35.0, 52.0, 57.0, 58.0, 60.0],
        "viability_7d_pct_grid": [100.0, 99.0, 98.0, 97.0, 95.0, 93.0, 81.0],
        "sprouting_7d_pct_grid": [100.0, 99.0, 97.0, 96.0, 94.0, 92.0, 76.0],
        "sprouting_delayed_7d_pct_grid": [100.0, 99.0, 97.5, 96.5, 94.5, 92.5, 78.0],
        "a0a_donor_replicates_by_conc": a0a_reps_ok,
        "a0a_fit_artifact_receipt": a0a_fit_ok,
    })
    a0b_donors = ["DON-A0B-1", "DON-A0B-2", "DON-A0B-3"]
    def _mk_a0b_raw_pair(pct_vals: Sequence[float], base_veh: float) -> dict[str, list[float]]:
        vehs = [round(base_veh * (1.0 + 0.02 * (i - 1)), 4) for i in range(len(pct_vals))]
        return {"treated": [round(vehs[i] * float(pct_vals[i]) / 100.0, 4) for i in range(len(pct_vals))], "vehicle": vehs}

    a0b_reps_ok = [
        (lambda _vv, _evv, _d0l, _d0b, _d0n, _d4l, _d4b, _d4n, _s0, _s4: {
            "conc_uM": c_u, "donor_ids": a0b_donors,
            "matched_vehicle_record_id": f"A0B-VASC-VEH-{int(c_u)}UM",
            "efficacy_matched_vehicle_record_id": f"A0B-EFF-VEH-{int(c_u)}UM",
            "matched_vehicle_raw_baselines": {
                "viability_raw": 96.5, "efficacy_viability_raw": 97.0,
                "day0_sprout_length_um": 410.0, "day0_branching_junctions": 28.0, "day0_network_persistence_idx": 0.91,
                "day4_sprout_length_um": 395.0, "day4_branching_junctions": 26.5, "day4_network_persistence_idx": 0.89,
            },
            "raw_donor_measurements": {
                "viability_14d": _mk_a0b_raw_pair(_vv, 96.5),
                "efficacy_culture_viability_14d": _mk_a0b_raw_pair(_evv, 97.0),
                "day0_sprout_length_14d": _mk_a0b_raw_pair(_d0l, 410.0),
                "day0_branching_14d": _mk_a0b_raw_pair(_d0b, 28.0),
                "day0_network_persistence_14d": _mk_a0b_raw_pair(_d0n, 0.91),
                "day4_sprout_length_14d": _mk_a0b_raw_pair(_d4l, 395.0),
                "day4_branching_14d": _mk_a0b_raw_pair(_d4b, 26.5),
                "day4_network_persistence_14d": _mk_a0b_raw_pair(_d4n, 0.89),
            },
            "viability_14d_pct": _vv, "efficacy_culture_viability_14d_pct": _evv,
            "day0_sprout_length_14d_pct": _d0l, "day0_branching_14d_pct": _d0b, "day0_network_persistence_14d_pct": _d0n,
            "day4_sprout_length_14d_pct": _d4l, "day4_branching_14d_pct": _d4b, "day4_network_persistence_14d_pct": _d4n,
            "day0_sprouting_14d_pct": _s0, "day4_delayed_sprouting_14d_pct": _s4,
        })(
            [round(v + d, 2) for d in (-0.3, 0.0, 0.3)],
            [round(ev_v + d, 2) for d in (-0.3, 0.0, 0.3)],
            [round(s0 + 0.4 + d, 2) for d in (-0.3, 0.0, 0.3)],
            [round(s0 + 0.2 + d, 2) for d in (-0.3, 0.0, 0.3)],
            [round(s0 + d, 2) for d in (-0.3, 0.0, 0.3)],
            [round(s4 + 0.4 + d, 2) for d in (-0.3, 0.0, 0.3)],
            [round(s4 + 0.2 + d, 2) for d in (-0.3, 0.0, 0.3)],
            [round(s4 + d, 2) for d in (-0.3, 0.0, 0.3)],
            [round(s0 + d, 2) for d in (-0.3, 0.0, 0.3)],
            [round(s4 + d, 2) for d in (-0.3, 0.0, 0.3)],
        )
        for c_u, v, ev_v, s0, s4 in (
            (0.0, 99.0, 99.2, 99.0, 99.5),
            (50.0, 97.5, 97.8, 96.5, 97.5),
            (100.0, 96.0, 96.4, 95.0, 96.0),
            (150.0, 95.0, 95.4, 94.0, 95.0),
            (190.0, 94.2, 94.6, 93.2, 94.0),
            (220.0, 93.0, 93.5, 91.8, 92.5),
            (240.0, 91.8, 92.2, 86.0, 88.0),
            (360.0, 82.0, 83.0, 72.0, 78.0),
        )
    ]
    a0b_fit_ok = _sign_receipt({
        "donor_ids": a0b_donors,
        "raw_replicates_sha256": sha256_bytes(canonical_json_bytes(a0b_reps_ok)),
        "cc10_free_14d_l95_uM": 240.0, "c_sprout_max_free_14d_l95_uM": 220.0,
        "day14_viability_pct": 94.0, "day14_sprouting_pct": 93.0,
    })
    def _mk_pfd_3lots(clot: str, t_arr: Sequence[float], c_arr: Sequence[float], load_mg: float = 18.75) -> list[dict[str, Any]]:
        lot_names = [clot, f"{clot}-REP2", f"{clot}-REP3"]
        scales = [1.0, 0.99, 1.01]
        out_l: list[dict[str, Any]] = []
        for lnm, sc in zip(lot_names, scales):
            b_l = {
                "coating_lot_id": lnm,
                "initial_pirfenidone_loading_mg": load_mg,
                "elution_time_hours": list(t_arr),
                "cumulative_intact_parent_released_mg": [round(x * sc, 4) for x in c_arr],
            }
            out_l.append({**b_l, "lot_trace_sha256": sha256_bytes(canonical_json_bytes(b_l))})
        return out_l

    def _mk_pfd_tp_rows(pts: Sequence[tuple[float, float]], clot: str, tag_u: str = "PFD", deltas: Sequence[float] = (-0.35, 0.0, 0.35), single_lot_only: bool = False, active_lot_offset: float = 0.0) -> list[dict[str, Any]]:
        lot_names = [clot] if single_lot_only else [clot, f"{clot}-REP2", f"{clot}-REP3"]
        lot_shifts = [active_lot_offset] if single_lot_only else [active_lot_offset, -0.25, 0.25]
        rows_out: list[dict[str, Any]] = []
        for hh, val in pts:
            urecs: list[dict[str, Any]] = []
            ums: list[float] = []
            ui = 0
            for ln_i, lshift in zip(lot_names, lot_shifts):
                for d in deltas:
                    ui += 1
                    um = round(val + (0.0 if all(x == 0.0 for x in deltas) else lshift) + d, 3)
                    ums.append(um)
                    urecs.append({
                        "coating_lot_id": ln_i,
                        "independent_unit_id": f"{tag_u}-UNIT-{ui}",
                        "specimen_id": f"{tag_u}-SPEC-{int(hh)}H-U{ui}",
                        "technical_well_readings_uM": [round(um - 0.05, 3), um, round(um + 0.05, 3)],
                        "unit_mean_uM": um,
                    })
            rows_out.append({
                "hour_h": hh,
                "independent_unit_records": urecs,
                "free_parent_uM_replicates": ums,
            })
        return rows_out
    a0b_tp_pts = ((6.0, 182.0), (24.0, 175.0), (72.0, 152.0), (144.0, 136.0), (216.0, 122.0), (288.0, 114.0), (336.0, 108.0))
    a1_tp_pts = ((6.0, 178.0), (24.0, 170.0), (72.0, 148.0), (144.0, 132.0), (216.0, 118.0), (288.0, 108.0), (336.0, 100.0), (600.0, 22.0), (840.0, 3.2))
    a0b_tp_ok = _mk_pfd_tp_rows(a0b_tp_pts, coat_a["coating_lot_id"], "A0B")
    a1_tp_ok = _mk_pfd_tp_rows(a1_tp_pts, coat_a["coating_lot_id"], "A1")
    def _mk_pfd_env(scope_s: str, comp_s: str, *, art_id: str = coat_a["coating_article_id"], lot_id: str = coat_a["coating_lot_id"], ke_a: float = 0.004, kr_a: float = 0.002, ke_w: float = 0.010) -> dict[str, Any]:
        # Dense pilot trace (1.0 h spacing <= 2.0 h cap) with observed slopes conservatively below declared bounds / 1.15!
        r_rise_p = min(kr_a / 1.25, 0.0015)
        r_elim_p = min(ke_a / 1.25, 0.0030)
        r_wash_p = min(ke_w / 1.25, 0.0080)
        bh_p = [0.5, 1.5, 2.5, 3.5, 4.5, 5.5]
        bc_p = [
            round(180.0, 4),
            round(180.0 * math.exp(r_rise_p * 1.0), 4),
            round(180.0 * math.exp(r_rise_p * 2.0), 4),
            round(180.0 * math.exp(r_rise_p * 2.0 - r_elim_p * 1.0), 4),
            round(180.0 * math.exp(r_rise_p * 2.0 - r_elim_p * 2.0), 4),
            round(180.0 * math.exp(r_rise_p * 2.0 - r_elim_p * 3.0), 4),
        ]
        wh_p = [336.0, 337.0, 338.0, 339.0]
        wc_p = [round(100.0 * math.exp(-r_wash_p * float(k)), 4) for k in range(4)]
        dpt_body = {
            "pilot_coating_lot_id": f"{lot_id}-PILOT",
            "pilot_compartment_id": comp_s,
            "burst_segment_hours_h": bh_p,
            "burst_segment_free_parent_uM": bc_p,
            "washout_segment_hours_h": wh_p,
            "washout_segment_free_parent_uM": wc_p,
        }
        dpt_sha = sha256_bytes(canonical_json_bytes(dpt_body))
        dpt_rec = {**dpt_body, "pilot_trace_sha256": dpt_sha}
        eb = {
            "k_elim_active_max_per_h": ke_a, "k_rise_active_max_per_h": kr_a, "k_elim_washout_max_per_h": ke_w,
            "coating_article_id": art_id, "evidence_scope": scope_s, "compartment_id": comp_s,
            "envelope_qualification_method": "DENSE_PILOT_TIMECOURSE_BOUND", "pilot_sampling_max_gap_h": 1.0,
            "burst_phase_covered": True, "washout_phase_covered": True,
            "source_study_ids": ["PFD-DENSE-PILOT-001", "PFD-WASHOUT-001"],
            "dense_pilot_trace": dpt_rec,
            "envelope_model_sha256": dpt_sha,
        }
        return {**eb, "envelope_receipt_sha256": sha256_bytes(canonical_json_bytes(eb))}
    a0b_env_ok = _mk_pfd_env("bench_unedited", "BENCH_LOCAL_PERI_GRAFT")
    a1b_env_ok = _mk_pfd_env("bench_unedited", "BENCH_ELUTION_LOCAL_PERI_GRAFT")
    a1e_env_ok = _mk_pfd_env("exact_product", "BENCH_ELUTION_LOCAL_PERI_GRAFT")
    a0b_mfu_ok = {
        "fibrosis_efficacy_assay": {
            "matrix_id": "human_macrophage_fibroblast_14d_media",
            "nominal_conc_uM_grid": [round(r["conc_uM"] / 0.42, 4) for r in a0b_reps_ok],
            "dialysis_fu_replicates": [0.415, 0.418, 0.420, 0.422, 0.425],
            "measured_fu_mean": 0.42,
            "analytical_sample_record_sha256": sha256_bytes(b"A0B-FIBROSIS-14D-FU-DIALYSIS-01"),
        },
        "vascular_viability_assay": {
            "matrix_id": "human_iec_sprouting_14d_media",
            "nominal_conc_uM_grid": [round(r["conc_uM"] / 0.50, 4) for r in a0b_reps_ok],
            "dialysis_fu_replicates": [0.494, 0.497, 0.500, 0.503, 0.506],
            "measured_fu_mean": 0.50,
            "analytical_sample_record_sha256": sha256_bytes(b"A0B-VASCULAR-14D-FU-DIALYSIS-01"),
        },
    }
    a0b_y = _sign_receipt({
        "stage": "A-0b", "verdict": "PASS", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "bench_unedited", "study_start_utc": "2026-07-02T09:00:00Z",
        "recorded_at_utc": "2026-07-20T09:00:00Z", "parent_receipt_sha256": a0a_ok["receipt_sha256"],
        **coat_a, "initial_pirfenidone_loading_mg": 18.75,
        "coating_thickness_um": 6.5, "day1_burst_pct": 9.6, "modeled_systemic_plasma_ug_ml": 0.16,
        "elution_time_hours": tr14_t, "cumulative_intact_parent_released_mg": tr14_m,
        "assumed_human_t_half_h": 3.0, "assumed_human_vd_l": 50.0,
        "worst_face_o2_mmhg": 44.0, "day14_viability_pct": 94.0, "day14_sprouting_pct": 93.0,
        "cc10_free_14d_l95_uM": 240.0, "c_sprout_max_free_14d_l95_uM": 220.0,
        "c_upper_provisional_14d_l95_uM": 220.0,
        "sustained_free_parent_lower_uM": 95.0, "peak_free_parent_u95_uM": 195.0,
        "day14_sustained_free_parent_u95_uM": 165.0,
        "added_coating_water_equiv_diff_path_um": 3.2, "water_equiv_diff_path_um": 24.0,
        "local_ph_min": 7.31, "local_ph_max": 7.39,
        "a0b_14d_safety_replicates_by_conc": a0b_reps_ok,
        "a0b_fit_artifact_receipt": a0b_fit_ok,
        "a0b_matrix_fu_by_assay": a0b_mfu_ok,
        "a0b_local_exposure_timepoints": a0b_tp_ok,
        "a0b_local_pk_envelope": a0b_env_ok,
        "a0b_local_ph_timepoints": [
            {"hour_h": h_p, "coating_lot_id": coat_a["coating_lot_id"], "ph_min": 7.33, "ph_max": 7.38}
            for h_p in (24.0, 168.0, 336.0)
        ],
        "manufacturing_lot_release_records": _mk_pfd_3lots(coat_a["coating_lot_id"], tr14_t, tr14_m),
    })
    a1b_y = _sign_receipt({
        "stage": "A-1-BENCH", "verdict": "PASS", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "bench_unedited", "elution_started_at_utc": "2026-07-21T10:00:00Z",
        "recorded_at_utc": "2026-08-26T10:00:00Z", "parent_receipt_sha256": a0b_y["receipt_sha256"],
        **coat_a, "initial_pirfenidone_loading_mg": 18.75,
        "day35_residual_parent_mg": 1.125, "day35_degradant_mass_mg": 0.0,
        "elution_t50_days": 9.75, "day14_usable_delivery_fraction_pct": 62.4,
        "day35_depot_exhaustion_pct": 94.0, "day35_residual_parent_pct": 6.0,
        "day35_terminal_mass_recovery_pct": 99.87, "day14_elution_verified": True,
        "elution_time_hours": tr35_t, "cumulative_intact_parent_released_mg": tr35_m,
        "assumed_human_t_half_h": 3.0, "assumed_human_vd_l": 50.0,
        "day1_intact_parent_free_uM": 180.0, "day14_intact_parent_free_uM": 92.0,
        "day35_intact_parent_free_uM": 4.0, "peak_daily_eluted_mg": 5.25,
        "assumed_human_clearance_l_per_day": 277.26,
        "a1_local_free_parent_timepoints": a1_tp_ok,
        "a1_local_pk_envelope": a1b_env_ok,
        "a1_local_ph_timepoints": [
            {"hour_h": h_p, "coating_lot_id": coat_a["coating_lot_id"], "ph_min": 7.32, "ph_max": 7.39}
            for h_p in (24.0, 168.0, 336.0, 504.0, 672.0, 840.0)
        ],
        "manufacturing_lot_release_records": _mk_pfd_3lots(coat_a["coating_lot_id"], tr35_t, tr35_m),
    })
    mat_y = _mk_r8_mat(py, by, ly, "2026-08-27T08:00:00Z")
    sw_y = _mk_r8_switch(py, by, ly, ry, mat_y, "2026-10-12T09:00:00Z", coating_identity=coat_a)
    g0v_y = _mk_r8_gate0v(py, by, ly, ry, mat_y, "2026-10-12T09:30:00Z", coating_identity=coat_a)
    pr_mat_y = {"BANK_MATERIALIZATION": mat_y["receipt_sha256"]}
    pr_all_y = {
        "BANK_MATERIALIZATION": mat_y["receipt_sha256"],
        "NATIVE_SAFETY_SWITCH": sw_y["receipt_sha256"],
        "GATE-0V-KILL": g0v_y["receipt_sha256"],
    }
    a1_y = _sign_receipt({
        "stage": "A-1", "verdict": "PASS", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "exact_product", "elution_started_at_utc": "2026-08-28T10:00:00Z",
        "recorded_at_utc": "2026-10-05T10:00:00Z", "parent_receipt_sha256": a1b_y["receipt_sha256"],
        "prerequisite_receipt_sha256s": pr_mat_y, **coat_a,
        "initial_pirfenidone_loading_mg": 18.75,
        "day35_residual_parent_mg": 1.125, "day35_degradant_mass_mg": 0.0,
        "elution_t50_days": 9.75, "day14_usable_delivery_fraction_pct": 62.4,
        "day35_depot_exhaustion_pct": 94.0, "day35_residual_parent_pct": 6.0,
        "day35_terminal_mass_recovery_pct": 99.87, "day14_elution_verified": True,
        "elution_time_hours": tr35_t, "cumulative_intact_parent_released_mg": tr35_m,
        "assumed_human_t_half_h": 3.0, "assumed_human_vd_l": 50.0,
        "day1_intact_parent_free_uM": 180.0, "day14_intact_parent_free_uM": 92.0,
        "day35_intact_parent_free_uM": 4.0, "peak_daily_eluted_mg": 5.25,
        "assumed_human_clearance_l_per_day": 277.26,
        "a1_local_free_parent_timepoints": a1_tp_ok,
        "a1_local_pk_envelope": a1e_env_ok,
        "a1_local_ph_timepoints": [
            {"hour_h": h_p, "coating_lot_id": coat_a["coating_lot_id"], "ph_min": 7.32, "ph_max": 7.39}
            for h_p in (24.0, 168.0, 336.0, 504.0, 672.0, 840.0)
        ],
        "manufacturing_lot_release_records": _mk_pfd_3lots(coat_a["coating_lot_id"], tr35_t, tr35_m),
    })
    a2_prolif_ok = [
        {"lot_id": f"A2-LOT-{i}", "assay_record_id": f"A2-PROLIF-ASSAY-{i}", "ki67_fold_vs_ctrl": 0.98, "edu_fold_vs_ctrl": 0.97, "ki67_edu_referred": False}
        for i in (1, 2, 3)
    ]
    a2_y = _sign_receipt({
        "stage": "A-2", "verdict": "PASS", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "exact_product", "study_start_utc": "2026-10-06T10:00:00Z",
        "a2_specimen_id": f"SPEC-A2-{ly}", "a2_cohort_id": f"COHORT-A2-{ly}",
        "recorded_at_utc": "2026-10-25T10:00:00Z", "parent_receipt_sha256": a1_y["receipt_sha256"],
        "prerequisite_receipt_sha256s": pr_mat_y, **coat_a,
        "shield_retention_by_component": _mk_r8_shields(py),
        "ins_positive_beta_viability_pct": 94.5, "a2_per_lot_proliferation_records": a2_prolif_ok,
        "worst_face_o2_mmhg": 43.0, "hour0_density_by_lineage": _mk_r8_hour0(py),
        "day14_iec_sprouting_pct_ctrl": 94.0, "day14_iec_sprout_length_pct_ctrl": 95.0,
        "day14_iec_branching_pct_ctrl": 94.5, "day14_iec_network_persistence_pct_ctrl": 94.0,
        "a2_vascular_vehicle_record_id": f"A2-VASC-VEH-{bv_a}",
        "a2_vascular_raw_measurements": (lambda _vb: {**_vb, "vascular_assay_receipt_sha256": sha256_bytes(canonical_json_bytes(_vb))})({
            "specimen_id": f"SPEC-A2-{ly}",
            "coating_lot_id": coat_a["coating_lot_id"],
            "matched_vehicle_lot_id": bv_a,
            "exposure_started_at_utc": "2026-10-06T12:00:00Z",
            "assessed_at_utc": "2026-10-21T12:00:00Z",
            "treated_sprout_length_um": 389.5, "vehicle_sprout_length_um": 410.0,
            "treated_branching_junctions": 26.46, "vehicle_branching_junctions": 28.0,
            "treated_network_persistence_idx": 0.8554, "vehicle_network_persistence_idx": 0.91,
        }),
        "day14_iec_teer_pct_ctrl": 96.0,
        "day14_iec_cdh5_pct_ctrl": 94.0, "day14_iec_col4a2_pct_ctrl": 92.0,
        "day14_iec_klf2_fold": 0.92, "day14_iec_vcam1_adhesion_fold": 1.05,
        "readout2_evidence": _mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B"),
        "readout3b_evidence": _mk_r8_readout3b(matched_vehicle_lot_id=bv_a, specimen_id=f"SPEC-A2-{ly}", specimen_lot_id=ly, intervention_cohort_id=f"COHORT-A2-{ly}"),
    })
    a3_y = _sign_receipt({
        "stage": "A-3", "verdict": "PASS", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "exact_product", "recorded_at_utc": "2026-11-01T10:00:00Z",
        "parent_receipt_sha256": a2_y["receipt_sha256"], "prerequisite_receipt_sha256s": pr_mat_y, **coat_a,
        "matched_control_switch_parity_evidence": _mk_r8_switch_parity(bv_a),
        "oq012_clonogenic_block": _mk_r8_oq012(),
    })
    a4a_y = _sign_receipt({
        "stage": "A-4a", "verdict": "PASS", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "exact_product", "coupon_started_at_utc": "2026-11-05T10:00:00Z",
        "recorded_at_utc": "2026-11-25T10:00:00Z", "parent_receipt_sha256": a3_y["receipt_sha256"],
        "prerequisite_receipt_sha256s": pr_all_y, **coat_a,
        "donor_pair_records": [
            {"donor_pair_id": "DP-1", "day7_col1a1_reduction_pct": 55.0, "day7_alpha_sma_reduction_pct": 53.0, "day14_col1a1_reduction_pct": 59.0, "day14_alpha_sma_reduction_pct": 57.0, "day14_viability_pct": 93.5, "worst_face_o2_mmhg": 42.5},
            {"donor_pair_id": "DP-2", "day7_col1a1_reduction_pct": 56.0, "day7_alpha_sma_reduction_pct": 54.0, "day14_col1a1_reduction_pct": 60.0, "day14_alpha_sma_reduction_pct": 58.0, "day14_viability_pct": 94.0, "worst_face_o2_mmhg": 43.0},
            {"donor_pair_id": "DP-3", "day7_col1a1_reduction_pct": 57.0, "day7_alpha_sma_reduction_pct": 55.0, "day14_col1a1_reduction_pct": 61.0, "day14_alpha_sma_reduction_pct": 59.0, "day14_viability_pct": 94.5, "worst_face_o2_mmhg": 43.5},
        ],
        "day7_col1a1_reduction_pct": 56.0, "day7_alpha_sma_reduction_pct": 54.0,
        "day14_col1a1_reduction_pct": 60.0, "day14_alpha_sma_reduction_pct": 58.0,
        "day14_viability_pct": 94.0, "worst_face_o2_mmhg": 43.0,
    })
    a4b_prereg_y, a4b_coh_y = _mk_r8_a4b_prereg_and_cohorts(py, by, ly, ry, a4a_y, coat_a, start_dt_str="2026-12-20T08:00:00Z")
    pr_a4b_y = {**pr_all_y, "A-4b-PREREGISTRATION": a4b_prereg_y["receipt_sha256"]}
    a4b_y = _sign_receipt({
        "stage": "A-4b", "verdict": "PASS", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "exact_product", "animal_work_started_at_utc": "2026-12-20T08:00:00Z",
        "recorded_at_utc": "2027-01-25T10:00:00Z", "parent_receipt_sha256": a4a_y["receipt_sha256"],
        "prerequisite_receipt_sha256s": pr_a4b_y, **coat_a,
        "blinded_allocation": True, "implant_extrusions": 0,
        **a4b_coh_y,
    })
    g40_bench = {
        "phase": "BENCH_UNEDITED", "track_mode": "PRIMARY", "credit_scope": "PRIMARY",
        "target_arm": "Y", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "a0a_evidence": a0a_ok, "a0b_evidence": a0b_y, "a1_bench_evidence": a1b_y,
    }
    g40_ok = {
        **g40_bench, "phase": "EXACT_PRODUCT",
        "materialization_evidence": mat_y, "native_switch_evidence": sw_y, "gate0v_evidence": g0v_y,
        "a1_evidence": a1_y, "a2_evidence": a2_y, "a3_evidence": a3_y, "a4a_evidence": a4a_y,
        "a4b_preregistration_receipt": a4b_prereg_y, "a4b_evidence": a4b_y,
    }
    r40 = evaluate_gate40_pirfenidone_h4(g40_ok)
    chk(r40["verdict"] == OFFLINE_VERDICT_PRIMARY and r40["release_authorizing"] is False and r40["live_ledger_authenticated"] is False, "G40_pass_Y_R3P")
    chk(evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": a0a_ok})["verdict"] == "PASS_ROUTE_FREE_A0A_ONLY", "G40_phase1_ok")
    chk(evaluate_gate40_pirfenidone_h4(g40_bench)["verdict"] == "PASS_BENCH_ONLY_UNEDITED_PRE_MATERIALIZATION", "G40_phase2_ok")

    # GATE-40 closures (10 brand-new tests!)
    # 1. Instantaneous 18 mg burst in 1 hour breaches 1-compartment C_max >= 0.20 ug/mL even though steady-state 18/250 = 0.072 < 0.20!
    chk("FAIL_GATE_A1_RECOMPUTED_PEAK_SYSTEMIC_CMAX_CAP_BREACH" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "cumulative_intact_parent_released_mg": [0.0] + [18.0] * (len(tr35_t) - 1)})})["failures"], "G40_ADV_burst_cmax_breach")
    # 2. A-0b modeled plasma understating recomputed burst C_max fails!
    chk("FAIL_GATE_A0B_MODELED_PLASMA_UNDERSTATES_BURST_CMAX" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "modeled_systemic_plasma_ug_ml": 0.001})})["failures"], "G40_ADV_a0b_understates_cmax")
    # 3. A-2 matched comparator drop to 50% of blank vehicle fails BOTH raw ratio & Fieller L95!
    bad_r2_50 = _mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B")
    for b in bad_r2_50["o2_40_mmhg"]["blocks"]:
        b["matched_control_z2_increment"] = round(b["z2_increment"] * 2.0, 4)
        b["matched_control_output_ratio"] = 0.50
    chk("FAIL_GATE_A2_READOUT2_O2_40_RECOMPUTED_CTRL_FIELLER_L95_BELOW_FLOOR" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": bad_r2_50})})["failures"], "G40_ADV_a2_matched_ctrl_50pct_fail")
    # 4. A-2 Readout-2 Rule S8 Fieller fails when extended clocks apply (> 28 days) and comparator is missing!
    r2_ext = _mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B")
    r2_ext["dual_clocks_utc"]["assay_harvest_utc"] = "2026-11-10T00:00:00Z"
    chk("FAIL_GATE_A2_READOUT2_O2_40_MISSING_RULE_S8_COMPARATOR_Z2" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": r2_ext})})["failures"], "G40_ADV_a2_rule_s8_enforced")
    # 5. A-2 INS+ beta viability < 90% fails!
    chk("FAIL_GATE_A2_INS_POSITIVE_BETA_VIABILITY_BELOW_90PCT" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "ins_positive_beta_viability_pct": 82.0})})["failures"], "G40_ADV_a2_ins_viab_lt90")
    # 6. A-2 unpooled proliferation > 1.0x unreferred fails (and referred holds)!
    chk("FAIL_GATE_A2_UNREFERRED_PROLIFERATION_ELEVATION:A2-LOT-1" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "a2_per_lot_proliferation_records": [{**a2_prolif_ok[0], "ki67_fold_vs_ctrl": 1.08}, a2_prolif_ok[1], a2_prolif_ok[2]]})})["failures"], "G40_ADV_a2_prolif_unreferred")
    # 7. Gate 0V autologous tier submitted for allogeneic Design Y triggers HOLD_INAPPLICABLE_QUALIFICATION_TIER_FOR_PRODUCT_FAMILY!
    g0v_wrong_tier = _mk_r8_gate0v(py, by, ly, ry, mat_y, "2026-10-12T09:30:00Z", coating_identity=coat_a, tier_override="PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL")
    chk("HOLD_INAPPLICABLE_QUALIFICATION_TIER_FOR_PRODUCT_FAMILY" in evaluate_gate40_pirfenidone_h4({**g40_ok, "gate0v_evidence": g0v_wrong_tier})["holds"], "G40_ADV_g0v_wrong_family_tier_hold")
    # 8. A-4b TERMINAL_HISTOLOGY reusing same animal ID across early & Day-28 cohorts FAILS!
    coh_overlap = _mk_r8_a4b_cohorts("2026-12-20T08:00:00Z")
    coh_overlap["day28_cohort_records"][0]["animal_id"] = coh_overlap["early_cohort_records"][0]["animal_id"]
    chk("FAIL_GATE_A4B_TERMINAL_EARLY_AND_DAY28_ANIMALS_NOT_DISJOINT" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_evidence": _sign_receipt({**a4b_y, **coh_overlap})})["failures"], "G40_ADV_a4b_terminal_overlap")
    # 9. A-4b null exclusion entry FAILS!
    chk("FAIL_GATE_A4B_EARLY_MALFORMED_OR_NULL_EXCLUSION_ROW:0" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_evidence": _sign_receipt({**a4b_y, "early_cohort_enrolled_coated_n": 9, "early_cohort_exclusions": [None]})})["failures"], "G40_ADV_a4b_null_excl")
    # 10. A-4b raw coated collagen indistinguishable from raw vehicle FAILS Welch t-test!
    coh_flat = _mk_r8_a4b_cohorts("2026-12-20T08:00:00Z")
    for r in coh_flat["day28_cohort_records"]:
        if r["arm"] == "COATED":
            r["pericapsular_collagen_thickness_um"] = 95.0
    chk("FAIL_GATE_A4B_RECOMPUTED_COLLAGEN_EFFICACY_OR_PVALUE_FAILED" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_evidence": _sign_receipt({**a4b_y, **coh_flat})})["failures"], "G40_ADV_a4b_flat_collagen_fails")

    # & Core 67 GATE-40 invariants
    chk("FAIL_A-1_COATING_IDENTITY_MISMATCH:coating_lot_id" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "coating_lot_id": "SWAPPED-LOT"})})["failures"], "G40_ADV_coating_lot_swap")
    chk("FAIL_GATE_A0A_ELAPSED_STUDY_DURATION_LT_7_DAYS" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "study_start_utc": "2026-06-28T08:00:00Z"})})["failures"], "G40_ADV_a0a_lt_7d")
    chk("FAIL_GATE_A0B_ELAPSED_OBSERVATION_LT_14_DAYS" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "study_start_utc": "2026-07-12T09:00:00Z"})})["failures"], "G40_ADV_a0b_lt_14d")
    chk("FAIL_GATE_A1_EXACT_STARTED_BEFORE_BENCH_A1_COMPLETION" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "elution_started_at_utc": "2026-08-15T10:00:00Z"})})["failures"], "G40_ADV_a1_before_bench")
    chk("FAIL_GATE_A1_RECOMPUTED_SYSTEMIC_PLASMA_CAP_BREACH" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "peak_daily_eluted_mg": 60.0})})["failures"], "G40_ADV_a1_sys_cap")
    chk("FAIL_GATE_A2_READOUT3B_R2_ALLO_CD8_CTL_GT_5PCT:NK-D1" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout3b_evidence": {**_mk_r8_readout3b(matched_vehicle_lot_id=bv_a), "donor_records": [{**_mk_r8_readout3b(matched_vehicle_lot_id=bv_a)["donor_records"][0], "regime_ii_t0_unpreinduced": {**_mk_r8_readout3b(matched_vehicle_lot_id=bv_a)["donor_records"][0]["regime_ii_t0_unpreinduced"], "allogeneic_cd8_ctl_lysis_pct": 8.0}}, *_mk_r8_readout3b(matched_vehicle_lot_id=bv_a)["donor_records"][1:]]}})})["failures"], "G40_ADV_a2_r3b_cd8_fail")
    chk("FAIL_GATE_A2_READOUT2_UNRECOGNIZED_OR_TAMPERED_CANONICAL_Z_MIN_FLOOR" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": {**_mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B"), "z_min_floor": 0.01}})})["failures"], "G40_ADV_r2_zmin_tamper")
    chk("FAIL_GATE_A4B_EARLY_PERFUSION_OUTSIDE_36_72H:E-COAT-01" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_evidence": _sign_receipt({**a4b_y, "early_cohort_records": [{**a4b_y["early_cohort_records"][0], "assessed_at_utc": "2026-12-20T20:00:00Z"}, *a4b_y["early_cohort_records"][1:]]})})["failures"], "G40_ADV_a4b_early_ts")
    g0v_60k = _mk_r8_gate0v(py, by, ly, ry, mat_y, "2026-10-12T09:30:00Z", coating_identity=coat_a, treated_72h_n=60000)
    chk("HOLD_GATE0V_ESTIMAND1_TOTAL_ESCAPE_U_GT_1E_4:active_persistent_cvb4:GCG_alpha" in evaluate_gate40_pirfenidone_h4({**g40_ok, "gate0v_evidence": g0v_60k})["holds"], "G40_ADV_g0v_60k_est1_hold")
    chk("FAIL_GATE_A2_READOUT2_O2_40_GLUCOSE_THRESHOLD_LT_4P5MM" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": {**_mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B"), "o2_40_mmhg": {"blocks": [{**_mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B")["o2_40_mmhg"]["blocks"][0], "glucose_threshold_mM": 3.5}, *_mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B")["o2_40_mmhg"]["blocks"][1:]]}}})})["failures"], "G40_ADV_r2_gthresh")

    chk("FAIL_GATE_A0B_ADDED_COATING_DIFF_PATH_GT_5UM" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "added_coating_water_equiv_diff_path_um": 6.5})})["failures"], "G40_ADV_a0b_added_path")
    chk("FAIL_GATE_A0B_LOCAL_PH_OUTSIDE_7P25_7P45" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "local_ph_min": 7.10})})["failures"], "G40_ADV_a0b_ph")
    chk("FAIL_GATE_A0B_PEAK_FREE_NOT_BELOW_ALL4_CEILINGS" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "peak_free_parent_u95_uM": 225.0})})["failures"], "G40_ADV_a0b_peak_ge")
    chk("FAIL_GATE_A0B_14D_SUSTAINED_NOT_BELOW_ALL4_CEILINGS" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "peak_free_parent_u95_uM": 235.0, "day14_sustained_free_parent_u95_uM": 220.0})})["failures"], "G40_ADV_a0b_sust_ge")
    chk("FAIL_GATE_A1_ELAPSED_ELUTION_DURATION_LT_35_DAYS" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "recorded_at_utc": "2026-09-10T10:00:00Z"})})["failures"], "G40_ADV_a1_elapsed_lt_35d")
    chk("FAIL_GATE_A4A_ELAPSED_COUPON_DURATION_LT_14_DAYS" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4a_evidence": _sign_receipt({**a4a_y, "recorded_at_utc": "2026-11-12T10:00:00Z"})})["failures"], "G40_ADV_a4a_elapsed_lt_14d")
    chk("FAIL_GATE_A4B_ELAPSED_STUDY_DURATION_LT_28_DAYS" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_evidence": _sign_receipt({**a4b_y, "recorded_at_utc": "2027-01-05T10:00:00Z"})})["failures"], "G40_ADV_a4b_elapsed_lt_28d")
    chk("FAIL_PREREQ_RECEIPT_DIGEST_BINDING_MISMATCH:GATE-0V-KILL_IN_A-4a" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4a_evidence": _sign_receipt({**a4a_y, "prerequisite_receipt_sha256s": {**pr_all_y, "GATE-0V-KILL": "0" * 64}})})["failures"], "G40_ADV_a4a_prereq_pin")
    chk("FAIL_NATIVE_SWITCH_OQ012_NEFF_EXCEEDS_FLOOR_N_F_ETA" in evaluate_gate40_pirfenidone_h4({**g40_ok, "native_switch_evidence": _sign_receipt({**sw_y, "oq012_clonogenic_block": _mk_r8_oq012(raw_cells=1_000_000_000, f_clon=0.5, eta=0.8, n_eff=500_000_000)})})["failures"], "G40_ADV_oq012_neff_exceeds_floor")
    chk("HOLD_NATIVE_SWITCH_OQ012_UNDERPOWERED_NEFF_LT_299573228" in evaluate_gate40_pirfenidone_h4({**g40_ok, "native_switch_evidence": _sign_receipt({**sw_y, "oq012_clonogenic_block": _mk_r8_oq012(raw_cells=500_000_000, f_clon=0.5, eta=0.8, n_eff=200_000_000)})})["holds"], "G40_ADV_oq012_underpowered_hold")
    chk("FAIL_GATE_A2_READOUT2_O2_40_PEAK_TO_BASAL_LT_4P5" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": {**_mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B"), "o2_40_mmhg": {"blocks": [{**_mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B")["o2_40_mmhg"]["blocks"][0], "pulse1_peak_to_basal_ratio": 3.2}, *_mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B")["o2_40_mmhg"]["blocks"][1:]]}}})})["failures"], "G40_ADV_r2_pkb_lt_4p5")
    chk("FAIL_GATE_A2_READOUT2_GATE_RESP1_OCR_FAILED" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": {**_mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B"), "gate_resp1_ocr_ratio": 1.15}})})["failures"], "G40_ADV_r2_ocr")
    chk("FAIL_GATE_A2_READOUT2_DEC134_WASHOUT_TAIL_FAILED" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": {**_mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B"), "dec134_washout_t90_min": 14.0}})})["failures"], "G40_ADV_r2_washout")
    chk("FAIL_GATE_A4B_EARLY_36_72H_LECTIN_PERFUSION_FAILED" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_evidence": _sign_receipt({**a4b_y, "early_cohort_records": [{**r, "raw_lectin_perfusion_signal": 80.0} if r["arm"] == "COATED" else r for r in a4b_y["early_cohort_records"]]})})["failures"], "G40_ADV_a4b_early_lectin")
    chk("FAIL_GATE_A4B_DAY28_LECTIN_VESSEL_DENSITY_FAILED" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_evidence": _sign_receipt({**a4b_y, "day28_cohort_records": [{**r, "raw_lectin_vessel_density": 82.0} if r["arm"] == "COATED" else r for r in a4b_y["day28_cohort_records"]]})})["failures"], "G40_ADV_a4b_day28_lectin")
    chk("FAIL_BENCH_PHASE_FORBIDS_EXACT_OR_ANIMAL_FIELDS:a4b_evidence" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a4b_evidence": None})["failures"], "G40_ADV_forbid_none_key")
    chk("FAIL_DESIGN_A_DRUG_FIREWALL_VIOLATION" in evaluate_gate40_pirfenidone_h4({**g40_ok, "target_arm": "A", "product_id": pa, "route_id": ra})["failures"], "G40_block_A")
    chk("FAIL_DESIGN_A_DRUG_FIREWALL_VIOLATION" in evaluate_gate40_pirfenidone_h4({**g40_ok, "product_id": "ISLET1_A4_ARM1B"})["failures"], "G40_block_A_alias")
    chk("FAIL_OUT_OF_ACTIVE_GATE_SCOPE_PRODUCT_ROUTE" in evaluate_gate40_pirfenidone_h4({**g40_ok, "target_arm": "B", "product_id": pb, "route_id": "R1"})["failures"], "G40_block_B_R1")
    chk("FAIL_LEGACY_PRODUCT_NON_TRANSFERABLE_TO_V090" in evaluate_gate40_pirfenidone_h4({**g40_ok, "product_id": "ISLET1_Y_FULLSTACK_V2_B2M_11TU"})["failures"], "G40_block_legacy")
    chk("FAIL_GATE_A0A_EMAX_BELOW_50PCT" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "emax_col1a1_pct": 42.0})})["failures"], "G40_a0a_emax")
    chk("FAIL_GATE_A0A_U95_BELOW_FITTED_IC50" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "ic50_free_max_u95_uM": 50.0})})["failures"], "G40_a0a_u95")
    chk("FAIL_GATE_A0A_ENDPOINT_SPLIT_GT_3X" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "ic50_free_alpha_sma_uM": 20.0, "ic50_free_col1a1_uM": 70.0})})["failures"], "G40_a0a_split")
    chk("FAIL_GATE_A0A_MARGIN_BELOW_1P5X" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "cc10_free_7d_l95_uM": 100.0, "c_sprout_max_free_7d_l95_uM": 100.0, "c_upper_provisional_7d_l95_uM": 100.0})})["failures"], "G40_a0a_margin")
    chk("FAIL_GATE_A0A_7D_CEILING_NOT_MIN_OF_VIABILITY_AND_SPROUTING" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "c_upper_provisional_7d_l95_uM": 270.0})})["failures"], "G40_a0a_7d_min")
    chk("FAIL_GATE_A0B_COATING_THICKNESS_INVALID" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "coating_thickness_um": 12.0})})["failures"], "G40_a0b_thick")
    chk("FAIL_GATE_A0B_DAY1_BURST_INVALID_OR_GT_15PCT" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "day1_burst_pct": 18.0})})["failures"], "G40_a0b_burst")
    chk("FAIL_GATE_A0B_SYSTEMIC_PLASMA_CAP_BREACH" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "modeled_systemic_plasma_ug_ml": 0.25})})["failures"], "G40_a0b_plasma")
    chk("FAIL_GATE_A0B_SUSTAINED_FREE_BELOW_IC50_U95" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "sustained_free_parent_lower_uM": 60.0})})["failures"], "G40_a0b_sust")
    chk("FAIL_GATE_A0B_14D_CEILING_EXCEEDS_7D_CEILING" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "cc10_free_14d_l95_uM": 300.0, "c_sprout_max_free_14d_l95_uM": 280.0, "c_upper_provisional_14d_l95_uM": 280.0})})["failures"], "G40_a0b_14gt7")
    chk("FAIL_GATE_A1_ELUTION_T50_OUT_OF_7_14_DAYS" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "elution_t50_days": 5.0})})["failures"], "G40_a1_t50")
    chk("FAIL_GATE_A1_DAY14_USABLE_FRACTION_GT_85PCT" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "day14_usable_delivery_fraction_pct": 90.0})})["failures"], "G40_a1_usable")
    chk("FAIL_GATE_A1_DAY35_EXHAUSTION_OR_RESIDUAL_FAILED" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "day35_depot_exhaustion_pct": 85.0, "day35_residual_parent_pct": 15.0})})["failures"], "G40_a1_exh")
    chk("FAIL_GATE_A1_DAY35_MASS_RECOVERY_OUT_OF_90_110" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "day35_terminal_mass_recovery_pct": 82.0})})["failures"], "G40_a1_mass")
    chk("FAIL_GATE_A2_SHIELD_COMPONENT_BELOW_85PCT:SERPINB9" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "shield_retention_by_component": {**_mk_r8_shields(py), "SERPINB9": 79.0}})})["failures"], "G40_a2_shield")
    chk("FAIL_GATE_A2_DAY14_IEC_TEER_BELOW_90PCT" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "day14_iec_teer_pct_ctrl": 80.0})})["failures"], "G40_a2_teer")
    chk("FAIL_GATE_A2_CD47_HOUR0_GY009_BELOW_200K_180K:PLVAP_iEC" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "hour0_density_by_lineage": {**_mk_r8_hour0(py), "PLVAP_iEC": {**_mk_r8_hour0(py)["PLVAP_iEC"], "cd47_p10_molecules_per_cell": 150000.0}}})})["failures"], "G40_a2_cd47")
    bad_swp_a3 = _mk_r8_switch_parity(bv_a); bad_swp_a3["treated_72h_kill_pct_by_block"] = [99.90]*6; bad_swp_a3["reported_l95_72h_delta_pp"] = -0.10
    chk("FAIL_GATE_A3_SW_PARITY_72H_NONINFERIORITY_MARGIN_FAILED" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a3_evidence": _sign_receipt({**a3_y, "matched_control_switch_parity_evidence": _sign_receipt(bad_swp_a3)})})["failures"], "G40_a3_ni72")
    chk("FAIL_GATE_A4A_COUPON_EFFICACY_BELOW_50PCT:day7_col1a1" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4a_evidence": _sign_receipt({**a4a_y, "day7_col1a1_reduction_pct": 40.0})})["failures"], "G40_a4a_d7")
    chk("FAIL_GATE_A4B_IMPLANT_EXTRUSION_DETECTED" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_evidence": _sign_receipt({**a4b_y, "implant_extrusions": 1})})["failures"], "G40_a4b_extr")
    chk("FAIL_GATE_A4B_BLINDED_ALLOCATION_REQUIRED" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_evidence": _sign_receipt({**a4b_y, "blinded_allocation": False})})["failures"], "G40_a4b_blind")
    chk("FAIL_GATE_A4B_ANIMAL_WORK_STARTED_BEFORE_A4A_AUTHORIZATION" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_evidence": _sign_receipt({**a4b_y, "animal_work_started_at_utc": "2026-11-10T08:00:00Z"})})["failures"], "G40_a4b_early_start")
    chk("FAIL_RECEIPT_CONTENT_HASH_TAMPER:A-4a" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4a_evidence": {**a4a_y, "day14_viability_pct": 99.0}})["failures"], "G40_hash_tamper")
    chk("FAIL_CHRONOLOGICAL_TIMESTAMP_ORDER_VIOLATION:A-3" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a3_evidence": _sign_receipt({**a3_y, "recorded_at_utc": "2026-10-10T10:00:00Z"})})["failures"], "G40_ts_order")
    chk("HOLD_GATE_A4B_RODENT_NOT_YET_COMPLETED" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_evidence": None})["holds"], "G40_a4b_hold")
    chk("FAIL_GATE40_UNKNOWN_OR_UNRECONCILED_FIELDS:rogue_key" in evaluate_gate40_pirfenidone_h4({**g40_ok, "rogue_key": 1})["failures"], "G40_unknown_key")
    # Deferred X/R1 quantitative GATE-31 + Route-4 separate vehicle check
    coat_x = _mk_r8_coating("PFD-XR1"); bv_x = coat_x["matched_blank_vehicle_lot_id"]
    mat_x = _mk_r8_mat(px, bx, lx, "2026-08-27T08:00:00Z")
    g31_x = _mk_r8_gate31(px, bx, lx, mat_x, coating_stab=True, ts="2026-08-28T09:00:00Z")
    sw_x = _mk_r8_switch(px, bx, lx, rx, mat_x, "2026-10-12T09:00:00Z", coating_identity=coat_x)
    g0v_x = _mk_r8_gate0v(px, bx, lx, rx, mat_x, "2026-10-12T09:30:00Z", coating_identity=coat_x)
    a0b_tp_x = _mk_pfd_tp_rows(a0b_tp_pts, coat_x["coating_lot_id"], "A0BX")
    a1_tp_x = _mk_pfd_tp_rows(a1_tp_pts, coat_x["coating_lot_id"], "A1X")
    a0b_x = _sign_receipt({**a0b_y, **coat_x, "product_id": px, "bank_id": bx, "lot_id": lx, "route_id": rx, "a0b_local_exposure_timepoints": a0b_tp_x, "a0b_local_pk_envelope": _mk_pfd_env("bench_unedited", "BENCH_LOCAL_PERI_GRAFT", art_id=coat_x["coating_article_id"], lot_id=coat_x["coating_lot_id"]), "a0b_local_ph_timepoints": [{"hour_h": h_p, "coating_lot_id": coat_x["coating_lot_id"], "ph_min": 7.33, "ph_max": 7.38} for h_p in (24.0, 168.0, 336.0)], "manufacturing_lot_release_records": _mk_pfd_3lots(coat_x["coating_lot_id"], tr14_t, tr14_m)})
    a1b_x = _sign_receipt({**a1b_y, **coat_x, "product_id": px, "bank_id": bx, "lot_id": lx, "route_id": rx, "parent_receipt_sha256": a0b_x["receipt_sha256"], "a1_local_free_parent_timepoints": a1_tp_x, "a1_local_pk_envelope": _mk_pfd_env("bench_unedited", "BENCH_ELUTION_LOCAL_PERI_GRAFT", art_id=coat_x["coating_article_id"], lot_id=coat_x["coating_lot_id"]), "a1_local_ph_timepoints": [{"hour_h": h_p, "coating_lot_id": coat_x["coating_lot_id"], "ph_min": 7.32, "ph_max": 7.39} for h_p in (24.0, 168.0, 336.0, 504.0, 672.0, 840.0)], "manufacturing_lot_release_records": _mk_pfd_3lots(coat_x["coating_lot_id"], tr35_t, tr35_m)})
    pr_mx = {"BANK_MATERIALIZATION": mat_x["receipt_sha256"]}
    pr_a1x = {"BANK_MATERIALIZATION": mat_x["receipt_sha256"], "GATE-31": g31_x["receipt_sha256"]}
    pr_ax = {"BANK_MATERIALIZATION": mat_x["receipt_sha256"], "NATIVE_SAFETY_SWITCH": sw_x["receipt_sha256"], "GATE-0V-KILL": g0v_x["receipt_sha256"]}
    a1_x = _sign_receipt({**a1_y, **coat_x, "product_id": px, "bank_id": bx, "lot_id": lx, "route_id": rx, "parent_receipt_sha256": a1b_x["receipt_sha256"], "prerequisite_receipt_sha256s": pr_a1x, "a1_local_free_parent_timepoints": a1_tp_x, "a1_local_pk_envelope": _mk_pfd_env("exact_product", "BENCH_ELUTION_LOCAL_PERI_GRAFT", art_id=coat_x["coating_article_id"], lot_id=coat_x["coating_lot_id"]), "a1_local_ph_timepoints": [{"hour_h": h_p, "coating_lot_id": coat_x["coating_lot_id"], "ph_min": 7.32, "ph_max": 7.39} for h_p in (24.0, 168.0, 336.0, 504.0, 672.0, 840.0)], "manufacturing_lot_release_records": _mk_pfd_3lots(coat_x["coating_lot_id"], tr35_t, tr35_m)})
    _a2_vraw_x_b = {k: v for k, v in a2_y["a2_vascular_raw_measurements"].items() if k != "vascular_assay_receipt_sha256"}
    _a2_vraw_x_b.update({"specimen_id": f"SPEC-A2-{lx}", "coating_lot_id": coat_x["coating_lot_id"], "matched_vehicle_lot_id": bv_x})
    a2_x = _sign_receipt({**a2_y, **coat_x, "product_id": px, "bank_id": bx, "lot_id": lx, "route_id": rx, "a2_specimen_id": f"SPEC-A2-{lx}", "a2_cohort_id": f"COHORT-A2-{lx}", "parent_receipt_sha256": a1_x["receipt_sha256"], "prerequisite_receipt_sha256s": pr_mx, "a2_vascular_vehicle_record_id": f"A2-VASC-VEH-{bv_x}", "a2_vascular_raw_measurements": {**_a2_vraw_x_b, "vascular_assay_receipt_sha256": sha256_bytes(canonical_json_bytes(_a2_vraw_x_b))}, "shield_retention_by_component": _mk_r8_shields(px), "hour0_density_by_lineage": _mk_r8_hour0(px), "readout2_evidence": _mk_r8_readout2(matched_comparator_id=bv_x, block_prefix="A2X", lot_id=lx), "readout3b_evidence": _mk_r8_readout3b(matched_vehicle_lot_id=bv_x, include_hla_e_spr=False, specimen_id=f"SPEC-A2-{lx}", specimen_lot_id=lx, intervention_cohort_id=f"COHORT-A2-{lx}")})
    a3_x = _sign_receipt({**a3_y, **coat_x, "product_id": px, "bank_id": bx, "lot_id": lx, "route_id": rx, "parent_receipt_sha256": a2_x["receipt_sha256"], "prerequisite_receipt_sha256s": pr_mx, "matched_control_switch_parity_evidence": _mk_r8_switch_parity(bv_x)})
    a4a_x = _sign_receipt({**a4a_y, **coat_x, "product_id": px, "bank_id": bx, "lot_id": lx, "route_id": rx, "parent_receipt_sha256": a3_x["receipt_sha256"], "prerequisite_receipt_sha256s": pr_ax})
    a4b_prereg_x, a4b_coh_x = _mk_r8_a4b_prereg_and_cohorts(px, bx, lx, rx, a4a_x, coat_x, start_dt_str="2026-12-20T08:00:00Z")
    pr_a4b_x = {**pr_ax, "A-4b-PREREGISTRATION": a4b_prereg_x["receipt_sha256"]}
    a4b_x = _sign_receipt({**a4b_y, **coat_x, "product_id": px, "bank_id": bx, "lot_id": lx, "route_id": rx, "parent_receipt_sha256": a4a_x["receipt_sha256"], "prerequisite_receipt_sha256s": pr_a4b_x, **a4b_coh_x})
    g40_x = {
        "phase": "EXACT_PRODUCT", "track_mode": "DEFERRED_NON_PRIMARY", "credit_scope": "NON_PRIMARY_TRACK_ONLY",
        "target_arm": "X", "product_id": px, "bank_id": bx, "lot_id": lx, "route_id": rx,
        "materialization_evidence": mat_x, "gate31_evidence": g31_x, "native_switch_evidence": sw_x, "gate0v_evidence": g0v_x,
        "a0a_evidence": a0a_ok, "a0b_evidence": a0b_x, "a1_bench_evidence": a1b_x, "a1_evidence": a1_x, "a2_evidence": a2_x, "a3_evidence": a3_x, "a4a_evidence": a4a_x,
        "a4b_preregistration_receipt": a4b_prereg_x, "a4b_evidence": a4b_x,
    }
    chk(evaluate_gate40_pirfenidone_h4(g40_x)["verdict"] == "DEFERRED_TRACK_QUALIFICATION_NON_PRIMARY", "G40_X_R1_deferred_pass")
    chk("FAIL_DEFERRED_X_R1_GATE31_CONSERVED_CAO2_LOADING_OUT_OF_791P5MG_5PCT" in evaluate_gate40_pirfenidone_h4({**g40_x, "gate31_evidence": _sign_receipt({**g31_x, "conserved_cao2_loading_mg": 600.0})})["failures"], "G40_X_R1_g31_cao2_fail")
    chk("FAIL_DEFERRED_X_R1_GATE31_COATING_STABILITY_UNVERIFIED" in evaluate_gate40_pirfenidone_h4({**g40_x, "gate31_evidence": _sign_receipt({**g31_x, "coating_stability_verified": False})})["failures"], "G40_X_R1_g31_stab")
    chk("FAIL_GATE_A2_READOUT2_O2_40_CHAMBER_TRACER_OR_DISPERSION_FAILED" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": {**_mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B"), "o2_40_mmhg": {"blocks": [{**_mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B")["o2_40_mmhg"]["blocks"][0], "chamber_tau_min": 0.8}, *_mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B")["o2_40_mmhg"]["blocks"][1:]]}}})})["failures"], "G40_r2_tau_fail")
    chk("FAIL_GATE_A2_READOUT2_O2_40_SHUTOFF_T50_LE_3MIN_OR_ORDER_FAILED" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": {**_mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B"), "o2_40_mmhg": {"blocks": [{**_mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B")["o2_40_mmhg"]["blocks"][0], "stepdown_t50_min": 2.9, "stepdown_t90_min": 2.8}, *_mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B")["o2_40_mmhg"]["blocks"][1:]]}}})})["failures"], "G40_r2_t50_t90")
    chk("FAIL_GATE_A2_READOUT2_ALK5I_FREE_NOT_VERIFIED" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": {**_mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B"), "alk5i_free_maturation_applied": False}})})["failures"], "G40_r2_alk5i")
    chk("FAIL_GATE_A2_READOUT2_ZM447439_WASHOUT_GT_0P005UM" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": {**_mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B"), "zm447439_washout_lcms_uM": 0.01}})})["failures"], "G40_r2_zm")
    chk("FAIL_GATE_A2_READOUT2_INVALID_DUAL_CLOCKS_ORDER" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": {**_mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B"), "dual_clocks_utc": {"stage7_start_utc": "2026-10-20T00:00:00Z", "sort_reaggregation_utc": "2026-10-15T00:00:00Z", "assay_harvest_utc": "2026-10-22T00:00:00Z"}}})})["failures"], "G40_r2_clocks")
    chk("HOLD_GATE_A2_READOUT2_GATE0S_ESCALATION_REQUIRED_GT_138P3_IU" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": _mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B", stored_u95_iu=145.0, gate0s_cleared=False)})})["holds"], "G40_ADV_r2_gate0s_hold")
    r2_cp39 = _mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B"); r2_cp39["o2_100_mmhg"] = r2_cp39["o2_40_mmhg"]
    chk("FAIL_GATE_A2_READOUT2_IDENTICAL_COPY_PASTE_40_AND_100MMHG" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": r2_cp39})})["failures"], "G40_ADV_r2_copypaste_o2")
    chk("FAIL_DUAL_SWITCH_ORTHOGONAL_NON_INTERFERENCE_UNVERIFIED" in evaluate_gate40_pirfenidone_h4({**g40_ok, "native_switch_evidence": _sign_receipt({**sw_y, "orthogonal_gcv_cid_non_interference": False})})["failures"], "G40_dual_orthog")
    chk("HOLD_GATE0V_KILL_EVIDENCE_MISSING" in evaluate_gate40_pirfenidone_h4({**g40_ok, "gate0v_evidence": None})["holds"], "G40_g0v_missing")
    chk("FAIL_NATIVE_SAFETY_SWITCH_MISMATCH_FOR_PRODUCT" in evaluate_gate40_pirfenidone_h4({**g40_ok, "native_switch_evidence": _sign_receipt({**sw_y, "switch_name": "TBP_ICASP9"})})["failures"], "G40_sw_mismatch")
    chk("HOLD_CANONICAL_BANK_MATERIALIZATION_MISSING" in evaluate_gate40_pirfenidone_h4({**g40_ok, "materialization_evidence": None})["holds"], "G40_mat_missing")
    chk("FAIL_A-0b_COATING_AND_BLANK_VEHICLE_LOT_IDENTICAL" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "matched_blank_vehicle_lot_id": coat_a["coating_lot_id"]})})["failures"], "G40_same_coat_veh")
    chk("FAIL_GATE_A0B_WORST_FACE_O2_BELOW_40MMHG" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "worst_face_o2_mmhg": 35.0})})["failures"], "G40_a0b_o2")
    chk("FAIL_GATE_A0B_DAY14_VIABILITY_BELOW_90PCT" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "day14_viability_pct": 85.0})})["failures"], "G40_a0b_viab")
    chk("FAIL_GATE_A0B_DAY14_SPROUTING_BELOW_90PCT" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "day14_sprouting_pct": 84.0})})["failures"], "G40_a0b_spr")
    chk("FAIL_GATE_A2_DAY14_IEC_VCAM1_GT_1P25" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "day14_iec_vcam1_adhesion_fold": 1.45})})["failures"], "G40_a2_vcam")
    chk("FAIL_GATE_A2_WORST_FACE_O2_BELOW_40MMHG" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "worst_face_o2_mmhg": 32.0})})["failures"], "G40_a2_o2")
    chk("FAIL_GATE_A4A_DAY14_VIABILITY_BELOW_90PCT" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4a_evidence": _sign_receipt({**a4a_y, "day14_viability_pct": 80.0})})["failures"], "G40_a4a_viab")
    chk("FAIL_GATE_A4A_WORST_FACE_O2_BELOW_40MMHG" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4a_evidence": _sign_receipt({**a4a_y, "worst_face_o2_mmhg": 30.0})})["failures"], "G40_a4a_o2")
    chk("FAIL_GATE_A0A_ENDPOINTS_UNBRACKETED" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "endpoints_bracketed": False})})["failures"], "G40_a0a_unbrack")
    chk("FAIL_GATE_A0A_FU_OUT_OF_DOMAIN" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "fu_measured": 1.2})})["failures"], "G40_a0a_fu")
    chk("FAIL_GATE_A0B_WATER_EQUIV_DIFF_PATH_GT_50UM" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "water_equiv_diff_path_um": 65.0})})["failures"], "G40_a0b_wpath")
    chk("FAIL_GATE_A1_DAY14_INTACT_PARENT_BELOW_IC50_U95" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "day14_intact_parent_free_uM": 50.0})})["failures"], "G40_a1_d14_low")
    chk("FAIL_GATE_A1_DAY35_INTACT_PARENT_NOT_EXHAUSTED" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "day35_intact_parent_free_uM": 15.0})})["failures"], "G40_a1_d35_hi")

    # ========================================================================
    # GATE-41 (80 tests: 70 prior + 10 adversarial closures)
    # ========================================================================
    coat_b = _mk_r8_coating("DEUC-R3P")
    bv_b = coat_b["matched_blank_vehicle_lot_id"]
    b0a_s_units = ["SAFE-U1", "SAFE-U2", "SAFE-U3", "SAFE-U4", "SAFE-U5", "SAFE-U6"]
    _b0a_d6 = (-0.38, -0.20, -0.06, 0.06, 0.20, 0.38)
    def _mk_b0a_raw_ratio(pcts: Sequence[float], veh_id: str, base_v: float, *, is_inhib: bool = False) -> dict[str, Any]:
        vehs = [round(base_v * (1.0 + 0.01 * (j - 2.5)), 4) for j in range(len(pcts))]
        if is_inhib:
            trs = [round(vehs[j] * (1.0 - float(pcts[j]) / 100.0), 4) for j in range(len(pcts))]
        else:
            trs = [round(vehs[j] * (float(pcts[j]) / 100.0), 4) for j in range(len(pcts))]
        return {"vehicle_record_id": veh_id, "treated": trs, "vehicle": vehs}

    b0a_s_reps_ok = [
        (lambda _vid, _sp, _nk, _cd, _il: {
            "unit_ids": b0a_s_units,
            "matched_vehicle_record_id": _vid,
            "sprouting_pct": _sp,
            "nkg2a_pct": _nk,
            "cd94_pct": _cd,
            "il10_retention_pct": _il,
            "raw_unit_measurements": {
                "sprouting_pct": _mk_b0a_raw_ratio(_sp, _vid, 400.0),
                "nkg2a_pct": _mk_b0a_raw_ratio(_nk, _vid, 12000.0),
                "cd94_pct": _mk_b0a_raw_ratio(_cd, _vid, 9500.0),
                "il10_retention_pct": _mk_b0a_raw_ratio(_il, _vid, 850.0),
            },
        })(
            f"B0A-VEH-CONC-{idx_b}",
            [round(s + d, 2) for d in _b0a_d6],
            [round(n + d, 2) for d in _b0a_d6],
            [round(c + d, 2) for d in _b0a_d6],
            [round(il + d, 2) for d in _b0a_d6],
        )
        for idx_b, (s, n, c, il) in enumerate(zip(
            [100.0, 99.0, 98.0, 97.0, 95.0, 93.0, 82.0, 65.0],
            [100.0, 99.0, 98.0, 96.0, 94.0, 91.0, 78.0, 60.0],
            [100.0, 99.0, 97.0, 96.0, 94.0, 90.0, 76.0, 58.0],
            [100.0, 98.0, 96.0, 94.0, 90.0, 86.0, 70.0, 50.0],
        ))
    ]
    b0a_e_units = ["EFF-U1", "EFF-U2", "EFF-U3", "EFF-U4", "EFF-U5", "EFF-U6"]
    b0a_eb_grid = [0.0, 24.0, 50.0, 72.0, 86.0, 93.0, 97.0, 98.5]
    b0a_en_grid = [0.0, 23.0, 49.0, 70.0, 85.0, 92.5, 96.5, 98.2]
    b0a_ei_grid = [0.0, 22.0, 48.0, 68.0, 84.0, 92.0, 96.0, 98.0]
    b0a_e_reps_ok = [
        (lambda _vid, _eb, _en, _ei: {
            "unit_ids": b0a_e_units,
            "matched_vehicle_record_id": _vid,
            "beta_cytokine_protection_pct": _eb,
            "nk_cytokine_suppression_pct": _en,
            "iec_ibmir_marker_suppression_pct": _ei,
            "raw_unit_measurements": {
                "beta_cytokine_protection_pct": _mk_b0a_raw_ratio(_eb, _vid, 100.0, is_inhib=True),
                "nk_cytokine_suppression_pct": _mk_b0a_raw_ratio(_en, _vid, 500.0, is_inhib=True),
                "iec_ibmir_marker_suppression_pct": _mk_b0a_raw_ratio(_ei, _vid, 250.0, is_inhib=True),
            },
        })(
            f"B0A-EFF-VEH-CONC-{idx_e}",
            [round(eb_v + d, 2) for d in _b0a_d6],
            [round(en_v + d, 2) for d in _b0a_d6],
            [round(ei_v + d, 2) for d in _b0a_d6],
        )
        for idx_e, (eb_v, en_v, ei_v) in enumerate(zip(b0a_eb_grid, b0a_en_grid, b0a_ei_grid))
    ]
    b0a_an_ok = _sign_receipt({
        "analysis_method": "SIMULTANEOUS_BONFERRONI_GRID_BRACKET_STUDENT_T",
        "efficacy_combination_rule": "CONJUNCTIVE_MAX_EC50_U95_ACROSS_ALL_3_ENDPOINTS",
        "efficacy_endpoints_tested": [
            "beta_cytokine_protection_pct",
            "iec_ibmir_marker_suppression_pct",
            "nk_cytokine_suppression_pct",
        ],
        "efficacy_unit_ids": b0a_e_units,
        "safety_unit_ids": b0a_s_units,
        "raw_efficacy_replicates_sha256": sha256_bytes(canonical_json_bytes(b0a_e_reps_ok)),
        "raw_safety_replicates_sha256": sha256_bytes(canonical_json_bytes(b0a_s_reps_ok)),
        "analysis_record_sha256": "a" * 64,
        "ec50_eff_u95_free_nM": 6.0, "c_safe_max_bench_l95_free_nM": 25.0,
    })
    b0a_ok = _sign_receipt({
        "stage": "B-0a", "verdict": "PASS", "evidence_scope": "route_free",
        "recorded_at_utc": "2026-08-01T08:00:00Z", "endpoints_bracketed": True,
        "analysis_record_sha256": "a" * 64,
        "lloq_parent_by_matrix_nM": {"low_serum_media": 0.05, "human_serum_100pct": 0.05, "whole_blood": 0.05},
        "lloq_bmt_by_matrix_nM": {"low_serum_media": 0.05, "human_serum_100pct": 0.05, "whole_blood": 0.05},
        "fu_parent_by_matrix": {"low_serum_media": 0.85, "human_serum_100pct": 0.14, "whole_blood": 0.11},
        "fu_bmt_by_matrix": {"low_serum_media": 0.86, "human_serum_100pct": 0.15, "whole_blood": 0.12},
        "tested_free_conc_grid_nM": [0.0, 1.0, 3.0, 6.0, 12.0, 25.0, 50.0, 100.0],
        "efficacy_inhibition_pct_grid": list(b0a_ei_grid),
        "efficacy_beta_protection_pct_grid": list(b0a_eb_grid),
        "efficacy_nk_suppression_pct_grid": list(b0a_en_grid),
        "efficacy_iec_ibmir_pct_grid": list(b0a_ei_grid),
        "safety_sprouting_pct_grid": [100.0, 99.0, 98.0, 97.0, 95.0, 93.0, 82.0, 65.0],
        "safety_nkg2a_pct_grid": [100.0, 99.0, 98.0, 96.0, 94.0, 91.0, 78.0, 60.0],
        "safety_cd94_pct_grid": [100.0, 99.0, 97.0, 96.0, 94.0, 90.0, 76.0, 58.0],
        "safety_il10_retention_pct_grid": [100.0, 98.0, 96.0, 94.0, 90.0, 86.0, 70.0, 50.0],
        "safety_replicates_by_conc": b0a_s_reps_ok,
        "efficacy_replicates_by_conc": b0a_e_reps_ok,
        "b0a_analysis_receipt": b0a_an_ok,
        "ec50_eff_u95_free_nM": 6.0, "c_safe_max_bench_l95_free_nM": 25.0,
    })
    def _mk_b0b_pk_model(b0a_sha: str, **ov: Any) -> dict[str, Any]:
        body: dict[str, Any] = {
            "b0a_receipt_sha256": b0a_sha,
            "pk_model_protocol_sha256": "c" * 64,
            "modeled_day1_burst_pct": 14.0,
            "modeled_days0_10_parent_l95_free_nM": 7.2,
            "modeled_days0_21_combined_peak_u95_free_nM": 19.5,
            "modeled_systemic_combined_cmax_u95_total_nM": 0.12,
            "alpha_conc": 0.025, "alpha_fu_parent": 0.0125, "alpha_fu_bmt": 0.0125,
            "used_marginal_u95_sum": False, "lloq_censoring_allocated": True,
        }
        body.update(ov)
        return {**body, "model_receipt_sha256": sha256_bytes(canonical_json_bytes(body))}

    b0b_pk_ok = _mk_b0b_pk_model(b0a_ok["receipt_sha256"])
    b0b_y = _sign_receipt({
        "stage": "B-0b", "verdict": "PASS", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "bench_unedited", "recorded_at_utc": "2026-08-05T09:00:00Z",
        "parent_receipt_sha256": b0a_ok["receipt_sha256"], **coat_b,
        "coating_thickness_um": 3.5, "worst_face_o2_mmhg": 44.0,
        "local_ph_min": 7.32, "local_ph_max": 7.40, "mass_balance_margin_verified": True,
        "route_clearance_l_per_day": 6.0, "target_total_conc_nM": 50.0, "active_duration_days": 10.0,
        "loaded_api_mass_mg": 2.0, "usable_recovery_fraction": 0.80,
        "provisional_pk_model_receipt": b0b_pk_ok,
    })
    _b2b_ref_tps = _mk_r8_b2b_replicates()["timepoint_replicate_records"]
    def _mk_b12_ledger(stage_tag: str, tps: Sequence[Mapping[str, Any]] = _b2b_ref_tps, *, assay_matrix: str = "human_serum_100pct", recirc_assay_matrix: str = "human_serum_100pct") -> list[dict[str, Any]]:
        out_lg: list[dict[str, Any]] = []
        for _tr in tps:
            _is_b2 = abs(float(_tr["hour_h"]) - 2.0) <= 1e-6
            if (stage_tag == "B-2" and not _is_b2) or (stage_tag == "B-1" and _is_b2):
                continue
            for _ri_l, _sid_l in enumerate(_tr["source_sample_ids"]):
                _buid_l = str(_tr["biological_unit_ids"][_ri_l]).strip().upper()
                _row_obj = {
                    "sample_id": str(_sid_l).strip().upper(),
                    "hour_h": float(_tr["hour_h"]),
                    "assay_matrix": assay_matrix,
                    "recirc_assay_matrix": recirc_assay_matrix,
                    "biological_unit_id": _buid_l,
                    "local_parent_total_nM": float(_tr["local_parent_total_replicates_nM"][_ri_l]), "local_parent_blq": bool(_tr["local_parent_blq_flags"][_ri_l]),
                    "local_bmt_total_nM": float(_tr["local_bmt_total_replicates_nM"][_ri_l]), "local_bmt_blq": bool(_tr["local_bmt_blq_flags"][_ri_l]),
                    "recirc_bmt_total_nM": float(_tr["recirc_bmt_total_replicates_nM"][_ri_l]), "recirc_bmt_blq": bool(_tr["recirc_bmt_blq_flags"][_ri_l]),
                    "systemic_parent_total_nM": float(_tr["systemic_parent_total_replicates_nM"][_ri_l]), "systemic_parent_blq": bool(_tr["systemic_parent_blq_flags"][_ri_l]),
                    "systemic_bmt_total_nM": float(_tr["systemic_bmt_total_replicates_nM"][_ri_l]), "systemic_bmt_blq": bool(_tr["systemic_bmt_blq_flags"][_ri_l]),
                }
                out_lg.append({
                    "sample_id": _sid_l, "hour_h": float(_tr["hour_h"]), "source_stage": stage_tag,
                    "assay_matrix": assay_matrix, "recirc_assay_matrix": recirc_assay_matrix, "biological_unit_id": _buid_l,
                    "raw_analytical_row_sha256": sha256_bytes(canonical_json_bytes(_row_obj)),
                })
        return out_lg
    b1_ledger_ok = _mk_b12_ledger("B-1")
    b2_ledger_ok = _mk_b12_ledger("B-2")
    b1_y = _sign_receipt({
        "stage": "B-1", "verdict": "PASS", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "bench_unedited", "elution_started_at_utc": "2026-08-06T09:00:00Z",
        "recorded_at_utc": "2026-08-28T09:00:00Z", "parent_receipt_sha256": b0b_y["receipt_sha256"], **coat_b,
        "day1_burst_pct": 14.0, "day21_effluent_total_nM": 3.5, "day21_effluent_free_nM": 0.45,
        "day21_depot_depletion_pct": 91.0, "day21_elution_verified": True, "terminal_mass_recovery_pct": 97.0,
        "analytical_sample_ledger": b1_ledger_ok,
    })
    b2_y = _sign_receipt({
        "stage": "B-2", "verdict": "PASS", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "bench_unedited", "recorded_at_utc": "2026-09-05T10:00:00Z",
        "parent_receipt_sha256": b1_y["receipt_sha256"], **coat_b,
        "enrolled_donors_n": 6, "excluded_invalid_donors_n": 0, "invalid_donor_exclusion_log": [],
        "donor_records": _mk_r8_b2_donors(),
        "analytical_sample_ledger": b2_ledger_ok,
        "iec_sprouting_pct_ctrl": 95.0, "iec_birc5_viability_pct": 94.0,
        "iec_txnip_fold": 1.10, "iec_ros_fold": 1.05, "iec_cd274_pct_ctrl": 92.0, "iec_hlae_pct_ctrl": 93.0,
        "iec_pgf_pct_ctrl": 91.0, "iec_c3_fold_vs_ctrl": 1.08,
    })
    b2bb_y = _sign_receipt({
        "stage": "B-2b-bench", "verdict": "PASS", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "bench_unedited", "recorded_at_utc": "2026-09-12T10:00:00Z",
        "parent_receipt_sha256": b2_y["receipt_sha256"],
        "prerequisite_receipt_sha256s": {"B-1": b1_y["receipt_sha256"], "B-2": b2_y["receipt_sha256"]}, **coat_b,
        "used_marginal_u95_sum": False, "alpha_conc": 0.025, "alpha_fu_parent": 0.0125, "alpha_fu_bmt": 0.0125,
        "u95_joint_peak_free_nM": 20.8, "days0_10_parent_lower_free_nM": 7.0,
        **_mk_r8_b2b_replicates(),
        "c_bmt_local_total_u_alloc_nM": 0.04, "c_bmt_local_free_u_alloc_nM": 0.02,
        "c_bmt_recirc_total_u_alloc_nM": 0.03, "c_bmt_recirc_free_u_alloc_nM": 0.02,
        "censoring_audit_passed": True, "intersample_peak_envelope_justified": True,
        "systemic_exposure_below_cap": True, "mixture_requalified": False,
    })
    mat_y40 = _mk_r8_mat(py, by, ly, "2026-09-15T08:00:00Z")
    b0a_ex_y = _sign_receipt({
        "stage": "B-0a-exact", "verdict": "PASS", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "exact_product", "recorded_at_utc": "2026-09-20T09:00:00Z",
        "parent_receipt_sha256": mat_y40["receipt_sha256"],
        "prerequisite_receipt_sha256s": {"B-0a": b0a_ok["receipt_sha256"], "B-2b-bench": b2bb_y["receipt_sha256"], "BANK_MATERIALIZATION": mat_y40["receipt_sha256"]},
        **coat_b,
        "endpoints_bracketed": True, "analysis_record_sha256": "b" * 64,
        "tested_free_conc_grid_nM": [0.0, 5.0, 12.0, 22.0, 45.0, 90.0],
        "cassette_retention_pct_grid": [100.0, 97.0, 94.0, 91.0, 80.0, 62.0],
        "cassette_retention_replicates_by_conc": [
            (lambda _vid, _tech, _blk: {
                "unit_ids": ["B0AEX-BLK-1", "B0AEX-BLK-2", "B0AEX-BLK-3", "B0AEX-BLK-4", "B0AEX-BLK-5"],
                "matched_vehicle_record_id": _vid,
                "technical_replicates_per_unit_pct": _tech,
                "cassette_retention_pct": _blk,
                "raw_unit_measurements": {
                    "vehicle_record_id": _vid,
                    "vehicle_by_unit_tech": [[1000.0, 1005.0, 995.0] for _ in _tech],
                    "treated_by_unit_tech": [
                        [round(vh * pct / 100.0, 4) for vh, pct in zip((1000.0, 1005.0, 995.0), tw)]
                        for tw in _tech
                    ],
                },
            })(
                f"B0AEX-VEH-{int(c_nm)}NM",
                [[round(v + d - 0.1, 2), round(v + d, 2), round(v + d + 0.1, 2)] for d in (-0.4, -0.2, 0.0, 0.2, 0.4)],
                [round(v + d, 2) for d in (-0.4, -0.2, 0.0, 0.2, 0.4)],
            )
            for c_nm, v in zip((0.0, 5.0, 12.0, 22.0, 45.0, 90.0), (100.0, 97.0, 94.0, 91.0, 80.0, 62.0))
        ],
        "c_safe_max_exact_l95_free_nM": 22.0, "exact_cassette_retention_at_csafe_pct": 91.5,
        "hour0_density_at_csafe_by_lineage": _mk_r8_hour0(py),
    })
    sw_y40 = _mk_r8_switch(py, by, ly, ry, mat_y40, "2026-10-08T09:00:00Z", coating_identity=coat_b)
    g0v_y40 = _mk_r8_gate0v(py, by, ly, ry, mat_y40, "2026-10-08T09:30:00Z", coating_identity=coat_b)
    pr_mat_40 = {"BANK_MATERIALIZATION": mat_y40["receipt_sha256"]}
    pr_b2be = {
        "BANK_MATERIALIZATION": mat_y40["receipt_sha256"], "B-0a-exact": b0a_ex_y["receipt_sha256"],
        "B-1": b1_y["receipt_sha256"], "B-2": b2_y["receipt_sha256"],
    }
    pr_all_40 = {
        "BANK_MATERIALIZATION": mat_y40["receipt_sha256"],
        "NATIVE_SAFETY_SWITCH": sw_y40["receipt_sha256"], "GATE-0V-KILL": g0v_y40["receipt_sha256"],
    }
    b2be_y = _sign_receipt({
        "stage": "B-2b-exact", "verdict": "PASS", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "exact_product", "recorded_at_utc": "2026-09-25T10:00:00Z",
        "parent_receipt_sha256": b2bb_y["receipt_sha256"], "prerequisite_receipt_sha256s": pr_b2be, **coat_b,
        "c_safe_max_operative_l95_free_nM": 22.0,
        "used_marginal_u95_sum": False, "alpha_conc": 0.025, "alpha_fu_parent": 0.0125, "alpha_fu_bmt": 0.0125,
        "u95_joint_peak_free_nM": 20.8, "days0_10_parent_lower_free_nM": 7.0,
        **_mk_r8_b2b_replicates(evidence_scope="exact_product"),
        "c_bmt_local_total_u_alloc_nM": 0.04, "c_bmt_local_free_u_alloc_nM": 0.02,
        "c_bmt_recirc_total_u_alloc_nM": 0.03, "c_bmt_recirc_free_u_alloc_nM": 0.02,
        "censoring_audit_passed": True, "intersample_peak_envelope_justified": True,
        "systemic_exposure_below_cap": True, "mixture_requalified": False,
    })
    def _mk_b3_il10_assay(
        lot_id_v: str = ly, veh_lot_v: str = bv_b, *,
        mean_rec: float = 95.0, wash_utc: str = "2026-10-05T09:00:00Z", recov_utc: str = "2026-10-08T09:00:00Z",
        **ov: Any,
    ) -> dict[str, Any]:
        drows = []
        for di, off in enumerate((-1.5, 0.0, 1.5), start=1):
            veh_v = 80.0
            tr_v = round(veh_v * (mean_rec + off) / 100.0, 4)
            db = {
                "donor_id": f"IL10-DONOR-{di:02d}",
                "raw_record_id": f"IL10-REC-{lot_id_v}-{di:02d}",
                "treated_post_washout_il10_suppression_pct": tr_v,
                "matched_vehicle_il10_suppression_pct": veh_v,
            }
            drows.append({**db, "record_sha256": sha256_bytes(canonical_json_bytes(db))})
        ab: dict[str, Any] = {
            "assay_id": f"IL10-WASHOUT-{lot_id_v}",
            "lot_id": lot_id_v,
            "matched_blank_vehicle_lot_id": veh_lot_v,
            "exposure_started_at_utc": "2026-10-01T09:00:00Z",
            "washout_started_at_utc": wash_utc,
            "recovery_collected_at_utc": recov_utc,
            "recorded_at_utc": "2026-10-08T18:00:00Z",
            "exposure_measured_free_parent_nM": 12.5,
            "donor_records": drows,
        }
        ab.update(ov)
        return {**ab, "assay_receipt_sha256": sha256_bytes(canonical_json_bytes(ab))}

    def _mk_b3_challenge_panel(
        b2be_sha: str, *, prod_id: str = py, lot_id_v: str = ly, veh_lot_v: str = bv_b,
        free_p_nM: float = 12.5, free_b_nM: float = 0.02, comp_overrides: Optional[Mapping[str, Mapping[str, float]]] = None,
    ) -> dict[str, Any]:
        req_c = sorted(SHIELD_COMPONENTS_BY_PRODUCT[prod_id])
        shields_ref = _mk_r8_shields(prod_id)
        chals_obj: dict[str, Any] = {}
        for c_nm in ("IFNG_PLUS_TNFA", "IFNG_PLUS_IL1B", "IFNA_PLUS_LOW_IFNG"):
            comps_map: dict[str, Any] = {}
            for cn in req_c:
                tgt_pct = float(comp_overrides[c_nm][cn]) if (comp_overrides and c_nm in comp_overrides and cn in comp_overrides[c_nm]) else float(shields_ref[cn])
                comps_map[cn] = {
                    "vehicle": [1000.0, 1020.0, 980.0],
                    "treated": [round(v * (tgt_pct + d) / 100.0, 4) for v, d in zip((1000.0, 1020.0, 980.0), (-0.4, 0.0, 0.4))],
                }
            chals_obj[c_nm] = {
                "block_ids": [f"B3-{c_nm}-BLK-1", f"B3-{c_nm}-BLK-2", f"B3-{c_nm}-BLK-3"],
                "matched_vehicle_record_id": f"B3-VEH-{c_nm}-{veh_lot_v}",
                "cassette_retention_raw": {
                    "vehicle": [1000.0, 1010.0, 990.0],
                    "treated": [round(v * (92.0 + d) / 100.0, 4) for v, d in zip((1000.0, 1010.0, 990.0), (-0.4, 0.0, 0.4))],
                },
                "components": comps_map,
            }
        pb: dict[str, Any] = {
            "lot_id": lot_id_v,
            "matched_blank_vehicle_lot_id": veh_lot_v,
            "b2b_exact_receipt_sha256": b2be_sha,
            "exposure_started_at_utc": "2026-10-01T09:00:00Z",
            "assessed_at_utc": "2026-10-03T09:00:00Z",
            "measured_free_parent_nM": free_p_nM,
            "measured_free_bmt_nM": free_b_nM,
            "challenges": chals_obj,
        }
        return {**pb, "panel_receipt_sha256": sha256_bytes(canonical_json_bytes(pb))}

    b3_il10_ok = _mk_b3_il10_assay()
    b3_cpanel_ok = _mk_b3_challenge_panel(b2be_y["receipt_sha256"])
    b3_y = _sign_receipt({
        "stage": "B-3", "verdict": "PASS", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "exact_product", "recorded_at_utc": "2026-10-09T11:00:00Z",
        "parent_receipt_sha256": b2be_y["receipt_sha256"], "prerequisite_receipt_sha256s": pr_mat_40, **coat_b,
        "transgene_cassette_retention_pct": 92.0, "shield_retention_by_component": _mk_r8_shields(py),
        "b3_cytokine_challenge_shield_panel": b3_cpanel_ok,
        "il10_suppression_pct": 12.0, "post_washout_72h_il10_recovery_pct": 95.0,
        "il10_washout_recovery_assay": b3_il10_ok,
        "nkg2a_mfi_pct_ctrl": 93.0, "cd94_mfi_pct_ctrl": 94.0,
        "readout3b_evidence": _mk_r8_readout3b(include_sirpa_low=True, matched_vehicle_lot_id=bv_b),
        "readout2_evidence": _mk_r8_readout2(
            matched_comparator_id=bv_b, block_prefix="B3B",
            stage7_start_utc="2026-09-16T00:00:00Z", sort_reaggregation_utc="2026-09-28T00:00:00Z", assay_harvest_utc="2026-10-07T00:00:00Z",
        ),
        "hour0_density_by_lineage": _mk_r8_hour0(py),
    })
    b4_hrs = [2.0, 12.0, 24.0, 72.0, 144.0, 192.0, 240.0, 312.0, 384.0, 456.0, 504.0]
    b4_lpf = [15.5, 14.0, 12.5, 10.6, 9.5, 8.6, 8.0, 4.2, 2.1, 0.9, 0.45]
    b4_lbf = [0.004, 0.005, 0.005, 0.005, 0.004, 0.004, 0.004, 0.003, 0.003, 0.003, 0.003]
    b4_spf = [0.035, 0.032, 0.028, 0.024, 0.020, 0.016, 0.014, 0.012, 0.010, 0.008, 0.008]
    b4_sbf = [0.012, 0.012, 0.010, 0.010, 0.009, 0.008, 0.008, 0.008, 0.008, 0.008, 0.008]
    b4_y = _sign_receipt({
        "stage": "B-4", "verdict": "PASS", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "exact_product", "invivo_study_started_at_utc": "2026-10-10T10:00:00Z",
        "recorded_at_utc": "2026-11-02T12:00:00Z", "parent_receipt_sha256": b3_y["receipt_sha256"],
        "prerequisite_receipt_sha256s": pr_all_40, **coat_b,
        "invivo_time_resolved_pk_gate_retained": True,
        "serial_pk_schedule_hours": b4_hrs,
        "serial_pk_local_parent_free_nM": b4_lpf,
        "serial_pk_local_bmt_free_nM": b4_lbf,
        "serial_pk_systemic_parent_total_nM": b4_spf,
        "serial_pk_systemic_bmt_total_nM": b4_sbf,
        **_mk_r8_b4_replicates(b4_hrs, b4_lpf, b4_lbf, b4_spf, b4_sbf),
        "censoring_audit_passed": True, "blq_imputation_rule": "LLOQ_TIMES_FU_U_ALLOC_SAFETY_AND_ZERO_EFFICACY",
        "alpha_conc": 0.025, "alpha_fu_parent": 0.0125, "alpha_fu_bmt": 0.0125,
        "intersample_peak_envelope_justified": True,
        "invivo_u95_joint_peak_free_nM": 19.2, "invivo_days0_10_parent_lower_free_nM": 6.4,
        "invivo_systemic_plasma_u95_nM": 0.38,
        "matched_control_switch_parity_evidence": _mk_r8_switch_parity(bv_b),
    })
    g41_bench = {
        "phase": "BENCH_UNEDITED", "track_mode": "PRIMARY", "credit_scope": "PRIMARY",
        "target_arm": "Y", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "b0a_evidence": b0a_ok, "b0b_evidence": b0b_y, "b1_evidence": b1_y, "b2_evidence": b2_y, "b2b_bench_evidence": b2bb_y,
    }
    g41_ok = {
        **g41_bench, "phase": "EXACT_PRODUCT",
        "materialization_evidence": mat_y40, "native_switch_evidence": sw_y40, "gate0v_evidence": g0v_y40,
        "b0a_exact_evidence": b0a_ex_y, "b2b_exact_evidence": b2be_y, "b3_evidence": b3_y, "b4_evidence": b4_y,
    }
    r41 = evaluate_gate41_deucravacitinib_tyk2(g41_ok)
    chk(r41["verdict"] == OFFLINE_VERDICT_PRIMARY and r41["release_authorizing"] is False and r41["live_ledger_authenticated"] is False, "G41_pass_Y_R3P")
    chk(evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": b0a_ok})["verdict"] == "PASS_ROUTE_FREE_B0A_ONLY", "G41_phase1_ok")
    chk(evaluate_gate41_deucravacitinib_tyk2(g41_bench)["verdict"] == "PASS_BENCH_ONLY_UNEDITED_PRE_MATERIALIZATION", "G41_phase2_ok")

    # GATE-41 closures (10 brand-new tests!)
    # 1. B-4 228-hour blind gap between 12 h and 240 h returns HOLD_GATE_B4_INSUFFICIENT_TEMPORAL_COVERAGE_GAP_GT_72H!
    chk("HOLD_GATE_B4_INSUFFICIENT_TEMPORAL_COVERAGE_GAP_GT_72H" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "serial_pk_schedule_hours": [2.0, 6.0, 12.0, 240.0, 360.0, 432.0, 504.0], "serial_pk_local_parent_free_nM": [15.5, 14.5, 14.0, 7.2, 2.4, 1.1, 0.45], "serial_pk_local_bmt_free_nM": [0.02]*7, "serial_pk_systemic_parent_total_nM": [0.10]*7, "serial_pk_systemic_bmt_total_nM": [0.01]*7})})["holds"], "G41_ADV_b4_228h_gap_hold")
    # 2. B-2 negative coated TAT (impossible >100% reduction) FAILS!
    bad_d_neg = _mk_r8_b2_donors(); bad_d_neg[0]["tat_coated_ng_ml"] = -5.0
    chk("FAIL_GATE_B2_TAT_RAW_VALUES_INVALID:D1" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2_evidence": _sign_receipt({**b2_y, "donor_records": bad_d_neg})})["failures"], "G41_ADV_b2_neg_tat_impossible")
    # 3. B-2 null exclusion entry FAILS!
    chk("FAIL_GATE_B2_MALFORMED_OR_NULL_EXCLUSION_ROW:0" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2_evidence": _sign_receipt({**b2_y, "enrolled_donors_n": 7, "excluded_invalid_donors_n": 1, "invalid_donor_exclusion_log": [None]})})["failures"], "G41_ADV_b2_null_excl")
    # 4. B-2 trailing-whitespace duplicate donor ID ("D1" vs "D1 ") FAILS!
    bad_d_ws = _mk_r8_b2_donors(); bad_d_ws[1]["donor_id"] = "D1 "
    chk("FAIL_GATE_B2_UNDERPOWERED_OR_DUPLICATE_DONORS_LT_6" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2_evidence": _sign_receipt({**b2_y, "donor_records": bad_d_ws})})["failures"], "G41_ADV_b2_whitespace_dup_donor")
    # 5. B-0a-exact swapped api_batch_id FAILS coating identity check!
    chk("FAIL_B-0a-exact_COATING_IDENTITY_MISMATCH:api_batch_id" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b0a_exact_evidence": _sign_receipt({**b0a_ex_y, "api_batch_id": "DIFFERENT-API-BATCH"})})["failures"], "G41_ADV_b0a_exact_api_batch_mismatch")
    # 6. B-3 Readout-2 50% drop vs matched blank vehicle FAILS!
    r2_b3_50 = _mk_r8_readout2(matched_comparator_id=bv_b, block_prefix="B3B")
    for b in r2_b3_50["o2_40_mmhg"]["blocks"]:
        b["matched_control_z2_increment"] = round(b["z2_increment"] * 2.0, 4)
        b["matched_control_output_ratio"] = 0.50
    chk("FAIL_GATE_B3_READOUT2_O2_40_RECOMPUTED_CTRL_FIELLER_L95_BELOW_FLOOR" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b3_evidence": _sign_receipt({**b3_y, "readout2_evidence": r2_b3_50})})["failures"], "G41_ADV_b3_r2_50pct_ctrl_fails")
    # 7. B-3 Readout-3B coated lysis > +2.0 pp above matched blank vehicle FAILS!
    r3b_d2 = _mk_r8_readout3b(include_sirpa_low=True, matched_vehicle_lot_id=bv_b)
    for d in r3b_d2["donor_records"]:
        d["regime_i_ifng_24h"]["veh_nkg2a_pos_lysis_pct"] = 1.0  # coated ~4.6 vs veh 1.0 -> +3.6 pp > +2 pp!
    chk("FAIL_GATE_B3_READOUT3B_R1_NKG2A_EXCEEDS_MATCHED_VEH_BY_GT_2PP" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b3_evidence": _sign_receipt({**b3_y, "readout3b_evidence": r3b_d2})})["failures"], "G41_ADV_b3_r3b_veh_delta_gt2pp")
    # 8. B-0a raw concentration-response grid failing to bracket bounds FAILS!
    chk("FAIL_GATE_B0A_BOUNDS_NOT_OBSERVATION_BRACKETED" in evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": _sign_receipt({**b0a_ok, "tested_free_conc_grid_nM": [0.0, 1.0, 2.0, 3.0, 5.0, 10.0, 20.0, 24.0]})})["failures"], "G41_ADV_b0a_grid_not_bracketed")
    # 9. B-2b-bench claimed U95 understating recomputed simultaneous replicate upper bound FAILS!
    chk("FAIL_GATE_B2B_BENCH_RECOMPUTED_SIMULTANEOUS_PEAK_EXCEEDS_CLAIMED_OR_CSAFE" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "u95_joint_peak_free_nM": 10.0})})["failures"], "G41_ADV_b2b_understates_recomp_peak")
    # 10. B-4 missing matched-control switch parity receipt triggers HOLD (no bare boolean shortcut!)
    chk("HOLD_GATE_B4_MATCHED_CONTROL_SWITCH_PARITY_MISSING" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "matched_control_switch_parity_evidence": None})})["holds"], "G41_ADV_b4_sw_parity_data_req")

    # & Core 67 GATE-41 invariants
    chk("FAIL_GATE_B4_SERIAL_PK_SAMPLE_POSTDATES_RECEIPT" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "serial_pk_schedule_hours": [2.0, 12.0, 24.0, 72.0, 144.0, 192.0, 240.0, 312.0, 384.0, 504.0, 600.0]})})["failures"], "G41_ADV_b4_postdated_sample")
    chk("FAIL_GATE_B4_SERIAL_PK_WINDOW_MISSES_BURST_DAY10_OR_DAY21_WINDOW" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "recorded_at_utc": "2026-11-10T12:00:00Z", "serial_pk_schedule_hours": [2.0, 12.0, 24.0, 72.0, 144.0, 192.0, 240.0, 312.0, 384.0, 456.0, 600.0]})})["failures"], "G41_ADV_b4_misses_day21_window")
    chk("HOLD_GATE_B0A_EXACT_CASSETTE_CEILING_MISSING" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b0a_exact_evidence": None})["holds"], "G41_ADV_missing_b0a_exact_hold")
    chk("FAIL_GATE_B2B_EXACT_OPERATIVE_NOT_EQUAL_TO_MIN_BENCH_AND_EXACT" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b2b_exact_evidence": _sign_receipt({**b2be_y, "c_safe_max_operative_l95_free_nM": 24.0})})["failures"], "G41_ADV_derived_op_mismatch")
    rmap_ind = {r: {l: dict(c) for l, c in lm.items()} for r, lm in g0v_y40["regime_by_lineage_raw_counts"].items()}
    rmap_ind["active_persistent_cvb4"]["INS_beta"]["infected_cell_escape_mode"] = "CONDITIONAL_INDIRECT_DIAGNOSTIC_ONLY"
    chk("HOLD_GATE0V_INDIRECT_CONDITIONAL_ESCAPE_UNSUPPORTED_FOR_RELEASE:active_persistent_cvb4:INS_beta" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "gate0v_evidence": _sign_receipt({**g0v_y40, "regime_by_lineage_raw_counts": rmap_ind})})["holds"], "G41_ADV_g0v_indirect_hold")
    rmap_sub = {r: {l: dict(c) for l, c in lm.items()} for r, lm in g0v_y40["regime_by_lineage_raw_counts"].items()}
    bad_dinf = [dict(u) for u in rmap_sub["active_persistent_cvb4"]["INS_beta"]["per_unit_counts_direct_infected_veh_72h"]]
    bad_dinf[0]["k"] = 33; bad_dinf[1]["k"] = 7
    rmap_sub["active_persistent_cvb4"]["INS_beta"]["per_unit_counts_direct_infected_veh_72h"] = bad_dinf
    chk("HOLD_GATE0V_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION:active_persistent_cvb4:INS_beta:direct_inf:W1" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "gate0v_evidence": _sign_receipt({**g0v_y40, "regime_by_lineage_raw_counts": rmap_sub})})["holds"], "G41_ADV_g0v_subset_contradiction")
    bad_d_ctrl = _mk_r8_b2_donors(); bad_d_ctrl[0]["pos_ctrl_tat_fold"] = 2.0
    chk("FAIL_GATE_B2_NUMERIC_DONOR_CONTROL_INVALID:pos_ctrl_tat_fold" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2_evidence": _sign_receipt({**b2_y, "donor_records": bad_d_ctrl})})["failures"], "G41_ADV_b2_numeric_ctrl_fail")
    bad_d_loo = _mk_r8_b2_donors()
    # Set raw platelet coated - vehicle / 250 -> [-2, 1, 22, 24, 26, 49] pp (overall passes, LOO fragile!)
    for i, target_pp in enumerate([-2.0, 1.0, 22.0, 24.0, 26.0, 49.0]):
        bad_d_loo[i]["platelet_vehicle_k_ul"] = 100.0
        bad_d_loo[i]["platelet_coated_k_ul"] = 100.0 + 2.5 * target_pp
    chk("FAIL_GATE_B2_PLATELET_LEAVE_ONE_DONOR_OUT_FRAGILE" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2_evidence": _sign_receipt({**b2_y, "donor_records": bad_d_loo})})["failures"], "G41_ADV_b2_loo_fragile")
    bad_r3b_sl = _mk_r8_readout3b(include_sirpa_low=True, matched_vehicle_lot_id=bv_b); bad_r3b_sl["donor_records"][0]["regime_ii_t0_unpreinduced"]["il12_il18_sirpa_low_lysis_pct"] = 14.0
    chk("FAIL_GATE_B3_READOUT3B_R2_SIRPA_LOW_LYSIS_GT_10PCT:NK-D1" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b3_evidence": _sign_receipt({**b3_y, "readout3b_evidence": bad_r3b_sl})})["failures"], "G41_ADV_b3_sirpa_low_checked")
    chk("FAIL_B-4_COATING_IDENTITY_MISMATCH:coating_article_id" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "coating_article_id": "OTHER-ARTICLE"})})["failures"], "G41_ADV_b4_coating_swap")

    chk("FAIL_GATE_B4_SERIAL_PK_WINDOW_MISSES_BURST_DAY10_OR_DAY21_WINDOW" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "serial_pk_schedule_hours": [2.0, 12.0, 24.0, 72.0, 120.0, 168.0, 240.0], "serial_pk_local_parent_free_nM": [15.5, 14.0, 12.5, 10.2, 9.0, 8.2, 7.2], "serial_pk_local_bmt_free_nM": [0.02]*7, "serial_pk_systemic_parent_total_nM": [0.10]*7, "serial_pk_systemic_bmt_total_nM": [0.02]*7})})["failures"], "G41_ADV_b4_ends_day10")
    chk("FAIL_GATE_B4_COMBINED_LOCAL_PEAK_EXCEEDS_REPORTED_U95_JOINT_PEAK" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "serial_pk_local_parent_free_nM": [16.5, 14.0, 12.5, 10.2, 8.8, 7.9, 7.2, 4.5, 2.4, 1.1, 0.45], "serial_pk_local_bmt_free_nM": [4.0, 0.03, 0.04, 0.04, 0.03, 0.02, 0.02, 0.02, 0.01, 0.01, 0.01]})})["failures"], "G41_ADV_b4_comb_local")
    chk("FAIL_GATE_B4_COMBINED_SYSTEMIC_PEAK_EXCEEDS_REPORTED_U95_SYSTEMIC" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "serial_pk_systemic_parent_total_nM": [0.35, 0.11, 0.09, 0.06, 0.04, 0.03, 0.03, 0.02, 0.02, 0.01, 0.01], "serial_pk_systemic_bmt_total_nM": [0.10, 0.02, 0.02, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01]})})["failures"], "G41_ADV_b4_comb_sys")
    chk("FAIL_GATE_B4_DAY21_WASHOUT_NOT_EXHAUSTED" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "serial_pk_local_parent_free_nM": [15.5, 14.0, 12.5, 10.2, 8.8, 7.9, 7.2, 5.5, 4.5, 3.8, 3.2]})})["failures"], "G41_ADV_b4_day21_not_exh")
    chk("FAIL_GATE_B4_ELAPSED_STUDY_DURATION_LT_21_DAYS" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "recorded_at_utc": "2026-10-20T12:00:00Z"})})["failures"], "G41_ADV_b4_lt_21d")
    chk("FAIL_PREREQ_RECEIPT_DIGEST_BINDING_MISMATCH:GATE-0V-KILL_IN_B-4" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "prerequisite_receipt_sha256s": {**pr_all_40, "GATE-0V-KILL": "0" * 64}})})["failures"], "G41_ADV_b4_prereq_pin")
    chk("FAIL_GATE_B3_POST_WASHOUT_72H_IL10_RECOVERY_LT_90PCT" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b3_evidence": _sign_receipt({**b3_y, "post_washout_72h_il10_recovery_pct": 82.0})})["failures"], "G41_ADV_b3_il10_rec")
    bad_r3b_cd107 = _mk_r8_readout3b(include_sirpa_low=True, matched_vehicle_lot_id=bv_b); bad_r3b_cd107["donor_records"][0]["regime_ii_t0_unpreinduced"]["nkg2a_pos_cd107a_degranulation_pct"] = 12.5
    chk("FAIL_GATE_B3_READOUT3B_R2_CD107A_GT_10PCT:NK-D1" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b3_evidence": _sign_receipt({**b3_y, "readout3b_evidence": bad_r3b_cd107})})["failures"], "G41_ADV_b3_r3b_cd107")
    bad_r3b_cp = _mk_r8_readout3b(include_sirpa_low=True, matched_vehicle_lot_id=bv_b)
    for d in bad_r3b_cp["donor_records"]:
        d["regime_ii_t0_unpreinduced"] = {**d["regime_i_ifng_24h"], "allogeneic_cd8_ctl_lysis_pct": 2.5, "veh_allogeneic_cd8_ctl_lysis_pct": 2.4, "continuous_0_24h_kinetic_trace_verified": True, "continuous_0_24h_kinetic_trace": d["regime_ii_t0_unpreinduced"]["continuous_0_24h_kinetic_trace"]}
    chk("FAIL_GATE_B3_READOUT3B_IDENTICAL_COPY_PASTE_REGIME_I_AND_II" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b3_evidence": _sign_receipt({**b3_y, "readout3b_evidence": bad_r3b_cp})})["failures"], "G41_ADV_b3_r3b_cp")
    chk("FAIL_GATE_B1_ELAPSED_ELUTION_DURATION_LT_21_DAYS" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b1_evidence": _sign_receipt({**b1_y, "recorded_at_utc": "2026-08-20T09:00:00Z"})})["failures"], "G41_ADV_b1_lt_21d")
    chk("FAIL_GATE_B1_DAY21_EFFLUENT_EXHAUSTION_FAILED" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b1_evidence": _sign_receipt({**b1_y, "day21_effluent_free_nM": 2.5})})["failures"], "G41_ADV_b1_d21_free")
    chk("FAIL_GATE_B1_DAY21_DEPOT_DEPLETION_LT_85PCT" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b1_evidence": _sign_receipt({**b1_y, "day21_depot_depletion_pct": 75.0})})["failures"], "G41_ADV_b1_d21_depl")
    chk("FAIL_BENCH_PHASE_FORBIDS_EXACT_OR_INVIVO_FIELDS:b4_evidence" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b4_evidence": None})["failures"], "G41_ADV_forbid_none_key")
    chk("FAIL_DESIGN_A_DRUG_FIREWALL_VIOLATION" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "target_arm": "A", "product_id": pa, "route_id": ra})["failures"], "G41_block_A")
    chk("FAIL_OUT_OF_ACTIVE_GATE_SCOPE_PRODUCT_ROUTE" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "target_arm": "B", "product_id": pb, "route_id": "R1"})["failures"], "G41_block_B_R1")
    chk("FAIL_LEGACY_PRODUCT_NON_TRANSFERABLE_TO_V090" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "product_id": "ISLET1_B2_5LOCUS_BASE"})["failures"], "G41_block_legacy")
    chk("FAIL_GATE_B0A_MISSING_PER_MATRIX_LLOQ_MAP" in evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": _sign_receipt({**b0a_ok, "lloq_bmt_by_matrix_nM": {"whole_blood": 0.1}})})["failures"], "G41_b0a_3mat")
    chk("FAIL_GATE_B0A_LLOQ_INVALID_OR_GT_0P2NM" in evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": _sign_receipt({**b0a_ok, "lloq_parent_by_matrix_nM": {"low_serum_media": 0.1, "human_serum_100pct": 0.3, "whole_blood": 0.1}})})["failures"], "G41_b0a_lloq")
    chk("FAIL_GATE_B0A_MARGIN_BELOW_2X" in evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": _sign_receipt({**b0a_ok, "c_safe_max_bench_l95_free_nM": 9.0})})["failures"], "G41_b0a_margin")
    chk("FAIL_GATE_B0B_COATING_THICKNESS_GT_5UM" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b0b_evidence": _sign_receipt({**b0b_y, "coating_thickness_um": 7.0})})["failures"], "G41_b0b_thick")
    chk("FAIL_GATE_B0B_WORST_FACE_O2_BELOW_40MMHG" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b0b_evidence": _sign_receipt({**b0b_y, "worst_face_o2_mmhg": 36.0})})["failures"], "G41_b0b_o2")
    chk("FAIL_GATE_B0B_LOCAL_PH_OUTSIDE_7P25_7P45" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b0b_evidence": _sign_receipt({**b0b_y, "local_ph_max": 7.6})})["failures"], "G41_b0b_ph")
    chk("FAIL_GATE_B1_MASS_RECOVERY_OUT_OF_90_110" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b1_evidence": _sign_receipt({**b1_y, "terminal_mass_recovery_pct": 85.0})})["failures"], "G41_b1_mass")
    chk("FAIL_GATE_B2_UNDERPOWERED_OR_DUPLICATE_DONORS_LT_6" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2_evidence": _sign_receipt({**b2_y, "donor_records": _mk_r8_b2_donors()[:4]})})["failures"], "G41_b2_n4")
    chk("FAIL_GATE_B2B_BENCH_MARGINAL_SUM_FORBIDDEN" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "used_marginal_u95_sum": True})})["failures"], "G41_b2bb_marg")
    chk("FAIL_GATE_B2B_BENCH_GLOBAL_ALPHA_EXCEEDS_0P05" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "alpha_conc": 0.03, "alpha_fu_parent": 0.02, "alpha_fu_bmt": 0.01})})["failures"], "G41_b2bb_alpha")
    chk("FAIL_GATE_B2B_BENCH_JOINT_PEAK_NOT_STRICTLY_BELOW_CSAFE" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "u95_joint_peak_free_nM": 25.0})})["failures"], "G41_b2bb_lt")
    chk("HOLD_GATE_B2B_BENCH_METABOLITE_TRIGGERED_MIXTURE_REQUAL_REQUIRED" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "c_bmt_local_total_u_alloc_nM": 0.16})})["holds"], "G41_b2bb_t1")
    chk("HOLD_GATE_B2B_BENCH_METABOLITE_TRIGGERED_MIXTURE_REQUAL_REQUIRED" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "c_bmt_local_total_u_alloc_nM": 3.0, "c_bmt_local_free_u_alloc_nM": 2.6})})["holds"], "G41_b2bb_t2")
    chk("HOLD_GATE_B2B_BENCH_METABOLITE_TRIGGERED_MIXTURE_REQUAL_REQUIRED" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "c_bmt_recirc_total_u_alloc_nM": 0.16})})["holds"], "G41_b2bb_t3")
    chk("HOLD_GATE_B2B_BENCH_METABOLITE_TRIGGERED_MIXTURE_REQUAL_REQUIRED" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "c_bmt_recirc_total_u_alloc_nM": 3.0, "c_bmt_recirc_free_u_alloc_nM": 2.6})})["holds"], "G41_b2bb_t4")
    chk("FAIL_GATE_B4_INVIVO_PEAK_NOT_STRICTLY_BELOW_CSAFE" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "invivo_u95_joint_peak_free_nM": 22.0})})["failures"], "G41_b4_pk_ge")
    chk("FAIL_GATE_B4_INVIVO_SYSTEMIC_PLASMA_GE_0P5NM" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "invivo_systemic_plasma_u95_nM": 0.50})})["failures"], "G41_b4_sys_0p5")
    bad_swp_b4 = _mk_r8_switch_parity(bv_b); bad_swp_b4["treated_24h_kill_pct_by_block"] = [99.80]*6; bad_swp_b4["reported_l95_24h_delta_pp"] = -0.14
    chk("FAIL_GATE_B4_SW_PARITY_24H_NONINFERIORITY_MARGIN_FAILED" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "matched_control_switch_parity_evidence": _sign_receipt(bad_swp_b4)})})["failures"], "G41_b4_sw_ni")
    chk("FAIL_MANDATORY_INVIVO_PK_GATE_WAIVED" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "invivo_time_resolved_pk_gate_retained": False})})["failures"], "G41_b4_waive")
    chk("FAIL_CHRONOLOGICAL_TIMESTAMP_ORDER_VIOLATION:B-4" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "recorded_at_utc": "2026-10-08T10:30:00Z"})})["failures"], "G41_b4_before_b3")
    chk("HOLD_PRE_INVIVO_B4_PENDING" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": None})["holds"], "G41_b4_hold")
    sw40_no_f = _sign_receipt({**sw_y40, "oq012_clonogenic_block": {k: v for k, v in _mk_r8_oq012().items() if k != "clonogenic_fraction_f"}})
    chk("HOLD_NATIVE_SWITCH_OQ012_INCOMPLETE_RECOVERY_DENOMINATOR" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "native_switch_evidence": sw40_no_f})["holds"], "G41_ADV_oq012_no_f")
    chk("HOLD_GATE0V_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "gate0v_evidence": _sign_receipt({**g0v_y40, "clustering_design_effect_deff": 1.2})})["holds"], "G41_ADV_g0v_deff")
    chk("FAIL_GATE_B2_DONOR_DENOMINATOR_RECONCILIATION_MISMATCH" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2_evidence": _sign_receipt({**b2_y, "enrolled_donors_n": 8})})["failures"], "G41_b2_enr_mm")
    chk("FAIL_GATE_B2B_BENCH_PARENT_EFFICACY_FLOOR_BELOW_EC50" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "days0_10_parent_lower_free_nM": 4.0})})["failures"], "G41_b2bb_ec50")
    chk("FAIL_GATE41_UNKNOWN_OR_UNRECONCILED_FIELDS:extra_x" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "extra_x": 1})["failures"], "G41_unknown_key")
    chk("FAIL_GATE_B3_SHIELD_COMPONENT_BELOW_85PCT:SERPINB9" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b3_evidence": _sign_receipt({**b3_y, "shield_retention_by_component": {**_mk_r8_shields(py), "SERPINB9": 78.0}})})["failures"], "G41_b3_shield_comp")
    chk("FAIL_GATE_B3_IL10_SUPPRESSION_GE_20PCT" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b3_evidence": _sign_receipt({**b3_y, "il10_suppression_pct": 24.0})})["failures"], "G41_b3_il10_supp")
    chk("FAIL_GATE_B3_NKG2A_CD94_MFI_BELOW_85PCT" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b3_evidence": _sign_receipt({**b3_y, "nkg2a_mfi_pct_ctrl": 75.0})})["failures"], "G41_b3_mfi")
    chk("FAIL_GATE_B3_CASSETTE_RETENTION_BELOW_85PCT" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b3_evidence": _sign_receipt({**b3_y, "transgene_cassette_retention_pct": 70.0})})["failures"], "G41_b3_cassette")
    chk("FAIL_GATE_B2_IEC_TXNIP_GT_1P5" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2_evidence": _sign_receipt({**b2_y, "iec_txnip_fold": 1.8})})["failures"], "G41_b2_txnip")
    chk("FAIL_GATE_B2_IEC_ROS_GT_1P2" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2_evidence": _sign_receipt({**b2_y, "iec_ros_fold": 1.4})})["failures"], "G41_b2_ros")
    chk("FAIL_GATE_B1_DAY1_BURST_GT_20PCT" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b1_evidence": _sign_receipt({**b1_y, "day1_burst_pct": 25.0})})["failures"], "G41_b1_burst")
    chk("FAIL_GATE_B4_BLQ_IMPUTATION_RULE_INVALID" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "blq_imputation_rule": "ZERO_EVERYWHERE"})})["failures"], "G41_b4_blq")
    chk("FAIL_GATE_B4_CENSORING_AUDIT_MISSING" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "censoring_audit_passed": False})})["failures"], "G41_b4_cens")
    chk("FAIL_GATE_B4_INTERSAMPLE_PEAK_UNJUSTIFIED" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "intersample_peak_envelope_justified": False})})["failures"], "G41_b4_env")
    chk("FAIL_GATE_B4_GLOBAL_ALPHA_EXCEEDS_0P05" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "alpha_conc": 0.04, "alpha_fu_parent": 0.01, "alpha_fu_bmt": 0.01})})["failures"], "G41_b4_alpha")
    chk("FAIL_GATE_B4_INVIVO_PARENT_FLOOR_BELOW_EC50" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "invivo_days0_10_parent_lower_free_nM": 4.0})})["failures"], "G41_b4_floor")
    chk("FAIL_GATE_B0A_EXACT_CASSETTE_RETENTION_BELOW_85PCT" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b0a_exact_evidence": _sign_receipt({**b0a_ex_y, "exact_cassette_retention_at_csafe_pct": 70.0})})["failures"], "G41_b0a_ex_ret")
    chk("FAIL_GATE_B0B_MASS_BALANCE_MARGIN_UNVERIFIED" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b0b_evidence": _sign_receipt({**b0b_y, "mass_balance_margin_verified": False})})["failures"], "G41_b0b_mb")
    chk("FAIL_GATE_B2_IEC_SPROUTING_LT_90PCT" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2_evidence": _sign_receipt({**b2_y, "iec_sprouting_pct_ctrl": 80.0})})["failures"], "G41_b2_spr")
    chk("FAIL_GATE_B2_IEC_VIABILITY_LT_90PCT" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2_evidence": _sign_receipt({**b2_y, "iec_birc5_viability_pct": 80.0})})["failures"], "G41_b2_viab")
    chk("FAIL_GATE_B2_IEC_CD274_LT_85PCT" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2_evidence": _sign_receipt({**b2_y, "iec_cd274_pct_ctrl": 70.0})})["failures"], "G41_b2_cd274")
    chk("FAIL_GATE_B2_IEC_HLAE_LT_85PCT" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2_evidence": _sign_receipt({**b2_y, "iec_hlae_pct_ctrl": 70.0})})["failures"], "G41_b2_hlae")
    chk("FAIL_GATE_B2B_BENCH_CENSORING_AUDIT_MISSING" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "censoring_audit_passed": False})})["failures"], "G41_b2bb_cens")
    chk("FAIL_GATE_B2B_BENCH_SYSTEMIC_EXPOSURE_UNVERIFIED" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "systemic_exposure_below_cap": False})})["failures"], "G41_b2bb_sys")
    chk("FAIL_GATE_B2B_BENCH_INTERSAMPLE_PEAK_UNJUSTIFIED" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "intersample_peak_envelope_justified": False})})["failures"], "G41_b2bb_env")
    chk("FAIL_GATE_B0A_ENDPOINTS_UNBRACKETED" in evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": _sign_receipt({**b0a_ok, "endpoints_bracketed": False})})["failures"], "G41_b0a_unbrack")
    chk("FAIL_GATE_B0A_MISSING_OR_INVALID_MEASURED_FU_BY_MATRIX" in evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": _sign_receipt({**b0a_ok, "fu_parent_by_matrix": {"whole_blood": 0.11}})})["failures"], "G41_b0a_fu_map")
    chk("FAIL_GATE_B4_INVIVO_BMT_SPIKE_WITHOUT_MIXTURE_REQUAL" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "serial_pk_local_bmt_free_nM": [2.5, 0.03, 0.04, 0.04, 0.03, 0.02, 0.02, 0.01, 0.01, 0.01, 0.01], "invivo_u95_joint_peak_free_nM": 19.2})})["failures"], "G41_b4_bmt_spike")
    chk("FAIL_GATE_B0A_EXACT_MISSING_ANALYSIS_RECORD_SHA256" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b0a_exact_evidence": _sign_receipt({**b0a_ex_y, "analysis_record_sha256": "short"})})["failures"], "G41_b0a_ex_sha")

    # ========================================================================
    # GATE-42 (80 tests: 70 prior + 10 adversarial closures)
    # ========================================================================
    nt_y = "NT-LOT-Y-001"
    tg_dual = "PMAIP1+BCL2L11"
    mat_yc = _mk_r8_mat(py, by, ly, "2026-09-10T08:00:00Z")
    df_y = _sign_receipt({
        "stage": "DRUG_FREE_EXPOSURE", "verdict": "PASS",
        "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "exact_product", "recorded_at_utc": "2026-09-11T08:15:00Z",
        "parent_receipt_sha256": mat_yc["receipt_sha256"],
        "route_coated": False, "added_drugs_count": 0,
    })
    g32_y = _sign_receipt({
        "stage": "GATE-32-DEBRIS-RECALL", "verdict": "PASS",
        "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "exact_product", "recorded_at_utc": "2026-09-12T07:30:00Z",
        "parent_receipt_sha256": mat_yc["receipt_sha256"],
        "canonical_gate32_producer_sha256": "7" * 64,
        "debris_recall_verdict": "PASS_DEBRIS_RECALL_FULL_CREDIT",
        "debris_recall_l95_suppressed_frac": 0.88,
        "residual_class2_recall_u95_frac": 0.14,
        "unrelated_recall_preserved": True,
    })
    g36_y = _sign_receipt({
        "stage": "GATE-36-FOUNDRY-V2", "verdict": "PASS",
        "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "exact_product", "recorded_at_utc": "2026-09-13T08:00:00Z",
        "parent_receipt_sha256": mat_yc["receipt_sha256"],
        "prerequisite_receipt_sha256s": {"DRUG_FREE_EXPOSURE": df_y["receipt_sha256"]},
        "canonical_gate36_producer_sha256": "6" * 64,
        "canonical_gate36_verdict": "PASS",
        "foundry_v2_module_scope": "INTRINSIC_CUFF_BIOLOGICS_NO_EXOGENOUS_SHIELD",
        "active_drug_free_modules": ["GATE-36-CUFF", "GATE-36-INS"],
        "module_producer_receipt_sha256s": {
            "GATE-36-CUFF": "a" * 64, "GATE-36-INS": "b" * 64,
        },
        "exogenous_shield_excluded_from_drug_free_scope": True,
        "live_gate32_debris_recall_receipt": g32_y,
        "matched_foundry_exposure_verified": True,
    })
    att_s2_bids = ["S2-BLK-1", "S2-BLK-2", "S2-BLK-3"]
    att_panel_norm = {
        "block_ids": att_s2_bids,
        "cond1_vehicle_beta_t0_pct_by_block": [92.0, 91.0, 93.0],
        "cond2_ifng_alone_beta_t0_pct_by_block": [89.0, 88.0, 90.0],
        "cond3_isolated_tnfa_ifng_beta_t0_pct_by_block": [71.0, 68.0, 71.0],
        "cond4_il1b_ifng_beta_t0_pct_by_block": [88.0, 86.0, 89.5],
        "cond5_pooled_triple_cytokine_beta_t0_pct_by_block": [68.0, 65.0, 68.0],
        "cleaved_caspase8_fold_by_block": [1.2, 1.3, 1.1],
        "cleaved_caspase9_fold_by_block": [3.4, 3.8, 3.6],
        "cytochrome_c_release_pct_by_block": [42.0, 46.0, 44.0],
        "pmlkl_ratio_by_block": [1.05, 1.08, 1.04],
        "bim_dp5_puma_induction_fold_by_block": [3.1, 3.5, 3.3],
        "il1_pathway_positive_control_verified": True,
        "il1_positive_control_parental_drop_pp_by_block": [28.0, 29.0, 28.0],
        "cxcl10_assay_lod_mfi": 50.0,
        "cxcl10_matched_ctrl_24h_mfi_by_block": [960.0, 955.0, 975.0],
        "cxcl10_0h_mfi_by_block": [1000.0, 1000.0, 1000.0],
        "cxcl10_24h_mfi_by_block": [920.0, 910.0, 940.0],
        "cxcl10_0h_vs_24h_shield_retention_pct_by_block": [92.0, 91.0, 94.0],
        "serpinb9_pct_matched_ctrl_by_block": [94.0, 93.0, 95.0],
        "pdl1_pct_matched_ctrl_by_block": [92.0, 91.5, 93.5],
        "post_washout_gsis_si_by_block": [3.6, 3.8, 3.5],
        "post_washout_gsis_z2_by_block": [1.75, 1.85, 1.80],
        "post_washout_gsis_stepdown_t50_min_by_block": [1.4, 1.5, 1.3],
        "lineage_survival_pct_by_lineage": {"INS_beta": 68.0, "GCG_alpha": 91.0, "SST_delta": 92.0, "PLVAP_iEC": 88.0, "pericyte": 90.0},
    }
    att_panel_hyp = {
        "block_ids": att_s2_bids,
        "cond1_vehicle_beta_t0_pct_by_block": [90.0, 89.0, 91.0],
        "cond2_ifng_alone_beta_t0_pct_by_block": [86.5, 85.5, 87.5],
        "cond3_isolated_tnfa_ifng_beta_t0_pct_by_block": [67.0, 64.0, 67.0],
        "cond4_il1b_ifng_beta_t0_pct_by_block": [85.0, 83.0, 86.5],
        "cond5_pooled_triple_cytokine_beta_t0_pct_by_block": [65.0, 62.0, 65.0],
        "cleaved_caspase8_fold_by_block": [1.3, 1.4, 1.2],
        "cleaved_caspase9_fold_by_block": [3.9, 4.1, 4.0],
        "cytochrome_c_release_pct_by_block": [48.0, 51.0, 49.0],
        "pmlkl_ratio_by_block": [1.08, 1.12, 1.07],
        "bim_dp5_puma_induction_fold_by_block": [3.6, 3.9, 3.7],
        "il1_pathway_positive_control_verified": True,
        "il1_positive_control_parental_drop_pp_by_block": [29.0, 30.0, 29.0],
        "cxcl10_assay_lod_mfi": 50.0,
        "cxcl10_matched_ctrl_24h_mfi_by_block": [940.0, 935.0, 955.0],
        "cxcl10_0h_mfi_by_block": [1000.0, 1000.0, 1000.0],
        "cxcl10_24h_mfi_by_block": [900.0, 890.0, 910.0],
        "cxcl10_0h_vs_24h_shield_retention_pct_by_block": [90.0, 89.0, 91.0],
        "serpinb9_pct_matched_ctrl_by_block": [92.5, 91.5, 93.5],
        "pdl1_pct_matched_ctrl_by_block": [91.0, 90.5, 92.0],
        "post_washout_gsis_si_by_block": [3.4, 3.5, 3.3],
        "post_washout_gsis_z2_by_block": [1.65, 1.72, 1.68],
        "post_washout_gsis_stepdown_t50_min_by_block": [1.6, 1.7, 1.5],
        "lineage_survival_pct_by_lineage": {"INS_beta": 64.0, "GCG_alpha": 89.0, "SST_delta": 90.0, "PLVAP_iEC": 86.0, "pericyte": 88.0},
    }
    att_y = _sign_receipt({
        "stage": "IIP0049_ATTRIBUTION", "verdict": "PASS",
        "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "exact_product", "recorded_at_utc": "2026-09-15T08:30:00Z",
        "prerequisite_receipt_sha256s": {
            "BANK_MATERIALIZATION": mat_yc["receipt_sha256"],
            "DRUG_FREE_EXPOSURE": df_y["receipt_sha256"],
            "GATE-36-FOUNDRY-V2": g36_y["receipt_sha256"],
        },
        "reference_comparator_backgrounds": [
            "PARENTAL_UNEDITED", "DESIGN_A_CHASSIS_REFERENCE",
            "MULTI_MIR_IL1R1_FAS_REFERENCE", "STANDALONE_IL1R1_FAS_CBE_REFERENCE",
            "CD64T_IL1RN_REFERENCE", "EXACT_PRODUCT_FOUNDRY_V2",
        ],
        "reference_comparator_measurements": {
            _bg: {
                "normoxia": {
                    "block_ids": att_s2_bids,
                    "cond1_vehicle_beta_t0_pct_by_block": _nc1,
                    "cond2_ifng_alone_beta_t0_pct_by_block": [x - 3.0 for x in _nc1],
                    "cond3_isolated_tnfa_ifng_beta_t0_pct_by_block": _nc3,
                    "cond4_il1b_ifng_beta_t0_pct_by_block": _nc4,
                    "cond5_pooled_triple_cytokine_beta_t0_pct_by_block": [x - 3.0 for x in _nc3],
                },
                "hypoxia_15mmhg": {
                    "block_ids": att_s2_bids,
                    "cond1_vehicle_beta_t0_pct_by_block": [x - 2.0 for x in _nc1],
                    "cond2_ifng_alone_beta_t0_pct_by_block": [x - 5.5 for x in _nc1],
                    "cond3_isolated_tnfa_ifng_beta_t0_pct_by_block": [x - 4.0 for x in _nc3],
                    "cond4_il1b_ifng_beta_t0_pct_by_block": [x - 3.0 for x in _nc4],
                    "cond5_pooled_triple_cytokine_beta_t0_pct_by_block": [x - 6.0 for x in _nc3],
                },
            }
            for _bg, _nc1, _nc3, _nc4 in (
                ("PARENTAL_UNEDITED", [93.0, 92.0, 94.0], [62.0, 60.0, 63.0], [65.0, 63.0, 66.0]),
                ("DESIGN_A_CHASSIS_REFERENCE", [92.5, 91.5, 93.5], [64.0, 62.0, 65.0], [67.0, 65.0, 68.0]),
                ("MULTI_MIR_IL1R1_FAS_REFERENCE", [92.0, 91.0, 93.0], [69.0, 67.0, 70.0], [87.5, 86.0, 88.5]),
                ("STANDALONE_IL1R1_FAS_CBE_REFERENCE", [92.0, 91.0, 93.0], [68.5, 66.5, 69.5], [87.0, 85.5, 88.0]),
                ("CD64T_IL1RN_REFERENCE", [92.0, 91.0, 93.0], [70.0, 67.5, 70.5], [88.0, 86.5, 89.0]),
                ("EXACT_PRODUCT_FOUNDRY_V2", [92.0, 91.0, 93.0], [71.0, 68.0, 71.0], [88.0, 86.0, 89.5]),
            )
        },
        "stage1_gatekeeper_record": {
            "batch_id": "S1-BATCH-001", "decision_id": "S1-DEC-2026-001",
            "assay_acquired_at_utc": "2026-09-14T08:00:00Z",
            "decision_recorded_at_utc": "2026-09-14T09:00:00Z",
            "parental_il1b_ifng_drop_pp": 28.0, "edited_il1b_ifng_drop_pp": 4.2, "edited_isolated_tnfa_ifng_drop_pp": 22.0,
            "unmodified_isogenic_viability_pct_by_cond": {"vehicle": 93.0, "il1b_ifng": 65.0, "isolated_tnfa_ifng": 62.0},
            "unmodified_isogenic_caspase3_7_fold_by_cond": {"vehicle": 1.0, "il1b_ifng": 3.8, "isolated_tnfa_ifng": 4.1},
            "edited_chassis_viability_pct_by_cond": {"vehicle": 92.5, "il1b_ifng": 87.5, "isolated_tnfa_ifng": 68.5},
            "edited_chassis_caspase3_7_fold_by_cond": {"vehicle": 1.0, "il1b_ifng": 1.25, "isolated_tnfa_ifng": 3.7},
            "edited_chassis_plus_foundry_v2_viability_pct_by_cond": {"vehicle": 92.2, "il1b_ifng": 88.0, "isolated_tnfa_ifng": 70.2},
            "edited_chassis_plus_foundry_v2_caspase3_7_fold_by_cond": {"vehicle": 1.0, "il1b_ifng": 1.2, "isolated_tnfa_ifng": 3.5},
        },
        "stage2_block_manifest": [
            {"block_id": "S2-BLK-1", "differentiation_batch_id": "DIFF-B1", "stage1_decision_id": "S1-DEC-2026-001", "study_start_utc": "2026-09-14T10:00:00Z", "harvest_utc": "2026-09-14T14:00:00Z"},
            {"block_id": "S2-BLK-2", "differentiation_batch_id": "DIFF-B2", "stage1_decision_id": "S1-DEC-2026-001", "study_start_utc": "2026-09-14T11:00:00Z", "harvest_utc": "2026-09-14T16:00:00Z"},
            {"block_id": "S2-BLK-3", "differentiation_batch_id": "DIFF-B3", "stage1_decision_id": "S1-DEC-2026-001", "study_start_utc": "2026-09-14T12:00:00Z", "harvest_utc": "2026-09-14T18:00:00Z"},
        ],
        "stage1_cytokine_window_positive": True, "stage1_cytokine_drop_pp": 22.0,
        "stage2_il1_independent_apoptosis_persists": True, "residual_viable_beta_drop_pp": 22.0,
        "concurrent_controls_valid": True, "t0_original_plated_denominators_used": True,
        "biological_blocks_n": 3, "background_class": "MATCHED_FOUNDRY_V2",
        "foundry_v2_gate36_receipt_sha256": g36_y["receipt_sha256"],
        "stage2_normoxia_mechanism_panel": att_panel_norm,
        "stage2_hypoxia_15mmhg_mechanism_panel": att_panel_hyp,
    })
    def _mk_c1_prereg(
        prod: str, bank: str, lot: str, route: str, att_r: Mapping[str, Any],
        *, n_b: int = 6, stat_m: str = "PAIRED_T_TEST_NORMALITY_VERIFIED",
        norm_bids: Optional[list[str]] = None, hyp_bids: Optional[list[str]] = None,
        cand_gene: str = tg_dual, nt_id: str = nt_y, ts: str = "2026-09-16T08:00:00Z",
    ) -> dict[str, Any]:
        nb = norm_bids or [f"B{i+1}" for i in range(n_b)]
        hb = hyp_bids or [f"H{i+1}" for i in range(n_b)]
        arm_order = sorted(C1_FAMILY_GENES | {"NT_CTRL"})
        return _sign_receipt({
            "stage": "C-1-PREREGISTRATION", "verdict": "PASS",
            "product_id": prod, "bank_id": bank, "lot_id": lot, "route_id": route,
            "evidence_scope": "exact_product", "recorded_at_utc": ts,
            "parent_receipt_sha256": att_r["receipt_sha256"],
            "preregistered_family_genes": sorted(C1_FAMILY_GENES),
            "comparator_nt_lot_id": nt_id,
            "shared_study_id": "STUDY-GY032-Y-001",
            "locked_analysis_plan_id": "PLAN-C1-LOCKED-001",
            "block_randomization_seed_sha256": "5" * 64,
            "planned_biological_blocks_n": n_b,
            "statistical_test_method": stat_m,
            "multiplicity_method": "HOLM_BONFERRONI_5_ARM",
            "exchangeability_design_statement": "WITHIN_BLOCK_SIBLING_RANDOMIZED_TREATMENT_ASSIGNMENT",
            "block_to_batch_allocations": {
                "normoxia": [{"block_id": b, "differentiation_batch_id": f"C1-NBAT-{i+1}", "randomized_arm_order": arm_order} for i, b in enumerate(nb)],
                "hypoxia_2pct_o2": [{"block_id": b, "differentiation_batch_id": f"C1-HBAT-{i+1}", "randomized_arm_order": arm_order} for i, b in enumerate(hb)],
            },
        })

    c1_prereg_y = _mk_c1_prereg(py, by, ly, ry, att_y)
    pr_c1_yc = {"BANK_MATERIALIZATION": mat_yc["receipt_sha256"], "DRUG_FREE_EXPOSURE": df_y["receipt_sha256"]}
    pr_c1_full = {**pr_c1_yc, "C-1-PREREGISTRATION": c1_prereg_y["receipt_sha256"]}
    c1_norm_6 = _mk_r8_c1_block(
        assay_record_id="C1-NORM-Y-01", bids=["B1", "B2", "B3", "B4", "B5", "B6"],
        c9_vec=[51.0, 55.0, 49.0, 54.0, 52.0, 56.0], ctrl_vec=[54.0, 52.0, 56.0, 55.0, 53.0, 54.0],
        tr_vec=[76.0, 75.0, 79.0, 77.0, 74.0, 78.0], veh_vec=[90.0, 89.0, 91.0, 90.0, 88.0, 91.0],
        comp_vec=[71.1, 69.6, 73.8, 72.5, 69.2, 72.4],
    )
    c1_hyp_6 = _mk_r8_c1_block(
        assay_record_id="C1-HYP-Y-01", bids=["H1", "H2", "H3", "H4", "H5", "H6"],
        c9_vec=[48.0, 52.0, 47.0, 51.0, 50.0, 53.0], ctrl_vec=[50.0, 49.0, 52.0, 51.0, 48.0, 50.0],
        tr_vec=[71.2, 69.8, 74.6, 73.1, 69.0, 72.3], veh_vec=[87.0, 86.0, 88.0, 87.0, 85.0, 88.0],
        comp_vec=[67.0, 66.5, 68.5, 68.2, 64.5, 67.3],
        target_kd=80.0, nonbeta_surv=93.0, ctrl_nonbeta=68.0, batch_prefix="C1-HBAT",
    )
    def _mk_c_eng(
        cohort: str, ts_w: str, *, stage_name: str, lot_s_id: str = ly,
        specimen_id: Optional[str] = None,
        win_start: Optional[str] = None, win_end: Optional[str] = None,
        start_measured_utc: Optional[str] = None,
        mode: str = "PAIRED_START_AND_END_ALIQUOT_ASSAY",
        start_aliquot_id: Optional[str] = None, end_aliquot_id: Optional[str] = None,
        target_g: str = tg_dual, kd_start_v: Optional[float] = None, kd_v: float = 78.0, recov: bool = False,
        mid_kd_override: Optional[float] = None,
    ) -> dict[str, Any]:
        ws_eff = win_start or ts_w
        we_eff = win_end or ts_w
        sm_eff = start_measured_utc or ws_eff
        ks_eff = kd_v if kd_start_v is None else kd_start_v
        s_aid = start_aliquot_id or f"ENG-START-{stage_name}-{lot_s_id}"
        e_aid = end_aliquot_id or f"ENG-END-{stage_name}-{lot_s_id}"
        eb: dict[str, Any] = {
            "intervention_cohort_id": cohort, "stage_name": stage_name, "specimen_lot_id": lot_s_id,
            "specimen_id": specimen_id or f"SPEC-{stage_name}-{lot_s_id}",
            "engagement_measurement_mode": mode,
            "start_aliquot_assay_record_id": s_aid,
            "end_aliquot_assay_record_id": e_aid,
            "assay_window_start_utc": ws_eff,
            "assay_window_end_utc": we_eff,
            "start_measured_at_utc": sm_eff,
            "end_measured_at_utc": ts_w,
            "start_of_window_kd_pct": ks_eff,
            "end_of_window_kd_pct": kd_v,
            "target_kd_pct": min(ks_eff, kd_v),
            "recovered_to_control": recov,
        }
        if target_g == "PMAIP1+BCL2L11":
            eb["pmaip1_start_kd_pct"] = ks_eff
            eb["pmaip1_end_kd_pct"] = kd_v
            eb["bcl2l11_start_kd_pct"] = ks_eff + 1.0
            eb["bcl2l11_end_kd_pct"] = kd_v + 1.0
        if mode == "VALIDATED_LONGITUDINAL_KINETICS":
            t0 = parse_utc_iso_ts(sm_eff)
            t_end = parse_utc_iso_ts(ts_w)
            t24 = (t0 + timedelta(hours=24, minutes=30)).strftime("%Y-%m-%dT%H:%M:%SZ")
            t48 = (t0 + timedelta(hours=48, minutes=30)).strftime("%Y-%m-%dT%H:%M:%SZ")
            k24 = round(0.5 * (ks_eff + kd_v), 2)
            k48 = k24 if mid_kd_override is None else mid_kd_override
            tps_l: list[dict[str, Any]] = []
            for aid_l, ts_l, kd_l in (
                (s_aid, sm_eff, ks_eff),
                (f"ENG-24H-{stage_name}-{lot_s_id}", t24, k24),
                (f"ENG-48H-{stage_name}-{lot_s_id}", t48, k48),
                (e_aid, ts_w, kd_v),
            ):
                row_l: dict[str, Any] = {
                    "aliquot_assay_record_id": aid_l,
                    "specimen_lot_id": lot_s_id,
                    "specimen_id": eb["specimen_id"],
                    "producer_record_sha256": sha256_bytes(f"{aid_l}|{lot_s_id}|{eb['specimen_id']}|{ts_l}".encode("utf-8")),
                    "measured_at_utc": ts_l, "target_kd_pct": kd_l,
                }
                if target_g == "PMAIP1+BCL2L11":
                    row_l["pmaip1_kd_pct"] = kd_l
                    row_l["bcl2l11_kd_pct"] = kd_l + 1.0
                tps_l.append(row_l)
            eb["validated_kinetics_protocol_sha256"] = "9" * 64
            eb["longitudinal_kinetics_timepoints"] = tps_l
            eb["target_kd_pct"] = min(ks_eff, k24, k48, kd_v)
        return {**eb, "engagement_record_sha256": sha256_bytes(canonical_json_bytes(eb))}

    def _mk_c1_fam_slice(ob: Mapping[str, Any]) -> dict[str, Any]:
        return {
            "block_ids": ob["block_ids"],
            "stressed_ctrl_beta_plated_t0_by_block": ob["stressed_ctrl_beta_plated_t0_by_block"],
            "stressed_ctrl_beta_surviving_by_block": ob["stressed_ctrl_beta_surviving_by_block"],
            "stressed_ctrl_beta_t0_pct_by_block": ob["stressed_ctrl_beta_t0_pct_by_block"],
            "casp9_stressed_ctrl_raw_by_block": ob["casp9_stressed_ctrl_raw_by_block"],
            "all_five_arms_paired_data": ob["all_five_arms_paired_data"],
        }

    def _mk_c1_fam_sha(n_blk: Mapping[str, Any], h_blk: Mapping[str, Any], study_id: str = "STUDY-GY032-Y-001", plan_id: str = "PLAN-C1-LOCKED-001") -> str:
        return sha256_bytes(canonical_json_bytes({
            "shared_study_id": study_id, "locked_analysis_plan_id": plan_id,
            "normoxia": _mk_c1_fam_slice(n_blk), "hypoxia_2pct_o2": _mk_c1_fam_slice(h_blk),
        }))

    def _mk_c1_common_acq(
        n_blk: Mapping[str, Any], h_blk: Mapping[str, Any], prereg_r: Mapping[str, Any],
        *, acq_id: str = "C1-COMMON-ACQ-001",
    ) -> dict[str, Any]:
        body_ca = {
            "producer_acquisition_record_id": acq_id,
            "shared_study_id": prereg_r["shared_study_id"],
            "locked_analysis_plan_id": prereg_r["locked_analysis_plan_id"],
            "preregistration_receipt_sha256": prereg_r["receipt_sha256"],
            "block_randomization_seed_sha256": prereg_r["block_randomization_seed_sha256"],
            "normoxia_block_allocations": prereg_r["block_to_batch_allocations"]["normoxia"],
            "hypoxia_2pct_o2_block_allocations": prereg_r["block_to_batch_allocations"]["hypoxia_2pct_o2"],
            "normoxia_family_matrix": _mk_c1_fam_slice(n_blk),
            "hypoxia_2pct_o2_family_matrix": _mk_c1_fam_slice(h_blk),
        }
        return {**body_ca, "common_family_acquisition_sha256": sha256_bytes(canonical_json_bytes(body_ca))}

    c1_cohort_y = "COHORT-GY032-Y-001"
    c1_fam_sha_6 = _mk_c1_fam_sha(c1_norm_6, c1_hyp_6)
    c1_common_acq_6 = _mk_c1_common_acq(c1_norm_6, c1_hyp_6, c1_prereg_y)
    c1_y = _sign_receipt({
        "stage": "C-1", "verdict": "PASS", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "exact_product",
        "study_start_utc": "2026-09-17T08:00:00Z", "assay_acquired_at_utc": "2026-09-19T18:00:00Z",
        "recorded_at_utc": "2026-09-20T10:00:00Z",
        "parent_receipt_sha256": att_y["receipt_sha256"], "prerequisite_receipt_sha256s": pr_c1_full,
        "candidate_gene": tg_dual, "comparator_nt_lot_id": nt_y, "shared_study_id": "STUDY-GY032-Y-001",
        "locked_analysis_plan_id": "PLAN-C1-LOCKED-001", "block_randomization_seed_sha256": "5" * 64,
        "intervention_cohort_id": c1_cohort_y, "five_arm_family_matrix_sha256": c1_fam_sha_6,
        "c1_common_family_acquisition_record": c1_common_acq_6,
        "biological_blocks_n": 6, "statistical_test_method": "PAIRED_T_TEST_NORMALITY_VERIFIED",
        "multiplicity_method": "HOLM_BONFERRONI_5_ARM",
        "c1_normoxia": c1_norm_6, "c1_hypoxia_2pct_o2": c1_hyp_6,
    })

    def _mk_c2_prolif_lot(
        i: int, *, active_lot: str = ly, prod_v: str = py, gene_v: str = tg_dual, active_nt: str = nt_y, **ov: Any,
    ) -> dict[str, Any]:
        lid_v = active_lot if i == 1 else f"C2-LOT-{i}"
        nt_v = active_nt if i == 1 else f"C2-NT-LOT-{i}"
        body: dict[str, Any] = {
            "lot_id": lid_v,
            "product_id": prod_v,
            "candidate_gene": gene_v,
            "comparator_nt_lot_id": nt_v,
            "treated_sample_id": f"C2-TR-SMP-{lid_v}",
            "matched_control_sample_id": f"C2-CTRL-SMP-{nt_v}",
            "resting_assay_record_id": f"REST-ASSAY-{i}",
            "post_recovery_assay_record_id": f"POSTREC-ASSAY-{i}",
            "resting_ki67_fold_vs_ctrl": 0.98, "resting_edu_fold_vs_ctrl": 0.99,
            "post_recovery_ki67_fold_vs_ctrl": 0.97, "post_recovery_edu_fold_vs_ctrl": 0.98,
            "ki67_edu_referred": False,
        }
        body.update(ov)
        body["lot_record_sha256"] = sha256_bytes(canonical_json_bytes(body))
        return body

    def _mk_c1_with_kd_lot(blk_in: Mapping[str, Any], lot_v: str, prod_v: str) -> dict[str, Any]:
        kpb = {k: v for k, v in blk_in["molecular_kd_provenance"].items() if k != "producer_record_sha256"}
        new_sp = f"SPEC-C1-KD-{blk_in['assay_record_id']}-{lot_v}"
        kpb["product_id"] = prod_v
        kpb["specimen_lot_id"] = lot_v
        kpb["specimen_id"] = new_sp
        new_obs = []
        for orow in kpb["target_observations"]:
            ob = {k: v for k, v in orow.items() if k != "producer_observation_sha256"}
            ob["product_id"] = prod_v
            ob["specimen_lot_id"] = lot_v
            ob["specimen_id"] = new_sp
            new_obs.append({**ob, "producer_observation_sha256": sha256_bytes(canonical_json_bytes(ob))})
        kpb["target_observations"] = new_obs
        return {**blk_in, "molecular_kd_provenance": {**kpb, "producer_record_sha256": sha256_bytes(canonical_json_bytes(kpb))}}

    def _mk_c2_sol_iapp(
        *, spec_v: str, lot_v: str, nt_v: str = nt_y, aid_v: Optional[str] = None,
        treated_pg: float = 14.5, ctrl_pg: float = 13.8, ratio_override: Optional[float] = None,
    ) -> dict[str, Any]:
        sib = {
            "assay_species": "SOLUBLE_OLIGOMERIC_IAPP_ELISA_MATCHED_CTRL",
            "assay_record_id": aid_v or f"C2-SOL-IAPP-{lot_v}",
            "specimen_id": spec_v,
            "specimen_lot_id": lot_v,
            "comparator_nt_lot_id": nt_v,
            "treated_soluble_iapp_pg_per_ieq": treated_pg,
            "matched_ctrl_soluble_iapp_pg_per_ieq": ctrl_pg,
            "soluble_iapp_ratio_vs_ctrl": round(treated_pg / ctrl_pg, 6) if ratio_override is None else ratio_override,
        }
        return {**sib, "assay_receipt_sha256": sha256_bytes(canonical_json_bytes(sib))}

    def _mk_c2_surv_panel(
        *, spec_v: str, lot_v: str, nt_v: str = nt_y, aid_v: Optional[str] = None,
        bcl2l1: float = 94.0, mcl1: float = 92.0, cd59: float = 95.0,
    ) -> dict[str, Any]:
        spb = {
            "specimen_id": spec_v,
            "specimen_lot_id": lot_v,
            "comparator_nt_lot_id": nt_v,
            "assay_record_id": aid_v or f"C2-SURV-PROT-{lot_v}",
            "bcl2l1_pct_ctrl": bcl2l1,
            "mcl1_pct_ctrl": mcl1,
            "cd59_pct_ctrl": cd59,
        }
        return {**spb, "panel_receipt_sha256": sha256_bytes(canonical_json_bytes(spb))}

    c2_prolif_ok = [_mk_c2_prolif_lot(1), _mk_c2_prolif_lot(2), _mk_c2_prolif_lot(3)]
    c2_y = _sign_receipt({
        "stage": "C-2", "verdict": "PASS", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "exact_product", "recorded_at_utc": "2026-09-25T11:00:00Z",
        "assay_started_at_utc": "2026-09-22T09:00:00Z", "assay_completed_at_utc": "2026-09-25T08:00:00Z", "specimen_id": f"SPEC-C-2-{ly}",
        "parent_receipt_sha256": c1_y["receipt_sha256"], "prerequisite_receipt_sha256s": pr_c1_yc,
        "candidate_gene": tg_dual, "comparator_nt_lot_id": nt_y,
        "basal_shield_retention_pct": 93.0, "basal_shield_retention_by_component": _mk_r8_shields(py, 93.0), "hour0_density_by_lineage": _mk_r8_hour0(py),
        "granule_processing_preserved": True,
        "proinsulin_to_insulin_fold_vs_ctrl": 1.05, "pcsk1_pct_ctrl": 94.0, "pcsk2_pct_ctrl": 93.0, "cpe_pct_ctrl": 95.0,
        "chgb_pct_ctrl": 94.0, "scg2_pct_ctrl": 93.0,
        "soluble_iapp_pg_per_ieq": 14.5,
        "soluble_iapp_matched_ctrl_assay": _mk_c2_sol_iapp(spec_v=f"SPEC-C-2-{ly}", lot_v=ly, nt_v=nt_y),
        "iapp_amyloid_ratio_vs_ctrl": 1.04,
        "resting_survival_protein_panel": _mk_c2_surv_panel(spec_v=f"SPEC-C-2-{ly}", lot_v=ly, nt_v=nt_y),
        "c2_per_lot_proliferation_records": c2_prolif_ok,
        "transient_target_engagement_record": _mk_c_eng(c1_cohort_y, "2026-09-25T08:00:00Z", stage_name="C-2", lot_s_id=ly, win_start="2026-09-22T08:00:00Z", win_end="2026-09-25T09:00:00Z"),
    })
    sw_y_c = _mk_r8_switch(py, by, ly, ry, mat_yc, "2026-09-28T14:00:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": c2_y["receipt_sha256"]}, transient_engagement=_mk_c_eng(c1_cohort_y, "2026-09-28T13:00:00Z", stage_name="NATIVE_SAFETY_SWITCH", lot_s_id=ly, win_start="2026-09-25T12:00:00Z", win_end="2026-09-28T13:15:00Z", mode="VALIDATED_LONGITUDINAL_KINETICS"))
    g0v_y_c = _mk_r8_gate0v(py, by, ly, ry, mat_yc, "2026-09-28T14:30:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": c2_y["receipt_sha256"]}, transient_engagement=_mk_c_eng(c1_cohort_y, "2026-09-28T13:15:00Z", stage_name="GATE-0V-KILL", lot_s_id=ly, win_start="2026-09-25T12:00:00Z", win_end="2026-09-28T13:30:00Z", mode="VALIDATED_LONGITUDINAL_KINETICS"))
    pr_c3_yc = {
        "BANK_MATERIALIZATION": mat_yc["receipt_sha256"], "DRUG_FREE_EXPOSURE": df_y["receipt_sha256"],
        "NATIVE_SAFETY_SWITCH": sw_y_c["receipt_sha256"], "GATE-0V-KILL": g0v_y_c["receipt_sha256"],
    }
    c3_nk_y = _sign_receipt({
        "stage": "C-3-NK", "verdict": "PASS", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "exact_product", "recorded_at_utc": "2026-09-30T12:00:00Z",
        "assay_started_at_utc": "2026-09-28T15:30:00Z", "assay_completed_at_utc": "2026-09-30T10:00:00Z", "specimen_id": f"SPEC-C-3-NK-{ly}",
        "parent_receipt_sha256": c2_y["receipt_sha256"], "prerequisite_receipt_sha256s": pr_c3_yc,
        "candidate_gene": tg_dual, "comparator_nt_lot_id": nt_y,
        "transient_target_engagement_record": _mk_c_eng(c1_cohort_y, "2026-09-30T09:00:00Z", stage_name="C-3-NK", lot_s_id=ly, win_start="2026-09-28T15:00:00Z", win_end="2026-09-30T11:00:00Z"),
        "readout3b_evidence": _mk_r8_readout3b(include_sirpa_low=True, specimen_id=f"SPEC-C-3-NK-{ly}", specimen_lot_id=ly, intervention_cohort_id=c1_cohort_y),
    })
    c3_gsis_y = _sign_receipt({
        "stage": "C-3-GSIS", "verdict": "PASS", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "exact_product", "recorded_at_utc": "2026-10-02T13:00:00Z",
        "assay_started_at_utc": "2026-09-30T14:00:00Z", "assay_completed_at_utc": "2026-10-01T16:00:00Z", "specimen_id": f"SPEC-C-3-GSIS-{ly}",
        "parent_receipt_sha256": c3_nk_y["receipt_sha256"], "prerequisite_receipt_sha256s": pr_c3_yc,
        "candidate_gene": tg_dual, "comparator_nt_lot_id": nt_y,
        "transient_target_engagement_record": _mk_c_eng(c1_cohort_y, "2026-10-01T16:00:00Z", stage_name="C-3-GSIS", lot_s_id=ly, win_start="2026-09-30T13:00:00Z", win_end="2026-10-01T18:00:00Z"),
        "readout2_evidence": _mk_r8_readout2(
            matched_comparator_id=nt_y, block_prefix="C3G", lot_id=ly,
            stage7_start_utc="2026-09-12T00:00:00Z", sort_reaggregation_utc="2026-09-22T00:00:00Z", assay_harvest_utc="2026-10-01T00:00:00Z",
            specimen_id=f"SPEC-C-3-GSIS-{ly}", intervention_cohort_id=c1_cohort_y, candidate_gene=tg_dual,
        ),
    })
    g42_ok = {
        "target_arm": "Y", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "drug_free_exposure_evidence": df_y, "materialization_evidence": mat_yc,
        "foundry_v2_gate36_evidence": g36_y, "native_switch_evidence": sw_y_c, "gate0v_evidence": g0v_y_c,
        "zero_fasta_minted": True, "iip0049_foundry_attribution_evidence": att_y,
        "target_gene": tg_dual, "c1_preregistered_plan_receipt": c1_prereg_y, "c1_evidence": c1_y, "c2_evidence": c2_y,
        "c3_nk_evidence": c3_nk_y, "c3_gsis_evidence": c3_gsis_y,
    }
    r42 = evaluate_gate42_gy032_channel_c_screen(g42_ok)
    chk(r42["verdict"] == OFFLINE_VERDICT_PRIMARY and r42["release_authorizing"] is False and r42["live_ledger_authenticated"] is False, "G42_pass_dual")

    # GATE-42 closures (10 brand-new tests!)
    # 1. IIP-0049 Stage-2 IL-1b+IFNg control NOT protected (confounded drop = 20 pp) FAILS!
    att_il1_bad = _sign_receipt({**att_y, "stage2_normoxia_mechanism_panel": {**att_panel_norm, "cond4_il1b_ifng_beta_t0_pct_by_block": [70.0, 71.0, 72.0]}})
    chk("FAIL_IIP0049_IL1_CONTROL_NOT_PROTECTED_OR_CONFOUNDED:NORMOXIA" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": att_il1_bad})["failures"], "G42_ADV_iip0049_il1_confounded")
    # 2. IIP-0049 Stage-2 extrinsic caspase-8 >= caspase-9 FAILS intrinsic attribution!
    att_c8_bad = _sign_receipt({**att_y, "stage2_normoxia_mechanism_panel": {**att_panel_norm, "cleaved_caspase8_fold_by_block": [4.5, 4.8, 4.6]}})
    chk("FAIL_IIP0049_INTRINSIC_CASP9_BH3_MECHANISM_UNPROVEN:NORMOXIA" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": att_c8_bad})["failures"], "G42_ADV_iip0049_casp8_dom")
    # 3. IIP-0049 Stage-2 compromised shield kinetics (< 85%) on attribution background FAILS!
    att_sh_bad = _sign_receipt({**att_y, "stage2_normoxia_mechanism_panel": {**att_panel_norm, "cxcl10_0h_vs_24h_shield_retention_pct_by_block": [70.0, 72.0, 74.0]}})
    chk("FAIL_IIP0049_SHIELD_KINETICS_COMPROMISED_ON_BACKGROUND:NORMOXIA" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": att_sh_bad})["failures"], "G42_ADV_iip0049_shield_kinetics")
    # 4. IIP-0049 Stage-2 failed post-washout GSIS (< 3.0) on attribution background FAILS!
    att_gs_bad = _sign_receipt({**att_y, "stage2_hypoxia_15mmhg_mechanism_panel": {**att_panel_hyp, "post_washout_gsis_si_by_block": [2.2, 2.5, 2.4]}})
    chk("FAIL_IIP0049_POST_WASHOUT_GSIS_FAILED_ON_BACKGROUND:HYPOXIA15" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": att_gs_bad})["failures"], "G42_ADV_iip0049_postwash_gsis")
    # 5. IIP-0049 reported residual drop mismatched vs 5-condition raw vectors FAILS!
    chk("FAIL_IIP0049_REPORTED_RESIDUAL_DROP_MISMATCH_VS_5COND_RAW" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _sign_receipt({**att_y, "residual_viable_beta_drop_pp": 30.0})})["failures"], "G42_ADV_iip0049_raw_mismatch")
    # 6. Native safety switch missing data-backed matched-control parity receipt triggers HOLD!
    sw_no_par = _sign_receipt({**sw_y_c, "matched_control_switch_parity_evidence": None})
    chk("HOLD_NATIVE_SWITCH_MATCHED_CONTROL_SWITCH_PARITY_MISSING" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "native_switch_evidence": sw_no_par})["holds"], "G42_ADV_sw_parity_missing_hold")
    # 7. Native safety switch parity bound to wrong NT comparator lot FAILS!
    sw_wrong_par = _sign_receipt({**sw_y_c, "matched_control_switch_parity_evidence": _mk_r8_switch_parity("OTHER-NT-LOT")})
    chk("FAIL_NATIVE_SWITCH_SW_PARITY_COMPARATOR_LOT_MISMATCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "native_switch_evidence": sw_wrong_par})["failures"], "G42_ADV_sw_parity_wrong_nt")
    # 8. C-2 cross-lot reuse of resting_assay_record_id across LOT-1 & LOT-2 FAILS!
    chk("FAIL_GATE_C2_PROLIF_ASSAY_RECORDS_MISSING_OR_IDENTICAL:C2-LOT-2" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "c2_per_lot_proliferation_records": [_mk_c2_prolif_lot(1), _mk_c2_prolif_lot(2, resting_assay_record_id="REST-ASSAY-1"), _mk_c2_prolif_lot(3)]})})["failures"], "G42_ADV_c2_cross_lot_assay_reuse")
    # 9. Exact scale-invariant Decimal sign-flip returns exact 0.5 on [1e-13, 2e-13] and 0.25 on [1e-13, 2e-13, 4e-13] (NOT 1.0 under 1e-12 epsilon!)
    chk(exact_two_sided_sign_flip_p([1e-13, 2e-13]) == 0.5 and exact_two_sided_sign_flip_p([1e-13, 2e-13, 4e-13]) == 0.25, "G42_ADV_exact_decimal_signflip_tiny_scale")
    # 10. JAK2 hypomorph requires quantitative gy001_cxcl10_inducible_shield_pct_ctrl >= 85% (below 85% FAILS)!
    c1_jk_bad = _mk_r8_c1_block(assay_record_id="C1-JK-N", bids=["B1","B2","B3","B4","B5","B6"], c9_vec=[51.0,55.0,49.0,54.0,52.0,56.0], ctrl_vec=[54.0,52.0,56.0,55.0,53.0,54.0], tr_vec=[76.0,75.0,79.0,77.0,74.0,78.0], veh_vec=[90.0]*6, comp_vec=[71.0]*6, target="JAK2", target_kd=58.0, jak2_shield_pct=72.0)
    chk("FAIL_GATE_C1_NORMOXIA_JAK2_GY001_SHIELD_BELOW_85PCT" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "target_gene": "JAK2", "c1_evidence": _sign_receipt({**c1_y, "candidate_gene": "JAK2", "c1_normoxia": c1_jk_bad})})["failures"], "G42_ADV_jak2_quant_gy001")

    # & Core 67 GATE-42 invariants
    ctrl17 = [50.0] * 16 + [99.0]
    tr17 = [67.0] * 16 + [1.0]
    c1_sf17_bad = _mk_r8_c1_block(assay_record_id="C1-NORM-SF17", bids=[f"S{i}" for i in range(17)], c9_vec=[50.0+(i%4) for i in range(17)], ctrl_vec=ctrl17, tr_vec=tr17, veh_vec=[99.5]*17, comp_vec=[62.0]*16+[1.0], stat_method="EXACT_TWO_SIDED_SIGN_FLIP")
    c1_sf17_hyp = _mk_r8_c1_block(assay_record_id="C1-HYP-SF17", bids=[f"H{i}" for i in range(17)], c9_vec=[48.0+(i%4) for i in range(17)], ctrl_vec=[48.0]*16+[97.0], tr_vec=[65.0]*16+[1.0], veh_vec=[98.0]*17, comp_vec=[60.0]*16+[1.0], stat_method="EXACT_TWO_SIDED_SIGN_FLIP")
    r_sf17 = evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "biological_blocks_n": 17, "statistical_test_method": "EXACT_TWO_SIDED_SIGN_FLIP", "c1_normoxia": c1_sf17_bad, "c1_hypoxia_2pct_o2": c1_sf17_hyp})})
    chk(exact_two_sided_sign_flip_p([6.0]*16 + [-90.0]) == 1.0 and "FAIL_GATE_C1_NORMOXIA_HOLM_BETA_PVALUE_GE_0P01" in r_sf17["failures"], "G42_ADV_sf17_counterexample_fails")
    bad_sib_p = {**c1_norm_6, "family_raw_p_values_beta": {**c1_norm_6["family_raw_p_values_beta"], "BBC3": 0.0001}}
    chk("FAIL_GATE_C1_NORMOXIA_SIBLING_RAW_PVALUE_MISMATCH_BETA:BBC3" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": bad_sib_p})})["failures"], "G42_ADV_sibling_rawp_tamper")
    c1_beta_cp = _mk_r8_c1_block(assay_record_id="C1-HYP-CP", bids=["H1","H2","H3","H4","H5","H6"], c9_vec=[48.0,52.0,47.0,51.0,50.0,53.0], ctrl_vec=[54.0,52.0,56.0,55.0,53.0,54.0], tr_vec=[76.0,75.0,79.0,77.0,74.0,78.0], veh_vec=[90.0,89.0,91.0,90.0,88.0,91.0], comp_vec=[71.0,70.0,73.0,72.0,70.0,72.0])
    chk("FAIL_GATE_C1_IDENTICAL_COPY_PASTE_BETA_ACROSS_OXYGEN_REGIMES" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_hypoxia_2pct_o2": c1_beta_cp})})["failures"], "G42_ADV_beta_only_cp")
    c1_neg_c9 = _mk_r8_c1_block(assay_record_id="C1-NORM-NEGC9", bids=["B1","B2","B3","B4","B5","B6"], c9_vec=[-15.0,50.0,48.0,45.0,42.0,40.0], ctrl_vec=[54.0,52.0,56.0,55.0,53.0,54.0], tr_vec=[76.0,75.0,79.0,77.0,74.0,78.0], veh_vec=[90.0,89.0,91.0,90.0,88.0,91.0], comp_vec=[71.0,70.0,73.0,72.0,70.0,72.0])
    r_negc9 = evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": c1_neg_c9})})
    chk("FAIL_GATE_C1_NORMOXIA_MEAN_CASP9_REDUCTION_BELOW_40PCT" in r_negc9["failures"] and "FAIL_GATE_C1_NORMOXIA_CASP9_OUT_OF_DOMAIN_NEG100_100" not in r_negc9["failures"], "G42_ADV_casp9_sign_preserving")
    sw_late = _mk_r8_switch(py, by, ly, ry, mat_yc, "2026-10-01T09:00:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y)
    pr_c3_late = {**pr_c3_yc, "NATIVE_SAFETY_SWITCH": sw_late["receipt_sha256"]}
    c3nk_late = _sign_receipt({**c3_nk_y, "prerequisite_receipt_sha256s": pr_c3_late})
    c3gs_late = _sign_receipt({**c3_gsis_y, "parent_receipt_sha256": c3nk_late["receipt_sha256"], "prerequisite_receipt_sha256s": pr_c3_late})
    chk("FAIL_CHRONOLOGICAL_PREREQ_POSTDATES_STAGE:NATIVE_SAFETY_SWITCH_AFTER_C-3-NK" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "native_switch_evidence": sw_late, "c3_nk_evidence": c3nk_late, "c3_gsis_evidence": c3gs_late})["failures"], "G42_ADV_sw_postdates_c3nk")
    df_late = _sign_receipt({**df_y, "recorded_at_utc": "2026-10-10T08:00:00Z"})
    chk("FAIL_CHRONOLOGICAL_PREREQ_POSTDATES_STAGE:DRUG_FREE_EXPOSURE_AFTER_C-1" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "drug_free_exposure_evidence": df_late, "foundry_v2_gate36_evidence": _sign_receipt({**g36_y, "prerequisite_receipt_sha256s": {"DRUG_FREE_EXPOSURE": df_late["receipt_sha256"]}}), "c1_evidence": _sign_receipt({**c1_y, "prerequisite_receipt_sha256s": {**pr_c1_yc, "DRUG_FREE_EXPOSURE": df_late["receipt_sha256"]}})})["failures"], "G42_ADV_df_postdates_c1")
    chk("FAIL_IIP0049_MISSING_SEPARATED_MECHANISM_PANEL:HYPOXIA15" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _sign_receipt({**att_y, "stage2_hypoxia_15mmhg_mechanism_panel": None})})["failures"], "G42_ADV_iip0049_panel_req")
    chk(f"FAIL_GATE_C2_PROLIF_ASSAY_RECORDS_MISSING_OR_IDENTICAL:{ly}" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "c2_per_lot_proliferation_records": [_mk_c2_prolif_lot(1, post_recovery_assay_record_id="REST-ASSAY-1"), c2_prolif_ok[1], c2_prolif_ok[2]]})})["failures"], "G42_ADV_c2_distinct_ids")
    chk(f"HOLD_GATE_C2_PROLIFERATION_ELEVATION_REFERRED:{ly}" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "c2_per_lot_proliferation_records": [_mk_c2_prolif_lot(1, post_recovery_edu_fold_vs_ctrl=1.04, ki67_edu_referred=True), c2_prolif_ok[1], c2_prolif_ok[2]]})})["holds"], "G42_ADV_c2_postrec_hold")
    c1_sf21 = _mk_r8_c1_block(assay_record_id="C1-NORM-SF21", bids=[f"S{i}" for i in range(21)], c9_vec=[50.0+(i%3) for i in range(21)], ctrl_vec=[52.0+(i%3) for i in range(21)], tr_vec=[75.0+(i%3) for i in range(21)], veh_vec=[90.0]*21, comp_vec=[70.0+(i%2) for i in range(21)], stat_method="PAIRED_T_TEST_NORMALITY_VERIFIED")
    chk("HOLD_GATE_C1_NORMOXIA_EXACT_SIGN_FLIP_N_GT_20_REQUIRES_PAIRED_T" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "biological_blocks_n": 21, "statistical_test_method": "EXACT_TWO_SIDED_SIGN_FLIP", "c1_normoxia": c1_sf21, "c1_hypoxia_2pct_o2": {**c1_sf21, "assay_record_id": "C1-HYP-SF21"}})})["holds"], "G42_ADV_sf21_holds")

    c1_t45 = _mk_r8_c1_block(assay_record_id="C1-T45", bids=["B1","B2","B3","B4","B5","B6"], c9_vec=[51.0,55.0,49.0,54.0,52.0,56.0], ctrl_vec=[50.0]*6, tr_vec=[62.0,78.0,59.0,81.0,61.0,85.0], veh_vec=[90.0]*6, comp_vec=[58.0,73.0,55.5,76.0,57.5,79.5])
    chk("FAIL_GATE_C1_NORMOXIA_HOLM_BETA_PVALUE_GE_0P01" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": c1_t45})})["failures"], "G42_ADV_t45_holm5")
    c1_n10 = _mk_r8_c1_block(assay_record_id="C1-SF10-N", bids=[f"N{i}" for i in range(10)], c9_vec=[50.0+(i%4) for i in range(10)], ctrl_vec=[53.0+(i%3) for i in range(10)], tr_vec=[76.0+(i%3) for i in range(10)], veh_vec=[90.0+(i%2) for i in range(10)], comp_vec=[70.0+(i%2) for i in range(10)], stat_method="EXACT_TWO_SIDED_SIGN_FLIP")
    c1_h10 = _mk_r8_c1_block(assay_record_id="C1-SF10-H", bids=[f"H{i}" for i in range(10)], c9_vec=[47.0+(i%4) for i in range(10)], ctrl_vec=[49.0+(i%3) for i in range(10)], tr_vec=[71.0+(i%3) for i in range(10)], veh_vec=[86.0+(i%2) for i in range(10)], comp_vec=[66.0+(i%2) for i in range(10)], stat_method="EXACT_TWO_SIDED_SIGN_FLIP", target_kd=80.0, nonbeta_surv=93.0, ctrl_nonbeta=68.0, batch_prefix="C1-HBAT")
    chk(abs(c1_n10["holm_adjusted_beta_p_value"] - 0.009765625) < 1e-9, "G42_ADV_sf10_exact")
    c1_prereg_sf10 = _mk_c1_prereg(py, by, ly, ry, att_y, n_b=10, stat_m="EXACT_TWO_SIDED_SIGN_FLIP", norm_bids=[f"N{i}" for i in range(10)], hyp_bids=[f"H{i}" for i in range(10)])
    c1_fam_sha_10 = _mk_c1_fam_sha(c1_n10, c1_h10)
    c1_sf10 = _sign_receipt({**c1_y, "prerequisite_receipt_sha256s": {**pr_c1_yc, "C-1-PREREGISTRATION": c1_prereg_sf10["receipt_sha256"]}, "biological_blocks_n": 10, "statistical_test_method": "EXACT_TWO_SIDED_SIGN_FLIP", "five_arm_family_matrix_sha256": c1_fam_sha_10, "c1_common_family_acquisition_record": _mk_c1_common_acq(c1_n10, c1_h10, c1_prereg_sf10, acq_id="C1-COMMON-ACQ-SF10"), "c1_normoxia": c1_n10, "c1_hypoxia_2pct_o2": c1_h10})
    c2_sf10 = _sign_receipt({**c2_y, "parent_receipt_sha256": c1_sf10["receipt_sha256"]})
    sw_sf10 = _mk_r8_switch(py, by, ly, ry, mat_yc, "2026-09-28T14:00:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": c2_sf10["receipt_sha256"]}, transient_engagement=_mk_c_eng(c1_cohort_y, "2026-09-28T13:00:00Z", stage_name="NATIVE_SAFETY_SWITCH", lot_s_id=ly, win_start="2026-09-25T12:00:00Z", win_end="2026-09-28T13:15:00Z", mode="VALIDATED_LONGITUDINAL_KINETICS"))
    g0v_sf10 = _mk_r8_gate0v(py, by, ly, ry, mat_yc, "2026-09-28T14:30:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": c2_sf10["receipt_sha256"]}, transient_engagement=_mk_c_eng(c1_cohort_y, "2026-09-28T13:15:00Z", stage_name="GATE-0V-KILL", lot_s_id=ly, win_start="2026-09-25T12:00:00Z", win_end="2026-09-28T13:30:00Z", mode="VALIDATED_LONGITUDINAL_KINETICS"))
    pr_c3_sf10 = {**pr_c1_yc, "NATIVE_SAFETY_SWITCH": sw_sf10["receipt_sha256"], "GATE-0V-KILL": g0v_sf10["receipt_sha256"]}
    c3n_sf10 = _sign_receipt({**c3_nk_y, "parent_receipt_sha256": c2_sf10["receipt_sha256"], "prerequisite_receipt_sha256s": pr_c3_sf10})
    c3g_sf10 = _sign_receipt({**c3_gsis_y, "parent_receipt_sha256": c3n_sf10["receipt_sha256"], "prerequisite_receipt_sha256s": pr_c3_sf10})
    chk(evaluate_gate42_gy032_channel_c_screen({**g42_ok, "native_switch_evidence": sw_sf10, "gate0v_evidence": g0v_sf10, "c1_preregistered_plan_receipt": c1_prereg_sf10, "c1_evidence": c1_sf10, "c2_evidence": c2_sf10, "c3_nk_evidence": c3n_sf10, "c3_gsis_evidence": c3g_sf10})["verdict"] == OFFLINE_VERDICT_PRIMARY, "G42_ADV_sf10_pass")
    chk("FAIL_GATE_C1_NORMOXIA_DUAL_L95_SUPERIORITY_VS_BCL2L11_FAILED" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "head_to_head_vs_bcl2l11_l95_delta_pp": 9.99}})})["failures"], "G42_ADV_dual_l95_tamper")
    chk("FAIL_FOUNDRY_V2_GATE36_LIVE_GATE32_DEBRIS_RECALL_NOT_PASSED" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "foundry_v2_gate36_evidence": _sign_receipt({**g36_y, "live_gate32_debris_recall_receipt": _sign_receipt({**g32_y, "debris_recall_verdict": "HOLD_DEBRIS_RECALL"})})})["failures"], "G42_ADV_g36_g32_fail")
    chk(f"FAIL_GATE_C2_UNREFERRED_PROLIFERATION_ELEVATION:{ly}" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "c2_per_lot_proliferation_records": [_mk_c2_prolif_lot(1, resting_ki67_fold_vs_ctrl=1.03, ki67_edu_referred=False), c2_prolif_ok[1], c2_prolif_ok[2]]})})["failures"], "G42_ADV_c2_prolif_unref")
    chk(f"FAIL_GATE_C2_PROLIF_LOT_RECORD_HASH_INVALID:{ly}" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "c2_per_lot_proliferation_records": [{**c2_prolif_ok[0], "resting_ki67_fold_vs_ctrl": 0.91}, c2_prolif_ok[1], c2_prolif_ok[2]]})})["failures"], "G42_c2_lot_hash_tamper")
    # Design A diagnostic sensitivity non-advancing (materialized + uncoated R1 + unmodified reference + no G36!)
    mat_ac = _mk_r8_mat(pa, ba, la, "2026-09-10T08:00:00Z")
    df_ac = _sign_receipt({**df_y, "product_id": pa, "bank_id": ba, "lot_id": la, "route_id": ra, "parent_receipt_sha256": mat_ac["receipt_sha256"]})
    s1_ac = {
        k: v for k, v in att_y["stage1_gatekeeper_record"].items()
        if k not in ("edited_chassis_plus_foundry_v2_viability_pct_by_cond", "edited_chassis_plus_foundry_v2_caspase3_7_fold_by_cond")
    }
    s1_ac["edited_il1b_ifng_drop_pp"] = 5.0
    s1_ac["edited_isolated_tnfa_ifng_drop_pp"] = 24.0
    ref_da_norm = att_y["reference_comparator_measurements"]["DESIGN_A_CHASSIS_REFERENCE"]["normoxia"]
    ref_da_hyp = att_y["reference_comparator_measurements"]["DESIGN_A_CHASSIS_REFERENCE"]["hypoxia_15mmhg"]
    # Design A diagnostic uses protected IL-1b comparator vector matching DESIGN_A_CHASSIS_REFERENCE!
    da_ref_fixed = {
        **att_y["reference_comparator_measurements"],
        "DESIGN_A_CHASSIS_REFERENCE": {
            "normoxia": {**ref_da_norm, "cond4_il1b_ifng_beta_t0_pct_by_block": [88.5, 87.0, 89.5]},
            "hypoxia_15mmhg": {**ref_da_hyp, "cond4_il1b_ifng_beta_t0_pct_by_block": [85.5, 84.0, 86.5]},
        },
    }
    att_panel_da_n = {**att_panel_norm, **{ck: da_ref_fixed["DESIGN_A_CHASSIS_REFERENCE"]["normoxia"][ck] for ck in ("cond1_vehicle_beta_t0_pct_by_block", "cond2_ifng_alone_beta_t0_pct_by_block", "cond3_isolated_tnfa_ifng_beta_t0_pct_by_block", "cond4_il1b_ifng_beta_t0_pct_by_block", "cond5_pooled_triple_cytokine_beta_t0_pct_by_block")}}
    att_panel_da_h = {**att_panel_hyp, **{ck: da_ref_fixed["DESIGN_A_CHASSIS_REFERENCE"]["hypoxia_15mmhg"][ck] for ck in ("cond1_vehicle_beta_t0_pct_by_block", "cond2_ifng_alone_beta_t0_pct_by_block", "cond3_isolated_tnfa_ifng_beta_t0_pct_by_block", "cond4_il1b_ifng_beta_t0_pct_by_block", "cond5_pooled_triple_cytokine_beta_t0_pct_by_block")}}
    att_ac = _sign_receipt({
        **att_y, "product_id": pa, "bank_id": ba, "lot_id": la, "route_id": ra,
        "background_class": "UNMODIFIED_DESIGN_A_REFERENCE", "foundry_v2_gate36_receipt_sha256": None,
        "prerequisite_receipt_sha256s": {"BANK_MATERIALIZATION": mat_ac["receipt_sha256"], "DRUG_FREE_EXPOSURE": df_ac["receipt_sha256"]},
        "reference_comparator_measurements": da_ref_fixed,
        "stage1_gatekeeper_record": s1_ac, "stage1_cytokine_drop_pp": 24.0,
        "residual_viable_beta_drop_pp": 28.833333333333332,
        "stage2_normoxia_mechanism_panel": att_panel_da_n,
        "stage2_hypoxia_15mmhg_mechanism_panel": att_panel_da_h,
    })
    c1_prereg_ac = _mk_c1_prereg(pa, ba, la, ra, att_ac)
    pr_c1_ac = {"BANK_MATERIALIZATION": mat_ac["receipt_sha256"], "DRUG_FREE_EXPOSURE": df_ac["receipt_sha256"]}
    c1_ac = _sign_receipt({**c1_y, "product_id": pa, "bank_id": ba, "lot_id": la, "route_id": ra, "parent_receipt_sha256": att_ac["receipt_sha256"], "prerequisite_receipt_sha256s": {**pr_c1_ac, "C-1-PREREGISTRATION": c1_prereg_ac["receipt_sha256"]}, "c1_common_family_acquisition_record": _mk_c1_common_acq(c1_norm_6, c1_hyp_6, c1_prereg_ac, acq_id="C1-COMMON-ACQ-A"), "c1_normoxia": _mk_c1_with_kd_lot(c1_norm_6, la, pa), "c1_hypoxia_2pct_o2": _mk_c1_with_kd_lot(c1_hyp_6, la, pa)})
    c2_ac = _sign_receipt({**c2_y, "product_id": pa, "bank_id": ba, "lot_id": la, "route_id": ra, "specimen_id": f"SPEC-C-2-{la}", "parent_receipt_sha256": c1_ac["receipt_sha256"], "prerequisite_receipt_sha256s": pr_c1_ac, "basal_shield_retention_by_component": _mk_r8_shields(pa, 93.0), "hour0_density_by_lineage": _mk_r8_hour0(pa), "soluble_iapp_matched_ctrl_assay": _mk_c2_sol_iapp(spec_v=f"SPEC-C-2-{la}", lot_v=la, nt_v=nt_y), "resting_survival_protein_panel": _mk_c2_surv_panel(spec_v=f"SPEC-C-2-{la}", lot_v=la, nt_v=nt_y), "c2_per_lot_proliferation_records": [_mk_c2_prolif_lot(1, active_lot=la, prod_v=pa), _mk_c2_prolif_lot(2, prod_v=pa), _mk_c2_prolif_lot(3, prod_v=pa)], "transient_target_engagement_record": _mk_c_eng(c1_cohort_y, "2026-09-25T08:00:00Z", stage_name="C-2", lot_s_id=la, win_start="2026-09-22T08:00:00Z", win_end="2026-09-25T09:00:00Z")})
    sw_ac = _mk_r8_switch(pa, ba, la, ra, mat_ac, "2026-09-28T14:00:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": c2_ac["receipt_sha256"]}, transient_engagement=_mk_c_eng(c1_cohort_y, "2026-09-28T13:00:00Z", stage_name="NATIVE_SAFETY_SWITCH", lot_s_id=la, win_start="2026-09-25T12:00:00Z", win_end="2026-09-28T13:15:00Z", mode="VALIDATED_LONGITUDINAL_KINETICS"))
    g0v_ac = _mk_r8_gate0v(pa, ba, la, ra, mat_ac, "2026-09-28T14:30:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": c2_ac["receipt_sha256"]}, transient_engagement=_mk_c_eng(c1_cohort_y, "2026-09-28T13:15:00Z", stage_name="GATE-0V-KILL", lot_s_id=la, win_start="2026-09-25T12:00:00Z", win_end="2026-09-28T13:30:00Z", mode="VALIDATED_LONGITUDINAL_KINETICS"))
    pr_c3_ac = {**pr_c1_ac, "NATIVE_SAFETY_SWITCH": sw_ac["receipt_sha256"], "GATE-0V-KILL": g0v_ac["receipt_sha256"]}
    c3n_ac = _sign_receipt({**c3_nk_y, "product_id": pa, "bank_id": ba, "lot_id": la, "route_id": ra, "specimen_id": f"SPEC-C-3-NK-{la}", "parent_receipt_sha256": c2_ac["receipt_sha256"], "prerequisite_receipt_sha256s": pr_c3_ac, "transient_target_engagement_record": _mk_c_eng(c1_cohort_y, "2026-09-30T09:00:00Z", stage_name="C-3-NK", lot_s_id=la, win_start="2026-09-28T15:00:00Z", win_end="2026-09-30T11:00:00Z"), "readout3b_evidence": _mk_r8_readout3b(include_sirpa_low=True, specimen_id=f"SPEC-C-3-NK-{la}", specimen_lot_id=la, intervention_cohort_id=c1_cohort_y)})
    c3g_ac = _sign_receipt({**c3_gsis_y, "product_id": pa, "bank_id": ba, "lot_id": la, "route_id": ra, "specimen_id": f"SPEC-C-3-GSIS-{la}", "parent_receipt_sha256": c3n_ac["receipt_sha256"], "prerequisite_receipt_sha256s": pr_c3_ac, "transient_target_engagement_record": _mk_c_eng(c1_cohort_y, "2026-10-01T16:00:00Z", stage_name="C-3-GSIS", lot_s_id=la, win_start="2026-09-30T13:00:00Z", win_end="2026-10-01T18:00:00Z"), "readout2_evidence": _mk_r8_readout2(matched_comparator_id=nt_y, block_prefix="C3GA", lot_id=la, stage7_start_utc="2026-09-12T00:00:00Z", sort_reaggregation_utc="2026-09-22T00:00:00Z", assay_harvest_utc="2026-10-01T00:00:00Z", specimen_id=f"SPEC-C-3-GSIS-{la}", intervention_cohort_id=c1_cohort_y, candidate_gene=tg_dual)})
    g42_a = {"target_arm": "A", "product_id": pa, "bank_id": ba, "lot_id": la, "route_id": ra, "drug_free_exposure_evidence": df_ac, "materialization_evidence": mat_ac, "native_switch_evidence": sw_ac, "gate0v_evidence": g0v_ac, "zero_fasta_minted": True, "iip0049_foundry_attribution_evidence": att_ac, "target_gene": tg_dual, "c1_preregistered_plan_receipt": c1_prereg_ac, "c1_evidence": c1_ac, "c2_evidence": c2_ac, "c3_nk_evidence": c3n_ac, "c3_gsis_evidence": c3g_ac}
    chk(evaluate_gate42_gy032_channel_c_screen(g42_a)["verdict"] == "DIAGNOSTIC_SENSITIVITY_ONLY_DESIGN_A_NON_ADVANCING", "G42_A_diag_pass")
    chk("FAIL_DESIGN_A_FORBIDS_FOUNDRY_V2_GATE36_RECEIPT" in evaluate_gate42_gy032_channel_c_screen({**g42_a, "foundry_v2_gate36_evidence": g36_y})["failures"], "G42_A_no_g36")
    chk("FAIL_EXCLUDED_CANDIDATE_BLOCKED:MAP3K7" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "target_gene": "MAP3K7"})["failures"], "G42_map3k7")
    chk("FAIL_EXCLUDED_CANDIDATE_BLOCKED:BACH2" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "target_gene": "BACH2"})["failures"], "G42_bach2")
    chk("FAIL_ZERO_FASTA_MINTED_BOUNDARY_VIOLATED" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "zero_fasta_minted": False})["failures"], "G42_zero_fasta")
    chk("FAIL_GATE42_REQUIRES_100PCT_DRUG_FREE_UNCOATED_EXPOSURE" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "drug_free_exposure_evidence": _sign_receipt({**df_y, "route_coated": True})})["failures"], "G42_drug_free")
    chk("FAIL_NO_RESIDUAL_APOPTOSIS_ON_MATCHED_BACKGROUND" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _sign_receipt({**att_y, "stage2_il1_independent_apoptosis_persists": False})})["failures"], "G42_no_res")
    chk("FAIL_INTERVENTION_CANDIDATE_MISMATCH:NATIVE_SAFETY_SWITCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "native_switch_evidence": _mk_r8_switch(py, by, ly, ry, mat_yc, "2026-09-26T09:00:00Z", candidate_gene="BCL2L11", comparator_nt_lot_id=nt_y)})["failures"], "G42_sw_gene_mm")
    chk("FAIL_COMPARATOR_NT_LOT_MISMATCH:GATE-0V-KILL" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "gate0v_evidence": _mk_r8_gate0v(py, by, ly, ry, mat_yc, "2026-09-26T09:30:00Z", candidate_gene=tg_dual, comparator_nt_lot_id="OTHER-NT")})["failures"], "G42_g0v_nt_mm")
    chk("FAIL_GATE_C1_EXACT_SIGN_FLIP_REQUIRES_AT_LEAST_10_BLOCKS_FOR_HOLM5" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "statistical_test_method": "EXACT_TWO_SIDED_SIGN_FLIP"})})["failures"], "G42_sf_lt10")
    chk("FAIL_GATE_C1_UNDERPOWERED_BLOCKS_LT_3" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "biological_blocks_n": 2})})["failures"], "G42_blk_lt3")
    chk("FAIL_GATE_C1_MISSING_HOLM_BONFERRONI_5_ARM_MULTIPLICITY" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "multiplicity_method": "UNADJUSTED"})})["failures"], "G42_mult")
    chk("FAIL_GATE_C1_DUPLICATE_ASSAY_RECORD_ID_ACROSS_OXYGEN_REGIMES" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_hypoxia_2pct_o2": {**c1_hyp_6, "assay_record_id": "C1-NORM-Y-01"}})})["failures"], "G42_dup_aid")
    chk("FAIL_GATE_C1_NORMOXIA_PMLKL_GY016_ORTHOGONAL_DIVERSION_REQUIRED" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "pmlkl_flag_triggered": True, "gy016_nec1s_gsk872_orthogonal_rescue_cleared": False}})})["failures"], "G42_pmlkl")
    chk("FAIL_GATE_C1_NORMOXIA_NONBETA_LINEAGE_DAMAGE" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "nonbeta_lineage_min_surv_pct_ctrl": 80.0}})})["failures"], "G42_nonbeta")
    chk("FAIL_GATE_C1_NORMOXIA_STRESSED_CONTROL_ASSAY_VALIDITY_FLOOR" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "stressed_ctrl_nonbeta_t0_survival_pct": 35.0}})})["failures"], "G42_ctrl_floor")
    chk("FAIL_GATE_C1_NORMOXIA_MISSING_T0_DENOMINATOR_RULE" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "t0_original_plated_denominators_used": False}})})["failures"], "G42_t0_denom")
    chk("FAIL_GATE_C2_BASAL_SHIELD_BELOW_85PCT" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "basal_shield_retention_pct": 75.0})})["failures"], "G42_c2_sh")
    chk("FAIL_GATE_C2_GRANULE_PROCESSING_DEGRADED" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "granule_processing_preserved": False})})["failures"], "G42_c2_gran")
    chk("FAIL_GATE_C2_IAPP_AMYLOID_RATIO_EXCEEDS_1P15" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "iapp_amyloid_ratio_vs_ctrl": 1.3})})["failures"], "G42_c2_iapp")
    chk("FAIL_GATE_C2_SOLUBLE_IAPP_MEASUREMENT_MISSING" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "soluble_iapp_pg_per_ieq": None})})["failures"], "G42_c2_sol_iapp")
    chk("FAIL_GATE_C1_NORMOXIA_DUAL_TARGET_COMPONENT_KD_FAILED" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "pmaip1_kd_pct": 55.0}})})["failures"], "G42_dual_kd")
    chk("FAIL_GATE_C1_NORMOXIA_KD_BELOW_70PCT" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "target_kd_pct": 60.0}})})["failures"], "G42_kd_lt70")
    chk("FAIL_GATE_C1_NORMOXIA_JAK2_HYPOMORPH_RANGE_50_65" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "target_gene": "JAK2", "c1_evidence": _sign_receipt({**c1_y, "candidate_gene": "JAK2", "c1_normoxia": _mk_r8_c1_block(assay_record_id="C1-JK2", bids=["B1","B2","B3","B4","B5","B6"], c9_vec=[51.0,55.0,49.0,54.0,52.0,56.0], ctrl_vec=[54.0,52.0,56.0,55.0,53.0,54.0], tr_vec=[76.0,75.0,79.0,77.0,74.0,78.0], veh_vec=[90.0]*6, comp_vec=[71.0]*6, target="JAK2", target_kd=85.0, jak2_shield_pct=92.0)})})["failures"], "G42_jak2_kd")
    chk("HOLD_GATE_C3_GSIS_MISSING" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c3_gsis_evidence": None})["holds"], "G42_c3g_hold")
    chk("HOLD_GATE_C3_NK_MISSING" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c3_nk_evidence": None})["holds"], "G42_c3n_hold")
    chk("HOLD_FOUNDRY_V2_GATE36_RECEIPT_MISSING" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "foundry_v2_gate36_evidence": None})["holds"], "G42_g36_hold")
    chk("HOLD_IIP0049_STAGE1_STAGE2_ATTRIBUTION_MISSING" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": None})["holds"], "G42_att_hold")
    chk("FAIL_MATCHED_FOUNDRY_V2_BACKGROUND_NOT_VERIFIED" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _sign_receipt({**att_y, "background_class": "UNMODIFIED_DESIGN_A_REFERENCE"})})["failures"], "G42_bg_mm")
    chk("FAIL_IIP0049_IDENTICAL_COPY_PASTE_NORMOXIA_HYPOXIA_ATTRIBUTION" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _sign_receipt({**att_y, "stage2_hypoxia_15mmhg_mechanism_panel": att_panel_norm})})["failures"], "G42_att_cp")
    chk("FAIL_GATE_C1_MISSING_SHARED_STUDY_ID" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "shared_study_id": ""})})["failures"], "G42_no_study_id")
    chk("FAIL_GATE42_UNKNOWN_OR_UNRECONCILED_FIELDS:rogue_c" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "rogue_c": 1})["failures"], "G42_unknown_key")
    # Descriptive pilot n=3 non-advancing check
    c1_n3 = _mk_r8_c1_block(assay_record_id="C1-P3-N", bids=["P1","P2","P3"], c9_vec=[50.0,54.0,52.0], ctrl_vec=[52.0,50.0,54.0], tr_vec=[74.0,73.0,77.0], veh_vec=[90.0,89.0,91.0], comp_vec=[68.0,67.0,70.5])
    c1_h3 = _mk_r8_c1_block(assay_record_id="C1-P3-H", bids=["Q1","Q2","Q3"], c9_vec=[48.0,51.0,49.0], ctrl_vec=[49.0,48.0,51.0], tr_vec=[71.0,70.0,73.0], veh_vec=[87.0,86.0,88.0], comp_vec=[65.0,64.5,67.2], batch_prefix="C1-HBAT")
    c1_prereg_p3 = _mk_c1_prereg(py, by, ly, ry, att_y, n_b=3, norm_bids=["P1", "P2", "P3"], hyp_bids=["Q1", "Q2", "Q3"])
    c1_p3 = _sign_receipt({**c1_y, "prerequisite_receipt_sha256s": {**pr_c1_yc, "C-1-PREREGISTRATION": c1_prereg_p3["receipt_sha256"]}, "biological_blocks_n": 3, "c1_normoxia": c1_n3, "c1_hypoxia_2pct_o2": c1_h3})
    c2_p3 = _sign_receipt({**c2_y, "parent_receipt_sha256": c1_p3["receipt_sha256"]})
    sw_p3 = _mk_r8_switch(py, by, ly, ry, mat_yc, "2026-09-28T14:00:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": c2_p3["receipt_sha256"]}, transient_engagement=_mk_c_eng(c1_cohort_y, "2026-09-28T13:00:00Z", stage_name="NATIVE_SAFETY_SWITCH", lot_s_id=ly, win_start="2026-09-25T12:00:00Z", win_end="2026-09-28T13:15:00Z", mode="VALIDATED_LONGITUDINAL_KINETICS"))
    g0v_p3 = _mk_r8_gate0v(py, by, ly, ry, mat_yc, "2026-09-28T14:30:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": c2_p3["receipt_sha256"]}, transient_engagement=_mk_c_eng(c1_cohort_y, "2026-09-28T13:15:00Z", stage_name="GATE-0V-KILL", lot_s_id=ly, win_start="2026-09-25T12:00:00Z", win_end="2026-09-28T13:30:00Z", mode="VALIDATED_LONGITUDINAL_KINETICS"))
    pr_c3_p3 = {**pr_c1_yc, "NATIVE_SAFETY_SWITCH": sw_p3["receipt_sha256"], "GATE-0V-KILL": g0v_p3["receipt_sha256"]}
    c3n_p3 = _sign_receipt({**c3_nk_y, "parent_receipt_sha256": c2_p3["receipt_sha256"], "prerequisite_receipt_sha256s": pr_c3_p3})
    c3g_p3 = _sign_receipt({**c3_gsis_y, "parent_receipt_sha256": c3n_p3["receipt_sha256"], "prerequisite_receipt_sha256s": pr_c3_p3})
    chk(evaluate_gate42_gy032_channel_c_screen({**g42_ok, "native_switch_evidence": sw_p3, "gate0v_evidence": g0v_p3, "c1_preregistered_plan_receipt": c1_prereg_p3, "c1_evidence": c1_p3, "c2_evidence": c2_p3, "c3_nk_evidence": c3n_p3, "c3_gsis_evidence": c3g_p3})["verdict"] == "DESCRIPTIVE_PILOT_ONLY_NON_ADVANCING", "G42_pilot3_non_adv")
    # Autologous Design D with canonical AUTOLOGOUS tier in Gate 0V passes cleanly!
    mat_d = _mk_r8_mat(pd_, bd_, ld_, "2026-09-10T08:00:00Z")
    df_d = _sign_receipt({**df_y, "product_id": pd_, "bank_id": bd_, "lot_id": ld_, "route_id": rd_, "parent_receipt_sha256": mat_d["receipt_sha256"]})
    g32_d = _sign_receipt({**g32_y, "product_id": pd_, "bank_id": bd_, "lot_id": ld_, "route_id": rd_, "parent_receipt_sha256": mat_d["receipt_sha256"]})
    g36_d = _sign_receipt({**g36_y, "product_id": pd_, "bank_id": bd_, "lot_id": ld_, "route_id": rd_, "parent_receipt_sha256": mat_d["receipt_sha256"], "prerequisite_receipt_sha256s": {"DRUG_FREE_EXPOSURE": df_d["receipt_sha256"]}, "live_gate32_debris_recall_receipt": g32_d})
    att_d = _sign_receipt({**att_y, "product_id": pd_, "bank_id": bd_, "lot_id": ld_, "route_id": rd_, "foundry_v2_gate36_receipt_sha256": g36_d["receipt_sha256"], "prerequisite_receipt_sha256s": {"BANK_MATERIALIZATION": mat_d["receipt_sha256"], "DRUG_FREE_EXPOSURE": df_d["receipt_sha256"], "GATE-36-FOUNDRY-V2": g36_d["receipt_sha256"]}})
    c1_prereg_d = _mk_c1_prereg(pd_, bd_, ld_, rd_, att_d)
    pr_c1_d = {"BANK_MATERIALIZATION": mat_d["receipt_sha256"], "DRUG_FREE_EXPOSURE": df_d["receipt_sha256"]}
    c1_d = _sign_receipt({**c1_y, "product_id": pd_, "bank_id": bd_, "lot_id": ld_, "route_id": rd_, "parent_receipt_sha256": att_d["receipt_sha256"], "prerequisite_receipt_sha256s": {**pr_c1_d, "C-1-PREREGISTRATION": c1_prereg_d["receipt_sha256"]}, "c1_common_family_acquisition_record": _mk_c1_common_acq(c1_norm_6, c1_hyp_6, c1_prereg_d, acq_id="C1-COMMON-ACQ-D"), "c1_normoxia": _mk_c1_with_kd_lot(c1_norm_6, ld_, pd_), "c1_hypoxia_2pct_o2": _mk_c1_with_kd_lot(c1_hyp_6, ld_, pd_)})
    c2_d = _sign_receipt({**c2_y, "product_id": pd_, "bank_id": bd_, "lot_id": ld_, "route_id": rd_, "specimen_id": f"SPEC-C-2-{ld_}", "parent_receipt_sha256": c1_d["receipt_sha256"], "prerequisite_receipt_sha256s": pr_c1_d, "basal_shield_retention_by_component": _mk_r8_shields(pd_, 93.0), "hour0_density_by_lineage": _mk_r8_hour0(pd_), "soluble_iapp_matched_ctrl_assay": _mk_c2_sol_iapp(spec_v=f"SPEC-C-2-{ld_}", lot_v=ld_, nt_v=nt_y), "resting_survival_protein_panel": _mk_c2_surv_panel(spec_v=f"SPEC-C-2-{ld_}", lot_v=ld_, nt_v=nt_y), "c2_per_lot_proliferation_records": [_mk_c2_prolif_lot(1, active_lot=ld_, prod_v=pd_), _mk_c2_prolif_lot(2, prod_v=pd_), _mk_c2_prolif_lot(3, prod_v=pd_)], "transient_target_engagement_record": _mk_c_eng(c1_cohort_y, "2026-09-25T08:00:00Z", stage_name="C-2", lot_s_id=ld_, win_start="2026-09-22T08:00:00Z", win_end="2026-09-25T09:00:00Z")})
    sw_d = _mk_r8_switch(pd_, bd_, ld_, rd_, mat_d, "2026-09-28T14:00:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": c2_d["receipt_sha256"]}, transient_engagement=_mk_c_eng(c1_cohort_y, "2026-09-28T13:00:00Z", stage_name="NATIVE_SAFETY_SWITCH", lot_s_id=ld_, win_start="2026-09-25T12:00:00Z", win_end="2026-09-28T13:15:00Z", mode="VALIDATED_LONGITUDINAL_KINETICS"))
    g0v_d = _mk_r8_gate0v(pd_, bd_, ld_, rd_, mat_d, "2026-09-28T14:30:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": c2_d["receipt_sha256"]}, transient_engagement=_mk_c_eng(c1_cohort_y, "2026-09-28T13:15:00Z", stage_name="GATE-0V-KILL", lot_s_id=ld_, win_start="2026-09-25T12:00:00Z", win_end="2026-09-28T13:30:00Z", mode="VALIDATED_LONGITUDINAL_KINETICS"))
    pr_c3_d = {**pr_c1_d, "NATIVE_SAFETY_SWITCH": sw_d["receipt_sha256"], "GATE-0V-KILL": g0v_d["receipt_sha256"]}
    c3n_d = _sign_receipt({**c3_nk_y, "product_id": pd_, "bank_id": bd_, "lot_id": ld_, "route_id": rd_, "specimen_id": f"SPEC-C-3-NK-{ld_}", "parent_receipt_sha256": c2_d["receipt_sha256"], "prerequisite_receipt_sha256s": pr_c3_d, "transient_target_engagement_record": _mk_c_eng(c1_cohort_y, "2026-09-30T09:00:00Z", stage_name="C-3-NK", lot_s_id=ld_, win_start="2026-09-28T15:00:00Z", win_end="2026-09-30T11:00:00Z"), "readout3b_evidence": _mk_r8_readout3b(include_sirpa_low=True, include_hla_e_spr=False, specimen_id=f"SPEC-C-3-NK-{ld_}", specimen_lot_id=ld_, intervention_cohort_id=c1_cohort_y)})
    c3g_d = _sign_receipt({**c3_gsis_y, "product_id": pd_, "bank_id": bd_, "lot_id": ld_, "route_id": rd_, "specimen_id": f"SPEC-C-3-GSIS-{ld_}", "parent_receipt_sha256": c3n_d["receipt_sha256"], "prerequisite_receipt_sha256s": pr_c3_d, "transient_target_engagement_record": _mk_c_eng(c1_cohort_y, "2026-10-01T16:00:00Z", stage_name="C-3-GSIS", lot_s_id=ld_, win_start="2026-09-30T13:00:00Z", win_end="2026-10-01T18:00:00Z"), "readout2_evidence": _mk_r8_readout2(matched_comparator_id=nt_y, block_prefix="C3GD", lot_id=ld_, stage7_start_utc="2026-09-12T00:00:00Z", sort_reaggregation_utc="2026-09-22T00:00:00Z", assay_harvest_utc="2026-10-01T00:00:00Z", specimen_id=f"SPEC-C-3-GSIS-{ld_}", intervention_cohort_id=c1_cohort_y, candidate_gene=tg_dual)})
    g42_d = {"target_arm": "D", "product_id": pd_, "bank_id": bd_, "lot_id": ld_, "route_id": rd_, "drug_free_exposure_evidence": df_d, "materialization_evidence": mat_d, "foundry_v2_gate36_evidence": g36_d, "native_switch_evidence": sw_d, "gate0v_evidence": g0v_d, "zero_fasta_minted": True, "iip0049_foundry_attribution_evidence": att_d, "target_gene": tg_dual, "c1_preregistered_plan_receipt": c1_prereg_d, "c1_evidence": c1_d, "c2_evidence": c2_d, "c3_nk_evidence": c3n_d, "c3_gsis_evidence": c3g_d}
    chk(evaluate_gate42_gy032_channel_c_screen(g42_d)["verdict"] == OFFLINE_VERDICT_PRIMARY, "G42_D_autologous_pass")
    # Autologous Design D given allogeneic BANK_QUALIFICATION tier -> HOLD_INAPPLICABLE_QUALIFICATION_TIER_FOR_PRODUCT_FAMILY!
    g0v_d_wrong = _mk_r8_gate0v(pd_, bd_, ld_, rd_, mat_d, "2026-09-26T09:30:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, tier_override="PASS_WHOLEGRAFT_BANK_QUALIFICATION")
    chk("HOLD_INAPPLICABLE_QUALIFICATION_TIER_FOR_PRODUCT_FAMILY" in evaluate_gate42_gy032_channel_c_screen({**g42_d, "gate0v_evidence": g0v_d_wrong})["holds"], "G42_D_wrong_g0v_tier_hold")
    chk("FAIL_GATE_C1_NORMOXIA_ACTIVE_ARM_MISMATCH_WITH_5ARM_TABLE" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "all_five_arms_paired_data": {**c1_norm_6["all_five_arms_paired_data"], tg_dual: {"treated_beta_plated_t0_by_block": [10000]*6, "treated_beta_surviving_by_block": [7000]*6, "treated_beta_t0_pct_by_block": [70.0]*6, "casp9_treated_raw_by_block": c1_norm_6["casp9_treated_raw_by_block"], "casp9_reduction_pct_by_block": c1_norm_6["casp9_reduction_pct_by_block"]}}}})})["failures"], "G42_active_5arm_mm")
    chk("FAIL_GATE_C1_NORMOXIA_MISSING_ALL_5_SIBLING_ARM_RAW_VECTORS" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "all_five_arms_paired_data": None}})})["failures"], "G42_missing_5arms")
    chk("FAIL_GATE_C1_NORMOXIA_NONPOSITIVE_NET_BETA_RESCUE" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": _mk_r8_c1_block(assay_record_id="C1-NEG", bids=["B1","B2","B3","B4","B5","B6"], c9_vec=[51.0,55.0,49.0,54.0,52.0,56.0], ctrl_vec=[54.0,52.0,56.0,55.0,53.0,54.0], tr_vec=[50.0,49.0,52.0,51.0,50.0,51.0], veh_vec=[90.0]*6, comp_vec=[48.0,47.5,50.0,49.5,48.0,49.0])})})["failures"], "G42_neg_rescue")
    chk("FAIL_GATE_C1_NORMOXIA_HOLM5_ADJUSTED_PVALUE_MISMATCH_BETA" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "holm_adjusted_beta_p_value": 0.000001}})})["failures"], "G42_holm_tamper")
    chk("FAIL_GATE_C1_UNDECLARED_STATISTICAL_METHOD" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "statistical_test_method": "WILCOXON"})})["failures"], "G42_stat_method")
    chk("FAIL_IIP0049_STAGE1_WINDOW_NOT_POSITIVE" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _sign_receipt({**att_y, "stage1_cytokine_window_positive": False})})["failures"], "G42_s1_neg")
    chk("FAIL_IIP0049_T0_DENOMINATORS_MISSING" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _sign_receipt({**att_y, "t0_original_plated_denominators_used": False})})["failures"], "G42_att_t0")
    chk("FAIL_IIP0049_CONCURRENT_CONTROLS_INVALID" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _sign_receipt({**att_y, "concurrent_controls_valid": False})})["failures"], "G42_att_ctrl")
    chk("FAIL_UNRECOGNIZED_TARGET_GENE" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "target_gene": "TP53"})["failures"], "G42_bad_gene")
    chk("FAIL_DESIGN_A_DIAGNOSTIC_MUST_USE_UNCOATED_R1" in evaluate_gate42_gy032_channel_c_screen({**g42_a, "route_id": "R2"})["failures"], "G42_A_not_r1")
    chk("FAIL_GATE_C2_REQUIRES_AT_LEAST_3_PER_LOT_PROLIFERATION_RECORDS" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "c2_per_lot_proliferation_records": c2_prolif_ok[:2]})})["failures"], "G42_c2_lt3")
    chk("FAIL_FOUNDRY_V2_GATE36_NOT_PASSED" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "foundry_v2_gate36_evidence": _sign_receipt({**g36_y, "canonical_gate36_verdict": "HOLD"})})["failures"], "G42_g36_not_pass")
    chk("FAIL_FOUNDRY_V2_GATE36_EXPOSURE_UNVERIFIED" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "foundry_v2_gate36_evidence": _sign_receipt({**g36_y, "matched_foundry_exposure_verified": False})})["failures"], "G42_g36_exp")
    chk("FAIL_CHRONOLOGICAL_PREREQ_POSTDATES_STAGE:GATE-32_AFTER_GATE-36" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "foundry_v2_gate36_evidence": _sign_receipt({**g36_y, "live_gate32_debris_recall_receipt": _sign_receipt({**g32_y, "recorded_at_utc": "2026-09-14T08:00:00Z"})})})["failures"], "G42_g32_after_g36")
    chk("FAIL_GATE_C1_NORMOXIA_BCL2L11_COMPARATOR_MISMATCH_WITH_5ARM_TABLE" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "bcl2l11_comparator_beta_t0_pct_by_block": [69.0,68.0,71.0,70.0,68.0,70.0]}})})["failures"], "G42_bcl2l11_5arm_mm")
    chk("FAIL_GATE_C1_NORMOXIA_CASP9_OUT_OF_DOMAIN_NEG100_100" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "casp9_reduction_pct_by_block": [-120.0,55.0,49.0,54.0,52.0,56.0]}})})["failures"], "G42_c9_lt_neg100")
    chk("FAIL_GATE_C1_IDENTICAL_COPY_PASTE_CASP9_ACROSS_OXYGEN_REGIMES" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_hypoxia_2pct_o2": {**c1_hyp_6, "casp9_reduction_pct_by_block": c1_norm_6["casp9_reduction_pct_by_block"]}})})["failures"], "G42_c9_cp")
    chk("FAIL_GATE_C2_PROLIF_DUPLICATE_OR_EMPTY_LOT_ID" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "c2_per_lot_proliferation_records": [_mk_c2_prolif_lot(1), _mk_c2_prolif_lot(1, resting_assay_record_id="R2", post_recovery_assay_record_id="P2"), _mk_c2_prolif_lot(3)]})})["failures"], "G42_c2_dup_lot")
    chk("FAIL_IIP0049_ATTRIBUTION_BLOCKS_LT_3" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _sign_receipt({**att_y, "biological_blocks_n": 2})})["failures"], "G42_att_lt3")
    chk("FAIL_IIP0049_STAGE1_CYTOKINE_DROP_BELOW_10PP" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _sign_receipt({**att_y, "stage1_cytokine_drop_pp": 5.0})})["failures"], "G42_s1_lt10")
    chk("FAIL_IIP0049_RESIDUAL_DROP_BELOW_10PP_OR_OUT_OF_DOMAIN" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _sign_receipt({**att_y, "residual_viable_beta_drop_pp": 6.0})})["failures"], "G42_res_lt10")
    chk("FAIL_FOUNDRY_V2_GATE36_RECEIPT_DIGEST_MISMATCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _sign_receipt({**att_y, "foundry_v2_gate36_receipt_sha256": "9" * 64})})["failures"], "G42_g36_sha_mm")
    chk("FAIL_GATE_C1_NORMOXIA_MISSING_ASSAY_RECORD_ID" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "assay_record_id": ""}})})["failures"], "G42_no_aid")
    chk("FAIL_GATE_C1_NORMOXIA_INVALID_OR_DUPLICATE_BLOCK_IDS" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "block_ids": ["B1","B1","B3","B4","B5","B6"]}})})["failures"], "G42_dup_bid")
    chk("FAIL_GATE_C1_NORMOXIA_MISSING_PMLKL_BOOL" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "pmlkl_flag_triggered": "no"}})})["failures"], "G42_pmlkl_bool")
    chk("FAIL_NATIVE_SAFETY_SWITCH_GATE34_NOT_PASSED" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "native_switch_evidence": _sign_receipt({**sw_y_c, "gate34_passed": False})})["failures"], "G42_sw_g34")
    chk("FAIL_GATE0V_EXPOSED_PRODUCT_NOT_TESTED" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "gate0v_evidence": _sign_receipt({**g0v_y_c, "exposed_product_tested": False})})["failures"], "G42_g0v_exp")

    # ========================================================================
    # GATE-43 (80 tests: 70 prior + 10 adversarial closures)
    # ========================================================================
    def _mk_d1_unified(base_d: Mapping[str, Any], **ov: Any) -> dict[str, Any]:
        body: dict[str, Any] = {
            "lot_id": "D1-LOT-001", "plate_id": "D1-PLATE-01", "sibling_aliquot_pair_id": "D1-SIBPAIR-01",
            "arm_a_exposure_start_utc": "2026-10-02T12:00:00Z", "arm_a_exposure_end_utc": "2026-10-03T12:00:00Z",
            "arm_b_exposure_start_utc": "2026-10-02T12:05:00Z", "arm_b_exposure_end_utc": "2026-10-03T12:05:00Z",
            "assay_acquired_at_utc": "2026-10-03T14:00:00Z", "recorded_at_utc": "2026-10-04T09:00:00Z",
            "arm_a_washes": base_d["check_d1_arm_a_washes"], "arm_b_washes": base_d["check_d1_arm_b_washes"],
            "starting_zm_regimen": base_d["check_d1_starting_zm_regimen"],
            "both_arms_matched_24h_nac": base_d["check_d1_both_arms_matched_24h_nac"],
            "zm447439_lloq_uM": base_d["check_d1_zm447439_lloq_uM"],
            "arm_a_zm447439_lcms_uM": base_d["check_d1_arm_a_zm447439_lcms_uM"],
            "arm_b_zm447439_lcms_uM": base_d["check_d1_arm_b_zm447439_lcms_uM"],
            "arm_a_spike_recovery_pct": base_d["check_d1_arm_a_spike_recovery_pct"],
            "arm_b_spike_recovery_pct": base_d["check_d1_arm_b_spike_recovery_pct"],
            "t3_lloq_nM": base_d["check_d1_t3_lloq_nM"],
            "residual_t3_arm_a_nM": base_d["check_d1_residual_t3_arm_a_nM"],
            "residual_t3_arm_b_nM": base_d["check_d1_residual_t3_arm_b_nM"],
            "arm_b_below_lloq": base_d["check_d1_arm_b_below_lloq"],
            "arm_a_chemistry_sample": {
                "sample_id": "D1-CHEM-A-001", "sibling_aliquot_pair_id": "D1-SIBPAIR-01",
                "collected_at_utc": "2026-10-03T12:00:00Z", "instrument_record_sha256": "1" * 64,
                "instrument_row_or_injection_id": "INJ-A-01",
            },
            "arm_b_chemistry_sample": {
                "sample_id": "D1-CHEM-B-001", "sibling_aliquot_pair_id": "D1-SIBPAIR-01",
                "collected_at_utc": "2026-10-03T12:05:00Z", "instrument_record_sha256": "2" * 64,
                "instrument_row_or_injection_id": "INJ-B-01",
            },
            "pre_coassembly_vascular_function_pass": base_d["check_d1_pre_coassembly_vascular_function_pass"],
            "paired_gsis_record_sha256": base_d["check_d1_paired_gsis_record"]["record_sha256"],
            "paired_facs_record_sha256": base_d["check_d1_paired_facs_record"]["record_sha256"],
            "vascular_adhesion_sprouting_record_sha256": base_d["check_d1_vascular_adhesion_sprouting_record"]["record_sha256"],
        }
        body.update(ov)
        return _sign_receipt(body)

    g43_base = {
        "evidence_tier": "cellgemma_e4b_in_silico_prior",
        "live_odds_delta_pp": 0.0, "prospective_odds_delta_pp": 0.0, "graveyard_severity": "WARN",
        "check_d1_claims_adoption_authority": False,
        "check_d1_arm_a_washes": 3, "check_d1_arm_b_washes": 3,
        "check_d1_starting_zm_regimen": "S7W0_ONLY_0UM_POST_SORT",
        "check_d1_zm447439_lloq_uM": 0.005, "check_d1_arm_a_zm447439_lcms_uM": 0.002,
        "check_d1_arm_b_zm447439_lcms_uM": 0.002, "check_d1_arm_a_spike_recovery_pct": 95.0,
        "check_d1_arm_b_spike_recovery_pct": 97.0, "check_d1_both_arms_matched_24h_nac": True,
        "check_d1_t3_lloq_nM": 0.20, "check_d1_residual_t3_arm_a_nM": 9.6,
        "check_d1_residual_t3_arm_b_nM": None, "check_d1_arm_b_below_lloq": True,
        "check_d1_pre_coassembly_vascular_function_pass": True,
        "check_d1_paired_gsis_40_100mmhg_recorded": True, "check_d1_paired_icam1_vcam1_facs_recorded": True,
        "check_d1_paired_gsis_record": (lambda _b: {**_b, "record_sha256": sha256_bytes(canonical_json_bytes(_b))})({
            "lot_id": "D1-LOT-001", "plate_id": "D1-PLATE-01", "sibling_aliquot_pair_id": "D1-SIBPAIR-01",
            "arm_a_acquired_at_utc": "2026-10-03T12:30:00Z", "arm_b_acquired_at_utc": "2026-10-03T12:35:00Z",
            "insulin_normalization_basis": "PER_IEQ_PER_HOUR", "raw_trace_sha256": "6" * 64,
            "arm_a_basal_40": 0.40, "arm_a_stim_40": 1.68, "arm_b_basal_40": 0.40, "arm_b_stim_40": 1.64,
            "arm_a_basal_100": 0.45, "arm_a_stim_100": 2.16, "arm_b_basal_100": 0.45, "arm_b_stim_100": 2.115,
            "arm_a_si_40": 4.2, "arm_b_si_40": 4.1, "arm_a_si_100": 4.8, "arm_b_si_100": 4.7,
        }),
        "check_d1_paired_facs_record": (lambda _b: {**_b, "record_sha256": sha256_bytes(canonical_json_bytes(_b))})({
            "lot_id": "D1-LOT-001", "plate_id": "D1-PLATE-01", "sibling_aliquot_pair_id": "D1-SIBPAIR-01",
            "arm_a_acquired_at_utc": "2026-10-03T12:45:00Z", "arm_b_acquired_at_utc": "2026-10-03T12:50:00Z",
            "icam1_mfi_ratio_b_over_a": 0.94, "vcam1_mfi_ratio_b_over_a": 0.96,
        }),
        "check_d1_vascular_adhesion_sprouting_record": (lambda _b: {**_b, "record_sha256": sha256_bytes(canonical_json_bytes(_b))})({
            "lot_id": "D1-LOT-001", "plate_id": "D1-PLATE-01", "sibling_aliquot_pair_id": "D1-SIBPAIR-01",
            "arm_a_acquired_at_utc": "2026-10-03T13:15:00Z", "arm_b_acquired_at_utc": "2026-10-03T13:20:00Z",
            "neutrophil_adhesion_ratio_b_over_a": 0.92, "iec_sprouting_pct_ctrl": 95.0,
        }),
        "check_d2_status": "NOT_APPLICABLE",
        "check_d3_c3_explicitly_untested": True,
        "check_d3a_status": "NOT_ATTEMPTED", "check_d3b_status": "NOT_ATTEMPTED",
    }
    g43_base["check_d1_paired_assay_receipt"] = _mk_d1_unified(g43_base)
    r43 = evaluate_gate43_cellgemma_guardrails_and_pilots(g43_base)
    chk(r43["verdict"] == "PASS_DESCRIPTIVE_PILOT_ZERO_ODDS_GY037_WARN_RETAINED" and r43["gy037_warn_retained"] is True and r43["gy037_revocation_eligible"] is False and r43["adoption_authority"] is False, "G43_pass_base")

    def _mk_d2_lot(i: int, *, ki67: float = 0.99, edu: float = 0.98, ref: bool = False, mctrl_override: Optional[str] = None, block_prefix_override: Optional[str] = None, meas_override: Optional[str] = None, **ov: Any) -> dict[str, Any]:
        lid = f"D2-LOT-{i}"
        mctrl = mctrl_override or f"CTRL-LOT-{i}"
        r2_rcpt_body: dict[str, Any] = {
            "stage": "READOUT_2_CHALLENGER", "verdict": "PASS",
            "product_id": py, "bank_id": by, "lot_id": lid, "evidence_scope": "exact_product",
            "recorded_at_utc": f"2026-10-2{4+i}T10:00:00Z",
            "candidate_gene": "ICAM1", "comparator_nt_lot_id": mctrl,
            "readout2_evidence": _mk_r8_readout2(matched_comparator_id=mctrl, block_prefix=block_prefix_override or f"D2L{i}", meas_id=meas_override or f"MEAS-D2-LOT-{i}", lot_id=lid, lot_jitter=float(i)),
            "proinsulin_to_insulin_fold_vs_ctrl": 1.04, "basal_cleaved_casp3_fold_vs_ctrl": 1.06,
            "basal_cleaved_casp9_fold_vs_ctrl": 1.05, "bcl2l1_protein_pct_ctrl": 93.0,
            "mcl1_protein_pct_ctrl": 91.0, "cd59_protein_pct_ctrl": 95.0,
            "ki67_fold_vs_ctrl": ki67, "edu_fold_vs_ctrl": edu, "ki67_edu_referred": ref,
        }
        r2_rcpt_body.update(ov)
        return {"lot_id": lid, "matched_control_lot_id": mctrl, "readout2_receipt": _sign_receipt(r2_rcpt_body)}

    def _mk_d3a_lot(i: int, **ov: Any) -> dict[str, Any]:
        body: dict[str, Any] = {
            "source_iec_preparation_id": f"IEC-PREP-BATCH-{i:02d}",
            "lot_id": f"IEC-LOT-{i}", "comparator_nt_lot_id": f"IEC-NT-{i}", "assay_record_id": f"D3A-ASSAY-{i}",
            "paired_assay_run_id": f"D3A-PAIRED-RUN-{i:02d}",
            "raw_elisa_record_sha256": sha256_bytes(f"D3A-ELISA-{i}".encode("utf-8")),
            "raw_elisa_well_or_row_id": f"PLATE1-ROW{i:02d}", 
            "inflammatory_challenge_condition": "TNFA_IFNG_PRIMED",
            "blood_donor_id": f"HUMAN-DONOR-{i:02d}", "matched_blood_split_id": f"BLOOD-SPLIT-{i:02d}",
            "assay_acquired_at_utc": f"2026-10-0{4+i}T08:00:00Z", "recorded_at_utc": f"2026-10-0{5+i}T10:00:00Z",
            "iec_ptprc_pct": 0.0, "cd31_pecam1_pct": 95.0, "plvap_pos_pct": 91.0, "cdh5_ve_cadherin_pct": 94.0,
            "f3_kd_pct": 76.0 + 0.5 * i, "cxcl10_retention_pct": 91.0, "cd274_retention_pct": 93.0,
            "cleaved_casp3_fold": 1.05, "pos_ctrl_tat_fold": 4.2, "neg_ctrl_tat_fold": 1.05,
            "tat_assay_lloq_ng_ml": 5.0, "tat_f3_below_lloq": False,
            "chandler_tat_nt_ctrl_ng_ml": 100.0 + 3.0 * i, "chandler_tat_f3_sirna_ng_ml": 68.0 + 1.5 * i,
        }
        body.update(ov)
        return _sign_receipt(body)

    d3a_ok_lots = [_mk_d3a_lot(1), _mk_d3a_lot(2), _mk_d3a_lot(3)]
    mat_a_42 = _mk_r8_mat(pa, ba, la, "2026-10-08T08:00:00Z")
    sw_a_42 = _mk_r8_switch(pa, ba, la, ra, mat_a_42, "2026-10-12T09:00:00Z", comparator_nt_lot_id=la)
    g0v_a_42 = _mk_r8_gate0v(pa, ba, la, ra, mat_a_42, "2026-10-12T09:30:00Z", comparator_nt_lot_id=la)
    g31_a_42 = _mk_r8_gate31(pa, ba, la, mat_a_42, coating_stab=None, ts="2026-10-12T09:45:00Z")
    d3b_rcpt_a = _sign_receipt({
        "stage": "CHECK_D3B_PILOT", "verdict": "PASS",
        "product_id": pa, "bank_id": ba, "lot_id": la, "route_id": ra,
        "evidence_scope": "exact_product", "recorded_at_utc": "2026-10-15T10:00:00Z",
        "parent_receipt_sha256": mat_a_42["receipt_sha256"],
        "prerequisite_receipt_sha256s": {
            "BANK_MATERIALIZATION": mat_a_42["receipt_sha256"],
            "NATIVE_SAFETY_SWITCH": sw_a_42["receipt_sha256"],
            "GATE-0V-KILL": g0v_a_42["receipt_sha256"],
            "GATE-31": g31_a_42["receipt_sha256"],
        },
        "d3b_assay_scope": "ASSEMBLED_ROUTE_QUALIFICATION",
        "assay_acquired_at_utc": "2026-10-14T10:00:00Z", "f3_kd_pct_in_pilot": 78.5,
        "d3a_lot_receipt_sha256s": [r["receipt_sha256"] for r in d3a_ok_lots],
        "treated_lot_id": la, "nt_control_lot_id": la,
        "same_product_nt_sirna": True, "parental_attribution_included": True,
        "f3_sirna_shield_by_component": _mk_r8_shields(pa, 91.0),
        "nt_sirna_shield_by_component": _mk_r8_shields(pa, 96.0),
        "parental_shield_by_component": _mk_r8_shields(pa, 98.0),
        "hour0_density_by_lineage": _mk_r8_hour0(pa, REQUIRED_HOUR0_LINEAGES_FULL),
    })
    g43_full_a = {
        **g43_base,
        "check_d2_status": "EVALUATED", "check_d2_challenger_gene": "ICAM1",
        "check_d2_product_id": py, "check_d2_bank_id": by,
        "check_d2_per_lot_records": [_mk_d2_lot(1), _mk_d2_lot(2), _mk_d2_lot(3)],
        "check_d3a_status": "EVALUATED", "check_d3a_per_lot_records": d3a_ok_lots,
        "check_d3b_status": "EVALUATED", "d3b_assay_scope": "ASSEMBLED_ROUTE_QUALIFICATION",
        "target_arm": "A", "product_id": pa, "bank_id": ba, "lot_id": la, "route_id": ra,
        "materialization_evidence": mat_a_42, "native_switch_evidence": sw_a_42,
        "gate0v_evidence": g0v_a_42, "gate31_evidence": g31_a_42, "d3b_pilot_receipt": d3b_rcpt_a,
    }
    r42_full = evaluate_gate43_cellgemma_guardrails_and_pilots(g43_full_a)
    chk(r42_full["verdict"] == "PASS_DESCRIPTIVE_PILOT_ZERO_ODDS_GY037_WARN_RETAINED" and r42_full["gy037_revocation_eligible"] is False, "G43_pass_full_assembled_A")

    # GATE-43 closures (10 brand-new tests — INCLUDING 's decisive Gate 0V hard-stop precedence!)
    # 1. Observed 1-survivor viral escape with deff = 1.1 MUST return FAIL (NOT HOLD!)
    rmap_1surv = {r: {l: dict(c) for l, c in lm.items()} for r, lm in g0v_a_42["regime_by_lineage_raw_counts"].items()}
    rmap_1surv["active_persistent_cvb4"]["INS_beta"]["post_ap1903_viable_viral_pos_k"] = 1
    rmap_1surv["active_persistent_cvb4"]["INS_beta"]["treated_72h_survivors_k"] = 1
    rmap_1surv["active_persistent_cvb4"]["INS_beta"]["post_ap1903_viable_survivors_total_n"] = 1
    g0v_deff_1surv = _sign_receipt({**g0v_a_42, "clustering_design_effect_deff": 1.1, "regime_by_lineage_raw_counts": rmap_1surv})
    r_deff_1surv = evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "gate0v_evidence": g0v_deff_1surv})
    chk(r_deff_1surv["verdict"] == "FAIL" and "FAIL_GATE0V_VIRAL_ESCAPE_NONZERO:active_persistent_cvb4:INS_beta" in r_deff_1surv["failures"], "G43_ADV_g0v_deff1p1_1surv_FAILS")
    # 2. Observed 1-survivor viral escape with MISSING sampling metadata MUST return FAIL (NOT HOLD!)
    g0v_nometa_1surv = _sign_receipt({**g0v_a_42, "independent_sampling_unit_class": None, "independent_biological_units_n": None, "regime_by_lineage_raw_counts": rmap_1surv})
    r_nometa = evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "gate0v_evidence": g0v_nometa_1surv})
    chk(r_nometa["verdict"] == "FAIL" and "FAIL_GATE0V_VIRAL_ESCAPE_NONZERO:active_persistent_cvb4:INS_beta" in r_nometa["failures"], "G43_ADV_g0v_nometa_1surv_FAILS")
    # 3. Below-floor caspase (< 5x) with deff = 1.1 MUST return FAIL (NOT HOLD!)
    rmap_casp = {r: {l: dict(c) for l, c in lm.items()} for r, lm in g0v_a_42["regime_by_lineage_raw_counts"].items()}
    rmap_casp["active_persistent_hcmv"]["PLVAP_iEC"]["caspase9_3_fold_over_veh"] = 2.5
    r_casp_deff = evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "gate0v_evidence": _sign_receipt({**g0v_a_42, "clustering_design_effect_deff": 1.1, "regime_by_lineage_raw_counts": rmap_casp})})
    chk(r_casp_deff["verdict"] == "FAIL" and "FAIL_GATE0V_CASPASE_FOLD_LT_5X:active_persistent_hcmv:PLVAP_iEC" in r_casp_deff["failures"], "G43_ADV_g0v_deff1p1_casp_FAILS")
    # 4. Zero adverse findings with deff = 1.1 STILL cleanly returns HOLD (zero failures!)
    g0v_deff_clean = _sign_receipt({**g0v_a_42, "clustering_design_effect_deff": 1.1})
    d3b_deff_clean = _sign_receipt({**d3b_rcpt_a, "prerequisite_receipt_sha256s": {**d3b_rcpt_a["prerequisite_receipt_sha256s"], "GATE-0V-KILL": g0v_deff_clean["receipt_sha256"]}})
    r_clean_deff = evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "gate0v_evidence": g0v_deff_clean, "d3b_pilot_receipt": d3b_deff_clean})
    chk(r_clean_deff["verdict"] == "HOLD" and len(r_clean_deff["failures"]) == 0 and "HOLD_GATE0V_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE" in r_clean_deff["holds"], "G43_ADV_g0v_deff1p1_clean_HOLDS")
    # 5. D-2 reused Readout-2 measurement / block IDs across different wrapper lot names FAILS!
    chk("FAIL_CHECK_D2_REUSED_READOUT2_MEASUREMENT_ACROSS_LOTS:D2-LOT-2" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1), _mk_d2_lot(2, meas_override="MEAS-D2-LOT-1", block_prefix_override="D2L1"), _mk_d2_lot(3)]})["failures"], "G43_ADV_d2_reused_r2_fails")
    # 6. D-3(a) non-string lot IDs (number, None, bool) FAIL!
    chk("FAIL_CHECK_D3A_DUPLICATE_OR_EMPTY_LOT_ID" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": [_mk_d3a_lot(1, lot_id=123), _mk_d3a_lot(2, lot_id=None), _mk_d3a_lot(3, lot_id=True)]})["failures"], "G43_ADV_d3a_nonstring_lot_ids_fail")
    # 7. D-3(a) missing positive endothelial identity (CD31/PLVAP/CDH5 < floor) FAILS!
    chk("FAIL_CHECK_D3A_POSITIVE_ENDOTHELIAL_IDENTITY_BELOW_FLOOR:IEC-LOT-1" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": [_mk_d3a_lot(1, plvap_pos_pct=60.0), d3a_ok_lots[1], d3a_ok_lots[2]]})["failures"], "G43_ADV_d3a_endoth_id_fail")
    # 8. Missing check_d2_status or non-verbatim lowercase spelling FAILS!
    chk("FAIL_CHECK_D2_INVALID_STATUS" in evaluate_gate43_cellgemma_guardrails_and_pilots({k: v for k, v in g43_base.items() if k != "check_d2_status"})["failures"], "G43_ADV_missing_d2_status_fails")
    chk("FAIL_CHECK_D3A_INVALID_STATUS" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d3a_status": "not_attempted"})["failures"], "G43_ADV_nonverbatim_d3a_status_fails")
    # 9. D-3(b) mismatched d3b_assay_scope between outer field & content-hashed d3b_pilot_receipt FAILS!
    chk("FAIL_CHECK_D3B_ASSAY_SCOPE_NOT_BOUND_IN_RECEIPT_HASH" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "d3b_pilot_receipt": _sign_receipt({**d3b_rcpt_a, "d3b_assay_scope": "IEC_ONLY_NON_ASSEMBLED"})})["failures"], "G43_ADV_d3b_scope_not_bound")

    # & Core 67 GATE-43 invariants
    g43_omit_t3b = {k: v for k, v in g43_base.items() if k != "check_d1_residual_t3_arm_b_nM"}
    chk("FAIL_CHECK_D1_OMITTED_T3_ARM_B_KEY_MUST_BE_EXPLICIT_NULL" in evaluate_gate43_cellgemma_guardrails_and_pilots(g43_omit_t3b)["failures"], "G43_ADV_d1_omit_t3b")
    chk("FAIL_CHECK_D2_D2-LOT-1_READOUT2_O2_40_RECOMPUTED_CTRL_FIELLER_L95_BELOW_FLOOR" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, readout2_evidence={**_mk_r8_readout2(matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1"), "o2_40_mmhg": {"blocks": [{**b, "matched_control_z2_increment": round(b["z2_increment"]*1.4, 4), "matched_control_output_ratio": round(1/1.4, 6)} for b in _mk_r8_readout2(matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1")["o2_40_mmhg"]["blocks"]]}}), _mk_d2_lot(2), _mk_d2_lot(3)]})["failures"], "G43_ADV_d2_ctrl_ratio")
    chk("FAIL_CHECK_D2_PROINSULIN_RATIO_GT_1P15:D2-LOT-1" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, proinsulin_to_insulin_fold_vs_ctrl=1.35), _mk_d2_lot(2), _mk_d2_lot(3)]})["failures"], "G43_ADV_d2_proins")
    chk("FAIL_CHECK_D2_BASAL_CASP3_GT_1P20:D2-LOT-1" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, basal_cleaved_casp3_fold_vs_ctrl=1.40), _mk_d2_lot(2), _mk_d2_lot(3)]})["failures"], "G43_ADV_d2_casp3")
    chk("FAIL_CHECK_D2_BASAL_CASP9_GT_1P20:D2-LOT-1" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, basal_cleaved_casp9_fold_vs_ctrl=1.40), _mk_d2_lot(2), _mk_d2_lot(3)]})["failures"], "G43_ADV_d2_casp9")
    chk("FAIL_CHECK_D2_BCL2L1_PROTEIN_LT_80PCT:D2-LOT-1" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, bcl2l1_protein_pct_ctrl=70.0), _mk_d2_lot(2), _mk_d2_lot(3)]})["failures"], "G43_ADV_d2_bcl2l1")
    chk("FAIL_CHECK_D2_MCL1_PROTEIN_LT_80PCT:D2-LOT-1" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, mcl1_protein_pct_ctrl=72.0), _mk_d2_lot(2), _mk_d2_lot(3)]})["failures"], "G43_ADV_d2_mcl1")
    chk("FAIL_CHECK_D2_CD59_PROTEIN_LT_80PCT:D2-LOT-1" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, cd59_protein_pct_ctrl=74.0), _mk_d2_lot(2), _mk_d2_lot(3)]})["failures"], "G43_ADV_d2_cd59")
    chk("FAIL_CHRONOLOGICAL_PREREQ_POSTDATES_STAGE:GATE-31_AFTER_CHECK_D3B_PILOT" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "d3b_pilot_receipt": _sign_receipt({**d3b_rcpt_a, "recorded_at_utc": "2026-10-12T09:35:00Z"})})["failures"], "G43_ADV_d3b_before_g31")
    chk("FAIL_R1_GATE31C_RECOMPUTED_PAIRED_L95_FAILED" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "gate31_evidence": _sign_receipt({**g31_a_42, "gate31c_paired_blocks": [{"block_id": f"B{i}", "open_sink_t_half_h": 28.0+0.2*i, "limited_exchange_t_half_h": 65.0+0.5*i} for i in range(6)]})})["failures"], "G43_ADV_g31c_raw_blocks_fail")

    chk("FAIL_CHECK_D2_NOT_APPLICABLE_FORBIDS_EVAL_FIELDS:check_d2_challenger_gene" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d2_challenger_gene": None})["failures"], "G43_ADV_forbid_d2_none")
    chk("FAIL_CHECK_D3A_NOT_ATTEMPTED_FORBIDS_EVAL_FIELDS:check_d3a_per_lot_records" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d3a_per_lot_records": None})["failures"], "G43_ADV_forbid_d3a_none")
    chk("FAIL_CHECK_D3B_NOT_ATTEMPTED_FORBIDS_EVAL_FIELDS:d3b_pilot_receipt" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "d3b_pilot_receipt": None})["failures"], "G43_ADV_forbid_d3b_none")
    chk("FAIL_CHECK_D2_UNREFERRED_PROLIFERATION_ELEVATION:D2-LOT-1" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, ki67=1.05, ref=False), _mk_d2_lot(2), _mk_d2_lot(3)]})["failures"], "G43_ADV_d2_prolif_unref")
    chk("HOLD_CHECK_D2_PROLIFERATION_REFERRED:D2-LOT-1" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, edu=1.04, ref=True), _mk_d2_lot(2), _mk_d2_lot(3)]})["holds"], "G43_ADV_d2_prolif_ref_hold")
    chk("HOLD_CANONICAL_BANK_MATERIALIZATION_MISSING" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "materialization_evidence": None})["holds"], "G43_ADV_A_requires_mat")
    chk("HOLD_MISSING_R1_GATE31_EVIDENCE" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "gate31_evidence": None})["holds"], "G43_ADV_A_assembled_req_g31")
    chk("FAIL_CHECK_D1_BLOQ_MUST_USE_NULL_CONCENTRATION_NOT_NUMERIC" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_residual_t3_arm_b_nM": 0.10, "check_d1_arm_b_below_lloq": True})["failures"], "G43_ADV_bloq_numeric")
    chk("FAIL_CHECK_D1_NON_BLOQ_CONCENTRATION_MISSING_OR_BELOW_LLOQ" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_residual_t3_arm_b_nM": 0.10, "check_d1_arm_b_below_lloq": False})["failures"], "G43_ADV_nonbloq_lt_lloq")
    g43_quant_t3b = {**g43_base, "check_d1_residual_t3_arm_b_nM": 0.45, "check_d1_arm_b_below_lloq": False}
    g43_quant_t3b["check_d1_paired_assay_receipt"] = _mk_d1_unified(g43_quant_t3b)
    chk(evaluate_gate43_cellgemma_guardrails_and_pilots(g43_quant_t3b)["verdict"] == "PASS_DESCRIPTIVE_PILOT_ZERO_ODDS_GY037_WARN_RETAINED", "G43_ADV_quant_t3b_pass")
    chk("FAIL_CHECK_D3A_REQUIRES_AT_LEAST_3_INDEPENDENT_LOT_RECORDS" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": d3a_ok_lots[:2]})["failures"], "G43_ADV_d3a_lt3")
    chk("FAIL_CHECK_D3A_NON_ZERO_PTPRC_CONTAMINATION:IEC-LOT-1" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": [_mk_d3a_lot(1, iec_ptprc_pct=0.5), d3a_ok_lots[1], d3a_ok_lots[2]]})["failures"], "G43_ADV_d3a_ptprc")
    chk("FAIL_CHECK_D3A_NO_FUNCTIONAL_TAT_REDUCTION:IEC-LOT-2" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": [d3a_ok_lots[0], _mk_d3a_lot(2, chandler_tat_f3_sirna_ng_ml=95.0), d3a_ok_lots[2]]})["failures"], "G43_ADV_d3a_tat")
    chk("FAIL_EPISTEMIC_TIER_MUST_BE_CELLGEMMA_IN_SILICO_PRIOR" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "evidence_tier": "clinical"})["failures"], "G43_tier")
    chk("FAIL_DRAFT_D_NONZERO_LIVE_ODDS" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "live_odds_delta_pp": 0.1})["failures"], "G43_live_odds")
    chk("FAIL_DRAFT_D_NONZERO_PROSPECTIVE_ODDS" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "prospective_odds_delta_pp": 0.1})["failures"], "G43_prosp_odds")
    chk("FAIL_GY037_MUST_USE_REVOCABLE_WARN_SEVERITY" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "graveyard_severity": "HARD_EXCLUDE"})["failures"], "G43_warn")
    chk("FAIL_CHECK_D1_ZERO_ADOPTION_AUTHORITY_VIOLATED_OR_MISSING" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_claims_adoption_authority": True})["failures"], "G43_adopt")
    chk("FAIL_CHECK_D1_ARM_WASHES_MUST_BE_IDENTICAL_INT_GE_3" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_arm_a_washes": 3, "check_d1_arm_b_washes": 4})["failures"], "G43_wash")
    chk("FAIL_CHECK_D1_UNDECLARED_ZM447439_REGIMEN" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_starting_zm_regimen": "CUSTOM"})["failures"], "G43_zm_reg")
    chk("FAIL_CHECK_D1_ZM447439_LLOQ_EXCEEDS_0P005UM" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_zm447439_lloq_uM": 0.01})["failures"], "G43_zm_lloq")
    chk("FAIL_CHECK_D1_ZM447439_ABOVE_LLOQ_OR_0P005UM" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_arm_a_zm447439_lcms_uM": 0.008})["failures"], "G43_zm_hi")
    chk("FAIL_CHECK_D1_SPIKE_RECOVERY_OUT_OF_80_120" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_arm_a_spike_recovery_pct": 70.0})["failures"], "G43_spike")
    chk("FAIL_CHECK_D1_UNMATCHED_HANDLING_ARMS" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_both_arms_matched_24h_nac": False})["failures"], "G43_nac")
    chk("FAIL_CHECK_D1_RETAINED_ARM_T3_OUTSIDE_7_13NM_WINDOW" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_residual_t3_arm_a_nM": 5.0})["failures"], "G43_t3_a")
    chk("FAIL_CHECK_D1_T3_LLOQ_INSUFFICIENT_TO_RESOLVE_RESIDUAL_LIMIT" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_t3_lloq_nM": 0.80})["failures"], "G43_t3_lloq")
    chk("HOLD_CHECK_D1_T3_EXPOSURE_NOT_SEPARATED" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_residual_t3_arm_b_nM": 1.8, "check_d1_arm_b_below_lloq": False})["holds"], "G43_t3_sep")
    chk("FAIL_CHECK_D1_PRE_COASSEMBLY_VASCULAR_FUNCTION_FAILED" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_pre_coassembly_vascular_function_pass": False})["failures"], "G43_vasc")
    chk("HOLD_CHECK_D1_PAIRED_GSIS_NOT_RECORDED" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_paired_gsis_40_100mmhg_recorded": False})["holds"], "G43_gsis_rec")
    chk("HOLD_CHECK_D1_PAIRED_ICAM1_VCAM1_FACS_NOT_RECORDED" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_paired_icam1_vcam1_facs_recorded": False})["holds"], "G43_facs_rec")
    chk("FAIL_CHECK_D3_C3_MUST_REMAIN_UNTESTED" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d3_c3_explicitly_untested": False})["failures"], "G43_c3")
    chk("FAIL_CHECK_D3B_UNMATCHED_TREATED_VS_NT_LOT_ID" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "d3b_pilot_receipt": _sign_receipt({**d3b_rcpt_a, "nt_control_lot_id": "OTHER"})})["failures"], "G43_d3b_lot")
    chk("FAIL_CHECK_D3B_MISSING_SAME_PRODUCT_NT_SIRNA" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "d3b_pilot_receipt": _sign_receipt({**d3b_rcpt_a, "same_product_nt_sirna": False})})["failures"], "G43_d3b_nt")
    chk("FAIL_CHECK_D3B_MISSING_PARENTAL_ATTRIBUTION_ARM" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "d3b_pilot_receipt": _sign_receipt({**d3b_rcpt_a, "parental_attribution_included": False})})["failures"], "G43_d3b_par")
    chk("FAIL_CHECK_D3B_SHIELD_PRESERVATION_BELOW_85PCT:PDL1" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "d3b_pilot_receipt": _sign_receipt({**d3b_rcpt_a, "f3_sirna_shield_by_component": {**_mk_r8_shields(pa, 91.0), "PDL1": 70.0}})})["failures"], "G43_d3b_sh")
    chk("FAIL_CHECK_D3B_UNDECLARED_ASSAY_SCOPE" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "d3b_assay_scope": "MYSTERY"})["failures"], "G43_d3b_scope")
    chk("FAIL_CHECK_D2_UNRECOGNIZED_CHALLENGER_GENE" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_challenger_gene": "TP53"})["failures"], "G43_d2_gene")
    chk("FAIL_GATE43_UNKNOWN_OR_UNRECONCILED_FIELDS:rogue_k" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "rogue_k": 1})["failures"], "G43_unknown_key")
    chk("FAIL_CHECK_D3A_F3_KD_BELOW_60PCT:IEC-LOT-1" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": [_mk_d3a_lot(1, f3_kd_pct=45.0), d3a_ok_lots[1], d3a_ok_lots[2]]})["failures"], "G43_d3a_kd")
    chk("FAIL_CHECK_D3A_CXCL10_RETENTION_BELOW_85PCT:IEC-LOT-1" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": [_mk_d3a_lot(1, cxcl10_retention_pct=70.0), d3a_ok_lots[1], d3a_ok_lots[2]]})["failures"], "G43_d3a_cxcl10")
    chk("FAIL_CHECK_D3A_CD274_RETENTION_BELOW_85PCT:IEC-LOT-1" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": [_mk_d3a_lot(1, cd274_retention_pct=70.0), d3a_ok_lots[1], d3a_ok_lots[2]]})["failures"], "G43_d3a_cd274")
    chk("FAIL_CHECK_D3A_APOPTOSIS_INCREASE:IEC-LOT-1" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": [_mk_d3a_lot(1, cleaved_casp3_fold=1.5), d3a_ok_lots[1], d3a_ok_lots[2]]})["failures"], "G43_d3a_casp3")
    chk("FAIL_CHECK_D3A_CHANDLER_CONTROLS_INVALID:IEC-LOT-1" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": [_mk_d3a_lot(1, pos_ctrl_tat_fold=1.5), d3a_ok_lots[1], d3a_ok_lots[2]]})["failures"], "G43_d3a_ctrl")
    chk("FAIL_CHECK_D3A_LOT_CONTENT_HASH_INVALID:IEC-LOT-1" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": [{**d3a_ok_lots[0], "f3_kd_pct": 88.0}, d3a_ok_lots[1], d3a_ok_lots[2]]})["failures"], "G43_d3a_hash")
    chk("FAIL_CHECK_D2_REQUIRES_AT_LEAST_3_ISOGENIC_LOT_RECORDS" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1), _mk_d2_lot(2)]})["failures"], "G43_d2_lt3")
    chk("FAIL_CHECK_D2_NON_CANONICAL_PRODUCT_ID" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_product_id": "LEGACY_PROD"})["failures"], "G43_d2_prod")
    chk("FAIL_CHECK_D2_MISSING_BANK_ID" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_bank_id": ""})["failures"], "G43_d2_bank")
    chk("FAIL_CHECK_D2_INVALID_MATCHED_CONTROL_LOT_ID:D2-LOT-1" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, mctrl_override="D2-LOT-1"), _mk_d2_lot(2), _mk_d2_lot(3)]})["failures"], "G43_d2_same_ctrl")
    chk("HOLD_CHECK_D3B_TIMED_PILOT_RECEIPT_MISSING" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "d3b_pilot_receipt": None})["holds"], "G43_d3b_rcpt_miss")
    chk("FAIL_CHECK_D3B_INCOMPLETE_INTERVENTION_SHIELD_RECORDS" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "d3b_pilot_receipt": _sign_receipt({**d3b_rcpt_a, "parental_shield_by_component": None})})["failures"], "G43_d3b_par_sh_miss")
    chk("FAIL_CHECK_D3B_INVALID_STATUS" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d3b_status": "EVAL"})["failures"], "G43_d3b_bad_stat")
    chk("HOLD_GATE0V_LOT_SURROGATE_REQUIRES_VERIFIED_PRIOR_BANK_ARCHIVE" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "gate0v_evidence": _mk_r8_gate0v(pa, ba, la, ra, mat_a_42, "2026-10-12T09:30:00Z", tier_override="PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE")})["holds"], "G43_ADV_g0v_surrogate_needs_bank")
    # IEC_ONLY_NON_ASSEMBLED on Design A does NOT require GATE-31 (only PLVAP_iEC Hour-0!)
    d3b_rcpt_iec = _sign_receipt({
        "stage": "CHECK_D3B_PILOT", "verdict": "PASS",
        "product_id": pa, "bank_id": ba, "lot_id": la, "route_id": ra,
        "evidence_scope": "exact_product", "recorded_at_utc": "2026-10-15T10:00:00Z",
        "parent_receipt_sha256": mat_a_42["receipt_sha256"],
        "prerequisite_receipt_sha256s": {
            "BANK_MATERIALIZATION": mat_a_42["receipt_sha256"],
            "NATIVE_SAFETY_SWITCH": sw_a_42["receipt_sha256"],
            "GATE-0V-KILL": g0v_a_42["receipt_sha256"],
        },
        "d3b_assay_scope": "IEC_ONLY_NON_ASSEMBLED",
        "assay_acquired_at_utc": "2026-10-14T10:00:00Z",
        "f3_kd_pct_in_pilot": 74.0,
        "treated_lot_id": la, "nt_control_lot_id": la,
        "same_product_nt_sirna": True, "parental_attribution_included": True,
        "f3_sirna_shield_by_component": _mk_r8_shields(pa, 91.0),
        "nt_sirna_shield_by_component": _mk_r8_shields(pa, 96.0),
        "parental_shield_by_component": _mk_r8_shields(pa, 98.0),
        "hour0_density_by_lineage": _mk_r8_hour0(pa, REQUIRED_HOUR0_LINEAGES_IEC),
    })
    g43_iec_a = {k: v for k, v in g43_full_a.items() if k != "gate31_evidence"}
    g43_iec_a.update({"d3b_assay_scope": "IEC_ONLY_NON_ASSEMBLED", "d3b_pilot_receipt": d3b_rcpt_iec})
    chk(evaluate_gate43_cellgemma_guardrails_and_pilots(g43_iec_a)["verdict"] == "PASS_DESCRIPTIVE_PILOT_ZERO_ODDS_GY037_WARN_RETAINED", "G43_iec_only_A_pass")
    # Exact outward-rounded Decimal Gate 0V upper bound parity check (0/120000, 180/200, 36/36 <= 1e-4)
    u_dec_120k = clopper_pearson_upper_decimal(0, 120000, "0.005") / (clopper_pearson_lower_decimal(180, 200, "0.025") * clopper_pearson_lower_decimal(36, 36, "0.005"))
    chk(Decimal("6.01e-5") < u_dec_120k < Decimal("6.03e-5"), "G43_ADV_decimal_g0v_est1_exact")
    chk("FAIL_CHECK_D2_READOUT2_SCOPE_MISMATCH_LOT" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [{**_mk_d2_lot(1), "readout2_receipt": _sign_receipt({**_mk_d2_lot(1)["readout2_receipt"], "lot_id": "WRONG-LOT"})}, _mk_d2_lot(2), _mk_d2_lot(3)]})["failures"], "G43_d2_lot_mm")
    chk("FAIL_CHECK_D1_MISSING_T3_QUANTIFICATION_OR_CENSORING_FLAG" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_arm_b_below_lloq": "yes"})["failures"], "G43_d1_bloq_type")
    chk("HOLD_CHECK_D1_PRE_COASSEMBLY_VASCULAR_FUNCTION_UNVERIFIED" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_pre_coassembly_vascular_function_pass": None})["holds"], "G43_d1_vasc_hold")
    chk("FAIL_CHECK_D2_DUPLICATE_OR_EMPTY_LOT_ID" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1), _mk_d2_lot(1), _mk_d2_lot(3)]})["failures"], "G43_d2_dup_lot")
    chk("FAIL_CHECK_D3B_CD47_HOUR0_GY009_BELOW_200K_180K:PLVAP_iEC" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_iec_a, "d3b_pilot_receipt": _sign_receipt({**d3b_rcpt_iec, "hour0_density_by_lineage": {"PLVAP_iEC": {**_mk_r8_hour0(pa, REQUIRED_HOUR0_LINEAGES_IEC)["PLVAP_iEC"], "cd47_median_molecules_per_cell": 150000.0}}})})["failures"], "G43_d3b_cd47")
    chk("FAIL_CHECK_D3B_HLAE_HOUR0_BELOW_15000:PLVAP_iEC" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_iec_a, "d3b_pilot_receipt": _sign_receipt({**d3b_rcpt_iec, "hour0_density_by_lineage": {"PLVAP_iEC": {**_mk_r8_hour0(pa, REQUIRED_HOUR0_LINEAGES_IEC)["PLVAP_iEC"], "hlae_molecules_per_cell": 8000.0}}})})["failures"], "G43_d3b_hlae")
    chk("FAIL_CHECK_D3A_DUPLICATE_OR_EMPTY_LOT_ID" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": [_mk_d3a_lot(1), _mk_d3a_lot(1), _mk_d3a_lot(3)]})["failures"], "G43_d3a_dup_lot")
    chk("FAIL_CHECK_D2_D2-LOT-1_READOUT2_MATCHED_COMPARATOR_ID_MISMATCH" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, readout2_evidence=_mk_r8_readout2(matched_comparator_id="WRONG-CTRL", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1")), _mk_d2_lot(2), _mk_d2_lot(3)]})["failures"], "G43_d2_comp_mm")
    chk("FAIL_CHECK_D2_READOUT2_SCOPE_MISMATCH_PRODUCT" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [{**_mk_d2_lot(1), "readout2_receipt": _sign_receipt({**_mk_d2_lot(1)["readout2_receipt"], "product_id": pb})}, _mk_d2_lot(2), _mk_d2_lot(3)]})["failures"], "G43_d2_prod_mm")


    # ========================================================================
    # ADVERSARIAL REGRESSION SUITE (39 NEW TESTS -> 400/400 TOTAL!)
    # Adversarial fail-closed invariant regression tests.
    # ========================================================================
    # --- Shared Statistics & Exactness (4 tests) ---
    # 1. Exact fractional Satterthwaite df in two_sample_welch_summary (df=4.4669 -> p ~ 0.30622, NOT floored 0.31250!)
    p_frac = student_t_two_sided_p(1.1538, 4.4669)
    chk(0.305 < p_frac < 0.308, "ADV_shared_welch_exact_fractional_df")
    # 2. Exact rational/scaled-integer paired sign-flip eliminates binary float subtraction tie drift on 10-block stress case!
    # Example: 10 blocks where 9 blocks have exact diff +44.5 and 1 block has exact diff -0.0001? Better: exact tie sum!
    # Construct exact tie: d = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0, 256.0, 0.0]? Even better: tr - ctrl with exact decimal 0.1+0.2 == 0.3!
    # tr=[50.1, 50.2, 50.3, 51.0, 52.0, 54.0, 58.0, 66.0, 82.0, 98.0], ctrl=[50.0]*10 -> diffs [0.1, 0.2, 0.3, ...]
    # And exact tie: [50.3, 50.1, 50.2, 50.0+0.6, ...] -> compare exact_two_sided_sign_flip_paired_p on [50.1, 50.2, 50.3] vs [50.0, 50.0, 50.0]:
    # diffs = [0.1, 0.2, 0.3], obs=0.6; flips with |sum|>=0.6: only +0.1+0.2+0.3 & -0.1-0.2-0.3 -> 2/8=0.25!
    # Exact tie with opposite sign: tr=[50.1, 50.2, 50.0], ctrl=[50.0, 50.0, 50.3] -> diffs=[0.1, 0.2, -0.3], sum=0 EXACT -> p=1.0 (float64 gives 0.1+0.2-0.3=5.55e-17 != 0 -> would give 0.75 or wrong!)
    chk(exact_two_sided_sign_flip_paired_p([50.1, 50.2, 50.0], [50.0, 50.0, 50.3]) == 1.0, "ADV_shared_exact_rational_signflip_0p1_0p2_0p3_zero")
    # Exact 10-block Holm boundary tie stress case: diffs = [0.1, 0.2, 0.3, 40.0, 40.0, 40.0, 40.0, 40.0, 40.0, 160.0] with last=-0.3+0.3 tie ->
    # Specifically [0.1, 0.2, -0.3] + 7 blocks of +40.0 -> obs = 280.0; BOTH (+0.1,+0.2,-0.3) AND (-0.1,-0.2,+0.3) give exact 280.0!
    # Plus flipping (+0.1,+0.2,+0.3) gives 280.6 > 280, etc. Exact rational count = 6/1024; in binary float64 (50.1-50.0)+(50.2-50.0)-(50.3-50.0) != 0 breaks symmetry!
    tr10_tie = [50.1, 50.2, 50.0, 90.0, 90.0, 90.0, 90.0, 90.0, 90.0, 90.0]
    ct10_tie = [50.0, 50.0, 50.3, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0, 50.0]
    # All 7 blocks of +40 = +280; among the 3 small diffs {+0.1,+0.2,-0.3}: sums >= 0 are (+0.1+0.2+0.3=+0.6, +0.1+0.2-0.3=0, -0.1-0.2+0.3=0, -0.1+0.2+0.3=+0.4, +0.1-0.2+0.3=+0.2) -> 5 positive * 2 (two-sided) = 10/1024!
    chk(exact_two_sided_sign_flip_paired_p(tr10_tie, ct10_tie) == 10.0 / 1024.0, "ADV_shared_exact_rational_10blk_tie_exact")
    # 3. Live wetlab_contract.py:13143-13175 parity: Full Gate 0M is ALWAYS mandatory! t90=6.0 FAILS EVEN when gate0m_applicable=False!
    r2_ord_t90_6 = _mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B", gate0m_applicable=False)
    for _o2k in ("o2_40_mmhg", "o2_100_mmhg"):
        for _b in r2_ord_t90_6[_o2k]["blocks"]:
            _b["stepdown_t50_min"] = 2.0; _b["stepdown_t90_min"] = 6.0
    chk("FAIL_GATE_A2_READOUT2_O2_40_GATE0M_SHUTOFF_T90_GT_3MIN_FAILED" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": r2_ord_t90_6})})["failures"], "ADV_shared_r2_gate0m_mandatory_even_when_flag_false")
    r2_g0m_t90_6 = {**r2_ord_t90_6, "gate0m_applicable": True}
    chk("FAIL_GATE_A2_READOUT2_O2_40_GATE0M_SHUTOFF_T90_GT_3MIN_FAILED" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": r2_g0m_t90_6})})["failures"], "ADV_shared_r2_gate0m_t90_6_FAILS")

    # --- GATE-40 Regressions (9 tests) ---
    # 4. Contradictory zero cumulative release trace in A-0b, A-1-bench, A-1-exact FAILS immediately (Critical #1)!
    chk("FAIL_GATE_A0B_ZERO_OR_CONTRADICTORY_RELEASE_TRACE" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "cumulative_intact_parent_released_mg": [0.0] * len(tr14_t)})})["failures"], "ADV_G40_a0b_zero_release_fails")
    chk("FAIL_GATE_A1_ZERO_OR_CONTRADICTORY_RELEASE_TRACE" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "cumulative_intact_parent_released_mg": [0.0] * len(tr35_t)})})["failures"], "ADV_G40_a1_zero_release_fails")
    # 5. Mismatched Day-14 usable fraction or terminal mass recovery vs release trace FAILS!
    chk("FAIL_GATE_A1_DAY14_USABLE_FRACTION_MISMATCH_WITH_TRACE" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "day14_usable_delivery_fraction_pct": 55.0})})["failures"], "ADV_G40_a1_u14_trace_mismatch")
    chk("FAIL_GATE_A1_TERMINAL_MASS_RECOVERY_MISMATCH_WITH_MASS_RECORD" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "day35_residual_parent_mg": 0.0, "day35_degradant_mass_mg": 0.0, "day35_terminal_mass_recovery_pct": 99.87})})["failures"], "ADV_G40_a1_mass_rec_mismatch")
    chk("FAIL_GATE_A1_T50_CONTRADICTS_RELEASE_TRACE" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "elution_t50_days": 13.5})})["failures"], "ADV_G40_a1_t50_trace_mismatch")
    # 6. Critical #2: Exact double-boundary burst counterexample (4 mg @ 1h, 8 mg @ 3h, t_half=2.0h, Vd=35L -> 0.22857 >= 0.20!)
    cmax_r1_ce = _recompute_pirfenidone_peak_systemic_cmax_ug_ml([0.0, 1.0, 3.0], [0.0, 4.0, 8.0], t_half_h=2.0, vd_l=35.0)
    chk(abs(cmax_r1_ce - (8.0 / 35.0)) < 1e-12 and cmax_r1_ce > 0.20, "ADV_G40_supremum_double_burst_0p2286")
    # Conservative PK policy rejects unrealistically fast t_half < 2.4 h or huge Vd > 65 L
    chk("FAIL_GATE_A0B_INVALID_HUMAN_PK_ENVELOPE_THALF_OR_VD" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "assumed_human_t_half_h": 2.0})})["failures"], "ADV_G40_pk_thalf_lt_2p4_fails")
    # 7. High #3: Future-dated 2028 Readout-2 inside 2026 A-2 receipt FAILS!
    r2_future_2028 = _mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B", stage7_start_utc="2028-10-01T00:00:00Z", sort_reaggregation_utc="2028-10-15T00:00:00Z", assay_harvest_utc="2028-10-22T00:00:00Z")
    chk("FAIL_GATE_A2_READOUT2_ASSAY_HARVEST_POSTDATES_RECEIPT" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": r2_future_2028})})["failures"], "ADV_G40_a2_future_2028_r2_fails")
    # 8. High #4: Longitudinal A-4b animal ID swapping COATED <-> BLANK_VEHICLE across early & Day 28 FAILS!
    prereg_long, a4b_long_base = _mk_r8_a4b_prereg_and_cohorts(py, by, ly, ry, a4a_y, coat_a, start_dt_str="2026-12-20T08:00:00Z", mode="VALIDATED_NONTERMINAL_LONGITUDINAL_IMAGING")
    for _i in range(8):
        a4b_long_base["day28_cohort_records"][2 * _i]["animal_id"] = f"L-VEH-{_i+1:02d}"
        a4b_long_base["day28_cohort_records"][2 * _i + 1]["animal_id"] = f"L-COAT-{_i+1:02d}"
    a4b_swap = _sign_receipt({**a4b_y, **a4b_long_base, "prerequisite_receipt_sha256s": {**pr_all_y, "A-4b-PREREGISTRATION": prereg_long["receipt_sha256"]}})
    chk("FAIL_GATE_A4B_LONGITUDINAL_ANIMAL_ARM_REASSIGNMENT:L-COAT-01" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_preregistration_receipt": prereg_long, "a4b_evidence": a4b_swap})["failures"], "ADV_G40_a4b_longitudinal_arm_swap_fails")

    # --- GATE-41 Regressions (11 tests) ---
    # 9. Decisive #1: Raw local BMT replicates = 0.30 nM while claimed = 0.08 nM & mixture_requalification_receipt absent FAILS & HOLDS in BOTH bench & exact!
    b2b_bad_raw_bmt = _mk_r8_b2b_replicates()
    b2b_bad_raw_bmt["timepoint_replicate_records"][0]["local_bmt_total_replicates_nM"] = [0.30] * 6
    b2b_bad_raw_bmt["timepoint_replicate_records"][0]["local_bmt_blq_flags"] = [False] * 6
    r_b2b_ce_bench = evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, **b2b_bad_raw_bmt})})
    chk("FAIL_GATE_B2B_BENCH_CLAIMED_LOCAL_BMT_UNDERSTATES_RAW_REPLICATES" in r_b2b_ce_bench["failures"] and "HOLD_GATE_B2B_BENCH_METABOLITE_TRIGGERED_MIXTURE_REQUAL_REQUIRED" in r_b2b_ce_bench["holds"], "ADV_G41_b2b_raw_bmt_0p30_contradiction_bench")
    b2b_bad_raw_bmt_ex = _mk_r8_b2b_replicates(evidence_scope="exact_product")
    b2b_bad_raw_bmt_ex["timepoint_replicate_records"][0]["local_bmt_total_replicates_nM"] = [0.30] * 6
    b2b_bad_raw_bmt_ex["timepoint_replicate_records"][0]["local_bmt_blq_flags"] = [False] * 6
    r_b2b_ce_exact = evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b2b_exact_evidence": _sign_receipt({**b2be_y, **b2b_bad_raw_bmt_ex})})
    chk("FAIL_GATE_B2B_EXACT_CLAIMED_LOCAL_BMT_UNDERSTATES_RAW_REPLICATES" in r_b2b_ce_exact["failures"] and "HOLD_GATE_B2B_EXACT_METABOLITE_TRIGGERED_MIXTURE_REQUAL_REQUIRED" in r_b2b_ce_exact["holds"], "ADV_G41_b2b_raw_bmt_0p30_contradiction_exact")
    # Also test contradictory blq_flags=True on 0.30 nM quantifiable BMT!
    b2b_bad_blq = _mk_r8_b2b_replicates()
    b2b_bad_blq["timepoint_replicate_records"][0]["local_bmt_total_replicates_nM"] = [0.30] * 6
    chk("FAIL_GATE_B2B_BENCH_BLQ_FLAG_CONTRADICTS_QUANTIFIABLE_LOCAL_BMT:0" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, **b2b_bad_blq})})["failures"], "ADV_G41_b2b_blq_flag_contradiction_fails")
    # 10. Bare mixture_requalified=True WITHOUT content-hashed mixture_requalification_receipt STILL HOLDS!
    chk("HOLD_GATE_B2B_BENCH_METABOLITE_TRIGGERED_MIXTURE_REQUAL_REQUIRED" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "c_bmt_local_total_u_alloc_nM": 0.25, "mixture_requalified": True})})["holds"], "ADV_G41_b2b_bare_mix_bool_insufficient")
    def _mk_7ep_curve_reps() -> tuple[list[dict[str, list[float]]], list[dict[str, list[float]]]]:
        d5 = (-0.2, -0.1, 0.0, 0.1, 0.2)
        s_rows = [
            {
                "sprouting_pct": [round(sp + d, 3) for d in d5],
                "nkg2a_pct": [round(nk + d, 3) for d in d5],
                "cd94_pct": [round(c9 + d, 3) for d in d5],
                "il10_retention_pct": [round(il + d, 3) for d in d5],
            }
            for sp, nk, c9, il in (
                (99.2, 99.0, 99.0, 99.0),
                (97.5, 96.5, 96.8, 96.0),
                (96.0, 94.5, 95.0, 93.5),
                (95.0, 93.0, 93.5, 91.0),
                (94.0, 91.5, 92.0, 88.5),
                (72.0, 74.0, 75.0, 68.0),
            )
        ]
        e_rows = [
            {
                "beta_cytokine_protection_pct": [round(eb + d, 3) for d in d5],
                "nk_cytokine_suppression_pct": [round(en + d, 3) for d in d5],
                "iec_ibmir_marker_suppression_pct": [round(ei + d, 3) for d in d5],
            }
            for eb, en, ei in (
                (4.0, 3.8, 4.2),
                (28.0, 27.5, 29.0),
                (62.0, 61.5, 61.0),
                (76.0, 75.0, 74.5),
                (85.0, 84.0, 83.5),
                (90.0, 89.5, 89.0),
            )
        ]
        return s_rows, e_rows

    def _mk_mix_dr(
        r_lo_m: float, r_hi_m: float, ec50_m: float = 6.5, csafe_m: float = 21.0,
        *, tested_product_id: str = "BENCH_UNEDITED_PANEL", cover_unbounded_to_1: bool = False,
    ) -> dict[str, Any]:
        grid_m = [0.0, 2.0, ec50_m, round(0.5 * (ec50_m + csafe_m), 2), csafe_m, round(csafe_m * 2.0, 2)]
        f_lo_m = round(r_lo_m / (1.0 + r_lo_m), 6) if r_lo_m > 0.0 else 0.0
        f_hi_m = 1.0 if cover_unbounded_to_1 else (round(r_hi_m / (1.0 + r_hi_m), 6) if r_hi_m > 0.0 else 0.0)
        if cover_unbounded_to_1:
            n_st = max(4, int(math.ceil((f_hi_m - f_lo_m) / 0.25)))
            fracs = [round(f_lo_m + (f_hi_m - f_lo_m) * (k / float(n_st)), 6) for k in range(n_st + 1)]
            fracs[0], fracs[-1] = f_lo_m, 1.0
            pts: list[tuple[float, Any]] = [
                (ff, "INF_PURE_BMT" if abs(ff - 1.0) <= 1e-9 else round(ff / (1.0 - ff), 6))
                for ff in fracs
            ]
        elif abs(r_hi_m - r_lo_m) <= 1e-9:
            pts = [(f_lo_m, r_lo_m)]
        else:
            n_st = max(2, int(math.ceil((r_hi_m - r_lo_m) / 0.50)), int(math.ceil((f_hi_m - f_lo_m) / 0.25)))
            ratios = [round(r_lo_m + (r_hi_m - r_lo_m) * (k / float(n_st)), 6) for k in range(n_st + 1)]
            ratios[0], ratios[-1] = r_lo_m, r_hi_m
            pts = [(round(rr / (1.0 + rr), 6) if rr > 0.0 else 0.0, rr) for rr in ratios]
        curves = []
        for ff, rr in pts:
            sr_c, er_c = _mk_7ep_curve_reps()
            curves.append({
                "measured_bmt_fraction": ff,
                "measured_bmt_to_parent_ratio": rr,
                "tested_free_combined_conc_grid_nM": list(grid_m),
                "mixture_safety_replicates_by_conc": sr_c,
                "mixture_efficacy_replicates_by_conc": er_c,
            })
        _b = {
            "analysis_method": "SIMULTANEOUS_BONFERRONI_GRID_BRACKET_STUDENT_T",
            "tested_product_id": tested_product_id,
            "tested_bmt_to_parent_ratio_min": r_lo_m,
            "tested_bmt_to_parent_ratio_max": r_hi_m,
            "tested_bmt_fraction_min": f_lo_m,
            "tested_bmt_fraction_max": f_hi_m,
            "composition_interpolation_rule": "CONSERVATIVE_MIN_CEILING_MAX_EC50_ACROSS_BRACKETED_RATIOS",
            "mixture_composition_curves": curves,
        }
        return {**_b, "evidence_sha256": sha256_bytes(canonical_json_bytes(_b))}

    # Valid content-hashed mixture_requalification_receipt clears triggered B-2b cleanly!
    mix_rcpt_ok = _sign_receipt({
        "stage": "MIXTURE_REQUALIFICATION", "verdict": "PASS",
        "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "bench_unedited", "recorded_at_utc": "2026-09-11T10:00:00Z", **coat_b,
        "analysis_record_sha256": "d" * 64,
        "tested_bmt_to_parent_ratio_min": 0.0, "tested_bmt_to_parent_ratio_max": 0.25,
        "mixture_ec50_eff_u95_free_nM": 6.5, "mixture_c_safe_max_l95_free_nM": 21.0,
        "mixture_dose_response_evidence": _mk_mix_dr(0.0, 0.25, 6.5, 21.0),
    })
    chk(evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "c_bmt_local_total_u_alloc_nM": 0.25, "mixture_requalified": True, "mixture_requalification_receipt": mix_rcpt_ok})})["verdict"] == "PASS_BENCH_ONLY_UNEDITED_PRE_MATERIALIZATION", "ADV_G41_b2b_valid_mixture_receipt_PASSES")
    # 11. B-0a flat 100% safety curves OR flat 60% efficacy at 0 nM OR missing CD94 FAIL!
    flat_s_reps = [{**b0a_s_reps_ok[0], "matched_vehicle_record_id": f"B0A-VEH-CONC-{_i}", "raw_unit_measurements": {k: {**v, "vehicle_record_id": f"B0A-VEH-CONC-{_i}"} for k, v in b0a_s_reps_ok[0]["raw_unit_measurements"].items()}} for _i in range(8)]
    chk("FAIL_GATE_B0A_RAW_CONC_RESPONSE_CONTRADICTS_WINDOW" in evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": _sign_receipt({**b0a_ok, "safety_sprouting_pct_grid": [100.0]*8, "safety_nkg2a_pct_grid": [100.0]*8, "safety_cd94_pct_grid": [100.0]*8, "safety_il10_retention_pct_grid": [100.0]*8, "safety_replicates_by_conc": flat_s_reps, "b0a_analysis_receipt": _sign_receipt({**b0a_an_ok, "raw_safety_replicates_sha256": sha256_bytes(canonical_json_bytes(flat_s_reps))})})})["failures"], "ADV_G41_b0a_flat_100_safety_fails")
    chk("FAIL_GATE_B0A_RAW_CONC_RESPONSE_CONTRADICTS_WINDOW" in evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": _sign_receipt({**b0a_ok, "efficacy_inhibition_pct_grid": [60.0]*8, "efficacy_beta_protection_pct_grid": [60.0]*8, "efficacy_nk_suppression_pct_grid": [60.0]*8, "efficacy_iec_ibmir_pct_grid": [60.0]*8})})["failures"], "ADV_G41_b0a_flat_60_efficacy_0nM_fails")
    chk("FAIL_GATE_B0A_MISSING_RAW_CONC_RESPONSE_GRID" in evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": _sign_receipt({k: v for k, v in b0a_ok.items() if k != "safety_cd94_pct_grid"})})["failures"], "ADV_G41_b0a_missing_cd94_fails")
    # B-0a-exact flat 98% cassette retention FAILS!
    chk("FAIL_GATE_B0A_EXACT_GRID_NOT_TWO_SIDED_BRACKETED" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b0a_exact_evidence": _sign_receipt({**b0a_ex_y, "cassette_retention_pct_grid": [98.0]*6})})["failures"], "ADV_G41_b0a_exact_flat_98_fails")
    # 12. B-0a-exact predating B-2b-bench FAILS!
    b0a_ex_early = _sign_receipt({**b0a_ex_y, "recorded_at_utc": "2026-09-11T09:00:00Z"})
    chk("FAIL_CHRONOLOGICAL_PREREQ_POSTDATES_STAGE:B-2b-bench_AFTER_B-0a-exact" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b0a_exact_evidence": b0a_ex_early})["failures"], "ADV_G41_b0a_exact_before_b2b_bench_fails")
    # 13. B-4 setting claimed bounds to observed sample extrema (ignoring alpha_conc/alpha_fu_parent/alpha_fu_bmt!) FAILS!
    r_b4_extrema = evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "invivo_u95_joint_peak_free_nM": 15.51, "invivo_days0_10_parent_lower_free_nM": 7.99, "invivo_systemic_plasma_u95_nM": 0.14})})
    chk("FAIL_GATE_B4_CLAIMED_PEAK_UNDERSTATES_RECOMPUTED_SIMULTANEOUS_U95" in r_b4_extrema["failures"] and "FAIL_GATE_B4_CLAIMED_FLOOR_OVERSTATES_RECOMPUTED_SIMULTANEOUS_L95" in r_b4_extrema["failures"] and "FAIL_GATE_B4_CLAIMED_SYSTEMIC_UNDERSTATES_RECOMPUTED_SIMULTANEOUS_U95" in r_b4_extrema["failures"], "ADV_G41_b4_extrema_bypass_fails")

    # --- GATE-42 Regressions (7 tests) ---
    # 14. Identical IFNg-only and isolated TNFa+IFNg (zero incremental TNF effect!) FAILS!
    att_zero_tnf = _sign_receipt({
        **att_y,
        "stage2_normoxia_mechanism_panel": {**att_panel_norm, "cond2_ifng_alone_beta_t0_pct_by_block": list(att_panel_norm["cond3_isolated_tnfa_ifng_beta_t0_pct_by_block"])},
        "stage2_hypoxia_15mmhg_mechanism_panel": {**att_panel_hyp, "cond2_ifng_alone_beta_t0_pct_by_block": list(att_panel_hyp["cond3_isolated_tnfa_ifng_beta_t0_pct_by_block"])},
    })
    chk("FAIL_IIP0049_ZERO_OR_UNPROVEN_INCREMENTAL_TNF_OVER_IFNG_ONLY:NORMOXIA" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": att_zero_tnf})["failures"], "ADV_G42_zero_incremental_tnf_over_ifng_fails")
    # 15. Missing IL-1 positive control or raw 0h/24h shield MFI mismatch FAILS!
    chk("FAIL_IIP0049_IL1_PATHWAY_POSITIVE_CONTROL_MISSING:NORMOXIA" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _sign_receipt({**att_y, "stage2_normoxia_mechanism_panel": {**att_panel_norm, "il1_pathway_positive_control_verified": False}})})["failures"], "ADV_G42_il1_pos_ctrl_missing")
    chk("FAIL_IIP0049_SHIELD_KINETICS_COMPROMISED_ON_BACKGROUND:NORMOXIA" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _sign_receipt({**att_y, "stage2_normoxia_mechanism_panel": {**att_panel_norm, "cxcl10_24h_mfi_by_block": [700.0, 700.0, 700.0]}})})["failures"], "ADV_G42_raw_mfi_mismatch")
    # 16. GATE-36 exogenous SHIELD scope outside drug-free boundary or GATE-32 recall L95 < 0.85 FAILS!
    chk("FAIL_FOUNDRY_V2_GATE36_EXOGENOUS_SHIELD_OUTSIDE_DRUG_FREE_SCOPE" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "foundry_v2_gate36_evidence": _sign_receipt({**g36_y, "foundry_v2_module_scope": "EXOGENOUS_CHRONIC_SHIELD"})})["failures"], "ADV_G42_g36_exogenous_shield_blocked")
    chk("FAIL_FOUNDRY_V2_GATE36_LIVE_GATE32_RECALL_L95_BELOW_0P70" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "foundry_v2_gate36_evidence": _sign_receipt({**g36_y, "live_gate32_debris_recall_receipt": _sign_receipt({**g32_y, "debris_recall_l95_suppressed_frac": 0.65})})})["failures"], "ADV_G42_g32_l95_lt_0p70")
    # 17. Major #4: C-3-GSIS missing matched NT control comparator fails!
    chk("FAIL_GATE_C3_GSIS_READOUT2_MATCHED_COMPARATOR_ID_MISMATCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c3_gsis_evidence": _sign_receipt({**c3_gsis_y, "readout2_evidence": _mk_r8_readout2(block_prefix="C3G", stage7_start_utc="2026-09-12T00:00:00Z", sort_reaggregation_utc="2026-09-22T00:00:00Z", assay_harvest_utc="2026-10-01T00:00:00Z")})})["failures"], "ADV_G42_c3_gsis_missing_nt_ctrl_fails")
    # 18. Chronology enforcement: SWITCH predating C-2 FAILS!
    chk("FAIL_GATE42_CHRONOLOGY_NATIVE_SAFETY_SWITCH_PREDATES_C2" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "native_switch_evidence": _mk_r8_switch(py, by, ly, ry, mat_yc, "2026-09-22T09:00:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": c2_y["receipt_sha256"]})})["failures"], "ADV_G42_sw_predates_c2_fails")

    # --- GATE-43 & Live GATE-31 Parity Regressions (9 tests) ---
    # 19. & 4 Blocking: Live GATE-31 hard-stops on conformal geometry, 19 um film (< 20 um), & 72,000 IU Day-14 catalase (< 73,800 IU)!
    chk("FAIL_R1_GATE31_CONFORMAL_OR_INVALID_BARRIER_GEOMETRY_HARD_STOP" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "gate31_evidence": _sign_receipt({**g31_a_42, "barrier_geometry_mode": "CONFORMAL_CORE_SHELL_BEAD_COATING"})})["failures"], "ADV_G43_g31_conformal_hard_stop")
    chk("FAIL_R1_GATE31_BARRIER_THICKNESS_LT_20UM" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "gate31_evidence": _sign_receipt({**g31_a_42, "barrier_thickness_l95_um": 19.0})})["failures"], "ADV_G43_g31_19um_hard_stop")
    chk("FAIL_R1_GATE31_CATALASE_RETENTION_BELOW_73800IU_OR_70PCT" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "gate31_evidence": _sign_receipt({**g31_a_42, "day14_catalase_retained_l95_iu": 72000.0})})["failures"], "ADV_G43_g31_72k_cat_hard_stop")
    # 20. D-2 receipt predating its own assay harvest FAILS!
    chk("FAIL_CHECK_D2_D2-LOT-1_READOUT2_ASSAY_HARVEST_POSTDATES_RECEIPT" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, recorded_at_utc="2026-10-01T10:00:00Z"), _mk_d2_lot(2), _mk_d2_lot(3)]})["failures"], "ADV_G43_d2_receipt_predates_harvest_fails")
    # 21. D-2 Gate 0S > 138.3 IU with bare gate0s_escalation_cleared=True STILL HOLDS (requires content-hashed receipt)!
    chk("HOLD_CHECK_D2_D2-LOT-1_READOUT2_GATE0S_ESCALATION_REQUIRED_GT_138P3_IU" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, readout2_evidence=_mk_r8_readout2(matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1", stored_u95_iu=150.0, stored_max_iu=155.0, gate0s_cleared=True)), _mk_d2_lot(2), _mk_d2_lot(3)]})["holds"], "ADV_G43_d2_gate0s_bare_bool_holds")
    # 22. Extended-clock Rule S8 missing locked plan HOLDS, & 2-window Bonferroni (k=2) fails borderline 0.850781 -> 0.839678 < 0.85!
    r2_s8_noplan = _mk_r8_readout2(matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1", rule_s8=True, assay_harvest_utc="2026-11-05T00:00:00Z")
    del r2_s8_noplan["rule_s8_locked_analysis_plan_id"]
    chk("HOLD_CHECK_D2_D2-LOT-1_READOUT2_RULE_S8_MISSING_LOCKED_ANALYSIS_PLAN" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, recorded_at_utc="2026-11-08T10:00:00Z", readout2_evidence=r2_s8_noplan), _mk_d2_lot(2), _mk_d2_lot(3)]})["holds"], "ADV_G43_d2_rules8_no_plan_holds")
    r2_s8_k2 = _mk_r8_readout2(matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1", rule_s8=True, rule_s8_k=2, rule_s8_design="MULTI_WINDOW_CONFIRMATION_BONFERRONI", assay_harvest_utc="2026-11-05T00:00:00Z")
    # Construct borderline blocks where 1-window alpha=0.05 Fieller (0.85585 > 0.85) passes,
    # but 2-window Bonferroni alpha=0.025 Fieller (0.84368 < 0.85) FAILS!
    for _bi, (_z2, _s8c) in enumerate([(1.68, 1.99), (1.92, 2.01), (1.704, 1.995), (1.896, 2.005), (1.728, 1.998), (1.872, 2.002)]):
        _b2 = r2_s8_k2["o2_40_mmhg"]["blocks"][_bi]
        _h2n = round(_b2["low2_value"] + _z2 / _b2["eta_sort_viable_recovery"], 6)
        _b2["high2_value"] = _h2n
        _b2["pulse2_si"] = round(_h2n / _b2["low2_value"], 4)
        _b2["kcl_value"] = round(_h2n + 1.40, 6)
        _b2["z2_increment"] = _z2
        _b2["matched_control_z2_increment"] = round(_z2 / 0.97, 4)
        _b2["matched_control_output_ratio"] = round(_z2 / round(_z2 / 0.97, 4), 6)
        _b2["rule_s8_comparator_z2_increment"] = _s8c
        r2_s8_k2["rule_s8_earlier_window_records"][_bi]["z2_40mmhg"] = _s8c
    chk("FAIL_CHECK_D2_D2-LOT-1_READOUT2_O2_40_RULE_S8_FIELLER_L95_LT_0P85" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, recorded_at_utc="2026-11-08T10:00:00Z", readout2_evidence=r2_s8_k2), _mk_d2_lot(2), _mk_d2_lot(3)]})["failures"], "ADV_G43_d2_rules8_k2_bonf_fails")
    # Same borderline data PASSES when single prespecified primary window (k=1, alpha=0.05 -> Fieller L95 > 0.85)!
    r2_s8_k1 = _mk_r8_readout2(matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1", lot_id="D2-LOT-1", rule_s8=True, rule_s8_k=1, rule_s8_design="SINGLE_PRESPECIFIED_PRIMARY", assay_harvest_utc="2026-11-05T00:00:00Z")
    for _bi, (_z2, _s8c) in enumerate([(1.68, 1.99), (1.92, 2.01), (1.704, 1.995), (1.896, 2.005), (1.728, 1.998), (1.872, 2.002)]):
        _b1 = r2_s8_k1["o2_40_mmhg"]["blocks"][_bi]
        _h2n1 = round(_b1["low2_value"] + _z2 / _b1["eta_sort_viable_recovery"], 6)
        _b1["high2_value"] = _h2n1
        _b1["pulse2_si"] = round(_h2n1 / _b1["low2_value"], 4)
        _b1["kcl_value"] = round(_h2n1 + 1.40, 6)
        _b1["z2_increment"] = _z2
        _b1["matched_control_z2_increment"] = round(_z2 / 0.97, 4)
        _b1["matched_control_output_ratio"] = round(_z2 / round(_z2 / 0.97, 4), 6)
        _b1["rule_s8_comparator_z2_increment"] = _s8c
        r2_s8_k1["rule_s8_earlier_window_records"][_bi]["z2_40mmhg"] = _s8c
    chk(evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, recorded_at_utc="2026-11-08T10:00:00Z", readout2_evidence=r2_s8_k1), _mk_d2_lot(2), _mk_d2_lot(3)]})["verdict"] == "PASS_DESCRIPTIVE_PILOT_ZERO_ODDS_GY037_WARN_RETAINED", "ADV_G43_d2_rules8_k1_passes")
    # 23. D-2 reusing LOT-1's 40mmHg block_id inside LOT-2's 100mmHg FAILS; D-3(a) copy-pasting measurements across lots FAILS!
    r2_l2_xblk = _mk_r8_readout2(matched_comparator_id="CTRL-LOT-2", block_prefix="D2L2", meas_id="MEAS-D2-LOT-2", lot_jitter=2.0)
    r2_l2_xblk["o2_100_mmhg"]["blocks"][0]["block_id"] = "D2L1-0-1"  # exact block_id from LOT-1 O2_40!
    chk("FAIL_CHECK_D2_REUSED_BLOCK_ID_ACROSS_LOTS:D2-LOT-2" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1), _mk_d2_lot(2, readout2_evidence=r2_l2_xblk), _mk_d2_lot(3)]})["failures"], "ADV_G43_d2_cross_o2_block_reuse_fails")
    chk("FAIL_CHECK_D3A_IDENTICAL_COPY_PASTE_ACROSS_LOTS:IEC-LOT-2" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": [_mk_d3a_lot(1), _mk_d3a_lot(2, f3_kd_pct=76.5, chandler_tat_nt_ctrl_ng_ml=103.0, chandler_tat_f3_sirna_ng_ml=69.5), _mk_d3a_lot(3)]})["failures"], "ADV_G43_d3a_copypaste_across_lots_fails")
    # 24. D-3(b) switch parity bound to wrong comparator lot (not pilot nt_control_lot_id!) FAILS!
    sw_a_wrong_ctrl = _mk_r8_switch(pa, ba, la, ra, mat_a_42, "2026-10-12T09:00:00Z", comparator_nt_lot_id="UNRELATED-CTRL-LOT")
    chk("FAIL_NATIVE_SWITCH_SW_PARITY_COMPARATOR_LOT_MISMATCH" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "native_switch_evidence": sw_a_wrong_ctrl})["failures"], "ADV_G43_d3b_switch_comparator_mismatch_fails")


    # ========================================================================
    # ADVERSARIAL REGRESSION SUITE (32 NEW TESTS -> 436/436 TOTAL!)
    # Adversarial fail-closed invariant regression tests.
    # ========================================================================
    # --- Shared Exactness & Live Parity (6 tests) ---
    # 1. Exact Fraction OQ-012 recovery floor catches 299,573,227 vs 299,573,228 ambient-Decimal rounding boundary!
    # Using exact rational: raw=399430970, f=0.9, eta=0.8333333333333333333333333333 -> 399430970 * 0.9 * 0.83333... = 299573227.4999... -> floor=299573227 < 299573228!
    oq_bnd_fails: list[str] = []
    oq_bnd_holds: list[str] = []
    _validate_oq012_gate34_clonogenic_block({
        "survivors_k": 0, "raw_cells_tested": 399_430_970,
        "clonogenic_fraction_f": "0.9", "detection_efficiency_eta": "0.8333333333333333333333333333",
        "effective_trials_n_eff": 299_573_228, "regrowth_assay_verified": True, "clonogenic_escape_u95": "9.99999993e-9",
    }, fails=oq_bnd_fails, holds=oq_bnd_holds, prefix="ADV_OQ")
    chk("FAIL_ADV_OQ_OQ012_NEFF_EXCEEDS_FLOOR_N_F_ETA" in oq_bnd_fails, "ADV_shared_oq012_exact_rational_floor_boundary")
    # 2. load_exact_receipt_json preserves exact finite decimal digits (zero IEEE-754 float drift on sign-flip)!
    raw_dec_json = '{"tr": [51.0000000000000001, 52.0, 53.0], "ct": [50.0, 51.0000000000000001, 52.0]}'
    dec_parsed = load_exact_receipt_json(raw_dec_json, "dec_test")
    chk(isinstance(dec_parsed["tr"][0], Decimal) and dec_parsed["tr"][0] == Decimal("51.0000000000000001"), "ADV_shared_load_exact_receipt_json_decimal")
    # 3. Gate 0M Basal1/Peak1 = 0.20 (Peak1/Basal1 = 5.0) FAILS live Gate 0M (<= 0.15), while passing ordinary Readout-2 (>= 4.5)!
    r2_g0m_5x = _mk_r8_readout2(matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1", gate0m_applicable=True, lot_jitter=1.0)
    for _o2k in ("o2_40_mmhg", "o2_100_mmhg"):
        for _b in r2_g0m_5x[_o2k]["blocks"]:
            _b["basal1_value"] = 0.50; _b["peak1_value"] = 2.50; _b["pulse1_peak_to_basal_ratio"] = 5.0
    chk("FAIL_CHECK_D2_D2-LOT-1_READOUT2_O2_40_GATE0M_BASAL1_OVER_PEAK1_GT_0P15" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, readout2_evidence=r2_g0m_5x), _mk_d2_lot(2), _mk_d2_lot(3)]})["failures"], "ADV_shared_gate0m_basal_0p20_fails")
    # 4. Rule S8 disjoint pilot with lowercase block_id matching uppercase pilot block_id HOLDS!
    r2_s8_case = _mk_r8_readout2(matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1", rule_s8=True, rule_s8_design="PILOT_SCREEN_THEN_DISJOINT_CONFIRMATION", assay_harvest_utc="2026-11-05T00:00:00Z", lot_jitter=1.0)
    r2_s8_case["o2_40_mmhg"]["blocks"][0]["block_id"] = "s8p-1"  # lowercase match to pilot "S8P-1"!
    chk("HOLD_CHECK_D2_D2-LOT-1_READOUT2_O2_40_RULE_S8_PILOT_CONFIRMATION_OVERLAP" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, recorded_at_utc="2026-11-08T10:00:00Z", readout2_evidence=r2_s8_case), _mk_d2_lot(2), _mk_d2_lot(3)]})["holds"], "ADV_shared_rules8_case_insensitive_overlap_holds")
    # 5. Live GATE-31 60-h parity PASSES L95(t1/2)=36.0 h & H2O2=2.25 uM, HOLDS H2O2=3.0 uM, FAILS L95=33.0 h & H2O2=5.5 uM!
    g31_a_36_225 = _sign_receipt({**g31_a_42, "halflife_l95_h": 36.0, "h2o2_z70_u95_uM": 2.25, "gate31c_open_sink_h2o2_u95_uM": 2.25})
    d3b_36_225 = _sign_receipt({**d3b_rcpt_a, "prerequisite_receipt_sha256s": {**d3b_rcpt_a["prerequisite_receipt_sha256s"], "GATE-31": g31_a_36_225["receipt_sha256"]}})
    chk(evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "gate31_evidence": g31_a_36_225, "d3b_pilot_receipt": d3b_36_225})["verdict"] == "PASS_DESCRIPTIVE_PILOT_ZERO_ODDS_GY037_WARN_RETAINED", "ADV_shared_g31_live_36h_2p25uM_PASSES")
    chk("HOLD_R1_GATE31_H2O2_Z70_EXCEEDS_2P5UM_TIER1_TARGET" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "gate31_evidence": _sign_receipt({**g31_a_42, "h2o2_z70_u95_uM": 3.0})})["holds"], "ADV_shared_g31_live_3p0uM_HOLDS")

    # --- GATE-40 Regressions (8 tests) ---
    # 6. A-1 Day-1 burst > 15% on A-1 trace FAILS (even if A-0b passed)!
    tr35_burst_hi = list(tr35_m)
    tr35_burst_hi[5] = 3.00  # 3.00 / 18.75 = 16.0% > 15% while staying monotone (<= tr35_m[6]=3.0)!
    chk("FAIL_GATE_A1_DAY1_BURST_EXCEEDS_15PCT_ON_A1_TRACE" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "cumulative_intact_parent_released_mg": tr35_burst_hi})})["failures"], "ADV_G40_a1_day1_burst_gt15_fails")
    # 7. A-1 Day-14 usable fraction strictly excludes Day-1 burst (62.4%, NOT 72.0% from t=0)!
    chk("FAIL_GATE_A1_DAY14_USABLE_FRACTION_MISMATCH_WITH_TRACE" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "day14_usable_delivery_fraction_pct": 72.0})})["failures"], "ADV_G40_a1_postburst_day14_strict")
    # 8. A-1 trace extending past Day 35 (e.g. 960 h) still reconciles Day-35 mass strictly at 840 h!
    tr_ext_t = tr35_t + [960.0]
    tr_ext_m = tr35_m + [18.70]  # extra release after 840 h cannot disguise missing Day-35 mass!
    chk("FAIL_GATE_A1_TERMINAL_MASS_RECOVERY_MISMATCH_WITH_MASS_RECORD" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "elution_time_hours": tr_ext_t, "cumulative_intact_parent_released_mg": tr_ext_m, "day35_residual_parent_mg": 0.05, "day35_residual_parent_pct": 0.27, "day35_depot_exhaustion_pct": 99.73, "day35_terminal_mass_recovery_pct": 100.0})})["failures"], "ADV_G40_a1_post_day35_tail_cannot_mask_840h_mass")
    # 9. True sliding 24-h cumulative release sums multiple adjacent intervals within 24 h!
    chk(abs(_recompute_max_24h_cumulative_mg([0.0, 6.0, 12.0, 18.0, 24.0, 48.0], [0.0, 1.0, 2.0, 3.0, 4.0, 4.5]) - 4.5) < 1e-9, "ADV_G40_sliding_24h_multi_interval_exact")
    # 10. Cherry-picked favorable (t_half=2.4, Vd=65) CANNOT mask worst-case FDA/PMDA corner (t_half=4.0, Vd=35)!
    chk("FAIL_GATE_A1_PK_CLEARANCE_INCONSISTENT_WITH_THALF_AND_VD" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "assumed_human_clearance_l_per_day": 450.0})})["failures"], "ADV_G40_a1_cl_inconsistent_fails")
    # 11. A-2 Readout-2 harvest predating A-2 exposure start FAILS!
    r2_early_hv = _mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B", stage7_start_utc="2026-09-20T00:00:00Z", sort_reaggregation_utc="2026-09-28T00:00:00Z", assay_harvest_utc="2026-10-04T00:00:00Z")
    chk("FAIL_GATE_A2_READOUT2_ASSAY_HARVEST_PREDATES_EXPOSURE_START" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": r2_early_hv})})["failures"], "ADV_G40_a2_r2_harvest_predates_exposure_fails")
    # 12. A-4b missing pre-enrollment preregistration receipt HOLDS; ghost animal in roster FAILS; excluded cross-cohort terminal animal FAILS!
    chk("HOLD_GATE_A4B_PREREGISTRATION_RECEIPT_MISSING" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_preregistration_receipt": None})["holds"], "ADV_G40_a4b_missing_prereg_holds")
    prereg_ghost = _sign_receipt({**a4b_prereg_y, "randomized_animal_roster": {**a4b_prereg_y["randomized_animal_roster"], "GHOST-99": "COATED"}, "day28_cohort_assigned_ids": [*a4b_prereg_y["day28_cohort_assigned_ids"], "GHOST-99"]})
    a4b_ghost = _sign_receipt({**a4b_y, "prerequisite_receipt_sha256s": {**pr_all_y, "A-4b-PREREGISTRATION": prereg_ghost["receipt_sha256"]}})
    chk("FAIL_GATE_A4B_DAY28_COHORT_UNACCOUNTED_OR_EXTRA_ROSTER_ANIMALS" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_preregistration_receipt": prereg_ghost, "a4b_evidence": a4b_ghost})["failures"], "ADV_G40_a4b_ghost_roster_animal_fails")

    # --- GATE-41 Regressions (8 tests) ---
    # 13. B-2b missing quantitative intersample_pk_envelope OR high elimination rate breaches continuous cap!
    chk("FAIL_GATE_B2B_BENCH_MISSING_QUANTITATIVE_INTERSAMPLE_ENVELOPE" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "intersample_pk_envelope": None})})["failures"], "ADV_G41_b2b_envelope_missing_fails")
    # 14. B-2b missing Day-21 washout replicate row FAILS; B-4 Day-21 replicate U95 >= 2.0 nM FAILS!
    b2b_no_d21 = _mk_r8_b2b_replicates(); b2b_no_d21["timepoint_replicate_records"] = b2b_no_d21["timepoint_replicate_records"][:-1]
    chk("FAIL_GATE_B2B_BENCH_TIMEPOINT_WINDOW_MISSES_BURST_DAY10_OR_DAY21_WASHOUT" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, **b2b_no_d21})})["failures"], "ADV_G41_b2b_missing_day21_washout_fails")
    b4_bad_d21 = _mk_r8_b4_replicates(b4_hrs, b4_lpf, b4_lbf, b4_spf, b4_sbf)
    b4_bad_d21["timepoint_replicate_records"][-1]["local_parent_total_replicates_nM"] = [0.5, 0.8, 1.0, 1.2, 2.0, 13.7]  # mean*0.140 ~ 0.45 (passes mean!) but U95 >= 2.0 nM!
    chk("FAIL_GATE_B4_DAY21_REPLICATE_WASHOUT_U95_NOT_EXHAUSTED" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, **b4_bad_d21})})["failures"], "ADV_G41_b4_day21_replicate_u95_fails")
    # 15. B-4 post-Day-10 gap > 72 h (e.g. 240 -> 504 = 264 h gap) HOLDS!
    b4_hrs_gap2 = [2.0, 12.0, 24.0, 72.0, 144.0, 192.0, 240.0, 504.0]
    chk("HOLD_GATE_B4_INSUFFICIENT_TEMPORAL_COVERAGE_GAP_GT_72H" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "serial_pk_schedule_hours": b4_hrs_gap2, "serial_pk_local_parent_free_nM": b4_lpf[:7] + [0.45], "serial_pk_local_bmt_free_nM": b4_lbf[:7] + [0.005], "serial_pk_systemic_parent_total_nM": b4_spf[:7] + [0.01], "serial_pk_systemic_bmt_total_nM": b4_sbf[:7] + [0.01], **_mk_r8_b4_replicates(b4_hrs_gap2, b4_lpf[:7] + [0.45], b4_lbf[:7] + [0.005], b4_spf[:7] + [0.01], b4_sbf[:7] + [0.01])})})["holds"], "ADV_G41_b4_post_day10_gap_gt72h_holds")
    # 16. Two-analyte BLQ flag mismatch on systemic parent FAILS!
    b2b_bad_sp_blq = _mk_r8_b2b_replicates(); b2b_bad_sp_blq["timepoint_replicate_records"][0]["systemic_parent_blq_flags"] = [False] * 6  # 0.032 < 0.05 LLOQ unflagged!
    chk("FAIL_GATE_B2B_BENCH_UNFLAGGED_BLQ_SYS_PARENT_REPLICATE:0" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, **b2b_bad_sp_blq})})["failures"], "ADV_G41_b2b_two_analyte_sys_parent_blq_fails")
    # 17. Triggered mixture receipt with narrower mixture window (csafe=18.0 < 19.5 claimed) OR wrong ratio range FAILS!
    mix_narrow = _sign_receipt({**mix_rcpt_ok, "mixture_c_safe_max_l95_free_nM": 18.0, "mixture_dose_response_evidence": _mk_mix_dr(0.0, 0.25, 6.5, 18.0)})
    chk("FAIL_GATE_B2B_BENCH_EXPOSURE_BREACHES_TRIGGERED_MIXTURE_WINDOW" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "c_bmt_local_total_u_alloc_nM": 0.25, "mixture_requalified": True, "mixture_requalification_receipt": mix_narrow})})["failures"], "ADV_G41_b2b_mixture_window_enforced")
    mix_wrong_ratio = _sign_receipt({**mix_rcpt_ok, "tested_bmt_to_parent_ratio_min": 0.10, "tested_bmt_to_parent_ratio_max": 0.20})
    chk("FAIL_GATE_B2B_BENCH_MIXTURE_REQUAL_RATIO_DOES_NOT_COVER_OBSERVED_BMT_PARENT" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "c_bmt_local_total_u_alloc_nM": 0.25, "mixture_requalified": True, "mixture_requalification_receipt": mix_wrong_ratio})})["failures"], "ADV_G41_b2b_mixture_ratio_coverage_enforced")
    # 18. Readout-3B missing HLA-E SPR affinity OR KIR+/- adaptive lysis > 10% FAILS!
    r3b_no_spr = {k: v for k, v in _mk_r8_readout3b(include_sirpa_low=True, matched_vehicle_lot_id=bv_b).items() if k != "hla_e_spr_affinity_evidence"}
    chk("FAIL_GATE_B3_READOUT3B_MISSING_HLAE_SPR_AFFINITY_EVIDENCE" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b3_evidence": _sign_receipt({**b3_y, "readout3b_evidence": r3b_no_spr})})["failures"], "ADV_G41_b3_r3b_missing_spr_fails")

    # --- GATE-42 Regressions (6 tests) ---
    # 19. Omitting comparator_nt_lot_id from C-1 FAILS immediately (never falls back to optional None)!
    c1_no_nt = _sign_receipt({k: v for k, v in c1_y.items() if k != "comparator_nt_lot_id"})
    chk("FAIL_GATE42_MISSING_MANDATORY_COMPARATOR_NT_LOT_ID" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": c1_no_nt})["failures"], "ADV_G42_missing_c1_comparator_nt_lot_fails")
    # 20. IIP-0049 missing Stage-1 gatekeeper record OR Stage-2 block manifest OR quantitative IL-1 control FAILS!
    chk("FAIL_IIP0049_MISSING_STAGE1_GATEKEEPER_RECORD" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _sign_receipt({**att_y, "stage1_gatekeeper_record": None})})["failures"], "ADV_G42_iip0049_missing_stage1_fails")
    chk("FAIL_IIP0049_MISSING_STAGE2_BLOCK_MANIFEST" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _sign_receipt({**att_y, "stage2_block_manifest": None})})["failures"], "ADV_G42_iip0049_missing_block_manifest_fails")
    # 21. C-1 caspase-9 reduction mismatch vs raw paired measurements OR missing locked analysis plan FAILS!
    c1_bad_c9raw = {**c1_norm_6, "casp9_treated_raw_by_block": [90.0]*6}
    chk("FAIL_GATE_C1_NORMOXIA_CASP9_REDUCTION_MISMATCH_VS_RAW_PAIRS" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": c1_bad_c9raw})})["failures"], "ADV_G42_c1_raw_casp9_mismatch_fails")
    chk("FAIL_GATE_C1_MISSING_LOCKED_ANALYSIS_PLAN_ID" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "locked_analysis_plan_id": ""})})["failures"], "ADV_G42_c1_missing_locked_plan_fails")
    # 22. Safety switch missing cryptographic C-2 prerequisite digest pin FAILS!
    sw_no_c2pin = _mk_r8_switch(py, by, ly, ry, mat_yc, "2026-09-26T09:00:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y)
    chk("FAIL_GATE42_MISSING_C2_PREREQ_DIGEST_IN_NATIVE_SAFETY_SWITCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "native_switch_evidence": sw_no_c2pin})["failures"], "ADV_G42_switch_missing_c2_pin_fails")

    # --- GATE-43 Regressions (4 tests) ---
    # 23. D-2 identical numerical arrays across lots (with renamed block IDs!) FAILS!
    d2_lot2_copy = _mk_d2_lot(2, readout2_evidence=_mk_r8_readout2(matched_comparator_id="CTRL-LOT-2", block_prefix="D2L2", meas_id="MEAS-D2-LOT-2", lot_jitter=1.0))
    chk("FAIL_CHECK_D2_IDENTICAL_NUMERICAL_ARRAYS_ACROSS_LOTS:D2-LOT-2" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1), d2_lot2_copy, _mk_d2_lot(3)]})["failures"], "ADV_G43_d2_identical_numeric_arrays_fails")
    # 24. D-3(b) missing F3 knockdown target engagement (< 60%) FAILS!
    chk("FAIL_CHECK_D3B_TARGET_ENGAGEMENT_F3_KD_BELOW_60PCT" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "d3b_pilot_receipt": _sign_receipt({**d3b_rcpt_a, "f3_kd_pct_in_pilot": 20.0})})["failures"], "ADV_G43_d3b_low_f3_kd_fails")
    # 25. D-3(b) assay acquired before prerequisite FAILS!
    chk("FAIL_CHECK_D3B_ASSAY_ACQUIRED_BEFORE_GATE-31" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "d3b_pilot_receipt": _sign_receipt({**d3b_rcpt_a, "assay_acquired_at_utc": "2026-10-12T09:40:00Z"})})["failures"], "ADV_G43_d3b_acquired_before_g31_fails")
    # 26. D-3(b) ASSEMBLED_ROUTE_QUALIFICATION without D-3(a) evaluated FAILS!
    g43_no_d3a = {k: v for k, v in g43_full_a.items() if k != "check_d3a_per_lot_records"}
    g43_no_d3a["check_d3a_status"] = "NOT_ATTEMPTED"
    chk("FAIL_CHECK_D3B_ASSEMBLED_REQUIRES_D3A_EVALUATED_FIRST" in evaluate_gate43_cellgemma_guardrails_and_pilots(g43_no_d3a)["failures"], "ADV_G43_d3b_assembled_requires_d3a_fails")
    # 27. GATE-36 live GATE-32 residual class-II > 0.30 OR exogenous shield not excluded FAILS!
    chk("FAIL_FOUNDRY_V2_GATE36_LIVE_GATE32_RESIDUAL_CLASS2_EXCEEDS_0P30" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "foundry_v2_gate36_evidence": _sign_receipt({**g36_y, "live_gate32_debris_recall_receipt": _sign_receipt({**g32_y, "residual_class2_recall_u95_frac": 0.35})})})["failures"], "ADV_G42_g36_g32_residual_class2_fails")
    chk("FAIL_FOUNDRY_V2_GATE36_EXOGENOUS_SHIELD_NOT_EXCLUDED" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "foundry_v2_gate36_evidence": _sign_receipt({**g36_y, "exogenous_shield_excluded_from_drug_free_scope": False})})["failures"], "ADV_G42_g36_exogenous_shield_excluded_fails")
    # 28. GY / Coated deferred X/R1 GATE-31 missing quantitative coating stability FAILS!
    g31_x_nocoat = _sign_receipt({k: v for k, v in g31_x.items() if k != "coating_stability_evidence"})
    chk("FAIL_DEFERRED_X_R1_GATE31_MISSING_QUANTITATIVE_COATING_STABILITY_EVIDENCE" in evaluate_gate40_pirfenidone_h4({**g40_x, "gate31_evidence": g31_x_nocoat})["failures"], "ADV_G40_x_r1_missing_coating_stability_fails")


    # ========================================================================
    # ADVERSARIAL REGRESSION SUITE (22 NEW TESTS -> 461/461 TOTAL!)
    # Adversarial fail-closed invariant regression tests.
    # ========================================================================
    # --- Shared DEC-134 Raw Washout Trace Reconciliation (3 tests) ---
    # 1. Contradictory DEC-134 raw washout trace (95% @ 4.5m, 90% @ 11m, 80% @ 15m, claiming t50=3.6, t90=9.2) FAILS in GATE-43 D-2!
    r2_bad_w = _mk_r8_readout2(matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1", lot_jitter=1.0)
    r2_bad_w["dec134_washout_time_min_series"] = [0.0, 4.5, 11.0, 15.0, 20.0]
    r2_bad_w["dec134_washout_remaining_peak_pct_series"] = [100.0, 95.0, 90.0, 80.0, 5.0]
    r2_bad_w["dec134_washout_raw_trace_sha256"] = sha256_bytes(canonical_json_bytes({"time_min": r2_bad_w["dec134_washout_time_min_series"], "remaining_peak_pct": r2_bad_w["dec134_washout_remaining_peak_pct_series"]}))
    r2_bad_w["dec134_washout_tail_remaining_pct"] = 5.0
    chk("FAIL_CHECK_D2_D2-LOT-1_READOUT2_DEC134_WASHOUT_TAIL_FAILED" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, readout2_evidence=r2_bad_w), _mk_d2_lot(2), _mk_d2_lot(3)]})["failures"], "ADV_shared_r2_contradictory_dec134_trace_fails")
    # 2. Tampered DEC-134 raw_trace_sha256 FAILS in Readout-2!
    r2_bad_wsha = _mk_r8_readout2(matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1", lot_jitter=1.0)
    r2_bad_wsha["dec134_washout_raw_trace_sha256"] = "9" * 64
    chk("FAIL_CHECK_D2_D2-LOT-1_READOUT2_DEC134_WASHOUT_TAIL_FAILED" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, readout2_evidence=r2_bad_wsha), _mk_d2_lot(2), _mk_d2_lot(3)]})["failures"], "ADV_shared_r2_tampered_dec134_sha_fails")
    # 3. Contradictory DEC-134 raw washout trace in GATE-31 whole_device_washout_dec134 FAILS!
    g31_bad_w = _sign_receipt({**g31_a_42, "whole_device_washout_dec134": {**g31_a_42["whole_device_washout_dec134"], "time_min_series": [0.0, 4.5, 11.0, 15.0, 20.0], "remaining_peak_pct_series": [100.0, 95.0, 90.0, 80.0, 5.0], "raw_trace_sha256": sha256_bytes(canonical_json_bytes({"time_min": [0.0, 4.5, 11.0, 15.0, 20.0], "remaining_peak_pct": [100.0, 95.0, 90.0, 80.0, 5.0]})), "tail_remaining_pct": 5.0}})
    chk("FAIL_R1_GATE31_DEC134_WASHOUT_FAILED" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "gate31_evidence": g31_bad_w})["failures"], "ADV_shared_g31_contradictory_dec134_trace_fails")

    # --- GATE-40 Regressions (6 tests) ---
    # 4. Exact monotone 24-h supremum on [0, 12, 36, 48] / [0, 0, 1, 2] returns 2.0 mg (never 1.0 mg!)
    chk(abs(_recompute_max_24h_cumulative_mg([0.0, 12.0, 36.0, 48.0], [0.0, 0.0, 1.0, 2.0]) - 2.0) < 1e-9, "ADV_G40_exact_monotone_24h_supremum_2p0mg")
    # 5. A-1 t50 crossing bracket straddling 7.0 d (e.g. [5.0, 9.0] d) HOLDS even when declared t50=8.0 d!
    tr_strad_t = [0.0, 1.0, 3.0, 6.0, 12.0, 24.0, 48.0, 120.0, 216.0, 336.0, 528.0, 840.0]
    tr_strad_m = [0.0, 0.2, 0.45, 0.75, 1.2, 1.8, 3.0, 7.0, 10.5, 13.5, 16.3, 17.6]  # half=8.8 crosses inside [120h=5d, 216h=9d]!
    chk("HOLD_GATE_A1_T50_CROSSING_BRACKET_STRADDLES_7_TO_14D_WINDOW" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "elution_time_hours": tr_strad_t, "cumulative_intact_parent_released_mg": tr_strad_m, "elution_t50_days": 8.0})})["holds"], "ADV_G40_a1_t50_straddling_bracket_holds")
    # 6. Raw recomputed Day-35 exhaustion <= 90% (1.90/18.75=10.13% residual -> 89.87% exh) FAILS even if declared 90.2%!
    chk("FAIL_GATE_A1_RAW_RECOMPUTED_DAY35_EXHAUSTION_LE_90PCT" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "day35_residual_parent_mg": 1.90, "day35_residual_parent_pct": 9.8, "day35_depot_exhaustion_pct": 90.2, "day35_terminal_mass_recovery_pct": 104.0})})["failures"], "ADV_G40_a1_raw_recomp_day35_le90_fails")
    # 7. Gap: A-0a raw concentration-response ceiling above max safe tested FAILS!
    chk("FAIL_GATE_A0A_RAW_CONC_RESPONSE_CONTRADICTS_BRACKET_OR_CEILING" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "cc10_free_7d_l95_uM": 400.0, "c_sprout_max_free_7d_l95_uM": 380.0, "c_upper_provisional_7d_l95_uM": 380.0})})["failures"], "ADV_G40_a0a_ceiling_above_safe_tested_fails")
    # 8. Gap: A-4a missing >= 3 donor pairs FAILS!
    chk("FAIL_GATE_A4A_REQUIRES_AT_LEAST_3_DONOR_PAIRS" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4a_evidence": _sign_receipt({**a4a_y, "donor_pair_records": a4a_y["donor_pair_records"][:2]})})["failures"], "ADV_G40_a4a_lt3_donor_pairs_fails")
    # 9. Gap: A-4b longitudinal shared animal with mismatched implanted_at_utc FAILS!
    prereg_l10, coh_l10 = _mk_r8_a4b_prereg_and_cohorts(py, by, ly, ry, a4a_y, coat_a, mode="VALIDATED_NONTERMINAL_LONGITUDINAL_IMAGING")
    coh_l10_bad = {**coh_l10, "day28_cohort_records": [{**coh_l10["day28_cohort_records"][0], "implanted_at_utc": "2026-12-20T09:00:00Z"}, *coh_l10["day28_cohort_records"][1:]]}
    chk("FAIL_GATE_A4B_LONGITUDINAL_IMPLANT_EVENT_MISMATCH:L-COAT-01" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_preregistration_receipt": prereg_l10, "a4b_evidence": _sign_receipt({**a4b_y, "prerequisite_receipt_sha256s": {**pr_all_y, "A-4b-PREREGISTRATION": prereg_l10["receipt_sha256"]}, **coh_l10_bad})})["failures"], "ADV_G40_a4b_longitudinal_implant_mismatch_fails")

    # --- GATE-41 Regressions (6 tests) ---
    # 10. B-0a claiming 49 nM C_safe_max when last tested safe is 25 nM (first unsafe 50 nM) FAILS!
    chk("FAIL_GATE_B0A_CSAFE_EXCEEDS_QUALIFIED_TESTED_SAFE_CONC" in evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": _sign_receipt({**b0a_ok, "c_safe_max_bench_l95_free_nM": 49.0})})["failures"], "ADV_G41_b0a_49nM_above_25nM_safe_fails")
    # 11. B-0a-exact claiming 44 nM when last tested safe cassette conc is 22 nM FAILS!
    chk("FAIL_GATE_B0A_EXACT_CSAFE_EXCEEDS_QUALIFIED_TESTED_SAFE_CONC" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b0a_exact_evidence": _sign_receipt({**b0a_ex_y, "c_safe_max_exact_l95_free_nM": 44.0})})["failures"], "ADV_G41_b0a_exact_44nM_above_22nM_safe_fails")
    # 12. Short first gap (3 h) + wide later gap (72 h) with t_half=10h (ke=0.0693, kr=0.0693) breaches local ceiling!
    def _mk_env_t(**kw: Any) -> dict[str, Any]:
        eb = {
            "coating_article_id": "ART-DEUC-R3P-01", "evidence_scope": "bench_unedited",
            "compartment_id": "BENCH_ELUTION_RECIRCULATION",
            "envelope_qualification_method": "DENSE_PILOT_TIMECOURSE_BOUND",
            "pilot_sampling_max_gap_h": 1.0,
            "k_elim_bmt_max_per_h": 0.020, "k_rise_bmt_max_per_h": 0.020,
            "burst_phase_covered": True, "washout_phase_covered": True, "source_study_ids": ["PK-TEST-1"], **kw,
        }
        return {**eb, "envelope_receipt_sha256": sha256_bytes(canonical_json_bytes(eb))}
    env_late_pk = _validate_and_apply_continuous_pk_envelope(
        _mk_env_t(k_elim_local_max_per_h=0.0693, k_rise_local_max_per_h=0.0693, k_elim_parent_max_per_h=0.0693, k_rise_parent_max_per_h=0.0693, k_elim_sys_max_per_h=0.0693, k_rise_sys_max_per_h=0.0693, efficacy_window_start_h=0.0, envelope_model_sha256="a" * 64),
        hours_seen=[3.0, 75.0, 240.0], u_local_series=[2.0, 0.758, 0.5], l_parent_all_series=[1.5, 0.5, 0.3], u_sys_series=[0.1, 0.1, 0.05], max_efficacy_start_h=6.0, fails=[], holds=[], prefix="T",
    )
    chk(env_late_pk is not None and env_late_pk[0] > 3.0, "ADV_G41_continuous_late_gap_peak_catches_hidden_spike")
    # 13. Systemic 0.348 nM after 12-h gap with 10-h half-life (ke_sys=0.0693) breaches 0.50 nM cap (>= 0.80 nM)!
    env_sys_pk = _validate_and_apply_continuous_pk_envelope(
        _mk_env_t(k_elim_local_max_per_h=0.012, k_rise_local_max_per_h=0.002, k_elim_parent_max_per_h=0.012, k_rise_parent_max_per_h=0.002, k_elim_sys_max_per_h=0.0693, k_rise_sys_max_per_h=0.0693, efficacy_window_start_h=0.0, envelope_model_sha256="a" * 64),
        hours_seen=[12.0, 24.0, 240.0], u_local_series=[10.0, 9.0, 8.0], l_parent_all_series=[8.0, 7.0, 6.5], u_sys_series=[0.348, 0.20, 0.05], max_efficacy_start_h=6.0, fails=[], holds=[], prefix="T",
    )
    chk(env_sys_pk is not None and env_sys_pk[2] >= 0.50, "ADV_G41_continuous_systemic_envelope_catches_0p80nM_peak")
    # 14. B-0b loaded API below quantitative mass requirement FAILS!
    chk("FAIL_GATE_B0B_LOADED_API_BELOW_QUANTITATIVE_MASS_REQUIREMENT" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b0b_evidence": _sign_receipt({**b0b_y, "loaded_api_mass_mg": 0.5})})["failures"], "ADV_G41_b0b_insufficient_loaded_api_fails")
    # 15. B-2b missing local_measurement_includes_recirculation flag FAILS!
    chk("FAIL_GATE_B2B_BENCH_MISSING_RECIRCULATION_ACCOUNTING_FLAG" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({k: v for k, v in b2bb_y.items() if k != "local_measurement_includes_recirculation"})})["failures"], "ADV_G41_b2b_missing_recirc_flag_fails")

    # --- GATE-42 Regressions (4 tests) ---
    # 16. Stage-2 block study_start_utc predating Stage-1 decision_recorded_at_utc FAILS!
    att_s2_early = _sign_receipt({**att_y, "stage2_block_manifest": [{**att_y["stage2_block_manifest"][0], "study_start_utc": "2026-09-14T07:00:00Z"}, *att_y["stage2_block_manifest"][1:]]})
    chk("FAIL_IIP0049_STAGE2_STARTED_BEFORE_STAGE1_DECISION:0" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": att_s2_early})["failures"], "ADV_G42_stage2_predates_stage1_fails")
    # 17. Adverse raw caspase-9 increase (mean(ctrl-tr) < 0) with mean % reduction >= 40% FAILS (cannot corroborate protection!)
    c1_adv = {**c1_norm_6, "casp9_stressed_ctrl_raw_by_block": [10.0, 10.0, 10.0, 10.0, 10.0, 1000.0], "casp9_treated_raw_by_block": [4.0, 4.0, 4.0, 4.0, 4.0, 1300.0], "casp9_reduction_pct_by_block": [60.0, 60.0, 60.0, 60.0, 60.0, -30.0]}
    chk("FAIL_GATE_C1_NORMOXIA_ADVERSE_OR_ZERO_RAW_CASP9_DIRECTION" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": c1_adv})})["failures"], "ADV_G42_c1_adverse_raw_casp9_direction_fails")
    # 18. Missing keyed reference_comparator_measurements FAILS!
    chk("FAIL_IIP0049_MISSING_KEYED_REFERENCE_COMPARATOR_MEASUREMENTS" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _sign_receipt({**att_y, "reference_comparator_measurements": None})})["failures"], "ADV_G42_missing_keyed_comparator_meas_fails")
    # 19. GATE-42 C-3-NK missing mandatory SIRPa-low NK endpoint FAILS!
    chk("FAIL_GATE_C3_NK_READOUT3B_R1_SIRPA_LOW_LYSIS_GT_10PCT:NK-D1" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c3_nk_evidence": _sign_receipt({**c3_nk_y, "readout3b_evidence": _mk_r8_readout3b(include_sirpa_low=False)})})["failures"], "ADV_G42_c3_nk_missing_sirpa_low_fails")

    # --- GATE-43 Regressions (3 tests) ---
    # 20. D-3(a) missing timestamps FAILS; D-3(b) assembled missing D-3(a) digest binding OR predating D-3(a) FAILS!
    chk("FAIL_CHECK_D3A_INVALID_OR_MISSING_TIMESTAMPS:IEC-LOT-1" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": [_sign_receipt({k: v for k, v in d3a_ok_lots[0].items() if k not in ("assay_acquired_at_utc", "recorded_at_utc")}), d3a_ok_lots[1], d3a_ok_lots[2]]})["failures"], "ADV_G43_d3a_missing_timestamps_fails")
    chk("FAIL_CHECK_D3B_ASSEMBLED_MISSING_D3A_RECEIPT_DIGEST_BINDING" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "d3b_pilot_receipt": _sign_receipt({k: v for k, v in d3b_rcpt_a.items() if k != "d3a_lot_receipt_sha256s"})})["failures"], "ADV_G43_d3b_missing_d3a_digest_pin_fails")
    # 21. D-2 reused matched_control_lot_id across independent lots FAILS!
    chk("FAIL_CHECK_D2_REUSED_MATCHED_CONTROL_LOT_ACROSS_LOTS:D2-LOT-2" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1), _mk_d2_lot(2, mctrl_override="CTRL-LOT-1"), _mk_d2_lot(3)]})["failures"], "ADV_G43_d2_reused_ctrl_lot_fails")


    # ========================================================================
    # ADVERSARIAL REGRESSION SUITE (24 NEW TESTS -> 485/485 TOTAL!)
    # Adversarial fail-closed invariant regression tests.
    # ========================================================================
    # --- Shared Live Readout-2 Parity (4 tests) ---
    # 1. Decisive: Missing pure-endocrine OCR HOLDS; qualifying whole-prep (3.45 <= 4.5479) + pure-endocrine breach (4.20 > 3.9547) FAILS!
    r2_no_pe = _mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B", lot_id=ly)
    r2_no_pe["gate_resp1_pure_endocrine_ocr_record"] = None
    chk("HOLD_GATE_A2_READOUT2_PURE_ENDOCRINE_OCR_MISSING" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": r2_no_pe})})["holds"], "ADV_shared_r2_missing_pure_endocrine_ocr_holds")
    r2_pe_hi = _mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B", lot_id=ly, pure_endocrine_ocr=4.20)
    chk("FAIL_GATE_A2_READOUT2_PURE_ENDOCRINE_OCR_EXCEEDS_3P9547" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": r2_pe_hi})})["failures"], "ADV_shared_r2_pure_endocrine_ocr_4p20_fails")
    # 2. Major: Missing cluster-surface O2/morphometry HOLDS; outer-band D_p90 = 115 um (> 100 um) FAILS!
    r2_no_morph = _mk_r8_readout2(matched_comparator_id=nt_y, block_prefix="C3G", lot_id=ly, stage7_start_utc="2026-09-12T00:00:00Z", sort_reaggregation_utc="2026-09-22T00:00:00Z", assay_harvest_utc="2026-10-01T00:00:00Z")
    r2_no_morph["cluster_surface_o2_and_morphometry_record"] = None
    chk("HOLD_GATE_C3_GSIS_READOUT2_MISSING_CLUSTER_SURFACE_O2_MORPHOMETRY" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c3_gsis_evidence": _sign_receipt({**c3_gsis_y, "readout2_evidence": r2_no_morph})})["holds"], "ADV_shared_r2_missing_morphometry_holds")
    r2_bad_morph = _mk_r8_readout2(matched_comparator_id=nt_y, block_prefix="C3G", lot_id=ly, stage7_start_utc="2026-09-12T00:00:00Z", sort_reaggregation_utc="2026-09-22T00:00:00Z", assay_harvest_utc="2026-10-01T00:00:00Z")
    mb_bad = {k: v for k, v in r2_bad_morph["cluster_surface_o2_and_morphometry_record"].items() if k != "record_sha256"}
    mb_bad["outer_band_d_p90_um"] = 115.0
    r2_bad_morph["cluster_surface_o2_and_morphometry_record"] = {**mb_bad, "record_sha256": sha256_bytes(canonical_json_bytes(mb_bad))}
    chk("FAIL_GATE_C3_GSIS_READOUT2_CLUSTER_SURFACE_O2_OR_MORPHOMETRY_FAILED" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c3_gsis_evidence": _sign_receipt({**c3_gsis_y, "readout2_evidence": r2_bad_morph})})["failures"], "ADV_shared_r2_outer_band_dp90_gt100_fails")

    # --- Shared Live GATE-31 (DEC-134) Cross-Evaluator Parity (5 tests) ---
    # 3. Decisive: Pre-cure catalase = 160,000 IU (> 158,300 IU cap) FAILS (matching live DEC-134)!
    chk("FAIL_R1_GATE31_PRE_CURE_CATALASE_EXCEEDS_158300IU_CAP" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "gate31_evidence": _sign_receipt({**g31_a_42, "pre_cure_catalase_load_iu_333cm2": 160000.0})})["failures"], "ADV_shared_g31_precure_cat_160k_fails")
    # 4. Decisive: Open-sink U95 = 69.9199 h (> 68.0 h window) FAILS (matching live DEC-134)!
    chk("FAIL_R1_GATE31C_OPEN_SINK_HALFLIFE_OUT_OF_34_68H" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "gate31_evidence": _sign_receipt({**g31_a_42, "gate31c_open_sink_halflife_u95_h": 69.9199})})["failures"], "ADV_shared_g31_open_sink_u95_69p92_fails")
    # 5. Decisive: Missing open-sink peroxide site provenance HOLDS (matching live DEC-134)!
    g31_no_os_site = _sign_receipt({**g31_a_42, "obs_open_sink_h2o2_measurement_site": None})
    d3b_no_os_site = _sign_receipt({**d3b_rcpt_a, "prerequisite_receipt_sha256s": {**d3b_rcpt_a["prerequisite_receipt_sha256s"], "GATE-31": g31_no_os_site["receipt_sha256"]}})
    r_g31_site = evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "gate31_evidence": g31_no_os_site, "d3b_pilot_receipt": d3b_no_os_site})
    chk(r_g31_site["verdict"] == "HOLD" and "HOLD_R1_GATE31_H2O2_NOT_AT_Z70P0_INTERFACE:OPEN_SINK" in r_g31_site["holds"], "ADV_shared_g31_missing_open_sink_site_holds")
    # 6. Decisive: Decoupled open_sink_lot_id FAILS; SEALED_CHAMBER_ONLY HOLDS (1:1 live parity)!
    chk("FAIL_R1_GATE31_DECOUPLED_LOT_MISMATCH:open_sink_lot_id" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "gate31_evidence": _sign_receipt({**g31_a_42, "open_sink_lot_id": "OTHER-LOT"})})["failures"], "ADV_shared_g31_decoupled_lot_fails")
    g31_sealed = _sign_receipt({**g31_a_42, "kinetics_assay_regime": "SEALED_CHAMBER_ONLY"})
    d3b_sealed = _sign_receipt({**d3b_rcpt_a, "prerequisite_receipt_sha256s": {**d3b_rcpt_a["prerequisite_receipt_sha256s"], "GATE-31": g31_sealed["receipt_sha256"]}})
    chk("HOLD_R1_GATE31_SEALED_CHAMBER_ONLY_OPEN_SINK_REQUIRED" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "gate31_evidence": g31_sealed, "d3b_pilot_receipt": d3b_sealed})["holds"], "ADV_shared_g31_sealed_chamber_holds")

    # --- GATE-40 Regressions (4 tests) ---
    # 7. A-0a missing donor replicates HOLDS; noisy potency replicates with L95 < 50% at IC50_U95 HOLDS!
    chk("HOLD_GATE_A0A_MISSING_DONOR_REPLICATES_OR_FIT_ARTIFACT" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "a0a_donor_replicates_by_conc": None})})["holds"], "ADV_G40_a0a_missing_donors_holds")
    a0a_noisy = [dict(r) for r in a0a_reps_ok]
    a0a_noisy[3] = {**a0a_noisy[3], "alpha_sma_inhibition_pct": [39.0, 46.5, 54.0, 61.5, 69.0]}  # mean=54% >= 50%, but L95_t = 28.7% < 50%!
    a0a_fit_noisy = _sign_receipt({**a0a_fit_ok, "raw_replicates_sha256": sha256_bytes(canonical_json_bytes(a0a_noisy))})
    chk("HOLD_GATE_A0A_IC50_U95_UNSUBSTANTIATED_BY_DONOR_REPLICATES" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "a0a_donor_replicates_by_conc": a0a_noisy, "a0a_fit_artifact_receipt": a0a_fit_noisy})})["holds"], "ADV_G40_a0a_noisy_potency_l95_lt50_holds")
    # 8. A-4b missing locked missing-data sensitivity rule in preregistration FAILS!
    prereg_no_md = _sign_receipt({k: v for k, v in a4b_prereg_y.items() if k != "missing_data_sensitivity_rule"})
    a4b_no_md = _sign_receipt({**a4b_y, "prerequisite_receipt_sha256s": {**pr_all_y, "A-4b-PREREGISTRATION": prereg_no_md["receipt_sha256"]}})
    chk("FAIL_GATE_A4B_PREREG_MISSING_LOCKED_MISSING_DATA_RULE" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_preregistration_receipt": prereg_no_md, "a4b_evidence": a4b_no_md})["failures"], "ADV_G40_a4b_missing_locked_md_rule_fails")
    # 9. A-4b differential/informative attrition (2 missing coated animals flipping worst-case tipping point below 35%) HOLDS!
    prereg_att = _sign_receipt({
        **a4b_prereg_y,
        "randomized_animal_roster": {**a4b_prereg_y["randomized_animal_roster"], "D28-COAT-09": "COATED", "D28-COAT-10": "COATED"},
        "day28_cohort_assigned_ids": [*a4b_prereg_y["day28_cohort_assigned_ids"], "D28-COAT-09", "D28-COAT-10"],
    })
    a4b_att = _sign_receipt({
        **a4b_y,
        "prerequisite_receipt_sha256s": {**pr_all_y, "A-4b-PREREGISTRATION": prereg_att["receipt_sha256"]},
        "day28_cohort_enrolled_coated_n": 10,
        "day28_cohort_exclusions": [
            {"animal_id": "D28-COAT-09", "arm": "COATED", "reason": "SAMPLE_LOSS_PRE_ADJUDICATION", "pre_adjudication_decision": True, "excluded_at_utc": "2026-12-21T09:00:00Z", "adverse_event_related": False, "adverse_event_code": "NONE"},
            {"animal_id": "D28-COAT-10", "arm": "COATED", "reason": "SAMPLE_LOSS_PRE_ADJUDICATION", "pre_adjudication_decision": True, "excluded_at_utc": "2026-12-22T09:00:00Z", "adverse_event_related": False, "adverse_event_code": "NONE"},
        ],
    })
    r_att = evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_preregistration_receipt": prereg_att, "a4b_evidence": a4b_att})
    chk("HOLD_GATE_A4B_DAY28_INFORMATIVE_ATTRITION_SENSITIVITY_NOT_ROBUST" in r_att["holds"], "ADV_G40_a4b_tipping_point_attrition_holds")

    # --- GATE-41 Regressions (5 tests) ---
    # 10. Exact censor-aware Student-t on (BLQ, 1, 1) with LLOQ=1.0 returns 1.6400 (NOT 1.000!)
    u_r2_ce = censor_aware_t_bound([(0.0, 1.0), (1.0, 1.0), (1.0, 1.0)], alpha=0.05, upper=True)
    chk(u_r2_ce is not None and abs(u_r2_ce - 1.63999519) < 1e-4, "ADV_G41_exact_censor_aware_student_t_1p640")
    # 11. Early nominal Day-10 sample at 228 h (followed by 312 h post-depletion) catches 228->240 h trough drop!
    env_228 = _validate_and_apply_continuous_pk_envelope(
        _mk_env_t(k_elim_local_max_per_h=0.015, k_rise_local_max_per_h=0.002, k_elim_parent_max_per_h=0.015, k_rise_parent_max_per_h=0.005, k_elim_sys_max_per_h=0.025, k_rise_sys_max_per_h=0.003, efficacy_window_start_h=0.0, envelope_model_sha256="e" * 64),
        hours_seen=[6.0, 228.0, 312.0], u_local_series=[15.0, 8.0, 4.0], l_parent_all_series=[12.0, 6.2, 2.5], u_sys_series=[0.1, 0.1, 0.05], max_efficacy_start_h=6.0, fails=[], holds=[], prefix="T228",
    )
    chk(env_228 is not None and env_228[1] < 6.0, "ADV_G41_parent_228_to_240h_straddle_trough_caught")
    # Missing coverage through 240.0 h (last sample 228 h) HOLDS!
    h_uncov: list[str] = []
    _validate_and_apply_continuous_pk_envelope(
        _mk_env_t(k_elim_local_max_per_h=0.015, k_rise_local_max_per_h=0.002, k_elim_parent_max_per_h=0.015, k_rise_parent_max_per_h=0.002, k_elim_sys_max_per_h=0.025, k_rise_sys_max_per_h=0.003, efficacy_window_start_h=0.0, envelope_model_sha256="e" * 64),
        hours_seen=[6.0, 228.0], u_local_series=[15.0, 8.0], l_parent_all_series=[12.0, 7.0], u_sys_series=[0.1, 0.1], max_efficacy_start_h=6.0, fails=[], holds=h_uncov, prefix="T228",
    )
    chk("HOLD_T228_PARENT_EFFICACY_WINDOW_UNCOVERED_THROUGH_240H" in h_uncov, "ADV_G41_uncovered_240h_endpoint_holds")
    # 12. b: Parent BLQ with positive BMT produces unbounded BMT/parent ratio -> HOLDS!
    b2b_pblq = _mk_r8_b2b_replicates()
    b2b_pblq["timepoint_replicate_records"][-1]["local_parent_total_replicates_nM"] = [0.02] * 6
    b2b_pblq["timepoint_replicate_records"][-1]["local_parent_blq_flags"] = [True] * 6
    chk("HOLD_GATE_B2B_BENCH_UNBOUNDED_BMT_TO_PARENT_RATIO_UNDER_PARENT_BLQ" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, **b2b_pblq})})["holds"], "ADV_G41_unbounded_bmt_parent_ratio_under_blq_holds")
    # 13. B-0a noisy efficacy replicates (mean 68% but L95_t < 50% at EC50_U95) HOLDS!
    b0a_e_noisy = [dict(r) for r in b0a_e_reps_ok]
    _noisy_vals = [48.0, 56.0, 64.0, 72.0, 80.0, 88.0]
    b0a_e_noisy[3] = {**b0a_e_noisy[3], "iec_ibmir_marker_suppression_pct": _noisy_vals, "raw_unit_measurements": {**b0a_e_noisy[3]["raw_unit_measurements"], "iec_ibmir_marker_suppression_pct": _mk_b0a_raw_ratio(_noisy_vals, b0a_e_noisy[3]["matched_vehicle_record_id"], 250.0, is_inhib=True)}}
    b0a_an_noisy = _sign_receipt({**b0a_an_ok, "raw_efficacy_replicates_sha256": sha256_bytes(canonical_json_bytes(b0a_e_noisy))})
    chk("HOLD_GATE_B0A_EC50_U95_UNSUBSTANTIATED_BY_EFFICACY_REPLICATES" in evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": _sign_receipt({**b0a_ok, "efficacy_replicates_by_conc": b0a_e_noisy, "b0a_analysis_receipt": b0a_an_noisy})})["holds"], "ADV_G41_b0a_noisy_efficacy_l95_lt50_holds")

    # --- GATE-42 Regressions (4 tests) ---
    # 14. Reduced 2-background comparator list (omitting DESIGN_A / MULTI_MIR / STANDALONE / CD64T_IL1RN) FAILS!
    chk("FAIL_IIP0049_MISSING_REFERENCE_COMPARATOR_BACKGROUNDS" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _sign_receipt({**att_y, "reference_comparator_backgrounds": ["PARENTAL_UNEDITED", "EXACT_PRODUCT_FOUNDRY_V2"]})})["failures"], "ADV_G42_reduced_2bg_comparator_fails")
    # 15. Missing C-1 preregistered plan receipt HOLDS; skewed outlier paired-t normality violation HOLDS recommending exact sign-flip!
    chk("HOLD_GATE_C1_PREREGISTERED_PLAN_RECEIPT_MISSING" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_preregistered_plan_receipt": None})["holds"], "ADV_G42_missing_c1_prereg_holds")
    c1_skew = _mk_r8_c1_block(assay_record_id="C1-NORM-SKEW", bids=["B1", "B2", "B3", "B4", "B5", "B6"], c9_vec=[51.0, 55.0, 49.0, 54.0, 52.0, 56.0], ctrl_vec=[50.0, 50.0, 50.0, 50.0, 50.0, 50.0], tr_vec=[65.0, 65.1, 65.0, 65.2, 65.1, 99.0], veh_vec=[99.5]*6, comp_vec=[60.0]*6)
    chk("HOLD_GATE_C1_NORMOXIA_PAIRED_T_NORMALITY_NOT_MET_USE_EXACT_SIGN_FLIP" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": c1_skew})})["holds"], "ADV_G42_c1_skewed_normality_holds")
    # 16. Major: C-2 quantitative proinsulin:insulin = 1.35 (> 1.15) FAILS even when granule_processing_preserved=True!
    chk("FAIL_GATE_C2_GRANULE_PROCESSING_DEGRADED" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "proinsulin_to_insulin_fold_vs_ctrl": 1.35})})["failures"], "ADV_G42_c2_quant_proinsulin_fails")

    # --- GATE-43 Regressions (2 tests -> total 485/485!) ---
    # 17. Missing unified D-1 paired assay receipt HOLDS; outer-vs-receipt handling mismatch FAILS!
    chk("HOLD_CHECK_D1_MISSING_UNIFIED_PAIRED_ASSAY_RECEIPT" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_paired_assay_receipt": None})["holds"], "ADV_G43_d1_missing_unified_receipt_holds")
    # 18. D-3(a) normalized CXCL10 / CD274 retention = 108.0% (> 100%, <= 200%) PASSES cleanly!
    d3a_108_lots = [_mk_d3a_lot(1, cxcl10_retention_pct=108.0, cd274_retention_pct=106.5), d3a_ok_lots[1], d3a_ok_lots[2]]
    d3b_108 = _sign_receipt({**d3b_rcpt_a, "d3a_lot_receipt_sha256s": [r["receipt_sha256"] for r in d3a_108_lots]})
    chk(evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": d3a_108_lots, "d3b_pilot_receipt": d3b_108})["verdict"] == "PASS_DESCRIPTIVE_PILOT_ZERO_ODDS_GY037_WARN_RETAINED", "ADV_G43_d3a_normalized_108pct_passes")


    # ========================================================================
    # ADVERSARIAL REGRESSION SUITE (24 NEW TESTS -> 509/509 TOTAL!)
    # Adversarial fail-closed invariant regression tests.
    # ========================================================================
    # --- Shared Live Readout-2 Parity (wetlab_contract.py 1:1 parity, 6 tests) ---
    # 1. Stage-7 total = 25 d (<= 28 d) & post-sort = 15 d (> 14 d!) MUST trigger Rule S8 + Gate 0M!
    r2_ps15_no_s8 = _mk_r8_readout2(
        matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1", lot_id="D2-LOT-1", lot_jitter=1.0,
        stage7_start_utc="2026-10-01T00:00:00Z", sort_reaggregation_utc="2026-10-11T00:00:00Z", assay_harvest_utc="2026-10-26T00:00:00Z",
        rule_s8=False,
    )
    chk("HOLD_CHECK_D2_D2-LOT-1_READOUT2_RULE_S8_MISSING_LOCKED_ANALYSIS_PLAN" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, readout2_evidence=r2_ps15_no_s8), _mk_d2_lot(2), _mk_d2_lot(3)]})["holds"], "ADV_shared_r2_post_sort_15d_total_25d_triggers_rule_s8")
    # 2. Rule S8 active WITHOUT per-lot earlier-window source records HOLDS!
    r2_s8_no_ew = _mk_r8_readout2(matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1", lot_id="D2-LOT-1", lot_jitter=1.0, rule_s8=True, stage7_start_utc="2026-10-01T00:00:00Z", sort_reaggregation_utc="2026-10-11T00:00:00Z", assay_harvest_utc="2026-10-26T00:00:00Z")
    r2_s8_no_ew.pop("rule_s8_earlier_window_records", None)
    chk("HOLD_CHECK_D2_D2-LOT-1_READOUT2_RULE_S8_MISSING_PER_LOT_EARLIER_WINDOW_RECORDS" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, readout2_evidence=r2_s8_no_ew), _mk_d2_lot(2), _mk_d2_lot(3)]})["holds"], "ADV_shared_r2_s8_missing_per_lot_earlier_window_holds")
    # 3. Earlier-window harvest >= assay_harvest_utc FAILS!
    r2_s8_bad_t = _mk_r8_readout2(matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1", lot_id="D2-LOT-1", lot_jitter=1.0, rule_s8=True, stage7_start_utc="2026-10-01T00:00:00Z", sort_reaggregation_utc="2026-10-11T00:00:00Z", assay_harvest_utc="2026-10-26T00:00:00Z")
    r2_s8_bad_t["rule_s8_earlier_window_records"][0]["early_harvest_utc"] = "2026-10-27T00:00:00Z"
    chk("FAIL_CHECK_D2_D2-LOT-1_READOUT2_RULE_S8_EARLIER_WINDOW_TIMING_OR_TRACE_INVALID:0" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, readout2_evidence=r2_s8_bad_t), _mk_d2_lot(2), _mk_d2_lot(3)]})["failures"], "ADV_shared_r2_s8_early_harvest_not_earlier_fails")
    # 4. Parity: REF_60_30_10 measured composition drift (beta=0.72) HOLDS requiring DEC-084!
    r2_comp_drift = _mk_r8_readout2(matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1", lot_id="D2-LOT-1", lot_jitter=1.0, beta_cell_fraction=0.72, alpha_cell_fraction=0.20, delta_cell_fraction=0.08)
    chk("HOLD_CHECK_D2_D2-LOT-1_READOUT2_COMPOSITION_DRIFT_REQUIRES_DEC084" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, readout2_evidence=r2_comp_drift), _mk_d2_lot(2), _mk_d2_lot(3)]})["holds"], "ADV_shared_r2_comp_drift_holds_dec084")
    # 5. Parity: Non-reference DEC084_M1_70_20_10 (n=8) missing linked DEC-084 receipt HOLDS!
    r2_d84_miss = _mk_r8_readout2(matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1", lot_id="D2-LOT-1", lot_jitter=1.0, registered_mixture_id="DEC084_M1_70_20_10", beta_cell_fraction=0.70, alpha_cell_fraction=0.20, delta_cell_fraction=0.10, n_blocks=8)
    chk("HOLD_CHECK_D2_D2-LOT-1_READOUT2_DEC084_MATCHED_AGE_MIXTURE_RECEIPT_MISSING" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, readout2_evidence=r2_d84_miss), _mk_d2_lot(2), _mk_d2_lot(3)]})["holds"], "ADV_shared_r2_dec084_nonref_missing_receipt_holds")
    # 6. Parity: Post-sort ZM447439 regimen mismatch OR missing pre-coassembly vascular check FAILS!
    r2_zm_bad = _mk_r8_readout2(matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1", lot_id="D2-LOT-1", lot_jitter=1.0, post_sort_zm_regimen="S7W0_ONLY_0UM_POST_SORT", post_sort_zm_uM=0.50, pre_coassembly_vasc_ok=False)
    r_zm_bad = evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, readout2_evidence=r2_zm_bad), _mk_d2_lot(2), _mk_d2_lot(3)]})
    chk("FAIL_CHECK_D2_D2-LOT-1_READOUT2_ZM447439_CONCENTRATION_REGIMEN_MISMATCH" in r_zm_bad["failures"] and "FAIL_CHECK_D2_D2-LOT-1_READOUT2_MISSING_PRE_COASSEMBLY_IEC_VASCULAR_FUNCTION" in r_zm_bad["failures"], "ADV_shared_r2_zm_regimen_and_pre_iec_vasc_fails")

    # --- GATE-40 Regressions (5 tests) ---
    # 7. Early-cohort adverse-event exclusion with explicit AE code HARD FAILS!
    prereg_ae_e = _sign_receipt({**a4b_prereg_y, "randomized_animal_roster": {**a4b_prereg_y["randomized_animal_roster"], "E-COAT-09": "COATED"}, "early_cohort_assigned_ids": [*a4b_prereg_y["early_cohort_assigned_ids"], "E-COAT-09"]})
    a4b_ae_e = _sign_receipt({**a4b_y, "prerequisite_receipt_sha256s": {**pr_all_y, "A-4b-PREREGISTRATION": prereg_ae_e["receipt_sha256"]}, "early_cohort_enrolled_coated_n": 9, "early_cohort_exclusions": [{"animal_id": "E-COAT-09", "arm": "COATED", "reason": "SAMPLE_LOSS_PRE_ADJUDICATION", "pre_adjudication_decision": True, "excluded_at_utc": "2026-12-21T09:00:00Z", "adverse_event_related": True, "adverse_event_code": "HEMORRHAGE"}]})
    chk("FAIL_GATE_A4B_EARLY_ADVERSE_EVENT_RELATED_EXCLUSION:E-COAT-09" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_preregistration_receipt": prereg_ae_e, "a4b_evidence": a4b_ae_e})["failures"], "ADV_G40_a4b_early_ae_exclusion_hard_fails")
    # 8. Day-28 adverse-event exclusion with explicit AE code HARD FAILS!
    prereg_ae_d = _sign_receipt({**a4b_prereg_y, "randomized_animal_roster": {**a4b_prereg_y["randomized_animal_roster"], "D28-COAT-09": "COATED"}, "day28_cohort_assigned_ids": [*a4b_prereg_y["day28_cohort_assigned_ids"], "D28-COAT-09"]})
    a4b_ae_d = _sign_receipt({**a4b_y, "prerequisite_receipt_sha256s": {**pr_all_y, "A-4b-PREREGISTRATION": prereg_ae_d["receipt_sha256"]}, "day28_cohort_enrolled_coated_n": 9, "day28_cohort_exclusions": [{"animal_id": "D28-COAT-09", "arm": "COATED", "reason": "SAMPLE_LOSS_PRE_ADJUDICATION", "pre_adjudication_decision": True, "excluded_at_utc": "2026-12-21T09:00:00Z", "adverse_event_related": True, "adverse_event_code": "NECROSIS"}]})
    chk("FAIL_GATE_A4B_DAY28_ADVERSE_EVENT_RELATED_EXCLUSION:D28-COAT-09" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_preregistration_receipt": prereg_ae_d, "a4b_evidence": a4b_ae_d})["failures"], "ADV_G40_a4b_day28_ae_exclusion_hard_fails")
    # 9. Exclusion timestamp AFTER histology_unblinding_utc (even before recorded_at_utc) FAILS!
    a4b_post_unb = _sign_receipt({**a4b_y, "prerequisite_receipt_sha256s": {**pr_all_y, "A-4b-PREREGISTRATION": prereg_ae_d["receipt_sha256"]}, "day28_cohort_enrolled_coated_n": 9, "day28_cohort_exclusions": [{"animal_id": "D28-COAT-09", "arm": "COATED", "reason": "SAMPLE_LOSS_PRE_ADJUDICATION", "pre_adjudication_decision": True, "excluded_at_utc": "2027-01-22T09:00:00Z", "adverse_event_related": False, "adverse_event_code": "NONE"}]})
    chk("FAIL_GATE_A4B_DAY28_EXCLUSION_TIMESTAMP_INVALID:D28-COAT-09" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_preregistration_receipt": prereg_ae_d, "a4b_evidence": a4b_post_unb})["failures"], "ADV_G40_a4b_exclusion_after_unblinding_fails")
    # 10. 1 non-AE exclusion per 9-animal arm (passes observed extrema, flips under physical [20, 1500] um / [0, 200]%) HOLDS!
    prereg_tp1 = _sign_receipt({**a4b_prereg_y, "randomized_animal_roster": {**a4b_prereg_y["randomized_animal_roster"], "D28-COAT-09": "COATED", "D28-VEH-09": "BLANK_VEHICLE"}, "day28_cohort_assigned_ids": [*a4b_prereg_y["day28_cohort_assigned_ids"], "D28-COAT-09", "D28-VEH-09"]})
    a4b_tp1 = _sign_receipt({**a4b_y, "prerequisite_receipt_sha256s": {**pr_all_y, "A-4b-PREREGISTRATION": prereg_tp1["receipt_sha256"]}, "day28_cohort_enrolled_coated_n": 9, "day28_cohort_enrolled_vehicle_n": 9, "day28_cohort_exclusions": [{"animal_id": "D28-COAT-09", "arm": "COATED", "reason": "SAMPLE_LOSS_PRE_ADJUDICATION", "pre_adjudication_decision": True, "excluded_at_utc": "2026-12-21T09:00:00Z", "adverse_event_related": False, "adverse_event_code": "NONE"}, {"animal_id": "D28-VEH-09", "arm": "BLANK_VEHICLE", "reason": "SAMPLE_LOSS_PRE_ADJUDICATION", "pre_adjudication_decision": True, "excluded_at_utc": "2026-12-21T09:00:00Z", "adverse_event_related": False, "adverse_event_code": "NONE"}]})
    r_tp1 = evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_preregistration_receipt": prereg_tp1, "a4b_evidence": a4b_tp1})
    chk(r_tp1["verdict"] == "HOLD" and "HOLD_GATE_A4B_DAY28_INFORMATIVE_ATTRITION_SENSITIVITY_NOT_ROBUST" in r_tp1["holds"], "ADV_G40_a4b_physical_tipping_point_1_per_arm_holds")
    # 11. Boundary: Outward-rounded 24-h supremum on [0, 12, 36-5e-10, 48] / [0, 5, 5, 10] returns 10.0 mg (never 5.0 mg)!
    chk(abs(_recompute_max_24h_cumulative_mg([0.0, 12.0, 36.0 - 5e-10, 48.0], [0.0, 5.0, 5.0, 10.0]) - 10.0) < 1e-9, "ADV_G40_a1_24h_boundary_outward_10mg")

    # --- GATE-41 Regressions (6 tests) ---
    # 12. Unpaired high-variance recirc BMT (local_measurement_includes_recirculation=False) pushes u_loc + u_rbt*u_fb above C_safe -> FAILS!
    b2b_rc_var = _mk_r8_b2b_replicates()
    b2b_rc_var["local_measurement_includes_recirculation"] = False
    b2b_rc_var["timepoint_replicate_records"][0]["recirc_bmt_total_replicates_nM"] = [0.2, 2.0, 4.0, 8.0, 12.0, 22.0]
    b2b_rc_var["timepoint_replicate_records"][0]["recirc_bmt_blq_flags"] = [False] * 6
    chk("FAIL_GATE_B2B_BENCH_RECOMPUTED_SIMULTANEOUS_PEAK_EXCEEDS_CLAIMED_OR_CSAFE" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, **b2b_rc_var, "u95_joint_peak_free_nM": 21.5})})["failures"], "ADV_G41_b2b_recirc_uncertainty_included_in_local_peak_fails")
    # 13. B-4 missing compartment-specific calibration FAILS!
    chk("FAIL_GATE_B4_MISSING_OR_INVALID_COMPARTMENT_CALIBRATION" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "b4_local_compartment_calibration": None})})["failures"], "ADV_G41_b4_missing_compartment_cal_fails")
    # 14. B-4 local compartment using in-vitro matrix OR recovery < 70% FAILS!
    bad_lcal = {k: v for k, v in b4_y["b4_local_compartment_calibration"].items() if k != "calibration_sha256"}
    bad_lcal["compartment_matrix_id"] = "human_serum_100pct"
    bad_lcal["calibration_sha256"] = sha256_bytes(canonical_json_bytes(bad_lcal))
    chk("FAIL_GATE_B4_MISSING_OR_INVALID_COMPARTMENT_CALIBRATION" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "b4_local_compartment_calibration": bad_lcal})})["failures"], "ADV_G41_b4_invitro_matrix_label_fails")
    # 15. Gap: Jointly-BLQ (BOTH parent=0 BLQ and BMT=0 BLQ) STILL triggers unbounded BMT/parent ratio HOLD!
    b2b_jblq = _mk_r8_b2b_replicates()
    b2b_jblq["timepoint_replicate_records"][-1]["local_parent_total_replicates_nM"] = [0.0] * 6
    b2b_jblq["timepoint_replicate_records"][-1]["local_parent_blq_flags"] = [True] * 6
    b2b_jblq["timepoint_replicate_records"][-1]["local_bmt_total_replicates_nM"] = [0.0] * 6
    b2b_jblq["timepoint_replicate_records"][-1]["local_bmt_blq_flags"] = [True] * 6
    chk("HOLD_GATE_B2B_BENCH_UNBOUNDED_BMT_TO_PARENT_RATIO_UNDER_PARENT_BLQ" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, **b2b_jblq})})["holds"], "ADV_G41_jointly_blq_unbounded_ratio_holds")
    # 16. Gap: Unbounded ratio mixture receipt with boolean=True but NO embedded bmt_alone_qualification_evidence HOLDS!
    mix_no_bmt = _sign_receipt({
        "stage": "MIXTURE_REQUALIFICATION", "verdict": "PASS", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "bench_unedited", "recorded_at_utc": "2026-09-12T09:00:00Z", **coat_b,
        "analysis_record_sha256": "d" * 64, "tested_bmt_to_parent_ratio_min": 0.0, "tested_bmt_to_parent_ratio_max": 10.0,
        "mixture_ec50_eff_u95_free_nM": 5.0, "mixture_c_safe_max_l95_free_nM": 25.0,
        "metabolite_dominant_unbounded_ratio_qualified": True,
    })
    chk("HOLD_GATE_B2B_BENCH_MISSING_BMT_ALONE_BIOLOGICAL_QUALIFICATION_EVIDENCE" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, **b2b_jblq, "mixture_requalification_receipt": mix_no_bmt})})["holds"], "ADV_G41_unbounded_ratio_requires_bmt_alone_evidence_holds")
    # 17. Continuous PK envelope declaring k_elim_local=0.001/h slower than observed washout slope (0.016/h) FAILS!
    b2b_slow_env = _mk_r8_b2b_replicates()
    eb_slow = {k: v for k, v in b2b_slow_env["intersample_pk_envelope"].items() if k != "envelope_receipt_sha256"}
    eb_slow["k_elim_local_max_per_h"] = 0.001
    b2b_slow_env["intersample_pk_envelope"] = {**eb_slow, "envelope_receipt_sha256": sha256_bytes(canonical_json_bytes(eb_slow))}
    chk("FAIL_GATE_B2B_BENCH_ENVELOPE_RATE_CONTRADICTS_OBSERVED_SLOPE" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, **b2b_slow_env})})["failures"], "ADV_G41_envelope_rate_slower_than_observed_slope_fails")

    # --- GATE-42 Regressions (5 tests) ---
    # 18. Decisive #1: Stage-1 missing edited_chassis_plus_foundry_v2 arm FAILS!
    s1_nof = {k: v for k, v in att_y["stage1_gatekeeper_record"].items() if "foundry_v2" not in k}
    chk("FAIL_IIP0049_MISSING_STAGE1_GATEKEEPER_RECORD" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _sign_receipt({**att_y, "stage1_gatekeeper_record": s1_nof})})["failures"], "ADV_G42_stage1_missing_foundry_arm_fails")
    # 19. Decisive #1: Foundry arm abolishes Stage-1 cytokine drop (3 pp < 10 pp) even while edited_chassis drops 24 pp -> FAILS!
    s1_prot = {**att_y["stage1_gatekeeper_record"], "edited_chassis_plus_foundry_v2_viability_pct_by_cond": {"vehicle": 92.2, "il1b_ifng": 88.0, "isolated_tnfa_ifng": 89.2}, "edited_chassis_plus_foundry_v2_caspase3_7_fold_by_cond": {"vehicle": 1.0, "il1b_ifng": 1.2, "isolated_tnfa_ifng": 1.3}}
    chk("FAIL_IIP0049_STAGE1_RAW_VIABILITY_OR_CASP37_CONTRADICTS_ESCALATION" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _sign_receipt({**att_y, "stage1_gatekeeper_record": s1_prot})})["failures"], "ADV_G42_stage1_foundry_abolishes_loss_fails")
    # 20. Decisive #2: Paired mock where reference rows stay fixed but EXACT_PRODUCT_FOUNDRY_V2 shows protection (diverging from mechanism panel) FAILS!
    ref_div = {**att_y["reference_comparator_measurements"], "EXACT_PRODUCT_FOUNDRY_V2": {**att_y["reference_comparator_measurements"]["EXACT_PRODUCT_FOUNDRY_V2"], "normoxia": {**att_y["reference_comparator_measurements"]["EXACT_PRODUCT_FOUNDRY_V2"]["normoxia"], "cond3_isolated_tnfa_ifng_beta_t0_pct_by_block": [89.0, 88.0, 90.0]}}}
    chk("FAIL_IIP0049_STAGE2_EXACT_PRODUCT_MATRIX_VS_PANEL_MISMATCH:normoxia" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _sign_receipt({**att_y, "reference_comparator_measurements": ref_div})})["failures"], "ADV_G42_stage2_exact_foundry_matrix_vs_panel_mismatch_fails")
    # 21. Statistical #3: Tampered Shapiro-Wilk p-value (claimed 0.99 vs recomputed AS R94) FAILS!
    nd_bad_sw = {k: v for k, v in c1_norm_6["normality_diagnostic_record"].items() if k != "diagnostic_sha256"}
    nd_bad_sw["beta_shapiro_wilk_p"] = 0.01
    nd_bad_sw["diagnostic_sha256"] = sha256_bytes(canonical_json_bytes(nd_bad_sw))
    chk("FAIL_GATE_C1_NORMOXIA_SHAPIRO_WILK_P_MISMATCH_VS_RAW_DIFFS" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "normality_diagnostic_record": nd_bad_sw}})})["failures"], "ADV_G42_c1_tampered_shapiro_wilk_p_fails")
    # 22. Statistical #3: Non-normal sibling arm (BBC3 outlier diffs) under paired-t HOLDS family-wide!
    _bbc3_nn_pct = [c1_norm_6["stressed_ctrl_beta_t0_pct_by_block"][i] + (0.1 if i < 5 else 35.0) for i in range(6)]
    c1_sib_nn = {**c1_norm_6, "all_five_arms_paired_data": {**c1_norm_6["all_five_arms_paired_data"], "BBC3": {**c1_norm_6["all_five_arms_paired_data"]["BBC3"], "treated_beta_surviving_by_block": [int(round(100 * v)) for v in _bbc3_nn_pct], "treated_beta_t0_pct_by_block": _bbc3_nn_pct}}}
    chk("HOLD_GATE_C1_NORMOXIA_PAIRED_T_FAMILY_NORMALITY_NOT_MET_USE_EXACT_SIGN_FLIP:BBC3" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": c1_sib_nn})})["holds"], "ADV_G42_c1_nonnormal_sibling_arm_holds")

    # --- GATE-43 Regressions (2 tests -> total 509/509!) ---
    # 23. Cheapest-Way: D-2 calendar (25 d total, 15 d post-sort) WITH full source-linked earlier-window Rule S8 + Gate 0M PASSES with zero authority!
    r2_ps15_ok = _mk_r8_readout2(
        matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1", lot_id="D2-LOT-1", lot_jitter=1.0,
        stage7_start_utc="2026-10-01T00:00:00Z", sort_reaggregation_utc="2026-10-11T00:00:00Z", assay_harvest_utc="2026-10-26T00:00:00Z",
        rule_s8=True, gate0m_applicable=True,
    )
    r_d2_ps15_ok = evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, recorded_at_utc="2026-10-28T10:00:00Z", readout2_evidence=r2_ps15_ok), _mk_d2_lot(2), _mk_d2_lot(3)]})
    chk(r_d2_ps15_ok["verdict"] == "PASS_DESCRIPTIVE_PILOT_ZERO_ODDS_GY037_WARN_RETAINED" and r_d2_ps15_ok["adoption_authority"] is False and r_d2_ps15_ok["gy037_warn_retained"] is True, "ADV_G43_d2_post_sort_15d_full_linked_s8_passes")
    # 24. Cheapest-Way: D-2 non-reference DEC084_M1_70_20_10 (n=8) WITH valid content-hashed DEC-084 receipt PASSES with zero authority!
    d84_ok_d2 = _sign_receipt({
        "stage": "DEC-084-MIXTURE", "verdict": "PASS",
        "product_id": py, "bank_id": by, "lot_id": "D2-LOT-1",
        "evidence_scope": "exact_product", "recorded_at_utc": "2026-10-20T00:00:00Z",
        "registered_mixture_id": "DEC084_M1_70_20_10",
        "canonical_dec084_producer_sha256": "7" * 64, "canonical_dec084_verdict": "PASS",
    })
    r2_d84_ok = _mk_r8_readout2(
        matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1", lot_id="D2-LOT-1", lot_jitter=1.0,
        registered_mixture_id="DEC084_M1_70_20_10", beta_cell_fraction=0.70, alpha_cell_fraction=0.20, delta_cell_fraction=0.10,
        n_blocks=8, dec084_receipt=d84_ok_d2,
    )
    r_d2_d84_ok = evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, readout2_evidence=r2_d84_ok), _mk_d2_lot(2), _mk_d2_lot(3)]})
    chk(r_d2_d84_ok["verdict"] == "PASS_DESCRIPTIVE_PILOT_ZERO_ODDS_GY037_WARN_RETAINED" and r_d2_d84_ok["adoption_authority"] is False, "ADV_G43_d2_dec084_nonref_linked_receipt_passes")


    # ========================================================================
    # ADVERSARIAL REGRESSION SUITE (24 NEW TESTS -> 533/533 TOTAL!)
    # Adversarial fail-closed invariant regression tests.
    # ========================================================================
    # --- Shared Readout-2 Live Parity Regressions (INVARIANT + INVARIANT, 5 tests) ---
    # 1. D-2 with stepdown_t90_min = 4.0 min and gate0m_applicable=False FAILS unconditionally!
    r2_d2_t90_4 = _mk_r8_readout2(matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1", lot_id="D2-LOT-1", lot_jitter=1.0, gate0m_applicable=False)
    for _o2k in ("o2_40_mmhg", "o2_100_mmhg"):
        for _b in r2_d2_t90_4[_o2k]["blocks"]:
            _b["stepdown_t90_min"] = 4.0
    chk("FAIL_CHECK_D2_D2-LOT-1_READOUT2_O2_40_GATE0M_SHUTOFF_T90_GT_3MIN_FAILED" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, readout2_evidence=r2_d2_t90_4), _mk_d2_lot(2), _mk_d2_lot(3)]})["failures"], "ADV_shared_r2_d2_t90_4_mandatory_gate0m_fails")
    # 2. Parity: Missing within_lot_technical_var_z2 HOLDS; huge technical variance pulls Z2 L95 below z_min -> FAILS!
    r2_no_tv = _mk_r8_readout2(matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1", lot_id="D2-LOT-1", lot_jitter=1.0)
    r2_no_tv.pop("within_lot_technical_var_z2", None)
    chk("HOLD_CHECK_D2_D2-LOT-1_READOUT2_MISSING_WITHIN_LOT_TECHNICAL_VARIANCE_Z2" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, readout2_evidence=r2_no_tv), _mk_d2_lot(2), _mk_d2_lot(3)]})["holds"], "ADV_shared_r2_missing_tech_var_holds")
    r2_hi_tv = _mk_r8_readout2(matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1", lot_id="D2-LOT-1", lot_jitter=1.0)
    r2_hi_tv["within_lot_technical_var_z2"] = 1.25
    chk("FAIL_CHECK_D2_D2-LOT-1_READOUT2_O2_40_RECOMPUTED_L95_Z2_BELOW_ZMIN" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, readout2_evidence=r2_hi_tv), _mk_d2_lot(2), _mk_d2_lot(3)]})["failures"], "ADV_shared_r2_high_tech_var_z2_l95_fails")
    # 3. Parity: Unverified insulin assay specificity OR missing cumulative secretion HOLDS!
    r2_bad_sp = _mk_r8_readout2(matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1", lot_id="D2-LOT-1", lot_jitter=1.0)
    r2_bad_sp["insulin_inventory_assay_specificity"] = "CROSS_REACTIVE_TOTAL_ELISA"
    chk("HOLD_CHECK_D2_D2-LOT-1_READOUT2_UNVERIFIED_MATURE_INSULIN_ASSAY_SPECIFICITY" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, readout2_evidence=r2_bad_sp), _mk_d2_lot(2), _mk_d2_lot(3)]})["holds"], "ADV_shared_r2_bad_insulin_specificity_holds")
    # 4. Parity: Raw stored_insulin_per_lot_iu breaching > 138.3 IU triggers Gate 0S even if summary u95 was understated!
    r2_hi_lot = _mk_r8_readout2(matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1", lot_id="D2-LOT-1", lot_jitter=1.0)
    r2_hi_lot["stored_insulin_per_lot_iu"] = [132.0, 134.0, 136.0, 137.0, 138.0, 145.0]
    r_hi_lot = evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, readout2_evidence=r2_hi_lot), _mk_d2_lot(2), _mk_d2_lot(3)]})
    chk("FAIL_CHECK_D2_D2-LOT-1_READOUT2_STORED_INSULIN_MAX_UNDERSTATES_RAW_LOTS" in r_hi_lot["failures"] and "HOLD_CHECK_D2_D2-LOT-1_READOUT2_GATE0S_ESCALATION_REQUIRED_GT_138P3_IU" in r_hi_lot["holds"], "ADV_shared_r2_raw_lot_inventory_gt138p3_caught")

    # --- GATE-40 [-> GATE-41] (IIP-0062) Regressions (INVARIANT + INVARIANT, 5 tests) ---
    # 5. A-0b missing raw 14-day safety/vascular replicates HOLDS!
    chk("HOLD_GATE_A0B_MISSING_RAW_14D_SAFETY_OR_VASCULAR_REPLICATES" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "a0b_14d_safety_replicates_by_conc": None})})["holds"], "ADV_G40_a0b_missing_14d_reps_holds")
    # 6. A-0b Day-4 delayed sprouting fails (< 90%) at 220 uM -> HOLDS unsubstantiated ceiling!
    a0b_reps_d4 = [dict(r) for r in a0b_reps_ok]
    a0b_reps_d4[5] = {**a0b_reps_d4[5], "day4_delayed_sprouting_14d_pct": [84.0, 86.0, 85.0]}
    a0b_fit_d4 = _sign_receipt({**a0b_fit_ok, "raw_replicates_sha256": sha256_bytes(canonical_json_bytes(a0b_reps_d4))})
    chk("HOLD_GATE_A0B_14D_CEILING_UNSUBSTANTIATED_BY_DONOR_REPLICATES" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "a0b_14d_safety_replicates_by_conc": a0b_reps_d4, "a0b_fit_artifact_receipt": a0b_fit_d4})})["holds"], "ADV_G40_a0b_day4_delayed_sprouting_fails_holds")
    # 7. A-0b missing local timecourse exposure HOLDS!
    chk("HOLD_GATE_A0B_MISSING_LOCAL_EXPOSURE_TIMEPOINTS" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "a0b_local_exposure_timepoints": None})})["holds"], "ADV_G40_a0b_missing_local_timepoints_holds")
    # 8. A-1 interior dip at Day 6 (144 h) below IC50_U95=75 uM FAILS even though Day 1 & Day 14 scalars pass!
    a1_tp_dip = [dict(r) for r in a1_tp_ok]
    a1_tp_dip[3] = _mk_pfd_tp_rows([(144.0, 63.5)], coat_a["coating_lot_id"], "A1DIP")[0]
    chk("FAIL_GATE_A1_DAYS1_14_INTERIOR_FREE_PARENT_DIP_BELOW_IC50_U95" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "a1_local_free_parent_timepoints": a1_tp_dip})})["failures"], "ADV_G40_a1_interior_day6_dip_below_ic50_fails")
    # 9. A-1 missing local free-parent timepoints HOLDS; > 72 h interior gap FAILS!
    chk("HOLD_GATE_A1_MISSING_LOCAL_FREE_PARENT_TIMEPOINTS" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "a1_local_free_parent_timepoints": None})})["holds"], "ADV_G40_a1_missing_local_timepoints_holds")

    # --- GATE-41 [-> GATE-42] (IIP-0063) Regressions (INVARIANT + INVARIANT, 5 tests) ---
    # 10. Parent BLQ at Day 21 WITH valid bmt_alone_qualification_evidence STILL FAILS when finite Day 1-10 BMT/parent ratio exceeds tested_bmt_to_parent_ratio_max!
    b2b_both_blq_fin = _mk_r8_b2b_replicates()
    for _ti_b, _bm_v in ((0, 2.5), (1, 2.2), (2, 1.8), (3, 1.1), (4, 0.50), (5, 0.15), (6, 0.02)):
        b2b_both_blq_fin["timepoint_replicate_records"][_ti_b]["local_bmt_total_replicates_nM"] = [round(_bm_v + d, 4) for d in (-0.005, 0.0, 0.005, -0.002, 0.002, 0.0)]
        b2b_both_blq_fin["timepoint_replicate_records"][_ti_b]["local_bmt_blq_flags"] = [_bm_v < 0.05] * 6
    b2b_both_blq_fin["timepoint_replicate_records"][-3]["local_parent_total_replicates_nM"] = [11.8, 12.0, 12.2, 11.9, 12.1, 12.0]
    b2b_both_blq_fin["timepoint_replicate_records"][-2]["local_parent_total_replicates_nM"] = [0.68, 0.70, 0.72, 0.69, 0.71, 0.70]
    b2b_both_blq_fin["timepoint_replicate_records"][-1]["local_parent_total_replicates_nM"] = [0.0] * 6
    b2b_both_blq_fin["timepoint_replicate_records"][-1]["local_parent_blq_flags"] = [True] * 6
    eb_bf = {k: v for k, v in b2b_both_blq_fin["intersample_pk_envelope"].items() if k != "envelope_receipt_sha256"}
    eb_bf["k_elim_local_max_per_h"] = 0.040
    eb_bf["k_elim_bmt_max_per_h"] = 0.040
    b2b_both_blq_fin["intersample_pk_envelope"] = {**eb_bf, "envelope_receipt_sha256": sha256_bytes(canonical_json_bytes(eb_bf))}
    def _mk_bmt_alone(tested_product_id: str = "BENCH_UNEDITED_PANEL") -> dict[str, Any]:
        sr_b, er_b = _mk_7ep_curve_reps()
        _b = {
            "analysis_method": "SIMULTANEOUS_BONFERRONI_GRID_BRACKET_STUDENT_T",
            "tested_product_id": tested_product_id,
            "tested_free_bmt_conc_grid_nM": [0.0, 2.0, 5.0, 12.0, 26.0, 50.0],
            "bmt_alone_safety_replicates_by_conc": sr_b,
            "bmt_alone_efficacy_replicates_by_conc": er_b,
            "bmt_alone_c_safe_max_l95_free_nM": 26.0, "bmt_alone_ec50_eff_u95_free_nM": 5.0,
        }
        return {**_b, "evidence_sha256": sha256_bytes(canonical_json_bytes(_b))}
    bmt_alone_ok_ref = _mk_bmt_alone("BENCH_UNEDITED_PANEL")
    mix_narrow_fin = _sign_receipt({
        "stage": "MIXTURE_REQUALIFICATION", "verdict": "PASS", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "bench_unedited", "recorded_at_utc": "2026-09-12T09:00:00Z", **coat_b,
        "analysis_record_sha256": "d" * 64, "tested_bmt_to_parent_ratio_min": 0.0, "tested_bmt_to_parent_ratio_max": 0.02,
        "mixture_ec50_eff_u95_free_nM": 5.0, "mixture_c_safe_max_l95_free_nM": 25.0,
        "mixture_dose_response_evidence": _mk_mix_dr(0.0, 0.02, 5.0, 25.0),
        "metabolite_dominant_unbounded_ratio_qualified": True,
        "bmt_alone_qualification_evidence": bmt_alone_ok_ref,
    })
    chk("FAIL_GATE_B2B_BENCH_MIXTURE_REQUAL_RATIO_DOES_NOT_COVER_OBSERVED_BMT_PARENT" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, **b2b_both_blq_fin, "mixture_requalification_receipt": mix_narrow_fin})})["failures"], "ADV_G41_blq_plus_uncovered_finite_ratio_fails")
    # 11. Same combined BLQ + finite ratio PASSES when mixture_requalification_receipt covers BOTH interval-wide finite ratio [0, 1.0] AND bmt_alone_qualification_evidence!
    mix_full_both = _sign_receipt({**mix_narrow_fin, "tested_bmt_to_parent_ratio_max": 1.0, "mixture_dose_response_evidence": _mk_mix_dr(0.0, 1.0, 5.0, 25.0, cover_unbounded_to_1=True)})
    _b1_bf = _sign_receipt({**b1_y, "analytical_sample_ledger": _mk_b12_ledger("B-1", b2b_both_blq_fin["timepoint_replicate_records"])})
    _b2_bf = _sign_receipt({**b2_y, "parent_receipt_sha256": _b1_bf["receipt_sha256"], "analytical_sample_ledger": _mk_b12_ledger("B-2", b2b_both_blq_fin["timepoint_replicate_records"])})
    _b2bb_bf = _sign_receipt({**b2bb_y, **b2b_both_blq_fin, "parent_receipt_sha256": _b2_bf["receipt_sha256"], "prerequisite_receipt_sha256s": {"B-1": _b1_bf["receipt_sha256"], "B-2": _b2_bf["receipt_sha256"]}, "u95_joint_peak_free_nM": 23.5, "c_bmt_local_total_u_alloc_nM": 3.0, "c_bmt_local_free_u_alloc_nM": 0.6, "mixture_requalification_receipt": mix_full_both})
    r_mix_ok = evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b1_evidence": _b1_bf, "b2_evidence": _b2_bf, "b2b_bench_evidence": _b2bb_bf})
    chk(r_mix_ok["verdict"] == "PASS_BENCH_ONLY_UNEDITED_PRE_MATERIALIZATION", "ADV_G41_blq_plus_covered_finite_ratio_passes")
    # 12. Gap: B-2b intersample_pk_envelope with mismatched coating_article_id FAILS!
    b2b_bad_art = _mk_r8_b2b_replicates(coating_article_id="ART-WRONG-COATING-99")
    chk("FAIL_GATE_B2B_BENCH_ENVELOPE_ARTICLE_PHASE_OR_COMPARTMENT_MISMATCH" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, **b2b_bad_art})})["failures"], "ADV_G41_env_wrong_article_fails")
    # 13. Gap: B-2b-exact reusing a bench_unedited intersample_pk_envelope FAILS!
    b2be_bench_env = _mk_r8_b2b_replicates(evidence_scope="bench_unedited")
    chk("FAIL_GATE_B2B_EXACT_ENVELOPE_ARTICLE_PHASE_OR_COMPARTMENT_MISMATCH" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b2b_exact_evidence": _sign_receipt({**b2be_y, **b2be_bench_env})})["failures"], "ADV_G41_b2be_reusing_bench_env_fails")
    # 14. Gap: B-4 envelope claiming pilot_sampling_max_gap_h = 8.0 h (> 2.0 h dense pilot bound) FAILS!
    eb4_gap = {k: v for k, v in b4_y["intersample_pk_envelope"].items() if k != "envelope_receipt_sha256"}
    eb4_gap["pilot_sampling_max_gap_h"] = 8.0
    eb4_gap["envelope_receipt_sha256"] = sha256_bytes(canonical_json_bytes(eb4_gap))
    chk("FAIL_GATE_B4_ENVELOPE_ARTICLE_PHASE_OR_COMPARTMENT_MISMATCH" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "intersample_pk_envelope": eb4_gap})})["failures"], "ADV_G41_b4_env_coarse_pilot_gap_fails")

    # --- GATE-42 [-> GATE-43] (IIP-0064) Regressions (INVARIANT + INVARIANT + INVARIANT, 7 tests) ---
    # 15. C-1 missing 5-lineage timecourse counts HOLDS; omitting PLVAP_iEC FAILS!
    chk("HOLD_GATE_C1_NORMOXIA_MISSING_LINEAGE_TIMECOURSE_COUNTS" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "lineage_timecourse_counts": None}})})["holds"], "ADV_G42_c1_missing_lineage_timecourse_holds")
    ltc_4 = {k: v for k, v in c1_norm_6["lineage_timecourse_counts"].items() if k != "PLVAP_iEC"}
    chk("FAIL_GATE_C1_NORMOXIA_INCOMPLETE_5_LINEAGE_TIMECOURSE_COUNTS" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "lineage_timecourse_counts": ltc_4}})})["failures"], "ADV_G42_c1_incomplete_4_lineage_fails")
    # 16. C-1 pmlkl_flag_triggered=False STILL FAILS when unconditional diversion assay reveals pMLKL=2.1x or Nec-1s rescue >= 5 pp!
    chk("FAIL_GATE_C1_NORMOXIA_UNDECLARED_NECROPTOSIS_DIVERSION" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "death_pathway_diversion_assay": {**c1_norm_6["death_pathway_diversion_assay"], "pmlkl_fold_vs_ctrl": 2.1}}})})["failures"], "ADV_G42_c1_undeclared_necroptosis_diversion_fails")
    # 17. Decayed transient knockdown (recovered_to_control=True) at NATIVE_SAFETY_SWITCH -> HOLD!
    sw_decayed = _mk_r8_switch(py, by, ly, ry, mat_yc, "2026-09-28T14:00:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": c2_y["receipt_sha256"]}, transient_engagement=_mk_c_eng(c1_cohort_y, "2026-09-28T13:00:00Z", stage_name="NATIVE_SAFETY_SWITCH", lot_s_id=ly, win_start="2026-09-25T12:00:00Z", win_end="2026-09-28T13:15:00Z", mode="VALIDATED_LONGITUDINAL_KINETICS", kd_v=12.0, recov=True))
    pr_dec = {**pr_c3_yc, "NATIVE_SAFETY_SWITCH": sw_decayed["receipt_sha256"]}
    r_sw_dec = evaluate_gate42_gy032_channel_c_screen({**g42_ok, "native_switch_evidence": sw_decayed, "c3_nk_evidence": _sign_receipt({**c3_nk_y, "prerequisite_receipt_sha256s": pr_dec}), "c3_gsis_evidence": _sign_receipt({**c3_gsis_y, "prerequisite_receipt_sha256s": pr_dec})})
    chk("HOLD_GATE_C_TRANSIENT_ENGAGEMENT_DECAYED_BEFORE_ASSAY:NATIVE_SAFETY_SWITCH" in r_sw_dec["holds"], "ADV_G42_switch_decayed_engagement_holds")
    # 18. Missing transient_target_engagement_record on C-3-GSIS -> HOLD!
    c3g_no_eng = _sign_receipt({k: v for k, v in c3_gsis_y.items() if k != "transient_target_engagement_record"})
    chk("HOLD_GATE_C_MISSING_TRANSIENT_ENGAGEMENT_RECORD:C-3-GSIS" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c3_gsis_evidence": c3g_no_eng})["holds"], "ADV_G42_c3gsis_missing_engagement_holds")
    # 19. GATE-36-INVVAX submitted under strict drug-free Foundry scope FAILS!
    g36_invvax = _sign_receipt({**g36_y, "active_drug_free_modules": ["GATE-36-INVVAX"], "module_producer_receipt_sha256s": {"GATE-36-INVVAX": "c" * 64}})
    chk("FAIL_FOUNDRY_V2_GATE36_INVALID_DRUG_FREE_MODULE_PRODUCERS" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "foundry_v2_gate36_evidence": g36_invvax})["failures"], "ADV_G42_g36_invvax_rejected_in_drug_free_scope")
    # 20. Tampered five_arm_family_matrix_sha256 FAILS!
    chk("FAIL_GATE_C1_FIVE_ARM_FAMILY_MATRIX_SHA256_MISMATCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "five_arm_family_matrix_sha256": "0" * 64})})["failures"], "ADV_G42_c1_tampered_family_matrix_sha_fails")

    # --- GATE-43 [-> GATE-43] (IIP-0065) Regressions (INVARIANT, 4 tests -> total 533/533!) ---
    # 21. Reversing block order in LOT-2 of identical LOT-1 numeric arrays STILL FAILS!
    r2_l2_rev = _mk_r8_readout2(matched_comparator_id="CTRL-LOT-2", block_prefix="D2L2", meas_id="MEAS-D2-LOT-2", lot_id="D2-LOT-2", lot_jitter=1.0)
    r2_l2_rev["o2_40_mmhg"]["blocks"] = list(reversed(r2_l2_rev["o2_40_mmhg"]["blocks"]))
    r2_l2_rev["o2_100_mmhg"]["blocks"] = list(reversed(r2_l2_rev["o2_100_mmhg"]["blocks"]))
    chk("FAIL_CHECK_D2_IDENTICAL_NUMERICAL_ARRAYS_ACROSS_LOTS:D2-LOT-2" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1), _mk_d2_lot(2, readout2_evidence=r2_l2_rev), _mk_d2_lot(3)]})["failures"], "ADV_G43_d2_reversed_block_order_copypaste_fails")
    # 22. D-3(a) treated lot IDs cycling through comparator NT lot IDs (A->B, B->C, C->A) FAILS!
    d3a_cyc = [
        _mk_d3a_lot(1, lot_id="LOT-CYC-A", comparator_nt_lot_id="LOT-CYC-B"),
        _mk_d3a_lot(2, lot_id="LOT-CYC-B", comparator_nt_lot_id="LOT-CYC-C"),
        _mk_d3a_lot(3, lot_id="LOT-CYC-C", comparator_nt_lot_id="LOT-CYC-A"),
    ]
    chk(any(f.startswith("FAIL_CHECK_D3A_TREATED_COMPARATOR_LOT_ID_OVERLAP_OR_CYCLE:") for f in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": d3a_cyc})["failures"]), "ADV_G43_d3a_treated_comparator_cycle_fails")
    # 23. Live ID Collision Closure: Returned gate IDs are strictly collision-free GATE-41..GATE-43!
    chk(r40["gate"] == "GATE-40" and r41["gate"] == "GATE-41" and r42["gate"] == "GATE-42" and r43["gate"] == "GATE-43", "ADV_all_4_gate_ids_rebound_cleanly")
    # 24. Differential regression check: D-2 with valid t90 <= 3.0, tech_var, assay specificity, & distinct blocks still retains GY-037 & zero authority!
    r_d2_clean_ref = evaluate_gate43_cellgemma_guardrails_and_pilots(g43_full_a)
    chk(r_d2_clean_ref["verdict"] == "PASS_DESCRIPTIVE_PILOT_ZERO_ODDS_GY037_WARN_RETAINED" and r_d2_clean_ref["gy037_warn_retained"] is True and r_d2_clean_ref["gy037_revocation_eligible"] is False and r_d2_clean_ref["adoption_authority"] is False, "ADV_G43_clean_d2_retains_gy037_zero_authority")



    # ========================================================================
    # ADVERSARIAL REGRESSION SUITE (25 NEW TESTS -> 560/560 TOTAL!)
    # Adversarial fail-closed invariant regression tests.
    # ========================================================================
    # --- Shared GY-009 & Readout-2 Live Parity Regressions (INVARIANT, INVARIANT, INVARIANT — 7 tests) ---
    # 1. (GY-009): Omitting GCG_alpha & SST_delta from A-2 Hour-0 density FAILS!
    h0_2lin = {k: v for k, v in _mk_r8_hour0(py).items() if k in ("INS_beta", "PLVAP_iEC")}
    chk("FAIL_GATE_A2_INCOMPLETE_LINEAGE_HOUR0_DENSITY:GCG_alpha,SST_delta" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "hour0_density_by_lineage": h0_2lin})})["failures"], "ADV_shared_gy009_a2_2lineages_only_fails")
    # 2. (GY-009): Omitting GCG_alpha & SST_delta from C-2 Hour-0 density FAILS!
    chk("FAIL_GATE_C2_INCOMPLETE_LINEAGE_HOUR0_DENSITY:GCG_alpha,SST_delta" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "hour0_density_by_lineage": h0_2lin})})["failures"], "ADV_shared_gy009_c2_2lineages_only_fails")
    # 3. (OCR U95): ocr_ratio=1.08 (point <= 1.097, U95_t = 1.110 > 1.097) HOLDS for S4 derating!
    r2_ocr_108 = _mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B", lot_id=ly)
    r2_ocr_108["gate_resp1_ocr_ratio"] = 1.08
    chk("HOLD_GATE_A2_READOUT2_LOT_OCR_UPPER95_EXCEEDS_1P097_REQUIRES_S4_DERATING" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": r2_ocr_108})})["holds"], "ADV_shared_r2_ocr_u95_gt_1p097_holds")
    # 4. (41.5 IU floor): stored_insulin L95 = 35.0 IU (passes old 30 IU floor, fails live 41.5 IU floor) HOLDS!
    r2_inv_35 = _mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B", lot_id=ly)
    r2_inv_35["stored_insulin_per_lot_iu"] = [35.5, 36.0, 36.2, 35.8, 36.1, 35.9]
    chk("HOLD_GATE_A2_READOUT2_STORED_INSULIN_L95_BELOW_MASS_FLOOR" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": r2_inv_35})})["holds"], "ADV_shared_r2_41p5_iu_floor_holds_35iu")
    # 5. (dose scaling): implanted_dose_ieq = 1_000_000 scales floor to 83.0 IU -> 70 IU HOLDS!
    r2_dose_1m = _mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B", lot_id=ly)
    r2_dose_1m["implanted_dose_ieq"] = 1_000_000.0
    r2_dose_1m["stored_insulin_per_lot_iu"] = [70.0, 71.0, 70.5, 70.8, 70.2, 70.4]
    chk("HOLD_GATE_A2_READOUT2_STORED_INSULIN_L95_BELOW_MASS_FLOOR" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": r2_dose_1m})})["holds"], "ADV_shared_r2_dose_scaled_83iu_floor_holds")
    # 6. (proinsulin:C-peptide): U95 > 0.10 HOLDS!
    r2_proins_hi = _mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B", lot_id=ly)
    r2_proins_hi["proinsulin_to_cpeptide_content_ratio_per_lot"] = [0.095, 0.105, 0.110, 0.108, 0.112, 0.106]
    chk("HOLD_GATE_A2_READOUT2_ELEVATED_PROINSULIN_TO_CPEPTIDE_CONTENT_RATIO" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": r2_proins_hi})})["holds"], "ADV_shared_r2_proinsulin_cpep_u95_gt_0p10_holds")
    # 7. Missing proinsulin_to_cpeptide_content_ratio_per_lot HOLDS!
    r2_no_proins = _mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B", lot_id=ly)
    r2_no_proins.pop("proinsulin_to_cpeptide_content_ratio_per_lot", None)
    chk("HOLD_GATE_A2_READOUT2_MISSING_PROINSULIN_TO_CPEPTIDE_ARRAY" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": r2_no_proins})})["holds"], "ADV_shared_r2_missing_proinsulin_cpep_holds")

    # --- GATE-40 (IIP-0062) Regressions (INVARIANT + INVARIANT — 5 tests) ---
    # 8. [80, 100, 100] (mean=93.33, L95=73.87) at 190 uM below [95, 96, 97] at 220 uM HOLDS!
    a0b_reps_dip = [dict(r) for r in a0b_reps_ok]
    a0b_reps_dip[4] = {**a0b_reps_dip[4], "viability_14d_pct": [80.0, 100.0, 100.0], "raw_donor_measurements": {**a0b_reps_dip[4]["raw_donor_measurements"], "viability_14d": _mk_a0b_raw_pair([80.0, 100.0, 100.0], 96.5)}}
    a0b_fit_dip = _sign_receipt({**a0b_fit_ok, "raw_replicates_sha256": sha256_bytes(canonical_json_bytes(a0b_reps_dip))})
    chk("HOLD_GATE_A0B_14D_CEILING_UNSUBSTANTIATED_BY_DONOR_REPLICATES" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "a0b_14d_safety_replicates_by_conc": a0b_reps_dip, "a0b_fit_artifact_receipt": a0b_fit_dip})})["holds"], "ADV_G40_a0b_interior_l95_dip_80_100_100_holds")
    # 9. A-0b missing continuous local PK envelope HOLDS!
    chk("HOLD_GATE_A0B_MISSING_CONTINUOUS_LOCAL_PK_ENVELOPE" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "a0b_local_pk_envelope": None})})["holds"], "ADV_G40_a0b_missing_local_pk_env_holds")
    # 10. A-0b first sample delayed to 24 h (no early burst anchor <= 6 h) FAILS!
    a0b_tp_late = [r for r in a0b_tp_ok if r["hour_h"] >= 24.0]
    chk("FAIL_GATE_A0B_LOCAL_EXPOSURE_SCHEDULE_GAP_OR_MALFORMED" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "a0b_local_exposure_timepoints": a0b_tp_late})})["failures"], "ADV_G40_a0b_first_sample_24h_no_early_burst_fails")
    # 11. A-1 continuous PK envelope with fast rate (ke_a=0.04/h) pushes continuous early [0, 6h] peak above 220 uM ceiling -> FAILS!
    a1e_env_steep = _mk_pfd_env("exact_product", "BENCH_ELUTION_LOCAL_PERI_GRAFT", ke_a=0.040, kr_a=0.002, ke_w=0.040)
    chk("FAIL_GATE_A1_DAYS1_14_LOCAL_FREE_PARENT_EXCEEDS_CEILING" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "a1_local_pk_envelope": a1e_env_steep})})["failures"], "ADV_G40_a1_continuous_early_peak_breaches_ceiling_fails")
    # 12. A-1 envelope declaring slower decay (ke_a=0.0005/h) than observed slope FAILS!
    a1e_env_slow = _mk_pfd_env("exact_product", "BENCH_ELUTION_LOCAL_PERI_GRAFT", ke_a=0.0005, kr_a=0.002, ke_w=0.010)
    chk("FAIL_GATE_A1_LOCAL_PK_ENVELOPE_RATE_CONTRADICTS_OBSERVED_SLOPE" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "a1_local_pk_envelope": a1e_env_slow})})["failures"], "ADV_G40_a1_env_rate_slower_than_observed_fails")

    # --- GATE-41 (IIP-0063) Regressions (INVARIANT + INVARIANT + INVARIANT — 5 tests) ---
    # 13. DECISIVE counterexample: b2be_ev has valid mixture receipt, b4_ev has mixture_requalification_receipt=None + Day-21 parent-BLQ -> MUST HOLD (never bypass B-4 validation)!
    mix_ex_ref = _sign_receipt({
        "stage": "MIXTURE_REQUALIFICATION", "verdict": "PASS", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "exact_product", "recorded_at_utc": "2026-09-14T11:00:00Z", **coat_b,
        "analysis_record_sha256": "d" * 64, "tested_bmt_to_parent_ratio_min": 0.0, "tested_bmt_to_parent_ratio_max": 0.60,
        "mixture_ec50_eff_u95_free_nM": 5.0, "mixture_c_safe_max_l95_free_nM": 25.0,
        "mixture_dose_response_evidence": _mk_mix_dr(0.0, 0.60, 5.0, 25.0, tested_product_id=py, cover_unbounded_to_1=True),
        "metabolite_dominant_unbounded_ratio_qualified": True,
        "bmt_alone_qualification_evidence": _mk_bmt_alone(py),
    })
    b4_blq_nomix = {k: v for k, v in b4_y.items() if k != "receipt_sha256"}
    b4_blq_tps = [dict(r) for r in b4_y["timepoint_replicate_records"]]
    b4_blq_tps[-1] = {**b4_blq_tps[-1], "local_parent_total_replicates_nM": [0.0] * 6, "local_parent_blq_flags": [True] * 6}
    b4_blq_nomix["timepoint_replicate_records"] = b4_blq_tps
    b4_blq_nomix["serial_pk_local_parent_free_nM"] = list(b4_y["serial_pk_local_parent_free_nM"][:-1]) + [0.0]
    r_b4_fb = evaluate_gate41_deucravacitinib_tyk2({
        **g41_ok,
        "b2b_exact_evidence": _sign_receipt({**b2be_y, "mixture_requalification_receipt": mix_ex_ref}),
        "b4_evidence": _sign_receipt(b4_blq_nomix),
    })
    chk("HOLD_GATE_B4_UNBOUNDED_BMT_TO_PARENT_RATIO_UNDER_PARENT_BLQ" in r_b4_fb["holds"], "ADV_G41_b4_parent_blq_cannot_silently_fallback_to_b2be_mix")
    # 14. B-4 duplicate animal_ids (technical repeats posing as independent animals) FAILS!
    b4_dup_an = [dict(r) for r in b4_y["timepoint_replicate_records"]]
    b4_dup_an[0] = {**b4_dup_an[0], "animal_ids": ["NSG-PK-01", "NSG-PK-01", "NSG-PK-02", "NSG-PK-03", "NSG-PK-04", "NSG-PK-05"]}
    chk("FAIL_GATE_B4_INVALID_TP_REPLICATES:0" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "timepoint_replicate_records": b4_dup_an})})["failures"], "ADV_G41_b4_duplicate_animal_id_fails")
    # 15. B-4 unpaired analyte_pairing_mode FAILS!
    b4_unp = [dict(r) for r in b4_y["timepoint_replicate_records"]]
    b4_unp[0] = {**b4_unp[0], "analyte_pairing_mode": "UNPAIRED_POOLED"}
    chk("FAIL_GATE_B4_INVALID_TP_REPLICATES:0" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "timepoint_replicate_records": b4_unp})})["failures"], "ADV_G41_b4_unpaired_analyte_mode_fails")
    # 16. B-4 PERI_GRAFT_MICRODIALYSIS_DIALYSATE with plasma fu=0.14 (not 1.0 protein-free) FAILS!
    bad_dial = {k: v for k, v in b4_y["b4_local_compartment_calibration"].items() if k != "calibration_sha256"}
    bad_dial["compartment_matrix_id"] = "PERI_GRAFT_MICRODIALYSIS_DIALYSATE"
    bad_dial["concentration_basis"] = "RECOVERY_CORRECTED_UNBOUND_INTERSTITIAL_DIALYSATE"
    bad_dial["calibration_sha256"] = sha256_bytes(canonical_json_bytes(bad_dial))
    chk("FAIL_GATE_B4_MISSING_OR_INVALID_COMPARTMENT_CALIBRATION" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "b4_local_compartment_calibration": bad_dial})})["failures"], "ADV_G41_b4_microdialysis_with_nonunit_fu_fails")
    # 17. B-4 pre_submission_recovery_correction_applied=False FAILS!
    bad_recov = {k: v for k, v in b4_y["b4_local_compartment_calibration"].items() if k != "calibration_sha256"}
    bad_recov["pre_submission_recovery_correction_applied"] = False
    bad_recov["calibration_sha256"] = sha256_bytes(canonical_json_bytes(bad_recov))
    chk("FAIL_GATE_B4_MISSING_OR_INVALID_COMPARTMENT_CALIBRATION" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "b4_local_compartment_calibration": bad_recov})})["failures"], "ADV_G41_b4_uncorrected_recovery_fails")

    # --- GATE-42 (IIP-0064) Regressions (INVARIANT + INVARIANT + INVARIANT — 5 tests) ---
    # 18. C-1 primary beta pct contradicts raw plated/surviving beta counts -> FAILS!
    c1_bad_cnt = {**c1_norm_6, "treated_beta_surviving_by_block": [5000] * 6}
    chk("FAIL_GATE_C1_NORMOXIA_BETA_PCT_CONTRADICTS_RAW_PLATED_COUNTS:ACTIVE_TREATED" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": c1_bad_cnt})})["failures"], "ADV_G42_c1_primary_beta_count_contradiction_fails")
    # 19. C-1 lineage_timecourse_counts["INS_beta"] contradicts primary beta survival -> FAILS!
    ltc_bad_beta = {**c1_norm_6["lineage_timecourse_counts"], "INS_beta": [
        {**b_e, "timepoints": [*b_e["timepoints"][:-1], {**b_e["timepoints"][-1], "treated_surviving_n": 400}]}
        for b_e in c1_norm_6["lineage_timecourse_counts"]["INS_beta"]
    ]}
    chk("FAIL_GATE_C1_NORMOXIA_INS_BETA_TIMECOURSE_MISMATCH_VS_PRIMARY" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "lineage_timecourse_counts": ltc_bad_beta}})})["failures"], "ADV_G42_c1_ins_beta_timecourse_mismatch_fails")
    # 20. Backdated C-1 transient engagement replayed on C-3-GSIS (win_start < C-3-NK recorded) FAILS!
    eng_backdated = _mk_c_eng(c1_cohort_y, "2026-09-21T08:00:00Z", stage_name="C-3-GSIS", lot_s_id=ly, win_start="2026-09-21T08:00:00Z", win_end="2026-10-01T18:00:00Z")
    chk("FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:C-3-GSIS" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c3_gsis_evidence": _sign_receipt({**c3_gsis_y, "transient_target_engagement_record": eng_backdated})})["failures"], "ADV_G42_c3gsis_backdated_engagement_fails")
    # 21. Engagement measured > 24 h before assay_window_end_utc HOLDS (stale knockdown)!
    eng_stale = _mk_c_eng(c1_cohort_y, "2026-09-30T15:00:00Z", stage_name="C-3-GSIS", lot_s_id=ly, win_start="2026-09-30T13:00:00Z", win_end="2026-10-01T18:00:00Z")
    chk("HOLD_GATE_C_TRANSIENT_ENGAGEMENT_STALE_BEFORE_ASSAY_END:C-3-GSIS" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c3_gsis_evidence": _sign_receipt({**c3_gsis_y, "transient_target_engagement_record": eng_stale})})["holds"], "ADV_G42_c3gsis_stale_engagement_gt24h_holds")
    # 22. Mutating common stressed control array without updating five_arm_family_matrix_sha256 FAILS!
    c1_ctrl_mut = {**c1_norm_6, "stressed_ctrl_beta_t0_pct_by_block": [53.9, 52.0, 56.0, 55.0, 53.0, 54.0]}
    chk("FAIL_GATE_C1_FIVE_ARM_FAMILY_MATRIX_SHA256_MISMATCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": c1_ctrl_mut})})["failures"], "ADV_G42_c1_ctrl_mutation_breaks_family_matrix_sha_fails")

    # --- GATE-43 (IIP-0065) Regressions (INVARIANT + INVARIANT + INVARIANT — 3 tests -> total 560/560!) ---
    # 23. D2-LOT-2 serving as D2-LOT-1 matched_control_lot_id FAILS!
    chk("FAIL_CHECK_D2_TREATED_AND_CONTROL_LOT_IDS_OVERLAP:D2-LOT-2" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, mctrl_override="D2-LOT-2"), _mk_d2_lot(2), _mk_d2_lot(3)]})["failures"], "ADV_G43_d2_treated_control_lot_overlap_fails")
    # 24. int 1 for bool True inside check_d1_paired_assay_receipt FAILS!
    d1_rcpt_int1 = _mk_d1_unified(g43_base, both_arms_matched_24h_nac=1)
    chk("FAIL_CHECK_D1_UNIFIED_ASSAY_RECEIPT_FIELD_MISMATCH" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_paired_assay_receipt": d1_rcpt_int1})["failures"], "ADV_G43_d1_int1_vs_bool_true_fails")
    # 25. & #2: Mismatched plate_id in D-1 GSIS endpoint FAILS, AND clean pass reports bank_registry_verified_live=False!
    d1_gsis_badp = (lambda _b: {**_b, "record_sha256": sha256_bytes(canonical_json_bytes(_b))})({
        **{k: v for k, v in g43_base["check_d1_paired_gsis_record"].items() if k != "record_sha256"},
        "plate_id": "D1-WRONG-PLATE-99",
    })
    d1_base_badp = {**g43_base, "check_d1_paired_gsis_record": d1_gsis_badp}
    d1_base_badp["check_d1_paired_assay_receipt"] = _mk_d1_unified(d1_base_badp)
    chk(
        "FAIL_CHECK_D1_ENDPOINT_SPECIMEN_OR_PLATE_IDENTITY_MISMATCH" in evaluate_gate43_cellgemma_guardrails_and_pilots(d1_base_badp)["failures"]
        and r_d2_clean_ref.get("bank_registry_verified_live") is False,
        "ADV_G43_d1_plate_id_mismatch_and_declared_bank_flag",
    )



    # ========================================================================
    # ADVERSARIAL REGRESSION SUITE (25 NEW TESTS -> 585/585 TOTAL!)
    # Adversarial fail-closed invariant regression tests.
    # ========================================================================
    # --- Shared Readout-2 Live wetlab_contract.py Parity (8 tests) ---
    # 1. Depleted KCl secretory reserve (kcl_value <= high2_value) FAILS across GATE-40, GATE-41, GATE-43!
    r2_no_kcl = _mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B", lot_id=ly)
    for _b in r2_no_kcl["o2_40_mmhg"]["blocks"]:
        _b["kcl_value"] = round(_b["high2_value"] - 0.15, 6)
    chk("FAIL_GATE_A2_READOUT2_O2_40_KCL_RESERVE_L95_FAILED" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": r2_no_kcl})})["failures"], "ADV_shared_r2_g40_depleted_kcl_reserve_fails")
    r2_d2_kcl = _mk_r8_readout2(matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1", lot_id="D2-LOT-1", lot_jitter=1.0)
    for _b in r2_d2_kcl["o2_40_mmhg"]["blocks"]:
        _b["kcl_value"] = round(_b["high2_value"] - 0.10, 6)
    chk("FAIL_CHECK_D2_D2-LOT-1_READOUT2_O2_40_KCL_RESERVE_L95_FAILED" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, readout2_evidence=r2_d2_kcl), _mk_d2_lot(2), _mk_d2_lot(3)]})["failures"], "ADV_shared_r2_d2_depleted_kcl_reserve_fails")
    # 2. Individual peak times all <= 8.0 min ([7.4, 7.95, 7.98, 7.99, 8.0, 8.0]) have U95_t = 8.08 > 8.0 -> FAILS!
    r2_pkt_u95 = _mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B", lot_id=ly)
    for _i_p, _pt in enumerate([7.4, 7.95, 7.98, 7.99, 8.0, 8.0]):
        r2_pkt_u95["o2_40_mmhg"]["blocks"][_i_p]["pulse1_peak_time_min"] = _pt
    chk("FAIL_GATE_A2_READOUT2_O2_40_PEAK1_LATENCY_U95_GT_8MIN" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": r2_pkt_u95})})["failures"], "ADV_shared_r2_peak_time_u95_gt_8min_fails")
    # 3. Caller-supplied z2_increment inflated above raw eta*(high2-low2) FAILS raw recomputation check!
    r2_bad_z2 = _mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B", lot_id=ly)
    r2_bad_z2["o2_40_mmhg"]["blocks"][0]["z2_increment"] = 2.80  # contradicts raw 0.84*(h2-l2)=1.79
    chk("FAIL_GATE_A2_READOUT2_O2_40_Z2_CONTRADICTS_RAW_ETA_HIGH2_LOW2" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": r2_bad_z2})})["failures"], "ADV_shared_r2_inflated_z2_vs_raw_high2_low2_fails")
    # 4. Integrated SI_1 L95 < 3.0 (even with marginal points) FAILS!
    r2_bad_si1 = _mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B", lot_id=ly)
    for _i_s, _b in enumerate(r2_bad_si1["o2_40_mmhg"]["blocks"]):
        _l1 = _b["low1_value"]
        _h1 = round(_l1 * (3.60 if _i_s == 5 else 3.005), 6)
        _b["high1_value"] = _h1
        _b["pulse1_si"] = round(_h1 / _l1, 4)
        _b["z1_increment"] = round(_b["eta_sort_viable_recovery"] * (_h1 - _l1), 4)
    chk("FAIL_GATE_A2_READOUT2_O2_40_INTEGRATED_SI1_L95_BELOW_3P0" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": r2_bad_si1})})["failures"], "ADV_shared_r2_integrated_si1_l95_lt_3_fails")
    # 5. Sorted maturation clock post-sort = 3 d (< 5.0 d minimum) HOLDS!
    r2_short_ps = _mk_r8_readout2(
        matched_comparator_id=bv_a, block_prefix="A2B", lot_id=ly,
        stage7_start_utc="2026-09-12T00:00:00Z", sort_reaggregation_utc="2026-09-24T00:00:00Z", assay_harvest_utc="2026-09-27T00:00:00Z",
    )
    chk("HOLD_GATE_A2_READOUT2_SORTED_CLOCK_BELOW_MINIMUM_MATURATION_DAYS" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": r2_short_ps})})["holds"], "ADV_shared_r2_sorted_post_sort_lt_5d_holds")
    # 6. Missing trace_id outside Rule S8 now HOLDS unconditionally!
    r2_no_tr = _mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B", lot_id=ly)
    r2_no_tr["o2_40_mmhg"]["blocks"][0].pop("trace_id", None)
    chk("HOLD_GATE_A2_READOUT2_O2_40_MISSING_CONFIRMATION_TRACE_ID" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": r2_no_tr})})["holds"], "ADV_shared_r2_unconditional_trace_id_missing_holds")
    # 7. Sorted per-lot eta = 0.98 (>= 0.95 exclusive ceiling) HOLDS!
    r2_bad_eta = _mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B", lot_id=ly)
    r2_bad_eta["o2_40_mmhg"]["blocks"][0]["eta_sort_viable_recovery"] = 0.98
    chk("HOLD_GATE_A2_READOUT2_O2_40_UNQUALIFIED_SORTED_ETA_RECOVERY" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": r2_bad_eta})})["holds"], "ADV_shared_r2_sorted_eta_ge_0p95_holds")

    # --- GATE-41 (IIP-0063) Regressions (INVARIANT + INVARIANT — 6 tests) ---
    # 8. B-4 SYSTEMIC_WHOLE_BLOOD without validated blood-to-plasma K_bp replicates FAILS!
    wb_no_kbp = {k: v for k, v in b4_y["b4_systemic_compartment_calibration"].items() if k != "calibration_sha256"}
    wb_no_kbp["compartment_matrix_id"] = "SYSTEMIC_WHOLE_BLOOD"
    wb_no_kbp["calibration_sha256"] = sha256_bytes(canonical_json_bytes(wb_no_kbp))
    chk("FAIL_GATE_B4_MISSING_OR_INVALID_COMPARTMENT_CALIBRATION" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "b4_systemic_compartment_calibration": wb_no_kbp})})["failures"], "ADV_G41_b4_whole_blood_without_kbp_fails")
    # 9. B-4 SYSTEMIC_WHOLE_BLOOD with validated K_bp < 1.0 (e.g. 0.45) scales whole-blood 0.28 nM -> plasma equivalent > 0.5 nM -> FAILS!
    wb_low_kbp = {k: v for k, v in b4_y["b4_systemic_compartment_calibration"].items() if k != "calibration_sha256"}
    wb_low_kbp.update({
        "compartment_matrix_id": "SYSTEMIC_WHOLE_BLOOD",
        "kbp_assay_method_id": "NSG-WHOLE-BLOOD-PLASMA-PARTITION-V1",
        "blood_to_plasma_ratio_parent_replicates": [0.44, 0.45, 0.46, 0.45, 0.44, 0.46],
        "blood_to_plasma_ratio_bmt_replicates": [0.43, 0.45, 0.44, 0.46, 0.45, 0.44],
        "alpha_kbp_parent": 0.004, "alpha_kbp_bmt": 0.004,
    })
    wb_low_kbp["calibration_sha256"] = sha256_bytes(canonical_json_bytes(wb_low_kbp))
    b4_wb_hi = _sign_receipt({**b4_y, "alpha_conc": 0.022, "alpha_fu_parent": 0.010, "alpha_fu_bmt": 0.010, "b4_systemic_compartment_calibration": wb_low_kbp})
    chk("FAIL_GATE_B4_CONTINUOUS_SYSTEMIC_PEAK_GE_0P5NM" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": b4_wb_hi})["failures"], "ADV_G41_b4_whole_blood_low_kbp_breaches_plasma_0p5_fails")
    # 10. B-4 SYSTEMIC_WHOLE_BLOOD with validated K_bp = 1.26 & alpha budget <= 0.05 PASSES!
    wb_ok_kbp = {k: v for k, v in wb_low_kbp.items() if k != "calibration_sha256"}
    wb_ok_kbp["blood_to_plasma_ratio_parent_replicates"] = [1.24, 1.26, 1.27, 1.25, 1.26, 1.28]
    wb_ok_kbp["blood_to_plasma_ratio_bmt_replicates"] = [1.20, 1.22, 1.21, 1.23, 1.22, 1.24]
    wb_ok_kbp["calibration_sha256"] = sha256_bytes(canonical_json_bytes(wb_ok_kbp))
    b4_wb_ok = _sign_receipt({**b4_y, "alpha_conc": 0.022, "alpha_fu_parent": 0.010, "alpha_fu_bmt": 0.010, "b4_systemic_compartment_calibration": wb_ok_kbp})
    chk(evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": b4_wb_ok})["verdict"] == OFFLINE_VERDICT_PRIMARY, "ADV_G41_b4_whole_blood_valid_kbp_passes")
    # 11. Continuous inter-sample BMT/parent ratio (~0.0208) exceeds sampled-only max (0.0170) -> mixture tested only up to 0.0185 FAILS!
    mix_sampled_only = _sign_receipt({**mix_rcpt_ok, "tested_bmt_to_parent_ratio_max": 0.0185, "mixture_dose_response_evidence": _mk_mix_dr(0.0, 0.0185, 6.5, 21.0)})
    chk("FAIL_GATE_B2B_BENCH_MIXTURE_REQUAL_RATIO_DOES_NOT_COVER_OBSERVED_BMT_PARENT" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "c_bmt_local_total_u_alloc_nM": 0.25, "mixture_requalified": True, "mixture_requalification_receipt": mix_sampled_only})})["failures"], "ADV_G41_continuous_intersample_bmt_ratio_exceeds_sampled_only_fails")
    # 12. Finite mixture receipt omitting mixture_dose_response_evidence HOLDS!
    mix_no_dr = _sign_receipt({k: v for k, v in mix_rcpt_ok.items() if k not in ("mixture_dose_response_evidence", "receipt_sha256")})
    chk("HOLD_GATE_B2B_BENCH_MISSING_MIXTURE_DOSE_RESPONSE_EVIDENCE" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "c_bmt_local_total_u_alloc_nM": 0.25, "mixture_requalified": True, "mixture_requalification_receipt": mix_no_dr})})["holds"], "ADV_G41_finite_mixture_missing_dose_response_holds")
    # 13. Finite mixture dose-response with interior safety dip (L95 < 85%) HOLDS!
    dr_bad_dip = {k: v for k, v in _mk_mix_dr(0.0, 0.25, 6.5, 21.0).items() if k != "evidence_sha256"}
    dr_bad_dip["mixture_composition_curves"][0]["mixture_safety_replicates_by_conc"][3]["nkg2a_pct"] = [78.0, 79.0, 80.0, 81.0, 82.0]
    dr_bad_dip["evidence_sha256"] = sha256_bytes(canonical_json_bytes(dr_bad_dip))
    mix_bad_dr = _sign_receipt({**mix_rcpt_ok, "mixture_dose_response_evidence": dr_bad_dip})
    chk("HOLD_GATE_B2B_BENCH_MIXTURE_REPLICATES_DO_NOT_SUBSTANTIATE_WINDOW" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "c_bmt_local_total_u_alloc_nM": 0.25, "mixture_requalified": True, "mixture_requalification_receipt": mix_bad_dr})})["holds"], "ADV_G41_finite_mixture_interior_safety_dip_holds")

    # --- GATE-42 (IIP-0064) Regressions (INVARIANT, INVARIANT, INVARIANT — 9 tests) ---
    # 14. Raw counts yielding 14.96 pp mean lift (< 15.0 pp) while rounded display pcts claim 15.00 pp (within 0.04 pp) FAILS effect threshold!
    _c1_bd_tr_sv = [6896, 6696, 7096, 6996, 6796, 6896]  # exact 68.96..70.96%, exact lift = 14.96 pp < 15.0; veh = 90.0 -> 76.6% < 85%!
    _c1_bd_tr_pct = [69.0, 67.0, 71.0, 70.0, 68.0, 69.0]  # rounded within 0.04 pp -> mean lift would falsely look like 15.00 pp!
    c1_bd_n = {**c1_norm_6, "treated_beta_surviving_by_block": _c1_bd_tr_sv, "treated_beta_t0_pct_by_block": _c1_bd_tr_pct}
    chk("FAIL_GATE_C1_NORMOXIA_BETA_EFFECT_THRESHOLD_NOT_MET" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": c1_bd_n})})["failures"], "ADV_G42_c1_exact_count_14p96_pp_blocks_15p00_rounding_bypass")
    # 15. Dual vs BCL2L11 under PAIRED_T with non-normal dual-minus-single diffs HOLDS!
    c1_h2h_nn = {**c1_norm_6}
    _bcl_nn_p = [c1_norm_6["treated_beta_t0_pct_by_block"][i] - (0.5 if i < 5 else 20.0) for i in range(6)]
    c1_h2h_nn["bcl2l11_comparator_beta_t0_pct_by_block"] = _bcl_nn_p
    c1_h2h_nn["all_five_arms_paired_data"] = {**c1_norm_6["all_five_arms_paired_data"], "BCL2L11": {**c1_norm_6["all_five_arms_paired_data"]["BCL2L11"], "treated_beta_surviving_by_block": [int(round(100 * v)) for v in _bcl_nn_p], "treated_beta_t0_pct_by_block": _bcl_nn_p}}
    chk("HOLD_GATE_C1_NORMOXIA_DUAL_H2H_NORMALITY_NOT_MET_USE_EXACT_SIGN_FLIP" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": c1_h2h_nn})})["holds"], "ADV_G42_c1_dual_h2h_nonnormal_diffs_holds_under_paired_t")
    # 16. Dual vs BCL2L11 under EXACT_TWO_SIDED_SIGN_FLIP fails when sign-flip p >= 0.05 even with positive outlier mean!
    c1_sf10_bad_h2h = _mk_r8_c1_block(assay_record_id="C1-SF10-NH", bids=[f"N{i}" for i in range(10)], c9_vec=[50.0+(i%4) for i in range(10)], ctrl_vec=[53.0+(i%3) for i in range(10)], tr_vec=[76.0+(i%3) for i in range(10)], veh_vec=[90.0+(i%2) for i in range(10)], comp_vec=[77.0, 78.0, 79.0, 77.0, 78.0, 79.0, 77.0, 78.0, 79.0, 56.0], stat_method="EXACT_TWO_SIDED_SIGN_FLIP")
    chk("FAIL_GATE_C1_NORMOXIA_DUAL_SIGN_FLIP_SUPERIORITY_VS_BCL2L11_FAILED" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "native_switch_evidence": sw_sf10, "gate0v_evidence": g0v_sf10, "c1_preregistered_plan_receipt": c1_prereg_sf10, "c1_evidence": _sign_receipt({**c1_sf10, "c1_normoxia": c1_sf10_bad_h2h}), "c2_evidence": c2_sf10, "c3_nk_evidence": c3n_sf10, "c3_gsis_evidence": c3g_sf10})["failures"], "ADV_G42_c1_dual_h2h_sign_flip_outlier_fails")
    # 17. C-3-NK assay physically acquired BEFORE GATE-0V-KILL completed (even if receipt issued later!) FAILS acquisition chronology!
    c3nk_early_acq = _sign_receipt({**c3_nk_y, "assay_started_at_utc": "2026-09-25T14:00:00Z", "transient_target_engagement_record": _mk_c_eng(c1_cohort_y, "2026-09-28T09:00:00Z", stage_name="C-3-NK", lot_s_id=ly, win_start="2026-09-25T13:00:00Z", win_end="2026-09-28T11:00:00Z")})
    chk("FAIL_GATE_C_ACQUISITION_CHRONOLOGY_VIOLATION:GATE-0V-KILL_AFTER_C-3-NK" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c3_nk_evidence": c3nk_early_acq})["failures"], "ADV_G42_c3nk_acquired_before_g0v_completed_fails")
    # 18. C-3-GSIS engagement starts AFTER C-3-GSIS assay_started_at_utc -> FAILS engagement coverage!
    eng_late_start = _mk_c_eng(c1_cohort_y, "2026-10-01T12:00:00Z", stage_name="C-3-GSIS", lot_s_id=ly, win_start="2026-09-30T18:00:00Z", win_end="2026-10-01T18:00:00Z")
    chk("FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:C-3-GSIS" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c3_gsis_evidence": _sign_receipt({**c3_gsis_y, "transient_target_engagement_record": eng_late_start})})["failures"], "ADV_G42_c3gsis_engagement_starts_after_assay_start_fails")
    # 19. Mismatched specimen_id between C-2 receipt and its transient engagement record FAILS!
    eng_bad_sp = _mk_c_eng(c1_cohort_y, "2026-09-25T08:00:00Z", stage_name="C-2", lot_s_id=ly, specimen_id="SPEC-DIFFERENT-99", win_start="2026-09-22T08:00:00Z", win_end="2026-09-25T09:00:00Z")
    chk("FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:C-2" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "transient_target_engagement_record": eng_bad_sp})})["failures"], "ADV_G42_c2_engagement_specimen_mismatch_fails")
    # 20. C-1 diversion assay with elevated cleaved caspase-3 (> 0.85x) OR spiking lytic LDH kinetics (> 20%) FAILS!
    chk("FAIL_GATE_C1_NORMOXIA_CLEAVED_CASP3_NOT_REDUCED_VS_CTRL" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "death_pathway_diversion_assay": {**c1_norm_6["death_pathway_diversion_assay"], "cleaved_casp3_fold_vs_ctrl": 1.05}}})})["failures"], "ADV_G42_c1_diversion_casp3_not_reduced_fails")
    div_lytic_spike = {**c1_norm_6["death_pathway_diversion_assay"], "lytic_ldh_or_sytox_timecourse_pct": [{"hour_h": 0.0, "treated_lytic_pct": 2.0, "ctrl_lytic_pct": 2.0}, {"hour_h": 12.0, "treated_lytic_pct": 4.0, "ctrl_lytic_pct": 4.5}, {"hour_h": 24.0, "treated_lytic_pct": 8.0, "ctrl_lytic_pct": 8.4}, {"hour_h": 48.0, "treated_lytic_pct": 28.0, "ctrl_lytic_pct": 12.0}]}
    chk("FAIL_GATE_C1_NORMOXIA_UNDECLARED_NECROPTOSIS_DIVERSION" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "death_pathway_diversion_assay": div_lytic_spike}})})["failures"], "ADV_G42_c1_diversion_lytic_spike_fails")
    # 21. GATE-36 with ONLY GATE-36-INS active accepts explicit N/A GATE-32 disposition; GATE-36-CUFF active REJECTS N/A!
    g36_ins_only = _sign_receipt({**g36_y, "active_drug_free_modules": ["GATE-36-INS"], "module_producer_receipt_sha256s": {"GATE-36-INS": "b" * 64}, "live_gate32_debris_recall_receipt": "NOT_APPLICABLE_NO_EXOGENOUS_SHIELD_OR_CUFF_DEBRIS_CLAIM"})
    att_ins_only = _sign_receipt({**att_y, "foundry_v2_gate36_receipt_sha256": g36_ins_only["receipt_sha256"], "prerequisite_receipt_sha256s": {**att_y["prerequisite_receipt_sha256s"], "GATE-36-FOUNDRY-V2": g36_ins_only["receipt_sha256"]}})
    c1p_ins = _mk_c1_prereg(py, by, ly, ry, att_ins_only)
    c1_ins = _sign_receipt({**c1_y, "parent_receipt_sha256": att_ins_only["receipt_sha256"], "prerequisite_receipt_sha256s": {**pr_c1_yc, "C-1-PREREGISTRATION": c1p_ins["receipt_sha256"]}, "c1_common_family_acquisition_record": _mk_c1_common_acq(c1_norm_6, c1_hyp_6, c1p_ins, acq_id="C1-COMMON-ACQ-INS")})
    c2_ins = _sign_receipt({**c2_y, "parent_receipt_sha256": c1_ins["receipt_sha256"]})
    sw_ins = _mk_r8_switch(py, by, ly, ry, mat_yc, "2026-09-28T14:00:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": c2_ins["receipt_sha256"]}, transient_engagement=_mk_c_eng(c1_cohort_y, "2026-09-28T13:00:00Z", stage_name="NATIVE_SAFETY_SWITCH", lot_s_id=ly, win_start="2026-09-25T12:00:00Z", win_end="2026-09-28T13:15:00Z", mode="VALIDATED_LONGITUDINAL_KINETICS"))
    g0v_ins = _mk_r8_gate0v(py, by, ly, ry, mat_yc, "2026-09-28T14:30:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": c2_ins["receipt_sha256"]}, transient_engagement=_mk_c_eng(c1_cohort_y, "2026-09-28T13:15:00Z", stage_name="GATE-0V-KILL", lot_s_id=ly, win_start="2026-09-25T12:00:00Z", win_end="2026-09-28T13:30:00Z", mode="VALIDATED_LONGITUDINAL_KINETICS"))
    pr_c3_ins = {**pr_c1_yc, "NATIVE_SAFETY_SWITCH": sw_ins["receipt_sha256"], "GATE-0V-KILL": g0v_ins["receipt_sha256"]}
    c3n_ins = _sign_receipt({**c3_nk_y, "parent_receipt_sha256": c2_ins["receipt_sha256"], "prerequisite_receipt_sha256s": pr_c3_ins})
    c3g_ins = _sign_receipt({**c3_gsis_y, "parent_receipt_sha256": c3n_ins["receipt_sha256"], "prerequisite_receipt_sha256s": pr_c3_ins})
    chk(evaluate_gate42_gy032_channel_c_screen({**g42_ok, "foundry_v2_gate36_evidence": g36_ins_only, "iip0049_foundry_attribution_evidence": att_ins_only, "c1_preregistered_plan_receipt": c1p_ins, "c1_evidence": c1_ins, "c2_evidence": c2_ins, "native_switch_evidence": sw_ins, "gate0v_evidence": g0v_ins, "c3_nk_evidence": c3n_ins, "c3_gsis_evidence": c3g_ins})["verdict"] == OFFLINE_VERDICT_PRIMARY, "ADV_G42_g36_ins_only_accepts_na_gate32_disposition")
    g36_cuff_na = _sign_receipt({**g36_y, "live_gate32_debris_recall_receipt": "NOT_APPLICABLE_NO_EXOGENOUS_SHIELD_OR_CUFF_DEBRIS_CLAIM"})
    chk("FAIL_FOUNDRY_V2_GATE36_CUFF_REQUIRES_LIVE_GATE32_RECEIPT" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "foundry_v2_gate36_evidence": g36_cuff_na})["failures"], "ADV_G42_g36_cuff_rejects_na_gate32_fails")

    # --- GATE-43 (IIP-0065) Regressions (2 tests -> total 585/585!) ---
    # 22. D-3(a) reusing a single human blood donor across all 3 lots FAILS!
    d3a_1donor = [_mk_d3a_lot(1, blood_donor_id="HUMAN-DONOR-01"), _mk_d3a_lot(2, blood_donor_id="HUMAN-DONOR-01"), _mk_d3a_lot(3, blood_donor_id="HUMAN-DONOR-01")]
    chk("FAIL_CHECK_D3A_INSUFFICIENT_INDEPENDENT_BLOOD_DONORS" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": d3a_1donor})["failures"], "ADV_G43_d3a_single_blood_donor_across_3_lots_fails")
    # 23. D-3(a) duplicate matched_blood_split_id across lots FAILS!
    d3a_dup_sp = [_mk_d3a_lot(1, matched_blood_split_id="SPLIT-DUP"), _mk_d3a_lot(2, matched_blood_split_id="SPLIT-DUP"), _mk_d3a_lot(3)]
    chk("FAIL_CHECK_D3A_DUPLICATE_OR_MISSING_BLOOD_SPLIT_ID:IEC-LOT-2" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": d3a_dup_sp})["failures"], "ADV_G43_d3a_duplicate_blood_split_id_fails")


    # ========================================================================
    # ADVERSARIAL REGRESSION SUITE (20 NEW TESTS -> 606/606 TOTAL!)
    # Adversarial fail-closed invariant regression tests.
    # ========================================================================
    # --- GATE-40 (IIP-0062) Regressions (4 tests) ---
    # 1. A-0a omitting delayed 7d sprouting grid FAILS!
    chk("FAIL_GATE_A0A_MISSING_RAW_CONC_RESPONSE_GRID" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({k: v for k, v in a0a_ok.items() if k not in ("sprouting_delayed_7d_pct_grid", "receipt_sha256")})})["failures"], "ADV_G40_a0a_missing_delayed_sprouting_grid_fails")
    # 2. A-0a Day-0 sprouting passes at 260 uM while delayed 7d sprouting drops below 90% L95 -> FAILS!
    a0a_reps_del_bad = [dict(r) for r in a0a_reps_ok]
    a0a_reps_del_bad[5] = {**a0a_reps_del_bad[5], "sprouting_delayed_7d_pct": [82.0, 82.5, 83.0, 83.5, 84.0]}
    a0a_fit_del_bad = _sign_receipt({**a0a_fit_ok, "raw_replicates_sha256": sha256_bytes(canonical_json_bytes(a0a_reps_del_bad))})
    r_a0a_del = evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "sprouting_delayed_7d_pct_grid": [100.0, 99.0, 97.5, 96.5, 94.5, 83.0, 78.0], "a0a_donor_replicates_by_conc": a0a_reps_del_bad, "a0a_fit_artifact_receipt": a0a_fit_del_bad})})
    chk("FAIL_GATE_A0A_7D_CEILING_EXCEEDS_DONOR_L95_SAFE_CONC" in r_a0a_del["failures"] and "FAIL_GATE_A0A_SPROUTING_CEILING_EXCEEDS_DAY0_OR_DELAYED_DONOR_L95" in r_a0a_del["failures"], "ADV_G40_a0a_delayed_sprouting_l95_drop_fails")
    # 3. A-4b preregistration with wrong/missing perfusion_normalization_scale FAILS!
    prereg_bad_sc = _sign_receipt({**a4b_prereg_y, "perfusion_normalization_scale": "RAW_RFU"})
    a4b_bad_sc = _sign_receipt({**a4b_y, "prerequisite_receipt_sha256s": {**pr_all_y, "A-4b-PREREGISTRATION": prereg_bad_sc["receipt_sha256"]}})
    chk("FAIL_GATE_A4B_PREREG_MISSING_PERFUSION_NORMALIZATION_SCALE" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_preregistration_receipt": prereg_bad_sc, "a4b_evidence": a4b_bad_sc})["failures"], "ADV_G40_a4b_prereg_missing_perfusion_scale_fails")
    # 4. A-4b feeding unnormalized raw fluorescence units (15000 RFU) alongside % tipping-point bounds FAILS BOTH cohorts!
    a4b_rfu = _sign_receipt({
        **a4b_y,
        "early_cohort_records": [{**r, "raw_lectin_perfusion_signal": r["raw_lectin_perfusion_signal"] * 150.0} for r in a4b_y["early_cohort_records"]],
        "day28_cohort_records": [{**r, "raw_lectin_vessel_density": r["raw_lectin_vessel_density"] * 150.0} for r in a4b_y["day28_cohort_records"]],
    })
    r_a4b_rfu = evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_evidence": a4b_rfu})
    chk("FAIL_GATE_A4B_EARLY_PERFUSION_SCALE_NOT_CONTROL_NORMALIZED" in r_a4b_rfu["failures"] and "FAIL_GATE_A4B_DAY28_VESSEL_DENSITY_SCALE_NOT_CONTROL_NORMALIZED" in r_a4b_rfu["failures"], "ADV_G40_a4b_unnormalized_rfu_perfusion_scale_fails")

    # --- GATE-41 (IIP-0063) Regressions (8 tests) ---
    # 5. Legacy flat mixture_dose_response_evidence without composition curves FAILS!
    flat_mdr_b = {
        "tested_bmt_to_parent_ratio_min": 0.0, "tested_bmt_to_parent_ratio_max": 0.25,
        "tested_free_combined_conc_grid_nM": [0.0, 2.0, 6.5, 13.75, 21.0, 42.0],
        "mixture_safety_replicates_by_conc": [[99.0, 98.5, 99.5]] * 5 + [[70.0, 72.0, 71.0]],
        "mixture_efficacy_replicates_by_conc": [[4.0, 3.5, 4.5], [28.0, 27.0, 29.0], [58.0, 57.0, 59.0], [75.0, 74.0, 76.0], [85.0, 84.0, 86.0], [90.0, 89.0, 91.0]],
    }
    flat_mdr = {**flat_mdr_b, "evidence_sha256": sha256_bytes(canonical_json_bytes(flat_mdr_b))}
    chk("FAIL_GATE_B2B_BENCH_INVALID_MIXTURE_DOSE_RESPONSE_EVIDENCE" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "c_bmt_local_total_u_alloc_nM": 0.25, "mixture_requalified": True, "mixture_requalification_receipt": _sign_receipt({**mix_rcpt_ok, "mixture_dose_response_evidence": flat_mdr})})})["failures"], "ADV_G41_mix_flat_unindexed_curves_fails")
    # 6. Composition curves stopping at 0.15 while claiming ratio_max=0.25 FAILS!
    dr_unbrack = {k: v for k, v in _mk_mix_dr(0.0, 0.25, 6.5, 21.0).items() if k != "evidence_sha256"}
    dr_unbrack["mixture_composition_curves"] = dr_unbrack["mixture_composition_curves"][:2]
    dr_unbrack["evidence_sha256"] = sha256_bytes(canonical_json_bytes(dr_unbrack))
    chk("FAIL_GATE_B2B_BENCH_INVALID_MIXTURE_DOSE_RESPONSE_EVIDENCE" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "c_bmt_local_total_u_alloc_nM": 0.25, "mixture_requalified": True, "mixture_requalification_receipt": _sign_receipt({**mix_rcpt_ok, "mixture_dose_response_evidence": dr_unbrack})})})["failures"], "ADV_G41_mix_curves_do_not_bracket_ratio_max_fails")
    # 7. Interior composition curve (ratio=0.125) has safety dip < 85% while endpoints pass -> HOLDS!
    dr_mid_dip = {k: v for k, v in _mk_mix_dr(0.0, 0.25, 6.5, 21.0).items() if k != "evidence_sha256"}
    dr_mid_dip["mixture_composition_curves"][1]["mixture_safety_replicates_by_conc"][4]["nkg2a_pct"] = [79.0, 79.5, 80.0, 80.5, 81.0]
    dr_mid_dip["evidence_sha256"] = sha256_bytes(canonical_json_bytes(dr_mid_dip))
    chk("HOLD_GATE_B2B_BENCH_MIXTURE_REPLICATES_DO_NOT_SUBSTANTIATE_WINDOW" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "c_bmt_local_total_u_alloc_nM": 0.25, "mixture_requalified": True, "mixture_requalification_receipt": _sign_receipt({**mix_rcpt_ok, "mixture_dose_response_evidence": dr_mid_dip})})})["holds"], "ADV_G41_mix_interior_ratio_curve_safety_dip_holds")
    # 8. Upper composition curve (ratio=0.25) fails efficacy at EC50 -> HOLDS!
    dr_hi_eff = {k: v for k, v in _mk_mix_dr(0.0, 0.25, 6.5, 21.0).items() if k != "evidence_sha256"}
    dr_hi_eff["mixture_composition_curves"][2]["mixture_efficacy_replicates_by_conc"][2]["iec_ibmir_marker_suppression_pct"] = [38.0, 39.0, 40.0, 41.0, 42.0]
    dr_hi_eff["evidence_sha256"] = sha256_bytes(canonical_json_bytes(dr_hi_eff))
    chk("HOLD_GATE_B2B_BENCH_MIXTURE_REPLICATES_DO_NOT_SUBSTANTIATE_WINDOW" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "c_bmt_local_total_u_alloc_nM": 0.25, "mixture_requalified": True, "mixture_requalification_receipt": _sign_receipt({**mix_rcpt_ok, "mixture_dose_response_evidence": dr_hi_eff})})})["holds"], "ADV_G41_mix_upper_ratio_curve_efficacy_fail_holds")
    # 9. Continuous inter-sample LOWER BMT/parent ratio trough falls below sampled min -> mixture with r_lo above continuous lower bound FAILS (B-2b)!
    b2b_pos_bmt = _mk_r8_b2b_replicates()
    for _tp_row in b2b_pos_bmt["timepoint_replicate_records"]:
        _lp_m = sum(_tp_row["local_parent_total_replicates_nM"]) / len(_tp_row["local_parent_total_replicates_nM"])
        _lb_t = [round(max(0.20, 0.14 * _lp_m) * (1.0 + d), 4) for d in (-0.01, -0.005, 0.0, 0.0, 0.005, 0.01)]
        _tp_row["local_bmt_total_replicates_nM"] = _lb_t
        _tp_row["local_bmt_blq_flags"] = [False] * 6
    # Sampled free ratio min is ~0.135, so r_lo=0.11 covers ALL sampled replicates, but continuous lower bound drops well below 0.11 -> MUST FAIL!
    mix_high_rlo = _sign_receipt({**mix_rcpt_ok, "tested_bmt_to_parent_ratio_min": 0.11, "tested_bmt_to_parent_ratio_max": 2.0, "mixture_dose_response_evidence": _mk_mix_dr(0.11, 2.0, 6.5, 21.0)})
    chk("FAIL_GATE_B2B_BENCH_MIXTURE_REQUAL_RATIO_DOES_NOT_COVER_OBSERVED_BMT_PARENT" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, **b2b_pos_bmt, "c_bmt_local_total_u_alloc_nM": 25.0, "c_bmt_local_free_u_alloc_nM": 5.0, "u95_joint_peak_free_nM": 20.8, "mixture_requalified": True, "mixture_requalification_receipt": mix_high_rlo})})["failures"], "ADV_G41_b2b_continuous_lower_ratio_trough_below_sampled_min_fails")
    # 10. Same continuous LOWER BMT/parent ratio trough check on B-4!
    b4_pos_lbf = [round(0.14 * p, 4) for p in b4_lpf]
    b4_pos_rep = _mk_r8_b4_replicates(b4_hrs, b4_lpf, b4_pos_lbf, b4_spf, b4_sbf)
    mix_b4_high_rlo = _sign_receipt({**mix_ex_ref, "tested_bmt_to_parent_ratio_min": 0.11, "tested_bmt_to_parent_ratio_max": 3.0, "mixture_dose_response_evidence": _mk_mix_dr(0.11, 3.0, 5.0, 25.0, tested_product_id=py)})
    chk("FAIL_GATE_B4_MIXTURE_REQUAL_RATIO_DOES_NOT_COVER_OBSERVED_BMT_PARENT" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "serial_pk_local_bmt_free_nM": b4_pos_lbf, **b4_pos_rep, "invivo_u95_joint_peak_free_nM": 21.5, "mixture_requalification_receipt": mix_b4_high_rlo})})["failures"], "ADV_G41_b4_continuous_lower_ratio_trough_below_sampled_min_fails")
    # 11. Restored B-2 endothelial PGF watch item (< 80% ctrl) FAILS!
    chk("FAIL_GATE_B2_IEC_PGF_LT_80PCT" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2_evidence": _sign_receipt({**b2_y, "iec_pgf_pct_ctrl": 72.0})})["failures"], "ADV_G41_b2_iec_pgf_below_80pct_fails")
    # 12. Restored B-2 endothelial C3 watch item (> 1.2x ctrl) FAILS!
    chk("FAIL_GATE_B2_IEC_C3_GT_1P2" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2_evidence": _sign_receipt({**b2_y, "iec_c3_fold_vs_ctrl": 1.35})})["failures"], "ADV_G41_b2_iec_c3_above_1p2_fails")

    # --- GATE-42 (IIP-0064) Regressions (4 tests) ---
    # 13. Missing start-of-window engagement (> 24 h after window start) emits distinct MISSING_START_COVERAGE HOLD (not decayed)!
    eng_late_sm = _mk_c_eng(c1_cohort_y, "2026-10-01T16:00:00Z", stage_name="C-3-GSIS", lot_s_id=ly, win_start="2026-09-30T13:00:00Z", win_end="2026-10-01T18:00:00Z", start_measured_utc="2026-10-01T14:00:00Z")
    r_late_sm = evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c3_gsis_evidence": _sign_receipt({**c3_gsis_y, "transient_target_engagement_record": eng_late_sm})})
    chk("HOLD_GATE_C_TRANSIENT_ENGAGEMENT_MISSING_START_COVERAGE:C-3-GSIS" in r_late_sm["holds"] and not any("DECAYED" in h for h in r_late_sm["holds"]), "ADV_G42_engagement_missing_start_coverage_distinct_hold")
    # 14. Reusing a single aliquot assay record ID for both start & end over a multi-day window FAILS!
    eng_same_aid = _mk_c_eng(c1_cohort_y, "2026-10-01T12:00:00Z", stage_name="C-3-GSIS", lot_s_id=ly, win_start="2026-09-30T13:00:00Z", win_end="2026-10-01T18:00:00Z", start_aliquot_id="ONE-ALIQUOT-ONLY", end_aliquot_id="ONE-ALIQUOT-ONLY")
    chk("FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:C-3-GSIS" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c3_gsis_evidence": _sign_receipt({**c3_gsis_y, "transient_target_engagement_record": eng_same_aid})})["failures"], "ADV_G42_engagement_reused_start_end_aliquot_id_fails")
    # 15. Insufficient start-of-window KD (35%) even with active end-of-window KD (78%) HOLDS as DECAYED!
    eng_low_start = _mk_c_eng(c1_cohort_y, "2026-09-25T08:00:00Z", stage_name="C-2", lot_s_id=ly, win_start="2026-09-22T08:00:00Z", win_end="2026-09-25T09:00:00Z", kd_start_v=35.0, kd_v=78.0)
    chk("HOLD_GATE_C_TRANSIENT_ENGAGEMENT_DECAYED_BEFORE_ASSAY:C-2" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "transient_target_engagement_record": eng_low_start})})["holds"], "ADV_G42_engagement_start_kd_decayed_while_end_ok_holds")
    # 16. Invalid engagement_measurement_mode FAILS!
    eng_bad_mode = _mk_c_eng(c1_cohort_y, "2026-09-25T08:00:00Z", stage_name="C-2", lot_s_id=ly, win_start="2026-09-22T08:00:00Z", win_end="2026-09-25T09:00:00Z", mode="SINGLE_ENDPOINT_ONLY")
    chk("FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:C-2" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "transient_target_engagement_record": eng_bad_mode})})["failures"], "ADV_G42_engagement_invalid_mode_fails")

    # --- GATE-43 (IIP-0065) Regressions (4 tests -> total 606/606!) ---
    # 17. D-3(a) missing source_iec_preparation_id FAILS!
    chk("FAIL_CHECK_D3A_DUPLICATE_OR_MISSING_SOURCE_IEC_PREP_ID:IEC-LOT-1" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": [_mk_d3a_lot(1, source_iec_preparation_id=""), d3a_ok_lots[1], d3a_ok_lots[2]]})["failures"], "ADV_G43_d3a_missing_source_iec_prep_id_fails")
    # 18. D-3(a) duplicate source_iec_preparation_id across lots FAILS!
    chk("FAIL_CHECK_D3A_DUPLICATE_OR_MISSING_SOURCE_IEC_PREP_ID:IEC-LOT-2" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": [_mk_d3a_lot(1, source_iec_preparation_id="SAME-PREP-01"), _mk_d3a_lot(2, source_iec_preparation_id="SAME-PREP-01"), d3a_ok_lots[2]]})["failures"], "ADV_G43_d3a_duplicate_source_iec_prep_id_fails")
    # 19. D-1 unmatched arm exposure duration (Arm A 24h vs Arm B 21h) FAILS!
    d1_bad_dur = _mk_d1_unified(g43_base, arm_b_exposure_end_utc="2026-10-03T09:05:00Z")
    chk("FAIL_CHECK_D1_EXPOSURE_WINDOW_UNMATCHED_OR_INVALID" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_paired_assay_receipt": d1_bad_dur})["failures"], "ADV_G43_d1_unmatched_arm_exposure_duration_fails")
    # 20. D-1 arm exposure ending AFTER assay_acquired_at_utc FAILS!
    d1_post_acq = _mk_d1_unified(g43_base, arm_b_exposure_start_utc="2026-10-02T15:00:00Z", arm_b_exposure_end_utc="2026-10-03T15:00:00Z")
    chk("FAIL_CHECK_D1_EXPOSURE_WINDOW_UNMATCHED_OR_INVALID" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_paired_assay_receipt": d1_post_acq})["failures"], "ADV_G43_d1_exposure_ends_after_assay_acquired_fails")


    # ========================================================================
    # ADVERSARIAL REGRESSION SUITE (22 NEW TESTS -> 628/628 TOTAL!)
    # Adversarial fail-closed invariant regression tests.
    # ========================================================================
    # --- Shared Readout-2 Zero-Variance Parity (4 tests) ---
    # 1. Zero between-block variance on Z2 WITH within_lot_technical_var_z2 = 0.008 STILL FAILS (live wetlab_contract.py parity)!
    r2_z2_zvar = _mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B", lot_id=ly)
    for _iz, _b in enumerate(r2_z2_zvar["o2_40_mmhg"]["blocks"]):
        _b["low2_value"] = 0.44
        _b["high2_value"] = 2.582857
        _b["z2_increment"] = round(_b["eta_sort_viable_recovery"] * (2.582857 - 0.44), 4)
        _b["pulse2_si"] = round(2.582857 / 0.44, 4)
        _b["kcl_value"] = round(2.582857 + 1.40 + 0.04 * _iz, 6)
        _b["matched_control_output_ratio"] = round(_b["z2_increment"] / _b["matched_control_z2_increment"], 6)
    chk("FAIL_GATE_A2_READOUT2_O2_40_RECOMPUTED_L95_Z2_BELOW_ZMIN" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": r2_z2_zvar})})["failures"], "ADV_shared_r2_z2_zero_variance_with_tech_var_fails")
    # 2. Constant Gate 0M stepdown_t90_min = [2.6]*6 HOLDS + FAILS (zero fallback to point estimate)!
    r2_t90_zvar = _mk_r8_readout2(matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1", lot_id="D2-LOT-1", lot_jitter=1.0)
    for _b in r2_t90_zvar["o2_40_mmhg"]["blocks"]:
        _b["stepdown_t90_min"] = 2.6
    r_t90_zv = evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, readout2_evidence=r2_t90_zvar), _mk_d2_lot(2), _mk_d2_lot(3)]})
    chk("HOLD_CHECK_D2_D2-LOT-1_READOUT2_O2_40_DEGENERATE_ZERO_VARIANCE_UNESTIMABLE" in r_t90_zv["holds"] and "FAIL_CHECK_D2_D2-LOT-1_READOUT2_O2_40_GATE0M_SHUTOFF_T90_U95_GT_3MIN_FAILED" in r_t90_zv["failures"], "ADV_shared_r2_gate0m_t90_zero_variance_holds_and_fails")
    # 3. Constant Gate 0M glucagon_fold = [2.5]*6 HOLDS + FAILS!
    r2_gcg_zvar = _mk_r8_readout2(matched_comparator_id="CTRL-LOT-1", block_prefix="D2L1", meas_id="MEAS-D2-LOT-1", lot_id="D2-LOT-1", lot_jitter=1.0)
    for _b in r2_gcg_zvar["o2_40_mmhg"]["blocks"]:
        _b["glucagon_fold"] = 2.5
    r_gcg_zv = evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, readout2_evidence=r2_gcg_zvar), _mk_d2_lot(2), _mk_d2_lot(3)]})
    chk("HOLD_CHECK_D2_D2-LOT-1_READOUT2_O2_40_DEGENERATE_ZERO_VARIANCE_UNESTIMABLE" in r_gcg_zv["holds"] and "FAIL_CHECK_D2_D2-LOT-1_READOUT2_O2_40_GATE0M_PARACRINE_GLUCAGON_L95_FAILED" in r_gcg_zv["failures"], "ADV_shared_r2_gate0m_paracrine_zero_variance_holds_and_fails")
    # 4. Constant stored_insulin_per_lot_iu = [110.0]*6 HOLDS!
    r2_st_zvar = _mk_r8_readout2(matched_comparator_id=bv_a, block_prefix="A2B", lot_id=ly)
    r2_st_zvar["stored_insulin_per_lot_iu"] = [110.0] * 6
    chk("HOLD_GATE_A2_READOUT2_STORED_INSULIN_ZERO_VARIANCE_UNESTIMABLE" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout2_evidence": r2_st_zvar})})["holds"], "ADV_shared_r2_stored_insulin_zero_variance_holds")

    # --- GATE-40 (IIP-0062) Regressions (3 tests) ---
    # 5. A-0b omitting explicit 24.0 h sample ([6, 48, 120, 192, 264, 336]) FAILS!
    a0b_tp_no24 = _mk_pfd_tp_rows(((6.0, 182.0), (48.0, 160.0), (120.0, 140.0), (192.0, 128.0), (264.0, 116.0), (336.0, 108.0)), coat_a["coating_lot_id"], "A0BNO24")
    chk("FAIL_GATE_A0B_LOCAL_EXPOSURE_SCHEDULE_GAP_OR_MALFORMED" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "a0b_local_exposure_timepoints": a0b_tp_no24})})["failures"], "ADV_G40_a0b_missing_24h_sample_fails")
    # 6. Direct clipped subinterval check on boundary-straddling [6.0, 48.0] catches trough on [24.0, 48.0] < 75 uM!
    _, tr_straddle = _compute_pfd_continuous_envelope_24_336(
        [6.0, 48.0, 336.0], [180.0, 150.0, 110.0], [82.0, 78.0, 95.0], ke_a=0.015, kr_a=0.015, ke_w=0.015,
    )
    chk(tr_straddle < 75.0, "ADV_G40_pfd_envelope_boundary_straddle_6_48h_trough_caught")
    # 7. A-1 continuous trough dip across [24.0, 96.0] below IC50_U95=75 uM FAILS even when every sampled point >= 78 uM!
    a1_tp_ctdip = _mk_pfd_tp_rows(((6.0, 92.0), (24.0, 82.0), (96.0, 80.0), (168.0, 82.0), (240.0, 84.0), (312.0, 86.0), (336.0, 86.0), (600.0, 22.0), (840.0, 3.2)), coat_a["coating_lot_id"], "A1CT", deltas=(-0.4, 0.0, 0.4, 0.2))
    a1e_env_mid = _mk_pfd_env("exact_product", "BENCH_ELUTION_LOCAL_PERI_GRAFT", ke_a=0.008, kr_a=0.008, ke_w=0.010)
    chk("FAIL_GATE_A1_DAYS1_14_INTERIOR_FREE_PARENT_DIP_BELOW_IC50_U95" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "day1_intact_parent_free_uM": 120.0, "day14_intact_parent_free_uM": 82.0, "a1_local_free_parent_timepoints": a1_tp_ctdip, "a1_local_pk_envelope": a1e_env_mid})})["failures"], "ADV_G40_a1_continuous_trough_24_96h_dip_below_ic50_fails")

    # --- GATE-41 (IIP-0063) Regressions (7 tests) ---
    # 8. B-0a omitting 3rd biological efficacy grid (efficacy_iec_ibmir_pct_grid) FAILS!
    chk("FAIL_GATE_B0A_MISSING_RAW_CONC_RESPONSE_GRID" in evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": _sign_receipt({k: v for k, v in b0a_ok.items() if k not in ("efficacy_iec_ibmir_pct_grid", "receipt_sha256")})})["failures"], "ADV_G41_b0a_missing_3_endpoint_efficacy_grids_fails")
    # 9. B-0a where beta & NK pass (>= 70%) at EC50_U95=6 nM while endothelial IBMIR suppression L95 < 50% HOLDS!
    b0a_ei_weak = list(b0a_ei_grid); b0a_ei_weak[3] = 44.0
    b0a_e_reps_weak = [dict(r) for r in b0a_e_reps_ok]
    _weak_vals = [43.62, 43.80, 43.94, 44.06, 44.20, 44.38]
    b0a_e_reps_weak[3] = {**b0a_e_reps_weak[3], "iec_ibmir_marker_suppression_pct": _weak_vals, "raw_unit_measurements": {**b0a_e_reps_weak[3]["raw_unit_measurements"], "iec_ibmir_marker_suppression_pct": _mk_b0a_raw_ratio(_weak_vals, b0a_e_reps_weak[3]["matched_vehicle_record_id"], 250.0, is_inhib=True)}}
    b0a_an_weak = _sign_receipt({**b0a_an_ok, "raw_efficacy_replicates_sha256": sha256_bytes(canonical_json_bytes(b0a_e_reps_weak))})
    chk("HOLD_GATE_B0A_EC50_U95_UNSUBSTANTIATED_BY_EFFICACY_REPLICATES" in evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": _sign_receipt({**b0a_ok, "efficacy_inhibition_pct_grid": b0a_ei_weak, "efficacy_iec_ibmir_pct_grid": b0a_ei_weak, "efficacy_replicates_by_conc": b0a_e_reps_weak, "b0a_analysis_receipt": b0a_an_weak})})["holds"], "ADV_G41_b0a_single_endpoint_iec_ibmir_below_50pct_holds")
    # 10. B-2b non-zero efficacy_window_start_h = 4.0 (skipping Day-0 first blood contact) FAILS!
    b2b_eff4 = _mk_r8_b2b_replicates()
    eb_eff4 = {k: v for k, v in b2b_eff4["intersample_pk_envelope"].items() if k != "envelope_receipt_sha256"}
    eb_eff4["efficacy_window_start_h"] = 4.0
    b2b_eff4["intersample_pk_envelope"] = {**eb_eff4, "envelope_receipt_sha256": sha256_bytes(canonical_json_bytes(eb_eff4))}
    chk("FAIL_GATE_B2B_BENCH_INVALID_INTERSAMPLE_ENVELOPE_PARAMS" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, **b2b_eff4})})["failures"], "ADV_G41_b2b_nonzero_efficacy_window_start_h_fails")
    # 11. B-4 non-zero efficacy_window_start_h = 2.0 (skipping Day-0 first blood contact) FAILS!
    eb4_eff2 = {k: v for k, v in b4_y["intersample_pk_envelope"].items() if k != "envelope_receipt_sha256"}
    eb4_eff2["efficacy_window_start_h"] = 2.0
    eb4_eff2["envelope_receipt_sha256"] = sha256_bytes(canonical_json_bytes(eb4_eff2))
    chk("FAIL_GATE_B4_INVALID_INTERSAMPLE_ENVELOPE_PARAMS" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "intersample_pk_envelope": eb4_eff2})})["failures"], "ADV_G41_b4_nonzero_efficacy_window_start_h_fails")
    # 12. B-2b recirc_assay_matrix == "whole_blood" WITHOUT systemic_kbp_calibration FAILS!
    chk("FAIL_GATE_B2B_BENCH_MISSING_OR_INVALID_WHOLE_BLOOD_KBP_CALIBRATION" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "recirc_assay_matrix": "whole_blood"})})["failures"], "ADV_G41_b2b_whole_blood_missing_kbp_calibration_fails")
    # 13. B-2b whole_blood with low K_bp (0.15) pushes plasma equivalent >= 0.5 nM -> FAILS, while valid K_bp (1.25) PASSES!
    kbp_b2b_low_b = {
        "kbp_assay_method_id": "BENCH-WHOLE-BLOOD-KBP-V1",
        "blood_to_plasma_ratio_parent_replicates": [0.14, 0.15, 0.16, 0.15, 0.14, 0.16],
        "blood_to_plasma_ratio_bmt_replicates": [0.14, 0.15, 0.16, 0.15, 0.14, 0.16],
        "alpha_kbp_parent": 0.004, "alpha_kbp_bmt": 0.004,
    }
    kbp_b2b_low = {**kbp_b2b_low_b, "calibration_sha256": sha256_bytes(canonical_json_bytes(kbp_b2b_low_b))}
    kbp_b2b_ok_b = {**kbp_b2b_low_b, "blood_to_plasma_ratio_parent_replicates": [1.24, 1.25, 1.26, 1.25, 1.24, 1.26], "blood_to_plasma_ratio_bmt_replicates": [1.20, 1.22, 1.21, 1.23, 1.22, 1.24]}
    kbp_b2b_ok = {**kbp_b2b_ok_b, "calibration_sha256": sha256_bytes(canonical_json_bytes(kbp_b2b_ok_b))}
    wb_rec_fu_ok = [0.118, 0.119, 0.120, 0.120, 0.121, 0.122]
    b1_wb = _sign_receipt({**b1_y, "analytical_sample_ledger": _mk_b12_ledger("B-1", recirc_assay_matrix="whole_blood")})
    b2_wb = _sign_receipt({**b2_y, "parent_receipt_sha256": b1_wb["receipt_sha256"], "analytical_sample_ledger": _mk_b12_ledger("B-2", recirc_assay_matrix="whole_blood")})
    b2bb_wb_base = {**b2bb_y, "parent_receipt_sha256": b2_wb["receipt_sha256"], "prerequisite_receipt_sha256s": {"B-1": b1_wb["receipt_sha256"], "B-2": b2_wb["receipt_sha256"]}, "recirc_assay_matrix": "whole_blood", "alpha_conc": 0.018, "alpha_fu_parent": 0.010, "alpha_fu_bmt": 0.010, "recirc_fu_bmt_replicates": wb_rec_fu_ok, "alpha_fu_bmt_recirc": 0.004}
    r_b2b_wb_fail = evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b1_evidence": b1_wb, "b2_evidence": b2_wb, "b2b_bench_evidence": _sign_receipt({**b2bb_wb_base, "systemic_kbp_calibration": kbp_b2b_low})})
    r_b2b_wb_ok = evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b1_evidence": b1_wb, "b2_evidence": b2_wb, "b2b_bench_evidence": _sign_receipt({**b2bb_wb_base, "systemic_kbp_calibration": kbp_b2b_ok})})
    chk("FAIL_GATE_B2B_BENCH_RECOMPUTED_SYSTEMIC_U95_GE_0P5NM" in r_b2b_wb_fail["failures"] and r_b2b_wb_ok["verdict"] == "PASS_BENCH_ONLY_UNEDITED_PRE_MATERIALIZATION", "ADV_G41_b2b_whole_blood_low_kbp_fails_and_valid_kbp_passes")
    # 14. Endpoint-only [0.0, 0.25] (no interior curve) AND wide sparse [0.0, 1.5, 3.0] (gap 1.5 > 0.50) both FAIL!
    dr_ep_only = {k: v for k, v in _mk_mix_dr(0.0, 0.25, 6.5, 21.0).items() if k != "evidence_sha256"}
    dr_ep_only["mixture_composition_curves"] = [dr_ep_only["mixture_composition_curves"][0], dr_ep_only["mixture_composition_curves"][-1]]
    dr_ep_only["evidence_sha256"] = sha256_bytes(canonical_json_bytes(dr_ep_only))
    dr_wide_sp = {k: v for k, v in _mk_mix_dr(0.0, 3.0, 6.5, 21.0).items() if k != "evidence_sha256"}
    dr_wide_sp["mixture_composition_curves"] = [dr_wide_sp["mixture_composition_curves"][0], dr_wide_sp["mixture_composition_curves"][3], dr_wide_sp["mixture_composition_curves"][-1]]
    dr_wide_sp["evidence_sha256"] = sha256_bytes(canonical_json_bytes(dr_wide_sp))
    chk(
        "FAIL_GATE_B2B_BENCH_MIXTURE_COMPOSITION_RATIO_GRID_TOO_SPARSE" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "c_bmt_local_total_u_alloc_nM": 0.25, "mixture_requalified": True, "mixture_requalification_receipt": _sign_receipt({**mix_rcpt_ok, "mixture_dose_response_evidence": dr_ep_only})})})["failures"]
        and "FAIL_GATE_B2B_BENCH_MIXTURE_COMPOSITION_RATIO_GRID_TOO_SPARSE" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "c_bmt_local_total_u_alloc_nM": 0.25, "mixture_requalified": True, "mixture_requalification_receipt": _sign_receipt({**mix_rcpt_ok, "tested_bmt_to_parent_ratio_max": 3.0, "mixture_dose_response_evidence": dr_wide_sp})})})["failures"],
        "ADV_G41_mix_endpoint_only_or_sparse_ratio_grid_fails",
    )

    # --- GATE-42 (IIP-0064) Regressions (6 tests) ---
    # 15. 20.5-hour safety-switch assay window (< 72 h required for 24h/72h kill endpoints) FAILS!
    sw_short20 = _mk_r8_switch(py, by, ly, ry, mat_yc, "2026-09-26T09:00:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": c2_y["receipt_sha256"]}, transient_engagement=_mk_c_eng(c1_cohort_y, "2026-09-26T08:00:00Z", stage_name="NATIVE_SAFETY_SWITCH", lot_s_id=ly, win_start="2026-09-25T12:00:00Z", win_end="2026-09-26T08:30:00Z", mode="VALIDATED_LONGITUDINAL_KINETICS"))
    chk("FAIL_GATE_C_SAFETY_SWITCH_24H_72H_ENDPOINT_TIMING_INVALID:NATIVE_SAFETY_SWITCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "native_switch_evidence": sw_short20})["failures"], "ADV_G42_switch_short_20h_window_fails_24h_72h_timing")
    # 16. GATE-0V-KILL using PAIRED_START_AND_END_ALIQUOT_ASSAY instead of VALIDATED_LONGITUDINAL_KINETICS FAILS!
    g0v_paired_only = _mk_r8_gate0v(py, by, ly, ry, mat_yc, "2026-09-28T14:30:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": c2_y["receipt_sha256"]}, transient_engagement=_mk_c_eng(c1_cohort_y, "2026-09-28T13:15:00Z", stage_name="GATE-0V-KILL", lot_s_id=ly, win_start="2026-09-25T12:00:00Z", win_end="2026-09-28T13:30:00Z", mode="PAIRED_START_AND_END_ALIQUOT_ASSAY"))
    chk("FAIL_GATE_C_SAFETY_SWITCH_REQUIRES_VALIDATED_LONGITUDINAL_KINETICS:GATE-0V-KILL" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "gate0v_evidence": g0v_paired_only})["failures"], "ADV_G42_switch_paired_only_mode_rejected_requires_longitudinal")
    # 17. Longitudinal kinetics with interior 48-h KD dip (42% < 60%) while 0 h & 72 h stay >= 78% HOLDS decayed!
    sw_mid_dip = _mk_r8_switch(py, by, ly, ry, mat_yc, "2026-09-28T14:00:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": c2_y["receipt_sha256"]}, transient_engagement=_mk_c_eng(c1_cohort_y, "2026-09-28T13:00:00Z", stage_name="NATIVE_SAFETY_SWITCH", lot_s_id=ly, win_start="2026-09-25T12:00:00Z", win_end="2026-09-28T13:15:00Z", mode="VALIDATED_LONGITUDINAL_KINETICS", mid_kd_override=42.0))
    chk("HOLD_GATE_C_TRANSIENT_ENGAGEMENT_DECAYED_BEFORE_ASSAY:NATIVE_SAFETY_SWITCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "native_switch_evidence": sw_mid_dip})["holds"], "ADV_G42_longitudinal_interior_48h_kd_dip_holds_decayed")
    # 18. C-1 raw caspase-9 pairs yielding exact 39.96% (< 40%) while display claims 40.00% FAILS!
    c1_c9_3996 = {
        **c1_norm_6,
        "casp9_stressed_ctrl_raw_by_block": [100.0] * 6,
        "casp9_treated_raw_by_block": [60.04] * 6,
        "casp9_reduction_pct_by_block": [40.0] * 6,
    }
    chk("FAIL_GATE_C1_NORMOXIA_MEAN_CASP9_REDUCTION_BELOW_40PCT" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": c1_c9_3996})})["failures"], "ADV_G42_c1_raw_casp9_39p96pct_blocks_40p00_display_rounding")
    # 19. Block-resolved INS_beta with canceling +4 pp / -4 pp errors across blocks 0 & 1 (identical pooled mean!) FAILS!
    ltc_cancel = {**c1_norm_6["lineage_timecourse_counts"], "INS_beta": [dict(b_e, timepoints=[dict(t) for t in b_e["timepoints"]]) for b_e in c1_norm_6["lineage_timecourse_counts"]["INS_beta"]]}
    ltc_cancel["INS_beta"][0]["timepoints"][-1]["treated_surviving_n"] += 40
    ltc_cancel["INS_beta"][1]["timepoints"][-1]["treated_surviving_n"] -= 40
    chk("FAIL_GATE_C1_NORMOXIA_INS_BETA_TIMECOURSE_MISMATCH_VS_PRIMARY" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "lineage_timecourse_counts": ltc_cancel}})})["failures"], "ADV_G42_c1_block_resolved_ins_beta_canceling_error_fails")
    # 20. Non-beta lineage (PLVAP_iEC) recovering at 48 h but dipping to 82% at 24 h FAILS!
    ltc_24dip = {**c1_norm_6["lineage_timecourse_counts"], "PLVAP_iEC": [dict(b_e, timepoints=[dict(t) for t in b_e["timepoints"]]) for b_e in c1_norm_6["lineage_timecourse_counts"]["PLVAP_iEC"]]}
    for _be in ltc_24dip["PLVAP_iEC"]:
        _be["timepoints"][1]["treated_surviving_n"] = int(round(0.82 * _be["timepoints"][1]["ctrl_surviving_n"]))
    chk("FAIL_GATE_C1_NORMOXIA_NONBETA_TIMECOURSE_COUNTS_BELOW_FLOOR_OR_MISMATCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "lineage_timecourse_counts": ltc_24dip}})})["failures"], "ADV_G42_c1_nonbeta_24h_intermediate_dip_fails")

    # --- GATE-43 (IIP-0065) Polish (2 tests -> total 628/628!) ---
    # 21. D-1 GSIS endpoint acquired with unmatched post-exposure wait (Arm A +0.5h vs Arm B +1.8h -> diff 1.3h > 0.5h) FAILS!
    d1_gsis_wait = (lambda _b: {**_b, "record_sha256": sha256_bytes(canonical_json_bytes(_b))})({
        **{k: v for k, v in g43_base["check_d1_paired_gsis_record"].items() if k != "record_sha256"},
        "arm_b_acquired_at_utc": "2026-10-03T13:55:00Z",
    })
    g43_d1_wait = {**g43_base, "check_d1_paired_gsis_record": d1_gsis_wait}
    g43_d1_wait["check_d1_paired_assay_receipt"] = _mk_d1_unified(g43_d1_wait)
    chk("FAIL_CHECK_D1_ENDPOINT_ACQUISITION_TIMING_UNMATCHED_OR_INVALID:check_d1_paired_gsis_record" in evaluate_gate43_cellgemma_guardrails_and_pilots(g43_d1_wait)["failures"], "ADV_G43_d1_endpoint_unmatched_post_exposure_wait_fails")
    # 22. D-1 FACS endpoint acquired BEFORE arm_b_exposure_end_utc FAILS!
    d1_facs_early = (lambda _b: {**_b, "record_sha256": sha256_bytes(canonical_json_bytes(_b))})({
        "lot_id": "D1-LOT-001", "plate_id": "D1-PLATE-01", "sibling_aliquot_pair_id": "D1-SIBPAIR-01",
        "arm_a_acquired_at_utc": "2026-10-03T12:30:00Z", "arm_b_acquired_at_utc": "2026-10-03T11:30:00Z",
        "icam1_mfi_ratio_b_over_a": 0.94, "vcam1_mfi_ratio_b_over_a": 0.96,
    })
    g43_d1_early = {**g43_base, "check_d1_paired_facs_record": d1_facs_early}
    g43_d1_early["check_d1_paired_assay_receipt"] = _mk_d1_unified(g43_d1_early)
    chk("FAIL_CHECK_D1_ENDPOINT_ACQUISITION_TIMING_UNMATCHED_OR_INVALID:check_d1_paired_facs_record" in evaluate_gate43_cellgemma_guardrails_and_pilots(g43_d1_early)["failures"], "ADV_G43_d1_endpoint_acquired_before_exposure_end_fails")


    # ========================================================================
    # PROVISIONAL PK, IL-10 WASHOUT, SWITCH-START COVERAGE, C-2 LOT BINDING,
    # D-1 CHEMISTRY/ABSOLUTE GSIS & D-3A LLOQ SUITE (24 NEW TESTS -> 652/652!)
    # ========================================================================
    # --- GATE-41 B-0b Provisional PK Exposure & Clearance Bounds (6 tests) ---
    chk("HOLD_GATE_B0B_PROVISIONAL_PK_MODEL_MISSING" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b0b_evidence": _sign_receipt({**b0b_y, "provisional_pk_model_receipt": None})})["holds"], "G41_b0b_missing_provisional_pk_model_holds")
    chk("FAIL_GATE_B0B_MODELED_DAYS0_10_PARENT_BELOW_B0A_EC50_U95" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b0b_evidence": _sign_receipt({**b0b_y, "provisional_pk_model_receipt": _mk_b0b_pk_model(b0a_ok["receipt_sha256"], modeled_days0_10_parent_l95_free_nM=4.5)})})["failures"], "G41_b0b_modeled_day0_10_parent_below_ec50_fails")
    chk("FAIL_GATE_B0B_MODELED_DAYS0_21_PEAK_GE_B0A_CSAFE_BENCH" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b0b_evidence": _sign_receipt({**b0b_y, "provisional_pk_model_receipt": _mk_b0b_pk_model(b0a_ok["receipt_sha256"], modeled_days0_21_combined_peak_u95_free_nM=26.5)})})["failures"], "G41_b0b_modeled_day0_21_peak_above_csafe_fails")
    chk("FAIL_GATE_B0B_MODELED_SYSTEMIC_CMAX_GE_0P5NM" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b0b_evidence": _sign_receipt({**b0b_y, "provisional_pk_model_receipt": _mk_b0b_pk_model(b0a_ok["receipt_sha256"], modeled_systemic_combined_cmax_u95_total_nM=0.65)})})["failures"], "G41_b0b_modeled_systemic_cmax_ge_0p5_fails")
    chk("FAIL_GATE_B0B_ROUTE_CLEARANCE_OUT_OF_RANGE" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b0b_evidence": _sign_receipt({**b0b_y, "route_clearance_l_per_day": 0.2})})["failures"], "G41_b0b_unrealistic_low_route_clearance_fails")
    chk("FAIL_GATE_B0B_USABLE_RECOVERY_EXCEEDS_85PCT" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b0b_evidence": _sign_receipt({**b0b_y, "usable_recovery_fraction": 0.96})})["failures"], "G41_b0b_usable_recovery_above_85pct_fails")

    # --- GATE-41 B-3 Time/Lot-Bound IL-10 Washout Assay & B-2b/B-4 Early t0 Boundary (5 tests) ---
    chk("HOLD_GATE_B3_IL10_WASHOUT_RECOVERY_ASSAY_MISSING" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b3_evidence": _sign_receipt({**b3_y, "il10_washout_recovery_assay": None})})["holds"], "G41_b3_missing_il10_washout_assay_holds")
    chk("FAIL_GATE_B3_IL10_WASHOUT_INTERVAL_NOT_72H" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b3_evidence": _sign_receipt({**b3_y, "il10_washout_recovery_assay": _mk_b3_il10_assay(recov_utc="2026-10-06T09:00:00Z")})})["failures"], "G41_b3_il10_washout_24h_interval_fails")
    chk("FAIL_GATE_B3_IL10_RECOVERY_MISMATCH_VS_RAW_DONORS" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b3_evidence": _sign_receipt({**b3_y, "il10_washout_recovery_assay": _mk_b3_il10_assay(mean_rec=91.0)})})["failures"], "G41_b3_il10_declared_vs_raw_donor_mismatch_fails")
    chk("FAIL_GATE_B3_IL10_WASHOUT_RECOVERY_ASSAY_INVALID" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b3_evidence": _sign_receipt({**b3_y, "il10_washout_recovery_assay": _mk_b3_il10_assay(lot_id_v="OTHER-LOT-99")})})["failures"], "G41_b3_il10_wrong_lot_id_fails")
    b2b_late6 = _mk_r8_b2b_replicates()
    b2b_late6["timepoint_replicate_records"][0]["hour_h"] = 12.0
    chk("HOLD_GATE_B2B_BENCH_MISSING_EARLY_INITIAL_EXPOSURE_SAMPLE_FOR_T0_BOUNDARY" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, **b2b_late6})})["holds"], "G41_b2b_late_12h_first_sample_t0_boundary_holds")

    # --- GATE-42 Switch Actual Assay-Start/End Longitudinal Coverage & C-2 Per-Lot Associations (7 tests) ---
    # Drop t=0 start observation by shifting start_measured_at_utc 10 h AFTER assay start (while keeping 24h & 72h passing!)
    eng_sw_no_t0 = _mk_c_eng(
        c1_cohort_y, "2026-09-28T13:00:00Z", stage_name="NATIVE_SAFETY_SWITCH", lot_s_id=ly,
        win_start="2026-09-25T12:00:00Z", win_end="2026-09-28T13:15:00Z",
        start_measured_utc="2026-09-25T22:30:00Z", mode="VALIDATED_LONGITUDINAL_KINETICS",
    )
    sw_no_t0 = _mk_r8_switch(py, by, ly, ry, mat_yc, "2026-09-28T14:00:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": c2_y["receipt_sha256"]}, transient_engagement=eng_sw_no_t0)
    chk("HOLD_GATE_C_TRANSIENT_ENGAGEMENT_MISSING_START_COVERAGE:NATIVE_SAFETY_SWITCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "native_switch_evidence": sw_no_t0})["holds"], "G42_switch_missing_actual_assay_start_t0_holds")
    # Same start-lag test on GATE-0V-KILL (2h lag after dimerizer induction -> HOLD even though within 24h of declared window start!)
    eng_g0v_lag2h = _mk_c_eng(
        c1_cohort_y, "2026-09-28T13:15:00Z", stage_name="GATE-0V-KILL", lot_s_id=ly,
        win_start="2026-09-25T12:00:00Z", win_end="2026-09-28T13:30:00Z",
        start_measured_utc="2026-09-25T14:30:00Z", mode="VALIDATED_LONGITUDINAL_KINETICS",
    )
    g0v_lag2h = _mk_r8_gate0v(py, by, ly, ry, mat_yc, "2026-09-28T14:30:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": c2_y["receipt_sha256"]}, transient_engagement=eng_g0v_lag2h)
    chk("HOLD_GATE_C_TRANSIENT_ENGAGEMENT_MISSING_START_COVERAGE:GATE-0V-KILL" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "gate0v_evidence": g0v_lag2h})["holds"], "G42_gate0v_2h_lag_after_assay_start_holds")
    # Stale end observation (4 h before assay completion) on NATIVE_SAFETY_SWITCH -> HOLD!
    eng_sw_early_end = _mk_c_eng(
        c1_cohort_y, "2026-09-28T09:00:00Z", stage_name="NATIVE_SAFETY_SWITCH", lot_s_id=ly,
        win_start="2026-09-25T12:00:00Z", win_end="2026-09-28T13:15:00Z",
        mode="VALIDATED_LONGITUDINAL_KINETICS",
    )
    sw_early_end = _mk_r8_switch(py, by, ly, ry, mat_yc, "2026-09-28T14:00:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": c2_y["receipt_sha256"]}, transient_engagement=eng_sw_early_end)
    chk("HOLD_GATE_C_TRANSIENT_ENGAGEMENT_STALE_BEFORE_ASSAY_END:NATIVE_SAFETY_SWITCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "native_switch_evidence": sw_early_end})["holds"], "G42_switch_stale_before_actual_assay_end_holds")
    # Producer specimen mismatch inside a longitudinal kinetics timepoint -> FAIL!
    eng_bad_tp_sp = {k: v for k, v in sw_y_c["transient_target_engagement_record"].items() if k != "engagement_record_sha256"}
    eng_bad_tp_sp["longitudinal_kinetics_timepoints"] = [dict(r) for r in eng_bad_tp_sp["longitudinal_kinetics_timepoints"]]
    eng_bad_tp_sp["longitudinal_kinetics_timepoints"][0]["specimen_id"] = "WRONG-SPEC-99"
    eng_bad_tp_sp["engagement_record_sha256"] = sha256_bytes(canonical_json_bytes(eng_bad_tp_sp))
    chk("FAIL_GATE_C_INVALID_OR_UNBOUND_TRANSIENT_ENGAGEMENT:NATIVE_SAFETY_SWITCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "native_switch_evidence": _sign_receipt({**sw_y_c, "transient_target_engagement_record": eng_bad_tp_sp})})["failures"], "G42_switch_longitudinal_tp_specimen_mismatch_fails")
    # C-2 missing active lot participation -> FAIL!
    chk("FAIL_GATE_C2_ACTIVE_LOT_MISSING_FROM_PROLIFERATION_RECORDS" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "c2_per_lot_proliferation_records": [_mk_c2_prolif_lot(1, lot_id="OTHER-LOT-1"), c2_prolif_ok[1], c2_prolif_ok[2]]})})["failures"], "G42_c2_missing_active_lot_participation_fails")
    # C-2 child candidate_gene mismatch -> FAIL!
    chk(f"FAIL_GATE_C2_PROLIF_LOT_CANDIDATE_OR_PRODUCT_MISMATCH:{ly}" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "c2_per_lot_proliferation_records": [_mk_c2_prolif_lot(1, candidate_gene="BCL2L11"), c2_prolif_ok[1], c2_prolif_ok[2]]})})["failures"], "G42_c2_child_candidate_gene_mismatch_fails")
    # C-2 active lot comparator_nt_lot_id mismatch vs outer nt_lot_id -> FAIL!
    chk(f"FAIL_GATE_C2_PROLIF_LOT_COMPARATOR_MISMATCH:{ly}" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "c2_per_lot_proliferation_records": [_mk_c2_prolif_lot(1, comparator_nt_lot_id="WRONG-NT-99"), c2_prolif_ok[1], c2_prolif_ok[2]]})})["failures"], "G42_c2_active_lot_comparator_mismatch_fails")

    # --- GATE-43 D-1 Chemistry Provenance + Basal/Stimulated GSIS & D-3(a) TAT LLOQ + Condition (6 tests) ---
    d1_bad_si = (lambda _b: {**_b, "record_sha256": sha256_bytes(canonical_json_bytes(_b))})({
        **{k: v for k, v in g43_base["check_d1_paired_gsis_record"].items() if k != "record_sha256"},
        "arm_b_stim_40": 1.20,
    })
    g43_d1_bsi = {**g43_base, "check_d1_paired_gsis_record": d1_bad_si}
    g43_d1_bsi["check_d1_paired_assay_receipt"] = _mk_d1_unified(g43_d1_bsi)
    chk("FAIL_CHECK_D1_GSIS_SI_BASAL_STIM_MISMATCH" in evaluate_gate43_cellgemma_guardrails_and_pilots(g43_d1_bsi)["failures"], "G43_d1_gsis_si_vs_basal_stim_mismatch_fails")
    d1_abs_drop = (lambda _b: {**_b, "record_sha256": sha256_bytes(canonical_json_bytes(_b))})({
        **{k: v for k, v in g43_base["check_d1_paired_gsis_record"].items() if k != "record_sha256"},
        "arm_b_basal_40": 0.25, "arm_b_stim_40": 1.025, "arm_b_si_40": 4.1,
    })
    g43_d1_drop = {**g43_base, "check_d1_paired_gsis_record": d1_abs_drop}
    g43_d1_drop["check_d1_paired_assay_receipt"] = _mk_d1_unified(g43_d1_drop)
    chk("HOLD_CHECK_D1_GSIS_ABSOLUTE_STIMULATED_OUTPUT_DROP" in evaluate_gate43_cellgemma_guardrails_and_pilots(g43_d1_drop)["holds"], "G43_d1_gsis_equal_si_with_collapsed_absolute_output_holds")
    d1_bad_chem = _mk_d1_unified(g43_base, arm_b_chemistry_sample={
        "sample_id": "D1-CHEM-B-LATE", "sibling_aliquot_pair_id": "D1-SIBPAIR-01",
        "collected_at_utc": "2026-10-02T10:00:00Z", "instrument_record_sha256": "2" * 64,
    })
    chk("FAIL_CHECK_D1_CHEMISTRY_SAMPLE_PROVENANCE_OR_TIMING_INVALID" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_paired_assay_receipt": d1_bad_chem})["failures"], "G43_d1_chemistry_sample_outside_exposure_window_fails")
    chk("HOLD_CHECK_D3A_TAT_COMPARATOR_NEAR_OR_BELOW_LLOQ:IEC-LOT-1" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": [_mk_d3a_lot(1, tat_assay_lloq_ng_ml=5.0, chandler_tat_nt_ctrl_ng_ml=10.0, chandler_tat_f3_sirna_ng_ml=6.0), d3a_ok_lots[1], d3a_ok_lots[2]]})["holds"], "G43_d3a_tat_nt_near_lloq_holds")
    chk("FAIL_CHECK_D3A_INCONSISTENT_OR_INVALID_INFLAMMATORY_CONDITION" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": [_mk_d3a_lot(1, inflammatory_challenge_condition="BASAL_UNSTIMULATED"), d3a_ok_lots[1], d3a_ok_lots[2]]})["failures"], "G43_d3a_mixed_inflammatory_conditions_across_lots_fails")
    chk("FAIL_CHECK_D3A_PAIRED_ASSAY_PROVENANCE_INVALID:IEC-LOT-2" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": [_mk_d3a_lot(1), _mk_d3a_lot(2, paired_assay_run_id="D3A-PAIRED-RUN-01"), d3a_ok_lots[2]]})["failures"], "G43_d3a_duplicate_paired_assay_run_id_fails")


    # ========================================================================
    # EXTRUSION RECONCILIATION, SIMULTANEOUS BONFERRONI DOSE-GRID, MATRIX-MATCHED
    # RECIRCULATION FU, DUAL MRNA/PROTEIN KD, C-2 COMPONENT SHIELDS, & D-3A/D-1
    # QUANTIFICATION SUITE (20 NEW TESTS -> 672/672!)
    # ========================================================================
    # --- GATE-40 A-4b Extrusion Reconciliation & A-0a Simultaneous Grid Bonferroni (5 tests) ---
    # 1. Measured Day-28 animal tagged IMPLANT_EXTRUSION while top-level implant_extrusions == 0 FAILS!
    a4b_hidden_extr = _sign_receipt({
        **a4b_y,
        "day28_cohort_records": [{**a4b_y["day28_cohort_records"][0], "adverse_event_code": "IMPLANT_EXTRUSION"}, *a4b_y["day28_cohort_records"][1:]],
    })
    r_a4b_he = evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_evidence": a4b_hidden_extr})
    chk("FAIL_GATE_A4B_IMPLANT_EXTRUSION_DETECTED" in r_a4b_he["failures"] and "FAIL_GATE_A4B_EXTRUSION_COUNT_MISMATCH_VS_ANIMAL_RECORDS" in r_a4b_he["failures"], "G40_a4b_measured_animal_extrusion_contradicts_zero_total_fails")
    # 2. Early measured animal with free-text unrecognized AE code FAILS!
    a4b_bad_ae = _sign_receipt({
        **a4b_y,
        "early_cohort_records": [{**a4b_y["early_cohort_records"][0], "adverse_event_code": "MILD_FREE_TEXT_NOTE"}, *a4b_y["early_cohort_records"][1:]],
    })
    chk("FAIL_GATE_A4B_UNRECOGNIZED_ADVERSE_EVENT_CODE:E-COAT-01" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_evidence": a4b_bad_ae})["failures"], "G40_a4b_unstructured_ae_code_fails")
    # 3. Excluded animal tagged IMPLANT_EXTRUSION even with adverse_event_related == False STILL FAILS!
    a4b_exc_extr = _sign_receipt({
        **a4b_y,
        "prerequisite_receipt_sha256s": {**pr_all_y, "A-4b-PREREGISTRATION": prereg_ae_d["receipt_sha256"]},
        "day28_cohort_enrolled_coated_n": 9,
        "day28_cohort_exclusions": [{"animal_id": "D28-COAT-09", "arm": "COATED", "reason": "SAMPLE_LOSS_PRE_ADJUDICATION", "pre_adjudication_decision": True, "excluded_at_utc": "2026-12-21T09:00:00Z", "adverse_event_related": False, "adverse_event_code": "IMPLANT_EXTRUSION"}],
    })
    chk("FAIL_GATE_A4B_IMPLANT_EXTRUSION_DETECTED" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a4b_preregistration_receipt": prereg_ae_d, "a4b_evidence": a4b_exc_extr})["failures"], "G40_a4b_excluded_animal_extrusion_fails")
    # 4. A-0a unverified external fit method label rejected!
    a0a_fit_badm = _sign_receipt({**a0a_fit_ok, "analysis_method": "EXTERNAL_UNREPLAYED_4PL"})
    chk("FAIL_GATE_A0A_FIT_ARTIFACT_DIGEST_OR_SUMMARY_MISMATCH" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "a0a_fit_artifact_receipt": a0a_fit_badm})})["failures"], "G40_a0a_unreplayed_external_fit_method_fails")
    # 5. A-0a dose clearing pointwise alpha=0.05 (mean=52, sd=1.5, L95_pw=50.57 >= 50) yet failing simultaneous Bonferroni alpha=0.05/14 (L_sim=48.55 < 50) HOLDS!
    a0a_pw_only = [dict(r) for r in a0a_reps_ok]
    a0a_pw_only[3] = {**a0a_pw_only[3], "col1a1_inhibition_pct": [50.0, 51.0, 52.0, 53.0, 54.0]}
    a0a_fit_pw = _sign_receipt({**a0a_fit_ok, "raw_replicates_sha256": sha256_bytes(canonical_json_bytes(a0a_pw_only))})
    chk("HOLD_GATE_A0A_IC50_U95_UNSUBSTANTIATED_BY_DONOR_REPLICATES" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "a0a_donor_replicates_by_conc": a0a_pw_only, "a0a_fit_artifact_receipt": a0a_fit_pw})})["holds"], "G40_a0a_pointwise_only_fails_simultaneous_grid_bonferroni_holds")

    # --- GATE-41 B-2b Matrix-Bound fu & B-0a Simultaneous Grid Bonferroni (5 tests) ---
    # 6. B-2b distinct recirc_assay_matrix ("low_serum_media", fu=0.86) WITHOUT recirc_fu_bmt_replicates FAILS!
    chk("FAIL_GATE_B2B_BENCH_MISSING_OR_INVALID_RECIRC_MATRIX_FU_BMT_CALIBRATION" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "recirc_assay_matrix": "low_serum_media"})})["failures"], "G41_b2b_distinct_recirc_matrix_missing_fu_fails")
    # 7. B-2b distinct recirc_assay_matrix ("low_serum_media") with mismatched serum fu (0.15 instead of 0.86) FAILS!
    chk("FAIL_GATE_B2B_BENCH_RECIRC_FU_BMT_MISMATCH_VS_B0A_MATRIX" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "recirc_assay_matrix": "low_serum_media", "alpha_conc": 0.020, "recirc_fu_bmt_replicates": [0.148, 0.150, 0.152], "alpha_fu_bmt_recirc": 0.005})})["failures"], "G41_b2b_recirc_fu_mismatched_vs_b0a_matrix_fails")
    # 8. B-2b local fu_parent_replicates mismatched vs B-0a local_assay_matrix (0.85 instead of 0.14) FAILS!
    chk("FAIL_GATE_B2B_BENCH_LOCAL_FU_PARENT_MISMATCH_VS_B0A_MATRIX" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "fu_parent_replicates": [0.84, 0.85, 0.86]})})["failures"], "G41_b2b_local_fu_mismatched_vs_b0a_matrix_fails")
    # 9. B-0a unverified FOUR_PARAM_LOGISTIC_PROFILE_LIKELIHOOD label rejected!
    chk("FAIL_GATE_B0A_ANALYSIS_RECEIPT_MISMATCH" in evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": _sign_receipt({**b0a_ok, "b0a_analysis_receipt": _sign_receipt({**b0a_an_ok, "analysis_method": "FOUR_PARAM_LOGISTIC_PROFILE_LIKELIHOOD"})})})["failures"], "G41_b0a_unreplayed_4pl_label_fails")
    # 10. B-0a dose clearing pointwise alpha=0.05 (mean=53, sd=2.0, L95_pw=51.09 >= 50) yet failing simultaneous Bonferroni alpha=0.05/24 (L_sim=47.68 < 50) HOLDS!
    b0a_ei_pw = list(b0a_ei_grid); b0a_ei_pw[3] = 53.0
    b0a_e_reps_pw = [dict(r) for r in b0a_e_reps_ok]
    _pw_vals = [50.0, 51.2, 52.4, 53.6, 54.8, 56.0]
    b0a_e_reps_pw[3] = {**b0a_e_reps_pw[3], "iec_ibmir_marker_suppression_pct": _pw_vals, "raw_unit_measurements": {**b0a_e_reps_pw[3]["raw_unit_measurements"], "iec_ibmir_marker_suppression_pct": _mk_b0a_raw_ratio(_pw_vals, b0a_e_reps_pw[3]["matched_vehicle_record_id"], 250.0, is_inhib=True)}}
    b0a_an_pw = _sign_receipt({**b0a_an_ok, "raw_efficacy_replicates_sha256": sha256_bytes(canonical_json_bytes(b0a_e_reps_pw))})
    chk("HOLD_GATE_B0A_EC50_U95_UNSUBSTANTIATED_BY_EFFICACY_REPLICATES" in evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": _sign_receipt({**b0a_ok, "efficacy_inhibition_pct_grid": b0a_ei_pw, "efficacy_iec_ibmir_pct_grid": b0a_ei_pw, "efficacy_replicates_by_conc": b0a_e_reps_pw, "b0a_analysis_receipt": b0a_an_pw})})["holds"], "G41_b0a_pointwise_only_fails_simultaneous_grid_bonferroni_holds")

    # --- GATE-42 C-1 Separate mRNA & Protein KD, C-2 Component Shields, & G36 Drug-Free Pin (5 tests) ---
    # 11. C-1 high mRNA KD (82%) with low protein KD (52% < 70%) FAILS (Barthson Fig. 4E-F distinction)!
    chk("FAIL_GATE_C1_NORMOXIA_KD_BELOW_70PCT" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "target_kd_pct": 52.0, "mrna_kd_pct": 82.0, "protein_kd_pct": 52.0}})})["failures"], "G42_c1_high_mrna_low_protein_kd_fails")
    # 12. C-1 identical mRNA and protein assay IDs FAILS separate assay verification!
    chk("FAIL_GATE_C1_NORMOXIA_MISSING_SEPARATE_MRNA_AND_PROTEIN_KD" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "protein_assay_record_id": c1_norm_6["mrna_assay_record_id"]}})})["failures"], "G42_c1_identical_mrna_and_protein_assay_ids_fails")
    # 13. C-1 dual arm where PMAIP1 protein KD drops to 55% while mRNA stays 83% FAILS!
    chk("FAIL_GATE_C1_NORMOXIA_DUAL_TARGET_COMPONENT_KD_FAILED" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "pmaip1_kd_pct": 55.0, "pmaip1_protein_kd_pct": 55.0}})})["failures"], "G42_c1_dual_pmaip1_low_protein_kd_fails")
    # 14. C-2 single shield component dropping below 85% (SERPINB9=76%) FAILS per-component check!
    chk("FAIL_GATE_C2_SHIELD_COMPONENT_BELOW_85PCT:SERPINB9" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "basal_shield_retention_by_component": {**_mk_r8_shields(py, 93.0), "SERPINB9": 76.0}})})["failures"], "G42_c2_single_shield_component_below_85pct_fails")
    # 15. GATE-36 Foundry receipt missing DRUG_FREE_EXPOSURE prerequisite pin FAILS!
    g36_no_df = _sign_receipt({k: v for k, v in g36_y.items() if k not in ("prerequisite_receipt_sha256s", "receipt_sha256")})
    chk("FAIL_MISSING_PREREQUISITE_RECEIPT_DIGEST_MAP:GATE-36-FOUNDRY-V2" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "foundry_v2_gate36_evidence": g36_no_df})["failures"], "G42_g36_missing_drug_free_prereq_pin_fails")

    # --- GATE-43 D-3(a) TAT LLOQ Consistency + ELISA Row Uniqueness & D-1 End-of-Exposure Chemistry (5 tests) ---
    # 16. D-3(a) quantified reading (tat_f3_below_lloq=False) with value 3.0 < LLOQ 5.0 FAILS analytical contradiction!
    chk("FAIL_CHECK_D3A_TAT_QUANTIFIED_BELOW_LLOQ:IEC-LOT-1" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": [_mk_d3a_lot(1, tat_assay_lloq_ng_ml=5.0, tat_f3_below_lloq=False, chandler_tat_f3_sirna_ng_ml=3.0), d3a_ok_lots[1], d3a_ok_lots[2]]})["failures"], "G43_d3a_quantified_tat_below_lloq_fails")
    # 17. D-3(a) censored reading (tat_f3_below_lloq=True, tat_f3=None) imputes LLOQ=5.0 cleanly and PASSES when NTC >= 15 & >= 20% reduction!
    d3a_cens_lots = [_mk_d3a_lot(1, tat_assay_lloq_ng_ml=5.0, tat_f3_below_lloq=True, chandler_tat_f3_sirna_ng_ml=None), d3a_ok_lots[1], d3a_ok_lots[2]]
    d3b_cens_rcpt = _sign_receipt({**d3b_rcpt_a, "d3a_lot_receipt_sha256s": [r["receipt_sha256"] for r in d3a_cens_lots]})
    r_d3a_cens = evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": d3a_cens_lots, "d3b_pilot_receipt": d3b_cens_rcpt})
    chk(r_d3a_cens["verdict"] == "PASS_DESCRIPTIVE_PILOT_ZERO_ODDS_GY037_WARN_RETAINED", "G43_d3a_valid_censored_blq_tat_passes")
    # 18. D-3(a) overlapping (raw_elisa_record_sha256, raw_elisa_well_or_row_id) across two lots FAILS!
    shared_elisa = sha256_bytes(b"SHARED-PLATE-EXPORT")
    chk("FAIL_CHECK_D3A_OVERLAPPING_ELISA_SOURCE_ROW:IEC-LOT-2" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d3a_per_lot_records": [_mk_d3a_lot(1, raw_elisa_record_sha256=shared_elisa, raw_elisa_well_or_row_id="WELL-A1"), _mk_d3a_lot(2, raw_elisa_record_sha256=shared_elisa, raw_elisa_well_or_row_id="WELL-A1"), d3a_ok_lots[2]]})["failures"], "G43_d3a_overlapping_elisa_source_row_fails")
    # 19. D-1 early-only chemistry collected at start of 24h exposure (12:00 Day 0 instead of end-of-exposure Day 1) FAILS!
    d1_early_chem = _mk_d1_unified(g43_base, arm_a_chemistry_sample={
        "sample_id": "D1-CHEM-A-EARLY", "sibling_aliquot_pair_id": "D1-SIBPAIR-01",
        "collected_at_utc": "2026-10-02T12:15:00Z", "instrument_record_sha256": "1" * 64,
        "instrument_row_or_injection_id": "INJ-A-EARLY",
    })
    chk("FAIL_CHECK_D1_CHEMISTRY_SAMPLE_PROVENANCE_OR_TIMING_INVALID" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_paired_assay_receipt": d1_early_chem})["failures"], "G43_d1_early_only_start_chemistry_fails")
    # 20. D-1 unmatched end-of-exposure chemistry timing (Arm A at +0.0h, Arm B at +0.9h -> diff 0.9h > 0.5h) FAILS!
    d1_unmatch_chem = _mk_d1_unified(g43_base, arm_b_chemistry_sample={
        "sample_id": "D1-CHEM-B-LATE", "sibling_aliquot_pair_id": "D1-SIBPAIR-01",
        "collected_at_utc": "2026-10-03T12:59:00Z", "instrument_record_sha256": "2" * 64,
        "instrument_row_or_injection_id": "INJ-B-LATE",
    })
    chk("FAIL_CHECK_D1_CHEMISTRY_SAMPLE_PROVENANCE_OR_TIMING_INVALID" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_paired_assay_receipt": d1_unmatch_chem})["failures"], "G43_d1_unmatched_arm_chemistry_timing_fails")


    # ========================================================================
    # ADVERSARIAL REGRESSION SUITE (16 NEW TESTS -> 688/688 TOTAL!)
    # ========================================================================
    # --- Exposure-Specific H3 Combined Model Firewall (2 tests) ---
    # 1. Toggling IIP-0064 (C) ON vs OFF changes coated-only (B_COAT/R2_COAT, Y_COAT/R3P_COAT) by exact 0.000000 pp!
    _ab_only = _eval_wave7_in_wave6_state("CHK_AB_ONLY", a_on=True, b_on=True, c_on=False, tier="CENTRAL", ceiling_lift=True, compute_strassen=False)
    _abc_exp = _eval_wave7_in_wave6_state("CHK_ABC_EXP", a_on=True, b_on=True, c_on=True, tier="CENTRAL", ceiling_lift=True, compute_strassen=False)
    _abc_cf_c = _eval_wave7_in_wave6_state("CHK_ABC_CF", a_on=True, b_on=True, c_on=True, tier="CENTRAL", ceiling_lift=True, allow_c_on_coated_paths=True, compute_strassen=False)
    chk(abs(_abc_exp["coated_only_by_modular_exact"] - _ab_only["coated_only_by_modular_exact"]) <= 1e-12, "G42_combined_h3_zero_c_spillover_onto_coated_by")
    # 2. Exposure-specific combined strictly excludes unverified C credit on coated paths (< counterfactual C-on-coated) while preserving standalone C!
    chk(_abc_exp["modular_exact"] < _abc_cf_c["modular_exact"] and _abc_exp["modular_exact"] > _ab_only["modular_exact"], "G42_combined_h3_exposure_specific_below_cf_and_above_ab")

    # --- GATE-40 (IIP-0062) 3-Component Vascular & Independent-Unit PK + Zero-Dispersion HOLDs (5 tests) ---
    # 3. A-0b preserved sprout length (94%) with lost Day-4 network persistence (81% < 90%) HOLDS!
    a0b_np_drop = [dict(r) for r in a0b_reps_ok]
    a0b_np_drop[5] = {**a0b_np_drop[5], "day4_network_persistence_14d_pct": [80.7, 81.0, 81.3], "day4_delayed_sprouting_14d_pct": [80.7, 81.0, 81.3], "raw_donor_measurements": {**a0b_np_drop[5]["raw_donor_measurements"], "day4_network_persistence_14d": _mk_a0b_raw_pair([80.7, 81.0, 81.3], 0.89)}}
    a0b_fit_np = _sign_receipt({**a0b_fit_ok, "raw_replicates_sha256": sha256_bytes(canonical_json_bytes(a0b_np_drop))})
    chk("HOLD_GATE_A0B_14D_CEILING_UNSUBSTANTIATED_BY_DONOR_REPLICATES" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "a0b_14d_safety_replicates_by_conc": a0b_np_drop, "a0b_fit_artifact_receipt": a0b_fit_np})})["holds"], "G40_a0b_network_persistence_drop_holds")
    # 4. A-2 preserved sprout length (95%) with failing branching (82% < 90%) FAILS!
    _a2_bad_br_vb = {k: v for k, v in a2_y["a2_vascular_raw_measurements"].items() if k != "vascular_assay_receipt_sha256"}
    _a2_bad_br_vb["treated_branching_junctions"] = 22.96
    a2_bad_br = _sign_receipt({
        **a2_y, "day14_iec_branching_pct_ctrl": 82.0,
        "a2_vascular_raw_measurements": {**_a2_bad_br_vb, "vascular_assay_receipt_sha256": sha256_bytes(canonical_json_bytes(_a2_bad_br_vb))},
    })
    chk("FAIL_GATE_A2_DAY14_IEC_BRANCHING_BELOW_90PCT" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": a2_bad_br})["failures"], "G40_a2_branching_below_90pct_fails")
    # 5. A-0b identical zero-dispersion safety replicates [95.0, 95.0, 95.0] HOLDS (no silent min fallback)!
    a0b_zdisp = [dict(r) for r in a0b_reps_ok]
    a0b_zdisp[5] = {**a0b_zdisp[5], "viability_14d_pct": [95.0, 95.0, 95.0], "raw_donor_measurements": {**a0b_zdisp[5]["raw_donor_measurements"], "viability_14d": _mk_a0b_raw_pair([95.0, 95.0, 95.0], 96.5)}}
    a0b_fit_zd = _sign_receipt({**a0b_fit_ok, "raw_replicates_sha256": sha256_bytes(canonical_json_bytes(a0b_zdisp))})
    chk("HOLD_GATE_A0B_14D_SAFETY_ZERO_DISPERSION_UNESTIMABLE" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "a0b_14d_safety_replicates_by_conc": a0b_zdisp, "a0b_fit_artifact_receipt": a0b_fit_zd})})["holds"], "G40_a0b_safety_zero_dispersion_holds")
    # 6. A-0b local PK with identical zero-dispersion readings HOLDS (no min/max fallback)!
    a0b_tp_zd = _mk_pfd_tp_rows(a0b_tp_pts, coat_a["coating_lot_id"], "A0BZD", deltas=(0.0, 0.0, 0.0, 0.0))
    chk("HOLD_GATE_A0B_LOCAL_PK_ZERO_DISPERSION_UNESTIMABLE" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "a0b_local_exposure_timepoints": a0b_tp_zd})})["holds"], "G40_a0b_local_pk_zero_dispersion_holds")
    # 7. A-1 local PK with mismatched coating_lot_id or duplicate independent_unit_id FAILS!
    a1_tp_badlot = _mk_pfd_tp_rows(a1_tp_pts, "WRONG-COATING-LOT-99", "A1BL")
    chk("FAIL_GATE_A1_LOCAL_FREE_PARENT_SCHEDULE_GAP_OR_MALFORMED" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "a1_local_free_parent_timepoints": a1_tp_badlot})})["failures"], "G40_a1_local_pk_mismatched_coating_lot_fails")

    # --- GATE-41 (IIP-0063) 7-Endpoint Mixture Panel, Simultaneous Bonferroni, Zero-Disp, & Readout-3B (6 tests) ---
    # 8. Mixture curve with sprouting_pct = 87% (>= old 85%, < B-0a 90% floor!) HOLDS!
    dr_spr87 = {k: v for k, v in _mk_mix_dr(0.0, 0.25, 6.5, 21.0).items() if k != "evidence_sha256"}
    dr_spr87["mixture_composition_curves"][1]["mixture_safety_replicates_by_conc"][4]["sprouting_pct"] = [86.8, 86.9, 87.0, 87.1, 87.2]
    dr_spr87["evidence_sha256"] = sha256_bytes(canonical_json_bytes(dr_spr87))
    chk("HOLD_GATE_B2B_BENCH_MIXTURE_REPLICATES_DO_NOT_SUBSTANTIATE_WINDOW" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "c_bmt_local_total_u_alloc_nM": 0.25, "mixture_requalified": True, "mixture_requalification_receipt": _sign_receipt({**mix_rcpt_ok, "mixture_dose_response_evidence": dr_spr87})})})["holds"], "G41_mix_sprouting_87pct_below_90pct_floor_holds")
    # 9. Mixture curve with zero-dispersion replicates HOLDS (no silent min fallback)!
    dr_zdisp = {k: v for k, v in _mk_mix_dr(0.0, 0.25, 6.5, 21.0).items() if k != "evidence_sha256"}
    dr_zdisp["mixture_composition_curves"][0]["mixture_safety_replicates_by_conc"][2]["sprouting_pct"] = [96.0, 96.0, 96.0, 96.0, 96.0]
    dr_zdisp["evidence_sha256"] = sha256_bytes(canonical_json_bytes(dr_zdisp))
    chk("HOLD_GATE_B2B_BENCH_MIXTURE_ZERO_DISPERSION_UNESTIMABLE" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "c_bmt_local_total_u_alloc_nM": 0.25, "mixture_requalified": True, "mixture_requalification_receipt": _sign_receipt({**mix_rcpt_ok, "mixture_dose_response_evidence": dr_zdisp})})})["holds"], "G41_mix_zero_dispersion_holds")
    # 10. Mixture curve clearing pointwise alpha=0.05 (mean=54, sd=2.5, L95_pw=51.6 >= 50) yet failing simultaneous Bonferroni alpha=0.05/54 HOLDS!
    dr_pw = {k: v for k, v in _mk_mix_dr(0.0, 0.25, 6.5, 21.0).items() if k != "evidence_sha256"}
    dr_pw["mixture_composition_curves"][2]["mixture_efficacy_replicates_by_conc"][2]["beta_cytokine_protection_pct"] = [51.0, 52.5, 54.0, 55.5, 57.0]
    dr_pw["evidence_sha256"] = sha256_bytes(canonical_json_bytes(dr_pw))
    chk("HOLD_GATE_B2B_BENCH_MIXTURE_REPLICATES_DO_NOT_SUBSTANTIATE_WINDOW" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "c_bmt_local_total_u_alloc_nM": 0.25, "mixture_requalified": True, "mixture_requalification_receipt": _sign_receipt({**mix_rcpt_ok, "mixture_dose_response_evidence": dr_pw})})})["holds"], "G41_mix_pointwise_only_fails_simultaneous_bonferroni_holds")
    # 11. BMT-alone panel with zero-dispersion OR sprouting < 90% HOLDS!
    bmt_bad_sp = {k: v for k, v in _mk_bmt_alone("BENCH_UNEDITED_PANEL").items() if k != "evidence_sha256"}
    bmt_bad_sp["bmt_alone_safety_replicates_by_conc"][4]["sprouting_pct"] = [87.8, 87.9, 88.0, 88.1, 88.2]
    bmt_bad_sp["evidence_sha256"] = sha256_bytes(canonical_json_bytes(bmt_bad_sp))
    mix_bmt88 = _sign_receipt({**mix_full_both, "bmt_alone_qualification_evidence": bmt_bad_sp})
    chk("HOLD_GATE_B2B_BENCH_BMT_ALONE_REPLICATES_DO_NOT_SUBSTANTIATE_WINDOW" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, **b2b_both_blq_fin, "u95_joint_peak_free_nM": 23.5, "c_bmt_local_total_u_alloc_nM": 3.0, "c_bmt_local_free_u_alloc_nM": 0.6, "mixture_requalification_receipt": mix_bmt88})})["holds"], "G41_bmt_alone_sprouting_88pct_holds")
    # 12. Readout-3B missing covalent HLA-E SCT comparator on HLA-E engineered product Y FAILS!
    r3b_no_sct = _mk_r8_readout3b(include_sirpa_low=True, matched_vehicle_lot_id=bv_b)
    r3b_no_sct["covalent_hla_e_sct_comparator"] = None
    chk("FAIL_GATE_B3_READOUT3B_MISSING_COVALENT_HLAE_SCT_COMPARATOR" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b3_evidence": _sign_receipt({**b3_y, "readout3b_evidence": r3b_no_sct})})["failures"], "G41_b3_r3b_missing_covalent_hlae_sct_fails")
    # 13. Readout-3B Regime II continuous 0-24 h kinetic trace spiking to 14% at 12 h FAILS even when terminal 24 h passes!
    r3b_kspike = _mk_r8_readout3b(include_sirpa_low=True, matched_vehicle_lot_id=bv_b)
    _kt0 = {k: v for k, v in r3b_kspike["donor_records"][0]["regime_ii_t0_unpreinduced"]["continuous_0_24h_kinetic_trace"].items() if k != "trace_sha256"}
    _kt0["target_lysis_pct_series"] = [0.0, 4.0, 9.5, 14.2, 8.0, 5.2]
    r3b_kspike["donor_records"][0]["regime_ii_t0_unpreinduced"]["continuous_0_24h_kinetic_trace"] = {**_kt0, "trace_sha256": sha256_bytes(canonical_json_bytes(_kt0))}
    chk("FAIL_GATE_B3_READOUT3B_R2_MISSING_0_24H_KINETIC_TRACE:NK-D1" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b3_evidence": _sign_receipt({**b3_y, "readout3b_evidence": r3b_kspike})})["failures"], "G41_b3_r3b_0_24h_kinetic_spike_fails")

    # --- GATE-42 (IIP-0064) C-1 Mandatory Delivery-Only Mock-Transfection Control (3 tests) ---
    # 14. C-1 omitting mock_transfection_control_by_block HOLDS!
    chk("HOLD_GATE_C1_NORMOXIA_MISSING_MOCK_TRANSFECTION_CONTROL" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "mock_transfection_control_by_block": None}})})["holds"], "G42_c1_missing_mock_transfection_holds")
    # 15. C-1 toxic delivery reagent (unstressed mock survival drops to 55% vs 90% vehicle) FAILS!
    mock_tox = [{**m, "unstressed_mock_surviving": 5500} for m in c1_norm_6["mock_transfection_control_by_block"]]
    chk("FAIL_GATE_C1_NORMOXIA_MOCK_DELIVERY_TOXICITY_EXCESSIVE" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "mock_transfection_control_by_block": mock_tox}})})["failures"], "G42_c1_mock_delivery_toxicity_fails")
    # 16. C-1 stressed mock showing artifactual rescue (+20 pp above stressed NT) FAILS concordance/specificity!
    mock_art = [{**m, "stressed_mock_surviving": 7600} for m in c1_norm_6["mock_transfection_control_by_block"]]
    chk("FAIL_GATE_C1_NORMOXIA_MOCK_CONTROL_CONCORDANCE_OR_SPECIFICITY_FAILED" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "mock_transfection_control_by_block": mock_art}})})["failures"], "G42_c1_mock_artifactual_rescue_fails")


    # ========================================================================
    # ADVERSARIAL REGRESSION SUITE (16 NEW TESTS -> 704/704 TOTAL!)
    # ========================================================================
    # --- GATE-41 (IIP-0063) Metabolite-Specific Rates & Compact [0,1] Fraction Coverage (5 tests) ---
    # 1. Exact midpoint surge counterexample: parent 1.0->0.98->1.0, BMT 0.01->0.03->0.01 (flat total 1.01, k_rise_local=0.01/h, k_rise_bmt=1.0/h) catches midpoint ratio >= 0.0306 (vs old combined-rate 0.01051)!
    _env_bmt_surge = _mk_env_t(
        k_elim_local_max_per_h=0.01, k_rise_local_max_per_h=0.01,
        k_elim_parent_max_per_h=0.04, k_rise_parent_max_per_h=0.04,
        k_elim_bmt_max_per_h=1.0, k_rise_bmt_max_per_h=1.0,
        k_elim_sys_max_per_h=0.02, k_rise_sys_max_per_h=0.02,
        efficacy_window_start_h=0.0, envelope_model_sha256="b" * 64,
    )
    _, _r_surge_max, _ = _compute_continuous_bmt_parent_ratio_bounds(
        [0.0, 2.0], [0.01, 0.01], [0.01, 0.01], [1.0, 1.0], [1.0, 1.0],
        _env_bmt_surge, fails=[], prefix="TSURGE",
    )
    chk(_r_surge_max > 0.028, "G41_bmt_specific_rate_catches_midpoint_surge_under_flat_total")
    # 2. Envelope omitting k_rise_bmt_max_per_h FAILS!
    _eb_nobmt = {k: v for k, v in b2bb_y["intersample_pk_envelope"].items() if k not in ("k_rise_bmt_max_per_h", "envelope_receipt_sha256")}
    _eb_nobmt["envelope_receipt_sha256"] = sha256_bytes(canonical_json_bytes(_eb_nobmt))
    chk("FAIL_GATE_B2B_BENCH_MISSING_QUANTITATIVE_INTERSAMPLE_ENVELOPE" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, "intersample_pk_envelope": _eb_nobmt})})["failures"], "G41_envelope_missing_bmt_specific_rate_fails")
    # 3. Parent-BLQ with finite max == 0 omitting mixture_dose_response_evidence STILL HOLDS (never skipped)!
    _b2b_all_pblq = _mk_r8_b2b_replicates()
    for _tp_r in _b2b_all_pblq["timepoint_replicate_records"]:
        _tp_r["local_parent_total_replicates_nM"] = [0.0] * 6
        _tp_r["local_parent_blq_flags"] = [True] * 6
    _mix_only_bmt = _sign_receipt({
        "stage": "MIXTURE_REQUALIFICATION", "verdict": "PASS", "product_id": py, "bank_id": by, "lot_id": ly, "route_id": ry,
        "evidence_scope": "bench_unedited", "recorded_at_utc": "2026-09-12T09:00:00Z", **coat_b,
        "analysis_record_sha256": "d" * 64, "tested_bmt_to_parent_ratio_min": 0.0, "tested_bmt_to_parent_ratio_max": 0.25,
        "mixture_ec50_eff_u95_free_nM": 5.0, "mixture_c_safe_max_l95_free_nM": 25.0,
        "metabolite_dominant_unbounded_ratio_qualified": True,
        "bmt_alone_qualification_evidence": bmt_alone_ok_ref,
    })
    chk("HOLD_GATE_B2B_BENCH_MISSING_MIXTURE_DOSE_RESPONSE_EVIDENCE" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, **_b2b_all_pblq, "mixture_requalification_receipt": _mix_only_bmt})})["holds"], "G41_parent_blq_cannot_skip_mixture_panel_holds")
    # 4. Parent-BLQ with mixture grid stopping at f_BMT=0.50 (r=1.0) + bmt_alone leaves high-finite (0.50, 1.0) untested -> HOLDS!
    _mix_gap_hi = _sign_receipt({**mix_full_both, "mixture_dose_response_evidence": _mk_mix_dr(0.0, 1.0, 5.0, 25.0, cover_unbounded_to_1=False)})
    chk("HOLD_GATE_B2B_BENCH_UNBOUNDED_HIGH_FINITE_MIXTURE_GAP_UNQUALIFIED" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, **b2b_both_blq_fin, "u95_joint_peak_free_nM": 23.5, "c_bmt_local_total_u_alloc_nM": 3.0, "c_bmt_local_free_u_alloc_nM": 0.6, "mixture_requalification_receipt": _mix_gap_hi})})["holds"], "G41_parent_blq_high_finite_composition_gap_holds")
    # 5. Parent-BLQ with sparse fraction grid [0.0, 0.20, 1.0] (gap 0.80 > 0.25!) HOLDS!
    _dr_sp_f = {k: v for k, v in _mk_mix_dr(0.0, 1.0, 5.0, 25.0, cover_unbounded_to_1=True).items() if k != "evidence_sha256"}
    _dr_sp_f["mixture_composition_curves"] = [_dr_sp_f["mixture_composition_curves"][0], _dr_sp_f["mixture_composition_curves"][1], _dr_sp_f["mixture_composition_curves"][-1]]
    _dr_sp_f["evidence_sha256"] = sha256_bytes(canonical_json_bytes(_dr_sp_f))
    chk("HOLD_GATE_B2B_BENCH_UNBOUNDED_HIGH_FINITE_MIXTURE_GAP_UNQUALIFIED" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, **b2b_both_blq_fin, "u95_joint_peak_free_nM": 23.5, "c_bmt_local_total_u_alloc_nM": 3.0, "c_bmt_local_free_u_alloc_nM": 0.6, "mixture_requalification_receipt": _sign_receipt({**mix_full_both, "mixture_dose_response_evidence": _dr_sp_f})})})["holds"], "G41_parent_blq_sparse_fraction_grid_holds")

    # --- GATE-42 (IIP-0064) Live GY-016 Lineage-Block Diversion & Even-Count Hodges-Lehmann (5 tests) ---
    # 6. C-1 diversion missing PLVAP_iEC lineage HOLDS!
    _div_no_iec = {**c1_norm_6["death_pathway_diversion_assay"], "lineage_block_diversion_records": {"INS_beta": c1_norm_6["death_pathway_diversion_assay"]["lineage_block_diversion_records"]["INS_beta"]}}
    chk("HOLD_GATE_C1_NORMOXIA_DIVERSION_MISSING_REQUIRED_LINEAGE" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "death_pathway_diversion_assay": _div_no_iec}})})["holds"], "G42_c1_gy016_missing_iec_lineage_holds")
    # 7. C-1 diversion with only 2 timepoints [0 h, 24 h] (no intermediate <= 12 h or 48 h) HOLDS!
    _div_2pt = {**c1_norm_6["death_pathway_diversion_assay"], "locked_timecourse_schedule_h": [0.0, 24.0]}
    chk("HOLD_GATE_C1_NORMOXIA_DIVERSION_TIMECOURSE_COVERAGE_INCOMPLETE" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "death_pathway_diversion_assay": _div_2pt}})})["holds"], "G42_c1_gy016_2pt_timecourse_incomplete_holds")
    # 8. C-1 PLVAP_iEC single block necroptosis rescue spike (Nec-1s = +8.5 pp while INS_beta passes) FAILS!
    _iec_nec_rows = [dict(r) for r in c1_norm_6["death_pathway_diversion_assay"]["lineage_block_diversion_records"]["PLVAP_iEC"]]
    _iec_nec_rows[2] = {**_iec_nec_rows[2], "necrostatin1s_rescue_delta_pp": 8.5}
    _div_iec_nec = {**c1_norm_6["death_pathway_diversion_assay"], "lineage_block_diversion_records": {**c1_norm_6["death_pathway_diversion_assay"]["lineage_block_diversion_records"], "PLVAP_iEC": _iec_nec_rows}}
    chk("FAIL_GATE_C1_NORMOXIA_UNDECLARED_NECROPTOSIS_DIVERSION" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "death_pathway_diversion_assay": _div_iec_nec}})})["failures"], "G42_c1_gy016_iec_single_block_nec1s_spike_fails")
    # 9. C-1 diversion paired_viability_timecourse_pct contradicting lineage_timecourse_counts FAILS!
    _beta_mm_rows = [dict(r) for r in c1_norm_6["death_pathway_diversion_assay"]["lineage_block_diversion_records"]["INS_beta"]]
    _beta_mm_rows[0] = {**_beta_mm_rows[0], "paired_viability_timecourse_pct": [{**_beta_mm_rows[0]["paired_viability_timecourse_pct"][0]}, {**_beta_mm_rows[0]["paired_viability_timecourse_pct"][1]}, {**_beta_mm_rows[0]["paired_viability_timecourse_pct"][2]}, {"hour_h": 48.0, "treated_viab_pct": 99.0, "ctrl_viab_pct": 54.0}]}
    _div_mm = {**c1_norm_6["death_pathway_diversion_assay"], "lineage_block_diversion_records": {**c1_norm_6["death_pathway_diversion_assay"]["lineage_block_diversion_records"], "INS_beta": _beta_mm_rows}}
    chk("FAIL_GATE_C1_NORMOXIA_INVALID_DIVERSION_ASSAY_VALUES" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "death_pathway_diversion_assay": _div_mm}})})["failures"], "G42_c1_gy016_viability_mismatch_vs_lineage_counts_fails")
    # 10. Exact even-count Hodges-Lehmann median boundary (n=8 -> 36 Walsh averages): upper central wa[18]=+1/2 > 0 while true exact_hodges_lehmann_median = 0 <= 0!
    _hl8_diffs = [Fraction(x, 1) for x in (-10, -8, -6, -4, -1, 5, 11, 20)]  # sum=+7 > 0; wa[17]=-1/2, wa[18]=+1/2 -> true HL=0 <= 0!
    _hl8_wa = sorted((_hl8_diffs[i] + _hl8_diffs[j]) / 2 for i in range(8) for j in range(i, 8))
    _hl8_prod = exact_hodges_lehmann_median(_hl8_diffs)
    _hl6_prod = exact_hodges_lehmann_median([Fraction(1, 1), Fraction(2, 1), Fraction(3, 1), Fraction(4, 1), Fraction(5, 1), Fraction(6, 1)])  # n=6 -> 21 odd Walsh avgs, med=3.5
    chk(len(_hl8_wa) == 36 and _hl8_wa[18] == Fraction(1, 2) and _hl8_prod == Fraction(0, 1) and _hl8_prod <= 0 and _hl6_prod == Fraction(7, 2), "G42_hl_even_walsh_boundary_true_median_neg_while_upper_pos")

    # --- GATE-40 (IIP-0062) A-0a 7d Vascular Components & A-0b/A-1 3-Lot Replication (4 tests) ---
    # 11. A-0a healthy sprout length (95%) with failing Day-0 branching (82% < 90%) FAILS!
    _a0a_br_bad = [dict(r) for r in a0a_reps_ok]
    _a0a_br_bad[5] = {**_a0a_br_bad[5], "day0_branching_7d_pct": [81.7, 81.85, 82.0, 82.15, 82.3], "sprouting_7d_pct": [81.7, 81.85, 82.0, 82.15, 82.3]}
    _a0a_fit_br = _sign_receipt({**a0a_fit_ok, "raw_replicates_sha256": sha256_bytes(canonical_json_bytes(_a0a_br_bad))})
    chk("FAIL_GATE_A0A_SPROUTING_CEILING_EXCEEDS_DAY0_OR_DELAYED_DONOR_L95" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "sprouting_7d_pct_grid": [100.0, 99.0, 97.0, 96.0, 94.0, 82.0, 76.0], "a0a_donor_replicates_by_conc": _a0a_br_bad, "a0a_fit_artifact_receipt": _a0a_fit_br})})["failures"], "G40_a0a_branching_below_90pct_fails")
    # 12. A-0a composite sprouting overstating failing branching component FAILS!
    _a0a_ov = [dict(r) for r in a0a_reps_ok]
    _a0a_ov[5] = {**_a0a_ov[5], "day0_branching_7d_pct": [82.0, 82.0, 82.0, 82.0, 82.0]}
    _a0a_fit_ov = _sign_receipt({**a0a_fit_ok, "raw_replicates_sha256": sha256_bytes(canonical_json_bytes(_a0a_ov))})
    chk("FAIL_GATE_A0A_VASCULAR_COMPOSITE_OVERSTATES_COMPONENT:5:DAY0" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "a0a_donor_replicates_by_conc": _a0a_ov, "a0a_fit_artifact_receipt": _a0a_fit_ov})})["failures"], "G40_a0a_composite_overstating_branching_fails")
    # 13. A-0b single manufacturing lot (3 specimens from 1 batch) FAILS 3-lot replication!
    _a0b_tp_1lot = _mk_pfd_tp_rows(a0b_tp_pts, coat_a["coating_lot_id"], "A0B1L", single_lot_only=True)
    chk("FAIL_GATE_A0B_LOCAL_EXPOSURE_SCHEDULE_GAP_OR_MALFORMED" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "a0b_local_exposure_timepoints": _a0b_tp_1lot})})["failures"], "G40_a0b_single_lot_specimens_fails_3lot_rule")
    # 14. A-1 release traces with only 1 manufacturing lot FAILS!
    chk("FAIL_GATE_A1_REQUIRES_AT_LEAST_3_DISTINCT_MANUFACTURING_LOTS" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "manufacturing_lot_release_records": a1_y["manufacturing_lot_release_records"][:1]})})["failures"], "G40_a1_single_lot_release_trace_fails")

    # --- GATE-43 (IIP-0065) D-2 Cross-Lot Trace Uniqueness & D-1 Strict-Int Wash Counts (2 tests) ---
    # 15. D-2 reusing a single trace_id across two otherwise distinct lots FAILS!
    _r2_dup_tr = _mk_r8_readout2(matched_comparator_id="CTRL-LOT-2", block_prefix="D2L2", meas_id="MEAS-D2-LOT-2", lot_id="D2-LOT-2", lot_jitter=1.08)
    _r2_dup_tr["o2_40_mmhg"]["blocks"][0]["trace_id"] = _mk_d2_lot(1)["readout2_receipt"]["readout2_evidence"]["o2_40_mmhg"]["blocks"][0]["trace_id"]
    chk("FAIL_CHECK_D2_REUSED_TRACE_ID_ACROSS_LOTS:D2-LOT-2" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1), _mk_d2_lot(2, readout2_evidence=_r2_dup_tr), _mk_d2_lot(3)]})["failures"], "G43_d2_reused_trace_id_across_lots_fails")
    # 16. D-1 float wash count (3.0 instead of strict int 3) inside unified receipt FAILS!
    _d1_fl_w = _mk_d1_unified(g43_base, arm_a_washes=3.0)
    chk("FAIL_CHECK_D1_UNIFIED_ASSAY_RECEIPT_FIELD_MISMATCH" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_paired_assay_receipt": _d1_fl_w})["failures"], "G43_d1_float_wash_count_in_unified_receipt_fails")


    # ========================================================================
    # ADVERSARIAL REGRESSION SUITE (12 NEW TESTS -> 716/716 TOTAL!)
    # ========================================================================
    # --- GATE-40 (IIP-0062) A-0a Lumen Formation Schema, Missing-Lumen HOLD, & Timing-Arm Failures (3 tests) ---
    # 1. Identical viability/length/branching with missing lumen_formation HOLDS!
    _a0a_no_lum = [{k: v for k, v in r.items() if k != "day0_lumen_formation_7d_pct"} for r in a0a_reps_ok]
    _a0a_fit_nl = _sign_receipt({**a0a_fit_ok, "raw_replicates_sha256": sha256_bytes(canonical_json_bytes(_a0a_no_lum))})
    chk("HOLD_GATE_A0A_MISSING_LUMEN_FORMATION_DATA" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "a0a_donor_replicates_by_conc": _a0a_no_lum, "a0a_fit_artifact_receipt": _a0a_fit_nl})})["holds"], "G40_a0a_missing_lumen_formation_holds")
    # 2. Identical healthy viability/length/branching with failing Day-0 lumen_formation (82% < 90%) FAILS!
    _a0a_lum0_bad = [dict(r) for r in a0a_reps_ok]
    _a0a_lum0_bad[5] = {**_a0a_lum0_bad[5], "day0_lumen_formation_7d_pct": [81.7, 81.85, 82.0, 82.15, 82.3], "sprouting_7d_pct": [81.7, 81.85, 82.0, 82.15, 82.3]}
    _a0a_fit_l0 = _sign_receipt({**a0a_fit_ok, "raw_replicates_sha256": sha256_bytes(canonical_json_bytes(_a0a_lum0_bad))})
    chk("FAIL_GATE_A0A_SPROUTING_CEILING_EXCEEDS_DAY0_OR_DELAYED_DONOR_L95" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "sprouting_7d_pct_grid": [100.0, 99.0, 97.0, 96.0, 94.0, 82.0, 76.0], "a0a_donor_replicates_by_conc": _a0a_lum0_bad, "a0a_fit_artifact_receipt": _a0a_fit_l0})})["failures"], "G40_a0a_day0_lumen_below_90pct_fails")
    # 3. Identical healthy viability/length/branching with failing delayed lumen_formation (82% < 90%) FAILS!
    _a0a_lumd_bad = [dict(r) for r in a0a_reps_ok]
    _a0a_lumd_bad[5] = {**_a0a_lumd_bad[5], "delayed_lumen_formation_7d_pct": [81.7, 81.85, 82.0, 82.15, 82.3], "sprouting_delayed_7d_pct": [81.7, 81.85, 82.0, 82.15, 82.3]}
    _a0a_fit_ld = _sign_receipt({**a0a_fit_ok, "raw_replicates_sha256": sha256_bytes(canonical_json_bytes(_a0a_lumd_bad))})
    chk("FAIL_GATE_A0A_SPROUTING_CEILING_EXCEEDS_DAY0_OR_DELAYED_DONOR_L95" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "sprouting_delayed_7d_pct_grid": [100.0, 99.0, 97.5, 96.5, 94.5, 82.0, 78.0], "a0a_donor_replicates_by_conc": _a0a_lumd_bad, "a0a_fit_artifact_receipt": _a0a_fit_ld})})["failures"], "G40_a0a_delayed_lumen_below_90pct_fails")

    # --- GATE-41 (IIP-0063) B-1/B-2 -> B-2b Sample-Ledger Completeness & Anti-Duplication (3 tests) ---
    # 4. Upstream B-1 ledger includes an extra high-peak sample omitted from B-2b-bench -> HOLDS!
    _b1_extra = _sign_receipt({**b1_y, "analytical_sample_ledger": b1_ledger_ok + [{"sample_id": "B1-ELU-H72-HIGHPEAK-OMITTED", "hour_h": 72.0, "source_stage": "B-1", "assay_matrix": "human_serum_100pct", "recirc_assay_matrix": "human_serum_100pct", "biological_unit_id": "B1-ELU-UNIT-99", "raw_analytical_row_sha256": sha256_bytes(b"HIGHPEAK")}]})
    _b2_re_ex = _sign_receipt({**b2_y, "parent_receipt_sha256": _b1_extra["receipt_sha256"]})
    _b2bb_om = _sign_receipt({**b2bb_y, "parent_receipt_sha256": _b2_re_ex["receipt_sha256"], "prerequisite_receipt_sha256s": {"B-1": _b1_extra["receipt_sha256"], "B-2": _b2_re_ex["receipt_sha256"]}})
    _r_om = evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b1_evidence": _b1_extra, "b2_evidence": _b2_re_ex, "b2b_bench_evidence": _b2bb_om})
    chk(_r_om["verdict"] == "HOLD" and "HOLD_GATE_B2B_BENCH_UPSTREAM_SAMPLE_LEDGER_INCOMPLETE_OR_DUPLICATE" in _r_om["holds"], "G41_b2b_omitted_b1_high_sample_holds")
    # 5. B-2b-bench duplicating a source_sample_id across replicates -> HOLDS!
    _b2b_dup = _mk_r8_b2b_replicates()
    _b2b_dup["timepoint_replicate_records"][0]["source_sample_ids"][5] = _b2b_dup["timepoint_replicate_records"][0]["source_sample_ids"][0]
    _r_dup = evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, **_b2b_dup})})
    chk(_r_dup["verdict"] == "HOLD" and "HOLD_GATE_B2B_BENCH_UPSTREAM_SAMPLE_LEDGER_INCOMPLETE_OR_DUPLICATE" in _r_dup["holds"], "G41_b2b_duplicate_source_sample_id_holds")
    # 6. B-2b-exact omitting an upstream B-2 blood-loop sample -> HOLDS!
    _b2be_dup = _mk_r8_b2b_replicates(evidence_scope="exact_product")
    _b2be_dup["timepoint_replicate_records"][0]["source_sample_ids"][5] = "UNREGISTERED-SUBSTITUTE-S6"
    _r_ex_om = evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b2b_exact_evidence": _sign_receipt({**b2be_y, **_b2be_dup})})
    chk("HOLD_GATE_B2B_EXACT_UPSTREAM_SAMPLE_LEDGER_INCOMPLETE_OR_DUPLICATE" in _r_ex_om["holds"], "G41_b2b_exact_omitted_upstream_sample_holds")

    # --- GATE-42 (IIP-0064) C-2 CHGB/SCG2 Granule Screen, Clean n=3..5 Pilot Verdict, & Exact Fraction Casp9 Dir (3 tests) ---
    # 7. C-2 CHGB or SCG2 below 85% FAILS granule processing!
    chk("FAIL_GATE_C2_GRANULE_PROCESSING_DEGRADED" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "chgb_pct_ctrl": 78.0})})["failures"], "G42_c2_chgb_below_85pct_fails")
    # 8. Clean n=3 C-1 pilot submitted WITHOUT downstream C-2/C-3/switch receipts cleanly returns DESCRIPTIVE_PILOT_ONLY_NON_ADVANCING!
    _g42_p3_only = {
        k: v for k, v in g42_ok.items()
        if k not in ("native_switch_evidence", "gate0v_evidence", "c2_evidence", "c3_nk_evidence", "c3_gsis_evidence")
    }
    _g42_p3_only["c1_preregistered_plan_receipt"] = c1_prereg_p3
    _g42_p3_only["c1_evidence"] = c1_p3
    _r_p3 = evaluate_gate42_gy032_channel_c_screen(_g42_p3_only)
    chk(_r_p3["verdict"] == "DESCRIPTIVE_PILOT_ONLY_NON_ADVANCING" and _r_p3["release_authorizing"] is False, "G42_c1_clean_n3_pilot_without_downstream_returns_descriptive_pilot")
    # 9. C-2 SCG2 below 85% FAILS granule processing!
    chk("FAIL_GATE_C2_GRANULE_PROCESSING_DEGRADED" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "scg2_pct_ctrl": 79.0})})["failures"], "G42_c2_scg2_below_85pct_fails")

    # --- GATE-43 (IIP-0065) Check D-1 Vascular Reconciliation & Per-Arm Chemistry Row Locator (3 tests) ---
    # 10. Adverse 5x neutrophil adhesion + 10% sprouting CANNOT return PASS when pre_coassembly flag is True (FAILS)!
    _d1_adv_v = (lambda _b: {**_b, "record_sha256": sha256_bytes(canonical_json_bytes(_b))})({
        "lot_id": "D1-LOT-001", "plate_id": "D1-PLATE-01", "sibling_aliquot_pair_id": "D1-SIBPAIR-01",
        "arm_a_acquired_at_utc": "2026-10-03T13:15:00Z", "arm_b_acquired_at_utc": "2026-10-03T13:20:00Z",
        "neutrophil_adhesion_ratio_b_over_a": 5.0, "iec_sprouting_pct_ctrl": 10.0,
    })
    _g43_adv = {**g43_base, "check_d1_vascular_adhesion_sprouting_record": _d1_adv_v}
    _g43_adv["check_d1_paired_assay_receipt"] = _mk_d1_unified(_g43_adv)
    chk("FAIL_CHECK_D1_VASCULAR_FLAG_CONTRADICTS_ADVERSE_MEASUREMENTS" in evaluate_gate43_cellgemma_guardrails_and_pilots(_g43_adv)["failures"], "G43_d1_adverse_5x_adhesion_or_10pct_sprouting_cannot_pass_fails")
    # 11. Two arms sharing the same chemistry file digest with IDENTICAL injection/row locator FAILS!
    _shared_chem_sha = "7" * 64
    _d1_same_inj = _mk_d1_unified(
        g43_base,
        arm_a_chemistry_sample={"sample_id": "D1-CHEM-A-001", "sibling_aliquot_pair_id": "D1-SIBPAIR-01", "collected_at_utc": "2026-10-03T12:00:00Z", "instrument_record_sha256": _shared_chem_sha, "instrument_row_or_injection_id": "INJ-ROW-1"},
        arm_b_chemistry_sample={"sample_id": "D1-CHEM-B-001", "sibling_aliquot_pair_id": "D1-SIBPAIR-01", "collected_at_utc": "2026-10-03T12:05:00Z", "instrument_record_sha256": _shared_chem_sha, "instrument_row_or_injection_id": "INJ-ROW-1"},
    )
    chk("FAIL_CHECK_D1_CHEMISTRY_SAMPLE_PROVENANCE_OR_TIMING_INVALID" in evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_paired_assay_receipt": _d1_same_inj})["failures"], "G43_d1_shared_chem_file_identical_injection_row_fails")
    # 12. Two arms sharing the same chemistry file digest with DISTINCT injection/row locators PASSES!
    _d1_diff_inj = _mk_d1_unified(
        g43_base,
        arm_a_chemistry_sample={"sample_id": "D1-CHEM-A-001", "sibling_aliquot_pair_id": "D1-SIBPAIR-01", "collected_at_utc": "2026-10-03T12:00:00Z", "instrument_record_sha256": _shared_chem_sha, "instrument_row_or_injection_id": "INJ-ROW-1"},
        arm_b_chemistry_sample={"sample_id": "D1-CHEM-B-001", "sibling_aliquot_pair_id": "D1-SIBPAIR-01", "collected_at_utc": "2026-10-03T12:05:00Z", "instrument_record_sha256": _shared_chem_sha, "instrument_row_or_injection_id": "INJ-ROW-2"},
    )
    chk(evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_base, "check_d1_paired_assay_receipt": _d1_diff_inj})["verdict"] == "PASS_DESCRIPTIVE_PILOT_ZERO_ODDS_GY037_WARN_RETAINED", "G43_d1_shared_chem_file_distinct_injection_rows_passes")


    # ========================================================================
    # ADVERSARIAL REGRESSION SUITE (12 NEW TESTS -> 728/728 TOTAL!)
    # ========================================================================
    # --- GATE-40 (IIP-0062) Active-Lot Isolation, A-0a IC50 Curve Bracket, & Dialysis fu (4 tests) ---
    # 1. A-0b active lot below IC50 floor (55 uM < 75 uM) while other 2 lots are high (pooled mean > 75 uM) FAILS active-lot check!
    _a0b_tp_low_act = _mk_pfd_tp_rows(a0b_tp_pts, coat_a["coating_lot_id"], "A0BLOW", active_lot_offset=-58.0)
    chk("FAIL_GATE_A0B_ACTIVE_LOT_EXPOSURE_OUT_OF_WINDOW" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "a0b_local_exposure_timepoints": _a0b_tp_low_act})})["failures"], "G40_a0b_active_lot_below_floor_fails_even_if_other_lots_high")
    # 2. A-1 active lot breaching ceiling (+60 uM) while other 2 lots stay safe FAILS active-lot check!
    _a1_tp_hi_act = _mk_pfd_tp_rows(a1_tp_pts, coat_a["coating_lot_id"], "A1HI", active_lot_offset=60.0)
    chk("FAIL_GATE_A1_ACTIVE_LOT_EXPOSURE_OUT_OF_WINDOW" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "a1_local_free_parent_timepoints": _a1_tp_hi_act})})["failures"], "G40_a1_active_lot_above_ceiling_fails_even_if_other_lots_safe")
    # 3. A-0a claimed IC50 outside its own curve's 50% crossing bracket [40, 75] (e.g. claiming 30 uM) FAILS!
    _a0a_fit_out = _sign_receipt({**a0a_fit_ok, "ic50_free_alpha_sma_uM": 30.0})
    chk("FAIL_GATE_A0A_ENDPOINT_IC50_OUTSIDE_CURVE_CROSSING_BRACKET" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "ic50_free_alpha_sma_uM": 30.0, "a0a_fit_artifact_receipt": _a0a_fit_out})})["failures"], "G40_a0a_claimed_ic50_outside_crossing_bracket_fails")
    # 4. A-0a missing dialysis fu replicates HOLDS!
    chk("HOLD_GATE_A0A_MISSING_DIALYSIS_FU_MATRIX_REPLICATES" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "a0a_dialysis_fu_replicates": None})})["holds"], "G40_a0a_missing_dialysis_fu_replicates_holds")

    # --- GATE-41 (IIP-0063) B-0a Safety Unit Provenance, n>=6, Skewed/Outlier HOLD & Single-Unit Floor (3 tests) ---
    # 5. B-0a skewed/bimodal safety distribution with 1 catastrophic outlier (e.g. [100, 99.9, 99.8, 99.7, 99.6, 70.0], mean=94.8% > 90%) triggers non-normal HOLD & fails single-unit floor!
    _b0a_s_bimod = [dict(r) for r in b0a_s_reps_ok]
    _bm_vals = [99.9, 99.8, 99.7, 99.6, 99.5, 59.5]
    _b0a_s_bimod[5] = {**_b0a_s_bimod[5], "sprouting_pct": _bm_vals, "raw_unit_measurements": {**_b0a_s_bimod[5]["raw_unit_measurements"], "sprouting_pct": _mk_b0a_raw_ratio(_bm_vals, _b0a_s_bimod[5]["matched_vehicle_record_id"], 400.0)}}
    _b0a_an_bm = _sign_receipt({**b0a_an_ok, "raw_safety_replicates_sha256": sha256_bytes(canonical_json_bytes(_b0a_s_bimod))})
    _r_bm = evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": _sign_receipt({**b0a_ok, "safety_replicates_by_conc": _b0a_s_bimod, "b0a_analysis_receipt": _b0a_an_bm})})
    chk("HOLD_GATE_B0A_NONNORMAL_OR_SKEWED_SAFETY_REPLICATES:5:sprouting_pct" in _r_bm["holds"] and "FAIL_GATE_B0A_CSAFE_EXCEEDS_QUALIFIED_TESTED_SAFE_CONC" in _r_bm["failures"], "G41_b0a_skewed_bimodal_safety_holds_and_fails_single_unit_floor")
    # 6. B-0a safety replicates with duplicate unit_ids FAILS!
    _b0a_s_dup = [dict(r) for r in b0a_s_reps_ok]
    _b0a_s_dup[0] = {**_b0a_s_dup[0], "unit_ids": ["SAFE-U1", "SAFE-U1", "SAFE-U3", "SAFE-U4", "SAFE-U5", "SAFE-U6"]}
    _b0a_an_du = _sign_receipt({**b0a_an_ok, "raw_safety_replicates_sha256": sha256_bytes(canonical_json_bytes(_b0a_s_dup))})
    chk("FAIL_GATE_B0A_DUPLICATE_SAFETY_UNIT_IDS:0" in evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": _sign_receipt({**b0a_ok, "safety_replicates_by_conc": _b0a_s_dup, "b0a_analysis_receipt": _b0a_an_du})})["failures"], "G41_b0a_duplicate_safety_unit_ids_fails")
    # 7. B-0a underpowered n=3 safety units FAILS!
    _b0a_s_n3 = [{**r, "unit_ids": b0a_s_units[:3], "sprouting_pct": r["sprouting_pct"][:3], "nkg2a_pct": r["nkg2a_pct"][:3], "cd94_pct": r["cd94_pct"][:3], "il10_retention_pct": r["il10_retention_pct"][:3]} for r in b0a_s_reps_ok]
    chk("FAIL_GATE_B0A_UNDERPOWERED_OR_INVALID_SAFETY_UNITS:0" in evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": _sign_receipt({**b0a_ok, "safety_replicates_by_conc": _b0a_s_n3})})["failures"], "G41_b0a_underpowered_n3_safety_units_fails")

    # --- GATE-42 (IIP-0064) Parental IL-1 Block Reconciliation, Matched-Control SERPINB9/PD-L1/CXCL10, & C-2 Uncapped Retention (3 tests) ---
    # 8. Parental matrix block-level IL-1 drop disagrees with mechanism panel vector (or single parental block < 15 pp while mean >= 15 pp) FAILS!
    _att_par_mm = _sign_receipt({**att_y, "stage2_normoxia_mechanism_panel": {**att_panel_norm, "il1_positive_control_parental_drop_pp_by_block": [26.0, 29.0, 28.0]}})
    chk("FAIL_IIP0049_PARENTAL_IL1_CONTROL_BLOCK_MISMATCH:NORMOXIA" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _att_par_mm})["failures"], "G42_stage2_parental_il1_block_mismatch_fails")
    # 9. Stage-2 flat weak CXCL10 below 3x LOD OR SERPINB9 < 85% of matched control FAILS!
    _att_weak_cx = _sign_receipt({**att_y, "stage2_normoxia_mechanism_panel": {**att_panel_norm, "cxcl10_0h_mfi_by_block": [100.0, 100.0, 100.0], "cxcl10_24h_mfi_by_block": [92.0, 91.0, 94.0]}})
    _att_low_sb9 = _sign_receipt({**att_y, "stage2_normoxia_mechanism_panel": {**att_panel_norm, "serpinb9_pct_matched_ctrl_by_block": [78.0, 93.0, 95.0]}})
    chk(
        "FAIL_IIP0049_SHIELD_KINETICS_COMPROMISED_ON_BACKGROUND:NORMOXIA" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _att_weak_cx})["failures"]
        and "FAIL_IIP0049_SERPINB9_OR_PDL1_SHIELD_BELOW_85PCT:NORMOXIA" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _att_low_sb9})["failures"],
        "G42_stage2_weak_cxcl10_or_low_serpinb9_fails",
    )
    # 10. C-2 uncapped basal shield retention > 100% (e.g. 112% expression vs control) PASSES cleanly!
    _c2_112 = _sign_receipt({**c2_y, "basal_shield_retention_pct": 112.0, "basal_shield_retention_by_component": _mk_r8_shields(py, 112.0)})
    _sw_112 = _sign_receipt({**sw_y_c, "prerequisite_receipt_sha256s": {**sw_y_c["prerequisite_receipt_sha256s"], "C-2": _c2_112["receipt_sha256"]}})
    _g0v_112 = _sign_receipt({**g0v_y_c, "prerequisite_receipt_sha256s": {**g0v_y_c["prerequisite_receipt_sha256s"], "C-2": _c2_112["receipt_sha256"]}})
    _pr_c3_112 = {**pr_c3_yc, "NATIVE_SAFETY_SWITCH": _sw_112["receipt_sha256"], "GATE-0V-KILL": _g0v_112["receipt_sha256"]}
    _c3nk_112 = _sign_receipt({**c3_nk_y, "parent_receipt_sha256": _c2_112["receipt_sha256"], "prerequisite_receipt_sha256s": _pr_c3_112})
    _c3g_112 = _sign_receipt({**c3_gsis_y, "parent_receipt_sha256": _c3nk_112["receipt_sha256"], "prerequisite_receipt_sha256s": _pr_c3_112})
    chk(evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _c2_112, "native_switch_evidence": _sw_112, "gate0v_evidence": _g0v_112, "c3_nk_evidence": _c3nk_112, "c3_gsis_evidence": _c3g_112})["verdict"] == OFFLINE_VERDICT_PRIMARY, "G42_c2_uncapped_basal_shield_112pct_passes")

    # --- GATE-43 (IIP-0065) Check D-1 Unresponsive Retained-T3 Control HOLD & Check D-2 Valid Measured Zero Proliferation (2 tests) ---
    # 11. Check D-1 unresponsive retained-T3 control (SI=1.0 in both arms, both equally poor) HOLDS cleanly with zero authority!
    _d1_dead_gsis = (lambda _b: {**_b, "record_sha256": sha256_bytes(canonical_json_bytes(_b))})({
        "lot_id": "D1-LOT-001", "plate_id": "D1-PLATE-01", "sibling_aliquot_pair_id": "D1-SIBPAIR-01",
        "arm_a_acquired_at_utc": "2026-10-03T12:30:00Z", "arm_b_acquired_at_utc": "2026-10-03T12:35:00Z",
        "insulin_normalization_basis": "PER_IEQ_PER_HOUR", "raw_trace_sha256": "6" * 64,
        "arm_a_basal_40": 0.40, "arm_a_stim_40": 0.40, "arm_b_basal_40": 0.40, "arm_b_stim_40": 0.40,
        "arm_a_basal_100": 0.45, "arm_a_stim_100": 0.45, "arm_b_basal_100": 0.45, "arm_b_stim_100": 0.45,
        "arm_a_si_40": 1.0, "arm_b_si_40": 1.0, "arm_a_si_100": 1.0, "arm_b_si_100": 1.0,
    })
    _g43_dead = {**g43_base, "check_d1_paired_gsis_record": _d1_dead_gsis}
    _g43_dead["check_d1_paired_assay_receipt"] = _mk_d1_unified(_g43_dead)
    _r_d1_dead = evaluate_gate43_cellgemma_guardrails_and_pilots(_g43_dead)
    chk(_r_d1_dead["verdict"] == "HOLD" and "HOLD_CHECK_D1_UNRESPONSIVE_RETAINED_T3_CONTROL" in _r_d1_dead["holds"] and _r_d1_dead["adoption_authority"] is False, "G43_d1_unresponsive_retained_t3_control_holds")
    # 12. Check D-2 valid measured 0.0x Ki-67/EdU proliferation PASSES cleanly (not rejected as missing)!
    chk(evaluate_gate43_cellgemma_guardrails_and_pilots({**g43_full_a, "check_d2_per_lot_records": [_mk_d2_lot(1, ki67=0.0, edu=0.0), _mk_d2_lot(2), _mk_d2_lot(3)]})["verdict"] == "PASS_DESCRIPTIVE_PILOT_ZERO_ODDS_GY037_WARN_RETAINED", "G43_d2_measured_zero_prolif_passes")


    # ========================================================================
    # ADVERSARIAL REGRESSION SUITE (8 NEW TESTS -> 736/736 TOTAL!)
    # ========================================================================
    # --- GATE-40 (IIP-0062) A-0a Free-Axis Nominal x fu Reconciliation, fu-Propagated Margin, & Self-Normalized 0 uM Control (4 tests) ---
    # 1. A-0a vascular nominal grid x fu contradicting shared tested_free_conc_uM_grid FAILS!
    _a0a_bad_mfu = {**a0a_ok["a0a_matrix_fu_by_assay"], "vascular_viability_assay": {**a0a_ok["a0a_matrix_fu_by_assay"]["vascular_viability_assay"], "nominal_conc_uM_grid": [0.0, 20.0, 40.0, 75.0, 150.0, 260.0, 500.0]}}
    chk("FAIL_GATE_A0A_FREE_GRID_MISMATCH_VS_NOMINAL_AND_FU:vascular_viability_assay" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "a0a_matrix_fu_by_assay": _a0a_bad_mfu})})["failures"], "G40_a0a_nominal_x_fu_mismatch_vs_free_grid_fails")
    # 2. A-0a missing a0a_matrix_fu_by_assay HOLDS!
    chk("HOLD_GATE_A0A_MISSING_DIALYSIS_FU_MATRIX_REPLICATES" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "a0a_matrix_fu_by_assay": None})})["holds"], "G40_a0a_missing_matrix_fu_by_assay_holds")
    # 3. A-0a exact self-normalized 0 uM vehicle control (identical [0.0]*5 inhibition and [100.0]*5 viability/sprouting/sub-endpoints) PASSES cleanly without spurious zero-variance HOLD!
    _a0a_reps_selfnorm = [dict(r) for r in a0a_reps_ok]
    _a0a_reps_selfnorm[0] = {
        **_a0a_reps_selfnorm[0],
        "alpha_sma_inhibition_pct": [0.0] * 5, "col1a1_inhibition_pct": [0.0] * 5,
        "viability_7d_pct": [100.0] * 5, "sprouting_7d_pct": [100.0] * 5, "sprouting_delayed_7d_pct": [100.0] * 5,
        "day0_sprout_length_7d_pct": [100.0] * 5, "day0_branching_7d_pct": [100.0] * 5, "day0_lumen_formation_7d_pct": [100.0] * 5,
        "delayed_sprout_length_7d_pct": [100.0] * 5, "delayed_branching_7d_pct": [100.0] * 5, "delayed_lumen_formation_7d_pct": [100.0] * 5,
    }
    _a0a_fit_sn = _sign_receipt({**a0a_fit_ok, "raw_replicates_sha256": sha256_bytes(canonical_json_bytes(_a0a_reps_selfnorm))})
    chk(evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "a0a_donor_replicates_by_conc": _a0a_reps_selfnorm, "a0a_fit_artifact_receipt": _a0a_fit_sn})})["verdict"] == "PASS_ROUTE_FREE_A0A_ONLY", "G40_a0a_exact_self_normalized_0uM_vehicle_passes")
    # 4. A-0a nominal margin 1.60x (>= 1.5x) eroded below 1.5x once dialysis fu uncertainty is propagated FAILS!
    _a0a_wide_fu = {
        "fibrosis_efficacy_assay": {**a0a_ok["a0a_matrix_fu_by_assay"]["fibrosis_efficacy_assay"], "dialysis_fu_replicates": [0.32, 0.37, 0.42, 0.47, 0.52]},
        "vascular_viability_assay": {**a0a_ok["a0a_matrix_fu_by_assay"]["vascular_viability_assay"], "dialysis_fu_replicates": [0.38, 0.44, 0.50, 0.56, 0.62]},
    }
    _a0a_fit_m16 = _sign_receipt({**a0a_fit_ok, "cc10_free_7d_l95_uM": 120.0, "c_sprout_max_free_7d_l95_uM": 120.0})
    chk("FAIL_GATE_A0A_FU_PROPAGATED_MARGIN_BELOW_1P5X" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "cc10_free_7d_l95_uM": 120.0, "c_sprout_max_free_7d_l95_uM": 120.0, "c_upper_provisional_7d_l95_uM": 120.0, "a0a_matrix_fu_by_assay": _a0a_wide_fu, "a0a_fit_artifact_receipt": _a0a_fit_m16})})["failures"], "G40_a0a_fu_propagated_margin_below_1p5x_fails")

    # --- GATE-41 (IIP-0063) B-0a Skewed Efficacy HOLD & B-2b Quantitative Upstream Analytical Row Digest Binding (2 tests) ---
    # 5. B-0a skewed efficacy replicates (high mean=68%, high Student-t LCB > 50%, yet severely skewed failing Shapiro-Wilk/Q-Q) -> HOLDS!
    _b0a_e_skew = [dict(r) for r in b0a_e_reps_ok]
    _sk_vals = [67.0, 67.1, 67.15, 67.2, 67.25, 72.3]
    _b0a_e_skew[3] = {**_b0a_e_skew[3], "iec_ibmir_marker_suppression_pct": _sk_vals, "raw_unit_measurements": {**_b0a_e_skew[3]["raw_unit_measurements"], "iec_ibmir_marker_suppression_pct": _mk_b0a_raw_ratio(_sk_vals, _b0a_e_skew[3]["matched_vehicle_record_id"], 250.0, is_inhib=True)}}
    _b0a_an_sk = _sign_receipt({**b0a_an_ok, "raw_efficacy_replicates_sha256": sha256_bytes(canonical_json_bytes(_b0a_e_skew))})
    _r_esk = evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": _sign_receipt({**b0a_ok, "efficacy_replicates_by_conc": _b0a_e_skew, "b0a_analysis_receipt": _b0a_an_sk})})
    chk(_r_esk["verdict"] == "HOLD" and "HOLD_GATE_B0A_NONNORMAL_OR_SKEWED_EFFICACY_REPLICATES:3:iec_ibmir_marker_suppression_pct" in _r_esk["holds"], "G41_b0a_skewed_otherwise_passing_efficacy_holds")
    # 6. B-2b-bench keeping identical sample_ids and hours while altering one concentration value (contradicting B-1/B-2 raw_analytical_row_sha256!) -> HOLDS!
    _b2b_tamp = _mk_r8_b2b_replicates()
    _b2b_tamp["timepoint_replicate_records"][0]["local_parent_total_replicates_nM"][0] = 109.5
    _r_btamp = evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, **_b2b_tamp})})
    chk(_r_btamp["verdict"] == "HOLD" and "HOLD_GATE_B2B_BENCH_UPSTREAM_ANALYTICAL_ROW_DIGEST_MISMATCH" in _r_btamp["holds"], "G41_b2b_tampered_value_vs_upstream_analytical_digest_holds")

    # --- GATE-42 (IIP-0064) Clean n=3 EXACT_TWO_SIDED_SIGN_FLIP Descriptive Pilot (1 test) ---
    # 7. Clean n=3 C-1 pilot labeled EXACT_TWO_SIDED_SIGN_FLIP cleanly returns DESCRIPTIVE_PILOT_ONLY_NON_ADVANCING!
    _c1_prereg_p3_sf = _sign_receipt({**c1_prereg_p3, "statistical_test_method": "EXACT_TWO_SIDED_SIGN_FLIP"})
    _c1_p3_sf = _sign_receipt({**c1_p3, "statistical_test_method": "EXACT_TWO_SIDED_SIGN_FLIP", "prerequisite_receipt_sha256s": {**c1_p3["prerequisite_receipt_sha256s"], "C-1-PREREGISTRATION": _c1_prereg_p3_sf["receipt_sha256"]}})
    _r_p3_sf = evaluate_gate42_gy032_channel_c_screen({**_g42_p3_only, "c1_preregistered_plan_receipt": _c1_prereg_p3_sf, "c1_evidence": _c1_p3_sf})
    chk(_r_p3_sf["verdict"] == "DESCRIPTIVE_PILOT_ONLY_NON_ADVANCING" and not _r_p3_sf["failures"], "G42_c1_clean_n3_exact_sign_flip_pilot_returns_descriptive")

    # --- GATE-43 (IIP-0065) Check D-1 Arm-B Withdrawal Elevated Basal / Lost Glucose Responsiveness (1 test) ---
    # 8. Check D-1 healthy retained-T3 control (SI=4.2/4.8) + Arm-B preserved stimulated output yet elevated basal collapsing SI_b to 1.4 -> HOLDS!
    _d1_armb_lost = (lambda _b: {**_b, "record_sha256": sha256_bytes(canonical_json_bytes(_b))})({
        "lot_id": "D1-LOT-001", "plate_id": "D1-PLATE-01", "sibling_aliquot_pair_id": "D1-SIBPAIR-01",
        "arm_a_acquired_at_utc": "2026-10-03T12:30:00Z", "arm_b_acquired_at_utc": "2026-10-03T12:35:00Z",
        "insulin_normalization_basis": "PER_IEQ_PER_HOUR", "raw_trace_sha256": "6" * 64,
        "arm_a_basal_40": 0.40, "arm_a_stim_40": 1.68, "arm_b_basal_40": 1.17, "arm_b_stim_40": 1.64,
        "arm_a_basal_100": 0.45, "arm_a_stim_100": 2.16, "arm_b_basal_100": 1.51, "arm_b_stim_100": 2.115,
        "arm_a_si_40": 4.2, "arm_b_si_40": 1.4, "arm_a_si_100": 4.8, "arm_b_si_100": 1.4,
    })
    _g43_blost = {**g43_base, "check_d1_paired_gsis_record": _d1_armb_lost}
    _g43_blost["check_d1_paired_assay_receipt"] = _mk_d1_unified(_g43_blost)
    _r_blost = evaluate_gate43_cellgemma_guardrails_and_pilots(_g43_blost)
    chk(_r_blost["verdict"] == "HOLD" and "HOLD_CHECK_D1_WITHDRAWAL_ARM_LOSS_OF_GLUCOSE_RESPONSIVENESS" in _r_blost["holds"], "G43_d1_arm_b_elevated_basal_lost_responsiveness_holds")


    # --- GATE-40 (IIP-0062) f_u-Uncertainty-Adjusted Operative Limits Carry-Forward into A-0b & A-1 (2 tests) ---
    # 1. Wide dialysis f_u uncertainty shifts operative window from [75, 260] -> ~[86.1, 222.8] (with 14d ceiling 220*0.857=188.5):
    #    A-0a passes (>= 1.5x margin), while A-0b exposure [80, 195] (inside unadjusted [75, 220], outside adjusted [86.1, 188.5]) FAILS both trough & peak!
    _a0a_wide_carry_mfu = {
        "fibrosis_efficacy_assay": {
            **a0a_ok["a0a_matrix_fu_by_assay"]["fibrosis_efficacy_assay"],
            "dialysis_fu_replicates": [0.36, 0.39, 0.42, 0.45, 0.48],  # mean=0.42, u95~0.482 -> factor ~1.148 -> ic50_op ~86.1 uM
        },
        "vascular_viability_assay": {
            **a0a_ok["a0a_matrix_fu_by_assay"]["vascular_viability_assay"],
            "dialysis_fu_replicates": [0.43, 0.465, 0.50, 0.535, 0.57],  # mean=0.50, l95~0.428 -> factor ~0.857 -> c7d_op ~222.8, c14d_op ~188.5 uM
        },
    }
    _a0a_wc = _sign_receipt({**a0a_ok, "a0a_matrix_fu_by_assay": _a0a_wide_carry_mfu})
    _r_a0a_wc = evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _a0a_wc})
    _a0b_wc_bad = _sign_receipt({
        **a0b_y, "parent_receipt_sha256": _a0a_wc["receipt_sha256"],
        "sustained_free_parent_lower_uM": 80.0, "peak_free_parent_u95_uM": 195.0,
        "a0b_local_exposure_timepoints": _mk_pfd_tp_rows(
            ((6.0, 192.0), (24.0, 180.0), (72.0, 150.0), (144.0, 130.0), (216.0, 110.0), (288.0, 95.0), (336.0, 82.0)),
            coat_a["coating_lot_id"], "A0BWC",
        ),
    })
    _r_a0b_wc = evaluate_gate40_pirfenidone_h4({**g40_ok, "a0a_evidence": _a0a_wc, "a0b_evidence": _a0b_wc_bad})
    chk(
        _r_a0a_wc["verdict"] == "PASS_ROUTE_FREE_A0A_ONLY"
        and _r_a0a_wc["a0a_operative_limits_uM"]["ic50_u95_fu_adjusted_uM"] > 85.0
        and "FAIL_GATE_A0B_SUSTAINED_FREE_BELOW_IC50_U95" in _r_a0b_wc["failures"]
        and "FAIL_GATE_A0B_PEAK_FREE_NOT_BELOW_ALL4_CEILINGS" in _r_a0b_wc["failures"],
        "G40_a0b_rejects_unadjusted_window_outside_fu_adjusted_bounds",
    )
    # 2. Same f_u-adjusted operative bounds enforced in A-1 (d14=80 < 86.1, d1=192 >= 188.5) AND understated already-adjusted flag FAILS!
    _a1b_wc_bad = _sign_receipt({
        **a1b_y, "parent_receipt_sha256": _a0b_wc_bad["receipt_sha256"],
        "day1_intact_parent_free_uM": 192.0, "day14_intact_parent_free_uM": 80.0,
        "a1_local_free_parent_timepoints": _mk_pfd_tp_rows(
            ((6.0, 190.0), (24.0, 180.0), (72.0, 150.0), (144.0, 130.0), (216.0, 110.0), (288.0, 95.0), (336.0, 81.0), (600.0, 20.0), (840.0, 3.0)),
            coat_a["coating_lot_id"], "A1WC",
        ),
    })
    _r_a1_wc = evaluate_gate40_pirfenidone_h4({**g40_ok, "a0a_evidence": _a0a_wc, "a0b_evidence": _a0b_wc_bad, "a1_bench_evidence": _a1b_wc_bad})
    _r_a0a_spoof_adj = evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**_a0a_wc, "a0a_limits_already_fu_adjusted": True})})
    chk(
        "FAIL_GATE_A1_BENCH_DAY14_INTACT_PARENT_BELOW_IC50_U95" in _r_a1_wc["failures"]
        and "FAIL_GATE_A1_BENCH_DAY1_INTACT_PARENT_EXCEEDS_CEILING" in _r_a1_wc["failures"]
        and "FAIL_GATE_A0A_CLAIMED_FU_ADJUSTED_LIMITS_UNDERSTATED" in _r_a0a_spoof_adj["failures"],
        "G40_a1_rejects_unadjusted_window_and_spoofed_fu_adjusted_flag",
    )

    # --- GATE-41 (IIP-0063) B-0a-exact Biological Unit Denominator & Block-Level Aggregation (1 test) ---
    # 3. Anonymous raw list in B-0a-exact HOLDS for missing biological unit denominator; unaggregated block mismatch FAILS!
    _b0a_ex_anon = _sign_receipt({**b0a_ex_y, "cassette_retention_replicates_by_conc": [[99.6, 99.8, 100.0, 100.2, 100.4] for _ in range(6)]})
    _ex0_ba = b0a_ex_y["cassette_retention_replicates_by_conc"][0]
    _ex0_ba_tech = [[80.0, 80.0, 80.0]] + _ex0_ba["technical_replicates_per_unit_pct"][1:]
    _b0a_ex_bad_agg = _sign_receipt({
        **b0a_ex_y,
        "cassette_retention_replicates_by_conc": [
            {
                **_ex0_ba,
                "technical_replicates_per_unit_pct": _ex0_ba_tech,
                "raw_unit_measurements": {
                    **_ex0_ba["raw_unit_measurements"],
                    "treated_by_unit_tech": [[800.0, 804.0, 796.0]] + _ex0_ba["raw_unit_measurements"]["treated_by_unit_tech"][1:],
                },
            },
            *b0a_ex_y["cassette_retention_replicates_by_conc"][1:],
        ],
    })
    chk(
        "HOLD_GATE_B0A_EXACT_MISSING_BIOLOGICAL_UNIT_DENOMINATOR" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b0a_exact_evidence": _b0a_ex_anon})["holds"]
        and "FAIL_GATE_B0A_EXACT_BLOCK_AGGREGATION_MISMATCH:0:B0AEX-BLK-1" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b0a_exact_evidence": _b0a_ex_bad_agg})["failures"],
        "G41_b0a_exact_biological_unit_denominator_and_block_aggregation",
    )

    # --- GATE-42 (IIP-0064) C-3-NK Specimen Binding, Exact Fraction Casp9, & Common Family Acquisition (3 tests) ---
    # 4. C-3-NK Readout-3B kinetic trace carrying an unrelated specimen_id FAILS; missing provenance HOLDS!
    _r3b_unlinked = _mk_r8_readout3b(include_sirpa_low=True, specimen_id="SPEC-UNRELATED-MATERIAL", specimen_lot_id=ly, intervention_cohort_id=c1_cohort_y)
    _r3b_no_prov = _mk_r8_readout3b(include_sirpa_low=True)
    chk(
        "FAIL_GATE_C3_NK_READOUT3B_SPECIMEN_LOT_OR_COHORT_MISMATCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c3_nk_evidence": _sign_receipt({**c3_nk_y, "readout3b_evidence": _r3b_unlinked})})["failures"]
        and "HOLD_GATE_C3_NK_READOUT3B_MISSING_SPECIMEN_PROVENANCE" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c3_nk_evidence": _sign_receipt({**c3_nk_y, "readout3b_evidence": _r3b_no_prov})})["holds"],
        "G42_c3_nk_specimen_provenance_and_kinetic_trace_binding",
    )
    # 5. Exact Fraction sibling caspase-9 catches float64-colliding decimal string mismatch ("49.0000000000000001" vs 49.0)!
    _c1_n_f64_mm = {
        **c1_norm_6,
        "all_five_arms_paired_data": {
            **c1_norm_6["all_five_arms_paired_data"],
            tg_dual: {
                **c1_norm_6["all_five_arms_paired_data"][tg_dual],
                "casp9_treated_raw_by_block": [f"{c1_norm_6['casp9_treated_raw_by_block'][0]:.1f}000000000000001", *c1_norm_6["casp9_treated_raw_by_block"][1:]],
            },
        },
    }
    chk(
        float(f"{c1_norm_6['casp9_treated_raw_by_block'][0]:.1f}000000000000001") == float(c1_norm_6["casp9_treated_raw_by_block"][0])
        and "FAIL_GATE_C1_NORMOXIA_ACTIVE_ARM_MISMATCH_WITH_5ARM_TABLE" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _sign_receipt({**c1_y, "c1_normoxia": _c1_n_f64_mm})})["failures"],
        "G42_c1_exact_fraction_casp9_catches_float64_collision",
    )
    # 6. C-1 common producer family acquisition record & preregistered batch/arm-order enforcement!
    _c1_no_cacq = _sign_receipt({**c1_y, "c1_common_family_acquisition_record": None})
    _c1_bad_batch = _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "differentiation_batch_ids": ["WRONG-BAT-1", *c1_norm_6["differentiation_batch_ids"][1:]]}})
    _c1_bad_cacq_sha = _sign_receipt({**c1_y, "c1_common_family_acquisition_record": {**c1_common_acq_6, "common_family_acquisition_sha256": "0" * 64}})
    chk(
        "HOLD_GATE_C1_MISSING_COMMON_FAMILY_ACQUISITION_RECORD" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _c1_no_cacq})["holds"]
        and "FAIL_GATE_C1_NORMOXIA_BATCH_OR_ARM_ORDER_MISMATCH_PREREG" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _c1_bad_batch})["failures"]
        and "FAIL_GATE_C1_COMMON_FAMILY_ACQUISITION_MISMATCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _c1_bad_cacq_sha})["failures"]
        and evaluate_gate42_gy032_channel_c_screen(g42_ok)["c1_common_family_acquisition_sha256"] == c1_common_acq_6["common_family_acquisition_sha256"],
        "G42_c1_common_family_acquisition_and_batch_allocation_enforced",
    )

    # --- GATE-43 (IIP-0065) Check D-1 Recomputed SI Responsiveness Boundary (2 tests) ---
    # 7. Computed stim/basal = 1.96 with reported SI = 2.00 (within 0.05 reconciliation tolerance) HOLDS on BOTH Arm A and Arm B!
    _d1_196_a = (lambda _b: {**_b, "record_sha256": sha256_bytes(canonical_json_bytes(_b))})({
        "lot_id": "D1-LOT-001", "plate_id": "D1-PLATE-01", "sibling_aliquot_pair_id": "D1-SIBPAIR-01",
        "arm_a_acquired_at_utc": "2026-10-03T12:30:00Z", "arm_b_acquired_at_utc": "2026-10-03T12:35:00Z",
        "insulin_normalization_basis": "PER_IEQ_PER_HOUR", "raw_trace_sha256": "6" * 64,
        "arm_a_basal_40": 1.00, "arm_a_stim_40": 1.96, "arm_b_basal_40": 1.00, "arm_b_stim_40": 2.20,
        "arm_a_basal_100": 1.00, "arm_a_stim_100": 2.20, "arm_b_basal_100": 1.00, "arm_b_stim_100": 2.20,
        "arm_a_si_40": 2.00, "arm_b_si_40": 2.20, "arm_a_si_100": 2.20, "arm_b_si_100": 2.20,
    })
    _d1_196_b = (lambda _b: {**_b, "record_sha256": sha256_bytes(canonical_json_bytes(_b))})({
        "lot_id": "D1-LOT-001", "plate_id": "D1-PLATE-01", "sibling_aliquot_pair_id": "D1-SIBPAIR-01",
        "arm_a_acquired_at_utc": "2026-10-03T12:30:00Z", "arm_b_acquired_at_utc": "2026-10-03T12:35:00Z",
        "insulin_normalization_basis": "PER_IEQ_PER_HOUR", "raw_trace_sha256": "6" * 64,
        "arm_a_basal_40": 1.00, "arm_a_stim_40": 2.20, "arm_b_basal_40": 1.00, "arm_b_stim_40": 1.96,
        "arm_a_basal_100": 1.00, "arm_a_stim_100": 2.20, "arm_b_basal_100": 1.00, "arm_b_stim_100": 2.20,
        "arm_a_si_40": 2.20, "arm_b_si_40": 2.00, "arm_a_si_100": 2.20, "arm_b_si_100": 2.20,
    })
    _g43_196a = {**g43_base, "check_d1_paired_gsis_record": _d1_196_a}; _g43_196a["check_d1_paired_assay_receipt"] = _mk_d1_unified(_g43_196a)
    _g43_196b = {**g43_base, "check_d1_paired_gsis_record": _d1_196_b}; _g43_196b["check_d1_paired_assay_receipt"] = _mk_d1_unified(_g43_196b)
    _r_196a = evaluate_gate43_cellgemma_guardrails_and_pilots(_g43_196a)
    _r_196b = evaluate_gate43_cellgemma_guardrails_and_pilots(_g43_196b)
    chk(
        _r_196a["verdict"] == "HOLD" and "HOLD_CHECK_D1_UNRESPONSIVE_RETAINED_T3_CONTROL" in _r_196a["holds"]
        and not _r_196a["failures"]
        and _r_196b["verdict"] == "HOLD" and "HOLD_CHECK_D1_WITHDRAWAL_ARM_LOSS_OF_GLUCOSE_RESPONSIVENESS" in _r_196b["holds"]
        and not _r_196b["failures"]
        and _r_196b["release_authorizing"] is False and _r_196b["adoption_authority"] is False and _r_196b["gy037_warn_retained"] is True,
        "G43_d1_recomputed_si_1p96_with_reported_2p00_holds",
    )
    # 8. Exact computed stim/basal == 2.00 with reported SI == 2.00 clears responsiveness check with all authority flags False!
    _d1_200 = (lambda _b: {**_b, "record_sha256": sha256_bytes(canonical_json_bytes(_b))})({
        "lot_id": "D1-LOT-001", "plate_id": "D1-PLATE-01", "sibling_aliquot_pair_id": "D1-SIBPAIR-01",
        "arm_a_acquired_at_utc": "2026-10-03T12:30:00Z", "arm_b_acquired_at_utc": "2026-10-03T12:35:00Z",
        "insulin_normalization_basis": "PER_IEQ_PER_HOUR", "raw_trace_sha256": "6" * 64,
        "arm_a_basal_40": 1.00, "arm_a_stim_40": 2.00, "arm_b_basal_40": 1.00, "arm_b_stim_40": 2.00,
        "arm_a_basal_100": 1.00, "arm_a_stim_100": 2.00, "arm_b_basal_100": 1.00, "arm_b_stim_100": 2.00,
        "arm_a_si_40": 2.00, "arm_b_si_40": 2.00, "arm_a_si_100": 2.00, "arm_b_si_100": 2.00,
    })
    _g43_200 = {**g43_base, "check_d1_paired_gsis_record": _d1_200}; _g43_200["check_d1_paired_assay_receipt"] = _mk_d1_unified(_g43_200)
    _r_200 = evaluate_gate43_cellgemma_guardrails_and_pilots(_g43_200)
    chk(
        _r_200["verdict"] == "PASS_DESCRIPTIVE_PILOT_ZERO_ODDS_GY037_WARN_RETAINED"
        and not _r_200["failures"] and not _r_200["holds"]
        and _r_200["release_authorizing"] is False and _r_200["adoption_authority"] is False
        and _r_200["live_ledger_authenticated"] is False and _r_200["gy037_revocation_eligible"] is False
        and _r_200["gy037_warn_retained"] is True,
        "G43_d1_recomputed_si_exact_2p00_passes_descriptive_only",
    )


    # --- GATE-40 (IIP-0062) Unified Recomputed Dialysis f_u Mean & Separate Efficacy-Culture Viability (3 tests) ---
    # 1. Low f_u disagreement (recomputed m_mu=0.020 vs submitted measured_fu_mean=0.029 -> diff 0.009, 1.45x inflation!) FAILS!
    _a0a_low_fu_inf = {
        **a0a_ok["a0a_matrix_fu_by_assay"],
        "vascular_viability_assay": {
            "matrix_id": "human_iec_sprouting_media",
            "nominal_conc_uM_grid": [round(x / 0.029, 4) for x in (0.0, 20.0, 40.0, 75.0, 150.0, 260.0, 500.0)],
            "dialysis_fu_replicates": [0.0195, 0.0198, 0.0200, 0.0202, 0.0205],
            "measured_fu_mean": 0.029,
            "analytical_sample_record_sha256": sha256_bytes(b"A0A-VASC-LOWFU-INFLATION"),
        },
    }
    _r_low_fu = evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "a0a_matrix_fu_by_assay": _a0a_low_fu_inf})})
    chk(
        "FAIL_GATE_A0A_FU_MISMATCH_VS_DIALYSIS_REPLICATES" in _r_low_fu["failures"]
        and "FAIL_GATE_A0A_FREE_GRID_MISMATCH_VS_NOMINAL_AND_FU:vascular_viability_assay" in _r_low_fu["failures"],
        "G40_a0a_low_fu_submitted_vs_recomputed_mean_inflation_fails",
    )
    # 2. Missing separate macrophage-fibroblast efficacy-culture viability/denominators HOLDS; raw viable-cell count mismatch FAILS!
    _a0a_no_ev = [{k: v for k, v in r.items() if k != "efficacy_culture_viability_7d_pct"} for r in a0a_reps_ok]
    _a0a_fit_no_ev = _sign_receipt({**a0a_fit_ok, "raw_replicates_sha256": sha256_bytes(canonical_json_bytes(_a0a_no_ev))})
    _a0a_bad_cnt = [dict(r) for r in a0a_reps_ok]
    _a0a_bad_cnt[3] = {**_a0a_bad_cnt[3], "efficacy_treated_viable_cells_by_donor": [6000, 6000, 6000, 6000, 6000]}
    _a0a_fit_bad_cnt = _sign_receipt({**a0a_fit_ok, "raw_replicates_sha256": sha256_bytes(canonical_json_bytes(_a0a_bad_cnt))})
    chk(
        "HOLD_GATE_A0A_MISSING_EFFICACY_CULTURE_VIABILITY" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "a0a_donor_replicates_by_conc": _a0a_no_ev, "a0a_fit_artifact_receipt": _a0a_fit_no_ev})})["holds"]
        and "FAIL_GATE_A0A_EFFICACY_VIABILITY_MISMATCH_VS_RAW_CELL_COUNTS:3" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "a0a_donor_replicates_by_conc": _a0a_bad_cnt, "a0a_fit_artifact_receipt": _a0a_fit_bad_cnt})})["failures"],
        "G40_a0a_efficacy_culture_viability_missing_holds_and_count_mismatch_fails",
    )
    # 3. Cytotoxic drop in macrophage-fibroblast efficacy culture at IC50_U95 (75 uM -> 72% viable) while vascular spheroids stay 97% FAILS!
    _a0a_cyto = [dict(r) for r in a0a_reps_ok]
    _a0a_cyto[3] = {**_a0a_cyto[3], "efficacy_treated_viable_cells_by_donor": [7170, 7185, 7200, 7215, 7230], "efficacy_culture_viability_7d_pct": [71.7, 71.85, 72.0, 72.15, 72.3]}
    _a0a_fit_cyto = _sign_receipt({**a0a_fit_ok, "raw_replicates_sha256": sha256_bytes(canonical_json_bytes(_a0a_cyto))})
    chk(
        "FAIL_GATE_A0A_EFFICACY_CULTURE_CYTOTOXICITY_CONFOUNDING" in evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _sign_receipt({**a0a_ok, "a0a_donor_replicates_by_conc": _a0a_cyto, "a0a_fit_artifact_receipt": _a0a_fit_cyto})})["failures"],
        "G40_a0a_efficacy_culture_cytotoxicity_at_ic50_fails",
    )

    # --- GATE-41 (IIP-0063) Contiguous B-0a Efficacy Window & Matrix/Unit-Bound Analytical Ledger (3 tests) ---
    # 4. B-0a interior non-monotonic efficacy dip at 12 nM (between EC50_U95=6 nM and C_safe_max_bench=25 nM) -> HOLDS!
    _b0a_e_dip = [dict(r) for r in b0a_e_reps_ok]
    _dip_vals = [42.0, 43.0, 44.0, 45.0, 46.0, 47.0]
    _b0a_e_dip[4] = {**_b0a_e_dip[4], "beta_cytokine_protection_pct": _dip_vals, "raw_unit_measurements": {**_b0a_e_dip[4]["raw_unit_measurements"], "beta_cytokine_protection_pct": _mk_b0a_raw_ratio(_dip_vals, _b0a_e_dip[4]["matched_vehicle_record_id"], 100.0, is_inhib=True)}}
    _b0a_eb_dip = list(b0a_eb_grid); _b0a_eb_dip[4] = 44.5
    _b0a_an_dip = _sign_receipt({**b0a_an_ok, "raw_efficacy_replicates_sha256": sha256_bytes(canonical_json_bytes(_b0a_e_dip))})
    _r_b0a_dip = evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": _sign_receipt({**b0a_ok, "efficacy_beta_protection_pct_grid": _b0a_eb_dip, "efficacy_replicates_by_conc": _b0a_e_dip, "b0a_analysis_receipt": _b0a_an_dip})})
    chk("HOLD_GATE_B0A_NONMONOTONIC_INTERIOR_EFFICACY_DIP" in _r_b0a_dip["holds"], "G41_b0a_interior_efficacy_dip_holds")
    # 5. B-2b repeating a biological_unit_id within a timepoint (technical pseudoreplication) -> HOLDS!
    _b2b_rep_unit = _mk_r8_b2b_replicates()
    _b2b_rep_unit["timepoint_replicate_records"][1]["biological_unit_ids"][5] = _b2b_rep_unit["timepoint_replicate_records"][1]["biological_unit_ids"][0]
    _r_rep_u = evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, **_b2b_rep_unit})})
    chk("HOLD_GATE_B2B_BENCH_UPSTREAM_SAMPLE_LEDGER_INCOMPLETE_OR_DUPLICATE" in _r_rep_u["holds"], "G41_b2b_duplicate_biological_unit_id_holds")
    # 6. Mixed assay_matrix between B-2 whole-blood ledger and B-2b serum exposure series -> HOLDS!
    _b2_wb_lg = _mk_b12_ledger("B-2", assay_matrix="human_whole_blood")
    _b2_wb_ev = _sign_receipt({**b2_y, "analytical_sample_ledger": _b2_wb_lg})
    _b2bb_wb_ev = _sign_receipt({**b2bb_y, "parent_receipt_sha256": _b2_wb_ev["receipt_sha256"], "prerequisite_receipt_sha256s": {"B-1": b1_y["receipt_sha256"], "B-2": _b2_wb_ev["receipt_sha256"]}})
    _r_mm_mat = evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2_evidence": _b2_wb_ev, "b2b_bench_evidence": _b2bb_wb_ev})
    chk("HOLD_GATE_B2B_BENCH_UPSTREAM_SAMPLE_LEDGER_INCOMPLETE_OR_DUPLICATE" in _r_mm_mat["holds"], "G41_b2b_mixed_assay_matrix_in_upstream_ledger_holds")

    # --- GATE-42 (IIP-0064) True Candidate-Neutral Shared Family Preregistration & Acquisition Digest (2 tests) ---
    # 7. Two distinct candidates (PMAIP1+BCL2L11 and BCL2L11) share the EXACT SAME byte-for-byte c1_prereg_y AND
    #    c1_common_family_acquisition_record AND five_arm_family_matrix_sha256, and BOTH pass with identical shared digests!
    _sh_norm_bcl_raw = _mk_r8_c1_block(
        assay_record_id="C1-SH-NORM-BCL", bids=["B1", "B2", "B3", "B4", "B5", "B6"],
        c9_vec=[44.0, 48.0, 43.0, 47.0, 45.0, 49.0], ctrl_vec=[54.0, 52.0, 56.0, 55.0, 53.0, 54.0],
        tr_vec=[71.1, 69.6, 73.8, 72.5, 69.2, 72.4], veh_vec=[90.0, 89.0, 91.0, 90.0, 88.0, 91.0],
        comp_vec=[71.1, 69.6, 73.8, 72.5, 69.2, 72.4], target="BCL2L11",
    )
    _sh_hyp_bcl_raw = _mk_r8_c1_block(
        assay_record_id="C1-SH-HYP-BCL", bids=["H1", "H2", "H3", "H4", "H5", "H6"],
        c9_vec=[42.0, 46.0, 41.0, 45.0, 43.0, 47.0], ctrl_vec=[50.0, 49.0, 52.0, 51.0, 48.0, 50.0],
        tr_vec=[67.0, 66.5, 68.5, 68.2, 64.5, 67.3], veh_vec=[87.0, 86.0, 88.0, 87.0, 85.0, 88.0],
        comp_vec=[67.0, 66.5, 68.5, 68.2, 64.5, 67.3], target="BCL2L11",
        target_kd=80.0, nonbeta_surv=93.0, ctrl_nonbeta=68.0, batch_prefix="C1-HBAT",
    )
    _sh_5_norm = {**c1_norm_6["all_five_arms_paired_data"], "BCL2L11": _sh_norm_bcl_raw["all_five_arms_paired_data"]["BCL2L11"]}
    _sh_5_hyp = {**c1_hyp_6["all_five_arms_paired_data"], "BCL2L11": _sh_hyp_bcl_raw["all_five_arms_paired_data"]["BCL2L11"]}
    _sh_p_c9_n = {**c1_norm_6["family_raw_p_values_casp9"], "BCL2L11": _sh_norm_bcl_raw["family_raw_p_values_casp9"]["BCL2L11"]}
    _sh_p_c9_h = {**c1_hyp_6["family_raw_p_values_casp9"], "BCL2L11": _sh_hyp_bcl_raw["family_raw_p_values_casp9"]["BCL2L11"]}
    _sh_p_b_n = {**c1_norm_6["family_raw_p_values_beta"], "BCL2L11": _sh_norm_bcl_raw["family_raw_p_values_beta"]["BCL2L11"]}
    _sh_p_b_h = {**c1_hyp_6["family_raw_p_values_beta"], "BCL2L11": _sh_hyp_bcl_raw["family_raw_p_values_beta"]["BCL2L11"]}
    _sh_norm_dual = {**c1_norm_6, "all_five_arms_paired_data": _sh_5_norm, "family_raw_p_values_casp9": _sh_p_c9_n, "holm_adjusted_casp9_p_value": holm_bonferroni_adjust(_sh_p_c9_n)[tg_dual], "family_raw_p_values_beta": _sh_p_b_n, "holm_adjusted_beta_p_value": holm_bonferroni_adjust(_sh_p_b_n)[tg_dual]}
    _sh_hyp_dual = {**c1_hyp_6, "all_five_arms_paired_data": _sh_5_hyp, "family_raw_p_values_casp9": _sh_p_c9_h, "holm_adjusted_casp9_p_value": holm_bonferroni_adjust(_sh_p_c9_h)[tg_dual], "family_raw_p_values_beta": _sh_p_b_h, "holm_adjusted_beta_p_value": holm_bonferroni_adjust(_sh_p_b_h)[tg_dual]}
    _sh_norm_bcl = {**_sh_norm_bcl_raw, "all_five_arms_paired_data": _sh_5_norm, "family_raw_p_values_casp9": _sh_p_c9_n, "holm_adjusted_casp9_p_value": holm_bonferroni_adjust(_sh_p_c9_n)["BCL2L11"], "family_raw_p_values_beta": _sh_p_b_n, "holm_adjusted_beta_p_value": holm_bonferroni_adjust(_sh_p_b_n)["BCL2L11"]}
    _sh_hyp_bcl = {**_sh_hyp_bcl_raw, "all_five_arms_paired_data": _sh_5_hyp, "family_raw_p_values_casp9": _sh_p_c9_h, "holm_adjusted_casp9_p_value": holm_bonferroni_adjust(_sh_p_c9_h)["BCL2L11"], "family_raw_p_values_beta": _sh_p_b_h, "holm_adjusted_beta_p_value": holm_bonferroni_adjust(_sh_p_b_h)["BCL2L11"]}
    _sh_fam_sha = _mk_c1_fam_sha(_sh_norm_dual, _sh_hyp_dual)
    _sh_common_acq = _mk_c1_common_acq(_sh_norm_dual, _sh_hyp_dual, c1_prereg_y, acq_id="C1-COMMON-ACQ-SHARED-2CAND")
    _c1_dual_sh = _sign_receipt({**c1_y, "five_arm_family_matrix_sha256": _sh_fam_sha, "c1_common_family_acquisition_record": _sh_common_acq, "c1_normoxia": _sh_norm_dual, "c1_hypoxia_2pct_o2": _sh_hyp_dual})
    _c2_dual_sh = _sign_receipt({**c2_y, "parent_receipt_sha256": _c1_dual_sh["receipt_sha256"]})
    _sw_dual_sh = _mk_r8_switch(py, by, ly, ry, mat_yc, "2026-09-28T14:00:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": _c2_dual_sh["receipt_sha256"]}, transient_engagement=_mk_c_eng(c1_cohort_y, "2026-09-28T13:00:00Z", stage_name="NATIVE_SAFETY_SWITCH", lot_s_id=ly, win_start="2026-09-25T12:00:00Z", win_end="2026-09-28T13:15:00Z", mode="VALIDATED_LONGITUDINAL_KINETICS"))
    _g0v_dual_sh = _mk_r8_gate0v(py, by, ly, ry, mat_yc, "2026-09-28T14:30:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": _c2_dual_sh["receipt_sha256"]}, transient_engagement=_mk_c_eng(c1_cohort_y, "2026-09-28T13:15:00Z", stage_name="GATE-0V-KILL", lot_s_id=ly, win_start="2026-09-25T12:00:00Z", win_end="2026-09-28T13:30:00Z", mode="VALIDATED_LONGITUDINAL_KINETICS"))
    _pr_c3_dual_sh = {**pr_c1_yc, "NATIVE_SAFETY_SWITCH": _sw_dual_sh["receipt_sha256"], "GATE-0V-KILL": _g0v_dual_sh["receipt_sha256"]}
    _c3n_dual_sh = _sign_receipt({**c3_nk_y, "parent_receipt_sha256": _c2_dual_sh["receipt_sha256"], "prerequisite_receipt_sha256s": _pr_c3_dual_sh})
    _c3g_dual_sh = _sign_receipt({**c3_gsis_y, "parent_receipt_sha256": _c3n_dual_sh["receipt_sha256"], "prerequisite_receipt_sha256s": _pr_c3_dual_sh})
    _c1_bcl_shared = _sign_receipt({**c1_y, "candidate_gene": "BCL2L11", "five_arm_family_matrix_sha256": _sh_fam_sha, "c1_common_family_acquisition_record": _sh_common_acq, "c1_normoxia": _sh_norm_bcl, "c1_hypoxia_2pct_o2": _sh_hyp_bcl})
    _c2_bcl_sh = _sign_receipt({**c2_y, "candidate_gene": "BCL2L11", "parent_receipt_sha256": _c1_bcl_shared["receipt_sha256"], "c2_per_lot_proliferation_records": [_mk_c2_prolif_lot(1, gene_v="BCL2L11"), _mk_c2_prolif_lot(2, gene_v="BCL2L11"), _mk_c2_prolif_lot(3, gene_v="BCL2L11")], "transient_target_engagement_record": _mk_c_eng(c1_cohort_y, "2026-09-25T08:00:00Z", stage_name="C-2", lot_s_id=ly, target_g="BCL2L11", win_start="2026-09-22T08:00:00Z", win_end="2026-09-25T09:00:00Z")})
    _sw_bcl_sh = _mk_r8_switch(py, by, ly, ry, mat_yc, "2026-09-28T14:00:00Z", candidate_gene="BCL2L11", comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": _c2_bcl_sh["receipt_sha256"]}, transient_engagement=_mk_c_eng(c1_cohort_y, "2026-09-28T13:00:00Z", stage_name="NATIVE_SAFETY_SWITCH", lot_s_id=ly, target_g="BCL2L11", win_start="2026-09-25T12:00:00Z", win_end="2026-09-28T13:15:00Z", mode="VALIDATED_LONGITUDINAL_KINETICS"))
    _g0v_bcl_sh = _mk_r8_gate0v(py, by, ly, ry, mat_yc, "2026-09-28T14:30:00Z", candidate_gene="BCL2L11", comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": _c2_bcl_sh["receipt_sha256"]}, transient_engagement=_mk_c_eng(c1_cohort_y, "2026-09-28T13:15:00Z", stage_name="GATE-0V-KILL", lot_s_id=ly, target_g="BCL2L11", win_start="2026-09-25T12:00:00Z", win_end="2026-09-28T13:30:00Z", mode="VALIDATED_LONGITUDINAL_KINETICS"))
    _pr_c3_bcl_sh = {**pr_c1_yc, "NATIVE_SAFETY_SWITCH": _sw_bcl_sh["receipt_sha256"], "GATE-0V-KILL": _g0v_bcl_sh["receipt_sha256"]}
    _c3n_bcl_sh = _sign_receipt({**c3_nk_y, "candidate_gene": "BCL2L11", "parent_receipt_sha256": _c2_bcl_sh["receipt_sha256"], "prerequisite_receipt_sha256s": _pr_c3_bcl_sh, "transient_target_engagement_record": _mk_c_eng(c1_cohort_y, "2026-09-30T09:00:00Z", stage_name="C-3-NK", lot_s_id=ly, target_g="BCL2L11", win_start="2026-09-28T15:00:00Z", win_end="2026-09-30T11:00:00Z")})
    _c3g_bcl_sh = _sign_receipt({**c3_gsis_y, "candidate_gene": "BCL2L11", "parent_receipt_sha256": _c3n_bcl_sh["receipt_sha256"], "prerequisite_receipt_sha256s": _pr_c3_bcl_sh, "transient_target_engagement_record": _mk_c_eng(c1_cohort_y, "2026-10-01T16:00:00Z", stage_name="C-3-GSIS", lot_s_id=ly, target_g="BCL2L11", win_start="2026-09-30T13:00:00Z", win_end="2026-10-01T18:00:00Z"), "readout2_evidence": _mk_r8_readout2(matched_comparator_id=nt_y, block_prefix="C3G", lot_id=ly, stage7_start_utc="2026-09-12T00:00:00Z", sort_reaggregation_utc="2026-09-22T00:00:00Z", assay_harvest_utc="2026-10-01T00:00:00Z", specimen_id=f"SPEC-C-3-GSIS-{ly}", intervention_cohort_id=c1_cohort_y, candidate_gene="BCL2L11")})
    _r_dual_sh = evaluate_gate42_gy032_channel_c_screen({**g42_ok, "native_switch_evidence": _sw_dual_sh, "gate0v_evidence": _g0v_dual_sh, "c1_evidence": _c1_dual_sh, "c2_evidence": _c2_dual_sh, "c3_nk_evidence": _c3n_dual_sh, "c3_gsis_evidence": _c3g_dual_sh})
    _r_bcl_sh = evaluate_gate42_gy032_channel_c_screen({**g42_ok, "target_gene": "BCL2L11", "native_switch_evidence": _sw_bcl_sh, "gate0v_evidence": _g0v_bcl_sh, "c1_evidence": _c1_bcl_shared, "c2_evidence": _c2_bcl_sh, "c3_nk_evidence": _c3n_bcl_sh, "c3_gsis_evidence": _c3g_bcl_sh})
    chk(
        _r_dual_sh["verdict"] == OFFLINE_VERDICT_PRIMARY
        and _r_bcl_sh["verdict"] == OFFLINE_VERDICT_PRIMARY
        and _r_dual_sh["c1_preregistration_sha256"] == _r_bcl_sh["c1_preregistration_sha256"] == c1_prereg_y["receipt_sha256"]
        and _r_dual_sh["c1_common_family_acquisition_sha256"] == _r_bcl_sh["c1_common_family_acquisition_sha256"] == _sh_common_acq["common_family_acquisition_sha256"],
        "G42_two_candidates_share_exact_same_prereg_and_common_acquisition_digest",
    )
    # 8. Candidate-bound preregistration receipt (carrying candidate_gene) FAILS candidate-neutrality!
    _c1_prereg_non_neutral = _sign_receipt({**c1_prereg_y, "candidate_gene": tg_dual})
    _c1_y_nn = _sign_receipt({**c1_y, "prerequisite_receipt_sha256s": {**pr_c1_yc, "C-1-PREREGISTRATION": _c1_prereg_non_neutral["receipt_sha256"]}, "c1_common_family_acquisition_record": _mk_c1_common_acq(c1_norm_6, c1_hyp_6, _c1_prereg_non_neutral)})
    chk(
        "FAIL_GATE_C1_PREREG_MUST_BE_CANDIDATE_NEUTRAL" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_preregistered_plan_receipt": _c1_prereg_non_neutral, "c1_evidence": _c1_y_nn})["failures"],
        "G42_c1_prereg_with_candidate_gene_fails_neutrality",
    )


    # --- GATE-40 (IIP-0062) A-0b Raw Donor/Efficacy Viability, Dense Pilot Envelope, & A-2 Readout-3B Provenance (5 tests) ---
    # 1. A-0b missing raw_donor_measurements or efficacy_culture_viability_14d_pct HOLDS; raw mismatch FAILS!
    _a0b_no_raw = [{k: v for k, v in r.items() if k != "raw_donor_measurements"} for r in a0b_reps_ok]
    _a0b_fit_nr = _sign_receipt({**a0b_fit_ok, "raw_replicates_sha256": sha256_bytes(canonical_json_bytes(_a0b_no_raw))})
    _a0b_bad_raw = [dict(r) for r in a0b_reps_ok]
    _a0b_bad_raw[3] = {**_a0b_bad_raw[3], "raw_donor_measurements": {**_a0b_bad_raw[3]["raw_donor_measurements"], "viability_14d": _mk_a0b_raw_pair([70.0, 70.0, 70.0], 96.5)}}
    _a0b_fit_br = _sign_receipt({**a0b_fit_ok, "raw_replicates_sha256": sha256_bytes(canonical_json_bytes(_a0b_bad_raw))})
    chk(
        "HOLD_GATE_A0B_MISSING_RAW_DONOR_OR_EFFICACY_VIABILITY" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "a0b_14d_safety_replicates_by_conc": _a0b_no_raw, "a0b_fit_artifact_receipt": _a0b_fit_nr})})["holds"]
        and "FAIL_GATE_A0B_NORMALIZED_PCT_MISMATCH_VS_RAW_DONOR_VALUES" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "a0b_14d_safety_replicates_by_conc": _a0b_bad_raw, "a0b_fit_artifact_receipt": _a0b_fit_br})})["failures"],
        "G40_a0b_raw_donor_missing_holds_and_mismatch_fails",
    )
    # 2. A-0b 0 uM self-normalized zero-dispersion control ([100,100,100]) PASSES while 14d efficacy-culture drop (<90%) HOLDS!
    _a0b_z0 = [dict(r) for r in a0b_reps_ok]
    _a0b_z0[0] = {**_a0b_z0[0], "viability_14d_pct": [100.0, 100.0, 100.0], "efficacy_culture_viability_14d_pct": [100.0, 100.0, 100.0], "raw_donor_measurements": {**_a0b_z0[0]["raw_donor_measurements"], "viability_14d": _mk_a0b_raw_pair([100.0, 100.0, 100.0], 96.5), "efficacy_culture_viability_14d": _mk_a0b_raw_pair([100.0, 100.0, 100.0], 97.0)}}
    _a0b_fit_z0 = _sign_receipt({**a0b_fit_ok, "raw_replicates_sha256": sha256_bytes(canonical_json_bytes(_a0b_z0))})
    _a0b_z0_rcpt = _sign_receipt({**a0b_y, "a0b_14d_safety_replicates_by_conc": _a0b_z0, "a0b_fit_artifact_receipt": _a0b_fit_z0})
    _a1b_z0_rcpt = _sign_receipt({**a1b_y, "parent_receipt_sha256": _a0b_z0_rcpt["receipt_sha256"]})
    _a0b_eff_drop = [dict(r) for r in a0b_reps_ok]
    _a0b_eff_drop[4] = {**_a0b_eff_drop[4], "efficacy_culture_viability_14d_pct": [81.7, 82.0, 82.3], "raw_donor_measurements": {**_a0b_eff_drop[4]["raw_donor_measurements"], "efficacy_culture_viability_14d": _mk_a0b_raw_pair([81.7, 82.0, 82.3], 97.0)}}
    _a0b_fit_ed = _sign_receipt({**a0b_fit_ok, "raw_replicates_sha256": sha256_bytes(canonical_json_bytes(_a0b_eff_drop))})
    chk(
        evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _a0b_z0_rcpt, "a1_bench_evidence": _a1b_z0_rcpt})["verdict"] == "PASS_BENCH_ONLY_UNEDITED_PRE_MATERIALIZATION"
        and "HOLD_GATE_A0B_14D_CEILING_UNSUBSTANTIATED_BY_DONOR_REPLICATES" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "a0b_14d_safety_replicates_by_conc": _a0b_eff_drop, "a0b_fit_artifact_receipt": _a0b_fit_ed})})["holds"],
        "G40_a0b_zero_conc_self_norm_passes_and_14d_efficacy_viab_drop_holds",
    )
    # 3. A-0b & A-1 missing dense_pilot_trace HOLDS!
    _env0b_nodpt = {k: v for k, v in a0b_env_ok.items() if k != "dense_pilot_trace"}
    _env1_nodpt = {k: v for k, v in a1e_env_ok.items() if k != "dense_pilot_trace"}
    chk(
        "HOLD_GATE_A0B_MISSING_DENSE_PILOT_ENVELOPE_EVIDENCE" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "a0b_local_pk_envelope": _env0b_nodpt})})["holds"]
        and "HOLD_GATE_A1_MISSING_DENSE_PILOT_ENVELOPE_EVIDENCE" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "a1_local_pk_envelope": _env1_nodpt})})["holds"],
        "G40_a0b_and_a1_missing_dense_pilot_trace_holds",
    )
    # 4. A-0b & A-1 dense_pilot_trace with faster empirical burst slope than declared k_rise/k_elim FAILS!
    _fast_dpt = {k: v for k, v in a0b_env_ok["dense_pilot_trace"].items() if k != "pilot_trace_sha256"}
    _fast_dpt["burst_segment_free_parent_uM"] = [180.0, 195.0, 200.0, 190.0, 180.0, 170.0]  # rise ~0.08/h >> kr_a=0.002/h!
    _fast_dpt_sha = sha256_bytes(canonical_json_bytes(_fast_dpt))
    _env0b_under = {k: v for k, v in a0b_env_ok.items() if k != "envelope_receipt_sha256"}
    _env0b_under["dense_pilot_trace"] = {**_fast_dpt, "pilot_trace_sha256": _fast_dpt_sha}
    _env0b_under["envelope_model_sha256"] = _fast_dpt_sha
    _env0b_under["envelope_receipt_sha256"] = sha256_bytes(canonical_json_bytes(_env0b_under))
    chk(
        "FAIL_GATE_A0B_LOCAL_PK_ENVELOPE_RATE_UNDERSTATES_DENSE_PILOT" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "a0b_local_pk_envelope": _env0b_under})})["failures"],
        "G40_a0b_dense_pilot_faster_slope_fails_envelope_rate",
    )
    # 5. A-2 Readout-3B kinetic trace carrying unrelated specimen_id FAILS; missing provenance HOLDS!
    _a2_r3b_unlinked = _mk_r8_readout3b(matched_vehicle_lot_id=bv_a, specimen_id="SPEC-UNRELATED-A2", specimen_lot_id=ly, intervention_cohort_id=f"COHORT-A2-{ly}")
    _a2_r3b_noprov = _mk_r8_readout3b(matched_vehicle_lot_id=bv_a)
    chk(
        "FAIL_GATE_A2_READOUT3B_SPECIMEN_LOT_OR_COHORT_MISMATCH" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout3b_evidence": _a2_r3b_unlinked})})["failures"]
        and "HOLD_GATE_A2_READOUT3B_MISSING_SPECIMEN_PROVENANCE" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "readout3b_evidence": _a2_r3b_noprov})})["holds"],
        "G40_a2_readout3b_specimen_provenance_enforced",
    )

    # --- GATE-41 (IIP-0063) B-2b All-5-Stream Reconciliation & Dual Matrix + B-4 Non-Dialysate Zero-Dispersion f_u (3 tests) ---
    # 6. B-2b (bench & exact) extra unindexed systemic/recirc measurement (len > len(source_sample_ids)) FAILS!
    _b2b_extra_sys = _mk_r8_b2b_replicates()
    _b2b_extra_sys["timepoint_replicate_records"][0]["systemic_parent_total_replicates_nM"].append(0.031)
    _b2b_extra_sys["timepoint_replicate_records"][0]["systemic_parent_blq_flags"].append(True)
    _b2b_extra_sys["timepoint_replicate_records"][0]["systemic_bmt_total_replicates_nM"].append(0.012)
    _b2b_extra_sys["timepoint_replicate_records"][0]["systemic_bmt_blq_flags"].append(True)
    _b2be_extra_rec = _mk_r8_b2b_replicates(evidence_scope="exact_product")
    _b2be_extra_rec["timepoint_replicate_records"][0]["recirc_bmt_total_replicates_nM"].append(0.018)
    _b2be_extra_rec["timepoint_replicate_records"][0]["recirc_bmt_blq_flags"].append(True)
    chk(
        "FAIL_GATE_B2B_BENCH_STREAM_LENGTH_MISMATCH_VS_SAMPLE_LEDGER:0" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b2b_bench_evidence": _sign_receipt({**b2bb_y, **_b2b_extra_sys})})["failures"]
        and "FAIL_GATE_B2B_EXACT_STREAM_LENGTH_MISMATCH_VS_SAMPLE_LEDGER:0" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b2b_exact_evidence": _sign_receipt({**b2be_y, **_b2be_extra_rec})})["failures"],
        "G41_b2b_unmatched_extra_stream_observations_fail_bench_and_exact",
    )
    # 7. B-2b mismatched recirc_assay_matrix in upstream ledger HOLDS!
    _b1_rec_mm = _sign_receipt({**b1_y, "analytical_sample_ledger": _mk_b12_ledger("B-1", recirc_assay_matrix="whole_blood")})
    _b2_rec_mm = _sign_receipt({**b2_y, "parent_receipt_sha256": _b1_rec_mm["receipt_sha256"]})
    _b2bb_rec_mm = _sign_receipt({**b2bb_y, "parent_receipt_sha256": _b2_rec_mm["receipt_sha256"], "prerequisite_receipt_sha256s": {"B-1": _b1_rec_mm["receipt_sha256"], "B-2": _b2_rec_mm["receipt_sha256"]}})
    chk(
        "HOLD_GATE_B2B_BENCH_UPSTREAM_SAMPLE_LEDGER_INCOMPLETE_OR_DUPLICATE" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b1_evidence": _b1_rec_mm, "b2_evidence": _b2_rec_mm, "b2b_bench_evidence": _b2bb_rec_mm})["holds"],
        "G41_b2b_recirc_assay_matrix_mismatch_in_ledger_holds",
    )
    # 8. B-4 non-dialysate interstitial fluid with identical zero-dispersion fu_parent_replicates [0.14, 0.14, 0.14] HOLDS (never falls back to replicate[0]), while normal non-zero dispersion PASSES!
    _b4_isf_zdisp_cal = {
        k: v for k, v in b4_y["b4_local_compartment_calibration"].items() if k != "calibration_sha256"
    }
    _b4_isf_zdisp_cal["compartment_matrix_id"] = "PERI_GRAFT_INTERSTITIAL_FLUID"
    _b4_isf_zdisp_cal["concentration_basis"] = "RECOVERY_CORRECTED_TOTAL_MATRIX_CONVERTED_BY_LOCAL_FU"
    _b4_isf_zdisp_cal["fu_parent_replicates"] = [0.14, 0.14, 0.14]
    _b4_isf_zdisp_cal["fu_bmt_replicates"] = [0.15, 0.15, 0.15]
    _b4_isf_zdisp_cal["calibration_sha256"] = sha256_bytes(canonical_json_bytes(_b4_isf_zdisp_cal))
    _r_b4_zfu = evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b4_evidence": _sign_receipt({**b4_y, "b4_local_compartment_calibration": _b4_isf_zdisp_cal})})
    chk(
        "HOLD_GATE_B4_LOCAL_FU_ZERO_DISPERSION_UNESTIMABLE" in _r_b4_zfu["holds"]
        and evaluate_gate41_deucravacitinib_tyk2(g41_ok)["verdict"] == OFFLINE_VERDICT_PRIMARY,
        "G41_b4_measured_total_zero_disp_fu_holds_while_dialysate_passes",
    )


    # --- GATE-40 (IIP-0062) A-0b 14-Day Nominal-to-Free Assay Matrix Reconciliation & Vehicle Baseline Binding (4 tests) ---
    # 1. A-0b missing a0b_matrix_fu_by_assay HOLDS!
    chk(
        "HOLD_GATE_A0B_MISSING_14D_ASSAY_MATRIX_FU_RECONCILIATION" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({k: v for k, v in a0b_y.items() if k not in ("a0b_matrix_fu_by_assay", "receipt_sha256")})})["holds"],
        "G40_a0b_missing_14d_matrix_fu_holds",
    )
    # 2. A-0b 14-day nominal*fu disagreeing with conc_uM grid FAILS!
    _a0b_mfu_bad = {**a0b_mfu_ok, "vascular_viability_assay": {**a0b_mfu_ok["vascular_viability_assay"], "nominal_conc_uM_grid": [x * 1.5 for x in a0b_mfu_ok["vascular_viability_assay"]["nominal_conc_uM_grid"]]}}
    chk(
        "FAIL_GATE_A0B_14D_NOMINAL_TO_FREE_RECONCILIATION_FAILED" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "a0b_matrix_fu_by_assay": _a0b_mfu_bad})})["failures"],
        "G40_a0b_14d_nominal_to_free_mismatch_fails",
    )
    # 3. A-0b 14-day dialysis_fu_replicates zero-dispersion HOLDS!
    _a0b_mfu_zd = {**a0b_mfu_ok, "vascular_viability_assay": {**a0b_mfu_ok["vascular_viability_assay"], "dialysis_fu_replicates": [0.50, 0.50, 0.50]}}
    chk(
        "HOLD_GATE_A0B_14D_DIALYSIS_FU_ZERO_DISPERSION:vascular_viability_assay" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "a0b_matrix_fu_by_assay": _a0b_mfu_zd})})["holds"],
        "G40_a0b_14d_dialysis_fu_zero_disp_holds",
    )
    # 4. A-0b matched_vehicle_raw_baselines disagreeing with donor vehicle denominators FAILS!
    _a0b_bad_vb = [dict(r) for r in a0b_reps_ok]
    _a0b_bad_vb[2] = {**_a0b_bad_vb[2], "matched_vehicle_raw_baselines": {**_a0b_bad_vb[2]["matched_vehicle_raw_baselines"], "day0_sprout_length_um": 600.0}}
    _a0b_fit_bvb = _sign_receipt({**a0b_fit_ok, "raw_replicates_sha256": sha256_bytes(canonical_json_bytes(_a0b_bad_vb))})
    chk(
        "FAIL_GATE_A0B_VEHICLE_BASELINE_MISMATCH_VS_DONOR_DENOMINATORS" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({**a0b_y, "a0b_14d_safety_replicates_by_conc": _a0b_bad_vb, "a0b_fit_artifact_receipt": _a0b_fit_bvb})})["failures"],
        "G40_a0b_vehicle_baseline_mismatch_vs_donor_denominators_fails",
    )

    # --- GATE-41 (IIP-0063) B-0a & B-0a-exact Matched-Vehicle Raw Denominator Reconciliation + Non-Numeric cs_op Guard (4 tests) ---
    # 5. B-0a missing raw_unit_measurements HOLDS; tampered matched-vehicle denominator FAILS!
    _b0a_s_noraw = [{k: v for k, v in r.items() if k != "raw_unit_measurements"} for r in b0a_s_reps_ok]
    _b0a_an_snr = _sign_receipt({**b0a_an_ok, "raw_safety_replicates_sha256": sha256_bytes(canonical_json_bytes(_b0a_s_noraw))})
    _b0a_s_badraw = [dict(r) for r in b0a_s_reps_ok]
    _b0a_s_badraw[2] = {**_b0a_s_badraw[2], "raw_unit_measurements": {**_b0a_s_badraw[2]["raw_unit_measurements"], "sprouting_pct": _mk_b0a_raw_ratio([75.0]*6, _b0a_s_badraw[2]["matched_vehicle_record_id"], 400.0)}}
    _b0a_an_sbr = _sign_receipt({**b0a_an_ok, "raw_safety_replicates_sha256": sha256_bytes(canonical_json_bytes(_b0a_s_badraw))})
    chk(
        "HOLD_GATE_B0A_MISSING_MATCHED_VEHICLE_RAW_DATA" in evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": _sign_receipt({**b0a_ok, "safety_replicates_by_conc": _b0a_s_noraw, "b0a_analysis_receipt": _b0a_an_snr})})["holds"]
        and "FAIL_GATE_B0A_NORMALIZED_PCT_MISMATCH_VS_MATCHED_VEHICLE:2:sprouting_pct" in evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": _sign_receipt({**b0a_ok, "safety_replicates_by_conc": _b0a_s_badraw, "b0a_analysis_receipt": _b0a_an_sbr})})["failures"],
        "G41_b0a_safety_raw_matched_vehicle_missing_holds_and_mismatch_fails",
    )
    # 6. B-0a efficacy missing raw_unit_measurements HOLDS; tampered efficacy vehicle denominator FAILS!
    _b0a_e_noraw = [{k: v for k, v in r.items() if k != "raw_unit_measurements"} for r in b0a_e_reps_ok]
    _b0a_an_enr = _sign_receipt({**b0a_an_ok, "raw_efficacy_replicates_sha256": sha256_bytes(canonical_json_bytes(_b0a_e_noraw))})
    _b0a_e_badraw = [dict(r) for r in b0a_e_reps_ok]
    _b0a_e_badraw[3] = {**_b0a_e_badraw[3], "raw_unit_measurements": {**_b0a_e_badraw[3]["raw_unit_measurements"], "beta_cytokine_protection_pct": _mk_b0a_raw_ratio([30.0]*6, _b0a_e_badraw[3]["matched_vehicle_record_id"], 100.0, is_inhib=True)}}
    _b0a_an_ebr = _sign_receipt({**b0a_an_ok, "raw_efficacy_replicates_sha256": sha256_bytes(canonical_json_bytes(_b0a_e_badraw))})
    chk(
        "HOLD_GATE_B0A_MISSING_MATCHED_VEHICLE_RAW_DATA" in evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": _sign_receipt({**b0a_ok, "efficacy_replicates_by_conc": _b0a_e_noraw, "b0a_analysis_receipt": _b0a_an_enr})})["holds"]
        and "FAIL_GATE_B0A_EFFICACY_NORMALIZED_PCT_MISMATCH_VS_MATCHED_VEHICLE:3:beta_cytokine_protection_pct" in evaluate_gate41_deucravacitinib_tyk2({"phase": "ROUTE_FREE_B0A", "b0a_evidence": _sign_receipt({**b0a_ok, "efficacy_replicates_by_conc": _b0a_e_badraw, "b0a_analysis_receipt": _b0a_an_ebr})})["failures"],
        "G41_b0a_efficacy_raw_matched_vehicle_missing_holds_and_mismatch_fails",
    )
    # 7. B-0a-exact missing raw_unit_measurements HOLDS; tampered technical vehicle denominator FAILS!
    _b0a_ex_noraw = _sign_receipt({**b0a_ex_y, "cassette_retention_replicates_by_conc": [{k: v for k, v in r.items() if k != "raw_unit_measurements"} for r in b0a_ex_y["cassette_retention_replicates_by_conc"]]})
    _ex1_br = b0a_ex_y["cassette_retention_replicates_by_conc"][1]
    _b0a_ex_badraw = _sign_receipt({
        **b0a_ex_y,
        "cassette_retention_replicates_by_conc": [
            b0a_ex_y["cassette_retention_replicates_by_conc"][0],
            {**_ex1_br, "raw_unit_measurements": {**_ex1_br["raw_unit_measurements"], "treated_by_unit_tech": [[500.0, 500.0, 500.0]] + _ex1_br["raw_unit_measurements"]["treated_by_unit_tech"][1:]}},
            *b0a_ex_y["cassette_retention_replicates_by_conc"][2:],
        ],
    })
    chk(
        "HOLD_GATE_B0A_EXACT_MISSING_MATCHED_VEHICLE_RAW_DATA" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b0a_exact_evidence": _b0a_ex_noraw})["holds"]
        and "FAIL_GATE_B0A_EXACT_NORMALIZED_PCT_MISMATCH_VS_MATCHED_VEHICLE:1:B0AEX-BLK-1" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b0a_exact_evidence": _b0a_ex_badraw})["failures"],
        "G41_b0a_exact_raw_matched_vehicle_missing_holds_and_mismatch_fails",
    )
    # 8. B-2b-exact non-numeric c_safe_max_operative_l95_free_nM returns structured FAIL without raising!
    _r_b2be_nonnum = evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b2b_exact_evidence": _sign_receipt({**b2be_y, "c_safe_max_operative_l95_free_nM": "invalid_ceiling"})})
    chk(
        _r_b2be_nonnum["verdict"] == "FAIL" and "FAIL_GATE_B2B_EXACT_MISSING_OPERATIVE_CSAFE" in _r_b2be_nonnum["failures"],
        "G41_b2b_exact_nonnumeric_operative_csafe_returns_structured_fail",
    )


    # --- GATE-41 (IIP-0063) Mixed-Source B-1 (100% Human Serum) + B-2 (Whole Blood) Analytical Ledger Reconciliation (4 tests) ---
    # Build faithful two-matrix analytical package: B-1 rows in human_serum_100pct + B-2 rows (2 h Chandler loop) in whole_blood!
    _mx_base_b = _mk_r8_b2b_replicates()
    _mx_base_e = _mk_r8_b2b_replicates(evidence_scope="exact_product")
    _mx_tps = [dict(r) for r in _mx_base_b["timepoint_replicate_records"]]
    # Scale whole-blood 2h total parent by (0.14 / 0.11) so free unbound concentration stays ~15.4 nM on the common unbound exposure basis!
    _wb_lp_2h = [round(140.0 * (1.0 + d), 4) for d in (-0.012, -0.007, -0.002, 0.002, 0.007, 0.012)]
    _mx_tps[0] = {
        **_mx_tps[0],
        "local_assay_matrix": "whole_blood",
        "recirc_assay_matrix": "whole_blood",
        "local_parent_total_replicates_nM": _wb_lp_2h,
        "local_parent_blq_flags": [v < 0.05 for v in _wb_lp_2h],
    }
    for _j_mx in range(1, len(_mx_tps)):
        _mx_tps[_j_mx] = {**_mx_tps[_j_mx], "local_assay_matrix": "human_serum_100pct", "recirc_assay_matrix": "human_serum_100pct"}
    _b1_mx_lg = _mk_b12_ledger("B-1", tps=_mx_tps, assay_matrix="human_serum_100pct", recirc_assay_matrix="human_serum_100pct")
    _b2_mx_lg = _mk_b12_ledger("B-2", tps=_mx_tps, assay_matrix="whole_blood", recirc_assay_matrix="whole_blood")
    _b1_mx = _sign_receipt({**b1_y, "analytical_sample_ledger": _b1_mx_lg})
    _b2_mx = _sign_receipt({**b2_y, "parent_receipt_sha256": _b1_mx["receipt_sha256"], "analytical_sample_ledger": _b2_mx_lg})
    _add_wb_cal = {
        "whole_blood": {
            "fu_parent_replicates": [0.108, 0.109, 0.110, 0.110, 0.111, 0.112],
            "fu_bmt_replicates": [0.118, 0.119, 0.120, 0.120, 0.121, 0.122],
            "alpha_fu_parent": 0.006,
            "alpha_fu_bmt": 0.006,
        },
    }
    _mx_kbp_b = {
        "kbp_assay_method_id": "BENCH-MIXED-WHOLE-BLOOD-KBP-V1",
        "blood_to_plasma_ratio_parent_replicates": [1.24, 1.25, 1.26, 1.25, 1.24, 1.26],
        "blood_to_plasma_ratio_bmt_replicates": [1.20, 1.22, 1.21, 1.23, 1.22, 1.24],
        "alpha_kbp_parent": 0.004,
        "alpha_kbp_bmt": 0.004,
    }
    _mx_kbp = {**_mx_kbp_b, "calibration_sha256": sha256_bytes(canonical_json_bytes(_mx_kbp_b))}
    _mx_env_b_raw = {k: v for k, v in _mx_base_b["intersample_pk_envelope"].items() if k != "envelope_receipt_sha256"}
    _mx_env_b_raw["k_rise_bmt_max_per_h"] = 0.005
    _mx_env_b = {**_mx_env_b_raw, "envelope_receipt_sha256": sha256_bytes(canonical_json_bytes(_mx_env_b_raw))}
    _mx_env_e_raw = {k: v for k, v in _mx_base_e["intersample_pk_envelope"].items() if k != "envelope_receipt_sha256"}
    _mx_env_e_raw["k_rise_bmt_max_per_h"] = 0.005
    _mx_env_e = {**_mx_env_e_raw, "envelope_receipt_sha256": sha256_bytes(canonical_json_bytes(_mx_env_e_raw))}
    # Unified global familywise alpha: 0.018 (conc) + 0.006 (serum fu_p) + 0.006 (serum fu_b) + 0.006 (wb fu_p) + 0.006 (wb fu_b) + 0.008 (kbp) = 0.050 <= 0.05!
    _b2bb_mx = _sign_receipt({
        **b2bb_y,
        "parent_receipt_sha256": _b2_mx["receipt_sha256"],
        "prerequisite_receipt_sha256s": {"B-1": _b1_mx["receipt_sha256"], "B-2": _b2_mx["receipt_sha256"]},
        "alpha_conc": 0.018, "alpha_fu_parent": 0.006, "alpha_fu_bmt": 0.006,
        "common_exposure_basis": "UNBOUND_FREE_CONC_NM_AND_PLASMA_EQUIV_SYSTEMIC_NM",
        "additional_matrix_calibrations": _add_wb_cal,
        "systemic_kbp_calibration": _mx_kbp,
        "intersample_pk_envelope": _mx_env_b,
        "timepoint_replicate_records": _mx_tps,
    })
    _b0a_ex_mx = _sign_receipt({**b0a_ex_y, "prerequisite_receipt_sha256s": {"B-0a": b0a_ok["receipt_sha256"], "B-2b-bench": _b2bb_mx["receipt_sha256"], "BANK_MATERIALIZATION": mat_y40["receipt_sha256"]}})
    _b2be_mx = _sign_receipt({
        **b2be_y,
        "parent_receipt_sha256": _b2bb_mx["receipt_sha256"],
        "prerequisite_receipt_sha256s": {"BANK_MATERIALIZATION": mat_y40["receipt_sha256"], "B-0a-exact": _b0a_ex_mx["receipt_sha256"], "B-1": _b1_mx["receipt_sha256"], "B-2": _b2_mx["receipt_sha256"]},
        "alpha_conc": 0.018, "alpha_fu_parent": 0.006, "alpha_fu_bmt": 0.006,
        "common_exposure_basis": "UNBOUND_FREE_CONC_NM_AND_PLASMA_EQUIV_SYSTEMIC_NM",
        "additional_matrix_calibrations": _add_wb_cal,
        "systemic_kbp_calibration": _mx_kbp,
        "timepoint_replicate_records": _mx_tps,
        "intersample_pk_envelope": _mx_env_e,
    })
    _b3_mx = _sign_receipt({**b3_y, "parent_receipt_sha256": _b2be_mx["receipt_sha256"], "b3_cytokine_challenge_shield_panel": _mk_b3_challenge_panel(_b2be_mx["receipt_sha256"])})
    _b4_mx = _sign_receipt({**b4_y, "parent_receipt_sha256": _b3_mx["receipt_sha256"]})
    # 1. Positive acceptance test: faithful mixed-source B-1 (serum) + B-2 (whole_blood) PASSES BOTH B-2b-bench AND full exact-product!
    _r_mx_bench = evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b1_evidence": _b1_mx, "b2_evidence": _b2_mx, "b2b_bench_evidence": _b2bb_mx})
    _r_mx_exact = evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b1_evidence": _b1_mx, "b2_evidence": _b2_mx, "b2b_bench_evidence": _b2bb_mx, "b0a_exact_evidence": _b0a_ex_mx, "b2b_exact_evidence": _b2be_mx, "b3_evidence": _b3_mx, "b4_evidence": _b4_mx})
    chk(
        _r_mx_bench["verdict"] == "PASS_BENCH_ONLY_UNEDITED_PRE_MATERIALIZATION"
        and _r_mx_exact["verdict"] == OFFLINE_VERDICT_PRIMARY,
        "G41_b2b_mixed_b1_serum_and_b2_whole_blood_passes_bench_and_exact",
    )
    # 2. Mixed-source B-2b omitting additional_matrix_calibrations for whole_blood HOLDS!
    _b2bb_mx_nocal = _sign_receipt({k: v for k, v in _b2bb_mx.items() if k not in ("additional_matrix_calibrations", "receipt_sha256")})
    chk(
        "HOLD_GATE_B2B_BENCH_MISSING_PER_MATRIX_FU_CALIBRATION:whole_blood" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b1_evidence": _b1_mx, "b2_evidence": _b2_mx, "b2b_bench_evidence": _b2bb_mx_nocal})["holds"],
        "G41_b2b_mixed_matrix_missing_extra_fu_calibration_holds",
    )
    # 3. Mixed-source B-2b whose unified global alpha (incl. extra matrix fu + kbp) exceeds 0.05 FAILS!
    _b2bb_mx_overa = _sign_receipt({**_b2bb_mx, "alpha_conc": 0.025})  # total = 0.057 > 0.05!
    chk(
        "FAIL_GATE_B2B_BENCH_GLOBAL_ALPHA_EXCEEDS_0P05" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b1_evidence": _b1_mx, "b2_evidence": _b2_mx, "b2b_bench_evidence": _b2bb_mx_overa})["failures"],
        "G41_b2b_mixed_matrix_global_alpha_over_0p05_fails",
    )
    # 4. Mixed-source B-2b mislabeling the whole-blood B-2 row as human_serum_100pct still HOLDS for ledger mismatch!
    _mx_tps_mislab = [{**_mx_tps[0], "local_assay_matrix": "human_serum_100pct", "recirc_assay_matrix": "human_serum_100pct"}, *_mx_tps[1:]]
    _b2bb_mx_mislab = _sign_receipt({**_b2bb_mx, "timepoint_replicate_records": _mx_tps_mislab})
    chk(
        "HOLD_GATE_B2B_BENCH_UPSTREAM_SAMPLE_LEDGER_INCOMPLETE_OR_DUPLICATE" in evaluate_gate41_deucravacitinib_tyk2({**g41_bench, "b1_evidence": _b1_mx, "b2_evidence": _b2_mx, "b2b_bench_evidence": _b2bb_mx_mislab})["holds"],
        "G41_b2b_mixed_matrix_mislabeled_row_holds_ledger_mismatch",
    )


    # --- GATE-40 (IIP-0062) A-2 Vascular 14-Day Timing/Specimen Provenance + A-0b/A-1 Time-Resolved pH (4 tests) ---
    # 1. A-2 vascular panel with short 7-day exposure FAILS; missing timing/specimen HOLDS!
    _a2_v_short_b = {k: v for k, v in a2_y["a2_vascular_raw_measurements"].items() if k != "vascular_assay_receipt_sha256"}
    _a2_v_short_b["assessed_at_utc"] = "2026-10-13T12:00:00Z"  # only 7 days (< 14 days)!
    _a2_v_short = {**_a2_v_short_b, "vascular_assay_receipt_sha256": sha256_bytes(canonical_json_bytes(_a2_v_short_b))}
    _a2_v_notime = {k: v for k, v in a2_y["a2_vascular_raw_measurements"].items() if k not in ("exposure_started_at_utc", "assessed_at_utc")}
    chk(
        "FAIL_GATE_A2_VASCULAR_EXPOSURE_DURATION_LT_14_DAYS" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "a2_vascular_raw_measurements": _a2_v_short})})["failures"]
        and "HOLD_GATE_A2_VASCULAR_MISSING_EXPOSURE_TIMING_OR_SPECIMEN" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "a2_vascular_raw_measurements": _a2_v_notime})})["holds"],
        "G40_a2_vascular_7d_short_exposure_fails_and_missing_timing_holds",
    )
    # 2. A-2 vascular panel referencing an unrelated specimen_id FAILS!
    _a2_v_wrongsp_b = {k: v for k, v in a2_y["a2_vascular_raw_measurements"].items() if k != "vascular_assay_receipt_sha256"}
    _a2_v_wrongsp_b["specimen_id"] = "SPEC-UNRELATED-999"
    _a2_v_wrongsp = {**_a2_v_wrongsp_b, "vascular_assay_receipt_sha256": sha256_bytes(canonical_json_bytes(_a2_v_wrongsp_b))}
    chk(
        "FAIL_GATE_A2_VASCULAR_RAW_MEASUREMENTS_OR_VEHICLE_UNBOUND" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a2_evidence": _sign_receipt({**a2_y, "a2_vascular_raw_measurements": _a2_v_wrongsp})})["failures"],
        "G40_a2_vascular_wrong_specimen_id_fails",
    )
    # 3. A-0b missing 14-day time-resolved pH HOLDS; A-1 missing 35-day time-resolved pH HOLDS!
    chk(
        "HOLD_GATE_A0B_MISSING_14D_TIME_RESOLVED_PH" in evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _sign_receipt({k: v for k, v in a0b_y.items() if k not in ("a0b_local_ph_timepoints", "receipt_sha256")})})["holds"]
        and "HOLD_GATE_A1_MISSING_35D_TIME_RESOLVED_PH" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({k: v for k, v in a1_y.items() if k not in ("a1_local_ph_timepoints", "receipt_sha256")})})["holds"],
        "G40_a0b_and_a1_missing_time_resolved_ph_holds",
    )
    # 4. A-1 Day-28 local pH excursion (7.18 < 7.25) or truncated Day-14-only pH trace FAILS!
    _a1_ph_low = [dict(r) for r in a1_y["a1_local_ph_timepoints"]]
    _a1_ph_low[4] = {**_a1_ph_low[4], "ph_min": 7.18}
    _a1_ph_trunc = a1_y["a1_local_ph_timepoints"][:3]
    chk(
        "FAIL_GATE_A1_LOCAL_PH_OUTSIDE_7P25_7P45_OR_INCOMPLETE_35D" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "a1_local_ph_timepoints": _a1_ph_low})})["failures"]
        and "FAIL_GATE_A1_LOCAL_PH_OUTSIDE_7P25_7P45_OR_INCOMPLETE_35D" in evaluate_gate40_pirfenidone_h4({**g40_ok, "a1_evidence": _sign_receipt({**a1_y, "a1_local_ph_timepoints": _a1_ph_trunc})})["failures"],
        "G40_a1_day28_ph_excursion_or_truncated_trace_fails",
    )

    # --- GATE-41 (IIP-0063) B-3 Per-Challenge Matched-Control Block Shield Panel & Exposure Linkage (4 tests) ---
    # 5. B-3 missing b3_cytokine_challenge_shield_panel HOLDS; omitting IFNG_PLUS_IL1B HOLDS!
    _b3_cp_inc_b = {k: v for k, v in b3_cpanel_ok.items() if k != "panel_receipt_sha256"}
    _b3_cp_inc_b["challenges"] = {k: v for k, v in _b3_cp_inc_b["challenges"].items() if k != "IFNG_PLUS_IL1B"}
    _b3_cp_inc = {**_b3_cp_inc_b, "panel_receipt_sha256": sha256_bytes(canonical_json_bytes(_b3_cp_inc_b))}
    chk(
        "HOLD_GATE_B3_MISSING_CYTOKINE_CHALLENGE_SHIELD_PANEL" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b3_evidence": _sign_receipt({k: v for k, v in b3_y.items() if k not in ("b3_cytokine_challenge_shield_panel", "receipt_sha256")})})["holds"]
        and "HOLD_GATE_B3_INCOMPLETE_REQUIRED_CYTOKINE_CHALLENGES" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b3_evidence": _sign_receipt({**b3_y, "b3_cytokine_challenge_shield_panel": _b3_cp_inc})})["holds"],
        "G41_b3_missing_or_incomplete_cytokine_challenge_panel_holds",
    )
    # 6. B-3 shield component dropping below 85% in ONE required challenge (PDL1_SYN6 = 78% under IFNG_PLUS_IL1B) FAILS even if summary claims >= 90%!
    _b3_cp_pd_fail = _mk_b3_challenge_panel(b2be_y["receipt_sha256"], comp_overrides={"IFNG_PLUS_IL1B": {"PDL1_SYN6": 78.0}})
    chk(
        "FAIL_GATE_B3_CHALLENGE_SHIELD_COMPONENT_BELOW_85PCT:IFNG_PLUS_IL1B:PDL1_SYN6" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b3_evidence": _sign_receipt({**b3_y, "b3_cytokine_challenge_shield_panel": _b3_cp_pd_fail})})["failures"],
        "G41_b3_single_challenge_pdl1_below_85pct_fails",
    )
    # 7. B-3 cytokine panel tested at sub-therapeutic exposure (2.0 nM < B-2b-exact parent floor 7.0 nM) FAILS exposure link!
    _b3_cp_subexp = _mk_b3_challenge_panel(b2be_y["receipt_sha256"], free_p_nM=2.0)
    chk(
        "FAIL_GATE_B3_CYTOKINE_CHALLENGE_EXPOSURE_UNLINKED_TO_B2B_EXACT" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b3_evidence": _sign_receipt({**b3_y, "b3_cytokine_challenge_shield_panel": _b3_cp_subexp})})["failures"],
        "G41_b3_challenge_panel_subtherapeutic_exposure_fails",
    )
    # 8. B-3 IL-10 washout assay missing measured treatment exposure HOLDS; sub-therapeutic exposure (1.5 nM) FAILS!
    _il10_noexp = {k: v for k, v in b3_il10_ok.items() if k != "exposure_measured_free_parent_nM"}
    _il10_subexp = _mk_b3_il10_assay(exposure_measured_free_parent_nM=1.5)
    chk(
        "HOLD_GATE_B3_IL10_WASHOUT_MISSING_MEASURED_EXPOSURE" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b3_evidence": _sign_receipt({**b3_y, "il10_washout_recovery_assay": _il10_noexp})})["holds"]
        and "FAIL_GATE_B3_IL10_WASHOUT_EXPOSURE_UNLINKED_TO_B2B_EXACT" in evaluate_gate41_deucravacitinib_tyk2({**g41_ok, "b3_evidence": _sign_receipt({**b3_y, "il10_washout_recovery_assay": _il10_subexp})})["failures"],
        "G41_b3_il10_washout_exposure_missing_holds_and_subtherapeutic_fails",
    )


    # --- GATE-42 (IIP-0064) C-3-GSIS Readout-2 Specimen/Trace Linkage, C-1 KD Provenance, C-2 Survival Proteins, Nested JSON Safety & Pure-HOLD Mock Control (8 tests) ---
    # 1. C-3-GSIS Readout-2 omitting readout2_specimen_provenance returns pure HOLD with zero failures!
    _r2_no_sp = {k: v for k, v in c3_gsis_y["readout2_evidence"].items() if k != "readout2_specimen_provenance"}
    _res_r2_nosp = evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c3_gsis_evidence": _sign_receipt({**c3_gsis_y, "readout2_evidence": _r2_no_sp})})
    chk(
        _res_r2_nosp["verdict"] == "HOLD"
        and _res_r2_nosp["failures"] == []
        and "HOLD_GATE_C3_GSIS_READOUT2_MISSING_INTERVENTION_SPECIMEN_LINKAGE" in _res_r2_nosp["holds"],
        "G42_c3gsis_missing_readout2_specimen_linkage_pure_hold",
    )
    # 2. C-3-GSIS Readout-2 with wrong same-lot specimen_id, unregistered trace aliquot, OR collection time outside engagement window ALL FAIL!
    _r2_wrong_sp = _mk_r8_readout2(
        matched_comparator_id=nt_y, block_prefix="C3G", lot_id=ly,
        stage7_start_utc="2026-09-12T00:00:00Z", sort_reaggregation_utc="2026-09-22T00:00:00Z", assay_harvest_utc="2026-10-01T00:00:00Z",
        specimen_id=f"SPEC-OTHER-SAME-LOT-{ly}", intervention_cohort_id=c1_cohort_y, candidate_gene=tg_dual,
    )
    _r2_bad_alq_p = {k: v for k, v in c3_gsis_y["readout2_evidence"]["readout2_specimen_provenance"].items() if k != "provenance_sha256"}
    _r2_bad_alq_p["trace_aliquot_links"] = [{**_r2_bad_alq_p["trace_aliquot_links"][0], "aliquot_id": "UNREGISTERED-ALQ-999"}, *_r2_bad_alq_p["trace_aliquot_links"][1:]]
    _r2_bad_alq = {**c3_gsis_y["readout2_evidence"], "readout2_specimen_provenance": {**_r2_bad_alq_p, "provenance_sha256": sha256_bytes(canonical_json_bytes(_r2_bad_alq_p))}}
    _r2_out_win = _mk_r8_readout2(
        matched_comparator_id=nt_y, block_prefix="C3G", lot_id=ly,
        stage7_start_utc="2026-09-12T00:00:00Z", sort_reaggregation_utc="2026-09-22T00:00:00Z", assay_harvest_utc="2026-10-01T00:00:00Z",
        specimen_id=f"SPEC-C-3-GSIS-{ly}", intervention_cohort_id=c1_cohort_y, candidate_gene=tg_dual,
        trace_collected_at_utc="2026-10-02T10:00:00Z",  # after engagement window end 2026-10-01T18:00:00Z!
    )
    chk(
        "FAIL_GATE_C3_GSIS_READOUT2_INTERVENTION_SPECIMEN_OR_TRACE_LINK_MISMATCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c3_gsis_evidence": _sign_receipt({**c3_gsis_y, "readout2_evidence": _r2_wrong_sp})})["failures"]
        and "FAIL_GATE_C3_GSIS_READOUT2_INTERVENTION_SPECIMEN_OR_TRACE_LINK_MISMATCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c3_gsis_evidence": _sign_receipt({**c3_gsis_y, "readout2_evidence": _r2_bad_alq})})["failures"]
        and "FAIL_GATE_C3_GSIS_READOUT2_INTERVENTION_SPECIMEN_OR_TRACE_LINK_MISMATCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c3_gsis_evidence": _sign_receipt({**c3_gsis_y, "readout2_evidence": _r2_out_win})})["failures"],
        "G42_c3gsis_readout2_wrong_specimen_unregistered_aliquot_or_out_of_window_fails",
    )
    # 3. C-3-GSIS Readout-2 referencing wrong candidate_gene (same lot & same specimen) FAILS!
    _r2_wrong_cg = _mk_r8_readout2(
        matched_comparator_id=nt_y, block_prefix="C3G", lot_id=ly,
        stage7_start_utc="2026-09-12T00:00:00Z", sort_reaggregation_utc="2026-09-22T00:00:00Z", assay_harvest_utc="2026-10-01T00:00:00Z",
        specimen_id=f"SPEC-C-3-GSIS-{ly}", intervention_cohort_id=c1_cohort_y, candidate_gene="BCL2L11",
    )
    chk(
        "FAIL_GATE_C3_GSIS_READOUT2_INTERVENTION_SPECIMEN_OR_TRACE_LINK_MISMATCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c3_gsis_evidence": _sign_receipt({**c3_gsis_y, "readout2_evidence": _r2_wrong_cg})})["failures"],
        "G42_c3gsis_readout2_wrong_candidate_gene_fails",
    )
    # 4. C-1 omitting molecular_kd_provenance (re-chained) returns pure HOLD; tampered assay_record_id FAILS!
    def _rechain_g42_from_c1(c1_new: Mapping[str, Any], *, c2_override: Optional[Mapping[str, Any]] = None) -> dict[str, Any]:
        c2_n = _sign_receipt({**(c2_override if c2_override is not None else c2_y), "parent_receipt_sha256": c1_new["receipt_sha256"]})
        sw_n = _mk_r8_switch(py, by, ly, ry, mat_yc, "2026-09-28T14:00:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": c2_n["receipt_sha256"]}, transient_engagement=_mk_c_eng(c1_cohort_y, "2026-09-28T13:00:00Z", stage_name="NATIVE_SAFETY_SWITCH", lot_s_id=ly, win_start="2026-09-25T12:00:00Z", win_end="2026-09-28T13:15:00Z", mode="VALIDATED_LONGITUDINAL_KINETICS"))
        g0v_n = _mk_r8_gate0v(py, by, ly, ry, mat_yc, "2026-09-28T14:30:00Z", candidate_gene=tg_dual, comparator_nt_lot_id=nt_y, prereq_receipts={"C-2": c2_n["receipt_sha256"]}, transient_engagement=_mk_c_eng(c1_cohort_y, "2026-09-28T13:15:00Z", stage_name="GATE-0V-KILL", lot_s_id=ly, win_start="2026-09-25T12:00:00Z", win_end="2026-09-28T13:30:00Z", mode="VALIDATED_LONGITUDINAL_KINETICS"))
        pr3_n = {**pr_c1_yc, "NATIVE_SAFETY_SWITCH": sw_n["receipt_sha256"], "GATE-0V-KILL": g0v_n["receipt_sha256"]}
        c3n_n = _sign_receipt({**c3_nk_y, "parent_receipt_sha256": c2_n["receipt_sha256"], "prerequisite_receipt_sha256s": pr3_n})
        c3g_n = _sign_receipt({**c3_gsis_y, "parent_receipt_sha256": c3n_n["receipt_sha256"], "prerequisite_receipt_sha256s": pr3_n})
        return {**g42_ok, "c1_evidence": c1_new, "c2_evidence": c2_n, "native_switch_evidence": sw_n, "gate0v_evidence": g0v_n, "c3_nk_evidence": c3n_n, "c3_gsis_evidence": c3g_n}

    _c1_no_kdp = _sign_receipt({**c1_y, "c1_normoxia": {k: v for k, v in c1_norm_6.items() if k != "molecular_kd_provenance"}})
    _res_c1_nokdp = evaluate_gate42_gy032_channel_c_screen(_rechain_g42_from_c1(_c1_no_kdp))
    _kdp_bad_b = {k: v for k, v in c1_norm_6["molecular_kd_provenance"].items() if k != "producer_record_sha256"}
    _kdp_bad_b["mrna_assay_record_id"] = "OTHER-QPCR-999"
    _c1_bad_kdp = _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "molecular_kd_provenance": {**_kdp_bad_b, "producer_record_sha256": sha256_bytes(canonical_json_bytes(_kdp_bad_b))}}})
    chk(
        _res_c1_nokdp["verdict"] == "HOLD" and _res_c1_nokdp["failures"] == []
        and "HOLD_GATE_C1_NORMOXIA_MISSING_MOLECULAR_KD_PROVENANCE" in _res_c1_nokdp["holds"]
        and "FAIL_GATE_C1_NORMOXIA_MOLECULAR_KD_PROVENANCE_MISMATCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _c1_bad_kdp})["failures"],
        "G42_c1_missing_molecular_kd_provenance_pure_hold_and_mismatch_fails",
    )
    # 5. C-2 omitting resting_survival_protein_panel (re-chained) returns pure HOLD with zero failures!
    _c2_no_sp = {k: v for k, v in c2_y.items() if k not in ("resting_survival_protein_panel", "receipt_sha256")}
    _res_c2_nosp = evaluate_gate42_gy032_channel_c_screen(_rechain_g42_from_c1(c1_y, c2_override=_c2_no_sp))
    chk(
        _res_c2_nosp["verdict"] == "HOLD" and _res_c2_nosp["failures"] == []
        and "HOLD_GATE_C2_MISSING_RESTING_SURVIVAL_PROTEIN_PANEL" in _res_c2_nosp["holds"],
        "G42_c2_missing_resting_survival_protein_panel_pure_hold",
    )
    # 6. C-2 resting survival proteins (BCL2L1 / MCL1 / CD59) < 80% FAIL, and specimen mismatch FAILS!
    _sp_low_bcl = _mk_c2_surv_panel(spec_v=f"SPEC-C-2-{ly}", lot_v=ly, nt_v=nt_y, bcl2l1=74.0)
    _sp_low_cd59 = _mk_c2_surv_panel(spec_v=f"SPEC-C-2-{ly}", lot_v=ly, nt_v=nt_y, cd59=76.5)
    _sp_bad_spec = _mk_c2_surv_panel(spec_v="SPEC-WRONG-C2-999", lot_v=ly, nt_v=nt_y)
    chk(
        "FAIL_GATE_C2_RESTING_SURVIVAL_PROTEINS_BELOW_80PCT" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "resting_survival_protein_panel": _sp_low_bcl})})["failures"]
        and "FAIL_GATE_C2_RESTING_SURVIVAL_PROTEINS_BELOW_80PCT" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "resting_survival_protein_panel": _sp_low_cd59})})["failures"]
        and "FAIL_GATE_C2_RESTING_SURVIVAL_PROTEIN_PANEL_MISMATCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "resting_survival_protein_panel": _sp_bad_spec})})["failures"],
        "G42_c2_resting_survival_proteins_below_80pct_and_specimen_mismatch_fail",
    )
    # 7. Malformed nested JSON container/element types in GATE-42 return structured FAIL without raising TypeError!
    _g36_unhash = _sign_receipt({**g36_y, "active_drug_free_modules": [{"bad": 1}]})
    _att_bad_o2 = _sign_receipt({**att_y, "reference_comparator_measurements": {**att_y["reference_comparator_measurements"], "PARENTAL_UNEDITED": {"normoxia": 123, "hypoxia_15mmhg": []}}})
    _prereg_bad_ord = _sign_receipt({**c1_prereg_y, "block_to_batch_allocations": {**c1_prereg_y["block_to_batch_allocations"], "normoxia": [{**c1_prereg_y["block_to_batch_allocations"]["normoxia"][0], "randomized_arm_order": [["unhashable"], "BCL2L11", "PMAIP1", "PMAIP1+BCL2L11", "BBC3", "NT_CTRL"]}, *c1_prereg_y["block_to_batch_allocations"]["normoxia"][1:]]}})
    chk(
        "FAIL_FOUNDRY_V2_GATE36_INVALID_DRUG_FREE_MODULE_PRODUCERS" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "foundry_v2_gate36_evidence": _g36_unhash})["failures"]
        and "FAIL_IIP0049_MALFORMED_COMPARATOR_MEASUREMENTS:PARENTAL_UNEDITED" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "iip0049_foundry_attribution_evidence": _att_bad_o2})["failures"]
        and "FAIL_GATE_C1_PREREG_INVALID_BATCH_OR_ARM_ORDER:normoxia" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_preregistered_plan_receipt": _prereg_bad_ord})["failures"],
        "G42_malformed_nested_json_containers_return_structured_fail_no_typeerror",
    )
    # 8. Absent C-1 mock_transfection_control_by_block (omitted key OR empty list, re-chained) returns single-disposition pure HOLD (failures == [])!
    _c1_nomock_omit = _sign_receipt({**c1_y, "c1_normoxia": {k: v for k, v in c1_norm_6.items() if k != "mock_transfection_control_by_block"}})
    _c1_nomock_empty = _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "mock_transfection_control_by_block": []}})
    _res_nm_o = evaluate_gate42_gy032_channel_c_screen(_rechain_g42_from_c1(_c1_nomock_omit))
    _res_nm_e = evaluate_gate42_gy032_channel_c_screen(_rechain_g42_from_c1(_c1_nomock_empty))
    chk(
        _res_nm_o["verdict"] == "HOLD" and _res_nm_o["failures"] == [] and _res_nm_o["holds"] == ["HOLD_GATE_C1_NORMOXIA_MISSING_MOCK_TRANSFECTION_CONTROL"]
        and _res_nm_e["verdict"] == "HOLD" and _res_nm_e["failures"] == [] and _res_nm_e["holds"] == ["HOLD_GATE_C1_NORMOXIA_MISSING_MOCK_TRANSFECTION_CONTROL"],
        "G42_c1_absent_mock_control_rechained_pure_hold_zero_failures",
    )


    # --- GATE-40 (IIP-0062) Matrix- & Duration-Specific f_u Propagation in A-0a & A-0b (4 tests) ---
    # 1. A-0a efficacy-culture viability limits at 110 uM with wider efficacy f_u uncertainty (~0.75) vs tight vascular f_u (~0.97):
    #    under vascular-only factor margin would exceed 1.5x, whereas true efficacy-culture-adjusted ceiling (~82.5 uM) drops margin < 1.5x -> FAIL!
    _a0a_eff_lim_reps = [dict(r) for r in a0a_reps_ok]
    for _ei_r in (4, 5, 6):  # at 150, 260, 420 uM efficacy-culture viability drops to 82% (< 90%), limiting max_qual_eff_viab_c to 110 uM (idx 3)!
        _a0a_eff_lim_reps[_ei_r] = {
            **_a0a_eff_lim_reps[_ei_r],
            "efficacy_treated_viable_cells_by_donor": [8200.0, 8250.0, 8150.0, 8220.0, 8180.0],
            "efficacy_culture_viability_7d_pct": [82.0, 82.5, 81.5, 82.2, 81.8],
        }
    _a0a_eff_lim_fit = _sign_receipt({**a0a_fit_ok, "cc10_free_7d_l95_uM": 110.0, "c_sprout_max_free_7d_l95_uM": 110.0, "raw_replicates_sha256": sha256_bytes(canonical_json_bytes(_a0a_eff_lim_reps))})
    _a0a_eff_wide_mfu = {
        "fibrosis_efficacy_assay": {
            **a0a_ok["a0a_matrix_fu_by_assay"]["fibrosis_efficacy_assay"],
            "dialysis_fu_replicates": [0.33, 0.375, 0.42, 0.465, 0.51],  # mean=0.42, l95~0.327 (factor ~0.779), u95~0.513 (factor ~1.221)
        },
        "vascular_viability_assay": a0a_ok["a0a_matrix_fu_by_assay"]["vascular_viability_assay"],  # tight ~0.980
    }
    _a0a_eff_lim_ev = _sign_receipt({
        **a0a_ok, "ic50_free_alpha_sma_uM": 52.0, "ic50_free_col1a1_uM": 58.0, "ic50_free_max_u95_uM": 64.0,
        "cc10_free_7d_l95_uM": 110.0, "c_sprout_max_free_7d_l95_uM": 110.0, "c_upper_provisional_7d_l95_uM": 110.0,
        "a0a_matrix_fu_by_assay": _a0a_eff_wide_mfu,
        "a0a_donor_replicates_by_conc": _a0a_eff_lim_reps,
        "a0a_fit_artifact_receipt": _sign_receipt({**_a0a_eff_lim_fit, "ic50_free_alpha_sma_uM": 52.0, "ic50_free_col1a1_uM": 58.0, "ic50_free_max_u95_uM": 64.0}),
    })
    _r_eff_lim = evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _a0a_eff_lim_ev})
    chk(
        "FAIL_GATE_A0A_FU_PROPAGATED_MARGIN_BELOW_1P5X" in _r_eff_lim["failures"]
        and _r_eff_lim["a0a_operative_limits_uM"]["c_up_7d_fu_adjusted_uM"] < 90.0,
        "G40_a0a_efficacy_culture_lower_fu_limits_safety_ceiling_and_fails_margin",
    )
    # 2. A-0a with a0a_limits_already_fu_adjusted=True overstating efficacy-culture-adjusted ceiling (claiming 102 uM vs ~85.7 uM) FAILS & clamps!
    _a0a_eff_adj_over = _sign_receipt({
        **_a0a_eff_lim_ev,
        "a0a_limits_already_fu_adjusted": True,
        "ic50_free_max_u95_uM": 80.0, "cc10_free_7d_l95_uM": 102.0, "c_sprout_max_free_7d_l95_uM": 102.0, "c_upper_provisional_7d_l95_uM": 102.0,
        "a0a_fit_artifact_receipt": _sign_receipt({**_a0a_eff_lim_fit, "ic50_free_alpha_sma_uM": 52.0, "ic50_free_col1a1_uM": 58.0, "ic50_free_max_u95_uM": 80.0, "cc10_free_7d_l95_uM": 102.0, "c_sprout_max_free_7d_l95_uM": 102.0}),
    })
    _r_eff_adj_over = evaluate_gate40_pirfenidone_h4({"phase": "ROUTE_FREE_A0A", "a0a_evidence": _a0a_eff_adj_over})
    chk(
        "FAIL_GATE_A0A_CLAIMED_FU_ADJUSTED_LIMITS_UNDERSTATED" in _r_eff_adj_over["failures"]
        and _r_eff_adj_over["a0a_operative_limits_uM"]["c_up_7d_fu_adjusted_uM"] < 90.0,
        "G40_a0a_already_fu_adjusted_overstating_efficacy_culture_ceiling_fails",
    )
    # 3. A-0b with tight 7-day f_u (~0.98) but wide 14-day vascular f_u (~0.70) and a0b_limits_already_fu_adjusted=True claiming 205 uM:
    #    FAILS claimed-ceiling overstatement AND fails peak (188 >= ~154 uM) AND clamps all4_ceiling_fu_adjusted_uM into A-1!
    _a0b_wide14_vasc_mfu = {
        "fibrosis_efficacy_assay": a0b_y["a0b_matrix_fu_by_assay"]["fibrosis_efficacy_assay"],
        "vascular_viability_assay": {
            **a0b_y["a0b_matrix_fu_by_assay"]["vascular_viability_assay"],
            "dialysis_fu_replicates": [0.37, 0.435, 0.50, 0.565, 0.63],  # mean=0.50, l95~0.370 (factor ~0.740 -> 220*0.740 ~162.8 uM < 188 peak!)
        },
    }
    _a0b_adj_omit14 = _sign_receipt({
        **a0b_y,
        "a0b_limits_already_fu_adjusted": True,
        "cc10_free_14d_l95_uM": 210.0, "c_sprout_max_free_14d_l95_uM": 205.0, "c_upper_14d_l95_uM": 205.0,
        "a0b_matrix_fu_by_assay": _a0b_wide14_vasc_mfu,
        "a0b_fit_artifact_receipt": _sign_receipt({**a0b_fit_ok, "cc10_free_14d_l95_uM": 210.0, "c_sprout_max_free_14d_l95_uM": 205.0}),
    })
    _a1b_omit14 = _sign_receipt({**a1b_y, "parent_receipt_sha256": _a0b_adj_omit14["receipt_sha256"]})
    _r_omit14 = evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _a0b_adj_omit14, "a1_bench_evidence": _a1b_omit14})
    chk(
        "FAIL_GATE_A0B_CLAIMED_FU_ADJUSTED_CEILING_OVERSTATED" in _r_omit14["failures"]
        and "FAIL_GATE_A0B_PEAK_FREE_NOT_BELOW_ALL4_CEILINGS" in _r_omit14["failures"]
        and "FAIL_GATE_A1_BENCH_DAY1_INTACT_PARENT_EXCEEDS_CEILING" in _r_omit14["failures"]
        and _r_omit14["a0a_operative_limits_uM"]["all4_ceiling_fu_adjusted_uM"] < 170.0,
        "G40_a0b_already_fu_adjusted_omitting_lower_14d_vasc_fu_fails_and_clamps_a1",
    )
    # 4. A-0b with tight 14-day vascular f_u (~0.98) but wide 14-day efficacy-culture f_u (~0.70):
    #    recomputed 14-day efficacy-culture ceiling (240*0.70 ~168 uM < 188 peak) clamps all4_ceiling and FAILS peak!
    _a0b_wide14_eff_mfu = {
        "fibrosis_efficacy_assay": {
            **a0b_y["a0b_matrix_fu_by_assay"]["fibrosis_efficacy_assay"],
            "dialysis_fu_replicates": [0.30, 0.36, 0.42, 0.48, 0.54],  # mean=0.42, l95~0.300 (factor ~0.714 -> 240*0.714 ~171.3 uM < 188 peak!)
        },
        "vascular_viability_assay": a0b_y["a0b_matrix_fu_by_assay"]["vascular_viability_assay"],
    }
    _a0b_eff14_lo = _sign_receipt({**a0b_y, "a0b_matrix_fu_by_assay": _a0b_wide14_eff_mfu})
    _r_eff14_lo = evaluate_gate40_pirfenidone_h4({**g40_bench, "a0b_evidence": _a0b_eff14_lo, "a1_bench_evidence": _sign_receipt({**a1b_y, "parent_receipt_sha256": _a0b_eff14_lo["receipt_sha256"]})})
    chk(
        "FAIL_GATE_A0B_PEAK_FREE_NOT_BELOW_ALL4_CEILINGS" in _r_eff14_lo["failures"]
        and "FAIL_GATE_A1_BENCH_DAY1_INTACT_PARENT_EXCEEDS_CEILING" in _r_eff14_lo["failures"]
        and _r_eff14_lo["a0a_operative_limits_uM"]["all4_ceiling_fu_adjusted_uM"] < 180.0,
        "G40_a0b_lower_14d_efficacy_culture_fu_clamps_all4_ceiling_and_fails_peak",
    )


    # --- GATE-42 (IIP-0064) Acquired Engagement Interval Trace Bounds, Dual-Arm 4-Observation KD Provenance, & C-2 Soluble IAPP Bound (4 tests) ---
    # 1. C-3-GSIS Readout-2 trace collected AFTER end_measured_at_utc (17:00Z > 16:00Z) even while inside declared assay_window_end_utc (18:00Z),
    #    OR before start_measured_at_utc (14:15Z < 14:30Z), FAILS!
    _r2_after_meas = _mk_r8_readout2(
        matched_comparator_id=nt_y, block_prefix="C3G", lot_id=ly,
        stage7_start_utc="2026-09-12T00:00:00Z", sort_reaggregation_utc="2026-09-22T00:00:00Z", assay_harvest_utc="2026-10-01T00:00:00Z",
        specimen_id=f"SPEC-C-3-GSIS-{ly}", intervention_cohort_id=c1_cohort_y, candidate_gene=tg_dual,
        trace_collected_at_utc="2026-10-01T17:00:00Z",  # inside declared win_end 18:00Z, but AFTER end_measured_at_utc 16:00Z!
    )
    _eng_late_start = _mk_c_eng(
        c1_cohort_y, "2026-10-01T16:00:00Z", stage_name="C-3-GSIS", lot_s_id=ly,
        win_start="2026-09-30T13:00:00Z", win_end="2026-10-01T18:00:00Z",
        start_measured_utc="2026-09-30T14:30:00Z",
    )
    _r2_before_meas = _mk_r8_readout2(
        matched_comparator_id=nt_y, block_prefix="C3G", lot_id=ly,
        stage7_start_utc="2026-09-12T00:00:00Z", sort_reaggregation_utc="2026-09-22T00:00:00Z", assay_harvest_utc="2026-10-01T00:00:00Z",
        specimen_id=f"SPEC-C-3-GSIS-{ly}", intervention_cohort_id=c1_cohort_y, candidate_gene=tg_dual,
        trace_collected_at_utc="2026-09-30T14:15:00Z",  # inside assay_started 14:00Z, but BEFORE start_measured_at_utc 14:30Z!
    )
    chk(
        "FAIL_GATE_C3_GSIS_READOUT2_INTERVENTION_SPECIMEN_OR_TRACE_LINK_MISMATCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c3_gsis_evidence": _sign_receipt({**c3_gsis_y, "readout2_evidence": _r2_after_meas})})["failures"]
        and "FAIL_GATE_C3_GSIS_READOUT2_INTERVENTION_SPECIMEN_OR_TRACE_LINK_MISMATCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c3_gsis_evidence": _sign_receipt({**c3_gsis_y, "transient_target_engagement_record": _eng_late_start, "readout2_evidence": _r2_before_meas})})["failures"],
        "G42_c3gsis_trace_outside_acquired_engagement_interval_fails",
    )
    # 2. C-1 dual PMAIP1+BCL2L11 molecular_kd_provenance omitting BCL2L11 observations (only 2 obs) OR tampering pmaip1_protein_kd_pct OR wrong product_id FAILS!
    _kdp_2only_b = {k: v for k, v in c1_norm_6["molecular_kd_provenance"].items() if k != "producer_record_sha256"}
    _kdp_2only_b["target_observations"] = _kdp_2only_b["target_observations"][:2]
    _c1_kdp_2only = _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "molecular_kd_provenance": {**_kdp_2only_b, "producer_record_sha256": sha256_bytes(canonical_json_bytes(_kdp_2only_b))}}})
    _kdp_mm_b = {k: v for k, v in c1_norm_6["molecular_kd_provenance"].items() if k != "producer_record_sha256"}
    _obs_mm0 = {k: v for k, v in _kdp_mm_b["target_observations"][1].items() if k != "producer_observation_sha256"}
    _obs_mm0["kd_pct"] = 76.0  # contradicts pmaip1_protein_kd_pct = 82.0!
    _kdp_mm_b["target_observations"] = [_kdp_mm_b["target_observations"][0], {**_obs_mm0, "producer_observation_sha256": sha256_bytes(canonical_json_bytes(_obs_mm0))}, *_kdp_mm_b["target_observations"][2:]]
    _c1_kdp_mm = _sign_receipt({**c1_y, "c1_normoxia": {**c1_norm_6, "molecular_kd_provenance": {**_kdp_mm_b, "producer_record_sha256": sha256_bytes(canonical_json_bytes(_kdp_mm_b))}}})
    _c1_kdp_wrongprod = _sign_receipt({**c1_y, "c1_normoxia": _mk_c1_with_kd_lot(c1_norm_6, ly, "ISLET1_DESIGN_B_V090")})
    chk(
        "FAIL_GATE_C1_NORMOXIA_MOLECULAR_KD_PROVENANCE_MISMATCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _c1_kdp_2only})["failures"]
        and "FAIL_GATE_C1_NORMOXIA_MOLECULAR_KD_PROVENANCE_MISMATCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _c1_kdp_mm})["failures"]
        and "FAIL_GATE_C1_NORMOXIA_MOLECULAR_KD_PROVENANCE_MISMATCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c1_evidence": _c1_kdp_wrongprod})["failures"],
        "G42_c1_dual_arm_4obs_kd_provenance_incomplete_or_mismatch_fails",
    )
    # 3. C-2 omitting soluble_iapp_matched_ctrl_assay (re-chained) returns pure HOLD with zero failures!
    _c2_no_si = {k: v for k, v in c2_y.items() if k not in ("soluble_iapp_matched_ctrl_assay", "receipt_sha256")}
    _res_c2_nosi = evaluate_gate42_gy032_channel_c_screen(_rechain_g42_from_c1(c1_y, c2_override=_c2_no_si))
    chk(
        _res_c2_nosi["verdict"] == "HOLD" and _res_c2_nosi["failures"] == []
        and "HOLD_GATE_C2_MISSING_SOLUBLE_IAPP_MATCHED_CONTROL_ASSAY" in _res_c2_nosi["holds"],
        "G42_c2_missing_soluble_iapp_matched_control_pure_hold",
    )
    # 4. C-2 soluble IAPP ratio > 1.25x matched NT control FAILS even when iapp_amyloid_ratio_vs_ctrl <= 1.15, and tampered ratio FAILS!
    _si_hi = _mk_c2_sol_iapp(spec_v=f"SPEC-C-2-{ly}", lot_v=ly, nt_v=nt_y, treated_pg=18.5, ctrl_pg=14.0)  # 1.3214x > 1.25!
    _si_tamper = _mk_c2_sol_iapp(spec_v=f"SPEC-C-2-{ly}", lot_v=ly, nt_v=nt_y, treated_pg=18.5, ctrl_pg=14.0, ratio_override=1.10)
    chk(
        "FAIL_GATE_C2_SOLUBLE_IAPP_RATIO_EXCEEDS_1P25" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "soluble_iapp_pg_per_ieq": 18.5, "soluble_iapp_matched_ctrl_assay": _si_hi})})["failures"]
        and "FAIL_GATE_C2_SOLUBLE_IAPP_MATCHED_CONTROL_MISMATCH" in evaluate_gate42_gy032_channel_c_screen({**g42_ok, "c2_evidence": _sign_receipt({**c2_y, "soluble_iapp_pg_per_ieq": 18.5, "soluble_iapp_matched_ctrl_assay": _si_tamper})})["failures"],
        "G42_c2_soluble_iapp_ratio_over_1p25_and_tamper_fail",
    )

    require(total == 796 and passed == 796, f"Expected 796/796 gate self-tests, got {passed}/{total}")
    return {"passed": passed, "total": total, "gates": ["GATE-40", "GATE-41", "GATE-42", "GATE-43"]}

def _auto_resolve_paths(script_path: Path) -> tuple[Optional[Path], Optional[Path], Path]:
    here = script_path.resolve().parent
    out_name = "wave7_cellgemma_iip0062_0065_2p24_portfolio_v0.9.0.json"
    if here.name == "scripts" and (here.parent / "data" / "protocols" / "wave6_master_contract.json").is_file():
        w6_p = here.parent / "data" / "protocols" / "wave6_master_contract.json"
        cg_p = here.parent / "data" / "extracted" / "cellgemma_islet_v0_1_receipt.json"
        out_p = here.parent / "data" / "extracted" / out_name
        if not out_p.is_file() and (here / out_name).is_file():
            out_p = here / out_name
        return w6_p, (cg_p if cg_p.is_file() else None), out_p
    cg_stg = here.parent / "upstream_v0_9_0" / "cellgemma_islet_v0_1_receipt.json"
    out_stg = here / out_name
    return None, (cg_stg if cg_stg.is_file() else None), out_stg


def main() -> None:
    ap = argparse.ArgumentParser(description="Wave-7 CellGemma 2^24 Rebase Verifier & Crosswalk Generator")
    ap.add_argument("--generate", action="store_true", help="Generate/overwrite the Wave-7 2^24 crosswalk JSON")
    ap.add_argument("--check", action="store_true", help="Verify existing Wave-7 2^24 crosswalk JSON byte/value parity")
    ap.add_argument("--wave6-contract", type=Path, default=None, help="Path to wave6_master_contract.json")
    ap.add_argument("--cellgemma-receipt", type=Path, default=None, help="Path to cellgemma_islet_v0_1_receipt.json")
    ap.add_argument("--output", type=Path, default=None, help="Path to crosswalk JSON output/check target")
    ap.add_argument("--json", action="store_true", help="Emit concise JSON verification summary")
    args = ap.parse_args()

    auto_w6, auto_cg, auto_out = _auto_resolve_paths(Path(__file__))
    w6_path = args.wave6_contract if args.wave6_contract is not None else auto_w6
    cg_path = args.cellgemma_receipt if args.cellgemma_receipt is not None else auto_cg
    out_path = args.output if args.output is not None else auto_out

    fresh = build_wave7_crosswalk(w6_path, cg_path)

    if args.generate:
        out_path.parent.mkdir(parents=True, exist_ok=True)
        out_path.write_text(json.dumps(fresh, indent=2, sort_keys=False) + "\n", encoding="utf-8")

    if args.check or not args.generate:
        if out_path.is_file():
            disk = load_strict_json(out_path.read_text(encoding="utf-8"), out_path.name)
            d_cmp = dict(disk)
            f_cmp = dict(fresh)
            d_sha = d_cmp.pop("portable_payload_sha256", None)
            f_sha = f_cmp.pop("portable_payload_sha256", None)
            require(isinstance(d_sha, str) and len(d_sha) == 64, "Missing disk portable_payload_sha256")
            require(sha256_bytes(canonical_json_bytes(d_cmp)) == d_sha, "Disk receipt self-hash tamper detected")
            if w6_path is not None and cg_path is not None:
                require(d_sha == f_sha, f"Wave-7 receipt drift: disk={d_sha} != fresh={f_sha}")
            else:
                require(d_cmp["headline_summary"] == f_cmp["headline_summary"], "Headline summary mismatch")
                require(d_cmp["primary_6arm_2p24_rebased"] == f_cmp["primary_6arm_2p24_rebased"], "Primary 2^24 mismatch")
                require(d_cmp["audit_sensitivities"] == f_cmp["audit_sensitivities"], "Audit sensitivities mismatch")
        elif args.check:
            raise RuntimeError(f"Expected Wave-7 crosswalk JSON missing at {out_path}")

    hs = fresh["headline_summary"]
    gt = fresh["executable_gate_self_tests"]
    summary = {
        "status": "PASS",
        "portable_payload_sha256": fresh["portable_payload_sha256"],
        "iip_ids": fresh["iip_ids"],
        "gate_ids": fresh["gate_ids"],
        "wave6_6arm_baseline_modular_pct": hs["wave6_6arm_central_baseline_modular_pct"],
        "wave7_6arm_central_modular_pct": hs["wave7_6arm_central_modular_pct"],
        "wave7_6arm_central_locked_pct": hs["wave7_6arm_central_locked_pct"],
        "wave7_6arm_central_ceiling_pct": hs["wave7_6arm_central_ceiling_pct"],
        "wave7_6arm_ceil_lift_band_modular_pct": hs["wave7_6arm_ceil_lift_band_modular_pct"],
        "wave7_6arm_h2_ceil_held_central_modular_pct": hs["wave7_6arm_h2_ceil_held_central_modular_pct"],
        "wave7_6arm_fixed_ceil_band_modular_pct": hs["wave7_6arm_fixed_ceil_band_modular_pct"],
        "wave7_192state_prelab_avg_central_modular_pct": hs["wave7_192state_prelab_avg_central_modular_pct"],
        "wave7_192state_c_foundry_conditional_band_central_pct": hs["wave7_192state_c_foundry_conditional_band_central_pct"],
        "c3_base_lifted_central_iip0064": fresh["headroom_compression_factors"]["c3_base_lifted_central_iip0064"],
        "design_a_physical_coated_route_modular_leak_pp": hs["design_a_physical_coated_route_modular_leak_pp"],
        "non_whitelisted_product_coated_route_modular_leak_pp": hs["non_whitelisted_product_coated_route_modular_leak_pp"],
        "uncoated_xdz_spillover_pp": hs["uncoated_xdz_spillover_pp"],
        "uncoated_b_r1_spillover_pp": hs["uncoated_b_r1_spillover_pp"],
        "uncoated_r1_and_r4_drift_pp": hs["uncoated_r1_and_r4_drift_pp"],
        "gate_self_tests": gt,
    }
    if args.json:
        print(json.dumps(summary, indent=2))
    else:
        print(
            f"WAVE-7 REBASE VERIFIED PASS ({', '.join(fresh['iip_ids'])} / {', '.join(fresh['gate_ids'])}) | "
            f"Wave-6={hs['wave6_6arm_central_baseline_modular_pct']:.4f}% -> "
            f"Wave-7 Central={hs['wave7_6arm_central_modular_pct']:.4f}% modular "
            f"(band {hs['wave7_6arm_ceil_lift_band_modular_pct'][0]:.4f}%-{hs['wave7_6arm_ceil_lift_band_modular_pct'][1]:.4f}%, "
            f"locked {hs['wave7_6arm_central_locked_pct']:.4f}%, ceil {hs['wave7_6arm_central_ceiling_pct']:.4f}%, "
            f"192-state pre-lab avg {hs['wave7_192state_prelab_avg_central_modular_pct']:.4f}%, "
            f"zero-spillover: X/D/Z={hs['uncoated_xdz_spillover_pp']}, B/R1={hs['uncoated_b_r1_spillover_pp']}, R1&R4={hs['uncoated_r1_and_r4_drift_pp']}) | "
            f"{gt['passed']}/{gt['total']} gate self-tests PASS | sha256={fresh['portable_payload_sha256'][:16]}..."
        )


if __name__ == "__main__":
    main()
