#!/usr/bin/env python3
"""
EXP-028 (CAND-031 / Target IIP-0041 — Bucket 2A) Remediated Verification Suite
==============================================================================
Reproducible end-to-end verification and artifact generator (installed at
OpenIslet/scripts/verify_iip0041_clinical_h1_cd64t_siglec.py):
  Part A: 2026 Clinical Hurdle 1 Audit (Blueprint H1 = 0.88 Post-Release Clinical Estimand
          Locked Live per ISLET-1-BLUEPRINT.md:37; Separate P_release_CMC & Joint
          H1_CMC_ATTEMPTED_LOT_READINESS = P_release_CMC * P_infuse_given_released * H1_Blueprint
          Executable CMC Readiness Evaluator; Reichman 2025 >=12-mo Analyzed Population &
          Product-vs-IS Death Attribution; Executable Bank/Lot-Clustered Gate 28-A Promotion
          Evaluator with Unified Deterministic Intercurrent-Event Adjudication)
  Part B: Core A/B/X CIITA Exon 5 Mode-B CD64t[1-313] + IL1RN Wave-5 Go Suite & Archived
          HOLD Comparators (Delta K = 0, GY-023/GY-025/GY-026 compliant; Full Protein Gate
          P1-P4 with programmatic Gravina 942-bp 235-nt/0-aa comparison, cognate biological
          assembly 4W4O/4X4M contact audit, pending FcRgamma gate, & runtime-SHA-256-pinned
          side-contract-bound fail-closed Gate 28-B CIITA Locus-2 arbitration requiring
          strictly literal IDs, exact rational boundary validation over decoded inputs
          (JSON-decoded IEEE-754 float64 precision for strict JSON intake; exact decimal/int
          precision for direct Python Decimal/int calls), linked raw t0/Day-90 MFI
          retention derivation, quantitative IL-1Ra/basal-leak/GSIS/AP1903 endpoints,
          independent classical + lectin C4b2a intervals, and independently stored,
          issuer-authenticated, SHA-256-verified Gate 0V/S11/Tier 6B & quantitative paired
          L2_V3 incumbent comparator records)
  Part C: Bounded Day 0-14 Research Comparator Luminal Siglec-7/-9 (Rana 2026, PMID:42875686)
          with Split Gate 28-C0/28-C1 & Permanent GY-029 (OFFGRID_GUARD_019) ST6GAL1 Rule
  Part D: Exact OQ-016 2^12 Core 3-Arm & 2^20 5-Arm (W_U3 / W_U4) Portfolio Odds Analysis
          (Zero-Tolerance Strict Domain/Ceiling Guards + True Unrounded 3-Arm/5-Arm Deltas
          + Shock-Law Conditioning)
  Part E: 100% Live NCBI E-utilities + Europe PMC PMID Verification Receipt
  Part F: WORKFLOW.md §5.6 Multi-Arm Quantitative Ring-1 + CEG Evidence Extraction Bundle
          (Retiered per Primary Sources, Production record_class, Optimize-Safe G2b & All
          9/9 Live Validator Gates, & PDL-019 Extraction Verification Receipt)

Strictly READ-ONLY on OpenIslet and OpenIslet-Website.
Run:
  PYTHONDONTWRITEBYTECODE=1 python3 -B scripts/verify_iip0041_clinical_h1_cd64t_siglec.py --repo-root <OpenIslet> --installed-check
  PYTHONDONTWRITEBYTECODE=1 python3 -O -B scripts/verify_iip0041_clinical_h1_cd64t_siglec.py --repo-root <OpenIslet> --installed-check
"""
from __future__ import annotations

import argparse
from collections import Counter
import copy
import decimal
from decimal import Decimal, InvalidOperation, getcontext, localcontext
import gzip
import hashlib
import importlib
import json
import math
import os
import pathlib
import random
import re
import sys
import tempfile
import time
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
from fractions import Fraction
from typing import Any

import jsonschema

sys.dont_write_bytecode = True

_SCRIPT_PATH = pathlib.Path(__file__).resolve()
_SCRIPT_DIR = _SCRIPT_PATH.parent


def _discover_default_roots() -> tuple[pathlib.Path, pathlib.Path]:
    """Auto-discover OpenIslet and optional sibling research cache roots."""
    if _SCRIPT_DIR.name == "scripts" and (_SCRIPT_DIR.parent / "scripts/rank_islet1_stacks.py").is_file():
        oi_root = _SCRIPT_DIR.parent
        inv_root = oi_root.parent / "OpenIslet-Investigations"
        return oi_root, inv_root
    if len(_SCRIPT_PATH.parents) >= 4 and (_SCRIPT_PATH.parents[3] / "idea-exploration").is_dir():
        inv_root = _SCRIPT_PATH.parents[3]
        oi_root = pathlib.Path(os.environ.get("OPENISLET_ROOT", str(inv_root.parent / "OpenIslet")))
        return oi_root, inv_root
    env_oi = os.environ.get("OPENISLET_ROOT")
    if env_oi:
        oi_root = pathlib.Path(env_oi).resolve()
        return oi_root, oi_root.parent / "OpenIslet-Investigations"
    return _SCRIPT_DIR.parent, _SCRIPT_DIR.parent.parent / "OpenIslet-Investigations"


def _resolve_optional_inv_cache(
    inv_root: pathlib.Path,
    *,
    env_var: str,
    glob_pattern: str,
    fallback_rel: str,
) -> pathlib.Path:
    """Resolve optional local full-mode research cache paths via env override or glob (never used in --installed-check)."""
    env_val = os.environ.get(env_var)
    if env_val:
        return pathlib.Path(env_val).expanduser().resolve()
    if inv_root.is_dir():
        matches = sorted(inv_root.glob(glob_pattern))
        if matches:
            return matches[0]
    return inv_root / fallback_rel


OPENISLET_ROOT, INV_ROOT = _discover_default_roots()
bceg: Any = None
erc: Any = None
grm: Any = None
pep: Any = None
rank_mod: Any = None
l2: Any = None

OUT_DIR = _SCRIPT_DIR
DOSSIERS_DIR = OUT_DIR / "dossiers_staged_exp028"
FASTA_OUT = OUT_DIR / "exp028_abx_cd64t_il1rn_modeb_v0.8.0.fasta"
RECEIPT_OUT = OUT_DIR / "exp028_verification_receipt.json"
PMID_RECEIPT_OUT = OUT_DIR / "pmid_verification_receipt.json"
EVIDENCE_BUNDLE_OUT = OUT_DIR / "evidence_extraction_bundle.json"
EXTRACTION_RECEIPT_OUT = OUT_DIR / "extraction_verification_receipt.json"
PRIVACY_HOME_TOKEN = "/" + "Users" + "/"
PINNED_AUDIT_DATE = "2026-11-28"
PINNED_MODEB_FASTA_REL = "data/constructs/islet1_abx_cd64t_il1rn_modeb_v0.8.0.fasta"
PINNED_SIDE_CONTRACT_REL = "data/protocols/iip0041_abx_cd64t_il1rn_side_contract_v0.8.0.json"
PINNED_SIDE_CONTRACT_SHA256 = "bfcbe96492b6a063335ca20f1fb43eb4227c81932ba81690046419cc20a26050"
TRUSTED_QUAL_STORE_SCHEMA_VERSION = "iip0041_gate28b_trusted_qualification_store_v1"
TRUSTED_CLINICAL_STORE_SCHEMA_VERSION = "iip0041_gate28a_trusted_clinical_store_v1"
TRUSTED_CLINICAL_STORE_DEPLOYMENT_DEPENDENCY = (
    "Runtime Gate 28-A clinical provenance verification depends operationally on independent QA/clinical "
    "governance custody, external store provenance confirmation, write-restricted access policy, and "
    "separation of duties over trusted_clinical_store; the repository snapshot supplies verification "
    "logic with synthetic test fixtures rather than a live clinical governance deployment."
)


def _clean_display_decimal_context() -> decimal.Context:
    """Return a clean display Decimal context explicitly clearing Inexact/Rounded/Clamped/Subnormal/Underflow traps and locking wide exponent bounds."""
    return decimal.Context(
        prec=50,
        rounding=decimal.ROUND_HALF_EVEN,
        Emin=-999999,
        Emax=999999,
        traps=[decimal.InvalidOperation, decimal.DivisionByZero, decimal.Overflow],
    )


_CLEAN_DISPLAY_DECIMAL_CTX = _clean_display_decimal_context

SWISSPROT_GZ = _resolve_optional_inv_cache(
    INV_ROOT,
    env_var="OPENISLET_SWISSPROT_GZ",
    glob_pattern="idea-exploration/EXP-020-*/*/uniprot_sprot_human_reviewed_20429.fasta.gz",
    fallback_rel="cache/uniprot_sprot_human_reviewed_20429.fasta.gz",
)
PINNED_SWISSPROT_SHA = "40a8856b4e3f3620b11635143b501ef701558ed97309b0cdb4423ef09e4618d0"
PROT_CACHE_DIR = _resolve_optional_inv_cache(
    INV_ROOT,
    env_var="OPENISLET_PROT_CACHE_DIR",
    glob_pattern="idea-exploration/EXP-025-*/*/_protein_cache",
    fallback_rel="cache/_protein_cache",
)
GRAVINA_PMC_XML_CACHE = _resolve_optional_inv_cache(
    INV_ROOT,
    env_var="OPENISLET_GRAVINA_PMC_XML",
    glob_pattern="idea-exploration/EXP-025-*/*/_ft_cache/36593395_PMC10188358.xml",
    fallback_rel="cache/_ft_cache/36593395_PMC10188358.xml",
)
GRCH38_CACHE_PATH = _resolve_optional_inv_cache(
    INV_ROOT,
    env_var="OPENISLET_GRCH38_CACHE",
    glob_pattern="idea-exploration/EXP-027-*/*/*/grch38_elements_cache.json",
    fallback_rel="cache/grch38_elements_cache.json",
)
LEDGER_PATH = _resolve_optional_inv_cache(
    INV_ROOT,
    env_var="OPENISLET_STAGE1_LEDGER",
    glob_pattern="reports/*/stage1_settled_3922_ledger.json",
    fallback_rel="cache/stage1_settled_3922_ledger.json",
)

# Exact published 942-bp coding sequence of human CD64t[1-313] from Gravina et al. Nat Biotechnol 2023 (PMC10188358)
GRAVINA_2023_PUBLISHED_CD64T_CDS_942BP = (
    "ATGTGGTTCTTGACAACTCTGCTCCTTTGGGTTCCAGTTGATGGGCAAGTGGACACCACAAAGGCAGTGATCACTTTGCAGCCTCCATGGGTCAGCGTGTTCCAAGAGGAAACCGTAACCTTGCACTGTGAGGTGCTCCATCTGCCTGGGAGCAGCTCTACACAGTGGTTTCTCAATGGCACAGCCACTCAGACCTCGACCCCCAGCTACAGAATCACCTCTGCCAGTGTCAATGACAGTGGTGAATACAGGTGCCAGAGAGGTCTCTCAGGGCGAAGTGACCCCATACAGCTGGAAATCCACAGAGGCTGGCTACTACTGCAGGTCTCCAGCAGAGTCTTCACGGAAGGAGAACCTCTGGCCTTGAGGTGTCATGCGTGGAAGGATAAGCTGGTGTACAATGTGCTTTACTATCGAAATGGCAAAGCCTTTAAGTTTTTCCACTGGAATTCTAACCTCACCATTCTGAAAACCAACATAAGTCACAATGGCACCTACCATTGCTCAGGCATGGGAAAGCATCGCTACACATCAGCAGGAATATCTGTCACTGTGAAAGAGCTATTTCCAGCTCCAGTGCTGAATGCATCTGTGACATCCCCACTCCTGGAGGGGAATCTGGTCACCCTGAGCTGTGAAACAAAGTTGCTCTTGCAGAGGCCTGGTTTGCAGCTTTACTTCTCCTTCTACATGGGCAGCAAGACCCTGCGAGGCAGGAACACATCCTCTGAATACCAAATACTAACTGCTAGAAGAGAAGACTCTGGGTTATACTGGTGCGAGGCTGCCACAGAGGATGGAAATGTCCTTAAGCGCAGCCCTGAGTTGGAGCTTCAAGTGCTTGGCCTCCAGTTACCAACTCCTGTCTGGTTTCATGTCCTTTTCTATCTGGCAGTGGGAATAATGTTTTTAGTGAACACTGTTCTCTGGGTGACAATATAG"
)
PINNED_FASTA_SHA = "77280c9a1bf8050b02e7aea0dba69ff40f4f71892e0bca23bc8b77c47601725e"


def _bind_openislet_modules(repo_root: pathlib.Path) -> None:
    global bceg, erc, grm, pep, rank_mod, l2
    scripts_dir = repo_root / "scripts"
    if not (scripts_dir / "rank_islet1_stacks.py").is_file():
        raise FileNotFoundError(f"Invalid --repo-root (missing scripts/rank_islet1_stacks.py): {repo_root}")
    sdir = str(scripts_dir)
    if sdir in sys.path:
        sys.path.remove(sdir)
    sys.path.insert(0, sdir)
    bceg = importlib.import_module("build_context_evidence_graph")
    erc = importlib.import_module("extract_ring1_corpus")
    grm = importlib.import_module("generate_release_manifest")
    pep = importlib.import_module("public_excerpt_policy")
    rank_mod = importlib.import_module("rank_islet1_stacks")
    l2 = importlib.import_module("run_layer2_perturbation_and_regulatory_plane")


def configure_runtime_paths(
    *,
    repo_root: pathlib.Path | None = None,
    inv_root: pathlib.Path | None = None,
    output: pathlib.Path | None = None,
) -> pathlib.Path | None:
    """Bind repo, optional research cache, and output paths cleanly (fail-closed on explicit invalid paths)."""
    global OPENISLET_ROOT, INV_ROOT, OUT_DIR, DOSSIERS_DIR
    global FASTA_OUT, RECEIPT_OUT, PMID_RECEIPT_OUT, EVIDENCE_BUNDLE_OUT, EXTRACTION_RECEIPT_OUT
    global SWISSPROT_GZ, PROT_CACHE_DIR, GRAVINA_PMC_XML_CACHE, GRCH38_CACHE_PATH, LEDGER_PATH

    if repo_root is not None:
        rr = pathlib.Path(repo_root).expanduser().resolve()
        if not rr.is_dir() or not (rr / "scripts/rank_islet1_stacks.py").is_file():
            raise FileNotFoundError(f"Explicit --repo-root is missing or invalid: {repo_root}")
        OPENISLET_ROOT = rr
    if inv_root is not None:
        ir = pathlib.Path(inv_root).expanduser().resolve()
        if not ir.is_dir():
            raise FileNotFoundError(f"Explicit --inv-root does not exist: {inv_root}")
        INV_ROOT = ir
    elif repo_root is not None and not (INV_ROOT / "idea-exploration").is_dir():
        cand_inv = OPENISLET_ROOT.parent / "OpenIslet-Investigations"
        if cand_inv.is_dir():
            INV_ROOT = cand_inv

    _bind_openislet_modules(OPENISLET_ROOT)

    explicit_receipt: pathlib.Path | None = None
    if output is not None:
        op = pathlib.Path(output).expanduser().resolve()
        if op.suffix.lower() == ".json":
            explicit_receipt = op
            OUT_DIR = op.parent
        else:
            OUT_DIR = op
    else:
        OUT_DIR = _SCRIPT_DIR

    DOSSIERS_DIR = OUT_DIR / "dossiers_staged_exp028"
    FASTA_OUT = OUT_DIR / "exp028_abx_cd64t_il1rn_modeb_v0.8.0.fasta"
    RECEIPT_OUT = explicit_receipt if explicit_receipt is not None else (OUT_DIR / "exp028_verification_receipt.json")
    PMID_RECEIPT_OUT = OUT_DIR / "pmid_verification_receipt.json"
    EVIDENCE_BUNDLE_OUT = OUT_DIR / "evidence_extraction_bundle.json"
    EXTRACTION_RECEIPT_OUT = OUT_DIR / "extraction_verification_receipt.json"

    SWISSPROT_GZ = _resolve_optional_inv_cache(
        INV_ROOT,
        env_var="OPENISLET_SWISSPROT_GZ",
        glob_pattern="idea-exploration/EXP-020-*/*/uniprot_sprot_human_reviewed_20429.fasta.gz",
        fallback_rel="cache/uniprot_sprot_human_reviewed_20429.fasta.gz",
    )
    PROT_CACHE_DIR = _resolve_optional_inv_cache(
        INV_ROOT,
        env_var="OPENISLET_PROT_CACHE_DIR",
        glob_pattern="idea-exploration/EXP-025-*/*/_protein_cache",
        fallback_rel="cache/_protein_cache",
    )
    GRAVINA_PMC_XML_CACHE = _resolve_optional_inv_cache(
        INV_ROOT,
        env_var="OPENISLET_GRAVINA_PMC_XML",
        glob_pattern="idea-exploration/EXP-025-*/*/_ft_cache/36593395_PMC10188358.xml",
        fallback_rel="cache/_ft_cache/36593395_PMC10188358.xml",
    )
    GRCH38_CACHE_PATH = _resolve_optional_inv_cache(
        INV_ROOT,
        env_var="OPENISLET_GRCH38_CACHE",
        glob_pattern="idea-exploration/EXP-027-*/*/*/grch38_elements_cache.json",
        fallback_rel="cache/grch38_elements_cache.json",
    )
    LEDGER_PATH = _resolve_optional_inv_cache(
        INV_ROOT,
        env_var="OPENISLET_STAGE1_LEDGER",
        glob_pattern="reports/*/stage1_settled_3922_ledger.json",
        fallback_rel="cache/stage1_settled_3922_ledger.json",
    )
    return explicit_receipt


if (OPENISLET_ROOT / "scripts/rank_islet1_stacks.py").is_file():
    _bind_openislet_modules(OPENISLET_ROOT)

STOP_CAP_3FRAME_12BP = "TAATAGTGATAG"
GRCH38_HOXA_CTCF_C5_80BP = "AGCCACACTGCCATCTGCTGGCCGCCGTTTGGTACTGCAGCCTCAGCTACCTCCGCCGGCCTGAGCTTTGGGAGCCGCCG"

HUMAN_CODONS: dict[str, list[str]] = {
    "A": ["GCC", "GCT", "GCA", "GCG"],
    "C": ["TGC", "TGT"],
    "D": ["GAC", "GAT"],
    "E": ["GAG", "GAA"],
    "F": ["TTC", "TTT"],
    "G": ["GGC", "GGA", "GGT", "GGG"],
    "H": ["CAC", "CAT"],
    "I": ["ATC", "ATT"],
    "K": ["AAG", "AAA"],
    "L": ["CTG", "CTC", "CTT", "TTG", "CTA"],
    "M": ["ATG"],
    "N": ["AAC", "AAT"],
    "P": ["CCC", "CCT", "CCA", "CCG"],
    "Q": ["CAG", "CAA"],
    "R": ["AGA", "AGG", "CGC", "CGG", "CGT", "CGA"],
    "S": ["AGC", "TCC", "TCT", "TCA", "AGT", "TCG"],
    "T": ["ACC", "ACA", "ACT", "ACG"],
    "V": ["GTG", "GTC", "GTT", "GTA"],
    "W": ["TGG"],
    "Y": ["TAC", "TAT"],
    "*": ["TGA"],
}

FORBIDDEN_CDS_MOTIFS = [
    "AATAAA", "TTTATT", "ATTAAA", "TTTAAT",
    "GGTCTC", "GAGACC", "CGTCTC", "GAGACG",
    "GCTCTTC", "GAAGAGC", "GCGGCCGC",
    "AAAAAAA", "CCCCCCC", "GGGGGGG", "TTTTTTT",
    "GTAAGT", "GTGAGT", "ACTTAC", "ACTCAC",
]

TWO_A_REGEX = re.compile(r"D[A-Z]E[A-Z]NPGP")


def sha256_str(s: str) -> str:
    return hashlib.sha256(s.encode("utf-8")).hexdigest()


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


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


def parse_fasta(p: pathlib.Path) -> dict[str, str]:
    recs: dict[str, list[str]] = {}
    cur = None
    for raw in p.read_text(encoding="utf-8").splitlines():
        ln = raw.strip()
        if not ln:
            continue
        if ln.startswith(">"):
            cur = ln[1:].split()[0]
            recs[cur] = []
        elif cur is not None:
            recs[cur].append(ln.upper())
    return {k: "".join(v) for k, v in recs.items()}


def walk_strings(obj: Any, path: str = "") -> list[tuple[str, str]]:
    out: list[tuple[str, str]] = []
    if isinstance(obj, str):
        out.append((path, obj))
    elif isinstance(obj, dict):
        for k, v in obj.items():
            out.extend(walk_strings(v, f"{path}.{k}" if path else str(k)))
    elif isinstance(obj, list):
        for i, v in enumerate(obj):
            out.extend(walk_strings(v, f"{path}[{i}]"))
    return out


# =============================================================================
# STRICT FAIL-CLOSED JSON DECODER & EXACT LITERAL / DECIMAL VALIDATORS
# =============================================================================
def _reject_duplicate_json_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
    out: dict[str, Any] = {}
    for k, v in pairs:
        if k in out:
            raise ValueError(f"Duplicate JSON object key rejected fail-closed: {k!r}")
        out[k] = v
    return out


def _reject_nonfinite_json_constant(const: str) -> Any:
    raise ValueError(f"Non-finite JSON constant rejected fail-closed: {const!r}")


def _parse_strict_finite_float(token: str) -> float:
    fv = float(token)
    if not math.isfinite(fv):
        raise ValueError(f"Overflowing or non-finite JSON float rejected fail-closed: {token!r}")
    return fv


def _parse_strict_finite_int(token: str) -> int:
    iv = int(token)
    if abs(iv) > 10 ** 300:
        raise ValueError(f"Overflowing JSON integer rejected fail-closed: {token[:32]!r}")
    return iv


def assert_strictly_finite_json(obj: Any, label: str, path: str = "$") -> None:
    if isinstance(obj, bool) or obj is None or isinstance(obj, str):
        return
    if isinstance(obj, int):
        if abs(obj) > 10 ** 300:
            raise ValueError(f"Overflowing integer in {label} at {path}")
        return
    if isinstance(obj, float):
        if not math.isfinite(obj):
            raise ValueError(f"Non-finite float in {label} at {path}: {obj!r}")
        return
    if isinstance(obj, dict):
        for k, v in obj.items():
            assert_strictly_finite_json(v, label, f"{path}.{k}")
        return
    if isinstance(obj, list):
        for i, v in enumerate(obj):
            assert_strictly_finite_json(v, label, f"{path}[{i}]")
        return


def load_strict_json_text(raw_text: str, label: str) -> Any:
    """Strict fail-closed JSON decoder rejecting duplicate keys, NaN/Inf constants, and overflowing numbers.

    Note on numeric precision: JSON floating-point tokens decode through Python IEEE-754 binary64
    (float64) via _parse_strict_finite_float. Downstream exact Fraction boundary comparisons
    (such as Gate 28-B Day-90 MFI retention) are therefore exact over JSON-decoded float64 values
    rather than raw decimal text exceeding 53-bit binary64 significand precision.
    """
    data = json.loads(
        raw_text,
        object_pairs_hook=_reject_duplicate_json_keys,
        parse_constant=_reject_nonfinite_json_constant,
        parse_float=_parse_strict_finite_float,
        parse_int=_parse_strict_finite_int,
    )
    assert_strictly_finite_json(data, label)
    return data


def load_strict_json_bytes(raw_bytes: bytes, label: str) -> Any:
    return load_strict_json_text(raw_bytes.decode("utf-8"), label)


def _strict_literal_id(val: Any) -> str | None:
    """Strictly literal identifier validator with ZERO silent whitespace stripping."""
    if not isinstance(val, str) or not val:
        return None
    if val != val.strip() or any(ch.isspace() for ch in val):
        return None
    return val


def _strict_decimal_in_range(
    val: Any,
    *,
    min_val: Decimal | Fraction | int | None = None,
    max_val: Decimal | Fraction | int | None = None,
    exclusive_min: bool = False,
) -> Decimal | Fraction | None:
    """Validate strict finite numeric value (int, float, Decimal, or Fraction; rejecting bool and non-finite float/Decimal), immune to caller Decimal traps/precision."""
    if isinstance(val, bool) or not isinstance(val, (int, float, Decimal, Fraction)):
        return None
    if isinstance(val, Fraction):
        fv = val
        if fv != 0:
            abs_num = abs(fv.numerator)
            den = fv.denominator
            # Exact [1e-300, 1e301) magnitude guard matching Decimal adjusted() in [-300, 300]
            if abs_num * (10 ** 300) < den or abs_num >= den * (10 ** 301):
                return None
        out_val: Decimal | Fraction = fv
    else:
        if isinstance(val, float) and not math.isfinite(val):
            return None
        if isinstance(val, Decimal) and not val.is_finite():
            return None
        try:
            dv = val if isinstance(val, Decimal) else Decimal(str(val))
        except (InvalidOperation, ValueError):
            return None
        if not dv.is_finite():
            return None
        if dv != 0 and abs(dv.adjusted()) > 300:
            return None
        fv = Fraction(dv)
        out_val = dv
    if min_val is not None:
        fmin = Fraction(min_val)
        if exclusive_min:
            if fv <= fmin:
                return None
        else:
            if fv < fmin:
                return None
    if max_val is not None and fv > Fraction(max_val):
        return None
    return out_val


def _format_exact_fraction_pct_display(
    derived_ret_frac: Fraction,
    *,
    out_of_assay_range: bool,
) -> tuple[float | None, str]:
    """Format an exact non-negative Fraction percentage inside an isolated Decimal display context (trap- and overflow-immune)."""
    with localcontext(_CLEAN_DISPLAY_DECIMAL_CTX()):
        if not out_of_assay_range:
            scaled_int = round(derived_ret_frac * 10000)
            display_dec = (Decimal(scaled_int) / Decimal(10000)).quantize(Decimal("0.0001"))
            display_ret_float = float(display_dec)
            return display_ret_float, f"{display_ret_float:.4f}%"
        int_part = derived_ret_frac.numerator // derived_ret_frac.denominator
        if int_part >= 1:
            exp = len(str(int_part)) - 1
            mantissa_1e4 = round((derived_ret_frac * 10000) / (10 ** exp))
            if mantissa_1e4 >= 100000:
                exp += 1
                mantissa_1e4 = round((derived_ret_frac * 10000) / (10 ** exp))
            display_dec = (Decimal(mantissa_1e4) / Decimal(10000)) * Decimal(f"1e{exp}")
        else:
            display_dec = Decimal(derived_ret_frac.numerator) / Decimal(derived_ret_frac.denominator)
        return None, f"{display_dec:.4E}%"


# =============================================================================
# EXACT STDLIB BETA DISTRIBUTION & CLOPPER-PEARSON HELPERS (ZERO SCIPY DRIFT)
# =============================================================================
def _betacf(a: float, b: float, x: float) -> float:
    maxit = 400
    eps = 3.0e-14
    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, maxit + 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 beta_cdf(x: float, a: float, b: float) -> float:
    if x <= 0.0:
        return 0.0
    if x >= 1.0:
        return 1.0
    bt = math.exp(
        math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
        + a * math.log(x) + b * math.log(1.0 - x)
    )
    if x < (a + 1.0) / (a + b + 2.0):
        return bt * _betacf(a, b, x) / a
    return 1.0 - bt * _betacf(b, a, 1.0 - x) / b


def beta_ppf(q: float, a: float, b: float) -> float:
    if q <= 0.0:
        return 0.0
    if q >= 1.0:
        return 1.0
    lo, hi = 0.0, 1.0
    for _ in range(90):
        mid = 0.5 * (lo + hi)
        if beta_cdf(mid, a, b) < q:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)


def clopper_pearson_ci(k: int, n: int, alpha: float = 0.05) -> tuple[float, float]:
    lo = 0.0 if k == 0 else beta_ppf(alpha / 2.0, float(k), float(n - k + 1))
    hi = 1.0 if k == n else beta_ppf(1.0 - alpha / 2.0, float(k + 1), float(n - k))
    return lo, hi


def _beta_posterior_summary(a0: float, b0: float, k: int, n: int, *, overlap_status: str) -> dict[str, Any]:
    a1 = a0 + k
    b1 = b0 + (n - k)
    mean = a1 / (a1 + b1)
    ci_lo = beta_ppf(0.025, a1, b1)
    ci_hi = beta_ppf(0.975, a1, b1)
    p_ge_88 = 1.0 - beta_cdf(0.88, a1, b1)
    p_ge_90 = 1.0 - beta_cdf(0.90, a1, b1)
    return {
        "prior_params": [round(a0, 4), round(b0, 4)],
        "posterior_params": [round(a1, 4), round(b1, 4)],
        "overlap_status": overlap_status,
        "posterior_mean_pct": round(100.0 * mean, 2),
        "credible_95_pct": [round(100.0 * ci_lo, 2), round(100.0 * ci_hi, 2)],
        "prob_ge_88pct": round(100.0 * p_ge_88, 2),
        "prob_ge_90pct": round(100.0 * p_ge_90, 2),
        "prob_ge_90_exact": round(p_ge_90, 6),
    }


def analyze_clinical_h1_reanchor() -> dict[str, Any]:
    # Non-informative priors (ZERO overlap with Reichman 2025) vs Reichman-anchored priors.
    # Live ISLET-1-BLUEPRINT.md line 37 conditions H1..H4 on having passed laboratory/GMP release checks
    # and cites Reichman 2025 to anchor clinical post-release H1 = 0.88; therefore:
    #   (a) Blueprint H1 MUST remain P(response | released lot infused) (never overloaded with CMC lot-release rate),
    #   (b) P_release_CMC (release-only operational yield) and H1_CMC_ATTEMPTED_LOT_READINESS =
    #       P_release_CMC * P_infuse_given_released * H1_Blueprint are tracked in a strictly separate readiness ledger,
    #   (c) updating Beta(8.8, 1.2) with Reichman's 12 outcomes double-counts Reichman, and
    #   (d) mixed-cohort pooled counts (13/13, 11/13, 12/14, 16/16) are descriptive sensitivities conditional on
    #       assumed common-endpoint counts ONLY (primary_verified=False; never an exchangeable promotion likelihood).
    non_informative_priors = {
        "uniform_Beta_1_1": (1.0, 1.0),
        "jeffreys_Beta_0p5_0p5": (0.5, 0.5),
    }
    anchored_priors = {
        "openislet_prior_Beta_8p8_1p2_n10": (8.8, 1.2),
        "openislet_prior_Beta_17p6_2p4_n20": (17.6, 2.4),
    }

    # Explicit per-study endpoint, observation-window, intercurrent-event, and missing-data adjudication ledger
    per_study_endpoint_adjudication_ledger = [
        {
            "study_id": "Reichman_2025_NEJM_PMID_40544428",
            "pmid": "40544428",
            "source_pointers": "Reichman et al. NEJM 2025 (PMID:40544428), Results and Figures 2-3 (NCT04786262 Parts A/B/C)",
            "product_class": "ALLOGENEIC_HESC_SC_ISLET_ZIMISLECEL_VX880",
            "transplant_site": "INTRAPORTAL_HEPATIC",
            "immunosuppression_regimen": "DE_NOVO_GLUCOCORTICOID_FREE_CHRONIC_SYSTEMIC_IS",
            "observation_window": "12 months (Day 365 efficacy follow-up; primary SHE window Days 90-365; HbA1c window Days 180-365)",
            "analyzed_population_definition": (
                "14 dosed participants in Parts A-C who had completed >= 12 months of follow-up at data cutoff "
                "(2 half-dose participants in Part A + 12 full-dose participants in Parts B/C); excludes any "
                "additional dosed participants with < 12 months of follow-up."
            ),
            "original_published_primary_endpoint": (
                "Elimination of severe hypoglycemic events (Days 90-365) with HbA1c < 7.0% or >= 1 percentage-point reduction "
                "from baseline (distinct from the stricter proposed common C2b sustained composite requiring simultaneous "
                "HbA1c < 7.0%, CGM TIR > 70%, 0 SHEs, and quantitative stimulated C-peptide)."
            ),
            "published_counts": {
                "analyzed_ge12mo_followup_population_n": 14,
                "analyzed_ge12mo_followup_breakdown": "2 half-dose Part A + 12 full-dose Parts B/C (participants with >= 12 months follow-up)",
                "analyzed_ge12mo_followup_c_peptide_engraftment_parts_abc": "14/14",
                "full_dose_12mo_analysis_n": 12,
                "full_dose_original_glycemic_target_met": "12/12",
                "day365_cgm_records_in_figure_3_n": 11,
                "day365_cgm_missing_count_of_12": 1,
                "day365_insulin_independence": "10/12",
                "protocol_prohibited_peri_infusion_glucocorticoids_n": 2,
                "protocol_prohibited_glucocorticoid_note": (
                    "Two full-dose participants received protocol-prohibited peri-infusion glucocorticoids; "
                    "those same 2 participants remained on exogenous insulin at Day 365."
                ),
                "trial_deaths_in_analyzed_14_n": 2,
                "trial_deaths_product_vs_regimen_attribution": {
                    "death_1_cryptococcal_meningitis": (
                        "Fatal cryptococcal meningitis (~19.5 months post-infusion) — occurred following surgery "
                        "complicated by skull-base injury, prolonged protocol-prohibited systemic glucocorticoids, "
                        "and concurrent chronic immunosuppression; assessed by investigators as UNRELATED to "
                        "zimislecel (the cell product) BUT RELATED to the chronic immunosuppressive medication regimen."
                    ),
                    "death_2_preexisting_neurocognitive_disease": (
                        "Progression of pre-existing neurocognitive disease (~30 months post-infusion) — assessed "
                        "as UNRELATED to zimislecel and unrelated to the immunosuppressive regimen."
                    ),
                },
                "trial_deaths_note": (
                    "2 deaths occurred in the 14-participant >=12-month analyzed population: "
                    "1 fatal cryptococcal meningitis (~19.5 months post-infusion) following surgery complicated by "
                    "skull-base injury, prolonged protocol-prohibited systemic glucocorticoids, and concurrent "
                    "chronic immunosuppression (assessed by investigators as unrelated to zimislecel [product] BUT "
                    "related to the chronic immunosuppressive medication regimen), and 1 progression of pre-existing "
                    "neurocognitive disease (~30 months post-infusion, unrelated to zimislecel or immunosuppression)."
                ),
            },
            "attempted_gmp_lots_cmc_denominator_disclosed": False,
            "missing_data_and_adjudication_status": "PUBLISHED_STUDY_SPECIFIC_ENDPOINT_ONLY_NOT_COMMON_C2B_ADJUDICATED",
        },
        {
            "study_id": "Wang_2024_Cell_PMID_39326417",
            "pmid": "39326417",
            "source_pointers": "Wang et al. Cell 2024 (PMID:39326417), Methods, Results, and Figures 2-3 (ChiCTR2300072200)",
            "product_class": "AUTOLOGOUS_UNEDITED_CIPSC_ISLET",
            "transplant_site": "ABDOMINAL_ANTERIOR_RECTUS_SHEATH",
            "immunosuppression_regimen": "CONTINUED_3_DRUG_PRIOR_LIVER_TRANSPLANT_IS_PLUS_PERI_INFUSION_INDUCTION",
            "observation_window": "1 year (365 days); insulin independence from Day 75 through 1-year follow-up",
            "original_published_primary_endpoint": "Single-recipient safety and 1-year glycemic/C-peptide restoration case report",
            "published_counts": {
                "infused_t1d_recipients_n": 1,
                "insulin_independence_day75_to_1yr": "1/1",
                "stimulated_c_peptide_and_improved_tir_and_0_she": "1/1",
                "missing_primary_cgm_count": 0,
            },
            "attempted_gmp_lots_cmc_denominator_disclosed": False,
            "missing_data_and_adjudication_status": "SINGLE_RECIPIENT_OBSERVED_INCOMPATIBLE_PRODUCT_SITE_REGIMEN_FOR_ALLO_POOLING",
        },
        {
            "study_id": "Wu_2024_CellDiscov_PMID_38684699",
            "pmid": "38684699",
            "source_pointers": "Wu et al. Cell Discov 2024 (PMID:38684699), T2D autologous endoderm SC-islet case",
            "product_class": "AUTOLOGOUS_ENDODERM_SC_ISLET_T2D",
            "transplant_site": "INTRAPORTAL_HEPATIC",
            "immunosuppression_regimen": "PRIOR_KIDNEY_TRANSPLANT_SYSTEMIC_IS",
            "observation_window": "116 weeks reported in T2D recipient (distinct disease from T1D)",
            "original_published_primary_endpoint": "Single-recipient T2D insulin-free glycemic control",
            "published_counts": {"infused_t2d_recipients_n": 1, "insulin_independence": "1/1"},
            "attempted_gmp_lots_cmc_denominator_disclosed": False,
            "missing_data_and_adjudication_status": "DISTINCT_DISEASE_T2D_EXCLUDED_FROM_T1D_H1_LIKELIHOOD",
        },
        {
            "study_id": "Shi_2026_LancetDE_PMID_41765034",
            "pmid": "41765034",
            "source_pointers": "Shi et al. Lancet Diabetes Endocrinol Apr 2026;14(4):285-288 (PMID:41765034; Letter with 0 abstract chars in PubMed XML)",
            "product_class": "MIXED_UNVERIFIED_PAYWALLED_LETTER_REPORT",
            "transplant_site": "UNVERIFIED_FROM_PRIMARY_PDF",
            "immunosuppression_regimen": "CHRONIC_IS_AND_REPORTED_AUTOLOGOUS_IS_WITHDRAWAL_LOSS_PER_SECONDARY_REPORT",
            "observation_window": "Unverified from paywalled primary full text; repeat infusion reported in first recipient",
            "original_published_primary_endpoint": "Unverified from paywalled primary Letter full text",
            "published_counts": {"reported_recipients_n": 3, "primary_verified_counts": None},
            "attempted_gmp_lots_cmc_denominator_disclosed": False,
            "missing_data_and_adjudication_status": "UNAUTHENTICATED_PAYWALLED_LETTER_SENSITIVITY_ONLY",
        },
    ]

    cohorts = [
        {
            "cohort_id": "C1a_Reichman2025_FullDose_InsulinFree",
            "label": "Reichman et al. 2025 (NEJM; PMID:40544428) full-dose zimislecel Parts B/C insulin independence at Day 365 (10/12 under chronic glucocorticoid-free IS; 2/12 non-independent recipients received protocol-prohibited peri-infusion glucocorticoids)",
            "k": 10, "n": 12, "includes_reichman": True, "setting": "ALLOGENEIC_ESC",
            "primary_verified": True, "common_c2b_adjudicated": False, "exchangeable_likelihood_valid": True,
            "analysis_role": "SINGLE_STUDY_PUBLISHED_INSULIN_INDEPENDENCE_OBSERVATION",
            "immunosuppression_status": "CHRONIC_SYSTEMIC_IS_WITH_2_OF_12_PROHIBITED_GLUCOCORTICOID_INTERCURRENT_EVENTS",
        },
        {
            "cohort_id": "C1b_Reichman2025_FullDose_OriginalGlycemicEndpoint",
            "label": "Reichman et al. 2025 (NEJM; PMID:40544428) full-dose zimislecel Parts B/C original NEJM glycemic target (12/12; note Figure 3 has 11/12 Day-365 CGM records, 2/12 had prohibited peri-infusion glucocorticoids, and original NEJM endpoint differs from common C2b)",
            "k": 12, "n": 12, "includes_reichman": True, "setting": "ALLOGENEIC_ESC",
            "primary_verified": True, "common_c2b_adjudicated": False, "exchangeable_likelihood_valid": True,
            "analysis_role": "SINGLE_STUDY_ORIGINAL_PRIMARY_ENDPOINT_NOT_COMMON_C2B",
            "immunosuppression_status": "CHRONIC_SYSTEMIC_IS_WITH_11_OF_12_D365_CGM_AND_2_PROHIBITED_GLUCOCORTICOIDS",
        },
        {
            "cohort_id": "C1c_Reichman2025_Analyzed12Mo_Engraftment",
            "label": "Reichman et al. 2025 (NEJM; PMID:40544428) Parts A+B+C >=12-month follow-up analyzed population C-peptide+ engraftment (14/14 under IS: 2 Part A half-dose + 12 Parts B/C full-dose; excludes any dosed participants with <12 months follow-up)",
            "k": 14, "n": 14, "includes_reichman": True, "setting": "ALLOGENEIC_ESC",
            "primary_verified": True, "common_c2b_adjudicated": False, "exchangeable_likelihood_valid": False,
            "analysis_role": "SINGLE_STUDY_ANALYZED_GE12MO_FOLLOWUP_ENGRAFTMENT_OBSERVATION",
            "immunosuppression_status": "CHRONIC_SYSTEMIC_IS",
        },
        {
            "cohort_id": "C1d_NonReichman_PrimaryVerified_Wang2024_Only",
            "label": "Non-Reichman single-recipient observation: Wang et al. 2024 (Cell; PMID:39326417, 1/1 autologous CiPSC in abdominal anterior rectus sheath on continued 3-drug prior liver-tx IS + peri-infusion induction; distinct product/site/IS from allogeneic Core A/B/X)",
            "k": 1, "n": 1, "includes_reichman": False, "setting": "AUTOLOGOUS_CIPSC",
            "primary_verified": True, "common_c2b_adjudicated": False, "exchangeable_likelihood_valid": False,
            "analysis_role": "SINGLE_RECIPIENT_AUTOLOGOUS_OBSERVATION_NON_EXCHANGEABLE_WITH_ALLO",
            "immunosuppression_status": "CONTINUED_3_DRUG_PRIOR_LIVER_TX_IS_PLUS_PERI_INFUSION_INDUCTION",
        },
        {
            "cohort_id": "C2a_DescriptiveSensitivity_MixedT1D_InsulinFree_11of13",
            "label": "DESCRIPTIVE SENSITIVITY ONLY (conditional on assumed common-endpoint count 11/13; mixes incompatible Reichman 10/12 allogeneic hESC intraportal + Wang 1/1 autologous CiPSC rectus-sheath 3-drug-IS; non-exchangeable, non-promotable)",
            "k": 11, "n": 13, "includes_reichman": True, "setting": "MIXED_ALLO_AND_AUTO_INCOMPATIBLE",
            "primary_verified": False, "common_c2b_adjudicated": False, "exchangeable_likelihood_valid": False,
            "analysis_role": "DESCRIPTIVE_SENSITIVITY_ONLY_CONDITIONAL_ON_ASSUMED_COMMON_COUNTS",
            "immunosuppression_status": "MIXED_CHRONIC_SYSTEMIC_IS_NON_EXCHANGEABLE",
        },
        {
            "cohort_id": "C2b_DescriptiveSensitivity_MixedT1D_AssumedCommonC2b_13of13",
            "label": "DESCRIPTIVE SENSITIVITY ONLY (conditional on assumed common-C2b count 13/13; NOT primary-verified common C2b: Reichman Fig. 3 has 11/12 D365 CGM & 2/12 prohibited glucocorticoids; Wang is autologous rectus-sheath on 3-drug liver-tx IS; non-exchangeable, non-promotable)",
            "k": 13, "n": 13, "includes_reichman": True, "setting": "MIXED_ALLO_AND_AUTO_INCOMPATIBLE",
            "primary_verified": False, "common_c2b_adjudicated": False, "exchangeable_likelihood_valid": False,
            "analysis_role": "DESCRIPTIVE_SENSITIVITY_ONLY_CONDITIONAL_ON_ASSUMED_COMMON_COUNTS",
            "immunosuppression_status": "MIXED_CHRONIC_SYSTEMIC_IS_NON_EXCHANGEABLE",
        },
        {
            "cohort_id": "C3a_DescriptiveSensitivity_MixedT1D_T2D_InsulinFree_12of14",
            "label": "DESCRIPTIVE SENSITIVITY ONLY (conditional on assumed common count 12/14 adding Wu et al. Cell Discov 2024 T2D PMID:38684699 1/1 to mixed T1D 11/13; mixes T1D + T2D + allo + auto; non-exchangeable)",
            "k": 12, "n": 14, "includes_reichman": True, "setting": "MIXED_T1D_T2D_ALLO_AUTO_INCOMPATIBLE",
            "primary_verified": False, "common_c2b_adjudicated": False, "exchangeable_likelihood_valid": False,
            "analysis_role": "DESCRIPTIVE_SENSITIVITY_ONLY_CONDITIONAL_ON_ASSUMED_COMMON_COUNTS",
            "immunosuppression_status": "MIXED_CHRONIC_SYSTEMIC_IS_ALL_THREE_COHORTS",
        },
        {
            "cohort_id": "C4a_CAS_Secondary_Sensitivity_InsulinFree",
            "label": "DESCRIPTIVE SECONDARY SENSITIVITY ONLY adding Shi et al. 2026 (Lancet Diabetes Endocrinol; PMID:41765034) per 2026-02-26 CAS account / CEG M0144 (1/3 insulin-free; assumed 11+1 / 13+3)",
            "k": 12, "n": 16, "includes_reichman": True, "setting": "MIXED_ALLO_AND_AUTO_INCOMPATIBLE",
            "primary_verified": False, "common_c2b_adjudicated": False, "exchangeable_likelihood_valid": False,
            "analysis_role": "DESCRIPTIVE_SENSITIVITY_ONLY_CONDITIONAL_ON_ASSUMED_COMMON_COUNTS",
            "immunosuppression_status": "CHRONIC_IS_AND_AUTOLOGOUS_LOSS_UPON_IS_WITHDRAWAL",
        },
        {
            "cohort_id": "C4b_CAS_Secondary_Sensitivity_CpeptideUnderIS",
            "label": "DESCRIPTIVE SECONDARY SENSITIVITY ONLY adding Shi et al. 2026 assumed C-peptide restoration under IS (13+3 / 13+3; autologous recipient lost C-peptide post-IS withdrawal)",
            "k": 16, "n": 16, "includes_reichman": True, "setting": "MIXED_ALLO_AND_AUTO_INCOMPATIBLE",
            "primary_verified": False, "common_c2b_adjudicated": False, "exchangeable_likelihood_valid": False,
            "analysis_role": "DESCRIPTIVE_SENSITIVITY_ONLY_CONDITIONAL_ON_ASSUMED_COMMON_COUNTS",
            "immunosuppression_status": "CHRONIC_IS_REQUIRED",
        },
        {
            "cohort_id": "C5_Unauthenticated_SecondaryClaim_UpperBound_InsulinFree",
            "label": "DESCRIPTIVE UNAUTHENTICATED UPPER-BOUND SENSITIVITY assuming Shi 2026 = 3/3 insulin-free (14/16) — NOT verified from paywalled Lancet Letter PDF (0 abstract chars in PubMed)",
            "k": 14, "n": 16, "includes_reichman": True, "setting": "UNVERIFIED_SECONDARY_CLAIM",
            "primary_verified": False, "common_c2b_adjudicated": False, "exchangeable_likelihood_valid": False,
            "analysis_role": "DESCRIPTIVE_SENSITIVITY_ONLY_CONDITIONAL_ON_ASSUMED_COMMON_COUNTS",
            "immunosuppression_status": "UNVERIFIED_SECONDARY_CLAIM",
        },
    ]

    results = []
    for c in cohorts:
        k, n = c["k"], c["n"]
        cp_lo, cp_hi = clopper_pearson_ci(k, n)
        post: dict[str, Any] = {}
        for pname, (a0, b0) in non_informative_priors.items():
            post[pname] = _beta_posterior_summary(a0, b0, k, n, overlap_status="NON_OVERLAPPING_PRIOR_LIKELIHOOD")
        for pname, (a0, b0) in anchored_priors.items():
            ov = (
                "OVERLAPPING_PRIOR_DIAGNOSTIC_ONLY_DOUBLES_REICHMAN"
                if c["includes_reichman"]
                else "NON_OVERLAPPING_PRIOR_LIKELIHOOD"
            )
            post[pname] = _beta_posterior_summary(a0, b0, k, n, overlap_status=ov)
        results.append({
            **c,
            "observed_rate_pct": round(100.0 * k / n, 2),
            "clopper_pearson_95_ci_pct": [round(100.0 * cp_lo, 2), round(100.0 * cp_hi, 2)],
            "clopper_pearson_95_ci_scope": "NOMINAL_IID_UNADJUSTED_RECIPIENT_COUNTS_ONLY_NOT_CLUSTER_ADJUSTED",
            "bayesian_posteriors": post,
        })

    # Explicit descriptive sensitivity decision table for all 4 possible Shi 2026 (n=3) assumed C2b outcomes:
    # Replaces retired contradictory ">=2/3 flips H1" rule (which lowered overlapping P(H1>=90%) 86.31% -> 67.73%).
    # Even under the hypothetical assumption of common C2b counts, all four Shi n=3 scenarios fail posterior
    # thresholds AND remain mixed-cohort descriptive sensitivities (non-promotable under the single-compatible-cohort rule).
    shi_decision_table = []
    for k_shi in (3, 2, 1, 0):
        k_pool = 13 + k_shi
        n_pool = 16
        k_nonr = 1 + k_shi  # Assumed descriptive sensitivity: Wang 2024 (1/1) + Shi 2026 (k_shi/3)
        n_nonr = 4
        cp_lo, cp_hi = clopper_pearson_ci(k_pool, n_pool)
        unif = _beta_posterior_summary(1.0, 1.0, k_pool, n_pool, overlap_status="NON_OVERLAPPING_PRIOR_LIKELIHOOD")
        jeff = _beta_posterior_summary(0.5, 0.5, k_pool, n_pool, overlap_status="NON_OVERLAPPING_PRIOR_LIKELIHOOD")
        nonr_anch = _beta_posterior_summary(8.8, 1.2, k_nonr, n_nonr, overlap_status="NON_OVERLAPPING_PRIOR_LIKELIHOOD")
        diag_ov = _beta_posterior_summary(8.8, 1.2, k_pool, n_pool, overlap_status="OVERLAPPING_PRIOR_DIAGNOSTIC_ONLY_DOUBLES_REICHMAN")
        passes_unif = unif["prob_ge_90_exact"] >= 0.90
        passes_nonr = nonr_anch["prob_ge_90_exact"] >= 0.85
        if passes_unif and passes_nonr:
            disp = "HOLD_H1_AT_88PCT_MIXED_COHORT_SENSITIVITY_ONLY"
        elif k_shi <= 1:
            disp = "HOLD_H1_AT_88PCT_AND_TRIGGER_DOWNWARD_REAUDIT"
        else:
            disp = "HOLD_H1_AT_88PCT_INSUFFICIENT_POSTERIOR_MASS"
        shi_decision_table.append({
            "analysis_role": "DESCRIPTIVE_SENSITIVITY_CONDITIONAL_ON_ASSUMED_COMMON_COUNTS_NON_PROMOTABLE_MIXED_COHORT",
            "shi_assumed_c2b_outcome": f"{k_shi}/3",
            "assumed_mixed_t1d_c2b_sensitivity": f"{k_pool}/{n_pool}",
            "descriptive_clopper_pearson_95_ci_pct": [round(100.0 * cp_lo, 2), round(100.0 * cp_hi, 2)],
            "descriptive_clopper_pearson_95_ci_scope": "NOMINAL_IID_UNADJUSTED_RECIPIENT_COUNTS_ONLY_NOT_CLUSTER_ADJUSTED",
            "uniform_Beta_1_1_posterior": unif,
            "jeffreys_Beta_0p5_0p5_posterior": jeff,
            "non_reichman_sensitivity_k_of_4": f"{k_nonr}/{n_nonr}",
            "non_overlapping_Beta_8p8_1p2_on_non_reichman_sensitivity": nonr_anch,
            "retired_double_counted_Beta_8p8_1p2_diagnostic": diag_ov,
            "passes_uniform_ge_90pct": passes_unif,
            "passes_non_overlapping_anchored_ge_85pct": passes_nonr,
            "gate_28a_disposition": disp,
        })

    # Programmatic exact verification of Uniform Beta(1,1) nominal integer lower-bound counts (21/21 & 36/37)
    # and the exact continuous fractional all-success Uniform transition n_eff = ln(0.10)/ln(0.90) - 1 ~= 20.854345
    p_u_20_20 = 1.0 - beta_cdf(0.90, 21.0, 1.0)
    p_u_21_21 = 1.0 - beta_cdf(0.90, 22.0, 1.0)
    p_u_35_36 = 1.0 - beta_cdf(0.90, 36.0, 2.0)
    p_u_36_37 = 1.0 - beta_cdf(0.90, 37.0, 2.0)
    continuous_all_success_n_eff_transition = (math.log(0.10) / math.log(0.90)) - 1.0
    if not (p_u_20_20 < 0.90 <= p_u_21_21):
        raise ValueError(f"Uniform minimum zero-failure check failed: 20/20={p_u_20_20}, 21/21={p_u_21_21}")
    if not (p_u_35_36 < 0.90 <= p_u_36_37):
        raise ValueError(f"Uniform minimum one-failure check failed: 35/36={p_u_35_36}, 36/37={p_u_36_37}")

    # Verify exact mathematical and governance sanity checks (optimize-safe!)
    wang_only = next(c for c in results if c["cohort_id"] == "C1d_NonReichman_PrimaryVerified_Wang2024_Only")
    if abs(wang_only["bayesian_posteriors"]["openislet_prior_Beta_8p8_1p2_n10"]["prob_ge_90_exact"] - 0.563803) >= 1e-4:
        raise ValueError("Wang 2024 non-overlapping Beta(8.8,1.2) posterior sanity check failed")
    c2b_row = next(c for c in results if c["cohort_id"] == "C2b_DescriptiveSensitivity_MixedT1D_AssumedCommonC2b_13of13")
    if c2b_row["primary_verified"] is not False or c2b_row["common_c2b_adjudicated"] is not False:
        raise ValueError("Mixed 13/13 C2b sensitivity MUST NOT be marked primary_verified=True or common_c2b_adjudicated=True")
    if not all(row["gate_28a_disposition"].startswith("HOLD_H1_AT_88PCT") for row in shi_decision_table):
        raise ValueError("Expected all four Shi 2026 scenarios to hold live H1 at 88%")

    return {
        "live_openislet_h1_held_today": 0.88,
        "conditional_h1_sensitivity_target": 0.90,
        "live_reanchor_decision": "HOLD_LOCKED_AT_0p88_SINGLE_COMPATIBLE_POST_RELEASE_COHORT_NOT_MET",
        "prior_vs_posterior_audit_note": (
            "Beta(8.8, 1.2) is the clinical post-release prior (mean 88.00%), NOT a posterior and NOT calibrated for "
            "CMC attempted-lot manufacturing yield. Because live ISLET-1-BLUEPRINT.md line 37 already cites Reichman 2025 "
            "to anchor H1 = 0.88, updating Beta(8.8, 1.2) with Reichman's 12 outcomes double-counts Reichman. All mixed "
            "13/13 and 11/13 intervals/posteriors are descriptive sensitivities conditional on assumed common-endpoint counts: "
            "under non-informative Uniform Beta(1,1), assumed 13/13 yields Beta(14,1) (mean 93.33%, P(H1>=90%)=77.12%; Jeffreys 90.53%) "
            "and assumed 11/13 yields Beta(12,3) (mean 80.00%, P(H1>=90%)=15.84%). Updating Beta(8.8, 1.2) strictly with non-Reichman "
            "Wang 2024 (1/1; incompatible autologous product/site/IS) gives descriptive Beta(9.8, 1.2) (mean 89.09%, P(H1>=90%)=56.38%). "
            "The retired 'flip iff >=2/3 Shi' rule is removed because 2/3 lowers P(H1>=90%) across every prior."
        ),
        "uniform_prior_minimum_threshold_verification": {
            "zero_failure_minimum_k_of_n": "21/21",
            "zero_failure_minimum_classification": "nominal_integer_lower_bound_unclustered_iid",
            "continuous_all_success_uniform_n_eff_transition": round(continuous_all_success_n_eff_transition, 6),
            "threshold_modeling_note": (
                "21/21 is the nominal integer lower bound under unclustered DEFF=1.0 i.i.d. assumptions; "
                "under the continuous fractional likelihood approximation Beta(1 + n_eff, 1), the exact "
                "all-success Uniform transition occurs at n_eff ~= 20.854345, and near the threshold "
                "exchangeability and ICC assumptions dominate over display rounding. All cluster-adjusted "
                "Beta-Binomial probabilities on fractional (k_eff, n_eff) are prespecified decision-model "
                "quantities conditional on assumed lot/bank variance-component ICCs (rho_lot, rho_bank) "
                "and cohort exchangeability rather than independently calibrated empirical probabilities."
            ),
            "prob_ge_90pct_at_20_of_20": round(100.0 * p_u_20_20, 4),
            "prob_ge_90pct_at_21_of_21": round(100.0 * p_u_21_21, 4),
            "one_failure_minimum_k_of_n": "36/37",
            "prob_ge_90pct_at_35_of_36": round(100.0 * p_u_35_36, 4),
            "prob_ge_90pct_at_36_of_37": round(100.0 * p_u_36_37, 4),
        },
        "per_study_endpoint_adjudication_ledger": per_study_endpoint_adjudication_ledger,
        "gate_28a_coherent_decision_contract": {
            "clinical_estimands_strictly_separated": {
                "blueprint_h1_clinical_post_release_estimand": (
                    "ISLET-1-BLUEPRINT.md:37 establishes the released-product post-release scope (conditioning in-body hurdles on passing "
                    "laboratory/GMP release checks) and the 88% illustrative class-level Hurdle-1 judgment. Gate 28-A (IIP-0041 / DEC-120) "
                    "operationalizes this post-release clinical estimand for future promotion adjudication as: "
                    "H1_Blueprint = P(durable >= 6-month adjudicated C2b glycemic target restoration under de novo chronic glucocorticoid-free "
                    "systemic IS | released full-dose GMP allogeneic SC-islet lot infused intraportally into an enrolled T1D recipient). "
                    "Held live at 0.88 (+0.00 pp). Reichman-anchored Beta(8.8, 1.2) applies ONLY to non-overlapping post-release clinical "
                    "cohorts on this same estimand. Changes in CMC lot-release or infusion-utilization rate alone can NEVER move Blueprint H1."
                ),
                "release_only_cmc_yield_metric": (
                    "P_release_CMC = N_released_lots / N_attempted_lots = "
                    "P(GMP lot passes pre-infusion release specifications | GMP manufacturing lot initiated). "
                    "Reported cleanly as a separate standalone operational CMC yield metric."
                ),
                "separate_cmc_attempted_lot_readiness_metric": (
                    "H1_CMC_ATTEMPTED_LOT_READINESS = P_release_CMC * P_infuse_given_released * H1_Blueprint, where "
                    "P_infuse_given_released = infused_primary_course_equivalents / released_lots_n carries explicit unit "
                    "infused primary-course equivalents per released lot (course-equivalent weighted rate, distinct from raw "
                    "physical-lot utilization — e.g., under a 2-lot pooled course both physical lots are infused [100% physical-lot "
                    "utilization] while course-equivalent p_infuse_given_released = 1.0 / 2 = 0.50). "
                    "Worked single-lot example: at P_release_CMC = 0.80, course-equivalent P_infuse_given_released = 0.50, and "
                    "H1_Blueprint = 0.88, the projected successful primary-course equivalents per attempted lot is 0.80 * 0.50 * 0.88 = 0.352 "
                    "(35.2% primary-course equivalents per attempted lot, NOT 70.4%; distinct from a physical-lot success probability "
                    "once a recipient's course spans multiple lots), while release-only P_release_CMC = 80.0% and authoritative measured weighted CMC readiness "
                    "(measured_weighted_cmc_readiness = lot_weighted_primary_successes / attempted_lots_n) are reported separately "
                    "from diagnostic unweighted-recipient-rate empirical_product_readiness "
                    "(DIAGNOSTIC_UNWEIGHTED_RECIPIENT_RATE_PRODUCT_ONLY) with matching conditioning and outcome "
                    "weights across every topology: released-but-uninfused lots (infusion = 0), "
                    "split lots (lot-level release weight 1, recipient-dose infusion weight infused_doses_n / planned_doses_n, explicit per-recipient "
                    "outcomes with zero positional inference), prespecified pooled multi-lot courses (complete reconciled membership, single agreed "
                    "primary_lot_id, matching course-equivalent infusion and outcome weight 1 / len(course_lot_ids) per constituent lot), and unplanned rescue repeat "
                    "lots (validated against an existing initial primary course, reconciled bidirectionally on exact rescue event "
                    "identities AND cardinalities/multiplicities between clinical cohort and raw CMC ledger so any extra, missing, "
                    "duplicate, or mismatched rescue lot fails closed, requiring independent verified ancestry in "
                    "VERIFIED_LOT_TO_BANK_MANIFEST including explicit matching wcb_id whenever declared in manifest, primary-course "
                    "infusion weight = 0, forced 0 primary credit on the rescued recipient), while retaining 1:1 unique recipients "
                    "in clinical H1; NEVER overloaded onto Blueprint H1 or Reichman's Beta(8.8, 1.2) prior."
                ),
                "is_free_boundary": (
                    "H1_Blueprint, P_release_CMC, and H1_CMC_ATTEMPTED_LOT_READINESS operate strictly under chronic systemic immunosuppression "
                    "and are explicitly distinct from C2a strict insulin independence and from OpenIslet's IS-free cure target "
                    "(ZERO spillover credit to IS-free H2/H3)."
                ),
            },
            "observation_unit_and_intercurrent_event_rules": {
                "primary_observation_unit": (
                    "1:1 unique enrolled, infused full-dose single-lot T1D recipient (each unique recipient enters the clinical H1 "
                    "binomial likelihood at most once; full-dose split-lot recipients receiving a complete prespecified single-lot "
                    "dose are eligible with cluster ancestry bound uniquely to that single lot_id/mcb_id while unused aliquots stay "
                    "in CMC; pooled multi-lot courses spanning >= 2 lots per recipient are tracked in CMC and excluded from primary "
                    "single-lot nested-cluster Gate 28-A promotion unless a prespecified multi-membership cluster model is registered)."
                ),
                "unused_failed_and_split_lot_disposition": (
                    "Failed/unreleased GMP lots, released-but-uninfused lots (infusion = 0), unused split-lot aliquots (infusion = 0), "
                    "and pooled multi-lot courses spanning >= 2 lots per recipient are excluded from the primary single-lot clinical H1 "
                    "recipient denominator and logged strictly in the separate CMC Readiness Ledger via "
                    "evaluate_cmc_attempted_lot_readiness(...) (attempted_lots_n, released_lots_n, uninfused_released_lots_n, "
                    "failed_release_lots_n, infused_lot_equivalents, projected_cmc_attempted_lot_readiness, "
                    "measured_weighted_cmc_readiness, lot_id -> mcb_id -> recipient_id)."
                ),
                "unified_intercurrent_event_adjudication_table": dict(GATE_28A_INTERCURRENT_EVENT_ADJUDICATION),
                "repeat_infusion_rule": (
                    "A recipient requiring a rescue repeat full-dose infusion to achieve or restore C2b counts as a primary "
                    "single-infusion non-responder (0) in BOTH Gate 28-A clinical H1 and primary-lot CMC readiness (multi-infusion rescue "
                    "outcomes may appear only as a separate descriptive sensitivity). Pooled multi-lot courses are excluded from primary "
                    "single-lot Gate 28-A promotion unless a prespecified multi-membership cluster model is registered."
                ),
                "prohibited_concomitant_therapy_rule": (
                    "Protocol-prohibited peri-infusion systemic glucocorticoids count deterministically as primary non-responders (0) in the "
                    "primary glucocorticoid-free H1 estimand (identical across protocol, side contract, DEC-120, and evaluate_gate28a_h1_promotion); "
                    "any steroid-exposed treatment-policy analysis is segregated strictly as a non-promoting secondary sensitivity."
                ),
                "missingness_and_dropout_rule": (
                    "Lost-to-follow-up, incomplete primary follow-up (< 6 months), missing required CGM/HbA1c/SHE/C-peptide observations, "
                    "primary graft non-function, or pre-landmark death count deterministically as primary non-responders (0); adjudicated "
                    "unrelated deaths with intact pre-death stimulated C-peptide may appear only in a separate descriptive sensitivity."
                ),
                "bank_and_lot_cluster_promotion_rule": (
                    "Every infused recipient MUST undergo Pass-0 unconditional raw clinical ancestry extraction across EVERY raw "
                    "row in recipients BEFORE follow-up, endpoint, intercurrent-event, or duplicate-recipient skipping (detecting "
                    "CONFLICTING_DUPLICATE_RECIPIENT_ANCESTRY and preserving missing-follow-up rows for manifest and raw-CMC "
                    "reconciliation across both normal and CMC-exception error-audit paths), carrying literal mcb_id and lot_id "
                    "linkage reconciled against a verified lot_to_mcb_manifest "
                    "(mapping every observed lot_id uniquely to ONE single mcb_id) AND a verified lot_to_wcb_manifest whenever ANY recipient "
                    "or manifest declares WCB. ALL supported manifest aliases (lot_to_mcb_manifest, lot_to_wcb_manifest, lot_to_bank_manifest) "
                    "are canonically bound in cohort_canonical_sha256 AND normalized/validated through ONE unified hierarchy validator in BOTH "
                    "cohort payloads and external VERIFIED_LOT_TO_BANK_MANIFEST records (rejecting overlapping contradictions, extra/widening "
                    "alias declarations, unrecognized manifest alias keys, and non-unique wcb_id -> mcb_id parentage across the combined "
                    "declarations). There is ZERO fallback to unverified recipient rows OR unverified inline manifests: absent "
                    "trusted_clinical_store, failed VERIFIED_LOT_TO_BANK_MANIFEST resolution, conflicting/widening/unrecognized bank or WCB "
                    "aliases (rejected BEFORE merging), non-unique WCB-to-MCB parentage (every distinct literal wcb_id MUST map to at most ONE mcb_id), "
                    "or missing/invalid/conflicting/mismatched manifests immediately return lot_bank_hierarchy_valid=False, "
                    "lot_to_mcb_manifest_verified=False, lot_to_wcb_manifest_verified=False, and null deff/n_eff/k_eff. Promotion requires resolving ALL "
                    "FOUR authenticated records from an independent external trusted_clinical_store (NEVER self-attested inline dicts): "
                    "PRESPECIFICATION_ATTESTATION and SOURCE_VERIFICATION_ATTESTATION bound to cohort_id and the full canonical cohort digest "
                    "(all compatibility fields, includes_reichman, primary_peer_reviewed_full_text_verified, "
                    "parallel_cmc_readiness_ledger_disclosed, rho_lot, rho_bank, lot_to_mcb_manifest, lot_to_wcb_manifest, "
                    "lot_to_bank_manifest, any extra manifest aliases, parallel_cmc_readiness_ledger_sha256, and canonical recipients — "
                    "injectively binding presence/absence of decision-relevant control flags and normalizing equivalent recipient "
                    "working_cell_bank_id <-> wcb_id aliases before hashing while preserving conflicts in the digest), VERIFIED_LOT_TO_BANK_MANIFEST, "
                    "and raw PARALLEL_CMC_READINESS_LEDGER bytes decoded strictly (rejecting duplicate JSON keys and non-finite numbers "
                    "fail-closed with null cluster outputs), passing evaluate_cmc_attempted_lot_readiness (with typed "
                    "CMCAncestryValidationError propagation and unconditional Pass-0-backed raw-CMC ancestry auditing so initial-validation and "
                    "cross-reconciliation ancestry contradictions — including WCB reuse across infused and failed-release lots, "
                    "canonical MCB vs recognized MCB/WCB alias conflict on any disposition, duplicate lot_id, or recipient lot/MCB/WCB "
                    "mismatch even when follow-up is missing or another CMC shape error occurs — all return parallel_cmc_ledger_verified=False, "
                    "lot_bank_hierarchy_valid=False, lot_to_mcb_manifest_verified=False, lot_to_wcb_manifest_verified=False, and null "
                    "deff/n_eff/k_eff), reconciling infused recipients AND exact rescue repeat-lot identities and cardinalities/multiplicities "
                    "bidirectionally BEFORE ordinary CMC validation can short-circuit it (0 clinical rescues = 0 CMC rescue lots; every clinically declared rescue repeat infusion MUST declare "
                    "an explicit canonical clinical rescue_lot_id or non-empty rescue_lot_ids list matching sorted CMC infused rescue lots "
                    "identically — ANY presence of an undocumented *rescue*lot* alias key such as rescue_repeat_lot_id / rescue_repeat_lot_ids [even with value None/null/empty or on intercurrent_event='NONE'] and unindexed rescue "
                    "declarations fail closed with UNRECOGNIZED_CLINICAL_RESCUE_LOT_ALIAS / CLINICAL_RESCUE_MISSING_EXPLICIT_LOT_ID, "
                    "duplicate clinical recipient rows extract raw rescue claims in Pass 0 and invalidate CMC verification "
                    "order-independently across all row permutations with DUPLICATE_CLINICAL_RECIPIENT_INVALIDATES_CMC_RECONCILIATION, "
                    "and ANY single-row or duplicate-row clinical-vs-CMC rescue identity, cardinality, omission, unindexed-rescue, or lineage contradiction [CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT / CLINICAL_RESCUE_LOT_ID_MISMATCH_IN_CMC_LEDGER / CLINICAL_RESCUE_OMITTED_FROM_CMC_LEDGER / CMC_EXTRA_RESCUE_LOT_OMITTED_FROM_CLINICAL_COHORT / CONFLICTING_DUPLICATE_RECIPIENT_RESCUE] — as well as EVERY distinct Pass-0 clinical primary-lot claim across all single and duplicate rows per recipient contradicting a raw CMC non-infused disposition (RELEASED_UNINFUSED, FAILED_RELEASE, or missing/non-infused disposition) or absent/uninfused primary lot [CLINICAL_PRIMARY_LOT_CMC_DISPOSITION_CONFLICT / CLINICAL_PRIMARY_LOT_MISSING_FROM_CMC_LEDGER / CLINICAL_PRIMARY_RECIPIENT_MISSING_FROM_CMC_LOT], audited against any attested raw CMC ledger in trusted_clinical_store EVEN BEFORE returning on clinical hierarchy errors such as CONFLICTING_DUPLICATE_RECIPIENT_ANCESTRY so both contradiction classes are always collected — routes unconditionally through "
                    "the full fail-closed ancestry nullification path returning parallel_cmc_ledger_verified=False, "
                    "lot_bank_hierarchy_valid=False, lot_to_mcb_manifest_verified=False, lot_to_wcb_manifest_verified=False, "
                    "icc_sensitivity_report_attached=False, and null deff/n_eff/k_eff in every row permutation even when an unrelated CMC shape error occurs, and every CMC "
                    "primary recipient outcome MUST reconcile against a deterministically adjudicated clinical outcome with deterministic "
                    "ITT non-response events adjudicated to 0 BEFORE endpoint/follow-up validation), AND reconciling raw CMC row ancestry "
                    "across EVERY disposition (all clinically infused primary, split, and rescue lots MUST carry matching independent "
                    "verified ancestry in VERIFIED_LOT_TO_BANK_MANIFEST AND explicitly attest matching wcb_id or recognized alias "
                    "working_cell_bank_id whenever declared in VERIFIED_LOT_TO_BANK_MANIFEST; non-infused RELEASED_UNINFUSED and "
                    "FAILED_RELEASE rows are optional in the verified manifest but MUST NOT contradict VERIFIED_LOT_TO_BANK_MANIFEST "
                    "or the unified wcb_id -> mcb_id parentage tree; semantic canonicalization preserves cohort_canonical_sha256 across "
                    "equivalent WCB representations [working_cell_bank_id <-> wcb_id and matching top-level lot_to_wcb_manifest alongside "
                    "identical nested WCB declarations] while any semantic ancestry mutation, conflict, widening, or "
                    "lot_to_bank_manifest/unrecognized alias addition alters cohort_canonical_sha256 and fails closed); ALL structural "
                    "manufacturing diversity floors (distinct_gmp_lots_n >= 3, distinct_mcb_n >= 2, max_single_lot_share <= 0.40 via exact "
                    "context-independent Fraction); AND both posteriors on cluster-adjusted effective sample size (k_eff, n_eff) where "
                    "DEFF = 1 + rho_lot * ((sum(m_g^2) / n) - 1) + rho_bank * ((sum(b_c^2) / n) - 1), n_eff = n / DEFF, "
                    "k_eff = n_eff * (k / n), with separate additive variance-component ICC shares rho_bank = sigma_bank^2 / sigma_tot^2 "
                    "and rho_lot = sigma_lot^2 / sigma_tot^2 (same-lot total correlation = rho_lot + rho_bank) enforcing conservative "
                    "prespecified floors rho_lot >= 0.05 and rho_bank >= 0.02 AND 0 <= rho_lot, 0 <= rho_bank, "
                    "rho_lot + rho_bank <= 1.0 (failing closed with INVALID_ICC_SUM_EXCEEDS_ONE / INVALID_ICC_DOMAIN and null "
                    "deff/n_eff/k_eff if violated), PLUS mandatory attachment of the prespecified 3-scenario same-cohort "
                    "icc_sensitivity_report (primary_floor=(0.05, 0.02), moderate_sensitivity=(0.10, 0.05), "
                    "high_clustering_sensitivity=(0.15, 0.10)) and explicit 4-state icc_sensitivity_review_status "
                    "(ROBUST_ACROSS_ALL_THREE_PRESPECIFIED_ICC_SCENARIOS [all 3 clear -> may promote]; "
                    "BOUNDARY_SENSITIVE_DISCLOSED_CLEARS_PRIMARY_AND_MODERATE [primary & moderate clear, high holds -> may promote ONLY "
                    "with attached sensitivity report disclosing boundary_sensitive_under_high_icc=True]; "
                    "HOLD_FAILS_MODERATE_ICC_SENSITIVITY [moderate (0.10, 0.05) fails -> HARD HOLD, NEVER promote]; "
                    "HOLD_FAILS_PRIMARY_ICC_FLOOR [primary floor (0.05, 0.02) fails -> HARD HOLD]); all cluster-adjusted "
                    "Beta-Binomial probabilities on fractional (k_eff, n_eff) and across the 3-scenario icc_sensitivity_report "
                    "are prespecified decision-model quantities conditional on assumed variance-component ICCs and cohort "
                    "exchangeability rather than independently calibrated empirical probabilities. A heavily skewed 20+1 split or "
                    "single-bank 21/21 cohort fails closed."
                ),
            },
            "single_compatible_cohort_transport_rule": {
                "promotion_restricted_to_single_compatible_cohort": True,
                "naive_pooling_prohibited": True,
                "unparameterized_hierarchical_transport_authorized": False,
                "prespecified_compatibility_target": dict(GATE_28A_COMPATIBILITY_TARGET),
                "rule": (
                    "Gate 28-A promotion of Blueprint H1 is STRICTLY RESTRICTED to a SINGLE prespecified, protocol-compatible "
                    "infused-recipient cohort matching the exact prespecified compatibility target: "
                    "(1) product_class = ALLOGENEIC_GMP_SC_ISLET (strictly separate from autologous CiPSC and edited D1b-Auto-C v2 "
                    "whose p1 stays held at 0.62), (2) transplant_site = INTRAPORTAL_HEPATIC, (3) disease_population = TYPE_1_DIABETES, "
                    "(4) immunosuppression_protocol_class = DE_NOVO_CHRONIC_GLUCOCORTICOID_FREE_SYSTEMIC_IS, and "
                    "(5) dose_regimen = FULL_DOSE_SINGLE_INFUSION. Naive fixed-effect pooling across distinct products, sites, diseases, "
                    "or IS regimens is PROHIBITED, and unparameterized hierarchical transport pooling is NOT authorized under Gate 28-A. "
                    "Mixed-cohort intervals/posteriors are descriptive sensitivities only."
                ),
            },
            "durability_horizon": ">= 6 months (>= 180 days) sustained adjudicated HbA1c < 7.0%, CGM TIR > 70%, 0 SHEs, and quantitative stimulated C-peptide+ under chronic glucocorticoid-free IS.",
            "cmc_readiness_ledger_failure_definition": (
                "Logged in the separate CMC Readiness Ledger (P_release_CMC and H1_CMC_ATTEMPTED_LOT_READINESS, NOT Blueprint H1): any GMP lot failing "
                "pre-infusion release specifications (viability, endocrine/beta-cell purity, static/dynamic GSIS potency, sterility/endotoxin), "
                "released-but-uninfused lot disposition (infusion = 0), or unused split-lot aliquots; clinical primary graft non-function "
                "(stimulated C-peptide < 0.1 ng/mL [< 33 pmol/L] by Day 90) counts as a clinical non-responder (0) in Blueprint H1."
            ),
            "pre_registered_posterior_flip_rule": (
                "Flip live Blueprint H1 from 0.88 to 0.90 IF AND ONLY IF evaluate_gate28a_h1_promotion(...) passes on a SINGLE prespecified, "
                "primary-verified, compatibility-target-matched full-dose T1D post-release infused-recipient cohort (1:1 unique recipients; "
                "distinct_gmp_lots_n >= 3; distinct_mcb_n >= 2; max_single_lot_share <= 0.40; unified intercurrent-event adjudication where "
                "rescue repeat infusion, prohibited peri-infusion glucocorticoids, missingness/LTFU, and pre-landmark death all equal 0): "
                "(1) Non-overlapping Uniform Beta(1,1) posterior P(H1 >= 0.90) >= 0.90 on cluster-adjusted (k_eff, n_eff) "
                "(21/21 [90.1523%; 20/20 = 89.0581% fails] and 36/37 [90.4705%; 35/36 = 89.6369% fails] are nominal integer "
                "lower bounds under unclustered DEFF=1.0 i.i.d. assumptions only; the exact continuous fractional all-success "
                "Uniform transition occurs at n_eff ~= 20.854345, and exchangeability and ICC assumptions dominate near the threshold), AND "
                "(2) Non-overlapping Reichman-anchored Beta(8.8,1.2) updated solely on a compatible non-Reichman cohort achieves "
                "P(H1 >= 0.90) >= 0.85 on cluster-adjusted (k_eff, n_eff), AND "
                "(3) Primary peer-reviewed PDFs verify >= 6-month sustained C2b durability, quantitative stimulated C-peptide, complete "
                "per-recipient adjudication, and transparent parallel disclosure of the separate CMC Readiness Ledger "
                "(P_release_CMC and H1_CMC_ATTEMPTED_LOT_READINESS). Clopper-Pearson 95% CIs MUST be published alongside any future headline change."
            ),
            "shi_2026_outcome_decision_table": shi_decision_table,
            "wang2024_autologous_vs_d1b_p1_asymmetry": (
                "Wang et al. 2024 (PMID:39326417) used unedited autologous CiPSC-islets in the abdominal anterior rectus sheath under "
                "continued 3-drug prior liver-tx IS plus peri-infusion induction; in Part D S2a, D1b-Auto-C v2 p1 is conservatively "
                "held at 0.62 (reflecting sequential 6-locus GMP editing friction rather than unedited CiPSC differentiation), "
                "while S2b reports the proportionally scaled 0.6341 sensitivity."
            ),
            "primary_cmc_and_registry_sources": [
                "ClinicalTrials.gov NCT04786262 (updated 2026-09-01; Phase 1/2/3 master protocol evaluating VX-880/zimislecel and VX-017, target enrollment n=57, primary completion 2027-12-31)",
                "Vertex Pharmaceuticals Q1 2026 Corporate/Earnings Update (May 2026: Jan 2026 voluntary zimislecel dosing pause for internal manufacturing analysis completed and dosing resumed; original 2026 BLA delayed)",
                "Vertex Pharmaceuticals Q3 2026 Corporate/Earnings Release (Nov 2, 2026: strategic prioritization of universal-donor Type-O VX-017 with FDA Fast Track designation over blood-type A/AB-restricted zimislecel; pivotal initiation expected 2027)",
            ],
        },
        "key_forensic_findings": [
            "Reichman et al. 2025 (NEJM; PMID:40544428): n = 14 analyzed population comprises 14 dosed participants in Parts A-C with >= 12 months follow-up (2 half-dose Part A + 12 full-dose Parts B/C; excludes any dosed participants with < 12 months follow-up), with 14/14 C-peptide+ engraftment; in the 12 full-dose Parts B/C 12-month analysis, 12/12 met the original NEJM glycemic endpoint, 11/12 had Day-365 CGM records in Figure 3, 10/12 (83.33%) were insulin-independent at Day 365, and 2/12 received protocol-prohibited peri-infusion glucocorticoids (both remained on insulin); 2 deaths occurred in the 14-participant analyzed population: 1 fatal cryptococcal meningitis (~19.5 months post-infusion) following surgery complicated by skull-base injury, prolonged protocol-prohibited systemic glucocorticoids, and concurrent chronic immunosuppression (assessed by investigators as unrelated to zimislecel [cell product] BUT related to the chronic immunosuppressive medication regimen), and 1 progression of pre-existing neurocognitive disease (~30 months post-infusion, unrelated to zimislecel or immunosuppression).",
            "Vertex 2026 CMC & strategic update (ClinicalTrials.gov NCT04786262 [2026-09-01]; Vertex Q1 2026 [May 2026] & Q3 2026 [Nov 2, 2026] earnings releases): tracked in the separate CMC Readiness Ledger (P_release_CMC and H1_CMC_ATTEMPTED_LOT_READINESS = P_release_CMC * P_infuse_given_released * H1_Blueprint) without overloading Blueprint H1's post-release clinical estimand.",
            "Wang et al. 2024 (Cell; PMID:39326417): 1/1 sustained insulin independence from Day 75 through 1 year in the abdominal anterior rectus sheath (ChiCTR2300072200), BUT recipient continued a 3-drug IS regimen from prior liver transplantation plus peri-infusion induction -> distinct product, site, and IS regimen from Reichman; mixed 13/13 intervals/posteriors are descriptive sensitivities only (primary_verified=False); autologous D1b-Auto-C v2 p1 stays held at 0.62.",
            "Shi et al. Lancet Diabetes Endocrinol Apr 2026;14(4):285-288 (PMID:41765034, DOI:10.1016/S2213-8587(25)00423-1): Live PubMed efetch confirms PublicationType=Letter with 0 abstract chars (paywalled). Investigators describe a repeat infusion in the first recipient; secondary claim of '3/3 insulin-independent' is unauthenticated and conflicts with the 2026-02-26 CAS institutional report logged in OpenIslet CEG M0144 (1/3 insulin-independent; autologous recipient lost detectable C-peptide upon stopping IS). Even under hypothetical assumed counts, all four n=3 scenarios hold live H1 at 88%.",
            "Strict H1 vs H2/H3 separation: Every human SC-islet insulin-independence durability outcome to date (Reichman, Wang, Wu, Shi) occurred under systemic immunosuppression. Live Blueprint H1 stays locked at 0.88 (+0.00 pp today); H1 = 0.90 remains strictly a conditional sensitivity with ZERO spillover onto IS-free H2/H3.",
        ],
        "cohorts": results,
    }


# =============================================================================
# EXECUTABLE CMC ATTEMPTED-LOT READINESS & BANK/LOT-AWARE GATE 28-A EVALUATORS
# =============================================================================
GATE_28A_COMPATIBILITY_TARGET: dict[str, str] = {
    "product_class": "ALLOGENEIC_GMP_SC_ISLET",
    "transplant_site": "INTRAPORTAL_HEPATIC",
    "disease_population": "TYPE_1_DIABETES",
    "immunosuppression_protocol_class": "DE_NOVO_CHRONIC_GLUCOCORTICOID_FREE_SYSTEMIC_IS",
    "dose_regimen": "FULL_DOSE_SINGLE_INFUSION",
}

GATE_28A_INTERCURRENT_EVENT_ADJUDICATION: dict[str, Any] = {
    "NONE": "PRIMARY_RESPONDER_1_IF_ALL_C2B_CRITERIA_MET_ELSE_0",
    "RESCUE_REPEAT_INFUSION": 0,
    "PROHIBITED_PERI_INFUSION_GLUCOCORTICOIDS": 0,
    "MISSING_PRIMARY_ENDPOINT_OR_LTFU": 0,
    "PRE_LANDMARK_DEATH": 0,
    "PRIMARY_GRAFT_NON_FUNCTION": 0,
}

GATE_28A_DISTINCT_LOTS_MIN = 3
GATE_28A_DISTINCT_MCB_MIN = 2
GATE_28A_MAX_SINGLE_LOT_SHARE = Decimal("0.40")
GATE_28A_RHO_LOT_MIN = 0.05
GATE_28A_RHO_BANK_MIN = 0.02
GATE_28A_ICC_SENSITIVITY_SCENARIOS: tuple[tuple[str, float, float], ...] = (
    ("primary_floor", 0.05, 0.02),
    ("moderate_sensitivity", 0.10, 0.05),
    ("high_clustering_sensitivity", 0.15, 0.10),
)
GATE_28A_ALLOWED_ATTESTATION_AUTHORITIES = frozenset({
    "OPENISLET_QA_RELEASE_BOARD_V1",
    "OPENISLET_INDEPENDENT_ASSAY_REGISTRY_V1",
    "OPENISLET_CLINICAL_ADJUDICATION_BOARD_V1",
})


def _compute_gate28a_icc_sensitivity_report(
    k: int,
    n: int,
    m_eff_lot: float,
    m_eff_bank: float,
) -> tuple[dict[str, Any], bool, str]:
    """Compute prespecified 3-scenario same-cohort ICC sensitivity report and 4-state review status."""
    report: dict[str, Any] = {}
    meets_by_scenario: dict[str, bool] = {}
    for scen_name, s_rho_lot, s_rho_mcb in GATE_28A_ICC_SENSITIVITY_SCENARIOS:
        s_deff = 1.0 + s_rho_lot * (m_eff_lot - 1.0) + s_rho_mcb * (m_eff_bank - 1.0)
        s_n_eff = float(n) / s_deff
        s_k_eff = s_n_eff * (float(k) / float(n))
        s_p_unif = 1.0 - beta_cdf(0.90, 1.0 + s_k_eff, 1.0 + (s_n_eff - s_k_eff))
        s_p_anch = 1.0 - beta_cdf(0.90, 8.8 + s_k_eff, 1.2 + (s_n_eff - s_k_eff))
        s_mean_unif = (1.0 + s_k_eff) / (2.0 + s_n_eff)
        s_mean_anch = (8.8 + s_k_eff) / (10.0 + s_n_eff)
        s_meets = (s_p_unif >= 0.90) and (s_p_anch >= 0.85)
        meets_by_scenario[scen_name] = s_meets
        report[scen_name] = {
            "rho_lot": s_rho_lot,
            "rho_mcb": s_rho_mcb,
            "rho_bank": s_rho_mcb,
            "deff_cluster": round(s_deff, 6),
            "n_eff": round(s_n_eff, 6),
            "k_eff": round(s_k_eff, 6),
            "posterior_mean": round(s_mean_unif, 6),
            "posterior_p_ge_090": round(s_p_unif, 6),
            "anchored_posterior_mean": round(s_mean_anch, 6),
            "anchored_posterior_p_ge_090": round(s_p_anch, 6),
            "meets_reanchor_bar": s_meets,
        }

    p_ok = meets_by_scenario["primary_floor"]
    m_ok = meets_by_scenario["moderate_sensitivity"]
    h_ok = meets_by_scenario["high_clustering_sensitivity"]
    boundary_sensitive = bool(p_ok and m_ok and (not h_ok))

    if not p_ok:
        review_status = "HOLD_FAILS_PRIMARY_ICC_FLOOR"
    elif not m_ok:
        review_status = "HOLD_FAILS_MODERATE_ICC_SENSITIVITY"
    elif not h_ok:
        review_status = "BOUNDARY_SENSITIVE_DISCLOSED_CLEARS_PRIMARY_AND_MODERATE"
    else:
        review_status = "ROBUST_ACROSS_ALL_THREE_PRESPECIFIED_ICC_SCENARIOS"

    report["boundary_sensitive_under_high_icc"] = boundary_sensitive
    report["icc_sensitivity_review_status"] = review_status
    report["probability_interpretation"] = (
        "PRESPECIFIED_DECISION_MODEL_QUANTITIES_CONDITIONAL_ON_ASSUMED_ICC_VARIANCE_COMPONENTS_NOT_INDEPENDENT_CALIBRATION"
    )
    report["calibration_scope_note"] = (
        "Cluster-adjusted Beta-Binomial probabilities (Uniform Beta(1,1) and anchored Beta(8.8,1.2) on "
        "fractional (k_eff, n_eff)) are prespecified decision-model quantities conditional on assumed lot/bank "
        "variance-component ICCs (rho_lot, rho_bank) and cohort exchangeability rather than independently "
        "calibrated empirical probabilities; attaching this 3-scenario icc_sensitivity_report documents "
        "sensitivity across prespecified variance-component pairs rather than independent ICC calibration."
    )
    return report, boundary_sensitive, review_status


def _parse_raw_clinical_rescue_declaration(
    rec: dict[str, Any],
    rid_label: str,
) -> dict[str, Any]:
    """Parse ALL clinical rescue declarations from a raw recipient row (executed in Pass 0 before duplicate skipping)."""
    parse_errors: list[str] = []
    ie = _strict_literal_id(rec.get("intercurrent_event"))
    ie_valid = ie in GATE_28A_INTERCURRENT_EVENT_ADJUDICATION

    rescue_declared = (ie == "RESCUE_REPEAT_INFUSION")
    rescue_parse_error = False
    if "rescue_infusion_occurred" in rec and rec["rescue_infusion_occurred"] is not None:
        resc_occ = rec["rescue_infusion_occurred"]
        if type(resc_occ) is not bool:
            parse_errors.append(f"Recipient {rid_label} rescue_infusion_occurred must be strict bool.")
            rescue_parse_error = True
        elif resc_occ is True:
            rescue_declared = True
            if ie_valid and ie != "RESCUE_REPEAT_INFUSION":
                parse_errors.append(
                    f"Recipient {rid_label} sets rescue_infusion_occurred=True contradicting intercurrent_event={ie!r}."
                )
                rescue_parse_error = True
        elif ie == "RESCUE_REPEAT_INFUSION":
            parse_errors.append(
                f"Recipient {rid_label} sets rescue_infusion_occurred=False contradicting intercurrent_event='RESCUE_REPEAT_INFUSION'."
            )
            rescue_parse_error = True

    # Reject ANY undocumented *rescue*lot* alias key BY KEY PRESENCE (even when value is None/null/""/[]
    # or intercurrent_event == "NONE"); only canonical rescue_lot_id and rescue_lot_ids are accepted.
    for rk, rv in sorted(rec.items(), key=lambda kv: str(kv[0])):
        if not isinstance(rk, str):
            continue
        if rk in ("rescue_lot_id", "rescue_lot_ids", "rescue_infusion_occurred"):
            continue
        rk_lo = rk.lower()
        if "rescue" in rk_lo and "lot" in rk_lo:
            parse_errors.append(
                f"UNRECOGNIZED_CLINICAL_RESCUE_LOT_ALIAS: recipient {rid_label} uses unsupported rescue key {rk!r} "
                f"(value={rv!r}; rejected by key presence — only canonical rescue_lot_id and rescue_lot_ids are accepted)."
            )
            rescue_parse_error = True

    rlid_a = rec.get("rescue_lot_id")
    declared_rescue_lot_id: str | None = None
    if rlid_a is not None:
        parsed_a = _strict_literal_id(rlid_a)
        if parsed_a is None:
            parse_errors.append(f"Recipient {rid_label} has invalid literal rescue_lot_id={rlid_a!r}.")
            rescue_parse_error = True
        else:
            declared_rescue_lot_id = parsed_a
            rescue_declared = True

    declared_list_rescue_lot_ids: list[str] | None = None
    if "rescue_lot_ids" in rec and rec["rescue_lot_ids"] is not None:
        raw_rlist = rec["rescue_lot_ids"]
        if not isinstance(raw_rlist, list):
            parse_errors.append(
                f"Recipient {rid_label} rescue_lot_ids must be a list of unique strict literal lot IDs."
            )
            rescue_parse_error = True
        else:
            parsed_rlist: list[str] = []
            bad_elem = False
            for r_elem in raw_rlist:
                lp = _strict_literal_id(r_elem)
                if lp is None:
                    parse_errors.append(
                        f"Recipient {rid_label} rescue_lot_ids contains invalid literal lot ID={r_elem!r}."
                    )
                    bad_elem = True
                    rescue_parse_error = True
                else:
                    parsed_rlist.append(lp)
            if not bad_elem:
                if len(set(parsed_rlist)) != len(parsed_rlist):
                    parse_errors.append(
                        f"CLINICAL_DUPLICATE_RESCUE_LOT_ID: recipient {rid_label} rescue_lot_ids={parsed_rlist!r} "
                        "contains duplicate rescue lot IDs."
                    )
                    rescue_parse_error = True
                sorted_rlist = sorted(parsed_rlist)
                if len(sorted_rlist) == 0:
                    if ie == "RESCUE_REPEAT_INFUSION" or rec.get("rescue_infusion_occurred") is True:
                        parse_errors.append(
                            f"CONFLICTING_CLINICAL_RESCUE_LOT_FIELDS: recipient {rid_label} declares empty "
                            "rescue_lot_ids=[] contradicting rescue infusion."
                        )
                        rescue_parse_error = True
                else:
                    rescue_declared = True
                declared_list_rescue_lot_ids = sorted_rlist

    if declared_rescue_lot_id is not None and declared_list_rescue_lot_ids is not None:
        if declared_list_rescue_lot_ids != [declared_rescue_lot_id]:
            parse_errors.append(
                f"CONFLICTING_CLINICAL_RESCUE_LOT_FIELDS: recipient {rid_label} scalar "
                f"rescue_lot_id={declared_rescue_lot_id!r} contradicts rescue_lot_ids={declared_list_rescue_lot_ids!r}."
            )
            rescue_parse_error = True

    if declared_list_rescue_lot_ids is not None and len(declared_list_rescue_lot_ids) > 0:
        explicit_rescue_ids_provided = True
        declared_rescue_lot_ids_sorted = list(declared_list_rescue_lot_ids)
    elif declared_rescue_lot_id is not None:
        explicit_rescue_ids_provided = True
        declared_rescue_lot_ids_sorted = [declared_rescue_lot_id]
    else:
        explicit_rescue_ids_provided = False
        declared_rescue_lot_ids_sorted = []

    if declared_rescue_lot_ids_sorted and ie_valid and ie != "RESCUE_REPEAT_INFUSION":
        parse_errors.append(
            f"Recipient {rid_label} declares rescue lot(s) {declared_rescue_lot_ids_sorted!r} contradicting intercurrent_event={ie!r}."
        )
        rescue_parse_error = True

    missing_explicit_rescue_lot_id = bool(rescue_declared and not explicit_rescue_ids_provided)
    if missing_explicit_rescue_lot_id:
        parse_errors.append(
            f"CLINICAL_RESCUE_MISSING_EXPLICIT_LOT_ID: recipient {rid_label} declares rescue repeat infusion "
            "without an explicit clinical rescue_lot_id / rescue_lot_ids (exact rescue-lot identity is required)."
        )

    return {
        "intercurrent_event": ie,
        "ie_valid": ie_valid,
        "rescue_declared": rescue_declared,
        "rescue_lot_id": declared_rescue_lot_id,
        "rescue_lot_ids": tuple(declared_rescue_lot_ids_sorted),
        "explicit_rescue_ids_provided": explicit_rescue_ids_provided,
        "missing_explicit_rescue_lot_id": missing_explicit_rescue_lot_id,
        "rescue_parse_error": rescue_parse_error,
        "parse_errors": parse_errors,
    }


CMC_LEDGER_KNOWN_BANK_KEYS = frozenset({
    "mcb_id",
    "master_cell_bank_id",
    "bank_id",
    "wcb_id",
    "working_cell_bank_id",
})


class CMCAncestryValidationError(ValueError):
    """Typed ValueError subclass raised when a CMC ledger fails lot/MCB/WCB ancestry validation."""

    def __init__(self, message: str, *, error_code: str = "CMC_LEDGER_ANCESTRY_CONFLICT") -> None:
        super().__init__(message)
        self.error_code = error_code


def _parse_strict_binary_outcome(val: Any, context: str) -> int:
    """Validate explicit binary clinical responder outcome (strict bool or exact int in {0, 1})."""
    if type(val) is bool:
        return 1 if val else 0
    if type(val) is int and val in (0, 1):
        return val
    raise ValueError(f"{context}: outcome must be strict bool or exact int in {{0, 1}}, got {val!r}")


def _canonical_cmc_lot_sort_key(entry: Any) -> tuple[int, str, str]:
    """Canonical sort key for CMC lot_ledger entries ensuring 100% order-independent validation and diagnostics."""
    cjson = json.dumps(
        _canonicalize_gate28a_value(entry),
        sort_keys=True,
        ensure_ascii=False,
        separators=(",", ":"),
    )
    if isinstance(entry, dict):
        lid = _strict_literal_id(entry.get("lot_id"))
        return (0, lid if lid is not None else "", cjson)
    return (1, "", cjson)


def evaluate_cmc_attempted_lot_readiness(
    lot_ledger: list[dict[str, Any]],
    *,
    h1_blueprint_override: float | Decimal | None = None,
) -> dict[str, Any]:
    """
    Executable CMC Readiness Ledger evaluator (order-independent, fail-closed) enforcing:
      - Standalone release-only operational yield: P_release_CMC = released_lots_n / attempted_lots_n
      - Primary-course-equivalent weighted infusion rate per released lot (unit:
        infused_primary_course_equivalents_per_released_lot; distinct from raw physical-lot utilization —
        e.g., under a 2-lot pooled course both physical lots are infused [100% physical-lot utilization]
        while course-equivalent P_infuse_given_released = 1.0 / 2 = 0.50):
          P_infuse_given_released = infused_primary_course_equivalents / released_lots_n
      - Projected attempted-lot readiness (separate from measured weighted readiness):
          projected_cmc_attempted_lot_readiness = P_release_CMC * P_infuse_given_released * H1_Blueprint
          (uses locked live H1_Blueprint = 0.88 unless h1_blueprint_override is supplied)
      - Measured weighted attempted-lot readiness (separate from projected readiness):
          measured_weighted_cmc_readiness = lot_weighted_primary_successes / attempted_lots_n
      - Matching conditioning (w_infuse) and primary outcome (w_success) weights across every topology:
          * SINGLE_RECIPIENT: w_infuse = 1, w_success = y_r
          * SPLIT_LOT (planned P >= 2, infused I <= P): w_infuse = I / P, w_success = sum(y_r) / P,
            requiring explicit recipient-keyed outcomes (recipient_outcomes dict or recipient_records list;
            ZERO positional inference from recipient_ids order!)
          * MULTI_LOT_COURSE (m >= 2 pooled lots -> 1 recipient): reconciled complete membership against
            declared course_lot_ids / pooled_lot_count, single agreed primary_lot_id, matching w_infuse = 1 / m
            and w_success = y_r / m per constituent lot (zero double-counting!)
          * RESCUE_REPEAT_LOT: MUST reference an existing infused initial primary lot & recipient (rejecting
            orphan rescue-only rows fail-closed), carries primary-course w_infuse = 0 and w_success = 0, and
            forces the rescued recipient's primary single-infusion outcome to 0.
    """
    if not isinstance(lot_ledger, list) or len(lot_ledger) == 0:
        raise ValueError("lot_ledger must be a non-empty list of lot dicts")

    h1_proj_frac = Fraction(88, 100)
    if h1_blueprint_override is not None:
        h1_dec = _strict_decimal_in_range(h1_blueprint_override, min_val=Decimal("0"), max_val=Decimal("1"))
        if h1_dec is None:
            raise ValueError(f"Invalid h1_blueprint_override={h1_blueprint_override!r}; require finite number in [0, 1]")
        h1_proj_frac = Fraction(h1_dec)

    valid_lot_types = {
        "SINGLE_RECIPIENT",
        "SPLIT_LOT",
        "MULTI_LOT_COURSE_PRIMARY",
        "MULTI_LOT_COURSE_CONSTITUENT",
        "RESCUE_REPEAT_LOT",
    }
    valid_dispositions = {"FAILED_RELEASE", "RELEASED_UNINFUSED", "RELEASED_INFUSED"}

    seen_lots: set[str] = set()
    attempted_lots_n = 0
    released_lots_n = 0
    failed_release_lots_n = 0
    uninfused_released_lots_n = 0
    split_lots_n = 0
    rescue_lots_n = 0
    rescue_infused_lots_n = 0

    multi_lot_courses: dict[str, dict[str, Any]] = {}
    normalized_lots: list[dict[str, Any]] = []
    cmc_wcb_to_mcbs: dict[str, set[str]] = {}

    ordered_ledger = sorted(lot_ledger, key=_canonical_cmc_lot_sort_key)
    for idx, entry in enumerate(ordered_ledger):
        if not isinstance(entry, dict):
            raise ValueError(f"Lot entry[{idx}] must be a dict")
        lot_id = _strict_literal_id(entry.get("lot_id"))
        mcb_id = _strict_literal_id(entry.get("mcb_id"))
        lot_type = _strict_literal_id(entry.get("lot_type"))
        disposition = _strict_literal_id(entry.get("disposition"))
        if lot_id is None or mcb_id is None:
            raise CMCAncestryValidationError(
                f"Lot entry[{idx}] missing literal lot_id or mcb_id",
                error_code="CMC_MISSING_LOT_OR_MCB_ID",
            )
        for ek, ev in sorted(entry.items(), key=lambda kv: str(kv[0])):
            if ev is None or not isinstance(ek, str) or ek in CMC_LEDGER_KNOWN_BANK_KEYS:
                continue
            ek_lo = ek.lower()
            if any(tok in ek_lo for tok in ("mcb", "wcb", "cell_bank", "bank_id")):
                raise CMCAncestryValidationError(
                    f"UNRECOGNIZED_BANK_ALIAS in CMC ledger lot {lot_id!r}: unsupported bank key {ek!r}",
                    error_code="UNRECOGNIZED_BANK_ALIAS",
                )
        for mcb_alias in ("master_cell_bank_id", "bank_id"):
            if mcb_alias in entry and entry[mcb_alias] is not None:
                amid = _strict_literal_id(entry[mcb_alias])
                if amid is None or amid != mcb_id:
                    raise CMCAncestryValidationError(
                        f"CONFLICTING_MCB_ALIAS in CMC ledger lot {lot_id!r}: {mcb_alias}={entry[mcb_alias]!r} contradicts mcb_id={mcb_id!r}",
                        error_code="CONFLICTING_MCB_ALIAS",
                    )
        wcb_id: str | None = None
        wcb_raw = entry.get("wcb_id")
        wcb_alias_raw = entry.get("working_cell_bank_id")
        if wcb_raw is not None:
            wcb_id = _strict_literal_id(wcb_raw)
            if wcb_id is None:
                raise CMCAncestryValidationError(
                    f"Lot {lot_id!r} has invalid literal wcb_id={wcb_raw!r}",
                    error_code="CMC_INVALID_WCB_ID",
                )
        if wcb_alias_raw is not None:
            wcb_alias_id = _strict_literal_id(wcb_alias_raw)
            if wcb_alias_id is None:
                raise CMCAncestryValidationError(
                    f"Lot {lot_id!r} has invalid literal working_cell_bank_id={wcb_alias_raw!r}",
                    error_code="CMC_INVALID_WCB_ID",
                )
            if wcb_id is not None and wcb_alias_id != wcb_id:
                raise CMCAncestryValidationError(
                    f"CONFLICTING_WCB_ALIAS in CMC ledger lot {lot_id!r}: working_cell_bank_id={wcb_alias_id!r} contradicts wcb_id={wcb_id!r}",
                    error_code="CONFLICTING_WCB_ALIAS",
                )
            wcb_id = wcb_alias_id
        if wcb_id is not None:
            cmc_wcb_to_mcbs.setdefault(wcb_id, set()).add(mcb_id)
        if lot_id in seen_lots:
            raise CMCAncestryValidationError(
                f"DUPLICATE_LOT_ID_IN_CMC_LEDGER: Duplicate lot_id in CMC ledger: {lot_id!r}",
                error_code="DUPLICATE_LOT_ID_IN_CMC_LEDGER",
            )
        seen_lots.add(lot_id)
        if lot_type not in valid_lot_types:
            raise ValueError(f"Lot {lot_id!r} invalid lot_type={lot_type!r}")
        if disposition not in valid_dispositions:
            raise ValueError(f"Lot {lot_id!r} invalid disposition={disposition!r}")

        planned = entry.get("planned_doses_n")
        infused = entry.get("infused_doses_n")
        if type(planned) is not int or planned < 1:
            raise ValueError(f"Lot {lot_id!r} planned_doses_n must be exact int >= 1")
        if type(infused) is not int or infused < 0 or infused > planned:
            raise ValueError(f"Lot {lot_id!r} infused_doses_n must be exact int in [0, {planned}]")

        if lot_type == "SINGLE_RECIPIENT" and planned != 1:
            raise ValueError(f"SINGLE_RECIPIENT lot {lot_id!r} must have planned_doses_n == 1")
        if lot_type == "SPLIT_LOT" and planned < 2:
            raise ValueError(f"SPLIT_LOT {lot_id!r} must have planned_doses_n >= 2")
        if lot_type in ("MULTI_LOT_COURSE_PRIMARY", "MULTI_LOT_COURSE_CONSTITUENT", "RESCUE_REPEAT_LOT") and planned != 1:
            raise ValueError(f"{lot_type} lot {lot_id!r} must have planned_doses_n == 1")
        if disposition in ("FAILED_RELEASE", "RELEASED_UNINFUSED") and infused != 0:
            raise ValueError(f"Lot {lot_id!r} with disposition {disposition!r} must have infused_doses_n == 0")
        if disposition == "RELEASED_INFUSED" and infused < 1:
            raise ValueError(f"Lot {lot_id!r} with disposition RELEASED_INFUSED must have infused_doses_n >= 1")

        # Parse explicit recipient-keyed outcomes (ZERO positional inference!)
        bind_err_code = (
            "CMC_RESCUE_RECIPIENT_BINDING_CONFLICT"
            if lot_type == "RESCUE_REPEAT_LOT"
            else "CMC_PRIMARY_RECIPIENT_BINDING_CONFLICT"
        )
        raw_out_dict = entry.get("recipient_outcomes")
        raw_out_recs = entry.get("recipient_records")
        parsed_from_dict: dict[str, int] | None = None
        parsed_from_recs: dict[str, int] | None = None

        if raw_out_dict is not None:
            if not isinstance(raw_out_dict, dict):
                raise CMCAncestryValidationError(
                    f"{bind_err_code}: Lot {lot_id!r} recipient_outcomes must be a dict mapping recipient_id -> outcome",
                    error_code=bind_err_code,
                )
            parsed_from_dict = {}
            for rk, rv in sorted(raw_out_dict.items(), key=lambda kv: repr(kv[0])):
                lr = _strict_literal_id(rk)
                if lr is None:
                    raise CMCAncestryValidationError(
                        f"{bind_err_code}: Lot {lot_id!r} recipient_outcomes contains invalid recipient_id={rk!r}",
                        error_code=bind_err_code,
                    )
                parsed_from_dict[lr] = _parse_strict_binary_outcome(rv, f"Lot {lot_id!r} recipient_outcomes[{lr!r}]")

        if raw_out_recs is not None:
            if not isinstance(raw_out_recs, list):
                raise CMCAncestryValidationError(
                    f"{bind_err_code}: Lot {lot_id!r} recipient_records must be a list of recipient outcome dicts",
                    error_code=bind_err_code,
                )
            parsed_from_recs = {}
            for r_i, r_obj in enumerate(raw_out_recs):
                if not isinstance(r_obj, dict):
                    raise CMCAncestryValidationError(
                        f"{bind_err_code}: Lot {lot_id!r} recipient_records[{r_i}] must be a dict",
                        error_code=bind_err_code,
                    )
                lr = _strict_literal_id(r_obj.get("recipient_id"))
                if lr is None:
                    raise CMCAncestryValidationError(
                        f"{bind_err_code}: Lot {lot_id!r} recipient_records[{r_i}] missing literal recipient_id",
                        error_code=bind_err_code,
                    )
                if lr in parsed_from_recs:
                    raise CMCAncestryValidationError(
                        f"{bind_err_code}: Lot {lot_id!r} recipient_records contains duplicate recipient_id={lr!r}",
                        error_code=bind_err_code,
                    )
                has_c2b = "c2b_responder" in r_obj
                has_out = "outcome" in r_obj
                if not has_c2b and not has_out:
                    raise ValueError(f"Lot {lot_id!r} recipient_records[{r_i}] requires c2b_responder or outcome")
                v_c2b = _parse_strict_binary_outcome(r_obj["c2b_responder"], f"Lot {lot_id!r} recipient_records[{lr!r}].c2b_responder") if has_c2b else None
                v_out = _parse_strict_binary_outcome(r_obj["outcome"], f"Lot {lot_id!r} recipient_records[{lr!r}].outcome") if has_out else None
                if v_c2b is not None and v_out is not None and v_c2b != v_out:
                    raise ValueError(f"Lot {lot_id!r} recipient_records[{lr!r}] has conflicting c2b_responder and outcome")
                parsed_from_recs[lr] = v_c2b if v_c2b is not None else int(v_out)  # type: ignore[arg-type]

        if parsed_from_dict is not None and parsed_from_recs is not None:
            if set(parsed_from_dict.keys()) != set(parsed_from_recs.keys()):
                raise CMCAncestryValidationError(
                    f"{bind_err_code}: Lot {lot_id!r} recipient_outcomes contradicts recipient_records "
                    f"(recipient_outcomes keys={sorted(parsed_from_dict.keys())!r} != "
                    f"recipient_records recipient_ids={sorted(parsed_from_recs.keys())!r})",
                    error_code=bind_err_code,
                )
            if parsed_from_dict != parsed_from_recs:
                raise ValueError(f"Lot {lot_id!r} recipient_outcomes contradicts recipient_records")

        if disposition == "RELEASED_INFUSED":
            if parsed_from_dict is None and parsed_from_recs is None:
                raise CMCAncestryValidationError(
                    f"{bind_err_code}: Lot {lot_id!r} ({lot_type}) with disposition RELEASED_INFUSED requires explicit "
                    "recipient_outcomes dict or recipient_records list; positional inference from recipient_ids is prohibited",
                    error_code=bind_err_code,
                )
            recipient_outcomes = parsed_from_dict if parsed_from_dict is not None else dict(parsed_from_recs or {})
            if len(recipient_outcomes) != infused:
                raise ValueError(
                    f"Lot {lot_id!r} explicit recipient outcome count ({len(recipient_outcomes)}) != infused_doses_n ({infused})"
                )
        else:
            if parsed_from_dict:
                raise CMCAncestryValidationError(
                    f"{bind_err_code}: Uninfused/failed lot {lot_id!r} must have empty recipient_outcomes",
                    error_code=bind_err_code,
                )
            if parsed_from_recs:
                raise CMCAncestryValidationError(
                    f"{bind_err_code}: Uninfused/failed lot {lot_id!r} must have empty recipient_records",
                    error_code=bind_err_code,
                )
            recipient_outcomes = {}

        if "recipient_ids" in entry and entry["recipient_ids"] is not None:
            rids_raw = entry["recipient_ids"]
            if not isinstance(rids_raw, list):
                raise CMCAncestryValidationError(
                    f"{bind_err_code}: Lot {lot_id!r} recipient_ids must be a list of length infused_doses_n={infused}",
                    error_code=bind_err_code,
                )
            rids: list[str] = []
            for r in rids_raw:
                lr = _strict_literal_id(r)
                if lr is None:
                    raise CMCAncestryValidationError(
                        f"{bind_err_code}: Lot {lot_id!r} contains invalid recipient_id={r!r}",
                        error_code=bind_err_code,
                    )
                rids.append(lr)
            if len(set(rids)) != len(rids):
                raise CMCAncestryValidationError(
                    f"{bind_err_code}: Lot {lot_id!r} contains duplicate recipient_ids",
                    error_code=bind_err_code,
                )
            if set(rids) != set(recipient_outcomes.keys()):
                raise CMCAncestryValidationError(
                    f"{bind_err_code}: Lot {lot_id!r} recipient_ids set does not match explicit recipient_outcomes keys "
                    f"(recipient_ids={sorted(set(rids))!r} != explicit={sorted(recipient_outcomes.keys())!r})",
                    error_code=bind_err_code,
                )
            if len(rids) != infused:
                raise ValueError(f"Lot {lot_id!r} recipient_ids must be a list of length infused_doses_n={infused}")
        rids_sorted = sorted(recipient_outcomes.keys())

        responders_sum = sum(recipient_outcomes.values())
        if "c2b_responder_doses_n" in entry and entry["c2b_responder_doses_n"] is not None:
            responders_raw = entry["c2b_responder_doses_n"]
            if type(responders_raw) is not int or responders_raw < 0 or responders_raw > infused:
                raise ValueError(f"Lot {lot_id!r} c2b_responder_doses_n must be exact int in [0, {infused}]")
            if responders_raw != responders_sum:
                raise ValueError(
                    f"Lot {lot_id!r} c2b_responder_doses_n ({responders_raw}) contradicts explicit recipient_outcomes sum ({responders_sum})"
                )

        attempted_lots_n += 1
        if disposition == "FAILED_RELEASE":
            failed_release_lots_n += 1
        elif disposition == "RELEASED_UNINFUSED":
            released_lots_n += 1
            uninfused_released_lots_n += 1
        else:
            released_lots_n += 1
            if lot_type == "SPLIT_LOT":
                split_lots_n += 1

        rec_norm: dict[str, Any] = {
            "lot_id": lot_id,
            "mcb_id": mcb_id,
            "wcb_id": wcb_id,
            "lot_type": lot_type,
            "disposition": disposition,
            "planned_doses_n": planned,
            "infused_doses_n": infused,
            "c2b_responder_doses_n": responders_sum,
            "recipient_ids": rids_sorted,
            "recipient_outcomes": recipient_outcomes,
        }

        if lot_type in ("MULTI_LOT_COURSE_PRIMARY", "MULTI_LOT_COURSE_CONSTITUENT"):
            cid_a = entry.get("pooled_course_id")
            cid_b = entry.get("course_id")
            if cid_a is not None and _strict_literal_id(cid_a) is None:
                raise ValueError(f"Multi-lot course entry {lot_id!r} has invalid pooled_course_id={cid_a!r}")
            if cid_b is not None and _strict_literal_id(cid_b) is None:
                raise ValueError(f"Multi-lot course entry {lot_id!r} has invalid course_id={cid_b!r}")
            if cid_a is not None and cid_b is not None and cid_a != cid_b:
                raise ValueError(f"Multi-lot course entry {lot_id!r} has conflicting pooled_course_id and course_id")
            course_id = _strict_literal_id(cid_a if cid_a is not None else cid_b)
            primary_lot_id = _strict_literal_id(entry.get("primary_lot_id"))

            def _validate_unique_course_lot_list(raw_list: Any, field_lbl: str) -> list[str]:
                if not isinstance(raw_list, list) or len(raw_list) < 2:
                    raise ValueError(
                        f"Multi-lot course entry {lot_id!r} {field_lbl} must be a list of >=2 unique strict literal lot IDs"
                    )
                cleaned: list[str] = []
                for x in raw_list:
                    lx = _strict_literal_id(x)
                    if lx is None:
                        raise ValueError(f"Multi-lot course entry {lot_id!r} {field_lbl} contains invalid lot id={x!r}")
                    cleaned.append(lx)
                if len(set(cleaned)) != len(cleaned):
                    raise ValueError(f"Multi-lot course entry {lot_id!r} {field_lbl} contains duplicate lot IDs")
                return cleaned

            clots_a = entry.get("pooled_course_lot_ids")
            clots_b = entry.get("course_lot_ids")
            validated_a = _validate_unique_course_lot_list(clots_a, "pooled_course_lot_ids") if clots_a is not None else None
            validated_b = _validate_unique_course_lot_list(clots_b, "course_lot_ids") if clots_b is not None else None
            if validated_a is not None and validated_b is not None and set(validated_a) != set(validated_b):
                raise ValueError(
                    f"Multi-lot course entry {lot_id!r} has conflicting pooled_course_lot_ids and course_lot_ids sets"
                )
            course_lots_opt = validated_a if validated_a is not None else validated_b

            if course_id is None or primary_lot_id is None or course_lots_opt is None:
                raise ValueError(
                    f"Multi-lot course entry {lot_id!r} requires literal course_id/pooled_course_id, "
                    "primary_lot_id, and >=2 unique course_lot_ids/pooled_course_lot_ids"
                )
            course_lots = course_lots_opt
            if lot_id not in course_lots or primary_lot_id not in course_lots:
                raise ValueError(f"Multi-lot course entry {lot_id!r} lot_id and primary_lot_id must belong to course_lot_ids")
            if "pooled_lot_count" in entry and entry["pooled_lot_count"] is not None:
                plc = entry["pooled_lot_count"]
                if type(plc) is not int or plc != len(course_lots):
                    raise ValueError(
                        f"Multi-lot course entry {lot_id!r} pooled_lot_count={plc!r} != len(course_lot_ids)={len(course_lots)}"
                    )
            if lot_type == "MULTI_LOT_COURSE_PRIMARY" and lot_id != primary_lot_id:
                raise ValueError(f"MULTI_LOT_COURSE_PRIMARY lot {lot_id!r} must equal primary_lot_id={primary_lot_id!r}")
            if lot_type == "MULTI_LOT_COURSE_CONSTITUENT" and lot_id == primary_lot_id:
                raise ValueError(f"MULTI_LOT_COURSE_CONSTITUENT lot {lot_id!r} cannot equal primary_lot_id={primary_lot_id!r}")
            if disposition == "RELEASED_INFUSED" and len(rids_sorted) != 1:
                raise ValueError(f"Multi-lot course entry {lot_id!r} must bind to exactly 1 unique recipient")

            rec_norm["course_id"] = course_id
            rec_norm["primary_lot_id"] = primary_lot_id
            rec_norm["course_lot_ids"] = sorted(course_lots)
            declared_set = frozenset(course_lots)
            if course_id not in multi_lot_courses:
                multi_lot_courses[course_id] = {
                    "primary_lot_id": primary_lot_id,
                    "declared_lot_ids": declared_set,
                    "declared_lot_count": len(course_lots),
                    "seen_lots": set(),
                    "primary_rows_seen": set(),
                    "dispositions_seen": set(),
                    "recipient_id": None,
                    "outcome": None,
                }
            c_info = multi_lot_courses[course_id]
            if c_info["primary_lot_id"] != primary_lot_id:
                raise ValueError(
                    f"Inconsistent pooled course {course_id!r}: conflicting primary_lot_id "
                    f"{c_info['primary_lot_id']!r} vs {primary_lot_id!r}"
                )
            if c_info["declared_lot_ids"] != declared_set:
                raise ValueError(
                    f"Inconsistent pooled course {course_id!r}: conflicting declared course_lot_ids across rows"
                )
            c_info["seen_lots"].add(lot_id)
            c_info["dispositions_seen"].add(disposition)
            if lot_type == "MULTI_LOT_COURSE_PRIMARY":
                c_info["primary_rows_seen"].add(lot_id)
            if disposition == "RELEASED_INFUSED":
                rid = rids_sorted[0]
                outc = recipient_outcomes[rid]
                if c_info["recipient_id"] is not None and c_info["recipient_id"] != rid:
                    raise ValueError(f"Multi-lot course {course_id!r} maps to multiple distinct recipients")
                c_info["recipient_id"] = rid
                if c_info["outcome"] is not None and c_info["outcome"] != outc:
                    raise ValueError(f"Multi-lot course {course_id!r} has conflicting responder outcomes across constituent lots")
                c_info["outcome"] = outc

        if lot_type == "RESCUE_REPEAT_LOT":
            rescue_lots_n += 1
            resc_rid = _strict_literal_id(entry.get("rescued_recipient_id"))
            resc_prim = _strict_literal_id(entry.get("rescued_primary_lot_id"))
            if resc_rid is None or resc_prim is None:
                raise CMCAncestryValidationError(
                    f"RESCUE_REPEAT_LOT {lot_id!r} requires literal rescued_recipient_id and rescued_primary_lot_id",
                    error_code="CMC_RESCUE_MISSING_LINKAGE_FIELDS",
                )
            rec_norm["rescued_recipient_id"] = resc_rid
            rec_norm["rescued_primary_lot_id"] = resc_prim
            if disposition == "RELEASED_INFUSED":
                if rids_sorted != [resc_rid]:
                    raise CMCAncestryValidationError(
                        f"RESCUE_REPEAT_LOT {lot_id!r} recipient_outcomes key must equal rescued_recipient_id={resc_rid!r}",
                        error_code="CMC_RESCUE_RECIPIENT_BINDING_CONFLICT",
                    )
                rescue_infused_lots_n += 1

        normalized_lots.append(rec_norm)

    for wid_cmc, mcbs_cmc in sorted(cmc_wcb_to_mcbs.items()):
        if len(mcbs_cmc) > 1:
            raise CMCAncestryValidationError(
                f"NON_UNIQUE_WCB_PARENTAGE in CMC ledger: wcb_id={wid_cmc!r} maps to multiple distinct MCBs {sorted(mcbs_cmc)}",
                error_code="NON_UNIQUE_WCB_PARENTAGE",
            )

    # Reconcile every pooled multi-lot course completely (fail-closed on missing constituent/primary lots or partial infusion!)
    for course_id, c_info in sorted(multi_lot_courses.items()):
        if c_info["seen_lots"] != c_info["declared_lot_ids"]:
            missing_lots = sorted(c_info["declared_lot_ids"] - c_info["seen_lots"])
            raise ValueError(
                f"Incomplete pooled course {course_id!r}: declared {c_info['declared_lot_count']} lots "
                f"({sorted(c_info['declared_lot_ids'])}), missing lot rows {missing_lots}"
            )
        if c_info["primary_rows_seen"] != {c_info["primary_lot_id"]}:
            raise ValueError(
                f"Inconsistent pooled course {course_id!r}: expected exactly one MULTI_LOT_COURSE_PRIMARY row "
                f"for primary_lot_id={c_info['primary_lot_id']!r}, saw {sorted(c_info['primary_rows_seen'])}"
            )
        if "RELEASED_INFUSED" in c_info["dispositions_seen"] and c_info["dispositions_seen"] != {"RELEASED_INFUSED"}:
            raise ValueError(
                f"Inconsistent pooled course {course_id!r}: mixed dispositions {sorted(c_info['dispositions_seen'])} "
                "across constituent lots of an infused pooled course"
            )

    # Pass 1: Populate 1:1 unique clinical recipients and primary-lot recipient ownership (order-independent!)
    # Bind ownership to a TYPED course identity tuple:
    #   ("SINGLE_OR_SPLIT_LOT", lot_id)  vs  ("POOLED_COURSE", course_id)
    # so a pooled course_id sharing the same string value as a single-lot lot_id can NEVER collide or overwrite,
    # and reject ANY recipient appearing in more than one initial (non-rescue) course BEFORE writing any outcome!
    clinical_recipient_outcomes: dict[str, int] = {}
    seen_initial_course_by_recipient: dict[str, tuple[str, str]] = {}
    primary_lot_recipients: dict[str, set[str]] = {}

    for item in sorted(normalized_lots, key=lambda x: x["lot_id"]):
        if item["disposition"] != "RELEASED_INFUSED" or item["lot_type"] == "RESCUE_REPEAT_LOT":
            continue
        lt = item["lot_type"]
        if lt in ("MULTI_LOT_COURSE_PRIMARY", "MULTI_LOT_COURSE_CONSTITUENT"):
            rid = item["recipient_ids"][0]
            course_identity = ("POOLED_COURSE", item["course_id"])
            if rid in seen_initial_course_by_recipient:
                if seen_initial_course_by_recipient[rid] != course_identity:
                    raise ValueError(
                        f"Recipient {rid!r} appears in multiple distinct initial courses "
                        f"({seen_initial_course_by_recipient[rid]!r} vs {course_identity!r}) without rescue flag"
                    )
            else:
                seen_initial_course_by_recipient[rid] = course_identity
                clinical_recipient_outcomes[rid] = item["recipient_outcomes"][rid]
            if lt == "MULTI_LOT_COURSE_PRIMARY":
                primary_lot_recipients[item["lot_id"]] = {rid}
        else:
            course_identity = ("SINGLE_OR_SPLIT_LOT", item["lot_id"])
            for rid, outc in sorted(item["recipient_outcomes"].items()):
                if rid in seen_initial_course_by_recipient:
                    raise ValueError(
                        f"Recipient {rid!r} appears in multiple distinct initial courses "
                        f"({seen_initial_course_by_recipient[rid]!r} vs {course_identity!r}) without rescue flag"
                    )
                seen_initial_course_by_recipient[rid] = course_identity
                clinical_recipient_outcomes[rid] = outc
            primary_lot_recipients[item["lot_id"]] = set(item["recipient_outcomes"].keys())

    # Pass 2: Validate EVERY RESCUE_REPEAT_LOT against an existing initial infused primary lot & recipient!
    # Never fabricate a recipient from an orphan rescue-only row.
    rescued_recipients: set[str] = set()
    for item in sorted(normalized_lots, key=lambda x: x["lot_id"]):
        if item["lot_type"] != "RESCUE_REPEAT_LOT":
            continue
        resc_rid = item["rescued_recipient_id"]
        resc_prim = item["rescued_primary_lot_id"]
        if resc_prim not in primary_lot_recipients:
            raise CMCAncestryValidationError(
                f"Orphan RESCUE_REPEAT_LOT {item['lot_id']!r}: rescued_primary_lot_id={resc_prim!r} "
                "does not match any infused initial primary lot/course in lot_ledger",
                error_code="CMC_ORPHAN_RESCUE_LOT",
            )
        if resc_rid not in clinical_recipient_outcomes or resc_rid not in primary_lot_recipients[resc_prim]:
            raise CMCAncestryValidationError(
                f"Orphan or mismatched RESCUE_REPEAT_LOT {item['lot_id']!r}: rescued_recipient_id={resc_rid!r} "
                f"was not infused in initial primary lot/course {resc_prim!r}",
                error_code="CMC_ORPHAN_RESCUE_LOT",
            )
        if item["disposition"] == "RELEASED_INFUSED":
            rescued_recipients.add(resc_rid)

    for resc_rid in rescued_recipients:
        clinical_recipient_outcomes[resc_rid] = 0

    # Pass 3: Matching primary-course conditioning weights (w_infuse) AND outcome weights (w_success) in exact Fraction!
    infused_course_equiv_frac = Fraction(0)
    lot_weighted_primary_successes_frac = Fraction(0)
    for item in normalized_lots:
        if item["disposition"] != "RELEASED_INFUSED":
            continue
        lt = item["lot_type"]
        if lt == "RESCUE_REPEAT_LOT":
            # Rescue repeat lots consume manufacturing capacity (counted in attempted_lots_n, released_lots_n, rescue_lots_n)
            # without creating a new primary clinical course (w_infuse = 0, w_success = 0).
            continue
        if lt == "SINGLE_RECIPIENT":
            rid = item["recipient_ids"][0]
            infused_course_equiv_frac += Fraction(1, 1)
            lot_weighted_primary_successes_frac += Fraction(clinical_recipient_outcomes[rid], 1)
        elif lt == "SPLIT_LOT":
            infused_course_equiv_frac += Fraction(item["infused_doses_n"], item["planned_doses_n"])
            non_rescued_resp = sum(clinical_recipient_outcomes[rid] for rid in item["recipient_outcomes"])
            lot_weighted_primary_successes_frac += Fraction(non_rescued_resp, item["planned_doses_n"])
        elif lt in ("MULTI_LOT_COURSE_PRIMARY", "MULTI_LOT_COURSE_CONSTITUENT"):
            m_lots = len(item["course_lot_ids"])
            rid = item["recipient_ids"][0]
            infused_course_equiv_frac += Fraction(1, m_lots)
            lot_weighted_primary_successes_frac += Fraction(clinical_recipient_outcomes[rid], m_lots)

    unique_clinical_recipients_n = len(clinical_recipient_outcomes)
    clinical_primary_responders_n = sum(clinical_recipient_outcomes.values())
    p_release_frac = Fraction(released_lots_n, attempted_lots_n)
    p_infuse_given_released_frac = (
        infused_course_equiv_frac / released_lots_n if released_lots_n > 0 else Fraction(0)
    )
    empirical_h1_frac = (
        Fraction(clinical_primary_responders_n, unique_clinical_recipients_n)
        if unique_clinical_recipients_n > 0
        else Fraction(0)
    )
    projected_readiness_frac = p_release_frac * p_infuse_given_released_frac * h1_proj_frac
    measured_weighted_readiness_frac = lot_weighted_primary_successes_frac / attempted_lots_n
    empirical_product_readiness_frac = p_release_frac * p_infuse_given_released_frac * empirical_h1_frac
    omitted_infusion_error_frac = p_release_frac * h1_proj_frac

    return {
        "attempted_lots_n": attempted_lots_n,
        "released_lots_n": released_lots_n,
        "failed_release_lots_n": failed_release_lots_n,
        "uninfused_released_lots_n": uninfused_released_lots_n,
        "split_lots_n": split_lots_n,
        "rescue_lots_n": rescue_lots_n,
        "rescue_infused_lots_n": rescue_infused_lots_n,
        "multi_lot_courses_n": len(multi_lot_courses),
        "infused_lot_equivalents": round(float(infused_course_equiv_frac), 6),
        "infused_primary_course_equivalents": round(float(infused_course_equiv_frac), 6),
        "release_only_cmc_yield": round(float(p_release_frac), 6),
        "p_release_cmc": round(float(p_release_frac), 6),
        "p_infuse_given_released": round(float(p_infuse_given_released_frac), 6),
        "p_infuse_given_released_unit": "infused_primary_course_equivalents_per_released_lot",
        "unique_clinical_recipients_n": unique_clinical_recipients_n,
        "clinical_primary_responders_n": clinical_primary_responders_n,
        "empirical_h1_post_release": round(float(empirical_h1_frac), 6),
        "h1_blueprint_applied": round(float(h1_proj_frac), 6),
        "projected_cmc_attempted_lot_readiness": round(float(projected_readiness_frac), 6),
        "projected_cmc_attempted_lot_readiness_pct": round(100.0 * float(projected_readiness_frac), 4),
        "measured_weighted_cmc_readiness": round(float(measured_weighted_readiness_frac), 6),
        "measured_weighted_cmc_readiness_pct": round(100.0 * float(measured_weighted_readiness_frac), 4),
        "authoritative_attempted_lot_metric": "measured_weighted_cmc_readiness",
        "empirical_product_readiness": round(float(empirical_product_readiness_frac), 6),
        "empirical_product_readiness_scope": "DIAGNOSTIC_UNWEIGHTED_RECIPIENT_RATE_PRODUCT_ONLY",
        "diagnostic_unweighted_recipient_rate_product_readiness": round(float(empirical_product_readiness_frac), 6),
        "h1_cmc_attempted_lot_readiness": round(float(projected_readiness_frac), 6),
        "h1_cmc_attempted_lot_readiness_pct": round(100.0 * float(projected_readiness_frac), 4),
        "diagnostic_omitted_infusion_product": round(float(omitted_infusion_error_frac), 6),
        "lot_weighted_primary_successes": round(float(lot_weighted_primary_successes_frac), 6),
        "equation_projected": "projected_cmc_attempted_lot_readiness = P_release_CMC * P_infuse_given_released * H1_Blueprint",
        "equation_measured": "measured_weighted_cmc_readiness = lot_weighted_primary_successes / attempted_lots_n",
        "equation_empirical_product_diagnostic": (
            "empirical_product_readiness = P_release_CMC * P_infuse_given_released * empirical_h1_post_release "
            "(diagnostic unweighted-recipient-rate product only; authoritative audited metric is measured_weighted_cmc_readiness)"
        ),
        "equation": "H1_CMC_ATTEMPTED_LOT_READINESS = P_release_CMC * P_infuse_given_released * H1_Blueprint",
    }


def _extract_cmc_reconciliation_view(
    lot_ledger: list[dict[str, Any]],
) -> tuple[dict[str, dict[str, Any]], dict[str, dict[str, Any]], dict[str, dict[str, Any]]]:
    """
    Extract exact infused clinical recipient bindings AND complete per-lot ancestry rows across
    EVERY disposition (primary, split, pooled, rescue, released-uninfused, manufacturing-failed)
    from a CMC lot_ledger that has ALREADY passed evaluate_cmc_attempted_lot_readiness(lot_ledger).
    Returns:
      - single_or_split_recipients: rid -> {lot_id, mcb_id, wcb_id, lot_type, rescued, rescue_lot_ids, rescued_primary_lot_ids, raw_primary_outcome, primary_outcome}
      - pooled_course_recipients: rid -> {course_id, primary_lot_id, course_lot_ids, rescued, rescue_lot_ids, rescued_primary_lot_ids, raw_primary_outcome, primary_outcome}
      - all_lot_rows: lot_id -> {lot_id, mcb_id, wcb_id, lot_type, disposition, rescued_recipient_id, rescued_primary_lot_id}
    """
    single_or_split: dict[str, dict[str, Any]] = {}
    pooled: dict[str, dict[str, Any]] = {}
    all_lot_rows: dict[str, dict[str, Any]] = {}
    rescued_rids: set[str] = set()
    rescued_lots_by_rid: dict[str, list[str]] = {}
    rescued_primary_lots_by_rid: dict[str, list[str]] = {}

    for entry in lot_ledger:
        lid = str(entry["lot_id"])
        mid = str(entry["mcb_id"])
        wid_raw = entry.get("wcb_id") if entry.get("wcb_id") is not None else entry.get("working_cell_bank_id")
        wid = str(wid_raw) if isinstance(wid_raw, str) and wid_raw else None
        lt = str(entry.get("lot_type"))
        disp = str(entry.get("disposition"))
        all_lot_rows[lid] = {
            "lot_id": lid,
            "mcb_id": mid,
            "wcb_id": wid,
            "lot_type": lt,
            "disposition": disp,
            "rescued_recipient_id": str(entry["rescued_recipient_id"]) if isinstance(entry.get("rescued_recipient_id"), str) else None,
            "rescued_primary_lot_id": str(entry["rescued_primary_lot_id"]) if isinstance(entry.get("rescued_primary_lot_id"), str) else None,
        }
        if disp != "RELEASED_INFUSED":
            continue
        if lt == "RESCUE_REPEAT_LOT":
            resc_rid = entry.get("rescued_recipient_id")
            if isinstance(resc_rid, str):
                rescued_rids.add(resc_rid)
                rescued_lots_by_rid.setdefault(resc_rid, []).append(lid)
                resc_prim = entry.get("rescued_primary_lot_id")
                if isinstance(resc_prim, str):
                    rescued_primary_lots_by_rid.setdefault(resc_rid, []).append(resc_prim)
            continue

        raw_out_dict = entry.get("recipient_outcomes")
        raw_out_recs = entry.get("recipient_records")
        outcomes: dict[str, int] = {}
        if isinstance(raw_out_dict, dict):
            for rk, rv in raw_out_dict.items():
                outcomes[str(rk)] = _parse_strict_binary_outcome(rv, "cmc_reconcile")
        elif isinstance(raw_out_recs, list):
            for r_obj in raw_out_recs:
                lr = str(r_obj["recipient_id"])
                val = r_obj["c2b_responder"] if "c2b_responder" in r_obj else r_obj["outcome"]
                outcomes[lr] = _parse_strict_binary_outcome(val, "cmc_reconcile")

        if lt in ("SINGLE_RECIPIENT", "SPLIT_LOT"):
            for rid, outc in outcomes.items():
                single_or_split[rid] = {
                    "lot_id": lid,
                    "mcb_id": mid,
                    "wcb_id": wid,
                    "lot_type": lt,
                    "rescued": False,
                    "rescue_lot_ids": [],
                    "rescued_primary_lot_ids": [],
                    "raw_primary_outcome": outc,
                    "primary_outcome": outc,
                }
        elif lt == "MULTI_LOT_COURSE_PRIMARY":
            cid = str(entry.get("pooled_course_id") or entry.get("course_id"))
            clots = entry.get("pooled_course_lot_ids") or entry.get("course_lot_ids") or []
            for rid, outc in outcomes.items():
                pooled[rid] = {
                    "course_id": cid,
                    "primary_lot_id": lid,
                    "course_lot_ids": sorted(str(x) for x in clots),
                    "rescued": False,
                    "rescue_lot_ids": [],
                    "rescued_primary_lot_ids": [],
                    "raw_primary_outcome": outc,
                    "primary_outcome": outc,
                }

    for rrid in sorted(rescued_rids):
        rlots = sorted(rescued_lots_by_rid.get(rrid, []))
        rprims = sorted(rescued_primary_lots_by_rid.get(rrid, []))
        if rrid in single_or_split:
            single_or_split[rrid]["rescued"] = True
            single_or_split[rrid]["rescue_lot_ids"] = rlots
            single_or_split[rrid]["rescued_primary_lot_ids"] = rprims
            single_or_split[rrid]["primary_outcome"] = 0
        if rrid in pooled:
            pooled[rrid]["rescued"] = True
            pooled[rrid]["rescue_lot_ids"] = rlots
            pooled[rrid]["rescued_primary_lot_ids"] = rprims
            pooled[rrid]["primary_outcome"] = 0

    return single_or_split, pooled, all_lot_rows


def _audit_raw_cmc_ledger_ancestry(
    lot_ledger_raw: Any,
    *,
    ref_mcb_map: dict[str, str],
    ref_wcb_map: dict[str, str],
    observed_wcb_to_mcbs: dict[str, set[str]],
    clinical_recipient_meta: dict[str, dict[str, Any]] | None = None,
    raw_ancestry_claims_by_rid: dict[str, list[tuple[str | None, tuple[str, ...], tuple[str, ...], bool]]] | None = None,
) -> tuple[list[str], bool]:
    """
    Single-source-of-truth raw PARALLEL_CMC_READINESS_LEDGER ancestry auditor executed across EVERY
    disposition (primary, split, pooled, rescue, released-uninfused, manufacturing-failed) BOTH when
    evaluate_cmc_attempted_lot_readiness succeeds AND when it raises any exception (preventing
    initial-validation or compound non-ancestry errors from bypassing fail-closed ancestry invalidation).
    Returns (ancestry_errors, has_ancestry_conflict).
    """
    if not isinstance(lot_ledger_raw, list) or len(lot_ledger_raw) == 0:
        return (
            [
                "CMC_LEDGER_ANCESTRY_UNVERIFIABLE: PARALLEL_CMC_READINESS_LEDGER lot_ledger must be a non-empty list of lot dicts."
            ],
            True,
        )

    errs: list[str] = []
    conflict = False
    tree_wcb_to_mcbs: dict[str, set[str]] = {
        wid_o: set(mcbs_o) for wid_o, mcbs_o in observed_wcb_to_mcbs.items()
    }
    for lid_r, wid_r in sorted(ref_wcb_map.items()):
        if lid_r in ref_mcb_map:
            tree_wcb_to_mcbs.setdefault(wid_r, set()).add(ref_mcb_map[lid_r])

    seen_lots_raw: dict[str, tuple[str, str | None]] = {}
    raw_primary_lot_rids: dict[str, set[str]] = {}
    raw_rescue_rows: list[tuple[str, str | None, str | None, str | None]] = []
    rescue_wcbs_seen: set[str] = set()
    raw_lot_rows_by_lid: dict[
        str,
        list[
            tuple[
                Any,
                str | None,
                Any,
                str | None,
                Any,
                set[str] | None,
                set[str] | None,
                set[str] | None,
                bool,
                bool,
                bool,
            ]
        ],
    ] = {}

    ordered_ledger_raw = sorted(lot_ledger_raw, key=_canonical_cmc_lot_sort_key)
    for idx, entry in enumerate(ordered_ledger_raw):
        if not isinstance(entry, dict):
            errs.append(f"CMC_LEDGER_ANCESTRY_UNVERIFIABLE: raw PARALLEL_CMC_READINESS_LEDGER lot_ledger[{idx}] is not a dict.")
            conflict = True
            continue
        lid = _strict_literal_id(entry.get("lot_id"))
        mid = _strict_literal_id(entry.get("mcb_id"))
        disp_raw = entry.get("disposition")
        disp = _strict_literal_id(disp_raw)
        lt_raw = entry.get("lot_type")
        lt = _strict_literal_id(lt_raw)
        infused_raw = entry.get("infused_doses_n")

        # Extract EVERY supplied raw recipient-binding field SEPARATELY (ZERO silent union across fields!)
        raw_out_dict = entry.get("recipient_outcomes")
        raw_out_recs = entry.get("recipient_records")
        raw_rids = entry.get("recipient_ids")

        od_present = raw_out_dict is not None
        od_valid_container = isinstance(raw_out_dict, dict)
        od_valid_ids: list[str] = []
        od_bad_keys: list[Any] = []
        if od_valid_container:
            for rk in sorted(raw_out_dict.keys(), key=repr):
                lr = _strict_literal_id(rk)
                if lr is None:
                    od_bad_keys.append(rk)
                else:
                    od_valid_ids.append(lr)
        od_set: set[str] | None = set(od_valid_ids) if (od_present and od_valid_container and not od_bad_keys) else None

        rr_present = raw_out_recs is not None
        rr_valid_container = isinstance(raw_out_recs, list)
        rr_valid_ids: list[str] = []
        rr_malformed = False
        if rr_valid_container:
            for r_obj in raw_out_recs:
                if not isinstance(r_obj, dict):
                    rr_malformed = True
                    continue
                lr = _strict_literal_id(r_obj.get("recipient_id"))
                if lr is None:
                    rr_malformed = True
                else:
                    rr_valid_ids.append(lr)
        rr_has_dups = len(set(rr_valid_ids)) != len(rr_valid_ids)
        rr_set: set[str] | None = (
            set(rr_valid_ids) if (rr_present and rr_valid_container and not rr_malformed and not rr_has_dups) else None
        )

        ri_present = raw_rids is not None
        ri_valid_container = isinstance(raw_rids, list)
        ri_valid_ids: list[str] = []
        ri_bad_ids: list[Any] = []
        if ri_valid_container:
            for rk in raw_rids:
                lr = _strict_literal_id(rk)
                if lr is None:
                    ri_bad_ids.append(rk)
                else:
                    ri_valid_ids.append(lr)
        ri_has_dups = len(set(ri_valid_ids)) != len(ri_valid_ids)
        ri_set: set[str] | None = (
            set(ri_valid_ids) if (ri_present and ri_valid_container and not ri_bad_ids and not ri_has_dups) else None
        )

        if lid is not None:
            raw_lot_rows_by_lid.setdefault(lid, []).append(
                (
                    disp_raw,
                    disp,
                    lt_raw,
                    lt,
                    infused_raw,
                    od_set,
                    rr_set,
                    ri_set,
                    od_present,
                    rr_present,
                    ri_present,
                )
            )

        # Pass-0 separate raw primary recipient-binding validation BEFORE general CMC shape/outcome validation
        # so earlier malformed split-lot counts can NEVER mask contradictory recipient bindings or leave ancestry positive!
        if lt != "RESCUE_REPEAT_LOT":
            lot_lbl = repr(lid) if lid is not None else f"lot_ledger[{idx}]"
            if disp in ("FAILED_RELEASE", "RELEASED_UNINFUSED"):
                if od_present and (not od_valid_container or len(raw_out_dict) > 0):
                    errs.append(
                        f"CMC_PRIMARY_RECIPIENT_BINDING_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER uninfused/failed "
                        f"lot {lot_lbl} (lot_type={lt!r}, disposition={disp!r}) must have empty recipient_outcomes; "
                        "ancestry verification and cluster statistics nullified fail-closed."
                    )
                    conflict = True
                if rr_present and (not rr_valid_container or len(raw_out_recs) > 0):
                    errs.append(
                        f"CMC_PRIMARY_RECIPIENT_BINDING_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER uninfused/failed "
                        f"lot {lot_lbl} (lot_type={lt!r}, disposition={disp!r}) must have empty recipient_records; "
                        "ancestry verification and cluster statistics nullified fail-closed."
                    )
                    conflict = True
                if ri_present and (not ri_valid_container or len(raw_rids) > 0):
                    errs.append(
                        f"CMC_PRIMARY_RECIPIENT_BINDING_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER uninfused/failed "
                        f"lot {lot_lbl} (lot_type={lt!r}, disposition={disp!r}) must have empty recipient_ids; "
                        "ancestry verification and cluster statistics nullified fail-closed."
                    )
                    conflict = True
            elif disp == "RELEASED_INFUSED":
                if not od_present and not rr_present:
                    errs.append(
                        f"CMC_PRIMARY_RECIPIENT_BINDING_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER infused "
                        f"lot {lot_lbl} (lot_type={lt!r}) is missing explicit recipient_outcomes or "
                        "recipient_records binding; ancestry verification and cluster statistics nullified fail-closed."
                    )
                    conflict = True
                if od_present:
                    if not od_valid_container:
                        errs.append(
                            f"CMC_PRIMARY_RECIPIENT_BINDING_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER infused "
                            f"lot {lot_lbl} (lot_type={lt!r}) recipient_outcomes must be a dict; "
                            "ancestry verification and cluster statistics nullified fail-closed."
                        )
                        conflict = True
                    elif od_bad_keys:
                        errs.append(
                            f"CMC_PRIMARY_RECIPIENT_BINDING_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER infused "
                            f"lot {lot_lbl} (lot_type={lt!r}) recipient_outcomes contains invalid literal "
                            f"recipient_id key(s) {od_bad_keys!r}; ancestry verification and cluster statistics nullified fail-closed."
                        )
                        conflict = True
                    elif len(od_valid_ids) == 0:
                        errs.append(
                            f"CMC_PRIMARY_RECIPIENT_BINDING_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER infused "
                            f"lot {lot_lbl} (lot_type={lt!r}) has empty recipient_outcomes; "
                            "ancestry verification and cluster statistics nullified fail-closed."
                        )
                        conflict = True
                if rr_present:
                    if not rr_valid_container:
                        errs.append(
                            f"CMC_PRIMARY_RECIPIENT_BINDING_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER infused "
                            f"lot {lot_lbl} (lot_type={lt!r}) recipient_records must be a list; "
                            "ancestry verification and cluster statistics nullified fail-closed."
                        )
                        conflict = True
                    elif rr_malformed or rr_has_dups:
                        errs.append(
                            f"CMC_PRIMARY_RECIPIENT_BINDING_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER infused "
                            f"lot {lot_lbl} (lot_type={lt!r}) recipient_records contains malformed or duplicate "
                            "recipient_id entries; ancestry verification and cluster statistics nullified fail-closed."
                        )
                        conflict = True
                    elif len(rr_valid_ids) == 0:
                        errs.append(
                            f"CMC_PRIMARY_RECIPIENT_BINDING_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER infused "
                            f"lot {lot_lbl} (lot_type={lt!r}) has empty recipient_records; "
                            "ancestry verification and cluster statistics nullified fail-closed."
                        )
                        conflict = True
                if ri_present:
                    if not ri_valid_container:
                        errs.append(
                            f"CMC_PRIMARY_RECIPIENT_BINDING_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER infused "
                            f"lot {lot_lbl} (lot_type={lt!r}) recipient_ids must be a list; "
                            "ancestry verification and cluster statistics nullified fail-closed."
                        )
                        conflict = True
                    elif ri_bad_ids or ri_has_dups:
                        errs.append(
                            f"CMC_PRIMARY_RECIPIENT_BINDING_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER infused "
                            f"lot {lot_lbl} (lot_type={lt!r}) recipient_ids contains invalid literal or duplicate "
                            "recipient_id entries; ancestry verification and cluster statistics nullified fail-closed."
                        )
                        conflict = True
                    elif len(ri_valid_ids) == 0:
                        errs.append(
                            f"CMC_PRIMARY_RECIPIENT_BINDING_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER infused "
                            f"lot {lot_lbl} (lot_type={lt!r}) has empty recipient_ids; "
                            "ancestry verification and cluster statistics nullified fail-closed."
                        )
                        conflict = True
            else:
                if od_present and (not od_valid_container or od_bad_keys):
                    errs.append(
                        f"CMC_PRIMARY_RECIPIENT_BINDING_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER "
                        f"lot {lot_lbl} (lot_type={lt!r}, disposition={disp_raw!r}) has malformed recipient_outcomes; "
                        "ancestry verification and cluster statistics nullified fail-closed."
                    )
                    conflict = True
                if rr_present and (not rr_valid_container or rr_malformed or rr_has_dups):
                    errs.append(
                        f"CMC_PRIMARY_RECIPIENT_BINDING_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER "
                        f"lot {lot_lbl} (lot_type={lt!r}, disposition={disp_raw!r}) has malformed or duplicate recipient_records; "
                        "ancestry verification and cluster statistics nullified fail-closed."
                    )
                    conflict = True
                if ri_present and (not ri_valid_container or ri_bad_ids or ri_has_dups):
                    errs.append(
                        f"CMC_PRIMARY_RECIPIENT_BINDING_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER "
                        f"lot {lot_lbl} (lot_type={lt!r}, disposition={disp_raw!r}) has malformed or duplicate recipient_ids; "
                        "ancestry verification and cluster statistics nullified fail-closed."
                    )
                    conflict = True

            # Require exact set agreement across ALL supplied raw recipient-binding fields on every non-rescue row!
            bound_sets: list[tuple[str, list[str]]] = []
            if od_present and od_valid_container and not od_bad_keys:
                bound_sets.append(("recipient_outcomes", sorted(set(od_valid_ids))))
            if rr_present and rr_valid_container and not rr_malformed:
                bound_sets.append(("recipient_records", sorted(set(rr_valid_ids))))
            if ri_present and ri_valid_container and not ri_bad_ids:
                bound_sets.append(("recipient_ids", sorted(set(ri_valid_ids))))
            if len(bound_sets) >= 2 and len({tuple(vals) for _lbl, vals in bound_sets}) > 1:
                errs.append(
                    f"CMC_PRIMARY_RECIPIENT_BINDING_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER "
                    f"lot {lot_lbl} (lot_type={lt!r}, disposition={disp_raw!r}) has mutually contradictory "
                    f"recipient bindings {bound_sets!r}; ancestry verification and cluster statistics nullified fail-closed."
                )
                conflict = True

        if lid is None or mid is None:
            errs.append(
                f"CMC_LEDGER_ANCESTRY_UNVERIFIABLE: raw PARALLEL_CMC_READINESS_LEDGER lot_ledger[{idx}] "
                f"missing valid literal lot_id={entry.get('lot_id')!r} or mcb_id={entry.get('mcb_id')!r}."
            )
            conflict = True
            continue

        for ek, ev in sorted(entry.items(), key=lambda kv: str(kv[0])):
            if ev is None or not isinstance(ek, str) or ek in CMC_LEDGER_KNOWN_BANK_KEYS:
                continue
            ek_lo = ek.lower()
            if any(tok in ek_lo for tok in ("mcb", "wcb", "cell_bank", "bank_id")):
                errs.append(
                    f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: UNRECOGNIZED_BANK_ALIAS in raw "
                    f"PARALLEL_CMC_READINESS_LEDGER lot_id={lid!r}: unsupported bank key {ek!r}."
                )
                if lt == "RESCUE_REPEAT_LOT":
                    errs.append(
                        f"CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER "
                        f"RESCUE_REPEAT_LOT lot_id={lid!r} declares unsupported bank alias key {ek!r}; "
                        "ancestry verification and cluster statistics nullified fail-closed."
                    )
                conflict = True

        row_mcbs: set[str] = {mid}
        for mcb_alias in ("master_cell_bank_id", "bank_id"):
            if mcb_alias in entry and entry[mcb_alias] is not None:
                amid = _strict_literal_id(entry[mcb_alias])
                if amid is None or amid != mid:
                    errs.append(
                        f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: CONFLICTING_MCB_ALIAS in raw "
                        f"PARALLEL_CMC_READINESS_LEDGER lot_id={lid!r} (disposition={disp!r}): "
                        f"{mcb_alias}={entry[mcb_alias]!r} contradicts mcb_id={mid!r}."
                    )
                    if lt == "RESCUE_REPEAT_LOT":
                        errs.append(
                            f"CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER "
                            f"RESCUE_REPEAT_LOT lot_id={lid!r} (disposition={disp!r}) declares "
                            f"{mcb_alias}={entry[mcb_alias]!r}, contradicting mcb_id={mid!r}; "
                            "ancestry verification and cluster statistics nullified fail-closed."
                        )
                    conflict = True
                if amid is not None:
                    row_mcbs.add(amid)
                    if lid in ref_mcb_map and amid != ref_mcb_map[lid]:
                        errs.append(
                            f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: raw PARALLEL_CMC_READINESS_LEDGER "
                            f"row lot_id={lid!r} (disposition={disp!r}) {mcb_alias}={amid!r} contradicts "
                            f"VERIFIED_LOT_TO_BANK_MANIFEST mcb_id={ref_mcb_map[lid]!r}."
                        )
                        if lt == "RESCUE_REPEAT_LOT":
                            errs.append(
                                f"CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER "
                                f"RESCUE_REPEAT_LOT lot_id={lid!r} (disposition={disp!r}) declares "
                                f"{mcb_alias}={amid!r}, contradicting VERIFIED_LOT_TO_BANK_MANIFEST mcb_id={ref_mcb_map[lid]!r}; "
                                "ancestry verification and cluster statistics nullified fail-closed."
                            )
                        conflict = True

        row_wcbs: set[str] = set()
        wid: str | None = None
        if entry.get("wcb_id") is not None:
            wid = _strict_literal_id(entry.get("wcb_id"))
            if wid is None:
                errs.append(
                    f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: raw PARALLEL_CMC_READINESS_LEDGER "
                    f"row lot_id={lid!r} has invalid literal wcb_id={entry.get('wcb_id')!r}."
                )
                if lt == "RESCUE_REPEAT_LOT":
                    errs.append(
                        f"CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER "
                        f"RESCUE_REPEAT_LOT lot_id={lid!r} has invalid literal wcb_id={entry.get('wcb_id')!r}; "
                        "ancestry verification and cluster statistics nullified fail-closed."
                    )
                conflict = True
            else:
                row_wcbs.add(wid)
        if entry.get("working_cell_bank_id") is not None:
            waid = _strict_literal_id(entry.get("working_cell_bank_id"))
            if waid is None:
                errs.append(
                    f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: raw PARALLEL_CMC_READINESS_LEDGER "
                    f"row lot_id={lid!r} has invalid literal working_cell_bank_id={entry.get('working_cell_bank_id')!r}."
                )
                if lt == "RESCUE_REPEAT_LOT":
                    errs.append(
                        f"CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER "
                        f"RESCUE_REPEAT_LOT lot_id={lid!r} has invalid literal "
                        f"working_cell_bank_id={entry.get('working_cell_bank_id')!r}; "
                        "ancestry verification and cluster statistics nullified fail-closed."
                    )
                conflict = True
            else:
                row_wcbs.add(waid)
                if wid is not None and waid != wid:
                    errs.append(
                        f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: CONFLICTING_WCB_ALIAS in raw "
                        f"PARALLEL_CMC_READINESS_LEDGER lot_id={lid!r}: working_cell_bank_id={waid!r} contradicts wcb_id={wid!r}."
                    )
                    if lt == "RESCUE_REPEAT_LOT":
                        errs.append(
                            f"CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER "
                            f"RESCUE_REPEAT_LOT lot_id={lid!r} declares working_cell_bank_id={waid!r}, "
                            f"contradicting wcb_id={wid!r}; ancestry verification and cluster statistics nullified fail-closed."
                        )
                    conflict = True
                elif wid is None:
                    wid = waid

        if lid in seen_lots_raw:
            errs.append(
                f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: DUPLICATE_LOT_ID_IN_CMC_LEDGER "
                f"for lot_id={lid!r} (ambiguous lot-to-bank ancestry)."
            )
            conflict = True
        else:
            seen_lots_raw[lid] = (mid, wid)

        if disp == "RELEASED_INFUSED":
            if lid not in ref_mcb_map:
                errs.append(
                    f"CMC_INFUSED_LOT_MISSING_FROM_VERIFIED_MANIFEST: raw PARALLEL_CMC_READINESS_LEDGER "
                    f"infused {lt} lot_id={lid!r} (mcb_id={mid!r}) lacks independent "
                    "verified ancestry in VERIFIED_LOT_TO_BANK_MANIFEST."
                )
                if lt == "RESCUE_REPEAT_LOT":
                    errs.append(
                        f"CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER infused "
                        f"RESCUE_REPEAT_LOT lot_id={lid!r} (mcb_id={mid!r}) lacks independent verified "
                        "ancestry in VERIFIED_LOT_TO_BANK_MANIFEST; ancestry verification and cluster statistics nullified fail-closed."
                    )
                conflict = True
            if row_wcbs and lid not in ref_wcb_map:
                errs.append(
                    f"CMC_INFUSED_LOT_WCB_MISSING_FROM_VERIFIED_MANIFEST: raw PARALLEL_CMC_READINESS_LEDGER "
                    f"infused {lt} lot_id={lid!r} declares wcb_id={sorted(row_wcbs)!r} absent from "
                    "VERIFIED_LOT_TO_BANK_MANIFEST."
                )
                if lt == "RESCUE_REPEAT_LOT":
                    errs.append(
                        f"CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER infused "
                        f"RESCUE_REPEAT_LOT lot_id={lid!r} declares wcb_id={sorted(row_wcbs)!r} absent from "
                        "VERIFIED_LOT_TO_BANK_MANIFEST; ancestry verification and cluster statistics nullified fail-closed."
                    )
                conflict = True
            if lid in ref_wcb_map and not row_wcbs:
                errs.append(
                    f"CMC_INFUSED_LOT_MISSING_DECLARED_WCB_ID: raw PARALLEL_CMC_READINESS_LEDGER "
                    f"infused {lt} lot_id={lid!r} omits wcb_id/working_cell_bank_id while "
                    f"VERIFIED_LOT_TO_BANK_MANIFEST declares wcb_id={ref_wcb_map[lid]!r} for this lot."
                )
                if lt == "RESCUE_REPEAT_LOT":
                    errs.append(
                        f"CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER infused "
                        f"RESCUE_REPEAT_LOT lot_id={lid!r} omits wcb_id/working_cell_bank_id while "
                        f"VERIFIED_LOT_TO_BANK_MANIFEST declares wcb_id={ref_wcb_map[lid]!r}; "
                        "ancestry verification and cluster statistics nullified fail-closed."
                    )
                conflict = True

        if lid in ref_mcb_map and mid != ref_mcb_map[lid]:
            errs.append(
                f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: raw PARALLEL_CMC_READINESS_LEDGER "
                f"row lot_id={lid!r} (lot_type={lt!r}, disposition={disp!r}) declares "
                f"mcb_id={mid!r}, contradicting VERIFIED_LOT_TO_BANK_MANIFEST mcb_id={ref_mcb_map[lid]!r}."
            )
            if lt == "RESCUE_REPEAT_LOT":
                errs.append(
                    f"CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER "
                    f"RESCUE_REPEAT_LOT lot_id={lid!r} (disposition={disp!r}) declares mcb_id={mid!r}, "
                    f"contradicting VERIFIED_LOT_TO_BANK_MANIFEST mcb_id={ref_mcb_map[lid]!r}; "
                    "ancestry verification and cluster statistics nullified fail-closed."
                )
            conflict = True

        for rw in sorted(row_wcbs):
            if lid in ref_wcb_map and rw != ref_wcb_map[lid]:
                errs.append(
                    f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: raw PARALLEL_CMC_READINESS_LEDGER "
                    f"row lot_id={lid!r} (lot_type={lt!r}, disposition={disp!r}) declares "
                    f"wcb_id={rw!r}, contradicting VERIFIED_LOT_TO_BANK_MANIFEST wcb_id={ref_wcb_map[lid]!r}."
                )
                if lt == "RESCUE_REPEAT_LOT":
                    errs.append(
                        f"CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER "
                        f"RESCUE_REPEAT_LOT lot_id={lid!r} (disposition={disp!r}) declares wcb_id={rw!r}, "
                        f"contradicting VERIFIED_LOT_TO_BANK_MANIFEST wcb_id={ref_wcb_map[lid]!r}; "
                        "ancestry verification and cluster statistics nullified fail-closed."
                    )
                conflict = True

        if lt == "RESCUE_REPEAT_LOT":
            rescue_wcbs_seen.update(row_wcbs)
            if lid in ref_wcb_map:
                rescue_wcbs_seen.add(ref_wcb_map[lid])

        # Unconditional Pass-0-backed recipient-level lot/MCB/WCB ancestry cross-check across raw CMC rows
        # (catches recipient-to-lot/MCB/WCB swaps AND missing/contradictory rescue linkage even when
        # follow-up/outcome is missing OR another row triggered an unrelated CMC ValueError!)
        if lt != "RESCUE_REPEAT_LOT":
            if (
                entry.get("rescued_recipient_id") is not None
                or entry.get("rescued_primary_lot_id") is not None
            ):
                errs.append(
                    f"CMC_RESCUE_LINKAGE_MISPLACED_ON_NON_RESCUE_LOT: raw PARALLEL_CMC_READINESS_LEDGER "
                    f"non-rescue lot {lid!r} (lot_type={lt!r}) declares rescue linkage fields "
                    f"(rescued_recipient_id={entry.get('rescued_recipient_id')!r}, "
                    f"rescued_primary_lot_id={entry.get('rescued_primary_lot_id')!r}); "
                    "ancestry verification and cluster statistics nullified fail-closed."
                )
                conflict = True
            row_rids: set[str] = set()
            row_rids.update(od_valid_ids)
            row_rids.update(rr_valid_ids)
            row_rids.update(ri_valid_ids)
            supplied_valid_sets: list[set[str]] = []
            if od_present:
                supplied_valid_sets.append(od_set if od_set is not None else set())
            if rr_present:
                supplied_valid_sets.append(rr_set if rr_set is not None else set())
            if ri_present:
                supplied_valid_sets.append(ri_set if ri_set is not None else set())
            unanimous_primary_rids: set[str] = (
                set.intersection(*supplied_valid_sets)
                if ((od_present or rr_present) and supplied_valid_sets)
                else set()
            )
            if disp == "RELEASED_INFUSED" and lt in ("SINGLE_RECIPIENT", "SPLIT_LOT", "MULTI_LOT_COURSE_PRIMARY"):
                raw_primary_lot_rids.setdefault(lid, set()).update(unanimous_primary_rids)
            if clinical_recipient_meta is not None or raw_ancestry_claims_by_rid is not None:
                for rid in sorted(row_rids):
                    raw_claims_for_rid = (
                        sorted(set(raw_ancestry_claims_by_rid.get(rid, ())), key=repr)
                        if raw_ancestry_claims_by_rid is not None
                        else []
                    )
                    cmeta = clinical_recipient_meta.get(rid) if clinical_recipient_meta is not None else None
                    if not raw_claims_for_rid and cmeta is None:
                        if disp == "RELEASED_INFUSED":
                            errs.append(
                                f"CMC_INFUSED_RECIPIENT_OMITTED_FROM_CLINICAL_COHORT: raw PARALLEL_CMC_READINESS_LEDGER "
                                f"infused lot_id={lid!r} records recipient {rid!r} absent from clinical cohort; "
                                "ancestry verification and cluster statistics nullified fail-closed."
                            )
                            conflict = True
                        continue
                    if raw_claims_for_rid:
                        for c_lid_cl, c_mcbs_cl, c_wcbs_cl, c_wcb_inv_cl in raw_claims_for_rid:
                            if c_lid_cl is not None and c_lid_cl != lid:
                                errs.append(
                                    f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: CMC reconciliation lot_id mismatch "
                                    f"for recipient {rid!r}: clinical={c_lid_cl!r} != cmc={lid!r}."
                                )
                                conflict = True
                            for c_mid_cl in c_mcbs_cl:
                                if c_mid_cl != mid:
                                    errs.append(
                                        f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: CMC reconciliation mcb_id mismatch "
                                        f"for recipient {rid!r}: clinical={c_mid_cl!r} != cmc={mid!r}."
                                    )
                                    conflict = True
                            if c_wcbs_cl:
                                if not row_wcbs:
                                    for c_wid_cl in c_wcbs_cl:
                                        if c_lid_cl == lid:
                                            errs.append(
                                                f"CMC_INFUSED_LOT_MISSING_DECLARED_WCB_ID: CMC reconciliation for recipient {rid!r} "
                                                f"(lot_id={lid!r}): clinical/manifest declares wcb_id={c_wid_cl!r} "
                                                "but raw CMC row omitted wcb_id."
                                            )
                                        else:
                                            errs.append(
                                                f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: CMC reconciliation wcb_id mismatch "
                                                f"for recipient {rid!r}: clinical={c_wid_cl!r} != cmc=None."
                                            )
                                        conflict = True
                                else:
                                    cmc_wcb_disp = next(iter(row_wcbs)) if len(row_wcbs) == 1 else sorted(row_wcbs)
                                    for c_wid_cl in c_wcbs_cl:
                                        if any(rw != c_wid_cl for rw in row_wcbs):
                                            errs.append(
                                                f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: CMC reconciliation wcb_id mismatch "
                                                f"for recipient {rid!r}: clinical={c_wid_cl!r} != cmc={cmc_wcb_disp!r}."
                                            )
                                            conflict = True
                            elif not c_wcb_inv_cl and row_wcbs:
                                cmc_wcb_disp = next(iter(row_wcbs)) if len(row_wcbs) == 1 else sorted(row_wcbs)
                                errs.append(
                                    f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: CMC reconciliation wcb_id mismatch "
                                    f"for recipient {rid!r}: clinical=None != cmc={cmc_wcb_disp!r}."
                                )
                                conflict = True
                    elif cmeta is not None:
                        if cmeta["lot_id"] != lid:
                            errs.append(
                                f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: CMC reconciliation lot_id mismatch "
                                f"for recipient {rid!r}: clinical={cmeta['lot_id']!r} != cmc={lid!r}."
                            )
                            conflict = True
                        if cmeta["mcb_id"] != mid:
                            errs.append(
                                f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: CMC reconciliation mcb_id mismatch "
                                f"for recipient {rid!r}: clinical={cmeta['mcb_id']!r} != cmc={mid!r}."
                            )
                            conflict = True
                        if cmeta["wcb_id"] is not None:
                            if not row_wcbs:
                                if cmeta["lot_id"] == lid:
                                    errs.append(
                                        f"CMC_INFUSED_LOT_MISSING_DECLARED_WCB_ID: CMC reconciliation for recipient {rid!r} "
                                        f"(lot_id={lid!r}): clinical/manifest declares wcb_id={cmeta['wcb_id']!r} "
                                        "but raw CMC row omitted wcb_id."
                                    )
                                else:
                                    errs.append(
                                        f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: CMC reconciliation wcb_id mismatch "
                                        f"for recipient {rid!r}: clinical={cmeta['wcb_id']!r} != cmc=None."
                                    )
                                conflict = True
                            elif any(rw != cmeta["wcb_id"] for rw in row_wcbs):
                                cmc_wcb_disp = next(iter(row_wcbs)) if len(row_wcbs) == 1 else sorted(row_wcbs)
                                errs.append(
                                    f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: CMC reconciliation wcb_id mismatch "
                                    f"for recipient {rid!r}: clinical={cmeta['wcb_id']!r} != cmc={cmc_wcb_disp!r}."
                                )
                                conflict = True
                        elif row_wcbs:
                            cmc_wcb_disp = next(iter(row_wcbs)) if len(row_wcbs) == 1 else sorted(row_wcbs)
                            errs.append(
                                f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: CMC reconciliation wcb_id mismatch "
                                f"for recipient {rid!r}: clinical=None != cmc={cmc_wcb_disp!r}."
                            )
                            conflict = True
        else:
            # RESCUE_REPEAT_LOT: unconditionally validate rescued_recipient_id & rescued_primary_lot_id linkage
            # BEFORE evaluate_cmc_attempted_lot_readiness so missing/contradictory rescue linkage ALWAYS nullifies ancestry!
            resc_rid = _strict_literal_id(entry.get("rescued_recipient_id"))
            resc_prim = _strict_literal_id(entry.get("rescued_primary_lot_id"))
            raw_rescue_rows.append((lid, disp, resc_rid, resc_prim))
            if resc_rid is None:
                errs.append(
                    f"CMC_RESCUE_LINKAGE_MISSING_OR_INVALID: raw PARALLEL_CMC_READINESS_LEDGER "
                    f"RESCUE_REPEAT_LOT {lid!r} (disposition={disp!r}) is missing valid literal "
                    f"rescued_recipient_id (got {entry.get('rescued_recipient_id')!r}); "
                    "ancestry verification and cluster statistics nullified fail-closed."
                )
                conflict = True
            if resc_prim is None:
                errs.append(
                    f"CMC_RESCUE_LINKAGE_MISSING_OR_INVALID: raw PARALLEL_CMC_READINESS_LEDGER "
                    f"RESCUE_REPEAT_LOT {lid!r} (disposition={disp!r}) is missing valid literal "
                    f"rescued_primary_lot_id (got {entry.get('rescued_primary_lot_id')!r}); "
                    "ancestry verification and cluster statistics nullified fail-closed."
                )
                conflict = True
            if resc_prim is not None and resc_prim == lid:
                errs.append(
                    f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: CMC rescue lot {lid!r} declares "
                    f"self-referential rescued_primary_lot_id={resc_prim!r}; "
                    "ancestry verification and cluster statistics nullified fail-closed."
                )
                errs.append(
                    f"CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: CMC rescue lot {lid!r} declares "
                    f"self-referential rescued_primary_lot_id={resc_prim!r}; "
                    "ancestry verification and cluster statistics nullified fail-closed."
                )
                conflict = True
            if (clinical_recipient_meta is not None or raw_ancestry_claims_by_rid is not None) and resc_rid is not None:
                in_clinical_resc = (
                    (raw_ancestry_claims_by_rid is not None and resc_rid in raw_ancestry_claims_by_rid)
                    or (clinical_recipient_meta is not None and resc_rid in clinical_recipient_meta)
                )
                if in_clinical_resc:
                    resc_claimed_lids: set[str] = set()
                    if raw_ancestry_claims_by_rid is not None and resc_rid in raw_ancestry_claims_by_rid:
                        for cl_r in raw_ancestry_claims_by_rid[resc_rid]:
                            if cl_r[0] is not None:
                                resc_claimed_lids.add(cl_r[0])
                    if clinical_recipient_meta is not None and resc_rid in clinical_recipient_meta:
                        cm_lid = clinical_recipient_meta[resc_rid].get("lot_id")
                        if cm_lid is not None:
                            resc_claimed_lids.add(cm_lid)
                    if resc_prim is not None:
                        for c_prim_lid in sorted(resc_claimed_lids):
                            if c_prim_lid != resc_prim:
                                errs.append(
                                    f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: CMC rescue lot {lid!r} declares "
                                    f"rescued_primary_lot_id={resc_prim!r} for recipient {resc_rid!r}, contradicting "
                                    f"clinical primary lot_id={c_prim_lid!r}."
                                )
                                errs.append(
                                    f"CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: CMC rescue lot {lid!r} declares "
                                    f"rescued_primary_lot_id={resc_prim!r} for recipient {resc_rid!r}, contradicting "
                                    f"clinical primary lot_id={c_prim_lid!r}; ancestry verification and cluster statistics nullified fail-closed."
                                )
                                conflict = True
                elif disp != "RELEASED_INFUSED":
                    errs.append(
                        f"CMC_RESCUE_LINKAGE_NON_COHORT_RECIPIENT: raw PARALLEL_CMC_READINESS_LEDGER "
                        f"RESCUE_REPEAT_LOT {lid!r} (disposition={disp!r}) declares rescued_recipient_id={resc_rid!r} "
                        "absent from clinical cohort; ancestry verification and cluster statistics nullified fail-closed."
                    )
                    conflict = True

        for rw in sorted(row_wcbs):
            tree_wcb_to_mcbs.setdefault(rw, set()).update(row_mcbs)
        if lid in ref_wcb_map:
            tree_wcb_to_mcbs.setdefault(ref_wcb_map[lid], set()).update(row_mcbs)

    if clinical_recipient_meta is not None or raw_ancestry_claims_by_rid is not None:
        valid_primary_lot_types = {
            "SINGLE_RECIPIENT",
            "SPLIT_LOT",
            "MULTI_LOT_COURSE_PRIMARY",
            "MULTI_LOT_COURSE_CONSTITUENT",
        }
        # Audit EVERY distinct Pass-0 primary-lot claim for EVERY recipient across all single and duplicate rows!
        claimed_primary_lids_by_rid: dict[str, set[str]] = {}
        if clinical_recipient_meta is not None:
            for rid_m, cmeta_m in clinical_recipient_meta.items():
                lid_m = cmeta_m.get("lot_id")
                if lid_m is not None:
                    claimed_primary_lids_by_rid.setdefault(rid_m, set()).add(lid_m)
        if raw_ancestry_claims_by_rid is not None:
            for rid_r, claims_r in raw_ancestry_claims_by_rid.items():
                for claim_lid_r, _cm, _cw, _cwi in claims_r:
                    if claim_lid_r is not None:
                        claimed_primary_lids_by_rid.setdefault(rid_r, set()).add(claim_lid_r)
        for rid in sorted(claimed_primary_lids_by_rid):
            for c_lid in sorted(claimed_primary_lids_by_rid[rid]):
                lot_rows = raw_lot_rows_by_lid.get(c_lid)
                if not lot_rows:
                    errs.append(
                        f"CLINICAL_PRIMARY_LOT_MISSING_FROM_CMC_LEDGER: clinical recipient {rid!r} claims "
                        f"infused primary lot_id={c_lid!r}, which is absent from raw PARALLEL_CMC_READINESS_LEDGER; "
                        "ancestry verification and cluster statistics nullified fail-closed."
                    )
                    conflict = True
                    continue
                has_valid_infused_primary_row = False
                any_row_binds_rid_completely = False
                any_row_missing_rid = False
                for (
                    disp_raw_r,
                    disp_r,
                    lt_raw_r,
                    lt_r,
                    inf_raw_r,
                    od_set_r,
                    rr_set_r,
                    ri_set_r,
                    od_pres_r,
                    rr_pres_r,
                    ri_pres_r,
                ) in lot_rows:
                    if disp_r != "RELEASED_INFUSED":
                        errs.append(
                            f"CLINICAL_PRIMARY_LOT_CMC_DISPOSITION_CONFLICT: clinical recipient {rid!r} claims "
                            f"infused primary lot_id={c_lid!r}, but raw PARALLEL_CMC_READINESS_LEDGER records "
                            f"lot_id={c_lid!r} with non-infused disposition={disp_raw_r!r} (lot_type={lt_raw_r!r}); "
                            "ancestry verification and cluster statistics nullified fail-closed."
                        )
                        conflict = True
                    elif lt_r not in valid_primary_lot_types:
                        errs.append(
                            f"CLINICAL_PRIMARY_LOT_CMC_DISPOSITION_CONFLICT: clinical recipient {rid!r} claims "
                            f"infused primary lot_id={c_lid!r}, but raw PARALLEL_CMC_READINESS_LEDGER records "
                            f"lot_id={c_lid!r} with non-primary lot_type={lt_raw_r!r} (disposition={disp_raw_r!r}); "
                            "ancestry verification and cluster statistics nullified fail-closed."
                        )
                        conflict = True
                    elif type(inf_raw_r) is not int or inf_raw_r < 1:
                        errs.append(
                            f"CLINICAL_PRIMARY_LOT_CMC_DISPOSITION_CONFLICT: clinical recipient {rid!r} claims "
                            f"infused primary lot_id={c_lid!r}, but raw PARALLEL_CMC_READINESS_LEDGER records "
                            f"lot_id={c_lid!r} with invalid/zero infused_doses_n={inf_raw_r!r} "
                            f"(disposition={disp_raw_r!r}); ancestry verification and cluster statistics nullified fail-closed."
                        )
                        conflict = True
                    else:
                        has_valid_infused_primary_row = True
                        has_explicit_binding = (od_set_r is not None) or (rr_set_r is not None)
                        missing_in_supplied = (
                            (not has_explicit_binding)
                            or (od_pres_r and (od_set_r is None or rid not in od_set_r))
                            or (rr_pres_r and (rr_set_r is None or rid not in rr_set_r))
                            or (ri_pres_r and (ri_set_r is None or rid not in ri_set_r))
                        )
                        if missing_in_supplied:
                            any_row_missing_rid = True
                        else:
                            any_row_binds_rid_completely = True
                if has_valid_infused_primary_row and (
                    not any_row_binds_rid_completely or any_row_missing_rid
                ):
                    errs.append(
                        f"CLINICAL_PRIMARY_RECIPIENT_MISSING_FROM_CMC_LOT: clinical recipient {rid!r} claims "
                        f"infused primary lot_id={c_lid!r}, but raw PARALLEL_CMC_READINESS_LEDGER row for "
                        f"lot_id={c_lid!r} does not record recipient {rid!r} as infused across all supplied recipient bindings; "
                        "ancestry verification and cluster statistics nullified fail-closed."
                    )
                    conflict = True

    for rlid, rdisp, r_rid, r_prim in raw_rescue_rows:
        if r_prim is not None and r_prim != rlid:
            if r_prim not in raw_primary_lot_rids:
                errs.append(
                    f"CMC_ORPHAN_RESCUE_PRIMARY_LOT: raw PARALLEL_CMC_READINESS_LEDGER "
                    f"RESCUE_REPEAT_LOT {rlid!r} (disposition={rdisp!r}) declares rescued_primary_lot_id={r_prim!r}, "
                    "which does not match any infused initial primary lot in PARALLEL_CMC_READINESS_LEDGER; "
                    "ancestry verification and cluster statistics nullified fail-closed."
                )
                errs.append(
                    f"CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER "
                    f"RESCUE_REPEAT_LOT {rlid!r} (disposition={rdisp!r}) declares orphan rescued_primary_lot_id={r_prim!r}; "
                    "ancestry verification and cluster statistics nullified fail-closed."
                )
                conflict = True
            elif r_rid is not None and r_rid not in raw_primary_lot_rids[r_prim]:
                errs.append(
                    f"CMC_ORPHAN_RESCUE_PRIMARY_LOT: raw PARALLEL_CMC_READINESS_LEDGER "
                    f"RESCUE_REPEAT_LOT {rlid!r} (disposition={rdisp!r}) declares rescued_recipient_id={r_rid!r} "
                    f"for rescued_primary_lot_id={r_prim!r}, but that recipient is absent from primary lot "
                    f"{r_prim!r} explicit recipient outcomes/records; ancestry verification and cluster statistics nullified fail-closed."
                )
                errs.append(
                    f"CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER "
                    f"RESCUE_REPEAT_LOT {rlid!r} (disposition={rdisp!r}) declares rescued_recipient_id={r_rid!r} "
                    f"absent from linked primary lot {r_prim!r}; ancestry verification and cluster statistics nullified fail-closed."
                )
                conflict = True

    for wid_t, mcbs_t in sorted(tree_wcb_to_mcbs.items()):
        if len(mcbs_t) > 1:
            errs.append(
                f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: NON_UNIQUE_WCB_PARENTAGE "
                f"across verified manifest and PARALLEL_CMC_READINESS_LEDGER: wcb_id={wid_t!r} "
                f"maps to multiple distinct MCBs {sorted(mcbs_t)}."
            )
            if wid_t in rescue_wcbs_seen:
                errs.append(
                    f"CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: rescue-linked wcb_id={wid_t!r} maps to "
                    f"multiple distinct MCBs {sorted(mcbs_t)} across verified manifest and PARALLEL_CMC_READINESS_LEDGER; "
                    "ancestry verification and cluster statistics nullified fail-closed."
                )
            conflict = True

    return sorted(dict.fromkeys(errs)), conflict


def _reconcile_raw_clinical_and_cmc_rescues(
    lot_ledger_raw: Any,
    *,
    seen_rids: set[str],
    clinical_recipient_meta: dict[str, dict[str, Any]],
    raw_ancestry_claims_by_rid: dict[str, list[Any]],
    raw_rescue_claims_by_rid: dict[str, list[dict[str, Any]]],
    duplicate_rids_set: set[str],
    duplicate_rescue_errors_by_rid: dict[str, list[str]],
    ref_mcb_map: dict[str, str],
    ref_wcb_map: dict[str, str],
) -> tuple[list[str], bool]:
    """
    Single-source-of-truth unconditional bidirectional raw clinical-vs-CMC rescue identity,
    cardinality, and bank-lineage reconciler executed BEFORE evaluate_cmc_attempted_lot_readiness
    so unrelated CMC shape errors (such as invalid split-lot planned_doses_n) can NEVER mask
    rescue-identity mismatches or bypass full fail-closed ancestry nullification.
    Returns (rescue_errors, has_rescue_ancestry_conflict).
    """
    if not isinstance(lot_ledger_raw, list) or len(lot_ledger_raw) == 0:
        return [], False

    errs: list[str] = []
    ancestry_conflict = False
    cmc_rescue_lots_by_rid: dict[str, list[str]] = {}
    cmc_rescue_lineages_by_rid: dict[str, list[tuple[str, str | None, str | None]]] = {}
    non_cohort_cmc_rescues: list[tuple[str, str]] = []
    malformed_cmc_rescue_errs: list[str] = []

    valid_disps = {"FAILED_RELEASE", "RELEASED_UNINFUSED", "RELEASED_INFUSED"}
    ordered_ledger_raw = sorted(lot_ledger_raw, key=_canonical_cmc_lot_sort_key)
    for entry in ordered_ledger_raw:
        if not isinstance(entry, dict):
            continue
        lt = _strict_literal_id(entry.get("lot_type"))
        if lt != "RESCUE_REPEAT_LOT":
            continue
        disp = _strict_literal_id(entry.get("disposition"))
        lid = _strict_literal_id(entry.get("lot_id"))
        mid = _strict_literal_id(entry.get("mcb_id"))
        wid_raw = entry.get("wcb_id") if entry.get("wcb_id") is not None else entry.get("working_cell_bank_id")
        wid = _strict_literal_id(wid_raw) if wid_raw is not None else None
        resc_rid = _strict_literal_id(entry.get("rescued_recipient_id"))
        if lid is None:
            ancestry_conflict = True
            continue
        if disp not in valid_disps:
            malformed_cmc_rescue_errs.append(
                f"CMC_RESCUE_RECIPIENT_BINDING_CONFLICT / CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: "
                f"raw PARALLEL_CMC_READINESS_LEDGER RESCUE_REPEAT_LOT {lid!r} has invalid "
                f"disposition={entry.get('disposition')!r}; ancestry verification and cluster statistics nullified fail-closed."
            )
            ancestry_conflict = True
            continue

        raw_out_dict = entry.get("recipient_outcomes")
        raw_out_recs = entry.get("recipient_records")
        raw_rids = entry.get("recipient_ids")

        if disp != "RELEASED_INFUSED":
            if raw_out_dict is not None and (not isinstance(raw_out_dict, dict) or len(raw_out_dict) > 0):
                malformed_cmc_rescue_errs.append(
                    f"CMC_RESCUE_RECIPIENT_BINDING_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER uninfused/failed "
                    f"RESCUE_REPEAT_LOT {lid!r} (disposition={disp!r}) must have empty recipient_outcomes; "
                    "ancestry verification and cluster statistics nullified fail-closed."
                )
                ancestry_conflict = True
            if raw_out_recs is not None and (not isinstance(raw_out_recs, list) or len(raw_out_recs) > 0):
                malformed_cmc_rescue_errs.append(
                    f"CMC_RESCUE_RECIPIENT_BINDING_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER uninfused/failed "
                    f"RESCUE_REPEAT_LOT {lid!r} (disposition={disp!r}) must have empty recipient_records; "
                    "ancestry verification and cluster statistics nullified fail-closed."
                )
                ancestry_conflict = True
            if raw_rids is not None and (not isinstance(raw_rids, list) or len(raw_rids) > 0):
                malformed_cmc_rescue_errs.append(
                    f"CMC_RESCUE_RECIPIENT_BINDING_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER uninfused/failed "
                    f"RESCUE_REPEAT_LOT {lid!r} (disposition={disp!r}) must have empty recipient_ids; "
                    "ancestry verification and cluster statistics nullified fail-closed."
                )
                ancestry_conflict = True
            continue

        # disp == "RELEASED_INFUSED": unconditionally reconcile resc_rid AND ALL recipient/outcome binding fields!
        bound_sets: list[tuple[str, list[str]]] = []
        if raw_out_dict is None and raw_out_recs is None:
            malformed_cmc_rescue_errs.append(
                f"CMC_RESCUE_RECIPIENT_BINDING_CONFLICT / CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: "
                f"raw PARALLEL_CMC_READINESS_LEDGER infused RESCUE_REPEAT_LOT {lid!r} is missing explicit "
                f"recipient_outcomes or recipient_records binding for rescued_recipient_id={resc_rid!r}; "
                "ancestry verification and cluster statistics nullified fail-closed."
            )
            ancestry_conflict = True

        if raw_out_dict is not None:
            if not isinstance(raw_out_dict, dict):
                malformed_cmc_rescue_errs.append(
                    f"CMC_RESCUE_RECIPIENT_BINDING_CONFLICT / CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: "
                    f"raw PARALLEL_CMC_READINESS_LEDGER infused RESCUE_REPEAT_LOT {lid!r} recipient_outcomes must be a dict; "
                    "ancestry verification and cluster statistics nullified fail-closed."
                )
                ancestry_conflict = True
            else:
                valid_od_keys: list[str] = []
                bad_od_keys: list[Any] = []
                for rk in sorted(raw_out_dict.keys(), key=repr):
                    lr = _strict_literal_id(rk)
                    if lr is None:
                        bad_od_keys.append(rk)
                    else:
                        valid_od_keys.append(lr)
                if bad_od_keys:
                    malformed_cmc_rescue_errs.append(
                        f"CMC_RESCUE_RECIPIENT_BINDING_CONFLICT / CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: "
                        f"raw PARALLEL_CMC_READINESS_LEDGER infused RESCUE_REPEAT_LOT {lid!r} recipient_outcomes "
                        f"contains invalid literal recipient_id key(s) {bad_od_keys!r}; "
                        "ancestry verification and cluster statistics nullified fail-closed."
                    )
                    ancestry_conflict = True
                else:
                    valid_od_keys_sorted = sorted(valid_od_keys)
                    bound_sets.append(("recipient_outcomes", valid_od_keys_sorted))
                    if resc_rid is not None and valid_od_keys_sorted != [resc_rid]:
                        malformed_cmc_rescue_errs.append(
                            f"CMC_RESCUE_RECIPIENT_BINDING_CONFLICT / CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: "
                            f"raw PARALLEL_CMC_READINESS_LEDGER infused RESCUE_REPEAT_LOT {lid!r} declares "
                            f"recipient_outcomes keys={valid_od_keys_sorted!r}, contradicting "
                            f"rescued_recipient_id={resc_rid!r}; ancestry verification and cluster statistics nullified fail-closed."
                        )
                        ancestry_conflict = True
                    elif resc_rid is None and len(valid_od_keys_sorted) != 1:
                        malformed_cmc_rescue_errs.append(
                            f"CMC_RESCUE_RECIPIENT_BINDING_CONFLICT / CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: "
                            f"raw PARALLEL_CMC_READINESS_LEDGER infused RESCUE_REPEAT_LOT {lid!r} declares "
                            f"recipient_outcomes keys={valid_od_keys_sorted!r} (expected exactly 1 rescued recipient); "
                            "ancestry verification and cluster statistics nullified fail-closed."
                        )
                        ancestry_conflict = True

        if raw_out_recs is not None:
            if not isinstance(raw_out_recs, list):
                malformed_cmc_rescue_errs.append(
                    f"CMC_RESCUE_RECIPIENT_BINDING_CONFLICT / CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: "
                    f"raw PARALLEL_CMC_READINESS_LEDGER infused RESCUE_REPEAT_LOT {lid!r} recipient_records must be a list; "
                    "ancestry verification and cluster statistics nullified fail-closed."
                )
                ancestry_conflict = True
            else:
                valid_rr_ids: list[str] = []
                rr_malformed = False
                for r_obj in raw_out_recs:
                    if not isinstance(r_obj, dict):
                        rr_malformed = True
                        continue
                    lr = _strict_literal_id(r_obj.get("recipient_id"))
                    if lr is None:
                        rr_malformed = True
                    else:
                        valid_rr_ids.append(lr)
                if rr_malformed or len(set(valid_rr_ids)) != len(valid_rr_ids):
                    malformed_cmc_rescue_errs.append(
                        f"CMC_RESCUE_RECIPIENT_BINDING_CONFLICT / CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: "
                        f"raw PARALLEL_CMC_READINESS_LEDGER infused RESCUE_REPEAT_LOT {lid!r} recipient_records "
                        "contains malformed or duplicate recipient_id entries; "
                        "ancestry verification and cluster statistics nullified fail-closed."
                    )
                    ancestry_conflict = True
                else:
                    valid_rr_sorted = sorted(valid_rr_ids)
                    bound_sets.append(("recipient_records", valid_rr_sorted))
                    if resc_rid is not None and valid_rr_sorted != [resc_rid]:
                        malformed_cmc_rescue_errs.append(
                            f"CMC_RESCUE_RECIPIENT_BINDING_CONFLICT / CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: "
                            f"raw PARALLEL_CMC_READINESS_LEDGER infused RESCUE_REPEAT_LOT {lid!r} declares "
                            f"recipient_records recipient_ids={valid_rr_sorted!r}, contradicting "
                            f"rescued_recipient_id={resc_rid!r}; ancestry verification and cluster statistics nullified fail-closed."
                        )
                        ancestry_conflict = True
                    elif resc_rid is None and len(valid_rr_sorted) != 1:
                        malformed_cmc_rescue_errs.append(
                            f"CMC_RESCUE_RECIPIENT_BINDING_CONFLICT / CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: "
                            f"raw PARALLEL_CMC_READINESS_LEDGER infused RESCUE_REPEAT_LOT {lid!r} declares "
                            f"recipient_records recipient_ids={valid_rr_sorted!r} (expected exactly 1 rescued recipient); "
                            "ancestry verification and cluster statistics nullified fail-closed."
                        )
                        ancestry_conflict = True

        if raw_rids is not None:
            if not isinstance(raw_rids, list):
                malformed_cmc_rescue_errs.append(
                    f"CMC_RESCUE_RECIPIENT_BINDING_CONFLICT / CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: "
                    f"raw PARALLEL_CMC_READINESS_LEDGER infused RESCUE_REPEAT_LOT {lid!r} recipient_ids must be a list; "
                    "ancestry verification and cluster statistics nullified fail-closed."
                )
                ancestry_conflict = True
            else:
                valid_rids_list: list[str] = []
                bad_rids_list: list[Any] = []
                for rk in raw_rids:
                    lr = _strict_literal_id(rk)
                    if lr is None:
                        bad_rids_list.append(rk)
                    else:
                        valid_rids_list.append(lr)
                if bad_rids_list or len(set(valid_rids_list)) != len(valid_rids_list):
                    malformed_cmc_rescue_errs.append(
                        f"CMC_RESCUE_RECIPIENT_BINDING_CONFLICT / CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: "
                        f"raw PARALLEL_CMC_READINESS_LEDGER infused RESCUE_REPEAT_LOT {lid!r} recipient_ids "
                        "contains invalid literal or duplicate recipient_id entries; "
                        "ancestry verification and cluster statistics nullified fail-closed."
                    )
                    ancestry_conflict = True
                else:
                    valid_rids_sorted = sorted(valid_rids_list)
                    bound_sets.append(("recipient_ids", valid_rids_sorted))
                    if resc_rid is not None and valid_rids_sorted != [resc_rid]:
                        malformed_cmc_rescue_errs.append(
                            f"CMC_RESCUE_RECIPIENT_BINDING_CONFLICT / CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: "
                            f"raw PARALLEL_CMC_READINESS_LEDGER infused RESCUE_REPEAT_LOT {lid!r} declares "
                            f"recipient_ids={valid_rids_sorted!r}, contradicting "
                            f"rescued_recipient_id={resc_rid!r}; ancestry verification and cluster statistics nullified fail-closed."
                        )
                        ancestry_conflict = True
                    elif resc_rid is None and len(valid_rids_sorted) != 1:
                        malformed_cmc_rescue_errs.append(
                            f"CMC_RESCUE_RECIPIENT_BINDING_CONFLICT / CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: "
                            f"raw PARALLEL_CMC_READINESS_LEDGER infused RESCUE_REPEAT_LOT {lid!r} declares "
                            f"recipient_ids={valid_rids_sorted!r} (expected exactly 1 rescued recipient); "
                            "ancestry verification and cluster statistics nullified fail-closed."
                        )
                        ancestry_conflict = True

        if len(bound_sets) >= 2 and len({tuple(vals) for _lbl, vals in bound_sets}) > 1:
            malformed_cmc_rescue_errs.append(
                f"CMC_RESCUE_RECIPIENT_BINDING_CONFLICT / CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: "
                f"raw PARALLEL_CMC_READINESS_LEDGER infused RESCUE_REPEAT_LOT {lid!r} has mutually contradictory "
                f"recipient bindings {bound_sets!r}; ancestry verification and cluster statistics nullified fail-closed."
            )
            ancestry_conflict = True

        if resc_rid is None:
            malformed_cmc_rescue_errs.append(
                f"CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: raw PARALLEL_CMC_READINESS_LEDGER infused "
                f"RESCUE_REPEAT_LOT {lid!r} is missing valid literal rescued_recipient_id."
            )
            ancestry_conflict = True
            continue
        if resc_rid not in seen_rids:
            non_cohort_cmc_rescues.append((resc_rid, lid))
            ancestry_conflict = True
            continue
        cmc_rescue_lots_by_rid.setdefault(resc_rid, []).append(lid)
        cmc_rescue_lineages_by_rid.setdefault(resc_rid, []).append((lid, mid, wid))

    for merr in sorted(set(malformed_cmc_rescue_errs)):
        if merr not in errs:
            errs.append(merr)
    for r_target, clid_r in sorted(non_cohort_cmc_rescues):
        nc_msg = (
            f"CMC_EXTRA_RESCUE_LOT_OMITTED_FROM_CLINICAL_COHORT: raw PARALLEL_CMC_READINESS_LEDGER "
            f"infused RESCUE_REPEAT_LOT {clid_r!r} references non-cohort recipient {r_target!r}."
        )
        if nc_msg not in errs:
            errs.append(nc_msg)

    for rid in sorted(seen_rids):
        cmeta = clinical_recipient_meta.get(rid)
        if cmeta is None:
            continue
        cmc_rescue_lots: list[str] = sorted(cmc_rescue_lots_by_rid.get(rid, []))
        cmc_rescue_lineages: list[tuple[str, str | None, str | None]] = sorted(
            cmc_rescue_lineages_by_rid.get(rid, []),
            key=repr,
        )

        if rid in duplicate_rids_set:
            dup_cmc_msg = (
                f"DUPLICATE_CLINICAL_RECIPIENT_INVALIDATES_CMC_RECONCILIATION: recipient {rid!r} "
                f"appears {len(raw_ancestry_claims_by_rid[rid])} times in clinical cohort "
                "(1:1 unique CMC reconciliation invalidated deterministically)."
            )
            if dup_cmc_msg not in errs:
                errs.append(dup_cmc_msg)
            dup_resc_errs_rid = duplicate_rescue_errors_by_rid.get(rid, [])
            for dup_resc_err in dup_resc_errs_rid:
                if dup_resc_err not in errs:
                    errs.append(dup_resc_err)
            if dup_resc_errs_rid:
                ancestry_conflict = True
                dup_rlids_sorted = sorted(
                    {
                        rlid_x
                        for rc_x in raw_rescue_claims_by_rid.get(rid, [])
                        for rlid_x in rc_x.get("rescue_lot_ids", ())
                    }
                )
                dup_rescue_lineages = sorted(
                    {
                        (rlid_x, ref_mcb_map.get(rlid_x), ref_wcb_map.get(rlid_x))
                        for rlid_x in dup_rlids_sorted
                    },
                    key=repr,
                )
                distinct_bank_lineages = {
                    (mcb_x, wcb_x) for _rl, mcb_x, wcb_x in dup_rescue_lineages
                }
                if len(distinct_bank_lineages) > 1 or any(
                    mcb_x is None for _rl, mcb_x, _wcb in dup_rescue_lineages
                ):
                    anc_resc_msg = (
                        f"CONFLICTING_DUPLICATE_RECIPIENT_RESCUE_ANCESTRY: duplicate clinical rows "
                        f"for recipient_id={rid!r} reference incompatible linked rescue lineages "
                        f"{dup_rescue_lineages!r}; ancestry verification and cluster statistics nullified fail-closed."
                    )
                    if anc_resc_msg not in errs:
                        errs.append(anc_resc_msg)

        rclaims_to_check = cmeta.get("all_raw_rescue_claims") or [{
            "intercurrent_event": cmeta["intercurrent_event"],
            "rescue_declared": cmeta["rescue_declared"],
            "rescue_lot_ids": tuple(cmeta["rescue_lot_ids"]),
            "explicit_rescue_ids_provided": cmeta["explicit_rescue_ids_provided"],
            "missing_explicit_rescue_lot_id": cmeta.get("missing_explicit_rescue_lot_id", False),
            "rescue_parse_error": cmeta["rescue_parse_error"],
        }]
        for rclaim_chk in rclaims_to_check:
            clin_rescue_lots: list[str] = list(rclaim_chk["rescue_lot_ids"])
            clin_rescue_lineages: list[tuple[str, str | None, str | None]] = sorted(
                [(rlid_c, ref_mcb_map.get(rlid_c), ref_wcb_map.get(rlid_c)) for rlid_c in clin_rescue_lots],
                key=repr,
            )
            if rclaim_chk["rescue_parse_error"]:
                err_rp = f"RESCUE_LOT_CARDINALITY_MISMATCH: recipient {rid!r} has invalid or conflicting clinical rescue declarations."
                if err_rp not in errs:
                    errs.append(err_rp)
            if not rclaim_chk["rescue_declared"]:
                if len(cmc_rescue_lots) > 0:
                    err_ex0 = (
                        f"CMC_EXTRA_RESCUE_LOT_OMITTED_FROM_CLINICAL_COHORT / RESCUE_LOT_CARDINALITY_MISMATCH: "
                        f"recipient {rid!r} has {len(cmc_rescue_lots)} infused CMC rescue lot(s) {cmc_rescue_lots!r} "
                        f"omitted from clinical cohort (clinical intercurrent_event={rclaim_chk['intercurrent_event']!r}, expected 0 rescue lots)."
                    )
                    if err_ex0 not in errs:
                        errs.append(err_ex0)
                    err_lin0 = (
                        f"CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: recipient {rid!r} has infused PARALLEL_CMC_READINESS_LEDGER "
                        f"rescue lot lineage(s) {cmc_rescue_lineages!r} omitted from clinical cohort "
                        f"(clinical intercurrent_event={rclaim_chk['intercurrent_event']!r}); ancestry verification and cluster statistics nullified fail-closed."
                    )
                    if err_lin0 not in errs:
                        errs.append(err_lin0)
                    ancestry_conflict = True
            elif rclaim_chk["explicit_rescue_ids_provided"]:
                if len(cmc_rescue_lots) == 0:
                    err_om1 = (
                        f"CLINICAL_RESCUE_OMITTED_FROM_CMC_LEDGER / RESCUE_LOT_CARDINALITY_MISMATCH: "
                        f"recipient {rid!r} declares clinical rescue lot(s) {clin_rescue_lots!r} with 0 "
                        "matching infused RESCUE_REPEAT_LOT records in PARALLEL_CMC_READINESS_LEDGER."
                    )
                    if err_om1 not in errs:
                        errs.append(err_om1)
                    err_lin1 = (
                        f"CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: recipient {rid!r} declares clinical rescue lot "
                        f"lineage(s) {clin_rescue_lineages!r} omitted from PARALLEL_CMC_READINESS_LEDGER infused rescue rows; "
                        "ancestry verification and cluster statistics nullified fail-closed."
                    )
                    if err_lin1 not in errs:
                        errs.append(err_lin1)
                    ancestry_conflict = True
                elif cmc_rescue_lots != clin_rescue_lots:
                    extra_cmc_resc = sorted((Counter(cmc_rescue_lots) - Counter(clin_rescue_lots)).elements())
                    missing_cmc_resc = sorted((Counter(clin_rescue_lots) - Counter(cmc_rescue_lots)).elements())
                    if extra_cmc_resc:
                        err_ex1 = (
                            f"CMC_EXTRA_RESCUE_LOT_OMITTED_FROM_CLINICAL_COHORT / RESCUE_LOT_CARDINALITY_MISMATCH: "
                            f"recipient {rid!r} raw PARALLEL_CMC_READINESS_LEDGER reports extra infused rescue lot(s) "
                            f"{extra_cmc_resc!r} omitted from clinical cohort "
                            f"(clinical={clin_rescue_lots!r} [n={len(clin_rescue_lots)}] vs cmc={cmc_rescue_lots!r} [n={len(cmc_rescue_lots)}])."
                        )
                        if err_ex1 not in errs:
                            errs.append(err_ex1)
                    if missing_cmc_resc:
                        err_ms1 = (
                            f"CLINICAL_RESCUE_LOT_ID_MISMATCH_IN_CMC_LEDGER / RESCUE_LOT_CARDINALITY_MISMATCH: "
                            f"recipient {rid!r} clinical rescue lot(s) {missing_cmc_resc!r} missing from "
                            f"PARALLEL_CMC_READINESS_LEDGER infused rescue lots "
                            f"(clinical={clin_rescue_lots!r} [n={len(clin_rescue_lots)}] vs cmc={cmc_rescue_lots!r} [n={len(cmc_rescue_lots)}])."
                        )
                        if err_ms1 not in errs:
                            errs.append(err_ms1)
                    err_lin2 = (
                        f"CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: recipient {rid!r} clinical rescue lot lineage(s) "
                        f"{clin_rescue_lineages!r} contradict PARALLEL_CMC_READINESS_LEDGER infused rescue lot lineage(s) "
                        f"{cmc_rescue_lineages!r}; ancestry verification and cluster statistics nullified fail-closed."
                    )
                    if err_lin2 not in errs:
                        errs.append(err_lin2)
                    ancestry_conflict = True
                elif cmc_rescue_lineages != clin_rescue_lineages:
                    err_lin_same = (
                        f"CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: recipient {rid!r} clinical/manifest rescue lot lineage(s) "
                        f"{clin_rescue_lineages!r} contradict PARALLEL_CMC_READINESS_LEDGER infused rescue lot lineage(s) "
                        f"{cmc_rescue_lineages!r} on matching rescue lot(s) {clin_rescue_lots!r}; "
                        "ancestry verification and cluster statistics nullified fail-closed."
                    )
                    if err_lin_same not in errs:
                        errs.append(err_lin_same)
                    ancestry_conflict = True
            else:
                # Exact rescue-lot identity is REQUIRED on every clinically declared rescue repeat infusion!
                err_miss_id = (
                    f"CLINICAL_RESCUE_MISSING_EXPLICIT_LOT_ID: recipient {rid!r} declares rescue repeat infusion "
                    f"(intercurrent_event={rclaim_chk['intercurrent_event']!r}) without an explicit clinical "
                    "rescue_lot_id / rescue_lot_ids (exact rescue-lot identity is required for CMC reconciliation)."
                )
                if err_miss_id not in errs:
                    errs.append(err_miss_id)
                if len(cmc_rescue_lots) == 0:
                    err_om2 = (
                        f"CLINICAL_RESCUE_OMITTED_FROM_CMC_LEDGER / RESCUE_LOT_CARDINALITY_MISMATCH: "
                        f"recipient {rid!r} has clinically declared rescue repeat infusion "
                        f"(intercurrent_event={rclaim_chk['intercurrent_event']!r}) with no matching infused "
                        "RESCUE_REPEAT_LOT record in PARALLEL_CMC_READINESS_LEDGER."
                    )
                    if err_om2 not in errs:
                        errs.append(err_om2)
                elif len(cmc_rescue_lots) != 1:
                    err_ex2 = (
                        f"CMC_EXTRA_RESCUE_LOT_OMITTED_FROM_CLINICAL_COHORT / RESCUE_LOT_CARDINALITY_MISMATCH: "
                        f"recipient {rid!r} declares unindexed clinical rescue while raw "
                        f"PARALLEL_CMC_READINESS_LEDGER reports {len(cmc_rescue_lots)} infused rescue lots "
                        f"{cmc_rescue_lots!r}; rescue events MUST declare exact matching clinical rescue_lot_id / rescue_lot_ids."
                    )
                    if err_ex2 not in errs:
                        errs.append(err_ex2)
                ancestry_conflict = True

    return errs, ancestry_conflict


def _audit_attested_raw_cmc_ledger_for_early_hold(
    cohort_payload: dict[str, Any],
    *,
    cohort_id: str | None,
    trusted_clinical_store: Any,
    manifest_mcb_norm: dict[str, str] | None,
    effective_wcb_manifest: dict[str, str],
    observed_wcb_to_mcbs: dict[str, set[str]],
    seen_rids: set[str],
    clinical_recipient_meta: dict[str, dict[str, Any]],
    raw_ancestry_claims_by_rid: dict[str, list[tuple[str | None, tuple[str, ...], tuple[str, ...], bool]]],
    raw_rescue_claims_by_rid: dict[str, list[dict[str, Any]]],
    duplicate_rids_set: set[str],
    duplicate_rescue_errors_by_rid: dict[str, list[str]],
) -> list[str]:
    """
    Resolve and audit any attested raw PARALLEL_CMC_READINESS_LEDGER in `trusted_clinical_store`
    against EVERY distinct Pass-0 primary-lot claim (and rescue claims / CMC validation) BEFORE
    returning on clinical hierarchy errors (such as CONFLICTING_DUPLICATE_RECIPIENT_ANCESTRY), so
    contradictory duplicate recipient rows can NEVER suppress CLINICAL_PRIMARY_LOT_CMC_DISPOSITION_CONFLICT
    or related raw CMC diagnostics.
    """
    if trusted_clinical_store is None:
        return []

    audit_errs: list[str] = []
    payload_cmc_sha, cmc_sha_errs = _resolve_payload_cmc_ledger_sha256(cohort_payload)
    for err_s in cmc_sha_errs:
        if err_s not in audit_errs:
            audit_errs.append(err_s)

    refs_raw = cohort_payload.get("clinical_store_refs")
    store_refs: dict[str, Any] = dict(refs_raw) if isinstance(refs_raw, dict) else {}

    source_att_cmc_sha: str | None = None
    s_ref = store_refs.get("source_verification_attestation_sha256")
    if s_ref is not None:
        srec, serr, _ssrc = _lookup_gate28a_trusted_record(
            trusted_clinical_store,
            category="source_verification_attestations",
            expected_sha256=s_ref,
            allowed_issuers=GATE_28A_ALLOWED_ATTESTATION_AUTHORITIES,
        )
        if serr is None and srec is not None:
            s_recomp = compute_gate28a_record_sha256(srec)
            s_cmc = srec.get("parallel_cmc_readiness_ledger_sha256")
            s_issuer = _strict_literal_id(srec.get("issuer_authority_id"))
            if (
                _is_valid_sha256_hex(srec.get("record_sha256"))
                and s_recomp == srec.get("record_sha256")
                and s_recomp == s_ref
                and srec.get("record_type") == "SOURCE_VERIFICATION_ATTESTATION"
                and (cohort_id is None or srec.get("cohort_id") == cohort_id)
                and s_issuer in GATE_28A_ALLOWED_ATTESTATION_AUTHORITIES
                and _is_valid_sha256_hex(s_cmc)
            ):
                source_att_cmc_sha = str(s_cmc)
                if payload_cmc_sha is not None and payload_cmc_sha != source_att_cmc_sha:
                    msg_sc = (
                        f"SOURCE_VERIFICATION_ATTESTATION parallel_cmc_readiness_ledger_sha256={source_att_cmc_sha} "
                        f"!= payload {payload_cmc_sha}."
                    )
                    if msg_sc not in audit_errs:
                        audit_errs.append(msg_sc)

    st_mcb: dict[str, str] | None = None
    st_eff_wcb: dict[str, str] = {}
    m_ref = store_refs.get("verified_lot_to_bank_manifest_sha256")
    if m_ref is not None:
        mrec, merr, _msrc = _lookup_gate28a_trusted_record(
            trusted_clinical_store,
            category="verified_lot_to_bank_manifests",
            expected_sha256=m_ref,
            allowed_issuers=GATE_28A_ALLOWED_ATTESTATION_AUTHORITIES,
        )
        if merr is None and mrec is not None:
            m_recomp = compute_gate28a_record_sha256(mrec)
            m_issuer = _strict_literal_id(mrec.get("issuer_authority_id"))
            if (
                _is_valid_sha256_hex(mrec.get("record_sha256"))
                and m_recomp == mrec.get("record_sha256")
                and m_recomp == m_ref
                and mrec.get("record_type") == "VERIFIED_LOT_TO_BANK_MANIFEST"
                and (cohort_id is None or mrec.get("cohort_id") == cohort_id)
                and m_issuer in GATE_28A_ALLOWED_ATTESTATION_AUTHORITIES
            ):
                cand_mcb, cand_wcb, _cand_wcb_pres, cand_man_errs = _merge_and_validate_bank_manifests(
                    mrec.get("lot_to_mcb_manifest"),
                    mrec.get("lot_to_wcb_manifest"),
                    mrec.get("lot_to_bank_manifest"),
                    context="VERIFIED_LOT_TO_BANK_MANIFEST",
                    extra_container=mrec,
                )
                if cand_mcb is not None and not cand_man_errs:
                    st_mcb = cand_mcb
                    st_eff_wcb = cand_wcb

    target_cmc_sha = payload_cmc_sha or source_att_cmc_sha
    if target_cmc_sha is None:
        return audit_errs

    cmc_bytes, cmc_err, _csrc = _lookup_gate28a_trusted_cmc_ledger_bytes(
        trusted_clinical_store,
        expected_sha256=target_cmc_sha,
        allowed_issuers=GATE_28A_ALLOWED_ATTESTATION_AUTHORITIES,
    )
    if cmc_err is not None or cmc_bytes is None:
        msg_ce = f"Trusted clinical store resolution failed for PARALLEL_CMC_READINESS_LEDGER: {cmc_err}."
        if msg_ce not in audit_errs:
            audit_errs.append(msg_ce)
        return audit_errs

    c_errs: list[str] = []
    try:
        cmc_doc = load_strict_json_bytes(cmc_bytes, "PARALLEL_CMC_READINESS_LEDGER")
    except Exception as exc:
        cmc_doc = None
        c_errs.append(
            f"PARALLEL_CMC_READINESS_LEDGER failed strict JSON decode (CMC_LEDGER_ANCESTRY_UNVERIFIABLE): {exc}"
        )
    if not isinstance(cmc_doc, dict):
        c_errs.append(
            "PARALLEL_CMC_READINESS_LEDGER payload must be a JSON object (CMC_LEDGER_ANCESTRY_UNVERIFIABLE)."
        )
    else:
        if cmc_doc.get("record_type") != "PARALLEL_CMC_READINESS_LEDGER":
            c_errs.append(f"Unexpected PARALLEL_CMC_READINESS_LEDGER record_type={cmc_doc.get('record_type')!r}.")
        if cohort_id is not None and cmc_doc.get("cohort_id") != cohort_id:
            c_errs.append(f"PARALLEL_CMC_READINESS_LEDGER cohort_id={cmc_doc.get('cohort_id')!r} != {cohort_id!r}.")
        c_issuer = _strict_literal_id(cmc_doc.get("issuer_authority_id"))
        if c_issuer not in GATE_28A_ALLOWED_ATTESTATION_AUTHORITIES:
            c_errs.append(
                f"PARALLEL_CMC_READINESS_LEDGER issuer_authority_id={cmc_doc.get('issuer_authority_id')!r} not in allowlist."
            )
        lot_ledger_raw = cmc_doc.get("lot_ledger")
        ref_mcb_map: dict[str, str] = st_mcb if st_mcb is not None else (manifest_mcb_norm or {})
        ref_wcb_map: dict[str, str] = st_eff_wcb if st_mcb is not None else effective_wcb_manifest

        raw_anc_errs, _raw_anc_conflict = _audit_raw_cmc_ledger_ancestry(
            lot_ledger_raw,
            ref_mcb_map=ref_mcb_map,
            ref_wcb_map=ref_wcb_map,
            observed_wcb_to_mcbs=observed_wcb_to_mcbs,
            clinical_recipient_meta=clinical_recipient_meta,
            raw_ancestry_claims_by_rid=raw_ancestry_claims_by_rid,
        )
        for aerr in raw_anc_errs:
            if aerr not in c_errs:
                c_errs.append(aerr)

        raw_resc_errs, _raw_resc_conflict = _reconcile_raw_clinical_and_cmc_rescues(
            lot_ledger_raw,
            seen_rids=seen_rids,
            clinical_recipient_meta=clinical_recipient_meta,
            raw_ancestry_claims_by_rid=raw_ancestry_claims_by_rid,
            raw_rescue_claims_by_rid=raw_rescue_claims_by_rid,
            duplicate_rids_set=duplicate_rids_set,
            duplicate_rescue_errors_by_rid=duplicate_rescue_errors_by_rid,
            ref_mcb_map=ref_mcb_map,
            ref_wcb_map=ref_wcb_map,
        )
        for rerr in raw_resc_errs:
            if rerr not in c_errs:
                c_errs.append(rerr)

        try:
            evaluate_cmc_attempted_lot_readiness(lot_ledger_raw)
        except CMCAncestryValidationError as exc:
            c_errs.append(
                f"PARALLEL_CMC_READINESS_LEDGER failed evaluate_cmc_attempted_lot_readiness "
                f"({exc.error_code}): {exc}"
            )
        except Exception as exc:
            c_errs.append(f"PARALLEL_CMC_READINESS_LEDGER failed evaluate_cmc_attempted_lot_readiness: {exc}")

    for cerr_item in c_errs:
        if cerr_item not in audit_errs:
            audit_errs.append(cerr_item)
    return audit_errs


GATE_28A_KNOWN_MANIFEST_RELATED_KEYS = frozenset({
    "lot_to_mcb_manifest",
    "lot_to_wcb_manifest",
    "lot_to_bank_manifest",
    "verified_lot_to_bank_manifest",
    "manifest_source_id",
})
GATE_28A_ALLOWED_MANIFEST_ENTRY_KEYS = frozenset({
    "mcb_id",
    "master_cell_bank_id",
    "bank_id",
    "wcb_id",
    "working_cell_bank_id",
})


def _find_extra_manifest_alias_keys(container: dict[str, Any] | None) -> dict[str, Any]:
    """Detect any unrecognized extra manifest/bank-map alias keys on a cohort payload or store manifest record."""
    if not isinstance(container, dict):
        return {}
    found: dict[str, Any] = {}
    for k, v in sorted(container.items(), key=lambda kv: str(kv[0])):
        if not isinstance(k, str) or v is None:
            continue
        if k in GATE_28A_KNOWN_MANIFEST_RELATED_KEYS or k.endswith("_sha256"):
            continue
        kl = k.lower()
        if "manifest" in kl or kl.endswith(("_bank_map", "_mcb_map", "_wcb_map", "_bank_mapping", "_mcb_mapping", "_wcb_mapping")):
            found[k] = v
    return found


def _normalize_lot_to_mcb_manifest(
    manifest_raw: Any,
    *,
    field_name: str = "lot_to_mcb_manifest",
) -> tuple[dict[str, str] | None, dict[str, str], list[str]]:
    """
    Validate strict 1-to-1 lot_id -> mcb_id (and optional embedded wcb_id) manifest mapping.
    Returns (lot_to_mcb_or_None, embedded_lot_to_wcb, errors).
    """
    errs: list[str] = []
    if not isinstance(manifest_raw, dict) or len(manifest_raw) == 0:
        return None, {}, [f"{field_name} must be a non-empty dict mapping every observed lot_id uniquely to its single mcb_id."]
    out_mcb: dict[str, str] = {}
    out_wcb: dict[str, str] = {}
    for k, v in manifest_raw.items():
        lid = _strict_literal_id(k)
        if lid is None:
            errs.append(f"{field_name} contains invalid lot_id key={k!r}.")
            continue
        if isinstance(v, str):
            mid = _strict_literal_id(v)
            if mid is None:
                errs.append(f"{field_name}[{lid!r}] has invalid mcb_id={v!r}.")
                continue
            out_mcb[lid] = mid
        elif isinstance(v, dict):
            extra_entry_keys = sorted(str(ek) for ek in v.keys() if ek not in GATE_28A_ALLOWED_MANIFEST_ENTRY_KEYS)
            if extra_entry_keys:
                errs.append(
                    f"UNRECOGNIZED_BANK_MANIFEST_ENTRY_KEY: {field_name}[{lid!r}] contains unsupported key(s) {extra_entry_keys!r}."
                )
            mid = _strict_literal_id(v.get("mcb_id"))
            if mid is None:
                errs.append(f"{field_name}[{lid!r}] missing valid literal mcb_id.")
                continue
            for mcb_alias in ("master_cell_bank_id", "bank_id"):
                if mcb_alias in v and v[mcb_alias] is not None:
                    amid = _strict_literal_id(v[mcb_alias])
                    if amid is None or amid != mid:
                        errs.append(
                            f"CONFLICTING_MCB_MANIFEST_ALIAS: {field_name}[{lid!r}].{mcb_alias}={v[mcb_alias]!r} "
                            f"contradicts mcb_id={mid!r}."
                        )
            wcb_raw = v.get("wcb_id")
            wcb_alias_raw = v.get("working_cell_bank_id")
            wid: str | None = None
            if wcb_raw is not None:
                wid = _strict_literal_id(wcb_raw)
                if wid is None:
                    errs.append(f"{field_name}[{lid!r}] has invalid literal wcb_id={wcb_raw!r}.")
                    continue
            if wcb_alias_raw is not None:
                waid = _strict_literal_id(wcb_alias_raw)
                if waid is None:
                    errs.append(f"{field_name}[{lid!r}] has invalid literal working_cell_bank_id={wcb_alias_raw!r}.")
                    continue
                if wid is not None and waid != wid:
                    errs.append(
                        f"CONFLICTING_WCB_MANIFEST_ALIAS: {field_name}[{lid!r}].working_cell_bank_id={waid!r} "
                        f"contradicts wcb_id={wid!r}."
                    )
                else:
                    wid = waid
            if wid is not None:
                out_wcb[lid] = wid
            out_mcb[lid] = mid
        else:
            errs.append(f"{field_name}[{lid!r}] must be a literal mcb_id string or dict with mcb_id.")
    if errs:
        return None, {}, errs
    return out_mcb, out_wcb, []


def _normalize_lot_to_wcb_manifest(
    wcb_manifest_raw: Any,
) -> tuple[dict[str, str] | None, list[str]]:
    """
    Validate optional top-level lot_to_wcb_manifest mapping lot_id -> strict literal wcb_id.
    Returns (None, []) when omitted (None); returns (None, errs) if non-dict, empty, or invalid;
    returns (normalized_dict, []) when valid.
    """
    if wcb_manifest_raw is None:
        return None, []
    if not isinstance(wcb_manifest_raw, dict) or len(wcb_manifest_raw) == 0:
        return None, ["lot_to_wcb_manifest must be a non-empty dict mapping lot_id uniquely to its literal wcb_id when supplied."]
    errs: list[str] = []
    out: dict[str, str] = {}
    for k, v in wcb_manifest_raw.items():
        lid = _strict_literal_id(k)
        if lid is None:
            errs.append(f"lot_to_wcb_manifest contains invalid lot_id key={k!r}.")
            continue
        wid = _strict_literal_id(v)
        if wid is None:
            errs.append(f"lot_to_wcb_manifest[{lid!r}] has invalid literal wcb_id={v!r}.")
            continue
        out[lid] = wid
    if errs:
        return None, errs
    return out, []


def _merge_and_validate_bank_manifests(
    mcb_raw: Any,
    wcb_raw: Any,
    bank_alias_raw: Any = None,
    *,
    context: str,
    extra_container: dict[str, Any] | None = None,
) -> tuple[dict[str, str] | None, dict[str, str], bool, list[str]]:
    """
    Unified manifest-alias normalizer and hierarchy validator across ALL supported manifest fields
    (lot_to_mcb_manifest, optional top-level lot_to_wcb_manifest, optional lot_to_bank_manifest alias,
    and detection of unrecognized extra manifest alias keys):
      1. Rejects unrecognized extra manifest alias keys fail-closed (UNRECOGNIZED_BANK_MANIFEST_ALIAS).
      2. Enforces exact agreement across overlapping MCB and WCB declarations BEFORE merging
         (CONFLICTING_BANK_MANIFEST_ALIASES / CONFLICTING_MCB_MANIFEST_ALIAS / CONFLICTING_WCB_MANIFEST_ALIAS).
      3. Rejects widening or partial/extra lot or WCB claims present solely in lot_to_bank_manifest
         that contradict or widen canonical lot_to_mcb_manifest / lot_to_wcb_manifest.
      4. Enforces strict global uniqueness of wcb_id -> mcb_id parentage across the COMBINED
         declarations from ALL aliases (every distinct literal wcb_id MUST map to at most ONE mcb_id;
         every lot with a WCB MUST have a known MCB parent).
    Returns (mcb_norm_or_None, effective_wcb_dict, any_wcb_present, errors).
    """
    errs: list[str] = []

    extra_aliases = _find_extra_manifest_alias_keys(extra_container)
    for ek in sorted(extra_aliases):
        errs.append(
            f"UNRECOGNIZED_BANK_MANIFEST_ALIAS: {context} contains unsupported manifest alias key {ek!r}; "
            "only canonical lot_to_mcb_manifest, lot_to_wcb_manifest, and exact-matching lot_to_bank_manifest are allowed."
        )

    mcb_norm, emb_wcb, mcb_errs = _normalize_lot_to_mcb_manifest(mcb_raw, field_name="lot_to_mcb_manifest")
    errs.extend(mcb_errs)
    wcb_norm, wcb_errs = _normalize_lot_to_wcb_manifest(wcb_raw)
    errs.extend(wcb_errs)

    alt_mcb: dict[str, str] | None = None
    alt_wcb: dict[str, str] = {}
    if bank_alias_raw is not None:
        alt_mcb, alt_wcb, alt_errs = _normalize_lot_to_mcb_manifest(bank_alias_raw, field_name="lot_to_bank_manifest")
        errs.extend(alt_errs)

    any_wcb_present = bool(emb_wcb) or (wcb_raw is not None) or bool(alt_wcb)
    canonical_wcb: dict[str, str] = dict(emb_wcb)

    # Pre-merge alias conflict check: inspect BOTH embedded and top-level WCB maps BEFORE merging!
    if wcb_norm is not None:
        for lid in sorted(wcb_norm):
            wid = wcb_norm[lid]
            if lid in canonical_wcb and canonical_wcb[lid] != wid:
                errs.append(
                    f"CONFLICTING_WCB_MANIFEST_ALIAS: {context} has contradictory wcb_id for lot_id={lid!r}: "
                    f"embedded lot_to_mcb_manifest={canonical_wcb[lid]!r} vs top-level lot_to_wcb_manifest={wid!r}."
                )
            else:
                canonical_wcb[lid] = wid

    effective_wcb: dict[str, str] = dict(canonical_wcb)

    # Unified lot_to_bank_manifest alias reconciliation: exact agreement on MCBs and zero widening/contradiction on WCBs!
    if bank_alias_raw is not None:
        if alt_mcb is not None and mcb_norm is not None:
            for lid in sorted(set(alt_mcb.keys()) & set(mcb_norm.keys())):
                if alt_mcb[lid] != mcb_norm[lid]:
                    errs.append(
                        f"CONFLICTING_BANK_MANIFEST_ALIASES / CONFLICTING_MCB_MANIFEST_ALIAS: {context} "
                        f"lot_to_bank_manifest[{lid!r}]={alt_mcb[lid]!r} contradicts lot_to_mcb_manifest[{lid!r}]={mcb_norm[lid]!r}."
                    )
            extra_mcb_lots = sorted(set(alt_mcb.keys()) - set(mcb_norm.keys()))
            missing_mcb_lots = sorted(set(mcb_norm.keys()) - set(alt_mcb.keys()))
            if extra_mcb_lots or missing_mcb_lots:
                errs.append(
                    f"CONFLICTING_BANK_MANIFEST_ALIASES: {context} lot_to_bank_manifest lot set contradicts or widens "
                    f"lot_to_mcb_manifest (extra={extra_mcb_lots!r}, missing={missing_mcb_lots!r})."
                )
        if alt_wcb:
            for lid_a in sorted(alt_wcb):
                wid_a = alt_wcb[lid_a]
                if lid_a in canonical_wcb and canonical_wcb[lid_a] != wid_a:
                    errs.append(
                        f"CONFLICTING_BANK_MANIFEST_ALIASES / CONFLICTING_WCB_MANIFEST_ALIAS: {context} "
                        f"lot_to_bank_manifest[{lid_a!r}] wcb_id={wid_a!r} contradicts canonical WCB={canonical_wcb[lid_a]!r}."
                    )
                elif lid_a not in canonical_wcb:
                    errs.append(
                        f"CONFLICTING_BANK_MANIFEST_ALIASES / CONFLICTING_WCB_MANIFEST_ALIAS: {context} "
                        f"lot_to_bank_manifest declares extra WCB entry lot_id={lid_a!r} -> wcb_id={wid_a!r} "
                        "absent from canonical lot_to_mcb_manifest / lot_to_wcb_manifest."
                    )
                    effective_wcb[lid_a] = wid_a
            omitted_wcb_lots = sorted(set(canonical_wcb.keys()) - set(alt_wcb.keys()))
            if omitted_wcb_lots:
                errs.append(
                    f"CONFLICTING_BANK_MANIFEST_ALIASES / CONFLICTING_WCB_MANIFEST_ALIAS: {context} "
                    f"lot_to_bank_manifest declares partial WCB entries omitting canonical WCB lots {omitted_wcb_lots!r}."
                )

    # Combined global WCB-to-MCB parentage uniqueness across ALL aliases (lot_to_mcb_manifest,
    # lot_to_wcb_manifest, AND lot_to_bank_manifest): every distinct literal wcb_id MUST descend
    # from at most ONE mcb_id across the combined declarations!
    combined_lot_to_mcbs: dict[str, set[str]] = {}
    for m_src in (mcb_norm, alt_mcb):
        if m_src is not None:
            for lid, mid in sorted(m_src.items()):
                combined_lot_to_mcbs.setdefault(lid, set()).add(mid)

    if combined_lot_to_mcbs and (emb_wcb or wcb_norm or alt_wcb):
        wcb_to_mcbs: dict[str, set[str]] = {}
        seen_pairs: set[tuple[str, str]] = set()
        for src_map in (emb_wcb, wcb_norm or {}, alt_wcb):
            for lid, wid in sorted(src_map.items()):
                if (lid, wid) in seen_pairs:
                    continue
                seen_pairs.add((lid, wid))
                if lid not in combined_lot_to_mcbs:
                    errs.append(
                        f"WCB_ORPHAN_LOT_WITHOUT_MCB_PARENT: {context} assigns wcb_id={wid!r} to lot_id={lid!r}, "
                        "which is absent from lot_to_mcb_manifest."
                    )
                else:
                    wcb_to_mcbs.setdefault(wid, set()).update(combined_lot_to_mcbs[lid])
        for wid, mcbs in sorted(wcb_to_mcbs.items()):
            if len(mcbs) > 1:
                errs.append(
                    f"NON_UNIQUE_WCB_PARENTAGE: {context} assigns literal wcb_id={wid!r} across multiple distinct "
                    f"MCBs {sorted(mcbs)} in combined manifest declarations (each distinct literal wcb_id must map to at most ONE mcb_id)."
                )

    return mcb_norm, effective_wcb, any_wcb_present, errs


_GATE28A_UNSET = object()


def _canonicalize_gate28a_value(val: Any) -> Any:
    """Injectively canonicalize values for Gate 28-A digest computation (equates int/float/Decimal numerically while preserving exact type distinctions across bool/None/str/num/dict/list)."""
    if type(val) is bool:
        return ["bool", val]
    if val is None:
        return ["null"]
    if isinstance(val, str):
        return ["str", val]
    if isinstance(val, (int, float, Decimal, Fraction)):
        d = _strict_decimal_in_range(val)
        if d is not None:
            return ["num", str(Fraction(d))]
        return ["nonfinite_num", type(val).__name__, repr(val)]
    if isinstance(val, dict):
        return [
            "dict",
            [[str(k), _canonicalize_gate28a_value(v)] for k, v in sorted(val.items(), key=lambda kv: str(kv[0]))],
        ]
    if isinstance(val, list):
        return ["list", [_canonicalize_gate28a_value(x) for x in val]]
    return ["other", type(val).__name__, repr(val)]


def _canonicalize_gate28a_presence_field(container: dict[str, Any], key: str) -> dict[str, Any]:
    """Injectively encode a decision-relevant field's presence/absence and typed canonical value."""
    if key in container:
        return {"present": True, "value": _canonicalize_gate28a_value(container[key])}
    return {"present": False}


def _canonicalize_gate28a_recipient(rec: dict[str, Any]) -> dict[str, Any]:
    """
    Canonicalize a Gate 28-A recipient dict before hashing:
      - Normalizes equivalent documented recipient WCB alias (`working_cell_bank_id` <-> `wcb_id`):
          * If ONLY `working_cell_bank_id` is non-None valid literal string (and `wcb_id` absent or None):
            canonicalizes to `"wcb_id": val` (omitting `working_cell_bank_id`).
          * If ONLY `wcb_id` is non-None valid literal string (and `working_cell_bank_id` absent or None):
            canonicalizes to `"wcb_id": val` (omitting `working_cell_bank_id`).
          * If BOTH `wcb_id` and `working_cell_bank_id` are non-None valid literal strings AND equal:
            canonicalizes to `"wcb_id": val` (dropping redundant matching `working_cell_bank_id`).
          * If EITHER is non-None with an invalid value (non-string, empty, or whitespace-padded) OR BOTH are
            present with CONFLICTING values: preserves BOTH raw keys untouched so conflicts ALWAYS alter
            `cohort_canonical_sha256` and fail closed!
    """
    normalized = dict(rec)
    has_wcb = "wcb_id" in normalized
    has_alias = "working_cell_bank_id" in normalized
    if has_wcb or has_alias:
        wcb_val = normalized.get("wcb_id")
        alias_val = normalized.get("working_cell_bank_id")
        wcb_non_none = has_wcb and (wcb_val is not None)
        alias_non_none = has_alias and (alias_val is not None)
        wcb_valid = _strict_literal_id(wcb_val) if wcb_non_none else None
        alias_valid = _strict_literal_id(alias_val) if alias_non_none else None

        if (not wcb_non_none) and (alias_valid is not None):
            normalized["wcb_id"] = alias_valid
            normalized.pop("working_cell_bank_id", None)
        elif (wcb_valid is not None) and (not alias_non_none):
            normalized["wcb_id"] = wcb_valid
            normalized.pop("working_cell_bank_id", None)
        elif (wcb_valid is not None) and (alias_valid is not None) and (wcb_valid == alias_valid):
            normalized["wcb_id"] = wcb_valid
            normalized.pop("working_cell_bank_id", None)
        # Conflicts (wcb_valid != alias_valid), invalid non-None values, or both-None keep raw keys untouched!

    return {
        str(k): _canonicalize_gate28a_value(v)
        for k, v in sorted(normalized.items(), key=lambda kv: str(kv[0]))
    }


def _resolve_payload_cmc_ledger_sha256(cohort_payload: dict[str, Any]) -> tuple[str | None, list[str]]:
    """Extract parallel_cmc_readiness_ledger_sha256 from payload/refs, rejecting any conflicting aliases."""
    errs: list[str] = []
    cands: list[tuple[str, Any]] = []
    if "parallel_cmc_readiness_ledger_sha256" in cohort_payload and cohort_payload["parallel_cmc_readiness_ledger_sha256"] is not None:
        cands.append(("parallel_cmc_readiness_ledger_sha256", cohort_payload["parallel_cmc_readiness_ledger_sha256"]))
    if "parallel_cmc_ledger_sha256" in cohort_payload and cohort_payload["parallel_cmc_ledger_sha256"] is not None:
        cands.append(("parallel_cmc_ledger_sha256", cohort_payload["parallel_cmc_ledger_sha256"]))
    refs = cohort_payload.get("clinical_store_refs")
    if isinstance(refs, dict) and refs.get("parallel_cmc_readiness_ledger_sha256") is not None:
        cands.append(("clinical_store_refs.parallel_cmc_readiness_ledger_sha256", refs["parallel_cmc_readiness_ledger_sha256"]))
    if not cands:
        return None, []
    first_val = cands[0][1]
    for lbl, val in cands[1:]:
        if val != first_val:
            errs.append(f"Conflicting {lbl}={val!r} vs {cands[0][0]}={first_val!r}.")
    if errs:
        return None, errs
    if not _is_valid_sha256_hex(first_val):
        return None, [f"Invalid 64-hex parallel_cmc_readiness_ledger_sha256={first_val!r}."]
    return str(first_val), []


def compute_gate28a_cohort_canonical_sha256(cohort_payload: dict[str, Any]) -> str:
    """
    Order-independent full canonical SHA-256 digest binding EVERY decision-relevant Gate 28-A declaration:
      - cohort_id
      - all 5 compatibility target declarations (product_class, transplant_site, disease_population,
        immunosuppression_protocol_class, dose_regimen)
      - includes_reichman
      - top-level decision-control flags (`primary_peer_reviewed_full_text_verified`,
        `parallel_cmc_readiness_ledger_disclosed`) with injective presence/absence tagging so adding,
        deleting, or toggling any control flag ALWAYS changes this digest and invalidates attestations
      - ICC inputs (rho_lot, rho_bank)
      - ALL supported manifest fields (lot_to_mcb_manifest, optional lot_to_wcb_manifest,
        optional lot_to_bank_manifest) AND any extra manifest alias keys
      - parallel_cmc_readiness_ledger_sha256 (preserving any alias conflict in the digest)
      - full canonical recipient ledger (preserving non-dict/non-list malformations, sorted by recipient_id)
    Semantic canonicalization: adding a matching top-level lot_to_wcb_manifest alongside identical nested WCB
    declarations inside lot_to_mcb_manifest AND replacing/adding a matching recipient `working_cell_bank_id`
    <-> `wcb_id` preserve semantic WCB ancestry identity and leave this digest invariant, whereas ANY semantic
    ancestry mutation, WCB alias conflict, invalid type, control-flag mutation/omission, widening, or
    post-attestation addition of lot_to_bank_manifest or unrecognized manifest alias keys alters this digest
    and fails closed.
    """
    recipients_raw = cohort_payload.get("recipients")
    if isinstance(recipients_raw, list):
        rec_items: list[tuple[int, str, str, Any]] = []
        for r in recipients_raw:
            if isinstance(r, dict):
                crec = _canonicalize_gate28a_recipient(r)
                cjson = json.dumps(crec, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
                rid_key = str(r.get("recipient_id", ""))
                rec_items.append((0, rid_key, cjson, ["rec", crec]))
            else:
                cval = _canonicalize_gate28a_value(r)
                cjson = json.dumps(cval, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
                rec_items.append((1, "", cjson, ["non_dict_rec", cval]))
        rec_items.sort(key=lambda item: (item[0], item[1], item[2]))
        norm_recs: Any = [item[3] for item in rec_items]
    else:
        norm_recs = ["non_list_recipients", _canonicalize_gate28a_value(recipients_raw)]

    mcb_raw = cohort_payload.get("lot_to_mcb_manifest")
    mcb_norm, emb_wcb, mcb_errs = _normalize_lot_to_mcb_manifest(mcb_raw, field_name="lot_to_mcb_manifest")
    wcb_raw = cohort_payload.get("lot_to_wcb_manifest")
    wcb_norm, wcb_errs = _normalize_lot_to_wcb_manifest(wcb_raw)
    if mcb_norm is not None and not mcb_errs:
        mcb_canon: Any = ["mcb_ok", dict(sorted(mcb_norm.items()))]
    else:
        mcb_canon = ["mcb_raw", _canonicalize_gate28a_value(mcb_raw)]
    if wcb_raw is None:
        wcb_canon: Any = ["wcb_ok", dict(sorted(emb_wcb.items()))] if emb_wcb else ["wcb_none"]
    elif wcb_norm is not None and not wcb_errs:
        has_wcb_conflict = any(lid in emb_wcb and emb_wcb[lid] != wid for lid, wid in wcb_norm.items())
        if has_wcb_conflict:
            wcb_canon = [
                "wcb_conflict",
                {
                    "embedded_wcb_manifest": dict(sorted(emb_wcb.items())),
                    "explicit_wcb_manifest": dict(sorted(wcb_norm.items())),
                },
            ]
        else:
            merged_wcb = dict(emb_wcb)
            merged_wcb.update(wcb_norm)
            wcb_canon = ["wcb_ok", dict(sorted(merged_wcb.items()))] if merged_wcb else ["wcb_none"]
    else:
        wcb_canon = ["wcb_raw", _canonicalize_gate28a_value(wcb_raw)]

    bank_alias_raw = cohort_payload.get("lot_to_bank_manifest")
    bank_alias_canon: Any = (
        ["bank_alias", _canonicalize_gate28a_value(bank_alias_raw)] if bank_alias_raw is not None else ["bank_alias_none"]
    )
    extra_aliases = _find_extra_manifest_alias_keys(cohort_payload)
    extra_aliases_canon: Any = (
        ["extra_aliases", _canonicalize_gate28a_value(extra_aliases)] if extra_aliases else ["extra_aliases_none"]
    )

    cmc_sha, cmc_sha_errs = _resolve_payload_cmc_ledger_sha256(cohort_payload)
    if cmc_sha_errs:
        refs_obj = cohort_payload.get("clinical_store_refs")
        cmc_sha_canon: Any = [
            "cmc_sha_error",
            {
                "parallel_cmc_readiness_ledger_sha256": _canonicalize_gate28a_presence_field(
                    cohort_payload, "parallel_cmc_readiness_ledger_sha256"
                ),
                "parallel_cmc_ledger_sha256": _canonicalize_gate28a_presence_field(
                    cohort_payload, "parallel_cmc_ledger_sha256"
                ),
                "clinical_store_refs_parallel_cmc_readiness_ledger_sha256": (
                    _canonicalize_gate28a_presence_field(refs_obj, "parallel_cmc_readiness_ledger_sha256")
                    if isinstance(refs_obj, dict)
                    else {"present": False}
                ),
            },
        ]
    elif cmc_sha is not None:
        cmc_sha_canon = ["cmc_sha_ok", cmc_sha]
    else:
        cmc_sha_canon = ["cmc_sha_none"]

    body = {
        "cohort_id": _canonicalize_gate28a_value(cohort_payload.get("cohort_id")),
        "compatibility_declarations": {
            k: _canonicalize_gate28a_value(cohort_payload.get(k))
            for k in sorted(GATE_28A_COMPATIBILITY_TARGET.keys())
        },
        "includes_reichman": _canonicalize_gate28a_value(cohort_payload.get("includes_reichman")),
        "primary_peer_reviewed_full_text_verified": _canonicalize_gate28a_presence_field(
            cohort_payload, "primary_peer_reviewed_full_text_verified"
        ),
        "parallel_cmc_readiness_ledger_disclosed": _canonicalize_gate28a_presence_field(
            cohort_payload, "parallel_cmc_readiness_ledger_disclosed"
        ),
        "rho_lot": _canonicalize_gate28a_value(cohort_payload.get("rho_lot", GATE_28A_RHO_LOT_MIN)),
        "rho_bank": _canonicalize_gate28a_value(cohort_payload.get("rho_bank", GATE_28A_RHO_BANK_MIN)),
        "lot_to_mcb_manifest": mcb_canon,
        "lot_to_wcb_manifest": wcb_canon,
        "lot_to_bank_manifest": bank_alias_canon,
        "extra_manifest_aliases": extra_aliases_canon,
        "parallel_cmc_readiness_ledger_sha256": cmc_sha_canon,
        "recipients": norm_recs,
    }
    return hashlib.sha256(
        json.dumps(body, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
    ).hexdigest()


def compute_gate28a_cohort_ledger_sha256(
    cohort_id_or_payload: str | dict[str, Any],
    recipients: list[dict[str, Any]] | None = None,
    lot_to_mcb_manifest: dict[str, Any] | None = None,
    *,
    lot_to_wcb_manifest: dict[str, Any] | None = None,
    lot_to_bank_manifest: dict[str, Any] | None = None,
    includes_reichman: bool = False,
    rho_lot: float | Decimal = GATE_28A_RHO_LOT_MIN,
    rho_bank: float | Decimal = GATE_28A_RHO_BANK_MIN,
    primary_peer_reviewed_full_text_verified: Any = _GATE28A_UNSET,
    parallel_cmc_readiness_ledger_disclosed: Any = _GATE28A_UNSET,
    parallel_cmc_readiness_ledger_sha256: str | None = None,
    compatibility_overrides: dict[str, Any] | None = None,
) -> str:
    """
    Compute the full canonical Gate 28-A attested cohort digest.
    Accepts either a full cohort_payload dict directly OR explicit arguments (binding compatibility
    declarations, includes_reichman, decision-control flags, rho_lot, rho_bank, manifests,
    parallel_cmc_readiness_ledger_sha256, and canonical recipients).
    """
    if isinstance(cohort_id_or_payload, dict):
        return compute_gate28a_cohort_canonical_sha256(cohort_id_or_payload)
    synth: dict[str, Any] = {
        "cohort_id": cohort_id_or_payload,
        **GATE_28A_COMPATIBILITY_TARGET,
        "includes_reichman": includes_reichman,
        "rho_lot": rho_lot,
        "rho_bank": rho_bank,
        "lot_to_mcb_manifest": lot_to_mcb_manifest,
        "lot_to_wcb_manifest": lot_to_wcb_manifest,
        "lot_to_bank_manifest": lot_to_bank_manifest,
        "parallel_cmc_readiness_ledger_sha256": parallel_cmc_readiness_ledger_sha256,
        "recipients": recipients or [],
    }
    if primary_peer_reviewed_full_text_verified is not _GATE28A_UNSET:
        synth["primary_peer_reviewed_full_text_verified"] = primary_peer_reviewed_full_text_verified
    if parallel_cmc_readiness_ledger_disclosed is not _GATE28A_UNSET:
        synth["parallel_cmc_readiness_ledger_disclosed"] = parallel_cmc_readiness_ledger_disclosed
    if compatibility_overrides:
        synth.update(compatibility_overrides)
    return compute_gate28a_cohort_canonical_sha256(synth)


def compute_gate28a_record_sha256(record: dict[str, Any]) -> str:
    """Canonical SHA-256 digest of a Gate 28-A store record excluding `record_sha256` and `attestation_sha256`."""
    body = {k: v for k, v in record.items() if k not in ("record_sha256", "attestation_sha256")}
    return hashlib.sha256(
        json.dumps(body, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
    ).hexdigest()


def compute_gate28a_attestation_sha256(attestation: dict[str, Any]) -> str:
    """Canonical SHA-256 digest of a Gate 28-A attestation excluding `attestation_sha256` and `record_sha256`."""
    return compute_gate28a_record_sha256(attestation)


def build_gate28a_prespecification_attestation(
    *,
    cohort_id: str,
    cohort_canonical_sha256: str,
    protocol_or_sap_id: str = "SAP-GATE28A-2026-V1",
    prespecified_before_unblinding: bool = True,
    single_compatible_cohort_confirmed: bool = True,
    issuer_authority_id: str = "OPENISLET_CLINICAL_ADJUDICATION_BOARD_V1",
) -> dict[str, Any]:
    """Build a SHA-256-authenticated PRESPECIFICATION_ATTESTATION record bound to cohort_id and full cohort_canonical_sha256."""
    rec: dict[str, Any] = {
        "record_type": "PRESPECIFICATION_ATTESTATION",
        "cohort_id": cohort_id,
        "cohort_canonical_sha256": cohort_canonical_sha256,
        "cohort_ledger_sha256": cohort_canonical_sha256,
        "protocol_or_sap_id": protocol_or_sap_id,
        "prespecified_before_unblinding": prespecified_before_unblinding,
        "single_compatible_cohort_confirmed": single_compatible_cohort_confirmed,
        "issuer_authority_id": issuer_authority_id,
    }
    digest = compute_gate28a_record_sha256(rec)
    rec["record_sha256"] = digest
    rec["attestation_sha256"] = digest
    return rec


def build_gate28a_source_verification_attestation(
    *,
    cohort_id: str,
    cohort_canonical_sha256: str,
    parallel_cmc_readiness_ledger_sha256: str,
    primary_source_citation_id: str = "PMID:99999999",
    primary_peer_reviewed_full_text_verified: bool = True,
    parallel_cmc_readiness_ledger_disclosed: bool = True,
    issuer_authority_id: str = "OPENISLET_CLINICAL_ADJUDICATION_BOARD_V1",
) -> dict[str, Any]:
    """Build a SHA-256-authenticated SOURCE_VERIFICATION_ATTESTATION record bound to full cohort_canonical_sha256 and CMC ledger SHA-256."""
    rec: dict[str, Any] = {
        "record_type": "SOURCE_VERIFICATION_ATTESTATION",
        "cohort_id": cohort_id,
        "cohort_canonical_sha256": cohort_canonical_sha256,
        "cohort_ledger_sha256": cohort_canonical_sha256,
        "primary_source_citation_id": primary_source_citation_id,
        "primary_peer_reviewed_full_text_verified": primary_peer_reviewed_full_text_verified,
        "parallel_cmc_readiness_ledger_disclosed": parallel_cmc_readiness_ledger_disclosed,
        "parallel_cmc_readiness_ledger_sha256": parallel_cmc_readiness_ledger_sha256,
        "parallel_cmc_ledger_sha256": parallel_cmc_readiness_ledger_sha256,
        "issuer_authority_id": issuer_authority_id,
    }
    digest = compute_gate28a_record_sha256(rec)
    rec["record_sha256"] = digest
    rec["attestation_sha256"] = digest
    return rec


def build_gate28a_verified_lot_to_bank_manifest(
    *,
    cohort_id: str,
    lot_to_mcb_manifest: dict[str, str],
    lot_to_wcb_manifest: dict[str, str] | None = None,
    manifest_source_id: str = "QA-BANK-MANIFEST-2026-V1",
    issuer_authority_id: str = "OPENISLET_QA_RELEASE_BOARD_V1",
) -> dict[str, Any]:
    """Build a SHA-256-authenticated VERIFIED_LOT_TO_BANK_MANIFEST store record."""
    mcb_norm, eff_wcb, any_wcb, man_errs = _merge_and_validate_bank_manifests(
        lot_to_mcb_manifest,
        lot_to_wcb_manifest,
        context="VERIFIED_LOT_TO_BANK_MANIFEST",
    )
    if man_errs or mcb_norm is None:
        raise ValueError(f"Invalid lot/bank manifest for store record: {man_errs}")
    merged_wcb: dict[str, str] | None = dict(sorted(eff_wcb.items())) if (any_wcb and eff_wcb) else None
    rec: dict[str, Any] = {
        "record_type": "VERIFIED_LOT_TO_BANK_MANIFEST",
        "cohort_id": cohort_id,
        "manifest_source_id": manifest_source_id,
        "issuer_authority_id": issuer_authority_id,
        "lot_to_mcb_manifest": dict(sorted(mcb_norm.items())),
        "lot_to_wcb_manifest": merged_wcb,
    }
    rec["record_sha256"] = compute_gate28a_record_sha256(rec)
    return rec


def build_gate28a_parallel_cmc_ledger_bytes(
    *,
    cohort_id: str,
    lot_ledger: list[dict[str, Any]],
    issuer_authority_id: str = "OPENISLET_QA_RELEASE_BOARD_V1",
) -> tuple[bytes, str]:
    """Build canonical UTF-8 payload bytes and exact SHA-256 for a PARALLEL_CMC_READINESS_LEDGER store artifact."""
    payload_obj = {
        "record_type": "PARALLEL_CMC_READINESS_LEDGER",
        "cohort_id": cohort_id,
        "issuer_authority_id": issuer_authority_id,
        "lot_ledger": copy.deepcopy(lot_ledger),
    }
    raw_bytes = (json.dumps(payload_obj, indent=2, sort_keys=True, ensure_ascii=False) + "\n").encode("utf-8")
    return raw_bytes, sha256_bytes(raw_bytes)


def write_gate28a_trusted_clinical_store(
    store_path: pathlib.Path | str,
    *,
    prespecification_attestations: list[dict[str, Any]] | None = None,
    source_verification_attestations: list[dict[str, Any]] | None = None,
    verified_lot_to_bank_manifests: list[dict[str, Any]] | None = None,
    parallel_cmc_readiness_ledgers: list[bytes | dict[str, Any]] | None = None,
    store_authority_id: str = "OPENISLET_CLINICAL_ADJUDICATION_BOARD_V1",
) -> pathlib.Path:
    """
    Persist Gate 28-A clinical attestations, verified lot->bank manifests, and raw PARALLEL_CMC_READINESS_LEDGER
    payload bytes into an independent external trusted clinical store (JSON registry file OR directory layout).
    """
    sp = pathlib.Path(store_path)
    prespecs = list(prespecification_attestations or [])
    sources = list(source_verification_attestations or [])
    manifests = list(verified_lot_to_bank_manifests or [])
    cmc_items = list(parallel_cmc_readiness_ledgers or [])

    for rec in prespecs + sources + manifests:
        if not isinstance(rec, dict) or not _is_valid_sha256_hex(rec.get("record_sha256")):
            raise ValueError("Every JSON record written to trusted_clinical_store must carry a valid 64-hex record_sha256")

    cmc_bytes_pairs: list[tuple[str, bytes]] = []
    for item in cmc_items:
        if isinstance(item, bytes):
            rb = item
        elif isinstance(item, dict):
            rb = (json.dumps(item, indent=2, sort_keys=True, ensure_ascii=False) + "\n").encode("utf-8")
        else:
            raise ValueError("parallel_cmc_readiness_ledgers items must be bytes or dict")
        cmc_bytes_pairs.append((sha256_bytes(rb), rb))

    if sp.suffix.lower() == ".json":
        if sp.is_file():
            doc = load_strict_json_bytes(sp.read_bytes(), f"trusted_clinical_store:{sp.name}")
        else:
            doc = {
                "schema_version": TRUSTED_CLINICAL_STORE_SCHEMA_VERSION,
                "store_authority_id": store_authority_id,
                "prespecification_attestations": {},
                "source_verification_attestations": {},
                "verified_lot_to_bank_manifests": {},
                "parallel_cmc_readiness_ledgers": {},
            }
        for rec in prespecs:
            doc.setdefault("prespecification_attestations", {})[rec["record_sha256"]] = copy.deepcopy(rec)
        for rec in sources:
            doc.setdefault("source_verification_attestations", {})[rec["record_sha256"]] = copy.deepcopy(rec)
        for rec in manifests:
            doc.setdefault("verified_lot_to_bank_manifests", {})[rec["record_sha256"]] = copy.deepcopy(rec)
        for digest, rb in cmc_bytes_pairs:
            doc.setdefault("parallel_cmc_readiness_ledgers", {})[digest] = {
                "payload_sha256": digest,
                "raw_payload_utf8": rb.decode("utf-8"),
            }
        sp.parent.mkdir(parents=True, exist_ok=True)
        sp.write_text(json.dumps(doc, indent=2, sort_keys=True, ensure_ascii=False) + "\n", encoding="utf-8")
        return sp

    # Directory store layout
    for sub in (
        "prespecification_attestations",
        "source_verification_attestations",
        "verified_lot_to_bank_manifests",
        "parallel_cmc_readiness_ledgers",
    ):
        (sp / sub).mkdir(parents=True, exist_ok=True)
    meta_file = sp / "store_metadata.json"
    if not meta_file.is_file():
        meta_file.write_text(
            json.dumps(
                {"schema_version": TRUSTED_CLINICAL_STORE_SCHEMA_VERSION, "store_authority_id": store_authority_id},
                indent=2,
                sort_keys=True,
            ) + "\n",
            encoding="utf-8",
        )
    for rec in prespecs:
        (sp / "prespecification_attestations" / f"{rec['record_sha256']}.json").write_text(
            json.dumps(rec, indent=2, sort_keys=True, ensure_ascii=False) + "\n", encoding="utf-8"
        )
    for rec in sources:
        (sp / "source_verification_attestations" / f"{rec['record_sha256']}.json").write_text(
            json.dumps(rec, indent=2, sort_keys=True, ensure_ascii=False) + "\n", encoding="utf-8"
        )
    for rec in manifests:
        (sp / "verified_lot_to_bank_manifests" / f"{rec['record_sha256']}.json").write_text(
            json.dumps(rec, indent=2, sort_keys=True, ensure_ascii=False) + "\n", encoding="utf-8"
        )
    for digest, rb in cmc_bytes_pairs:
        (sp / "parallel_cmc_readiness_ledgers" / f"{digest}.json").write_bytes(rb)
    return sp


def _lookup_gate28a_trusted_record(
    store_path: pathlib.Path | str | None,
    *,
    category: str,
    expected_sha256: Any,
    allowed_issuers: frozenset[str] | set[str],
) -> tuple[dict[str, Any] | None, str | None, str | None]:
    """Resolve a Gate 28-A JSON record STRICTLY from an independent external trusted_clinical_store."""
    if store_path is None:
        return None, "trusted_clinical_store not provided", None
    if not isinstance(store_path, (pathlib.Path, str)):
        return None, "trusted_clinical_store has invalid path type", None
    sp = pathlib.Path(store_path)
    if not sp.exists():
        return None, f"trusted_clinical_store path missing: {sp.name}", f"missing:{sp.name}"
    if not _is_valid_sha256_hex(expected_sha256):
        return None, f"Invalid 64-hex reference digest for {category}: {expected_sha256!r}", f"store:{sp.name}"

    try:
        if sp.is_file():
            doc = load_strict_json_bytes(sp.read_bytes(), f"trusted_clinical_store:{sp.name}")
            if not isinstance(doc, dict):
                return None, "Trusted clinical store registry JSON must be an object", f"registry_file:{sp.name}"
            if doc.get("schema_version") != TRUSTED_CLINICAL_STORE_SCHEMA_VERSION:
                return None, f"Trusted clinical store schema_version mismatch: {doc.get('schema_version')!r}", f"registry_file:{sp.name}"
            if _strict_literal_id(doc.get("store_authority_id")) not in allowed_issuers:
                return None, f"Trusted clinical store authority {doc.get('store_authority_id')!r} not in allowlist", f"registry_file:{sp.name}"
            bucket = doc.get(category)
            if not isinstance(bucket, dict):
                return None, f"Trusted clinical store missing bucket {category!r}", f"registry_file:{sp.name}"
            rec = bucket.get(expected_sha256)
            if not isinstance(rec, dict):
                return None, f"Record {expected_sha256[:16]}... not found in trusted clinical store bucket {category!r}", f"registry_file:{sp.name}"
            return rec, None, f"registry_file:{sp.name}"

        if sp.is_dir():
            meta_file = sp / "store_metadata.json"
            if meta_file.is_file():
                meta = load_strict_json_bytes(meta_file.read_bytes(), "store_metadata.json")
                if (
                    not isinstance(meta, dict)
                    or meta.get("schema_version") != TRUSTED_CLINICAL_STORE_SCHEMA_VERSION
                    or _strict_literal_id(meta.get("store_authority_id")) not in allowed_issuers
                ):
                    return None, "Trusted clinical store directory store_metadata.json failed authority/schema verification", "store_dir"
            elif (sp / "registry.json").is_file():
                return _lookup_gate28a_trusted_record(
                    sp / "registry.json",
                    category=category,
                    expected_sha256=expected_sha256,
                    allowed_issuers=allowed_issuers,
                )
            else:
                return None, "Trusted clinical store directory missing store_metadata.json", "store_dir"
            rec_file = sp / category / f"{expected_sha256}.json"
            if not rec_file.is_file():
                return None, f"Record {expected_sha256[:16]}... not found in trusted clinical store dir {category!r}", "store_dir"
            rec = load_strict_json_bytes(rec_file.read_bytes(), rec_file.name)
            if not isinstance(rec, dict):
                return None, f"Trusted clinical store record {rec_file.name} is not a JSON object", "store_dir"
            return rec, None, "store_dir"
    except Exception as exc:
        return None, f"Failed reading trusted clinical store ({type(exc).__name__}): {exc}", f"unreadable:{sp.name}"

    return None, "Unsupported trusted_clinical_store path type", f"unsupported:{sp.name}"


def _lookup_gate28a_trusted_cmc_ledger_bytes(
    store_path: pathlib.Path | str | None,
    *,
    expected_sha256: Any,
    allowed_issuers: frozenset[str] | set[str],
) -> tuple[bytes | None, str | None, str | None]:
    """Resolve raw PARALLEL_CMC_READINESS_LEDGER payload bytes strictly from trusted_clinical_store and verify byte SHA-256."""
    if store_path is None:
        return None, "trusted_clinical_store not provided", None
    if not isinstance(store_path, (pathlib.Path, str)):
        return None, "trusted_clinical_store has invalid path type", None
    sp = pathlib.Path(store_path)
    if not sp.exists():
        return None, f"trusted_clinical_store path missing: {sp.name}", f"missing:{sp.name}"
    if not _is_valid_sha256_hex(expected_sha256):
        return None, f"Invalid 64-hex parallel_cmc_readiness_ledger_sha256={expected_sha256!r}", f"store:{sp.name}"

    try:
        if sp.is_file():
            doc = load_strict_json_bytes(sp.read_bytes(), f"trusted_clinical_store:{sp.name}")
            if not isinstance(doc, dict):
                return None, "Trusted clinical store registry JSON must be an object", f"registry_file:{sp.name}"
            if doc.get("schema_version") != TRUSTED_CLINICAL_STORE_SCHEMA_VERSION:
                return None, f"Trusted clinical store schema_version mismatch: {doc.get('schema_version')!r}", f"registry_file:{sp.name}"
            if _strict_literal_id(doc.get("store_authority_id")) not in allowed_issuers:
                return None, f"Trusted clinical store authority {doc.get('store_authority_id')!r} not in allowlist", f"registry_file:{sp.name}"
            bucket = doc.get("parallel_cmc_readiness_ledgers")
            if not isinstance(bucket, dict):
                return None, "Trusted clinical store missing bucket 'parallel_cmc_readiness_ledgers'", f"registry_file:{sp.name}"
            entry = bucket.get(expected_sha256)
            if not isinstance(entry, dict) or not isinstance(entry.get("raw_payload_utf8"), str):
                return None, f"PARALLEL_CMC_READINESS_LEDGER bytes {expected_sha256[:16]}... not found in trusted clinical store", f"registry_file:{sp.name}"
            raw_b = entry["raw_payload_utf8"].encode("utf-8")
            if entry.get("payload_sha256") is not None and entry.get("payload_sha256") != expected_sha256:
                return None, "Stored PARALLEL_CMC_READINESS_LEDGER payload_sha256 mismatch", f"registry_file:{sp.name}"
            if sha256_bytes(raw_b) != expected_sha256:
                return None, "Stored PARALLEL_CMC_READINESS_LEDGER raw bytes SHA-256 verification failed", f"registry_file:{sp.name}"
            return raw_b, None, f"registry_file:{sp.name}"

        if sp.is_dir():
            meta_file = sp / "store_metadata.json"
            if meta_file.is_file():
                meta = load_strict_json_bytes(meta_file.read_bytes(), "store_metadata.json")
                if (
                    not isinstance(meta, dict)
                    or meta.get("schema_version") != TRUSTED_CLINICAL_STORE_SCHEMA_VERSION
                    or _strict_literal_id(meta.get("store_authority_id")) not in allowed_issuers
                ):
                    return None, "Trusted clinical store directory store_metadata.json failed authority/schema verification", "store_dir"
            elif (sp / "registry.json").is_file():
                return _lookup_gate28a_trusted_cmc_ledger_bytes(
                    sp / "registry.json",
                    expected_sha256=expected_sha256,
                    allowed_issuers=allowed_issuers,
                )
            else:
                return None, "Trusted clinical store directory missing store_metadata.json", "store_dir"
            rec_file = sp / "parallel_cmc_readiness_ledgers" / f"{expected_sha256}.json"
            if not rec_file.is_file():
                return None, f"PARALLEL_CMC_READINESS_LEDGER file {expected_sha256[:16]}... not found in store_dir", "store_dir"
            raw_b = rec_file.read_bytes()
            if sha256_bytes(raw_b) != expected_sha256:
                return None, "Stored PARALLEL_CMC_READINESS_LEDGER raw file SHA-256 verification failed", "store_dir"
            return raw_b, None, "store_dir"
    except Exception as exc:
        return None, f"Failed reading trusted clinical store CMC ledger ({type(exc).__name__}): {exc}", f"unreadable:{sp.name}"

    return None, "Unsupported trusted_clinical_store path type", f"unsupported:{sp.name}"


def _derive_reconciling_cmc_lot_ledger_from_recipients(
    recipients: list[dict[str, Any]],
    lot_to_mcb_manifest: dict[str, str],
    lot_to_wcb_manifest: dict[str, str] | None = None,
) -> list[dict[str, Any]]:
    """Derive a valid, reconciling single/split-lot CMC readiness ledger from a clinical recipient list."""
    by_lot: dict[str, list[dict[str, Any]]] = {}
    for rec in recipients:
        by_lot.setdefault(str(rec["lot_id"]), []).append(rec)

    wcb_map = dict(lot_to_wcb_manifest or {})
    lot_ledger: list[dict[str, Any]] = []
    rescue_idx = 0
    for lid in sorted(by_lot):
        lot_recs = by_lot[lid]
        mcb_id = lot_to_mcb_manifest.get(lid, str(lot_recs[0]["mcb_id"]))
        lot_wcb: str | None = wcb_map.get(lid)
        if lot_wcb is None:
            for rec_w in lot_recs:
                w_cand = rec_w.get("wcb_id") if rec_w.get("wcb_id") is not None else rec_w.get("working_cell_bank_id")
                if isinstance(w_cand, str) and w_cand:
                    lot_wcb = w_cand
                    break
        outcomes: dict[str, int] = {}
        rids: list[str] = []
        rescued_in_lot: list[tuple[str, list[str] | None]] = []
        for rec in sorted(lot_recs, key=lambda x: str(x["recipient_id"])):
            rid = str(rec["recipient_id"])
            ie = str(rec.get("intercurrent_event", "NONE"))
            met_c2b = bool(rec.get("met_c2b_criteria", False))
            fu_d = _strict_decimal_in_range(rec.get("followup_months", 0), min_val=Decimal("0"))
            fu_ge_6 = (fu_d is not None) and (Fraction(fu_d) >= Fraction(6, 1))
            raw_rlids = rec.get("rescue_lot_ids")
            has_rlid_list = isinstance(raw_rlids, list) and len(raw_rlids) > 0
            resc_flag = (
                ie == "RESCUE_REPEAT_INFUSION"
                or rec.get("rescue_infusion_occurred") is True
                or rec.get("rescue_lot_id") is not None
                or has_rlid_list
            )
            outc = 1 if (ie == "NONE" and not resc_flag and met_c2b and fu_ge_6) else 0
            outcomes[rid] = outc
            rids.append(rid)
            if resc_flag:
                if has_rlid_list:
                    rlids_clean = [str(x) for x in raw_rlids if isinstance(x, str) and x]
                    rescued_in_lot.append((rid, rlids_clean if rlids_clean else None))
                else:
                    rlid_raw = rec.get("rescue_lot_id")
                    rlid_str = str(rlid_raw) if isinstance(rlid_raw, str) and rlid_raw else None
                    rescued_in_lot.append((rid, [rlid_str] if rlid_str is not None else None))
        lt = "SINGLE_RECIPIENT" if len(lot_recs) == 1 else "SPLIT_LOT"
        lot_row: dict[str, Any] = {
            "lot_id": lid,
            "mcb_id": mcb_id,
            "lot_type": lt,
            "disposition": "RELEASED_INFUSED",
            "planned_doses_n": len(lot_recs),
            "infused_doses_n": len(lot_recs),
            "c2b_responder_doses_n": sum(outcomes.values()),
            "recipient_ids": rids,
            "recipient_outcomes": outcomes,
        }
        if lot_wcb is not None:
            lot_row["wcb_id"] = lot_wcb
        lot_ledger.append(lot_row)
        for rrid, explicit_rlids in rescued_in_lot:
            target_rlids = explicit_rlids if explicit_rlids is not None else [None]
            for explicit_rlid in target_rlids:
                rescue_idx += 1
                rlid_final = explicit_rlid or f"RESCUE-{lid}-{rescue_idx:03d}"
                resc_row: dict[str, Any] = {
                    "lot_id": rlid_final,
                    "mcb_id": lot_to_mcb_manifest.get(rlid_final, mcb_id),
                    "lot_type": "RESCUE_REPEAT_LOT",
                    "disposition": "RELEASED_INFUSED",
                    "planned_doses_n": 1,
                    "infused_doses_n": 1,
                    "c2b_responder_doses_n": 1,
                    "recipient_ids": [rrid],
                    "recipient_outcomes": {rrid: 1},
                    "rescued_recipient_id": rrid,
                    "rescued_primary_lot_id": lid,
                }
                if rlid_final in wcb_map:
                    resc_row["wcb_id"] = wcb_map[rlid_final]
                lot_ledger.append(resc_row)
    return lot_ledger


def build_valid_gate28a_reference_bundle(
    store_path: pathlib.Path | str,
    recipients: list[dict[str, Any]],
    *,
    cohort_id: str = "COHORT-GATE28A-REF-001",
    lot_to_mcb_manifest: dict[str, Any] | None = None,
    lot_to_wcb_manifest: dict[str, str] | None = None,
    parallel_cmc_lot_ledger: list[dict[str, Any]] | None = None,
    protocol_or_sap_id: str = "SAP-GATE28A-2026-V1",
    primary_source_citation_id: str = "PMID:99999999",
    manifest_source_id: str = "QA-BANK-MANIFEST-2026-V1",
    issuer_authority_id: str = "OPENISLET_CLINICAL_ADJUDICATION_BOARD_V1",
    store_authority_id: str = "OPENISLET_CLINICAL_ADJUDICATION_BOARD_V1",
    **overrides: Any,
) -> tuple[dict[str, Any], dict[str, Any]]:
    """
    Build a complete, contract-valid Gate 28-A cohort payload AND write all 4 independently stored records
    (PRESPECIFICATION_ATTESTATION, SOURCE_VERIFICATION_ATTESTATION, VERIFIED_LOT_TO_BANK_MANIFEST, and
    raw PARALLEL_CMC_READINESS_LEDGER bytes) into `store_path`.
    Returns (cohort_payload_without_inline_attestations, store_records_dict).
    """
    if lot_to_mcb_manifest is None:
        mcb_map: dict[str, str] = {}
        derived_wcb_map: dict[str, str] = {}
        for rec in recipients:
            lid = str(rec["lot_id"])
            if lid not in mcb_map:
                mcb_map[lid] = str(rec["mcb_id"])
            wid = rec.get("wcb_id") if rec.get("wcb_id") is not None else rec.get("working_cell_bank_id")
            if wid is not None and lid not in derived_wcb_map:
                derived_wcb_map[lid] = str(wid)
        eff_derive_wcb = lot_to_wcb_manifest if lot_to_wcb_manifest is not None else (derived_wcb_map or None)
        cmc_ledger_list = (
            copy.deepcopy(parallel_cmc_lot_ledger)
            if parallel_cmc_lot_ledger is not None
            else _derive_reconciling_cmc_lot_ledger_from_recipients(recipients, mcb_map, lot_to_wcb_manifest=eff_derive_wcb)
        )
        # Ensure all clinically infused CMC lots (primary/split AND rescue lots) carry verified manifest ancestry!
        for cmc_row in cmc_ledger_list:
            if cmc_row.get("disposition") == "RELEASED_INFUSED":
                clid = str(cmc_row["lot_id"])
                if clid not in mcb_map:
                    mcb_map[clid] = str(cmc_row["mcb_id"])
                cwid = cmc_row.get("wcb_id") if cmc_row.get("wcb_id") is not None else cmc_row.get("working_cell_bank_id")
                if cwid is not None and clid not in derived_wcb_map:
                    derived_wcb_map[clid] = str(cwid)
        payload_mcb_manifest: dict[str, Any] = dict(sorted(mcb_map.items()))
        payload_wcb_manifest: dict[str, str] | None = (
            copy.deepcopy(lot_to_wcb_manifest)
            if lot_to_wcb_manifest is not None
            else (dict(sorted(derived_wcb_map.items())) if derived_wcb_map else None)
        )
    else:
        payload_mcb_manifest = copy.deepcopy(lot_to_mcb_manifest)
        mcb_norm_tmp, emb_wcb_tmp, _ = _normalize_lot_to_mcb_manifest(payload_mcb_manifest)
        mcb_map = dict(mcb_norm_tmp or {})
        if lot_to_wcb_manifest is not None:
            payload_wcb_manifest = copy.deepcopy(lot_to_wcb_manifest)
        elif emb_wcb_tmp:
            payload_wcb_manifest = dict(sorted(emb_wcb_tmp.items()))
        else:
            payload_wcb_manifest = None
        cmc_ledger_list = (
            copy.deepcopy(parallel_cmc_lot_ledger)
            if parallel_cmc_lot_ledger is not None
            else _derive_reconciling_cmc_lot_ledger_from_recipients(
                recipients, mcb_map, lot_to_wcb_manifest=payload_wcb_manifest
            )
        )
    cmc_raw_bytes, cmc_sha = build_gate28a_parallel_cmc_ledger_bytes(
        cohort_id=cohort_id,
        lot_ledger=cmc_ledger_list,
        issuer_authority_id=issuer_authority_id,
    )

    payload: dict[str, Any] = {
        "cohort_id": cohort_id,
        **GATE_28A_COMPATIBILITY_TARGET,
        "includes_reichman": False,
        "rho_lot": GATE_28A_RHO_LOT_MIN,
        "rho_bank": GATE_28A_RHO_BANK_MIN,
        "primary_peer_reviewed_full_text_verified": True,
        "parallel_cmc_readiness_ledger_disclosed": True,
        "parallel_cmc_readiness_ledger_sha256": cmc_sha,
        "lot_to_mcb_manifest": payload_mcb_manifest,
        "recipients": copy.deepcopy(recipients),
    }
    if payload_wcb_manifest is not None:
        payload["lot_to_wcb_manifest"] = payload_wcb_manifest
    payload.update(overrides)

    canon_sha = compute_gate28a_cohort_canonical_sha256(payload)
    prespec_rec = build_gate28a_prespecification_attestation(
        cohort_id=str(payload["cohort_id"]),
        cohort_canonical_sha256=canon_sha,
        protocol_or_sap_id=protocol_or_sap_id,
        issuer_authority_id=issuer_authority_id,
    )
    source_rec = build_gate28a_source_verification_attestation(
        cohort_id=str(payload["cohort_id"]),
        cohort_canonical_sha256=canon_sha,
        parallel_cmc_readiness_ledger_sha256=cmc_sha,
        primary_source_citation_id=primary_source_citation_id,
        issuer_authority_id=issuer_authority_id,
    )
    manifest_rec = build_gate28a_verified_lot_to_bank_manifest(
        cohort_id=str(payload["cohort_id"]),
        lot_to_mcb_manifest=mcb_map,
        lot_to_wcb_manifest=payload_wcb_manifest,
        manifest_source_id=manifest_source_id,
        issuer_authority_id=issuer_authority_id,
    )

    write_gate28a_trusted_clinical_store(
        store_path,
        prespecification_attestations=[prespec_rec],
        source_verification_attestations=[source_rec],
        verified_lot_to_bank_manifests=[manifest_rec],
        parallel_cmc_readiness_ledgers=[cmc_raw_bytes],
        store_authority_id=store_authority_id,
    )

    payload["clinical_store_refs"] = {
        "prespecification_attestation_sha256": prespec_rec["record_sha256"],
        "source_verification_attestation_sha256": source_rec["record_sha256"],
        "verified_lot_to_bank_manifest_sha256": manifest_rec["record_sha256"],
        "parallel_cmc_readiness_ledger_sha256": cmc_sha,
    }
    store_records = {
        "prespecification_attestation": prespec_rec,
        "source_verification_attestation": source_rec,
        "verified_lot_to_bank_manifest": manifest_rec,
        "parallel_cmc_readiness_ledger_bytes": cmc_raw_bytes,
        "parallel_cmc_readiness_ledger_sha256": cmc_sha,
        "cohort_canonical_sha256": canon_sha,
    }
    return payload, store_records


def build_valid_gate28a_cohort_payload(
    recipients: list[dict[str, Any]],
    *,
    cohort_id: str = "COHORT-GATE28A-REF-001",
    lot_to_mcb_manifest: dict[str, Any] | None = None,
    lot_to_wcb_manifest: dict[str, str] | None = None,
    protocol_or_sap_id: str = "SAP-GATE28A-2026-V1",
    primary_source_citation_id: str = "PMID:99999999",
    parallel_cmc_ledger_sha256: str = "a1b2c3d4e5f60718293a4b5c6d7e8f90123456789abcdef0123456789abcdef0",
    issuer_authority_id: str = "OPENISLET_CLINICAL_ADJUDICATION_BOARD_V1",
    **overrides: Any,
) -> dict[str, Any]:
    """
    Build a full-digest-bound inline Gate 28-A payload (useful for diagnostic inspection and negative
    self-attested-inline rejection tests; CANNOT authorize promotion without trusted_clinical_store!).
    """
    if lot_to_mcb_manifest is None:
        manifest: dict[str, Any] = {}
        derived_wcb: dict[str, str] = {}
        for rec in recipients:
            lid = rec["lot_id"]
            mid = rec["mcb_id"]
            if lid not in manifest:
                manifest[lid] = mid
            wid = rec.get("wcb_id") if rec.get("wcb_id") is not None else rec.get("working_cell_bank_id")
            if wid is not None and lid not in derived_wcb:
                derived_wcb[lid] = wid
        wcb_manifest = copy.deepcopy(lot_to_wcb_manifest) if lot_to_wcb_manifest is not None else (derived_wcb or None)
    else:
        manifest = copy.deepcopy(lot_to_mcb_manifest)
        wcb_manifest = copy.deepcopy(lot_to_wcb_manifest) if lot_to_wcb_manifest is not None else None

    payload: dict[str, Any] = {
        "cohort_id": cohort_id,
        **GATE_28A_COMPATIBILITY_TARGET,
        "includes_reichman": False,
        "rho_lot": GATE_28A_RHO_LOT_MIN,
        "rho_bank": GATE_28A_RHO_BANK_MIN,
        "primary_peer_reviewed_full_text_verified": True,
        "parallel_cmc_readiness_ledger_disclosed": True,
        "parallel_cmc_readiness_ledger_sha256": parallel_cmc_ledger_sha256,
        "lot_to_mcb_manifest": manifest,
        "recipients": copy.deepcopy(recipients),
    }
    if wcb_manifest is not None:
        payload["lot_to_wcb_manifest"] = wcb_manifest
    payload.update(overrides)

    canon_sha = compute_gate28a_cohort_canonical_sha256(payload)
    payload["prespecification_attestation"] = build_gate28a_prespecification_attestation(
        cohort_id=str(payload["cohort_id"]),
        cohort_canonical_sha256=canon_sha,
        protocol_or_sap_id=protocol_or_sap_id,
        issuer_authority_id=issuer_authority_id,
    )
    payload["source_verification_attestation"] = build_gate28a_source_verification_attestation(
        cohort_id=str(payload["cohort_id"]),
        cohort_canonical_sha256=canon_sha,
        parallel_cmc_readiness_ledger_sha256=str(payload.get("parallel_cmc_readiness_ledger_sha256") or parallel_cmc_ledger_sha256),
        primary_source_citation_id=primary_source_citation_id,
        issuer_authority_id=issuer_authority_id,
    )
    return payload


def evaluate_gate28a_h1_promotion(
    cohort_payload: dict[str, Any],
    *,
    trusted_clinical_store: pathlib.Path | str | None = None,
) -> dict[str, Any]:
    """
    Executable bank/lot-aware Gate 28-A clinical H1 promotion evaluator (fail-closed):
      1. Enforces the exact prespecified single compatibility target (allogeneic GMP SC-islet,
         intraportal hepatic site, T1D, de novo chronic glucocorticoid-free systemic IS,
         full-dose single infusion). Full-dose split-lot recipients are eligible 1:1 with single-lot
         ancestry; pooled multi-lot courses are excluded from primary single-lot promotion.
      2. Enforces 1:1 unique recipients and STRICT functional lot -> MCB (and verified lot_to_wcb_manifest
         whenever ANY recipient declares wcb_id) hierarchy with ZERO fallback to unverified recipient rows:
         missing, empty, invalid, incomplete, conflicting, or mismatched manifests IMMEDIATELY return
         lot_bank_hierarchy_valid=False, deff=None, n_eff=None, k_eff=None, promotion_authorized=False.
      3. Requires resolving ALL FOUR authenticated records from an independent external `trusted_clinical_store`
         (NEVER trusting self-attested inline caller dicts or bare booleans; operational deployment dependency:
         independent QA/clinical governance custody, verified external store provenance, write-restricted
         access policy, and separation of duties):
           (a) PRESPECIFICATION_ATTESTATION bound to exact cohort_id + full cohort_canonical_sha256
               (binding cohort_id, all 5 compatibility declarations, includes_reichman, rho_lot, rho_bank,
               manifests, parallel_cmc_readiness_ledger_sha256, and full canonical recipients),
           (b) SOURCE_VERIFICATION_ATTESTATION bound to exact cohort_id + full cohort_canonical_sha256 +
               parallel_cmc_readiness_ledger_sha256,
           (c) VERIFIED_LOT_TO_BANK_MANIFEST matching payload MCB (and WCB) manifests,
           (d) Raw PARALLEL_CMC_READINESS_LEDGER bytes whose SHA-256 matches, passes
               evaluate_cmc_attempted_lot_readiness(...), contains zero pooled multi-lot courses, and
               reconciles infused clinical recipient IDs/lots/MCBs/rescue status/outcomes against the cohort.
      4. Enforces ONE unified deterministic intercurrent-event adjudication table (rescue repeat infusion = 0,
         prohibited peri-infusion systemic glucocorticoids = 0 in the primary glucocorticoid-free H1 estimand,
         missingness/LTFU = 0, pre-landmark death = 0, primary graft non-function = 0).
      5. Enforces structural manufacturing diversity floors (distinct_gmp_lots_n >= 3, distinct_mcb_n >= 2,
         max_single_lot_share <= 0.40 via exact context-independent Fraction) AND evaluates BOTH non-overlapping
         posteriors (Uniform Beta(1,1) P(H1>=0.90) >= 0.90 AND non-Reichman anchored Beta(8.8,1.2)
         P(H1>=0.90) >= 0.85) on cluster-adjusted (k_eff, n_eff).
    """
    if not isinstance(cohort_payload, dict):
        return {
            "status": "HOLD_H1_AT_88PCT",
            "promotion_authorized": False,
            "external_clinical_store_verified": False,
            "lot_bank_hierarchy_valid": False,
            "lot_to_mcb_manifest_verified": False,
            "lot_to_wcb_manifest_verified": False,
            "prespecification_attestation_verified": False,
            "source_verification_attestation_verified": False,
            "parallel_cmc_ledger_verified": False,
            "icc_sensitivity_report_attached": False,
            "icc_sensitivity_report": None,
            "boundary_sensitive_under_high_icc": False,
            "icc_sensitivity_review_status": None,
            "deff": None,
            "n_eff": None,
            "k_eff": None,
            "trusted_clinical_store_deployment_dependency": TRUSTED_CLINICAL_STORE_DEPLOYMENT_DEPENDENCY,
            "failure_reasons": ["cohort_payload must be a dict"],
        }

    failure_reasons: list[str] = []
    cohort_canonical_sha256 = compute_gate28a_cohort_canonical_sha256(cohort_payload)

    cohort_id = _strict_literal_id(cohort_payload.get("cohort_id"))
    if cohort_id is None:
        failure_reasons.append(f"Missing or invalid literal cohort_id={cohort_payload.get('cohort_id')!r}.")

    for field, expected in GATE_28A_COMPATIBILITY_TARGET.items():
        actual = _strict_literal_id(cohort_payload.get(field))
        if actual != expected:
            failure_reasons.append(f"Compatibility target mismatch for {field}: got {cohort_payload.get(field)!r}, expected {expected!r}.")

    includes_reichman = cohort_payload.get("includes_reichman")
    if type(includes_reichman) is not bool:
        failure_reasons.append("includes_reichman must be explicit strict bool.")
    elif includes_reichman is True:
        failure_reasons.append("Cohort includes Reichman 2025 recipients; non-overlapping Beta(8.8, 1.2) requires a non-Reichman compatible cohort.")

    if "primary_peer_reviewed_full_text_verified" in cohort_payload:
        pdf_ok = cohort_payload.get("primary_peer_reviewed_full_text_verified")
        if type(pdf_ok) is not bool or pdf_ok is not True:
            failure_reasons.append("primary_peer_reviewed_full_text_verified must be strict bool True when supplied.")

    if "parallel_cmc_readiness_ledger_disclosed" in cohort_payload:
        cmc_ok = cohort_payload.get("parallel_cmc_readiness_ledger_disclosed")
        if type(cmc_ok) is not bool or cmc_ok is not True:
            failure_reasons.append("parallel_cmc_readiness_ledger_disclosed must be strict bool True when supplied.")

    icc_domain_invalid = False
    rho_lot_raw = cohort_payload.get("rho_lot", GATE_28A_RHO_LOT_MIN)
    rho_bank_raw = cohort_payload.get("rho_bank", GATE_28A_RHO_BANK_MIN)
    rho_lot_dec = _strict_decimal_in_range(rho_lot_raw, min_val=Decimal("0"), max_val=Decimal("1"))
    rho_bank_dec = _strict_decimal_in_range(rho_bank_raw, min_val=Decimal("0"), max_val=Decimal("1"))
    if rho_lot_dec is None or Fraction(rho_lot_dec) < Fraction(Decimal(str(GATE_28A_RHO_LOT_MIN))):
        failure_reasons.append(
            f"INVALID_ICC_DOMAIN: rho_lot={rho_lot_raw!r} invalid or below prespecified conservative floor {GATE_28A_RHO_LOT_MIN}."
        )
        rho_lot = GATE_28A_RHO_LOT_MIN
        icc_domain_invalid = True
    else:
        rho_lot = float(rho_lot_dec)
    if rho_bank_dec is None or Fraction(rho_bank_dec) < Fraction(Decimal(str(GATE_28A_RHO_BANK_MIN))):
        failure_reasons.append(
            f"INVALID_ICC_DOMAIN: rho_bank={rho_bank_raw!r} invalid or below prespecified conservative floor {GATE_28A_RHO_BANK_MIN}."
        )
        rho_bank = GATE_28A_RHO_BANK_MIN
        icc_domain_invalid = True
    else:
        rho_bank = float(rho_bank_dec)
    if (
        rho_lot_dec is not None
        and rho_bank_dec is not None
        and (Fraction(rho_lot_dec) + Fraction(rho_bank_dec)) > Fraction(1, 1)
    ):
        failure_reasons.append(
            f"INVALID_ICC_SUM_EXCEEDS_ONE: separate variance-component ICC shares require 0 <= rho_lot, "
            f"0 <= rho_bank, and rho_lot + rho_bank <= 1.0 (got rho_lot={rho_lot_raw!r}, "
            f"rho_bank={rho_bank_raw!r}, sum={float(Fraction(rho_lot_dec) + Fraction(rho_bank_dec)):.6f} > 1.0)."
        )
        icc_domain_invalid = True

    recipients = cohort_payload.get("recipients")
    if not isinstance(recipients, list) or len(recipients) == 0:
        failure_reasons.append("recipients must be a non-empty list of unique recipient records.")
        return {
            "status": "HOLD_H1_AT_88PCT",
            "promotion_authorized": False,
            "external_clinical_store_verified": False,
            "cohort_id": cohort_id,
            "cohort_canonical_sha256": cohort_canonical_sha256,
            "cohort_ledger_sha256": cohort_canonical_sha256,
            "lot_bank_hierarchy_valid": False,
            "lot_to_mcb_manifest_verified": False,
            "lot_to_wcb_manifest_verified": False,
            "prespecification_attestation_verified": False,
            "source_verification_attestation_verified": False,
            "parallel_cmc_ledger_verified": False,
            "icc_sensitivity_report_attached": False,
            "icc_sensitivity_report": None,
            "boundary_sensitive_under_high_icc": False,
            "icc_sensitivity_review_status": None,
            "deff": None,
            "n_eff": None,
            "k_eff": None,
            "trusted_clinical_store_deployment_dependency": TRUSTED_CLINICAL_STORE_DEPLOYMENT_DEPENDENCY,
            "failure_reasons": failure_reasons,
        }

    hierarchy_errors: list[str] = []
    manifest_raw = cohort_payload.get("lot_to_mcb_manifest")
    wcb_manifest_raw = cohort_payload.get("lot_to_wcb_manifest")
    bank_alias_raw = cohort_payload.get("lot_to_bank_manifest")
    manifest_mcb_norm, effective_wcb_manifest, payload_wcb_present, manifest_errs = _merge_and_validate_bank_manifests(
        manifest_raw,
        wcb_manifest_raw,
        bank_alias_raw,
        context="cohort payload",
        extra_container=cohort_payload,
    )
    hierarchy_errors.extend(manifest_errs)

    seen_rids: set[str] = set()
    lot_ids: list[str] = []
    observed_lot_to_mcbs: dict[str, set[str]] = {}
    observed_lot_to_wcbs: dict[str, set[str | None]] = {}
    observed_wcb_to_mcbs: dict[str, set[str]] = {}
    raw_ancestry_claims_by_rid: dict[str, list[tuple[str | None, tuple[str, ...], tuple[str, ...], bool]]] = {}
    raw_rescue_claims_by_rid: dict[str, list[dict[str, Any]]] = {}
    pass0_valid_ancestry_rows: list[tuple[str, str, str, str, str | None]] = []
    pass1_valid_rows: list[tuple[str, str, str, str, dict[str, Any], dict[str, Any]]] = []
    clinical_recipient_meta: dict[str, dict[str, Any]] = {}
    clinical_adjudicated_by_rid: dict[str, int] = {}
    any_recipient_wcb_declared = False
    primary_responders = 0
    secondary_steroid_exposed_c2b = 0
    ie_counts: dict[str, int] = {k: 0 for k in GATE_28A_INTERCURRENT_EVENT_ADJUDICATION}

    # PASS 0 — UNCONDITIONAL RAW CLINICAL ANCESTRY & RESCUE EXTRACTION OVER EVERY ROW IN `recipients`
    # Executes BEFORE any follow-up, endpoint, intercurrent-event, or duplicate-recipient skipping so that:
    #   (a) conflicting duplicate clinical recipient rows are ALWAYS detected on BOTH primary ancestry
    #       (CONFLICTING_DUPLICATE_RECIPIENT_ANCESTRY) AND raw rescue declarations
    #       (CONFLICTING_DUPLICATE_RECIPIENT_RESCUE), order-independently across all row permutations,
    #   (b) recipients with missing/invalid followup_months, met_c2b_criteria, or intercurrent_event STILL populate
    #       clinical_recipient_meta and observed lot/MCB/WCB sets for manifest & raw-CMC cross-reconciliation
    #       on BOTH the normal CMC path AND the CMC exception/error-path audit!
    for idx, rec in enumerate(recipients):
        if not isinstance(rec, dict):
            failure_reasons.append(f"Recipient[{idx}] must be a dict.")
            hierarchy_errors.append(f"Recipient[{idx}] invalid structure; lot/bank ancestry unverifiable.")
            continue

        for ek, ev in sorted(rec.items(), key=lambda kv: str(kv[0])):
            if ev is None or not isinstance(ek, str) or ek in CMC_LEDGER_KNOWN_BANK_KEYS:
                continue
            ek_lo = ek.lower()
            if any(tok in ek_lo for tok in ("mcb", "wcb", "cell_bank", "bank_id")):
                msg = (
                    f"UNRECOGNIZED_BANK_ALIAS in cohort recipient[{idx}]: unsupported bank key {ek!r}."
                )
                failure_reasons.append(msg)
                hierarchy_errors.append(msg)

        rid = _strict_literal_id(rec.get("recipient_id"))
        lid = _strict_literal_id(rec.get("lot_id"))
        mid = _strict_literal_id(rec.get("mcb_id"))
        row_ancestry_valid = True
        if rid is None or lid is None or mid is None:
            msg = f"Recipient[{idx}] missing literal recipient_id, lot_id, or mcb_id."
            failure_reasons.append(msg)
            hierarchy_errors.append(msg)
            row_ancestry_valid = False

        row_mcbs: set[str] = {mid} if mid is not None else set()
        for mcb_alias in ("master_cell_bank_id", "bank_id"):
            if mcb_alias in rec and rec[mcb_alias] is not None:
                amid = _strict_literal_id(rec[mcb_alias])
                if amid is None or (mid is not None and amid != mid):
                    msg = (
                        f"CONFLICTING_MCB_ALIAS in cohort recipient {rid if rid is not None else f'[{idx}]'!r} "
                        f"(lot_id={lid!r}): {mcb_alias}={rec[mcb_alias]!r} contradicts mcb_id={mid!r}."
                    )
                    failure_reasons.append(msg)
                    hierarchy_errors.append(msg)
                if amid is not None:
                    row_mcbs.add(amid)

        has_wcb = "wcb_id" in rec and rec["wcb_id"] is not None
        wid: str | None = None
        row_wcbs: set[str] = set()
        wcb_invalid = False
        if has_wcb:
            any_recipient_wcb_declared = True
            wid = _strict_literal_id(rec.get("wcb_id"))
            if wid is None:
                msg = f"Recipient {rid if rid is not None else f'[{idx}]'!r} has invalid literal wcb_id={rec.get('wcb_id')!r}."
                failure_reasons.append(msg)
                hierarchy_errors.append(msg)
                wcb_invalid = True
            else:
                row_wcbs.add(wid)
        wcb_alias_raw = rec.get("working_cell_bank_id")
        if wcb_alias_raw is not None:
            any_recipient_wcb_declared = True
            waid = _strict_literal_id(wcb_alias_raw)
            if waid is None:
                msg = (
                    f"Recipient {rid if rid is not None else f'[{idx}]'!r} has invalid literal "
                    f"working_cell_bank_id={wcb_alias_raw!r}."
                )
                failure_reasons.append(msg)
                hierarchy_errors.append(msg)
                wcb_invalid = True
            else:
                row_wcbs.add(waid)
                if wid is not None and waid != wid:
                    msg = (
                        f"CONFLICTING_WCB_ALIAS in cohort recipient {rid if rid is not None else f'[{idx}]'!r} "
                        f"(lot_id={lid!r}): working_cell_bank_id={waid!r} contradicts wcb_id={wid!r}."
                    )
                    failure_reasons.append(msg)
                    hierarchy_errors.append(msg)
                elif wid is None:
                    wid = waid

        if lid is not None and row_mcbs:
            observed_lot_to_mcbs.setdefault(lid, set()).update(row_mcbs)
            if row_wcbs:
                observed_lot_to_wcbs.setdefault(lid, set()).update(row_wcbs)
                for rw in row_wcbs:
                    observed_wcb_to_mcbs.setdefault(rw, set()).update(row_mcbs)
            elif not wcb_invalid:
                observed_lot_to_wcbs.setdefault(lid, set()).add(None)

        if rid is not None:
            raw_ancestry_claims_by_rid.setdefault(rid, []).append(
                (lid, tuple(sorted(row_mcbs)), tuple(sorted(row_wcbs)), wcb_invalid)
            )
            rclaim_raw = _parse_raw_clinical_rescue_declaration(rec, repr(rid))
            raw_rescue_claims_by_rid.setdefault(rid, []).append(rclaim_raw)
            if rid is not None and lid is not None and mid is not None:
                canon_rec_key = json.dumps(
                    _canonicalize_gate28a_recipient(rec),
                    sort_keys=True,
                    ensure_ascii=False,
                    separators=(",", ":"),
                )
                if row_ancestry_valid and not wcb_invalid:
                    pass0_valid_ancestry_rows.append((rid, canon_rec_key, lid, mid, wid))
                pass1_valid_rows.append((rid, canon_rec_key, lid, mid, rec, rclaim_raw))

    # Populate clinical_recipient_meta in canonical (rid, canon_rec_key) order so downstream
    # inspection is 100% invariant to recipient row ordering even on duplicate recipient rows.
    for rid_a, _canon_a, lid_a, mid_a, wid_a in sorted(
        pass0_valid_ancestry_rows, key=lambda item: (item[0], item[1])
    ):
        if rid_a not in clinical_recipient_meta:
            clinical_recipient_meta[rid_a] = {
                "lot_id": lid_a,
                "mcb_id": mid_a,
                "wcb_id": wid_a,
                "intercurrent_event": None,
                "rescue_declared": False,
                "rescue_lot_id": None,
                "rescue_lot_ids": [],
                "explicit_rescue_ids_provided": False,
                "missing_explicit_rescue_lot_id": False,
                "rescue_parse_error": False,
                "all_raw_rescue_claims": [],
            }

    duplicate_rids_set: set[str] = set()
    duplicate_rescue_errors_by_rid: dict[str, list[str]] = {}
    for rid_dup, claims_dup in sorted(raw_ancestry_claims_by_rid.items()):
        if len(claims_dup) > 1:
            duplicate_rids_set.add(rid_dup)
        distinct_claims = sorted(set(claims_dup), key=repr)
        if len(distinct_claims) > 1:
            hierarchy_errors.append(
                f"CONFLICTING_DUPLICATE_RECIPIENT_ANCESTRY: duplicate clinical rows for recipient_id={rid_dup!r} "
                f"declare contradictory lot/bank ancestry {distinct_claims!r}."
            )
        if rid_dup in duplicate_rids_set:
            rclaims_list = raw_rescue_claims_by_rid.get(rid_dup, [])
            distinct_resc_sigs = sorted(
                {
                    (
                        rc["rescue_declared"],
                        rc["explicit_rescue_ids_provided"],
                        tuple(rc["rescue_lot_ids"]),
                        rc["missing_explicit_rescue_lot_id"],
                        rc["rescue_parse_error"],
                    )
                    for rc in rclaims_list
                },
                key=repr,
            )
            if len(distinct_resc_sigs) > 1:
                sorted_lot_claims = sorted(
                    {
                        (rc["intercurrent_event"], tuple(rc["rescue_lot_ids"]))
                        for rc in rclaims_list
                    },
                    key=repr,
                )
                dup_resc_msg = (
                    f"CONFLICTING_DUPLICATE_RECIPIENT_RESCUE: duplicate clinical rows for recipient_id={rid_dup!r} "
                    f"declare contradictory rescue claims {sorted_lot_claims!r}."
                )
                duplicate_rescue_errors_by_rid.setdefault(rid_dup, []).append(dup_resc_msg)
                failure_reasons.append(dup_resc_msg)

    # PASS 1 — ORDER-INDEPENDENT CANONICAL CLINICAL ENDPOINT, INTERCURRENT-EVENT, & RESCUE ADJUDICATION
    # Sort valid rows canonically by (rid, canonical_json) so duplicate-row diagnostics and outcomes are 100% order-independent!
    for rid, _canon_key, lid, _mid, rec, rclaim in sorted(pass1_valid_rows, key=lambda item: (item[0], item[1])):
        if rid in seen_rids:
            failure_reasons.append(f"Duplicate recipient_id {rid!r} violates 1:1 unique recipient unit.")
            continue

        seen_rids.add(rid)
        lot_ids.append(lid)

        ie = rclaim["intercurrent_event"]
        ie_valid = rclaim["ie_valid"]
        if ie_valid:
            ie_counts[ie] += 1  # type: ignore[index]
        else:
            failure_reasons.append(f"Recipient {rid!r} has invalid intercurrent_event={rec.get('intercurrent_event')!r}.")

        # Collect sorted unique parse errors across ALL raw Pass-0 rows for this rid (order-independent!)
        all_rclaims_for_rid = raw_rescue_claims_by_rid.get(rid, [rclaim])
        sorted_parse_errs = sorted({pe for rc in all_rclaims_for_rid for pe in rc["parse_errors"]})
        for pe in sorted_parse_errs:
            if pe not in failure_reasons:
                failure_reasons.append(pe)

        # Deduplicate & sort distinct raw rescue claims for order-independent CMC reconciliation
        dedup_rclaims_map: dict[tuple[Any, ...], dict[str, Any]] = {}
        for rc in all_rclaims_for_rid:
            sig = (
                rc["rescue_declared"],
                rc["explicit_rescue_ids_provided"],
                tuple(rc["rescue_lot_ids"]),
                rc["missing_explicit_rescue_lot_id"],
                rc["rescue_parse_error"],
                rc["intercurrent_event"],
            )
            if sig not in dedup_rclaims_map:
                dedup_rclaims_map[sig] = rc
        sorted_distinct_rclaims = [dedup_rclaims_map[k_sig] for k_sig in sorted(dedup_rclaims_map, key=repr)]

        rescue_declared = rclaim["rescue_declared"]
        if rid in clinical_recipient_meta:
            clinical_recipient_meta[rid].update({
                "intercurrent_event": ie,
                "rescue_declared": rescue_declared,
                "rescue_lot_id": rclaim["rescue_lot_id"],
                "rescue_lot_ids": list(rclaim["rescue_lot_ids"]),
                "explicit_rescue_ids_provided": rclaim["explicit_rescue_ids_provided"],
                "missing_explicit_rescue_lot_id": rclaim["missing_explicit_rescue_lot_id"],
                "rescue_parse_error": rclaim["rescue_parse_error"],
                "all_raw_rescue_claims": sorted_distinct_rclaims,
            })

        if not ie_valid:
            continue

        # Unified deterministic ITT primary adjudication (glucocorticoid-free single-infusion H1 estimand):
        # Classify ALL deterministic ITT non-response events (RESCUE_REPEAT_INFUSION,
        # PROHIBITED_PERI_INFUSION_GLUCOCORTICOIDS, MISSING_PRIMARY_ENDPOINT_OR_LTFU,
        # PRE_LANDMARK_DEATH, PRIMARY_GRAFT_NON_FUNCTION, or rescue_declared) to 0 BEFORE
        # attempting the endpoint/follow-up-dependent path!
        is_deterministic_nonresponse = (
            GATE_28A_INTERCURRENT_EVENT_ADJUDICATION.get(ie) == 0
            or rescue_declared
        )
        met_c2b_raw = rec.get("met_c2b_criteria")
        fu_raw = rec.get("followup_months")

        if is_deterministic_nonresponse:
            met_c2b_val: bool | None = None
            if met_c2b_raw is not None:
                if type(met_c2b_raw) is not bool:
                    failure_reasons.append(f"Recipient {rid!r} met_c2b_criteria must be strict bool.")
                else:
                    met_c2b_val = met_c2b_raw
            fu_mo_val: Decimal | None = None
            if fu_raw is not None:
                fu_mo_val = _strict_decimal_in_range(fu_raw, min_val=Decimal("0"))
                if fu_mo_val is None:
                    failure_reasons.append(f"Recipient {rid!r} followup_months invalid.")
            if (
                ie == "PROHIBITED_PERI_INFUSION_GLUCOCORTICOIDS"
                and met_c2b_val is True
                and fu_mo_val is not None
                and Fraction(fu_mo_val) >= Fraction(6, 1)
            ):
                secondary_steroid_exposed_c2b += 1
            adjudicated = 0
            primary_responders += adjudicated
            clinical_adjudicated_by_rid[rid] = adjudicated
        else:
            if type(met_c2b_raw) is not bool:
                failure_reasons.append(f"Recipient {rid!r} met_c2b_criteria must be strict bool.")
                continue
            fu_mo = _strict_decimal_in_range(fu_raw, min_val=Decimal("0"))
            if fu_mo is None:
                failure_reasons.append(f"Recipient {rid!r} followup_months invalid.")
                continue
            fu_ge_6 = Fraction(fu_mo) >= Fraction(6, 1)
            adjudicated = 1 if (fu_ge_6 and met_c2b_raw) else 0
            primary_responders += adjudicated
            clinical_adjudicated_by_rid[rid] = adjudicated

    combined_payload_wcb_to_mcbs: dict[str, set[str]] = {wid: set(mcbs) for wid, mcbs in observed_wcb_to_mcbs.items()}
    if manifest_mcb_norm is not None:
        for lid_w, wid_w in sorted(effective_wcb_manifest.items()):
            if lid_w in manifest_mcb_norm:
                combined_payload_wcb_to_mcbs.setdefault(wid_w, set()).add(manifest_mcb_norm[lid_w])
    for wid_obs, mcbs_obs in sorted(combined_payload_wcb_to_mcbs.items()):
        if len(mcbs_obs) > 1:
            hierarchy_errors.append(
                f"NON_UNIQUE_WCB_PARENTAGE: combined cohort rows and bank manifests assign literal wcb_id={wid_obs!r} across multiple distinct "
                f"MCBs {sorted(mcbs_obs)} (each distinct literal wcb_id must map to at most ONE mcb_id)."
            )

    n = len(seen_rids)
    k = primary_responders
    if n == 0:
        failure_reasons.append("No valid unique recipients in cohort.")
        if trusted_clinical_store is not None and raw_ancestry_claims_by_rid:
            early_cmc_errs_n0 = _audit_attested_raw_cmc_ledger_for_early_hold(
                cohort_payload,
                cohort_id=cohort_id,
                trusted_clinical_store=trusted_clinical_store,
                manifest_mcb_norm=manifest_mcb_norm,
                effective_wcb_manifest=effective_wcb_manifest,
                observed_wcb_to_mcbs=observed_wcb_to_mcbs,
                seen_rids=seen_rids,
                clinical_recipient_meta=clinical_recipient_meta,
                raw_ancestry_claims_by_rid=raw_ancestry_claims_by_rid,
                raw_rescue_claims_by_rid=raw_rescue_claims_by_rid,
                duplicate_rids_set=duplicate_rids_set,
                duplicate_rescue_errors_by_rid=duplicate_rescue_errors_by_rid,
            )
            for err_n0 in early_cmc_errs_n0:
                if err_n0 not in failure_reasons:
                    failure_reasons.append(err_n0)
        return {
            "status": "HOLD_H1_AT_88PCT",
            "promotion_authorized": False,
            "external_clinical_store_verified": False,
            "cohort_id": cohort_id,
            "cohort_canonical_sha256": cohort_canonical_sha256,
            "cohort_ledger_sha256": cohort_canonical_sha256,
            "lot_bank_hierarchy_valid": False,
            "lot_to_mcb_manifest_verified": False,
            "lot_to_wcb_manifest_verified": False,
            "prespecification_attestation_verified": False,
            "source_verification_attestation_verified": False,
            "parallel_cmc_ledger_verified": False,
            "icc_sensitivity_report_attached": False,
            "icc_sensitivity_report": None,
            "boundary_sensitive_under_high_icc": False,
            "icc_sensitivity_review_status": None,
            "k": k,
            "n": n,
            "deff": None,
            "n_eff": None,
            "k_eff": None,
            "intercurrent_event_counts": ie_counts,
            "secondary_steroid_exposed_c2b_count_excluded_from_primary": secondary_steroid_exposed_c2b,
            "trusted_clinical_store_deployment_dependency": TRUSTED_CLINICAL_STORE_DEPLOYMENT_DEPENDENCY,
            "failure_reasons": failure_reasons,
        }

    # STRICT NESTED LOT -> MCB (AND WCB WHENEVER DECLARED) HIERARCHY CHECK BEFORE CLUSTER DEFF / n_eff!
    # ZERO UNVERIFIED ANCESTRY FALLBACK: NEVER populate verified_lot_to_mcb from unverified recipient rows!
    verified_lot_to_mcb: dict[str, str] = {}
    if manifest_mcb_norm is None:
        hierarchy_errors.append(
            "Required lot_to_mcb_manifest is missing or invalid; unverified recipient-row ancestry fallback is prohibited."
        )
    for lid in sorted(observed_lot_to_mcbs):
        mcbs_for_lot = observed_lot_to_mcbs[lid]
        if len(mcbs_for_lot) > 1:
            hierarchy_errors.append(
                f"Conflicting mcb_id assignments within lot_id={lid!r}: observed {sorted(mcbs_for_lot)} "
                "(a single GMP lot MUST descend from exactly ONE MCB)."
            )
        wcbs_for_lot = observed_lot_to_wcbs.get(lid, {None})
        if len(wcbs_for_lot) > 1:
            hierarchy_errors.append(
                f"Conflicting or partially omitted wcb_id assignments within lot_id={lid!r}: observed {sorted(str(x) for x in wcbs_for_lot)}."
            )
        if manifest_mcb_norm is not None:
            if lid not in manifest_mcb_norm:
                hierarchy_errors.append(f"Observed lot_id={lid!r} is missing from verified lot_to_mcb_manifest.")
            elif len(mcbs_for_lot) == 1:
                obs_mcb = next(iter(mcbs_for_lot))
                if manifest_mcb_norm[lid] != obs_mcb:
                    hierarchy_errors.append(
                        f"Manifest mismatch for lot_id={lid!r}: recipient ledger has mcb_id={obs_mcb!r} "
                        f"but lot_to_mcb_manifest maps to {manifest_mcb_norm[lid]!r}."
                    )
                else:
                    verified_lot_to_mcb[lid] = manifest_mcb_norm[lid]

        # Strict WCB provenance verification whenever ANY recipient declares wcb_id OR manifest declares a WCB
        any_wcb_in_lot = any(x is not None for x in wcbs_for_lot)
        manifest_wcb_for_lot = effective_wcb_manifest.get(lid)
        if any_wcb_in_lot:
            if manifest_wcb_for_lot is None:
                hierarchy_errors.append(
                    f"Observed wcb_id on lot_id={lid!r} lacks a matching verified lot_to_wcb_manifest entry."
                )
            elif wcbs_for_lot != {manifest_wcb_for_lot}:
                hierarchy_errors.append(
                    f"Manifest lot_to_wcb_manifest mismatch for lot_id={lid!r}: expected {manifest_wcb_for_lot!r}, "
                    f"observed {sorted(str(x) for x in wcbs_for_lot)}."
                )
        elif manifest_wcb_for_lot is not None:
            hierarchy_errors.append(
                f"Manifest lot_to_wcb_manifest declares wcb_id={manifest_wcb_for_lot!r} for lot_id={lid!r}, "
                "but recipient rows omitted wcb_id."
            )

    wcb_required_or_present = any_recipient_wcb_declared or payload_wcb_present or bool(effective_wcb_manifest) or (wcb_manifest_raw is not None)

    if hierarchy_errors:
        for herr in hierarchy_errors:
            if herr not in failure_reasons:
                failure_reasons.append(herr)
        if trusted_clinical_store is not None:
            early_cmc_errs = _audit_attested_raw_cmc_ledger_for_early_hold(
                cohort_payload,
                cohort_id=cohort_id,
                trusted_clinical_store=trusted_clinical_store,
                manifest_mcb_norm=manifest_mcb_norm,
                effective_wcb_manifest=effective_wcb_manifest,
                observed_wcb_to_mcbs=observed_wcb_to_mcbs,
                seen_rids=seen_rids,
                clinical_recipient_meta=clinical_recipient_meta,
                raw_ancestry_claims_by_rid=raw_ancestry_claims_by_rid,
                raw_rescue_claims_by_rid=raw_rescue_claims_by_rid,
                duplicate_rids_set=duplicate_rids_set,
                duplicate_rescue_errors_by_rid=duplicate_rescue_errors_by_rid,
            )
            for err_hc in early_cmc_errs:
                if err_hc not in failure_reasons:
                    failure_reasons.append(err_hc)
        return {
            "status": "HOLD_H1_AT_88PCT",
            "promotion_authorized": False,
            "external_clinical_store_verified": False,
            "cohort_id": cohort_id,
            "cohort_canonical_sha256": cohort_canonical_sha256,
            "cohort_ledger_sha256": cohort_canonical_sha256,
            "lot_bank_hierarchy_valid": False,
            "lot_to_mcb_manifest_verified": False,
            "lot_to_wcb_manifest_verified": False,
            "prespecification_attestation_verified": False,
            "source_verification_attestation_verified": False,
            "parallel_cmc_ledger_verified": False,
            "icc_sensitivity_report_attached": False,
            "icc_sensitivity_report": None,
            "boundary_sensitive_under_high_icc": False,
            "icc_sensitivity_review_status": None,
            "k": k,
            "n": n,
            "deff": None,
            "n_eff": None,
            "k_eff": None,
            "intercurrent_event_counts": ie_counts,
            "secondary_steroid_exposed_c2b_count_excluded_from_primary": secondary_steroid_exposed_c2b,
            "trusted_clinical_store_deployment_dependency": TRUSTED_CLINICAL_STORE_DEPLOYMENT_DEPENDENCY,
            "failure_reasons": failure_reasons,
        }

    # INDEPENDENT EXTERNAL trusted_clinical_store RESOLUTION (ZERO SELF-ATTESTATION!)
    self_attested_inline_rejected = any(
        k_in in cohort_payload and cohort_payload[k_in] is not None
        for k_in in (
            "prespecification_attestation",
            "source_verification_attestation",
            "verified_lot_to_bank_manifest",
            "parallel_cmc_readiness_ledger",
        )
    )
    payload_cmc_sha, cmc_sha_errs = _resolve_payload_cmc_ledger_sha256(cohort_payload)
    failure_reasons.extend(cmc_sha_errs)

    refs_raw = cohort_payload.get("clinical_store_refs")
    if refs_raw is not None and not isinstance(refs_raw, dict):
        failure_reasons.append("clinical_store_refs must be a dict mapping reference keys to 64-hex SHA-256 digests.")
        store_refs: dict[str, Any] = {}
    else:
        store_refs = dict(refs_raw or {})

    prespec_verified = False
    source_verified = False
    store_manifest_verified = False
    store_wcb_verified: bool | None = (False if wcb_required_or_present else None)
    cmc_ledger_verified = False
    store_manifest_failed_hierarchy = False
    cmc_ancestry_conflict = False
    st_mcb: dict[str, str] | None = None
    st_eff_wcb: dict[str, str] = {}
    trusted_store_source: str | None = None
    authenticated_store_digests: dict[str, str] = {}
    authenticated_store_issuers: dict[str, str] = {}
    parallel_cmc_summary: dict[str, Any] | None = None

    if trusted_clinical_store is None:
        failure_reasons.append(
            "Independent external trusted_clinical_store is required to certify lot/bank hierarchy and "
            "authorize Gate 28-A promotion (self-attested inline caller dicts and bare booleans can NEVER "
            "certify hierarchy, emit DEFF/n_eff/k_eff, or authorize promotion)."
        )
        store_manifest_failed_hierarchy = True
    else:
        # 1. Resolve PRESPECIFICATION_ATTESTATION strictly from trusted_clinical_store
        p_ref = store_refs.get("prespecification_attestation_sha256")
        if p_ref is None:
            failure_reasons.append("Missing clinical_store_refs.prespecification_attestation_sha256 for trusted_clinical_store lookup.")
        else:
            prec, perr, psrc = _lookup_gate28a_trusted_record(
                trusted_clinical_store,
                category="prespecification_attestations",
                expected_sha256=p_ref,
                allowed_issuers=GATE_28A_ALLOWED_ATTESTATION_AUTHORITIES,
            )
            if psrc is not None:
                trusted_store_source = psrc
            if perr is not None or prec is None:
                failure_reasons.append(f"Trusted clinical store resolution failed for PRESPECIFICATION_ATTESTATION: {perr}.")
            else:
                p_errs: list[str] = []
                p_recomp = compute_gate28a_record_sha256(prec)
                if not _is_valid_sha256_hex(prec.get("record_sha256")) or p_recomp != prec.get("record_sha256") or p_recomp != p_ref:
                    p_errs.append("PRESPECIFICATION_ATTESTATION SHA-256 verification failed.")
                if prec.get("attestation_sha256") is not None and prec.get("attestation_sha256") != p_recomp:
                    p_errs.append("PRESPECIFICATION_ATTESTATION attestation_sha256 contradicts record_sha256.")
                if prec.get("record_type") != "PRESPECIFICATION_ATTESTATION":
                    p_errs.append(f"Unexpected PRESPECIFICATION_ATTESTATION record_type={prec.get('record_type')!r}.")
                if cohort_id is not None and prec.get("cohort_id") != cohort_id:
                    p_errs.append(f"PRESPECIFICATION_ATTESTATION cohort_id={prec.get('cohort_id')!r} != {cohort_id!r}.")
                if prec.get("cohort_canonical_sha256") != cohort_canonical_sha256:
                    p_errs.append(
                        "PRESPECIFICATION_ATTESTATION cohort_canonical_sha256 does not match the full canonical cohort digest "
                        "(post-attestation mutation of compatibility, overlap, ICC, manifest, CMC hash, or recipients detected)."
                    )
                if prec.get("cohort_ledger_sha256") is not None and prec.get("cohort_ledger_sha256") != cohort_canonical_sha256:
                    p_errs.append("PRESPECIFICATION_ATTESTATION cohort_ledger_sha256 does not match full canonical cohort digest.")
                if _strict_literal_id(prec.get("protocol_or_sap_id")) is None:
                    p_errs.append("PRESPECIFICATION_ATTESTATION missing literal protocol_or_sap_id.")
                if prec.get("prespecified_before_unblinding") is not True or type(prec.get("prespecified_before_unblinding")) is not bool:
                    p_errs.append("PRESPECIFICATION_ATTESTATION prespecified_before_unblinding must be strict bool True.")
                if prec.get("single_compatible_cohort_confirmed") is not True or type(prec.get("single_compatible_cohort_confirmed")) is not bool:
                    p_errs.append("PRESPECIFICATION_ATTESTATION single_compatible_cohort_confirmed must be strict bool True.")
                p_issuer = _strict_literal_id(prec.get("issuer_authority_id"))
                if p_issuer not in GATE_28A_ALLOWED_ATTESTATION_AUTHORITIES:
                    p_errs.append(f"PRESPECIFICATION_ATTESTATION issuer_authority_id={prec.get('issuer_authority_id')!r} not in allowlist.")
                inline_p = cohort_payload.get("prespecification_attestation")
                if isinstance(inline_p, dict) and compute_gate28a_record_sha256(inline_p) != p_recomp:
                    p_errs.append("Inline prespecification_attestation contradicts trusted_clinical_store record.")
                if p_errs:
                    failure_reasons.extend(p_errs)
                else:
                    prespec_verified = True
                    authenticated_store_digests["prespecification_attestation"] = p_recomp
                    if p_issuer is not None:
                        authenticated_store_issuers["prespecification_attestation"] = p_issuer

        # 2. Resolve SOURCE_VERIFICATION_ATTESTATION strictly from trusted_clinical_store
        s_ref = store_refs.get("source_verification_attestation_sha256")
        source_att_cmc_sha: str | None = None
        if s_ref is None:
            failure_reasons.append("Missing clinical_store_refs.source_verification_attestation_sha256 for trusted_clinical_store lookup.")
        else:
            srec, serr, ssrc = _lookup_gate28a_trusted_record(
                trusted_clinical_store,
                category="source_verification_attestations",
                expected_sha256=s_ref,
                allowed_issuers=GATE_28A_ALLOWED_ATTESTATION_AUTHORITIES,
            )
            if ssrc is not None:
                trusted_store_source = ssrc
            if serr is not None or srec is None:
                failure_reasons.append(f"Trusted clinical store resolution failed for SOURCE_VERIFICATION_ATTESTATION: {serr}.")
            else:
                s_errs: list[str] = []
                s_recomp = compute_gate28a_record_sha256(srec)
                if not _is_valid_sha256_hex(srec.get("record_sha256")) or s_recomp != srec.get("record_sha256") or s_recomp != s_ref:
                    s_errs.append("SOURCE_VERIFICATION_ATTESTATION SHA-256 verification failed.")
                if srec.get("attestation_sha256") is not None and srec.get("attestation_sha256") != s_recomp:
                    s_errs.append("SOURCE_VERIFICATION_ATTESTATION attestation_sha256 contradicts record_sha256.")
                if srec.get("record_type") != "SOURCE_VERIFICATION_ATTESTATION":
                    s_errs.append(f"Unexpected SOURCE_VERIFICATION_ATTESTATION record_type={srec.get('record_type')!r}.")
                if cohort_id is not None and srec.get("cohort_id") != cohort_id:
                    s_errs.append(f"SOURCE_VERIFICATION_ATTESTATION cohort_id={srec.get('cohort_id')!r} != {cohort_id!r}.")
                if srec.get("cohort_canonical_sha256") != cohort_canonical_sha256:
                    s_errs.append(
                        "SOURCE_VERIFICATION_ATTESTATION cohort_canonical_sha256 does not match the full canonical cohort digest."
                    )
                if srec.get("cohort_ledger_sha256") is not None and srec.get("cohort_ledger_sha256") != cohort_canonical_sha256:
                    s_errs.append("SOURCE_VERIFICATION_ATTESTATION cohort_ledger_sha256 does not match full canonical cohort digest.")
                if _strict_literal_id(srec.get("primary_source_citation_id")) is None:
                    s_errs.append("SOURCE_VERIFICATION_ATTESTATION missing literal primary_source_citation_id.")
                if srec.get("primary_peer_reviewed_full_text_verified") is not True or type(srec.get("primary_peer_reviewed_full_text_verified")) is not bool:
                    s_errs.append("SOURCE_VERIFICATION_ATTESTATION primary_peer_reviewed_full_text_verified must be strict bool True.")
                elif "primary_peer_reviewed_full_text_verified" in cohort_payload:
                    pl_pdf = cohort_payload["primary_peer_reviewed_full_text_verified"]
                    if type(pl_pdf) is not bool or pl_pdf is not True:
                        s_errs.append(
                            f"SOURCE_VERIFICATION_ATTESTATION primary_peer_reviewed_full_text_verified=True contradicts "
                            f"cohort payload primary_peer_reviewed_full_text_verified={pl_pdf!r}."
                        )
                if srec.get("parallel_cmc_readiness_ledger_disclosed") is not True or type(srec.get("parallel_cmc_readiness_ledger_disclosed")) is not bool:
                    s_errs.append("SOURCE_VERIFICATION_ATTESTATION parallel_cmc_readiness_ledger_disclosed must be strict bool True.")
                elif "parallel_cmc_readiness_ledger_disclosed" in cohort_payload:
                    pl_cmc = cohort_payload["parallel_cmc_readiness_ledger_disclosed"]
                    if type(pl_cmc) is not bool or pl_cmc is not True:
                        s_errs.append(
                            f"SOURCE_VERIFICATION_ATTESTATION parallel_cmc_readiness_ledger_disclosed=True contradicts "
                            f"cohort payload parallel_cmc_readiness_ledger_disclosed={pl_cmc!r}."
                        )
                s_cmc = srec.get("parallel_cmc_readiness_ledger_sha256")
                if not _is_valid_sha256_hex(s_cmc):
                    s_errs.append("SOURCE_VERIFICATION_ATTESTATION missing valid 64-hex parallel_cmc_readiness_ledger_sha256.")
                else:
                    source_att_cmc_sha = str(s_cmc)
                    if payload_cmc_sha is not None and payload_cmc_sha != source_att_cmc_sha:
                        s_errs.append(
                            f"SOURCE_VERIFICATION_ATTESTATION parallel_cmc_readiness_ledger_sha256={source_att_cmc_sha} "
                            f"!= payload {payload_cmc_sha}."
                        )
                if srec.get("parallel_cmc_ledger_sha256") is not None and srec.get("parallel_cmc_ledger_sha256") != s_cmc:
                    s_errs.append("SOURCE_VERIFICATION_ATTESTATION conflicting parallel_cmc_ledger_sha256 alias.")
                s_issuer = _strict_literal_id(srec.get("issuer_authority_id"))
                if s_issuer not in GATE_28A_ALLOWED_ATTESTATION_AUTHORITIES:
                    s_errs.append(f"SOURCE_VERIFICATION_ATTESTATION issuer_authority_id={srec.get('issuer_authority_id')!r} not in allowlist.")
                inline_s = cohort_payload.get("source_verification_attestation")
                if isinstance(inline_s, dict) and compute_gate28a_record_sha256(inline_s) != s_recomp:
                    s_errs.append("Inline source_verification_attestation contradicts trusted_clinical_store record.")
                if s_errs:
                    failure_reasons.extend(s_errs)
                else:
                    source_verified = True
                    authenticated_store_digests["source_verification_attestation"] = s_recomp
                    if s_issuer is not None:
                        authenticated_store_issuers["source_verification_attestation"] = s_issuer

        # 3. Resolve VERIFIED_LOT_TO_BANK_MANIFEST strictly from trusted_clinical_store
        m_ref = store_refs.get("verified_lot_to_bank_manifest_sha256")
        if m_ref is None:
            failure_reasons.append("Missing clinical_store_refs.verified_lot_to_bank_manifest_sha256 for trusted_clinical_store lookup.")
            store_manifest_failed_hierarchy = True
        else:
            mrec, merr, msrc = _lookup_gate28a_trusted_record(
                trusted_clinical_store,
                category="verified_lot_to_bank_manifests",
                expected_sha256=m_ref,
                allowed_issuers=GATE_28A_ALLOWED_ATTESTATION_AUTHORITIES,
            )
            if msrc is not None:
                trusted_store_source = msrc
            if merr is not None or mrec is None:
                failure_reasons.append(f"Trusted clinical store resolution failed for VERIFIED_LOT_TO_BANK_MANIFEST: {merr}.")
                store_manifest_failed_hierarchy = True
            else:
                m_errs: list[str] = []
                m_recomp = compute_gate28a_record_sha256(mrec)
                if not _is_valid_sha256_hex(mrec.get("record_sha256")) or m_recomp != mrec.get("record_sha256") or m_recomp != m_ref:
                    m_errs.append("VERIFIED_LOT_TO_BANK_MANIFEST SHA-256 verification failed.")
                if mrec.get("record_type") != "VERIFIED_LOT_TO_BANK_MANIFEST":
                    m_errs.append(f"Unexpected VERIFIED_LOT_TO_BANK_MANIFEST record_type={mrec.get('record_type')!r}.")
                if cohort_id is not None and mrec.get("cohort_id") != cohort_id:
                    m_errs.append(f"VERIFIED_LOT_TO_BANK_MANIFEST cohort_id={mrec.get('cohort_id')!r} != {cohort_id!r}.")
                if _strict_literal_id(mrec.get("manifest_source_id")) is None:
                    m_errs.append("VERIFIED_LOT_TO_BANK_MANIFEST missing literal manifest_source_id.")
                m_issuer = _strict_literal_id(mrec.get("issuer_authority_id"))
                if m_issuer not in GATE_28A_ALLOWED_ATTESTATION_AUTHORITIES:
                    m_errs.append(f"VERIFIED_LOT_TO_BANK_MANIFEST issuer_authority_id={mrec.get('issuer_authority_id')!r} not in allowlist.")
                st_mcb, st_eff_wcb, st_wcb_present, st_man_errs = _merge_and_validate_bank_manifests(
                    mrec.get("lot_to_mcb_manifest"),
                    mrec.get("lot_to_wcb_manifest"),
                    mrec.get("lot_to_bank_manifest"),
                    context="VERIFIED_LOT_TO_BANK_MANIFEST",
                    extra_container=mrec,
                )
                m_errs.extend(st_man_errs)
                if st_mcb is not None and manifest_mcb_norm is not None:
                    if st_mcb != manifest_mcb_norm:
                        m_errs.append("VERIFIED_LOT_TO_BANK_MANIFEST lot_to_mcb_manifest does not match cohort payload manifest.")
                    for lid, obs_mcb in verified_lot_to_mcb.items():
                        if st_mcb.get(lid) != obs_mcb:
                            m_errs.append(
                                f"VERIFIED_LOT_TO_BANK_MANIFEST mismatch for lot_id={lid!r}: store={st_mcb.get(lid)!r} vs cohort={obs_mcb!r}."
                            )
                if wcb_required_or_present or st_wcb_present or st_eff_wcb:
                    if not st_eff_wcb:
                        m_errs.append("VERIFIED_LOT_TO_BANK_MANIFEST missing required lot_to_wcb_manifest for declared wcb_id ancestry.")
                    elif st_eff_wcb != effective_wcb_manifest:
                        m_errs.append("VERIFIED_LOT_TO_BANK_MANIFEST lot_to_wcb_manifest does not match cohort payload WCB manifest.")
                if m_errs:
                    failure_reasons.extend(m_errs)
                    store_manifest_failed_hierarchy = True
                else:
                    store_manifest_verified = True
                    store_wcb_verified = True if (wcb_required_or_present or st_wcb_present or st_eff_wcb) else None
                    authenticated_store_digests["verified_lot_to_bank_manifest"] = m_recomp
                    if m_issuer is not None:
                        authenticated_store_issuers["verified_lot_to_bank_manifest"] = m_issuer

        # 4. Resolve ACTUAL PARALLEL_CMC_READINESS_LEDGER payload bytes, verify SHA-256, run CMC evaluator, and reconcile recipients!
        target_cmc_sha = payload_cmc_sha or source_att_cmc_sha
        if target_cmc_sha is None:
            failure_reasons.append("Missing parallel_cmc_readiness_ledger_sha256 for trusted_clinical_store CMC ledger lookup.")
        else:
            cmc_bytes, cmc_err, csrc = _lookup_gate28a_trusted_cmc_ledger_bytes(
                trusted_clinical_store,
                expected_sha256=target_cmc_sha,
                allowed_issuers=GATE_28A_ALLOWED_ATTESTATION_AUTHORITIES,
            )
            if csrc is not None:
                trusted_store_source = csrc
            if cmc_err is not None or cmc_bytes is None:
                failure_reasons.append(f"Trusted clinical store resolution failed for PARALLEL_CMC_READINESS_LEDGER: {cmc_err}.")
            else:
                c_errs: list[str] = []
                c_issuer: str | None = None
                try:
                    cmc_doc = load_strict_json_bytes(cmc_bytes, "PARALLEL_CMC_READINESS_LEDGER")
                except Exception as exc:
                    cmc_doc = None
                    c_errs.append(
                        f"PARALLEL_CMC_READINESS_LEDGER failed strict JSON decode (CMC_LEDGER_ANCESTRY_UNVERIFIABLE): {exc}"
                    )
                    cmc_ancestry_conflict = True
                if not isinstance(cmc_doc, dict):
                    c_errs.append(
                        "PARALLEL_CMC_READINESS_LEDGER payload must be a JSON object (CMC_LEDGER_ANCESTRY_UNVERIFIABLE)."
                    )
                    cmc_ancestry_conflict = True
                else:
                    if cmc_doc.get("record_type") != "PARALLEL_CMC_READINESS_LEDGER":
                        c_errs.append(f"Unexpected PARALLEL_CMC_READINESS_LEDGER record_type={cmc_doc.get('record_type')!r}.")
                    if cohort_id is not None and cmc_doc.get("cohort_id") != cohort_id:
                        c_errs.append(f"PARALLEL_CMC_READINESS_LEDGER cohort_id={cmc_doc.get('cohort_id')!r} != {cohort_id!r}.")
                    c_issuer = _strict_literal_id(cmc_doc.get("issuer_authority_id"))
                    if c_issuer not in GATE_28A_ALLOWED_ATTESTATION_AUTHORITIES:
                        c_errs.append(f"PARALLEL_CMC_READINESS_LEDGER issuer_authority_id={cmc_doc.get('issuer_authority_id')!r} not in allowlist.")
                    lot_ledger_raw = cmc_doc.get("lot_ledger")
                    ref_mcb_map: dict[str, str] = st_mcb if st_mcb is not None else (manifest_mcb_norm or {})
                    ref_wcb_map: dict[str, str] = st_eff_wcb if st_mcb is not None else effective_wcb_manifest

                    # UNCONDITIONAL PRE-VALIDATION RAW CMC ANCESTRY & BIDIRECTIONAL RESCUE RECONCILIATION
                    # Runs ONCE unconditionally BEFORE evaluate_cmc_attempted_lot_readiness so NO unrelated CMC
                    # validation/shape error (e.g., invalid planned_doses_n on another split lot) can EVER mask
                    # raw CMC ancestry conflicts OR clinical-vs-CMC rescue identity/cardinality/lineage conflicts!
                    raw_anc_errs, raw_anc_conflict = _audit_raw_cmc_ledger_ancestry(
                        lot_ledger_raw,
                        ref_mcb_map=ref_mcb_map,
                        ref_wcb_map=ref_wcb_map,
                        observed_wcb_to_mcbs=observed_wcb_to_mcbs,
                        clinical_recipient_meta=clinical_recipient_meta,
                        raw_ancestry_claims_by_rid=raw_ancestry_claims_by_rid,
                    )
                    for aerr in raw_anc_errs:
                        if aerr not in c_errs:
                            c_errs.append(aerr)
                    if raw_anc_conflict:
                        cmc_ancestry_conflict = True

                    raw_resc_errs, raw_resc_conflict = _reconcile_raw_clinical_and_cmc_rescues(
                        lot_ledger_raw,
                        seen_rids=seen_rids,
                        clinical_recipient_meta=clinical_recipient_meta,
                        raw_ancestry_claims_by_rid=raw_ancestry_claims_by_rid,
                        raw_rescue_claims_by_rid=raw_rescue_claims_by_rid,
                        duplicate_rids_set=duplicate_rids_set,
                        duplicate_rescue_errors_by_rid=duplicate_rescue_errors_by_rid,
                        ref_mcb_map=ref_mcb_map,
                        ref_wcb_map=ref_wcb_map,
                    )
                    for rerr in raw_resc_errs:
                        if rerr not in c_errs:
                            c_errs.append(rerr)
                    if raw_resc_conflict:
                        cmc_ancestry_conflict = True

                    try:
                        parallel_cmc_summary = evaluate_cmc_attempted_lot_readiness(lot_ledger_raw)
                    except CMCAncestryValidationError as exc:
                        c_errs.append(
                            f"PARALLEL_CMC_READINESS_LEDGER failed evaluate_cmc_attempted_lot_readiness "
                            f"({exc.error_code}): {exc}"
                        )
                        cmc_ancestry_conflict = True
                    except Exception as exc:
                        c_errs.append(f"PARALLEL_CMC_READINESS_LEDGER failed evaluate_cmc_attempted_lot_readiness: {exc}")
                    else:
                        single_map, pooled_map, _all_cmc_rows = _extract_cmc_reconciliation_view(lot_ledger_raw)
                        if pooled_map:
                            c_errs.append(
                                f"PARALLEL_CMC_READINESS_LEDGER contains {len(pooled_map)} pooled multi-lot course recipient(s); "
                                "pooled multi-lot courses are excluded from primary single-lot nested-cluster Gate 28-A promotion "
                                "unless a prespecified multi-membership cluster model is registered."
                            )
                        cmc_rids = set(single_map.keys())
                        missing_from_cmc = sorted(seen_rids - cmc_rids)
                        extra_in_cmc = sorted(cmc_rids - seen_rids)
                        if missing_from_cmc:
                            c_errs.append(
                                f"Clinical cohort recipients missing from PARALLEL_CMC_READINESS_LEDGER: {missing_from_cmc[:5]} (total {len(missing_from_cmc)})."
                            )
                            cmc_ancestry_conflict = True
                        if extra_in_cmc:
                            c_errs.append(
                                f"Infused recipients in PARALLEL_CMC_READINESS_LEDGER omitted from clinical cohort: {extra_in_cmc[:5]} (total {len(extra_in_cmc)})."
                            )
                            cmc_ancestry_conflict = True
                        for rid in sorted(seen_rids & cmc_rids):
                            cmeta = clinical_recipient_meta[rid]
                            sinfo = single_map[rid]
                            if cmeta["lot_id"] != sinfo["lot_id"]:
                                msg_lid = (
                                    f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: CMC reconciliation lot_id mismatch for recipient {rid!r}: clinical={cmeta['lot_id']!r} != cmc={sinfo['lot_id']!r}."
                                )
                                if msg_lid not in c_errs:
                                    c_errs.append(msg_lid)
                                cmc_ancestry_conflict = True
                            if cmeta["mcb_id"] != sinfo["mcb_id"]:
                                msg_mid = (
                                    f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: CMC reconciliation mcb_id mismatch for recipient {rid!r}: clinical={cmeta['mcb_id']!r} != cmc={sinfo['mcb_id']!r}."
                                )
                                if msg_mid not in c_errs:
                                    c_errs.append(msg_mid)
                                cmc_ancestry_conflict = True
                            if cmeta["wcb_id"] != sinfo["wcb_id"]:
                                if cmeta["lot_id"] == sinfo["lot_id"] and cmeta["wcb_id"] is not None and sinfo["wcb_id"] is None:
                                    msg_wid = (
                                        f"CMC_INFUSED_LOT_MISSING_DECLARED_WCB_ID: CMC reconciliation for recipient {rid!r} "
                                        f"(lot_id={sinfo['lot_id']!r}): clinical/manifest declares wcb_id={cmeta['wcb_id']!r} "
                                        "but raw CMC row omitted wcb_id."
                                    )
                                else:
                                    msg_wid = (
                                        f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: CMC reconciliation wcb_id mismatch "
                                        f"for recipient {rid!r}: clinical={cmeta['wcb_id']!r} != cmc={sinfo['wcb_id']!r}."
                                    )
                                if msg_wid not in c_errs:
                                    c_errs.append(msg_wid)
                                cmc_ancestry_conflict = True
                            if any(p_lid != cmeta["lot_id"] for p_lid in sinfo["rescued_primary_lot_ids"]):
                                msg_plid = (
                                    f"CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST: CMC rescue primary-lot mismatch "
                                    f"for recipient {rid!r}: clinical primary lot_id={cmeta['lot_id']!r} != cmc rescued_primary_lot_ids={sinfo['rescued_primary_lot_ids']!r}."
                                )
                                if msg_plid not in c_errs:
                                    c_errs.append(msg_plid)
                                msg_plid_resc = (
                                    f"CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT: CMC rescue primary-lot mismatch "
                                    f"for recipient {rid!r}: clinical primary lot_id={cmeta['lot_id']!r} != cmc rescued_primary_lot_ids={sinfo['rescued_primary_lot_ids']!r}; "
                                    "ancestry verification and cluster statistics nullified fail-closed."
                                )
                                if msg_plid_resc not in c_errs:
                                    c_errs.append(msg_plid_resc)
                                cmc_ancestry_conflict = True

                            # Strict mandatory clinical-vs-CMC outcome reconciliation for EVERY primary CMC recipient:
                            # Compare against the RAW submitted initial-lot CMC outcome BEFORE rescue normalization
                            # zeroes primary_outcome so a rescued recipient whose initial CMC lot still claims
                            # responder outcome=1 fails closed with CMC_OUTCOME_MISMATCH!
                            raw_cmc_outcome = sinfo["raw_primary_outcome"]
                            if rid not in clinical_adjudicated_by_rid:
                                c_errs.append(
                                    f"CMC_OUTCOME_UNRECONCILED_MISSING_CLINICAL_ADJUDICATION: CMC reconciliation failed for "
                                    f"recipient {rid!r}: cmc={raw_cmc_outcome} lacks a reconciled clinical adjudication."
                                )
                            elif clinical_adjudicated_by_rid[rid] != raw_cmc_outcome:
                                c_errs.append(
                                    f"CMC_OUTCOME_MISMATCH: CMC reconciliation outcome mismatch for recipient {rid!r}: "
                                    f"clinical={clinical_adjudicated_by_rid[rid]} != cmc={raw_cmc_outcome}."
                                )
                if c_errs:
                    for cerr_item in c_errs:
                        if cerr_item not in failure_reasons:
                            failure_reasons.append(cerr_item)
                else:
                    cmc_ledger_verified = True
                    authenticated_store_digests["parallel_cmc_readiness_ledger"] = target_cmc_sha
                    if c_issuer is not None:
                        authenticated_store_issuers["parallel_cmc_readiness_ledger"] = c_issuer

    if duplicate_rescue_errors_by_rid or any(
        "CONFLICTING_CLINICAL_RESCUE_LOT_FIELDS" in fr for fr in failure_reasons
    ):
        cmc_ancestry_conflict = True

    if cmc_ancestry_conflict or store_manifest_failed_hierarchy or not store_manifest_verified:
        cmc_ledger_verified = False

    if store_manifest_failed_hierarchy or not store_manifest_verified or cmc_ancestry_conflict:
        return {
            "status": "HOLD_H1_AT_88PCT",
            "promotion_authorized": False,
            "external_clinical_store_verified": False,
            "cohort_id": cohort_id,
            "cohort_canonical_sha256": cohort_canonical_sha256,
            "cohort_ledger_sha256": cohort_canonical_sha256,
            "lot_bank_hierarchy_valid": False,
            "lot_to_mcb_manifest_verified": False,
            "lot_to_wcb_manifest_verified": False,
            "prespecification_attestation_verified": prespec_verified,
            "source_verification_attestation_verified": source_verified,
            "parallel_cmc_ledger_verified": False,
            "icc_sensitivity_report_attached": False,
            "icc_sensitivity_report": None,
            "boundary_sensitive_under_high_icc": False,
            "icc_sensitivity_review_status": None,
            "parallel_cmc_readiness_summary": parallel_cmc_summary,
            "self_attested_inline_records_rejected": self_attested_inline_rejected,
            "trusted_clinical_store_resolution_source": trusted_store_source,
            "trusted_clinical_store_deployment_dependency": TRUSTED_CLINICAL_STORE_DEPLOYMENT_DEPENDENCY,
            "k": k,
            "n": n,
            "deff": None,
            "n_eff": None,
            "k_eff": None,
            "intercurrent_event_counts": ie_counts,
            "secondary_steroid_exposed_c2b_count_excluded_from_primary": secondary_steroid_exposed_c2b,
            "failure_reasons": failure_reasons,
        }

    # Compute cluster counts strictly from the verified nested lot -> MCB hierarchy!
    lot_counts = Counter(lot_ids)
    bank_counts: Counter[str] = Counter()
    for lid, cnt in lot_counts.items():
        bank_counts[verified_lot_to_mcb[lid]] += cnt
    distinct_gmp_lots_n = len(lot_counts)
    distinct_mcb_n = len(bank_counts)
    max_single_lot_n = max(lot_counts.values())
    max_single_lot_share_frac = Fraction(max_single_lot_n, n)
    max_share_cap_frac = Fraction(GATE_28A_MAX_SINGLE_LOT_SHARE)

    if distinct_gmp_lots_n < GATE_28A_DISTINCT_LOTS_MIN:
        failure_reasons.append(
            f"distinct_gmp_lots_n={distinct_gmp_lots_n} < required minimum {GATE_28A_DISTINCT_LOTS_MIN}."
        )
    if distinct_mcb_n < GATE_28A_DISTINCT_MCB_MIN:
        failure_reasons.append(
            f"distinct_mcb_n={distinct_mcb_n} < required minimum {GATE_28A_DISTINCT_MCB_MIN} (single-bank risk blocked)."
        )
    if max_single_lot_share_frac > max_share_cap_frac:
        failure_reasons.append(
            f"max_single_lot_share={float(max_single_lot_share_frac):.4f} ({max_single_lot_n}/{n}) > allowed cap {float(max_share_cap_frac):.2f}."
        )

    if icc_domain_invalid:
        cp_lo, cp_hi = clopper_pearson_ci(k, n)
        external_clinical_store_verified = (
            prespec_verified and source_verified and store_manifest_verified and cmc_ledger_verified
        )
        return {
            "status": "HOLD_H1_AT_88PCT",
            "promotion_authorized": False,
            "external_clinical_store_verified": external_clinical_store_verified,
            "cohort_id": cohort_id,
            "cohort_canonical_sha256": cohort_canonical_sha256,
            "cohort_ledger_sha256": cohort_canonical_sha256,
            "lot_bank_hierarchy_valid": True,
            "lot_to_mcb_manifest_verified": store_manifest_verified,
            "lot_to_wcb_manifest_verified": store_wcb_verified,
            "prespecification_attestation_verified": prespec_verified,
            "source_verification_attestation_verified": source_verified,
            "parallel_cmc_ledger_verified": cmc_ledger_verified,
            "icc_sensitivity_report_attached": False,
            "icc_sensitivity_report": None,
            "boundary_sensitive_under_high_icc": False,
            "icc_sensitivity_review_status": None,
            "self_attested_inline_records_rejected": self_attested_inline_rejected,
            "trusted_clinical_store_resolution_source": trusted_store_source,
            "authenticated_store_record_sha256": authenticated_store_digests,
            "authenticated_store_issuer_authorities": authenticated_store_issuers,
            "parallel_cmc_readiness_summary": parallel_cmc_summary,
            "trusted_clinical_store_deployment_dependency": TRUSTED_CLINICAL_STORE_DEPLOYMENT_DEPENDENCY,
            "k": k,
            "n": n,
            "observed_rate_pct": round(100.0 * k / n, 4),
            "clopper_pearson_95_ci_pct": [round(100.0 * cp_lo, 2), round(100.0 * cp_hi, 2)],
            "clopper_pearson_95_ci_scope": "NOMINAL_IID_UNADJUSTED_RECIPIENT_COUNTS_ONLY_NOT_CLUSTER_ADJUSTED",
            "distinct_gmp_lots_n": distinct_gmp_lots_n,
            "distinct_mcb_n": distinct_mcb_n,
            "max_single_lot_n": max_single_lot_n,
            "max_single_lot_share": round(float(max_single_lot_share_frac), 6),
            "rho_lot": float(rho_lot_dec) if rho_lot_dec is not None else None,
            "rho_bank": float(rho_bank_dec) if rho_bank_dec is not None else None,
            "icc_variance_component_sum": (
                round(float(Fraction(rho_lot_dec) + Fraction(rho_bank_dec)), 6)
                if (rho_lot_dec is not None and rho_bank_dec is not None)
                else None
            ),
            "icc_convention": "SEPARATE_VARIANCE_COMPONENTS_RHO_LOT_PLUS_RHO_BANK_LE_1",
            "deff": None,
            "n_eff": None,
            "k_eff": None,
            "uniform_cluster_adjusted_p_ge_90": None,
            "anchored_cluster_adjusted_p_ge_90": None,
            "intercurrent_event_counts": ie_counts,
            "secondary_steroid_exposed_c2b_count_excluded_from_primary": secondary_steroid_exposed_c2b,
            "failure_reasons": failure_reasons,
        }

    m_eff_lot = sum(m * m for m in lot_counts.values()) / float(n)
    m_eff_bank = sum(b * b for b in bank_counts.values()) / float(n)
    deff = 1.0 + rho_lot * (m_eff_lot - 1.0) + rho_bank * (m_eff_bank - 1.0)
    n_eff = float(n) / deff
    k_eff = n_eff * (float(k) / float(n))

    p_unif_eff_ge_90 = 1.0 - beta_cdf(0.90, 1.0 + k_eff, 1.0 + (n_eff - k_eff))
    p_anch_eff_ge_90 = 1.0 - beta_cdf(0.90, 8.8 + k_eff, 1.2 + (n_eff - k_eff))
    p_unif_nom_ge_90 = 1.0 - beta_cdf(0.90, 1.0 + k, 1.0 + (n - k))
    cp_lo, cp_hi = clopper_pearson_ci(k, n)

    icc_sensitivity_report, boundary_sensitive_under_high_icc, icc_sensitivity_review_status = (
        _compute_gate28a_icc_sensitivity_report(k, n, m_eff_lot, m_eff_bank)
    )
    icc_sensitivity_report_attached = True

    if p_unif_eff_ge_90 < 0.90:
        failure_reasons.append(
            f"Cluster-adjusted Uniform Beta(1,1) P(H1>=0.90)={p_unif_eff_ge_90:.6f} < 0.90 "
            f"(k={k}, n={n}, DEFF={deff:.4f}, k_eff={k_eff:.4f}, n_eff={n_eff:.4f})."
        )
    if p_anch_eff_ge_90 < 0.85:
        failure_reasons.append(
            f"Cluster-adjusted non-Reichman Beta(8.8,1.2) P(H1>=0.90)={p_anch_eff_ge_90:.6f} < 0.85 "
            f"(k_eff={k_eff:.4f}, n_eff={n_eff:.4f})."
        )
    if icc_sensitivity_review_status == "HOLD_FAILS_PRIMARY_ICC_FLOOR":
        pf = icc_sensitivity_report["primary_floor"]
        failure_reasons.append(
            f"HOLD_FAILS_PRIMARY_ICC_FLOOR: prespecified primary ICC floor (rho_lot=0.05, rho_mcb=0.02) "
            f"fails Gate 28-A reanchor bar (DEFF={pf['deff_cluster']:.6f}, n_eff={pf['n_eff']:.6f}, "
            f"Uniform P(H1>=0.90)={pf['posterior_p_ge_090']:.6f}, Anchored P(H1>=0.90)={pf['anchored_posterior_p_ge_090']:.6f})."
        )
    elif icc_sensitivity_review_status == "HOLD_FAILS_MODERATE_ICC_SENSITIVITY":
        ms = icc_sensitivity_report["moderate_sensitivity"]
        failure_reasons.append(
            f"HOLD_FAILS_MODERATE_ICC_SENSITIVITY: prespecified moderate ICC sensitivity scenario "
            f"(rho_lot=0.10, rho_mcb=0.05) fails Gate 28-A reanchor bar (DEFF={ms['deff_cluster']:.6f}, "
            f"n_eff={ms['n_eff']:.6f}, Uniform P(H1>=0.90)={ms['posterior_p_ge_090']:.6f}, "
            f"Anchored P(H1>=0.90)={ms['anchored_posterior_p_ge_090']:.6f}); promotion blocked."
        )

    external_clinical_store_verified = (
        prespec_verified and source_verified and store_manifest_verified and cmc_ledger_verified
    )
    icc_sensitivity_allows_promotion = icc_sensitivity_review_status in (
        "ROBUST_ACROSS_ALL_THREE_PRESPECIFIED_ICC_SCENARIOS",
        "BOUNDARY_SENSITIVE_DISCLOSED_CLEARS_PRIMARY_AND_MODERATE",
    )
    promoted = (
        (len(failure_reasons) == 0)
        and external_clinical_store_verified
        and icc_sensitivity_report_attached
        and icc_sensitivity_allows_promotion
    )
    return {
        "status": "PROMOTE_H1_88_TO_90" if promoted else "HOLD_H1_AT_88PCT",
        "promotion_authorized": promoted,
        "external_clinical_store_verified": external_clinical_store_verified,
        "cohort_id": cohort_id,
        "cohort_canonical_sha256": cohort_canonical_sha256,
        "cohort_ledger_sha256": cohort_canonical_sha256,
        "lot_bank_hierarchy_valid": True,
        "lot_to_mcb_manifest_verified": store_manifest_verified,
        "lot_to_wcb_manifest_verified": store_wcb_verified,
        "prespecification_attestation_verified": prespec_verified,
        "source_verification_attestation_verified": source_verified,
        "parallel_cmc_ledger_verified": cmc_ledger_verified,
        "icc_sensitivity_report_attached": icc_sensitivity_report_attached,
        "icc_sensitivity_report": icc_sensitivity_report,
        "boundary_sensitive_under_high_icc": boundary_sensitive_under_high_icc,
        "icc_sensitivity_review_status": icc_sensitivity_review_status,
        "self_attested_inline_records_rejected": self_attested_inline_rejected,
        "trusted_clinical_store_resolution_source": trusted_store_source,
        "authenticated_store_record_sha256": authenticated_store_digests,
        "authenticated_store_issuer_authorities": authenticated_store_issuers,
        "parallel_cmc_readiness_summary": parallel_cmc_summary,
        "trusted_clinical_store_deployment_dependency": TRUSTED_CLINICAL_STORE_DEPLOYMENT_DEPENDENCY,
        "k": k,
        "n": n,
        "observed_rate_pct": round(100.0 * k / n, 4),
        "clopper_pearson_95_ci_pct": [round(100.0 * cp_lo, 2), round(100.0 * cp_hi, 2)],
        "clopper_pearson_95_ci_scope": "NOMINAL_IID_UNADJUSTED_RECIPIENT_COUNTS_ONLY_NOT_CLUSTER_ADJUSTED",
        "distinct_gmp_lots_n": distinct_gmp_lots_n,
        "distinct_mcb_n": distinct_mcb_n,
        "max_single_lot_n": max_single_lot_n,
        "max_single_lot_share": round(float(max_single_lot_share_frac), 6),
        "rho_lot": rho_lot,
        "rho_bank": rho_bank,
        "icc_variance_component_sum": round(float(Fraction(rho_lot_dec) + Fraction(rho_bank_dec)), 6) if (rho_lot_dec is not None and rho_bank_dec is not None) else round(rho_lot + rho_bank, 6),
        "icc_convention": "SEPARATE_VARIANCE_COMPONENTS_RHO_LOT_PLUS_RHO_BANK_LE_1",
        "m_eff_lot": round(m_eff_lot, 6),
        "m_eff_bank": round(m_eff_bank, 6),
        "deff": round(deff, 6),
        "n_eff": round(n_eff, 6),
        "k_eff": round(k_eff, 6),
        "uniform_nominal_p_ge_90": round(p_unif_nom_ge_90, 6),
        "uniform_cluster_adjusted_p_ge_90": round(p_unif_eff_ge_90, 6),
        "anchored_cluster_adjusted_p_ge_90": round(p_anch_eff_ge_90, 6),
        "cluster_adjusted_probability_scope": (
            "PRESPECIFIED_DECISION_MODEL_QUANTITIES_CONDITIONAL_ON_ASSUMED_ICC_VARIANCE_COMPONENTS_NOT_INDEPENDENT_CALIBRATION"
        ),
        "intercurrent_event_counts": ie_counts,
        "secondary_steroid_exposed_c2b_count_excluded_from_primary": secondary_steroid_exposed_c2b,
        "glycemic_safety_companion_bpr19": (
            evaluate_h1_glycemic_safety_companion_bpr19(recipients)
            if any(
                any(
                    k_cgm in r
                    for k_cgm in (
                        "cgm_readings_mg_dL_weights",
                        "tbr_lt70_pct",
                        "tbr_lt54_pct",
                        "tar_gt250_pct",
                        "cgm_coverage_pct",
                        "adjudicated_level3_she_count",
                    )
                )
                for r in recipients
                if isinstance(r, dict)
            )
            else {
                "companion_metrics_provided": False,
                "status": "NOT_PROVIDED_IN_LEGACY_COHORT_PAYLOAD",
                "note": (
                    "Prespecified H1 efficacy decision is preserved unchanged; attach per-window CGM safety "
                    "fields (tbr_lt70_pct, tbr_lt54_pct, tar_gt250_pct, cgm_coverage_pct, "
                    "adjudicated_level3_she_count) when interpreting net glycemic safety (BPR-19)."
                ),
            }
        ),
        "failure_reasons": failure_reasons,
    }


def evaluate_h1_glycemic_safety_companion_bpr19(
    records: list[dict[str, Any]],
    *,
    min_cgm_coverage_pct: float = 70.0,
) -> dict[str, Any]:
    """
    BPR-19 companion net glycemic safety reporter for H1 cohorts (Battelino 2019, PMID:31177185;
    ADA Standards Section 6 / Table 6.3).

    Design invariants:
      - Preserves the prespecified H1 efficacy benchmark (HbA1c < 7.0%, TIR 70-180 mg/dL > 70%,
        0 clinician-adjudicated Level-3 assisted SHEs, quantitative positive stimulated C-peptide,
        >= 180 d follow-up) and its historical numerator unchanged.
      - Separately reports time below 70 mg/dL (< 4.0% target), Level-2 biochemical hypoglycemia
        below 54 mg/dL (< 1.0% target), time above 250 mg/dL (< 5.0% target), CGM sensor coverage
        (explicit incomplete sensor follow-up flag when missing or < 70.0%), and clinician-adjudicated
        Level-3 assisted severe hypoglycemic events for the exact same window.
      - An independently observed clinician-adjudicated Level-3 assisted SHE ALWAYS fails both
        H1 efficacy and net glycemic safety, even if the CGM reading distribution appears normal.
    """
    if not isinstance(records, list) or len(records) == 0:
        raise ValueError("records must be a non-empty list of participant records")

    per_record: list[dict[str, Any]] = []
    for idx, raw in enumerate(records):
        if not isinstance(raw, dict):
            raise ValueError(f"record[{idx}] must be a dict")
        rid = str(raw.get("recipient_id", f"REC-{idx + 1:03d}"))

        # Optional discrete reading distribution: list of (glucose_mg_dL, weight) pairs
        mean_mg_dl: float | None = None
        tir_pct = raw.get("tir_70_180_pct")
        tbr70_pct = raw.get("tbr_lt70_pct")
        tbr54_pct = raw.get("tbr_lt54_pct")
        tar180_pct = raw.get("tar_gt180_pct")
        tar250_pct = raw.get("tar_gt250_pct")

        dist_pairs = raw.get("cgm_readings_mg_dL_weights")
        if dist_pairs is not None:
            if not isinstance(dist_pairs, list) or len(dist_pairs) == 0:
                raise ValueError(f"{rid}: cgm_readings_mg_dL_weights must be a non-empty list")
            total_w = 0.0
            mean_acc = 0.0
            w_tir = w_lt70 = w_lt54 = w_gt180 = w_gt250 = 0.0
            for pair in dist_pairs:
                g_val = float(pair[0])
                w_val = float(pair[1])
                if not (math.isfinite(g_val) and math.isfinite(w_val)) or w_val < 0.0:
                    raise ValueError(f"{rid}: invalid (glucose, weight) pair {pair!r}")
                total_w += w_val
                mean_acc += g_val * w_val
                if 70.0 <= g_val <= 180.0:
                    w_tir += w_val
                if g_val < 70.0:
                    w_lt70 += w_val
                if g_val < 54.0:
                    w_lt54 += w_val
                if g_val > 180.0:
                    w_gt180 += w_val
                if g_val > 250.0:
                    w_gt250 += w_val
            if total_w <= 0.0:
                raise ValueError(f"{rid}: cgm_readings_mg_dL_weights sum must be > 0")
            mean_mg_dl = mean_acc / total_w
            tir_pct = 100.0 * w_tir / total_w
            tbr70_pct = 100.0 * w_lt70 / total_w
            tbr54_pct = 100.0 * w_lt54 / total_w
            tar180_pct = 100.0 * w_gt180 / total_w
            tar250_pct = 100.0 * w_gt250 / total_w

        hba1c_pct = raw.get("hba1c_pct")
        cpep_pos = raw.get("stimulated_c_peptide_positive")
        followup_days = raw.get("followup_days", 180.0)
        she_raw = raw.get("adjudicated_level3_she_count")
        she_count = int(she_raw) if (she_raw is not None and type(she_raw) is not bool) else None
        cov_raw = raw.get("cgm_coverage_pct")
        cov_pct = float(cov_raw) if (cov_raw is not None and type(cov_raw) is not bool) else None

        # Prespecified H1 efficacy composite (preserved untouched)
        if "meets_h1_efficacy_override" in raw:
            meets_h1_eff = bool(raw["meets_h1_efficacy_override"]) and (she_count == 0)
        else:
            meets_h1_eff = (
                (hba1c_pct is not None and float(hba1c_pct) < 7.0)
                and (tir_pct is not None and float(tir_pct) > 70.0)
                and (she_count is not None and she_count == 0)
                and (cpep_pos is True)
                and (float(followup_days) >= 180.0)
            )

        incomplete_sensor_followup = (
            cov_pct is None
            or not math.isfinite(cov_pct)
            or cov_pct < float(min_cgm_coverage_pct)
            or tbr70_pct is None
            or tbr54_pct is None
            or tar250_pct is None
        )

        safety_flags: list[str] = []
        if she_count is None:
            safety_flags.append("MISSING_LEVEL3_SHE_ADJUDICATION")
        elif she_count > 0:
            safety_flags.append(f"CLINICIAN_ADJUDICATED_LEVEL3_ASSISTED_SHE_COUNT={she_count}")

        if incomplete_sensor_followup:
            safety_flags.append(
                f"INCOMPLETE_SENSOR_FOLLOWUP(coverage={cov_pct!r}<{min_cgm_coverage_pct:.1f}%_or_missing_cgm_safety_fields)"
            )
        else:
            if float(tbr70_pct) >= 4.0:
                safety_flags.append(f"TBR_LT70_EXCEEDS_ADA_4PCT({float(tbr70_pct):.2f}%)")
            if float(tbr54_pct) >= 1.0:
                safety_flags.append(f"LEVEL2_BIOCHEMICAL_HYPO_TBR_LT54_EXCEEDS_ADA_1PCT({float(tbr54_pct):.2f}%)")
            if float(tar250_pct) >= 5.0:
                safety_flags.append(f"TAR_GT250_EXCEEDS_ADA_5PCT({float(tar250_pct):.2f}%)")

        # Strict precedence: Level-3 assisted SHE ALWAYS fails safety regardless of normal CGM
        if she_count is not None and she_count > 0:
            safety_status = "FAIL_LEVEL3_ASSISTED_SHE"
            passes_net_safety = False
        elif incomplete_sensor_followup or she_count is None:
            safety_status = "INCOMPLETE_SENSOR_FOLLOWUP"
            passes_net_safety = False
        elif len(safety_flags) > 0:
            safety_status = "FAIL_BIOCHEMICAL_HYPO_OR_HYPERGLYCEMIA"
            passes_net_safety = False
        else:
            safety_status = "PASS_ADA_CGM_SAFETY_COMPANION"
            passes_net_safety = True

        per_record.append({
            "recipient_id": rid,
            "meets_h1_efficacy_benchmark": meets_h1_eff,
            "passes_net_glycemic_safety_companion": passes_net_safety,
            "net_glycemic_safety_status": safety_status,
            "incomplete_sensor_followup": incomplete_sensor_followup,
            "mean_glucose_mg_dL": round(mean_mg_dl, 4) if mean_mg_dl is not None else None,
            "hba1c_pct": round(float(hba1c_pct), 4) if hba1c_pct is not None else None,
            "tir_70_180_pct": round(float(tir_pct), 4) if tir_pct is not None else None,
            "tbr_lt70_pct": round(float(tbr70_pct), 4) if tbr70_pct is not None else None,
            "tbr_lt54_pct": round(float(tbr54_pct), 4) if tbr54_pct is not None else None,
            "tar_gt180_pct": round(float(tar180_pct), 4) if tar180_pct is not None else None,
            "tar_gt250_pct": round(float(tar250_pct), 4) if tar250_pct is not None else None,
            "cgm_coverage_pct": round(cov_pct, 4) if cov_pct is not None else None,
            "adjudicated_level3_she_count": she_count,
            "safety_flags": safety_flags,
        })

    n_tot = len(per_record)
    n_h1 = sum(1 for r in per_record if r["meets_h1_efficacy_benchmark"])
    n_safe = sum(1 for r in per_record if r["passes_net_glycemic_safety_companion"])
    n_inc = sum(1 for r in per_record if r["incomplete_sensor_followup"])
    n_she = sum(1 for r in per_record if (r["adjudicated_level3_she_count"] or 0) > 0)
    return {
        "audit_id": "BPR-19",
        "companion_metrics_provided": True,
        "preserves_prespecified_h1_efficacy_benchmark": True,
        "min_cgm_coverage_pct_required": float(min_cgm_coverage_pct),
        "ada_adult_consensus_targets": {
            "tbr_lt70_pct_lt": 4.0,
            "tbr_lt54_level2_biochemical_hypo_pct_lt": 1.0,
            "tar_gt250_pct_lt": 5.0,
            "adjudicated_level3_assisted_she_count_eq": 0,
        },
        "n_records": n_tot,
        "n_meeting_h1_efficacy_benchmark": n_h1,
        "n_passing_net_glycemic_safety_companion": n_safe,
        "n_h1_efficacy_pass_but_safety_fail_or_incomplete": sum(
            1 for r in per_record if r["meets_h1_efficacy_benchmark"] and not r["passes_net_glycemic_safety_companion"]
        ),
        "n_incomplete_sensor_followup": n_inc,
        "n_with_clinician_adjudicated_level3_she": n_she,
        "records": per_record,
    }


def evaluate_bpr06_baseline_attribution(record: dict[str, Any]) -> dict[str, Any]:
    """
    BPR-06 clinical baseline and graft-benefit attribution evaluator (Igls consensus & Stage 5
    indication separation between early-onset insulin-deficient T1D and early/longstanding LADA).

    Rules:
      - Requires explicit declaration of age_at_implantation_years, baseline endogenous C-peptide
        status, baseline insulin use, baseline severe hypoglycemia history, and background care.
      - When pre-implant endogenous C-peptide is measurable and ONLY post-implant positive
        C-peptide (without graft-attributed change from baseline) is supplied, returns
        `attribution_status = "ATTRIBUTION_UNRESOLVED"` ("attribution unresolved").
      - In an insulin-deficient recipient (undetectable baseline C-peptide), improved glycemic
        control (e.g., delta_tir_pct > 0 or delta_hba1c_pct < 0) with continued exogenous insulin
        is explicitly recognized as partial clinical benefit rather than zero benefit.
    """
    if not isinstance(record, dict):
        raise ValueError("record must be a dict")
    required_baseline_fields = (
        "age_at_implantation_years",
        "baseline_endogenous_c_peptide_measurable",
        "baseline_exogenous_insulin_u_per_day",
        "baseline_severe_hypo_events_prior_12mo",
        "background_care_regimen",
    )
    missing_fields = [f for f in required_baseline_fields if record.get(f) is None]
    base_cpep_meas = record.get("baseline_endogenous_c_peptide_measurable")
    post_cpep_pos = record.get("post_implant_c_peptide_positive")
    delta_cpep = record.get("delta_stimulated_c_peptide_ng_ml")
    delta_tir = record.get("delta_tir_pct")
    delta_hba1c = record.get("delta_hba1c_pct")
    continued_insulin = bool(record.get("post_implant_continued_exogenous_insulin", False))

    if missing_fields:
        status = "ATTRIBUTION_UNRESOLVED"
        label = "attribution unresolved"
        reason = f"Missing required baseline stratification fields: {', '.join(missing_fields)}."
    elif base_cpep_meas is True:
        # Measurable pre-implant C-peptide (e.g., early LADA): post-implant positivity alone proves nothing
        has_verified_change = (
            (delta_cpep is not None and float(delta_cpep) > 0.0 and record.get("graft_specific_attribution_verified") is True)
            and (
                (delta_tir is not None and float(delta_tir) > 0.0)
                or (delta_hba1c is not None and float(delta_hba1c) < 0.0)
            )
        )
        if not has_verified_change:
            status = "ATTRIBUTION_UNRESOLVED"
            label = "attribution unresolved"
            reason = (
                "Pre-implant endogenous C-peptide is measurable; post-implant positive C-peptide or "
                "insulin freedom alone cannot separate graft function from residual native beta cells "
                "without verified graft-attributed change from baseline."
            )
        else:
            status = "GRAFT_ATTRIBUTED_CHANGE_FROM_BASELINE"
            label = "graft-attributed improvement over measurable baseline"
            reason = "Verified graft-attributed C-peptide increment accompanied by improved glycemic outcomes."
    else:
        # Insulin-deficient baseline (undetectable baseline C-peptide)
        improved_glycemic = (
            (delta_tir is not None and float(delta_tir) > 0.0)
            or (delta_hba1c is not None and float(delta_hba1c) < 0.0)
        )
        if post_cpep_pos is True and improved_glycemic and continued_insulin:
            status = "PARTIAL_CLINICAL_BENEFIT_RECOGNIZED_WITH_CONTINUED_INSULIN"
            label = "partial clinical benefit with continued insulin"
            reason = (
                "Insulin-deficient recipient achieved graft-derived C-peptide and improved glycemic control "
                "while continuing reduced exogenous insulin (recognized as genuine clinical benefit per BPR-06/Igls)."
            )
        elif post_cpep_pos is True and improved_glycemic and not continued_insulin:
            status = "INSULIN_INDEPENDENT_CLINICAL_BENEFIT_FROM_DEFICIENT_BASELINE"
            label = "insulin-independent clinical benefit from insulin-deficient baseline"
            reason = "Insulin-deficient recipient achieved graft-derived C-peptide and improved glycemia without exogenous insulin."
        else:
            status = "ATTRIBUTION_UNRESOLVED"
            label = "attribution unresolved"
            reason = "Insufficient post-implant change-from-baseline glycemic or C-peptide evidence."

    return {
        "audit_id": "BPR-06",
        "attribution_status": status,
        "attribution_label": label,
        "missing_baseline_fields": missing_fields,
        "baseline_endogenous_c_peptide_measurable": base_cpep_meas,
        "post_implant_c_peptide_positive": post_cpep_pos,
        "continued_exogenous_insulin": continued_insulin,
        "reason": reason,
    }


def _run_gate28a_and_cmc_unit_tests() -> dict[str, Any]:
    """Executable unit & adversarial tests for B1 (CMC attempted-lot readiness, pooled reconciliation, order-independence, orphan rescue rejection) and B2 (Gate 28-A lot->MCB hierarchy, manifest, cohort-bound attestations, clustering, context independence)."""
    cases: list[dict[str, Any]] = []

    def _expect_cmc_value_error(label: str, bad_ledger: list[dict[str, Any]]) -> None:
        try:
            res = evaluate_cmc_attempted_lot_readiness(bad_ledger)
        except ValueError:
            cases.append({"case": label, "passed": True, "rejected_with_value_error": True})
            return
        raise ValueError(f"CMC negative test {label} unexpectedly succeeded: {res}")

    # 1. B1 exact worked example: P_release=0.80, P_infuse_given_released=0.50, H1=0.88 -> projected 0.352 (35.2%), measured 0.40!
    ledger_ex: list[dict[str, Any]] = []
    for i in range(1, 3):
        ledger_ex.append({
            "lot_id": f"LOT-FAIL-{i}", "mcb_id": "MCB-1", "lot_type": "SINGLE_RECIPIENT",
            "disposition": "FAILED_RELEASE", "planned_doses_n": 1, "infused_doses_n": 0,
            "c2b_responder_doses_n": 0, "recipient_ids": [], "recipient_outcomes": {},
        })
    for i in range(1, 5):
        ledger_ex.append({
            "lot_id": f"LOT-UNINF-{i}", "mcb_id": "MCB-1", "lot_type": "SINGLE_RECIPIENT",
            "disposition": "RELEASED_UNINFUSED", "planned_doses_n": 1, "infused_doses_n": 0,
            "c2b_responder_doses_n": 0, "recipient_ids": [], "recipient_outcomes": {},
        })
    for i in range(1, 5):
        ledger_ex.append({
            "lot_id": f"LOT-INF-{i}", "mcb_id": "MCB-1", "lot_type": "SINGLE_RECIPIENT",
            "disposition": "RELEASED_INFUSED", "planned_doses_n": 1, "infused_doses_n": 1,
            "c2b_responder_doses_n": 1, "recipient_ids": [f"REC-EX-{i}"],
            "recipient_outcomes": {f"REC-EX-{i}": 1},
        })
    cmc_ex = evaluate_cmc_attempted_lot_readiness(ledger_ex, h1_blueprint_override=0.88)
    if not (
        abs(cmc_ex["p_release_cmc"] - 0.80) < 1e-9
        and abs(cmc_ex["p_infuse_given_released"] - 0.50) < 1e-9
        and abs(cmc_ex["projected_cmc_attempted_lot_readiness"] - 0.352) < 1e-9
        and abs(cmc_ex["h1_cmc_attempted_lot_readiness"] - 0.352) < 1e-9
        and abs(cmc_ex["measured_weighted_cmc_readiness"] - 0.40) < 1e-9
        and abs(cmc_ex["diagnostic_omitted_infusion_product"] - 0.704) < 1e-9
        and cmc_ex["uninfused_released_lots_n"] == 4
        and cmc_ex["unique_clinical_recipients_n"] == 4
    ):
        raise ValueError(f"B1 CMC worked example check failed: {cmc_ex}")
    cases.append({"case": "b1_cmc_worked_example_0p80_0p50_0p88_equals_0p352", "passed": True, "projected": cmc_ex["projected_cmc_attempted_lot_readiness"], "measured": cmc_ex["measured_weighted_cmc_readiness"]})

    # 2. B1 split-lot recipient-weighted infusion & unused aliquot=0 (projected vs measured separated!)
    cmc_split = evaluate_cmc_attempted_lot_readiness([
        {
            "lot_id": "LOT-SPLIT-1", "mcb_id": "MCB-1", "lot_type": "SPLIT_LOT",
            "disposition": "RELEASED_INFUSED", "planned_doses_n": 4, "infused_doses_n": 3,
            "c2b_responder_doses_n": 3, "recipient_ids": ["REC-S1", "REC-S2", "REC-S3"],
            "recipient_outcomes": {"REC-S1": 1, "REC-S2": 1, "REC-S3": 1},
        }
    ])
    if not (
        abs(cmc_split["p_release_cmc"] - 1.0) < 1e-9
        and abs(cmc_split["p_infuse_given_released"] - 0.75) < 1e-9
        and abs(cmc_split["projected_cmc_attempted_lot_readiness"] - 0.66) < 1e-9
        and abs(cmc_split["measured_weighted_cmc_readiness"] - 0.75) < 1e-9
        and abs(cmc_split["empirical_product_readiness"] - 0.75) < 1e-9
        and cmc_split["unique_clinical_recipients_n"] == 3
    ):
        raise ValueError(f"B1 split-lot check failed: {cmc_split}")
    cases.append({"case": "b1_cmc_split_lot_recipient_weighted_accounting", "passed": True, "projected": cmc_split["projected_cmc_attempted_lot_readiness"], "measured": cmc_split["measured_weighted_cmc_readiness"]})

    # 3. B1 valid 2-lot pooled course: matching conditioning (1.0 infused course-equiv / 2 lots = 0.50) AND outcome (1.0 / 2 = 0.50)!
    cmc_multi = evaluate_cmc_attempted_lot_readiness([
        {
            "lot_id": "LOT-ML-1", "mcb_id": "MCB-1", "lot_type": "MULTI_LOT_COURSE_PRIMARY",
            "disposition": "RELEASED_INFUSED", "planned_doses_n": 1, "infused_doses_n": 1,
            "c2b_responder_doses_n": 1, "recipient_ids": ["REC-ML1"], "recipient_outcomes": {"REC-ML1": 1},
            "pooled_course_id": "COURSE-001", "pooled_lot_count": 2, "primary_lot_id": "LOT-ML-1",
            "pooled_course_lot_ids": ["LOT-ML-1", "LOT-ML-2"],
        },
        {
            "lot_id": "LOT-ML-2", "mcb_id": "MCB-1", "lot_type": "MULTI_LOT_COURSE_CONSTITUENT",
            "disposition": "RELEASED_INFUSED", "planned_doses_n": 1, "infused_doses_n": 1,
            "c2b_responder_doses_n": 1, "recipient_ids": ["REC-ML1"], "recipient_outcomes": {"REC-ML1": 1},
            "pooled_course_id": "COURSE-001", "pooled_lot_count": 2, "primary_lot_id": "LOT-ML-1",
            "pooled_course_lot_ids": ["LOT-ML-1", "LOT-ML-2"],
        },
    ])
    if not (
        cmc_multi["attempted_lots_n"] == 2
        and cmc_multi["released_lots_n"] == 2
        and abs(cmc_multi["infused_lot_equivalents"] - 1.0) < 1e-9
        and abs(cmc_multi["p_infuse_given_released"] - 0.50) < 1e-9
        and cmc_multi["unique_clinical_recipients_n"] == 1
        and cmc_multi["clinical_primary_responders_n"] == 1
        and abs(cmc_multi["lot_weighted_primary_successes"] - 1.0) < 1e-9
        and abs(cmc_multi["measured_weighted_cmc_readiness"] - 0.50) < 1e-9
        and abs(cmc_multi["empirical_product_readiness"] - 0.50) < 1e-9
        and abs(cmc_multi["projected_cmc_attempted_lot_readiness"] - 0.44) < 1e-9
    ):
        raise ValueError(f"B1 multi-lot course check failed: {cmc_multi}")
    cases.append({"case": "b1_cmc_multilot_course_matching_conditioning_and_outcome_weights", "passed": True, "infused_equiv": cmc_multi["infused_lot_equivalents"], "measured": cmc_multi["measured_weighted_cmc_readiness"], "projected": cmc_multi["projected_cmc_attempted_lot_readiness"]})

    # 4. B1 unplanned rescue repeat-lot infusion forces primary single-infusion outcome to 0 and w_infuse=0 on rescue lot!
    cmc_resc = evaluate_cmc_attempted_lot_readiness([
        {
            "lot_id": "LOT-INIT-1", "mcb_id": "MCB-1", "lot_type": "SINGLE_RECIPIENT",
            "disposition": "RELEASED_INFUSED", "planned_doses_n": 1, "infused_doses_n": 1,
            "c2b_responder_doses_n": 0, "recipient_ids": ["REC-R1"], "recipient_outcomes": {"REC-R1": 0},
        },
        {
            "lot_id": "LOT-RESC-1", "mcb_id": "MCB-1", "lot_type": "RESCUE_REPEAT_LOT",
            "disposition": "RELEASED_INFUSED", "planned_doses_n": 1, "infused_doses_n": 1,
            "c2b_responder_doses_n": 1, "recipient_ids": ["REC-R1"], "recipient_outcomes": {"REC-R1": 1},
            "rescued_recipient_id": "REC-R1", "rescued_primary_lot_id": "LOT-INIT-1",
        },
    ])
    if not (
        cmc_resc["attempted_lots_n"] == 2
        and cmc_resc["rescue_lots_n"] == 1
        and abs(cmc_resc["infused_lot_equivalents"] - 1.0) < 1e-9
        and abs(cmc_resc["p_infuse_given_released"] - 0.50) < 1e-9
        and cmc_resc["unique_clinical_recipients_n"] == 1
        and cmc_resc["clinical_primary_responders_n"] == 0
        and abs(cmc_resc["lot_weighted_primary_successes"] - 0.0) < 1e-9
        and abs(cmc_resc["measured_weighted_cmc_readiness"] - 0.0) < 1e-9
        and abs(cmc_resc["projected_cmc_attempted_lot_readiness"] - 0.44) < 1e-9
    ):
        raise ValueError(f"B1 rescue repeat-lot check failed: {cmc_resc}")
    cases.append({"case": "b1_cmc_rescue_repeat_lot_forces_primary_nonresponder", "passed": True, "measured": cmc_resc["measured_weighted_cmc_readiness"]})

    # 5. B1 adversarial: incomplete 2-lot pooled course (missing constituent row) MUST raise ValueError!
    _expect_cmc_value_error(
        "b1_cmc_reject_incomplete_pooled_course_missing_constituent",
        [
            {
                "lot_id": "LOT-INC-1", "mcb_id": "MCB-1", "lot_type": "MULTI_LOT_COURSE_PRIMARY",
                "disposition": "RELEASED_INFUSED", "planned_doses_n": 1, "infused_doses_n": 1,
                "recipient_outcomes": {"REC-INC": 1}, "pooled_course_id": "C-INC", "pooled_lot_count": 2,
                "primary_lot_id": "LOT-INC-1", "pooled_course_lot_ids": ["LOT-INC-1", "LOT-INC-2"],
            }
        ],
    )

    # 6. B1 adversarial: 2-lot pooled course with conflicting primary_lot_id MUST raise ValueError!
    _expect_cmc_value_error(
        "b1_cmc_reject_pooled_course_conflicting_primary_lot_id",
        [
            {
                "lot_id": "LOT-CONF-1", "mcb_id": "MCB-1", "lot_type": "MULTI_LOT_COURSE_PRIMARY",
                "disposition": "RELEASED_INFUSED", "planned_doses_n": 1, "infused_doses_n": 1,
                "recipient_outcomes": {"REC-CONF": 1}, "course_id": "C-CONF", "primary_lot_id": "LOT-CONF-1",
                "course_lot_ids": ["LOT-CONF-1", "LOT-CONF-2"],
            },
            {
                "lot_id": "LOT-CONF-2", "mcb_id": "MCB-1", "lot_type": "MULTI_LOT_COURSE_CONSTITUENT",
                "disposition": "RELEASED_INFUSED", "planned_doses_n": 1, "infused_doses_n": 1,
                "recipient_outcomes": {"REC-CONF": 1}, "course_id": "C-CONF", "primary_lot_id": "LOT-CONF-2",
                "course_lot_ids": ["LOT-CONF-1", "LOT-CONF-2"],
            },
        ],
    )

    # 7. B1 adversarial: split-lot omitting explicit recipient_outcomes (positional-only) MUST raise ValueError!
    _expect_cmc_value_error(
        "b1_cmc_reject_split_lot_without_explicit_recipient_outcomes",
        [
            {
                "lot_id": "LOT-POS-1", "mcb_id": "MCB-1", "lot_type": "SPLIT_LOT",
                "disposition": "RELEASED_INFUSED", "planned_doses_n": 2, "infused_doses_n": 2,
                "c2b_responder_doses_n": 1, "recipient_ids": ["REC-A", "REC-B"],
            }
        ],
    )

    # 8. B1 adversarial: split-lot + rescue MUST be 100% invariant to recipient_ids order AND lot_ledger order!
    split_fwd = {
        "lot_id": "LOT-SP-INV", "mcb_id": "MCB-1", "lot_type": "SPLIT_LOT",
        "disposition": "RELEASED_INFUSED", "planned_doses_n": 2, "infused_doses_n": 2,
        "c2b_responder_doses_n": 1, "recipient_ids": ["REC-A", "REC-B"],
        "recipient_outcomes": {"REC-A": 1, "REC-B": 0},
    }
    split_rev = {
        "lot_id": "LOT-SP-INV", "mcb_id": "MCB-1", "lot_type": "SPLIT_LOT",
        "disposition": "RELEASED_INFUSED", "planned_doses_n": 2, "infused_doses_n": 2,
        "c2b_responder_doses_n": 1, "recipient_ids": ["REC-B", "REC-A"],
        "recipient_records": [{"recipient_id": "REC-B", "c2b_responder": False}, {"recipient_id": "REC-A", "c2b_responder": True}],
    }
    resc_b = {
        "lot_id": "LOT-RESC-B", "mcb_id": "MCB-1", "lot_type": "RESCUE_REPEAT_LOT",
        "disposition": "RELEASED_INFUSED", "planned_doses_n": 1, "infused_doses_n": 1,
        "c2b_responder_doses_n": 1, "recipient_ids": ["REC-B"], "recipient_outcomes": {"REC-B": 1},
        "rescued_recipient_id": "REC-B", "rescued_primary_lot_id": "LOT-SP-INV",
    }
    r_p1 = evaluate_cmc_attempted_lot_readiness([split_fwd, resc_b])
    r_p2 = evaluate_cmc_attempted_lot_readiness([split_rev, resc_b])
    r_p3 = evaluate_cmc_attempted_lot_readiness([resc_b, split_fwd])
    r_p4 = evaluate_cmc_attempted_lot_readiness([resc_b, split_rev])
    if not (
        r_p1 == r_p2 == r_p3 == r_p4
        and r_p1["clinical_primary_responders_n"] == 1
        and abs(r_p1["measured_weighted_cmc_readiness"] - 0.25) < 1e-9
        and abs(r_p1["empirical_product_readiness"] - 0.25) < 1e-9
        and abs(r_p1["projected_cmc_attempted_lot_readiness"] - 0.44) < 1e-9
    ):
        raise ValueError(f"B1 split+rescue order invariance failed: p1={r_p1}, p2={r_p2}, p3={r_p3}, p4={r_p4}")
    cases.append({"case": "b1_cmc_split_lot_plus_rescue_100pct_order_invariant", "passed": True, "measured": r_p1["measured_weighted_cmc_readiness"]})

    # 9. B1 adversarial: orphan rescue-only row MUST raise ValueError (NEVER fabricate a recipient)!
    _expect_cmc_value_error(
        "b1_cmc_reject_orphan_rescue_only_row",
        [
            {
                "lot_id": "LOT-ORPHAN-RESC", "mcb_id": "MCB-1", "lot_type": "RESCUE_REPEAT_LOT",
                "disposition": "RELEASED_INFUSED", "planned_doses_n": 1, "infused_doses_n": 1,
                "recipient_outcomes": {"REC-GHOST": 1},
                "rescued_recipient_id": "REC-GHOST", "rescued_primary_lot_id": "LOT-MISSING-INIT",
            }
        ],
    )

    # 10. R06 Blocking 1a: lot_id == course_id == "COLLIDE-1" for same recipient MUST raise ValueError in ALL orders!
    collide_single = {
        "lot_id": "COLLIDE-1", "mcb_id": "MCB-1", "lot_type": "SINGLE_RECIPIENT",
        "disposition": "RELEASED_INFUSED", "planned_doses_n": 1, "infused_doses_n": 1,
        "c2b_responder_doses_n": 0, "recipient_ids": ["REC-COL"], "recipient_outcomes": {"REC-COL": 0},
    }
    collide_ml1 = {
        "lot_id": "ML-COL-1", "mcb_id": "MCB-1", "lot_type": "MULTI_LOT_COURSE_PRIMARY",
        "disposition": "RELEASED_INFUSED", "planned_doses_n": 1, "infused_doses_n": 1,
        "c2b_responder_doses_n": 1, "recipient_ids": ["REC-COL"], "recipient_outcomes": {"REC-COL": 1},
        "course_id": "COLLIDE-1", "primary_lot_id": "ML-COL-1", "course_lot_ids": ["ML-COL-1", "ML-COL-2"],
    }
    collide_ml2 = {
        "lot_id": "ML-COL-2", "mcb_id": "MCB-1", "lot_type": "MULTI_LOT_COURSE_CONSTITUENT",
        "disposition": "RELEASED_INFUSED", "planned_doses_n": 1, "infused_doses_n": 1,
        "c2b_responder_doses_n": 1, "recipient_ids": ["REC-COL"], "recipient_outcomes": {"REC-COL": 1},
        "course_id": "COLLIDE-1", "primary_lot_id": "ML-COL-1", "course_lot_ids": ["ML-COL-1", "ML-COL-2"],
    }
    _expect_cmc_value_error("b1_r06_cmc_reject_single_and_pooled_id_collision_fwd", [collide_single, collide_ml1, collide_ml2])
    # Also test reverse lexical sort order where pooled lot_id sorts BEFORE single lot_id ("A-ML-1" < "Z-COLLIDE")
    collide_single_z = dict(collide_single, lot_id="Z-COLLIDE")
    collide_ml1_a = dict(collide_ml1, lot_id="A-ML-1", course_id="Z-COLLIDE", primary_lot_id="A-ML-1", course_lot_ids=["A-ML-1", "A-ML-2"])
    collide_ml2_a = dict(collide_ml2, lot_id="A-ML-2", course_id="Z-COLLIDE", primary_lot_id="A-ML-1", course_lot_ids=["A-ML-1", "A-ML-2"])
    _expect_cmc_value_error("b1_r06_cmc_reject_single_and_pooled_id_collision_rev", [collide_ml1_a, collide_ml2_a, collide_single_z])

    # 11. R06 Blocking 1b: Reordered equivalent pooled_course_lot_ids vs course_lot_ids SUCCEEDS cleanly (and duplicates/mismatches reject)!
    cmc_reord = evaluate_cmc_attempted_lot_readiness([
        {
            "lot_id": "LOT-ORD-1", "mcb_id": "MCB-1", "lot_type": "MULTI_LOT_COURSE_PRIMARY",
            "disposition": "RELEASED_INFUSED", "planned_doses_n": 1, "infused_doses_n": 1,
            "recipient_outcomes": {"REC-ORD": 1}, "pooled_course_id": "C-ORD", "course_id": "C-ORD",
            "primary_lot_id": "LOT-ORD-1",
            "pooled_course_lot_ids": ["LOT-ORD-1", "LOT-ORD-2"],
            "course_lot_ids": ["LOT-ORD-2", "LOT-ORD-1"],
        },
        {
            "lot_id": "LOT-ORD-2", "mcb_id": "MCB-1", "lot_type": "MULTI_LOT_COURSE_CONSTITUENT",
            "disposition": "RELEASED_INFUSED", "planned_doses_n": 1, "infused_doses_n": 1,
            "recipient_outcomes": {"REC-ORD": 1}, "pooled_course_id": "C-ORD", "course_id": "C-ORD",
            "primary_lot_id": "LOT-ORD-1",
            "pooled_course_lot_ids": ["LOT-ORD-2", "LOT-ORD-1"],
            "course_lot_ids": ["LOT-ORD-1", "LOT-ORD-2"],
        },
    ])
    if not (
        cmc_reord["unique_clinical_recipients_n"] == 1
        and abs(cmc_reord["infused_lot_equivalents"] - 1.0) < 1e-9
        and abs(cmc_reord["measured_weighted_cmc_readiness"] - 0.5) < 1e-9
    ):
        raise ValueError(f"R06 B1 reordered equivalent course_lot_ids aliases failed: {cmc_reord}")
    cases.append({"case": "b1_r06_cmc_accept_reordered_equivalent_course_lot_ids_aliases", "passed": True})
    _expect_cmc_value_error(
        "b1_r06_cmc_reject_duplicate_inside_course_lot_ids_alias",
        [
            {
                "lot_id": "LOT-DUP-1", "mcb_id": "MCB-1", "lot_type": "MULTI_LOT_COURSE_PRIMARY",
                "disposition": "RELEASED_INFUSED", "planned_doses_n": 1, "infused_doses_n": 1,
                "recipient_outcomes": {"REC-DUP": 1}, "course_id": "C-DUP", "primary_lot_id": "LOT-DUP-1",
                "pooled_course_lot_ids": ["LOT-DUP-1", "LOT-DUP-2"],
                "course_lot_ids": ["LOT-DUP-1", "LOT-DUP-1", "LOT-DUP-2"],
            },
            {
                "lot_id": "LOT-DUP-2", "mcb_id": "MCB-1", "lot_type": "MULTI_LOT_COURSE_CONSTITUENT",
                "disposition": "RELEASED_INFUSED", "planned_doses_n": 1, "infused_doses_n": 1,
                "recipient_outcomes": {"REC-DUP": 1}, "course_id": "C-DUP", "primary_lot_id": "LOT-DUP-1",
                "pooled_course_lot_ids": ["LOT-DUP-1", "LOT-DUP-2"],
            },
        ],
    )

    with tempfile.TemporaryDirectory() as tmp_g28a_dir:
        tmp_dir_p = pathlib.Path(tmp_g28a_dir)
        clin_store_json = tmp_dir_p / "gate28a_trusted_clinical_store.json"
        clin_store_dir = tmp_dir_p / "gate28a_trusted_clinical_store_dir"

        # 12. B2 skewed 21/21 (20 from Lot 1 + 1 from Lot 2, single bank) FAILS to promote even with trusted store!
        skewed_21 = [
            {
                "recipient_id": f"P-{i:02d}",
                "lot_id": "LOT-01" if i <= 20 else "LOT-02",
                "mcb_id": "MCB-A",
                "followup_months": 12.0,
                "met_c2b_criteria": True,
                "intercurrent_event": "NONE",
            }
            for i in range(1, 22)
        ]
        p_skew, _ = build_valid_gate28a_reference_bundle(clin_store_json, skewed_21, cohort_id="COHORT-SKEW-21")
        g28a_skew = evaluate_gate28a_h1_promotion(p_skew, trusted_clinical_store=clin_store_json)
        if g28a_skew["promotion_authorized"] is not False or g28a_skew["status"] != "HOLD_H1_AT_88PCT":
            raise ValueError(f"B2 skewed 20+1 21/21 MUST fail closed: {g28a_skew}")
        cases.append({"case": "b2_gate28a_skewed_20_plus_1_single_bank_21of21_fails", "passed": True, "n_eff": g28a_skew["n_eff"]})

        # 13. B2 balanced 3-lot 21/21 from a SINGLE bank STILL FAILS (single bank + n_eff < 21)!
        single_bank_21 = [
            {
                "recipient_id": f"SB-{i:02d}",
                "lot_id": f"LOT-{(i - 1) // 7 + 1}",
                "mcb_id": "MCB-ONLY",
                "followup_months": 12.0,
                "met_c2b_criteria": True,
                "intercurrent_event": "NONE",
            }
            for i in range(1, 22)
        ]
        p_sb, _ = build_valid_gate28a_reference_bundle(clin_store_json, single_bank_21, cohort_id="COHORT-SB-21")
        g28a_sb = evaluate_gate28a_h1_promotion(p_sb, trusted_clinical_store=clin_store_json)
        if g28a_sb["promotion_authorized"] is not False:
            raise ValueError(f"B2 single-bank 21/21 MUST fail closed: {g28a_sb}")
        cases.append({"case": "b2_gate28a_single_bank_3_lots_21of21_fails", "passed": True, "n_eff": g28a_sb["n_eff"]})

        # 14. B2 consistent single-bank 30/30 across 6 lots holds at n_eff=16.853933!
        single_bank_30 = [
            {
                "recipient_id": f"SB30-{i:02d}",
                "lot_id": f"LOT-{(i - 1) // 5 + 1}",
                "mcb_id": "MCB-SINGLE",
                "followup_months": 12.0,
                "met_c2b_criteria": True,
                "intercurrent_event": "NONE",
            }
            for i in range(1, 31)
        ]
        p_sb30, _ = build_valid_gate28a_reference_bundle(clin_store_json, single_bank_30, cohort_id="COHORT-SB-30")
        g28a_sb30 = evaluate_gate28a_h1_promotion(p_sb30, trusted_clinical_store=clin_store_json)
        if g28a_sb30["promotion_authorized"] is not False or g28a_sb30["distinct_mcb_n"] != 1 or abs(g28a_sb30["n_eff"] - 16.853933) > 1e-5:
            raise ValueError(f"B2 single-bank 30/30 check failed: {g28a_sb30}")
        cases.append({"case": "b2_gate28a_single_bank_6_lots_30of30_holds", "passed": True, "n_eff": g28a_sb30["n_eff"]})

        # 15. B2 well-replicated 45/45 across 15 lots (3 each) and 5 MCBs (9 each) WITH independent trusted_clinical_store
        #     (clears ALL THREE prespecified ICC scenarios) PROMOTES! (good_30 6-lot/3-MCB kept for moderate-ICC HOLD & negative controls.)
        good_30 = [
            {
                "recipient_id": f"G-{i:02d}",
                "lot_id": f"LOT-{(i - 1) // 5 + 1}",
                "mcb_id": f"MCB-{(i - 1) // 10 + 1}",
                "followup_months": 12.0,
                "met_c2b_criteria": True,
                "intercurrent_event": "NONE",
            }
            for i in range(1, 31)
        ]
        robust_45 = [
            {
                "recipient_id": f"G45-{i:02d}",
                "lot_id": f"LOT-{(i - 1) // 3 + 1}",
                "mcb_id": f"MCB-{(i - 1) // 9 + 1}",
                "followup_months": 12.0,
                "met_c2b_criteria": True,
                "intercurrent_event": "NONE",
            }
            for i in range(1, 46)
        ]
        p_good_json, good_recs = build_valid_gate28a_reference_bundle(clin_store_json, robust_45, cohort_id="COHORT-ROBUST-45")
        g28a_ok = evaluate_gate28a_h1_promotion(p_good_json, trusted_clinical_store=clin_store_json)
        if not (
            g28a_ok["promotion_authorized"] is True
            and g28a_ok["status"] == "PROMOTE_H1_88_TO_90"
            and g28a_ok["external_clinical_store_verified"] is True
            and g28a_ok["lot_bank_hierarchy_valid"] is True
            and g28a_ok["lot_to_mcb_manifest_verified"] is True
            and g28a_ok["parallel_cmc_ledger_verified"] is True
            and g28a_ok["icc_sensitivity_report_attached"] is True
            and g28a_ok["icc_sensitivity_review_status"] == "ROBUST_ACROSS_ALL_THREE_PRESPECIFIED_ICC_SCENARIOS"
        ):
            raise ValueError(f"B2 well-replicated 45/45 multi-bank cohort with trusted store should promote: {g28a_ok}")
        cases.append({"case": "b2_gate28a_replicated_45of45_15lots_5mcbs_promotes_with_trusted_store", "passed": True, "n_eff": g28a_ok["n_eff"]})

        # 16. R06 Blocking 2: Directory-layout trusted_clinical_store promotes identically to JSON registry store!
        write_gate28a_trusted_clinical_store(
            clin_store_dir,
            prespecification_attestations=[good_recs["prespecification_attestation"]],
            source_verification_attestations=[good_recs["source_verification_attestation"]],
            verified_lot_to_bank_manifests=[good_recs["verified_lot_to_bank_manifest"]],
            parallel_cmc_readiness_ledgers=[good_recs["parallel_cmc_readiness_ledger_bytes"]],
        )
        g28a_ok_dir = evaluate_gate28a_h1_promotion(p_good_json, trusted_clinical_store=clin_store_dir)
        if not (g28a_ok_dir["promotion_authorized"] is True and g28a_ok_dir["status"] == "PROMOTE_H1_88_TO_90" and g28a_ok_dir["external_clinical_store_verified"] is True):
            raise ValueError(f"R06 B2 directory trusted_clinical_store should promote: {g28a_ok_dir}")
        cases.append({"case": "b2_r06_gate28a_directory_store_promotes_identically", "passed": True})

        # 17. R06 Blocking 2: Self-attested inline records WITHOUT trusted_clinical_store MUST FAIL CLOSED!
        p_inline_only = build_valid_gate28a_cohort_payload(good_30, cohort_id="COHORT-INLINE-ONLY")
        g28a_inline = evaluate_gate28a_h1_promotion(p_inline_only, trusted_clinical_store=None)
        if not (
            g28a_inline["promotion_authorized"] is False
            and g28a_inline["status"] == "HOLD_H1_AT_88PCT"
            and g28a_inline["external_clinical_store_verified"] is False
            and g28a_inline["self_attested_inline_records_rejected"] is True
        ):
            raise ValueError(f"R06 B2 inline-only self-attested Gate 28-A MUST fail closed: {g28a_inline}")
        cases.append({"case": "b2_r06_gate28a_reject_inline_only_without_trusted_clinical_store", "passed": True})

        # 18. R06 Blocking 2: Post-attestation mutation of compatibility, overlap, ICC, or CMC hash MUST FAIL CLOSED!
        for mut_lbl, mut_key, mut_val in (
            ("transplant_site", "transplant_site", "ABDOMINAL_ANTERIOR_RECTUS_SHEATH"),
            ("includes_reichman", "includes_reichman", True),
            ("rho_lot", "rho_lot", 0.06),
            ("rho_bank", "rho_bank", 0.03),
            ("cmc_sha", "parallel_cmc_readiness_ledger_sha256", "0" * 64),
        ):
            p_mut = copy.deepcopy(p_good_json)
            p_mut[mut_key] = mut_val
            r_mut = evaluate_gate28a_h1_promotion(p_mut, trusted_clinical_store=clin_store_json)
            if r_mut["promotion_authorized"] is not False or r_mut["external_clinical_store_verified"] is not False:
                raise ValueError(f"R06 B2 post-attestation mutation ({mut_lbl}) MUST fail closed: {r_mut}")
        cases.append({"case": "b2_r06_gate28a_reject_post_attestation_mutation_of_declarations_and_icc", "passed": True})

        # 19. R06 Blocking 2: Missing, tampered, or unreconciled PARALLEL_CMC_READINESS_LEDGER bytes MUST FAIL CLOSED!
        # (a) Tampered bytes in store -> SHA-256 mismatch
        tampered_store = tmp_dir_p / "tampered_cmc_store.json"
        shutil_doc = load_strict_json_bytes(clin_store_json.read_bytes(), "copy_store")
        csha = good_recs["parallel_cmc_readiness_ledger_sha256"]
        shutil_doc["parallel_cmc_readiness_ledgers"][csha]["raw_payload_utf8"] += " "
        tampered_store.write_text(json.dumps(shutil_doc, indent=2, sort_keys=True) + "\n", encoding="utf-8")
        r_tamp_cmc = evaluate_gate28a_h1_promotion(p_good_json, trusted_clinical_store=tampered_store)
        # (b) Valid CMC bytes whose recipient list drops 1 clinical recipient -> reconciliation fails!
        unrec_store = tmp_dir_p / "unreconciled_cmc_store.json"
        partial_cmc = _derive_reconciling_cmc_lot_ledger_from_recipients(
            good_30[:-1], {f"LOT-{j}": f"MCB-{(j - 1) // 2 + 1}" for j in range(1, 7)}
        )
        p_unrec, _ = build_valid_gate28a_reference_bundle(
            unrec_store, good_30, cohort_id="COHORT-UNREC-CMC", parallel_cmc_lot_ledger=partial_cmc
        )
        r_unrec_cmc = evaluate_gate28a_h1_promotion(p_unrec, trusted_clinical_store=unrec_store)
        if not (
            r_tamp_cmc["promotion_authorized"] is False
            and r_tamp_cmc["parallel_cmc_ledger_verified"] is False
            and r_unrec_cmc["promotion_authorized"] is False
            and r_unrec_cmc["parallel_cmc_ledger_verified"] is False
        ):
            raise ValueError(f"R06 B2 tampered/unreconciled CMC ledger bytes MUST fail closed: {r_tamp_cmc} / {r_unrec_cmc}")
        cases.append({"case": "b2_r06_gate28a_reject_tampered_or_unreconciled_cmc_ledger_bytes", "passed": True})

        # 20. B2 adversarial counterexample: conflicting mcb_id inside same lot -> MUST HOLD BEFORE DEFF/n_eff!
        conflicting_mcb_30 = [
            {
                "recipient_id": f"CM-{i:02d}",
                "lot_id": f"LOT-{(i - 1) // 5 + 1}",
                "mcb_id": f"MCB-{(i - 1) % 3 + 1}",
                "followup_months": 12.0,
                "met_c2b_criteria": True,
                "intercurrent_event": "NONE",
            }
            for i in range(1, 31)
        ]
        g28a_conf_mcb = evaluate_gate28a_h1_promotion(
            build_valid_gate28a_cohort_payload(
                conflicting_mcb_30,
                cohort_id="COHORT-CONFLICT-MCB-30",
                lot_to_mcb_manifest={f"LOT-{j}": "MCB-1" for j in range(1, 7)},
            )
        )
        if (
            g28a_conf_mcb["promotion_authorized"] is not False
            or g28a_conf_mcb["status"] != "HOLD_H1_AT_88PCT"
            or g28a_conf_mcb["lot_bank_hierarchy_valid"] is not False
            or g28a_conf_mcb["deff"] is not None
            or g28a_conf_mcb["n_eff"] is not None
        ):
            raise ValueError(f"B2 conflicting lot->MCB cohort MUST fail closed before DEFF/n_eff: {g28a_conf_mcb}")
        cases.append({"case": "b2_gate28a_reject_conflicting_mcb_within_same_lot_before_deff", "passed": True})

        # 21. B2 adversarial: conflicting wcb_id within the same lot_id MUST fail closed before DEFF/n_eff!
        conflicting_wcb_30 = copy.deepcopy(good_30)
        for idx_r, rec in enumerate(conflicting_wcb_30):
            rec["wcb_id"] = "WCB-ALT" if idx_r == 1 else f"WCB-FOR-{rec['lot_id']}"
        g28a_conf_wcb = evaluate_gate28a_h1_promotion(
            build_valid_gate28a_cohort_payload(
                conflicting_wcb_30,
                cohort_id="COHORT-CONFLICT-WCB-30",
                lot_to_mcb_manifest={f"LOT-{j}": f"MCB-{(j - 1) // 2 + 1}" for j in range(1, 7)},
                lot_to_wcb_manifest={f"LOT-{j}": f"WCB-FOR-LOT-{j}" for j in range(1, 7)},
            )
        )
        if (
            g28a_conf_wcb["promotion_authorized"] is not False
            or g28a_conf_wcb["lot_bank_hierarchy_valid"] is not False
            or g28a_conf_wcb["deff"] is not None
            or g28a_conf_wcb["n_eff"] is not None
        ):
            raise ValueError(f"B2 conflicting lot->WCB cohort MUST fail closed before DEFF/n_eff: {g28a_conf_wcb}")
        cases.append({"case": "b2_gate28a_reject_conflicting_wcb_within_same_lot_before_deff", "passed": True})

        # 22. R06 Blocking 3a: Omitted or mismatched lot_to_mcb_manifest MUST return lot_bank_hierarchy_valid=False, deff=None, n_eff=None!
        p_no_manifest = copy.deepcopy(p_good_json)
        p_no_manifest.pop("lot_to_mcb_manifest")
        g28a_noman = evaluate_gate28a_h1_promotion(p_no_manifest, trusted_clinical_store=clin_store_json)
        g28a_noman_nostore = evaluate_gate28a_h1_promotion(p_no_manifest, trusted_clinical_store=None)
        p_bad_manifest = build_valid_gate28a_cohort_payload(
            good_30,
            cohort_id="COHORT-BADMAN",
            lot_to_mcb_manifest={f"LOT-{j}": ("MCB-WRONG" if j == 1 else f"MCB-{(j - 1) // 2 + 1}") for j in range(1, 7)},
        )
        g28a_badman = evaluate_gate28a_h1_promotion(p_bad_manifest)
        for lbl_m, res_m in (("no_manifest_store", g28a_noman), ("no_manifest_nostore", g28a_noman_nostore), ("bad_manifest", g28a_badman)):
            if not (
                res_m["promotion_authorized"] is False
                and res_m["status"] == "HOLD_H1_AT_88PCT"
                and res_m["lot_bank_hierarchy_valid"] is False
                and res_m["deff"] is None
                and res_m["n_eff"] is None
                and res_m["k_eff"] is None
            ):
                raise ValueError(f"R06 B3 {lbl_m} MUST return lot_bank_hierarchy_valid=False & null deff/n_eff/k_eff: {res_m}")
        cases.append({"case": "b3_r06_gate28a_missing_or_mismatched_mcb_manifest_returns_null_cluster_outputs", "passed": True})

        # 23. R06 Blocking 3b: Recipients declaring wcb_id without matching lot_to_wcb_manifest return null cluster outputs; valid store-verified WCB promotes!
        wcb_good_30 = copy.deepcopy(good_30)
        for rec in wcb_good_30:
            rec["wcb_id"] = f"WCB-FOR-{rec['lot_id']}"
        wcb_robust_45 = copy.deepcopy(robust_45)
        for rec in wcb_robust_45:
            rec["wcb_id"] = f"WCB-FOR-{rec['lot_id']}"
        p_wcb_ok, _ = build_valid_gate28a_reference_bundle(clin_store_json, wcb_robust_45, cohort_id="COHORT-WCB-OK-45")
        g28a_wcb_ok = evaluate_gate28a_h1_promotion(p_wcb_ok, trusted_clinical_store=clin_store_json)
        p_wcb_missing = copy.deepcopy(p_wcb_ok)
        p_wcb_missing.pop("lot_to_wcb_manifest")
        g28a_wcb_miss = evaluate_gate28a_h1_promotion(p_wcb_missing, trusted_clinical_store=clin_store_json)
        p_wcb_mismatch = copy.deepcopy(p_wcb_ok)
        p_wcb_mismatch["lot_to_wcb_manifest"]["LOT-1"] = "WCB-WRONG"
        g28a_wcb_mis = evaluate_gate28a_h1_promotion(p_wcb_mismatch, trusted_clinical_store=clin_store_json)
        if not (
            g28a_wcb_ok["promotion_authorized"] is True
            and g28a_wcb_ok["lot_bank_hierarchy_valid"] is True
            and g28a_wcb_ok["lot_to_wcb_manifest_verified"] is True
            and g28a_wcb_miss["lot_bank_hierarchy_valid"] is False
            and g28a_wcb_miss["deff"] is None
            and g28a_wcb_miss["n_eff"] is None
            and g28a_wcb_mis["lot_bank_hierarchy_valid"] is False
            and g28a_wcb_mis["deff"] is None
            and g28a_wcb_mis["n_eff"] is None
        ):
            raise ValueError(f"R06 B3 WCB provenance checks failed: ok={g28a_wcb_ok}, miss={g28a_wcb_miss}, mis={g28a_wcb_mis}")
        cases.append({"case": "b3_r06_gate28a_wcb_provenance_enforced_and_missing_returns_null_outputs", "passed": True})

        # 24. B2 adversarial: bare booleans without attestations OR attestation bound to wrong cohort/digest MUST fail closed!
        p_bare_bools = {
            "cohort_id": "COHORT-BARE",
            **GATE_28A_COMPATIBILITY_TARGET,
            "includes_reichman": False,
            "primary_peer_reviewed_full_text_verified": True,
            "parallel_cmc_readiness_ledger_disclosed": True,
            "lot_to_mcb_manifest": {f"LOT-{j}": f"MCB-{(j - 1) // 2 + 1}" for j in range(1, 7)},
            "recipients": good_30,
        }
        g28a_bare = evaluate_gate28a_h1_promotion(p_bare_bools, trusted_clinical_store=clin_store_json)
        p_stale = copy.deepcopy(p_good_json)
        p_stale["recipients"][0]["followup_months"] = 18.0
        g28a_stale = evaluate_gate28a_h1_promotion(p_stale, trusted_clinical_store=clin_store_json)
        if g28a_bare["promotion_authorized"] is not False or g28a_stale["promotion_authorized"] is not False:
            raise ValueError(f"B2 bare booleans or stale cohort digest MUST fail closed: {g28a_bare} / {g28a_stale}")
        cases.append({"case": "b2_gate28a_reject_bare_booleans_and_wrong_cohort_or_digest_attestation", "passed": True})

        # 25. B2 prohibited peri-infusion systemic glucocorticoid recipient in same 30-cohort FAILS to promote!
        steroid_30 = copy.deepcopy(good_30)
        steroid_30[0]["intercurrent_event"] = "PROHIBITED_PERI_INFUSION_GLUCOCORTICOIDS"
        p_ster, _ = build_valid_gate28a_reference_bundle(clin_store_json, steroid_30, cohort_id="COHORT-STER-30")
        g28a_ster = evaluate_gate28a_h1_promotion(p_ster, trusted_clinical_store=clin_store_json)
        if (
            g28a_ster["promotion_authorized"] is not False
            or g28a_ster["k"] != 29
            or g28a_ster["secondary_steroid_exposed_c2b_count_excluded_from_primary"] != 1
        ):
            raise ValueError(f"B2 prohibited glucocorticoid recipient MUST count as 0 and fail promotion: {g28a_ster}")
        cases.append({"case": "b2_gate28a_prohibited_glucocorticoid_counts_as_zero_and_fails", "passed": True, "k": g28a_ster["k"]})

        # 26. B2 rescue repeat infusion, missing endpoint, and pre-landmark death all adjudicate deterministically to 0!
        ie_30 = copy.deepcopy(good_30)
        ie_30[0]["intercurrent_event"] = "RESCUE_REPEAT_INFUSION"
        ie_30[1]["intercurrent_event"] = "MISSING_PRIMARY_ENDPOINT_OR_LTFU"
        ie_30[2]["intercurrent_event"] = "PRE_LANDMARK_DEATH"
        p_ie, _ = build_valid_gate28a_reference_bundle(clin_store_json, ie_30, cohort_id="COHORT-IE-30")
        g28a_ie = evaluate_gate28a_h1_promotion(p_ie, trusted_clinical_store=clin_store_json)
        if g28a_ie["promotion_authorized"] is not False or g28a_ie["k"] != 27:
            raise ValueError(f"B2 intercurrent-event adjudication check failed: {g28a_ie}")
        cases.append({"case": "b2_gate28a_rescue_missing_death_all_adjudicate_zero", "passed": True, "k": g28a_ie["k"]})

        # 27. B2 incompatible cohort (autologous product or rectus-sheath site) fails closed!
        p_inc, _ = build_valid_gate28a_reference_bundle(
            clin_store_json, good_30, cohort_id="COHORT-INC-SITE", transplant_site="ABDOMINAL_ANTERIOR_RECTUS_SHEATH"
        )
        g28a_inc = evaluate_gate28a_h1_promotion(p_inc, trusted_clinical_store=clin_store_json)
        if g28a_inc["promotion_authorized"] is not False:
            raise ValueError(f"B2 incompatible site cohort MUST fail closed: {g28a_inc}")
        cases.append({"case": "b2_gate28a_incompatible_site_fails_closed", "passed": True})

        # 28. B2/B5 context-independence: max_single_lot_share = 13/32 (0.40625 > 0.40) FAILS identically under prec=2 and prec=28!
        share_32 = [
            {
                "recipient_id": f"SH-{i:02d}",
                "lot_id": "LOT-BIG" if i <= 13 else f"LOT-{(i - 14) // 5 + 2}",
                "mcb_id": "MCB-1" if i <= 13 else f"MCB-{(i - 14) // 10 + 2}",
                "followup_months": 12.0,
                "met_c2b_criteria": True,
                "intercurrent_event": "NONE",
            }
            for i in range(1, 33)
        ]
        share_payload, _ = build_valid_gate28a_reference_bundle(clin_store_json, share_32, cohort_id="COHORT-SHARE-32")
        with localcontext() as ctx_low:
            ctx_low.prec = 2
            r_sh_low = evaluate_gate28a_h1_promotion(share_payload, trusted_clinical_store=clin_store_json)
        with localcontext() as ctx_hi:
            ctx_hi.prec = 28
            r_sh_hi = evaluate_gate28a_h1_promotion(share_payload, trusted_clinical_store=clin_store_json)
        if r_sh_low["promotion_authorized"] is not False or r_sh_hi["promotion_authorized"] is not False:
            raise ValueError(f"B2/B5 max_single_lot_share 13/32 MUST fail identically under prec=2 and prec=28: {r_sh_low} / {r_sh_hi}")
        cases.append({"case": "b2_b5_gate28a_max_single_lot_share_context_independent_prec2_vs_prec28", "passed": True})

        # 29. R06 Blocking 4 file-wide: Gate 28-A & CMC evaluators immune to ALL caller Decimal traps!
        with localcontext() as trap_ctx:
            trap_ctx.prec = 4
            for sig in (decimal.Inexact, decimal.Rounded, decimal.Subnormal, decimal.Clamped, decimal.Underflow):
                trap_ctx.traps[sig] = True
            r_trap_g28a = evaluate_gate28a_h1_promotion(p_good_json, trusted_clinical_store=clin_store_json)
            r_trap_cmc = evaluate_cmc_attempted_lot_readiness(ledger_ex, h1_blueprint_override=Decimal("0.888888888"))
        if not (r_trap_g28a["promotion_authorized"] is True and r_trap_cmc["attempted_lots_n"] == 10):
            raise ValueError(f"R06 B4 Gate 28-A / CMC trap immunity check failed: {r_trap_g28a} / {r_trap_cmc}")
        cases.append({"case": "b4_r06_gate28a_and_cmc_immune_to_all_caller_decimal_traps", "passed": True})

        # 30. R07 M2: Unequal split-lot example explicitly labels empirical_product_readiness as diagnostic-only vs authoritative measured_weighted_cmc_readiness!
        cmc_unequal = evaluate_cmc_attempted_lot_readiness([
            {
                "lot_id": "LOT-UEQ-1", "mcb_id": "MCB-1", "lot_type": "SPLIT_LOT",
                "disposition": "RELEASED_INFUSED", "planned_doses_n": 2, "infused_doses_n": 2,
                "c2b_responder_doses_n": 2, "recipient_ids": ["UEQ-1", "UEQ-2"],
                "recipient_outcomes": {"UEQ-1": 1, "UEQ-2": 1},
            },
            {
                "lot_id": "LOT-UEQ-2", "mcb_id": "MCB-2", "lot_type": "SPLIT_LOT",
                "disposition": "RELEASED_INFUSED", "planned_doses_n": 10, "infused_doses_n": 1,
                "c2b_responder_doses_n": 0, "recipient_ids": ["UEQ-3"],
                "recipient_outcomes": {"UEQ-3": 0},
            },
        ])
        if not (
            abs(cmc_unequal["measured_weighted_cmc_readiness"] - 0.50) < 1e-9
            and abs(cmc_unequal["empirical_product_readiness"] - (11.0 / 30.0)) < 1e-6
            and cmc_unequal["empirical_product_readiness_scope"] == "DIAGNOSTIC_UNWEIGHTED_RECIPIENT_RATE_PRODUCT_ONLY"
            and cmc_unequal["authoritative_attempted_lot_metric"] == "measured_weighted_cmc_readiness"
        ):
            raise ValueError(f"R07 M2 unequal split-lot diagnostic vs measured check failed: {cmc_unequal}")
        cases.append({
            "case": "m2_r07_cmc_empirical_product_diagnostic_vs_authoritative_measured_weighted",
            "passed": True,
            "measured_weighted": cmc_unequal["measured_weighted_cmc_readiness"],
            "diagnostic_empirical_product": cmc_unequal["empirical_product_readiness"],
        })

        # 31. R07 B1: Balanced 60-recipient fixture (15 split lots x 4 across 3 MCBs) with trusted_clinical_store=None
        #     MUST return lot_bank_hierarchy_valid=False, lot_to_mcb_manifest_verified=False, lot_to_wcb_manifest_verified=False,
        #     deff=None, n_eff=None, k_eff=None, promotion_authorized=False!
        bal_60 = [
            {
                "recipient_id": f"B60-{i:02d}",
                "lot_id": f"LOT60-{(i - 1) // 4 + 1:02d}",
                "mcb_id": f"MCB60-{(i - 1) // 20 + 1}",
                "followup_months": 12.0,
                "met_c2b_criteria": True,
                "intercurrent_event": "NONE",
            }
            for i in range(1, 61)
        ]
        p_bal60, _ = build_valid_gate28a_reference_bundle(clin_store_json, bal_60, cohort_id="COHORT-R07-BAL60")
        g28a_bal60_nostore = evaluate_gate28a_h1_promotion(p_bal60, trusted_clinical_store=None)
        g28a_bal60_store = evaluate_gate28a_h1_promotion(p_bal60, trusted_clinical_store=clin_store_json)
        if not (
            g28a_bal60_nostore["lot_bank_hierarchy_valid"] is False
            and g28a_bal60_nostore["lot_to_mcb_manifest_verified"] is False
            and g28a_bal60_nostore["lot_to_wcb_manifest_verified"] is False
            and g28a_bal60_nostore["deff"] is None
            and g28a_bal60_nostore["n_eff"] is None
            and g28a_bal60_nostore["k_eff"] is None
            and g28a_bal60_nostore["promotion_authorized"] is False
            and g28a_bal60_store["lot_bank_hierarchy_valid"] is True
            and g28a_bal60_store["promotion_authorized"] is True
            and abs(g28a_bal60_store["deff"] - 1.53) < 1e-6
            and abs(g28a_bal60_store["n_eff"] - 39.215686) < 1e-5
        ):
            raise ValueError(f"R07 B1 absent-store 60-recipient hierarchy nullification failed: nostore={g28a_bal60_nostore} store={g28a_bal60_store}")
        cases.append({"case": "b1_r07_gate28a_absent_store_60_recipient_nullifies_hierarchy_and_cluster_outputs", "passed": True})

        # 32 & 33. R07 B2: Bidirectional rescue-infusion reconciliation on fixed 59/60 clinical cohort with 1 rescue
        #   (15 split lots x 4 across 5 MCBs so primary & moderate ICC both clear while keeping exact 16-lot CMC 92.1875%):
        #   (a) Matching 16-lot CMC ledger (15 split lots + 1 infused rescue lot, 92.1875% measured readiness) -> VERIFIES & PROMOTES!
        #   (b) Otherwise identical 15-lot CMC ledger omitting that rescue lot (98.3333% measured readiness) -> FAILS CLOSED!
        resc_59of60 = [
            {
                "recipient_id": f"B60-{i:02d}",
                "lot_id": f"LOT60-{(i - 1) // 4 + 1:02d}",
                "mcb_id": f"MCB60-{(i - 1) // 12 + 1}",
                "followup_months": 12.0,
                "met_c2b_criteria": True,
                "intercurrent_event": "NONE",
            }
            for i in range(1, 61)
        ]
        resc_59of60[0]["intercurrent_event"] = "RESCUE_REPEAT_INFUSION"
        resc_59of60[0]["rescue_infusion_occurred"] = True
        resc_59of60[0]["rescue_lot_id"] = "RESCUE-LOT60-01-001"
        mcb60_map = {f"LOT60-{j:02d}": f"MCB60-{(j - 1) // 3 + 1}" for j in range(1, 16)}
        cmc_16_with_rescue = _derive_reconciling_cmc_lot_ledger_from_recipients(resc_59of60, mcb60_map)
        cmc_15_omit_rescue = [row for row in cmc_16_with_rescue if row["lot_type"] != "RESCUE_REPEAT_LOT"]

        p_resc_16, _ = build_valid_gate28a_reference_bundle(
            clin_store_json, resc_59of60, cohort_id="COHORT-R07-RESC-16LOT", parallel_cmc_lot_ledger=cmc_16_with_rescue
        )
        r_resc_16 = evaluate_gate28a_h1_promotion(p_resc_16, trusted_clinical_store=clin_store_json)
        if not (
            r_resc_16["parallel_cmc_ledger_verified"] is True
            and r_resc_16["promotion_authorized"] is True
            and r_resc_16["status"] == "PROMOTE_H1_88_TO_90"
            and r_resc_16["k"] == 59
            and r_resc_16["n"] == 60
            and r_resc_16["parallel_cmc_readiness_summary"]["attempted_lots_n"] == 16
            and abs(r_resc_16["parallel_cmc_readiness_summary"]["measured_weighted_cmc_readiness_pct"] - 92.1875) < 1e-4
        ):
            raise ValueError(f"R07 B2 matching 16-lot rescue CMC ledger should verify and promote: {r_resc_16}")
        cases.append({
            "case": "b2_r07_gate28a_59of60_with_rescue_matching_16lot_cmc_92p1875pct_promotes",
            "passed": True,
            "measured_weighted_pct": r_resc_16["parallel_cmc_readiness_summary"]["measured_weighted_cmc_readiness_pct"],
        })

        p_resc_15, _ = build_valid_gate28a_reference_bundle(
            clin_store_json, resc_59of60, cohort_id="COHORT-R07-RESC-15LOT-OMIT", parallel_cmc_lot_ledger=cmc_15_omit_rescue
        )
        r_resc_15 = evaluate_gate28a_h1_promotion(p_resc_15, trusted_clinical_store=clin_store_json)
        cmc_16_wrong_rlid = copy.deepcopy(cmc_16_with_rescue)
        for row in cmc_16_wrong_rlid:
            if row["lot_type"] == "RESCUE_REPEAT_LOT":
                row["lot_id"] = "RESCUE-WRONG-ID"
        p_resc_wrong_rlid, _ = build_valid_gate28a_reference_bundle(
            clin_store_json, resc_59of60, cohort_id="COHORT-R07-RESC-WRONG-ID", parallel_cmc_lot_ledger=cmc_16_wrong_rlid
        )
        r_resc_wrong_rlid = evaluate_gate28a_h1_promotion(p_resc_wrong_rlid, trusted_clinical_store=clin_store_json)
        if not (
            r_resc_15["parallel_cmc_ledger_verified"] is False
            and r_resc_15["promotion_authorized"] is False
            and r_resc_15["status"] == "HOLD_H1_AT_88PCT"
            and r_resc_15["parallel_cmc_readiness_summary"]["attempted_lots_n"] == 15
            and abs(r_resc_15["parallel_cmc_readiness_summary"]["measured_weighted_cmc_readiness_pct"] - 98.3333) < 1e-4
            and any("CLINICAL_RESCUE_OMITTED_FROM_CMC_LEDGER" in fr for fr in r_resc_15["failure_reasons"])
            and r_resc_wrong_rlid["parallel_cmc_ledger_verified"] is False
            and r_resc_wrong_rlid["promotion_authorized"] is False
            and any("CLINICAL_RESCUE_LOT_ID_MISMATCH_IN_CMC_LEDGER" in fr for fr in r_resc_wrong_rlid["failure_reasons"])
        ):
            raise ValueError(f"R07 B2 omitted/mismatched rescue lot in CMC ledger MUST fail closed: omit={r_resc_15} wrong={r_resc_wrong_rlid}")
        cases.append({
            "case": "b2_r07_gate28a_59of60_with_rescue_omitted_in_15lot_cmc_98p3333pct_fails_closed",
            "passed": True,
            "omitted_measured_weighted_pct": r_resc_15["parallel_cmc_readiness_summary"]["measured_weighted_cmc_readiness_pct"],
        })

        # 34. R07 B3a: Contradictory embedded vs top-level WCB manifest aliases MUST fail closed BEFORE merging (in BOTH external store & payload)!
        bad_alias_store = tmp_dir_p / "r07_b3_bad_wcb_alias_store.json"
        wcb_ok_copy = copy.deepcopy(wcb_good_30)
        p_alias_base, recs_alias = build_valid_gate28a_reference_bundle(
            bad_alias_store, wcb_ok_copy, cohort_id="COHORT-R07-WCB-ALIAS-CONFLICT"
        )
        # Tamper signed external VERIFIED_LOT_TO_BANK_MANIFEST so embedded WCB contradicts top-level WCB for LOT-1!
        bad_mrec = {
            "record_type": "VERIFIED_LOT_TO_BANK_MANIFEST",
            "cohort_id": "COHORT-R07-WCB-ALIAS-CONFLICT",
            "manifest_source_id": "QA-BANK-MANIFEST-CONFLICT-TEST",
            "issuer_authority_id": "OPENISLET_CLINICAL_ADJUDICATION_BOARD_V1",
            "lot_to_mcb_manifest": {
                f"LOT-{j}": {
                    "mcb_id": f"MCB-{(j - 1) // 2 + 1}",
                    "wcb_id": "WCB-EMBEDDED-CONFLICT" if j == 1 else f"WCB-FOR-LOT-{j}",
                }
                for j in range(1, 7)
            },
            "lot_to_wcb_manifest": {f"LOT-{j}": f"WCB-FOR-LOT-{j}" for j in range(1, 7)},
        }
        bad_mrec["record_sha256"] = compute_gate28a_record_sha256(bad_mrec)
        write_gate28a_trusted_clinical_store(
            bad_alias_store,
            verified_lot_to_bank_manifests=[bad_mrec],
            store_authority_id="OPENISLET_CLINICAL_ADJUDICATION_BOARD_V1",
        )
        p_alias_store_test = copy.deepcopy(p_alias_base)
        p_alias_store_test["clinical_store_refs"]["verified_lot_to_bank_manifest_sha256"] = bad_mrec["record_sha256"]
        r_alias_store = evaluate_gate28a_h1_promotion(p_alias_store_test, trusted_clinical_store=bad_alias_store)

        p_alias_payload = copy.deepcopy(p_alias_base)
        p_alias_payload["lot_to_mcb_manifest"] = copy.deepcopy(bad_mrec["lot_to_mcb_manifest"])
        r_alias_payload = evaluate_gate28a_h1_promotion(p_alias_payload, trusted_clinical_store=bad_alias_store)

        for lbl_al, res_al in (("store_manifest", r_alias_store), ("payload_manifest", r_alias_payload)):
            if not (
                res_al["lot_to_wcb_manifest_verified"] is False
                and res_al["lot_bank_hierarchy_valid"] is False
                and res_al["lot_to_mcb_manifest_verified"] is False
                and res_al["deff"] is None
                and res_al["n_eff"] is None
                and res_al["k_eff"] is None
                and res_al["promotion_authorized"] is False
                and any("CONFLICTING_WCB_MANIFEST_ALIAS" in fr for fr in res_al["failure_reasons"])
            ):
                raise ValueError(f"R07 B3a contradictory WCB alias ({lbl_al}) MUST fail closed: {res_al}")
        cases.append({"case": "b3_r07_gate28a_reject_contradictory_wcb_manifest_aliases_before_merge", "passed": True})

        # 35. R07 B3b: One literal wcb_id assigned to 3 distinct MCBs MUST fail closed (unique WCB-to-MCB parentage)!
        shared_wcb_store = tmp_dir_p / "r07_b3_shared_wcb_3mcbs_store.json"
        shared_wcb_30 = copy.deepcopy(good_30)
        for rec in shared_wcb_30:
            rec["wcb_id"] = "WCB-SHARED-ACROSS-3MCBS"
        mcb30_map = {f"LOT-{j}": f"MCB-{(j - 1) // 2 + 1}" for j in range(1, 7)}
        shared_wcb_map = {f"LOT-{j}": "WCB-SHARED-ACROSS-3MCBS" for j in range(1, 7)}
        cmc_sh_bytes, cmc_sh_sha = build_gate28a_parallel_cmc_ledger_bytes(
            cohort_id="COHORT-R07-WCB-3MCBS",
            lot_ledger=_derive_reconciling_cmc_lot_ledger_from_recipients(shared_wcb_30, mcb30_map),
            issuer_authority_id="OPENISLET_CLINICAL_ADJUDICATION_BOARD_V1",
        )
        p_shared_wcb = {
            "cohort_id": "COHORT-R07-WCB-3MCBS",
            **GATE_28A_COMPATIBILITY_TARGET,
            "includes_reichman": False,
            "rho_lot": GATE_28A_RHO_LOT_MIN,
            "rho_bank": GATE_28A_RHO_BANK_MIN,
            "primary_peer_reviewed_full_text_verified": True,
            "parallel_cmc_readiness_ledger_disclosed": True,
            "parallel_cmc_readiness_ledger_sha256": cmc_sh_sha,
            "lot_to_mcb_manifest": mcb30_map,
            "lot_to_wcb_manifest": shared_wcb_map,
            "recipients": shared_wcb_30,
        }
        sh_canon = compute_gate28a_cohort_canonical_sha256(p_shared_wcb)
        sh_prespec = build_gate28a_prespecification_attestation(cohort_id="COHORT-R07-WCB-3MCBS", cohort_canonical_sha256=sh_canon)
        sh_source = build_gate28a_source_verification_attestation(
            cohort_id="COHORT-R07-WCB-3MCBS", cohort_canonical_sha256=sh_canon, parallel_cmc_readiness_ledger_sha256=cmc_sh_sha
        )
        sh_mrec = {
            "record_type": "VERIFIED_LOT_TO_BANK_MANIFEST",
            "cohort_id": "COHORT-R07-WCB-3MCBS",
            "manifest_source_id": "QA-BANK-MANIFEST-3MCBS-TEST",
            "issuer_authority_id": "OPENISLET_CLINICAL_ADJUDICATION_BOARD_V1",
            "lot_to_mcb_manifest": mcb30_map,
            "lot_to_wcb_manifest": shared_wcb_map,
        }
        sh_mrec["record_sha256"] = compute_gate28a_record_sha256(sh_mrec)
        write_gate28a_trusted_clinical_store(
            shared_wcb_store,
            prespecification_attestations=[sh_prespec],
            source_verification_attestations=[sh_source],
            verified_lot_to_bank_manifests=[sh_mrec],
            parallel_cmc_readiness_ledgers=[cmc_sh_bytes],
            store_authority_id="OPENISLET_CLINICAL_ADJUDICATION_BOARD_V1",
        )
        p_shared_wcb["clinical_store_refs"] = {
            "prespecification_attestation_sha256": sh_prespec["record_sha256"],
            "source_verification_attestation_sha256": sh_source["record_sha256"],
            "verified_lot_to_bank_manifest_sha256": sh_mrec["record_sha256"],
            "parallel_cmc_readiness_ledger_sha256": cmc_sh_sha,
        }
        r_shared_wcb = evaluate_gate28a_h1_promotion(p_shared_wcb, trusted_clinical_store=shared_wcb_store)

        # Also test when cohort omits WCB entirely while the external VERIFIED_LOT_TO_BANK_MANIFEST assigns 1 literal WCB to 3 MCBs!
        p_no_wcb_payload, _ = build_valid_gate28a_reference_bundle(
            shared_wcb_store, good_30, cohort_id="COHORT-R07-STORE-WCB-3MCBS"
        )
        sh_mrec_store_only = copy.deepcopy(sh_mrec)
        sh_mrec_store_only["cohort_id"] = "COHORT-R07-STORE-WCB-3MCBS"
        sh_mrec_store_only["record_sha256"] = compute_gate28a_record_sha256(sh_mrec_store_only)
        write_gate28a_trusted_clinical_store(
            shared_wcb_store,
            verified_lot_to_bank_manifests=[sh_mrec_store_only],
            store_authority_id="OPENISLET_CLINICAL_ADJUDICATION_BOARD_V1",
        )
        p_no_wcb_payload["clinical_store_refs"]["verified_lot_to_bank_manifest_sha256"] = sh_mrec_store_only["record_sha256"]
        r_shared_wcb_store_only = evaluate_gate28a_h1_promotion(p_no_wcb_payload, trusted_clinical_store=shared_wcb_store)

        for lbl_sw, res_sw in (("payload_and_store", r_shared_wcb), ("store_manifest_only", r_shared_wcb_store_only)):
            if not (
                res_sw["lot_to_wcb_manifest_verified"] is False
                and res_sw["lot_bank_hierarchy_valid"] is False
                and res_sw["lot_to_mcb_manifest_verified"] is False
                and res_sw["deff"] is None
                and res_sw["n_eff"] is None
                and res_sw["k_eff"] is None
                and res_sw["promotion_authorized"] is False
                and any("NON_UNIQUE_WCB_PARENTAGE" in fr for fr in res_sw["failure_reasons"])
            ):
                raise ValueError(f"R07 B3b single literal WCB assigned to 3 MCBs ({lbl_sw}) MUST fail closed: {res_sw}")
        cases.append({"case": "b3_r07_gate28a_reject_single_literal_wcb_assigned_to_three_mcbs", "passed": True})

        # --- R08 B1, B2, M2: Unified manifest-alias digest & parentage, all-disposition CMC ancestry reconciliation, course-equiv unit ---
        r08_store = tmp_dir_p / "r08_gate28a_store.json"
        r08_bal60: list[dict[str, Any]] = []
        r08_mcb_map: dict[str, str] = {}
        r08_wcb_map: dict[str, str] = {"L00": "W0"}
        for g_idx in range(15):
            lid_g = f"L{g_idx:02d}"
            mid_g = f"M{g_idx // 5}"
            r08_mcb_map[lid_g] = mid_g
            for r_idx in range(4):
                row_r: dict[str, Any] = {
                    "recipient_id": f"R08-{g_idx:02d}-{r_idx}",
                    "lot_id": lid_g,
                    "mcb_id": mid_g,
                    "followup_months": 12.0,
                    "met_c2b_criteria": True,
                    "intercurrent_event": "NONE",
                }
                if g_idx == 0:
                    row_r["wcb_id"] = "W0"
                r08_bal60.append(row_r)

        p_r08_base, r08_base_recs = build_valid_gate28a_reference_bundle(
            r08_store,
            r08_bal60,
            cohort_id="COHORT-R08-B1-BASE",
            lot_to_mcb_manifest=r08_mcb_map,
            lot_to_wcb_manifest=r08_wcb_map,
        )
        r_r08_base = evaluate_gate28a_h1_promotion(p_r08_base, trusted_clinical_store=r08_store)
        if not (
            r_r08_base["status"] == "PROMOTE_H1_88_TO_90"
            and r_r08_base["promotion_authorized"] is True
            and r_r08_base["lot_bank_hierarchy_valid"] is True
            and r_r08_base["lot_to_wcb_manifest_verified"] is True
            and abs(r_r08_base["n_eff"] - 39.215686) < 1e-5
        ):
            raise ValueError(f"R08 B1 baseline positive control failed: {r_r08_base}")

        # 38. R08 B1a: Adding L05 -> W0 -> M1 solely in lot_to_bank_manifest on submitted cohort MUST alter
        #     cohort_canonical_sha256 AND fail closed with null DEFF/n_eff/k_eff!
        p_r08_alias_payload = copy.deepcopy(p_r08_base)
        p_r08_alias_payload["lot_to_bank_manifest"] = {
            lid: ({"mcb_id": mid, "wcb_id": "W0"} if lid == "L05" else mid)
            for lid, mid in r08_mcb_map.items()
        }
        r_r08_alias_payload = evaluate_gate28a_h1_promotion(p_r08_alias_payload, trusted_clinical_store=r08_store)
        if not (
            r_r08_alias_payload["cohort_canonical_sha256"] != r_r08_base["cohort_canonical_sha256"]
            and r_r08_alias_payload["status"] == "HOLD_H1_AT_88PCT"
            and r_r08_alias_payload["promotion_authorized"] is False
            and r_r08_alias_payload["lot_bank_hierarchy_valid"] is False
            and r_r08_alias_payload["lot_to_wcb_manifest_verified"] is False
            and r_r08_alias_payload["deff"] is None
            and r_r08_alias_payload["n_eff"] is None
            and r_r08_alias_payload["k_eff"] is None
            and any("CONFLICTING_BANK_MANIFEST_ALIASES" in fr for fr in r_r08_alias_payload["failure_reasons"])
            and any("NON_UNIQUE_WCB_PARENTAGE" in fr for fr in r_r08_alias_payload["failure_reasons"])
        ):
            raise ValueError(f"R08 B1a conflicting WCB parent hidden in cohort lot_to_bank_manifest MUST fail closed: {r_r08_alias_payload}")
        cases.append({"case": "b1a_r08_gate28a_reject_wcb_parent_conflict_in_cohort_lot_to_bank_manifest_and_change_digest", "passed": True})

        # 39. R08 B1b: Adding L05 -> W0 -> M1 solely in lot_to_bank_manifest inside externally signed
        #     VERIFIED_LOT_TO_BANK_MANIFEST (clean cohort payload) MUST fail closed with null DEFF/n_eff/k_eff!
        bad_store_mrec_r08 = copy.deepcopy(r08_base_recs["verified_lot_to_bank_manifest"])
        bad_store_mrec_r08["lot_to_bank_manifest"] = {
            lid: ({"mcb_id": mid, "wcb_id": "W0"} if lid == "L05" else mid)
            for lid, mid in r08_mcb_map.items()
        }
        bad_store_mrec_r08["record_sha256"] = compute_gate28a_record_sha256(bad_store_mrec_r08)
        write_gate28a_trusted_clinical_store(
            r08_store,
            verified_lot_to_bank_manifests=[bad_store_mrec_r08],
            store_authority_id="OPENISLET_CLINICAL_ADJUDICATION_BOARD_V1",
        )
        p_r08_alias_store = copy.deepcopy(p_r08_base)
        p_r08_alias_store["clinical_store_refs"]["verified_lot_to_bank_manifest_sha256"] = bad_store_mrec_r08["record_sha256"]
        r_r08_alias_store = evaluate_gate28a_h1_promotion(p_r08_alias_store, trusted_clinical_store=r08_store)
        if not (
            r_r08_alias_store["status"] == "HOLD_H1_AT_88PCT"
            and r_r08_alias_store["promotion_authorized"] is False
            and r_r08_alias_store["lot_bank_hierarchy_valid"] is False
            and r_r08_alias_store["lot_to_wcb_manifest_verified"] is False
            and r_r08_alias_store["deff"] is None
            and r_r08_alias_store["n_eff"] is None
            and r_r08_alias_store["k_eff"] is None
            and any("CONFLICTING_BANK_MANIFEST_ALIASES" in fr for fr in r_r08_alias_store["failure_reasons"])
            and any("NON_UNIQUE_WCB_PARENTAGE" in fr for fr in r_r08_alias_store["failure_reasons"])
        ):
            raise ValueError(f"R08 B1b conflicting WCB parent hidden in store VERIFIED_LOT_TO_BANK_MANIFEST alias MUST fail closed: {r_r08_alias_store}")
        cases.append({"case": "b1b_r08_gate28a_reject_wcb_parent_conflict_in_store_lot_to_bank_manifest", "passed": True})

        # 40. R08 B1c: Widening extra WCB entry (L05 -> W5 -> M1) solely in lot_to_bank_manifest AND unrecognized
        #     manifest alias key (bank_manifest) MUST both alter digest and fail closed!
        p_r08_widen = copy.deepcopy(p_r08_base)
        p_r08_widen["lot_to_bank_manifest"] = {
            lid: ({"mcb_id": mid, "wcb_id": "W5"} if lid == "L05" else mid)
            for lid, mid in r08_mcb_map.items()
        }
        r_r08_widen = evaluate_gate28a_h1_promotion(p_r08_widen, trusted_clinical_store=r08_store)
        p_r08_unrec_alias = copy.deepcopy(p_r08_base)
        p_r08_unrec_alias["bank_manifest"] = copy.deepcopy(r08_mcb_map)
        r_r08_unrec_alias = evaluate_gate28a_h1_promotion(p_r08_unrec_alias, trusted_clinical_store=r08_store)
        if not (
            r_r08_widen["cohort_canonical_sha256"] != r_r08_base["cohort_canonical_sha256"]
            and r_r08_widen["lot_bank_hierarchy_valid"] is False
            and r_r08_widen["deff"] is None
            and r_r08_widen["promotion_authorized"] is False
            and any("CONFLICTING_BANK_MANIFEST_ALIASES" in fr for fr in r_r08_widen["failure_reasons"])
            and r_r08_unrec_alias["cohort_canonical_sha256"] != r_r08_base["cohort_canonical_sha256"]
            and r_r08_unrec_alias["lot_bank_hierarchy_valid"] is False
            and r_r08_unrec_alias["deff"] is None
            and r_r08_unrec_alias["promotion_authorized"] is False
            and any("UNRECOGNIZED_BANK_MANIFEST_ALIAS" in fr for fr in r_r08_unrec_alias["failure_reasons"])
        ):
            raise ValueError(f"R08 B1c widening/unrecognized manifest alias checks failed: widen={r_r08_widen}, unrec={r_r08_unrec_alias}")
        cases.append({"case": "b1c_r08_gate28a_reject_widening_and_unrecognized_bank_manifest_aliases", "passed": True})

        # 41. R08 B2a: Rescue lot ancestry reconciliation on 59/60 cohort (15 lots x 4 across 5 MCBs so moderate ICC clears;
        #     matched positive control promotes; conflicting rescue MCB M0 vs M1 fails closed; rescue lot omitted from manifest fails closed!)
        r08_resc_60: list[dict[str, Any]] = []
        r08_resc_mcb_map: dict[str, str] = {}
        for g_idx in range(15):
            lid_g = f"L{g_idx:02d}"
            mid_g = f"M{g_idx // 3}"
            r08_resc_mcb_map[lid_g] = mid_g
            for r_idx in range(4):
                row_r = {
                    "recipient_id": f"R08-{g_idx:02d}-{r_idx}",
                    "lot_id": lid_g,
                    "mcb_id": mid_g,
                    "followup_months": 12.0,
                    "met_c2b_criteria": True,
                    "intercurrent_event": "NONE",
                }
                if g_idx == 0:
                    row_r["wcb_id"] = "W0"
                r08_resc_60.append(row_r)
        r08_resc_60[0]["intercurrent_event"] = "RESCUE_REPEAT_INFUSION"
        r08_resc_60[0]["rescue_infusion_occurred"] = True
        r08_resc_60[0]["rescue_lot_id"] = "L_RESC_01"
        r08_mcb_with_resc = dict(r08_resc_mcb_map, L_RESC_01="M0")
        cmc_r08_resc_match = _derive_reconciling_cmc_lot_ledger_from_recipients(r08_resc_60, r08_mcb_with_resc)
        cmc_r08_resc_conflict = copy.deepcopy(cmc_r08_resc_match)
        for row_c in cmc_r08_resc_conflict:
            if row_c["lot_id"] == "L_RESC_01":
                row_c["mcb_id"] = "M1"

        p_r08_resc_ok, _ = build_valid_gate28a_reference_bundle(
            r08_store,
            r08_resc_60,
            cohort_id="COHORT-R08-B2-RESC-OK",
            lot_to_mcb_manifest=r08_mcb_with_resc,
            lot_to_wcb_manifest=r08_wcb_map,
            parallel_cmc_lot_ledger=cmc_r08_resc_match,
        )
        r_r08_resc_ok = evaluate_gate28a_h1_promotion(p_r08_resc_ok, trusted_clinical_store=r08_store)

        p_r08_resc_conf, _ = build_valid_gate28a_reference_bundle(
            r08_store,
            r08_resc_60,
            cohort_id="COHORT-R08-B2-RESC-CONF",
            lot_to_mcb_manifest=r08_mcb_with_resc,
            lot_to_wcb_manifest=r08_wcb_map,
            parallel_cmc_lot_ledger=cmc_r08_resc_conflict,
        )
        r_r08_resc_conf = evaluate_gate28a_h1_promotion(p_r08_resc_conf, trusted_clinical_store=r08_store)

        p_r08_resc_omit, _ = build_valid_gate28a_reference_bundle(
            r08_store,
            r08_resc_60,
            cohort_id="COHORT-R08-B2-RESC-OMIT-MAN",
            lot_to_mcb_manifest=r08_resc_mcb_map,
            lot_to_wcb_manifest=r08_wcb_map,
            parallel_cmc_lot_ledger=cmc_r08_resc_match,
        )
        r_r08_resc_omit = evaluate_gate28a_h1_promotion(p_r08_resc_omit, trusted_clinical_store=r08_store)

        if not (
            r_r08_resc_ok["status"] == "PROMOTE_H1_88_TO_90"
            and r_r08_resc_ok["promotion_authorized"] is True
            and r_r08_resc_ok["parallel_cmc_ledger_verified"] is True
            and r_r08_resc_conf["status"] == "HOLD_H1_AT_88PCT"
            and r_r08_resc_conf["promotion_authorized"] is False
            and r_r08_resc_conf["parallel_cmc_ledger_verified"] is False
            and r_r08_resc_conf["lot_bank_hierarchy_valid"] is False
            and r_r08_resc_conf["deff"] is None
            and r_r08_resc_conf["n_eff"] is None
            and any("CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST" in fr for fr in r_r08_resc_conf["failure_reasons"])
            and r_r08_resc_omit["status"] == "HOLD_H1_AT_88PCT"
            and r_r08_resc_omit["promotion_authorized"] is False
            and r_r08_resc_omit["parallel_cmc_ledger_verified"] is False
            and r_r08_resc_omit["lot_bank_hierarchy_valid"] is False
            and r_r08_resc_omit["deff"] is None
            and any("CMC_INFUSED_LOT_MISSING_FROM_VERIFIED_MANIFEST" in fr for fr in r_r08_resc_omit["failure_reasons"])
        ):
            raise ValueError(
                f"R08 B2a rescue ancestry reconciliation failed: ok={r_r08_resc_ok}, conf={r_r08_resc_conf}, omit={r_r08_resc_omit}"
            )
        cases.append({"case": "b2a_r08_gate28a_rescue_lot_verified_ancestry_required_and_mcb_conflict_rejected", "passed": True})

        # 42. R08 B2b: Non-infused CMC rows (RELEASED_UNINFUSED & FAILED_RELEASE): consistent non-infused rows
        #     absent from manifest promote cleanly; contradictory MCB vs verified manifest fails closed!
        cmc_r08_noninf_clean = _derive_reconciling_cmc_lot_ledger_from_recipients(r08_bal60, r08_mcb_map) + [
            {
                "lot_id": "L_UNINF_CLEAN", "mcb_id": "M0", "lot_type": "SINGLE_RECIPIENT",
                "disposition": "RELEASED_UNINFUSED", "planned_doses_n": 1, "infused_doses_n": 0,
                "c2b_responder_doses_n": 0, "recipient_ids": [], "recipient_outcomes": {},
            },
            {
                "lot_id": "L_FAIL_CLEAN", "mcb_id": "M1", "lot_type": "SINGLE_RECIPIENT",
                "disposition": "FAILED_RELEASE", "planned_doses_n": 1, "infused_doses_n": 0,
                "c2b_responder_doses_n": 0, "recipient_ids": [], "recipient_outcomes": {},
            },
        ]
        p_r08_noninf_ok, _ = build_valid_gate28a_reference_bundle(
            r08_store,
            r08_bal60,
            cohort_id="COHORT-R08-B2-NONINF-OK",
            lot_to_mcb_manifest=r08_mcb_map,
            lot_to_wcb_manifest=r08_wcb_map,
            parallel_cmc_lot_ledger=cmc_r08_noninf_clean,
        )
        r_r08_noninf_ok = evaluate_gate28a_h1_promotion(p_r08_noninf_ok, trusted_clinical_store=r08_store)

        r08_mcb_with_uninf = dict(r08_mcb_map, L_UNINF_01="M0")
        cmc_r08_uninf_conf = _derive_reconciling_cmc_lot_ledger_from_recipients(r08_bal60, r08_mcb_with_uninf) + [
            {
                "lot_id": "L_UNINF_01", "mcb_id": "M1", "lot_type": "SINGLE_RECIPIENT",
                "disposition": "RELEASED_UNINFUSED", "planned_doses_n": 1, "infused_doses_n": 0,
                "c2b_responder_doses_n": 0, "recipient_ids": [], "recipient_outcomes": {},
            },
        ]
        p_r08_uninf_conf, _ = build_valid_gate28a_reference_bundle(
            r08_store,
            r08_bal60,
            cohort_id="COHORT-R08-B2-UNINF-CONF",
            lot_to_mcb_manifest=r08_mcb_with_uninf,
            lot_to_wcb_manifest=r08_wcb_map,
            parallel_cmc_lot_ledger=cmc_r08_uninf_conf,
        )
        r_r08_uninf_conf = evaluate_gate28a_h1_promotion(p_r08_uninf_conf, trusted_clinical_store=r08_store)

        r08_mcb_with_fail = dict(r08_mcb_map, L_FAIL_01="M0")
        cmc_r08_fail_conf = _derive_reconciling_cmc_lot_ledger_from_recipients(r08_bal60, r08_mcb_with_fail) + [
            {
                "lot_id": "L_FAIL_01", "mcb_id": "M2", "lot_type": "SINGLE_RECIPIENT",
                "disposition": "FAILED_RELEASE", "planned_doses_n": 1, "infused_doses_n": 0,
                "c2b_responder_doses_n": 0, "recipient_ids": [], "recipient_outcomes": {},
            },
        ]
        p_r08_fail_conf, _ = build_valid_gate28a_reference_bundle(
            r08_store,
            r08_bal60,
            cohort_id="COHORT-R08-B2-FAIL-CONF",
            lot_to_mcb_manifest=r08_mcb_with_fail,
            lot_to_wcb_manifest=r08_wcb_map,
            parallel_cmc_lot_ledger=cmc_r08_fail_conf,
        )
        r_r08_fail_conf = evaluate_gate28a_h1_promotion(p_r08_fail_conf, trusted_clinical_store=r08_store)

        if not (
            r_r08_noninf_ok["status"] == "PROMOTE_H1_88_TO_90"
            and r_r08_noninf_ok["promotion_authorized"] is True
            and r_r08_noninf_ok["parallel_cmc_ledger_verified"] is True
            and r_r08_uninf_conf["status"] == "HOLD_H1_AT_88PCT"
            and r_r08_uninf_conf["promotion_authorized"] is False
            and r_r08_uninf_conf["parallel_cmc_ledger_verified"] is False
            and r_r08_uninf_conf["lot_bank_hierarchy_valid"] is False
            and r_r08_uninf_conf["deff"] is None
            and any("CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST" in fr for fr in r_r08_uninf_conf["failure_reasons"])
            and r_r08_fail_conf["status"] == "HOLD_H1_AT_88PCT"
            and r_r08_fail_conf["promotion_authorized"] is False
            and r_r08_fail_conf["parallel_cmc_ledger_verified"] is False
            and r_r08_fail_conf["lot_bank_hierarchy_valid"] is False
            and r_r08_fail_conf["deff"] is None
            and any("CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST" in fr for fr in r_r08_fail_conf["failure_reasons"])
        ):
            raise ValueError(
                f"R08 B2b non-infused CMC row ancestry check failed: ok={r_r08_noninf_ok}, uninf={r_r08_uninf_conf}, fail={r_r08_fail_conf}"
            )
        cases.append({"case": "b2b_r08_gate28a_noninfused_released_and_failed_cmc_rows_mcb_conflict_rejected", "passed": True})

        # 43. R08 B2c: Non-infused CMC row (absent from manifest) declaring W0 -> M1 contradicts manifest W0 -> M0!
        cmc_r08_wcb_tree_conf = _derive_reconciling_cmc_lot_ledger_from_recipients(r08_bal60, r08_mcb_map) + [
            {
                "lot_id": "L_UNINF_WCB_BAD", "mcb_id": "M1", "wcb_id": "W0", "lot_type": "SINGLE_RECIPIENT",
                "disposition": "RELEASED_UNINFUSED", "planned_doses_n": 1, "infused_doses_n": 0,
                "c2b_responder_doses_n": 0, "recipient_ids": [], "recipient_outcomes": {},
            },
        ]
        p_r08_wcb_tree_conf, _ = build_valid_gate28a_reference_bundle(
            r08_store,
            r08_bal60,
            cohort_id="COHORT-R08-B2-WCB-TREE-CONF",
            lot_to_mcb_manifest=r08_mcb_map,
            lot_to_wcb_manifest=r08_wcb_map,
            parallel_cmc_lot_ledger=cmc_r08_wcb_tree_conf,
        )
        r_r08_wcb_tree_conf = evaluate_gate28a_h1_promotion(p_r08_wcb_tree_conf, trusted_clinical_store=r08_store)
        if not (
            r_r08_wcb_tree_conf["status"] == "HOLD_H1_AT_88PCT"
            and r_r08_wcb_tree_conf["promotion_authorized"] is False
            and r_r08_wcb_tree_conf["parallel_cmc_ledger_verified"] is False
            and r_r08_wcb_tree_conf["lot_bank_hierarchy_valid"] is False
            and r_r08_wcb_tree_conf["deff"] is None
            and any("CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST" in fr for fr in r_r08_wcb_tree_conf["failure_reasons"])
            and any("NON_UNIQUE_WCB_PARENTAGE" in fr for fr in r_r08_wcb_tree_conf["failure_reasons"])
        ):
            raise ValueError(f"R08 B2c non-infused CMC row WCB-to-MCB parentage conflict MUST fail closed: {r_r08_wcb_tree_conf}")
        cases.append({"case": "b2c_r08_gate28a_noninfused_cmc_row_wcb_parentage_conflict_rejected", "passed": True})

        # 44. R08 M2: Explicit course-equivalent weighted unit surfaced on p_infuse_given_released
        if not (
            cmc_multi.get("p_infuse_given_released_unit") == "infused_primary_course_equivalents_per_released_lot"
            and abs(cmc_multi["p_infuse_given_released"] - 0.50) < 1e-9
        ):
            raise ValueError(f"R08 M2 p_infuse_given_released_unit missing or invalid: {cmc_multi}")
        cases.append({"case": "m2_r08_cmc_p_infuse_given_released_course_equivalent_unit_surfaced", "passed": True})

        # --- R09 B1 & M3: Typed raw-CMC ancestry error propagation, strict JSON duplicate-key intake,
        #     ordinary clinical HOLD preservation, and separate variance-component ICC sum <= 1.0 bounds ---
        r09_store = tmp_dir_p / "r09_gate28a_store.json"
        r09_base_cmc = _derive_reconciling_cmc_lot_ledger_from_recipients(r08_bal60, r08_mcb_map)
        for row_b in r09_base_cmc:
            if row_b["lot_id"] == "L00":
                row_b["wcb_id"] = "W0"

        # 45. R09 B1a: Positive 60-recipient control with raw CMC W0 on L00 promotes, while adding failed-release
        #     lot F01 reusing W0 under M1 MUST fail closed with null deff/n_eff/k_eff and all ancestry flags False!
        p_r09_ctrl, _ = build_valid_gate28a_reference_bundle(
            r09_store,
            r08_bal60,
            cohort_id="COHORT-R09-B1-CTRL",
            lot_to_mcb_manifest=r08_mcb_map,
            lot_to_wcb_manifest=r08_wcb_map,
            parallel_cmc_lot_ledger=r09_base_cmc,
        )
        r_r09_ctrl = evaluate_gate28a_h1_promotion(p_r09_ctrl, trusted_clinical_store=r09_store)
        cmc_r09_wcb_reuse = copy.deepcopy(r09_base_cmc) + [
            {
                "lot_id": "F01", "mcb_id": "M1", "wcb_id": "W0",
                "lot_type": "SINGLE_RECIPIENT", "disposition": "FAILED_RELEASE",
                "planned_doses_n": 1, "infused_doses_n": 0,
            }
        ]
        p_r09_wcb_reuse, _ = build_valid_gate28a_reference_bundle(
            r09_store,
            r08_bal60,
            cohort_id="COHORT-R09-B1-WCB-REUSE",
            lot_to_mcb_manifest=r08_mcb_map,
            lot_to_wcb_manifest=r08_wcb_map,
            parallel_cmc_lot_ledger=cmc_r09_wcb_reuse,
        )
        r_r09_wcb_reuse = evaluate_gate28a_h1_promotion(p_r09_wcb_reuse, trusted_clinical_store=r09_store)
        if not (
            r_r09_ctrl["status"] == "PROMOTE_H1_88_TO_90"
            and r_r09_ctrl["promotion_authorized"] is True
            and r_r09_ctrl["lot_bank_hierarchy_valid"] is True
            and r_r09_ctrl["lot_to_mcb_manifest_verified"] is True
            and r_r09_ctrl["lot_to_wcb_manifest_verified"] is True
            and r_r09_ctrl["parallel_cmc_ledger_verified"] is True
            and abs(r_r09_ctrl["deff"] - 1.53) < 1e-6
            and abs(r_r09_ctrl["n_eff"] - 39.215686) < 1e-5
            and abs(r_r09_ctrl["k_eff"] - 39.215686) < 1e-5
            and r_r09_wcb_reuse["status"] == "HOLD_H1_AT_88PCT"
            and r_r09_wcb_reuse["promotion_authorized"] is False
            and r_r09_wcb_reuse["parallel_cmc_ledger_verified"] is False
            and r_r09_wcb_reuse["lot_bank_hierarchy_valid"] is False
            and r_r09_wcb_reuse["lot_to_mcb_manifest_verified"] is False
            and r_r09_wcb_reuse["lot_to_wcb_manifest_verified"] is False
            and r_r09_wcb_reuse["deff"] is None
            and r_r09_wcb_reuse["n_eff"] is None
            and r_r09_wcb_reuse["k_eff"] is None
            and any("NON_UNIQUE_WCB_PARENTAGE" in fr for fr in r_r09_wcb_reuse["failure_reasons"])
        ):
            raise ValueError(f"R09 B1a raw CMC WCB reuse across infused+failed lots check failed: ctrl={r_r09_ctrl}, wcb={r_r09_wcb_reuse}")
        cases.append({"case": "b1a_r09_gate28a_raw_cmc_wcb_reuse_infused_and_failed_lot_invalidates_hierarchy", "passed": True})

        # 46. R09 B1b: Released-uninfused raw CMC row with canonical MCB vs recognized MCB alias (and WCB alias)
        #     contradicting verified manifest MUST fail closed with null deff/n_eff/k_eff and all ancestry flags False!
        r09_mcb_u01 = dict(r08_mcb_map, U01="M0")
        for lbl_al9, extra_row_al9, exp_tok_al9 in (
            (
                "master_cell_bank_id",
                {
                    "lot_id": "U01", "mcb_id": "M1", "master_cell_bank_id": "M0",
                    "lot_type": "SINGLE_RECIPIENT", "disposition": "RELEASED_UNINFUSED",
                    "planned_doses_n": 1, "infused_doses_n": 0,
                },
                "CONFLICTING_MCB_ALIAS",
            ),
            (
                "bank_id",
                {
                    "lot_id": "U01", "mcb_id": "M1", "bank_id": "M0",
                    "lot_type": "SINGLE_RECIPIENT", "disposition": "RELEASED_UNINFUSED",
                    "planned_doses_n": 1, "infused_doses_n": 0,
                },
                "CONFLICTING_MCB_ALIAS",
            ),
            (
                "working_cell_bank_id",
                {
                    "lot_id": "U01", "mcb_id": "M0", "wcb_id": "W0", "working_cell_bank_id": "W9",
                    "lot_type": "SINGLE_RECIPIENT", "disposition": "RELEASED_UNINFUSED",
                    "planned_doses_n": 1, "infused_doses_n": 0,
                },
                "CONFLICTING_WCB_ALIAS",
            ),
        ):
            p_al9, _ = build_valid_gate28a_reference_bundle(
                r09_store,
                r08_bal60,
                cohort_id=f"COHORT-R09-B1-ALIAS-{lbl_al9.upper()}",
                lot_to_mcb_manifest=r09_mcb_u01,
                lot_to_wcb_manifest=r08_wcb_map,
                parallel_cmc_lot_ledger=copy.deepcopy(r09_base_cmc) + [extra_row_al9],
            )
            r_al9 = evaluate_gate28a_h1_promotion(p_al9, trusted_clinical_store=r09_store)
            if not (
                r_al9["status"] == "HOLD_H1_AT_88PCT"
                and r_al9["promotion_authorized"] is False
                and r_al9["parallel_cmc_ledger_verified"] is False
                and r_al9["lot_bank_hierarchy_valid"] is False
                and r_al9["lot_to_mcb_manifest_verified"] is False
                and r_al9["lot_to_wcb_manifest_verified"] is False
                and r_al9["deff"] is None
                and r_al9["n_eff"] is None
                and r_al9["k_eff"] is None
                and any(exp_tok_al9 in fr for fr in r_al9["failure_reasons"])
            ):
                raise ValueError(f"R09 B1b raw CMC alias conflict ({lbl_al9}) MUST invalidate hierarchy: {r_al9}")
        cases.append({"case": "b1b_r09_gate28a_raw_cmc_mcb_and_wcb_alias_conflict_on_noninfused_row_invalidates_hierarchy", "passed": True})

        # 47. R09 B1c: Compound non-ancestry mask attack, duplicate JSON keys in raw CMC bytes, AND recipient lot_id
        #     swap within same MCB ALL invalidate hierarchy and nullify deff/n_eff/k_eff!
        cmc_r09_mask = copy.deepcopy(r09_base_cmc) + [
            {
                "lot_id": "F01", "mcb_id": "M1", "wcb_id": "W0",
                "lot_type": "SINGLE_RECIPIENT", "disposition": "FAILED_RELEASE",
                "planned_doses_n": 1, "infused_doses_n": 0,
            }
        ]
        cmc_r09_mask[0]["planned_doses_n"] = 0  # non-ancestry CMC error preceding WCB conflict
        p_r09_mask, _ = build_valid_gate28a_reference_bundle(
            r09_store,
            r08_bal60,
            cohort_id="COHORT-R09-B1-COMPOUND-MASK",
            lot_to_mcb_manifest=r08_mcb_map,
            lot_to_wcb_manifest=r08_wcb_map,
            parallel_cmc_lot_ledger=cmc_r09_mask,
        )
        r_r09_mask = evaluate_gate28a_h1_promotion(p_r09_mask, trusted_clinical_store=r09_store)

        # Duplicate JSON key in raw PARALLEL_CMC_READINESS_LEDGER bytes stored hash-pinned in trusted_clinical_store
        dup_cmc_json_str = (
            '{"cohort_id":"COHORT-R09-B1-DUPJSON","issuer_authority_id":"OPENISLET_CLINICAL_ADJUDICATION_BOARD_V1",'
            '"lot_ledger":[{"disposition":"RELEASED_UNINFUSED","infused_doses_n":0,"lot_id":"U01","lot_type":"SINGLE_RECIPIENT",'
            '"mcb_id":"M0","mcb_id":"M1","planned_doses_n":1}],"record_type":"PARALLEL_CMC_READINESS_LEDGER"}\n'
        )
        dup_cmc_bytes = dup_cmc_json_str.encode("utf-8")
        dup_cmc_sha = sha256_bytes(dup_cmc_bytes)
        p_r09_dup = {
            "cohort_id": "COHORT-R09-B1-DUPJSON",
            **GATE_28A_COMPATIBILITY_TARGET,
            "includes_reichman": False,
            "rho_lot": GATE_28A_RHO_LOT_MIN,
            "rho_bank": GATE_28A_RHO_BANK_MIN,
            "primary_peer_reviewed_full_text_verified": True,
            "parallel_cmc_readiness_ledger_disclosed": True,
            "parallel_cmc_readiness_ledger_sha256": dup_cmc_sha,
            "lot_to_mcb_manifest": copy.deepcopy(r08_mcb_map),
            "lot_to_wcb_manifest": copy.deepcopy(r08_wcb_map),
            "recipients": copy.deepcopy(r08_bal60),
        }
        dup_canon = compute_gate28a_cohort_canonical_sha256(p_r09_dup)
        dup_prespec = build_gate28a_prespecification_attestation(cohort_id="COHORT-R09-B1-DUPJSON", cohort_canonical_sha256=dup_canon)
        dup_source = build_gate28a_source_verification_attestation(
            cohort_id="COHORT-R09-B1-DUPJSON", cohort_canonical_sha256=dup_canon, parallel_cmc_readiness_ledger_sha256=dup_cmc_sha
        )
        dup_mrec = build_gate28a_verified_lot_to_bank_manifest(
            cohort_id="COHORT-R09-B1-DUPJSON", lot_to_mcb_manifest=r08_mcb_map, lot_to_wcb_manifest=r08_wcb_map
        )
        write_gate28a_trusted_clinical_store(
            r09_store,
            prespecification_attestations=[dup_prespec],
            source_verification_attestations=[dup_source],
            verified_lot_to_bank_manifests=[dup_mrec],
            parallel_cmc_readiness_ledgers=[dup_cmc_bytes],
        )
        p_r09_dup["clinical_store_refs"] = {
            "prespecification_attestation_sha256": dup_prespec["record_sha256"],
            "source_verification_attestation_sha256": dup_source["record_sha256"],
            "verified_lot_to_bank_manifest_sha256": dup_mrec["record_sha256"],
            "parallel_cmc_readiness_ledger_sha256": dup_cmc_sha,
        }
        r_r09_dup = evaluate_gate28a_h1_promotion(p_r09_dup, trusted_clinical_store=r09_store)

        # Recipient lot_id swap within same MCB M0 (R08-00-0 <-> R08-01-0 between L00 and L01)
        cmc_r09_lotswap = copy.deepcopy(r09_base_cmc)
        row_l00 = next(x for x in cmc_r09_lotswap if x["lot_id"] == "L00")
        row_l01 = next(x for x in cmc_r09_lotswap if x["lot_id"] == "L01")
        row_l00["recipient_outcomes"].pop("R08-00-0")
        row_l00["recipient_outcomes"]["R08-01-0"] = 1
        row_l00["recipient_ids"] = sorted(row_l00["recipient_outcomes"].keys())
        row_l01["recipient_outcomes"].pop("R08-01-0")
        row_l01["recipient_outcomes"]["R08-00-0"] = 1
        row_l01["recipient_ids"] = sorted(row_l01["recipient_outcomes"].keys())
        p_r09_lotswap, _ = build_valid_gate28a_reference_bundle(
            r09_store,
            r08_bal60,
            cohort_id="COHORT-R09-B1-LOTSWAP",
            lot_to_mcb_manifest=r08_mcb_map,
            lot_to_wcb_manifest=r08_wcb_map,
            parallel_cmc_lot_ledger=cmc_r09_lotswap,
        )
        r_r09_lotswap = evaluate_gate28a_h1_promotion(p_r09_lotswap, trusted_clinical_store=r09_store)

        for lbl_c9, res_c9 in (("compound_mask", r_r09_mask), ("dup_json_key", r_r09_dup), ("lot_swap", r_r09_lotswap)):
            if not (
                res_c9["status"] == "HOLD_H1_AT_88PCT"
                and res_c9["promotion_authorized"] is False
                and res_c9["parallel_cmc_ledger_verified"] is False
                and res_c9["lot_bank_hierarchy_valid"] is False
                and res_c9["lot_to_mcb_manifest_verified"] is False
                and res_c9["lot_to_wcb_manifest_verified"] is False
                and res_c9["deff"] is None
                and res_c9["n_eff"] is None
                and res_c9["k_eff"] is None
            ):
                raise ValueError(f"R09 B1c ({lbl_c9}) MUST fail closed with null cluster outputs: {res_c9}")
        if not any("Duplicate JSON object key" in fr for fr in r_r09_dup["failure_reasons"]):
            raise ValueError(f"R09 B1c duplicate JSON key reason missing: {r_r09_dup}")
        cases.append({"case": "b1c_r09_gate28a_compound_mask_duplicate_json_key_and_recipient_lot_mismatch_invalidate_hierarchy", "passed": True})

        # 48. R09 B1d: Ordinary non-ancestry clinical HOLD (54/60 responders, valid manifest & reconciling CMC)
        #     holds promotion WHILE preserving valid hierarchy flags and exact cluster outputs!
        r09_hold_60 = copy.deepcopy(r08_bal60)
        for i_fail in range(6):
            r09_hold_60[i_fail * 10]["met_c2b_criteria"] = False
        cmc_r09_hold = _derive_reconciling_cmc_lot_ledger_from_recipients(r09_hold_60, r08_mcb_map)
        for row_h in cmc_r09_hold:
            if row_h["lot_id"] == "L00":
                row_h["wcb_id"] = "W0"
        p_r09_hold, _ = build_valid_gate28a_reference_bundle(
            r09_store,
            r09_hold_60,
            cohort_id="COHORT-R09-B1-ORD-HOLD",
            lot_to_mcb_manifest=r08_mcb_map,
            lot_to_wcb_manifest=r08_wcb_map,
            parallel_cmc_lot_ledger=cmc_r09_hold,
        )
        r_r09_hold = evaluate_gate28a_h1_promotion(p_r09_hold, trusted_clinical_store=r09_store)
        if not (
            r_r09_hold["status"] == "HOLD_H1_AT_88PCT"
            and r_r09_hold["promotion_authorized"] is False
            and r_r09_hold["lot_bank_hierarchy_valid"] is True
            and r_r09_hold["lot_to_mcb_manifest_verified"] is True
            and r_r09_hold["lot_to_wcb_manifest_verified"] is True
            and r_r09_hold["parallel_cmc_ledger_verified"] is True
            and abs(r_r09_hold["deff"] - 1.53) < 1e-6
            and abs(r_r09_hold["n_eff"] - 39.215686) < 1e-5
            and abs(r_r09_hold["k_eff"] - 35.294118) < 1e-5
        ):
            raise ValueError(f"R09 B1d ordinary non-ancestry clinical HOLD regression failed: {r_r09_hold}")
        cases.append({"case": "b1d_r09_gate28a_ordinary_clinical_hold_preserves_valid_hierarchy_and_cluster_outputs", "passed": True})

        # 49. R09 M3: Separate variance-component ICC bounds (0 <= rho_lot, 0 <= rho_bank, rho_lot + rho_bank <= 1.0)
        #     fail closed on sum > 1.0 or negative/below-floor ICC, accept sum == 1.0 boundary, and verify sensitivity!
        p_icc_over, _ = build_valid_gate28a_reference_bundle(
            r09_store, r08_bal60, cohort_id="COHORT-R09-ICC-OVER", lot_to_mcb_manifest=r08_mcb_map,
            lot_to_wcb_manifest=r08_wcb_map, parallel_cmc_lot_ledger=r09_base_cmc, rho_lot=0.7, rho_bank=0.5,
        )
        r_icc_over = evaluate_gate28a_h1_promotion(p_icc_over, trusted_clinical_store=r09_store)
        p_icc_eps, _ = build_valid_gate28a_reference_bundle(
            r09_store, r08_bal60, cohort_id="COHORT-R09-ICC-EPS", lot_to_mcb_manifest=r08_mcb_map,
            lot_to_wcb_manifest=r08_wcb_map, parallel_cmc_lot_ledger=r09_base_cmc, rho_lot=0.6, rho_bank=0.400001,
        )
        r_icc_eps = evaluate_gate28a_h1_promotion(p_icc_eps, trusted_clinical_store=r09_store)
        p_icc_neg, _ = build_valid_gate28a_reference_bundle(
            r09_store, r08_bal60, cohort_id="COHORT-R09-ICC-NEG", lot_to_mcb_manifest=r08_mcb_map,
            lot_to_wcb_manifest=r08_wcb_map, parallel_cmc_lot_ledger=r09_base_cmc, rho_lot=-0.05, rho_bank=0.02,
        )
        r_icc_neg = evaluate_gate28a_h1_promotion(p_icc_neg, trusted_clinical_store=r09_store)
        p_icc_eq1, _ = build_valid_gate28a_reference_bundle(
            r09_store, r08_bal60, cohort_id="COHORT-R09-ICC-EQ1", lot_to_mcb_manifest=r08_mcb_map,
            lot_to_wcb_manifest=r08_wcb_map, parallel_cmc_lot_ledger=r09_base_cmc, rho_lot=0.6, rho_bank=0.4,
        )
        r_icc_eq1 = evaluate_gate28a_h1_promotion(p_icc_eq1, trusted_clinical_store=r09_store)
        p_icc_mod, _ = build_valid_gate28a_reference_bundle(
            r09_store, r08_bal60, cohort_id="COHORT-R09-ICC-MOD", lot_to_mcb_manifest=r08_mcb_map,
            lot_to_wcb_manifest=r08_wcb_map, parallel_cmc_lot_ledger=r09_base_cmc, rho_lot=0.10, rho_bank=0.05,
        )
        r_icc_mod = evaluate_gate28a_h1_promotion(p_icc_mod, trusted_clinical_store=r09_store)
        p_icc_hi, _ = build_valid_gate28a_reference_bundle(
            r09_store, r08_bal60, cohort_id="COHORT-R09-ICC-HI", lot_to_mcb_manifest=r08_mcb_map,
            lot_to_wcb_manifest=r08_wcb_map, parallel_cmc_lot_ledger=r09_base_cmc, rho_lot=0.15, rho_bank=0.10,
        )
        r_icc_hi = evaluate_gate28a_h1_promotion(p_icc_hi, trusted_clinical_store=r09_store)
        if not (
            r_icc_over["promotion_authorized"] is False
            and r_icc_over["deff"] is None
            and r_icc_over["n_eff"] is None
            and r_icc_over["k_eff"] is None
            and any("INVALID_ICC_SUM_EXCEEDS_ONE" in fr for fr in r_icc_over["failure_reasons"])
            and r_icc_eps["promotion_authorized"] is False
            and r_icc_eps["deff"] is None
            and any("INVALID_ICC_SUM_EXCEEDS_ONE" in fr for fr in r_icc_eps["failure_reasons"])
            and r_icc_neg["promotion_authorized"] is False
            and r_icc_neg["deff"] is None
            and any("INVALID_ICC_DOMAIN" in fr for fr in r_icc_neg["failure_reasons"])
            and r_icc_eq1["promotion_authorized"] is False
            and r_icc_eq1["deff"] is not None
            and abs(r_icc_eq1["deff"] - 10.4) < 1e-6
            and not any("INVALID_ICC" in fr for fr in r_icc_eq1["failure_reasons"])
            and r_icc_mod["promotion_authorized"] is True
            and abs(r_icc_mod["deff"] - 2.25) < 1e-6
            and abs(r_icc_mod["n_eff"] - 26.666667) < 1e-5
            and r_icc_hi["promotion_authorized"] is False
            and abs(r_icc_hi["deff"] - 3.35) < 1e-6
            and abs(r_icc_hi["n_eff"] - 17.910448) < 1e-5
        ):
            raise ValueError(
                f"R09 M3 ICC sum/sensitivity checks failed: over={r_icc_over}, eps={r_icc_eps}, "
                f"neg={r_icc_neg}, eq1={r_icc_eq1}, mod={r_icc_mod}, hi={r_icc_hi}"
            )
        cases.append({"case": "m3_r09_gate28a_icc_variance_component_sum_le_1_enforced_and_sensitivity_verified", "passed": True})

        # --- R10 B1, B2, M1, M2: Exact bidirectional rescue identity & cardinality (0/1/2), Pass-0 unconditional
        #     clinical ancestry extraction independent of follow-up/outcome/duplicate/CMC-shape errors, explicit
        #     infused CMC WCB attestation, and Reichman cryptococcal death context ---
        r10_store = tmp_dir_p / "r10_gate28a_store.json"
        r10_plain60 = [
            {
                "recipient_id": f"R{lot:02d}-{rep}",
                "lot_id": f"L{lot:02d}",
                "mcb_id": f"M{lot // 5}",
                "followup_months": 12,
                "met_c2b_criteria": True,
                "intercurrent_event": "NONE",
            }
            for lot in range(15)
            for rep in range(4)
        ]
        r10_bank_map = {r["lot_id"]: r["mcb_id"] for r in r10_plain60}
        r10_plain_rows = _derive_reconciling_cmc_lot_ledger_from_recipients(r10_plain60, r10_bank_map)

        # 50. R10 B1: Exact bidirectional rescue identity & cardinality reconciliation (0, 1, 2 rescues + extra/missing/duplicate rejections)
        p_r10_zero, _ = build_valid_gate28a_reference_bundle(
            r10_store, r10_plain60, cohort_id="COHORT-R10-RESC-0",
            lot_to_mcb_manifest=r10_bank_map, parallel_cmc_lot_ledger=r10_plain_rows,
        )
        r_r10_zero = evaluate_gate28a_h1_promotion(p_r10_zero, trusted_clinical_store=r10_store)

        r10_resc_base60 = [
            {
                "recipient_id": f"R{lot:02d}-{rep}",
                "lot_id": f"L{lot:02d}",
                "mcb_id": f"M{lot // 3}",
                "followup_months": 12,
                "met_c2b_criteria": True,
                "intercurrent_event": "NONE",
            }
            for lot in range(15)
            for rep in range(4)
        ]
        r10_resc_bank_map = {r["lot_id"]: r["mcb_id"] for r in r10_resc_base60}

        r10_resc1 = copy.deepcopy(r10_resc_base60)
        r10_resc1[0].update(intercurrent_event="RESCUE_REPEAT_INFUSION", rescue_lot_id="RA")
        r10_resc1_rows = _derive_reconciling_cmc_lot_ledger_from_recipients(r10_resc1, r10_resc_bank_map)
        r10_resc2_rows = copy.deepcopy(r10_resc1_rows) + [{
            "lot_id": "RB", "mcb_id": "M0", "lot_type": "RESCUE_REPEAT_LOT",
            "disposition": "RELEASED_INFUSED", "planned_doses_n": 1, "infused_doses_n": 1,
            "rescued_recipient_id": "R00-0", "rescued_primary_lot_id": "L00",
            "recipient_outcomes": {"R00-0": True},
        }]
        p_r10_one_ok, _ = build_valid_gate28a_reference_bundle(
            r10_store, r10_resc1, cohort_id="COHORT-R10-RESC-1-OK",
            lot_to_mcb_manifest={**r10_resc_bank_map, "RA": "M0"}, parallel_cmc_lot_ledger=r10_resc1_rows,
        )
        r_r10_one_ok = evaluate_gate28a_h1_promotion(p_r10_one_ok, trusted_clinical_store=r10_store)

        # Extra CMC rescue RB omitted from clinical cohort (clinical=['RA'] vs CMC=['RA','RB'], both in manifest) -> HOLD!
        p_r10_extra_rb, _ = build_valid_gate28a_reference_bundle(
            r10_store, r10_resc1, cohort_id="COHORT-R10-RESC-EXTRA-RB",
            lot_to_mcb_manifest={**r10_resc_bank_map, "RA": "M0", "RB": "M0"}, parallel_cmc_lot_ledger=r10_resc2_rows,
        )
        r_r10_extra_rb = evaluate_gate28a_h1_promotion(p_r10_extra_rb, trusted_clinical_store=r10_store)

        # Exact-match 2 rescues: clinical rescue_lot_ids=['RA','RB'] vs CMC=['RA','RB'] -> PROMOTE!
        r10_resc2_clin = copy.deepcopy(r10_resc_base60)
        r10_resc2_clin[0].update(intercurrent_event="RESCUE_REPEAT_INFUSION", rescue_lot_ids=["RA", "RB"])
        p_r10_two_ok, _ = build_valid_gate28a_reference_bundle(
            r10_store, r10_resc2_clin, cohort_id="COHORT-R10-RESC-2-OK",
            lot_to_mcb_manifest={**r10_resc_bank_map, "RA": "M0", "RB": "M0"}, parallel_cmc_lot_ledger=r10_resc2_rows,
        )
        r_r10_two_ok = evaluate_gate28a_h1_promotion(p_r10_two_ok, trusted_clinical_store=r10_store)

        # Clinical declares 2 rescues ['RA','RB'] while CMC has only ['RA'] -> HOLD!
        p_r10_two_vs_one, _ = build_valid_gate28a_reference_bundle(
            r10_store, r10_resc2_clin, cohort_id="COHORT-R10-RESC-2-VS-1",
            lot_to_mcb_manifest={**r10_resc_bank_map, "RA": "M0", "RB": "M0"}, parallel_cmc_lot_ledger=r10_resc1_rows,
        )
        r_r10_two_vs_one = evaluate_gate28a_h1_promotion(p_r10_two_vs_one, trusted_clinical_store=r10_store)

        # Unindexed clinical rescue (ie_only) vs 2 CMC rescues ['RA','RB'] -> HOLD!
        r10_resc_ie_only = copy.deepcopy(r10_resc_base60)
        r10_resc_ie_only[0]["intercurrent_event"] = "RESCUE_REPEAT_INFUSION"
        p_r10_ie_vs_two, _ = build_valid_gate28a_reference_bundle(
            r10_store, r10_resc_ie_only, cohort_id="COHORT-R10-RESC-IE-VS-2",
            lot_to_mcb_manifest={**r10_resc_bank_map, "RA": "M0", "RB": "M0"}, parallel_cmc_lot_ledger=r10_resc2_rows,
        )
        r_r10_ie_vs_two = evaluate_gate28a_h1_promotion(p_r10_ie_vs_two, trusted_clinical_store=r10_store)

        # Duplicate identical RA rescue row in CMC -> fails closed with DUPLICATE_LOT_ID_IN_CMC_LEDGER!
        r10_dup_ra_rows = copy.deepcopy(r10_resc1_rows) + [{
            "lot_id": "RA", "mcb_id": "M0", "lot_type": "RESCUE_REPEAT_LOT",
            "disposition": "RELEASED_INFUSED", "planned_doses_n": 1, "infused_doses_n": 1,
            "rescued_recipient_id": "R00-0", "rescued_primary_lot_id": "L00",
            "recipient_outcomes": {"R00-0": True},
        }]
        p_r10_dup_ra, _ = build_valid_gate28a_reference_bundle(
            r10_store, r10_resc1, cohort_id="COHORT-R10-RESC-DUP-RA",
            lot_to_mcb_manifest={**r10_resc_bank_map, "RA": "M0"}, parallel_cmc_lot_ledger=r10_dup_ra_rows,
        )
        r_r10_dup_ra = evaluate_gate28a_h1_promotion(p_r10_dup_ra, trusted_clinical_store=r10_store)

        if not (
            r_r10_zero["status"] == "PROMOTE_H1_88_TO_90"
            and r_r10_zero["promotion_authorized"] is True
            and r_r10_one_ok["status"] == "PROMOTE_H1_88_TO_90"
            and r_r10_one_ok["promotion_authorized"] is True
            and r_r10_one_ok["parallel_cmc_ledger_verified"] is True
            and r_r10_extra_rb["status"] == "HOLD_H1_AT_88PCT"
            and r_r10_extra_rb["promotion_authorized"] is False
            and r_r10_extra_rb["parallel_cmc_ledger_verified"] is False
            and any("CMC_EXTRA_RESCUE_LOT_OMITTED_FROM_CLINICAL_COHORT" in fr for fr in r_r10_extra_rb["failure_reasons"])
            and any("RESCUE_LOT_CARDINALITY_MISMATCH" in fr for fr in r_r10_extra_rb["failure_reasons"])
            and r_r10_two_ok["status"] == "PROMOTE_H1_88_TO_90"
            and r_r10_two_ok["promotion_authorized"] is True
            and r_r10_two_ok["parallel_cmc_ledger_verified"] is True
            and r_r10_two_ok["parallel_cmc_readiness_summary"]["attempted_lots_n"] == 17
            and r_r10_two_ok["parallel_cmc_readiness_summary"]["rescue_lots_n"] == 2
            and r_r10_two_vs_one["status"] == "HOLD_H1_AT_88PCT"
            and r_r10_two_vs_one["promotion_authorized"] is False
            and r_r10_two_vs_one["parallel_cmc_ledger_verified"] is False
            and any("RESCUE_LOT_CARDINALITY_MISMATCH" in fr for fr in r_r10_two_vs_one["failure_reasons"])
            and r_r10_ie_vs_two["status"] == "HOLD_H1_AT_88PCT"
            and r_r10_ie_vs_two["promotion_authorized"] is False
            and r_r10_ie_vs_two["parallel_cmc_ledger_verified"] is False
            and any("CMC_EXTRA_RESCUE_LOT_OMITTED_FROM_CLINICAL_COHORT" in fr for fr in r_r10_ie_vs_two["failure_reasons"])
            and r_r10_dup_ra["status"] == "HOLD_H1_AT_88PCT"
            and r_r10_dup_ra["promotion_authorized"] is False
            and r_r10_dup_ra["parallel_cmc_ledger_verified"] is False
            and r_r10_dup_ra["lot_bank_hierarchy_valid"] is False
            and r_r10_dup_ra["deff"] is None
        ):
            raise ValueError(
                f"R10 B1 exact rescue identity/cardinality checks failed: zero={r_r10_zero}, one={r_r10_one_ok}, "
                f"extra_rb={r_r10_extra_rb}, two_ok={r_r10_two_ok}, two_vs_one={r_r10_two_vs_one}, "
                f"ie_vs_two={r_r10_ie_vs_two}, dup_ra={r_r10_dup_ra}"
            )
        cases.append({"case": "b1_r10_gate28a_exact_bidirectional_rescue_identity_and_cardinality_0_1_2_enforced", "passed": True})

        # 51. R10 B2a: Pass-0 unconditional clinical ancestry catches cross-MCB swap masked by missing followup_months
        #     (and missing met_c2b_criteria) and unconditionally clears ALL 4 flags + nullifies deff/n_eff/k_eff!
        r10_obs_wcb = copy.deepcopy(r10_plain60)
        for row_w in r10_obs_wcb:
            if row_w["lot_id"] == "L00":
                row_w["wcb_id"] = "W0"
        r10_annot_rows = copy.deepcopy(r10_plain_rows)
        r10_annot_rows[0]["wcb_id"] = "W0"
        r10_swapped_rows = copy.deepcopy(r10_annot_rows)
        for row_idx_s, old_rid, new_rid in ((0, "R00-0", "R05-0"), (5, "R05-0", "R00-0")):
            srow = r10_swapped_rows[row_idx_s]
            srow["recipient_outcomes"][new_rid] = srow["recipient_outcomes"].pop(old_rid)
            srow["recipient_ids"] = [new_rid if rid_x == old_rid else rid_x for rid_x in srow["recipient_ids"]]
        r10_both_nofu = copy.deepcopy(r10_obs_wcb)
        r10_both_nofu[0]["followup_months"] = None
        r10_both_nofu[20]["followup_months"] = None
        p_r10_swap_nofu, _ = build_valid_gate28a_reference_bundle(
            r10_store, r10_both_nofu, cohort_id="COHORT-R10-SWAP-NOFU",
            lot_to_mcb_manifest=r10_bank_map, lot_to_wcb_manifest={"L00": "W0"},
            parallel_cmc_lot_ledger=r10_swapped_rows,
        )
        r_r10_swap_nofu = evaluate_gate28a_h1_promotion(p_r10_swap_nofu, trusted_clinical_store=r10_store)

        r10_both_noc2b = copy.deepcopy(r10_obs_wcb)
        r10_both_noc2b[0]["met_c2b_criteria"] = None
        r10_both_noc2b[20]["intercurrent_event"] = "INVALID_IE"
        p_r10_swap_noc2b, _ = build_valid_gate28a_reference_bundle(
            r10_store, r10_both_noc2b, cohort_id="COHORT-R10-SWAP-NOC2B",
            lot_to_mcb_manifest=r10_bank_map, lot_to_wcb_manifest={"L00": "W0"},
            parallel_cmc_lot_ledger=r10_swapped_rows,
        )
        r_r10_swap_noc2b = evaluate_gate28a_h1_promotion(p_r10_swap_noc2b, trusted_clinical_store=r10_store)

        for lbl_sw10, res_sw10 in (("missing_followup", r_r10_swap_nofu), ("invalid_outcome_and_ie", r_r10_swap_noc2b)):
            if not (
                res_sw10["status"] == "HOLD_H1_AT_88PCT"
                and res_sw10["promotion_authorized"] is False
                and res_sw10["parallel_cmc_ledger_verified"] is False
                and res_sw10["lot_bank_hierarchy_valid"] is False
                and res_sw10["lot_to_mcb_manifest_verified"] is False
                and res_sw10["lot_to_wcb_manifest_verified"] is False
                and res_sw10["deff"] is None
                and res_sw10["n_eff"] is None
                and res_sw10["k_eff"] is None
                and any("CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST" in fr for fr in res_sw10["failure_reasons"])
            ):
                raise ValueError(f"R10 B2a cross-MCB swap ({lbl_sw10}) MUST invalidate all 4 flags + null cluster outputs: {res_sw10}")
        cases.append({"case": "b2a_r10_gate28a_pass0_cross_mcb_swap_masked_by_missing_followup_invalidates_ancestry", "passed": True})

        # 52. R10 B2b: Pass-0 catches conflicting duplicate clinical recipient rows (both conflicting bank M9 and cross-lot L05/M1)!
        r10_dupe_m9 = copy.deepcopy(r10_obs_wcb)
        r10_dupe_m9.append({**r10_dupe_m9[0], "mcb_id": "M9"})
        p_r10_dupe_m9, _ = build_valid_gate28a_reference_bundle(
            r10_store, r10_dupe_m9, cohort_id="COHORT-R10-DUPE-M9",
            lot_to_mcb_manifest=r10_bank_map, lot_to_wcb_manifest={"L00": "W0"},
            parallel_cmc_lot_ledger=r10_annot_rows,
        )
        r_r10_dupe_m9 = evaluate_gate28a_h1_promotion(p_r10_dupe_m9, trusted_clinical_store=r10_store)

        r10_dupe_crosslot = copy.deepcopy(r10_obs_wcb)
        r10_dupe_crosslot.append({**r10_dupe_crosslot[0], "lot_id": "L05", "mcb_id": "M1", "wcb_id": None})
        p_r10_dupe_xlot, _ = build_valid_gate28a_reference_bundle(
            r10_store, r10_dupe_crosslot, cohort_id="COHORT-R10-DUPE-XLOT",
            lot_to_mcb_manifest=r10_bank_map, lot_to_wcb_manifest={"L00": "W0"},
            parallel_cmc_lot_ledger=r10_annot_rows,
        )
        r_r10_dupe_xlot = evaluate_gate28a_h1_promotion(p_r10_dupe_xlot, trusted_clinical_store=r10_store)

        for lbl_dp10, res_dp10 in (("same_lot_m9", r_r10_dupe_m9), ("cross_lot_l05_m1", r_r10_dupe_xlot)):
            if not (
                res_dp10["status"] == "HOLD_H1_AT_88PCT"
                and res_dp10["promotion_authorized"] is False
                and res_dp10["parallel_cmc_ledger_verified"] is False
                and res_dp10["lot_bank_hierarchy_valid"] is False
                and res_dp10["lot_to_mcb_manifest_verified"] is False
                and res_dp10["lot_to_wcb_manifest_verified"] is False
                and res_dp10["deff"] is None
                and res_dp10["n_eff"] is None
                and res_dp10["k_eff"] is None
                and any("CONFLICTING_DUPLICATE_RECIPIENT_ANCESTRY" in fr for fr in res_dp10["failure_reasons"])
            ):
                raise ValueError(f"R10 B2b conflicting duplicate clinical recipient ({lbl_dp10}) MUST invalidate all 4 flags + null cluster outputs: {res_dp10}")
        cases.append({"case": "b2b_r10_gate28a_pass0_conflicting_duplicate_clinical_recipient_invalidates_ancestry", "passed": True})

        # 53. R10 B2c: Pass-0-backed error-path audit catches cross-MCB mismatch masked by BOTH missing followup_months
        #     AND an unrelated CMC record-shape failure!
        r10_bad_rows = copy.deepcopy(r10_plain_rows)
        r10_bad_rows[0]["recipient_outcomes"].pop("R00-0")
        r10_bad_rows[0]["recipient_outcomes"]["R05-0"] = True
        r10_bad_rec = copy.deepcopy(r10_plain60)
        r10_bad_rec[20]["followup_months"] = None
        p_r10_mask_err, _ = build_valid_gate28a_reference_bundle(
            r10_store, r10_bad_rec, cohort_id="COHORT-R10-MASK-ERRPATH",
            lot_to_mcb_manifest=r10_bank_map, parallel_cmc_lot_ledger=r10_bad_rows,
        )
        r_r10_mask_err = evaluate_gate28a_h1_promotion(p_r10_mask_err, trusted_clinical_store=r10_store)
        if not (
            r_r10_mask_err["status"] == "HOLD_H1_AT_88PCT"
            and r_r10_mask_err["promotion_authorized"] is False
            and r_r10_mask_err["parallel_cmc_ledger_verified"] is False
            and r_r10_mask_err["lot_bank_hierarchy_valid"] is False
            and r_r10_mask_err["lot_to_mcb_manifest_verified"] is False
            and r_r10_mask_err["lot_to_wcb_manifest_verified"] is False
            and r_r10_mask_err["deff"] is None
            and r_r10_mask_err["n_eff"] is None
            and r_r10_mask_err["k_eff"] is None
            and any("CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST" in fr for fr in r_r10_mask_err["failure_reasons"])
        ):
            raise ValueError(f"R10 B2c error-path audit masked by followup + CMC shape error MUST invalidate all 4 flags: {r_r10_mask_err}")
        cases.append({"case": "b2c_r10_gate28a_pass0_error_path_audit_catches_swap_masked_by_followup_and_cmc_shape", "passed": True})

        # 54. R10 M1: Infused CMC row MUST explicitly declare matching wcb_id whenever VERIFIED_LOT_TO_BANK_MANIFEST
        #     declares wcb_id for that lot (matched-wcb promotes; missing-infused-cmc-wcb fails closed!)
        p_r10_wcb_match, _ = build_valid_gate28a_reference_bundle(
            r10_store, r10_obs_wcb, cohort_id="COHORT-R10-WCB-MATCH",
            lot_to_mcb_manifest=r10_bank_map, lot_to_wcb_manifest={"L00": "W0"},
            parallel_cmc_lot_ledger=r10_annot_rows,
        )
        r_r10_wcb_match = evaluate_gate28a_h1_promotion(p_r10_wcb_match, trusted_clinical_store=r10_store)

        p_r10_wcb_omitted, _ = build_valid_gate28a_reference_bundle(
            r10_store, r10_obs_wcb, cohort_id="COHORT-R10-WCB-OMITTED",
            lot_to_mcb_manifest=r10_bank_map, lot_to_wcb_manifest={"L00": "W0"},
            parallel_cmc_lot_ledger=r10_plain_rows,
        )
        r_r10_wcb_omitted = evaluate_gate28a_h1_promotion(p_r10_wcb_omitted, trusted_clinical_store=r10_store)
        if not (
            r_r10_wcb_match["status"] == "PROMOTE_H1_88_TO_90"
            and r_r10_wcb_match["promotion_authorized"] is True
            and r_r10_wcb_match["parallel_cmc_ledger_verified"] is True
            and r_r10_wcb_match["lot_to_wcb_manifest_verified"] is True
            and r_r10_wcb_omitted["status"] == "HOLD_H1_AT_88PCT"
            and r_r10_wcb_omitted["promotion_authorized"] is False
            and r_r10_wcb_omitted["parallel_cmc_ledger_verified"] is False
            and r_r10_wcb_omitted["lot_bank_hierarchy_valid"] is False
            and r_r10_wcb_omitted["lot_to_mcb_manifest_verified"] is False
            and r_r10_wcb_omitted["lot_to_wcb_manifest_verified"] is False
            and r_r10_wcb_omitted["deff"] is None
            and r_r10_wcb_omitted["n_eff"] is None
            and r_r10_wcb_omitted["k_eff"] is None
            and any("CMC_INFUSED_LOT_MISSING_DECLARED_WCB_ID" in fr for fr in r_r10_wcb_omitted["failure_reasons"])
        ):
            raise ValueError(
                f"R10 M1 explicit infused CMC WCB attestation failed: match={r_r10_wcb_match}, omitted={r_r10_wcb_omitted}"
            )
        cases.append({"case": "m1_r10_gate28a_infused_cmc_row_missing_manifest_declared_wcb_fails_closed", "passed": True})

        # 55. R10 M2: Reichman cryptococcal meningitis death entry preserves full NEJM clinical context
        part_a_r10 = analyze_clinical_h1_reanchor()
        reich_r10 = next(
            e for e in part_a_r10["per_study_endpoint_adjudication_ledger"]
            if e["study_id"] == "Reichman_2025_NEJM_PMID_40544428"
        )
        d1_txt = reich_r10["published_counts"]["trial_deaths_product_vs_regimen_attribution"]["death_1_cryptococcal_meningitis"]
        if not (
            "skull-base injury" in d1_txt
            and "prolonged protocol-prohibited systemic glucocorticoids" in d1_txt
            and "concurrent chronic immunosuppression" in d1_txt
            and "UNRELATED to zimislecel" in d1_txt
            and "RELATED to the chronic immunosuppressive" in d1_txt
        ):
            raise ValueError(f"R10 M2 Reichman cryptococcal death context incomplete: {d1_txt}")
        cases.append({"case": "m2_r10_reichman_cryptococcal_death_clinical_context_preserved", "passed": True})

        # --- R11 B1, B2, B3, M1, M2, M3: Final-Closure Self-Tests (Cases 56-61) ---
        r11_store = tmp_dir_p / "r11_gate28a_store.json"

        # 56. R11 B1: Deterministic ITT non-response events (MISSING_PRIMARY_ENDPOINT_OR_LTFU, PRE_LANDMARK_DEATH,
        #     PRIMARY_GRAFT_NON_FUNCTION) with endpoint & follow-up omitted/None adjudicate to 0 BEFORE endpoint checks
        #     and MUST reject CMC=1 (parallel_cmc_ledger_verified=False + CMC_OUTCOME_MISMATCH) while matching CMC=0!
        #     Also: non-response-exempt IE="NONE" with missing follow-up MUST NOT skip CMC reconciliation (missing adjudication fails closed!).
        for ie_nr_lbl in ("MISSING_PRIMARY_ENDPOINT_OR_LTFU", "PRE_LANDMARK_DEATH", "PRIMARY_GRAFT_NON_FUNCTION"):
            for omit_mode in ("omitted", "explicit_none"):
                r11_nr_recs = copy.deepcopy(r10_plain60)
                r11_nr_recs[0]["intercurrent_event"] = ie_nr_lbl
                if omit_mode == "omitted":
                    r11_nr_recs[0].pop("met_c2b_criteria", None)
                    r11_nr_recs[0].pop("followup_months", None)
                else:
                    r11_nr_recs[0]["met_c2b_criteria"] = None
                    r11_nr_recs[0]["followup_months"] = None

                cmc_nr_contra = copy.deepcopy(r10_plain_rows)  # R00-0 == 1 contradicting clinical 0
                p_nr_contra, _ = build_valid_gate28a_reference_bundle(
                    r11_store, r11_nr_recs, cohort_id=f"COHORT-R11-B1-{ie_nr_lbl}-{omit_mode}-CONTRA",
                    lot_to_mcb_manifest=r10_bank_map, parallel_cmc_lot_ledger=cmc_nr_contra,
                )
                r_nr_contra = evaluate_gate28a_h1_promotion(p_nr_contra, trusted_clinical_store=r11_store)

                cmc_nr_match = copy.deepcopy(r10_plain_rows)
                cmc_nr_match[0]["recipient_outcomes"]["R00-0"] = 0
                cmc_nr_match[0]["c2b_responder_doses_n"] = 3
                p_nr_match, _ = build_valid_gate28a_reference_bundle(
                    r11_store, r11_nr_recs, cohort_id=f"COHORT-R11-B1-{ie_nr_lbl}-{omit_mode}-MATCH",
                    lot_to_mcb_manifest=r10_bank_map, parallel_cmc_lot_ledger=cmc_nr_match,
                )
                r_nr_match = evaluate_gate28a_h1_promotion(p_nr_match, trusted_clinical_store=r11_store)

                if not (
                    r_nr_contra["parallel_cmc_ledger_verified"] is False
                    and r_nr_contra["promotion_authorized"] is False
                    and r_nr_contra["k"] == 59
                    and any("CMC_OUTCOME_MISMATCH" in fr for fr in r_nr_contra["failure_reasons"])
                    and r_nr_match["parallel_cmc_ledger_verified"] is True
                    and r_nr_match["k"] == 59
                    and not any("CMC_OUTCOME_MISMATCH" in fr for fr in r_nr_match["failure_reasons"])
                ):
                    raise ValueError(
                        f"R11 B1 deterministic non-response CMC reconciliation failed ({ie_nr_lbl}/{omit_mode}): "
                        f"contra={r_nr_contra}, match={r_nr_match}"
                    )

        r11_unadj = copy.deepcopy(r10_plain60)
        r11_unadj[0]["followup_months"] = None  # IE='NONE' -> cannot adjudicate clinical outcome
        p_unadj, _ = build_valid_gate28a_reference_bundle(
            r11_store, r11_unadj, cohort_id="COHORT-R11-B1-UNRECONCILED-NONE",
            lot_to_mcb_manifest=r10_bank_map, parallel_cmc_lot_ledger=r10_plain_rows,
        )
        r_unadj = evaluate_gate28a_h1_promotion(p_unadj, trusted_clinical_store=r11_store)
        if not (
            r_unadj["parallel_cmc_ledger_verified"] is False
            and r_unadj["promotion_authorized"] is False
            and any("CMC_OUTCOME_UNRECONCILED_MISSING_CLINICAL_ADJUDICATION" in fr for fr in r_unadj["failure_reasons"])
        ):
            raise ValueError(f"R11 B1 unreconciled clinical outcome MUST fail CMC verification: {r_unadj}")
        cases.append({"case": "b1_r11_gate28a_deterministic_nonresponse_omitted_fields_reconciled_against_cmc", "passed": True})

        # 57. R11 B2: Duplicate clinical rescue rows (RA, RB) vs (RB, RA) produce 100% IDENTICAL order-independent
        #     results with parallel_cmc_ledger_verified=False in BOTH orders; identical duplicates also fail CMC
        #     reconciliation; unindexed single rescue without explicit rescue_lot_id fails closed!
        r11_dup_ab = copy.deepcopy(r10_resc_base60)
        r11_dup_ab[0].update(intercurrent_event="RESCUE_REPEAT_INFUSION", rescue_lot_id="RA")
        r11_dup_ab.append({**r10_resc_base60[0], "intercurrent_event": "RESCUE_REPEAT_INFUSION", "rescue_lot_id": "RB"})
        r11_dup_ba = copy.deepcopy(r10_resc_base60)
        r11_dup_ba[0].update(intercurrent_event="RESCUE_REPEAT_INFUSION", rescue_lot_id="RB")
        r11_dup_ba.append({**r10_resc_base60[0], "intercurrent_event": "RESCUE_REPEAT_INFUSION", "rescue_lot_id": "RA"})

        p_dup_ab, _ = build_valid_gate28a_reference_bundle(
            r11_store, r11_dup_ab, cohort_id="COHORT-R11-B2-DUP-RESC",
            lot_to_mcb_manifest={**r10_resc_bank_map, "RA": "M0", "RB": "M0"},
            parallel_cmc_lot_ledger=r10_resc1_rows,
        )
        p_dup_ba, _ = build_valid_gate28a_reference_bundle(
            r11_store, r11_dup_ba, cohort_id="COHORT-R11-B2-DUP-RESC",
            lot_to_mcb_manifest={**r10_resc_bank_map, "RA": "M0", "RB": "M0"},
            parallel_cmc_lot_ledger=r10_resc1_rows,
        )
        r_dup_ab = evaluate_gate28a_h1_promotion(p_dup_ab, trusted_clinical_store=r11_store)
        r_dup_ba = evaluate_gate28a_h1_promotion(p_dup_ba, trusted_clinical_store=r11_store)

        # Identical non-conflicting duplicate (RA, RA) still invalidates 1:1 CMC reconciliation
        r11_dup_aa = copy.deepcopy(r10_resc_base60)
        r11_dup_aa[0].update(intercurrent_event="RESCUE_REPEAT_INFUSION", rescue_lot_id="RA")
        r11_dup_aa.append({**r10_resc_base60[0], "intercurrent_event": "RESCUE_REPEAT_INFUSION", "rescue_lot_id": "RA"})
        p_dup_aa, _ = build_valid_gate28a_reference_bundle(
            r11_store, r11_dup_aa, cohort_id="COHORT-R11-B2-DUP-AA",
            lot_to_mcb_manifest={**r10_resc_bank_map, "RA": "M0"},
            parallel_cmc_lot_ledger=r10_resc1_rows,
        )
        r_dup_aa = evaluate_gate28a_h1_promotion(p_dup_aa, trusted_clinical_store=r11_store)

        # Unindexed single clinical rescue (omitting rescue_lot_id) vs single CMC rescue RA MUST fail closed!
        r11_unindexed_1 = copy.deepcopy(r10_resc_base60)
        r11_unindexed_1[0]["intercurrent_event"] = "RESCUE_REPEAT_INFUSION"
        p_unidx_1, _ = build_valid_gate28a_reference_bundle(
            r11_store, r11_unindexed_1, cohort_id="COHORT-R11-B2-UNINDEXED-1",
            lot_to_mcb_manifest={**r10_resc_bank_map, "RA": "M0"},
            parallel_cmc_lot_ledger=r10_resc1_rows,
        )
        r_unidx_1 = evaluate_gate28a_h1_promotion(p_unidx_1, trusted_clinical_store=r11_store)

        if not (
            r_dup_ab["cohort_canonical_sha256"] == r_dup_ba["cohort_canonical_sha256"]
            and r_dup_ab == r_dup_ba
            and r_dup_ab["parallel_cmc_ledger_verified"] is False
            and r_dup_ba["parallel_cmc_ledger_verified"] is False
            and r_dup_ab["lot_bank_hierarchy_valid"] is False
            and r_dup_ab["lot_to_mcb_manifest_verified"] is False
            and r_dup_ab["lot_to_wcb_manifest_verified"] is False
            and r_dup_ab["deff"] is None
            and r_dup_ab["n_eff"] is None
            and r_dup_ab["k_eff"] is None
            and r_dup_ab["icc_sensitivity_report_attached"] is False
            and r_dup_ab["icc_sensitivity_report"] is None
            and r_dup_ab["promotion_authorized"] is False
            and any("CONFLICTING_DUPLICATE_RECIPIENT_RESCUE" in fr for fr in r_dup_ab["failure_reasons"])
            and any("DUPLICATE_CLINICAL_RECIPIENT_INVALIDATES_CMC_RECONCILIATION" in fr for fr in r_dup_ab["failure_reasons"])
            and any("CLINICAL_RESCUE_LOT_ID_MISMATCH_IN_CMC_LEDGER" in fr for fr in r_dup_ab["failure_reasons"])
            and r_dup_aa["parallel_cmc_ledger_verified"] is False
            and any("DUPLICATE_CLINICAL_RECIPIENT_INVALIDATES_CMC_RECONCILIATION" in fr for fr in r_dup_aa["failure_reasons"])
            and r_unidx_1["parallel_cmc_ledger_verified"] is False
            and r_unidx_1["promotion_authorized"] is False
            and any("CLINICAL_RESCUE_MISSING_EXPLICIT_LOT_ID" in fr for fr in r_unidx_1["failure_reasons"])
        ):
            raise ValueError(
                f"R11 B2 duplicate rescue order-independence / explicit lot ID check failed: "
                f"ab={r_dup_ab}, ba={r_dup_ba}, aa={r_dup_aa}, unidx1={r_unidx_1}"
            )
        cases.append({"case": "b2_r11_gate28a_duplicate_clinical_rescue_order_independent_and_explicit_lot_id_required", "passed": True})

        # 58. R11 B3: Prespecified 3-scenario same-cohort icc_sensitivity_report and 4-state icc_sensitivity_review_status
        #     (ROBUST 3/3 promote; BOUNDARY_SENSITIVE primary+moderate promote with disclosure; MODERATE FAIL HARD HOLD;
        #      PRIMARY FAIL HARD HOLD; below-floor supplied ICC rejected with icc_sensitivity_report_attached=False!)
        p_good30_hold, _ = build_valid_gate28a_reference_bundle(r11_store, good_30, cohort_id="COHORT-R11-B3-GOOD30-MODHOLD")
        r_good30_hold = evaluate_gate28a_h1_promotion(p_good30_hold, trusted_clinical_store=r11_store)

        r11_59of60_3mcb = copy.deepcopy(r10_plain60)
        r11_59of60_3mcb[0]["met_c2b_criteria"] = False
        p_59_3mcb, _ = build_valid_gate28a_reference_bundle(
            r11_store, r11_59of60_3mcb, cohort_id="COHORT-R11-B3-59OF60-3MCB-MODHOLD",
            lot_to_mcb_manifest=r10_bank_map,
        )
        r_59_3mcb = evaluate_gate28a_h1_promotion(p_59_3mcb, trusted_clinical_store=r11_store)

        p_below_floor, _ = build_valid_gate28a_reference_bundle(
            r11_store, robust_45, cohort_id="COHORT-R11-B3-BELOW-FLOOR", rho_lot=0.04, rho_bank=0.02
        )
        r_below_floor = evaluate_gate28a_h1_promotion(p_below_floor, trusted_clinical_store=r11_store)

        for scen_k in ("primary_floor", "moderate_sensitivity", "high_clustering_sensitivity"):
            if scen_k not in g28a_bal60_store["icc_sensitivity_report"]:
                raise ValueError(f"R11 B3 missing scenario {scen_k} in icc_sensitivity_report")
            for req_field in ("rho_lot", "rho_mcb", "deff_cluster", "n_eff", "posterior_mean", "posterior_p_ge_090", "meets_reanchor_bar"):
                if req_field not in g28a_bal60_store["icc_sensitivity_report"][scen_k]:
                    raise ValueError(f"R11 B3 missing field {req_field} in scenario {scen_k}")

        if not (
            g28a_ok["icc_sensitivity_report_attached"] is True
            and g28a_ok["boundary_sensitive_under_high_icc"] is False
            and g28a_ok["icc_sensitivity_review_status"] == "ROBUST_ACROSS_ALL_THREE_PRESPECIFIED_ICC_SCENARIOS"
            and g28a_ok["icc_sensitivity_report"]["high_clustering_sensitivity"]["meets_reanchor_bar"] is True
            and g28a_bal60_store["icc_sensitivity_report_attached"] is True
            and g28a_bal60_store["boundary_sensitive_under_high_icc"] is True
            and g28a_bal60_store["icc_sensitivity_review_status"] == "BOUNDARY_SENSITIVE_DISCLOSED_CLEARS_PRIMARY_AND_MODERATE"
            and g28a_bal60_store["promotion_authorized"] is True
            and g28a_bal60_store["icc_sensitivity_report"]["primary_floor"]["meets_reanchor_bar"] is True
            and g28a_bal60_store["icc_sensitivity_report"]["moderate_sensitivity"]["meets_reanchor_bar"] is True
            and g28a_bal60_store["icc_sensitivity_report"]["high_clustering_sensitivity"]["meets_reanchor_bar"] is False
            and abs(g28a_bal60_store["icc_sensitivity_report"]["high_clustering_sensitivity"]["n_eff"] - 17.910448) < 1e-5
            and r_good30_hold["icc_sensitivity_report_attached"] is True
            and r_good30_hold["boundary_sensitive_under_high_icc"] is False
            and r_good30_hold["icc_sensitivity_review_status"] == "HOLD_FAILS_MODERATE_ICC_SENSITIVITY"
            and r_good30_hold["promotion_authorized"] is False
            and r_good30_hold["status"] == "HOLD_H1_AT_88PCT"
            and any("HOLD_FAILS_MODERATE_ICC_SENSITIVITY" in fr for fr in r_good30_hold["failure_reasons"])
            and r_59_3mcb["icc_sensitivity_report_attached"] is True
            and r_59_3mcb["icc_sensitivity_review_status"] == "HOLD_FAILS_MODERATE_ICC_SENSITIVITY"
            and r_59_3mcb["promotion_authorized"] is False
            and r_r09_hold["icc_sensitivity_report_attached"] is True
            and r_r09_hold["icc_sensitivity_review_status"] == "HOLD_FAILS_PRIMARY_ICC_FLOOR"
            and r_r09_hold["promotion_authorized"] is False
            and r_below_floor["icc_sensitivity_report_attached"] is False
            and r_below_floor["icc_sensitivity_report"] is None
            and r_below_floor["promotion_authorized"] is False
            and any("INVALID_ICC_DOMAIN" in fr for fr in r_below_floor["failure_reasons"])
        ):
            raise ValueError(
                f"R11 B3 3-scenario ICC sensitivity report check failed: ok={g28a_ok}, bal60={g28a_bal60_store}, "
                f"good30={r_good30_hold}, c59={r_59_3mcb}, r09hold={r_r09_hold}, below={r_below_floor}"
            )
        cases.append({"case": "b3_r11_gate28a_three_scenario_icc_sensitivity_report_and_four_state_rule", "passed": True})

        # 59. R11 M1: Structural mmCIF helper prefers wwPDB label_asym_id over auth_asym_id, preserving 4X4M Assembly 2
        #     glycan label chains L (14 heavy atoms) and M (10 heavy atoms, total 24 heavy atoms sharing auth_asym_id='D'),
        #     exact protein (>=7.709 A) and glycan (>=21.821 A) distances, AND catching a positive-control 3.5 A contact on L!
        def _build_synthetic_4x4m_asm2_cif(glyc_l_x: float) -> str:
            cif_lines = [
                "data_SYNTH_4X4M_ASM2",
                "#",
                "loop_",
                "_struct_conn.id",
                "_struct_conn.conn_type_id",
                "_struct_conn.ptnr1_label_asym_id",
                "_struct_conn.ptnr1_auth_asym_id",
                "_struct_conn.ptnr1_auth_comp_id",
                "_struct_conn.ptnr1_auth_seq_id",
                "_struct_conn.ptnr2_label_asym_id",
                "_struct_conn.ptnr2_auth_asym_id",
                "_struct_conn.ptnr2_auth_comp_id",
                "_struct_conn.ptnr2_auth_seq_id",
                "covale4 covale D D ASN 297 L D NAG 1001",
                "#",
                "loop_",
                "_struct_ref_seq_dif.pdbx_pdb_strand_id",
                "_struct_ref_seq_dif.pdbx_seq_db_seq_num",
                "_struct_ref_seq_dif.db_mon_id",
                "_struct_ref_seq_dif.mon_id",
                "_struct_ref_seq_dif.details",
                "F 163 ASN SER 'engineered mutation'",
                "#",
                "loop_",
                "_atom_site.group_PDB",
                "_atom_site.id",
                "_atom_site.type_symbol",
                "_atom_site.label_atom_id",
                "_atom_site.label_comp_id",
                "_atom_site.label_asym_id",
                "_atom_site.label_seq_id",
                "_atom_site.Cartn_x",
                "_atom_site.Cartn_y",
                "_atom_site.Cartn_z",
                "_atom_site.auth_seq_id",
                "_atom_site.auth_comp_id",
                "_atom_site.auth_asym_id",
                "ATOM 1 O OG SER F 163 0.000 0.000 0.000 163 SER F",
                "ATOM 2 C CA ASN D 297 7.709 0.000 0.000 297 ASN D",
            ]
            aid = 3
            for i_l in range(14):
                cif_lines.append(
                    f"HETATM {aid} C C{i_l + 1} NAG L . {glyc_l_x + 0.1 * i_l:.3f} 0.000 0.000 1001 NAG D"
                )
                aid += 1
            for i_m in range(10):
                cif_lines.append(
                    f"HETATM {aid} C C{i_m + 1} FUC M . {22.500 + 0.1 * i_m:.3f} 0.000 0.000 1002 FUC D"
                )
                aid += 1
            return "\n".join(cif_lines) + "\n"

        synth_cif_ok = tmp_dir_p / "synth_4x4m_asm2_ok.cif"
        synth_cif_ok.write_text(_build_synthetic_4x4m_asm2_cif(21.821), encoding="utf-8")
        res_m1_ok = parse_mmcif_interface_contacts(
            synth_cif_ok,
            receptor_chains={"F"},
            partner_chains={"C", "D", "I", "J", "K", "L", "M"},
            cutoff_angstrom=4.5,
            include_partner_hetatm=True,
            partner_protein_chains={"C", "D"},
        )
        synth_cif_hit = tmp_dir_p / "synth_4x4m_asm2_hit.cif"
        synth_cif_hit.write_text(_build_synthetic_4x4m_asm2_cif(3.500), encoding="utf-8")
        res_m1_hit = parse_mmcif_interface_contacts(
            synth_cif_hit,
            receptor_chains={"F"},
            partner_chains={"C", "D", "I", "J", "K", "L", "M"},
            cutoff_angstrom=4.5,
            include_partner_hetatm=True,
            partner_protein_chains={"C", "D"},
        )
        if not (
            res_m1_ok["chain_id_namespace"] == "label_asym_id_preferred_with_auth_asym_id_fallback"
            and res_m1_ok["fc_linked_glycan_chains_from_struct_conn"] == ["L"]
            and res_m1_ok["partner_fc_hetatm_glycan_heavy_atoms_by_chain"] == {"L": 14, "M": 10}
            and res_m1_ok["partner_fc_hetatm_glycan_heavy_atoms_total"] == 24
            and abs(res_m1_ok["min_engineered_mutation_dist_to_partner_protein_A"] - 7.709) < 1e-3
            and abs(res_m1_ok["min_engineered_mutation_dist_to_partner_glycan_A"] - 21.821) < 1e-3
            and res_m1_ok["engineered_mutations_in_protein_contacts_le_4p5A"] == []
            and res_m1_ok["engineered_mutations_in_fc_glycan_contacts_le_4p5A"] == []
            and res_m1_hit["engineered_mutations_in_fc_glycan_contacts_le_4p5A"] == ["N163S"]
            and abs(res_m1_hit["min_engineered_mutation_dist_to_partner_glycan_A"] - 3.500) < 1e-3
        ):
            raise ValueError(f"R11 M1 label_asym_id glycan inventory/distance check failed: ok={res_m1_ok}, hit={res_m1_hit}")
        cases.append({"case": "m1_r11_mmcif_label_asym_id_glycan_inventory_and_distance_audit", "passed": True})

        # 60. R11 M2: Early rejections (n == 0 all-missing-mcb_id, empty recipients=[], non-dict payload) MUST return
        #     explicit False (never None or omitted!) for ALL 4 ancestry/ledger verification flags AND icc_sensitivity_report_attached=False!
        r11_no_mcb = [
            {"recipient_id": f"NM-{i:02d}", "lot_id": "L00", "followup_months": 12, "met_c2b_criteria": True, "intercurrent_event": "NONE"}
            for i in range(5)
        ]
        p_early_nomcb = {
            "cohort_id": "COHORT-R11-M2-NOMCB",
            **GATE_28A_COMPATIBILITY_TARGET,
            "includes_reichman": False,
            "recipients": r11_no_mcb,
        }
        p_early_empty = {
            "cohort_id": "COHORT-R11-M2-EMPTY",
            **GATE_28A_COMPATIBILITY_TARGET,
            "includes_reichman": False,
            "recipients": [],
        }
        for lbl_m2, res_m2 in (
            ("all_missing_mcb_n0", evaluate_gate28a_h1_promotion(p_early_nomcb, trusted_clinical_store=r11_store)),
            ("empty_recipients", evaluate_gate28a_h1_promotion(p_early_empty, trusted_clinical_store=r11_store)),
            ("non_dict_payload", evaluate_gate28a_h1_promotion("not-a-dict", trusted_clinical_store=r11_store)),  # type: ignore[arg-type]
        ):
            if not (
                res_m2["promotion_authorized"] is False
                and res_m2["status"] == "HOLD_H1_AT_88PCT"
                and res_m2["lot_bank_hierarchy_valid"] is False
                and res_m2["lot_to_mcb_manifest_verified"] is False
                and res_m2["lot_to_wcb_manifest_verified"] is False
                and res_m2["parallel_cmc_ledger_verified"] is False
                and res_m2["icc_sensitivity_report_attached"] is False
                and res_m2["icc_sensitivity_report"] is None
                and res_m2["deff"] is None
                and res_m2["n_eff"] is None
                and res_m2["k_eff"] is None
            ):
                raise ValueError(f"R11 M2 early rejection ({lbl_m2}) missing explicit False flags: {res_m2}")
        cases.append({"case": "m2_r11_gate28a_early_rejection_explicit_false_flags_and_no_sensitivity_report", "passed": True})

        # 61. R11 M3: Semantic canonicalization of WCB ancestry aliases:
        #     (a) working_cell_bank_id alone (without wcb_id) reconciles cleanly against manifest lot_to_wcb_manifest;
        #     (b) adding identical top-level lot_to_wcb_manifest alongside matching nested WCB in lot_to_mcb_manifest
        #         leaves cohort_canonical_sha256 invariant; semantic WCB mutation changes digest and fails closed!
        r11_wcb_alias_recs = copy.deepcopy(r10_plain60)
        for rec_wa in r11_wcb_alias_recs:
            if rec_wa["lot_id"] == "L00":
                rec_wa["working_cell_bank_id"] = "W0"
        r11_wcb_alias_cmc = copy.deepcopy(r10_plain_rows)
        r11_wcb_alias_cmc[0]["working_cell_bank_id"] = "W0"
        p_wcb_alias, _ = build_valid_gate28a_reference_bundle(
            r11_store, r11_wcb_alias_recs, cohort_id="COHORT-R11-M3-WCB-ALIAS",
            lot_to_mcb_manifest={lid: ({"mcb_id": mid, "wcb_id": "W0"} if lid == "L00" else mid) for lid, mid in r10_bank_map.items()},
            lot_to_wcb_manifest=None,
            parallel_cmc_lot_ledger=r11_wcb_alias_cmc,
        )
        sha_nested_only = compute_gate28a_cohort_canonical_sha256(p_wcb_alias)
        p_wcb_alias_plus_top = copy.deepcopy(p_wcb_alias)
        p_wcb_alias_plus_top["lot_to_wcb_manifest"] = {"L00": "W0"}
        sha_nested_plus_matching_top = compute_gate28a_cohort_canonical_sha256(p_wcb_alias_plus_top)
        p_wcb_alias_mut = copy.deepcopy(p_wcb_alias)
        p_wcb_alias_mut["lot_to_wcb_manifest"] = {"L00": "W9"}
        sha_mutated_wcb = compute_gate28a_cohort_canonical_sha256(p_wcb_alias_mut)
        r_m3_ok = evaluate_gate28a_h1_promotion(p_wcb_alias_plus_top, trusted_clinical_store=r11_store)
        r_m3_mut = evaluate_gate28a_h1_promotion(p_wcb_alias_mut, trusted_clinical_store=r11_store)
        if not (
            sha_nested_only == sha_nested_plus_matching_top
            and sha_mutated_wcb != sha_nested_only
            and r_m3_ok["promotion_authorized"] is True
            and r_m3_ok["lot_to_wcb_manifest_verified"] is True
            and r_m3_mut["promotion_authorized"] is False
            and r_m3_mut["lot_to_wcb_manifest_verified"] is False
        ):
            raise ValueError(
                f"R11 M3 semantic canonicalization check failed: sha_same={sha_nested_only == sha_nested_plus_matching_top}, "
                f"sha_diff={sha_mutated_wcb != sha_nested_only}, ok={r_m3_ok}, mut={r_m3_mut}"
            )
        cases.append({"case": "m3_r11_gate28a_semantic_canonicalization_wcb_aliases_and_mutation_rejection", "passed": True})

        # --- R12 B1, B2, B3, M1: Final-Closure Self-Tests (Cases 62-65) ---
        r12_store = tmp_dir_p / "r12_gate28a_store.json"

        # 62. R12 B1: Decision-relevant top-level control flags (`primary_peer_reviewed_full_text_verified` and
        #     `parallel_cmc_readiness_ledger_disclosed`) are injectively bound into `cohort_canonical_sha256`
        #     (and reconciled against SOURCE_VERIFICATION_ATTESTATION):
        #     On a 120-recipient / 30-lot / 10-MCB cohort with both flags False -> HOLD; deleting both flags,
        #     deleting either single flag, toggling False->True post-attestation, mutating invalid non-bool values
        #     (including literal "__ABSENT__"), or adding a False flag post-attestation ALL alter cohort_canonical_sha256,
        #     invalidate stored attestations, and HOLD (NEVER PROMOTE)!
        r12_120 = [
            {
                "recipient_id": f"R12-{lot:02d}-{rep}",
                "lot_id": f"L12-{lot:02d}",
                "mcb_id": f"M12-{lot // 3}",
                "followup_months": 12,
                "met_c2b_criteria": True,
                "intercurrent_event": "NONE",
            }
            for lot in range(30)
            for rep in range(4)
        ]
        p_b1_false, _ = build_valid_gate28a_reference_bundle(
            r12_store,
            r12_120,
            cohort_id="COHORT-R12-B1-BOTH-FALSE",
            primary_peer_reviewed_full_text_verified=False,
            parallel_cmc_readiness_ledger_disclosed=False,
        )
        r_b1_false = evaluate_gate28a_h1_promotion(p_b1_false, trusted_clinical_store=r12_store)
        sha_b1_false = r_b1_false["cohort_canonical_sha256"]

        p_b1_del_both = copy.deepcopy(p_b1_false)
        p_b1_del_both.pop("primary_peer_reviewed_full_text_verified")
        p_b1_del_both.pop("parallel_cmc_readiness_ledger_disclosed")
        r_b1_del_both = evaluate_gate28a_h1_promotion(p_b1_del_both, trusted_clinical_store=r12_store)

        p_b1_del_pdf = copy.deepcopy(p_b1_false)
        p_b1_del_pdf.pop("primary_peer_reviewed_full_text_verified")
        r_b1_del_pdf = evaluate_gate28a_h1_promotion(p_b1_del_pdf, trusted_clinical_store=r12_store)

        p_b1_del_cmc = copy.deepcopy(p_b1_false)
        p_b1_del_cmc.pop("parallel_cmc_readiness_ledger_disclosed")
        r_b1_del_cmc = evaluate_gate28a_h1_promotion(p_b1_del_cmc, trusted_clinical_store=r12_store)

        p_b1_toggle_true = copy.deepcopy(p_b1_false)
        p_b1_toggle_true["primary_peer_reviewed_full_text_verified"] = True
        p_b1_toggle_true["parallel_cmc_readiness_ledger_disclosed"] = True
        r_b1_toggle_true = evaluate_gate28a_h1_promotion(p_b1_toggle_true, trusted_clinical_store=r12_store)

        p_b1_nonbool, _ = build_valid_gate28a_reference_bundle(
            r12_store,
            r12_120,
            cohort_id="COHORT-R12-B1-NONBOOL",
            primary_peer_reviewed_full_text_verified="__ABSENT__",
            parallel_cmc_readiness_ledger_disclosed=1,
        )
        r_b1_nonbool = evaluate_gate28a_h1_promotion(p_b1_nonbool, trusted_clinical_store=r12_store)
        p_b1_nonbool_del = copy.deepcopy(p_b1_nonbool)
        p_b1_nonbool_del.pop("primary_peer_reviewed_full_text_verified")
        p_b1_nonbool_del.pop("parallel_cmc_readiness_ledger_disclosed")
        r_b1_nonbool_del = evaluate_gate28a_h1_promotion(p_b1_nonbool_del, trusted_clinical_store=r12_store)

        p_b1_ok, _ = build_valid_gate28a_reference_bundle(
            r12_store,
            r12_120,
            cohort_id="COHORT-R12-B1-VALID-TRUE",
        )
        r_b1_ok = evaluate_gate28a_h1_promotion(p_b1_ok, trusted_clinical_store=r12_store)

        if not (
            r_b1_ok["status"] == "PROMOTE_H1_88_TO_90"
            and r_b1_ok["promotion_authorized"] is True
            and r_b1_false["status"] == "HOLD_H1_AT_88PCT"
            and r_b1_false["promotion_authorized"] is False
            and r_b1_false["source_verification_attestation_verified"] is False
            and r_b1_del_both["status"] == "HOLD_H1_AT_88PCT"
            and r_b1_del_both["promotion_authorized"] is False
            and r_b1_del_both["cohort_canonical_sha256"] != sha_b1_false
            and r_b1_del_both["prespecification_attestation_verified"] is False
            and r_b1_del_both["source_verification_attestation_verified"] is False
            and r_b1_del_pdf["promotion_authorized"] is False
            and r_b1_del_pdf["cohort_canonical_sha256"] != sha_b1_false
            and r_b1_del_pdf["prespecification_attestation_verified"] is False
            and r_b1_del_cmc["promotion_authorized"] is False
            and r_b1_del_cmc["cohort_canonical_sha256"] != sha_b1_false
            and r_b1_del_cmc["prespecification_attestation_verified"] is False
            and r_b1_toggle_true["status"] == "HOLD_H1_AT_88PCT"
            and r_b1_toggle_true["promotion_authorized"] is False
            and r_b1_toggle_true["cohort_canonical_sha256"] != sha_b1_false
            and r_b1_toggle_true["prespecification_attestation_verified"] is False
            and r_b1_toggle_true["source_verification_attestation_verified"] is False
            and r_b1_nonbool["promotion_authorized"] is False
            and r_b1_nonbool_del["promotion_authorized"] is False
            and r_b1_nonbool_del["cohort_canonical_sha256"] != r_b1_nonbool["cohort_canonical_sha256"]
            and r_b1_nonbool_del["prespecification_attestation_verified"] is False
        ):
            raise ValueError(
                f"R12 B1 control-flag canonical digest binding failed: ok={r_b1_ok}, false={r_b1_false}, "
                f"del_both={r_b1_del_both}, toggle={r_b1_toggle_true}, nonbool={r_b1_nonbool}, nonbool_del={r_b1_nonbool_del}"
            )
        cases.append({"case": "b1_r12_gate28a_control_flags_bound_in_canonical_digest_and_tamper_rejected", "passed": True})

        # 63. R12 B2: Recipient WCB alias normalization (`working_cell_bank_id` <-> `wcb_id`) BEFORE hashing:
        #     Given a verified WCB cohort attested with `wcb_id="W0"`, (a) replacing `wcb_id` with
        #     `working_cell_bank_id="W0"` AND (b) adding matching `working_cell_bank_id="W0"` alongside `wcb_id="W0"`
        #     BOTH yield the IDENTICAL `cohort_canonical_sha256`, verify unchanged stored attestations, and PROMOTE,
        #     while (c) adding conflicting `working_cell_bank_id="W_OTHER"` or invalid whitespace changes the digest
        #     and fails closed!
        r12_wcb_base = copy.deepcopy(r12_120)
        for rec_w12 in r12_wcb_base:
            if rec_w12["lot_id"] == "L12-00":
                rec_w12["wcb_id"] = "W0"
        p_b2_base, _ = build_valid_gate28a_reference_bundle(
            r12_store,
            r12_wcb_base,
            cohort_id="COHORT-R12-B2-WCB-NORM",
        )
        r_b2_base = evaluate_gate28a_h1_promotion(p_b2_base, trusted_clinical_store=r12_store)

        p_b2_swap = copy.deepcopy(p_b2_base)
        for rec_sw in p_b2_swap["recipients"]:
            if "wcb_id" in rec_sw:
                rec_sw["working_cell_bank_id"] = rec_sw.pop("wcb_id")
        r_b2_swap = evaluate_gate28a_h1_promotion(p_b2_swap, trusted_clinical_store=r12_store)

        p_b2_both_match = copy.deepcopy(p_b2_base)
        for rec_bm in p_b2_both_match["recipients"]:
            if "wcb_id" in rec_bm:
                rec_bm["working_cell_bank_id"] = rec_bm["wcb_id"]
        r_b2_both_match = evaluate_gate28a_h1_promotion(p_b2_both_match, trusted_clinical_store=r12_store)

        p_b2_conflict = copy.deepcopy(p_b2_base)
        p_b2_conflict["recipients"][0]["working_cell_bank_id"] = "W_OTHER"
        r_b2_conflict = evaluate_gate28a_h1_promotion(p_b2_conflict, trusted_clinical_store=r12_store)

        p_b2_bad_ws = copy.deepcopy(p_b2_base)
        p_b2_bad_ws["recipients"][0]["working_cell_bank_id"] = " W0"
        r_b2_bad_ws = evaluate_gate28a_h1_promotion(p_b2_bad_ws, trusted_clinical_store=r12_store)

        if not (
            r_b2_base["promotion_authorized"] is True
            and r_b2_swap["cohort_canonical_sha256"] == r_b2_base["cohort_canonical_sha256"]
            and r_b2_swap["promotion_authorized"] is True
            and r_b2_swap["prespecification_attestation_verified"] is True
            and r_b2_swap["source_verification_attestation_verified"] is True
            and r_b2_swap["lot_to_wcb_manifest_verified"] is True
            and r_b2_both_match["cohort_canonical_sha256"] == r_b2_base["cohort_canonical_sha256"]
            and r_b2_both_match["promotion_authorized"] is True
            and r_b2_both_match["prespecification_attestation_verified"] is True
            and r_b2_both_match["source_verification_attestation_verified"] is True
            and r_b2_conflict["cohort_canonical_sha256"] != r_b2_base["cohort_canonical_sha256"]
            and r_b2_conflict["promotion_authorized"] is False
            and r_b2_conflict["lot_bank_hierarchy_valid"] is False
            and r_b2_conflict["lot_to_wcb_manifest_verified"] is False
            and r_b2_conflict["deff"] is None
            and any("CONFLICTING_WCB_ALIAS" in fr for fr in r_b2_conflict["failure_reasons"])
            and r_b2_bad_ws["cohort_canonical_sha256"] != r_b2_base["cohort_canonical_sha256"]
            and r_b2_bad_ws["promotion_authorized"] is False
            and r_b2_bad_ws["lot_bank_hierarchy_valid"] is False
        ):
            raise ValueError(
                f"R12 B2 recipient WCB alias normalization check failed: base={r_b2_base}, swap={r_b2_swap}, "
                f"match={r_b2_both_match}, conflict={r_b2_conflict}, ws={r_b2_bad_ws}"
            )
        cases.append({"case": "b2_r12_gate28a_recipient_wcb_alias_semantic_canonicalization_and_conflict_preservation", "passed": True})

        # 64. R12 B3: Contradictory duplicate clinical rescue identities linked to incompatible lineages
        #     (RA -> M12-0/WR-A vs RB -> M12-1/WR-B, CMC records RA) route through the full fail-closed ancestry
        #     nullification path in BOTH row orders (RA, RB) and (RB, RA) with 100% identical outputs!
        r12_mcb_map = {f"L12-{lot:02d}": f"M12-{lot // 3}" for lot in range(30)}
        r12_resc_ra = copy.deepcopy(r12_120)
        r12_resc_ra[0].update(intercurrent_event="RESCUE_REPEAT_INFUSION", rescue_lot_id="RA")
        r12_resc_mcb_full = {**r12_mcb_map, "RA": "M12-0", "RB": "M12-1"}
        r12_resc_wcb_full = {"RA": "WR-A", "RB": "WR-B"}
        r12_cmc_ra = _derive_reconciling_cmc_lot_ledger_from_recipients(
            r12_resc_ra, r12_resc_mcb_full, lot_to_wcb_manifest=r12_resc_wcb_full
        )
        r12_dup_ab = copy.deepcopy(r12_120)
        r12_dup_ab[0].update(intercurrent_event="RESCUE_REPEAT_INFUSION", rescue_lot_id="RA")
        r12_dup_ab.append({**r12_120[0], "intercurrent_event": "RESCUE_REPEAT_INFUSION", "rescue_lot_id": "RB"})
        r12_dup_ba = copy.deepcopy(r12_120)
        r12_dup_ba[0].update(intercurrent_event="RESCUE_REPEAT_INFUSION", rescue_lot_id="RB")
        r12_dup_ba.append({**r12_120[0], "intercurrent_event": "RESCUE_REPEAT_INFUSION", "rescue_lot_id": "RA"})
        p_b3_ab, _ = build_valid_gate28a_reference_bundle(
            r12_store, r12_dup_ab, cohort_id="COHORT-R12-B3-DUP-LINEAGE",
            lot_to_mcb_manifest=r12_resc_mcb_full, lot_to_wcb_manifest=r12_resc_wcb_full,
            parallel_cmc_lot_ledger=r12_cmc_ra,
        )
        p_b3_ba, _ = build_valid_gate28a_reference_bundle(
            r12_store, r12_dup_ba, cohort_id="COHORT-R12-B3-DUP-LINEAGE",
            lot_to_mcb_manifest=r12_resc_mcb_full, lot_to_wcb_manifest=r12_resc_wcb_full,
            parallel_cmc_lot_ledger=r12_cmc_ra,
        )
        r_b3_ab = evaluate_gate28a_h1_promotion(p_b3_ab, trusted_clinical_store=r12_store)
        r_b3_ba = evaluate_gate28a_h1_promotion(p_b3_ba, trusted_clinical_store=r12_store)
        if not (
            r_b3_ab == r_b3_ba
            and r_b3_ab["status"] == "HOLD_H1_AT_88PCT"
            and r_b3_ab["promotion_authorized"] is False
            and r_b3_ab["external_clinical_store_verified"] is False
            and r_b3_ab["parallel_cmc_ledger_verified"] is False
            and r_b3_ab["lot_bank_hierarchy_valid"] is False
            and r_b3_ab["lot_to_mcb_manifest_verified"] is False
            and r_b3_ab["lot_to_wcb_manifest_verified"] is False
            and r_b3_ab["deff"] is None
            and r_b3_ab["n_eff"] is None
            and r_b3_ab["k_eff"] is None
            and r_b3_ab["icc_sensitivity_report_attached"] is False
            and r_b3_ab["icc_sensitivity_report"] is None
            and any("CONFLICTING_DUPLICATE_RECIPIENT_RESCUE" in fr for fr in r_b3_ab["failure_reasons"])
            and any("CONFLICTING_DUPLICATE_RECIPIENT_RESCUE_ANCESTRY" in fr for fr in r_b3_ab["failure_reasons"])
        ):
            raise ValueError(
                f"R12 B3 contradictory duplicate rescue lineage nullification failed: ab={r_b3_ab}, ba={r_b3_ba}"
            )
        cases.append({"case": "b3_r12_gate28a_contradictory_duplicate_rescue_ancestry_nullification_both_orders", "passed": True})

        # 65. R12 M1: Explicit clinical rescue fields strictly narrowed to canonical `rescue_lot_id` / `rescue_lot_ids`;
        #     undocumented `rescue_repeat_lot_id` and `rescue_repeat_lot_ids` fail closed!
        r12_m1_scalar = copy.deepcopy(r12_120)
        r12_m1_scalar[0].update(intercurrent_event="RESCUE_REPEAT_INFUSION", rescue_repeat_lot_id="RA")
        r12_m1_list = copy.deepcopy(r12_120)
        r12_m1_list[0].update(intercurrent_event="RESCUE_REPEAT_INFUSION", rescue_repeat_lot_ids=["RA"])
        r12_m1_canon = copy.deepcopy(r12_120)
        r12_m1_canon[0].update(intercurrent_event="RESCUE_REPEAT_INFUSION", rescue_lot_id="RA")
        cmc_m1 = _derive_reconciling_cmc_lot_ledger_from_recipients(r12_m1_canon, {**r12_mcb_map, "RA": "M12-0"})

        p_m1_sc, _ = build_valid_gate28a_reference_bundle(
            r12_store, r12_m1_scalar, cohort_id="COHORT-R12-M1-REPEAT-SCALAR",
            lot_to_mcb_manifest={**r12_mcb_map, "RA": "M12-0"}, parallel_cmc_lot_ledger=cmc_m1,
        )
        p_m1_ls, _ = build_valid_gate28a_reference_bundle(
            r12_store, r12_m1_list, cohort_id="COHORT-R12-M1-REPEAT-LIST",
            lot_to_mcb_manifest={**r12_mcb_map, "RA": "M12-0"}, parallel_cmc_lot_ledger=cmc_m1,
        )
        p_m1_ok, _ = build_valid_gate28a_reference_bundle(
            r12_store, r12_m1_canon, cohort_id="COHORT-R12-M1-CANON-OK",
            lot_to_mcb_manifest={**r12_mcb_map, "RA": "M12-0"}, parallel_cmc_lot_ledger=cmc_m1,
        )
        r_m1_sc = evaluate_gate28a_h1_promotion(p_m1_sc, trusted_clinical_store=r12_store)
        r_m1_ls = evaluate_gate28a_h1_promotion(p_m1_ls, trusted_clinical_store=r12_store)
        r_m1_ok = evaluate_gate28a_h1_promotion(p_m1_ok, trusted_clinical_store=r12_store)
        if not (
            r_m1_ok["status"] == "PROMOTE_H1_88_TO_90"
            and r_m1_ok["promotion_authorized"] is True
            and r_m1_ok["parallel_cmc_ledger_verified"] is True
            and r_m1_sc["status"] == "HOLD_H1_AT_88PCT"
            and r_m1_sc["promotion_authorized"] is False
            and r_m1_sc["parallel_cmc_ledger_verified"] is False
            and any("CLINICAL_RESCUE_MISSING_EXPLICIT_LOT_ID" in fr for fr in r_m1_sc["failure_reasons"])
            and any("UNRECOGNIZED_CLINICAL_RESCUE_LOT_ALIAS" in fr for fr in r_m1_sc["failure_reasons"])
            and r_m1_ls["status"] == "HOLD_H1_AT_88PCT"
            and r_m1_ls["promotion_authorized"] is False
            and r_m1_ls["parallel_cmc_ledger_verified"] is False
            and any("CLINICAL_RESCUE_MISSING_EXPLICIT_LOT_ID" in fr for fr in r_m1_ls["failure_reasons"])
            and any("UNRECOGNIZED_CLINICAL_RESCUE_LOT_ALIAS" in fr for fr in r_m1_ls["failure_reasons"])
        ):
            raise ValueError(
                f"R12 M1 narrowed rescue fields check failed: ok={r_m1_ok}, sc={r_m1_sc}, ls={r_m1_ls}"
            )
        cases.append({"case": "m1_r12_gate28a_narrowed_explicit_rescue_fields_reject_undocumented_aliases", "passed": True})

        # --- R13 B1 & M1: Final-Closure Self-Tests (Cases 66-68) ---
        r13_store = tmp_dir_p / "r13_gate28a_store.json"

        # 66. R13 B1a: Single-row clinical-vs-CMC rescue identity/lineage contradiction (RA -> M12-0/WR-A vs
        #     CMC RB -> M12-1/WR-B) AND omitted CMC rescue row BOTH route unconditionally through full fail-closed
        #     ancestry nullification identically in forward & reversed recipient order, while matching RA promotes!
        r13_mcb_full = {**r12_mcb_map, "RA": "M12-0", "RB": "M12-1"}
        r13_wcb_full = {"RA": "WR-A", "RB": "WR-B"}
        r13_clin_ra = copy.deepcopy(r12_120)
        r13_clin_ra[0].update(intercurrent_event="RESCUE_REPEAT_INFUSION", rescue_lot_id="RA")
        r13_clin_ra_rev = list(reversed(copy.deepcopy(r13_clin_ra)))

        r13_cmc_ra = _derive_reconciling_cmc_lot_ledger_from_recipients(
            r13_clin_ra, r13_mcb_full, lot_to_wcb_manifest=r13_wcb_full
        )
        r13_cmc_rb = copy.deepcopy(r13_cmc_ra)
        for row_rb in r13_cmc_rb:
            if row_rb.get("lot_type") == "RESCUE_REPEAT_LOT":
                row_rb["lot_id"] = "RB"
                row_rb["mcb_id"] = "M12-1"
                row_rb["wcb_id"] = "WR-B"
        r13_cmc_omit = [row_o for row_o in r13_cmc_ra if row_o.get("lot_type") != "RESCUE_REPEAT_LOT"]

        p_r13_match, _ = build_valid_gate28a_reference_bundle(
            r13_store, r13_clin_ra, cohort_id="COHORT-R13-B1-MATCH-RA",
            lot_to_mcb_manifest=r13_mcb_full, lot_to_wcb_manifest=r13_wcb_full,
            parallel_cmc_lot_ledger=r13_cmc_ra,
        )
        p_r13_sub_fwd, _ = build_valid_gate28a_reference_bundle(
            r13_store, r13_clin_ra, cohort_id="COHORT-R13-B1-SUB-RA-VS-RB",
            lot_to_mcb_manifest=r13_mcb_full, lot_to_wcb_manifest=r13_wcb_full,
            parallel_cmc_lot_ledger=r13_cmc_rb,
        )
        p_r13_sub_rev, _ = build_valid_gate28a_reference_bundle(
            r13_store, r13_clin_ra_rev, cohort_id="COHORT-R13-B1-SUB-RA-VS-RB",
            lot_to_mcb_manifest=r13_mcb_full, lot_to_wcb_manifest=r13_wcb_full,
            parallel_cmc_lot_ledger=r13_cmc_rb,
        )
        p_r13_omit, _ = build_valid_gate28a_reference_bundle(
            r13_store, r13_clin_ra, cohort_id="COHORT-R13-B1-OMIT-CMC-RESC",
            lot_to_mcb_manifest=r13_mcb_full, lot_to_wcb_manifest=r13_wcb_full,
            parallel_cmc_lot_ledger=r13_cmc_omit,
        )
        r_r13_match = evaluate_gate28a_h1_promotion(p_r13_match, trusted_clinical_store=r13_store)
        r_r13_sub_fwd = evaluate_gate28a_h1_promotion(p_r13_sub_fwd, trusted_clinical_store=r13_store)
        r_r13_sub_rev = evaluate_gate28a_h1_promotion(p_r13_sub_rev, trusted_clinical_store=r13_store)
        r_r13_omit = evaluate_gate28a_h1_promotion(p_r13_omit, trusted_clinical_store=r13_store)

        if not (
            r_r13_match["status"] == "PROMOTE_H1_88_TO_90"
            and r_r13_match["promotion_authorized"] is True
            and r_r13_match["parallel_cmc_ledger_verified"] is True
            and r_r13_match["lot_bank_hierarchy_valid"] is True
            and r_r13_match["lot_to_mcb_manifest_verified"] is True
            and r_r13_match["lot_to_wcb_manifest_verified"] is True
            and r_r13_match["icc_sensitivity_report_attached"] is True
            and r_r13_match["deff"] is not None
            and r_r13_sub_fwd == r_r13_sub_rev
            and r_r13_sub_fwd["status"] == "HOLD_H1_AT_88PCT"
            and r_r13_sub_fwd["promotion_authorized"] is False
            and r_r13_sub_fwd["parallel_cmc_ledger_verified"] is False
            and r_r13_sub_fwd["lot_bank_hierarchy_valid"] is False
            and r_r13_sub_fwd["lot_to_mcb_manifest_verified"] is False
            and r_r13_sub_fwd["lot_to_wcb_manifest_verified"] is False
            and r_r13_sub_fwd["deff"] is None
            and r_r13_sub_fwd["n_eff"] is None
            and r_r13_sub_fwd["k_eff"] is None
            and r_r13_sub_fwd["icc_sensitivity_report_attached"] is False
            and r_r13_sub_fwd["icc_sensitivity_report"] is None
            and any("CLINICAL_RESCUE_LOT_ID_MISMATCH_IN_CMC_LEDGER" in fr for fr in r_r13_sub_fwd["failure_reasons"])
            and any("CMC_EXTRA_RESCUE_LOT_OMITTED_FROM_CLINICAL_COHORT" in fr for fr in r_r13_sub_fwd["failure_reasons"])
            and any("CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT" in fr for fr in r_r13_sub_fwd["failure_reasons"])
            and r_r13_omit["status"] == "HOLD_H1_AT_88PCT"
            and r_r13_omit["promotion_authorized"] is False
            and r_r13_omit["parallel_cmc_ledger_verified"] is False
            and r_r13_omit["lot_bank_hierarchy_valid"] is False
            and r_r13_omit["lot_to_mcb_manifest_verified"] is False
            and r_r13_omit["lot_to_wcb_manifest_verified"] is False
            and r_r13_omit["deff"] is None
            and r_r13_omit["n_eff"] is None
            and r_r13_omit["k_eff"] is None
            and r_r13_omit["icc_sensitivity_report_attached"] is False
            and r_r13_omit["icc_sensitivity_report"] is None
            and any("CLINICAL_RESCUE_OMITTED_FROM_CMC_LEDGER" in fr for fr in r_r13_omit["failure_reasons"])
            and any("CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT" in fr for fr in r_r13_omit["failure_reasons"])
        ):
            raise ValueError(
                f"R13 B1a single-row rescue substitution/omission nullification failed: "
                f"match={r_r13_match}, sub_fwd={r_r13_sub_fwd}, sub_rev={r_r13_sub_rev}, omit={r_r13_omit}"
            )
        # R17 M1: Same rescue ID ('RA') with mutated bank (MCB), WCB, or linked primary lot MUST retain
        # lineage-specific diagnostics AND emit the CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT umbrella code
        # with full ancestry nullification across all 4 (clinical x CMC) row orderings!
        r17_m1_fields = (
            "status", "promotion_authorized", "external_clinical_store_verified",
            "lot_bank_hierarchy_valid", "lot_to_mcb_manifest_verified", "lot_to_wcb_manifest_verified",
            "parallel_cmc_ledger_verified", "icc_sensitivity_report_attached", "icc_sensitivity_report",
            "deff", "n_eff", "k_eff", "failure_reasons",
        )
        for r17_m1_tag, r17_m1_key, r17_m1_val in (
            ("MCB", "mcb_id", "M12-1"),
            ("WCB", "wcb_id", "WR-B"),
            ("PRIM-LOT", "rescued_primary_lot_id", "L12-01"),
        ):
            cmc_m1_same = copy.deepcopy(r13_cmc_ra)
            for row_m1 in cmc_m1_same:
                if row_m1.get("lot_type") == "RESCUE_REPEAT_LOT":
                    row_m1[r17_m1_key] = r17_m1_val
            m1_same_views = []
            for rev_rec in (False, True):
                for rev_cmc in (False, True):
                    p_m1_s, _ = build_valid_gate28a_reference_bundle(
                        r13_store,
                        list(reversed(r13_clin_ra)) if rev_rec else r13_clin_ra,
                        cohort_id=f"COHORT-R17-M1-SAMEID-{r17_m1_tag}-{int(rev_rec)}-{int(rev_cmc)}",
                        lot_to_mcb_manifest=r13_mcb_full,
                        lot_to_wcb_manifest=r13_wcb_full,
                        parallel_cmc_lot_ledger=list(reversed(cmc_m1_same)) if rev_cmc else cmc_m1_same,
                    )
                    res_m1_s = evaluate_gate28a_h1_promotion(p_m1_s, trusted_clinical_store=r13_store)
                    m1_same_views.append({fk: res_m1_s.get(fk) for fk in r17_m1_fields})
            if any(rv != m1_same_views[0] for rv in m1_same_views[1:]):
                raise ValueError(f"R17 M1 same-rescue-ID {r17_m1_tag} order dependence: {m1_same_views}")
            vm1 = m1_same_views[0]
            if not (
                vm1["status"] == "HOLD_H1_AT_88PCT"
                and vm1["promotion_authorized"] is False
                and vm1["external_clinical_store_verified"] is False
                and vm1["lot_bank_hierarchy_valid"] is False
                and vm1["lot_to_mcb_manifest_verified"] is False
                and vm1["lot_to_wcb_manifest_verified"] is False
                and vm1["parallel_cmc_ledger_verified"] is False
                and vm1["icc_sensitivity_report_attached"] is False
                and vm1["icc_sensitivity_report"] is None
                and vm1["deff"] is None
                and vm1["n_eff"] is None
                and vm1["k_eff"] is None
                and any("CMC_ROW_ANCESTRY_CONFLICTS_WITH_VERIFIED_MANIFEST" in fr for fr in vm1["failure_reasons"])
                and any("CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT" in fr for fr in vm1["failure_reasons"])
            ):
                raise ValueError(f"R17 M1 same-rescue-ID {r17_m1_tag} umbrella conflict failed: {vm1}")
        cases.append({"case": "b1a_r13_gate28a_single_row_rescue_substitution_and_omission_full_nullification", "passed": True})

        # 67. R13 B1b: Compound RA-vs-RB single-row substitution PLUS unrelated malformed split-lot planned_doses_n
        #     MUST NOT mask rescue-identity diagnostics OR bypass full fail-closed ancestry nullification (both row orders)!
        r13_cmc_compound_fwd = copy.deepcopy(r13_cmc_rb)
        for row_sp in r13_cmc_compound_fwd:
            if row_sp.get("lot_id") == "L12-01":
                row_sp["planned_doses_n"] = 1
        r13_cmc_compound_rev = list(reversed(copy.deepcopy(r13_cmc_compound_fwd)))

        p_r13_comp_fwd, _ = build_valid_gate28a_reference_bundle(
            r13_store, r13_clin_ra, cohort_id="COHORT-R13-B1-COMPOUND-FWD",
            lot_to_mcb_manifest=r13_mcb_full, lot_to_wcb_manifest=r13_wcb_full,
            parallel_cmc_lot_ledger=r13_cmc_compound_fwd,
        )
        p_r13_comp_rev, _ = build_valid_gate28a_reference_bundle(
            r13_store, r13_clin_ra_rev, cohort_id="COHORT-R13-B1-COMPOUND-REV",
            lot_to_mcb_manifest=r13_mcb_full, lot_to_wcb_manifest=r13_wcb_full,
            parallel_cmc_lot_ledger=r13_cmc_compound_rev,
        )
        r_r13_comp_fwd = evaluate_gate28a_h1_promotion(p_r13_comp_fwd, trusted_clinical_store=r13_store)
        r_r13_comp_rev = evaluate_gate28a_h1_promotion(p_r13_comp_rev, trusted_clinical_store=r13_store)

        if not (
            r_r13_comp_fwd["status"] == "HOLD_H1_AT_88PCT"
            and r_r13_comp_fwd["promotion_authorized"] is False
            and r_r13_comp_fwd["parallel_cmc_ledger_verified"] is False
            and r_r13_comp_fwd["lot_bank_hierarchy_valid"] is False
            and r_r13_comp_fwd["lot_to_mcb_manifest_verified"] is False
            and r_r13_comp_fwd["lot_to_wcb_manifest_verified"] is False
            and r_r13_comp_fwd["deff"] is None
            and r_r13_comp_fwd["n_eff"] is None
            and r_r13_comp_fwd["k_eff"] is None
            and r_r13_comp_fwd["icc_sensitivity_report_attached"] is False
            and r_r13_comp_fwd["icc_sensitivity_report"] is None
            and any("CLINICAL_RESCUE_LOT_ID_MISMATCH_IN_CMC_LEDGER" in fr for fr in r_r13_comp_fwd["failure_reasons"])
            and any("CMC_EXTRA_RESCUE_LOT_OMITTED_FROM_CLINICAL_COHORT" in fr for fr in r_r13_comp_fwd["failure_reasons"])
            and any("CLINICAL_CMC_RESCUE_IDENTITY_CONFLICT" in fr for fr in r_r13_comp_fwd["failure_reasons"])
            and any("failed evaluate_cmc_attempted_lot_readiness" in fr for fr in r_r13_comp_fwd["failure_reasons"])
            and r_r13_comp_rev["status"] == r_r13_comp_fwd["status"]
            and r_r13_comp_rev["promotion_authorized"] is False
            and r_r13_comp_rev["parallel_cmc_ledger_verified"] is False
            and r_r13_comp_rev["lot_bank_hierarchy_valid"] is False
            and r_r13_comp_rev["lot_to_mcb_manifest_verified"] is False
            and r_r13_comp_rev["lot_to_wcb_manifest_verified"] is False
            and r_r13_comp_rev["deff"] is None
            and r_r13_comp_rev["n_eff"] is None
            and r_r13_comp_rev["k_eff"] is None
            and r_r13_comp_rev["icc_sensitivity_report_attached"] is False
            and r_r13_comp_rev["failure_reasons"] == r_r13_comp_fwd["failure_reasons"]
        ):
            raise ValueError(
                f"R13 B1b compound rescue substitution + invalid split-lot check failed: "
                f"fwd={r_r13_comp_fwd}, rev={r_r13_comp_rev}"
            )
        # Also verify missing rescued_primary_lot_id AND contradictory rescue recipient/outcome bindings
        # (both alone AND paired with unrelated malformed split-lot L12-01 planned_doses_n=1, forward & reversed)!
        for variant_lbl, mutate_kind in (
            ("MISSING-PRIM", "missing_prim"),
            ("MISSING-PRIM-SHAPE", "missing_prim_shape"),
            ("CONF-RECIP-BIND", "conf_recip"),
            ("CONF-RECIP-BIND-SHAPE", "conf_recip_shape"),
            ("CONF-RECIP-RECS-SHAPE", "conf_recip_recs_shape"),
        ):
            cmc_var_fwd = copy.deepcopy(r13_cmc_ra)
            resc_var = next(row_v for row_v in cmc_var_fwd if row_v.get("lot_type") == "RESCUE_REPEAT_LOT")
            if mutate_kind.startswith("missing_prim"):
                resc_var.pop("rescued_primary_lot_id", None)
            elif mutate_kind.startswith("conf_recip_recs"):
                resc_var.pop("recipient_outcomes", None)
                resc_var["recipient_ids"] = ["R12-00-1"]
                resc_var["recipient_records"] = [{"recipient_id": "R12-00-1", "c2b_responder": 1}]
            elif mutate_kind.startswith("conf_recip"):
                resc_var["recipient_ids"] = ["R12-00-1"]
                resc_var["recipient_outcomes"] = {"R12-00-1": resc_var["recipient_outcomes"]["R12-00-0"]}
            if mutate_kind.endswith("shape"):
                for row_s in cmc_var_fwd:
                    if row_s.get("lot_id") == "L12-01":
                        row_s["planned_doses_n"] = 1
            cmc_var_rev = list(reversed(copy.deepcopy(cmc_var_fwd)))
            p_vf, _ = build_valid_gate28a_reference_bundle(
                r13_store, r13_clin_ra, cohort_id=f"COHORT-R13-B1-{variant_lbl}-FWD",
                lot_to_mcb_manifest=r13_mcb_full, lot_to_wcb_manifest=r13_wcb_full,
                parallel_cmc_lot_ledger=cmc_var_fwd,
            )
            p_vr, _ = build_valid_gate28a_reference_bundle(
                r13_store, r13_clin_ra_rev, cohort_id=f"COHORT-R13-B1-{variant_lbl}-REV",
                lot_to_mcb_manifest=r13_mcb_full, lot_to_wcb_manifest=r13_wcb_full,
                parallel_cmc_lot_ledger=cmc_var_rev,
            )
            r_vf = evaluate_gate28a_h1_promotion(p_vf, trusted_clinical_store=r13_store)
            r_vr = evaluate_gate28a_h1_promotion(p_vr, trusted_clinical_store=r13_store)
            expected_tok = (
                "CMC_RESCUE_LINKAGE_MISSING_OR_INVALID"
                if mutate_kind.startswith("missing_prim")
                else "CMC_RESCUE_RECIPIENT_BINDING_CONFLICT"
            )
            if not (
                r_vf["status"] == "HOLD_H1_AT_88PCT"
                and r_vf["promotion_authorized"] is False
                and r_vf["external_clinical_store_verified"] is False
                and r_vf["parallel_cmc_ledger_verified"] is False
                and r_vf["lot_bank_hierarchy_valid"] is False
                and r_vf["lot_to_mcb_manifest_verified"] is False
                and r_vf["lot_to_wcb_manifest_verified"] is False
                and r_vf["icc_sensitivity_report_attached"] is False
                and r_vf["icc_sensitivity_report"] is None
                and r_vf["deff"] is None
                and r_vf["n_eff"] is None
                and r_vf["k_eff"] is None
                and any(expected_tok in fr for fr in r_vf["failure_reasons"])
                and r_vr["status"] == r_vf["status"]
                and r_vr["promotion_authorized"] is False
                and r_vr["external_clinical_store_verified"] is False
                and r_vr["parallel_cmc_ledger_verified"] is False
                and r_vr["lot_bank_hierarchy_valid"] is False
                and r_vr["lot_to_mcb_manifest_verified"] is False
                and r_vr["lot_to_wcb_manifest_verified"] is False
                and r_vr["icc_sensitivity_report_attached"] is False
                and r_vr["icc_sensitivity_report"] is None
                and r_vr["deff"] is None
                and r_vr["n_eff"] is None
                and r_vr["k_eff"] is None
                and r_vr["failure_reasons"] == r_vf["failure_reasons"]
            ):
                raise ValueError(
                    f"R13 B1b pre-validation rescue linkage/binding check failed for {variant_lbl}: "
                    f"fwd={r_vf}, rev={r_vr}"
                )
        # Also verify Pass-0 clinical primary-lot claims vs raw CMC RELEASED_UNINFUSED / FAILED_RELEASE
        # dispositions BEFORE shape validation (alone AND combined with unrelated L29 planned_doses_n=0,
        # identically in forward & reverse row orders, while keeping matching 30-recipient control promoting)!
        r15_recips_30 = [
            {
                "recipient_id": f"P{idx_p:02d}",
                "lot_id": f"L{idx_p:02d}",
                "mcb_id": f"M{idx_p // 3:02d}",
                "wcb_id": f"W{idx_p // 2:02d}-{idx_p // 3:02d}",
                "followup_months": 12,
                "met_c2b_criteria": True,
                "intercurrent_event": "NONE",
            }
            for idx_p in range(30)
        ]
        r15_mcb_30 = {row_p["lot_id"]: row_p["mcb_id"] for row_p in r15_recips_30}
        r15_wcb_30 = {row_p["lot_id"]: row_p["wcb_id"] for row_p in r15_recips_30}
        r15_base_cmc = _derive_reconciling_cmc_lot_ledger_from_recipients(
            r15_recips_30, r15_mcb_30, lot_to_wcb_manifest=r15_wcb_30
        )
        r15_disp_fields = (
            "status", "promotion_authorized", "external_clinical_store_verified",
            "lot_bank_hierarchy_valid", "lot_to_mcb_manifest_verified", "lot_to_wcb_manifest_verified",
            "parallel_cmc_ledger_verified", "icc_sensitivity_report_attached", "icc_sensitivity_report",
            "deff", "n_eff", "k_eff", "clopper_pearson_95_ci_scope", "failure_reasons",
        )
        for disp_var, new_disp, add_shape in (
            ("MATCHING", None, False),
            ("UNINFUSED", "RELEASED_UNINFUSED", False),
            ("FAILED", "FAILED_RELEASE", False),
            ("UNINFUSED-SHAPE", "RELEASED_UNINFUSED", True),
            ("FAILED-SHAPE", "FAILED_RELEASE", True),
        ):
            cmc_dv = copy.deepcopy(r15_base_cmc)
            if new_disp is not None:
                cmc_dv[0].update(
                    disposition=new_disp,
                    infused_doses_n=0,
                    recipient_ids=[],
                    recipient_outcomes={},
                    c2b_responder_doses_n=0,
                )
            if add_shape:
                cmc_dv[-1]["planned_doses_n"] = 0
            r15_views = []
            for is_rev in (False, True):
                p_dv, _ = build_valid_gate28a_reference_bundle(
                    r13_store,
                    list(reversed(r15_recips_30)) if is_rev else r15_recips_30,
                    cohort_id=f"COHORT-R15-DISP-{disp_var}-{int(is_rev)}",
                    lot_to_mcb_manifest=r15_mcb_30,
                    lot_to_wcb_manifest=r15_wcb_30,
                    parallel_cmc_lot_ledger=list(reversed(cmc_dv)) if is_rev else cmc_dv,
                )
                r_dv = evaluate_gate28a_h1_promotion(p_dv, trusted_clinical_store=r13_store)
                r15_views.append({fk: r_dv.get(fk) for fk in r15_disp_fields})
            if r15_views[0] != r15_views[1]:
                raise ValueError(f"R15 primary-lot disposition order dependence for {disp_var}: {r15_views}")
            v0 = r15_views[0]
            if new_disp is None:
                if not (
                    v0["status"] == "PROMOTE_H1_88_TO_90"
                    and v0["promotion_authorized"] is True
                    and v0["lot_bank_hierarchy_valid"] is True
                    and v0["parallel_cmc_ledger_verified"] is True
                    and v0["icc_sensitivity_report_attached"] is True
                    and abs(float(v0["deff"]) - 1.04) < 1e-6
                    and v0["clopper_pearson_95_ci_scope"] == "NOMINAL_IID_UNADJUSTED_RECIPIENT_COUNTS_ONLY_NOT_CLUSTER_ADJUSTED"
                    and v0["failure_reasons"] == []
                ):
                    raise ValueError(f"R15 matching positive control failed: {v0}")
            else:
                if not (
                    v0["status"] == "HOLD_H1_AT_88PCT"
                    and v0["promotion_authorized"] is False
                    and v0["external_clinical_store_verified"] is False
                    and v0["lot_bank_hierarchy_valid"] is False
                    and v0["lot_to_mcb_manifest_verified"] is False
                    and v0["lot_to_wcb_manifest_verified"] is False
                    and v0["parallel_cmc_ledger_verified"] is False
                    and v0["icc_sensitivity_report_attached"] is False
                    and v0["icc_sensitivity_report"] is None
                    and v0["deff"] is None
                    and v0["n_eff"] is None
                    and v0["k_eff"] is None
                    and any(
                        "CLINICAL_PRIMARY_LOT_CMC_DISPOSITION_CONFLICT" in fr and new_disp in fr
                        for fr in v0["failure_reasons"]
                    )
                    and ((not add_shape) or any("Lot 'L29'" in fr for fr in v0["failure_reasons"]))
                ):
                    raise ValueError(f"R15 primary-lot disposition nullification failed for {disp_var}: {v0}")
        # R16: Contradictory duplicate recipient ancestry (P00/L00 missing follow-up + P00/L01 valid L01 bank IDs)
        # MUST NEVER suppress raw CMC primary-lot disposition audit (single bad lot OR both bad lots + L29 shape error),
        # identically across BOTH recipient orders AND BOTH CMC row orders!
        r16_dup_recips = copy.deepcopy(r15_recips_30)
        r16_dup_recips[0]["followup_months"] = None
        r16_dup_recips.append({
            "recipient_id": "P00",
            "lot_id": "L01",
            "mcb_id": r15_mcb_30["L01"],
            "wcb_id": r15_wcb_30["L01"],
            "followup_months": 12,
            "met_c2b_criteria": True,
            "intercurrent_event": "NONE",
        })
        for r16_lbl, l00_disp, l01_disp in (
            ("DUP-L00-FAILED", "FAILED_RELEASE", None),
            ("DUP-L00-UNINFUSED", "RELEASED_UNINFUSED", None),
            ("DUP-BOTH-FAILED-UNINFUSED", "FAILED_RELEASE", "RELEASED_UNINFUSED"),
            ("DUP-L01-FAILED", None, "FAILED_RELEASE"),
        ):
            cmc_r16 = copy.deepcopy(r15_base_cmc)
            if l00_disp is not None:
                cmc_r16[0].update(
                    disposition=l00_disp,
                    infused_doses_n=0,
                    recipient_ids=[],
                    recipient_outcomes={},
                    c2b_responder_doses_n=0,
                )
            if l01_disp is not None:
                cmc_r16[1].update(
                    disposition=l01_disp,
                    infused_doses_n=0,
                    recipient_ids=[],
                    recipient_outcomes={},
                    c2b_responder_doses_n=0,
                )
            cmc_r16[-1]["planned_doses_n"] = 0
            r16_views = []
            for rev_rec in (False, True):
                for rev_cmc in (False, True):
                    p_r16, _ = build_valid_gate28a_reference_bundle(
                        r13_store,
                        list(reversed(r16_dup_recips)) if rev_rec else r16_dup_recips,
                        cohort_id=f"COHORT-R16-{r16_lbl}-{int(rev_rec)}-{int(rev_cmc)}",
                        lot_to_mcb_manifest=r15_mcb_30,
                        lot_to_wcb_manifest=r15_wcb_30,
                        parallel_cmc_lot_ledger=list(reversed(cmc_r16)) if rev_cmc else cmc_r16,
                    )
                    r_r16 = evaluate_gate28a_h1_promotion(p_r16, trusted_clinical_store=r13_store)
                    r16_views.append({fk: r_r16.get(fk) for fk in r15_disp_fields})
            if any(rv != r16_views[0] for rv in r16_views[1:]):
                raise ValueError(f"R16 duplicate-recipient + CMC disposition order dependence for {r16_lbl}: {r16_views}")
            rv0 = r16_views[0]
            if not (
                rv0["status"] == "HOLD_H1_AT_88PCT"
                and rv0["promotion_authorized"] is False
                and rv0["external_clinical_store_verified"] is False
                and rv0["lot_bank_hierarchy_valid"] is False
                and rv0["lot_to_mcb_manifest_verified"] is False
                and rv0["lot_to_wcb_manifest_verified"] is False
                and rv0["parallel_cmc_ledger_verified"] is False
                and rv0["icc_sensitivity_report_attached"] is False
                and rv0["icc_sensitivity_report"] is None
                and rv0["deff"] is None
                and rv0["n_eff"] is None
                and rv0["k_eff"] is None
                and any("CONFLICTING_DUPLICATE_RECIPIENT_ANCESTRY" in fr for fr in rv0["failure_reasons"])
                and any("Lot 'L29'" in fr for fr in rv0["failure_reasons"])
                and (
                    l00_disp is None
                    or any(
                        "CLINICAL_PRIMARY_LOT_CMC_DISPOSITION_CONFLICT" in fr
                        and "'P00'" in fr and "'L00'" in fr and l00_disp in fr
                        for fr in rv0["failure_reasons"]
                    )
                )
                and (
                    l01_disp is None
                    or any(
                        "CLINICAL_PRIMARY_LOT_CMC_DISPOSITION_CONFLICT" in fr
                        and "'P00'" in fr and "'L01'" in fr and l01_disp in fr
                        for fr in rv0["failure_reasons"]
                    )
                )
            ):
                raise ValueError(f"R16 duplicate-recipient + CMC disposition audit failed for {r16_lbl}: {rv0}")
        cases.append({"case": "b1b_r13_gate28a_compound_rescue_substitution_plus_invalid_split_lot_no_masking", "passed": True})

        # 68. R13 M1: Undocumented *rescue*lot* alias keys rejected BY KEY PRESENCE even when value is
        #     None/null/""/[] or on a qualifying recipient with intercurrent_event="NONE"!
        r13_m1_results = []
        for idx_m1, (bad_k, bad_v) in enumerate((
            ("rescue_repeat_lot_id", None),
            ("rescue_repeat_lot_ids", None),
            ("rescue_repeat_lot_id", ""),
            ("rescue_repeat_lot_ids", []),
            ("alt_rescue_lot_ref", None),
        )):
            rec_m1_null = copy.deepcopy(r12_120)
            rec_m1_null[0][bad_k] = bad_v
            p_m1_null, _ = build_valid_gate28a_reference_bundle(
                r13_store, rec_m1_null, cohort_id=f"COHORT-R13-M1-PRESENCE-{idx_m1}",
            )
            res_m1_null = evaluate_gate28a_h1_promotion(p_m1_null, trusted_clinical_store=r13_store)
            r13_m1_results.append((bad_k, bad_v, res_m1_null))
            if not (
                res_m1_null["status"] == "HOLD_H1_AT_88PCT"
                and res_m1_null["promotion_authorized"] is False
                and res_m1_null["parallel_cmc_ledger_verified"] is False
                and any("UNRECOGNIZED_CLINICAL_RESCUE_LOT_ALIAS" in fr for fr in res_m1_null["failure_reasons"])
            ):
                raise ValueError(
                    f"R13 M1 by-presence undocumented rescue key check failed for {bad_k}={bad_v!r}: {res_m1_null}"
                )
        cases.append({"case": "m1_r13_gate28a_null_undocumented_rescue_alias_rejected_by_presence", "passed": True})

        # 69. R17 B1: Paired initial-lot raw CMC outcome (0 vs 1 with updated c2b_responder_doses_n) on a matched
        #     120-recipient cohort with one declared & matched rescue across ALL 4 (recipient x CMC) row orders:
        #       - CMC=0 vs clinical=0 -> PROMOTE_H1_88_TO_90, parallel_cmc_ledger_verified=True, 119/120, zero failures
        #       - CMC=1 vs clinical=0 -> HOLD_H1_AT_88PCT, parallel_cmc_ledger_verified=False, CMC_OUTCOME_MISMATCH!
        r17_rid0 = r13_clin_ra[0]["recipient_id"]
        r17_lot0 = r13_clin_ra[0]["lot_id"]
        r17_cmc_raw0 = copy.deepcopy(r13_cmc_ra)
        r17_cmc_raw1 = copy.deepcopy(r13_cmc_ra)
        for row_r17 in r17_cmc_raw1:
            if row_r17.get("lot_id") == r17_lot0:
                row_r17["recipient_outcomes"][r17_rid0] = 1
                row_r17["c2b_responder_doses_n"] = sum(row_r17["recipient_outcomes"].values())
        r17_cmc_raw1_recs = copy.deepcopy(r17_cmc_raw1)
        for row_r17r in r17_cmc_raw1_recs:
            if row_r17r.get("lot_id") == r17_lot0:
                out_map = row_r17r.pop("recipient_outcomes")
                row_r17r["recipient_records"] = [
                    {"recipient_id": k_r, "c2b_responder": bool(v_r)}
                    for k_r, v_r in sorted(out_map.items())
                ]
        r17_compare_fields = (
            "status", "promotion_authorized", "external_clinical_store_verified",
            "lot_bank_hierarchy_valid", "lot_to_mcb_manifest_verified", "lot_to_wcb_manifest_verified",
            "parallel_cmc_ledger_verified", "k", "n", "deff", "n_eff", "k_eff", "failure_reasons",
        )
        for r17_tag, r17_cmc_rows, expect_promote in (
            ("RAW0-MATCH", r17_cmc_raw0, True),
            ("RAW1-MISMATCH", r17_cmc_raw1, False),
            ("RAW1-RECS-MISMATCH", r17_cmc_raw1_recs, False),
        ):
            r17_views = []
            for rev_rec in (False, True):
                for rev_cmc in (False, True):
                    p_r17, _ = build_valid_gate28a_reference_bundle(
                        r13_store,
                        list(reversed(r13_clin_ra)) if rev_rec else r13_clin_ra,
                        cohort_id=f"COHORT-R17-B1-{r17_tag}-{int(rev_rec)}-{int(rev_cmc)}",
                        lot_to_mcb_manifest=r13_mcb_full,
                        lot_to_wcb_manifest=r13_wcb_full,
                        parallel_cmc_lot_ledger=list(reversed(r17_cmc_rows)) if rev_cmc else r17_cmc_rows,
                    )
                    res_r17 = evaluate_gate28a_h1_promotion(p_r17, trusted_clinical_store=r13_store)
                    r17_views.append({fk: res_r17.get(fk) for fk in r17_compare_fields})
            if any(rv != r17_views[0] for rv in r17_views[1:]):
                raise ValueError(f"R17 B1 rescue raw CMC outcome order dependence for {r17_tag}: {r17_views}")
            v17 = r17_views[0]
            if expect_promote:
                if not (
                    v17["status"] == "PROMOTE_H1_88_TO_90"
                    and v17["promotion_authorized"] is True
                    and v17["external_clinical_store_verified"] is True
                    and v17["parallel_cmc_ledger_verified"] is True
                    and v17["k"] == 119
                    and v17["n"] == 120
                    and v17["failure_reasons"] == []
                ):
                    raise ValueError(f"R17 B1 rescue CMC=0 control failed: {v17}")
            else:
                if not (
                    v17["status"] == "HOLD_H1_AT_88PCT"
                    and v17["promotion_authorized"] is False
                    and v17["external_clinical_store_verified"] is False
                    and v17["parallel_cmc_ledger_verified"] is False
                    and v17["k"] == 119
                    and v17["n"] == 120
                    and any(
                        "CMC_OUTCOME_MISMATCH" in fr
                        and repr(r17_rid0) in fr
                        and "clinical=0 != cmc=1" in fr
                        for fr in v17["failure_reasons"]
                    )
                ):
                    raise ValueError(f"R17 B1 rescue raw CMC=1 mismatch failed to HOLD ({r17_tag}): {v17}")
        cases.append({"case": "b1_r17_gate28a_raw_cmc_rescue_primary_outcome_reconciliation_all_4_orders", "passed": True})

        # 70. R18 B1: Contradictory primary recipient bindings on CMC lot L01 (4 recipients in recipient_outcomes
        #     vs 3 in recipient_records, or 4 in recipient_outcomes vs 3 in recipient_ids) MUST nullify ALL ancestry,
        #     manifest, ICC, and cluster fields fail-closed across all 4 (clinical x CMC) row orderings — BOTH alone
        #     AND when paired with an earlier malformed split-lot count on L00 (planned_doses_n=1) — while a consistent
        #     3-recipient control on L01 promotes cleanly!
        r18_recips_4 = [
            {
                "recipient_id": f"R18-{lot_i:02d}-{rep_i}",
                "lot_id": f"L{lot_i:02d}",
                "mcb_id": f"M{lot_i // 3:02d}",
                "wcb_id": f"W{lot_i // 2:02d}-M{lot_i // 3:02d}",
                "followup_months": 12,
                "met_c2b_criteria": True,
                "intercurrent_event": "NONE",
            }
            for lot_i in range(30)
            for rep_i in range(4)
        ]
        r18_mcb = {row_x["lot_id"]: row_x["mcb_id"] for row_x in r18_recips_4}
        r18_wcb = {row_x["lot_id"]: row_x["wcb_id"] for row_x in r18_recips_4}
        r18_base_cmc_4 = _derive_reconciling_cmc_lot_ledger_from_recipients(
            r18_recips_4, r18_mcb, lot_to_wcb_manifest=r18_wcb
        )

        # (a) 4 recipients in recipient_outcomes vs 3 in recipient_records on L01
        r18_cmc_4v3_recs = copy.deepcopy(r18_base_cmc_4)
        for row_18 in r18_cmc_4v3_recs:
            if row_18.get("lot_id") == "L01":
                row_18["recipient_records"] = [
                    {"recipient_id": f"R18-01-{rep_i}", "c2b_responder": True}
                    for rep_i in range(3)
                ]

        # (b) Same 4-vs-3 contradiction on L01 PLUS earlier malformed split-lot count on L00 (planned_doses_n=1)
        r18_cmc_4v3_recs_shape = copy.deepcopy(r18_cmc_4v3_recs)
        for row_18 in r18_cmc_4v3_recs_shape:
            if row_18.get("lot_id") == "L00":
                row_18["planned_doses_n"] = 1

        # (b2) 4 recipients in recipient_outcomes vs 3 in recipient_ids on L01 + earlier malformed split-lot on L00
        r18_cmc_4v3_rids_shape = copy.deepcopy(r18_base_cmc_4)
        for row_18 in r18_cmc_4v3_rids_shape:
            if row_18.get("lot_id") == "L00":
                row_18["planned_doses_n"] = 1
            elif row_18.get("lot_id") == "L01":
                row_18["recipient_ids"] = [f"R18-01-{rep_i}" for rep_i in range(3)]

        # (c) Consistent 3-recipient control on L01 (all three binding fields present and exactly matching)
        r18_recips_ctrl3 = [row_x for row_x in r18_recips_4 if row_x["recipient_id"] != "R18-01-3"]
        r18_cmc_ctrl3 = _derive_reconciling_cmc_lot_ledger_from_recipients(
            r18_recips_ctrl3, r18_mcb, lot_to_wcb_manifest=r18_wcb
        )
        for row_18 in r18_cmc_ctrl3:
            if row_18.get("lot_id") == "L01":
                row_18["planned_doses_n"] = 4
                row_18["recipient_records"] = [
                    {"recipient_id": f"R18-01-{rep_i}", "c2b_responder": True}
                    for rep_i in range(3)
                ]

        r18_compare_fields = (
            "status", "promotion_authorized", "external_clinical_store_verified",
            "lot_bank_hierarchy_valid", "lot_to_mcb_manifest_verified", "lot_to_wcb_manifest_verified",
            "parallel_cmc_ledger_verified", "icc_sensitivity_report_attached", "icc_sensitivity_report",
            "k", "n", "deff", "n_eff", "k_eff", "failure_reasons",
        )
        for r18_tag, r18_clin_rows, r18_cmc_rows, expect_promote, expect_shape_l00 in (
            ("4V3-RECS", r18_recips_4, r18_cmc_4v3_recs, False, False),
            ("4V3-RECS-SHAPE", r18_recips_4, r18_cmc_4v3_recs_shape, False, True),
            ("4V3-RIDS-SHAPE", r18_recips_4, r18_cmc_4v3_rids_shape, False, True),
            ("CTRL-3-MATCH", r18_recips_ctrl3, r18_cmc_ctrl3, True, False),
        ):
            r18_views = []
            for rev_rec in (False, True):
                for rev_cmc in (False, True):
                    p_r18, _ = build_valid_gate28a_reference_bundle(
                        r13_store,
                        list(reversed(r18_clin_rows)) if rev_rec else r18_clin_rows,
                        cohort_id=f"COHORT-R18-B1-{r18_tag}-{int(rev_rec)}-{int(rev_cmc)}",
                        lot_to_mcb_manifest=r18_mcb,
                        lot_to_wcb_manifest=r18_wcb,
                        parallel_cmc_lot_ledger=list(reversed(r18_cmc_rows)) if rev_cmc else r18_cmc_rows,
                    )
                    res_r18 = evaluate_gate28a_h1_promotion(p_r18, trusted_clinical_store=r13_store)
                    r18_views.append({fk: res_r18.get(fk) for fk in r18_compare_fields})
            if any(rv != r18_views[0] for rv in r18_views[1:]):
                raise ValueError(f"R18 B1 primary recipient binding order dependence for {r18_tag}: {r18_views}")
            v18 = r18_views[0]
            if expect_promote:
                if not (
                    v18["status"] == "PROMOTE_H1_88_TO_90"
                    and v18["promotion_authorized"] is True
                    and v18["external_clinical_store_verified"] is True
                    and v18["lot_bank_hierarchy_valid"] is True
                    and v18["lot_to_mcb_manifest_verified"] is True
                    and v18["lot_to_wcb_manifest_verified"] is True
                    and v18["parallel_cmc_ledger_verified"] is True
                    and v18["icc_sensitivity_report_attached"] is True
                    and v18["icc_sensitivity_report"] is not None
                    and v18["k"] == 119
                    and v18["n"] == 119
                    and v18["deff"] is not None
                    and v18["n_eff"] is not None
                    and v18["k_eff"] is not None
                    and v18["failure_reasons"] == []
                ):
                    raise ValueError(f"R18 B1 consistent 3-recipient control failed: {v18}")
            else:
                if not (
                    v18["status"] == "HOLD_H1_AT_88PCT"
                    and v18["promotion_authorized"] is False
                    and v18["external_clinical_store_verified"] is False
                    and v18["lot_bank_hierarchy_valid"] is False
                    and v18["lot_to_mcb_manifest_verified"] is False
                    and v18["lot_to_wcb_manifest_verified"] is False
                    and v18["parallel_cmc_ledger_verified"] is False
                    and v18["icc_sensitivity_report_attached"] is False
                    and v18["icc_sensitivity_report"] is None
                    and v18["deff"] is None
                    and v18["n_eff"] is None
                    and v18["k_eff"] is None
                    and any("CMC_PRIMARY_RECIPIENT_BINDING_CONFLICT" in fr and "'L01'" in fr for fr in v18["failure_reasons"])
                    and (
                        (not expect_shape_l00)
                        or any("Lot 'L00'" in fr or "SPLIT_LOT 'L00'" in fr for fr in v18["failure_reasons"])
                    )
                ):
                    raise ValueError(f"R18 B1 contradictory primary recipient binding nullification failed ({r18_tag}): {v18}")
        cases.append({"case": "b1_r18_gate28a_contradictory_primary_recipient_bindings_full_nullification_all_4_orders", "passed": True})

    return {"total_cases": len(cases), "all_passed": True, "cases": cases}


# =============================================================================
# PART B — MODE-B CONSTRUCT ASSEMBLY & FULL 4-POINT PROTEIN GATE (P1-P4)
# =============================================================================
def load_swissprot() -> tuple[dict[str, str], dict[int, set[str]], str]:
    gz_sha = sha256_file(SWISSPROT_GZ)
    if not (gz_sha == PINNED_SWISSPROT_SHA):
        raise ValueError(f"Swiss-Prot SHA mismatch: {gz_sha}")
    prots: dict[str, str] = {}
    cid, buf = None, []
    with gzip.open(SWISSPROT_GZ, "rt", encoding="utf-8") as fh:
        for ln in fh:
            ln = ln.strip()
            if not ln:
                continue
            if ln.startswith(">"):
                if cid is not None:
                    prots[cid] = "".join(buf)
                parts = ln[1:].split()[0].split("|")
                cid = parts[1] if len(parts) >= 3 else ln[1:].split()[0]
                buf = []
            else:
                buf.append(ln)
        if cid is not None:
            prots[cid] = "".join(buf)
    ksets = {k: set() for k in (8, 9, 10, 11, 15)}
    for s in prots.values():
        n = len(s)
        for k in (8, 9, 10, 11, 15):
            sk = ksets[k]
            for i in range(n - k + 1):
                sk.add(s[i : i + k])
    return prots, ksets, gz_sha


def find_ir_ge(seq: str, k: int = 16) -> list[tuple[int, int, str]]:
    s = seq.upper()
    rc_map = str.maketrans("ACGT", "TGCA")
    n = len(s)
    idx: dict[str, list[int]] = {}
    hits: list[tuple[int, int, str]] = []
    for i in range(n - k + 1):
        sub = s[i : i + k]
        rc = sub.translate(rc_map)[::-1]
        if rc in idx:
            for p in idx[rc]:
                if i - p >= k:
                    hits.append((p, i, sub))
                    if len(hits) >= 20:
                        return hits
        idx.setdefault(sub, []).append(i)
    return hits


def find_dr_ge(seq: str, k: int = 20, disjoint: bool = True) -> list[tuple[int, int, str]]:
    s = seq.upper()
    n = len(s)
    idx: dict[str, int] = {}
    hits: list[tuple[int, int, str]] = []
    for i in range(n - k + 1):
        sub = s[i : i + k]
        if sub in idx:
            p = idx[sub]
            if (not disjoint) or (i - p >= k):
                hits.append((p, i, sub))
                if len(hits) >= 30:
                    return hits
        else:
            idx[sub] = i
    return hits


def max_repeat_outside_canonical(seq: str, canonical_exempt_spans: list[tuple[int, int]]) -> dict[str, Any]:
    s = seq.upper()
    n = len(s)
    full_dr, full_motif = l2._max_disjoint_dr(s)
    full_ir, full_ir_motif = l2._max_disjoint_ir(s)
    best_out = (0, -1, -1, "")
    for k in range(50, 10, -1):
        seen: dict[str, list[int]] = {}
        found = None
        for i in range(n - k + 1):
            sub = s[i : i + k]
            if sub in seen:
                for p in seen[sub]:
                    if i - p >= k:
                        same_exempt = any(
                            (s0 <= p and p + k <= e0 and s0 <= i and i + k <= e0)
                            for s0, e0 in canonical_exempt_spans
                        )
                        if not same_exempt:
                            found = (k, p + 1, i + 1, sub)
                            break
                if found:
                    break
            seen.setdefault(sub, []).append(i)
        if found:
            best_out = found
            break
    return {
        "max_disjoint_ir_bp": int(full_ir),
        "max_ir_motif": str(full_ir_motif),
        "max_disjoint_dr_full_bp": int(full_dr),
        "max_dr_full_motif": str(full_motif),
        "max_disjoint_dr_outside_canonical_bp": best_out[0],
        "max_dr_outside_positions_1based": [best_out[1], best_out[2]] if best_out[0] else [],
        "max_dr_outside_motif": best_out[3],
    }


def harden_polya_atg_and_acceptors(pa_seq: str) -> str:
    s = list(pa_seq.upper())
    n = len(s)
    prot = [False] * n
    for mot in ("AATAAA", "ATTAAA"):
        st = 0
        while True:
            idx = "".join(s).find(mot, st)
            if idx == -1:
                break
            for j in range(idx, idx + 6):
                prot[j] = True
            st = idx + 1
    for _ in range(12):
        idx = "".join(s).find("ATG")
        if idx == -1:
            break
        if not prot[idx + 1]:
            s[idx + 1] = "C"
        elif not prot[idx]:
            s[idx] = "C"
        else:
            s[idx + 2] = "C"
    for _ in range(30):
        cur = "".join(s)
        sp = l2.scan_donors_and_acceptors_both_strands(cur, cargo_bounds_1based=(1, n), min_donor_cv=70.0, min_acc_idx=68.0)
        plus_a = [a for a in sp["acceptors"] if a["strand_relative_to_input"] == "+"]
        plus_d = [d for d in sp["donors"] if d["strand_relative_to_input"] == "+"]
        if not plus_a and not plus_d:
            break
        changed = False
        for a in plus_a:
            g_pos = a["exon_start_1based_on_input_plus"] - 2
            a_pos = g_pos - 1
            if 0 <= g_pos < n and not prot[g_pos]:
                s[g_pos] = "C"
                changed = True
                break
            elif 0 <= a_pos < n and not prot[a_pos]:
                s[a_pos] = "C"
                changed = True
                break
        if changed:
            continue
        for d in plus_d:
            t_pos = d["exon_end_1based_on_input_plus"] + 1
            g_pos = d["exon_end_1based_on_input_plus"]
            if 0 <= t_pos < n and not prot[t_pos]:
                s[t_pos] = "C"
                changed = True
                break
            elif 0 <= g_pos < n and not prot[g_pos]:
                s[g_pos] = "C"
                changed = True
                break
        if not changed:
            break
    for _ in range(10):
        idx = "".join(s).find("ATG")
        if idx == -1:
            break
        if not prot[idx + 1]:
            s[idx + 1] = "C"
    res = "".join(s)
    if not ("ATG" not in res):
        raise ValueError('Verification check failed: "ATG" not in res')
    if not (("AATAAA" in res) or ("ATTAAA" in res)):
        raise ValueError('Verification check failed: ("AATAAA" in res) or ("ATTAAA" in res)')
    sp_chk = l2.scan_donors_and_acceptors_both_strands(res, cargo_bounds_1based=(1, len(res)), min_donor_cv=70.0, min_acc_idx=68.0)
    if not (not [a for a in sp_chk["acceptors"] if a["strand_relative_to_input"] == "+"]):
        raise ValueError('Verification check failed: not [a for a in sp_chk["acceptors"] if a["strand_relative_to_input"] == "+"]')
    if not (not [d for d in sp_chk["donors"] if d["strand_relative_to_input"] == "+"]):
        raise ValueError('Verification check failed: not [d for d in sp_chk["donors"] if d["strand_relative_to_input"] == "+"]')
    return res


def optimize_cds_zero_splice_zero_defect(
    aa_seq: str,
    *,
    prefix_context: str,
    suffix_context: str,
    existing_seq: str,
    pwms: dict[str, Any],
    seed: int,
    stop_codon: str = "TGA",
    max_attempts: int = 40,
) -> str:
    rng = random.Random(seed)
    full_aa = aa_seq + "*"
    pre = prefix_context[-45:].upper()
    suf = suffix_context[:45].upper()
    pre_len = len(pre)
    ext = existing_seq.upper()
    ext_15 = {ext[i : i + 15] for i in range(max(0, len(ext) - 14))}
    ext_15_rc = {l2.revcomp(k) for k in ext_15}
    ext_16_rc = {l2.revcomp(ext[j : j + 16]) for j in range(max(0, len(ext) - 15))}
    ext_18 = {ext[i : i + 18] for i in range(max(0, len(ext) - 17))}
    lock_mwf_ttc = aa_seq.startswith("MWF")

    def sample_cds() -> list[str]:
        cods = []
        for aa in full_aa:
            if aa == "*":
                cods.append(stop_codon)
                continue
            opts = HUMAN_CODONS[aa]
            if len(opts) == 1:
                cods.append(opts[0])
            else:
                wts = [0.42, 0.28, 0.16, 0.08, 0.04, 0.02][: len(opts)]
                cods.append(rng.choices(opts, weights=wts, k=1)[0])
        return cods

    def mutate_at(cods: list[str], pos_in_cds: int, radius: int = 2) -> None:
        c_idx = min(len(cods) - 2, max(0, pos_in_cds // 3))
        for j in range(max(0, c_idx - radius), min(len(cods) - 1, c_idx + radius + 1)):
            opts = HUMAN_CODONS[full_aa[j]]
            if len(opts) > 1:
                cods[j] = rng.choice([o for o in opts if o != cods[j]])

    best_dna = None
    best_score = (9999, 9999, 9999, 9999)
    for _ in range(max_attempts):
        cods = sample_cds()
        if lock_mwf_ttc:
            cods[2] = "TTC"
        for _step in range(200):
            if lock_mwf_ttc:
                cods[2] = "TTC"
            dna = "".join(cods)
            fixed = False
            for mot in FORBIDDEN_CDS_MOTIFS:
                idx = dna.find(mot)
                if idx >= 0:
                    mutate_at(cods, idx + 1, 2)
                    fixed = True
                    break
            if fixed:
                continue
            win = pre + dna + suf
            sp = l2.scan_donors_and_acceptors_both_strands(win, cargo_bounds_1based=(1, len(win)), min_donor_cv=70.0, min_acc_idx=68.0)
            sp_targets = []
            for d in sp["donors"]:
                p1 = d["exon_end_1based_on_input_plus"]
                if (pre_len - 5) <= p1 <= (pre_len + len(dna) + 6):
                    sp_targets.append(max(0, min(len(dna) - 3, p1 - pre_len - 1)))
            for a in sp["acceptors"]:
                p1 = a["exon_start_1based_on_input_plus"]
                if (pre_len + 1) <= p1 <= (pre_len + len(dna) + 20):
                    sp_targets.append(max(0, min(len(dna) - 3, p1 - pre_len - 2)))
            if sp_targets:
                for t in sp_targets[:8]:
                    mutate_at(cods, t, 2)
                continue
            rep_targets = []
            for _p, q, _ in find_ir_ge(dna, 15)[:4]:
                rep_targets.append(q + 4)
            for _p, q, _ in find_dr_ge(dna, 17, disjoint=True)[:4]:
                rep_targets.append(q + 4)
            for i in range(0, len(dna) - 14):
                if dna[i : i + 15] in ext_15_rc:
                    rep_targets.append(i + 5)
                    if len(rep_targets) >= 6:
                        break
            if not rep_targets:
                for i in range(0, len(dna) - 17):
                    if dna[i : i + 18] in ext_18:
                        rep_targets.append(i + 6)
                        if len(rep_targets) >= 6:
                            break
            if rep_targets:
                for t in rep_targets[:6]:
                    mutate_at(cods, t, 2)
                continue
            pwm_targets = []
            for _mid, pe in pwms.items():
                sc = l2.scan_jaspar_pwm(dna, pe, top_k=4, n_matrices_in_scan=len(pwms))
                for h in sc["all_significant_hits"]:
                    if h["passes_region_wide_bonferroni_0p05"]:
                        mid_p = (int(h["start_1based_in_window"]) + int(h["end_1based_in_window"])) // 2
                        pwm_targets.append(max(0, min(len(dna) - 3, mid_p - 1)))
            if pwm_targets:
                for t in pwm_targets[:6]:
                    mutate_at(cods, t, 2)
                continue
            break
        dna = "".join(cods)
        if not (l2.translate_dna(dna) == full_aa):
            raise ValueError('Verification check failed: l2.translate_dna(dna) == full_aa')
        win = pre + dna + suf
        sp = l2.scan_donors_and_acceptors_both_strands(win, cargo_bounds_1based=(1, len(win)), min_donor_cv=70.0, min_acc_idx=68.0)
        sp_plus_cds = sum(1 for d in sp["donors"] if d["strand_relative_to_input"] == "+" and (pre_len - 5) <= d["exon_end_1based_on_input_plus"] <= (pre_len + len(dna) + 6)) + \
                      sum(1 for a in sp["acceptors"] if a["strand_relative_to_input"] == "+" and (pre_len + 1) <= a["exon_start_1based_on_input_plus"] <= (pre_len + len(dna) + 20))
        sp_all_cds = sum(1 for d in sp["donors"] if (pre_len - 5) <= d["exon_end_1based_on_input_plus"] <= (pre_len + len(dna) + 6)) + \
                     sum(1 for a in sp["acceptors"] if (pre_len + 1) <= a["exon_start_1based_on_input_plus"] <= (pre_len + len(dna) + 20))
        bad_m = sum(dna.count(m) for m in FORBIDDEN_CDS_MOTIFS)
        ir16_ext = sum(1 for i in range(len(dna) - 15) if dna[i : i + 16] in ext_16_rc)
        ir15_int = len(find_ir_ge(dna, 15))
        dr18_ext = sum(1 for i in range(len(dna) - 17) if dna[i : i + 18] in ext_18)
        pwm_cnt = sum(l2.scan_jaspar_pwm(dna, pe, top_k=2, n_matrices_in_scan=len(pwms))["significant_hits_rel0p80_region_wide_bonferroni_0p05"] for pe in pwms.values())
        score = (bad_m + ir16_ext + dr18_ext + pwm_cnt + sp_plus_cds, sp_all_cds, ir15_int, 0)
        if score < best_score:
            best_score = score
            best_dna = dna
        if score == (0, 0, 0, 0):
            break
    if not (best_dna is not None):
        raise ValueError('Verification check failed: best_dna is not None')
    return best_dna


def scan_unbounded_cryptic_introns(full_seq: str, tu_specs: list[dict[str, Any]]) -> dict[str, Any]:
    s_full = full_seq.upper()

    def _scan(use_full_prom: bool) -> dict[str, Any]:
        all_i, clip_i, prom_to_cds_i, internal_i = [], [], [], []
        for tu in tu_specs:
            start0 = tu["prom_start_0based"] if use_full_prom else tu["tss_0based"]
            pa_e0 = tu["polya_end_0based"]
            cds_s0 = tu["cds_start_0based"]
            tx = s_full[start0:pa_e0]
            rel_cds = cds_s0 - start0
            sp = l2.scan_donors_and_acceptors_both_strands(tx, cargo_bounds_1based=(1, len(tx)), min_donor_cv=70.0, min_acc_idx=68.0)
            pd = [d for d in sp["donors"] if d["strand_relative_to_input"] == "+"]
            pa = [a for a in sp["acceptors"] if a["strand_relative_to_input"] == "+"]
            met1 = rel_cds + 1
            sp_end = rel_cds + 105
            for d in pd:
                dp = int(d["exon_end_1based_on_input_plus"])
                for a in pa:
                    ap = int(a["exon_start_1based_on_input_plus"])
                    ilen = ap - dp - 1
                    if ilen >= 50:
                        clips = (dp + 1) <= sp_end and (ap - 1) >= met1
                        is_prom_to_cds = (dp < met1) and (ap >= met1)
                        is_internal = dp >= met1
                        rec = {
                            "tu": tu["tu_id"], "donor_pos1": dp, "donor_9mer": d["nine_mer"],
                            "donor_cv": d["ss87_cv"], "acceptor_pos1": ap,
                            "acceptor_idx": a["heuristic_acceptor_index"], "intron_len_nt": ilen,
                            "clips_start_or_sp": clips, "prom_to_cds_or_pa": is_prom_to_cds,
                            "internal_cds_or_pa": is_internal,
                        }
                        all_i.append(rec)
                        if clips:
                            clip_i.append(rec)
                        if is_prom_to_cds:
                            prom_to_cds_i.append(rec)
                        if is_internal:
                            internal_i.append(rec)
        return {
            "total_introns_ge50nt": len(all_i),
            "start_or_sp_clipping_introns": clip_i,
            "prom_to_cds_or_pa_introns": prom_to_cds_i,
            "internal_cds_or_pa_introns": internal_i,
        }

    return {
        "tss_to_polya": _scan(use_full_prom=False),
        "full_promoter_to_polya": _scan(use_full_prom=True),
    }


def scan_strict_orfs_and_readthrough(full_seq: str, tu_specs: list[dict[str, Any]], min_aa: int = 8) -> dict[str, Any]:
    s_full = full_seq.upper()
    utr5_uatgs, post_stop_orfs_ge8, stop_tails = [], [], []
    for tu in tu_specs:
        tss0, cds_s0, cds_e0, pa_e0 = tu["tss_0based"], tu["cds_start_0based"], tu["cds_end_0based"], tu["polya_end_0based"]
        rt_bound = tu.get("rt_bound_0based", min(len(s_full), pa_e0 + 180))
        leader = s_full[tss0:cds_s0]
        for m in re.finditer("ATG", leader):
            utr5_uatgs.append({"tu": tu["tu_id"], "offset_from_tss": m.start(), "leader_len": len(leader)})
        after_stop = s_full[cds_e0 : cds_e0 + 12]
        if not (after_stop[:3] in ("TAA", "TAG", "TGA")):
            raise ValueError(f"{tu['tu_id']} missing immediate tandem stop: {after_stop}")
        stop_tails.append({"tu": tu["tu_id"], "cap_12bp": after_stop, "inframe_readthrough_aa": 0})
        end_rt = min(len(s_full), pa_e0 + 180, rt_bound)
        tx_rt = s_full[cds_e0:end_rt]
        for i in range(len(tx_rt) - 2):
            if tx_rt[i : i + 3] == "ATG":
                aas = []
                for j in range(i, len(tx_rt) - 2, 3):
                    aa = l2.GENETIC_CODE[tx_rt[j : j + 3]]
                    if aa == "*":
                        break
                    aas.append(aa)
                if len(aas) >= min_aa:
                    post_stop_orfs_ge8.append({"tu": tu["tu_id"], "offset": i, "aa_len": len(aas), "peptide": "".join(aas)})
    return {
        "mkglehldsa_present": ("ATGAAGGGCCTTGAGCATCTGGATTCTGCCTAA" in s_full) or ("ATGAAGGGCCTTGAGCATCTGGATTCTGCCTAA" in l2.revcomp(s_full)),
        "utr5_uATG_hits": utr5_uatgs,
        "stop_readthrough_caps": stop_tails,
        "post_stop_downstream_orf_ge8aa": post_stop_orfs_ge8,
    }


def scan_swissprot_peptides(aa: str, sp_kmers: dict[int, set[str]]) -> dict[str, Any]:
    out = {}
    tot_8_11 = 0
    f8_11_list = []
    for k in (8, 9, 10, 11, 15):
        n_tot = max(0, len(aa) - k + 1)
        foreign = [aa[i : i + k] for i in range(n_tot) if aa[i : i + k] not in sp_kmers[k]]
        out[f"k{k}_total"] = n_tot
        out[f"k{k}_foreign"] = len(foreign)
        if k in (8, 9, 10, 11):
            tot_8_11 += len(foreign)
            f8_11_list.extend(foreign[:5])
        if k == 15:
            out["k15_foreign_examples"] = foreign[:5]
    out["foreign_8_11mers_total"] = tot_8_11
    out["foreign_8_11mer_examples"] = f8_11_list[:8]
    return out


def _mmcif_chain_id(row: dict[str, str], label_key: str, auth_key: str) -> str:
    """Prefer wwPDB canonical label_asym_id over author-assigned auth_asym_id (preserving deposited glycan subchains)."""
    lbl = row.get(label_key, "")
    if lbl and lbl not in (".", "?"):
        return lbl
    auth = row.get(auth_key, "")
    return "" if auth in (".", "?") else auth


def _parse_mmcif_struct_conn_glycan_links(
    lines: list[str], receptor_chains: set[str], partner_protein_chains: set[str]
) -> dict[str, Any]:
    """Parse _struct_conn covalent links directly (preferring wwPDB label_asym_id over auth_asym_id) to classify
    glycan chains covalently attached to partner (Fc) protein chains vs receptor self-glycan chains."""
    cols: list[str] = []
    in_loop = False
    reading_rows = False
    tok_buf: list[str] = []
    rows: list[dict[str, str]] = []
    for ln in lines:
        s = ln.strip()
        if s == "loop_":
            cols = []
            in_loop = False
            reading_rows = False
            tok_buf = []
            continue
        if s.startswith("_struct_conn."):
            cols.append(s)
            in_loop = True
            reading_rows = False
            continue
        if in_loop and cols:
            if not s or s.startswith("#") or s.startswith("_"):
                in_loop = False
                reading_rows = False
                continue
            reading_rows = True
            toks = re.findall(r"'[^']*'|\"[^\"]*\"|\S+", s)
            tok_buf.extend(t.strip("'\"") for t in toks)
            while len(tok_buf) >= len(cols):
                row_toks = tok_buf[: len(cols)]
                tok_buf = tok_buf[len(cols) :]
                rows.append({cols[i]: row_toks[i] for i in range(len(cols))})
    partner_glyc: set[str] = set()
    receptor_glyc: set[str] = set()
    glycan_links: list[dict[str, str]] = []
    for r in rows:
        if r.get("_struct_conn.conn_type_id") != "covale":
            continue
        c1 = _mmcif_chain_id(r, "_struct_conn.ptnr1_label_asym_id", "_struct_conn.ptnr1_auth_asym_id")
        comp1 = r.get("_struct_conn.ptnr1_auth_comp_id") or r.get("_struct_conn.ptnr1_label_comp_id", "")
        seq1 = r.get("_struct_conn.ptnr1_auth_seq_id") or r.get("_struct_conn.ptnr1_label_seq_id", "")
        c2 = _mmcif_chain_id(r, "_struct_conn.ptnr2_label_asym_id", "_struct_conn.ptnr2_auth_asym_id")
        comp2 = r.get("_struct_conn.ptnr2_auth_comp_id") or r.get("_struct_conn.ptnr2_label_comp_id", "")
        seq2 = r.get("_struct_conn.ptnr2_auth_seq_id") or r.get("_struct_conn.ptnr2_label_seq_id", "")
        if c1 != c2:
            if c1 in partner_protein_chains and c2 not in receptor_chains and c2 not in partner_protein_chains:
                partner_glyc.add(c2)
                glycan_links.append({"id": r.get("_struct_conn.id", ""), "owner": "PARTNER_FC", "from": f"{c1}:{comp1}{seq1}", "to": f"{c2}:{comp2}{seq2}"})
            elif c2 in partner_protein_chains and c1 not in receptor_chains and c1 not in partner_protein_chains:
                partner_glyc.add(c1)
                glycan_links.append({"id": r.get("_struct_conn.id", ""), "owner": "PARTNER_FC", "from": f"{c2}:{comp2}{seq2}", "to": f"{c1}:{comp1}{seq1}"})
            elif c1 in receptor_chains and c2 not in receptor_chains and c2 not in partner_protein_chains:
                receptor_glyc.add(c2)
                glycan_links.append({"id": r.get("_struct_conn.id", ""), "owner": "RECEPTOR_SELF", "from": f"{c1}:{comp1}{seq1}", "to": f"{c2}:{comp2}{seq2}"})
            elif c2 in receptor_chains and c1 not in receptor_chains and c1 not in partner_protein_chains:
                receptor_glyc.add(c1)
                glycan_links.append({"id": r.get("_struct_conn.id", ""), "owner": "RECEPTOR_SELF", "from": f"{c2}:{comp2}{seq2}", "to": f"{c1}:{comp1}{seq1}"})
    return {
        "partner_glycan_chains": sorted(partner_glyc),
        "receptor_self_glycan_chains": sorted(receptor_glyc),
        "covalent_glycan_links": glycan_links,
    }


def parse_mmcif_interface_contacts(
    cif_path: pathlib.Path,
    receptor_chains: set[str],
    partner_chains: set[str],
    cutoff_angstrom: float = 4.5,
    include_partner_hetatm: bool = False,
    partner_protein_chains: set[str] | None = None,
    receptor_self_glycan_chains: set[str] | None = None,
) -> dict[str, Any]:
    """Direct pure-Python mmCIF parser computing heavy-atom interface contacts (ATOM + partner Fc HETATM
    glycans, strictly separated from receptor-linked self-glycans verified via _struct_conn), using
    wwPDB canonical label_asym_id (with auth_asym_id fallback) so glycan label subchains sharing an
    author chain ID (such as 4X4M Assembly 2 chains L and M sharing auth_asym_id='D') are never dropped."""
    cols: list[str] = []
    rec_atoms: list[tuple[str, int, str, float, float, float]] = []
    par_atoms: list[tuple[str, int, str, str, float, float, float]] = []
    self_glyc_atoms: list[tuple[str, int, str, float, float, float]] = []
    partner_hetatm_atoms_by_chain: dict[str, int] = {}
    lines = cif_path.read_text(encoding="utf-8", errors="ignore").splitlines()
    p_prot = partner_protein_chains if partner_protein_chains is not None else set(partner_chains)
    conn_info = _parse_mmcif_struct_conn_glycan_links(lines, receptor_chains, p_prot)
    partner_glyc_set = (set(conn_info["partner_glycan_chains"]) | (partner_chains - p_prot)) & partner_chains
    self_g_set = set(receptor_self_glycan_chains) if receptor_self_glycan_chains is not None else set(conn_info["receptor_self_glycan_chains"])
    in_atom_loop = False
    for ln in lines:
        s = ln.strip()
        if s == "loop_":
            cols = []
            in_atom_loop = False
            continue
        if s.startswith("_atom_site."):
            cols.append(s)
            in_atom_loop = True
            continue
        if in_atom_loop and (s.startswith("ATOM ") or s.startswith("HETATM ")):
            toks = s.split()
            if len(toks) < len(cols):
                continue
            cmap = {cols[i]: toks[i] for i in range(len(cols))}
            grp = cmap.get("_atom_site.group_PDB", "")
            elem = cmap.get("_atom_site.type_symbol", "")
            if elem in ("H", "D"):
                continue
            ch = _mmcif_chain_id(cmap, "_atom_site.label_asym_id", "_atom_site.auth_asym_id")
            comp = cmap.get("_atom_site.auth_comp_id") or cmap.get("_atom_site.label_comp_id", "")
            if comp == "HOH":
                continue
            try:
                resn = int(cmap.get("_atom_site.auth_seq_id") or cmap.get("_atom_site.label_seq_id") or "0")
                x = float(cmap["_atom_site.Cartn_x"])
                y = float(cmap["_atom_site.Cartn_y"])
                z = float(cmap["_atom_site.Cartn_z"])
            except Exception:
                continue
            if grp == "ATOM" and ch in receptor_chains:
                rec_atoms.append((ch, resn, comp, x, y, z))
            if grp == "ATOM" and ch in p_prot:
                par_atoms.append((ch, resn, comp, grp, x, y, z))
            elif include_partner_hetatm and grp == "HETATM" and ch in partner_glyc_set:
                par_atoms.append((ch, resn, comp, grp, x, y, z))
                partner_hetatm_atoms_by_chain[ch] = partner_hetatm_atoms_by_chain.get(ch, 0) + 1
            if grp == "HETATM" and ch in self_g_set:
                self_glyc_atoms.append((ch, resn, comp, x, y, z))
        elif in_atom_loop and s and not s.startswith("#") and not s.startswith("_"):
            if s.startswith("loop_"):
                cols = []
                in_atom_loop = False
            else:
                in_atom_loop = False

    c2 = cutoff_angstrom * cutoff_angstrom
    rec_contact_res: set[int] = set()
    rec_protein_contact_res: set[int] = set()
    rec_fc_glycan_contact_res: set[int] = set()
    rec_self_glycan_contact_res: set[int] = set()
    par_contact_res: set[tuple[str, int, str, str]] = set()
    fc_glycan_contacts = 0
    self_glycan_contacts = 0
    for rch, rseq, rcomp, rx, ry, rz in rec_atoms:
        for pch, pseq, pcomp, pgrp, px, py, pz in par_atoms:
            dx = rx - px
            if abs(dx) > cutoff_angstrom:
                continue
            dy = ry - py
            if abs(dy) > cutoff_angstrom:
                continue
            dz = rz - pz
            if dx * dx + dy * dy + dz * dz <= c2:
                rec_contact_res.add(rseq)
                par_contact_res.add((pch, pseq, pcomp, pgrp))
                if pgrp == "HETATM":
                    fc_glycan_contacts += 1
                    rec_fc_glycan_contact_res.add(rseq)
                else:
                    rec_protein_contact_res.add(rseq)
        for sch, sseq, scomp, sx, sy, sz in self_glyc_atoms:
            dx = rx - sx
            if abs(dx) > cutoff_angstrom:
                continue
            dy = ry - sy
            if abs(dy) > cutoff_angstrom:
                continue
            dz = rz - sz
            if dx * dx + dy * dy + dz * dz <= c2:
                self_glycan_contacts += 1
                rec_self_glycan_contact_res.add(rseq)

    # Parse _struct_ref_seq_dif engineered mutations on receptor_chains & check contact overlap directly from mmCIF!
    aa3_to_1 = {
        "ALA": "A", "ARG": "R", "ASN": "N", "ASP": "D", "CYS": "C", "GLN": "Q", "GLU": "E",
        "GLY": "G", "HIS": "H", "ILE": "I", "LEU": "L", "LYS": "K", "MET": "M", "PHE": "F",
        "PRO": "P", "SER": "S", "THR": "T", "TRP": "W", "TYR": "Y", "VAL": "V",
    }
    resolved_rec_seqs = {rseq for (_rch, rseq, _rcomp, _rx, _ry, _rz) in rec_atoms}
    eng_muts_per_chain: dict[str, list[tuple[int, str]]] = {}
    all_eng_mut_rows = 0
    dif_cols: list[str] = []
    in_dif = False
    for ln in lines:
        s = ln.strip()
        if s == "loop_":
            dif_cols = []
            in_dif = False
            continue
        if s.startswith("_struct_ref_seq_dif."):
            dif_cols.append(s)
            in_dif = True
            continue
        if in_dif:
            if not s or s.startswith("#") or s.startswith("_") or s == "loop_":
                in_dif = False
                continue
            if "engineered mutation" in s.lower():
                all_eng_mut_rows += 1
                toks = re.findall(r"'[^']*'|\"[^\"]*\"|\S+", s)
                if len(toks) >= len(dif_cols):
                    dmap = {dif_cols[i]: toks[i].strip("'\"") for i in range(len(dif_cols))}
                    ch_d = dmap.get("_struct_ref_seq_dif.pdbx_pdb_strand_id", "")
                    if ch_d in receptor_chains:
                        db_num = dmap.get("_struct_ref_seq_dif.pdbx_seq_db_seq_num", "")
                        wt3 = dmap.get("_struct_ref_seq_dif.db_mon_id", "")
                        mut3 = dmap.get("_struct_ref_seq_dif.mon_id", "")
                        if db_num.isdigit():
                            pos = int(db_num)
                            lbl = f"{aa3_to_1.get(wt3, wt3)}{pos}{aa3_to_1.get(mut3, mut3)}"
                            eng_muts_per_chain.setdefault(ch_d, []).append((pos, lbl))
    rec_muts = sorted({item for v in eng_muts_per_chain.values() for item in v})
    resolved_muts = [lbl for p, lbl in rec_muts if p in resolved_rec_seqs]
    muts_in_prot = [lbl for p, lbl in rec_muts if p in rec_protein_contact_res]
    muts_in_fc_glyc = [lbl for p, lbl in rec_muts if p in rec_fc_glycan_contact_res]
    muts_in_self_glyc = [lbl for p, lbl in rec_muts if p in rec_self_glycan_contact_res]

    # Exact minimum heavy-atom distances for ALL resolved engineered mutations to partner protein & partner Fc glycans
    par_prot_pts = [(px, py, pz) for (_pch, _pseq, _pcomp, pgrp, px, py, pz) in par_atoms if pgrp == "ATOM"]
    fc_glyc_atoms = [(pch, pseq, pcomp, px, py, pz) for (pch, pseq, pcomp, pgrp, px, py, pz) in par_atoms if pgrp == "HETATM"]
    fc_glyc_pts = [(gx, gy, gz) for (_c, _s, _m, gx, gy, gz) in fc_glyc_atoms]
    resolved_mut_positions = {p for p, _lbl in rec_muts if p in resolved_rec_seqs}
    resolved_mut_pts = [(rx, ry, rz) for (_rch, rseq, _rc, rx, ry, rz) in rec_atoms if rseq in resolved_mut_positions]
    min_mut_dist_prot: float | None = (
        round(min(math.dist(rp, pp) for rp in resolved_mut_pts for pp in par_prot_pts), 3)
        if (resolved_mut_pts and par_prot_pts)
        else None
    )
    min_mut_dist_glyc: float | None = (
        round(min(math.dist(rp, gp) for rp in resolved_mut_pts for gp in fc_glyc_pts), 3)
        if (resolved_mut_pts and fc_glyc_pts)
        else None
    )

    mut_glycan_dists: dict[str, dict[str, float]] = {}
    for pos, lbl in rec_muts:
        if lbl in muts_in_self_glyc:
            rpts = [(rx, ry, rz) for (_rch, rseq, _rc, rx, ry, rz) in rec_atoms if rseq == pos]
            d_fc = min(math.dist(rp, (gx, gy, gz)) for rp in rpts for (_c, _s, _m, gx, gy, gz) in fc_glyc_atoms) if (rpts and fc_glyc_atoms) else -1.0
            d_self = min(math.dist(rp, (sx, sy, sz)) for rp in rpts for (_c, _s, _m, sx, sy, sz) in self_glyc_atoms) if (rpts and self_glyc_atoms) else -1.0
            mut_glycan_dists[lbl] = {
                "min_dist_to_fc_linked_glycans_A": round(d_fc, 3),
                "min_dist_to_receptor_self_glycans_A": round(d_self, 3),
            }

    return {
        "pdb_file": cif_path.name,
        "pdb_sha256_prefix16": sha256_file(cif_path)[:16],
        "chain_id_namespace": "label_asym_id_preferred_with_auth_asym_id_fallback",
        "cutoff_angstrom": cutoff_angstrom,
        "receptor_chains": sorted(receptor_chains),
        "partner_chains": sorted(partner_chains),
        "fc_linked_glycan_chains_from_struct_conn": conn_info["partner_glycan_chains"],
        "receptor_self_glycan_chains_from_struct_conn": sorted(self_g_set),
        "struct_conn_covalent_glycan_links": conn_info["covalent_glycan_links"],
        "partner_fc_hetatm_glycan_heavy_atoms_by_chain": dict(sorted(partner_hetatm_atoms_by_chain.items())),
        "partner_fc_hetatm_glycan_heavy_atoms_total": sum(partner_hetatm_atoms_by_chain.values()),
        "receptor_contact_residue_count": len(rec_contact_res),
        "receptor_contact_min_max_auth_seq": [min(rec_contact_res), max(rec_contact_res)] if rec_contact_res else [],
        "partner_contact_residue_count": len(par_contact_res),
        "partner_fc_hetatm_glycan_contact_pairs": fc_glycan_contacts,
        "receptor_self_glycan_contact_pairs": self_glycan_contacts,
        "declared_engineered_mutation_rows_all_chains": all_eng_mut_rows,
        "receptor_chain_engineered_mutations_declared_count": len(rec_muts),
        "receptor_chain_engineered_mutations_resolved_count": len(resolved_muts),
        "receptor_chain_engineered_mutations_resolved": resolved_muts,
        "engineered_mutations_in_protein_contacts_le_4p5A": muts_in_prot,
        "engineered_mutations_in_fc_glycan_contacts_le_4p5A": muts_in_fc_glyc,
        "engineered_mutations_in_receptor_self_glycan_contacts_le_4p5A": muts_in_self_glyc,
        "min_engineered_mutation_dist_to_partner_protein_A": min_mut_dist_prot,
        "min_engineered_mutation_dist_to_partner_glycan_A": min_mut_dist_glyc,
        "receptor_self_glycan_contact_mutation_distances_A": mut_glycan_dists,
    }


def measure_5fo9_stalk_distance(cif_path: pathlib.Path) -> float:
    """Measure exact C3b-TED anchor (hydrolyzed thioester Glu1013, from native C3 Gln1013) to CR1 CCP17 C-terminus distance in PDB 5FO9 (verifying GY-026 49.21 A geometry)."""
    cols: list[str] = []
    coords: dict[tuple[str, int, str], tuple[float, float, float]] = {}
    in_atom = False
    for ln in cif_path.read_text(encoding="utf-8", errors="ignore").splitlines():
        s = ln.strip()
        if s == "loop_":
            cols = []
            in_atom = False
            continue
        if s.startswith("_atom_site."):
            cols.append(s)
            in_atom = True
            continue
        if in_atom and s.startswith("ATOM "):
            toks = s.split()
            if len(toks) < len(cols):
                continue
            cmap = {cols[i]: toks[i] for i in range(len(cols))}
            aname = cmap.get("_atom_site.label_atom_id", "")
            if aname != "CA":
                continue
            ch = cmap.get("_atom_site.auth_asym_id", "")
            try:
                rseq = int(cmap.get("_atom_site.auth_seq_id", "0"))
                coords[(ch, rseq, aname)] = (
                    float(cmap["_atom_site.Cartn_x"]),
                    float(cmap["_atom_site.Cartn_y"]),
                    float(cmap["_atom_site.Cartn_z"]),
                )
            except Exception:
                continue
    # C3b hydrolyzed thioester Glu1013 (chain B, native C3 Gln1013 per _struct_ref_seq_dif) to CR1 CCP17 C-terminal residue (chain C max auth_seq)
    c_res = sorted(r for (ch, r, _) in coords if ch == "C")
    b_ca = coords.get(("B", 1013, "CA"))
    c_end = coords.get(("C", c_res[-1], "CA")) if c_res else None
    if b_ca and c_end:
        return round(math.dist(b_ca, c_end), 2)
    return -1.0


def verify_gravina_cd64t_cds_comparison(
    staged_cds: str,
    expected_aa: str | None = None,
    *,
    check_private_xml_cache: bool = False,
) -> dict[str, Any]:
    """Programmatically compare staged CD64t[1-313] CDS against Gravina et al. 2023 (PMC10188358) published 942-bp CDS.

    When check_private_xml_cache=False (default, used by portable --installed-check), verification uses ONLY
    the embedded curated PMC10188358 942-bp sequence so output is 100% deterministic across private repos and
    public snapshots without depending on local XML caches.
    """
    gravina_cds = GRAVINA_2023_PUBLISHED_CD64T_CDS_942BP.upper()
    source_origin = "embedded_curated_PMC10188358_942bp_cds"
    xml_verified: bool | None = None
    if check_private_xml_cache:
        xml_verified = False
        if GRAVINA_PMC_XML_CACHE.is_file():
            xml_txt = GRAVINA_PMC_XML_CACHE.read_text(encoding="utf-8", errors="ignore")
            xml_stripped = re.sub(r"\s+", "", re.sub(r"<[^>]+>", " ", xml_txt)).upper()
            if gravina_cds in xml_stripped:
                xml_verified = True
                source_origin = "PMC10188358_xml_cache_verified_and_embedded_942bp_cds"
    staged = staged_cds.upper()
    if len(staged) != len(gravina_cds) or len(staged) != 942:
        raise ValueError(f"Gravina comparison length mismatch: staged={len(staged)}, gravina={len(gravina_cds)}")
    if len(staged) % 3 != 0:
        raise ValueError(f"CD64t CDS length {len(staged)} not divisible by 3")
    nt_diffs = sum(1 for a, b in zip(staged, gravina_cds) if a != b)
    aa_staged = l2.translate_dna(staged)
    aa_gravina = l2.translate_dna(gravina_cds)
    aa_diffs = sum(1 for a, b in zip(aa_staged, aa_gravina) if a != b)
    codon_diffs = sum(1 for i in range(0, len(staged) - 3, 3) if staged[i : i + 3] != gravina_cds[i : i + 3])
    staged_term_ile = staged[-6:-3]
    gravina_term_ile = gravina_cds[-6:-3]
    staged_stop = staged[-3:]
    gravina_stop = gravina_cds[-3:]
    staged_sha = sha256_str(staged)
    gravina_sha = sha256_str(gravina_cds)
    if expected_aa is not None and aa_staged != expected_aa + "*":
        raise ValueError("Staged CD64t translation does not match P12314[1-313]*")
    if aa_diffs != 0 or aa_staged != aa_gravina:
        raise ValueError(f"Expected 0 amino-acid differences vs Gravina 2023, got {aa_diffs}")
    if nt_diffs != 235:
        raise ValueError(f"Expected 235 synonymous nucleotide differences vs Gravina 2023, got {nt_diffs}")
    if staged_term_ile != "ATT" or gravina_term_ile != "ATA":
        raise ValueError(f"Unexpected terminal Ile codons: staged={staged_term_ile}, gravina={gravina_term_ile}")
    if staged_stop != "TAG" or gravina_stop != "TAG":
        raise ValueError(f"Unexpected stop codons: staged={staged_stop}, gravina={gravina_stop}")
    if staged_sha != "0390bb1d298aa7dc4eea19909377bf6e3200091f05f28918e94d6dc148beea86":
        raise ValueError(f"Staged CD64t CDS SHA-256 mismatch: {staged_sha}")
    if gravina_sha != "76300c42d602eaf14e24d66df1b84e992590f02309127e4a3a0e2dbecc5ad7df":
        raise ValueError(f"Gravina published CD64t CDS SHA-256 mismatch: {gravina_sha}")
    return {
        "source_pmcid": "PMC10188358",
        "comparison_method": "programmatic_base_by_base_and_translation_diff",
        "gravina_reference_origin": source_origin,
        "portable_verification_scope": (
            "PRIVATE_CACHE_XML_ATTESTATION_MODE"
            if check_private_xml_cache
            else "PORTABLE_EMBEDDED_PMC10188358_REFERENCE_NO_PRIVATE_CACHE_DEPENDENCY"
        ),
        "local_private_xml_cache_checked": bool(check_private_xml_cache),
        "local_pmc_xml_substring_verified": xml_verified,
        "compared_bp": len(staged),
        "compared_aa_excl_stop": len(aa_staged) - 1,
        "staged_cds_sha256": staged_sha,
        "gravina_published_cds_sha256": gravina_sha,
        "staged_terminal_ile_codon": staged_term_ile,
        "gravina_published_terminal_ile_codon": gravina_term_ile,
        "staged_stop_codon": staged_stop,
        "gravina_published_stop_codon": gravina_stop,
        "synonymous_nucleotide_differences_vs_gravina": nt_diffs,
        "synonymous_codon_differences_vs_gravina": codon_diffs,
        "amino_acid_differences_vs_gravina": aa_diffs,
        "exact_protein_match": aa_diffs == 0,
        "exact_nucleotide_match": nt_diffs == 0,
        "note": (
            f"Embedded-reference comparison against the curated {len(staged)}-bp Gravina 2023 coding sequence "
            f"({gravina_sha[:8]}..., encoding UniProt P12314[1-313], published directly in Gravina et al. 2023 "
            f"public Methods [PMC10188358]; independent live retrieval of that external article text lies outside "
            f"the public snapshot): "
            f"exact {len(aa_staged)-1}-aa protein match ({aa_diffs} aa diffs), with {nt_diffs} synonymous nucleotide differences "
            f"({codon_diffs} synonymous codon changes; terminal Ile313 {staged_term_ile} vs {gravina_term_ile}) — NOT a 942-bp nucleotide identity match."
        ),
    }


def _is_valid_sha256_hex(val: Any) -> bool:
    return (
        isinstance(val, str)
        and len(val) == 64
        and all(ch in "0123456789abcdef" for ch in val)
        and len(set(val)) > 1
    )


def compute_upstream_record_sha256(record: dict[str, Any]) -> str:
    """Canonical SHA-256 digest of an upstream qualification record excluding its `record_sha256` field."""
    body = {k: v for k, v in record.items() if k != "record_sha256"}
    canonical = json.dumps(body, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def build_authenticated_upstream_record(
    *,
    gate_id: str,
    verdict: str,
    lot_id: str,
    mcb_id: str,
    construct_id: str,
    chassis_id: str,
    evidence_summary: dict[str, Any],
    assay_id: str = "ASSAY-QA-VERIFIED-001",
    issuer_authority_id: str = "OPENISLET_QA_RELEASE_BOARD_V1",
    product_track: str = "CORE_ABX",
    product_variant_id: str | None = None,
) -> dict[str, Any]:
    """Construct a canonically SHA-256-authenticated, issuer-bound same-lot upstream qualification record."""
    if not isinstance(evidence_summary, dict) or len(evidence_summary) == 0:
        raise ValueError("evidence_summary is mandatory and must be a non-empty dict")
    pvid = product_variant_id if product_variant_id is not None else construct_id
    for lbl, val in (
        ("gate_id", gate_id),
        ("verdict", verdict),
        ("lot_id", lot_id),
        ("mcb_id", mcb_id),
        ("construct_id", construct_id),
        ("chassis_id", chassis_id),
        ("product_track", product_track),
        ("product_variant_id", pvid),
        ("assay_id", assay_id),
        ("issuer_authority_id", issuer_authority_id),
    ):
        if _strict_literal_id(val) is None:
            raise ValueError(f"build_authenticated_upstream_record requires strict literal {lbl}, got {val!r}")
    assert_strictly_finite_json(evidence_summary, "upstream_evidence_summary")
    rec: dict[str, Any] = {
        "gate_id": gate_id,
        "verdict": verdict,
        "lot_id": lot_id,
        "mcb_id": mcb_id,
        "construct_id": construct_id,
        "product_variant_id": pvid,
        "chassis_id": chassis_id,
        "product_track": product_track,
        "assay_id": assay_id,
        "issuer_authority_id": issuer_authority_id,
        "evidence_summary": copy.deepcopy(evidence_summary),
    }
    rec["record_sha256"] = compute_upstream_record_sha256(rec)
    return rec


INCUMBENT_ADJUDICATION_STATES = frozenset({
    "INCUMBENT_CONCLUSIVELY_BROKEN",
    "INCUMBENT_UNRESOLVED_STRADDLING_CAP",
    "INCUMBENT_INTACT_WITHIN_CAPS",
})

INCUMBENT_STATE_TO_RECORD_VERDICT: dict[str, str] = {
    "INCUMBENT_CONCLUSIVELY_BROKEN": "PAIRED_COMPARATOR_L2V3_CONCLUSIVELY_BROKEN",
    "INCUMBENT_UNRESOLVED_STRADDLING_CAP": "PAIRED_COMPARATOR_L2V3_UNRESOLVED_STRADDLING_CAP",
    "INCUMBENT_INTACT_WITHIN_CAPS": "PAIRED_COMPARATOR_L2V3_INTACT_WITHIN_CAPS",
}


def _validate_literal_panel_id_list(
    raw_ids: Any,
    *,
    field_name: str,
    min_count: int,
) -> tuple[list[str] | None, list[str]]:
    """Validate a list of unique strict literal panel IDs (sera, NK donors, differentiation batches)."""
    if not isinstance(raw_ids, list) or len(raw_ids) < min_count:
        return None, [f"{field_name} must be a list of >= {min_count} unique strict literal IDs."]
    cleaned: list[str] = []
    for item in raw_ids:
        lid = _strict_literal_id(item)
        if lid is None:
            return None, [f"{field_name} contains invalid or whitespace-padded ID={item!r}."]
        cleaned.append(lid)
    if len(set(cleaned)) != len(cleaned):
        return None, [f"{field_name} contains duplicate IDs."]
    return sorted(cleaned), []


def compute_paired_assay_panel_digest(
    paired_assay_run_id: str,
    t1d_sera_panel_ids: list[str],
    nk_donor_panel_ids: list[str],
    differentiation_batch_ids: list[str],
) -> str:
    """Order-independent canonical SHA-256 digest of the matched head-to-head assay panel."""
    body = {
        "paired_assay_run_id": paired_assay_run_id,
        "t1d_sera_panel_ids": sorted(t1d_sera_panel_ids),
        "nk_donor_panel_ids": sorted(nk_donor_panel_ids),
        "differentiation_batch_ids": sorted(differentiation_batch_ids),
    }
    return hashlib.sha256(
        json.dumps(body, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
    ).hexdigest()


def _validate_candidate_arm_evidence(
    candidate_arm_evidence: Any,
) -> tuple[dict[str, Any] | None, list[str]]:
    """Validate the candidate-arm quantitative head-to-head metrics bound inside PAIRED_L2V3_INCUMBENT_COMPARATOR."""
    errs: list[str] = []
    if not isinstance(candidate_arm_evidence, dict):
        return None, ["Paired comparator missing mandatory candidate_arm_evidence dict binding candidate head-to-head metrics."]
    parsed: dict[str, Any] = {}
    for copy_lbl in ("copy1_monoallelic", "copy2_biallelic"):
        sub = candidate_arm_evidence.get(copy_lbl)
        if not isinstance(sub, dict):
            errs.append(f"Paired comparator candidate_arm_evidence missing {copy_lbl} dict.")
            continue
        sub_parsed: dict[str, Fraction] = {}
        for metric_k in (
            "intact_serum_cd16_adcc_u95_pct",
            "igg_attributable_cd16_adcc_u95_pct",
            "ap_c5b9_u95_pct",
            "overall_20pct_nhs_u95_pct",
        ):
            dv = _strict_decimal_in_range(sub.get(metric_k), min_val=Decimal("0"), max_val=Decimal("100"))
            if dv is None:
                errs.append(
                    f"Paired comparator candidate_arm_evidence.{copy_lbl}.{metric_k}={sub.get(metric_k)!r} "
                    "missing or outside [0, 100]%."
                )
            else:
                sub_parsed[metric_k] = Fraction(dv)
        parsed[copy_lbl] = sub_parsed

    for p_lbl, l_k, u_k in (
        ("classical_c4b2a", "classical_c4b2a_l95_pct", "classical_c4b2a_u95_pct"),
        ("lectin_c4b2a", "lectin_c4b2a_l95_pct", "lectin_c4b2a_u95_pct"),
    ):
        lv = _strict_decimal_in_range(candidate_arm_evidence.get(l_k), min_val=Decimal("0"), max_val=Decimal("100"))
        uv = _strict_decimal_in_range(candidate_arm_evidence.get(u_k), min_val=Decimal("0"), max_val=Decimal("100"))
        if lv is None or uv is None:
            errs.append(f"Paired comparator candidate_arm_evidence missing or out-of-domain {p_lbl} ({l_k}, {u_k}).")
        elif Fraction(uv) < Fraction(lv):
            errs.append(f"Paired comparator candidate_arm_evidence malformed {p_lbl} interval (L95 > U95).")
        else:
            parsed[l_k] = Fraction(lv)
            parsed[u_k] = Fraction(uv)

    if errs:
        return None, errs
    return parsed, []


def _derive_paired_comparator_incumbent_adjudication(
    evidence_summary: Any,
    *,
    adcc_cap: Decimal = Decimal("5.0"),
    ap_cap: Decimal = Decimal("5.0"),
    nhs_cap: Decimal = Decimal("5.0"),
    classical_c4b2a_cap: Decimal = Decimal("10.0"),
    lectin_c4b2a_cap: Decimal = Decimal("10.0"),
) -> tuple[str | None, dict[str, Any], list[str]]:
    """
    Validate all 6 paired incumbent L2_V3 confidence intervals (12 endpoints: L95 & U95 in [0, 100]%)
    using exact context-independent Fraction arithmetic and enforce the symmetric 3-state incumbent rule:
      - INCUMBENT_CONCLUSIVELY_BROKEN: at least one incumbent endpoint has L95 > cap;
      - INCUMBENT_UNRESOLVED_STRADDLING_CAP: no endpoint has L95 > cap, but >= 1 straddles (L95 <= cap < U95);
      - INCUMBENT_INTACT_WITHIN_CAPS: all 6 incumbent endpoints have U95 <= cap.
    Never classifies incumbent uncertainty (L95 <= cap < U95) as broken!
    """
    errs: list[str] = []
    if not isinstance(evidence_summary, dict):
        return None, {}, ["Paired comparator evidence_summary must be a dict."]

    endpoint_specs: tuple[tuple[str, str, str, Fraction], ...] = (
        ("incumbent_intact_serum_cd16_adcc", "incumbent_intact_serum_cd16_adcc_l95_pct", "incumbent_intact_serum_cd16_adcc_u95_pct", Fraction(adcc_cap)),
        ("incumbent_igg_attributable_cd16_adcc", "incumbent_igg_attributable_cd16_adcc_l95_pct", "incumbent_igg_attributable_cd16_adcc_u95_pct", Fraction(adcc_cap)),
        ("incumbent_ap_c5b9", "incumbent_ap_c5b9_l95_pct", "incumbent_ap_c5b9_u95_pct", Fraction(ap_cap)),
        ("incumbent_overall_20pct_nhs", "incumbent_overall_20pct_nhs_l95_pct", "incumbent_overall_20pct_nhs_u95_pct", Fraction(nhs_cap)),
        ("incumbent_classical_c4b2a", "incumbent_classical_c4b2a_l95_pct", "incumbent_classical_c4b2a_u95_pct", Fraction(classical_c4b2a_cap)),
        ("incumbent_lectin_c4b2a", "incumbent_lectin_c4b2a_l95_pct", "incumbent_lectin_c4b2a_u95_pct", Fraction(lectin_c4b2a_cap)),
    )

    conclusively_broken: list[str] = []
    straddling_cap: list[str] = []
    for name, l_key, u_key, cap_frac in endpoint_specs:
        lv = _strict_decimal_in_range(evidence_summary.get(l_key), min_val=Decimal("0"), max_val=Decimal("100"))
        uv = _strict_decimal_in_range(evidence_summary.get(u_key), min_val=Decimal("0"), max_val=Decimal("100"))
        if lv is None:
            errs.append(f"Paired comparator missing or out-of-domain [0, 100]% field {l_key}={evidence_summary.get(l_key)!r}.")
        if uv is None:
            errs.append(f"Paired comparator missing or out-of-domain [0, 100]% field {u_key}={evidence_summary.get(u_key)!r}.")
        if lv is None or uv is None:
            continue
        lf = Fraction(lv)
        uf = Fraction(uv)
        if uf < lf:
            errs.append(f"Paired comparator malformed {name} interval (L95={lv} > U95={uv}).")
            continue
        if lf > cap_frac:
            conclusively_broken.append(f"{name} (L95={float(lf):.2f}% > {float(cap_frac):.2f}%)")
        elif uf > cap_frac:
            straddling_cap.append(f"{name} (L95={float(lf):.2f}% <= {float(cap_frac):.2f}% < U95={float(uf):.2f}%)")

    if errs:
        return None, {}, errs

    if conclusively_broken:
        state = "INCUMBENT_CONCLUSIVELY_BROKEN"
    elif straddling_cap:
        state = "INCUMBENT_UNRESOLVED_STRADDLING_CAP"
    else:
        state = "INCUMBENT_INTACT_WITHIN_CAPS"

    details = {
        "incumbent_adjudication_state": state,
        "conclusively_broken_endpoints": conclusively_broken,
        "straddling_cap_endpoints": straddling_cap,
    }
    return state, details, []


def _derive_paired_comparator_l2v3_broken(
    evidence_summary: dict[str, Any],
    *,
    adcc_ap_nhs_cap: Decimal = Decimal("5.0"),
    c4b2a_cap: Decimal = Decimal("10.0"),
) -> tuple[bool | None, list[str]]:
    """Back-compatible wrapper around 3-state incumbent adjudication (returns True ONLY if conclusively broken, False ONLY if intact, None if unresolved or invalid)."""
    state, details, errs = _derive_paired_comparator_incumbent_adjudication(
        evidence_summary,
        adcc_cap=adcc_ap_nhs_cap,
        ap_cap=adcc_ap_nhs_cap,
        nhs_cap=adcc_ap_nhs_cap,
        classical_c4b2a_cap=c4b2a_cap,
        lectin_c4b2a_cap=c4b2a_cap,
    )
    if errs or state is None:
        return None, errs
    if state == "INCUMBENT_CONCLUSIVELY_BROKEN":
        return True, []
    if state == "INCUMBENT_INTACT_WITHIN_CAPS":
        return False, []
    return None, [f"Incumbent comparator unresolved (straddles cap): {', '.join(details['straddling_cap_endpoints'])}."]


def build_authenticated_paired_comparator_record(
    *,
    candidate_construct_id: str,
    candidate_lot_id: str,
    candidate_mcb_id: str,
    chassis_id: str,
    incumbent_comparator_construct_id: str,
    incumbent_comparator_lot_id: str,
    incumbent_comparator_mcb_id: str,
    paired_assay_run_id: str,
    evidence_summary: dict[str, Any],
    candidate_arm_evidence: dict[str, Any],
    t1d_sera_panel_ids: list[str],
    nk_donor_panel_ids: list[str],
    differentiation_batch_ids: list[str],
    independent_t1d_sera_n: int | None = None,
    independent_nk_donors_n: int | None = None,
    independent_differentiations_n: int | None = None,
    issuer_authority_id: str = "OPENISLET_INDEPENDENT_ASSAY_REGISTRY_V1",
    product_track: str = "CORE_ABX",
    product_variant_id: str | None = None,
) -> dict[str, Any]:
    """Construct a SHA-256-authenticated head-to-head paired comparator record binding BOTH candidate & incumbent quantitative arms and the matched assay panel."""
    pvid = product_variant_id if product_variant_id is not None else candidate_construct_id
    for lbl, val in (
        ("candidate_construct_id", candidate_construct_id),
        ("candidate_lot_id", candidate_lot_id),
        ("candidate_mcb_id", candidate_mcb_id),
        ("chassis_id", chassis_id),
        ("incumbent_comparator_construct_id", incumbent_comparator_construct_id),
        ("incumbent_comparator_lot_id", incumbent_comparator_lot_id),
        ("incumbent_comparator_mcb_id", incumbent_comparator_mcb_id),
        ("paired_assay_run_id", paired_assay_run_id),
        ("issuer_authority_id", issuer_authority_id),
        ("product_track", product_track),
        ("product_variant_id", pvid),
    ):
        if _strict_literal_id(val) is None:
            raise ValueError(f"Paired comparator record requires strict literal {lbl}, got {val!r}")

    sera_ids, s_errs = _validate_literal_panel_id_list(t1d_sera_panel_ids, field_name="t1d_sera_panel_ids", min_count=6)
    nk_ids, n_errs = _validate_literal_panel_id_list(nk_donor_panel_ids, field_name="nk_donor_panel_ids", min_count=3)
    diff_ids, d_errs = _validate_literal_panel_id_list(differentiation_batch_ids, field_name="differentiation_batch_ids", min_count=3)
    if s_errs or n_errs or d_errs or sera_ids is None or nk_ids is None or diff_ids is None:
        raise ValueError(f"Invalid paired assay panel IDs: {s_errs + n_errs + d_errs}")

    sera_cnt = len(sera_ids) if independent_t1d_sera_n is None else independent_t1d_sera_n
    nk_cnt = len(nk_ids) if independent_nk_donors_n is None else independent_nk_donors_n
    diff_cnt = len(diff_ids) if independent_differentiations_n is None else independent_differentiations_n
    for lbl, cnt, expected_len in (
        ("independent_t1d_sera_n", sera_cnt, len(sera_ids)),
        ("independent_nk_donors_n", nk_cnt, len(nk_ids)),
        ("independent_differentiations_n", diff_cnt, len(diff_ids)),
    ):
        if type(cnt) is not int or cnt != expected_len:
            raise ValueError(f"Paired comparator {lbl}={cnt!r} must be exact int matching panel ID count {expected_len}")

    cand_parsed, cand_errs = _validate_candidate_arm_evidence(candidate_arm_evidence)
    if cand_errs or cand_parsed is None:
        raise ValueError(f"Invalid paired comparator candidate_arm_evidence: {cand_errs}")

    inc_state, inc_details, inc_errs = _derive_paired_comparator_incumbent_adjudication(evidence_summary)
    if inc_errs or inc_state is None:
        raise ValueError(f"Invalid paired comparator incumbent evidence_summary: {inc_errs}")

    panel_digest = compute_paired_assay_panel_digest(paired_assay_run_id, sera_ids, nk_ids, diff_ids)
    rec: dict[str, Any] = {
        "gate_id": "PAIRED_L2V3_INCUMBENT_COMPARATOR",
        "verdict": INCUMBENT_STATE_TO_RECORD_VERDICT[inc_state],
        "incumbent_adjudication_state": inc_state,
        "derived_incumbent_broken": inc_state == "INCUMBENT_CONCLUSIVELY_BROKEN",
        "product_track": product_track,
        "chassis_id": chassis_id,
        "candidate_construct_id": candidate_construct_id,
        "product_variant_id": pvid,
        "candidate_lot_id": candidate_lot_id,
        "candidate_mcb_id": candidate_mcb_id,
        "incumbent_comparator_construct_id": incumbent_comparator_construct_id,
        "incumbent_comparator_lot_id": incumbent_comparator_lot_id,
        "incumbent_comparator_mcb_id": incumbent_comparator_mcb_id,
        "paired_assay_run_id": paired_assay_run_id,
        "t1d_sera_panel_ids": sera_ids,
        "nk_donor_panel_ids": nk_ids,
        "differentiation_batch_ids": diff_ids,
        "panel_digest": panel_digest,
        "independent_t1d_sera_n": sera_cnt,
        "independent_nk_donors_n": nk_cnt,
        "independent_differentiations_n": diff_cnt,
        "issuer_authority_id": issuer_authority_id,
        "evidence_summary": copy.deepcopy(evidence_summary),
        "candidate_arm_evidence": copy.deepcopy(candidate_arm_evidence),
        "incumbent_adjudication_details": inc_details,
    }
    rec["record_sha256"] = compute_upstream_record_sha256(rec)
    return rec


def write_gate28b_trusted_qualification_store(
    store_path: pathlib.Path | str,
    *,
    upstream_records: list[dict[str, Any]] | None = None,
    paired_comparator_records: list[dict[str, Any]] | None = None,
    store_authority_id: str = "OPENISLET_QA_RELEASE_BOARD_V1",
) -> pathlib.Path:
    """Persist Gate 28-B upstream and paired comparator records into an independent trusted store (JSON registry or directory)."""
    sp = pathlib.Path(store_path)
    up_list = list(upstream_records or [])
    pc_list = list(paired_comparator_records or [])
    for rec in up_list + pc_list:
        if not isinstance(rec, dict) or not _is_valid_sha256_hex(rec.get("record_sha256")):
            raise ValueError("Every record written to trusted store must have a valid 64-hex record_sha256")

    if sp.suffix.lower() == ".json":
        if sp.is_file():
            doc = load_strict_json_bytes(sp.read_bytes(), f"trusted_store:{sp.name}")
        else:
            doc = {
                "schema_version": TRUSTED_QUAL_STORE_SCHEMA_VERSION,
                "store_authority_id": store_authority_id,
                "upstream_qualifications": {},
                "paired_comparator_records": {},
            }
        for rec in up_list:
            doc.setdefault("upstream_qualifications", {})[rec["record_sha256"]] = copy.deepcopy(rec)
        for rec in pc_list:
            doc.setdefault("paired_comparator_records", {})[rec["record_sha256"]] = copy.deepcopy(rec)
        sp.parent.mkdir(parents=True, exist_ok=True)
        sp.write_text(json.dumps(doc, indent=2, sort_keys=True, ensure_ascii=False) + "\n", encoding="utf-8")
        return sp

    # Directory store layout
    (sp / "upstream_qualifications").mkdir(parents=True, exist_ok=True)
    (sp / "paired_comparator_records").mkdir(parents=True, exist_ok=True)
    meta_file = sp / "store_metadata.json"
    if not meta_file.is_file():
        meta_file.write_text(
            json.dumps(
                {"schema_version": TRUSTED_QUAL_STORE_SCHEMA_VERSION, "store_authority_id": store_authority_id},
                indent=2,
                sort_keys=True,
            ) + "\n",
            encoding="utf-8",
        )
    for rec in up_list:
        (sp / "upstream_qualifications" / f"{rec['record_sha256']}.json").write_text(
            json.dumps(rec, indent=2, sort_keys=True, ensure_ascii=False) + "\n", encoding="utf-8"
        )
    for rec in pc_list:
        (sp / "paired_comparator_records" / f"{rec['record_sha256']}.json").write_text(
            json.dumps(rec, indent=2, sort_keys=True, ensure_ascii=False) + "\n", encoding="utf-8"
        )
    return sp


def _lookup_gate28b_trusted_record(
    store_path: pathlib.Path | str | None,
    *,
    category: str,
    expected_sha256: Any,
    allowed_issuers: set[str],
) -> tuple[dict[str, Any] | None, str | None, str | None]:
    """
    Resolve a Gate 28-B qualification or paired comparator record STRICTLY from an independent
    external trusted qualification store (JSON registry file or directory). Never reads caller inline payloads.
    Returns (record_or_None, error_msg_or_None, deterministic_source_label_or_None).
    """
    if store_path is None:
        return None, "trusted_qualification_store not provided", None
    if not isinstance(store_path, (pathlib.Path, str)):
        return None, "trusted_qualification_store has invalid path type", None
    sp = pathlib.Path(store_path)
    if not sp.exists():
        return None, f"trusted_qualification_store path missing: {sp.name}", f"missing:{sp.name}"
    if not _is_valid_sha256_hex(expected_sha256):
        return None, f"Invalid 64-hex reference digest for {category}: {expected_sha256!r}", f"store:{sp.name}"

    try:
        if sp.is_file():
            doc = load_strict_json_bytes(sp.read_bytes(), f"trusted_store:{sp.name}")
            if not isinstance(doc, dict):
                return None, "Trusted store registry JSON must be an object", f"registry_file:{sp.name}"
            if doc.get("schema_version") != TRUSTED_QUAL_STORE_SCHEMA_VERSION:
                return None, f"Trusted store schema_version mismatch: {doc.get('schema_version')!r}", f"registry_file:{sp.name}"
            if _strict_literal_id(doc.get("store_authority_id")) not in allowed_issuers:
                return None, f"Trusted store authority {doc.get('store_authority_id')!r} not in allowlist", f"registry_file:{sp.name}"
            bucket = doc.get(category)
            if not isinstance(bucket, dict):
                return None, f"Trusted store missing bucket {category!r}", f"registry_file:{sp.name}"
            rec = bucket.get(expected_sha256)
            if not isinstance(rec, dict):
                return None, f"Record {expected_sha256[:16]}... not found in trusted store bucket {category!r}", f"registry_file:{sp.name}"
            return rec, None, f"registry_file:{sp.name}"

        if sp.is_dir():
            meta_file = sp / "store_metadata.json"
            if meta_file.is_file():
                meta = load_strict_json_bytes(meta_file.read_bytes(), "store_metadata.json")
                if (
                    not isinstance(meta, dict)
                    or meta.get("schema_version") != TRUSTED_QUAL_STORE_SCHEMA_VERSION
                    or _strict_literal_id(meta.get("store_authority_id")) not in allowed_issuers
                ):
                    return None, "Trusted store directory store_metadata.json failed authority/schema verification", "store_dir"
            elif (sp / "registry.json").is_file():
                return _lookup_gate28b_trusted_record(
                    sp / "registry.json",
                    category=category,
                    expected_sha256=expected_sha256,
                    allowed_issuers=allowed_issuers,
                )
            else:
                return None, "Trusted store directory missing store_metadata.json", "store_dir"
            rec_file = sp / category / f"{expected_sha256}.json"
            if not rec_file.is_file():
                return None, f"Record {expected_sha256[:16]}... not found in trusted store dir {category!r}", "store_dir"
            rec = load_strict_json_bytes(rec_file.read_bytes(), rec_file.name)
            if not isinstance(rec, dict):
                return None, f"Trusted store record {rec_file.name} is not a JSON object", "store_dir"
            return rec, None, "store_dir"
    except Exception as exc:
        return None, f"Failed reading trusted store ({type(exc).__name__}): {exc}", f"unreadable:{sp.name}"

    return None, "Unsupported trusted_qualification_store path type", f"unsupported:{sp.name}"


def _validate_iip0041_side_contract_schema(sc: Any) -> None:
    """Strictly validate required Gate 28-B structure & allowlists on the decoded side contract."""
    if not isinstance(sc, dict):
        raise ValueError("Side contract JSON root must be a dict")
    if sc.get("schema_version") != "iip0041_abx_cd64t_il1rn_side_contract_v0.8.0":
        raise ValueError(f"Unexpected side contract schema_version={sc.get('schema_version')!r}")
    if sc.get("contribution_id") != "IIP-0041" or sc.get("decision_id") != "DEC-120":
        raise ValueError("Invalid IIP-0041 side contract metadata")
    zlt = sc.get("zero_lims_touch_implementation_compliance")
    if not isinstance(zlt, dict) or zlt.get("modeb_construct_fasta_sha256") != PINNED_FASTA_SHA:
        raise ValueError("Side contract Mode-B FASTA SHA-256 pin mismatch")
    gates = sc.get("executable_stage0_gates")
    if not isinstance(gates, dict) or not isinstance(gates.get("Gate_28_B"), dict):
        raise ValueError("Side contract missing executable_stage0_gates.Gate_28_B")
    g28b = gates["Gate_28_B"]
    for req_list_key in (
        "allowed_issuer_authorities",
        "eligible_product_tracks",
        "blocked_product_tracks",
        "eligible_chassis",
        "promotion_eligible_construct_ids",
        "non_promotable_control_construct_ids",
        "blocked_cd46_hold_construct_ids",
        "blocked_tertiary_cfh_cd55_hold_construct_ids",
        "allowed_zygosities",
    ):
        val = g28b.get(req_list_key)
        if not isinstance(val, list) or len(val) == 0 or not all(_strict_literal_id(x) is not None for x in val):
            raise ValueError(f"Side contract Gate_28_B.{req_list_key} must be a non-empty list of strict literal IDs")
    if not isinstance(g28b.get("eligible_incumbent_comparators_by_chassis"), dict):
        raise ValueError("Side contract missing eligible_incumbent_comparators_by_chassis")
    if not isinstance(g28b.get("required_authenticated_upstream_records"), dict):
        raise ValueError("Side contract missing required_authenticated_upstream_records")
    if not isinstance(g28b.get("required_trusted_paired_comparator_record"), dict):
        raise ValueError("Side contract missing required_trusted_paired_comparator_record")


def _load_iip0041_side_contract(
    side_contract_path: pathlib.Path | None = None,
    *,
    require_pinned_sha: bool = True,
) -> tuple[dict[str, Any], str, bool]:
    """
    Strictly decode and validate the IIP-0041 side contract (rejecting duplicate keys and non-finite numbers)
    and check its SHA-256 against runtime PINNED_SIDE_CONTRACT_SHA256.
    Returns (side_contract_dict, actual_sha256, policy_pin_verified).
    """
    sc_path = side_contract_path if side_contract_path is not None else (OPENISLET_ROOT / PINNED_SIDE_CONTRACT_REL)
    if not sc_path.is_file():
        raise FileNotFoundError(f"Missing immutable IIP-0041 side contract: {sc_path}")
    raw_bytes = sc_path.read_bytes()
    actual_sha = sha256_bytes(raw_bytes)
    sc = load_strict_json_bytes(raw_bytes, f"side_contract:{sc_path.name}")
    _validate_iip0041_side_contract_schema(sc)
    pin_ok = actual_sha == PINNED_SIDE_CONTRACT_SHA256
    if require_pinned_sha and not pin_ok:
        raise ValueError(
            f"Pinned IIP-0041 side-contract SHA-256 mismatch: actual={actual_sha} != pinned={PINNED_SIDE_CONTRACT_SHA256}"
        )
    return sc, actual_sha, pin_ok


def evaluate_ciita_locus2_arbitration(
    payload: dict[str, Any],
    *,
    side_contract_path: pathlib.Path | None = None,
    trusted_qualification_store: pathlib.Path | str | None = None,
) -> dict[str, Any]:
    """
    Executable winner-takes-allele CIITA Exon 5 Locus-2 arbitration & full GY-025 / Gate 28-B evaluator (fail-closed).

    Binds eligibility, allowlists, and quantitative cutoffs to the runtime-SHA-256-pinned
    data/protocols/iip0041_abx_cd64t_il1rn_side_contract_v0.8.0.json contract:
      - Runtime Policy Pin (B4): Strictly decodes the side contract (rejecting duplicate keys and non-finite values)
        and verifies its SHA-256 matches PINNED_SIDE_CONTRACT_SHA256. Any alternate or modified policy file is
        explicitly non-authorizing (status="NON_AUTHORIZING_UNPINNED_POLICY_DIAGNOSTIC", policy_pin_verified=False,
        full_promotion_authorized=False, lead_promotion_authorized=False).
      - Strictly Literal IDs & Context-Independent Rational Bounds: Zero silent whitespace stripping; leading, trailing,
        or embedded whitespace fails closed. All quantitative threshold checks use exact fractions.Fraction after strict
        finite validation (immune to ambient decimal.getcontext() precision and traps). Exact Fraction arithmetic operates
        on already-decoded Python inputs: for strict JSON-ingested payloads decoded via IEEE-754 binary64 (float64) in
        load_strict_json_text / load_strict_json_bytes, exactness starts at JSON-decoded float64 precision (not raw
        decimal text beyond 53-bit significand), whereas direct Python Decimal or int inputs retain exact decimal/integer
        precision. Day-90 MFI retention is verified via exact cross-product Fraction(day90_mfi) * 100 >= Fraction(t0_mfi) * 75
        with display rounding isolated in localcontext(prec=50), reconciling caller-supplied day90_mfi_retention_pct_vs_t0 within <= 0.5 pp.
      - Independent Trusted Qualification Store, Head-to-Head Binding, & 3-State Incumbent Adjudication: Full authorization
        NEVER accepts bare summary booleans, self-attested inline upstream records, or a bare caller boolean. All four
        records (GATE_0V_WHOLEGRAFT, RULE_S11_MOLECULAR_BATTERY, GY025_TIER6B_MASTER_LOT_OUTGROWTH, and
        PAIRED_L2V3_INCUMBENT_COMPARATOR) resolve strictly from trusted_qualification_store (operational deployment
        dependencies: independent QA operator control, verified external store provenance, write-restricted access policy,
        and separation of duties). PAIRED_L2V3_INCUMBENT_COMPARATOR binds BOTH candidate and incumbent arms plus matched
        assay panel (paired_assay_run_id, t1d_sera_panel_ids, nk_donor_panel_ids, differentiation_batch_ids, panel_digest)
        and enforces symmetric 3-state incumbent adjudication (INCUMBENT_CONCLUSIVELY_BROKEN via L95 > cap;
        INCUMBENT_UNRESOLVED_STRADDLING_CAP -> HOLD_INCUMBENT_COMPARATOR_UNRESOLVED; INCUMBENT_INTACT_WITHIN_CAPS -> RETAIN).
      - Distinct Retain-Incumbent vs Lead-Promotion Semantics: PASS_FULL_GY025_AND_GATE28B_RETAIN_L2V3 sets
        full_promotion_authorized=False and lead_promotion_authorized=False (while arbitration_closed=True and
        incumbent_retained=True); ONLY PASS_FULL_GY025_AND_GATE28B_PROMOTE authorizes lead promotion.
    """
    if not isinstance(payload, dict):
        return {
            "status": "FAIL_INVALID_PAYLOAD",
            "disposition": "DO_NOT_PROMOTE_LOCUS_2",
            "full_promotion_authorized": False,
            "lead_promotion_authorized": False,
            "arbitration_closed": False,
            "incumbent_retained": False,
            "policy_pin_verified": False,
            "pending_full_qualification_fields": [],
            "reasons": ["Gate 28-B payload must be a JSON object/dict."],
        }

    try:
        side_contract, side_contract_sha, policy_pin_verified = _load_iip0041_side_contract(
            side_contract_path,
            require_pinned_sha=False,
        )
        gate_cfg = side_contract["executable_stage0_gates"]["Gate_28_B"]
    except Exception as exc:
        return {
            "status": "FAIL_HARD_STOP",
            "disposition": "BLOCKED_MISSING_OR_INVALID_SIDE_CONTRACT",
            "full_promotion_authorized": False,
            "lead_promotion_authorized": False,
            "arbitration_closed": False,
            "incumbent_retained": False,
            "policy_pin_verified": False,
            "expected_pinned_side_contract_sha256": PINNED_SIDE_CONTRACT_SHA256,
            "pending_full_qualification_fields": [],
            "reasons": [f"Cannot load or validate immutable Gate 28-B side contract: {exc}"],
        }

    if not policy_pin_verified:
        return {
            "status": "NON_AUTHORIZING_UNPINNED_POLICY_DIAGNOSTIC",
            "disposition": "UNPINNED_OR_MODIFIED_SIDE_CONTRACT_NO_PROMOTION_AUTHORITY",
            "full_promotion_authorized": False,
            "lead_promotion_authorized": False,
            "arbitration_closed": False,
            "incumbent_retained": False,
            "policy_pin_verified": False,
            "expected_pinned_side_contract_sha256": PINNED_SIDE_CONTRACT_SHA256,
            "side_contract_sha256": side_contract_sha,
            "pending_full_qualification_fields": ["pinned_side_contract_sha256_verification"],
            "reasons": [
                f"Alternate or modified side contract rejected for authorization: "
                f"actual_sha256={side_contract_sha} != pinned_sha256={PINNED_SIDE_CONTRACT_SHA256}. "
                "Runtime promotion authority requires the exact runtime-pinned side contract."
            ],
        }

    reasons: list[str] = []
    pending_full_fields: list[str] = []

    def _strict_bool(val: Any) -> bool | None:
        return val if type(val) is bool else None

    def _strict_int(val: Any, *, min_val: int, max_val: int | None = None) -> int | None:
        if type(val) is not int:
            return None
        if val < min_val:
            return None
        if max_val is not None and val > max_val:
            return None
        return val

    allowed_issuers = set(gate_cfg["allowed_issuer_authorities"])
    eligible_tracks = set(gate_cfg["eligible_product_tracks"])
    blocked_tracks = set(gate_cfg["blocked_product_tracks"])
    eligible_chassis = set(gate_cfg["eligible_chassis"])
    promotable_leads = set(gate_cfg["promotion_eligible_construct_ids"])
    control_ids = set(gate_cfg["non_promotable_control_construct_ids"])
    cd46_hold_ids = set(gate_cfg["blocked_cd46_hold_construct_ids"])
    cfh_hold_ids = set(gate_cfg["blocked_tertiary_cfh_cd55_hold_construct_ids"])
    comparators_by_chassis: dict[str, list[str]] = gate_cfg["eligible_incumbent_comparators_by_chassis"]

    def _early_stop(status: str, disposition: str, msg_list: list[str], pending: list[str] | None = None) -> dict[str, Any]:
        return {
            "status": status,
            "disposition": disposition,
            "full_promotion_authorized": False,
            "lead_promotion_authorized": False,
            "arbitration_closed": False,
            "incumbent_retained": False,
            "policy_pin_verified": True,
            "expected_pinned_side_contract_sha256": PINNED_SIDE_CONTRACT_SHA256,
            "pending_full_qualification_fields": list(pending or []),
            "reasons": msg_list,
            "side_contract_sha256": side_contract_sha,
        }

    # 1. Positive strictly literal product_track binding (zero silent stripping!)
    product_track = _strict_literal_id(payload.get("product_track"))
    if product_track in blocked_tracks:
        return _early_stop(
            "FAIL_HARD_STOP",
            "INCOMPATIBLE_AT_LOCUS_2_PER_GY025",
            ["Track-2 B'-SCT is permanently incompatible at CIITA Locus 2 per GY-025."],
        )
    if product_track not in eligible_tracks:
        return _early_stop(
            "FAIL_HARD_STOP",
            "BLOCKED_INELIGIBLE_PRODUCT_TRACK_FOR_GATE28B",
            [
                f"product_track {payload.get('product_track')!r} is ineligible or contains illegal whitespace for Gate 28-B "
                f"(allowed exact literal side-contract tracks: {sorted(eligible_tracks)}; autologous D1b is governed exclusively by IIP-0035/DEC-114)."
            ],
        )

    # 2. Positive strictly literal construct_id binding against pinned side-contract allowlist
    construct_id = _strict_literal_id(payload.get("construct_id"))
    if construct_id is None:
        return _early_stop(
            "FAIL_HARD_STOP",
            "BLOCKED_UNREGISTERED_OR_INELIGIBLE_CONSTRUCT_ID",
            [
                f"Missing, non-string, or whitespace-padded construct_id={payload.get('construct_id')!r}; "
                "Gate 28-B requires exact literal side-contract lead construct binding (no silent stripping)."
            ],
        )
    cid_upper = construct_id.upper()
    if construct_id in cd46_hold_ids or "CD46" in cid_upper:
        addendum_raw = payload.get("cand034_cd46_tropic_addendum_cleared", False)
        addendum_bool = _strict_bool(addendum_raw)
        cd46_reasons = [
            f"{construct_id!r} is archived as an immutable HOLD-comparator outside Wave-5 Go scope "
            "(manufacture_authorized=false; requires IIP-0043/DEC-122 executable cd46_tropic_addendum and separate contract amendment; "
            "core Gate 0V-B covering CVB/HCMV is non-citable for CD46_WT)."
        ]
        if addendum_bool is None:
            cd46_reasons.append(f"Non-boolean cand034_cd46_tropic_addendum_cleared={addendum_raw!r} rejected fail-closed.")
        return _early_stop(
            "HOLD_BLOCKED",
            "BLOCKED_ARCHIVED_HOLD_COMPARATOR_CD46WT_PENDING_IIP0043_ADDENDUM",
            cd46_reasons,
            pending=["iip0043_cd46_tropic_addendum_and_contract_amendment"],
        )
    if construct_id in cfh_hold_ids or "CFH_CD55" in cid_upper:
        return _early_stop(
            "HOLD_BLOCKED",
            "BLOCKED_TERTIARY_HOLD_COMPARATOR_CFH_CD55_PIGK1",
            [
                f"{construct_id!r} is a tertiary HOLD comparator (PIGK=1, 26/12 absent Swiss-Prot windows, manufacture_authorized=false) "
                "and is ineligible for Gate 28-B promotion pending IIP-0043 cd55_full_length_addendum, matched CTRL_CFH_CD55_ONLY control, and PIGK qualification."
            ],
            pending=["iip0043_cd55_full_length_addendum_and_pigk_qualification"],
        )
    if construct_id in control_ids:
        return _early_stop(
            "CONTROL_ATTRIBUTION_ONLY_NON_PROMOTABLE",
            "NON_PROMOTABLE_SINGLE_CARGO_ATTRIBUTION_CONTROL",
            [
                f"{construct_id!r} is a single-cargo attribution control (promotion_eligible=false in immutable side contract) "
                "and can NEVER receive lead therapeutic promotion."
            ],
        )
    if "CR1" in cid_upper:
        return _early_stop(
            "FAIL_HARD_STOP",
            "BLOCKED_BY_GY026_SHORT_STALK_CR1",
            [f"{construct_id!r} is permanently blocked by GY-026 (short-stalk CR1)."],
        )
    if construct_id not in promotable_leads:
        return _early_stop(
            "FAIL_HARD_STOP",
            "BLOCKED_UNREGISTERED_OR_INELIGIBLE_CONSTRUCT_ID",
            [
                f"construct_id {construct_id!r} is not in Gate 28-B promotion-eligible lead allowlist {sorted(promotable_leads)}."
            ],
        )

    # 3. Required strictly literal chassis, lot, MCB, product_variant_id, and incumbent comparator identity binding
    chassis_id = _strict_literal_id(payload.get("chassis_id"))
    if chassis_id not in eligible_chassis:
        reasons.append(f"Invalid, whitespace-padded, or missing chassis_id {payload.get('chassis_id')!r}; allowed Core A/B/X chassis: {sorted(eligible_chassis)}.")
    lot_id = _strict_literal_id(payload.get("lot_id"))
    if lot_id is None:
        reasons.append(f"Missing or whitespace-padded mandatory literal lot_id={payload.get('lot_id')!r} for same-lot qualification binding.")
    mcb_id = _strict_literal_id(payload.get("mcb_id"))
    if mcb_id is None:
        reasons.append(f"Missing or whitespace-padded mandatory literal mcb_id={payload.get('mcb_id')!r} for master cell bank binding.")
    pvid_raw = payload.get("product_variant_id")
    if pvid_raw is None:
        product_variant_id = construct_id
    else:
        product_variant_id = _strict_literal_id(pvid_raw)
        if product_variant_id != construct_id:
            reasons.append(f"product_variant_id={pvid_raw!r} must literally match lead construct_id={construct_id!r}.")
    inc_comp_id = _strict_literal_id(payload.get("incumbent_comparator_construct_id"))
    inc_comp_lot_id = _strict_literal_id(payload.get("incumbent_comparator_lot_id"))
    if chassis_id in comparators_by_chassis:
        allowed_comps = set(comparators_by_chassis[chassis_id])
        if inc_comp_id not in allowed_comps:
            reasons.append(
                f"incumbent_comparator_construct_id {payload.get('incumbent_comparator_construct_id')!r} is not an allowlisted "
                f"literal IIP-0031 L2_V3 comparator for chassis {chassis_id!r} (allowed: {sorted(allowed_comps)})."
            )
    elif inc_comp_id is None:
        reasons.append("Missing or whitespace-padded mandatory incumbent_comparator_construct_id.")
    if inc_comp_lot_id is None:
        reasons.append("Missing or whitespace-padded mandatory literal incumbent_comparator_lot_id for paired comparator binding.")

    # 4. Strict literal zygosity & explicit exact-integer counts (ZERO defaults, NO floats, NO bools!)
    zygosity = _strict_literal_id(payload.get("zygosity"))
    allowed_zyg = set(gate_cfg["allowed_zygosities"])
    if zygosity not in allowed_zyg:
        reasons.append(
            f"Zygosity {payload.get('zygosity')!r} not in allowed exact literal set {sorted(allowed_zyg)} "
            "(heterotypic half-dosage requires separate full qualification)."
        )

    clone_cap = int(gate_cfg["clone_screening_cap_per_design"])
    clones_n = _strict_int(payload.get("clones_screened_n"), min_val=1, max_val=clone_cap)
    if clones_n is None:
        reasons.append(
            f"Invalid or omitted clones_screened_n={payload.get('clones_screened_n')!r}: require explicit exact int in [1, {clone_cap}]."
        )

    fam_cap = int(gate_cfg["gmp_aav6_locus2_donor_family_cap"])
    donor_fam_n = _strict_int(payload.get("gmp_aav6_locus2_donor_families_n"), min_val=1, max_val=fam_cap)
    if donor_fam_n is None:
        reasons.append(
            f"Invalid or omitted gmp_aav6_locus2_donor_families_n={payload.get('gmp_aav6_locus2_donor_families_n')!r}: "
            f"require explicit exact int == {fam_cap} (winner-takes-allele cap)."
        )

    min_sera = int(gate_cfg["independent_t1d_sera_min"])
    min_nk = int(gate_cfg["independent_nk_donors_min"])
    min_diff = int(gate_cfg["independent_differentiations_min"])
    sera_n = _strict_int(payload.get("independent_t1d_sera_n"), min_val=min_sera)
    nk_n = _strict_int(payload.get("independent_nk_donors_n"), min_val=min_nk)
    diff_n = _strict_int(payload.get("independent_differentiations_n"), min_val=min_diff)
    if sera_n is None or nk_n is None or diff_n is None:
        reasons.append(
            f"Invalid, omitted, or underpowered exact-int sampling counts "
            f"(sera={payload.get('independent_t1d_sera_n')!r} [min {min_sera}], "
            f"nk={payload.get('independent_nk_donors_n')!r} [min {min_nk}], "
            f"diffs={payload.get('independent_differentiations_n')!r} [min {min_diff}])."
        )

    # Mandatory matched head-to-head assay run & donor/sera/differentiation panel identity on payload
    payload_run_id = _strict_literal_id(payload.get("paired_assay_run_id"))
    if payload_run_id is None:
        reasons.append(f"Missing or whitespace-padded mandatory literal paired_assay_run_id={payload.get('paired_assay_run_id')!r}.")
    p_sera_ids, ps_errs = _validate_literal_panel_id_list(payload.get("t1d_sera_panel_ids"), field_name="t1d_sera_panel_ids", min_count=min_sera)
    p_nk_ids, pn_errs = _validate_literal_panel_id_list(payload.get("nk_donor_panel_ids"), field_name="nk_donor_panel_ids", min_count=min_nk)
    p_diff_ids, pd_errs = _validate_literal_panel_id_list(payload.get("differentiation_batch_ids"), field_name="differentiation_batch_ids", min_count=min_diff)
    reasons.extend(ps_errs + pn_errs + pd_errs)
    if sera_n is not None and p_sera_ids is not None and len(p_sera_ids) != sera_n:
        reasons.append(f"Payload t1d_sera_panel_ids count ({len(p_sera_ids)}) != independent_t1d_sera_n ({sera_n}).")
    if nk_n is not None and p_nk_ids is not None and len(p_nk_ids) != nk_n:
        reasons.append(f"Payload nk_donor_panel_ids count ({len(p_nk_ids)}) != independent_nk_donors_n ({nk_n}).")
    if diff_n is not None and p_diff_ids is not None and len(p_diff_ids) != diff_n:
        reasons.append(f"Payload differentiation_batch_ids count ({len(p_diff_ids)}) != independent_differentiations_n ({diff_n}).")
    payload_panel_digest: str | None = None
    if payload_run_id is not None and p_sera_ids is not None and p_nk_ids is not None and p_diff_ids is not None:
        payload_panel_digest = compute_paired_assay_panel_digest(payload_run_id, p_sera_ids, p_nk_ids, p_diff_ids)
        if "panel_digest" in payload and payload["panel_digest"] is not None and payload["panel_digest"] != payload_panel_digest:
            reasons.append("Payload panel_digest does not match canonical digest of paired_assay_run_id and panel IDs.")

    # 5. Mandatory separate 1-copy & 2-copy QuantiBRITE density + linked raw t0_mfi/day90_mfi retention derivation
    #    using context-independent exact Fraction cross-product comparisons over already-decoded inputs
    #    (JSON-decoded IEEE-754 float64 precision for strict JSON intake; exact Decimal/int precision when passed directly;
    #    always immune to ambient decimal.getcontext() precision and traps!)
    dens_min_frac = Fraction(Decimal(str(gate_cfg["quantibrite_surface_density_min_molecules_per_cell"])))
    ret_min = Decimal(str(gate_cfg["day90_mfi_retention_min_pct"]))
    ret_min_frac = Fraction(ret_min)
    ret_max_assay = Decimal(str(gate_cfg.get("day90_mfi_retention_max_assay_domain_pct", 1000.0)))
    ret_max_assay_frac = Fraction(ret_max_assay)
    ret_tol = Decimal(str(gate_cfg["day90_mfi_retention_reconciliation_tolerance_pp"]))
    ret_tol_frac = Fraction(ret_tol)
    adcc_max = Decimal(str(gate_cfg["intact_and_igg_adcc_u95_max_pct"]))
    ap_max = Decimal(str(gate_cfg["ap_c5b9_u95_max_pct"]))
    nhs_max = Decimal(str(gate_cfg["overall_20pct_nhs_u95_max_pct"]))
    adcc_max_frac = Fraction(adcc_max)
    ap_max_frac = Fraction(ap_max)
    nhs_max_frac = Fraction(nhs_max)
    derived_mfi_retentions: dict[str, float | None] = {}
    payload_cand_head_to_head: dict[str, Any] = {}

    for copy_lbl in ("copy1_monoallelic", "copy2_biallelic"):
        sub = payload.get(copy_lbl)
        if not isinstance(sub, dict):
            reasons.append(f"Missing mandatory separate {copy_lbl} qualification block.")
            continue
        t0 = _strict_decimal_in_range(sub.get("quantibrite_t0_molecules_per_cell"), min_val=Decimal("0"))
        d90 = _strict_decimal_in_range(sub.get("quantibrite_day90_molecules_per_cell"), min_val=Decimal("0"))
        t0_mfi = _strict_decimal_in_range(sub.get("t0_mfi"), min_val=Decimal("0"), exclusive_min=True)
        d90_mfi = _strict_decimal_in_range(sub.get("day90_mfi"), min_val=Decimal("0"))
        ret_reported_raw = sub.get("day90_mfi_retention_pct_vs_t0")
        adcc_int = _strict_decimal_in_range(sub.get("intact_serum_cd16_adcc_u95_pct"), min_val=Decimal("0"), max_val=Decimal("100"))
        adcc_igg = _strict_decimal_in_range(sub.get("igg_attributable_cd16_adcc_u95_pct"), min_val=Decimal("0"), max_val=Decimal("100"))
        ap_c5b9 = _strict_decimal_in_range(sub.get("ap_c5b9_u95_pct"), min_val=Decimal("0"), max_val=Decimal("100"))
        nhs20 = _strict_decimal_in_range(sub.get("overall_20pct_nhs_u95_pct"), min_val=Decimal("0"), max_val=Decimal("100"))
        preload_ok = _strict_bool(sub.get("post_7day_10mgml_igg_preload_functional_pass"))

        if t0 is None or Fraction(t0) < dens_min_frac:
            reasons.append(f"{copy_lbl}: t=0 calibrated CD64t density invalid or < {float(dens_min_frac):.0f} molecules/cell.")
        if d90 is None or Fraction(d90) < dens_min_frac:
            reasons.append(f"{copy_lbl}: Day-90 calibrated CD64t density invalid or < {float(dens_min_frac):.0f} molecules/cell.")
        if t0_mfi is None or d90_mfi is None:
            reasons.append(
                f"{copy_lbl}: mandatory linked raw t0_mfi (> 0) and day90_mfi (>= 0) required to derive and authenticate Day-90 MFI retention."
            )
        else:
            # Exact context-independent rational cross-product comparisons FIRST (NEVER affected by caller Decimal traps/precision/Emax):
            # 100 * day90_mfi / t0_mfi >= ret_min  <==>  Fraction(day90_mfi) * 100 >= Fraction(t0_mfi) * Fraction(ret_min)
            # 100 * day90_mfi / t0_mfi <= ret_max_assay  <==>  Fraction(day90_mfi) * 100 <= Fraction(t0_mfi) * Fraction(ret_max_assay)
            d90_mfi_frac = Fraction(d90_mfi)
            t0_mfi_frac = Fraction(t0_mfi)
            derived_ret_frac = (d90_mfi_frac * 100) / t0_mfi_frac
            out_of_assay_range_mfi = (d90_mfi_frac * 100) > (t0_mfi_frac * ret_max_assay_frac)
            passes_mfi_retention = (not out_of_assay_range_mfi) and ((d90_mfi_frac * 100) >= (t0_mfi_frac * ret_min_frac))
            # Display formatting AFTER exact Fraction comparison inside a clean Decimal context explicitly clearing
            # Inexact/Rounded/Clamped/Subnormal/Underflow and locking wide exponent bounds (supports direct Fraction,
            # Decimal, int, and float inputs; NEVER calls float() on out-of-range ratios!).
            display_ret_float, display_ret_str = _format_exact_fraction_pct_display(
                derived_ret_frac,
                out_of_assay_range=out_of_assay_range_mfi,
            )
            derived_mfi_retentions[copy_lbl] = display_ret_float
            if out_of_assay_range_mfi:
                reasons.append(
                    f"OUT_OF_ASSAY_RANGE_MFI_RETENTION: {copy_lbl}: derived Day-90 MFI retention "
                    f"({display_ret_str} = 100*{d90_mfi}/{t0_mfi}) exceeds physical assay domain cap [0, {ret_max_assay}]%."
                )
            elif not passes_mfi_retention:
                reasons.append(
                    f"{copy_lbl}: derived Day-90 MFI retention ({display_ret_str} = 100*{d90_mfi}/{t0_mfi}) < {ret_min}%."
                )
            if ret_reported_raw is not None:
                ret_rep = _strict_decimal_in_range(ret_reported_raw, min_val=Decimal("0"), max_val=ret_max_assay)
                if ret_rep is None or abs(Fraction(ret_rep) - derived_ret_frac) > ret_tol_frac:
                    reasons.append(
                        f"{copy_lbl}: reported day90_mfi_retention_pct_vs_t0={ret_reported_raw!r} fails reconciliation "
                        f"against derived 100*day90_mfi/t0_mfi={display_ret_str} (max tol {ret_tol} pp)."
                    )
        if adcc_int is None or Fraction(adcc_int) > adcc_max_frac or adcc_igg is None or Fraction(adcc_igg) > adcc_max_frac:
            reasons.append(
                f"{copy_lbl}: intact ({sub.get('intact_serum_cd16_adcc_u95_pct')!r}) or IgG-attributable "
                f"({sub.get('igg_attributable_cd16_adcc_u95_pct')!r}) CD16+ ADCC U95_t outside [0, {adcc_max}]%."
            )
        if ap_c5b9 is None or Fraction(ap_c5b9) > ap_max_frac or nhs20 is None or Fraction(nhs20) > nhs_max_frac:
            reasons.append(
                f"{copy_lbl}: AP C5b-9 ({sub.get('ap_c5b9_u95_pct')!r}) or 20% NHS ({sub.get('overall_20pct_nhs_u95_pct')!r}) "
                f"U95_t outside [0, {ap_max}]%."
            )
        if preload_ok is not True:
            reasons.append(f"{copy_lbl}: 7-day 10 mg/mL polyclonal IgG pre-loading functional assay must be strict bool True.")
        if adcc_int is not None and adcc_igg is not None and ap_c5b9 is not None and nhs20 is not None:
            payload_cand_head_to_head[copy_lbl] = {
                "intact_serum_cd16_adcc_u95_pct": Fraction(adcc_int),
                "igg_attributable_cd16_adcc_u95_pct": Fraction(adcc_igg),
                "ap_c5b9_u95_pct": Fraction(ap_c5b9),
                "overall_20pct_nhs_u95_pct": Fraction(nhs20),
            }

    # 6. Strict boolean signaling/matrix gates + mandatory quantitative IL-1Ra, basal leak, GSIS, and AP1903 endpoints
    if _strict_bool(payload.get("fcr_gamma_coip_and_phospho_syk_negative")) is not True:
        reasons.append("Empirical FcRgamma (FCER1G) co-IP & phospho-Syk/ITAM negative check must be strict bool True.")
    if _strict_bool(payload.get("cd274p_il1rn_ifn_titration_matrix_passed")) is not True:
        reasons.append("CD274p::IL1RN IFN-gamma titration matrix check must be strict bool True.")

    il1ra_min = Decimal(str(gate_cfg["il1rn_to_il1b_molar_excess_min"]))
    leak_max = Decimal(str(gate_cfg["il1rn_basal_leak_max_pct"]))
    gsis_min = Decimal(str(gate_cfg["gsis_retention_min_pct"]))
    ap1903_min = Decimal(str(gate_cfg["ap1903_icasp9_ablation_min_pct"]))

    il1ra_excess = _strict_decimal_in_range(payload.get("il1rn_to_il1b_molar_excess"), min_val=Decimal("0"))
    if il1ra_excess is None or Fraction(il1ra_excess) < Fraction(il1ra_min):
        reasons.append(
            f"Quantitative stimulated IL-1Ra:IL-1beta molar excess ({payload.get('il1rn_to_il1b_molar_excess')!r}) "
            f"missing, out of domain, or < {il1ra_min} (prospective design criterion)."
        )
    basal_leak = _strict_decimal_in_range(payload.get("il1rn_basal_leak_pct_of_induced"), min_val=Decimal("0"), max_val=Decimal("100"))
    if basal_leak is None or Fraction(basal_leak) > Fraction(leak_max):
        reasons.append(
            f"Quantitative unstimulated CD274p::IL1RN basal leak ({payload.get('il1rn_basal_leak_pct_of_induced')!r}) "
            f"missing, outside [0, 100]%, or > {leak_max}% (prospective design criterion)."
        )
    gsis_ret = _strict_decimal_in_range(payload.get("dynamic_gsis_retention_pct_of_ctrl"), min_val=Decimal("0"), max_val=Decimal("1000"))
    if gsis_ret is None or Fraction(gsis_ret) < Fraction(gsis_min):
        reasons.append(
            f"Quantitative dynamic GSIS retention ({payload.get('dynamic_gsis_retention_pct_of_ctrl')!r}) "
            f"missing, out of domain, or < {gsis_min}%."
        )
    ap1903_abl = _strict_decimal_in_range(payload.get("ap1903_icasp9_ablation_pct"), min_val=Decimal("0"), max_val=Decimal("100"))
    if ap1903_abl is None or Fraction(ap1903_abl) < Fraction(ap1903_min):
        reasons.append(
            f"Quantitative AP1903 iCasp9 ablation ({payload.get('ap1903_icasp9_ablation_pct')!r}) "
            f"missing, outside [0, 100]%, or < {ap1903_min}%."
        )

    # Optional legacy caller flag l2v3_broken_by_t1d_sera_gt_5pct: validate strict bool if supplied,
    # NEVER allow bare caller boolean alone to authorize promotion or override trusted paired comparator!
    caller_l2v3_broken: bool | None = None
    if "l2v3_broken_by_t1d_sera_gt_5pct" in payload and payload["l2v3_broken_by_t1d_sera_gt_5pct"] is not None:
        caller_l2v3_broken = _strict_bool(payload.get("l2v3_broken_by_t1d_sera_gt_5pct"))
        if caller_l2v3_broken is None:
            reasons.append(
                f"l2v3_broken_by_t1d_sera_gt_5pct={payload.get('l2v3_broken_by_t1d_sera_gt_5pct')!r} must be explicit strict bool (True/False) when supplied."
            )

    # 7. Owning GY-025 requires BOTH independent classical (C1q/sensitized) AND lectin (MBL/mannan) C4b2a intervals in [0, 100]%!
    cl_max = Decimal(str(gate_cfg["classical_c1q_c4b2a_u95_max_pct"]))
    lec_max = Decimal(str(gate_cfg["lectin_mbl_c4b2a_u95_max_pct"]))
    hold_pathways: list[str] = []
    for p_label, l_key, u_key, cap_pct in (
        ("classical_C1q_C4b2a", "classical_c4b2a_l95_pct", "classical_c4b2a_u95_pct", cl_max),
        ("lectin_MBL_C4b2a", "lectin_c4b2a_l95_pct", "lectin_c4b2a_u95_pct", lec_max),
    ):
        l95 = _strict_decimal_in_range(payload.get(l_key), min_val=Decimal("0"), max_val=Decimal("100"))
        u95 = _strict_decimal_in_range(payload.get(u_key), min_val=Decimal("0"), max_val=Decimal("100"))
        if l95 is None or u95 is None:
            reasons.append(f"Missing or out-of-domain [0, 100]% independent {p_label} interval ({l_key}, {u_key}) required by GY-025.")
        elif Fraction(u95) < Fraction(l95):
            reasons.append(f"Malformed {p_label} interval (L95={l95} > U95={u95}).")
        else:
            payload_cand_head_to_head[l_key] = Fraction(l95)
            payload_cand_head_to_head[u_key] = Fraction(u95)
            if Fraction(l95) > Fraction(cap_pct):
                reasons.append(f"{p_label} L95_t = {float(l95):.2f}% > {cap_pct}% -> FAIL_HARD_STOP.")
            elif Fraction(u95) > Fraction(cap_pct):
                hold_pathways.append(f"{p_label} (L95_t={float(l95):.2f}% <= {cap_pct}% < U95_t={float(u95):.2f}%)")

    # 8. Full GY-025 physical endpoints (omitted -> caps at COMPONENT_PASS; supplied invalid/failing -> FAIL closed!)
    eff_abs_min = Decimal(str(gate_cfg["efferocytosis_abs_min_pct"]))
    eff_wt_min = Decimal(str(gate_cfg["efferocytosis_wt_min_pct"]))
    iec_t50_max = Decimal(str(gate_cfg["iec_morphogenesis_t50_max_h"]))
    iec_viab_min = Decimal(str(gate_cfg["iec_viability_min_pct"]))
    pericyte_min = Decimal(str(gate_cfg["gate0g_pericyte_min_pct"]))

    eff_abs_raw = payload.get("exact_stack_efferocytosis_abs_pct")
    eff_wt_raw = payload.get("exact_stack_efferocytosis_pct_of_wt")
    if eff_abs_raw is None and eff_wt_raw is None:
        pending_full_fields.append("exact_stack_efferocytosis_abs_pct_and_pct_of_wt")
    else:
        eff_abs = _strict_decimal_in_range(eff_abs_raw, min_val=Decimal("0"), max_val=Decimal("100"))
        eff_wt = _strict_decimal_in_range(eff_wt_raw, min_val=Decimal("0"), max_val=Decimal("1000"))
        if eff_abs is None or eff_wt is None or Fraction(eff_abs) < Fraction(eff_abs_min) or Fraction(eff_wt) < Fraction(eff_wt_min):
            reasons.append(
                f"Combination macrophage efferocytosis guard invalid or failed "
                f"(require abs in [{eff_abs_min}, 100.0]% and WT >= {eff_wt_min}% per GY-025/GY-010)."
            )

    iec_t50_raw = payload.get("iec_morphogenesis_t50_h")
    iec_viab_raw = payload.get("iec_viability_pct")
    if iec_t50_raw is None and iec_viab_raw is None:
        pending_full_fields.append("iec_morphogenesis_t50_h_and_iec_viability_pct")
    else:
        iec_t50 = _strict_decimal_in_range(iec_t50_raw, min_val=Decimal("0"), exclusive_min=True)
        iec_viab = _strict_decimal_in_range(iec_viab_raw, min_val=Decimal("0"), max_val=Decimal("100"))
        if iec_t50 is None or iec_viab is None or Fraction(iec_t50) > Fraction(iec_t50_max) or Fraction(iec_viab) < Fraction(iec_viab_min):
            reasons.append(
                f"Standing GY-025 PLVAP+ iEC morphogenesis/viability gate invalid or failed "
                f"(require 0 < t50 <= {iec_t50_max} h and viability in [{iec_viab_min}, 100.0]%; "
                f"got t50={iec_t50_raw!r}, viability={iec_viab_raw!r})."
            )

    pericyte_raw = payload.get("gate0g_pericyte_pct")
    if pericyte_raw is None:
        pending_full_fields.append("gate0g_pericyte_pct")
    else:
        pericyte = _strict_decimal_in_range(pericyte_raw, min_val=Decimal("0"), max_val=Decimal("100"))
        if pericyte is None or Fraction(pericyte) < Fraction(pericyte_min):
            reasons.append(
                f"Standing GY-025 Gate 0G pericyte criterion invalid or failed (require [{pericyte_min}, 100.0]%; got {pericyte_raw!r})."
            )

    # 9. Summary flags (strict bool validation) + INDEPENDENT TRUSTED QUALIFICATION STORE RESOLUTION (B3 & B4)!
    # Bare summary booleans AND self-attested inline records can NEVER authorize promotion or arbitration closure!
    for req_bool_key, desc in (
        ("gate0v_viral_safety_passed", "Gate 0V viral safety summary flag"),
        ("rule_s11_molecular_battery_passed", "Rule S11 molecular battery summary flag"),
        ("gy025_tier6b_master_lot_outgrowth_passed", "GY-025 Tier 6B master-lot outgrowth summary flag"),
    ):
        if req_bool_key in payload and payload[req_bool_key] is not None:
            bval = _strict_bool(payload[req_bool_key])
            if bval is None:
                reasons.append(f"{desc} must be strict bool when provided ({req_bool_key}={payload[req_bool_key]!r}).")
            elif bval is False:
                reasons.append(f"{desc} explicitly failed ({req_bool_key}=False).")

    req_upstream_specs: dict[str, dict[str, str]] = gate_cfg["required_authenticated_upstream_records"]
    inline_upstream = payload.get("upstream_qualification_records")
    inline_comp = payload.get("paired_comparator_record")
    self_attested_inline_ignored = (inline_upstream is not None) or (inline_comp is not None)

    # Still fail closed on malformed or tampered inline records if supplied!
    if inline_upstream is not None and not isinstance(inline_upstream, dict):
        reasons.append("upstream_qualification_records must be a dict if supplied (and is NEVER trusted without trusted_qualification_store).")
    elif isinstance(inline_upstream, dict):
        for rec_key, spec in req_upstream_specs.items():
            irec = inline_upstream.get(rec_key)
            if irec is None:
                continue
            if not isinstance(irec, dict):
                reasons.append(f"Inline upstream record {rec_key} must be a dict.")
                continue
            rsha = irec.get("record_sha256")
            if not _is_valid_sha256_hex(rsha) or compute_upstream_record_sha256(irec) != rsha:
                reasons.append(f"Inline upstream record {rec_key} SHA-256 tamper/mismatch rejected fail-closed.")
            if lot_id is not None and irec.get("lot_id") != lot_id:
                reasons.append(f"Inline upstream record {rec_key} lot_id={irec.get('lot_id')!r} != payload lot_id={lot_id!r}.")
            if mcb_id is not None and irec.get("mcb_id") != mcb_id:
                reasons.append(f"Inline upstream record {rec_key} mcb_id={irec.get('mcb_id')!r} != payload mcb_id={mcb_id!r}.")

    refs_raw = payload.get("upstream_record_refs")
    if refs_raw is not None and not isinstance(refs_raw, dict):
        reasons.append("upstream_record_refs must be a dict mapping record reference keys to 64-hex SHA-256 digests.")
        refs: dict[str, Any] = {}
    else:
        refs = dict(refs_raw or {})

    top_comp_sha = payload.get("paired_comparator_record_sha256")
    if top_comp_sha is not None:
        if "paired_comparator_record_sha256" in refs and refs["paired_comparator_record_sha256"] != top_comp_sha:
            reasons.append("Conflicting paired_comparator_record_sha256 between top-level payload and upstream_record_refs.")
        refs["paired_comparator_record_sha256"] = top_comp_sha

    authenticated_upstream_digests: dict[str, str] = {}
    trusted_store_issuers: dict[str, str] = {}
    trusted_store_source: str | None = None
    derived_incumbent_state: str | None = None
    derived_incumbent_details: dict[str, Any] = {}
    paired_comparator_summary: dict[str, Any] | None = None
    head_to_head_reconciled = False

    if trusted_qualification_store is None:
        pending_full_fields.append("trusted_qualification_store")
        for rec_key in req_upstream_specs:
            pending_full_fields.append(f"trusted_{rec_key}")
        pending_full_fields.append("trusted_paired_comparator_record")
    else:
        # Resolve all 3 upstream records from independent trusted_qualification_store
        for rec_key, spec in req_upstream_specs.items():
            ref_field = f"{rec_key}_sha256"
            ref_sha = refs.get(ref_field)
            if ref_sha is None:
                pending_full_fields.append(f"trusted_{rec_key}")
                continue
            rec, lerr, src_lbl = _lookup_gate28b_trusted_record(
                trusted_qualification_store,
                category=spec.get("store_category", "upstream_qualifications"),
                expected_sha256=ref_sha,
                allowed_issuers=allowed_issuers,
            )
            if src_lbl is not None:
                trusted_store_source = src_lbl
            if lerr is not None or rec is None:
                reasons.append(f"Trusted store resolution failed for {rec_key}: {lerr}.")
                continue
            recomputed = compute_upstream_record_sha256(rec)
            if not _is_valid_sha256_hex(rec.get("record_sha256")) or recomputed != rec.get("record_sha256") or recomputed != ref_sha:
                reasons.append(f"Trusted store record {rec_key} SHA-256 verification failed.")
                continue
            issuer = _strict_literal_id(rec.get("issuer_authority_id"))
            if issuer not in allowed_issuers:
                reasons.append(f"Trusted store record {rec_key} issuer_authority_id={rec.get('issuer_authority_id')!r} not in allowlist.")
            if _strict_literal_id(rec.get("assay_id")) is None:
                reasons.append(f"Trusted store record {rec_key} missing literal assay_id.")
            ev_sum = rec.get("evidence_summary")
            if not isinstance(ev_sum, dict) or len(ev_sum) == 0:
                reasons.append(f"Trusted store record {rec_key} missing mandatory non-empty evidence_summary.")
            if rec.get("gate_id") != spec["gate_id"]:
                reasons.append(f"Trusted store record {rec_key} gate_id={rec.get('gate_id')!r} != expected {spec['gate_id']!r}.")
            if rec.get("verdict") != spec["required_verdict"]:
                reasons.append(f"Trusted store record {rec_key} verdict={rec.get('verdict')!r} != required {spec['required_verdict']!r}.")
            if lot_id is not None and rec.get("lot_id") != lot_id:
                reasons.append(f"Trusted store record {rec_key} lot_id={rec.get('lot_id')!r} != payload lot_id={lot_id!r}.")
            if mcb_id is not None and rec.get("mcb_id") != mcb_id:
                reasons.append(f"Trusted store record {rec_key} mcb_id={rec.get('mcb_id')!r} != payload mcb_id={mcb_id!r}.")
            if rec.get("construct_id") != construct_id:
                reasons.append(f"Trusted store record {rec_key} construct_id={rec.get('construct_id')!r} != payload construct_id={construct_id!r}.")
            if rec.get("product_variant_id") != product_variant_id:
                reasons.append(f"Trusted store record {rec_key} product_variant_id={rec.get('product_variant_id')!r} != {product_variant_id!r}.")
            if chassis_id is not None and rec.get("chassis_id") != chassis_id:
                reasons.append(f"Trusted store record {rec_key} chassis_id={rec.get('chassis_id')!r} != payload chassis_id={chassis_id!r}.")
            if rec.get("product_track") != product_track:
                reasons.append(f"Trusted store record {rec_key} product_track={rec.get('product_track')!r} != {product_track!r}.")
            if isinstance(inline_upstream, dict) and isinstance(inline_upstream.get(rec_key), dict):
                if compute_upstream_record_sha256(inline_upstream[rec_key]) != recomputed:
                    reasons.append(f"Inline {rec_key} contradicts trusted qualification store record.")
            authenticated_upstream_digests[rec_key] = recomputed
            if issuer is not None:
                trusted_store_issuers[rec_key] = issuer

        # Resolve paired head-to-head comparator record binding BOTH candidate & incumbent arms + matched panel!
        comp_cfg = gate_cfg["required_trusted_paired_comparator_record"]
        comp_ref_sha = refs.get("paired_comparator_record_sha256")
        if comp_ref_sha is None:
            pending_full_fields.append("trusted_paired_comparator_record")
        else:
            crec, cerr, csrc = _lookup_gate28b_trusted_record(
                trusted_qualification_store,
                category=comp_cfg.get("store_category", "paired_comparator_records"),
                expected_sha256=comp_ref_sha,
                allowed_issuers=allowed_issuers,
            )
            if csrc is not None:
                trusted_store_source = csrc
            if cerr is not None or crec is None:
                reasons.append(f"Trusted store resolution failed for paired_comparator_record: {cerr}.")
            else:
                crecomp = compute_upstream_record_sha256(crec)
                if not _is_valid_sha256_hex(crec.get("record_sha256")) or crecomp != crec.get("record_sha256") or crecomp != comp_ref_sha:
                    reasons.append("Trusted store paired_comparator_record SHA-256 verification failed.")
                else:
                    h2h_mismatches: list[str] = []
                    c_issuer = _strict_literal_id(crec.get("issuer_authority_id"))
                    if c_issuer not in allowed_issuers:
                        h2h_mismatches.append(f"Paired comparator issuer_authority_id={crec.get('issuer_authority_id')!r} not in allowlist.")
                    if crec.get("gate_id") != comp_cfg["gate_id"]:
                        h2h_mismatches.append(f"Paired comparator gate_id={crec.get('gate_id')!r} != expected {comp_cfg['gate_id']!r}.")
                    if crec.get("product_track") != product_track:
                        h2h_mismatches.append(f"Paired comparator product_track={crec.get('product_track')!r} != {product_track!r}.")
                    if chassis_id is not None and crec.get("chassis_id") != chassis_id:
                        h2h_mismatches.append(f"Paired comparator chassis_id={crec.get('chassis_id')!r} != {chassis_id!r}.")
                    if crec.get("candidate_construct_id") != construct_id:
                        h2h_mismatches.append(f"Paired comparator candidate_construct_id={crec.get('candidate_construct_id')!r} != {construct_id!r}.")
                    if crec.get("product_variant_id") != product_variant_id:
                        h2h_mismatches.append(f"Paired comparator product_variant_id={crec.get('product_variant_id')!r} != {product_variant_id!r}.")
                    if lot_id is not None and crec.get("candidate_lot_id") != lot_id:
                        h2h_mismatches.append(f"Paired comparator candidate_lot_id={crec.get('candidate_lot_id')!r} != {lot_id!r}.")
                    if mcb_id is not None and crec.get("candidate_mcb_id") != mcb_id:
                        h2h_mismatches.append(f"Paired comparator candidate_mcb_id={crec.get('candidate_mcb_id')!r} != {mcb_id!r}.")
                    if inc_comp_id is not None and crec.get("incumbent_comparator_construct_id") != inc_comp_id:
                        h2h_mismatches.append(f"Paired comparator incumbent_comparator_construct_id={crec.get('incumbent_comparator_construct_id')!r} != {inc_comp_id!r}.")
                    if inc_comp_lot_id is not None and crec.get("incumbent_comparator_lot_id") != inc_comp_lot_id:
                        h2h_mismatches.append(f"Paired comparator incumbent_comparator_lot_id={crec.get('incumbent_comparator_lot_id')!r} != {inc_comp_lot_id!r}.")
                    if _strict_literal_id(crec.get("incumbent_comparator_mcb_id")) is None:
                        h2h_mismatches.append("Paired comparator missing literal incumbent_comparator_mcb_id.")

                    # Reconcile paired_assay_run_id, sera/NK/diff panel IDs, and panel_digest EXACTLY against payload!
                    c_run_id = _strict_literal_id(crec.get("paired_assay_run_id"))
                    if c_run_id is None:
                        h2h_mismatches.append("Paired comparator missing literal paired_assay_run_id.")
                    elif payload_run_id is not None and c_run_id != payload_run_id:
                        h2h_mismatches.append(
                            f"Head-to-head paired_assay_run_id mismatch: payload={payload_run_id!r} != trusted_record={c_run_id!r}."
                        )

                    c_sera_ids, cs_errs = _validate_literal_panel_id_list(crec.get("t1d_sera_panel_ids"), field_name="paired_record.t1d_sera_panel_ids", min_count=min_sera)
                    c_nk_ids, cn_errs = _validate_literal_panel_id_list(crec.get("nk_donor_panel_ids"), field_name="paired_record.nk_donor_panel_ids", min_count=min_nk)
                    c_diff_ids, cd_errs = _validate_literal_panel_id_list(crec.get("differentiation_batch_ids"), field_name="paired_record.differentiation_batch_ids", min_count=min_diff)
                    h2h_mismatches.extend(cs_errs + cn_errs + cd_errs)

                    c_sera_n = _strict_int(crec.get("independent_t1d_sera_n"), min_val=min_sera)
                    c_nk_n = _strict_int(crec.get("independent_nk_donors_n"), min_val=min_nk)
                    c_diff_n = _strict_int(crec.get("independent_differentiations_n"), min_val=min_diff)
                    if c_sera_n is None or (c_sera_ids is not None and c_sera_n != len(c_sera_ids)):
                        h2h_mismatches.append("Paired comparator independent_t1d_sera_n invalid or inconsistent with t1d_sera_panel_ids.")
                    if c_nk_n is None or (c_nk_ids is not None and c_nk_n != len(c_nk_ids)):
                        h2h_mismatches.append("Paired comparator independent_nk_donors_n invalid or inconsistent with nk_donor_panel_ids.")
                    if c_diff_n is None or (c_diff_ids is not None and c_diff_n != len(c_diff_ids)):
                        h2h_mismatches.append("Paired comparator independent_differentiations_n invalid or inconsistent with differentiation_batch_ids.")

                    if c_run_id is not None and c_sera_ids is not None and c_nk_ids is not None and c_diff_ids is not None:
                        c_panel_digest = compute_paired_assay_panel_digest(c_run_id, c_sera_ids, c_nk_ids, c_diff_ids)
                        if crec.get("panel_digest") != c_panel_digest:
                            h2h_mismatches.append("Paired comparator panel_digest failed canonical verification.")
                        if p_sera_ids is not None and p_sera_ids != c_sera_ids:
                            h2h_mismatches.append("Head-to-head t1d_sera_panel_ids mismatch between payload and trusted paired comparator record.")
                        if p_nk_ids is not None and p_nk_ids != c_nk_ids:
                            h2h_mismatches.append("Head-to-head nk_donor_panel_ids mismatch between payload and trusted paired comparator record.")
                        if p_diff_ids is not None and p_diff_ids != c_diff_ids:
                            h2h_mismatches.append("Head-to-head differentiation_batch_ids mismatch between payload and trusted paired comparator record.")
                        if payload_panel_digest is not None and payload_panel_digest != c_panel_digest:
                            h2h_mismatches.append("Head-to-head panel_digest mismatch between payload and trusted paired comparator record.")

                    # Reconcile ALL candidate-arm quantitative head-to-head endpoints EXACTLY against trusted record!
                    c_cand_parsed, c_cand_errs = _validate_candidate_arm_evidence(crec.get("candidate_arm_evidence"))
                    if c_cand_errs or c_cand_parsed is None:
                        h2h_mismatches.extend(c_cand_errs)
                    else:
                        for copy_lbl in ("copy1_monoallelic", "copy2_biallelic"):
                            p_sub = payload_cand_head_to_head.get(copy_lbl)
                            if p_sub is None:
                                h2h_mismatches.append(f"Cannot reconcile missing payload {copy_lbl} metrics against paired comparator record.")
                                continue
                            for mk, c_frac in c_cand_parsed[copy_lbl].items():
                                if p_sub.get(mk) != c_frac:
                                    h2h_mismatches.append(
                                        f"Head-to-head candidate metric mismatch for {copy_lbl}.{mk}: "
                                        f"payload={float(p_sub[mk]) if mk in p_sub else None} != trusted_paired_record={float(c_frac)}."
                                    )
                        for c4_k in (
                            "classical_c4b2a_l95_pct",
                            "classical_c4b2a_u95_pct",
                            "lectin_c4b2a_l95_pct",
                            "lectin_c4b2a_u95_pct",
                        ):
                            if payload_cand_head_to_head.get(c4_k) != c_cand_parsed[c4_k]:
                                h2h_mismatches.append(
                                    f"Head-to-head candidate metric mismatch for {c4_k}: "
                                    f"payload={float(payload_cand_head_to_head[c4_k]) if c4_k in payload_cand_head_to_head else None} "
                                    f"!= trusted_paired_record={float(c_cand_parsed[c4_k])}."
                                )

                    # Derive 3-state incumbent adjudication (CONCLUSIVELY_BROKEN / UNRESOLVED_STRADDLING_CAP / INTACT_WITHIN_CAPS)
                    c_state, c_inc_details, c_ev_errs = _derive_paired_comparator_incumbent_adjudication(
                        crec.get("evidence_summary"),
                        adcc_cap=adcc_max,
                        ap_cap=ap_max,
                        nhs_cap=nhs_max,
                        classical_c4b2a_cap=cl_max,
                        lectin_c4b2a_cap=lec_max,
                    )
                    if c_ev_errs or c_state is None:
                        h2h_mismatches.extend(c_ev_errs or ["Failed to derive quantitative 3-state paired comparator adjudication."])
                    else:
                        expected_c_verdict = INCUMBENT_STATE_TO_RECORD_VERDICT[c_state]
                        if crec.get("verdict") != expected_c_verdict:
                            h2h_mismatches.append(
                                f"Paired comparator verdict={crec.get('verdict')!r} contradicts quantitative measurements ({expected_c_verdict!r})."
                            )
                        if crec.get("incumbent_adjudication_state") != c_state:
                            h2h_mismatches.append(
                                f"Paired comparator incumbent_adjudication_state={crec.get('incumbent_adjudication_state')!r} != derived {c_state!r}."
                            )
                        # Caller legacy boolean cannot contradict a conclusive store state (broken vs intact)!
                        if c_state == "INCUMBENT_CONCLUSIVELY_BROKEN" and caller_l2v3_broken is False:
                            h2h_mismatches.append(
                                "Caller l2v3_broken_by_t1d_sera_gt_5pct=False contradicts trusted paired comparator state INCUMBENT_CONCLUSIVELY_BROKEN."
                            )
                        elif c_state == "INCUMBENT_INTACT_WITHIN_CAPS" and caller_l2v3_broken is True:
                            h2h_mismatches.append(
                                "Caller l2v3_broken_by_t1d_sera_gt_5pct=True contradicts trusted paired comparator state INCUMBENT_INTACT_WITHIN_CAPS."
                            )
                        derived_incumbent_state = c_state
                        derived_incumbent_details = c_inc_details
                        authenticated_upstream_digests["paired_comparator_record"] = crecomp
                        if c_issuer is not None:
                            trusted_store_issuers["paired_comparator_record"] = c_issuer
                        paired_comparator_summary = {
                            "paired_assay_run_id": c_run_id,
                            "panel_digest": crec.get("panel_digest"),
                            "incumbent_comparator_construct_id": crec.get("incumbent_comparator_construct_id"),
                            "incumbent_comparator_lot_id": crec.get("incumbent_comparator_lot_id"),
                            "incumbent_comparator_mcb_id": crec.get("incumbent_comparator_mcb_id"),
                            "incumbent_adjudication_state": c_state,
                            "derived_incumbent_broken": c_state == "INCUMBENT_CONCLUSIVELY_BROKEN",
                            "straddling_cap_endpoints": list(c_inc_details.get("straddling_cap_endpoints", [])),
                            "conclusively_broken_endpoints": list(c_inc_details.get("conclusively_broken_endpoints", [])),
                            "verdict": expected_c_verdict,
                            "head_to_head_candidate_and_panel_reconciled": len(h2h_mismatches) == 0,
                        }
                    if isinstance(inline_comp, dict) and compute_upstream_record_sha256(inline_comp) != crecomp:
                        h2h_mismatches.append("Inline paired_comparator_record contradicts trusted qualification store record.")
                    if h2h_mismatches:
                        reasons.extend(h2h_mismatches)
                    else:
                        head_to_head_reconciled = True

    bound_identity = {
        "product_track": product_track,
        "chassis_id": chassis_id,
        "construct_id": construct_id,
        "product_variant_id": product_variant_id,
        "lot_id": lot_id,
        "mcb_id": mcb_id,
        "incumbent_comparator_construct_id": inc_comp_id,
        "incumbent_comparator_lot_id": inc_comp_lot_id,
        "paired_assay_run_id": payload_run_id,
        "panel_digest": payload_panel_digest,
        "head_to_head_reconciled": head_to_head_reconciled,
        "derived_day90_mfi_retention_pct": derived_mfi_retentions,
        "trusted_store_resolution_source": trusted_store_source,
        "self_attested_inline_records_rejected": self_attested_inline_ignored,
        "authenticated_upstream_record_sha256": authenticated_upstream_digests,
        "authenticated_issuer_authorities": trusted_store_issuers,
        "paired_comparator_summary": paired_comparator_summary,
    }

    if reasons:
        return {
            "status": "FAIL_OR_PENDING",
            "disposition": "DO_NOT_PROMOTE_LOCUS_2",
            "full_promotion_authorized": False,
            "lead_promotion_authorized": False,
            "arbitration_closed": False,
            "incumbent_retained": False,
            "incumbent_adjudication_state": derived_incumbent_state,
            "policy_pin_verified": True,
            "expected_pinned_side_contract_sha256": PINNED_SIDE_CONTRACT_SHA256,
            "pending_full_qualification_fields": pending_full_fields,
            "reasons": reasons,
            "bound_identity": bound_identity,
            "side_contract_sha256": side_contract_sha,
        }
    if hold_pathways:
        return {
            "status": "HOLD_UNDERPOWERED_EXPAND_N",
            "disposition": "INCONCLUSIVE_C4B2A_BAND_EXPAND_REPLICATES",
            "full_promotion_authorized": False,
            "lead_promotion_authorized": False,
            "arbitration_closed": False,
            "incumbent_retained": False,
            "incumbent_adjudication_state": derived_incumbent_state,
            "policy_pin_verified": True,
            "expected_pinned_side_contract_sha256": PINNED_SIDE_CONTRACT_SHA256,
            "pending_full_qualification_fields": pending_full_fields,
            "reasons": [f"Inconclusive C4b2a HOLD band on {', '.join(hold_pathways)}; expand independent T1D sera/donor n."],
            "bound_identity": bound_identity,
            "side_contract_sha256": side_contract_sha,
        }
    if pending_full_fields or derived_incumbent_state is None:
        hint_broken = (
            (derived_incumbent_state == "INCUMBENT_CONCLUSIVELY_BROKEN")
            if derived_incumbent_state is not None
            else caller_l2v3_broken
        )
        winner_disp = (
            "COMPONENT_ARBITRATION_WINNER_ABX_CD64T_IL1RN_PENDING_FULL_GY025_AND_TRUSTED_STORE"
            if hint_broken is True
            else "COMPONENT_ARBITRATION_RETAIN_L2V3_PENDING_FULL_GY025_AND_TRUSTED_STORE"
        )
        return {
            "status": "COMPONENT_PASS_CIITA_ARBITRATION_ONLY_PENDING_FULL_GY025",
            "disposition": winner_disp,
            "full_promotion_authorized": False,
            "lead_promotion_authorized": False,
            "arbitration_closed": False,
            "incumbent_retained": False,
            "incumbent_adjudication_state": derived_incumbent_state,
            "policy_pin_verified": True,
            "expected_pinned_side_contract_sha256": PINNED_SIDE_CONTRACT_SHA256,
            "pending_full_qualification_fields": pending_full_fields,
            "reasons": [
                "CIITA Locus-2 humoral/signaling/IL-1Ra component passed, but full GY-025 physical endpoints and/or "
                "independent trusted_qualification_store records (Gate 0V, Rule S11, GY-025 Tier 6B, and head-to-head paired "
                f"incumbent comparator) remain pending: {', '.join(pending_full_fields)}."
            ],
            "bound_identity": bound_identity,
            "side_contract_sha256": side_contract_sha,
        }
    if derived_incumbent_state == "INCUMBENT_UNRESOLVED_STRADDLING_CAP":
        strad_list = derived_incumbent_details.get("straddling_cap_endpoints", [])
        return {
            "status": "HOLD_INCUMBENT_COMPARATOR_UNRESOLVED",
            "disposition": "INCONCLUSIVE_INCUMBENT_COMPARATOR_STRADDLES_CAP_EXPAND_REPLICATES",
            "full_promotion_authorized": False,
            "lead_promotion_authorized": False,
            "arbitration_closed": False,
            "incumbent_retained": False,
            "incumbent_adjudication_state": "INCUMBENT_UNRESOLVED_STRADDLING_CAP",
            "policy_pin_verified": True,
            "expected_pinned_side_contract_sha256": PINNED_SIDE_CONTRACT_SHA256,
            "pending_full_qualification_fields": ["incumbent_comparator_conclusive_resolution"],
            "reasons": [
                "Incumbent L2_V3 comparator is unresolved (no endpoint has L95 > cap, but >= 1 endpoint straddles cap: "
                f"{', '.join(strad_list)}); incumbent uncertainty NEVER authorizes lead promotion — expand matched replicates."
            ],
            "bound_identity": bound_identity,
            "side_contract_sha256": side_contract_sha,
        }
    if derived_incumbent_state == "INCUMBENT_CONCLUSIVELY_BROKEN":
        return {
            "status": "PASS_FULL_GY025_AND_GATE28B_PROMOTE",
            "disposition": "WINNER_TAKES_ALLELE_ABX_L2_V2_CD64T_IL1RN_ARCHIVE_LOSER_FAMILY",
            "full_promotion_authorized": True,
            "lead_promotion_authorized": True,
            "arbitration_closed": True,
            "incumbent_retained": False,
            "incumbent_adjudication_state": "INCUMBENT_CONCLUSIVELY_BROKEN",
            "policy_pin_verified": True,
            "expected_pinned_side_contract_sha256": PINNED_SIDE_CONTRACT_SHA256,
            "pending_full_qualification_fields": [],
            "reasons": [],
            "bound_identity": bound_identity,
            "side_contract_sha256": side_contract_sha,
        }
    return {
        "status": "PASS_FULL_GY025_AND_GATE28B_RETAIN_L2V3",
        "disposition": "WINNER_TAKES_ALLELE_RETAIN_IIP0031_L2V3_ARCHIVE_LOSER_FAMILY",
        "full_promotion_authorized": False,
        "lead_promotion_authorized": False,
        "arbitration_closed": True,
        "incumbent_retained": True,
        "incumbent_adjudication_state": "INCUMBENT_INTACT_WITHIN_CAPS",
        "policy_pin_verified": True,
        "expected_pinned_side_contract_sha256": PINNED_SIDE_CONTRACT_SHA256,
        "pending_full_qualification_fields": [],
        "reasons": [],
        "bound_identity": bound_identity,
        "side_contract_sha256": side_contract_sha,
    }


def build_valid_gate28b_reference_bundle(
    store_path: pathlib.Path | str | None = None,
    *,
    lot_id: str = "LOT-ABX-2026-001",
    mcb_id: str = "MCB-ISLET1A-001",
    chassis_id: str = "ISLET1_A",
    incumbent_comparator_construct_id: str = "L2_V3_CO_PRIMARY_CD200",
    incumbent_comparator_lot_id: str = "LOT-L2V3-2026-001",
    incumbent_comparator_mcb_id: str = "MCB-L2V3-001",
    l2v3_broken: bool = True,
    incumbent_state: str | None = None,
    incumbent_evidence_override: dict[str, Any] | None = None,
    candidate_arm_override: dict[str, Any] | None = None,
    paired_assay_run_id: str = "PAIRED-HUMORAL-2026-001",
    t1d_sera_panel_ids: list[str] | None = None,
    nk_donor_panel_ids: list[str] | None = None,
    differentiation_batch_ids: list[str] | None = None,
) -> tuple[dict[str, Any], dict[str, dict[str, Any]]]:
    """
    Build a complete, contract-valid Gate 28-B payload + independent trusted-store records
    (binding BOTH candidate & incumbent head-to-head arms and matched assay panel IDs, with
    3-state incumbent adjudication: INCUMBENT_CONCLUSIVELY_BROKEN / INCUMBENT_UNRESOLVED_STRADDLING_CAP /
    INCUMBENT_INTACT_WITHIN_CAPS).
    """
    construct_id = "ABX_L2_v2_CD64T_IL1RN"
    product_track = "CORE_ABX"
    sera_ids = list(t1d_sera_panel_ids) if t1d_sera_panel_ids is not None else [f"SERA-T1D-{i:02d}" for i in range(1, 7)]
    nk_ids = list(nk_donor_panel_ids) if nk_donor_panel_ids is not None else [f"NK-DONOR-{i:02d}" for i in range(1, 4)]
    diff_ids = list(differentiation_batch_ids) if differentiation_batch_ids is not None else [f"DIFF-S7-{i:02d}" for i in range(1, 4)]

    eff_state = (
        incumbent_state
        if incumbent_state is not None
        else ("INCUMBENT_CONCLUSIVELY_BROKEN" if l2v3_broken else "INCUMBENT_INTACT_WITHIN_CAPS")
    )
    if eff_state not in INCUMBENT_ADJUDICATION_STATES:
        raise ValueError(f"Invalid incumbent_state={eff_state!r}; expected one of {sorted(INCUMBENT_ADJUDICATION_STATES)}")

    g0v_rec = build_authenticated_upstream_record(
        gate_id="GATE_0V_WHOLEGRAFT",
        verdict="PASS_WHOLEGRAFT_GATE0V_AND_STRESS_AP1903",
        lot_id=lot_id,
        mcb_id=mcb_id,
        construct_id=construct_id,
        chassis_id=chassis_id,
        product_track=product_track,
        assay_id="GATE0V-WHOLEGRAFT-2026-001",
        evidence_summary={"beta_alpha_delta_iec_pericyte_persistent_vp1_ie1_events": 0, "stressed_ap1903_log10_kill": 4.7},
    )
    s11_rec = build_authenticated_upstream_record(
        gate_id="RULE_S11_MOLECULAR_BATTERY",
        verdict="PASS_RULE_S11_MOLECULAR_BATTERY",
        lot_id=lot_id,
        mcb_id=mcb_id,
        construct_id=construct_id,
        chassis_id=chassis_id,
        product_track=product_track,
        assay_id="RULES11-BATTERY-2026-001",
        evidence_summary={"tp53_ppm1d_bcor_vaf": 0.0, "castseq_translocations": 0, "race_umi_count": 4200},
    )
    t6b_rec = build_authenticated_upstream_record(
        gate_id="GY025_TIER6B_MASTER_LOT_OUTGROWTH",
        verdict="PASS_GY025_TIER6B_MASTER_LOT_OUTGROWTH",
        lot_id=lot_id,
        mcb_id=mcb_id,
        construct_id=construct_id,
        chassis_id=chassis_id,
        product_track=product_track,
        assay_id="GY025-TIER6B-2026-001",
        evidence_summary={"clonogenic_survivors_k": 0, "effective_clonogenic_trials": 300000000},
    )

    if eff_state == "INCUMBENT_CONCLUSIVELY_BROKEN":
        comp_evidence: dict[str, Any] = {
            "incumbent_intact_serum_cd16_adcc_l95_pct": 9.2,
            "incumbent_intact_serum_cd16_adcc_u95_pct": 14.8,
            "incumbent_igg_attributable_cd16_adcc_l95_pct": 7.8,
            "incumbent_igg_attributable_cd16_adcc_u95_pct": 12.6,
            "incumbent_ap_c5b9_l95_pct": 1.9,
            "incumbent_ap_c5b9_u95_pct": 4.1,
            "incumbent_overall_20pct_nhs_l95_pct": 5.4,
            "incumbent_overall_20pct_nhs_u95_pct": 7.9,
            "incumbent_classical_c4b2a_l95_pct": 10.6,
            "incumbent_classical_c4b2a_u95_pct": 15.2,
            "incumbent_lectin_c4b2a_l95_pct": 3.2,
            "incumbent_lectin_c4b2a_u95_pct": 7.4,
        }
    elif eff_state == "INCUMBENT_UNRESOLVED_STRADDLING_CAP":
        comp_evidence = {
            "incumbent_intact_serum_cd16_adcc_l95_pct": 1.8,
            "incumbent_intact_serum_cd16_adcc_u95_pct": 3.4,
            "incumbent_igg_attributable_cd16_adcc_l95_pct": 1.4,
            "incumbent_igg_attributable_cd16_adcc_u95_pct": 2.9,
            "incumbent_ap_c5b9_l95_pct": 1.5,
            "incumbent_ap_c5b9_u95_pct": 3.1,
            "incumbent_overall_20pct_nhs_l95_pct": 2.0,
            "incumbent_overall_20pct_nhs_u95_pct": 3.8,
            "incumbent_classical_c4b2a_l95_pct": 9.0,
            "incumbent_classical_c4b2a_u95_pct": 11.0,
            "incumbent_lectin_c4b2a_l95_pct": 3.0,
            "incumbent_lectin_c4b2a_u95_pct": 7.2,
        }
    else:
        comp_evidence = {
            "incumbent_intact_serum_cd16_adcc_l95_pct": 1.8,
            "incumbent_intact_serum_cd16_adcc_u95_pct": 3.4,
            "incumbent_igg_attributable_cd16_adcc_l95_pct": 1.4,
            "incumbent_igg_attributable_cd16_adcc_u95_pct": 2.9,
            "incumbent_ap_c5b9_l95_pct": 1.5,
            "incumbent_ap_c5b9_u95_pct": 3.1,
            "incumbent_overall_20pct_nhs_l95_pct": 2.0,
            "incumbent_overall_20pct_nhs_u95_pct": 3.8,
            "incumbent_classical_c4b2a_l95_pct": 3.8,
            "incumbent_classical_c4b2a_u95_pct": 8.1,
            "incumbent_lectin_c4b2a_l95_pct": 3.0,
            "incumbent_lectin_c4b2a_u95_pct": 7.2,
        }
    if incumbent_evidence_override:
        comp_evidence.update(incumbent_evidence_override)

    cand_arm: dict[str, Any] = {
        "copy1_monoallelic": {
            "intact_serum_cd16_adcc_u95_pct": 3.8,
            "igg_attributable_cd16_adcc_u95_pct": 3.1,
            "ap_c5b9_u95_pct": 3.4,
            "overall_20pct_nhs_u95_pct": 4.1,
        },
        "copy2_biallelic": {
            "intact_serum_cd16_adcc_u95_pct": 2.9,
            "igg_attributable_cd16_adcc_u95_pct": 2.4,
            "ap_c5b9_u95_pct": 2.8,
            "overall_20pct_nhs_u95_pct": 3.2,
        },
        "classical_c4b2a_l95_pct": 4.2,
        "classical_c4b2a_u95_pct": 8.6,
        "lectin_c4b2a_l95_pct": 3.5,
        "lectin_c4b2a_u95_pct": 7.9,
    }
    if candidate_arm_override:
        for k_ov, v_ov in candidate_arm_override.items():
            if k_ov in ("copy1_monoallelic", "copy2_biallelic") and isinstance(v_ov, dict):
                cand_arm[k_ov].update(v_ov)
            else:
                cand_arm[k_ov] = v_ov

    comp_rec = build_authenticated_paired_comparator_record(
        candidate_construct_id=construct_id,
        candidate_lot_id=lot_id,
        candidate_mcb_id=mcb_id,
        chassis_id=chassis_id,
        incumbent_comparator_construct_id=incumbent_comparator_construct_id,
        incumbent_comparator_lot_id=incumbent_comparator_lot_id,
        incumbent_comparator_mcb_id=incumbent_comparator_mcb_id,
        paired_assay_run_id=paired_assay_run_id,
        evidence_summary=comp_evidence,
        candidate_arm_evidence=cand_arm,
        t1d_sera_panel_ids=sera_ids,
        nk_donor_panel_ids=nk_ids,
        differentiation_batch_ids=diff_ids,
    )

    records_map = {
        "gate0v_record": g0v_rec,
        "rule_s11_record": s11_rec,
        "gy025_tier6b_record": t6b_rec,
        "paired_comparator_record": comp_rec,
    }
    if store_path is not None:
        write_gate28b_trusted_qualification_store(
            store_path,
            upstream_records=[g0v_rec, s11_rec, t6b_rec],
            paired_comparator_records=[comp_rec],
        )

    payload: dict[str, Any] = {
        "product_track": product_track,
        "chassis_id": chassis_id,
        "construct_id": construct_id,
        "product_variant_id": construct_id,
        "lot_id": lot_id,
        "mcb_id": mcb_id,
        "incumbent_comparator_construct_id": incumbent_comparator_construct_id,
        "incumbent_comparator_lot_id": incumbent_comparator_lot_id,
        "paired_assay_run_id": paired_assay_run_id,
        "t1d_sera_panel_ids": list(sera_ids),
        "nk_donor_panel_ids": list(nk_ids),
        "differentiation_batch_ids": list(diff_ids),
        "panel_digest": comp_rec["panel_digest"],
        "zygosity": "MONOALLELIC_1COPY_HDR_KO",
        "clones_screened_n": 48,
        "gmp_aav6_locus2_donor_families_n": 1,
        "copy1_monoallelic": {
            "quantibrite_t0_molecules_per_cell": 72000.0,
            "quantibrite_day90_molecules_per_cell": 61000.0,
            "t0_mfi": 7200.0,
            "day90_mfi": 6100.0,
            "day90_mfi_retention_pct_vs_t0": 84.7,
            **cand_arm["copy1_monoallelic"],
            "post_7day_10mgml_igg_preload_functional_pass": True,
        },
        "copy2_biallelic": {
            "quantibrite_t0_molecules_per_cell": 135000.0,
            "quantibrite_day90_molecules_per_cell": 115000.0,
            "t0_mfi": 13500.0,
            "day90_mfi": 11500.0,
            "day90_mfi_retention_pct_vs_t0": 85.2,
            **cand_arm["copy2_biallelic"],
            "post_7day_10mgml_igg_preload_functional_pass": True,
        },
        "independent_t1d_sera_n": len(sera_ids),
        "independent_nk_donors_n": len(nk_ids),
        "independent_differentiations_n": len(diff_ids),
        "fcr_gamma_coip_and_phospho_syk_negative": True,
        "cd274p_il1rn_ifn_titration_matrix_passed": True,
        "il1rn_to_il1b_molar_excess": 125.0,
        "il1rn_basal_leak_pct_of_induced": 2.4,
        "dynamic_gsis_retention_pct_of_ctrl": 94.5,
        "ap1903_icasp9_ablation_pct": 99.6,
        "classical_c4b2a_l95_pct": cand_arm["classical_c4b2a_l95_pct"],
        "classical_c4b2a_u95_pct": cand_arm["classical_c4b2a_u95_pct"],
        "lectin_c4b2a_l95_pct": cand_arm["lectin_c4b2a_l95_pct"],
        "lectin_c4b2a_u95_pct": cand_arm["lectin_c4b2a_u95_pct"],
        "exact_stack_efferocytosis_abs_pct": 84.0,
        "exact_stack_efferocytosis_pct_of_wt": 78.0,
        "iec_morphogenesis_t50_h": 28.0,
        "iec_viability_pct": 91.0,
        "gate0g_pericyte_pct": 76.0,
        "gate0v_viral_safety_passed": True,
        "rule_s11_molecular_battery_passed": True,
        "gy025_tier6b_master_lot_outgrowth_passed": True,
        "upstream_record_refs": {
            "gate0v_record_sha256": g0v_rec["record_sha256"],
            "rule_s11_record_sha256": s11_rec["record_sha256"],
            "gy025_tier6b_record_sha256": t6b_rec["record_sha256"],
            "paired_comparator_record_sha256": comp_rec["record_sha256"],
        },
    }
    if comp_rec["incumbent_adjudication_state"] == "INCUMBENT_CONCLUSIVELY_BROKEN":
        payload["l2v3_broken_by_t1d_sera_gt_5pct"] = True
    elif comp_rec["incumbent_adjudication_state"] == "INCUMBENT_INTACT_WITHIN_CAPS":
        payload["l2v3_broken_by_t1d_sera_gt_5pct"] = False
    return payload, records_map


def build_valid_gate28b_reference_payload(
    *,
    lot_id: str = "LOT-ABX-2026-001",
    mcb_id: str = "MCB-ISLET1A-001",
    chassis_id: str = "ISLET1_A",
    incumbent_comparator_construct_id: str = "L2_V3_CO_PRIMARY_CD200",
    incumbent_comparator_lot_id: str = "LOT-L2V3-2026-001",
    l2v3_broken: bool = True,
) -> dict[str, Any]:
    """Convenience wrapper returning the Gate 28-B reference payload (requires trusted_qualification_store for full authorization)."""
    payload, _ = build_valid_gate28b_reference_bundle(
        store_path=None,
        lot_id=lot_id,
        mcb_id=mcb_id,
        chassis_id=chassis_id,
        incumbent_comparator_construct_id=incumbent_comparator_construct_id,
        incumbent_comparator_lot_id=incumbent_comparator_lot_id,
        l2v3_broken=l2v3_broken,
    )
    return payload


def _run_locus2_arbitration_unit_tests() -> dict[str, Any]:
    cases: list[dict[str, Any]] = []

    with tempfile.TemporaryDirectory(prefix="openislet_g28b_test_") as td:
        td_path = pathlib.Path(td)
        store_json = td_path / "trusted_qualification_store.json"
        store_dir = td_path / "trusted_store_dir"

        base_full_pass, base_recs = build_valid_gate28b_reference_bundle(store_path=store_json, l2v3_broken=True)
        # Also populate directory-layout store for directory resolution check
        write_gate28b_trusted_qualification_store(
            store_dir,
            upstream_records=[base_recs["gate0v_record"], base_recs["rule_s11_record"], base_recs["gy025_tier6b_record"]],
            paired_comparator_records=[base_recs["paired_comparator_record"]],
        )
        # Also write retain-incumbent paired comparator record into store_json
        retain_payload, _ = build_valid_gate28b_reference_bundle(store_path=store_json, l2v3_broken=False)

        def _check_case(
            name: str,
            payload: dict[str, Any],
            expected_status: str,
            expected_auth: bool,
            *,
            store: pathlib.Path | str | None = store_json,
            sc_path: pathlib.Path | None = None,
            expected_lead_auth: bool | None = None,
            expected_arb_closed: bool | None = None,
            expected_inc_retained: bool | None = None,
            expected_pin_verified: bool | None = True,
        ) -> None:
            res = evaluate_ciita_locus2_arbitration(
                payload,
                side_contract_path=sc_path,
                trusted_qualification_store=store,
            )
            lead_exp = expected_auth if expected_lead_auth is None else expected_lead_auth
            if res["status"] != expected_status or res["full_promotion_authorized"] is not expected_auth:
                raise ValueError(
                    f"Arbitration unit test {name} failed: got status={res['status']!r}, "
                    f"auth={res['full_promotion_authorized']!r} (expected {expected_status!r}, {expected_auth!r}); "
                    f"reasons={res.get('reasons')}"
                )
            if res["lead_promotion_authorized"] is not lead_exp:
                raise ValueError(
                    f"Arbitration unit test {name} lead_promotion_authorized={res['lead_promotion_authorized']!r} != {lead_exp!r}"
                )
            if expected_arb_closed is not None and res["arbitration_closed"] is not expected_arb_closed:
                raise ValueError(f"Arbitration unit test {name} arbitration_closed mismatch: {res['arbitration_closed']!r}")
            if expected_inc_retained is not None and res["incumbent_retained"] is not expected_inc_retained:
                raise ValueError(f"Arbitration unit test {name} incumbent_retained mismatch: {res['incumbent_retained']!r}")
            if expected_pin_verified is not None and res["policy_pin_verified"] is not expected_pin_verified:
                raise ValueError(f"Arbitration unit test {name} policy_pin_verified mismatch: {res['policy_pin_verified']!r}")
            cases.append({
                "case": name,
                "status": res["status"],
                "full_promotion_authorized": res["full_promotion_authorized"],
                "lead_promotion_authorized": res["lead_promotion_authorized"],
                "arbitration_closed": res["arbitration_closed"],
                "incumbent_retained": res["incumbent_retained"],
                "policy_pin_verified": res["policy_pin_verified"],
                "pending_full_qualification_fields": res["pending_full_qualification_fields"],
                "passed": True,
            })

        # 1. Full qualification via independent JSON registry store promotes winner
        _check_case(
            "full_qualification_pass_promotes_winner",
            base_full_pass,
            "PASS_FULL_GY025_AND_GATE28B_PROMOTE",
            True,
            expected_lead_auth=True,
            expected_arb_closed=True,
            expected_inc_retained=False,
        )

        # 2. Full qualification via independent directory store promotes winner
        _check_case(
            "full_qualification_dir_store_promotes_winner",
            base_full_pass,
            "PASS_FULL_GY025_AND_GATE28B_PROMOTE",
            True,
            store=store_dir,
            expected_lead_auth=True,
            expected_arb_closed=True,
            expected_inc_retained=False,
        )

        # 3. Full qualification with incumbent L2_V3 holding quantitatively retains incumbent with lead_promotion_authorized=False! (M4)
        _check_case(
            "full_qualification_retain_incumbent_l2v3",
            retain_payload,
            "PASS_FULL_GY025_AND_GATE28B_RETAIN_L2V3",
            False,
            expected_lead_auth=False,
            expected_arb_closed=True,
            expected_inc_retained=True,
        )

        # 4. Self-attested inline records WITHOUT trusted_qualification_store NEVER authorize promotion! (B3)
        p_self_attest = copy.deepcopy(base_full_pass)
        p_self_attest["upstream_qualification_records"] = {
            "gate0v_record": base_recs["gate0v_record"],
            "rule_s11_record": base_recs["rule_s11_record"],
            "gy025_tier6b_record": base_recs["gy025_tier6b_record"],
        }
        p_self_attest["paired_comparator_record"] = base_recs["paired_comparator_record"]
        _check_case(
            "self_attested_inline_records_without_trusted_store_capped",
            p_self_attest,
            "COMPONENT_PASS_CIITA_ARBITRATION_ONLY_PENDING_FULL_GY025",
            False,
            store=None,
        )

        # 5. Bare caller boolean l2v3_broken=True WITHOUT trusted paired comparator record capped! (B3)
        p_no_comp = copy.deepcopy(base_full_pass)
        p_no_comp["upstream_record_refs"].pop("paired_comparator_record_sha256")
        _check_case(
            "bare_caller_l2v3_boolean_without_trusted_paired_comparator_capped",
            p_no_comp,
            "COMPONENT_PASS_CIITA_ARBITRATION_ONLY_PENDING_FULL_GY025",
            False,
        )

        # 6. Caller l2v3_broken=True contradicting trusted quantitative comparator (L2_V3 held) fails closed! (B3)
        p_comp_contra = copy.deepcopy(retain_payload)
        p_comp_contra["l2v3_broken_by_t1d_sera_gt_5pct"] = True
        _check_case(
            "caller_l2v3_flag_contradicting_trusted_quantitative_comparator_rejected",
            p_comp_contra,
            "FAIL_OR_PENDING",
            False,
        )

        # 7. Unauthorized issuer_authority_id in trusted store rejected fail-closed! (B3)
        bad_issuer_store = td_path / "bad_issuer_store.json"
        bad_g0v = build_authenticated_upstream_record(
            gate_id="GATE_0V_WHOLEGRAFT",
            verdict="PASS_WHOLEGRAFT_GATE0V_AND_STRESS_AP1903",
            lot_id=base_full_pass["lot_id"],
            mcb_id=base_full_pass["mcb_id"],
            construct_id=base_full_pass["construct_id"],
            chassis_id=base_full_pass["chassis_id"],
            issuer_authority_id="UNTRUSTED_SELF_ISSUER_X",
            evidence_summary={"beta_alpha_delta_iec_pericyte_persistent_vp1_ie1_events": 0},
        )
        write_gate28b_trusted_qualification_store(
            bad_issuer_store,
            upstream_records=[bad_g0v, base_recs["rule_s11_record"], base_recs["gy025_tier6b_record"]],
            paired_comparator_records=[base_recs["paired_comparator_record"]],
        )
        p_bad_iss = copy.deepcopy(base_full_pass)
        p_bad_iss["upstream_record_refs"]["gate0v_record_sha256"] = bad_g0v["record_sha256"]
        _check_case(
            "untrusted_issuer_authority_in_store_rejected",
            p_bad_iss,
            "FAIL_OR_PENDING",
            False,
            store=bad_issuer_store,
        )

        # 8. Alternate / mutated side-contract policy file CANNOT authorize promotion! (B4)
        alt_sc = td_path / "mutated_side_contract.json"
        sc_orig = load_strict_json_bytes((OPENISLET_ROOT / PINNED_SIDE_CONTRACT_REL).read_bytes(), "orig_sc")
        sc_orig["executable_stage0_gates"]["Gate_28_B"]["promotion_eligible_construct_ids"].append("UNAUTHORIZED_MUTANT_LEAD")
        alt_sc.write_text(json.dumps(sc_orig, indent=2) + "\n", encoding="utf-8")
        _check_case(
            "mutated_alternate_side_contract_non_authorizing_diagnostic",
            base_full_pass,
            "NON_AUTHORIZING_UNPINNED_POLICY_DIAGNOSTIC",
            False,
            sc_path=alt_sc,
            expected_pin_verified=False,
        )

        # 9. Whitespace-padded construct_id and lot_id fail closed (zero silent stripping!) (M4)
        p_ws_cid = copy.deepcopy(base_full_pass)
        p_ws_cid["construct_id"] = " ABX_L2_v2_CD64T_IL1RN "
        _check_case("whitespace_padded_construct_id_rejected", p_ws_cid, "FAIL_HARD_STOP", False)

        p_ws_lot = copy.deepcopy(base_full_pass)
        p_ws_lot["lot_id"] = "LOT-ABX-2026-001 "
        _check_case("whitespace_padded_lot_id_rejected", p_ws_lot, "FAIL_OR_PENDING", False)

        # 10. Missing raw t0_mfi/day90_mfi and contradictory Day-90 MFI retention fail closed! (M4)
        p_no_mfi = copy.deepcopy(base_full_pass)
        p_no_mfi["copy1_monoallelic"].pop("t0_mfi")
        _check_case("missing_raw_t0_mfi_rejected", p_no_mfi, "FAIL_OR_PENDING", False)

        p_bad_ret = copy.deepcopy(base_full_pass)
        p_bad_ret["copy1_monoallelic"]["day90_mfi_retention_pct_vs_t0"] = 99.0  # contradicts 6100/7200 = 84.72%!
        _check_case("contradictory_day90_mfi_retention_rejected", p_bad_ret, "FAIL_OR_PENDING", False)

        # 11. Component-only pass (missing full GY-025 physical fields & refs) does NOT authorize promotion
        p_comp = copy.deepcopy(base_full_pass)
        for k in (
            "exact_stack_efferocytosis_abs_pct", "exact_stack_efferocytosis_pct_of_wt",
            "iec_morphogenesis_t50_h", "iec_viability_pct", "gate0g_pericyte_pct",
            "gate0v_viral_safety_passed", "rule_s11_molecular_battery_passed",
            "gy025_tier6b_master_lot_outgrowth_passed", "upstream_record_refs",
        ):
            p_comp.pop(k)
        _check_case(
            "partial_component_only_pending_full_gy025",
            p_comp,
            "COMPONENT_PASS_CIITA_ARBITRATION_ONLY_PENDING_FULL_GY025",
            False,
        )

        # 12. Summary-flag-only run (bare booleans True WITHOUT trusted-store refs) stays strictly capped!
        p_sum_only = copy.deepcopy(base_full_pass)
        p_sum_only.pop("upstream_record_refs")
        _check_case(
            "summary_flags_only_without_trusted_store_refs_capped_at_component",
            p_sum_only,
            "COMPONENT_PASS_CIITA_ARBITRATION_ONLY_PENDING_FULL_GY025",
            False,
        )

        # 13. Mismatched lot_id on trusted-store Gate 0V record rejected fail-closed
        mis_lot_store = td_path / "mis_lot_store.json"
        mis_g0v = build_authenticated_upstream_record(
            gate_id="GATE_0V_WHOLEGRAFT",
            verdict="PASS_WHOLEGRAFT_GATE0V_AND_STRESS_AP1903",
            lot_id="LOT-DIFFERENT-999",
            mcb_id=base_full_pass["mcb_id"],
            construct_id=base_full_pass["construct_id"],
            chassis_id=base_full_pass["chassis_id"],
            evidence_summary={"beta_alpha_delta_iec_pericyte_persistent_vp1_ie1_events": 0},
        )
        write_gate28b_trusted_qualification_store(
            mis_lot_store,
            upstream_records=[mis_g0v, base_recs["rule_s11_record"], base_recs["gy025_tier6b_record"]],
            paired_comparator_records=[base_recs["paired_comparator_record"]],
        )
        p_lot_mis = copy.deepcopy(base_full_pass)
        p_lot_mis["upstream_record_refs"]["gate0v_record_sha256"] = mis_g0v["record_sha256"]
        _check_case("mismatched_lot_upstream_gate0v_record_rejected", p_lot_mis, "FAIL_OR_PENDING", False, store=mis_lot_store)

        # 14. Tampered record_sha256 reference rejected fail-closed
        p_tamp = copy.deepcopy(base_full_pass)
        orig_h = p_tamp["upstream_record_refs"]["rule_s11_record_sha256"]
        p_tamp["upstream_record_refs"]["rule_s11_record_sha256"] = ("0" if orig_h[0] != "0" else "1") + orig_h[1:]
        _check_case("tampered_upstream_record_sha256_rejected", p_tamp, "FAIL_OR_PENDING", False)

        # 15. Single complement interval only (lectin omitted) rejected fail-closed per owning GY-025
        p_no_lectin = copy.deepcopy(base_full_pass)
        p_no_lectin.pop("lectin_c4b2a_l95_pct")
        p_no_lectin.pop("lectin_c4b2a_u95_pct")
        _check_case("missing_lectin_c4b2a_interval_rejected", p_no_lectin, "FAIL_OR_PENDING", False)

        # 16. Classical C4b2a HOLD inconclusive band (L95<=10 < U95) with matched paired head-to-head record!
        p_cl_hold, _ = build_valid_gate28b_reference_bundle(
            store_path=store_json,
            l2v3_broken=True,
            candidate_arm_override={"classical_c4b2a_l95_pct": 7.5, "classical_c4b2a_u95_pct": 12.4},
        )
        _check_case("classical_c4b2a_inconclusive_hold_band", p_cl_hold, "HOLD_UNDERPOWERED_EXPAND_N", False)

        # 17. Lectin C4b2a HOLD inconclusive band (L95<=10 < U95) while classical passes, with matched paired head-to-head record!
        p_lec_hold, _ = build_valid_gate28b_reference_bundle(
            store_path=store_json,
            l2v3_broken=True,
            candidate_arm_override={"lectin_c4b2a_l95_pct": 6.8, "lectin_c4b2a_u95_pct": 11.9},
        )
        _check_case("lectin_c4b2a_inconclusive_hold_band", p_lec_hold, "HOLD_UNDERPOWERED_EXPAND_N", False)

        # 18. Track-2 B'-SCT blocked
        p_tr2 = copy.deepcopy(base_full_pass)
        p_tr2["product_track"] = "TRACK_2_B_PRIME_SCT"
        _check_case("track2_b_prime_sct_blocked", p_tr2, "FAIL_HARD_STOP", False)

        # 19. Non-Core track (e.g. autologous D1b) blocked fail-closed
        p_noncore = copy.deepcopy(base_full_pass)
        p_noncore["product_track"] = "AUTOLOGOUS_D1B_AUTO_C_V2"
        _check_case("non_core_track_autologous_d1b_blocked", p_noncore, "FAIL_HARD_STOP", False)

        # 20. Archived CD46_WT hold comparator blocked
        p_cd46 = copy.deepcopy(base_full_pass)
        p_cd46["construct_id"] = "ABX_L2_v2_CD64T_CD46WT_COMP"
        p_cd46["cand034_cd46_tropic_addendum_cleared"] = False
        _check_case("cd46wt_archived_hold_blocked", p_cd46, "HOLD_BLOCKED", False)

        # 21. Tertiary CFH-CD55 hold comparator blocked
        p_cfh = copy.deepcopy(base_full_pass)
        p_cfh["construct_id"] = "ABX_L2_v2_CD64T_CFH_CD55_COMP"
        _check_case("tertiary_cfh_cd55_hold_blocked", p_cfh, "HOLD_BLOCKED", False)

        # 22. Single-cargo attribution control ABX_L2_v2_CTRL_CD64T_ONLY non-promotable
        p_ctrl_full = copy.deepcopy(base_full_pass)
        p_ctrl_full["construct_id"] = "ABX_L2_v2_CTRL_CD64T_ONLY"
        _check_case("single_cargo_control_cd64t_only_non_promotable", p_ctrl_full, "CONTROL_ATTRIBUTION_ONLY_NON_PROMOTABLE", False)

        # 23. Short control alias CTRL_CD64T_ONLY non-promotable
        p_ctrl_short = copy.deepcopy(base_full_pass)
        p_ctrl_short["construct_id"] = "CTRL_CD64T_ONLY"
        _check_case("short_alias_control_ctrl_cd64t_only_non_promotable", p_ctrl_short, "CONTROL_ATTRIBUTION_ONLY_NON_PROMOTABLE", False)

        # 24. Absent construct_id blocked fail-closed
        p_no_cid = copy.deepcopy(base_full_pass)
        p_no_cid.pop("construct_id")
        _check_case("absent_construct_id_blocked", p_no_cid, "FAIL_HARD_STOP", False)

        # 25. Chassis-mismatched incumbent comparator rejected (ISLET1_B with A/X comparator)
        p_comp_mis = copy.deepcopy(base_full_pass)
        p_comp_mis["chassis_id"] = "ISLET1_B"
        _check_case("mismatched_incumbent_comparator_for_chassis_rejected", p_comp_mis, "FAIL_OR_PENDING", False)

        # 26. Only 2-copy passes (1-copy fails density) -> manufacturing fail
        p_1c = copy.deepcopy(base_full_pass)
        p_1c["copy1_monoallelic"]["quantibrite_t0_molecules_per_cell"] = 22000.0
        _check_case("monoallelic_1copy_fail_blocks_promotion", p_1c, "FAIL_OR_PENDING", False)

        # 27. Pending FcRgamma co-IP blocks promotion
        p_fcr = copy.deepcopy(base_full_pass)
        p_fcr["fcr_gamma_coip_and_phospho_syk_negative"] = False
        _check_case("pending_fcr_gamma_blocks_promotion", p_fcr, "FAIL_OR_PENDING", False)

        # 28. Explicit Gate 0V failure blocks promotion even when all CIITA/humoral checks pass
        p_g0v = copy.deepcopy(base_full_pass)
        p_g0v["gate0v_viral_safety_passed"] = False
        _check_case("failed_gate0v_blocks_promotion", p_g0v, "FAIL_OR_PENDING", False)

        # 29. Negative intact-serum ADCC U95 rejected
        p_neg_adcc = copy.deepcopy(base_full_pass)
        p_neg_adcc["copy1_monoallelic"]["intact_serum_cd16_adcc_u95_pct"] = -1.5
        _check_case("negative_intact_adcc_u95_rejected", p_neg_adcc, "FAIL_OR_PENDING", False)

        # 30. Out-of-domain ADCC U95 > 100 rejected
        p_hi_adcc = copy.deepcopy(base_full_pass)
        p_hi_adcc["copy2_biallelic"]["intact_serum_cd16_adcc_u95_pct"] = 104.0
        _check_case("adcc_u95_over_100_rejected", p_hi_adcc, "FAIL_OR_PENDING", False)

        # 31. Negative iEC morphogenesis time rejected
        p_neg_t50 = copy.deepcopy(base_full_pass)
        p_neg_t50["iec_morphogenesis_t50_h"] = -5.0
        _check_case("negative_iec_morphogenesis_t50_rejected", p_neg_t50, "FAIL_OR_PENDING", False)

        # 32. Omitted clone count rejected (no permissive default)
        p_no_clones = copy.deepcopy(base_full_pass)
        p_no_clones.pop("clones_screened_n")
        _check_case("omitted_clone_count_rejected", p_no_clones, "FAIL_OR_PENDING", False)

        # 33. Omitted donor-family count rejected (no permissive default)
        p_no_fam = copy.deepcopy(base_full_pass)
        p_no_fam.pop("gmp_aav6_locus2_donor_families_n")
        _check_case("omitted_donor_family_count_rejected", p_no_fam, "FAIL_OR_PENDING", False)

        # 34. Fractional clone count 96.9 rejected (strict int required)
        p_frac_clone = copy.deepcopy(base_full_pass)
        p_frac_clone["clones_screened_n"] = 96.9
        _check_case("fractional_clone_count_96p9_rejected", p_frac_clone, "FAIL_OR_PENDING", False)

        # 35. Non-boolean string for l2v3_broken_by_t1d_sera_gt_5pct rejected (no truthy coercion)
        p_str_bool = copy.deepcopy(base_full_pass)
        p_str_bool["l2v3_broken_by_t1d_sera_gt_5pct"] = "unknown"
        _check_case("non_bool_string_l2v3_broken_rejected", p_str_bool, "FAIL_OR_PENDING", False)

        # 36. Missing quantitative IL-1Ra:IL-1beta molar excess rejected
        p_no_il1ra = copy.deepcopy(base_full_pass)
        p_no_il1ra.pop("il1rn_to_il1b_molar_excess")
        _check_case("missing_il1rn_molar_excess_rejected", p_no_il1ra, "FAIL_OR_PENDING", False)

        # 37. Missing quantitative IL-1Ra basal leak rejected
        p_no_leak = copy.deepcopy(base_full_pass)
        p_no_leak.pop("il1rn_basal_leak_pct_of_induced")
        _check_case("missing_il1rn_basal_leak_rejected", p_no_leak, "FAIL_OR_PENDING", False)

        # 38. Missing quantitative dynamic GSIS retention rejected
        p_no_gsis = copy.deepcopy(base_full_pass)
        p_no_gsis.pop("dynamic_gsis_retention_pct_of_ctrl")
        _check_case("missing_dynamic_gsis_rejected", p_no_gsis, "FAIL_OR_PENDING", False)

        # 39. Missing quantitative AP1903 ablation rejected
        p_no_ap = copy.deepcopy(base_full_pass)
        p_no_ap.pop("ap1903_icasp9_ablation_pct")
        _check_case("missing_ap1903_ablation_rejected", p_no_ap, "FAIL_OR_PENDING", False)

        # 40. Boolean passed as integer count rejected (True is bool, not exact int)
        p_bool_cnt = copy.deepcopy(base_full_pass)
        p_bool_cnt["clones_screened_n"] = True
        _check_case("bool_count_rejected", p_bool_cnt, "FAIL_OR_PENDING", False)

        # 41. Missing/empty evidence_summary in trusted store record rejected fail-closed (B3)
        empty_ev_store = td_path / "empty_ev_store.json"
        tampered_s11 = copy.deepcopy(base_recs["rule_s11_record"])
        tampered_s11["evidence_summary"] = {}
        tampered_s11["record_sha256"] = compute_upstream_record_sha256(tampered_s11)
        write_gate28b_trusted_qualification_store(
            empty_ev_store,
            upstream_records=[base_recs["gate0v_record"], tampered_s11, base_recs["gy025_tier6b_record"]],
            paired_comparator_records=[base_recs["paired_comparator_record"]],
        )
        p_empty_ev = copy.deepcopy(base_full_pass)
        p_empty_ev["upstream_record_refs"]["rule_s11_record_sha256"] = tampered_s11["record_sha256"]
        _check_case("empty_evidence_summary_in_trusted_store_rejected", p_empty_ev, "FAIL_OR_PENDING", False, store=empty_ev_store)

        # 42. Quantitative paired comparator omitted (l2v3_broken omitted too) with valid store promotes cleanly from store!
        p_store_only_comp = copy.deepcopy(base_full_pass)
        p_store_only_comp.pop("l2v3_broken_by_t1d_sera_gt_5pct")
        _check_case(
            "trusted_quantitative_paired_comparator_authorizes_without_caller_boolean",
            p_store_only_comp,
            "PASS_FULL_GY025_AND_GATE28B_PROMOTE",
            True,
            expected_lead_auth=True,
            expected_arb_closed=True,
            expected_inc_retained=False,
        )

        # --- R05 B3: Head-to-head paired assay run, panel ID, and candidate-arm quantitative reconciliation ---
        # 43. Missing paired_assay_run_id fails closed
        p_no_run = copy.deepcopy(base_full_pass)
        p_no_run.pop("paired_assay_run_id")
        _check_case("b3_missing_paired_assay_run_id_rejected", p_no_run, "FAIL_OR_PENDING", False)

        # 44. Mismatched paired_assay_run_id fails closed
        p_mis_run = copy.deepcopy(base_full_pass)
        p_mis_run["paired_assay_run_id"] = "PAIRED-DIFFERENT-RUN-999"
        _check_case("b3_mismatched_paired_assay_run_id_rejected", p_mis_run, "FAIL_OR_PENDING", False)

        # 45. Mismatched T1D sera panel IDs fails closed
        p_mis_sera = copy.deepcopy(base_full_pass)
        p_mis_sera["t1d_sera_panel_ids"][-1] = "SERA-T1D-UNMATCHED-99"
        p_mis_sera["panel_digest"] = compute_paired_assay_panel_digest(
            p_mis_sera["paired_assay_run_id"], p_mis_sera["t1d_sera_panel_ids"],
            p_mis_sera["nk_donor_panel_ids"], p_mis_sera["differentiation_batch_ids"],
        )
        _check_case("b3_mismatched_t1d_sera_panel_ids_rejected", p_mis_sera, "FAIL_OR_PENDING", False)

        # 46. Mismatched NK donor panel IDs fails closed
        p_mis_nk = copy.deepcopy(base_full_pass)
        p_mis_nk["nk_donor_panel_ids"][0] = "NK-DONOR-OTHER-99"
        p_mis_nk["panel_digest"] = compute_paired_assay_panel_digest(
            p_mis_nk["paired_assay_run_id"], p_mis_nk["t1d_sera_panel_ids"],
            p_mis_nk["nk_donor_panel_ids"], p_mis_nk["differentiation_batch_ids"],
        )
        _check_case("b3_mismatched_nk_donor_panel_ids_rejected", p_mis_nk, "FAIL_OR_PENDING", False)

        # 47. Mismatched differentiation batch IDs fails closed
        p_mis_diff = copy.deepcopy(base_full_pass)
        p_mis_diff["differentiation_batch_ids"][0] = "DIFF-S7-OTHER-99"
        p_mis_diff["panel_digest"] = compute_paired_assay_panel_digest(
            p_mis_diff["paired_assay_run_id"], p_mis_diff["t1d_sera_panel_ids"],
            p_mis_diff["nk_donor_panel_ids"], p_mis_diff["differentiation_batch_ids"],
        )
        _check_case("b3_mismatched_differentiation_batch_ids_rejected", p_mis_diff, "FAIL_OR_PENDING", False)

        # 48. Candidate copy1 ADCC value still <= 5.0% BUT disagrees with trusted paired head-to-head record -> fails closed!
        p_mis_cand_adcc = copy.deepcopy(base_full_pass)
        p_mis_cand_adcc["copy1_monoallelic"]["intact_serum_cd16_adcc_u95_pct"] = 3.9
        _check_case("b3_mismatched_candidate_copy1_adcc_vs_paired_record_rejected", p_mis_cand_adcc, "FAIL_OR_PENDING", False)

        # 49. Candidate classical C4b2a still <= 10.0% BUT disagrees with trusted paired head-to-head record -> fails closed!
        p_mis_cand_c4 = copy.deepcopy(base_full_pass)
        p_mis_cand_c4["classical_c4b2a_u95_pct"] = 8.7
        _check_case("b3_mismatched_candidate_classical_c4b2a_vs_paired_record_rejected", p_mis_cand_c4, "FAIL_OR_PENDING", False)

        # --- R05 B4: 3-state incumbent adjudication (uncertainty straddling cap != broken!) ---
        # 50. Incumbent classical C4b2a [9%, 11%] straddling 10% cap -> HOLD_INCUMBENT_COMPARATOR_UNRESOLVED!
        p_inc_strad_c4, _ = build_valid_gate28b_reference_bundle(
            store_path=store_json,
            incumbent_state="INCUMBENT_UNRESOLVED_STRADDLING_CAP",
            paired_assay_run_id="PAIRED-STRADDLE-C4-001",
        )
        _check_case(
            "b4_incumbent_straddling_classical_c4b2a_9_to_11_hold_unresolved",
            p_inc_strad_c4,
            "HOLD_INCUMBENT_COMPARATOR_UNRESOLVED",
            False,
            expected_lead_auth=False,
            expected_arb_closed=False,
            expected_inc_retained=False,
        )

        # 51. Incumbent intact ADCC [4%, 6%] straddling 5% cap (all other endpoints intact) -> HOLD_INCUMBENT_COMPARATOR_UNRESOLVED!
        p_inc_strad_adcc, _ = build_valid_gate28b_reference_bundle(
            store_path=store_json,
            incumbent_state="INCUMBENT_INTACT_WITHIN_CAPS",
            incumbent_evidence_override={
                "incumbent_intact_serum_cd16_adcc_l95_pct": 4.0,
                "incumbent_intact_serum_cd16_adcc_u95_pct": 6.0,
            },
            paired_assay_run_id="PAIRED-STRADDLE-ADCC-001",
        )
        _check_case(
            "b4_incumbent_straddling_adcc_4_to_6_hold_unresolved",
            p_inc_strad_adcc,
            "HOLD_INCUMBENT_COMPARATOR_UNRESOLVED",
            False,
            expected_lead_auth=False,
            expected_arb_closed=False,
            expected_inc_retained=False,
        )

        # 52. Incumbent classical C4b2a [10.5%, 14.0%] (L95 > 10.0%) conclusively broken -> PROMOTE!
        p_inc_broken_c4, _ = build_valid_gate28b_reference_bundle(
            store_path=store_json,
            incumbent_state="INCUMBENT_INTACT_WITHIN_CAPS",
            incumbent_evidence_override={
                "incumbent_classical_c4b2a_l95_pct": 10.5,
                "incumbent_classical_c4b2a_u95_pct": 14.0,
            },
            paired_assay_run_id="PAIRED-BROKEN-C4-001",
        )
        _check_case(
            "b4_incumbent_conclusively_broken_classical_l95_gt_10_promotes",
            p_inc_broken_c4,
            "PASS_FULL_GY025_AND_GATE28B_PROMOTE",
            True,
            expected_lead_auth=True,
            expected_arb_closed=True,
            expected_inc_retained=False,
        )

        # --- R05 B5: Context-independent exact Day-90 MFI retention boundary under prec=4 AND prec=28 ---
        # 53. Below-75% boundary (74.999 / 100 and 74999 / 100000) FAILS identically under BOTH prec=4 and prec=28!
        p_mfi_low = copy.deepcopy(base_full_pass)
        p_mfi_low["copy1_monoallelic"]["t0_mfi"] = Decimal("100")
        p_mfi_low["copy1_monoallelic"]["day90_mfi"] = Decimal("74.999")
        p_mfi_low["copy1_monoallelic"].pop("day90_mfi_retention_pct_vs_t0", None)
        p_mfi_low_int = copy.deepcopy(base_full_pass)
        p_mfi_low_int["copy1_monoallelic"]["t0_mfi"] = 100000
        p_mfi_low_int["copy1_monoallelic"]["day90_mfi"] = 74999
        p_mfi_low_int["copy1_monoallelic"].pop("day90_mfi_retention_pct_vs_t0", None)
        orig_prec = getcontext().prec
        try:
            getcontext().prec = 4
            r_low_p4 = evaluate_ciita_locus2_arbitration(p_mfi_low, trusted_qualification_store=store_json)
            r_low_int_p4 = evaluate_ciita_locus2_arbitration(p_mfi_low_int, trusted_qualification_store=store_json)
            getcontext().prec = 28
            r_low_p28 = evaluate_ciita_locus2_arbitration(p_mfi_low, trusted_qualification_store=store_json)
            r_low_int_p28 = evaluate_ciita_locus2_arbitration(p_mfi_low_int, trusted_qualification_store=store_json)
        finally:
            getcontext().prec = orig_prec
        if not (
            r_low_p4["status"] == r_low_p28["status"] == "FAIL_OR_PENDING"
            and r_low_p4["full_promotion_authorized"] is False
            and r_low_p28["full_promotion_authorized"] is False
            and r_low_int_p4["status"] == r_low_int_p28["status"] == "FAIL_OR_PENDING"
            and r_low_p4["bound_identity"]["derived_day90_mfi_retention_pct"] == r_low_p28["bound_identity"]["derived_day90_mfi_retention_pct"]
        ):
            raise ValueError(f"B5 Day-90 MFI 74.999/100 context-independence check failed: p4={r_low_p4}, p28={r_low_p28}")
        cases.append({
            "case": "b5_day90_mfi_74p999_of_100_rejected_identically_under_prec4_and_prec28",
            "status": "FAIL_OR_PENDING",
            "full_promotion_authorized": False,
            "lead_promotion_authorized": False,
            "arbitration_closed": False,
            "incumbent_retained": False,
            "policy_pin_verified": True,
            "pending_full_qualification_fields": [],
            "passed": True,
        })

        # 54. Exact 75% boundary (75 / 100) PASSES identically under BOTH prec=4 and prec=28!
        p_mfi_exact = copy.deepcopy(base_full_pass)
        p_mfi_exact["copy1_monoallelic"]["t0_mfi"] = Decimal("100")
        p_mfi_exact["copy1_monoallelic"]["day90_mfi"] = Decimal("75")
        p_mfi_exact["copy1_monoallelic"]["day90_mfi_retention_pct_vs_t0"] = Decimal("75.0")
        orig_prec = getcontext().prec
        try:
            getcontext().prec = 4
            r_ex_p4 = evaluate_ciita_locus2_arbitration(p_mfi_exact, trusted_qualification_store=store_json)
            getcontext().prec = 28
            r_ex_p28 = evaluate_ciita_locus2_arbitration(p_mfi_exact, trusted_qualification_store=store_json)
        finally:
            getcontext().prec = orig_prec
        if not (
            r_ex_p4["status"] == r_ex_p28["status"] == "PASS_FULL_GY025_AND_GATE28B_PROMOTE"
            and r_ex_p4["full_promotion_authorized"] is True
            and r_ex_p28["full_promotion_authorized"] is True
        ):
            raise ValueError(f"B5 Day-90 MFI exact 75/100 context-independence check failed: p4={r_ex_p4}, p28={r_ex_p28}")
        cases.append({
            "case": "b5_day90_mfi_exact_75_of_100_passes_identically_under_prec4_and_prec28",
            "status": "PASS_FULL_GY025_AND_GATE28B_PROMOTE",
            "full_promotion_authorized": True,
            "lead_promotion_authorized": True,
            "arbitration_closed": True,
            "incumbent_retained": False,
            "policy_pin_verified": True,
            "pending_full_qualification_fields": [],
            "passed": True,
        })

        # --- R06 Blocking 4: Non-terminating MFI ratios under ALL caller Decimal traps enabled ---
        # 57. Non-terminating PASS ratio (80 / 99 = 80.8080...%) clears under Inexact + Rounded + Subnormal + Clamped + Underflow traps!
        p_mfi_80_99 = copy.deepcopy(base_full_pass)
        p_mfi_80_99["copy1_monoallelic"]["t0_mfi"] = 99
        p_mfi_80_99["copy1_monoallelic"]["day90_mfi"] = 80
        p_mfi_80_99["copy1_monoallelic"].pop("day90_mfi_retention_pct_vs_t0", None)
        with localcontext() as trap_ctx:
            trap_ctx.prec = 28
            for sig in (decimal.Inexact, decimal.Rounded, decimal.Subnormal, decimal.Clamped, decimal.Underflow):
                trap_ctx.traps[sig] = True
            r_80_99_p28 = evaluate_ciita_locus2_arbitration(p_mfi_80_99, trusted_qualification_store=store_json)
            trap_ctx.prec = 4
            r_80_99_p4 = evaluate_ciita_locus2_arbitration(p_mfi_80_99, trusted_qualification_store=store_json)
        if not (
            r_80_99_p28["status"] == r_80_99_p4["status"] == "PASS_FULL_GY025_AND_GATE28B_PROMOTE"
            and r_80_99_p28["full_promotion_authorized"] is True
            and r_80_99_p4["full_promotion_authorized"] is True
            and abs(r_80_99_p28["bound_identity"]["derived_day90_mfi_retention_pct"]["copy1_monoallelic"] - 80.8081) < 1e-6
            and r_80_99_p28["bound_identity"]["derived_day90_mfi_retention_pct"] == r_80_99_p4["bound_identity"]["derived_day90_mfi_retention_pct"]
        ):
            raise ValueError(f"R06 B4 non-terminating 80/99 under Decimal traps failed: p28={r_80_99_p28}, p4={r_80_99_p4}")
        cases.append({
            "case": "b4_r06_day90_mfi_80_of_99_nonterminating_passes_under_all_decimal_traps",
            "status": "PASS_FULL_GY025_AND_GATE28B_PROMOTE",
            "full_promotion_authorized": True,
            "lead_promotion_authorized": True,
            "arbitration_closed": True,
            "incumbent_retained": False,
            "policy_pin_verified": True,
            "pending_full_qualification_fields": [],
            "passed": True,
        })

        # 58. Non-terminating FAIL ratio (74 / 99 = 74.7474...%) fails cleanly without crashing under all Decimal traps!
        p_mfi_74_99 = copy.deepcopy(base_full_pass)
        p_mfi_74_99["copy1_monoallelic"]["t0_mfi"] = 99
        p_mfi_74_99["copy1_monoallelic"]["day90_mfi"] = 74
        p_mfi_74_99["copy1_monoallelic"].pop("day90_mfi_retention_pct_vs_t0", None)
        with localcontext() as trap_ctx:
            trap_ctx.prec = 28
            for sig in (decimal.Inexact, decimal.Rounded, decimal.Subnormal, decimal.Clamped, decimal.Underflow):
                trap_ctx.traps[sig] = True
            r_74_99_p28 = evaluate_ciita_locus2_arbitration(p_mfi_74_99, trusted_qualification_store=store_json)
            trap_ctx.prec = 4
            r_74_99_p4 = evaluate_ciita_locus2_arbitration(p_mfi_74_99, trusted_qualification_store=store_json)
        if not (
            r_74_99_p28["status"] == r_74_99_p4["status"] == "FAIL_OR_PENDING"
            and r_74_99_p28["full_promotion_authorized"] is False
            and r_74_99_p4["full_promotion_authorized"] is False
            and abs(r_74_99_p28["bound_identity"]["derived_day90_mfi_retention_pct"]["copy1_monoallelic"] - 74.7475) < 1e-6
            and r_74_99_p28["bound_identity"]["derived_day90_mfi_retention_pct"] == r_74_99_p4["bound_identity"]["derived_day90_mfi_retention_pct"]
        ):
            raise ValueError(f"R06 B4 non-terminating 74/99 under Decimal traps failed: p28={r_74_99_p28}, p4={r_74_99_p4}")
        cases.append({
            "case": "b4_r06_day90_mfi_74_of_99_nonterminating_fails_under_all_decimal_traps",
            "status": "FAIL_OR_PENDING",
            "full_promotion_authorized": False,
            "lead_promotion_authorized": False,
            "arbitration_closed": False,
            "incumbent_retained": False,
            "policy_pin_verified": True,
            "pending_full_qualification_fields": [],
            "passed": True,
        })

        # --- R08 Minor M1: Extreme finite MFI ratios NEVER raise OverflowError; out-of-assay-range (>1000%) fails closed ---
        # 59. Extreme finite MFI ratio (1e200 / 1e-200 = 1e402%) under all Decimal traps + tight caller Emax=5 -> structured FAIL_OR_PENDING, ZERO OverflowError!
        p_mfi_extreme_dec = copy.deepcopy(base_full_pass)
        p_mfi_extreme_dec["copy1_monoallelic"]["t0_mfi"] = Decimal("1e-200")
        p_mfi_extreme_dec["copy1_monoallelic"]["day90_mfi"] = Decimal("1e200")
        p_mfi_extreme_dec["copy1_monoallelic"].pop("day90_mfi_retention_pct_vs_t0", None)
        p_mfi_extreme_flt = copy.deepcopy(base_full_pass)
        p_mfi_extreme_flt["copy1_monoallelic"]["t0_mfi"] = 1e-200
        p_mfi_extreme_flt["copy1_monoallelic"]["day90_mfi"] = 1e200
        p_mfi_extreme_flt["copy1_monoallelic"].pop("day90_mfi_retention_pct_vs_t0", None)
        with localcontext() as ext_ctx:
            ext_ctx.prec = 4
            ext_ctx.Emax = 5
            ext_ctx.Emin = -5
            for sig in (decimal.Inexact, decimal.Rounded, decimal.Subnormal, decimal.Clamped, decimal.Underflow):
                ext_ctx.traps[sig] = True
            r_ext_dec = evaluate_ciita_locus2_arbitration(p_mfi_extreme_dec, trusted_qualification_store=store_json)
            r_ext_flt = evaluate_ciita_locus2_arbitration(p_mfi_extreme_flt, trusted_qualification_store=store_json)
        for lbl_e, res_e in (("decimal_1e402", r_ext_dec), ("float_1e402", r_ext_flt)):
            if not (
                res_e["status"] == "FAIL_OR_PENDING"
                and res_e["full_promotion_authorized"] is False
                and res_e["lead_promotion_authorized"] is False
                and res_e["bound_identity"]["derived_day90_mfi_retention_pct"]["copy1_monoallelic"] is None
                and any("OUT_OF_ASSAY_RANGE_MFI_RETENTION" in r for r in res_e["reasons"])
            ):
                raise ValueError(f"R08 M1 extreme finite MFI ratio ({lbl_e}) check failed: {res_e}")
            # Confirm returned dict is strict-JSON-serializable with zero Infinity/NaN!
            load_strict_json_text(json.dumps(res_e), f"m1_{lbl_e}")
        cases.append({
            "case": "m1_r08_day90_mfi_extreme_finite_ratio_returns_structured_fail_without_overflow_error",
            "status": "FAIL_OR_PENDING",
            "full_promotion_authorized": False,
            "lead_promotion_authorized": False,
            "arbitration_closed": False,
            "incumbent_retained": False,
            "policy_pin_verified": True,
            "pending_full_qualification_fields": [],
            "passed": True,
        })

        # 60. Physical assay domain boundary for derived Day-90 MFI retention: 1000% passes cleanly, 1500% (>1000% cap) fails closed!
        p_mfi_cap_ok = copy.deepcopy(base_full_pass)
        p_mfi_cap_ok["copy1_monoallelic"]["t0_mfi"] = 100
        p_mfi_cap_ok["copy1_monoallelic"]["day90_mfi"] = 1000
        p_mfi_cap_ok["copy1_monoallelic"]["day90_mfi_retention_pct_vs_t0"] = 1000.0
        r_cap_ok = evaluate_ciita_locus2_arbitration(p_mfi_cap_ok, trusted_qualification_store=store_json)

        p_mfi_cap_over = copy.deepcopy(base_full_pass)
        p_mfi_cap_over["copy1_monoallelic"]["t0_mfi"] = 100
        p_mfi_cap_over["copy1_monoallelic"]["day90_mfi"] = 1500
        p_mfi_cap_over["copy1_monoallelic"].pop("day90_mfi_retention_pct_vs_t0", None)
        r_cap_over = evaluate_ciita_locus2_arbitration(p_mfi_cap_over, trusted_qualification_store=store_json)
        if not (
            r_cap_ok["status"] == "PASS_FULL_GY025_AND_GATE28B_PROMOTE"
            and r_cap_ok["full_promotion_authorized"] is True
            and abs(r_cap_ok["bound_identity"]["derived_day90_mfi_retention_pct"]["copy1_monoallelic"] - 1000.0) < 1e-9
            and r_cap_over["status"] == "FAIL_OR_PENDING"
            and r_cap_over["full_promotion_authorized"] is False
            and any("OUT_OF_ASSAY_RANGE_MFI_RETENTION" in r for r in r_cap_over["reasons"])
        ):
            raise ValueError(f"R08 M1 assay domain cap [0, 1000]% check failed: ok={r_cap_ok}, over={r_cap_over}")
        cases.append({
            "case": "m1_r08_day90_mfi_assay_domain_cap_1000pct_boundary_enforced",
            "status": "FAIL_OR_PENDING",
            "full_promotion_authorized": False,
            "lead_promotion_authorized": False,
            "arbitration_closed": False,
            "incumbent_retained": False,
            "policy_pin_verified": True,
            "pending_full_qualification_fields": [],
            "passed": True,
        })

        # --- R17 Minor #1: Direct fractions.Fraction MFI support (exact parity with Decimal + fail-closed guards) ---
        # 61. Direct Fraction(75) / Fraction(100) promotes identically to Decimal("75") / Decimal("100") at exact 75.0%,
        #     non-terminating Fraction(1, 1) / Fraction(4, 3) promotes at exact 75.0%, sub-threshold / negative / zero /
        #     bool / extreme Fraction inputs fail closed cleanly with strict-JSON-serializable output!
        p_mfi_dec_75 = copy.deepcopy(base_full_pass)
        p_mfi_dec_75["copy1_monoallelic"]["t0_mfi"] = Decimal("100")
        p_mfi_dec_75["copy1_monoallelic"]["day90_mfi"] = Decimal("75")
        p_mfi_dec_75["copy1_monoallelic"].pop("day90_mfi_retention_pct_vs_t0", None)

        p_mfi_frac_75 = copy.deepcopy(base_full_pass)
        p_mfi_frac_75["copy1_monoallelic"]["t0_mfi"] = Fraction(100)
        p_mfi_frac_75["copy1_monoallelic"]["day90_mfi"] = Fraction(75)
        p_mfi_frac_75["copy1_monoallelic"].pop("day90_mfi_retention_pct_vs_t0", None)

        p_mfi_frac_75_rep = copy.deepcopy(p_mfi_frac_75)
        p_mfi_frac_75_rep["copy1_monoallelic"]["day90_mfi_retention_pct_vs_t0"] = Fraction(75)

        p_mfi_frac_nonterm = copy.deepcopy(base_full_pass)
        p_mfi_frac_nonterm["copy1_monoallelic"]["t0_mfi"] = Fraction(4, 3)
        p_mfi_frac_nonterm["copy1_monoallelic"]["day90_mfi"] = Fraction(1, 1)
        p_mfi_frac_nonterm["copy1_monoallelic"].pop("day90_mfi_retention_pct_vs_t0", None)

        p_mfi_frac_low = copy.deepcopy(base_full_pass)
        p_mfi_frac_low["copy1_monoallelic"]["t0_mfi"] = Fraction(100)
        p_mfi_frac_low["copy1_monoallelic"]["day90_mfi"] = Fraction(74999, 1000)
        p_mfi_frac_low["copy1_monoallelic"].pop("day90_mfi_retention_pct_vs_t0", None)

        p_mfi_frac_neg = copy.deepcopy(base_full_pass)
        p_mfi_frac_neg["copy1_monoallelic"]["t0_mfi"] = Fraction(100)
        p_mfi_frac_neg["copy1_monoallelic"]["day90_mfi"] = Fraction(-75)
        p_mfi_frac_neg["copy1_monoallelic"].pop("day90_mfi_retention_pct_vs_t0", None)

        p_mfi_frac_zero_t0 = copy.deepcopy(base_full_pass)
        p_mfi_frac_zero_t0["copy1_monoallelic"]["t0_mfi"] = Fraction(0)
        p_mfi_frac_zero_t0["copy1_monoallelic"]["day90_mfi"] = Fraction(75)
        p_mfi_frac_zero_t0["copy1_monoallelic"].pop("day90_mfi_retention_pct_vs_t0", None)

        p_mfi_frac_extreme = copy.deepcopy(base_full_pass)
        p_mfi_frac_extreme["copy1_monoallelic"]["t0_mfi"] = Fraction(1, 10 ** 200)
        p_mfi_frac_extreme["copy1_monoallelic"]["day90_mfi"] = Fraction(10 ** 200, 1)
        p_mfi_frac_extreme["copy1_monoallelic"].pop("day90_mfi_retention_pct_vs_t0", None)

        with localcontext() as f_ctx:
            f_ctx.prec = 4
            f_ctx.Emax = 5
            f_ctx.Emin = -5
            for sig in (decimal.Inexact, decimal.Rounded, decimal.Subnormal, decimal.Clamped, decimal.Underflow):
                f_ctx.traps[sig] = True
            r_dec_75 = evaluate_ciita_locus2_arbitration(p_mfi_dec_75, trusted_qualification_store=store_json)
            r_frac_75 = evaluate_ciita_locus2_arbitration(p_mfi_frac_75, trusted_qualification_store=store_json)
            r_frac_75_rep = evaluate_ciita_locus2_arbitration(p_mfi_frac_75_rep, trusted_qualification_store=store_json)
            r_frac_nonterm = evaluate_ciita_locus2_arbitration(p_mfi_frac_nonterm, trusted_qualification_store=store_json)
            r_frac_low = evaluate_ciita_locus2_arbitration(p_mfi_frac_low, trusted_qualification_store=store_json)
            r_frac_neg = evaluate_ciita_locus2_arbitration(p_mfi_frac_neg, trusted_qualification_store=store_json)
            r_frac_zero_t0 = evaluate_ciita_locus2_arbitration(p_mfi_frac_zero_t0, trusted_qualification_store=store_json)
            r_frac_extreme = evaluate_ciita_locus2_arbitration(p_mfi_frac_extreme, trusted_qualification_store=store_json)

        if not (
            r_dec_75 == r_frac_75 == r_frac_75_rep == r_frac_nonterm
            and r_frac_75["status"] == "PASS_FULL_GY025_AND_GATE28B_PROMOTE"
            and r_frac_75["full_promotion_authorized"] is True
            and r_frac_75["lead_promotion_authorized"] is True
            and abs(r_frac_75["bound_identity"]["derived_day90_mfi_retention_pct"]["copy1_monoallelic"] - 75.0) < 1e-9
            and r_frac_low["status"] == "FAIL_OR_PENDING"
            and r_frac_low["full_promotion_authorized"] is False
            and abs(r_frac_low["bound_identity"]["derived_day90_mfi_retention_pct"]["copy1_monoallelic"] - 74.999) < 1e-9
            and r_frac_neg["status"] == "FAIL_OR_PENDING"
            and r_frac_neg["full_promotion_authorized"] is False
            and r_frac_zero_t0["status"] == "FAIL_OR_PENDING"
            and r_frac_zero_t0["full_promotion_authorized"] is False
            and r_frac_extreme["status"] == "FAIL_OR_PENDING"
            and r_frac_extreme["full_promotion_authorized"] is False
            and r_frac_extreme["bound_identity"]["derived_day90_mfi_retention_pct"]["copy1_monoallelic"] is None
            and any("OUT_OF_ASSAY_RANGE_MFI_RETENTION" in r for r in r_frac_extreme["reasons"])
        ):
            raise ValueError(
                f"R17 M1 direct Fraction MFI parity/guards failed: dec={r_dec_75}, frac={r_frac_75}, "
                f"low={r_frac_low}, neg={r_frac_neg}, zero={r_frac_zero_t0}, ext={r_frac_extreme}"
            )
        load_strict_json_text(json.dumps(r_frac_75), "r17_m1_frac75")
        load_strict_json_text(json.dumps(r_frac_extreme), "r17_m1_frac_ext")
        cases.append({
            "case": "m1_r17_day90_mfi_direct_fraction_75_of_100_promotes_identically_to_decimal",
            "status": "PASS_FULL_GY025_AND_GATE28B_PROMOTE",
            "full_promotion_authorized": True,
            "lead_promotion_authorized": True,
            "arbitration_closed": True,
            "incumbent_retained": False,
            "policy_pin_verified": True,
            "pending_full_qualification_fields": [],
            "passed": True,
        })

    return {"total_cases": len(cases), "all_passed": True, "cases": cases}


def build_and_audit_part_b(prots: dict[str, str], sp_kmers: dict[int, set[str]], sp_sha: str) -> dict[str, Any]:
    l2_v3_fa = parse_fasta(OPENISLET_ROOT / "data/constructs/islet1_locus2_ciita_modeb_comparators_v0.8.0.fasta")
    d1_v2_fa = parse_fasta(OPENISLET_ROOT / "data/constructs/islet1_d1b_auto_v2_v0.8.0.fasta")
    dy_fa = parse_fasta(OPENISLET_ROOT / "data/constructs/islet1_design_y_wildcard_comparators_v0.8.0.fasta")
    ref = json.loads((OPENISLET_ROOT / "data/raw/layer2_genomic_and_jaspar_reference.json").read_text(encoding="utf-8"))
    grch = json.loads(GRCH38_CACHE_PATH.read_text(encoding="utf-8"))
    pwms = ref["jaspar_pwms"]
    ref_bundle = ref["iip0031_locus2_modeb_v3_reference_bundle"]

    # Verified exact parts shared with IIP-0031 & IIP-0035
    seq_v3 = l2_v3_fa["L2_V3_CD274P_ZERO_TATATA"]
    seq_l1a = d1_v2_fa["D1AUTO_v2_L1A_CIITA_CD64T_IL1RN"]
    seq_l1b = d1_v2_fa["D1AUTO_v2_L1B_CIITA_CD64T_CD46WT_COMPARATOR"]

    CIITA_HA_L = seq_v3[0:375]
    STOP_3F = seq_v3[375:387]
    SHIELD_154 = seq_v3[387:541]
    CD274P_250 = seq_v3[541:791]
    KOZAK_9 = seq_v3[791:800]
    HGAPDH_PA_HARD = harden_polya_atg_and_acceptors(seq_v3[1637:1787])
    HPRT1_PA_HARD = harden_polya_atg_and_acceptors(grch["HPRT1_pA_150bp"]["sequence"])
    EEF1A1_230 = seq_v3[1867:2097]
    DM1_RC80 = seq_v3[3659:3739]
    CIITA_HA_R = seq_v3[3739:4114]
    PGK1_250 = dy_fa["DESIGN_Y_CORE_CD200_IEC_11066bp"][2981:3231]

    # Assert exact homology-arm & scaffold byte-identity between IIP-0035 L1A/L1B and IIP-0031 L2_V3!
    if not (seq_l1a[:800] == seq_v3[:800]):
        raise ValueError("L1A 5' arm+STOP_3F+SPA_MAZ4+CD274p+Kozak must match L2_V3 byte-for-byte!")
    if not (seq_l1a[-455:] == seq_v3[-455:]):
        raise ValueError("L1A 3' DM1_RC80+CIITA_HA_R must match L2_V3 byte-for-byte!")
    if not (seq_l1b[:541] == seq_v3[:541]):
        raise ValueError("L1B 5' arm+STOP_3F+SPA_MAZ4 must match L2_V3 byte-for-byte!")
    if not (seq_l1b[-455:] == seq_v3[-455:]):
        raise ValueError("L1B 3' DM1_RC80+CIITA_HA_R must match L2_V3 byte-for-byte!")

    # Extract exact IIP-0035 hardened CDSs and pause barriers directly from seq_l1a / seq_l1b
    # seq_l1a: HA_L(375)+STOP_3F(12)+SPA_MAZ4(154)+CD274P(250)+KOZAK(9)=800; IL1RN(534)->1334; STOP_CAP(12)->1346; HGAPDH_PA(150)->1496;
    # PAUSE_L1A_MID(45)->1541; HOXA_CTCF(80)->1621; EEF1A1_230(230)->1851; KOZAK(9)->1860; CD64T(942)->2802; STOP_CAP(12)->2814;
    # HPRT1_PA(150)->2964; PAUSE_L1A_3P(36)->3000; DM1_RC80(80)->3080; HA_R(375)->3455
    cds_il1rn = seq_l1a[800:1334]
    pause_l1a_mid = seq_l1a[1496:1541]
    cds_cd64t = seq_l1a[1860:2802]
    pause_l1a_3p = seq_l1a[2964:3000]
    # seq_l1b: ... PGK1_250(250)+KOZAK(9)=800; CD46(1179)->1979; STOP_CAP(12)->1991; HGAPDH_PA(150)->2141; PAUSE_L1B_MID(45)->2186;
    # HOXA(80)->2266; EEF1A1(230)->2496; KOZAK(9)->2505; CD64T(942)->3447; STOP_CAP(12)->3459; HPRT1_PA(150)->3609; PAUSE_L1B_3P(36)->3645
    cds_cd46 = seq_l1b[800:1979]
    pause_l1b_mid = seq_l1b[2141:2186]
    pause_l1b_3p = seq_l1b[3609:3645]

    aa_il1rn = prots["P18510"]
    aa_cd64t = prots["P12314"][:313]
    aa_cd46 = prots["P15529"]
    aa_cfh_cd55 = prots["P08603"][:264] + prots["P08174"][285:381]  # CFH[1-264](Val62)-CD55[286-381] GPI (360 aa)
    aa_cr1_held = prots["P17927"][:687] + prots["P17927"][1969:2005]  # GY-026 HELD!

    if not (l2.translate_dna(cds_il1rn) == aa_il1rn + "*"):
        raise ValueError('Verification check failed: l2.translate_dna(cds_il1rn) == aa_il1rn + "*"')
    if not (l2.translate_dna(cds_cd64t) == aa_cd64t + "*"):
        raise ValueError('Verification check failed: l2.translate_dna(cds_cd64t) == aa_cd64t + "*"')
    if not (l2.translate_dna(cds_cd46) == aa_cd46 + "*"):
        raise ValueError('Verification check failed: l2.translate_dna(cds_cd46) == aa_cd46 + "*"')
    if not (prots["P08603"][61] == "V"):
        raise ValueError("CFH pos 62 must be protective Val62 (rs800292)!")

    # Synthesize zero-splice, zero-defect CFH[1-264]-CD55[286-381] CDS on the hardened L1B backbone!
    bg_cfh = (
        CIITA_HA_L + STOP_3F + SHIELD_154 + PGK1_250 + KOZAK_9 + STOP_CAP_3FRAME_12BP + HGAPDH_PA_HARD
        + pause_l1b_mid + GRCH38_HOXA_CTCF_C5_80BP + EEF1A1_230 + KOZAK_9 + cds_cd64t
        + STOP_CAP_3FRAME_12BP + HPRT1_PA_HARD + pause_l1b_3p + DM1_RC80 + CIITA_HA_R
    )
    cds_cfh_cd55 = optimize_cds_zero_splice_zero_defect(
        aa_cfh_cd55,
        prefix_context=PGK1_250 + KOZAK_9,
        suffix_context=STOP_CAP_3FRAME_12BP + HGAPDH_PA_HARD,
        existing_seq=bg_cfh,
        pwms=pwms,
        seed=28031,
        stop_codon="TGA",
    )

    def assemble(parts: list[tuple[str, str]]) -> tuple[str, dict[str, tuple[int, int]]]:
        chunks, spans, pos = [], {}, 1
        for k, v in parts:
            chunks.append(v)
            spans[k] = (pos, pos + len(v) - 1)
            pos += len(v)
        return "".join(chunks), spans

    construct_defs = [
        (
            "ABX_L2_v2_CD64T_IL1RN",
            "MODE_B_CO_PRIMARY_ABX_AND_D1B_SHARED_CIITA_KO_CD274P_IL1RN_EEF1A1_CD64T_313_ZERO_VIRAL_RECEPTOR",
            [
                ("HA_L", CIITA_HA_L), ("STOP_3F", STOP_3F), ("SPA_MAZ4_154", SHIELD_154),
                ("CD274P_250", CD274P_250), ("KOZAK_1", KOZAK_9), ("CDS_IL1RN_177", cds_il1rn),
                ("STOP_CAP_1", STOP_CAP_3FRAME_12BP), ("HGAPDH_PA_HARD", HGAPDH_PA_HARD),
                ("PAUSE_MID", pause_l1a_mid), ("HOXA_CTCF_C5_80", GRCH38_HOXA_CTCF_C5_80BP),
                ("EEF1A1_230", EEF1A1_230), ("KOZAK_2", KOZAK_9), ("CDS_CD64T_313", cds_cd64t),
                ("STOP_CAP_2", STOP_CAP_3FRAME_12BP), ("HPRT1_PA_HARD", HPRT1_PA_HARD),
                ("PAUSE_3P", pause_l1a_3p), ("DM1_RC80", DM1_RC80), ("HA_R", CIITA_HA_R),
            ],
            [
                {"tu_id": "TU1_CD274p_IL1RN", "prom": "CD274P_250", "tss_off": 215, "cds": "CDS_IL1RN_177", "pa": "HGAPDH_PA_HARD", "next_prom": "EEF1A1_230"},
                {"tu_id": "TU2_EEF1A1_CD64t", "prom": "EEF1A1_230", "tss_off": 197, "cds": "CDS_CD64T_313", "pa": "HPRT1_PA_HARD", "next_prom": None},
            ],
            ["CD274P_250", "EEF1A1_230"], ["HOXA_CTCF_C5_80", "DM1_RC80"], ["SPA_MAZ4_154"], 0, "D1AUTO_v2_L1A_CIITA_CD64T_IL1RN",
        ),
        (
            "ABX_L2_v2_CD64T_CD46WT_COMP",
            "MODE_B_SECONDARY_COMPLEMENT_COMPARATOR_ABX_PGK1_CD46WT_EEF1A1_CD64T_313_GATE0V_REQUIRED",
            [
                ("HA_L", CIITA_HA_L), ("STOP_3F", STOP_3F), ("SPA_MAZ4_154", SHIELD_154),
                ("PGK1_250", PGK1_250), ("KOZAK_1", KOZAK_9), ("CDS_CD46_392", cds_cd46),
                ("STOP_CAP_1", STOP_CAP_3FRAME_12BP), ("HGAPDH_PA_HARD", HGAPDH_PA_HARD),
                ("PAUSE_MID", pause_l1b_mid), ("HOXA_CTCF_C5_80", GRCH38_HOXA_CTCF_C5_80BP),
                ("EEF1A1_230", EEF1A1_230), ("KOZAK_2", KOZAK_9), ("CDS_CD64T_313", cds_cd64t),
                ("STOP_CAP_2", STOP_CAP_3FRAME_12BP), ("HPRT1_PA_HARD", HPRT1_PA_HARD),
                ("PAUSE_3P", pause_l1b_3p), ("DM1_RC80", DM1_RC80), ("HA_R", CIITA_HA_R),
            ],
            [
                {"tu_id": "TU1_PGK1_CD46_WT", "prom": "PGK1_250", "tss_off": 230, "cds": "CDS_CD46_392", "pa": "HGAPDH_PA_HARD", "next_prom": "EEF1A1_230"},
                {"tu_id": "TU2_EEF1A1_CD64t", "prom": "EEF1A1_230", "tss_off": 197, "cds": "CDS_CD64T_313", "pa": "HPRT1_PA_HARD", "next_prom": None},
            ],
            ["PGK1_250", "EEF1A1_230"], ["HOXA_CTCF_C5_80", "DM1_RC80"], ["SPA_MAZ4_154"], 0, "D1AUTO_v2_L1B_CIITA_CD64T_CD46WT_COMPARATOR",
        ),
        (
            "ABX_L2_v2_CD64T_CFH_CD55_COMP",
            "MODE_B_TERTIARY_COMPLEMENT_COMPARATOR_ABX_PGK1_CFH1_264_CD55_286_381_GPI_EEF1A1_CD64T_313_PIGK1_AP_ONLY",
            [
                ("HA_L", CIITA_HA_L), ("STOP_3F", STOP_3F), ("SPA_MAZ4_154", SHIELD_154),
                ("PGK1_250", PGK1_250), ("KOZAK_1", KOZAK_9), ("CDS_CFH_CD55_360", cds_cfh_cd55),
                ("STOP_CAP_1", STOP_CAP_3FRAME_12BP), ("HGAPDH_PA_HARD", HGAPDH_PA_HARD),
                ("PAUSE_MID", pause_l1b_mid), ("HOXA_CTCF_C5_80", GRCH38_HOXA_CTCF_C5_80BP),
                ("EEF1A1_230", EEF1A1_230), ("KOZAK_2", KOZAK_9), ("CDS_CD64T_313", cds_cd64t),
                ("STOP_CAP_2", STOP_CAP_3FRAME_12BP), ("HPRT1_PA_HARD", HPRT1_PA_HARD),
                ("PAUSE_3P", pause_l1b_3p), ("DM1_RC80", DM1_RC80), ("HA_R", CIITA_HA_R),
            ],
            [
                {"tu_id": "TU1_PGK1_CFH_CD55_GPI", "prom": "PGK1_250", "tss_off": 230, "cds": "CDS_CFH_CD55_360", "pa": "HGAPDH_PA_HARD", "next_prom": "EEF1A1_230"},
                {"tu_id": "TU2_EEF1A1_CD64t", "prom": "EEF1A1_230", "tss_off": 197, "cds": "CDS_CD64T_313", "pa": "HPRT1_PA_HARD", "next_prom": None},
            ],
            ["PGK1_250", "EEF1A1_230"], ["HOXA_CTCF_C5_80", "DM1_RC80"], ["SPA_MAZ4_154"], 1, None,
        ),
        (
            "ABX_L2_v2_CTRL_CD64T_ONLY",
            "MODE_B_SINGLE_CARGO_ATTRIBUTION_CONTROL_EEF1A1_CD64T_313_ONLY",
            [
                ("HA_L", CIITA_HA_L), ("STOP_3F", STOP_3F), ("SPA_MAZ4_154", SHIELD_154),
                ("HOXA_CTCF_C5_80", GRCH38_HOXA_CTCF_C5_80BP),
                ("EEF1A1_230", EEF1A1_230), ("KOZAK_2", KOZAK_9), ("CDS_CD64T_313", cds_cd64t),
                ("STOP_CAP_2", STOP_CAP_3FRAME_12BP), ("HPRT1_PA_HARD", HPRT1_PA_HARD),
                ("PAUSE_3P", pause_l1a_3p), ("DM1_RC80", DM1_RC80), ("HA_R", CIITA_HA_R),
            ],
            [
                {"tu_id": "TU1_EEF1A1_CD64t", "prom": "EEF1A1_230", "tss_off": 197, "cds": "CDS_CD64T_313", "pa": "HPRT1_PA_HARD", "next_prom": None},
            ],
            ["EEF1A1_230"], ["HOXA_CTCF_C5_80", "DM1_RC80"], ["SPA_MAZ4_154"], 0, None,
        ),
        (
            "ABX_L2_v2_CTRL_IL1RN_ONLY",
            "MODE_B_SINGLE_CARGO_ATTRIBUTION_CONTROL_CD274P_IL1RN_177_ONLY_SYMMETRIC_2CTCF",
            [
                ("HA_L", CIITA_HA_L), ("STOP_3F", STOP_3F), ("SPA_MAZ4_154", SHIELD_154),
                ("HOXA_CTCF_C5_80", GRCH38_HOXA_CTCF_C5_80BP),
                ("CD274P_250", CD274P_250), ("KOZAK_1", KOZAK_9), ("CDS_IL1RN_177", cds_il1rn),
                ("STOP_CAP_1", STOP_CAP_3FRAME_12BP), ("HGAPDH_PA_HARD", HGAPDH_PA_HARD),
                ("PAUSE_MID", pause_l1a_mid), ("DM1_RC80", DM1_RC80), ("HA_R", CIITA_HA_R),
            ],
            [
                {"tu_id": "TU1_CD274p_IL1RN", "prom": "CD274P_250", "tss_off": 215, "cds": "CDS_IL1RN_177", "pa": "HGAPDH_PA_HARD", "next_prom": None},
            ],
            ["CD274P_250"], ["HOXA_CTCF_C5_80", "DM1_RC80"], ["SPA_MAZ4_154"], 0, None,
        ),
        (
            "ABX_L2_v2_CTRL_CD46WT_ONLY",
            "MODE_B_SINGLE_CARGO_ATTRIBUTION_CONTROL_PGK1_CD46WT_392_ONLY_SYMMETRIC_2CTCF",
            [
                ("HA_L", CIITA_HA_L), ("STOP_3F", STOP_3F), ("SPA_MAZ4_154", SHIELD_154),
                ("HOXA_CTCF_C5_80", GRCH38_HOXA_CTCF_C5_80BP),
                ("PGK1_250", PGK1_250), ("KOZAK_1", KOZAK_9), ("CDS_CD46_392", cds_cd46),
                ("STOP_CAP_1", STOP_CAP_3FRAME_12BP), ("HGAPDH_PA_HARD", HGAPDH_PA_HARD),
                ("PAUSE_MID", pause_l1b_mid), ("DM1_RC80", DM1_RC80), ("HA_R", CIITA_HA_R),
            ],
            [
                {"tu_id": "TU1_PGK1_CD46_WT", "prom": "PGK1_250", "tss_off": 230, "cds": "CDS_CD46_392", "pa": "HGAPDH_PA_HARD", "next_prom": None},
            ],
            ["PGK1_250"], ["HOXA_CTCF_C5_80", "DM1_RC80"], ["SPA_MAZ4_154"], 0, None,
        ),
    ]

    chr16_seq = ref_bundle["grch38_chr16_ciita_exon5_2001bp"]["sequence"].upper()
    ex5_78bp = chr16_seq[10898925 - 10898000 : 10899002 - 10898000 + 1]
    cut_off_ex5 = 10898967 - 10898925 + 1
    ciita_iso_bundle = ref_bundle["ciita_refseq_isoforms_8"]
    sv40_sig = "AACTTGTTTATTGCAGCTTATAATGGTTACAAATAAAGCAATAGCATCACAAATTTCACAAATAAAGCATTTTTTTCACTGC"
    bgh_sig = "CGACTGTGCCTTCTAGTTGCCAGCCATCTGTTGTTTGCCCCTCCCCCGTGCCTTCCTTGACCCTGGAAGGTGCCACTCCCAC"

    p1_audits = []
    fasta_lines = []
    for cid, role, parts, tu_defs, prom_keys, ins_keys, canon_keys, pigk_cnt, byte_eq_iip35 in construct_defs:
        seq, spans = assemble(parts)
        if byte_eq_iip35 is not None:
            if not (seq == d1_v2_fa[byte_eq_iip35]):
                raise ValueError(f"{cid} is NOT byte-identical to {byte_eq_iip35}!")
        dlen = len(seq)
        pkg_bp = dlen + 290
        headroom = 4700 - pkg_bp
        if not (pkg_bp <= 4700):
            raise ValueError(f"{cid} exceeds 4,700 bp single-AAV6 limit: {pkg_bp}")

        tu_specs = []
        for td in tu_defs:
            p_s1, _ = spans[td["prom"]]
            c_s1, c_e1 = spans[td["cds"]]
            _, pa_e1 = spans[td["pa"]]
            rt_b = (spans[td["next_prom"]][0] - 1) if td["next_prom"] else len(seq)
            tu_specs.append({
                "tu_id": td["tu_id"], "strand": "+", "prom_start_0based": p_s1 - 1,
                "tss_0based": (p_s1 - 1) + td["tss_off"], "cds_start_0based": c_s1 - 1,
                "cds_end_0based": c_e1, "polya_end_0based": pa_e1, "rt_bound_0based": rt_b,
            })

        exempt_spans = [(spans[ck][0] - 1, spans[ck][1]) for ck in canon_keys]
        rep = max_repeat_outside_canonical(seq, exempt_spans)
        ir_ge16 = l2._count_disjoint_ir_ge_k(seq, min_k=16)
        near_ir = l2.scan_disjoint_inverted_repeats_with_mismatches(seq, min_k=20, max_mismatches=1)
        if not (rep["max_disjoint_ir_bp"] <= 15 and ir_ge16 == 0):
            raise ValueError(f"{cid} IR violation: {rep}")
        if not (len(near_ir) == 0):
            raise ValueError(f"{cid} near-IR violation: {near_ir}")
        if not (rep["max_disjoint_dr_full_bp"] < 30 and rep["max_disjoint_dr_outside_canonical_bp"] < 30):
            raise ValueError(f"{cid} DR violation: {rep}")

        sp_unb = scan_unbounded_cryptic_introns(seq, tu_specs)
        n_all_tss = int(sp_unb["tss_to_polya"]["total_introns_ge50nt"])
        n_all_full = int(sp_unb["full_promoter_to_polya"]["total_introns_ge50nt"])
        n_clip_tss = len(sp_unb["tss_to_polya"]["start_or_sp_clipping_introns"])
        n_clip_full = len(sp_unb["full_promoter_to_polya"]["start_or_sp_clipping_introns"])
        n_p2c_full = len(sp_unb["full_promoter_to_polya"]["prom_to_cds_or_pa_introns"])
        n_int_full = len(sp_unb["full_promoter_to_polya"]["internal_cds_or_pa_introns"])
        if not (n_clip_tss == 0 and n_clip_full == 0 and n_p2c_full == 0 and n_int_full == 0):
            raise ValueError(f"{cid} splice failure: {sp_unb}")
        if not (n_all_tss == 0):
            raise ValueError(f"{cid} unexpected TSS-to-polyA splice pair: {sp_unb}")

        orf_aud = scan_strict_orfs_and_readthrough(seq, tu_specs, min_aa=8)
        if not (not orf_aud["mkglehldsa_present"]):
            raise ValueError('Verification check failed: not orf_aud["mkglehldsa_present"]')
        if not (len(orf_aud["utr5_uATG_hits"]) == 0):
            raise ValueError('Verification check failed: len(orf_aud["utr5_uATG_hits"]) == 0')
        if not (len(orf_aud["post_stop_downstream_orf_ge8aa"]) == 0):
            raise ValueError('Verification check failed: len(orf_aud["post_stop_downstream_orf_ge8aa"]) == 0')
        if not (seq.count(sv40_sig) == 0 and seq.count(bgh_sig) == 0):
            raise ValueError('Verification check failed: seq.count(sv40_sig) == 0 and seq.count(bgh_sig) == 0')

        cds_summaries = []
        cds_homos = 0
        for pname, pseq in parts:
            if pname.startswith("CDS_"):
                aa = l2.translate_dna(pseq)
                if not (aa.endswith("*") and aa.count("*") == 1):
                    raise ValueError('Verification check failed: aa.endswith("*") and aa.count("*") == 1')
                aa_clean = aa[:-1]
                if not (not TWO_A_REGEX.search(aa_clean)):
                    raise ValueError('Verification check failed: not TWO_A_REGEX.search(aa_clean)')
                cds_homos += len(re.findall(r"(A{7,}|C{7,}|G{7,}|T{7,})", pseq))
                sp_scan = scan_swissprot_peptides(aa_clean, sp_kmers)
                cds_summaries.append({
                    "part": pname, "cds_bp": len(pseq), "aa_len": len(aa_clean),
                    "aa_sha256": sha256_str(aa_clean),
                    "swissprot_foreign_8_11m": sp_scan["foreign_8_11mers_total"],
                    "swissprot_foreign_15m": sp_scan["k15_foreign"],
                })
        if not (cds_homos == 0):
            raise ValueError('Verification check failed: cds_homos == 0')

        # CIITA 8-isoform chimera audit
        def _km(p: str, szs: tuple[int, ...]) -> set[str]:
            return {p[i : i + sz] for sz in szs for i in range(max(0, len(p) - sz + 1))}
        mx8, mx15 = 0, 0
        for _acc_c, rec_c in ciita_iso_bundle.items():
            mrna_c = rec_c["mrna_sequence"].upper()
            cs_c, ce_c = rec_c["cds_start_1based"], rec_c["cds_end_1based"]
            ex5_p1 = mrna_c.find(ex5_78bp) + 1
            cds_before = mrna_c[cs_c - 1 : ex5_p1 - 1]
            nat_aa = l2.translate_dna(mrna_c[cs_c - 1 : ce_c]).rstrip("*")
            chim_dna = cds_before + seq[375 - cut_off_ex5 :]
            aas = []
            for ic in range(0, len(chim_dna) - 2, 3):
                aa_c = l2.GENETIC_CODE[chim_dna[ic : ic + 3]]
                if aa_c == "*":
                    break
                aas.append(aa_c)
            trunc = "".join(aas)
            mx8 = max(mx8, len(_km(trunc, (8, 9, 10, 11)) - _km(nat_aa, (8, 9, 10, 11))))
            mx15 = max(mx15, len(_km(trunc, (15,)) - _km(nat_aa, (15,))))
        if not (mx8 == 0 and mx15 == 0):
            raise ValueError('Verification check failed: mx8 == 0 and mx15 == 0')

        # Insulator-aware 6-PWM JASPAR Bonferroni audit
        allowed_spans = [(spans[k][0], spans[k][1]) for k in (prom_keys + ins_keys + ["HA_L", "HA_R"])]
        fam_t = sum(max(0, 2 * (dlen - int(m["length"]) + 1)) for m in pwms.values())
        ectopic_6pwm = []
        ctcf_hits = 0
        for mid, pentry in pwms.items():
            sc = l2.scan_jaspar_pwm(seq, pentry, top_k=30, n_matrices_in_scan=len(pwms), actual_family_total_tests=fam_t)
            for hp in sc["all_significant_hits"]:
                if not hp["passes_region_wide_bonferroni_0p05"]:
                    continue
                s1, e1 = int(hp["start_1based_in_window"]), int(hp["end_1based_in_window"])
                if not any(not (e1 < a or s1 > b) for a, b in allowed_spans):
                    ectopic_6pwm.append({"matrix_id": mid, "tf": hp["tf_name"], "pos": [s1, e1], "strand": hp["strand"]})
                elif mid == "MA0139.1":
                    ctcf_hits += 1
        if not (len(ectopic_6pwm) == 0):
            raise ValueError(f"{cid} ectopic 6-PWM: {ectopic_6pwm}")

        d_sha = sha256_str(seq)
        if cid in ("ABX_L2_v2_CD64T_IL1RN", "ABX_L2_v2_CTRL_CD64T_ONLY", "ABX_L2_v2_CTRL_IL1RN_ONLY"):
            dep_status = "ACTIVE_WAVE5_GO_SCOPE_MODE_B"
        elif "CD46WT" in cid:
            dep_status = "HOLD_COMPARATOR_BLOCKED_PENDING_CAND034_CD46_TROPIC_ADDENDUM"
        else:
            dep_status = "TERTIARY_HOLD_COMPARATOR_PIGK1_REQUIRES_CTRL_CFH_CD55_ONLY"
        p1_audits.append({
            "construct_id": cid,
            "locus": "chr16p13.13_CIITA_Exon5",
            "role": role,
            "deployment_status": dep_status,
            "execution_supported": False,
            "delta_k_vs_abx_core": 0,
            "byte_identical_to_iip0035_construct": byte_eq_iip35,
            "donor_length_bp": dlen,
            "fasta_omits_physical_itrs": True,
            "nominal_aav6_packaged_bp": pkg_bp,
            "nominal_aav6_headroom_bp": headroom,
            "fits_nominal_single_aav6_le_4700bp": pkg_bp <= 4700,
            "donor_sha256": d_sha,
            "gc_pct": round(100.0 * (seq.count("G") + seq.count("C")) / dlen, 2),
            "two_a_count": 0,
            "pigk_gpi_count": pigk_cnt,
            "sv40_or_bgh_count": 0,
            "mkglehldsa_count": 0,
            "utr5_uATG_count": 0,
            "post_stop_downstream_orf_ge8aa_count": 0,
            "start_or_sp_clipping_introns_tss_and_full": f"{n_clip_tss}/{n_clip_full}",
            "all_predicted_splice_pairs_tss_and_full": f"{n_all_tss}/{n_all_full}",
            "all_predicted_splice_pairs_note": (
                "2 upstream promoter-internal pairs lie upstream of the annotated CD274p TSS (0 in transcribed TSS->polyA window, 0 start/SP-clipping)"
                if n_all_full > 0
                else "0 predicted splice pairs in both TSS->polyA and full-promoter->polyA scan windows"
            ),
            "repeats": {**rep, "disjoint_ir_ge16_count": ir_ge16, "near_ir_ge20_le1mm_count": len(near_ir)},
            "ectopic_6pwm_hits": 0,
            "verified_ctcf_ma0139_hits": ctcf_hits,
            "ciita_8isoform_novel_peptides_8_11m_15m": [mx8, mx15],
            "cds_protein_audits": cds_summaries,
        })
        hdr = (
            f">{cid} locus=chr16p13.13_CIITA_Exon5 delta_k=0 donor_bp={dlen} aav6_pkg_bp={pkg_bp} "
            f"headroom_bp={headroom} clip_introns_tss_full=0/0 mkglehldsa=0 uATG=0 rt_orf_ge8aa=0 "
            f"2a=0 pigk={pigk_cnt} ir={rep['max_disjoint_ir_bp']} dr_out={rep['max_disjoint_dr_outside_canonical_bp']} "
            f"ectopic_6pwm=0 ciita_chim=0 sha256={d_sha}"
        )
        fasta_lines.append(hdr)
        for i in range(0, dlen, 80):
            fasta_lines.append(seq[i : i + 80])

    FASTA_OUT.write_text("\n".join(fasta_lines) + "\n", encoding="utf-8")
    fasta_sha = sha256_file(FASTA_OUT)

    # Gate P2 — Topology, Disulfides, EPB41L2 clearance, iCasp9 orthogonality (R1 fixed!)
    def _uniprot_features(acc: str) -> dict[str, Any]:
        uj = json.loads((PROT_CACHE_DIR / f"uniprot_{acc}.json").read_text(encoding="utf-8"))
        feats = uj.get("features", [])
        sp_f = [f for f in feats if f.get("type") == "Signal"]
        tm_f = [f for f in feats if f.get("type") == "Transmembrane"]
        cyt_f = [f for f in feats if f.get("type") == "Topological domain" and "cytoplasmic" in str(f.get("description", "")).lower()]
        ss_f = [f for f in feats if f.get("type") == "Disulfide bond"]
        glyc_f = [f for f in feats if f.get("type") == "Glycosylation"]
        n_glyc = [f for f in glyc_f if "n-linked" in str(f.get("description", "")).lower()]
        o_glyc = [f for f in glyc_f if "o-linked" in str(f.get("description", "")).lower()]
        return {
            "uniprot_acc": acc,
            "protein_len": len(uj["sequence"]["value"]),
            "signal_peptide_1based": (
                [sp_f[0]["location"]["start"]["value"], sp_f[0]["location"]["end"]["value"]] if sp_f else None
            ),
            "transmembrane_1based": (
                [tm_f[0]["location"]["start"]["value"], tm_f[0]["location"]["end"]["value"]] if tm_f else None
            ),
            "cytoplasmic_1based": (
                [cyt_f[0]["location"]["start"]["value"], cyt_f[0]["location"]["end"]["value"]] if cyt_f else None
            ),
            "disulfide_bonds_total": len(ss_f),
            "n_glycosylation_sites": len(n_glyc),
            "o_glycosylation_sites": len(o_glyc),
            "total_glycosylation_sites": len(glyc_f),
        }

    u_p12314 = _uniprot_features("P12314")
    u_p18510 = _uniprot_features("P18510")
    u_p15529 = _uniprot_features("P15529")
    # Programmatic R1 checks directly against UniProt features, translated CDS, and published Gravina 2023 CDS!
    if u_p12314["transmembrane_1based"] != [293, 313] or u_p12314["cytoplasmic_1based"] != [314, 374]:
        raise ValueError(f"Unexpected P12314 topology: {u_p12314}")
    if not (aa_cd64t[311] == "T" and aa_cd64t[312] == "I" and prots["P12314"][313] == "R"):
        raise ValueError("CD64t C-terminal boundary T312-I313 / excised R314 check failed")
    if not (u_p12314["n_glycosylation_sites"] == 7 and u_p12314["o_glycosylation_sites"] == 0):
        raise ValueError(f"Unexpected P12314 glycosylation counts: {u_p12314}")
    if not (u_p15529["n_glycosylation_sites"] == 3 and u_p15529["o_glycosylation_sites"] == 18 and u_p15529["total_glycosylation_sites"] == 21):
        raise ValueError(f"Unexpected P15529 glycosylation counts: {u_p15529}")
    if not (u_p18510["n_glycosylation_sites"] == 1 and u_p18510["o_glycosylation_sites"] == 0):
        raise ValueError(f"Unexpected P18510 glycosylation counts: {u_p18510}")

    gravina_cmp = verify_gravina_cd64t_cds_comparison(cds_cd64t, expected_aa=aa_cd64t, check_private_xml_cache=True)
    p2_topology = {
        "CD64t_313_Gravina2023": {
            **u_p12314,
            "truncated_length_aa": 313,
            "c_terminal_residue_313": "Ile313 (staged codon ATT vs Gravina published ATA) — terminal residue of TM helix 293-313; Arg314-Tyr374 cytoplasmic domain completely deleted (NOT Arg313)",
            "stop_codon": gravina_cmp["staged_stop_codon"],
            "gravina_2023_sequence_comparison": gravina_cmp,
            "retains_all_3_ig_domains_and_tm_293_313": True,
            "cytoplasmic_tail_len_aa": 0,
            "epb41l2_4p1g_region_312_332_disposition": "Cytoplasmic 314-332 (basic HxxBxxxBB docking core RKELKRKKKWDLEISLDSG) excised; TM-end Thr312-Ile313 reside inside TM helix 293-313",
            "epb41l2_reference_pmid": "18023480",
            "fcgr_gamma_chain_association_status": "PENDING_EMPIRICAL_GATE_28B_VERIFICATION",
            "fcgr_gamma_chain_signaling_note": (
                "Tailless deletion (Arg314-Tyr374) removes direct cytosolic tail motifs, but the retained transmembrane helix (TM 293-313) "
                "can associate with the FcRgamma (FCER1G) ITAM signaling adaptor where expressed (Davis et al. 1995 PMID:7859733 / PMC398101). Absence of FcRgamma "
                "co-IP and phospho-Syk/ITAM signaling in Stage-7 SC-islets and iECs is an empirical Gate 28-B requirement, NOT an assumed boolean property."
            ),
            "cis_fc_competition_mechanism_and_tonic_saturation": (
                "At physiological 5-10 mg/mL (33-67 uM) polyclonal human IgG and Kd ~1-10 nM, ~99.97%-99.999% of surface CD64t is tonically occupied "
                "by irrelevant bulk IgG (~0.03-0.24 nmol total graft CD64t across 8e8 cells vs ~200 umol plasma IgG, ~1e6:1 ratio). Protection, if achieved, "
                "operates via cis Fc competition / steric blockade of CD16 engagement at the graft membrane rather than bulk autoantibody depletion."
            ),
            "tailless_1copy_and_2copy_hdr_surface_density_qc": (
                "REQUIRED in Gate 28-B: QuantiBRITE absolute >= 50,000 molecules/cell at calibrated t=0 and Day-90 (>=75% retention AND >=50,000 abs) "
                "reported SEPARATELY for 1-copy (monoallelic HDR, modal outcome) and 2-copy (biallelic HDR) clones, PLUS immune-complex surface half-life, "
                "soluble CD64t shedding ELISA, macrophage trogocytosis/stripping, and functional ADCC/CDC retention after 7-day 10 mg/mL IgG pre-loading."
            ),
            "kill_switch_orthogonality_gy002_gy026": "PASS — paired exclusively with small-molecule AP1903/rimiducid AAVS1-iCasp9 (ZERO IgG-Fc mAb kill-switch clash).",
        },
        "IL1RN_177_Secreted_Isoform1": {
            **u_p18510,
            "secreted_mature_length_aa": 152,
            "signal_peptide_cleavage": "1-25",
            "promoter_regime": (
                "Inducible human CD274p_250 (IFN-gamma/JAK1-2/STAT1-IRF1). Prospective OpenIslet Gate 28-B design criteria "
                "(NOT directly measured in Dror 2017, Arend 1990, or Giannoukakis 1999): unstimulated basal leak <= 5.0% of induced "
                "output (motivated by physiological mouse postprandial macrophage IL-1beta in Dror 2017 PMID:28092375, which did not "
                "measure CD274p leak) and stimulated local IL-1Ra:IL-1beta >= 100:1 molar excess (motivated by assay-specific up-to-100-fold "
                "50% inhibition in non-islet cells in Arend 1990 PMID:2139669). Carries GY-001/STAT1 epistasis risk under IFN-dampened "
                "backgrounds (e.g., TYK2 P1104A or low-IFN IL-1beta-dominant IBMIR) -> mandatory IFN-gamma titration matrix in Gate 28-B."
            ),
            "pigk_gpi_load": 0,
        },
        "CD46_WT_392_Native_Complement_HOLD_COMPARATOR": {
            **u_p15529,
            "deployment_status": "HOLD_COMPARATOR_BLOCKED_PENDING_CAND034_CD46_TROPIC_ADDENDUM",
            "glycosylation_evidence_note": "UniProt P15529 annotates 3 N-linked and 18 O-linked sites (all 18 O-linked entries carry sequence-model annotations; product glycan occupancy is unmeasured).",
            "mode_of_action": "Type-I TM cofactor for Factor I cleavage of BOTH C4b (classical/lectin IgM/IgG) and C3b (alternative pathway) -> addresses Gou 2026 PMID:41543848 IgM gap with 0 absent Swiss-Prot windows & 0 PIGK load, but HELD outside Wave-5 Go scope.",
            "viral_receptor_gate": "ARCHIVED AS HOLD-COMPARATOR: barred from advancement or manufacture until CAND-034 executable cd46_tropic_addendum (distinguishing HHV-6A vs HHV-6B, vaccine vs wild-type measles strains, and AdV-B) clears; core Gate 0V-B (CVB4/CVB3/HCMV) is NON-CITABLE as CD46_WT clearance.",
            "pigk_gpi_load": 0,
        },
        "CFH_1_264_CD55_286_381_GPI_Comparator": {
            "deployment_status": "TERTIARY_HOLD_COMPARATOR_PIGK1_REQUIRES_CTRL_CFH_CD55_ONLY",
            "cfh_uniprot_P08603_slice": "1-264 (SP 1-18 + SCR1-4 C3b/FI decay-accelerating & cofactor domain; protective Val62 rs800292 verified; 16 mature CFH Cys = 8 intact SCR1-4 disulfides)",
            "cd55_uniprot_P08174_slice": "286-381 (STP O-glycosylated stalk + GPI-anchor omega-site Ser353; Cys364 cleanly inside cleaved GPI propeptide 354-381)",
            "total_length_aa": 360,
            "pigk_gpi_load": 1,
            "advancement_control_requirement": "Advancing tertiary CFH-CD55 requires adding a matched symmetric-2CTCF CTRL_CFH_CD55_ONLY (PIGK=1) single-cargo control plus viral CVB/echovirus co-receptor check on CD55.",
            "honest_tradeoffs": [
                "Junction PSCEE|KSLTS creates 26 absent 8-11mers and 12 absent 15mers vs 20,429 human Swiss-Prot (sequence-membership counts; immunogenicity unmeasured).",
                "Adds +1 PIGK GPI-anchor cargo competing with CD47-IgV-GPI on Core A/X (PIGK titration required).",
                "Alternative-pathway (C3bBb) focused; lacks classical C4b2a cofactor cleavage provided by CD46_WT.",
            ],
        },
    }

    # Gate P3 — Swiss-Prot 20,429-protein neo-epitope scan + gnomAD v4.1 + GY-026 CR1 hold
    gnomad_v4 = json.loads((PROT_CACHE_DIR / "gnomad_v4_1_coding_variants.json").read_text(encoding="utf-8"))
    p3_swissprot = {
        "swissprot_protein_count": len(prots),
        "swissprot_gz_sha256": sp_sha,
        "pinned_sha_match": sp_sha == PINNED_SWISSPROT_SHA,
        "active_proteins": {
            "CD64t_313": scan_swissprot_peptides(aa_cd64t, sp_kmers),
            "IL1RN_177": scan_swissprot_peptides(aa_il1rn, sp_kmers),
            "CD46_WT_392": scan_swissprot_peptides(aa_cd46, sp_kmers),
            "CFH_1_264_CD55_286_381": scan_swissprot_peptides(aa_cfh_cd55, sp_kmers),
        },
        "gy026_blocked_short_stalk_cr1_audit": {
            "construct_name": "CR1_SCR1-10_TM[1-687+1970-2005]",
            "status": "HELD_BLOCKED_BY_GY026_NOT_IN_ACTIVE_FASTA",
            "aa_len": len(aa_cr1_held),
            "seam_20aa": aa_cr1_held[677:697],
            "swissprot_scan": scan_swissprot_peptides(aa_cr1_held, sp_kmers),
            "gy026_blocking_defects": [
                "Junction seam IIPNKHDAL (687|1970) verified strong HLA-C*01:02 binder (33.75 nM / EL 0.01%) and HLA-DRB1*03:01 (451.6 nM).",
                "5-aa juxtamembrane stalk (<=17.5 A) fails 49.21 A PDB 5FO9 C3b hydrolyzed-thioester Glu1013 (native Gln1013) to CR1 CCP17 C-terminus reach geometry.",
                "CR1 SCR1-3 retains P. falciparum PfRh4 binding (PMID:20855594) and SCR1-2/LHR-A binds EBV gp350 (PMID:23416052).",
            ],
        },
        "gnomad_v4_1_reference_snapshot": gnomad_v4,
    }
    if not (p3_swissprot["active_proteins"]["CD64t_313"]["foreign_8_11mers_total"] == 0):
        raise ValueError('Verification check failed: p3_swissprot["active_proteins"]["CD64t_313"]["foreign_8_11mers_total"] == 0')
    if not (p3_swissprot["active_proteins"]["IL1RN_177"]["foreign_8_11mers_total"] == 0):
        raise ValueError('Verification check failed: p3_swissprot["active_proteins"]["IL1RN_177"]["foreign_8_11mers_total"] == 0')
    if not (p3_swissprot["active_proteins"]["CD46_WT_392"]["foreign_8_11mers_total"] == 0):
        raise ValueError('Verification check failed: p3_swissprot["active_proteins"]["CD46_WT_392"]["foreign_8_11mers_total"] == 0')
    if not (p3_swissprot["active_proteins"]["CFH_1_264_CD55_286_381"]["foreign_8_11mers_total"] == 26):
        raise ValueError('Verification check failed: p3_swissprot["active_proteins"]["CFH_1_264_CD55_286_381"]["foreign_8_11mers_total"] == 26')
    if not (p3_swissprot["active_proteins"]["CFH_1_264_CD55_286_381"]["k15_foreign"] == 12):
        raise ValueError('Verification check failed: p3_swissprot["active_proteins"]["CFH_1_264_CD55_286_381"]["k15_foreign"] == 12')
    if not (p3_swissprot["gy026_blocked_short_stalk_cr1_audit"]["swissprot_scan"]["foreign_8_11mers_total"] == 34):
        raise ValueError('Verification check failed: p3_swissprot["gy026_blocked_short_stalk_cr1_audit"]["swissprot_scan"]["foreign_8_11mers_total"] == 34')

    # Gate P4 — Direct mmCIF atomic interface + exact _struct_conn glycan ownership & mutation provenance
    # In 4W4O.cif _struct_conn: D/E are covalently linked to Fc chains A/B (A:Asn297->D, B:Asn297->E),
    # whereas F/G are receptor-linked self-glycans covalently attached to chain C (C:Asn59->F, C:Asn159->G)!
    p4_4w4o = parse_mmcif_interface_contacts(
        PROT_CACHE_DIR / "4W4O.cif",
        receptor_chains={"C"},
        partner_chains={"A", "B", "D", "E"},
        cutoff_angstrom=4.5,
        include_partner_hetatm=True,
        partner_protein_chains={"A", "B"},
    )
    p4_4w4o["mmcif_provenance"] = {
        "biological_assembly_scope": "COGNATE_DEPOSITED_BIOLOGICAL_ASSEMBLY_1 (author_defined_assembly, trimeric: receptor chain C + self-glycans F/G vs cognate Fc A/B + Fc-linked glycans D/E)",
        "biological_assembly_ids": ["1"],
        "receptor_entity2_expression_host": "Spodoptera frugiperda (Baculovirus) expressing the 19-mutation stability-engineered human FCGR1A ectodomain (NOT wild-type CD64)",
        "partner_entity1_expression_host": "Commercial human IgG1 Fc (glycosylated mammalian IgG1, chains A/B with Fc-linked glycans D/E at Asn297)",
        "glycan_ownership_verified_from_struct_conn": (
            "covale1 A:ASN297->D:NAG1 & covale2 B:ASN297->E:NAG1 are Fc-linked glycans; "
            "covale3 C:ASN59->F:NAG1 & covale4 C:ASN159->G:NAG1 are receptor-linked self-glycans on chain C."
        ),
        "engineered_mutation_summary": (
            "19 declared engineered mutations on chain C (15 resolved in coordinates); within deposited Biological Assembly 1, "
            "0 in cognate Fc ATOM protein contacts, 0 in <=4.5 A Fc-linked glycan (D/E) contacts "
            "(E77 min dist to D/E = 25.756 A, D78 min dist to D/E = 31.505 A); "
            "V77E (3.357 A) and N78D (3.177 A) contact only receptor-linked self-glycans F/G on chain C."
        ),
    }
    p4_4x4m = parse_mmcif_interface_contacts(
        PROT_CACHE_DIR / "4X4M.cif",
        receptor_chains={"E"},
        partner_chains={"A", "B", "G", "H"},
        cutoff_angstrom=4.5,
        include_partner_hetatm=True,
        partner_protein_chains={"A", "B"},
    )
    p4_4x4m_asm2 = parse_mmcif_interface_contacts(
        PROT_CACHE_DIR / "4X4M.cif",
        receptor_chains={"F"},
        partner_chains={"C", "D", "I", "J", "K", "L", "M"},
        cutoff_angstrom=4.5,
        include_partner_hetatm=True,
        partner_protein_chains={"C", "D"},
    )
    if p4_4x4m_asm2["engineered_mutations_in_protein_contacts_le_4p5A"] != [] or p4_4x4m_asm2["engineered_mutations_in_fc_glycan_contacts_le_4p5A"] != []:
        raise ValueError("4X4M Biological Assembly 2 cognate contact check failed")
    asm2_glyc_atoms = p4_4x4m_asm2["partner_fc_hetatm_glycan_heavy_atoms_by_chain"]
    if not (
        asm2_glyc_atoms.get("L") == 14
        and asm2_glyc_atoms.get("M") == 10
        and (asm2_glyc_atoms.get("L", 0) + asm2_glyc_atoms.get("M", 0)) == 24
        and p4_4x4m_asm2["partner_fc_hetatm_glycan_heavy_atoms_total"] == 240
        and p4_4x4m_asm2["min_engineered_mutation_dist_to_partner_protein_A"] is not None
        and p4_4x4m_asm2["min_engineered_mutation_dist_to_partner_protein_A"] >= 7.70
        and p4_4x4m_asm2["min_engineered_mutation_dist_to_partner_glycan_A"] is not None
        and p4_4x4m_asm2["min_engineered_mutation_dist_to_partner_glycan_A"] >= 21.80
    ):
        raise ValueError(f"4X4M Biological Assembly 2 label_asym_id glycan/distance check failed: {p4_4x4m_asm2}")
    p4_4x4m["biological_assembly_2_label_asym_id_audit"] = {
        "partner_fc_hetatm_glycan_heavy_atoms_by_chain": asm2_glyc_atoms,
        "label_chains_L_and_M_heavy_atoms_sum": asm2_glyc_atoms.get("L", 0) + asm2_glyc_atoms.get("M", 0),
        "partner_fc_hetatm_glycan_heavy_atoms_total": p4_4x4m_asm2["partner_fc_hetatm_glycan_heavy_atoms_total"],
        "min_engineered_mutation_dist_to_partner_protein_A": p4_4x4m_asm2["min_engineered_mutation_dist_to_partner_protein_A"],
        "min_engineered_mutation_dist_to_partner_glycan_A": p4_4x4m_asm2["min_engineered_mutation_dist_to_partner_glycan_A"],
        "engineered_mutations_in_protein_contacts_le_4p5A": p4_4x4m_asm2["engineered_mutations_in_protein_contacts_le_4p5A"],
        "engineered_mutations_in_fc_glycan_contacts_le_4p5A": p4_4x4m_asm2["engineered_mutations_in_fc_glycan_contacts_le_4p5A"],
    }
    p4_4x4m["mmcif_provenance"] = {
        "biological_assembly_scope": "COGNATE_DEPOSITED_BIOLOGICAL_ASSEMBLIES_1_AND_2 (Assembly 1: E vs cognate Fc A/B + glycans G/H; Assembly 2: F vs cognate Fc C/D + label_asym_id glycans I/J/K/L/M including L=14 & M=10 [24 heavy atoms sharing auth_asym_id='D'])",
        "biological_assembly_ids": ["1", "2"],
        "asymmetric_unit_non_cognate_note": (
            "In the 4X4M asymmetric unit crystal lattice, engineered N163S (F:SER163 OG, Biological Assembly 2) "
            "lies 4.225 A (4.2252 A) from A:GLN438 O on non-cognate Fc chain A of Biological Assembly 1; "
            "both deposited cognate biological assemblies (1 and 2) have 0 resolved engineered positions within 4.5 A "
            "of cognate Fc protein (>=8.420 A asm1 / >=7.709 A asm2) or Fc-linked glycans (>=21.047 A asm1 / >=21.821 A asm2 including label_asym_id L+M 24 heavy atoms)."
        ),
        "receptor_entity2_expression_host": "Escherichia coli (NOT mammalian WT CD64!) expressing the 18-mutation stability-engineered human FCGR1A ectodomain (chains E/F; unglycosylated in bacteria)",
        "partner_entity1_expression_host": "Cricetulus griseus (CHO mammalian cells; glycosylated human IgG1 Fc, chains A/B/C/D with Fc glycans G/H and I/J/K/L/M)",
        "engineered_mutation_summary": "18 declared engineered mutations per FCGR1A chain (36 rows across chains E & F; 16 resolved in chain E, 16 resolved in chain F); 0 in cognate Fc protein or <=4.5 A Fc-glycan contacts in either deposited Biological Assembly 1 or Biological Assembly 2 (verified via wwPDB label_asym_id including L+M = 24 glycan heavy atoms).",
    }
    # Programmatic assertions directly verified from 4W4O.cif and 4X4M.cif!
    if not (p4_4w4o["fc_linked_glycan_chains_from_struct_conn"] == ["D", "E"]):
        raise ValueError('Verification check failed: p4_4w4o["fc_linked_glycan_chains_from_struct_conn"] == ["D", "E"]')
    if not (p4_4w4o["receptor_self_glycan_chains_from_struct_conn"] == ["F", "G"]):
        raise ValueError('Verification check failed: p4_4w4o["receptor_self_glycan_chains_from_struct_conn"] == ["F", "G"]')
    if not (p4_4w4o["receptor_chain_engineered_mutations_declared_count"] == 19):
        raise ValueError('Verification check failed: p4_4w4o["receptor_chain_engineered_mutations_declared_count"] == 19')
    if not (p4_4w4o["receptor_chain_engineered_mutations_resolved_count"] == 15):
        raise ValueError('Verification check failed: p4_4w4o["receptor_chain_engineered_mutations_resolved_count"] == 15')
    if not (p4_4w4o["engineered_mutations_in_protein_contacts_le_4p5A"] == []):
        raise ValueError('Verification check failed: p4_4w4o["engineered_mutations_in_protein_contacts_le_4p5A"] == []')
    if not (p4_4w4o["engineered_mutations_in_fc_glycan_contacts_le_4p5A"] == []):
        raise ValueError('Verification check failed: p4_4w4o["engineered_mutations_in_fc_glycan_contacts_le_4p5A"] == []')
    if not (p4_4w4o["engineered_mutations_in_receptor_self_glycan_contacts_le_4p5A"] == ["V77E", "N78D"]):
        raise ValueError('Verification check failed: p4_4w4o["engineered_mutations_in_receptor_self_glycan_contacts_le_4p5A"] == ["V77E", "N78D"]')
    if not (abs(p4_4w4o["receptor_self_glycan_contact_mutation_distances_A"]["V77E"]["min_dist_to_fc_linked_glycans_A"] - 25.756) < 0.005):
        raise ValueError('Verification check failed: abs(p4_4w4o["receptor_self_glycan_contact_mutation_distances_A"]["V77E"]["min_dist_to_fc_linked_glycans_A"] - 25.756) < 0.005')
    if not (abs(p4_4w4o["receptor_self_glycan_contact_mutation_distances_A"]["N78D"]["min_dist_to_fc_linked_glycans_A"] - 31.505) < 0.005):
        raise ValueError('Verification check failed: abs(p4_4w4o["receptor_self_glycan_contact_mutation_distances_A"]["N78D"]["min_dist_to_fc_linked_glycans_A"] - 31.505) < 0.005')
    if not (abs(p4_4w4o["receptor_self_glycan_contact_mutation_distances_A"]["V77E"]["min_dist_to_receptor_self_glycans_A"] - 3.357) < 0.005):
        raise ValueError('Verification check failed: abs(p4_4w4o["receptor_self_glycan_contact_mutation_distances_A"]["V77E"]["min_dist_to_receptor_self_glycans_A"] - 3.357) < 0.005')
    if not (abs(p4_4w4o["receptor_self_glycan_contact_mutation_distances_A"]["N78D"]["min_dist_to_receptor_self_glycans_A"] - 3.177) < 0.005):
        raise ValueError('Verification check failed: abs(p4_4w4o["receptor_self_glycan_contact_mutation_distances_A"]["N78D"]["min_dist_to_receptor_self_glycans_A"] - 3.177) < 0.005')
    if not (p4_4x4m["declared_engineered_mutation_rows_all_chains"] == 36):
        raise ValueError('Verification check failed: p4_4x4m["declared_engineered_mutation_rows_all_chains"] == 36')
    if not (p4_4x4m["receptor_chain_engineered_mutations_declared_count"] == 18):
        raise ValueError('Verification check failed: p4_4x4m["receptor_chain_engineered_mutations_declared_count"] == 18')
    if not (p4_4x4m["receptor_chain_engineered_mutations_resolved_count"] == 16):
        raise ValueError('Verification check failed: p4_4x4m["receptor_chain_engineered_mutations_resolved_count"] == 16')
    if not (p4_4x4m["engineered_mutations_in_protein_contacts_le_4p5A"] == []):
        raise ValueError('Verification check failed: p4_4x4m["engineered_mutations_in_protein_contacts_le_4p5A"] == []')
    if not (p4_4x4m["engineered_mutations_in_fc_glycan_contacts_le_4p5A"] == []):
        raise ValueError('Verification check failed: p4_4x4m["engineered_mutations_in_fc_glycan_contacts_le_4p5A"] == []')
    if not (p4_4x4m["receptor_self_glycan_chains_from_struct_conn"] == []):
        raise ValueError('Verification check failed: p4_4x4m["receptor_self_glycan_chains_from_struct_conn"] == []')

    p4_pdb = {
        "CD64_engineered_IgG1_Fc_4W4O": p4_4w4o,
        "CD64_ecoli_engineered_IgG1_Fc_glycan_4X4M": p4_4x4m,
        "IL1RN_IL1R1_1IRA": parse_mmcif_interface_contacts(PROT_CACHE_DIR / "1IRA.cif", {"A"}, {"B"}, 4.5, include_partner_hetatm=False),
        "CD46_C3b_5FO8": parse_mmcif_interface_contacts(PROT_CACHE_DIR / "5FO8.cif", {"C"}, {"A", "B"}, 4.5, include_partner_hetatm=False),
        "GY026_CR1_5FO9_C3b_TED_hydrolyzed_Glu1013_to_CCP17_Cterm_dist_A": measure_5fo9_stalk_distance(PROT_CACHE_DIR / "5FO9.cif"),
        "GY026_CR1_5FO9_B1013_note": "PDB 5FO9 B:1013 is hydrolyzed thioester Glu1013 (derived from native C3 Gln1013 per _struct_ref_seq_dif); soluble fragment C-alpha backbone proxy (49.20794 A exact, 49.21 A rounded), not a membrane-to-surface measurement.",
    }
    if not (p4_pdb["CD64_engineered_IgG1_Fc_4W4O"]["receptor_contact_min_max_auth_seq"][1] <= 313):
        raise ValueError('Verification check failed: p4_pdb["CD64_engineered_IgG1_Fc_4W4O"]["receptor_contact_min_max_auth_seq"][1] <= 313')
    if not (p4_pdb["CD64_ecoli_engineered_IgG1_Fc_glycan_4X4M"]["receptor_contact_min_max_auth_seq"][1] <= 313):
        raise ValueError('Verification check failed: p4_pdb["CD64_ecoli_engineered_IgG1_Fc_glycan_4X4M"]["receptor_contact_min_max_auth_seq"][1] <= 313')
    if not (p4_pdb["CD64_ecoli_engineered_IgG1_Fc_glycan_4X4M"]["partner_fc_hetatm_glycan_contact_pairs"] > 0):
        raise ValueError('Verification check failed: p4_pdb["CD64_ecoli_engineered_IgG1_Fc_glycan_4X4M"]["partner_fc_hetatm_glycan_contact_pairs"] > 0')
    if not (p4_pdb["CD46_C3b_5FO8"]["receptor_contact_residue_count"] > 0):
        raise ValueError('Verification check failed: p4_pdb["CD46_C3b_5FO8"]["receptor_contact_residue_count"] > 0')
    if not (p4_pdb["IL1RN_IL1R1_1IRA"]["receptor_contact_residue_count"] > 0):
        raise ValueError('Verification check failed: p4_pdb["IL1RN_IL1R1_1IRA"]["receptor_contact_residue_count"] > 0')
    if not (p4_pdb["GY026_CR1_5FO9_C3b_TED_hydrolyzed_Glu1013_to_CCP17_Cterm_dist_A"] > 45.0):
        raise ValueError('Verification check failed: p4_pdb["GY026_CR1_5FO9_C3b_TED_hydrolyzed_Glu1013_to_CCP17_Cterm_dist_A"] > 45.0')

    locus2_tests = _run_locus2_arbitration_unit_tests()
    locus2_contract = {
        "wave5_go_scope_owner_policy_lock": (
            "Wave-5 Go scope is strictly restricted to CD64t[1-313] + CD274p::IL1RN (ABX_L2_v2_CD64T_IL1RN + symmetric controls "
            "CTRL_CD64T_ONLY, CTRL_IL1RN_ONLY). ABX_L2_v2_CD64T_CD46WT_COMP & CTRL_CD46WT_ONLY are explicitly ARCHIVED as "
            "HOLD-comparators blocked from advancement or manufacture until CAND-034's executable cd46_tropic_addendum "
            "(HHV-6A vs HHV-6B, vaccine vs wild-type measles strains, AdV-B) clears; core Gate 0V-B (CVB4/CVB3/HCMV) is NON-CITABLE."
        ),
        "governing_contract_for_l1a_l1b_sequence_reuse": (
            "Autologous D1b-Auto-C v2 product IDs (ISLET1_D1_AUTO_V2_L1A_CIITA_CD64T_IL1RN, ISLET1_D1_AUTO_V2_L1B_CIITA_CD64T_CD46WT_COMPARATOR) "
            "are governed EXCLUSIVELY by IIP-0035 (DEC-114) 45-cell contract (verify_iip0035_d1b_auto_and_portfolio.py). Allogeneic Core A/B/X Mode-B "
            "product IDs (ISLET1_ABX_L2V2_*) are governed EXCLUSIVELY by CAND-031 (IIP-0041) Gate 28-B. NO DOUBLE-COUNTING: wet-lab functional evidence "
            "from autologous D1b (B2M-intact) CANNOT be credited toward allogeneic Core A/B/X (B2M-/- or HLA-C-retained) qualification or vice versa; "
            "only plasmid/AAV6 donor DNA identity QC is shared."
        ),
        "iip0031_locus2_competition_disclosure": (
            "ABX_L2_v2_* targets the exact same chr16p13.13 CIITA Exon 5 allele as shipped IIP-0031 Mode-B comparators "
            "(L2_V3_CO_PRIMARY_CD200, L2_V3_CO_PRIMARY_MANF, L2_V3_DESIGN_B_CD200/MANF, L2_V3_ALT2_CCL22)."
        ),
        "executable_winner_takes_allele_arbitration": {
            "allowed_zygosities": ["HOMOTYPIC_BIALLELIC_2COPY", "MONOALLELIC_1COPY_HDR_KO"],
            "heterotypic_half_dosage_rule": "DISALLOWED_UNLESS_SEPARATELY_QUALIFIED_AT_HALF_DOSAGE",
            "separate_1copy_qualification_mandatory": True,
            "independent_classical_and_lectin_c4b2a_required": True,
            "component_vs_full_qualification_verdicts": {
                "component_only_pass": "COMPONENT_PASS_CIITA_ARBITRATION_ONLY_PENDING_FULL_GY025",
                "full_qualification_promote": "PASS_FULL_GY025_AND_GATE28B_PROMOTE",
                "full_qualification_retain_l2v3": "PASS_FULL_GY025_AND_GATE28B_RETAIN_L2V3",
            },
            "clone_screening_cap_per_design": 96,
            "gmp_aav6_locus2_donor_family_cap": 1,
            "loser_family_disposition": "ARCHIVE_UPON_ARBITRATION_COMPLETION_NO_PARALLEL_GMP_LOTS",
            "unit_tests": locus2_tests,
        },
        "track2_b_prime_sct_compatibility": "INCOMPATIBLE_AT_LOCUS_2 (fail-closed enforced in evaluate_ciita_locus2_arbitration per GY-025).",
        "restored_gy023_gy025_y07_y08_humoral_and_density_thresholds": {
            "quantibrite_calibrated_density_floor": ">= 50,000 CD64t molecules/cell at calibrated t=0 AND Day-90 (>= 75% retention vs t=0 AND >= 50,000 abs) verified SEPARATELY on 1-copy monoallelic AND 2-copy biallelic clones",
            "independent_sampling_denominators": "n >= 6 independent ZnT8ecA+/TSPAN7A+ T1D human sera x n >= 3 primary human CD16+ NK/PBMC donors x n >= 3 independent Stage-7 differentiations",
            "intact_serum_total_cd16_adcc_u95_t_pct": "<= 5.0% (NOT <= 10%)",
            "paired_igg_attributable_cd16_adcc_u95_t_pct": "<= 5.0% (NOT <= 10%)",
            "complement_ap_c5b9_and_20pct_nhs_u95_t_pct": "<= 5.0%",
            "classical_and_lectin_c4b2a_two_sided_rule": "BOTH independent classical (C1q/sensitized) AND lectin (MBL/mannan) C4b2a intervals required per owning GY-025: U95_t <= 10.0% PASS on both; L95_t > 10.0% on either FAIL_HARD_STOP; L95_t <= 10.0% < U95_t on either -> HOLD_UNDERPOWERED_EXPAND_N",
            "mandatory_subgates": [
                "Non-DTT IgM-preserved T1D serum + IgG2 + 5-10 mg/mL polyclonal human IgG saturation (cis-Fc competition mechanism)",
                "CD64t turnover panel: immune-complex surface half-life, soluble CD64t shedding ELISA, macrophage trogocytosis/stripping, and functional ADCC/CDC pass after 7-day pre-loading in 10 mg/mL polyclonal IgG",
                "Pending empirical FcRgamma (FCER1G) co-IP & phospho-Syk/ITAM negative check + baseline FCER1G RNA/protein audit",
                "CD274p::IL1RN IFN-gamma titration matrix (0, 0.5, 2, 10, 50 ng/mL IFN-gamma at fixed IL-1beta + hIAPP, plus TYK2 P1104A het/hom background cross-linked to GY-001)",
                "Combination macrophage efferocytosis & necrotic debris-clearance guard (exact-stack >= 80.0% abs and >= 70.0% WT per GY-025/GY-010)",
            ],
        },
        "mandatory_gy025_standing_criteria_full_traceability": [
            "GY-025 status remains PENDING until exact-product wet-lab qualification clears (exploratory bulk-kill micro-screen is distinct from full product-switch qualification)",
            "PLVAP+ iEC morphogenesis and viability: t50 <= 36.0 h AND viability >= 85.0%",
            "Exact-stack macrophage efferocytosis: >= 80.0% absolute AND >= 70.0% matched WT",
            "Gate 0G pericyte retention/viability: >= 70.0%",
            "CIITA Exon 5 (78 bp, divisible by 3) Ex4->Ex6 in-frame skipping audit + quantitative KI/KO informative transcript recovery",
            "16p13.13 cis sentinel 90% TOST equivalence (SOCS1, DEXI, CLEC16A) + lineage-matched WT Stage-7 HLA-DR/DP/DQ IFN-gamma inducibility >= 50%",
            "Promoter-specific 5'-RACE (>= 3,689 effective UMIs) + 3'-RACE verifying polyadenylation cleavage efficiency of mutated HGAPDH_PA_HARD (pos 11, 59, 92 [+19 nt past AATAAA], 115) and HPRT1_PA_HARD (pos 48, 85, 138)",
            "Stage 0-7 CpG methylation & CTCF ChIP across HOXA_CTCF_C5_80 and DM1_RC80",
            "Reconciled AAV6 packaged species (>= 80% monomer, < 10% truncated, <= 15% dimer summing to 100%)",
        ],
    }

    return {
        "fasta_filename": FASTA_OUT.name,
        "fasta_sha256": fasta_sha,
        "active_construct_count": len(p1_audits),
        "single_cargo_controls_2ctcf_symmetric": True,
        "gy023_gy025_gy026_strictly_enforced": True,
        "shared_ciita_arms_byte_identical_to_iip0031_and_iip0035": True,
        "locus2_arbitration_and_graveyard_contract": locus2_contract,
        "gate_p1_constructs": p1_audits,
        "gate_p2_topology_and_disulfides": p2_topology,
        "gate_p3_swissprot_and_gnomad": p3_swissprot,
        "gate_p4_experimental_pdb_interfaces": p4_pdb,
    }


# =============================================================================
# PART C — ZERO-EDIT (K=0) SIGLEC-7/-9 GLYCOENGINEERING & ST6GAL1 CONTRAST
# =============================================================================
def analyze_part_c_siglec_glycoengineering(sp_kmers: dict[int, set[str]]) -> dict[str, Any]:
    qtag = "GQQQLGGGGG"
    qtag_scan = {
        "peptide": qtag,
        "length_aa": len(qtag),
        "k8_total": len(qtag) - 7,
        "k8_foreign_vs_20429_swissprot": sum(1 for i in range(len(qtag) - 7) if qtag[i : i + 8] not in sp_kmers[8]),
        "k9_total": len(qtag) - 8,
        "k9_foreign_vs_20429_swissprot": sum(1 for i in range(len(qtag) - 8) if qtag[i : i + 9] not in sp_kmers[9]),
        "k10_total": 1,
        "k10_foreign_vs_20429_swissprot": int(qtag not in sp_kmers[10]),
        "foreign_9mers": [qtag[i : i + 9] for i in range(len(qtag) - 8) if qtag[i : i + 9] not in sp_kmers[9]],
    }

    # First-order exponential endothelial/beta-cell glycocalyx turnover retention model
    # Rana 2026 PMC13668765 P[9] / Fig. S14A-B observed progressive drop over 48h after rewarming
    half_lives_h = [12.0, 24.0, 36.0, 48.0, 72.0]
    timepoints_days = [2.0, 7.0, 14.0, 28.0, 90.0]
    turnover_table = []
    for hl in half_lives_h:
        row: dict[str, Any] = {"half_life_hours": hl}
        for d in timepoints_days:
            frac = 0.5 ** ((d * 24.0) / hl)
            row[f"day_{int(d)}_retained_pct"] = round(100.0 * frac, 4)
        # Hours until surface coverage drops below 10% (EC10 functional floor)
        row["days_to_10pct_remaining"] = round((hl * math.log2(10.0)) / 24.0, 2)
        turnover_table.append(row)

    return {
        "comparator_classification": "RESEARCH_COMPARATOR_ONLY_BOUNDED_DAY_0_TO_14_WINDOW_UNVALIDATED_FOR_ISLETS",
        "genetic_edit_cost_delta_k": 0,
        "assigned_permanent_graveyard_rule": {
            "guardrail_id": "OFFGRID_GUARD_019_ECTOPIC_ST6GAL1_SIALYLTRANSFERASE_NONSPECIFIC_GLYCAN_REMODELING",
            "graveyard_card_id": "GY-029",
            "severity_level": "BLOCK",
            "wave5_collision_check": "ZERO_COLLISION_CAND034_TAKES_GY030",
        },
        "primary_source": {
            "pmid": "42875686",
            "pmcid": "PMC13668765",
            "license": "CC-BY 4.0",
            "journal": "Adv Sci (Weinh)",
            "year": 2026,
            "chemistry": "Linear polyglycerol (LPG, 14.5 kDa) functionalized with 8% 2,3-sialyllactose (LQS8%, 0.56-1.5 mM) + synthetic peptide Q-tag GQQQLGGGGG covalently ligated to endothelial surface lysines via guinea-pig tissue transglutaminase (gtTGase, 60 min at 4 C in UW preservation solution).",
            "verified_in_vivo_endpoints": {
                "mouse_aorta_balbc_to_c57bl6": "Day 2 (~94% neutrophil reduction), Day 5, Day 15 (~63-67% Mac-3+ macrophage reduction; NKp46+ unchanged). Study terminated at Day 15.",
                "rat_kidney_aci_to_lewis_no_is": "Day 7 endpoint only (attenuated C4d, CD3/CD8 T cells, ATN, microvascular inflammation at 1.5 mM).",
                "in_vitro_stability_pmc13668765_p9_figs14": "Fluorescently labeled polymer tracked ONLY 48 h post-rewarming (progressive signal decline and supernatant release); fluorescence persistence does NOT establish duration of immune function or a demonstrated 14-day protective window.",
                "author_explicit_limitation_p60": "Authors explicitly state durability/longer-term retention under endothelial turnover and delayed humoral anti-conjugate immune responses were NOT evaluated; HLA-E was NOT measured and Fig. S20 leaves steric masking vs altered expression unresolved.",
            },
        },
        "surface_turnover_half_life_sensitivity": turnover_table,
        "qtag_swissprot_immunogenicity_audit": qtag_scan,
        "split_gate_28c_contract": {
            "operational_verifier_enforcement_status": "PRESPECIFIED_RESEARCH_CRITERIA_NOT_YET_WIRED_TO_LIMS_OR_RUNTIME_VERIFIER",
            "gate_28_c0_precell_biochemical_kill_fast": {
                "scope": "Prespecified research comparator criterion (not yet wired to an operational LIMS/runtime record evaluator); execute FIRST before any SC-islet or iEC expenditure.",
                "requirement": (
                    "Empirically verify GMP recombinant human TGM2 (required on its own terms by DEC-120 Gate 28-C0 to exclude "
                    "guinea-pig gtTGase; GY-013 is cited strictly as xenogeneic-protein rationale, as GY-013's standing rule governs catalase) "
                    "achieves >= 50% transamidation conversion of GQQQLGGGGG at 4 C in UW preservation buffer relative to a 37 C Ca2+-activated "
                    "positive control across n >= 3 independent enzyme lots (NH3/isopeptide assay), PLUS <= LOQ residual enzyme washout QC."
                ),
            },
            "gate_28_c1_cellular_titration_only_if_c0_passes": {
                "scope": "Prespecified research comparator criterion (not yet wired to an operational LIMS/runtime record evaluator); executed ONLY if linked Gate 28-C0 provenance passes.",
                "required_linked_c0_provenance_schema": [
                    "c0_record_sha256",
                    "c0_issuer_authority_id",
                    "rhtgm2_supplier_and_grade",
                    "enzyme_lot_ids",
                    "per_lot_conversion_pct_4c_uw_vs_37c_ca2_ctrl",
                    "washout_assay_method",
                    "washout_loq_value_and_units",
                    "per_lot_residual_rhtgm2_after_washout",
                    "washout_determination_protocol_id",
                ],
                "steric_masking_vs_expression_controls": (
                    "Explicitly resolve steric masking vs altered surface expression (matched pre-/post-ligation flow + non-competing/intracellular/mRNA controls) "
                    "using Fc-silent LALAPG or F(ab')2/Fab probes for SIRPalpha (CD47), NKG2A/CD94 (HLA-E — explicitly measured since Rana 2026 did not measure HLA-E), "
                    "and anti-CD64 Fab (preventing Fc-tagged probe confounding on CD64t+ cells)."
                ),
                "numeric_functional_and_safety_thresholds": (
                    "Titrate 0.1-1.5 mM LQS8% across n >= 3 primary human PBMC/NK donors and n >= 3 human sera on Stage-7 SC-islets and iECs. "
                    "Hard kill-switch if NO dose simultaneously achieves: (a) >= 50% reduction in human serum C3b deposition AND >= 50% reduction in "
                    "primary human PBMC/NK cytotoxicity vs matched sham-UW vehicle, (b) >= 85% retention of accessible CD47, HLA-E, and CD64t, "
                    "(c) dynamic perifusion GSIS >= 90% of matched sham-UW-treated Stage-7 SC-islet control, AND (d) exact-stack macrophage efferocytosis "
                    "debris-clearance guard (>= 80.0% abs, >= 70.0% WT)."
                ),
                "in_vivo_only_humoral_note": (
                    "Anti-LPG / anti-Q-tag (GQQQLGGGGG) IgG/IgM seroconversion is REMOVED from the in-vitro Stage-0 panel (vacuous in vitro) "
                    "and gated strictly on any future immunocompetent/humanized-mouse or NHP in-vivo arm if 28-C0 and 28-C1 both pass."
                ),
            },
        },
        "four_mandatory_veto_gates": [
            {
                "gate_id": "SIGLEC_VETO_1_CD47_AND_HLA_E_STERIC_MASKING_VS_EXPRESSION",
                "finding": "Rana 2026 PMC13668765 P[20]/P[23] & Fig. S20 observed progressively lower antibody-accessible CD47 and HLA-A,B,C signals on TNF-alpha-activated EA.hy926 cells across the protective 1.0-1.5 mM LQS8% dose window without resolving altered expression vs steric masking, and did NOT measure HLA-E.",
                "release_criterion": "Gate 28-C1 titration (0.1-1.5 mM) using Fc-silent/Fab probes proving >= 50% C3b reduction AND >= 50% PBMC/NK cytotoxicity reduction while retaining >= 85% accessible CD47, HLA-E, and CD64t without expression loss.",
            },
            {
                "gate_id": "SIGLEC_VETO_2_XENO_ENZYME_RHTGM2_4C_UW_FEASIBILITY_AND_QTAG_IMMUNOGENICITY",
                "finding": (
                    f"Protocol uses guinea-pig liver gtTGase (disallowed for Gate 28-C0 by DEC-120; GY-013 is cited strictly as "
                    f"xenogeneic-protein rationale because GY-013 governs catalase) plus synthetic Q-tag {qtag} "
                    f"({qtag_scan['k8_foreign_vs_20429_swissprot']}/{qtag_scan['k8_total']} absent 8-mers, "
                    f"{qtag_scan['k9_foreign_vs_20429_swissprot']}/{qtag_scan['k9_total']} absent 9-mers vs 20,429 human Swiss-Prot). "
                    f"Recombinant human TGM2 is tightly Ca2+-gated/GTP-inhibited and unproven at 4 C in UW buffer."
                ),
                "release_criterion": "Gate 28-C0 pre-cell biochemical proof of GMP rhTGM2 >= 50% ligation at 4 C in UW buffer (n >= 3 lots) + <= LOQ residual enzyme washout QC; anti-LPG/anti-Q-tag seroconversion gated in future in-vivo studies only.",
            },
            {
                "gate_id": "SIGLEC_VETO_3_ZERO_ISLET_GSIS_OR_ENDOCRINE_DATA",
                "finding": "PMC13668765 contains ZERO pancreatic islet, SC-islet, or GSIS data (exclusively vascular EA.hy926/HUVEC, mouse aorta, rat kidney).",
                "release_criterion": "Scope strictly as research comparator (preferentially on co-transplanted iEC vasculature) OR verify static + dynamic perifusion GSIS >= 90% of matched sham-UW-treated Stage-7 SC-islet control.",
            },
            {
                "gate_id": "SIGLEC_VETO_4_GENETIC_ST6GAL1_PERMANENTLY_BARRED_GY029",
                "finding": "Bhalerao et al. 2023 (JCI Insight; PMID:37643018, PMC10619436) is an oncogenic mouse GEMM / human PDAC xenograft result: (i) in KRASG12D GEMMs (KSC vs KC, n=10/group, P<0.0001), pancreatic ST6GAL1 OE cut median survival -68.4% (13.6 to 4.3 months, 3.16x shorter), with 5/9 adenocarcinoma and 6/9 metastases at 20 wk vs 0/9 KC; (ii) in nonmalignant WT-KRAS SC vs WT mice (wk20, n=3/group, Fig. 3D), ST6GAL1 upregulated EGFR (NES=2.22, FDR=0.003), MET (NES=2.04, FDR=0.010), and SOX9 networks; (iii) in human Suit2 PDAC xenografts (n=7/group), ST6GAL1 OE accelerated tumor growth/metastasis. Retained as a precautionary permanent disqualification without claiming a measured human graft cancer rate.",
                "release_criterion": "Assigned permanent Graveyard rule OFFGRID_GUARD_019_ECTOPIC_ST6GAL1_SIALYLTRANSFERASE_NONSPECIFIC_GLYCAN_REMODELING (GY-029; zero collision with CAND-034 GY-030): genetic ST6GAL1 overexpression is permanently barred in pancreatic/SC-islet grafts.",
            },
        ],
    }


# =============================================================================
# PART D — EXACT OQ-016 2^12 CORE 3-ARM & 2^20 5-ARM PORTFOLIO ODDS
# =============================================================================
def eval_5arm_generalized_exact(
    label: str,
    *,
    c1: float,
    pa: tuple[float, float, float, float],
    pb: tuple[float, float, float, float],
    px: tuple[float, float, float, float],
    p_y: tuple[float, float, float, float],
    p_d1: tuple[float, float, float, float],
    c2_abx: float = 0.87,
    c2_y: float = 0.87,
    c2_univ: float = 0.95,
    c2_auto: float = 0.93,
    c3_abx: float = 0.89,
    c3_y: float = 0.89,
    phi_yx: float = 0.75,
    phi_c: float = 0.25,
    c4_univ: float = 0.92,
    c4_r3: float = 0.85,
) -> dict[str, Any]:
    """
    Exact 2^20 (32-state per hurdle) 5-arm portfolio evaluator using OpenIslet's exact
    rank_islet1_stacks.py Fréchet primitives + registered-route-only DP kernel,
    with fail-closed domain, ceiling-ordering, nonnegativity, and event-ceiling validation
    (rejecting reversed nested H2/H3/H4 ceilings or negative probability masses via ValueError!).
    """
    tol = 1e-12
    all_scalars = [
        ("c1", c1), ("c2_abx", c2_abx), ("c2_y", c2_y), ("c2_univ", c2_univ), ("c2_auto", c2_auto),
        ("c3_abx", c3_abx), ("c3_y", c3_y), ("phi_yx", phi_yx), ("phi_c", phi_c), ("c4_univ", c4_univ), ("c4_r3", c4_r3),
    ]
    for nm, val in all_scalars:
        if not isinstance(val, (int, float)) or isinstance(val, bool) or not math.isfinite(val):
            raise ValueError(f"{label}: non-finite scalar {nm}={val!r}")
        if not (0.0 <= val <= 1.0):
            raise ValueError(f"{label}: scalar {nm}={val} outside [0, 1]")
    for nm in ("c1", "c2_abx", "c2_y", "c2_univ", "c2_auto", "c3_abx", "c3_y", "c4_univ", "c4_r3"):
        if dict(all_scalars)[nm] <= 0.0:
            raise ValueError(f"{label}: denominator ceiling {nm} must be > 0")
    arms = [pa, pb, px, p_y, p_d1]
    arm_names = ("pa", "pb", "px", "p_y", "p_d1")
    for anm, avec in zip(arm_names, arms):
        if len(avec) != 4:
            raise ValueError(f"{label}: arm {anm} must have 4 hurdle probabilities")
        for h_i, v in enumerate(avec):
            if not isinstance(v, (int, float)) or isinstance(v, bool) or not math.isfinite(v) or not (0.0 <= v <= 1.0):
                raise ValueError(f"{label}: arm {anm}[{h_i}]={v!r} outside finite [0, 1]")
    # Strict zero-tolerance ceiling-ordering & marginal-vs-ceiling checks (ZERO 1e-12 slack on impossible orderings!)
    if c2_abx > c2_y:
        raise ValueError(f"{label}: reversed nested H2 ceilings rejected (c2_abx={c2_abx} > c2_y={c2_y})")
    if c2_y > c2_univ or c2_auto > c2_univ:
        raise ValueError(f"{label}: H2 sub-ceiling exceeds c2_univ ({c2_y}, {c2_auto} vs {c2_univ})")
    if c3_abx > c3_y:
        raise ValueError(f"{label}: reversed nested H3 ceilings rejected (c3_abx={c3_abx} > c3_y={c3_y})")
    if c4_r3 > c4_univ or 0.85 > c4_univ:
        raise ValueError(f"{label}: H4 sub-ceiling exceeds c4_univ (c4_r3={c4_r3}, 0.85 vs c4_univ={c4_univ})")
    # Strict arm marginal vs ceiling checks (zero upward slack!)
    if any(v[0] != c1 for v in (pa, pb, px, p_y)) or p_d1[0] > c1:
        raise ValueError(f"{label}: H1 marginal violates c1={c1}")
    if any(v[1] > c2_abx for v in (pa, pb, px)) or p_y[1] > c2_y or p_d1[1] > c2_auto:
        raise ValueError(f"{label}: H2 marginal exceeds assigned ceiling")
    if any(v[2] > c3_abx for v in (pa, pb, px)) or p_y[2] > c3_y or p_d1[2] > c3_y:
        raise ValueError(f"{label}: H3 marginal exceeds assigned ceiling")
    if any(v[3] > 0.85 for v in (pa, pb, px)) or p_y[3] > c4_r3 or p_d1[3] > c4_r3:
        raise ValueError(f"{label}: H4 marginal exceeds assigned ceiling")

    # H1 (32 states: bit0=A, bit1=B, bit2=X, bit3=Y, bit4=D1b)
    u_d1 = p_d1[0] / c1
    d1 = [0.0] * 32
    d1[0] = 1.0 - c1
    d1[15] = c1 * (1.0 - u_d1)
    d1[31] = c1 * u_d1

    # H2
    d2_inc = rank_mod._frechet_bernoulli_joint_iip0034([pa[1] / c2_abx, pb[1] / c2_abx, px[1] / c2_abx], 0.0)
    r2 = c2_abx / c2_y
    u_y2 = p_y[1] / c2_y
    d2_both = rank_mod._frechet_couple_new_arm_iip0034(d2_inc, u_y2, phi_yx, lambda mi: bool(mi & 4))
    d2_allo4 = [0.0] * 16
    for k in range(16):
        d2_allo4[k] += r2 * d2_both[k]
    d2_allo4[0] += (1.0 - r2) * (1.0 - u_y2)
    d2_allo4[8] += (1.0 - r2) * u_y2

    biv2 = rank_mod._bivariate_bernoulli_iip0034(c2_y / c2_univ, c2_auto / c2_univ, phi_c)
    u_d2 = p_d1[1] / c2_auto
    d2 = [0.0] * 32
    d2[0] += 1.0 - c2_univ
    for (s0, s1), wp in biv2.items():
        w = c2_univ * wp
        if s0 == 0 and s1 == 0:
            d2[0] += w
        elif s0 == 1 and s1 == 0:
            for m4 in range(16):
                d2[m4] += w * d2_allo4[m4]
        elif s0 == 0 and s1 == 1:
            d2[0] += w * (1.0 - u_d2)
            d2[16] += w * u_d2
        else:
            for m4 in range(16):
                d2[m4] += w * d2_allo4[m4] * (1.0 - u_d2)
                d2[m4 | 16] += w * d2_allo4[m4] * u_d2
    c2_e = c2_univ * (1.0 - biv2[(0, 0)])

    # H3 (nested autoAb shock r3 = c3_abx / c3_y so asymmetric A/B/X-only gap works cleanly!)
    d3_inc = rank_mod._frechet_bernoulli_joint_iip0034([pa[2] / c3_abx, pb[2] / c3_abx, px[2] / c3_abx], 0.0)
    r3 = c3_abx / c3_y
    u_y3 = p_y[2] / c3_y
    d3_both = rank_mod._frechet_couple_new_arm_iip0034(d3_inc, u_y3, phi_yx, lambda mi: bool(mi & 4))
    d3_allo4 = [0.0] * 16
    for k in range(16):
        d3_allo4[k] += r3 * d3_both[k]
    d3_allo4[0] += (1.0 - r3) * (1.0 - u_y3)
    d3_allo4[8] += (1.0 - r3) * u_y3
    d3_5cond = rank_mod._frechet_couple_new_arm_iip0034(d3_allo4, p_d1[2] / c3_y, phi_c, lambda m4: m4 != 0)
    d3 = [0.0] * 32
    d3[0] += 1.0 - c3_y
    for k in range(32):
        d3[k] += c3_y * d3_5cond[k]
    c3_e = c3_y

    # H4 (A/X on R1, B on R2, Y & D1b on R3P — registered-route-only!)
    d4_inc = rank_mod._live_incumbent_h4_cond_iip0034()
    biv4 = rank_mod._bivariate_bernoulli_iip0034(0.85 / c4_univ, c4_r3 / c4_univ, phi_c)
    d4 = [0.0] * 32
    d4[0] += 1.0 - c4_univ
    d4_r3 = rank_mod._frechet_bernoulli_joint_iip0034([p_y[3] / c4_r3, p_d1[3] / c4_r3], 1.0)
    for (s0, s1), wp in biv4.items():
        w = c4_univ * wp
        if s0 == 0 and s1 == 0:
            d4[0] += w
        elif s0 == 1 and s1 == 0:
            for m3 in range(8):
                d4[m3] += w * d4_inc[m3]
        elif s0 == 0 and s1 == 1:
            for mr in range(4):
                m5 = ((mr & 1) << 3) | (((mr >> 1) & 1) << 4)
                d4[m5] += w * d4_r3[mr]
        else:
            for m3 in range(8):
                for mr in range(4):
                    m5 = m3 | ((mr & 1) << 3) | (((mr >> 1) & 1) << 4)
                    d4[m5] += w * d4_inc[m3] * d4_r3[mr]
    c4_e = c4_univ * (1.0 - biv4[(0, 0)])

    # Fail-closed probability-domain, STRICT zero-tolerance nonnegativity (< 0.0), event-ceiling, & exact 20-marginal recovery verification
    dists = [d1, d2, d3, d4]
    h_ceils = [c1, c2_e, c3_e, c4_e]
    for h in range(4):
        dh = dists[h]
        min_w = min(dh)
        if min_w < 0.0:
            raise ValueError(f"{label}: negative probability mass detected in H{h+1}: min={min_w}")
        if abs(sum(dh) - 1.0) > tol:
            raise ValueError(f"{label}: H{h+1} does not normalize to 1.0 (sum={sum(dh)})")
        if (1.0 - dh[0]) > h_ceils[h] + tol:
            raise ValueError(f"{label}: H{h+1} union event probability {1.0 - dh[0]} exceeds hurdle ceiling {h_ceils[h]}")
        for i in range(5):
            marg = sum(w for m, w in enumerate(dh) if (m & (1 << i)))
            if abs(marg - arms[i][h]) > tol:
                raise ValueError(f"{label} H{h+1} arm {i} marginal mismatch: {marg} vs {arms[i][h]}")

    # Exact DP for H1..H3 survivor masks + H4 registered-route-only modular & locked union
    c_classes = ("UNHARDENED_A_B_X", "UNHARDENED_A_B_X", "UNHARDENED_A_B_X", "DESIGN_Y_FULLSTACK_V2", "D1B_AUTO_C_V2")
    r_ids = ("R1", "R2", "R1", "R3P", "R3P")
    reg_compat = {
        "UNHARDENED_A_B_X": frozenset({"R1", "R2"}),
        "DESIGN_Y_FULLSTACK_V2": frozenset({"R3P"}),
        "D1B_AUTO_C_V2": frozenset({"R3P"}),
    }

    v = [0.0] * 32
    v[31] = 1.0
    for h in range(3):
        dh = dists[h]
        vn = [0.0] * 32
        for s, vs in enumerate(v):
            if vs == 0.0:
                continue
            for mh, w in enumerate(dh):
                if w != 0.0:
                    vn[s & mh] += vs * w
        v = vn
    v_h123 = v

    v_all = [0.0] * 32
    for s, vs in enumerate(v_h123):
        if vs == 0.0:
            continue
        for mh, w in enumerate(d4):
            if w != 0.0:
                v_all[s & mh] += vs * w

    locked_reg = 1.0 - v_all[0]  # all 5 assigned routes are registered-compatible
    mod100_reg = 0.0
    for m_cell in range(1, 32):
        wc = v_h123[m_cell]
        if wc == 0.0:
            continue
        allowed_r: set[str] = set()
        for i in range(5):
            if m_cell & (1 << i):
                allowed_r |= reg_compat[c_classes[i]]
        for m_h4 in range(1, 32):
            wh = d4[m_h4]
            if wh == 0.0:
                continue
            if any(r_ids[j] in allowed_r for j in range(5) if (m_h4 & (1 << j))):
                mod100_reg += wc * wh
    mod90_reg = 0.90 * mod100_reg + 0.10 * locked_reg
    ceiling_5arm = c1 * c2_e * c3_e * c4_e

    return {
        "scenario": label,
        "params": {
            "c1": c1, "c3_abx": c3_abx, "c3_y_d1": c3_y, "phi_c": phi_c, "phi_yx": phi_yx, "c4_univ": c4_univ,
            "pa": list(pa), "pb": list(pb), "px": list(px), "p_y": list(p_y), "p_d1": list(p_d1),
        },
        "locked_pct": round(100.0 * locked_reg, 4),
        "modular_k100_pct": round(100.0 * mod100_reg, 4),
        "modular_k90_pct": round(100.0 * mod90_reg, 4),
        "ceiling_pct": round(100.0 * ceiling_5arm, 4),
        "locked_exact": locked_reg,
        "modular_k100_exact": mod100_reg,
        "ceiling_exact": ceiling_5arm,
    }


def eval_3arm_2pow12_unrounded(
    pa: tuple[float, float, float, float],
    pb: tuple[float, float, float, float],
    px: tuple[float, float, float, float],
    c_vec: tuple[float, float, float, float],
) -> tuple[float, float, float]:
    """Exact unrounded 2^12 (4,096-state) shared-A/X 2-route 3-arm tree matching rank_islet1_stacks.py without 9-dp rounding."""
    def _h_ind(h: int) -> list[float]:
        ch = c_vec[h]
        if h == 0:
            d = [0.0] * 8
            d[0] = 1.0 - ch
            d[7] = ch
            return d
        ua, ub, ux = pa[h] / ch, pb[h] / ch, px[h] / ch
        d = [0.0] * 8
        d[0] += 1.0 - ch
        for m in range(8):
            d[m] += ch * (ua if (m & 1) else (1.0 - ua)) * (ub if (m & 2) else (1.0 - ub)) * (ux if (m & 4) else (1.0 - ux))
        return d

    c4 = c_vec[3]
    ua4, ub4, ux4 = pa[3] / c4, pb[3] / c4, px[3] / c4
    p11 = min(ua4, ux4)
    p10 = max(0.0, ua4 - ux4)
    p01 = max(0.0, ux4 - ua4)
    p00 = 1.0 - max(ua4, ux4)
    d4_sh = [0.0] * 8
    d4_sh[0] += 1.0 - c4
    for (ab, xb), pax in (((0, 0), p00), ((1, 0), p10), ((0, 1), p01), ((1, 1), p11)):
        for bb, pbv in ((0, 1.0 - ub4), (1, ub4)):
            d4_sh[ab | (bb << 1) | (xb << 2)] += c4 * pax * pbv

    d0, d1, d2 = _h_ind(0), _h_ind(1), _h_ind(2)
    any_h123 = 0.0
    locked_sh = 0.0
    for m0 in range(8):
        p0 = d0[m0]
        if p0 == 0.0:
            continue
        for m1 in range(8):
            p01 = p0 * d1[m1]
            s1 = m0 & m1
            if p01 == 0.0 or s1 == 0:
                continue
            for m2 in range(8):
                s2 = s1 & m2
                if s2 == 0:
                    continue
                p012 = p01 * d2[m2]
                if p012 == 0.0:
                    continue
                any_h123 += p012
                for m3 in range(8):
                    if (s2 & m3) != 0 and d4_sh[m3] != 0.0:
                        locked_sh += p012 * d4_sh[m3]

    pouch_2route = c4 * (1.0 - (1.0 - max(ua4, ux4)) * (1.0 - ub4))
    mod_2route = any_h123 * pouch_2route
    ceil_ex = c_vec[0] * c_vec[1] * c_vec[2] * c_vec[3]
    return locked_sh, mod_2route, ceil_ex


def run_portfolio_domain_guard_tests() -> dict[str, Any]:
    """Fail-closed unit tests verifying reversed nested ceilings (even at 5e-13!) and invalid probability domains raise ValueError."""
    pa0 = (0.88, 0.78, 0.57, 0.69)
    pb0 = (0.88, 0.79, 0.64, 0.70)
    px0 = (0.88, 0.82, 0.73, 0.69)
    py0 = (0.88, 0.84, 0.80, 0.72)
    pd1_0 = (0.62, 0.92, 0.70, 0.70)
    bad_cases = [
        (
            "reversed_nested_h2_ceiling_0p88_gt_0p87",
            dict(
                c1=0.88,
                pa=(0.88, 0.88, 0.57, 0.69), pb=(0.88, 0.88, 0.64, 0.70), px=(0.88, 0.88, 0.73, 0.69),
                p_y=(0.88, 0.87, 0.80, 0.72), p_d1=pd1_0, c2_abx=0.88, c2_y=0.87,
            ),
        ),
        (
            "micro_epsilon_reversed_h2_ceiling_0p8700000000005_gt_0p87_at_caps",
            dict(
                c1=0.88,
                pa=(0.88, 0.8700000000005, 0.57, 0.69),
                pb=(0.88, 0.8700000000005, 0.64, 0.70),
                px=(0.88, 0.8700000000005, 0.73, 0.69),
                p_y=(0.88, 0.87, 0.80, 0.72),
                p_d1=pd1_0,
                c2_abx=0.8700000000005,
                c2_y=0.87,
            ),
        ),
        (
            "reversed_nested_h3_ceiling_0p90_gt_0p89",
            dict(c1=0.88, pa=pa0, pb=pb0, px=px0, p_y=py0, p_d1=pd1_0, c3_abx=0.90, c3_y=0.89),
        ),
        (
            "micro_epsilon_reversed_h3_ceiling_0p8900000000005_gt_0p89",
            dict(c1=0.88, pa=pa0, pb=pb0, px=px0, p_y=py0, p_d1=pd1_0, c3_abx=0.8900000000005, c3_y=0.89),
        ),
        (
            "marginal_exceeds_ceiling_h2",
            dict(c1=0.88, pa=(0.88, 0.90, 0.57, 0.69), pb=pb0, px=px0, p_y=py0, p_d1=pd1_0),
        ),
        (
            "out_of_range_phi_gt_1",
            dict(c1=0.88, pa=pa0, pb=pb0, px=px0, p_y=py0, p_d1=pd1_0, phi_c=1.05),
        ),
        (
            "non_finite_nan_c1",
            dict(c1=float("nan"), pa=pa0, pb=pb0, px=px0, p_y=py0, p_d1=pd1_0),
        ),
    ]
    results = []
    for cname, kw in bad_cases:
        raised = False
        err_msg = ""
        try:
            eval_5arm_generalized_exact(f"TEST_{cname}", **kw)
        except ValueError as exc:
            raised = True
            err_msg = str(exc)
        if not raised:
            raise RuntimeError(f"Domain guard FAILED to reject {cname}!")
        results.append({"case": cname, "rejected_with_ValueError": True, "error": err_msg})
    return {"total_negative_tests": len(results), "all_rejected_fail_closed": True, "cases": results}


def analyze_part_d_portfolio_odds() -> dict[str, Any]:
    domain_guard_tests = run_portfolio_domain_guard_tests()

    # 1. Live baseline parity check directly via OpenIslet rank_islet1_stacks.py!
    pa0 = (0.88, 0.78, 0.57, 0.69)
    pb0 = (0.88, 0.79, 0.64, 0.70)
    px0 = (0.88, 0.82, 0.73, 0.69)
    py0 = (0.88, 0.84, 0.80, 0.72)
    pd1_0 = (0.62, 0.92, 0.70, 0.70)
    c0_vec = (0.88, 0.87, 0.89, 0.85)

    live_3arm = rank_mod.compute_common_shock_2pow12_portfolio_tree(pa0, pb0, px0, c0_vec)
    live_5arm_bundle = rank_mod.compute_5arm_autologous_portfolio_iip0035(OPENISLET_ROOT)
    wu3_live = next(r for r in live_5arm_bundle["stage0_gated_5arm_unified_waveBC_portfolio"] if r["scenario"].startswith("W_U3_"))
    wu4_live = next(r for r in live_5arm_bundle["stage0_gated_5arm_unified_waveBC_portfolio"] if r["scenario"].startswith("W_U4_"))

    # Verify our generalized 2^20 evaluator reproduces live W_U3 & W_U4 UNROUNDED to < 1e-12!
    def _unrounded_reg_metrics_from_law(law: dict[str, Any], phi_c_val: float) -> tuple[float, float, float]:
        dists = law["stage_dists"]
        c_classes = law["cell_architecture_classes"]
        r_ids = law["h4_route_assignments"]
        reg_compat = {
            "UNHARDENED_A_B_X": frozenset({"R1", "R2"}),
            "DESIGN_Y_FULLSTACK_V2": frozenset({"R3P"}),
            "D1B_AUTO_C_V2": frozenset({"R3P"}),
        }
        v = [0.0] * 32
        v[31] = 1.0
        for h in range(3):
            dh = dists[h]
            vn = [0.0] * 32
            for s, vs in enumerate(v):
                if vs:
                    for mh, w in enumerate(dh):
                        if w:
                            vn[s & mh] += vs * w
            v = vn
        v_h123 = v
        v_all = [0.0] * 32
        for s, vs in enumerate(v_h123):
            if vs:
                for mh, w in enumerate(dists[3]):
                    if w:
                        v_all[s & mh] += vs * w
        locked_u = 1.0 - v_all[0]
        mod100_u = 0.0
        for mc in range(1, 32):
            wc = v_h123[mc]
            if not wc:
                continue
            al: set[str] = set()
            for i in range(5):
                if mc & (1 << i):
                    al |= reg_compat[c_classes[i]]
            for mh in range(1, 32):
                wh = dists[3][mh]
                if wh and any(r_ids[j] in al for j in range(5) if (mh & (1 << j))):
                    mod100_u += wc * wh
        biv2_l = rank_mod._bivariate_bernoulli_iip0034(0.87 / 0.95, 0.93 / 0.95, phi_c_val)
        biv4_l = rank_mod._bivariate_bernoulli_iip0034(0.85 / 0.92, 0.85 / 0.92, phi_c_val)
        ceil_u = 0.88 * (0.95 * (1.0 - biv2_l[(0, 0)])) * 0.89 * (0.92 * (1.0 - biv4_l[(0, 0)]))
        return locked_u, mod100_u, ceil_u

    live_laws: dict[str, dict[str, Any]] = {}
    _tok = rank_mod._ACTIVE_LAW_COLLECTOR_IIP0035.set(live_laws)
    try:
        p0_l = float(live_3arm["locked_2route_shared_ax_pouch_exact"])
        p0_m = float(live_3arm["modular_2route_shared_ax_pouch_exact"])
        c0_ex = math.prod(c0_vec)
        rank_mod._eval_5arm_unified_iip0035(
            "LIVE_UNROUNDED_W_U3", py0, pd1_0, pa=pa0, pb=pb0, px=px0,
            c2_y=0.87, c3_y=0.89, phi_yx=0.75, phi_c=0.25, d1_on_r3=True,
            c4_univ=0.92, c4_r3=0.85, p0_l=p0_l, p0_m=p0_m, c0=c0_ex, stage0_status="PARITY",
        )
        rank_mod._eval_5arm_unified_iip0035(
            "LIVE_UNROUNDED_W_U4", py0, pd1_0, pa=pa0, pb=pb0, px=px0,
            c2_y=0.87, c3_y=0.89, phi_yx=0.75, phi_c=0.50, d1_on_r3=True,
            c4_univ=0.92, c4_r3=0.85, p0_l=p0_l, p0_m=p0_m, c0=c0_ex, stage0_status="PARITY",
        )
    finally:
        rank_mod._ACTIVE_LAW_COLLECTOR_IIP0035.reset(_tok)

    wu3_live_ex = _unrounded_reg_metrics_from_law(live_laws["LIVE_UNROUNDED_W_U3"], 0.25)
    wu4_live_ex = _unrounded_reg_metrics_from_law(live_laws["LIVE_UNROUNDED_W_U4"], 0.50)
    wu3_check = eval_5arm_generalized_exact("PARITY_W_U3", c1=0.88, pa=pa0, pb=pb0, px=px0, p_y=py0, p_d1=pd1_0, phi_c=0.25)
    wu4_check = eval_5arm_generalized_exact("PARITY_W_U4", c1=0.88, pa=pa0, pb=pb0, px=px0, p_y=py0, p_d1=pd1_0, phi_c=0.50)

    parity_errs = [
        abs(wu3_check["locked_exact"] - wu3_live_ex[0]),
        abs(wu3_check["modular_k100_exact"] - wu3_live_ex[1]),
        abs(wu3_check["ceiling_exact"] - wu3_live_ex[2]),
        abs(wu4_check["locked_exact"] - wu4_live_ex[0]),
        abs(wu4_check["modular_k100_exact"] - wu4_live_ex[1]),
        abs(wu4_check["ceiling_exact"] - wu4_live_ex[2]),
    ]
    max_unrounded_parity_err = max(parity_errs)
    if not (max_unrounded_parity_err < 1e-12):
        raise ValueError(f"Unrounded 5-arm parity failed: {max_unrounded_parity_err}")

    s85 = 0.85 / 0.89
    # Compute TRUE unrounded float64 Core 3-arm probabilities directly (NOT 9-dp rounded live_3arm keys!),
    # while asserting exact 9-dp parity against rank_islet1_stacks.compute_common_shock_2pow12_portfolio_tree!
    live_3_l_ex, live_3_m_ex, live_3_c_ex = eval_3arm_2pow12_unrounded(pa0, pb0, px0, c0_vec)
    if round(live_3_l_ex, 9) != float(live_3arm["locked_2route_shared_ax_pouch_exact"]):
        raise ValueError("Unrounded Core 3-arm locked parity mismatch vs live rank_islet1_stacks.py")
    if round(live_3_m_ex, 9) != float(live_3arm["modular_2route_shared_ax_pouch_exact"]):
        raise ValueError("Unrounded Core 3-arm modular parity mismatch vs live rank_islet1_stacks.py")

    def _run_3arm(label: str, c1: float, c3: float, p3_triple: tuple[float, float, float]) -> dict[str, Any]:
        pa = (c1, 0.78, p3_triple[0], 0.69)
        pb = (c1, 0.79, p3_triple[1], 0.70)
        px = (c1, 0.82, p3_triple[2], 0.69)
        c_t = (c1, 0.87, c3, 0.85)
        t_live = rank_mod.compute_common_shock_2pow12_portfolio_tree(pa, pb, px, c_t)
        l_ex, m_ex, c_ex = eval_3arm_2pow12_unrounded(pa, pb, px, c_t)
        if round(l_ex, 9) != float(t_live["locked_2route_shared_ax_pouch_exact"]):
            raise ValueError(f"{label}: 3-arm locked 9-dp mismatch vs live ranker")
        if round(m_ex, 9) != float(t_live["modular_2route_shared_ax_pouch_exact"]):
            raise ValueError(f"{label}: 3-arm modular 9-dp mismatch vs live ranker")
        # Compute ALL deltas from TRUE unrounded float64 probabilities BEFORE 4-dp display rounding!
        dl_ex = 100.0 * (l_ex - live_3_l_ex)
        dm_ex = 100.0 * (m_ex - live_3_m_ex)
        dc_ex = 100.0 * (c_ex - live_3_c_ex)
        return {
            "scenario": label,
            "c1": c1, "c3": c3, "p3_abx": [round(x, 4) for x in p3_triple],
            "locked_pct": round(100.0 * l_ex, 4),
            "delta_locked_vs_live_pp": round(dl_ex, 4),
            "delta_locked_vs_live_exact_pp": round(dl_ex, 12),
            "modular_k100_pct": round(100.0 * m_ex, 4),
            "delta_modular_vs_live_pp": round(dm_ex, 4),
            "delta_modular_vs_live_exact_pp": round(dm_ex, 12),
            "ceiling_pct": round(100.0 * c_ex, 4),
            "delta_ceiling_vs_live_pp": round(dc_ex, 4),
            "locked_exact": l_ex,
            "modular_k100_exact": m_ex,
            "ceiling_exact": c_ex,
        }

    p3_base = (0.57, 0.64, 0.73)
    p3_down = (0.57 * s85, 0.64 * s85, 0.73 * s85)
    p3_cond_stage0 = (0.62, 0.68, 0.78)  # speculative uncalibrated Stage-0 Mode-B sensitivity inside c3=0.89

    core_3arm_scenarios = [
        _run_3arm("S0_Live_Baseline_H1_88_c3_89", 0.88, 0.89, p3_base),
        _run_3arm("S1a_H1_88_Unfixed_CD64t_Downside_c3_85_ProportionalShock", 0.88, 0.85, p3_down),
        _run_3arm("S1b_H1_90_Unfixed_CD64t_Downside_c3_85_ProportionalShock", 0.90, 0.85, p3_down),
        _run_3arm("S1c_H1_90_CeilingCompressionOnly_c3_85_FixedMarginals_Diagnostic", 0.90, 0.85, p3_base),
        _run_3arm("S2a_H1_90_ABX_CD64t_IL1RN_Fix_ZeroH3Lift_c3_89", 0.90, 0.89, p3_base),
        _run_3arm("S2c_H1_90_ABX_CD64t_IL1RN_ConditionalStage0_p3_62_68_78_c3_89", 0.90, 0.89, p3_cond_stage0),
    ]

    five_arm_scenarios = []
    for phi_c_val, phi_tag, base_ex in ((0.25, "W_U3_phi0p25", wu3_live_ex), (0.50, "W_U4_phi0p50", wu4_live_ex)):

        def _add5(lbl: str, **kw: Any) -> None:
            res = eval_5arm_generalized_exact(f"{phi_tag}__{lbl}", phi_c=phi_c_val, **kw)
            # Compute ALL deltas from unrounded exact probabilities BEFORE 4-dp display rounding!
            res["delta_locked_vs_live_same_phi_pp"] = round(100.0 * (res["locked_exact"] - base_ex[0]), 4)
            res["delta_modular_vs_live_same_phi_pp"] = round(100.0 * (res["modular_k100_exact"] - base_ex[1]), 4)
            res["delta_ceiling_vs_live_same_phi_pp"] = round(100.0 * (res["ceiling_exact"] - base_ex[2]), 4)
            five_arm_scenarios.append(res)

        pa_90 = (0.90, 0.78, 0.57, 0.69)
        pb_90 = (0.90, 0.79, 0.64, 0.70)
        px_90 = (0.90, 0.82, 0.73, 0.69)
        py_90 = (0.90, 0.84, 0.80, 0.72)

        pa_88_d = (0.88, 0.78, 0.57 * s85, 0.69)
        pb_88_d = (0.88, 0.79, 0.64 * s85, 0.70)
        px_88_d = (0.88, 0.82, 0.73 * s85, 0.69)

        pa_90_d = (0.90, 0.78, 0.57 * s85, 0.69)
        pb_90_d = (0.90, 0.79, 0.64 * s85, 0.70)
        px_90_d = (0.90, 0.82, 0.73 * s85, 0.69)
        py_90_d = (0.90, 0.84, 0.80 * s85, 0.72)
        pd1_d = (0.62, 0.92, 0.70 * s85, 0.70)

        _add5("S0_Live_Baseline_H1_88_c3_89", c1=0.88, pa=pa0, pb=pb0, px=px0, p_y=py0, p_d1=pd1_0, c3_abx=0.89, c3_y=0.89)
        _add5("S1a_H1_88_Asym_ABX_Unfixed_c3abx85_c3yd89", c1=0.88, pa=pa_88_d, pb=pb_88_d, px=px_88_d, p_y=py0, p_d1=pd1_0, c3_abx=0.85, c3_y=0.89)
        _add5("S1b_H1_90_Asym_ABX_Unfixed_c3abx85_c3yd89", c1=0.90, pa=pa_90_d, pb=pb_90_d, px=px_90_d, p_y=py_90, p_d1=pd1_0, c3_abx=0.85, c3_y=0.89)
        _add5("S1c_H1_90_PortfolioWide_c3_85_All5Arms_ProportionalShock", c1=0.90, pa=pa_90_d, pb=pb_90_d, px=px_90_d, p_y=py_90_d, p_d1=pd1_d, c3_abx=0.85, c3_y=0.85)
        _add5("S2a_H1_90_ABX_CD64t_IL1RN_Fix_ZeroH3Lift_D1bHeld62", c1=0.90, pa=pa_90, pb=pb_90, px=px_90, p_y=py_90, p_d1=pd1_0, c3_abx=0.89, c3_y=0.89)
        _add5("S2b_H1_90_ABX_CD64t_IL1RN_Fix_D1bScaled63p41", c1=0.90, pa=pa_90, pb=pb_90, px=px_90, p_y=py_90, p_d1=(0.62 * 0.90 / 0.88, 0.92, 0.70, 0.70), c3_abx=0.89, c3_y=0.89)
        _add5("S2c_H1_90_ABX_CD64t_IL1RN_ConditionalStage0_p3_62_68_78", c1=0.90, pa=(0.90, 0.78, 0.62, 0.69), pb=(0.90, 0.79, 0.68, 0.70), px=(0.90, 0.82, 0.78, 0.69), p_y=py_90, p_d1=pd1_0, c3_abx=0.89, c3_y=0.89)
        _add5("S3_Stress_H1_90_Fix_phiYX1p00_c4u0p90", c1=0.90, pa=pa_90, pb=pb_90, px=px_90, p_y=py_90, p_d1=pd1_0, c3_abx=0.89, c3_y=0.89, phi_yx=1.00, c4_univ=0.90)

    by_5 = {r["scenario"]: r for r in five_arm_scenarios}
    wu3_rec_ex = 100.0 * (
        by_5["W_U3_phi0p25__S2a_H1_90_ABX_CD64t_IL1RN_Fix_ZeroH3Lift_D1bHeld62"]["locked_exact"]
        - by_5["W_U3_phi0p25__S1b_H1_90_Asym_ABX_Unfixed_c3abx85_c3yd89"]["locked_exact"]
    )
    wu4_rec_ex = 100.0 * (
        by_5["W_U4_phi0p50__S2a_H1_90_ABX_CD64t_IL1RN_Fix_ZeroH3Lift_D1bHeld62"]["locked_exact"]
        - by_5["W_U4_phi0p50__S1b_H1_90_Asym_ABX_Unfixed_c3abx85_c3yd89"]["locked_exact"]
    )
    wu3_s1c_ex = 100.0 * (
        by_5["W_U3_phi0p25__S2a_H1_90_ABX_CD64t_IL1RN_Fix_ZeroH3Lift_D1bHeld62"]["locked_exact"]
        - by_5["W_U3_phi0p25__S1c_H1_90_PortfolioWide_c3_85_All5Arms_ProportionalShock"]["locked_exact"]
    )
    by_3 = {r["scenario"]: r for r in core_3arm_scenarios}
    core_h1_only_ex = 100.0 * (
        by_3["S2a_H1_90_ABX_CD64t_IL1RN_Fix_ZeroH3Lift_c3_89"]["locked_exact"]
        - by_3["S0_Live_Baseline_H1_88_c3_89"]["locked_exact"]
    )
    if round(core_h1_only_ex, 4) != 1.1540:
        raise ValueError(f"Expected +1.1540 pp Core H1-only delta from true unrounded diff, got {core_h1_only_ex}")
    if round(wu3_rec_ex, 4) != 0.6033:
        raise ValueError(f"Expected +0.6033 pp from unrounded diff, got {wu3_rec_ex}")
    if by_5["W_U4_phi0p50__S2a_H1_90_ABX_CD64t_IL1RN_Fix_ZeroH3Lift_D1bHeld62"]["delta_locked_vs_live_same_phi_pp"] != 1.2926:
        raise ValueError("Expected +1.2926 pp W_U4 S0->S2a delta from unrounded diff")

    return {
        "live_headline_delta_pp": 0.0,
        "precision_interface_contract": "All Core 3-arm (2^12) and 5-arm (2^20) deltas are computed directly on true unrounded float64 probabilities first (never from 9-dp rounded endpoints) and then rounded to 4 decimal places for display, while asserting exact 9-dp parity against live rank_islet1_stacks.py.",
        "domain_and_ceiling_guard_unit_tests": domain_guard_tests,
        "live_parity_verification": {
            "core_3arm_live_exact_pct": {
                "locked": round(100.0 * live_3_l_ex, 6),
                "modular": round(100.0 * live_3_m_ex, 6),
                "ceiling": round(100.0 * live_3_c_ex, 6),
            },
            "five_arm_W_U3_W_U4_unrounded_max_abs_err": max_unrounded_parity_err,
            "five_arm_unrounded_parity_lt_1e12": max_unrounded_parity_err < 1e-12,
            "five_arm_W_U3_live_pct": {"locked": wu3_live["locked_pct"], "modular": wu3_live["modular_k100_pct"], "ceiling": wu3_live["composite_ceiling_pct"]},
            "five_arm_W_U4_live_pct": {"locked": wu4_live["locked_pct"], "modular": wu4_live["modular_k100_pct"], "ceiling": wu4_live["composite_ceiling_pct"]},
        },
        "attribution_decomposition_and_disclosures": {
            "core_3arm_h1_only_delta_S0_to_S2a_pp": round(core_h1_only_ex, 4),
            "core_3arm_h1_only_delta_S0_to_S2a_exact_pp": round(core_h1_only_ex, 12),
            "core_3arm_S0_to_S2a_attribution": (
                "100.00% of Core 3-arm S2a's true unrounded +1.1540 pp locked gain (+1.154049955346 pp exact; "
                "50.7781980352% -> 51.9322479906%, display 50.7782% -> 51.9322%) comes strictly from H1: 88% -> 90% "
                "(50.7781980352% * 90/88 = 51.9322479906%); 0.0000 pp comes from ABX_L2_v2_CD64T_IL1RN vs live S0 "
                "(its +2.3340 pp value is strictly defensive recovery vs the modeled unfixed S1b c3=85% downside 49.5982% -> 51.9322%)."
            ),
            "five_arm_abx_cd64t_recovery_S1b_to_S2a_W_U3_pp": round(wu3_rec_ex, 4),
            "five_arm_abx_cd64t_recovery_S1b_to_S2a_W_U3_exact_pp": round(wu3_rec_ex, 10),
            "five_arm_abx_cd64t_recovery_S1b_to_S2a_W_U4_pp": round(wu4_rec_ex, 4),
            "five_arm_abx_cd64t_recovery_S1b_to_S2a_W_U4_exact_pp": round(wu4_rec_ex, 10),
            "five_arm_portfolio_wide_shock_S1c_to_S2a_W_U3_pp": round(wu3_s1c_ex, 4),
            "five_arm_portfolio_wide_shock_S1c_to_S2a_W_U3_exact_pp": round(wu3_s1c_ex, 10),
            "five_arm_attribution_note": (
                "Computed on unrounded exact probabilities BEFORE display rounding: on 5-arm W_U3, co-primary ABX_L2_v2_CD64T_IL1RN alone "
                "recovers +0.6033 pp locked (+0.6033300593 pp exact; S1b -> S2a; W_U4: +0.5938 pp exact +0.5938006279 pp) against the A/B/X-only IgG gap. "
                "The larger +2.7844 pp delta (S1c -> S2a: +2.7843979952 pp exact) is a counterfactual parameter change reflecting a portfolio-wide c3=85% IgM/Ab shock "
                "hitting ALL 5 arms; mitigating it via CD46_WT is explicitly ARCHIVED as HOLD-comparator outside Wave-5 Go scope until CAND-034's executable "
                "cd46_tropic_addendum clears (zero circular gate reference)."
            ),
            "judgemental_sensitivity_parameters_disclosure": (
                "Both c3 = 0.85 (-4 pp autoAb shock) and S2c p3 = [0.62, 0.68, 0.78] are speculative uncalibrated judgemental sensitivity scenarios — "
                "NOT empirically parameterized from Gu 2021's 23.6% new-onset ZnT8ecA seroprevalence (endogenous long-standing T1D titer distribution and "
                "Channel-(b) fraction of H3 failure remain unquantified)."
            ),
            "shock_law_conditioning_disclosure": (
                "In asymmetric scenarios S1a/S1b (c3_abx = 0.85, c3_y = 0.89), attribution is conditional on the assumed nested shock law (where Y's H3 survival "
                "is conditionally independent of the A/B/X-only shock given U_y = 1, u_y3 = 89.89%). Holding arm marginals and the incumbent law fixed while sweeping "
                "feasible Y survival within the shared H3 shock moves W_U3 recovery across [+0.4977, +1.5440] pp and W_U4 across [+0.4605, +1.7828] pp; "
                "these numbers evaluate parameter counterfactuals and do not measure experimentally proven construct protection."
            ),
        },
        "core_3arm_2pow12_scenarios": core_3arm_scenarios,
        "five_arm_2pow20_registered_route_only_scenarios": five_arm_scenarios,
    }


# =============================================================================
# PART E — 100% LIVE NCBI E-UTILITIES + EUROPE PMC PMID VERIFICATION RECEIPT
# =============================================================================
ALL_EXP028_PMIDS = [
    # Part A — Clinical H1 SC-islet cohorts
    "40544428",  # Reichman et al. NEJM 2025 (zimislecel/VX-880)
    "39326417",  # Wang et al. Cell 2024 (autologous CiPSC under rectus sheath, prior liver tx tacrolimus)
    "41765034",  # Shi et al. Lancet Diabetes Endocrinol Apr 2026 (Letter, 0 abs chars)
    "38684699",  # Wu et al. Cell Discov 2024 (autologous E-islet T2D)
    "40757665",  # Carlsson et al. NEJM 2025 (UP421 HIP B2M-/- CIITA-/- CD47+ human sentinel)
    "42430558",  # Carlsson et al. NEJM 2026 (UP421 14-month sentinel)
    # Part B — Autoantibody gap, CD64t, IL1RN, CD46, CFH, GY-026 CR1 & iCasp9
    "42392079",  # Deuse & Schrepfer Cell Rep Med Oct 2026 (Review, anti-ZnT8/TSPAN7)
    "36593395",  # Gravina et al. Nat Biotechnol 2023 (CD64t[1-313] shields against IgG ADCC/CDC)
    "41543848",  # Gou et al. Xenotransplantation 2026 (hCD64 blocks IgG CDC/ADCC, NOT IgM)
    "34130115",  # Gu et al. J Autoimmun 2021 (ZnT8ecA 74/313=23.6%, earliest IAb 10/10, binds beta-cell surface)
    "18023480",  # Beekman et al. Mol Immunol 2008 (Protein 4.1G/EPB41L2 binds Fc gamma RI cytoplasmic tail)
    "10480601",  # Giannoukakis et al. Diabetes 1999 (IL-1Ra gene transfer to human islets prevents IL-1beta GSIS loss & Fas apoptosis)
    "28092375",  # Dror et al. Nat Immunol 2017 (postprandial macrophage IL-1beta stimulates physiological insulin secretion)
    "28494868",  # Garcia-Diaz et al. Cell Rep 2017 (IFN-gamma-JAK1/2-STAT1/2/3-IRF1 regulates CD274/PD-L1 promoter)
    "2139669",   # Arend et al. J Clin Invest 1990 (IL-1Ra requires up to 100-fold molar excess over IL-1 for 50% inhibition)
    "40812299",  # Hu et al. Cell Stem Cell 2025 (already in live Ring-1; CD64t / HIP context)
    "23416052",  # Ogembo et al. Cell Rep 2013 (CR1 is EBV gp350 receptor — GY-026)
    "20855594",  # Tham et al. PNAS 2010 (CR1 is P. falciparum PfRh4 receptor — GY-026)
    "27013439",  # Forneris et al. EMBO J 2016 (PDB 5FO8 CD46 / 5FO9 CR1 C3b complement structures)
    "25925696",  # Kiyoshi et al. Nat Commun 2015 (PDB 4W4O FcgammaRI-IgG1 Fc)
    "25561553",  # Lu et al. PNAS 2015 (PDB 4X4M FcgammaRI-IgG1 Fc glycan pocket)
    "9062194",   # Schreuder et al. Nature 1997 (PDB 1IRA IL1RN-IL1R1 crystal structure)
    "22047558",  # Di Stasi et al. NEJM 2011 (iCasp9 / AP1903 clinical safety switch)
    "21813778",  # Westwell-Roper et al. J Immunol 2011 (hIAPP-macrophage IL-1beta)
    "24222351",  # Westwell-Roper et al. Diabetes 2014 (islet resident macrophage IL-1beta)
    # Part C — Zero-edit Siglec-7/-9 glycoengineering vs genetic ST6GAL1 PDAC hazard
    "42875686",  # Rana et al. Adv Sci Oct 2026 (luminal Siglec-7/-9 LQS8% glycoengineering)
    "37643018",  # Bhalerao et al. JCI Insight 2023 (ST6GAL1 drives ADM & accelerates PDAC survival collapse)
]


def _urlopen_with_retry(url: str, *, timeout: int = 45, attempts: int = 3) -> bytes:
    last_err: Exception | None = None
    for attempt in range(attempts):
        try:
            return urllib.request.urlopen(
                urllib.request.Request(url, headers={"User-Agent": "OpenIslet-EXP028/1.0"}),
                timeout=timeout,
            ).read()
        except Exception as exc:
            last_err = exc
            time.sleep(1.5 * (attempt + 1))
    raise RuntimeError(f"Failed to fetch {url} after {attempts} attempts: {last_err}")


def fetch_live_pubmed_and_epmc(pmids: list[str]) -> dict[str, dict[str, Any]]:
    ids_csv = ",".join(pmids)
    # 1. NCBI E-utilities esummary.fcgi (JSON)
    esum_url = f"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&id={ids_csv}&retmode=json"
    esum_raw = _urlopen_with_retry(esum_url)
    esum_json = json.loads(esum_raw.decode("utf-8"))["result"]

    time.sleep(0.35)
    # 2. NCBI E-utilities efetch.fcgi (XML — full abstract, DOI, PMCID, pub types, retraction flags)
    efetch_url = f"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id={ids_csv}&retmode=xml"
    efetch_xml = _urlopen_with_retry(efetch_url)
    root = ET.fromstring(efetch_xml)

    records: dict[str, dict[str, Any]] = {}
    for art in root.findall(".//PubmedArticle"):
        pmid = art.findtext(".//MedlineCitation/PMID") or ""
        title_el = art.find(".//ArticleTitle")
        title = "".join(title_el.itertext()).strip() if title_el is not None else ""
        journal = art.findtext(".//Journal/ISOAbbreviation") or art.findtext(".//Journal/Title") or ""
        year = (
            art.findtext(".//JournalIssue/PubDate/Year")
            or art.findtext(".//JournalIssue/PubDate/MedlineDate")
            or ""
        )
        m_yr = re.search(r"(19|20)\d{2}", year)
        pub_year = int(m_yr.group(0)) if m_yr else None
        authors = []
        for au in art.findall(".//AuthorList/Author"):
            ln = au.findtext("LastName")
            ini = au.findtext("Initials")
            coll = au.findtext("CollectiveName")
            if ln:
                authors.append(f"{ln} {ini}".strip() if ini else ln)
            elif coll:
                authors.append(coll)
        abs_parts = ["".join(ab.itertext()).strip() for ab in art.findall(".//Abstract/AbstractText")]
        abstract = " ".join(p for p in abs_parts if p)
        pub_types = [pt.text.strip() for pt in art.findall(".//PublicationTypeList/PublicationType") if pt.text]
        doi, pmcid = None, None
        for aid in art.findall(".//PubmedData/ArticleIdList/ArticleId"):
            idtype = aid.attrib.get("IdType")
            if idtype == "doi" and aid.text:
                doi = aid.text.strip()
            elif idtype == "pmc" and aid.text:
                pmcid = aid.text.strip()
        retracted = any("retracted" in pt.lower() or "retraction of" in pt.lower() for pt in pub_types)
        esum_rec = esum_json.get(pmid, {})
        records[pmid] = {
            "pmid": pmid,
            "pmcid": pmcid,
            "doi": doi,
            "pub_year": pub_year,
            "pubdate_esummary": esum_rec.get("pubdate"),
            "journal": journal,
            "first_author": authors[0] if authors else None,
            "senior_author": authors[-1] if authors else None,
            "authors_count": len(authors),
            "title": title,
            "abstract": abstract,
            "abstract_chars": len(abstract),
            "publication_types": pub_types,
            "retracted": retracted,
            "esummary_verified": pmid in esum_json and "error" not in esum_rec,
            "epmc_is_open_access": None,
            "epmc_oa_license": None,
        }

    # 3. Europe PMC OA / license batch lookup
    epmc_q = " OR ".join(f"EXT_ID:{p}" for p in pmids)
    epmc_url = (
        "https://www.ebi.ac.uk/europepmc/webservices/rest/search?"
        + urllib.parse.urlencode({"query": epmc_q, "format": "json", "resultType": "core", "pageSize": len(pmids) + 5})
    )
    epmc_raw = _urlopen_with_retry(epmc_url)
    for res in json.loads(epmc_raw.decode("utf-8")).get("resultList", {}).get("result", []):
        pm = str(res.get("pmid") or "")
        if pm in records:
            records[pm]["epmc_is_open_access"] = res.get("isOpenAccess")
            lic = None
            ft_list = (res.get("fullTextUrlList") or {}).get("fullTextUrl") or []
            if res.get("license"):
                lic = str(res["license"])
            elif res.get("isOpenAccess") == "Y":
                lic = "OA_EPMC"
            records[pm]["epmc_oa_license"] = lic
            if not records[pm]["pmcid"] and res.get("pmcid"):
                records[pm]["pmcid"] = res["pmcid"]

    missing = [p for p in pmids if p not in records]
    if not (not missing):
        raise ValueError(f"Missing PMIDs in live NCBI efetch: {missing}")
    if not (all(not r["retracted"] for r in records.values())):
        raise ValueError("Retracted PMID encountered!")
    return records


def fetch_epmc_fulltext_sections(pmcid: str) -> dict[str, Any]:
    urls = [
        f"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pmc&id={pmcid}&retmode=xml",
        f"https://www.ebi.ac.uk/europepmc/webservices/rest/{pmcid}/fullTextXML",
    ]
    xml_bytes = None
    last_err = None
    for url in urls:
        for attempt in range(3):
            try:
                xml_bytes = urllib.request.urlopen(
                    urllib.request.Request(url, headers={"User-Agent": "OpenIslet-EXP028/1.0"}), timeout=30
                ).read()
                if xml_bytes and b"<body" in xml_bytes:
                    break
            except Exception as exc:
                last_err = exc
                time.sleep(1.5 * (attempt + 1))
        if xml_bytes and b"<body" in xml_bytes:
            break
    if not xml_bytes:
        raise RuntimeError(f"Failed to fetch full-text XML for {pmcid}: {last_err}")
    root = ET.fromstring(xml_bytes)
    paras: list[str] = []
    for sec in root.findall(".//body//sec"):
        sec_t = "".join(sec.find("title").itertext()).lower() if sec.find("title") is not None else ""
        if any(k in sec_t for k in ("result", "discussion", "finding")):
            for p in sec.findall(".//p"):
                txt = re.sub(r"\s+", " ", "".join(p.itertext())).strip()
                if len(txt) >= 40 and txt not in paras:
                    paras.append(txt)
    figs: list[dict[str, str]] = []
    seen_caps: set[str] = set()
    for fig in root.findall(".//fig"):
        lbl = re.sub(r"\s+", " ", "".join(fig.find("label").itertext())).strip() if fig.find("label") is not None else ""
        cap = re.sub(r"\s+", " ", "".join(fig.find("caption").itertext())).strip() if fig.find("caption") is not None else ""
        if len(cap) >= 30 and cap not in seen_caps:
            seen_caps.add(cap)
            figs.append({"label": lbl or f"Figure {len(figs) + 1}", "caption": cap})
    return {"results_paragraphs": paras[:120], "methods_paragraphs": [], "figure_legends": figs[:40]}


# =============================================================================
# PART F — WORKFLOW.md §5.6 MULTI-ARM QUANTITATIVE RING-1 + CEG EXTRACTION (G1..G8)
# =============================================================================
def compute_aggregate_verbatim_chars(record_obj: Any, source_text: str, min_run: int = 25) -> dict[str, Any]:
    src_norm = re.sub(r"\s+", " ", source_text).strip().lower()
    exempt = {
        "pmid", "pmcid", "doi", "citation_short", "title", "journal",
        "schema_version", "study", "dossier_sha256", "first_author", "senior_author",
    }
    max_single, max_field = 0, ""
    intervals: list[tuple[int, int]] = []
    for fpath, val in walk_strings(record_obj):
        leaf = fpath.split(".")[-1].split("[")[0]
        if leaf in exempt or len(val) < min_run or pep.is_redaction_token_prefix(val):
            continue
        sh = int(grm._max_verbatim_shingle_chars(val, source_text))
        if sh > max_single:
            max_single, max_field = sh, fpath
        if sh >= min_run:
            v_norm = re.sub(r"\s+", " ", val).strip().lower()
            i = 0
            while i <= len(v_norm) - min_run:
                sub = v_norm[i : i + min_run]
                pos = src_norm.find(sub)
                if pos != -1:
                    k = min_run
                    while i + k < len(v_norm) and pos + k < len(src_norm) and v_norm[i + k] == src_norm[pos + k]:
                        k += 1
                    intervals.append((pos, pos + k))
                    i += k
                else:
                    i += 1
    merged: list[tuple[int, int]] = []
    for s, e in sorted(intervals):
        if merged and s <= merged[-1][1]:
            merged[-1] = (merged[-1][0], max(merged[-1][1], e))
        else:
            merged.append((s, e))
    return {"max_single_field_shingle_chars": max_single, "max_single_field_name": max_field, "aggregate_verbatim_chars_ge25": sum(e - s for s, e in merged)}


def make_empty_readouts(**overrides: Any) -> dict[str, Any]:
    base: dict[str, Any] = {
        "specific_lysis_or_death_pct_mean": None, "specific_lysis_or_death_pct_sd": None,
        "cell_viability_pct_mean": None, "early_72h_graft_survival_pct": None,
        "time_to_vascular_inosculation_hours": None, "necrotic_core_or_damp_release_pct": None,
        "fibrotic_capsule_thickness_um": None, "in_vivo_graft_survival_days_median": None,
        "pct_graft_surviving_at_end_of_followup": None, "followup_duration_days": None,
        "static_gsis_stimulation_index_mean": None, "static_gsis_stimulation_index_sd": None,
        "dynamic_perifusion_first_phase_fold": None, "proinsulin_to_insulin_ratio": None,
        "in_vivo_stimulated_c_peptide_ng_ml": None, "de_novo_dsa_or_autoantibody_spreading_observed": None,
    }
    base.update(overrides)
    return base


def make_arm(
    arm_id: str,
    arm_label: str,
    *,
    cohort_id: str,
    is_reference_control: bool = False,
    sample_size_n: int | None = None,
    sample_size_unit: str = "unspecified_in_source",
    cell_source_class: str,
    cell_line_id: str | None = None,
    stage: str | None = None,
    site: str = "InVitro_Only",
    sys_is: str | None = None,
    challenges: list[dict[str, Any]] | None = None,
    readouts: dict[str, Any] | None = None,
) -> dict[str, Any]:
    ch_list = challenges or [{
        "challenge_type": "Unstressed_Baseline", "effector_to_target_ratio": None, "oxygen_pct": None,
        "glucose_concentration_mM": None, "duration_hours_or_days": None, "specific_autoantigen_or_hla_restriction": None,
    }]
    return {
        "arm_id": arm_id, "arm_label": arm_label, "cohort_id": cohort_id,
        "is_reference_control": is_reference_control,
        "sample_size_n": sample_size_n, "sample_size_unit": sample_size_unit,
        "gate1_substrate_and_differentiation": {
            "cell_source_class": cell_source_class, "cell_line_id": cell_line_id, "donor_hla_profile": None,
            "protocol_backbone": None, "canonical_differentiation_stage_evaluated": stage,
            "stage_small_molecules_and_factors": [], "cluster_mean_diameter_um": None,
            "pct_nkx6_1_cpeptide_double_pos": None, "pct_mafa_pos": None, "pct_alpha_gcg_pos": None,
            "pct_delta_sst_pos": None, "pct_off_target_enterochromaffin_slc18a1": None,
        },
        "gate2_3_4_genetic_and_epitope_edits": [],
        "gate5_engraftment_niche": {
            "transplant_site": site, "prevascularization_lead_time_days": None,
            "in_dish_vascular_assembly": "None_Avascular_Islet", "oxygen_bridge_72h_carrier": "None",
            "packing_density_ieq_per_cm2_or_ml": None, "number_of_distributed_micro_pockets": None,
            "staged_insertion_schedule": None, "encapsulation_or_biomaterial": None,
            "co_transplanted_cells_or_oxygen_source": None, "systemic_immunosuppression_regimen": sys_is,
        },
        "challenge_conditions": ch_list,
        "quantitative_readouts": make_empty_readouts(**(readouts or {})),
    }


def locate_exact_span(dossier: dict[str, Any], quote_substring: str) -> tuple[str, str, str]:
    """Locate quote_substring in abstract, results_paragraphs, or figure_legends and return (span, source_type, fig_or_sec)."""
    abs_txt = dossier.get("abstract") or ""
    idx = abs_txt.find(quote_substring)
    if idx >= 0:
        return f"abstract[{idx}:{idx + len(quote_substring)}]|norm=exact", "abstract", "Abstract"
    ft = dossier.get("fulltext_data_sections") or {}
    for i, p in enumerate(ft.get("results_paragraphs") or []):
        idx = p.find(quote_substring)
        if idx >= 0:
            return f"fulltext_data_sections.results_paragraphs[{i}][{idx}:{idx + len(quote_substring)}]|norm=exact", "results_text", f"Results P[{i}]"
    for i, fg in enumerate(ft.get("figure_legends") or []):
        cap = fg.get("caption") or ""
        idx = cap.find(quote_substring)
        if idx >= 0:
            return f"fulltext_data_sections.figure_legends[{i}].caption[{idx}:{idx + len(quote_substring)}]|norm=exact", "figure_legend", fg.get("label") or f"Figure {i + 1}"
    raise ValueError(f"PMID {dossier.get('pmid')}: quote not found in dossier: {quote_substring!r}")


def make_effect(
    *,
    pmid: str,
    effect_id: str,
    dossier: dict[str, Any],
    dos_sha: str,
    focal_arm_id: str,
    comparator_arm_id: str | None,
    cohort_id: str,
    focal_factor_X: str,
    comparator_X0: str,
    comparator_label: str | None,
    outcome_variable_Y: str,
    outcome_domain: str,
    effect_direction: str,
    quote_substring: str,
    stage: str | None,
    cell_source: str,
    site: str,
    tier: str,
    treatment_mean: float | None = None,
    control_mean: float | None = None,
    point_estimate: float | None = None,
    effect_notes: str | None = None,
    treatment_n: int | None = None,
    control_n: int | None = None,
    measurement_unit: str = "qualitative_statement",
    statistic_type: str = "qualitative_statement_only",
    contrast_type: str = "qualitative_statement_only",
    polarity_class: str = "Qualitative_or_Unoriented_Endpoint",
    orientation_sign: int = 0,
    matched_lexicon_term: str = "none_or_mixed",
    n_unit: str = "unspecified_in_source",
    censoring_note: str = "Not_Time_To_Event_Endpoint",
    timepoint: str | None = None,
    population_or_model: str | None = None,
    penalty_flag: bool = False,
) -> dict[str, Any]:
    span, _src_type, src_fig = locate_exact_span(dossier, quote_substring)
    if not (len(quote_substring) <= 240):
        raise ValueError(f"PMID {pmid}: quote > 240 chars ({len(quote_substring)})!")
    p_tokens = erc._pvalue_tokens(quote_substring)
    p_rel, p_bnd = (p_tokens[0] if len(p_tokens) == 1 else (None, None))
    p_bnd_f = float(p_bnd) if p_bnd is not None else None
    p_exact = p_bnd_f if p_rel == "=" else None
    lrr: float | None = None
    if statistic_type == "log_response_ratio_paired_means":
        if not (treatment_mean is not None and control_mean is not None and treatment_mean > 0 and control_mean > 0):
            raise ValueError('Verification check failed: treatment_mean is not None and control_mean is not None and treatment_mean > 0 and control_mean > 0')
        lrr = round(math.log(treatment_mean / control_mean), 4)
    elif statistic_type == "log_response_ratio_fold_change":
        if not (treatment_mean is not None and treatment_mean > 0 and treatment_mean != 1.0 and control_mean is None):
            raise ValueError('Verification check failed: treatment_mean is not None and treatment_mean > 0 and treatment_mean != 1.0 and control_mean is None')
        sign_mult = (
            1.0
            if (effect_direction == "Protective_or_Improved" and orientation_sign > 0)
            or (effect_direction == "Deleterious_or_Impaired" and orientation_sign < 0)
            else -1.0
        )
        lrr = round(sign_mult * abs(math.log(treatment_mean)), 4)
    return {
        "effect_id": effect_id,
        "source_figure_or_table": src_fig,
        "focal_factor_X": focal_factor_X,
        "comparator_X0": comparator_X0,
        "outcome_variable_Y": outcome_variable_Y,
        "outcome_domain": outcome_domain,
        "treatment_mean": treatment_mean, "treatment_sd_or_sem": None, "treatment_n": treatment_n,
        "control_mean": control_mean, "control_sd_or_sem": None, "control_n": control_n,
        "measurement_unit": measurement_unit,
        "log_response_ratio_or_smd": lrr,
        "point_estimate": point_estimate,
        "effect_notes": effect_notes,
        "p_value": p_exact,
        "effect_direction": effect_direction,
        "secretome_or_differentiation_penalty_observed": penalty_flag,
        "conditioning_context_Z": {
            "Z1_developmental_stage_and_timing": stage or "Not_Applicable_NonIslet_Model",
            "Z2_genetic_background_and_allelic_dose": cell_source,
            "Z3_immune_effector_and_stressor_pathway": outcome_domain,
            "Z4_metabolic_and_glucose_load_state": "Assay condition per primary study",
            "Z5_cytoarchitecture_and_cluster_diameter": "Not_Applicable_or_Unspecified",
            "Z6_microenvironment_oxygen_and_vascular_niche": site,
            "Z7_promoter_and_epigenetic_context": "Endogenous_or_Study_Locus",
            "Z8_species_age_and_sex_context": population_or_model or tier,
        },
        "verbatim_evidence_quote": quote_substring,
        "focal_arm_id": focal_arm_id,
        "comparator_arm_id": comparator_arm_id,
        "p_value_relation": p_rel,
        "p_value_bound": p_bnd_f,
        "direction_adjudication_method": "source_adjudicated_curated_override",
        "dispersion_type": "Not_Reported_in_Source_Sentence",
        "n_unit": n_unit,
        "censoring_note": censoring_note,
        "endpoint_polarity_registry": {
            "polarity_class": polarity_class,
            "orientation_sign": int(orientation_sign),
            "matched_lexicon_term": matched_lexicon_term,
        },
        "dossier_sha256": dos_sha,
        "source_span": span,
        "quote_source_dossier_pmid": pmid,
        "statistic_type": statistic_type,
        "contrast_metadata": {
            "cohort_id": cohort_id,
            "intervention_label": focal_factor_X,
            "comparator_label": comparator_label,
            "endpoint_name": outcome_domain,
            "timepoint": timepoint,
            "population_or_model": population_or_model or f"{cell_source} ({tier})",
            "units": measurement_unit,
            "contrast_type": contrast_type,
        },
    }


def build_and_validate_evidence_bundle(live_pm: dict[str, dict[str, Any]]) -> dict[str, Any]:
    DOSSIERS_DIR.mkdir(parents=True, exist_ok=True)
    # Fetch OA full-text results paragraphs + figure legends for the 2 CC-BY 4.0 net-new studies
    ft_42875686 = fetch_epmc_fulltext_sections("PMC13668765")
    time.sleep(0.3)
    ft_37643018 = fetch_epmc_fulltext_sections("PMC10619436")

    def _ch(ctype: str, *, dur: float | None = None, ag: str | None = None) -> list[dict[str, Any]]:
        return [{
            "challenge_type": ctype, "effector_to_target_ratio": None, "oxygen_pct": None,
            "glucose_concentration_mM": None, "duration_hours_or_days": dur,
            "specific_autoantigen_or_hla_restriction": ag,
        }]

    # 8 strictly net-new empirical studies upgraded to full multi-arm quantitative WORKFLOW.md §5.6 depth (R4 closed!):
    # Every CEG text string is written freshly to have ZERO >=6-word overlap with any dossier abstract/title/results/figures,
    # ZERO "See primary source" / "See primary study follow-up" placeholders, and ZERO post-hoc OpenIslet editorializing in outcomes!
    study_specs: list[dict[str, Any]] = [
        # ------------------------------------------------------------------
        # 1. PMID:42875686 (Rana et al. Adv Sci Oct 2026 — CC-BY 4.0 full text)
        # Retiered per primary source: human EA.hy926/HUVEC is an immortalized endothelial cell line (CEG T5_Rodent_or_CellLine, NOT islet T4);
        # Ring-1 eff1 upgraded to comparative log_response_ratio_fold_change (~7-fold); eff2/3/5/6 comparative descriptive (NOT single_arm_descriptive_only).
        # ------------------------------------------------------------------
        {
            "pmid": "42875686", "ceg_qid": "PMID:42875686", "citation_short": "Rana 2026",
            "oa_pub_allowed": True, "oa_lic": "CC-BY 4.0", "ft_sections": ft_42875686,
            "pillars": ["Pillar2_Immune_Cloaking_Autoantigen_Neoantigen_Stealth", "Pillar4_Engraftment_Vascularization_Oxygenation_Devices"],
            "tier": "Tier_2B_Human_Cells_InVitro_HumanImmune_or_AutoAb_CoCulture",
            "ceg_tier": "T5_Rodent_or_CellLine",
            "ceg_model": "Human EA.hy926/HUVEC immortalized/vascular endothelial monolayers + human PBMC/serum in vitro (non-islet T5); Balb/c->C57BL/6 mouse aortic allograft Day 2/5/15 (T5); ACI->Lewis rat kidney allograft Day 7 (T5)",
            "ceg_immune": "Human PBMC/NK cytotoxicity & human serum C3b deposition (Siglec-7/-9); IS-free murine aortic & rat renal allograft rejection",
            "ceg_donor_source": "Human EA.hy926/HUVEC monolayers + 2 human PBMC donors; Balb/c->C57BL/6 mice (n=3-8/group); ACI->Lewis rats (n=4/group)",
            "ceg_follow_up": "48 h in vitro rewarming retention; Day 2/5/15 mouse aortic allograft; Day 7 rat kidney allograft (no systemic IS)",
            "ceg_target": "Gate 3 / Gate 5 / zero-edit peri-transplant Siglec-7/-9 luminal glycoengineering comparator",
            "ceg_topics": ["EFF:Humoral_DSA_FcR_ADCC_Complement_CDC", "EFF:Leukocyte_Endothelial_Adhesion_ICAM1_LFA1", "EFF:Macrophage_Myeloid_SIRPa_Phagocytosis"],
            "arms": [
                make_arm("pmid42875686_arm1_human_ea_lqs8", "Human endothelial EAhy926 monolayers coated with graded LQS8pct doses + gtTGase, PBMC/serum challenge",
                         cohort_id="pmid42875686_cohort1", is_reference_control=False, sample_size_n=None, sample_size_unit="human_immune_donors",
                         cell_source_class="Human_NonIslet_Immortalized_Cell_Line", cell_line_id=None, site="InVitro_Only", sys_is="None_in_vitro",
                         challenges=_ch("Allogeneic_PBMC_or_T_Cell_CoCulture")),
                make_arm("pmid42875686_arm2_human_ea_inflamed_ctrl", "Unmodified TNFa-primed human endothelial EAhy926 reference controls",
                         cohort_id="pmid42875686_cohort1", is_reference_control=True, sample_size_n=None, sample_size_unit="human_immune_donors",
                         cell_source_class="Human_NonIslet_Immortalized_Cell_Line", cell_line_id=None, site="InVitro_Only", sys_is="None_in_vitro",
                         challenges=_ch("Allogeneic_PBMC_or_T_Cell_CoCulture")),
                make_arm("pmid42875686_arm3_human_ea_steric_decay", "Human endothelial EAhy926 graded LQS8pct titration CD47/HLA FigS20 probe labeling and 48h fluorescence decay assay",
                         cohort_id="pmid42875686_cohort2", is_reference_control=False, sample_size_n=None, sample_size_unit="in_vitro_monoculture_replicates",
                         cell_source_class="Human_NonIslet_Immortalized_Cell_Line", cell_line_id=None, site="InVitro_Only", sys_is="None_in_vitro",
                         challenges=_ch("Cytokine_Cocktail_IFNg_IL1b_TNFa_or_IFNa", dur=48.0)),
                make_arm("pmid42875686_arm4_mouse_aorta_lqs8", "Murine Balbc-to-C57BL6 abdominal arterial allograft coated ex vivo with 0.56 mM LQS8pct (no IS)",
                         cohort_id="pmid42875686_cohort3", is_reference_control=False, sample_size_n=8, sample_size_unit="mouse_recipients",
                         cell_source_class="NonIslet_Immune_Endothelial_or_Hematopoietic_Model", site="Unspecified_InVivo_or_Source_Site", sys_is="None_IS_free_mouse",
                         challenges=_ch("InVivo_Allogeneic_or_Autoimmune_Graft", dur=15.0), readouts={"followup_duration_days": 15.0}),
                make_arm("pmid42875686_arm5_mouse_aorta_uw_ctrl", "Unmodified UW-buffer Balbc-to-C57BL6 murine arterial allograft reference controls (no IS)",
                         cohort_id="pmid42875686_cohort3", is_reference_control=True, sample_size_n=8, sample_size_unit="mouse_recipients",
                         cell_source_class="NonIslet_Immune_Endothelial_or_Hematopoietic_Model", site="Unspecified_InVivo_or_Source_Site", sys_is="None_IS_free_mouse",
                         challenges=_ch("InVivo_Allogeneic_or_Autoimmune_Graft", dur=15.0), readouts={"followup_duration_days": 15.0}),
                make_arm("pmid42875686_arm6_rat_kidney_lqs8_high", "ACI-to-Lewis rat renal graft perfused ex vivo with 1.5 mM LQS8pct (day7, no IS)",
                         cohort_id="pmid42875686_cohort4", is_reference_control=False, sample_size_n=4, sample_size_unit="rat_recipients",
                         cell_source_class="NonIslet_Immune_Endothelial_or_Hematopoietic_Model", site="Unspecified_InVivo_or_Source_Site", sys_is="None_IS_free_rat",
                         challenges=_ch("InVivo_Allogeneic_or_Autoimmune_Graft", dur=7.0), readouts={"followup_duration_days": 7.0}),
                make_arm("pmid42875686_arm7_rat_kidney_uw_ctrl", "Unmodified UW-buffer ACI-to-Lewis rat renal graft reference controls (day7, no IS)",
                         cohort_id="pmid42875686_cohort4", is_reference_control=True, sample_size_n=4, sample_size_unit="rat_recipients",
                         cell_source_class="NonIslet_Immune_Endothelial_or_Hematopoietic_Model", site="Unspecified_InVivo_or_Source_Site", sys_is="None_IS_free_rat",
                         challenges=_ch("InVivo_Allogeneic_or_Autoimmune_Graft", dur=7.0), readouts={"followup_duration_days": 7.0}),
            ],
            "effects": [
                {
                    "effect_id": "pmid42875686_eff1_human_pbmc_cytotox",
                    "focal_arm_id": "pmid42875686_arm1_human_ea_lqs8", "comparator_arm_id": "pmid42875686_arm2_human_ea_inflamed_ctrl",
                    "cohort_id": "pmid42875686_cohort1", "focal_factor_X": "High_dose_1p5mM_LQS8pct_human_endothelium",
                    "comparator_X0": "Unmodified_TNFa_primed_EAhy926_controls",
                    "comparator_label": "Unmodified TNFa-primed human endothelial EAhy926 reference controls",
                    "outcome_variable_Y": "Comparative human PBMC killing reduction on LQS8pct-coated EAhy926 (~85pct drop / ~7x protection at 1.5mM)",
                    "outcome_domain": "NK_or_Macrophage_Innate_Survival", "effect_direction": "Protective_or_Improved",
                    "quote": "85% reduction in PBMC‐mediated", "point_estimate": 85.0, "measurement_unit": "pct_reduction_vs_ctrl",
                    "effect_notes": "Numeric comparative percentage reduction (point_estimate=85.0% PBMC killing drop / ~7x protection at 1.5 mM vs unmodified EAhy926; approximate ~ relative pct reduction without raw paired arm means/95% CI, encoded as quarantined_ambiguous_numeric + between_arm_comparative_descriptive per frozen Ring-1 schema v0.2 rather than qualitative_statement_only).",
                    "statistic_type": "quarantined_ambiguous_numeric", "contrast_type": "between_arm_comparative_descriptive",
                    "polarity_class": "Higher_Is_Better_Protective_Endpoint", "orientation_sign": 1, "matched_lexicon_term": "cytoprotective_reduction",
                    "n_unit": "human_immune_donors", "cell_source": "Human_NonIslet_Immortalized_Cell_Line", "site": "InVitro_Only",
                    "tier": "Tier_2B_Human_Cells_InVitro_HumanImmune_or_AutoAb_CoCulture",
                    "population_or_model": "Human_EAhy926_plus_2_human_PBMC_donors",
                },
                {
                    "effect_id": "pmid42875686_eff2_human_icam1_mask",
                    "focal_arm_id": "pmid42875686_arm1_human_ea_lqs8", "comparator_arm_id": "pmid42875686_arm2_human_ea_inflamed_ctrl",
                    "cohort_id": "pmid42875686_cohort1", "focal_factor_X": "Dose_escalated_LQS8pct_human_endothelium",
                    "comparator_X0": "Unmodified_TNFa_primed_EAhy926_controls",
                    "comparator_label": "Unmodified TNFa-primed human endothelial EAhy926 reference controls",
                    "outcome_variable_Y": "Comparative human endothelial ICAM1 accessibility reduction (~67pct peak at 1.5mM vs unmodified)",
                    "outcome_domain": "Surface_HLA_or_Transgene_Expression_Level", "effect_direction": "Protective_or_Improved",
                    "quote": "strongest reduction (∼67% compared", "point_estimate": 67.0, "measurement_unit": "pct_reduction_vs_ctrl",
                    "effect_notes": "Numeric comparative percentage reduction (point_estimate=67.0% drop in ICAM1 staining at 1.5 mM vs unmodified TNFa-primed EAhy926; approximate ~ relative pct reduction without raw paired arm means/95% CI, encoded as quarantined_ambiguous_numeric + between_arm_comparative_descriptive per frozen Ring-1 schema v0.2).",
                    "statistic_type": "quarantined_ambiguous_numeric", "contrast_type": "between_arm_comparative_descriptive",
                    "polarity_class": "Higher_Is_Better_Protective_Endpoint", "orientation_sign": 1, "matched_lexicon_term": "adhesion_masking_reduction",
                    "n_unit": "in_vitro_monoculture_replicates", "cell_source": "Human_NonIslet_Immortalized_Cell_Line", "site": "InVitro_Only",
                    "tier": "Tier_3_Human_Cells_AbioticStress_or_ImmunodeficientMouse",
                    "population_or_model": "TNFa_primed_human_EAhy926_monolayers",
                },
                {
                    "effect_id": "pmid42875686_eff3_human_serum_c3b",
                    "focal_arm_id": "pmid42875686_arm1_human_ea_lqs8", "comparator_arm_id": "pmid42875686_arm2_human_ea_inflamed_ctrl",
                    "cohort_id": "pmid42875686_cohort1", "focal_factor_X": "Dose_escalated_LQS8pct_human_endothelium",
                    "comparator_X0": "Unmodified_TNFa_primed_EAhy926_controls",
                    "comparator_label": "Unmodified TNFa-primed human endothelial EAhy926 reference controls",
                    "outcome_variable_Y": "Comparative human serum C3b fixation reduction (~22pct/38pct/50pct across 0.1-1.0mM vs unmodified)",
                    "outcome_domain": "Complement_or_IBMIR_Coagulation_Block", "effect_direction": "Protective_or_Improved",
                    "quote": "C3b binding by ∼22%, ∼38%, and ∼50%", "point_estimate": 50.0, "measurement_unit": "pct_reduction_at_1p0mM_vs_ctrl",
                    "effect_notes": "Numeric comparative percentage reduction (point_estimate=50.0% serum C3b drop at 1.0 mM; ~22%/~38%/~50% across graded LQS8pct doses vs unmodified EAhy926; approximate ~ relative pct reduction without raw paired arm means/95% CI, encoded as quarantined_ambiguous_numeric + between_arm_comparative_descriptive per frozen Ring-1 schema v0.2).",
                    "statistic_type": "quarantined_ambiguous_numeric", "contrast_type": "between_arm_comparative_descriptive",
                    "polarity_class": "Higher_Is_Better_Protective_Endpoint", "orientation_sign": 1, "matched_lexicon_term": "complement_blockade",
                    "n_unit": "in_vitro_monoculture_replicates", "cell_source": "Human_NonIslet_Immortalized_Cell_Line", "site": "InVitro_Only",
                    "tier": "Tier_2B_Human_Cells_InVitro_HumanImmune_or_AutoAb_CoCulture",
                    "population_or_model": "Human_EAhy926_exposed_to_human_serum",
                },
                {
                    "effect_id": "pmid42875686_eff4_human_cd47_hla_masking",
                    "focal_arm_id": "pmid42875686_arm3_human_ea_steric_decay", "comparator_arm_id": None,
                    "cohort_id": "pmid42875686_cohort2", "focal_factor_X": "Escalating_LQS8pct_dose_FigS20_EAhy926",
                    "comparator_X0": "Unmodified_EAhy926_baseline", "comparator_label": None,
                    "outcome_variable_Y": "Reduced antibody-accessible CD47 & HLA-A,B,C on EAhy926 (FigS20; masking vs expression unresolved; HLA-E unmeasured) + 48h decay (FigS14)",
                    "outcome_domain": "Surface_HLA_or_Transgene_Expression_Level", "effect_direction": "Deleterious_or_Impaired",
                    "quote": "antibody‐accessible HLA‐A,B,C and CD47", "measurement_unit": "qualitative_statement",
                    "statistic_type": "qualitative_statement_only", "contrast_type": "single_arm_descriptive_only",
                    "polarity_class": "Qualitative_or_Unoriented_Endpoint", "orientation_sign": 0, "matched_lexicon_term": "none_or_mixed",
                    "n_unit": "in_vitro_monoculture_replicates", "cell_source": "Human_NonIslet_Immortalized_Cell_Line", "site": "InVitro_Only",
                    "tier": "Tier_3_Human_Cells_AbioticStress_or_ImmunodeficientMouse",
                    "population_or_model": "Human_EAhy926_FigS20_accessibility_and_FigS14_48h_decay",
                    "penalty_flag": True,
                },
                {
                    "effect_id": "pmid42875686_eff5_mouse_aorta_d2_neutrophil",
                    "focal_arm_id": "pmid42875686_arm4_mouse_aorta_lqs8", "comparator_arm_id": "pmid42875686_arm5_mouse_aorta_uw_ctrl",
                    "cohort_id": "pmid42875686_cohort3", "focal_factor_X": "ExVivo_0p56mM_LQS8pct_murine_aorta",
                    "comparator_X0": "UW_buffer_murine_aorta_controls",
                    "comparator_label": "Unmodified UW-buffer Balbc-to-C57BL6 murine arterial allograft reference controls (no IS)",
                    "outcome_variable_Y": "Comparative murine arterial Day2 adventitial MPO+ neutrophil reduction (~94pct vs UW control, n=3/group)",
                    "outcome_domain": "Innate_Myeloid_or_Neutrophil_Infiltration_and_Host_Response", "effect_direction": "Protective_or_Improved",
                    "quote": "94% reduction) in LQS‐treated", "point_estimate": 94.0, "measurement_unit": "pct_reduction_vs_ctrl",
                    "effect_notes": "Numeric comparative percentage reduction (point_estimate=94.0% Day-2 arterial MPO+ neutrophil drop vs UW controls, n=3 mice/group; approximate ~ relative pct reduction without raw paired arm means/95% CI, encoded as quarantined_ambiguous_numeric + between_arm_comparative_descriptive per frozen Ring-1 schema v0.2).",
                    "statistic_type": "quarantined_ambiguous_numeric", "contrast_type": "between_arm_comparative_descriptive",
                    "polarity_class": "Higher_Is_Better_Protective_Endpoint", "orientation_sign": 1, "matched_lexicon_term": "neutrophil_suppression",
                    "n_unit": "mouse_recipients", "timepoint": "d2_murine",
                    "cell_source": "NonIslet_Immune_Endothelial_or_Hematopoietic_Model", "site": "Unspecified_InVivo_or_Source_Site",
                    "tier": "Tier_4_Rodent_or_Xenogeneic_Only", "population_or_model": "Balbc_to_C57BL6_mouse_aortic_graft_n3",
                },
                {
                    "effect_id": "pmid42875686_eff6_mouse_aorta_d15_mac3",
                    "focal_arm_id": "pmid42875686_arm4_mouse_aorta_lqs8", "comparator_arm_id": "pmid42875686_arm5_mouse_aorta_uw_ctrl",
                    "cohort_id": "pmid42875686_cohort3", "focal_factor_X": "ExVivo_0p56mM_LQS8pct_murine_aorta",
                    "comparator_X0": "UW_buffer_murine_aorta_controls",
                    "comparator_label": "Unmodified UW-buffer Balbc-to-C57BL6 murine arterial allograft reference controls (no IS)",
                    "outcome_variable_Y": "Comparative murine arterial Day15 Mac3+ macrophage reduction (~63pct adventitia, ~67pct media vs UW, n=8/group)",
                    "outcome_domain": "Innate_Myeloid_or_Neutrophil_Infiltration_and_Host_Response", "effect_direction": "Protective_or_Improved",
                    "quote": "∼63% in the adventitia and ∼67%", "point_estimate": 63.0, "measurement_unit": "pct_reduction_vs_ctrl",
                    "effect_notes": "Numeric comparative percentage reduction (point_estimate=63.0% Day-15 Mac-3+ macrophage drop in adventitia / ~67% media vs UW, n=8 mice/group; NKp46+ unchanged; approximate ~ relative pct reduction without raw paired arm means/95% CI, encoded as quarantined_ambiguous_numeric + between_arm_comparative_descriptive per frozen Ring-1 schema v0.2).",
                    "statistic_type": "quarantined_ambiguous_numeric", "contrast_type": "between_arm_comparative_descriptive",
                    "polarity_class": "Higher_Is_Better_Protective_Endpoint", "orientation_sign": 1, "matched_lexicon_term": "macrophage_suppression",
                    "n_unit": "mouse_recipients", "timepoint": "d15_murine",
                    "cell_source": "NonIslet_Immune_Endothelial_or_Hematopoietic_Model", "site": "Unspecified_InVivo_or_Source_Site",
                    "tier": "Tier_4_Rodent_or_Xenogeneic_Only", "population_or_model": "Balbc_to_C57BL6_mouse_aortic_graft_n8",
                },
                {
                    "effect_id": "pmid42875686_eff7_rat_kidney_d7_c4d",
                    "focal_arm_id": "pmid42875686_arm6_rat_kidney_lqs8_high", "comparator_arm_id": "pmid42875686_arm7_rat_kidney_uw_ctrl",
                    "cohort_id": "pmid42875686_cohort4", "focal_factor_X": "High_dose_1p5mM_LQS8pct_rat_renal_graft",
                    "comparator_X0": "UW_buffer_rat_renal_controls",
                    "comparator_label": "Unmodified UW-buffer ACI-to-Lewis rat renal graft reference controls (day7, no IS)",
                    "outcome_variable_Y": "Rat renal Day7 C4d area, MVI, v-score, ATN & CD8+ drop (1.5mM, n=4/group)",
                    "outcome_domain": "Complement_or_IBMIR_Coagulation_Block", "effect_direction": "Protective_or_Improved",
                    "quote": "high‐dose LQS8% attenuated early", "measurement_unit": "qualitative_statement",
                    "statistic_type": "qualitative_statement_only", "contrast_type": "between_arm_comparative_descriptive",
                    "polarity_class": "Qualitative_or_Unoriented_Endpoint", "orientation_sign": 0, "matched_lexicon_term": "none_or_mixed",
                    "n_unit": "rat_recipients", "timepoint": "d7_rat",
                    "cell_source": "NonIslet_Immune_Endothelial_or_Hematopoietic_Model", "site": "Unspecified_InVivo_or_Source_Site",
                    "tier": "Tier_4_Rodent_or_Xenogeneic_Only", "population_or_model": "ACI_to_Lewis_rat_kidney_graft_n4_noIS",
                },
            ],
            "ceg_arms": [
                {"arm_id": "A1_human_ea_lqs8", "label": "Human EAhy926 endothelium ligated with LQS8pct (0.1-1.5 mM) + gtTGase at 4C in UW", "edits": ["Surface_LQS8pct_SiaLac_Polymer_K0"], "n": "2 human PBMC whole-blood donors (EAhy926/HUVEC in vitro)", "iso": "Paired negative control"},
                {"arm_id": "A2_human_ea_ctrl", "label": "Unmodified TNFa-primed human EAhy926 endothelial controls", "edits": [], "n": "2 human PBMC whole-blood donors", "iso": "Baseline comparator"},
                {"arm_id": "A3_mouse_aorta_lqs8", "label": "Balbc->C57BL6 murine arterial allograft coated ex vivo with 0.56 mM LQS8pct (no IS)", "edits": ["Surface_LQS8pct_SiaLac_Polymer_K0"], "n": "n=3 (d2), n=4 (d5), n=8 (d15) mice/group", "iso": "Vehicle control"},
                {"arm_id": "A4_mouse_aorta_uw_ctrl", "label": "Unmodified UW-buffer Balbc->C57BL6 murine arterial allograft controls (no IS)", "edits": [], "n": "n=3 (d2), n=3 (d5), n=8 (d15) mice/group", "iso": "Baseline comparator"},
                {"arm_id": "A5_rat_kidney_lqs8", "label": "ACI->Lewis rat renal graft perfused ex vivo with 0.56 or 1.5 mM LQS8pct vs UW (no IS)", "edits": ["Surface_LQS8pct_SiaLac_Polymer_K0"], "n": "n=4 rats/group (UW, 0.56 mM, 1.5 mM)", "iso": "Vehicle control"},
            ],
            "ceg_outcomes": [
                {"oid": "O1", "endpoint": "Human EAhy926 PBMC killing suppression (1.5 mM LQS8pct)", "comp": "A1_human_ea_lqs8 vs A2_human_ea_ctrl", "dir": "favorable_to_intervention", "stat": "fold_change", "tier": "T5_Rodent_or_CellLine", "ival": "7x cytotoxicity protection (~85pct drop, 1.5 mM; 3.4x, 0.56 mM)", "summary": "Titrating LQS8pct up to 1.5 mM conferred ~7x protection (~85pct drop in human leukocyte killing) on cytokine-primed EAhy926 cell monolayers.", "quote_eff": "pmid42875686_eff1_human_pbmc_cytotox"},
                {"oid": "O2", "endpoint": "Human endothelial ICAM1 shielding and serum C3b fixation", "comp": "A1_human_ea_lqs8 vs A2_human_ea_ctrl", "dir": "favorable_to_intervention", "stat": "proportion_or_rate", "tier": "T5_Rodent_or_CellLine", "ival": "67pct ICAM1 drop (1.5 mM); 50pct C3b drop (1.0 mM)", "summary": "Polymer ligation lowered TNFa-evoked ICAM1 detection by ~67pct (1.5 mM) and cut human C3b deposition ~22pct/38pct/50pct across 0.1-1.0 mM on EAhy926 cells.", "quote_eff": "pmid42875686_eff3_human_serum_c3b"},
                {"oid": "O3", "endpoint": "Human EAhy926 CD47/HLA-A,B,C accessibility drop (FigS20) & 48h polymer loss (FigS14)", "comp": "A1_human_ea_lqs8 dose escalation (0.1-1.5 mM)", "dir": "unfavorable_or_toxic", "stat": "qualitative_no_pvalue", "tier": "T5_Rodent_or_CellLine", "ival": "Progressive CD47/HLA-A,B,C accessibility drop (masking vs expression unresolved; HLA-E unmeasured); 48h decay", "summary": "Higher polymer doses progressively lowered antibody-detected CD47 and HLA-A,B,C on EAhy926 cells (without resolving masking vs expression or measuring HLA-E) while fluorescent conjugate decayed over 48 h at 37C.", "quote_eff": "pmid42875686_eff4_human_cd47_hla_masking"},
                {"oid": "O4", "endpoint": "Mouse arterial allograft Day-2 neutrophils and Day-15 Mac3+ macrophages", "comp": "A3_mouse_aorta_lqs8 vs A4_mouse_aorta_uw_ctrl", "dir": "favorable_to_intervention", "stat": "proportion_or_rate", "tier": "T5_Rodent_or_CellLine", "ival": "94pct neutrophil drop (d2, n=3); 63-67pct Mac3+ drop (d15, n=8)", "summary": "Ex vivo 0.56 mM LQS8pct cut Day-2 arterial neutrophil infiltration ~94pct and Day-15 Mac3+ macrophages ~63pct (adventitia) / ~67pct (media), leaving NKp46+ unchanged.", "quote_eff": "pmid42875686_eff5_mouse_aorta_d2_neutrophil"},
                {"oid": "O5", "endpoint": "Rat renal allograft Day-7 C4d, microvascular inflammation, ATN & CD8+ T cells", "comp": "A5_rat_kidney_lqs8 (1.5 mM vs 0.56 mM vs UW control)", "dir": "favorable_to_intervention", "stat": "qualitative_with_pvalue", "tier": "T5_Rodent_or_CellLine", "ival": "Significant C4d, MVI, v-score, ATN & CD8+ drop at 1.5 mM (n=4/group)", "summary": "High-dose 1.5 mM LQS8pct significantly lowered Day-7 rat kidney C4d area, intimal arteritis, ATN, and CD8+ T-cell infiltration (n=4/group; durability beyond Day 7 untested).", "quote_eff": "pmid42875686_eff7_rat_kidney_d7_c4d"},
            ],
            "ceg_relation": "novel_upgrade_hypothesis", "ceg_applicability": "unvalidated_transfer",
            "ceg_edge_claim": "Ex vivo LQS8pct sialoside coating cuts human PBMC cytotoxicity (~7-fold/~85pct), C3b (~50pct), mouse neutrophils (~94pct), and rat Day-7 C4d, yet 48-hour loss, unmeasured HLA-E, and 1.0-1.5 mM CD47/HLA-I accessibility drops restrict it to a Day 0-14 research comparator.",
        },
        # ------------------------------------------------------------------
        # 2. PMID:37643018 (Bhalerao et al. JCI Insight 2023 — CC-BY 4.0 full text)
        # Retiered per primary source: murine GEMMs + human PDAC tumor xenograft in mice -> CEG T5_Rodent_or_CellLine (NOT islet T4)!
        # eff1 upgraded to paired comparative log_response_ratio_paired_means (4.3 vs 13.6 mo -> LRR = -1.1515).
        # ------------------------------------------------------------------
        {
            "pmid": "37643018", "ceg_qid": "PMID:37643018", "citation_short": "Bhalerao 2023",
            "oa_pub_allowed": True, "oa_lic": "CC-BY 4.0", "ft_sections": ft_37643018,
            "pillars": ["Pillar1_Differentiation_Maturation_Cytoarchitecture", "Pillar3_Intrinsic_BetaCell_Genetic_Resilience_Amyloid_Viral"],
            "tier": "Tier_3_Human_Cells_AbioticStress_or_ImmunodeficientMouse",
            "ceg_tier": "T5_Rodent_or_CellLine",
            "ceg_model": "Murine pancreatic GEMMs (WT, SC ST6GAL1-only, KC KrasG12D, KSC dual transgene), organoids, immunodeficient-mouse human Suit2 PDAC xenografts, and human PDAC tissue IHC (non-islet oncology T5)",
            "ceg_immune": "Syngeneic pancreatic tumorigenesis, cerulein pancreatitis ADM, and immunodeficient mouse human Suit2 PDAC xenografts",
            "ceg_donor_source": "KC/KSC survival (n=10/group) & wk20 histology (n=9/group); SC/WT RNA-Seq (n=3/group); Suit2 xenografts (n=7-11/group); human PDAC IHC (n=48-216)",
            "ceg_follow_up": "Kaplan-Meier survival through death (median 4.3 vs 13.6 mo); wk20 GEMM histology/RNA-Seq; Suit2 xenograft BLI/metastasis",
            "ceg_target": "Gate 1 / Gate 3 / genetic ST6GAL1 sialylation oncogenic disqualification guardrail (GY-029)",
            "ceg_topics": ["EFF:OffTarget_Enterochromaffin_Hepatic_Ductal_Contamination", "EFF:Teratoma_Residual_Pluripotency_Clonogenic_Escape"],
            "arms": [
                make_arm("pmid37643018_arm1_ksc_kras_st6gal1", "KSC double-transgenic pancreatic GEMM co-expressing ST6GAL1 + KrasG12D",
                         cohort_id="pmid37643018_cohort1", is_reference_control=False, sample_size_n=10, sample_size_unit="mouse_recipients",
                         cell_source_class="NonIslet_Immune_Endothelial_or_Hematopoietic_Model", site="Unspecified_InVivo_or_Source_Site", sys_is="None_syngeneic_GEMM"),
                make_arm("pmid37643018_arm2_kc_kras_ctrl", "KC single-oncogene KrasG12D pancreatic GEMM reference controls",
                         cohort_id="pmid37643018_cohort1", is_reference_control=True, sample_size_n=10, sample_size_unit="mouse_recipients",
                         cell_source_class="NonIslet_Immune_Endothelial_or_Hematopoietic_Model", site="Unspecified_InVivo_or_Source_Site", sys_is="None_syngeneic_GEMM"),
                make_arm("pmid37643018_arm3_sc_st6gal1_only", "SC single-transgene ST6GAL1-only GEMM (WT KRAS, nonmalignant wk20, RNA-Seq Fig3D)",
                         cohort_id="pmid37643018_cohort2", is_reference_control=False, sample_size_n=3, sample_size_unit="mouse_recipients",
                         cell_source_class="NonIslet_Immune_Endothelial_or_Hematopoietic_Model", site="Unspecified_InVivo_or_Source_Site", sys_is="None_syngeneic_GEMM"),
                make_arm("pmid37643018_arm4_wt_ctrl", "Cre-negative littermate WT pancreatic reference controls at wk20",
                         cohort_id="pmid37643018_cohort2", is_reference_control=True, sample_size_n=3, sample_size_unit="mouse_recipients",
                         cell_source_class="NonIslet_Immune_Endothelial_or_Hematopoietic_Model", site="Unspecified_InVivo_or_Source_Site", sys_is="None_syngeneic_GEMM"),
                make_arm("pmid37643018_arm5_human_suit2_oe", "Human Suit2 PDAC orthotopic xenografts with ectopic ST6GAL1 overexpression",
                         cohort_id="pmid37643018_cohort3", is_reference_control=False, sample_size_n=7, sample_size_unit="mouse_recipients",
                         cell_source_class="Human_NonIslet_Immortalized_Cell_Line", cell_line_id=None, site="Unspecified_InVivo_or_Source_Site", sys_is="Immunodeficient_xenograft"),
                make_arm("pmid37643018_arm6_human_suit2_ev_ctrl", "Human Suit2 PDAC empty-vector orthotopic xenograft reference controls",
                         cohort_id="pmid37643018_cohort3", is_reference_control=True, sample_size_n=7, sample_size_unit="mouse_recipients",
                         cell_source_class="Human_NonIslet_Immortalized_Cell_Line", cell_line_id=None, site="Unspecified_InVivo_or_Source_Site", sys_is="Immunodeficient_xenograft"),
            ],
            "effects": [
                {
                    "effect_id": "pmid37643018_eff1_ksc_vs_kc_survival",
                    "focal_arm_id": "pmid37643018_arm1_ksc_kras_st6gal1", "comparator_arm_id": "pmid37643018_arm2_kc_kras_ctrl",
                    "cohort_id": "pmid37643018_cohort1", "focal_factor_X": "Dual_ST6GAL1_plus_KrasG12D_KSC",
                    "comparator_X0": "Single_KrasG12D_KC_controls",
                    "comparator_label": "KC single-oncogene KrasG12D pancreatic GEMM reference controls",
                    "outcome_variable_Y": "Kaplan-Meier overall lifespan shortened -68.4pct (4.3 vs 13.6 mo, 3.16x shorter, n=10/group)",
                    "outcome_domain": "InVivo_Glycemic_Cure_and_Graft_Longevity", "effect_direction": "Deleterious_or_Impaired",
                    "quote": "4.3 months for KSC mice and 13.6 months for KC mice (n = 10 mice/group). P < 0.0001",
                    "point_estimate": 4.3, "treatment_n": 10, "control_n": 10, "measurement_unit": "median_survival_mo",
                    "effect_notes": "Oncogenic KRASG12D mouse GEMM result: KSC 4.3 mo vs KC 13.6 mo (-68.4pct, 3.16x shorter, log_ratio=-1.1515, n=10/group, P<0.0001; median survival without parametric mean/SD -> quarantined_ambiguous_numeric + between_arm_comparative_descriptive)",
                    "statistic_type": "quarantined_ambiguous_numeric", "contrast_type": "between_arm_comparative_descriptive",
                    "polarity_class": "Higher_Is_Better_Protective_Endpoint", "orientation_sign": 1, "matched_lexicon_term": "survival",
                    "n_unit": "mouse_recipients", "censoring_note": "Kaplan_Meier_Median_Overall_Survival",
                    "cell_source": "NonIslet_Immune_Endothelial_or_Hematopoietic_Model", "site": "Unspecified_InVivo_or_Source_Site",
                    "tier": "Tier_4_Rodent_or_Xenogeneic_Only", "population_or_model": "KrasG12D_GEMM_KSC_vs_KC_n10",
                    "penalty_flag": True,
                },
                {
                    "effect_id": "pmid37643018_eff2_ksc_20wk_pdac",
                    "focal_arm_id": "pmid37643018_arm1_ksc_kras_st6gal1", "comparator_arm_id": "pmid37643018_arm2_kc_kras_ctrl",
                    "cohort_id": "pmid37643018_cohort1", "focal_factor_X": "Dual_ST6GAL1_plus_KrasG12D_KSC",
                    "comparator_X0": "Single_KrasG12D_KC_wk20_0of9",
                    "comparator_label": "KC single-oncogene KrasG12D pancreatic GEMM reference controls",
                    "outcome_variable_Y": "Wk20 invasive PDAC rate in KSC (5/9=56pct vs 0/9 KC; 6/9=67pct metastases)",
                    "outcome_domain": "Differentiation_Yield_and_Lineage_Purity", "effect_direction": "Deleterious_or_Impaired",
                    "quote": "5/9 (56%) KSC mice developed adenocarcinoma", "point_estimate": 56.0, "measurement_unit": "pct_incidence",
                    "effect_notes": "5/9 (56pct) KSC adenocarcinoma and 6/9 (67pct) distal metastases vs 0/9 KC at wk20 (zero-denominator incidence -> quarantined_ambiguous_numeric + between_arm_comparative_descriptive)",
                    "statistic_type": "quarantined_ambiguous_numeric", "contrast_type": "between_arm_comparative_descriptive",
                    "polarity_class": "Lower_Is_Better_Hazard_Endpoint", "orientation_sign": -1, "matched_lexicon_term": "adenocarcinoma",
                    "n_unit": "mouse_recipients", "timepoint": "wk20_gemm",
                    "cell_source": "NonIslet_Immune_Endothelial_or_Hematopoietic_Model", "site": "Unspecified_InVivo_or_Source_Site",
                    "tier": "Tier_4_Rodent_or_Xenogeneic_Only", "population_or_model": "Wk20_KrasG12D_GEMM_KSC_vs_KC_n9",
                    "penalty_flag": True,
                },
                {
                    "effect_id": "pmid37643018_eff3_sc_vs_wt_egfr_gsea",
                    "focal_arm_id": "pmid37643018_arm3_sc_st6gal1_only", "comparator_arm_id": "pmid37643018_arm4_wt_ctrl",
                    "cohort_id": "pmid37643018_cohort2", "focal_factor_X": "Single_ST6GAL1_WT_KRAS_SC",
                    "comparator_X0": "Cre_negative_WT_littermates",
                    "comparator_label": "Cre-negative littermate WT pancreatic reference controls at wk20",
                    "outcome_variable_Y": "WT-KRAS nonmalignant SC vs WT Fig3D EGFR pathway GSEA score (2.22, q=0.003)",
                    "outcome_domain": "Differentiation_Yield_and_Lineage_Purity", "effect_direction": "Deleterious_or_Impaired",
                    "quote": "EGFR: NES = 2.22, FDR = 0.003", "point_estimate": 2.22, "measurement_unit": "gsea_nes",
                    "effect_notes": "SC vs WT (no KrasG12D, no malignancy at wk20, n=3/genotype, Fig3D; GSEA NES score -> quarantined_ambiguous_numeric + between_arm_comparative_descriptive)",
                    "statistic_type": "quarantined_ambiguous_numeric", "contrast_type": "between_arm_comparative_descriptive",
                    "polarity_class": "Qualitative_or_Unoriented_Endpoint", "orientation_sign": 0, "matched_lexicon_term": "none_or_mixed",
                    "n_unit": "mouse_recipients", "timepoint": "wk20_gemm",
                    "cell_source": "NonIslet_Immune_Endothelial_or_Hematopoietic_Model", "site": "Unspecified_InVivo_or_Source_Site",
                    "tier": "Tier_4_Rodent_or_Xenogeneic_Only", "population_or_model": "Wk20_WT_KRAS_SC_vs_WT_n3_Fig3D",
                    "penalty_flag": True,
                },
                {
                    "effect_id": "pmid37643018_eff4_sc_vs_wt_met_gsea",
                    "focal_arm_id": "pmid37643018_arm3_sc_st6gal1_only", "comparator_arm_id": "pmid37643018_arm4_wt_ctrl",
                    "cohort_id": "pmid37643018_cohort2", "focal_factor_X": "Single_ST6GAL1_WT_KRAS_SC",
                    "comparator_X0": "Cre_negative_WT_littermates",
                    "comparator_label": "Cre-negative littermate WT pancreatic reference controls at wk20",
                    "outcome_variable_Y": "WT-KRAS nonmalignant SC vs WT Fig3D MET pathway GSEA score (2.04, q=0.010)",
                    "outcome_domain": "Differentiation_Yield_and_Lineage_Purity", "effect_direction": "Deleterious_or_Impaired",
                    "quote": "MET: NES = 2.04, FDR = 0.010", "point_estimate": 2.04, "measurement_unit": "gsea_nes",
                    "effect_notes": "SC vs WT (no KrasG12D, no malignancy at wk20, n=3/genotype, Fig3D; GSEA NES score -> quarantined_ambiguous_numeric + between_arm_comparative_descriptive)",
                    "statistic_type": "quarantined_ambiguous_numeric", "contrast_type": "between_arm_comparative_descriptive",
                    "polarity_class": "Qualitative_or_Unoriented_Endpoint", "orientation_sign": 0, "matched_lexicon_term": "none_or_mixed",
                    "n_unit": "mouse_recipients", "timepoint": "wk20_gemm",
                    "cell_source": "NonIslet_Immune_Endothelial_or_Hematopoietic_Model", "site": "Unspecified_InVivo_or_Source_Site",
                    "tier": "Tier_4_Rodent_or_Xenogeneic_Only", "population_or_model": "Wk20_WT_KRAS_SC_vs_WT_n3_Fig3D",
                    "penalty_flag": True,
                },
                {
                    "effect_id": "pmid37643018_eff5_human_suit2_xenograft",
                    "focal_arm_id": "pmid37643018_arm5_human_suit2_oe", "comparator_arm_id": "pmid37643018_arm6_human_suit2_ev_ctrl",
                    "cohort_id": "pmid37643018_cohort3", "focal_factor_X": "Human_Suit2_ST6GAL1_OE_xenograft",
                    "comparator_X0": "Human_Suit2_EV_xenograft_controls",
                    "comparator_label": "Human Suit2 PDAC empty-vector orthotopic xenograft reference controls",
                    "outcome_variable_Y": "Accelerated orthotopic human Suit2 PDAC xenograft expansion and hepatic metastasis (n=7/group)",
                    "outcome_domain": "Differentiation_Yield_and_Lineage_Purity", "effect_direction": "Deleterious_or_Impaired",
                    "quote": "tumor growth was observed for OE", "measurement_unit": "qualitative_statement",
                    "statistic_type": "qualitative_statement_only", "contrast_type": "between_arm_comparative_descriptive",
                    "polarity_class": "Qualitative_or_Unoriented_Endpoint", "orientation_sign": 0, "matched_lexicon_term": "none_or_mixed",
                    "n_unit": "mouse_recipients",
                    "cell_source": "Human_NonIslet_Immortalized_Cell_Line", "site": "Unspecified_InVivo_or_Source_Site",
                    "tier": "Tier_3_Human_Cells_AbioticStress_or_ImmunodeficientMouse", "population_or_model": "Human_Suit2_PDAC_orthotopic_xenograft_n7",
                    "penalty_flag": True,
                },
            ],
            "ceg_arms": [
                {"arm_id": "A1_KSC", "label": "KSC dual-transgenic pancreatic GEMM combining ST6GAL1 and KrasG12D", "edits": ["ST6GAL1_Transgenic_OE", "KRAS_G12D"], "n": "n=10 survival; n=9 wk20; n=3 RNA-Seq", "iso": "Direct paired transgene comparison"},
                {"arm_id": "A2_KC", "label": "KC single-oncogene KrasG12D pancreatic GEMM controls", "edits": ["KRAS_G12D"], "n": "n=10 survival; n=9 wk20; n=3 RNA-Seq", "iso": "Baseline comparator"},
                {"arm_id": "A3_SC", "label": "SC single-transgene ST6GAL1-only mice (wild-type KRAS; nonmalignant wk20)", "edits": ["ST6GAL1_Transgenic_OE"], "n": "n=3 RNA-Seq; n=8 SOX9 IHC", "iso": "Direct paired transgene comparison"},
                {"arm_id": "A4_WT", "label": "Cre-negative littermate wild-type control mice", "edits": [], "n": "n=3 RNA-Seq; n=8 SOX9 IHC", "iso": "Baseline comparator"},
                {"arm_id": "A5_Suit2_OE", "label": "Human Suit2 PDAC orthotopic xenografts with ectopic ST6GAL1 vs EV", "edits": ["ST6GAL1_Transgenic_OE"], "n": "n=7 mice/group (Suit2 OE vs EV); n=11 (S2-013 KD)", "iso": "Paired negative control"},
            ],
            "ceg_outcomes": [
                {"oid": "O1", "endpoint": "Kaplan-Meier median survival on KRASG12D background (KSC vs KC)", "comp": "A1_KSC vs A2_KC", "dir": "unfavorable_or_toxic", "stat": "median_no_iqr", "tier": "T5_Rodent_or_CellLine", "ival": "4.3 mo (KSC) vs 13.6 mo (KC); -68.4pct / 3.16x shorter (n=10/group, P<0.0001)", "summary": "Adding transgenic pancreatic ST6GAL1 onto KRASG12D shortened median survival by 68.4pct (13.6 to 4.3 months; 3.16-fold reduction, n=10/group, P<0.0001) in oncogenic mouse GEMMs.", "quote_eff": "pmid37643018_eff1_ksc_vs_kc_survival"},
                {"oid": "O2", "endpoint": "Wk20 adenocarcinoma and distal metastasis incidence (KSC vs KC)", "comp": "A1_KSC vs A2_KC", "dir": "unfavorable_or_toxic", "stat": "proportion_or_rate", "tier": "T5_Rodent_or_CellLine", "ival": "5/9 (56pct) adenocarcinoma & 6/9 (67pct) metastases vs 0/9 in KC", "summary": "At 20 weeks, 5/9 KSC mice had invasive adenocarcinoma and 6/9 had distal metastases versus 0/9 KC littermates.", "quote_eff": "pmid37643018_eff2_ksc_20wk_pdac"},
                {"oid": "O3", "endpoint": "WT-KRAS nonmalignant SC vs WT Fig3D GSEA (EGFR, MET) & ductal SOX9", "comp": "A3_SC vs A4_WT", "dir": "unfavorable_or_toxic", "stat": "descriptive_scalar", "tier": "T5_Rodent_or_CellLine", "ival": "EGFR +2.22 (q=0.003); MET +2.04 (q=0.010); 0pct malignancy at wk20", "summary": "Without KRASG12D or overt 20-week tumors, ectopic ST6GAL1 in SC mice activated EGFR (+2.22), MET (+2.04), and SOX9 ductal gene networks.", "quote_eff": "pmid37643018_eff3_sc_vs_wt_egfr_gsea"},
                {"oid": "O4", "endpoint": "Human Suit2 PDAC orthotopic xenograft growth and liver metastasis in immunodeficient mice", "comp": "A5_Suit2_OE vs EV control", "dir": "unfavorable_or_toxic", "stat": "qualitative_with_pvalue", "tier": "T5_Rodent_or_CellLine", "ival": "Elevated pancreatic BLI tumor growth and liver metastasis (n=7/group, P<0.05)", "summary": "ST6GAL1 overexpression accelerated orthotopic human Suit2 PDAC tumor expansion and hepatic metastasis in immunodeficient mice (n=7/group, P<0.05); knockdown reversed growth.", "quote_eff": "pmid37643018_eff5_human_suit2_xenograft"},
            ],
            "ceg_relation": "contradicts", "ceg_applicability": "justified_bridge",
            "ceg_edge_claim": "Pancreatic ST6GAL1 cut oncogenic KRASG12D mouse median survival by 68.4pct (13.6 to 4.3 months), activated EGFR/MET/SOX9 in WT-KRAS SC mice, and accelerated human Suit2 PDAC xenografts, motivating precautionary genetic ST6GAL1 exclusion (GY-029).",
        },
        # ------------------------------------------------------------------
        # 3. PMID:34130115 (Gu et al. J Autoimmun 2021 — Non-OA abstract)
        # ------------------------------------------------------------------
        {
            "pmid": "34130115", "ceg_qid": "PMID:34130115", "citation_short": "Gu 2021",
            "oa_pub_allowed": False, "oa_lic": None, "ft_sections": None,
            "pillars": ["Pillar2_Immune_Cloaking_Autoantigen_Neoantigen_Stealth"],
            "tier": "Tier_2B_Human_Cells_InVitro_HumanImmune_or_AutoAb_CoCulture",
            "ceg_tier": "T4_Human_Islet_or_SC_Islet_InVitro",
            "ceg_model": "Cross-sectional new-onset human T1D cohort (n=313) vs healthy controls (n=336), longitudinal pediatric cohort (n=30), and human beta-cell immunofluorescence",
            "ceg_immune": "Endogenous human T1D humoral autoantibodies targeting plasma-membrane extracellular ZnT8 loops (ZnT8ecA)",
            "ceg_donor_source": "313 newly diagnosed T1D patients, 336 healthy controls, 30 longitudinally followed children, and primary human beta cells",
            "ceg_follow_up": "Cross-sectional diagnosis assay (313 T1D vs 336 controls) plus longitudinal pediatric follow-up (30 children) to clinical T1D onset",
            "ceg_target": "Gate 3 / Locus 2 Design A Design B complement CD64t IgG shield and saturability",
            "ceg_topics": ["EFF:Humoral_DSA_FcR_ADCC_Complement_CDC"],
            "arms": [
                make_arm("pmid34130115_arm1_t1d_new_onset", "Human serum autoantibody biomarker arm: recent-onset T1D patient sera screened for extracellular ZnT8ecA (74/313 seropositive; binding-only biomarker, no cytotoxic challenge)",
                         cohort_id="pmid34130115_cohort1", is_reference_control=False, sample_size_n=None, sample_size_unit="human_participants",
                         cell_source_class="NonIslet_Immune_Endothelial_or_Hematopoietic_Model", stage=None, site="InVitro_Only", sys_is="None_human_serum_biomarker",
                         challenges=_ch("Unstressed_Baseline", ag="ZnT8ec_human_serum_autoantibody_biomarker_binding_only_no_cytotoxic_challenge")),
                make_arm("pmid34130115_arm2_healthy_ctrl", "Human serum autoantibody biomarker reference arm: healthy control sera defining 99th-centile cutoff (336 control subjects; no cytotoxic challenge)",
                         cohort_id="pmid34130115_cohort1", is_reference_control=True, sample_size_n=None, sample_size_unit="human_participants",
                         cell_source_class="NonIslet_Immune_Endothelial_or_Hematopoietic_Model", stage=None, site="InVitro_Only", sys_is="None_human_serum_biomarker",
                         challenges=_ch("Unstressed_Baseline", ag="ZnT8ec_human_serum_autoantibody_biomarker_binding_only_no_cytotoxic_challenge")),
                make_arm("pmid34130115_arm3_pediatric_longitudinal", "Human serum autoantibody biomarker longitudinal arm: pediatric T1D progressor sera tracked for sequential IAb seroconversion (30 youth; 10 ZnT8ecA+; no cytotoxic challenge)",
                         cohort_id="pmid34130115_cohort2", is_reference_control=False, sample_size_n=None, sample_size_unit="human_participants",
                         cell_source_class="NonIslet_Immune_Endothelial_or_Hematopoietic_Model", stage=None, site="InVitro_Only", sys_is="None_human_serum_biomarker",
                         challenges=_ch("Unstressed_Baseline", ag="ZnT8ec_human_serum_autoantibody_biomarker_binding_only_no_cytotoxic_challenge")),
            ],
            "effects": [
                {
                    "effect_id": "pmid34130115_eff1_znt8eca_prevalence",
                    "focal_arm_id": "pmid34130115_arm1_t1d_new_onset", "comparator_arm_id": "pmid34130115_arm2_healthy_ctrl",
                    "cohort_id": "pmid34130115_cohort1", "focal_factor_X": "New_onset_T1D_serum_ZnT8ecA",
                    "comparator_X0": "Healthy_human_99th_centile_cutoff",
                    "comparator_label": "Human serum autoantibody biomarker reference arm: healthy control sera defining 99th-centile cutoff (336 control subjects; no cytotoxic challenge)",
                    "outcome_variable_Y": "ZnT8ecA seropositivity in recent-onset T1D (74/313 = 23.6pct vs 336 healthy control subjects)",
                    "outcome_domain": "Autoimmune_TCR_or_AutoAb_Evasion", "effect_direction": "Deleterious_or_Impaired",
                    "quote": "99th percentile of 336 healthy controls, the ZnT8ecA positivity rate was 23.6% (74/313)",
                    "point_estimate": 23.6, "measurement_unit": "pct_positive",
                    "effect_notes": "Human serum biomarker prevalence: 74/313 (23.6pct) recent-onset T1D subjects above 99th-centile cutoff across 336 control donors; separate immunofluorescence showed live beta-cell membrane binding without cytotoxic ADCC/CDC testing (encoded as quarantined_ambiguous_numeric + between_arm_comparative_descriptive).",
                    "statistic_type": "quarantined_ambiguous_numeric", "contrast_type": "between_arm_comparative_descriptive",
                    "polarity_class": "Lower_Is_Better_Hazard_Endpoint", "orientation_sign": -1, "matched_lexicon_term": "autoantibody",
                    "n_unit": "human_participants", "cell_source": "NonIslet_Immune_Endothelial_or_Hematopoietic_Model", "stage": None, "site": "InVitro_Only",
                    "tier": "Tier_2B_Human_Cells_InVitro_HumanImmune_or_AutoAb_CoCulture",
                    "population_or_model": "313_new_onset_T1D_sera_vs_336_healthy_control_sera",
                },
                {
                    "effect_id": "pmid34130115_eff2_znt8eca_earliest_iab",
                    "focal_arm_id": "pmid34130115_arm3_pediatric_longitudinal", "comparator_arm_id": None,
                    "cohort_id": "pmid34130115_cohort2", "focal_factor_X": "Pediatric_longitudinal_ZnT8ecA_seroconversion",
                    "comparator_X0": "Within_subject_IAb_appearance_order", "comparator_label": None,
                    "outcome_variable_Y": "ZnT8ecA earliest IAb in 10/10 seropositive youth among 30 monitored longitudinally (7/10 first alone, 3/10 co-first)",
                    "outcome_domain": "Autoimmune_TCR_or_AutoAb_Evasion", "effect_direction": "Deleterious_or_Impaired",
                    "quote": "ZnT8ecA was the earliest IAb to appear in all 10 children",
                    "measurement_unit": "earliest_IAb_proportion",
                    "effect_notes": "Pediatric serum biomarker cohort: 10/10 earliest or co-earliest autoantibody among selected ZnT8ecA+ youth within 30 longitudinally monitored subjects (7/10 first alone, 3/10 co-first per full text; no cytotoxic challenge).",
                    "statistic_type": "single_arm_descriptive_only", "contrast_type": "longitudinal_or_within_arm_descriptive",
                    "polarity_class": "Qualitative_or_Unoriented_Endpoint", "orientation_sign": 0, "matched_lexicon_term": "none_or_mixed",
                    "n_unit": "human_participants", "cell_source": "NonIslet_Immune_Endothelial_or_Hematopoietic_Model", "stage": None, "site": "InVitro_Only",
                    "tier": "Tier_2B_Human_Cells_InVitro_HumanImmune_or_AutoAb_CoCulture",
                    "population_or_model": "30_longitudinal_pediatric_sera_10_ZnT8ecA_pos",
                },
            ],
            "ceg_arms": [
                {"arm_id": "A1_t1d_new_onset", "label": "Newly diagnosed human T1D cohort tested for extracellular ZnT8ecA", "edits": [], "n": "313 new-onset T1D patients", "iso": "NOT_ESTABLISHED"},
                {"arm_id": "A2_healthy_controls", "label": "Healthy human control cohort defining 99th-percentile assay specificity", "edits": [], "n": "336 healthy controls", "iso": "Baseline comparator"},
                {"arm_id": "A3_pediatric_longitudinal", "label": "Pediatric longitudinal T1D progression cohort tracked across IAA, GADA, IA-2A, ZnT8icA, ZnT8ecA", "edits": [], "n": "30 children (10 ZnT8ecA+)", "iso": "NOT_ESTABLISHED"},
            ],
            "ceg_outcomes": [
                {"oid": "O1", "endpoint": "Extracellular ZnT8ecA prevalence in new-onset T1D and live beta-cell surface staining", "comp": "A1_t1d_new_onset vs A2_healthy_controls", "dir": "unfavorable_or_toxic", "stat": "proportion_or_rate", "tier": "T4_Human_Islet_or_SC_Islet_InVitro", "ival": "74/313 (23.6pct) at 99th percentile of 336 controls; positive human beta-cell surface IF", "summary": "ZnT8ecA was positive in 74/313 (23.6pct) newly diagnosed T1D subjects at the 99th percentile of 336 controls and directly labeled intact human beta-cell surfaces (killing not measured).", "quote_eff": "pmid34130115_eff1_znt8eca_prevalence"},
                {"oid": "O2", "endpoint": "Longitudinal order of ZnT8ecA seroconversion in selected pediatric progressors", "comp": "A3_pediatric_longitudinal (within-subject timing)", "dir": "unfavorable_or_toxic", "stat": "proportion_or_rate", "tier": "T1_Human_Clinical", "ival": "10/10 earliest/co-earliest IAb (7/10 first alone, 3/10 co-first) among 10 ZnT8ecA+ of 30 children", "summary": "Among 30 children monitored longitudinally, 10 were ZnT8ecA-positive and ZnT8ecA appeared earliest in all 10 (first alone in 7/10 and co-first in 3/10).", "quote_eff": "pmid34130115_eff2_znt8eca_earliest_iab"},
            ],
            "ceg_relation": "supports", "ceg_applicability": "matched_domain",
            "ceg_edge_claim": "Surface-reactive ZnT8ecA occurs in 74/313 (23.6pct) new-onset T1D patients and binds intact human beta-cell membranes, establishing an endogenous surface-binding autoantibody hypothesis for Stage-0 CD64t screening.",
        },
        # ------------------------------------------------------------------
        # 4. PMID:10480601 (Giannoukakis et al. Diabetes 1999 — canonical M3217, Non-OA)
        # Retiered per primary source: soluble recombinant IL-1beta + Fas/CD95 stimuli on primary human islets -> Ring-1 Tier_3 (NOT immune co-culture Tier_2B!); CEG T4 primary human islets valid.
        # ------------------------------------------------------------------
        {
            "pmid": "10480601", "ceg_qid": "M3217", "citation_short": "Giannoukakis 1999",
            "oa_pub_allowed": False, "oa_lic": None, "ft_sections": None,
            "pillars": ["Pillar3_Intrinsic_BetaCell_Genetic_Resilience_Amyloid_Viral"],
            "tier": "Tier_3_Human_Cells_AbioticStress_or_ImmunodeficientMouse",
            "ceg_tier": "T4_Human_Islet_or_SC_Islet_InVitro",
            "ceg_model": "Cultured primary human pancreatic islets transduced with adenoviral IL-1Ra cDNA vs controls under soluble recombinant IL-1beta and Fas/CD95 stress (no immune-cell co-culture)",
            "ceg_immune": "Soluble recombinant IL-1beta nitric oxide stress, GSIS suppression, and CD95/Fas apoptosis sensitization",
            "ceg_donor_source": "Primary human pancreatic islets cultured in vitro (exact donor count not reported in abstract)",
            "ceg_follow_up": "In vitro cultured human islet soluble IL-1beta and Fas challenge assays (exact culture duration not reported in abstract)",
            "ceg_target": "Gate 2B / Locus 2 CD274 IL1RN systemic vs local IL-1 blockade scoping",
            "ceg_topics": ["EFF:Apoptosis_Caspase_ERStress_UPR", "EFF:Glycolysis_Mitochondria_KATP_Ca2_Exocytosis"],
            "arms": [
                make_arm("pmid10480601_arm1_ad_il1rn_islets", "Primary human islets transduced with adenoviral IL-1Ra (IL1RN) cDNA exposed to soluble IL-1beta",
                         cohort_id="pmid10480601_cohort1", is_reference_control=False, sample_size_n=None, sample_size_unit="human_islet_preparations",
                         cell_source_class="Primary_Human_Islet", stage="Primary_Mature_Islet", site="InVitro_Only", sys_is="None (ex vivo human islets)",
                         challenges=_ch("Cytokine_Cocktail_IFNg_IL1b_TNFa_or_IFNa")),
                make_arm("pmid10480601_arm2_ctrl_islets", "Control primary human islets exposed to soluble IL-1beta without adenoviral IL-1Ra gene transfer",
                         cohort_id="pmid10480601_cohort1", is_reference_control=True, sample_size_n=None, sample_size_unit="human_islet_preparations",
                         cell_source_class="Primary_Human_Islet", stage="Primary_Mature_Islet", site="InVitro_Only", sys_is="None (ex vivo human islets)",
                         challenges=_ch("Cytokine_Cocktail_IFNg_IL1b_TNFa_or_IFNa")),
            ],
            "effects": [
                {
                    "effect_id": "pmid10480601_eff1_no_and_gsis_rescue",
                    "focal_arm_id": "pmid10480601_arm1_ad_il1rn_islets", "comparator_arm_id": "pmid10480601_arm2_ctrl_islets",
                    "cohort_id": "pmid10480601_cohort1", "focal_factor_X": "Adenoviral intra-islet human IL-1Ra (IL1RN) expression",
                    "comparator_X0": "Control primary human islets exposed to soluble IL-1beta",
                    "comparator_label": "Control primary human islets exposed to soluble IL-1beta without adenoviral IL-1Ra gene transfer",
                    "outcome_variable_Y": "Protection of primary human islets against soluble IL-1beta nitric oxide generation and GSIS impairment",
                    "outcome_domain": "Cytokine_IFN_NFkB_or_ER_Stress_Survival", "effect_direction": "Protective_or_Improved",
                    "quote": "protection of human islets in vitro against IL-1beta-induced nitric oxide formation",
                    "measurement_unit": "qualitative_statement", "statistic_type": "qualitative_statement_only",
                    "contrast_type": "between_arm_comparative_descriptive",
                    "polarity_class": "Qualitative_or_Unoriented_Endpoint", "orientation_sign": 0, "matched_lexicon_term": "none_or_mixed",
                    "n_unit": "human_islet_preparations", "cell_source": "Primary_Human_Islet", "stage": "Primary_Mature_Islet", "site": "InVitro_Only",
                    "tier": "Tier_3_Human_Cells_AbioticStress_or_ImmunodeficientMouse", "population_or_model": "Cultured primary human islets under soluble IL-1beta",
                },
                {
                    "effect_id": "pmid10480601_eff2_fas_apoptosis_rescue",
                    "focal_arm_id": "pmid10480601_arm1_ad_il1rn_islets", "comparator_arm_id": "pmid10480601_arm2_ctrl_islets",
                    "cohort_id": "pmid10480601_cohort1", "focal_factor_X": "Adenoviral intra-islet human IL-1Ra (IL1RN) expression",
                    "comparator_X0": "Control primary human islets exposed to soluble IL-1beta and FasL",
                    "comparator_label": "Control primary human islets exposed to soluble IL-1beta without adenoviral IL-1Ra gene transfer",
                    "outcome_variable_Y": "Prevention of soluble IL-1beta-sensitized Fas (CD95) apoptosis activation in primary human islets",
                    "outcome_domain": "Granzyme_or_Fas_Apoptosis_Resistance", "effect_direction": "Protective_or_Improved",
                    "quote": "glucose-stimulated insulin production, and Fas-triggered apoptosis activation",
                    "measurement_unit": "qualitative_statement", "statistic_type": "qualitative_statement_only",
                    "contrast_type": "between_arm_comparative_descriptive",
                    "polarity_class": "Qualitative_or_Unoriented_Endpoint", "orientation_sign": 0, "matched_lexicon_term": "none_or_mixed",
                    "n_unit": "human_islet_preparations", "cell_source": "Primary_Human_Islet", "stage": "Primary_Mature_Islet", "site": "InVitro_Only",
                    "tier": "Tier_3_Human_Cells_AbioticStress_or_ImmunodeficientMouse", "population_or_model": "Cultured primary human islets under soluble IL-1beta + Fas",
                },
            ],
            "ceg_arms": [
                {"arm_id": "A1_ad_il1rn_islets", "label": "Primary human islets expressing adenoviral IL-1Ra (IL1RN) cDNA under IL-1beta", "edits": ["IL1RN_Local_GeneTransfer"], "n": "Primary human islet preparations (n not reported in abstract)", "iso": "Direct paired transgene comparison"},
                {"arm_id": "A2_ctrl_islets", "label": "Control primary human islets exposed to IL-1beta", "edits": [], "n": "Primary human islet preparations (n not reported in abstract)", "iso": "Baseline comparator"},
            ],
            "ceg_outcomes": [
                {"oid": "O1", "endpoint": "IL-1beta-induced nitric oxide generation and glucose-stimulated insulin preservation", "comp": "A1_ad_il1rn_islets vs A2_ctrl_islets", "dir": "favorable_to_intervention", "stat": "qualitative_no_pvalue", "tier": "T4_Human_Islet_or_SC_Islet_InVitro", "ival": "Protected NO & GSIS output in Ad-IL-1Ra human islets", "summary": "Adenoviral IL1RN transfer in primary human islets prevented IL-1beta-triggered nitric oxide accumulation and insulin-secretory decline.", "quote_eff": "pmid10480601_eff1_no_and_gsis_rescue"},
                {"oid": "O2", "endpoint": "Fas (CD95)-triggered human islet apoptosis activation", "comp": "A1_ad_il1rn_islets vs A2_ctrl_islets", "dir": "favorable_to_intervention", "stat": "qualitative_no_pvalue", "tier": "T4_Human_Islet_or_SC_Islet_InVitro", "ival": "Blocked Fas apoptosis activation in Ad-IL-1Ra human islets", "summary": "Local intra-islet IL-1Ra expression prevented IL-1beta-mediated sensitization to Fas/CD95 apoptotic killing in primary human islets.", "quote_eff": "pmid10480601_eff2_fas_apoptosis_rescue"},
            ],
            "ceg_relation": "supports", "ceg_applicability": "matched_domain",
            "ceg_edge_claim": "Autonomous intra-islet IL1RN expression directly shields primary human beta cells from IL-1beta secretory collapse and Fas-mediated cytotoxicity.",
        },
        # ------------------------------------------------------------------
        # 5. PMID:28092375 (Dror et al. Nat Immunol 2017 — Non-OA; ZERO editorializing in O1/O2!)
        # ------------------------------------------------------------------
        {
            "pmid": "28092375", "ceg_qid": "PMID:28092375", "citation_short": "Dror 2017",
            "oa_pub_allowed": False, "oa_lic": None, "ft_sections": None,
            "pillars": ["Pillar1_Differentiation_Maturation_Cytoarchitecture", "Pillar3_Intrinsic_BetaCell_Genetic_Resilience_Amyloid_Viral"],
            "tier": "Tier_4_Rodent_or_Xenogeneic_Only",
            "ceg_tier": "T5_Rodent_or_CellLine",
            "ceg_model": "Fed/fasted and obese mouse cohorts with endogenous IL-1beta signaling deficiency or SGLT2 inhibition vs wild-type controls",
            "ceg_immune": "Physiological postprandial peritoneal macrophage glucose-NLRP3-IL-1beta signaling axis",
            "ceg_donor_source": "Mouse metabolic cohorts (exact mouse sample size not reported in abstract)",
            "ceg_follow_up": "Acute postprandial refeeding and obesity cohorts in mice (duration not reported in abstract)",
            "ceg_target": "Gate 2B / Locus 2 CD274 IL1RN systemic vs local IL-1 blockade scoping",
            "ceg_topics": ["EFF:Glycolysis_Mitochondria_KATP_Ca2_Exocytosis", "EFF:Macrophage_Myeloid_SIRPa_Phagocytosis"],
            "arms": [
                make_arm("pmid28092375_arm1_il1b_deficient", "Mice lacking endogenous IL-1beta signaling during postprandial refeeding and obesity",
                         cohort_id="pmid28092375_cohort1", is_reference_control=False, sample_size_n=None, sample_size_unit="mouse_recipients",
                         cell_source_class="Rodent_Primary_Islet", stage="Primary_Mature_Islet", site="Unspecified_InVivo_or_Source_Site", sys_is="None (physiological feeding)",
                         challenges=_ch("Glucolipotoxicity_HighGlucose_Palmitate")),
                make_arm("pmid28092375_arm2_wt_refed_ctrl", "Wild-type mice with intact postprandial macrophage IL-1beta signaling during refeeding",
                         cohort_id="pmid28092375_cohort1", is_reference_control=True, sample_size_n=None, sample_size_unit="mouse_recipients",
                         cell_source_class="Rodent_Primary_Islet", stage="Primary_Mature_Islet", site="Unspecified_InVivo_or_Source_Site", sys_is="None (physiological feeding)",
                         challenges=_ch("Glucolipotoxicity_HighGlucose_Palmitate")),
                make_arm("pmid28092375_arm3_sglt2_inhibited", "Refed mice treated with sodium-glucose cotransporter SGLT2 inhibitor to normalize glycemia",
                         cohort_id="pmid28092375_cohort1", is_reference_control=False, sample_size_n=None, sample_size_unit="mouse_recipients",
                         cell_source_class="Rodent_Primary_Islet", stage="Primary_Mature_Islet", site="Unspecified_InVivo_or_Source_Site", sys_is="None (SGLT2 inhibitor)",
                         challenges=_ch("Glucolipotoxicity_HighGlucose_Palmitate")),
            ],
            "effects": [
                {
                    "effect_id": "pmid28092375_eff1_il1b_loss_insulin",
                    "focal_arm_id": "pmid28092375_arm1_il1b_deficient", "comparator_arm_id": "pmid28092375_arm2_wt_refed_ctrl",
                    "cohort_id": "pmid28092375_cohort1", "focal_factor_X": "Loss of endogenous IL-1beta signaling during refeeding and obesity",
                    "comparator_X0": "Wild-type mice with intact postprandial macrophage IL-1beta signaling",
                    "comparator_label": "Wild-type mice with intact postprandial macrophage IL-1beta signaling during refeeding",
                    "outcome_variable_Y": "Diminished postprandial plasma insulin concentration upon endogenous IL-1beta blockade",
                    "outcome_domain": "Metabolic_and_Biphasic_GSIS_Maturation", "effect_direction": "Deleterious_or_Impaired",
                    "quote": "lack of endogenous IL-1β signaling in mice during refeeding and obesity diminished the concentration of insulin in plasma.",
                    "measurement_unit": "qualitative_statement", "statistic_type": "qualitative_statement_only",
                    "contrast_type": "between_arm_comparative_descriptive",
                    "polarity_class": "Qualitative_or_Unoriented_Endpoint", "orientation_sign": 0, "matched_lexicon_term": "none_or_mixed",
                    "n_unit": "mouse_recipients", "cell_source": "Rodent_Primary_Islet", "stage": "Primary_Mature_Islet",
                    "site": "Unspecified_InVivo_or_Source_Site", "tier": "Tier_4_Rodent_or_Xenogeneic_Only",
                    "population_or_model": "Refed and obese mice lacking endogenous IL-1beta signaling",
                },
                {
                    "effect_id": "pmid28092375_eff2_sglt2_inflammation",
                    "focal_arm_id": "pmid28092375_arm3_sglt2_inhibited", "comparator_arm_id": "pmid28092375_arm2_wt_refed_ctrl",
                    "cohort_id": "pmid28092375_cohort1", "focal_factor_X": "Glycemia normalization via SGLT2 inhibition during refeeding",
                    "comparator_X0": "Wild-type refed mice without SGLT2 inhibition",
                    "comparator_label": "Wild-type mice with intact postprandial macrophage IL-1beta signaling during refeeding",
                    "outcome_variable_Y": "Prevention of postprandial macrophage inflammatory activation by SGLT2 inhibition",
                    "outcome_domain": "Innate_Myeloid_or_Neutrophil_Infiltration_and_Host_Response", "effect_direction": "Protective_or_Improved",
                    "quote": "prevented by inhibition of the sodium-glucose cotransporter SGLT2",
                    "measurement_unit": "qualitative_statement", "statistic_type": "qualitative_statement_only",
                    "contrast_type": "between_arm_comparative_descriptive",
                    "polarity_class": "Qualitative_or_Unoriented_Endpoint", "orientation_sign": 0, "matched_lexicon_term": "none_or_mixed",
                    "n_unit": "mouse_recipients", "cell_source": "Rodent_Primary_Islet", "stage": "Primary_Mature_Islet",
                    "site": "Unspecified_InVivo_or_Source_Site", "tier": "Tier_4_Rodent_or_Xenogeneic_Only",
                    "population_or_model": "Refed mice treated with SGLT2 inhibitor",
                },
            ],
            "ceg_arms": [
                {"arm_id": "A1_il1b_deficient", "label": "Mice lacking endogenous IL-1beta signaling during refeeding and obesity", "edits": ["IL1B_Signaling_Deficiency"], "n": "Mouse cohorts (n not reported in abstract)", "iso": "Direct paired transgene comparison"},
                {"arm_id": "A2_wt_refed_ctrl", "label": "Wild-type refed mice with intact macrophage NLRP3-IL-1beta signaling", "edits": [], "n": "Mouse cohorts (n not reported in abstract)", "iso": "Baseline comparator"},
                {"arm_id": "A3_sglt2_inhibited", "label": "Refed mice treated with SGLT2 inhibitor normalizing glycemia", "edits": ["SGLT2_Inhibition"], "n": "Mouse cohorts (n not reported in abstract)", "iso": "Vehicle control"},
            ],
            "ceg_outcomes": [
                {"oid": "O1", "endpoint": "Postprandial plasma insulin output under endogenous IL-1beta deficiency", "comp": "A1_il1b_deficient vs A2_wt_refed_ctrl", "dir": "unfavorable_or_toxic", "stat": "qualitative_no_pvalue", "tier": "T5_Rodent_or_CellLine", "ival": "Lower plasma insulin in refed & obese IL-1beta-deficient mice", "summary": "Ablating endogenous IL-1beta signaling in refed and obese mice decreased circulating plasma insulin levels relative to wild-type controls.", "quote_eff": "pmid28092375_eff1_il1b_loss_insulin"},
                {"oid": "O2", "endpoint": "Glycemia-dependent postprandial macrophage NLRP3-IL-1beta activation", "comp": "A3_sglt2_inhibited vs A2_wt_refed_ctrl", "dir": "favorable_to_intervention", "stat": "qualitative_no_pvalue", "tier": "T5_Rodent_or_CellLine", "ival": "Postprandial inflammation prevented by SGLT2 blockade", "summary": "Normalizing meal-time glycemia via SGLT2 blockade prevented glucose-driven macrophage NLRP3-IL-1beta inflammatory activation.", "quote_eff": "pmid28092375_eff2_sglt2_inflammation"},
            ],
            "ceg_relation": "scoping_qualification", "ceg_applicability": "justified_bridge",
            "ceg_edge_claim": "Physiological postprandial macrophage IL-1beta augments meal-time insulin output in mice, motivating prospective inflammation-inducible CD274p control of IL1RN over constitutive basal secretion (Dror 2017 did not measure CD274p basal leak).",
        },
        # ------------------------------------------------------------------
        # 6. PMID:28494868 (Garcia-Diaz et al. Cell Rep 2017 — CC-BY-NC-ND redacted)
        # Retiered per primary source: human melanoma cell lines + oncology biopsies are non-islet -> Ring-1 Tier_3, CEG T5_Rodent_or_CellLine (NOT islet T4 or immune co-culture Tier_2B!).
        # ------------------------------------------------------------------
        {
            "pmid": "28494868", "ceg_qid": "PMID:28494868", "citation_short": "Garcia-Diaz 2017",
            "oa_pub_allowed": False, "oa_lic": None, "ft_sections": None,
            "pillars": ["Pillar2_Immune_Cloaking_Autoantigen_Neoantigen_Stealth"],
            "tier": "Tier_3_Human_Cells_AbioticStress_or_ImmunodeficientMouse",
            "ceg_tier": "T5_Rodent_or_CellLine",
            "ceg_model": "Human melanoma cell lines stimulated with IFN-gamma vs IFN-beta plus non-islet human melanoma patient biopsy transcriptome profiles (anti-PD-1 responders; T5 non-islet oncology)",
            "ceg_immune": "Human IFN-gamma JAK1/2-STAT1/2/3-IRF1 transcriptional regulation of CD274 (PD-L1) and PD-L2 promoters",
            "ceg_donor_source": "Human melanoma cell lines and clinical human melanoma patient tumor biopsies (exact n not reported in abstract)",
            "ceg_follow_up": "In vitro IFN stimulation assays plus clinical human anti-PD-1 tumor biopsy cohort (duration not reported in abstract)",
            "ceg_target": "Gate 2B / Gate 3 / Locus 2 CD274 inducible IL1RN amyloid macrophage shield",
            "ceg_topics": ["EFF:JAK_STAT_IFN_IRF1_MHC_Upregulation"],
            "arms": [
                make_arm("pmid28494868_arm1_human_melanoma_ifng", "Human melanoma cell lines stimulated with IFN-gamma mapped for JAK1/2-STAT1/2/3-IRF1 binding at PD-L1 promoter",
                         cohort_id="pmid28494868_cohort1", is_reference_control=False, sample_size_n=None, sample_size_unit="in_vitro_monoculture_replicates",
                         cell_source_class="Human_NonIslet_Immortalized_Cell_Line", site="InVitro_Only", sys_is="None (human in vitro signaling)",
                         challenges=_ch("Cytokine_Cocktail_IFNg_IL1b_TNFa_or_IFNa")),
                make_arm("pmid28494868_arm2_human_melanoma_ifnb", "Human melanoma cell lines stimulated with IFN-beta comparator arm (PD-L2 STAT3/IRF1 regulation)",
                         cohort_id="pmid28494868_cohort1", is_reference_control=True, sample_size_n=None, sample_size_unit="in_vitro_monoculture_replicates",
                         cell_source_class="Human_NonIslet_Immortalized_Cell_Line", site="InVitro_Only", sys_is="None (human in vitro signaling)",
                         challenges=_ch("Cytokine_Cocktail_IFNg_IL1b_TNFa_or_IFNa")),
                make_arm("pmid28494868_arm3_human_patient_biopsies", "Non-islet clinical melanoma patient tumor biopsies profiled for STAT1/2/3 and IRF1 target upregulation in anti-PD-1 responders",
                         cohort_id="pmid28494868_cohort2", is_reference_control=False, sample_size_n=None, sample_size_unit="human_participants",
                         cell_source_class="NonIslet_Immune_Endothelial_or_Hematopoietic_Model", site="Unspecified_InVivo_or_Source_Site", sys_is="Anti-PD-1 clinical melanoma biopsy cohort",
                         challenges=_ch("Unstressed_Baseline")),
            ],
            "effects": [
                {
                    "effect_id": "pmid28494868_eff1_ifng_irf1_pdl1",
                    "focal_arm_id": "pmid28494868_arm1_human_melanoma_ifng", "comparator_arm_id": "pmid28494868_arm2_human_melanoma_ifnb",
                    "cohort_id": "pmid28494868_cohort1", "focal_factor_X": "Human IFN-gamma-JAK1/2-STAT1/2/3-IRF1 axis on CD274 (PD-L1) promoter",
                    "comparator_X0": "IFN-beta comparator signaling on PD-L2 promoter",
                    "comparator_label": "Human melanoma cell lines stimulated with IFN-beta comparator arm (PD-L2 STAT3/IRF1 regulation)",
                    "outcome_variable_Y": "Primary IFN-gamma-JAK1/2-STAT1/2/3-IRF1 promoter binding regulating human PD-L1 expression",
                    "outcome_domain": "Surface_HLA_or_Transgene_Expression_Level", "effect_direction": "Protective_or_Improved",
                    "quote": "interferon-gamma-JAK1/JAK2-STAT1/STAT2/STAT3-IRF1 axis primarily regulates PD-L1 expression",
                    "measurement_unit": "qualitative_statement", "statistic_type": "qualitative_statement_only",
                    "contrast_type": "between_arm_comparative_descriptive",
                    "polarity_class": "Qualitative_or_Unoriented_Endpoint", "orientation_sign": 0, "matched_lexicon_term": "none_or_mixed",
                    "n_unit": "in_vitro_monoculture_replicates", "cell_source": "Human_NonIslet_Immortalized_Cell_Line", "site": "InVitro_Only",
                    "tier": "Tier_3_Human_Cells_AbioticStress_or_ImmunodeficientMouse", "population_or_model": "Human melanoma cell lines under IFN-gamma vs IFN-beta",
                },
                {
                    "effect_id": "pmid28494868_eff2_patient_biopsies_stat_irf1",
                    "focal_arm_id": "pmid28494868_arm3_human_patient_biopsies", "comparator_arm_id": None,
                    "cohort_id": "pmid28494868_cohort2", "focal_factor_X": "Human melanoma patient tumor interferon signature in anti-PD-1 responders",
                    "comparator_X0": "Patient biopsy transcriptomic pathway analysis", "comparator_label": None,
                    "outcome_variable_Y": "Confirmed interferon signature and STAT1/2/3 + IRF1 target gene enrichment in non-islet human melanoma biopsies",
                    "outcome_domain": "Surface_HLA_or_Transgene_Expression_Level", "effect_direction": "Descriptive_or_Unoriented",
                    "quote": "biopsy specimens from patients with melanoma confirmed interferon signature enrichment",
                    "measurement_unit": "qualitative_statement", "statistic_type": "single_arm_descriptive_only",
                    "contrast_type": "single_arm_descriptive_only",
                    "polarity_class": "Qualitative_or_Unoriented_Endpoint", "orientation_sign": 0, "matched_lexicon_term": "none_or_mixed",
                    "n_unit": "human_participants", "cell_source": "NonIslet_Immune_Endothelial_or_Hematopoietic_Model", "site": "Unspecified_InVivo_or_Source_Site",
                    "tier": "Tier_3_Human_Cells_AbioticStress_or_ImmunodeficientMouse", "population_or_model": "Non-islet clinical human melanoma patient tumor biopsies",
                },
            ],
            "ceg_arms": [
                {"arm_id": "A1_human_melanoma_ifng", "label": "Human melanoma cell lines stimulated with IFN-gamma", "edits": [], "n": "Human melanoma cell lines (n not reported in abstract)", "iso": "NOT_ESTABLISHED"},
                {"arm_id": "A2_human_melanoma_ifnb", "label": "Human melanoma cell lines stimulated with IFN-beta", "edits": [], "n": "Human melanoma cell lines (n not reported in abstract)", "iso": "Baseline comparator"},
                {"arm_id": "A3_patient_biopsies", "label": "Non-islet human melanoma patient biopsy specimens from anti-PD-1 responders", "edits": [], "n": "Human patient biopsy cohort (n not reported in abstract)", "iso": "NOT_ESTABLISHED"},
            ],
            "ceg_outcomes": [
                {"oid": "O1", "endpoint": "IFN-gamma JAK1/2-STAT1/2/3-IRF1 control of human PD-L1 promoter", "comp": "A1_human_melanoma_ifng vs A2_human_melanoma_ifnb", "dir": "descriptive_or_neutral", "stat": "qualitative_no_pvalue", "tier": "T5_Rodent_or_CellLine", "ival": "Direct IRF1 promoter binding drives IFN-gamma PD-L1 induction", "summary": "Human melanoma signaling mapping established that IFN-gamma drives PD-L1 primarily via JAK1/2-STAT1/2/3-IRF1 promoter binding, whereas PD-L2 responds to both IFN-beta and IFN-gamma.", "quote_eff": "pmid28494868_eff1_ifng_irf1_pdl1"},
                {"oid": "O2", "endpoint": "STAT1/2/3 and IRF1 target upregulation in non-islet human melanoma biopsies", "comp": "A3_patient_biopsies (anti-PD-1 responders)", "dir": "descriptive_or_neutral", "stat": "qualitative_no_pvalue", "tier": "T5_Rodent_or_CellLine", "ival": "Enriched interferon & STAT/IRF1 gene signatures in melanoma tumor biopsies", "summary": "Non-islet melanoma biopsy profiles from anti-PD-1-responsive patients exhibited enriched interferon pathways alongside elevated STAT1/2/3 and IRF1 target transcripts.", "quote_eff": "pmid28494868_eff2_patient_biopsies_stat_irf1"},
            ],
            "ceg_relation": "supports", "ceg_applicability": "justified_bridge",
            "ceg_edge_claim": "IFN-gamma drives human CD274 transcription via direct JAK1/2-STAT1/2/3-IRF1 promoter binding in cultured human melanoma cell lines (with anti-PD-1 patient tumor biopsies supplying correlative interferon/STAT/IRF1 transcript-expression data), grounding inflammation-inducible CD274p_250 gating of IL1RN (subject to beta-cell IFN titration).",
        },
        # ------------------------------------------------------------------
        # 7. PMID:2139669 (Arend et al. J Clin Invest 1990 — Non-OA)
        # Retiered per primary source: mixed non-islet human synovial cells, rabbit chondrocytes & murine thymocytes -> CEG T5_Rodent_or_CellLine (NOT islet T4!).
        # Split O2 (PGE2 in human synovial cells + rabbit chondrocytes) vs O3 (collagenase in human synovial cells ONLY) per primary abstract.
        # ------------------------------------------------------------------
        {
            "pmid": "2139669", "ceg_qid": "PMID:2139669", "citation_short": "Arend 1990",
            "oa_pub_allowed": False, "oa_lic": None, "ft_sections": None,
            "pillars": ["Pillar3_Intrinsic_BetaCell_Genetic_Resilience_Amyloid_Viral"],
            "tier": "Tier_3_Human_Cells_AbioticStress_or_ImmunodeficientMouse",
            "ceg_tier": "T5_Rodent_or_CellLine",
            "ceg_model": "Mixed non-islet IL-1 assays: human synovial cells (PGE2 & collagenase), rabbit articular chondrocytes (PGE2), and PHA-stimulated murine thymocytes (proliferation) titrated with recombinant human IL-1Ra against IL-1alpha/beta (T5 non-islet)",
            "ceg_immune": "Competitive human IL-1 receptor antagonism blocking IL-1alpha/beta PGE2 (synovial cells & rabbit chondrocytes), collagenase (human synovial cells), and murine thymocyte proliferation",
            "ceg_donor_source": "Human synovial cells, rabbit articular chondrocytes, and murine thymocytes (exact n not reported in abstract)",
            "ceg_follow_up": "In vitro dose-response titration of recombinant human IL-1Ra (17 kDa) vs exogenous IL-1alpha/beta",
            "ceg_target": "Gate 2B / Locus 2 CD274 IL1RN systemic vs local IL-1 blockade scoping",
            "ceg_topics": ["EFF:Apoptosis_Caspase_ERStress_UPR"],
            "arms": [
                make_arm("pmid2139669_arm1_human_synovial_il1ra", "Human synovial cells treated with recombinant human IL-1Ra titrated against IL-1alpha/beta",
                         cohort_id="pmid2139669_cohort1", is_reference_control=False, sample_size_n=None, sample_size_unit="in_vitro_monoculture_replicates",
                         cell_source_class="NonIslet_Immune_Endothelial_or_Hematopoietic_Model", site="InVitro_Only", sys_is="None (in vitro protein titration)",
                         challenges=_ch("Cytokine_Cocktail_IFNg_IL1b_TNFa_or_IFNa")),
                make_arm("pmid2139669_arm2_human_synovial_il1_ctrl", "Human synovial cells stimulated with IL-1alpha/beta without recombinant human IL-1Ra",
                         cohort_id="pmid2139669_cohort1", is_reference_control=True, sample_size_n=None, sample_size_unit="in_vitro_monoculture_replicates",
                         cell_source_class="NonIslet_Immune_Endothelial_or_Hematopoietic_Model", site="InVitro_Only", sys_is="None (in vitro protein titration)",
                         challenges=_ch("Cytokine_Cocktail_IFNg_IL1b_TNFa_or_IFNa")),
                make_arm("pmid2139669_arm3_rabbit_murine_il1ra", "Rabbit articular chondrocytes (PGE2 assay) and PHA-stimulated murine thymocytes (proliferation assay) titrated with recombinant human IL-1Ra",
                         cohort_id="pmid2139669_cohort2", is_reference_control=False, sample_size_n=None, sample_size_unit="in_vitro_monoculture_replicates",
                         cell_source_class="NonIslet_Immune_Endothelial_or_Hematopoietic_Model", site="InVitro_Only", sys_is="None (in vitro protein titration)",
                         challenges=_ch("Cytokine_Cocktail_IFNg_IL1b_TNFa_or_IFNa")),
            ],
            "effects": [
                {
                    "effect_id": "pmid2139669_eff1_100fold_stoichiometry",
                    "focal_arm_id": "pmid2139669_arm1_human_synovial_il1ra", "comparator_arm_id": "pmid2139669_arm2_human_synovial_il1_ctrl",
                    "cohort_id": "pmid2139669_cohort1", "focal_factor_X": "Recombinant human IL-1Ra molar excess vs exogenous IL-1alpha/beta",
                    "comparator_X0": "Unopposed IL-1alpha/beta stimulation in human synovial cells",
                    "comparator_label": "Human synovial cells stimulated with IL-1alpha/beta without recombinant human IL-1Ra",
                    "outcome_variable_Y": "Stoichiometric molar excess of IL-1Ra required for 50% inhibition of IL-1 biological responses (up to 100-fold)",
                    "outcome_domain": "Cytokine_IFN_NFkB_or_ER_Stress_Survival", "effect_direction": "Descriptive_or_Unoriented",
                    "quote": "IL-1-induced biological responses requires amounts of IL-1ra up to 100-fold",
                    "point_estimate": 100.0, "measurement_unit": "molar_excess_fold_for_50pct_inhibition",
                    "effect_notes": "Numeric comparative molar stoichiometry threshold: up to 100-fold molar IL-1Ra excess over IL-1alpha/beta required for 50pct biological blockade despite near-equal receptor affinity (encoded as quarantined_ambiguous_numeric + between_arm_comparative_descriptive).",
                    "statistic_type": "quarantined_ambiguous_numeric", "contrast_type": "between_arm_comparative_descriptive",
                    "polarity_class": "Qualitative_or_Unoriented_Endpoint", "orientation_sign": 0, "matched_lexicon_term": "none_or_mixed",
                    "n_unit": "in_vitro_monoculture_replicates", "cell_source": "NonIslet_Immune_Endothelial_or_Hematopoietic_Model", "site": "InVitro_Only",
                    "tier": "Tier_3_Human_Cells_AbioticStress_or_ImmunodeficientMouse", "population_or_model": "Human synovial cells, rabbit chondrocytes & murine thymocytes",
                },
                {
                    "effect_id": "pmid2139669_eff2_synovial_and_chondrocyte_pge2",
                    "focal_arm_id": "pmid2139669_arm1_human_synovial_il1ra", "comparator_arm_id": "pmid2139669_arm2_human_synovial_il1_ctrl",
                    "cohort_id": "pmid2139669_cohort1", "focal_factor_X": "Recombinant human IL-1Ra receptor blockade (PGE2 assay)",
                    "comparator_X0": "Unopposed IL-1alpha/beta stimulation of PGE2",
                    "comparator_label": "Human synovial cells stimulated with IL-1alpha/beta without recombinant human IL-1Ra",
                    "outcome_variable_Y": "Blockade of IL-1alpha/beta-evoked PGE2 release across rabbit articular chondrocytes plus cultured human synovial cells",
                    "outcome_domain": "Cytokine_IFN_NFkB_or_ER_Stress_Survival", "effect_direction": "Protective_or_Improved",
                    "quote": "PGE2 production in human synovial cells",
                    "measurement_unit": "qualitative_statement", "statistic_type": "qualitative_statement_only",
                    "contrast_type": "between_arm_comparative_descriptive",
                    "polarity_class": "Qualitative_or_Unoriented_Endpoint", "orientation_sign": 0, "matched_lexicon_term": "none_or_mixed",
                    "n_unit": "in_vitro_monoculture_replicates", "cell_source": "NonIslet_Immune_Endothelial_or_Hematopoietic_Model", "site": "InVitro_Only",
                    "tier": "Tier_3_Human_Cells_AbioticStress_or_ImmunodeficientMouse", "population_or_model": "Rabbit articular chondrocytes plus cultured human synovial cells (PGE2)",
                },
                {
                    "effect_id": "pmid2139669_eff3_human_synovial_collagenase",
                    "focal_arm_id": "pmid2139669_arm1_human_synovial_il1ra", "comparator_arm_id": "pmid2139669_arm2_human_synovial_il1_ctrl",
                    "cohort_id": "pmid2139669_cohort1", "focal_factor_X": "Recombinant human IL-1Ra receptor blockade (collagenase assay)",
                    "comparator_X0": "Unopposed IL-1alpha/beta stimulation of collagenase in human synovial cultures",
                    "comparator_label": "Human synovial cells stimulated with IL-1alpha/beta without recombinant human IL-1Ra",
                    "outcome_variable_Y": "Blockade of IL-1alpha/beta-evoked collagenase release specifically in cultured human synovial cells",
                    "outcome_domain": "Cytokine_IFN_NFkB_or_ER_Stress_Survival", "effect_direction": "Protective_or_Improved",
                    "quote": "collagenase production by the synovial cells",
                    "measurement_unit": "qualitative_statement", "statistic_type": "qualitative_statement_only",
                    "contrast_type": "between_arm_comparative_descriptive",
                    "polarity_class": "Qualitative_or_Unoriented_Endpoint", "orientation_sign": 0, "matched_lexicon_term": "none_or_mixed",
                    "n_unit": "in_vitro_monoculture_replicates", "cell_source": "NonIslet_Immune_Endothelial_or_Hematopoietic_Model", "site": "InVitro_Only",
                    "tier": "Tier_3_Human_Cells_AbioticStress_or_ImmunodeficientMouse", "population_or_model": "Cultured human synovial cells only (collagenase)",
                },
            ],
            "ceg_arms": [
                {"arm_id": "A1_human_synovial_il1ra", "label": "Human synovial cells treated with recombinant human 17 kDa IL-1Ra", "edits": ["Recombinant_Human_IL1Ra"], "n": "Human synovial cell assays (n not reported in abstract)", "iso": "Pharmacologic IL-1R blockade"},
                {"arm_id": "A2_human_synovial_ctrl", "label": "Human synovial cells stimulated with IL-1alpha/beta alone", "edits": [], "n": "Human synovial cell assays (n not reported in abstract)", "iso": "Baseline comparator"},
                {"arm_id": "A3_rabbit_murine_il1ra", "label": "Rabbit articular chondrocytes (PGE2) and PHA-stimulated murine thymocytes (proliferation) with recombinant IL-1Ra", "edits": ["Recombinant_Human_IL1Ra"], "n": "Rabbit chondrocytes & murine thymocytes (n not reported in abstract)", "iso": "Pharmacologic IL-1R blockade"},
            ],
            "ceg_outcomes": [
                {"oid": "O1", "endpoint": "Molar IL-1Ra excess required for 50% inhibition of IL-1alpha/beta responses across non-islet assays", "comp": "A1_human_synovial_il1ra & A3_rabbit_murine_il1ra vs controls", "dir": "descriptive_or_neutral", "stat": "threshold_or_limit", "tier": "T5_Rodent_or_CellLine", "ival": "Up to 100-fold molar IL-1Ra:IL-1 excess for 50% inhibition (incl. murine thymocyte proliferation)", "summary": "Half-maximal inhibition of IL-1alpha/beta responses across human synovial cells, rabbit chondrocytes, and PHA-stimulated murine thymocytes required up to 100-fold molar excess of recombinant human IL-1Ra despite near-equal receptor affinity.", "quote_eff": "pmid2139669_eff1_100fold_stoichiometry"},
                {"oid": "O2", "endpoint": "Blockade of IL-1-evoked PGE2 release across rabbit chondrocytes and human synovial cultures", "comp": "A1_human_synovial_il1ra & A3_rabbit_murine_il1ra vs controls", "dir": "favorable_to_intervention", "stat": "qualitative_no_pvalue", "tier": "T5_Rodent_or_CellLine", "ival": "Inhibited IL-1-evoked PGE2 release across rabbit chondrocytes plus human synovial cultures", "summary": "Purified 17 kDa recombinant IL-1Ra inhibited IL-1alpha/beta-evoked PGE2 synthesis across both rabbit articular chondrocytes and cultured human synovial cells.", "quote_eff": "pmid2139669_eff2_synovial_and_chondrocyte_pge2"},
                {"oid": "O3", "endpoint": "Blockade of IL-1-evoked collagenase release in cultured human synovial cells", "comp": "A1_human_synovial_il1ra vs A2_human_synovial_ctrl", "dir": "favorable_to_intervention", "stat": "qualitative_no_pvalue", "tier": "T5_Rodent_or_CellLine", "ival": "Inhibited IL-1-evoked collagenase release in cultured human synovial cells only", "summary": "Purified 17 kDa recombinant IL-1Ra blocked IL-1alpha/beta-driven collagenase release specifically in cultured human synovial cells (separate from the rabbit chondrocyte PGE2 substrate).", "quote_eff": "pmid2139669_eff3_human_synovial_collagenase"},
            ],
            "ceg_relation": "scoping_qualification", "ceg_applicability": "justified_bridge",
            "ceg_edge_claim": "Competitive IL-1R1 antagonism required up to 100-fold molar IL-1Ra excess for 50% inhibition in assay-specific non-islet contexts, motivating a prospective Stage-0 ELISA secretion potency criterion for CD274p::IL1RN.",
        },
        # ------------------------------------------------------------------
        # 8. PMID:18023480 (Beekman et al. Mol Immunol 2008 — Non-OA; ZERO UniProt 312-332 or 2023/2026 editorializing in O1/O2!)
        # ------------------------------------------------------------------
        {
            "pmid": "18023480", "ceg_qid": "PMID:18023480", "citation_short": "Beekman 2008",
            "oa_pub_allowed": False, "oa_lic": None, "ft_sections": None,
            "pillars": ["Pillar2_Immune_Cloaking_Autoantigen_Neoantigen_Stealth"],
            "tier": "Tier_3_Human_Cells_AbioticStress_or_ImmunodeficientMouse",
            "ceg_tier": "T5_Rodent_or_CellLine",
            "ceg_model": "Yeast two-hybrid truncation/alanine-scanning mutagenesis of human Fc gamma RI cytoplasmic tail and immune-cell 4.1G transcript profiling",
            "ceg_immune": "Human CD64 (FCGR1A) cytosolic-tail cytoskeletal docking via EPB41L2 (4.1G)",
            "ceg_donor_source": "Human FCGR1A cytosolic-tail yeast two-hybrid mutants and immune-cell transcript panels (exact n not reported in abstract)",
            "ceg_follow_up": "In vitro yeast two-hybrid binding and immune-cell transcript enrichment assays",
            "ceg_target": "Gate 3 / Locus 2 Design A Design B complement CD64t IgG shield and saturability",
            "ceg_topics": ["EFF:Humoral_DSA_FcR_ADCC_Complement_CDC"],
            "arms": [
                make_arm("pmid18023480_arm1_fcgr1a_cy_mutants", "Human Fc gamma RI cytosolic-tail truncated and alanine-substituted mutants in yeast two-hybrid",
                         cohort_id="pmid18023480_cohort1", is_reference_control=False, sample_size_n=None, sample_size_unit="in_vitro_monoculture_replicates",
                         cell_source_class="NonIslet_Immune_Endothelial_or_Hematopoietic_Model", site="InVitro_Only", sys_is="None (yeast two-hybrid)"),
                make_arm("pmid18023480_arm2_fcgr1a_wt_cy_ctrl", "Wild-type human Fc gamma RI cytosolic tail reference construct in yeast two-hybrid",
                         cohort_id="pmid18023480_cohort1", is_reference_control=True, sample_size_n=None, sample_size_unit="in_vitro_monoculture_replicates",
                         cell_source_class="NonIslet_Immune_Endothelial_or_Hematopoietic_Model", site="InVitro_Only", sys_is="None (yeast two-hybrid)"),
            ],
            "effects": [
                {
                    "effect_id": "pmid18023480_eff1_hxxbxxxbb_motif",
                    "focal_arm_id": "pmid18023480_arm1_fcgr1a_cy_mutants", "comparator_arm_id": "pmid18023480_arm2_fcgr1a_wt_cy_ctrl",
                    "cohort_id": "pmid18023480_cohort1", "focal_factor_X": "Fc gamma RI cytosolic-tail truncation and alanine substitutions",
                    "comparator_X0": "Wild-type Fc gamma RI cytosolic tail Protein 4.1G binding",
                    "comparator_label": "Wild-type human Fc gamma RI cytosolic tail reference construct in yeast two-hybrid",
                    "outcome_variable_Y": "Mapping of Protein 4.1G docking site to membrane-proximal Fc gamma RI cytosolic core motif HxxBxxxBB",
                    "outcome_domain": "Surface_HLA_or_Transgene_Expression_Level", "effect_direction": "Descriptive_or_Unoriented",
                    "quote": "membrane-proximal core motif of HxxBxxxBB",
                    "measurement_unit": "qualitative_statement", "statistic_type": "qualitative_statement_only",
                    "contrast_type": "between_arm_comparative_descriptive",
                    "polarity_class": "Qualitative_or_Unoriented_Endpoint", "orientation_sign": 0, "matched_lexicon_term": "none_or_mixed",
                    "n_unit": "in_vitro_monoculture_replicates", "cell_source": "NonIslet_Immune_Endothelial_or_Hematopoietic_Model", "site": "InVitro_Only",
                    "tier": "Tier_3_Human_Cells_AbioticStress_or_ImmunodeficientMouse", "population_or_model": "Yeast two-hybrid Fc gamma RI cytosolic mutagenesis",
                },
                {
                    "effect_id": "pmid18023480_eff2_spliced_4p1g_enrichment",
                    "focal_arm_id": "pmid18023480_arm2_fcgr1a_wt_cy_ctrl", "comparator_arm_id": None,
                    "cohort_id": "pmid18023480_cohort1", "focal_factor_X": "Alternatively spliced Protein 4.1G isoform in immune cells",
                    "comparator_X0": "Canonical 4.1G yeast two-hybrid binding baseline", "comparator_label": None,
                    "outcome_variable_Y": "Increased Fc gamma RI binding and immune-cell transcript enrichment of alternatively spliced 4.1G",
                    "outcome_domain": "Surface_HLA_or_Transgene_Expression_Level", "effect_direction": "Descriptive_or_Unoriented",
                    "quote": "4.1G product to be associated with increased Fc gamma RI binding",
                    "measurement_unit": "qualitative_statement", "statistic_type": "single_arm_descriptive_only",
                    "contrast_type": "single_arm_descriptive_only",
                    "polarity_class": "Qualitative_or_Unoriented_Endpoint", "orientation_sign": 0, "matched_lexicon_term": "none_or_mixed",
                    "n_unit": "in_vitro_monoculture_replicates", "cell_source": "NonIslet_Immune_Endothelial_or_Hematopoietic_Model", "site": "InVitro_Only",
                    "tier": "Tier_3_Human_Cells_AbioticStress_or_ImmunodeficientMouse", "population_or_model": "Yeast two-hybrid & immune-cell transcript profiling",
                },
            ],
            "ceg_arms": [
                {"arm_id": "A1_fcgr1a_cy_mutants", "label": "Fc gamma RI cytosolic-tail truncation and alanine-substitution mutants", "edits": ["FCGR1A_CY_Truncation_AlanineScan"], "n": "Yeast two-hybrid mutant panel (n not reported in abstract)", "iso": "Direct paired transgene comparison"},
                {"arm_id": "A2_fcgr1a_wt_cy_ctrl", "label": "Wild-type human Fc gamma RI cytosolic tail construct", "edits": [], "n": "Yeast two-hybrid reference & immune-cell transcripts", "iso": "Baseline comparator"},
            ],
            "ceg_outcomes": [
                {"oid": "O1", "endpoint": "Protein 4.1G docking motif within Fc gamma RI cytoplasmic tail", "comp": "A1_fcgr1a_cy_mutants vs A2_fcgr1a_wt_cy_ctrl", "dir": "descriptive_or_neutral", "stat": "qualitative_no_pvalue", "tier": "T5_Rodent_or_CellLine", "ival": "Membrane-proximal cytosolic HxxBxxxBB core + downstream hydrophobic/acidic residues", "summary": "Truncation and alanine scanning localized Protein 4.1G interaction to a membrane-proximal Fc gamma RI cytosolic core motif (HxxBxxxBB) followed by hydrophobic and acidic residues.", "quote_eff": "pmid18023480_eff1_hxxbxxxbb_motif"},
                {"oid": "O2", "endpoint": "Alternatively spliced 4.1G isoform binding and immune-cell transcript enrichment", "comp": "A2_fcgr1a_wt_cy_ctrl (isoform binding)", "dir": "descriptive_or_neutral", "stat": "qualitative_no_pvalue", "tier": "T5_Rodent_or_CellLine", "ival": "Elevated CD64 Y2H binding & selective immune-cell enrichment", "summary": "A splice isoform of EPB41L2 showed stronger CD64 cytosolic-tail binding in Y2H screens and selective immune-cell transcript enrichment.", "quote_eff": "pmid18023480_eff2_spliced_4p1g_enrichment"},
            ],
            "ceg_relation": "scoping_qualification", "ceg_applicability": "justified_bridge",
            "ceg_edge_claim": "Protein 4.1G binds the membrane-proximal HxxBxxxBB cytosolic motif immediately downstream of the FCGR1A transmembrane domain (deleted in tailless CD64t[1-313] where Arg314-Tyr374 is excised).",
        },
    ]

    dossiers: dict[str, dict[str, Any]] = {}
    dshas: dict[str, str] = {}
    ring1_records: list[dict[str, Any]] = []
    ceg_new_studies: dict[str, Any] = {}
    ceg_new_arms: dict[str, Any] = {}
    ceg_new_outcomes: dict[str, Any] = {}
    ceg_new_edges: list[dict[str, Any]] = []

    for sp in study_specs:
        pmid = sp["pmid"]
        rp = live_pm[pmid]
        ft_sec = sp.get("ft_sections")
        dos: dict[str, Any] = {
            "pmid": pmid,
            "pmcid": rp.get("pmcid"),
            "doi": rp.get("doi"),
            "pub_year": rp.get("pub_year"),
            "journal": rp.get("journal") or "",
            "first_author": rp.get("first_author"),
            "senior_author": rp.get("senior_author"),
            "title": rp.get("title") or "",
            "abstract": rp.get("abstract") or "",
            "publication_types": rp.get("publication_types") or ["Journal Article"],
            "mesh_terms": [], "keywords": [],
            "matched_pillars": sp["pillars"],
            "linked_geo_datasets": [],
            "has_parsed_fulltext_xml": bool(ft_sec),
            "fulltext_data_sections": ft_sec,
        }
        if sp.get("oa_lic"):
            dos["license"] = sp["oa_lic"]
        raw_b = json.dumps(dos, sort_keys=True, ensure_ascii=False).encode("utf-8")
        (DOSSIERS_DIR / f"{pmid}.json").write_bytes(raw_b)
        dossiers[pmid] = dos
        dshas[pmid] = sha256_bytes(raw_b)

        eff_objs: list[dict[str, Any]] = []
        eff_by_id: dict[str, dict[str, Any]] = {}
        for ef in sp["effects"]:
            eo = make_effect(
                pmid=pmid,
                effect_id=ef["effect_id"],
                dossier=dos,
                dos_sha=dshas[pmid],
                focal_arm_id=ef["focal_arm_id"],
                comparator_arm_id=ef["comparator_arm_id"],
                cohort_id=ef["cohort_id"],
                focal_factor_X=ef["focal_factor_X"],
                comparator_X0=ef["comparator_X0"],
                comparator_label=ef["comparator_label"],
                outcome_variable_Y=ef["outcome_variable_Y"],
                outcome_domain=ef["outcome_domain"],
                effect_direction=ef["effect_direction"],
                quote_substring=ef["quote"],
                stage=ef.get("stage"),
                cell_source=ef["cell_source"],
                site=ef["site"],
                tier=ef["tier"],
                treatment_mean=ef.get("treatment_mean"),
                control_mean=ef.get("control_mean"),
                point_estimate=ef.get("point_estimate"),
                effect_notes=ef.get("effect_notes"),
                treatment_n=ef.get("treatment_n"),
                control_n=ef.get("control_n"),
                measurement_unit=ef.get("measurement_unit", "qualitative_statement"),
                statistic_type=ef.get("statistic_type", "qualitative_statement_only"),
                contrast_type=ef.get("contrast_type", "qualitative_statement_only"),
                polarity_class=ef.get("polarity_class", "Qualitative_or_Unoriented_Endpoint"),
                orientation_sign=int(ef.get("orientation_sign", 0)),
                matched_lexicon_term=ef.get("matched_lexicon_term", "none_or_mixed"),
                n_unit=ef.get("n_unit", "unspecified_in_source"),
                censoring_note=ef.get("censoring_note", "Not_Time_To_Event_Endpoint"),
                timepoint=ef.get("timepoint"),
                population_or_model=ef.get("population_or_model"),
                penalty_flag=bool(ef.get("penalty_flag", False)),
            )
            eff_objs.append(eo)
            eff_by_id[ef["effect_id"]] = eo

        doc = {
            "schema_version": "0.2.0",
            "study_metadata": {
                "pmid": pmid, "pmcid": dos.get("pmcid"), "doi": dos.get("doi"), "nct_id": None,
                "geo_accessions": [], "title": dos["title"], "first_author": dos.get("first_author"),
                "senior_author": dos.get("senior_author"), "pub_year": dos["pub_year"], "journal": dos["journal"],
                "source_text_type": "FullText_XML_or_PDF" if ft_sec else "Abstract_Only",
                "pillars_covered": sp["pillars"], "max_biological_fidelity_tier": sp["tier"],
            },
            "screening_decision": {"included": True, "is_crispr_or_high_throughput_screen": False, "screen_library_size_genes": None, "exclusion_reason": None},
            "arms": sp["arms"],
            "atomic_effects": eff_objs,
            "effect_modifier_interactions": [],
            "causal_mechanism_edges": [],
            "cross_study_discovery_bridges": {
                "collateral_and_pleiotropic_findings": [], "residual_failure_and_escape_vectors": [],
                "regime_thresholds": [], "high_throughput_screen_hits": [],
            },
        }
        ring1_records.append(doc)

        qid = sp["ceg_qid"]
        eid = f"{qid}:L1"
        vids = []
        for ca in sp["ceg_arms"]:
            vid = f"VAR:{qid}:{ca['arm_id']}"
            vids.append(vid)
            ceg_new_arms[vid] = {
                "variable_id": vid, "queue_id": qid, "context_id": f"CTX:{qid}", "arm_id": ca["arm_id"],
                "label": ca["label"], "edits_or_interventions": ca["edits"],
                "n_donors_or_animals": ca["n"], "causal_isolation": ca["iso"],
            }
        cited_oids = []
        cited_otuples = []
        for co in sp["ceg_outcomes"]:
            oid_short = co["oid"]
            oid = f"{qid}:{oid_short}"
            cited_oids.append(oid_short)
            cited_otuples.append(oid)
            ref_eff = eff_by_id[co["quote_eff"]]
            src_type = "abstract" if ref_eff["source_span"].startswith("abstract") else ("figure_legend" if "figure_legends" in ref_eff["source_span"] else "results_text")
            ceg_new_outcomes[oid] = {
                "outcome_node_id": oid, "queue_id": qid, "outcome_id": oid_short,
                "endpoint_name": co["endpoint"], "comparison_arms": co["comp"],
                "direction": co["dir"], "stat_type": co["stat"],
                "quantitative_summary": co["summary"], "manuscript_tier": co["tier"],
                "intervention_value": co["ival"],
                "source_pin": {"source_type": src_type, "pmid": pmid, "span": ref_eff["source_span"]},
                "quote_sha256": sha256_str(ref_eff["verbatim_evidence_quote"]),
                "cited_by_edge_ids": [eid],
            }
        st_obj: dict[str, Any] = {
            "context_id": f"CTX:{qid}", "queue_id": qid, "id_type": "PMID", "id_value": pmid,
            "pmid": pmid, "pmcid": dos.get("pmcid"), "citation_short": sp["citation_short"],
            "fidelity_tier": sp["ceg_tier"], "biological_model": sp["ceg_model"],
            "immune_context": sp["ceg_immune"], "donor_or_cell_source": sp["ceg_donor_source"],
            "follow_up": sp["ceg_follow_up"], "variable_arm_ids": vids,
            "blueprint_targets": [sp["ceg_target"]], "outcomes_count": len(cited_oids), "links_count": 1,
            "candidate_effector_topics": sp["ceg_topics"],
        }
        st_obj["record_class"] = bceg.classify_ceg_study_record(st_obj)
        if not (st_obj["record_class"] == "empirical_primary_study"):
            raise ValueError(f"Unexpected record_class on {qid}: {st_obj['record_class']}")
        ceg_new_studies[qid] = st_obj
        ceg_new_edges.append({
            "edge_id": eid, "queue_id": qid, "link_index": 0,
            "target_gate_or_module": sp["ceg_target"], "relation": sp["ceg_relation"],
            "applicability": sp["ceg_applicability"], "incorporation": "not_yet_accounted_for",
            "readiness": "semantically_verified", "primary_certification_eligible": False,
            "cited_outcome_ids": cited_oids, "cited_outcome_tuples": cited_otuples,
            "claim_summary": sp["ceg_edge_claim"], "candidate_effector_topics": sp["ceg_topics"],
        })

    # --- RUN ALL LIVE OPENISLET PRODUCTION VALIDATOR GATES ---
    gates: dict[str, Any] = {}
    spec_by_pm = {s["pmid"]: s for s in study_specs}

    # G1: jsonschema Draft202012Validator (raw records checked here; public records checked below in G1b/G2b)
    schema_v02 = json.loads((OPENISLET_ROOT / "schemas/extraction_schema_v0.2.json").read_text(encoding="utf-8"))
    v02 = jsonschema.Draft202012Validator(schema_v02)
    g1_errs = [f"{r['study_metadata']['pmid']}: {list(e.path)} -> {e.message}" for r in ring1_records for e in v02.iter_errors(r)]
    gates["G1_schema_v02_Draft202012"] = {"records_tested": len(ring1_records), "errors": g1_errs, "passed": len(g1_errs) == 0}

    # G2: Live extract_ring1_corpus.validate_study_semantics on source-bound raw records
    orig_dir = erc.DOSSIER_DIR
    g2_errs, g2_rows = [], []
    try:
        erc.DOSSIER_DIR = DOSSIERS_DIR
        for rec in ring1_records:
            pm_id = rec["study_metadata"]["pmid"]
            try:
                erc.validate_study_semantics(rec, dossiers[pm_id])
                for ae in rec["atomic_effects"]:
                    if not (type(ae["endpoint_polarity_registry"]["orientation_sign"]) is int):
                        raise ValueError('Verification check failed: type(ae["endpoint_polarity_registry"]["orientation_sign"]) is int')
                g2_rows.append({"pmid": pm_id, "status": "PASS", "arms": len(rec["arms"]), "effects": len(rec["atomic_effects"])})
            except Exception as exc:
                g2_errs.append(f"{pm_id}: {exc}")
                g2_rows.append({"pmid": pm_id, "status": "FAIL", "error": str(exc)})
    finally:
        erc.DOSSIER_DIR = orig_dir
    gates["G2_live_validate_study_semantics_raw_source_bound"] = {
        "records_passed": sum(1 for r in g2_rows if r["status"] == "PASS"),
        "records_tested": len(ring1_records),
        "total_arms": sum(len(r["arms"]) for r in ring1_records),
        "total_atomic_effects": sum(len(r["atomic_effects"]) for r in ring1_records),
        "per_study": g2_rows,
        "errors": g2_errs, "passed": len(g2_errs) == 0,
    }

    # G3: public_excerpt_policy bounded metadata & redaction tokens
    g3_errs, g3_tokens = [], {}
    for rec in ring1_records:
        sm = rec["study_metadata"]
        pm_id = sm["pmid"]
        cs = spec_by_pm[pm_id]["citation_short"]
        if not pep.is_bounded_metadata(pm_id, "pmid"):
            g3_errs.append(f"{pm_id}: invalid pmid")
        if sm["doi"] and not pep.is_bounded_metadata(sm["doi"], "doi"):
            g3_errs.append(f"{pm_id}: invalid doi")
        if not pep.is_bounded_metadata(cs, "citation_short", bibliographic=True):
            g3_errs.append(f"{pm_id}: invalid citation_short {cs}")
        for ae in rec["atomic_effects"]:
            pfx = "[REDACTED_CONSERVATIVE_EXCERPT:" if live_pm[pm_id].get("epmc_oa_license") == "cc by-nc-nd" else "[REDACTED_NON_OA_EXCERPT:"
            tok = f"{pfx} see PMID:{pm_id} field=verbatim_evidence_quote quote_sha256={sha256_str(ae['verbatim_evidence_quote'])}]"
            if not pep.validate_token(tok, expected_pmid=pm_id, source_quote=ae["verbatim_evidence_quote"], expected_field="verbatim_evidence_quote"):
                g3_errs.append(f"{pm_id}: invalid PEP token")
            g3_tokens[ae["effect_id"]] = tok
    gates["G3_public_excerpt_policy"] = {"errors": g3_errs, "redacted_non_oa_count": sum(1 for s in study_specs if not s["oa_pub_allowed"]), "passed": len(g3_errs) == 0}

    # G4: <= 240c aggregate verbatim chars across ALL fields (both raw AND public-exported!) + explicit public-record validation
    g4_errs, g4_detail = [], {}
    public_ring1_records = []
    for rec in ring1_records:
        pm_id = rec["study_metadata"]["pmid"]
        dos = dossiers[pm_id]
        src_parts = [dos.get("title") or "", dos.get("abstract") or ""]
        if dos.get("fulltext_data_sections"):
            src_parts.extend(dos["fulltext_data_sections"].get("results_paragraphs") or [])
            src_parts.extend(fg.get("caption") or "" for fg in (dos["fulltext_data_sections"].get("figure_legends") or []))
        src_blob = "\n".join(src_parts)
        raw_sh = compute_aggregate_verbatim_chars(rec, src_blob)
        pub_rec = copy.deepcopy(rec)
        for ae in pub_rec["atomic_effects"]:
            if not spec_by_pm[pm_id]["oa_pub_allowed"]:
                ae["verbatim_evidence_quote"] = g3_tokens[ae["effect_id"]]
        public_ring1_records.append(pub_rec)
        pub_sh = compute_aggregate_verbatim_chars(pub_rec, src_blob)
        grm_pub_chars = int(grm._max_verbatim_shingle_chars(pub_rec, src_blob, shingle_words=6))
        g4_detail[pm_id] = {
            "oa_public_quote_allowed": spec_by_pm[pm_id]["oa_pub_allowed"],
            "oa_license": spec_by_pm[pm_id]["oa_lic"],
            "effects_count": len(rec["atomic_effects"]),
            "raw_aggregate_verbatim_chars_all_fields": raw_sh["aggregate_verbatim_chars_ge25"],
            "public_aggregate_verbatim_chars_all_fields": pub_sh["aggregate_verbatim_chars_ge25"],
            "grm_public_shingle_chars": grm_pub_chars,
        }
        if raw_sh["aggregate_verbatim_chars_ge25"] > 240:
            g4_errs.append(f"{pm_id}: RAW aggregate {raw_sh['aggregate_verbatim_chars_ge25']}c > 240c")
        if pub_sh["aggregate_verbatim_chars_ge25"] > 240 or grm_pub_chars > 240:
            g4_errs.append(f"{pm_id}: PUBLIC aggregate {pub_sh['aggregate_verbatim_chars_ge25']}c / grm {grm_pub_chars}c > 240c")
    gates["G4_shingle_le_240c_raw_and_public_all_fields"] = {
        "max_raw_aggregate_chars": max(v["raw_aggregate_verbatim_chars_all_fields"] for v in g4_detail.values()),
        "max_public_grm_chars": max(v["grm_public_shingle_chars"] for v in g4_detail.values()),
        "per_study": g4_detail, "errors": g4_errs, "passed": len(g4_errs) == 0,
    }

    # G2b: Explicit optimize-safe public Ring-1 validation without requiring unredacted restricted quotes in public files
    g2b_errs = []
    g2b_schema_errs = [f"{r['study_metadata']['pmid']}: {list(e.path)} -> {e.message}" for r in public_ring1_records for e in v02.iter_errors(r)]
    g2b_errs.extend(g2b_schema_errs)
    rehydrated_ok = 0
    redacted_tokens_verified = 0
    literal_ccby_verified = 0
    try:
        erc.DOSSIER_DIR = DOSSIERS_DIR
        for pub_rec in public_ring1_records:
            pm_id = pub_rec["study_metadata"]["pmid"]
            dos = dossiers[pm_id]
            if spec_by_pm[pm_id]["oa_pub_allowed"]:
                erc.validate_study_semantics(pub_rec, dos)
                literal_ccby_verified += len(pub_rec["atomic_effects"])
                rehydrated_ok += 1
            else:
                rehy = copy.deepcopy(pub_rec)
                for ae in rehy["atomic_effects"]:
                    tok = ae["verbatim_evidence_quote"]
                    if not pep.is_redaction_token_prefix(tok):
                        raise ValueError(f"{pm_id}: non-OA quote not redacted!")
                    # Rehydrate directly from source_span on the private dossier and verify digest matches public token (optimize-safe!)
                    m_sp = re.match(r"^(abstract|title)\[(\d+):(\d+)\]\|norm=exact$", ae["source_span"])
                    if m_sp is None:
                        raise ValueError(f"{pm_id}: unexpected span {ae['source_span']}")
                    field_nm, s0, e0 = m_sp.group(1), int(m_sp.group(2)), int(m_sp.group(3))
                    orig_q = (dos.get(field_nm) or "")[s0:e0]
                    if not pep.validate_token(tok, expected_pmid=pm_id, source_quote=orig_q, expected_field="verbatim_evidence_quote"):
                        raise ValueError(f"{pm_id}: redaction token digest/metadata validation FAILED on {ae['effect_id']}")
                    ae["verbatim_evidence_quote"] = orig_q
                    redacted_tokens_verified += 1
                erc.validate_study_semantics(rehy, dos)
                rehydrated_ok += 1
    except Exception as exc:
        g2b_errs.append(str(exc))
    finally:
        erc.DOSSIER_DIR = orig_dir
    gates["G2b_public_ring1_schema_redaction_and_rehydration"] = {
        "public_schema_records_passed": len(public_ring1_records) - len(g2b_schema_errs),
        "cc_by_literal_effects_verified_directly": literal_ccby_verified,
        "non_oa_redacted_tokens_verified_and_rehydrated": redacted_tokens_verified,
        "rehydrated_semantic_records_passed": rehydrated_ok,
        "optimize_safe_no_assert": True,
        "errors": g2b_errs, "passed": len(g2b_errs) == 0,
    }

    # G5: CEG _SourceGuard (with explicit per-record queue_id binding — no array-path qid loss!) + production record_class + canonical 20 effectors + FKs + enums
    live_ceg = json.loads((OPENISLET_ROOT / "data/extracted/context_evidence_graph_v1.json").read_text(encoding="utf-8"))
    valid_effs = set(live_ceg["effectors"].keys())
    if len(valid_effs) != 20:
        raise ValueError(f"Expected 20 live CEG effectors, got {len(valid_effs)}")
    valid_rels = {"contradicts", "noninformative", "novel_upgrade_hypothesis", "scoping_qualification", "supports"}
    valid_apps = {"domain_mismatch", "justified_bridge", "matched_domain", "unvalidated_transfer"}
    valid_dirs = {"context_dependent_or_mixed", "descriptive_or_neutral", "favorable_to_intervention", "null_or_no_difference", "unfavorable_or_toxic", "unknown_or_unresolvable"}

    g5_errs = []
    for oid, oc in ceg_new_outcomes.items():
        if not isinstance(oc.get("source_pin"), dict) or not str(oc["source_pin"].get("source_type") or "").strip():
            g5_errs.append(f"Invalid source_pin on {oid}")
        if oc["direction"] not in valid_dirs:
            g5_errs.append(f"Invalid direction on {oid}: {oc['direction']}")
        if "verbatim_quote" in oc and oc["verbatim_quote"] is not None:
            g5_errs.append(f"Raw verbatim_quote retained on {oid}")
        if not re.fullmatch(r"[0-9a-f]{64}", str(oc.get("quote_sha256") or "")):
            g5_errs.append(f"Malformed quote_sha256 on {oid}")
    for qid, st in ceg_new_studies.items():
        expected_rc = bceg.classify_ceg_study_record(st)
        if st.get("record_class") != expected_rc:
            g5_errs.append(f"Study {qid} record_class={st.get('record_class')!r} != expected {expected_rc!r}")
        if "see primary" in str(st.get("follow_up", "")).lower():
            g5_errs.append(f"Placeholder follow_up on {qid}")
        actual_oc = sum(1 for o in ceg_new_outcomes.values() if o.get("queue_id") == qid)
        if st.get("outcomes_count") != actual_oc:
            g5_errs.append(f"Study {qid} outcomes_count={st.get('outcomes_count')} != actual {actual_oc}")
        actual_ed = sum(1 for e in ceg_new_edges if e.get("queue_id") == qid)
        if st.get("links_count") != actual_ed:
            g5_errs.append(f"Study {qid} links_count={st.get('links_count')} != actual {actual_ed}")
        for vid in st["variable_arm_ids"]:
            if vid not in ceg_new_arms or ceg_new_arms[vid].get("queue_id") != qid:
                g5_errs.append(f"Missing/mismatched arm FK {vid} on {qid}")
            elif "see primary" in str(ceg_new_arms[vid].get("n_donors_or_animals", "")).lower():
                g5_errs.append(f"Placeholder n_donors_or_animals on {vid}")
        for eff_id in st["candidate_effector_topics"]:
            if eff_id not in valid_effs:
                g5_errs.append(f"Invalid effector {eff_id} on {qid}")
    for ed in ceg_new_edges:
        if type(ed.get("primary_certification_eligible")) is not bool:
            g5_errs.append(f"Non-bool primary_certification_eligible on {ed['edge_id']}")
        if ed["relation"] not in valid_rels:
            g5_errs.append(f"Invalid relation {ed['relation']} on {ed['edge_id']}")
        if ed["applicability"] not in valid_apps:
            g5_errs.append(f"Invalid applicability {ed['applicability']} on {ed['edge_id']}")
        for eff_id in ed["candidate_effector_topics"]:
            if eff_id not in valid_effs:
                g5_errs.append(f"Invalid effector {eff_id} on {ed['edge_id']}")
        resolved_loc = {f"{ed['queue_id']}:{x}" for x in ed["cited_outcome_ids"]}
        if resolved_loc != set(ed["cited_outcome_tuples"]):
            g5_errs.append(f"cited_outcome_ids/tuples mismatch on {ed['edge_id']}")
        for ot in ed["cited_outcome_tuples"]:
            if ot not in ceg_new_outcomes or ed["edge_id"] not in ceg_new_outcomes[ot]["cited_by_edge_ids"]:
                g5_errs.append(f"Broken outcome FK {ot}")

    study_shingles: dict[str, set[tuple[str, ...]]] = {}
    dossier_texts: list[str] = []
    for dp in sorted((OPENISLET_ROOT / "data/dossiers").glob("*.json")):
        try:
            d0 = json.loads(dp.read_text(encoding="utf-8"))
            txt0 = " ".join(x for x in [d0.get("title"), d0.get("abstract")] if x)
            if txt0:
                dossier_texts.append(txt0)
        except Exception:
            pass
    for sp in study_specs:
        pm_id = sp["pmid"]
        dos = dossiers[pm_id]
        parts = [dos.get("title") or "", dos.get("abstract") or ""]
        if dos.get("fulltext_data_sections"):
            parts.extend(dos["fulltext_data_sections"].get("results_paragraphs") or [])
            parts.extend(fg.get("caption") or "" for fg in (dos["fulltext_data_sections"].get("figure_legends") or []))
        blob = " ".join(parts)
        dossier_texts.append(blob)
        ws = bceg._words(blob)
        sh = {tuple(ws[i : i + 6]) for i in range(max(0, len(ws) - 5))}
        study_shingles[sp["ceg_qid"]] = sh
        study_shingles[f"PMID:{pm_id}"] = sh
    sg = bceg._SourceGuard(study_shingles, dossier_texts)
    sg_hits = []
    exempt_sg_leaves = {"span", "quote_sha256", "id_value", "pmid", "pmcid", "title", "journal", "citation_short"}
    # Explicitly bind every study, arm, outcome, and edge to its declared queue_id (zero array-path qid loss!)
    sg_items: list[tuple[str, str, Any]] = []
    for qid, st in ceg_new_studies.items():
        sg_items.append((f"studies.{qid}", qid, st))
    for vid, arm in ceg_new_arms.items():
        sg_items.append((f"arms.{vid}", str(arm.get("queue_id") or ""), arm))
    for oid, oc in ceg_new_outcomes.items():
        sg_items.append((f"outcomes.{oid}", str(oc.get("queue_id") or ""), oc))
    for i_ed, ed in enumerate(ceg_new_edges):
        sg_items.append((f"edges[{i_ed}]({ed['edge_id']})", str(ed.get("queue_id") or ""), ed))
    for prefix, owner_qid, obj in sg_items:
        for fpath, val in walk_strings(obj, prefix):
            leaf = fpath.split(".")[-1].split("[")[0]
            if leaf in exempt_sg_leaves:
                continue
            if len(val) >= 20 and sg.overlaps(owner_qid, val):
                sg_hits.append(f"{fpath} ({owner_qid}): {val[:90]!r}")
    g5_errs.extend(sg_hits)
    gates["G5_ceg_sourceguard_record_class_effectors_and_fks"] = {
        "dossiers_in_sourceguard": len(dossier_texts),
        "new_studies": len(ceg_new_studies), "new_arms": len(ceg_new_arms),
        "new_outcomes": len(ceg_new_outcomes), "new_edges": len(ceg_new_edges),
        "record_class_all_match_production_classifier": True,
        "all_effectors_within_20_live_topics": True,
        "explicit_edge_qid_sourceguard_binding": True,
        "sourceguard_hits": sg_hits, "errors": g5_errs, "passed": len(g5_errs) == 0,
    }

    # G6: Zero collisions against live 604 Ring-1 / 1,182 CEG / Stage-1 settled 3,922 ledger
    live_r1 = {p.stem for p in (OPENISLET_ROOT / "data/extracted").glob("*.json") if p.stem.isdigit()}
    live_ceg_sids = set(live_ceg["studies"].keys())
    live_ceg_pms = {str(v.get("pmid") or v.get("id_value")): k for k, v in live_ceg["studies"].items() if (v.get("pmid") or v.get("id_value"))}
    ledger = json.loads(LEDGER_PATH.read_text(encoding="utf-8"))
    ledger_by_pm = {str(r.get("id_value")): r.get("queue_id") for r in ledger["settled_candidates_3359"] if r.get("id_type") == "PMID"}
    ledger_by_qid = {r["queue_id"]: str(r["id_value"]) for r in ledger["settled_candidates_3359"]}
    g6_errs = []
    ledger_verify = {}
    for rec in ring1_records:
        pm_id = rec["study_metadata"]["pmid"]
        if pm_id in live_r1:
            g6_errs.append(f"Live Ring-1 collision: {pm_id}")
    for qid, st in ceg_new_studies.items():
        pm_id = st["pmid"]
        if qid in live_ceg_sids or pm_id in live_ceg_pms:
            g6_errs.append(f"Live CEG collision: {qid} / PMID:{pm_id}")
        exp_q = ledger_by_pm.get(pm_id)
        if exp_q is not None and exp_q != qid:
            g6_errs.append(f"Stage-1 ledger mismatch for PMID:{pm_id}: {qid} vs {exp_q}")
        if qid in ledger_by_qid and ledger_by_qid[qid] != pm_id:
            g6_errs.append(f"Stage-1 reverse collision for {qid}: {pm_id} vs {ledger_by_qid[qid]}")
        ledger_verify[qid] = {"pmid": pm_id, "stage1_ledger_qid": exp_q, "exact_match": (exp_q == qid if exp_q else None)}
    gates["G6_zero_collisions_live604_ceg1182_ledger"] = {
        "live_ring1_count": len(live_r1),
        "post_exp028_ring1_count": len(live_r1) + len(ring1_records),
        "live_ceg_studies_count": len(live_ceg_sids),
        "post_exp028_ceg_studies_count": len(live_ceg_sids) + len(ceg_new_studies),
        "stage1_ledger_canonical_check": ledger_verify,
        "errors": g6_errs, "passed": len(g6_errs) == 0,
    }

    # G7: Full Layer-1 rank_islet1_stacks.py replay (604 live + 8 net-new = 612) -> 0/2,160 unintended mutations!
    inp = rank_mod.load_inputs()
    studies_live = list(inp[1])
    omics = inp[2]
    prof_live = rank_mod.build_target_evidence_profiles(studies_live, omics)
    combos_live = rank_mod.run_combinatorial_multi_gate_search(prof_live)
    prof_new = rank_mod.build_target_evidence_profiles(copy.deepcopy(studies_live) + copy.deepcopy(ring1_records), omics)
    combos_new = rank_mod.run_combinatorial_multi_gate_search(prof_new)
    mut_cnt = sum(
        1 for a, c in zip(combos_live, combos_new)
        if a["combination_id"] != c["combination_id"]
        or abs(a["composite_series_system_utility"] - c["composite_series_system_utility"]) > 1e-12
    )
    gates["G7_layer1_rank_islet1_stacks_612_replay"] = {
        "studies_live": len(studies_live),
        "studies_post_exp028": len(studies_live) + len(ring1_records),
        "mutated_stacks_of_2160": mut_cnt,
        "passed": mut_cnt == 0,
    }

    bundle: dict[str, Any] = {
        "bundle_id": "EXP-028_STAGE_S3R3_REMEDIATED_RING1_CEG_BUNDLE_v4",
        "generated_date": PINNED_AUDIT_DATE,
        "stacked_on_top_of": f"Live OpenIslet v0.8.0 ({len(live_r1)} Ring-1 / {len(live_ceg_sids)} CEG studies; unified Wave-5 S5 migration required for live CEG cardinality update)",
        "already_in_live_openislet_zero_duplication": [
            "40544428", "39326417", "38684699", "40757665", "42430558",
            "36593395", "41543848", "40812299", "21813778", "24222351",
        ],
        "pending_primary_pdf_verification": [
            {
                "pmid": "41765034",
                "existing_ceg_id": "M0144",
                "citation_short": "Shi 2026",
                "journal": "Lancet Diabetes Endocrinol",
                "doi": "10.1016/S2213-8587(25)00423-1",
                "reason": "Live PubMed efetch returns PublicationType=Letter with 0 abstract characters (paywalled). Investigators report a repeat infusion in the first recipient; secondary '3/3 insulin-independent' claim conflicts with 2026-02-26 CAS institutional report (1/3 insulin-independent; autologous recipient lost C-peptide post-IS withdrawal). Zero fabricated Ring-1 extraction rows.",
            }
        ],
        "parked_context_reviews": [
            {
                "pmid": "42392079",
                "pmcid": "PMC13710137",
                "citation_short": "Deuse & Schrepfer 2026",
                "journal": "Cell Rep Med",
                "license": "CC-BY-NC-ND",
                "reason": "Review article with founder COI and restrictive license; parked strictly outside empirical Ring-1/CEG while primary empirical targets (Gu 2021 PMID:34130115; Gravina 2023 PMID:36593395; Gou 2026 PMID:41543848) supply direct evidence.",
            }
        ],
        "ring1_dossiers_metadata": {
            pm_id: {
                "pmid": dos["pmid"], "pmcid": dos["pmcid"], "doi": dos["doi"],
                "pub_year": dos["pub_year"], "journal": dos["journal"],
                "oa_public_quote_allowed": spec_by_pm[pm_id]["oa_pub_allowed"],
                "oa_license": spec_by_pm[pm_id]["oa_lic"],
                "dossier_sha256": dshas[pm_id],
                "has_parsed_fulltext_xml": dos["has_parsed_fulltext_xml"],
            }
            for pm_id, dos in dossiers.items()
        },
        "ring1_extracted_net_new_public_safe": public_ring1_records,
        "ceg_new_studies": ceg_new_studies,
        "ceg_new_arms": ceg_new_arms,
        "ceg_new_outcomes": ceg_new_outcomes,
        "ceg_new_edges": ceg_new_edges,
        "live_validator_audit": {"gates": gates},
    }

    raw_str = json.dumps(bundle, indent=2, ensure_ascii=False)
    has_abs = PRIVACY_HOME_TOKEN in raw_str
    gates["G8_zero_privacy_path_leaks"] = {"abs_path_detected": has_abs, "passed": not has_abs}
    all_pass = all(g["passed"] for g in gates.values())
    bundle["live_validator_audit"] = {"overall_status": "ALL_9_LIVE_PRODUCTION_GATES_PASSED" if all_pass else "FAILED", "gates": gates}
    EVIDENCE_BUNDLE_OUT.write_text(json.dumps(bundle, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    if not all_pass:
        raise ValueError(f"Evidence bundle validation FAILED: {json.dumps(gates, indent=2)}")

    # Write explicit PDL-019 / WORKFLOW §5.6 primary-source extraction_verification_receipt.json!
    bundle_sha = sha256_file(EVIDENCE_BUNDLE_OUT)
    per_study_pdl019 = []
    rec_by_pm = {r["study_metadata"]["pmid"]: r for r in ring1_records}
    pub_by_pm = {r["study_metadata"]["pmid"]: r for r in public_ring1_records}
    for sp in study_specs:
        pm_id = sp["pmid"]
        qid = sp["ceg_qid"]
        dos = dossiers[pm_id]
        raw_rec = rec_by_pm[pm_id]
        pub_rec = pub_by_pm[pm_id]
        st_ceg = ceg_new_studies[qid]
        ceg_ocs = [o for o in ceg_new_outcomes.values() if o["queue_id"] == qid]
        eff_audit = []
        for ae_raw, ae_pub in zip(raw_rec["atomic_effects"], pub_rec["atomic_effects"]):
            eff_audit.append({
                "effect_id": ae_raw["effect_id"],
                "focal_arm_id": ae_raw["focal_arm_id"],
                "comparator_arm_id": ae_raw["comparator_arm_id"],
                "statistic_type": ae_raw["statistic_type"],
                "contrast_type": ae_raw["contrast_metadata"]["contrast_type"],
                "timepoint": ae_raw["contrast_metadata"]["timepoint"],
                "population_or_model": ae_raw["contrast_metadata"]["population_or_model"],
                "treatment_mean": ae_raw["treatment_mean"],
                "control_mean": ae_raw["control_mean"],
                "point_estimate": ae_raw["point_estimate"],
                "log_response_ratio_or_smd": ae_raw["log_response_ratio_or_smd"],
                "treatment_n": ae_raw["treatment_n"],
                "control_n": ae_raw["control_n"],
                "source_span": ae_raw["source_span"],
                "raw_quote_chars": len(ae_raw["verbatim_evidence_quote"]),
                "quote_sha256": sha256_str(ae_raw["verbatim_evidence_quote"]),
                "public_quote_redacted": pep.is_redaction_token_prefix(ae_pub["verbatim_evidence_quote"]),
                "exact_span_verified": True,
            })
        per_study_pdl019.append({
            "pmid": pm_id,
            "pmcid": dos.get("pmcid"),
            "doi": dos.get("doi"),
            "first_author": dos.get("first_author"),
            "pub_year": dos.get("pub_year"),
            "journal": dos.get("journal"),
            "title": dos.get("title"),
            "source_text_verified": "FullText_XML_and_Abstract" if dos.get("has_parsed_fulltext_xml") else "PubMed_Abstract_and_Metadata",
            "dossier_sha256": dshas[pm_id],
            "ceg_queue_id": qid,
            "ceg_record_class": st_ceg["record_class"],
            "ring1_max_biological_fidelity_tier": raw_rec["study_metadata"]["max_biological_fidelity_tier"],
            "ceg_fidelity_tier": st_ceg["fidelity_tier"],
            "species_and_model_verified": st_ceg["biological_model"],
            "immune_and_immunosuppression_context_verified": st_ceg["immune_context"],
            "arms_and_denominators_verified": [
                {
                    "arm_id": a["arm_id"],
                    "is_reference_control": a["is_reference_control"],
                    "cell_source_class": a["gate1_substrate_and_differentiation"]["cell_source_class"],
                    "sample_size_n": a["sample_size_n"],
                    "sample_size_unit": a["sample_size_unit"],
                    "transplant_site": a["gate5_engraftment_niche"]["transplant_site"],
                    "systemic_immunosuppression_regimen": a["gate5_engraftment_niche"]["systemic_immunosuppression_regimen"],
                    "followup_duration_days": a["quantitative_readouts"]["followup_duration_days"],
                }
                for a in raw_rec["arms"]
            ],
            "oa_license": sp["oa_lic"],
            "oa_public_quote_allowed": sp["oa_pub_allowed"],
            "g4_raw_aggregate_verbatim_chars": g4_detail[pm_id]["raw_aggregate_verbatim_chars_all_fields"],
            "g4_public_grm_shingle_chars": g4_detail[pm_id]["grm_public_shingle_chars"],
            "ring1_atomic_effects_verified": eff_audit,
            "ceg_outcomes_verified": [
                {
                    "outcome_node_id": o["outcome_node_id"],
                    "manuscript_tier": o["manuscript_tier"],
                    "direction": o["direction"],
                    "stat_type": o["stat_type"],
                    "comparison_arms": o["comparison_arms"],
                    "intervention_value": o["intervention_value"],
                    "source_pin": o["source_pin"],
                    "quote_sha256": o["quote_sha256"],
                }
                for o in ceg_ocs
            ],
            "pdl019_primary_source_audit_status": "VERIFIED_AGAINST_PRIMARY_SOURCE_DOSSIER",
        })

    pdl019_receipt = {
        "schema_version": "0.8.0-exp028-pdl019-s56-extraction-verification-receipt-v1",
        "investigation_id": "EXP-028",
        "candidate_id": "CAND-031",
        "target_iip": "IIP-0041",
        "verified_date": PINNED_AUDIT_DATE,
        "python_version": sys.version.split()[0],
        "bundle_file": EVIDENCE_BUNDLE_OUT.name,
        "bundle_sha256": bundle_sha,
        "overall_status": bundle["live_validator_audit"]["overall_status"],
        "counts": {
            "net_new_ring1_studies": len(ring1_records),
            "net_new_ring1_arms": sum(len(r["arms"]) for r in ring1_records),
            "net_new_ring1_atomic_effects": sum(len(r["atomic_effects"]) for r in ring1_records),
            "net_new_ceg_studies": len(ceg_new_studies),
            "net_new_ceg_arms": len(ceg_new_arms),
            "net_new_ceg_outcomes": len(ceg_new_outcomes),
            "net_new_ceg_edges": len(ceg_new_edges),
            "cc_by_4_0_live_quote_studies": sum(1 for s in study_specs if s["oa_pub_allowed"]),
            "non_oa_or_conservative_redacted_studies": sum(1 for s in study_specs if not s["oa_pub_allowed"]),
            "standalone_post_exp028_ring1_total": len(live_r1) + len(ring1_records),
            "standalone_post_exp028_ceg_total": len(live_ceg_sids) + len(ceg_new_studies),
        },
        "s5_unified_migration_note": (
            "All 8 CEG studies carry deterministic production record_class='empirical_primary_study', valid 20-key live effector topics, "
            "and primary-source-verified species/model/arm/comparator/timepoint/outcome/immunosuppression tiers. Fold-in into live OpenIslet "
            "executes as part of one unified Wave-5 Ring-1/CEG migration updating live cardinality constants and ideas/CEG-DELTA-STAGING.md."
        ),
        "gates_summary": {k: v["passed"] for k, v in gates.items()},
        "per_study_pdl019_primary_source_verification": per_study_pdl019,
    }
    pdl_raw = json.dumps(pdl019_receipt, indent=2, ensure_ascii=False)
    if PRIVACY_HOME_TOKEN in pdl_raw:
        raise ValueError("Privacy leak in extraction_verification_receipt.json!")
    EXTRACTION_RECEIPT_OUT.write_text(pdl_raw + "\n", encoding="utf-8")
    return bundle["live_validator_audit"]


def _verify_g2b_tamper_resistance_self_test() -> dict[str, Any]:
    """Optimize-safe self-test confirming valid redaction tokens pass and tampered digests fail under both -B and -O -B."""
    sample_pmid = "34130115"
    sample_quote = "99th percentile of 336 healthy controls, the ZnT8ecA positivity rate was 23.6% (74/313)"
    valid_tok = f"[REDACTED_NON_OA_EXCERPT: see PMID:{sample_pmid} field=verbatim_evidence_quote quote_sha256={sha256_str(sample_quote)}]"
    if not pep.is_redaction_token_prefix(valid_tok):
        raise ValueError("G2b self-test failed: valid token prefix rejected")
    if not pep.validate_token(valid_tok, expected_pmid=sample_pmid, source_quote=sample_quote, expected_field="verbatim_evidence_quote"):
        raise ValueError("G2b self-test failed: valid redaction token did not validate")
    tampered_tok, n_sub = re.subn(
        r"(quote_sha256=)([0-9a-f])",
        lambda m: m.group(1) + ("0" if m.group(2) != "0" else "1"),
        valid_tok,
        count=1,
    )
    if n_sub != 1:
        raise ValueError("G2b self-test failed: could not tamper token digest")
    tamper_rejected = not pep.validate_token(
        tampered_tok, expected_pmid=sample_pmid, source_quote=sample_quote, expected_field="verbatim_evidence_quote"
    )
    if not tamper_rejected:
        raise ValueError("G2b self-test failed: tampered redaction token was NOT rejected!")
    return {
        "valid_token_accepted": True,
        "tampered_digest_rejected": tamper_rejected,
        "optimize_safe_no_assert": True,
    }


def run_installed_check(output_path: pathlib.Path | None = None) -> dict[str, Any]:
    """
    Portable, read-only self-check mode suitable for running when installed at
    OpenIslet/scripts/verify_iip0041_clinical_h1_cd64t_siglec.py without external caches or network.
    - REQUIRES installed data/constructs/islet1_abx_cd64t_il1rn_modeb_v0.8.0.fasta and
      data/protocols/iip0041_abx_cd64t_il1rn_side_contract_v0.8.0.json (fail-closed if absent).
    - Emits a host-independent deterministic portable receipt payload decoupled from runtime python_version
      and local private XML cache presence so private checkouts and public snapshots verify identically.
    """
    print("=== IIP-0041 / EXP-028 INSTALLED READ-ONLY SELF-CHECK ===")
    print(f"0. Runtime: Python {sys.version.split()[0]} (optimize={sys.flags.optimize}, bytecode_disabled={sys.dont_write_bytecode})")
    part_a = analyze_clinical_h1_reanchor()

    # REQUIRE runtime-SHA-256-pinned immutable side contract and verify FASTA pin alignment
    side_contract, side_contract_sha, side_contract_pin_ok = _load_iip0041_side_contract(require_pinned_sha=True)
    if not side_contract_pin_ok or side_contract_sha != PINNED_SIDE_CONTRACT_SHA256:
        raise ValueError(f"Pinned side-contract SHA-256 check failed: {side_contract_sha} != {PINNED_SIDE_CONTRACT_SHA256}")
    sc_fasta_pin = side_contract["zero_lims_touch_implementation_compliance"]["modeb_construct_fasta_sha256"]
    if sc_fasta_pin != PINNED_FASTA_SHA:
        raise ValueError(f"Side-contract Mode-B FASTA SHA mismatch: {sc_fasta_pin} != {PINNED_FASTA_SHA}")

    # REQUIRE live IIP-0035 D1b FASTA for cross-identity verification AND REQUIRE installed Mode-B FASTA (fail-closed!)
    d1_v2_path = OPENISLET_ROOT / "data/constructs/islet1_d1b_auto_v2_v0.8.0.fasta"
    if not d1_v2_path.is_file():
        raise FileNotFoundError(f"Missing live OpenIslet construct file: {d1_v2_path}")
    d1_v2_fa = parse_fasta(d1_v2_path)
    seq_l1a = d1_v2_fa["D1AUTO_v2_L1A_CIITA_CD64T_IL1RN"]
    seq_l1b = d1_v2_fa["D1AUTO_v2_L1B_CIITA_CD64T_CD46WT_COMPARATOR"]

    modeb_fa_path = OPENISLET_ROOT / PINNED_MODEB_FASTA_REL
    if not modeb_fa_path.is_file():
        raise FileNotFoundError(f"Missing REQUIRED Mode-B construct FASTA: {modeb_fa_path}")
    fa_recs = parse_fasta(modeb_fa_path)
    fa_sha = sha256_file(modeb_fa_path)
    expected_donor_ids = {
        d["fasta_record_id"]
        for d in (
            side_contract["modeb_core_abx_ciita_exon5_suite"]["active_wave5_go_scope_donors"]
            + side_contract["modeb_core_abx_ciita_exon5_suite"]["archived_hold_comparator_donors"]
        )
    }
    if len(fa_recs) != 6 or set(fa_recs.keys()) != expected_donor_ids:
        raise ValueError(
            f"Mode-B FASTA record set mismatch in {modeb_fa_path.name}: got {sorted(fa_recs.keys())} vs expected {sorted(expected_donor_ids)}"
        )
    if fa_recs.get("ABX_L2_v2_CD64T_IL1RN") != seq_l1a:
        raise ValueError("ABX_L2_v2_CD64T_IL1RN does not match live D1AUTO_v2_L1A_CIITA_CD64T_IL1RN byte-for-byte")
    if fa_recs.get("ABX_L2_v2_CD64T_CD46WT_COMP") != seq_l1b:
        raise ValueError("ABX_L2_v2_CD64T_CD46WT_COMP does not match live D1AUTO_v2_L1B_CIITA_CD64T_CD46WT_COMPARATOR byte-for-byte")
    if fa_sha != PINNED_FASTA_SHA:
        raise ValueError(f"Mode-B FASTA SHA-256 mismatch: {fa_sha} != {PINNED_FASTA_SHA}")

    for donor_spec in (
        side_contract["modeb_core_abx_ciita_exon5_suite"]["active_wave5_go_scope_donors"]
        + side_contract["modeb_core_abx_ciita_exon5_suite"]["archived_hold_comparator_donors"]
    ):
        did = donor_spec["fasta_record_id"]
        exp_dsha = donor_spec.get("donor_sha256")
        if exp_dsha and sha256_str(fa_recs[did]) != exp_dsha:
            raise ValueError(f"Per-donor SHA-256 mismatch for {did}: {sha256_str(fa_recs[did])} != {exp_dsha}")

    fasta_check = {
        "required": True,
        "present": True,
        "verified": True,
        "filename": modeb_fa_path.name,
        "record_count": len(fa_recs),
        "sha256": fa_sha,
        "matches_live_iip0035_l1a_l1b": True,
        "matches_side_contract_donor_pins": True,
    }

    # Extract staged CD64t[1-313] CDS directly from the verified required Mode-B lead construct
    lead_seq = fa_recs["ABX_L2_v2_CD64T_IL1RN"]
    cd64t_cds = None
    for i in range(len(lead_seq) - 941):
        sub = lead_seq[i : i + 942]
        if sub.startswith("ATG") and sub.endswith("ATTTAG") and sha256_str(sub) == "0390bb1d298aa7dc4eea19909377bf6e3200091f05f28918e94d6dc148beea86":
            cd64t_cds = sub
            break
    if cd64t_cds is None:
        raise ValueError("Could not locate verified 942-bp CD64t[1-313] CDS inside required ABX_L2_v2_CD64T_IL1RN")
    # Portable mode: explicitly decoupled from local private XML cache presence!
    gravina_cmp = verify_gravina_cd64t_cds_comparison(cd64t_cds, check_private_xml_cache=False)

    gate28a_cmc_tests = _run_gate28a_and_cmc_unit_tests()
    arb_tests = _run_locus2_arbitration_unit_tests()
    part_d = analyze_part_d_portfolio_odds()
    g2b_self = _verify_g2b_tamper_resistance_self_test()

    c2b_entry = next(
        c for c in part_a["cohorts"]
        if c["cohort_id"] == "C2b_DescriptiveSensitivity_MixedT1D_AssumedCommonC2b_13of13"
    )
    summary: dict[str, Any] = {
        "mode": "INSTALLED_READ_ONLY_SELF_CHECK",
        "receipt_determinism_policy": "PORTABLE_HOST_INDEPENDENT_EXCLUDES_RUNTIME_PYTHON_VERSION_AND_PRIVATE_CACHE_STATE",
        "private_cache_attestation_included": False,
        "experiment_id": "EXP-028",
        "candidate_id": "CAND-031",
        "target_iip": "IIP-0041",
        "remediation_stage": "R13",
        "receipt_revision": "R17",
        "receipt_content_stage": "R17_CMC_RAW_RESCUE_OUTCOME_AND_FRACTION_CLOSURE",
        "verified_date": PINNED_AUDIT_DATE,
        "portable_receipt_scope_note": (
            "Portable read-only self-check performs an embedded-reference comparison against the curated 942-bp "
            "Gravina 2023 coding sequence (76300c42..., encoding UniProt P12314[1-313], published directly in "
            "Gravina et al. 2023 public Methods [PMC10188358]; independent live retrieval of that external article "
            "text lies outside the public snapshot) and verifies staged Mode-B FASTA pins, runtime-pinned side "
            "contract, executable Gate 28-A/CMC and Gate 28-B unit suites (Gate 28-C0/C1 remain prespecified "
            "research criteria outside the installed runtime evaluator), domain-guard and G2b self-tests, and "
            "locked live portfolio parity without private cache or network access; Ring-1/CEG integrity, raw RCSB "
            "mmCIF parsing, live external PMC10188358 Methods text retrieval, and full Swiss-Prot scans execute "
            "in dedicated repository and full-mode verifiers."
        ),
        "side_contract_sha256": side_contract_sha,
        "pinned_side_contract_sha256": PINNED_SIDE_CONTRACT_SHA256,
        "side_contract_pin_verified": side_contract_pin_ok,
        "live_h1_held": part_a["live_openislet_h1_held_today"],
        "live_headline_delta_pp": part_d["live_headline_delta_pp"],
        "blueprint_h1_estimand_separated": True,
        "release_only_cmc_yield_metric": "P_release_CMC",
        "p_infuse_given_released_unit": "infused_primary_course_equivalents_per_released_lot",
        "separate_cmc_readiness_metric": "H1_CMC_ATTEMPTED_LOT_READINESS = P_release_CMC * P_infuse_given_released * H1_Blueprint",
        "cmc_projected_and_measured_readiness_separated": True,
        "cmc_empirical_product_readiness_labeled_diagnostic_only": True,
        "cmc_typed_course_identity_and_set_alias_enforced": True,
        "gate_28a_single_compatible_cohort_only": part_a["gate_28a_coherent_decision_contract"]["single_compatible_cohort_transport_rule"]["promotion_restricted_to_single_compatible_cohort"],
        "gate_28a_bank_lot_clustering_enforced": True,
        "gate_28a_strict_lot_to_mcb_manifest_and_cohort_attestations_enforced": True,
        "gate_28a_independent_trusted_clinical_store_and_full_digest_enforced": True,
        "gate_28a_zero_unverified_ancestry_fallback_and_wcb_provenance_enforced": True,
        "gate_28a_absent_store_nullifies_hierarchy_and_cluster_outputs": True,
        "gate_28a_bidirectional_rescue_cmc_reconciliation_enforced": True,
        "gate_28a_exact_bidirectional_rescue_identity_and_cardinality_enforced": True,
        "gate_28a_pass0_unconditional_clinical_ancestry_reconciliation_enforced": True,
        "gate_28a_infused_cmc_explicit_wcb_attestation_required": True,
        "gate_28a_wcb_alias_conflict_and_unique_parentage_enforced": True,
        "gate_28a_alternate_manifest_aliases_canonicalized_and_validated": True,
        "gate_28a_raw_cmc_ancestry_reconciled_across_all_dispositions": True,
        "gate_28a_typed_raw_cmc_ancestry_error_propagation_enforced": True,
        "gate_28a_strict_duplicate_key_json_intake_nullifies_ancestry_outputs": True,
        "gate_28a_icc_variance_component_sum_le_1_enforced": True,
        "gate_28a_deterministic_nonresponse_reconciled_against_cmc": True,
        "gate_28a_duplicate_clinical_rescue_order_independent_and_explicit_lot_id_required": True,
        "gate_28a_three_scenario_icc_sensitivity_report_enforced": True,
        "gate_28a_early_rejection_explicit_false_flags_enforced": True,
        "gate_28a_decision_control_flags_bound_in_canonical_digest": True,
        "gate_28a_recipient_wcb_alias_canonicalized_before_hashing": True,
        "gate_28a_contradictory_duplicate_rescue_nullifies_ancestry": True,
        "gate_28a_explicit_rescue_fields_strictly_narrowed": True,
        "gate_28a_rescue_linkage_and_recipient_binding_prevalidated": True,
        "gate_28a_primary_lot_cmc_disposition_prevalidated": True,
        "gate_28a_duplicate_recipient_primary_lot_cmc_disposition_audited": True,
        "gate_28a_raw_cmc_rescue_primary_outcome_reconciled": True,
        "gate_28a_clopper_pearson_95_ci_scope": "NOMINAL_IID_UNADJUSTED_RECIPIENT_COUNTS_ONLY_NOT_CLUSTER_ADJUSTED",
        "gate_28a_cluster_adjusted_beta_probability_scope": (
            "Prespecified decision-model quantities conditional on assumed lot/bank variance-component ICCs "
            "(rho_lot, rho_bank) and cohort exchangeability rather than independent empirical calibration; "
            "attaching the 3-scenario icc_sensitivity_report documents sensitivity across prespecified ICC "
            "grids rather than independent calibration of those variance components."
        ),
        "structural_mmcif_label_asym_id_enforced": True,
        "gate_28b_head_to_head_paired_panel_and_candidate_reconciliation_enforced": True,
        "gate_28b_three_state_incumbent_adjudication_enforced": True,
        "gate_28b_context_independent_rational_mfi_boundary_enforced": True,
        "gate_28b_direct_fraction_mfi_supported": True,
        "gate_28b_mfi_exact_fraction_precision_scope": (
            "Exact fractions.Fraction cross-product comparisons operate on already-decoded Python inputs: "
            "for strict JSON-ingested payloads decoded via IEEE-754 binary64 (float64) in load_strict_json_text / "
            "load_strict_json_bytes, exactness starts at JSON-decoded float64 precision (not raw decimal text "
            "beyond 53-bit binary64 significand precision), whereas direct Python Fraction, Decimal, or int inputs retain "
            "exact rational/decimal/integer precision."
        ),
        "gate_28b_clean_display_decimal_context_trap_immune": True,
        "gate_28b_mfi_display_formatting_overflow_immune": True,
        "published_13_of_13_primary_verified": c2b_entry["primary_verified"],
        "per_study_adjudication_ledger_count": len(part_a["per_study_endpoint_adjudication_ledger"]),
        "uniform_prior_minimum_threshold_verification": part_a["uniform_prior_minimum_threshold_verification"],
        "gate_28a_and_cmc_unit_tests": gate28a_cmc_tests,
        "gravina_2023_sequence_comparison": gravina_cmp,
        "modeb_fasta_check": fasta_check,
        "locus2_arbitration_unit_tests": arb_tests,
        "domain_and_ceiling_guard_unit_tests": part_d["domain_and_ceiling_guard_unit_tests"],
        "core_3arm_h1_only_delta_S0_to_S2a_pp": part_d["attribution_decomposition_and_disclosures"]["core_3arm_h1_only_delta_S0_to_S2a_pp"],
        "core_3arm_h1_only_delta_S0_to_S2a_exact_pp": part_d["attribution_decomposition_and_disclosures"]["core_3arm_h1_only_delta_S0_to_S2a_exact_pp"],
        "five_arm_unrounded_parity_max_abs_err": part_d["live_parity_verification"]["five_arm_W_U3_W_U4_unrounded_max_abs_err"],
        "g2b_tamper_resistance_self_test": g2b_self,
        "overall_status": "INSTALLED_SELF_CHECK_PASSED",
    }
    summary["portable_payload_sha256"] = sha256_str(
        json.dumps(summary, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
    )
    raw = json.dumps(summary, indent=2, ensure_ascii=False)
    if PRIVACY_HOME_TOKEN in raw:
        raise ValueError("Privacy leak detected in installed self-check output!")
    if output_path is not None:
        out_file = output_path if output_path.suffix.lower() == ".json" else (output_path / "iip0041_installed_check_receipt.json")
        out_file.parent.mkdir(parents=True, exist_ok=True)
        out_file.write_text(raw + "\n", encoding="utf-8")
        print(f"Wrote installed self-check receipt: {out_file.name} ({out_file.stat().st_size} B, SHA-256={sha256_file(out_file)})")
    print(
        f"PASS: H1={summary['live_h1_held']}, Core H1-only={summary['core_3arm_h1_only_delta_S0_to_S2a_pp']:+.4f} pp, "
        f"Gravina={gravina_cmp['synonymous_nucleotide_differences_vs_gravina']}nt/{gravina_cmp['amino_acid_differences_vs_gravina']}aa, "
        f"G28A/CMC={gate28a_cmc_tests['total_cases']}/{gate28a_cmc_tests['total_cases']}, "
        f"Arb={arb_tests['total_cases']}/{arb_tests['total_cases']}, Domain={part_d['domain_and_ceiling_guard_unit_tests']['total_negative_tests']}/{part_d['domain_and_ceiling_guard_unit_tests']['total_negative_tests']}, "
        f"G2b-tamper-reject={g2b_self['tampered_digest_rejected']}, PinOK={side_contract_pin_ok}, PortableSHA={summary['portable_payload_sha256'][:12]} (optimize={sys.flags.optimize})"
    )
    return summary


def build_cli_parser() -> argparse.ArgumentParser:
    ap = argparse.ArgumentParser(
        description="EXP-028 / IIP-0041 Clinical H1, Mode-B CD64t+IL1RN, Siglec-7/-9, Portfolio, & Evidence Verifier",
    )
    ap.add_argument("--repo-root", type=pathlib.Path, default=None, help="Path to OpenIslet repository root (fail-closed if invalid).")
    ap.add_argument("--inv-root", type=pathlib.Path, default=None, help="Optional path to OpenIslet-Investigations root (full staged mode).")
    ap.add_argument("--output", type=pathlib.Path, default=None, help="Output directory or .json receipt file path (read-only in --installed-check unless set).")
    ap.add_argument("--installed-check", "--check", dest="installed_check", action="store_true", help="Run read-only installed self-check without external caches or network.")
    return ap


def main(argv: list[str] | None = None) -> None:
    args = build_cli_parser().parse_args(argv)
    configure_runtime_paths(repo_root=args.repo_root, inv_root=args.inv_root, output=args.output)
    if args.installed_check:
        run_installed_check(output_path=args.output)
        return

    OUT_DIR.mkdir(parents=True, exist_ok=True)
    print("=== EXP-028 / IIP-0041 REMEDIATED VERIFICATION SUITE ===")
    print(f"0. Runtime: Python {sys.version.split()[0]} (optimize={sys.flags.optimize}, bytecode_disabled={sys.dont_write_bytecode})")
    print("1. Loading pinned 20,429-protein human Swiss-Prot...")
    prots, sp_kmers, sp_sha = load_swissprot()

    print("2. Running Part A: Clinical Hurdle 1 Audit (Blueprint H1=0.88 post-release estimand; separate H1_CMC_ATTEMPTED_LOT_READINESS; single-cohort Gate 28-A)...")
    part_a = analyze_clinical_h1_reanchor()

    print("3. Running Part B: Mode-B Core A/B/X CIITA Exon 5 FASTA + Protein Gate P1-P4 + Full-vs-Component Arbitration...")
    part_b = build_and_audit_part_b(prots, sp_kmers, sp_sha)

    print("4. Running Part C: Research Comparator Siglec-7/-9 (Split 28-C0/C1) & Permanent GY-029 ST6GAL1 Rule...")
    part_c = analyze_part_c_siglec_glycoengineering(sp_kmers)

    print("5. Running Part D: Exact OQ-016 2^12 & 2^20 Portfolio Odds (Strict Zero-Tol Guards + True Unrounded Deltas)...")
    part_d = analyze_part_d_portfolio_odds()

    print(f"6. Running Part E: Live NCBI E-utilities + Europe PMC verification of {len(ALL_EXP028_PMIDS)} PMIDs...")
    live_pm = fetch_live_pubmed_and_epmc(ALL_EXP028_PMIDS)
    pmid_receipt = {
        "schema_version": "exp028_pmid_receipt_v2",
        "verified_date": PINNED_AUDIT_DATE,
        "python_version": sys.version.split()[0],
        "verification_sources": ["NCBI E-utilities esummary.fcgi", "NCBI E-utilities efetch.fcgi", "Europe PMC REST search API"],
        "total_pmids_verified": len(live_pm),
        "missing_count": 0,
        "retracted_count": sum(1 for r in live_pm.values() if r["retracted"]),
        "records": {
            pm: {k: v for k, v in rec.items() if k != "abstract"}
            for pm, rec in sorted(live_pm.items(), key=lambda x: int(x[0]))
        },
    }
    pmid_raw = json.dumps(pmid_receipt, indent=2, ensure_ascii=False)
    if PRIVACY_HOME_TOKEN in pmid_raw:
        raise ValueError("Privacy leak detected in pmid_verification_receipt.json!")
    PMID_RECEIPT_OUT.write_text(pmid_raw + "\n", encoding="utf-8")

    print("7. Running Part F: §5.6 Ring-1 + CEG Evidence Extraction, Optimize-Safe G2b, All 9/9 Live Validators, & PDL-019 Receipt...")
    ev_audit = build_and_validate_evidence_bundle(live_pm)
    g2b_self = _verify_g2b_tamper_resistance_self_test()

    receipt = {
        "experiment_id": "EXP-028",
        "candidate_id": "CAND-031",
        "target_iip": "IIP-0041",
        "bucket": "2A",
        "remediation_stage": "S3-R3",
        "generated_date": PINNED_AUDIT_DATE,
        "python_version": sys.version.split()[0],
        "part_a_clinical_h1_reanchor": part_a,
        "part_b_abx_cd64t_il1rn_modeb_protein_gate": part_b,
        "part_c_siglec_glycoengineering_and_st6gal1": part_c,
        "part_d_oq016_portfolio_odds": part_d,
        "part_e_live_pmid_verification_summary": {
            "receipt_filename": PMID_RECEIPT_OUT.name,
            "receipt_sha256": sha256_file(PMID_RECEIPT_OUT),
            "total_pmids_verified": pmid_receipt["total_pmids_verified"],
            "retracted_count": pmid_receipt["retracted_count"],
        },
        "part_f_evidence_extraction_validation_summary": {
            "bundle_filename": EVIDENCE_BUNDLE_OUT.name,
            "bundle_sha256": sha256_file(EVIDENCE_BUNDLE_OUT),
            "extraction_verification_receipt_filename": EXTRACTION_RECEIPT_OUT.name,
            "extraction_verification_receipt_sha256": sha256_file(EXTRACTION_RECEIPT_OUT),
            "overall_status": ev_audit["overall_status"],
            "gate_pass_map": {k: v["passed"] for k, v in ev_audit["gates"].items()},
            "g2b_tamper_resistance_self_test": g2b_self,
        },
    }
    rec_raw = json.dumps(receipt, indent=2, ensure_ascii=False)
    if PRIVACY_HOME_TOKEN in rec_raw:
        raise ValueError("Privacy leak detected in verification receipt!")
    RECEIPT_OUT.write_text(rec_raw + "\n", encoding="utf-8")

    print("\n=== ALL EXP-028 STAGE S3-R3 VERIFICATION GATES PASSED ===")
    for fn in (_SCRIPT_PATH, FASTA_OUT, RECEIPT_OUT, PMID_RECEIPT_OUT, EVIDENCE_BUNDLE_OUT, EXTRACTION_RECEIPT_OUT):
        print(f"  {fn.name:48s}  {fn.stat().st_size:7d} B  SHA-256={sha256_file(fn)}")


if __name__ == "__main__":
    main()
