#!/usr/bin/env python3
"""
IIP-0043 / DEC-122 (CAND-034 / EXP-031 — Bucket 1 Closure, Stage S3-R2 Remediated)
Standalone 80-Digit Outward-Directed Taylor Interval Decimal Verifier for:
  - Part A (NW-18): Hardened 3-Pathogen (CVB4-E2, CVB3, HCMV) x 5-Lineage Whole-Graft
    Viral Safety Gate 0V (two-stage FPR-calibrated screen + orthogonal ddPCR confirmation,
    latent HCMV + CVB 5'-deletion genome arm, dual-marker <=5% unassigned lineage cap,
    fragile infected-cell spike control, fixed 500 ng/mL non-vacuous Gate 0V-A with
    >=2.0-fold induction in >=3/4 markers/lineage + controls, strain-specific ectopic
    CD46_WT / CD55 viral addenda across A/B/X, Y-FullStack v2, and D1b-Auto L1B,
    operational bank-qualification vs lot-release vs autologous D1b split, explicit
    clustering/independence design-effect adjustment, raw-count recomputed Gate 0V-Kill
    separating per-total-input and conditional per-pre-treatment-infected-at-risk
    estimands, viral caspase-9/3 blockade check in infected HCMV/CVB4 arms, reconciled
    survivors_scored_n, assay volume/LOD, SHA-256 evidence digests, and lot/MCB/product/
    payload_sha256 binding with CLI --evaluate-lot <json>)
  - Part B (NW-08): True 3D FVM Vascular-Voxel (m_vasc = 1.3164) Layer-4 Oxygen Replay
    across all 8 live Route 1 / Route 2 / Route 3P cases (D_O2_ISLET = 1.3e-5 cm^2/s),
    margin + measurement-uncertainty-to-15-mmHg triggering (replacing the flawed +20%
    trigger), and source-typed 5-lineage calibration matrix (literature group means,
    whole-islet proxies, cell-line stress sensitivities, model allowances)
  - Part C (CEG-DELTA V3.3 + Option-2 Governance): Parameterized Protected-File Manifest
    (--protected-manifest), Playbook §4.1.20 Canonical Section-Hash Check, In-Memory
    render_documentation.py Verification for docs/GATE-0V-WHOLEGRAFT-PROTOCOL.md,
    Dual-Evaluator Composite Release Governance, Case-Normalized CEG-DELTA Live Diff
    (7 real staging repairs + 1 confirmed Zenodo CC-BY-4.0 dataset record 10813168), and
    De-Collided Idea Graveyard Guardrail GY-030 (OFFGRID_GUARD_020_*)
  - Part D (OQ-016 §5.5): +0.00 pp Headline Odds Invariance & Corrected Pre-IND
    Detection Power (99.833392% / 1.6661e-3 / 1.2513e-14)

Strict Option-2 Zero-LIMS-Touch & Cross-Runtime Design:
  - Core Gate 0V evaluator uses Python standard library only; ZERO imports of
    scripts/wetlab_contract.py or scripts/ingest_wetlab_results.py (composite dual
    evaluation lives in standalone evaluate_gate0v_composite_release.py); ZERO `assert`
    statements (`python3 -O -B` safe).
  - ZERO reliance on Python Decimal.ln() / Decimal.exp() for sound bounds (exact Fraction
    argument reduction + elementary +, -, *, / outward-directed Taylor interval arithmetic
    with full ambient-context & Inexact-trap immunity).
  - ZERO hardcoded user home paths; fully portable via Path(__file__).resolve() / CLI flags.

Run with:
  PYTHONDONTWRITEBYTECODE=1 python3 -B verify_exp031_wholegraft_gate0v_and_calibration.py
  PYTHONDONTWRITEBYTECODE=1 python3 -O -B verify_exp031_wholegraft_gate0v_and_calibration.py
  PYTHONDONTWRITEBYTECODE=1 python3 -B verify_exp031_wholegraft_gate0v_and_calibration.py --evaluate-lot <lot.json>
"""
from __future__ import annotations

import argparse
import copy
from datetime import datetime, timezone
import decimal
from decimal import Context, Decimal, ROUND_CEILING, ROUND_FLOOR, ROUND_HALF_EVEN, localcontext
from fractions import Fraction
from functools import lru_cache
import glob
import hashlib
import importlib.util
import inspect
import json
import math
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tempfile
import threading
from typing import Any, Dict, List, Tuple

sys.dont_write_bytecode = True

# Process-wide thread-safe cache lock & root-keyed native float64 caches shared across ALL loaded
# instances of verify_iip0043 (direct import, composite wrapper, or importlib copies) (R03-B2 + R14-B3 + R18-B1/B2).
# Native 3D FVM solves execute inside isolated child Python subprocesses bound strictly to the
# requested `openislet_root / "scripts"` so parent `sys.path`, `sys.modules`, and Layer-4 callbacks
# are NEVER mutated.
_FVM_SOLVER_LOCK: threading.RLock = threading.__dict__.setdefault(
    "_OPENISLET_IIP0043_FVM_SOLVER_LOCK", threading.RLock()
)
_NATIVE_BASELINE_MMHG_CACHE: Dict[Tuple[str, str, float, float], float] = threading.__dict__.setdefault(
    "_OPENISLET_IIP0043_NATIVE_BASELINE_MMHG_CACHE", {}
)
_NATIVE_BASELINE_META_CACHE: Dict[Tuple[str, str, float, float], Dict[str, Any]] = threading.__dict__.setdefault(
    "_OPENISLET_IIP0043_NATIVE_BASELINE_META_CACHE", {}
)
_MESH_REFINEMENT_SOLVE_CACHE: Dict[Tuple[str, str, float, float, int, int, str], Tuple[float, float]] = threading.__dict__.setdefault(
    "_OPENISLET_IIP0043_MESH_REFINEMENT_SOLVE_CACHE", {}
)

# ---------------------------------------------------------------------------
# Portable Path Resolution (Zero Hardcoded User Paths)
# ---------------------------------------------------------------------------
SCRIPT_DIR = Path(__file__).resolve().parent
DEFAULT_RECEIPT_PATH = (
    SCRIPT_DIR.parent / "data" / "extracted" / "iip0043_wholegraft_gate0v_and_calibration_v0.8.0.json"
    if SCRIPT_DIR.name == "scripts"
    else SCRIPT_DIR / "exp031_verification_receipt.json"
)

_LOT_ALIAS_KEYS: Tuple[str, ...] = ("evaluated_lot_id", "lot_id", "batch_id", "mcb_lot_id", "mcb_batch_id")
_LOT_PLANNED_ROUTE_KEYS: Tuple[str, ...] = (
    "nw08_route_id",
    "planned_nw08_route_id",
    "planned_route_id",
    "geometry_route_id",
)
_PLACEHOLDER_TOKEN_RE = re.compile(r"(?i)\b(?:TBD|TODO|PLACEHOLDER|FIXME|XXX|PENDING_VALUE|DUMMY)\b|\?\?\?")
_FORBIDDEN_ID_CHARS_RE = re.compile(r"[\x00-\x1f\x7f\u200b-\u200f\u2028-\u202f\u2060-\u206f\ufeff]")
_HEX64_RE = re.compile(r"^[0-9a-f]{64}$")
_UTC_ISO8601_RE = re.compile(r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?)(?:Z|\+00:00)$")
MAX_STRICT_JSON_INT_ABS: int = 10 ** 300
MAX_JSON_NESTING_DEPTH: int = 64


def _check_json_nesting_depth_iterative(raw_text: str, *, max_depth: int = MAX_JSON_NESTING_DEPTH) -> None:
    """
    R11-B4 Purely iterative O(n), string/escape-aware JSON container nesting-depth validator.
    Enforces `depth <= max_depth` BEFORE invoking `json.loads` with ZERO recursion so deeply nested
    documents (e.g. > 64 nested `{`/`[` frames) fail closed cleanly with `StrictJSONDecodeError`
    (`JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED`) instead of exhausting Python's recursion limit.
    """
    depth = 0
    in_string = False
    escaped = False
    for ch in raw_text:
        if in_string:
            if escaped:
                escaped = False
            elif ch == "\\":
                escaped = True
            elif ch == '"':
                in_string = False
            continue
        if ch == '"':
            in_string = True
        elif ch == "{" or ch == "[":
            depth += 1
            if depth > max_depth:
                raise StrictJSONDecodeError(
                    f"JSON nesting depth exceeds supported limit {max_depth}",
                    reason_code="JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED",
                )
        elif ch == "}" or ch == "]":
            if depth > 0:
                depth -= 1


def _enforce_release_authorizing_false_iterative(root_obj: Any) -> Any:
    """
    R11-B2 Purely iterative stack walk ensuring NO dict anywhere inside a standalone diagnostic
    payload carries `release_authorizing == True` (forces every occurrence to `False`).
    """
    stack: List[Any] = [root_obj]
    seen_ids: set[int] = set()
    while stack:
        cur = stack.pop()
        if isinstance(cur, dict):
            cid = id(cur)
            if cid in seen_ids:
                continue
            seen_ids.add(cid)
            if "release_authorizing" in cur:
                cur["release_authorizing"] = False
            for v in cur.values():
                if isinstance(v, (dict, list, tuple)):
                    stack.append(v)
        elif isinstance(cur, (list, tuple)):
            cid = id(cur)
            if cid in seen_ids:
                continue
            seen_ids.add(cid)
            for item in cur:
                if isinstance(item, (dict, list, tuple)):
                    stack.append(item)
    return root_obj


class StrictJSONDecodeError(ValueError):
    """Raised on ambiguous, non-canonical, non-finite, or out-of-range JSON."""

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


_EXACT_DECIMAL_PRESERVED_JSON_KEYS: frozenset[str] = frozenset({
    # Clustering / independence design-effect boundary keys (R12-B2)
    "clustering_design_effect_deff",
    "deff",
    # NW-08 measured OCR / FVM boundary keys
    "measured_ocr",
    "uncertainty_se",
    "measured_ocr_u95_override",
    "p_bed_mmhg",
    "baseline_vasc_ocr_mult",
    "baseline_min_face_mmhg",
    "local_3d_slope_mmhg_per_pct",
    "z_one_sided_95",
    "z_score",
    "floor_mmhg",
    # Gate 0V-A / 0V-B / 0V-Geno / 0V-Kill / CD46 / CD55 exact threshold keys
    "caspase9_3_activity_fold_over_vehicle",
    "poly_ic_dose_ng_ml",
    "assay_duration_h",
    "IFNB1_or_IFNL1_fold",
    "ISG15_fold",
    "MX1_fold",
    "OAS1_fold",
    "beta",
    "alpha",
    "delta",
    "plvap_iec",
    "pericyte",
    "endocrine_72h_log10_pfu_u95",
    "vascular_72h_log10_pfu_u95",
    "coculture_72h_log10_pfu_u95",
    "endocrine_day14_log10_reduction_l95",
    "vascular_day14_log10_reduction_l95",
    "day28_supernatant_infectious_pfu_ml",
    "day28_supernatant_assay_volume_ml",
    "day28_supernatant_lod_pfu_ml",
    "edited_minus_wt_day14_log10_reduction_l95",
    "reactivation_7d_outgrowth_pfu_ml",
    "reactivation_assay_volume_ml",
    "reactivation_lod_pfu_ml",
    "titer_72h_log10_pfu_u95",
    "day14_log10_reduction_l95",
    "day28_supernatant_pfu_ml",
    "day28_assay_volume_ml",
    "day28_lod_pfu_ml",
    "echovirus_titer_72h_log10_pfu_u95",
    "echovirus_day14_log10_reduction_l95",
    "echovirus_day28_supernatant_pfu_ml",
})


def _coerce_non_dict_decimals_to_float(val: Any) -> Any:
    """Convert raw parsed Decimal tokens outside preserved exact-boundary keys to IEEE-754 float64
    without mutating child dicts whose keys were already finalized by object_pairs_hook."""
    if isinstance(val, Decimal):
        return float(val)
    if isinstance(val, list):
        return [_coerce_non_dict_decimals_to_float(item) for item in val]
    return val


def _make_strict_json_object_pairs_hook(preserve_boundary_decimals: bool):
    def _hook(pairs: List[Tuple[str, Any]]) -> Dict[str, Any]:
        obj: Dict[str, Any] = {}
        for key, val in pairs:
            if key in obj:
                raise StrictJSONDecodeError(
                    f"Duplicate JSON object key rejected: {key!r}",
                    reason_code="DUPLICATE_JSON_KEY",
                )
            if preserve_boundary_decimals and key in _EXACT_DECIMAL_PRESERVED_JSON_KEYS:
                obj[key] = val
            else:
                obj[key] = _coerce_non_dict_decimals_to_float(val)
        return obj
    return _hook


_strict_json_object_pairs_hook = _make_strict_json_object_pairs_hook(True)


def _strict_json_reject_constant(token: str) -> Any:
    raise StrictJSONDecodeError(
        f"Non-standard JSON constant rejected: {token!r}",
        reason_code="NON_STANDARD_JSON_CONSTANT",
    )


def _strict_json_parse_finite_float(token: str) -> Decimal:
    """
    R12-B2 Exact-Decimal JSON float token parser:
      - Parses every JSON float token via exact `Decimal(token)` inside an isolated untrapped context.
      - Rejects NaN, Infinity, or magnitude > 1e300 (`NON_FINITE_JSON_FLOAT`).
      - Rejects nonzero IEEE-754 float64 underflow (e.g. `-1e-400`, `1e-400`, `-1e-325` where
        `dec_val != 0` yet `float(token) == 0.0`) with `NONZERO_FLOAT_UNDERFLOW_REJECTED`.
      - Returns exact `Decimal` so adjudication-boundary keys preserve full precision and sign
        (including `-0.0` and `1.00000000000000001`).
    """
    with localcontext(
        Context(
            prec=120,
            rounding=ROUND_HALF_EVEN,
            Emax=decimal.MAX_EMAX,
            Emin=decimal.MIN_EMIN,
            capitals=1,
            clamp=0,
            flags=[],
            traps=[],
        )
    ):
        try:
            dec_val = Decimal(token)
        except (decimal.InvalidOperation, ValueError) as exc:
            raise StrictJSONDecodeError(
                f"Unrepresentable JSON float rejected: {token!r}",
                reason_code="NON_FINITE_JSON_FLOAT",
            ) from exc
        if not dec_val.is_finite() or dec_val.copy_abs() > Decimal("1e300"):
            raise StrictJSONDecodeError(
                f"Non-finite or overflowing JSON float rejected: {token!r}",
                reason_code="NON_FINITE_JSON_FLOAT",
            )
        try:
            fval = float(token)
        except (OverflowError, ValueError) as exc:
            raise StrictJSONDecodeError(
                f"Unrepresentable JSON float rejected: {token!r}",
                reason_code="NON_FINITE_JSON_FLOAT",
            ) from exc
        if not math.isfinite(fval) or abs(fval) > 1e300:
            raise StrictJSONDecodeError(
                f"Non-finite or overflowing JSON float rejected: {token!r}",
                reason_code="NON_FINITE_JSON_FLOAT",
            )
        if dec_val != Decimal(0) and fval == 0.0:
            raise StrictJSONDecodeError(
                f"Nonzero JSON float underflowing float64 to zero rejected: {token!r}",
                reason_code="NONZERO_FLOAT_UNDERFLOW_REJECTED",
            )
        return dec_val


def _make_bounded_int_parser(max_int_abs: int | None):
    def _parse_bounded_int(token: str) -> int:
        try:
            val = int(token)
        except ValueError as exc:
            raise StrictJSONDecodeError(
                f"Out-of-range JSON integer literal rejected (length={len(token)})",
                reason_code="OUT_OF_RANGE_JSON_INTEGER",
            ) from exc
        if token.startswith("-") and val == 0:
            raise StrictJSONDecodeError(
                f"Signed negative-zero JSON integer literal rejected: {token!r}",
                reason_code="INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE",
            )
        if max_int_abs is not None and abs(val) > max_int_abs:
            raise StrictJSONDecodeError(
                f"Out-of-float64-range JSON integer rejected (digits={len(token.lstrip('+-'))})",
                reason_code="OUT_OF_RANGE_JSON_INTEGER",
            )
        return val
    return _parse_bounded_int


def _is_negative_zero(val: Any) -> bool:
    """Return True strictly when `val` is a signed negative zero (`-0.0`, `Decimal('-0.0')`, `'-0.0'`)."""
    if isinstance(val, bool) or val is None:
        return False
    if isinstance(val, Decimal):
        with localcontext(
            Context(prec=120, rounding=ROUND_HALF_EVEN, Emax=decimal.MAX_EMAX, Emin=decimal.MIN_EMIN, traps=[])
        ):
            return bool(val.is_finite() and val == Decimal(0) and val.is_signed())
    if isinstance(val, float):
        return bool(math.isfinite(val) and val == 0.0 and math.copysign(1.0, val) < 0.0)
    if isinstance(val, str):
        s = val.strip()
        if not s:
            return False
        with localcontext(
            Context(prec=120, rounding=ROUND_HALF_EVEN, Emax=decimal.MAX_EMAX, Emin=decimal.MIN_EMIN, traps=[])
        ):
            try:
                d = Decimal(s)
            except (decimal.InvalidOperation, ValueError):
                return False
            return bool(d.is_finite() and d == Decimal(0) and d.is_signed())
    return False


def _safe_finite_float(val: Any, name: str) -> float:
    """Safely convert non-bool int/float/Decimal to finite IEEE-754 float64, rejecting NaN/Inf,
    magnitude > 1e300, OverflowError, and nonzero float64 underflow."""
    if isinstance(val, bool) or not isinstance(val, (int, float, Decimal)):
        raise ValueError(f"Non-finite or non-numeric {name}={val!r}")
    if isinstance(val, Decimal):
        with localcontext(
            Context(prec=120, rounding=ROUND_HALF_EVEN, Emax=decimal.MAX_EMAX, Emin=decimal.MIN_EMIN, traps=[])
        ):
            if not val.is_finite() or val.copy_abs() > Decimal("1e300"):
                raise ValueError(f"Non-finite or overflowing {name}={val!r}")
            try:
                fval = float(val)
            except (OverflowError, TypeError, ValueError) as exc:
                raise ValueError(f"Out-of-float64-range or invalid {name}") from exc
            if not math.isfinite(fval) or abs(fval) > 1e300:
                raise ValueError(f"Non-finite or overflowing {name}={val!r}")
            if val != Decimal(0) and fval == 0.0:
                raise ValueError(f"NONZERO_FLOAT_UNDERFLOW_REJECTED:{name}={val!r}")
            return fval
    try:
        fval = float(val)
    except (OverflowError, TypeError, ValueError) as exc:
        raise ValueError(f"Out-of-float64-range or invalid {name}") from exc
    if not math.isfinite(fval) or abs(fval) > 1e300:
        raise ValueError(f"Non-finite {name}={val!r}")
    return fval


def _parse_nw08_boundary_scalar(
    val: Any,
    name: str,
    *,
    non_negative: bool = True,
    strictly_positive: bool = False,
) -> Tuple[float, Decimal]:
    """
    R12-B2 Strictly validate an NW-08 numeric boundary parameter (`int`, `float`, or exact `Decimal`):
      - Rejects bool, str, None, NaN, Infinity, magnitude > 1e300, and nonzero float64 underflow.
      - When `non_negative=True` or `strictly_positive=True`, explicitly rejects signed negative zero
        (`-0.0`, `Decimal('-0.0')`) and negative values BEFORE float64 conversion with
        `INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE`.
      - Returns `(float64_val, exact_decimal_val)` preserving exact precision and sign.
    """
    if (non_negative or strictly_positive) and _is_negative_zero(val):
        raise ValueError(f"INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE:{name}={val!r}")
    if isinstance(val, bool) or not isinstance(val, (int, float, Decimal)):
        raise ValueError(f"Non-finite or non-numeric {name}={val!r}")
    with localcontext(
        Context(prec=120, rounding=ROUND_HALF_EVEN, Emax=decimal.MAX_EMAX, Emin=decimal.MIN_EMIN, traps=[])
    ):
        if isinstance(val, Decimal):
            if not val.is_finite() or val.copy_abs() > Decimal("1e300"):
                raise ValueError(f"Non-finite or overflowing {name}={val!r}")
            dec_val = val
            try:
                fval = float(val)
            except (OverflowError, TypeError, ValueError) as exc:
                raise ValueError(f"Out-of-float64-range or invalid {name}") from exc
            if not math.isfinite(fval) or abs(fval) > 1e300:
                raise ValueError(f"Non-finite or overflowing {name}={val!r}")
            if dec_val != Decimal(0) and fval == 0.0:
                raise ValueError(f"NONZERO_FLOAT_UNDERFLOW_REJECTED:{name}={val!r}")
        elif isinstance(val, int):
            if abs(val) > MAX_STRICT_JSON_INT_ABS:
                raise ValueError(f"Out-of-float64-range {name}")
            dec_val = Decimal(val)
            try:
                fval = float(val)
            except (OverflowError, TypeError, ValueError) as exc:
                raise ValueError(f"Out-of-float64-range or invalid {name}") from exc
            if not math.isfinite(fval):
                raise ValueError(f"Non-finite {name}")
        else:
            if not math.isfinite(val) or abs(val) > 1e300:
                raise ValueError(f"Non-finite or overflowing {name}={val!r}")
            fval = val
            dec_val = Decimal(str(val))
        if (non_negative or strictly_positive) and _is_negative_zero(val):
            raise ValueError(f"INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE:{name}={val!r}")
        if strictly_positive and dec_val <= Decimal(0):
            raise ValueError(f"INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE:{name} must be > 0; got {val!r}")
        if non_negative and dec_val < Decimal(0):
            raise ValueError(f"INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE:{name} must be >= 0; got {val!r}")
    return fval, dec_val


def _parse_strict_utc_timestamp(val: Any) -> datetime | None:
    """Parse strict RFC-3339/ISO-8601 UTC timestamp (`YYYY-MM-DDTHH:MM:SS[.ffffff](Z|+00:00)`)."""
    if not isinstance(val, str) or val != val.strip():
        return None
    if not _UTC_ISO8601_RE.fullmatch(val):
        return None
    try:
        iso_norm = val[:-1] + "+00:00" if val.endswith("Z") else val
        dt = datetime.fromisoformat(iso_norm)
    except ValueError:
        return None
    if dt.tzinfo is None or dt.utcoffset() != timezone.utc.utcoffset(dt):
        return None
    return dt.astimezone(timezone.utc)


def strict_json_loads(
    raw_text: str,
    *,
    max_int_abs: int | None = None,
    max_depth: int = MAX_JSON_NESTING_DEPTH,
    preserve_boundary_decimals: bool = True,
) -> Any:
    """
    R09-B1 + R10-B2 + R11-B4 + R12-B2 Single canonical strict RFC-8259 JSON decoder enforced across ALL IIP-0043 intake boundaries:
      - Enforces bounded JSON nesting depth (`max_depth = MAX_JSON_NESTING_DEPTH = 64`) via a
        purely iterative O(n) pre-scanner AND maps any parser `RecursionError` to
        `StrictJSONDecodeError(reason_code="JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED")`.
      - Rejects duplicate object keys at ANY nesting depth (including unicode-escaped duplicates)
        via `object_pairs_hook`, raising `StrictJSONDecodeError(reason_code="DUPLICATE_JSON_KEY")`.
      - Rejects non-standard `NaN`, `Infinity`, and `-Infinity` constants via `parse_constant`,
        raising `StrictJSONDecodeError(reason_code="NON_STANDARD_JSON_CONSTANT")`.
      - Parses every JSON float via exact `Decimal(token)`, rejecting NaN/Inf/magnitude > 1e300
        (`NON_FINITE_JSON_FLOAT`) AND rejecting nonzero float64 underflow (e.g. `-1e-400`, `1e-400`)
        with `StrictJSONDecodeError(reason_code="NONZERO_FLOAT_UNDERFLOW_REJECTED")`.
      - When `preserve_boundary_decimals=True` (default for all operator adjudication intake),
        preserves exact `Decimal` on all adjudication-boundary keys (`clustering_design_effect_deff`,
        `deff`, `measured_ocr`, `uncertainty_se`, `p_bed_mmhg`, `baseline_vasc_ocr_mult`, `floor_mmhg`,
        `z_one_sided_95`, etc.) so JSON numbers and JSON strings never diverge on precision or sign.
      - When `max_int_abs` is set (enforced on all operator lot/OCR/store intake files with
        `MAX_STRICT_JSON_INT_ABS = 10**300`), rejects out-of-float64-range finite JSON integers
        (e.g. `10**350`, `10**400`) via `parse_int`, raising `StrictJSONDecodeError(reason_code="OUT_OF_RANGE_JSON_INTEGER")`.
      - Rejects standard syntax errors via `json.JSONDecodeError`.
    """
    if not isinstance(raw_text, str):
        raise StrictJSONDecodeError(
            f"Expected JSON text str, got {type(raw_text).__name__}",
            reason_code="INVALID_JSON_INPUT_TYPE",
        )
    if not _is_strict_int(max_depth) or max_depth < 1:
        raise StrictJSONDecodeError(
            f"Invalid max_depth={max_depth!r}",
            reason_code="INVALID_JSON_MAX_DEPTH",
        )
    _check_json_nesting_depth_iterative(raw_text, max_depth=max_depth)
    kw: Dict[str, Any] = {
        "object_pairs_hook": _make_strict_json_object_pairs_hook(bool(preserve_boundary_decimals)),
        "parse_constant": _strict_json_reject_constant,
        "parse_float": _strict_json_parse_finite_float,
        "parse_int": _make_bounded_int_parser(max_int_abs),
    }
    try:
        parsed = json.loads(raw_text, **kw)
    except RecursionError as exc:
        raise StrictJSONDecodeError(
            f"JSON parser recursion limit exceeded (max supported nesting depth={max_depth})",
            reason_code="JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED",
        ) from exc
    return _coerce_non_dict_decimals_to_float(parsed)


def strict_json_load_file(
    path: Path,
    *,
    max_int_abs: int | None = None,
    max_depth: int = MAX_JSON_NESTING_DEPTH,
    preserve_boundary_decimals: bool = True,
) -> Any:
    """Read UTF-8 text from `path` and decode strictly with `strict_json_loads`."""
    return strict_json_loads(
        path.read_text(encoding="utf-8"),
        max_int_abs=max_int_abs,
        max_depth=max_depth,
        preserve_boundary_decimals=preserve_boundary_decimals,
    )


def _resolve_roots(
    repo_root_arg: Path | None = None,
    investigations_root_arg: Path | None = None,
) -> Tuple[Path, Path | None]:
    """Resolve OpenIslet science repo root and optional Investigations root portably."""
    if repo_root_arg is not None:
        openislet_root = repo_root_arg.resolve()
    else:
        cand_installed = SCRIPT_DIR.parent
        cand_sibling = SCRIPT_DIR.parents[3] / "OpenIslet" if len(SCRIPT_DIR.parents) >= 4 else cand_installed
        if (cand_installed / "data" / "extracted" / "context_evidence_graph_v1.json").is_file():
            openislet_root = cand_installed
        elif (cand_sibling / "data" / "extracted" / "context_evidence_graph_v1.json").is_file():
            openislet_root = cand_sibling
        else:
            openislet_root = cand_installed

    if investigations_root_arg is not None:
        inv_root: Path | None = investigations_root_arg.resolve()
    else:
        cand_inv = SCRIPT_DIR.parents[2] if len(SCRIPT_DIR.parents) >= 3 else None
        if cand_inv is not None and (cand_inv / "ideas" / "CEG-DELTA-STAGING.md").is_file():
            inv_root = cand_inv
        else:
            inv_root = None

    return openislet_root, inv_root


# ---------------------------------------------------------------------------
# Default Baseline Protected Pins (Overridable via --protected-manifest at S5)
# Playbook is pinned by canonical §4.1.20 section SHA-256 (matching verify_iip0035),
# NOT a brittle whole-file hash!
# In public-bundle mode (detected via `.openislet_public_bundle`), the two
# publisher-redacted study extracts (17375075.json, 39571901.json) are pinned
# strictly to their exact public-redacted SHA-256 hashes.
# ---------------------------------------------------------------------------
IIP0035_17_PROTECTED_FILES_SHA256: Dict[str, str] = {
    "scripts/wetlab_contract.py": "331ecd2f2d8602dfceae8b89263d0f360cfadfd0638a46d7d668a376294cfc73",
    "scripts/ingest_wetlab_results.py": "e050593675170515382257ce379449db596c87cc06ffc26d31d128e127630cb1",
    "data/protocols/wetlab_endpoint_contract_v0.8.0.json": "757bc1d9c2722c129cc4fd5962e8995b9f5bc5f7035f8530f5716da9aa2ac26f",
    "data/extracted/islet1_multiparadigm_portfolio_v0.8.0.json": "3ed4d53f1756b8b8615fbbc4e9a15755b9ab4968d206da61160eeb04d833cd45",
    "data/extracted/iip0034_planar_and_portfolio_verification_v0.8.0.json": "e54c7ee4759267befd8f77fc6dd47a72452e2e1c39c1a103bf00281db39f97f1",
    "data/extracted/iip0033_bilayer_and_respirometry_verification_v0.8.0.json": "bf581a628a69efa41acfc4d5e01de08d36b1c52fc913a0a9c309a27b6b97807e",
    "data/extracted/islet1_combinatorial_pareto_and_ladder_v0.8.0.json": "460ebc1939eb98b38627eaa7d6603c086e5a75c127fc1ddeced0d5a325305f40",
    "data/extracted/17375075.json": "b8decbb5b7ef6807b9ed53eddee4159c98d524200dbbfb8601d0dcf02f5ea3b5",
    "data/extracted/39571901.json": "73d155458b30d631326a5362403e8fa30d03a92a93dbcf44da960e686a3998f1",
    "data/constructs/islet1_design_b_complete_constructs_v0.8.0.fasta": "4bb20389773c76b2705031ba675487825dfbd94d920a692cde75b7d56af22aa4",
    "data/constructs/islet1_design_y_fullstack_v2_v0.8.0.fasta": "9826f7917c73f56b62f38db9df0fd61d2ffbf90da3f454392c9f415c16de336c",
    "data/constructs/islet1_design_y_wildcard_comparators_v0.8.0.fasta": "c7f54b824a73cf9d40247d4fd251cb5c28a8eca4a1530b9661284200bb4cbabc",
    "data/constructs/islet1_locus1_s10_modeb_comparators_v0.8.0.fasta": "a589ea72144cf1ad2cfa82e9b08c22e075746c63a9264e276a3bd4ec3f896854",
    "data/constructs/islet1_locus2_ciita_modeb_comparators_v0.8.0.fasta": "25ffcb10e2bad77a4b34725c7eff0532990ebf7b80864cf7217d33f5ccbe5b6d",
    "data/constructs/islet1_locus3_multimir_modeb_comparators_v0.8.0.fasta": "22df54a27ef3f68b646b63dc036b11f5a66a9fcadb50378dfb8057e108c79ffa",
    "data/constructs/islet1_scenario_a_constructs_v0.7.0.fasta": "b5ba4e2b4bbbcc7d6cf1138975c5fae5c6ab074dda43973f071c671cd8cd1d88",
    "data/constructs/nm_021999_5_archival_mrna.fasta": "4a4cb15d0544884a62d86ebf4137c5284edad8210b6e32e74c2eb0aff005d13e",
}

PUBLIC_BUNDLE_REDACTED_FILES_SHA256: Dict[str, str] = {
    "data/extracted/17375075.json": "04338bd37bf6149aacc1d8153f7455ee1a4e4a71fa8398dff1c77ced66eac48b",
    "data/extracted/39571901.json": "fd0fea4c563a674ed67c6f9ae260a38ab7d204c4238cfa19bf3671de457a45e7",
}

IIP0035_OWN_FROZEN_OUTPUTS_SHA256: Dict[str, str] = {
    "data/constructs/islet1_d1b_auto_v2_v0.8.0.fasta": "36b5c38181fd6d9409e82d53edee16130f4309e08c481a59055d705de4f01974",
    "data/extracted/iip0035_d1b_auto_and_portfolio_verification_v0.8.0.json": "9d3252b780f14781154a7b969c5ada4907e037c19da1a8559e4977ce1ebe81d5",
    "data/extracted/islet1_5arm_autologous_portfolio_v0.8.0.json": "31320c0e6ac039773c2ca58160f064e8655d1a58b97050a713dfbf00d283ff99",
}

PLAYBOOK_SEC4120_EXPECTED_SHA256 = "e3fb5ec701678dfdeb62a77c15866327842b60b6b4c503cb86dfc79885a626a8"

GRAVEYARD_GUARDRAIL_ID = "OFFGRID_GUARD_020_BETA_ONLY_VIRAL_GATE_AND_UNVERIFIED_STRESSED_AP1903_ERASURE"
GRAVEYARD_CARD_ID = "GY-030"

TRUSTED_STORE_SCHEMA_VERSION = "0.8.0-iip0043-trusted-qualification-store-v1"
BANK_QUAL_RECORD_SCHEMA_VERSION = "0.8.0-iip0043-bank-qual-record-v2"
PROC_QUAL_RECORD_SCHEMA_VERSION = "0.8.0-iip0043-d1b-proc-qual-record-v2"

# 5 living graft lineages in OpenIslet Islet-1 (500,000 IEQ = 8.00e8 endocrine + 1.335e8 vascular = 9.335e8 total cells)
GRAFT_LINEAGES: Tuple[str, ...] = ("beta", "alpha", "delta", "plvap_iec", "pericyte")

GRAFT_COMPOSITION_CELLS: Dict[str, int] = {
    "beta": 480_000_000,       # 60% of 8.00e8 endocrine (51.4194% of total graft)
    "alpha": 240_000_000,      # 30% of 8.00e8 endocrine (25.7097% of total graft)
    "delta": 80_000_000,       # 10% of 8.00e8 endocrine (8.5699% of total graft)
    "plvap_iec": 100_125_000,  # 75% of 1.335e8 vascular stroma (10.7258% of total graft)
    "pericyte": 33_375_000,    # 25% of 1.335e8 vascular stroma (3.5753% of total graft)
}
TOTAL_GRAFT_CELLS: int = sum(GRAFT_COMPOSITION_CELLS.values())  # 933,500,000

GATE0V_PATHOGENS: Tuple[str, ...] = ("cvb4_e2", "cvb3", "hcmv")

HCMV_REQUIRED_DDPCR_TARGETS: Tuple[str, ...] = ("UL138", "UL55")
CVB_REQUIRED_DDPCR_TARGETS: Tuple[str, ...] = (
    "CVB_5PRIME_DELETION_POS_RNA",
    "CVB_5PRIME_DELETION_NEG_RNA",
)

CD46_ADDENDUM_VIRUSES: Tuple[str, ...] = (
    "hhv6a",
    "measles_edmonston_vaccine_strain",
    "adenovirus_group_b",
)

CD55_REQUIRED_ECHOVIRUS_STRAINS: Tuple[str, ...] = (
    "echovirus_7",
    "echovirus_11",
)

ALLOWED_ECTOPIC_RECEPTORS = frozenset({"CD46_WT", "CD55_FULL_LENGTH"})

# Explicit canonical ectopic viral-receptor registry (ZERO substring inference!).
# Products expressing only the 37-aa CD55(345-381) GPI stalk on CD47-IgV-GPI do NOT
# express full-length DAF/CD55 and are intentionally excluded from CD55_FULL_LENGTH.
CANONICAL_ECTOPIC_VIRAL_RECEPTORS: Dict[str, Tuple[str, ...]] = {
    "ISLET1_Y_FULLSTACK_V2_B2M_11TU": ("CD46_WT",),
    "ISLET1_D1_AUTO_V2_L1B_CIITA_CD64T_CD46WT_COMPARATOR": ("CD46_WT",),
    "ABX_L2_v2_CD64T_CD46WT_COMP": ("CD46_WT",),
    "ABX_L2_v2_CTRL_CD46WT_ONLY": ("CD46_WT",),
    "ISLET1_Y_FULLSTACK_V2_CD55_CFH_COMPARATOR": ("CD55_FULL_LENGTH",),
    "ABX_L2_v2_CD64T_CFH_CD55_COMP": ("CD55_FULL_LENGTH",),
}

ALLOWED_QUALIFICATION_TIERS = frozenset({
    "BANK_QUALIFICATION",
    "LOT_RELEASE_SURROGATE",
    "AUTOLOGOUS_D1B_PROCESS_QUAL",
})

# R12-B1: Minimum independent biological units and canonical sampling-unit class allowlist.
MIN_INDEPENDENT_BIOLOGICAL_UNITS_N: int = 6
ALLOWED_INDEPENDENT_SAMPLING_UNIT_CLASSES: Tuple[str, ...] = (
    "INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT",
    "RECONCILED_MULTI_WELL_CELL_ASSAY_WITH_UNIT_PARTITION",
)

# R13-B4: Machine-readable software qualification scope emitted directly on live PASS results
# across all tiers (explicitly separating modeled Stage-0 software checks from physical qualification).
QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL: str = (
    "CONDITIONAL_ON_MODELED_ASSUMPTIONS_PENDING_PHYSICAL_QUALIFICATION"
)

# R04-B1: Strict canonical product-family-to-qualification-tier allowlist.
# AUTOLOGOUS_D1B_PROCESS_QUAL is strictly restricted to canonical autologous D1b-Auto-C
# variants (ISLET1_D1_AUTO_*); BANK_QUALIFICATION and LOT_RELEASE_SURROGATE are restricted
# to allogeneic MCB-banked product families (including IIP-0041 allogeneic ABX side-contract donors).
PRODUCT_TIER_FAMILY_ALLOWED_TIERS: Dict[str, Tuple[str, ...]] = {
    "ALLOGENEIC_MCB_BANKED": ("BANK_QUALIFICATION", "LOT_RELEASE_SURROGATE"),
    "ALLOGENEIC_ABX_SIDE_CONTRACT": ("BANK_QUALIFICATION", "LOT_RELEASE_SURROGATE"),
    "AUTOLOGOUS_D1B_AUTO_C": ("AUTOLOGOUS_D1B_PROCESS_QUAL",),
}

# R04-B5 + R17-B2: Provably outward-conservative one-sided >=95% standard-normal quantile
# z_{0.95} > Phi^{-1}(0.95) = 1.644853626951472714863848907991632136083195744275322071769672094...
# (applicable ONLY to explicitly declared KNOWN_SIGMA_NORMAL measurement models with external
# calibration provenance). Both the 60-digit Decimal constant and its upward-rounded IEEE-754
# float64 value strictly satisfy 1 - Phi(z) <= 0.05 (eliminating the ~5.39e-17 undercoverage of
# float 1.6448536269514722).
MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95_DEC: Decimal = Decimal(
    "1.644853626951472714863848907991632136083195744275322071769673"
)
MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95: float = 1.6448536269514729

# R14-B2: Canonical NW-08 measured-OCR inferential uncertainty models (NIST §8.6 compliant).
# Small-sample estimated SE requires STUDENT_T_ESTIMATED_SE with integer replicates/df (using exact
# one-sided 95% Student-t critical value t_{0.95, df}), or INDEPENDENT_JUSTIFIED_UPPER_BOUND with
# explicit provenance, or KNOWN_SIGMA_NORMAL strictly scoped to externally known sigma provenance.
NW08_OCR_UNCERTAINTY_MODEL_ZERO_POINT: str = "ZERO_UNCERTAINTY_DETERMINISTIC_POINT"
NW08_OCR_UNCERTAINTY_MODEL_STUDENT_T: str = "STUDENT_T_ESTIMATED_SE"
NW08_OCR_UNCERTAINTY_MODEL_KNOWN_SIGMA: str = "KNOWN_SIGMA_NORMAL"
NW08_OCR_UNCERTAINTY_MODEL_INDEPENDENT_UPPER: str = "INDEPENDENT_JUSTIFIED_UPPER_BOUND"
NW08_ALLOWED_OCR_UNCERTAINTY_MODELS = frozenset({
    NW08_OCR_UNCERTAINTY_MODEL_ZERO_POINT,
    NW08_OCR_UNCERTAINTY_MODEL_STUDENT_T,
    NW08_OCR_UNCERTAINTY_MODEL_KNOWN_SIGMA,
    NW08_OCR_UNCERTAINTY_MODEL_INDEPENDENT_UPPER,
})
MAX_NW08_STUDENT_T_DF: int = 10 ** 9

# R05-B2: Immutable canonical GSIS oxygen safety floor for NW-08 release adjudication (mmHg).
# Alternate diagnostic floors may be reported separately, but NEVER alter canonical release pass/verdict!
CANONICAL_NW08_PO2_FLOOR_MMHG: float = 15.0

# R14-B1 + R15-B2: Predeclared 3-grid numerical convergence verification policy (NASA / Roache GCI & ASME V&V-20).
# Any solve within its route-family near-floor screening band around 15.0 mmHg executes the predeclared
# refinement ladder; cases whose coarse-to-medium grids directly cross 15.0 mmHg or whose 3-grid
# conservative discretization interval straddles 15.0 mmHg route to unresolved HOLD (exit 2) before any
# coupled release authorization. Monotone sequences with sub-asymptotic slow observed order (`p_obs < 0.5`),
# non-positive/unverifiable order, extreme super-convergence (`p_obs > 2.5`), or non-asymptotic acceleration
# toward 15.0 mmHg NEVER clamp `p` upward to shrink GCI and instead route fail-closed to unresolved HOLD
# (`HOLD_NW08_MESH_CONVERGENCE_UNQUALIFIED_SLOW_OR_NON_ASYMPTOTIC_ORDER`, exit 2, `interval_valid = False`).
NW08_MESH_CONVERGENCE_POLICY_VERSION: str = "NW08_THREE_GRID_CONVERGENCE_HOLD_POLICY_V2"
NW08_MESH_CONVERGENCE_TRIGGER_BAND_MMHG: float = 0.25
NW08_MESH_CONVERGENCE_TRIGGER_BANDS_BY_FAMILY: Dict[str, Tuple[float, float]] = {
    "R1": (-0.12, 0.25),
    "R2": (-0.25, 0.25),
    "R3P": (-0.30, 0.30),
}
NW08_MESH_CONVERGENCE_SAFETY_FACTOR_FS: float = 1.25
NW08_MESH_CONVERGENCE_MIN_ADMISSIBLE_ORDER_P: float = 0.5
NW08_MESH_CONVERGENCE_FORMAL_ORDER_P: float = 2.0
NW08_MESH_CONVERGENCE_MAX_ADMISSIBLE_ORDER_P: float = 2.5
NW08_HOLD_TOKEN_STRADDLES_FLOOR: str = "HOLD_NW08_MESH_CONVERGENCE_STRADDLES_15MMHG_FLOOR"
NW08_HOLD_TOKEN_UNQUALIFIED_ORDER: str = "HOLD_NW08_MESH_CONVERGENCE_UNQUALIFIED_SLOW_OR_NON_ASYMPTOTIC_ORDER"
NW08_HOLD_TOKEN_INFERENTIAL_REQUIRES_POSITIVE_SE: str = "HOLD_NW08_INFERENTIAL_MODEL_REQUIRES_POSITIVE_SE"

NW08_MESH_STATUS_SINGLE_GRID_POLICY_PASS: str = "SINGLE_GRID_FAR_FROM_FLOOR_POLICY_PASS_ORDER_NOT_EVALUATED"
NW08_MESH_STATUS_SINGLE_GRID_POLICY_FAIL: str = "SINGLE_GRID_FAR_FROM_FLOOR_POLICY_FAIL_ORDER_NOT_EVALUATED"
NW08_MESH_STATUS_TWO_GRID_DIRECT_CROSSING_HOLD: str = "TWO_GRID_DIRECT_FLOOR_CROSSING_HOLD"
NW08_MESH_STATUS_THREE_GRID_ASYMPTOTIC_GCI_QUALIFIED: str = "THREE_GRID_ASYMPTOTIC_GCI_QUALIFIED"
NW08_MESH_STATUS_THREE_GRID_EXACT_ZERO_SPREAD: str = "THREE_GRID_EXACT_ZERO_SPREAD_CONVERGED"
NW08_MESH_STATUS_THREE_GRID_OSCILLATORY_BOUND: str = "THREE_GRID_OSCILLATORY_ASME_VV20_HALF_RANGE_BOUND"
NW08_MESH_STATUS_THREE_GRID_MONOTONE_FALLBACK: str = "THREE_GRID_MONOTONE_NON_ASYMPTOTIC_FALLBACK_ORDER_NOT_QUALIFIED"
NW08_MESH_STATUS_THREE_GRID_UNQUALIFIED_ORDER_HOLD: str = "THREE_GRID_UNQUALIFIED_ORDER_HOLD"
NW08_MESH_STATUS_THREE_GRID_NON_ASYMPTOTIC_HOLD: str = "THREE_GRID_NON_ASYMPTOTIC_STRADDLE_OR_TOWARD_FLOOR_HOLD"
NW08_MESH_STATUS_THREE_GRID_INVALID_HOLD: str = "THREE_GRID_INVALID_OR_NONFINITE_HOLD"

# R10-B1: Canonical 8-route NW-08 geometry allowlist shared by lot-envelope validation and coupled OCR dispatch.
CANONICAL_NW08_ROUTE_IDS = frozenset({
    "R1_390_nominal",
    "R1_350_stress",
    "R1_390_stress",
    "R2_DZ40",
    "R3P_35",
    "R3P_30",
    "R3P_30_KRBH",
    "R3P_35_VPIO120",
})

# R05-M1 + R10-M2 + R15-M2: Public release ledger of the exact 8 indirect/contextual non-certifying
# CEG cross-link edges (`primary_certification_eligible = false`) added under IIP-0043
# (CEG-DELTA V3.3) to pre-existing studies in data/extracted/context_evidence_graph_v1.json,
# carrying independent expected relation, target_gate_or_module, applicability, and cited_outcome_tuples
# fields for verbatim programmatic parity verification.
CEG_DELTA_V33_EIGHT_CROSSLINKS_SPEC: Tuple[Dict[str, Any], ...] = (
    {
        "edge_id": "M0085:L4",
        "queue_id": "M0085",
        "pmid": "37854597",
        "pre_iip0043_study_status": "existing_wave1_ceg_candidate_promoted_to_ring1_in_wave5",
        "pre_iip0043_prior_edge_ids": ["M0085:L1", "M0085:L2", "M0085:L3"],
        "expected_relation": "scoping_qualification",
        "expected_target_gate_or_module": "Gate0V-Geno / NW-18 (selective TYK2 pseudokinase inhibition preserves IFN-gamma while blunting IFN-alpha; EndoC-betaH1 cell line T5)",
        "expected_applicability": "unvalidated_transfer",
        "expected_cited_outcome_tuples": ["M0085:O1", "M0085:O5", "M0085:O6"],
        "previous_edge_state": "absent_pre_iip0043",
        "added_edge_status": "added_by_iip0043_scoping_non_certifying",
        "evidence_scope": "indirect_contextual_non_certifying",
        "contextual_scope_note": "Indirect contextual cross-link (primary_certification_eligible=false): selective TYK2 inhibition in EndoC-betaH1 cell line provides Gate 0V-Geno context.",
    },
    {
        "edge_id": "M0630:L4",
        "queue_id": "M0630",
        "pmid": "35013114",
        "pre_iip0043_study_status": "existing_wave1_ceg_candidate_promoted_to_ring1_in_wave5",
        "pre_iip0043_prior_edge_ids": ["M0630:L1", "M0630:L2", "M0630:L3"],
        "expected_relation": "scoping_qualification",
        "expected_target_gate_or_module": "Gate0V-Kill / NW-18 (HeLa AP20187 mechanism hypothesis showing iCasp9 expression & XIAP/Caspase-3 drive escape; diagnostic probe only)",
        "expected_applicability": "unvalidated_transfer",
        "expected_cited_outcome_tuples": ["M0630:O13", "M0630:O14", "M0630:O15", "M0630:O17"],
        "previous_edge_state": "absent_pre_iip0043",
        "added_edge_status": "added_by_iip0043_scoping_non_certifying",
        "evidence_scope": "indirect_contextual_non_certifying",
        "contextual_scope_note": "Indirect contextual cross-link (primary_certification_eligible=false): HeLa AP20187 iCasp9/XIAP study provides diagnostic kill-variability context for Gate 0V-Kill.",
    },
    {
        "edge_id": "M0458:L3",
        "queue_id": "M0458",
        "pmid": "26258815",
        "pre_iip0043_study_status": "existing_wave1_ceg_candidate_promoted_to_ring1_in_wave5",
        "pre_iip0043_prior_edge_ids": ["M0458:L1", "M0458:L2"],
        "expected_relation": "supports",
        "expected_target_gate_or_module": "Layer 4 / NW-08 (external whole-prep clinical autoislet OCR/DNA group mean from M0458:O4, converted analytically via 10.4 ng DNA/IE)",
        "expected_applicability": "justified_bridge",
        "expected_cited_outcome_tuples": ["M0458:O4"],
        "previous_edge_state": "absent_pre_iip0043",
        "added_edge_status": "added_by_iip0043_scoping_non_certifying",
        "evidence_scope": "indirect_contextual_non_certifying",
        "contextual_scope_note": "Indirect contextual cross-link (primary_certification_eligible=false): whole autologous human islet OCR/DNA group mean provides prior respirometry context for NW-08.",
    },
    {
        "edge_id": "M0184:L4",
        "queue_id": "M0184",
        "pmid": "38956087",
        "pre_iip0043_study_status": "existing_wave1_ceg_candidate_promoted_to_ring1_in_wave5",
        "pre_iip0043_prior_edge_ids": ["M0184:L1", "M0184:L2", "M0184:L3"],
        "expected_relation": "supports",
        "expected_target_gate_or_module": "NW-08 & Gate 0V-Kill (CC-BY-4.0 human beta/alpha/ductal ER and cytokine stress regulon divergence)",
        "expected_applicability": "matched_domain",
        "expected_cited_outcome_tuples": ["M0184:O1", "M0184:O2", "M0184:O3", "M0184:O4"],
        "previous_edge_state": "absent_pre_iip0043",
        "added_edge_status": "added_by_iip0043_scoping_non_certifying",
        "evidence_scope": "indirect_contextual_non_certifying",
        "contextual_scope_note": "Indirect contextual cross-link (primary_certification_eligible=false): human islet ER/cytokine stress-response study provides stress-response context indirect to NW-08 and Gate 0V-Kill.",
    },
    {
        "edge_id": "M0066:L3",
        "queue_id": "M0066",
        "pmid": "41403780",
        "pre_iip0043_study_status": "existing_wave1_ceg_candidate_promoted_to_ring1_in_wave5",
        "pre_iip0043_prior_edge_ids": ["M0066:L1", "M0066:L2"],
        "expected_relation": "supports",
        "expected_target_gate_or_module": "Layer 1/3 & NW-08 (CC-BY-4.0 T3 humanized-mouse calibration of CD155/PVR & CD276/B7-H3 blockade on iPSC/EP grafts)",
        "expected_applicability": "justified_bridge",
        "expected_cited_outcome_tuples": ["M0066:O2", "M0066:O3", "M0066:O5"],
        "previous_edge_state": "absent_pre_iip0043",
        "added_edge_status": "added_by_iip0043_scoping_non_certifying",
        "evidence_scope": "indirect_contextual_non_certifying",
        "contextual_scope_note": "Indirect contextual cross-link (primary_certification_eligible=false): CD155/CD276 humanized-mouse study provides immune-engraftment context indirect to NW-08.",
    },
    {
        "edge_id": "R1_0287:L4",
        "queue_id": "R1_0287",
        "pmid": "39232561",
        "pre_iip0043_study_status": "pre_existing_ring1_and_wave1_ceg_study",
        "pre_iip0043_prior_edge_ids": ["R1_0287:L1", "R1_0287:L2", "R1_0287:L3"],
        "expected_relation": "supports",
        "expected_target_gate_or_module": "Gate0V / NW-18 & NW-08 (CC-BY-4.0 human VMI organoid vascular-macrophage beta-cell pyroptosis anchor)",
        "expected_applicability": "matched_domain",
        "expected_cited_outcome_tuples": ["R1_0287:O10", "R1_0287:O11", "R1_0287:O13"],
        "previous_edge_state": "absent_pre_iip0043",
        "added_edge_status": "added_by_iip0043_scoping_non_certifying",
        "evidence_scope": "indirect_contextual_non_certifying",
        "contextual_scope_note": "Indirect contextual cross-link (primary_certification_eligible=false): human vascularized macrophage-islet organoid study provides model-system context indirect to Gate 0V and NW-08.",
    },
    {
        "edge_id": "R1_0099:L3",
        "queue_id": "R1_0099",
        "pmid": "28000722",
        "pre_iip0043_study_status": "pre_existing_ring1_and_wave1_ceg_study",
        "pre_iip0043_prior_edge_ids": ["R1_0099:L1", "R1_0099:L2"],
        "expected_relation": "scoping_qualification",
        "expected_target_gate_or_module": "Gate0V-Geno / NW-18 (CC-BY-4.0 primary human islet IFIH1 rs1990760 TC vs TT IFN/ISG and 48-h CVB3 genotype contrast)",
        "expected_applicability": "matched_domain",
        "expected_cited_outcome_tuples": ["R1_0099:O11", "R1_0099:O12", "R1_0099:O15", "R1_0099:O16"],
        "previous_edge_state": "absent_pre_iip0043",
        "added_edge_status": "added_by_iip0043_scoping_non_certifying",
        "evidence_scope": "indirect_contextual_non_certifying",
        "contextual_scope_note": "Indirect contextual cross-link (primary_certification_eligible=false): human islet IFIH1 rs1990760 CVB3 genotype contrast provides antiviral genotype context for Gate 0V-Geno.",
    },
    {
        "edge_id": "R1_0095:L4",
        "queue_id": "R1_0095",
        "pmid": "27626039",
        "pre_iip0043_study_status": "pre_existing_ring1_and_wave1_ceg_study",
        "pre_iip0043_prior_edge_ids": ["R1_0095:L1", "R1_0095:L2", "R1_0095:L3"],
        "expected_relation": "scoping_qualification",
        "expected_target_gate_or_module": "Gate0V-Kill / NW-18 (hiPSC iCasp9 escape mechanism via silencing/EF1a methylation/BCL2; T5 cell line)",
        "expected_applicability": "unvalidated_transfer",
        "expected_cited_outcome_tuples": ["R1_0095:O2", "R1_0095:O4", "R1_0095:O7", "R1_0095:O12", "R1_0095:O13"],
        "previous_edge_state": "absent_pre_iip0043",
        "added_edge_status": "added_by_iip0043_scoping_non_certifying",
        "evidence_scope": "indirect_contextual_non_certifying",
        "contextual_scope_note": "Indirect contextual cross-link (primary_certification_eligible=false): hiPSC iCasp9 silencing/BCL2 escape study provides escape-risk context for Gate 0V-Kill.",
    },
)

# Tier-distinct PASS verdict codes carrying explicit tested-vs-inherited scope (B6)
GATE0V_PASS_VERDICTS_BY_TIER: Dict[str, str] = {
    "BANK_QUALIFICATION": "PASS_WHOLEGRAFT_BANK_QUALIFICATION",
    "LOT_RELEASE_SURROGATE": "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE",
    "AUTOLOGOUS_D1B_PROCESS_QUAL": "PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL",
}
GATE0V_ALL_PASS_VERDICTS = frozenset(GATE0V_PASS_VERDICTS_BY_TIER.values())

GATE0V_A_REQUIRED_ISG_MARKERS: Tuple[str, ...] = (
    "IFNB1_or_IFNL1_fold",
    "ISG15_fold",
    "MX1_fold",
    "OAS1_fold",
)

STRESS_AP1903_REGIMES: Tuple[str, ...] = (
    "normoxia_baseline",
    "hypoxia_1pct_plus_cytokines",
    "er_stress_tg_or_tm",
    "active_or_persistent_cvb4_infection",
    "active_or_persistent_hcmv_infection",
)

INFECTED_AP1903_REGIMES: Tuple[str, ...] = (
    "active_or_persistent_cvb4_infection",
    "active_or_persistent_hcmv_infection",
)

ALLOWED_ANTIVIRAL_GENOTYPES: Tuple[str, ...] = (
    "TYK2_WT__IFIH1_WT_OR_A946T",
    "TYK2_P1104A_HOM__IFIH1_WT",
    "TYK2_P1104A_HET__IFIH1_WT",
    "TYK2_WT__IFIH1_PROTECTIVE_LOF",
)

EDITED_ANTIVIRAL_GENOTYPES: Tuple[str, ...] = (
    "TYK2_P1104A_HOM__IFIH1_WT",
    "TYK2_P1104A_HET__IFIH1_WT",
    "TYK2_WT__IFIH1_PROTECTIVE_LOF",
)


def _is_public_bundle(openislet_root: Path) -> bool:
    """Detect public-export bundle mode cleanly via `.openislet_public_bundle` marker."""
    return (openislet_root / ".openislet_public_bundle").is_file()

# ---------------------------------------------------------------------------
# Pure Elementary Outward-Directed Taylor Interval Arithmetic (Zero .ln/.exp)
# ---------------------------------------------------------------------------
def _clean_dec_ctx(prec: int = 80, rounding: str = ROUND_CEILING):
    """Fresh Decimal context immune to active-context, DefaultContext, or Inexact traps."""
    return localcontext(
        Context(
            prec=prec,
            rounding=rounding,
            Emin=-999999,
            Emax=999999,
            capitals=1,
            clamp=0,
            flags=[],
            traps=[],
        )
    )


def _to_exact_decimal(val: Any) -> Decimal | None:
    """Strictly convert non-bool int/float/Decimal/str to finite Decimal without binary64 drift."""
    if isinstance(val, bool) or val is None:
        return None
    if isinstance(val, Decimal):
        return Decimal(val) if val.is_finite() else None
    if isinstance(val, int):
        return Decimal(val)
    if isinstance(val, float):
        if not math.isfinite(val):
            return None
        return Decimal(str(val))
    if isinstance(val, str):
        s = val.strip()
        if not s:
            return None
        try:
            with localcontext(
                Context(prec=120, rounding=ROUND_HALF_EVEN, Emax=decimal.MAX_EMAX, Emin=decimal.MIN_EMIN, traps=[])
            ):
                d = Decimal(s)
        except Exception:
            return None
        return d if d.is_finite() else None
    return None


def _to_exact_decimal_nonneg(val: Any) -> Decimal | None:
    """R12-B2 Strictly convert non-negative boundary scalar to finite Decimal, rejecting signed negative zero (`-0.0`)."""
    if _is_negative_zero(val):
        return None
    d = _to_exact_decimal(val)
    if d is None:
        return None
    with localcontext(
        Context(prec=120, rounding=ROUND_HALF_EVEN, Emax=decimal.MAX_EMAX, Emin=decimal.MIN_EMIN, traps=[])
    ):
        if d < Decimal(0):
            return None
    return d


def _is_strict_int(val: Any) -> bool:
    return isinstance(val, int) and not isinstance(val, bool)


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


def _is_valid_sha256_hex(val: Any) -> bool:
    return isinstance(val, str) and bool(_HEX64_RE.fullmatch(val)) and len(set(val)) > 1


def _is_valid_identifier(val: Any) -> bool:
    if not isinstance(val, str):
        return False
    s = val.strip()
    if not s or s != val:
        return False
    if _PLACEHOLDER_TOKEN_RE.search(s) or _FORBIDDEN_ID_CHARS_RE.search(s):
        return False
    return True


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


def _dec_to_float_pct(val: Decimal, ndigits: int = 6) -> float:
    """Convert Decimal fraction to percentage float completely inside an isolated untrapped context."""
    with _clean_dec_ctx(80, ROUND_HALF_EVEN):
        return round(float(val * Decimal(100)), ndigits)


def _dec_to_float(val: Decimal, ndigits: int = 6) -> float:
    """Convert Decimal to float completely inside an isolated untrapped context."""
    with _clean_dec_ctx(80, ROUND_HALF_EVEN):
        return round(float(+val), ndigits)


def _canonical_json_dumps(obj: Any) -> str:
    """
    R12-B2 Canonical compact RFC-8259 JSON serializer (`sort_keys=True`, `separators=(',', ':')`,
    `ensure_ascii=False`, `allow_nan=False`) supporting preserved exact `Decimal` boundary values
    deterministically without lossy float64 rounding or `TypeError`:
      - Losslessly float64-representable Decimals (`Decimal('1.097')`, `Decimal('1.0')`, `Decimal('0.0')`)
        emit the identical token to `json.dumps(float(d))` so existing canonical hashes remain invariant.
      - Signed negative zero (`Decimal('-0.0')`) emits `"-0.0"`.
      - Higher-precision Decimals (e.g. `Decimal('1.00000000000000001')`) emit exact finite JSON number
        literals (`1.00000000000000001`).
    """
    if isinstance(obj, dict):
        items: List[str] = []
        for k in sorted(obj.keys()):
            if not isinstance(k, str):
                raise TypeError(f"Canonical JSON object keys must be str, got {type(k).__name__}")
            items.append(f"{json.dumps(k, ensure_ascii=False)}:{_canonical_json_dumps(obj[k])}")
        return "{" + ",".join(items) + "}"
    if isinstance(obj, (list, tuple)):
        return "[" + ",".join(_canonical_json_dumps(x) for x in obj) + "]"
    if isinstance(obj, Decimal):
        with localcontext(
            Context(prec=120, rounding=ROUND_HALF_EVEN, Emax=decimal.MAX_EMAX, Emin=decimal.MIN_EMIN, traps=[])
        ):
            if not obj.is_finite():
                raise ValueError(f"Non-finite Decimal rejected in canonical JSON: {obj!r}")
            if obj == Decimal(0):
                return "-0.0" if obj.is_signed() else "0.0"
            try:
                fval = float(obj)
            except (OverflowError, ValueError):
                fval = math.nan
            if math.isfinite(fval) and fval != 0.0:
                f_str = json.dumps(fval, allow_nan=False)
                if Decimal(f_str) == obj:
                    return f_str
            return str(obj)
    return json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":"), allow_nan=False)


def compute_canonical_lot_sha256(payload: Dict[str, Any]) -> str:
    """Compute canonical SHA-256 digest of a measured-lot Gate 0V payload (excluding payload_sha256)."""
    body = {k: v for k, v in payload.items() if k != "payload_sha256"}
    canonical = _canonical_json_dumps(body)
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def _safe_canonical_lot_sha256(payload: Dict[str, Any]) -> str | None:
    """Return canonical SHA-256 or None if payload contains non-finite floats (NaN/Infinity), excessive depth, or non-JSON values."""
    try:
        return compute_canonical_lot_sha256(payload)
    except (TypeError, ValueError, OverflowError, RecursionError):
        return None


def build_reconciled_unit_partition(
    k: int,
    n: int,
    units_n: int = MIN_INDEPENDENT_BIOLOGICAL_UNITS_N,
    *,
    unit_prefix: str = "WELL",
) -> List[Dict[str, Any]]:
    """
    R12-B1 Deterministic balanced partition of binomial integer counts `(k, n)` across `units_n`
    independent biological units (`len == units_n`, each `n_u > 0`, `0 <= k_u <= n_u`, `sum(n_u) == n`,
    `sum(k_u) == k`). Used strictly for reference/test fixture generation; NEVER used by the evaluator
    to backfill omitted or mismatched operator partitions!
    """
    if not (_is_strict_int(units_n) and units_n >= 1):
        raise ValueError(f"units_n must be a positive int, got {units_n!r}")
    if not (_is_strict_int(n) and n >= units_n and _is_strict_int(k) and 0 <= k <= n):
        raise ValueError(f"Cannot partition (k={k!r}, n={n!r}) across {units_n} positive-denominator units")
    base_n, rem_n = divmod(n, units_n)
    n_parts = [base_n + (1 if idx < rem_n else 0) for idx in range(units_n)]
    k_parts = [0] * units_n
    rem_k = k
    for idx in range(units_n):
        if rem_k <= 0:
            break
        share = min(n_parts[idx], (rem_k + (units_n - idx) - 1) // (units_n - idx))
        k_parts[idx] = share
        rem_k -= share
    for idx in range(units_n):
        if rem_k <= 0:
            break
        room = n_parts[idx] - k_parts[idx]
        if room > 0:
            add = min(room, rem_k)
            k_parts[idx] += add
            rem_k -= add
    return [
        {"unit_id": f"{unit_prefix}-{idx + 1:02d}", "k": k_parts[idx], "n": n_parts[idx]}
        for idx in range(units_n)
    ]


def _build_subset_unit_partition(
    k_sub: int,
    parent_part: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
    """
    R13-B2 Deterministic synchronized subset partition of integer `k_sub` across the exact same
    `unit_id`s and `n_u` denominators as `parent_part`, guaranteeing `0 <= k_sub_u <= parent_k_u <= n_u`
    on EVERY individual unit and `sum(k_sub_u) == k_sub`. Used strictly by test/fixture generation.
    """
    cap_list = [int(p["k"]) for p in parent_part]
    cap_tot = sum(cap_list)
    if not (_is_strict_int(k_sub) and 0 <= k_sub <= cap_tot):
        raise ValueError(f"Cannot partition subset k_sub={k_sub!r} within parent capacity {cap_tot!r}")
    if k_sub == 0 or cap_tot == 0:
        return [
            {"unit_id": p["unit_id"], "k": 0, "n": int(p["n"])}
            for p in parent_part
        ]
    k_parts = [(k_sub * c) // cap_tot for c in cap_list]
    rem = k_sub - sum(k_parts)
    if rem > 0:
        order = sorted(
            range(len(parent_part)),
            key=lambda i: (-((k_sub * cap_list[i]) % cap_tot), i),
        )
        for idx in order:
            if rem <= 0:
                break
            if k_parts[idx] < cap_list[idx]:
                k_parts[idx] += 1
                rem -= 1
    return [
        {"unit_id": parent_part[i]["unit_id"], "k": k_parts[i], "n": int(parent_part[i]["n"])}
        for i in range(len(parent_part))
    ]


def reconcile_fixture_per_unit_counts(
    payload: Dict[str, Any],
    units_n: int | None = None,
) -> Dict[str, Any]:
    """
    R12-B1 + R13-B2 Test/fixture utility that rebuilds matching `per_unit_counts` across valid
    integer count fields on a mutated synthetic Gate-0V fixture (NEVER invoked by the production
    evaluator!), guaranteeing synchronized same-unit IDs and within-unit subset inequalities
    (`direct_infected_veh_72h <= veh_72h` and `infected_viral_pos_72h <= ap1903_72h`).
    """
    if not isinstance(payload, dict):
        return payload
    clust = payload.get("clustering_and_independence_spec")
    u_n = units_n
    if u_n is None and isinstance(clust, dict) and _is_strict_int(clust.get("independent_biological_units_n")):
        u_n = int(clust["independent_biological_units_n"])
    if not (_is_strict_int(u_n) and u_n >= 1):
        u_n = MIN_INDEPENDENT_BIOLOGICAL_UNITS_N

    def _try_part(k_val: Any, n_val: Any) -> List[Dict[str, Any]] | None:
        if _is_strict_int(k_val) and _is_strict_int(n_val) and n_val >= u_n and 0 <= k_val <= n_val:
            return build_reconciled_unit_partition(k_val, n_val, u_n)
        return None

    inf = payload.get("gate0v_b_infectious_challenge")
    if isinstance(inf, dict) and isinstance(inf.get("pathogens"), dict):
        for pb in inf["pathogens"].values():
            if not isinstance(pb, dict):
                continue
            lat = pb.get("day28_latent_and_defective_genome_arm")
            if isinstance(lat, dict):
                lp = _try_part(lat.get("ddpcr_positive_events_k"), lat.get("ddpcr_cell_equivalents_screened_n"))
                if lp is not None:
                    lat["per_unit_counts"] = lp
                tgts = lat.get("ddpcr_targets")
                if isinstance(tgts, dict):
                    for te in tgts.values():
                        if isinstance(te, dict):
                            tp = _try_part(te.get("k"), te.get("n"))
                            if tp is not None:
                                te["per_unit_counts"] = tp
            lin_map = pb.get("day28_persistence_by_lineage")
            if isinstance(lin_map, dict):
                for le in lin_map.values():
                    if isinstance(le, dict):
                        ep = _try_part(le.get("stage2_confirmed_infectious_k"), le.get("cells_scored_n"))
                        if ep is not None:
                            le["per_unit_counts"] = ep
                        uc_p = _try_part(le.get("uninfected_ctrl_fp_k"), le.get("uninfected_ctrl_scored_n"))
                        if uc_p is not None:
                            le["uninfected_ctrl_per_unit_counts"] = uc_p
                        sc_p = _try_part(le.get("spike_calibrant_detected_k"), le.get("spike_calibrant_total_n"))
                        if sc_p is not None:
                            le["spike_calibrant_per_unit_counts"] = sc_p
                        fsc_p = _try_part(
                            le.get("fragile_infected_spike_detected_k"),
                            le.get("fragile_infected_spike_total_n"),
                        )
                        if fsc_p is not None:
                            le["fragile_infected_spike_per_unit_counts"] = fsc_p

    cd46 = payload.get("cd46_tropic_viral_addendum")
    if isinstance(cd46, dict):
        for vid in CD46_ADDENDUM_VIRUSES:
            vb = cd46.get(vid)
            if isinstance(vb, dict):
                vp = _try_part(vb.get("day28_5lineage_ddpcr_confirmed_k"), vb.get("day28_5lineage_cells_screened_per_lineage_min_n"))
                if vp is not None:
                    vb["per_unit_counts"] = vp

    cd55 = payload.get("cd55_tropic_echovirus_addendum")
    if isinstance(cd55, dict) and isinstance(cd55.get("strain_results"), dict):
        for sb in cd55["strain_results"].values():
            if isinstance(sb, dict) and isinstance(sb.get("day28_persistence_by_lineage"), dict):
                for le in sb["day28_persistence_by_lineage"].values():
                    if isinstance(le, dict):
                        ep = _try_part(le.get("confirmed_k"), le.get("cells_screened_n"))
                        if ep is not None:
                            le["per_unit_counts"] = ep

    ap = payload.get("gate0v_kill_stress_ap1903")
    if isinstance(ap, dict):
        for reg, rb in ap.items():
            if not isinstance(rb, dict):
                continue
            for lb in rb.values():
                if not isinstance(lb, dict):
                    continue
                puc: Dict[str, Any] = {}
                for k_name, k_key, n_key in (
                    ("veh_24h", "veh_24h_viable_n", "veh_24h_input_n"),
                    ("ap1903_24h", "ap1903_24h_viable_survivors_k", "ap1903_24h_input_n"),
                    ("veh_72h", "veh_72h_viable_n", "veh_72h_input_n"),
                    ("ap1903_72h", "ap1903_72h_viable_survivors_k", "ap1903_72h_input_n"),
                ):
                    pt = _try_part(lb.get(k_key), lb.get(n_key))
                    if pt is not None:
                        puc[k_name] = pt
                if reg in INFECTED_AP1903_REGIMES:
                    vk_v = lb.get("post_ap1903_viable_viral_pos_k")
                    n_in_v = lb.get("pre_ap1903_lineage_input_cells_n")
                    a72_part = puc.get("ap1903_72h")
                    if (
                        a72_part is not None
                        and _is_strict_int(vk_v)
                        and _is_strict_int(n_in_v)
                        and n_in_v == lb.get("ap1903_72h_input_n")
                        and 0 <= vk_v <= sum(int(p["k"]) for p in a72_part)
                    ):
                        puc["infected_viral_pos_72h"] = _build_subset_unit_partition(vk_v, a72_part)
                    else:
                        pt_vp = _try_part(vk_v, n_in_v)
                        if pt_vp is not None:
                            puc["infected_viral_pos_72h"] = pt_vp
                    div_k = lb.get("pretreat_infected_veh_survivor_n")
                    if div_k is not None:
                        v72_part = puc.get("veh_72h")
                        if (
                            v72_part is not None
                            and _is_strict_int(div_k)
                            and 0 <= div_k <= sum(int(p["k"]) for p in v72_part)
                        ):
                            puc["direct_infected_veh_72h"] = _build_subset_unit_partition(div_k, v72_part)
                        else:
                            pt_div = _try_part(div_k, lb.get("veh_72h_input_n"))
                            if pt_div is not None:
                                puc["direct_infected_veh_72h"] = pt_div
                    pt_sc = _try_part(lb.get("spike_calibrant_detected_k"), lb.get("spike_calibrant_total_n"))
                    if pt_sc is not None:
                        puc["spike_calibrant"] = pt_sc
                    pt_fsc = _try_part(
                        lb.get("fragile_infected_spike_detected_k"),
                        lb.get("fragile_infected_spike_total_n"),
                    )
                    if pt_fsc is not None:
                        puc["fragile_infected_spike_calibrant"] = pt_fsc
                if puc:
                    lb["per_unit_counts"] = puc
    return payload


def _inspect_per_unit_counts(
    raw_partition: Any,
    *,
    expected_units_n: int | None,
    expected_k: int | None,
    expected_n: int | None,
) -> Dict[str, Any]:
    """
    R12-B1 + R13-B1 + R13-B2 Exhaustive zero-early-return validator and adverse-row scanner for
    per-estimand `per_unit_counts`:
      - NEVER early-returns on a malformed row (`NON_DICT_UNIT_ENTRY`, `INVALID_UNIT_ID`,
        `INVALID_UNIT_DICT_ENTRY`, `DUPLICATE_UNIT_ID`, etc.): collects ALL schema errors AND scans
        EVERY interpretable dict row in the collection regardless of row-ID validity.
      - Tracks `any_pos_k`, `any_k_gt_n`, `sum_interp_k`, `sum_interp_n`, `interpretable_rows_n`,
        and canonical `unit_map: {unit_id: (k_u, n_u)}` for cross-estimand same-unit reconciliation.
      - Enforces `expected_units_n >= MIN_INDEPENDENT_BIOLOGICAL_UNITS_N (6)`, `len == expected_units_n`,
        unique valid `unit_id`s, strict ints `n_u > 0` and `0 <= k_u <= n_u`, and exact arithmetic
        reconciliation `sum(n_u) == expected_n` AND `sum(k_u) == expected_k`.
    """
    any_pos_k = False
    any_k_gt_n = False
    sum_interp_k = 0
    sum_interp_n = 0
    interpretable_rows_n = 0
    sum_valid_k = 0
    sum_valid_n = 0
    errors: List[str] = []
    seen_uids: set[str] = set()
    unit_map: Dict[str, Tuple[int, int]] = {}
    total_rows = 0

    def _add_err(code: str) -> None:
        if code not in errors:
            errors.append(code)

    raw_items: List[Tuple[Any, Any, bool]] = []
    if isinstance(raw_partition, list):
        total_rows = len(raw_partition)
        for item in raw_partition:
            if not isinstance(item, dict):
                _add_err("NON_DICT_UNIT_ENTRY")
                continue
            raw_items.append((item.get("unit_id"), item, True))
    elif isinstance(raw_partition, dict):
        total_rows = len(raw_partition)
        for uid, item in raw_partition.items():
            if not isinstance(item, dict):
                _add_err("INVALID_UNIT_DICT_ENTRY")
                continue
            raw_items.append((uid, item, False))
    else:
        return {
            "reconciled_ok": False,
            "any_pos_k": False,
            "any_k_gt_n": False,
            "sum_interp_k": 0,
            "sum_interp_n": 0,
            "interpretable_rows_n": 0,
            "reason_code": "MISSING_OR_NON_COLLECTION_PER_UNIT_COUNTS",
            "all_errors": ["MISSING_OR_NON_COLLECTION_PER_UNIT_COUNTS"],
            "unit_map": {},
        }

    for uid, item, is_list_entry in raw_items:
        k_u = item.get("k")
        n_u = item.get("n")
        k_is_int = _is_strict_int(k_u)
        n_is_int = _is_strict_int(n_u)
        if k_is_int or n_is_int:
            interpretable_rows_n += 1
        if k_is_int:
            if k_u >= 1:
                any_pos_k = True
            if k_u >= 0:
                sum_interp_k += int(k_u)
        if n_is_int and n_u >= 0:
            sum_interp_n += int(n_u)
        if k_is_int and n_is_int and n_u >= 0 and k_u > n_u:
            any_k_gt_n = True

        uid_ok = _is_valid_identifier(uid)
        if not uid_ok:
            _add_err("INVALID_UNIT_ID" if is_list_entry else "INVALID_UNIT_DICT_ENTRY")
        elif uid in seen_uids:
            _add_err("DUPLICATE_UNIT_ID")
            uid_ok = False
        else:
            seen_uids.add(uid)

        counts_ok = bool(k_is_int and n_is_int and n_u > 0 and 0 <= k_u <= n_u)
        if not counts_ok:
            _add_err("INVALID_UNIT_COUNT_DOMAIN")
        elif uid_ok:
            sum_valid_k += int(k_u)
            sum_valid_n += int(n_u)
            unit_map[str(uid)] = (int(k_u), int(n_u))

    if not (_is_strict_int(expected_units_n) and expected_units_n >= MIN_INDEPENDENT_BIOLOGICAL_UNITS_N):
        _add_err("INSUFFICIENT_INDEPENDENT_BIOLOGICAL_UNITS")
    elif total_rows != expected_units_n or len(unit_map) != expected_units_n:
        if not errors:
            _add_err("UNIT_COUNT_LENGTH_MISMATCH")

    if not (_is_strict_int(expected_k) and _is_strict_int(expected_n) and expected_n >= 1 and 0 <= expected_k <= expected_n):
        _add_err("INVALID_AGGREGATE_COUNTS")
    elif not errors and (sum_valid_n != expected_n or sum_valid_k != expected_k):
        _add_err("UNIT_SUM_MISMATCH")

    reconciled_ok = len(errors) == 0
    return {
        "reconciled_ok": reconciled_ok,
        "any_pos_k": any_pos_k,
        "any_k_gt_n": any_k_gt_n,
        "sum_interp_k": sum_interp_k,
        "sum_interp_n": sum_interp_n,
        "interpretable_rows_n": interpretable_rows_n,
        "reason_code": "OK" if reconciled_ok else errors[0],
        "all_errors": errors,
        "unit_map": unit_map,
    }


def _validate_per_unit_counts(
    raw_partition: Any,
    *,
    expected_units_n: int | None,
    expected_k: int | None,
    expected_n: int | None,
) -> Tuple[bool, bool, str]:
    """Backwards-compatible 3-tuple wrapper around `_inspect_per_unit_counts` (zero early returns)."""
    info = _inspect_per_unit_counts(
        raw_partition,
        expected_units_n=expected_units_n,
        expected_k=expected_k,
        expected_n=expected_n,
    )
    return bool(info["reconciled_ok"]), bool(info["any_pos_k"]), str(info["reason_code"])


def _scan_all_submitted_per_unit_counts_adverse(
    payload: Any,
    *,
    raw_deff_dec: Decimal | None,
    hard_stops: List[str],
    required_kill_regimes: Tuple[str, ...] = (),
) -> Dict[str, Any]:
    """
    R13-B1 Dedicated pre-schema adverse `per_unit_counts` scanner executed BEFORE any sampling-class,
    required-vs-supplemental, or row-ID schema early return:
      - Scans EVERY arm (required AND supplemental stress regimes, pathogen arms, latent ddPCR arms
        and targets, CD46/CD55 addenda, extra lineages/strains/targets, plus a whole-payload sweep)
        in BOTH single-cell AND multi-well modes (and even when `clustering_and_independence_spec`
        is missing or invalid!).
      - On post-AP1903 viral-positive escape (`infected_viral_pos_72h` / `post_ap1903_*viral_pos*`):
        ANY interpretable unit dict row with `k >= 1` immediately records deterministic biological
        `FAIL_HARD_STOP` (`HARD_STOP_ADVERSE_PER_UNIT_POST_AP1903_VIRAL_ESCAPE`).
      - On any zero-tolerance viral persistence estimand (Gate 0V-B, latent ddPCR, CD46, CD55):
        ANY interpretable unit dict row with `k >= 1` immediately records deterministic biological
        `FAIL_HARD_STOP` (`HARD_STOP_ADVERSE_PER_UNIT_VIRAL_PERSISTENCE`).
      - On any `per_unit_counts` estimand with `k_u > n_u` OR any adverse-event estimand where
        interpretable unit rows sum to `k > declared aggregate k` (e.g., unit reports positive
        survivor while aggregate claims `0`) OR where AP1903 24h/72h unit counts conclusively breach
        the kill floor at `deff == 1.0`, immediately records deterministic `FAIL_HARD_STOP`
        (`HARD_STOP_ADVERSE_PER_UNIT_CONTRADICTS_AGGREGATE_OR_BREACHES_KILL_FLOOR`).
      - Reports `any_per_unit_counts_present` so single-cell mode (`INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT`)
        can fail closed on ANY submitted `per_unit_counts` (`HOLD_UNEXPECTED_PER_UNIT_COUNTS_IN_SINGLE_CELL_MODE`).
    """
    any_puc_present = False
    visited_containers: set[int] = set()

    def _append_hs(tok: str) -> None:
        if tok not in hard_stops:
            hard_stops.append(tok)

    def _check_part(
        raw_part: Any,
        *,
        expected_k: Any,
        expected_n: Any,
        zero_tol: bool,
        zt_tokens: Tuple[str, ...] = (),
        check_agg_exceed: bool = False,
        ap1903_cap: Decimal | None = None,
        kill_cap_token: str | None = None,
    ) -> None:
        info = _inspect_per_unit_counts(
            raw_part,
            expected_units_n=None,
            expected_k=expected_k if _is_strict_int(expected_k) else None,
            expected_n=expected_n if _is_strict_int(expected_n) else None,
        )
        if zero_tol and info["any_pos_k"]:
            for tok in zt_tokens:
                _append_hs(tok)
        if info["any_k_gt_n"]:
            _append_hs("HARD_STOP_ADVERSE_PER_UNIT_CONTRADICTS_AGGREGATE_OR_BREACHES_KILL_FLOOR")
        if (
            check_agg_exceed
            and info["interpretable_rows_n"] > 0
            and _is_strict_int(expected_k)
            and info["sum_interp_k"] > int(expected_k)
        ):
            _append_hs("HARD_STOP_ADVERSE_PER_UNIT_CONTRADICTS_AGGREGATE_OR_BREACHES_KILL_FLOOR")
        if ap1903_cap is not None and info["sum_interp_k"] >= 1:
            den_n = max(
                int(info["sum_interp_n"]),
                int(expected_n) if (_is_strict_int(expected_n) and int(expected_n) >= 1) else 0,
            )
            if den_n >= 1:
                if int(info["sum_interp_k"]) > den_n:
                    _append_hs("HARD_STOP_ADVERSE_PER_UNIT_CONTRADICTS_AGGREGATE_OR_BREACHES_KILL_FLOOR")
                elif raw_deff_dec == Decimal("1.0"):
                    l_ideal = exact_clopper_pearson_lower_calibrant(
                        int(info["sum_interp_k"]), den_n, Decimal("0.025"), prec=60
                    )
                    if l_ideal > ap1903_cap:
                        _append_hs("HARD_STOP_ADVERSE_PER_UNIT_CONTRADICTS_AGGREGATE_OR_BREACHES_KILL_FLOOR")
                        if kill_cap_token:
                            _append_hs(kill_cap_token)

    if not isinstance(payload, dict):
        return {"any_per_unit_counts_present": False}

    # 1. Gate 0V-Kill (ALL stress regimes — required, supplemental, and unrecognized; ALL lineages!)
    ap = payload.get("gate0v_kill_stress_ap1903")
    if isinstance(ap, dict):
        for reg, rb in ap.items():
            if not isinstance(rb, dict):
                continue
            is_sup = bool(required_kill_regimes and reg not in required_kill_regimes)
            sup_hs = "SUPPLEMENTAL_" if is_sup else ""
            reg_tag = str(reg).upper()
            for lin, lb in rb.items():
                if not isinstance(lb, dict) or "per_unit_counts" not in lb:
                    continue
                any_puc_present = True
                visited_containers.add(id(lb))
                lin_tag = str(lin).upper()
                puc = lb.get("per_unit_counts")
                if isinstance(puc, dict):
                    for sub_k, sub_raw in puc.items():
                        sk_low = str(sub_k).lower()
                        if sub_k == "veh_24h":
                            _check_part(
                                sub_raw,
                                expected_k=lb.get("veh_24h_viable_n"),
                                expected_n=lb.get("veh_24h_input_n"),
                                zero_tol=False,
                                check_agg_exceed=False,
                            )
                        elif sub_k == "veh_72h":
                            _check_part(
                                sub_raw,
                                expected_k=lb.get("veh_72h_viable_n"),
                                expected_n=lb.get("veh_72h_input_n"),
                                zero_tol=False,
                                check_agg_exceed=False,
                            )
                        elif sub_k == "direct_infected_veh_72h":
                            _check_part(
                                sub_raw,
                                expected_k=lb.get("pretreat_infected_veh_survivor_n"),
                                expected_n=lb.get("veh_72h_input_n"),
                                zero_tol=False,
                                check_agg_exceed=False,
                            )
                        elif sub_k == "spike_calibrant":
                            _check_part(
                                sub_raw,
                                expected_k=lb.get("spike_calibrant_detected_k"),
                                expected_n=lb.get("spike_calibrant_total_n"),
                                zero_tol=False,
                                check_agg_exceed=False,
                            )
                        elif sub_k == "fragile_infected_spike_calibrant":
                            _check_part(
                                sub_raw,
                                expected_k=lb.get("fragile_infected_spike_detected_k"),
                                expected_n=lb.get("fragile_infected_spike_total_n"),
                                zero_tol=False,
                                check_agg_exceed=False,
                            )
                        elif sub_k == "ap1903_24h":
                            _check_part(
                                sub_raw,
                                expected_k=lb.get("ap1903_24h_viable_survivors_k"),
                                expected_n=lb.get("ap1903_24h_input_n"),
                                zero_tol=False,
                                check_agg_exceed=True,
                                ap1903_cap=Decimal("0.001"),
                                kill_cap_token=f"FAIL_HARD_STOP_{sup_hs}AP1903_24H_KILL_BELOW_99P9PCT_{reg_tag}_{lin_tag}",
                            )
                        elif sub_k == "ap1903_72h":
                            _check_part(
                                sub_raw,
                                expected_k=lb.get("ap1903_72h_viable_survivors_k"),
                                expected_n=lb.get("ap1903_72h_input_n"),
                                zero_tol=False,
                                check_agg_exceed=True,
                                ap1903_cap=Decimal("0.0001"),
                                kill_cap_token=f"FAIL_HARD_STOP_{sup_hs}AP1903_72H_PK_KILL_BELOW_4LOG10_{reg_tag}_{lin_tag}",
                            )
                        elif (
                            sub_k == "infected_viral_pos_72h"
                            or "viral_pos" in sk_low
                            or "post_ap1903_viral" in sk_low
                            or "viral_escape" in sk_low
                        ):
                            _check_part(
                                sub_raw,
                                expected_k=lb.get("post_ap1903_viable_viral_pos_k"),
                                expected_n=lb.get("pre_ap1903_lineage_input_cells_n"),
                                zero_tol=True,
                                zt_tokens=(
                                    "HARD_STOP_ADVERSE_PER_UNIT_POST_AP1903_VIRAL_ESCAPE",
                                    f"FAIL_HARD_STOP_{sup_hs}POST_AP1903_VIABLE_VIRAL_SURVIVOR_{reg_tag}_{lin_tag}",
                                ),
                                check_agg_exceed=True,
                            )
                        else:
                            # Unknown extra sub-key inside Gate 0V-Kill per_unit_counts
                            is_viral_extra = ("viral" in sk_low) or ("escape" in sk_low)
                            _check_part(
                                sub_raw,
                                expected_k=0 if is_viral_extra else None,
                                expected_n=None,
                                zero_tol=is_viral_extra,
                                zt_tokens=(
                                    "HARD_STOP_ADVERSE_PER_UNIT_POST_AP1903_VIRAL_ESCAPE",
                                    f"FAIL_HARD_STOP_{sup_hs}POST_AP1903_VIABLE_VIRAL_SURVIVOR_{reg_tag}_{lin_tag}",
                                ) if is_viral_extra else (),
                                check_agg_exceed=is_viral_extra,
                            )
                elif isinstance(puc, list):
                    # Flat list directly under lblock["per_unit_counts"]
                    info_flat = _inspect_per_unit_counts(puc, expected_units_n=None, expected_k=None, expected_n=None)
                    if info_flat["any_k_gt_n"]:
                        _append_hs("HARD_STOP_ADVERSE_PER_UNIT_CONTRADICTS_AGGREGATE_OR_BREACHES_KILL_FLOOR")
                    if (
                        info_flat["any_pos_k"]
                        and lb.get("ap1903_24h_viable_survivors_k") == 0
                        and lb.get("ap1903_72h_viable_survivors_k") == 0
                        and lb.get("post_ap1903_viable_viral_pos_k", 0) == 0
                    ):
                        _append_hs("HARD_STOP_ADVERSE_PER_UNIT_CONTRADICTS_AGGREGATE_OR_BREACHES_KILL_FLOOR")

    # 2. Gate 0V-B pathogens (ALL pathogens — required, supplemental, and unrecognized; ALL lineages & targets!)
    inf = payload.get("gate0v_b_infectious_challenge")
    if isinstance(inf, dict) and isinstance(inf.get("pathogens"), dict):
        for pid, pb in inf["pathogens"].items():
            if not isinstance(pb, dict):
                continue
            p_tag = str(pid).upper()
            lat = pb.get("day28_latent_and_defective_genome_arm")
            if isinstance(lat, dict):
                if "per_unit_counts" in lat:
                    any_puc_present = True
                    visited_containers.add(id(lat))
                    _check_part(
                        lat.get("per_unit_counts"),
                        expected_k=lat.get("ddpcr_positive_events_k"),
                        expected_n=lat.get("ddpcr_cell_equivalents_screened_n"),
                        zero_tol=True,
                        zt_tokens=(
                            "HARD_STOP_ADVERSE_PER_UNIT_VIRAL_PERSISTENCE",
                            f"FAIL_HARD_STOP_GATE0V_B_LATENT_OR_DEFECTIVE_GENOME_DETECTED_{p_tag}_K_UNIT_POS",
                        ),
                        check_agg_exceed=True,
                    )
                tgts = lat.get("ddpcr_targets")
                if isinstance(tgts, dict):
                    for tname, te in tgts.items():
                        if isinstance(te, dict) and "per_unit_counts" in te:
                            any_puc_present = True
                            visited_containers.add(id(te))
                            t_tag = str(tname).upper()
                            _check_part(
                                te.get("per_unit_counts"),
                                expected_k=te.get("k"),
                                expected_n=te.get("n"),
                                zero_tol=True,
                                zt_tokens=(
                                    "HARD_STOP_ADVERSE_PER_UNIT_VIRAL_PERSISTENCE",
                                    f"FAIL_HARD_STOP_GATE0V_B_LATENT_OR_DEFECTIVE_GENOME_DETECTED_{p_tag}_{t_tag}_K_UNIT_POS",
                                ),
                                check_agg_exceed=True,
                            )
            unass = pb.get("unassigned_fraction_viral_readout")
            if isinstance(unass, dict) and "per_unit_counts" in unass:
                any_puc_present = True
                visited_containers.add(id(unass))
                _check_part(
                    unass.get("per_unit_counts"),
                    expected_k=unass.get("stage2_confirmed_infectious_k"),
                    expected_n=unass.get("unassigned_cells_screened_n"),
                    zero_tol=True,
                    zt_tokens=(
                        "HARD_STOP_ADVERSE_PER_UNIT_VIRAL_PERSISTENCE",
                        f"FAIL_HARD_STOP_GATE0V_CONFIRMED_VIRAL_POSITIVE_UNASSIGNED_{p_tag}_K_UNIT_POS",
                    ),
                    check_agg_exceed=True,
                )
            lin_map = pb.get("day28_persistence_by_lineage")
            if isinstance(lin_map, dict):
                for lin_name, le in lin_map.items():
                    if not isinstance(le, dict):
                        continue
                    l_tag = str(lin_name).upper()
                    if "per_unit_counts" in le:
                        any_puc_present = True
                        visited_containers.add(id(le))
                        _check_part(
                            le.get("per_unit_counts"),
                            expected_k=le.get("stage2_confirmed_infectious_k"),
                            expected_n=le.get("cells_scored_n"),
                            zero_tol=True,
                            zt_tokens=(
                                "HARD_STOP_ADVERSE_PER_UNIT_VIRAL_PERSISTENCE",
                                f"FAIL_HARD_STOP_GATE0V_CONFIRMED_VIRAL_POSITIVE_{p_tag}_{l_tag}_K_UNIT_POS",
                            ),
                            check_agg_exceed=True,
                        )
                    for aux_puc_key, aux_k_key, aux_n_key in (
                        ("uninfected_ctrl_per_unit_counts", "uninfected_ctrl_fp_k", "uninfected_ctrl_scored_n"),
                        ("spike_calibrant_per_unit_counts", "spike_calibrant_detected_k", "spike_calibrant_total_n"),
                        (
                            "fragile_infected_spike_per_unit_counts",
                            "fragile_infected_spike_detected_k",
                            "fragile_infected_spike_total_n",
                        ),
                    ):
                        if aux_puc_key in le:
                            any_puc_present = True
                            visited_containers.add(id(le))
                            _check_part(
                                le.get(aux_puc_key),
                                expected_k=le.get(aux_k_key),
                                expected_n=le.get(aux_n_key),
                                zero_tol=False,
                                check_agg_exceed=False,
                            )

    # 3. CD46 addendum (ALL submitted virus blocks, required or supplemental!)
    cd46 = payload.get("cd46_tropic_viral_addendum")
    if isinstance(cd46, dict):
        for vid, vb in cd46.items():
            if isinstance(vb, dict) and "per_unit_counts" in vb:
                any_puc_present = True
                visited_containers.add(id(vb))
                v_tag = str(vid).upper()
                _check_part(
                    vb.get("per_unit_counts"),
                    expected_k=vb.get("day28_5lineage_ddpcr_confirmed_k"),
                    expected_n=vb.get("day28_5lineage_cells_screened_per_lineage_min_n"),
                    zero_tol=True,
                    zt_tokens=(
                        "HARD_STOP_ADVERSE_PER_UNIT_VIRAL_PERSISTENCE",
                        f"FAIL_HARD_STOP_CD46_ADDENDUM_CONFIRMED_PERSISTENCE_{v_tag}",
                    ),
                    check_agg_exceed=True,
                )

    # 4. CD55 echovirus addendum (top-level AND ALL strains x ALL lineages, required or supplemental!)
    cd55 = payload.get("cd55_tropic_echovirus_addendum")
    if isinstance(cd55, dict):
        if "per_unit_counts" in cd55:
            any_puc_present = True
            visited_containers.add(id(cd55))
            _check_part(
                cd55.get("per_unit_counts"),
                expected_k=cd55.get("echovirus_persistence_confirmed_k"),
                expected_n=cd55.get("echovirus_cells_screened_per_lineage_min_n"),
                zero_tol=True,
                zt_tokens=(
                    "HARD_STOP_ADVERSE_PER_UNIT_VIRAL_PERSISTENCE",
                    "FAIL_HARD_STOP_CD55_ECHOVIRUS_PERSISTENCE_DETECTED",
                ),
                check_agg_exceed=True,
            )
        sr = cd55.get("strain_results")
        if isinstance(sr, dict):
            for sid, sb in sr.items():
                if not isinstance(sb, dict):
                    continue
                s_tag = str(sid).upper()
                if "per_unit_counts" in sb:
                    any_puc_present = True
                    visited_containers.add(id(sb))
                    _check_part(
                        sb.get("per_unit_counts"),
                        expected_k=0,
                        expected_n=None,
                        zero_tol=True,
                        zt_tokens=(
                            "HARD_STOP_ADVERSE_PER_UNIT_VIRAL_PERSISTENCE",
                            f"FAIL_HARD_STOP_CD55_ECHOVIRUS_PERSISTENCE_DETECTED_{s_tag}_K_UNIT_POS",
                        ),
                        check_agg_exceed=True,
                    )
                lm = sb.get("day28_persistence_by_lineage")
                if isinstance(lm, dict):
                    for lin_name, le in lm.items():
                        if isinstance(le, dict) and "per_unit_counts" in le:
                            any_puc_present = True
                            visited_containers.add(id(le))
                            l_tag = str(lin_name).upper()
                            _check_part(
                                le.get("per_unit_counts"),
                                expected_k=le.get("confirmed_k"),
                                expected_n=le.get("cells_screened_n"),
                                zero_tol=True,
                                zt_tokens=(
                                    "HARD_STOP_ADVERSE_PER_UNIT_VIRAL_PERSISTENCE",
                                    f"FAIL_HARD_STOP_CD55_ECHOVIRUS_PERSISTENCE_DETECTED_{s_tag}_{l_tag}_K_UNIT_POS",
                                ),
                                check_agg_exceed=True,
                            )

    # 5. Iterative whole-payload sweep for any uncovered `per_unit_counts` key anywhere in payload
    stack: List[Any] = [payload]
    seen_walk: set[int] = set()
    while stack:
        cur = stack.pop()
        cid = id(cur)
        if cid in seen_walk:
            continue
        seen_walk.add(cid)
        if isinstance(cur, dict):
            if cid not in visited_containers:
                for cur_k, raw_unc in cur.items():
                    if cur_k == "per_unit_counts" or (isinstance(cur_k, str) and cur_k.endswith("_per_unit_counts")):
                        any_puc_present = True
                        if isinstance(raw_unc, dict):
                            for uk, uv in raw_unc.items():
                                uk_low = str(uk).lower()
                                is_v = ("viral" in uk_low) or ("escape" in uk_low)
                                _check_part(
                                    uv,
                                    expected_k=0 if is_v else None,
                                    expected_n=None,
                                    zero_tol=is_v,
                                    zt_tokens=("HARD_STOP_ADVERSE_PER_UNIT_POST_AP1903_VIRAL_ESCAPE",) if is_v else (),
                                    check_agg_exceed=is_v,
                                )
                        else:
                            _check_part(raw_unc, expected_k=None, expected_n=None, zero_tol=False, check_agg_exceed=False)
            for v in cur.values():
                if isinstance(v, (dict, list)):
                    stack.append(v)
        elif isinstance(cur, list):
            for item in cur:
                if isinstance(item, (dict, list)):
                    stack.append(item)

    return {"any_per_unit_counts_present": any_puc_present}


def _fraction_to_outward_dec(y_frac: Fraction, sig_digits: int) -> Tuple[Decimal, Decimal]:
    """
    Exact integer-long-division outward bracket [y_lo, y_hi] for rational y_frac > 0
    with at least sig_digits significant digits at ANY exponent scale (including 10^-200).
    Guarantees: 0 < y_lo <= y_frac <= y_hi with zero ambient Decimal rounding.
    """
    if y_frac == 0:
        return Decimal(0), Decimal(0)
    if y_frac < 0:
        raise ValueError("Require y_frac >= 0")
    p_num = y_frac.numerator
    q_den = y_frac.denominator
    # Choose shift so p_num * 10^shift / q_den >= 10^(sig_digits - 1)
    shift = max(0, len(str(q_den)) - len(str(p_num)) + 1) + sig_digits
    q_int, r_int = divmod(p_num * (10 ** shift), q_den)
    with _clean_dec_ctx(max(sig_digits + 20, len(str(q_int)) + 10), ROUND_FLOOR):
        y_lo = Decimal(q_int).scaleb(-shift)
    with _clean_dec_ctx(max(sig_digits + 20, len(str(q_int + 1)) + 10), ROUND_CEILING):
        y_hi = Decimal(q_int + (1 if r_int else 0)).scaleb(-shift)
    return y_lo, y_hi


@lru_cache(maxsize=4096)
def _exact_ln_interval(a: Decimal, prec: int = 120) -> Tuple[Decimal, Decimal]:
    """
    Provably outward-directed interval [lo, hi] enclosing ln(a) for ALL finite Decimal a in (0, 1),
    using exact Fraction argument reduction + elementary +, -, *, / directed rounding
    (ZERO Decimal.ln() calls; handles arbitrary-digit inputs such as 0.125 - 1e-180,
    0.5, 0.5 +/- 1e-180, and 1 - 1e-180 with zero inward violations!).

    Argument reduction (exact in Q):
      Multiply x = Fraction(a) by 2^m until x in [1/2, 1).
      Then ln(a) = -2*atanh((1 - x)/(1 + x)) - m * 2*atanh(1/3).
    Recombination (strictly outward):
      m_ln2_hi = CEIL(m * ln2_hi), m_ln2_lo = FLOOR(m * ln2_lo)
      ln_a_lo  = FLOOR(-neg_lnb_hi - m_ln2_hi)
      ln_a_hi  = CEIL(-neg_lnb_lo - m_ln2_lo)
    """
    if not isinstance(a, Decimal) or not a.is_finite() or not (Decimal(0) < a < Decimal(1)):
        raise ValueError("a must be a finite Decimal strictly in (0, 1)")

    wprec = max(prec + 35, 145)

    def _two_atanh_frac_bounds(y_frac: Fraction) -> Tuple[Decimal, Decimal]:
        if y_frac == 0:
            return Decimal(0), Decimal(0)
        y_lo_raw, y_hi_raw = _fraction_to_outward_dec(y_frac, wprec)
        # Since 0 < y_frac <= 1/3, (1/9)^k < 10^-wprec after ~1.1 * wprec terms;
        # for tiny y_frac (<= 1e-6), 40 terms already gives remainder < 10^-480.
        terms = 40 if y_frac <= Fraction(1, 1_000_000) else max(165, int(wprec * 1.15) + 20)

        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            y_lo = +y_lo_raw
            y2_lo = y_lo * y_lo
            p_lo = y_lo
            s_lo = Decimal(0)
            for k in range(terms):
                s_lo = s_lo + (p_lo / Decimal(2 * k + 1))
                p_lo = p_lo * y2_lo
            lo = Decimal(2) * s_lo

        with _clean_dec_ctx(wprec, ROUND_CEILING):
            y_hi = +y_hi_raw
            y2_hi = y_hi * y_hi
            p_hi = y_hi
            s_hi = Decimal(0)
            for k in range(terms):
                s_hi = s_hi + (p_hi / Decimal(2 * k + 1))
                p_hi = p_hi * y2_hi
        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            one_minus_y2 = Decimal(1) - y2_hi
            denom_tail = Decimal(2 * terms + 1) * one_minus_y2
        with _clean_dec_ctx(wprec, ROUND_CEILING):
            tail = (Decimal(2) * p_hi) / denom_tail
            hi = Decimal(2) * s_hi + tail
        return lo, hi

    x_frac = Fraction(a)
    m = 0
    while x_frac < Fraction(1, 2):
        x_frac *= 2
        m += 1
    y_b = (Fraction(1) - x_frac) / (Fraction(1) + x_frac)

    ln2_lo, ln2_hi = _two_atanh_frac_bounds(Fraction(1, 3)) if m > 0 else (Decimal(0), Decimal(0))
    neg_lnb_lo, neg_lnb_hi = _two_atanh_frac_bounds(y_b)

    # Critical outward recombination:
    # For LOWER bound on (-neg_lnb - m*ln2), we MUST round m*ln2_hi UP (ROUND_CEILING) before subtracting!
    # For UPPER bound on (-neg_lnb - m*ln2), we MUST round m*ln2_lo DOWN (ROUND_FLOOR) before subtracting!
    m_dec = Decimal(m)
    with _clean_dec_ctx(wprec, ROUND_CEILING):
        m_ln2_hi = m_dec * ln2_hi
    with _clean_dec_ctx(wprec, ROUND_FLOOR):
        ln_a_lo_w = neg_lnb_hi.copy_negate() - m_ln2_hi
    with _clean_dec_ctx(prec, ROUND_FLOOR):
        ln_a_lo = +ln_a_lo_w

    with _clean_dec_ctx(wprec, ROUND_FLOOR):
        m_ln2_lo = m_dec * ln2_lo
    with _clean_dec_ctx(wprec, ROUND_CEILING):
        ln_a_hi_w = neg_lnb_lo.copy_negate() - m_ln2_lo
    with _clean_dec_ctx(prec, ROUND_CEILING):
        ln_a_hi = +ln_a_hi_w

    return ln_a_lo, ln_a_hi


def _exact_exp_neg_interval(z_lo: Decimal, z_hi: Decimal, prec: int = 120) -> Tuple[Decimal, Decimal]:
    """
    Provably outward-directed interval [lo, hi] enclosing exp(-z) for z in [z_lo, z_hi] > 0,
    using ONLY elementary +, -, *, / with directed rounding (ZERO Decimal.exp() calls!).
    """
    if z_lo <= Decimal(0) or z_hi < z_lo:
        raise ValueError("Require 0 < z_lo <= z_hi")

    wprec = max(prec + 30, 140)
    pairs = max(52, (wprec // 2) + 10)

    s = 0
    scale_int = 1
    with _clean_dec_ctx(wprec, ROUND_CEILING):
        while z_hi / Decimal(scale_int) > Decimal("0.05"):
            scale_int <<= 1
            s += 1
        u_hi = z_hi / Decimal(scale_int)
    with _clean_dec_ctx(wprec, ROUND_FLOOR):
        u_lo = z_lo / Decimal(scale_int)

    # Lower bound on exp(-u_hi): stop at odd term 2*pairs - 1
    with _clean_dec_ctx(wprec, ROUND_FLOOR):
        pos_lo = Decimal(1)
        term = Decimal(1)
        u2_lo = u_hi * u_hi
        for k in range(1, pairs):
            term = (term * u2_lo) / Decimal((2 * k - 1) * (2 * k))
            pos_lo = pos_lo + term
    with _clean_dec_ctx(wprec, ROUND_CEILING):
        neg_hi = +u_hi
        term = +u_hi
        u2_hi = u_hi * u_hi
        for k in range(1, pairs):
            term = (term * u2_hi) / Decimal((2 * k) * (2 * k + 1))
            neg_hi = neg_hi + term
    with _clean_dec_ctx(wprec, ROUND_FLOOR):
        lo = pos_lo - neg_hi
        if lo < Decimal(0):
            lo = Decimal(0)

    # Upper bound on exp(-u_lo): stop at even term 2*pairs
    with _clean_dec_ctx(wprec, ROUND_CEILING):
        pos_hi = Decimal(1)
        term = Decimal(1)
        u2_hi = u_lo * u_lo
        for k in range(1, pairs + 1):
            term = (term * u2_hi) / Decimal((2 * k - 1) * (2 * k))
            pos_hi = pos_hi + term
    with _clean_dec_ctx(wprec, ROUND_FLOOR):
        neg_lo = +u_lo
        term = +u_lo
        u2_lo = u_lo * u_lo
        for k in range(1, pairs):
            term = (term * u2_lo) / Decimal((2 * k) * (2 * k + 1))
            neg_lo = neg_lo + term
    with _clean_dec_ctx(wprec, ROUND_CEILING):
        hi = pos_hi - neg_lo
        if hi > Decimal(1):
            hi = Decimal(1)

    for _ in range(s):
        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            lo = lo * lo
        with _clean_dec_ctx(wprec, ROUND_CEILING):
            hi = hi * hi

    with _clean_dec_ctx(prec, ROUND_FLOOR):
        lo_out = +lo
    with _clean_dec_ctx(prec, ROUND_CEILING):
        hi_out = +hi
    return lo_out, hi_out


def _exact_one_minus_exp_neg_interval(
    z_lo: Decimal, z_hi: Decimal, prec: int = 120
) -> Tuple[Decimal, Decimal]:
    """
    Provably outward-directed interval [p_lo, p_hi] enclosing 1 - exp(-z) for z in [z_lo, z_hi] > 0.
    For z_hi < 0.05, evaluates paired alternating Taylor series directly (zero cancellation);
    for larger z, delegates to _exact_exp_neg_interval.
    """
    if z_lo <= Decimal(0) or z_hi < z_lo:
        raise ValueError("Require 0 < z_lo <= z_hi")

    wprec = max(prec + 30, 140)
    if z_hi < Decimal("0.05"):
        max_pairs = max(68, (wprec // 2) + 14)
        with _clean_dec_ctx(wprec, ROUND_FLOOR) as ctx_t:
            thresh_lo = z_lo * Decimal(1).scaleb(-(prec + 14))
            fact = 1
            pow_lo = +z_lo
            pow_hi = +z_lo
            s_lo = Decimal(0)
            for pair_idx in range(1, max_pairs + 1):
                ctx_t.rounding = ROUND_FLOOR
                s_lo = s_lo + (pow_lo / Decimal(fact))
                k_even = 2 * pair_idx
                fact *= k_even
                ctx_t.rounding = ROUND_FLOOR
                pow_lo = pow_lo * z_lo
                ctx_t.rounding = ROUND_CEILING
                pow_hi = pow_hi * z_lo
                term_even_hi = pow_hi / Decimal(fact)
                ctx_t.rounding = ROUND_FLOOR
                s_lo = s_lo - term_even_hi
                if term_even_hi <= thresh_lo:
                    break
                fact *= k_even + 1
                ctx_t.rounding = ROUND_FLOOR
                pow_lo = pow_lo * z_lo
                ctx_t.rounding = ROUND_CEILING
                pow_hi = pow_hi * z_lo
            if s_lo < Decimal(0):
                s_lo = Decimal(0)

            thresh_hi = z_hi * Decimal(1).scaleb(-(prec + 14))
            fact = 1
            ctx_t.rounding = ROUND_FLOOR
            pow_lo = +z_hi
            ctx_t.rounding = ROUND_CEILING
            pow_hi = +z_hi
            s_hi = +z_hi
            for pair_idx in range(1, max_pairs + 1):
                k_even = 2 * pair_idx
                fact *= k_even
                ctx_t.rounding = ROUND_FLOOR
                pow_lo = pow_lo * z_hi
                ctx_t.rounding = ROUND_CEILING
                pow_hi = pow_hi * z_hi
                ctx_t.rounding = ROUND_FLOOR
                term_even_lo = pow_lo / Decimal(fact)
                ctx_t.rounding = ROUND_CEILING
                s_hi = s_hi - term_even_lo
                k_odd = k_even + 1
                fact *= k_odd
                ctx_t.rounding = ROUND_FLOOR
                pow_lo = pow_lo * z_hi
                ctx_t.rounding = ROUND_CEILING
                pow_hi = pow_hi * z_hi
                ctx_t.rounding = ROUND_CEILING
                term_odd_hi = pow_hi / Decimal(fact)
                s_hi = s_hi + term_odd_hi
                if term_odd_hi <= thresh_hi:
                    break
            if s_hi > Decimal(1):
                s_hi = Decimal(1)

        with _clean_dec_ctx(prec, ROUND_FLOOR):
            p_lo_out = +s_lo
        with _clean_dec_ctx(prec, ROUND_CEILING):
            p_hi_out = +s_hi
        return p_lo_out, p_hi_out

    e_lo, e_hi = _exact_exp_neg_interval(z_lo, z_hi, prec=wprec)
    with _clean_dec_ctx(prec, ROUND_FLOOR):
        p_lo_out = max(Decimal(0), Decimal(1) - e_hi)
    with _clean_dec_ctx(prec, ROUND_CEILING):
        p_hi_out = min(Decimal(1), Decimal(1) - e_lo)
    return p_lo_out, p_hi_out


def _alpha_root_interval(alpha: Decimal, n: int, prec: int = 120) -> Tuple[Decimal, Decimal]:
    """Provably outward-directed interval [lo, hi] enclosing alpha^(1/n) using pure +, -, *, /."""
    wprec = max(prec + 25, 140)
    ln_lo, ln_hi = _exact_ln_interval(alpha, prec=wprec)
    with _clean_dec_ctx(wprec, ROUND_FLOOR):
        z_lo = ln_hi.copy_negate() / Decimal(n)
    with _clean_dec_ctx(wprec, ROUND_CEILING):
        z_hi = ln_lo.copy_negate() / Decimal(n)
    return _exact_exp_neg_interval(z_lo, z_hi, prec=prec)


def _pow_directed(x: Decimal, exp_n: int, prec: int, rounding: str) -> Decimal:
    """Binary exponentiation x^exp_n for x >= 0 under explicit directed rounding."""
    if exp_n == 0:
        return Decimal(1)
    with _clean_dec_ctx(prec, rounding):
        res = Decimal(1)
        base = +x
        e = exp_n
        while e > 0:
            if e & 1:
                res = res * base
            e >>= 1
            if e > 0:
                base = base * base
        return res


def _binomial_lower_tail_monotone_interval(
    k: int, n: int, p_lo: Decimal, p_hi: Decimal, q_lo: Decimal, q_hi: Decimal, prec: int
) -> Tuple[Decimal, Decimal]:
    """
    Fast provably outward-directed interval for P(Bin(n, p) <= k) when k <= floor((n+1)*p),
    where terms f(j) are monotonically non-decreasing for j = 0..k.
    Steps downward from j = k using exact recurrence with rigorous tail bound <= j * f_hi(j).
    Handles arbitrary n (including n = 100,000, k = 50,000) in milliseconds and is 100% immune
    to narrow ambient exponent ranges (Emin/Emax) and Inexact traps!
    """
    wprec = max(prec + 30, 125)
    with _clean_dec_ctx(wprec, ROUND_HALF_EVEN):
        c_int = math.comb(n, k)
        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            c_lo = +Decimal(c_int)
            p_k_lo = _pow_directed(p_lo, k, wprec, ROUND_FLOOR)
            q_nk_lo = _pow_directed(q_lo, n - k, wprec, ROUND_FLOOR)
            f_lo = c_lo * p_k_lo * q_nk_lo
        with _clean_dec_ctx(wprec, ROUND_CEILING):
            c_hi = +Decimal(c_int)
            p_k_hi = _pow_directed(p_hi, k, wprec, ROUND_CEILING)
            q_nk_hi = _pow_directed(q_hi, n - k, wprec, ROUND_CEILING)
            f_hi = c_hi * p_k_hi * q_nk_hi

        tot_lo = f_lo
        tot_hi = f_hi
        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            stop_thresh = Decimal(1).scaleb(-(prec + 10))
        cur_lo = f_lo
        cur_hi = f_hi

        for j in range(k, 0, -1):
            # f(j-1) = f(j) * (j * q) / ((n - j + 1) * p)
            j_dec = Decimal(j)
            nj_dec = Decimal(n - j + 1)
            with _clean_dec_ctx(wprec, ROUND_CEILING):
                den_hi = nj_dec * p_hi
                num_hi = cur_hi * j_dec * q_hi
            with _clean_dec_ctx(wprec, ROUND_FLOOR):
                den_lo = nj_dec * p_lo
                num_lo = cur_lo * j_dec * q_lo
                next_lo = num_lo / den_hi if den_hi > Decimal(0) else Decimal(0)
                tot_lo = tot_lo + next_lo
            with _clean_dec_ctx(wprec, ROUND_CEILING):
                next_hi = num_hi / den_lo if den_lo > Decimal(0) else Decimal(1)
                tot_hi = tot_hi + next_hi
                rem_bound = Decimal(j - 1) * next_hi
            cur_lo = next_lo
            cur_hi = next_hi
            if j > 1 and rem_bound <= stop_thresh:
                with _clean_dec_ctx(wprec, ROUND_CEILING):
                    tot_hi = tot_hi + rem_bound
                break

        with _clean_dec_ctx(prec, ROUND_FLOOR):
            out_lo = max(Decimal(0), min(Decimal(1), +tot_lo))
        with _clean_dec_ctx(prec, ROUND_CEILING):
            out_hi = max(Decimal(0), min(Decimal(1), +tot_hi))
        return out_lo, out_hi


def _binomial_tail_lower_eq_interval(k: int, n: int, p: Decimal, prec: int = 80) -> Tuple[Decimal, Decimal]:
    """
    Provably outward-directed interval [tail_lo, tail_hi] enclosing P(Bin(n, p) <= k)
    for ANY 0 <= k <= n and p in [0, 1] using unimodal symmetry + directed rounding
    (strict ROUND_FLOOR for lower endpoint, strict ROUND_CEILING for upper endpoint on ALL branches,
    and 100% isolated from ambient Decimal exponent range and Inexact traps).
    """
    p_adj = abs(p.adjusted()) if (isinstance(p, Decimal) and p.is_finite() and p != 0) else 0
    wprec = max(prec + 30, 125, p_adj + 40, len(str(n + 1)) + 30)
    with _clean_dec_ctx(wprec, ROUND_HALF_EVEN):
        if p <= Decimal(0):
            return Decimal(1), Decimal(1)
        if p >= Decimal(1):
            v = Decimal(1) if k >= n else Decimal(0)
            return v, v

        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            p_lo = +p
            q_lo = Decimal(1) - p
        with _clean_dec_ctx(wprec, ROUND_CEILING):
            p_hi = +p
            q_hi = Decimal(1) - p

        # Exact mode boundary check: k <= (n + 1) * p?
        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            thresh_lo = Decimal(n + 1) * p_lo
        with _clean_dec_ctx(wprec, ROUND_CEILING):
            thresh_hi = Decimal(n + 1) * p_hi

        if Decimal(k) <= thresh_lo:
            return _binomial_lower_tail_monotone_interval(k, n, p_lo, p_hi, q_lo, q_hi, prec)
        if Decimal(k) >= thresh_hi:
            # Complement: P(Bin(n, p) <= k) = 1 - P(Bin(n, q) <= n - k - 1), where n - k - 1 <= (n + 1) * q
            k_comp = n - k - 1
            if k_comp < 0:
                return Decimal(1), Decimal(1)
            c_lo, c_hi = _binomial_lower_tail_monotone_interval(k_comp, n, q_lo, q_hi, p_lo, p_hi, wprec)
            with _clean_dec_ctx(prec, ROUND_FLOOR):
                out_lo = max(Decimal(0), Decimal(1) - c_hi)
            with _clean_dec_ctx(prec, ROUND_CEILING):
                out_hi = min(Decimal(1), Decimal(1) - c_lo)
            return out_lo, out_hi

        # Mode-straddling fallback: k in (thresh_lo, thresh_hi)
        if k <= 120:
            tot_lo = Decimal(0)
            tot_hi = Decimal(0)
            for j in range(0, k + 1):
                c_int = math.comb(n, j)
                with _clean_dec_ctx(wprec, ROUND_FLOOR):
                    tot_lo = tot_lo + (+Decimal(c_int)) * _pow_directed(p_lo, j, wprec, ROUND_FLOOR) * _pow_directed(q_lo, n - j, wprec, ROUND_FLOOR)
                with _clean_dec_ctx(wprec, ROUND_CEILING):
                    tot_hi = tot_hi + (+Decimal(c_int)) * _pow_directed(p_hi, j, wprec, ROUND_CEILING) * _pow_directed(q_hi, n - j, wprec, ROUND_CEILING)
            with _clean_dec_ctx(prec, ROUND_FLOOR):
                out_lo = max(Decimal(0), min(Decimal(1), +tot_lo))
            with _clean_dec_ctx(prec, ROUND_CEILING):
                out_hi = max(Decimal(0), min(Decimal(1), +tot_hi))
            return out_lo, out_hi

        # Split: P(<= k) = P(<= k - 1) + f(k), where k - 1 <= (n+1)*p_lo
        lo_prev, hi_prev = _binomial_lower_tail_monotone_interval(k - 1, n, p_lo, p_hi, q_lo, q_hi, wprec)
        c_int = math.comb(n, k)
        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            fk_lo = (+Decimal(c_int)) * _pow_directed(p_lo, k, wprec, ROUND_FLOOR) * _pow_directed(q_lo, n - k, wprec, ROUND_FLOOR)
            out_lo_w = lo_prev + fk_lo
        with _clean_dec_ctx(wprec, ROUND_CEILING):
            fk_hi = (+Decimal(c_int)) * _pow_directed(p_hi, k, wprec, ROUND_CEILING) * _pow_directed(q_hi, n - k, wprec, ROUND_CEILING)
            out_hi_w = hi_prev + fk_hi
        with _clean_dec_ctx(prec, ROUND_FLOOR):
            out_lo = max(Decimal(0), min(Decimal(1), +out_lo_w))
        with _clean_dec_ctx(prec, ROUND_CEILING):
            out_hi = max(Decimal(0), min(Decimal(1), +out_hi_w))
        return out_lo, out_hi


@lru_cache(maxsize=4096)
def _sound_zero_event_core(
    n: int,
    alpha: Decimal,
    eta_lower: Decimal,
    prec: int,
) -> Tuple[Decimal, Decimal, Decimal]:
    wprec = max(prec + 35, 130, len(str(n)) + 35)
    with _clean_dec_ctx(wprec, ROUND_HALF_EVEN):
        ln_lo, ln_hi = _exact_ln_interval(alpha, prec=wprec)
        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            z_lo = ln_hi.copy_negate() / Decimal(n)
        with _clean_dec_ctx(wprec, ROUND_CEILING):
            z_hi = ln_lo.copy_negate() / Decimal(n)

        u_raw_lo, u_raw_hi = _exact_one_minus_exp_neg_interval(z_lo, z_hi, prec=wprec)

        with _clean_dec_ctx(prec, ROUND_CEILING):
            u_thinned_upper = u_raw_hi / eta_lower
            if u_thinned_upper > Decimal(1):
                u_thinned_upper = Decimal(1)
            u_raw_upper_out = +u_raw_hi
        with _clean_dec_ctx(prec, ROUND_FLOOR):
            u_thinned_lower = u_raw_lo / eta_lower
            if u_thinned_lower < Decimal(0):
                u_thinned_lower = Decimal(0)
            if u_thinned_lower > Decimal(1):
                u_thinned_lower = Decimal(1)
        return u_raw_upper_out, u_thinned_lower, u_thinned_upper


def sound_zero_event_clopper_pearson_upper(
    n: int,
    alpha: Decimal,
    eta_lower: Decimal = Decimal(1),
    prec: int = 80,
) -> Dict[str, Any]:
    """
    Compute provably outward-directed interval [u_thinned_lower, u_thinned_upper] enclosing:
        p_upper = min(1, (1 - alpha^(1/n)) / eta_lower)
    using exact Fraction reduction + pure elementary Taylor bounds (ZERO Decimal.ln()/exp(),
    ZERO ambient Decimal operations, immune to Inexact traps & hostile prec=4 / narrow Emin contexts!).
    """
    if not _is_strict_int(n) or n < 1:
        raise ValueError("n must be a positive integer")
    if not isinstance(alpha, Decimal) or not alpha.is_finite() or not (Decimal(0) < alpha < Decimal(1)):
        raise ValueError("alpha must be a finite Decimal strictly in (0, 1)")
    if not isinstance(eta_lower, Decimal) or not eta_lower.is_finite() or not (Decimal(0) < eta_lower <= Decimal(1)):
        raise ValueError("eta_lower must be a finite Decimal in (0, 1]")

    with _clean_dec_ctx(max(prec + 35, 130, len(str(n)) + 35), ROUND_HALF_EVEN):
        u_raw_upper_out, u_thinned_lower, u_thinned_upper = _sound_zero_event_core(n, alpha, eta_lower, prec)
        return {
            "n": n,
            "alpha": str(alpha),
            "eta_lower": str(eta_lower),
            "u_raw_upper_80d": format(u_raw_upper_out, "f"),
            "u_thinned_lower_80d": format(u_thinned_lower, "f"),
            "u_thinned_upper_80d": format(u_thinned_upper, "f"),
            "u_thinned_upper_dec": u_thinned_upper,
            "u_thinned_lower_dec": u_thinned_lower,
            "u_thinned_upper_pct_6dp": _dec_to_float_pct(u_thinned_upper, 6),
        }


def _adjudicate_zero_event_vs_cap(
    n: int,
    cap_frac: Decimal,
    alpha: Decimal,
    eta_lower: Decimal,
    *,
    prec: int = 80,
) -> str:
    """
    Three-valued provably sound adjudication of the clamped zero-event upper bound:
        min(1, (1 - alpha^(1/n)) / eta_lower) <= cap_frac
    Returns:
      - "LE"            : STRICTLY proven <= cap_frac
      - "GT"            : STRICTLY proven >  cap_frac
      - "INDETERMINATE" : straddles even at elevated precision & exact-rational budget exceeded
    NEVER infers "GT" from the complement of a one-sided "LE" check!
    """
    if cap_frac >= Decimal(1):
        return "LE"
    t_scale = max(0, -cap_frac.adjusted()) + max(0, -eta_lower.adjusted())
    a_scale = max(0, -alpha.adjusted())
    n_digits = len(str(n))
    base_wprec = max(prec + 40, 140, t_scale + 80, a_scale + 80, n_digits + 60)

    # Escalating outward binary-exponentiation brackets on q^n = (1 - cap_frac * eta_lower)^n vs alpha
    for extra in (0, 140, 360):
        wprec = base_wprec + extra
        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            t_lo = cap_frac * eta_lower
        with _clean_dec_ctx(wprec, ROUND_CEILING):
            t_hi = cap_frac * eta_lower
        if t_lo >= Decimal(1):
            return "LE"
        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            q_lo = max(Decimal(0), Decimal(1) - t_hi)
        with _clean_dec_ctx(wprec, ROUND_CEILING):
            q_hi = min(Decimal(1), Decimal(1) - t_lo)
        q_n_hi = _pow_directed(q_hi, n, wprec, ROUND_CEILING)
        if q_n_hi <= alpha:
            return "LE"
        q_n_lo = _pow_directed(q_lo, n, wprec, ROUND_FLOOR)
        if q_n_lo > alpha:
            return "GT"

    # Exact rational adjudication whenever outward brackets straddle (handles exact ties like 0.9**4097!)
    t_frac = Fraction(cap_frac) * Fraction(eta_lower)
    if t_frac >= 1:
        return "LE"
    q_frac = Fraction(1) - t_frac
    max_bits = max(q_frac.numerator.bit_length(), q_frac.denominator.bit_length())
    if n * max_bits <= 8_000_000:
        return "LE" if (q_frac ** n) <= Fraction(alpha) else "GT"
    return "INDETERMINATE"


def min_n_for_zero_event_cap(
    cap_frac: Decimal,
    alpha: Decimal,
    eta_lower: Decimal = Decimal(1),
    prec: int = 80,
) -> Dict[str, Any]:
    """
    Find exact minimum positive integer n such that the clamped zero-event upper bound
        min(1, (1 - alpha^(1/n)) / eta_lower) <= cap_frac
    using dynamically boosted precision (handling tiny caps such as 1e-106 without 1 - cap rounding
    to 1), valid unit-cap handling (cap = 1.0 -> exact clamped n = 1, distinct from unclamped),
    three-valued exact/interval adjudication (handling large ties such as alpha = 0.9**4097 -> n = 4,097),
    and strict two-sided proof for boundary_strictly_verified (n proven LE AND n-1 proven GT).
    """
    if not isinstance(cap_frac, Decimal) or not cap_frac.is_finite() or not (Decimal(0) < cap_frac <= Decimal(1)):
        raise ValueError("cap_frac must be a finite Decimal in (0, 1]")
    if not isinstance(alpha, Decimal) or not alpha.is_finite() or not (Decimal(0) < alpha < Decimal(1)):
        raise ValueError("alpha must be a finite Decimal strictly in (0, 1)")
    if not isinstance(eta_lower, Decimal) or not eta_lower.is_finite() or not (Decimal(0) < eta_lower <= Decimal(1)):
        raise ValueError("eta_lower must be a finite Decimal in (0, 1]")

    def _solve_unclamped_min_n(target_t_cap: Decimal, target_eta: Decimal) -> Tuple[int, bool, bool]:
        """Solve minimum n >= 1 for (1 - target_t_cap * target_eta)^n <= alpha with dynamic precision."""
        t_scale = max(0, -target_t_cap.adjusted()) + max(0, -target_eta.adjusted())
        a_scale = max(0, -alpha.adjusted())
        sig_digits = (
            len(target_t_cap.as_tuple().digits)
            + len(target_eta.as_tuple().digits)
            + len(alpha.as_tuple().digits)
        )
        wprec = max(prec + 45, 145, t_scale + a_scale + 90, sig_digits + 60)

        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            t_lo = target_t_cap * target_eta
        with _clean_dec_ctx(wprec, ROUND_CEILING):
            t_hi = target_t_cap * target_eta
        if t_lo >= Decimal(1):
            return 1, True, True

        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            q_lo = Decimal(1) - t_hi
        with _clean_dec_ctx(wprec, ROUND_CEILING):
            q_hi = Decimal(1) - t_lo
        if q_lo <= Decimal(0):
            return 1, True, True

        ln_a_lo, ln_a_hi = _exact_ln_interval(alpha, prec=wprec)
        ln_q_lo_b, _ = _exact_ln_interval(q_lo, prec=wprec)
        _, ln_q_hi_b = _exact_ln_interval(q_hi, prec=wprec)

        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            n_lo_est = int((ln_a_hi.copy_negate() / ln_q_lo_b.copy_negate()).to_integral_value(rounding=ROUND_FLOOR))
        with _clean_dec_ctx(wprec, ROUND_CEILING):
            n_hi_est = int((ln_a_lo.copy_negate() / ln_q_hi_b.copy_negate()).to_integral_value(rounding=ROUND_CEILING))

        lo_n = max(1, n_lo_est - 2)
        hi_n = max(lo_n, n_hi_est + 2)

        # Ensure lo_n - 1 (if > 1) is strictly GT and hi_n is strictly LE
        while lo_n > 1 and _adjudicate_zero_event_vs_cap(lo_n, target_t_cap, alpha, target_eta, prec=prec) == "LE":
            hi_n = lo_n
            lo_n = max(1, lo_n - max(1, (hi_n - lo_n) + 1))
        step = 1
        while _adjudicate_zero_event_vs_cap(hi_n, target_t_cap, alpha, target_eta, prec=prec) != "LE":
            lo_n = hi_n + 1
            hi_n = hi_n + step
            step *= 2

        # Binary search for exact minimal n_star in [lo_n, hi_n]
        while lo_n < hi_n:
            mid = (lo_n + hi_n) // 2
            adj_mid = _adjudicate_zero_event_vs_cap(mid, target_t_cap, alpha, target_eta, prec=prec)
            if adj_mid == "LE":
                hi_n = mid
            elif adj_mid == "GT":
                lo_n = mid + 1
            else:
                # Conservative: cannot prove mid clears, advance linearly only if needed
                lo_n = mid + 1

        n_cand = lo_n
        adj_n = _adjudicate_zero_event_vs_cap(n_cand, target_t_cap, alpha, target_eta, prec=prec)
        if n_cand == 1:
            adj_prev_gt = True
        else:
            adj_prev = _adjudicate_zero_event_vs_cap(n_cand - 1, target_t_cap, alpha, target_eta, prec=prec)
            adj_prev_gt = adj_prev == "GT"
        return n_cand, (adj_n == "LE"), adj_prev_gt

    with _clean_dec_ctx(max(prec + 45, 145), ROUND_HALF_EVEN):
        unclamped_ref: int | None = None
        if cap_frac == Decimal(1):
            # Clamped model: u(n) = min(1, (1 - alpha^(1/n))/eta_lower) <= 1 holds for ALL n >= 1 -> exact n = 1!
            n_star = 1
            at_n_verified_le = True
            prev_verified_gt = True
            if eta_lower < Decimal(1):
                # Record unclamped comparison (solving (1 - eta_lower)^n <= alpha) for diagnostic transparency
                unclamped_n, _, _ = _solve_unclamped_min_n(eta_lower, Decimal(1))
                unclamped_ref = unclamped_n
        else:
            n_star, at_n_verified_le, prev_verified_gt = _solve_unclamped_min_n(cap_frac, eta_lower)

        at_n = sound_zero_event_clopper_pearson_upper(n_star, alpha, eta_lower, prec=prec)
        at_n_minus_1 = (
            sound_zero_event_clopper_pearson_upper(n_star - 1, alpha, eta_lower, prec=prec)
            if n_star > 1
            else None
        )
        out_dict: Dict[str, Any] = {
            "cap_frac": str(cap_frac),
            "alpha": str(alpha),
            "eta_lower": str(eta_lower),
            "min_n_pass": n_star,
            "operational_n_rounded_up_500": ((n_star + 499) // 500) * 500,
            "u_at_min_n_upper_80d": at_n["u_thinned_upper_80d"],
            "u_at_min_n_pct": _dec_to_float_pct(at_n["u_thinned_upper_dec"], 8),
            "fail_n_minus_1": (n_star - 1) if n_star > 1 else None,
            "u_at_n_minus_1_pct": (
                _dec_to_float_pct(at_n_minus_1["u_thinned_upper_dec"], 8)
                if at_n_minus_1 is not None
                else None
            ),
            "boundary_strictly_verified": bool(at_n_verified_le and prev_verified_gt),
        }
        if unclamped_ref is not None:
            out_dict["unclamped_min_n_reference"] = unclamped_ref
        return out_dict


@lru_cache(maxsize=4096)
def exact_clopper_pearson_lower_calibrant(
    r_k: int,
    r_n: int,
    alpha_cal: Decimal,
    prec: int = 60,
) -> Decimal:
    """
    Provably conservative (<= true) one-sided Clopper-Pearson lower bound at level (1 - alpha_cal)
    for r_k successes out of r_n trials (100% isolated from ambient Decimal exponent/trap settings).
    """
    if not (_is_strict_int(r_k) and _is_strict_int(r_n) and 0 <= r_k <= r_n and r_n >= 1):
        raise ValueError("Require integer 0 <= r_k <= r_n and r_n >= 1")
    wprec = max(prec + 25, 64)
    with _clean_dec_ctx(wprec, ROUND_HALF_EVEN):
        if r_k == 0:
            return Decimal(0)
        if r_k == r_n:
            eta_lo, _ = _alpha_root_interval(alpha_cal, r_n, prec=prec)
            return eta_lo

        m = r_n - r_k
        lo_q = Decimal(0)
        hi_q = Decimal(1)
        iters = min(240, int(prec * 3.4) + 12)
        for _ in range(iters):
            with _clean_dec_ctx(wprec, ROUND_HALF_EVEN):
                mid = (lo_q + hi_q) / Decimal(2)
                if mid <= lo_q or mid >= hi_q:
                    break
            tail_lo, tail_hi = _binomial_tail_lower_eq_interval(m, r_n, mid, prec=wprec)
            if tail_lo > alpha_cal:
                lo_q = mid
            elif tail_hi <= alpha_cal:
                hi_q = mid
            else:
                break
        with _clean_dec_ctx(prec, ROUND_FLOOR):
            return max(Decimal(0), Decimal(1) - hi_q)


@lru_cache(maxsize=4096)
def exact_clopper_pearson_upper_general(
    k: int,
    n: int,
    alpha: Decimal,
    prec: int = 60,
) -> Decimal:
    """
    Provably conservative (>= true) one-sided Clopper-Pearson upper bound U(k, n; alpha)
    solving P(Bin(n, p) <= k) = alpha via outward-invariant bisection (100% isolated from
    ambient Decimal exponent range and Inexact traps).
    """
    if not (_is_strict_int(k) and _is_strict_int(n) and 0 <= k <= n and n >= 1):
        raise ValueError("Require integer 0 <= k <= n and n >= 1")
    wprec = max(prec + 25, 64)
    with _clean_dec_ctx(wprec, ROUND_HALF_EVEN):
        if k == n:
            return Decimal(1)
        if k == 0:
            return sound_zero_event_clopper_pearson_upper(n, alpha, Decimal(1), prec=prec)["u_thinned_upper_dec"]

        lo_p = Decimal(0)
        hi_p = Decimal(1)
        iters = min(240, int(prec * 3.4) + 12)
        for _ in range(iters):
            with _clean_dec_ctx(wprec, ROUND_HALF_EVEN):
                mid = (lo_p + hi_p) / Decimal(2)
                if mid <= lo_p or mid >= hi_p:
                    break
            tail_lo, tail_hi = _binomial_tail_lower_eq_interval(k, n, mid, prec=wprec)
            if tail_lo > alpha:
                lo_p = mid
            elif tail_hi <= alpha:
                hi_p = mid
            else:
                break
        with _clean_dec_ctx(prec, ROUND_CEILING):
            return min(Decimal(1), +hi_p)


def _clear_math_caches() -> None:
    _exact_ln_interval.cache_clear()
    _sound_zero_event_core.cache_clear()
    exact_clopper_pearson_lower_calibrant.cache_clear()
    exact_clopper_pearson_upper_general.cache_clear()
    exact_student_t_one_sided_95.cache_clear()


def _exact_floor_div_by_decimal(n: int, denom: Decimal) -> int:
    """
    R16-M2 Exact arbitrary-precision integer floor `floor(n / denom)` via exact rational
    arithmetic (`Fraction(n) // Fraction(denom)`). Eliminates finite-precision Decimal truncation
    even for huge admitted synthetic counts (e.g. `n = 10**80 + 1, deff = 1 -> 10**80 + 1`).
    """
    if not _is_strict_int(n) or n < 0:
        raise ValueError("n must be a non-negative integer")
    if not isinstance(denom, Decimal) or not denom.is_finite() or denom <= Decimal(0):
        raise ValueError("denom must be a finite positive Decimal")
    if n == 0:
        return 0
    if denom == Decimal(1):
        return int(n)
    # Guard against astronomically large positive exponents where denom > n trivially implies floor = 0
    if denom.adjusted() > len(str(n)) + 2:
        return 0
    return int(Fraction(n) // Fraction(denom))


def exact_component_probability_ratio_upper(
    k_treated: int,
    n_treated: int,
    alpha_treated: Decimal,
    denominator_lower_factors: Tuple[Decimal, ...],
    *,
    deff: Decimal = Decimal("1.0"),
    prec: int = 80,
) -> Dict[str, Any]:
    """
    R06-B2 + R08-M1 + R09-B2 Exact conservative component-probability ratio one-sided upper bound
    over the true mathematical ratio domain `R = p_treated / prod_i p_den_i in [0, +infinity)`:
      1. Bound the treated event probability on the actual treated effective sampling
         denominator `n_treated_eff = floor(n_treated / deff)` via outward `ROUND_CEILING`
         Clopper-Pearson `u_treated = U(k_treated, n_treated_eff; alpha_treated)`.
      2. Multiply the outward `ROUND_FLOOR` denominator component lower bounds
         `den_lower_prod = floor(prod(denominator_lower_factors))`.
      3. Form the unclamped conservative directional one-sided upper ratio limit
         `u_ratio = ceil(u_treated / den_lower_prod)` on `[0, +infinity)` (`+Infinity` when
         `den_lower_prod == 0` since `u_treated > 0`). NEVER clamped to `1.0`!
    Guarantees directional one-sided upper confidence `>= 1 - (alpha_treated + sum(alpha_den_i))`
    across the numerator and denominator component bounds via Bonferroni union bound (not a
    simultaneous two-sided interval at that same unsplit alpha), with ZERO adjusted-denominator
    Clopper-Pearson direction-of-coverage inversion and ZERO domain-clipping inversion.
    """
    if not (_is_strict_int(k_treated) and _is_strict_int(n_treated) and 0 <= k_treated <= n_treated and n_treated >= 1):
        raise ValueError("Require integer 0 <= k_treated <= n_treated and n_treated >= 1")
    if not isinstance(alpha_treated, Decimal) or not alpha_treated.is_finite() or not (Decimal(0) < alpha_treated < Decimal(1)):
        raise ValueError("alpha_treated must be a finite Decimal strictly in (0, 1)")
    if not isinstance(deff, Decimal) or not deff.is_finite() or deff < Decimal("1.0"):
        raise ValueError("deff must be a finite Decimal >= 1.0")
    if not denominator_lower_factors:
        raise ValueError("Require at least one denominator lower-bound factor")

    wprec = max(prec, 80)
    n_treated_eff = _exact_floor_div_by_decimal(n_treated, deff)
    with _clean_dec_ctx(wprec, ROUND_FLOOR):
        den_lower_prod = Decimal(1)
        for fac in denominator_lower_factors:
            if not isinstance(fac, Decimal) or not fac.is_finite() or fac < Decimal(0) or fac > Decimal(1):
                raise ValueError("Each denominator factor must be a finite Decimal in [0, 1]")
            den_lower_prod = den_lower_prod * fac

    if n_treated_eff < 1:
        k_treated_eff_upper: int | None = 0 if k_treated == 0 else None
        u_treated = Decimal(1)
    else:
        # R10-B3 Outward-upward effective numerator count:
        #   k_eff_upper = ceil(k_treated * n_treated_eff / n_treated)
        # guarantees k_eff_upper / n_treated_eff >= k_treated / n_treated unconditionally
        # (and equals k_treated when deff == 1.0, and equals 0 when k_treated == 0!).
        k_treated_eff_upper = (k_treated * n_treated_eff + n_treated - 1) // n_treated
        cp_prec = wprec if k_treated_eff_upper == 0 else min(wprec, 60)
        u_treated = exact_clopper_pearson_upper_general(k_treated_eff_upper, n_treated_eff, alpha_treated, prec=cp_prec)

    if den_lower_prod <= Decimal(0):
        u_ratio = Decimal("Infinity")
        u_ratio_str = "Infinity"
    else:
        with _clean_dec_ctx(wprec, ROUND_CEILING):
            u_ratio = u_treated / den_lower_prod
        u_ratio_str = format(u_ratio, "f")

    # R11-B3: Exact Clopper-Pearson directional confidence authorization is STRICTLY narrowed to
    # `deff == 1.0` (verified independent binary observations, matching GY-018 and IIP-0044).
    # For `deff > 1.0`, variance-adjusted effective counts remain a non-authorizing diagnostic display
    # only and NEVER certify exact directional confidence or release authorization!
    is_exact_independent = bool(deff == Decimal("1.0"))
    return {
        "k_treated": k_treated,
        "n_treated_actual": n_treated,
        "deff": format(deff, "f"),
        "n_treated_eff": n_treated_eff,
        "k_treated_eff_upper": k_treated_eff_upper,
        "u_treated_dec": u_treated,
        "den_lower_prod_dec": den_lower_prod,
        "u_ratio_unclamped_dec": u_ratio,
        "u_ratio_dec": u_ratio,
        "u_ratio_80d": u_ratio_str,
        "estimand_domain": "[0, +infinity)",
        "u_ratio_clamped_to_unity": False,
        "ratio_upper_limit_exceeds_unity": bool(u_ratio > Decimal(1)),
        "exact_directional_confidence_certified": is_exact_independent,
        "confidence_scope": (
            "EXACT_INDEPENDENT_BINOMIAL_BONFERRONI_DEFF_EQ_1"
            if is_exact_independent
            else "NON_AUTHORIZING_VARIANCE_ADJUSTED_DIAGNOSTIC_ONLY"
        ),
        "release_authorizing_eligible": is_exact_independent,
        "adjudication_disposition": (
            None
            if is_exact_independent
            else "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE"
        ),
        "confidence_statement_type": (
            "DIRECTIONAL_ONE_SIDED_UPPER_AT_1_MINUS_ALPHA_SUM"
            if is_exact_independent
            else "NON_AUTHORIZING_VARIANCE_ADJUSTED_DIAGNOSTIC_ONLY_NOT_EXACT_CONFIDENCE"
        ),
    }


def exact_paired_vehicle_ratio_bounds(
    k_treated: int,
    n_treated: int,
    k_veh_alive: int,
    n_veh: int,
    *,
    alpha_treated: Decimal = Decimal("0.025"),
    alpha_veh: Decimal = Decimal("0.025"),
    deff: Decimal = Decimal("1.0"),
    prec: int = 80,
) -> Dict[str, Any]:
    """
    R06-B2 + R08-M1 + R09-B2 + R10-B3 Exact conservative component-probability ratio limits
    (separate directional one-sided upper and lower confidence statements) for the paired
    vehicle-normalized survival ratio `R = p_treated / s_veh` over its true mathematical
    domain `[0, +infinity)`:
      - Effective sample size `n_treated_eff = floor(n_treated / deff)` with outward-consistent
        integer event counts:
          * Upper bound: `k_treated_eff_upper = ceil(k_treated * n_treated_eff / n_treated)`
            (`>= k_treated / n_treated * n_treated_eff`), giving
            `u_ratio = ceil(U(k_treated_eff_upper, n_treated_eff; alpha_treated) / L(k_veh_alive, n_veh; alpha_veh))`
            (`+Infinity` if `L(k_veh_alive, n_veh; alpha_veh) == 0`; `u_treated = 1` when `n_treated_eff < 1`;
            NEVER clamped to `1.0`!).
          * Lower bound: `k_treated_eff_lower = floor(k_treated * n_treated_eff / n_treated)`
            (`<= k_treated / n_treated * n_treated_eff`), giving
            `l_ratio = floor(L(k_treated_eff_lower, n_treated_eff; alpha_treated) / U(k_veh_alive, n_veh; alpha_veh))`
            (`0` when `n_treated_eff < 1` or `k_treated_eff_lower == 0`).
    By the Kaas-Buhrman (1980) binomial median theorem (`L_CP(k, n, alpha) <= k/n <= U_CP(k, n, alpha)`
    for all `0 < alpha <= 0.5`) combined with exact outward integer rounding
    `k_eff_lower / n_eff <= k / n <= k_eff_upper / n_eff`, this guarantees
    `0 <= l_ratio <= empirical_point <= u_ratio` UNCONDITIONALLY across the ENTIRE admitted
    domain (`0 <= k_t <= n_t`, `n_t >= 1`, `0 <= k_v <= n_v`, `n_v >= 1`, `deff >= 1.0`,
    `0 < alpha_treated, alpha_veh <= 0.5`, `alpha_treated + alpha_veh < 1`) — eliminating the
    `floor(k/deff) / floor(n/deff) > k/n` inward-bias bug (e.g. `200/299` at `deff=100`).
    """
    if not (_is_strict_int(k_veh_alive) and _is_strict_int(n_veh) and 0 <= k_veh_alive <= n_veh and n_veh >= 1):
        raise ValueError("Require integer 0 <= k_veh_alive <= n_veh and n_veh >= 1")
    if not isinstance(alpha_treated, Decimal) or not alpha_treated.is_finite() or not (Decimal(0) < alpha_treated <= Decimal("0.5")):
        raise ValueError("alpha_treated must be a finite Decimal in (0, 0.5]")
    if not isinstance(alpha_veh, Decimal) or not alpha_veh.is_finite() or not (Decimal(0) < alpha_veh <= Decimal("0.5")):
        raise ValueError("alpha_veh must be a finite Decimal in (0, 0.5]")
    if alpha_treated + alpha_veh >= Decimal(1):
        raise ValueError("Require alpha_treated + alpha_veh < 1 for positive directional confidence")

    wprec = max(prec, 80)
    cp_prec = min(wprec, 60)
    s_veh_lower = exact_clopper_pearson_lower_calibrant(k_veh_alive, n_veh, alpha_veh, prec=cp_prec)
    s_veh_upper = exact_clopper_pearson_upper_general(k_veh_alive, n_veh, alpha_veh, prec=cp_prec)

    upper_res = exact_component_probability_ratio_upper(
        k_treated,
        n_treated,
        alpha_treated,
        (s_veh_lower,),
        deff=deff,
        prec=wprec,
    )
    n_treated_eff = upper_res["n_treated_eff"]
    # R10-B3 Outward-downward effective numerator count:
    #   k_eff_lower = floor(k_treated * n_treated_eff / n_treated)
    # guarantees k_eff_lower / n_treated_eff <= k_treated / n_treated unconditionally!
    k_treated_eff_lower = (k_treated * n_treated_eff) // n_treated if n_treated_eff >= 1 else 0

    if n_treated_eff < 1 or k_treated_eff_lower < 1:
        l_treated = Decimal(0)
    else:
        l_treated = exact_clopper_pearson_lower_calibrant(k_treated_eff_lower, n_treated_eff, alpha_treated, prec=cp_prec)

    if s_veh_upper <= Decimal(0):
        l_ratio = Decimal(0)
    else:
        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            l_ratio = l_treated / s_veh_upper

    if k_veh_alive == 0:
        emp_ratio_dec: Decimal | None = None if k_treated == 0 else Decimal("Infinity")
    else:
        with _clean_dec_ctx(wprec, ROUND_HALF_EVEN):
            emp_ratio_dec = (Decimal(k_treated) * Decimal(n_veh)) / (Decimal(n_treated) * Decimal(k_veh_alive))

    with _clean_dec_ctx(wprec, ROUND_FLOOR):
        dir_conf_lb = Decimal(1) - (alpha_treated + alpha_veh)

    u_ratio = upper_res["u_ratio_dec"]
    # R11-M1: Zero-denominator boundary convention:
    #   - 0/0 (k_treated == 0 and k_veh_alive == 0): empirical point estimate is undefined (None),
    #     so `bounds_ordered_l_le_point_le_u` is reported as `None` (undefined), NOT `True`!
    #   - k > 0 / 0 (k_treated > 0 and k_veh_alive == 0): empirical point estimate is `+Infinity`
    #     and `u_ratio == +Infinity`, so `0 <= l_ratio <= +Infinity <= +Infinity` holds (`True`).
    if emp_ratio_dec is None:
        bounds_l_le_pt_le_u: bool | None = None
        zero_denom_convention = "UNDEFINED_0_OVER_0_POINT_AND_POINT_ORDERING_FLAG_NONE"
    elif emp_ratio_dec == Decimal("Infinity"):
        bounds_l_le_pt_le_u = bool(Decimal(0) <= l_ratio <= emp_ratio_dec <= u_ratio)
        zero_denom_convention = "POSITIVE_NUMERATOR_ZERO_DENOMINATOR_POINT_PLUS_INFINITY"
    else:
        bounds_l_le_pt_le_u = bool(Decimal(0) <= l_ratio <= emp_ratio_dec <= u_ratio)
        zero_denom_convention = "FINITE_POSITIVE_DENOMINATOR"

    # R11-B3: Exact Clopper-Pearson directional confidence authorization is STRICTLY narrowed to
    # `deff == 1.0` (verified independent binary observations, matching GY-018 and IIP-0044).
    # For `deff > 1.0`, variance-adjusted bounds preserve outward point ordering strictly as a
    # non-authorizing diagnostic display and NEVER certify exact directional confidence!
    is_exact_independent = bool(deff == Decimal("1.0"))
    return {
        **upper_res,
        "k_treated_eff": k_treated_eff_lower,
        "k_treated_eff_lower": k_treated_eff_lower,
        "s_veh_lower_dec": s_veh_lower,
        "s_veh_upper_dec": s_veh_upper,
        "l_treated_dec": l_treated,
        "l_ratio_dec": l_ratio,
        "l_ratio_80d": format(l_ratio, "f"),
        "empirical_ratio_point_estimate_dec": emp_ratio_dec,
        "zero_denominator_boundary_convention": zero_denom_convention,
        "estimand_domain": "[0, +infinity)",
        "u_ratio_clamped_to_unity": False,
        "treated_survival_exceeds_vehicle_survival": bool(k_treated * n_veh > k_veh_alive * n_treated),
        "ratio_lower_limit_exceeds_unity": bool(l_ratio > Decimal(1)),
        "ratio_upper_limit_exceeds_unity": bool(u_ratio > Decimal(1)),
        "bounds_ordered_l_le_u": bool(l_ratio <= u_ratio),
        "bounds_ordered_l_le_point_le_u": bounds_l_le_pt_le_u,
        "exact_directional_confidence_certified": is_exact_independent,
        "confidence_scope": (
            "EXACT_INDEPENDENT_BINOMIAL_BONFERRONI_DEFF_EQ_1"
            if is_exact_independent
            else "NON_AUTHORIZING_VARIANCE_ADJUSTED_DIAGNOSTIC_ONLY"
        ),
        "release_authorizing_eligible": is_exact_independent,
        "adjudication_disposition": (
            None
            if is_exact_independent
            else "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE"
        ),
        "confidence_statement_type": (
            "DIRECTIONAL_ONE_SIDED_SEPARATE_AT_1_MINUS_ALPHA_SUM"
            if is_exact_independent
            else "NON_AUTHORIZING_VARIANCE_ADJUSTED_DIAGNOSTIC_ONLY_NOT_EXACT_CONFIDENCE"
        ),
        "directional_one_sided_confidence_lower_bound": (
            format(dir_conf_lb, "f") if is_exact_independent else None
        ),
        "simultaneous_two_sided_at_unsplit_alpha_claimed": False,
        "confidence_statement_note": (
            (
                "Estimand R = p_treated / s_veh has mathematical domain [0, +infinity) and may exceed 1.0 "
                "when treated survival exceeds matched vehicle survival. At deff == 1.0 (verified independent "
                "binary observations, matching GY-018 and IIP-0044), neither u_ratio (ceil(u_treated / s_veh_lower)) "
                "nor l_ratio (floor(l_treated / s_veh_upper)) is clamped to 1.0, guaranteeing 0 <= l_ratio <= point <= u_ratio "
                "for every defined empirical point (with zero-denominator boundary conventions: 0/0 -> undefined point "
                "estimate None and bounds_ordered_l_le_point_le_u = None; k > 0 / 0 -> point estimate +Infinity and "
                "u_ratio = +Infinity). u_ratio and l_ratio are separate directional (one-sided) confidence statements "
                "at >= 1 - (alpha_treated + alpha_veh) each, using the same per-component one-sided tail budgets in "
                "each direction (NOT a simultaneous two-sided confidence interval at that same unsplit alpha)."
            )
            if is_exact_independent
            else (
                "NON-AUTHORIZING DIAGNOSTIC ONLY (deff > 1.0): Outward-consistent effective counts "
                "k_eff_lower = floor(k * n_eff / n) and k_eff_upper = ceil(k * n_eff / n) with n_eff = floor(n / deff) "
                "preserve point ordering (0 <= l_ratio <= point <= u_ratio whenever the empirical point is defined; "
                "0/0 yields undefined point estimate None and bounds_ordered_l_le_point_le_u = None; k > 0 / 0 yields "
                "+Infinity) strictly for diagnostic display, but variance-adjusted binomial bounds do NOT guarantee "
                "exact nominal directional confidence under correlated/clustered observations (exact directional "
                "confidence is certified strictly at deff == 1.0). Release adjudication MUST route to "
                "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE."
            )
        ),
    }


def _alpha_3pathogen_global_floor(prec: int = 120) -> Decimal:
    """Conservative floor of 0.05 / 30 = 1/600 so 30 * alpha <= 0.05 holds strictly."""
    with _clean_dec_ctx(prec, ROUND_FLOOR):
        return Decimal(1) / Decimal(600)


# ---------------------------------------------------------------------------
# Part A (NW-18): Canonical Product Registry, Trusted External Qualification Store,
#                 & Hardened Whole-Graft Gate 0V + Stress-State AP1903 Evaluator
# ---------------------------------------------------------------------------
@lru_cache(maxsize=8)
def _load_canonical_product_registry_cached(openislet_root_str: str) -> Dict[str, Any]:
    """
    Load canonical product definitions strictly from:
      1. data/protocols/islet1_product_definitions_v0.8.0.json (38 canonical products + aliases)
      2. data/protocols/iip0041_abx_cd64t_il1rn_side_contract_v0.8.0.json (6 explicit ABX_L2_v2_* donors)
    Eliminates ALL fragile substring inference for ectopic viral receptors and genotypes (B2).
    """
    root = Path(openislet_root_str)
    products_by_id: Dict[str, Dict[str, Any]] = {}
    alias_to_canonical: Dict[str, str] = {}

    pd_path = root / "data" / "protocols" / "islet1_product_definitions_v0.8.0.json"
    if pd_path.is_file():
        pd_doc = strict_json_load_file(pd_path, preserve_boundary_decimals=False)
        for entry in pd_doc.get("products", []):
            cid = str(entry["product_variant_id"])
            base_or_prime = list(entry.get("base_or_prime_edit_loci") or [])
            dsb_or_indel = list(entry.get("dsb_or_indel_loci") or [])
            tyk2_mode = (
                "TYK2_PE_P1104A"
                if "TYK2" in base_or_prime
                else ("TYK2_KO_PROPOSED" if "TYK2" in dsb_or_indel else "TYK2_UNEDITED_DONOR_DECLARED")
            )
            cell_source_raw = str(((entry.get("donor_lineage") or {}).get("cell_source")) or "").strip().lower()
            explicit_bank_origin = str(entry.get("bank_origin") or "").strip().lower()
            explicit_tier_family = entry.get("product_tier_family")
            if isinstance(explicit_tier_family, str) and explicit_tier_family in PRODUCT_TIER_FAMILY_ALLOWED_TIERS:
                tier_family = explicit_tier_family
            else:
                is_autologous_d1b = bool(
                    explicit_bank_origin == "autologous_hipsc"
                    or cell_source_raw == "autologous_hipsc"
                    or (cid.startswith("ISLET1_D1_AUTO_") and "autologous" in cell_source_raw)
                )
                tier_family = "AUTOLOGOUS_D1B_AUTO_C" if is_autologous_d1b else "ALLOGENEIC_MCB_BANKED"
            rec = {
                "product_variant_id": cid,
                "registry_source": "islet1_product_definitions_v0.8.0.json",
                "family": entry.get("family"),
                "product_tier_family": tier_family,
                "allowed_qualification_tiers": list(PRODUCT_TIER_FAMILY_ALLOWED_TIERS[tier_family]),
                "execution_supported": bool(entry.get("execution_supported", False)),
                "required_ectopic_viral_receptors": list(CANONICAL_ECTOPIC_VIRAL_RECEPTORS.get(cid, ())),
                "tyk2_product_genotype_class": tyk2_mode,
                "aliases": list(entry.get("aliases") or []),
            }
            products_by_id[cid] = rec
            alias_to_canonical[cid] = cid
            for al in rec["aliases"]:
                if isinstance(al, str) and al.strip():
                    alias_to_canonical[al] = cid

    sc36_path = root / "data" / "protocols" / "iip0041_abx_cd64t_il1rn_side_contract_v0.8.0.json"
    if sc36_path.is_file():
        sc36 = strict_json_load_file(sc36_path, preserve_boundary_decimals=False)
        suite = sc36.get("modeb_core_abx_ciita_exon5_suite") or {}
        donors = list(suite.get("active_wave5_go_scope_donors") or []) + list(
            suite.get("archived_hold_comparator_donors") or []
        )
        for d in donors:
            did = d.get("fasta_record_id")
            if isinstance(did, str) and did.strip():
                rec = {
                    "product_variant_id": did,
                    "registry_source": "iip0041_abx_cd64t_il1rn_side_contract_v0.8.0.json",
                    "family": "ABX_MODEB_SIDE_CONTRACT",
                    "product_tier_family": "ALLOGENEIC_ABX_SIDE_CONTRACT",
                    "allowed_qualification_tiers": list(PRODUCT_TIER_FAMILY_ALLOWED_TIERS["ALLOGENEIC_ABX_SIDE_CONTRACT"]),
                    "execution_supported": False,
                    "manufacture_authorized": bool(d.get("manufacture_authorized", False)),
                    "required_ectopic_viral_receptors": list(CANONICAL_ECTOPIC_VIRAL_RECEPTORS.get(did, ())),
                    "tyk2_product_genotype_class": "TYK2_UNEDITED_DONOR_DECLARED",
                    "aliases": [],
                }
                products_by_id[did] = rec
                alias_to_canonical[did] = did

    return {
        "products_by_id": products_by_id,
        "alias_to_canonical": alias_to_canonical,
    }


def resolve_canonical_product_variant(
    raw_identifier: Any,
    *,
    openislet_root: Path | None = None,
) -> Dict[str, Any] | None:
    """
    Resolve a submitted product_variant_id (or registered alias) canonically against
    islet1_product_definitions_v0.8.0.json + allowlisted IIP-0041 ABX_L2_v2_* side contract.
    Returns None for unregistered, empty, whitespace-padded, or non-string identifiers.
    """
    if not _is_valid_identifier(raw_identifier):
        return None
    root = openislet_root.resolve() if openislet_root is not None else _resolve_roots(None, None)[0]
    reg = _load_canonical_product_registry_cached(str(root))
    cid = reg["alias_to_canonical"].get(str(raw_identifier))
    if cid is None:
        return None
    return copy.deepcopy(reg["products_by_id"][cid])


def _implied_ectopic_receptors_for_product(
    product_variant_id: str,
    *,
    openislet_root: Path | None = None,
) -> set[str]:
    """
    Return exact ectopic viral receptors required by a canonically registered product_variant_id.
    ZERO fragile substring inference: looks up strictly in the canonical product registry!
    """
    resolved = resolve_canonical_product_variant(product_variant_id, openislet_root=openislet_root)
    if resolved is None:
        return set()
    return set(resolved.get("required_ectopic_viral_receptors") or [])


def is_qualification_tier_allowed_for_product(
    canonical_product_def: Dict[str, Any] | None,
    qual_tier: Any,
) -> Tuple[bool, List[str]]:
    """
    R04-B1: Enforce strict canonical product-family-to-qualification-tier allowlist.
      - AUTOLOGOUS_D1B_PROCESS_QUAL is allowed ONLY for canonical autologous D1b-Auto-C
        variants (ISLET1_D1_AUTO_*).
      - BANK_QUALIFICATION and LOT_RELEASE_SURROGATE require allogeneic MCB-banked product
        families (rejecting autologous D1b variants on allogeneic tiers).
    """
    if canonical_product_def is None or not isinstance(qual_tier, str) or qual_tier not in ALLOWED_QUALIFICATION_TIERS:
        return False, []
    allowed = canonical_product_def.get("allowed_qualification_tiers") or []
    if qual_tier in allowed:
        return True, []
    fam = str(canonical_product_def.get("product_tier_family") or "UNKNOWN_FAMILY")
    pvid = str(canonical_product_def.get("product_variant_id") or "UNKNOWN_PRODUCT")
    return False, [
        "HOLD_INAPPLICABLE_QUALIFICATION_TIER_FOR_PRODUCT_FAMILY",
        f"HOLD_INAPPLICABLE_QUALIFICATION_TIER_{qual_tier}_FOR_{fam}_{pvid}",
    ]


def compute_canonical_qualification_artifact_sha256(record: Dict[str, Any]) -> str:
    """Canonical SHA-256 of an authenticated bank/process qualification record excluding its `sha256` field."""
    body = {k: v for k, v in record.items() if k != "sha256"}
    canonical = _canonical_json_dumps(body)
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def _safe_canonical_qualification_artifact_sha256(record: Dict[str, Any]) -> str | None:
    """Return canonical record SHA-256 or None if record contains non-finite floats, excessive depth, or non-JSON values."""
    try:
        return compute_canonical_qualification_artifact_sha256(record)
    except (TypeError, ValueError, OverflowError, RecursionError):
        return None


def build_authenticated_bank_qualification_record(
    *,
    mcb_id: str,
    product_variant_id: str | None = None,
    product_variant: str | None = None,
    bank_lot_id: str,
    bank_payload_sha256: str,
    verdict: str = "PASS_COMPOSITE_BANK_QUALIFICATION",
    operational_tier: str = "BANK_QUALIFICATION",
    legacy_tier: str = "READY_FOR_ENCAPSULATION_COMPLETE_STAGE0_EVIDENCE",
    legacy_evaluator_passed: bool = True,
    legacy_safety_kill_s9_triggered: bool = False,
    gate0v_verdict: str = "PASS_WHOLEGRAFT_BANK_QUALIFICATION",
    gate0v_evaluator_passed: bool = True,
    gate0v_hard_stops_count: int = 0,
    gate0v_holds_count: int = 0,
    antiviral_genotype_stratum: str = "TYK2_WT__IFIH1_WT_OR_A946T",
    approved_by_authority_id: str = "OPENISLET_QA_RELEASE_BOARD_V1",
) -> Dict[str, Any]:
    """Construct an authenticated, digest-bound prior bank-qualification record for storage in an external trusted store."""
    pvid = product_variant_id if product_variant_id is not None else product_variant
    rec: Dict[str, Any] = {
        "schema_version": BANK_QUAL_RECORD_SCHEMA_VERSION,
        "operational_tier": operational_tier,
        "verdict": verdict,
        "mcb_id": mcb_id,
        "product_variant_id": pvid,
        "product_variant": pvid,
        "antiviral_genotype_stratum": antiviral_genotype_stratum,
        "bank_lot_id": bank_lot_id,
        "bank_payload_sha256": bank_payload_sha256,
        "approved_by_authority_id": approved_by_authority_id,
        "legacy_tier": legacy_tier,
        "legacy_evaluator_passed": bool(legacy_evaluator_passed),
        "legacy_safety_kill_s9_triggered": bool(legacy_safety_kill_s9_triggered),
        "gate0v_verdict": gate0v_verdict,
        "gate0v_evaluator_passed": bool(gate0v_evaluator_passed),
        "gate0v_hard_stops_count": int(gate0v_hard_stops_count),
        "gate0v_holds_count": int(gate0v_holds_count),
    }
    rec["sha256"] = compute_canonical_qualification_artifact_sha256(rec)
    return rec


def build_authenticated_process_qualification_record(
    *,
    product_variant_id: str | None = None,
    product_variant: str | None = None,
    process_qual_id: str,
    process_qual_payload_sha256: str | None = None,
    verdict: str = "PASS_AUTOLOGOUS_D1B_PROCESS_QUALIFICATION",
    operational_tier: str = "AUTOLOGOUS_D1B_PROCESS_QUAL",
    underlying_gate0v_verdict: str = "PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL",
    underlying_gate0v_passed: bool = True,
    underlying_hard_stops_count: int = 0,
    underlying_holds_count: int = 0,
    approved_by_authority_id: str = "OPENISLET_QA_RELEASE_BOARD_V1",
) -> Dict[str, Any]:
    """Construct an authenticated prior autologous D1b process-qualification record aligned to autologous family semantics."""
    pvid = product_variant_id if product_variant_id is not None else product_variant
    pq_sha = (
        process_qual_payload_sha256
        if process_qual_payload_sha256 is not None
        else hashlib.sha256(f"OPENISLET_PROC_QUAL_PAYLOAD::{pvid}::{process_qual_id}".encode("utf-8")).hexdigest()
    )
    rec: Dict[str, Any] = {
        "schema_version": PROC_QUAL_RECORD_SCHEMA_VERSION,
        "operational_tier": operational_tier,
        "verdict": verdict,
        "product_variant_id": pvid,
        "product_variant": pvid,
        "process_qual_id": process_qual_id,
        "process_qual_payload_sha256": pq_sha,
        "approved_by_authority_id": approved_by_authority_id,
        "underlying_gate0v_verdict": underlying_gate0v_verdict,
        "underlying_gate0v_passed": bool(underlying_gate0v_passed),
        "underlying_hard_stops_count": int(underlying_hard_stops_count),
        "underlying_holds_count": int(underlying_holds_count),
    }
    rec["sha256"] = compute_canonical_qualification_artifact_sha256(rec)
    return rec


def compute_nw08_ocr_record_sha256(record: Dict[str, Any]) -> str:
    """R10-B1 Canonical SHA-256 of a bound NW-08 measured-OCR record excluding `ocr_record_sha256`."""
    body = {k: v for k, v in record.items() if k != "ocr_record_sha256"}
    canonical = _canonical_json_dumps(body)
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def _safe_nw08_ocr_record_sha256(record: Dict[str, Any]) -> str | None:
    """Return canonical NW-08 OCR record SHA-256 or None if record contains non-finite, excessive depth, or non-JSON values."""
    try:
        return compute_nw08_ocr_record_sha256(record)
    except (TypeError, ValueError, OverflowError, RecursionError):
        return None


def build_bound_nw08_ocr_record(
    *,
    lot_id: str,
    mcb_id: str,
    product_variant_id: str,
    route_id: str,
    lot_payload_sha256: str,
    measured_ocr: float,
    uncertainty_se: float,
    measurement_record_id: str,
    measurement_evidence_sha256: str,
    measurement_timestamp_utc: str = "2026-11-29T00:00:00Z",
    baseline_min_face_mmhg: float | None = None,
    baseline_vasc_ocr_mult: float | None = None,
    p_bed_mmhg: float | None = None,
    local_3d_slope_mmhg_per_pct: float | None = None,
    z_one_sided_95: float | None = None,
    floor_mmhg: float | None = None,
    always_solve_3d: bool | None = None,
    ocr_uncertainty_model: str | None = None,
    ocr_replicates_n: int | None = None,
    ocr_degrees_of_freedom: int | None = None,
    ocr_uncertainty_provenance: str | None = None,
    measured_ocr_u95_override: float | None = None,
) -> Dict[str, Any]:
    """
    R10-B1 + R14-B2 Construct a cryptographically lot-, geometry-, evidence-, and
    inferential-model-bound NW-08 measured-OCR sidecar record for coupled composite release
    (`--nw08-ocr-json`). Whenever `uncertainty_se > 0`, explicit inferential provenance
    (`ocr_uncertainty_model` + `ocr_replicates_n`/`ocr_degrees_of_freedom` or
    `ocr_uncertainty_provenance`/`measured_ocr_u95_override`) is bound into `ocr_record_sha256`.
    """
    rec: Dict[str, Any] = {
        "lot_id": lot_id,
        "mcb_id": mcb_id,
        "product_variant_id": product_variant_id,
        "route_id": route_id,
        "lot_payload_sha256": lot_payload_sha256,
        "measured_ocr": measured_ocr,
        "uncertainty_se": uncertainty_se,
        "measurement_record_id": measurement_record_id,
        "measurement_evidence_sha256": measurement_evidence_sha256,
        "measurement_timestamp_utc": measurement_timestamp_utc,
    }
    for k, v in (
        ("baseline_min_face_mmhg", baseline_min_face_mmhg),
        ("baseline_vasc_ocr_mult", baseline_vasc_ocr_mult),
        ("p_bed_mmhg", p_bed_mmhg),
        ("local_3d_slope_mmhg_per_pct", local_3d_slope_mmhg_per_pct),
        ("z_one_sided_95", z_one_sided_95),
        ("floor_mmhg", floor_mmhg),
        ("always_solve_3d", always_solve_3d),
        ("ocr_uncertainty_model", ocr_uncertainty_model),
        ("ocr_replicates_n", ocr_replicates_n),
        ("ocr_degrees_of_freedom", ocr_degrees_of_freedom),
        ("ocr_uncertainty_provenance", ocr_uncertainty_provenance),
        ("measured_ocr_u95_override", measured_ocr_u95_override),
    ):
        if v is not None:
            rec[k] = v
    rec["ocr_record_sha256"] = compute_nw08_ocr_record_sha256(rec)
    return rec


def write_record_to_trusted_qualification_store(
    store_path: Path | str,
    record: Dict[str, Any],
    *,
    category: str = "bank_qualifications",
    archived_payload: Dict[str, Any] | None = None,
    store_authority_id: str = "OPENISLET_QA_RELEASE_BOARD_V1",
) -> Path:
    """
    Persist an approved qualification or NW-08 OCR measurement record into an independent external
    trusted store (either a registry JSON file or a directory of sha256-indexed JSON files).
    """
    sp = Path(store_path)
    rec_sha = record.get("ocr_record_sha256") if category == "nw08_ocr_records" else record.get("sha256")
    if not _is_valid_sha256_hex(rec_sha):
        raise ValueError(
            "Record must carry a valid 64-hex sha256 (or ocr_record_sha256 for nw08_ocr_records) before writing to trusted store"
        )
    if sp.suffix.lower() == ".json":
        if sp.is_file():
            doc = strict_json_load_file(sp, preserve_boundary_decimals=False)
        else:
            doc = {
                "schema_version": TRUSTED_STORE_SCHEMA_VERSION,
                "store_authority_id": store_authority_id,
                "bank_qualifications": {},
                "process_qualifications": {},
                "archived_payloads": {},
            }
        doc.setdefault(category, {})[rec_sha] = copy.deepcopy(record)
        if archived_payload is not None:
            p_sha = archived_payload.get("payload_sha256") or compute_canonical_lot_sha256(archived_payload)
            doc.setdefault("archived_payloads", {})[p_sha] = copy.deepcopy(archived_payload)
        sp.parent.mkdir(parents=True, exist_ok=True)
        sp.write_text(json.dumps(doc, indent=2, sort_keys=True, allow_nan=False) + "\n", encoding="utf-8")
        return sp
    # Directory store layout
    cat_dir = sp / category
    cat_dir.mkdir(parents=True, exist_ok=True)
    rec_file = cat_dir / f"{rec_sha}.json"
    rec_file.write_text(json.dumps(record, indent=2, sort_keys=True, allow_nan=False) + "\n", encoding="utf-8")
    if archived_payload is not None:
        arch_dir = sp / "archived_payloads"
        arch_dir.mkdir(parents=True, exist_ok=True)
        p_sha = archived_payload.get("payload_sha256") or compute_canonical_lot_sha256(archived_payload)
        (arch_dir / f"{p_sha}.json").write_text(
            json.dumps(archived_payload, indent=2, sort_keys=True, allow_nan=False) + "\n", encoding="utf-8"
        )
    return rec_file


def resolve_and_verify_trusted_nw08_ocr_record(
    store_path: Path | str | None,
    *,
    expected_ocr_record_sha256: Any,
    submitted_ocr_record: Dict[str, Any],
    require_store_entry: bool = False,
) -> Tuple[bool, List[str], Dict[str, Any]]:
    """
    R10-B1 Verify a coupled NW-08 OCR record against an independent external
    `--trusted-qualification-store` (`nw08_ocr_records` registry bucket or directory) whenever:
      - `require_store_entry` is True (e.g., lot declares `require_trusted_nw08_ocr_record: true`), OR
      - the provided external store tracks `nw08_ocr_records` (non-empty JSON dict or `nw08_ocr_records/` dir).
    Uses `strict_json_load_file` and checks exact canonical SHA-256 + full-record equality.
    """
    if store_path is None:
        if require_store_entry:
            return (
                False,
                [
                    "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE",
                    "HOLD_NW08_COUPLED_EXTERNAL_OCR_STORE_REQUIRED_BUT_NOT_PROVIDED",
                ],
                {"checked": True, "required": True, "verified": False, "source": None},
            )
        return True, [], {"checked": False, "required": False, "verified": None, "source": "self_digest_and_lot_binding_only"}

    if not isinstance(store_path, (Path, str)):
        return (
            False,
            ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_NW08_COUPLED_EXTERNAL_OCR_STORE_INVALID_PATH"],
            {"checked": True, "required": require_store_entry, "verified": False, "source": None},
        )
    sp = Path(store_path)
    if not sp.exists():
        if require_store_entry:
            return (
                False,
                ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_NW08_COUPLED_EXTERNAL_OCR_STORE_MISSING"],
                {"checked": True, "required": True, "verified": False, "source": sp.name},
            )
        return True, [], {"checked": False, "required": False, "verified": None, "source": sp.name}

    try:
        stored_rec: Dict[str, Any] | None = None
        store_tracks_ocr = False
        store_source = sp.name

        if sp.is_file():
            doc = strict_json_load_file(sp, max_int_abs=MAX_STRICT_JSON_INT_ABS)
            if not isinstance(doc, dict):
                return (
                    False,
                    ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_NW08_COUPLED_EXTERNAL_OCR_STORE_MALFORMED"],
                    {"checked": True, "required": True, "verified": False, "source": f"registry_file:{sp.name}"},
                )
            bucket = doc.get("nw08_ocr_records")
            if bucket is not None:
                if not isinstance(bucket, dict):
                    return (
                        False,
                        ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_NW08_COUPLED_EXTERNAL_OCR_STORE_MALFORMED_BUCKET"],
                        {"checked": True, "required": True, "verified": False, "source": f"registry_file:{sp.name}"},
                    )
                if len(bucket) > 0:
                    store_tracks_ocr = True
                    cand = bucket.get(expected_ocr_record_sha256) if isinstance(expected_ocr_record_sha256, str) else None
                    if isinstance(cand, dict):
                        stored_rec = cand
            store_source = f"registry_file:{sp.name}"
        elif sp.is_dir():
            ocr_dir = sp / "nw08_ocr_records"
            if ocr_dir.exists() and not ocr_dir.is_dir():
                return (
                    False,
                    ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_NW08_COUPLED_EXTERNAL_OCR_STORE_MALFORMED_BUCKET"],
                    {"checked": True, "required": True, "verified": False, "source": f"store_dir:{sp.name}"},
                )
            if ocr_dir.is_dir():
                store_tracks_ocr = True
                if isinstance(expected_ocr_record_sha256, str) and _is_valid_sha256_hex(expected_ocr_record_sha256):
                    cand_f = ocr_dir / f"{expected_ocr_record_sha256}.json"
                    if cand_f.is_file():
                        loaded = strict_json_load_file(cand_f, max_int_abs=MAX_STRICT_JSON_INT_ABS)
                        if isinstance(loaded, dict):
                            stored_rec = loaded
            elif (sp / "registry.json").is_file():
                return resolve_and_verify_trusted_nw08_ocr_record(
                    sp / "registry.json",
                    expected_ocr_record_sha256=expected_ocr_record_sha256,
                    submitted_ocr_record=submitted_ocr_record,
                    require_store_entry=require_store_entry,
                )
            store_source = f"store_dir:{sp.name}"
    except StrictJSONDecodeError as exc:
        return (
            False,
            [
                "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE",
                "HOLD_INVALID_INPUT_JSON",
                f"HOLD_NW08_COUPLED_EXTERNAL_OCR_STORE_AMBIGUOUS_OR_NONCANONICAL_JSON:{exc.reason_code}",
            ],
            {"checked": True, "required": True, "verified": False, "source": sp.name},
        )
    except (OSError, UnicodeDecodeError, json.JSONDecodeError, TypeError, ValueError, OverflowError, RecursionError) as exc:
        err_toks = ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_NW08_COUPLED_EXTERNAL_OCR_STORE_UNREADABLE"]
        if isinstance(exc, RecursionError):
            err_toks.extend([
                "HOLD_INVALID_INPUT_JSON",
                "HOLD_NW08_COUPLED_EXTERNAL_OCR_STORE_AMBIGUOUS_OR_NONCANONICAL_JSON:JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED",
            ])
        return (
            False,
            err_toks,
            {"checked": True, "required": True, "verified": False, "source": sp.name},
        )

    if not store_tracks_ocr and not require_store_entry:
        return (
            True,
            [],
            {
                "checked": False,
                "required": False,
                "verified": None,
                "source": store_source,
                "note": "External store does not track nw08_ocr_records; lot-hash and canonical self-digest binding enforced.",
            },
        )

    if not isinstance(stored_rec, dict):
        return (
            False,
            ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_NW08_COUPLED_UNVERIFIED_EXTERNAL_OCR_STORE_RECORD"],
            {"checked": True, "required": True, "verified": False, "source": store_source},
        )

    stored_recomp = _safe_nw08_ocr_record_sha256(stored_rec)
    sub_recomp = _safe_nw08_ocr_record_sha256(submitted_ocr_record)
    try:
        canon_eq = bool(_canonical_json_dumps(stored_rec) == _canonical_json_dumps(submitted_ocr_record))
    except (TypeError, ValueError, OverflowError, RecursionError):
        canon_eq = False
    if (
        stored_recomp is None
        or sub_recomp is None
        or stored_rec.get("ocr_record_sha256") != expected_ocr_record_sha256
        or stored_recomp != expected_ocr_record_sha256
        or sub_recomp != expected_ocr_record_sha256
        or not canon_eq
    ):
        return (
            False,
            ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_NW08_COUPLED_EXTERNAL_OCR_STORE_RECORD_TAMPERED_OR_MISMATCHED"],
            {"checked": True, "required": True, "verified": False, "source": store_source},
        )

    return (
        True,
        [],
        {"checked": True, "required": True, "verified": True, "source": store_source},
    )


def _lookup_in_trusted_qualification_store_with_archive_status(
    store_path: Path | str | None,
    *,
    category: str,
    expected_sha256: Any,
) -> Tuple[Dict[str, Any] | None, Dict[str, Any] | None, List[str], str | None, str]:
    """
    Resolve a prior qualification record AND its archived payload STRICTLY from an
    independently controlled external store path (embedded-dict registry JSON file or
    file-backed directory store), distinguishing absent vs non-object/unreadable/ambiguous archives.
    Enforces `strict_json_load_file` (rejecting duplicate object keys and NaN/Infinity constants)
    across registry, record, and archived payload files. NEVER reads caller-supplied inline lot payloads!
    """
    if store_path is None:
        return None, None, ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE_NOT_PROVIDED"], None, "store_not_provided"
    if not isinstance(store_path, (Path, str)):
        return None, None, ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE_INVALID_PATH_TYPE"], None, "invalid_store_path"
    sp = Path(store_path)
    if not sp.exists():
        return None, None, ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE_PATH_MISSING"], str(sp.name), "store_missing"
    if not _is_valid_sha256_hex(expected_sha256):
        return None, None, ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE_INVALID_REF_SHA256"], str(sp.name), "invalid_ref_sha256"

    try:
        if sp.is_file():
            doc = strict_json_load_file(sp, max_int_abs=MAX_STRICT_JSON_INT_ABS)
            if not isinstance(doc, dict):
                return None, None, ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE_MALFORMED_REGISTRY"], str(sp.name), "malformed_registry"
            bucket = doc.get(category)
            rec: Dict[str, Any] | None = None
            if isinstance(bucket, dict):
                cand = bucket.get(expected_sha256)
                if isinstance(cand, dict):
                    rec = cand
            elif isinstance(bucket, list):
                for item in bucket:
                    if isinstance(item, dict) and item.get("sha256") == expected_sha256:
                        rec = item
                        break
            if rec is None:
                return None, None, ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE_RECORD_NOT_FOUND"], str(sp.name), "record_not_found"

            raw_arch_map = doc.get("archived_payloads")
            p_key = rec.get("bank_payload_sha256") or rec.get("process_qual_payload_sha256")
            archived: Dict[str, Any] | None = None
            if raw_arch_map is None:
                arch_status = "absent"
            elif not isinstance(raw_arch_map, dict):
                arch_status = f"invalid_container_non_object:{type(raw_arch_map).__name__}"
            elif not (isinstance(p_key, str) and _is_valid_sha256_hex(p_key)):
                arch_status = "missing_or_invalid_payload_key"
            elif p_key not in raw_arch_map:
                arch_status = "absent"
            else:
                raw_arch = raw_arch_map[p_key]
                if raw_arch is None:
                    arch_status = "absent_null"
                elif isinstance(raw_arch, dict):
                    archived = raw_arch
                    arch_status = "present_object"
                else:
                    arch_status = f"non_object:{type(raw_arch).__name__}"
            return rec, archived, [], f"registry_file:{sp.name}", arch_status

        if sp.is_dir():
            rec = None
            archived = None
            for cand_path in (sp / category / f"{expected_sha256}.json", sp / f"{expected_sha256}.json"):
                if cand_path.is_file():
                    loaded = strict_json_load_file(cand_path, max_int_abs=MAX_STRICT_JSON_INT_ABS)
                    if isinstance(loaded, dict):
                        rec = loaded
                        break
            if rec is None and (sp / "registry.json").is_file():
                return _lookup_in_trusted_qualification_store_with_archive_status(
                    sp / "registry.json", category=category, expected_sha256=expected_sha256
                )
            if rec is None:
                return None, None, ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE_RECORD_NOT_FOUND"], str(sp.name), "record_not_found"

            p_key = rec.get("bank_payload_sha256") or rec.get("process_qual_payload_sha256")
            arch_dir = sp / "archived_payloads"
            if not (isinstance(p_key, str) and _is_valid_sha256_hex(p_key)):
                arch_status = "missing_or_invalid_payload_key"
            elif arch_dir.exists() and not arch_dir.is_dir():
                arch_status = "invalid_container_non_directory"
            else:
                arch_file = arch_dir / f"{p_key}.json"
                if not arch_file.is_file():
                    arch_status = "absent"
                else:
                    try:
                        loaded_arch = strict_json_load_file(arch_file, max_int_abs=MAX_STRICT_JSON_INT_ABS)
                    except StrictJSONDecodeError as exc:
                        arch_status = f"ambiguous_or_noncanonical_json:{exc.reason_code.lower()}"
                    except RecursionError:
                        arch_status = "ambiguous_or_noncanonical_json:json_depth_or_recursion_limit_exceeded"
                    except (OSError, UnicodeDecodeError, json.JSONDecodeError, TypeError, ValueError, OverflowError):
                        arch_status = "unreadable_or_malformed_json"
                    else:
                        if loaded_arch is None:
                            arch_status = "absent_null"
                        elif isinstance(loaded_arch, dict):
                            archived = loaded_arch
                            arch_status = "present_object"
                        else:
                            arch_status = f"non_object:{type(loaded_arch).__name__}"
            return rec, archived, [], f"store_dir:{sp.name}", arch_status
    except StrictJSONDecodeError as exc:
        return (
            None,
            None,
            [
                "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE",
                "HOLD_INVALID_INPUT_JSON",
                f"HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE_AMBIGUOUS_OR_NONCANONICAL_JSON:{exc.reason_code}",
            ],
            str(sp.name),
            f"ambiguous_or_noncanonical_json:{exc.reason_code.lower()}",
        )
    except RecursionError:
        return (
            None,
            None,
            [
                "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE",
                "HOLD_INVALID_INPUT_JSON",
                "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE_AMBIGUOUS_OR_NONCANONICAL_JSON:JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED",
            ],
            str(sp.name),
            "ambiguous_or_noncanonical_json:json_depth_or_recursion_limit_exceeded",
        )
    except (OSError, UnicodeDecodeError, json.JSONDecodeError, TypeError, ValueError, OverflowError):
        return None, None, ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE_UNREADABLE"], str(sp.name), "store_unreadable"

    return None, None, ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE_UNSUPPORTED_PATH"], str(sp.name), "unsupported_store_path"


def _lookup_in_trusted_qualification_store(
    store_path: Path | str | None,
    *,
    category: str,
    expected_sha256: Any,
) -> Tuple[Dict[str, Any] | None, Dict[str, Any] | None, List[str], str | None]:
    """
    Backward-compatible 4-tuple wrapper around `_lookup_in_trusted_qualification_store_with_archive_status`.
    """
    rec, archived, lookup_errs, store_src, _arch_status = _lookup_in_trusted_qualification_store_with_archive_status(
        store_path,
        category=category,
        expected_sha256=expected_sha256,
    )
    return rec, archived, lookup_errs, store_src


def validate_canonical_composite_envelope(
    composite_doc: Any,
    *,
    openislet_root: Path | None = None,
    expected_tier: str | None = None,
    expected_lot_id: Any = None,
    expected_mcb_id: Any = None,
    expected_product_variant_id: Any = None,
) -> Dict[str, Any]:
    """
    R08-B1 Shared Canonical Composite Envelope Validator executed identically at BOTH:
      1. Direct composite submission (`evaluate_gate0v_composite_release.evaluate_composite_clinical_release`), AND
      2. Archived composite bank verification (`resolve_and_verify_trusted_bank_qualification`).

    Enforces:
      - Canonical top-level `product_variant_id` (mandatory clean non-empty string; alias-only
        `product_variant` is ALWAYS rejected with `HOLD_COMPOSITE_MISSING_TOP_PRODUCT_VARIANT_ID`),
        reconciled with optional `product_variant` alias and nested legacy/Gate-0V `product_variant_id`s.
      - Reconciled `lot_id` (plus top-level/nested lot aliases) and `mcb_id` across top-level,
        `legacy_stage0_observations`, and `gate0v_wholegraft_payload`.
      - Verified top-level canonical `payload_sha256`.
      - Exhaustive reconciliation of EVERY supplied tier field independently (ZERO `or`
        short-circuiting!): top-level `qualification_tier`, top-level `operational_tier`, nested
        `gate0v_wholegraft_payload.qualification_tier` and `.operational_tier`, and any tier field
        supplied on `legacy_stage0_observations` MUST ALL match the active/expected tier, else
        `HOLD_COMPOSITE_OPERATIONAL_TIER_MISMATCH`.
      - Top-level `antiviral_genotype_stratum` (when present) reconciled against nested Gate-0V.
      - Canonical product-family-to-tier allowlist enforcement.
    """
    holds: List[str] = []

    def _add_hold(tok: str) -> None:
        if tok not in holds:
            holds.append(tok)

    if not isinstance(composite_doc, dict):
        return {
            "valid": False,
            "holds": ["HOLD_COMPOSITE_PAYLOAD_NOT_DICT"],
            "top_lot": None,
            "top_mcb": None,
            "top_pvid_raw": None,
            "top_sha": None,
            "computed_comp_sha": None,
            "canonical_product_def": None,
            "canonical_pvid": None,
            "legacy_obs": None,
            "gate0v_obs": None,
            "leg_pvid_canon": None,
            "g0v_pvid_canon": None,
            "qual_tier": None,
            "tier_allowed_for_product": False,
            "planned_nw08_route_id": None,
            "planned_nw08_route_errors": [],
            "planned_nw08_measurement_evidence_sha256": None,
            "planned_nw08_measurement_not_before_utc": None,
            "require_trusted_nw08_ocr_record": False,
        }

    top_lot = composite_doc.get("lot_id")
    top_mcb = composite_doc.get("mcb_id")
    top_pvid_raw = composite_doc.get("product_variant_id")
    top_pv_legacy = composite_doc.get("product_variant")
    top_sha = composite_doc.get("payload_sha256")
    computed_comp_sha = _safe_canonical_lot_sha256(composite_doc)
    if computed_comp_sha is None:
        _add_hold("HOLD_COMPOSITE_NONCANONICAL_OR_NONFINITE_PAYLOAD")

    if not _is_clean_nonempty_str(top_lot):
        _add_hold("HOLD_COMPOSITE_MISSING_TOP_LOT_ID")
    else:
        for ak in ("current_lot_id", "batch_id"):
            if ak in composite_doc and composite_doc.get(ak) is not None and composite_doc.get(ak) != top_lot:
                _add_hold("HOLD_COMPOSITE_TOP_LOT_ALIAS_MISMATCH")
        if expected_lot_id is not None and top_lot != expected_lot_id:
            _add_hold("HOLD_COMPOSITE_TOP_LOT_ID_MISMATCH")

    if not _is_clean_nonempty_str(top_mcb):
        _add_hold("HOLD_COMPOSITE_MISSING_TOP_MCB_ID")
    elif expected_mcb_id is not None and top_mcb != expected_mcb_id:
        _add_hold("HOLD_COMPOSITE_TOP_MCB_ID_MISMATCH")

    canonical_product_def: Dict[str, Any] | None = None
    canonical_pvid: str | None = None
    if not _is_clean_nonempty_str(top_pvid_raw):
        _add_hold("HOLD_COMPOSITE_MISSING_TOP_PRODUCT_VARIANT_ID")
    else:
        canonical_product_def = resolve_canonical_product_variant(top_pvid_raw, openislet_root=openislet_root)
        if canonical_product_def is None:
            _add_hold("HOLD_COMPOSITE_UNREGISTERED_PRODUCT_VARIANT_ID")
        else:
            canonical_pvid = canonical_product_def["product_variant_id"]
            if expected_product_variant_id is not None and canonical_pvid != expected_product_variant_id:
                _add_hold("HOLD_COMPOSITE_TOP_PRODUCT_VARIANT_ID_MISMATCH")

    if top_pv_legacy is not None:
        pv_leg_res = resolve_canonical_product_variant(top_pv_legacy, openislet_root=openislet_root)
        if pv_leg_res is None:
            _add_hold("HOLD_COMPOSITE_UNREGISTERED_TOP_PRODUCT_VARIANT_ALIAS")
        else:
            if canonical_pvid is not None and pv_leg_res["product_variant_id"] != canonical_pvid:
                _add_hold("HOLD_COMPOSITE_TOP_PRODUCT_VARIANT_ALIAS_MISMATCH")
            if expected_product_variant_id is not None and pv_leg_res["product_variant_id"] != expected_product_variant_id:
                _add_hold("HOLD_COMPOSITE_TOP_PRODUCT_VARIANT_ALIAS_MISMATCH")

    if not (_is_valid_sha256_hex(top_sha) and top_sha == computed_comp_sha):
        _add_hold("HOLD_COMPOSITE_PAYLOAD_SHA256_MISMATCH")

    legacy_obs = composite_doc.get("legacy_stage0_observations")
    gate0v_obs = composite_doc.get("gate0v_wholegraft_payload")
    if not isinstance(legacy_obs, dict):
        _add_hold("HOLD_COMPOSITE_MISSING_LEGACY_STAGE0_OBSERVATIONS")
    if not isinstance(gate0v_obs, dict):
        _add_hold("HOLD_COMPOSITE_MISSING_GATE0V_WHOLEGRAFT_PAYLOAD")

    leg_pvid_canon: str | None = None
    if isinstance(legacy_obs, dict):
        leg_lot_keys_found: List[Tuple[str, Any]] = []
        for lk in ("current_lot_id", "lot_id", "batch_id"):
            if lk in legacy_obs and legacy_obs.get(lk) is not None:
                leg_lot_keys_found.append((lk, legacy_obs.get(lk)))
        if (
            not leg_lot_keys_found
            or any(val != top_lot for _, val in leg_lot_keys_found)
            or (expected_lot_id is not None and any(val != expected_lot_id for _, val in leg_lot_keys_found))
        ):
            _add_hold("HOLD_COMPOSITE_LEGACY_LOT_ID_MISMATCH")
        if legacy_obs.get("mcb_id") != top_mcb or (expected_mcb_id is not None and legacy_obs.get("mcb_id") != expected_mcb_id):
            _add_hold("HOLD_COMPOSITE_LEGACY_MCB_ID_MISMATCH")

        leg_pvid_raw = legacy_obs.get("product_variant_id")
        if not _is_clean_nonempty_str(leg_pvid_raw):
            _add_hold("HOLD_COMPOSITE_LEGACY_MISSING_PRODUCT_VARIANT_ID")
        else:
            leg_pvid_res = resolve_canonical_product_variant(leg_pvid_raw, openislet_root=openislet_root)
            if leg_pvid_res is None:
                _add_hold("HOLD_COMPOSITE_LEGACY_UNREGISTERED_PRODUCT_VARIANT_ID")
            else:
                leg_pvid_canon = leg_pvid_res["product_variant_id"]
                if (canonical_pvid is not None and leg_pvid_canon != canonical_pvid) or (
                    expected_product_variant_id is not None and leg_pvid_canon != expected_product_variant_id
                ):
                    _add_hold("HOLD_COMPOSITE_LEGACY_PRODUCT_VARIANT_ID_MISMATCH")
        if "product_variant" in legacy_obs and legacy_obs.get("product_variant") is not None:
            lpv_res = resolve_canonical_product_variant(legacy_obs.get("product_variant"), openislet_root=openislet_root)
            if (
                lpv_res is None
                or (canonical_pvid is not None and lpv_res["product_variant_id"] != canonical_pvid)
                or (expected_product_variant_id is not None and lpv_res["product_variant_id"] != expected_product_variant_id)
            ):
                _add_hold("HOLD_COMPOSITE_LEGACY_PRODUCT_VARIANT_ALIAS_MISMATCH")

    qual_tier: str | None = None
    g0v_pvid_canon: str | None = None
    if isinstance(gate0v_obs, dict):
        qual_tier = gate0v_obs.get("qualification_tier") if isinstance(gate0v_obs.get("qualification_tier"), str) else None
        if gate0v_obs.get("lot_id") != top_lot or (expected_lot_id is not None and gate0v_obs.get("lot_id") != expected_lot_id):
            _add_hold("HOLD_COMPOSITE_GATE0V_LOT_ID_MISMATCH")
        if gate0v_obs.get("mcb_id") != top_mcb or (expected_mcb_id is not None and gate0v_obs.get("mcb_id") != expected_mcb_id):
            _add_hold("HOLD_COMPOSITE_GATE0V_MCB_ID_MISMATCH")
        g0v_pvid_raw = gate0v_obs.get("product_variant_id")
        if not _is_clean_nonempty_str(g0v_pvid_raw):
            _add_hold("HOLD_COMPOSITE_GATE0V_MISSING_PRODUCT_VARIANT_ID")
        else:
            g0v_pvid_res = resolve_canonical_product_variant(g0v_pvid_raw, openislet_root=openislet_root)
            if g0v_pvid_res is None:
                _add_hold("HOLD_COMPOSITE_GATE0V_UNREGISTERED_PRODUCT_VARIANT_ID")
            else:
                g0v_pvid_canon = g0v_pvid_res["product_variant_id"]
                if (canonical_pvid is not None and g0v_pvid_canon != canonical_pvid) or (
                    expected_product_variant_id is not None and g0v_pvid_canon != expected_product_variant_id
                ):
                    _add_hold("HOLD_COMPOSITE_GATE0V_PRODUCT_VARIANT_ID_MISMATCH")
        if "product_variant" in gate0v_obs and gate0v_obs.get("product_variant") is not None:
            gpv_res = resolve_canonical_product_variant(gate0v_obs.get("product_variant"), openislet_root=openislet_root)
            if (
                gpv_res is None
                or (canonical_pvid is not None and gpv_res["product_variant_id"] != canonical_pvid)
                or (expected_product_variant_id is not None and gpv_res["product_variant_id"] != expected_product_variant_id)
            ):
                _add_hold("HOLD_COMPOSITE_GATE0V_PRODUCT_VARIANT_ALIAS_MISMATCH")

    if not (isinstance(qual_tier, str) and qual_tier in ALLOWED_QUALIFICATION_TIERS):
        _add_hold("HOLD_COMPOSITE_MISSING_OR_INVALID_QUALIFICATION_TIER")

    # R08-B1: Exhaustively reconcile EVERY supplied tier field across top-level, Gate-0V, and legacy
    # sections independently (NEVER short-circuit `qualification_tier or operational_tier`!).
    target_tier = expected_tier if expected_tier is not None else qual_tier
    if target_tier is not None:
        if expected_tier is not None and qual_tier != expected_tier:
            _add_hold("HOLD_COMPOSITE_OPERATIONAL_TIER_MISMATCH")
        if "operational_tier" in composite_doc and composite_doc.get("operational_tier") != target_tier:
            _add_hold("HOLD_COMPOSITE_OPERATIONAL_TIER_MISMATCH")
        if "qualification_tier" in composite_doc and composite_doc.get("qualification_tier") != target_tier:
            _add_hold("HOLD_COMPOSITE_OPERATIONAL_TIER_MISMATCH")
        if isinstance(gate0v_obs, dict) and "operational_tier" in gate0v_obs and gate0v_obs.get("operational_tier") != target_tier:
            _add_hold("HOLD_COMPOSITE_OPERATIONAL_TIER_MISMATCH")
        if isinstance(legacy_obs, dict):
            if "operational_tier" in legacy_obs and legacy_obs.get("operational_tier") != target_tier:
                _add_hold("HOLD_COMPOSITE_OPERATIONAL_TIER_MISMATCH")
            if "qualification_tier" in legacy_obs and legacy_obs.get("qualification_tier") != target_tier:
                _add_hold("HOLD_COMPOSITE_OPERATIONAL_TIER_MISMATCH")

    # Reconcile optional top-level antiviral_genotype_stratum against nested gate0v_wholegraft_payload
    if (
        "antiviral_genotype_stratum" in composite_doc
        and isinstance(gate0v_obs, dict)
        and composite_doc.get("antiviral_genotype_stratum") != gate0v_obs.get("antiviral_genotype_stratum")
    ):
        _add_hold("HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM")

    # R10-B1: Extract & reconcile any lot-declared planned NW-08 geometry route & evidence constraints
    # across top-level composite envelope and nested gate0v_wholegraft_payload (ZERO unhashable lookups!).
    declared_routes: List[str] = []
    planned_route_errors: List[str] = []
    for container in (composite_doc, gate0v_obs if isinstance(gate0v_obs, dict) else None):
        if container is None:
            continue
        for rk in _LOT_PLANNED_ROUTE_KEYS:
            if rk in container and container.get(rk) is not None:
                rv = container.get(rk)
                if not (_is_clean_nonempty_str(rv) and rv in CANONICAL_NW08_ROUTE_IDS):
                    if "HOLD_NW08_COUPLED_INVALID_LOT_PLANNED_ROUTE" not in planned_route_errors:
                        planned_route_errors.append("HOLD_NW08_COUPLED_INVALID_LOT_PLANNED_ROUTE")
                    _add_hold("HOLD_NW08_COUPLED_INVALID_LOT_PLANNED_ROUTE")
                else:
                    declared_routes.append(rv)
    planned_nw08_route_id: str | None = None
    if declared_routes:
        if len(set(declared_routes)) > 1:
            if "HOLD_NW08_COUPLED_CONFLICTING_LOT_PLANNED_ROUTE" not in planned_route_errors:
                planned_route_errors.append("HOLD_NW08_COUPLED_CONFLICTING_LOT_PLANNED_ROUTE")
            _add_hold("HOLD_NW08_COUPLED_CONFLICTING_LOT_PLANNED_ROUTE")
        elif not planned_route_errors:
            planned_nw08_route_id = declared_routes[0]

    declared_ev_shas: List[str] = []
    for container in (composite_doc, gate0v_obs if isinstance(gate0v_obs, dict) else None):
        if container is None:
            continue
        if "nw08_measurement_evidence_sha256" in container and container.get("nw08_measurement_evidence_sha256") is not None:
            ev_v = container.get("nw08_measurement_evidence_sha256")
            if not _is_valid_sha256_hex(ev_v):
                if "HOLD_NW08_COUPLED_INVALID_LOT_MEASUREMENT_EVIDENCE_SHA256" not in planned_route_errors:
                    planned_route_errors.append("HOLD_NW08_COUPLED_INVALID_LOT_MEASUREMENT_EVIDENCE_SHA256")
                _add_hold("HOLD_NW08_COUPLED_INVALID_LOT_MEASUREMENT_EVIDENCE_SHA256")
            else:
                declared_ev_shas.append(ev_v)
    planned_ev_sha: str | None = None
    if declared_ev_shas:
        if len(set(declared_ev_shas)) > 1:
            if "HOLD_NW08_COUPLED_CONFLICTING_LOT_MEASUREMENT_EVIDENCE_SHA256" not in planned_route_errors:
                planned_route_errors.append("HOLD_NW08_COUPLED_CONFLICTING_LOT_MEASUREMENT_EVIDENCE_SHA256")
            _add_hold("HOLD_NW08_COUPLED_CONFLICTING_LOT_MEASUREMENT_EVIDENCE_SHA256")
        elif "HOLD_NW08_COUPLED_INVALID_LOT_MEASUREMENT_EVIDENCE_SHA256" not in planned_route_errors:
            planned_ev_sha = declared_ev_shas[0]

    planned_not_before_utc: str | None = None
    if "nw08_measurement_not_before_utc" in composite_doc and composite_doc.get("nw08_measurement_not_before_utc") is not None:
        nb_raw = composite_doc.get("nw08_measurement_not_before_utc")
        if _parse_strict_utc_timestamp(nb_raw) is None:
            planned_route_errors.append("HOLD_NW08_COUPLED_INVALID_LOT_NOT_BEFORE_TIMESTAMP_UTC")
            _add_hold("HOLD_NW08_COUPLED_INVALID_LOT_NOT_BEFORE_TIMESTAMP_UTC")
        else:
            planned_not_before_utc = nb_raw

    # R11-B1: Strictly validate `require_trusted_nw08_ocr_record` as `bool` whenever present in
    # top-level composite envelope OR nested `gate0v_wholegraft_payload` (non-bool including None/int/str
    # or conflicting True/False fails closed to HOLD!).
    req_trusted_ocr = False
    declared_req_ocr: List[bool] = []
    for container in (composite_doc, gate0v_obs if isinstance(gate0v_obs, dict) else None):
        if container is None:
            continue
        if "require_trusted_nw08_ocr_record" in container:
            rt_raw = container.get("require_trusted_nw08_ocr_record")
            if not _is_strict_bool(rt_raw):
                if "HOLD_NW08_COUPLED_INVALID_REQUIRE_TRUSTED_OCR_FLAG" not in planned_route_errors:
                    planned_route_errors.append("HOLD_NW08_COUPLED_INVALID_REQUIRE_TRUSTED_OCR_FLAG")
                _add_hold("HOLD_NW08_COUPLED_INVALID_REQUIRE_TRUSTED_OCR_FLAG")
            else:
                declared_req_ocr.append(bool(rt_raw))
    if declared_req_ocr:
        if len(set(declared_req_ocr)) > 1:
            if "HOLD_NW08_COUPLED_CONFLICTING_REQUIRE_TRUSTED_OCR_FLAG" not in planned_route_errors:
                planned_route_errors.append("HOLD_NW08_COUPLED_CONFLICTING_REQUIRE_TRUSTED_OCR_FLAG")
            _add_hold("HOLD_NW08_COUPLED_CONFLICTING_REQUIRE_TRUSTED_OCR_FLAG")
            req_trusted_ocr = True
        elif "HOLD_NW08_COUPLED_INVALID_REQUIRE_TRUSTED_OCR_FLAG" not in planned_route_errors:
            req_trusted_ocr = declared_req_ocr[0]

    # R13-B3: Subtractive policy enforced identically at direct admission AND archived replay —
    # NW-08 measured-OCR release gating applies strictly to clinical release lots
    # (`LOT_RELEASE_SURROGATE` / `AUTOLOGOUS_D1B_PROCESS_QUAL`), NEVER to `BANK_QUALIFICATION`!
    if req_trusted_ocr and (qual_tier == "BANK_QUALIFICATION" or expected_tier == "BANK_QUALIFICATION"):
        if "HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION" not in planned_route_errors:
            planned_route_errors.append("HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION")
        _add_hold("HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION")

    tier_allowed_for_product = False
    if canonical_product_def is not None and isinstance(qual_tier, str) and qual_tier in ALLOWED_QUALIFICATION_TIERS:
        tier_allowed_for_product, tier_family_errs = is_qualification_tier_allowed_for_product(
            canonical_product_def, qual_tier
        )
        for te in tier_family_errs:
            _add_hold(te)

    return {
        "valid": len(holds) == 0,
        "holds": holds,
        "top_lot": top_lot,
        "top_mcb": top_mcb,
        "top_pvid_raw": top_pvid_raw,
        "top_sha": top_sha,
        "computed_comp_sha": computed_comp_sha,
        "canonical_product_def": canonical_product_def,
        "canonical_pvid": canonical_pvid,
        "legacy_obs": legacy_obs,
        "gate0v_obs": gate0v_obs,
        "leg_pvid_canon": leg_pvid_canon,
        "g0v_pvid_canon": g0v_pvid_canon,
        "qual_tier": qual_tier,
        "tier_allowed_for_product": tier_allowed_for_product,
        "planned_nw08_route_id": planned_nw08_route_id,
        "planned_nw08_route_errors": planned_route_errors,
        "planned_nw08_measurement_evidence_sha256": planned_ev_sha,
        "planned_nw08_measurement_not_before_utc": planned_not_before_utc,
        "require_trusted_nw08_ocr_record": req_trusted_ocr,
    }


def resolve_and_verify_trusted_bank_qualification(
    trusted_qualification_store: Path | str | None,
    *,
    expected_sha256: Any,
    expected_mcb_id: Any,
    expected_product_variant_id: Any,
    expected_genotype_stratum: Any | None = None,
    inline_record_if_supplied: Any = None,
    openislet_root: Path | None = None,
    hold_prefix: str = "HOLD_GATE0V_PRIOR_BANK_QUAL",
    legacy_evaluator: Any = None,
    composite_bank_revalidator: Any = None,
    _revalidating_archived_bank: bool = False,
) -> Tuple[bool, List[str], Dict[str, Any]]:
    """
    Resolve and verify prior MCB BANK_QUALIFICATION approval SOLELY from an independently
    controlled external trusted qualification store (B1 / R04-B2 / R05-B1 / R06-B4 / R07-B1 / R08-B1).
    Self-attested records embedded inside the caller's lot bundle are NEVER trusted as proof
    of prior approval, and a complete, canonical, self-digest-verified, envelope-aligned,
    nested-identity-reconciled, and live-evaluator-reverified archived original BANK_QUALIFICATION
    payload is MANDATORY in BOTH store layouts (embedded registry JSON and file-backed directory store):
      - Composite clinical release (`legacy_evaluator is not None`): REQUIRES a complete
        composite bank archive containing BOTH `gate0v_wholegraft_payload` AND
        `legacy_stage0_observations`, validates the archived composite envelope through the EXACT
        SAME `validate_canonical_composite_envelope(...)` contract as direct composite submission
        (mandatory canonical top-level `product_variant_id`, exhaustive reconciliation of EVERY
        supplied tier field against `"BANK_QUALIFICATION"`), and requires BOTH live Gate-0V
        revalidation (`archived_bank_payload_live_g0v_revalidation_passed == True`), live legacy
        `wetlab_contract` revalidation (`archived_bank_payload_live_legacy_revalidation_passed == True`),
        and (when provided by the composite wrapper) live composite bank replay
        (`archived_bank_payload_live_composite_revalidation_passed == True`). Plain standalone
        whole-graft-only bank archives lacking archived legacy observations are REJECTED immediately
        with `HOLD_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE`.
      - Standalone `verify_iip0043` evidence boundary (`legacy_evaluator is None`): accepts
        either a complete canonical standalone Gate-0V `BANK_QUALIFICATION` payload (requiring
        canonical `product_variant_id` and reconciling any `operational_tier` against
        `"BANK_QUALIFICATION"`) OR a complete canonical composite bank bundle validated by
        `validate_canonical_composite_envelope(...)`, requiring live Gate-0V revalidation.
    """
    require_composite_legacy_replay: bool = legacy_evaluator is not None
    if _revalidating_archived_bank:
        return False, ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD", f"{hold_prefix}_RECURSIVE_REVALIDATION_BARRED"], {
            "authenticated": False,
            "resolution_source": None,
            "self_attested_inline_record_ignored": inline_record_if_supplied is not None,
            "archived_bank_payload_verified": False,
            "archived_bank_payload_status": "recursive_revalidation_barred",
            "archived_bank_payload_live_revalidation_passed": False,
            "archived_bank_payload_live_g0v_revalidation_passed": False,
            "archived_bank_payload_live_legacy_revalidation_required": require_composite_legacy_replay,
            "archived_bank_payload_live_legacy_revalidation_passed": False if require_composite_legacy_replay else None,
            "archived_bank_payload_live_composite_revalidation_passed": False if composite_bank_revalidator is not None else None,
        }
    rec, archived_payload, lookup_errs, store_src, archive_status = (
        _lookup_in_trusted_qualification_store_with_archive_status(
            trusted_qualification_store,
            category="bank_qualifications",
            expected_sha256=expected_sha256,
        )
    )
    if lookup_errs or rec is None:
        return False, lookup_errs, {
            "authenticated": False,
            "resolution_source": store_src,
            "self_attested_inline_record_ignored": inline_record_if_supplied is not None,
            "archived_bank_payload_verified": False,
            "archived_bank_payload_status": archive_status,
            "archived_bank_payload_live_revalidation_passed": False,
            "archived_bank_payload_live_g0v_revalidation_passed": False,
            "archived_bank_payload_live_legacy_revalidation_required": require_composite_legacy_replay,
            "archived_bank_payload_live_legacy_revalidation_passed": False if require_composite_legacy_replay else None,
            "archived_bank_payload_live_composite_revalidation_passed": False if composite_bank_revalidator is not None else None,
        }

    errs: List[str] = []

    def _add_err(tok: str) -> None:
        if tok not in errs:
            errs.append(tok)

    rec_sha = rec.get("sha256")
    computed_sha = _safe_canonical_qualification_artifact_sha256(rec)
    if computed_sha is None or not _is_valid_sha256_hex(rec_sha) or rec_sha != computed_sha:
        _add_err(f"{hold_prefix}_RECORD_INTERNAL_SHA256_MISMATCH")
    elif rec_sha != expected_sha256:
        _add_err(f"{hold_prefix}_RECORD_SHA256_DOES_NOT_MATCH_BRIDGED_DIGEST")

    if not _is_valid_identifier(rec.get("approved_by_authority_id")):
        _add_err(f"{hold_prefix}_MISSING_APPROVED_BY_AUTHORITY_ID")
    if rec.get("operational_tier") != "BANK_QUALIFICATION":
        _add_err(f"{hold_prefix}_WRONG_OPERATIONAL_TIER")
    if "qualification_tier" in rec and rec.get("qualification_tier") != "BANK_QUALIFICATION":
        _add_err(f"{hold_prefix}_WRONG_OPERATIONAL_TIER")
    if rec.get("verdict") != "PASS_COMPOSITE_BANK_QUALIFICATION":
        _add_err(f"{hold_prefix}_VERDICT_NOT_PASS_COMPOSITE_BANK_QUALIFICATION")
    if rec.get("mcb_id") != expected_mcb_id:
        _add_err(f"{hold_prefix}_MCB_ID_MISMATCH")

    rec_pvid_raw = rec.get("product_variant_id")
    if not _is_clean_nonempty_str(rec_pvid_raw):
        _add_err(f"{hold_prefix}_MISSING_RECORD_PRODUCT_VARIANT_ID")
    rec_pvid_res = (
        resolve_canonical_product_variant(rec_pvid_raw, openislet_root=openislet_root)
        if _is_clean_nonempty_str(rec_pvid_raw)
        else None
    )
    rec_pvid_canon = rec_pvid_res["product_variant_id"] if rec_pvid_res is not None else rec_pvid_raw
    if rec_pvid_canon != expected_product_variant_id:
        _add_err(f"{hold_prefix}_PRODUCT_VARIANT_ID_MISMATCH")
    if "product_variant" in rec and rec.get("product_variant") is not None:
        rpv_res = resolve_canonical_product_variant(rec.get("product_variant"), openislet_root=openislet_root)
        if rpv_res is None or rpv_res["product_variant_id"] != expected_product_variant_id:
            _add_err(f"{hold_prefix}_PRODUCT_VARIANT_ID_MISMATCH")

    # R04-B1: Bank qualification & LOT_RELEASE_SURROGATE require an allogeneic MCB-banked product family!
    exp_pvid_res = resolve_canonical_product_variant(expected_product_variant_id, openislet_root=openislet_root)
    if rec_pvid_res is None:
        errs.append(f"{hold_prefix}_UNREGISTERED_RECORD_PRODUCT_VARIANT_ID")
    else:
        tier_ok_rec, tier_errs_rec = is_qualification_tier_allowed_for_product(rec_pvid_res, "BANK_QUALIFICATION")
        if not tier_ok_rec:
            errs.extend(tier_errs_rec)
    if exp_pvid_res is not None:
        tier_ok_exp, tier_errs_exp = is_qualification_tier_allowed_for_product(exp_pvid_res, "LOT_RELEASE_SURROGATE")
        if not tier_ok_exp:
            for te in tier_errs_exp:
                if te not in errs:
                    errs.append(te)

    # Verify underlying dual-evaluator PASS outcomes recorded in the trusted bank approval!
    if rec.get("legacy_tier") != "READY_FOR_ENCAPSULATION_COMPLETE_STAGE0_EVIDENCE":
        errs.append(f"{hold_prefix}_UNDERLYING_LEGACY_TIER_NOT_READY")
    if rec.get("legacy_evaluator_passed") is not True or rec.get("legacy_safety_kill_s9_triggered") is not False:
        errs.append(f"{hold_prefix}_UNDERLYING_LEGACY_EVALUATOR_NOT_PASSED")
    if rec.get("gate0v_verdict") != "PASS_WHOLEGRAFT_BANK_QUALIFICATION":
        errs.append(f"{hold_prefix}_UNDERLYING_GATE0V_VERDICT_NOT_PASS_BANK")
    if rec.get("gate0v_evaluator_passed") is not True:
        errs.append(f"{hold_prefix}_UNDERLYING_GATE0V_EVALUATOR_NOT_PASSED")
    if rec.get("gate0v_hard_stops_count") != 0 or rec.get("gate0v_holds_count") != 0:
        errs.append(f"{hold_prefix}_UNDERLYING_GATE0V_NONZERO_STOPS_OR_HOLDS")
    if not _is_valid_sha256_hex(rec.get("bank_payload_sha256")) or not _is_valid_identifier(rec.get("bank_lot_id")):
        errs.append(f"{hold_prefix}_MISSING_BANK_PAYLOAD_DIGEST_OR_LOT_ID")

    rec_req_ocr = False
    if "require_trusted_nw08_ocr_record" in rec:
        if not _is_strict_bool(rec.get("require_trusted_nw08_ocr_record")):
            _add_err("HOLD_NW08_COUPLED_INVALID_REQUIRE_TRUSTED_OCR_FLAG")
            _add_err(f"{hold_prefix}_INVALID_REQUIRE_TRUSTED_OCR_FLAG")
        else:
            rec_req_ocr = bool(rec.get("require_trusted_nw08_ocr_record"))

    # R04-B2: antiviral_genotype_stratum is MANDATORY (recognized canonical stratum) on EVERY
    # bank qualification record AND strictly bound to BOTH current lot AND archived bank payload!
    rec_geno = rec.get("antiviral_genotype_stratum")
    rec_geno_valid = isinstance(rec_geno, str) and rec_geno in ALLOWED_ANTIVIRAL_GENOTYPES
    exp_geno_valid = isinstance(expected_genotype_stratum, str) and expected_genotype_stratum in ALLOWED_ANTIVIRAL_GENOTYPES
    if not rec_geno_valid:
        errs.append("HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM")
        errs.append(f"{hold_prefix}_MISSING_OR_UNRECOGNIZED_BANK_GENOTYPE_STRATUM")
    elif rec_pvid_res is not None:
        rec_tyk2_cls = rec_pvid_res.get("tyk2_product_genotype_class")
        if rec_tyk2_cls == "TYK2_PE_P1104A" and rec_geno not in ("TYK2_P1104A_HOM__IFIH1_WT", "TYK2_P1104A_HET__IFIH1_WT"):
            errs.append("HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM")
            errs.append(f"{hold_prefix}_BANK_GENOTYPE_CONFLICTS_WITH_PRODUCT_DEFINITION")
        elif rec_tyk2_cls == "TYK2_KO_PROPOSED":
            errs.append("HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM")
            errs.append(f"{hold_prefix}_BANK_TYK2_KO_UNQUALIFIED")

    if not exp_geno_valid:
        if "HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM" not in errs:
            errs.append("HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM")
        errs.append(f"{hold_prefix}_MISSING_OR_UNRECOGNIZED_CURRENT_LOT_GENOTYPE_STRATUM")
    elif rec_geno_valid and rec_geno != expected_genotype_stratum:
        if "HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM" not in errs:
            errs.append("HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM")
        errs.append(f"{hold_prefix}_GENOTYPE_STRATUM_MISMATCH")

    # R05-B1 + R06-B4 + R07-B1 + R08-B1: Verified original archived BANK_QUALIFICATION payload is MANDATORY
    # in BOTH external trusted-store layouts (embedded dict registry JSON AND file-backed directory
    # store), enforcing the EXACT SAME canonical composite envelope contract as direct composite
    # submission (`validate_canonical_composite_envelope`: mandatory canonical top-level
    # `product_variant_id`, exhaustive reconciliation of EVERY supplied tier field against
    # "BANK_QUALIFICATION"), plus optional live composite bank replay (`composite_bank_revalidator`),
    # rejecting metadata-only stubs, tampered internal self-digests, conflicting tier/envelope fields,
    # alias-only envelopes, nested-identity contradictions, and archives that fail live Gate-0V or
    # (in composite release mode when legacy_evaluator is provided) live legacy wetlab_contract revalidation!
    archived_verified: bool = False
    arch_geno: Any = None
    arch_format: str = "absent_or_non_object"
    arch_self_digest_ok: bool = False
    arch_nested_ok: bool = False
    arch_envelope_ok: bool = False
    arch_reval_verdict: str | None = None
    live_reval_ok: bool = False
    arch_leg_reval_ok: bool | None = False if require_composite_legacy_replay else None
    arch_comp_reval_ok: bool | None = False if composite_bank_revalidator is not None else None
    arch_fail_reasons: List[str] = []

    if not isinstance(archived_payload, dict):
        _add_err("HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD")
        _add_err(f"{hold_prefix}_ARCHIVED_BANK_PAYLOAD_{archive_status.upper().replace(':', '_')}")
        arch_fail_reasons.append(f"archive_status:{archive_status}")
    else:
        arch_sha = _safe_canonical_lot_sha256(archived_payload)
        arch_supplied_sha = archived_payload.get("payload_sha256")
        arch_self_digest_ok = bool(
            arch_sha is not None
            and _is_valid_sha256_hex(arch_supplied_sha)
            and arch_supplied_sha == arch_sha
            and arch_sha == rec.get("bank_payload_sha256")
        )
        if not arch_self_digest_ok:
            arch_fail_reasons.append("top_level_payload_sha256_missing_or_mismatch")
            _add_err(f"{hold_prefix}_ARCHIVED_PAYLOAD_SELF_DIGEST_MISMATCH")

        # R08-B1: NEVER fall back to alias-only `product_variant`! Require canonical `product_variant_id`!
        arch_pvid_raw = archived_payload.get("product_variant_id")
        arch_pvid_present = _is_clean_nonempty_str(arch_pvid_raw)
        arch_pvid_res = (
            resolve_canonical_product_variant(arch_pvid_raw, openislet_root=openislet_root)
            if arch_pvid_present
            else None
        )
        arch_pvid_canon = arch_pvid_res["product_variant_id"] if arch_pvid_res is not None else None
        top_alias_ok = True
        if archived_payload.get("product_variant") is not None:
            top_pv_res = resolve_canonical_product_variant(archived_payload.get("product_variant"), openislet_root=openislet_root)
            top_alias_ok = bool(top_pv_res is not None and top_pv_res["product_variant_id"] == expected_product_variant_id)

        top_identity_ok = bool(
            archived_payload.get("mcb_id") == expected_mcb_id
            and arch_pvid_present
            and arch_pvid_canon == expected_product_variant_id
            and top_alias_ok
            and archived_payload.get("lot_id") == rec.get("bank_lot_id")
        )
        if not top_identity_ok:
            arch_fail_reasons.append("top_level_identity_mismatch")

        has_comp_leg = "legacy_stage0_observations" in archived_payload
        has_comp_g0v = "gate0v_wholegraft_payload" in archived_payload
        target_g0v_payload: Dict[str, Any] | None = None
        nested_reconcile_ok = True
        arch_envelope_ok = True

        if has_comp_leg or has_comp_g0v:
            arch_format = "composite_bank_bundle"
            # R08-B1: Enforce the EXACT SAME shared canonical composite envelope contract as direct submission!
            env_res = validate_canonical_composite_envelope(
                archived_payload,
                openislet_root=openislet_root,
                expected_tier="BANK_QUALIFICATION",
                expected_lot_id=rec.get("bank_lot_id"),
                expected_mcb_id=expected_mcb_id,
                expected_product_variant_id=expected_product_variant_id,
            )
            if not env_res["valid"]:
                arch_envelope_ok = False
                nested_reconcile_ok = False
                _add_err("HOLD_ARCHIVED_BANK_ENVELOPE_MISMATCH")
                for eh in env_res["holds"]:
                    _add_err(eh)
                    arch_fail_reasons.append(f"archived_composite_envelope:{eh}")

            arch_leg = archived_payload.get("legacy_stage0_observations")
            arch_g0v = archived_payload.get("gate0v_wholegraft_payload")
            if not isinstance(arch_leg, dict) or not isinstance(arch_g0v, dict):
                nested_reconcile_ok = False
                arch_fail_reasons.append("incomplete_composite_bundle_missing_legacy_or_gate0v_section")
                if require_composite_legacy_replay and not isinstance(arch_leg, dict):
                    arch_leg_reval_ok = False
                    _add_err("HOLD_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE")
                    _add_err(f"{hold_prefix}_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE")
            else:
                # Reconcile legacy_stage0_observations identities & non-stub observation keys
                leg_lot_vals = [
                    arch_leg.get(lk)
                    for lk in ("current_lot_id", "lot_id", "batch_id")
                    if lk in arch_leg and arch_leg.get(lk) is not None
                ]
                leg_lot_ok = bool(leg_lot_vals and all(v == rec.get("bank_lot_id") for v in leg_lot_vals))
                leg_mcb_ok = bool(arch_leg.get("mcb_id") == expected_mcb_id)
                leg_pvid_raw_a = arch_leg.get("product_variant_id")
                leg_pvid_res = (
                    resolve_canonical_product_variant(leg_pvid_raw_a, openislet_root=openislet_root)
                    if _is_clean_nonempty_str(leg_pvid_raw_a)
                    else None
                )
                leg_pvid_ok = bool(leg_pvid_res is not None and leg_pvid_res["product_variant_id"] == expected_product_variant_id)
                leg_alias_ok = True
                if arch_leg.get("product_variant") is not None:
                    la_res = resolve_canonical_product_variant(arch_leg.get("product_variant"), openislet_root=openislet_root)
                    leg_alias_ok = bool(la_res is not None and la_res["product_variant_id"] == expected_product_variant_id)
                required_leg_obs_keys = (
                    "obs_icasp9_log10_kill",
                    "obs_tp53_ppm1d_bcor_vaf",
                    "obs_mcb_effective_clonogenic_trials",
                    "obs_gate0v_day28_persistent_vp1_ie1_cells_scored",
                )
                leg_structure_ok = all(k in arch_leg and arch_leg.get(k) is not None for k in required_leg_obs_keys)
                if not (leg_lot_ok and leg_mcb_ok and leg_pvid_ok and leg_alias_ok and leg_structure_ok):
                    nested_reconcile_ok = False
                    arch_fail_reasons.append("composite_legacy_section_identity_or_structure_invalid")

                # Reconcile nested gate0v_wholegraft_payload identities & internal self-digest
                g0v_lot_ok = bool(arch_g0v.get("lot_id") == rec.get("bank_lot_id"))
                g0v_mcb_ok = bool(arch_g0v.get("mcb_id") == expected_mcb_id)
                g0v_pvid_raw_a = arch_g0v.get("product_variant_id")
                g0v_pvid_res = (
                    resolve_canonical_product_variant(g0v_pvid_raw_a, openislet_root=openislet_root)
                    if _is_clean_nonempty_str(g0v_pvid_raw_a)
                    else None
                )
                g0v_pvid_ok = bool(g0v_pvid_res is not None and g0v_pvid_res["product_variant_id"] == expected_product_variant_id)
                g0v_alias_ok = True
                if arch_g0v.get("product_variant") is not None:
                    ga_res = resolve_canonical_product_variant(arch_g0v.get("product_variant"), openislet_root=openislet_root)
                    g0v_alias_ok = bool(ga_res is not None and ga_res["product_variant_id"] == expected_product_variant_id)
                g0v_tier_ok = bool(
                    arch_g0v.get("qualification_tier") == "BANK_QUALIFICATION"
                    and ("operational_tier" not in arch_g0v or arch_g0v.get("operational_tier") == "BANK_QUALIFICATION")
                )
                g0v_supplied_sha = arch_g0v.get("payload_sha256")
                g0v_computed_sha = _safe_canonical_lot_sha256(arch_g0v)
                g0v_self_sha_ok = bool(
                    g0v_computed_sha is not None
                    and _is_valid_sha256_hex(g0v_supplied_sha)
                    and g0v_supplied_sha == g0v_computed_sha
                )
                if not g0v_self_sha_ok:
                    nested_reconcile_ok = False
                    arch_fail_reasons.append("composite_nested_gate0v_payload_sha256_mismatch")
                    _add_err(f"{hold_prefix}_ARCHIVED_NESTED_GATE0V_SELF_DIGEST_MISMATCH")
                if not (g0v_lot_ok and g0v_mcb_ok and g0v_pvid_ok and g0v_alias_ok and g0v_tier_ok):
                    nested_reconcile_ok = False
                    arch_fail_reasons.append("composite_nested_gate0v_identity_or_tier_mismatch")

                # R07-B1 + R08-B1: Mandatory live legacy revalidation when called from composite wrapper
                # (Zero-LIMS-Touch preserved in standalone verify_iip0043 when legacy_evaluator is None!)
                if require_composite_legacy_replay:
                    if not arch_envelope_ok:
                        arch_leg_reval_ok = False
                        nested_reconcile_ok = False
                        arch_fail_reasons.append("archived_legacy_revalidation_blocked_by_invalid_composite_envelope")
                    elif (
                        rec_pvid_res is not None
                        and rec_pvid_res.get("registry_source") == "iip0041_abx_cd64t_il1rn_side_contract_v0.8.0.json"
                    ):
                        arch_leg_reval_ok = False
                        nested_reconcile_ok = False
                        arch_fail_reasons.append("archived_legacy_revalidation_failed:SIDE_CONTRACT_COMPARATOR_UNSUPPORTED_FOR_CLINICAL_RELEASE")
                        _add_err(f"{hold_prefix}_ARCHIVED_LEGACY_REVALIDATION_FAILED")
                    elif leg_lot_ok and leg_mcb_ok and leg_pvid_ok and leg_alias_ok:
                        try:
                            leg_in = {k: v for k, v in arch_leg.items() if k not in ("lot_id", "product_variant")}
                            leg_in["product_variant_id"] = expected_product_variant_id
                            leg_in.setdefault("current_lot_id", rec.get("bank_lot_id"))
                            leg_in.setdefault("mcb_id", expected_mcb_id)
                            sig = inspect.signature(legacy_evaluator)
                            params = sig.parameters
                            if any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()) or "root" in params:
                                leg_out = legacy_evaluator(leg_in, root=openislet_root)
                            else:
                                leg_out = legacy_evaluator(leg_in)
                            leg_arch_out = leg_out.get("resolved_architecture_assignments") or {}
                            leg_tier_out = str(
                                leg_out.get("lot_release_readiness_tier")
                                or leg_arch_out.get("lot_release_readiness_tier")
                                or "UNKNOWN"
                            )
                            leg_s9_out = bool(leg_out.get("safety_kill_s9_triggered"))
                            leg_pvid_out = leg_arch_out.get("product_variant_id")
                            arch_leg_reval_ok = bool(
                                leg_structure_ok
                                and leg_tier_out == "READY_FOR_ENCAPSULATION_COMPLETE_STAGE0_EVIDENCE"
                                and not leg_s9_out
                                and leg_pvid_out == expected_product_variant_id
                            )
                            if not arch_leg_reval_ok:
                                nested_reconcile_ok = False
                                arch_fail_reasons.append(f"archived_legacy_revalidation_failed:{leg_tier_out}")
                                _add_err(f"{hold_prefix}_ARCHIVED_LEGACY_REVALIDATION_FAILED")
                        except Exception as exc:
                            arch_leg_reval_ok = False
                            nested_reconcile_ok = False
                            arch_fail_reasons.append(f"archived_legacy_revalidation_exception:{type(exc).__name__}")
                            _add_err(f"{hold_prefix}_ARCHIVED_LEGACY_REVALIDATION_FAILED")
                    else:
                        arch_leg_reval_ok = False
                        nested_reconcile_ok = False
                        arch_fail_reasons.append("archived_legacy_revalidation_skipped_due_to_identity_mismatch")
                        _add_err(f"{hold_prefix}_ARCHIVED_LEGACY_REVALIDATION_FAILED")

                # R08-B1: When invoked from composite release wrapper, ALSO execute live composite
                # bank replay on the archived composite bank payload itself so it is IMPOSSIBLE for
                # any archived composite bank bundle that direct composite holds to pass the archive path!
                if composite_bank_revalidator is not None:
                    try:
                        comp_reval = composite_bank_revalidator(archived_payload)
                        cr_lb = comp_reval.get("lot_binding") or {}
                        cr_leg = comp_reval.get("legacy_result_summary") or {}
                        cr_g0v = comp_reval.get("gate0v_result_summary") or {}
                        arch_comp_reval_ok = bool(
                            comp_reval.get("composite_verdict") == "PASS_COMPOSITE_BANK_QUALIFICATION"
                            and len(comp_reval.get("hard_stops") or []) == 0
                            and len(comp_reval.get("holds") or []) == 0
                            and cr_lb.get("payload_sha256_verified") is True
                            and cr_lb.get("lot_id") == rec.get("bank_lot_id")
                            and cr_lb.get("mcb_id") == expected_mcb_id
                            and cr_lb.get("canonical_product_variant_id") == expected_product_variant_id
                            and cr_leg.get("legacy_evaluator_passed") is True
                            and cr_g0v.get("gate0v_evaluator_passed") is True
                        )
                        if not arch_comp_reval_ok:
                            nested_reconcile_ok = False
                            if not arch_envelope_ok:
                                _add_err("HOLD_ARCHIVED_BANK_ENVELOPE_MISMATCH")
                            for cr_h in (comp_reval.get("holds") or []):
                                if isinstance(cr_h, str):
                                    _add_err(cr_h)
                            arch_fail_reasons.append(
                                f"archived_composite_bank_live_replay_failed:{comp_reval.get('composite_verdict')}"
                            )
                    except Exception as exc:
                        arch_comp_reval_ok = False
                        nested_reconcile_ok = False
                        arch_fail_reasons.append(f"archived_composite_bank_live_replay_exception:{type(exc).__name__}")
                        _add_err("HOLD_ARCHIVED_BANK_ENVELOPE_MISMATCH")

                target_g0v_payload = arch_g0v
        else:
            # Direct canonical BANK_QUALIFICATION Gate-0V payload (standalone evidence boundary ONLY!)
            # R08-B1: Standalone plain whole-graft archives MUST also carry canonical product_variant_id
            # (never alias-only) AND reconcile any supplied operational_tier against BANK_QUALIFICATION!
            standalone_tier_ok = bool(
                archived_payload.get("qualification_tier") == "BANK_QUALIFICATION"
                and ("operational_tier" not in archived_payload or archived_payload.get("operational_tier") == "BANK_QUALIFICATION")
            )
            if not arch_pvid_present:
                arch_envelope_ok = False
                nested_reconcile_ok = False
                _add_err("HOLD_ARCHIVED_BANK_ENVELOPE_MISMATCH")
                _add_err("HOLD_GATE0V_MISSING_CANONICAL_PRODUCT_VARIANT_ID")
                arch_fail_reasons.append("standalone_archive_missing_canonical_product_variant_id")
            if "operational_tier" in archived_payload and archived_payload.get("operational_tier") != "BANK_QUALIFICATION":
                arch_envelope_ok = False
                nested_reconcile_ok = False
                _add_err("HOLD_ARCHIVED_BANK_ENVELOPE_MISMATCH")
                _add_err("HOLD_GATE0V_OPERATIONAL_TIER_MISMATCH")
                arch_fail_reasons.append("standalone_archive_conflicting_operational_tier")

            has_core_g0v_blocks = (
                isinstance(archived_payload.get("gate0v_a_poly_ic_sensing"), dict)
                and isinstance(archived_payload.get("gate0v_b_infectious_challenge"), dict)
                and isinstance(archived_payload.get("gate0v_kill_stress_ap1903"), dict)
                and isinstance(archived_payload.get("clustering_and_independence_spec"), dict)
            )
            if has_core_g0v_blocks and standalone_tier_ok and arch_pvid_present:
                target_g0v_payload = archived_payload
                if require_composite_legacy_replay:
                    # R07-B1: Composite clinical release STRICTLY REQUIRES a complete composite bank
                    # archive containing BOTH whole-graft AND archived legacy wetlab_contract observations!
                    arch_format = "standalone_gate0v_bank_payload_missing_legacy_for_composite_release"
                    nested_reconcile_ok = False
                    arch_leg_reval_ok = False
                    if composite_bank_revalidator is not None:
                        arch_comp_reval_ok = False
                    arch_fail_reasons.append("missing_archived_legacy_stage0_observations_for_composite_release")
                    _add_err("HOLD_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE")
                    _add_err(f"{hold_prefix}_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE")
                else:
                    arch_format = "canonical_gate0v_bank_payload"
            else:
                arch_format = "incomplete_or_metadata_only_stub_rejected"
                nested_reconcile_ok = False
                if require_composite_legacy_replay:
                    arch_leg_reval_ok = False
                if composite_bank_revalidator is not None:
                    arch_comp_reval_ok = False
                arch_fail_reasons.append("metadata_only_or_incomplete_bank_archive_rejected")

        # Strict genotype reconciliation across top-level, nested Gate-0V, bank record, and current lot
        arch_geno_top = archived_payload.get("antiviral_genotype_stratum")
        arch_geno_nested = target_g0v_payload.get("antiviral_genotype_stratum") if isinstance(target_g0v_payload, dict) else None
        if arch_format == "composite_bank_bundle":
            arch_geno = arch_geno_nested
            arch_geno_self_consistent = bool(arch_geno_top is None or arch_geno_top == arch_geno_nested)
        else:
            arch_geno = arch_geno_top
            arch_geno_self_consistent = True

        arch_geno_ok = bool(
            arch_geno_self_consistent
            and isinstance(arch_geno, str)
            and arch_geno in ALLOWED_ANTIVIRAL_GENOTYPES
            and rec_geno_valid
            and exp_geno_valid
            and arch_geno == rec_geno
            and arch_geno == expected_genotype_stratum
        )
        if not arch_geno_ok:
            _add_err("HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM")
            _add_err(f"{hold_prefix}_ARCHIVED_PAYLOAD_GENOTYPE_STRATUM_MISMATCH")
            arch_fail_reasons.append("archived_genotype_stratum_mismatch_or_contradiction")

        # Verify mandatory canonical BANK_QUALIFICATION evidence sections on target_g0v_payload
        g0v_evidence_blocks_ok = False
        live_reval_ok = False
        if isinstance(target_g0v_payload, dict):
            g0v_a_blk = target_g0v_payload.get("gate0v_a_poly_ic_sensing")
            g0v_b_blk = target_g0v_payload.get("gate0v_b_infectious_challenge")
            g0v_b_paths = g0v_b_blk.get("pathogens") if isinstance(g0v_b_blk, dict) else None
            g0v_k_blk = target_g0v_payload.get("gate0v_kill_stress_ap1903")
            g0v_evidence_blocks_ok = bool(
                target_g0v_payload.get("qualification_tier") == "BANK_QUALIFICATION"
                and ("operational_tier" not in target_g0v_payload or target_g0v_payload.get("operational_tier") == "BANK_QUALIFICATION")
                and isinstance(g0v_a_blk, dict)
                and isinstance(g0v_b_paths, dict)
                and set(GATE0V_PATHOGENS).issubset(set(g0v_b_paths.keys()))
                and isinstance(g0v_k_blk, dict)
                and set(STRESS_AP1903_REGIMES).issubset(set(g0v_k_blk.keys()))
                and target_g0v_payload.get("antiviral_genotype_stratum") in ALLOWED_ANTIVIRAL_GENOTYPES
            )
            if not g0v_evidence_blocks_ok:
                arch_fail_reasons.append("archived_gate0v_missing_mandatory_bank_evidence_blocks")
            elif not arch_envelope_ok:
                # R08-B1: NEVER report positive live revalidation on an archived bank bundle whose
                # envelope fails canonical validation (prevents direct-vs-archived parity drift!).
                live_reval_ok = False
                arch_reval_verdict = "HOLD_ARCHIVED_BANK_ENVELOPE_MISMATCH"
                arch_fail_reasons.append("archived_bank_live_gate0v_revalidation_blocked_by_envelope_mismatch")
            else:
                # R06-B4: Live re-execution of evaluate_wholegraft_gate0v_and_stress_ap1903 on archived bank payload!
                reval_res = evaluate_wholegraft_gate0v_and_stress_ap1903(
                    target_g0v_payload,
                    trusted_qualification_store=None,
                    openislet_root=openislet_root,
                    _revalidating_archived_bank=True,
                )
                arch_reval_verdict = str(reval_res.get("verdict") or "UNKNOWN")
                reval_lb = reval_res.get("lot_binding") or {}
                live_reval_ok = bool(
                    arch_reval_verdict == "PASS_WHOLEGRAFT_BANK_QUALIFICATION"
                    and len(reval_res.get("hard_stops") or []) == 0
                    and len(reval_res.get("holds") or []) == 0
                    and reval_lb.get("payload_sha256_verified") is True
                    and reval_lb.get("canonical_product_variant_id") == expected_product_variant_id
                    and reval_lb.get("mcb_id") == expected_mcb_id
                    and reval_lb.get("lot_id") == rec.get("bank_lot_id")
                )
                if not live_reval_ok:
                    arch_fail_reasons.append(f"archived_bank_failed_live_gate0v_revalidation:{arch_reval_verdict}")
                    _add_err(f"{hold_prefix}_ARCHIVED_PAYLOAD_FAILED_LIVE_GATE0V_REVALIDATION")

        arch_nested_ok = bool(top_identity_ok and arch_envelope_ok and nested_reconcile_ok and arch_geno_ok)
        legacy_replay_gate_ok = (arch_leg_reval_ok is True) if require_composite_legacy_replay else True
        comp_replay_gate_ok = (arch_comp_reval_ok is True) if (composite_bank_revalidator is not None and arch_format == "composite_bank_bundle") else (
            False if (composite_bank_revalidator is not None) else True
        )
        arch_ok = bool(
            arch_self_digest_ok
            and arch_envelope_ok
            and arch_nested_ok
            and g0v_evidence_blocks_ok
            and (live_reval_ok is True)
            and legacy_replay_gate_ok
            and comp_replay_gate_ok
        )
        archived_verified = arch_ok
        if not arch_ok:
            _add_err("HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD")
            _add_err(f"{hold_prefix}_ARCHIVED_BANK_PAYLOAD_VERIFICATION_FAILED")

    # If caller embedded an inline copy that contradicts the trusted store record, reject!
    if isinstance(inline_record_if_supplied, dict):
        inline_sha = _safe_canonical_qualification_artifact_sha256(inline_record_if_supplied)
        if inline_sha is None or computed_sha is None or inline_sha != computed_sha:
            _add_err(f"{hold_prefix}_INLINE_RECORD_CONFLICTS_WITH_TRUSTED_STORE")

    if errs:
        errs = ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE"] + [e for e in errs if e != "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE"]

    all_live_reval_ok = bool(
        archived_verified is True
        and arch_envelope_ok is True
        and (live_reval_ok is True)
        and ((arch_leg_reval_ok is True) if require_composite_legacy_replay else True)
        and ((arch_comp_reval_ok is True) if composite_bank_revalidator is not None else True)
    )
    ok = bool(len(errs) == 0 and all_live_reval_ok)
    return ok, errs, {
        "authenticated": ok,
        "resolution_source": store_src,
        "self_attested_inline_record_ignored": inline_record_if_supplied is not None,
        "computed_sha256": computed_sha,
        "approved_by_authority_id": rec.get("approved_by_authority_id"),
        "record_mcb_id": rec.get("mcb_id"),
        "record_product_variant_id": rec_pvid_canon,
        "record_antiviral_genotype_stratum": rec_geno,
        "archived_antiviral_genotype_stratum": arch_geno,
        "record_operational_tier": rec.get("operational_tier"),
        "record_verdict": rec.get("verdict"),
        "record_legacy_tier": rec.get("legacy_tier"),
        "record_gate0v_verdict": rec.get("gate0v_verdict"),
        "record_require_trusted_nw08_ocr_record": rec_req_ocr,
        "archived_bank_payload_verified": archived_verified,
        "archived_bank_payload_envelope_verified": arch_envelope_ok,
        "archived_bank_payload_status": archive_status,
        "archived_bank_payload_format": arch_format,
        "archived_bank_payload_self_digest_verified": arch_self_digest_ok,
        "archived_bank_payload_nested_identities_reconciled": arch_nested_ok,
        "archived_bank_payload_live_revalidation_passed": all_live_reval_ok,
        "archived_bank_payload_live_g0v_revalidation_passed": bool(live_reval_ok),
        "archived_bank_payload_live_gate0v_revalidation_verdict": arch_reval_verdict,
        "archived_bank_payload_live_legacy_revalidation_required": require_composite_legacy_replay,
        "archived_bank_payload_live_legacy_revalidation_passed": arch_leg_reval_ok,
        "archived_bank_payload_live_composite_revalidation_passed": arch_comp_reval_ok,
        "archived_bank_payload_failure_reasons": arch_fail_reasons,
        "deployment_prerequisite": (
            "Software record-content, self-digest, canonical envelope alignment, and live evaluator "
            "re-verification require independent QA operator administration, write-restricted storage "
            "control, and separation of duties over --trusted-qualification-store as deployment prerequisites."
        ),
    }


def resolve_and_verify_trusted_process_qualification(
    trusted_qualification_store: Path | str | None,
    *,
    expected_sha256: Any,
    expected_product_variant_id: Any,
    inline_record_if_supplied: Any = None,
    openislet_root: Path | None = None,
    hold_prefix: str = "HOLD_GATE0V_AUTOLOGOUS_PROC_QUAL",
) -> Tuple[bool, List[str], Dict[str, Any]]:
    """
    Resolve and verify prior AUTOLOGOUS_D1B_PROCESS_QUAL approval SOLELY from an independently
    controlled external trusted qualification store (B1).
    """
    rec, archived_payload, lookup_errs, store_src, archive_status = (
        _lookup_in_trusted_qualification_store_with_archive_status(
            trusted_qualification_store,
            category="process_qualifications",
            expected_sha256=expected_sha256,
        )
    )
    if lookup_errs or rec is None:
        return False, lookup_errs, {
            "authenticated": False,
            "resolution_source": store_src,
            "self_attested_inline_record_ignored": inline_record_if_supplied is not None,
        }

    errs: List[str] = []
    rec_sha = rec.get("sha256")
    computed_sha = _safe_canonical_qualification_artifact_sha256(rec)
    if computed_sha is None or not _is_valid_sha256_hex(rec_sha) or rec_sha != computed_sha:
        errs.append(f"{hold_prefix}_RECORD_INTERNAL_SHA256_MISMATCH")
    elif rec_sha != expected_sha256:
        errs.append(f"{hold_prefix}_RECORD_SHA256_DOES_NOT_MATCH_REF_DIGEST")

    if not _is_valid_identifier(rec.get("approved_by_authority_id")):
        errs.append(f"{hold_prefix}_MISSING_APPROVED_BY_AUTHORITY_ID")
    if rec.get("operational_tier") != "AUTOLOGOUS_D1B_PROCESS_QUAL":
        errs.append(f"{hold_prefix}_WRONG_OPERATIONAL_TIER")
    if "qualification_tier" in rec and rec.get("qualification_tier") != "AUTOLOGOUS_D1B_PROCESS_QUAL":
        errs.append(f"{hold_prefix}_WRONG_OPERATIONAL_TIER")
    if rec.get("verdict") != "PASS_AUTOLOGOUS_D1B_PROCESS_QUALIFICATION":
        errs.append(f"{hold_prefix}_VERDICT_NOT_PASS")

    rec_pvid_raw = rec.get("product_variant_id")
    if not _is_clean_nonempty_str(rec_pvid_raw):
        errs.append(f"{hold_prefix}_MISSING_RECORD_PRODUCT_VARIANT_ID")
    rec_pvid_res = (
        resolve_canonical_product_variant(rec_pvid_raw, openislet_root=openislet_root)
        if _is_clean_nonempty_str(rec_pvid_raw)
        else None
    )
    rec_pvid_canon = rec_pvid_res["product_variant_id"] if rec_pvid_res is not None else rec_pvid_raw
    if rec_pvid_canon != expected_product_variant_id:
        errs.append(f"{hold_prefix}_PRODUCT_VARIANT_ID_MISMATCH")
    if "product_variant" in rec and rec.get("product_variant") is not None:
        rpv_res = resolve_canonical_product_variant(rec.get("product_variant"), openislet_root=openislet_root)
        if rpv_res is None or rpv_res["product_variant_id"] != expected_product_variant_id:
            errs.append(f"{hold_prefix}_PRODUCT_VARIANT_ID_MISMATCH")

    # R04-B1: AUTOLOGOUS_D1B_PROCESS_QUAL is strictly allowed ONLY for canonical autologous
    # D1b-Auto-C variants (ISLET1_D1_AUTO_*) — reject any allogeneic product EVEN IF its
    # external QA process-record digest and product_variant_id agree!
    exp_pvid_res = resolve_canonical_product_variant(expected_product_variant_id, openislet_root=openislet_root)
    if rec_pvid_res is None:
        errs.append(f"{hold_prefix}_UNREGISTERED_RECORD_PRODUCT_VARIANT_ID")
    else:
        tier_ok_rec, tier_errs_rec = is_qualification_tier_allowed_for_product(
            rec_pvid_res, "AUTOLOGOUS_D1B_PROCESS_QUAL"
        )
        if not tier_ok_rec:
            errs.extend(tier_errs_rec)
    if exp_pvid_res is not None:
        tier_ok_exp, tier_errs_exp = is_qualification_tier_allowed_for_product(
            exp_pvid_res, "AUTOLOGOUS_D1B_PROCESS_QUAL"
        )
        if not tier_ok_exp:
            for te in tier_errs_exp:
                if te not in errs:
                    errs.append(te)

    # R06-M3: Align autologous process-qualification validation with canonical autologous family semantics
    # (NEVER accept allogeneic PASS_WHOLEGRAFT_BANK_QUALIFICATION as the underlying autologous process pass!)
    if rec.get("underlying_gate0v_verdict") not in (
        "PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL",
        "PASS_COMPOSITE_AUTOLOGOUS_PROCESS_QUAL",
    ):
        errs.append(f"{hold_prefix}_UNDERLYING_GATE0V_VERDICT_NOT_AUTOLOGOUS_PROCESS_QUAL_PASS")
    if rec.get("underlying_gate0v_passed") is not True:
        errs.append(f"{hold_prefix}_UNDERLYING_GATE0V_NOT_PASSED")
    if rec.get("underlying_hard_stops_count") != 0 or rec.get("underlying_holds_count") != 0:
        errs.append(f"{hold_prefix}_UNDERLYING_NONZERO_STOPS_OR_HOLDS")
    if not _is_valid_sha256_hex(rec.get("process_qual_payload_sha256")) or not _is_valid_identifier(rec.get("process_qual_id")):
        errs.append(f"{hold_prefix}_MISSING_PAYLOAD_DIGEST_OR_ID")

    rec_req_ocr = False
    if "require_trusted_nw08_ocr_record" in rec:
        if not _is_strict_bool(rec.get("require_trusted_nw08_ocr_record")):
            errs.append("HOLD_NW08_COUPLED_INVALID_REQUIRE_TRUSTED_OCR_FLAG")
            errs.append(f"{hold_prefix}_INVALID_REQUIRE_TRUSTED_OCR_FLAG")
        else:
            rec_req_ocr = bool(rec.get("require_trusted_nw08_ocr_record"))

    archived_verified: bool | None = None
    if archived_payload is not None:
        arch_sha = _safe_canonical_lot_sha256(archived_payload)
        arch_pvid_raw = archived_payload.get("product_variant_id")
        arch_pvid_present = _is_clean_nonempty_str(arch_pvid_raw)
        arch_pvid_res = (
            resolve_canonical_product_variant(arch_pvid_raw, openislet_root=openislet_root)
            if arch_pvid_present
            else None
        )
        arch_pvid_canon = arch_pvid_res["product_variant_id"] if arch_pvid_res is not None else None
        arch_alias_ok = True
        if archived_payload.get("product_variant") is not None:
            apv_res = resolve_canonical_product_variant(archived_payload.get("product_variant"), openislet_root=openislet_root)
            arch_alias_ok = bool(apv_res is not None and apv_res["product_variant_id"] == expected_product_variant_id)
        arch_tier_ok = bool(
            ("qualification_tier" not in archived_payload or archived_payload.get("qualification_tier") == "AUTOLOGOUS_D1B_PROCESS_QUAL")
            and ("operational_tier" not in archived_payload or archived_payload.get("operational_tier") == "AUTOLOGOUS_D1B_PROCESS_QUAL")
        )
        arch_ok = bool(
            arch_sha is not None
            and arch_sha == rec.get("process_qual_payload_sha256")
            and arch_pvid_present
            and arch_pvid_canon == expected_product_variant_id
            and arch_alias_ok
            and arch_tier_ok
        )
        archived_verified = arch_ok
        if not arch_ok:
            errs.append(f"{hold_prefix}_ARCHIVED_PROCESS_PAYLOAD_VERIFICATION_FAILED")
    elif archive_status.startswith(("non_object", "unreadable", "invalid_container", "ambiguous")):
        archived_verified = False
        errs.append(f"{hold_prefix}_ARCHIVED_PROCESS_PAYLOAD_INVALID")

    if isinstance(inline_record_if_supplied, dict):
        inline_sha = _safe_canonical_qualification_artifact_sha256(inline_record_if_supplied)
        if inline_sha is None or computed_sha is None or inline_sha != computed_sha:
            errs.append(f"{hold_prefix}_INLINE_RECORD_CONFLICTS_WITH_TRUSTED_STORE")

    if errs:
        errs = ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE"] + errs

    ok = len(errs) == 0
    return ok, errs, {
        "authenticated": ok,
        "resolution_source": store_src,
        "self_attested_inline_record_ignored": inline_record_if_supplied is not None,
        "computed_sha256": computed_sha,
        "approved_by_authority_id": rec.get("approved_by_authority_id"),
        "record_product_variant_id": rec_pvid_canon,
        "record_operational_tier": rec.get("operational_tier"),
        "record_verdict": rec.get("verdict"),
        "record_underlying_gate0v_verdict": rec.get("underlying_gate0v_verdict"),
        "record_require_trusted_nw08_ocr_record": rec_req_ocr,
        "archived_process_payload_verified": archived_verified,
        "staged_autologous_contract_note": (
            "AUTOLOGOUS_D1B_PROCESS_QUAL is a staged autologous path contingent on legacy execution_supported "
            "promotion; legitimate upstream issuers must use autologous process-qualification PASS semantics "
            "(PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL / PASS_COMPOSITE_AUTOLOGOUS_PROCESS_QUAL, never "
            "allogeneic PASS_WHOLEGRAFT_BANK_QUALIFICATION) with linked process archive evidence prior to activation."
        ),
        "deployment_prerequisite": (
            "Software record-content and SHA-256 verification require independent QA operator "
            "administration, write-restricted storage control, and separation of duties over "
            "--trusted-qualification-store as deployment prerequisites."
        ),
    }


def _adjudicate_supplemental_pathogen_adverse_data(
    path_id: str,
    pblock: Any,
    *,
    deff: Decimal | None,
    alpha_obs_tier: Decimal,
    hard_stops: List[str],
    holds: List[str],
    adjudicated_log: List[str],
    check_unit_basis_fn: Any = None,
) -> None:
    """
    B6 / R03-B1 rule: Never silently drop submitted pathogen results in abbreviated tiers!
    Any submitted adverse finding in a supplemental pathogen block MUST trigger FAIL_HARD_STOP,
    and any submitted malformed/uncalibrated control or confirmation data MUST fail closed (HOLD).
    """
    p_tag = str(path_id).upper()
    adjudicated_log.append(f"supplemental_pathogen:{path_id}")
    if not isinstance(pblock, dict):
        holds.append(f"HOLD_GATE0V_B_SUPPLEMENTAL_INVALID_PATHOGEN_BLOCK_{p_tag}")
        return

    for comp_key in ("endocrine_72h_log10_pfu_u95", "vascular_72h_log10_pfu_u95", "coculture_72h_log10_pfu_u95"):
        v = _to_exact_decimal(pblock.get(comp_key))
        if v is not None and v > Decimal("2.0"):
            hard_stops.append(f"FAIL_GATE0V_B_SUPPLEMENTAL_ACUTE_TITER_EXCEEDS_2LOG10_{p_tag}_{comp_key.upper()}")

    for comp_key in ("endocrine_day14_log10_reduction_l95", "vascular_day14_log10_reduction_l95"):
        v = _to_exact_decimal(pblock.get(comp_key))
        if v is not None and v < Decimal("3.0"):
            hard_stops.append(f"FAIL_GATE0V_B_SUPPLEMENTAL_DAY14_CLEARANCE_BELOW_3LOG10_{p_tag}_{comp_key.upper()}")

    rna_k = pblock.get("day14_negative_strand_or_ie1_rna_positive_wells_k")
    if _is_strict_int(rna_k) and rna_k > 0:
        hard_stops.append(f"FAIL_HARD_STOP_GATE0V_B_SUPPLEMENTAL_ACTIVE_VIRAL_RNA_DETECTED_{p_tag}")

    day28_pfu = _to_exact_decimal(pblock.get("day28_supernatant_infectious_pfu_ml"))
    if day28_pfu is not None and day28_pfu > Decimal(0):
        hard_stops.append(f"FAIL_HARD_STOP_GATE0V_B_SUPPLEMENTAL_DAY28_INFECTIOUS_SHEDDING_{p_tag}")

    delta_l95 = _to_exact_decimal(pblock.get("edited_minus_wt_day14_log10_reduction_l95"))
    if delta_l95 is not None and delta_l95 < Decimal("-0.50"):
        hard_stops.append(f"FAIL_GATE0V_B_SUPPLEMENTAL_ANTIVIRAL_COMPETENCE_LOSS_EXCEEDS_0P5_LOG10_{p_tag}")

    lat_arm = pblock.get("day28_latent_and_defective_genome_arm")
    if isinstance(lat_arm, dict):
        dd_k = lat_arm.get("ddpcr_positive_events_k")
        if _is_strict_int(dd_k) and dd_k >= 1:
            hard_stops.append(f"FAIL_HARD_STOP_GATE0V_B_SUPPLEMENTAL_LATENT_OR_DEFECTIVE_GENOME_DETECTED_{p_tag}_K_{dd_k}")
        dd_targets = lat_arm.get("ddpcr_targets")
        if isinstance(dd_targets, dict):
            for tname, tentry in dd_targets.items():
                if isinstance(tentry, dict) and _is_strict_int(tentry.get("k")) and tentry["k"] >= 1:
                    hard_stops.append(
                        f"FAIL_HARD_STOP_GATE0V_B_SUPPLEMENTAL_LATENT_TARGET_DETECTED_{p_tag}_{str(tname).upper()}_K_{tentry['k']}"
                    )
        react_pfu = _to_exact_decimal(lat_arm.get("reactivation_7d_outgrowth_pfu_ml"))
        if react_pfu is not None and react_pfu > Decimal(0):
            hard_stops.append(f"FAIL_HARD_STOP_GATE0V_B_SUPPLEMENTAL_{p_tag}_LATENT_REACTIVATION_OUTGROWTH")

    unass_ro = pblock.get("unassigned_fraction_viral_readout")
    if isinstance(unass_ro, dict):
        uk2 = unass_ro.get("stage2_confirmed_infectious_k")
        if _is_strict_int(uk2) and uk2 >= 1:
            hard_stops.append(f"FAIL_HARD_STOP_GATE0V_SUPPLEMENTAL_CONFIRMED_VIRAL_POSITIVE_UNASSIGNED_{p_tag}_K_{uk2}")
        uk1 = unass_ro.get("stage1_screen_positive_k")
        un2 = unass_ro.get("stage2_sorted_for_confirmation_n")
        if _is_strict_int(uk1) and _is_strict_int(un2) and un2 != uk1:
            holds.append(f"HOLD_GATE0V_B_SUPPLEMENTAL_UNCONFIRMED_UNASSIGNED_STAGE1_HITS_{p_tag}")

    lin_data = pblock.get("day28_persistence_by_lineage")
    if isinstance(lin_data, dict):
        alpha_05 = Decimal("0.05")
        max_neg_ctrl_fpr_u95 = Decimal("0.0015")
        min_eta_cal = Decimal("0.80")
        for lin_name, entry in lin_data.items():
            lin_tag = str(lin_name).upper()
            if lin_name not in GRAFT_LINEAGES:
                holds.append(f"HOLD_UNRECOGNIZED_LINEAGE_KEY_GATE0V_B_SUPPLEMENTAL_{p_tag}_{lin_tag}")
            if not isinstance(entry, dict):
                holds.append(f"HOLD_GATE0V_B_SUPPLEMENTAL_INVALID_LINEAGE_ENTRY_{p_tag}_{lin_tag}")
                continue
            k2 = entry.get("stage2_confirmed_infectious_k")
            if _is_strict_int(k2) and k2 >= 1:
                hard_stops.append(
                    f"FAIL_HARD_STOP_GATE0V_SUPPLEMENTAL_CONFIRMED_VIRAL_POSITIVE_{p_tag}_{lin_tag}_K_{k2}"
                )
            k1 = entry.get("stage1_screen_positive_k")
            n2 = entry.get("stage2_sorted_for_confirmation_n")
            if k1 is not None or n2 is not None:
                if not (_is_strict_int(k1) and _is_strict_int(n2) and n2 == k1):
                    holds.append(f"HOLD_GATE0V_B_SUPPLEMENTAL_UNCONFIRMED_STAGE1_HITS_{p_tag}_{lin_tag}")
            uc_k = entry.get("uninfected_ctrl_fp_k")
            uc_n = entry.get("uninfected_ctrl_scored_n")
            if uc_k is not None or uc_n is not None:
                if check_unit_basis_fn is not None:
                    check_unit_basis_fn(
                        entry.get("uninfected_ctrl_per_unit_counts"),
                        k_val=uc_k,
                        n_val=uc_n,
                        label=f"SUPP_NEG_CTRL_{p_tag}_{lin_tag}",
                    )
                if not (_is_strict_int(uc_k) and _is_strict_int(uc_n) and uc_n >= 20_000 and 0 <= uc_k <= uc_n):
                    holds.append(f"HOLD_GATE0V_B_SUPPLEMENTAL_UNDERPOWERED_UNINFECTED_FPR_CTRL_{p_tag}_{lin_tag}")
                else:
                    fpr_u95 = exact_clopper_pearson_upper_general(uc_k, uc_n, alpha_05, prec=60)
                    if fpr_u95 > max_neg_ctrl_fpr_u95:
                        holds.append(f"HOLD_GATE0V_B_SUPPLEMENTAL_UNINFECTED_CTRL_FPR_U95_EXCEEDS_0P15PCT_{p_tag}_{lin_tag}")
            rk_i = entry.get("spike_calibrant_detected_k")
            rn_i = entry.get("spike_calibrant_total_n")
            frk_i = entry.get("fragile_infected_spike_detected_k")
            frn_i = entry.get("fragile_infected_spike_total_n")
            if any(x is not None for x in (rk_i, rn_i, frk_i, frn_i)):
                if check_unit_basis_fn is not None:
                    check_unit_basis_fn(
                        entry.get("spike_calibrant_per_unit_counts"),
                        k_val=rk_i,
                        n_val=rn_i,
                        label=f"SUPP_SPIKE_CAL_HEALTHY_{p_tag}_{lin_tag}",
                    )
                    check_unit_basis_fn(
                        entry.get("fragile_infected_spike_per_unit_counts"),
                        k_val=frk_i,
                        n_val=frn_i,
                        label=f"SUPP_SPIKE_CAL_FRAGILE_{p_tag}_{lin_tag}",
                    )
                if not (
                    _is_strict_int(rk_i) and _is_strict_int(rn_i) and rn_i >= 1 and 0 <= rk_i <= rn_i
                    and _is_strict_int(frk_i) and _is_strict_int(frn_i) and frn_i >= 1 and 0 <= frk_i <= frn_i
                ):
                    holds.append(f"HOLD_GATE0V_B_SUPPLEMENTAL_INVALID_DUAL_SPIKE_CALIBRANT_{p_tag}_{lin_tag}")
                else:
                    eta_eff_l = min(
                        exact_clopper_pearson_lower_calibrant(rk_i, rn_i, alpha_obs_tier, prec=80),
                        exact_clopper_pearson_lower_calibrant(frk_i, frn_i, alpha_obs_tier, prec=80),
                    )
                    if eta_eff_l < min_eta_cal:
                        holds.append(f"HOLD_GATE0V_B_SUPPLEMENTAL_CALIBRANT_SENSITIVITY_BELOW_0P80_{p_tag}_{lin_tag}")


def _adjudicate_kill_regime_lineage_arm(
    reg: str,
    lin: str,
    lblock: Dict[str, Any],
    *,
    deff: Decimal | None,
    hard_stops: List[str],
    holds: List[str],
    is_supplemental: bool = False,
    sampling_spec_valid: bool = True,
    sampling_unit_class: str | None = None,
    indep_units_n: int | None = None,
    sampling_tracker: Dict[str, Any] | None = None,
) -> Tuple[bool, Dict[str, Any]]:
    """
    Single unified fail-closed Gate 0V-Kill adjudicator shared by BOTH required stress arms
    and submitted supplemental stress arms in abbreviated tiers (R03-B1 + R12-B1):
      - NEVER certifies exact directional confidence when `clustering_and_independence_spec` is
        missing/invalid (`deff is None`), clustered (`deff > 1.0`), has `< 6` independent biological
        units, or lacks reconciled per-estimand `per_unit_counts` / unit-matched single-cell basis.
      - Recomputes paired 24-h (>= 99.9%) and 72-h (>= 4.0 log10) vehicle-adjusted kill
        bounds directly from raw integer counts (Bonferroni 0.025 + 0.025 = 0.050).
      - Preserves deterministic biological FAIL_HARD_STOPs (`vk >= 1`, `caspase < 5.0x`,
        `k_treated > n_treated`, `surv_n > n_in`) even when exact confidence is uncertified!
      - Applies full infected-arm caspase-9/3 blockade (< 5.0x -> FAIL_HARD_STOP), viable
        viral-positive survivor veto (`vk >= 1` -> FAIL_HARD_STOP, checked unconditionally
        so no HOLD can mask a hard stop), aliquot reconciliation, dual healthy + fragile
        spike calibrant (`eta >= 0.80`), Estimand 1 (`U_esc,total <= 1e-4`, sum 0.035),
        and Estimand 2 (`U_esc,cond <= 1e-3`, direct or indirect sum 0.050).
    """
    reg_tag = str(reg).upper()
    lin_tag = str(lin).upper()
    sup_hs = "SUPPLEMENTAL_" if is_supplemental else ""
    sup_hd = "SUPPLEMENTAL_" if is_supplemental else ""

    cap_frac_kill_esc_total = Decimal("0.0001")  # 0.01% (4.0 log10) per total input at risk (proposed)
    cap_frac_kill_esc_cond = Decimal("0.001")    # 0.10% (3.0 log10) conditional per infected cell (proposed)
    alpha_paired_veh = Decimal("0.025")
    alpha_paired_surv = Decimal("0.025")
    alpha_e1_eta = Decimal("0.005")
    alpha_e1_esc = Decimal("0.005")
    alpha_e2_ind_veh = Decimal("0.015")
    alpha_e2_ind_prev = Decimal("0.015")
    alpha_e2_ind_eta = Decimal("0.005")
    alpha_e2_ind_esc = Decimal("0.015")
    alpha_e2_dir_inf_veh = Decimal("0.025")
    alpha_e2_dir_eta = Decimal("0.005")
    alpha_e2_dir_esc = Decimal("0.020")
    min_eta_cal = Decimal("0.80")
    min_s_veh = Decimal("0.10")

    def _append_unique(target_list: List[str], token: str) -> None:
        if token not in target_list:
            target_list.append(token)

    v24_v = lblock.get("veh_24h_viable_n")
    v24_n = lblock.get("veh_24h_input_n")
    a24_n = lblock.get("ap1903_24h_input_n")
    a24_k = lblock.get("ap1903_24h_viable_survivors_k")

    v72_v = lblock.get("veh_72h_viable_n")
    v72_n = lblock.get("veh_72h_input_n")
    a72_n = lblock.get("ap1903_72h_input_n")
    a72_k = lblock.get("ap1903_72h_viable_survivors_k")

    is_infected_arm = reg in INFECTED_AP1903_REGIMES
    casp_fold_raw = lblock.get("caspase9_3_activity_fold_over_vehicle")
    vk_raw = lblock.get("post_ap1903_viable_viral_pos_k")
    n_in = lblock.get("pre_ap1903_lineage_input_cells_n")
    direct_inf_veh_k = lblock.get("pretreat_infected_veh_survivor_n")
    rk = lblock.get("spike_calibrant_detected_k")
    rn = lblock.get("spike_calibrant_total_n")
    frk = lblock.get("fragile_infected_spike_detected_k")
    frn = lblock.get("fragile_infected_spike_total_n")

    # R12-B1 + R17-B1: Track ALL binomial denominators (including stressed-arm recovery calibrants!)
    # & validate per-estimand sampling-unit partitions on EVERY count entering Clopper-Pearson bounds!
    arm_partition_ok = True
    arm_denoms: List[int] = [
        int(d_n)
        for d_n in (
            v24_n,
            a24_n,
            v72_n,
            a72_n,
            n_in if is_infected_arm else None,
            rn if is_infected_arm else None,
            frn if is_infected_arm else None,
        )
        if _is_strict_int(d_n) and d_n >= 1
    ]
    if sampling_tracker is not None and arm_denoms:
        max_arm_n = max(arm_denoms)
        if max_arm_n > sampling_tracker["max_binomial_denominator_n"]:
            sampling_tracker["max_binomial_denominator_n"] = max_arm_n

    raw_puc = lblock.get("per_unit_counts")
    arm_estimand_specs: List[Tuple[str, Any, Any, bool]] = [
        ("veh_24h", v24_v, v24_n, False),
        ("ap1903_24h", a24_k, a24_n, False),
        ("veh_72h", v72_v, v72_n, False),
        ("ap1903_72h", a72_k, a72_n, False),
    ]
    if is_infected_arm:
        arm_estimand_specs.append(("infected_viral_pos_72h", vk_raw, n_in, True))
        if direct_inf_veh_k is not None:
            arm_estimand_specs.append(("direct_infected_veh_72h", direct_inf_veh_k, v72_n, False))
        arm_estimand_specs.append(("spike_calibrant", rk, rn, False))
        arm_estimand_specs.append(("fragile_infected_spike_calibrant", frk, frn, False))

    if sampling_unit_class == "RECONCILED_MULTI_WELL_CELL_ASSAY_WITH_UNIT_PARTITION":
        sub_parsed: Dict[str, Dict[str, Any]] = {}
        sub_cross_ok: Dict[str, bool] = {}
        for sub_key, exp_k, exp_n, is_zt_viral in arm_estimand_specs:
            if sampling_tracker is not None:
                sampling_tracker["partitions_checked"] += 1
            sub_raw = raw_puc.get(sub_key) if isinstance(raw_puc, dict) else None
            p_info = _inspect_per_unit_counts(
                sub_raw,
                expected_units_n=indep_units_n,
                expected_k=exp_k if _is_strict_int(exp_k) else None,
                expected_n=exp_n if _is_strict_int(exp_n) else None,
            )
            sub_parsed[sub_key] = p_info
            sub_cross_ok[sub_key] = bool(p_info["reconciled_ok"])
            if is_zt_viral and p_info["any_pos_k"]:
                _append_unique(hard_stops, "HARD_STOP_ADVERSE_PER_UNIT_POST_AP1903_VIRAL_ESCAPE")
                _append_unique(hard_stops, f"FAIL_HARD_STOP_{sup_hs}POST_AP1903_VIABLE_VIRAL_SURVIVOR_{reg_tag}_{lin_tag}")
            if not p_info["reconciled_ok"]:
                arm_partition_ok = False
                if sampling_tracker is not None:
                    sampling_tracker["all_partitions_reconciled"] = False
                _append_unique(holds, "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS")
                _append_unique(
                    holds,
                    f"HOLD_GATE0V_KILL_{sup_hd}SAMPLING_UNIT_PARTITION_MISMATCH_{reg_tag}_{lin_tag}_{sub_key.upper()}_{p_info['reason_code']}",
                )

        # R13-B2: Cross-estimand same-unit ID set matching & within-unit subset inequality reconciliation!
        # All paired estimands in the same arm MUST share the exact same canonical unit_id set
        # (`len == independent_biological_units_n >= 6`), and within EVERY individual unit `u`:
        #   - `direct_infected_veh_72h`: `n_u == veh_72h.n_u` and `0 <= k_u <= veh_72h.k_u <= veh_72h.n_u`
        #   - `infected_viral_pos_72h` (under SAME_72H_ALIQUOT): `n_u == ap1903_72h.n_u` and `0 <= k_u <= ap1903_72h.k_u <= ap1903_72h.n_u`
        ref_uid_set: set[str] | None = None
        if "veh_72h" in sub_parsed and sub_parsed["veh_72h"]["reconciled_ok"]:
            ref_uid_set = set(sub_parsed["veh_72h"]["unit_map"].keys())
        else:
            for sk_i, pi_i in sub_parsed.items():
                if pi_i["reconciled_ok"] and pi_i["unit_map"]:
                    ref_uid_set = set(pi_i["unit_map"].keys())
                    break

        if ref_uid_set is not None:
            for sub_key, p_info in sub_parsed.items():
                if p_info["reconciled_ok"] and set(p_info["unit_map"].keys()) != ref_uid_set:
                    sub_cross_ok[sub_key] = False
                    arm_partition_ok = False
                    if sampling_tracker is not None:
                        sampling_tracker["all_partitions_reconciled"] = False
                    _append_unique(holds, "HOLD_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION")
                    _append_unique(
                        holds,
                        f"HOLD_GATE0V_KILL_{sup_hd}SAMPLING_UNIT_ID_SET_MISMATCH_{reg_tag}_{lin_tag}_{sub_key.upper()}",
                    )

        # Pair A: direct_infected_veh_72h <= veh_72h (same unit IDs, same n_u, k_inf_u <= k_veh72_u <= n_u)
        if (
            "direct_infected_veh_72h" in sub_parsed
            and "veh_72h" in sub_parsed
            and sub_parsed["direct_infected_veh_72h"]["unit_map"]
            and sub_parsed["veh_72h"]["unit_map"]
        ):
            dir_map = sub_parsed["direct_infected_veh_72h"]["unit_map"]
            v72_map = sub_parsed["veh_72h"]["unit_map"]
            if set(dir_map.keys()) != set(v72_map.keys()):
                sub_cross_ok["direct_infected_veh_72h"] = False
                arm_partition_ok = False
                if sampling_tracker is not None:
                    sampling_tracker["all_partitions_reconciled"] = False
                _append_unique(holds, "HOLD_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION")
                _append_unique(
                    holds,
                    f"HOLD_GATE0V_KILL_{sup_hd}DIRECT_INFECTED_VEH_UNIT_ID_MISMATCH_{reg_tag}_{lin_tag}",
                )
            else:
                for uid_key, (dir_k_u, dir_n_u) in dir_map.items():
                    v72_k_u, v72_n_u = v72_map[uid_key]
                    if dir_n_u != v72_n_u or not (0 <= dir_k_u <= v72_k_u <= v72_n_u):
                        sub_cross_ok["direct_infected_veh_72h"] = False
                        arm_partition_ok = False
                        if sampling_tracker is not None:
                            sampling_tracker["all_partitions_reconciled"] = False
                        _append_unique(holds, "HOLD_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION")
                        _append_unique(
                            holds,
                            f"HOLD_GATE0V_KILL_{sup_hd}DIRECT_INFECTED_VEH_UNIT_SUBSET_CONTRADICTION_{reg_tag}_{lin_tag}",
                        )
                        break

        # Pair B: under SAME_72H_ALIQUOT, infected_viral_pos_72h <= ap1903_72h (same unit IDs, same n_u, k_vp_u <= k_a72_u <= n_u)
        if (
            is_infected_arm
            and lblock.get("infected_surveillance_aliquot_linkage_mode") == "SAME_72H_ALIQUOT"
            and "infected_viral_pos_72h" in sub_parsed
            and "ap1903_72h" in sub_parsed
            and sub_parsed["infected_viral_pos_72h"]["unit_map"]
            and sub_parsed["ap1903_72h"]["unit_map"]
        ):
            vp_map = sub_parsed["infected_viral_pos_72h"]["unit_map"]
            a72_map = sub_parsed["ap1903_72h"]["unit_map"]
            if set(vp_map.keys()) != set(a72_map.keys()):
                sub_cross_ok["infected_viral_pos_72h"] = False
                arm_partition_ok = False
                if sampling_tracker is not None:
                    sampling_tracker["all_partitions_reconciled"] = False
                _append_unique(holds, "HOLD_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION")
                _append_unique(
                    holds,
                    f"HOLD_GATE0V_KILL_{sup_hd}INFECTED_VIRAL_POS_UNIT_ID_MISMATCH_{reg_tag}_{lin_tag}",
                )
            else:
                for uid_key, (vp_k_u, vp_n_u) in vp_map.items():
                    a72_k_u, a72_n_u = a72_map[uid_key]
                    if vp_n_u != a72_n_u or not (0 <= vp_k_u <= a72_k_u <= a72_n_u):
                        sub_cross_ok["infected_viral_pos_72h"] = False
                        arm_partition_ok = False
                        if sampling_tracker is not None:
                            sampling_tracker["all_partitions_reconciled"] = False
                        _append_unique(holds, "HOLD_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION")
                        _append_unique(
                            holds,
                            f"HOLD_GATE0V_KILL_{sup_hd}INFECTED_VIRAL_POS_UNIT_SUBSET_CONTRADICTION_{reg_tag}_{lin_tag}",
                        )
                        break

        if sampling_tracker is not None:
            for sub_key, _ek, _en, _iz in arm_estimand_specs:
                if sub_parsed[sub_key]["reconciled_ok"] and sub_cross_ok.get(sub_key, False):
                    sampling_tracker["partitions_reconciled"] += 1
    elif sampling_unit_class == "INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT":
        if "per_unit_counts" in lblock:
            # R13-B1: Single-cell mode NEVER accepts submitted `per_unit_counts` (adverse unit counts
            # were already escalated to FAIL_HARD_STOP by the pre-schema scanner; clean unexpected
            # partitions fail closed with HOLD_UNEXPECTED_PER_UNIT_COUNTS_IN_SINGLE_CELL_MODE!).
            arm_partition_ok = False
            if sampling_tracker is not None:
                sampling_tracker["all_partitions_reconciled"] = False
            _append_unique(holds, "HOLD_UNEXPECTED_PER_UNIT_COUNTS_IN_SINGLE_CELL_MODE")
            _append_unique(
                holds,
                f"HOLD_GATE0V_KILL_{sup_hd}UNEXPECTED_PER_UNIT_COUNTS_IN_SINGLE_CELL_MODE_{reg_tag}_{lin_tag}",
            )
        if not (
            _is_strict_int(indep_units_n)
            and indep_units_n >= MIN_INDEPENDENT_BIOLOGICAL_UNITS_N
            and all(indep_units_n >= d_n for d_n in arm_denoms)
        ):
            arm_partition_ok = False
            if sampling_tracker is not None:
                sampling_tracker["all_partitions_reconciled"] = False
            _append_unique(holds, "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS")
            _append_unique(
                holds,
                f"HOLD_GATE0V_KILL_{sup_hd}INDEPENDENT_UNIT_COUNT_BELOW_DENOMINATOR_{reg_tag}_{lin_tag}",
            )
        if is_infected_arm and not (
            _is_strict_int(rk) and _is_strict_int(rn) and rn >= 1 and 0 <= rk <= rn
            and _is_strict_int(frk) and _is_strict_int(frn) and frn >= 1 and 0 <= frk <= frn
        ):
            arm_partition_ok = False
            if sampling_tracker is not None:
                sampling_tracker["all_partitions_reconciled"] = False
            _append_unique(holds, "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS")
    else:
        arm_partition_ok = False
        if sampling_tracker is not None:
            sampling_tracker["all_partitions_reconciled"] = False
        if isinstance(raw_puc, dict) and is_infected_arm:
            p_inf_info = _inspect_per_unit_counts(
                raw_puc.get("infected_viral_pos_72h"),
                expected_units_n=indep_units_n,
                expected_k=vk_raw if _is_strict_int(vk_raw) else None,
                expected_n=n_in if _is_strict_int(n_in) else None,
            )
            if p_inf_info["any_pos_k"]:
                _append_unique(hard_stops, "HARD_STOP_ADVERSE_PER_UNIT_POST_AP1903_VIRAL_ESCAPE")
                _append_unique(hard_stops, f"FAIL_HARD_STOP_{sup_hs}POST_AP1903_VIABLE_VIRAL_SURVIVOR_{reg_tag}_{lin_tag}")

    is_clustered_deff_gt_1 = bool(deff is not None and deff > Decimal("1.0"))
    if not sampling_spec_valid or deff is None:
        is_exact_independent = False
        arm_confidence_scope = "UNCERTIFIED_MISSING_OR_INVALID_SAMPLING_SPEC"
    elif is_clustered_deff_gt_1:
        is_exact_independent = False
        arm_confidence_scope = "NON_AUTHORIZING_VARIANCE_ADJUSTED_DIAGNOSTIC_ONLY"
    elif not arm_partition_ok:
        is_exact_independent = False
        arm_confidence_scope = "UNCERTIFIED_SAMPLING_UNIT_PARTITION_MISMATCH"
    elif sampling_unit_class == "INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT":
        is_exact_independent = True
        arm_confidence_scope = "EXACT_INDEPENDENT_BINOMIAL_BONFERRONI_DEFF_EQ_1_UNIT_MATCHED"
    else:
        is_exact_independent = True
        arm_confidence_scope = "CONDITIONAL_ON_EXTERNALLY_VALIDATED_WITHIN_WELL_INDEPENDENCE_DEFF_EQ_1"

    arm_pass = bool(is_exact_independent)
    lin_detail: Dict[str, Any] = {
        "clustering_design_effect_deff": format(deff, "f") if deff is not None else None,
        "exact_directional_confidence_certified": is_exact_independent,
        "confidence_scope": arm_confidence_scope,
        "sampling_unit_partition_reconciled": bool(arm_partition_ok and sampling_spec_valid),
    }
    if is_infected_arm:
        if sampling_unit_class == "RECONCILED_MULTI_WELL_CELL_ASSAY_WITH_UNIT_PARTITION":
            _arm_cal_h_ok = bool(
                sub_parsed.get("spike_calibrant", {}).get("reconciled_ok")
                and sub_cross_ok.get("spike_calibrant", False)
            )
            _arm_cal_f_ok = bool(
                sub_parsed.get("fragile_infected_spike_calibrant", {}).get("reconciled_ok")
                and sub_cross_ok.get("fragile_infected_spike_calibrant", False)
            )
            lin_detail["spike_calibrant_sampling_units_reconciled"] = bool(
                _arm_cal_h_ok and _arm_cal_f_ok and sampling_spec_valid
            )
        elif sampling_unit_class == "INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT":
            lin_detail["spike_calibrant_sampling_units_reconciled"] = bool(
                arm_partition_ok and sampling_spec_valid
            )
        else:
            lin_detail["spike_calibrant_sampling_units_reconciled"] = False

    # R11-B3: Narrow exact Clopper-Pearson directional confidence authorization strictly to deff == 1.0
    # with valid reconciled sampling-unit basis (matching GY-018 and IIP-0044). Clustered/correlated
    # lots (deff > 1.0) NEVER certify release PASS!
    if is_clustered_deff_gt_1:
        _append_unique(holds, "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE")
        _append_unique(
            holds,
            f"HOLD_GATE0V_KILL_{sup_hd}CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE_{reg_tag}_{lin_tag}",
        )
        arm_pass = False

    def _check_ideal_sveh_conclusive_24h_hard_stop() -> None:
        """
        R04-B3 + R06-B3 + R07-M1 + R12-B1: Under a concurrent 24-h vehicle-control HOLD (missing, invalid,
        or s_veh_l975 < 0.10), ALWAYS enforce deterministic `a24_k > a24_n -> FAIL_HARD_STOP`, and when
        `deff` is present evaluate the 3-state ideal s_veh = 1.0 survivor check for ALL 0 <= a24_k <= a24_n:
          - Escalate to FAIL_HARD_STOP ONLY when conclusively adverse: `a24_k > a24_n` OR
            (when exact confidence is certified) `L_ideal(k_eff, n_eff; alpha_paired_surv) > 0.001`.
          - When `L_ideal <= 0.001 < U_ideal`, emit INDETERMINATE_INTERVAL_STRADDLING_CAP_UNDER_CONTROL_HOLD.
        """
        if _is_strict_int(a24_n) and a24_n >= 1 and _is_strict_int(a24_k):
            if a24_k > a24_n:
                _append_unique(hard_stops, f"FAIL_HARD_STOP_{sup_hs}AP1903_24H_INVALID_SURVIVORS_EXCEED_INPUT_{reg_tag}_{lin_tag}")
                lin_detail["conclusive_kill_failure_at_ideal_sveh_24h"] = True
                lin_detail["ideal_sveh_24h_adjudication"] = "DETERMINISTIC_HARD_STOP_SURVIVORS_EXCEED_INPUT"
            elif deff is None:
                lin_detail["conclusive_kill_failure_at_ideal_sveh_24h"] = False
                lin_detail["ideal_sveh_24h_adjudication"] = "UNCERTIFIED_MISSING_OR_INVALID_SAMPLING_SPEC"
            elif 0 <= a24_k <= a24_n:
                n_tr_24_ideal = _exact_floor_div_by_decimal(a24_n, deff)
                if n_tr_24_ideal < 1:
                    lin_detail["conclusive_kill_failure_at_ideal_sveh_24h"] = False
                    lin_detail["ideal_sveh_24h_adjudication"] = "INDETERMINATE_EFFECTIVE_DENOM_LT_1_UNDER_CONTROL_HOLD"
                else:
                    k_tr_24_eff_lo = (a24_k * n_tr_24_ideal) // a24_n
                    k_tr_24_eff_hi = (a24_k * n_tr_24_ideal + a24_n - 1) // a24_n
                    u24_ideal = exact_clopper_pearson_upper_general(k_tr_24_eff_hi, n_tr_24_ideal, alpha_paired_surv, prec=60)
                    l24_ideal = (
                        exact_clopper_pearson_lower_calibrant(k_tr_24_eff_lo, n_tr_24_ideal, alpha_paired_surv, prec=60)
                        if k_tr_24_eff_lo >= 1
                        else Decimal(0)
                    )
                    lin_detail["recomputed_l_surv_24h_ideal_sveh_lower"] = format(l24_ideal, "f")[:24]
                    lin_detail["recomputed_u_surv_24h_ideal_sveh_upper"] = format(u24_ideal, "f")[:24]
                    if not is_exact_independent:
                        lin_detail["conclusive_kill_failure_at_ideal_sveh_24h"] = False
                        lin_detail["ideal_sveh_24h_adjudication"] = (
                            "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE"
                            if is_clustered_deff_gt_1
                            else arm_confidence_scope
                        )
                    elif l24_ideal > Decimal("0.001"):
                        _append_unique(hard_stops, f"FAIL_HARD_STOP_{sup_hs}AP1903_24H_KILL_BELOW_99P9PCT_{reg_tag}_{lin_tag}")
                        with _clean_dec_ctx(60, ROUND_FLOOR):
                            kill24_ideal_hi = (Decimal(1) - l24_ideal) * Decimal(100)
                        lin_detail["recomputed_kill_24h_pct_ideal_sveh_upper_bound"] = _dec_to_float(kill24_ideal_hi, 6)
                        lin_detail["conclusive_kill_failure_at_ideal_sveh_24h"] = True
                        lin_detail["ideal_sveh_24h_adjudication"] = "CONCLUSIVE_FAILURE_LOWER_BOUND_EXCEEDS_CAP"
                    elif u24_ideal > Decimal("0.001"):
                        lin_detail["conclusive_kill_failure_at_ideal_sveh_24h"] = False
                        lin_detail["ideal_sveh_24h_adjudication"] = "INDETERMINATE_INTERVAL_STRADDLING_CAP_UNDER_CONTROL_HOLD"
                        _append_unique(holds, "HOLD_INDETERMINATE_INTERVAL_STRADDLING_CAP_UNDER_CONTROL_HOLD")
                        _append_unique(
                            holds,
                            f"HOLD_GATE0V_KILL_{sup_hd}24H_INDETERMINATE_INTERVAL_STRADDLING_CAP_UNDER_CONTROL_HOLD_{reg_tag}_{lin_tag}",
                        )
                    else:
                        lin_detail["conclusive_kill_failure_at_ideal_sveh_24h"] = False
                        lin_detail["ideal_sveh_24h_adjudication"] = "WITHIN_CAP_AT_IDEAL_SVEH_HELD_BY_CONTROL"

    def _check_ideal_sveh_conclusive_72h_hard_stop() -> None:
        """
        R04-B3 + R06-B3 + R07-M1 + R12-B1: Under a concurrent 72-h vehicle-control HOLD, ALWAYS enforce
        deterministic `a72_k > a72_n -> FAIL_HARD_STOP`, and when `deff` is present evaluate the 3-state
        ideal s_veh = 1.0 survivor check for ALL 0 <= a72_k <= a72_n.
        """
        if _is_strict_int(a72_n) and a72_n >= 1 and _is_strict_int(a72_k):
            if a72_k > a72_n:
                _append_unique(hard_stops, f"FAIL_HARD_STOP_{sup_hs}AP1903_72H_INVALID_SURVIVORS_EXCEED_INPUT_{reg_tag}_{lin_tag}")
                lin_detail["conclusive_kill_failure_at_ideal_sveh_72h"] = True
                lin_detail["ideal_sveh_72h_adjudication"] = "DETERMINISTIC_HARD_STOP_SURVIVORS_EXCEED_INPUT"
            elif deff is None:
                lin_detail["conclusive_kill_failure_at_ideal_sveh_72h"] = False
                lin_detail["ideal_sveh_72h_adjudication"] = "UNCERTIFIED_MISSING_OR_INVALID_SAMPLING_SPEC"
            elif 0 <= a72_k <= a72_n:
                n_tr_72_ideal = _exact_floor_div_by_decimal(a72_n, deff)
                if n_tr_72_ideal < 1:
                    lin_detail["conclusive_kill_failure_at_ideal_sveh_72h"] = False
                    lin_detail["ideal_sveh_72h_adjudication"] = "INDETERMINATE_EFFECTIVE_DENOM_LT_1_UNDER_CONTROL_HOLD"
                else:
                    k_tr_72_eff_lo = (a72_k * n_tr_72_ideal) // a72_n
                    k_tr_72_eff_hi = (a72_k * n_tr_72_ideal + a72_n - 1) // a72_n
                    u72_ideal = exact_clopper_pearson_upper_general(k_tr_72_eff_hi, n_tr_72_ideal, alpha_paired_surv, prec=60)
                    l72_ideal = (
                        exact_clopper_pearson_lower_calibrant(k_tr_72_eff_lo, n_tr_72_ideal, alpha_paired_surv, prec=60)
                        if k_tr_72_eff_lo >= 1
                        else Decimal(0)
                    )
                    lin_detail["recomputed_l_surv_72h_ideal_sveh_lower"] = format(l72_ideal, "f")[:24]
                    lin_detail["recomputed_u_surv_72h_ideal_sveh_upper"] = format(u72_ideal, "f")[:24]
                    if not is_exact_independent:
                        lin_detail["conclusive_kill_failure_at_ideal_sveh_72h"] = False
                        lin_detail["ideal_sveh_72h_adjudication"] = (
                            "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE"
                            if is_clustered_deff_gt_1
                            else arm_confidence_scope
                        )
                    elif l72_ideal > cap_frac_kill_esc_total:
                        _append_unique(hard_stops, f"FAIL_HARD_STOP_{sup_hs}AP1903_72H_PK_KILL_BELOW_4LOG10_{reg_tag}_{lin_tag}")
                        lin_detail["conclusive_kill_failure_at_ideal_sveh_72h"] = True
                        lin_detail["ideal_sveh_72h_adjudication"] = "CONCLUSIVE_FAILURE_LOWER_BOUND_EXCEEDS_CAP"
                    elif u72_ideal > cap_frac_kill_esc_total:
                        lin_detail["conclusive_kill_failure_at_ideal_sveh_72h"] = False
                        lin_detail["ideal_sveh_72h_adjudication"] = "INDETERMINATE_INTERVAL_STRADDLING_CAP_UNDER_CONTROL_HOLD"
                        _append_unique(holds, "HOLD_INDETERMINATE_INTERVAL_STRADDLING_CAP_UNDER_CONTROL_HOLD")
                        _append_unique(
                            holds,
                            f"HOLD_GATE0V_KILL_{sup_hd}72H_INDETERMINATE_INTERVAL_STRADDLING_CAP_UNDER_CONTROL_HOLD_{reg_tag}_{lin_tag}",
                        )
                    else:
                        lin_detail["conclusive_kill_failure_at_ideal_sveh_72h"] = False
                        lin_detail["ideal_sveh_72h_adjudication"] = "WITHIN_CAP_AT_IDEAL_SVEH_HELD_BY_CONTROL"

    # 1. Paired 24-h vehicle-adjusted kill check via EXACT component-probability ratio bound (R06-B2; Bonferroni 0.025 + 0.025 = 0.050)
    if not (
        _is_strict_int(v24_v) and _is_strict_int(v24_n) and v24_n >= 100 and 0 <= v24_v <= v24_n
        and _is_strict_int(a24_n) and a24_n >= 1
        and _is_strict_int(a24_k) and 0 <= a24_k <= a24_n
    ):
        holds.append(f"HOLD_GATE0V_KILL_{sup_hd}RAW_24H_COUNTS_REQUIRED_{reg_tag}_{lin_tag}")
        arm_pass = False
        _check_ideal_sveh_conclusive_24h_hard_stop()
    elif deff is None:
        arm_pass = False
        lin_detail["ratio_bound_method_24h"] = "uncertified_missing_or_invalid_sampling_spec"
        lin_detail["bonferroni_alpha_budget_24h"] = {
            "alpha_veh": str(alpha_paired_veh),
            "alpha_surv": str(alpha_paired_surv),
            "union_bound_sum": str(alpha_paired_veh + alpha_paired_surv),
            "exact_directional_confidence_certified": False,
            "confidence_scope": arm_confidence_scope,
            "joint_confidence_lower_bound": None,
            "confidence_statement_type": "UNCERTIFIED_MISSING_OR_INVALID_SAMPLING_SPEC",
            "scope": "uncertified_missing_or_invalid_sampling_spec",
        }
    else:
        b24 = exact_paired_vehicle_ratio_bounds(
            a24_k,
            a24_n,
            v24_v,
            v24_n,
            alpha_treated=alpha_paired_surv,
            alpha_veh=alpha_paired_veh,
            deff=deff,
            prec=80,
        )
        s_veh_24h_l975 = b24["s_veh_lower_dec"]
        lin_detail["recomputed_s_veh_24h_l975"] = _dec_to_float(s_veh_24h_l975, 6)
        lin_detail["ratio_bound_method_24h"] = (
            "exact_component_probability_bonferroni_ratio"
            if is_exact_independent
            else "non_authorizing_variance_adjusted_diagnostic_ratio"
        )
        lin_detail["bonferroni_alpha_budget_24h"] = {
            "alpha_veh": str(alpha_paired_veh),
            "alpha_surv": str(alpha_paired_surv),
            "union_bound_sum": str(alpha_paired_veh + alpha_paired_surv),
            "exact_directional_confidence_certified": is_exact_independent,
            "confidence_scope": arm_confidence_scope,
            "joint_confidence_lower_bound": "0.950" if is_exact_independent else None,
            "confidence_statement_type": (
                b24["confidence_statement_type"]
                if is_exact_independent
                else (
                    "NON_AUTHORIZING_VARIANCE_ADJUSTED_DIAGNOSTIC_ONLY_NOT_EXACT_CONFIDENCE"
                    if is_clustered_deff_gt_1
                    else arm_confidence_scope
                )
            ),
            "directional_one_sided_confidence_note": (
                "Upper (u_ratio) and lower (l_ratio) ratio limits are separate directional one-sided "
                "confidence statements at >= 1 - (alpha_veh + alpha_surv) = 0.950 each strictly at "
                "deff == 1.0 under a reconciled per-estimand sampling-unit basis, NOT a simultaneous "
                "two-sided interval at that unsplit alpha."
                if is_exact_independent
                else "NON-AUTHORIZING / UNCERTIFIED: exact directional Clopper-Pearson confidence is "
                "NOT certified without a valid reconciled deff == 1.0 sampling-unit basis."
            ),
            "scope": (
                "per_lineage_per_regime_estimand_deff_eq_1"
                if is_exact_independent
                else (
                    "non_authorizing_variance_adjusted_diagnostic_only_deff_gt_1"
                    if is_clustered_deff_gt_1
                    else "uncertified_sampling_unit_basis"
                )
            ),
        }
        if s_veh_24h_l975 < min_s_veh:
            holds.append(f"HOLD_GATE0V_KILL_{sup_hd}24H_VEHICLE_SURVIVAL_L975_BELOW_0P10_{reg_tag}_{lin_tag}")
            arm_pass = False
            # R04-B3 + R06-B3: Escalate to FAIL_HARD_STOP ONLY when L_ideal > 0.001 (conclusively adverse when exact certified)!
            _check_ideal_sveh_conclusive_24h_hard_stop()
        elif b24["n_treated_eff"] < 1:
            holds.append(f"HOLD_GATE0V_KILL_{sup_hd}24H_INVALID_EFFECTIVE_DENOM_{reg_tag}_{lin_tag}")
            arm_pass = False
            _check_ideal_sveh_conclusive_24h_hard_stop()
        else:
            u_ratio_24h = b24["u_ratio_dec"]
            l_ratio_24h = b24["l_ratio_dec"]
            with _clean_dec_ctx(80, ROUND_FLOOR):
                kill_24h_l95_joint = (Decimal(1) - u_ratio_24h) * Decimal(100)
            lin_detail["recomputed_n_treated_24h"] = b24["n_treated_eff"]
            lin_detail["recomputed_u_treated_24h_upper"] = format(b24["u_treated_dec"], "f")[:24]
            lin_detail["recomputed_u_ratio_24h_joint_upper"] = format(u_ratio_24h, "f")[:24]
            lin_detail["recomputed_l_ratio_24h_joint_lower"] = format(l_ratio_24h, "f")[:24]
            lin_detail["recomputed_kill_24h_pct_joint_l95"] = _dec_to_float(kill_24h_l95_joint, 6)
            lin_detail["ratio_estimand_domain_24h"] = "[0, +infinity)"
            lin_detail["u_ratio_clamped_to_unity_24h"] = False
            lin_detail["treated_survival_exceeds_vehicle_survival_24h"] = b24["treated_survival_exceeds_vehicle_survival"]
            lin_detail["ratio_lower_limit_exceeds_unity_24h"] = b24["ratio_lower_limit_exceeds_unity"]
            lin_detail["ratio_upper_limit_exceeds_unity_24h"] = b24["ratio_upper_limit_exceeds_unity"]
            lin_detail["ratio_bounds_ordered_l_le_u_24h"] = b24["bounds_ordered_l_le_u"]
            lin_detail["ratio_bounds_ordered_l_le_point_le_u_24h"] = b24["bounds_ordered_l_le_point_le_u"]
            if not is_exact_independent:
                lin_detail["diagnostic_24h_empirical_ratio_exceeds_cap"] = bool(
                    b24["empirical_ratio_point_estimate_dec"] is not None
                    and b24["empirical_ratio_point_estimate_dec"] > Decimal("0.001")
                )
                arm_pass = False
            elif u_ratio_24h > Decimal("0.001"):
                if l_ratio_24h > Decimal("0.001"):
                    _append_unique(hard_stops, f"FAIL_HARD_STOP_{sup_hs}AP1903_24H_KILL_BELOW_99P9PCT_{reg_tag}_{lin_tag}")
                elif a24_k == 0:
                    holds.append(f"HOLD_GATE0V_KILL_{sup_hd}24H_UNDERPOWERED_N_EFF_{reg_tag}_{lin_tag}")
                else:
                    holds.append(f"HOLD_GATE0V_KILL_{sup_hd}24H_INDETERMINATE_INTERVAL_STRADDLING_CAP_{reg_tag}_{lin_tag}")
                arm_pass = False

    # 2. Paired 72-h / pulsed-PK vehicle-adjusted kill check via EXACT component-probability ratio bound (R06-B2; Bonferroni 0.025 + 0.025 = 0.050)
    s_veh_72h_l975: Decimal | None = None
    s_veh_72h_u975: Decimal | None = None
    if not (
        _is_strict_int(v72_v) and _is_strict_int(v72_n) and v72_n >= 100 and 0 <= v72_v <= v72_n
        and _is_strict_int(a72_n) and a72_n >= 1
        and _is_strict_int(a72_k) and 0 <= a72_k <= a72_n
    ):
        holds.append(f"HOLD_GATE0V_KILL_{sup_hd}RAW_72H_COUNTS_REQUIRED_{reg_tag}_{lin_tag}")
        arm_pass = False
        _check_ideal_sveh_conclusive_72h_hard_stop()
    elif deff is None:
        arm_pass = False
        lin_detail["ratio_bound_method_72h"] = "uncertified_missing_or_invalid_sampling_spec"
        lin_detail["bonferroni_alpha_budget_72h"] = {
            "alpha_veh": str(alpha_paired_veh),
            "alpha_surv": str(alpha_paired_surv),
            "union_bound_sum": str(alpha_paired_veh + alpha_paired_surv),
            "exact_directional_confidence_certified": False,
            "confidence_scope": arm_confidence_scope,
            "joint_confidence_lower_bound": None,
            "confidence_statement_type": "UNCERTIFIED_MISSING_OR_INVALID_SAMPLING_SPEC",
            "scope": "uncertified_missing_or_invalid_sampling_spec",
        }
    else:
        b72 = exact_paired_vehicle_ratio_bounds(
            a72_k,
            a72_n,
            v72_v,
            v72_n,
            alpha_treated=alpha_paired_surv,
            alpha_veh=alpha_paired_veh,
            deff=deff,
            prec=80,
        )
        s_veh_72h_l975 = b72["s_veh_lower_dec"]
        s_veh_72h_u975 = b72["s_veh_upper_dec"]
        lin_detail["recomputed_s_veh_72h_l975"] = _dec_to_float(s_veh_72h_l975, 6)
        lin_detail["ratio_bound_method_72h"] = (
            "exact_component_probability_bonferroni_ratio"
            if is_exact_independent
            else "non_authorizing_variance_adjusted_diagnostic_ratio"
        )
        lin_detail["bonferroni_alpha_budget_72h"] = {
            "alpha_veh": str(alpha_paired_veh),
            "alpha_surv": str(alpha_paired_surv),
            "union_bound_sum": str(alpha_paired_veh + alpha_paired_surv),
            "exact_directional_confidence_certified": is_exact_independent,
            "confidence_scope": arm_confidence_scope,
            "joint_confidence_lower_bound": "0.950" if is_exact_independent else None,
            "confidence_statement_type": (
                b72["confidence_statement_type"]
                if is_exact_independent
                else (
                    "NON_AUTHORIZING_VARIANCE_ADJUSTED_DIAGNOSTIC_ONLY_NOT_EXACT_CONFIDENCE"
                    if is_clustered_deff_gt_1
                    else arm_confidence_scope
                )
            ),
            "directional_one_sided_confidence_note": (
                "Upper (u_ratio) and lower (l_ratio) ratio limits are separate directional one-sided "
                "confidence statements at >= 1 - (alpha_veh + alpha_surv) = 0.950 each strictly at "
                "deff == 1.0 under a reconciled per-estimand sampling-unit basis, NOT a simultaneous "
                "two-sided interval at that unsplit alpha."
                if is_exact_independent
                else "NON-AUTHORIZING / UNCERTIFIED: exact directional Clopper-Pearson confidence is "
                "NOT certified without a valid reconciled deff == 1.0 sampling-unit basis."
            ),
            "scope": (
                "per_lineage_per_regime_estimand_deff_eq_1"
                if is_exact_independent
                else (
                    "non_authorizing_variance_adjusted_diagnostic_only_deff_gt_1"
                    if is_clustered_deff_gt_1
                    else "uncertified_sampling_unit_basis"
                )
            ),
        }
        if s_veh_72h_l975 < min_s_veh:
            holds.append(f"HOLD_GATE0V_KILL_{sup_hd}72H_VEHICLE_SURVIVAL_L975_BELOW_0P10_{reg_tag}_{lin_tag}")
            arm_pass = False
            # R04-B3 + R06-B3: Escalate to FAIL_HARD_STOP ONLY when L_ideal > 0.0001 (conclusively adverse when exact certified)!
            _check_ideal_sveh_conclusive_72h_hard_stop()
        elif b72["n_treated_eff"] < 1:
            holds.append(f"HOLD_GATE0V_KILL_{sup_hd}72H_INVALID_EFFECTIVE_DENOM_{reg_tag}_{lin_tag}")
            arm_pass = False
            _check_ideal_sveh_conclusive_72h_hard_stop()
        else:
            u_ratio_72h = b72["u_ratio_dec"]
            l_ratio_72h = b72["l_ratio_dec"]
            lin_detail["recomputed_n_treated_72h"] = b72["n_treated_eff"]
            lin_detail["recomputed_u_treated_72h_upper"] = format(b72["u_treated_dec"], "f")[:24]
            lin_detail["recomputed_u_surv_72h_joint_upper"] = format(u_ratio_72h, "f")[:24]
            lin_detail["recomputed_l_surv_72h_joint_lower"] = format(l_ratio_72h, "f")[:24]
            lin_detail["recomputed_kill_72h_clears_4log10"] = bool(is_exact_independent and u_ratio_72h <= cap_frac_kill_esc_total)
            lin_detail["ratio_estimand_domain_72h"] = "[0, +infinity)"
            lin_detail["u_ratio_clamped_to_unity_72h"] = False
            lin_detail["treated_survival_exceeds_vehicle_survival_72h"] = b72["treated_survival_exceeds_vehicle_survival"]
            lin_detail["ratio_lower_limit_exceeds_unity_72h"] = b72["ratio_lower_limit_exceeds_unity"]
            lin_detail["ratio_upper_limit_exceeds_unity_72h"] = b72["ratio_upper_limit_exceeds_unity"]
            lin_detail["ratio_bounds_ordered_l_le_u_72h"] = b72["bounds_ordered_l_le_u"]
            lin_detail["ratio_bounds_ordered_l_le_point_le_u_72h"] = b72["bounds_ordered_l_le_point_le_u"]
            if not is_exact_independent:
                lin_detail["diagnostic_72h_empirical_ratio_exceeds_cap"] = bool(
                    b72["empirical_ratio_point_estimate_dec"] is not None
                    and b72["empirical_ratio_point_estimate_dec"] > cap_frac_kill_esc_total
                )
                arm_pass = False
            elif u_ratio_72h > cap_frac_kill_esc_total:
                if l_ratio_72h > cap_frac_kill_esc_total:
                    _append_unique(hard_stops, f"FAIL_HARD_STOP_{sup_hs}AP1903_72H_PK_KILL_BELOW_4LOG10_{reg_tag}_{lin_tag}")
                elif a72_k == 0:
                    holds.append(f"HOLD_GATE0V_KILL_{sup_hd}72H_UNDERPOWERED_N_EFF_{reg_tag}_{lin_tag}")
                else:
                    holds.append(f"HOLD_GATE0V_KILL_{sup_hd}72H_INDETERMINATE_INTERVAL_STRADDLING_CAP_{reg_tag}_{lin_tag}")
                arm_pass = False

    # 3. Infected-arm adjudication (always enforced for INFECTED_AP1903_REGIMES, plus
    #    unconditional adverse checks if infected-arm fields are submitted on any other arm!)
    if not is_infected_arm:
        casp_extra = _to_exact_decimal_nonneg(casp_fold_raw)
        if casp_extra is not None and casp_extra < Decimal("5.0"):
            hard_stops.append(f"FAIL_HARD_STOP_{sup_hs}VIRAL_CASPASE_BLOCKADE_REQUIRES_NON_CASPASE_BACKUP_SWITCH_{reg_tag}_{lin_tag}")
            arm_pass = False
        if _is_strict_int(vk_raw) and vk_raw >= 1:
            hard_stops.append(f"FAIL_HARD_STOP_{sup_hs}POST_AP1903_VIABLE_VIRAL_SURVIVOR_{reg_tag}_{lin_tag}")
            arm_pass = False
        return arm_pass, lin_detail

    # Infected arm: full caspase-9/3 blockade, viral survivor, aliquot linkage, dual calibrant,
    # Estimand 1, and Estimand 2 adjudication (identical rigor for required & supplemental arms!)
    casp_fold = _to_exact_decimal_nonneg(casp_fold_raw)
    casp_sha = lblock.get("viral_caspase_stratification_evidence_sha256")
    if casp_fold is None or casp_fold < Decimal(0) or casp_fold > Decimal("10000"):
        holds.append(f"HOLD_GATE0V_KILL_{sup_hd}MISSING_CASPASE9_3_ACTIVITY_{reg_tag}_{lin_tag}")
        arm_pass = False
    elif casp_fold < Decimal("5.0"):
        hard_stops.append(
            f"FAIL_HARD_STOP_{sup_hs}VIRAL_CASPASE_BLOCKADE_REQUIRES_NON_CASPASE_BACKUP_SWITCH_{reg_tag}_{lin_tag}"
        )
        arm_pass = False
    if not _is_valid_sha256_hex(casp_sha):
        holds.append(f"HOLD_GATE0V_KILL_{sup_hd}MISSING_VIRAL_CASPASE_EVIDENCE_SHA256_{reg_tag}_{lin_tag}")
        arm_pass = False

    surv_n = lblock.get("post_ap1903_viable_survivors_total_n")
    surv_scored_n = lblock.get("survivors_scored_n")
    vk = vk_raw
    aliquot_id = lblock.get("aliquot_linkage_id")
    aliquot_mode = lblock.get("infected_surveillance_aliquot_linkage_mode")
    supplied_escape_mode = lblock.get("infected_cell_escape_mode")
    pt_k = lblock.get("pretreat_viral_pos_k")
    pt_n = lblock.get("pretreat_scored_n")
    pre_dissoc_k = lblock.get("pre_dissociation_spike_in_attested")
    spike_k_sha = lblock.get("pre_dissociation_spike_sop_evidence_sha256")

    # Unconditional hard-stop veto on ANY viable viral-positive survivor (never masked by HOLD!)
    if _is_strict_int(vk) and vk >= 1:
        _append_unique(hard_stops, f"FAIL_HARD_STOP_{sup_hs}POST_AP1903_VIABLE_VIRAL_SURVIVOR_{reg_tag}_{lin_tag}")
        arm_pass = False

    # R07-B2: Strictly enforce the published SAME_72H_ALIQUOT count-reconciliation rule for
    # release authorization (`n_in == a72_n` and `surv_n == a72_k`). Any non-same-aliquot mode
    # (e.g. PAIRED_HIGH_INPUT_ALIQUOT, even with a syntactically valid 64-hex digest) fails closed
    # to non-authorizing HOLD (`HOLD_NON_SAME_ALIQUOT_UNVERIFIED_COUNT_RECONCILIATION`) and NEVER
    # authorizes PASS, while downstream adverse checks still run to preserve FAIL_HARD_STOP!
    aliquot_reconciled_ok = False
    if not _is_valid_identifier(aliquot_id):
        _append_unique(holds, f"HOLD_GATE0V_KILL_{sup_hd}MISSING_ALIQUOT_LINKAGE_{reg_tag}_{lin_tag}")
        arm_pass = False
    if aliquot_mode != "SAME_72H_ALIQUOT":
        if not _is_valid_identifier(aliquot_mode):
            _append_unique(holds, f"HOLD_GATE0V_KILL_{sup_hd}MISSING_ALIQUOT_LINKAGE_{reg_tag}_{lin_tag}")
        _append_unique(holds, "HOLD_NON_SAME_ALIQUOT_UNVERIFIED_COUNT_RECONCILIATION")
        _append_unique(
            holds,
            f"HOLD_GATE0V_KILL_{sup_hd}NON_SAME_ALIQUOT_UNVERIFIED_COUNT_RECONCILIATION_{reg_tag}_{lin_tag}",
        )
        if n_in != a72_n or surv_n != a72_k:
            _append_unique(holds, f"HOLD_GATE0V_KILL_{sup_hd}ALIQUOT_SURVIVOR_COUNT_MISMATCH_{reg_tag}_{lin_tag}")
        arm_pass = False
    else:
        if n_in != a72_n or surv_n != a72_k:
            _append_unique(holds, f"HOLD_GATE0V_KILL_{sup_hd}ALIQUOT_SURVIVOR_COUNT_MISMATCH_{reg_tag}_{lin_tag}")
            arm_pass = False
        elif _is_valid_identifier(aliquot_id):
            aliquot_reconciled_ok = True
    lin_detail["aliquot_count_reconciliation_verified"] = aliquot_reconciled_ok
    lin_detail["aliquot_release_authorizing_eligible"] = aliquot_reconciled_ok

    # Always adjudicate pre-dissociation spike attestation & dual calibrant independently of vehicle survival
    if pre_dissoc_k is not True or not _is_valid_sha256_hex(spike_k_sha):
        holds.append(f"HOLD_GATE0V_KILL_{sup_hd}PRE_DISSOCIATION_SPIKE_OR_DIGEST_MISSING_{reg_tag}_{lin_tag}")
        arm_pass = False
    eta_kill: Decimal | None = None
    if not (
        _is_strict_int(rk) and _is_strict_int(rn) and rn >= 1 and 0 <= rk <= rn
        and _is_strict_int(frk) and _is_strict_int(frn) and frn >= 1 and 0 <= frk <= frn
    ):
        holds.append(f"HOLD_GATE0V_KILL_{sup_hd}MISSING_OR_INVALID_DUAL_CALIBRANT_{reg_tag}_{lin_tag}")
        arm_pass = False
    else:
        # Intersection-union principle: min(L_h(alpha_eta), L_f(alpha_eta)) has error <= alpha_eta!
        eta_k_h = exact_clopper_pearson_lower_calibrant(rk, rn, alpha_e1_eta, prec=80)
        eta_k_f = exact_clopper_pearson_lower_calibrant(frk, frn, alpha_e1_eta, prec=80)
        eta_kill = min(eta_k_h, eta_k_f)
        lin_detail["eta_kill_effective_lower_80d"] = format(eta_kill, "f")[:24]
        if eta_kill < min_eta_cal:
            holds.append(f"HOLD_GATE0V_KILL_{sup_hd}CALIBRANT_BELOW_0P80_{reg_tag}_{lin_tag}")
            arm_pass = False

    if not (_is_strict_int(n_in) and n_in >= 1):
        holds.append(f"HOLD_GATE0V_KILL_{sup_hd}MISSING_PRE_AP1903_INPUT_CELLS_{reg_tag}_{lin_tag}")
        arm_pass = False
    elif deff is None:
        # R12-B1: Preserve deterministic `surv_n > n_in` hard stop even when sampling spec is missing/invalid!
        if _is_strict_int(surv_n) and surv_n > n_in:
            _append_unique(hard_stops, f"FAIL_HARD_STOP_{sup_hs}AP1903_72H_INFECTED_ALIQUOT_SURVIVORS_EXCEED_INPUT_{reg_tag}_{lin_tag}")
            lin_detail["ideal_sveh_72h_infected_aliquot_adjudication"] = "DETERMINISTIC_HARD_STOP_SURVIVORS_EXCEED_INPUT"
        else:
            lin_detail["ideal_sveh_72h_infected_aliquot_adjudication"] = "UNCERTIFIED_MISSING_OR_INVALID_SAMPLING_SPEC"
        lin_detail["estimand2_release_authorizing_eligible"] = False
        arm_pass = False
    elif s_veh_72h_l975 is None or s_veh_72h_l975 < min_s_veh:
        # R04-B3 + R06-B3 + R07-M1: Under a concurrent 72-h vehicle-control HOLD, evaluate the
        # 3-state ideal s_veh = 1.0 check for ALL 0 <= surv_n <= n_in (including zero-event
        # straddles such as 0/1,000!). Escalate to FAIL_HARD_STOP ONLY when conclusively adverse!
        if _is_strict_int(surv_n):
            if surv_n > n_in:
                _append_unique(hard_stops, f"FAIL_HARD_STOP_{sup_hs}AP1903_72H_INFECTED_ALIQUOT_SURVIVORS_EXCEED_INPUT_{reg_tag}_{lin_tag}")
                lin_detail["ideal_sveh_72h_infected_aliquot_adjudication"] = "DETERMINISTIC_HARD_STOP_SURVIVORS_EXCEED_INPUT"
                arm_pass = False
            elif 0 <= surv_n <= n_in:
                n_tot_ideal = _exact_floor_div_by_decimal(n_in, deff)
                if n_tot_ideal < 1:
                    lin_detail["ideal_sveh_72h_infected_aliquot_adjudication"] = "INDETERMINATE_EFFECTIVE_DENOM_LT_1_UNDER_CONTROL_HOLD"
                else:
                    k_tot_eff_lo = (surv_n * n_tot_ideal) // n_in
                    k_tot_eff_hi = (surv_n * n_tot_ideal + n_in - 1) // n_in
                    u_tot_ideal = exact_clopper_pearson_upper_general(k_tot_eff_hi, n_tot_ideal, alpha_paired_surv, prec=60)
                    l_tot_ideal = (
                        exact_clopper_pearson_lower_calibrant(k_tot_eff_lo, n_tot_ideal, alpha_paired_surv, prec=60)
                        if k_tot_eff_lo >= 1
                        else Decimal(0)
                    )
                    lin_detail["recomputed_l_surv_72h_infected_aliquot_ideal_sveh_lower"] = format(l_tot_ideal, "f")[:24]
                    lin_detail["recomputed_u_surv_72h_infected_aliquot_ideal_sveh_upper"] = format(u_tot_ideal, "f")[:24]
                    if not is_exact_independent:
                        lin_detail["ideal_sveh_72h_infected_aliquot_adjudication"] = (
                            "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE"
                            if is_clustered_deff_gt_1
                            else arm_confidence_scope
                        )
                        arm_pass = False
                    elif l_tot_ideal > cap_frac_kill_esc_total:
                        _append_unique(hard_stops, f"FAIL_HARD_STOP_{sup_hs}AP1903_72H_PK_KILL_BELOW_4LOG10_{reg_tag}_{lin_tag}")
                        lin_detail["ideal_sveh_72h_infected_aliquot_adjudication"] = "CONCLUSIVE_FAILURE_LOWER_BOUND_EXCEEDS_CAP"
                        arm_pass = False
                    elif u_tot_ideal > cap_frac_kill_esc_total:
                        lin_detail["ideal_sveh_72h_infected_aliquot_adjudication"] = "INDETERMINATE_INTERVAL_STRADDLING_CAP_UNDER_CONTROL_HOLD"
                        _append_unique(holds, "HOLD_INDETERMINATE_INTERVAL_STRADDLING_CAP_UNDER_CONTROL_HOLD")
                        _append_unique(
                            holds,
                            f"HOLD_GATE0V_KILL_{sup_hd}72H_INDETERMINATE_INTERVAL_STRADDLING_CAP_UNDER_CONTROL_HOLD_{reg_tag}_{lin_tag}",
                        )
                        arm_pass = False
                    else:
                        lin_detail["ideal_sveh_72h_infected_aliquot_adjudication"] = "WITHIN_CAP_AT_IDEAL_SVEH_HELD_BY_CONTROL"
        if direct_inf_veh_k is None and _is_strict_int(pt_k) and _is_strict_int(pt_n) and pt_n >= 1000 and 1 <= pt_k <= pt_n:
            lin_detail["infected_cell_escape_mode"] = "CONDITIONAL_INDIRECT_DIAGNOSTIC_ONLY_UNVERIFIED_SURVIVAL_INEQUALITY"
            lin_detail["estimand2_release_authorizing_eligible"] = False
            _append_unique(holds, "HOLD_INDIRECT_CONDITIONAL_ESCAPE_UNSUPPORTED_FOR_RELEASE")
            arm_pass = False
    elif s_veh_72h_l975 is not None and s_veh_72h_l975 >= min_s_veh:
        n_in_eff = _exact_floor_div_by_decimal(n_in, deff)
        lin_detail["aliquot_linkage_id"] = aliquot_id if isinstance(aliquot_id, str) else None
        lin_detail["infected_surveillance_aliquot_linkage_mode"] = aliquot_mode
        lin_detail["pre_ap1903_lineage_input_cells_n"] = n_in
        lin_detail["estimand1_n_treated_eff"] = n_in_eff

        if not (_is_strict_int(surv_n) and 0 <= surv_n <= n_in):
            if _is_strict_int(surv_n) and surv_n > n_in:
                _append_unique(hard_stops, f"FAIL_HARD_STOP_{sup_hs}AP1903_72H_INFECTED_ALIQUOT_SURVIVORS_EXCEED_INPUT_{reg_tag}_{lin_tag}")
            holds.append(f"HOLD_GATE0V_KILL_{sup_hd}INVALID_POST_SURVIVORS_COUNT_{reg_tag}_{lin_tag}")
            arm_pass = False
        elif n_in_eff < 1:
            holds.append(f"HOLD_GATE0V_KILL_{sup_hd}EFFECTIVE_DENOM_ZERO_{reg_tag}_{lin_tag}")
            arm_pass = False
        else:
            b_tot = exact_paired_vehicle_ratio_bounds(
                surv_n,
                n_in,
                v72_v,
                v72_n,
                alpha_treated=alpha_paired_surv,
                alpha_veh=alpha_paired_veh,
                deff=deff,
                prec=80,
            )
            if is_exact_independent and b_tot["l_ratio_dec"] > cap_frac_kill_esc_total:
                _append_unique(hard_stops, f"FAIL_HARD_STOP_{sup_hs}AP1903_72H_INFECTED_ALIQUOT_SURVIVORS_EXCEED_CAP_{reg_tag}_{lin_tag}")
                arm_pass = False
            if not (_is_strict_int(surv_scored_n) and surv_scored_n == surv_n):
                holds.append(f"HOLD_GATE0V_KILL_{sup_hd}SURVIVORS_SCORED_MISMATCH_{reg_tag}_{lin_tag}")
                arm_pass = False
            elif not (_is_strict_int(vk) and 0 <= vk <= surv_scored_n):
                holds.append(f"HOLD_GATE0V_KILL_{sup_hd}INVALID_POST_VIRAL_POS_COUNT_{reg_tag}_{lin_tag}")
                arm_pass = False
            elif eta_kill is not None:
                # ESTIMAND 1 (R06-B2 + R11-B3 + R12-B1): Exact component-probability ratio bound strictly at deff == 1.0 with reconciled sampling basis!
                # B4 budget: alpha_veh(0.025) + alpha_eta(0.005) + alpha_escape(0.005) = 0.035 <= 0.050 (>= 96.5% joint)
                if eta_kill <= Decimal(0):
                    u_esc_total = Decimal(1)
                else:
                    e1_ratio = exact_component_probability_ratio_upper(
                        vk,
                        n_in,
                        alpha_e1_esc,
                        (s_veh_72h_l975, eta_kill),
                        deff=deff,
                        prec=80,
                    )
                    u_esc_total = e1_ratio["u_ratio_dec"]
                lin_detail["estimand1_ratio_bound_method"] = (
                    "exact_component_probability_bonferroni_ratio"
                    if is_exact_independent
                    else "non_authorizing_variance_adjusted_diagnostic_ratio"
                )
                lin_detail["estimand1_bonferroni_alpha_budget"] = {
                    "alpha_veh": str(alpha_paired_veh),
                    "alpha_eta": str(alpha_e1_eta),
                    "alpha_escape": str(alpha_e1_esc),
                    "union_bound_sum": str(alpha_paired_veh + alpha_e1_eta + alpha_e1_esc),
                    "exact_directional_confidence_certified": is_exact_independent,
                    "confidence_scope": arm_confidence_scope,
                    "joint_confidence_lower_bound": "0.965" if is_exact_independent else None,
                    "confidence_statement_type": (
                        "DIRECTIONAL_ONE_SIDED_UPPER_AT_1_MINUS_ALPHA_SUM"
                        if is_exact_independent
                        else (
                            "NON_AUTHORIZING_VARIANCE_ADJUSTED_DIAGNOSTIC_ONLY_NOT_EXACT_CONFIDENCE"
                            if is_clustered_deff_gt_1
                            else arm_confidence_scope
                        )
                    ),
                    "scope": (
                        "per_lineage_per_regime_estimand_not_familywise_across_all_5x2_arms"
                        if is_exact_independent
                        else (
                            "non_authorizing_variance_adjusted_diagnostic_only_deff_gt_1"
                            if is_clustered_deff_gt_1
                            else "uncertified_sampling_unit_basis"
                        )
                    ),
                }
                lin_detail["estimand1_u_esc_per_total_input_80d"] = format(u_esc_total, "f")[:24]
                lin_detail["post_ap1903_viable_survivors_total_n"] = surv_n
                lin_detail["survivors_scored_n"] = surv_scored_n
                lin_detail["post_ap1903_viable_viral_pos_k"] = vk
                if vk == 0 and eta_kill > Decimal(0) and u_esc_total > cap_frac_kill_esc_total:
                    holds.append(f"HOLD_GATE0V_KILL_{sup_hd}ESTIMAND1_TOTAL_INPUT_TOO_SMALL_{reg_tag}_{lin_tag}")
                    arm_pass = False

                # ESTIMAND 2 (B4 + R06-B1 + R06-B2 + R11-B3 + R12-B1): Conditional per pre-treatment infected cells at risk!
                e2_ratio_factors: Tuple[Decimal, ...] | None = None
                e2_alpha_escape: Decimal | None = None
                if direct_inf_veh_k is not None:
                    if supplied_escape_mode not in (None, "DIRECT_INFECTED_VEHICLE_DENOMINATOR"):
                        holds.append(f"HOLD_GATE0V_KILL_{sup_hd}CONFLICTING_INFECTED_CELL_ESCAPE_MODE_{reg_tag}_{lin_tag}")
                        arm_pass = False
                    if not (_is_strict_int(direct_inf_veh_k) and _is_strict_int(v72_v) and _is_strict_int(v72_n) and 1 <= direct_inf_veh_k <= v72_v <= v72_n):
                        holds.append(f"HOLD_GATE0V_KILL_{sup_hd}INVALID_DIRECT_INFECTED_VEH_SURVIVOR_COUNT_{reg_tag}_{lin_tag}")
                        arm_pass = False
                    else:
                        q_inf_veh_l975 = exact_clopper_pearson_lower_calibrant(direct_inf_veh_k, v72_n, alpha_e2_dir_inf_veh, prec=60)
                        e2_ratio_factors = (q_inf_veh_l975, eta_kill)
                        e2_alpha_escape = alpha_e2_dir_esc
                        lin_detail["infected_cell_escape_mode"] = "DIRECT_INFECTED_VEHICLE_DENOMINATOR"
                        lin_detail["estimand2_denominator_mode"] = (
                            "DIRECT_EXACT_BINOMIAL_RATIO_WITHOUT_INDIRECT_SURVIVAL_INEQUALITY_CONDITIONAL_ON_REPRESENTATIVE_PAIRED_ALIQUOTS"
                        )
                        lin_detail["estimand2_sampling_model_qualifier"] = (
                            "DIRECT_EXACT_BINOMIAL_RATIO_WITHOUT_INDIRECT_SURVIVAL_INEQUALITY_CONDITIONAL_ON_REPRESENTATIVE_PAIRED_ALIQUOTS"
                        )
                        lin_detail["estimand2_ratio_bound_method"] = (
                            "exact_component_probability_bonferroni_ratio"
                            if is_exact_independent
                            else "non_authorizing_variance_adjusted_diagnostic_ratio"
                        )
                        lin_detail["estimand2_release_authorizing_eligible"] = bool(is_exact_independent)
                        lin_detail["estimand2_bonferroni_alpha_budget"] = {
                            "alpha_inf_veh": str(alpha_e2_dir_inf_veh),
                            "alpha_eta": str(alpha_e2_dir_eta),
                            "alpha_escape": str(alpha_e2_dir_esc),
                            "union_bound_sum": str(alpha_e2_dir_inf_veh + alpha_e2_dir_eta + alpha_e2_dir_esc),
                            "exact_directional_confidence_certified": is_exact_independent,
                            "confidence_scope": arm_confidence_scope,
                            "joint_confidence_lower_bound": "0.950" if is_exact_independent else None,
                            "confidence_statement_type": (
                                "DIRECTIONAL_ONE_SIDED_UPPER_AT_1_MINUS_ALPHA_SUM"
                                if is_exact_independent
                                else (
                                    "NON_AUTHORIZING_VARIANCE_ADJUSTED_DIAGNOSTIC_ONLY_NOT_EXACT_CONFIDENCE"
                                    if is_clustered_deff_gt_1
                                    else arm_confidence_scope
                                )
                            ),
                            "scope": (
                                "per_lineage_per_regime_estimand_not_familywise_across_all_5x2_arms"
                                if is_exact_independent
                                else (
                                    "non_authorizing_variance_adjusted_diagnostic_only_deff_gt_1"
                                    if is_clustered_deff_gt_1
                                    else "uncertified_sampling_unit_basis"
                                )
                            ),
                        }
                        lin_detail["estimand2_joint_coverage_lower_bound"] = (
                            (
                                "0.950 per lineage x regime estimand at deff == 1.0 (direct exact component-ratio Bonferroni: "
                                "0.025 inf_veh + 0.005 eta + 0.020 escape = 0.050; conditional on valid measured "
                                "fractions, calibrated detection efficiency eta, reconciled sampling-unit basis, and "
                                "representative paired aliquots)"
                            )
                            if is_exact_independent
                            else (
                                "NON-AUTHORIZING / UNCERTIFIED: does NOT certify 0.950 directional confidence "
                                "without a valid reconciled deff == 1.0 sampling-unit basis."
                            )
                        )
                        lin_detail["estimand2_direct_infected_veh_frac_l975"] = _dec_to_float(q_inf_veh_l975, 6)
                        lin_detail["estimand2_identifiability_assumption"] = (
                            "Removes the unverified indirect survival inequality (s_veh_infected >= s_veh_bulk) "
                            "by directly measuring viable infected survivors in the 72-h vehicle control; exact "
                            "binomial component-ratio bound applies strictly at deff == 1.0 under a reconciled "
                            "sampling-unit basis and remains conditional on valid measured fractions, calibrated "
                            "detection efficiency (eta), externally validated within-well independence (for multi-well "
                            "assays), and representative paired aliquots."
                        )
                elif supplied_escape_mode == "DIRECT_INFECTED_VEHICLE_DENOMINATOR":
                    holds.append(f"HOLD_GATE0V_KILL_{sup_hd}MISSING_DIRECT_INFECTED_VEH_SURVIVOR_COUNT_{reg_tag}_{lin_tag}")
                    arm_pass = False
                elif not (_is_strict_int(pt_k) and _is_strict_int(pt_n) and pt_n >= 1000 and 1 <= pt_k <= pt_n):
                    holds.append(f"HOLD_GATE0V_KILL_{sup_hd}MISSING_PRETREAT_INFECTED_DENOMINATOR_{reg_tag}_{lin_tag}")
                    arm_pass = False
                else:
                    # R06-B1: Indirect marginal estimation is DIAGNOSTIC ONLY — NEVER authorizes PASS!
                    s_veh_72h_l985 = exact_clopper_pearson_lower_calibrant(v72_v, v72_n, alpha_e2_ind_veh, prec=60)
                    p_inf_l985 = exact_clopper_pearson_lower_calibrant(pt_k, pt_n, alpha_e2_ind_prev, prec=60)
                    e2_ratio_factors = (s_veh_72h_l985, p_inf_l985, eta_kill)
                    e2_alpha_escape = alpha_e2_ind_esc
                    lin_detail["infected_cell_escape_mode"] = "CONDITIONAL_INDIRECT_DIAGNOSTIC_ONLY_UNVERIFIED_SURVIVAL_INEQUALITY"
                    lin_detail["estimand2_denominator_mode"] = "CONDITIONAL_INDIRECT_DIAGNOSTIC_ONLY_UNVERIFIED_SURVIVAL_INEQUALITY"
                    lin_detail["estimand2_ratio_bound_method"] = (
                        "exact_component_probability_bonferroni_ratio"
                        if is_exact_independent
                        else "non_authorizing_variance_adjusted_diagnostic_ratio"
                    )
                    lin_detail["estimand2_release_authorizing_eligible"] = False
                    lin_detail["estimand2_bonferroni_alpha_budget"] = {
                        "alpha_veh": str(alpha_e2_ind_veh),
                        "alpha_prev": str(alpha_e2_ind_prev),
                        "alpha_eta": str(alpha_e2_ind_eta),
                        "alpha_escape": str(alpha_e2_ind_esc),
                        "union_bound_sum": str(alpha_e2_ind_veh + alpha_e2_ind_prev + alpha_e2_ind_eta + alpha_e2_ind_esc),
                        "exact_directional_confidence_certified": is_exact_independent,
                        "confidence_scope": arm_confidence_scope,
                        "joint_confidence_lower_bound": "0.950" if is_exact_independent else None,
                        "confidence_statement_type": (
                            "DIRECTIONAL_ONE_SIDED_UPPER_AT_1_MINUS_ALPHA_SUM"
                            if is_exact_independent
                            else (
                                "NON_AUTHORIZING_VARIANCE_ADJUSTED_DIAGNOSTIC_ONLY_NOT_EXACT_CONFIDENCE"
                                if is_clustered_deff_gt_1
                                else arm_confidence_scope
                            )
                        ),
                        "scope": (
                            "diagnostic_only_per_lineage_per_regime_estimand_conditional_on_unverified_survival_inequality"
                            if is_exact_independent
                            else (
                                "non_authorizing_variance_adjusted_diagnostic_only_deff_gt_1"
                                if is_clustered_deff_gt_1
                                else "uncertified_sampling_unit_basis"
                            )
                        ),
                    }
                    lin_detail["estimand2_joint_coverage_lower_bound"] = (
                        (
                            "0.950 diagnostic-only at deff == 1.0 conditional on unverified s_veh_infected >= s_veh_bulk "
                            "(indirect exact component-ratio Bonferroni: 0.015 veh + 0.015 prev + 0.005 eta + 0.015 escape = 0.050)"
                        )
                        if is_exact_independent
                        else (
                            "NON-AUTHORIZING DIAGNOSTIC ONLY: does NOT certify 0.950 directional confidence."
                        )
                    )
                    lin_detail["estimand2_s_veh_72h_l985"] = _dec_to_float(s_veh_72h_l985, 6)
                    lin_detail["estimand2_pretreat_infected_frac_l985"] = _dec_to_float(p_inf_l985, 6)
                    lin_detail["estimand2_identifiability_assumption"] = (
                        "DIAGNOSTIC ONLY (UNSUPPORTED FOR RELEASE): relies on unverified survival inequality "
                        "s_veh_infected >= s_veh_bulk; supply direct pretreat_infected_veh_survivor_n out of "
                        "veh_72h_input_n (DIRECT_INFECTED_VEHICLE_DENOMINATOR) at deff == 1.0 with reconciled "
                        "sampling-unit partition for release-authorizing PASS."
                    )
                    _append_unique(holds, "HOLD_INDIRECT_CONDITIONAL_ESCAPE_UNSUPPORTED_FOR_RELEASE")
                    _append_unique(
                        holds,
                        f"HOLD_GATE0V_KILL_{sup_hd}INDIRECT_CONDITIONAL_ESCAPE_UNSUPPORTED_FOR_RELEASE_{reg_tag}_{lin_tag}",
                    )
                    arm_pass = False

                if e2_ratio_factors is not None and e2_alpha_escape is not None:
                    if eta_kill <= Decimal(0):
                        u_esc_cond = Decimal(1)
                        holds.append(f"HOLD_GATE0V_KILL_{sup_hd}ESTIMAND2_CONDITIONAL_INFECTED_TOO_SMALL_{reg_tag}_{lin_tag}")
                        arm_pass = False
                    else:
                        e2_ratio = exact_component_probability_ratio_upper(
                            vk,
                            n_in,
                            e2_alpha_escape,
                            e2_ratio_factors,
                            deff=deff,
                            prec=80,
                        )
                        u_esc_cond = e2_ratio["u_ratio_dec"]
                        lin_detail["estimand2_u_esc_conditional_per_infected_80d"] = format(u_esc_cond, "f")[:24]
                        lin_detail["estimand2_clears_3log10_conditional"] = bool(is_exact_independent and u_esc_cond <= cap_frac_kill_esc_cond)
                        lin_detail["estimand2_clears_4log10_conditional"] = bool(is_exact_independent and u_esc_cond <= cap_frac_kill_esc_total)
                        if vk == 0 and u_esc_cond > cap_frac_kill_esc_cond:
                            holds.append(f"HOLD_GATE0V_KILL_{sup_hd}ESTIMAND2_CONDITIONAL_INFECTED_TOO_SMALL_{reg_tag}_{lin_tag}")
                            arm_pass = False

    return arm_pass, lin_detail


def _adjudicate_supplemental_kill_regime_adverse_data(
    reg: str,
    rblock: Any,
    *,
    deff: Decimal | None,
    hard_stops: List[str],
    holds: List[str],
    adjudicated_log: List[str],
    sampling_spec_valid: bool = True,
    sampling_unit_class: str | None = None,
    indep_units_n: int | None = None,
    sampling_tracker: Dict[str, Any] | None = None,
) -> Dict[str, Any]:
    """
    R03-B1 / B6 rule: Apply FULL consistent fail-closed raw-count, calibration, aliquot,
    caspase, and dual-estimand adjudication (same rigor as the required branch!) to EVERY
    submitted supplemental stress regime / lineage arm in abbreviated tiers.
    NEVER silently skip a survivor count exceeding n_eff, invalid counts, or bad calibration!
    """
    reg_tag = str(reg).upper()
    adjudicated_log.append(f"supplemental_kill_regime:{reg}")

    if reg not in STRESS_AP1903_REGIMES:
        holds.append(f"HOLD_GATE0V_KILL_SUPPLEMENTAL_UNRECOGNIZED_REGIME_{reg_tag}")
    if not isinstance(rblock, dict) or len(rblock) == 0:
        holds.append(f"HOLD_GATE0V_KILL_SUPPLEMENTAL_INVALID_OR_EMPTY_REGIME_{reg_tag}")
        return {"passed": False, "lineages": {}}

    reg_pass = reg in STRESS_AP1903_REGIMES
    reg_lineage_details: Dict[str, Any] = {}
    for lin_name, lblock in rblock.items():
        lin_tag = str(lin_name).upper()
        if lin_name not in GRAFT_LINEAGES:
            holds.append(f"HOLD_UNRECOGNIZED_LINEAGE_KEY_GATE0V_KILL_SUPPLEMENTAL_{reg_tag}_{lin_tag}")
            holds.append(f"HOLD_GATE0V_KILL_SUPPLEMENTAL_UNRECOGNIZED_LINEAGE_{reg_tag}_{lin_tag}")
            reg_pass = False
        if not isinstance(lblock, dict):
            holds.append(f"HOLD_GATE0V_KILL_SUPPLEMENTAL_INVALID_LINEAGE_BLOCK_{reg_tag}_{lin_tag}")
            reg_pass = False
            continue
        arm_ok, lin_detail = _adjudicate_kill_regime_lineage_arm(
            reg,
            lin_name,
            lblock,
            deff=deff,
            hard_stops=hard_stops,
            holds=holds,
            is_supplemental=True,
            sampling_spec_valid=sampling_spec_valid,
            sampling_unit_class=sampling_unit_class,
            indep_units_n=indep_units_n,
            sampling_tracker=sampling_tracker,
        )
        if not arm_ok:
            reg_pass = False
        reg_lineage_details[lin_name] = lin_detail
    return {"passed": reg_pass, "lineages": reg_lineage_details}


def evaluate_wholegraft_gate0v_and_stress_ap1903(
    payload: Dict[str, Any],
    *,
    trusted_qualification_store: Path | str | None = None,
    openislet_root: Path | None = None,
    _revalidating_archived_bank: bool = False,
    _nw08_ocr_adjudicated_externally: bool = False,
) -> Dict[str, Any]:
    """
    Fail-closed evaluator for EXP-031 / IIP-0043 / DEC-122 Whole-Graft Gate 0V & Stress-State AP1903
    (Round-02 remediated across B1-B8 and M1-M4):
      - B1: Prior BANK_QUALIFICATION / AUTOLOGOUS_D1B_PROCESS_QUAL approval is resolved SOLELY
            from an independent external `--trusted-qualification-store`; inline self-attested
            records inside the lot bundle are NEVER accepted.
      - B2: Canonical `product_variant_id` resolution against `islet1_product_definitions_v0.8.0.json`
            plus allowlisted `IIP-0041` side-contract `ABX_L2_v2_*` donors (ZERO substring inference),
            with strict genotype compatibility against canonical product definitions.
      - B3: Enforces TRUE Clopper-Pearson `U95 <= 0.15%` on uninfected negative controls (n >= 20,000;
            20/20,000 U95 = 0.145277% PASS vs 21/20,000 U95 = 0.151167% HOLD).
      - B4: Exact <= 0.050 Bonferroni joint confidence budget across EVERY estimated parameter per
            lineage x regime estimand (Indirect E2: 0.015+0.015+0.005+0.015=0.050; Direct E2:
            0.025+0.005+0.020=0.050; Paired 24h/72h: 0.025+0.025=0.050; Estimand 1: 0.025+0.005+0.005=0.035).
      - B5: Mandatory dual-target ddPCR panel validation (HCMV UL138+UL55; CVB pos+neg 5'-del RNA),
            powered exact-Decimal Clopper-Pearson CD55 echovirus addendum, and exact lineage ledger
            reconciliation (`total_acquired_n == sum(lineage_assigned_n) + unassigned_n`) plus
            mandatory unassigned-fraction viral readout.
      - B6: Adjudicates ALL submitted adverse data across abbreviated tiers (never silently drops
            supplemental pathogen/regime/addendum findings), keeps edited-genotype non-inferiority
            active in AUTOLOGOUS_D1B_PROCESS_QUAL, and emits tier-distinct PASS codes with explicit
            tested-vs-inherited scope.
    """
    hard_stops: List[str] = []
    holds: List[str] = []

    resolved_root = openislet_root.resolve() if openislet_root is not None else _resolve_roots(None, None)[0]

    cap_frac_persist = Decimal("0.0005")         # 0.05% per-lineage viral persistence cap (proposed)
    cap_frac_kill_esc_total = Decimal("0.0001")  # 0.01% (4.0 log10) per total input at risk (proposed)
    cap_frac_kill_esc_cond = Decimal("0.001")    # 0.10% (3.0 log10) conditional per infected cell (proposed)
    alpha_3p = _alpha_3pathogen_global_floor(prec=120)  # 0.05 / 30 = floor(1/600)
    alpha_1p = Decimal("0.005")                  # 0.05 / 10 (single-pathogen / 5-lineage)
    alpha_05 = Decimal("0.05")
    # B4 exact Bonferroni allocations (every per-estimand union-bound sum <= 0.050 -> >= 95.0% joint confidence!)
    alpha_paired_veh = Decimal("0.025")          # 24h & 72h paired ratios: 0.025 + 0.025 = 0.050
    alpha_paired_surv = Decimal("0.025")
    alpha_e1_eta = Decimal("0.005")              # Estimand 1: 0.025 (veh) + 0.005 (eta) + 0.005 (esc) = 0.035 <= 0.050
    alpha_e1_esc = Decimal("0.005")
    alpha_e2_ind_veh = Decimal("0.015")          # Indirect E2: 0.015 + 0.015 + 0.005 + 0.015 = 0.050
    alpha_e2_ind_prev = Decimal("0.015")
    alpha_e2_ind_eta = Decimal("0.005")
    alpha_e2_ind_esc = Decimal("0.015")
    alpha_e2_dir_inf_veh = Decimal("0.025")      # Direct E2: 0.025 + 0.005 + 0.020 = 0.050
    alpha_e2_dir_eta = Decimal("0.005")
    alpha_e2_dir_esc = Decimal("0.020")

    min_eta_cal = Decimal("0.80")
    min_s_veh = Decimal("0.10")
    max_unassigned_frac = Decimal("0.05")
    # B3: True one-sided Clopper-Pearson U95 cap <= 0.15% at n >= 20,000 (admits <= 20/20,000 [U95=0.145277%], rejects 21/20,000 [U95=0.151167%])
    max_neg_ctrl_fpr_u95 = Decimal("0.0015")
    max_stage1_screen_frac = Decimal("0.002")
    min_neg_rna_wells = 6
    min_uninfected_ctrl_n = 20_000
    min_noninf_replicates = 6

    if not isinstance(payload, dict):
        return {
            "verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
            "release_authorizing": False,
            "gate0v_component_passed": False,
            "qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
            "physical_qualification_complete": False,
            "clustering_design_effect_deff": None,
            "submitted_clustering_design_effect_deff_unvalidated": None,
            "lot_binding": None,
            "tested_vs_inherited_scope": None,
            "hard_stops": [],
            "holds": ["HOLD_GATE0V_PAYLOAD_NOT_DICT"],
            "all_required_pathogens_and_5_lineages_calibrated": False,
            "pathogen_results": {},
            "cd46_addendum_results": {},
            "cd55_addendum_results": {},
            "stress_ap1903_regimes": {},
        }

    # ------------------------------------------------------------------
    # 0A. Shared Lot, MCB, Canonical Product Variant ID, Qualification Tier & SHA-256 Binding
    # ------------------------------------------------------------------
    lot_id = payload.get("lot_id")
    mcb_id = payload.get("mcb_id")
    pvid_raw = payload.get("product_variant_id")
    pv_legacy_raw = payload.get("product_variant")
    qual_tier = payload.get("qualification_tier")
    supplied_sha = payload.get("payload_sha256")
    computed_sha = _safe_canonical_lot_sha256(payload)
    if computed_sha is None:
        holds.append("HOLD_GATE0V_NONCANONICAL_OR_NONFINITE_PAYLOAD")

    if not _is_valid_identifier(lot_id):
        holds.append("HOLD_GATE0V_MISSING_OR_INVALID_LOT_ID")
    else:
        for ak in _LOT_ALIAS_KEYS:
            if ak in payload and ak != "lot_id" and payload.get(ak) is not None and payload.get(ak) != lot_id:
                holds.append(f"HOLD_GATE0V_CONFLICTING_LOT_ALIAS_{ak.upper()}")
    if not _is_valid_identifier(mcb_id):
        holds.append("HOLD_GATE0V_MISSING_OR_INVALID_MCB_ID")

    # B2 + R08-B1: Canonical product_variant_id resolution (no unregistered IDs, no alias-only omission, no silent alias mismatch)
    canonical_product_def: Dict[str, Any] | None = None
    canonical_pvid: str | None = None
    if not _is_clean_nonempty_str(pvid_raw):
        holds.append("HOLD_GATE0V_MISSING_CANONICAL_PRODUCT_VARIANT_ID")
    else:
        canonical_product_def = resolve_canonical_product_variant(pvid_raw, openislet_root=resolved_root)
        if canonical_product_def is None:
            holds.append("HOLD_GATE0V_UNREGISTERED_PRODUCT_VARIANT_ID")
        else:
            canonical_pvid = canonical_product_def["product_variant_id"]

    if pv_legacy_raw is not None:
        pv_leg_res = resolve_canonical_product_variant(pv_legacy_raw, openislet_root=resolved_root)
        if pv_leg_res is None:
            holds.append("HOLD_GATE0V_UNREGISTERED_PRODUCT_VARIANT_ALIAS")
        elif canonical_pvid is not None and pv_leg_res["product_variant_id"] != canonical_pvid:
            holds.append("HOLD_GATE0V_CONFLICTING_PRODUCT_VARIANT_ALIAS")

    qual_tier_valid = isinstance(qual_tier, str) and qual_tier in ALLOWED_QUALIFICATION_TIERS
    if not qual_tier_valid:
        holds.append("HOLD_GATE0V_MISSING_OR_INVALID_QUALIFICATION_TIER")
    if "operational_tier" in payload and payload.get("operational_tier") != qual_tier:
        holds.append("HOLD_GATE0V_OPERATIONAL_TIER_MISMATCH")
    if not _is_valid_sha256_hex(supplied_sha) or supplied_sha != computed_sha:
        holds.append("HOLD_GATE0V_MISSING_OR_MISMATCHED_PAYLOAD_SHA256")

    # R04-B1: Strict canonical product-family-to-qualification-tier allowlist enforcement!
    tier_allowed_for_product = True
    if canonical_product_def is not None and qual_tier_valid:
        tier_allowed_for_product, tier_family_errs = is_qualification_tier_allowed_for_product(
            canonical_product_def, qual_tier
        )
        for te in tier_family_errs:
            if te not in holds:
                holds.append(te)

    geno = payload.get("antiviral_genotype_stratum")

    # B1 / R04-B1 / R04-B2: Resolve prior bank/process approval SOLELY from independent external trusted store!
    prior_qual_auth: Dict[str, Any] = {
        "required": qual_tier != "BANK_QUALIFICATION",
        "authenticated": qual_tier == "BANK_QUALIFICATION",
        "resolution_source": "direct_bank_qualification_current_lot" if qual_tier == "BANK_QUALIFICATION" else None,
    }
    if qual_tier == "LOT_RELEASE_SURROGATE":
        pq_ok, pq_errs, pq_meta = resolve_and_verify_trusted_bank_qualification(
            trusted_qualification_store,
            expected_sha256=payload.get("bridged_mcb_qualification_sha256"),
            expected_mcb_id=mcb_id,
            expected_product_variant_id=canonical_pvid,
            expected_genotype_stratum=geno,
            inline_record_if_supplied=payload.get("bridged_mcb_qualification_record"),
            openislet_root=resolved_root,
            hold_prefix="HOLD_GATE0V_PRIOR_BANK_QUAL",
            _revalidating_archived_bank=_revalidating_archived_bank,
        )
        prior_qual_auth = {"required": True, **pq_meta}
        for pe in pq_errs:
            if pe not in holds:
                holds.append(pe)
        if prior_qual_auth.get("archived_bank_payload_verified") is not True:
            if "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD" not in holds:
                holds.append("HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD")
            if "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE" not in holds:
                holds.append("HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE")
    elif qual_tier == "AUTOLOGOUS_D1B_PROCESS_QUAL":
        pq_ok, pq_errs, pq_meta = resolve_and_verify_trusted_process_qualification(
            trusted_qualification_store,
            expected_sha256=payload.get("process_qualification_ref_sha256"),
            expected_product_variant_id=canonical_pvid,
            inline_record_if_supplied=payload.get("process_qualification_record"),
            openislet_root=resolved_root,
            hold_prefix="HOLD_GATE0V_AUTOLOGOUS_PROC_QUAL",
        )
        prior_qual_auth = {"required": True, **pq_meta}
        for pe in pq_errs:
            if pe not in holds:
                holds.append(pe)
        if not _is_valid_sha256_hex(payload.get("adventitious_agent_panel_evidence_sha256")):
            holds.append("HOLD_GATE0V_AUTOLOGOUS_D1B_MISSING_ADVENTITIOUS_AGENT_PANEL_SHA256")

    # R11-B1 + R13-B3: Strictly validate `require_trusted_nw08_ocr_record` (must be `bool` if present),
    # reject `require_trusted_nw08_ocr_record = True` on `BANK_QUALIFICATION` at direct admission
    # (`HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION`), and fail closed with
    # `HOLD_NW08_REQUIRED_OCR_RECORD_MISSING` on uncoupled standalone clinical Gate-0V runs whenever
    # required OCR is not adjudicated externally by the coupled composite wrapper!
    req_trusted_ocr_flag = False
    if "require_trusted_nw08_ocr_record" in payload:
        rt_ocr_raw = payload.get("require_trusted_nw08_ocr_record")
        if not _is_strict_bool(rt_ocr_raw):
            holds.append("HOLD_NW08_COUPLED_INVALID_REQUIRE_TRUSTED_OCR_FLAG")
        else:
            req_trusted_ocr_flag = bool(rt_ocr_raw)
    if prior_qual_auth.get("record_require_trusted_nw08_ocr_record") is True:
        req_trusted_ocr_flag = True
    if req_trusted_ocr_flag and qual_tier == "BANK_QUALIFICATION":
        if "HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION" not in holds:
            holds.append("HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION")
    elif req_trusted_ocr_flag and not _nw08_ocr_adjudicated_externally:
        if "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING" not in holds:
            holds.append("HOLD_NW08_REQUIRED_OCR_RECORD_MISSING")

    lot_binding = {
        "lot_id": lot_id if isinstance(lot_id, str) else None,
        "mcb_id": mcb_id if isinstance(mcb_id, str) else None,
        "supplied_product_variant_id": pvid_raw if isinstance(pvid_raw, str) else None,
        "canonical_product_variant_id": canonical_pvid,
        "canonical_product_tier_family": (
            canonical_product_def.get("product_tier_family") if canonical_product_def is not None else None
        ),
        "allowed_qualification_tiers_for_product": (
            canonical_product_def.get("allowed_qualification_tiers") if canonical_product_def is not None else None
        ),
        "qualification_tier_allowed_for_product_family": (
            bool(tier_allowed_for_product) if (canonical_product_def is not None and qual_tier_valid) else False
        ),
        "canonical_product_registry_source": (
            canonical_product_def.get("registry_source") if canonical_product_def is not None else None
        ),
        "canonical_product_execution_supported": (
            canonical_product_def.get("execution_supported") if canonical_product_def is not None else None
        ),
        "qualification_tier": qual_tier if isinstance(qual_tier, str) else None,
        "supplied_payload_sha256": supplied_sha if isinstance(supplied_sha, str) else None,
        "computed_payload_sha256": computed_sha,
        "payload_sha256_verified": bool(_is_valid_sha256_hex(supplied_sha) and supplied_sha == computed_sha),
        "require_trusted_nw08_ocr_record": req_trusted_ocr_flag,
        "prior_qualification_authentication": prior_qual_auth,
    }

    # ------------------------------------------------------------------
    # 0B. Clustering, Independence & Per-Estimand Sampling-Unit Specification (R11-B3 + R12-B1 + R13-B1/M2)
    # ------------------------------------------------------------------
    clust = payload.get("clustering_and_independence_spec")
    deff: Decimal | None = None
    raw_deff_val: Decimal | None = None
    submitted_deff_unvalidated_safe: str | None = None
    indep_units: int | None = None
    indep_units_valid = False
    sampling_unit_class: str | None = None
    sampling_unit_class_valid = False
    unit_def: Any = None
    unit_def_valid = False
    sampling_spec_valid = False

    if not isinstance(clust, dict):
        holds.append("HOLD_GATE0V_MISSING_CLUSTERING_AND_INDEPENDENCE_SPEC")
    else:
        raw_units = clust.get("independent_biological_units_n")
        deff_raw = clust.get("clustering_design_effect_deff")
        if deff_raw is not None:
            if isinstance(deff_raw, Decimal) and deff_raw.is_finite():
                submitted_deff_unvalidated_safe = format(deff_raw, "f")
            elif isinstance(deff_raw, bool):
                submitted_deff_unvalidated_safe = str(deff_raw)
            elif isinstance(deff_raw, (int, float)) and math.isfinite(deff_raw):
                submitted_deff_unvalidated_safe = str(deff_raw)
            elif isinstance(deff_raw, str):
                submitted_deff_unvalidated_safe = deff_raw
            else:
                submitted_deff_unvalidated_safe = repr(deff_raw)
        deff_val = _to_exact_decimal_nonneg(deff_raw)
        raw_deff_val = deff_val
        unit_def = clust.get("unit_definition")
        raw_unit_class = clust.get("independent_sampling_unit_class")

        if _is_strict_int(raw_units) and raw_units >= MIN_INDEPENDENT_BIOLOGICAL_UNITS_N:
            indep_units = int(raw_units)
            indep_units_valid = True
        else:
            if _is_strict_int(raw_units):
                indep_units = int(raw_units)
            holds.append("HOLD_INSUFFICIENT_INDEPENDENT_BIOLOGICAL_UNITS")

        if isinstance(raw_unit_class, str) and raw_unit_class in ALLOWED_INDEPENDENT_SAMPLING_UNIT_CLASSES:
            sampling_unit_class = raw_unit_class
            sampling_unit_class_valid = True
        else:
            holds.append("HOLD_GATE0V_INVALID_OR_MISSING_INDEPENDENT_SAMPLING_UNIT_CLASS")

        if _is_valid_identifier(unit_def):
            unit_def_valid = True
        else:
            holds.append("HOLD_GATE0V_MISSING_INDEPENDENCE_UNIT_DEFINITION")

        deff_valid = bool(deff_val is not None and Decimal("1.0") <= deff_val <= Decimal("1000"))
        if not deff_valid:
            deff = None
            if _is_negative_zero(deff_raw) and "INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE" not in holds:
                holds.append("INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE")
            holds.append("HOLD_GATE0V_INVALID_CLUSTERING_DESIGN_EFFECT_DEFF")
        else:
            deff = deff_val
            if deff > Decimal("1.0") and "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE" not in holds:
                holds.append("HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE")

        sampling_spec_valid = bool(deff_valid and indep_units_valid and sampling_unit_class_valid and unit_def_valid)
        if not sampling_spec_valid:
            # R12-B1 + R13-M2: NEVER retain any unvalidated numeric `deff` (neither 1.0 nor 2.0!)
            # when `clustering_and_independence_spec` fails validation!
            deff = None

    sampling_tracker: Dict[str, Any] = {
        "max_binomial_denominator_n": 0,
        "partitions_checked": 0,
        "partitions_reconciled": 0,
        "all_partitions_reconciled": True,
    }

    # R13-B1: Dedicated pre-schema adverse `per_unit_counts` scanner runs UNCONDITIONALLY across
    # EVERY arm (required AND supplemental stress regimes, pathogens, CD46/CD55 addenda, extra keys)
    # in BOTH single-cell AND multi-well modes (and even when `clustering_and_independence_spec` is
    # missing/invalid!) BEFORE any schema, class, or row-ID gating!
    _req_kill_regimes_pre: Tuple[str, ...] = (
        STRESS_AP1903_REGIMES
        if qual_tier == "BANK_QUALIFICATION"
        else ("normoxia_baseline", "hypoxia_1pct_plus_cytokines")
    )
    _puc_prescan = _scan_all_submitted_per_unit_counts_adverse(
        payload,
        raw_deff_dec=raw_deff_val,
        hard_stops=hard_stops,
        required_kill_regimes=_req_kill_regimes_pre,
    )
    if (
        sampling_unit_class == "INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT"
        and _puc_prescan["any_per_unit_counts_present"]
    ):
        sampling_tracker["all_partitions_reconciled"] = False
        if "HOLD_UNEXPECTED_PER_UNIT_COUNTS_IN_SINGLE_CELL_MODE" not in holds:
            holds.append("HOLD_UNEXPECTED_PER_UNIT_COUNTS_IN_SINGLE_CELL_MODE")

    def _check_estimand_sampling_unit_basis(
        raw_partition: Any,
        *,
        k_val: Any,
        n_val: Any,
        label: str,
        zero_tolerance_hard_stop_token: str | None = None,
        out_unit_maps: Dict[str, Dict[str, Tuple[int, int]]] | None = None,
    ) -> bool:
        if _is_strict_int(n_val) and n_val >= 1:
            if n_val > sampling_tracker["max_binomial_denominator_n"]:
                sampling_tracker["max_binomial_denominator_n"] = int(n_val)
        if sampling_unit_class == "RECONCILED_MULTI_WELL_CELL_ASSAY_WITH_UNIT_PARTITION":
            sampling_tracker["partitions_checked"] += 1
            p_info = _inspect_per_unit_counts(
                raw_partition,
                expected_units_n=indep_units,
                expected_k=k_val if _is_strict_int(k_val) else None,
                expected_n=n_val if _is_strict_int(n_val) else None,
            )
            if zero_tolerance_hard_stop_token is not None and p_info["any_pos_k"]:
                if "HARD_STOP_ADVERSE_PER_UNIT_VIRAL_PERSISTENCE" not in hard_stops:
                    hard_stops.append("HARD_STOP_ADVERSE_PER_UNIT_VIRAL_PERSISTENCE")
                if zero_tolerance_hard_stop_token not in hard_stops:
                    hard_stops.append(zero_tolerance_hard_stop_token)
            if p_info["reconciled_ok"]:
                if out_unit_maps is not None:
                    out_unit_maps[label] = p_info["unit_map"]
                sampling_tracker["partitions_reconciled"] += 1
                return True
            sampling_tracker["all_partitions_reconciled"] = False
            if "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS" not in holds:
                holds.append("HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS")
            tok = f"HOLD_GATE0V_SAMPLING_UNIT_PARTITION_MISMATCH_{label}_{p_info['reason_code']}"
            if tok not in holds:
                holds.append(tok)
            return False
        if sampling_unit_class == "INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT":
            if raw_partition is not None:
                sampling_tracker["all_partitions_reconciled"] = False
                if "HOLD_UNEXPECTED_PER_UNIT_COUNTS_IN_SINGLE_CELL_MODE" not in holds:
                    holds.append("HOLD_UNEXPECTED_PER_UNIT_COUNTS_IN_SINGLE_CELL_MODE")
                return False
            if not (_is_strict_int(k_val) and _is_strict_int(n_val) and n_val >= 1 and 0 <= k_val <= n_val):
                sampling_tracker["all_partitions_reconciled"] = False
                if "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS" not in holds:
                    holds.append("HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS")
                return False
            if not (indep_units_valid and indep_units is not None and indep_units >= n_val):
                sampling_tracker["all_partitions_reconciled"] = False
                if "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS" not in holds:
                    holds.append("HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS")
                return False
            return True
        # Missing/invalid unit class: still scan submitted partition for hidden positive viral events
        if raw_partition is not None and zero_tolerance_hard_stop_token is not None:
            p_info = _inspect_per_unit_counts(
                raw_partition,
                expected_units_n=indep_units,
                expected_k=k_val if _is_strict_int(k_val) else None,
                expected_n=n_val if _is_strict_int(n_val) else None,
            )
            if p_info["any_pos_k"]:
                if "HARD_STOP_ADVERSE_PER_UNIT_VIRAL_PERSISTENCE" not in hard_stops:
                    hard_stops.append("HARD_STOP_ADVERSE_PER_UNIT_VIRAL_PERSISTENCE")
                if zero_tolerance_hard_stop_token not in hard_stops:
                    hard_stops.append(zero_tolerance_hard_stop_token)
        sampling_tracker["all_partitions_reconciled"] = False
        return False

    # ------------------------------------------------------------------
    # 0C. Strict CXADR KO Boolean + Genotyping SHA-256 Digest
    # ------------------------------------------------------------------
    if "cxadr_ko_present" not in payload or not _is_strict_bool(payload.get("cxadr_ko_present")):
        holds.append("HOLD_GATE0V_MISSING_OR_NONBOOL_CXADR_KO_FLAG")
    elif payload["cxadr_ko_present"] is True:
        hard_stops.append("FAIL_HARD_STOP_SPECULATIVE_CXADR_KO_BARRED_FROM_ACTIVE_GATE0V")
    if not _is_valid_sha256_hex(payload.get("cxadr_locus_genotyping_evidence_sha256")):
        holds.append("HOLD_GATE0V_MISSING_CXADR_GENOTYPING_EVIDENCE_SHA256")

    # ------------------------------------------------------------------
    # 1. Genotype & Antiviral Competence (Gate 0V-Geno) reconciled with Canonical Product
    # ------------------------------------------------------------------
    geno_valid = isinstance(geno, str) and geno in ALLOWED_ANTIVIRAL_GENOTYPES
    if not geno_valid:
        holds.append("HOLD_GATE0V_UNRECOGNIZED_OR_MISSING_ANTIVIRAL_GENOTYPE_STRATUM")
    elif canonical_product_def is not None:
        tyk2_cls = canonical_product_def.get("tyk2_product_genotype_class")
        if tyk2_cls == "TYK2_PE_P1104A" and geno not in ("TYK2_P1104A_HOM__IFIH1_WT", "TYK2_P1104A_HET__IFIH1_WT"):
            holds.append("HOLD_GATE0V_GENOTYPE_CONFLICTS_WITH_CANONICAL_PRODUCT_DEFINITION")
        elif tyk2_cls == "TYK2_KO_PROPOSED":
            holds.append("HOLD_GATE0V_TYK2_KO_VARIANT_NOT_QUALIFIED_BY_WT_OR_P1104A_STRATUM")

    if geno == "TYK2_P1104A_HOM__IFIH1_WT":
        if payload.get("mycobacterial_tb_igra_screening_attested") is not True:
            holds.append("HOLD_GATE0V_TYK2_P1104A_HOM_REQUIRES_TB_MYCOBACTERIAL_SCREENING")
        if not _is_valid_sha256_hex(payload.get("tb_igra_evidence_sha256")):
            holds.append("HOLD_GATE0V_TYK2_P1104A_HOM_MISSING_TB_IGRA_EVIDENCE_SHA256")

    # ------------------------------------------------------------------
    # 1B. Ectopic Viral Receptor Declaration & Mandatory Powered Strain-Specific Addenda (B2 + B5 + B6)
    # ------------------------------------------------------------------
    ectopic_raw = payload.get("ectopic_viral_receptors_expressed")
    cd46_results: Dict[str, Any] = {}
    cd55_results: Dict[str, Any] = {}
    supplemental_adjudicated: List[str] = []

    if not isinstance(ectopic_raw, list) or any(
        not isinstance(r, str) or r not in ALLOWED_ECTOPIC_RECEPTORS for r in ectopic_raw
    ):
        holds.append("HOLD_GATE0V_MISSING_OR_INVALID_ECTOPIC_VIRAL_RECEPTORS_LIST")
        ectopic_set: set[str] = set()
    else:
        ectopic_set = set(ectopic_raw)

    # B2: Exact canonical registry lookup (ZERO substring inference!)
    implied_receptors = (
        set(canonical_product_def.get("required_ectopic_viral_receptors") or [])
        if canonical_product_def is not None
        else set()
    )
    for req_rec in sorted(implied_receptors):
        if req_rec not in ectopic_set:
            holds.append(f"HOLD_GATE0V_UNDECLARED_ECTOPIC_RECEPTOR_{req_rec}_FOR_PRODUCT_VARIANT")
    effective_ectopic = ectopic_set | implied_receptors

    cd46_add = payload.get("cd46_tropic_viral_addendum")
    if "CD46_WT" in effective_ectopic:
        if not isinstance(cd46_add, dict):
            holds.append("HOLD_GATE0V_CD46_WT_ARM_REQUIRES_COMPLETED_CD46_VIRAL_ADDENDUM")
        else:
            if cd46_add.get("hhv6b_cd134_scope_distinguished") is not True:
                holds.append("HOLD_GATE0V_CD46_ADDENDUM_MISSING_HHV6A_VS_HHV6B_RECEPTOR_SCOPE")
            if cd46_add.get("measles_wt_slam_nectin4_scope_distinguished") is not True:
                holds.append("HOLD_GATE0V_CD46_ADDENDUM_MISSING_MEASLES_STRAIN_RECEPTOR_SCOPE")
            for v_id in CD46_ADDENDUM_VIRUSES:
                v_tag = v_id.upper()
                vb = cd46_add.get(v_id)
                if not isinstance(vb, dict):
                    holds.append(f"HOLD_GATE0V_CD46_ADDENDUM_MISSING_{v_tag}")
                    continue
                t72 = _to_exact_decimal_nonneg(vb.get("titer_72h_log10_pfu_u95"))
                d14 = _to_exact_decimal(vb.get("day14_log10_reduction_l95"))
                d28_pfu = _to_exact_decimal_nonneg(vb.get("day28_supernatant_pfu_ml"))
                d28_vol = _to_exact_decimal_nonneg(vb.get("day28_assay_volume_ml"))
                d28_lod = _to_exact_decimal_nonneg(vb.get("day28_lod_pfu_ml"))
                dd_k = vb.get("day28_5lineage_ddpcr_confirmed_k")
                dd_n = vb.get("day28_5lineage_cells_screened_per_lineage_min_n")
                ev_sha = vb.get("protocol_evidence_sha256")
                v_ok = True
                if t72 is None or not (Decimal(0) <= t72 <= Decimal("15")):
                    holds.append(f"HOLD_GATE0V_CD46_INVALID_72H_TITER_{v_tag}")
                    v_ok = False
                elif t72 > Decimal("2.0"):
                    hard_stops.append(f"FAIL_HARD_STOP_CD46_ADDENDUM_72H_TITER_{v_tag}")
                    v_ok = False
                if d14 is None or not (Decimal("-10") <= d14 <= Decimal("15")):
                    holds.append(f"HOLD_GATE0V_CD46_INVALID_DAY14_CLEARANCE_{v_tag}")
                    v_ok = False
                elif d14 < Decimal("3.0"):
                    hard_stops.append(f"FAIL_HARD_STOP_CD46_ADDENDUM_DAY14_CLEARANCE_{v_tag}")
                    v_ok = False
                if d28_pfu is None or d28_pfu < Decimal(0) or d28_vol is None or d28_vol < Decimal("1.0") or d28_lod is None or d28_lod <= Decimal(0) or d28_lod > Decimal("1.0"):
                    holds.append(f"HOLD_GATE0V_CD46_INVALID_DAY28_PLAQUE_OR_LOD_{v_tag}")
                    v_ok = False
                elif d28_pfu > Decimal(0):
                    hard_stops.append(f"FAIL_HARD_STOP_CD46_ADDENDUM_DAY28_SHEDDING_{v_tag}")
                    v_ok = False
                u_cd46_str: str | None = None
                if not (_is_strict_int(dd_k) and _is_strict_int(dd_n) and dd_n >= 1 and 0 <= dd_k <= dd_n):
                    holds.append(f"HOLD_GATE0V_CD46_INVALID_DDPCR_COUNTS_{v_tag}")
                    v_ok = False
                else:
                    if dd_k >= 1:
                        hard_stops.append(f"FAIL_HARD_STOP_CD46_ADDENDUM_CONFIRMED_PERSISTENCE_{v_tag}")
                        v_ok = False
                    if not _check_estimand_sampling_unit_basis(
                        vb.get("per_unit_counts"),
                        k_val=dd_k,
                        n_val=dd_n,
                        label=f"CD46_{v_tag}",
                        zero_tolerance_hard_stop_token=f"FAIL_HARD_STOP_CD46_ADDENDUM_CONFIRMED_PERSISTENCE_{v_tag}",
                    ):
                        v_ok = False
                    if deff is None:
                        v_ok = False
                    else:
                        dd_n_indep = _exact_floor_div_by_decimal(dd_n, deff)
                        if dd_n_indep < 1:
                            holds.append(f"HOLD_GATE0V_CD46_UNDERPOWERED_DDPCR_{v_tag}")
                            v_ok = False
                        elif dd_k == 0:
                            u_cd46 = sound_zero_event_clopper_pearson_upper(dd_n_indep, alpha_3p, min_eta_cal, prec=80)["u_thinned_upper_dec"]
                            u_cd46_str = format(u_cd46, "f")[:24]
                            if u_cd46 > cap_frac_persist:
                                holds.append(f"HOLD_GATE0V_CD46_UNDERPOWERED_DDPCR_{v_tag}")
                                v_ok = False
                if not _is_valid_sha256_hex(ev_sha):
                    holds.append(f"HOLD_GATE0V_CD46_MISSING_EVIDENCE_SHA256_{v_tag}")
                    v_ok = False
                cd46_results[v_id] = {"passed": v_ok, "u_cd46_upper_80d": u_cd46_str}
    elif isinstance(cd46_add, dict):
        # B6: Never silently drop submitted adverse CD46 addendum data even on non-CD46 arms!
        supplemental_adjudicated.append("supplemental_addendum:cd46_tropic_viral_addendum")
        for v_id in CD46_ADDENDUM_VIRUSES:
            vb = cd46_add.get(v_id)
            if not isinstance(vb, dict):
                continue
            v_tag = v_id.upper()
            t72 = _to_exact_decimal(vb.get("titer_72h_log10_pfu_u95"))
            d14 = _to_exact_decimal(vb.get("day14_log10_reduction_l95"))
            d28_pfu = _to_exact_decimal(vb.get("day28_supernatant_pfu_ml"))
            dd_k = vb.get("day28_5lineage_ddpcr_confirmed_k")
            if t72 is not None and t72 > Decimal("2.0"):
                hard_stops.append(f"FAIL_HARD_STOP_SUPPLEMENTAL_CD46_ADDENDUM_72H_TITER_{v_tag}")
            if d14 is not None and d14 < Decimal("3.0"):
                hard_stops.append(f"FAIL_HARD_STOP_SUPPLEMENTAL_CD46_ADDENDUM_DAY14_CLEARANCE_{v_tag}")
            if d28_pfu is not None and d28_pfu > Decimal(0):
                hard_stops.append(f"FAIL_HARD_STOP_SUPPLEMENTAL_CD46_ADDENDUM_DAY28_SHEDDING_{v_tag}")
            if _is_strict_int(dd_k) and dd_k >= 1:
                hard_stops.append(f"FAIL_HARD_STOP_SUPPLEMENTAL_CD46_ADDENDUM_CONFIRMED_PERSISTENCE_{v_tag}")

    cd55_add = payload.get("cd55_tropic_echovirus_addendum")
    if "CD55_FULL_LENGTH" in effective_ectopic:
        # R04-B4: Require SEPARATE per-strain (echovirus_7 AND echovirus_11) attributable evidence
        # blocks with per-strain acute/Day-14/Day-28 clearance AND per-strain x 5-lineage raw
        # persistence counts (confirmed_k == 0, cells_screened_n) each individually clearing exact-Decimal
        # Clopper-Pearson U <= 5e-4! Reject any legacy aggregate-only block or missing strain/lineage!
        if not isinstance(cd55_add, dict):
            holds.append("HOLD_GATE0V_CD55_FULL_LENGTH_REQUIRES_COMPLETED_ECHOVIRUS_ADDENDUM")
            cd55_results = {
                "passed": False,
                "detection_efficiency_assurance_level": "CONDITIONAL_ON_ASSUMED_MINIMUM_ETA_PENDING_LINKED_CALIBRANT_EVIDENCE",
                "assumed_minimum_eta_used": str(min_eta_cal),
                "strain_results": {},
            }
        else:
            c55_ok = True
            strains_raw = cd55_add.get("echovirus_strain_panel")
            if not isinstance(strains_raw, list) or not set(CD55_REQUIRED_ECHOVIRUS_STRAINS).issubset(
                {str(s).strip().lower() for s in strains_raw if isinstance(s, str)}
            ):
                holds.append("HOLD_GATE0V_CD55_MISSING_REQUIRED_ECHOVIRUS_STRAIN_PANEL")
                c55_ok = False
            if not _is_valid_sha256_hex(cd55_add.get("protocol_evidence_sha256")):
                holds.append("HOLD_GATE0V_CD55_MISSING_PROTOCOL_EVIDENCE_SHA256")
                c55_ok = False

            # Always inspect any submitted top-level legacy keys so adverse data or underpowered
            # overrides are never silently ignored even if present alongside strain_results!
            leg_t72 = _to_exact_decimal(cd55_add.get("echovirus_titer_72h_log10_pfu_u95"))
            leg_d14 = _to_exact_decimal(cd55_add.get("echovirus_day14_log10_reduction_l95"))
            leg_d28 = _to_exact_decimal(cd55_add.get("echovirus_day28_supernatant_pfu_ml"))
            leg_k = cd55_add.get("echovirus_persistence_confirmed_k")
            leg_n = cd55_add.get("echovirus_cells_screened_per_lineage_min_n")
            if leg_t72 is not None and leg_t72 > Decimal("2.0"):
                hard_stops.append("FAIL_HARD_STOP_CD55_ADDENDUM_72H_TITER")
                c55_ok = False
            if leg_d14 is not None and leg_d14 < Decimal("3.0"):
                hard_stops.append("FAIL_HARD_STOP_CD55_ADDENDUM_DAY14_CLEARANCE")
                c55_ok = False
            if leg_d28 is not None and leg_d28 > Decimal(0):
                hard_stops.append("FAIL_HARD_STOP_CD55_ADDENDUM_DAY28_SHEDDING")
                c55_ok = False
            if _is_strict_int(leg_k) and leg_k >= 1:
                hard_stops.append("FAIL_HARD_STOP_CD55_ECHOVIRUS_PERSISTENCE_DETECTED")
                c55_ok = False
            if leg_n is not None:
                if not (_is_strict_int(leg_n) and leg_n >= 1):
                    holds.append("HOLD_GATE0V_CD55_UNDERPOWERED_ECHOVIRUS_DENOMINATOR")
                    c55_ok = False
                elif deff is None:
                    c55_ok = False
                else:
                    leg_n_indep = _exact_floor_div_by_decimal(leg_n, deff)
                    if leg_n_indep < 1:
                        holds.append("HOLD_GATE0V_CD55_UNDERPOWERED_ECHOVIRUS_DENOMINATOR")
                        c55_ok = False
                    else:
                        u_leg = sound_zero_event_clopper_pearson_upper(
                            leg_n_indep, alpha_3p, min_eta_cal, prec=80
                        )["u_thinned_upper_dec"]
                        if u_leg > cap_frac_persist:
                            holds.append("HOLD_GATE0V_CD55_UNDERPOWERED_ECHOVIRUS_DENOMINATOR")
                            c55_ok = False

            strain_results_raw = cd55_add.get("strain_results")
            per_strain_out: Dict[str, Any] = {}
            overall_min_n: int | None = None
            overall_max_u: Decimal | None = None
            if not isinstance(strain_results_raw, dict):
                holds.append("HOLD_GATE0V_CD55_MISSING_PER_STRAIN_RESULTS_AGGREGATE_ONLY_REJECTED")
                c55_ok = False
            else:
                for strain_id in CD55_REQUIRED_ECHOVIRUS_STRAINS:
                    s_tag = strain_id.upper()
                    sb = strain_results_raw.get(strain_id)
                    if not isinstance(sb, dict):
                        holds.append(f"HOLD_GATE0V_CD55_MISSING_STRAIN_BLOCK_{s_tag}")
                        c55_ok = False
                        per_strain_out[strain_id] = {"passed": False, "lineage_results": {}}
                        continue
                    s_ok = True
                    if not _is_valid_sha256_hex(sb.get("protocol_evidence_sha256")):
                        holds.append(f"HOLD_GATE0V_CD55_MISSING_STRAIN_EVIDENCE_SHA256_{s_tag}")
                        s_ok = False
                    t72_s = _to_exact_decimal(sb.get("titer_72h_log10_pfu_u95"))
                    d14_s = _to_exact_decimal(sb.get("day14_log10_reduction_l95"))
                    d28_pfu_s = _to_exact_decimal(sb.get("day28_supernatant_pfu_ml"))
                    d28_vol_s = _to_exact_decimal(sb.get("day28_assay_volume_ml"))
                    d28_lod_s = _to_exact_decimal(sb.get("day28_lod_pfu_ml"))

                    if t72_s is None or not (Decimal(0) <= t72_s <= Decimal("15")):
                        holds.append(f"HOLD_GATE0V_CD55_INVALID_72H_TITER_{s_tag}")
                        s_ok = False
                    elif t72_s > Decimal("2.0"):
                        hard_stops.append(f"FAIL_HARD_STOP_CD55_ADDENDUM_72H_TITER_{s_tag}")
                        s_ok = False
                    if d14_s is None or not (Decimal("-10") <= d14_s <= Decimal("15")):
                        holds.append(f"HOLD_GATE0V_CD55_INVALID_DAY14_CLEARANCE_{s_tag}")
                        s_ok = False
                    elif d14_s < Decimal("3.0"):
                        hard_stops.append(f"FAIL_HARD_STOP_CD55_ADDENDUM_DAY14_CLEARANCE_{s_tag}")
                        s_ok = False
                    if (
                        d28_pfu_s is None or d28_pfu_s < Decimal(0)
                        or d28_vol_s is None or d28_vol_s < Decimal("1.0")
                        or d28_lod_s is None or d28_lod_s <= Decimal(0) or d28_lod_s > Decimal("1.0")
                    ):
                        holds.append(f"HOLD_GATE0V_CD55_INVALID_DAY28_PLAQUE_OR_LOD_{s_tag}")
                        s_ok = False
                    elif d28_pfu_s > Decimal(0):
                        hard_stops.append(f"FAIL_HARD_STOP_CD55_ADDENDUM_DAY28_SHEDDING_{s_tag}")
                        s_ok = False

                    lin_map = sb.get("day28_persistence_by_lineage")
                    lin_out: Dict[str, Any] = {}
                    strain_min_n: int | None = None
                    strain_max_u: Decimal | None = None
                    if not isinstance(lin_map, dict):
                        holds.append(f"HOLD_GATE0V_CD55_MISSING_5LINEAGE_PERSISTENCE_{s_tag}")
                        s_ok = False
                    else:
                        for lin in GRAFT_LINEAGES:
                            l_tag = lin.upper()
                            l_entry = lin_map.get(lin)
                            if not isinstance(l_entry, dict):
                                holds.append(f"HOLD_GATE0V_CD55_MISSING_LINEAGE_{s_tag}_{l_tag}")
                                s_ok = False
                                lin_out[lin] = {"passed": False}
                                continue
                            lk = l_entry.get("confirmed_k")
                            ln = l_entry.get("cells_screened_n")
                            l_ok = True
                            l_n_indep: int | None = None
                            u_l_str: str | None = None
                            if not (_is_strict_int(lk) and _is_strict_int(ln) and ln >= 1 and 0 <= lk <= ln):
                                holds.append(f"HOLD_GATE0V_CD55_INVALID_LINEAGE_COUNTS_{s_tag}_{l_tag}")
                                l_ok = False
                            else:
                                if lk >= 1:
                                    hard_stops.append(
                                        f"FAIL_HARD_STOP_CD55_ECHOVIRUS_PERSISTENCE_DETECTED_{s_tag}_{l_tag}_K_{lk}"
                                    )
                                    l_ok = False
                                if not _check_estimand_sampling_unit_basis(
                                    l_entry.get("per_unit_counts"),
                                    k_val=lk,
                                    n_val=ln,
                                    label=f"CD55_{s_tag}_{l_tag}",
                                    zero_tolerance_hard_stop_token=f"FAIL_HARD_STOP_CD55_ECHOVIRUS_PERSISTENCE_DETECTED_{s_tag}_{l_tag}_K_UNIT_POS",
                                ):
                                    l_ok = False
                                if strain_min_n is None or ln < strain_min_n:
                                    strain_min_n = ln
                                if overall_min_n is None or ln < overall_min_n:
                                    overall_min_n = ln
                                if deff is None:
                                    l_ok = False
                                else:
                                    l_n_indep = _exact_floor_div_by_decimal(ln, deff)
                                    if l_n_indep < 1:
                                        holds.append(f"HOLD_GATE0V_CD55_UNDERPOWERED_ECHOVIRUS_DENOMINATOR_{s_tag}_{l_tag}")
                                        l_ok = False
                                    elif lk == 0:
                                        u_l = sound_zero_event_clopper_pearson_upper(
                                            l_n_indep, alpha_3p, min_eta_cal, prec=80
                                        )["u_thinned_upper_dec"]
                                        u_l_str = format(u_l, "f")[:24]
                                        if strain_max_u is None or u_l > strain_max_u:
                                            strain_max_u = u_l
                                        if overall_max_u is None or u_l > overall_max_u:
                                            overall_max_u = u_l
                                        if u_l > cap_frac_persist:
                                            holds.append(f"HOLD_GATE0V_CD55_UNDERPOWERED_ECHOVIRUS_DENOMINATOR_{s_tag}_{l_tag}")
                                            l_ok = False
                            if not l_ok:
                                s_ok = False
                            lin_out[lin] = {
                                "confirmed_k": lk if _is_strict_int(lk) else None,
                                "cells_screened_n": ln if _is_strict_int(ln) else None,
                                "effective_independent_n": l_n_indep,
                                "u_cd55_upper_80d": u_l_str,
                                "passed": l_ok,
                            }
                        # R04-B3 consistency: reject any extra non-canonical lineage keys inside CD55 strain block!
                        for extra_lin, extra_entry in lin_map.items():
                            if extra_lin not in GRAFT_LINEAGES:
                                el_tag = str(extra_lin).upper()
                                holds.append(f"HOLD_UNRECOGNIZED_LINEAGE_KEY_GATE0V_CD55_{s_tag}_{el_tag}")
                                s_ok = False
                                if isinstance(extra_entry, dict):
                                    ek = extra_entry.get("confirmed_k")
                                    if _is_strict_int(ek) and ek >= 1:
                                        hard_stops.append(
                                            f"FAIL_HARD_STOP_CD55_ECHOVIRUS_PERSISTENCE_DETECTED_{s_tag}_{el_tag}_K_{ek}"
                                        )
                    if not s_ok:
                        c55_ok = False
                    per_strain_out[strain_id] = {
                        "passed": s_ok,
                        "detection_efficiency_assurance_level": "CONDITIONAL_ON_ASSUMED_MINIMUM_ETA_PENDING_LINKED_CALIBRANT_EVIDENCE",
                        "assumed_minimum_eta_used": str(min_eta_cal),
                        "min_cells_screened_n": strain_min_n,
                        "max_u_cd55_upper_80d": format(strain_max_u, "f")[:24] if strain_max_u is not None else None,
                        "lineage_results": lin_out,
                    }

                # Adjudicate any extra submitted echovirus strains so adverse data is never silently dropped
                for extra_sid, extra_sb in strain_results_raw.items():
                    if extra_sid not in CD55_REQUIRED_ECHOVIRUS_STRAINS and isinstance(extra_sb, dict):
                        es_tag = str(extra_sid).upper()
                        et72 = _to_exact_decimal(extra_sb.get("titer_72h_log10_pfu_u95"))
                        ed14 = _to_exact_decimal(extra_sb.get("day14_log10_reduction_l95"))
                        ed28 = _to_exact_decimal(extra_sb.get("day28_supernatant_pfu_ml"))
                        if et72 is not None and et72 > Decimal("2.0"):
                            hard_stops.append(f"FAIL_HARD_STOP_CD55_ADDENDUM_72H_TITER_{es_tag}")
                            c55_ok = False
                        if ed14 is not None and ed14 < Decimal("3.0"):
                            hard_stops.append(f"FAIL_HARD_STOP_CD55_ADDENDUM_DAY14_CLEARANCE_{es_tag}")
                            c55_ok = False
                        if ed28 is not None and ed28 > Decimal(0):
                            hard_stops.append(f"FAIL_HARD_STOP_CD55_ADDENDUM_DAY28_SHEDDING_{es_tag}")
                            c55_ok = False
                        elin_map = extra_sb.get("day28_persistence_by_lineage")
                        if isinstance(elin_map, dict):
                            for elin, eent in elin_map.items():
                                if isinstance(eent, dict) and _is_strict_int(eent.get("confirmed_k")) and eent["confirmed_k"] >= 1:
                                    hard_stops.append(
                                        f"FAIL_HARD_STOP_CD55_ECHOVIRUS_PERSISTENCE_DETECTED_{es_tag}_{str(elin).upper()}_K_{eent['confirmed_k']}"
                                    )
                                    c55_ok = False

            cd55_results = {
                "passed": c55_ok,
                "required_strains": list(CD55_REQUIRED_ECHOVIRUS_STRAINS),
                "all_strains_and_5_lineages_attributable_and_powered": c55_ok,
                "detection_efficiency_assurance_level": "CONDITIONAL_ON_ASSUMED_MINIMUM_ETA_PENDING_LINKED_CALIBRANT_EVIDENCE",
                "assumed_minimum_eta_used": str(min_eta_cal),
                "later_authorization_requirement": (
                    "Two-strain CD55 persistence bounds currently apply the assumed minimum detection "
                    "efficiency eta = 0.80 and protocol SHA-256 attribution; linked strain-specific "
                    "detection-efficiency calibrant evidence and measurement attribution are required "
                    "prior to any later product authorization."
                ),
                "min_cells_screened_across_strains_and_lineages_n": overall_min_n,
                "max_u_cd55_upper_80d": format(overall_max_u, "f")[:24] if overall_max_u is not None else None,
                "strain_results": per_strain_out,
            }
    elif isinstance(cd55_add, dict):
        # B6 / R04-B4: Never silently drop submitted adverse CD55 addendum data (legacy OR per-strain)!
        supplemental_adjudicated.append("supplemental_addendum:cd55_tropic_echovirus_addendum")
        t72_55 = _to_exact_decimal(cd55_add.get("echovirus_titer_72h_log10_pfu_u95"))
        d14_55 = _to_exact_decimal(cd55_add.get("echovirus_day14_log10_reduction_l95"))
        d28_pfu_55 = _to_exact_decimal(cd55_add.get("echovirus_day28_supernatant_pfu_ml"))
        c55_k = cd55_add.get("echovirus_persistence_confirmed_k")
        if t72_55 is not None and t72_55 > Decimal("2.0"):
            hard_stops.append("FAIL_HARD_STOP_SUPPLEMENTAL_CD55_ADDENDUM_72H_TITER")
        if d14_55 is not None and d14_55 < Decimal("3.0"):
            hard_stops.append("FAIL_HARD_STOP_SUPPLEMENTAL_CD55_ADDENDUM_DAY14_CLEARANCE")
        if d28_pfu_55 is not None and d28_pfu_55 > Decimal(0):
            hard_stops.append("FAIL_HARD_STOP_SUPPLEMENTAL_CD55_ADDENDUM_DAY28_SHEDDING")
        if _is_strict_int(c55_k) and c55_k >= 1:
            hard_stops.append("FAIL_HARD_STOP_SUPPLEMENTAL_CD55_ECHOVIRUS_PERSISTENCE_DETECTED")
        sup_sr = cd55_add.get("strain_results")
        if isinstance(sup_sr, dict):
            for sid, sb in sup_sr.items():
                if not isinstance(sb, dict):
                    continue
                s_tag = str(sid).upper()
                st72 = _to_exact_decimal(sb.get("titer_72h_log10_pfu_u95"))
                sd14 = _to_exact_decimal(sb.get("day14_log10_reduction_l95"))
                sd28 = _to_exact_decimal(sb.get("day28_supernatant_pfu_ml"))
                if st72 is not None and st72 > Decimal("2.0"):
                    hard_stops.append(f"FAIL_HARD_STOP_SUPPLEMENTAL_CD55_ADDENDUM_72H_TITER_{s_tag}")
                if sd14 is not None and sd14 < Decimal("3.0"):
                    hard_stops.append(f"FAIL_HARD_STOP_SUPPLEMENTAL_CD55_ADDENDUM_DAY14_CLEARANCE_{s_tag}")
                if sd28 is not None and sd28 > Decimal(0):
                    hard_stops.append(f"FAIL_HARD_STOP_SUPPLEMENTAL_CD55_ADDENDUM_DAY28_SHEDDING_{s_tag}")
                slin = sb.get("day28_persistence_by_lineage")
                if isinstance(slin, dict):
                    for ln_name, l_ent in slin.items():
                        if ln_name not in GRAFT_LINEAGES:
                            holds.append(f"HOLD_UNRECOGNIZED_LINEAGE_KEY_GATE0V_CD55_SUPPLEMENTAL_{s_tag}_{str(ln_name).upper()}")
                        if isinstance(l_ent, dict) and _is_strict_int(l_ent.get("confirmed_k")) and l_ent["confirmed_k"] >= 1:
                            hard_stops.append(
                                f"FAIL_HARD_STOP_SUPPLEMENTAL_CD55_ECHOVIRUS_PERSISTENCE_DETECTED_{s_tag}_{str(ln_name).upper()}_K_{l_ent['confirmed_k']}"
                            )

    # ------------------------------------------------------------------
    # 2. Non-Vacuous Gate 0V-A: Fixed 500 ng/mL poly(I:C) + Controls + >=2.0x in >=3/4 Markers
    # ------------------------------------------------------------------
    poly_ic = payload.get("gate0v_a_poly_ic_sensing")
    if not isinstance(poly_ic, dict):
        holds.append("HOLD_GATE0V_A_POLY_IC_INNATE_SENSING_PANEL_MISSING")
    else:
        dose = _to_exact_decimal_nonneg(poly_ic.get("poly_ic_dose_ng_ml"))
        dur = _to_exact_decimal_nonneg(poly_ic.get("assay_duration_h"))
        veh_ok = poly_ic.get("vehicle_control_isg_baseline_verified")
        veh_sha = poly_ic.get("vehicle_control_evidence_sha256")
        pos_ctrl = poly_ic.get("positive_control_ifna_isg_fold")
        lin_isg = poly_ic.get("lineage_isg_fold_induction")

        if dose is None or dose != Decimal("500"):
            holds.append("HOLD_GATE0V_A_DOSE_MUST_BE_EXACT_500_NG_ML")
        if dur is None or not (Decimal("24") <= dur <= Decimal("48")):
            holds.append("HOLD_GATE0V_A_INVALID_OR_MISSING_ASSAY_DURATION_H")
        if veh_ok is not True or not _is_valid_sha256_hex(veh_sha):
            holds.append("HOLD_GATE0V_A_MISSING_VEHICLE_CONTROL_OR_DIGEST")
        if not isinstance(pos_ctrl, dict):
            holds.append("HOLD_GATE0V_A_MISSING_POSITIVE_CONTROL_PANEL")
        else:
            for lin in GRAFT_LINEAGES:
                pv = _to_exact_decimal_nonneg(pos_ctrl.get(lin))
                if pv is None or pv < Decimal("4.0") or pv > Decimal("1000000"):
                    holds.append(f"HOLD_GATE0V_A_POSITIVE_CONTROL_BELOW_4X_OR_MISSING_{lin.upper()}")
            for extra_lin in pos_ctrl.keys():
                if extra_lin not in GRAFT_LINEAGES:
                    holds.append(f"HOLD_UNRECOGNIZED_LINEAGE_KEY_GATE0V_A_POS_CTRL_{str(extra_lin).upper()}")
        if not isinstance(lin_isg, dict):
            holds.append("HOLD_GATE0V_A_MISSING_STRUCTURED_5LINEAGE_ISG_NUMERIC_PANEL")
        else:
            for lin in GRAFT_LINEAGES:
                l_entry = lin_isg.get(lin)
                if not isinstance(l_entry, dict):
                    holds.append(f"HOLD_GATE0V_A_MISSING_ISG_LINEAGE_{lin.upper()}")
                    continue
                valid_markers = 0
                induced_ge_2x = 0
                for mk in GATE0V_A_REQUIRED_ISG_MARKERS:
                    mv = _to_exact_decimal_nonneg(l_entry.get(mk))
                    if mv is None or mv < Decimal(0) or mv > Decimal("1000000"):
                        holds.append(f"HOLD_GATE0V_A_INVALID_ISG_{mk.upper()}_{lin.upper()}")
                    else:
                        valid_markers += 1
                        if mv >= Decimal("2.0"):
                            induced_ge_2x += 1
                if valid_markers == len(GATE0V_A_REQUIRED_ISG_MARKERS) and induced_ge_2x < 3:
                    hard_stops.append(
                        f"FAIL_HARD_STOP_GATE0V_A_INSUFFICIENT_ISG_INDUCTION_{lin.upper()}_{induced_ge_2x}_OF_4_LT_3"
                    )
            for extra_lin, extra_entry in lin_isg.items():
                if extra_lin not in GRAFT_LINEAGES:
                    el_tag = str(extra_lin).upper()
                    holds.append(f"HOLD_UNRECOGNIZED_LINEAGE_KEY_GATE0V_A_ISG_{el_tag}")
                    if isinstance(extra_entry, dict):
                        ev_valid = 0
                        ev_ge_2x = 0
                        for mk in GATE0V_A_REQUIRED_ISG_MARKERS:
                            mv = _to_exact_decimal_nonneg(extra_entry.get(mk))
                            if mv is not None and Decimal(0) <= mv <= Decimal("1000000"):
                                ev_valid += 1
                                if mv >= Decimal("2.0"):
                                    ev_ge_2x += 1
                        if ev_valid == len(GATE0V_A_REQUIRED_ISG_MARKERS) and ev_ge_2x < 3:
                            hard_stops.append(
                                f"FAIL_HARD_STOP_GATE0V_A_INSUFFICIENT_ISG_INDUCTION_{el_tag}_{ev_ge_2x}_OF_4_LT_3"
                            )

    # ------------------------------------------------------------------
    # 3. Gate 0V-B: Two-Stage True-U95-Calibrated + Dual-Target Latent-Genome + Reconciled Lineage Ledger
    # ------------------------------------------------------------------
    required_pathogens: Tuple[str, ...] = (
        GATE0V_PATHOGENS
        if qual_tier == "BANK_QUALIFICATION"
        else (
            ("cvb4_e2",)
            if qual_tier == "LOT_RELEASE_SURROGATE"
            else (() if (qual_tier == "AUTOLOGOUS_D1B_PROCESS_QUAL" and tier_allowed_for_product) else GATE0V_PATHOGENS)
        )
    )
    alpha_obs_tier = alpha_3p if len(required_pathogens) == 3 else alpha_1p

    inf = payload.get("gate0v_b_infectious_challenge")
    pathogens_map = inf.get("pathogens") if isinstance(inf, dict) else None
    pathogen_results: Dict[str, Any] = {}
    all_pathogens_ok = True

    if required_pathogens:
        if not isinstance(inf, dict):
            holds.append("HOLD_GATE0V_B_MISSING_LIVE_INFECTIOUS_CHALLENGE_POLY_IC_CANNOT_SUBSTITUTE")
            all_pathogens_ok = False
        elif not isinstance(pathogens_map, dict):
            holds.append("HOLD_GATE0V_B_MISSING_PATHOGEN_SURVEILLANCE_SCHEMA")
            all_pathogens_ok = False
        else:
            for path_id in required_pathogens:
                p_tag = path_id.upper()
                pblock = pathogens_map.get(path_id)
                if not isinstance(pblock, dict):
                    holds.append(f"HOLD_GATE0V_B_MISSING_PATHOGEN_{p_tag}")
                    all_pathogens_ok = False
                    continue

                # Acute 72-h titers
                for comp_key in (
                    "endocrine_72h_log10_pfu_u95",
                    "vascular_72h_log10_pfu_u95",
                    "coculture_72h_log10_pfu_u95",
                ):
                    v = _to_exact_decimal_nonneg(pblock.get(comp_key))
                    if v is None or v < Decimal(0) or v > Decimal("15"):
                        holds.append(f"HOLD_GATE0V_B_MISSING_OR_INVALID_{p_tag}_{comp_key.upper()}")
                    elif v > Decimal("2.0"):
                        hard_stops.append(f"FAIL_GATE0V_B_ACUTE_TITER_EXCEEDS_2LOG10_{p_tag}_{comp_key.upper()}")

                # Day-14 genome reduction >= 3.0 log10
                for comp_key in ("endocrine_day14_log10_reduction_l95", "vascular_day14_log10_reduction_l95"):
                    v = _to_exact_decimal(pblock.get(comp_key))
                    if v is None or v < Decimal("-10") or v > Decimal("15"):
                        holds.append(f"HOLD_GATE0V_B_MISSING_OR_INVALID_{p_tag}_{comp_key.upper()}")
                    elif v < Decimal("3.0"):
                        hard_stops.append(f"FAIL_GATE0V_B_DAY14_CLEARANCE_BELOW_3LOG10_{p_tag}_{comp_key.upper()}")

                # Day-14 active replication RNA (-RNA for CVB4/CVB3; IE1 RNA for HCMV)
                rna_k = pblock.get("day14_negative_strand_or_ie1_rna_positive_wells_k")
                rna_n = pblock.get("day14_negative_strand_or_ie1_rna_wells_tested_n")
                if not (_is_strict_int(rna_k) and _is_strict_int(rna_n) and rna_k >= 0 and rna_n >= min_neg_rna_wells and rna_k <= rna_n):
                    holds.append(f"HOLD_GATE0V_B_INVALID_OR_UNDERPOWERED_ACTIVE_RNA_WELLS_{p_tag}")
                elif rna_k > 0:
                    hard_stops.append(f"FAIL_HARD_STOP_GATE0V_B_ACTIVE_VIRAL_RNA_DETECTED_{p_tag}")

                # Day-28 supernatant infectious shedding == 0 PFU/mL WITH volume >= 1.0 mL & LOD <= 1.0 PFU/mL
                day28_pfu = _to_exact_decimal_nonneg(pblock.get("day28_supernatant_infectious_pfu_ml"))
                day28_vol = _to_exact_decimal_nonneg(pblock.get("day28_supernatant_assay_volume_ml"))
                day28_lod = _to_exact_decimal_nonneg(pblock.get("day28_supernatant_lod_pfu_ml"))
                if day28_pfu is None or day28_pfu < Decimal(0):
                    holds.append(f"HOLD_GATE0V_B_MISSING_DAY28_SUPERNATANT_PLAQUE_{p_tag}")
                elif day28_pfu > Decimal(0):
                    hard_stops.append(f"FAIL_HARD_STOP_GATE0V_B_DAY28_INFECTIOUS_SHEDDING_{p_tag}")
                if day28_vol is None or day28_vol < Decimal("1.0"):
                    holds.append(f"HOLD_GATE0V_B_MISSING_OR_LOW_DAY28_ASSAY_VOLUME_ML_{p_tag}")
                if day28_lod is None or day28_lod <= Decimal(0) or day28_lod > Decimal("1.0"):
                    holds.append(f"HOLD_GATE0V_B_MISSING_OR_COARSE_DAY28_ASSAY_LOD_{p_tag}")

                # Paired edited-vs-WT non-inferiority across ALL edited antiviral genotypes (with replicate n >= 6)
                if isinstance(geno, str) and geno in EDITED_ANTIVIRAL_GENOTYPES:
                    delta_l95 = _to_exact_decimal(pblock.get("edited_minus_wt_day14_log10_reduction_l95"))
                    ni_reps = pblock.get("paired_noninferiority_replicates_n")
                    if not (_is_strict_int(ni_reps) and ni_reps >= min_noninf_replicates):
                        holds.append(f"HOLD_GATE0V_B_UNDERPOWERED_NONINFERIORITY_REPLICATES_{p_tag}")
                    if delta_l95 is None or delta_l95 < Decimal("-15") or delta_l95 > Decimal("15"):
                        holds.append(f"HOLD_GATE0V_B_MISSING_EDITED_VS_WT_NONINFERIORITY_{p_tag}")
                    elif delta_l95 < Decimal("-0.50"):
                        hard_stops.append(f"FAIL_GATE0V_B_ANTIVIRAL_COMPETENCE_LOSS_EXCEEDS_0P5_LOG10_{p_tag}")

                # Dual-Marker Lineage Fidelity + <= 5% Unassigned Cap + Mandatory Unassigned Viral Readout (B5)
                dual_mk_ok = pblock.get("dual_marker_lineage_panel_attested")
                panel_sha = pblock.get("lineage_panel_spec_sha256")
                tot_acq = pblock.get("total_viable_cells_acquired_n")
                unassigned_n = pblock.get("lineage_unassigned_cells_n")
                unassigned_frac_disp: float | None = None
                if dual_mk_ok is not True or not _is_valid_sha256_hex(panel_sha):
                    holds.append(f"HOLD_GATE0V_B_MISSING_DUAL_MARKER_LINEAGE_PANEL_OR_DIGEST_{p_tag}")
                if not (_is_strict_int(tot_acq) and tot_acq >= 1 and _is_strict_int(unassigned_n) and 0 <= unassigned_n <= tot_acq):
                    holds.append(f"HOLD_GATE0V_B_MISSING_OR_INVALID_LINEAGE_UNASSIGNED_COUNTS_{p_tag}")
                else:
                    with _clean_dec_ctx(80, ROUND_CEILING):
                        u_frac = Decimal(unassigned_n) / Decimal(tot_acq)
                    unassigned_frac_disp = _dec_to_float_pct(u_frac, 4)
                    if u_frac > max_unassigned_frac:
                        holds.append(f"HOLD_GATE0V_B_LINEAGE_UNASSIGNED_EXCEEDS_5PCT_{p_tag}")

                # B5: Mandatory unassigned-fraction viral readout so infected cells cannot hide in <=5% unassigned bucket!
                unass_ro = pblock.get("unassigned_fraction_viral_readout")
                unass_ro_summary: Dict[str, Any] = {"passed": False}
                if not isinstance(unass_ro, dict):
                    holds.append(f"HOLD_GATE0V_B_MISSING_UNASSIGNED_FRACTION_VIRAL_READOUT_{p_tag}")
                else:
                    u_scr = unass_ro.get("unassigned_cells_screened_n")
                    u_k1 = unass_ro.get("stage1_screen_positive_k")
                    u_n2 = unass_ro.get("stage2_sorted_for_confirmation_n")
                    u_k2 = unass_ro.get("stage2_confirmed_infectious_k")
                    u_ok = True
                    if not (
                        _is_strict_int(u_scr) and _is_strict_int(unassigned_n) and u_scr == unassigned_n
                        and _is_strict_int(u_k1) and 0 <= u_k1 <= u_scr
                        and _is_strict_int(u_n2) and 0 <= u_n2 <= u_scr
                        and _is_strict_int(u_k2) and 0 <= u_k2 <= u_n2
                    ):
                        holds.append(f"HOLD_GATE0V_B_INVALID_UNASSIGNED_VIRAL_READOUT_COUNTS_{p_tag}")
                        u_ok = False
                    else:
                        if u_k2 >= 1:
                            hard_stops.append(f"FAIL_HARD_STOP_GATE0V_CONFIRMED_VIRAL_POSITIVE_UNASSIGNED_{p_tag}_K_{u_k2}")
                            u_ok = False
                        if u_n2 != u_k1:
                            holds.append(f"HOLD_GATE0V_B_UNCONFIRMED_UNASSIGNED_STAGE1_HITS_{p_tag}")
                            u_ok = False
                        if u_scr >= 1:
                            with _clean_dec_ctx(80, ROUND_CEILING):
                                u_s1_frac = Decimal(u_k1) / Decimal(u_scr)
                            if u_s1_frac > max_stage1_screen_frac:
                                holds.append(f"HOLD_GATE0V_B_UNASSIGNED_STAGE1_SCREEN_EXCEEDS_0P2PCT_{p_tag}")
                                u_ok = False
                    unass_ro_summary = {
                        "unassigned_cells_screened_n": u_scr if _is_strict_int(u_scr) else None,
                        "stage1_screen_positive_k": u_k1 if _is_strict_int(u_k1) else None,
                        "stage2_sorted_for_confirmation_n": u_n2 if _is_strict_int(u_n2) else None,
                        "stage2_confirmed_infectious_k": u_k2 if _is_strict_int(u_k2) else None,
                        "passed": u_ok,
                    }

                # B5: Day-28 Latent-State & Defective-Genome ddPCR Arm with STRICT Dual-Target Panel Validation!
                lat_arm = pblock.get("day28_latent_and_defective_genome_arm")
                lat_summary: Dict[str, Any] = {"passed": False}
                if not isinstance(lat_arm, dict):
                    holds.append(f"HOLD_GATE0V_B_MISSING_LATENT_OR_DEFECTIVE_GENOME_ARM_{p_tag}")
                else:
                    dd_panel = lat_arm.get("ddpcr_target_panel")
                    dd_targets = lat_arm.get("ddpcr_targets")
                    dd_k = lat_arm.get("ddpcr_positive_events_k")
                    dd_n = lat_arm.get("ddpcr_cell_equivalents_screened_n")
                    dd_sha = lat_arm.get("evidence_sha256")
                    lat_ok = True

                    expected_panel_name = (
                        "HCMV_UL138_UL55_LATENT_LYTIC"
                        if path_id == "hcmv"
                        else "CVB_5PRIME_DELETION_AWARE_POS_NEG_RNA"
                    )
                    required_targets = (
                        HCMV_REQUIRED_DDPCR_TARGETS
                        if path_id == "hcmv"
                        else CVB_REQUIRED_DDPCR_TARGETS
                    )
                    if dd_panel != expected_panel_name:
                        holds.append(f"HOLD_GATE0V_B_INVALID_OR_MISSING_DDPCR_TARGET_PANEL_{p_tag}")
                        lat_ok = False

                    target_details: Dict[str, Any] = {}
                    lat_unit_maps: Dict[str, Dict[str, Tuple[int, int]]] = {}
                    sum_target_k = 0
                    all_targets_valid_ints = True
                    if not isinstance(dd_targets, dict):
                        holds.append(f"HOLD_GATE0V_B_MISSING_DUAL_DDPCR_TARGETS_TABLE_{p_tag}")
                        lat_ok = False
                        all_targets_valid_ints = False
                    else:
                        for tgt in required_targets:
                            t_entry = dd_targets.get(tgt)
                            if not isinstance(t_entry, dict):
                                holds.append(f"HOLD_GATE0V_B_MISSING_REQUIRED_DDPCR_TARGET_{p_tag}_{tgt}")
                                lat_ok = False
                                all_targets_valid_ints = False
                                continue
                            tk = t_entry.get("k")
                            tn = t_entry.get("n")
                            tpv = t_entry.get("primers_verified")
                            if tpv is not True:
                                holds.append(f"HOLD_GATE0V_B_UNVERIFIED_DDPCR_TARGET_PRIMERS_{p_tag}_{tgt}")
                                lat_ok = False
                            if not (_is_strict_int(tk) and _is_strict_int(tn) and tn >= 1 and 0 <= tk <= tn):
                                holds.append(f"HOLD_GATE0V_B_INVALID_DDPCR_TARGET_COUNTS_{p_tag}_{tgt}")
                                lat_ok = False
                                all_targets_valid_ints = False
                                continue
                            sum_target_k += tk
                            if tk >= 1:
                                hard_stops.append(
                                    f"FAIL_HARD_STOP_GATE0V_B_LATENT_OR_DEFECTIVE_GENOME_DETECTED_{p_tag}_{tgt}_K_{tk}"
                                )
                                lat_ok = False
                            if not _check_estimand_sampling_unit_basis(
                                t_entry.get("per_unit_counts"),
                                k_val=tk,
                                n_val=tn,
                                label=f"LATENT_{p_tag}_{tgt}",
                                zero_tolerance_hard_stop_token=f"FAIL_HARD_STOP_GATE0V_B_LATENT_OR_DEFECTIVE_GENOME_DETECTED_{p_tag}_{tgt}_K_UNIT_POS",
                                out_unit_maps=lat_unit_maps,
                            ):
                                lat_ok = False
                            tn_indep: int | None = None
                            u_tgt_str: str | None = None
                            if deff is None:
                                lat_ok = False
                            else:
                                tn_indep = _exact_floor_div_by_decimal(tn, deff)
                                if tn_indep < 1:
                                    holds.append(f"HOLD_GATE0V_B_LATENT_TARGET_UNDERPOWERED_{p_tag}_{tgt}")
                                    lat_ok = False
                                elif tk == 0:
                                    u_tgt = sound_zero_event_clopper_pearson_upper(
                                        tn_indep, alpha_obs_tier, min_eta_cal, prec=80
                                    )["u_thinned_upper_dec"]
                                    u_tgt_str = format(u_tgt, "f")[:24]
                                    if u_tgt > cap_frac_persist:
                                        holds.append(f"HOLD_GATE0V_B_LATENT_TARGET_UNDERPOWERED_{p_tag}_{tgt}")
                                        lat_ok = False
                            target_details[tgt] = {
                                "k": tk,
                                "n": tn,
                                "effective_independent_n": tn_indep,
                                "primers_verified": bool(tpv is True),
                                "u_target_upper_80d": u_tgt_str,
                            }
                        for extra_tgt, extra_tentry in dd_targets.items():
                            if extra_tgt not in required_targets:
                                et_tag = str(extra_tgt).upper()
                                holds.append(f"HOLD_GATE0V_B_UNRECOGNIZED_DDPCR_TARGET_{p_tag}_{et_tag}")
                                lat_ok = False
                                if isinstance(extra_tentry, dict) and _is_strict_int(extra_tentry.get("k")) and extra_tentry["k"] >= 1:
                                    hard_stops.append(
                                        f"FAIL_HARD_STOP_GATE0V_B_LATENT_OR_DEFECTIVE_GENOME_DETECTED_{p_tag}_{et_tag}_K_{extra_tentry['k']}"
                                    )

                    if not _is_valid_sha256_hex(dd_sha):
                        holds.append(f"HOLD_GATE0V_B_LATENT_ARM_MISSING_EVIDENCE_SHA256_{p_tag}")
                        lat_ok = False
                    if not (_is_strict_int(dd_k) and _is_strict_int(dd_n) and dd_n >= 1 and 0 <= dd_k <= dd_n):
                        holds.append(f"HOLD_GATE0V_B_LATENT_ARM_INVALID_DDPCR_COUNTS_{p_tag}")
                        lat_ok = False
                    else:
                        if all_targets_valid_ints and dd_k != sum_target_k:
                            holds.append(f"HOLD_GATE0V_B_LATENT_ARM_AGGREGATE_VS_TARGET_K_MISMATCH_{p_tag}")
                            lat_ok = False
                        if dd_k >= 1:
                            hard_stops.append(f"FAIL_HARD_STOP_GATE0V_B_LATENT_OR_DEFECTIVE_GENOME_DETECTED_{p_tag}_K_{dd_k}")
                            lat_ok = False
                        lat_arm_lbl = f"LATENT_ARM_{p_tag}"
                        if not _check_estimand_sampling_unit_basis(
                            lat_arm.get("per_unit_counts"),
                            k_val=dd_k,
                            n_val=dd_n,
                            label=lat_arm_lbl,
                            zero_tolerance_hard_stop_token=f"FAIL_HARD_STOP_GATE0V_B_LATENT_OR_DEFECTIVE_GENOME_DETECTED_{p_tag}_K_UNIT_POS",
                            out_unit_maps=lat_unit_maps,
                        ):
                            lat_ok = False
                        elif (
                            sampling_unit_class == "RECONCILED_MULTI_WELL_CELL_ASSAY_WITH_UNIT_PARTITION"
                            and lat_arm_lbl in lat_unit_maps
                            and all(f"LATENT_{p_tag}_{t}" in lat_unit_maps for t in required_targets)
                        ):
                            # R13-B2: Reconcile same unit_id set and per-unit target k sums across latent arm!
                            arm_umap = lat_unit_maps[lat_arm_lbl]
                            tgt_umaps = [lat_unit_maps[f"LATENT_{p_tag}_{t}"] for t in required_targets]
                            lat_cross_ok = all(set(tu.keys()) == set(arm_umap.keys()) for tu in tgt_umaps)
                            if lat_cross_ok:
                                for u_k, (arm_k_u, _arm_n_u) in arm_umap.items():
                                    if sum(tu[u_k][0] for tu in tgt_umaps) != arm_k_u:
                                        lat_cross_ok = False
                                        break
                            if not lat_cross_ok:
                                lat_ok = False
                                sampling_tracker["all_partitions_reconciled"] = False
                                if sampling_tracker["partitions_reconciled"] > 0:
                                    sampling_tracker["partitions_reconciled"] -= 1
                                if "HOLD_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION" not in holds:
                                    holds.append("HOLD_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION")
                                holds.append(f"HOLD_GATE0V_B_LATENT_ARM_UNIT_ID_OR_SUM_CONTRADICTION_{p_tag}")
                        if deff is None:
                            lat_ok = False
                        else:
                            dd_n_indep = _exact_floor_div_by_decimal(dd_n, deff)
                            if dd_n_indep < 1:
                                holds.append(f"HOLD_GATE0V_B_LATENT_ARM_UNDERPOWERED_{p_tag}")
                                lat_ok = False
                            elif dd_k == 0:
                                u_lat = sound_zero_event_clopper_pearson_upper(dd_n_indep, alpha_obs_tier, min_eta_cal, prec=80)["u_thinned_upper_dec"]
                                lat_summary["u_latent_upper_80d"] = format(u_lat, "f")[:24]
                                if u_lat > cap_frac_persist:
                                    holds.append(f"HOLD_GATE0V_B_LATENT_ARM_UNDERPOWERED_{p_tag}")
                                    lat_ok = False
                    if path_id == "hcmv":
                        react_app = lat_arm.get("reactivation_challenge_applied")
                        react_sha = lat_arm.get("reactivation_protocol_evidence_sha256")
                        react_pfu = _to_exact_decimal(lat_arm.get("reactivation_7d_outgrowth_pfu_ml"))
                        react_vol = _to_exact_decimal(lat_arm.get("reactivation_assay_volume_ml"))
                        react_lod = _to_exact_decimal(lat_arm.get("reactivation_lod_pfu_ml"))
                        if react_app is not True or not _is_valid_sha256_hex(react_sha):
                            holds.append("HOLD_GATE0V_B_HCMV_MISSING_REACTIVATION_CHALLENGE_OR_DIGEST")
                            lat_ok = False
                        if react_pfu is None or react_pfu < Decimal(0) or react_vol is None or react_vol < Decimal("1.0") or react_lod is None or react_lod <= Decimal(0) or react_lod > Decimal("1.0"):
                            holds.append("HOLD_GATE0V_B_HCMV_INVALID_REACTIVATION_OUTGROWTH_OR_LOD")
                            lat_ok = False
                        elif react_pfu > Decimal(0):
                            hard_stops.append("FAIL_HARD_STOP_GATE0V_B_HCMV_LATENT_REACTIVATION_OUTGROWTH")
                            lat_ok = False
                    else:
                        if lat_arm.get("cvb_5prime_deletion_primers_verified") is not True:
                            holds.append(f"HOLD_GATE0V_B_MISSING_CVB_5PRIME_DELETION_PRIMER_VERIFICATION_{p_tag}")
                            lat_ok = False
                    lat_summary["ddpcr_target_panel"] = dd_panel
                    lat_summary["ddpcr_targets"] = target_details
                    lat_summary["passed"] = lat_ok

                # 5-Lineage Two-Stage True-U95-Calibrated Surveillance + Reconciled Lineage Ledger (B3 + B5)
                lin_data = pblock.get("day28_persistence_by_lineage")
                lin_results: Dict[str, Any] = {}
                comp_weighted_u95 = Decimal(0)
                path_5lin_cal_ok = True
                sum_lineage_assigned_n = 0
                all_assigned_counts_present = True

                if not isinstance(lin_data, dict):
                    holds.append(f"HOLD_GATE0V_B_MISSING_5LINEAGE_TABLE_{p_tag}")
                    path_5lin_cal_ok = False
                    all_pathogens_ok = False
                    all_assigned_counts_present = False
                else:
                    for lin in GRAFT_LINEAGES:
                        entry = lin_data.get(lin)
                        if not isinstance(entry, dict):
                            holds.append(f"HOLD_GATE0V_B_MISSING_LINEAGE_{p_tag}_{lin.upper()}")
                            path_5lin_cal_ok = False
                            all_pathogens_ok = False
                            all_assigned_counts_present = False
                            continue
                        n_assigned = entry.get("cells_assigned_n")
                        n_i = entry.get("cells_scored_n")
                        k1_i = entry.get("stage1_screen_positive_k")
                        n2_sorted = entry.get("stage2_sorted_for_confirmation_n")
                        k2_conf = entry.get("stage2_confirmed_infectious_k")
                        uc_k = entry.get("uninfected_ctrl_fp_k")
                        uc_n = entry.get("uninfected_ctrl_scored_n")
                        rk_i = entry.get("spike_calibrant_detected_k")
                        rn_i = entry.get("spike_calibrant_total_n")
                        frk_i = entry.get("fragile_infected_spike_detected_k")
                        frn_i = entry.get("fragile_infected_spike_total_n")
                        pre_dissoc = entry.get("pre_dissociation_spike_in_attested")
                        spike_sha = entry.get("pre_dissociation_spike_sop_evidence_sha256")

                        if not (_is_strict_int(n_assigned) and _is_strict_int(n_i) and n_i >= 1 and n_assigned >= n_i):
                            holds.append(f"HOLD_GATE0V_B_MISSING_OR_INVALID_LINEAGE_ASSIGNED_COUNT_{p_tag}_{lin.upper()}")
                            path_5lin_cal_ok = False
                            all_pathogens_ok = False
                            all_assigned_counts_present = False
                        else:
                            sum_lineage_assigned_n += n_assigned

                        if not (
                            _is_strict_int(n_i) and n_i >= 1
                            and _is_strict_int(k1_i) and 0 <= k1_i <= n_i
                            and _is_strict_int(n2_sorted) and 0 <= n2_sorted <= n_i
                            and _is_strict_int(k2_conf) and 0 <= k2_conf <= n2_sorted
                        ):
                            holds.append(f"HOLD_GATE0V_B_INVALID_TWOSTAGE_COUNTS_{p_tag}_{lin.upper()}")
                            sampling_tracker["all_partitions_reconciled"] = False
                            path_5lin_cal_ok = False
                            all_pathogens_ok = False
                            continue

                        # Hard-stop veto on ANY confirmed infectious cell (evaluated BEFORE power holds!)
                        if k2_conf >= 1:
                            hard_stops.append(
                                f"FAIL_HARD_STOP_GATE0V_CONFIRMED_VIRAL_POSITIVE_{p_tag}_{lin.upper()}_K_{k2_conf}"
                            )

                        # R12-B1 + R17-B1: Validate per-estimand sampling-unit basis for Day-28 viral
                        # persistence, uninfected negative control, AND both recovery calibrants!
                        lin_unit_maps: Dict[str, Dict[str, Tuple[int, int]]] = {}
                        persist_lbl = f"PERSIST_{p_tag}_{lin.upper()}"
                        lin_unit_basis_ok = _check_estimand_sampling_unit_basis(
                            entry.get("per_unit_counts"),
                            k_val=k2_conf,
                            n_val=n_i,
                            label=persist_lbl,
                            zero_tolerance_hard_stop_token=f"FAIL_HARD_STOP_GATE0V_CONFIRMED_VIRAL_POSITIVE_{p_tag}_{lin.upper()}_K_UNIT_POS",
                            out_unit_maps=lin_unit_maps,
                        )
                        if not lin_unit_basis_ok:
                            path_5lin_cal_ok = False
                            all_pathogens_ok = False

                        # 100% of Stage-1 screen hits must be routed to Stage-2 orthogonal confirmation
                        if n2_sorted != k1_i:
                            holds.append(f"HOLD_GATE0V_B_UNCONFIRMED_STAGE1_HITS_{p_tag}_{lin.upper()}")
                            path_5lin_cal_ok = False
                            all_pathogens_ok = False

                        with _clean_dec_ctx(80, ROUND_CEILING):
                            screen_frac = Decimal(k1_i) / Decimal(n_i)
                        if screen_frac > max_stage1_screen_frac:
                            holds.append(f"HOLD_GATE0V_B_STAGE1_SCREEN_BURDEN_EXCEEDS_0P2PCT_{p_tag}_{lin.upper()}")
                            path_5lin_cal_ok = False
                            all_pathogens_ok = False

                        # B3 + R17-B1: Uninfected negative-control TRUE Clopper-Pearson U95 <= 0.15% gate
                        # (n >= 20,000) WITH mandatory typed sampling-unit reconciliation!
                        # At n = 20,000, alpha = 0.05: k = 20 -> U95 = 0.145277% <= 0.15% PASS;
                        #                              k = 21 -> U95 = 0.151167% >  0.15% HOLD!
                        fpr_u95_disp: float | None = None
                        fpr_u95_pass = False
                        neg_ctrl_unit_basis_ok = _check_estimand_sampling_unit_basis(
                            entry.get("uninfected_ctrl_per_unit_counts"),
                            k_val=uc_k,
                            n_val=uc_n,
                            label=f"NEG_CTRL_{p_tag}_{lin.upper()}",
                        )
                        if not neg_ctrl_unit_basis_ok:
                            path_5lin_cal_ok = False
                            all_pathogens_ok = False
                        if not (_is_strict_int(uc_k) and _is_strict_int(uc_n) and uc_n >= min_uninfected_ctrl_n and 0 <= uc_k <= uc_n):
                            holds.append(f"HOLD_GATE0V_B_MISSING_OR_UNDERPOWERED_UNINFECTED_FPR_CTRL_{p_tag}_{lin.upper()}")
                            path_5lin_cal_ok = False
                            all_pathogens_ok = False
                        else:
                            fpr_u95 = exact_clopper_pearson_upper_general(uc_k, uc_n, alpha_05, prec=60)
                            fpr_u95_disp = _dec_to_float_pct(fpr_u95, 6)
                            if fpr_u95 > max_neg_ctrl_fpr_u95:
                                holds.append(f"HOLD_GATE0V_B_UNINFECTED_CTRL_FPR_U95_EXCEEDS_0P15PCT_{p_tag}_{lin.upper()}")
                                path_5lin_cal_ok = False
                                all_pathogens_ok = False
                            elif neg_ctrl_unit_basis_ok and sampling_spec_valid and deff == Decimal("1.0"):
                                fpr_u95_pass = True

                        if pre_dissoc is not True or not _is_valid_sha256_hex(spike_sha):
                            holds.append(f"HOLD_GATE0V_B_PRE_DISSOCIATION_SPIKE_OR_DIGEST_MISSING_{p_tag}_{lin.upper()}")
                            path_5lin_cal_ok = False
                            all_pathogens_ok = False

                        # R17-B1: Mandatory typed sampling-unit reconciliation for BOTH Day-28 recovery calibrants!
                        cal_h_lbl = f"SPIKE_CAL_HEALTHY_{p_tag}_{lin.upper()}"
                        cal_f_lbl = f"SPIKE_CAL_FRAGILE_{p_tag}_{lin.upper()}"
                        cal_h_unit_basis_ok = _check_estimand_sampling_unit_basis(
                            entry.get("spike_calibrant_per_unit_counts"),
                            k_val=rk_i,
                            n_val=rn_i,
                            label=cal_h_lbl,
                            out_unit_maps=lin_unit_maps,
                        )
                        cal_f_unit_basis_ok = _check_estimand_sampling_unit_basis(
                            entry.get("fragile_infected_spike_per_unit_counts"),
                            k_val=frk_i,
                            n_val=frn_i,
                            label=cal_f_lbl,
                            out_unit_maps=lin_unit_maps,
                        )
                        if (
                            sampling_unit_class == "RECONCILED_MULTI_WELL_CELL_ASSAY_WITH_UNIT_PARTITION"
                            and persist_lbl in lin_unit_maps
                        ):
                            ref_lin_uids = set(lin_unit_maps[persist_lbl].keys())
                            if (
                                cal_h_unit_basis_ok
                                and cal_h_lbl in lin_unit_maps
                                and set(lin_unit_maps[cal_h_lbl].keys()) != ref_lin_uids
                            ):
                                cal_h_unit_basis_ok = False
                                sampling_tracker["all_partitions_reconciled"] = False
                                if sampling_tracker["partitions_reconciled"] > 0:
                                    sampling_tracker["partitions_reconciled"] -= 1
                                if "HOLD_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION" not in holds:
                                    holds.append("HOLD_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION")
                                holds.append(f"HOLD_GATE0V_B_SPIKE_CAL_HEALTHY_UNIT_ID_MISMATCH_{p_tag}_{lin.upper()}")
                            if (
                                cal_f_unit_basis_ok
                                and cal_f_lbl in lin_unit_maps
                                and set(lin_unit_maps[cal_f_lbl].keys()) != ref_lin_uids
                            ):
                                cal_f_unit_basis_ok = False
                                sampling_tracker["all_partitions_reconciled"] = False
                                if sampling_tracker["partitions_reconciled"] > 0:
                                    sampling_tracker["partitions_reconciled"] -= 1
                                if "HOLD_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION" not in holds:
                                    holds.append("HOLD_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION")
                                holds.append(f"HOLD_GATE0V_B_SPIKE_CAL_FRAGILE_UNIT_ID_MISMATCH_{p_tag}_{lin.upper()}")
                        if not (cal_h_unit_basis_ok and cal_f_unit_basis_ok):
                            path_5lin_cal_ok = False
                            all_pathogens_ok = False

                        if not (
                            _is_strict_int(rk_i) and _is_strict_int(rn_i) and rn_i >= 1 and 0 <= rk_i <= rn_i
                            and _is_strict_int(frk_i) and _is_strict_int(frn_i) and frn_i >= 1 and 0 <= frk_i <= frn_i
                        ):
                            holds.append(f"HOLD_GATE0V_B_MISSING_OR_INVALID_DUAL_SPIKE_CALIBRANT_{p_tag}_{lin.upper()}")
                            sampling_tracker["all_partitions_reconciled"] = False
                            path_5lin_cal_ok = False
                            all_pathogens_ok = False
                            continue

                        # By intersection-union principle, min(L_h(alpha), L_f(alpha)) guarantees error <= alpha
                        # for bounding min(eta_h, eta_f) from below without doubling the calibrant error budget.
                        eta_healthy_l = exact_clopper_pearson_lower_calibrant(rk_i, rn_i, alpha_obs_tier, prec=80)
                        eta_fragile_l = exact_clopper_pearson_lower_calibrant(frk_i, frn_i, alpha_obs_tier, prec=80)
                        eta_eff_l = min(eta_healthy_l, eta_fragile_l)
                        if eta_eff_l < min_eta_cal:
                            holds.append(f"HOLD_GATE0V_B_CALIBRANT_SENSITIVITY_BELOW_0P80_{p_tag}_{lin.upper()}")
                            path_5lin_cal_ok = False
                            all_pathogens_ok = False

                        # Apply clustering design effect conservatively (NEVER default deff=1.0 when missing/invalid!)
                        n_indep: int | None = None
                        u_lin_str: str | None = None
                        u_lin_pct_float: float | None = None
                        with _clean_dec_ctx(80, ROUND_HALF_EVEN):
                            w_i_float = round(float(Decimal(GRAFT_COMPOSITION_CELLS[lin]) / Decimal(TOTAL_GRAFT_CELLS)), 6)
                        if deff is None:
                            lin_pass = False
                            path_5lin_cal_ok = False
                            all_pathogens_ok = False
                        else:
                            n_indep = _exact_floor_div_by_decimal(n_i, deff)

                            if n_indep < 1 or eta_eff_l <= Decimal(0):
                                u_lin = Decimal(1)
                            elif k2_conf == 0:
                                cp = sound_zero_event_clopper_pearson_upper(n_indep, alpha_obs_tier, eta_eff_l, prec=80)
                                u_lin = cp["u_thinned_upper_dec"]
                            else:
                                u_raw = exact_clopper_pearson_upper_general(k2_conf, n_indep, alpha_obs_tier, prec=80)
                                with _clean_dec_ctx(80, ROUND_CEILING):
                                    u_lin = min(Decimal(1), u_raw / eta_eff_l)

                            with _clean_dec_ctx(80, ROUND_CEILING):
                                w_i_ceil = Decimal(GRAFT_COMPOSITION_CELLS[lin]) / Decimal(TOTAL_GRAFT_CELLS)
                                comp_weighted_u95 = comp_weighted_u95 + (w_i_ceil * u_lin)
                            u_lin_str = format(u_lin, "f")[:24]
                            u_lin_pct_float = _dec_to_float_pct(u_lin, 6)

                            lin_pass = bool(
                                k2_conf == 0
                                and n2_sorted == k1_i
                                and screen_frac <= max_stage1_screen_frac
                                and pre_dissoc is True
                                and _is_valid_sha256_hex(spike_sha)
                                and eta_eff_l >= min_eta_cal
                                and u_lin <= cap_frac_persist
                                and fpr_u95_pass
                                and lin_unit_basis_ok
                                and neg_ctrl_unit_basis_ok
                                and cal_h_unit_basis_ok
                                and cal_f_unit_basis_ok
                                and sampling_spec_valid
                                and deff == Decimal("1.0")
                            )
                            if k2_conf == 0 and eta_eff_l > Decimal(0) and u_lin > cap_frac_persist:
                                holds.append(f"HOLD_GATE0V_B_INSUFFICIENT_DENOMINATOR_{p_tag}_{lin.upper()}_U95_GT_5E4")

                        lin_results[lin] = {
                            "graft_fraction": w_i_float,
                            "cells_assigned_n": n_assigned if _is_strict_int(n_assigned) else None,
                            "cells_scored_n": n_i,
                            "effective_independent_n": n_indep,
                            "stage1_screen_positive_k": k1_i,
                            "stage2_sorted_for_confirmation_n": n2_sorted,
                            "stage2_confirmed_infectious_k": k2_conf,
                            "uninfected_ctrl_fpr_u95_pct": fpr_u95_disp,
                            "uninfected_ctrl_fpr_u95_clears_0p15pct": fpr_u95_pass,
                            "eta_healthy_lower_80d": format(eta_healthy_l, "f")[:24],
                            "eta_fragile_lower_80d": format(eta_fragile_l, "f")[:24],
                            "eta_effective_lower_80d": format(eta_eff_l, "f")[:24],
                            "u_lin_upper_80d": u_lin_str,
                            "u_lin_upper_pct": u_lin_pct_float,
                            "uninfected_ctrl_sampling_unit_reconciled": bool(neg_ctrl_unit_basis_ok and sampling_spec_valid),
                            "spike_calibrant_sampling_units_reconciled": bool(
                                cal_h_unit_basis_ok and cal_f_unit_basis_ok and sampling_spec_valid
                            ),
                            "sampling_unit_partition_reconciled": bool(
                                lin_unit_basis_ok
                                and neg_ctrl_unit_basis_ok
                                and cal_h_unit_basis_ok
                                and cal_f_unit_basis_ok
                                and sampling_spec_valid
                            ),
                            "passes_lineage_gate": lin_pass,
                        }

                    # R04-B3: Inspect ALL keys in day28_persistence_by_lineage — NEVER silently discard extra
                    # non-canonical lineage keys! Reject fail-closed and adjudicate any adverse viral counts.
                    for extra_lin, extra_entry in lin_data.items():
                        if extra_lin not in GRAFT_LINEAGES:
                            el_tag = str(extra_lin).upper()
                            holds.append(f"HOLD_UNRECOGNIZED_LINEAGE_KEY_GATE0V_B_{p_tag}_{el_tag}")
                            path_5lin_cal_ok = False
                            all_pathogens_ok = False
                            if not isinstance(extra_entry, dict):
                                holds.append(f"HOLD_GATE0V_B_INVALID_EXTRA_LINEAGE_ENTRY_{p_tag}_{el_tag}")
                                continue
                            ek2 = extra_entry.get("stage2_confirmed_infectious_k")
                            if _is_strict_int(ek2) and ek2 >= 1:
                                hard_stops.append(
                                    f"FAIL_HARD_STOP_GATE0V_CONFIRMED_VIRAL_POSITIVE_{p_tag}_{el_tag}_K_{ek2}"
                                )
                            ek1 = extra_entry.get("stage1_screen_positive_k")
                            en2 = extra_entry.get("stage2_sorted_for_confirmation_n")
                            if ek1 is not None or en2 is not None:
                                if not (_is_strict_int(ek1) and _is_strict_int(en2) and en2 == ek1):
                                    holds.append(f"HOLD_GATE0V_B_EXTRA_LINEAGE_UNCONFIRMED_STAGE1_HITS_{p_tag}_{el_tag}")

                # B5: Exact arithmetic reconciliation: total_acquired_n == sum(lineage_assigned_n) + unassigned_n!
                reconciled_exact = False
                if all_assigned_counts_present and _is_strict_int(tot_acq) and _is_strict_int(unassigned_n):
                    reconciled_exact = (tot_acq == sum_lineage_assigned_n + unassigned_n)
                    if not reconciled_exact:
                        holds.append(f"HOLD_GATE0V_B_LINEAGE_ACCOUNTING_RECONCILIATION_MISMATCH_{p_tag}")
                        path_5lin_cal_ok = False
                        all_pathogens_ok = False

                comp_pct = _dec_to_float_pct(comp_weighted_u95, 6) if path_5lin_cal_ok else None
                pathogen_results[path_id] = {
                    "all_5_lineages_calibrated": path_5lin_cal_ok,
                    "lineage_unassigned_pct": unassigned_frac_disp,
                    "lineage_accounting_ledger": {
                        "total_viable_cells_acquired_n": tot_acq if _is_strict_int(tot_acq) else None,
                        "sum_lineage_assigned_n": sum_lineage_assigned_n if all_assigned_counts_present else None,
                        "lineage_unassigned_cells_n": unassigned_n if _is_strict_int(unassigned_n) else None,
                        "reconciled_exact": reconciled_exact,
                    },
                    "unassigned_fraction_viral_readout": unass_ro_summary,
                    "latent_and_defective_genome_arm": lat_summary,
                    "composite_weighted_u95_pct": comp_pct,
                    "lineage_results": lin_results,
                }

    # B6 / R03-B1: Never silently drop submitted adverse or uncalibrated data in supplemental pathogens!
    if isinstance(pathogens_map, dict):
        for extra_pid, extra_pblock in pathogens_map.items():
            if extra_pid not in required_pathogens:
                _adjudicate_supplemental_pathogen_adverse_data(
                    extra_pid,
                    extra_pblock,
                    deff=deff,
                    alpha_obs_tier=alpha_obs_tier,
                    hard_stops=hard_stops,
                    holds=holds,
                    adjudicated_log=supplemental_adjudicated,
                    check_unit_basis_fn=_check_estimand_sampling_unit_basis,
                )

    # B6: Keep edited-genotype non-inferiority ACTIVE for AUTOLOGOUS_D1B_PROCESS_QUAL!
    if qual_tier == "AUTOLOGOUS_D1B_PROCESS_QUAL" and isinstance(geno, str) and geno in EDITED_ANTIVIRAL_GENOTYPES:
        ni_map = payload.get("genotype_noninferiority_by_pathogen")
        for path_id in GATE0V_PATHOGENS:
            p_tag = path_id.upper()
            src_blk = None
            if isinstance(ni_map, dict) and isinstance(ni_map.get(path_id), dict):
                src_blk = ni_map[path_id]
            elif isinstance(pathogens_map, dict) and isinstance(pathogens_map.get(path_id), dict):
                src_blk = pathogens_map[path_id]
            if not isinstance(src_blk, dict):
                holds.append(f"HOLD_GATE0V_GENO_AUTOLOGOUS_MISSING_NONINFERIORITY_{p_tag}")
                continue
            delta_l95 = _to_exact_decimal(src_blk.get("edited_minus_wt_day14_log10_reduction_l95"))
            ni_reps = src_blk.get("paired_noninferiority_replicates_n")
            if not (_is_strict_int(ni_reps) and ni_reps >= min_noninf_replicates):
                holds.append(f"HOLD_GATE0V_GENO_AUTOLOGOUS_UNDERPOWERED_NONINFERIORITY_REPLICATES_{p_tag}")
            if delta_l95 is None or delta_l95 < Decimal("-15") or delta_l95 > Decimal("15"):
                holds.append(f"HOLD_GATE0V_GENO_AUTOLOGOUS_MISSING_EDITED_VS_WT_NONINFERIORITY_{p_tag}")
            elif delta_l95 < Decimal("-0.50"):
                hard_stops.append(f"FAIL_GATE0V_GENO_AUTOLOGOUS_ANTIVIRAL_COMPETENCE_LOSS_EXCEEDS_0P5_LOG10_{p_tag}")

    # ------------------------------------------------------------------
    # 4. Gate 0V-Kill: Raw-Count Recomputed L95s + Exact <= 0.05 Bonferroni Joint Budgets (B4 + B6 + R03-B1)
    # ------------------------------------------------------------------
    required_kill_regimes: Tuple[str, ...] = (
        STRESS_AP1903_REGIMES
        if qual_tier == "BANK_QUALIFICATION"
        else ("normoxia_baseline", "hypoxia_1pct_plus_cytokines")
    )
    ap_data = payload.get("gate0v_kill_stress_ap1903")
    ap_summary: Dict[str, Any] = {}
    supplemental_ap_summary: Dict[str, Any] = {}
    if not isinstance(ap_data, dict):
        holds.append("HOLD_GATE0V_KILL_MISSING_STRESS_AP1903_PANEL")
    else:
        for reg in required_kill_regimes:
            rblock = ap_data.get(reg)
            if not isinstance(rblock, dict):
                holds.append(f"HOLD_GATE0V_KILL_MISSING_REGIME_{reg.upper()}")
                continue
            reg_pass = True
            reg_lineage_details: Dict[str, Any] = {}
            for lin in GRAFT_LINEAGES:
                lblock = rblock.get(lin)
                if not isinstance(lblock, dict):
                    holds.append(f"HOLD_GATE0V_KILL_MISSING_{reg.upper()}_{lin.upper()}")
                    reg_pass = False
                    continue
                arm_ok, lin_detail = _adjudicate_kill_regime_lineage_arm(
                    reg,
                    lin,
                    lblock,
                    deff=deff,
                    hard_stops=hard_stops,
                    holds=holds,
                    is_supplemental=False,
                    sampling_spec_valid=sampling_spec_valid,
                    sampling_unit_class=sampling_unit_class,
                    indep_units_n=indep_units,
                    sampling_tracker=sampling_tracker,
                )
                if not arm_ok:
                    reg_pass = False
                reg_lineage_details[lin] = lin_detail
            # R04-B3: Inspect ALL keys in required stress-regime dict — NEVER silently discard extra
            # non-canonical lineage keys! Fail closed on unrecognized keys AND fully adjudicate
            # raw counts / caspase / viral survivors so adverse observations ALWAYS emit FAIL_HARD_STOP!
            for extra_lin, extra_lblock in rblock.items():
                if extra_lin not in GRAFT_LINEAGES:
                    el_tag = str(extra_lin).upper()
                    holds.append(f"HOLD_UNRECOGNIZED_LINEAGE_KEY_GATE0V_KILL_{reg.upper()}_{el_tag}")
                    reg_pass = False
                    if not isinstance(extra_lblock, dict):
                        holds.append(f"HOLD_GATE0V_KILL_INVALID_EXTRA_LINEAGE_BLOCK_{reg.upper()}_{el_tag}")
                        continue
                    _extra_ok, extra_detail = _adjudicate_kill_regime_lineage_arm(
                        reg,
                        str(extra_lin),
                        extra_lblock,
                        deff=deff,
                        hard_stops=hard_stops,
                        holds=holds,
                        is_supplemental=False,
                        sampling_spec_valid=sampling_spec_valid,
                        sampling_unit_class=sampling_unit_class,
                        indep_units_n=indep_units,
                        sampling_tracker=sampling_tracker,
                    )
                    reg_lineage_details[str(extra_lin)] = extra_detail
            ap_summary[reg] = {"passed": reg_pass, "lineages": reg_lineage_details}

        # R03-B1 / B6: Apply FULL consistent fail-closed adjudication to EVERY submitted supplemental stress regime!
        for extra_reg, extra_rblock in ap_data.items():
            if extra_reg not in required_kill_regimes:
                supplemental_ap_summary[extra_reg] = _adjudicate_supplemental_kill_regime_adverse_data(
                    extra_reg,
                    extra_rblock,
                    deff=deff,
                    hard_stops=hard_stops,
                    holds=holds,
                    adjudicated_log=supplemental_adjudicated,
                    sampling_spec_valid=sampling_spec_valid,
                    sampling_unit_class=sampling_unit_class,
                    indep_units_n=indep_units,
                    sampling_tracker=sampling_tracker,
                )

    # B6: Explicit tested-vs-inherited scope & tier-distinct PASS codes!
    inherited_pathogens = [p for p in GATE0V_PATHOGENS if p not in required_pathogens]
    inherited_kill_regimes = [r for r in STRESS_AP1903_REGIMES if r not in required_kill_regimes]
    tested_vs_inherited_scope = {
        "operational_tier": qual_tier if isinstance(qual_tier, str) else None,
        "tested_current_lot_pathogens": list(required_pathogens),
        "inherited_from_trusted_store_pathogens": inherited_pathogens,
        "tested_current_lot_kill_regimes": list(required_kill_regimes),
        "inherited_from_trusted_store_kill_regimes": inherited_kill_regimes,
        "edited_genotype_noninferiority_enforced_current_lot": bool(isinstance(geno, str) and geno in EDITED_ANTIVIRAL_GENOTYPES),
        "supplemental_submitted_data_adjudicated": supplemental_adjudicated,
        "inheritance_policy": (
            "BANK_QUALIFICATION tests full 3-pathogen x 5-lineage + 5-regime matrix directly (zero inheritance). "
            "LOT_RELEASE_SURROGATE inherits CVB3/HCMV persistence and ER/infected AP1903 regimes strictly from an "
            "externally verified MCB BANK_QUALIFICATION record while testing current-lot CVB4-E2 + 2-regime AP1903 "
            "and applying full consistent fail-closed adjudication to ALL submitted supplemental data. "
            "AUTOLOGOUS_D1B_PROCESS_QUAL inherits platform viral challenge strictly from an externally verified "
            "process-qualification record while enforcing current-lot adventitious-agent screening, Gate 0V-A, "
            "2-regime AP1903, edited-genotype non-inferiority, and full consistent fail-closed adjudication of ALL submitted supplemental data."
        ),
    }

    numerical_evidence_provenance_scope = {
        "supplied_assay_interval_and_replicate_summaries": (
            "Gate 0V-Geno paired edited-vs-WT antiviral non-inferiority (`edited_minus_wt_day14_log10_reduction_l95`, "
            "`paired_noninferiority_replicates_n >= 6`) and Gate 0V-B acute 72-h titer U95 / Day-14 log10 reduction L95 "
            "fields consume caller-supplied assay interval and replicate summaries rather than recomputing confidence "
            "intervals from raw replicate titers."
        ),
        "raw_count_recomputed_decimal_clopper_pearson_bounds": (
            "Gate 0V-B Day-28 viral persistence U_lin, uninfected negative-control U95 (<= 0.15% on n >= 20,000), "
            "dual healthy + fragile spike-calibrant recovery lower bounds (eta >= 0.80), dual-target latent/defective-genome "
            "ddPCR bounds, powered CD46/CD55 persistence bounds, and ALL Gate 0V-Kill 24-h, 72-h, vehicle survival, "
            "calibrant, Estimand 1, and Estimand 2 erasure bounds are independently recomputed from raw integer counts "
            "via outward-directed Decimal Clopper-Pearson interval arithmetic."
        ),
    }

    # R12-B1: Reconcile global per-estimand sampling-unit basis BEFORE finalizing confidence certification!
    is_clustered_deff_gt_1 = bool(deff is not None and deff > Decimal("1.0"))
    if (
        sampling_unit_class == "INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT"
        and sampling_tracker["max_binomial_denominator_n"] >= 1
        and (not indep_units_valid or indep_units is None or indep_units < sampling_tracker["max_binomial_denominator_n"])
    ):
        sampling_tracker["all_partitions_reconciled"] = False
        if "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS" not in holds:
            holds.append("HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS")

    all_sampling_units_reconciled = bool(
        sampling_spec_valid
        and sampling_tracker["all_partitions_reconciled"]
        and (
            (
                sampling_unit_class == "INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT"
                and indep_units is not None
                and sampling_tracker["max_binomial_denominator_n"] >= 1
                and indep_units >= max(MIN_INDEPENDENT_BIOLOGICAL_UNITS_N, sampling_tracker["max_binomial_denominator_n"])
            )
            or (
                sampling_unit_class == "RECONCILED_MULTI_WELL_CELL_ASSAY_WITH_UNIT_PARTITION"
                and sampling_tracker["partitions_checked"] > 0
                and sampling_tracker["partitions_reconciled"] == sampling_tracker["partitions_checked"]
            )
        )
    )

    # R13-M2: NEVER retain an unvalidated numeric `deff` inside `clustering_design_effect_deff`
    # when `clustering_and_independence_spec` is invalid, has < 6 units, or lacks reconciled partitions!
    validated_deff: Decimal | None = deff if (sampling_spec_valid and all_sampling_units_reconciled) else None
    deff_unvalidated_out: str | None = None if validated_deff is not None else submitted_deff_unvalidated_safe

    if not sampling_spec_valid or deff is None:
        is_exact_independent = False
        top_confidence_scope = "UNCERTIFIED_MISSING_OR_INVALID_SAMPLING_SPEC"
    elif not all_sampling_units_reconciled:
        is_exact_independent = False
        top_confidence_scope = "UNCERTIFIED_SAMPLING_UNIT_PARTITION_MISMATCH"
        if (
            "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS" not in holds
            and "HOLD_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION" not in holds
            and "HOLD_UNEXPECTED_PER_UNIT_COUNTS_IN_SINGLE_CELL_MODE" not in holds
        ):
            holds.append("HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS")
    elif is_clustered_deff_gt_1:
        is_exact_independent = False
        top_confidence_scope = "NON_AUTHORIZING_VARIANCE_ADJUSTED_DIAGNOSTIC_ONLY"
    elif sampling_unit_class == "INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT":
        is_exact_independent = True
        top_confidence_scope = "EXACT_INDEPENDENT_BINOMIAL_BONFERRONI_DEFF_EQ_1_UNIT_MATCHED"
    else:
        is_exact_independent = True
        top_confidence_scope = "CONDITIONAL_ON_EXTERNALLY_VALIDATED_WITHIN_WELL_INDEPENDENCE_DEFF_EQ_1"

    # Ensure NO nested Gate 0V-Kill arm or alpha-budget dict retains `exact_directional_confidence_certified = True`
    # when top-level certification is False, AND scrub unvalidated nested `clustering_design_effect_deff` to None!
    if not is_exact_independent or validated_deff is None:
        _scrub_stack: List[Any] = [ap_summary, supplemental_ap_summary]
        while _scrub_stack:
            _cur = _scrub_stack.pop()
            if isinstance(_cur, dict):
                if not is_exact_independent:
                    if _cur.get("exact_directional_confidence_certified") is True:
                        _cur["exact_directional_confidence_certified"] = False
                    if "confidence_scope" in _cur:
                        _cur["confidence_scope"] = top_confidence_scope
                    if "joint_confidence_lower_bound" in _cur:
                        _cur["joint_confidence_lower_bound"] = None
                    if _cur.get("estimand2_release_authorizing_eligible") is True:
                        _cur["estimand2_release_authorizing_eligible"] = False
                if validated_deff is None and "clustering_design_effect_deff" in _cur:
                    _cur["clustering_design_effect_deff"] = None
                for _v in _cur.values():
                    if isinstance(_v, (dict, list, tuple)):
                        _scrub_stack.append(_v)
            elif isinstance(_cur, (list, tuple)):
                for _item in _cur:
                    if isinstance(_item, (dict, list, tuple)):
                        _scrub_stack.append(_item)

    sampling_unit_basis = {
        "clustering_and_independence_spec_valid": sampling_spec_valid,
        "clustering_design_effect_deff": format(validated_deff, "f") if validated_deff is not None else None,
        "submitted_clustering_design_effect_deff_unvalidated": deff_unvalidated_out,
        "independent_sampling_unit_class": sampling_unit_class if sampling_unit_class_valid else None,
        "independent_biological_units_n": indep_units if indep_units_valid else None,
        "supplied_independent_biological_units_n": indep_units,
        "min_required_independent_biological_units_n": MIN_INDEPENDENT_BIOLOGICAL_UNITS_N,
        "unit_definition": unit_def if unit_def_valid else None,
        "max_binomial_denominator_n": sampling_tracker["max_binomial_denominator_n"],
        "estimand_partitions_checked": sampling_tracker["partitions_checked"],
        "estimand_partitions_reconciled": sampling_tracker["partitions_reconciled"],
        "all_sampling_units_reconciled": all_sampling_units_reconciled,
        "within_well_independence_externally_validated_required": bool(
            sampling_unit_class == "RECONCILED_MULTI_WELL_CELL_ASSAY_WITH_UNIT_PARTITION"
        ),
        "external_qa_disclaimer": (
            "JSON unit-partition reconciliation verifies per-unit arithmetic traceability across "
            ">= 6 declared independent biological units but does NOT by itself prove physical "
            "within-well statistical independence (deff == 1.0) or equal per-unit event probability "
            "(common-probability binomial model); external assay QA must verify zero intra-well "
            "clustering and homogeneous event probabilities, otherwise cluster-level or heterogeneous-unit "
            "inference is required."
            if sampling_unit_class == "RECONCILED_MULTI_WELL_CELL_ASSAY_WITH_UNIT_PARTITION"
            else (
                "Declared single-cell / limiting-dilution sampling basis matches independent unit count "
                "to the maximum evaluated binomial denominator (independent_biological_units_n >= max_n); "
                "unit-count declaration and arithmetic reconciliation do NOT physically prove representative "
                "sampling or a common Bernoulli event probability across units."
                if sampling_unit_class == "INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT" and all_sampling_units_reconciled
                else "Sampling-unit basis is missing, invalid, clustered (deff > 1.0), or unreconciled; exact directional confidence is NOT certified."
            )
        ),
        "probability_model_assumptions": (
            "Exact per-estimand directional one-sided Clopper-Pearson bounds assume representative, "
            "independent binary trials sharing a common event probability p within each component "
            "(standard Binomial(n, p) model). Independent sampling with unequal / heterogeneous unit "
            "event probabilities falls outside the standard common-probability binomial model. "
            "Gate 0V-Kill evaluates acute 24-h/72-h stressed AP1903 viability/erasure separately from "
            "long-horizon pan-lineage clonogenic eradication (which is owned by Blueprint Gate 5 / "
            "legacy MCB clonogenic trials in wetlab_contract.py & ISLET-1-BLUEPRINT.md §1.2/§4.5)."
        ),
    }

    # Hard stops ALWAYS take precedence over power/completeness holds!
    if hard_stops:
        verdict = "FAIL_HARD_STOP"
    elif holds:
        if holds == ["HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION"]:
            verdict = "HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION"
        elif holds == ["HOLD_NW08_REQUIRED_OCR_RECORD_MISSING"]:
            verdict = "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING"
        elif (
            sampling_spec_valid
            and all_sampling_units_reconciled
            and is_clustered_deff_gt_1
            and "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE" in holds
        ):
            verdict = "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE"
        else:
            verdict = "HOLD_INCOMPLETE_OR_UNDERPOWERED"
    else:
        verdict = (
            GATE0V_PASS_VERDICTS_BY_TIER.get(str(qual_tier), "HOLD_INCOMPLETE_OR_UNDERPOWERED")
            if is_exact_independent
            else "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        )

    return {
        "verdict": verdict,
        "release_authorizing": False,
        "gate0v_component_passed": bool(verdict in GATE0V_ALL_PASS_VERDICTS and is_exact_independent),
        "qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
        "physical_qualification_complete": False,
        "exact_directional_confidence_certified": is_exact_independent,
        "confidence_scope": top_confidence_scope,
        "sampling_unit_basis": sampling_unit_basis,
        "lot_binding": lot_binding,
        "tested_vs_inherited_scope": tested_vs_inherited_scope,
        "numerical_evidence_provenance_scope": numerical_evidence_provenance_scope,
        "ectopic_viral_receptors_evaluated": sorted(effective_ectopic),
        "clustering_design_effect_deff": format(validated_deff, "f") if validated_deff is not None else None,
        "submitted_clustering_design_effect_deff_unvalidated": deff_unvalidated_out,
        "hard_stops": hard_stops,
        "holds": holds,
        "global_3pathogen_fwer_alpha_per_test": format(alpha_3p, "f")[:24],
        "negative_control_u95_cap_pct": "0.15",
        "all_required_pathogens_and_5_lineages_calibrated": all_pathogens_ok,
        "pathogen_results": pathogen_results,
        "cd46_addendum_results": cd46_results,
        "cd55_addendum_results": cd55_results,
        "stress_ap1903_regimes": ap_summary,
        "supplemental_stress_ap1903_regimes": supplemental_ap_summary,
    }


# ---------------------------------------------------------------------------
# Part B (NW-08): True 3D FVM Vascular-Voxel Replay & Margin+Uncertainty Triggers
# ---------------------------------------------------------------------------
def _passes_unrounded_diagnostic_floor(raw_face_min_mmhg: float, custom_floor_mmhg: float) -> bool:
    """
    Strictly evaluate a non-authorizing diagnostic floor against the native UNROUNDED float64
    FV interface minimum. NEVER governs canonical 15.0 mmHg release pass/verdict!
    """
    try:
        val = _safe_finite_float(raw_face_min_mmhg, "raw_face_min_mmhg")
        fl = _safe_finite_float(custom_floor_mmhg, "custom_floor_mmhg")
    except ValueError:
        return False
    return bool(val >= fl)


def _passes_unrounded_15mmhg_floor(
    raw_face_min_mmhg: float,
    floor_mmhg: float = CANONICAL_NW08_PO2_FLOOR_MMHG,
) -> bool:
    """
    Strictly evaluate the IMMUTABLE canonical 15.0 mmHg GSIS floor against the native UNROUNDED
    float64 FV interface minimum BEFORE any 4-decimal display rounding (so 14.999959999870875
    strictly FAILS even though it formats to 15.0000!). Rejects any attempt to pass a non-15.0
    floor to this canonical release predicate.
    """
    try:
        fl = _safe_finite_float(floor_mmhg, "floor_mmhg")
    except ValueError as exc:
        raise ValueError(
            f"Canonical NW-08 15.0 mmHg release predicate requires floor_mmhg == "
            f"{CANONICAL_NW08_PO2_FLOOR_MMHG}; got invalid value"
        ) from exc
    if fl != CANONICAL_NW08_PO2_FLOOR_MMHG:
        raise ValueError(
            f"Canonical NW-08 15.0 mmHg release predicate requires floor_mmhg == "
            f"{CANONICAL_NW08_PO2_FLOOR_MMHG}; got {floor_mmhg!r}"
        )
    return _passes_unrounded_diagnostic_floor(raw_face_min_mmhg, CANONICAL_NW08_PO2_FLOOR_MMHG)


def _regularized_incomplete_beta(a: float, b: float, x: float) -> float:
    """Stdlib-only regularized incomplete beta I_x(a, b) via Lentz's continued fraction (zero assert)."""
    if x <= 0.0:
        return 0.0
    if x >= 1.0:
        return 1.0
    log_bt = (
        math.lgamma(a + b)
        - math.lgamma(a)
        - math.lgamma(b)
        + a * math.log(x)
        + b * math.log1p(-x)
    )
    bt = math.exp(log_bt)

    def _betacf(pa: float, pb: float, px: float) -> float:
        fpmin = 1.0e-300
        eps = 3.0e-15
        qab = pa + pb
        qap = pa + 1.0
        qam = pa - 1.0
        c = 1.0
        d = 1.0 - qab * px / qap
        if abs(d) < fpmin:
            d = fpmin
        d = 1.0 / d
        h = d
        for m in range(1, 201):
            m2 = 2 * m
            aa = m * (pb - m) * px / ((qam + m2) * (pa + 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 = -(pa + m) * (qab + m) * px / ((pa + 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

    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 exact_student_t_cdf(t_val: float, df: int) -> float:
    """Exact Student-t CDF F_t(t_val; df) for integer df >= 1 (pure Python stdlib)."""
    if isinstance(df, bool) or not isinstance(df, int) or df < 1 or df > MAX_NW08_STUDENT_T_DF:
        raise ValueError(f"HOLD_NW08_OCR_INVALID_DEGREES_OF_FREEDOM:df must be int in [1, {MAX_NW08_STUDENT_T_DF}]; got {df!r}")
    ft = _safe_finite_float(t_val, "t_val")
    if ft == 0.0:
        return 0.5
    x = float(df) / (float(df) + ft * ft)
    ib = _regularized_incomplete_beta(0.5 * float(df), 0.5, x)
    return (1.0 - 0.5 * ib) if ft > 0.0 else (0.5 * ib)


def _dec_atan_high_prec(u: Decimal, prec: int = 60) -> Decimal:
    """High-precision Decimal arctan(u) for u >= 0 under isolated clean Decimal context."""
    with _clean_dec_ctx(prec + 12, ROUND_HALF_EVEN):
        if u > Decimal("0.25"):
            return Decimal(2) * _dec_atan_high_prec(
                u / (Decimal(1) + (Decimal(1) + u * u).sqrt()), prec
            )
        u2 = u * u
        p_term = u
        tot = Decimal(0)
        tol = Decimal(10) ** (-(prec + 8))
        for idx in range(300):
            add = p_term / Decimal(2 * idx + 1)
            tot = (tot + add) if (idx % 2 == 0) else (tot - add)
            if abs(add) < tol:
                break
            p_term *= u2
        return tot


@lru_cache(maxsize=4)
def _dec_pi_high_prec(prec: int = 60) -> Decimal:
    """High-precision Decimal pi via Machin's formula under isolated clean Decimal context."""
    with _clean_dec_ctx(prec + 12, ROUND_HALF_EVEN):
        return Decimal(4) * (
            Decimal(4) * _dec_atan_high_prec(Decimal(1) / Decimal(5), prec)
            - _dec_atan_high_prec(Decimal(1) / Decimal(239), prec)
        )


def _exact_student_t_cdf_dec(t_dec: Decimal, df: int, prec: int = 55) -> Decimal:
    """
    Exact finite-sum Student-t CDF F_t(t_dec; df) in high-precision Decimal for integer df >= 1,
    t_dec >= 0 (pure Python stdlib, clean-context isolated).
    """
    with _clean_dec_ctx(prec, ROUND_HALF_EVEN):
        d = Decimal(df)
        x = d / (d + t_dec * t_dec)
        if df % 2 == 0:
            k = df // 2
            term = Decimal(1)
            s = term
            for j in range(1, k):
                term = term * Decimal(2 * j - 1) / Decimal(2 * j) * x
                s += term
            return Decimal("0.5") + Decimal("0.5") * (t_dec / (t_dec * t_dec + d).sqrt()) * s
        k = (df - 1) // 2
        pi_d = _dec_pi_high_prec(prec + 6)
        u = t_dec / d.sqrt()
        if k == 0:
            return Decimal("0.5") + _dec_atan_high_prec(u, prec + 6) / pi_d
        term = Decimal(1)
        s = term
        for j in range(1, k):
            term = term * Decimal(2 * j) / Decimal(2 * j + 1) * x
            s += term
        return Decimal("0.5") + (_dec_atan_high_prec(u, prec + 6) + u * x * s) / pi_d


# R17-B2: Provably upper-enclosed 60-digit standard-normal 95% one-sided quantile z_{0.95}
# (exact Phi^{-1}(0.95) = 1.644853626951472714863848907991632136083195744275322071769672094...).
_EXACT_Z95_UPPER_40D: Decimal = MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95_DEC


def _exact_standard_normal_cdf_dec(z_dec: Decimal, prec: int = 80) -> Decimal:
    """
    R17-B2 High-precision standard-normal CDF Phi(z_dec) in isolated clean Decimal context via
    exact alternating Taylor series erf(z / sqrt(2)) = (2/sqrt(pi)) * sum (-1)^n x^(2n+1) / (n!(2n+1)).
    Used to verify 1 - Phi(z) <= 0.05 strictly for upper normal quantile bounds.
    """
    with _clean_dec_ctx(prec + 16, ROUND_HALF_EVEN):
        z = Decimal(z_dec)
        if z == Decimal(0):
            return Decimal("0.5")
        az = z.copy_abs()
        x = az / Decimal(2).sqrt()
        x2 = x * x
        term = x
        total = term
        tol = Decimal(10) ** (-(prec + 12))
        for n in range(1, 600):
            term = -term * x2 / Decimal(n)
            add = term / Decimal(2 * n + 1)
            total += add
            if add.copy_abs() < tol:
                break
        pi_d = _dec_pi_high_prec(prec + 12)
        erf_val = Decimal(2) * total / pi_d.sqrt()
        if z > Decimal(0):
            return (Decimal(1) + erf_val) / Decimal(2)
        return (Decimal(1) - erf_val) / Decimal(2)


def _float64_round_up_from_fraction(target: Fraction) -> float:
    """
    R17-B2 Exact IEEE-754 float64 upward rounding of a finite non-negative rational `target`:
    returns the smallest finite float64 `f` such that `Fraction(f) >= target` via `math.nextafter`.
    """
    if target < 0:
        raise ValueError(f"Expected non-negative rational target; got {target!r}")
    if target == 0:
        return 0.0
    try:
        f_val = float(target)
    except OverflowError as exc:
        raise ValueError("Rational target overflowed IEEE-754 float64 range") from exc
    if not math.isfinite(f_val):
        raise ValueError("Rational target overflowed IEEE-754 float64 range")
    while Fraction(f_val) < target:
        f_val = math.nextafter(f_val, math.inf)
        if not math.isfinite(f_val):
            raise ValueError("Upward-rounded float64 overflowed IEEE-754 float64 range")
    return f_val


def _compute_conservative_upper_float64_vasc_scale(
    ocr_u95_dec: Decimal,
    baseline_ocr_float: float,
    baseline_ocr_dec: Decimal,
) -> Tuple[float, float]:
    """
    R17-B2 Derive the native 3D FVM solver's IEEE-754 float64 vascular-voxel scaling multiplier
    directly from exact rational `Fraction(ocr_u95_dec) / Fraction(baseline_ocr_dec)` and
    `Fraction(ocr_u95_dec)`, rounding strictly upward via `math.nextafter(..., math.inf)` so:
      1. `Fraction(mult_f64) >= Fraction(ocr_u95_dec) / Fraction(baseline_ocr_dec)`,
      2. `Fraction(baseline_ocr_float * mult_f64) >= Fraction(ocr_u95_dec)`,
      3. `Fraction(baseline_ocr_float) * Fraction(mult_f64) >= Fraction(ocr_u95_dec)`, and
      4. Whenever `ocr_u95_dec > baseline_ocr_dec`, `mult_f64 > 1.0` strictly.
    Returns `(mult_f64, effective_solver_ocr_f64)`.
    """
    target_ocr = Fraction(ocr_u95_dec)
    base_dec_frac = Fraction(baseline_ocr_dec)
    if (
        target_ocr <= 0
        or base_dec_frac <= 0
        or (not math.isfinite(baseline_ocr_float))
        or baseline_ocr_float <= 0.0
    ):
        raise ValueError("Require finite strictly positive OCR and baseline OCR for vascular scaling")
    if target_ocr == base_dec_frac:
        return 1.0, float(baseline_ocr_float)
    target_ratio = target_ocr / base_dec_frac
    base_float_frac = Fraction(baseline_ocr_float)
    mult_f64 = _float64_round_up_from_fraction(target_ratio)
    if target_ocr > base_dec_frac and mult_f64 <= 1.0:
        mult_f64 = math.nextafter(1.0, math.inf)
    while True:
        eff_ocr = baseline_ocr_float * mult_f64
        if not math.isfinite(eff_ocr) or eff_ocr <= 0.0:
            raise ValueError("Computed effective solver vascular OCR overflowed IEEE-754 float64 range")
        if (
            Fraction(mult_f64) >= target_ratio
            and Fraction(eff_ocr) >= target_ocr
            and base_float_frac * Fraction(mult_f64) >= target_ocr
            and (not (target_ocr > base_dec_frac) or mult_f64 > 1.0)
        ):
            return mult_f64, eff_ocr
        mult_f64 = math.nextafter(mult_f64, math.inf)
        if not math.isfinite(mult_f64):
            raise ValueError("Computed vascular voxel scale factor overflowed IEEE-754 float64 range")


@lru_cache(maxsize=256)
def exact_student_t_one_sided_95(df: int) -> float:
    """
    R14-B2 + R16-M1 Provably outward-conservative upper-enclosed one-sided 95% Student-t critical
    value t_{0.95, df} >= exact_quantile for ALL integer degrees of freedom df in [1, 10**9]:
      - df == 1: exact algebraic Cauchy identity cot(pi/20) = sqrt(5 + 2*sqrt(5)) + sqrt(5) + 1
        evaluated in 80-digit Decimal and rounded UP to IEEE-754 float64 (`>= cot(pi/20)`).
      - df == 2: exact closed form sqrt(162 / 19) evaluated in 80-digit Decimal and rounded UP.
      - 3 <= df <= 2000: safeguarded high-precision Decimal inversion of the exact finite-sum
        Student-t CDF with outward margin + upward float64 enclosure (e.g. df = 5 -> 2.0150483733330247,
        displaying exact 7-dp `2.0150484` with ZERO inward rounding error).
      - df > 2000: 4-term high-precision Decimal Cornish-Fisher expansion from upper-enclosed z_{0.95}
        plus provably positive conservative O(1/df^5) remainder `10 / df^5`, rounded UP to float64.
    Guarantees BOTH `Decimal.from_float(res) >= exact_quantile` AND `Decimal(str(res)) >= exact_quantile`.
    """
    if isinstance(df, bool) or not isinstance(df, int) or df < 1 or df > MAX_NW08_STUDENT_T_DF:
        raise ValueError(f"HOLD_NW08_OCR_INVALID_DEGREES_OF_FREEDOM:df must be int in [1, {MAX_NW08_STUDENT_T_DF}]; got {df!r}")

    def _cf_upper_dec(d_int: int) -> Decimal:
        with _clean_dec_ctx(60, ROUND_HALF_EVEN):
            z = _EXACT_Z95_UPPER_40D
            z2 = z * z
            z3 = z2 * z
            z5 = z3 * z2
            z7 = z5 * z2
            z9 = z7 * z2
            d = Decimal(d_int)
            g1 = (z3 + z) / Decimal(4)
            g2 = (Decimal(5) * z5 + Decimal(16) * z3 + Decimal(3) * z) / Decimal(96)
            g3 = (Decimal(3) * z7 + Decimal(19) * z5 + Decimal(17) * z3 - Decimal(15) * z) / Decimal(384)
            g4 = (
                Decimal(79) * z9
                + Decimal(776) * z7
                + Decimal(1482) * z5
                - Decimal(1920) * z3
                - Decimal(945) * z
            ) / Decimal(92160)
            # Conservative strictly positive O(1/df^5) remainder (>60x true g5 ~ 0.145 at p=0.95)
            rem = Decimal(10) / (d ** 5)
            return z + g1 / d + g2 / (d * d) + g3 / (d ** 3) + g4 / (d ** 4) + rem

    if df == 1:
        with _clean_dec_ctx(80, ROUND_HALF_EVEN):
            s5 = Decimal(5).sqrt()
            exact_u = (Decimal(5) + Decimal(2) * s5).sqrt() + s5 + Decimal(1) + Decimal("1e-60")
    elif df == 2:
        with _clean_dec_ctx(80, ROUND_HALF_EVEN):
            exact_u = (Decimal(162) / Decimal(19)).sqrt() + Decimal("1e-60")
    elif df <= 2000:
        with _clean_dec_ctx(60, ROUND_HALF_EVEN):
            p95 = Decimal("0.95")
            t_est = _cf_upper_dec(df)
            step = Decimal("0.01") if df >= 10 else Decimal("0.2")
            lo = max(_EXACT_Z95_UPPER_40D, t_est - step)
            hi = t_est + step
            while _exact_student_t_cdf_dec(lo, df, 52) >= p95:
                hi = lo
                lo = max(Decimal("1.6448536"), lo - step)
            while _exact_student_t_cdf_dec(hi, df, 52) < p95:
                lo = hi
                hi = hi + step
            f_lo = _exact_student_t_cdf_dec(lo, df, 52) - p95
            f_hi = _exact_student_t_cdf_dec(hi, df, 52) - p95
            for it in range(100):
                if hi - lo <= Decimal("1e-35"):
                    break
                if it % 3 != 2 and f_hi != f_lo:
                    cand = lo - f_lo * (hi - lo) / (f_hi - f_lo)
                    if not (lo < cand < hi):
                        cand = (lo + hi) / Decimal(2)
                else:
                    cand = (lo + hi) / Decimal(2)
                f_c = _exact_student_t_cdf_dec(cand, df, 52) - p95
                if f_c < Decimal(0):
                    lo, f_lo = cand, f_c
                else:
                    hi, f_hi = cand, f_c
            exact_u = hi + Decimal("1e-32")
    else:
        with _clean_dec_ctx(60, ROUND_HALF_EVEN):
            exact_u = _cf_upper_dec(df) + Decimal("1e-50")

    f_val = max(MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95, float(exact_u))
    with _clean_dec_ctx(80, ROUND_HALF_EVEN):
        while Decimal.from_float(f_val) < exact_u or Decimal(str(f_val)) < exact_u:
            f_val = math.nextafter(f_val, math.inf)
    return f_val


def _resolve_nw08_ocr_uncertainty_bound(
    *,
    f_measured_ocr: float,
    dec_measured_ocr: Decimal,
    f_uncertainty_se: float,
    dec_uncertainty_se: Decimal,
    z_one_sided_95: Any = None,
    ocr_uncertainty_model: Any = None,
    ocr_replicates_n: Any = None,
    ocr_degrees_of_freedom: Any = None,
    ocr_uncertainty_provenance: Any = None,
    measured_ocr_u95_override: Any = None,
    require_explicit_model_for_positive_se: bool = False,
) -> Dict[str, Any]:
    """
    R14-B2 + R17-B2 Canonical NW-08 measured-OCR inferential uncertainty validator and upper-bound
    resolver (NIST §8.6 compliant). Rejects undeclared bare positive `uncertainty_se` without an
    explicit inferential model / degrees of freedom / independently justified upper bound, computes
    exact upward-enclosed one-sided 95% Student-t critical values for `STUDENT_T_ESTIMATED_SE`,
    strictly scopes the provably upper-enclosed normal quantile `z_{0.95} > Phi^{-1}(0.95)`
    (`MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95_DEC`, upward float64 `1.6448536269514729`) to declared
    `KNOWN_SIGMA_NORMAL` models with provenance, and rounds float64 upper OCR strictly upward.
    """
    # 1. Validate explicit z_one_sided_95 first whenever supplied (preserves R04-B5 / R12-B2 error codes)
    f_z95_sup: float | None = None
    dec_z95_sup: Decimal | None = None
    if z_one_sided_95 is not None:
        if _is_negative_zero(z_one_sided_95):
            raise ValueError(
                f"INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE:Require conservative one-sided >=95% "
                f"confidence quantile z_one_sided_95 >= {MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95_DEC}; got {z_one_sided_95!r}"
            )
        f_z95_sup, dec_z95_sup = _parse_nw08_boundary_scalar(
            z_one_sided_95, "z_one_sided_95", non_negative=False, strictly_positive=False
        )
        with _clean_dec_ctx(120, ROUND_HALF_EVEN):
            min_z95_dec = MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95_DEC
            float_undercuts_z95 = isinstance(z_one_sided_95, float) and (Decimal.from_float(f_z95_sup) < min_z95_dec)
            if dec_z95_sup < min_z95_dec or float_undercuts_z95:
                z_prefix = "INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE:" if dec_z95_sup <= Decimal(0) else ""
                raise ValueError(
                    f"{z_prefix}Require conservative one-sided >=95% confidence quantile "
                    f"z_one_sided_95 >= {MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95_DEC}; got {z_one_sided_95!r}"
                )

    # 2. Validate replicates_n and degrees_of_freedom strictly as positive integers (no bool/float/str)
    rep_n: int | None = None
    if ocr_replicates_n is not None:
        if (
            isinstance(ocr_replicates_n, bool)
            or not isinstance(ocr_replicates_n, int)
            or ocr_replicates_n < 2
            or ocr_replicates_n > MAX_NW08_STUDENT_T_DF + 1
        ):
            raise ValueError(
                f"HOLD_NW08_OCR_INVALID_REPLICATES_N:ocr_replicates_n must be int >= 2; got {ocr_replicates_n!r}"
            )
        rep_n = ocr_replicates_n

    df_sup: int | None = None
    if ocr_degrees_of_freedom is not None:
        if (
            isinstance(ocr_degrees_of_freedom, bool)
            or not isinstance(ocr_degrees_of_freedom, int)
            or ocr_degrees_of_freedom < 1
            or ocr_degrees_of_freedom > MAX_NW08_STUDENT_T_DF
        ):
            raise ValueError(
                f"HOLD_NW08_OCR_INVALID_DEGREES_OF_FREEDOM:ocr_degrees_of_freedom must be int >= 1; got {ocr_degrees_of_freedom!r}"
            )
        df_sup = ocr_degrees_of_freedom

    if rep_n is not None and df_sup is not None and df_sup > (rep_n - 1):
        raise ValueError(
            f"HOLD_NW08_OCR_INCONSISTENT_REPLICATES_AND_DF:ocr_degrees_of_freedom ({df_sup}) exceeds "
            f"ocr_replicates_n - 1 ({rep_n - 1})"
        )
    eff_df: int | None = df_sup if df_sup is not None else ((rep_n - 1) if rep_n is not None else None)

    # 3. Validate provenance string whenever supplied (clean, non-empty, zero placeholder tokens)
    prov_clean: str | None = None
    if ocr_uncertainty_provenance is not None:
        if (
            not _is_clean_nonempty_str(ocr_uncertainty_provenance)
            or _FORBIDDEN_ID_CHARS_RE.search(ocr_uncertainty_provenance)
            or _PLACEHOLDER_TOKEN_RE.search(ocr_uncertainty_provenance)
        ):
            raise ValueError(
                f"HOLD_NW08_OCR_INVALID_UNCERTAINTY_PROVENANCE:ocr_uncertainty_provenance must be a clean "
                f"non-placeholder string; got {ocr_uncertainty_provenance!r}"
            )
        prov_clean = ocr_uncertainty_provenance

    # 4. Validate measured_ocr_u95_override whenever supplied
    f_u95_ov: float | None = None
    dec_u95_ov: Decimal | None = None
    if measured_ocr_u95_override is not None:
        f_u95_ov, dec_u95_ov = _parse_nw08_boundary_scalar(
            measured_ocr_u95_override, "measured_ocr_u95_override", strictly_positive=True
        )

    # 5. Determine canonical inferential model (fail-closed on undeclared bare positive SE!)
    with _clean_dec_ctx(120, ROUND_HALF_EVEN):
        has_positive_se = bool(dec_uncertainty_se > Decimal(0))

    if ocr_uncertainty_model is not None:
        if not isinstance(ocr_uncertainty_model, str) or ocr_uncertainty_model not in NW08_ALLOWED_OCR_UNCERTAINTY_MODELS:
            raise ValueError(
                f"HOLD_NW08_OCR_INVALID_UNCERTAINTY_MODEL:Unrecognized ocr_uncertainty_model={ocr_uncertainty_model!r}; "
                f"expected one of {sorted(NW08_ALLOWED_OCR_UNCERTAINTY_MODELS)}"
            )
        eff_model = ocr_uncertainty_model
    elif (not has_positive_se) and (f_u95_ov is None) and (eff_df is None):
        eff_model = NW08_OCR_UNCERTAINTY_MODEL_ZERO_POINT
    elif require_explicit_model_for_positive_se:
        raise ValueError(
            "HOLD_NW08_OCR_MISSING_UNCERTAINTY_MODEL_OR_DF:NW-08 OCR records with uncertainty_se > 0 "
            "(or df/upper-bound specifications) require explicit ocr_uncertainty_model "
            "('STUDENT_T_ESTIMATED_SE', 'KNOWN_SIGMA_NORMAL', or 'INDEPENDENT_JUSTIFIED_UPPER_BOUND')"
        )
    elif f_u95_ov is not None:
        eff_model = NW08_OCR_UNCERTAINTY_MODEL_INDEPENDENT_UPPER
    elif eff_df is not None:
        eff_model = NW08_OCR_UNCERTAINTY_MODEL_STUDENT_T
    else:
        raise ValueError(
            "HOLD_NW08_OCR_MISSING_UNCERTAINTY_MODEL_OR_DF:Positive uncertainty_se requires explicit inferential "
            "model provenance: specify ocr_uncertainty_model='STUDENT_T_ESTIMATED_SE' with ocr_replicates_n>=2 "
            "or ocr_degrees_of_freedom>=1, 'KNOWN_SIGMA_NORMAL' with ocr_uncertainty_provenance, or "
            "'INDEPENDENT_JUSTIFIED_UPPER_BOUND' with measured_ocr_u95_override + ocr_uncertainty_provenance"
        )

    # 6. Resolve conservative upper bound under the validated inferential model
    normal_z_cov_at_df: float | None = (
        exact_student_t_cdf(MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95, eff_df) if eff_df is not None else None
    )
    req_min_mult: float | None = None
    req_min_mult_dec: Decimal | None = None
    applied_mult: float | None = None
    applied_mult_dec: Decimal | None = None
    assumptions_text: str

    if eff_model == NW08_OCR_UNCERTAINTY_MODEL_ZERO_POINT:
        if has_positive_se:
            raise ValueError(
                "HOLD_NW08_OCR_ZERO_MODEL_WITH_POSITIVE_SE:ZERO_UNCERTAINTY_DETERMINISTIC_POINT requires uncertainty_se == 0"
            )
        if f_u95_ov is not None:
            raise ValueError(
                "HOLD_NW08_OCR_UNEXPECTED_UPPER_BOUND_OVERRIDE:measured_ocr_u95_override is only valid with INDEPENDENT_JUSTIFIED_UPPER_BOUND"
            )
        ocr_u95_dec = dec_measured_ocr
        ocr_u95_f = _float64_round_up_from_fraction(Fraction(ocr_u95_dec))
        applied_mult = (
            _float64_round_up_from_fraction(Fraction(dec_z95_sup))
            if dec_z95_sup is not None
            else None
        )
        applied_mult_dec = dec_z95_sup
        assumptions_text = (
            "Deterministic point evaluation (uncertainty_se == 0); no sampling-error inflation applied."
        )
    elif eff_model == NW08_OCR_UNCERTAINTY_MODEL_STUDENT_T:
        if (not has_positive_se) or f_uncertainty_se <= 0.0:
            raise ValueError(
                f"{NW08_HOLD_TOKEN_INFERENTIAL_REQUIRES_POSITIVE_SE}:STUDENT_T_ESTIMATED_SE requires "
                f"strictly positive uncertainty_se > 0 (got uncertainty_se={f_uncertainty_se!r}); use "
                f"{NW08_OCR_UNCERTAINTY_MODEL_ZERO_POINT} for deterministic zero-SE point evaluation"
            )
        if f_u95_ov is not None:
            raise ValueError(
                "HOLD_NW08_OCR_UNEXPECTED_UPPER_BOUND_OVERRIDE:measured_ocr_u95_override is only valid with INDEPENDENT_JUSTIFIED_UPPER_BOUND"
            )
        if eff_df is None:
            raise ValueError(
                "HOLD_NW08_OCR_MISSING_DEGREES_OF_FREEDOM:STUDENT_T_ESTIMATED_SE requires ocr_replicates_n >= 2 or ocr_degrees_of_freedom >= 1"
            )
        t_crit = exact_student_t_one_sided_95(eff_df)
        with _clean_dec_ctx(120, ROUND_HALF_EVEN):
            t_crit_dec = max(Decimal.from_float(t_crit), Decimal(str(t_crit)))
        req_min_mult_dec = t_crit_dec
        req_min_mult = _float64_round_up_from_fraction(Fraction(t_crit_dec))
        if f_z95_sup is not None and dec_z95_sup is not None:
            with _clean_dec_ctx(120, ROUND_HALF_EVEN):
                f_undercut_t = isinstance(z_one_sided_95, float) and (Decimal.from_float(f_z95_sup) < t_crit_dec)
                if dec_z95_sup < t_crit_dec or f_undercut_t:
                    raise ValueError(
                        f"HOLD_NW08_OCR_MULTIPLIER_BELOW_STUDENT_T_CRITICAL:Require conservative one-sided >=95% "
                        f"Student-t quantile >= {t_crit:.7f} for df={eff_df}; got z_one_sided_95={z_one_sided_95!r}"
                    )
            eff_mult_dec = dec_z95_sup
            eff_mult_f = _float64_round_up_from_fraction(Fraction(eff_mult_dec))
        else:
            eff_mult_dec = t_crit_dec
            eff_mult_f = req_min_mult
        applied_mult = eff_mult_f
        applied_mult_dec = eff_mult_dec
        with _clean_dec_ctx(120, ROUND_CEILING):
            ocr_u95_dec = dec_measured_ocr + eff_mult_dec * dec_uncertainty_se
        ocr_u95_f = _float64_round_up_from_fraction(Fraction(ocr_u95_dec))
        assumptions_text = (
            f"Small-sample one-sided 95% Student-t upper confidence bound (df={eff_df}, "
            f"t_0.95={t_crit:.7f}; ordinary normal z=1.6448536 would achieve only "
            f"{100.0 * float(normal_z_cov_at_df):.4f}% repeated-sampling coverage at df={eff_df}) "
            f"assuming independent normal replicates with sample-estimated standard error."
        )
    elif eff_model == NW08_OCR_UNCERTAINTY_MODEL_KNOWN_SIGMA:
        if (not has_positive_se) or f_uncertainty_se <= 0.0:
            raise ValueError(
                f"{NW08_HOLD_TOKEN_INFERENTIAL_REQUIRES_POSITIVE_SE}:KNOWN_SIGMA_NORMAL requires "
                f"strictly positive uncertainty_se > 0 (got uncertainty_se={f_uncertainty_se!r}); use "
                f"{NW08_OCR_UNCERTAINTY_MODEL_ZERO_POINT} for deterministic zero-SE point evaluation"
            )
        if f_u95_ov is not None:
            raise ValueError(
                "HOLD_NW08_OCR_UNEXPECTED_UPPER_BOUND_OVERRIDE:measured_ocr_u95_override is only valid with INDEPENDENT_JUSTIFIED_UPPER_BOUND"
            )
        if df_sup is not None:
            raise ValueError(
                "HOLD_NW08_OCR_KNOWN_SIGMA_FORBIDS_SAMPLE_DF:KNOWN_SIGMA_NORMAL applies strictly to externally "
                "calibrated known population sigma, not sample-estimated df; use STUDENT_T_ESTIMATED_SE"
            )
        if prov_clean is None:
            raise ValueError(
                "HOLD_NW08_OCR_KNOWN_SIGMA_REQUIRES_PROVENANCE:KNOWN_SIGMA_NORMAL requires explicit "
                "ocr_uncertainty_provenance documenting external known-sigma calibration"
            )
        req_min_mult_dec = MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95_DEC
        req_min_mult = _float64_round_up_from_fraction(Fraction(req_min_mult_dec))
        eff_mult_dec = dec_z95_sup if dec_z95_sup is not None else req_min_mult_dec
        eff_mult_f = _float64_round_up_from_fraction(Fraction(eff_mult_dec))
        applied_mult = eff_mult_f
        applied_mult_dec = eff_mult_dec
        with _clean_dec_ctx(120, ROUND_CEILING):
            ocr_u95_dec = dec_measured_ocr + eff_mult_dec * dec_uncertainty_se
        ocr_u95_f = _float64_round_up_from_fraction(Fraction(ocr_u95_dec))
        assumptions_text = (
            "Normal one-sided >=95% upper bound (z >= 1.64485362695147271486..., upward float64 1.6448536269514729) "
            "strictly scoped to declared externally calibrated known-sigma normal measurement model "
            "(NOT applicable to small-sample estimated SE)."
        )
    else:  # NW08_OCR_UNCERTAINTY_MODEL_INDEPENDENT_UPPER
        if f_u95_ov is None or dec_u95_ov is None:
            raise ValueError(
                "HOLD_NW08_OCR_MISSING_INDEPENDENT_UPPER_BOUND:INDEPENDENT_JUSTIFIED_UPPER_BOUND requires measured_ocr_u95_override"
            )
        if prov_clean is None:
            raise ValueError(
                "HOLD_NW08_OCR_INDEPENDENT_UPPER_BOUND_REQUIRES_PROVENANCE:INDEPENDENT_JUSTIFIED_UPPER_BOUND "
                "requires explicit ocr_uncertainty_provenance documenting independent upper-bound derivation"
            )
        if eff_df is not None:
            _t_ind = exact_student_t_one_sided_95(eff_df)
            with _clean_dec_ctx(120, ROUND_HALF_EVEN):
                req_min_mult_dec = max(Decimal.from_float(_t_ind), Decimal(str(_t_ind)))
        else:
            req_min_mult_dec = MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95_DEC
        with _clean_dec_ctx(120, ROUND_HALF_EVEN):
            if dec_z95_sup is not None and dec_z95_sup > req_min_mult_dec:
                req_min_mult_dec = dec_z95_sup
        req_min_mult = _float64_round_up_from_fraction(Fraction(req_min_mult_dec))
        with _clean_dec_ctx(120, ROUND_CEILING):
            min_floor_u95_dec = dec_measured_ocr + req_min_mult_dec * dec_uncertainty_se
        with _clean_dec_ctx(120, ROUND_HALF_EVEN):
            if dec_u95_ov < dec_measured_ocr or dec_u95_ov < min_floor_u95_dec:
                raise ValueError(
                    f"HOLD_NW08_OCR_INDEPENDENT_UPPER_BOUND_UNDERCUTS_MODEL:measured_ocr_u95_override ({f_u95_ov}) "
                    f"is below conservative one-sided 95% floor ({float(min_floor_u95_dec):.7f} at multiplier {req_min_mult:.7f})"
                )
        ocr_u95_dec = dec_u95_ov
        ocr_u95_f = _float64_round_up_from_fraction(Fraction(ocr_u95_dec))
        applied_mult = ((f_u95_ov - f_measured_ocr) / f_uncertainty_se) if f_uncertainty_se > 0.0 else None
        if has_positive_se:
            with _clean_dec_ctx(120, ROUND_HALF_EVEN):
                applied_mult_dec = (dec_u95_ov - dec_measured_ocr) / dec_uncertainty_se
        assumptions_text = (
            "Caller-supplied independently justified conservative upper bound verified >= model minimum "
            f"(multiplier floor {req_min_mult:.7f}) with explicit provenance."
        )

    if not math.isfinite(ocr_u95_f) or ocr_u95_f <= 0.0:
        raise ValueError("Computed measured_ocr_u95 overflowed IEEE-754 float64 range")

    return {
        "ocr_u95_float": ocr_u95_f,
        "ocr_u95_dec": ocr_u95_dec,
        "ocr_uncertainty_model": eff_model,
        "ocr_replicates_n": rep_n,
        "ocr_degrees_of_freedom": eff_df,
        "ocr_uncertainty_provenance": prov_clean,
        "required_min_one_sided_95_multiplier": round(req_min_mult, 7) if req_min_mult is not None else None,
        "required_min_one_sided_95_multiplier_dec": str(req_min_mult_dec) if req_min_mult_dec is not None else None,
        "applied_one_sided_95_multiplier": round(applied_mult, 7) if applied_mult is not None else None,
        "applied_one_sided_95_multiplier_dec": str(applied_mult_dec) if applied_mult_dec is not None else None,
        "normal_z_repeated_sampling_coverage_at_df": (
            round(normal_z_cov_at_df, 6) if normal_z_cov_at_df is not None else None
        ),
        "ocr_uncertainty_assumptions": assumptions_text,
    }


def evaluate_nw08_measured_ocr_trigger(
    route_id: str,
    measured_ocr: float,
    uncertainty_se: float,
    *,
    baseline_min_face_mmhg: float,
    baseline_vasc_ocr_mult: float,
    p_bed_mmhg: float,
    local_3d_slope_mmhg_per_pct: float | None = None,
    z_one_sided_95: float | None = None,
    floor_mmhg: float = CANONICAL_NW08_PO2_FLOOR_MMHG,
    ocr_uncertainty_model: str | None = None,
    ocr_replicates_n: int | None = None,
    ocr_degrees_of_freedom: int | None = None,
    ocr_uncertainty_provenance: str | None = None,
    measured_ocr_u95_override: float | None = None,
    _require_explicit_model_for_positive_se: bool = False,
) -> Dict[str, Any]:
    """
    Executable NW-08 measured-OCR margin+uncertainty dispatch rule (replaces fixed +20% trigger).
    Computes one-sided >=95% upper bound on measured vascular OCR under an explicitly declared
    inferential model (exact Student-t for small-sample estimated SE, scoped known-sigma normal
    with provenance, or independently justified upper bound; R14-B2), projects oxygen drop
    conservatively via both linearized slab sensitivity and local 3D FVM slope (when supplied),
    compares STRICTLY against the immutable canonical `15.0 mmHg` floor (`baseline_min_face_mmhg - 15.0`)
    for all release triggering decisions, and reports any caller-supplied alternate `floor_mmhg`
    strictly in separate non-authorizing diagnostic fields.
    """
    if not isinstance(route_id, str) or not route_id.strip():
        raise ValueError(f"Unrecognized or non-string NW-08 route_id: {type(route_id).__name__}")
    route_upper = route_id.upper()
    if route_upper.startswith("R1"):
        operator_name = "verify_iip0033_bilayer_and_resp1.solve_route1_supercell_fixed_pitch"
    elif route_upper.startswith("R2"):
        operator_name = "run_layer4_tissue_and_metabolic_twin.compute_design_z_140um_parameterized_case"
    elif route_upper.startswith("R3P"):
        operator_name = "verify_iip0034_planar_and_portfolio.solve_planar_route3p_fvm"
    else:
        raise ValueError(f"Unrecognized NW-08 route_id: {route_id!r}")

    f_measured_ocr, dec_measured_ocr = _parse_nw08_boundary_scalar(
        measured_ocr, "measured_ocr", strictly_positive=True
    )
    f_uncertainty_se, dec_uncertainty_se = _parse_nw08_boundary_scalar(
        uncertainty_se, "uncertainty_se", non_negative=True
    )
    f_base_face, _dec_base_face = _parse_nw08_boundary_scalar(
        baseline_min_face_mmhg, "baseline_min_face_mmhg", non_negative=False
    )
    f_base_ocr, dec_base_ocr = _parse_nw08_boundary_scalar(
        baseline_vasc_ocr_mult, "baseline_vasc_ocr_mult", strictly_positive=True
    )
    f_p_bed, dec_p_bed = _parse_nw08_boundary_scalar(
        p_bed_mmhg, "p_bed_mmhg", strictly_positive=True
    )
    diag_floor, dec_diag_floor = _parse_nw08_boundary_scalar(
        floor_mmhg, "floor_mmhg", strictly_positive=True
    )
    f_local_slope: float | None = None
    if local_3d_slope_mmhg_per_pct is not None:
        f_local_slope, _dec_slope = _parse_nw08_boundary_scalar(
            local_3d_slope_mmhg_per_pct, "local_3d_slope_mmhg_per_pct", non_negative=True
        )
    unc_info = _resolve_nw08_ocr_uncertainty_bound(
        f_measured_ocr=f_measured_ocr,
        dec_measured_ocr=dec_measured_ocr,
        f_uncertainty_se=f_uncertainty_se,
        dec_uncertainty_se=dec_uncertainty_se,
        z_one_sided_95=z_one_sided_95,
        ocr_uncertainty_model=ocr_uncertainty_model,
        ocr_replicates_n=ocr_replicates_n,
        ocr_degrees_of_freedom=ocr_degrees_of_freedom,
        ocr_uncertainty_provenance=ocr_uncertainty_provenance,
        measured_ocr_u95_override=measured_ocr_u95_override,
        require_explicit_model_for_positive_se=_require_explicit_model_for_positive_se,
    )
    with _clean_dec_ctx(120, ROUND_HALF_EVEN):
        canon_floor_dec = Decimal(str(CANONICAL_NW08_PO2_FLOOR_MMHG))
        if (
            dec_p_bed <= canon_floor_dec
            or dec_p_bed <= dec_diag_floor
            or f_p_bed <= CANONICAL_NW08_PO2_FLOOR_MMHG
            or f_p_bed <= diag_floor
        ):
            raise ValueError(
                f"Require measured_ocr > 0, uncertainty_se >= 0, baseline_vasc_ocr_mult > 0, "
                f"and p_bed_mmhg > max(canonical {CANONICAL_NW08_PO2_FLOOR_MMHG}, floor_mmhg {diag_floor})"
            )

    ocr_u95 = unc_info["ocr_u95_float"]
    ocr_u95_exact = unc_info["ocr_u95_dec"]
    delta_vasc_pct_point = max(0.0, ((f_measured_ocr / f_base_ocr) - 1.0) * 100.0)
    if Fraction(ocr_u95_exact) <= Fraction(dec_base_ocr):
        delta_vasc_pct_u95 = 0.0
    else:
        delta_vasc_pct_u95 = _float64_round_up_from_fraction(
            ((Fraction(ocr_u95_exact) / Fraction(dec_base_ocr)) - Fraction(1)) * Fraction(100)
        )
    if not (math.isfinite(delta_vasc_pct_point) and math.isfinite(delta_vasc_pct_u95)):
        raise ValueError("Computed vascular OCR delta overflowed IEEE-754 float64 range")

    # Canonical release trigger ALWAYS enforces CANONICAL_NW08_PO2_FLOOR_MMHG = 15.0 mmHg!
    # R08-B2: Scale the 1D linearized vascular OCR share monotonically with baseline_vasc_ocr_mult
    # (never understating vascular share at elevated baseline_vasc_ocr_mult > 1.0), AND explicitly
    # mark this screen as non-authorizing: ONLY the live native 3D FVM solver in
    # `dispatch_and_solve_nw08_measured_ocr` may authorize release PASS whenever
    # `ocr_u95 > baseline_vasc_ocr_mult` or any non-canonical parameter override is active!
    baseline_margin_raw = f_base_face - CANONICAL_NW08_PO2_FLOOR_MMHG
    eff_vasc_share = max(
        0.15 / 1.15,
        (0.15 * f_base_ocr) / (1.0 + 0.15 * f_base_ocr),
    )
    lin_slope_per_pct = max(0.0, (f_p_bed - f_base_face) * eff_vasc_share / 100.0)
    pred_drop_linear_u95 = delta_vasc_pct_u95 * lin_slope_per_pct
    pred_drop_3d_u95 = (
        delta_vasc_pct_u95 * f_local_slope
        if f_local_slope is not None and f_local_slope > 0.0
        else None
    )
    if not math.isfinite(pred_drop_linear_u95) or (pred_drop_3d_u95 is not None and not math.isfinite(pred_drop_3d_u95)):
        raise ValueError("Computed predicted oxygen drop overflowed IEEE-754 float64 range")

    already_below_floor = not _passes_unrounded_15mmhg_floor(f_base_face)
    triggered_by_linear = bool(already_below_floor or baseline_margin_raw <= pred_drop_linear_u95)
    triggered_by_3d_slope = bool(
        already_below_floor or (pred_drop_3d_u95 is not None and baseline_margin_raw <= pred_drop_3d_u95)
    )
    triggered = bool(triggered_by_linear or triggered_by_3d_slope)
    base_far_from_floor = bool(f_base_face >= (CANONICAL_NW08_PO2_FLOOR_MMHG + NW08_MESH_CONVERGENCE_TRIGGER_BAND_MMHG))
    with _clean_dec_ctx(120, ROUND_CEILING):
        within_monotone_no_increase = bool(
            (not already_below_floor)
            and base_far_from_floor
            and (ocr_u95_exact <= dec_base_ocr)
        )

    # Non-authorizing diagnostic custom-floor screen (strictly informational; NEVER alters canonical trigger!)
    diag_margin_raw = f_base_face - diag_floor
    diag_already_below = not _passes_unrounded_diagnostic_floor(f_base_face, diag_floor)
    diag_triggered = bool(
        diag_already_below
        or diag_margin_raw <= pred_drop_linear_u95
        or (pred_drop_3d_u95 is not None and diag_margin_raw <= pred_drop_3d_u95)
    )
    return {
        "route_id": route_id,
        "route_specific_3d_fvm_operator": operator_name,
        "screening_mode": "PRELIMINARY_NON_AUTHORIZING_TRIGGER_SCREEN",
        "release_authorizing": False,
        "measured_ocr": f_measured_ocr,
        "uncertainty_se": f_uncertainty_se,
        "measured_ocr_u95": round(ocr_u95, 6),
        "measured_ocr_u95_exact_dec": format(ocr_u95_exact, "f"),
        "measured_ocr_u95_unrounded_float64": ocr_u95,
        "ocr_uncertainty_model": unc_info["ocr_uncertainty_model"],
        "ocr_replicates_n": unc_info["ocr_replicates_n"],
        "ocr_degrees_of_freedom": unc_info["ocr_degrees_of_freedom"],
        "ocr_uncertainty_provenance": unc_info["ocr_uncertainty_provenance"],
        "required_min_one_sided_95_multiplier": unc_info["required_min_one_sided_95_multiplier"],
        "applied_one_sided_95_multiplier": unc_info["applied_one_sided_95_multiplier"],
        "normal_z_repeated_sampling_coverage_at_df": unc_info["normal_z_repeated_sampling_coverage_at_df"],
        "ocr_uncertainty_assumptions": unc_info["ocr_uncertainty_assumptions"],
        "delta_vasc_pct_point": round(delta_vasc_pct_point, 4),
        "delta_vasc_pct_u95": round(delta_vasc_pct_u95, 4),
        "delta_vasc_pct_u95_unrounded_float64": delta_vasc_pct_u95,
        "effective_vascular_ocr_share_screen": round(eff_vasc_share, 6),
        "canonical_floor_mmhg": CANONICAL_NW08_PO2_FLOOR_MMHG,
        "baseline_min_face_unrounded_mmhg": f_base_face,
        "baseline_margin_unrounded_mmhg": baseline_margin_raw,
        "predicted_drop_linear_u95_mmhg": round(pred_drop_linear_u95, 6),
        "predicted_drop_3d_local_slope_u95_mmhg": round(pred_drop_3d_u95, 6) if pred_drop_3d_u95 is not None else None,
        "triggered_by_linear_screen": triggered_by_linear,
        "triggered_by_3d_local_slope": triggered_by_3d_slope,
        "within_provably_monotone_no_increase_domain": within_monotone_no_increase,
        "candidate_3d_solve_required_for_release_pass": bool(triggered or (not within_monotone_no_increase)),
        "trigger_dispatched": triggered,
        "decision": (
            "TRIGGER_3D_FVM_RESOLVE_AND_PRECOMMITTED_DERATING_CHECK"
            if triggered
            else "PRELIMINARY_SCREEN_WITHIN_LINEAR_MARGIN_3D_SOLVE_REQUIRED_IF_OCR_INCREASED"
        ),
        "diagnostic_custom_floor_mmhg": diag_floor,
        "diagnostic_custom_floor_applied": bool(diag_floor != CANONICAL_NW08_PO2_FLOOR_MMHG),
        "diagnostic_trigger_dispatched_at_custom_floor": diag_triggered,
    }


def run_nw08_trigger_and_floor_unit_tests() -> Dict[str, Any]:
    """Unit tests proving unrounded 15.0 mmHg floor gating & executable NW-08 measured-OCR trigger."""
    tests: List[Dict[str, Any]] = []

    # 1. Near-boundary false-pass witness: 14.999959999870875 formats to 15.0000 but MUST FAIL!
    near_floor_val = 14.999959999870875
    near_floor_pass = _passes_unrounded_15mmhg_floor(near_floor_val, 15.0)
    tests.append({
        "test": "unrounded_floor_rejects_14p999959999870875_despite_15p0000_display",
        "raw_value": near_floor_val,
        "display_4dp": f"{near_floor_val:.4f}",
        "unrounded_passed": near_floor_pass,
        "passed": bool((f"{near_floor_val:.4f}" == "15.0000") and (near_floor_pass is False)),
    })

    # 2. Exact 15.0 mmHg boundary passes unrounded check
    tests.append({
        "test": "unrounded_floor_accepts_exact_15p0",
        "raw_value": 15.0,
        "unrounded_passed": _passes_unrounded_15mmhg_floor(15.0, 15.0),
        "passed": bool(_passes_unrounded_15mmhg_floor(15.0, 15.0) is True),
    })

    # 3. R1 350 um stress (baseline raw 15.039395902009547, base OCR 1.2067): exact linear breach is +1.5132%
    #    (displays as +1.51%); verify +1.5132% (SE=0) AND +1.51% with tiny SE=0.001 BOTH dispatch!
    r1_350_base = 15.039395902009547
    r1_350_ocr = 1.2067
    r1_350_slope_3d = (r1_350_base - 14.8446244044785) / (((1.3164 / 1.2067) - 1.0) * 100.0)
    t_151_exact = evaluate_nw08_measured_ocr_trigger(
        "R1_350_stress",
        r1_350_ocr * 1.01514,
        0.0,
        baseline_min_face_mmhg=r1_350_base,
        baseline_vasc_ocr_mult=r1_350_ocr,
        p_bed_mmhg=35.0,
        local_3d_slope_mmhg_per_pct=r1_350_slope_3d,
    )
    t_151_se = evaluate_nw08_measured_ocr_trigger(
        "R1_350_stress",
        r1_350_ocr * 1.0151,
        0.001,
        baseline_min_face_mmhg=r1_350_base,
        baseline_vasc_ocr_mult=r1_350_ocr,
        p_bed_mmhg=35.0,
        local_3d_slope_mmhg_per_pct=r1_350_slope_3d,
        ocr_uncertainty_model=NW08_OCR_UNCERTAINTY_MODEL_KNOWN_SIGMA,
        ocr_uncertainty_provenance="unit_test_calibrated_known_sigma_v1",
    )
    tests.append({
        "test": "nw08_trigger_r1_350_fires_at_plus_1p51pct_linear_threshold",
        "trigger_at_1p514_se0": t_151_exact["trigger_dispatched"],
        "trigger_at_1p51_se0p001": t_151_se["trigger_dispatched"],
        "triggered_by_linear_screen": t_151_exact["triggered_by_linear_screen"],
        "operator": t_151_exact["route_specific_3d_fvm_operator"],
        "passed": bool(
            t_151_exact["trigger_dispatched"] is True
            and t_151_exact["triggered_by_linear_screen"] is True
            and t_151_se["trigger_dispatched"] is True
            and "solve_route1_supercell_fixed_pitch" in t_151_exact["route_specific_3d_fvm_operator"]
        ),
    })

    # 4. R1 350 um stress triggers at +1.84% via BOTH linear screen AND 3D local slope!
    t_184 = evaluate_nw08_measured_ocr_trigger(
        "R1_350_stress",
        r1_350_ocr * 1.0184,
        0.0,
        baseline_min_face_mmhg=r1_350_base,
        baseline_vasc_ocr_mult=r1_350_ocr,
        p_bed_mmhg=35.0,
        local_3d_slope_mmhg_per_pct=r1_350_slope_3d,
    )
    tests.append({
        "test": "nw08_trigger_r1_350_fires_at_plus_1p84_pct_linear_and_3d_slope",
        "trigger_dispatched": t_184["trigger_dispatched"],
        "triggered_by_3d_local_slope": t_184["triggered_by_3d_local_slope"],
        "passed": bool(t_184["trigger_dispatched"] is True and t_184["triggered_by_3d_local_slope"] is True),
    })

    # 5. Measurement uncertainty (SE) elevates sub-threshold +0.50% point estimate to trigger!
    t_low_no_se = evaluate_nw08_measured_ocr_trigger(
        "R1_350_stress",
        r1_350_ocr * 1.005,
        0.0,
        baseline_min_face_mmhg=r1_350_base,
        baseline_vasc_ocr_mult=r1_350_ocr,
        p_bed_mmhg=35.0,
        local_3d_slope_mmhg_per_pct=r1_350_slope_3d,
    )
    t_low_with_se = evaluate_nw08_measured_ocr_trigger(
        "R1_350_stress",
        r1_350_ocr * 1.005,
        0.015,
        baseline_min_face_mmhg=r1_350_base,
        baseline_vasc_ocr_mult=r1_350_ocr,
        p_bed_mmhg=35.0,
        local_3d_slope_mmhg_per_pct=r1_350_slope_3d,
        ocr_uncertainty_model=NW08_OCR_UNCERTAINTY_MODEL_STUDENT_T,
        ocr_replicates_n=6,
    )
    tests.append({
        "test": "nw08_trigger_r1_350_measurement_se_escalates_plus_0p50pct_to_trigger",
        "no_se_triggered": t_low_no_se["trigger_dispatched"],
        "with_se_triggered": t_low_with_se["trigger_dispatched"],
        "passed": bool(t_low_no_se["trigger_dispatched"] is False and t_low_with_se["trigger_dispatched"] is True),
    })

    # 6. Nominal R1 390 um at +20% (1.3164, SE=0.02) stays comfortably within margin (no premature derating!)
    t_nom = evaluate_nw08_measured_ocr_trigger(
        "R1_390_nominal",
        1.3164,
        0.02,
        baseline_min_face_mmhg=17.299735976843305,
        baseline_vasc_ocr_mult=1.097,
        p_bed_mmhg=35.0,
        local_3d_slope_mmhg_per_pct=0.0186,
        ocr_uncertainty_model=NW08_OCR_UNCERTAINTY_MODEL_STUDENT_T,
        ocr_replicates_n=6,
    )
    tests.append({
        "test": "nw08_trigger_r1_390_nominal_does_not_derate_at_1p3164",
        "trigger_dispatched": t_nom["trigger_dispatched"],
        "passed": bool(t_nom["trigger_dispatched"] is False),
    })

    # 7. Already-below-floor corner (R3P Bed30 KRBH = 14.4198 < 15.0) immediately triggers at 0% perturbation
    t_krbh = evaluate_nw08_measured_ocr_trigger(
        "R3P_30_KRBH",
        1.097,
        0.0,
        baseline_min_face_mmhg=14.419817781758784,
        baseline_vasc_ocr_mult=1.097,
        p_bed_mmhg=30.0,
    )
    tests.append({
        "test": "nw08_trigger_r3p_bed30_krbh_immediate_dispatch_below_floor",
        "trigger_dispatched": t_krbh["trigger_dispatched"],
        "operator": t_krbh["route_specific_3d_fvm_operator"],
        "passed": bool(
            t_krbh["trigger_dispatched"] is True
            and "solve_planar_route3p_fvm" in t_krbh["route_specific_3d_fvm_operator"]
        ),
    })

    # 8. R04-B5 + R17-B2: Reject non-conservative quantiles (z <= 0 or z < exact Phi^{-1}(0.95),
    #    including the old float64 under-covering 1.6448536269514722 and 1.6448536269514726) fail-closed!
    rejected_bad_z: Dict[str, bool] = {}
    for z_label, z_bad in (
        ("neg_1p6449", -1.6448536269514729),
        ("zero", 0.0),
        ("sub_95_1p6448", 1.6448),
        ("r17_b2_old_undercovering_1p6448536269514722", 1.6448536269514722),
        ("r17_b2_sub_exact_1p6448536269514726", 1.6448536269514726),
    ):
        raised = False
        try:
            evaluate_nw08_measured_ocr_trigger(
                "R1_390_stress",
                1.44804,
                0.08,
                baseline_min_face_mmhg=15.261956,
                baseline_vasc_ocr_mult=1.2067,
                p_bed_mmhg=35.0,
                z_one_sided_95=z_bad,
            )
        except ValueError:
            raised = True
        rejected_bad_z[z_label] = raised
    tests.append({
        "test": "r04_b5_nw08_trigger_rejects_negative_zero_and_sub95_z_quantiles",
        "rejected_bad_z": rejected_bad_z,
        "passed": all(rejected_bad_z.values()),
    })

    # 9. R05-B2: Lowering diagnostic floor_mmhg (e.g. 14.0) NEVER suppresses canonical 15.0 mmHg
    #    trigger dispatch, and _passes_unrounded_15mmhg_floor rejects non-15.0 floor overrides!
    t_diag14 = evaluate_nw08_measured_ocr_trigger(
        "R3P_30",
        1.3164,
        0.0,
        baseline_min_face_mmhg=15.2152,
        baseline_vasc_ocr_mult=1.097,
        p_bed_mmhg=30.0,
        floor_mmhg=14.0,
    )
    non15_floor_rejected = False
    try:
        _passes_unrounded_15mmhg_floor(14.906233358064961, 14.0)
    except ValueError:
        non15_floor_rejected = True
    tests.append({
        "test": "r05_b2_nw08_trigger_canonical_15mmhg_floor_immutable_under_diagnostic_14mmhg",
        "canonical_floor_mmhg": t_diag14["canonical_floor_mmhg"],
        "trigger_dispatched": t_diag14["trigger_dispatched"],
        "diagnostic_custom_floor_mmhg": t_diag14["diagnostic_custom_floor_mmhg"],
        "diagnostic_trigger_dispatched_at_custom_floor": t_diag14["diagnostic_trigger_dispatched_at_custom_floor"],
        "non15_canonical_predicate_rejected": non15_floor_rejected,
        "passed": bool(
            t_diag14["canonical_floor_mmhg"] == 15.0
            and t_diag14["trigger_dispatched"] is True
            and t_diag14["diagnostic_custom_floor_mmhg"] == 14.0
            and t_diag14["diagnostic_trigger_dispatched_at_custom_floor"] is False
            and non15_floor_rejected is True
        ),
    })

    # 10. R08-B2: Elevated baseline_vasc_ocr_mult (5.0 -> 10.0 at p_bed=40.0) and near-floor
    #     Route-2 override (2.0 -> 2.0997527523 at p_bed=32.0) BOTH fire the baseline-scaled
    #     preliminary screen AND require candidate 3D FVM solve for release PASS!
    t_r08_near = evaluate_nw08_measured_ocr_trigger(
        "R2_DZ40",
        2.099752752324571,
        0.0,
        baseline_min_face_mmhg=15.110983261117214,
        baseline_vasc_ocr_mult=2.0,
        p_bed_mmhg=32.0,
    )
    t_r08_ov5 = evaluate_nw08_measured_ocr_trigger(
        "R2_DZ40",
        10.0,
        0.0,
        baseline_min_face_mmhg=19.19079251185101,
        baseline_vasc_ocr_mult=5.0,
        p_bed_mmhg=40.0,
    )
    tests.append({
        "test": "r08_b2_trigger_fires_on_elevated_baseline_overrides_and_marks_non_authorizing",
        "near_floor_triggered": t_r08_near["trigger_dispatched"],
        "override_5to10_triggered": t_r08_ov5["trigger_dispatched"],
        "near_floor_requires_3d": t_r08_near["candidate_3d_solve_required_for_release_pass"],
        "override_5to10_requires_3d": t_r08_ov5["candidate_3d_solve_required_for_release_pass"],
        "passed": bool(
            t_r08_near["trigger_dispatched"] is True
            and t_r08_ov5["trigger_dispatched"] is True
            and t_r08_near["release_authorizing"] is False
            and t_r08_ov5["release_authorizing"] is False
            and t_r08_near["candidate_3d_solve_required_for_release_pass"] is True
            and t_r08_ov5["candidate_3d_solve_required_for_release_pass"] is True
        ),
    })

    # 11. R08-B2: Even when nominal linear screen does not fire (R1_390_nominal 1.3164 > 1.097),
    #     candidate_3d_solve_required_for_release_pass is True because ocr_u95 > baseline_vasc_ocr_mult,
    #     whereas zero-increase (ocr_u95 <= 1.097 on >=15.0 baseline) is within the provably monotone domain!
    t_r08_zero = evaluate_nw08_measured_ocr_trigger(
        "R1_390_nominal",
        1.097,
        0.0,
        baseline_min_face_mmhg=17.299735976843305,
        baseline_vasc_ocr_mult=1.097,
        p_bed_mmhg=35.0,
    )
    tests.append({
        "test": "r08_b2_positive_ocr_shift_requires_3d_solve_while_zero_increase_is_monotone",
        "nominal_plus20_requires_3d": t_nom["candidate_3d_solve_required_for_release_pass"],
        "zero_increase_monotone": t_r08_zero["within_provably_monotone_no_increase_domain"],
        "zero_increase_requires_3d": t_r08_zero["candidate_3d_solve_required_for_release_pass"],
        "passed": bool(
            t_nom["candidate_3d_solve_required_for_release_pass"] is True
            and t_nom["within_provably_monotone_no_increase_domain"] is False
            and t_r08_zero["within_provably_monotone_no_increase_domain"] is True
            and t_r08_zero["candidate_3d_solve_required_for_release_pass"] is False
        ),
    })

    # 12. R14-B2: Exact one-sided 95% Student-t inference for small-sample OCR (n=6 -> df=5, t=2.0150484,
    #     normal-z coverage = 91.9540%), bare undeclared SE rejected fail-closed, KNOWN_SIGMA_NORMAL scoped
    #     strictly to explicit provenance without sample df, and INDEPENDENT_JUSTIFIED_UPPER_BOUND validated!
    t5_crit = exact_student_t_one_sided_95(5)
    cov_z_df5 = exact_student_t_cdf(MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95, 5)
    t_df5_trig = evaluate_nw08_measured_ocr_trigger(
        "R1_390_stress",
        1.25,
        0.06,
        baseline_min_face_mmhg=15.261956,
        baseline_vasc_ocr_mult=1.2067,
        p_bed_mmhg=35.0,
        ocr_uncertainty_model=NW08_OCR_UNCERTAINTY_MODEL_STUDENT_T,
        ocr_replicates_n=6,
    )
    t_indep_ok = evaluate_nw08_measured_ocr_trigger(
        "R1_390_stress",
        1.25,
        0.06,
        baseline_min_face_mmhg=15.261956,
        baseline_vasc_ocr_mult=1.2067,
        p_bed_mmhg=35.0,
        ocr_uncertainty_model=NW08_OCR_UNCERTAINTY_MODEL_INDEPENDENT_UPPER,
        ocr_replicates_n=6,
        measured_ocr_u95_override=1.370903,
        ocr_uncertainty_provenance="independent_student_t_df5_upper_95_bound_v1",
    )
    r14_b2_rejects: Dict[str, bool] = {}
    for rej_tag, rej_kwargs in (
        ("bare_se_no_model", {}),
        ("known_sigma_no_provenance", {"ocr_uncertainty_model": NW08_OCR_UNCERTAINTY_MODEL_KNOWN_SIGMA}),
        (
            "known_sigma_with_df",
            {
                "ocr_uncertainty_model": NW08_OCR_UNCERTAINTY_MODEL_KNOWN_SIGMA,
                "ocr_uncertainty_provenance": "cal_sigma_v1",
                "ocr_degrees_of_freedom": 5,
            },
        ),
        (
            "student_t_undercut_by_normal_z",
            {
                "ocr_uncertainty_model": NW08_OCR_UNCERTAINTY_MODEL_STUDENT_T,
                "ocr_replicates_n": 6,
                "z_one_sided_95": MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95,
            },
        ),
        (
            "independent_bound_undercuts_df5",
            {
                "ocr_uncertainty_model": NW08_OCR_UNCERTAINTY_MODEL_INDEPENDENT_UPPER,
                "ocr_replicates_n": 6,
                "measured_ocr_u95_override": 1.348691,
                "ocr_uncertainty_provenance": "under_conservative_normal_bound",
            },
        ),
    ):
        rej_raised = False
        try:
            evaluate_nw08_measured_ocr_trigger(
                "R1_390_stress",
                1.25,
                0.06,
                baseline_min_face_mmhg=15.261956,
                baseline_vasc_ocr_mult=1.2067,
                p_bed_mmhg=35.0,
                **rej_kwargs,
            )
        except ValueError:
            rej_raised = True
        r14_b2_rejects[rej_tag] = rej_raised
    tests.append({
        "test": "r14_b2_student_t_small_sample_n6_exact_quantile_and_rejects_bare_se",
        "student_t_0p95_df5": round(t5_crit, 7),
        "normal_z_coverage_at_df5": round(cov_z_df5, 6),
        "student_t_n6_ocr_u95": t_df5_trig["measured_ocr_u95"],
        "independent_upper_bound_ocr_u95": t_indep_ok["measured_ocr_u95"],
        "rejections": r14_b2_rejects,
        "passed": bool(
            abs(t5_crit - 2.015048373333021) < 1e-11
            and abs(cov_z_df5 - 0.9195401268717253) < 1e-9
            and t_df5_trig["ocr_uncertainty_model"] == NW08_OCR_UNCERTAINTY_MODEL_STUDENT_T
            and t_df5_trig["ocr_degrees_of_freedom"] == 5
            and abs(t_df5_trig["measured_ocr_u95"] - 1.370903) <= 1e-6
            and abs(t_indep_ok["measured_ocr_u95"] - 1.370903) <= 1e-6
            and all(r14_b2_rejects.values())
        ),
    })

    # 13. R15-B2: Slow / sub-asymptotic / non-positive / extreme super-convergent / accelerating-toward-floor
    #     mesh convergence sequences MUST NEVER clamp p_obs UP to 0.5 and MUST route fail-closed to HOLD
    #     (`HOLD_NW08_MESH_CONVERGENCE_UNQUALIFIED_SLOW_OR_NON_ASYMPTOTIC_ORDER`, `interval_valid=False`,
    #     no claimed clearance bound)! Includes exact synthetic power-law counterexample (f(n) = 14.95 +
    #     0.06*(96/n)**0.06 -> 15.012547946, 15.011044645, 15.010000000 on R2 [48, 72, 96], true limit 14.95).
    r2_std_ladder = (("coarse", 48, 28), ("medium", 72, 42), ("fine", 96, 56))
    slow_f3, slow_f2, slow_f1 = 15.012547946, 15.011044645, 15.010000000
    m_slow = _adjudicate_nw08_three_grid_convergence(slow_f3, slow_f2, slow_f1, r2_std_ladder)
    m_nonpos = _adjudicate_nw08_three_grid_convergence(15.012, 15.011, 15.0102, r2_std_ladder)
    m_super = _adjudicate_nw08_three_grid_convergence(15.10, 15.01001, 15.01000, r2_std_ladder)
    m_accel_down = _adjudicate_nw08_three_grid_convergence(15.50, 15.49, 15.30, r2_std_ladder)
    ok_13 = bool(
        m_slow["verdict_from_mesh_policy"] == "HOLD"
        and m_slow["mesh_convergence_resolved"] is False
        and m_slow["interval_valid"] is False
        and m_slow["order_qualified"] is False
        and m_slow["convergence_regime"] == "MONOTONE_SUB_ASYMPTOTIC_SLOW_ORDER_HOLD"
        and m_slow["hold_reason_token"] == NW08_HOLD_TOKEN_UNQUALIFIED_ORDER
        and m_slow["conservative_po2_lower_bound_mmhg"] is None
        and m_slow["conservative_po2_upper_bound_mmhg"] is None
        and m_slow["discretization_uncertainty_mmhg"] is None
        and m_slow["richardson_extrapolated_mmhg"] is None
        and m_slow["apparent_order_p"] is not None
        and abs(m_slow["apparent_order_p"] - 0.06) < 1e-4
        and m_slow["apparent_order_p"] < 0.5
        and m_nonpos["verdict_from_mesh_policy"] == "HOLD"
        and m_nonpos["hold_reason_token"] == NW08_HOLD_TOKEN_UNQUALIFIED_ORDER
        and m_nonpos["interval_valid"] is False
        and m_super["verdict_from_mesh_policy"] == "HOLD"
        and m_super["hold_reason_token"] == NW08_HOLD_TOKEN_UNQUALIFIED_ORDER
        and m_super["interval_valid"] is False
        and m_accel_down["verdict_from_mesh_policy"] == "HOLD"
        and m_accel_down["hold_reason_token"] == NW08_HOLD_TOKEN_UNQUALIFIED_ORDER
        and m_accel_down["interval_valid"] is False
    )
    tests.append({
        "test": "r15_b2_slow_sub_asymptotic_order_p0p06_and_unqualified_orders_route_to_hold_never_clamp_p_up",
        "slow_counterexample_grid_values": [slow_f3, slow_f2, slow_f1],
        "slow_counterexample_true_limit_mmhg": 14.95,
        "slow_counterexample_observed_order_p": m_slow["apparent_order_p"],
        "slow_counterexample_regime": m_slow["convergence_regime"],
        "slow_counterexample_verdict": m_slow["verdict_from_mesh_policy"],
        "slow_counterexample_hold_token": m_slow["hold_reason_token"],
        "slow_counterexample_interval_valid": m_slow["interval_valid"],
        "slow_counterexample_lower_bound_mmhg": m_slow["conservative_po2_lower_bound_mmhg"],
        "nonpositive_order_verdict": m_nonpos["verdict_from_mesh_policy"],
        "extreme_superconvergent_verdict": m_super["verdict_from_mesh_policy"],
        "accelerating_toward_floor_verdict": m_accel_down["verdict_from_mesh_policy"],
        "passed": ok_13,
    })

    # 14. R15-B2: Independently established asymptotic order acceptance controls on R2 [48, 72, 96]:
    #     (a) p = 1.5 exact limit 15.05 > 15.0 -> qualified Roache GCI lower bound 15.04 >= 15.0 -> PASS!
    #     (b) mild super-convergence p = 2.2 capped conservatively DOWN to formal order 2.0 -> PASS!
    #     (c) p = 1.5 exact limit 14.99 < 15.0 (fine grid 15.03 > 15.0) -> GCI straddles 15.0 -> HOLD!
    #     (d) p = 1.5 exact limit 14.90 < 15.0 (all grids < 15.0) -> GCI upper bound < 15.0 -> FAIL!
    acc_p15 = [15.05 + 0.04 * ((96.0 / n) ** 1.5) for n in (48, 72, 96)]
    m_acc_pass = _adjudicate_nw08_three_grid_convergence(acc_p15[0], acc_p15[1], acc_p15[2], r2_std_ladder)
    acc_p22 = [15.05 + 0.04 * ((96.0 / n) ** 2.2) for n in (48, 72, 96)]
    m_acc_cap2 = _adjudicate_nw08_three_grid_convergence(acc_p22[0], acc_p22[1], acc_p22[2], r2_std_ladder)
    acc_straddle = [14.99 + 0.04 * ((96.0 / n) ** 1.5) for n in (48, 72, 96)]
    m_acc_hold = _adjudicate_nw08_three_grid_convergence(acc_straddle[0], acc_straddle[1], acc_straddle[2], r2_std_ladder)
    acc_fail = [14.90 + 0.02 * ((96.0 / n) ** 1.5) for n in (48, 72, 96)]
    m_acc_fail = _adjudicate_nw08_three_grid_convergence(acc_fail[0], acc_fail[1], acc_fail[2], r2_std_ladder)
    ok_14 = bool(
        m_acc_pass["verdict_from_mesh_policy"] == "PASS"
        and m_acc_pass["mesh_convergence_resolved"] is True
        and m_acc_pass["interval_valid"] is True
        and m_acc_pass["order_qualified"] is True
        and m_acc_pass["convergence_regime"] == "MONOTONE_CONVERGING_GCI"
        and abs(float(m_acc_pass["apparent_order_p"]) - 1.5) < 1e-5
        and abs(float(m_acc_pass["richardson_extrapolated_mmhg"]) - 15.05) < 1e-6
        and abs(float(m_acc_pass["conservative_po2_lower_bound_mmhg"]) - 15.04) < 1e-6
        and m_acc_cap2["verdict_from_mesh_policy"] == "PASS"
        and m_acc_cap2["convergence_regime"] == "MONOTONE_CONVERGING_GCI_FORMAL_ORDER_CAPPED"
        and abs(float(m_acc_cap2["observed_order_p_raw"]) - 2.2) < 1e-5
        and float(m_acc_cap2["apparent_order_p"]) == 2.0
        and m_acc_cap2["interval_valid"] is True
        and float(m_acc_cap2["conservative_po2_lower_bound_mmhg"]) >= 15.0
        and m_acc_hold["verdict_from_mesh_policy"] == "HOLD"
        and m_acc_hold["hold_reason_token"] == NW08_HOLD_TOKEN_STRADDLES_FLOOR
        and m_acc_hold["straddles_canonical_15mmhg_floor"] is True
        and abs(float(m_acc_hold["conservative_po2_lower_bound_mmhg"]) - 14.98) < 1e-6
        and m_acc_fail["verdict_from_mesh_policy"] == "FAIL"
        and m_acc_fail["interval_valid"] is True
        and float(m_acc_fail["conservative_po2_upper_bound_mmhg"]) < 15.0
    )
    tests.append({
        "test": "r15_b2_asymptotic_order_p1p5_and_capped_p2p2_acceptance_controls_pass_hold_fail",
        "p1p5_pass_grid_values": [round(x, 9) for x in acc_p15],
        "p1p5_pass_observed_order_p": m_acc_pass["apparent_order_p"],
        "p1p5_pass_richardson_mmhg": m_acc_pass["richardson_extrapolated_mmhg"],
        "p1p5_pass_lower_bound_mmhg": m_acc_pass["conservative_po2_lower_bound_mmhg"],
        "p1p5_pass_verdict": m_acc_pass["verdict_from_mesh_policy"],
        "p2p2_capped_raw_order_p": m_acc_cap2["observed_order_p_raw"],
        "p2p2_capped_effective_order_p": m_acc_cap2["apparent_order_p"],
        "p2p2_capped_verdict": m_acc_cap2["verdict_from_mesh_policy"],
        "p1p5_straddle_verdict": m_acc_hold["verdict_from_mesh_policy"],
        "p1p5_fail_verdict": m_acc_fail["verdict_from_mesh_policy"],
        "passed": ok_14,
    })

    # 15. R16-B1: Strictly reject uncertainty_se <= 0 (== 0) under BOTH inferential models
    #     (`STUDENT_T_ESTIMATED_SE` and `KNOWN_SIGMA_NORMAL`) with
    #     `HOLD_NW08_INFERENTIAL_MODEL_REQUIRES_POSITIVE_SE`, while retaining explicit
    #     `ZERO_UNCERTAINTY_DETERMINISTIC_POINT` for SE == 0 and positive-SE `STUDENT_T_ESTIMATED_SE`!
    r16_b1_zero_rejects: Dict[str, bool] = {}
    for z_tag, z_kw in (
        (
            "student_t_se_zero_float",
            {
                "uncertainty_se": 0.0,
                "ocr_uncertainty_model": NW08_OCR_UNCERTAINTY_MODEL_STUDENT_T,
                "ocr_replicates_n": 6,
            },
        ),
        (
            "student_t_se_zero_int",
            {
                "uncertainty_se": 0,
                "ocr_uncertainty_model": NW08_OCR_UNCERTAINTY_MODEL_STUDENT_T,
                "ocr_degrees_of_freedom": 5,
            },
        ),
        (
            "known_sigma_se_zero_float",
            {
                "uncertainty_se": 0.0,
                "ocr_uncertainty_model": NW08_OCR_UNCERTAINTY_MODEL_KNOWN_SIGMA,
                "ocr_uncertainty_provenance": "calibrated_respirometer_known_sigma_cert_v1",
            },
        ),
        (
            "known_sigma_se_zero_dec",
            {
                "uncertainty_se": Decimal("0.0"),
                "ocr_uncertainty_model": NW08_OCR_UNCERTAINTY_MODEL_KNOWN_SIGMA,
                "ocr_uncertainty_provenance": "calibrated_respirometer_known_sigma_cert_v1",
            },
        ),
    ):
        got_tok = False
        try:
            evaluate_nw08_measured_ocr_trigger(
                "R1_390_stress",
                1.25,
                z_kw["uncertainty_se"],
                baseline_min_face_mmhg=15.261956,
                baseline_vasc_ocr_mult=1.2067,
                p_bed_mmhg=35.0,
                ocr_uncertainty_model=z_kw.get("ocr_uncertainty_model"),
                ocr_replicates_n=z_kw.get("ocr_replicates_n"),
                ocr_degrees_of_freedom=z_kw.get("ocr_degrees_of_freedom"),
                ocr_uncertainty_provenance=z_kw.get("ocr_uncertainty_provenance"),
            )
        except ValueError as exc_z:
            got_tok = NW08_HOLD_TOKEN_INFERENTIAL_REQUIRES_POSITIVE_SE in str(exc_z)
        r16_b1_zero_rejects[z_tag] = got_tok

    t_det_ctrl = evaluate_nw08_measured_ocr_trigger(
        "R2_DZ40",
        1.097,
        0.0,
        baseline_min_face_mmhg=24.0468,
        baseline_vasc_ocr_mult=1.097,
        p_bed_mmhg=40.0,
        ocr_uncertainty_model=NW08_OCR_UNCERTAINTY_MODEL_ZERO_POINT,
    )
    ok_15 = bool(
        all(r16_b1_zero_rejects.values())
        and t_det_ctrl["ocr_uncertainty_model"] == NW08_OCR_UNCERTAINTY_MODEL_ZERO_POINT
        and t_det_ctrl["measured_ocr_u95"] == 1.097
        and t_df5_trig["ocr_uncertainty_model"] == NW08_OCR_UNCERTAINTY_MODEL_STUDENT_T
        and abs(t_df5_trig["measured_ocr_u95"] - 1.370903) <= 1e-6
    )
    tests.append({
        "test": "r16_b1_reject_zero_se_under_student_t_and_known_sigma_retain_deterministic_and_pos_se",
        "zero_se_rejections": r16_b1_zero_rejects,
        "explicit_deterministic_model": t_det_ctrl["ocr_uncertainty_model"],
        "explicit_deterministic_u95": t_det_ctrl["measured_ocr_u95"],
        "positive_se_student_t_n6_u95": t_df5_trig["measured_ocr_u95"],
        "passed": ok_15,
    })

    # 16. R16-M1: Provably outward-conservative upper enclosure on `exact_student_t_one_sided_95(df)`
    #     across df >= 1 (zero inward error at df=1 Cauchy cot(pi/20), df=2, df=5 displaying exact
    #     2.0150484, through df=10**9, plus hostile ambient Decimal context immunity)!
    with _clean_dec_ctx(80, ROUND_HALF_EVEN):
        s5_ref = Decimal(5).sqrt()
        exact_cot_pi20 = (Decimal(5) + Decimal(2) * s5_ref).sqrt() + s5_ref + Decimal(1)
        exact_t2 = (Decimal(162) / Decimal(19)).sqrt()
    t1_val = exact_student_t_one_sided_95(1)
    t2_val = exact_student_t_one_sided_95(2)
    t5_val = exact_student_t_one_sided_95(5)
    t_sweep_ok = bool(
        Decimal.from_float(t1_val) >= exact_cot_pi20
        and Decimal(str(t1_val)) >= exact_cot_pi20
        and Decimal.from_float(t2_val) >= exact_t2
        and Decimal(str(t2_val)) >= exact_t2
        and round(t5_val, 7) == 2.0150484
        and abs(t5_val - 2.015048373333021) < 1e-11
    )
    p95_dec = Decimal("0.95")
    for chk_df in (1, 2, 3, 4, 5, 6, 10, 20, 50, 100, 500, 1000, 2000):
        tv = exact_student_t_one_sided_95(chk_df)
        if not (
            _exact_student_t_cdf_dec(Decimal.from_float(tv), chk_df, 55) >= p95_dec
            and _exact_student_t_cdf_dec(Decimal(str(tv)), chk_df, 55) >= p95_dec
        ):
            t_sweep_ok = False
    for large_df in (2001, 5000, 10000, 100000, 1_000_000, 1_000_000_000):
        tv_l = exact_student_t_one_sided_95(large_df)
        if not (tv_l > float(_EXACT_Z95_UPPER_40D) or Decimal.from_float(tv_l) >= _EXACT_Z95_UPPER_40D):
            t_sweep_ok = False
    # Verify exact_student_t_one_sided_95 is immune to hostile ambient context (prec=4, Inexact trap)
    exact_student_t_one_sided_95.cache_clear()
    hostile_t_ok = True
    with localcontext(Context(prec=4, rounding=ROUND_FLOOR, Emin=-2, Emax=100, traps=[decimal.Inexact])):
        try:
            if exact_student_t_one_sided_95(1) != t1_val or exact_student_t_one_sided_95(5) != t5_val:
                hostile_t_ok = False
        except Exception:
            hostile_t_ok = False
    ok_16 = bool(t_sweep_ok and hostile_t_ok)
    tests.append({
        "test": "r16_m1_student_t_quantile_outward_upper_enclosure_df1_cauchy_df5_and_large_df",
        "t_df1_float": t1_val,
        "t_df1_ge_exact_cot_pi_over_20": bool(Decimal.from_float(t1_val) >= exact_cot_pi20),
        "t_df5_7dp": round(t5_val, 7),
        "all_tested_df_outward_ge_0p95": t_sweep_ok,
        "hostile_decimal_context_immune": hostile_t_ok,
        "passed": ok_16,
    })

    # 17. R16-M3: Explicit `mesh_uncertainty_status` and `order_qualified`/`interval_valid` separation
    #     across 3-grid asymptotic GCI qualified, 3-grid monotone non-asymptotic fallback (R3P_35_VPIO120),
    #     3-grid oscillatory ASME V&V-20 half-range, and 3-grid slow-order unqualified HOLD!
    r3p_std_ladder = (("coarse", 28, 32), ("medium", 42, 48), ("fine", 56, 64))
    m_vpio_fb = _adjudicate_nw08_three_grid_convergence(15.1005, 15.1059, 15.3084, r3p_std_ladder)
    m_osc_r1 = _adjudicate_nw08_three_grid_convergence(15.0741, 14.9753, 15.0638, r2_std_ladder)
    ok_17 = bool(
        m_acc_pass["order_qualified"] is True
        and m_acc_pass["interval_valid"] is True
        and m_acc_pass["grids_run"] == 3
        and m_acc_pass["mesh_uncertainty_status"] == NW08_MESH_STATUS_THREE_GRID_ASYMPTOTIC_GCI_QUALIFIED
        and m_vpio_fb["verdict_from_mesh_policy"] == "PASS"
        and m_vpio_fb["order_qualified"] is False
        and m_vpio_fb["interval_valid"] is True
        and m_vpio_fb["grids_run"] == 3
        and m_vpio_fb["mesh_uncertainty_status"] == NW08_MESH_STATUS_THREE_GRID_MONOTONE_FALLBACK
        and m_osc_r1["verdict_from_mesh_policy"] == "HOLD"
        and m_osc_r1["order_qualified"] is False
        and m_osc_r1["interval_valid"] is True
        and m_osc_r1["mesh_uncertainty_status"] == NW08_MESH_STATUS_THREE_GRID_OSCILLATORY_BOUND
        and m_slow["order_qualified"] is False
        and m_slow["interval_valid"] is False
        and m_slow["mesh_uncertainty_status"] == NW08_MESH_STATUS_THREE_GRID_UNQUALIFIED_ORDER_HOLD
    )
    tests.append({
        "test": "r16_m3_mesh_uncertainty_status_separates_asymptotic_gci_fallback_oscillatory_and_hold",
        "asymptotic_gci_status": m_acc_pass["mesh_uncertainty_status"],
        "monotone_fallback_status": m_vpio_fb["mesh_uncertainty_status"],
        "monotone_fallback_order_qualified": m_vpio_fb["order_qualified"],
        "oscillatory_status": m_osc_r1["mesh_uncertainty_status"],
        "slow_order_hold_status": m_slow["mesh_uncertainty_status"],
        "passed": ok_17,
    })

    # 18. R17-B2: Provably upper-enclosed known-sigma normal quantile z_{0.95} (rejecting old
    #     under-covering 1.6448536269514722 / 1.6448536269514726) AND Sol's exact sub-ULP positive-SE
    #     example (ocr=1.097, SE=1e-20, Student-t df=5) strictly stepping ocr_u95_float > 1.097 and
    #     delta_vasc_pct_u95 > 0.0 while canonical SE=0 deterministic point remains monotone!
    t_r17_sub_ulp_t5 = evaluate_nw08_measured_ocr_trigger(
        "R2_DZ40",
        1.097,
        1e-20,
        baseline_min_face_mmhg=19.19079251185101,
        baseline_vasc_ocr_mult=1.097,
        p_bed_mmhg=40.0,
        ocr_uncertainty_model=NW08_OCR_UNCERTAINTY_MODEL_STUDENT_T,
        ocr_degrees_of_freedom=5,
    )
    t_r17_sub_ulp_ks = evaluate_nw08_measured_ocr_trigger(
        "R2_DZ40",
        1.097,
        1e-20,
        baseline_min_face_mmhg=19.19079251185101,
        baseline_vasc_ocr_mult=1.097,
        p_bed_mmhg=40.0,
        z_one_sided_95=MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95,
        ocr_uncertainty_model=NW08_OCR_UNCERTAINTY_MODEL_KNOWN_SIGMA,
        ocr_uncertainty_provenance="NIST_CALIBRATED_KNOWN_SIGMA_SEAHORSE_ASSAY",
    )
    t_r17_det0 = evaluate_nw08_measured_ocr_trigger(
        "R2_DZ40",
        1.097,
        0.0,
        baseline_min_face_mmhg=19.19079251185101,
        baseline_vasc_ocr_mult=1.097,
        p_bed_mmhg=40.0,
        ocr_uncertainty_model=NW08_OCR_UNCERTAINTY_MODEL_ZERO_POINT,
    )
    ks_old_z_rejected = False
    try:
        evaluate_nw08_measured_ocr_trigger(
            "R2_DZ40",
            1.097,
            1e-20,
            baseline_min_face_mmhg=19.19079251185101,
            baseline_vasc_ocr_mult=1.097,
            p_bed_mmhg=40.0,
            z_one_sided_95=1.6448536269514722,
            ocr_uncertainty_model=NW08_OCR_UNCERTAINTY_MODEL_KNOWN_SIGMA,
            ocr_uncertainty_provenance="NIST_CALIBRATED_KNOWN_SIGMA_SEAHORSE_ASSAY",
        )
    except ValueError:
        ks_old_z_rejected = True
    u95_t5_dec = Decimal(str(t_r17_sub_ulp_t5["measured_ocr_u95_exact_dec"]))
    u95_ks_dec = Decimal(str(t_r17_sub_ulp_ks["measured_ocr_u95_exact_dec"]))
    ok_18 = bool(
        ks_old_z_rejected is True
        and u95_t5_dec > Decimal("1.097")
        and Fraction(float(t_r17_sub_ulp_t5["measured_ocr_u95_unrounded_float64"])) >= Fraction(u95_t5_dec)
        and float(t_r17_sub_ulp_t5["measured_ocr_u95_unrounded_float64"]) > 1.097
        and float(t_r17_sub_ulp_t5["delta_vasc_pct_u95_unrounded_float64"]) > 0.0
        and t_r17_sub_ulp_t5["within_provably_monotone_no_increase_domain"] is False
        and t_r17_sub_ulp_t5["candidate_3d_solve_required_for_release_pass"] is True
        and u95_ks_dec > Decimal("1.097")
        and Fraction(float(t_r17_sub_ulp_ks["measured_ocr_u95_unrounded_float64"])) >= Fraction(u95_ks_dec)
        and float(t_r17_sub_ulp_ks["measured_ocr_u95_unrounded_float64"]) > 1.097
        and float(t_r17_sub_ulp_ks["delta_vasc_pct_u95_unrounded_float64"]) > 0.0
        and Decimal(str(t_r17_det0["measured_ocr_u95_exact_dec"])) == Decimal("1.097")
        and float(t_r17_det0["delta_vasc_pct_u95_unrounded_float64"]) == 0.0
        and t_r17_det0["within_provably_monotone_no_increase_domain"] is True
        and t_r17_det0["candidate_3d_solve_required_for_release_pass"] is False
    )
    tests.append({
        "test": "r17_b2_known_sigma_z95_upper_enclosure_and_sub_ulp_positive_se_trigger",
        "old_undercovering_z_rejected": ks_old_z_rejected,
        "sub_ulp_t5_ocr_u95_dec": str(u95_t5_dec),
        "sub_ulp_t5_ocr_u95_float": t_r17_sub_ulp_t5["measured_ocr_u95_unrounded_float64"],
        "sub_ulp_t5_delta_vasc_pct_u95_unrounded": t_r17_sub_ulp_t5["delta_vasc_pct_u95_unrounded_float64"],
        "sub_ulp_ks_ocr_u95_float": t_r17_sub_ulp_ks["measured_ocr_u95_unrounded_float64"],
        "det0_monotone": t_r17_det0["within_provably_monotone_no_increase_domain"],
        "passed": ok_18,
    })

    passed_n = sum(1 for t in tests if t["passed"])
    return {
        "total_tests": len(tests),
        "passed_tests": passed_n,
        "all_passed": passed_n == len(tests),
        "tests": tests,
    }


def _build_nw08_route_catalog(openislet_root: Path) -> Dict[str, Dict[str, Any]]:
    """
    Canonical catalog of all 8 OpenIslet Route 1 / Route 2 / Route 3P 3D FVM solver geometries
    shared by BOTH `_run_true_3d_fvm_vascular_voxel_replays` AND live `dispatch_and_solve_nw08_measured_ocr` (B7).
    """
    d33 = strict_json_load_file(openislet_root / "data/extracted/iip0033_bilayer_and_respirometry_verification_v0.8.0.json", preserve_boundary_decimals=False)
    d34 = strict_json_load_file(openislet_root / "data/extracted/iip0034_planar_and_portfolio_verification_v0.8.0.json", preserve_boundary_decimals=False)
    l4 = strict_json_load_file(openislet_root / "data/extracted/layer4_tissue_and_metabolic_twin_atlas.json", preserve_boundary_decimals=False)
    r1_rows = d33["fixed_pitch_bilayer_and_holds"]["pass_runs_multimesh"]

    def _r1_row(lbl: str) -> Dict[str, Any]:
        return next(r for r in r1_rows if r["label"] == lbl)

    def _iip34_val(lbl: str) -> float:
        return float(next(r["worst_face_mmhg"] for r in d34["planar_3d_fvm_oxygen_envelopes"] if r["label"] == lbl))

    nominal = 1.097
    comp = (2.0 * (65.0 ** 3) - (68.0 ** 3)) ** (1.0 / 3.0)
    catalog: Dict[str, Dict[str, Any]] = {}

    for key, lbl, slab, top in (
        ("R1_390_nominal", "PASS_R1_390_Staggered_Nominal1p097_p95_68_2xAdj_nx80", 390, [68, 68, comp, comp]),
        ("R1_350_stress", "PASS_R1_350_Staggered_PurePlus10OCR_15umStandoff_max68_t7p95_66p95_1x68_nx80", 350, [68, 65, 65, comp]),
        ("R1_390_stress", "PASS_R1_390_Staggered_CoupledPlus10OCR_16p5umStandoff_p95_68_2xAdj_nx80", 390, [68, 68, comp, comp]),
    ):
        row = _r1_row(lbl)
        catalog[key] = {
            "route_family": "R1",
            "operator_name": "verify_iip0033_bilayer_and_resp1.solve_route1_supercell_fixed_pitch",
            "p_bed_mmhg": 35.0,
            "baseline_shared_ocr": float(row["ocr_mult"]),
            "baseline_display_mmhg": float(row["worst_face_mmhg"]),
            "kwargs": {
                "label": lbl,
                "slab_um": slab,
                "top_diams_um": top,
                "bot_diams_um": [65] * 4,
                "staggered": True,
                "bed_po2_mmhg": 35.0,
                "ocr_mult": row["ocr_mult"],
                "standoff_phys_um": row["standoff_phys_um"],
                "nx_tot": row["nx_tot"],
                "nz": row["nz"],
            },
        }

    r2_base = float(
        l4["part_a_336h_spatial_reaction_diffusion_pouch_pde"]
        ["lineage_partitioned_metabolic_rest_and_m101_exclusion_audit"]
        ["design_z_140um_parameterized_acute_chronic_and_pfc_matrix"]
        ["cases"]["Chronic_40mmHg_1p097xOCR_ChronicGel"]["fv_harmonic_face_min_mmhg"]
    )
    catalog["R2_DZ40"] = {
        "route_family": "R2",
        "operator_name": "run_layer4_tissue_and_metabolic_twin.compute_design_z_140um_parameterized_case",
        "p_bed_mmhg": 40.0,
        "baseline_shared_ocr": nominal,
        "baseline_display_mmhg": r2_base,
        "kwargs": {"bed_po2_mmhg": 40.0, "ocr_multiplier": nominal, "d_gel_cm2_s": 1.5e-5, "k_perf_s_inv": 0.1358},
    }

    r3p_krbh_base = float(
        d34["planar_30mmhg_buffer_solubility_sensitivity"]["hybrid333_h180_bed30_clean_phys_buffer"]["worst_face_mmhg"]
    )
    for key, bed, diam, alpha_b, base_mmhg in (
        ("R3P_35", 35.0, 65.0, 1.34e-9, _iip34_val("Hybrid333_H180_Day0_Clean_65um_PASS")),
        ("R3P_30", 30.0, 65.0, 1.34e-9, _iip34_val("Hybrid333_H180_Day0_Clean_65um_Bed30mmHg_PASS")),
        ("R3P_30_KRBH", 30.0, 65.0, 1.27e-9, r3p_krbh_base),
        ("R3P_35_VPIO120", 35.0, 120.0, 1.34e-9, _iip34_val("Hybrid333_H180_Day0_Avascular_VPIO120_Clean_PASS")),
    ):
        catalog[key] = {
            "route_family": "R3P",
            "operator_name": "verify_iip0034_planar_and_portfolio.solve_planar_route3p_fvm",
            "p_bed_mmhg": bed,
            "baseline_shared_ocr": nominal,
            "baseline_display_mmhg": base_mmhg,
            "kwargs": {
                "label": key,
                "area_cm2": 333.3,
                "bed_po2_mmhg": bed,
                "cluster_diam_um": diam,
                "alpha_mol_cm3_mmhg": alpha_b,
                "ocr_mult": nominal,
            },
        }
    return catalog


_NW08_ISOLATED_FVM_WORKER_SRC: str = r"""
from __future__ import annotations

from fractions import Fraction
import importlib
import inspect
import json
import math
import os
from pathlib import Path
import sys

sys.dont_write_bytecode = True

_REAL_STDOUT = sys.stdout


def _run_worker() -> int:
    raw_in = sys.stdin.read()
    req = json.loads(raw_in)
    resolved_root = Path(req["repo_root"]).resolve()
    scripts_dir = (resolved_root / "scripts").resolve()
    if not scripts_dir.is_dir():
        raise RuntimeError(f"Requested repo_root scripts directory does not exist: {scripts_dir}")

    # Strip ambient cwd and any foreign OpenIslet scripts directories from sys.path,
    # prepending ONLY resolved_root/scripts so solver imports bind exclusively to repo_root.
    cleaned_path = []
    for entry in sys.path:
        if entry in ("", "."):
            continue
        try:
            ep = Path(entry).resolve()
        except Exception:
            cleaned_path.append(entry)
            continue
        if (
            ep == resolved_root
            or ep == scripts_dir
            or (ep / "run_layer4_tissue_and_metabolic_twin.py").is_file()
            or (ep / "verify_iip0033_bilayer_and_resp1.py").is_file()
            or (ep / "verify_iip0034_planar_and_portfolio.py").is_file()
        ):
            continue
        cleaned_path.append(entry)
    sys.path[:] = [str(scripts_dir), *cleaned_path]

    fam = str(req["route_family"])
    operator_name = str(req.get("operator_name") or "")
    solve_kwargs = dict(req["solve_kwargs"])
    for fk, fhex in (req.get("solve_kwargs_float_hex") or {}).items():
        solve_kwargs[fk] = float.fromhex(str(fhex))
    expected_p_bed = float.fromhex(str(req["expected_p_bed_hex"]))
    vasc_scale = (
        None
        if req.get("vasc_scale_hex") is None
        else float.fromhex(str(req["vasc_scale_hex"]))
    )
    min_ratio_pair = req.get("min_exact_scale_ratio")
    min_exact_scale_ratio = (
        None
        if min_ratio_pair is None
        else Fraction(int(min_ratio_pair[0]), int(min_ratio_pair[1]))
    )

    required_files = ["run_layer4_tissue_and_metabolic_twin.py"]
    if fam == "R1":
        required_files.append("verify_iip0033_bilayer_and_resp1.py")
    elif fam == "R3P":
        required_files.append("verify_iip0034_planar_and_portfolio.py")
    elif fam != "R2":
        raise ValueError(f"Unknown route_family: {fam!r}")

    for rf in required_files:
        rfp = (scripts_dir / rf).resolve()
        if not rfp.is_file() or not rfp.is_relative_to(resolved_root) or not rfp.is_relative_to(scripts_dir):
            raise RuntimeError(
                f"Required solver script {rf!r} missing or resolves outside requested repo_root"
            )

    sys.stdout = sys.stderr
    try:
        import numpy as np

        layer4 = importlib.import_module("run_layer4_tissue_and_metabolic_twin")
        loaded_solver_mods = {"run_layer4_tissue_and_metabolic_twin": layer4}
        if fam == "R1":
            route1 = importlib.import_module("verify_iip0033_bilayer_and_resp1")
            loaded_solver_mods["verify_iip0033_bilayer_and_resp1"] = route1
            fn = route1.solve_route1_supercell_fixed_pitch
            if getattr(route1, "l4", None) is not layer4:
                raise RuntimeError("Route-1 solver did not bind the requested repo_root Layer-4 module")
            if getattr(route1, "ROOT", None) != resolved_root:
                raise RuntimeError("Route-1 solver ROOT mismatch against requested repo_root")
        elif fam == "R2":
            fn = layer4.compute_design_z_140um_parameterized_case
        else:
            route3p = importlib.import_module("verify_iip0034_planar_and_portfolio")
            loaded_solver_mods["verify_iip0034_planar_and_portfolio"] = route3p
            fn = route3p.solve_planar_route3p_fvm
            if getattr(route3p, "l4", None) is not layer4:
                raise RuntimeError("Route-3P solver did not bind the requested repo_root Layer-4 module")
            if getattr(route3p, "ROOT", None) != resolved_root:
                raise RuntimeError("Route-3P solver ROOT mismatch against requested repo_root")

        for extra_name in (
            "rank_islet1_stacks",
            "product_contract",
            "openislet_engineering_priors",
            "openislet_public_excerpt_policy",
        ):
            extra_mod = sys.modules.get(extra_name)
            if extra_mod is not None:
                loaded_solver_mods[extra_name] = extra_mod
                if extra_name == "rank_islet1_stacks" and getattr(extra_mod, "PROJECT_ROOT", None) != resolved_root:
                    raise RuntimeError("Transitive rank_islet1_stacks PROJECT_ROOT mismatch against requested repo_root")

        resolved_origins = {}
        resolved_relpaths = {}
        for mod_name, mod_obj in sorted(loaded_solver_mods.items()):
            mod_file = getattr(mod_obj, "__file__", None)
            if not mod_file:
                raise RuntimeError(f"Solver module {mod_name!r} has no __file__ provenance")
            mod_path = Path(mod_file).resolve()
            if not mod_path.is_relative_to(resolved_root) or not mod_path.is_relative_to(scripts_dir):
                raise RuntimeError(
                    f"Solver module {mod_name!r} resolved outside requested repo_root: "
                    f"{mod_path} not under {resolved_root}"
                )
            resolved_origins[mod_name] = str(mod_path)
            resolved_relpaths[mod_name] = mod_path.relative_to(resolved_root).as_posix()

        sig_params = inspect.signature(fn).parameters
        if "bed_po2_mmhg" in solve_kwargs and "bed_po2_mmhg" not in sig_params:
            raise ValueError(
                f"Route operator {operator_name!r} does not accept boundary-pressure override 'bed_po2_mmhg'"
            )

        source_solver = layer4._solve_3d_oxygen_strict_iip_0019
        source_fv_stats = layer4._compute_exact_fv_interface_stats_iip_0019
        captured_mins = []
        captured_p_beds = []
        operand_audits = []

        def _fv_spy(*a, **kw):
            fv_out = source_fv_stats(*a, **kw)
            captured_mins.append(float(fv_out["fv_harmonic_face_min_mmhg"]))
            return fv_out

        def _solve_spy(perm, vmax, *a, **kw):
            raw_pb = kw.get("p_bed", a[5] if len(a) > 5 else None)
            if raw_pb is None or isinstance(raw_pb, bool) or not math.isfinite(float(raw_pb)):
                raise RuntimeError(f"3D FVM solver received invalid p_bed={raw_pb!r}")
            captured_p_beds.append(float(raw_pb))
            if vasc_scale is None:
                active_u = vmax > 0
                if np.any(active_u):
                    smallest_u = np.min(perm[active_u])
                    islet_u = active_u & (perm == smallest_u)
                    vascular_u = active_u & ~islet_u
                    if np.any(islet_u) and np.any(vascular_u):
                        base_u_list = [float(x) for x in np.unique(vmax[vascular_u])]
                        operand_audits.append({
                            "scaled": False,
                            "islet_vmax_unchanged": True,
                            "all_vascular_vmax_strictly_greater_than_base": False,
                            "all_vascular_voxels_satisfy_min_exact_scale_ratio": True,
                            "base_to_scaled_vascular_vmax_pairs_hex": [[x.hex(), x.hex()] for x in base_u_list],
                            "islet_voxel_count": int(np.sum(islet_u)),
                            "vascular_voxel_count": int(np.sum(vascular_u)),
                        })
                return source_solver(perm, vmax, *a, **kw)

            active = vmax > 0
            smallest_active_perm = np.min(perm[active])
            islet = active & (perm == smallest_active_perm)
            vascular = active & ~islet
            if not np.any(islet) or not np.any(vascular):
                raise ValueError("Expected distinct active islet and stromal/vascular voxels")
            scaled_vasc = vmax[vascular] * float(vasc_scale)
            if min_exact_scale_ratio is not None:
                for base_u in np.unique(vmax[vascular]):
                    bf = float(base_u)
                    sf = float(bf * float(vasc_scale))
                    req_v = Fraction(bf) * min_exact_scale_ratio
                    bumped = sf
                    while Fraction(bumped) < req_v:
                        bumped = math.nextafter(bumped, math.inf)
                    if bumped != sf:
                        scaled_vasc = np.where(vmax[vascular] == base_u, bumped, scaled_vasc)
            scaled_vmax = vmax.copy()
            scaled_vmax[vascular] = scaled_vasc

            pairs_hex = []
            ratio_ok = True
            for base_u in np.unique(vmax[vascular]):
                bf = float(base_u)
                s_vals = np.unique(scaled_vmax[vascular & (vmax == base_u)])
                if len(s_vals) != 1:
                    ratio_ok = False
                sf_actual = float(s_vals[0])
                pairs_hex.append([bf.hex(), sf_actual.hex()])
                if min_exact_scale_ratio is not None and Fraction(sf_actual) < Fraction(bf) * min_exact_scale_ratio:
                    ratio_ok = False

            operand_audits.append({
                "scaled": True,
                "islet_vmax_unchanged": bool(np.array_equal(scaled_vmax[islet], vmax[islet])),
                "all_vascular_vmax_strictly_greater_than_base": bool(np.all(scaled_vmax[vascular] > vmax[vascular])),
                "all_vascular_voxels_satisfy_min_exact_scale_ratio": bool(ratio_ok),
                "base_to_scaled_vascular_vmax_pairs_hex": pairs_hex,
                "islet_voxel_count": int(np.sum(islet)),
                "vascular_voxel_count": int(np.sum(vascular)),
            })
            return source_solver(perm, scaled_vmax, *a, **kw)

        layer4._compute_exact_fv_interface_stats_iip_0019 = _fv_spy
        layer4._solve_3d_oxygen_strict_iip_0019 = _solve_spy
        try:
            res_obj = fn(**solve_kwargs)
        finally:
            layer4._compute_exact_fv_interface_stats_iip_0019 = source_fv_stats
            layer4._solve_3d_oxygen_strict_iip_0019 = source_solver

        if not captured_mins:
            raise RuntimeError("Native FV interface statistics callback was not invoked during 3D FVM solve")
        if not captured_p_beds:
            raise RuntimeError("3D FVM oxygen solver callback was not invoked during solve")
        if any(pb != expected_p_bed for pb in captured_p_beds):
            raise RuntimeError(
                f"3D FVM solver p_bed mismatch: expected {expected_p_bed!r}, observed {captured_p_beds!r}"
            )

        min_face = float(min(captured_mins))
        verified_pb = float(captured_p_beds[-1])
        out = {
            "ok": True,
            "res_obj": res_obj,
            "face_min_raw_hex": min_face.hex(),
            "verified_p_bed_hex": verified_pb.hex(),
            "d_o2_islet_tissue_cm2_s_hex": float(layer4.D_O2_ISLET_TISSUE_CM2_S).hex(),
            "resolved_solver_module_paths": resolved_origins,
            "resolved_solver_module_relpaths": resolved_relpaths,
            "vascular_operand_audit": operand_audits[-1] if operand_audits else None,
            "child_pid": os.getpid(),
            "child_optimize_flag": int(sys.flags.optimize),
        }
    finally:
        sys.stdout = _REAL_STDOUT

    _REAL_STDOUT.write(json.dumps(out, allow_nan=False))
    _REAL_STDOUT.flush()
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(_run_worker())
    except Exception as exc:
        err_payload = {
            "ok": False,
            "error_type": type(exc).__name__,
            "error_message": str(exc),
        }
        _REAL_STDOUT.write(json.dumps(err_payload, allow_nan=False))
        _REAL_STDOUT.flush()
        raise SystemExit(1)
"""


def _execute_single_3d_fvm_vascular_scaled_solve_with_meta(
    openislet_root: Path,
    route_spec: Dict[str, Any],
    *,
    vasc_scale: float | None = None,
    min_exact_scale_ratio: Fraction | None = None,
) -> Tuple[Dict[str, Any], float, float]:
    """
    Invoke the exact read-only OpenIslet 3D FVM operator for `route_spec` with optional
    vascular-voxel-only OCR scaling and explicit boundary-pressure (`bed_po2_mmhg`) enforcement
    inside an **isolated child Python subprocess** bound strictly to `openislet_root.resolve() / "scripts"`.
    NEVER mutates parent `sys.path`, `sys.modules`, or `run_layer4_tissue_and_metabolic_twin` callbacks
    so concurrent raw native Layer-4 callers AND sequential cross-root calls against distinct repo
    copies remain 100% isolated (R18-B1 + R18-B2).
    Returns `(res_obj, native_unrounded_face_min_mmhg, verified_solver_p_bed_mmhg)` with verified
    isolated solver provenance attached under `res_obj["_nw08_isolated_solver_meta"]`.
    """
    resolved_root = Path(openislet_root).resolve()
    scripts_dir = (resolved_root / "scripts").resolve()
    if not scripts_dir.is_dir():
        raise ValueError(f"Requested openislet_root scripts directory does not exist: {scripts_dir}")

    fam = str(route_spec["route_family"])
    if fam not in ("R1", "R2", "R3P"):
        raise ValueError(f"Unknown route_family: {fam!r}")

    solve_kwargs = dict(route_spec["kwargs"])
    expected_p_bed = float(solve_kwargs.get("bed_po2_mmhg", route_spec["p_bed_mmhg"]))
    float_hex_map = {
        k: float(v).hex()
        for k, v in solve_kwargs.items()
        if isinstance(v, float) and not isinstance(v, bool)
    }

    child_req = {
        "repo_root": str(resolved_root),
        "route_family": fam,
        "operator_name": str(route_spec.get("operator_name") or ""),
        "solve_kwargs": solve_kwargs,
        "solve_kwargs_float_hex": float_hex_map,
        "expected_p_bed_hex": expected_p_bed.hex(),
        "vasc_scale_hex": None if vasc_scale is None else float(vasc_scale).hex(),
        "min_exact_scale_ratio": (
            None
            if min_exact_scale_ratio is None
            else [int(min_exact_scale_ratio.numerator), int(min_exact_scale_ratio.denominator)]
        ),
    }

    child_env = dict(os.environ)
    child_env["PYTHONDONTWRITEBYTECODE"] = "1"
    child_env.pop("PYTHONPATH", None)
    child_env.pop("PYTHONSTARTUP", None)

    cmd = [
        sys.executable,
        *(["-O"] if sys.flags.optimize else []),
        "-B",
        "-c",
        _NW08_ISOLATED_FVM_WORKER_SRC,
    ]
    proc = subprocess.run(
        cmd,
        input=json.dumps(child_req, allow_nan=False),
        cwd=str(resolved_root),
        env=child_env,
        capture_output=True,
        text=True,
        check=False,
    )

    parsed: Dict[str, Any] | None = None
    if proc.stdout.strip():
        try:
            loaded = json.loads(proc.stdout)
            if isinstance(loaded, dict):
                parsed = loaded
        except json.JSONDecodeError:
            parsed = None

    if proc.returncode != 0 or not isinstance(parsed, dict) or parsed.get("ok") is not True:
        if isinstance(parsed, dict) and parsed.get("ok") is False:
            err_type = str(parsed.get("error_type") or "RuntimeError")
            err_msg = str(parsed.get("error_message") or "Isolated 3D FVM solver worker failed")
            if err_type == "ValueError":
                raise ValueError(err_msg)
            raise RuntimeError(f"Isolated 3D FVM solver subprocess error ({err_type}): {err_msg}")
        raise RuntimeError(
            f"Isolated 3D FVM solver subprocess failed (rc={proc.returncode}): {proc.stderr.strip() or proc.stdout.strip()}"
        )

    raw_origins = parsed.get("resolved_solver_module_paths")
    raw_relpaths = parsed.get("resolved_solver_module_relpaths")
    if not isinstance(raw_origins, dict) or not raw_origins or "run_layer4_tissue_and_metabolic_twin" not in raw_origins:
        raise RuntimeError("Isolated 3D FVM solver subprocess did not return verified solver module origins")

    verified_origins: Dict[str, str] = {}
    verified_relpaths: Dict[str, str] = {}
    for mod_name, origin_str in sorted(raw_origins.items()):
        if not isinstance(mod_name, str) or not isinstance(origin_str, str):
            raise RuntimeError(f"Invalid solver module origin entry: {mod_name!r}: {origin_str!r}")
        origin_path = Path(origin_str).resolve()
        if not origin_path.is_relative_to(resolved_root) or not origin_path.is_relative_to(scripts_dir):
            raise RuntimeError(
                f"Isolated 3D FVM solver module {mod_name!r} resolved outside requested openislet_root: "
                f"{origin_path} not under {resolved_root}"
            )
        verified_origins[mod_name] = str(origin_path)
        verified_relpaths[mod_name] = origin_path.relative_to(resolved_root).as_posix()

    if isinstance(raw_relpaths, dict):
        for mod_name, rel_str in raw_relpaths.items():
            if mod_name in verified_relpaths and rel_str != verified_relpaths[mod_name]:
                raise RuntimeError(f"Solver module relpath mismatch for {mod_name!r}")

    face_min_raw = float.fromhex(str(parsed["face_min_raw_hex"]))
    verified_pb = float.fromhex(str(parsed["verified_p_bed_hex"]))
    d_o2_islet_verified = float.fromhex(str(parsed["d_o2_islet_tissue_cm2_s_hex"]))
    if verified_pb != expected_p_bed:
        raise RuntimeError(
            f"3D FVM solver p_bed mismatch: expected {expected_p_bed!r}, observed {verified_pb!r}"
        )

    res_obj = parsed.get("res_obj")
    if not isinstance(res_obj, dict):
        res_obj = {}
    res_obj["_nw08_isolated_solver_meta"] = {
        "solver_isolation_mode": "ISOLATED_CHILD_SUBPROCESS",
        "resolved_solver_module_paths": verified_origins,
        "resolved_solver_module_relpaths": verified_relpaths,
        "all_solver_module_origins_within_repo_root": True,
        "vascular_operand_audit": parsed.get("vascular_operand_audit"),
        "d_o2_islet_tissue_cm2_s": d_o2_islet_verified,
        "child_pid": int(parsed.get("child_pid") or 0),
        "child_optimize_flag": int(parsed.get("child_optimize_flag") or 0),
    }
    return res_obj, face_min_raw, verified_pb


def _execute_single_3d_fvm_vascular_scaled_solve(
    openislet_root: Path,
    route_spec: Dict[str, Any],
    *,
    vasc_scale: float | None = None,
) -> Tuple[Dict[str, Any], float]:
    """
    Invoke the exact read-only OpenIslet 3D FVM operator for `route_spec` with optional
    vascular-voxel-only OCR scaling and capture the native UNROUNDED float64 face minimum
    directly from `_compute_exact_fv_interface_stats_iip_0019` BEFORE 4-dp display rounding.
    """
    res_obj, face_min_raw, _verified_p_bed = _execute_single_3d_fvm_vascular_scaled_solve_with_meta(
        openislet_root,
        route_spec,
        vasc_scale=vasc_scale,
    )
    return res_obj, face_min_raw


def _get_native_unrounded_baseline_mmhg_with_meta(
    openislet_root: Path,
    route_id: str,
    effective_spec: Dict[str, Any],
    eff_base_ocr: float,
) -> Tuple[float, Dict[str, Any]]:
    """
    Compute (with thread-safe root-keyed memoization) the exact native float64 unrounded baseline
    face minimum and verified isolated-subprocess module-origin metadata directly from the route's
    3D FVM operator at the requested boundary pressure (`effective_spec["kwargs"]["bed_po2_mmhg"]`)
    and baseline vascular OCR (R03-B2 + R18-B2).
    Never substitutes a 4-decimal display string as an unrounded baseline!
    """
    eff_p_bed = float(effective_spec["kwargs"]["bed_po2_mmhg"])
    resolved_root_str = str(openislet_root.resolve())
    cache_key = (resolved_root_str, str(route_id), eff_p_bed, float(eff_base_ocr))
    with _FVM_SOLVER_LOCK:
        cached = _NATIVE_BASELINE_MMHG_CACHE.get(cache_key)
        cached_meta = _NATIVE_BASELINE_META_CACHE.get(cache_key)
        if cached is not None and isinstance(cached_meta, dict) and cached_meta.get("resolved_solver_module_paths"):
            return cached, copy.deepcopy(cached_meta)
    shared_ocr = float(effective_spec["baseline_shared_ocr"])
    base_scale: float | None = (
        None if float(eff_base_ocr) == shared_ocr else (float(eff_base_ocr) / shared_ocr)
    )
    res_obj, native_base_mmhg, _pb = _execute_single_3d_fvm_vascular_scaled_solve_with_meta(
        openislet_root,
        effective_spec,
        vasc_scale=base_scale,
    )
    iso_meta = copy.deepcopy(res_obj.get("_nw08_isolated_solver_meta") or {})
    with _FVM_SOLVER_LOCK:
        _NATIVE_BASELINE_MMHG_CACHE[cache_key] = native_base_mmhg
        _NATIVE_BASELINE_META_CACHE[cache_key] = iso_meta
    return native_base_mmhg, copy.deepcopy(iso_meta)


def _get_native_unrounded_baseline_mmhg(
    openislet_root: Path,
    route_id: str,
    effective_spec: Dict[str, Any],
    eff_base_ocr: float,
) -> float:
    """
    Compute (with thread-safe memoization) the exact native float64 unrounded baseline
    face minimum directly from the route's 3D FVM operator at the requested boundary
    pressure (`effective_spec["kwargs"]["bed_po2_mmhg"]`) and baseline vascular OCR (R03-B2).
    Never substitutes a 4-decimal display string as an unrounded baseline!
    """
    native_base_mmhg, _meta = _get_native_unrounded_baseline_mmhg_with_meta(
        openislet_root, route_id, effective_spec, eff_base_ocr
    )
    return native_base_mmhg


def _get_nw08_mesh_refinement_ladder(route_spec: Dict[str, Any]) -> Tuple[Tuple[str, int, int], ...]:
    """
    R14-B1 Predeclared 3-grid numerical refinement ladder per canonical NW-08 route family
    (coarse native grid -> medium refined grid -> fine refined grid):
      - R1: (nx0, nz0) -> (nx0+16, round(nz0*(nx0+16)/nx0)) -> (nx0+32, round(nz0*(nx0+32)/nx0))
      - R2: (48, 28) -> (72, 42) -> (96, 56)
      - R3P: (28, 32) -> (42, 48) -> (56, 64)
    """
    fam = str(route_spec["route_family"])
    kw = route_spec["kwargs"]
    if fam == "R1":
        nx0 = int(kw["nx_tot"])
        nz0 = int(kw["nz"])
        return (
            ("coarse", nx0, nz0),
            ("medium", nx0 + 16, int(round(nz0 * (nx0 + 16) / nx0))),
            ("fine", nx0 + 32, int(round(nz0 * (nx0 + 32) / nx0))),
        )
    if fam == "R2":
        nx0 = int(kw.get("nx_override", 48))
        nz0 = int(kw.get("nz_override", 28))
        return (
            ("coarse", nx0, nz0),
            ("medium", int(round(nx0 * 1.5)), int(round(nz0 * 1.5))),
            ("fine", nx0 * 2, nz0 * 2),
        )
    if fam == "R3P":
        nx0 = int(kw.get("nx", 28))
        nz0 = int(kw.get("nz", 32))
        return (
            ("coarse", nx0, nz0),
            ("medium", int(round(nx0 * 1.5)), int(round(nz0 * 1.5))),
            ("fine", nx0 * 2, nz0 * 2),
        )
    raise ValueError(f"Unknown route_family for mesh refinement ladder: {fam!r}")


def _solve_nw08_grid_level_cached(
    openislet_root: Path,
    route_id: str,
    effective_spec: Dict[str, Any],
    *,
    vasc_scale: float,
    nx: int,
    nz: int,
    use_cache: bool = True,
    min_exact_scale_ratio: Fraction | None = None,
) -> Tuple[float, float]:
    """Solve a single refined grid level (nx, nx, nz) with process-wide memoization under `_FVM_SOLVER_LOCK`."""
    eff_p_bed = float(effective_spec["kwargs"]["bed_po2_mmhg"])
    ratio_key = (
        f"{min_exact_scale_ratio.numerator}/{min_exact_scale_ratio.denominator}"
        if min_exact_scale_ratio is not None
        else None
    )
    cache_key = (
        str(openislet_root.resolve()),
        str(route_id),
        eff_p_bed,
        float(vasc_scale),
        int(nx),
        int(nz),
        ratio_key,
    )
    if use_cache:
        with _FVM_SOLVER_LOCK:
            cached = _MESH_REFINEMENT_SOLVE_CACHE.get(cache_key)
            if cached is not None:
                return cached
    refined_spec = copy.deepcopy(effective_spec)
    fam = str(refined_spec["route_family"])
    if fam == "R1":
        refined_spec["kwargs"].update({"nx_tot": int(nx), "nz": int(nz)})
    elif fam == "R2":
        refined_spec["kwargs"].update({"nx_override": int(nx), "nz_override": int(nz)})
    else:
        refined_spec["kwargs"].update({"nx": int(nx), "nz": int(nz)})
    _res, face_raw, verified_pb = _execute_single_3d_fvm_vascular_scaled_solve_with_meta(
        openislet_root,
        refined_spec,
        vasc_scale=vasc_scale,
        min_exact_scale_ratio=min_exact_scale_ratio,
    )
    out = (float(face_raw), float(verified_pb))
    if use_cache:
        with _FVM_SOLVER_LOCK:
            _MESH_REFINEMENT_SOLVE_CACHE[cache_key] = out
    return out


def _adjudicate_nw08_three_grid_convergence(
    f3: float,
    f2: float,
    f1: float,
    ladder: Tuple[Tuple[str, int, int], Tuple[str, int, int], Tuple[str, int, int]],
    *,
    band_mmhg: List[float] | None = None,
    near_floor: bool = True,
    floor_mmhg: float = CANONICAL_NW08_PO2_FLOOR_MMHG,
    fs: float = NW08_MESH_CONVERGENCE_SAFETY_FACTOR_FS,
) -> Dict[str, Any]:
    """
    Pure 3-grid numerical convergence adjudication helper (NASA / Roache GCI & ASME V&V-20; R14-B1 + R15-B2).
    NEVER raises observed convergence order `p_obs` UP to `0.5`: any monotone sequence with
    sub-asymptotic slow order (`p_obs < 0.5`), non-positive/unverifiable order, extreme
    super-convergence (`p_obs > 2.5`), or non-asymptotic movement toward `15.0 mmHg` routes
    strictly fail-closed to `HOLD` (`HOLD_NW08_MESH_CONVERGENCE_UNQUALIFIED_SLOW_OR_NON_ASYMPTOTIC_ORDER`)
    with `interval_valid = False` and NO claimed clearance bound!
    """
    (c_lvl, c_nx, c_nz), (m_lvl, m_nx, m_nz), (f_lvl, f_nx, f_nz) = ladder
    floor_val = float(floor_mmhg)
    eff_band = list(band_mmhg) if band_mmhg is not None else [
        floor_val - NW08_MESH_CONVERGENCE_TRIGGER_BAND_MMHG,
        floor_val + NW08_MESH_CONVERGENCE_TRIGGER_BAND_MMHG,
    ]
    h3 = (float(c_nx) * float(c_nx) * float(c_nz)) ** (-1.0 / 3.0)
    h2 = (float(m_nx) * float(m_nx) * float(m_nz)) ** (-1.0 / 3.0)
    h1 = (float(f_nx) * float(f_nx) * float(f_nz)) ** (-1.0 / 3.0)
    r32 = h3 / h2
    r21 = h2 / h1

    if not (
        math.isfinite(f3)
        and math.isfinite(f2)
        and math.isfinite(f1)
        and math.isfinite(r32)
        and math.isfinite(r21)
        and r32 > 1.0
        and r21 > 1.0
    ):
        return {
            "policy_version": NW08_MESH_CONVERGENCE_POLICY_VERSION,
            "near_floor_trigger_band_mmhg": eff_band,
            "safety_factor_fs": fs,
            "admissible_asymptotic_order_range_p": [
                NW08_MESH_CONVERGENCE_MIN_ADMISSIBLE_ORDER_P,
                NW08_MESH_CONVERGENCE_MAX_ADMISSIBLE_ORDER_P,
            ],
            "formal_order_cap_p": NW08_MESH_CONVERGENCE_FORMAL_ORDER_P,
            "triggered_by_near_floor_band": near_floor,
            "executed": True,
            "grids_run": 3,
            "fine_grid_skipped_already_straddling": False,
            "grid_ladder": [
                {"level": c_lvl, "grid": [c_nx, c_nx, c_nz], "h_rel": round(h3 / h1, 6), "face_min_mmhg_unrounded": f3},
                {"level": m_lvl, "grid": [m_nx, m_nx, m_nz], "h_rel": round(h2 / h1, 6), "face_min_mmhg_unrounded": f2},
                {"level": f_lvl, "grid": [f_nx, f_nx, f_nz], "h_rel": 1.0, "face_min_mmhg_unrounded": f1},
            ],
            "refinement_ratios": {"r32": round(r32, 6), "r21": round(r21, 6)},
            "convergence_regime": "INVALID_OR_NONFINITE_GRID_VALUES_HOLD",
            "mesh_uncertainty_status": NW08_MESH_STATUS_THREE_GRID_INVALID_HOLD,
            "observed_order_p_raw": None,
            "apparent_order_p": None,
            "order_qualified": False,
            "interval_valid": False,
            "richardson_extrapolated_mmhg": None,
            "grid_min_mmhg": None,
            "grid_max_mmhg": None,
            "grid_spread_mmhg": None,
            "fine_grid_face_min_mmhg_unrounded": f1 if math.isfinite(f1) else None,
            "discretization_uncertainty_mmhg": None,
            "conservative_po2_lower_bound_mmhg": None,
            "conservative_po2_upper_bound_mmhg": None,
            "straddles_canonical_15mmhg_floor": None,
            "mesh_convergence_resolved": False,
            "hold_reason_token": NW08_HOLD_TOKEN_UNQUALIFIED_ORDER,
            "verdict_from_mesh_policy": "HOLD",
        }

    f_min = min(f3, f2, f1)
    f_max = max(f3, f2, f1)
    spread = f_max - f_min
    eps21 = f1 - f2
    eps32 = f2 - f3
    direct_straddle = bool(f_min < floor_val <= f_max)

    p_obs_raw: float | None = None
    p_app: float | None = None
    f_ext: float | None = None
    u_num: float | None = None
    l_bound: float | None = None
    u_bound: float | None = None
    interval_valid: bool = False
    order_qualified: bool = False
    mesh_uncertainty_status: str = NW08_MESH_STATUS_THREE_GRID_UNQUALIFIED_ORDER_HOLD

    if spread == 0.0:
        regime = "CONVERGED_EXACT"
        u_num = 0.0
        l_bound = f1
        u_bound = f1
        f_ext = f1
        interval_valid = True
        order_qualified = True
        mesh_uncertainty_status = NW08_MESH_STATUS_THREE_GRID_EXACT_ZERO_SPREAD
    elif eps21 * eps32 < 0.0:
        regime = "OSCILLATORY_ASME_VV20_HALF_RANGE"
        f_mid = 0.5 * (f_min + f_max)
        u_num = fs * 0.5 * spread
        l_bound = f_mid - u_num
        u_bound = f_mid + u_num
        interval_valid = True
        order_qualified = False
        mesh_uncertainty_status = NW08_MESH_STATUS_THREE_GRID_OSCILLATORY_BOUND
    elif eps21 * eps32 > 0.0 and abs(eps21) < abs(eps32):
        target_log = math.log(abs(eps32) / abs(eps21))
        ln_r32 = math.log(r32)
        ln_r21 = math.log(r21)

        def _gci_order_lhs(p_val: float) -> float:
            # Numerically stable for arbitrarily small p_val > 0 via expm1 (avoids r^p - 1 cancellation).
            return p_val * ln_r21 + math.log(math.expm1(p_val * ln_r32) / math.expm1(p_val * ln_r21))

        lhs_zero = math.log(ln_r32 / ln_r21)
        lhs_min = _gci_order_lhs(NW08_MESH_CONVERGENCE_MIN_ADMISSIBLE_ORDER_P)
        lhs_max = _gci_order_lhs(NW08_MESH_CONVERGENCE_MAX_ADMISSIBLE_ORDER_P)

        if target_log <= lhs_zero:
            # No positive algebraic convergence order p > 0 exists on (r32, r21) (e.g., logarithmic/sub-power drift).
            regime = "MONOTONE_SUB_ASYMPTOTIC_NONPOSITIVE_ORDER_HOLD"
            p_obs_raw = None
            p_app = None
            interval_valid = False
            order_qualified = False
            mesh_uncertainty_status = NW08_MESH_STATUS_THREE_GRID_UNQUALIFIED_ORDER_HOLD
        elif target_log < lhs_min:
            # R15-B2: Sub-asymptotic slow convergence (0 < p_obs < 0.5). NEVER clamp p UP to 0.5!
            # Solve the true observed order for audit transparency and fail closed to HOLD.
            p_tiny = 1e-12
            if target_log <= _gci_order_lhs(p_tiny):
                p_obs_raw = 0.0
            else:
                p_lo, p_hi = p_tiny, NW08_MESH_CONVERGENCE_MIN_ADMISSIBLE_ORDER_P
                for _ in range(80):
                    p_mid = 0.5 * (p_lo + p_hi)
                    if _gci_order_lhs(p_mid) < target_log:
                        p_lo = p_mid
                    else:
                        p_hi = p_mid
                p_obs_raw = 0.5 * (p_lo + p_hi)
            p_app = p_obs_raw
            regime = "MONOTONE_SUB_ASYMPTOTIC_SLOW_ORDER_HOLD"
            interval_valid = False
            order_qualified = False
            mesh_uncertainty_status = NW08_MESH_STATUS_THREE_GRID_UNQUALIFIED_ORDER_HOLD
        elif target_log <= lhs_max:
            p_lo = NW08_MESH_CONVERGENCE_MIN_ADMISSIBLE_ORDER_P
            p_hi = NW08_MESH_CONVERGENCE_MAX_ADMISSIBLE_ORDER_P
            for _ in range(64):
                p_mid = 0.5 * (p_lo + p_hi)
                if _gci_order_lhs(p_mid) < target_log:
                    p_lo = p_mid
                else:
                    p_hi = p_mid
            p_obs_raw = 0.5 * (p_lo + p_hi)
            if p_obs_raw <= NW08_MESH_CONVERGENCE_FORMAL_ORDER_P:
                p_eff = p_obs_raw
                regime = "MONOTONE_CONVERGING_GCI"
            else:
                # Conservatively cap DOWN to formal 2nd-order accuracy (widens GCI; never shrinks).
                p_eff = NW08_MESH_CONVERGENCE_FORMAL_ORDER_P
                regime = "MONOTONE_CONVERGING_GCI_FORMAL_ORDER_CAPPED"
            p_app = p_eff
            denom = math.expm1(p_eff * ln_r21)
            gci_fine = fs * abs(eps21) / denom
            f_ext = f1 + eps21 / denom
            u_num = gci_fine
            l_bound = min(f_min, f1 - gci_fine)
            u_bound = max(f_max, f1 + gci_fine)
            interval_valid = True
            order_qualified = True
            mesh_uncertainty_status = NW08_MESH_STATUS_THREE_GRID_ASYMPTOTIC_GCI_QUALIFIED
        else:
            # Extreme super-convergence (p_obs > 2.5): potential pre-asymptotic error cancellation.
            if target_log <= _gci_order_lhs(100.0):
                p_lo, p_hi = NW08_MESH_CONVERGENCE_MAX_ADMISSIBLE_ORDER_P, 100.0
                for _ in range(64):
                    p_mid = 0.5 * (p_lo + p_hi)
                    if _gci_order_lhs(p_mid) < target_log:
                        p_lo = p_mid
                    else:
                        p_hi = p_mid
                p_obs_raw = 0.5 * (p_lo + p_hi)
            else:
                p_obs_raw = None
            p_app = p_obs_raw
            regime = "MONOTONE_SUPERCONVERGENT_NON_ASYMPTOTIC_HOLD"
            interval_valid = False
            order_qualified = False
            mesh_uncertainty_status = NW08_MESH_STATUS_THREE_GRID_UNQUALIFIED_ORDER_HOLD
    else:
        if direct_straddle:
            regime = "MONOTONE_NON_ASYMPTOTIC_STRADDLES_FLOOR"
            u_num = fs * spread
            l_bound = min(f_min, f1 - u_num)
            u_bound = max(f_max, f1 + u_num)
            interval_valid = False
            order_qualified = False
            mesh_uncertainty_status = NW08_MESH_STATUS_THREE_GRID_NON_ASYMPTOTIC_HOLD
        elif (f_min >= floor_val and eps32 > 0.0 and eps21 > 0.0) or (
            f_max < floor_val and eps32 < 0.0 and eps21 < 0.0
        ):
            # Monotone strictly moving AWAY from 15.0 mmHg with conservative full-spread envelope
            # (`f1 - Fs*spread = f3 - 0.25*(f1-f3) < f3` when moving upward above 15.0 mmHg).
            regime = "MONOTONE_NON_ASYMPTOTIC_AWAY_FROM_FLOOR_CONSERVATIVE"
            u_num = fs * spread
            l_bound = min(f_min, f1 - u_num)
            u_bound = max(f_max, f1 + u_num)
            interval_valid = True
            order_qualified = False
            mesh_uncertainty_status = NW08_MESH_STATUS_THREE_GRID_MONOTONE_FALLBACK
        else:
            # Non-shrinking / accelerating drift TOWARD 15.0 mmHg or stalled zero step with spread > 0:
            # fail closed to HOLD with no claimed clearance bound.
            regime = "MONOTONE_NON_ASYMPTOTIC_TOWARD_FLOOR_HOLD"
            interval_valid = False
            order_qualified = False
            mesh_uncertainty_status = NW08_MESH_STATUS_THREE_GRID_NON_ASYMPTOTIC_HOLD

    hold_tok: str | None = None
    straddles: bool | None
    if (not interval_valid) or (l_bound is None) or (u_bound is None):
        verdict = "HOLD"
        if direct_straddle:
            straddles = True
            hold_tok = NW08_HOLD_TOKEN_STRADDLES_FLOOR
        else:
            straddles = None
            hold_tok = NW08_HOLD_TOKEN_UNQUALIFIED_ORDER
    elif l_bound >= floor_val and f_min >= floor_val:
        verdict = "PASS"
        straddles = False
    elif u_bound < floor_val and f_max < floor_val:
        verdict = "FAIL"
        straddles = False
    else:
        verdict = "HOLD"
        straddles = True
        hold_tok = NW08_HOLD_TOKEN_STRADDLES_FLOOR

    return {
        "policy_version": NW08_MESH_CONVERGENCE_POLICY_VERSION,
        "near_floor_trigger_band_mmhg": eff_band,
        "safety_factor_fs": fs,
        "admissible_asymptotic_order_range_p": [
            NW08_MESH_CONVERGENCE_MIN_ADMISSIBLE_ORDER_P,
            NW08_MESH_CONVERGENCE_MAX_ADMISSIBLE_ORDER_P,
        ],
        "formal_order_cap_p": NW08_MESH_CONVERGENCE_FORMAL_ORDER_P,
        "triggered_by_near_floor_band": near_floor,
        "executed": True,
        "grids_run": 3,
        "fine_grid_skipped_already_straddling": False,
        "grid_ladder": [
            {"level": c_lvl, "grid": [c_nx, c_nx, c_nz], "h_rel": round(h3 / h1, 6), "face_min_mmhg_unrounded": f3},
            {"level": m_lvl, "grid": [m_nx, m_nx, m_nz], "h_rel": round(h2 / h1, 6), "face_min_mmhg_unrounded": f2},
            {"level": f_lvl, "grid": [f_nx, f_nx, f_nz], "h_rel": 1.0, "face_min_mmhg_unrounded": f1},
        ],
        "refinement_ratios": {"r32": round(r32, 6), "r21": round(r21, 6)},
        "convergence_regime": regime,
        "mesh_uncertainty_status": mesh_uncertainty_status,
        "observed_order_p_raw": round(p_obs_raw, 6) if p_obs_raw is not None else None,
        "apparent_order_p": round(p_app, 6) if p_app is not None else None,
        "order_qualified": order_qualified,
        "interval_valid": interval_valid,
        "richardson_extrapolated_mmhg": round(f_ext, 8) if f_ext is not None else None,
        "grid_min_mmhg": f_min,
        "grid_max_mmhg": f_max,
        "grid_spread_mmhg": spread,
        "fine_grid_face_min_mmhg_unrounded": f1,
        "discretization_uncertainty_mmhg": u_num,
        "conservative_po2_lower_bound_mmhg": l_bound,
        "conservative_po2_upper_bound_mmhg": u_bound,
        "straddles_canonical_15mmhg_floor": straddles,
        "mesh_convergence_resolved": bool(verdict in ("PASS", "FAIL")),
        "hold_reason_token": hold_tok,
        "verdict_from_mesh_policy": verdict,
    }


def _evaluate_nw08_mesh_convergence(
    openislet_root: Path,
    route_id: str,
    effective_spec: Dict[str, Any],
    *,
    vasc_scale: float,
    native_coarse_face_mmhg: float,
    verified_p_bed: float,
    force_check: bool = False,
    min_exact_scale_ratio: Fraction | None = None,
) -> Dict[str, Any]:
    """
    R14-B1 + R15-B2 + R17-M2 Predeclared 3-grid numerical resolution / error policy (NASA / Roache GCI & ASME V&V-20):
      - Automatically executes the predeclared 3-grid ladder whenever `f_coarse` lies inside the
        route-family near-floor band (`R1 [14.88, 15.25]`, `R2 [14.75, 15.25]`, `R3P [14.70, 15.30] mmHg`)
        or `force_check=True`, with a recorded 2-grid early-stop exception (`grids_run=2`,
        `fine_grid_skipped_already_straddling=True`,
        `mesh_uncertainty_status=TWO_GRID_DIRECT_FLOOR_CROSSING_HOLD`) when
        `force_check=False` and the coarse and medium grids already directly straddle `15.0 mmHg`
        (an irreversible crossing no fine grid can eliminate; pass `force_check=True` for full 3-grid replay).
      - Computes a conservative discretization error interval `[L_num, U_hi]` with safety factor Fs = 1.25:
          * Oscillatory (`(f1 - f2) * (f2 - f3) < 0`): ASME V&V-20 oscillatory half-range
            `U_num = Fs * 0.5 * (f_max - f_min)` centered at `0.5 * (f_min + f_max)`, enclosing `[f_min, f_max]`.
          * Monotone converging (`(f1 - f2) * (f2 - f3) > 0` and `|f1 - f2| < |f2 - f3|`): solves the exact
            observed order `p_obs` on `(r32, r21)`. NEVER clamps `p_obs` upward to `0.5`!
            - Qualified Roache GCI requires `0.5 <= p_obs <= 2.5` (with mild super-convergence `2.0 < p_obs <= 2.5`
              conservatively capped DOWN to formal order `2.0`, widening GCI).
            - Sub-asymptotic slow order (`p_obs < 0.5`), non-positive/unverifiable order, or extreme
              super-convergence (`p_obs > 2.5`) routes fail-closed to `HOLD`
              (`HOLD_NW08_MESH_CONVERGENCE_UNQUALIFIED_SLOW_OR_NON_ASYMPTOTIC_ORDER`, `interval_valid = False`).
          * Monotone non-shrinking / non-asymptotic: strictly moving AWAY from `15.0 mmHg` applies conservative
            full-spread bounds `Fs * (f_max - f_min)`; direct straddling or accelerating/stalled drift TOWARD
            `15.0 mmHg` routes fail-closed to `HOLD`.
      - Adjudication against immutable `15.0 mmHg` floor:
          * `PASS` iff `interval_valid` and `L_num >= 15.0` and `f_min >= 15.0`
          * `FAIL` iff `interval_valid` and `U_hi < 15.0` and `f_max < 15.0`
          * `HOLD` (`HOLD_NW08_MESH_CONVERGENCE_STRADDLES_15MMHG_FLOOR` or
            `HOLD_NW08_MESH_CONVERGENCE_UNQUALIFIED_SLOW_OR_NON_ASYMPTOTIC_ORDER`) otherwise!
    """
    ladder = _get_nw08_mesh_refinement_ladder(effective_spec)
    c_lvl, c_nx, c_nz = ladder[0]
    m_lvl, m_nx, m_nz = ladder[1]
    f_lvl, f_nx, f_nz = ladder[2]
    fam = str(effective_spec["route_family"])
    lo_delta, hi_delta = NW08_MESH_CONVERGENCE_TRIGGER_BANDS_BY_FAMILY.get(
        fam, (-NW08_MESH_CONVERGENCE_TRIGGER_BAND_MMHG, NW08_MESH_CONVERGENCE_TRIGGER_BAND_MMHG)
    )
    band_lo_mmhg = CANONICAL_NW08_PO2_FLOOR_MMHG + lo_delta
    band_hi_mmhg = CANONICAL_NW08_PO2_FLOOR_MMHG + hi_delta
    near_floor = bool(band_lo_mmhg <= native_coarse_face_mmhg <= band_hi_mmhg)
    if (not near_floor) and (not force_check):
        decisive_pass = _passes_unrounded_15mmhg_floor(native_coarse_face_mmhg)
        return {
            "policy_version": NW08_MESH_CONVERGENCE_POLICY_VERSION,
            "near_floor_trigger_band_mmhg": [band_lo_mmhg, band_hi_mmhg],
            "safety_factor_fs": NW08_MESH_CONVERGENCE_SAFETY_FACTOR_FS,
            "admissible_asymptotic_order_range_p": [
                NW08_MESH_CONVERGENCE_MIN_ADMISSIBLE_ORDER_P,
                NW08_MESH_CONVERGENCE_MAX_ADMISSIBLE_ORDER_P,
            ],
            "formal_order_cap_p": NW08_MESH_CONVERGENCE_FORMAL_ORDER_P,
            "triggered_by_near_floor_band": False,
            "executed": False,
            "grids_run": 1,
            "grid_ladder": [
                {"level": c_lvl, "grid": [c_nx, c_nx, c_nz], "face_min_mmhg_unrounded": native_coarse_face_mmhg}
            ],
            "predeclared_refinement_grids": [
                [c_nx, c_nx, c_nz],
                [m_nx, m_nx, m_nz],
                [f_nx, f_nx, f_nz],
            ],
            "convergence_regime": "NOT_REQUIRED_FAR_FROM_FLOOR",
            "mesh_uncertainty_status": (
                NW08_MESH_STATUS_SINGLE_GRID_POLICY_PASS
                if decisive_pass
                else NW08_MESH_STATUS_SINGLE_GRID_POLICY_FAIL
            ),
            "observed_order_p_raw": None,
            "apparent_order_p": None,
            "order_qualified": False,
            "interval_valid": False,
            "richardson_extrapolated_mmhg": None,
            "grid_min_mmhg": native_coarse_face_mmhg,
            "grid_max_mmhg": native_coarse_face_mmhg,
            "grid_spread_mmhg": 0.0,
            "fine_grid_face_min_mmhg_unrounded": None,
            "discretization_uncertainty_mmhg": None,
            "conservative_po2_lower_bound_mmhg": None,
            "conservative_po2_upper_bound_mmhg": None,
            "straddles_canonical_15mmhg_floor": False,
            "mesh_convergence_resolved": True,
            "hold_reason_token": None,
            "verdict_from_mesh_policy": "PASS" if decisive_pass else "FAIL",
        }

    f3 = float(native_coarse_face_mmhg)
    f2, _pb2 = _solve_nw08_grid_level_cached(
        openislet_root,
        route_id,
        effective_spec,
        vasc_scale=vasc_scale,
        nx=m_nx,
        nz=m_nz,
        min_exact_scale_ratio=min_exact_scale_ratio,
    )
    floor_val = CANONICAL_NW08_PO2_FLOOR_MMHG
    # Fast exact early-exit when coarse and medium grids already directly straddle 15.0 mmHg
    # (unless full 3-grid diagnostic replay is explicitly forced via force_check=True):
    # no fine-grid value can eliminate min(f3, f2, f1) < 15.0 <= max(f3, f2, f1)!
    direct_c_to_m_straddle = bool(min(f3, f2) < floor_val <= max(f3, f2))
    if direct_c_to_m_straddle and (not force_check):
        f_min_2 = min(f3, f2)
        f_max_2 = max(f3, f2)
        spread_2 = f_max_2 - f_min_2
        return {
            "policy_version": NW08_MESH_CONVERGENCE_POLICY_VERSION,
            "near_floor_trigger_band_mmhg": [band_lo_mmhg, band_hi_mmhg],
            "safety_factor_fs": NW08_MESH_CONVERGENCE_SAFETY_FACTOR_FS,
            "admissible_asymptotic_order_range_p": [
                NW08_MESH_CONVERGENCE_MIN_ADMISSIBLE_ORDER_P,
                NW08_MESH_CONVERGENCE_MAX_ADMISSIBLE_ORDER_P,
            ],
            "formal_order_cap_p": NW08_MESH_CONVERGENCE_FORMAL_ORDER_P,
            "triggered_by_near_floor_band": near_floor,
            "executed": True,
            "grids_run": 2,
            "fine_grid_skipped_already_straddling": True,
            "grid_ladder": [
                {"level": c_lvl, "grid": [c_nx, c_nx, c_nz], "face_min_mmhg_unrounded": f3},
                {"level": m_lvl, "grid": [m_nx, m_nx, m_nz], "face_min_mmhg_unrounded": f2},
            ],
            "predeclared_refinement_grids": [
                [c_nx, c_nx, c_nz],
                [m_nx, m_nx, m_nz],
                [f_nx, f_nx, f_nz],
            ],
            "convergence_regime": "DIRECT_FLOOR_CROSSING_COARSE_TO_MEDIUM",
            "mesh_uncertainty_status": NW08_MESH_STATUS_TWO_GRID_DIRECT_CROSSING_HOLD,
            "observed_order_p_raw": None,
            "apparent_order_p": None,
            "order_qualified": False,
            "interval_valid": False,
            "richardson_extrapolated_mmhg": None,
            "grid_min_mmhg": f_min_2,
            "grid_max_mmhg": f_max_2,
            "grid_spread_mmhg": spread_2,
            "fine_grid_face_min_mmhg_unrounded": None,
            "discretization_uncertainty_mmhg": NW08_MESH_CONVERGENCE_SAFETY_FACTOR_FS * spread_2,
            "conservative_po2_lower_bound_mmhg": f_min_2,
            "conservative_po2_upper_bound_mmhg": f_max_2,
            "straddles_canonical_15mmhg_floor": True,
            "mesh_convergence_resolved": False,
            "hold_reason_token": NW08_HOLD_TOKEN_STRADDLES_FLOOR,
            "verdict_from_mesh_policy": "HOLD",
        }

    f1, _pb1 = _solve_nw08_grid_level_cached(
        openislet_root,
        route_id,
        effective_spec,
        vasc_scale=vasc_scale,
        nx=f_nx,
        nz=f_nz,
        min_exact_scale_ratio=min_exact_scale_ratio,
    )
    return _adjudicate_nw08_three_grid_convergence(
        f3,
        f2,
        f1,
        ladder,
        band_mmhg=[band_lo_mmhg, band_hi_mmhg],
        near_floor=near_floor,
        floor_mmhg=floor_val,
        fs=NW08_MESH_CONVERGENCE_SAFETY_FACTOR_FS,
    )


def dispatch_and_solve_nw08_measured_ocr(
    route_id: str,
    measured_ocr: float,
    uncertainty_se: float,
    *,
    openislet_root: Path | None = None,
    baseline_min_face_mmhg: float | None = None,
    baseline_vasc_ocr_mult: float | None = None,
    p_bed_mmhg: float | None = None,
    local_3d_slope_mmhg_per_pct: float | None = None,
    z_one_sided_95: float | None = None,
    floor_mmhg: float = CANONICAL_NW08_PO2_FLOOR_MMHG,
    always_solve_3d: bool = False,
    ocr_uncertainty_model: str | None = None,
    ocr_replicates_n: int | None = None,
    ocr_degrees_of_freedom: int | None = None,
    ocr_uncertainty_provenance: str | None = None,
    measured_ocr_u95_override: float | None = None,
    force_mesh_convergence_check: bool = False,
    _require_explicit_model_for_positive_se: bool = False,
) -> Dict[str, Any]:
    """
    B7 / R03-B2 / R04-B5 / R05-B2 / R14-B1..B3 Live Executable 3D FVM Solver Dispatch Entry Point:
      1. Validates `route_id` against the canonical 8-route NW-08 catalog and validates any
         caller-supplied boundary-pressure (`p_bed_mmhg`) or baseline overrides fail-closed.
      2. Enforces explicit inferential uncertainty provenance whenever `uncertainty_se > 0`
         (exact Student-t critical value `t_{0.95, df}` for `STUDENT_T_ESTIMATED_SE`, scoped
         `KNOWN_SIGMA_NORMAL` with external calibration provenance, or `INDEPENDENT_JUSTIFIED_UPPER_BOUND`;
         rejects bare undeclared positive SE fail-closed; R14-B2).
      3. Carries `p_bed_mmhg` consistently into BOTH the preliminary screen AND the actual
         route-specific 3D FVM solver kwargs (`bed_po2_mmhg`), and computes the exact native
         float64 unrounded baseline directly from the 3D FVM solver at `(eff_p_bed, eff_base_ocr)`
         on every call path (rejecting stale mismatched caller baselines).
      4. Executes every native 3D FVM solve inside an isolated child Python subprocess bound strictly
         to `openislet_root.resolve() / "scripts"` (verifying `Path(mod.__file__).resolve().is_relative_to(resolved_root)`
         for all loaded solver modules and reporting `resolved_solver_module_origins` without mutating
         parent `sys.path`, `sys.modules`, or Layer-4 callbacks; R18-B1 + R18-B2), while retaining the
         process-wide `_FVM_SOLVER_LOCK` for thread-safe root-keyed cache access (R14-B3).
      5. Enforces the predefined 3-grid numerical resolution / error policy (NASA / Roache GCI &
         ASME V&V-20; R14-B1 + R15-B2 + R17-M2): whenever a live solve lies inside the route-family
         near-floor band (`R1 [14.88, 15.25]`, `R2 [14.75, 15.25]`, `R3P [14.70, 15.30] mmHg`; or
         `force_mesh_convergence_check=True`), executes the predeclared 3-grid ladder — with the
         recorded 2-grid early-stop exception (`grids_run=2`,
         `fine_grid_skipped_already_straddling=True`,
         `mesh_uncertainty_status=TWO_GRID_DIRECT_FLOOR_CROSSING_HOLD`) when
         `force_mesh_convergence_check=False` and the coarse and medium grids already directly
         straddle `15.0 mmHg` (`min(f3, f2) < 15.0 <= max(f3, f2)`), since no fine-grid solve can
         remove that irreversible floor crossing (pass `force_mesh_convergence_check=True` to force
         full 3-grid diagnostic replay). Routes any threshold-straddling case to unresolved `HOLD`
         (`HOLD_NW08_MESH_CONVERGENCE_STRADDLES_15MMHG_FLOOR`, exit 2) and any slow/non-asymptotic
         order case (`p_obs < 0.5`, non-positive order, `p_obs > 2.5`, or non-asymptotic drift toward
         `15.0 mmHg`) to unresolved `HOLD`
         (`HOLD_NW08_MESH_CONVERGENCE_UNQUALIFIED_SLOW_OR_NON_ASYMPTOTIC_ORDER`, exit 2,
         `interval_valid=False`) before any release authorization!
    """
    resolved_root = openislet_root.resolve() if openislet_root is not None else _resolve_roots(None, None)[0]
    catalog = _build_nw08_route_catalog(resolved_root)
    if not isinstance(route_id, str) or route_id not in catalog:
        raise ValueError(f"Unrecognized NW-08 canonical route_id: {route_id!r}; expected one of {sorted(catalog.keys())}")
    spec = catalog[route_id]
    catalog_default_p_bed = float(spec["p_bed_mmhg"])
    catalog_default_p_bed_dec = Decimal(str(catalog_default_p_bed))

    f_measured_ocr, dec_measured_ocr = _parse_nw08_boundary_scalar(
        measured_ocr, "measured_ocr", strictly_positive=True
    )
    f_uncertainty_se, dec_uncertainty_se = _parse_nw08_boundary_scalar(
        uncertainty_se, "uncertainty_se", non_negative=True
    )
    diag_floor, dec_diag_floor = _parse_nw08_boundary_scalar(
        floor_mmhg, "floor_mmhg", strictly_positive=True
    )
    unc_info = _resolve_nw08_ocr_uncertainty_bound(
        f_measured_ocr=f_measured_ocr,
        dec_measured_ocr=dec_measured_ocr,
        f_uncertainty_se=f_uncertainty_se,
        dec_uncertainty_se=dec_uncertainty_se,
        z_one_sided_95=z_one_sided_95,
        ocr_uncertainty_model=ocr_uncertainty_model,
        ocr_replicates_n=ocr_replicates_n,
        ocr_degrees_of_freedom=ocr_degrees_of_freedom,
        ocr_uncertainty_provenance=ocr_uncertainty_provenance,
        measured_ocr_u95_override=measured_ocr_u95_override,
        require_explicit_model_for_positive_se=_require_explicit_model_for_positive_se,
    )

    if p_bed_mmhg is not None:
        eff_p_bed, dec_p_bed = _parse_nw08_boundary_scalar(p_bed_mmhg, "p_bed_mmhg", strictly_positive=True)
    else:
        eff_p_bed = catalog_default_p_bed
        dec_p_bed = catalog_default_p_bed_dec

    with _clean_dec_ctx(120, ROUND_HALF_EVEN):
        canon_floor_dec = Decimal(str(CANONICAL_NW08_PO2_FLOOR_MMHG))
        if (
            dec_p_bed <= canon_floor_dec
            or dec_p_bed <= dec_diag_floor
            or eff_p_bed <= CANONICAL_NW08_PO2_FLOOR_MMHG
            or eff_p_bed <= diag_floor
        ):
            raise ValueError(
                f"Require p_bed_mmhg ({eff_p_bed}) > max(canonical {CANONICAL_NW08_PO2_FLOOR_MMHG}, floor_mmhg {diag_floor})"
            )

    catalog_default_base_ocr = float(spec["baseline_shared_ocr"])
    catalog_default_base_ocr_dec = Decimal(str(catalog_default_base_ocr))
    if baseline_vasc_ocr_mult is not None:
        eff_base_ocr, dec_base_ocr = _parse_nw08_boundary_scalar(
            baseline_vasc_ocr_mult, "baseline_vasc_ocr_mult", strictly_positive=True
        )
    else:
        eff_base_ocr = catalog_default_base_ocr
        dec_base_ocr = catalog_default_base_ocr_dec

    ocr_u95 = unc_info["ocr_u95_float"]
    ocr_u95_exact = unc_info["ocr_u95_dec"]
    vasc_scale, effective_solver_ocr_f64 = _compute_conservative_upper_float64_vasc_scale(
        ocr_u95_exact,
        catalog_default_base_ocr,
        catalog_default_base_ocr_dec,
    )
    min_exact_scale_ratio = Fraction(ocr_u95_exact) / Fraction(catalog_default_base_ocr_dec)
    if not math.isfinite(vasc_scale) or vasc_scale <= 0.0:
        raise ValueError("Computed vascular voxel scale factor overflowed IEEE-754 float64 range")

    # R09-B3 + R12-B2: Exact IEEE-754 float64 AND exact Decimal canonical equality (ZERO deadband!) so ANY
    # single-ULP or sub-ULP deviation in p_bed_mmhg or baseline_vasc_ocr_mult triggers native 3D FVM solve.
    with _clean_dec_ctx(120, ROUND_HALF_EVEN):
        p_bed_override_applied = bool(eff_p_bed != catalog_default_p_bed or dec_p_bed != catalog_default_p_bed_dec)
        baseline_ocr_override_applied = bool(
            eff_base_ocr != catalog_default_base_ocr or dec_base_ocr != catalog_default_base_ocr_dec
        )
    any_override_applied = bool(p_bed_override_applied or baseline_ocr_override_applied)
    effective_spec = copy.deepcopy(spec)
    effective_spec["p_bed_mmhg"] = eff_p_bed
    effective_spec["kwargs"]["bed_po2_mmhg"] = eff_p_bed

    # R04-B5 + R18-B2: ALWAYS compute & verify the true native float64 unrounded 3D FVM baseline AND
    # isolated subprocess module origins for the active (resolved_root, route_id, eff_p_bed, eff_base_ocr)
    # on EVERY call path — including default bed pressure!
    native_base_mmhg, base_iso_meta = _get_native_unrounded_baseline_mmhg_with_meta(
        resolved_root, route_id, effective_spec, eff_base_ocr
    )
    if baseline_min_face_mmhg is None:
        eff_base_mmhg = native_base_mmhg
        baseline_source = "native_3d_fvm_unrounded_float64"
    else:
        caller_base_mmhg, _dec_caller_base = _parse_nw08_boundary_scalar(
            baseline_min_face_mmhg, "baseline_min_face_mmhg", non_negative=False
        )
        if abs(caller_base_mmhg - native_base_mmhg) > 1e-3:
            raise ValueError(
                f"Caller-supplied baseline_min_face_mmhg={caller_base_mmhg} is inconsistent with native 3D FVM "
                f"baseline ({native_base_mmhg:.6f} mmHg) for route_id={route_id!r} at p_bed_mmhg={eff_p_bed}, "
                f"baseline_vasc_ocr_mult={eff_base_ocr}"
            )
        # Always adjudicate using the exact unrounded native float64 baseline after confirming caller consistency
        eff_base_mmhg = native_base_mmhg
        baseline_source = "caller_supplied_verified_against_native_3d_fvm_unrounded_float64"

    trig = evaluate_nw08_measured_ocr_trigger(
        route_id,
        dec_measured_ocr,
        dec_uncertainty_se,
        baseline_min_face_mmhg=eff_base_mmhg,
        baseline_vasc_ocr_mult=dec_base_ocr,
        p_bed_mmhg=dec_p_bed,
        local_3d_slope_mmhg_per_pct=local_3d_slope_mmhg_per_pct,
        z_one_sided_95=z_one_sided_95,
        floor_mmhg=dec_diag_floor,
        ocr_uncertainty_model=ocr_uncertainty_model,
        ocr_replicates_n=ocr_replicates_n,
        ocr_degrees_of_freedom=ocr_degrees_of_freedom,
        ocr_uncertainty_provenance=ocr_uncertainty_provenance,
        measured_ocr_u95_override=measured_ocr_u95_override,
        _require_explicit_model_for_positive_se=_require_explicit_model_for_positive_se,
    )

    # R08-B2 + R09-B3 + R14-B1: NEVER skip the live candidate 3D FVM solve outside a provably monotone,
    # zero-increase, far-from-floor canonical baseline domain (`eff_base_mmhg > 15.0 + hi_band`)!
    _lo_b, _hi_b = NW08_MESH_CONVERGENCE_TRIGGER_BANDS_BY_FAMILY.get(
        str(effective_spec["route_family"]),
        (-NW08_MESH_CONVERGENCE_TRIGGER_BAND_MMHG, NW08_MESH_CONVERGENCE_TRIGGER_BAND_MMHG),
    )
    base_far_from_floor = bool(eff_base_mmhg > (CANONICAL_NW08_PO2_FLOOR_MMHG + _hi_b))
    within_provably_monotone_no_increase_domain = bool(
        _passes_unrounded_15mmhg_floor(eff_base_mmhg)
        and base_far_from_floor
        and (ocr_u95_exact <= dec_base_ocr)
        and (not any_override_applied)
    )
    linear_screen_triggered = bool(trig["trigger_dispatched"])
    triggered_by_non_monotone_or_override_guard = bool(not within_provably_monotone_no_increase_domain)
    effective_trigger_dispatched = bool(linear_screen_triggered or triggered_by_non_monotone_or_override_guard)
    requires_candidate_3d_solve = bool(
        always_solve_3d or force_mesh_convergence_check or effective_trigger_dispatched
    )

    if not requires_candidate_3d_solve:
        ladder = _get_nw08_mesh_refinement_ladder(effective_spec)
        base_origins = dict(base_iso_meta.get("resolved_solver_module_paths") or {})
        base_relpaths = dict(base_iso_meta.get("resolved_solver_module_relpaths") or {})
        base_origins_ok = bool(
            base_origins
            and all(Path(p).resolve().is_relative_to(resolved_root) for p in base_origins.values())
        )
        return {
            **trig,
            "release_authorizing": False,
            "qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
            "physical_qualification_complete": False,
            "solver_isolation_mode": "ISOLATED_CHILD_SUBPROCESS",
            "resolved_solver_module_origins": base_origins,
            "resolved_solver_module_relpaths": base_relpaths,
            "all_solver_module_origins_within_repo_root": base_origins_ok,
            "native_solver_vascular_operand_audit": None,
            "solver_cleared_oxygen_floor_diagnostic": True,
            "nw08_oxygen_floor_adjudication_authoritative": True,
            "linear_screen_trigger_dispatched": linear_screen_triggered,
            "triggered_by_non_monotone_or_override_guard": False,
            "within_provably_monotone_no_increase_domain": True,
            "trigger_dispatched": False,
            "decision": "WITHIN_PROVABLY_MONOTONE_BASELINE_NO_INCREASE_DOMAIN",
            "catalog_default_p_bed_mmhg": catalog_default_p_bed,
            "effective_p_bed_mmhg": eff_p_bed,
            "p_bed_override_applied": p_bed_override_applied,
            "baseline_ocr_override_applied": baseline_ocr_override_applied,
            "any_parameter_override_applied": any_override_applied,
            "solver_p_bed_mmhg_verified": eff_p_bed,
            "baseline_source": baseline_source,
            "solver_executed": False,
            "solved_at_vascular_ocr_u95": round(ocr_u95, 6),
            "solved_at_vascular_ocr_u95_exact_dec": str(ocr_u95_exact),
            "vascular_voxel_scale_factor": round(vasc_scale, 6),
            "native_solver_vasc_scale_float64": vasc_scale,
            "native_solver_effective_vascular_ocr_float64": effective_solver_ocr_f64,
            "face_min_mmhg_unrounded": None,
            "face_min_mmhg": None,
            "canonical_floor_mmhg": CANONICAL_NW08_PO2_FLOOR_MMHG,
            "floor_mmhg": CANONICAL_NW08_PO2_FLOOR_MMHG,
            "margin_above_floor_unrounded_mmhg": None,
            "passes_15mmhg_floor_unrounded": True,
            "mesh_convergence_verification": {
                "policy_version": NW08_MESH_CONVERGENCE_POLICY_VERSION,
                "near_floor_trigger_band_mmhg": [
                    CANONICAL_NW08_PO2_FLOOR_MMHG + _lo_b,
                    CANONICAL_NW08_PO2_FLOOR_MMHG + _hi_b,
                ],
                "safety_factor_fs": NW08_MESH_CONVERGENCE_SAFETY_FACTOR_FS,
                "admissible_asymptotic_order_range_p": [
                    NW08_MESH_CONVERGENCE_MIN_ADMISSIBLE_ORDER_P,
                    NW08_MESH_CONVERGENCE_MAX_ADMISSIBLE_ORDER_P,
                ],
                "formal_order_cap_p": NW08_MESH_CONVERGENCE_FORMAL_ORDER_P,
                "triggered_by_near_floor_band": False,
                "executed": False,
                "grids_run": 1,
                "predeclared_refinement_grids": [[nx, nx, nz] for _lvl, nx, nz in ladder],
                "convergence_regime": "NOT_REQUIRED_FAR_FROM_FLOOR_MONOTONE_BASELINE",
                "mesh_uncertainty_status": NW08_MESH_STATUS_SINGLE_GRID_POLICY_PASS,
                "observed_order_p_raw": None,
                "apparent_order_p": None,
                "order_qualified": False,
                "interval_valid": False,
                "discretization_uncertainty_mmhg": None,
                "conservative_po2_lower_bound_mmhg": None,
                "conservative_po2_upper_bound_mmhg": None,
                "straddles_canonical_15mmhg_floor": False,
                "mesh_convergence_resolved": True,
                "hold_reason_token": None,
                "verdict_from_mesh_policy": "PASS",
            },
            "mesh_convergence_resolved": True,
            "holds": [],
            "adjudicated_verdict": "PASS",
            "adjudicated_decision": "PASS_PROVABLY_MONOTONE_ZERO_OCR_INCREASE_ABOVE_NATIVE_15MMHG_BASELINE",
            "diagnostic_custom_floor_mmhg": diag_floor,
            "diagnostic_margin_above_custom_floor_unrounded_mmhg": None,
            "diagnostic_passes_custom_floor": None,
            "diagnostic_custom_floor_non_authorizing": True,
        }

    _res_obj, solved_raw_mmhg, verified_solver_p_bed = _execute_single_3d_fvm_vascular_scaled_solve_with_meta(
        resolved_root,
        effective_spec,
        vasc_scale=vasc_scale,
        min_exact_scale_ratio=min_exact_scale_ratio,
    )
    solve_iso_meta = (
        _res_obj.get("_nw08_isolated_solver_meta")
        if isinstance(_res_obj, dict) and isinstance(_res_obj.get("_nw08_isolated_solver_meta"), dict)
        else base_iso_meta
    )
    solve_origins = dict((solve_iso_meta or {}).get("resolved_solver_module_paths") or {})
    solve_relpaths = dict((solve_iso_meta or {}).get("resolved_solver_module_relpaths") or {})
    solve_origins_ok = bool(
        solve_origins
        and all(Path(p).resolve().is_relative_to(resolved_root) for p in solve_origins.values())
    )
    solve_operand_audit = (solve_iso_meta or {}).get("vascular_operand_audit")
    mesh_conv = _evaluate_nw08_mesh_convergence(
        resolved_root,
        route_id,
        effective_spec,
        vasc_scale=vasc_scale,
        native_coarse_face_mmhg=solved_raw_mmhg,
        verified_p_bed=verified_solver_p_bed,
        force_check=force_mesh_convergence_check,
        min_exact_scale_ratio=min_exact_scale_ratio,
    )
    mesh_verdict = str(mesh_conv["verdict_from_mesh_policy"])
    mesh_resolved = bool(mesh_conv["mesh_convergence_resolved"])
    # R05-B2 + R11-B2 + R14-B1 + R15-B2: Canonical 15.0 mmHg floor + 3-grid numerical convergence ALWAYS enforced!
    # Threshold-straddling and unqualified slow/non-asymptotic cases route to unresolved HOLD (exit 2) before
    # any coupled authorization.
    passed_canonical_15mmhg = bool(mesh_verdict == "PASS")
    diagnostic_passed_custom = _passes_unrounded_diagnostic_floor(solved_raw_mmhg, diag_floor)
    if mesh_verdict == "PASS":
        adj_decision = "PASS_3D_FVM_AT_CONSERVATIVE_OCR_U95"
        adj_holds: List[str] = []
    elif mesh_verdict == "FAIL":
        adj_decision = "FAIL_3D_FVM_BELOW_15MMHG_DERATE_REQUIRED"
        adj_holds = []
    else:
        hold_tok = str(mesh_conv.get("hold_reason_token") or NW08_HOLD_TOKEN_STRADDLES_FLOOR)
        adj_decision = hold_tok
        adj_holds = [hold_tok]
    return {
        **trig,
        "release_authorizing": False,
        "qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
        "physical_qualification_complete": False,
        "solver_isolation_mode": "ISOLATED_CHILD_SUBPROCESS",
        "resolved_solver_module_origins": solve_origins,
        "resolved_solver_module_relpaths": solve_relpaths,
        "all_solver_module_origins_within_repo_root": solve_origins_ok,
        "native_solver_vascular_operand_audit": solve_operand_audit,
        "solver_cleared_oxygen_floor_diagnostic": bool(passed_canonical_15mmhg),
        "nw08_oxygen_floor_adjudication_authoritative": True,
        "linear_screen_trigger_dispatched": linear_screen_triggered,
        "triggered_by_non_monotone_or_override_guard": triggered_by_non_monotone_or_override_guard,
        "within_provably_monotone_no_increase_domain": within_provably_monotone_no_increase_domain,
        "trigger_dispatched": effective_trigger_dispatched,
        "decision": (
            "TRIGGER_3D_FVM_RESOLVE_AND_PRECOMMITTED_DERATING_CHECK"
            if effective_trigger_dispatched
            else "FORCED_3D_FVM_RESOLVE_WITHIN_MONOTONE_DOMAIN"
        ),
        "catalog_default_p_bed_mmhg": catalog_default_p_bed,
        "effective_p_bed_mmhg": eff_p_bed,
        "p_bed_override_applied": p_bed_override_applied,
        "baseline_ocr_override_applied": baseline_ocr_override_applied,
        "any_parameter_override_applied": any_override_applied,
        "solver_p_bed_mmhg_verified": verified_solver_p_bed,
        "baseline_source": baseline_source,
        "solver_executed": True,
        "solved_at_vascular_ocr_u95": round(ocr_u95, 6),
        "solved_at_vascular_ocr_u95_exact_dec": str(ocr_u95_exact),
        "vascular_voxel_scale_factor": round(vasc_scale, 6),
        "native_solver_vasc_scale_float64": vasc_scale,
        "native_solver_effective_vascular_ocr_float64": effective_solver_ocr_f64,
        "face_min_mmhg_unrounded": solved_raw_mmhg,
        "face_min_mmhg": round(solved_raw_mmhg, 4),
        "canonical_floor_mmhg": CANONICAL_NW08_PO2_FLOOR_MMHG,
        "floor_mmhg": CANONICAL_NW08_PO2_FLOOR_MMHG,
        "margin_above_floor_unrounded_mmhg": solved_raw_mmhg - CANONICAL_NW08_PO2_FLOOR_MMHG,
        "passes_15mmhg_floor_unrounded": passed_canonical_15mmhg,
        "mesh_convergence_verification": mesh_conv,
        "mesh_convergence_resolved": mesh_resolved,
        "holds": adj_holds,
        "adjudicated_verdict": mesh_verdict,
        "adjudicated_decision": adj_decision,
        "diagnostic_custom_floor_mmhg": diag_floor,
        "diagnostic_margin_above_custom_floor_unrounded_mmhg": solved_raw_mmhg - diag_floor,
        "diagnostic_passes_custom_floor": diagnostic_passed_custom,
        "diagnostic_custom_floor_non_authorizing": True,
    }


def _run_r18_b1_concurrent_raw_native_isolation_test(openislet_root: Path) -> Dict[str, Any]:
    """
    R18-B1: Verify that a simultaneous raw native Layer-4 call (executed directly on
    `run_layer4_tissue_and_metabolic_twin.compute_design_z_140um_parameterized_case` WITHOUT
    acquiring `_FVM_SOLVER_LOCK`) agrees bit-for-bit before, during, and after concurrent
    modified NW-08 calls (`R2_DZ40`, bed=40, base=5.0, meas=10.0 -> ~13.1032 mmHg), while
    parent Layer-4 callbacks remain completely untouched throughout.
    """
    from concurrent.futures import ThreadPoolExecutor

    resolved_root = Path(openislet_root).resolve()
    r2_native_kw = {
        "bed_po2_mmhg": 40.0,
        "ocr_multiplier": 1.097,
        "d_gel_cm2_s": 1.5e-5,
        "k_perf_s_inv": 0.1358,
    }
    scripts_str = str(resolved_root / "scripts")
    added = False
    if scripts_str not in sys.path:
        sys.path.insert(0, scripts_str)
        added = True
    try:
        import run_layer4_tissue_and_metabolic_twin as raw_l4  # noqa: E402

        orig_solve_cb = raw_l4._solve_3d_oxygen_strict_iip_0019
        orig_fv_cb = raw_l4._compute_exact_fv_interface_stats_iip_0019

        # 1. Raw native BEFORE (NO _FVM_SOLVER_LOCK)
        raw_before = float(
            raw_l4.compute_design_z_140um_parameterized_case(**r2_native_kw)["fv_harmonic_face_min_unrounded_mmhg"]
        )
        # 2. Serial modified NW-08 baseline (~13.1032 mmHg, FAIL)
        nw08_serial = dispatch_and_solve_nw08_measured_ocr(
            "R2_DZ40",
            10.0,
            0.0,
            openislet_root=resolved_root,
            p_bed_mmhg=40.0,
            baseline_vasc_ocr_mult=5.0,
            always_solve_3d=True,
        )
        nw08_serial_val = float(nw08_serial["face_min_mmhg_unrounded"])

        # 3. Concurrent execution: background thread runs 3 consecutive NW-08 solves while main thread
        #    calls raw native Layer-4 directly WITHOUT acquiring _FVM_SOLVER_LOCK.
        nw08_started = threading.Event()
        nw08_done = threading.Event()

        def _bg_nw08_runner() -> List[Tuple[float, str]]:
            out_list: List[Tuple[float, str]] = []
            nw08_started.set()
            try:
                for _ in range(3):
                    res_bg = dispatch_and_solve_nw08_measured_ocr(
                        "R2_DZ40",
                        10.0,
                        0.0,
                        openislet_root=resolved_root,
                        p_bed_mmhg=40.0,
                        baseline_vasc_ocr_mult=5.0,
                        always_solve_3d=True,
                    )
                    out_list.append((float(res_bg["face_min_mmhg_unrounded"]), str(res_bg["adjudicated_verdict"])))
            finally:
                nw08_done.set()
            return out_list

        raw_during_vals: List[float] = []
        callbacks_untouched = True
        with ThreadPoolExecutor(max_workers=1) as pool_b1:
            fut_nw08 = pool_b1.submit(_bg_nw08_runner)
            nw08_started.wait(timeout=10.0)
            for iter_idx in range(8):
                if (
                    raw_l4._solve_3d_oxygen_strict_iip_0019 is not orig_solve_cb
                    or raw_l4._compute_exact_fv_interface_stats_iip_0019 is not orig_fv_cb
                ):
                    callbacks_untouched = False
                v_during = float(
                    raw_l4.compute_design_z_140um_parameterized_case(**r2_native_kw)[
                        "fv_harmonic_face_min_unrounded_mmhg"
                    ]
                )
                raw_during_vals.append(v_during)
                if (
                    raw_l4._solve_3d_oxygen_strict_iip_0019 is not orig_solve_cb
                    or raw_l4._compute_exact_fv_interface_stats_iip_0019 is not orig_fv_cb
                ):
                    callbacks_untouched = False
                if iter_idx >= 1 and nw08_done.is_set():
                    break
            nw08_conc_results = fut_nw08.result()

        # 4. Raw native AFTER (NO _FVM_SOLVER_LOCK)
        raw_after = float(
            raw_l4.compute_design_z_140um_parameterized_case(**r2_native_kw)["fv_harmonic_face_min_unrounded_mmhg"]
        )
        if (
            raw_l4._solve_3d_oxygen_strict_iip_0019 is not orig_solve_cb
            or raw_l4._compute_exact_fv_interface_stats_iip_0019 is not orig_fv_cb
        ):
            callbacks_untouched = False
    finally:
        if added and scripts_str in sys.path:
            sys.path.remove(scripts_str)

    raw_during_bit_exact = bool(len(raw_during_vals) >= 1 and all(v == raw_before for v in raw_during_vals))
    nw08_conc_bit_exact = bool(
        len(nw08_conc_results) == 3
        and all(v == nw08_serial_val and verd == "FAIL" for v, verd in nw08_conc_results)
    )
    ok_32 = bool(
        abs(raw_before - 24.0468) < 0.001
        and abs(nw08_serial_val - 13.1032) < 0.001
        and nw08_serial.get("adjudicated_verdict") == "FAIL"
        and nw08_serial.get("solver_isolation_mode") == "ISOLATED_CHILD_SUBPROCESS"
        and raw_before == raw_after
        and raw_during_bit_exact
        and nw08_conc_bit_exact
        and callbacks_untouched
    )
    return {
        "test": "r18_b1_concurrent_raw_native_layer4_and_nw08_bit_for_bit_isolation",
        "raw_native_before_mmhg": raw_before,
        "raw_native_after_mmhg": raw_after,
        "raw_native_during_matches_before_bit_for_bit": raw_during_bit_exact,
        "nw08_modified_serial_mmhg": nw08_serial_val,
        "nw08_concurrent_matches_serial_bit_for_bit": nw08_conc_bit_exact,
        "raw_native_callbacks_untouched_throughout": callbacks_untouched,
        "passed": ok_32,
    }


def _run_r18_b2_cross_root_sequential_isolation_test(openislet_root: Path) -> Dict[str, Any]:
    """
    R18-B2: Verify that sequential `dispatch_and_solve_nw08_measured_ocr` calls targeting two
    distinct repo copies (`copy_A` then `copy_B`) execute strictly from the requested copy's
    `scripts/` tree across R2, R3P, and R1 (reporting exact `resolved_solver_module_origins`
    under `copy_A` on call 1 and under `copy_B` on call 2, never reusing `copy_A` or parent
    `sys.modules`), while failing closed if a solver script symlinks outside `repo_root`, and
    emitting ZERO absolute host paths into the portable receipt dict.
    """
    resolved_src = Path(openislet_root).resolve()
    required_scripts = (
        "run_layer4_tissue_and_metabolic_twin.py",
        "verify_iip0033_bilayer_and_resp1.py",
        "verify_iip0034_planar_and_portfolio.py",
        "rank_islet1_stacks.py",
        "product_contract.py",
        "engineering_priors.py",
        "public_excerpt_policy.py",
    )
    required_jsons = (
        "iip0033_bilayer_and_respirometry_verification_v0.8.0.json",
        "iip0034_planar_and_portfolio_verification_v0.8.0.json",
        "layer4_tissue_and_metabolic_twin_atlas.json",
    )
    route_cases: Tuple[Tuple[str, float, float, Tuple[str, ...]], ...] = (
        ("R2_DZ40", 1.3164, 0.0, ("run_layer4_tissue_and_metabolic_twin",)),
        (
            "R3P_35",
            1.3164,
            0.0,
            (
                "run_layer4_tissue_and_metabolic_twin",
                "verify_iip0034_planar_and_portfolio",
                "rank_islet1_stacks",
                "product_contract",
            ),
        ),
        (
            "R1_390_nominal",
            1.097,
            0.0,
            (
                "run_layer4_tissue_and_metabolic_twin",
                "verify_iip0033_bilayer_and_resp1",
                "rank_islet1_stacks",
            ),
        ),
    )

    def _populate_minimal_copy(dst_root: Path) -> None:
        (dst_root / "scripts").mkdir(parents=True, exist_ok=True)
        (dst_root / "data" / "extracted").mkdir(parents=True, exist_ok=True)
        for fn in required_scripts:
            shutil.copy2(resolved_src / "scripts" / fn, dst_root / "scripts" / fn)
        for jn in required_jsons:
            shutil.copy2(resolved_src / "data" / "extracted" / jn, dst_root / "data" / "extracted" / jn)

    def _purge_temp_caches(roots_to_purge: Tuple[Path, ...]) -> None:
        purge_strs = {str(p.resolve()) for p in roots_to_purge}
        with _FVM_SOLVER_LOCK:
            for cache_obj in (
                _NATIVE_BASELINE_MMHG_CACHE,
                _NATIVE_BASELINE_META_CACHE,
                _MESH_REFINEMENT_SOLVE_CACHE,
            ):
                for ck in list(cache_obj.keys()):
                    if isinstance(ck, tuple) and len(ck) >= 1 and ck[0] in purge_strs:
                        cache_obj.pop(ck, None)

    with tempfile.TemporaryDirectory() as td_b2:
        td_p = Path(td_b2)
        copy_a = (td_p / "copy_A").resolve()
        copy_b = (td_p / "copy_B").resolve()
        copy_c = (td_p / "copy_C_symlink_escape").resolve()
        _populate_minimal_copy(copy_a)
        _populate_minimal_copy(copy_b)
        _populate_minimal_copy(copy_c)
        # Replace copy_C's Layer-4 script with a symlink pointing outside copy_C (into copy_A)
        (copy_c / "scripts" / "run_layer4_tissue_and_metabolic_twin.py").unlink()
        (copy_c / "scripts" / "run_layer4_tissue_and_metabolic_twin.py").symlink_to(
            copy_a / "scripts" / "run_layer4_tissue_and_metabolic_twin.py"
        )

        copy_a_ok = True
        copy_b_ok = True
        disjoint_ok = True
        parity_ok = True
        relpaths_union: set[str] = set()
        symlink_escape_rejected = False
        try:
            for rt, ocr_val, se_val, expected_mods in route_cases:
                res_a = dispatch_and_solve_nw08_measured_ocr(rt, ocr_val, se_val, openislet_root=copy_a)
                res_b = dispatch_and_solve_nw08_measured_ocr(rt, ocr_val, se_val, openislet_root=copy_b)
                orig_a = res_a.get("resolved_solver_module_origins") or {}
                orig_b = res_b.get("resolved_solver_module_origins") or {}
                rel_a = res_a.get("resolved_solver_module_relpaths") or {}
                rel_b = res_b.get("resolved_solver_module_relpaths") or {}

                if (
                    res_a.get("solver_isolation_mode") != "ISOLATED_CHILD_SUBPROCESS"
                    or res_a.get("all_solver_module_origins_within_repo_root") is not True
                    or not orig_a
                ):
                    copy_a_ok = False
                if (
                    res_b.get("solver_isolation_mode") != "ISOLATED_CHILD_SUBPROCESS"
                    or res_b.get("all_solver_module_origins_within_repo_root") is not True
                    or not orig_b
                ):
                    copy_b_ok = False

                for mod_name in expected_mods:
                    if mod_name not in orig_a:
                        copy_a_ok = False
                    if mod_name not in orig_b:
                        copy_b_ok = False

                for mod_name, path_str in orig_a.items():
                    mp_a = Path(path_str).resolve()
                    if not mp_a.is_relative_to(copy_a):
                        copy_a_ok = False
                    if mp_a.is_relative_to(copy_b) or mp_a.is_relative_to(resolved_src):
                        disjoint_ok = False
                for mod_name, path_str in orig_b.items():
                    mp_b = Path(path_str).resolve()
                    if not mp_b.is_relative_to(copy_b):
                        copy_b_ok = False
                    if mp_b.is_relative_to(copy_a) or mp_b.is_relative_to(resolved_src):
                        disjoint_ok = False
                for mod_name in set(orig_a.keys()) & set(orig_b.keys()):
                    if orig_a[mod_name] == orig_b[mod_name]:
                        disjoint_ok = False

                if rel_a != rel_b:
                    parity_ok = False
                relpaths_union.update(str(v) for v in rel_a.values())

                if (
                    res_a.get("adjudicated_verdict") != res_b.get("adjudicated_verdict")
                    or res_a.get("baseline_min_face_unrounded_mmhg") != res_b.get("baseline_min_face_unrounded_mmhg")
                    or res_a.get("face_min_mmhg_unrounded") != res_b.get("face_min_mmhg_unrounded")
                ):
                    parity_ok = False

            try:
                dispatch_and_solve_nw08_measured_ocr("R2_DZ40", 1.3164, 0.0, openislet_root=copy_c)
            except RuntimeError:
                symlink_escape_rejected = True
        finally:
            _purge_temp_caches((copy_a, copy_b, copy_c))

    ok_33 = bool(copy_a_ok and copy_b_ok and disjoint_ok and parity_ok and symlink_escape_rejected)
    return {
        "test": "r18_b2_cross_root_sequential_copy_a_then_copy_b_module_origin_isolation",
        "routes_tested": [rt for rt, _o, _s, _m in route_cases],
        "copy_a_all_origins_strictly_inside_copy_a": copy_a_ok,
        "copy_b_all_origins_strictly_inside_copy_b": copy_b_ok,
        "copy_a_and_copy_b_origins_disjoint_and_distinct_from_parent_root": disjoint_ok,
        "copy_a_and_copy_b_bit_for_bit_numerical_parity": parity_ok,
        "verified_module_relpaths_union": sorted(relpaths_union),
        "symlink_escape_outside_repo_root_rejected": symlink_escape_rejected,
        "passed": ok_33,
    }


def run_nw08_live_dispatch_solver_tests(openislet_root: Path) -> Dict[str, Any]:
    """
    B7 / R03-B2 live verification tests observing actual 3D FVM execution through
    `dispatch_and_solve_nw08_measured_ocr(...)` across R3P, R2, and R1 routes, including
    boundary-pressure override consistency, native unrounded float64 baselines, and
    concurrent in-process state isolation!
    """
    from concurrent.futures import ThreadPoolExecutor

    tests: List[Dict[str, Any]] = []
    _known_sig = {
        "ocr_uncertainty_model": NW08_OCR_UNCERTAINTY_MODEL_KNOWN_SIGMA,
        "ocr_uncertainty_provenance": "live_dispatch_calibrated_known_sigma_reference_v1",
    }

    # 1. R3P_30 triggered by measured OCR + SE -> actually solves 3D FVM and FAILS < 15.0 mmHg
    d_r3p30 = dispatch_and_solve_nw08_measured_ocr("R3P_30", 1.25, 0.04, openislet_root=openislet_root, **_known_sig)
    ok_1 = bool(
        d_r3p30["trigger_dispatched"] is True
        and d_r3p30["solver_executed"] is True
        and d_r3p30["baseline_source"] == "native_3d_fvm_unrounded_float64"
        and abs(d_r3p30["baseline_min_face_unrounded_mmhg"] - 15.2152) > 1e-6
        and d_r3p30["solver_p_bed_mmhg_verified"] == 30.0
        and isinstance(d_r3p30["face_min_mmhg_unrounded"], float)
        and d_r3p30["face_min_mmhg_unrounded"] < 15.0
        and d_r3p30["passes_15mmhg_floor_unrounded"] is False
        and d_r3p30["adjudicated_verdict"] == "FAIL"
    )
    tests.append({
        "test": "live_dispatch_r3p_bed30_executes_3d_fvm_and_fails_below_15mmhg",
        "solver_executed": d_r3p30["solver_executed"],
        "baseline_source": d_r3p30["baseline_source"],
        "solver_p_bed_mmhg_verified": d_r3p30["solver_p_bed_mmhg_verified"],
        "solved_at_vascular_ocr_u95": d_r3p30["solved_at_vascular_ocr_u95"],
        "face_min_mmhg_unrounded": d_r3p30["face_min_mmhg_unrounded"],
        "adjudicated_verdict": d_r3p30["adjudicated_verdict"],
        "passed": ok_1,
    })

    # 2. R3P_35_VPIO120 triggered by linear screen, but live 3D FVM resolves PASS >= 15.0 mmHg (reversal!)
    d_vpio = dispatch_and_solve_nw08_measured_ocr("R3P_35_VPIO120", 1.28, 0.022, openislet_root=openislet_root, **_known_sig)
    ok_2 = bool(
        d_vpio["trigger_dispatched"] is True
        and d_vpio["solver_executed"] is True
        and d_vpio["baseline_source"] == "native_3d_fvm_unrounded_float64"
        and d_vpio["solver_p_bed_mmhg_verified"] == 35.0
        and isinstance(d_vpio["face_min_mmhg_unrounded"], float)
        and d_vpio["face_min_mmhg_unrounded"] >= 15.0
        and d_vpio["passes_15mmhg_floor_unrounded"] is True
        and d_vpio["adjudicated_verdict"] == "PASS"
    )
    tests.append({
        "test": "live_dispatch_r3p_vpio120_linear_triggers_3d_fvm_resolves_pass",
        "solver_executed": d_vpio["solver_executed"],
        "solved_at_vascular_ocr_u95": d_vpio["solved_at_vascular_ocr_u95"],
        "face_min_mmhg_unrounded": d_vpio["face_min_mmhg_unrounded"],
        "adjudicated_verdict": d_vpio["adjudicated_verdict"],
        "passed": ok_2,
    })

    # 3. R2_DZ40 forced live 3D FVM solve at elevated OCR + SE -> PASS > 23 mmHg
    d_r2 = dispatch_and_solve_nw08_measured_ocr("R2_DZ40", 1.25, 0.04, openislet_root=openislet_root, always_solve_3d=True, **_known_sig)
    ok_3 = bool(
        d_r2["solver_executed"] is True
        and d_r2["baseline_source"] == "native_3d_fvm_unrounded_float64"
        and d_r2["solver_p_bed_mmhg_verified"] == 40.0
        and isinstance(d_r2["face_min_mmhg_unrounded"], float)
        and d_r2["face_min_mmhg_unrounded"] > 23.0
        and d_r2["adjudicated_verdict"] == "PASS"
    )
    tests.append({
        "test": "live_dispatch_r2_designz_executes_3d_fvm_and_passes",
        "solver_executed": d_r2["solver_executed"],
        "solved_at_vascular_ocr_u95": d_r2["solved_at_vascular_ocr_u95"],
        "face_min_mmhg_unrounded": d_r2["face_min_mmhg_unrounded"],
        "adjudicated_verdict": d_r2["adjudicated_verdict"],
        "passed": ok_3,
    })

    # 4. R1_350_stress triggered by measured OCR + SE -> executes live Route-1 3D FVM and FAILS < 15.0 mmHg
    d_r1 = dispatch_and_solve_nw08_measured_ocr("R1_350_stress", 1.26, 0.034, openislet_root=openislet_root, **_known_sig)
    ok_4 = bool(
        d_r1["trigger_dispatched"] is True
        and d_r1["solver_executed"] is True
        and d_r1["baseline_source"] == "native_3d_fvm_unrounded_float64"
        and d_r1["solver_p_bed_mmhg_verified"] == 35.0
        and isinstance(d_r1["face_min_mmhg_unrounded"], float)
        and d_r1["face_min_mmhg_unrounded"] < 15.0
        and d_r1["adjudicated_verdict"] == "FAIL"
    )
    tests.append({
        "test": "live_dispatch_r1_350_stress_executes_3d_fvm_and_fails_below_15mmhg",
        "solver_executed": d_r1["solver_executed"],
        "solved_at_vascular_ocr_u95": d_r1["solved_at_vascular_ocr_u95"],
        "face_min_mmhg_unrounded": d_r1["face_min_mmhg_unrounded"],
        "adjudicated_verdict": d_r1["adjudicated_verdict"],
        "passed": ok_4,
    })

    # 5. R03-B2: Lowered boundary pressure override on R3P_35 (p_bed_mmhg=30.0) carries through to BOTH
    #    native baseline screen AND live 3D FVM solver, matching R3P_30 to < 1e-12 mmHg and flipping PASS -> FAIL!
    d_r3p35_nom = dispatch_and_solve_nw08_measured_ocr("R3P_35", 1.25, 0.04, openislet_root=openislet_root, always_solve_3d=True, **_known_sig)
    d_r3p35_ov30 = dispatch_and_solve_nw08_measured_ocr("R3P_35", 1.25, 0.04, openislet_root=openislet_root, p_bed_mmhg=30.0, **_known_sig)
    ok_5 = bool(
        d_r3p35_nom["adjudicated_verdict"] == "PASS"
        and d_r3p35_nom["face_min_mmhg_unrounded"] > 19.5
        and d_r3p35_ov30["p_bed_override_applied"] is True
        and d_r3p35_ov30["effective_p_bed_mmhg"] == 30.0
        and d_r3p35_ov30["solver_p_bed_mmhg_verified"] == 30.0
        and d_r3p35_ov30["baseline_source"] == "native_3d_fvm_unrounded_float64"
        and d_r3p35_ov30["trigger_dispatched"] is True
        and d_r3p35_ov30["solver_executed"] is True
        and d_r3p35_ov30["adjudicated_verdict"] == "FAIL"
        and abs(d_r3p35_ov30["baseline_min_face_unrounded_mmhg"] - d_r3p30["baseline_min_face_unrounded_mmhg"]) < 1e-12
        and abs(d_r3p35_ov30["face_min_mmhg_unrounded"] - d_r3p30["face_min_mmhg_unrounded"]) < 1e-12
        and (d_r3p35_nom["face_min_mmhg_unrounded"] - d_r3p35_ov30["face_min_mmhg_unrounded"]) > 4.5
    )
    tests.append({
        "test": "r03_b2_r3p35_lowered_p_bed_30mmhg_override_matches_r3p30_and_flips_to_fail",
        "nominal_35mmhg_face_min_unrounded": d_r3p35_nom["face_min_mmhg_unrounded"],
        "override_30mmhg_face_min_unrounded": d_r3p35_ov30["face_min_mmhg_unrounded"],
        "solver_p_bed_mmhg_verified": d_r3p35_ov30["solver_p_bed_mmhg_verified"],
        "max_abs_diff_vs_r3p30_mmhg": abs(d_r3p35_ov30["face_min_mmhg_unrounded"] - d_r3p30["face_min_mmhg_unrounded"]),
        "adjudicated_verdict": d_r3p35_ov30["adjudicated_verdict"],
        "passed": ok_5,
    })

    # 6. R03-B2: Lowered boundary pressure override on R2_DZ40 (p_bed_mmhg=30.0) drops face_min_mmhg < 15.0 (FAIL)
    #    AND passing a stale 40-mmHg baseline with a 30-mmHg override raises ValueError fail-closed!
    d_r2_ov30 = dispatch_and_solve_nw08_measured_ocr("R2_DZ40", 1.25, 0.04, openislet_root=openislet_root, p_bed_mmhg=30.0, **_known_sig)
    stale_base_rejected = False
    try:
        dispatch_and_solve_nw08_measured_ocr(
            "R2_DZ40", 1.25, 0.04, openislet_root=openislet_root, p_bed_mmhg=30.0, baseline_min_face_mmhg=24.0468, **_known_sig
        )
    except ValueError:
        stale_base_rejected = True
    ok_6 = bool(
        d_r2_ov30["p_bed_override_applied"] is True
        and d_r2_ov30["solver_p_bed_mmhg_verified"] == 30.0
        and d_r2_ov30["trigger_dispatched"] is True
        and d_r2_ov30["solver_executed"] is True
        and d_r2_ov30["face_min_mmhg_unrounded"] < 15.0
        and d_r2_ov30["adjudicated_verdict"] == "FAIL"
        and (d_r2["face_min_mmhg_unrounded"] - d_r2_ov30["face_min_mmhg_unrounded"]) > 9.0
        and stale_base_rejected is True
    )
    tests.append({
        "test": "r03_b2_r2_dz40_lowered_p_bed_30mmhg_override_fails_and_rejects_stale_baseline",
        "nominal_40mmhg_face_min_unrounded": d_r2["face_min_mmhg_unrounded"],
        "override_30mmhg_face_min_unrounded": d_r2_ov30["face_min_mmhg_unrounded"],
        "solver_p_bed_mmhg_verified": d_r2_ov30["solver_p_bed_mmhg_verified"],
        "stale_baseline_rejected": stale_base_rejected,
        "adjudicated_verdict": d_r2_ov30["adjudicated_verdict"],
        "passed": ok_6,
    })

    # 7. R03-B2: Concurrent multi-threaded dispatch isolation (zero global callback corruption/state leak)
    with ThreadPoolExecutor(max_workers=2) as pool:
        f_hi = pool.submit(
            dispatch_and_solve_nw08_measured_ocr, "R3P_35", 1.25, 0.04, openislet_root=openislet_root, p_bed_mmhg=35.0, always_solve_3d=True, **_known_sig
        )
        f_lo = pool.submit(
            dispatch_and_solve_nw08_measured_ocr, "R3P_35", 1.25, 0.04, openislet_root=openislet_root, p_bed_mmhg=30.0, always_solve_3d=True, **_known_sig
        )
        c_hi = f_hi.result()
        c_lo = f_lo.result()
    ok_7 = bool(
        c_hi["solver_p_bed_mmhg_verified"] == 35.0
        and c_lo["solver_p_bed_mmhg_verified"] == 30.0
        and abs(c_hi["face_min_mmhg_unrounded"] - d_r3p35_nom["face_min_mmhg_unrounded"]) < 1e-12
        and abs(c_lo["face_min_mmhg_unrounded"] - d_r3p35_ov30["face_min_mmhg_unrounded"]) < 1e-12
    )
    tests.append({
        "test": "r03_b2_concurrent_in_process_fvm_dispatch_state_isolation",
        "thread_35mmhg_face_min_unrounded": c_hi["face_min_mmhg_unrounded"],
        "thread_30mmhg_face_min_unrounded": c_lo["face_min_mmhg_unrounded"],
        "passed": ok_7,
    })

    # 8. R04-B5: At DEFAULT bed pressure on R1_390_stress, a stale 25.0 mmHg caller baseline
    #    MUST raise ValueError immediately (never passing without solving!), while the native
    #    unrounded baseline (~15.261956 mmHg) dispatches live 3D FVM and FAILS < 15.0 mmHg!
    stale_default_rejected = False
    try:
        dispatch_and_solve_nw08_measured_ocr(
            "R1_390_stress",
            1.44804,
            0.0,
            openislet_root=openislet_root,
            baseline_min_face_mmhg=25.0,
        )
    except ValueError:
        stale_default_rejected = True
    d_r1_390_stress_fail = dispatch_and_solve_nw08_measured_ocr(
        "R1_390_stress",
        1.44804,
        0.0,
        openislet_root=openislet_root,
    )
    ok_8 = bool(
        stale_default_rejected is True
        and d_r1_390_stress_fail["p_bed_override_applied"] is False
        and d_r1_390_stress_fail["trigger_dispatched"] is True
        and d_r1_390_stress_fail["solver_executed"] is True
        and abs(d_r1_390_stress_fail["baseline_min_face_unrounded_mmhg"] - 15.261956) < 0.001
        and d_r1_390_stress_fail["face_min_mmhg_unrounded"] < 15.0
        and d_r1_390_stress_fail["adjudicated_verdict"] == "FAIL"
    )
    tests.append({
        "test": "r04_b5_default_bed_pressure_rejects_stale_25mmhg_baseline_and_fails_live_r1_390_stress",
        "stale_25mmhg_default_pressure_rejected": stale_default_rejected,
        "native_baseline_unrounded_mmhg": d_r1_390_stress_fail["baseline_min_face_unrounded_mmhg"],
        "solved_face_min_unrounded_mmhg": d_r1_390_stress_fail["face_min_mmhg_unrounded"],
        "adjudicated_verdict": d_r1_390_stress_fail["adjudicated_verdict"],
        "passed": ok_8,
    })

    # 9. R04-B5: Negative or sub-95% caller-supplied one-sided quantile MUST raise ValueError
    #    immediately so it can NEVER flip a live FAIL into PASS!
    neg_z_rejected = False
    sub95_z_rejected = False
    try:
        dispatch_and_solve_nw08_measured_ocr(
            "R1_390_stress",
            1.44804,
            0.15,
            openislet_root=openislet_root,
            z_one_sided_95=-1.6448536269514722,
        )
    except ValueError:
        neg_z_rejected = True
    try:
        dispatch_and_solve_nw08_measured_ocr(
            "R1_390_stress",
            1.44804,
            0.15,
            openislet_root=openislet_root,
            z_one_sided_95=1.6448,
        )
    except ValueError:
        sub95_z_rejected = True
    ok_9 = bool(neg_z_rejected is True and sub95_z_rejected is True)
    tests.append({
        "test": "r04_b5_live_dispatch_rejects_negative_and_sub95_confidence_quantiles",
        "negative_z_rejected": neg_z_rejected,
        "sub95_z_rejected": sub95_z_rejected,
        "passed": ok_9,
    })

    # 10. R05-B2: Forced & triggered live 3D FVM solve on R3P_30 (1.3164, 0.0 -> 14.906233... mmHg)
    #     at BOTH floor_mmhg=15.0 AND floor_mmhg=14.0 MUST BOTH return FAIL and
    #     passes_15mmhg_floor_unrounded=False, while diagnostic_passes_custom_floor reports
    #     False at 15.0 and True at 14.0!
    d_r3p30_f15 = dispatch_and_solve_nw08_measured_ocr(
        "R3P_30", 1.3164, 0.0, openislet_root=openislet_root, floor_mmhg=15.0, always_solve_3d=True
    )
    d_r3p30_f14 = dispatch_and_solve_nw08_measured_ocr(
        "R3P_30", 1.3164, 0.0, openislet_root=openislet_root, floor_mmhg=14.0, always_solve_3d=True
    )
    d_r3p30_f14_unforced = dispatch_and_solve_nw08_measured_ocr(
        "R3P_30", 1.3164, 0.0, openislet_root=openislet_root, floor_mmhg=14.0, always_solve_3d=False
    )
    ok_10 = bool(
        d_r3p30_f15["solver_executed"] is True
        and d_r3p30_f14["solver_executed"] is True
        and d_r3p30_f14_unforced["trigger_dispatched"] is True
        and d_r3p30_f14_unforced["solver_executed"] is True
        and abs(d_r3p30_f15["face_min_mmhg_unrounded"] - 14.906233358064961) < 1e-9
        and abs(d_r3p30_f14["face_min_mmhg_unrounded"] - d_r3p30_f15["face_min_mmhg_unrounded"]) < 1e-12
        and abs(d_r3p30_f14_unforced["face_min_mmhg_unrounded"] - d_r3p30_f15["face_min_mmhg_unrounded"]) < 1e-12
        and d_r3p30_f15["canonical_floor_mmhg"] == 15.0
        and d_r3p30_f14["canonical_floor_mmhg"] == 15.0
        and d_r3p30_f15["passes_15mmhg_floor_unrounded"] is False
        and d_r3p30_f14["passes_15mmhg_floor_unrounded"] is False
        and d_r3p30_f14_unforced["passes_15mmhg_floor_unrounded"] is False
        and d_r3p30_f15["adjudicated_verdict"] == "FAIL"
        and d_r3p30_f14["adjudicated_verdict"] == "FAIL"
        and d_r3p30_f14_unforced["adjudicated_verdict"] == "FAIL"
        and d_r3p30_f15["diagnostic_custom_floor_mmhg"] == 15.0
        and d_r3p30_f15["diagnostic_passes_custom_floor"] is False
        and d_r3p30_f14["diagnostic_custom_floor_mmhg"] == 14.0
        and d_r3p30_f14["diagnostic_passes_custom_floor"] is True
        and d_r3p30_f14_unforced["diagnostic_passes_custom_floor"] is True
    )
    tests.append({
        "test": "r05_b2_r3p_bed30_sub15mmhg_immutable_canonical_fail_at_floor_15_and_14",
        "face_min_mmhg_unrounded": d_r3p30_f15["face_min_mmhg_unrounded"],
        "at_floor_15_verdict": d_r3p30_f15["adjudicated_verdict"],
        "at_floor_15_passes_15mmhg": d_r3p30_f15["passes_15mmhg_floor_unrounded"],
        "at_floor_15_diagnostic_passes_custom": d_r3p30_f15["diagnostic_passes_custom_floor"],
        "at_floor_14_verdict": d_r3p30_f14["adjudicated_verdict"],
        "at_floor_14_passes_15mmhg": d_r3p30_f14["passes_15mmhg_floor_unrounded"],
        "at_floor_14_diagnostic_passes_custom": d_r3p30_f14["diagnostic_passes_custom_floor"],
        "at_floor_14_unforced_solver_executed": d_r3p30_f14_unforced["solver_executed"],
        "passed": ok_10,
    })

    # 11. R05-B2: Second canonical route below 15.0 mmHg (R1_350_stress at 1.3164, 0.0 -> ~14.8446 mmHg)
    #     at BOTH floor_mmhg=15.0 AND floor_mmhg=14.0 MUST BOTH return FAIL and
    #     passes_15mmhg_floor_unrounded=False, while diagnostic_passes_custom_floor is False at 15.0 and True at 14.0!
    d_r1_350_f15 = dispatch_and_solve_nw08_measured_ocr(
        "R1_350_stress", 1.3164, 0.0, openislet_root=openislet_root, floor_mmhg=15.0, always_solve_3d=True
    )
    d_r1_350_f14 = dispatch_and_solve_nw08_measured_ocr(
        "R1_350_stress", 1.3164, 0.0, openislet_root=openislet_root, floor_mmhg=14.0, always_solve_3d=True
    )
    d_r1_350_f14_unforced = dispatch_and_solve_nw08_measured_ocr(
        "R1_350_stress", 1.3164, 0.0, openislet_root=openislet_root, floor_mmhg=14.0, always_solve_3d=False
    )
    ok_11 = bool(
        d_r1_350_f15["solver_executed"] is True
        and d_r1_350_f14["solver_executed"] is True
        and d_r1_350_f14_unforced["trigger_dispatched"] is True
        and d_r1_350_f14_unforced["solver_executed"] is True
        and 14.0 < d_r1_350_f15["face_min_mmhg_unrounded"] < 15.0
        and abs(d_r1_350_f14["face_min_mmhg_unrounded"] - d_r1_350_f15["face_min_mmhg_unrounded"]) < 1e-12
        and abs(d_r1_350_f14_unforced["face_min_mmhg_unrounded"] - d_r1_350_f15["face_min_mmhg_unrounded"]) < 1e-12
        and d_r1_350_f15["canonical_floor_mmhg"] == 15.0
        and d_r1_350_f14["canonical_floor_mmhg"] == 15.0
        and d_r1_350_f15["passes_15mmhg_floor_unrounded"] is False
        and d_r1_350_f14["passes_15mmhg_floor_unrounded"] is False
        and d_r1_350_f14_unforced["passes_15mmhg_floor_unrounded"] is False
        and d_r1_350_f15["adjudicated_verdict"] == "FAIL"
        and d_r1_350_f14["adjudicated_verdict"] == "FAIL"
        and d_r1_350_f14_unforced["adjudicated_verdict"] == "FAIL"
        and d_r1_350_f15["diagnostic_custom_floor_mmhg"] == 15.0
        and d_r1_350_f15["diagnostic_passes_custom_floor"] is False
        and d_r1_350_f14["diagnostic_custom_floor_mmhg"] == 14.0
        and d_r1_350_f14["diagnostic_passes_custom_floor"] is True
        and d_r1_350_f14_unforced["diagnostic_passes_custom_floor"] is True
    )
    tests.append({
        "test": "r05_b2_r1_350_stress_sub15mmhg_immutable_canonical_fail_at_floor_15_and_14",
        "face_min_mmhg_unrounded": d_r1_350_f15["face_min_mmhg_unrounded"],
        "at_floor_15_verdict": d_r1_350_f15["adjudicated_verdict"],
        "at_floor_15_passes_15mmhg": d_r1_350_f15["passes_15mmhg_floor_unrounded"],
        "at_floor_15_diagnostic_passes_custom": d_r1_350_f15["diagnostic_passes_custom_floor"],
        "at_floor_14_verdict": d_r1_350_f14["adjudicated_verdict"],
        "at_floor_14_passes_15mmhg": d_r1_350_f14["passes_15mmhg_floor_unrounded"],
        "at_floor_14_diagnostic_passes_custom": d_r1_350_f14["diagnostic_passes_custom_floor"],
        "at_floor_14_unforced_solver_executed": d_r1_350_f14_unforced["solver_executed"],
        "passed": ok_11,
    })

    # 12. R08-B2 (a) + R14-B1: Near-floor Route-2 override counterexample verbatim:
    #     R2_DZ40 at p_bed=32.0, baseline_vasc_ocr_mult=2.0, measured_ocr=2.099752752324571, SE=0.0
    #     gives 14.98975358 on 48x48x28, 15.02371692 on 72x72x42, and 15.13803340 on 96x96x56
    #     (straddling 15.0 mmHg across predeclared grids!), so under R14-B1 it MUST dispatch live
    #     3D FVM + 3-grid convergence verification and route to unresolved HOLD (never PASS and
    #     never decisive fixed-grid FAIL) in BOTH default and forced modes!
    d_r08_near_def = dispatch_and_solve_nw08_measured_ocr(
        "R2_DZ40",
        2.099752752324571,
        0.0,
        openislet_root=openislet_root,
        baseline_vasc_ocr_mult=2.0,
        p_bed_mmhg=32.0,
    )
    d_r08_near_forced = dispatch_and_solve_nw08_measured_ocr(
        "R2_DZ40",
        2.099752752324571,
        0.0,
        openislet_root=openislet_root,
        baseline_vasc_ocr_mult=2.0,
        p_bed_mmhg=32.0,
        always_solve_3d=True,
    )
    r2_mc = d_r08_near_def.get("mesh_convergence_verification") or {}
    ok_12 = bool(
        d_r08_near_def["solver_executed"] is True
        and d_r08_near_def["trigger_dispatched"] is True
        and d_r08_near_def["adjudicated_verdict"] == "HOLD"
        and d_r08_near_forced["adjudicated_verdict"] == "HOLD"
        and "HOLD_NW08_MESH_CONVERGENCE_STRADDLES_15MMHG_FLOOR" in (d_r08_near_def.get("holds") or [])
        and d_r08_near_def["passes_15mmhg_floor_unrounded"] is False
        and d_r08_near_def["face_min_mmhg_unrounded"] < 15.0
        and r2_mc.get("executed") is True
        and r2_mc.get("straddles_canonical_15mmhg_floor") is True
        and r2_mc.get("grid_max_mmhg", 0.0) > 15.0
        and abs(d_r08_near_def["face_min_mmhg_unrounded"] - d_r08_near_forced["face_min_mmhg_unrounded"]) < 1e-12
    )
    tests.append({
        "test": "r08_b2_r14_b1_r2_dz40_near_floor_pbed32_base2p0_meas2p09975_mesh_reversal_routes_to_hold",
        "baseline_min_face_unrounded_mmhg": d_r08_near_def["baseline_min_face_unrounded_mmhg"],
        "default_face_min_unrounded_mmhg": d_r08_near_def["face_min_mmhg_unrounded"],
        "refined_max_face_min_unrounded_mmhg": r2_mc.get("grid_max_mmhg"),
        "default_verdict": d_r08_near_def["adjudicated_verdict"],
        "forced_verdict": d_r08_near_forced["adjudicated_verdict"],
        "solver_executed": d_r08_near_def["solver_executed"],
        "passed": ok_12,
    })

    # 13. R08-B2 (b): Default 40.0 mmHg bed pressure with elevated baseline override (5.0 -> 10.0)
    #     MUST dispatch live candidate 3D FVM and return FAIL (~13.1032141 < 15.0 mmHg) matching
    #     forced always_solve_3d=True exactly!
    d_r08_ov5_def = dispatch_and_solve_nw08_measured_ocr(
        "R2_DZ40",
        10.0,
        0.0,
        openislet_root=openislet_root,
        baseline_vasc_ocr_mult=5.0,
    )
    d_r08_ov5_forced = dispatch_and_solve_nw08_measured_ocr(
        "R2_DZ40",
        10.0,
        0.0,
        openislet_root=openislet_root,
        baseline_vasc_ocr_mult=5.0,
        always_solve_3d=True,
    )
    ok_13 = bool(
        d_r08_ov5_def["solver_executed"] is True
        and d_r08_ov5_def["trigger_dispatched"] is True
        and d_r08_ov5_def["baseline_ocr_override_applied"] is True
        and d_r08_ov5_def["adjudicated_verdict"] == "FAIL"
        and d_r08_ov5_forced["adjudicated_verdict"] == "FAIL"
        and d_r08_ov5_def["passes_15mmhg_floor_unrounded"] is False
        and d_r08_ov5_def["face_min_mmhg_unrounded"] < 15.0
        and abs(d_r08_ov5_def["face_min_mmhg_unrounded"] - d_r08_ov5_forced["face_min_mmhg_unrounded"]) < 1e-12
    )
    tests.append({
        "test": "r08_b2_r2_dz40_default_pbed40_base5p0_meas10p0_fails_in_default_and_forced",
        "baseline_min_face_unrounded_mmhg": d_r08_ov5_def["baseline_min_face_unrounded_mmhg"],
        "default_face_min_unrounded_mmhg": d_r08_ov5_def["face_min_mmhg_unrounded"],
        "forced_face_min_unrounded_mmhg": d_r08_ov5_forced["face_min_mmhg_unrounded"],
        "default_verdict": d_r08_ov5_def["adjudicated_verdict"],
        "forced_verdict": d_r08_ov5_forced["adjudicated_verdict"],
        "solver_executed": d_r08_ov5_def["solver_executed"],
        "passed": ok_13,
    })

    # 14. R08-B2 (c): Canonical zero-increase monotone fast-path (ocr_u95 <= baseline on >=15.0
    #     native baseline, zero overrides) agrees 100% with forced 3D solve (PASS >= 15.0 mmHg)!
    d_r08_mono_def = dispatch_and_solve_nw08_measured_ocr(
        "R2_DZ40",
        1.097,
        0.0,
        openislet_root=openislet_root,
    )
    d_r08_mono_forced = dispatch_and_solve_nw08_measured_ocr(
        "R2_DZ40",
        1.097,
        0.0,
        openislet_root=openislet_root,
        always_solve_3d=True,
    )
    ok_14 = bool(
        d_r08_mono_def["within_provably_monotone_no_increase_domain"] is True
        and d_r08_mono_def["solver_executed"] is False
        and d_r08_mono_def["adjudicated_verdict"] == "PASS"
        and d_r08_mono_forced["adjudicated_verdict"] == "PASS"
        and d_r08_mono_forced["face_min_mmhg_unrounded"] >= 15.0
    )
    tests.append({
        "test": "r08_b2_canonical_zero_increase_monotone_fast_path_agrees_with_forced_3d",
        "within_provably_monotone_no_increase_domain": d_r08_mono_def["within_provably_monotone_no_increase_domain"],
        "default_verdict": d_r08_mono_def["adjudicated_verdict"],
        "forced_verdict": d_r08_mono_forced["adjudicated_verdict"],
        "forced_face_min_unrounded_mmhg": d_r08_mono_forced["face_min_mmhg_unrounded"],
        "passed": ok_14,
    })

    # 15. R09-B3 (a): Exact canonical dispatch (ZERO 1e-12 deadband) — 1-ULP p_bed_mmhg overrides
    #     below and above 40.0 mmHg MUST set p_bed_override_applied=True and execute native 3D FVM!
    pbed_1ulp_lo = math.nextafter(40.0, 0.0)
    pbed_1ulp_hi = math.nextafter(40.0, math.inf)
    d_r09_pb_lo = dispatch_and_solve_nw08_measured_ocr(
        "R2_DZ40", 1.0, 0.0, openislet_root=openislet_root, p_bed_mmhg=pbed_1ulp_lo
    )
    d_r09_pb_lo_frc = dispatch_and_solve_nw08_measured_ocr(
        "R2_DZ40", 1.0, 0.0, openislet_root=openislet_root, p_bed_mmhg=pbed_1ulp_lo, always_solve_3d=True
    )
    d_r09_pb_hi = dispatch_and_solve_nw08_measured_ocr(
        "R2_DZ40", 1.0, 0.0, openislet_root=openislet_root, p_bed_mmhg=pbed_1ulp_hi
    )
    ok_15 = bool(
        d_r09_pb_lo["p_bed_override_applied"] is True
        and d_r09_pb_lo["any_parameter_override_applied"] is True
        and d_r09_pb_lo["within_provably_monotone_no_increase_domain"] is False
        and d_r09_pb_lo["solver_executed"] is True
        and d_r09_pb_lo["effective_p_bed_mmhg"] == pbed_1ulp_lo
        and d_r09_pb_lo["solver_p_bed_mmhg_verified"] == pbed_1ulp_lo
        and d_r09_pb_lo["face_min_mmhg_unrounded"] is not None
        and d_r09_pb_lo["face_min_mmhg_unrounded"] == d_r09_pb_lo_frc["face_min_mmhg_unrounded"]
        and d_r09_pb_hi["p_bed_override_applied"] is True
        and d_r09_pb_hi["any_parameter_override_applied"] is True
        and d_r09_pb_hi["solver_executed"] is True
        and d_r09_pb_hi["effective_p_bed_mmhg"] == pbed_1ulp_hi
        and d_r09_pb_hi["solver_p_bed_mmhg_verified"] == pbed_1ulp_hi
        and d_r09_pb_hi["face_min_mmhg_unrounded"] is not None
    )
    tests.append({
        "test": "r09_b3_r2_dz40_one_ulp_pbed_below_and_above_40mmhg_executes_native_3d_fvm",
        "pbed_1ulp_below_40": pbed_1ulp_lo,
        "pbed_1ulp_above_40": pbed_1ulp_hi,
        "below_solver_executed": d_r09_pb_lo["solver_executed"],
        "above_solver_executed": d_r09_pb_hi["solver_executed"],
        "below_face_min_unrounded_mmhg": d_r09_pb_lo["face_min_mmhg_unrounded"],
        "above_face_min_unrounded_mmhg": d_r09_pb_hi["face_min_mmhg_unrounded"],
        "passed": ok_15,
    })

    # 16. R09-B3 (b): Exact canonical dispatch (ZERO 1e-12 deadband) — 1-ULP baseline_vasc_ocr_mult
    #     overrides above and below 1.097 MUST set baseline_ocr_override_applied=True and execute 3D FVM!
    base_1ulp_hi = math.nextafter(1.097, math.inf)
    base_1ulp_lo = math.nextafter(1.097, 0.0)
    d_r09_b_hi = dispatch_and_solve_nw08_measured_ocr(
        "R2_DZ40", 1.0, 0.0, openislet_root=openislet_root, baseline_vasc_ocr_mult=base_1ulp_hi
    )
    d_r09_b_lo = dispatch_and_solve_nw08_measured_ocr(
        "R2_DZ40", 1.0, 0.0, openislet_root=openislet_root, baseline_vasc_ocr_mult=base_1ulp_lo
    )
    ok_16 = bool(
        d_r09_b_hi["baseline_ocr_override_applied"] is True
        and d_r09_b_hi["any_parameter_override_applied"] is True
        and d_r09_b_hi["within_provably_monotone_no_increase_domain"] is False
        and d_r09_b_hi["solver_executed"] is True
        and d_r09_b_hi["face_min_mmhg_unrounded"] is not None
        and d_r09_b_lo["baseline_ocr_override_applied"] is True
        and d_r09_b_lo["any_parameter_override_applied"] is True
        and d_r09_b_lo["within_provably_monotone_no_increase_domain"] is False
        and d_r09_b_lo["solver_executed"] is True
        and d_r09_b_lo["face_min_mmhg_unrounded"] is not None
    )
    tests.append({
        "test": "r09_b3_r2_dz40_one_ulp_baseline_vasc_ocr_above_and_below_1p097_executes_native_3d_fvm",
        "baseline_1ulp_above_1p097": base_1ulp_hi,
        "baseline_1ulp_below_1p097": base_1ulp_lo,
        "above_solver_executed": d_r09_b_hi["solver_executed"],
        "below_solver_executed": d_r09_b_lo["solver_executed"],
        "above_face_min_unrounded_mmhg": d_r09_b_hi["face_min_mmhg_unrounded"],
        "below_face_min_unrounded_mmhg": d_r09_b_lo["face_min_mmhg_unrounded"],
        "passed": ok_16,
    })

    # 17. R09-B3 (c): 1-ULP positive measured_ocr AND sub-ULP positive uncertainty_se at canonical
    #     baseline MUST both exit monotone fast-path and execute native 3D FVM!
    meas_1ulp_hi = math.nextafter(1.097, math.inf)
    d_r09_m_hi = dispatch_and_solve_nw08_measured_ocr(
        "R2_DZ40", meas_1ulp_hi, 0.0, openislet_root=openislet_root
    )
    d_r09_se_tiny = dispatch_and_solve_nw08_measured_ocr(
        "R2_DZ40", 1.097, 1e-20, openislet_root=openislet_root, **_known_sig
    )
    ok_17 = bool(
        d_r09_m_hi["within_provably_monotone_no_increase_domain"] is False
        and d_r09_m_hi["solver_executed"] is True
        and d_r09_m_hi["face_min_mmhg_unrounded"] is not None
        and d_r09_se_tiny["within_provably_monotone_no_increase_domain"] is False
        and d_r09_se_tiny["solver_executed"] is True
        and d_r09_se_tiny["face_min_mmhg_unrounded"] is not None
    )
    tests.append({
        "test": "r09_b3_r2_dz40_one_ulp_and_sub_ulp_positive_measured_ocr_executes_native_3d_fvm",
        "meas_1ulp_solver_executed": d_r09_m_hi["solver_executed"],
        "sub_ulp_se_solver_executed": d_r09_se_tiny["solver_executed"],
        "meas_1ulp_face_min_unrounded_mmhg": d_r09_m_hi["face_min_mmhg_unrounded"],
        "passed": ok_17,
    })

    # 18. R09-M1 + R09-B1 + R14-B1: Explicit operator file/CLI entry point `evaluate_nw08_measured_ocr_file`
    #     handles PASS (exit 0), mesh-converged FAIL (exit 3), mesh-straddling HOLD (exit 2),
    #     duplicate-key JSON (exit 2), and NaN JSON (exit 2)!
    with tempfile.TemporaryDirectory() as td_ocr:
        td_op = Path(td_ocr)
        f_pass = td_op / "nw08_pass.json"
        f_pass.write_text('{"route_id": "R2_DZ40", "measured_ocr": 1.097, "uncertainty_se": 0.0}', encoding="utf-8")
        f_fail = td_op / "nw08_fail.json"
        f_fail.write_text(
            '{"route_id": "R2_DZ40", "measured_ocr": 10.0, "uncertainty_se": 0.0, '
            '"baseline_vasc_ocr_mult": 5.0}',
            encoding="utf-8",
        )
        f_straddle = td_op / "nw08_straddle.json"
        f_straddle.write_text(
            '{"route_id": "R2_DZ40", "measured_ocr": 2.099752752324571, "uncertainty_se": 0.0, '
            '"baseline_vasc_ocr_mult": 2.0, "p_bed_mmhg": 32.0}',
            encoding="utf-8",
        )
        f_dup = td_op / "nw08_dup.json"
        f_dup.write_text(
            '{"route_id": "R1_350_stress", "route_id": "R2_DZ40", "measured_ocr": 1.097, "uncertainty_se": 0.0}',
            encoding="utf-8",
        )
        f_nan = td_op / "nw08_nan.json"
        f_nan.write_text('{"route_id": "R2_DZ40", "measured_ocr": NaN, "uncertainty_se": 0.0}', encoding="utf-8")
        res_p, rc_p = evaluate_nw08_measured_ocr_file(f_pass, openislet_root=openislet_root)
        res_f, rc_f = evaluate_nw08_measured_ocr_file(f_fail, openislet_root=openislet_root)
        res_st, rc_st = evaluate_nw08_measured_ocr_file(f_straddle, openislet_root=openislet_root)
        res_d, rc_d = evaluate_nw08_measured_ocr_file(f_dup, openislet_root=openislet_root)
        res_n, rc_n = evaluate_nw08_measured_ocr_file(f_nan, openislet_root=openislet_root)
    ok_18 = bool(
        rc_p == 0
        and res_p.get("adjudicated_verdict") == "PASS"
        and rc_f == 3
        and res_f.get("adjudicated_verdict") == "FAIL"
        and res_f.get("solver_executed") is True
        and rc_st == 2
        and res_st.get("adjudicated_verdict") == "HOLD"
        and "HOLD_NW08_MESH_CONVERGENCE_STRADDLES_15MMHG_FLOOR" in (res_st.get("holds") or [])
        and rc_d == 2
        and "HOLD_NW08_AMBIGUOUS_OR_NONCANONICAL_OCR_JSON:DUPLICATE_JSON_KEY" in (res_d.get("holds") or [])
        and rc_n == 2
        and "HOLD_NW08_AMBIGUOUS_OR_NONCANONICAL_OCR_JSON:NON_STANDARD_JSON_CONSTANT" in (res_n.get("holds") or [])
    )
    tests.append({
        "test": "r09_m1_b1_operator_nw08_ocr_file_entrypoint_pass_fail_and_strict_json_holds",
        "pass_rc": rc_p,
        "fail_rc": rc_f,
        "straddle_hold_rc": rc_st,
        "dup_key_rc": rc_d,
        "nan_rc": rc_n,
        "passed": ok_18,
    })

    # 19. R10-B2: Out-of-float64-range integers (10**400), overflowing float (1e500), sum overflow (1e308+1e308),
    #     and unhashable list route_id fail closed cleanly (structured HOLD exit 2 on file entry point; ValueError on API)!
    with tempfile.TemporaryDirectory() as td_r10_ocr:
        td_r10_o = Path(td_r10_ocr)
        bad_ocr_files = (
            ("meas_1e400", f'{{"route_id": "R2_DZ40", "measured_ocr": {10**400}, "uncertainty_se": 0}}'),
            ("se_1e400", f'{{"route_id": "R2_DZ40", "measured_ocr": 1.097, "uncertainty_se": {10**400}}}'),
            ("pbed_1e400", f'{{"route_id": "R2_DZ40", "measured_ocr": 1.097, "uncertainty_se": 0, "p_bed_mmhg": {10**400}}}'),
            ("meas_1e500", '{"route_id": "R2_DZ40", "measured_ocr": 1e500, "uncertainty_se": 0}'),
            ("sum_overflow", '{"route_id": "R2_DZ40", "measured_ocr": 1e308, "uncertainty_se": 1e308}'),
            ("list_route", '{"route_id": ["R2_DZ40"], "measured_ocr": 1.097, "uncertainty_se": 0}'),
        )
        r10_f_ok = True
        for b_tag, b_raw in bad_ocr_files:
            bf = td_r10_o / f"bad_{b_tag}.json"
            bf.write_text(b_raw, encoding="utf-8")
            bres, brc = evaluate_nw08_measured_ocr_file(bf, openislet_root=openislet_root)
            if not (brc == 2 and bres.get("adjudicated_verdict") == "HOLD" and bres.get("solver_executed") is False):
                r10_f_ok = False
    r10_api_ok = True
    for bad_call in (
        lambda: dispatch_and_solve_nw08_measured_ocr("R2_DZ40", 10 ** 400, 0.0, openislet_root=openislet_root),
        lambda: dispatch_and_solve_nw08_measured_ocr("R2_DZ40", 1.097, 10 ** 400, openislet_root=openislet_root),
        lambda: dispatch_and_solve_nw08_measured_ocr("R2_DZ40", 1.097, 0.0, p_bed_mmhg=10 ** 400, openislet_root=openislet_root),
        lambda: dispatch_and_solve_nw08_measured_ocr("R2_DZ40", 1e308, 1e308, openislet_root=openislet_root),
        lambda: dispatch_and_solve_nw08_measured_ocr(["R2_DZ40"], 1.097, 0.0, openislet_root=openislet_root),  # type: ignore[arg-type]
    ):
        raised_ve = False
        try:
            bad_call()
        except ValueError:
            raised_ve = True
        except Exception:
            raised_ve = False
        if not raised_ve:
            r10_api_ok = False
    tests.append({
        "test": "r10_b2_nw08_ocr_file_and_api_reject_10pow400_1e500_overflow_and_list_route_exit_2",
        "file_cases_all_structured_hold_exit_2": r10_f_ok,
        "api_cases_all_raise_value_error": r10_api_ok,
        "passed": bool(r10_f_ok and r10_api_ok),
    })

    # 20. R10-B1: Coupled lot + planned-route + lot_payload_sha256 + evidence digest + external store binding
    #     on `evaluate_nw08_measured_ocr_file`: matched R2_DZ40 passes (exit 0), matched failing R1_350_stress
    #     fails (exit 3), while route swap, stale lot hash, tampered ocr_record_sha256, and missing lot route HOLD (exit 2)!
    with tempfile.TemporaryDirectory() as td_r10_bind:
        td_rb = Path(td_r10_bind)
        ev_sha = _valid_digest("r10_b1_nw08_raw_respirometry_v1")
        lot_sha_r2 = _valid_digest("r10_b1_lot_bundle_r2")
        lot_sha_r1 = _valid_digest("r10_b1_lot_bundle_r1")
        bind_ctx_r2 = {
            "lot_id": "LOT-R10-BIND-001",
            "mcb_id": "MCB-R10-BIND-001",
            "canonical_product_variant_id": "ISLET1_A4_ARM1B",
            "computed_payload_sha256": lot_sha_r2,
            "payload_sha256_verified": True,
            "planned_nw08_route_id": "R2_DZ40",
            "planned_nw08_route_errors": [],
            "planned_nw08_measurement_evidence_sha256": ev_sha,
            "planned_nw08_measurement_not_before_utc": "2026-11-28T00:00:00Z",
            "require_trusted_nw08_ocr_record": True,
        }
        bind_ctx_r1 = {
            **bind_ctx_r2,
            "computed_payload_sha256": lot_sha_r1,
            "planned_nw08_route_id": "R1_350_stress",
            "require_trusted_nw08_ocr_record": False,
        }
        bind_ctx_no_route = {**bind_ctx_r1, "planned_nw08_route_id": None}
        rec_r2_ok = build_bound_nw08_ocr_record(
            lot_id="LOT-R10-BIND-001",
            mcb_id="MCB-R10-BIND-001",
            product_variant_id="ISLET1_A4_ARM1B",
            route_id="R2_DZ40",
            lot_payload_sha256=lot_sha_r2,
            measured_ocr=1.097,
            uncertainty_se=0.0,
            measurement_record_id="OCR-REC-R10-001",
            measurement_evidence_sha256=ev_sha,
            measurement_timestamp_utc="2026-11-29T00:00:00Z",
        )
        rec_r1_fail = build_bound_nw08_ocr_record(
            lot_id="LOT-R10-BIND-001",
            mcb_id="MCB-R10-BIND-001",
            product_variant_id="ISLET1_A4_ARM1B",
            route_id="R1_350_stress",
            lot_payload_sha256=lot_sha_r1,
            measured_ocr=1.3164,
            uncertainty_se=0.0,
            measurement_record_id="OCR-REC-R10-002",
            measurement_evidence_sha256=ev_sha,
            measurement_timestamp_utc="2026-11-29T00:00:00Z",
        )
        rec_r1_swapped_r2 = build_bound_nw08_ocr_record(
            lot_id="LOT-R10-BIND-001",
            mcb_id="MCB-R10-BIND-001",
            product_variant_id="ISLET1_A4_ARM1B",
            route_id="R2_DZ40",
            lot_payload_sha256=lot_sha_r1,
            measured_ocr=1.3164,
            uncertainty_se=0.0,
            measurement_record_id="OCR-REC-R10-SWAP",
            measurement_evidence_sha256=ev_sha,
            measurement_timestamp_utc="2026-11-29T00:00:00Z",
        )
        rec_stale_hash = build_bound_nw08_ocr_record(
            lot_id="LOT-R10-BIND-001",
            mcb_id="MCB-R10-BIND-001",
            product_variant_id="ISLET1_A4_ARM1B",
            route_id="R1_350_stress",
            lot_payload_sha256=_valid_digest("r10_b1_older_lot_hash"),
            measured_ocr=1.097,
            uncertainty_se=0.0,
            measurement_record_id="OCR-REC-R10-STALE",
            measurement_evidence_sha256=ev_sha,
            measurement_timestamp_utc="2026-11-29T00:00:00Z",
        )
        ocr_store_f = td_rb / "qa_ocr_store.json"
        write_record_to_trusted_qualification_store(ocr_store_f, rec_r2_ok, category="nw08_ocr_records")

        f_r2 = td_rb / "r2_ok.json"
        f_r2.write_text(json.dumps(rec_r2_ok), encoding="utf-8")
        f_r1_f = td_rb / "r1_fail.json"
        f_r1_f.write_text(json.dumps(rec_r1_fail), encoding="utf-8")
        f_swap = td_rb / "r1_swap_r2.json"
        f_swap.write_text(json.dumps(rec_r1_swapped_r2), encoding="utf-8")
        f_stale = td_rb / "r1_stale.json"
        f_stale.write_text(json.dumps(rec_stale_hash), encoding="utf-8")

        rp_ok, rcp_ok = evaluate_nw08_measured_ocr_file(
            f_r2, openislet_root=openislet_root, coupled_lot_binding=bind_ctx_r2, trusted_qualification_store=ocr_store_f
        )
        rp_nostore, rcp_nostore = evaluate_nw08_measured_ocr_file(
            f_r2, openislet_root=openislet_root, coupled_lot_binding=bind_ctx_r2, trusted_qualification_store=None
        )
        rf_r1, rcf_r1 = evaluate_nw08_measured_ocr_file(
            f_r1_f, openislet_root=openislet_root, coupled_lot_binding=bind_ctx_r1
        )
        rs_sw, rcs_sw = evaluate_nw08_measured_ocr_file(
            f_swap, openislet_root=openislet_root, coupled_lot_binding=bind_ctx_r1
        )
        rs_st, rcs_st = evaluate_nw08_measured_ocr_file(
            f_stale, openislet_root=openislet_root, coupled_lot_binding=bind_ctx_r1
        )
        rs_nr, rcs_nr = evaluate_nw08_measured_ocr_file(
            f_r1_f, openislet_root=openislet_root, coupled_lot_binding=bind_ctx_no_route
        )
    ok_20 = bool(
        rcp_ok == 0
        and rp_ok.get("adjudicated_verdict") == "PASS"
        and rp_ok.get("lot_binding_verified") is True
        and rcp_nostore == 2
        and "HOLD_NW08_COUPLED_EXTERNAL_OCR_STORE_REQUIRED_BUT_NOT_PROVIDED" in (rp_nostore.get("holds") or [])
        and rcf_r1 == 3
        and rf_r1.get("adjudicated_verdict") == "FAIL"
        and rcs_sw == 2
        and "HOLD_NW08_COUPLED_ROUTE_ID_MISMATCH" in (rs_sw.get("holds") or [])
        and rcs_st == 2
        and "HOLD_NW08_COUPLED_STALE_OR_MISMATCHED_LOT_PAYLOAD_SHA256" in (rs_st.get("holds") or [])
        and rcs_nr == 2
        and "HOLD_NW08_COUPLED_LOT_MISSING_PLANNED_ROUTE" in (rs_nr.get("holds") or [])
    )
    tests.append({
        "test": "r10_b1_nw08_ocr_file_coupled_binding_matched_swapped_stale_missing_route_and_store",
        "matched_pass_rc": rcp_ok,
        "missing_required_store_rc": rcp_nostore,
        "matched_fail_rc": rcf_r1,
        "route_swap_rc": rcs_sw,
        "stale_hash_rc": rcs_st,
        "missing_lot_route_rc": rcs_nr,
        "passed": ok_20,
    })

    # 21. R11-B2: Standalone unbound `--dispatch-nw08-ocr` (`evaluate_nw08_measured_ocr_file` with
    #     coupled_lot_binding=None) MUST emit `release_authorizing = False` at top-level AND across
    #     every nested sub-dict on BOTH monotone fast-path PASS, 3D-FVM solve PASS, and 3D-FVM FAIL!
    def _has_any_release_authorizing_true(obj: Any) -> bool:
        stack: List[Any] = [obj]
        while stack:
            cur = stack.pop()
            if isinstance(cur, dict):
                if cur.get("release_authorizing") is True:
                    return True
                for v in cur.values():
                    if isinstance(v, (dict, list, tuple)):
                        stack.append(v)
            elif isinstance(cur, (list, tuple)):
                for item in cur:
                    if isinstance(item, (dict, list, tuple)):
                        stack.append(item)
        return False

    with tempfile.TemporaryDirectory() as td_r11_b2:
        td_b2 = Path(td_r11_b2)
        f_sa_fast = td_b2 / "sa_fast_pass.json"
        f_sa_fast.write_text('{"route_id": "R2_DZ40", "measured_ocr": 1.097, "uncertainty_se": 0.0}', encoding="utf-8")
        f_sa_3d_pass = td_b2 / "sa_3d_pass.json"
        f_sa_3d_pass.write_text('{"route_id": "R2_DZ40", "measured_ocr": 1.3164, "uncertainty_se": 0.0}', encoding="utf-8")
        f_sa_3d_fail = td_b2 / "sa_3d_fail.json"
        f_sa_3d_fail.write_text('{"route_id": "R1_350_stress", "measured_ocr": 1.3164, "uncertainty_se": 0.0}', encoding="utf-8")
        r_sa_fast, rc_sa_fast = evaluate_nw08_measured_ocr_file(f_sa_fast, openislet_root=openislet_root)
        r_sa_3dp, rc_sa_3dp = evaluate_nw08_measured_ocr_file(f_sa_3d_pass, openislet_root=openislet_root)
        r_sa_3df, rc_sa_3df = evaluate_nw08_measured_ocr_file(f_sa_3d_fail, openislet_root=openislet_root)
    ok_21 = bool(
        rc_sa_fast == 0
        and r_sa_fast.get("adjudicated_verdict") == "PASS"
        and r_sa_fast.get("binding_mode") == "STANDALONE_UNBOUND_DIAGNOSTIC_ONLY"
        and r_sa_fast.get("lot_binding_verified") is False
        and r_sa_fast.get("release_authorizing") is False
        and r_sa_fast.get("solver_cleared_oxygen_floor_diagnostic") is True
        and not _has_any_release_authorizing_true(r_sa_fast)
        and rc_sa_3dp == 0
        and r_sa_3dp.get("adjudicated_verdict") == "PASS"
        and r_sa_3dp.get("solver_executed") is True
        and r_sa_3dp.get("release_authorizing") is False
        and r_sa_3dp.get("solver_cleared_oxygen_floor_diagnostic") is True
        and not _has_any_release_authorizing_true(r_sa_3dp)
        and rc_sa_3df == 3
        and r_sa_3df.get("adjudicated_verdict") == "FAIL"
        and r_sa_3df.get("release_authorizing") is False
        and r_sa_3df.get("solver_cleared_oxygen_floor_diagnostic") is False
        and not _has_any_release_authorizing_true(r_sa_3df)
    )
    tests.append({
        "test": "r11_b2_standalone_unbound_nw08_ocr_release_authorizing_false_recursively",
        "fast_pass_release_authorizing": r_sa_fast.get("release_authorizing"),
        "solve_pass_release_authorizing": r_sa_3dp.get("release_authorizing"),
        "solve_fail_release_authorizing": r_sa_3df.get("release_authorizing"),
        "passed": ok_21,
    })

    # 22. R11-B4: JSON nesting depth > 64 AND injected parser RecursionError on `--dispatch-nw08-ocr`
    #     intake BOTH map cleanly to structured HOLD exit 2 (`release_authorizing = False`), zero traceback!
    with tempfile.TemporaryDirectory() as td_r11_b4:
        td_b4 = Path(td_r11_b4)
        f_deep_ocr = td_b4 / "deep_70_ocr.json"
        f_deep_ocr.write_text('{"a":' * 70 + "1" + "}" * 70, encoding="utf-8")
        r_deep_ocr, rc_deep_ocr = evaluate_nw08_measured_ocr_file(f_deep_ocr, openislet_root=openislet_root)
        f_empty_ocr = td_b4 / "empty_ocr.json"
        f_empty_ocr.write_text("{}", encoding="utf-8")
        orig_json_loads = json.loads

        def _raise_rec_err(*_a: Any, **_kw: Any) -> Any:
            raise RecursionError("simulated parser recursion limit")

        json.loads = _raise_rec_err  # type: ignore[assignment]
        try:
            r_rec_ocr, rc_rec_ocr = evaluate_nw08_measured_ocr_file(f_empty_ocr, openislet_root=openislet_root)
        finally:
            json.loads = orig_json_loads  # type: ignore[assignment]
    ok_22 = bool(
        rc_deep_ocr == 2
        and r_deep_ocr.get("adjudicated_verdict") == "HOLD"
        and r_deep_ocr.get("release_authorizing") is False
        and "HOLD_NW08_AMBIGUOUS_OR_NONCANONICAL_OCR_JSON:JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED" in (r_deep_ocr.get("holds") or [])
        and rc_rec_ocr == 2
        and r_rec_ocr.get("adjudicated_verdict") == "HOLD"
        and r_rec_ocr.get("release_authorizing") is False
        and "HOLD_NW08_AMBIGUOUS_OR_NONCANONICAL_OCR_JSON:JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED" in (r_rec_ocr.get("holds") or [])
    )
    tests.append({
        "test": "r11_b4_nw08_ocr_depth_gt_64_and_injected_recursion_error_structured_hold_exit_2",
        "deep_70_rc": rc_deep_ocr,
        "injected_recursion_error_rc": rc_rec_ocr,
        "passed": ok_22,
    })

    # 23. R12-B2: Nonzero float underflow (-1e-400, 1e-400) AND signed negative zero (-0.0, "-0.0")
    #     on NW-08 OCR boundary keys MUST fail closed (exit 2 HOLD, release_authorizing=False,
    #     solver_executed=False on file entry; ValueError on Python API) — NEVER silent PASS!
    with tempfile.TemporaryDirectory() as td_r12_b2:
        td_12b2 = Path(td_r12_b2)
        f_uf_se = td_12b2 / "underflow_neg_se.json"
        f_uf_se.write_text('{"route_id": "R2_DZ40", "measured_ocr": 1.097, "uncertainty_se": -1e-400}', encoding="utf-8")
        f_uf_pos = td_12b2 / "underflow_pos_ocr.json"
        f_uf_pos.write_text('{"route_id": "R2_DZ40", "measured_ocr": 1e-400, "uncertainty_se": 0.0}', encoding="utf-8")
        f_sz_num = td_12b2 / "signed_zero_num.json"
        f_sz_num.write_text('{"route_id": "R2_DZ40", "measured_ocr": 1.097, "uncertainty_se": -0.0}', encoding="utf-8")
        f_sz_str = td_12b2 / "signed_zero_str.json"
        f_sz_str.write_text('{"route_id": "R2_DZ40", "measured_ocr": 1.097, "uncertainty_se": "-0.0"}', encoding="utf-8")
        r_uf_se, rc_uf_se = evaluate_nw08_measured_ocr_file(f_uf_se, openislet_root=openislet_root)
        r_uf_pos, rc_uf_pos = evaluate_nw08_measured_ocr_file(f_uf_pos, openislet_root=openislet_root)
        r_sz_num, rc_sz_num = evaluate_nw08_measured_ocr_file(f_sz_num, openislet_root=openislet_root)
        r_sz_str, rc_sz_str = evaluate_nw08_measured_ocr_file(f_sz_str, openislet_root=openislet_root)

    api_neg_zero_rejected = False
    try:
        dispatch_and_solve_nw08_measured_ocr("R2_DZ40", 1.097, -0.0, openislet_root=openislet_root)
    except ValueError:
        api_neg_zero_rejected = True
    api_dec_underflow_rejected = False
    try:
        dispatch_and_solve_nw08_measured_ocr("R2_DZ40", 1.097, Decimal("-1e-400"), openislet_root=openislet_root)
    except ValueError:
        api_dec_underflow_rejected = True

    ok_23 = bool(
        rc_uf_se == 2
        and r_uf_se.get("adjudicated_verdict") == "HOLD"
        and r_uf_se.get("release_authorizing") is False
        and r_uf_se.get("solver_executed") is False
        and "HOLD_NW08_AMBIGUOUS_OR_NONCANONICAL_OCR_JSON:NONZERO_FLOAT_UNDERFLOW_REJECTED" in (r_uf_se.get("holds") or [])
        and rc_uf_pos == 2
        and r_uf_pos.get("adjudicated_verdict") == "HOLD"
        and r_uf_pos.get("release_authorizing") is False
        and "HOLD_NW08_AMBIGUOUS_OR_NONCANONICAL_OCR_JSON:NONZERO_FLOAT_UNDERFLOW_REJECTED" in (r_uf_pos.get("holds") or [])
        and rc_sz_num == 2
        and r_sz_num.get("adjudicated_verdict") == "HOLD"
        and r_sz_num.get("release_authorizing") is False
        and r_sz_num.get("solver_executed") is False
        and "INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE" in (r_sz_num.get("holds") or [])
        and rc_sz_str == 2
        and r_sz_str.get("adjudicated_verdict") == "HOLD"
        and r_sz_str.get("release_authorizing") is False
        and r_sz_str.get("solver_executed") is False
        and "INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE" in (r_sz_str.get("holds") or [])
        and api_neg_zero_rejected
        and api_dec_underflow_rejected
    )
    tests.append({
        "test": "r12_b2_nw08_ocr_underflow_and_signed_zero_rejected_fail_closed",
        "underflow_neg_se_rc": rc_uf_se,
        "underflow_pos_ocr_rc": rc_uf_pos,
        "signed_zero_num_rc": rc_sz_num,
        "signed_zero_str_rc": rc_sz_str,
        "api_neg_zero_rejected": api_neg_zero_rejected,
        "api_dec_underflow_rejected": api_dec_underflow_rejected,
        "passed": ok_23,
    })

    # 24. R13-M1 + R13-B4: JSON integer spelling `-0` AND quoted string `"-0"` for non-negative
    #     NW-08 boundary keys (`uncertainty_se`) MUST fail closed (exit 2 HOLD,
    #     `INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE`, `solver_executed=False`), AND live
    #     standalone PASS responses carry explicit `qualification_scope` & `physical_qualification_complete=False`!
    with tempfile.TemporaryDirectory() as td_r13_m1:
        td_13m1 = Path(td_r13_m1)
        f_neg_int_0 = td_13m1 / "neg_zero_int.json"
        f_neg_int_0.write_text('{"route_id": "R2_DZ40", "measured_ocr": 1.097, "uncertainty_se": -0}', encoding="utf-8")
        f_neg_str_0 = td_13m1 / "neg_zero_int_str.json"
        f_neg_str_0.write_text('{"route_id": "R2_DZ40", "measured_ocr": 1.097, "uncertainty_se": "-0"}', encoding="utf-8")
        f_clean_ocr = td_13m1 / "clean_ocr.json"
        f_clean_ocr.write_text('{"route_id": "R2_DZ40", "measured_ocr": 1.097, "uncertainty_se": 0}', encoding="utf-8")
        r_ni0, rc_ni0 = evaluate_nw08_measured_ocr_file(f_neg_int_0, openislet_root=openislet_root)
        r_ns0, rc_ns0 = evaluate_nw08_measured_ocr_file(f_neg_str_0, openislet_root=openislet_root)
        r_cl0, rc_cl0 = evaluate_nw08_measured_ocr_file(f_clean_ocr, openislet_root=openislet_root)
    ok_24 = bool(
        rc_ni0 == 2
        and r_ni0.get("adjudicated_verdict") == "HOLD"
        and r_ni0.get("release_authorizing") is False
        and r_ni0.get("solver_executed") is False
        and "INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE" in (r_ni0.get("holds") or [])
        and "HOLD_NW08_AMBIGUOUS_OR_NONCANONICAL_OCR_JSON:INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE" in (r_ni0.get("holds") or [])
        and rc_ns0 == 2
        and r_ns0.get("adjudicated_verdict") == "HOLD"
        and r_ns0.get("release_authorizing") is False
        and r_ns0.get("solver_executed") is False
        and "INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE" in (r_ns0.get("holds") or [])
        and rc_cl0 == 0
        and r_cl0.get("adjudicated_verdict") == "PASS"
        and r_cl0.get("release_authorizing") is False
        and r_cl0.get("qualification_scope") == QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL
        and r_cl0.get("physical_qualification_complete") is False
    )
    tests.append({
        "test": "r13_m1_b4_nw08_ocr_neg_zero_integer_and_string_rejected_and_pass_scope_attached",
        "neg_int_zero_rc": rc_ni0,
        "neg_str_zero_rc": rc_ns0,
        "clean_zero_rc": rc_cl0,
        "clean_qualification_scope": r_cl0.get("qualification_scope"),
        "passed": ok_24,
    })

    # 25. R14-B1: Both Round-13 observed mesh-resolution reversals (R1_390_stress @ 1.3164, bed=35 AND
    #     R2_DZ40 @ 2.099752752324571, bed=32; full 3-grid audit via force_mesh_convergence_check=True)
    #     plus near-floor R1_350_stress baseline (1.2067, SE=0.0) route cleanly to unresolved HOLD
    #     (exit 2, HOLD_NW08_MESH_CONVERGENCE_STRADDLES_15MMHG_FLOOR)!
    r14_r1_res, r14_r1_rc = evaluate_nw08_measured_ocr_record(
        {
            "route_id": "R1_390_stress",
            "measured_ocr": 1.3164,
            "uncertainty_se": 0.0,
            "force_mesh_convergence_check": True,
        },
        openislet_root=openislet_root,
    )
    r14_r2_res, r14_r2_rc = evaluate_nw08_measured_ocr_record(
        {
            "route_id": "R2_DZ40",
            "measured_ocr": 2.099752752324571,
            "uncertainty_se": 0.0,
            "baseline_vasc_ocr_mult": 2.0,
            "p_bed_mmhg": 32.0,
            "force_mesh_convergence_check": True,
        },
        openislet_root=openislet_root,
    )
    r14_r1_350_base_res, r14_r1_350_base_rc = evaluate_nw08_measured_ocr_record(
        {"route_id": "R1_350_stress", "measured_ocr": 1.2067, "uncertainty_se": 0.0},
        openislet_root=openislet_root,
    )
    mc_r1 = r14_r1_res.get("mesh_convergence_verification") or {}
    mc_r2 = r14_r2_res.get("mesh_convergence_verification") or {}
    mc_350b = r14_r1_350_base_res.get("mesh_convergence_verification") or {}
    ok_25 = bool(
        r14_r1_rc == 2
        and r14_r1_res.get("adjudicated_verdict") == "HOLD"
        and r14_r1_res.get("release_authorizing") is False
        and r14_r1_res.get("passes_15mmhg_floor_unrounded") is False
        and "HOLD_NW08_MESH_CONVERGENCE_STRADDLES_15MMHG_FLOOR" in (r14_r1_res.get("holds") or [])
        and mc_r1.get("executed") is True
        and mc_r1.get("straddles_canonical_15mmhg_floor") is True
        and len(mc_r1.get("grid_ladder") or []) == 3
        and mc_r1["grid_ladder"][0]["face_min_mmhg_unrounded"] > 15.0
        and mc_r1["grid_ladder"][1]["face_min_mmhg_unrounded"] < 15.0
        and mc_r1["grid_ladder"][2]["face_min_mmhg_unrounded"] > 15.0
        and r14_r2_rc == 2
        and r14_r2_res.get("adjudicated_verdict") == "HOLD"
        and r14_r2_res.get("release_authorizing") is False
        and "HOLD_NW08_MESH_CONVERGENCE_STRADDLES_15MMHG_FLOOR" in (r14_r2_res.get("holds") or [])
        and mc_r2.get("executed") is True
        and mc_r2.get("straddles_canonical_15mmhg_floor") is True
        and len(mc_r2.get("grid_ladder") or []) == 3
        and mc_r2["grid_ladder"][0]["face_min_mmhg_unrounded"] < 15.0
        and mc_r2["grid_ladder"][1]["face_min_mmhg_unrounded"] > 15.0
        and mc_r2["grid_ladder"][2]["face_min_mmhg_unrounded"] > 15.0
        and r14_r1_350_base_rc == 2
        and r14_r1_350_base_res.get("adjudicated_verdict") == "HOLD"
        and mc_350b.get("executed") is True
        and mc_350b.get("straddles_canonical_15mmhg_floor") is True
    )
    tests.append({
        "test": "r14_b1_mesh_convergence_reversals_r1_390_r2_dz40_and_r1_350_baseline_route_to_hold",
        "r1_390_grid_mins": [g["face_min_mmhg_unrounded"] for g in (mc_r1.get("grid_ladder") or [])],
        "r1_390_bounds_mmhg": [mc_r1.get("conservative_po2_lower_bound_mmhg"), mc_r1.get("conservative_po2_upper_bound_mmhg")],
        "r1_390_verdict": r14_r1_res.get("adjudicated_verdict"),
        "r1_390_rc": r14_r1_rc,
        "r2_dz40_grid_mins": [g["face_min_mmhg_unrounded"] for g in (mc_r2.get("grid_ladder") or [])],
        "r2_dz40_bounds_mmhg": [mc_r2.get("conservative_po2_lower_bound_mmhg"), mc_r2.get("conservative_po2_upper_bound_mmhg")],
        "r2_dz40_verdict": r14_r2_res.get("adjudicated_verdict"),
        "r2_dz40_rc": r14_r2_rc,
        "r1_350_baseline_verdict": r14_r1_350_base_res.get("adjudicated_verdict"),
        "passed": ok_25,
    })

    # 26. R14-B2: Small-sample OCR inference (R1_390_stress, OCR=1.25, SE=0.06, n=6 -> df=5,
    #     t_{0.95, 5} = 2.0150484, u95 = 1.370903 -> native 14.98082429 < 15.0, 3-grid decisive FAIL exit 3),
    #     independent justified upper bound reproduces FAIL exit 3, bare undeclared SE=0.06 HOLDs exit 2,
    #     and declared KNOWN_SIGMA_NORMAL at 1.25 +/- 0.06 still HOLDs exit 2 under Blocker #1 mesh check!
    r14_b2_bare, r14_b2_bare_rc = evaluate_nw08_measured_ocr_record(
        {"route_id": "R1_390_stress", "measured_ocr": 1.25, "uncertainty_se": 0.06},
        openislet_root=openislet_root,
    )
    r14_b2_t6, r14_b2_t6_rc = evaluate_nw08_measured_ocr_record(
        {
            "route_id": "R1_390_stress",
            "measured_ocr": 1.25,
            "uncertainty_se": 0.06,
            "ocr_uncertainty_model": NW08_OCR_UNCERTAINTY_MODEL_STUDENT_T,
            "ocr_replicates_n": 6,
        },
        openislet_root=openislet_root,
    )
    r14_b2_indep, r14_b2_indep_rc = evaluate_nw08_measured_ocr_record(
        {
            "route_id": "R1_390_stress",
            "measured_ocr": 1.25,
            "uncertainty_se": 0.06,
            "ocr_uncertainty_model": NW08_OCR_UNCERTAINTY_MODEL_INDEPENDENT_UPPER,
            "ocr_replicates_n": 6,
            "measured_ocr_u95_override": 1.370903,
            "ocr_uncertainty_provenance": "independent_student_t_df5_upper_95_bound_v1",
        },
        openislet_root=openislet_root,
    )
    r14_b2_norm, r14_b2_norm_rc = evaluate_nw08_measured_ocr_record(
        {
            "route_id": "R1_390_stress",
            "measured_ocr": 1.25,
            "uncertainty_se": 0.06,
            "ocr_uncertainty_model": NW08_OCR_UNCERTAINTY_MODEL_KNOWN_SIGMA,
            "ocr_uncertainty_provenance": "calibrated_respirometer_known_sigma_cert_v1",
        },
        openislet_root=openislet_root,
    )
    ok_26 = bool(
        r14_b2_bare_rc == 2
        and r14_b2_bare.get("adjudicated_verdict") == "HOLD"
        and r14_b2_bare.get("solver_executed") is False
        and "HOLD_NW08_OCR_MISSING_UNCERTAINTY_MODEL_OR_DF" in (r14_b2_bare.get("holds") or [])
        and r14_b2_t6_rc == 3
        and r14_b2_t6.get("adjudicated_verdict") == "FAIL"
        and r14_b2_t6.get("ocr_degrees_of_freedom") == 5
        and abs(float(r14_b2_t6.get("applied_one_sided_95_multiplier") or 0.0) - 2.0150484) < 1e-6
        and abs(float(r14_b2_t6.get("face_min_mmhg_unrounded") or 0.0) - 14.98082429) < 1e-5
        and (r14_b2_t6.get("mesh_convergence_verification") or {}).get("conservative_po2_upper_bound_mmhg", 99.0) < 15.0
        and r14_b2_indep_rc == 3
        and r14_b2_indep.get("adjudicated_verdict") == "FAIL"
        and r14_b2_norm_rc == 2
        and r14_b2_norm.get("adjudicated_verdict") == "HOLD"
        and "HOLD_NW08_MESH_CONVERGENCE_STRADDLES_15MMHG_FLOOR" in (r14_b2_norm.get("holds") or [])
    )
    tests.append({
        "test": "r14_b2_small_sample_student_t_n6_flips_1p25_se0p06_to_fail_and_rejects_bare_se",
        "bare_se_rc": r14_b2_bare_rc,
        "student_t_n6_rc": r14_b2_t6_rc,
        "student_t_n6_multiplier": r14_b2_t6.get("applied_one_sided_95_multiplier"),
        "student_t_n6_u95": r14_b2_t6.get("solved_at_vascular_ocr_u95"),
        "student_t_n6_face_min_unrounded": r14_b2_t6.get("face_min_mmhg_unrounded"),
        "independent_upper_rc": r14_b2_indep_rc,
        "known_sigma_normal_rc": r14_b2_norm_rc,
        "passed": ok_26,
    })

    # 27. R14-B3: Process-wide lock & callback-owner serialization across separately loaded verifier
    #     module instances (direct + composite-wrapper-loaded copy) running barrier-synchronized concurrent solves!
    comp_script_path = openislet_root / "scripts" / "evaluate_gate0v_composite_release.py"
    r14_b3_shared_lock = False
    r14_b3_callbacks_restored = False
    r14_b3_all_matched = False
    if comp_script_path.is_file():
        comp_spec = importlib.util.spec_from_file_location("iip0043_r14_b3_comp_probe", str(comp_script_path))
        if comp_spec is not None and comp_spec.loader is not None:
            comp_probe = importlib.util.module_from_spec(comp_spec)
            comp_spec.loader.exec_module(comp_probe)
            wrapped_v38 = comp_probe._get_v38_module()
            # Also load a second completely distinct exec_module copy of verify_iip0043 to prove
            # process-wide lock sharing holds EVEN WITHOUT sys.modules reuse!
            iso_spec = importlib.util.spec_from_file_location("iip0043_r14_b3_isolated_copy", str(Path(__file__).resolve()))
            iso_v38 = None
            if iso_spec is not None and iso_spec.loader is not None:
                iso_v38 = importlib.util.module_from_spec(iso_spec)
                iso_spec.loader.exec_module(iso_v38)
            r14_b3_shared_lock = bool(
                wrapped_v38._FVM_SOLVER_LOCK is _FVM_SOLVER_LOCK
                and iso_v38 is not None
                and iso_v38 is not sys.modules[__name__]
                and iso_v38._FVM_SOLVER_LOCK is _FVM_SOLVER_LOCK
            )
            scripts_str_b3 = str(openislet_root / "scripts")
            added_b3 = False
            if scripts_str_b3 not in sys.path:
                sys.path.insert(0, scripts_str_b3)
                added_b3 = True
            try:
                import run_layer4_tissue_and_metabolic_twin as l4_b3  # noqa: E402

                orig_cbs = (
                    l4_b3._solve_3d_oxygen_strict_iip_0019,
                    l4_b3._compute_exact_fv_interface_stats_iip_0019,
                )
                ser_a = dispatch_and_solve_nw08_measured_ocr(
                    "R3P_35", 1.3164, 0.0, openislet_root=openislet_root, p_bed_mmhg=35.0
                )
                ser_b = wrapped_v38.dispatch_and_solve_nw08_measured_ocr(
                    "R3P_30", 1.3164, 0.0, openislet_root=openislet_root, p_bed_mmhg=30.0
                )
                ref_pair = (
                    (ser_a["face_min_mmhg_unrounded"], ser_a["adjudicated_verdict"]),
                    (ser_b["face_min_mmhg_unrounded"], ser_b["adjudicated_verdict"]),
                )
                all_attempts_ok = True
                for peer_mod in (wrapped_v38, iso_v38):
                    if peer_mod is None:
                        all_attempts_ok = False
                        continue
                    for _attempt in range(2):
                        barrier_b3 = threading.Barrier(2)

                        def _conc_call(mod_obj: Any, rt: str, pb: float):
                            barrier_b3.wait(timeout=10)
                            out_c = mod_obj.dispatch_and_solve_nw08_measured_ocr(
                                rt, 1.3164, 0.0, openislet_root=openislet_root, p_bed_mmhg=pb
                            )
                            return (out_c["face_min_mmhg_unrounded"], out_c["adjudicated_verdict"])

                        with ThreadPoolExecutor(max_workers=2) as pool_b3:
                            fa = pool_b3.submit(_conc_call, sys.modules[__name__], "R3P_35", 35.0)
                            fb = pool_b3.submit(_conc_call, peer_mod, "R3P_30", 30.0)
                            got_pair = (fa.result(), fb.result())
                        restored_now = bool(
                            orig_cbs
                            == (
                                l4_b3._solve_3d_oxygen_strict_iip_0019,
                                l4_b3._compute_exact_fv_interface_stats_iip_0019,
                            )
                        )
                        if got_pair != ref_pair or not restored_now:
                            all_attempts_ok = False
                r14_b3_callbacks_restored = bool(
                    orig_cbs
                    == (
                        l4_b3._solve_3d_oxygen_strict_iip_0019,
                        l4_b3._compute_exact_fv_interface_stats_iip_0019,
                    )
                )
                r14_b3_all_matched = all_attempts_ok
            finally:
                if added_b3 and scripts_str_b3 in sys.path:
                    sys.path.remove(scripts_str_b3)
    ok_27 = bool(r14_b3_shared_lock and r14_b3_callbacks_restored and r14_b3_all_matched)
    tests.append({
        "test": "r14_b3_concurrent_direct_and_composite_wrapper_shared_lock_and_callback_isolation",
        "shared_process_lock": r14_b3_shared_lock,
        "callbacks_restored": r14_b3_callbacks_restored,
        "all_concurrent_attempts_matched_serial": r14_b3_all_matched,
        "passed": ok_27,
    })

    # 28. R15-B2: Live dispatch & `_evaluate_nw08_mesh_convergence` end-to-end harness test on standard R2
    #     [48, 72, 96] ladder reproducing (a) the exact synthetic slow-order counterexample (p=0.06,
    #     true limit 14.95 < 15.0: 15.012547946, 15.011044645, 15.010000000 -> HOLD exit 2,
    #     HOLD_NW08_MESH_CONVERGENCE_UNQUALIFIED_SLOW_OR_NON_ASYMPTOTIC_ORDER, passes_15mmhg=False,
    #     interval_valid=False, NO clearance bound) and (b) the asymptotic p=1.5 clearance control
    #     (true limit 15.05 > 15.0: 15.163137085, 15.111584029, 15.090000000 -> PASS exit 0,
    #     Richardson 15.05, lower bound 15.04 >= 15.0)!
    from unittest.mock import patch as _mock_patch

    r2_cat_spec = _build_nw08_route_catalog(openislet_root)["R2_DZ40"]
    # Warm native R2_DZ40 baseline cache BEFORE patching so candidate solve only uses patched grid outputs.
    _get_native_unrounded_baseline_mmhg(openislet_root, "R2_DZ40", r2_cat_spec, float(r2_cat_spec["baseline_shared_ocr"]))
    cur_mod = sys.modules[__name__]

    slow_face_map = {48: 15.012547946, 72: 15.011044645, 96: 15.010000000}
    with _mock_patch.object(
        cur_mod, "_solve_nw08_grid_level_cached", side_effect=lambda *a, nx, **kw: (slow_face_map[int(nx)], 40.0)
    ):
        mc_slow_direct = _evaluate_nw08_mesh_convergence(
            openislet_root,
            "R2_DZ40",
            r2_cat_spec,
            vasc_scale=1.0,
            native_coarse_face_mmhg=slow_face_map[48],
            verified_p_bed=40.0,
            force_check=True,
        )
        with _mock_patch.object(
            cur_mod,
            "_execute_single_3d_fvm_vascular_scaled_solve_with_meta",
            side_effect=lambda *a, **kw: ({}, slow_face_map[48], 40.0),
        ):
            rec_slow_res, rec_slow_rc = evaluate_nw08_measured_ocr_record(
                {"route_id": "R2_DZ40", "measured_ocr": 1.3164, "uncertainty_se": 0.0},
                openislet_root=openislet_root,
            )

    acc_face_map = {n: 15.05 + 0.04 * ((96.0 / n) ** 1.5) for n in (48, 72, 96)}
    with _mock_patch.object(
        cur_mod, "_solve_nw08_grid_level_cached", side_effect=lambda *a, nx, **kw: (acc_face_map[int(nx)], 40.0)
    ):
        mc_acc_direct = _evaluate_nw08_mesh_convergence(
            openislet_root,
            "R2_DZ40",
            r2_cat_spec,
            vasc_scale=1.0,
            native_coarse_face_mmhg=acc_face_map[48],
            verified_p_bed=40.0,
            force_check=True,
        )
        with _mock_patch.object(
            cur_mod,
            "_execute_single_3d_fvm_vascular_scaled_solve_with_meta",
            side_effect=lambda *a, **kw: ({}, acc_face_map[48], 40.0),
        ):
            rec_acc_res, rec_acc_rc = evaluate_nw08_measured_ocr_record(
                {"route_id": "R2_DZ40", "measured_ocr": 1.3164, "uncertainty_se": 0.0},
                openislet_root=openislet_root,
            )

    ok_28 = bool(
        mc_slow_direct["verdict_from_mesh_policy"] == "HOLD"
        and mc_slow_direct["hold_reason_token"] == NW08_HOLD_TOKEN_UNQUALIFIED_ORDER
        and mc_slow_direct["interval_valid"] is False
        and mc_slow_direct["order_qualified"] is False
        and mc_slow_direct["conservative_po2_lower_bound_mmhg"] is None
        and mc_slow_direct["apparent_order_p"] is not None
        and abs(mc_slow_direct["apparent_order_p"] - 0.06) < 1e-4
        and rec_slow_rc == 2
        and rec_slow_res["adjudicated_verdict"] == "HOLD"
        and rec_slow_res["passes_15mmhg_floor_unrounded"] is False
        and rec_slow_res["release_authorizing"] is False
        and rec_slow_res["solver_cleared_oxygen_floor_diagnostic"] is False
        and NW08_HOLD_TOKEN_UNQUALIFIED_ORDER in (rec_slow_res.get("holds") or [])
        and mc_acc_direct["verdict_from_mesh_policy"] == "PASS"
        and mc_acc_direct["interval_valid"] is True
        and mc_acc_direct["order_qualified"] is True
        and abs(float(mc_acc_direct["apparent_order_p"]) - 1.5) < 1e-5
        and abs(float(mc_acc_direct["richardson_extrapolated_mmhg"]) - 15.05) < 1e-6
        and abs(float(mc_acc_direct["conservative_po2_lower_bound_mmhg"]) - 15.04) < 1e-6
        and rec_acc_rc == 0
        and rec_acc_res["adjudicated_verdict"] == "PASS"
        and rec_acc_res["passes_15mmhg_floor_unrounded"] is True
        and rec_acc_res["release_authorizing"] is False
    )
    tests.append({
        "test": "r15_b2_live_mesh_harness_slow_p0p06_counterexample_hold_and_asymptotic_p1p5_pass",
        "slow_counterexample_direct_verdict": mc_slow_direct["verdict_from_mesh_policy"],
        "slow_counterexample_observed_order_p": mc_slow_direct["apparent_order_p"],
        "slow_counterexample_record_rc": rec_slow_rc,
        "slow_counterexample_holds": rec_slow_res.get("holds"),
        "slow_counterexample_lower_bound_mmhg": mc_slow_direct["conservative_po2_lower_bound_mmhg"],
        "asymptotic_p1p5_direct_verdict": mc_acc_direct["verdict_from_mesh_policy"],
        "asymptotic_p1p5_observed_order_p": mc_acc_direct["apparent_order_p"],
        "asymptotic_p1p5_richardson_mmhg": mc_acc_direct["richardson_extrapolated_mmhg"],
        "asymptotic_p1p5_lower_bound_mmhg": mc_acc_direct["conservative_po2_lower_bound_mmhg"],
        "asymptotic_p1p5_record_rc": rec_acc_rc,
        "passed": ok_28,
    })

    # 29. R16-B1: Standalone (API, record, file) AND coupled zero-SE inferential-model rejection
    #     (`STUDENT_T_ESTIMATED_SE` & `KNOWN_SIGMA_NORMAL` with `uncertainty_se == 0` -> HOLD BEFORE
    #     solving with `HOLD_NW08_INFERENTIAL_MODEL_REQUIRES_POSITIVE_SE`, `solver_executed=False`,
    #     `release_authorizing=False`, exit 2; `ValueError` on direct API), retaining explicit
    #     `ZERO_UNCERTAINTY_DETERMINISTIC_POINT` control (PASS exit 0), positive-SE Student-t control
    #     (`R1_390_stress, OCR=1.25, SE=0.06, n=6, df=5` -> `u95=1.370903`, coarse `14.9808 mmHg` -> FAIL exit 3),
    #     AND coupled `evaluate_nw08_measured_ocr_file` zero-SE HOLD!
    api_zero_st_rejected = False
    api_zero_ks_rejected = False
    try:
        dispatch_and_solve_nw08_measured_ocr(
            "R1_390_stress",
            1.25,
            0.0,
            openislet_root=openislet_root,
            ocr_uncertainty_model=NW08_OCR_UNCERTAINTY_MODEL_STUDENT_T,
            ocr_replicates_n=6,
        )
    except ValueError as exc_st0:
        api_zero_st_rejected = NW08_HOLD_TOKEN_INFERENTIAL_REQUIRES_POSITIVE_SE in str(exc_st0)
    try:
        dispatch_and_solve_nw08_measured_ocr(
            "R2_DZ40",
            1.097,
            0.0,
            openislet_root=openislet_root,
            ocr_uncertainty_model=NW08_OCR_UNCERTAINTY_MODEL_KNOWN_SIGMA,
            ocr_uncertainty_provenance="calibrated_respirometer_known_sigma_cert_v1",
        )
    except ValueError as exc_ks0:
        api_zero_ks_rejected = NW08_HOLD_TOKEN_INFERENTIAL_REQUIRES_POSITIVE_SE in str(exc_ks0)

    with tempfile.TemporaryDirectory() as td_r16_b1:
        td_16b1 = Path(td_r16_b1)
        f_st0_r2 = td_16b1 / "r16_b1_r2_student_t_se0.json"
        f_st0_r2.write_text(
            json.dumps({
                "route_id": "R2_DZ40",
                "measured_ocr": 1.097,
                "uncertainty_se": 0.0,
                "ocr_uncertainty_model": NW08_OCR_UNCERTAINTY_MODEL_STUDENT_T,
                "ocr_replicates_n": 6,
            }),
            encoding="utf-8",
        )
        f_st0_r1 = td_16b1 / "r16_b1_r1_student_t_se0.json"
        f_st0_r1.write_text(
            json.dumps({
                "route_id": "R1_390_stress",
                "measured_ocr": 1.25,
                "uncertainty_se": 0.0,
                "ocr_uncertainty_model": NW08_OCR_UNCERTAINTY_MODEL_STUDENT_T,
                "ocr_replicates_n": 6,
            }),
            encoding="utf-8",
        )
        f_ks0_r2 = td_16b1 / "r16_b1_r2_known_sigma_se0.json"
        f_ks0_r2.write_text(
            json.dumps({
                "route_id": "R2_DZ40",
                "measured_ocr": 1.097,
                "uncertainty_se": 0.0,
                "ocr_uncertainty_model": NW08_OCR_UNCERTAINTY_MODEL_KNOWN_SIGMA,
                "ocr_uncertainty_provenance": "calibrated_respirometer_known_sigma_cert_v1",
            }),
            encoding="utf-8",
        )
        f_det0_r2 = td_16b1 / "r16_b1_r2_deterministic_se0.json"
        f_det0_r2.write_text(
            json.dumps({
                "route_id": "R2_DZ40",
                "measured_ocr": 1.097,
                "uncertainty_se": 0.0,
                "ocr_uncertainty_model": NW08_OCR_UNCERTAINTY_MODEL_ZERO_POINT,
            }),
            encoding="utf-8",
        )
        r_sa_st0_r2, rc_sa_st0_r2 = evaluate_nw08_measured_ocr_file(f_st0_r2, openislet_root=openislet_root)
        r_sa_st0_r1, rc_sa_st0_r1 = evaluate_nw08_measured_ocr_file(f_st0_r1, openislet_root=openislet_root)
        r_sa_ks0_r2, rc_sa_ks0_r2 = evaluate_nw08_measured_ocr_file(f_ks0_r2, openislet_root=openislet_root)
        r_sa_det0_r2, rc_sa_det0_r2 = evaluate_nw08_measured_ocr_file(f_det0_r2, openislet_root=openislet_root)

        ev_sha_16 = _valid_digest("r16_b1_coupled_ocr_ev")
        lot_sha_16 = _valid_digest("r16_b1_coupled_lot_sha")
        bind_ctx_16 = {
            "lot_id": "LOT-R16-B1-001",
            "mcb_id": "MCB-R16-B1-001",
            "canonical_product_variant_id": "ISLET1_A4_ARM1B",
            "computed_payload_sha256": lot_sha_16,
            "payload_sha256_verified": True,
            "planned_nw08_route_id": "R1_390_stress",
            "planned_nw08_route_errors": [],
            "planned_nw08_measurement_evidence_sha256": ev_sha_16,
            "planned_nw08_measurement_not_before_utc": "2026-11-28T00:00:00Z",
            "require_trusted_nw08_ocr_record": False,
        }
        c_rec_st0 = build_bound_nw08_ocr_record(
            lot_id="LOT-R16-B1-001",
            mcb_id="MCB-R16-B1-001",
            product_variant_id="ISLET1_A4_ARM1B",
            route_id="R1_390_stress",
            lot_payload_sha256=lot_sha_16,
            measured_ocr=1.25,
            uncertainty_se=0.0,
            ocr_uncertainty_model=NW08_OCR_UNCERTAINTY_MODEL_STUDENT_T,
            ocr_replicates_n=6,
            measurement_record_id="OCR-R16-B1-COUPLED-ST0",
            measurement_evidence_sha256=ev_sha_16,
            measurement_timestamp_utc="2026-11-29T00:00:00Z",
        )
        c_rec_ks0 = build_bound_nw08_ocr_record(
            lot_id="LOT-R16-B1-001",
            mcb_id="MCB-R16-B1-001",
            product_variant_id="ISLET1_A4_ARM1B",
            route_id="R1_390_stress",
            lot_payload_sha256=lot_sha_16,
            measured_ocr=1.25,
            uncertainty_se=0.0,
            ocr_uncertainty_model=NW08_OCR_UNCERTAINTY_MODEL_KNOWN_SIGMA,
            ocr_uncertainty_provenance="calibrated_respirometer_known_sigma_cert_v1",
            measurement_record_id="OCR-R16-B1-COUPLED-KS0",
            measurement_evidence_sha256=ev_sha_16,
            measurement_timestamp_utc="2026-11-29T00:00:00Z",
        )
        r_cp_st0, rc_cp_st0 = evaluate_nw08_measured_ocr_record(
            c_rec_st0, openislet_root=openislet_root, coupled_lot_binding=bind_ctx_16
        )
        r_cp_ks0, rc_cp_ks0 = evaluate_nw08_measured_ocr_record(
            c_rec_ks0, openislet_root=openislet_root, coupled_lot_binding=bind_ctx_16
        )

    ok_29 = bool(
        api_zero_st_rejected is True
        and api_zero_ks_rejected is True
        and rc_sa_st0_r2 == 2
        and r_sa_st0_r2.get("adjudicated_verdict") == "HOLD"
        and r_sa_st0_r2.get("solver_executed") is False
        and r_sa_st0_r2.get("release_authorizing") is False
        and NW08_HOLD_TOKEN_INFERENTIAL_REQUIRES_POSITIVE_SE in (r_sa_st0_r2.get("holds") or [])
        and rc_sa_st0_r1 == 2
        and r_sa_st0_r1.get("adjudicated_verdict") == "HOLD"
        and r_sa_st0_r1.get("solver_executed") is False
        and r_sa_st0_r1.get("release_authorizing") is False
        and NW08_HOLD_TOKEN_INFERENTIAL_REQUIRES_POSITIVE_SE in (r_sa_st0_r1.get("holds") or [])
        and rc_sa_ks0_r2 == 2
        and r_sa_ks0_r2.get("adjudicated_verdict") == "HOLD"
        and r_sa_ks0_r2.get("solver_executed") is False
        and r_sa_ks0_r2.get("release_authorizing") is False
        and NW08_HOLD_TOKEN_INFERENTIAL_REQUIRES_POSITIVE_SE in (r_sa_ks0_r2.get("holds") or [])
        and rc_sa_det0_r2 == 0
        and r_sa_det0_r2.get("adjudicated_verdict") == "PASS"
        and r_sa_det0_r2.get("ocr_uncertainty_model") == NW08_OCR_UNCERTAINTY_MODEL_ZERO_POINT
        and r_sa_det0_r2.get("release_authorizing") is False
        and rc_cp_st0 == 2
        and r_cp_st0.get("adjudicated_verdict") == "HOLD"
        and r_cp_st0.get("solver_executed") is False
        and r_cp_st0.get("release_authorizing") is False
        and NW08_HOLD_TOKEN_INFERENTIAL_REQUIRES_POSITIVE_SE in (r_cp_st0.get("holds") or [])
        and rc_cp_ks0 == 2
        and r_cp_ks0.get("adjudicated_verdict") == "HOLD"
        and r_cp_ks0.get("solver_executed") is False
        and r_cp_ks0.get("release_authorizing") is False
        and NW08_HOLD_TOKEN_INFERENTIAL_REQUIRES_POSITIVE_SE in (r_cp_ks0.get("holds") or [])
        and r14_b2_t6_rc == 3
        and r14_b2_t6.get("adjudicated_verdict") == "FAIL"
    )
    tests.append({
        "test": "r16_b1_standalone_and_coupled_zero_se_inferential_models_held_before_solve_exit_2",
        "api_student_t_zero_se_rejected": api_zero_st_rejected,
        "api_known_sigma_zero_se_rejected": api_zero_ks_rejected,
        "standalone_r2_student_t_zero_se_rc": rc_sa_st0_r2,
        "standalone_r1_student_t_zero_se_rc": rc_sa_st0_r1,
        "standalone_r2_known_sigma_zero_se_rc": rc_sa_ks0_r2,
        "standalone_r2_deterministic_control_rc": rc_sa_det0_r2,
        "coupled_student_t_zero_se_rc": rc_cp_st0,
        "coupled_known_sigma_zero_se_rc": rc_cp_ks0,
        "positive_se_student_t_control_rc": r14_b2_t6_rc,
        "passed": ok_29,
    })

    # 30. R16-M3: Live 3D FVM mesh receipt distinguishes policy skip vs fallback vs asymptotic GCI:
    #     - Single-grid far-from-floor solve (R2_DZ40 @ 1.3164) and monotone fast-path (R2_DZ40 @ 1.097)
    #       BOTH emit `order_qualified = False`, `interval_valid = False`,
    #       `mesh_uncertainty_status = "SINGLE_GRID_FAR_FROM_FLOOR_POLICY_PASS_ORDER_NOT_EVALUATED"`.
    #     - Single-grid far-from-floor FAIL (R2_DZ40 @ 10.0, base=5.0) emits `order_qualified = False`,
    #       `interval_valid = False`, `SINGLE_GRID_FAR_FROM_FLOOR_POLICY_FAIL_ORDER_NOT_EVALUATED`.
    #     - Live 3-grid monotone non-asymptotic fallback (R3P_35_VPIO120 @ 1.3164) emits
    #       `order_qualified = False`, `interval_valid = True`,
    #       `THREE_GRID_MONOTONE_NON_ASYMPTOTIC_FALLBACK_ORDER_NOT_QUALIFIED`.
    #     - 3-grid asymptotic GCI qualified control (`p = 1.5`) emits `order_qualified = True`,
    #       `interval_valid = True`, `THREE_GRID_ASYMPTOTIC_GCI_QUALIFIED`.
    mc_sg_pass = (r_sa_3dp.get("mesh_convergence_verification") or {})
    mc_sg_mono = (d_r08_mono_def.get("mesh_convergence_verification") or {})
    mc_sg_fail = (d_r08_ov5_def.get("mesh_convergence_verification") or {})
    mc_vpio_live = (d_vpio.get("mesh_convergence_verification") or {})
    ok_30 = bool(
        mc_sg_pass.get("grids_run") == 1
        and mc_sg_pass.get("order_qualified") is False
        and mc_sg_pass.get("interval_valid") is False
        and mc_sg_pass.get("mesh_uncertainty_status") == NW08_MESH_STATUS_SINGLE_GRID_POLICY_PASS
        and mc_sg_mono.get("grids_run") == 1
        and mc_sg_mono.get("order_qualified") is False
        and mc_sg_mono.get("interval_valid") is False
        and mc_sg_mono.get("mesh_uncertainty_status") == NW08_MESH_STATUS_SINGLE_GRID_POLICY_PASS
        and mc_sg_fail.get("grids_run") == 1
        and mc_sg_fail.get("order_qualified") is False
        and mc_sg_fail.get("interval_valid") is False
        and mc_sg_fail.get("mesh_uncertainty_status") == NW08_MESH_STATUS_SINGLE_GRID_POLICY_FAIL
        and mc_vpio_live.get("grids_run") == 3
        and mc_vpio_live.get("order_qualified") is False
        and mc_vpio_live.get("interval_valid") is True
        and mc_vpio_live.get("mesh_uncertainty_status") == NW08_MESH_STATUS_THREE_GRID_MONOTONE_FALLBACK
        and mc_acc_direct.get("grids_run") == 3
        and mc_acc_direct.get("order_qualified") is True
        and mc_acc_direct.get("interval_valid") is True
        and mc_acc_direct.get("mesh_uncertainty_status") == NW08_MESH_STATUS_THREE_GRID_ASYMPTOTIC_GCI_QUALIFIED
    )
    tests.append({
        "test": "r16_m3_live_mesh_receipt_distinguishes_single_grid_policy_skip_fallback_and_asymptotic_gci",
        "single_grid_pass_status": mc_sg_pass.get("mesh_uncertainty_status"),
        "single_grid_pass_order_qualified": mc_sg_pass.get("order_qualified"),
        "single_grid_pass_interval_valid": mc_sg_pass.get("interval_valid"),
        "monotone_fast_path_status": mc_sg_mono.get("mesh_uncertainty_status"),
        "single_grid_fail_status": mc_sg_fail.get("mesh_uncertainty_status"),
        "r3p_vpio120_3grid_status": mc_vpio_live.get("mesh_uncertainty_status"),
        "r3p_vpio120_3grid_order_qualified": mc_vpio_live.get("order_qualified"),
        "asymptotic_gci_status": mc_acc_direct.get("mesh_uncertainty_status"),
        "passed": ok_30,
    })

    # 31. R17-B2 + R17-M1: Live native 3D FVM solver operand verification for Sol's exact sub-ULP
    #     positive-SE example (ocr=1.097, SE=1e-20, Student-t df=5) AND KNOWN_SIGMA_NORMAL (z95 upper
    #     enclosure) vs canonical SE=0 ZERO_UNCERTAINTY_DETERMINISTIC_POINT control, PLUS direct
    #     `qualification_scope` & `physical_qualification_complete=False` on BOTH fast-path and live 3D
    #     return dicts of `dispatch_and_solve_nw08_measured_ocr` (verified via isolated child subprocess
    #     operand audit without mutating parent-process Layer-4 callbacks!).
    d_r17_fast_det0 = dispatch_and_solve_nw08_measured_ocr(
        "R2_DZ40",
        1.097,
        0.0,
        openislet_root=openislet_root,
        ocr_uncertainty_model=NW08_OCR_UNCERTAINTY_MODEL_ZERO_POINT,
    )
    with _FVM_SOLVER_LOCK:
        for _ck in list(_MESH_REFINEMENT_SOLVE_CACHE.keys()):
            if len(_ck) >= 2 and _ck[1] in ("R2_DZ40", "R1_390_stress"):
                _MESH_REFINEMENT_SOLVE_CACHE.pop(_ck, None)

    d_r17_live_det0 = dispatch_and_solve_nw08_measured_ocr(
        "R2_DZ40",
        1.097,
        0.0,
        openislet_root=openislet_root,
        always_solve_3d=True,
        ocr_uncertainty_model=NW08_OCR_UNCERTAINTY_MODEL_ZERO_POINT,
    )
    d_r17_sub_ulp_t5 = dispatch_and_solve_nw08_measured_ocr(
        "R2_DZ40",
        1.097,
        1e-20,
        openislet_root=openislet_root,
        ocr_uncertainty_model=NW08_OCR_UNCERTAINTY_MODEL_STUDENT_T,
        ocr_degrees_of_freedom=5,
    )
    d_r17_sub_ulp_ks = dispatch_and_solve_nw08_measured_ocr(
        "R2_DZ40",
        1.097,
        1e-20,
        openislet_root=openislet_root,
        z_one_sided_95=MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95,
        ocr_uncertainty_model=NW08_OCR_UNCERTAINTY_MODEL_KNOWN_SIGMA,
        ocr_uncertainty_provenance="NIST_CALIBRATED_KNOWN_SIGMA_SEAHORSE_ASSAY",
    )
    d_r17_live_r1_det0 = dispatch_and_solve_nw08_measured_ocr(
        "R1_390_stress",
        1.2067,
        0.0,
        openislet_root=openislet_root,
        always_solve_3d=True,
        ocr_uncertainty_model=NW08_OCR_UNCERTAINTY_MODEL_ZERO_POINT,
    )
    d_r17_sub_ulp_r1_t5 = dispatch_and_solve_nw08_measured_ocr(
        "R1_390_stress",
        1.2067,
        1e-20,
        openislet_root=openislet_root,
        ocr_uncertainty_model=NW08_OCR_UNCERTAINTY_MODEL_STUDENT_T,
        ocr_degrees_of_freedom=5,
    )

    def _verify_isolated_vasc_strictly_up(base_disp: Dict[str, Any], scaled_disp: Dict[str, Any], base_dec: Decimal) -> bool:
        b_aud = base_disp.get("native_solver_vascular_operand_audit")
        s_aud = scaled_disp.get("native_solver_vascular_operand_audit")
        if not isinstance(b_aud, dict) or not isinstance(s_aud, dict):
            return False
        if not (
            s_aud.get("scaled") is True
            and s_aud.get("islet_vmax_unchanged") is True
            and s_aud.get("all_vascular_vmax_strictly_greater_than_base") is True
            and s_aud.get("all_vascular_voxels_satisfy_min_exact_scale_ratio") is True
        ):
            return False
        b_pairs = b_aud.get("base_to_scaled_vascular_vmax_pairs_hex") or []
        s_pairs = s_aud.get("base_to_scaled_vascular_vmax_pairs_hex") or []
        if not b_pairs or not s_pairs or len(b_pairs) != len(s_pairs):
            return False
        b_bases = [float.fromhex(str(pair[0])) for pair in b_pairs]
        s_bases = [float.fromhex(str(pair[0])) for pair in s_pairs]
        if b_bases != s_bases:
            return False
        u95_d = Decimal(str(scaled_disp["solved_at_vascular_ocr_u95_exact_dec"]))
        req_ratio = Fraction(u95_d) / Fraction(base_dec)
        for pair in s_pairs:
            b_u = float.fromhex(str(pair[0]))
            s_u = float.fromhex(str(pair[1]))
            if not (s_u > b_u and Fraction(s_u) >= Fraction(b_u) * req_ratio):
                return False
        scale_f = float(scaled_disp["native_solver_vasc_scale_float64"])
        eff_ocr_f = float(scaled_disp["native_solver_effective_vascular_ocr_float64"])
        return bool(
            scale_f > 1.0
            and Fraction(scale_f) >= req_ratio
            and Fraction(eff_ocr_f) >= Fraction(u95_d)
        )

    r17_t5_r2_solver_ok = _verify_isolated_vasc_strictly_up(d_r17_live_det0, d_r17_sub_ulp_t5, Decimal("1.097"))
    r17_ks_r2_solver_ok = _verify_isolated_vasc_strictly_up(d_r17_live_det0, d_r17_sub_ulp_ks, Decimal("1.097"))
    r17_t5_r1_solver_ok = _verify_isolated_vasc_strictly_up(d_r17_live_r1_det0, d_r17_sub_ulp_r1_t5, Decimal("1.2067"))

    r17_m1_scope_ok = all(
        (
            d_obj.get("qualification_scope") == QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL
            and d_obj.get("physical_qualification_complete") is False
            and d_obj.get("solver_isolation_mode") == "ISOLATED_CHILD_SUBPROCESS"
            and d_obj.get("all_solver_module_origins_within_repo_root") is True
        )
        for d_obj in (
            d_r17_fast_det0,
            d_r17_live_det0,
            d_r17_sub_ulp_t5,
            d_r17_sub_ulp_ks,
            d_r17_live_r1_det0,
            d_r17_sub_ulp_r1_t5,
        )
    )
    ok_31 = bool(
        d_r17_fast_det0["solver_executed"] is False
        and d_r17_fast_det0["native_solver_vasc_scale_float64"] == 1.0
        and d_r17_live_det0["solver_executed"] is True
        and d_r17_live_det0["native_solver_vasc_scale_float64"] == 1.0
        and d_r17_sub_ulp_t5["solver_executed"] is True
        and d_r17_sub_ulp_ks["solver_executed"] is True
        and d_r17_sub_ulp_r1_t5["solver_executed"] is True
        and r17_t5_r2_solver_ok
        and r17_ks_r2_solver_ok
        and r17_t5_r1_solver_ok
        and r17_m1_scope_ok
    )
    tests.append({
        "test": "r17_b2_m1_sub_ulp_positive_se_upward_native_solver_scale_and_direct_qualification_scope",
        "det0_fast_path_scale": d_r17_fast_det0["native_solver_vasc_scale_float64"],
        "det0_live_3d_scale": d_r17_live_det0["native_solver_vasc_scale_float64"],
        "sub_ulp_t5_r2_scale_float64": d_r17_sub_ulp_t5["native_solver_vasc_scale_float64"],
        "sub_ulp_t5_r2_effective_ocr_float64": d_r17_sub_ulp_t5["native_solver_effective_vascular_ocr_float64"],
        "sub_ulp_t5_r2_solver_operand_strictly_up": r17_t5_r2_solver_ok,
        "sub_ulp_ks_r2_solver_operand_strictly_up": r17_ks_r2_solver_ok,
        "sub_ulp_t5_r1_1p2067_solver_operand_strictly_up": r17_t5_r1_solver_ok,
        "direct_dispatch_qualification_scope_present_all_paths": r17_m1_scope_ok,
        "passed": ok_31,
    })

    # 32. R18-B1: Concurrent raw native Layer-4 isolation (WITHOUT acquiring `_FVM_SOLVER_LOCK`):
    #     unchanged native R2 call (~24.0468 mmHg) agrees bit-for-bit before, during, and after
    #     a simultaneous modified NW-08 call (R2_DZ40, bed=40, base=5.0, meas=10.0 -> ~13.1032 mmHg)!
    tests.append(_run_r18_b1_concurrent_raw_native_isolation_test(openislet_root))

    # 33. R18-B2: Sequential cross-root isolation (`copy_A` then `copy_B` across R2, R3P, and R1):
    #     `resolved_solver_module_origins` points strictly inside `copy_A` on call 1 and strictly
    #     inside `copy_B` on call 2, rejecting symlink escape outside `repo_root` with zero host path leaks!
    tests.append(_run_r18_b2_cross_root_sequential_isolation_test(openislet_root))

    passed_n = sum(1 for t in tests if t["passed"])
    return {
        "executed": True,
        "total_tests": len(tests),
        "passed_tests": passed_n,
        "all_passed": passed_n == len(tests),
        "tests": tests,
    }


def _run_true_3d_fvm_vascular_voxel_replays(
    openislet_root: Path,
    r1_rows: List[Dict[str, Any]],
) -> Dict[str, Any]:
    """
    Replay ALL 8 live Route 1 / Route 2 / Route 3P 3D FVM baselines AND exact vascular-voxel-only
    stress solves (m_vasc = 1.3164 = 1.097 * 1.20, plus matched +20% above 1.2067 = 1.44804 on
    R1_390_stress so linear vs 3D are compared on IDENTICAL perturbations!) using OpenIslet's
    read-only 3D FVM operators inside isolated child Python subprocesses bound strictly to
    `openislet_root`. Captures native UNROUNDED float64 face minima directly from
    _compute_exact_fv_interface_stats_iip_0019 BEFORE route 4-dp display serialization!
    """
    nominal = 1.097
    m_vasc_target = nominal * 1.20  # 1.3164
    catalog = _build_nw08_route_catalog(openislet_root)
    replays: Dict[str, Any] = {}
    diffusivity_verified: float | None = None

    for label in (
        "R1_390_nominal",
        "R1_350_stress",
        "R1_390_stress",
        "R2_DZ40",
        "R3P_35",
        "R3P_30",
        "R3P_30_KRBH",
        "R3P_35_VPIO120",
    ):
        spec = catalog[label]
        current_vasc_ocr = float(spec["baseline_shared_ocr"])
        p_bed = float(spec["p_bed_mmhg"])
        operator_name = str(spec["operator_name"])
        base_res, base_raw_mmhg = _execute_single_3d_fvm_vascular_scaled_solve(
            openislet_root, spec, vasc_scale=None
        )
        base_iso_meta = (
            copy.deepcopy(base_res.get("_nw08_isolated_solver_meta") or {})
            if isinstance(base_res, dict)
            else {}
        )
        if diffusivity_verified is None and isinstance(base_iso_meta.get("d_o2_islet_tissue_cm2_s"), float):
            diffusivity_verified = float(base_iso_meta["d_o2_islet_tissue_cm2_s"])
        cache_key = (str(openislet_root.resolve()), str(label), float(p_bed), float(current_vasc_ocr))
        with _FVM_SOLVER_LOCK:
            _NATIVE_BASELINE_MMHG_CACHE[cache_key] = base_raw_mmhg
            if base_iso_meta:
                _NATIVE_BASELINE_META_CACHE[cache_key] = base_iso_meta
        _stress_res, stress_raw_mmhg = _execute_single_3d_fvm_vascular_scaled_solve(
            openislet_root, spec, vasc_scale=(m_vasc_target / current_vasc_ocr)
        )
        delta_vasc_pct = ((m_vasc_target / current_vasc_ocr) - 1.0) * 100.0
        drop_mmhg = base_raw_mmhg - stress_raw_mmhg
        slope_mmhg_per_pct = drop_mmhg / delta_vasc_pct if delta_vasc_pct > 0 else 0.0
        extrap_breach_pct = ((base_raw_mmhg - 15.0) / slope_mmhg_per_pct) if (base_raw_mmhg > 15.0 and slope_mmhg_per_pct > 0) else 0.0
        entry: Dict[str, Any] = {
            "route_operator": operator_name,
            "p_bed_mmhg": p_bed,
            "baseline_shared_ocr": round(current_vasc_ocr, 4),
            "target_vascular_voxel_ocr": round(m_vasc_target, 4),
            "vascular_ocr_increment_pct_above_baseline_operator": round(delta_vasc_pct, 2),
            "baseline_3d_fvm_face_min_unrounded_mmhg": base_raw_mmhg,
            "vasc_1p3164_3d_fvm_face_min_unrounded_mmhg": stress_raw_mmhg,
            "baseline_3d_fvm_face_min_mmhg": round(base_raw_mmhg, 4),
            "vasc_1p3164_3d_fvm_face_min_mmhg": round(stress_raw_mmhg, 4),
            "delta_3d_fvm_mmhg": round(stress_raw_mmhg - base_raw_mmhg, 4),
            "local_3d_slope_mmhg_per_pct": round(slope_mmhg_per_pct, 6),
            "passes_15mmhg_at_baseline_unrounded": _passes_unrounded_15mmhg_floor(base_raw_mmhg, 15.0),
            "passes_15mmhg_at_vasc_1p3164_3d_fvm_unrounded": _passes_unrounded_15mmhg_floor(stress_raw_mmhg, 15.0),
            "two_point_linear_extrapolated_breach_pct_not_exact_3d_threshold": (
                round(extrap_breach_pct, 2) if _passes_unrounded_15mmhg_floor(base_raw_mmhg, 15.0) else 0.0
            ),
        }
        if label == "R1_390_stress":
            _s20_res, stress_plus20_raw_mmhg = _execute_single_3d_fvm_vascular_scaled_solve(
                openislet_root, spec, vasc_scale=1.20
            )
            entry["matched_plus20pct_above_1p2067_vasc_ocr"] = round(current_vasc_ocr * 1.20, 5)
            entry["matched_plus20pct_3d_fvm_face_min_unrounded_mmhg"] = stress_plus20_raw_mmhg
            entry["matched_plus20pct_3d_fvm_face_min_mmhg"] = round(stress_plus20_raw_mmhg, 4)
            entry["passes_15mmhg_at_matched_plus20pct_3d_fvm_unrounded"] = _passes_unrounded_15mmhg_floor(stress_plus20_raw_mmhg, 15.0)
        replays[label] = entry

    if diffusivity_verified is None:
        raise RuntimeError("Isolated 3D FVM replay failed to verify D_O2_ISLET_TISSUE_CM2_S")

    return {
        "executed": True,
        "unrounded_native_floor_comparison_enforced": True,
        "diffusivity_cm2_s_verified": diffusivity_verified,
        "two_point_extrapolation_caveat": (
            "Reported `two_point_linear_extrapolated_breach_pct_not_exact_3d_threshold` values are "
            "two-point local-slope linear extrapolations from baseline and m_vasc=1.3164 solves, NOT exact "
            "nonlinear 3D FVM thresholds (direct nonlinear 3D solves at R2 +659.39% and R3P35 +327.38% "
            "remain above 15.0 mmHg at 15.11128 and 15.03710 mmHg respectively)."
        ),
        "note_r1_shared_ocr_operator": (
            "In live verify_iip0033_bilayer_and_resp1.py, both R1_350_stress ('PurePlus10OCR') and "
            "R1_390_stress ('CoupledPlus10OCR') invoke the same shared 1.2067x OCR multiplier for both "
            "islet and gel voxels; scaling only vascular voxels from 1.2067 to 1.3164 is +9.09% above "
            "1.2067x (+20.0% above 1.097x), whereas +20.0% above 1.2067x is m_vasc = 1.44804. On the "
            "native 80x80x78 grid for R1_390_stress at +9.09% (1.3164), face pO2 is 15.0741 mmHg, "
            "but predeclared 3-grid refinement (80x80x78 -> 96x96x94 -> 112x112x109: 15.0741 -> "
            "14.9753 -> 15.0638 mmHg; conservative ASME V&V-20 interval [14.9629, 15.0864] mmHg) "
            "straddles 15.0 mmHg and therefore routes to unresolved HOLD "
            "(HOLD_NW08_MESH_CONVERGENCE_STRADDLES_15MMHG_FLOOR) rather than decisive PASS. At +20.0% "
            "(1.44804), all three grids (14.8489, 14.7492, 14.8373 mmHg; interval [14.7367, 14.8614]) "
            "remain strictly < 15.0 mmHg (decisive FAIL). R3P_35_VPIO120 at +20.0% (1.3164) clears "
            "15.0 mmHg across all three predeclared grids (15.1005, 15.1059, 15.3084 mmHg; lower bound "
            "15.0485 >= 15.0 mmHg -> decisive PASS)."
        ),
        "replays": replays,
    }


def run_nw08_calibration_and_layer4_margin_audit(
    openislet_root: Path,
    *,
    run_3d_fvm: bool = True,
) -> Dict[str, Any]:
    """
    NW-08 multi-lineage calibration & true 3D FVM vascular-voxel oxygen audit:
      - Reads exact live IIP-0033, Layer-4 Design Z, and IIP-0034 baselines
      - Executes true 3D FVM vascular-voxel (m_vasc = 1.3164) solves across all 8 geometries
        comparing strictly on native UNROUNDED float64 face minima >= 15.0 mmHg, plus matched
        +20% (1.44804) on R1 390 Coupled so linear vs 3D are compared on identical perturbations
      - Provides executable evaluate_nw08_measured_ocr_trigger(...) & unit tests
      - Labels all breach percentages honestly as two-point linear extrapolations (not exact 3D thresholds)
      - Explicitly source-types every calibration row and distinguishes Layer-4 1.000x basal (2.312 fmol/min/cell)
        from 1.097x stimulated (2.536 / ~2.54 fmol/min/cell).
    """
    vmax_islet_mol_cm3_s = 3.4e-8
    vol_1_ieq_cm3 = (4.0 / 3.0) * math.pi * ((75.0e-4) ** 3)
    alpha_bunsen_nominal = 1.34e-9
    d_o2_islet = 1.3e-5             # Exact live Layer-4 D_O2_ISLET_TISSUE_CM2_S (run_layer4:306)
    d_o2_gel_chronic = 1.50e-5
    diploid_dna_pg_per_cell = 6.67
    cells_per_ieq_standard_diploid = 10.4 / (diploid_dna_pg_per_cell * 1e-3)

    l4_pure_ieq_pmol_min = vmax_islet_mol_cm3_s * vol_1_ieq_cm3 * 60.0 * 1e12  # 3.604978
    l4_whole_1p00_pmol_min = l4_pure_ieq_pmol_min * 1.15                       # 4.145724
    l4_whole_1p097_pmol_min = l4_whole_1p00_pmol_min * 1.097                   # 4.547860
    l4_pure_1p00_fmol_min_cell = (l4_pure_ieq_pmol_min * 1000.0) / cells_per_ieq_standard_diploid        # 2.3120
    l4_pure_1p097_fmol_min_cell = (l4_pure_ieq_pmol_min * 1.097 * 1000.0) / cells_per_ieq_standard_diploid  # 2.5363

    papas_human_id_pmol_min_ieq = 110.0 * 10.4e-3  # 1.144 pmol/(min*IEQ)
    papas_human_ii_pmol_min_ieq = 115.0 * 10.4e-3  # 1.196 pmol/(min*IEQ)

    d33 = strict_json_load_file(openislet_root / "data/extracted/iip0033_bilayer_and_respirometry_verification_v0.8.0.json", preserve_boundary_decimals=False)
    d34 = strict_json_load_file(openislet_root / "data/extracted/iip0034_planar_and_portfolio_verification_v0.8.0.json", preserve_boundary_decimals=False)
    l4 = strict_json_load_file(openislet_root / "data/extracted/layer4_tissue_and_metabolic_twin_atlas.json", preserve_boundary_decimals=False)

    r1_rows = d33["fixed_pitch_bilayer_and_holds"]["pass_runs_multimesh"]

    def _find_iip33(lbl: str) -> float:
        for r in r1_rows:
            if r["label"] == lbl:
                return float(r["worst_face_mmhg"])
        raise ValueError(f"Missing live IIP-0033 baseline {lbl}")

    def _find_iip34(lbl: str) -> float:
        for r in d34["planar_3d_fvm_oxygen_envelopes"]:
            if r["label"] == lbl:
                return float(r["worst_face_mmhg"])
        raise ValueError(f"Missing live IIP-0034 baseline {lbl}")

    r1_390_nom_live = _find_iip33("PASS_R1_390_Staggered_Nominal1p097_p95_68_2xAdj_nx80")
    r2_dz_40_live = float(
        l4["part_a_336h_spatial_reaction_diffusion_pouch_pde"]
        ["lineage_partitioned_metabolic_rest_and_m101_exclusion_audit"]
        ["design_z_140um_parameterized_acute_chronic_and_pfc_matrix"]
        ["cases"]["Chronic_40mmHg_1p097xOCR_ChronicGel"]["fv_harmonic_face_min_mmhg"]
    )
    r3p_h180_35_live = _find_iip34("Hybrid333_H180_Day0_Clean_65um_PASS")
    r3p_h180_30_nom_live = _find_iip34("Hybrid333_H180_Day0_Clean_65um_Bed30mmHg_PASS")
    r3p_h180_30_krbh_live = float(
        d34["planar_30mmhg_buffer_solubility_sensitivity"]["hybrid333_h180_bed30_clean_phys_buffer"]["worst_face_mmhg"]
    )
    r3p_h180_35_vpio120_live = _find_iip34("Hybrid333_H180_Day0_Avascular_VPIO120_Clean_PASS")
    r1_350_p10_live = _find_iip33("PASS_R1_350_Staggered_PurePlus10OCR_15umStandoff_max68_t7p95_66p95_1x68_nx80")
    r1_390_cpl10_live = _find_iip33("PASS_R1_390_Staggered_CoupledPlus10OCR_16p5umStandoff_p95_68_2xAdj_nx80")

    fvm_3d = (
        _run_true_3d_fvm_vascular_voxel_replays(openislet_root, r1_rows)
        if run_3d_fvm
        else {"executed": False, "replays": {}}
    )
    live_dispatch_tests = (
        run_nw08_live_dispatch_solver_tests(openislet_root)
        if run_3d_fvm
        else {"executed": False, "total_tests": 0, "passed_tests": 0, "all_passed": True, "tests": []}
    )
    trigger_tests = run_nw08_trigger_and_floor_unit_tests()

    m_vasc_true_plus20 = 1.097 * 1.20  # 1.3164 (+2.6087% whole-slab weighted demand)

    regimes = [
        ("L4_Canonical_1p00x_Baseline", 1.000, 1.000, "Layer-4 canonical basal design point (3.605 pure [2.312 fmol/min/cell] + 0.541 vasc = 4.146 pmol/min/IEQ)"),
        ("L4_Canonical_1p097x_Stimulated", 1.097, 1.097, "Layer-4 canonical chronic stimulated design point (3.955 pure [2.536 fmol/min/cell] + 0.593 vasc = 4.548 pmol/min/IEQ)"),
        ("NW08_External_WholePrep_Basal_Papas_GlycolyticEC", papas_human_ii_pmol_min_ieq / l4_pure_ieq_pmol_min, 0.35, "External whole-prep calibration: Papas 2015 clinical autoislet basal (1.196 pmol/min/IEQ) + glycolytic EC model prior (0.35x L4 vasc)"),
        ("NW08_External_WholePrep_2p2xStim_GlycolyticEC", (papas_human_ii_pmol_min_ieq * 2.2) / l4_pure_ieq_pmol_min, 0.50, "2.2x stimulated external whole-prep scaling (2.631 pmol/min/IEQ) + glycolytic EC model prior (0.50x L4 vasc)"),
        ("NW08_StressSensitivity_SenescentHUVEC_1p3164", 1.097, m_vasc_true_plus20, "Stress sensitivity: stimulated endocrine 1.097x + ~20% higher basal OCR in replicatively senescent HUVEC (m_vasc = 1.3164; Stabenow 2022 Cells Fig. 3A)"),
        ("NW08_Extreme_ActivatedStroma_1p50x_x_StimEndo1p097", 1.097, 1.500, "Extreme stress sensitivity: stimulated endocrine 1.097x + 1.50x vascular stroma (+4.79% weighted slab)"),
    ]

    r1_drop = 35.0 - r1_390_nom_live
    r2_drop = 40.0 - r2_dz_40_live
    r3p_drop = 35.0 - r3p_h180_35_live

    regime_rows = []
    for name, m_endo, m_vasc, desc in regimes:
        m_slab_vs_1p00 = (m_endo + 0.15 * m_vasc) / 1.15
        rel_vs_1p097 = m_slab_vs_1p00 / 1.097
        whole_pmol_min_ieq = l4_whole_1p00_pmol_min * m_slab_vs_1p00
        dp_core_65 = (vmax_islet_mol_cm3_s * m_endo * (32.5e-4 ** 2)) / (6.0 * d_o2_islet * alpha_bunsen_nominal)
        dp_core_100 = (vmax_islet_mol_cm3_s * m_endo * (50.0e-4 ** 2)) / (6.0 * d_o2_islet * alpha_bunsen_nominal)
        r1_face = 35.0 - r1_drop * rel_vs_1p097
        r2_face_40 = 40.0 - r2_drop * rel_vs_1p097
        r3p_face_35 = 35.0 - r3p_drop * rel_vs_1p097
        regime_rows.append({
            "regime": name,
            "description": desc,
            "m_endocrine": round(m_endo, 4),
            "m_vascular": round(m_vasc, 4),
            "slab_ocr_mult_vs_1p00": round(m_slab_vs_1p00, 4),
            "slab_ocr_delta_pct_vs_1p097": round((rel_vs_1p097 - 1.0) * 100.0, 2),
            "whole_prep_ocr_pmol_min_ieq": round(whole_pmol_min_ieq, 4),
            "krogh_core_drop_65um_mmhg": round(dp_core_65, 3),
            "krogh_core_drop_100um_mmhg": round(dp_core_100, 3),
            "route1_390um_bilayer_35mmhg_linearized_screen_mmhg": round(r1_face, 2),
            "route2_140um_designz_40mmhg_linearized_screen_mmhg": round(r2_face_40, 2),
            "route3p_180um_planar_35mmhg_linearized_screen_mmhg": round(r3p_face_35, 2),
            "all_3_nominal_routes_above_15mmhg_gsis_floor": bool(
                _passes_unrounded_15mmhg_floor(r1_face)
                and _passes_unrounded_15mmhg_floor(r2_face_40)
                and _passes_unrounded_15mmhg_floor(r3p_face_35)
            ),
        })

    # Margin + measurement-uncertainty-to-15-mmHg trigger table comparing MATCHED linear screen vs TRUE 3D FVM!
    def _lin_breach_pct(p_bed: float, base_mmhg: float) -> float:
        if base_mmhg <= 15.0:
            return 0.0
        return round(100.0 * (base_mmhg - 15.0) / ((p_bed - base_mmhg) * (0.15 / 1.15)), 2)

    def _lin_at_vasc_target(p_bed: float, base_mmhg: float, base_ocr: float, target_vasc_ocr: float) -> float:
        rel_slab = ((base_ocr + 0.15 * target_vasc_ocr) / 1.15) / base_ocr
        return p_bed - (p_bed - base_mmhg) * rel_slab

    replays_map = fvm_3d.get("replays", {})

    corner_specs = [
        (
            "R1_350um_PurePlus10OCR_Bed35_nx80",
            "R1_350_stress",
            35.0,
            r1_350_p10_live,
            1.2067,
            "verify_iip0033_bilayer_and_resp1.solve_route1_supercell_fixed_pitch",
            "BOTH matched linear screen (14.8027 mmHg) and true 3D FVM (14.8446 mmHg) FAIL at matched m_vasc=1.3164 (+9.09% above 1.2067x). Pre-committed derating: retire compressed 350 um slab in favor of 390 um bilayer via executable evaluate_nw08_measured_ocr_trigger (fires at +1.51% linear / +1.84% two-point 3D slope).",
        ),
        (
            "R1_390um_CoupledPlus10OCR_Bed35_nx80",
            "R1_390_stress",
            35.0,
            r1_390_cpl10_live,
            1.2067,
            "verify_iip0033_bilayer_and_resp1.solve_route1_supercell_fixed_pitch",
            "MESH-SENSITIVE NEAR-FLOOR CORNER (R14-B1 HOLD): at +9.09% (m_vasc=1.3164), native 80x80x78 is 15.0741 mmHg (+0.0741), but predeclared 3-grid refinement (80x80x78: 15.0741 -> 96x96x94: 14.9753 -> 112x112x109: 15.0638 mmHg; conservative interval [14.9629, 15.0864]) straddles 15.0 mmHg and routes to unresolved HOLD (HOLD_NW08_MESH_CONVERGENCE_STRADDLES_15MMHG_FLOOR, exit 2). At +20.0% (m_vasc=1.44804), all three grids (14.8489, 14.7492, 14.8373; upper bound 14.8614 < 15.0) decisively FAIL.",
        ),
        (
            "R3P_H180_65um_Bed30_AlphaNom",
            "R3P_30",
            30.0,
            r3p_h180_30_nom_live,
            1.097,
            "verify_iip0034_planar_and_portfolio.solve_planar_route3p_fvm",
            "BOTH linear (14.8297 mmHg) and true 3D FVM (14.9062 mmHg) FAIL at m_vasc=1.3164 (+20% above 1.097x); pre-committed derating action: require qualified bed pO2 >= 35 mmHg or pre-vascularized bed / reduced loading density.",
        ),
        (
            "R3P_H180_65um_Bed30_KRBH_Alpha1p27e9",
            "R3P_30_KRBH",
            30.0,
            r3p_h180_30_krbh_live,
            1.097,
            "verify_iip0034_planar_and_portfolio.solve_planar_route3p_fvm",
            "ALREADY FAILS LIVE at 14.4198 mmHg (and 14.0951 mmHg at m_vasc=1.3164) under physiological KRBH alpha=1.27e-9; disqualified without P_bed >= 35 mmHg or pre-vascularization.",
        ),
        (
            "R3P_H180_VPIO120_Bed35_AlphaNom",
            "R3P_35_VPIO120",
            35.0,
            r3p_h180_35_vpio120_live,
            1.097,
            "verify_iip0034_planar_and_portfolio.solve_planar_route3p_fvm",
            "GENUINE LINEAR-VS-3D REVERSAL: at matched +20% (m_vasc=1.3164 above 1.097x), linearized screen FAILS (14.8656 mmHg) while true 3D FVM PASSES (15.1005 mmHg >= 15.0 unrounded); margin is +0.1005 mmHg so measured OCR+uncertainty reaching floor triggers strict <= 65 um cluster sieving or area expansion.",
        ),
    ]

    marginal_corners = []
    for cid, rkey, p_bed, base_val, base_ocr, op_name, action_txt in corner_specs:
        rep = replays_map.get(rkey, {})
        base_unrounded = float(rep.get("baseline_3d_fvm_face_min_unrounded_mmhg", base_val))
        lin_matched_1p3164 = _lin_at_vasc_target(p_bed, base_unrounded, base_ocr, m_vasc_true_plus20)
        lin_matched_plus20 = _lin_at_vasc_target(p_bed, base_unrounded, base_ocr, base_ocr * 1.20)
        true_3d_val = rep.get("vasc_1p3164_3d_fvm_face_min_mmhg")
        true_3d_unrounded = rep.get("vasc_1p3164_3d_fvm_face_min_unrounded_mmhg")
        lin_pass_1p3164 = _passes_unrounded_15mmhg_floor(lin_matched_1p3164)
        fvm_pass_1p3164 = rep.get("passes_15mmhg_at_vasc_1p3164_3d_fvm_unrounded")
        corner_entry: Dict[str, Any] = {
            "corner_id": cid,
            "replay_key": rkey,
            "route_specific_3d_fvm_operator": op_name,
            "p_bed_mmhg": p_bed,
            "baseline_operator_ocr_mult": base_ocr,
            "live_baseline_min_face_mmhg": round(base_unrounded, 4),
            "baseline_margin_above_15mmhg": round(base_unrounded - 15.0, 4),
            "matched_vasc_1p3164_increment_pct_above_baseline": round(((m_vasc_true_plus20 / base_ocr) - 1.0) * 100.0, 2),
            "matched_linearized_screen_at_vasc_1p3164_mmhg": round(lin_matched_1p3164, 4),
            "matched_linearized_passes_15mmhg_at_vasc_1p3164": lin_pass_1p3164,
            "true_3d_fvm_at_vasc_1p3164_unrounded_mmhg": true_3d_unrounded,
            "true_3d_fvm_at_vasc_1p3164_mmhg": true_3d_val,
            "true_3d_fvm_passes_15mmhg_at_vasc_1p3164_unrounded": fvm_pass_1p3164,
            "genuine_linear_vs_3d_reversal_at_matched_perturbation": (
                bool(lin_pass_1p3164 != fvm_pass_1p3164) if fvm_pass_1p3164 is not None else None
            ),
            "linearized_vascular_ocr_breach_pct": _lin_breach_pct(p_bed, base_unrounded),
            "two_point_linear_extrapolated_3d_breach_pct_not_exact_3d_threshold": rep.get(
                "two_point_linear_extrapolated_breach_pct_not_exact_3d_threshold"
            ),
            "executable_trigger_function": "evaluate_nw08_measured_ocr_trigger",
            "precommitted_derating_action": action_txt,
        }
        if rkey == "R1_390_stress":
            corner_entry["matched_plus20pct_above_1p2067_comparison"] = {
                "target_vasc_ocr_mult": round(base_ocr * 1.20, 5),
                "linearized_min_face_mmhg": round(lin_matched_plus20, 4),
                "linearized_passes_15mmhg": _passes_unrounded_15mmhg_floor(lin_matched_plus20),
                "true_3d_fvm_min_face_unrounded_mmhg": rep.get("matched_plus20pct_3d_fvm_face_min_unrounded_mmhg"),
                "true_3d_fvm_min_face_mmhg": rep.get("matched_plus20pct_3d_fvm_face_min_mmhg"),
                "true_3d_fvm_passes_15mmhg_unrounded": rep.get("passes_15mmhg_at_matched_plus20pct_3d_fvm_unrounded"),
                "linear_and_3d_agree": (
                    bool(_passes_unrounded_15mmhg_floor(lin_matched_plus20) == rep.get("passes_15mmhg_at_matched_plus20pct_3d_fvm_unrounded"))
                    if rep.get("passes_15mmhg_at_matched_plus20pct_3d_fvm_unrounded") is not None
                    else None
                ),
            }
        marginal_corners.append(corner_entry)

    # Explicitly source-typed 5-lineage calibration matrix (zero unbacked donor-level HPAP label;
    # Layer-4 1.000x basal = 2.312 fmol/min/cell vs 1.097x stimulated = 2.536 [~2.54] fmol/min/cell!)
    calibration_table_5lineages = [
        {
            "lineage": "beta",
            "graft_cell_count": GRAFT_COMPOSITION_CELLS["beta"],
            "graft_share_pct": round(100.0 * GRAFT_COMPOSITION_CELLS["beta"] / TOTAL_GRAFT_CELLS, 2),
            "ocr_evidence_source_type": "literature_whole_islet_group_mean_and_layer4_design_upper_envelope",
            "ocr_fmol_min_cell_reference_range": (
                "0.73 - 2.31 basal / 2.54 stimulated (external whole-preparation clinical autoislet basal group mean: "
                "Papas 2015 PMID:26258815 1.144-1.196 pmol/min/IEQ = 0.73-0.77 fmol/min/cell at 10.4 ng DNA/IE & "
                "standard ~6.67 pg diploid DNA/cell; Layer-4 1.000x basal endocrine design point = 2.312 fmol/min/cell; "
                "Layer-4 1.097x stimulated endocrine design point = 2.536 [~2.54] fmol/min/cell; neither is a directly "
                "measured single-cell beta OCR or donor-level HPAP OCR)"
            ),
            "surface_nk_complement_ccby4": "CD46+/CD55+/CD59+ mature (CDC-resistant, ADCC-susceptible: PMID:27787618 Diabetologia); PVR/CD155 & CD276/B7-H3 activating ligands in SC-islet/EP grafts (PMID:41403780 humanized mouse)",
            "antiviral_isg_apoptosis_ccby4": "Immunogold EM localizes CAR-SIV to dense-core insulin secretory granules in human islets (PMID:30074059; observational localization, zero KO/GSIS assays); TYK2-dependent IFN-a/HLA-I (PMID:36289205); IFIH1 rs1990760 IFN-b/l1/l2 (PMID:28000722); adenoviral rat BCL2L1 overexpression rescues rat INS-1E (~40%, slight Ca2+/GSIS reduction) and human EndoC-bH1 (>80%, no GSIS penalty) upstream of mitochondria (PMID:36982731)",
            "ccby4_primary_pmids": ["26258815", "35241836", "37188763", "38956087", "27787618", "41403780", "30074059", "36289205", "28000722", "36982731"],
        },
        {
            "lineage": "alpha",
            "graft_cell_count": GRAFT_COMPOSITION_CELLS["alpha"],
            "graft_share_pct": round(100.0 * GRAFT_COMPOSITION_CELLS["alpha"] / TOTAL_GRAFT_CELLS, 2),
            "ocr_evidence_source_type": "literature_whole_islet_proxy_and_transcriptomic_annotation",
            "ocr_fmol_min_cell_reference_range": "0.60 - 1.50 (assumed modeling range informed by whole-islet OCR & single-cell mitochondrial annotations in PMID:35241836, PMID:38956087; NOT directly measured lineage-specific product OCR)",
            "surface_nk_complement_ccby4": "Endocrine CD46+/CD55+/CD59+ complement regulators (PMID:27787618); SC-islet PVR/CD155 & CD276 context (PMID:41403780)",
            "antiviral_isg_apoptosis_ccby4": "Higher basal/induced STAT1 antiviral clearance in primary rat alpha vs beta cells with separate human islet transcriptomic arm (PMID:26061776); distinct human islet ER/cytokine stress regulons (PMID:38956087); downstream iCasp9/AP20187 escape governed by iCasp9 abundance & XIAP/Caspase-3 ratio in HeLa cells (PMID:35013114; zero islet assays) -> mandates direct empirical Gate 0V-Kill per-lineage verification",
            "ccby4_primary_pmids": ["35241836", "37188763", "38956087", "26061776", "36982731", "35013114", "27787618"],
        },
        {
            "lineage": "delta",
            "graft_cell_count": GRAFT_COMPOSITION_CELLS["delta"],
            "graft_share_pct": round(100.0 * GRAFT_COMPOSITION_CELLS["delta"] / TOTAL_GRAFT_CELLS, 2),
            "ocr_evidence_source_type": "whole_islet_proxy_no_direct_lineage_respirometry",
            "ocr_fmol_min_cell_reference_range": "0.50 - 1.40 (modeling proxy bundled within whole-islet Papas/Balboa OCR; zero direct purified human delta-cell respirometry)",
            "surface_nk_complement_ccby4": "Endocrine CD46+/CD55+/CD59+ (PMID:27787618); SC-islet multi-ome chromatin/transcriptome annotation (PMID:37188763)",
            "antiviral_isg_apoptosis_ccby4": "Distinct ER/cytokine stress regulons in human islets (PMID:38956087); completely unscreened in legacy beta-only Gate 0V",
            "ccby4_primary_pmids": ["35241836", "37188763", "38956087", "27787618"],
        },
        {
            "lineage": "plvap_iec",
            "graft_cell_count": GRAFT_COMPOSITION_CELLS["plvap_iec"],
            "graft_share_pct": round(100.0 * GRAFT_COMPOSITION_CELLS["plvap_iec"] / TOTAL_GRAFT_CELLS, 2),
            "ocr_evidence_source_type": "literature_cultured_huvec_stress_sensitivity_and_model_allowance",
            "ocr_fmol_min_cell_reference_range": "0.15 - 0.55 (model allowance for glycolytic endothelium; cultured replicatively senescent primary HUVECs show ~+20% higher basal OCR in Stabenow 2022 Cells Fig. 3A PMID:35883656 — external stress sensitivity, NOT graft-specific PLVAP+ iEC measurement)",
            "surface_nk_complement_ccby4": "Constitutive CD46/CD55/CD59 + THBD vascular thrombo-protection; PLVAP/ESM1/KDR primary human islet EC identity (factual PMID:39915484); requires >=180k CD47 p10",
            "antiviral_isg_apoptosis_ccby4": "Supports vascular-macrophage crosstalk during CVB4/viral infection in human VMI organoids (PMID:39232561); cultured primary human islet ECs express CAR/DAF and sustain non-lytic CVB4 (factual PMID:17494992)",
            "ccby4_primary_pmids": ["35883656", "37548091", "39232561"],
        },
        {
            "lineage": "pericyte",
            "graft_cell_count": GRAFT_COMPOSITION_CELLS["pericyte"],
            "graft_share_pct": round(100.0 * GRAFT_COMPOSITION_CELLS["pericyte"] / TOTAL_GRAFT_CELLS, 2),
            "ocr_evidence_source_type": "model_engineering_allowance_pending_product_respirometry",
            "ocr_fmol_min_cell_reference_range": "0.15 - 0.50 (engineering model allowance inside Layer-4 15% vascular OCR budget; 3.58% graft share; zero direct human islet pericyte OCR dataset)",
            "surface_nk_complement_ccby4": "NG2+/PDGFRB+ mural markers; vulnerable to myofibroblast conversion & microvascular dysfunction in T1D (factual PMID:37531253, PMID:29514070)",
            "antiviral_isg_apoptosis_ccby4": "Viral spike S1 induces mural ACE2 stripping & capillary constriction in human pancreas slices (factual PMID:39715591); zero prior Gate 0V viral or AP1903 surveillance",
            "ccby4_primary_pmids": ["39232561"],
        },
    ]

    return {
        "layer4_design_constants": {
            "pure_endocrine_vmax_pmol_min_ieq": round(l4_pure_ieq_pmol_min, 6),
            "whole_prep_1p00x_with_15pct_vasc_pmol_min_ieq": round(l4_whole_1p00_pmol_min, 6),
            "whole_prep_1p097x_chronic_pmol_min_ieq": round(l4_whole_1p097_pmol_min, 6),
            "pure_endocrine_1p00x_basal_fmol_min_cell": round(l4_pure_1p00_fmol_min_cell, 4),
            "pure_endocrine_1p097x_stimulated_fmol_min_cell": round(l4_pure_1p097_fmol_min_cell, 4),
            "d_o2_islet_tissue_cm2_s_live_run_layer4": d_o2_islet,
            "d_o2_gel_chronic_cm2_s": d_o2_gel_chronic,
            "papas2015_external_wholeprep_autoislet_id_pmol_min_ieq": round(papas_human_id_pmol_min_ieq, 6),
            "papas2015_external_wholeprep_autoislet_ii_pmol_min_ieq": round(papas_human_ii_pmol_min_ieq, 6),
            "cells_per_ieq_from_10p4ng_papas_and_6p67pg_standard_diploid_dna": round(cells_per_ieq_standard_diploid, 2),
            "l4_conservative_headroom_over_papas_basal_fold": round(l4_pure_ieq_pmol_min / papas_human_ii_pmol_min_ieq, 3),
        },
        "live_fvm_baselines_read_programmatically": {
            "route1_390um_staggered_nominal1p097_nx80_mmhg": round(r1_390_nom_live, 4),
            "route2_designz_140um_40mmhg_chronic1p097_mmhg": round(r2_dz_40_live, 4),
            "route3p_hybrid333_h180_35mmhg_65um_clean_mmhg": round(r3p_h180_35_live, 4),
            "route3p_hybrid333_h180_30mmhg_nominal_65um_mmhg": round(r3p_h180_30_nom_live, 4),
            "route3p_hybrid333_h180_30mmhg_krbh_65um_FAIL_mmhg": round(r3p_h180_30_krbh_live, 4),
            "route3p_hybrid333_h180_35mmhg_vpio120_mmhg": round(r3p_h180_35_vpio120_live, 4),
            "route1_350um_staggered_pureplus10_nx80_mmhg": round(r1_350_p10_live, 4),
            "route1_390um_staggered_coupledplus10_nx80_mmhg": round(r1_390_cpl10_live, 4),
        },
        "true_3d_fvm_vascular_voxel_1p3164_replays": fvm_3d,
        "nw08_trigger_and_floor_unit_tests": trigger_tests,
        "nw08_live_dispatch_solver_tests": live_dispatch_tests,
        "five_lineage_source_typed_calibration_matrix": calibration_table_5lineages,
        "layer4_oxygen_margin_linearized_screen_nominal_routes": regime_rows,
        "marginal_live_corners_margin_uncertainty_triggers": marginal_corners,
        "nw08_r14_numerical_and_statistical_policy": {
            "mesh_convergence_policy_version": NW08_MESH_CONVERGENCE_POLICY_VERSION,
            "near_floor_trigger_bands_by_route_family_mmhg": {
                k: [CANONICAL_NW08_PO2_FLOOR_MMHG + lo, CANONICAL_NW08_PO2_FLOOR_MMHG + hi]
                for k, (lo, hi) in NW08_MESH_CONVERGENCE_TRIGGER_BANDS_BY_FAMILY.items()
            },
            "safety_factor_fs": NW08_MESH_CONVERGENCE_SAFETY_FACTOR_FS,
            "admissible_asymptotic_order_range_p": [
                NW08_MESH_CONVERGENCE_MIN_ADMISSIBLE_ORDER_P,
                NW08_MESH_CONVERGENCE_MAX_ADMISSIBLE_ORDER_P,
            ],
            "formal_order_cap_p": NW08_MESH_CONVERGENCE_FORMAL_ORDER_P,
            "upward_order_clamping_prohibited": True,
            "predeclared_grid_ladders_by_route_family": {
                "R1_390": [[80, 80, 78], [96, 96, 94], [112, 112, 109]],
                "R1_350": [[80, 80, 70], [96, 96, 84], [112, 112, 98]],
                "R2": [[48, 48, 28], [72, 72, 42], [96, 96, 56]],
                "R3P": [[28, 28, 32], [42, 42, 48], [56, 56, 64]],
            },
            "straddling_verdict_token": NW08_HOLD_TOKEN_STRADDLES_FLOOR,
            "unqualified_slow_or_non_asymptotic_order_verdict_token": NW08_HOLD_TOKEN_UNQUALIFIED_ORDER,
            "inferential_model_requires_positive_se_token": NW08_HOLD_TOKEN_INFERENTIAL_REQUIRES_POSITIVE_SE,
            "mesh_uncertainty_status_taxonomy": {
                "single_grid_policy_pass": NW08_MESH_STATUS_SINGLE_GRID_POLICY_PASS,
                "single_grid_policy_fail": NW08_MESH_STATUS_SINGLE_GRID_POLICY_FAIL,
                "three_grid_monotone_fallback": NW08_MESH_STATUS_THREE_GRID_MONOTONE_FALLBACK,
                "three_grid_asymptotic_gci_qualified": NW08_MESH_STATUS_THREE_GRID_ASYMPTOTIC_GCI_QUALIFIED,
                "three_grid_oscillatory_bound": NW08_MESH_STATUS_THREE_GRID_OSCILLATORY_BOUND,
                "three_grid_unqualified_order_hold": NW08_MESH_STATUS_THREE_GRID_UNQUALIFIED_ORDER_HOLD,
            },
            "allowed_ocr_uncertainty_models": sorted(NW08_ALLOWED_OCR_UNCERTAINTY_MODELS),
            "student_t_one_sided_95_df1_outward_upper": exact_student_t_one_sided_95(1),
            "student_t_one_sided_95_df5_n6": round(exact_student_t_one_sided_95(5), 7),
            "student_t_outward_upper_enclosure_enforced": True,
            "normal_z_repeated_sampling_coverage_at_df5": round(
                exact_student_t_cdf(MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95, 5), 6
            ),
            "bare_positive_se_without_model_or_df_rejected_token": "HOLD_NW08_OCR_MISSING_UNCERTAINTY_MODEL_OR_DF",
            "process_wide_fvm_lock_and_callback_owner_serialized": True,
            "isolated_child_subprocess_solver_execution": True,
            "per_root_solver_module_origin_verified": True,
        },
        "calibration_and_trigger_policy": (
            "True route-specific 3D FVM vascular-voxel replay (m_vasc = 1.3164, gated on native UNROUNDED float64 "
            "face minima >= 15.0 mmHg and predeclared 3-grid numerical convergence inside route-family near-floor "
            "bands [R1: 14.88-15.25, R2: 14.75-15.25, R3P: 14.70-15.30 mmHg] under NASA/Roache GCI and ASME V&V-20 "
            "oscillatory half-range bounds with Fs = 1.25 and NO upward clamping of sub-asymptotic order p_obs < 0.5) "
            "confirms all 3 nominal routes pass comfortably (R1 390 um: 16.9277, R2 Design Z: 23.7724, R3P 35 mmHg: "
            "19.8121 mmHg). On near-floor stress corners, R1 390 Coupled+10% at +9.09% (1.3164: 80x80x78=15.0741, "
            "96x96x94=14.9753, 112x112x109=15.0638; interval [14.9629, 15.0864]), R2 Design Z at bed 32 mmHg / 2.09975 "
            "(48x48x28=14.9898, 72x72x42=15.0237, 96x96x56=15.1380; interval [14.9527, 15.3234]), and R1 350 baseline "
            "(15.0394, 14.8640, 14.9211; interval [14.8421, 15.0613]) straddle 15.0 mmHg across predeclared grids and "
            "route to unresolved HOLD (HOLD_NW08_MESH_CONVERGENCE_STRADDLES_15MMHG_FLOOR, exit 2) before any coupled "
            "authorization. Monotone sequences with sub-asymptotic slow observed order p_obs < 0.5 (e.g., synthetic "
            "R2 sequence 15.012547946, 15.011044645, 15.010000000 with p_obs=0.06 and true limit 14.95 < 15.0), "
            "non-positive order, extreme super-convergence (p_obs > 2.5), or non-asymptotic drift toward 15.0 mmHg "
            "NEVER clamp p upward to 0.5 and instead route fail-closed to HOLD "
            "(HOLD_NW08_MESH_CONVERGENCE_UNQUALIFIED_SLOW_OR_NON_ASYMPTOTIC_ORDER, interval_valid=False, exit 2). "
            "At +20% (1.44804), R1 390 Coupled+10% decisively FAILS across all three grids (14.8489, 14.7492, 14.8373; "
            "upper bound 14.8614 < 15.0). R3P VPIO120 at 1.3164 clears 15.0 mmHg monotonically away from the floor "
            "across all three grids (15.1005, 15.1059, 15.3084; conservative lower bound 15.0485 >= 15.0 -> PASS), "
            "while R1 350 um (14.8446), R3P Bed30 (14.9062), and R3P Bed30 KRBH (14.0951; already failing live at "
            "14.4198) decisively FAIL < 15.0 mmHg. Executable dispatch_and_solve_nw08_measured_ocr(...) requires "
            "explicit inferential model provenance whenever uncertainty_se > 0 (exact Student-t t_{0.95, df} for "
            "small-sample estimated SE, e.g. t_{0.95,5}=2.0150484 for n=6 replicates; scoped KNOWN_SIGMA_NORMAL with "
            "external calibration provenance; or INDEPENDENT_JUSTIFIED_UPPER_BOUND), rejects undeclared bare SE "
            "fail-closed, and serializes native Layer-4 callbacks process-wide across direct and composite-wrapper "
            "interfaces. Reported breach percentages are two-point linear extrapolations (not exact nonlinear 3D thresholds)."
        ),
    }


# ---------------------------------------------------------------------------
# Part C: Parameterized Protected Manifest, Playbook §4.1.20 Section Hash,
#         render_documentation.py Check & Case-Normalized CEG Diff
# ---------------------------------------------------------------------------
def verify_r4_playbook_decision_tree_and_renderer_compatibility(openislet_root: Path) -> Dict[str, Any]:
    """
    Read-only temp-dir & in-memory proof that Option-2 placement:
      - Adds dedicated block to stage0_decision_tree_v1.json (preserving DEC-114 block SHA-256)
      - Creates standalone docs/GATE-0V-WHOLEGRAFT-PROTOCOL.md
      - Leaves docs/STAGE-0-EXECUTION-PLAYBOOK.md §4.1.20 canonical section hash invariant
      - Passes render_documentation.render_text() cleanly on docs/GATE-0V-WHOLEGRAFT-PROTOCOL.md
        (recording authored vs post-render sizes & documenting that S5 MUST hash-pin the
        protocol doc AFTER running render_documentation.py at the end of the fold sequence!).
    """
    v35_path = openislet_root / "scripts" / "verify_iip0035_d1b_auto_and_portfolio.py"
    rd_path = openislet_root / "scripts" / "render_documentation.py"
    pb_path = openislet_root / "docs" / "STAGE-0-EXECUTION-PLAYBOOK.md"
    dt_path = openislet_root / "data" / "protocols" / "stage0_decision_tree_v1.json"
    if not (v35_path.is_file() and pb_path.is_file() and dt_path.is_file()):
        return {"tested": False, "passed": False, "reason": "Missing live IIP-0035 files"}

    spec = importlib.util.spec_from_file_location("v35_compat_probe", str(v35_path))
    if spec is None or spec.loader is None:
        return {"tested": False, "passed": False, "reason": "Could not load verify_iip0035 module"}
    v35 = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(v35)

    proto_authored = (
        "# Gate 0V Whole-Graft Viral Safety, Stress AP1903 Erasure & NW-08 Calibration Protocol (IIP-0043)\n\n"
        "Standalone companion protocol preserving Playbook §4.1.20 canonical section hash.\n"
        "Clinical release mandates composite PASS from both legacy wetlab_contract.py and "
        "verify_iip0043_wholegraft_gate0v_and_calibration.py on the same lot_id/mcb_id/payload_sha256.\n"
    )

    with tempfile.TemporaryDirectory() as td:
        tr = Path(td)
        (tr / "docs").mkdir(parents=True)
        (tr / "data" / "protocols").mkdir(parents=True)
        (tr / "docs" / "STAGE-0-EXECUTION-PLAYBOOK.md").write_bytes(pb_path.read_bytes())
        (tr / "docs" / "GATE-0V-WHOLEGRAFT-PROTOCOL.md").write_text(proto_authored, encoding="utf-8")
        dt_doc = strict_json_load_file(dt_path, preserve_boundary_decimals=False)
        dt_doc["wholegraft_gate0v_composite_and_nw08_calibration_iip_0043"] = {
            "decision_id": "DEC-122",
            "companion_protocol_doc": "docs/GATE-0V-WHOLEGRAFT-PROTOCOL.md",
            "required_evaluators": [
                "scripts/wetlab_contract.py",
                "scripts/verify_iip0043_wholegraft_gate0v_and_calibration.py",
                "scripts/evaluate_gate0v_composite_release.py",
            ],
            "graveyard_guardrail_id": GRAVEYARD_GUARDRAIL_ID,
            "graveyard_card_id": GRAVEYARD_CARD_ID,
            "playbook_sec4120_untouched": True,
        }
        (tr / "data" / "protocols" / "stage0_decision_tree_v1.json").write_text(
            json.dumps(dt_doc, indent=2), encoding="utf-8"
        )
        pb_res = v35._verify_playbook_sec4120(tr, require_canonical_sha=True)
        dt_reloaded = strict_json_load_file(tr / "data" / "protocols" / "stage0_decision_tree_v1.json", preserve_boundary_decimals=False)
        dec114_blk = dt_reloaded["autologous_d1b_auto_c_v2_vanguard_gates_iip_0035"]
        dec114_sha = hashlib.sha256(
            json.dumps(dec114_blk, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
        ).hexdigest()
        dt_ok = dec114_sha == v35.EXPECTED_DEC114_DECISION_TREE_SHA256
        pb_ok = bool(pb_res.get("canonical_sha_verified"))
        pb_sec_sha = pb_res.get("controlling_playbook_sec4120_sha256")

    # Test render_documentation.py in-memory on docs/GATE-0V-WHOLEGRAFT-PROTOCOL.md
    renderer_check: Dict[str, Any] = {"tested": False, "passed": False}
    if rd_path.is_file():
        rd_spec = importlib.util.spec_from_file_location("rd_compat_probe", str(rd_path))
        if rd_spec is not None and rd_spec.loader is not None:
            rd_mod = importlib.util.module_from_spec(rd_spec)
            rd_spec.loader.exec_module(rd_mod)
            manifest_path = openislet_root / "manifest.json"
            pin_count = 0
            if manifest_path.is_file():
                m_obj = strict_json_load_file(manifest_path, preserve_boundary_decimals=False)
                if isinstance(m_obj, dict):
                    if isinstance(m_obj.get("artifacts"), (list, dict)):
                        pin_count = len(m_obj["artifacts"])
                    elif isinstance(m_obj.get("files"), (list, dict)):
                        pin_count = len(m_obj["files"])
                    else:
                        pin_count = len(m_obj)
            # In public-bundle mode (where islet1_candidate_stack_rankings.json is excluded from public export),
            # load the pinned identical data/extracted/documentation_facts_v0.8.0.json so post_render_bytes
            # matches full-repo derive_facts(repo, 1643) byte-for-byte (B8)!
            facts_json_path = openislet_root / "data" / "extracted" / "documentation_facts_v0.8.0.json"
            rankings_path = openislet_root / "data" / "extracted" / "islet1_candidate_stack_rankings.json"
            if facts_json_path.is_file() and (_is_public_bundle(openislet_root) or not rankings_path.is_file()):
                facts = strict_json_load_file(facts_json_path, preserve_boundary_decimals=False)
                facts_source = "pinned_documentation_facts_v0.8.0.json"
            else:
                facts = rd_mod.derive_facts(openislet_root, pin_count)
                facts_source = "derived_from_repo_artifacts"
            rendered_doc = rd_mod.render_text(proto_authored, facts, "GATE-0V-WHOLEGRAFT-PROTOCOL.md")
            rendered_again = rd_mod.render_text(rendered_doc, facts, "GATE-0V-WHOLEGRAFT-PROTOCOL.md")
            idempotent = rendered_doc == rendered_again
            has_facts_block = "<!-- OPENISLET_GENERATED_FACTS_START -->" in rendered_doc
            has_scope_footer = "<!-- OPENISLET_CURRENT_LAYER_SCOPE -->" in rendered_doc
            renderer_check = {
                "tested": True,
                "facts_source": facts_source,
                "manifest_pin_count": pin_count,
                "authored_bytes": len(proto_authored.encode("utf-8")),
                "post_render_bytes": len(rendered_doc.encode("utf-8")),
                "generated_facts_block_inserted": has_facts_block,
                "layer_scope_footer_inserted": has_scope_footer,
                "render_idempotent_on_second_pass": idempotent,
                "post_render_pinning_rule": (
                    "render_documentation.py transforms every docs/*.md by injecting generated corpus facts and "
                    "layer-scope footers; therefore docs/GATE-0V-WHOLEGRAFT-PROTOCOL.md MUST be SHA-256 pinned "
                    "ONLY AFTER final render_documentation.py execution at the end of Stage S5."
                ),
                "passed": bool(has_facts_block and has_scope_footer and idempotent),
            }

    return {
        "tested": True,
        "non_breaking_placement": "stage0_decision_tree_v1.json dedicated block + standalone docs/GATE-0V-WHOLEGRAFT-PROTOCOL.md (Playbook §4.1.20 section hash pinned rather than whole-file hash)",
        "playbook_sec4120_expected_sha256": PLAYBOOK_SEC4120_EXPECTED_SHA256,
        "playbook_sec4120_actual_sha256": pb_sec_sha,
        "verify_iip0035_playbook_sec4120_canonical_sha_verified": pb_ok,
        "verify_iip0035_dec114_decision_tree_sha256_preserved": dt_ok,
        "render_documentation_protocol_doc_replay": renderer_check,
        "passed": bool(pb_ok and dt_ok and renderer_check.get("passed", False)),
    }


def verify_gy030_graveyard_parity(openislet_root: Path) -> Dict[str, Any]:
    """
    R03-B3: Programmatic parity check verifying that `GY-030` in
    `data/graveyard/idea_graveyard_v0.5.json` agrees with this verifier's exact
    true Clopper-Pearson negative-control bound (`U95 <= 0.15%` on `n >= 20,000`)
    and tier-specific PASS statuses (`PASS_WHOLEGRAFT_BANK_QUALIFICATION`,
    `PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE`, `PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL`),
    with zero stale generic PASS or `0.10%` control-bound instructions!
    """
    gy_path = openislet_root / "data" / "graveyard" / "idea_graveyard_v0.5.json"
    if not gy_path.is_file():
        return {"tested": True, "passed": False, "reason": "Missing data/graveyard/idea_graveyard_v0.5.json"}
    gy_doc = strict_json_load_file(gy_path, preserve_boundary_decimals=False)
    guards = gy_doc.get("off_grid_molecular_dead_end_guardrails", {}).get("guardrails", [])
    gy30 = next((g for g in guards if g.get("graveyard_card_id") == GRAVEYARD_CARD_ID), None)
    if not isinstance(gy30, dict):
        return {"tested": True, "passed": False, "reason": f"Missing {GRAVEYARD_CARD_ID} entry in idea_graveyard_v0.5.json"}

    assay_text = str(gy30.get("cheapest_falsification_assay") or "")
    summary_text = str(gy30.get("summary") or "")
    combined_text = assay_text + "\n" + summary_text

    required_pass_statuses = sorted(GATE0V_PASS_VERDICTS_BY_TIER.values())
    missing_pass_statuses = [st for st in required_pass_statuses if st not in assay_text]
    has_obsolete_generic_pass = "PASS_WHOLEGRAFT_GATE0V_AND_STRESS_AP1903" in combined_text
    has_exact_0p15_bound = "U95 <= 0.15%" in assay_text and "n >= 20,000" in assay_text
    has_stale_0p10_bound = bool(re.search(r"(?:<=|U95\s*<=)\s*0\.10%|0\.10%\s*UCL", assay_text))
    has_trusted_store_ref = "--trusted-qualification-store" in assay_text
    metadata_ok = bool(
        gy30.get("guardrail_id") == GRAVEYARD_GUARDRAIL_ID
        and gy30.get("severity_level") == "BLOCK"
        and gy30.get("contribution_id") == "IIP-0043"
    )
    passed = bool(
        metadata_ok
        and len(missing_pass_statuses) == 0
        and (not has_obsolete_generic_pass)
        and has_exact_0p15_bound
        and (not has_stale_0p10_bound)
        and has_trusted_store_ref
    )
    return {
        "tested": True,
        "graveyard_card_id": GRAVEYARD_CARD_ID,
        "guardrail_id": gy30.get("guardrail_id"),
        "metadata_ok": metadata_ok,
        "expected_tier_pass_statuses": required_pass_statuses,
        "missing_tier_pass_statuses": missing_pass_statuses,
        "obsolete_generic_pass_absent": not has_obsolete_generic_pass,
        "exact_neg_ctrl_u95_0p15pct_bound_present": has_exact_0p15_bound,
        "stale_0p10pct_control_bound_absent": not has_stale_0p10_bound,
        "trusted_qualification_store_referenced": has_trusted_store_ref,
        "passed": passed,
    }


def audit_protected_files_and_ceg_delta(
    openislet_root: Path,
    investigations_root: Path | None,
    protected_manifest_path: Path | None = None,
) -> Dict[str, Any]:
    """
    Verify protected files against either an explicit post-0038 --protected-manifest JSON
    OR the built-in 20 frozen IIP-0035 file pins (automatically switching the two publisher-
    redacted study extracts `17375075.json` and `39571901.json` to their exact manifest-pinned
    public-redacted SHA-256 hashes when `.openislet_public_bundle` is present — B8!), PLUS
    Playbook §4.1.20 canonical section hash.
    """
    is_public_bundle = _is_public_bundle(openislet_root)
    if protected_manifest_path is not None:
        manifest_obj = strict_json_load_file(protected_manifest_path, preserve_boundary_decimals=False)
        if isinstance(manifest_obj, dict) and "protected_files_sha256" in manifest_obj:
            all_expected = dict(manifest_obj["protected_files_sha256"])
        elif isinstance(manifest_obj, dict):
            all_expected = {str(k): str(v) for k, v in manifest_obj.items() if isinstance(v, str)}
        else:
            raise ValueError("Protected manifest must be a JSON object mapping relative paths to SHA-256 hex digests")
        manifest_source = f"parameterized_manifest:{protected_manifest_path.name}"
        bundle_mode = "parameterized_manifest"
    else:
        all_expected = {
            **IIP0035_17_PROTECTED_FILES_SHA256,
            **IIP0035_OWN_FROZEN_OUTPUTS_SHA256,
        }
        if is_public_bundle:
            all_expected.update(PUBLIC_BUNDLE_REDACTED_FILES_SHA256)
            manifest_source = "default_iip0035_20_frozen_files_public_bundle_plus_playbook_sec4120_section_hash"
            bundle_mode = "public_bundle_redacted_pins"
        else:
            manifest_source = "default_iip0035_20_frozen_files_plus_playbook_sec4120_section_hash"
            bundle_mode = "full_private_repo_pins"

    protected_check = {}
    all_protected_ok = True
    for rel, exp_sha in all_expected.items():
        p = openislet_root / rel
        if p.is_file():
            actual = hashlib.sha256(p.read_bytes()).hexdigest()
            ok = actual == exp_sha
        else:
            actual = None
            ok = False
        if not ok:
            all_protected_ok = False
        category = (
            "public_bundle_redacted_study_pin"
            if (is_public_bundle and rel in PUBLIC_BUNDLE_REDACTED_FILES_SHA256 and protected_manifest_path is None)
            else (
                "iip0035_17_protected"
                if rel in IIP0035_17_PROTECTED_FILES_SHA256
                else ("iip0035_own_frozen" if rel in IIP0035_OWN_FROZEN_OUTPUTS_SHA256 else "parameterized_manifest_pin")
            )
        )
        protected_check[rel] = {
            "category": category,
            "expected_sha256": exp_sha,
            "actual_sha256": actual,
            "matches": ok,
        }

    r4_compat = verify_r4_playbook_decision_tree_and_renderer_compatibility(openislet_root)
    playbook_sec4120_ok = bool(r4_compat.get("verify_iip0035_playbook_sec4120_canonical_sha_verified"))
    all_protected_ok = bool(all_protected_ok and playbook_sec4120_ok)

    # Live CEG v1 & Ring-1 diff with CASE-NORMALIZED id_type + BOTH pmid & id_value checked
    ceg_path = openislet_root / "data" / "extracted" / "context_evidence_graph_v1.json"
    ceg = strict_json_load_file(ceg_path, preserve_boundary_decimals=False)
    ceg_studies = ceg["studies"]
    ceg_pmids: set[str] = set()
    lowercase_id_type_records: List[str] = []
    for sid, s in ceg_studies.items():
        p_raw = str(s.get("pmid") or "").strip()
        iv_raw = str(s.get("id_value") or "").strip()
        it_raw = str(s.get("id_type") or "").strip()
        if it_raw == "pmid":
            lowercase_id_type_records.append(sid)
        if p_raw.isdigit():
            ceg_pmids.add(p_raw)
        if it_raw.upper() == "PMID" and iv_raw.isdigit():
            ceg_pmids.add(iv_raw)

    ring1_pmids = {
        os.path.basename(p).replace(".json", "")
        for p in glob.glob(str(openislet_root / "data" / "extracted" / "[0-9]*.json"))
    }
    ring1_only_missing_from_ceg = sorted(ring1_pmids - ceg_pmids, key=int)

    staging_diff: Dict[str, Any] = {"available": False}
    if investigations_root is not None and (investigations_root / "ideas" / "CEG-DELTA-STAGING.md").is_file():
        staging_path = investigations_root / "ideas" / "CEG-DELTA-STAGING.md"
        lines = staging_path.read_text(encoding="utf-8").splitlines()
        inline_pmids: Dict[str, Dict[str, Any]] = {}
        url_mismatches: List[Dict[str, Any]] = []
        for idx, line in enumerate(lines, 1):
            if line.startswith("*(Audit note:"):
                continue
            if line.startswith("|") and not line.startswith("| Added") and not line.startswith("| :---:") and not line.startswith("|---"):
                cols = [c.strip() for c in line.strip("|").split("|")]
                pmid_col = cols[1] if len(cols) > 1 else ""
                status_col = cols[6] if len(cols) > 6 else ""
                for disp, url_id in re.findall(r"\[`?(\d{6,9})`?\]\(https://pubmed\.ncbi\.nlm\.nih\.gov/(\d{6,9})/?\)", pmid_col):
                    if disp != url_id:
                        url_mismatches.append({"line": idx, "display_pmid": disp, "url_pmid": url_id})
                    inline_pmids.setdefault(disp, {"line": idx, "status": status_col})

        exp023_path = (
            investigations_root
            / "idea-exploration"
            / "EXP-023-ars-route3-euglycemic-rest-and-39326417-fix"
            / "artifacts-neon-s3"
            / "ceg_delta_candidates_s3.md"
        )
        exp023_extra: List[str] = []
        if exp023_path.is_file():
            found_023 = set(re.findall(r"(?:PMID[:\s]*|pubmed\.ncbi\.nlm\.nih\.gov/)(\d{6,9})", exp023_path.read_text(encoding="utf-8")))
            exp023_extra = sorted(found_023 - set(inline_pmids.keys()), key=int)

        all_inline = set(inline_pmids.keys())
        all_combined = all_inline | set(exp023_extra)
        already_in_ceg = sorted(all_inline & ceg_pmids, key=int)
        already_in_ring1 = sorted(all_inline & ring1_pmids, key=int)
        net_new_inline = sorted(all_inline - ceg_pmids, key=int)
        net_new_combined = sorted(all_combined - ceg_pmids, key=int)

        # 7 REAL staging repairs + 1 confirmed Zenodo CC-BY-4.0 dataset record (10813168 false-positive dropped!)
        staging_diff = {
            "available": True,
            "inline_unique_staged_pmids": len(all_inline),
            "exp023_linked_extra_pmids": len(exp023_extra),
            "exp023_linked_extra_list": exp023_extra,
            "combined_unique_staged_pmids": len(all_combined),
            "already_ingested_in_ceg_v1_count": len(already_in_ceg),
            "already_ingested_in_ring1_count": len(already_in_ring1),
            "net_new_inline_missing_from_ceg_v1_count": len(net_new_inline),
            "net_new_combined_missing_from_ceg_v1_count": len(net_new_combined),
            "verified_real_staging_repairs_count": 7,
            "confirmed_non_bug_zenodo_records_count": 1,
            "staging_anomalies_detected_7_real_repairs": {
                "repair_1_url_vs_display_mismatches": url_mismatches,
                "repair_2_stale_header_claim_line10": "Header still reads '135/135 Net-New Staged PMIDs' whereas file has 237 inline (243 combined), 46 already ingested, 191 inline (197 combined) genuinely net-new",
                "repair_3_journal_typos_line44": [
                    "PMID:37188763 (Augsornworawat 2023): Nature Cell Biology, mislabeled Nat Biotechnol",
                    "PMID:38864729 (Chen 2024): Protein Science, mislabeled Nat Commun",
                    "PMID:27787618 (van der Torren 2017): Diabetologia, mislabeled Diabetes",
                ],
                "repair_4_license_mislabels_lines_43_44": [
                    "Line 43 PMID:35795779 (Wunderlich 2022): cc-by-nc-nd in Europe PMC, mislabeled CC-BY-4.0",
                    "Line 44 PMID:38864729 (Chen 2024): cc-by-nc-nd in Europe PMC, mislabeled CC-BY-4.0",
                ],
                "repair_5_journal_typos_line43": [
                    "PMID:15228089: Mol Cell Biochem, mislabeled JBC",
                    "PMID:12370285: Mol Cell Biol, mislabeled PNAS",
                ],
                "repair_6_uninlined_exp023_linked_pmids_line50": exp023_extra,
                "repair_7_untyped_reviews_and_guidelines": "14 net-new staged PMIDs are PubMed-indexed Reviews/Guidelines requiring 6-class CEG record_class typing (not empirical_primary_study)",
            },
            "confirmed_false_positive_non_bugs_cleared": [
                {
                    "location": "CEG-DELTA-STAGING.md:48",
                    "record_id": "Zenodo:10813168",
                    "status": "CONFIRMED_VALID_ZENODO_CC_BY_4_0_DATASET_DO_NOT_MUTATE",
                    "detail": (
                        "10813168 on line 48 is a valid Zenodo v3 variant-effect predictions dataset record "
                        "(confirmed CC-BY-4.0 via Zenodo API), NOT a PubMed PMID. Prior repair #7 was a false "
                        "positive from querying 10813168 as a PMID; retain line 48 intact while keeping raw "
                        "prediction score values quarantined under Rule C3."
                    ),
                }
            ],
        }

    gy030_parity = verify_gy030_graveyard_parity(openislet_root)

    # R05-M1 + R15-M2: Programmatic public release ledger verifying all 8 IIP-0043 attributed CEG
    # cross-link edges verbatim against data/extracted/context_evidence_graph_v1.json, checking exact
    # parity against the independent expected specification on edge_id, queue_id, PMID, prior edge IDs,
    # relation, target_gate_or_module, applicability, cited_outcome_tuples list, reciprocal links, and
    # primary_certification_eligible=False.
    ceg_edges_by_id = {
        str(e.get("edge_id")): e
        for e in ceg.get("edges", [])
        if isinstance(e, dict) and e.get("edge_id")
    }
    ceg_outcomes = ceg.get("outcomes", {})
    eight_crosslinks_rows: List[Dict[str, Any]] = []
    all_8_crosslinks_ok = True
    for spec in CEG_DELTA_V33_EIGHT_CROSSLINKS_SPEC:
        eid = spec["edge_id"]
        qid = spec["queue_id"]
        exp_pmid = spec["pmid"]
        exp_priors = list(spec["pre_iip0043_prior_edge_ids"])
        exp_relation = str(spec["expected_relation"])
        exp_target = str(spec["expected_target_gate_or_module"])
        exp_applicability = str(spec["expected_applicability"])
        exp_outcomes = list(spec["expected_cited_outcome_tuples"])
        edge_obj = ceg_edges_by_id.get(eid)
        study_obj = ceg_studies.get(qid) if isinstance(ceg_studies, dict) else None
        actual_pmid = str((study_obj or {}).get("pmid") or (study_obj or {}).get("id_value") or "").strip()
        prior_all_present = all(peid in ceg_edges_by_id for peid in exp_priors)
        cited_tuples = list(edge_obj.get("cited_outcome_tuples", [])) if isinstance(edge_obj, dict) else []
        reciprocal_ok = bool(
            cited_tuples
            and all(
                isinstance(ceg_outcomes.get(ot), dict)
                and eid in (ceg_outcomes[ot].get("cited_by_edge_ids") or [])
                for ot in cited_tuples
            )
        )
        edge_present = isinstance(edge_obj, dict)
        relation_exact_match = bool(edge_present and edge_obj.get("relation") == exp_relation)
        target_exact_match = bool(edge_present and edge_obj.get("target_gate_or_module") == exp_target)
        applicability_exact_match = bool(edge_present and edge_obj.get("applicability") == exp_applicability)
        outcome_ids_exact_match = bool(edge_present and cited_tuples == exp_outcomes)
        verbatim_fields_ok = bool(
            relation_exact_match
            and target_exact_match
            and applicability_exact_match
            and outcome_ids_exact_match
        )
        row_ok = bool(
            edge_present
            and edge_obj.get("queue_id") == qid
            and actual_pmid == exp_pmid
            and prior_all_present
            and verbatim_fields_ok
            and reciprocal_ok
            and edge_obj.get("primary_certification_eligible") is False
        )
        if not row_ok:
            all_8_crosslinks_ok = False
        eight_crosslinks_rows.append({
            "edge_id": eid,
            "source_queue_id": qid,
            "source_pmid": exp_pmid,
            "pre_iip0043_study_status": spec["pre_iip0043_study_status"],
            "pre_iip0043_prior_edge_ids": exp_priors,
            "previous_edge_state": spec["previous_edge_state"],
            "added_edge_status": spec["added_edge_status"],
            "evidence_scope": spec["evidence_scope"],
            "contextual_scope_note": spec["contextual_scope_note"],
            "expected_relation": exp_relation,
            "expected_target_gate_or_module": exp_target,
            "expected_applicability": exp_applicability,
            "expected_cited_outcome_tuples": exp_outcomes,
            "target_gate_or_module": edge_obj.get("target_gate_or_module") if edge_present else None,
            "relation": edge_obj.get("relation") if edge_present else None,
            "applicability": edge_obj.get("applicability") if edge_present else None,
            "primary_certification_eligible": edge_obj.get("primary_certification_eligible") if edge_present else None,
            "cited_outcome_tuples": cited_tuples,
            "exists_verbatim_in_ceg_v1": edge_present,
            "prior_edges_verified_in_ceg_v1": prior_all_present,
            "expected_relation_verified": relation_exact_match,
            "expected_target_gate_or_module_verified": target_exact_match,
            "expected_applicability_verified": applicability_exact_match,
            "expected_cited_outcome_tuples_verified": outcome_ids_exact_match,
            "verbatim_field_parity_verified": verbatim_fields_ok,
            "reciprocal_cited_by_edge_ids_verified": reciprocal_ok,
            "verified": row_ok,
        })
    eight_crosslinks_ledger = {
        "ceg_source_file": "data/extracted/context_evidence_graph_v1.json",
        "expected_crosslinks_count": len(CEG_DELTA_V33_EIGHT_CROSSLINKS_SPEC),
        "verified_crosslinks_count": sum(1 for r in eight_crosslinks_rows if r["verified"]),
        "all_eight_crosslinks_verified": all_8_crosslinks_ok,
        "all_eight_verbatim_field_parity_verified": bool(
            all_8_crosslinks_ok and all(r["verbatim_field_parity_verified"] for r in eight_crosslinks_rows)
        ),
        "verbatim_field_parity_fields_checked": [
            "edge_id",
            "queue_id",
            "pmid",
            "pre_iip0043_prior_edge_ids",
            "relation",
            "target_gate_or_module",
            "applicability",
            "cited_outcome_tuples",
            "reciprocal_cited_by_edge_ids",
            "primary_certification_eligible",
        ],
        "contextual_scope_summary": (
            "All 8 CEG-DELTA V3.3 cross-link edges are indirect/contextual scoping links "
            "(primary_certification_eligible=false). In particular, M0066:L3 (PMID:41403780, CD155/CD276 mouse study) "
            "provides immune-engraftment context and M0184:L4 (PMID:38956087, human islet stress study) provides "
            "stress-response context, both indirect to NW-08."
        ),
        "edges": eight_crosslinks_rows,
    }

    return {
        "bundle_mode": bundle_mode,
        "protected_manifest_source": manifest_source,
        "protected_files_zero_byte_invariance_ok": all_protected_ok,
        "protected_files_checked_total": len(protected_check),
        "playbook_sec4120_section_hash_verified": playbook_sec4120_ok,
        "protected_files": protected_check,
        "r4_playbook_sec4120_dec114_and_renderer_compatibility": r4_compat,
        "gy030_graveyard_parity": gy030_parity,
        "ceg_delta_v33_eight_crosslinks_ledger": eight_crosslinks_ledger,
        "graveyard_allocation": {
            "guardrail_id": GRAVEYARD_GUARDRAIL_ID,
            "graveyard_card_id": GRAVEYARD_CARD_ID,
            "decollision_note": "GY-030 / OFFGRID_GUARD_020 allocated cleanly to CAND-034 (IIP-0043); CAND-031 owns GY-029.",
        },
        "dual_evaluator_composite_release_governance": {
            "option2_zero_lims_touch_active": True,
            "executable_composite_wrapper": "evaluate_gate0v_composite_release.py",
            "lot_cli_entrypoint": "verify_iip0043_wholegraft_gate0v_and_calibration.py --evaluate-lot <lot.json> --trusted-qualification-store <store>",
            "trusted_store_deployment_prerequisite": (
                "Software record-content and SHA-256 verification leave independent QA operator administration, "
                "write-restricted storage control, and separation of duties over --trusted-qualification-store "
                "as mandatory deployment prerequisites."
            ),
            "non_substitution_rule": (
                "Because scripts/wetlab_contract.py remains 0-byte frozen under Option-2 invariance, "
                "a standalone READY_FOR_ENCAPSULATION_COMPLETE_STAGE0_EVIDENCE verdict from wetlab_contract.py "
                "NEVER clears Gate 0V or clinical release on its own. Clinical release is enforced by "
                "executable evaluate_gate0v_composite_release.py requiring BOTH (1) legacy wetlab_contract.py "
                "READY_FOR_ENCAPSULATION_COMPLETE_STAGE0_EVIDENCE invoked with preserved canonical product_variant_id/"
                "current_lot_id/mcb_id AND (2) tier-matched verify_iip0043 PASS (`PASS_WHOLEGRAFT_BANK_QUALIFICATION`, "
                "`PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE`, or `PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL`), with prior "
                "bank/process qualification (including the mandatory verified original JSON-object archived bank payload "
                "for LOT_RELEASE_SURROGATE) resolved SOLELY from an independently administered `--trusted-qualification-store`."
            ),
        },
        "live_corpus_counts": {
            "ceg_v1_total_records": len(ceg_studies),
            "ceg_v1_unique_numeric_pmids_case_normalized": len(ceg_pmids),
            "ceg_v1_lowercase_id_type_records_caught": lowercase_id_type_records,
            "ceg_v1_non_pmid_records": len(ceg_studies) - len(ceg_pmids),
            "ring1_extracted_numeric_studies": len(ring1_pmids),
            "ring1_studies_missing_from_ceg_v1_backfill_candidates": {
                "count": len(ring1_only_missing_from_ceg),
                "includes_30074059_ifie2018": "30074059" in ring1_only_missing_from_ceg,
            },
            "ceg_v1_arms": len(ceg.get("arms", {})),
            "ceg_v1_outcomes": len(ceg.get("outcomes", {})),
            "ceg_v1_edges": len(ceg.get("edges", [])),
        },
        "ceg_delta_staging_diff": staging_diff,
    }


# ---------------------------------------------------------------------------
# Part D: OQ-016 §5.5 Invariance, Detection Power & Two-Stage FPR Pass Power
# ---------------------------------------------------------------------------
def quantify_oq016_and_tail_risk_reduction(openislet_root: Path) -> Dict[str, Any]:
    port_path = openislet_root / "data" / "extracted" / "islet1_5arm_autologous_portfolio_v0.8.0.json"
    port = strict_json_load_file(port_path, preserve_boundary_decimals=False)
    inv = port["live_3x2_baseline_invariant"]

    # Detection power under independent-cell model P(K >= 1 | p_true, n, eta) = 1 - (1 - p_true * eta)^n
    tail_risk_rows = []
    for p_true_pct in (0.05, 0.10, 0.25, 0.50, 1.00, 5.00):
        with _clean_dec_ctx(80, ROUND_HALF_EVEN):
            p_true = Decimal(str(p_true_pct)) / Decimal(100)
            eta = Decimal("0.80")
            q_eff = Decimal(1) - p_true * eta
        p_miss_1p = _pow_directed(q_eff, 13244, 80, ROUND_CEILING)
        p_miss_3p = _pow_directed(q_eff, 15990, 80, ROUND_CEILING)
        with _clean_dec_ctx(80, ROUND_FLOOR):
            p_det_1p = Decimal(1) - p_miss_1p
            p_det_3p = Decimal(1) - p_miss_3p
        tail_risk_rows.append({
            "silent_non_beta_reservoir_prevalence_pct": p_true_pct,
            "infected_cells_if_in_alpha_240M": int(240_000_000 * (p_true_pct / 100.0)),
            "infected_cells_if_in_iec_100M": int(100_125_000 * (p_true_pct / 100.0)),
            "infected_cells_if_in_pericyte_33M": int(33_375_000 * (p_true_pct / 100.0)),
            "legacy_beta_only_gate0v_detection_prob_pct": 0.0,
            "exp031_1pathogen_n13244_eta0p80_detection_prob_pct": _dec_to_float_pct(p_det_1p, 6),
            "exp031_3pathogen_n15990_eta0p80_detection_prob_pct": _dec_to_float_pct(p_det_3p, 6),
            "residual_miss_prob_3pathogen": format(p_miss_3p, ".4e"),
            "statistical_model_note": "Exact binomial Clopper-Pearson confidence applies strictly at deff=1.0 (independent binary observations); clustered lots (deff > 1.0) route to HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE.",
        })

    # B3 / R03-M1: Modeled two-stage screening/control clean-lot pass probability derived PROGRAMMATICALLY
    # from TRUE Clopper-Pearson U95 cutoffs at fixed sample sizes (n_panel = 15,990, n_ctrl = 20,000) across
    # 15 independent panels under perfect Stage-2 confirmation (models ONLY screening + negative-control checks,
    # NOT full-protocol pass probability across calibrants, latent ddPCR, Gate 0V-A, Gate 0V-Geno, or Gate 0V-Kill):
    #   - True U95 <= 0.15% admits k <= 20 (U95(20,20000) = 0.145277% <= 0.15%; U95(21,20000) = 0.151167% > 0.15%)
    #     -> 97.6508% modeled 15-panel screening/control pass probability at nominal FPR = 5e-4!
    #   - True U95 <= 0.10% admits k <= 12 (U95(12,20000) = 0.097195% <= 0.10%; U95(13,20000) = 0.103323% > 0.10%)
    #     -> collapses to 3.0034% modeled 15-panel screening/control pass probability at nominal FPR = 5e-4!
    fpr_comparison = []
    n_panel = 15990
    max_s1_events = int(n_panel * 0.002)  # 31
    n_ctrl = 20000
    alpha_ctrl = Decimal("0.05")

    def _max_admissible_k_for_true_u95(cap: Decimal) -> int:
        k_max = -1
        for k_try in range(0, 60):
            if exact_clopper_pearson_upper_general(k_try, n_ctrl, alpha_ctrl, prec=60) <= cap:
                k_max = k_try
            else:
                break
        return k_max

    max_ctrl_uncal_0p05 = 10  # Uncalibrated empirical <= 0.05% of 20,000
    max_ctrl_true_u95_0p10 = _max_admissible_k_for_true_u95(Decimal("0.0010"))  # 12
    max_ctrl_true_u95_0p15 = _max_admissible_k_for_true_u95(Decimal("0.0015"))  # 20
    u95_at_k20_pct = _dec_to_float_pct(exact_clopper_pearson_upper_general(max_ctrl_true_u95_0p15, n_ctrl, alpha_ctrl, prec=60), 6)
    u95_at_k21_pct = _dec_to_float_pct(exact_clopper_pearson_upper_general(max_ctrl_true_u95_0p15 + 1, n_ctrl, alpha_ctrl, prec=60), 6)

    for fpr_val in (1e-6, 1e-5, 1e-4, 5e-4):
        fpr_dec = Decimal(str(fpr_val))
        p_naive_all15 = (1.0 - fpr_val) ** (15 * n_panel)
        lam = n_panel * fpr_val
        p_s1_single = float(_binomial_tail_lower_eq_interval(max_s1_events, n_panel, fpr_dec, prec=30)[0])
        p_s1_all15 = p_s1_single ** 15
        p_ctrl_0p05_single = float(_binomial_tail_lower_eq_interval(max_ctrl_uncal_0p05, n_ctrl, fpr_dec, prec=30)[0])
        p_ctrl_0p05_all15_complete = (p_s1_single * p_ctrl_0p05_single) ** 15
        p_ctrl_u95_0p10_single = float(_binomial_tail_lower_eq_interval(max_ctrl_true_u95_0p10, n_ctrl, fpr_dec, prec=30)[0])
        p_complete_u95_0p10_all15 = (p_s1_single * p_ctrl_u95_0p10_single) ** 15
        p_ctrl_u95_0p15_single = float(_binomial_tail_lower_eq_interval(max_ctrl_true_u95_0p15, n_ctrl, fpr_dec, prec=30)[0])
        p_complete_u95_0p15_all15 = (p_s1_single * p_ctrl_u95_0p15_single) ** 15
        scoped_model_desc = (
            "Modeled two-stage screening/control clean-lot pass probability at fixed sample sizes "
            "(n_panel=15,990, n_ctrl=20,000) across 15 independent panels under perfect Stage-2 confirmation; "
            "excludes spike-calibrant, latent-ddPCR, Gate 0V-A, Gate 0V-Geno, and Gate 0V-Kill pass probabilities."
        )
        fpr_comparison.append({
            "stage1_flow_fpr": fpr_val,
            "expected_false_positives_per_panel_15990": round(lam, 3),
            "expected_false_positives_per_neg_ctrl_20000": round(n_ctrl * fpr_val, 3),
            "true_u95_0p15pct_max_admissible_k": max_ctrl_true_u95_0p15,
            "true_u95_at_max_admissible_k_pct": u95_at_k20_pct,
            "true_u95_at_first_rejected_k_pct": u95_at_k21_pct,
            "true_u95_0p10pct_max_admissible_k": max_ctrl_true_u95_0p10,
            "naive_conjunctive_raw_k0_p_pass_all15_pct": round(p_naive_all15 * 100.0, 4),
            "stage1_screen_only_p_pass_all15_pct": round(p_s1_all15 * 100.0, 4),
            "true_u95_0p15pct_ctrl_single_panel_p_pass_pct": round(p_ctrl_u95_0p15_single * 100.0, 4),
            # R04-M1: Primary scoped machine-readable fields accurately naming the modeled 15-panel screen+control scope
            "modeled_two_stage_screening_control_15panel_pass_pct": round(p_complete_u95_0p15_all15 * 100.0, 4),
            "modeled_two_stage_screening_control_15panel_pass_pct_at_u95_0p10pct": round(p_complete_u95_0p10_all15 * 100.0, 4),
            "modeled_two_stage_screening_control_15panel_pass_pct_at_uncal_0p05pct": round(p_ctrl_0p05_all15_complete * 100.0, 4),
            "modeled_two_stage_screening_control_scope": scoped_model_desc,
            "modeled_screening_and_control_pass_probability_scope": scoped_model_desc,
            "clears_80pct_modeled_screening_and_control_criterion": bool(p_complete_u95_0p15_all15 >= 0.80),
            # Explicitly documented deprecated legacy aliases retained strictly for backward JSON-key compatibility
            "deprecated_legacy_field_aliases": {
                "status": "DEPRECATED_BACKWARD_COMPAT_ALIASES_DO_NOT_INTERPRET_AS_FULL_PROTOCOL_END_TO_END",
                "true_u95_0p15pct_complete_end_to_end_all15_p_pass_pct": "Deprecated alias for modeled_two_stage_screening_control_15panel_pass_pct (15-panel Stage-1 screen + neg-control model only)",
                "true_u95_0p10pct_ctrl_cap_complete_all15_p_pass_pct": "Deprecated alias for modeled_two_stage_screening_control_15panel_pass_pct_at_u95_0p10pct",
                "uncalibrated_0p05pct_emp_ctrl_cap_complete_all15_p_pass_pct": "Deprecated alias for modeled_two_stage_screening_control_15panel_pass_pct_at_uncal_0p05pct",
                "clears_80pct_complete_clean_lot_qualification_criterion": "Deprecated alias for clears_80pct_modeled_screening_and_control_criterion",
            },
            "uncalibrated_0p05pct_emp_ctrl_cap_complete_all15_p_pass_pct": round(p_ctrl_0p05_all15_complete * 100.0, 4),
            "true_u95_0p10pct_ctrl_cap_complete_all15_p_pass_pct": round(p_complete_u95_0p10_all15 * 100.0, 4),
            "true_u95_0p15pct_complete_end_to_end_all15_p_pass_pct": round(p_complete_u95_0p15_all15 * 100.0, 4),
            "clears_80pct_complete_clean_lot_qualification_criterion": bool(p_complete_u95_0p15_all15 >= 0.80),
        })

    return {
        "oq016_live_headline_delta_pp": 0.0,
        "live_3x2_baseline_preserved": {
            "locked_pct": inv["locked_pct"],
            "modular_k100_pct": inv["modular_k100_pct"],
            "modular_k90_pct": inv["modular_k90_pct"],
            "shared_ceiling_pct": inv["shared_ceiling_pct"],
        },
        "substantive_modeling_reason_for_zero_headline_delta": (
            "IIP-0043 introduces and extends Stage-0 candidate qualification checks targeting five pre-IND "
            "surveillance and calibration blindspots pending physical confirmation (non-beta viral reservoirs "
            "and innate-antiviral/intrinsic-stress resilience under Blueprint Gates 1, 2B, and 4; acute "
            "24-h/72-h stressed pan-lineage AP1903 viability/erasure screening and 72-hour NW-08 oxygen-bridge "
            "verification linked to Blueprint Gate 5 per ISLET-1-BLUEPRINT.md §1.2, while long-horizon "
            "pan-lineage clonogenic eradication remains owned by Blueprint Gate 5 / legacy MCB clonogenic "
            "outgrowth trials in wetlab_contract.py and ISLET-1-BLUEPRINT.md §4.5) without modifying any "
            "H1-H4 therapeutic ceiling (c = [0.88, 0.87, 0.89, 0.85])."
        ),
        "statistical_family_and_coverage_scope": (
            "The 30-test global FWER <= 0.05 allocation (alpha = floor(1/600)) governs the named 3-pathogen x "
            "5-lineage x 2-stage Day-28 surveillance assay endpoint family; Gate 0V-Kill, latent-genome ddPCR, "
            "and ectopic-receptor addenda are reported and gated separately under their explicit directional "
            "one-sided per-estimand sampling models (assuming independent representative binary observations "
            "with a common event probability p per component; independent trials with unequal unit event "
            "probabilities fall outside the standard common-probability binomial model). "
            "The 97.6508% figure is strictly the modeled two-stage screening/control clean-lot pass probability at "
            "fixed sample sizes (n_panel = 15,990, n_ctrl = 20,000) across 15 independent panels at nominal FPR = 5e-4 "
            "with perfect Stage-2 confirmation (not a full-protocol empirical pass rate)."
        ),
        "pre_ind_silent_reservoir_tail_risk_reduction": tail_risk_rows,
        "twostage_fpr_clean_lot_pass_probability_audit": fpr_comparison,
    }


# ---------------------------------------------------------------------------
# Reference Passing Measured-Lot Payload & Adversarial Test Suite (Zero `assert`)
# ---------------------------------------------------------------------------
def _valid_digest(tag: str) -> str:
    return hashlib.sha256(f"OPENISLET_EXP031_REFERENCE_EVIDENCE::{tag}".encode("utf-8")).hexdigest()


def build_passing_reference_payload(
    *,
    lot_id: str = "LOT-2026-MCB01-R01",
    mcb_id: str = "MCB-ISLET1-A-001",
    product_variant_id: str | None = None,
    product_variant: str | None = None,
    qualification_tier: str = "BANK_QUALIFICATION",
    ectopic_receptors: List[str] | None = None,
    include_cd46_addendum: bool = False,
    include_cd55_addendum: bool = False,
    bridged_mcb_qualification_sha256: str | None = None,
    bridged_mcb_qualification_record: Dict[str, Any] | None = None,
    process_qualification_ref_sha256: str | None = None,
    process_qualification_record: Dict[str, Any] | None = None,
    use_direct_infected_veh_survivor_mode: bool = True,
    antiviral_genotype_stratum: str = "TYK2_WT__IFIH1_WT_OR_A946T",
    independent_biological_units_n: int = MIN_INDEPENDENT_BIOLOGICAL_UNITS_N,
    independent_sampling_unit_class: str = "RECONCILED_MULTI_WELL_CELL_ASSAY_WITH_UNIT_PARTITION",
    openislet_root: Path | None = None,
) -> Dict[str, Any]:
    """
    Construct a fully passing, auditable, raw-count measured-lot payload for Gate 0V & Gate 0V-Kill
    (Round-02 compliant across B1-B6):
      - Canonical registered `product_variant_id` (default: `ISLET1_A4_ARM1B`).
      - Exact lineage ledger reconciliation (`total_viable_cells_acquired_n == 5*16000 + 2400 == 82400`)
        plus mandatory `unassigned_fraction_viral_readout` (`2400` screened, `0` hits).
      - Dual-target ddPCR validation (`UL138`+`UL55` for HCMV; `POS`+`NEG` 5'-del RNA for CVB).
      - Powered exact-Decimal Clopper-Pearson CD55 echovirus addendum (`n = 16,000` / lineage).
      - External trusted store reference digests ONLY (no self-attested inline approval unless caller
        explicitly passes an inline record to test rejection/conflict!).
    """
    pvid = (
        product_variant_id
        if product_variant_id is not None
        else (product_variant if product_variant is not None else "ISLET1_A4_ARM1B")
    )

    def _make_pathogen_block(pid: str) -> Dict[str, Any]:
        if pid == "hcmv":
            dd_targets = {
                "UL138": {"k": 0, "n": 16000, "primers_verified": True},
                "UL55": {"k": 0, "n": 16000, "primers_verified": True},
            }
        else:
            dd_targets = {
                "CVB_5PRIME_DELETION_POS_RNA": {"k": 0, "n": 16000, "primers_verified": True},
                "CVB_5PRIME_DELETION_NEG_RNA": {"k": 0, "n": 16000, "primers_verified": True},
            }
        lat_block: Dict[str, Any] = {
            "ddpcr_target_panel": "HCMV_UL138_UL55_LATENT_LYTIC" if pid == "hcmv" else "CVB_5PRIME_DELETION_AWARE_POS_NEG_RNA",
            "ddpcr_targets": dd_targets,
            "ddpcr_positive_events_k": 0,
            "ddpcr_cell_equivalents_screened_n": 16000,
            "evidence_sha256": _valid_digest(f"latent_{pid}"),
        }
        if pid == "hcmv":
            lat_block.update({
                "reactivation_challenge_applied": True,
                "reactivation_protocol_evidence_sha256": _valid_digest("hcmv_reactivation"),
                "reactivation_7d_outgrowth_pfu_ml": "0",
                "reactivation_assay_volume_ml": "2.0",
                "reactivation_lod_pfu_ml": "0.5",
            })
        else:
            lat_block["cvb_5prime_deletion_primers_verified"] = True

        return {
            "endocrine_72h_log10_pfu_u95": "1.65",
            "vascular_72h_log10_pfu_u95": "1.50",
            "coculture_72h_log10_pfu_u95": "1.72",
            "endocrine_day14_log10_reduction_l95": "3.60",
            "vascular_day14_log10_reduction_l95": "3.85",
            "day14_negative_strand_or_ie1_rna_positive_wells_k": 0,
            "day14_negative_strand_or_ie1_rna_wells_tested_n": 12,
            "day28_supernatant_infectious_pfu_ml": "0",
            "day28_supernatant_assay_volume_ml": "2.0",
            "day28_supernatant_lod_pfu_ml": "0.5",
            "dual_marker_lineage_panel_attested": True,
            "lineage_panel_spec_sha256": _valid_digest(f"dual_marker_panel_{pid}"),
            # Exact arithmetic reconciliation: 5 * 16,000 + 2,400 = 82,400 (2.9126% unassigned <= 5.0%)
            "total_viable_cells_acquired_n": 82400,
            "lineage_unassigned_cells_n": 2400,
            "unassigned_fraction_viral_readout": {
                "unassigned_cells_screened_n": 2400,
                "stage1_screen_positive_k": 0,
                "stage2_sorted_for_confirmation_n": 0,
                "stage2_confirmed_infectious_k": 0,
            },
            "day28_latent_and_defective_genome_arm": lat_block,
            "day28_persistence_by_lineage": {
                lin: {
                    "cells_assigned_n": 16000,
                    "cells_scored_n": 16000,
                    "stage1_screen_positive_k": 2,
                    "stage2_sorted_for_confirmation_n": 2,
                    "stage2_confirmed_infectious_k": 0,
                    "uninfected_ctrl_fp_k": 1,
                    "uninfected_ctrl_scored_n": 20000,
                    "spike_calibrant_detected_k": 29,
                    "spike_calibrant_total_n": 29,
                    "fragile_infected_spike_detected_k": 29,
                    "fragile_infected_spike_total_n": 29,
                    "pre_dissociation_spike_in_attested": True,
                    "pre_dissociation_spike_sop_evidence_sha256": _valid_digest(f"spike_{pid}_{lin}"),
                }
                for lin in GRAFT_LINEAGES
            },
        }

    # Realistic 1.0e7 assembled organoid cells/arm -> pericyte = 357,530 input cells
    input_cells_1e7_arm = {
        "beta": 5_141_940,
        "alpha": 2_570_970,
        "delta": 856_990,
        "plvap_iec": 1_072_580,
        "pericyte": 357_530,
    }

    receptors = (
        list(ectopic_receptors)
        if ectopic_receptors is not None
        else sorted(_implied_ectopic_receptors_for_product(pvid, openislet_root=openislet_root))
    )

    kill_regimes_to_build = (
        STRESS_AP1903_REGIMES
        if qualification_tier == "BANK_QUALIFICATION"
        else ("normoxia_baseline", "hypoxia_1pct_plus_cytokines")
    )
    pathogens_to_build = (
        GATE0V_PATHOGENS
        if qualification_tier == "BANK_QUALIFICATION"
        else (("cvb4_e2",) if qualification_tier == "LOT_RELEASE_SURROGATE" else ())
    )

    payload: Dict[str, Any] = {
        "lot_id": lot_id,
        "mcb_id": mcb_id,
        "product_variant_id": pvid,
        "qualification_tier": qualification_tier,
        "ectopic_viral_receptors_expressed": receptors,
        "clustering_and_independence_spec": {
            "independent_biological_units_n": independent_biological_units_n,
            "independent_sampling_unit_class": independent_sampling_unit_class,
            "clustering_design_effect_deff": "1.0",
            "unit_definition": (
                "independent_single_cell_limiting_dilution_units"
                if independent_sampling_unit_class == "INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT"
                else "independent_stage7_differentiation_organoid_wells"
            ),
        },
        "cxadr_ko_present": False,
        "cxadr_locus_genotyping_evidence_sha256": _valid_digest("cxadr_wt_pcr_sanger"),
        "antiviral_genotype_stratum": antiviral_genotype_stratum,
        "gate0v_a_poly_ic_sensing": {
            "poly_ic_dose_ng_ml": "500",
            "assay_duration_h": "24",
            "vehicle_control_isg_baseline_verified": True,
            "vehicle_control_evidence_sha256": _valid_digest("polyic_vehicle_ctrl"),
            "positive_control_ifna_isg_fold": {lin: "12.5" for lin in GRAFT_LINEAGES},
            "lineage_isg_fold_induction": {
                lin: {
                    "IFNB1_or_IFNL1_fold": "18.5",
                    "ISG15_fold": "42.0",
                    "MX1_fold": "31.2",
                    "OAS1_fold": "24.8",
                }
                for lin in GRAFT_LINEAGES
            },
        },
        "gate0v_b_infectious_challenge": {
            "pathogens": {pid: _make_pathogen_block(pid) for pid in pathogens_to_build},
        },
        "gate0v_kill_stress_ap1903": {
            reg: {
                lin: {
                    "veh_24h_viable_n": 950 if reg == "normoxia_baseline" else 560,
                    "veh_24h_input_n": 1000,
                    "ap1903_24h_input_n": 10000,
                    "ap1903_24h_viable_survivors_k": 0,
                    "veh_72h_viable_n": 940 if reg == "normoxia_baseline" else 540,
                    "veh_72h_input_n": 1000,
                    "ap1903_72h_input_n": input_cells_1e7_arm[lin] if reg in INFECTED_AP1903_REGIMES else 100000,
                    "ap1903_72h_viable_survivors_k": 0,
                    **(
                        {
                            "aliquot_linkage_id": f"ALQ-{lot_id}-{reg[:8].upper()}-{lin.upper()}",
                            "infected_surveillance_aliquot_linkage_mode": "SAME_72H_ALIQUOT",
                            "caspase9_3_activity_fold_over_vehicle": "14.2",
                            "viral_caspase_stratification_evidence_sha256": _valid_digest(f"casp_{reg}_{lin}"),
                            "pre_ap1903_lineage_input_cells_n": input_cells_1e7_arm[lin],
                            "post_ap1903_viable_survivors_total_n": 0,
                            "survivors_scored_n": 0,
                            "post_ap1903_viable_viral_pos_k": 0,
                            "pretreat_viral_pos_k": 250,
                            "pretreat_scored_n": 1000,
                            **(
                                {
                                    "infected_cell_escape_mode": "DIRECT_INFECTED_VEHICLE_DENOMINATOR",
                                    "pretreat_infected_veh_survivor_n": 125,
                                }
                                if use_direct_infected_veh_survivor_mode
                                else {}
                            ),
                            "spike_calibrant_detected_k": 24,
                            "spike_calibrant_total_n": 24,
                            "fragile_infected_spike_detected_k": 24,
                            "fragile_infected_spike_total_n": 24,
                            "pre_dissociation_spike_in_attested": True,
                            "pre_dissociation_spike_sop_evidence_sha256": _valid_digest(f"kill_spike_{reg}_{lin}"),
                        }
                        if reg in INFECTED_AP1903_REGIMES
                        else {}
                    ),
                }
                for lin in GRAFT_LINEAGES
            }
            for reg in kill_regimes_to_build
        },
    }

    if antiviral_genotype_stratum in EDITED_ANTIVIRAL_GENOTYPES:
        if antiviral_genotype_stratum == "TYK2_P1104A_HOM__IFIH1_WT":
            payload["mycobacterial_tb_igra_screening_attested"] = True
            payload["tb_igra_evidence_sha256"] = _valid_digest("tb_igra_clear")
        for pid in pathogens_to_build:
            payload["gate0v_b_infectious_challenge"]["pathogens"][pid]["edited_minus_wt_day14_log10_reduction_l95"] = "-0.12"
            payload["gate0v_b_infectious_challenge"]["pathogens"][pid]["paired_noninferiority_replicates_n"] = 6
        if qualification_tier == "AUTOLOGOUS_D1B_PROCESS_QUAL":
            payload["genotype_noninferiority_by_pathogen"] = {
                pid: {
                    "edited_minus_wt_day14_log10_reduction_l95": "-0.12",
                    "paired_noninferiority_replicates_n": 6,
                }
                for pid in GATE0V_PATHOGENS
            }

    if qualification_tier == "LOT_RELEASE_SURROGATE":
        if bridged_mcb_qualification_sha256 is not None:
            payload["bridged_mcb_qualification_sha256"] = bridged_mcb_qualification_sha256
        elif bridged_mcb_qualification_record is not None:
            payload["bridged_mcb_qualification_sha256"] = bridged_mcb_qualification_record["sha256"]
        else:
            rec_bq = build_authenticated_bank_qualification_record(
                mcb_id=mcb_id,
                product_variant_id=pvid,
                bank_lot_id=f"BANK-{mcb_id}",
                bank_payload_sha256=_valid_digest(f"bank_payload_{mcb_id}_{pvid}"),
                antiviral_genotype_stratum=antiviral_genotype_stratum,
            )
            payload["bridged_mcb_qualification_sha256"] = rec_bq["sha256"]
        if bridged_mcb_qualification_record is not None:
            payload["bridged_mcb_qualification_record"] = bridged_mcb_qualification_record
    elif qualification_tier == "AUTOLOGOUS_D1B_PROCESS_QUAL":
        if process_qualification_ref_sha256 is not None:
            payload["process_qualification_ref_sha256"] = process_qualification_ref_sha256
        elif process_qualification_record is not None:
            payload["process_qualification_ref_sha256"] = process_qualification_record["sha256"]
        else:
            rec_pq = build_authenticated_process_qualification_record(
                product_variant_id=pvid,
                process_qual_id=f"PROCQUAL-{pvid}",
            )
            payload["process_qualification_ref_sha256"] = rec_pq["sha256"]
        if process_qualification_record is not None:
            payload["process_qualification_record"] = process_qualification_record
        payload["adventitious_agent_panel_evidence_sha256"] = _valid_digest("d1b_adv_agent_pass")

    if include_cd46_addendum:
        payload["cd46_tropic_viral_addendum"] = {
            "hhv6b_cd134_scope_distinguished": True,
            "measles_wt_slam_nectin4_scope_distinguished": True,
            **{
                vid: {
                    "titer_72h_log10_pfu_u95": "1.40",
                    "day14_log10_reduction_l95": "3.70",
                    "day28_supernatant_pfu_ml": "0",
                    "day28_assay_volume_ml": "2.0",
                    "day28_lod_pfu_ml": "0.5",
                    "day28_5lineage_ddpcr_confirmed_k": 0,
                    "day28_5lineage_cells_screened_per_lineage_min_n": 16000,
                    "protocol_evidence_sha256": _valid_digest(f"cd46_{vid}"),
                }
                for vid in CD46_ADDENDUM_VIRUSES
            },
        }

    if include_cd55_addendum:
        payload["cd55_tropic_echovirus_addendum"] = {
            "echovirus_strain_panel": list(CD55_REQUIRED_ECHOVIRUS_STRAINS),
            "protocol_evidence_sha256": _valid_digest("cd55_echovirus_panel"),
            "strain_results": {
                strain_id: {
                    "titer_72h_log10_pfu_u95": "1.35" if strain_id == "echovirus_7" else "1.38",
                    "day14_log10_reduction_l95": "3.80" if strain_id == "echovirus_7" else "3.75",
                    "day28_supernatant_pfu_ml": "0",
                    "day28_assay_volume_ml": "2.0",
                    "day28_lod_pfu_ml": "0.5",
                    "protocol_evidence_sha256": _valid_digest(f"cd55_{strain_id}"),
                    "day28_persistence_by_lineage": {
                        lin: {
                            "confirmed_k": 0,
                            "cells_screened_n": 16000,
                        }
                        for lin in GRAFT_LINEAGES
                    },
                }
                for strain_id in CD55_REQUIRED_ECHOVIRUS_STRAINS
            },
        }

    if independent_sampling_unit_class == "RECONCILED_MULTI_WELL_CELL_ASSAY_WITH_UNIT_PARTITION":
        reconcile_fixture_per_unit_counts(payload, units_n=independent_biological_units_n)
    payload["payload_sha256"] = compute_canonical_lot_sha256(payload)
    return payload


def _seal(payload: Dict[str, Any]) -> Dict[str, Any]:
    payload["payload_sha256"] = compute_canonical_lot_sha256(payload)
    return payload


def run_decimal_interval_regression_suite() -> Dict[str, Any]:
    """
    Rigorous outward-directed interval regression proofs across extreme finite inputs,
    exact-equality thresholds, and all R2 interval/boundary counterexamples (mode-straddling CDF upper endpoint,
    large exact tie n=4,097, tiny cap 1e-106, unit cap 1.0 clamped vs unclamped, narrow ambient
    exponent range Emin=-2 with Inexact trap enabled).
    """
    checks: List[Dict[str, Any]] = []

    def _rational_enclose_ln(x_frac: Fraction) -> Tuple[Fraction, Fraction]:
        def _two_atanh(y: Fraction) -> Tuple[Fraction, Fraction]:
            terms = 150
            low = 2 * sum((y ** (2 * j + 1)) / (2 * j + 1) for j in range(terms))
            tail = 2 * (y ** (2 * terms + 1)) / ((2 * terms + 1) * (1 - y * y))
            return low, low + tail

        m = 0
        x = x_frac
        while x < Fraction(1, 2):
            x *= 2
            m += 1
        t_lo, t_hi = _two_atanh(Fraction(1, 3))
        x_lo, x_hi = _two_atanh((1 - x) / (1 + x))
        return -x_hi - m * t_hi, -x_lo - m * t_lo

    # 1. Exact rational enclosure at alpha = 0.005, prec = 120
    alpha_005 = Decimal("0.005")
    lo_005, hi_005 = _exact_ln_interval(alpha_005, prec=120)
    r_lo, r_hi = _rational_enclose_ln(Fraction(alpha_005))
    checks.append({
        "test": "ln_interval_alpha_0p005_strictly_outward",
        "passed": bool(Fraction(lo_005) <= r_lo and r_hi <= Fraction(hi_005)),
        "inward_violation": bool(r_hi < Fraction(lo_005) or Fraction(hi_005) < r_lo),
    })

    # 2. alpha = 0.5, 0.5 - 1e-180, 0.5 + 1e-180, 1 - 1e-180, 1e-180 (zero reversal, zero exception!)
    with _clean_dec_ctx(240, ROUND_HALF_EVEN):
        special_alphas = [
            ("alpha_0p5_exact", Decimal("0.5")),
            ("alpha_0p5_minus_1e180", Decimal("0.5") - Decimal("1e-180")),
            ("alpha_0p5_plus_1e180", Decimal("0.5") + Decimal("1e-180")),
            ("alpha_1_minus_1e180", Decimal("1") - Decimal("1e-180")),
            ("alpha_1e180", Decimal("1e-180")),
        ]
    for name, aval in special_alphas:
        try:
            lo_a, hi_a = _exact_ln_interval(aval, prec=120)
            cp_a = sound_zero_event_clopper_pearson_upper(1, aval, Decimal(1), prec=80)
            true_u = Fraction(1) - Fraction(aval)
            ok = bool(lo_a <= hi_a < Decimal(0) and Fraction(cp_a["u_thinned_lower_dec"]) <= true_u <= Fraction(cp_a["u_thinned_upper_dec"]))
        except Exception:
            ok = False
        checks.append({"test": f"domain_enclosure_{name}", "passed": ok})

    # 3. Exact counterexample: n = 1, eta = 1, alpha = 0.125 - 1e-180 (MUST NOT under-cover!)
    with _clean_dec_ctx(240, ROUND_HALF_EVEN):
        alpha_ce = Decimal("0.125") - Decimal("1e-180")
    cp_ce = sound_zero_event_clopper_pearson_upper(1, alpha_ce, Decimal(1), prec=80)
    true_u_ce = Fraction(1) - Fraction(alpha_ce)
    ce_ok = bool(Fraction(cp_ce["u_thinned_lower_dec"]) <= true_u_ce <= Fraction(cp_ce["u_thinned_upper_dec"]))
    checks.append({
        "test": "counterexample_n1_eta1_alpha_0p125_minus_1e180_no_undercoverage",
        "returned_upper": str(cp_ce["u_thinned_upper_dec"]),
        "undercoverage": bool(Fraction(cp_ce["u_thinned_upper_dec"]) < true_u_ce),
        "passed": ce_ok,
    })

    # 4. Exact-equality boundary: alpha = 0.25, cap = 0.5, eta = 1 -> exact min_n_pass == 2, verified True!
    ss_eq = min_n_for_zero_event_cap(Decimal("0.5"), Decimal("0.25"), Decimal(1), prec=80)
    checks.append({
        "test": "min_n_exact_equality_alpha_0p25_cap_0p5_n_eq_2",
        "reported_n": ss_eq["min_n_pass"],
        "boundary_strictly_verified": ss_eq["boundary_strictly_verified"],
        "passed": bool(ss_eq["min_n_pass"] == 2 and ss_eq["boundary_strictly_verified"] is True),
    })

    # 5. Hostile ambient context: prec=4, ROUND_FLOOR, Inexact trap ENABLED!
    ord_disp = sound_zero_event_clopper_pearson_upper(70, Decimal("0.005"), Decimal("0.80"))["u_thinned_upper_pct_6dp"]
    ord_minn = min_n_for_zero_event_cap(Decimal("0.0005"), Decimal("0.005"), Decimal("0.80"))
    trapped = False
    hostile_disp = None
    hostile_minn = None
    _clear_math_caches()
    with localcontext() as ctx:
        ctx.prec = 4
        ctx.rounding = ROUND_FLOOR
        ctx.traps[decimal.Inexact] = True
        try:
            hostile_disp = sound_zero_event_clopper_pearson_upper(70, Decimal("0.005"), Decimal("0.80"))["u_thinned_upper_pct_6dp"]
            hostile_minn = min_n_for_zero_event_cap(Decimal("0.0005"), Decimal("0.005"), Decimal("0.80"))
        except decimal.Inexact:
            trapped = True
    checks.append({
        "test": "hostile_prec4_floor_inexact_trap_immunity",
        "ordinary_pct": ord_disp,
        "hostile_pct": hostile_disp,
        "inexact_trapped": trapped,
        "passed": bool((not trapped) and hostile_disp == ord_disp and hostile_minn == ord_minn),
    })

    # 6. Counterexample #1: mode-straddling mixed-count binomial CDF fallback
    #    k=1, n=2, p=Decimal('0.' + '3'*178) -> upper endpoint MUST be >= exact rational CDF!
    p_178 = Decimal("0." + "3" * 178)
    p_178_frac = Fraction(p_178)
    exact_cdf_1_2 = (1 - p_178_frac) ** 2 + 2 * p_178_frac * (1 - p_178_frac)
    t_lo_178, t_hi_178 = _binomial_tail_lower_eq_interval(1, 2, p_178, prec=80)
    ce1_ok = bool(Fraction(t_lo_178) <= exact_cdf_1_2 <= Fraction(t_hi_178))
    checks.append({
        "test": "r2_counterexample1_mode_straddle_binomial_cdf_k1_n2_p_178threes",
        "lower_outward": bool(Fraction(t_lo_178) <= exact_cdf_1_2),
        "upper_outward": bool(Fraction(t_hi_178) >= exact_cdf_1_2),
        "passed": ce1_ok,
    })

    # 7. Counterexample #2: large exact equality cap=0.1, eta=1, alpha=0.9**4097 -> exact n=4097!
    tie_n = 4097
    tie_alpha = Decimal("0." + str(9 ** tie_n).zfill(tie_n))
    big_tie = min_n_for_zero_event_cap(Decimal("0.1"), tie_alpha, Decimal(1), prec=80)
    ce2_ok = bool(
        big_tie["min_n_pass"] == 4097
        and big_tie["fail_n_minus_1"] == 4096
        and big_tie["boundary_strictly_verified"] is True
    )
    checks.append({
        "test": "r2_counterexample2_large_exact_tie_cap0p1_alpha_0p9_pow_4097",
        "reported_n": big_tie["min_n_pass"],
        "fail_n_minus_1": big_tie["fail_n_minus_1"],
        "boundary_strictly_verified": big_tie["boundary_strictly_verified"],
        "passed": ce2_ok,
    })

    # 8. Counterexample #3a: tiny positive cap=1e-106, alpha=0.5 (dynamic precision, zero exception!)
    try:
        tiny_res = min_n_for_zero_event_cap(Decimal("1e-106"), Decimal("0.5"), Decimal(1), prec=80)
        ce3a_ok = bool(
            tiny_res["min_n_pass"] > 10 ** 105
            and tiny_res["boundary_strictly_verified"] is True
            and _adjudicate_zero_event_vs_cap(tiny_res["min_n_pass"], Decimal("1e-106"), Decimal("0.5"), Decimal(1)) == "LE"
            and _adjudicate_zero_event_vs_cap(tiny_res["min_n_pass"] - 1, Decimal("1e-106"), Decimal("0.5"), Decimal(1)) == "GT"
        )
        tiny_err = None
    except Exception as exc:
        ce3a_ok = False
        tiny_res = {}
        tiny_err = f"{type(exc).__name__}: {exc}"
    checks.append({
        "test": "r2_counterexample3a_tiny_cap_1e_neg106_alpha_0p5_dynamic_precision",
        "min_n_digits": len(str(tiny_res.get("min_n_pass", ""))) if tiny_res else 0,
        "boundary_strictly_verified": tiny_res.get("boundary_strictly_verified"),
        "error": tiny_err,
        "passed": ce3a_ok,
    })

    # 9. Counterexample #3b: valid unit-cap cap=1.0, alpha=0.05, eta=0.1 -> clamped n=1 (unclamped ref=29)!
    unit_res = min_n_for_zero_event_cap(Decimal(1), Decimal("0.05"), Decimal("0.1"), prec=80)
    ce3b_ok = bool(
        unit_res["min_n_pass"] == 1
        and unit_res["fail_n_minus_1"] is None
        and unit_res["boundary_strictly_verified"] is True
        and unit_res.get("unclamped_min_n_reference") == 29
    )
    checks.append({
        "test": "r2_counterexample3b_unit_cap_1p0_clamped_n1_vs_unclamped_n29",
        "reported_n": unit_res["min_n_pass"],
        "unclamped_ref": unit_res.get("unclamped_min_n_reference"),
        "boundary_strictly_verified": unit_res["boundary_strictly_verified"],
        "passed": ce3b_ok,
    })

    # 10. Counterexample #3c: narrow ambient exponent range Emin=-2, Emax=100 + Inexact trap on mixed CP!
    _clear_math_caches()
    narrow_trapped = False
    narrow_val = None
    with localcontext(Context(prec=4, rounding=ROUND_FLOOR, Emin=-2, Emax=100, traps=[decimal.Inexact])):
        try:
            narrow_val = exact_clopper_pearson_upper_general(1, 3, Decimal("0.05"), prec=80)
        except Exception:
            narrow_trapped = True
    ce3c_ok = bool((not narrow_trapped) and narrow_val is not None and Decimal(0) < narrow_val < Decimal(1))
    checks.append({
        "test": "r2_counterexample3c_mixed_cp_narrow_ambient_emin_neg2_inexact_trap_immunity",
        "trapped": narrow_trapped,
        "passed": ce3c_ok,
    })

    # 11. R06-B2 Exact component-probability ratio boundary:
    #     veh = 51/100 (alpha_veh = 0.025 -> s_veh_lower ≈ 0.4080363292), treated = 0/90402
    #     (alpha_treated = 0.025 -> u_ratio = 0.00010000201070... > 0.0001 MUST NOT PASS 0.0001,
    #     whereas 0/90404 clears <= 0.0001!).
    b2_fail_res = exact_paired_vehicle_ratio_bounds(
        0, 90402, 51, 100, alpha_treated=Decimal("0.025"), alpha_veh=Decimal("0.025"), prec=80
    )
    b2_pass_res = exact_paired_vehicle_ratio_bounds(
        0, 90404, 51, 100, alpha_treated=Decimal("0.025"), alpha_veh=Decimal("0.025"), prec=80
    )
    b2_ok = bool(
        abs(float(b2_fail_res["s_veh_lower_dec"]) - 0.4080363292) < 1e-9
        and abs(float(b2_fail_res["u_ratio_dec"]) - 0.00010000201070) < 1e-13
        and b2_fail_res["u_ratio_dec"] > Decimal("0.0001")
        and b2_pass_res["u_ratio_dec"] <= Decimal("0.0001")
    )
    checks.append({
        "test": "r06_b2_exact_component_ratio_boundary_veh_51of100_treated_0of90402_exceeds_1e4",
        "s_veh_lower_10dp": format(b2_fail_res["s_veh_lower_dec"], ".10f"),
        "u_ratio_at_90402_14dp": format(b2_fail_res["u_ratio_dec"], ".14f"),
        "u_ratio_at_90404_14dp": format(b2_pass_res["u_ratio_dec"], ".14f"),
        "exceeds_1e4_at_90402": bool(b2_fail_res["u_ratio_dec"] > Decimal("0.0001")),
        "clears_1e4_at_90404": bool(b2_pass_res["u_ratio_dec"] <= Decimal("0.0001")),
        "passed": b2_ok,
    })

    # 12. R08-M1: Exact paired ratio bounds (u_ratio and l_ratio) explicitly labeled as separate
    #     directional one-sided confidence statements at 1 - (alpha_treated + alpha_veh) each,
    #     not a simultaneous two-sided interval at that same unsplit alpha!
    m1_dir_ok = bool(
        b2_fail_res.get("confidence_statement_type") == "DIRECTIONAL_ONE_SIDED_SEPARATE_AT_1_MINUS_ALPHA_SUM"
        and b2_fail_res.get("directional_one_sided_confidence_lower_bound") == "0.950"
        and b2_fail_res.get("simultaneous_two_sided_at_unsplit_alpha_claimed") is False
        and b2_pass_res.get("confidence_statement_type") == "DIRECTIONAL_ONE_SIDED_SEPARATE_AT_1_MINUS_ALPHA_SUM"
    )
    checks.append({
        "test": "r08_m1_exact_paired_ratio_bounds_labeled_directional_one_sided_separate",
        "confidence_statement_type": b2_fail_res.get("confidence_statement_type"),
        "directional_one_sided_confidence_lower_bound": b2_fail_res.get("directional_one_sided_confidence_lower_bound"),
        "simultaneous_two_sided_at_unsplit_alpha_claimed": b2_fail_res.get("simultaneous_two_sided_at_unsplit_alpha_claimed"),
        "passed": m1_dir_ok,
    })

    # 13. R09-B2 (a) + R15-M1: Vehicle-normalized survival ratio domain [0, +infinity) — synthetic 90%
    #     (900/1,000) vs 70% (700/1,000) at deff=1 with component tails alpha_treated=0.025 and alpha_veh=0.025
    #     MUST NEVER clamp u_ratio to 1.0; guarantees 0 <= l_ratio <= point_est <= u_ratio!
    r90_70 = exact_paired_vehicle_ratio_bounds(
        900, 1000, 700, 1000, alpha_treated=Decimal("0.025"), alpha_veh=Decimal("0.025"), prec=80
    )
    pt_90_70 = Decimal(900) / Decimal(700)
    r90_70_ok = bool(
        Decimal(0) <= r90_70["l_ratio_dec"] <= pt_90_70 <= r90_70["u_ratio_dec"]
        and r90_70["u_ratio_dec"] == r90_70["u_ratio_unclamped_dec"]
        and r90_70["u_ratio_clamped_to_unity"] is False
        and r90_70["estimand_domain"] == "[0, +infinity)"
        and r90_70["bounds_ordered_l_le_u"] is True
        and r90_70["treated_survival_exceeds_vehicle_survival"] is True
        and r90_70["ratio_lower_limit_exceeds_unity"] is True
        and r90_70["ratio_upper_limit_exceeds_unity"] is True
        and abs(float(r90_70["l_ratio_dec"]) - 1.2079329473) < 1e-8
        and abs(float(r90_70["u_ratio_dec"]) - 1.3688921818) < 1e-8
    )
    checks.append({
        "test": "r09_b2_paired_ratio_90pct_vs_70pct_unclamped_domain_valid_l_le_pt_le_u",
        "treated_counts": "900/1000",
        "vehicle_counts": "700/1000",
        "alpha_treated": "0.025",
        "alpha_veh": "0.025",
        "l_ratio_10dp": format(r90_70["l_ratio_dec"], ".10f"),
        "point_est_10dp": format(pt_90_70, ".10f"),
        "u_ratio_10dp": format(r90_70["u_ratio_dec"], ".10f"),
        "u_ratio_clamped_to_unity": r90_70["u_ratio_clamped_to_unity"],
        "bounds_ordered_l_le_u": r90_70["bounds_ordered_l_le_u"],
        "passed": r90_70_ok,
    })

    # 14. R09-B2 (b): Full ratio-domain sweep (p_drug = 0, < p_veh, == p_veh, > p_veh, = 1,
    #     k_veh = 0 yielding u_ratio = +Infinity, and deff >= 1.0) guaranteeing 0 <= L <= U ALWAYS!
    sweep_cases = (
        (0, 1000, 700, 1000, Decimal("1.0")),
        (500, 1000, 700, 1000, Decimal("1.0")),
        (700, 1000, 700, 1000, Decimal("1.0")),
        (900, 1000, 700, 1000, Decimal("1.0")),
        (1000, 1000, 700, 1000, Decimal("1.0")),
        (900, 1000, 700, 1000, Decimal("2.0")),
        (10, 1000, 700, 1000, Decimal("2.5")),
        (500, 1000, 0, 1000, Decimal("1.0")),
        (0, 1000, 0, 1000, Decimal("1.0")),
    )
    sweep_ok = True
    for kt, nt, kv, nv, dff in sweep_cases:
        sw = exact_paired_vehicle_ratio_bounds(kt, nt, kv, nv, deff=dff, prec=80)
        if not (
            Decimal(0) <= sw["l_ratio_dec"] <= sw["u_ratio_dec"]
            and sw["bounds_ordered_l_le_u"] is True
            and sw["u_ratio_clamped_to_unity"] is False
            and sw["u_ratio_dec"] == sw["u_ratio_unclamped_dec"]
        ):
            sweep_ok = False
        if kv == 0:
            if not (sw["u_ratio_dec"] == Decimal("Infinity") and sw["u_ratio_80d"] == "Infinity"):
                sweep_ok = False
        elif dff == Decimal("1.0"):
            pt_sw = Decimal(kt * nv) / Decimal(nt * kv)
            if not (sw["l_ratio_dec"] <= pt_sw <= sw["u_ratio_dec"]):
                sweep_ok = False
    checks.append({
        "test": "r09_b2_paired_ratio_full_domain_sweep_l_le_u_including_zero_veh_and_deff",
        "cases_swept": len(sweep_cases),
        "all_ordered_and_unclamped": sweep_ok,
        "passed": sweep_ok,
    })

    # 15. R10-B3 (a): Exact Round-09 counterexample (200/299 vs 500/500, deff=100, alpha=0.49/0.025)
    #     Outward effective counts k_eff_lower = floor(k * n_eff / n) = 1, k_eff_upper = ceil(k * n_eff / n) = 2
    #     eliminate the floor(k/deff)/floor(n/deff) > k/n inward-bias bug and guarantee 0 <= L <= point <= U!
    r10_ce = exact_paired_vehicle_ratio_bounds(
        200,
        299,
        500,
        500,
        alpha_treated=Decimal("0.49"),
        alpha_veh=Decimal("0.025"),
        deff=Decimal("100"),
        prec=80,
    )
    r10_pt = Decimal(200) / Decimal(299)
    r10_ce_ok = bool(
        r10_ce["n_treated_eff"] == 2
        and r10_ce["k_treated_eff_lower"] == 1
        and r10_ce["k_treated_eff_upper"] == 2
        and Decimal(0) <= r10_ce["l_ratio_dec"] <= r10_pt <= r10_ce["u_ratio_dec"]
        and r10_ce["bounds_ordered_l_le_u"] is True
        and r10_ce["bounds_ordered_l_le_point_le_u"] is True
    )
    checks.append({
        "test": "r10_b3_counterexample_200of299_vs_500of500_deff100_alpha0p49_ordered_l_le_pt_le_u",
        "n_treated_eff": r10_ce["n_treated_eff"],
        "k_treated_eff_lower": r10_ce["k_treated_eff_lower"],
        "k_treated_eff_upper": r10_ce["k_treated_eff_upper"],
        "l_ratio_10dp": format(r10_ce["l_ratio_dec"], ".10f"),
        "point_est_10dp": format(r10_pt, ".10f"),
        "u_ratio_10dp": format(r10_ce["u_ratio_dec"], ".10f"),
        "passed": r10_ce_ok,
    })

    # 16. R10-B3 (b): Dense admitted-domain ordering sweep across n, k, deff (including deff > n),
    #     and alpha_treated, alpha_veh <= 0.5 (with alpha_treated + alpha_veh < 1) -> ZERO violations!
    dense_total = 0
    dense_violations = 0
    for nt_d in (1, 2, 3, 7, 17, 299):
        kt_vals = sorted(set((0, 1, nt_d // 3, nt_d // 2, (2 * nt_d) // 3, max(0, nt_d - 1), nt_d)))
        for kt_d in kt_vals:
            for dff_d in (Decimal("1"), Decimal("1.5"), Decimal("3"), Decimal("100"), Decimal("500")):
                for kv_d, nv_d in ((0, 10), (1, 10), (7, 10), (10, 10)):
                    for at_d, av_d in (
                        (Decimal("0.025"), Decimal("0.025")),
                        (Decimal("0.49"), Decimal("0.025")),
                        (Decimal("0.5"), Decimal("0.49")),
                        (Decimal("0.025"), Decimal("0.5")),
                    ):
                        dense_total += 1
                        res_d = exact_paired_vehicle_ratio_bounds(
                            kt_d, nt_d, kv_d, nv_d, alpha_treated=at_d, alpha_veh=av_d, deff=dff_d, prec=40
                        )
                        if res_d["empirical_ratio_point_estimate_dec"] is None:
                            if not (
                                res_d["bounds_ordered_l_le_u"] is True
                                and res_d["bounds_ordered_l_le_point_le_u"] is None
                                and Decimal(0) <= res_d["l_ratio_dec"] <= res_d["u_ratio_dec"]
                            ):
                                dense_violations += 1
                        elif not (
                            res_d["bounds_ordered_l_le_u"] is True
                            and res_d["bounds_ordered_l_le_point_le_u"] is True
                            and Decimal(0) <= res_d["l_ratio_dec"] <= res_d["empirical_ratio_point_estimate_dec"] <= res_d["u_ratio_dec"]
                        ):
                            dense_violations += 1
    checks.append({
        "test": "r10_b3_dense_admitted_domain_ordering_sweep_zero_violations",
        "grid_points_verified": dense_total,
        "ordering_violations": dense_violations,
        "passed": bool(dense_total >= 1000 and dense_violations == 0),
    })

    # 17. R11-B3: Sol's exact exchangeable binary count mixture counterexample (N=1000, P(K=0)=0.20,
    #     P(K=10)=0.80, true rate=0.008, true variance=16, true deff=125/62=2.0161290322580645,
    #     deterministic control=1.0): n_eff=496 gives u_ratio~0.00740994 < 0.008 (80% actual coverage
    #     for a nominal 95% upper bound!). Narrowed helper MUST set exact_directional_confidence_certified=False,
    #     confidence_scope="NON_AUTHORIZING_VARIANCE_ADJUSTED_DIAGNOSTIC_ONLY", release_authorizing_eligible=False,
    #     directional_one_sided_confidence_lower_bound=None, and adjudication_disposition=
    #     "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE" (while deff==1.0 certifies True)!
    sol_deff = Decimal("2.0161290322580645")
    sol_u_only = exact_component_probability_ratio_upper(
        0, 1000, Decimal("0.025"), (Decimal("1.0"),), deff=sol_deff, prec=80
    )
    sol_paired = exact_paired_vehicle_ratio_bounds(
        0, 1000, 1_000_000, 1_000_000, alpha_treated=Decimal("0.025"), alpha_veh=Decimal("0.025"), deff=sol_deff, prec=80
    )
    indep_ref = exact_paired_vehicle_ratio_bounds(
        0, 1000, 1_000_000, 1_000_000, alpha_treated=Decimal("0.025"), alpha_veh=Decimal("0.025"), deff=Decimal("1.0"), prec=80
    )
    r11_b3_ok = bool(
        sol_u_only["n_treated_eff"] == 496
        and abs(float(sol_u_only["u_ratio_dec"]) - 0.00740994) < 1e-6
        and sol_u_only["u_ratio_dec"] < Decimal("0.008")
        and sol_u_only["exact_directional_confidence_certified"] is False
        and sol_u_only["confidence_scope"] == "NON_AUTHORIZING_VARIANCE_ADJUSTED_DIAGNOSTIC_ONLY"
        and sol_u_only["release_authorizing_eligible"] is False
        and sol_u_only["adjudication_disposition"] == "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE"
        and sol_paired["n_treated_eff"] == 496
        and sol_paired["exact_directional_confidence_certified"] is False
        and sol_paired["confidence_scope"] == "NON_AUTHORIZING_VARIANCE_ADJUSTED_DIAGNOSTIC_ONLY"
        and sol_paired["release_authorizing_eligible"] is False
        and sol_paired["directional_one_sided_confidence_lower_bound"] is None
        and sol_paired["adjudication_disposition"] == "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE"
        and sol_paired["bounds_ordered_l_le_point_le_u"] is True
        and indep_ref["exact_directional_confidence_certified"] is True
        and indep_ref["confidence_scope"] == "EXACT_INDEPENDENT_BINOMIAL_BONFERRONI_DEFF_EQ_1"
        and indep_ref["release_authorizing_eligible"] is True
        and indep_ref["directional_one_sided_confidence_lower_bound"] == "0.950"
    )
    checks.append({
        "test": "r11_b3_sol_exchangeable_mixture_deff_2p0161_non_authorizing_vs_deff_eq_1_certified",
        "n_treated_eff": sol_u_only["n_treated_eff"],
        "diagnostic_u_ratio_8dp": format(sol_u_only["u_ratio_dec"], ".8f"),
        "clustered_certified": sol_paired["exact_directional_confidence_certified"],
        "clustered_disposition": sol_paired["adjudication_disposition"],
        "independent_certified": indep_ref["exact_directional_confidence_certified"],
        "passed": r11_b3_ok,
    })

    # 18. R11-M1: Zero-denominator boundary conventions:
    #     (a) 0/0 -> empirical point is None and bounds_ordered_l_le_point_le_u is None (NOT True!)
    #     (b) k > 0 / 0 -> empirical point is +Infinity, u_ratio is +Infinity, bounds_ordered_l_le_point_le_u is True.
    z00 = exact_paired_vehicle_ratio_bounds(0, 100, 0, 100, prec=60)
    z50 = exact_paired_vehicle_ratio_bounds(5, 100, 0, 100, prec=60)
    r11_m1_ok = bool(
        z00["empirical_ratio_point_estimate_dec"] is None
        and z00["bounds_ordered_l_le_u"] is True
        and z00["bounds_ordered_l_le_point_le_u"] is None
        and z00["u_ratio_dec"] == Decimal("Infinity")
        and z00["zero_denominator_boundary_convention"] == "UNDEFINED_0_OVER_0_POINT_AND_POINT_ORDERING_FLAG_NONE"
        and z50["empirical_ratio_point_estimate_dec"] == Decimal("Infinity")
        and z50["bounds_ordered_l_le_u"] is True
        and z50["bounds_ordered_l_le_point_le_u"] is True
        and z50["u_ratio_dec"] == Decimal("Infinity")
        and z50["zero_denominator_boundary_convention"] == "POSITIVE_NUMERATOR_ZERO_DENOMINATOR_POINT_PLUS_INFINITY"
    )
    checks.append({
        "test": "r11_m1_zero_denominator_boundary_conventions_0over0_none_and_kpos_over0_infinity",
        "zero_over_zero_point": z00["empirical_ratio_point_estimate_dec"],
        "zero_over_zero_point_ordering_flag": z00["bounds_ordered_l_le_point_le_u"],
        "pos_over_zero_point": str(z50["empirical_ratio_point_estimate_dec"]),
        "pos_over_zero_point_ordering_flag": z50["bounds_ordered_l_le_point_le_u"],
        "passed": r11_m1_ok,
    })

    # 19. R16-M2: Exact arbitrary-precision integer floor `n_eff = floor(n / deff)` via
    #     `Fraction(n) // Fraction(deff)` — eliminates 80-digit Decimal rounding down for huge
    #     admitted counts such as `n = 10**80 + 1, deff = 1 -> exact 10**80 + 1`!
    n_huge = 10 ** 80 + 1
    r_huge_u = exact_component_probability_ratio_upper(
        0, n_huge, Decimal("0.025"), (Decimal("1.0"),), deff=Decimal("1.0"), prec=80
    )
    r_huge_p = exact_paired_vehicle_ratio_bounds(
        0, n_huge, 100, 100, alpha_treated=Decimal("0.025"), alpha_veh=Decimal("0.025"), deff=Decimal("1.000"), prec=80
    )
    r_huge_d2 = exact_component_probability_ratio_upper(
        0, 2 * (10 ** 80) + 2, Decimal("0.025"), (Decimal("1.0"),), deff=Decimal("2.0"), prec=80
    )
    r_huge_d15 = exact_component_probability_ratio_upper(
        0, 3 * (10 ** 80) + 3, Decimal("0.025"), (Decimal("1.0"),), deff=Decimal("1.5"), prec=80
    )
    sub_ulp_deff = Decimal("1.00000000000000001")
    r_huge_sub = exact_component_probability_ratio_upper(
        0, n_huge, Decimal("0.025"), (Decimal("1.0"),), deff=sub_ulp_deff, prec=80
    )
    exp_sub_eff = int(Fraction(n_huge) // Fraction(sub_ulp_deff))
    r16_m2_ok = bool(
        r_huge_u["n_treated_eff"] == n_huge
        and r_huge_p["n_treated_eff"] == n_huge
        and r_huge_d2["n_treated_eff"] == n_huge
        and r_huge_d15["n_treated_eff"] == 2 * (10 ** 80) + 2
        and r_huge_sub["n_treated_eff"] == exp_sub_eff
        and r_huge_sub["exact_directional_confidence_certified"] is False
    )
    checks.append({
        "test": "r16_m2_exact_integer_floor_n_eff_for_huge_counts_10pow80_plus_1",
        "n_10pow80_plus_1_deff1_exact_match": bool(r_huge_u["n_treated_eff"] == n_huge),
        "n_2e80_plus_2_deff2_exact_match": bool(r_huge_d2["n_treated_eff"] == n_huge),
        "n_3e80_plus_3_deff1p5_exact_match": bool(r_huge_d15["n_treated_eff"] == 2 * (10 ** 80) + 2),
        "sub_ulp_deff_exact_rational_floor_match": bool(r_huge_sub["n_treated_eff"] == exp_sub_eff),
        "passed": r16_m2_ok,
    })

    # 20. R17-B2: Provably outward-conservative upper-enclosed standard-normal 95% quantile z_{0.95}
    #     (80-digit Phi(z) > 0.95 -> tail 1 - Phi(z) < 0.05 strictly, while old 1.6448536269514722
    #     and 1.6448536269514726 strictly under-cover!) AND upward-rounded IEEE-754 float64 native
    #     solver vascular scaling on Sol's exact sub-ULP positive-SE example (1.097, SE=1e-20, df=5)
    #     plus 1.2067 + SE=1e-20 under BOTH clean and hostile Decimal contexts!
    p95_d = Decimal("0.95")
    phi_z_dec = _exact_standard_normal_cdf_dec(MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95_DEC, prec=80)
    phi_z_f64 = _exact_standard_normal_cdf_dec(Decimal.from_float(MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95), prec=80)
    phi_z_str = _exact_standard_normal_cdf_dec(Decimal(str(MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95)), prec=80)
    phi_old_722 = _exact_standard_normal_cdf_dec(Decimal.from_float(1.6448536269514722), prec=80)
    phi_old_726 = _exact_standard_normal_cdf_dec(Decimal.from_float(1.6448536269514726), prec=80)

    t5_upper_d = Decimal.from_float(exact_student_t_one_sided_95(5))
    with _clean_dec_ctx(60, ROUND_CEILING):
        sol_u95_t5_d = Decimal("1.097") + t5_upper_d * Decimal("1e-20")
        sol_u95_ks_d = Decimal("1.097") + MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95_DEC * Decimal("1e-20")
        sol_u95_12067_d = Decimal("1.2067") + t5_upper_d * Decimal("1e-20")

    sc_det_1097, eff_det_1097 = _compute_conservative_upper_float64_vasc_scale(Decimal("1.097"), 1.097, Decimal("1.097"))
    sc_det_12067, eff_det_12067 = _compute_conservative_upper_float64_vasc_scale(Decimal("1.2067"), 1.2067, Decimal("1.2067"))
    sc_t5_1097, eff_t5_1097 = _compute_conservative_upper_float64_vasc_scale(sol_u95_t5_d, 1.097, Decimal("1.097"))
    sc_ks_1097, eff_ks_1097 = _compute_conservative_upper_float64_vasc_scale(sol_u95_ks_d, 1.097, Decimal("1.097"))
    sc_t5_12067, eff_t5_12067 = _compute_conservative_upper_float64_vasc_scale(sol_u95_12067_d, 1.2067, Decimal("1.2067"))

    hostile_r17_ok = True
    with localcontext(Context(prec=4, rounding=ROUND_FLOOR, Emin=-2, Emax=100, traps=[decimal.Inexact])):
        try:
            sc_h, eff_h = _compute_conservative_upper_float64_vasc_scale(sol_u95_t5_d, 1.097, Decimal("1.097"))
            phi_h = _exact_standard_normal_cdf_dec(MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95_DEC, prec=80)
            if sc_h != sc_t5_1097 or eff_h != eff_t5_1097 or phi_h != phi_z_dec:
                hostile_r17_ok = False
        except Exception:
            hostile_r17_ok = False

    r17_b2_dec_ok = bool(
        phi_z_dec > p95_d
        and phi_z_f64 > p95_d
        and phi_z_str > p95_d
        and phi_old_722 < p95_d
        and phi_old_726 < p95_d
        and sc_det_1097 == 1.0
        and sc_det_12067 == 1.0
        and sc_t5_1097 > 1.0
        and Fraction(sc_t5_1097) >= Fraction(sol_u95_t5_d) / Fraction(Decimal("1.097"))
        and Fraction(eff_t5_1097) >= Fraction(sol_u95_t5_d)
        and sc_ks_1097 > 1.0
        and Fraction(sc_ks_1097) >= Fraction(sol_u95_ks_d) / Fraction(Decimal("1.097"))
        and Fraction(eff_ks_1097) >= Fraction(sol_u95_ks_d)
        and sc_t5_12067 > 1.0
        and Fraction(sc_t5_12067) >= Fraction(sol_u95_12067_d) / Fraction(Decimal("1.2067"))
        and Fraction(eff_t5_12067) >= Fraction(sol_u95_12067_d)
        and hostile_r17_ok
    )
    checks.append({
        "test": "r17_b2_known_sigma_z95_strict_upper_enclosure_and_upward_float64_solver_scale",
        "z95_dec_strictly_above_0p95": bool(phi_z_dec > p95_d),
        "z95_float64_strictly_above_0p95": bool(phi_z_f64 > p95_d),
        "old_1p6448536269514722_undercovers": bool(phi_old_722 < p95_d),
        "old_1p6448536269514726_undercovers": bool(phi_old_726 < p95_d),
        "sub_ulp_t5_1p097_scale_f64": sc_t5_1097,
        "sub_ulp_t5_1p097_eff_ocr_f64": eff_t5_1097,
        "sub_ulp_t5_1p2067_scale_f64": sc_t5_12067,
        "hostile_decimal_context_immune": hostile_r17_ok,
        "passed": r17_b2_dec_ok,
    })

    passed_n = sum(1 for c in checks if c["passed"])
    return {
        "total_checks": len(checks),
        "passed_checks": passed_n,
        "all_passed": passed_n == len(checks),
        "checks": checks,
    }


def run_adversarial_contract_tests(openislet_root: Path | None = None) -> Dict[str, Any]:
    resolved_root = openislet_root.resolve() if openislet_root is not None else _resolve_roots(None, None)[0]
    cases: List[Dict[str, Any]] = []

    def _record(
        name: str,
        expected_verdict: str,
        payload: Dict[str, Any],
        expected_token: str | None = None,
        *,
        store_path: Path | None = None,
    ):
        res = evaluate_wholegraft_gate0v_and_stress_ap1903(
            payload,
            trusted_qualification_store=store_path,
            openislet_root=resolved_root,
        )
        ok = res["verdict"] == expected_verdict
        if expected_token is not None:
            all_msgs = res["hard_stops"] + res["holds"]
            ok = ok and any(expected_token in m for m in all_msgs)
        cases.append({
            "case": name,
            "expected_verdict": expected_verdict,
            "actual_verdict": res["verdict"],
            "expected_token": expected_token,
            "hard_stops": res["hard_stops"][:3],
            "holds": res["holds"][:3],
            "passed": ok,
        })
        return res

    # 1. Clean 3-pathogen x 5-lineage + 5-regime BANK_QUALIFICATION -> PASS_WHOLEGRAFT_BANK_QUALIFICATION (B6)
    _record("clean_bank_qualification_twostage_pass", "PASS_WHOLEGRAFT_BANK_QUALIFICATION", build_passing_reference_payload(openislet_root=resolved_root))

    # 2. Reconciled non-zero viral-negative survivors (2==2 on high-input beta arm clearing 4-log) -> PASS_WHOLEGRAFT_BANK_QUALIFICATION
    p_rec_nz = build_passing_reference_payload(openislet_root=resolved_root)
    p_rec_nz["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["ap1903_72h_viable_survivors_k"] = 2
    p_rec_nz["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["post_ap1903_viable_survivors_total_n"] = 2
    p_rec_nz["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["survivors_scored_n"] = 2
    reconcile_fixture_per_unit_counts(p_rec_nz)
    _record("reconciled_nonzero_viral_negative_survivors_passes", "PASS_WHOLEGRAFT_BANK_QUALIFICATION", _seal(p_rec_nz))

    # 2B. Survivor reconciliation regression: unreconciled 72h survivors (0) vs infected-arm viable survivors (3) -> HOLD!
    p_unrec = build_passing_reference_payload(openislet_root=resolved_root)
    p_unrec["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["ap1903_72h_viable_survivors_k"] = 0
    p_unrec["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["post_ap1903_viable_survivors_total_n"] = 3
    p_unrec["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["survivors_scored_n"] = 3
    _record("unreconciled_72h_vs_infected_survivors_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_unrec), "ALIQUOT_SURVIVOR_COUNT_MISMATCH")

    # 2C. B4 + R06-B1 Exact <= 0.050 Bonferroni union-bound budgets across 24h, 72h, E1, Direct E2 & Indirect E2,
    #     with release-authorizing PASS restricted strictly to DIRECT_INFECTED_VEHICLE_DENOMINATOR and
    #     indirect-only marginal mode strictly held as CONDITIONAL_INDIRECT_DIAGNOSTIC_ONLY_UNVERIFIED_SURVIVAL_INEQUALITY!
    p_dir_e2 = build_passing_reference_payload(use_direct_infected_veh_survivor_mode=True, openislet_root=resolved_root)
    res_dir_e2 = evaluate_wholegraft_gate0v_and_stress_ap1903(p_dir_e2, openislet_root=resolved_root)
    res_ind_e2 = evaluate_wholegraft_gate0v_and_stress_ap1903(
        build_passing_reference_payload(use_direct_infected_veh_survivor_mode=False, openislet_root=resolved_root),
        openislet_root=resolved_root,
    )
    ind_per = res_ind_e2["stress_ap1903_regimes"]["active_or_persistent_cvb4_infection"]["lineages"]["pericyte"]
    dir_per = res_dir_e2["stress_ap1903_regimes"]["active_or_persistent_cvb4_infection"]["lineages"]["pericyte"]
    b_ok = bool(
        res_dir_e2["verdict"] == "PASS_WHOLEGRAFT_BANK_QUALIFICATION"
        and dir_per["infected_cell_escape_mode"] == "DIRECT_INFECTED_VEHICLE_DENOMINATOR"
        and dir_per["estimand2_release_authorizing_eligible"] is True
        and res_ind_e2["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        and "HOLD_INDIRECT_CONDITIONAL_ESCAPE_UNSUPPORTED_FOR_RELEASE" in res_ind_e2["holds"]
        and ind_per["infected_cell_escape_mode"] == "CONDITIONAL_INDIRECT_DIAGNOSTIC_ONLY_UNVERIFIED_SURVIVAL_INEQUALITY"
        and ind_per["estimand2_release_authorizing_eligible"] is False
        and Decimal(ind_per["bonferroni_alpha_budget_24h"]["union_bound_sum"]) <= Decimal("0.050")
        and Decimal(ind_per["bonferroni_alpha_budget_72h"]["union_bound_sum"]) <= Decimal("0.050")
        and Decimal(ind_per["estimand1_bonferroni_alpha_budget"]["union_bound_sum"]) <= Decimal("0.050")
        and Decimal(ind_per["estimand2_bonferroni_alpha_budget"]["union_bound_sum"]) == Decimal("0.050")
        and Decimal(dir_per["estimand2_bonferroni_alpha_budget"]["union_bound_sum"]) == Decimal("0.050")
        and ind_per["estimand2_bonferroni_alpha_budget"]["alpha_veh"] == "0.015"
        and ind_per["estimand2_bonferroni_alpha_budget"]["alpha_prev"] == "0.015"
        and ind_per["estimand2_bonferroni_alpha_budget"]["alpha_eta"] == "0.005"
        and ind_per["estimand2_bonferroni_alpha_budget"]["alpha_escape"] == "0.015"
        and dir_per["estimand2_bonferroni_alpha_budget"]["alpha_inf_veh"] == "0.025"
        and dir_per["estimand2_bonferroni_alpha_budget"]["alpha_eta"] == "0.005"
        and dir_per["estimand2_bonferroni_alpha_budget"]["alpha_escape"] == "0.020"
    )
    cases.append({
        "case": "b4_r06_b1_bonferroni_budgets_direct_pass_and_indirect_diagnostic_hold",
        "expected_verdict": "DIRECT_PASS_INDIRECT_HOLD_ALL_BUDGETS_LE_0P050",
        "actual_verdict": "DIRECT_PASS_INDIRECT_HOLD_ALL_BUDGETS_LE_0P050" if b_ok else f"FAILED({res_dir_e2['verdict']},{res_ind_e2['verdict']})",
        "expected_token": "HOLD_INDIRECT_CONDITIONAL_ESCAPE_UNSUPPORTED_FOR_RELEASE",
        "hard_stops": [],
        "holds": res_ind_e2["holds"][:3],
        "passed": b_ok,
    })

    # 3. Lot-binding tamper: payload_sha256 mismatch -> HOLD
    p_tamper = build_passing_reference_payload(openislet_root=resolved_root)
    p_tamper["lot_id"] = "LOT-TAMPERED-999"
    _record("payload_sha256_tamper_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", p_tamper, "MISMATCHED_PAYLOAD_SHA256")

    # 3B. B2 Unregistered product_variant_id rejected fail-closed!
    p_unreg = build_passing_reference_payload(product_variant_id="ISLET1_DESIGN_A_LEAD", openislet_root=resolved_root)
    _record("b2_unregistered_product_variant_id_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", p_unreg, "UNREGISTERED_PRODUCT_VARIANT_ID")

    # 3C. B2 Canonical TYK2_PE product declaring TYK2_WT genotype rejected!
    p_tyk2_confl = build_passing_reference_payload(
        product_variant_id="ISLET1_A4_ARM1B_TYK2_PE",
        antiviral_genotype_stratum="TYK2_WT__IFIH1_WT_OR_A946T",
        openislet_root=resolved_root,
    )
    _record("b2_tyk2_pe_product_declaring_wt_genotype_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", p_tyk2_confl, "GENOTYPE_CONFLICTS_WITH_CANONICAL_PRODUCT_DEFINITION")

    # 4. B2 Canonical ectopic CD46_WT arms (IIP-0041 ABX side-contract, Design Y 11-TU) WITHOUT addendum -> HOLD
    for pv in (
        "ABX_L2_v2_CD64T_CD46WT_COMP",
        "ISLET1_Y_FULLSTACK_V2_B2M_11TU",
    ):
        p_cd46_no = build_passing_reference_payload(
            product_variant_id=pv,
            ectopic_receptors=["CD46_WT"],
            include_cd46_addendum=False,
            openislet_root=resolved_root,
        )
        _record(f"ectopic_cd46_without_addendum_held_{pv.lower()}", "HOLD_INCOMPLETE_OR_UNDERPOWERED", p_cd46_no, "CD46_VIRAL_ADDENDUM")

    # 4A-D1b. Canonical autologous D1b-Auto L1B CD46_WT comparator on its canonical AUTOLOGOUS_D1B_PROCESS_QUAL tier
    with tempfile.TemporaryDirectory() as td_cd46_d1b:
        d1b_cd46_store = Path(td_cd46_d1b) / "d1b_cd46_store.json"
        d1b_cd46_rec = build_authenticated_process_qualification_record(
            product_variant_id="ISLET1_D1_AUTO_V2_L1B_CIITA_CD64T_CD46WT_COMPARATOR",
            process_qual_id="PROCQUAL-D1B-L1B-CD46",
        )
        write_record_to_trusted_qualification_store(d1b_cd46_store, d1b_cd46_rec, category="process_qualifications")
        p_d1b_cd46_no = build_passing_reference_payload(
            product_variant_id="ISLET1_D1_AUTO_V2_L1B_CIITA_CD64T_CD46WT_COMPARATOR",
            qualification_tier="AUTOLOGOUS_D1B_PROCESS_QUAL",
            process_qualification_ref_sha256=d1b_cd46_rec["sha256"],
            ectopic_receptors=["CD46_WT"],
            include_cd46_addendum=False,
            openislet_root=resolved_root,
        )
        _record(
            "ectopic_cd46_without_addendum_held_islet1_d1_auto_v2_l1b_ciita_cd64t_cd46wt_comparator",
            "HOLD_INCOMPLETE_OR_UNDERPOWERED",
            p_d1b_cd46_no,
            "CD46_VIRAL_ADDENDUM",
            store_path=d1b_cd46_store,
        )
        p_d1b_cd46_ok = build_passing_reference_payload(
            product_variant_id="ISLET1_D1_AUTO_V2_L1B_CIITA_CD64T_CD46WT_COMPARATOR",
            qualification_tier="AUTOLOGOUS_D1B_PROCESS_QUAL",
            process_qualification_ref_sha256=d1b_cd46_rec["sha256"],
            ectopic_receptors=["CD46_WT"],
            include_cd46_addendum=True,
            openislet_root=resolved_root,
        )
        _record(
            "ectopic_cd46_autologous_d1b_with_completed_addendum_passes",
            "PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL",
            p_d1b_cd46_ok,
            store_path=d1b_cd46_store,
        )

    # 4B. B2+B5+R04-B4 Canonical CD55/CFH comparators route strictly to CD55_FULL_LENGTH ONLY and verify per-strain x 5-lineage blocks!
    pv_cfh = "ISLET1_Y_FULLSTACK_V2_CD55_CFH_COMPARATOR"
    pv_abx_cfh = "ABX_L2_v2_CD64T_CFH_CD55_COMP"
    implied_cfh = _implied_ectopic_receptors_for_product(pv_cfh, openislet_root=resolved_root)
    implied_abx_cfh = _implied_ectopic_receptors_for_product(pv_abx_cfh, openislet_root=resolved_root)
    p_cfh_ok = build_passing_reference_payload(
        product_variant_id=pv_cfh,
        ectopic_receptors=["CD55_FULL_LENGTH"],
        include_cd46_addendum=False,
        include_cd55_addendum=True,
        openislet_root=resolved_root,
    )
    res_cfh_ok = evaluate_wholegraft_gate0v_and_stress_ap1903(p_cfh_ok, openislet_root=resolved_root)
    cd55_sr = (res_cfh_ok.get("cd55_addendum_results") or {}).get("strain_results") or {}
    cfh_route_ok = bool(
        implied_cfh == {"CD55_FULL_LENGTH"}
        and implied_abx_cfh == {"CD55_FULL_LENGTH"}
        and "CD46_WT" not in implied_cfh
        and res_cfh_ok["verdict"] == "PASS_WHOLEGRAFT_BANK_QUALIFICATION"
        and res_cfh_ok["ectopic_viral_receptors_evaluated"] == ["CD55_FULL_LENGTH"]
        and res_cfh_ok["cd55_addendum_results"]["passed"] is True
        and set(cd55_sr.keys()) == set(CD55_REQUIRED_ECHOVIRUS_STRAINS)
        and all(
            cd55_sr[sid]["passed"] is True and set(cd55_sr[sid]["lineage_results"].keys()) == set(GRAFT_LINEAGES)
            for sid in CD55_REQUIRED_ECHOVIRUS_STRAINS
        )
    )
    cases.append({
        "case": "live_cd55_cfh_comparator_canonical_routing_and_powered_addendum",
        "expected_verdict": "PASS_CD55_ONLY_POWERED_PER_STRAIN_5LINEAGE",
        "actual_verdict": "PASS_CD55_ONLY_POWERED_PER_STRAIN_5LINEAGE" if cfh_route_ok else f"FAIL({res_cfh_ok['verdict']},{res_cfh_ok['holds'][:2]})",
        "expected_token": None,
        "hard_stops": res_cfh_ok["hard_stops"][:2],
        "holds": res_cfh_ok["holds"][:2],
        "passed": cfh_route_ok,
    })

    # 4C. B5 / R04-B4 Underpowered per-strain per-lineage CD55 denominator (k=0, n=500 on echovirus_11 pericyte) MUST HOLD!
    p_cd55_lown = copy.deepcopy(p_cfh_ok)
    p_cd55_lown["cd55_tropic_echovirus_addendum"]["strain_results"]["echovirus_11"]["day28_persistence_by_lineage"]["pericyte"]["cells_screened_n"] = 500
    _record("b5_cd55_addendum_underpowered_denominator_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_cd55_lown), "CD55_UNDERPOWERED_ECHOVIRUS_DENOMINATOR_ECHOVIRUS_11_PERICYTE")

    # 4D. R04-B4 Legacy aggregate-only CD55 block (no per-strain strain_results) MUST fail closed (HOLD)!
    p_cd55_agg = copy.deepcopy(p_cfh_ok)
    p_cd55_agg["cd55_tropic_echovirus_addendum"] = {
        "echovirus_strain_panel": list(CD55_REQUIRED_ECHOVIRUS_STRAINS),
        "echovirus_titer_72h_log10_pfu_u95": "1.35",
        "echovirus_day14_log10_reduction_l95": "3.80",
        "echovirus_day28_supernatant_pfu_ml": "0",
        "echovirus_day28_assay_volume_ml": "2.0",
        "echovirus_day28_lod_pfu_ml": "0.5",
        "echovirus_persistence_confirmed_k": 0,
        "echovirus_cells_screened_per_lineage_min_n": 16000,
        "protocol_evidence_sha256": _valid_digest("cd55_legacy_agg"),
    }
    _record("r04_b4_cd55_legacy_aggregate_only_block_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_cd55_agg), "CD55_MISSING_PER_STRAIN_RESULTS_AGGREGATE_ONLY_REJECTED")

    # 4E. R04-B4 Missing echovirus_11 strain block MUST fail closed (HOLD)!
    p_cd55_no_e11 = copy.deepcopy(p_cfh_ok)
    del p_cd55_no_e11["cd55_tropic_echovirus_addendum"]["strain_results"]["echovirus_11"]
    _record("r04_b4_cd55_missing_echovirus11_strain_block_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_cd55_no_e11), "CD55_MISSING_STRAIN_BLOCK_ECHOVIRUS_11")

    # 4F. R04-B4 Confirmed persistence k=1 on echovirus_11 pericyte -> FAIL_HARD_STOP!
    p_cd55_k1 = copy.deepcopy(p_cfh_ok)
    p_cd55_k1["cd55_tropic_echovirus_addendum"]["strain_results"]["echovirus_11"]["day28_persistence_by_lineage"]["pericyte"]["confirmed_k"] = 1
    _record("r04_b4_cd55_echovirus11_pericyte_k1_hard_stop", "FAIL_HARD_STOP", _seal(p_cd55_k1), "CD55_ECHOVIRUS_PERSISTENCE_DETECTED_ECHOVIRUS_11_PERICYTE_K_1")

    # 5. Ectopic CD46_WT allogeneic arm (Design Y 11-TU) WITH completed strain-specific addendum -> PASS_WHOLEGRAFT_BANK_QUALIFICATION
    p_cd46_ok = build_passing_reference_payload(
        product_variant_id="ISLET1_Y_FULLSTACK_V2_B2M_11TU",
        ectopic_receptors=["CD46_WT"],
        include_cd46_addendum=True,
        openislet_root=resolved_root,
    )
    _record("ectopic_cd46_with_completed_addendum_passes", "PASS_WHOLEGRAFT_BANK_QUALIFICATION", p_cd46_ok)

    # 6. Gate 0V-A vacuity fixed — zero induction (0.0 across markers) MUST FAIL_HARD_STOP
    p_0va_zero = build_passing_reference_payload(openislet_root=resolved_root)
    for mk in GATE0V_A_REQUIRED_ISG_MARKERS:
        p_0va_zero["gate0v_a_poly_ic_sensing"]["lineage_isg_fold_induction"]["beta"][mk] = "0.0"
    _record("gate0v_a_zero_induction_fails_hard_stop", "FAIL_HARD_STOP", _seal(p_0va_zero), "INSUFFICIENT_ISG_INDUCTION_BETA")

    # 7. Gate 0V-A wrong dose (100 ng/mL != fixed 500 ng/mL) -> HOLD
    p_0va_dose = build_passing_reference_payload(openislet_root=resolved_root)
    p_0va_dose["gate0v_a_poly_ic_sensing"]["poly_ic_dose_ng_ml"] = "100"
    _record("gate0v_a_non500_dose_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_0va_dose), "DOSE_MUST_BE_EXACT_500_NG_ML")

    # 8. Unconfirmed Stage-1 screen hits (sorted < screen_positive) -> HOLD
    p_unconf = build_passing_reference_payload(openislet_root=resolved_root)
    p_unconf["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["day28_persistence_by_lineage"]["pericyte"]["stage2_sorted_for_confirmation_n"] = 1
    _record("twostage_unconfirmed_screen_hit_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_unconf), "UNCONFIRMED_STAGE1_HITS")

    # 9. B3 Exact true Clopper-Pearson U95 <= 0.15% negative-control boundary!
    #    20/20,000 -> U95 = 0.145277% <= 0.15% -> PASS; 21/20,000 -> U95 = 0.151167% > 0.15% -> HOLD!
    p_fpr_20 = build_passing_reference_payload(openislet_root=resolved_root)
    p_fpr_20["gate0v_b_infectious_challenge"]["pathogens"]["cvb3"]["day28_persistence_by_lineage"]["alpha"]["uninfected_ctrl_fp_k"] = 20
    reconcile_fixture_per_unit_counts(p_fpr_20)
    _record("b3_neg_ctrl_true_u95_boundary_20_of_20000_passes", "PASS_WHOLEGRAFT_BANK_QUALIFICATION", _seal(p_fpr_20))

    p_fpr_21 = build_passing_reference_payload(openislet_root=resolved_root)
    p_fpr_21["gate0v_b_infectious_challenge"]["pathogens"]["cvb3"]["day28_persistence_by_lineage"]["alpha"]["uninfected_ctrl_fp_k"] = 21
    reconcile_fixture_per_unit_counts(p_fpr_21)
    _record("b3_neg_ctrl_true_u95_boundary_21_of_20000_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_fpr_21), "UNINFECTED_CTRL_FPR_U95_EXCEEDS_0P15PCT")

    p_ctrl_n = build_passing_reference_payload(openislet_root=resolved_root)
    p_ctrl_n["gate0v_b_infectious_challenge"]["pathogens"]["cvb3"]["day28_persistence_by_lineage"]["alpha"]["uninfected_ctrl_scored_n"] = 19999
    reconcile_fixture_per_unit_counts(p_ctrl_n)
    _record("uninfected_ctrl_n_below_20000_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_ctrl_n), "UNDERPOWERED_UNINFECTED_FPR_CTRL")

    # 10. Latent HCMV reactivation outgrowth > 0 despite VP1/IE1 protein k==0 -> FAIL_HARD_STOP
    p_lat = build_passing_reference_payload(openislet_root=resolved_root)
    p_lat["gate0v_b_infectious_challenge"]["pathogens"]["hcmv"]["day28_latent_and_defective_genome_arm"]["reactivation_7d_outgrowth_pfu_ml"] = "1.5"
    _record("hcmv_latent_reactivation_hard_stop", "FAIL_HARD_STOP", _seal(p_lat), "HCMV_LATENT_REACTIVATION_OUTGROWTH")

    # 10B. B5 HCMV missing UL55 target or wrong ddpcr_target_panel -> HOLD!
    p_no_ul55 = build_passing_reference_payload(openislet_root=resolved_root)
    del p_no_ul55["gate0v_b_infectious_challenge"]["pathogens"]["hcmv"]["day28_latent_and_defective_genome_arm"]["ddpcr_targets"]["UL55"]
    _record("b5_hcmv_missing_ul55_ddpcr_target_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_no_ul55), "MISSING_REQUIRED_DDPCR_TARGET_HCMV_UL55")

    p_bad_panel = build_passing_reference_payload(openislet_root=resolved_root)
    p_bad_panel["gate0v_b_infectious_challenge"]["pathogens"]["hcmv"]["day28_latent_and_defective_genome_arm"]["ddpcr_target_panel"] = "UNVERIFIED_PANEL"
    _record("b5_hcmv_wrong_ddpcr_target_panel_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_bad_panel), "INVALID_OR_MISSING_DDPCR_TARGET_PANEL_HCMV")

    # 11. CVB 5'-deletion ddPCR positive event -> FAIL_HARD_STOP
    p_def = build_passing_reference_payload(openislet_root=resolved_root)
    p_def["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["day28_latent_and_defective_genome_arm"]["ddpcr_positive_events_k"] = 1
    p_def["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["day28_latent_and_defective_genome_arm"]["ddpcr_targets"]["CVB_5PRIME_DELETION_POS_RNA"]["k"] = 1
    _record("cvb_5prime_deletion_ddpcr_hard_stop", "FAIL_HARD_STOP", _seal(p_def), "LATENT_OR_DEFECTIVE_GENOME_DETECTED_CVB4_E2")

    # 12. Lineage-unassigned fraction > 5% -> HOLD, AND B5 reconciliation mismatch -> HOLD, AND B5 unassigned positive -> FAIL_HARD_STOP!
    p_unass = build_passing_reference_payload(openislet_root=resolved_root)
    p_unass["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["lineage_unassigned_cells_n"] = 6000
    p_unass["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["total_viable_cells_acquired_n"] = 86000
    p_unass["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["unassigned_fraction_viral_readout"]["unassigned_cells_screened_n"] = 6000
    _record("lineage_unassigned_gt_5pct_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_unass), "LINEAGE_UNASSIGNED_EXCEEDS_5PCT")

    p_unrec_lin = build_passing_reference_payload(openislet_root=resolved_root)
    p_unrec_lin["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["total_viable_cells_acquired_n"] = 100000  # 80000 + 2400 != 100000!
    _record("b5_lineage_accounting_reconciliation_mismatch_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_unrec_lin), "LINEAGE_ACCOUNTING_RECONCILIATION_MISMATCH")

    p_unass_pos = build_passing_reference_payload(openislet_root=resolved_root)
    p_unass_pos["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["unassigned_fraction_viral_readout"] = {
        "unassigned_cells_screened_n": 2400,
        "stage1_screen_positive_k": 1,
        "stage2_sorted_for_confirmation_n": 1,
        "stage2_confirmed_infectious_k": 1,
    }
    _record("b5_unassigned_fraction_confirmed_viral_positive_hard_stop", "FAIL_HARD_STOP", _seal(p_unass_pos), "CONFIRMED_VIRAL_POSITIVE_UNASSIGNED_CVB4_E2_K_1")

    # 13. Viral caspase blockade (caspase-9/3 fold = 1.4 < 5.0 in HCMV-infected arm) -> FAIL_HARD_STOP
    p_casp = build_passing_reference_payload(openislet_root=resolved_root)
    p_casp["gate0v_kill_stress_ap1903"]["active_or_persistent_hcmv_infection"]["plvap_iec"]["caspase9_3_activity_fold_over_vehicle"] = "1.4"
    _record("hcmv_viral_caspase_blockade_hard_stop", "FAIL_HARD_STOP", _seal(p_casp), "VIRAL_CASPASE_BLOCKADE_REQUIRES_NON_CASPASE_BACKUP_SWITCH")

    # 14. Bare self-attested L95 scalar without raw counts -> HOLD
    p_bare = build_passing_reference_payload(openislet_root=resolved_root)
    del p_bare["gate0v_kill_stress_ap1903"]["normoxia_baseline"]["beta"]["ap1903_24h_input_n"]
    p_bare["gate0v_kill_stress_ap1903"]["normoxia_baseline"]["beta"]["kill_24h_pct_l95"] = "99.95"
    _record("bare_self_attested_kill_l95_rejected", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_bare), "RAW_24H_COUNTS_REQUIRED")

    # 15. survivors_scored_n < post_ap1903_viable_survivors_total_n mismatch -> HOLD
    p_surv_mm = build_passing_reference_payload(openislet_root=resolved_root)
    p_surv_mm["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["ap1903_72h_viable_survivors_k"] = 2
    p_surv_mm["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["post_ap1903_viable_survivors_total_n"] = 2
    p_surv_mm["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["survivors_scored_n"] = 1
    _record("survivors_scored_mismatch_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_surv_mm), "SURVIVORS_SCORED_MISMATCH")

    # 16. Estimand 2 direct conditional infected-at-risk denominator underpowered despite huge total input -> HOLD
    p_cond_low = build_passing_reference_payload(openislet_root=resolved_root)
    p_cond_low["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["pericyte"]["pretreat_infected_veh_survivor_n"] = 2
    _record("estimand2_conditional_infected_underpowered_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_cond_low), "ESTIMAND2_CONDITIONAL_INFECTED_TOO_SMALL")

    # 17. Missing Day-28 assay volume / coarse LOD -> HOLD
    p_lod = build_passing_reference_payload(openislet_root=resolved_root)
    p_lod["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["day28_supernatant_lod_pfu_ml"] = "10.0"
    _record("coarse_day28_lod_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_lod), "COARSE_DAY28_ASSAY_LOD")

    # 18. Missing evidence SHA-256 digest for CXADR genotyping -> HOLD
    p_nodig = build_passing_reference_payload(openislet_root=resolved_root)
    p_nodig["cxadr_locus_genotyping_evidence_sha256"] = "0" * 64
    _record("trivial_evidence_sha256_rejected", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_nodig), "MISSING_CXADR_GENOTYPING_EVIDENCE_SHA256")

    # 19. Hard stop preserved even when separate power check ALSO fails -> FAIL_HARD_STOP
    p_hs_and_hold = build_passing_reference_payload(openislet_root=resolved_root)
    p_hs_and_hold["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["day28_persistence_by_lineage"]["pericyte"]["stage2_confirmed_infectious_k"] = 1
    p_hs_and_hold["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["day28_persistence_by_lineage"]["beta"]["cells_scored_n"] = 500
    _record("hard_stop_preserved_over_power_hold", "FAIL_HARD_STOP", _seal(p_hs_and_hold), "CONFIRMED_VIRAL_POSITIVE_CVB4_E2_PERICYTE_K_1")

    # 20. B1 + B6 + R05-B1 Operational tier split with INDEPENDENT EXTERNAL TRUSTED QUALIFICATION STORE
    #     requiring a verified original JSON-object archived BANK_QUALIFICATION payload in BOTH store layouts!
    with tempfile.TemporaryDirectory() as td:
        store_json = Path(td) / "trusted_qual_registry.json"
        store_dir = Path(td) / "trusted_qual_dir"
        bank_payload_mcb01 = build_passing_reference_payload(
            lot_id="BANK-MCB01-001",
            mcb_id="MCB-ISLET1-A-001",
            product_variant_id="ISLET1_A4_ARM1B",
            qualification_tier="BANK_QUALIFICATION",
            openislet_root=resolved_root,
        )
        bank_rec = build_authenticated_bank_qualification_record(
            mcb_id="MCB-ISLET1-A-001",
            product_variant_id="ISLET1_A4_ARM1B",
            bank_lot_id="BANK-MCB01-001",
            bank_payload_sha256=bank_payload_mcb01["payload_sha256"],
        )
        write_record_to_trusted_qualification_store(
            store_json, bank_rec, category="bank_qualifications", archived_payload=bank_payload_mcb01
        )
        write_record_to_trusted_qualification_store(
            store_dir, bank_rec, category="bank_qualifications", archived_payload=bank_payload_mcb01
        )

        # 20A. LOT_RELEASE_SURROGATE verified via external trusted store (both registry JSON and directory store) -> PASS
        p_lot_surr = build_passing_reference_payload(
            product_variant_id="ISLET1_A4_ARM1B",
            qualification_tier="LOT_RELEASE_SURROGATE",
            bridged_mcb_qualification_sha256=bank_rec["sha256"],
            openislet_root=resolved_root,
        )
        _record("b1_b6_lot_release_surrogate_via_external_trusted_store_passes", "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE", p_lot_surr, store_path=store_json)
        _record("r05_b1_lot_release_surrogate_via_file_backed_dir_store_with_archive_passes", "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE", p_lot_surr, store_path=store_dir)

        # 20A-R05-1..4. R05-B1: Absent (None/missing) AND non-object (list/str/int) archived bank payloads MUST
        # fail closed with HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD and archived_bank_payload_verified=False
        # in BOTH embedded-dict registry JSON store AND file-backed directory store!
        reg_no_arch = Path(td) / "reg_absent_archive.json"
        write_record_to_trusted_qualification_store(reg_no_arch, bank_rec, category="bank_qualifications", archived_payload=None)
        res_reg_absent = evaluate_wholegraft_gate0v_and_stress_ap1903(
            p_lot_surr, trusted_qualification_store=reg_no_arch, openislet_root=resolved_root
        )
        cases.append({
            "case": "r05_b1_registry_store_absent_archived_bank_payload_held",
            "expected_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
            "actual_verdict": res_reg_absent["verdict"],
            "expected_token": "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD",
            "hard_stops": res_reg_absent["hard_stops"][:3],
            "holds": res_reg_absent["holds"][:4],
            "archived_bank_payload_verified": res_reg_absent["lot_binding"]["prior_qualification_authentication"]["archived_bank_payload_verified"],
            "passed": bool(
                res_reg_absent["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
                and "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD" in res_reg_absent["holds"]
                and res_reg_absent["lot_binding"]["prior_qualification_authentication"]["archived_bank_payload_verified"] is False
            ),
        })

        reg_nonobj_ok = True
        for tag, bad_val in (("none", None), ("list", ["not", "an", "object"]), ("str", "not-a-dict"), ("int", 42)):
            reg_bad = Path(td) / f"reg_nonobj_{tag}.json"
            doc_bad = {
                "schema_version": TRUSTED_STORE_SCHEMA_VERSION,
                "store_authority_id": "OPENISLET_QA_RELEASE_BOARD_V1",
                "bank_qualifications": {bank_rec["sha256"]: bank_rec},
                "process_qualifications": {},
                "archived_payloads": {bank_rec["bank_payload_sha256"]: bad_val},
            }
            reg_bad.write_text(json.dumps(doc_bad), encoding="utf-8")
            r_nb = evaluate_wholegraft_gate0v_and_stress_ap1903(
                p_lot_surr, trusted_qualification_store=reg_bad, openislet_root=resolved_root
            )
            if not (
                r_nb["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
                and "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD" in r_nb["holds"]
                and r_nb["lot_binding"]["prior_qualification_authentication"]["archived_bank_payload_verified"] is False
            ):
                reg_nonobj_ok = False
        cases.append({
            "case": "r05_b1_registry_store_nonobject_archived_bank_payloads_held",
            "expected_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
            "actual_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED" if reg_nonobj_ok else "UNEXPECTED_PASS_OR_MISSING_TOKEN",
            "expected_token": "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD",
            "hard_stops": [],
            "holds": ["HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD"],
            "passed": reg_nonobj_ok,
        })

        dir_no_arch = Path(td) / "dir_absent_archive"
        write_record_to_trusted_qualification_store(dir_no_arch, bank_rec, category="bank_qualifications", archived_payload=None)
        res_dir_absent = evaluate_wholegraft_gate0v_and_stress_ap1903(
            p_lot_surr, trusted_qualification_store=dir_no_arch, openislet_root=resolved_root
        )
        cases.append({
            "case": "r05_b1_dir_store_absent_archived_bank_payload_held",
            "expected_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
            "actual_verdict": res_dir_absent["verdict"],
            "expected_token": "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD",
            "hard_stops": res_dir_absent["hard_stops"][:3],
            "holds": res_dir_absent["holds"][:4],
            "archived_bank_payload_verified": res_dir_absent["lot_binding"]["prior_qualification_authentication"]["archived_bank_payload_verified"],
            "passed": bool(
                res_dir_absent["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
                and "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD" in res_dir_absent["holds"]
                and res_dir_absent["lot_binding"]["prior_qualification_authentication"]["archived_bank_payload_verified"] is False
            ),
        })

        dir_nonobj_ok = True
        for tag, bad_val in (("none", None), ("list", ["not", "an", "object"]), ("str", "not-a-dict"), ("int", 42)):
            dir_bad = Path(td) / f"dir_nonobj_{tag}"
            write_record_to_trusted_qualification_store(dir_bad, bank_rec, category="bank_qualifications", archived_payload=None)
            arch_dir_bad = dir_bad / "archived_payloads"
            arch_dir_bad.mkdir(parents=True, exist_ok=True)
            (arch_dir_bad / f"{bank_rec['bank_payload_sha256']}.json").write_text(
                json.dumps(bad_val), encoding="utf-8"
            )
            r_db = evaluate_wholegraft_gate0v_and_stress_ap1903(
                p_lot_surr, trusted_qualification_store=dir_bad, openislet_root=resolved_root
            )
            if not (
                r_db["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
                and "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD" in r_db["holds"]
                and r_db["lot_binding"]["prior_qualification_authentication"]["archived_bank_payload_verified"] is False
            ):
                dir_nonobj_ok = False
        cases.append({
            "case": "r05_b1_dir_store_nonobject_archived_bank_payloads_held",
            "expected_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
            "actual_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED" if dir_nonobj_ok else "UNEXPECTED_PASS_OR_MISSING_TOKEN",
            "expected_token": "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD",
            "hard_stops": [],
            "holds": ["HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD"],
            "passed": dir_nonobj_ok,
        })

        # 20B. B1 Self-attested inline bank-qual record WITHOUT --trusted-qualification-store MUST HOLD!
        p_self_att = build_passing_reference_payload(
            product_variant_id="ISLET1_A4_ARM1B",
            qualification_tier="LOT_RELEASE_SURROGATE",
            bridged_mcb_qualification_record=bank_rec,
            openislet_root=resolved_root,
        )
        _record("b1_self_attested_inline_bank_qual_without_external_store_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", p_self_att, "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", store_path=None)

        # 20C. B1 Failing bank-qual record in trusted store -> HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE!
        fail_bank_rec = build_authenticated_bank_qualification_record(
            mcb_id="MCB-ISLET1-A-001",
            product_variant_id="ISLET1_A4_ARM1B",
            bank_lot_id="BANK-FAIL",
            bank_payload_sha256=_valid_digest("bank_fail"),
            verdict="HOLD_COMPOSITE_RELEASE",
        )
        write_record_to_trusted_qualification_store(store_json, fail_bank_rec, category="bank_qualifications")
        p_lot_wrong_verdict = build_passing_reference_payload(
            product_variant_id="ISLET1_A4_ARM1B",
            qualification_tier="LOT_RELEASE_SURROGATE",
            bridged_mcb_qualification_sha256=fail_bank_rec["sha256"],
            openislet_root=resolved_root,
        )
        _record("b1_failing_bank_qual_in_trusted_store_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", p_lot_wrong_verdict, "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", store_path=store_json)

        # 20D. B6 Adverse supplemental HCMV reactivation submitted on LOT_RELEASE_SURROGATE MUST FAIL_HARD_STOP!
        p_surr_adv_hcmv = copy.deepcopy(p_lot_surr)
        p_surr_adv_hcmv["gate0v_b_infectious_challenge"]["pathogens"]["hcmv"] = {
            "day28_latent_and_defective_genome_arm": {"reactivation_7d_outgrowth_pfu_ml": "2.0"}
        }
        _record("b6_lot_release_surrogate_adverse_supplemental_hcmv_hard_stop", "FAIL_HARD_STOP", _seal(p_surr_adv_hcmv), "SUPPLEMENTAL_HCMV_LATENT_REACTIVATION_OUTGROWTH", store_path=store_json)

        # 20E. B6 Adverse supplemental infected-arm viral caspase blockade submitted on LOT_RELEASE_SURROGATE MUST FAIL_HARD_STOP!
        p_surr_adv_casp = copy.deepcopy(p_lot_surr)
        p_surr_adv_casp["gate0v_kill_stress_ap1903"]["active_or_persistent_hcmv_infection"] = {
            "plvap_iec": {"caspase9_3_activity_fold_over_vehicle": "1.2"}
        }
        _record("b6_lot_release_surrogate_adverse_supplemental_caspase_hard_stop", "FAIL_HARD_STOP", _seal(p_surr_adv_casp), "SUPPLEMENTAL_VIRAL_CASPASE_BLOCKADE", store_path=store_json)

        # 20E-R03-1. R03-B1: Supplemental stress arm with valid raw 24-h survivors > n_eff_24h MUST FAIL_HARD_STOP (never skipped!)
        p_bank_ref_r03 = build_passing_reference_payload(openislet_root=resolved_root)
        p_surr_gt_neff_24 = copy.deepcopy(p_lot_surr)
        er_arm_24 = copy.deepcopy(p_bank_ref_r03["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"]["beta"])
        er_arm_24["ap1903_24h_viable_survivors_k"] = 7000  # valid <= 10,000 input, exceeds n_eff_24h (~5,285)!
        p_surr_gt_neff_24["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"] = {"beta": er_arm_24}
        reconcile_fixture_per_unit_counts(p_surr_gt_neff_24)
        _record("r03_b1_surrogate_supplemental_24h_survivors_gt_neff_hard_stop", "FAIL_HARD_STOP", _seal(p_surr_gt_neff_24), "SUPPLEMENTAL_AP1903_24H_KILL_BELOW_99P9PCT", store_path=store_json)

        # 20E-R03-2. R03-B1: Supplemental stress arm with valid raw 72-h survivors > n_eff_72h MUST FAIL_HARD_STOP (never skipped!)
        p_surr_gt_neff_72 = copy.deepcopy(p_lot_surr)
        er_arm_72 = copy.deepcopy(p_bank_ref_r03["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"]["alpha"])
        er_arm_72["ap1903_72h_viable_survivors_k"] = 70000  # valid <= 100,000 input, exceeds n_eff_72h (~50,852)!
        p_surr_gt_neff_72["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"] = {"alpha": er_arm_72}
        reconcile_fixture_per_unit_counts(p_surr_gt_neff_72)
        _record("r03_b1_surrogate_supplemental_72h_survivors_gt_neff_hard_stop", "FAIL_HARD_STOP", _seal(p_surr_gt_neff_72), "SUPPLEMENTAL_AP1903_72H_PK_KILL_BELOW_4LOG10", store_path=store_json)

        # 20E-R03-3. R03-B1: Supplemental infected stress arm with bad dual spike calibration (eta < 0.80) MUST HOLD (never ignored!)
        p_surr_bad_cal = copy.deepcopy(p_lot_surr)
        cvb_arm_cal = copy.deepcopy(p_bank_ref_r03["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["pericyte"])
        cvb_arm_cal["fragile_infected_spike_detected_k"] = 10  # 10/24 -> eta << 0.80
        p_surr_bad_cal["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"] = {"pericyte": cvb_arm_cal}
        reconcile_fixture_per_unit_counts(p_surr_bad_cal)
        _record("r03_b1_surrogate_supplemental_bad_calibrant_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_surr_bad_cal), "SUPPLEMENTAL_CALIBRANT_BELOW_0P80", store_path=store_json)

        # 20E-R03-4. R03-B1: Supplemental infected arm with missing raw counts / aliquot linkage MUST HOLD (never ignored!)
        p_surr_miss_cnt = copy.deepcopy(p_lot_surr)
        er_arm_miss = copy.deepcopy(p_bank_ref_r03["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"]["delta"])
        del er_arm_miss["ap1903_24h_input_n"]
        p_surr_miss_cnt["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"] = {"delta": er_arm_miss}
        _record("r03_b1_surrogate_supplemental_missing_raw_counts_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_surr_miss_cnt), "SUPPLEMENTAL_RAW_24H_COUNTS_REQUIRED", store_path=store_json)

        # 20E-R03-5. R03-B1: Supplemental clean passing raw-count arm in LOT_RELEASE_SURROGATE passes cleanly!
        p_surr_clean_sup = copy.deepcopy(p_lot_surr)
        p_surr_clean_sup["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"] = {
            "beta": copy.deepcopy(p_bank_ref_r03["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"]["beta"])
        }
        _record("r03_b1_surrogate_supplemental_clean_complete_arm_passes", "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE", _seal(p_surr_clean_sup), store_path=store_json)

        # 20F. B1+B6 AUTOLOGOUS_D1B_PROCESS_QUAL via external trusted store -> PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL!
        proc_rec = build_authenticated_process_qualification_record(
            product_variant_id="ISLET1_D1_AUTO_V2_L1A_CIITA_CD64T_IL1RN",
            process_qual_id="PROCQUAL-D1B-L1A-001",
        )
        write_record_to_trusted_qualification_store(store_json, proc_rec, category="process_qualifications")
        p_auto = build_passing_reference_payload(
            product_variant_id="ISLET1_D1_AUTO_V2_L1A_CIITA_CD64T_IL1RN",
            qualification_tier="AUTOLOGOUS_D1B_PROCESS_QUAL",
            process_qualification_ref_sha256=proc_rec["sha256"],
            openislet_root=resolved_root,
        )
        _record("b1_b6_autologous_d1b_process_qual_via_trusted_store_passes", "PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL", p_auto, store_path=store_json)

        # 20F-R03-1. R03-B1: AUTOLOGOUS_D1B_PROCESS_QUAL supplemental infected arm with survivors > n_eff MUST FAIL_HARD_STOP!
        p_auto_gt_neff = copy.deepcopy(p_auto)
        cvb_auto_arm = copy.deepcopy(p_bank_ref_r03["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"])
        cvb_auto_arm["ap1903_24h_viable_survivors_k"] = 7000
        p_auto_gt_neff["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"] = {"beta": cvb_auto_arm}
        reconcile_fixture_per_unit_counts(p_auto_gt_neff)
        _record("r03_b1_autologous_supplemental_survivors_gt_neff_hard_stop", "FAIL_HARD_STOP", _seal(p_auto_gt_neff), "SUPPLEMENTAL_AP1903_24H_KILL_BELOW_99P9PCT", store_path=store_json)

        # 20F-R03-2. R03-B1: AUTOLOGOUS_D1B_PROCESS_QUAL supplemental infected arm with underpowered direct Estimand 2 MUST HOLD!
        p_auto_e2_low = copy.deepcopy(p_auto)
        hcmv_auto_arm = copy.deepcopy(p_bank_ref_r03["gate0v_kill_stress_ap1903"]["active_or_persistent_hcmv_infection"]["pericyte"])
        hcmv_auto_arm["pretreat_infected_veh_survivor_n"] = 2
        p_auto_e2_low["gate0v_kill_stress_ap1903"]["active_or_persistent_hcmv_infection"] = {"pericyte": hcmv_auto_arm}
        _record("r03_b1_autologous_supplemental_underpowered_estimand2_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_auto_e2_low), "SUPPLEMENTAL_ESTIMAND2_CONDITIONAL_INFECTED_TOO_SMALL", store_path=store_json)

        # 20G. B6 AUTOLOGOUS_D1B_PROCESS_QUAL with edited genotype enforces non-inferiority (never silently skipped!)
        p_auto_geno_miss = build_passing_reference_payload(
            product_variant_id="ISLET1_D1_AUTO_V2_L1A_CIITA_CD64T_IL1RN",
            qualification_tier="AUTOLOGOUS_D1B_PROCESS_QUAL",
            process_qualification_ref_sha256=proc_rec["sha256"],
            antiviral_genotype_stratum="TYK2_P1104A_HET__IFIH1_WT",
            openislet_root=resolved_root,
        )
        _record("b6_autologous_d1b_edited_genotype_with_noninf_passes", "PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL", p_auto_geno_miss, store_path=store_json)
        del p_auto_geno_miss["genotype_noninferiority_by_pathogen"]
        _record("b6_autologous_d1b_edited_genotype_missing_noninf_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_auto_geno_miss), "AUTOLOGOUS_MISSING_NONINFERIORITY", store_path=store_json)

        # 20H-R04-B1a. Allogeneic ISLET1_A4_ARM1B submitted on AUTOLOGOUS_D1B_PROCESS_QUAL EVEN WITH
        # matching external QA process-qual record MUST fail closed (HOLD_INAPPLICABLE_QUALIFICATION_TIER_FOR_PRODUCT_FAMILY)!
        bad_allo_proc_rec = build_authenticated_process_qualification_record(
            product_variant_id="ISLET1_A4_ARM1B",
            process_qual_id="PROCQUAL-MISAPPLIED-ARM1B",
        )
        write_record_to_trusted_qualification_store(store_json, bad_allo_proc_rec, category="process_qualifications")
        p_allo_on_auto = build_passing_reference_payload(
            product_variant_id="ISLET1_A4_ARM1B",
            qualification_tier="AUTOLOGOUS_D1B_PROCESS_QUAL",
            process_qualification_ref_sha256=bad_allo_proc_rec["sha256"],
            openislet_root=resolved_root,
        )
        _record(
            "r04_b1_allogeneic_arm1b_on_autologous_tier_with_matching_qa_record_held",
            "HOLD_INCOMPLETE_OR_UNDERPOWERED",
            p_allo_on_auto,
            "HOLD_INAPPLICABLE_QUALIFICATION_TIER_FOR_PRODUCT_FAMILY",
            store_path=store_json,
        )

        # 20H-R04-B1b. Autologous D1b submitted on BANK_QUALIFICATION or LOT_RELEASE_SURROGATE MUST fail closed!
        p_d1b_on_bank = build_passing_reference_payload(
            product_variant_id="ISLET1_D1_AUTO_V2_L1A_CIITA_CD64T_IL1RN",
            qualification_tier="BANK_QUALIFICATION",
            openislet_root=resolved_root,
        )
        _record(
            "r04_b1_autologous_d1b_on_bank_qualification_tier_held",
            "HOLD_INCOMPLETE_OR_UNDERPOWERED",
            p_d1b_on_bank,
            "HOLD_INAPPLICABLE_QUALIFICATION_TIER_FOR_PRODUCT_FAMILY",
            store_path=store_json,
        )

        # 20I-R04-B2. Exact Round-03 counterexample: external QA bank record omitting antiviral_genotype_stratum
        # + archived WT bank payload used for protective-LOF current lot -> MUST HOLD!
        archived_wt_bank = build_passing_reference_payload(
            lot_id="BANK-WT-ARCH-001",
            mcb_id="MCB-ISLET1-A-001",
            product_variant_id="ISLET1_A4_ARM1B",
            qualification_tier="BANK_QUALIFICATION",
            antiviral_genotype_stratum="TYK2_WT__IFIH1_WT_OR_A946T",
            openislet_root=resolved_root,
        )
        no_geno_bank_rec = build_authenticated_bank_qualification_record(
            mcb_id="MCB-ISLET1-A-001",
            product_variant_id="ISLET1_A4_ARM1B",
            bank_lot_id="BANK-WT-ARCH-001",
            bank_payload_sha256=archived_wt_bank["payload_sha256"],
        )
        no_geno_bank_rec.pop("antiviral_genotype_stratum", None)
        no_geno_bank_rec["sha256"] = compute_canonical_qualification_artifact_sha256(no_geno_bank_rec)
        write_record_to_trusted_qualification_store(
            store_json, no_geno_bank_rec, category="bank_qualifications", archived_payload=archived_wt_bank
        )
        p_lof_from_nogeno = build_passing_reference_payload(
            lot_id="LOT-LOF-SURR-001",
            mcb_id="MCB-ISLET1-A-001",
            product_variant_id="ISLET1_A4_ARM1B",
            qualification_tier="LOT_RELEASE_SURROGATE",
            bridged_mcb_qualification_sha256=no_geno_bank_rec["sha256"],
            antiviral_genotype_stratum="TYK2_WT__IFIH1_PROTECTIVE_LOF",
            openislet_root=resolved_root,
        )
        _record(
            "r04_b2_missing_bank_stratum_with_archived_wt_for_lof_lot_held",
            "HOLD_INCOMPLETE_OR_UNDERPOWERED",
            p_lof_from_nogeno,
            "HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM",
            store_path=store_json,
        )

        # 20I-R04-B2b. Bank record claiming LOF while archived bank payload is WT -> MUST HOLD!
        mismatched_arch_rec = build_authenticated_bank_qualification_record(
            mcb_id="MCB-ISLET1-A-001",
            product_variant_id="ISLET1_A4_ARM1B",
            bank_lot_id="BANK-WT-ARCH-001",
            bank_payload_sha256=archived_wt_bank["payload_sha256"],
            antiviral_genotype_stratum="TYK2_WT__IFIH1_PROTECTIVE_LOF",
        )
        write_record_to_trusted_qualification_store(
            store_json, mismatched_arch_rec, category="bank_qualifications", archived_payload=archived_wt_bank
        )
        p_lof_from_mismatched_arch = build_passing_reference_payload(
            lot_id="LOT-LOF-SURR-002",
            mcb_id="MCB-ISLET1-A-001",
            product_variant_id="ISLET1_A4_ARM1B",
            qualification_tier="LOT_RELEASE_SURROGATE",
            bridged_mcb_qualification_sha256=mismatched_arch_rec["sha256"],
            antiviral_genotype_stratum="TYK2_WT__IFIH1_PROTECTIVE_LOF",
            openislet_root=resolved_root,
        )
        _record(
            "r04_b2_bank_record_stratum_contradicts_archived_wt_payload_held",
            "HOLD_INCOMPLETE_OR_UNDERPOWERED",
            p_lof_from_mismatched_arch,
            "HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM",
            store_path=store_json,
        )

    # 20J-R04-B3a. Extra non-canonical lineage key inside required stress regime (clean counts -> HOLD; adverse counts -> FAIL_HARD_STOP!)
    p_extra_lin_clean = build_passing_reference_payload(openislet_root=resolved_root)
    p_extra_lin_clean["gate0v_kill_stress_ap1903"]["hypoxia_1pct_plus_cytokines"]["ductal_noncanonical"] = copy.deepcopy(
        p_extra_lin_clean["gate0v_kill_stress_ap1903"]["hypoxia_1pct_plus_cytokines"]["beta"]
    )
    _record(
        "r04_b3_extra_noncanonical_lineage_key_clean_counts_held",
        "HOLD_INCOMPLETE_OR_UNDERPOWERED",
        _seal(p_extra_lin_clean),
        "HOLD_UNRECOGNIZED_LINEAGE_KEY",
    )

    p_extra_lin_adv = copy.deepcopy(p_extra_lin_clean)
    p_extra_lin_adv["gate0v_kill_stress_ap1903"]["hypoxia_1pct_plus_cytokines"]["ductal_noncanonical"]["ap1903_24h_viable_survivors_k"] = 7000
    reconcile_fixture_per_unit_counts(p_extra_lin_adv)
    _record(
        "r04_b3_extra_noncanonical_lineage_key_adverse_raw_counts_hard_stop",
        "FAIL_HARD_STOP",
        _seal(p_extra_lin_adv),
        "AP1903_24H_KILL_BELOW_99P9PCT_HYPOXIA_1PCT_PLUS_CYTOKINES_DUCTAL_NONCANONICAL",
    )

    # 20J-R04-B3b. Zero-killing arm paired with poorly surviving vehicle control (veh_24h_viable_n=50,
    # ap1903_24h_viable_survivors_k=10000) MUST preserve FAIL_HARD_STOP (NOT return HOLD-only)!
    p_zero_kill_low_veh = build_passing_reference_payload(openislet_root=resolved_root)
    p_zero_kill_low_veh["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"]["alpha"]["veh_24h_viable_n"] = 50
    p_zero_kill_low_veh["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"]["alpha"]["ap1903_24h_viable_survivors_k"] = 10000
    reconcile_fixture_per_unit_counts(p_zero_kill_low_veh)
    _record(
        "r04_b3_zero_killing_with_low_vehicle_survival_preserves_hard_stop",
        "FAIL_HARD_STOP",
        _seal(p_zero_kill_low_veh),
        "AP1903_24H_KILL_BELOW_99P9PCT_ER_STRESS_TG_OR_TM_ALPHA",
    )

    # 20J-R04-B3c. Extra non-canonical lineage key inside pathogen day28_persistence_by_lineage with k2=1 -> FAIL_HARD_STOP!
    p_extra_path_lin = build_passing_reference_payload(openislet_root=resolved_root)
    extra_path_entry = copy.deepcopy(p_extra_path_lin["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["day28_persistence_by_lineage"]["beta"])
    extra_path_entry["stage1_screen_positive_k"] = 1
    extra_path_entry["stage2_sorted_for_confirmation_n"] = 1
    extra_path_entry["stage2_confirmed_infectious_k"] = 1
    p_extra_path_lin["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["day28_persistence_by_lineage"]["ductal_noncanonical"] = extra_path_entry
    _record(
        "r04_b3_extra_noncanonical_pathogen_lineage_viral_pos_hard_stop",
        "FAIL_HARD_STOP",
        _seal(p_extra_path_lin),
        "CONFIRMED_VIRAL_POSITIVE_CVB4_E2_DUCTAL_NONCANONICAL_K_1",
    )

    # 21. R11-B3: Clustering design effect deff = 2.0 routes to HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE
    #     (and also flags reduced effective n INSUFFICIENT_DENOMINATOR diagnostically; exact_directional_confidence_certified=False)!
    p_deff = build_passing_reference_payload(openislet_root=resolved_root)
    p_deff["clustering_and_independence_spec"]["clustering_design_effect_deff"] = "2.0"
    r_deff_21 = _record(
        "clustering_deff_2p0_reduces_neff_held",
        "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE",
        _seal(p_deff),
        "INSUFFICIENT_DENOMINATOR",
    )
    if not (
        r_deff_21.get("exact_directional_confidence_certified") is False
        and r_deff_21.get("release_authorizing") is False
        and "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE" in r_deff_21.get("holds", [])
    ):
        cases[-1]["passed"] = False

    # 22. Exact 3-pathogen boundary (15,949 PASS vs 15,948 HOLD at 29/29)
    alpha_3p = _alpha_3pathogen_global_floor(prec=120)
    eta_3p_29 = exact_clopper_pearson_lower_calibrant(29, 29, alpha_3p, prec=80)
    n_3p_29 = min_n_for_zero_event_cap(Decimal("0.0005"), alpha_3p, eta_3p_29, prec=80)["min_n_pass"]
    p_3p_pass = build_passing_reference_payload(openislet_root=resolved_root)
    p_3p_pass["gate0v_b_infectious_challenge"]["pathogens"]["cvb3"]["day28_persistence_by_lineage"]["plvap_iec"]["cells_scored_n"] = n_3p_29
    reconcile_fixture_per_unit_counts(p_3p_pass)
    _record(f"exact_3pathogen_boundary_pass_n_{n_3p_29}", "PASS_WHOLEGRAFT_BANK_QUALIFICATION", _seal(p_3p_pass))

    p_3p_hold = build_passing_reference_payload(openislet_root=resolved_root)
    p_3p_hold["gate0v_b_infectious_challenge"]["pathogens"]["cvb3"]["day28_persistence_by_lineage"]["plvap_iec"]["cells_scored_n"] = n_3p_29 - 1
    reconcile_fixture_per_unit_counts(p_3p_hold)
    _record(f"exact_3pathogen_boundary_hold_n_{n_3p_29 - 1}", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_3p_hold), "INSUFFICIENT_DENOMINATOR_CVB3_PLVAP_IEC")

    # 23. TYK2_P1104A_HET paired non-inferiority with >= 6 replicates passes, < 6 holds
    p_tyk2_ok = build_passing_reference_payload(
        antiviral_genotype_stratum="TYK2_P1104A_HET__IFIH1_WT",
        openislet_root=resolved_root,
    )
    _record("tyk2_het_noninferiority_n6_passes", "PASS_WHOLEGRAFT_BANK_QUALIFICATION", p_tyk2_ok)

    p_tyk2_lown = copy.deepcopy(p_tyk2_ok)
    p_tyk2_lown["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["paired_noninferiority_replicates_n"] = 2
    _record("tyk2_het_noninferiority_n2_held", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_tyk2_lown), "UNDERPOWERED_NONINFERIORITY_REPLICATES")

    # 24. Hostile ambient Decimal prec=4, ROUND_FLOOR, Inexact trap ENABLED on FULL evaluator!
    p_ctx = build_passing_reference_payload(openislet_root=resolved_root)
    res_clean = evaluate_wholegraft_gate0v_and_stress_ap1903(p_ctx, openislet_root=resolved_root)
    ctx_trapped = False
    res_polluted = None
    _clear_math_caches()
    with localcontext() as ctx:
        ctx.prec = 4
        ctx.rounding = ROUND_FLOOR
        ctx.traps[decimal.Inexact] = True
        try:
            res_polluted = evaluate_wholegraft_gate0v_and_stress_ap1903(p_ctx, openislet_root=resolved_root)
        except decimal.Inexact:
            ctx_trapped = True
    ctx_identical = (not ctx_trapped) and (json.dumps(res_clean, sort_keys=True) == json.dumps(res_polluted, sort_keys=True))
    cases.append({
        "case": "ambient_decimal_prec4_floor_inexact_trap_full_evaluator_immunity",
        "expected_verdict": "IDENTICAL_BYTE_EXACT_OUTPUT",
        "actual_verdict": "IDENTICAL_BYTE_EXACT_OUTPUT" if ctx_identical else f"DRIFT_OR_TRAP(trapped={ctx_trapped})",
        "expected_token": None,
        "hard_stops": [],
        "holds": [],
        "passed": ctx_identical,
    })

    # 25. Speculative CXADR KO True -> FAIL_HARD_STOP
    p_cx = build_passing_reference_payload(openislet_root=resolved_root)
    p_cx["cxadr_ko_present"] = True
    _record("speculative_cxadr_ko_barred", "FAIL_HARD_STOP", _seal(p_cx), "SPECULATIVE_CXADR_KO_BARRED")

    # 26. Raw 24-h AP1903 survivors causing kill_24h < 99.9% -> FAIL_HARD_STOP
    p_24f = build_passing_reference_payload(openislet_root=resolved_root)
    p_24f["gate0v_kill_stress_ap1903"]["hypoxia_1pct_plus_cytokines"]["alpha"]["ap1903_24h_viable_survivors_k"] = 30
    reconcile_fixture_per_unit_counts(p_24f)
    _record("raw_24h_kill_drop_below_99p9pct_hard_stop", "FAIL_HARD_STOP", _seal(p_24f), "AP1903_24H_KILL_BELOW_99P9PCT_HYPOXIA_1PCT_PLUS_CYTOKINES_ALPHA")

    # 27. rk = 0 fragile spike calibrant -> deterministic HOLD, zero crash
    p_rk0 = build_passing_reference_payload(openislet_root=resolved_root)
    p_rk0["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["day28_persistence_by_lineage"]["pericyte"]["fragile_infected_spike_detected_k"] = 0
    reconcile_fixture_per_unit_counts(p_rk0)
    _record("rk0_fragile_calibrant_deterministic_hold", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_rk0), "CALIBRANT_SENSITIVITY_BELOW_0P80_CVB4_E2_PERICYTE")

    # 28. Legacy beta-only payload rejected
    p_beta_only = build_passing_reference_payload(openislet_root=resolved_root)
    p_beta_only["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["day28_persistence_by_lineage"] = {
        "beta": p_beta_only["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["day28_persistence_by_lineage"]["beta"]
    }
    _record("legacy_beta_only_rejected", "HOLD_INCOMPLETE_OR_UNDERPOWERED", _seal(p_beta_only), "MISSING_LINEAGE_CVB4_E2_ALPHA")

    # ------------------------------------------------------------------
    # Round-06 Final-Closure Adversarial Regression Suite (B1-B4 & M2-M3)
    # ------------------------------------------------------------------
    # 29. R06-B1a: Indirect-only marginal conditional escape NEVER issues PASS -> HOLD_INDIRECT_CONDITIONAL_ESCAPE_UNSUPPORTED_FOR_RELEASE!
    p_ind_only = build_passing_reference_payload(use_direct_infected_veh_survivor_mode=False, openislet_root=resolved_root)
    _record(
        "r06_b1_indirect_only_conditional_escape_held_never_pass",
        "HOLD_INCOMPLETE_OR_UNDERPOWERED",
        p_ind_only,
        "HOLD_INDIRECT_CONDITIONAL_ESCAPE_UNSUPPORTED_FOR_RELEASE",
    )

    # 30. R06-B1b: Indirect-only marginal payload WITH conclusive adverse caspase blockade STILL emits FAIL_HARD_STOP!
    p_ind_adv = build_passing_reference_payload(use_direct_infected_veh_survivor_mode=False, openislet_root=resolved_root)
    p_ind_adv["gate0v_kill_stress_ap1903"]["active_or_persistent_hcmv_infection"]["plvap_iec"]["caspase9_3_activity_fold_over_vehicle"] = "1.2"
    _record(
        "r06_b1_indirect_only_with_adverse_caspase_preserves_hard_stop",
        "FAIL_HARD_STOP",
        _seal(p_ind_adv),
        "VIRAL_CASPASE_BLOCKADE_REQUIRES_NON_CASPASE_BACKUP_SWITCH",
    )

    # 31. R06-B2a & B2b: Exact component-probability ratio boundary in live Gate 0V evaluator:
    #     veh = 51/100, treated = 0/90402 -> u_ratio = 0.00010000201070... > 0.0001 -> HOLD!
    #     veh = 51/100, treated = 0/90404 -> u_ratio <= 0.0001 -> PASS!
    p_b2_hold = build_passing_reference_payload(openislet_root=resolved_root)
    arm_b2_h = p_b2_hold["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"]["alpha"]
    arm_b2_h["veh_72h_viable_n"] = 51
    arm_b2_h["veh_72h_input_n"] = 100
    arm_b2_h["ap1903_72h_input_n"] = 90402
    arm_b2_h["ap1903_72h_viable_survivors_k"] = 0
    reconcile_fixture_per_unit_counts(p_b2_hold)
    _record(
        "r06_b2_exact_component_ratio_veh51of100_0of90402_held",
        "HOLD_INCOMPLETE_OR_UNDERPOWERED",
        _seal(p_b2_hold),
        "72H_UNDERPOWERED_N_EFF_ER_STRESS_TG_OR_TM_ALPHA",
    )

    p_b2_pass = copy.deepcopy(p_b2_hold)
    p_b2_pass["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"]["alpha"]["ap1903_72h_input_n"] = 90404
    reconcile_fixture_per_unit_counts(p_b2_pass)
    _record(
        "r06_b2_exact_component_ratio_veh51of100_0of90404_passes",
        "PASS_WHOLEGRAFT_BANK_QUALIFICATION",
        _seal(p_b2_pass),
    )

    # 32. R06-B3a & B3b: Indeterminate straddling intervals under concurrent vehicle-control HOLD
    #     MUST return HOLD_INCOMPLETE_OR_UNDERPOWERED (NEVER FAIL_HARD_STOP and NEVER PASS!):
    #     (a) 24-h 1/5,000 vs 0.001 (L_ideal ≈ 5.06e-6 <= 0.001 < U_ideal ≈ 1.11e-3)
    #     (b) 72-h 1/20,000 vs 0.0001 (L_ideal ≈ 1.27e-6 <= 0.0001 < U_ideal ≈ 2.79e-4)
    p_strad_24 = build_passing_reference_payload(openislet_root=resolved_root)
    arm_s24 = p_strad_24["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"]["alpha"]
    arm_s24["veh_24h_viable_n"] = 50
    arm_s24["veh_24h_input_n"] = 1000
    arm_s24["ap1903_24h_input_n"] = 5000
    arm_s24["ap1903_24h_viable_survivors_k"] = 1
    reconcile_fixture_per_unit_counts(p_strad_24)
    _record(
        "r06_b3_24h_1of5000_straddling_under_low_veh_returns_hold_not_hard_stop",
        "HOLD_INCOMPLETE_OR_UNDERPOWERED",
        _seal(p_strad_24),
        "INDETERMINATE_INTERVAL_STRADDLING_CAP_UNDER_CONTROL_HOLD",
    )

    p_strad_72 = build_passing_reference_payload(openislet_root=resolved_root)
    arm_s72 = p_strad_72["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"]["delta"]
    arm_s72["veh_72h_viable_n"] = 40
    arm_s72["veh_72h_input_n"] = 1000
    arm_s72["ap1903_72h_input_n"] = 20000
    arm_s72["ap1903_72h_viable_survivors_k"] = 1
    reconcile_fixture_per_unit_counts(p_strad_72)
    _record(
        "r06_b3_72h_1of20000_straddling_under_low_veh_returns_hold_not_hard_stop",
        "HOLD_INCOMPLETE_OR_UNDERPOWERED",
        _seal(p_strad_72),
        "INDETERMINATE_INTERVAL_STRADDLING_CAP_UNDER_CONTROL_HOLD",
    )

    # 33. R06-B3c & B3d: Conclusively adverse counts under concurrent vehicle-control HOLD
    #     (L_ideal > cap!) MUST preserve FAIL_HARD_STOP:
    #     (c) 24-h 30/5,000 (L_ideal ≈ 0.00405 > 0.001) -> FAIL_HARD_STOP
    #     (d) 72-h 10/20,000 (L_ideal ≈ 0.00024 > 0.0001) -> FAIL_HARD_STOP
    p_conc_24 = copy.deepcopy(p_strad_24)
    p_conc_24["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"]["alpha"]["ap1903_24h_viable_survivors_k"] = 30
    reconcile_fixture_per_unit_counts(p_conc_24)
    _record(
        "r06_b3_24h_30of5000_conclusive_l_gt_cap_under_low_veh_hard_stop",
        "FAIL_HARD_STOP",
        _seal(p_conc_24),
        "AP1903_24H_KILL_BELOW_99P9PCT_ER_STRESS_TG_OR_TM_ALPHA",
    )

    p_conc_72 = copy.deepcopy(p_strad_72)
    p_conc_72["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"]["delta"]["ap1903_72h_viable_survivors_k"] = 10
    reconcile_fixture_per_unit_counts(p_conc_72)
    _record(
        "r06_b3_72h_10of20000_conclusive_l_gt_cap_under_low_veh_hard_stop",
        "FAIL_HARD_STOP",
        _seal(p_conc_72),
        "AP1903_72H_PK_KILL_BELOW_4LOG10_ER_STRESS_TG_OR_TM_DELTA",
    )

    # 34. R06-B4: Archived bank payload full canonical structure, self-digest, nested-identity reconciliation,
    #     and live Gate-0V re-verification across BOTH store layouts (embedded registry JSON & directory store)!
    with tempfile.TemporaryDirectory() as td_b4:
        td_b4_p = Path(td_b4)
        base_bank_p = build_passing_reference_payload(
            lot_id="BANK-R06B4-001",
            mcb_id="MCB-ISLET1-A-001",
            product_variant_id="ISLET1_A4_ARM1B",
            qualification_tier="BANK_QUALIFICATION",
            openislet_root=resolved_root,
        )

        def _check_bad_archive_both_layouts(tag: str, bad_arch: Dict[str, Any], rec_bank_sha: str, expected_subtoken: str | None = None) -> None:
            bad_rec = build_authenticated_bank_qualification_record(
                mcb_id="MCB-ISLET1-A-001",
                product_variant_id="ISLET1_A4_ARM1B",
                bank_lot_id="BANK-R06B4-001",
                bank_payload_sha256=rec_bank_sha,
            )
            p_surr_b4 = build_passing_reference_payload(
                lot_id="LOT-R06B4-SURR-001",
                mcb_id="MCB-ISLET1-A-001",
                product_variant_id="ISLET1_A4_ARM1B",
                qualification_tier="LOT_RELEASE_SURROGATE",
                bridged_mcb_qualification_sha256=bad_rec["sha256"],
                openislet_root=resolved_root,
            )
            reg_st = td_b4_p / f"reg_{tag}.json"
            reg_st.write_text(
                json.dumps({
                    "schema_version": TRUSTED_STORE_SCHEMA_VERSION,
                    "store_authority_id": "OPENISLET_QA_RELEASE_BOARD_V1",
                    "bank_qualifications": {bad_rec["sha256"]: bad_rec},
                    "process_qualifications": {},
                    "archived_payloads": {rec_bank_sha: bad_arch},
                }),
                encoding="utf-8",
            )
            dir_st = td_b4_p / f"dir_{tag}"
            write_record_to_trusted_qualification_store(dir_st, bad_rec, category="bank_qualifications", archived_payload=None)
            (dir_st / "archived_payloads").mkdir(parents=True, exist_ok=True)
            (dir_st / "archived_payloads" / f"{rec_bank_sha}.json").write_text(json.dumps(bad_arch), encoding="utf-8")

            both_ok = True
            last_holds: List[str] = []
            for st_layout in (reg_st, dir_st):
                r_l = evaluate_wholegraft_gate0v_and_stress_ap1903(
                    p_surr_b4, trusted_qualification_store=st_layout, openislet_root=resolved_root
                )
                last_holds = r_l["holds"]
                auth = r_l["lot_binding"]["prior_qualification_authentication"]
                if not (
                    r_l["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
                    and "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD" in r_l["holds"]
                    and auth.get("archived_bank_payload_verified") is False
                    and (expected_subtoken is None or any(expected_subtoken in h for h in r_l["holds"]))
                ):
                    both_ok = False
            cases.append({
                "case": f"r06_b4_both_store_layouts_{tag}_held",
                "expected_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
                "actual_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED" if both_ok else "UNEXPECTED_PASS_OR_MISSING_TOKEN",
                "expected_token": expected_subtoken or "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD",
                "hard_stops": [],
                "holds": last_holds[:4],
                "passed": both_ok,
            })

        # (i) Metadata-only stub archive
        stub_arch = {
            "lot_id": "BANK-R06B4-001",
            "mcb_id": "MCB-ISLET1-A-001",
            "product_variant_id": "ISLET1_A4_ARM1B",
            "qualification_tier": "BANK_QUALIFICATION",
            "antiviral_genotype_stratum": "TYK2_WT__IFIH1_WT_OR_A946T",
        }
        stub_sha = compute_canonical_lot_sha256(stub_arch)
        stub_arch["payload_sha256"] = stub_sha
        _check_bad_archive_both_layouts("metadata_only_stub_archive", stub_arch, stub_sha)

        # (ii) Tampered internal payload_sha256 self-digest on complete bank payload
        tampered_self_arch = copy.deepcopy(base_bank_p)
        tampered_self_sha = compute_canonical_lot_sha256(tampered_self_arch)
        tampered_self_arch["payload_sha256"] = hashlib.sha256(b"TAMPERED_SELF_DIGEST").hexdigest()
        _check_bad_archive_both_layouts(
            "tampered_internal_payload_sha256", tampered_self_arch, tampered_self_sha, "ARCHIVED_PAYLOAD_SELF_DIGEST_MISMATCH"
        )

        # (iii) Contradictory nested mcb_id inside composite bank archive
        contra_g0v = build_passing_reference_payload(
            lot_id="BANK-R06B4-001",
            mcb_id="MCB-CONTRADICTORY-999",
            product_variant_id="ISLET1_A4_ARM1B",
            qualification_tier="BANK_QUALIFICATION",
            openislet_root=resolved_root,
        )
        contra_comp = {
            "lot_id": "BANK-R06B4-001",
            "mcb_id": "MCB-ISLET1-A-001",
            "product_variant_id": "ISLET1_A4_ARM1B",
            "legacy_stage0_observations": {
                "current_lot_id": "BANK-R06B4-001",
                "mcb_id": "MCB-ISLET1-A-001",
                "product_variant_id": "ISLET1_A4_ARM1B",
                "obs_icasp9_log10_kill": 4.6,
                "obs_tp53_ppm1d_bcor_vaf": 0.0,
                "obs_mcb_effective_clonogenic_trials": 299573228.0,
                "obs_gate0v_day28_persistent_vp1_ie1_cells_scored": 5990.0,
            },
            "gate0v_wholegraft_payload": contra_g0v,
        }
        contra_comp_sha = compute_canonical_lot_sha256(contra_comp)
        contra_comp["payload_sha256"] = contra_comp_sha
        _check_bad_archive_both_layouts("contradictory_nested_mcb_id", contra_comp, contra_comp_sha)

        # (iii-b) Contradictory nested antiviral_genotype_stratum & tampered nested gate0v payload_sha256 inside composite archive
        contra_geno_comp = copy.deepcopy(contra_comp)
        contra_geno_comp["antiviral_genotype_stratum"] = "TYK2_WT__IFIH1_WT_OR_A946T"
        contra_geno_comp["gate0v_wholegraft_payload"] = build_passing_reference_payload(
            lot_id="BANK-R06B4-001",
            mcb_id="MCB-ISLET1-A-001",
            product_variant_id="ISLET1_A4_ARM1B",
            qualification_tier="BANK_QUALIFICATION",
            antiviral_genotype_stratum="TYK2_WT__IFIH1_PROTECTIVE_LOF",
            openislet_root=resolved_root,
        )
        contra_geno_sha = compute_canonical_lot_sha256(contra_geno_comp)
        contra_geno_comp["payload_sha256"] = contra_geno_sha
        _check_bad_archive_both_layouts(
            "contradictory_nested_genotype_stratum",
            contra_geno_comp,
            contra_geno_sha,
            "HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM",
        )

        tampered_nested_comp = copy.deepcopy(contra_comp)
        tampered_nested_g0v = copy.deepcopy(base_bank_p)
        tampered_nested_g0v["payload_sha256"] = hashlib.sha256(b"TAMPERED_NESTED_G0V_DIGEST").hexdigest()
        tampered_nested_comp["gate0v_wholegraft_payload"] = tampered_nested_g0v
        tampered_nested_sha = compute_canonical_lot_sha256(tampered_nested_comp)
        tampered_nested_comp["payload_sha256"] = tampered_nested_sha
        _check_bad_archive_both_layouts(
            "tampered_nested_gate0v_payload_sha256",
            tampered_nested_comp,
            tampered_nested_sha,
            "ARCHIVED_NESTED_GATE0V_SELF_DIGEST_MISMATCH",
        )

        # (iv) Structurally complete archived bank payload that FAILS BANK_QUALIFICATION (confirmed viral positive k2=1)
        failing_bank_arch = copy.deepcopy(base_bank_p)
        failing_bank_arch["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["day28_persistence_by_lineage"]["pericyte"]["stage2_confirmed_infectious_k"] = 1
        failing_bank_arch["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["day28_persistence_by_lineage"]["pericyte"]["stage2_sorted_for_confirmation_n"] = 2
        _seal(failing_bank_arch)
        _check_bad_archive_both_layouts(
            "structurally_complete_failing_bank_archive",
            failing_bank_arch,
            failing_bank_arch["payload_sha256"],
            "ARCHIVED_PAYLOAD_FAILED_LIVE_GATE0V_REVALIDATION",
        )

    # 35. R06-M2: CD55 two-strain result emits explicit detection_efficiency_assurance_level!
    cd55_assur_ok = bool(
        res_cfh_ok["cd55_addendum_results"].get("detection_efficiency_assurance_level")
        == "CONDITIONAL_ON_ASSUMED_MINIMUM_ETA_PENDING_LINKED_CALIBRANT_EVIDENCE"
        and all(
            res_cfh_ok["cd55_addendum_results"]["strain_results"][sid].get("detection_efficiency_assurance_level")
            == "CONDITIONAL_ON_ASSUMED_MINIMUM_ETA_PENDING_LINKED_CALIBRANT_EVIDENCE"
            for sid in CD55_REQUIRED_ECHOVIRUS_STRAINS
        )
    )
    cases.append({
        "case": "r06_m2_cd55_emits_explicit_detection_efficiency_assurance_level",
        "expected_verdict": "CONDITIONAL_ON_ASSUMED_MINIMUM_ETA_PENDING_LINKED_CALIBRANT_EVIDENCE",
        "actual_verdict": res_cfh_ok["cd55_addendum_results"].get("detection_efficiency_assurance_level"),
        "expected_token": None,
        "hard_stops": [],
        "holds": [],
        "passed": cd55_assur_ok,
    })

    # 36. R06-M3: Autologous process record helper defaults to PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL
    #     and rejects allogeneic PASS_WHOLEGRAFT_BANK_QUALIFICATION as underlying_gate0v_verdict!
    with tempfile.TemporaryDirectory() as td_m3:
        st_m3 = Path(td_m3) / "m3_store.json"
        default_proc = build_authenticated_process_qualification_record(
            product_variant_id="ISLET1_D1_AUTO_V2_L1A_CIITA_CD64T_IL1RN",
            process_qual_id="PROCQUAL-M3-DEFAULT",
        )
        bad_bank_proc = build_authenticated_process_qualification_record(
            product_variant_id="ISLET1_D1_AUTO_V2_L1A_CIITA_CD64T_IL1RN",
            process_qual_id="PROCQUAL-M3-ALLO-VERDICT",
            underlying_gate0v_verdict="PASS_WHOLEGRAFT_BANK_QUALIFICATION",
        )
        write_record_to_trusted_qualification_store(st_m3, default_proc, category="process_qualifications")
        write_record_to_trusted_qualification_store(st_m3, bad_bank_proc, category="process_qualifications")
        p_m3_bad = build_passing_reference_payload(
            product_variant_id="ISLET1_D1_AUTO_V2_L1A_CIITA_CD64T_IL1RN",
            qualification_tier="AUTOLOGOUS_D1B_PROCESS_QUAL",
            process_qualification_ref_sha256=bad_bank_proc["sha256"],
            openislet_root=resolved_root,
        )
        r_m3_bad = evaluate_wholegraft_gate0v_and_stress_ap1903(p_m3_bad, trusted_qualification_store=st_m3, openislet_root=resolved_root)
        m3_ok = bool(
            default_proc["underlying_gate0v_verdict"] == "PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL"
            and r_m3_bad["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
            and any("UNDERLYING_GATE0V_VERDICT_NOT_AUTOLOGOUS_PROCESS_QUAL_PASS" in h for h in r_m3_bad["holds"])
        )
        cases.append({
            "case": "r06_m3_autologous_process_qual_aligns_family_verdict_and_rejects_bank_pass",
            "expected_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
            "actual_verdict": r_m3_bad["verdict"],
            "expected_token": "UNDERLYING_GATE0V_VERDICT_NOT_AUTOLOGOUS_PROCESS_QUAL_PASS",
            "hard_stops": [],
            "holds": r_m3_bad["holds"][:3],
            "passed": m3_ok,
        })

    # ------------------------------------------------------------------
    # Round-07 Final-Closure Adversarial Regression Suite (B1, B2, M1, M2)
    # ------------------------------------------------------------------
    # 37. R07-B1: Standalone whole-graft-only bank archive is accepted ONLY when legacy_evaluator is None,
    #     and MUST fail closed when legacy_evaluator is active (composite clinical release mode) across BOTH
    #     store layouts (embedded-dict registry JSON AND file-backed directory store)!
    with tempfile.TemporaryDirectory() as td_r07_b1:
        td_r07_p = Path(td_r07_b1)
        plain_bank_p = build_passing_reference_payload(
            lot_id="BANK-R07B1-PLAIN-001",
            mcb_id="MCB-ISLET1-A-001",
            product_variant_id="ISLET1_A4_ARM1B",
            qualification_tier="BANK_QUALIFICATION",
            openislet_root=resolved_root,
        )
        plain_bank_rec = build_authenticated_bank_qualification_record(
            mcb_id="MCB-ISLET1-A-001",
            product_variant_id="ISLET1_A4_ARM1B",
            bank_lot_id="BANK-R07B1-PLAIN-001",
            bank_payload_sha256=plain_bank_p["payload_sha256"],
            antiviral_genotype_stratum=plain_bank_p["antiviral_genotype_stratum"],
        )
        reg_plain = td_r07_p / "r07_b1_plain_reg.json"
        dir_plain = td_r07_p / "r07_b1_plain_dir"
        write_record_to_trusted_qualification_store(reg_plain, plain_bank_rec, category="bank_qualifications", archived_payload=plain_bank_p)
        write_record_to_trusted_qualification_store(dir_plain, plain_bank_rec, category="bank_qualifications", archived_payload=plain_bank_p)
        p_surr_plain = build_passing_reference_payload(
            lot_id="LOT-R07B1-SURR-001",
            mcb_id="MCB-ISLET1-A-001",
            product_variant_id="ISLET1_A4_ARM1B",
            qualification_tier="LOT_RELEASE_SURROGATE",
            bridged_mcb_qualification_sha256=plain_bank_rec["sha256"],
            openislet_root=resolved_root,
        )

        standalone_both_ok = True
        for st_plain in (reg_plain, dir_plain):
            r_st = evaluate_wholegraft_gate0v_and_stress_ap1903(
                p_surr_plain, trusted_qualification_store=st_plain, openislet_root=resolved_root
            )
            auth_st = r_st["lot_binding"]["prior_qualification_authentication"]
            if not (
                r_st["verdict"] == "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE"
                and auth_st.get("archived_bank_payload_verified") is True
                and auth_st.get("archived_bank_payload_live_g0v_revalidation_passed") is True
                and auth_st.get("archived_bank_payload_live_legacy_revalidation_passed") is None
            ):
                standalone_both_ok = False
        cases.append({
            "case": "r07_b1_standalone_wholegraft_bank_archive_accepted_only_when_legacy_none",
            "expected_verdict": "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE",
            "actual_verdict": "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE" if standalone_both_ok else "UNEXPECTED_HOLD_OR_META",
            "expected_token": None,
            "hard_stops": [],
            "holds": [],
            "passed": standalone_both_ok,
        })

        def _mock_passing_legacy_eval(_obs: Dict[str, Any], **_kw: Any) -> Dict[str, Any]:
            return {
                "lot_release_readiness_tier": "READY_FOR_ENCAPSULATION_COMPLETE_STAGE0_EVIDENCE",
                "safety_kill_s9_triggered": False,
                "resolved_architecture_assignments": {"product_variant_id": "ISLET1_A4_ARM1B"},
            }

        composite_reject_both_ok = True
        last_comp_errs: List[str] = []
        for st_plain in (reg_plain, dir_plain):
            pq_ok_c, pq_errs_c, pq_meta_c = resolve_and_verify_trusted_bank_qualification(
                st_plain,
                expected_sha256=plain_bank_rec["sha256"],
                expected_mcb_id="MCB-ISLET1-A-001",
                expected_product_variant_id="ISLET1_A4_ARM1B",
                expected_genotype_stratum=plain_bank_p["antiviral_genotype_stratum"],
                openislet_root=resolved_root,
                hold_prefix="HOLD_COMPOSITE_PRIOR_BANK_QUAL",
                legacy_evaluator=_mock_passing_legacy_eval,
            )
            last_comp_errs = pq_errs_c
            if not (
                pq_ok_c is False
                and pq_meta_c.get("archived_bank_payload_verified") is False
                and pq_meta_c.get("archived_bank_payload_live_g0v_revalidation_passed") is True
                and pq_meta_c.get("archived_bank_payload_live_legacy_revalidation_passed") is False
                and "HOLD_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE" in pq_errs_c
                and "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD" in pq_errs_c
                and "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE" in pq_errs_c
            ):
                composite_reject_both_ok = False
        cases.append({
            "case": "r07_b1_plain_wholegraft_bank_archive_rejected_when_legacy_evaluator_active_both_layouts",
            "expected_verdict": "HOLD_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE",
            "actual_verdict": (
                "HOLD_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE"
                if composite_reject_both_ok
                else "UNEXPECTED_ACCEPT_OR_MISSING_TOKEN"
            ),
            "expected_token": "HOLD_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE",
            "hard_stops": [],
            "holds": last_comp_errs[:4],
            "passed": composite_reject_both_ok,
        })

    # 38. R07-B2: Strict published SAME_72H_ALIQUOT count reconciliation (closing undocumented PAIRED_HIGH_INPUT_ALIQUOT bypass!)
    #     (a) Matched same-aliquot counts -> PASS_WHOLEGRAFT_BANK_QUALIFICATION
    p_alq_match = build_passing_reference_payload(openislet_root=resolved_root)
    r_alq_match = _record("r07_b2_same_aliquot_matched_counts_passes", "PASS_WHOLEGRAFT_BANK_QUALIFICATION", p_alq_match)
    if (
        r_alq_match["stress_ap1903_regimes"]["active_or_persistent_cvb4_infection"]["lineages"]["beta"].get(
            "aliquot_count_reconciliation_verified"
        )
        is not True
    ):
        cases[-1]["passed"] = False

    #     (b) Mismatched same-aliquot input count -> HOLD_INCOMPLETE_OR_UNDERPOWERED
    p_alq_mm = build_passing_reference_payload(openislet_root=resolved_root)
    p_alq_mm["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["pre_ap1903_lineage_input_cells_n"] = (
        p_alq_mm["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["ap1903_72h_input_n"] + 5000
    )
    _record(
        "r07_b2_same_aliquot_mismatched_input_counts_held",
        "HOLD_INCOMPLETE_OR_UNDERPOWERED",
        _seal(p_alq_mm),
        "ALIQUOT_SURVIVOR_COUNT_MISMATCH",
    )

    #     (c) PAIRED_HIGH_INPUT_ALIQUOT with mismatched counts AND well-formed 64-hex digest -> HOLD (NEVER PASS!)
    p_paired_hi = build_passing_reference_payload(openislet_root=resolved_root)
    arm_phi = p_paired_hi["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]
    arm_phi["infected_surveillance_aliquot_linkage_mode"] = "PAIRED_HIGH_INPUT_ALIQUOT"
    arm_phi["paired_aliquot_linkage_evidence_sha256"] = _valid_digest("paired_high_input_well_formed_digest")
    arm_phi["ap1903_72h_input_n"] = 100000
    arm_phi["ap1903_72h_viable_survivors_k"] = 0
    arm_phi["pre_ap1903_lineage_input_cells_n"] = 5_141_940
    arm_phi["post_ap1903_viable_survivors_total_n"] = 2
    arm_phi["survivors_scored_n"] = 2
    _record(
        "r07_b2_paired_high_input_mismatched_counts_valid_digest_held_never_pass",
        "HOLD_INCOMPLETE_OR_UNDERPOWERED",
        _seal(p_paired_hi),
        "HOLD_NON_SAME_ALIQUOT_UNVERIFIED_COUNT_RECONCILIATION",
    )

    #     (d) PAIRED_HIGH_INPUT_ALIQUOT with valid 64-hex digest AND adverse escape -> preserves FAIL_HARD_STOP!
    p_paired_adv = copy.deepcopy(p_paired_hi)
    arm_phi_adv = p_paired_adv["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]
    arm_phi_adv["pre_ap1903_lineage_input_cells_n"] = 20000
    arm_phi_adv["post_ap1903_viable_survivors_total_n"] = 20
    arm_phi_adv["survivors_scored_n"] = 20
    reconcile_fixture_per_unit_counts(p_paired_adv)
    _record(
        "r07_b2_paired_high_input_with_adverse_escape_preserves_hard_stop",
        "FAIL_HARD_STOP",
        _seal(p_paired_adv),
        "AP1903_72H_INFECTED_ALIQUOT_SURVIVORS_EXCEED_CAP",
    )

    # 39. R07-M1: Zero-event straddling control-HOLD disposition at 24 h AND 72 h (0/1,000 gives L_ideal=0 <= cap < U_ideal=0.00368208!)
    p_zero_strad_24 = build_passing_reference_payload(openislet_root=resolved_root)
    arm_z24 = p_zero_strad_24["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"]["alpha"]
    arm_z24["veh_24h_viable_n"] = 50
    arm_z24["veh_24h_input_n"] = 1000
    arm_z24["ap1903_24h_input_n"] = 1000
    arm_z24["ap1903_24h_viable_survivors_k"] = 0
    reconcile_fixture_per_unit_counts(p_zero_strad_24)
    r_z24 = _record(
        "r07_m1_24h_0of1000_straddling_under_control_hold_emits_straddling_disposition",
        "HOLD_INCOMPLETE_OR_UNDERPOWERED",
        _seal(p_zero_strad_24),
        "HOLD_INDETERMINATE_INTERVAL_STRADDLING_CAP_UNDER_CONTROL_HOLD",
    )
    z24_det = r_z24["stress_ap1903_regimes"]["er_stress_tg_or_tm"]["lineages"]["alpha"]
    if not (
        z24_det.get("ideal_sveh_24h_adjudication") == "INDETERMINATE_INTERVAL_STRADDLING_CAP_UNDER_CONTROL_HOLD"
        and z24_det.get("recomputed_l_surv_24h_ideal_sveh_lower") == "0"
        and abs(float(z24_det.get("recomputed_u_surv_24h_ideal_sveh_upper", "0")) - 0.00368208) < 1e-6
    ):
        cases[-1]["passed"] = False

    p_zero_strad_72 = build_passing_reference_payload(openislet_root=resolved_root)
    arm_z72 = p_zero_strad_72["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"]["delta"]
    arm_z72["veh_72h_viable_n"] = 40
    arm_z72["veh_72h_input_n"] = 1000
    arm_z72["ap1903_72h_input_n"] = 1000
    arm_z72["ap1903_72h_viable_survivors_k"] = 0
    reconcile_fixture_per_unit_counts(p_zero_strad_72)
    r_z72 = _record(
        "r07_m1_72h_0of1000_straddling_under_control_hold_emits_straddling_disposition",
        "HOLD_INCOMPLETE_OR_UNDERPOWERED",
        _seal(p_zero_strad_72),
        "HOLD_INDETERMINATE_INTERVAL_STRADDLING_CAP_UNDER_CONTROL_HOLD",
    )
    z72_det = r_z72["stress_ap1903_regimes"]["er_stress_tg_or_tm"]["lineages"]["delta"]
    if not (
        z72_det.get("ideal_sveh_72h_adjudication") == "INDETERMINATE_INTERVAL_STRADDLING_CAP_UNDER_CONTROL_HOLD"
        and z72_det.get("recomputed_l_surv_72h_ideal_sveh_lower") == "0"
        and abs(float(z72_det.get("recomputed_u_surv_72h_ideal_sveh_upper", "0")) - 0.00368208) < 1e-6
    ):
        cases[-1]["passed"] = False

    # 40. R07-M2: Direct-mode exact-interval fields carry an accurate sampling-model qualifier (zero "assumption-free" wording!)
    expected_m2_qual = (
        "DIRECT_EXACT_BINOMIAL_RATIO_WITHOUT_INDIRECT_SURVIVAL_INEQUALITY_CONDITIONAL_ON_REPRESENTATIVE_PAIRED_ALIQUOTS"
    )
    m2_ok = bool(
        dir_per.get("estimand2_denominator_mode") == expected_m2_qual
        and dir_per.get("estimand2_sampling_model_qualifier") == expected_m2_qual
        and "assumption_free" not in str(dir_per).lower()
        and "assumption-free" not in str(dir_per).lower()
        and "representative paired aliquots" in str(dir_per.get("estimand2_identifiability_assumption", "")).lower()
    )
    cases.append({
        "case": "r07_m2_direct_mode_sampling_model_qualifier_no_assumption_free",
        "expected_verdict": expected_m2_qual,
        "actual_verdict": dir_per.get("estimand2_denominator_mode"),
        "expected_token": None,
        "hard_stops": [],
        "holds": [],
        "passed": m2_ok,
    })

    # ------------------------------------------------------------------
    # Round-08 Final-Closure Adversarial Regression Suite (B1 & M1)
    # ------------------------------------------------------------------
    # 41. R08-B1: Archived composite bank bundles with (a) conflicting qualification_tier="BANK_QUALIFICATION"
    #     + operational_tier="LOT_RELEASE_SURROGATE", or (b) alias-only product_variant (missing canonical
    #     top-level product_variant_id), MUST fail closed in BOTH store layouts (registry JSON and directory
    #     store) with HOLD_ARCHIVED_BANK_ENVELOPE_MISMATCH + exact direct composite hold token, AND
    #     archived_bank_payload_live_revalidation_passed=False, archived_bank_payload_live_g0v_revalidation_passed=False,
    #     archived_bank_payload_live_legacy_revalidation_passed=False!
    with tempfile.TemporaryDirectory() as td_r08_b1:
        td_r08_p = Path(td_r08_b1)
        r08_g0v_bank = build_passing_reference_payload(
            lot_id="BANK-R08B1-001",
            mcb_id="MCB-ISLET1-A-R08",
            product_variant_id="ISLET1_A4_ARM1B",
            qualification_tier="BANK_QUALIFICATION",
            openislet_root=resolved_root,
        )
        r08_leg_bank = {
            "current_lot_id": "BANK-R08B1-001",
            "mcb_id": "MCB-ISLET1-A-R08",
            "product_variant_id": "ISLET1_A4_ARM1B",
            "obs_icasp9_log10_kill": 4.6,
            "obs_tp53_ppm1d_bcor_vaf": 0.0,
            "obs_mcb_effective_clonogenic_trials": 299573228.0,
            "obs_gate0v_day28_persistent_vp1_ie1_cells_scored": 5990.0,
        }

        def _r08_mock_legacy(_obs: Dict[str, Any], **_kw: Any) -> Dict[str, Any]:
            return {
                "lot_release_readiness_tier": "READY_FOR_ENCAPSULATION_COMPLETE_STAGE0_EVIDENCE",
                "safety_kill_s9_triggered": False,
                "resolved_architecture_assignments": {"product_variant_id": "ISLET1_A4_ARM1B"},
            }

        def _check_r08_bad_comp_archive(case_label: str, mut_fn, expected_tok: str) -> None:
            arch_doc: Dict[str, Any] = {
                "lot_id": "BANK-R08B1-001",
                "mcb_id": "MCB-ISLET1-A-R08",
                "product_variant_id": "ISLET1_A4_ARM1B",
                "legacy_stage0_observations": copy.deepcopy(r08_leg_bank),
                "gate0v_wholegraft_payload": copy.deepcopy(r08_g0v_bank),
            }
            mut_fn(arch_doc)
            arch_sha = compute_canonical_lot_sha256(arch_doc)
            arch_doc["payload_sha256"] = arch_sha
            env_direct = validate_canonical_composite_envelope(arch_doc, openislet_root=resolved_root)
            brec = build_authenticated_bank_qualification_record(
                mcb_id="MCB-ISLET1-A-R08",
                product_variant_id="ISLET1_A4_ARM1B",
                bank_lot_id="BANK-R08B1-001",
                bank_payload_sha256=arch_sha,
                antiviral_genotype_stratum=r08_g0v_bank["antiviral_genotype_stratum"],
            )
            reg_p = td_r08_p / f"{case_label}_reg.json"
            dir_p = td_r08_p / f"{case_label}_dir"
            write_record_to_trusted_qualification_store(reg_p, brec, category="bank_qualifications", archived_payload=arch_doc)
            write_record_to_trusted_qualification_store(dir_p, brec, category="bank_qualifications", archived_payload=arch_doc)
            p_surr = build_passing_reference_payload(
                lot_id="LOT-R08B1-SURR-001",
                mcb_id="MCB-ISLET1-A-R08",
                product_variant_id="ISLET1_A4_ARM1B",
                qualification_tier="LOT_RELEASE_SURROGATE",
                bridged_mcb_qualification_sha256=brec["sha256"],
                openislet_root=resolved_root,
            )
            both_ok = bool((not env_direct["valid"]) and (expected_tok in env_direct["holds"]))
            last_errs: List[str] = []
            for st_p in (reg_p, dir_p):
                # Composite archive resolution (legacy_evaluator active)
                pq_ok, pq_errs, pq_meta = resolve_and_verify_trusted_bank_qualification(
                    st_p,
                    expected_sha256=brec["sha256"],
                    expected_mcb_id="MCB-ISLET1-A-R08",
                    expected_product_variant_id="ISLET1_A4_ARM1B",
                    expected_genotype_stratum=r08_g0v_bank["antiviral_genotype_stratum"],
                    openislet_root=resolved_root,
                    hold_prefix="HOLD_COMPOSITE_PRIOR_BANK_QUAL",
                    legacy_evaluator=_r08_mock_legacy,
                )
                last_errs = pq_errs
                if not (
                    pq_ok is False
                    and pq_meta.get("archived_bank_payload_verified") is False
                    and pq_meta.get("archived_bank_payload_envelope_verified") is False
                    and pq_meta.get("archived_bank_payload_live_revalidation_passed") is False
                    and pq_meta.get("archived_bank_payload_live_g0v_revalidation_passed") is False
                    and pq_meta.get("archived_bank_payload_live_legacy_revalidation_passed") is False
                    and "HOLD_ARCHIVED_BANK_ENVELOPE_MISMATCH" in pq_errs
                    and expected_tok in pq_errs
                ):
                    both_ok = False
                # Standalone Gate-0V evaluator MUST also reject invalid archived composite envelope!
                r_sa = evaluate_wholegraft_gate0v_and_stress_ap1903(
                    p_surr, trusted_qualification_store=st_p, openislet_root=resolved_root
                )
                if not (
                    r_sa["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
                    and "HOLD_ARCHIVED_BANK_ENVELOPE_MISMATCH" in r_sa["holds"]
                    and expected_tok in r_sa["holds"]
                    and r_sa["lot_binding"]["prior_qualification_authentication"]["archived_bank_payload_live_revalidation_passed"] is False
                ):
                    both_ok = False
            cases.append({
                "case": case_label,
                "expected_verdict": expected_tok,
                "actual_verdict": expected_tok if both_ok else "PARITY_DRIFT_OR_UNEXPECTED_ACCEPT",
                "expected_token": expected_tok,
                "hard_stops": [],
                "holds": last_errs[:5],
                "passed": both_ok,
            })

        _check_r08_bad_comp_archive(
            "r08_b1_archived_composite_conflicting_operational_tier_rejected_both_layouts",
            lambda d: d.update(qualification_tier="BANK_QUALIFICATION", operational_tier="LOT_RELEASE_SURROGATE"),
            "HOLD_COMPOSITE_OPERATIONAL_TIER_MISMATCH",
        )
        _check_r08_bad_comp_archive(
            "r08_b1_archived_composite_missing_top_product_variant_id_alias_only_rejected_both_layouts",
            lambda d: d.__setitem__("product_variant", d.pop("product_variant_id")),
            "HOLD_COMPOSITE_MISSING_TOP_PRODUCT_VARIANT_ID",
        )

        # Standalone plain whole-graft archive with conflicting operational_tier MUST ALSO fail closed!
        plain_bad_tier = copy.deepcopy(r08_g0v_bank)
        plain_bad_tier["operational_tier"] = "LOT_RELEASE_SURROGATE"
        _seal(plain_bad_tier)
        direct_plain_bad = evaluate_wholegraft_gate0v_and_stress_ap1903(plain_bad_tier, openislet_root=resolved_root)
        brec_pt = build_authenticated_bank_qualification_record(
            mcb_id="MCB-ISLET1-A-R08",
            product_variant_id="ISLET1_A4_ARM1B",
            bank_lot_id="BANK-R08B1-001",
            bank_payload_sha256=plain_bad_tier["payload_sha256"],
            antiviral_genotype_stratum=plain_bad_tier["antiviral_genotype_stratum"],
        )
        reg_pt = td_r08_p / "plain_bad_tier_reg.json"
        dir_pt = td_r08_p / "plain_bad_tier_dir"
        write_record_to_trusted_qualification_store(reg_pt, brec_pt, category="bank_qualifications", archived_payload=plain_bad_tier)
        write_record_to_trusted_qualification_store(dir_pt, brec_pt, category="bank_qualifications", archived_payload=plain_bad_tier)
        p_surr_pt = build_passing_reference_payload(
            lot_id="LOT-R08B1-PT-001",
            mcb_id="MCB-ISLET1-A-R08",
            product_variant_id="ISLET1_A4_ARM1B",
            qualification_tier="LOT_RELEASE_SURROGATE",
            bridged_mcb_qualification_sha256=brec_pt["sha256"],
            openislet_root=resolved_root,
        )
        pt_ok = bool(
            direct_plain_bad["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
            and "HOLD_GATE0V_OPERATIONAL_TIER_MISMATCH" in direct_plain_bad["holds"]
        )
        last_pt_holds: List[str] = []
        for st_pt in (reg_pt, dir_pt):
            r_pt = evaluate_wholegraft_gate0v_and_stress_ap1903(
                p_surr_pt, trusted_qualification_store=st_pt, openislet_root=resolved_root
            )
            last_pt_holds = r_pt["holds"]
            if not (
                r_pt["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
                and "HOLD_ARCHIVED_BANK_ENVELOPE_MISMATCH" in r_pt["holds"]
                and "HOLD_GATE0V_OPERATIONAL_TIER_MISMATCH" in r_pt["holds"]
                and r_pt["lot_binding"]["prior_qualification_authentication"]["archived_bank_payload_live_revalidation_passed"] is False
            ):
                pt_ok = False
        cases.append({
            "case": "r08_b1_standalone_plain_wholegraft_conflicting_operational_tier_direct_and_archived_held",
            "expected_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
            "actual_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED" if pt_ok else "UNEXPECTED_ACCEPT",
            "expected_token": "HOLD_GATE0V_OPERATIONAL_TIER_MISMATCH",
            "hard_stops": [],
            "holds": last_pt_holds[:4],
            "passed": pt_ok,
        })

    # 42. R08-M1: Gate 0V-Kill paired 24-h and 72-h ratio bounds carry explicit separate directional
    #     one-sided confidence statement labeling in receipt budgets!
    m1_kill_ok = bool(
        dir_per.get("bonferroni_alpha_budget_24h", {}).get("confidence_statement_type")
        == "DIRECTIONAL_ONE_SIDED_SEPARATE_AT_1_MINUS_ALPHA_SUM"
        and dir_per.get("bonferroni_alpha_budget_72h", {}).get("confidence_statement_type")
        == "DIRECTIONAL_ONE_SIDED_SEPARATE_AT_1_MINUS_ALPHA_SUM"
        and dir_per.get("estimand1_bonferroni_alpha_budget", {}).get("confidence_statement_type")
        == "DIRECTIONAL_ONE_SIDED_UPPER_AT_1_MINUS_ALPHA_SUM"
        and dir_per.get("estimand2_bonferroni_alpha_budget", {}).get("confidence_statement_type")
        == "DIRECTIONAL_ONE_SIDED_UPPER_AT_1_MINUS_ALPHA_SUM"
    )
    cases.append({
        "case": "r08_m1_gate0v_kill_ratio_budgets_labeled_directional_one_sided_separate",
        "expected_verdict": "DIRECTIONAL_ONE_SIDED_SEPARATE_AT_1_MINUS_ALPHA_SUM",
        "actual_verdict": dir_per.get("bonferroni_alpha_budget_24h", {}).get("confidence_statement_type"),
        "expected_token": None,
        "hard_stops": [],
        "holds": [],
        "passed": m1_kill_ok,
    })

    # ------------------------------------------------------------------
    # Round-09 Final-Closure Adversarial Regressions (R09-B1 Strict JSON & R09-B2 Ratio Domain)
    # ------------------------------------------------------------------
    with tempfile.TemporaryDirectory() as td_r09:
        td_r09_p = Path(td_r09)
        r09_g0v_bank = build_passing_reference_payload(
            lot_id="BANK-R09-001",
            mcb_id="MCB-ISLET1-A-R09",
            product_variant_id="ISLET1_A4_ARM1B",
            qualification_tier="BANK_QUALIFICATION",
            openislet_root=resolved_root,
        )
        r09_raw_bank = json.dumps(r09_g0v_bank, sort_keys=True)

        # 43. R09-B1 (a): Standalone lot file intake rejects duplicate top-level, nested, and
        #     unicode-escaped duplicate JSON object keys with structured HOLD exit 2!
        f_top_dup = td_r09_p / "r09_top_dup.json"
        f_top_dup.write_text(
            '{"qualification_tier": "LOT_RELEASE_SURROGATE", ' + r09_raw_bank[1:],
            encoding="utf-8",
        )
        f_nested_dup = td_r09_p / "r09_nested_dup.json"
        f_nested_dup.write_text(
            r09_raw_bank.replace(
                '"gate0v_a_poly_ic_sensing": {',
                '"gate0v_a_poly_ic_sensing": {"poly_ic_dose_ng_ml": 0, ',
                1,
            ),
            encoding="utf-8",
        )
        f_uni_dup = td_r09_p / "r09_uni_dup.json"
        f_uni_dup.write_text(
            '{"lot_\\u0069d": "FAKE-LOT", ' + r09_raw_bank[1:],
            encoding="utf-8",
        )
        r09_dup_ok = True
        r09_dup_holds: List[str] = []
        for dup_p in (f_top_dup, f_nested_dup, f_uni_dup):
            res_dp, rc_dp = evaluate_wholegraft_gate0v_lot_file(dup_p, openislet_root=resolved_root)
            r09_dup_holds = res_dp.get("holds") or []
            if not (
                rc_dp == 2
                and res_dp.get("verdict") == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
                and "HOLD_GATE0V_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:DUPLICATE_JSON_KEY" in r09_dup_holds
            ):
                r09_dup_ok = False
        cases.append({
            "case": "r09_b1_standalone_lot_file_top_nested_unicode_duplicate_keys_hold_exit_2",
            "expected_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
            "actual_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED" if r09_dup_ok else "UNEXPECTED_ACCEPT",
            "expected_token": "HOLD_GATE0V_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:DUPLICATE_JSON_KEY",
            "hard_stops": [],
            "holds": r09_dup_holds[:3],
            "passed": r09_dup_ok,
        })

        # 44. R09-B1 (b): Standalone lot file intake rejects NaN, Infinity, -Infinity with structured HOLD exit 2!
        r09_const_ok = True
        r09_const_holds: List[str] = []
        for idx_c, tok_c in enumerate(("NaN", "Infinity", "-Infinity")):
            f_c = td_r09_p / f"r09_const_{idx_c}.json"
            f_c.write_text(f'{{"lot_id": "BANK-R09-C", "bad_val": {tok_c}}}', encoding="utf-8")
            res_c, rc_c = evaluate_wholegraft_gate0v_lot_file(f_c, openislet_root=resolved_root)
            r09_const_holds = res_c.get("holds") or []
            if not (
                rc_c == 2
                and res_c.get("verdict") == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
                and "HOLD_GATE0V_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:NON_STANDARD_JSON_CONSTANT" in r09_const_holds
            ):
                r09_const_ok = False
        cases.append({
            "case": "r09_b1_standalone_lot_file_nan_infinity_constants_hold_exit_2",
            "expected_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
            "actual_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED" if r09_const_ok else "UNEXPECTED_ACCEPT",
            "expected_token": "HOLD_GATE0V_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:NON_STANDARD_JSON_CONSTANT",
            "hard_stops": [],
            "holds": r09_const_holds[:3],
            "passed": r09_const_ok,
        })

        # 45. R09-B1 (c): External trusted qualification store rejects duplicate keys AND NaN across
        #     registry JSON, directory bank record JSON, directory bank archive JSON, and directory
        #     autologous process-qual archive JSON!
        r09_brec = build_authenticated_bank_qualification_record(
            mcb_id="MCB-ISLET1-A-R09",
            product_variant_id="ISLET1_A4_ARM1B",
            bank_lot_id="BANK-R09-001",
            bank_payload_sha256=r09_g0v_bank["payload_sha256"],
            antiviral_genotype_stratum=r09_g0v_bank["antiviral_genotype_stratum"],
        )
        r09_surr = build_passing_reference_payload(
            lot_id="LOT-R09-SURR-001",
            mcb_id="MCB-ISLET1-A-R09",
            product_variant_id="ISLET1_A4_ARM1B",
            qualification_tier="LOT_RELEASE_SURROGATE",
            bridged_mcb_qualification_sha256=r09_brec["sha256"],
            openislet_root=resolved_root,
        )
        reg_dup_r09 = td_r09_p / "r09_store_reg_dup.json"
        write_record_to_trusted_qualification_store(
            reg_dup_r09, r09_brec, category="bank_qualifications", archived_payload=r09_g0v_bank
        )
        reg_dup_r09.write_text(
            reg_dup_r09.read_text(encoding="utf-8").replace(
                '"operational_tier": "BANK_QUALIFICATION"',
                '"operational_tier": "LOT_RELEASE_SURROGATE", "operational_tier": "BANK_QUALIFICATION"',
                1,
            ),
            encoding="utf-8",
        )
        dir_rec_dup_r09 = td_r09_p / "r09_store_dir_rec_dup"
        write_record_to_trusted_qualification_store(
            dir_rec_dup_r09, r09_brec, category="bank_qualifications", archived_payload=r09_g0v_bank
        )
        rec_f_r09 = dir_rec_dup_r09 / "bank_qualifications" / f"{r09_brec['sha256']}.json"
        rec_f_r09.write_text(
            '{"verdict": "HOLD_FAKE", ' + rec_f_r09.read_text(encoding="utf-8").lstrip()[1:],
            encoding="utf-8",
        )
        dir_arch_dup_r09 = td_r09_p / "r09_store_dir_arch_dup"
        write_record_to_trusted_qualification_store(
            dir_arch_dup_r09, r09_brec, category="bank_qualifications", archived_payload=r09_g0v_bank
        )
        arch_f_r09 = dir_arch_dup_r09 / "archived_payloads" / f"{r09_g0v_bank['payload_sha256']}.json"
        arch_f_r09.write_text(
            '{"qualification_tier": "LOT_RELEASE_SURROGATE", ' + arch_f_r09.read_text(encoding="utf-8").lstrip()[1:],
            encoding="utf-8",
        )
        dir_arch_nan_r09 = td_r09_p / "r09_store_dir_arch_nan"
        write_record_to_trusted_qualification_store(
            dir_arch_nan_r09, r09_brec, category="bank_qualifications", archived_payload=r09_g0v_bank
        )
        arch_nan_f = dir_arch_nan_r09 / "archived_payloads" / f"{r09_g0v_bank['payload_sha256']}.json"
        arch_nan_f.write_text(
            '{"nan_probe": NaN, ' + arch_nan_f.read_text(encoding="utf-8").lstrip()[1:],
            encoding="utf-8",
        )
        r09_store_ok = True
        r09_store_holds: List[str] = []
        for st_r09 in (reg_dup_r09, dir_rec_dup_r09, dir_arch_dup_r09, dir_arch_nan_r09):
            res_st = evaluate_wholegraft_gate0v_and_stress_ap1903(
                r09_surr, trusted_qualification_store=st_r09, openislet_root=resolved_root
            )
            r09_store_holds = res_st.get("holds") or []
            pqa_st = (res_st.get("lot_binding") or {}).get("prior_qualification_authentication") or {}
            if not (
                res_st.get("verdict") == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
                and "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE" in r09_store_holds
                and pqa_st.get("archived_bank_payload_verified") is False
                and pqa_st.get("archived_bank_payload_live_revalidation_passed") is False
                and any("AMBIGUOUS_OR_NONCANONICAL_JSON" in h for h in r09_store_holds)
            ):
                r09_store_ok = False
        # Also test autologous process-qualification directory archive with duplicate key!
        proc_rec_r09 = build_authenticated_process_qualification_record(
            product_variant_id="ISLET1_D1_AUTO_V2_L1B_CIITA_CD64T_IL1RN",
            process_qual_id="PQ-R09-001",
            process_qual_payload_sha256=r09_g0v_bank["payload_sha256"],
        )
        dir_proc_dup = td_r09_p / "r09_store_proc_arch_dup"
        write_record_to_trusted_qualification_store(
            dir_proc_dup, proc_rec_r09, category="process_qualifications", archived_payload=r09_g0v_bank
        )
        proc_arch_f = dir_proc_dup / "archived_payloads" / f"{r09_g0v_bank['payload_sha256']}.json"
        proc_arch_f.write_text(
            '{"lot_id": "FAKE", ' + proc_arch_f.read_text(encoding="utf-8").lstrip()[1:],
            encoding="utf-8",
        )
        pq_proc_ok, pq_proc_errs, _pq_proc_meta = resolve_and_verify_trusted_process_qualification(
            dir_proc_dup,
            expected_sha256=proc_rec_r09["sha256"],
            expected_product_variant_id="ISLET1_D1_AUTO_V2_L1B_CIITA_CD64T_IL1RN",
            openislet_root=resolved_root,
        )
        if not (pq_proc_ok is False and "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE" in pq_proc_errs):
            r09_store_ok = False
        cases.append({
            "case": "r09_b1_external_store_registry_record_bank_and_proc_archives_dup_key_nan_hold",
            "expected_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
            "actual_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED" if r09_store_ok else "UNEXPECTED_ACCEPT",
            "expected_token": "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE",
            "hard_stops": [],
            "holds": r09_store_holds[:4],
            "passed": r09_store_ok,
        })

    # 46. R09-B2 + R15-M1: Live Gate 0V-Kill arm with 90% drug (900/1,000) vs 70% vehicle (700/1,000)
    #     survival at component tails alpha_treated=alpha_veh=0.025 reports valid unclamped ordered
    #     directional limits (L ~ 1.20793 <= U ~ 1.36889, negative kill L95) and FAIL_HARD_STOP!
    p_90_70 = copy.deepcopy(r09_g0v_bank)
    arm_90_70 = p_90_70["gate0v_kill_stress_ap1903"]["normoxia_baseline"]["alpha"]
    arm_90_70["veh_24h_viable_n"] = 700
    arm_90_70["veh_24h_input_n"] = 1000
    arm_90_70["ap1903_24h_input_n"] = 1000
    arm_90_70["ap1903_24h_viable_survivors_k"] = 900
    reconcile_fixture_per_unit_counts(p_90_70)
    _seal(p_90_70)
    r_90_70 = evaluate_wholegraft_gate0v_and_stress_ap1903(p_90_70, openislet_root=resolved_root)
    det_90_70 = r_90_70["stress_ap1903_regimes"]["normoxia_baseline"]["lineages"]["alpha"]
    l_90_70_d = Decimal(det_90_70["recomputed_l_ratio_24h_joint_lower"])
    u_90_70_d = Decimal(det_90_70["recomputed_u_ratio_24h_joint_upper"])
    ok_90_70_live = bool(
        r_90_70["verdict"] == "FAIL_HARD_STOP"
        and l_90_70_d <= u_90_70_d
        and u_90_70_d > Decimal("1.36")
        and l_90_70_d > Decimal("1.20")
        and det_90_70.get("u_ratio_clamped_to_unity_24h") is False
        and det_90_70.get("ratio_estimand_domain_24h") == "[0, +infinity)"
        and det_90_70.get("treated_survival_exceeds_vehicle_survival_24h") is True
        and det_90_70.get("ratio_bounds_ordered_l_le_u_24h") is True
        and det_90_70.get("recomputed_kill_24h_pct_joint_l95", 0.0) < -36.0
    )
    cases.append({
        "case": "r09_b2_live_gate0v_kill_90pct_vs_70pct_unclamped_ordered_bounds_and_hard_stop",
        "expected_verdict": "FAIL_HARD_STOP",
        "actual_verdict": r_90_70["verdict"],
        "expected_token": "FAIL_HARD_STOP_AP1903_24H_KILL_BELOW_99P9PCT_NORMOXIA_BASELINE_ALPHA",
        "hard_stops": r_90_70["hard_stops"][:3],
        "holds": r_90_70["holds"][:3],
        "passed": ok_90_70_live,
    })

    # 47. R09-B1 (d): In-memory Python dict with float('nan') fails closed cleanly to HOLD (no traceback)!
    p_nan_mem = copy.deepcopy(r09_g0v_bank)
    p_nan_mem["nonfinite_probe"] = float("nan")
    r_nan_mem = evaluate_wholegraft_gate0v_and_stress_ap1903(p_nan_mem, openislet_root=resolved_root)
    ok_nan_mem = bool(
        r_nan_mem["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        and "HOLD_GATE0V_NONCANONICAL_OR_NONFINITE_PAYLOAD" in r_nan_mem["holds"]
    )
    cases.append({
        "case": "r09_b1_in_memory_nonfinite_float_payload_fails_closed_hold",
        "expected_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
        "actual_verdict": r_nan_mem["verdict"],
        "expected_token": "HOLD_GATE0V_NONCANONICAL_OR_NONFINITE_PAYLOAD",
        "hard_stops": r_nan_mem["hard_stops"][:2],
        "holds": r_nan_mem["holds"][:3],
        "passed": ok_nan_mem,
    })

    # 48. R10-B2 (a): Schema-invalid unhashable list/dict values (e.g., qualification_tier: ["BANK_QUALIFICATION"])
    #     in standalone --evaluate-lot intake return structured JSON HOLD exit 2 (NEVER TypeError traceback)!
    with tempfile.TemporaryDirectory() as td_r10:
        td_r10_p = Path(td_r10)
        unhash_cases = (
            ("list_tier", {"qualification_tier": ["BANK_QUALIFICATION"]}),
            ("dict_tier", {"qualification_tier": {"tier": "BANK_QUALIFICATION"}}),
            ("list_geno", {"qualification_tier": "BANK_QUALIFICATION", "antiviral_genotype_stratum": ["TYK2_WT__IFIH1_WT_OR_A946T"]}),
            ("list_lot_id", {"lot_id": ["LOT-1"], "qualification_tier": "BANK_QUALIFICATION"}),
        )
        r10_unhash_ok = True
        r10_unhash_holds: List[str] = []
        for u_tag, u_doc in unhash_cases:
            uf = td_r10_p / f"r10_unhash_{u_tag}.json"
            uf.write_text(json.dumps(u_doc), encoding="utf-8")
            u_res, u_rc = evaluate_wholegraft_gate0v_lot_file(uf, openislet_root=resolved_root)
            r10_unhash_holds = u_res.get("holds") or []
            if not (u_rc == 2 and u_res.get("verdict") == "HOLD_INCOMPLETE_OR_UNDERPOWERED" and len(r10_unhash_holds) >= 1):
                r10_unhash_ok = False
        cases.append({
            "case": "r10_b2_unhashable_list_and_dict_types_standalone_lot_file_structured_hold_exit_2",
            "expected_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
            "actual_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED" if r10_unhash_ok else "UNHANDLED_ERROR_OR_WRONG_RC",
            "expected_token": "HOLD_GATE0V_MISSING_OR_INVALID_QUALIFICATION_TIER",
            "hard_stops": [],
            "holds": r10_unhash_holds[:3],
            "passed": r10_unhash_ok,
        })

        # 49. R10-B2 (b): Out-of-float64-range finite JSON integers (10**400, -10**400) and overflowing float (1e500)
        #     at standalone --evaluate-lot intake return structured JSON HOLD exit 2 (NEVER OverflowError traceback)!
        huge_cases = (
            ("pos_1e400", f'{{"qualification_tier": "BANK_QUALIFICATION", "huge_int": {10**400}}}', "OUT_OF_RANGE_JSON_INTEGER"),
            ("neg_1e400", f'{{"qualification_tier": "BANK_QUALIFICATION", "huge_int": {-10**400}}}', "OUT_OF_RANGE_JSON_INTEGER"),
            ("float_1e500", '{"qualification_tier": "BANK_QUALIFICATION", "huge_flt": 1e500}', "NON_FINITE_JSON_FLOAT"),
        )
        r10_huge_ok = True
        r10_huge_holds: List[str] = []
        for h_tag, h_raw, h_reason in huge_cases:
            hf = td_r10_p / f"r10_huge_{h_tag}.json"
            hf.write_text(h_raw, encoding="utf-8")
            h_res, h_rc = evaluate_wholegraft_gate0v_lot_file(hf, openislet_root=resolved_root)
            r10_huge_holds = h_res.get("holds") or []
            if not (
                h_rc == 2
                and h_res.get("verdict") == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
                and f"HOLD_GATE0V_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:{h_reason}" in r10_huge_holds
            ):
                r10_huge_ok = False
        cases.append({
            "case": "r10_b2_out_of_float64_range_integers_and_1e500_standalone_lot_file_structured_hold_exit_2",
            "expected_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
            "actual_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED" if r10_huge_ok else "UNHANDLED_OVERFLOW_OR_WRONG_RC",
            "expected_token": "HOLD_GATE0V_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:OUT_OF_RANGE_JSON_INTEGER",
            "hard_stops": [],
            "holds": r10_huge_holds[:3],
            "passed": r10_huge_ok,
        })

    # ------------------------------------------------------------------
    # Round-11 Final-Closure Adversarial Regressions (R11-B1, R11-B3, R11-B4)
    # ------------------------------------------------------------------
    # 50. R11-B3: Sol's exact exchangeable mixture deff = 2.0161290322580645 even when ALL sample sizes
    #     are scaled up 3x (so naive n_eff clears every threshold!) MUST STILL route to non-authorizing
    #     HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE (`exact_directional_confidence_certified=False`,
    #     `release_authorizing=False`), while deterministic biological FAIL_HARD_STOP (`vk=1`) is preserved!
    p_sol_scaled = build_passing_reference_payload(openislet_root=resolved_root)
    p_sol_scaled["clustering_and_independence_spec"]["clustering_design_effect_deff"] = "2.0161290322580645"
    for _pid, _pb in p_sol_scaled["gate0v_b_infectious_challenge"]["pathogens"].items():
        _pb["total_viable_cells_acquired_n"] = _pb["total_viable_cells_acquired_n"] * 3
        _pb["lineage_unassigned_cells_n"] = _pb["lineage_unassigned_cells_n"] * 3
        _pb["unassigned_fraction_viral_readout"]["unassigned_cells_screened_n"] = _pb["lineage_unassigned_cells_n"]
        _pb["day28_latent_and_defective_genome_arm"]["ddpcr_cell_equivalents_screened_n"] *= 3
        for _tentry in _pb["day28_latent_and_defective_genome_arm"]["ddpcr_targets"].values():
            _tentry["n"] *= 3
        for _lentry in _pb["day28_persistence_by_lineage"].values():
            _lentry["cells_assigned_n"] *= 3
            _lentry["cells_scored_n"] *= 3
    for _reg, _rb in p_sol_scaled["gate0v_kill_stress_ap1903"].items():
        for _lin, _lb in _rb.items():
            _lb["ap1903_24h_input_n"] *= 3
            _lb["ap1903_72h_input_n"] *= 3
            if "pre_ap1903_lineage_input_cells_n" in _lb:
                _lb["pre_ap1903_lineage_input_cells_n"] *= 3
    reconcile_fixture_per_unit_counts(p_sol_scaled)
    r_sol_scaled = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_sol_scaled), openislet_root=resolved_root)
    det_sol_arm = r_sol_scaled["stress_ap1903_regimes"]["active_or_persistent_cvb4_infection"]["lineages"]["beta"]
    p_sol_bio_fail = copy.deepcopy(p_sol_scaled)
    p_sol_bio_fail["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["post_ap1903_viable_viral_pos_k"] = 1
    reconcile_fixture_per_unit_counts(p_sol_bio_fail)
    r_sol_bio_fail = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_sol_bio_fail), openislet_root=resolved_root)
    p_sol_cp_only = copy.deepcopy(p_sol_scaled)
    p_sol_cp_only["gate0v_kill_stress_ap1903"]["normoxia_baseline"]["alpha"]["ap1903_24h_viable_survivors_k"] = 30
    reconcile_fixture_per_unit_counts(p_sol_cp_only)
    r_sol_cp_only = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_sol_cp_only), openislet_root=resolved_root)
    ok_r11_b3 = bool(
        r_sol_scaled["verdict"] == "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE"
        and r_sol_scaled["release_authorizing"] is False
        and r_sol_scaled["exact_directional_confidence_certified"] is False
        and r_sol_scaled["confidence_scope"] == "NON_AUTHORIZING_VARIANCE_ADJUSTED_DIAGNOSTIC_ONLY"
        and "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE" in r_sol_scaled["holds"]
        and det_sol_arm["exact_directional_confidence_certified"] is False
        and det_sol_arm["bonferroni_alpha_budget_24h"]["joint_confidence_lower_bound"] is None
        and det_sol_arm["bonferroni_alpha_budget_72h"]["joint_confidence_lower_bound"] is None
        and det_sol_arm["estimand1_bonferroni_alpha_budget"]["joint_confidence_lower_bound"] is None
        and det_sol_arm["estimand2_bonferroni_alpha_budget"]["joint_confidence_lower_bound"] is None
        and det_sol_arm["estimand2_release_authorizing_eligible"] is False
        and r_sol_bio_fail["verdict"] == "FAIL_HARD_STOP"
        and r_sol_cp_only["verdict"] == "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE"
    )
    cases.append({
        "case": "r11_b3_sol_deff_2p0161_high_n_held_cluster_inference_bio_fail_preserved",
        "expected_verdict": "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE",
        "actual_verdict": r_sol_scaled["verdict"],
        "expected_token": "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE",
        "hard_stops": r_sol_bio_fail["hard_stops"][:2],
        "holds": r_sol_scaled["holds"][:3],
        "passed": ok_r11_b3,
    })

    # 51. R11-B1 + R13-B3: Standalone clinical `LOT_RELEASE_SURROGATE` Gate-0V payload declaring
    #     `require_trusted_nw08_ocr_record = True` without coupled OCR emits
    #     `HOLD_NW08_REQUIRED_OCR_RECORD_MISSING` (exit 2, release_authorizing=False), non-bool
    #     flag fails closed to HOLD, and independent biological FAIL_HARD_STOP is preserved!
    with tempfile.TemporaryDirectory() as td_r11_b1_sa:
        td_b1_sa = Path(td_r11_b1_sa)
        b_ref_51 = build_passing_reference_payload(
            lot_id="BANK-R11B1-SA-001",
            mcb_id="MCB-R11B1-SA-001",
            product_variant_id="ISLET1_A4_ARM1B",
            qualification_tier="BANK_QUALIFICATION",
            openislet_root=resolved_root,
        )
        brec_51 = build_authenticated_bank_qualification_record(
            mcb_id="MCB-R11B1-SA-001",
            product_variant_id="ISLET1_A4_ARM1B",
            bank_lot_id="BANK-R11B1-SA-001",
            bank_payload_sha256=b_ref_51["payload_sha256"],
        )
        st_51 = td_b1_sa / "trusted_store_51.json"
        write_record_to_trusted_qualification_store(
            st_51, brec_51, category="bank_qualifications", archived_payload=b_ref_51
        )
        p_req_ocr = build_passing_reference_payload(
            lot_id="LOT-R11B1-SA-001",
            mcb_id="MCB-R11B1-SA-001",
            product_variant_id="ISLET1_A4_ARM1B",
            qualification_tier="LOT_RELEASE_SURROGATE",
            bridged_mcb_qualification_sha256=brec_51["sha256"],
            openislet_root=resolved_root,
        )
        p_req_ocr["require_trusted_nw08_ocr_record"] = True
        r_req_ocr = evaluate_wholegraft_gate0v_and_stress_ap1903(
            _seal(p_req_ocr), trusted_qualification_store=st_51, openislet_root=resolved_root
        )
        p_req_ocr_fail = copy.deepcopy(p_req_ocr)
        p_req_ocr_fail["cxadr_ko_present"] = True
        r_req_ocr_fail = evaluate_wholegraft_gate0v_and_stress_ap1903(
            _seal(p_req_ocr_fail), trusted_qualification_store=st_51, openislet_root=resolved_root
        )
        p_req_ocr_badtype = copy.deepcopy(p_req_ocr)
        p_req_ocr_badtype["require_trusted_nw08_ocr_record"] = "true"
        r_req_ocr_badtype = evaluate_wholegraft_gate0v_and_stress_ap1903(
            _seal(p_req_ocr_badtype), trusted_qualification_store=st_51, openislet_root=resolved_root
        )
        p_req_ocr_null = copy.deepcopy(p_req_ocr)
        p_req_ocr_null["require_trusted_nw08_ocr_record"] = None
        r_req_ocr_null = evaluate_wholegraft_gate0v_and_stress_ap1903(
            _seal(p_req_ocr_null), trusted_qualification_store=st_51, openislet_root=resolved_root
        )
    ok_r11_b1_sa = bool(
        r_req_ocr["verdict"] == "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING"
        and r_req_ocr["release_authorizing"] is False
        and "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING" in r_req_ocr["holds"]
        and r_req_ocr_fail["verdict"] == "FAIL_HARD_STOP"
        and "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING" in r_req_ocr_fail["holds"]
        and r_req_ocr_badtype["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        and "HOLD_NW08_COUPLED_INVALID_REQUIRE_TRUSTED_OCR_FLAG" in r_req_ocr_badtype["holds"]
        and r_req_ocr_null["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        and "HOLD_NW08_COUPLED_INVALID_REQUIRE_TRUSTED_OCR_FLAG" in r_req_ocr_null["holds"]
    )
    cases.append({
        "case": "r11_b1_standalone_require_trusted_nw08_ocr_missing_hold_nonbool_hold_fail_preserved",
        "expected_verdict": "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING",
        "actual_verdict": r_req_ocr["verdict"],
        "expected_token": "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING",
        "hard_stops": r_req_ocr_fail["hard_stops"][:2],
        "holds": r_req_ocr["holds"][:3],
        "passed": ok_r11_b1_sa,
    })

    # 52. R11-B4: JSON nesting depth > 64 AND monkeypatched parser RecursionError on `{}` map cleanly
    #     to structured HOLD exit 2 (`release_authorizing=False`, `JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED`)
    #     across standalone lot intake AND trusted qualification store (registry JSON + dir store + OCR store)!
    with tempfile.TemporaryDirectory() as td_r11_b4_sa:
        td_b4s = Path(td_r11_b4_sa)
        deep_70_txt = '{"a":' * 70 + "1" + "}" * 70
        f_deep_lot = td_b4s / "deep_70_lot.json"
        f_deep_lot.write_text(deep_70_txt, encoding="utf-8")
        f_empty_lot = td_b4s / "empty_lot.json"
        f_empty_lot.write_text("{}", encoding="utf-8")
        f_deep_store = td_b4s / "deep_70_store.json"
        f_deep_store.write_text(deep_70_txt, encoding="utf-8")

        r_dl, rc_dl = evaluate_wholegraft_gate0v_lot_file(f_deep_lot, openislet_root=resolved_root)
        _rec_ds, _arch_ds, errs_ds, _src_ds, _ast_ds = _lookup_in_trusted_qualification_store_with_archive_status(
            f_deep_store, category="bank_qualifications", expected_sha256=_valid_digest("r11_b4_ref")
        )
        ok_ocr_ds, errs_ocr_ds, _meta_ocr_ds = resolve_and_verify_trusted_nw08_ocr_record(
            f_deep_store,
            expected_ocr_record_sha256=_valid_digest("r11_b4_ocr"),
            submitted_ocr_record={"route_id": "R2_DZ40"},
            require_store_entry=True,
        )

        orig_jl = json.loads

        def _boom_rec(*_a: Any, **_kw: Any) -> Any:
            raise RecursionError("simulated parser recursion error")

        json.loads = _boom_rec  # type: ignore[assignment]
        try:
            r_rl, rc_rl = evaluate_wholegraft_gate0v_lot_file(f_empty_lot, openislet_root=resolved_root)
            _rec_rs, _arch_rs, errs_rs, _src_rs, _ast_rs = _lookup_in_trusted_qualification_store_with_archive_status(
                f_empty_lot, category="bank_qualifications", expected_sha256=_valid_digest("r11_b4_ref")
            )
            ok_ocr_rs, errs_ocr_rs, _meta_ocr_rs = resolve_and_verify_trusted_nw08_ocr_record(
                f_empty_lot,
                expected_ocr_record_sha256=_valid_digest("r11_b4_ocr"),
                submitted_ocr_record={"route_id": "R2_DZ40"},
                require_store_entry=True,
            )
        finally:
            json.loads = orig_jl  # type: ignore[assignment]
    ok_r11_b4_sa = bool(
        rc_dl == 2
        and r_dl.get("release_authorizing") is False
        and "HOLD_GATE0V_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED" in (r_dl.get("holds") or [])
        and rc_rl == 2
        and r_rl.get("release_authorizing") is False
        and "HOLD_GATE0V_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED" in (r_rl.get("holds") or [])
        and "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE" in errs_ds
        and any("JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED" in e for e in errs_ds)
        and "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE" in errs_rs
        and any("JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED" in e for e in errs_rs)
        and ok_ocr_ds is False
        and any("JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED" in e for e in errs_ocr_ds)
        and ok_ocr_rs is False
        and any("JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED" in e for e in errs_ocr_rs)
    )
    cases.append({
        "case": "r11_b4_depth_gt_64_and_injected_recursion_error_standalone_lot_and_trusted_store_hold_exit_2",
        "expected_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
        "actual_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED" if ok_r11_b4_sa else "UNHANDLED_RECURSION_OR_WRONG_RC",
        "expected_token": "JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED",
        "hard_stops": [],
        "holds": (r_rl.get("holds") or [])[:3],
        "passed": ok_r11_b4_sa,
    })

    # ------------------------------------------------------------------
    # Round-12 Final-Closure Adversarial Regressions (R12-B1 & R12-B2)
    # ------------------------------------------------------------------
    # 53. R12-B1 (a): Missing or invalid clustering_and_independence_spec NEVER defaults deff=1.0,
    #     sets deff=None, exact_directional_confidence_certified=False,
    #     confidence_scope="UNCERTIFIED_MISSING_OR_INVALID_SAMPLING_SPEC", release_authorizing=False,
    #     and preserves deterministic biological FAIL_HARD_STOP (cxadr_ko_present, vk=1, caspase<5, k>n)!
    p_miss_spec = build_passing_reference_payload(openislet_root=resolved_root)
    p_miss_spec.pop("clustering_and_independence_spec", None)
    r_miss_spec = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_miss_spec), openislet_root=resolved_root)

    p_bad_deff = build_passing_reference_payload(openislet_root=resolved_root)
    p_bad_deff["clustering_and_independence_spec"]["clustering_design_effect_deff"] = "bad_deff"
    r_bad_deff = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_bad_deff), openislet_root=resolved_root)

    p_lt1_deff = build_passing_reference_payload(openislet_root=resolved_root)
    p_lt1_deff["clustering_and_independence_spec"]["clustering_design_effect_deff"] = "0.5"
    r_lt1_deff = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_lt1_deff), openislet_root=resolved_root)

    p_miss_cx = copy.deepcopy(p_miss_spec)
    p_miss_cx["cxadr_ko_present"] = True
    r_miss_cx = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_miss_cx), openislet_root=resolved_root)

    p_miss_vk = copy.deepcopy(p_miss_spec)
    p_miss_vk["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["post_ap1903_viable_viral_pos_k"] = 1
    r_miss_vk = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_miss_vk), openislet_root=resolved_root)

    p_miss_casp = copy.deepcopy(p_miss_spec)
    p_miss_casp["gate0v_kill_stress_ap1903"]["active_or_persistent_hcmv_infection"]["beta"]["caspase9_3_activity_fold_over_vehicle"] = "1.5"
    r_miss_casp = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_miss_casp), openislet_root=resolved_root)

    p_miss_k_gt_n = copy.deepcopy(p_miss_spec)
    p_miss_k_gt_n["gate0v_kill_stress_ap1903"]["normoxia_baseline"]["beta"]["ap1903_24h_viable_survivors_k"] = 10001
    r_miss_k_gt_n = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_miss_k_gt_n), openislet_root=resolved_root)

    def _any_nested_cert_true(obj: Any) -> bool:
        stack: List[Any] = [obj]
        while stack:
            cur = stack.pop()
            if isinstance(cur, dict):
                if cur.get("exact_directional_confidence_certified") is True:
                    return True
                for v in cur.values():
                    if isinstance(v, (dict, list, tuple)):
                        stack.append(v)
            elif isinstance(cur, (list, tuple)):
                for item in cur:
                    if isinstance(item, (dict, list, tuple)):
                        stack.append(item)
        return False

    ok_r12_b1a = bool(
        r_miss_spec["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        and r_miss_spec["clustering_design_effect_deff"] is None
        and r_miss_spec["exact_directional_confidence_certified"] is False
        and r_miss_spec["confidence_scope"] == "UNCERTIFIED_MISSING_OR_INVALID_SAMPLING_SPEC"
        and r_miss_spec["release_authorizing"] is False
        and not _any_nested_cert_true(r_miss_spec)
        and r_bad_deff["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        and r_bad_deff["clustering_design_effect_deff"] is None
        and r_bad_deff["exact_directional_confidence_certified"] is False
        and r_bad_deff["confidence_scope"] == "UNCERTIFIED_MISSING_OR_INVALID_SAMPLING_SPEC"
        and r_bad_deff["release_authorizing"] is False
        and r_lt1_deff["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        and r_lt1_deff["clustering_design_effect_deff"] is None
        and r_lt1_deff["exact_directional_confidence_certified"] is False
        and r_miss_cx["verdict"] == "FAIL_HARD_STOP"
        and r_miss_cx["exact_directional_confidence_certified"] is False
        and r_miss_cx["release_authorizing"] is False
        and r_miss_vk["verdict"] == "FAIL_HARD_STOP"
        and r_miss_vk["exact_directional_confidence_certified"] is False
        and r_miss_casp["verdict"] == "FAIL_HARD_STOP"
        and r_miss_casp["exact_directional_confidence_certified"] is False
        and r_miss_k_gt_n["verdict"] == "FAIL_HARD_STOP"
        and r_miss_k_gt_n["exact_directional_confidence_certified"] is False
    )
    cases.append({
        "case": "r12_b1_missing_or_invalid_sampling_spec_never_defaults_deff_1_bio_fail_preserved",
        "expected_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
        "actual_verdict": r_miss_spec["verdict"],
        "expected_token": "HOLD_GATE0V_MISSING_CLUSTERING_AND_INDEPENDENCE_SPEC",
        "hard_stops": r_miss_vk["hard_stops"][:2],
        "holds": r_miss_spec["holds"][:3],
        "passed": ok_r12_b1a,
    })

    # 54. R12-B1 (b): Sol's 6 -> 3 probe, mutated per_unit_counts sum mismatch, omitted per_unit_counts,
    #     and single-cell unit-matched vs multi-well conditional scopes!
    p_ref_r12 = build_passing_reference_payload(openislet_root=resolved_root)
    r_ref_r12 = evaluate_wholegraft_gate0v_and_stress_ap1903(p_ref_r12, openislet_root=resolved_root)

    p_units_3 = build_passing_reference_payload(openislet_root=resolved_root)
    p_units_3["clustering_and_independence_spec"]["independent_biological_units_n"] = 3
    r_units_3 = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_units_3), openislet_root=resolved_root)

    p_units_3_rebuilt = copy.deepcopy(p_units_3)
    reconcile_fixture_per_unit_counts(p_units_3_rebuilt, units_n=3)
    r_units_3_rebuilt = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_units_3_rebuilt), openislet_root=resolved_root)

    p_mut_part = build_passing_reference_payload(openislet_root=resolved_root)
    p_mut_part["gate0v_kill_stress_ap1903"]["normoxia_baseline"]["beta"]["per_unit_counts"]["ap1903_24h"][0]["n"] += 1
    r_mut_part = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_mut_part), openislet_root=resolved_root)

    p_omit_part = build_passing_reference_payload(openislet_root=resolved_root)
    p_omit_part["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["day28_persistence_by_lineage"]["beta"].pop("per_unit_counts", None)
    r_omit_part = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_omit_part), openislet_root=resolved_root)

    p_sc_pass = build_passing_reference_payload(
        independent_biological_units_n=6_000_000,
        independent_sampling_unit_class="INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT",
        openislet_root=resolved_root,
    )
    r_sc_pass = evaluate_wholegraft_gate0v_and_stress_ap1903(p_sc_pass, openislet_root=resolved_root)

    p_sc_under = build_passing_reference_payload(
        independent_biological_units_n=50,
        independent_sampling_unit_class="INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT",
        openislet_root=resolved_root,
    )
    r_sc_under = evaluate_wholegraft_gate0v_and_stress_ap1903(p_sc_under, openislet_root=resolved_root)

    ok_r12_b1b = bool(
        r_ref_r12["verdict"] == "PASS_WHOLEGRAFT_BANK_QUALIFICATION"
        and r_ref_r12["exact_directional_confidence_certified"] is True
        and r_ref_r12["confidence_scope"] == "CONDITIONAL_ON_EXTERNALLY_VALIDATED_WITHIN_WELL_INDEPENDENCE_DEFF_EQ_1"
        and r_units_3["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        and r_units_3["exact_directional_confidence_certified"] is False
        and r_units_3["release_authorizing"] is False
        and "HOLD_INSUFFICIENT_INDEPENDENT_BIOLOGICAL_UNITS" in r_units_3["holds"]
        and not _any_nested_cert_true(r_units_3)
        and r_units_3_rebuilt["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        and r_units_3_rebuilt["exact_directional_confidence_certified"] is False
        and "HOLD_INSUFFICIENT_INDEPENDENT_BIOLOGICAL_UNITS" in r_units_3_rebuilt["holds"]
        and r_mut_part["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        and r_mut_part["exact_directional_confidence_certified"] is False
        and r_mut_part["release_authorizing"] is False
        and "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS" in r_mut_part["holds"]
        and not _any_nested_cert_true(r_mut_part)
        and r_omit_part["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        and r_omit_part["exact_directional_confidence_certified"] is False
        and "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS" in r_omit_part["holds"]
        and r_sc_pass["verdict"] == "PASS_WHOLEGRAFT_BANK_QUALIFICATION"
        and r_sc_pass["exact_directional_confidence_certified"] is True
        and r_sc_pass["confidence_scope"] == "EXACT_INDEPENDENT_BINOMIAL_BONFERRONI_DEFF_EQ_1_UNIT_MATCHED"
        and r_sc_under["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        and r_sc_under["exact_directional_confidence_certified"] is False
        and "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS" in r_sc_under["holds"]
    )
    cases.append({
        "case": "r12_b1_units_6_to_3_and_partition_mismatch_held_and_single_cell_unit_matched",
        "expected_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
        "actual_verdict": r_units_3["verdict"],
        "expected_token": "HOLD_INSUFFICIENT_INDEPENDENT_BIOLOGICAL_UNITS",
        "hard_stops": [],
        "holds": r_units_3["holds"][:3],
        "passed": ok_r12_b1b,
    })

    # 55. R12-B2 (a): JSON number `1.00000000000000001` vs JSON string `"1.00000000000000001"` for
    #     `clustering_design_effect_deff` via file-based `--evaluate-lot` intake MUST BOTH fail closed
    #     identically with exit 2, HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE,
    #     exact_directional_confidence_certified=False, release_authorizing=False!
    with tempfile.TemporaryDirectory() as td_r12_b2:
        td_12 = Path(td_r12_b2)
        p_deff_str = build_passing_reference_payload(openislet_root=resolved_root)
        p_deff_str["clustering_and_independence_spec"]["clustering_design_effect_deff"] = "1.00000000000000001"
        _seal(p_deff_str)
        f_deff_str = td_12 / "deff_str.json"
        f_deff_str.write_text(json.dumps(p_deff_str), encoding="utf-8")

        p_deff_num_base = build_passing_reference_payload(openislet_root=resolved_root)
        p_deff_num_base["clustering_and_independence_spec"]["clustering_design_effect_deff"] = Decimal("1.00000000000000001")
        _seal(p_deff_num_base)
        raw_num_json = _canonical_json_dumps(p_deff_num_base)
        f_deff_num = td_12 / "deff_num.json"
        f_deff_num.write_text(raw_num_json, encoding="utf-8")

        r_ds, rc_ds = evaluate_wholegraft_gate0v_lot_file(f_deff_str, openislet_root=resolved_root)
        r_dn, rc_dn = evaluate_wholegraft_gate0v_lot_file(f_deff_num, openislet_root=resolved_root)

        # 56. R12-B2 (b): Lot file with nonzero float underflow (-1e-400) and signed-zero deff (-0.0) fail closed exit 2!
        f_lot_uf = td_12 / "lot_underflow.json"
        f_lot_uf.write_text(
            '{"qualification_tier": "BANK_QUALIFICATION", "probe_underflow": -1e-400}',
            encoding="utf-8",
        )
        r_luf, rc_luf = evaluate_wholegraft_gate0v_lot_file(f_lot_uf, openislet_root=resolved_root)

        p_deff_nz = build_passing_reference_payload(openislet_root=resolved_root)
        p_deff_nz["clustering_and_independence_spec"]["clustering_design_effect_deff"] = Decimal("-0.0")
        _seal(p_deff_nz)
        f_deff_nz = td_12 / "deff_neg_zero.json"
        f_deff_nz.write_text(
            json.dumps(p_deff_nz, default=lambda x: "-0.0").replace('"-0.0"', "-0.0"),
            encoding="utf-8",
        )
        r_dnz, rc_dnz = evaluate_wholegraft_gate0v_lot_file(f_deff_nz, openislet_root=resolved_root)

    ok_r12_b2a = bool(
        '"clustering_design_effect_deff":1.00000000000000001' in raw_num_json
        and rc_ds == 2
        and rc_dn == 2
        and r_ds["verdict"] == "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE"
        and r_dn["verdict"] == "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE"
        and r_ds["exact_directional_confidence_certified"] is False
        and r_dn["exact_directional_confidence_certified"] is False
        and r_ds["release_authorizing"] is False
        and r_dn["release_authorizing"] is False
        and r_ds["clustering_design_effect_deff"] == "1.00000000000000001"
        and r_dn["clustering_design_effect_deff"] == "1.00000000000000001"
    )
    cases.append({
        "case": "r12_b2_deff_json_number_vs_string_1p00000000000000001_identical_clustered_hold",
        "expected_verdict": "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE",
        "actual_verdict": r_dn["verdict"],
        "expected_token": "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE",
        "hard_stops": [],
        "holds": r_dn["holds"][:3],
        "passed": ok_r12_b2a,
    })

    ok_r12_b2b = bool(
        rc_luf == 2
        and r_luf["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        and r_luf["release_authorizing"] is False
        and "HOLD_GATE0V_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:NONZERO_FLOAT_UNDERFLOW_REJECTED" in (r_luf.get("holds") or [])
        and rc_dnz == 2
        and r_dnz["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        and r_dnz["exact_directional_confidence_certified"] is False
        and r_dnz["clustering_design_effect_deff"] is None
        and "INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE" in (r_dnz.get("holds") or [])
    )
    cases.append({
        "case": "r12_b2_lot_file_float_underflow_neg_1e_minus_400_and_signed_zero_rejected",
        "expected_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
        "actual_verdict": r_luf["verdict"],
        "expected_token": "NONZERO_FLOAT_UNDERFLOW_REJECTED",
        "hard_stops": [],
        "holds": (r_luf.get("holds") or [])[:3],
        "passed": ok_r12_b2b,
    })

    # ------------------------------------------------------------------
    # Round-13 Final-Closure Adversarial Regressions (R13-B1, B2, B3, B4, M1, M2)
    # ------------------------------------------------------------------
    # 57. R13-B1 (a): Single-cell mode MUST NEVER bypass submitted `per_unit_counts`!
    #     Adverse k=1 survivor in a supplemental stress arm's `per_unit_counts` (both viral-pos
    #     AND AP1903 72h while aggregate=0) triggers deterministic `FAIL_HARD_STOP`, while clean
    #     unexpected `per_unit_counts` in single-cell mode fails closed with
    #     `HOLD_UNEXPECTED_PER_UNIT_COUNTS_IN_SINGLE_CELL_MODE`!
    with tempfile.TemporaryDirectory() as td_r13:
        td_13 = Path(td_r13)
        b_r13 = build_passing_reference_payload(
            lot_id="BANK-R13-001",
            mcb_id="MCB-R13-001",
            product_variant_id="ISLET1_A4_ARM1B",
            qualification_tier="BANK_QUALIFICATION",
            openislet_root=resolved_root,
        )
        brec_r13 = build_authenticated_bank_qualification_record(
            mcb_id="MCB-R13-001",
            product_variant_id="ISLET1_A4_ARM1B",
            bank_lot_id="BANK-R13-001",
            bank_payload_sha256=b_r13["payload_sha256"],
        )
        st_r13 = td_13 / "store_r13.json"
        write_record_to_trusted_qualification_store(
            st_r13, brec_r13, category="bank_qualifications", archived_payload=b_r13
        )
        p_sc_clin = build_passing_reference_payload(
            lot_id="LOT-R13-SC-001",
            mcb_id="MCB-R13-001",
            product_variant_id="ISLET1_A4_ARM1B",
            qualification_tier="LOT_RELEASE_SURROGATE",
            bridged_mcb_qualification_sha256=brec_r13["sha256"],
            independent_biological_units_n=6_000_000,
            independent_sampling_unit_class="INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT",
            openislet_root=resolved_root,
        )
        r_sc_clean = evaluate_wholegraft_gate0v_and_stress_ap1903(
            p_sc_clin, trusted_qualification_store=st_r13, openislet_root=resolved_root
        )
        # Inject supplemental infected stress arm with aggregate=0 but per_unit_counts viral-pos k=1!
        p_sc_adv_vp = copy.deepcopy(p_sc_clin)
        sup_cvb = copy.deepcopy(b_r13["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"])
        sup_cvb["beta"]["per_unit_counts"]["infected_viral_pos_72h"][0]["k"] = 1
        p_sc_adv_vp["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"] = sup_cvb
        r_sc_adv_vp = evaluate_wholegraft_gate0v_and_stress_ap1903(
            _seal(p_sc_adv_vp), trusted_qualification_store=st_r13, openislet_root=resolved_root
        )
        # Inject supplemental arm with aggregate ap1903_72h=0 but per_unit_counts ap1903_72h k=1!
        p_sc_adv_a72 = copy.deepcopy(p_sc_clin)
        sup_er = copy.deepcopy(b_r13["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"])
        sup_er["beta"]["per_unit_counts"]["ap1903_72h"][0]["k"] = 1
        p_sc_adv_a72["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"] = sup_er
        r_sc_adv_a72 = evaluate_wholegraft_gate0v_and_stress_ap1903(
            _seal(p_sc_adv_a72), trusted_qualification_store=st_r13, openislet_root=resolved_root
        )
        # Clean unexpected per_unit_counts in single-cell mode -> HOLD_UNEXPECTED_PER_UNIT_COUNTS_IN_SINGLE_CELL_MODE!
        p_sc_unexp = copy.deepcopy(p_sc_clin)
        p_sc_unexp["gate0v_kill_stress_ap1903"]["normoxia_baseline"]["beta"]["per_unit_counts"] = copy.deepcopy(
            b_r13["gate0v_kill_stress_ap1903"]["normoxia_baseline"]["beta"]["per_unit_counts"]
        )
        r_sc_unexp = evaluate_wholegraft_gate0v_and_stress_ap1903(
            _seal(p_sc_unexp), trusted_qualification_store=st_r13, openislet_root=resolved_root
        )

        # 58. R13-B1 (b): Multi-well malformed row (missing/invalid unit_id or non-dict) BEFORE an
        #     adverse k=1 row MUST NEVER early-return or downgrade FAIL_HARD_STOP to HOLD!
        p_mw_mal_adv = copy.deepcopy(b_r13)
        vp_rows = p_mw_mal_adv["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["per_unit_counts"]["infected_viral_pos_72h"]
        vp_rows[0]["unit_id"] = ""  # malformed row 0 BEFORE valid adverse row 1!
        vp_rows[1]["k"] = 1
        r_mw_mal_adv = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_mw_mal_adv), openislet_root=resolved_root)

        p_mw_nondict_adv = copy.deepcopy(b_r13)
        vp_rows2 = p_mw_nondict_adv["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["per_unit_counts"]["infected_viral_pos_72h"]
        vp_rows2[0] = "not_a_dict_row"
        vp_rows2[2] = {"k": 1, "n": 1000}  # adverse row itself missing unit_id!
        r_mw_nondict_adv = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_mw_nondict_adv), openislet_root=resolved_root)

        # 59. R13-B2: Sol's impossible same-well subset (125 direct infected-vehicle survivors in WELL-01
        #     which has only 90 total veh_72h viable survivors, aggregate sums unchanged!) AND unit-ID set
        #     mismatch MUST fail closed with `HOLD_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION` (reconciled < 209)!
        p_sub_125_90 = copy.deepcopy(b_r13)
        div_rows = p_sub_125_90["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["per_unit_counts"]["direct_infected_veh_72h"]
        div_rows[0]["k"] = 125
        for _idx in range(1, len(div_rows)):
            div_rows[_idx]["k"] = 0
        r_sub_125_90 = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_sub_125_90), openislet_root=resolved_root)

        p_uid_mm = copy.deepcopy(b_r13)
        div_rows_uid = p_uid_mm["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["per_unit_counts"]["direct_infected_veh_72h"]
        for _idx, _row in enumerate(div_rows_uid):
            _row["unit_id"] = f"ALT-UNIT-{_idx + 1:02d}"
        r_uid_mm = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_uid_mm), openislet_root=resolved_root)

        # 60. R13-B3: Pure subtractive policy — `require_trusted_nw08_ocr_record=True` on `BANK_QUALIFICATION`
        #     rejected at direct admission (`HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION`),
        #     while preserving biological `FAIL_HARD_STOP` if `cxadr_ko_present=True`!
        p_bank_req_ocr = copy.deepcopy(b_r13)
        p_bank_req_ocr["require_trusted_nw08_ocr_record"] = True
        r_bank_req_ocr = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_bank_req_ocr), openislet_root=resolved_root)
        p_bank_req_ocr_fail = copy.deepcopy(p_bank_req_ocr)
        p_bank_req_ocr_fail["cxadr_ko_present"] = True
        r_bank_req_ocr_fail = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_bank_req_ocr_fail), openislet_root=resolved_root)

        # 61. R13-B4: Live PASS responses across ALL 3 tiers (Bank, Surrogate, Autologous Process Qual)
        #     carry explicit machine-readable `qualification_scope` & `physical_qualification_complete=False`
        #     on BOTH Python API and `--evaluate-lot` file intake!
        pq_r13 = build_authenticated_process_qualification_record(
            product_variant_id="ISLET1_D1_AUTO_V2_L1A_CIITA_CD64T_IL1RN",
            process_qual_id="PQ-R13-001",
        )
        write_record_to_trusted_qualification_store(st_r13, pq_r13, category="process_qualifications")
        p_auto_r13 = build_passing_reference_payload(
            lot_id="AUTO-R13-001",
            mcb_id="MCB-AUTO-R13-001",
            product_variant_id="ISLET1_D1_AUTO_V2_L1A_CIITA_CD64T_IL1RN",
            qualification_tier="AUTOLOGOUS_D1B_PROCESS_QUAL",
            process_qualification_ref_sha256=pq_r13["sha256"],
            openislet_root=resolved_root,
        )
        r_bank_pass_13 = evaluate_wholegraft_gate0v_and_stress_ap1903(b_r13, openislet_root=resolved_root)
        r_auto_pass_13 = evaluate_wholegraft_gate0v_and_stress_ap1903(
            p_auto_r13, trusted_qualification_store=st_r13, openislet_root=resolved_root
        )
        f_b_r13 = td_13 / "bank_pass_r13.json"
        f_b_r13.write_text(json.dumps(b_r13, sort_keys=True), encoding="utf-8")
        r_bank_file_13, rc_bank_file_13 = evaluate_wholegraft_gate0v_lot_file(f_b_r13, openislet_root=resolved_root)

        # 62. R13-M1 & R13-M2: JSON integer `-0` rejected fail-closed at `--evaluate-lot` intake AND
        #     unvalidated `deff` cleared to `None` on invalid spec (`units=3, deff=2.0`) AND missing
        #     estimand partition (`deff=1.0`), recording raw value in `submitted_clustering_design_effect_deff_unvalidated`!
        f_neg_int_lot = td_13 / "lot_neg_zero_int.json"
        f_neg_int_lot.write_text('{"qualification_tier": "BANK_QUALIFICATION", "probe_int": -0}', encoding="utf-8")
        r_nil, rc_nil = evaluate_wholegraft_gate0v_lot_file(f_neg_int_lot, openislet_root=resolved_root)

        p_u3_d2 = copy.deepcopy(b_r13)
        p_u3_d2["clustering_and_independence_spec"]["independent_biological_units_n"] = 3
        p_u3_d2["clustering_and_independence_spec"]["clustering_design_effect_deff"] = "2.0"
        r_u3_d2 = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_u3_d2), openislet_root=resolved_root)

        p_miss_part_d1 = copy.deepcopy(b_r13)
        p_miss_part_d1["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["day28_persistence_by_lineage"]["beta"].pop("per_unit_counts", None)
        r_mp_d1 = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_miss_part_d1), openislet_root=resolved_root)

    ok_r13_b1a = bool(
        r_sc_clean["verdict"] == "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE"
        and r_sc_adv_vp["verdict"] == "FAIL_HARD_STOP"
        and "HARD_STOP_ADVERSE_PER_UNIT_POST_AP1903_VIRAL_ESCAPE" in r_sc_adv_vp["hard_stops"]
        and "HOLD_UNEXPECTED_PER_UNIT_COUNTS_IN_SINGLE_CELL_MODE" in r_sc_adv_vp["holds"]
        and r_sc_adv_vp["exact_directional_confidence_certified"] is False
        and r_sc_adv_a72["verdict"] == "FAIL_HARD_STOP"
        and "HARD_STOP_ADVERSE_PER_UNIT_CONTRADICTS_AGGREGATE_OR_BREACHES_KILL_FLOOR" in r_sc_adv_a72["hard_stops"]
        and r_sc_unexp["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        and "HOLD_UNEXPECTED_PER_UNIT_COUNTS_IN_SINGLE_CELL_MODE" in r_sc_unexp["holds"]
        and r_sc_unexp["exact_directional_confidence_certified"] is False
    )
    cases.append({
        "case": "r13_b1_single_cell_adverse_per_unit_counts_supplemental_arm_hard_stop_and_clean_hold",
        "expected_verdict": "FAIL_HARD_STOP",
        "actual_verdict": r_sc_adv_vp["verdict"],
        "expected_token": "HARD_STOP_ADVERSE_PER_UNIT_POST_AP1903_VIRAL_ESCAPE",
        "hard_stops": r_sc_adv_vp["hard_stops"][:3],
        "holds": r_sc_unexp["holds"][:3],
        "passed": ok_r13_b1a,
    })

    ok_r13_b1b = bool(
        r_mw_mal_adv["verdict"] == "FAIL_HARD_STOP"
        and "HARD_STOP_ADVERSE_PER_UNIT_POST_AP1903_VIRAL_ESCAPE" in r_mw_mal_adv["hard_stops"]
        and r_mw_mal_adv["exact_directional_confidence_certified"] is False
        and r_mw_nondict_adv["verdict"] == "FAIL_HARD_STOP"
        and "HARD_STOP_ADVERSE_PER_UNIT_POST_AP1903_VIRAL_ESCAPE" in r_mw_nondict_adv["hard_stops"]
        and r_mw_nondict_adv["exact_directional_confidence_certified"] is False
    )
    cases.append({
        "case": "r13_b1_multi_well_malformed_row_before_adverse_row_preserves_hard_stop",
        "expected_verdict": "FAIL_HARD_STOP",
        "actual_verdict": r_mw_mal_adv["verdict"],
        "expected_token": "HARD_STOP_ADVERSE_PER_UNIT_POST_AP1903_VIRAL_ESCAPE",
        "hard_stops": r_mw_mal_adv["hard_stops"][:3],
        "holds": r_mw_mal_adv["holds"][:3],
        "passed": ok_r13_b1b,
    })

    sub_basis = r_sub_125_90["sampling_unit_basis"]
    ok_r13_b2 = bool(
        r_sub_125_90["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        and r_sub_125_90["exact_directional_confidence_certified"] is False
        and r_sub_125_90["release_authorizing"] is False
        and r_sub_125_90["clustering_design_effect_deff"] is None
        and "HOLD_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION" in r_sub_125_90["holds"]
        and sub_basis["all_sampling_units_reconciled"] is False
        and sub_basis["estimand_partitions_reconciled"] < sub_basis["estimand_partitions_checked"]
        and r_uid_mm["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        and r_uid_mm["exact_directional_confidence_certified"] is False
        and "HOLD_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION" in r_uid_mm["holds"]
    )
    cases.append({
        "case": "r13_b2_within_unit_direct_infected_veh_125_gt_90_and_unit_id_mismatch_hold",
        "expected_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
        "actual_verdict": r_sub_125_90["verdict"],
        "expected_token": "HOLD_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION",
        "hard_stops": r_sub_125_90["hard_stops"][:2],
        "holds": r_sub_125_90["holds"][:3],
        "passed": ok_r13_b2,
    })

    ok_r13_b3 = bool(
        r_bank_req_ocr["verdict"] == "HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION"
        and r_bank_req_ocr["release_authorizing"] is False
        and r_bank_req_ocr["gate0v_component_passed"] is False
        and "HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION" in r_bank_req_ocr["holds"]
        and r_bank_req_ocr_fail["verdict"] == "FAIL_HARD_STOP"
        and "HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION" in r_bank_req_ocr_fail["holds"]
    )
    cases.append({
        "case": "r13_b3_bank_require_trusted_nw08_ocr_rejected_at_direct_admission",
        "expected_verdict": "HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION",
        "actual_verdict": r_bank_req_ocr["verdict"],
        "expected_token": "HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION",
        "hard_stops": r_bank_req_ocr_fail["hard_stops"][:2],
        "holds": r_bank_req_ocr["holds"][:3],
        "passed": ok_r13_b3,
    })

    ok_r13_b4 = bool(
        r_bank_pass_13["verdict"] == "PASS_WHOLEGRAFT_BANK_QUALIFICATION"
        and r_bank_pass_13.get("qualification_scope") == QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL
        and r_bank_pass_13.get("physical_qualification_complete") is False
        and r_sc_clean["verdict"] == "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE"
        and r_sc_clean.get("qualification_scope") == QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL
        and r_sc_clean.get("physical_qualification_complete") is False
        and r_auto_pass_13["verdict"] == "PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL"
        and r_auto_pass_13.get("qualification_scope") == QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL
        and r_auto_pass_13.get("physical_qualification_complete") is False
        and rc_bank_file_13 == 0
        and r_bank_file_13.get("qualification_scope") == QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL
        and r_bank_file_13.get("physical_qualification_complete") is False
    )
    cases.append({
        "case": "r13_b4_live_pass_emits_qualification_scope_and_physical_qualification_complete_false_all_tiers",
        "expected_verdict": "PASS_WHOLEGRAFT_BANK_QUALIFICATION",
        "actual_verdict": r_bank_pass_13["verdict"],
        "expected_token": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
        "hard_stops": [],
        "holds": [],
        "passed": ok_r13_b4,
    })

    ok_r13_m12 = bool(
        rc_nil == 2
        and r_nil["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        and "INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE" in (r_nil.get("holds") or [])
        and "HOLD_GATE0V_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE" in (r_nil.get("holds") or [])
        and r_u3_d2["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        and r_u3_d2["clustering_design_effect_deff"] is None
        and r_u3_d2["submitted_clustering_design_effect_deff_unvalidated"] == "2.0"
        and r_u3_d2["sampling_unit_basis"]["clustering_design_effect_deff"] is None
        and r_u3_d2["sampling_unit_basis"]["submitted_clustering_design_effect_deff_unvalidated"] == "2.0"
        and r_mp_d1["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        and r_mp_d1["clustering_design_effect_deff"] is None
        and r_mp_d1["submitted_clustering_design_effect_deff_unvalidated"] == "1.0"
        and r_mp_d1["sampling_unit_basis"]["clustering_design_effect_deff"] is None
        and r_mp_d1["sampling_unit_basis"]["submitted_clustering_design_effect_deff_unvalidated"] == "1.0"
    )
    cases.append({
        "case": "r13_m1_m2_neg_zero_int_rejected_and_unvalidated_deff_cleared_to_none",
        "expected_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
        "actual_verdict": r_u3_d2["verdict"],
        "expected_token": "INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE",
        "hard_stops": [],
        "holds": (r_nil.get("holds") or [])[:3],
        "passed": ok_r13_m12,
    })

    # ------------------------------------------------------------------
    # Round-17 Blocker #1 Paired Offline Acceptance Suite (a)-(e):
    # Mandatory typed sampling-unit reconciliation for ALL release-critical
    # control & recovery counts (stressed-arm recovery calibrants, Day-28
    # uninfected negative controls, and Day-28 recovery calibrants)!
    # ------------------------------------------------------------------
    # 63. R17-B1 (a): Positive control with EVERY component's sampling-unit basis reconciled
    #     (both multi-well 209/209 bank fixture AND single-cell unit-matched bank fixture) -> PASS,
    #     exact_directional_confidence_certified=True, all_sampling_units_reconciled=True!
    p_r17_mw = build_passing_reference_payload(openislet_root=resolved_root)
    r_r17_mw = evaluate_wholegraft_gate0v_and_stress_ap1903(p_r17_mw, openislet_root=resolved_root)
    sb_r17_mw = r_r17_mw["sampling_unit_basis"]
    all_inf_arms_cal_rec = all(
        r_r17_mw["stress_ap1903_regimes"][reg]["lineages"][lin].get("spike_calibrant_sampling_units_reconciled") is True
        for reg in INFECTED_AP1903_REGIMES
        for lin in GRAFT_LINEAGES
    )
    all_d28_ctrl_and_cal_rec = all(
        (
            r_r17_mw["pathogen_results"][p]["lineage_results"][lin].get("uninfected_ctrl_sampling_unit_reconciled") is True
            and r_r17_mw["pathogen_results"][p]["lineage_results"][lin].get("spike_calibrant_sampling_units_reconciled") is True
        )
        for p in GATE0V_PATHOGENS
        for lin in GRAFT_LINEAGES
    )
    p_r17_sc = build_passing_reference_payload(
        independent_sampling_unit_class="INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT",
        independent_biological_units_n=5_200_000,
        openislet_root=resolved_root,
    )
    r_r17_sc = evaluate_wholegraft_gate0v_and_stress_ap1903(p_r17_sc, openislet_root=resolved_root)
    ok_r17_a = bool(
        r_r17_mw["verdict"] == "PASS_WHOLEGRAFT_BANK_QUALIFICATION"
        and r_r17_mw["exact_directional_confidence_certified"] is True
        and sb_r17_mw["all_sampling_units_reconciled"] is True
        and sb_r17_mw["estimand_partitions_checked"] == 209
        and sb_r17_mw["estimand_partitions_reconciled"] == 209
        and all_inf_arms_cal_rec
        and all_d28_ctrl_and_cal_rec
        and r_r17_sc["verdict"] == "PASS_WHOLEGRAFT_BANK_QUALIFICATION"
        and r_r17_sc["exact_directional_confidence_certified"] is True
        and r_r17_sc["sampling_unit_basis"]["all_sampling_units_reconciled"] is True
    )
    cases.append({
        "case": "r17_b1_a_positive_control_all_calibrants_and_neg_ctrl_reconciled_passes",
        "expected_verdict": "PASS_WHOLEGRAFT_BANK_QUALIFICATION",
        "actual_verdict": r_r17_mw["verdict"],
        "expected_token": None,
        "checked_partitions": sb_r17_mw["estimand_partitions_checked"],
        "reconciled_partitions": sb_r17_mw["estimand_partitions_reconciled"],
        "hard_stops": [],
        "holds": [],
        "passed": ok_r17_a,
    })

    # 64. R17-B1 (b): Missing or mismatched stressed-arm recovery calibrant sampling-unit reconciliation
    #     (`spike_calibrant` or `fragile_infected_spike_calibrant`) -> HOLD, certified=False, reconciled=False!
    p_r17_b_h = copy.deepcopy(p_r17_mw)
    p_r17_b_h["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["per_unit_counts"].pop("spike_calibrant", None)
    r_r17_b_h = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_r17_b_h), openislet_root=resolved_root)

    p_r17_b_f = copy.deepcopy(p_r17_mw)
    p_r17_b_f["gate0v_kill_stress_ap1903"]["active_or_persistent_hcmv_infection"]["pericyte"]["per_unit_counts"].pop("fragile_infected_spike_calibrant", None)
    r_r17_b_f = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_r17_b_f), openislet_root=resolved_root)

    p_r17_b_mm = copy.deepcopy(p_r17_mw)
    p_r17_b_mm["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["per_unit_counts"]["spike_calibrant"][0]["k"] -= 1
    r_r17_b_mm = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_r17_b_mm), openislet_root=resolved_root)

    ok_r17_b = all(
        (
            r_x["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
            and r_x["exact_directional_confidence_certified"] is False
            and r_x["release_authorizing"] is False
            and r_x["clustering_design_effect_deff"] is None
            and r_x["sampling_unit_basis"]["all_sampling_units_reconciled"] is False
            and r_x["sampling_unit_basis"]["estimand_partitions_reconciled"] == 208
            and r_x["sampling_unit_basis"]["estimand_partitions_checked"] == 209
            and "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS" in r_x["holds"]
        )
        for r_x in (r_r17_b_h, r_r17_b_f, r_r17_b_mm)
    )
    cases.append({
        "case": "r17_b1_b_missing_or_mismatched_stressed_recovery_calibrant_partition_holds",
        "expected_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
        "actual_verdict": r_r17_b_h["verdict"],
        "expected_token": "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS",
        "hard_stops": [],
        "holds": r_r17_b_h["holds"][:3],
        "passed": ok_r17_b,
    })

    # 65. R17-B1 (c): Missing or mismatched Day-28 negative-control sampling-unit reconciliation
    #     (multi-well missing/mismatch AND single-cell `independent_biological_units_n < uninfected_ctrl_scored_n`)
    #     -> HOLD, exact_directional_confidence_certified=False, all_sampling_units_reconciled=False!
    p_r17_c_miss = copy.deepcopy(p_r17_mw)
    p_r17_c_miss["gate0v_b_infectious_challenge"]["pathogens"]["cvb3"]["day28_persistence_by_lineage"]["alpha"].pop("uninfected_ctrl_per_unit_counts", None)
    r_r17_c_miss = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_r17_c_miss), openislet_root=resolved_root)

    p_r17_c_mm = copy.deepcopy(p_r17_mw)
    p_r17_c_mm["gate0v_b_infectious_challenge"]["pathogens"]["cvb3"]["day28_persistence_by_lineage"]["alpha"]["uninfected_ctrl_fp_k"] = 20
    # Deliberately do NOT reconcile uninfected_ctrl_per_unit_counts -> aggregate-vs-unit mismatch!
    r_r17_c_mm = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_r17_c_mm), openislet_root=resolved_root)

    p_r17_c_sc = copy.deepcopy(p_r17_sc)
    p_r17_c_sc["gate0v_b_infectious_challenge"]["pathogens"]["cvb3"]["day28_persistence_by_lineage"]["alpha"]["uninfected_ctrl_scored_n"] = 5_300_000
    r_r17_c_sc = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_r17_c_sc), openislet_root=resolved_root)

    ok_r17_c = bool(
        all(
            (
                r_x["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
                and r_x["exact_directional_confidence_certified"] is False
                and r_x["release_authorizing"] is False
                and r_x["clustering_design_effect_deff"] is None
                and r_x["sampling_unit_basis"]["all_sampling_units_reconciled"] is False
                and "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS" in r_x["holds"]
            )
            for r_x in (r_r17_c_miss, r_r17_c_mm, r_r17_c_sc)
        )
        and r_r17_c_miss["sampling_unit_basis"]["estimand_partitions_reconciled"] == 208
        and r_r17_c_mm["sampling_unit_basis"]["estimand_partitions_reconciled"] == 208
    )
    cases.append({
        "case": "r17_b1_c_missing_or_mismatched_day28_neg_ctrl_sampling_unit_basis_holds",
        "expected_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
        "actual_verdict": r_r17_c_miss["verdict"],
        "expected_token": "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS",
        "hard_stops": [],
        "holds": r_r17_c_miss["holds"][:3],
        "passed": ok_r17_c,
    })

    # 66. R17-B1 (d): Missing or mismatched Day-28 recovery calibrant sampling-unit reconciliation
    #     (`spike_calibrant_per_unit_counts`, `fragile_infected_spike_per_unit_counts`, or unit-ID mismatch)
    #     -> HOLD, exact_directional_confidence_certified=False, all_sampling_units_reconciled=False!
    p_r17_d_h = copy.deepcopy(p_r17_mw)
    p_r17_d_h["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["day28_persistence_by_lineage"]["beta"].pop("spike_calibrant_per_unit_counts", None)
    r_r17_d_h = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_r17_d_h), openislet_root=resolved_root)

    p_r17_d_f = copy.deepcopy(p_r17_mw)
    p_r17_d_f["gate0v_b_infectious_challenge"]["pathogens"]["hcmv"]["day28_persistence_by_lineage"]["plvap_iec"].pop("fragile_infected_spike_per_unit_counts", None)
    r_r17_d_f = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_r17_d_f), openislet_root=resolved_root)

    p_r17_d_uid = copy.deepcopy(p_r17_mw)
    for _idx_u, _row_u in enumerate(
        p_r17_d_uid["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["day28_persistence_by_lineage"]["beta"]["spike_calibrant_per_unit_counts"]
    ):
        _row_u["unit_id"] = f"UNLINKED-CAL-UNIT-{_idx_u + 1:02d}"
    r_r17_d_uid = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_r17_d_uid), openislet_root=resolved_root)

    ok_r17_d = bool(
        all(
            (
                r_x["verdict"] == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
                and r_x["exact_directional_confidence_certified"] is False
                and r_x["release_authorizing"] is False
                and r_x["clustering_design_effect_deff"] is None
                and r_x["sampling_unit_basis"]["all_sampling_units_reconciled"] is False
                and r_x["sampling_unit_basis"]["estimand_partitions_reconciled"] == 208
                and r_x["sampling_unit_basis"]["estimand_partitions_checked"] == 209
            )
            for r_x in (r_r17_d_h, r_r17_d_f, r_r17_d_uid)
        )
        and "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS" in r_r17_d_h["holds"]
        and "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS" in r_r17_d_f["holds"]
        and "HOLD_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION" in r_r17_d_uid["holds"]
    )
    cases.append({
        "case": "r17_b1_d_missing_or_mismatched_day28_recovery_calibrant_partition_holds",
        "expected_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
        "actual_verdict": r_r17_d_h["verdict"],
        "expected_token": "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS",
        "hard_stops": [],
        "holds": r_r17_d_h["holds"][:3],
        "passed": ok_r17_d,
    })

    # 67. R17-B1 (e): Biological FAIL_HARD_STOP co-occurring with missing stressed/Day-28 recovery
    #     calibrant AND negative-control reconciliation MUST preserve FAIL_HARD_STOP precedence while
    #     setting exact_directional_confidence_certified=False and all_sampling_units_reconciled=False!
    def _strip_all_three_cal_and_ctrl(pl_obj: Dict[str, Any]) -> None:
        pl_obj["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["per_unit_counts"].pop("spike_calibrant", None)
        pl_obj["gate0v_b_infectious_challenge"]["pathogens"]["cvb3"]["day28_persistence_by_lineage"]["alpha"].pop("uninfected_ctrl_per_unit_counts", None)
        pl_obj["gate0v_b_infectious_challenge"]["pathogens"]["hcmv"]["day28_persistence_by_lineage"]["plvap_iec"].pop("fragile_infected_spike_per_unit_counts", None)

    p_r17_e_vp = copy.deepcopy(p_r17_mw)
    _strip_all_three_cal_and_ctrl(p_r17_e_vp)
    p_r17_e_vp["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["post_ap1903_viable_viral_pos_k"] = 1
    r_r17_e_vp = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_r17_e_vp), openislet_root=resolved_root)

    p_r17_e_d28 = copy.deepcopy(p_r17_mw)
    _strip_all_three_cal_and_ctrl(p_r17_e_d28)
    p_r17_e_d28["gate0v_b_infectious_challenge"]["pathogens"]["cvb3"]["day28_persistence_by_lineage"]["alpha"]["stage2_confirmed_infectious_k"] = 1
    r_r17_e_d28 = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_r17_e_d28), openislet_root=resolved_root)

    p_r17_e_cx = copy.deepcopy(p_r17_mw)
    _strip_all_three_cal_and_ctrl(p_r17_e_cx)
    p_r17_e_cx["cxadr_ko_present"] = True
    r_r17_e_cx = evaluate_wholegraft_gate0v_and_stress_ap1903(_seal(p_r17_e_cx), openislet_root=resolved_root)

    ok_r17_e = all(
        (
            r_x["verdict"] == "FAIL_HARD_STOP"
            and r_x["exact_directional_confidence_certified"] is False
            and r_x["release_authorizing"] is False
            and r_x["sampling_unit_basis"]["all_sampling_units_reconciled"] is False
            and "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS" in r_x["holds"]
            and len(r_x["hard_stops"]) >= 1
        )
        for r_x in (r_r17_e_vp, r_r17_e_d28, r_r17_e_cx)
    )
    cases.append({
        "case": "r17_b1_e_biological_hard_stop_preserved_when_calibrant_and_neg_ctrl_reconciliation_missing",
        "expected_verdict": "FAIL_HARD_STOP",
        "actual_verdict": r_r17_e_vp["verdict"],
        "expected_token": "POST_AP1903_VIABLE_VIRAL_SURVIVOR",
        "hard_stops": r_r17_e_vp["hard_stops"][:3],
        "holds": r_r17_e_vp["holds"][:3],
        "passed": ok_r17_e,
    })

    passed_n = sum(1 for c in cases if c["passed"])
    return {
        "total_cases": len(cases),
        "passed_cases": passed_n,
        "all_passed": passed_n == len(cases),
        "cases": cases,
    }


def _normalize_receipt_for_portable_check(receipt_doc: Dict[str, Any]) -> Dict[str, Any]:
    """
    B8 Portable `--check` Projection:
    Strips volatile runtime metadata (`python_version`) and normalizes ONLY the known
    public-bundle vs full-repo redaction metadata (`bundle_mode`, `protected_manifest_source`,
    `facts_source`, and the two publisher-redacted study digests `17375075.json`/`39571901.json`
    ONLY AFTER verifying `matches is True` against the exact mode-specific pin!).
    ALL scientific outputs, ALL 20 `matches` flags, ALL 18 shared file hashes, ALL Playbook §4.1.20
    hashes, `post_render_bytes`, Decimal bounds, adversarial tests, and 3D FVM unrounded floats
    MUST match 100% identically!
    """
    proj = copy.deepcopy(receipt_doc)
    proj.pop("python_version", None)
    part_c = proj.get("part_c_protected_invariance_and_ceg_delta_diff")
    if isinstance(part_c, dict):
        part_c.pop("bundle_mode", None)
        part_c.pop("protected_manifest_source", None)
        r4 = part_c.get("r4_playbook_sec4120_dec114_and_renderer_compatibility")
        if isinstance(r4, dict):
            rd_rep = r4.get("render_documentation_protocol_doc_replay")
            if isinstance(rd_rep, dict):
                rd_rep.pop("facts_source", None)
        pf = part_c.get("protected_files")
        if isinstance(pf, dict):
            for redacted_rel in PUBLIC_BUNDLE_REDACTED_FILES_SHA256:
                entry = pf.get(redacted_rel)
                if isinstance(entry, dict) and entry.get("matches") is True:
                    # Only normalize if the digest is one of the two exact known pins (private or public-redacted)
                    valid_pair = {
                        IIP0035_17_PROTECTED_FILES_SHA256[redacted_rel],
                        PUBLIC_BUNDLE_REDACTED_FILES_SHA256[redacted_rel],
                    }
                    if entry.get("expected_sha256") in valid_pair and entry.get("actual_sha256") in valid_pair:
                        entry["category"] = "mode_verified_redacted_study_pin"
                        entry["expected_sha256"] = "<mode_verified_pin>"
                        entry["actual_sha256"] = "<mode_verified_pin>"
    return proj


def evaluate_wholegraft_gate0v_lot_file(
    lot_json_path: Path | str,
    *,
    trusted_qualification_store: Path | str | None = None,
    openislet_root: Path | None = None,
) -> Tuple[Dict[str, Any], int]:
    """
    R09-B1 + R10-B2 + R11-B4 Fail-closed standalone file intake boundary using `strict_json_load_file`:
    rejects missing files, nesting depth > MAX_JSON_NESTING_DEPTH (64), parser RecursionError,
    duplicate JSON object keys (at any nesting depth), non-standard NaN/Infinity constants,
    out-of-range integers, and syntax/type errors with structured HOLD (exit 2, release_authorizing=False).
    """
    lp = Path(lot_json_path)
    if not lp.is_file():
        return (
            {
                "verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
                "release_authorizing": False,
                "qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
                "physical_qualification_complete": False,
                "hard_stops": [],
                "holds": [f"HOLD_GATE0V_LOT_FILE_NOT_FOUND:{lp.name}"],
            },
            2,
        )
    try:
        lot_payload = strict_json_load_file(lp, max_int_abs=MAX_STRICT_JSON_INT_ABS, max_depth=MAX_JSON_NESTING_DEPTH)
    except StrictJSONDecodeError as exc:
        strict_holds = [
            "HOLD_INVALID_INPUT_JSON",
            f"HOLD_GATE0V_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:{exc.reason_code}",
            f"HOLD_GATE0V_MALFORMED_LOT_JSON:{type(exc).__name__}",
        ]
        if exc.reason_code in ("INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE", "NONZERO_FLOAT_UNDERFLOW_REJECTED"):
            strict_holds.append(exc.reason_code)
        return (
            {
                "verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
                "release_authorizing": False,
                "qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
                "physical_qualification_complete": False,
                "hard_stops": [],
                "holds": strict_holds,
            },
            2,
        )
    except (OSError, UnicodeDecodeError, json.JSONDecodeError, TypeError, ValueError, OverflowError, RecursionError) as exc:
        err_holds = ["HOLD_INVALID_INPUT_JSON", f"HOLD_GATE0V_MALFORMED_LOT_JSON:{type(exc).__name__}"]
        if isinstance(exc, RecursionError):
            err_holds.insert(1, "HOLD_GATE0V_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED")
        return (
            {
                "verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
                "release_authorizing": False,
                "qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
                "physical_qualification_complete": False,
                "hard_stops": [],
                "holds": err_holds,
            },
            2,
        )
    res = evaluate_wholegraft_gate0v_and_stress_ap1903(
        lot_payload,
        trusted_qualification_store=trusted_qualification_store,
        openislet_root=openislet_root,
    )
    if res["verdict"] in GATE0V_ALL_PASS_VERDICTS:
        return res, 0
    if res["verdict"] == "FAIL_HARD_STOP":
        return res, 3
    return res, 2


_NW08_OCR_BINDING_REQUIRED_KEYS: Tuple[str, ...] = (
    "lot_id",
    "mcb_id",
    "product_variant_id",
    "lot_payload_sha256",
    "measurement_record_id",
    "measurement_evidence_sha256",
    "measurement_timestamp_utc",
    "ocr_record_sha256",
)

_NW08_OCR_ALLOWED_KEYS = frozenset({
    "route_id",
    "measured_ocr",
    "uncertainty_se",
    "baseline_min_face_mmhg",
    "baseline_vasc_ocr_mult",
    "p_bed_mmhg",
    "local_3d_slope_mmhg_per_pct",
    "z_one_sided_95",
    "floor_mmhg",
    "always_solve_3d",
    "ocr_uncertainty_model",
    "ocr_replicates_n",
    "ocr_degrees_of_freedom",
    "ocr_uncertainty_provenance",
    "measured_ocr_u95_override",
    "force_mesh_convergence_check",
    *_NW08_OCR_BINDING_REQUIRED_KEYS,
})


def evaluate_nw08_measured_ocr_record(
    req: Any,
    *,
    openislet_root: Path | None = None,
    coupled_lot_binding: Dict[str, Any] | None = None,
    trusted_qualification_store: Path | str | None = None,
) -> Tuple[Dict[str, Any], int]:
    """
    R10-B1 + R11-B1 + R11-B2 + R11-B4 Core in-memory & file-shared NW-08 measured-OCR evaluator:
      - In coupled composite release mode (`coupled_lot_binding is not None`), enforces cryptographic
        and structural binding to the lot and optional/required external QA store BEFORE dispatching
        the live 3D FVM solver.
      - In standalone unbound diagnostic mode (`coupled_lot_binding is None`), ALWAYS forces
        `release_authorizing = False` at top-level and recursively across all nested sub-dicts,
        recording floor clearance strictly in `solver_cleared_oxygen_floor_diagnostic`.
    """
    is_coupled = coupled_lot_binding is not None
    binding_mode = "COUPLED_COMPOSITE_LOT_BOUND" if is_coupled else "STANDALONE_UNBOUND_DIAGNOSTIC_ONLY"

    def _hold(holds_list: List[str], binding_meta: Dict[str, Any] | None = None) -> Tuple[Dict[str, Any], int]:
        out: Dict[str, Any] = {
            "adjudicated_verdict": "HOLD",
            "release_authorizing": False,
            "qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
            "physical_qualification_complete": False,
            "solver_cleared_oxygen_floor_diagnostic": False,
            "solver_executed": False,
            "binding_mode": binding_mode,
            "lot_binding_verified": False,
            "holds": holds_list,
        }
        if binding_meta is not None:
            out["nw08_lot_binding"] = binding_meta
        return out, 2

    if not isinstance(req, dict):
        return _hold(["HOLD_NW08_OCR_PAYLOAD_NOT_OBJECT"])
    extra_keys = sorted(set(req.keys()) - _NW08_OCR_ALLOWED_KEYS)
    if extra_keys:
        return _hold([f"HOLD_NW08_OCR_UNRECOGNIZED_KEYS:{','.join(extra_keys)}"])
    for rk in ("route_id", "measured_ocr", "uncertainty_se"):
        if rk not in req:
            return _hold([f"HOLD_NW08_OCR_MISSING_REQUIRED_KEY:{rk}"])
    if not isinstance(req["route_id"], str) or not req["route_id"].strip():
        return _hold(["HOLD_NW08_OCR_INVALID_ROUTE_ID_TYPE"])
    if "always_solve_3d" in req and not isinstance(req["always_solve_3d"], bool):
        return _hold(["HOLD_NW08_OCR_INVALID_ALWAYS_SOLVE_3D_TYPE"])
    if "force_mesh_convergence_check" in req and not isinstance(req["force_mesh_convergence_check"], bool):
        return _hold(["HOLD_NW08_OCR_INVALID_FORCE_MESH_CONVERGENCE_CHECK_TYPE"])

    resolved_root = openislet_root.resolve() if openislet_root is not None else _resolve_roots(None, None)[0]

    # Validate self-digest and any optional binding fields even in standalone mode whenever supplied
    standalone_binding_holds: List[str] = []
    if "ocr_record_sha256" in req:
        recomp_self = _safe_nw08_ocr_record_sha256(req)
        if not (_is_valid_sha256_hex(req.get("ocr_record_sha256")) and recomp_self == req.get("ocr_record_sha256")):
            standalone_binding_holds.append("HOLD_NW08_OCR_RECORD_SHA256_MISMATCH")
    if "measurement_evidence_sha256" in req and not _is_valid_sha256_hex(req.get("measurement_evidence_sha256")):
        standalone_binding_holds.append("HOLD_NW08_COUPLED_INVALID_MEASUREMENT_EVIDENCE_SHA256")
    if "lot_payload_sha256" in req and not _is_valid_sha256_hex(req.get("lot_payload_sha256")):
        standalone_binding_holds.append("HOLD_NW08_COUPLED_INVALID_LOT_PAYLOAD_SHA256")
    if "measurement_record_id" in req and not _is_valid_identifier(req.get("measurement_record_id")):
        standalone_binding_holds.append("HOLD_NW08_COUPLED_INVALID_MEASUREMENT_RECORD_ID")
    if "measurement_timestamp_utc" in req and _parse_strict_utc_timestamp(req.get("measurement_timestamp_utc")) is None:
        standalone_binding_holds.append("HOLD_NW08_COUPLED_INVALID_MEASUREMENT_TIMESTAMP_UTC")
    if "lot_id" in req and not _is_valid_identifier(req.get("lot_id")):
        standalone_binding_holds.append("HOLD_NW08_COUPLED_INVALID_LOT_ID")
    if "mcb_id" in req and not _is_valid_identifier(req.get("mcb_id")):
        standalone_binding_holds.append("HOLD_NW08_COUPLED_INVALID_MCB_ID")
    if "product_variant_id" in req:
        pvid_chk = req.get("product_variant_id")
        if not _is_clean_nonempty_str(pvid_chk) or resolve_canonical_product_variant(pvid_chk, openislet_root=resolved_root) is None:
            standalone_binding_holds.append("HOLD_NW08_COUPLED_UNREGISTERED_PRODUCT_VARIANT_ID")

    nw08_lot_binding_meta: Dict[str, Any] = {
        "binding_mode": binding_mode,
        "binding_verified": False,
        "external_ocr_store_verification": None,
    }

    if is_coupled:
        bind_holds: List[str] = list(standalone_binding_holds)

        def _add_bh(tok: str) -> None:
            if tok not in bind_holds:
                bind_holds.append(tok)

        if not isinstance(coupled_lot_binding, dict):
            _add_bh("HOLD_NW08_COUPLED_INVALID_LOT_BINDING_CONTEXT")
            return _hold(bind_holds, nw08_lot_binding_meta)

        exp_lot_id = coupled_lot_binding.get("lot_id")
        exp_mcb_id = coupled_lot_binding.get("mcb_id")
        exp_pvid = coupled_lot_binding.get("canonical_product_variant_id")
        exp_lot_sha = coupled_lot_binding.get("computed_payload_sha256")
        exp_lot_sha_ok = bool(coupled_lot_binding.get("payload_sha256_verified") is True and _is_valid_sha256_hex(exp_lot_sha))
        exp_route = coupled_lot_binding.get("planned_nw08_route_id")
        exp_route_errs = list(coupled_lot_binding.get("planned_nw08_route_errors") or [])
        exp_ev_sha = coupled_lot_binding.get("planned_nw08_measurement_evidence_sha256")
        exp_not_before = coupled_lot_binding.get("planned_nw08_measurement_not_before_utc")
        req_trusted_ocr = bool(coupled_lot_binding.get("require_trusted_nw08_ocr_record") is True)

        for re_tok in exp_route_errs:
            _add_bh(str(re_tok))
        if not exp_route_errs:
            if not _is_clean_nonempty_str(exp_route):
                _add_bh("HOLD_NW08_COUPLED_LOT_MISSING_PLANNED_ROUTE")
            elif exp_route not in CANONICAL_NW08_ROUTE_IDS:
                _add_bh("HOLD_NW08_COUPLED_INVALID_LOT_PLANNED_ROUTE")
        if not exp_lot_sha_ok:
            _add_bh("HOLD_NW08_COUPLED_LOT_PAYLOAD_SHA256_UNVERIFIED")
        if not _is_valid_identifier(exp_lot_id):
            _add_bh("HOLD_NW08_COUPLED_LOT_MISSING_VALID_LOT_ID")
        if not _is_valid_identifier(exp_mcb_id):
            _add_bh("HOLD_NW08_COUPLED_LOT_MISSING_VALID_MCB_ID")
        if not _is_clean_nonempty_str(exp_pvid):
            _add_bh("HOLD_NW08_COUPLED_LOT_MISSING_CANONICAL_PRODUCT_VARIANT_ID")

        for bk in _NW08_OCR_BINDING_REQUIRED_KEYS:
            if bk not in req:
                _add_bh(f"HOLD_NW08_COUPLED_MISSING_REQUIRED_BINDING_KEY:{bk}")

        if "lot_id" in req and _is_valid_identifier(exp_lot_id) and req.get("lot_id") != exp_lot_id:
            _add_bh("HOLD_NW08_COUPLED_LOT_ID_MISMATCH")
        if "mcb_id" in req and _is_valid_identifier(exp_mcb_id) and req.get("mcb_id") != exp_mcb_id:
            _add_bh("HOLD_NW08_COUPLED_MCB_ID_MISMATCH")
        if "product_variant_id" in req and _is_clean_nonempty_str(exp_pvid):
            if not _is_clean_nonempty_str(req.get("product_variant_id")) or req.get("product_variant_id") != exp_pvid:
                _add_bh("HOLD_NW08_COUPLED_PRODUCT_VARIANT_ID_MISMATCH")
        if _is_clean_nonempty_str(exp_route) and exp_route in CANONICAL_NW08_ROUTE_IDS and req.get("route_id") != exp_route:
            _add_bh("HOLD_NW08_COUPLED_ROUTE_ID_MISMATCH")
        if "lot_payload_sha256" in req and exp_lot_sha_ok and req.get("lot_payload_sha256") != exp_lot_sha:
            _add_bh("HOLD_NW08_COUPLED_STALE_OR_MISMATCHED_LOT_PAYLOAD_SHA256")
        if (
            exp_ev_sha is not None
            and _is_valid_sha256_hex(exp_ev_sha)
            and "measurement_evidence_sha256" in req
            and req.get("measurement_evidence_sha256") != exp_ev_sha
        ):
            _add_bh("HOLD_NW08_COUPLED_MEASUREMENT_EVIDENCE_SHA256_MISMATCH")
        if exp_not_before is not None and "measurement_timestamp_utc" in req:
            nb_dt = _parse_strict_utc_timestamp(exp_not_before)
            meas_dt = _parse_strict_utc_timestamp(req.get("measurement_timestamp_utc"))
            if nb_dt is not None and meas_dt is not None and meas_dt < nb_dt:
                _add_bh("HOLD_NW08_COUPLED_STALE_MEASUREMENT_TIMESTAMP_UTC")

        store_ok, store_errs, store_meta = resolve_and_verify_trusted_nw08_ocr_record(
            trusted_qualification_store,
            expected_ocr_record_sha256=req.get("ocr_record_sha256"),
            submitted_ocr_record=req,
            require_store_entry=req_trusted_ocr,
        )
        for se_tok in store_errs:
            _add_bh(se_tok)

        nw08_lot_binding_meta = {
            "binding_mode": binding_mode,
            "binding_verified": bool(len(bind_holds) == 0 and store_ok),
            "expected_lot_id": exp_lot_id if isinstance(exp_lot_id, str) else None,
            "supplied_lot_id": req.get("lot_id") if isinstance(req.get("lot_id"), str) else None,
            "expected_mcb_id": exp_mcb_id if isinstance(exp_mcb_id, str) else None,
            "supplied_mcb_id": req.get("mcb_id") if isinstance(req.get("mcb_id"), str) else None,
            "expected_product_variant_id": exp_pvid if isinstance(exp_pvid, str) else None,
            "supplied_product_variant_id": req.get("product_variant_id") if isinstance(req.get("product_variant_id"), str) else None,
            "expected_planned_route_id": exp_route if isinstance(exp_route, str) else None,
            "supplied_route_id": req.get("route_id") if isinstance(req.get("route_id"), str) else None,
            "expected_lot_payload_sha256": exp_lot_sha if isinstance(exp_lot_sha, str) else None,
            "supplied_lot_payload_sha256": req.get("lot_payload_sha256") if isinstance(req.get("lot_payload_sha256"), str) else None,
            "measurement_record_id": req.get("measurement_record_id") if isinstance(req.get("measurement_record_id"), str) else None,
            "measurement_evidence_sha256": req.get("measurement_evidence_sha256") if isinstance(req.get("measurement_evidence_sha256"), str) else None,
            "measurement_timestamp_utc": req.get("measurement_timestamp_utc") if isinstance(req.get("measurement_timestamp_utc"), str) else None,
            "ocr_record_sha256": req.get("ocr_record_sha256") if isinstance(req.get("ocr_record_sha256"), str) else None,
            "external_ocr_store_verification": store_meta,
        }
        if bind_holds or not store_ok:
            return _hold(bind_holds, nw08_lot_binding_meta)
    elif standalone_binding_holds:
        return _hold(standalone_binding_holds, nw08_lot_binding_meta)

    try:
        kwargs: Dict[str, Any] = {
            "openislet_root": resolved_root,
            "_require_explicit_model_for_positive_se": True,
        }
        for opt_k in (
            "baseline_min_face_mmhg",
            "baseline_vasc_ocr_mult",
            "p_bed_mmhg",
            "local_3d_slope_mmhg_per_pct",
            "z_one_sided_95",
            "floor_mmhg",
            "always_solve_3d",
            "ocr_uncertainty_model",
            "ocr_replicates_n",
            "ocr_degrees_of_freedom",
            "ocr_uncertainty_provenance",
            "measured_ocr_u95_override",
            "force_mesh_convergence_check",
        ):
            if opt_k in req and req[opt_k] is not None:
                kwargs[opt_k] = req[opt_k]
        res = dispatch_and_solve_nw08_measured_ocr(
            req["route_id"],
            req["measured_ocr"],
            req["uncertainty_se"],
            **kwargs,
        )
    except (TypeError, ValueError, OverflowError, RuntimeError, RecursionError) as exc:
        exc_msg = str(exc)
        err_holds: List[str] = []
        if "INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE" in exc_msg:
            err_holds.append("INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE")
        if "NONZERO_FLOAT_UNDERFLOW_REJECTED" in exc_msg:
            err_holds.append("NONZERO_FLOAT_UNDERFLOW_REJECTED")
        if ":" in exc_msg:
            lead_tok = exc_msg.split(":", 1)[0].strip()
            if lead_tok.startswith("HOLD_NW08_") and lead_tok not in err_holds:
                err_holds.append(lead_tok)
        err_holds.append(f"HOLD_NW08_OCR_INVALID_PARAMETERS:{type(exc).__name__}:{exc_msg}")
        return _hold(err_holds, nw08_lot_binding_meta)

    verdict_str = str(res.get("adjudicated_verdict") or "HOLD")
    cleared_floor = bool(verdict_str == "PASS" and res.get("passes_15mmhg_floor_unrounded") is True)
    res["binding_mode"] = binding_mode
    res["lot_binding_verified"] = bool(is_coupled)
    res["nw08_lot_binding"] = nw08_lot_binding_meta
    res["solver_cleared_oxygen_floor_diagnostic"] = cleared_floor
    res["qualification_scope"] = QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL
    res["physical_qualification_complete"] = False
    # R11-B2: Standalone unbound diagnostic output MUST NEVER carry `release_authorizing = True`
    # (at top-level OR inside any nested sub-dict!). Even in coupled mode, clinical release
    # authorization belongs strictly to the composite release wrapper (`evaluate_composite_clinical_release`),
    # while this component reports `nw08_component_cleared_for_coupled_lot`.
    res["release_authorizing"] = False
    if is_coupled:
        res["nw08_component_cleared_for_coupled_lot"] = cleared_floor
    else:
        _enforce_release_authorizing_false_iterative(res)
    if verdict_str == "PASS":
        rc = 0
    elif verdict_str == "FAIL":
        rc = 3
    else:
        rc = 2
    return res, rc


def evaluate_nw08_measured_ocr_file(
    ocr_json_path: Path | str,
    *,
    openislet_root: Path | None = None,
    coupled_lot_binding: Dict[str, Any] | None = None,
    trusted_qualification_store: Path | str | None = None,
) -> Tuple[Dict[str, Any], int]:
    """
    R09-M1 + R09-B1 + R10-B1 + R10-B2 + R11-B2 + R11-B4 Explicit operator file/CLI entry point for
    `dispatch_and_solve_nw08_measured_ocr`:
      - Decodes the measured-OCR request strictly via `strict_json_load_file` (enforcing bounded
        nesting depth `MAX_JSON_NESTING_DEPTH = 64`, mapping `RecursionError`, duplicate keys,
        NaN/Infinity constants, overflowing floats like 1e500, and out-of-float64-range integers
        like 10**400 to structured exit-2 HOLD with `release_authorizing = False`).
      - Delegates validation, binding, and dispatch to `evaluate_nw08_measured_ocr_record(...)`.
    """
    is_coupled = coupled_lot_binding is not None
    binding_mode = "COUPLED_COMPOSITE_LOT_BOUND" if is_coupled else "STANDALONE_UNBOUND_DIAGNOSTIC_ONLY"

    def _hold(holds_list: List[str]) -> Tuple[Dict[str, Any], int]:
        return (
            {
                "adjudicated_verdict": "HOLD",
                "release_authorizing": False,
                "qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
                "physical_qualification_complete": False,
                "solver_cleared_oxygen_floor_diagnostic": False,
                "solver_executed": False,
                "binding_mode": binding_mode,
                "lot_binding_verified": False,
                "holds": holds_list,
            },
            2,
        )

    op = Path(ocr_json_path)
    if not op.is_file():
        return _hold([f"HOLD_NW08_OCR_FILE_NOT_FOUND:{op.name}"])
    try:
        req = strict_json_load_file(op, max_int_abs=MAX_STRICT_JSON_INT_ABS, max_depth=MAX_JSON_NESTING_DEPTH)
    except StrictJSONDecodeError as exc:
        strict_holds = [
            "HOLD_INVALID_INPUT_JSON",
            f"HOLD_NW08_AMBIGUOUS_OR_NONCANONICAL_OCR_JSON:{exc.reason_code}",
            f"HOLD_NW08_MALFORMED_OCR_JSON:{type(exc).__name__}",
        ]
        if exc.reason_code in ("INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE", "NONZERO_FLOAT_UNDERFLOW_REJECTED"):
            strict_holds.append(exc.reason_code)
        return _hold(strict_holds)
    except (OSError, UnicodeDecodeError, json.JSONDecodeError, TypeError, ValueError, OverflowError, RecursionError) as exc:
        err_holds = ["HOLD_INVALID_INPUT_JSON", f"HOLD_NW08_MALFORMED_OCR_JSON:{type(exc).__name__}"]
        if isinstance(exc, RecursionError):
            err_holds.insert(1, "HOLD_NW08_AMBIGUOUS_OR_NONCANONICAL_OCR_JSON:JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED")
        return _hold(err_holds)

    return evaluate_nw08_measured_ocr_record(
        req,
        openislet_root=openislet_root,
        coupled_lot_binding=coupled_lot_binding,
        trusted_qualification_store=trusted_qualification_store,
    )


def main() -> int:
    parser = argparse.ArgumentParser(
        description="EXP-031 Round-02 hardened 80-digit outward Taylor Gate 0V, 3D FVM NW-08 & public-bundle portable verifier"
    )
    parser.add_argument("--out", type=Path, default=DEFAULT_RECEIPT_PATH, help="Output JSON receipt path")
    parser.add_argument("--repo-root", type=Path, default=None, help="Path to OpenIslet science repository (read-only)")
    parser.add_argument("--investigations-root", type=Path, default=None, help="Path to OpenIslet-Investigations repository")
    parser.add_argument("--protected-manifest", type=Path, default=None, help="Optional JSON manifest mapping protected relative file paths to SHA-256 hex digests")
    parser.add_argument("--evaluate-lot", type=Path, default=None, help="Evaluate a single measured-lot Gate 0V JSON payload (strict RFC-8259 JSON; fail-closed exit 0 ONLY on tier-matched PASS)")
    parser.add_argument(
        "--dispatch-nw08-ocr",
        type=Path,
        default=None,
        help=(
            "Explicit operator CLI path to dispatch_and_solve_nw08_measured_ocr: evaluate a measured-OCR "
            "JSON request (route_id, measured_ocr, uncertainty_se, optional p_bed_mmhg / baseline_vasc_ocr_mult / "
            "always_solve_3d) under strict JSON decoding and immutable 15.0 mmHg floor (exit 0 PASS, 3 FAIL, 2 HOLD)"
        ),
    )
    parser.add_argument("--trusted-qualification-store", type=Path, default=None, help="Independent external trusted qualification store (registry JSON or directory) required for LOT_RELEASE_SURROGATE / AUTOLOGOUS_D1B_PROCESS_QUAL")
    parser.add_argument("--skip-3d-fvm", action="store_true", help="Skip live 3D FVM vascular-voxel solves (default: False, runs full 3D FVM)")
    parser.add_argument("--check", action="store_true", help="Verify deterministic portable replay against pinned --out receipt without overwriting")
    args = parser.parse_args()

    openislet_root, inv_root = _resolve_roots(args.repo_root, args.investigations_root)

    # Single measured-lot evaluation mode (fail-closed structured JSON on ANY I/O, strict-JSON, or type error!)
    if args.evaluate_lot is not None:
        res, rc = evaluate_wholegraft_gate0v_lot_file(
            args.evaluate_lot,
            trusted_qualification_store=args.trusted_qualification_store,
            openislet_root=openislet_root,
        )
        print(json.dumps(res, indent=2, sort_keys=True, allow_nan=False))
        return rc

    # Explicit NW-08 measured-OCR 3D FVM solver dispatch CLI mode (R09-M1 + R09-B1)
    if args.dispatch_nw08_ocr is not None:
        ocr_res, ocr_rc = evaluate_nw08_measured_ocr_file(
            args.dispatch_nw08_ocr,
            openislet_root=openislet_root,
        )
        print(json.dumps(ocr_res, indent=2, sort_keys=True, allow_nan=False))
        return ocr_rc

    cap_persist = Decimal("0.0005")
    cap_kill_esc = Decimal("0.0001")
    alpha_1p_2way = Decimal("0.005")
    alpha_3p_2way = _alpha_3pathogen_global_floor(prec=120)

    legacy_beta_only = min_n_for_zero_event_cap(cap_persist, Decimal("0.05"), Decimal("1.0"), prec=80)
    fwer_5lin_1way = {
        f"eta_{eta}": min_n_for_zero_event_cap(cap_persist, Decimal("0.01"), Decimal(eta), prec=80)
        for eta in ("1.00", "0.90", "0.85", "0.80", "0.70")
    }
    fwer_1pathogen_5lin_2way = {
        f"eta_{eta}": min_n_for_zero_event_cap(cap_persist, alpha_1p_2way, Decimal(eta), prec=80)
        for eta in ("1.00", "0.90", "0.85", "0.80", "0.70")
    }
    fwer_3pathogen_5lin_2way = {
        f"eta_{eta}": min_n_for_zero_event_cap(cap_persist, alpha_3p_2way, Decimal(eta), prec=80)
        for eta in ("1.00", "0.90", "0.85", "0.80", "0.70")
    }

    calibrant_1p_thresholds = {}
    for rn in (23, 24, 25, 30, 50):
        eta_l = exact_clopper_pearson_lower_calibrant(rn, rn, alpha_1p_2way, prec=80)
        n_req = min_n_for_zero_event_cap(cap_persist, alpha_1p_2way, eta_l, prec=80)["min_n_pass"]
        calibrant_1p_thresholds[f"{rn}_of_{rn}"] = {
            "eta_lower_80d": format(eta_l, "f")[:24],
            "clears_0p80_floor": bool(eta_l >= Decimal("0.80")),
            "min_obs_n_per_lineage": n_req,
            "total_obs_cells_5_lineages": n_req * 5,
        }

    calibrant_3p_thresholds = {}
    for rn in (28, 29, 30, 40, 50):
        eta_l = exact_clopper_pearson_lower_calibrant(rn, rn, alpha_3p_2way, prec=80)
        n_req = min_n_for_zero_event_cap(cap_persist, alpha_3p_2way, eta_l, prec=80)["min_n_pass"]
        calibrant_3p_thresholds[f"{rn}_of_{rn}"] = {
            "eta_lower_80d": format(eta_l, "f")[:24],
            "clears_0p80_floor": bool(eta_l >= Decimal("0.80")),
            "min_obs_n_per_lineage_per_pathogen": n_req,
            "total_obs_cells_5lin_1pathogen": n_req * 5,
            "total_obs_cells_5lin_3pathogens": n_req * 15,
        }

    kill_eta_0p80 = min_n_for_zero_event_cap(cap_kill_esc, alpha_1p_2way, Decimal("0.80"), prec=80)
    eta_kill_24 = exact_clopper_pearson_lower_calibrant(24, 24, alpha_1p_2way, prec=80)
    kill_eta_24 = min_n_for_zero_event_cap(cap_kill_esc, alpha_1p_2way, eta_kill_24, prec=80)
    kill_cond_3log_eta_0p80_indirect = min_n_for_zero_event_cap(Decimal("0.001"), Decimal("0.015"), Decimal("0.80"), prec=80)
    kill_cond_3log_eta_0p80_direct = min_n_for_zero_event_cap(Decimal("0.001"), Decimal("0.020"), Decimal("0.80"), prec=80)
    kill_cond_3log_eta_0p80_legacy_0p005 = min_n_for_zero_event_cap(Decimal("0.001"), alpha_1p_2way, Decimal("0.80"), prec=80)
    with _clean_dec_ctx(80, ROUND_HALF_EVEN):
        w_pericyte = Decimal(GRAFT_COMPOSITION_CELLS["pericyte"]) / Decimal(TOTAL_GRAFT_CELLS)
        weighted_masking_pct = float(w_pericyte * Decimal("1.30"))
    kill_lab_scale_by_sveh = {}
    for sveh_str in ("0.50", "0.25", "0.10"):
        sveh_d = Decimal(sveh_str)
        with _clean_dec_ctx(80, ROUND_FLOOR):
            sveh_eta_prod = sveh_d * Decimal("0.80")
        pericytes_needed = min_n_for_zero_event_cap(
            cap_kill_esc, alpha_1p_2way, sveh_eta_prod, prec=80
        )["min_n_pass"]
        with _clean_dec_ctx(80, ROUND_CEILING):
            organoid_cells_needed = int((Decimal(pericytes_needed) / w_pericyte).to_integral_value(rounding=ROUND_CEILING))
        kill_lab_scale_by_sveh[f"s_veh_{sveh_str}"] = {
            "ratio_bound_method": "exact_component_probability_bonferroni_ratio",
            "min_at_risk_n_eff_per_lineage_at_eta0p80": kill_eta_0p80["min_n_pass"],
            "min_pre_ap1903_pericytes_needed": pericytes_needed,
            "min_assembled_organoid_cells_per_arm": organoid_cells_needed,
            "fits_within_2e7_cells_per_arm": bool(organoid_cells_needed <= 20_000_000),
        }

    decimal_regression = run_decimal_interval_regression_suite()
    adversarial = run_adversarial_contract_tests(openislet_root=openislet_root)
    nw08 = run_nw08_calibration_and_layer4_margin_audit(openislet_root, run_3d_fvm=not args.skip_3d_fvm)
    ceg_and_prot = audit_protected_files_and_ceg_delta(openislet_root, inv_root, args.protected_manifest)
    oq016 = quantify_oq016_and_tail_risk_reduction(openislet_root)

    r4_ok = bool(ceg_and_prot["r4_playbook_sec4120_dec114_and_renderer_compatibility"]["passed"])
    gy030_parity_ok = bool(ceg_and_prot["gy030_graveyard_parity"]["passed"])
    ceg_eight_crosslinks_ok = bool(ceg_and_prot["ceg_delta_v33_eight_crosslinks_ledger"]["all_eight_crosslinks_verified"])
    fvm_ok = bool(args.skip_3d_fvm or nw08["true_3d_fvm_vascular_voxel_1p3164_replays"].get("executed"))
    dispatch_ok = bool(args.skip_3d_fvm or nw08["nw08_live_dispatch_solver_tests"].get("all_passed"))
    nw08_trig_ok = bool(nw08["nw08_trigger_and_floor_unit_tests"]["all_passed"])
    all_ok = bool(
        decimal_regression["all_passed"]
        and adversarial["all_passed"]
        and nw08_trig_ok
        and dispatch_ok
        and ceg_and_prot["protected_files_zero_byte_invariance_ok"]
        and r4_ok
        and gy030_parity_ok
        and ceg_eight_crosslinks_ok
        and fvm_ok
    )

    receipt = {
        "schema_version": "0.8.0-exp031-r17-v20",
        "investigation_id": "EXP-031",
        "candidate_id": "CAND-034",
        "target_iip": "IIP-0043",
        "decision_id": "DEC-122",
        "python_version": sys.version.split()[0],
        "graveyard_guardrail_id": GRAVEYARD_GUARDRAIL_ID,
        "graveyard_card_id": GRAVEYARD_CARD_ID,
        "design_pattern": (
            "Option-2 Zero-LIMS-Touch (R17-B1 mandatory typed sampling-unit reconciliation extended to ALL "
            "release-critical control & recovery counts entering exact Clopper-Pearson or joint directional bounds "
            "[BOTH stressed-arm recovery calibrants spike_calibrant & fragile_infected_spike_calibrant, Day-28 "
            "uninfected negative controls uninfected_ctrl_per_unit_counts, AND BOTH Day-28 recovery calibrants "
            "spike_calibrant_per_unit_counts & fragile_infected_spike_per_unit_counts; 209/209 reconciled partitions "
            "on shipping multi-well bank fixture; missing/mismatched calibrant or neg-ctrl basis routes to HOLD with "
            "exact_directional_confidence_certified=False and all_sampling_units_reconciled=False while strictly "
            "preserving FAIL_HARD_STOP precedence] + R17-B2 provably upper-enclosed 60-digit standard-normal 95th "
            "percentile z_{0.95} = 1.64485362695147271486... [upward IEEE-754 float64 1.6448536269514729; 1 - Phi(z) "
            "< 0.05 strictly, rejecting old under-covering 1.6448536269514722] AND guaranteed upward-rounded IEEE-754 "
            "float64 live 3D FVM vascular OCR multiplier derived directly from exact rational Fraction(ocr_u95_dec) / "
            "Fraction(baseline_ocr_dec) via math.nextafter(..., +inf) with per-voxel upward guarantee [strictly > 1.0 "
            "even on sub-ULP positive SE such as 1.097 + t_{0.95, 5}*1e-20] + R17-M1 direct qualification_scope and "
            "physical_qualification_complete=False emitted on dispatch_and_solve_nw08_measured_ocr return dicts + "
            "R17-M2 3-grid ladder docstrings explicitly qualified with recorded 2-grid direct-crossing early-stop "
            "exception + R16-B1 strict uncertainty_se > 0 enforcement for BOTH inferential NW-08 "
            "OCR models [STUDENT_T_ESTIMATED_SE and KNOWN_SIGMA_NORMAL] before solving -> "
            "HOLD_NW08_INFERENTIAL_MODEL_REQUIRES_POSITIVE_SE [solver_executed=False, release_authorizing=False, "
            "exit 2; ValueError on direct API] while retaining ZERO_UNCERTAINTY_DETERMINISTIC_POINT for SE == 0 "
            "+ R16-M1 provably outward-conservative upper-enclosed Student-t critical values t_{0.95, df} >= exact "
            "across all df >= 1 [including df=1 Cauchy cot(pi/20) and exact 7-dp t_{0.95, 5}=2.0150484] "
            "+ R16-M2 exact arbitrary-precision rational integer floor n_eff = floor(n / deff) via Fraction(n) // "
            "Fraction(deff) eliminating finite-precision Decimal truncation for huge counts [10**80 + 1] "
            "+ R16-M3 explicit mesh_uncertainty_status distinguishing single-grid far-from-floor policy skip "
            "[order_qualified=False, interval_valid=False, SINGLE_GRID_FAR_FROM_FLOOR_POLICY_PASS_ORDER_NOT_EVALUATED], "
            "3-grid monotone non-asymptotic fallback [order_qualified=False, "
            "THREE_GRID_MONOTONE_NON_ASYMPTOTIC_FALLBACK_ORDER_NOT_QUALIFIED], and 3-grid asymptotic GCI qualified "
            "[order_qualified=True, interval_valid=True, THREE_GRID_ASYMPTOTIC_GCI_QUALIFIED] + "
            "R14-B1 + R15-B2 predeclared 3-grid numerical convergence verification policy "
            "inside route-family near-floor bands [R1: 14.88-15.25, R2: 14.75-15.25, R3P: 14.70-15.30 mmHg] using "
            "NASA/Roache GCI [admissible p_obs in [0.5, 2.5], formal cap 2.0, ZERO upward clamping of slow p_obs < 0.5] "
            "and ASME V&V-20 oscillatory half-range bounds [Fs=1.25] routing threshold-straddling cases to "
            "HOLD_NW08_MESH_CONVERGENCE_STRADDLES_15MMHG_FLOOR and sub-asymptotic/unqualified order cases to "
            "HOLD_NW08_MESH_CONVERGENCE_UNQUALIFIED_SLOW_OR_NON_ASYMPTOTIC_ORDER [interval_valid=False, exit 2] "
            "before any coupled authorization + R15-M2 verbatim 8-edge CEG-DELTA field parity check on relation, "
            "target_gate_or_module, applicability, and cited_outcome_tuples + R14-B2 exact Student-t small-sample "
            "OCR inference [t_{0.95, df}, e.g. t_{0.95, 5}=2.0150484 for n=6 replicates] and required inferential model "
            "provenance rejecting bare undeclared positive SE fail-closed while scoping normal z=1.6448536 "
            "strictly to declared KNOWN_SIGMA_NORMAL models with external calibration provenance + R18-B1/B2 "
            "isolated child Python subprocess native 3D FVM execution strictly bound to openislet_root/scripts "
            "[verifying Path(mod.__file__).resolve().is_relative_to(resolved_root), reporting "
            "resolved_solver_module_origins on live dispatch responses, zero parent sys.path/sys.modules/"
            "layer4 callback mutation for concurrent raw native Layer-4 callers, and sequential cross-root "
            "copy_A -> copy_B module-origin isolation] + R14-B3 process-wide _FVM_SOLVER_LOCK cache "
            "serialization across direct and composite-wrapper interfaces + single canonical strict RFC-8259 JSON decoder enforcing exact-Decimal "
            "preservation on adjudication-boundary keys + nonzero float64 underflow rejection (-1e-400, 1e-400) + "
            "full signed negative-zero rejection (-0, -0.0, '-0', '-0.0') on non-negative parameters + bounded nesting "
            "depth MAX_JSON_NESTING_DEPTH=64 + RecursionError capture + duplicate-key, NaN/Infinity, overflowing-float, "
            "& out-of-float64-range integer rejection across all direct, store, archive, and CLI intake boundaries + "
            "unconditional pre-schema adverse per_unit_counts scanner across all required/supplemental arms and both "
            "single-cell/multi-well classes with zero early returns on malformed rows + single-cell per_unit_counts "
            "rejection + cross-estimand same-unit ID set and within-unit subset inequality reconciliation "
            "(direct_infected_veh_72h <= veh_72h and SAME_72H_ALIQUOT infected_viral_pos_72h <= ap1903_72h) + "
            "reconciled per-estimand sampling-unit basis enforcing independent_biological_units_n >= 6, canonical "
            "independent_sampling_unit_class enum, and ZERO unvalidated numeric deff retention when spec or partitions "
            "fail validation + subtractive prohibition of require_trusted_nw08_ocr_record=True on BANK_QUALIFICATION "
            "enforced identically at direct admission and archive replay + machine-readable qualification_scope and "
            "physical_qualification_complete=False attached directly onto every live PASS response across all tiers + "
            "safe type-checked intake guaranteeing structured HOLD exit 2 + mandatory fail-closed enforcement of "
            "require_trusted_nw08_ocr_record=True on clinical release lots -> HOLD_NW08_REQUIRED_OCR_RECORD_MISSING "
            "when OCR is omitted + standalone unbound --dispatch-nw08-ocr strictly non-authorizing "
            "release_authorizing=False recursively + external --trusted-qualification-store with canonical composite "
            "envelope parity & live dual/composite bank replay across both store layouts + cryptographic & structural "
            "coupled --nw08-ocr-json binding + strict SAME_72H_ALIQUOT count reconciliation + direct infected-vehicle "
            "conditional escape requirement + unclamped [0, +infinity) exact component-probability Bonferroni ratio "
            "bounds strictly certified ONLY at deff == 1.0 under a valid reconciled sampling-unit basis [matching "
            "GY-018/IIP-0044], routing deff > 1.0 to non-authorizing HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE "
            "+ explicit 0/0 [point=None, flag=None] vs k>0/0 [point=+Infinity] zero-denominator boundary conventions + "
            "0..n 3-state control-HOLD adjudication + canonical product_variant_id reconciliation + true U95 <= 0.15% "
            "negative controls + exact zero-deadband IEEE-754 canonical live 3D FVM dispatch solver + public-bundle "
            "portable verification)"
        ),
        "arithmetic_engine": (
            "Exact Fraction argument reduction + pure elementary (+,-,*,/) outward-directed 80/120-digit "
            "Taylor interval Decimal + dynamic working precision + three-valued exact/interval boundary "
            "adjudication (ZERO Decimal.ln()/exp() reliance; full ambient-context, narrow-exponent, & Inexact-trap immunity)"
        ),
        "graft_5lineage_composition": {
            "composition_scope": "reference_design_fraction_lot_composition_unmeasured",
            "total_cells_per_500k_ieq_graft": TOTAL_GRAFT_CELLS,
            "cells_by_lineage": GRAFT_COMPOSITION_CELLS,
            "non_beta_cell_count": TOTAL_GRAFT_CELLS - GRAFT_COMPOSITION_CELLS["beta"],
            "non_beta_share_pct": round(100.0 * (TOTAL_GRAFT_CELLS - GRAFT_COMPOSITION_CELLS["beta"]) / TOTAL_GRAFT_CELLS, 4),
            "composition_caveat": (
                "48.58% non-beta share is the reference design fraction for the 500k IEQ modeled graft; "
                "actual lot cellular composition remains to be measured experimentally across SC-islet and "
                "native pancreas preparations."
            ),
        },
        "part_a_gate0v_outward_taylor_decimal_bounds": {
            "decimal_interval_regression_suite": decimal_regression,
            "per_lineage_persistence_cap_frac": "0.0005",
            "negative_control_true_u95_cap_pct": "0.15",
            "negative_control_n_min": 20000,
            "legacy_beta_only_alpha_0p05_eta_1p0": legacy_beta_only,
            "five_lineage_1way_bonferroni_alpha_0p01": fwer_5lin_1way,
            "single_pathogen_cvb4_5lin_2way_alpha_0p005": fwer_1pathogen_5lin_2way,
            "full_3pathogen_global_fwer_30tests_alpha_1_over_600": fwer_3pathogen_5lin_2way,
            "spike_calibrant_1pathogen_alpha_0p005": calibrant_1p_thresholds,
            "spike_calibrant_3pathogen_alpha_1_over_600": calibrant_3p_thresholds,
            "gate0v_kill_dual_estimand_sizing": {
                "estimand1_per_total_input_escape_cap": "0.0001",
                "estimand2_conditional_per_pretreat_infected_escape_cap": "0.001",
                "bonferroni_per_estimand_alpha_budgets": {
                    "confidence_statement_type": "DIRECTIONAL_ONE_SIDED_SEPARATE_AT_1_MINUS_ALPHA_SUM",
                    "paired_24h_ratio": {
                        "alpha_veh": "0.025",
                        "alpha_surv": "0.025",
                        "union_bound_sum": "0.050",
                        "confidence_statement_type": "DIRECTIONAL_ONE_SIDED_SEPARATE_AT_1_MINUS_ALPHA_SUM",
                    },
                    "paired_72h_ratio": {
                        "alpha_veh": "0.025",
                        "alpha_surv": "0.025",
                        "union_bound_sum": "0.050",
                        "confidence_statement_type": "DIRECTIONAL_ONE_SIDED_SEPARATE_AT_1_MINUS_ALPHA_SUM",
                    },
                    "estimand1_total_input": {
                        "alpha_veh": "0.025",
                        "alpha_eta": "0.005",
                        "alpha_escape": "0.005",
                        "union_bound_sum": "0.035",
                        "confidence_statement_type": "DIRECTIONAL_ONE_SIDED_UPPER_AT_1_MINUS_ALPHA_SUM",
                    },
                    "estimand2_indirect": {
                        "alpha_veh": "0.015",
                        "alpha_prev": "0.015",
                        "alpha_eta": "0.005",
                        "alpha_escape": "0.015",
                        "union_bound_sum": "0.050",
                        "confidence_statement_type": "DIRECTIONAL_ONE_SIDED_UPPER_AT_1_MINUS_ALPHA_SUM",
                    },
                    "estimand2_direct": {
                        "alpha_inf_veh": "0.025",
                        "alpha_eta": "0.005",
                        "alpha_escape": "0.020",
                        "union_bound_sum": "0.050",
                        "confidence_statement_type": "DIRECTIONAL_ONE_SIDED_UPPER_AT_1_MINUS_ALPHA_SUM",
                    },
                    "coverage_scope_disclosure": (
                        "Each budget certifies >= 95.0% exact directional one-sided confidence across all estimated "
                        "component parameters within an individual lineage x stress-regime estimand STRICTLY AT "
                        "deff == 1.0 UNDER A VALID, RECONCILED PER-ESTIMAND SAMPLING-UNIT BASIS (independent_biological_units_n >= 6, "
                        "canonical independent_sampling_unit_class enum, and verified per-unit counts; matching GY-018 and IIP-0044). "
                        "Missing or invalid clustering_and_independence_spec NEVER defaults deff = 1.0 and sets "
                        "exact_directional_confidence_certified = false (confidence_scope = UNCERTIFIED_MISSING_OR_INVALID_SAMPLING_SPEC). "
                        "For RECONCILED_MULTI_WELL_CELL_ASSAY_WITH_UNIT_PARTITION (6 <= independent_biological_units_n < n), "
                        "certification carries explicit scope CONDITIONAL_ON_EXTERNALLY_VALIDATED_WITHIN_WELL_INDEPENDENCE_DEFF_EQ_1 "
                        "(JSON partition reconciliation verifies accounting against declared biological units but does NOT prove "
                        "physical within-well independence; external assay QA must verify zero intra-well clustering, otherwise "
                        "cluster-level inference is required). Only INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT with "
                        "independent_biological_units_n >= max_binomial_denominator_n carries "
                        "EXACT_INDEPENDENT_BINOMIAL_BONFERRONI_DEFF_EQ_1_UNIT_MATCHED. "
                        "Whenever deff > 1.0 (clustered/correlated observations, including sub-ULP JSON numbers such as "
                        "1.00000000000000001 preserved via exact Decimal parsing), variance-adjusted effective-count "
                        "bounds with outward effective counts k_eff_lower = floor(k * n_eff / n) and "
                        "k_eff_upper = ceil(k * n_eff / n) at n_eff = floor(n / deff) preserve point ordering "
                        "(0 <= l_ratio <= point <= u_ratio whenever the empirical point is defined) strictly as a "
                        "NON-AUTHORIZING DIAGNOSTIC DISPLAY (exact_directional_confidence_certified = false), NEVER "
                        "advertise nominal 95% directional coverage, and route Gate 0V-Kill release adjudication to "
                        "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE (release_authorizing = false). "
                        "For paired 24-h and 72-h vehicle-normalized survival ratios R = p_treated / s_veh over their "
                        "true domain [0, +infinity), neither u_ratio (ceil(u_treated / s_veh_lower)) nor l_ratio "
                        "(floor(l_treated / s_veh_upper)) is clamped to 1.0, with explicit zero-denominator boundary "
                        "conventions: 0/0 reports undefined point estimate None and bounds_ordered_l_le_point_le_u = "
                        "None (while bounds_ordered_l_le_u = true and u_ratio = +Infinity), whereas k > 0 / 0 reports "
                        "point estimate +Infinity and u_ratio = +Infinity (bounds_ordered_l_le_point_le_u = true). "
                        "At deff == 1.0, u_ratio and l_ratio are separate directional one-sided confidence statements "
                        "at >= 1 - (alpha_treated + alpha_veh) = 0.950 each using the same per-component tail budgets, "
                        "NOT a simultaneous two-sided interval at that same unsplit alpha (by intersection-union, "
                        "min(eta_healthy_L, eta_fragile_L) uses single alpha_eta = 0.005); NOT familywise across all "
                        "5 lineages x 5 regimes simultaneously. Exact Clopper-Pearson coverage additionally assumes "
                        "representative independent binary observations sharing a common event probability p within "
                        "each component (independent sampling with unequal per-unit event probabilities falls outside "
                        "the standard common-probability binomial model); neither single-cell unit-count declaration "
                        "nor multi-well partition arithmetic proves equal unit probabilities or physical independence "
                        "on its own. Gate 0V-Kill evaluates acute 24-h/72-h stressed AP1903 viability/erasure separately "
                        "from long-horizon pan-lineage clonogenic eradication (which is owned by Blueprint Gate 5 / "
                        "legacy MCB clonogenic trials in wetlab_contract.py and ISLET-1-BLUEPRINT.md §1.2/§4.5). "
                        "All PASS statuses remain conditional on modeled assumptions (including the 15-panel "
                        "screening/control 97.6508% scope and NW-08 15.0 mmHg modeled oxygen floor) and pending physical qualification."
                    ),
                },
                "alpha_obs_and_cal_2way": "0.005",
                "estimand1_min_n_eff_at_eta_0p80": kill_eta_0p80,
                "estimand1_min_n_eff_at_24_of_24_calibrant": kill_eta_24,
                "estimand2_indirect_min_infected_at_risk_at_eta_0p80_alpha_0p015": kill_cond_3log_eta_0p80_indirect,
                "estimand2_direct_min_infected_at_risk_at_eta_0p80_alpha_0p020": kill_cond_3log_eta_0p80_direct,
                "estimand2_reference_min_infected_at_risk_at_eta_0p80_alpha_0p005": kill_cond_3log_eta_0p80_legacy_0p005,
                "ideal_100pct_kill_zero_survivors_passes": True,
                "lab_scale_by_stressed_vehicle_survival": kill_lab_scale_by_sveh,
            },
            "operational_tier_scope": {
                "BANK_QUALIFICATION": "Full 3-pathogen (CVB4-E2, CVB3, HCMV) + applicable receptor addenda x 5-lineage two-stage screen/ddPCR + dual-target latent genome arm + 5-regime raw-count Gate 0V-Kill -> emits PASS_WHOLEGRAFT_BANK_QUALIFICATION / PASS_COMPOSITE_BANK_QUALIFICATION (NEVER clinical lot release).",
                "LOT_RELEASE_SURROGATE": "Clinical lot release bridged strictly via independent external --trusted-qualification-store verifying prior PASS_COMPOSITE_BANK_QUALIFICATION AND mandatory original JSON-object archived BANK_QUALIFICATION payload (bound across bank record, archived payload, and current lot) + 1-pathogen sentinel (CVB4-E2) + dual-target latent ddPCR + 2-regime AP1903 + adjudication of ALL submitted supplemental adverse data -> emits PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE / PASS_COMPOSITE_CLINICAL_RELEASE.",
                "AUTOLOGOUS_D1B_PROCESS_QUAL": "Autologous D1b-Auto bridged strictly via independent external --trusted-qualification-store process-qualification record + per-patient adventitious-agent panel + Gate 0V-A + active edited-genotype non-inferiority + 2-regime AP1903 + adjudication of ALL submitted supplemental adverse data -> emits PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL / PASS_COMPOSITE_AUTOLOGOUS_CLINICAL_RELEASE.",
            },
            "composite_weighted_average_loophole_proof": {
                "scenario": "1.30% persistently VP1+ pericytes (~433,875 infected cells) with 0% in beta/alpha/delta/iEC",
                "pericyte_graft_weight": round(float(w_pericyte), 6),
                "weighted_graft_average_pct": round(weighted_masking_pct, 6),
                "would_falsely_pass_weighted_only_0p05_cap": bool(weighted_masking_pct < 0.05),
                "blocked_by_conjunctive_per_lineage_rule": True,
            },
            "numerical_evidence_provenance_scope": {
                "supplied_assay_interval_and_replicate_summaries": (
                    "Gate 0V-Geno paired edited-vs-WT non-inferiority (edited_minus_wt_day14_log10_reduction_l95, "
                    "paired_noninferiority_replicates_n >= 6) and Gate 0V-B acute 72-h U95 / Day-14 L95 fields "
                    "consume caller-supplied assay summaries rather than recomputing intervals from raw replicate titers."
                ),
                "raw_count_recomputed_decimal_clopper_pearson_bounds": (
                    "Gate 0V-B Day-28 persistence U_lin, negative-control U95 (<= 0.15% on n >= 20,000), dual spike "
                    "calibrants (eta >= 0.80), dual-target latent ddPCR bounds, powered CD46/CD55 persistence bounds, "
                    "and all Gate 0V-Kill 24-h/72-h/Estimand-1/Estimand-2 erasure bounds are recomputed from raw integer counts."
                ),
            },
            "adversarial_contract_tests": adversarial,
        },
        "part_b_nw08_ccby4_calibration_and_layer4_margins": nw08,
        "part_c_protected_invariance_and_ceg_delta_diff": ceg_and_prot,
        "part_d_oq016_odds_and_tail_risk_reduction": oq016,
        "overall_status": "PASS" if all_ok else "FAIL",
    }

    rendered_text = json.dumps(receipt, indent=2) + "\n"
    if args.check:
        if not args.out.is_file():
            print(f"FAIL: missing pinned receipt {args.out}", file=sys.stderr)
            return 1
        on_disk_doc = strict_json_load_file(args.out, preserve_boundary_decimals=False)
        norm_disk = _normalize_receipt_for_portable_check(on_disk_doc)
        norm_curr = _normalize_receipt_for_portable_check(receipt)
        if norm_disk != norm_curr:
            print(f"FAIL: deterministic portable replay mismatch against {args.out.name}", file=sys.stderr)
            return 1
        norm_sha = hashlib.sha256(
            json.dumps(norm_curr, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
        ).hexdigest()
        print(
            f"OK: {args.out.name} (portable_SHA-256={norm_sha}) matches deterministic replay | "
            f"mode={ceg_and_prot['bundle_mode']} | status={receipt['overall_status']} | "
            f"decimal_reg={decimal_regression['passed_checks']}/{decimal_regression['total_checks']} | "
            f"adversarial={adversarial['passed_cases']}/{adversarial['total_cases']} | "
            f"nw08_trig={nw08['nw08_trigger_and_floor_unit_tests']['passed_tests']}/{nw08['nw08_trigger_and_floor_unit_tests']['total_tests']} | "
            f"live_dispatch={nw08['nw08_live_dispatch_solver_tests']['passed_tests']}/{nw08['nw08_live_dispatch_solver_tests']['total_tests']} | "
            f"protected={ceg_and_prot['protected_files_checked_total']} ok={ceg_and_prot['protected_files_zero_byte_invariance_ok']} | "
            f"r4_renderer_compat={r4_ok} | gy030_parity={gy030_parity_ok} | fvm3d={fvm_ok}"
        )
        return 0 if all_ok else 1
    args.out.parent.mkdir(parents=True, exist_ok=True)
    args.out.write_text(rendered_text, encoding="utf-8")
    print(
        f"Wrote {args.out.name} | mode={ceg_and_prot['bundle_mode']} | status={receipt['overall_status']} | "
        f"decimal_reg={decimal_regression['passed_checks']}/{decimal_regression['total_checks']} | "
        f"adversarial={adversarial['passed_cases']}/{adversarial['total_cases']} | "
        f"nw08_trig={nw08['nw08_trigger_and_floor_unit_tests']['passed_tests']}/{nw08['nw08_trigger_and_floor_unit_tests']['total_tests']} | "
        f"live_dispatch={nw08['nw08_live_dispatch_solver_tests']['passed_tests']}/{nw08['nw08_live_dispatch_solver_tests']['total_tests']} | "
        f"protected={ceg_and_prot['protected_files_checked_total']} ok={ceg_and_prot['protected_files_zero_byte_invariance_ok']} | "
        f"r4_renderer_compat={r4_ok} | gy030_parity={gy030_parity_ok} | fvm3d={fvm_ok}"
    )
    return 0 if all_ok else 1


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