#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""
Standalone Zero-GPU / Pure-CPU Fail-Closed Verifier for OpenIslet CellGemma-Islet v0.9.0.

License & Distribution Distinction:
  - This executable verifier script: Apache-2.0 (distributed inside OpenIslet LICENSE for scripts/**;
    any standalone distribution outside the licensed repository MUST include the full Apache-2.0
    license text alongside the 6 runtime verifier inputs per Apache-2.0 §4(a)).
  - Narrative IIP drafts & JSON provenance receipt: CC BY 4.0 (docs/** and data/**).
  - Underlying model weights card (google/cellgemma-e4b, commit 6212145e0131d3744171739ea5232afc6aaa7c76):
    Apache-2.0 research weights (intended for research use with independent experimental validation);
    frozen PubMed bibliographic records are a dated NLM/NCBI E-utilities snapshot (2026-12-02T16:04:39Z)
    subject to NLM data/download terms (https://www.nlm.nih.gov/databases/download.html).

Honest Scope Separation:
  - Default portable mode (6 runtime inputs): deterministically verifies strict JSON/nonfinite
    safety, payload & file SHA-256 integrity, embedded 31-file manifest syntax (NOT external raw
    bytes), exact S1/S2 panel-gene-to-mean & n_up/n_down arithmetic on 120/139 full-vector profiles
    (6,263 embedded 4-decimal NPZ entries) + S1/S2 residual accounting (NOT omitted-gene recovery)
    and composite arithmetic on 19/139 thresholded raw-JSON profiles (70/70 panels flagged
    unverifiable below 0.05; 46/70 S1 nonzero across 17/19 profiles; 70/70 S2 nonzero across 19/19
    profiles), track-specific falsifying Step-0 G1 checks (Track 1 >=0.25/0.25 on post-cutoff CM &
    6-cond Flex; Track 2 >=0.15/0.20 on 8-target RQC; 3x1 vs 5x3) & 8/8 RQC target bindings in Draft C,
    embedded per-file generation-cap sums (142/147, 272/351, 36 unknown), all 23 retrospective
    concordance scalars in Draft C, all 36 core + 40 omega [0,1] + 24 Design B discount 2^20 rows +
    full Design-A parameter & output firewall invariance, strict Section-6 live-odds (`+0.00 percentage
    points`), exact labeled baseline-role bindings (including explicit `inactive Track-B`), exact
    ordered triple header columns (`Ceiling / Locked / Modular` for `phi = 0.25` & `phi = 0.50`),
    exact per-row ceiling strings, BOTH canonical BPR-05 bounds (`64.61%` and `67.25%`), & promoted-
    scalar Markdown binding, 60/60 body/Section-7 PMID parity + 9 curated claim_to_source_map records
    (33 unique PMIDs) body/locator resolution, Graveyard pairs, and fixed host-independent portable
    preflight hygiene across all 6 files (identical result regardless of reader account name;
    canonical OpenIslet exporter checks remain authoritative at submission; pair with a sanitized
    trusted detached manifest or canonical immutable source for full draft-byte integrity).
  - Local source mode (`--verify-local-sources`): scoped explicitly to the 31 local files listed in
    `source_file_sha256_manifest` (verifying exact byte sizes & SHA-256 digests on disk, incl.
    primary Track-1/Track-2 truth NPZs & summaries, locked benchmark plan, scripts, builder, and raw
    results) plus dated NLM snapshot parity across all 60 PubMed records (does not re-extract raw
    NPZ/JSON numeric values into the receipt from scratch; model weights/config remain pinned to HF).
  - Semantic claim-to-full-text fidelity, live NCBI retraction API status, raw-to-receipt numerical
    re-extraction, GPU re-inference, and wet-lab biological hypothesis testing are external to this script.

Fail-Closed Guarantee:
  Uses explicit RuntimeError checks (zero assert statements), remaining 100% fail-closed under
  both `python3 -W error -B` and `python3 -W error -O -B`.

Usage:
  PYTHONDONTWRITEBYTECODE=1 python3 -B verify_cellgemma_islet_v0_1.py
  PYTHONDONTWRITEBYTECODE=1 python3 -B verify_cellgemma_islet_v0_1.py --verify-local-sources
"""

from __future__ import annotations

import argparse
import hashlib
import json
import math
import re
from pathlib import Path
from typing import Any

HERE = Path(__file__).resolve().parent
RECEIPT_PATH = (
    HERE / "cellgemma_islet_v0_1_receipt.json"
    if (HERE / "cellgemma_islet_v0_1_receipt.json").is_file()
    else HERE.parent / "data" / "extracted" / "cellgemma_islet_v0_1_receipt.json"
)
VERIFIER_PATH = Path(__file__).resolve()
IIP_DRAFT_FILES = {
    "A": "IIP_DRAFT_A_PIRFENIDONE_LOCAL_ANTIFBR_IEC_H4.md",
    "B": "IIP_DRAFT_B_DEUCRAVACITINIB_LOCAL_TYK2_IBMIR_NK.md",
    "C": "IIP_DRAFT_C_BBC3_PMAIP1_JAK2_H3_CHANNEL_C_BYSTANDER.md",
    "D": "IIP_DRAFT_D_CELLGEMMA_BLUEPRINT_GUARDRAILS_AND_HIPCORE_AUDIT.md",
}

SHIPPED_IIP0042_EXACT = {
    "phi_0p25_central": {
        "L1": (0.6641165402574369, 0.6064389039505889, 0.6159208654195334),
        "L3B": (0.7059206074620995, 0.6600787450699173, 0.6657313735189612),
    },
    "phi_0p50_harsh_stress": {
        "L1": (0.6490015923569795, 0.5968696707734863, 0.6057678502003759),
        "L3B": (0.6898542206807782, 0.6491393219690672, 0.6543971951385278),
    },
}

CANONICAL_GY_OFFGRID = {
    "OFFGRID_GUARD_001": "GY-015",
    "OFFGRID_GUARD_002": "GY-016",
    "OFFGRID_GUARD_003": "GY-011",
    "OFFGRID_GUARD_004": "GY-012",
    "OFFGRID_GUARD_005": "GY-013",
    "OFFGRID_GUARD_006": "GY-014",
    "OFFGRID_GUARD_007": "GY-017",
    "OFFGRID_GUARD_008": "GY-018",
    "OFFGRID_GUARD_009": "GY-019",
    "OFFGRID_GUARD_010": "GY-020",
    "OFFGRID_GUARD_011": "GY-021",
    "OFFGRID_GUARD_012": "GY-022",
    "OFFGRID_GUARD_013": "GY-023",
    "OFFGRID_GUARD_014": "GY-024",
    "OFFGRID_GUARD_015": "GY-025",
    "OFFGRID_GUARD_016": "GY-026",
    "OFFGRID_GUARD_017": "GY-027",
    "OFFGRID_GUARD_018": "GY-028",
    "OFFGRID_GUARD_019": "GY-029",
    "OFFGRID_GUARD_020": "GY-030",
    "OFFGRID_GUARD_021": "GY-031",
    "OFFGRID_GUARD_022": "GY-032",
}


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


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, 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) -> Any:
    def _reject_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 rejected: {k!r}")
            out[k] = v
        return out

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

    data = json.loads(raw_text, object_pairs_hook=_reject_dup, parse_constant=_reject_const)
    _check_all_finite(data)
    return data


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(isinstance(val, (int, float)) and math.isfinite(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 = max(delta_a, delta_b)
    lo = min(delta_a, delta_b)
    if lo == 0.0:
        return base + hi
    rem_frac = max(0.0, 1.0 - hi / (1.0 - base))
    val = base + hi + (1.0 - omega) * lo * rem_frac
    require(base <= val < 1.0, f"Out-of-envelope combined value={val}")
    return val


def _bivariate(p1: float, p2: float, phi: float) -> dict[tuple[int, int], float]:
    p1, p2 = min(1.0, max(0.0, p1)), 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: list[float], phi: float) -> list[float]:
    m = len(probs)
    n = 1 << m
    d_ind = [0.0] * n
    for mask in range(n):
        w = 1.0
        for i in range(m):
            w *= probs[i] if (mask & (1 << i)) else (1.0 - probs[i])
        d_ind[mask] = w
    if phi == 0.0:
        return d_ind
    order = sorted(range(m), key=lambda i: probs[i])
    d_pos = [0.0] * n
    prev = 0.0
    for idx, i in enumerate(order):
        w = probs[i] - prev
        if w > 0.0:
            d_pos[sum(1 << j for j in order[idx:])] += w
        prev = probs[i]
    d_pos[0] += 1.0 - prev
    return [(1.0 - phi) * d_ind[s] + phi * d_pos[s] for s in range(n)]


def _frechet_couple(inc: list[float], u_new: float, phi: float, target_fn) -> list[float]:
    n0 = len(inc)
    u_new = min(1.0, max(0.0, 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)
            d_pos[mi | n0] = p_11 * (w / p_e1)
        else:
            d_pos[mi] = p_00 * (w / p_e0)
            d_pos[mi | n0] = p_01 * (w / p_e0)
    return [(1.0 - phi) * d_ind[s] + phi * d_pos[s] for s in range(2 * n0)]


def eval_5arm_from_inputs(inp: dict[str, Any]) -> dict[str, Any]:
    arms = inp["arms"]
    require(len(arms) == 5 and all(len(a) == 4 for a in arms), "Invalid arms shape")
    pa, pb, px, py, pd = arms
    c1_allo = inp["c1_allo"]
    c2_a, c2_bx, c2_y, c2_univ, c2_auto = inp["c2_a"], inp["c2_bx"], inp["c2_y"], inp["c2_univ"], inp["c2_auto"]
    c2_u0 = inp.get("c2_univ_base_for_a", c2_univ)
    c3_a, c3_bx, c3_y, c3_d = inp["c3_a"], inp["c3_bx"], inp["c3_y"], inp["c3_d"]
    c4_univ, c4_pa, c4_pbx, c4_r3p = inp["c4_univ"], inp["c4_pouch_a"], inp["c4_pouch_bx"], inp["c4_r3p"]
    phi_c = inp["phi_c"]
    phi_yx = 0.75

    u_d1 = min(1.0, max(0.0, pd[0] / c1_allo))
    d1 = [0.0] * 32
    d1[0], d1[15], d1[31] = 1.0 - c1_allo, c1_allo * (1.0 - u_d1), c1_allo * u_d1

    require(c2_a <= c2_bx + 1e-12 and c2_bx <= c2_y + 1e-12 and c2_y <= c2_univ + 1e-12, "Invalid H2 ceilings")
    biv2_y = _bivariate(c2_y / c2_univ, c2_auto / c2_univ, phi_c)
    u_d2 = pd[1] / c2_auto
    if abs(c2_a - c2_bx) <= 1e-12 and abs(c2_univ - c2_u0) <= 1e-12:
        d2_inc = _frechet_joint([pa[1] / c2_bx, pb[1] / c2_bx, px[1] / c2_bx], 0.0)
        r2, u_y2 = c2_bx / c2_y, py[1] / c2_y
        d2_both = _frechet_couple(d2_inc, u_y2, 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_y2)
        d2_allo4[8] += (1.0 - r2) * u_y2
        d2 = [0.0] * 32
        d2[0] += 1.0 - c2_univ
        for (s0, s1), wp in biv2_y.items():
            w = c2_univ * wp
            if s0 == 0 and s1 == 0:
                d2[0] += w
            elif s0 == 1 and s1 == 0:
                for m4 in range(16):
                    d2[m4] += w * d2_allo4[m4]
            elif s0 == 0 and s1 == 1:
                d2[0] += w * (1.0 - u_d2)
                d2[16] += w * u_d2
            else:
                for m4 in range(16):
                    d2[m4] += w * d2_allo4[m4] * (1.0 - u_d2)
                    d2[m4 | 16] += w * d2_allo4[m4] * u_d2
    else:
        biv2_a = _bivariate(c2_a / c2_u0, c2_auto / c2_u0, phi_c)
        p_a1_d1, p_a1_d0 = c2_u0 * biv2_a[(1, 1)], c2_u0 * biv2_a[(1, 0)]
        p_y1_d1, p_y1_d0 = c2_univ * biv2_y[(1, 1)], c2_univ * biv2_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")
        require(abs(c2_bx - c2_y) <= 1e-12, "Nested H2 firewall requires c2_bx == c2_y")
        q11 = p_a1_d1 / p_y1_d1 if p_y1_d1 > 0 else 0.0
        q10 = p_a1_d0 / p_y1_d0 if p_y1_d0 > 0 else 0.0
        d2_with_a = _frechet_couple(_frechet_joint([pa[1] / c2_a, pb[1] / c2_bx, px[1] / c2_bx], 0.0), py[1] / c2_y, phi_yx, lambda mi: bool(mi & 4))
        d2_no_a = _frechet_couple(_frechet_joint([0.0, pb[1] / c2_bx, px[1] / c2_bx], 0.0), py[1] / c2_y, phi_yx, lambda mi: bool(mi & 4))
        d2 = [0.0] * 32
        d2[0] += 1.0 - c2_univ + c2_univ * biv2_y[(0, 0)]
        w01 = c2_univ * biv2_y[(0, 1)]
        d2[0] += w01 * (1.0 - u_d2)
        d2[16] += w01 * u_d2
        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_d2)
            d2[m4 | 16] += p_y1_d1 * mix * u_d2
    c2_e = c2_univ * (1.0 - biv2_y[(0, 0)])

    if abs(c3_a - c3_bx) <= 1e-12 and abs(c3_d - c3_y) <= 1e-12 and c3_bx <= c3_y + 1e-12:
        d3_inc = _frechet_joint([pa[2] / c3_bx, pb[2] / c3_bx, px[2] / c3_bx], 0.0)
        r3 = c3_bx / c3_y
        u_y3 = py[2] / c3_y
        d3_both = _frechet_couple(d3_inc, u_y3, phi_yx, lambda mi: bool(mi & 4))
        d3_allo4 = [r3 * d3_both[k] for k in range(16)]
        d3_allo4[0] += (1.0 - r3) * (1.0 - u_y3)
        d3_allo4[8] += (1.0 - r3) * u_y3
        d3_5 = _frechet_couple(d3_allo4, pd[2] / c3_y, phi_c, lambda m4: m4 != 0)
        d3 = [c3_y * x for x in d3_5]
        d3[0] += 1.0 - c3_y
    elif c3_a < c3_bx and abs(c3_bx - c3_y) <= 1e-12 and abs(c3_d - c3_y) <= 1e-12:
        r_a = c3_a / c3_y
        d5_all = _frechet_couple(_frechet_couple(_frechet_joint([pa[2] / c3_a, pb[2] / c3_y, px[2] / c3_y], 0.0), py[2] / c3_y, phi_yx, lambda mi: bool(mi & 4)), pd[2] / c3_y, phi_c, lambda m4: m4 != 0)
        d5_noa = _frechet_couple(_frechet_couple(_frechet_joint([0.0, pb[2] / c3_y, px[2] / c3_y], 0.0), py[2] / c3_y, phi_yx, lambda mi: bool(mi & 4)), pd[2] / c3_y, phi_c, lambda m4: m4 != 0)
        d3 = [c3_y * (r_a * d5_all[k] + (1.0 - r_a) * d5_noa[k]) for k in range(32)]
        d3[0] += 1.0 - c3_y
    else:
        raise RuntimeError(f"Unsupported H3 ceiling configuration: {(c3_a, c3_bx, c3_y, c3_d)}")
    c3_e = c3_y

    require(c4_pa <= c4_pbx + 1e-12 and c4_pbx <= c4_univ + 1e-12, "Invalid H4 ceilings")
    r_a4 = c4_pa / c4_pbx
    d_ax_with = _frechet_joint([pa[3] / c4_pa, px[3] / c4_pbx], 1.0)
    d_ax_no = _frechet_joint([0.0, px[3] / c4_pbx], 1.0)
    d_ax = [r_a4 * d_ax_with[k] + (1.0 - r_a4) * d_ax_no[k] for k in range(4)]
    u_b4 = pb[3] / c4_pbx
    d4_inc = [0.0] * 8
    for m_ax in range(4):
        bm = (m_ax & 1) | (((m_ax >> 1) & 1) << 2)
        d4_inc[bm] += d_ax[m_ax] * (1.0 - u_b4)
        d4_inc[bm | 2] += d_ax[m_ax] * u_b4
    biv4 = _bivariate(c4_pbx / c4_univ, c4_r3p / c4_univ, phi_c)
    d4_r3 = _frechet_joint([py[3] / c4_r3p, pd[3] / c4_r3p], 1.0)
    d4 = [0.0] * 32
    d4[0] += 1.0 - c4_univ
    for (s0, s1), wp in biv4.items():
        w = c4_univ * wp
        if s0 == 0 and s1 == 0:
            d4[0] += w
        elif s0 == 1 and s1 == 0:
            for m3 in range(8):
                d4[m3] += w * d4_inc[m3]
        elif s0 == 0 and s1 == 1:
            for mr in range(4):
                d4[((mr & 1) << 3) | (((mr >> 1) & 1) << 4)] += w * d4_r3[mr]
        else:
            for m3 in range(8):
                for mr in range(4):
                    d4[m3 | ((mr & 1) << 3) | (((mr >> 1) & 1) << 4)] += w * d4_inc[m3] * d4_r3[mr]
    c4_e = c4_univ * (1.0 - biv4[(0, 0)])

    dists = (d1, d2, d3, d4)
    for h, dh in enumerate(dists):
        require(abs(sum(dh) - 1.0) <= 1e-12 and all(w >= -1e-15 for w in dh), f"H{h+1} distribution invalid")
        for i in range(5):
            rec = sum(dh[m] for m in range(32) if (m & (1 << i)))
            require(abs(rec - arms[i][h]) <= 1e-11, f"H{h+1} arm {i} marginal mismatch: {rec} vs {arms[i][h]}")

    v = [0.0] * 32
    v[31] = 1.0
    v_h123: list[float] = []
    for h, dh in enumerate(dists):
        vn = [0.0] * 32
        for s, vs in enumerate(v):
            if vs:
                for m, w in enumerate(dh):
                    if w:
                        vn[s & m] += vs * w
        v = vn
        if h == 2:
            v_h123 = list(v)

    routes = ("R1", "R2", "R1", "R3P", "R3P")
    classes = ("UNHARDENED_A_B_X", "UNHARDENED_A_B_X", "UNHARDENED_A_B_X", "DESIGN_Y_FULLSTACK_V2", "D1B_AUTO_C_V2")
    compat = {
        "UNHARDENED_A_B_X": frozenset({"R1", "R2"}),
        "DESIGN_Y_FULLSTACK_V2": frozenset({"R3P"}),
        "D1B_AUTO_C_V2": frozenset({"R3P"}),
    }
    locked = sum(v[s] for s in range(1, 32))
    mod100 = 0.0
    for mc in range(1, 32):
        wc = v_h123[mc]
        if not wc:
            continue
        allowed = set()
        for i in range(5):
            if mc & (1 << i):
                allowed |= compat[classes[i]]
        for mh in range(1, 32):
            wh = d4[mh]
            if wh and any(routes[j] in allowed for j in range(5) if (mh & (1 << j))):
                mod100 += wc * wh

    a_4_marginals = [sum(dh[m] for m in range(32) if (m & 1)) for dh in dists]
    a_standalone = sum(v[s] for s in range(32) if (s & 1))
    h2_ad_4cell = [
        sum(d2[m] for m in range(32) if not (m & 1) and not (m & 16)),
        sum(d2[m] for m in range(32) if (m & 1) and not (m & 16)),
        sum(d2[m] for m in range(32) if not (m & 1) and (m & 16)),
        sum(d2[m] for m in range(32) if (m & 1) and (m & 16)),
    ]
    return {
        "ceiling_exact": c1_allo * c2_e * c3_e * c4_e,
        "locked_exact": locked,
        "modular_k100_exact": mod100,
        "design_a_4_marginals_exact": a_4_marginals,
        "design_a_standalone_exact": a_standalone,
        "design_a_d_h2_joint_4cell_exact": h2_ad_4cell,
        "p_h2_a1_d1_exact": h2_ad_4cell[3],
        "p_h4_a1_exact": a_4_marginals[3],
    }


def check_item_full(item_name: str, item: dict[str, Any], scoring_panels: dict[str, dict[str, list[str]]]) -> dict[str, int]:
    fam = item["cell_family"]
    p = item["panels"]
    c = item["composite"]
    tol = 2.5e-4
    counts = {
        "full_vec": 0,
        "thresh": 0,
        "full_genes": 0,
        "thresh_panels": 0,
        "thresh_s1_nz": 0,
        "thresh_s2_nz": 0,
        "thresh_prof_s1_nz": 0,
        "thresh_prof_s2_nz": 0,
    }
    sources = set()

    for pn, pv in p.items():
        expected_n = len(scoring_panels[fam][pn])
        require(pv["n_panel_genes"] == expected_n, f"{item_name}:{pn} n_panel_genes mismatch")
        genes_map = pv["nonzero_panel_genes"]
        for g in genes_map:
            require(g in scoring_panels[fam][pn], f"{item_name}:{pn} unknown gene {g}")
        src = pv["panel_genes_source"]
        sources.add(src)
        if src == "exact_full_npz_nonzero":
            require(pv["sub_0p05_tail_unverifiable_at_gene_level"] is False, f"{item_name}:{pn} flag mismatch")
            counts["full_genes"] += len(genes_map)
            recon_s1 = sum(d["s1_norm_rank"] for d in genes_map.values()) / expected_n
            recon_s2 = sum(d["s2_lfc"] for d in genes_map.values()) / expected_n
            recon_up = sum(1 for d in genes_map.values() if d["s1_norm_rank"] > 0.05)
            recon_dn = sum(1 for d in genes_map.values() if d["s1_norm_rank"] < -0.05)
            require(abs(recon_s1 - pv["mean_s1_norm_rank"]) <= tol, f"{item_name}:{pn} exact S1 gene->mean mismatch")
            require(abs(recon_s2 - pv["mean_s2_lfc"]) <= tol, f"{item_name}:{pn} exact S2 gene->mean mismatch")
            require(recon_up == pv["n_up"], f"{item_name}:{pn} exact n_up mismatch: {recon_up} != {pv['n_up']}")
            require(recon_dn == pv["n_down"], f"{item_name}:{pn} exact n_down mismatch: {recon_dn} != {pv['n_down']}")
        elif src == "raw_json_abs_gt_0p05_thresholded":
            require(pv["sub_0p05_tail_unverifiable_at_gene_level"] is True, f"{item_name}:{pn} flag mismatch")
            counts["thresh_panels"] += 1
            tail_s1 = pv["unverifiable_sub_0p05_tail_residual_s1"]
            tail_s2 = pv["unverifiable_sub_0p05_tail_residual_s2"]
            if abs(tail_s1) > 1e-6:
                counts["thresh_s1_nz"] += 1
            if abs(tail_s2) > 1e-6:
                counts["thresh_s2_nz"] += 1
            recon_s1 = (sum(d["s1_norm_rank"] for d in genes_map.values()) + tail_s1) / expected_n
            recon_s2 = (sum(d["s2_lfc"] for d in genes_map.values()) + tail_s2) / expected_n
            # Raw-JSON genes are stored to 3 decimals whenever |s1|>0.05 OR |s2|>0.05; values exactly at +/-0.050
            # may have been >0.050 before rounding (e.g. Baricitinib NK GZMB = 0.050), giving tight [strict, inclusive] bounds.
            up_lo = sum(1 for d in genes_map.values() if d["s1_norm_rank"] > 0.05)
            up_hi = sum(1 for d in genes_map.values() if d["s1_norm_rank"] >= 0.05)
            dn_lo = sum(1 for d in genes_map.values() if d["s1_norm_rank"] < -0.05)
            dn_hi = sum(1 for d in genes_map.values() if d["s1_norm_rank"] <= -0.05)
            require(abs(recon_s1 - pv["mean_s1_norm_rank"]) <= tol, f"{item_name}:{pn} thresholded S1 sum mismatch")
            require(abs(recon_s2 - pv["mean_s2_lfc"]) <= tol, f"{item_name}:{pn} thresholded S2 sum mismatch")
            require(up_lo <= pv["n_up"] <= up_hi, f"{item_name}:{pn} thresholded n_up out of [{up_lo},{up_hi}]: {pv['n_up']}")
            require(dn_lo <= pv["n_down"] <= dn_hi, f"{item_name}:{pn} thresholded n_down out of [{dn_lo},{dn_hi}]: {pv['n_down']}")
        else:
            raise RuntimeError(f"Unknown panel_genes_source {src!r} in {item_name}:{pn}")

    require(len(sources) == 1, f"Mixed panel sources within {item_name}: {sources}")
    if "exact_full_npz_nonzero" in sources:
        counts["full_vec"] = 1
    else:
        counts["thresh"] = 1
        if counts["thresh_s1_nz"] > 0:
            counts["thresh_prof_s1_nz"] = 1
        if counts["thresh_s2_nz"] > 0:
            counts["thresh_prof_s2_nz"] = 1

    if fam == "iec":
        bar = p["barrier_angio_good"]["mean_s1_norm_rank"]
        inf = p["inflam_coag_complement_bad"]["mean_s1_norm_rank"]
        mit = p["mitotic_prolif_marker"]["mean_s1_norm_rank"]
        tox = p["arrest_stress_apop_bad"]["mean_s1_norm_rank"]
        require(abs(c["vascular_rescue_score"] - round(bar - inf - 0.5 * tox, 4)) <= tol, f"{item_name} vasc")
        require(abs(c["pre_iec_safety_score"] - round(bar + 0.3 * mit - 1.0 * tox - 0.5 * inf, 4)) <= tol, f"{item_name} pre_iec")
        require(abs(c["c3_mitotic_suppression_index"] - round(-mit, 4)) <= tol, f"{item_name} c3_mit")
    elif fam == "beta":
        ident = p["identity_gsis_good"]["mean_s1_norm_rank"]
        apop = p["apoptosis_upr_bad"]["mean_s1_norm_rank"]
        imm = p["immune_chemokine_mhc_bad"]["mean_s1_norm_rank"]
        prol = p["prolif_ec_drift_bad"]["mean_s1_norm_rank"]
        surv = p["survival_protective_good"]["mean_s1_norm_rank"]
        exp_h3 = round(0.8 * ident + 0.4 * surv - 1.2 * apop - 1.0 * imm - 1.0 * max(0.0, prol), 4)
        exp_sf = round(1.2 * ident - 1.0 * max(0.0, apop) - 1.0 * max(0.0, prol) - 0.5 * max(0.0, imm), 4)
        require(abs(c["h3_bystander_rescue_score"] - exp_h3) <= tol, f"{item_name} h3")
        require(abs(c["ring1_safety_score"] - exp_sf) <= tol, f"{item_name} safety")
    elif fam == "macrophage":
        fbr = p["profibrotic_fbr_bad"]["mean_s1_norm_rank"]
        eff = p["efferocytosis_homeostatic_good"]["mean_s1_norm_rank"]
        tox = p["apop_tox_bad"]["mean_s1_norm_rank"]
        require(abs(c["anti_fbr_score"] - round(-1.2 * fbr + 0.8 * eff - 1.0 * max(0.0, tox), 4)) <= tol, f"{item_name} anti_fbr")
    elif fam == "tcell":
        treg = p["treg_tolerance_good"]["mean_s1_norm_rank"]
        eff = p["effector_autoimmune_bad"]["mean_s1_norm_rank"]
        require(abs(c["local_tolerance_score"] - round(1.2 * treg - 1.0 * eff, 4)) <= tol, f"{item_name} tcell")
    elif fam == "nk":
        act = p["nk_activating_cytotoxic_bad"]["mean_s1_norm_rank"]
        inh = p["nk_inhibitory_quiescent_good"]["mean_s1_norm_rank"]
        require(abs(c["nk_safety_score"] - round(inh - 1.2 * act, 4)) <= tol, f"{item_name} nk")
    else:
        raise RuntimeError(f"Unknown cell family {fam} in {item_name}")
    return counts


def _build_portable_preflight_hygiene_patterns() -> list[tuple[str, re.Pattern[str]]]:
    """Fixed, host-independent portable preflight privacy/hygiene scanner (identical across any reader account name)."""
    pats: list[tuple[str, re.Pattern[str]]] = [
        (
            "private_home_or_temp_path",
            re.compile(
                r"(?<![A-Za-z0-9._-])(?:/" + "Users/" + r"|/" + "home/[a-z0-9_-]+/"
                + r"|/" + "private/tmp" + r"|/" + "var/folders"
                + r"|~/" + r"\.?[A-Za-z0-9_-]{2,}/|C:" + r"\\)"
            ),
        ),
        ("currency_symbol", re.compile("[" + chr(36) + chr(8364) + chr(163) + "]")),
        ("iso_currency_code", re.compile(r"\b(?:" + "U" + "SD|" + "E" + "UR|" + "G" + r"BP)\b")),
        ("internal_session_task_id", re.compile(r"\b" + "ta" + r"sk-\d+\b")),
        (
            "commercial_vendor_or_hosted_token",
            re.compile(r"\b(?:" + "Chat" + "GPT|" + "Open" + "AI|" + "Cla" + "ude|" + "Anthro" + "pic|" + "Alpha" + "Fold Server" + r")\b"),
        ),
        (
            "private_key_or_token",
            re.compile(
                r"(?:-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----|gh[pousr]_[A-Za-z0-9]{16,}"
                + r"|github_pat_[A-Za-z0-9_]{16,}|sk-ant-[A-Za-z0-9_-]{8,}|sk-proj-[A-Za-z0-9_-]{16,}"
                + r"|AIza[0-9A-Za-z_-]{20,}|hf_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16})"
            ),
        ),
        ("personal_mailbox", re.compile(r"[\w.+-]+@(?:g" + "mail|ic" + "loud|hot" + "mail|out" + "look|ya" + r"hoo)\.com", re.I)),
    ]
    return pats


def check_public_hygiene(text: str, label: str, patterns: list[tuple[str, re.Pattern[str]]]) -> None:
    for pname, rx in patterns:
        require(rx.search(text) is None, f"Portable preflight hygiene violation ({pname}) in {label}")


def check_decoded_json_hygiene(obj: Any, label: str, patterns: list[tuple[str, re.Pattern[str]]]) -> None:
    if isinstance(obj, str):
        check_public_hygiene(obj, label, patterns)
    elif isinstance(obj, dict):
        for k, v in obj.items():
            check_public_hygiene(str(k), label, patterns)
            check_decoded_json_hygiene(v, label, patterns)
    elif isinstance(obj, list):
        for v in obj:
            check_decoded_json_hygiene(v, label, patterns)


def check_graveyard_pairs(text: str, label: str) -> None:
    for m in re.finditer(r"`?(GY-\d{3})`?\s*(?:\(|/)\s*`?(OFFGRID_GUARD_\d{3})", text):
        gy_id, og_id = m.group(1), m.group(2)
        require(CANONICAL_GY_OFFGRID.get(og_id) == gy_id, f"Swapped Graveyard ID in {label}: {gy_id} / {og_id}")
    for m in re.finditer(r"`?(OFFGRID_GUARD_\d{3})`?\s*(?:\(|/)\s*`?(GY-\d{3})", text):
        og_id, gy_id = m.group(1), m.group(2)
        require(CANONICAL_GY_OFFGRID.get(og_id) == gy_id, f"Swapped Graveyard ID in {label}: {og_id} / {gy_id}")


def _parse_sec6_table_rows(md_text: str, fname: str) -> list[list[str]]:
    require("## 6." in md_text, f"Missing Section 6 in {fname}")
    sec6 = md_text.split("## 6.", 1)[1]
    if "## 7." in sec6:
        sec6 = sec6.split("## 7.", 1)[0]
    rows: list[list[str]] = []
    for ln in sec6.splitlines():
        s = ln.strip()
        if s.startswith("|") and s.endswith("|"):
            cells = [c.strip() for c in s.strip("|").split("|")]
            if all(re.fullmatch(r":?-+:?", c.replace(" ", "")) for c in cells):
                continue
            rows.append(cells)
    return rows


def _fmt_pct(exact_val: float) -> str:
    return f"{100.0 * exact_val:.2f}%"


def _fmt_delta_pp(val_exact: float, base_exact: float) -> str:
    return f"{100.0 * (val_exact - base_exact):+.2f} pp"


def verify_sec6_live_and_bpr05_lines(fname: str, md_text: str) -> None:
    """Bind Section 6 live headline odds (+0.00 pp), EVERY named baseline/metric/phi role (incl. inactive Track-B), AND BOTH canonical BPR-05 bounds (64.61%, 67.25%)."""
    require("## 6." in md_text, f"Missing Section 6 in {fname}")
    sec6 = md_text.split("## 6.", 1)[1]
    if "## 7." in sec6:
        sec6 = sec6.split("## 7.", 1)[0]
    ln_live = _find_single_line(sec6, "Live headline computational", f"{fname} §6")
    live_deltas = re.findall(r"[+-]?\d+\.\d{2}\s+percentage\s+points?", ln_live)
    require(live_deltas == ["+0.00 percentage points"], f"{fname} §6 live headline delta mismatch: {live_deltas!r}")

    # Strict labeled ordered role checks (rejects swapping locked/modular, swapping phi, or flipping inactive->active Track-B!)
    require(not re.search(r"\bactive\s+Track-B\b", ln_live, re.IGNORECASE), f"{fname} §6 live line must not mark Track-B active")
    role_patterns = [
        ("core_3arm_locked_modular", r"Core 3-(?:arm|design baseline) `50\.78%` locked / `54\.12%` modular"),
        ("shipped_l1_locked_modular", r"[Ss]hipped 5-arm `L1` `60\.64%` / `61\.59%`"),
        ("wave5_l3b_phi025", r"Wave-5 strict zero-drug `L3B` `66\.01%` / `66\.57%` at `phi = 0\.25`"),
        ("wave5_l3b_phi050", r"and `64\.91%` / `65\.44%` at `phi = 0\.50`"),
        ("inactive_track_b", r"(?:optional\s+)?(?:inactive\s+Track-B\s+`66\.65%`\s*/\s*`67\.21%`|Track-B\s+reset\s+`66\.65%`\s*/\s*`67\.21%`\s+remains\s+strictly\s+inactive\s+today)"),
    ]
    for rname, pat in role_patterns:
        require(bool(re.search(pat, ln_live)), f"{fname} §6 live baseline role mismatch ({rname}) in: {ln_live!r}")
    all_live_pcts = re.findall(r"\d+\.\d{2}%", ln_live)
    require(
        all_live_pcts == ["50.78%", "54.12%", "60.64%", "61.59%", "66.01%", "66.57%", "64.91%", "65.44%", "66.65%", "67.21%"],
        f"{fname} §6 live baseline exact ordered percentages mismatch: got {all_live_pcts!r}",
    )

    ln_bpr = _find_single_line(sec6, "BPR-05", f"{fname} §6")
    bpr_pcts = re.findall(r"[+-]?\d+\.\d{2}%", ln_bpr)
    require(bpr_pcts == ["64.61%", "67.25%", "66.57%"], f"{fname} §6 BPR-05 bounds mismatch (expected 64.61%, 67.25%, 66.57%): got {bpr_pcts!r}")


def verify_sec6_table_binding(
    fname: str,
    md_text: str,
    expected_rows: list[tuple[str, str, str]],
    p25: dict[str, Any],
    p50: dict[str, Any],
) -> None:
    """
    Strict row-by-row, column-by-column binding of Section-6 2^20 Markdown tables:
      Header: Exact normalized ordered triple & delta headings (rejects swapping Locked/Modular or phi=0.25/0.50!)
      Col 0: Scenario label (must contain exact identifier token)
      Col 1: EXACT normalized ceiling parameter specification (rejects appended/contradictory ceiling assignments!)
      Col 2: phi = 0.25 Ceiling / Locked / Modular (EXACTLY 3 signed % tokens matching exact scalars)
      Col 3: phi = 0.25 Delta (Mod) vs L3B (EXACTLY 1 signed pp token)
      Col 4: phi = 0.50 Ceiling / Locked / Modular (EXACTLY 3 signed % tokens matching exact scalars)
      Col 5: phi = 0.50 Delta (Mod) vs L3B (EXACTLY 1 signed pp token)
    """
    rows = _parse_sec6_table_rows(md_text, fname)
    require(len(rows) == 1 + len(expected_rows), f"{fname} Section 6 table expected {1 + len(expected_rows)} rows, found {len(rows)}")
    hdr_cols = rows[0]
    require(len(hdr_cols) == 6, f"{fname} Section 6 header expected 6 columns, got {len(hdr_cols)}")
    require("Scenario" in hdr_cols[0] and hdr_cols[1] == "Explicit Ceiling Parameters Changed", f"{fname} Col 0/1 header role mismatch: {hdr_cols[:2]!r}")
    require(hdr_cols[2] == "`phi = 0.25` Ceiling / Locked / Modular", f"{fname} Col 2 ordered header mismatch: got {hdr_cols[2]!r}")
    require(hdr_cols[3] == "`phi = 0.25` Delta (Mod)", f"{fname} Col 3 ordered header mismatch: got {hdr_cols[3]!r}")
    require(hdr_cols[4] == "`phi = 0.50` Ceiling / Locked / Modular", f"{fname} Col 4 ordered header mismatch: got {hdr_cols[4]!r}")
    require(hdr_cols[5] == "`phi = 0.50` Delta (Mod)", f"{fname} Col 5 ordered header mismatch: got {hdr_cols[5]!r}")
    data_rows = rows[1:]

    b25 = p25["L3B_WAVE5_STRICT_ZERO_DRUG_BASELINE"]["modular_k100_exact"]
    b50 = p50["L3B_WAVE5_STRICT_ZERO_DRUG_BASELINE"]["modular_k100_exact"]

    for idx, (label_token, sc_key, exact_col1) in enumerate(expected_rows):
        cols = data_rows[idx]
        require(len(cols) == 6, f"{fname} row {idx} expected 6 columns, got {len(cols)}")
        require(label_token in cols[0], f"{fname} row {idx} label mismatch: expected {label_token!r} in {cols[0]!r}")
        require(cols[1] == exact_col1, f"{fname} row {sc_key} exact Col 1 ceiling spec mismatch: got {cols[1]!r} vs expected {exact_col1!r}")

        r25 = p25[sc_key]
        r50 = p50[sc_key]

        exp_25_tri = [_fmt_pct(r25["ceiling_exact"]), _fmt_pct(r25["locked_exact"]), _fmt_pct(r25["modular_k100_exact"])]
        got_25_tri = re.findall(r"[+-]?\d+\.\d{2}%", cols[2])
        require(got_25_tri == exp_25_tri, f"{fname} row {sc_key} phi=0.25 triple mismatch: got {got_25_tri} vs {exp_25_tri}")

        exp_25_d = _fmt_delta_pp(r25["modular_k100_exact"], b25)
        got_25_d = re.findall(r"[+-]?\d+\.\d{2}\s+pp", cols[3])
        require(got_25_d == [exp_25_d], f"{fname} row {sc_key} phi=0.25 delta mismatch: got {got_25_d} vs [{exp_25_d}]")

        exp_50_tri = [_fmt_pct(r50["ceiling_exact"]), _fmt_pct(r50["locked_exact"]), _fmt_pct(r50["modular_k100_exact"])]
        got_50_tri = re.findall(r"[+-]?\d+\.\d{2}%", cols[4])
        require(got_50_tri == exp_50_tri, f"{fname} row {sc_key} phi=0.50 triple mismatch: got {got_50_tri} vs {exp_50_tri}")

        exp_50_d = _fmt_delta_pp(r50["modular_k100_exact"], b50)
        got_50_d = re.findall(r"[+-]?\d+\.\d{2}\s+pp", cols[5])
        require(got_50_d == [exp_50_d], f"{fname} row {sc_key} phi=0.50 delta mismatch: got {got_50_d} vs [{exp_50_d}]")


def _find_single_line(text: str, marker: str, label: str) -> str:
    hits = [ln for ln in text.splitlines() if marker in ln]
    require(len(hits) == 1, f"Expected exactly 1 line containing {marker!r} in {label}, found {len(hits)}")
    return hits[0]


def verify_draft_b_band_and_discount_lines(
    txt_b: str,
    omega_band: dict[str, Any],
    b_disc: dict[str, Any],
) -> None:
    """Bind BOTH phi=0.25 AND phi=0.50 omega [0,1] band endpoints & Design B discount ranges on exact labeled lines."""
    for phi_key, marker in (("phi_0p25_central", "**`phi = 0.25` overlap band"), ("phi_0p50_harsh_stress", "**`phi = 0.50` overlap band")):
        ln = _find_single_line(txt_b, marker, "Draft B")
        om00 = omega_band[phi_key]["omega_0p00"]
        om10 = omega_band[phi_key]["omega_1p00"]
        exp_pcts = [
            _fmt_pct(om10["COMBINED_ABC_FIXED_CEIL_LOW"]["modular_k100_exact"]),
            _fmt_pct(om00["COMBINED_ABC_FIXED_CEIL_LOW"]["modular_k100_exact"]),
            _fmt_pct(om10["COMBINED_ABC_FIXED_CEIL_HIGH"]["modular_k100_exact"]),
            _fmt_pct(om00["COMBINED_ABC_FIXED_CEIL_HIGH"]["modular_k100_exact"]),
            _fmt_pct(om10["COMBINED_ABC_CEIL_LIFT_LOW"]["modular_k100_exact"]),
            _fmt_pct(om00["COMBINED_ABC_CEIL_LIFT_LOW"]["modular_k100_exact"]),
            _fmt_pct(om10["COMBINED_ABC_CEIL_LIFT_HIGH"]["modular_k100_exact"]),
            _fmt_pct(om00["COMBINED_ABC_CEIL_LIFT_HIGH"]["modular_k100_exact"]),
        ]
        got_pcts = re.findall(r"[+-]?\d+\.\d{2}%", ln)
        require(got_pcts == exp_pcts, f"Draft B {phi_key} omega [0,1] band line mismatch: got {got_pcts} vs {exp_pcts}")

    for phi_key, marker in (("phi_0p25_central", "**`phi = 0.25` Design B discount"), ("phi_0p50_harsh_stress", "**`phi = 0.50` Design B discount")):
        ln = _find_single_line(txt_b, marker, "Draft B")
        d0 = b_disc[phi_key]["discount_0pct_B2_base_WT_TYK2"]
        d100 = b_disc[phi_key]["discount_100pct_full_redundancy"]
        exp_pcts = [
            _fmt_pct(d100["fixed_low_mod_exact"]),
            _fmt_pct(d0["fixed_low_mod_exact"]),
            _fmt_pct(d100["fixed_high_mod_exact"]),
            _fmt_pct(d0["fixed_high_mod_exact"]),
            _fmt_pct(d100["ceil_lift_low_mod_exact"]),
            _fmt_pct(d0["ceil_lift_low_mod_exact"]),
            _fmt_pct(d100["ceil_lift_high_mod_exact"]),
            _fmt_pct(d0["ceil_lift_high_mod_exact"]),
        ]
        got_pcts = re.findall(r"[+-]?\d+\.\d{2}%", ln)
        require(got_pcts == exp_pcts, f"Draft B {phi_key} Design B discount line mismatch: got {got_pcts} vs {exp_pcts}")


def _md_cells(row: str, label: str) -> list[str]:
    s = row.strip()
    require(s.startswith("|") and s.endswith("|"), f"Expected Markdown table row for {label}")
    return [c.strip() for c in s.strip("|").split("|")]


def verify_promoted_table_scalars(receipt: dict[str, Any], draft_texts: dict[str, str]) -> None:
    """Bind key promoted raw-to-table scalars across Drafts A-D directly to their exact Markdown table cells."""
    ev = receipt["phase1_frozen_evaluations"]

    # Draft A: Nintedanib Pure-P5 safety rank #5/7, vascular #6/7 (Col 3)
    p5 = ev["pure_p5_ec_drug_rescue"]
    safety_rank = [k for k, _ in sorted(p5.items(), key=lambda kv: kv[1]["composite"]["pre_iec_safety_score"], reverse=True)].index("PURE_P5_EC_IFNG__Nintedanib") + 1
    vasc_rank = [k for k, _ in sorted(p5.items(), key=lambda kv: kv[1]["composite"]["vascular_rescue_score"], reverse=True)].index("PURE_P5_EC_IFNG__Nintedanib") + 1
    require(safety_rank == 5 and vasc_rank == 6, "Unexpected Nintedanib Pure-P5 rank in receipt")
    cols_a_nin = _md_cells(_find_single_line(draft_texts["A"], "| **Nintedanib (`135423438`", "Draft A"), "Draft A Nintedanib")
    require(f"`#{safety_rank}/7`" in cols_a_nin[3] and f"`#{vasc_rank}/7`" in cols_a_nin[3], "Draft A Nintedanib Pure-P5 rank cell mismatch")

    # Draft B: Baricitinib & Upadacitinib Pure-P5 NR (<0.05) (Col 1), S1B (Col 2), Baricitinib NK GZMB (+0.050 / -0.087) (Col 4)
    s1 = ev["screen1_iec_vascular_and_pre_iec"]
    bar_s1b = s1["IEC_IFNG_RESCUE_DRUG__Baricitinib"]["composite"]
    upa_s1b = s1["IEC_IFNG_RESCUE_DRUG__Upadacitinib"]["composite"]
    bar_gzmb = ev["extra_immune_safety"]["NK_SAFETY__Baricitinib"]["panels"]["nk_activating_cytotoxic_bad"]["nonzero_panel_genes"]["GZMB"]
    cols_b_bar = _md_cells(_find_single_line(draft_texts["B"], "| **Baricitinib**", "Draft B"), "Draft B Baricitinib")
    cols_b_upa = _md_cells(_find_single_line(draft_texts["B"], "| **Upadacitinib**", "Draft B"), "Draft B Upadacitinib")
    require(cols_b_bar[1].count("NR (<0.05)") >= 2 and cols_b_upa[1].count("NR (<0.05)") >= 2, "Draft B unreported F3/SERPINE1 cell must tag NR (<0.05) twice")
    require(f"{bar_s1b['vascular_rescue_score']:+.4f}" in cols_b_bar[2] and f"{bar_s1b['pre_iec_safety_score']:+.4f}" in cols_b_bar[2], "Draft B Baricitinib S1B cell mismatch")
    require(f"{bar_gzmb['s1_norm_rank']:+.3f}" in cols_b_bar[4] and f"{bar_gzmb['s2_lfc']:+.3f}" in cols_b_bar[4], "Draft B Baricitinib NK GZMB cell mismatch")
    require(f"{upa_s1b['vascular_rescue_score']:+.4f}" in cols_b_upa[2] and f"{upa_s1b['pre_iec_safety_score']:+.4f}" in cols_b_upa[2], "Draft B Upadacitinib S1B cell mismatch")

    # Draft C: MAP3K7 stressed self_kd (-0.321 in Col 3) + BCL2L11/PMAIP1/BBC3/JAK2 promoted scalars
    s2 = ev["screen2_beta_stressed_and_resting"]
    s2r = ev["screen2_resting_h3_top6_followup"]
    map3k7_skd = s2["BETA_CM_STRESSED_CRISPRI__MAP3K7"]["extra"]["self_kd_s1_norm_rank"]
    cols_c_map = _md_cells(_find_single_line(draft_texts["C"], "| **`MAP3K7`**", "Draft C"), "Draft C MAP3K7")
    require(f"{map3k7_skd:+.3f}" in cols_c_map[3], f"Draft C MAP3K7 Col 3 stressed self_kd mismatch (expected {map3k7_skd:+.3f})")

    bim_s_imm = s2["BETA_CM_STRESSED_CRISPRI__BCL2L11"]["panels"]["immune_chemokine_mhc_bad"]["nonzero_panel_genes"]
    bim_r_imm = s2r["BETA_RESTING_CRISPRI__BCL2L11"]["panels"]["immune_chemokine_mhc_bad"]["nonzero_panel_genes"]
    cols_c_bim = _md_cells(_find_single_line(draft_texts["C"], "| **`BCL2L11`**", "Draft C"), "Draft C BCL2L11")
    require(
        f"HLA-E {bim_s_imm['HLA-E']['s1_norm_rank']:+.3f}" in cols_c_bim[4]
        and f"HLA-C {bim_s_imm['HLA-C']['s1_norm_rank']:+.3f}" in cols_c_bim[4]
        and f"HLA-E {bim_r_imm['HLA-E']['s1_norm_rank']:+.3f}" in cols_c_bim[4]
        and f"HLA-C {bim_r_imm['HLA-C']['s1_norm_rank']:+.3f}" in cols_c_bim[4]
        and f"HLA-B {bim_r_imm['HLA-B']['s1_norm_rank']:+.3f}" in cols_c_bim[4],
        "Draft C BCL2L11 Col 4 HLA-E/HLA-C/HLA-B watch-item scalar mismatch",
    )

    noxa_s_imm = s2["BETA_CM_STRESSED_CRISPRI__PMAIP1"]["panels"]["immune_chemokine_mhc_bad"]["nonzero_panel_genes"]
    noxa_r_imm = s2r["BETA_RESTING_CRISPRI__PMAIP1"]["panels"]["immune_chemokine_mhc_bad"]["nonzero_panel_genes"]
    cols_c_noxa = _md_cells(_find_single_line(draft_texts["C"], "| **`PMAIP1`**", "Draft C"), "Draft C PMAIP1")
    require(
        f"HLA-C {noxa_s_imm['HLA-C']['s1_norm_rank']:+.3f}" in cols_c_noxa[4]
        and f"HLA-E {noxa_s_imm['HLA-E']['s1_norm_rank']:+.3f}" in cols_c_noxa[4]
        and f"HLA-B {noxa_r_imm['HLA-B']['s1_norm_rank']:+.3f}" in cols_c_noxa[4]
        and f"HLA-C {noxa_r_imm['HLA-C']['s1_norm_rank']:+.3f}" in cols_c_noxa[4]
        and f"HLA-E {noxa_r_imm['HLA-E']['s1_norm_rank']:+.3f}" in cols_c_noxa[4],
        "Draft C PMAIP1 Col 4 HLA-B/HLA-C/HLA-E watch-item scalar mismatch",
    )

    bbc3_r = s2r["BETA_RESTING_CRISPRI__BBC3"]
    cols_c_bbc3 = _md_cells(_find_single_line(draft_texts["C"], "| **`BBC3`**", "Draft C"), "Draft C BBC3")
    require(
        f"{bbc3_r['composite']['ring1_safety_score']:+.4f}" in cols_c_bbc3[2]
        and f"{bbc3_r['panels']['identity_gsis_good']['mean_s1_norm_rank']:+.4f}" in cols_c_bbc3[2],
        "Draft C BBC3 Col 2 resting ring1_safety/identity_mean mismatch",
    )

    # Verify Draft C stressed immune_bad composite share disclosures directly from receipt
    for g, marker in (("PMAIP1", "78.3%"), ("JAK2", "95.8%"), ("BCL2L11", "193.4%")):
        st = s2[f"BETA_CM_STRESSED_CRISPRI__{g}"]
        share = 100.0 * (-st["panels"]["immune_chemokine_mhc_bad"]["mean_s1_norm_rank"]) / st["composite"]["h3_bystander_rescue_score"]
        require(f"{share:.1f}%" == marker and marker in draft_texts["C"], f"Draft C {g} immune_bad share mismatch ({share:.1f}%)")

    # Draft D: PVR resting self_kd (-0.466 in Col 3) and TNFRSF1A stressed self_kd (-0.227 in Col 3)
    pvr_rkd = s2["BETA_RESTING_CRISPRI__PVR"]["extra"]["self_kd_s1_norm_rank"]
    tnf_skd = s2["BETA_CM_STRESSED_CRISPRI__TNFRSF1A"]["extra"]["self_kd_s1_norm_rank"]
    cols_d_pvr = _md_cells(_find_single_line(draft_texts["D"], "| **`PVR` (`CD155`)**", "Draft D"), "Draft D PVR")
    cols_d_tnf = _md_cells(_find_single_line(draft_texts["D"], "| **`STAT1` & `TNFRSF1A`**", "Draft D"), "Draft D STAT1/TNFRSF1A")
    require(f"{pvr_rkd:+.3f}" in cols_d_pvr[3], f"Draft D PVR Col 3 resting self_kd mismatch (expected {pvr_rkd:+.3f})")
    require(f"{tnf_skd:+.3f}" in cols_d_tnf[3], f"Draft D TNFRSF1A Col 3 stressed self_kd mismatch (expected {tnf_skd:+.3f})")


def verify_local_sources(receipt: dict[str, Any], project_root: Path) -> None:
    """Explicit local-source mode: open every file in source_file_sha256_manifest, verify bytes & SHA-256, and cross-check NCBI snapshot."""
    src_man = receipt["source_file_sha256_manifest"]
    for rel, meta in src_man.items():
        fp = project_root / rel
        require(fp.is_file(), f"Missing local source file: {rel}")
        data = fp.read_bytes()
        require(len(data) == meta["bytes"], f"Byte size mismatch for {rel}: {len(data)} != {meta['bytes']}")
        got_sha = hashlib.sha256(data).hexdigest()
        require(got_sha == meta["sha256"], f"SHA-256 mismatch for {rel}: {got_sha} != {meta['sha256']}")

    snap_rel = receipt["claim_to_source_map"]["snapshot_file_relpath"]
    snap = load_strict_json((project_root / snap_rel).read_text(encoding="utf-8"))
    snap_recs = snap["records"]
    for pmid, reg_rec in receipt["verified_pubmed_registry"].items():
        require(pmid in snap_recs, f"PMID {pmid} missing from authoritative snapshot {snap_rel}")
        sr = snap_recs[pmid]
        require(reg_rec["title"] == sr["title"].strip(), f"Title mismatch vs NCBI snapshot for PMID:{pmid}")
        require(reg_rec["doi"] == sr["doi"], f"DOI mismatch vs NCBI snapshot for PMID:{pmid}")
        require(reg_rec["journal"] == sr["journal"], f"Journal mismatch vs NCBI snapshot for PMID:{pmid}")
        require(reg_rec["pubtypes_ncbi"] == sr["pubtypes_ncbi"], f"pubtypes_ncbi mismatch for PMID:{pmid}")


def main() -> None:
    ap = argparse.ArgumentParser(description="Fail-closed zero-GPU verifier for CellGemma-Islet v0.9.0.")
    ap.add_argument(
        "--verify-local-sources",
        action="store_true",
        help="Rehash all 31 local files listed in source_file_sha256_manifest relative to the parent directory and cross-check all 60 dated NLM snapshot records.",
    )
    args = ap.parse_args()

    require(RECEIPT_PATH.is_file(), f"Missing receipt file {RECEIPT_PATH}")
    patterns = _build_portable_preflight_hygiene_patterns()

    # 1. Strict JSON + nonfinite guard + exact payload & file SHA-256
    raw_bytes = RECEIPT_PATH.read_bytes()
    receipt_file_sha = hashlib.sha256(raw_bytes).hexdigest()
    raw_text = raw_bytes.decode("utf-8")
    receipt = load_strict_json(raw_text)

    claimed_sha = receipt["portable_payload_sha256"]
    payload_no_hash = {k: v for k, v in receipt.items() if k != "portable_payload_sha256"}
    canon = json.dumps(payload_no_hash, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
    actual_sha = hashlib.sha256(canon.encode("utf-8")).hexdigest()
    require(actual_sha == claimed_sha, f"Payload SHA-256 mismatch: {actual_sha} != {claimed_sha}")
    require(receipt["schema_version"] == "openislet.cellgemma_islet_provenance.v0.9.0", "Unexpected schema_version")
    print(f"[PASS 1/10] Strict JSON + nonfinite guard + SHA-256 verified (payload={actual_sha[:16]}..., file={receipt_file_sha[:16]}...)")

    # 2. Fixed host-independent portable preflight hygiene across ALL 6 runtime inputs + 31-file manifest syntax / optional local rehash
    check_public_hygiene(raw_text, RECEIPT_PATH.name, patterns)
    check_decoded_json_hygiene(receipt, f"{RECEIPT_PATH.name}:decoded", patterns)
    check_public_hygiene(VERIFIER_PATH.read_text(encoding="utf-8"), VERIFIER_PATH.name, patterns)
    draft_texts: dict[str, str] = {}
    for did, fname in IIP_DRAFT_FILES.items():
        dp = (HERE / fname) if (HERE / fname).is_file() else (HERE.parent / "docs" / fname)
        require(dp.is_file(), f"Missing draft file {fname}")
        txt = dp.read_text(encoding="utf-8")
        check_public_hygiene(txt, fname, patterns)
        draft_texts[did] = txt
    require(receipt["evidence_tier"] == "cellgemma_e4b_in_silico_prior", "Unexpected evidence_tier")
    require(receipt["live_headline_delta_pp_today"] == 0.0, "live_headline_delta_pp_today must be 0.0")
    src_man = receipt["source_file_sha256_manifest"]
    require(len(src_man) == 31, f"Expected 31 listed local dependencies in manifest, got {len(src_man)}")
    for req_dep in (
        "STEP0_PREREGISTERED_BENCHMARK_PLAN.md",
        "build_cellgemma_islet_receipt.py",
        "processed/gse254985_d20276_full.npz",
        "processed/gse254985_d20276_full_summary.json",
        "tmp_pubmed/ncbi_60_authoritative_snapshot.json",
    ):
        require(req_dep in src_man, f"Missing required dependency in source_file_sha256_manifest: {req_dep}")
    for rel_k, meta in src_man.items():
        require(bool(re.fullmatch(r"[0-9a-f]{64}", meta["sha256"])), f"Invalid source SHA-256 syntax for {rel_k}")
        require(isinstance(meta["bytes"], int) and meta["bytes"] > 0, f"Invalid byte size for {rel_k}")
    if args.verify_local_sources:
        verify_local_sources(receipt, HERE.parent)
        print("[PASS 2/10] Host-independent preflight hygiene (6/6 inputs + decoded JSON) AND local-source rehash verified (31/31 listed files + 60/60 dated NLM snapshot parity)")
    else:
        print("[PASS 2/10] Host-independent preflight hygiene passed on 6/6 inputs (incl. verifier + decoded JSON) + 31-file manifest syntax checked (pass --verify-local-sources to rehash listed files)")

    # 3. Track-specific falsifying Step-0 G1 checks (T1 >=0.25/0.25; T2 >=0.15/0.20), 3x1 vs 5x3, 8/8 RQC targets in Draft C, & summed embedded per-file cap counts
    s0 = receipt["step0_benchmark_audit"]
    require(sum(s0["generation_count_breakdown"].values()) == s0["total_benchmark_and_phase1_generations"] == 534, "Generation count mismatch")
    gsp = s0["generation_evidence_split"]
    require(gsp["per_draw_truncated_gene_array_backed_in_raw_jsons"] == 498 and gsp["author_recorded_summary_without_per_draw_arrays"] == 36, "Generation split mismatch")
    gcap = s0["generation_cap_and_truncation_audit"]
    by_rf = gcap["by_raw_file"]
    s0_cap_sum = sum(v["capped_runs"] for k, v in by_rf.items() if k.startswith("step0_"))
    s0_tot_sum = sum(v["total_runs_with_token_counts"] for k, v in by_rf.items() if k.startswith("step0_"))
    p1_cap_sum = sum(v["capped_runs"] for k, v in by_rf.items() if k.startswith("phase1_"))
    p1_tot_sum = sum(v["total_runs_with_token_counts"] for k, v in by_rf.items() if k.startswith("phase1_"))
    require([s0_cap_sum, s0_tot_sum] == gcap["step0_4096_token_cap_hits"] == [142, 147], "Embedded per-file Step-0 cap sum mismatch")
    require([p1_cap_sum, p1_tot_sum] == gcap["phase1_retained_3072_token_cap_hits"] == [272, 351], "Embedded per-file Phase-1 cap sum mismatch")
    require(gcap["phase1_unknown_stopping_reason_runs"] == 36, "Unknown stopping-reason count mismatch")
    bf16 = s0["bf16_vs_mlx8_parity_receipt"]
    require(bf16["evidence_status"] == "author_recorded_summary_without_per_draw_portable_arrays", "BF16 evidence status missing")
    dv = s0["domain_verdicts"]
    p5_dv = dv["pure_human_islet_endothelium_p5_ifng"]
    require(p5_dv["status"] == "PASS_DIRECTIONAL_MICROBENCHMARK" and p5_dv["n_fdr05_genes_in_p5_summary"] == 0, "Pure P5 metadata mismatch")
    require(p5_dv["regime4"]["top100_roc_auc_s2"] >= 0.90 and p5_dv["regime1"]["top100_roc_auc_s2"] < 0.70, "P5 R4/R1 contrast missing")
    c1_beta = dv["beta_alpha_multi_cytokine_and_synergy_c1"]["gse254985_beta_cm"]
    flex_dv = dv["tenx_flex_probe_capture_endocrine"]
    flex_6_keys = ("gse237448_beta_ifng", "gse237448_beta_il1b", "gse237448_beta_il1bifng", "gse237448_beta_cm", "gse237448_beta_bfa", "gse237448_beta_tg")
    flex_6_mean_r = sum(flex_dv[k]["pearson_r_r4"] for k in flex_6_keys) / 6.0
    flex_6_mean_nr = sum(flex_dv[k]["nr_vs_b1_r4"] for k in flex_6_keys) / 6.0
    rqc_dv = dv["endoc_bh1_3p_crispri_zero_leakage"]
    rec_g1 = rqc_dv["preregistered_g1_reconciliation"]
    require(
        rec_g1["preregistered_input_pseudobulks"] == 5
        and rec_g1["preregistered_stochastic_draws_per_pseudobulk"] == 3
        and rec_g1["preregistered_generations_per_condition_per_regime"] == 15
        and rec_g1["executed_input_pseudobulks"] == 3
        and rec_g1["executed_stochastic_draws_per_pseudobulk"] == 1
        and rec_g1["executed_generations_per_condition_per_regime"] == 3,
        "5x3 -> 3x1 sampling-plan deviation fields mismatch",
    )
    require(rec_g1["superseding_preregistration_issued"] is False, "superseding_preregistration_issued must be False")
    rqc_targets_raw = {k.split("__")[-1]: v["pearson_r_r4"] for k, v in rqc_dv["all_8_rqc_targets"].items()}
    rqc_nr_raw = [v["nr_vs_b1_r4"] for v in rqc_dv["all_8_rqc_targets"].values()]
    require(len(rqc_targets_raw) == 8, "Expected 8 evaluated RQC targets")
    t1_r, t1_nr, t1_b3a = c1_beta["pearson_r_r4"], c1_beta["nr_vs_b1_r4"], c1_beta["b3a_r"]
    t2_mean_r = sum(rqc_targets_raw.values()) / 8.0
    t2_mean_nr = sum(rqc_nr_raw) / 8.0
    t1_r_floor = rec_g1["preregistered_track1_g1_pearson_floor"]
    t1_nr_floor = rec_g1["preregistered_track1_g1_norm_recovery_floor"]
    t2_r_floor = rec_g1["preregistered_track2_g1_pearson_floor"]
    t2_nr_floor = rec_g1["preregistered_track2_g1_norm_recovery_floor"]
    require(abs(t1_r_floor - 0.25) <= 1e-12 and abs(t1_nr_floor - 0.25) <= 1e-12, "Track-1 locked G1 floors must be 0.25/0.25")
    require(abs(t2_r_floor - 0.15) <= 1e-12 and abs(t2_nr_floor - 0.20) <= 1e-12, "Track-2 locked G1 floors must be 0.15/0.20")
    require(abs(t1_r - rec_g1["track1_post_cutoff_beta_cm_r4_pearson_r"]) <= 1e-6, "Track-1 beta CM r mismatch")
    require(abs(t1_nr - rec_g1["track1_post_cutoff_beta_cm_r4_norm_recovery"]) <= 1e-6, "Track-1 beta CM norm_recovery mismatch")
    require(abs(t1_b3a - rec_g1["track1_post_cutoff_beta_cm_b3a_naive_mean_shift_r"]) <= 1e-6, "Track-1 B3a mismatch")
    require(abs(flex_6_mean_r - rec_g1["track1_flex_6cond_beta_r4_mean_pearson_r"]) <= 1e-6, "Track-1 6-cond Flex mean r mismatch")
    require(abs(flex_6_mean_nr - rec_g1["track1_flex_6cond_beta_r4_mean_norm_recovery"]) <= 1e-6, "Track-1 6-cond Flex mean nr mismatch")
    require(abs(t2_mean_r - rec_g1["all_8_rqc_r4_mean_pearson_r"]) <= 1e-6, "RQC 8-target mean r mismatch")
    require(abs(t2_mean_nr - rec_g1["all_8_rqc_r4_mean_norm_recovery"]) <= 1e-5, "RQC 8-target mean norm_recovery mismatch")
    # Track-specific necessary G1 conditions (plan:159): Track 1 requires >=0.25/0.25 on post-cutoff CM AND 6-cond aggregate (separately checking G3 r < B3a); Track 2 requires >=0.15/0.20
    derived_t1_g1_necessary = (t1_r >= t1_r_floor) and (t1_nr >= t1_nr_floor) and (flex_6_mean_r >= t1_r_floor) and (flex_6_mean_nr >= t1_nr_floor)
    derived_t1_g3_beats_b3a = t1_r > t1_b3a
    derived_t2_g1_necessary = (t2_mean_r >= t2_r_floor) and (t2_mean_nr >= t2_nr_floor)
    derived_hard_stop = (not derived_t1_g1_necessary) and (not derived_t2_g1_necessary)
    require(derived_t1_g1_necessary is False and derived_t1_g3_beats_b3a is False and rec_g1["track1_cleared_preregistered_g1"] is False, "Track-1 necessary G1/G3 falsification mismatch")
    require(derived_t2_g1_necessary is False and rec_g1["cleared_preregistered_g1_floor"] is False, "Track-2 necessary G1 falsification mismatch")
    require(derived_hard_stop is True and rec_g1["hard_stop_triggered_under_locked_plan"] is True, "Derived Step-0 hard-stop mismatch")
    for tg, rv in sorted(rqc_targets_raw.items()):
        require(abs(rec_g1["evaluated_8_rqc_r4_pearson_by_target"][tg] - rv) <= 1e-4, f"RQC target {tg} map mismatch")
        tok = f"`{tg} {rv:+.4f}`"
        require(tok in draft_texts["C"], f"Draft C missing verified RQC target/score token {tok}")
    require(dv["beta_alpha_multi_cytokine_and_synergy_c1"]["status"] == "KILLED" and flex_dv["status"] == "KILLED", "Hard-kill check failed")
    print("[PASS 3/10] Track-specific Step-0 G1 falsifiers (T1 0.25/0.25, T2 0.15/0.20, 3x1 vs 5x3), 8/8 RQC targets in Draft C, & embedded per-file cap sums (142/147, 272/351, 36 unknown) verified")

    # 4. Panel-gene (S1 + S2 + n_up/n_down) & composite checks across ALL 139 evaluations (120 4-decimal NPZ + 19 thresholded raw-JSON residual accounting)
    scoring_panels = receipt["scoring_panels"]
    tot = {
        "n": 0,
        "full_vec": 0,
        "thresh": 0,
        "full_genes": 0,
        "thresh_panels": 0,
        "thresh_s1_nz": 0,
        "thresh_s2_nz": 0,
        "thresh_prof_s1_nz": 0,
        "thresh_prof_s2_nz": 0,
    }
    for grp_name, grp in receipt["phase1_frozen_evaluations"].items():
        for item_name, item in grp.items():
            c = check_item_full(f"{grp_name}:{item_name}", item, scoring_panels)
            tot["n"] += 1
            for k in ("full_vec", "thresh", "full_genes", "thresh_panels", "thresh_s1_nz", "thresh_s2_nz", "thresh_prof_s1_nz", "thresh_prof_s2_nz"):
                tot[k] += c[k]
    cov = receipt["panel_evidence_coverage_audit"]
    require(tot["n"] == cov["total_profiles"] == 139, f"Expected 139 profiles, got {tot['n']}")
    require(tot["full_vec"] == cov["exact_full_vector_profiles"] == 120, "Full-vector count mismatch")
    require(tot["full_genes"] == cov["exact_full_vector_nonzero_panel_genes"] == 6263, "Full-vector gene count mismatch")
    require(tot["thresh"] == cov["thresholded_raw_json_profiles"] == 19, "Thresholded profile count mismatch")
    require(tot["thresh_panels"] == cov["thresholded_raw_json_panels_total"] == cov["thresholded_raw_json_panels_flagged_unverifiable_below_0p05"] == 70, "Thresholded flagged panel count mismatch")
    require(tot["thresh_s1_nz"] == cov["thresholded_raw_json_panels_with_nonzero_s1_residual"] == 46 and tot["thresh_prof_s1_nz"] == cov["thresholded_raw_json_profiles_with_nonzero_s1_residual"] == 17, "Nonzero S1 residual count mismatch")
    require(tot["thresh_s2_nz"] == cov["thresholded_raw_json_panels_with_nonzero_s2_residual"] == 70 and tot["thresh_prof_s2_nz"] == cov["thresholded_raw_json_profiles_with_nonzero_s2_residual"] == 19, "Nonzero S2 residual count mismatch")
    print("[PASS 4/10] 139/139 S1+S2+n_up/n_down & composite checks passed: 120/139 4-dec NPZ (6,263 genes) + 19/139 thresholded residual accounting (70/70 flagged; 46/70 S1 nz [17/19]; 70/70 S2 nz [19/19])")

    # 5. Honest non-duplicated retrospective concordance audit (15 flagged + 8 missed/discrepant = 23 unique entries; EVERY scalar bound in Draft C!)
    cal = receipt["graveyard_retrospective_concordance_audit"]
    require(cal["audit_classification"] == "retrospective_concordance_not_prespecified_before_inference", "Missing retrospective concordance label")
    caught = cal["adversely_flagged_controls"]
    missed = cal["missed_or_discrepant_controls"]
    require(len(caught) == 15 and len(missed) == 8, f"Concordance counts mismatch: {len(caught)} / {len(missed)}")
    require("resting_TXNIP_safety" in caught and not any("resting_TXNIP" in k for k in missed), "resting_TXNIP duplicate check failed")
    ln_c_flagged = _find_single_line(draft_texts["C"], "Adversely Flagged by Model (`15`", "Draft C concordance flagged")
    ln_c_missed = _find_single_line(draft_texts["C"], "Missed or Discrepant Model Flags (`8`", "Draft C concordance missed")
    for k_f, v_f in caught.items():
        # Match either 3-decimal or 4-decimal exact signed formatting next to key in Draft C
        ok_f = (f"`{k_f}` (`{v_f:+.3f}`" in ln_c_flagged) or (f"`{k_f}` (`{v_f:+.4f}`" in ln_c_flagged) or (f"`{k_f}` (`{v_f:+.3f}`," in ln_c_flagged) or (f"`{k_f}` (`{v_f:+.4f}`," in ln_c_flagged)
        require(ok_f, f"Draft C flagged concordance mismatch for {k_f}: expected {v_f:+.3f} or {v_f:+.4f}")
    missed_short_map = {
        "stressed_GAD2_h3_missed_GY007": "stressed_GAD2_h3",
        "stressed_TXNIP_h3_missed_GY026_conditional_split": "stressed_TXNIP_h3",
        "stressed_FADD_h3_missed_GY012": "stressed_FADD_h3",
        "resting_FADD_safety_missed_GY012": "resting_FADD_safety",
        "resting_TNFAIP3_safety_missed_GY007_conditional_split": "resting_TNFAIP3_safety",
        "stressed_STAT1_h3_missed_GY001_conditional_split": "stressed_STAT1_h3",
        "resting_CIITA_safety_model_adverse_flag_on_accepted_core_edit": "resting_CIITA_safety",
        "resting_EC_Nintedanib_safety_positive_S1A_conditional_split": "resting_EC_Nintedanib_safety",
    }
    for k_m, v_m in missed.items():
        short_m = missed_short_map[k_m]
        ok_m = (f"`{short_m}` (`{v_m:+.3f}`" in ln_c_missed) or (f"`{short_m}` (`{v_m:+.4f}`" in ln_c_missed)
        require(ok_m, f"Draft C missed concordance mismatch for {short_m}: expected {v_m:+.3f} or {v_m:+.4f}")
    print("[PASS 5/10] Retrospective Graveyard concordance verified & ALL 23/23 scalars bound in Draft C (15 flagged + 8 missed/discrepant; zero duplicates)")

    # 6. ALL 36 core + 40 omega [0,1] + 24 Design B discount 2^20 rows + IIP-0042 parity + full Design-A firewall!
    sens = receipt["portfolio_2pow20_prospective_sensitivity"]
    omega_band = sens["combined_abc_omega_h4_sensitivity_band"]
    b_disc = sens["design_b_tyk2_discount_sensitivity"]
    n_rows = 0
    for phi_key in ("phi_0p25_central", "phi_0p50_harsh_stress"):
        block = sens[phi_key]
        l3b_row = block["L3B_WAVE5_STRICT_ZERO_DRUG_BASELINE"]
        base_arms = l3b_row["inputs"]["arms"]
        for tag, row_key in (("L1", "L1_SHIPPED_5ARM_BASELINE"), ("L3B", "L3B_WAVE5_STRICT_ZERO_DRUG_BASELINE")):
            exp_c, exp_l, exp_m = SHIPPED_IIP0042_EXACT[phi_key][tag]
            r = block[row_key]
            require(abs(r["ceiling_exact"] - exp_c) <= 1e-12 and abs(r["locked_exact"] - exp_l) <= 1e-12 and abs(r["modular_k100_exact"] - exp_m) <= 1e-12, f"{phi_key}:{tag} parity")

        for sc_name, row in block.items():
            got = eval_5arm_from_inputs(row["inputs"])
            for k in ("ceiling_exact", "locked_exact", "modular_k100_exact", "design_a_standalone_exact", "p_h2_a1_d1_exact", "p_h4_a1_exact"):
                require(abs(got[k] - row[k]) <= 1e-12, f"{phi_key}:{sc_name} {k}")
            require(abs(row["composite_ceiling_pct"] - round(100.0 * got["ceiling_exact"], 4)) <= 1e-9, f"{phi_key}:{sc_name} ceil display")
            require(abs(row["locked_pct"] - round(100.0 * got["locked_exact"], 4)) <= 1e-9, f"{phi_key}:{sc_name} lock display")
            require(abs(row["modular_k100_pct"] - round(100.0 * got["modular_k100_exact"], 4)) <= 1e-9, f"{phi_key}:{sc_name} mod display")
            require(abs(row["delta_locked_vs_l3b_pp"] - round(100.0 * (got["locked_exact"] - l3b_row["locked_exact"]), 4)) <= 1e-9, f"{phi_key}:{sc_name} d_lock")
            require(abs(row["delta_mod100_vs_l3b_pp"] - round(100.0 * (got["modular_k100_exact"] - l3b_row["modular_k100_exact"]), 4)) <= 1e-9, f"{phi_key}:{sc_name} d_mod")
            for h in range(4):
                require(abs(got["design_a_4_marginals_exact"][h] - row["design_a_4_marginals_exact"][h]) <= 1e-12, f"{phi_key}:{sc_name} A_H{h+1}")
            for c_idx in range(4):
                require(abs(got["design_a_d_h2_joint_4cell_exact"][c_idx] - row["design_a_d_h2_joint_4cell_exact"][c_idx]) <= 1e-12, f"{phi_key}:{sc_name} H2_AD[{c_idx}]")

            ref_key = None
            if sc_name.startswith(("IIP_A_", "IIP_B_")):
                ref_key = "L3B_WAVE5_STRICT_ZERO_DRUG_BASELINE"
            elif sc_name.startswith("COMBINED_ABC_"):
                ref_key = sc_name.replace("COMBINED_ABC_", "IIP_C_GENETIC_")
            if ref_key is not None:
                ref_row = block[ref_key]
                require(row["inputs"]["design_a_firewalled"] is True and row["inputs"]["firewall_reference_row"] == ref_key, f"{phi_key}:{sc_name} firewall metadata")
                require(abs(row["inputs"]["c4_pouch_a"] - ref_row["inputs"]["c4_pouch_a"]) <= 1e-12, f"Design-A c4_pouch_a firewall leak in {phi_key}:{sc_name}")
                require(abs(row["inputs"]["c2_a"] - ref_row["inputs"]["c2_a"]) <= 1e-12, f"Design-A c2_a firewall leak in {phi_key}:{sc_name}")
                require(row["inputs"]["arms"][0] == ref_row["inputs"]["arms"][0], f"Design-A arm-0 input vector leak in {phi_key}:{sc_name}")
                for h in range(4):
                    require(abs(got["design_a_4_marginals_exact"][h] - ref_row["design_a_4_marginals_exact"][h]) <= 1e-12, f"Design-A H{h+1} leak in {phi_key}:{sc_name}")
                require(abs(got["design_a_standalone_exact"] - ref_row["design_a_standalone_exact"]) <= 1e-12, f"Design-A standalone leak in {phi_key}:{sc_name}")
                for c_idx in range(4):
                    require(abs(got["design_a_d_h2_joint_4cell_exact"][c_idx] - ref_row["design_a_d_h2_joint_4cell_exact"][c_idx]) <= 1e-12, f"Design-A H2 (A,D) leak in {phi_key}:{sc_name}")
            n_rows += 1

        # Reconstruct & verify ALL 40 omega [0,1] rows (exact + display + deltas + full omega=0.50 binding!)
        for suffix in ("FIXED_CEIL_LOW", "FIXED_CEIL_HIGH", "CEIL_LIFT_LOW", "CEIL_LIFT_HIGH"):
            ra = block[f"IIP_A_NON_A_{suffix}"]["inputs"]
            rb = block[f"IIP_B_NON_A_{suffix}"]["inputs"]
            rc = block[f"IIP_C_GENETIC_{suffix}"]["inputs"]
            rcomb = block[f"COMBINED_ABC_{suffix}"]
            for om in (0.0, 0.25, 0.50, 0.75, 1.0):
                recon_arms = []
                for arm_i in range(5):
                    if arm_i == 0:
                        recon_arms.append([base_arms[0][0], base_arms[0][1], rc["arms"][0][2], base_arms[0][3]])
                    else:
                        da = ra["arms"][arm_i][3] - base_arms[arm_i][3]
                        db = rb["arms"][arm_i][3] - base_arms[arm_i][3]
                        recon_arms.append([base_arms[arm_i][0], rb["arms"][arm_i][1], rc["arms"][arm_i][2], subadditive_overlap(base_arms[arm_i][3], da, db, om)])
                recon_inp = dict(rc)
                recon_inp["arms"] = recon_arms
                recon_inp["c2_a"], recon_inp["c2_bx"], recon_inp["c2_y"], recon_inp["c2_univ"] = rb["c2_a"], rb["c2_bx"], rb["c2_y"], rb["c2_univ"]
                recon_inp["c2_univ_base_for_a"] = rb["c2_univ_base_for_a"]
                recon_inp["c4_pouch_a"] = 0.85
                recon_inp["c4_univ"] = subadditive_overlap(0.92, ra["c4_univ"] - 0.92, rb["c4_univ"] - 0.92, om)
                c4p = subadditive_overlap(0.85, ra["c4_pouch_bx"] - 0.85, rb["c4_pouch_bx"] - 0.85, om)
                recon_inp["c4_pouch_bx"] = c4p
                recon_inp["c4_r3p"] = c4p
                got_om = eval_5arm_from_inputs(recon_inp)
                om_key = f"omega_{om:.2f}".replace(".", "p")
                rec_om = omega_band[phi_key][om_key][f"COMBINED_ABC_{suffix}"]
                require(abs(got_om["ceiling_exact"] - rec_om["ceiling_exact"]) <= 1e-12, f"omega={om} {phi_key}:{suffix} ceil")
                require(abs(got_om["locked_exact"] - rec_om["locked_exact"]) <= 1e-12, f"omega={om} {phi_key}:{suffix} lock")
                require(abs(got_om["modular_k100_exact"] - rec_om["modular_k100_exact"]) <= 1e-12, f"omega={om} {phi_key}:{suffix} mod")
                require(abs(rec_om["composite_ceiling_pct"] - round(100.0 * got_om["ceiling_exact"], 4)) <= 1e-9, f"omega={om} ceil pct")
                require(abs(rec_om["locked_pct"] - round(100.0 * got_om["locked_exact"], 4)) <= 1e-9, f"omega={om} lock pct")
                require(abs(rec_om["modular_k100_pct"] - round(100.0 * got_om["modular_k100_exact"], 4)) <= 1e-9, f"omega={om} mod pct")
                require(abs(rec_om["delta_locked_vs_l3b_pp"] - round(100.0 * (got_om["locked_exact"] - l3b_row["locked_exact"]), 4)) <= 1e-9, f"omega={om} d_lock")
                require(abs(rec_om["delta_mod100_vs_l3b_pp"] - round(100.0 * (got_om["modular_k100_exact"] - l3b_row["modular_k100_exact"]), 4)) <= 1e-9, f"omega={om} d_mod")
                if om == 0.50:
                    require(abs(rec_om["ceiling_exact"] - rcomb["ceiling_exact"]) <= 1e-12 and abs(rec_om["locked_exact"] - rcomb["locked_exact"]) <= 1e-12 and abs(rec_om["modular_k100_exact"] - rcomb["modular_k100_exact"]) <= 1e-12, f"omega=0.50 mismatch vs principal {suffix}")

        # Recompute & verify ALL 24 Design B TYK2 discount values from scratch!
        for d_label, mult in (("discount_0pct_B2_base_WT_TYK2", 1.0), ("discount_50pct_B1_B2_PE_default", 0.5), ("discount_100pct_full_redundancy", 0.0)):
            bd = b_disc[phi_key][d_label]
            require(abs(bd["design_b_multiplier"] - mult) <= 1e-12, f"Design B mult mismatch {d_label}")
            for mode_key, base_sc_key, d_h2, d_h4 in (
                ("fixed_low", "IIP_B_NON_A_FIXED_CEIL_LOW", 0.005, 0.010),
                ("fixed_high", "IIP_B_NON_A_FIXED_CEIL_HIGH", 0.010, 0.020),
                ("ceil_lift_low", "IIP_B_NON_A_CEIL_LIFT_LOW", 0.005, 0.010),
                ("ceil_lift_high", "IIP_B_NON_A_CEIL_LIFT_HIGH", 0.010, 0.020),
            ):
                inp_m = json.loads(json.dumps(block[base_sc_key]["inputs"]))
                inp_m["arms"][1] = [base_arms[1][0], base_arms[1][1] + d_h2 * mult, base_arms[1][2], base_arms[1][3] + d_h4 * mult]
                got_d = eval_5arm_from_inputs(inp_m)
                require(abs(got_d["modular_k100_exact"] - bd[f"{mode_key}_mod_exact"]) <= 1e-12, f"B disc {phi_key}:{d_label}:{mode_key} exact")
                require(abs(bd[f"{mode_key}_mod_pct"] - round(100.0 * got_d["modular_k100_exact"], 4)) <= 1e-9, f"B disc {phi_key}:{d_label}:{mode_key} pct")

    require(n_rows == 36, f"Expected 36 core 2^20 rows, got {n_rows}")
    print("[PASS 6/10] ALL 36 core + 40 omega [0,1] + 24 Design B discount 2^20 rows + IIP-0042 parity + full Design-A firewall verified to <= 1e-12")

    # 7-9. Audit all 4 IIP drafts: SHA-256 pins (payload + file), dual license, offline PubMed registry (60==60), BODY-level claim-locator resolution, Graveyard cards
    pm_reg = receipt["verified_pubmed_registry"]
    claim_map = receipt["claim_to_source_map"]
    require(len(pm_reg) == 60, f"Expected 60 PubMed records, got {len(pm_reg)}")
    allowed_pt = {"primary_experiment", "clinical_trial", "veterinary_trial", "review", "case_report", "letter"}
    for pmid, meta in pm_reg.items():
        require("RETRACTED" not in meta["title"].upper() and not meta["retracted_in_ncbi_snapshot"], f"Retracted PMID in snapshot: {pmid}")
        require(meta["publication_type"] in allowed_pt, f"Invalid/preprint publication_type for {pmid}: {meta['publication_type']!r}")
        require(bool(meta["pubtypes_ncbi"]) and bool(meta["retrieval_timestamp_utc"]) and len(meta["title"]) >= 20, f"Incomplete metadata for {pmid}")
        require(meta["url"] == f"https://pubmed.ncbi.nlm.nih.gov/{pmid}/", f"URL mismatch for {pmid}")

    cited_body_by_draft: dict[str, set[str]] = {}
    cited_total: set[str] = set()
    for did, fname in IIP_DRAFT_FILES.items():
        txt = draft_texts[did]
        check_graveyard_pairs(txt, fname)
        require("cellgemma_e4b_in_silico_prior" in txt, f"Missing evidence_tier in {fname}")
        require(actual_sha in txt and receipt_file_sha in txt, f"Missing payload/file SHA-256 pin in {fname}")
        require("CC BY 4.0" in txt and "Apache-2.0" in txt and "6212145e0131d3744171739ea5232afc6aaa7c76" in txt, f"Missing license/model pin in {fname}")
        require("nlm.nih.gov/databases/download.html" in txt, f"Missing NLM data terms attribution in {fname}")

        found_pmids = set(re.findall(r"PMID:(\d+)", txt))
        unverified = sorted(found_pmids - set(pm_reg.keys()))
        require(not unverified, f"Unverified PMIDs in {fname}: {unverified}")
        m_hdr = re.search(r"\((\d+)\s+verified PubMed records\b", txt)
        require(m_hdr is not None, f"Missing '(N verified PubMed records...' header in {fname}")
        hdr_n = int(m_hdr.group(1))
        require("## 7. Verified PubMed Literature Registry" in txt, f"Missing Section 7 in {fname}")
        body_text, sec7 = txt.split("## 7. Verified PubMed Literature Registry", 1)
        body_pmids = set(re.findall(r"PMID:(\d+)", body_text))
        sec7_pmids = set(re.findall(r"PMID:(\d+)", sec7))
        require(
            hdr_n == len(sec7_pmids) == len(body_pmids) == len(found_pmids) and body_pmids == sec7_pmids,
            f"PMID body/Section-7/header mismatch in {fname}: hdr={hdr_n}, body={len(body_pmids)}, sec7={len(sec7_pmids)}, only_in_sec7={sorted(sec7_pmids - body_pmids)}, only_in_body={sorted(body_pmids - sec7_pmids)}",
        )
        # Bind every Section-7 line's publication_type tag, exact upstream title (stripped of trailing '.'), and URL against the frozen registry
        for ln in sec7.splitlines():
            m_p = re.search(r"PMID:(\d+)", ln)
            if not m_p:
                continue
            pid = m_p.group(1)
            meta = pm_reg[pid]
            expected_title = meta["title"].strip().rstrip(".")
            require(f"[`{meta['publication_type']}`]" in ln, f"Section 7 publication_type tag mismatch in {fname} for PMID:{pid}: expected [`{meta['publication_type']}`]")
            require(expected_title in ln, f"Section 7 title mismatch in {fname} for PMID:{pid}: expected {expected_title!r}")
            require(meta["url"] in ln, f"Section 7 URL mismatch in {fname} for PMID:{pid}")
        cited_body_by_draft[did] = body_pmids
        cited_total |= body_pmids

    uncited = sorted(set(pm_reg.keys()) - cited_total)
    require(not uncited, f"Uncited dead records in PubMed registry: {uncited}")

    # Resolve every claim_to_source_map binding (9 curated records, 33 unique PMIDs) against registry, explicit PMID presence in locator, AND draft BODY (Sections 1-6)
    bindings = claim_map.get("key_boundary_bindings", {})
    require(len(bindings) == claim_map.get("curated_claim_record_count") == 9, f"Expected 9 curated claim records, got {len(bindings)}")
    claim_unique_pmids: set[str] = set()
    for cid, b in bindings.items():
        loc = b.get("locator", "")
        require(bool(loc) and bool(b.get("model_and_boundary")), f"Missing locator/boundary in claim {cid}")
        require(bool(b.get("pmids")) and bool(b.get("draft_ids")), f"Missing pmids/draft_ids in claim {cid}")
        for pid in b["pmids"]:
            require(pid in pm_reg, f"Claim {cid} references unknown PMID:{pid}")
            require(pid in loc, f"Claim {cid} PMID:{pid} is missing from its own locator string: {loc!r}")
            require(any(pid in cited_body_by_draft[did] for did in b["draft_ids"]), f"Claim {cid} PMID:{pid} not cited in BODY (Sections 1-6) of any listed draft {b['draft_ids']}")
            claim_unique_pmids.add(pid)
        for did in b["draft_ids"]:
            require(did in cited_body_by_draft, f"Claim {cid} references unknown draft {did}")
            require(any(pid in cited_body_by_draft[did] for pid in b["pmids"]), f"Claim {cid} PMIDs not cited in BODY (Sections 1-6) of Draft {did}")
    require(len(claim_unique_pmids) == claim_map.get("curated_claim_unique_pmid_count") == 33, f"Expected 33 unique PMIDs across 9 curated claim records, got {len(claim_unique_pmids)}")

    print("[PASS 7/10] Exact payload & file SHA-256, dual CC BY 4.0 / Apache-2.0, HF commit, & dated NLM attribution pins verified across 4/4 drafts")
    print(f"[PASS 8/10] Offline bibliographic parity ({len(cited_total)}/{len(pm_reg)} unique PMIDs in Sections 1-6 & Section 7; 0 uncited, 0 orphans) + {len(bindings)} curated claim records ({len(claim_unique_pmids)} unique PMIDs) body/locator checks passed")
    print("[PASS 9/10] All GY-0xx <-> OFFGRID_GUARD_0xx Graveyard card pairs verified across 4/4 drafts")

    # 10. Strict Section-6 live-odds, BOTH BPR-05 bounds, exact header-role & Col-1 ceiling strings, Draft B overlap/discount lines, & promoted raw-table scalars!
    for did, fname in IIP_DRAFT_FILES.items():
        verify_sec6_live_and_bpr05_lines(fname, draft_texts[did])

    p25 = sens["phi_0p25_central"]
    p50 = sens["phi_0p50_harsh_stress"]
    verify_sec6_table_binding(
        IIP_DRAFT_FILES["A"],
        draft_texts["A"],
        [
            ("Wave-5 `L3B` Baseline", "L3B_WAVE5_STRICT_ZERO_DRUG_BASELINE", "None (`c4_univ=0.92`, `c4_pouch_a=c4_pouch_bx=c4_r3p=0.85`)"),
            ("IIP A Fixed-Ceiling Low", "IIP_A_NON_A_FIXED_CEIL_LOW", "**None (ALL systemic ceilings fixed)**"),
            ("IIP A Fixed-Ceiling High", "IIP_A_NON_A_FIXED_CEIL_HIGH", "**None (ALL systemic ceilings fixed)**"),
            ("IIP A Firewalled Ceiling-Lift Low", "IIP_A_NON_A_CEIL_LIFT_LOW", "`c4_pouch_a=0.85` fixed; `c4_pouch_bx=c4_r3p=0.870`, `c4_univ=0.935`"),
            ("IIP A Firewalled Ceiling-Lift High", "IIP_A_NON_A_CEIL_LIFT_HIGH", "`c4_pouch_a=0.85` fixed; `c4_pouch_bx=c4_r3p=0.885`, `c4_univ=0.945`"),
        ],
        p25,
        p50,
    )
    verify_sec6_table_binding(
        IIP_DRAFT_FILES["B"],
        draft_texts["B"],
        [
            ("Wave-5 `L3B` Baseline", "L3B_WAVE5_STRICT_ZERO_DRUG_BASELINE", "None (`c2=0.87/0.95`, `c3=0.925`, `c4=0.85/0.92`)"),
            ("IIP B Fixed-Ceiling Low", "IIP_B_NON_A_FIXED_CEIL_LOW", "**None (ALL systemic ceilings fixed)**"),
            ("IIP B Fixed-Ceiling High", "IIP_B_NON_A_FIXED_CEIL_HIGH", "**None (ALL systemic ceilings fixed)**"),
            ("IIP B Firewalled Ceiling-Lift Low", "IIP_B_NON_A_CEIL_LIFT_LOW", "`c2_a=0.87` fixed, `c2_bx/y=0.88`, `c2_univ=0.953`; `c4_pouch_a=0.85` fixed, `c4_bx/r3p=0.86`, `c4_univ=0.928`"),
            ("IIP B Firewalled Ceiling-Lift High", "IIP_B_NON_A_CEIL_LIFT_HIGH", "`c2_a=0.87` fixed, `c2_bx/y=0.89`, `c2_univ=0.956`; `c4_pouch_a=0.85` fixed, `c4_bx/r3p=0.87`, `c4_univ=0.935`"),
            ("Combined A+B+C Fixed-Ceiling Low", "COMBINED_ABC_FIXED_CEIL_LOW", "**None (ALL systemic ceilings fixed)**"),
            ("Combined A+B+C Fixed-Ceiling High", "COMBINED_ABC_FIXED_CEIL_HIGH", "**None (ALL systemic ceilings fixed)**"),
            ("Combined A+B+C Ceiling-Lift Low", "COMBINED_ABC_CEIL_LIFT_LOW", "`c2` from B-Low, `c3=0.930` from C-Low, `c4` `subadditive_overlap(0.50)` (`c4_pouch_a=0.85` fixed)"),
            ("Combined A+B+C Ceiling-Lift High", "COMBINED_ABC_CEIL_LIFT_HIGH", "`c2` from B-High, `c3=0.937` from C-High, `c4` `subadditive_overlap(0.50)` (`c4_pouch_a=0.85` fixed)"),
        ],
        p25,
        p50,
    )
    verify_draft_b_band_and_discount_lines(draft_texts["B"], omega_band, b_disc)

    verify_sec6_table_binding(
        IIP_DRAFT_FILES["C"],
        draft_texts["C"],
        [
            ("Wave-5 `L3B` Baseline", "L3B_WAVE5_STRICT_ZERO_DRUG_BASELINE", "None (`c3 = 0.925`)"),
            ("IIP C Fixed-Ceiling Low", "IIP_C_GENETIC_FIXED_CEIL_LOW", "**None (ALL systemic ceilings fixed)**"),
            ("IIP C Fixed-Ceiling High", "IIP_C_GENETIC_FIXED_CEIL_HIGH", "**None (ALL systemic ceilings fixed)**"),
            ("IIP C Ceiling-Lift Low", "IIP_C_GENETIC_CEIL_LIFT_LOW", "`c3: 0.925 -> 0.930`"),
            ("IIP C Ceiling-Lift High", "IIP_C_GENETIC_CEIL_LIFT_HIGH", "`c3: 0.925 -> 0.937`"),
        ],
        p25,
        p50,
    )

    sec6_d = draft_texts["D"].split("## 6.", 1)[1].split("## 7.", 1)[0]
    ln_d_pros = _find_single_line(sec6_d, "Prospective additive upside", "Draft D §6")
    require(re.findall(r"[+-]?\d+\.\d{2}\s+pp", ln_d_pros) == ["+0.00 pp"], "Draft D §6 prospective delta mismatch")

    # Verify promoted raw-to-table scalars across Drafts A-D directly from receipt IDs
    verify_promoted_table_scalars(receipt, draft_texts)
    print("[PASS 10/10] Strict Section-6 live-odds (+0.00 pp), BOTH BPR-05 bounds, exact header-roles & Col-1 ceilings, phi=0.25/0.50 bands, & promoted scalars verified across 4/4 drafts")

    print("\nALL 10/10 FAIL-CLOSED CHECKS PASSED (ZERO GPU REQUIRED; OPTIMIZED-PYTHON SAFE).")


if __name__ == "__main__":
    main()
