#!/usr/bin/env python3
"""
IIP-0043 / DEC-122 (CAND-034 / EXP-031) Executable Dual-Evaluator Composite Release Wrapper
(Round-02 Remediated across B1, B2, and B6).

Enforces Stage-0 dual-evaluator Option-2 composite release governance:
  - Imports legacy OpenIslet/scripts/wetlab_contract.py (100% READ-ONLY; zero mutation)
    AND standalone verify_iip0043_wholegraft_gate0v_and_calibration.py.
  - B1 / R03-M2 (Trusted External Qualification Store): Prior BANK_QUALIFICATION and
    AUTOLOGOUS_D1B_PROCESS_QUAL approvals are resolved SOLELY from an independent
    external `--trusted-qualification-store <dir_or_registry.json>` — self-attested
    prior qualification records embedded in the caller's lot bundle are NEVER accepted.
    Omitting or failing external store verification emits `HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE`
    (exit 2). 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`.
  - B2 (Canonical Product/Lot/MCB Reconciliation): Resolves `product_variant_id` canonically
    against `data/protocols/islet1_product_definitions_v0.8.0.json` (+ allowlisted `IIP-0041`
    side-contract `ABX_L2_v2_*` donors), preserves canonical `product_variant_id`,
    `current_lot_id`, and `mcb_id` when invoking `wetlab_contract.py`, and reconciles
    `wetlab_contract.py`'s resolved `product_variant_id` against the composite envelope and
    Gate 0V record. Unregistered variants, mismatches, or `execution_supported: false`
    staged research comparators fail closed with `HOLD_COMPOSITE_RELEASE` (exit 2).
  - B6 (Tier-Distinct PASS Codes & Adverse-Data Adjudication): Requires tier-matched Gate 0V
    PASS codes (`PASS_WHOLEGRAFT_BANK_QUALIFICATION`, `PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE`,
    `PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL`), propagates exact tested-vs-inherited scope,
    and preserves `FAIL_HARD_STOP_COMPOSITE_RELEASE` (exit 3) for any submitted adverse finding.

Run with:
  PYTHONDONTWRITEBYTECODE=1 python3 -B evaluate_gate0v_composite_release.py --self-test
  PYTHONDONTWRITEBYTECODE=1 python3 -B evaluate_gate0v_composite_release.py --lot-json <lot.json> --trusted-qualification-store <store>
"""
from __future__ import annotations

import argparse
import copy
import hashlib
import importlib.util
import inspect
import json
from pathlib import Path
import sys
import tempfile
from typing import Any, Callable, Dict, List, Tuple

sys.dont_write_bytecode = True

SCRIPT_DIR = Path(__file__).resolve().parent
DEFAULT_RECEIPT_PATH = (
    SCRIPT_DIR.parent / "data" / "extracted" / "iip0043_composite_release_evaluator_v0.8.0.json"
    if SCRIPT_DIR.name == "scripts"
    else SCRIPT_DIR / "composite_release_evaluator_receipt.json"
)
LEGACY_PASS_TIER = "READY_FOR_ENCAPSULATION_COMPLETE_STAGE0_EVIDENCE"

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",
}

PASS_VERDICTS = frozenset({
    "PASS_COMPOSITE_BANK_QUALIFICATION",
    "PASS_COMPOSITE_CLINICAL_RELEASE",
    "PASS_COMPOSITE_AUTOLOGOUS_CLINICAL_RELEASE",
})

CLINICAL_RELEASE_PASS_VERDICTS = frozenset({
    "PASS_COMPOSITE_CLINICAL_RELEASE",
    "PASS_COMPOSITE_AUTOLOGOUS_CLINICAL_RELEASE",
})

MAX_JSON_NESTING_DEPTH: int = 64
QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL: str = (
    "CONDITIONAL_ON_MODELED_ASSUMPTIONS_PENDING_PHYSICAL_QUALIFICATION"
)

_V38_MOD_CACHE: Any = None


def _resolve_openislet_root(repo_root_arg: Path | None = None) -> Path:
    if repo_root_arg is not None:
        return repo_root_arg.resolve()
    cand_inst = SCRIPT_DIR.parent
    cand_sib = SCRIPT_DIR.parents[3] / "OpenIslet" if len(SCRIPT_DIR.parents) >= 4 else cand_inst
    if (cand_inst / "scripts" / "wetlab_contract.py").is_file():
        return cand_inst
    return cand_sib


def _resolve_gate0v_verifier_path() -> Path:
    for fname in (
        "verify_iip0043_wholegraft_gate0v_and_calibration.py",
        "verify_exp031_wholegraft_gate0v_and_calibration.py",
        "verify_iip0044_wholegraft_gate0v_and_calibration.py",
    ):
        cand = SCRIPT_DIR / fname
        if cand.is_file():
            return cand
    return SCRIPT_DIR / "verify_iip0043_wholegraft_gate0v_and_calibration.py"


def _load_module(name: str, path: Path):
    spec = importlib.util.spec_from_file_location(name, str(path))
    if spec is None or spec.loader is None:
        raise ImportError(f"Could not create module spec for {path}")
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod


def _get_v38_module():
    global _V38_MOD_CACHE
    v38_path = _resolve_gate0v_verifier_path().resolve()
    if _V38_MOD_CACHE is None:
        for mod_name in ("verify_iip0043_wholegraft_gate0v_and_calibration", "iip0043_gate0v_verifier_shared"):
            existing = sys.modules.get(mod_name)
            existing_file = getattr(existing, "__file__", None) if existing is not None else None
            if existing is not None and existing_file:
                try:
                    if Path(existing_file).resolve() == v38_path:
                        _V38_MOD_CACHE = existing
                        break
                except OSError:
                    pass
        if _V38_MOD_CACHE is None:
            _V38_MOD_CACHE = _load_module("iip0043_gate0v_verifier_shared", v38_path)
            sys.modules.setdefault("iip0043_gate0v_verifier_shared", _V38_MOD_CACHE)
    return _V38_MOD_CACHE


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


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


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:
    """Delegate strictly to the single canonical RFC-8259 JSON decoder in verify_iip0043 (R09-B1 + R10-B2 + R11-B4 + R12-B2)."""
    return _get_v38_module().strict_json_loads(
        raw_text,
        max_int_abs=max_int_abs,
        max_depth=max_depth,
        preserve_boundary_decimals=preserve_boundary_decimals,
    )


def compute_composite_payload_sha256(composite_doc: Dict[str, Any]) -> str:
    """Canonical SHA-256 of a composite lot release bundle excluding top-level payload_sha256."""
    body = {k: v for k, v in composite_doc.items() if k != "payload_sha256"}
    canonical = _get_v38_module()._canonical_json_dumps(body)
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


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


def _call_with_optional_kwargs(fn: Callable[..., Any], payload: Dict[str, Any], optional_kwargs: Dict[str, Any]) -> Any:
    """Invoke an evaluator passing only optional kwargs present in its signature (or **kwargs)."""
    sig = inspect.signature(fn)
    params = sig.parameters
    has_var_kw = any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values())
    if has_var_kw:
        return fn(payload, **optional_kwargs)
    filtered = {k: v for k, v in optional_kwargs.items() if k in params}
    return fn(payload, **filtered)


def evaluate_composite_clinical_release(
    composite_doc: Dict[str, Any],
    *,
    legacy_evaluator: Callable[..., Dict[str, Any]] | None,
    gate0v_evaluator: Callable[..., Dict[str, Any]] | None,
    trusted_qualification_store: Path | str | None = None,
    openislet_root: Path | None = None,
    nw08_ocr_json_path: Path | str | None = None,
    nw08_ocr_record: Dict[str, Any] | None = None,
    _revalidating_archived_bank: bool = False,
) -> Dict[str, Any]:
    """
    Fail-closed conjunction of legacy Stage-0 wetlab_contract.py AND whole-graft Gate 0V
    evaluator bound to the same measured lot with:
      - Shared canonical composite-envelope validation (`v38.validate_canonical_composite_envelope`)
        enforced identically at BOTH direct submission AND archived bank replay (R08-B1)
      - Canonical product_variant_id resolution & cross-evaluator reconciliation (B2)
      - Independent external `--trusted-qualification-store` verification for all prior
        bank/process qualification inheritance with live composite bank replay (B1 / R07-B1 / R08-B1)
      - Mandatory fail-closed NW-08 measured-OCR enforcement whenever a lot (or verified trusted
        record) declares `require_trusted_nw08_ocr_record = True` across BOTH Python API and CLI,
        emitting `HOLD_NW08_REQUIRED_OCR_RECORD_MISSING` (`release_authorizing = False`, exit 2)
        when omitted while preserving any independent biological `FAIL_HARD_STOP` (R11-B1)
      - Tier-distinct PASS codes & full adverse-data adjudication across tiers (B6)
    """
    hard_stops: List[str] = []
    holds: List[str] = []
    resolved_root = _resolve_openislet_root(openislet_root)
    v38 = _get_v38_module()

    if legacy_evaluator is None:
        holds.append("HOLD_COMPOSITE_MISSING_LEGACY_WETLAB_CONTRACT_EVALUATOR")
    if gate0v_evaluator is None:
        holds.append("HOLD_COMPOSITE_MISSING_GATE0V_WHOLEGRAFT_EVALUATOR")
    if not isinstance(composite_doc, dict):
        return {
            "composite_verdict": "HOLD_COMPOSITE_RELEASE",
            "release_authorizing": False,
            "bank_qualification_authorized": False,
            "qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
            "physical_qualification_complete": False,
            "operational_tier": None,
            "hard_stops": [],
            "holds": holds + ["HOLD_COMPOSITE_PAYLOAD_NOT_DICT"],
            "lot_binding": None,
            "tested_vs_inherited_scope": None,
            "prior_qualification_authentication": None,
            "legacy_result_summary": None,
            "gate0v_result_summary": None,
            "authenticated_bank_qualification_record": None,
        }

    # R08-B1: Validate the composite envelope through the EXACT SAME shared canonical validator
    # used by archived composite bank replay (`v38.validate_canonical_composite_envelope`).
    env = v38.validate_canonical_composite_envelope(composite_doc, openislet_root=resolved_root)
    for eh in env["holds"]:
        if eh not in holds:
            holds.append(eh)

    top_lot = env["top_lot"]
    top_mcb = env["top_mcb"]
    top_pvid_raw = env["top_pvid_raw"]
    top_sha = env["top_sha"]
    computed_comp_sha = env["computed_comp_sha"]
    canonical_product_def = env["canonical_product_def"]
    canonical_pvid = env["canonical_pvid"]
    legacy_obs = env["legacy_obs"]
    gate0v_obs = env["gate0v_obs"]
    leg_pvid_canon = env["leg_pvid_canon"]
    qual_tier = env["qual_tier"]
    tier_allowed_for_product = env["tier_allowed_for_product"]

    # B1 / R04-B1 / R04-B2 / R07-B1 / R08-B1: Resolve prior bank/process qualification SOLELY from
    # independent external trusted store, executing live composite bank replay on archived bank bundles!
    prior_qual_auth: Dict[str, Any] = {
        "required": False,
        "authenticated": True,
        "resolution_source": "direct_bank_qualification_current_lot",
    }
    if qual_tier == "LOT_RELEASE_SURROGATE" and isinstance(gate0v_obs, dict):
        inline_prior = composite_doc.get("prior_bank_qualification_record")
        if inline_prior is None:
            inline_prior = gate0v_obs.get("bridged_mcb_qualification_record")

        def _replay_archived_composite_bank(arch_doc: Dict[str, Any]) -> Dict[str, Any]:
            return evaluate_composite_clinical_release(
                arch_doc,
                legacy_evaluator=legacy_evaluator,
                gate0v_evaluator=gate0v_evaluator,
                trusted_qualification_store=None,
                openislet_root=resolved_root,
                _revalidating_archived_bank=True,
            )

        pq_ok, pq_errs, pq_meta = v38.resolve_and_verify_trusted_bank_qualification(
            trusted_qualification_store,
            expected_sha256=gate0v_obs.get("bridged_mcb_qualification_sha256"),
            expected_mcb_id=top_mcb,
            expected_product_variant_id=canonical_pvid,
            expected_genotype_stratum=gate0v_obs.get("antiviral_genotype_stratum"),
            inline_record_if_supplied=inline_prior,
            openislet_root=resolved_root,
            hold_prefix="HOLD_COMPOSITE_PRIOR_BANK_QUAL",
            legacy_evaluator=legacy_evaluator,
            composite_bank_revalidator=(
                _replay_archived_composite_bank
                if (legacy_evaluator is not None and gate0v_evaluator is not None and not _revalidating_archived_bank)
                else None
            ),
            _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)
        # R07-B1 + R08-B1: Composite clinical release STRICTLY REQUIRES canonical composite envelope
        # parity AND live Gate-0V + live legacy + live composite bank replay on a complete composite bank archive!
        if (
            prior_qual_auth.get("archived_bank_payload_verified") is not True
            or prior_qual_auth.get("archived_bank_payload_live_revalidation_passed") is not True
            or prior_qual_auth.get("archived_bank_payload_live_g0v_revalidation_passed") is not True
            or prior_qual_auth.get("archived_bank_payload_live_legacy_revalidation_passed") is not True
            or prior_qual_auth.get("archived_bank_payload_live_composite_revalidation_passed") is not True
        ):
            if (
                prior_qual_auth.get("archived_bank_payload_live_legacy_revalidation_passed") is not True
                and (
                    legacy_evaluator is None
                    or prior_qual_auth.get("archived_bank_payload_format")
                    in ("standalone_gate0v_bank_payload_missing_legacy_for_composite_release", "canonical_gate0v_bank_payload")
                )
            ):
                if "HOLD_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE" not in holds:
                    holds.append("HOLD_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE")
            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" and isinstance(gate0v_obs, dict):
        inline_proc = composite_doc.get("prior_process_qualification_record")
        if inline_proc is None:
            inline_proc = gate0v_obs.get("process_qualification_record")
        pq_ok, pq_errs, pq_meta = v38.resolve_and_verify_trusted_process_qualification(
            trusted_qualification_store,
            expected_sha256=gate0v_obs.get("process_qualification_ref_sha256"),
            expected_product_variant_id=canonical_pvid,
            inline_record_if_supplied=inline_proc,
            openislet_root=resolved_root,
            hold_prefix="HOLD_COMPOSITE_AUTOLOGOUS_PROC_QUAL",
        )
        prior_qual_auth = {"required": True, **pq_meta}
        for pe in pq_errs:
            if pe not in holds:
                holds.append(pe)

    legacy_summary: Dict[str, Any] | None = None
    gate0v_summary: Dict[str, Any] | None = None
    g0v_scope: Dict[str, Any] | None = None

    # B2: Invoke legacy wetlab_contract.py WITH preserved canonical product_variant_id, current_lot_id & mcb_id!
    if legacy_evaluator is not None and isinstance(legacy_obs, dict):
        if (
            canonical_product_def is not None
            and canonical_product_def.get("registry_source") == "iip0041_abx_cd64t_il1rn_side_contract_v0.8.0.json"
        ):
            # Side-contract-only ABX_L2_v2_* donors have execution_supported=False and are NOT promoted in wetlab_contract.py
            legacy_summary = {
                "lot_release_readiness_tier": "SIDE_CONTRACT_COMPARATOR_UNSUPPORTED_FOR_CLINICAL_RELEASE",
                "resolved_product_variant_id": canonical_pvid,
                "product_execution_supported": False,
                "safety_kill_s9_triggered": False,
                "legacy_evaluator_passed": False,
                "canonical_scope_reconciled": True,
                "legacy_obs_gate0v_beta_cells_scored": legacy_obs.get("obs_gate0v_day28_persistent_vp1_ie1_cells_scored"),
                "legacy_omitted_acute_cvb4_72h_titer": "obs_cvb4_10moi_72h_viral_titer_log10_pfu" not in legacy_obs,
            }
            holds.append("HOLD_COMPOSITE_LEGACY_EVALUATOR_NOT_READY:SIDE_CONTRACT_COMPARATOR_UNSUPPORTED_FOR_CLINICAL_RELEASE")
        else:
            try:
                # Preserve canonical contract metadata keys (product_variant_id, current_lot_id, mcb_id)!
                # Strip ONLY non-contract wrapper aliases (lot_id, product_variant) AFTER verifying reconciliation above.
                legacy_input = {
                    k: v for k, v in legacy_obs.items()
                    if k not in ("lot_id", "product_variant")
                }
                if leg_pvid_canon is not None:
                    legacy_input["product_variant_id"] = leg_pvid_canon
                if _is_clean_nonempty_str(top_lot) and "current_lot_id" not in legacy_input:
                    legacy_input["current_lot_id"] = top_lot
                if _is_clean_nonempty_str(top_mcb) and "mcb_id" not in legacy_input:
                    legacy_input["mcb_id"] = top_mcb

                leg_res = _call_with_optional_kwargs(legacy_evaluator, legacy_input, {"root": resolved_root})
                resolved_arch = leg_res.get("resolved_architecture_assignments") or {}
                leg_tier = str(
                    leg_res.get("lot_release_readiness_tier")
                    or resolved_arch.get("lot_release_readiness_tier")
                    or "UNKNOWN"
                )
                leg_resolved_pvid = resolved_arch.get("product_variant_id")
                leg_exec_supported = resolved_arch.get("product_execution_supported")
                leg_s9 = bool(leg_res.get("safety_kill_s9_triggered"))
                leg_pvid_matched = bool(canonical_pvid is not None and leg_resolved_pvid == canonical_pvid)
                if canonical_pvid is not None and not leg_pvid_matched:
                    holds.append("HOLD_COMPOSITE_LEGACY_RESOLVED_PRODUCT_VARIANT_ID_MISMATCH")

                leg_pass = bool(leg_tier == LEGACY_PASS_TIER and not leg_s9 and leg_pvid_matched)
                legacy_summary = {
                    "lot_release_readiness_tier": leg_tier,
                    "resolved_product_variant_id": leg_resolved_pvid,
                    "product_execution_supported": leg_exec_supported,
                    "canonical_scope_reconciled": leg_pvid_matched,
                    "safety_kill_s9_triggered": leg_s9,
                    "legacy_evaluator_passed": leg_pass,
                    "legacy_obs_gate0v_beta_cells_scored": legacy_obs.get("obs_gate0v_day28_persistent_vp1_ie1_cells_scored"),
                    "legacy_omitted_acute_cvb4_72h_titer": "obs_cvb4_10moi_72h_viral_titer_log10_pfu" not in legacy_obs,
                }
                if leg_s9 or leg_tier == "HARD_SAFETY_STOP_REJECTED":
                    hard_stops.append(f"FAIL_HARD_STOP_LEGACY_EVALUATOR:{leg_tier}")
                elif not leg_pass:
                    holds.append(f"HOLD_COMPOSITE_LEGACY_EVALUATOR_NOT_READY:{leg_tier}")
            except Exception as exc:
                holds.append(f"HOLD_COMPOSITE_LEGACY_EVALUATOR_EXCEPTION:{type(exc).__name__}")

    has_coupled_ocr_input = bool(nw08_ocr_json_path is not None or nw08_ocr_record is not None)
    if gate0v_evaluator is not None and isinstance(gate0v_obs, dict):
        try:
            g0v_res = _call_with_optional_kwargs(
                gate0v_evaluator,
                gate0v_obs,
                {
                    "trusted_qualification_store": trusted_qualification_store,
                    "openislet_root": resolved_root,
                    "_nw08_ocr_adjudicated_externally": has_coupled_ocr_input,
                },
            )
            g0v_verdict = str(g0v_res.get("verdict") or "UNKNOWN")
            expected_g0v_pass = GATE0V_PASS_VERDICTS_BY_TIER.get(str(qual_tier))
            g0v_lot_bind = g0v_res.get("lot_binding") or {}
            g0v_resolved_pvid = g0v_lot_bind.get("canonical_product_variant_id")
            if canonical_pvid is not None and g0v_resolved_pvid != canonical_pvid:
                holds.append("HOLD_COMPOSITE_GATE0V_RESOLVED_PRODUCT_VARIANT_ID_MISMATCH")
            g0v_pass = bool(
                expected_g0v_pass is not None
                and g0v_verdict == expected_g0v_pass
                and g0v_res.get("exact_directional_confidence_certified") is True
                and (canonical_pvid is None or g0v_resolved_pvid == canonical_pvid)
            )
            g0v_scope = g0v_res.get("tested_vs_inherited_scope")
            gate0v_summary = {
                "verdict": g0v_verdict,
                "expected_tier_pass_verdict": expected_g0v_pass,
                "gate0v_evaluator_passed": g0v_pass,
                "qualification_scope": g0v_res.get("qualification_scope"),
                "physical_qualification_complete": g0v_res.get("physical_qualification_complete"),
                "qualification_tier": g0v_lot_bind.get("qualification_tier"),
                "canonical_product_variant_id": g0v_resolved_pvid,
                "ectopic_viral_receptors_evaluated": g0v_res.get("ectopic_viral_receptors_evaluated", []),
                "exact_directional_confidence_certified": g0v_res.get("exact_directional_confidence_certified"),
                "confidence_scope": g0v_res.get("confidence_scope"),
                "clustering_design_effect_deff": g0v_res.get("clustering_design_effect_deff"),
                "submitted_clustering_design_effect_deff_unvalidated": g0v_res.get("submitted_clustering_design_effect_deff_unvalidated"),
                "sampling_unit_basis": g0v_res.get("sampling_unit_basis"),
                "hard_stops_count": len(g0v_res.get("hard_stops") or []),
                "holds_count": len(g0v_res.get("holds") or []),
                "hard_stops_sample": (g0v_res.get("hard_stops") or [])[:4],
                "holds_sample": (g0v_res.get("holds") or [])[:4],
            }
            if g0v_verdict == "FAIL_HARD_STOP":
                hard_stops.extend(g0v_res.get("hard_stops") or ["FAIL_HARD_STOP_GATE0V"])
            elif not g0v_pass:
                holds.append(f"HOLD_COMPOSITE_GATE0V_NOT_PASSED:{g0v_verdict}")
                g0v_holds_all = list(g0v_res.get("holds") or [])
                sentinel_holds = (
                    "HOLD_INDIRECT_CONDITIONAL_ESCAPE_UNSUPPORTED_FOR_RELEASE",
                    "HOLD_INDETERMINATE_INTERVAL_STRADDLING_CAP_UNDER_CONTROL_HOLD",
                    "HOLD_NON_SAME_ALIQUOT_UNVERIFIED_COUNT_RECONCILIATION",
                    "HOLD_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE",
                    "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD",
                    "HOLD_ARCHIVED_BANK_ENVELOPE_MISMATCH",
                    "HOLD_COMPOSITE_OPERATIONAL_TIER_MISMATCH",
                    "HOLD_COMPOSITE_MISSING_TOP_PRODUCT_VARIANT_ID",
                    "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE",
                    "HOLD_INAPPLICABLE_QUALIFICATION_TIER_FOR_PRODUCT_FAMILY",
                    "HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM",
                    "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE",
                    "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING",
                    "HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION",
                    "HOLD_UNEXPECTED_PER_UNIT_COUNTS_IN_SINGLE_CELL_MODE",
                    "HOLD_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION",
                    "HOLD_INSUFFICIENT_INDEPENDENT_BIOLOGICAL_UNITS",
                    "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS",
                    "HOLD_GATE0V_MISSING_CLUSTERING_AND_INDEPENDENCE_SPEC",
                    "HOLD_GATE0V_INVALID_CLUSTERING_DESIGN_EFFECT_DEFF",
                    "HOLD_GATE0V_INVALID_OR_MISSING_INDEPENDENT_SAMPLING_UNIT_CLASS",
                )
                for sh in sentinel_holds:
                    if sh in g0v_holds_all and sh not in holds:
                        holds.append(sh)
                for h_item in g0v_holds_all[:5]:
                    if h_item not in holds:
                        holds.append(h_item)
        except Exception as exc:
            holds.append(f"HOLD_COMPOSITE_GATE0V_EVALUATOR_EXCEPTION:{type(exc).__name__}")

    effective_require_trusted_ocr = bool(
        env.get("require_trusted_nw08_ocr_record") is True
        or prior_qual_auth.get("record_require_trusted_nw08_ocr_record") is True
    )
    lot_binding_dict: Dict[str, Any] = {
        "lot_id": top_lot if isinstance(top_lot, str) else None,
        "mcb_id": top_mcb if isinstance(top_mcb, str) else None,
        "supplied_product_variant_id": top_pvid_raw if isinstance(top_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),
        "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
        ),
        "supplied_payload_sha256": top_sha if isinstance(top_sha, str) else None,
        "computed_payload_sha256": computed_comp_sha,
        "payload_sha256_verified": bool(isinstance(top_sha, str) and top_sha == computed_comp_sha),
        "planned_nw08_route_id": env.get("planned_nw08_route_id"),
        "planned_nw08_route_errors": list(env.get("planned_nw08_route_errors") or []),
        "planned_nw08_measurement_evidence_sha256": env.get("planned_nw08_measurement_evidence_sha256"),
        "planned_nw08_measurement_not_before_utc": env.get("planned_nw08_measurement_not_before_utc"),
        "require_trusted_nw08_ocr_record": effective_require_trusted_ocr,
    }

    # R10-B1 + R11-B1: Enforce coupled NW-08 measured-OCR binding/dispatch when provided, AND fail
    # closed whenever `require_trusted_nw08_ocr_record = True` is declared on the lot (or trusted
    # store record) and no OCR input is supplied — across BOTH Python API and CLI!
    nw08_ocr_dispatch_res: Dict[str, Any] | None = None
    nw08_required_ocr_missing = False
    if nw08_ocr_json_path is not None and nw08_ocr_record is not None:
        if "HOLD_NW08_AMBIGUOUS_DUPLICATE_OCR_INPUTS" not in holds:
            holds.append("HOLD_NW08_AMBIGUOUS_DUPLICATE_OCR_INPUTS")
        nw08_ocr_dispatch_res = {
            "adjudicated_verdict": "HOLD",
            "release_authorizing": False,
            "solver_cleared_oxygen_floor_diagnostic": False,
            "solver_executed": False,
            "binding_mode": "COUPLED_COMPOSITE_LOT_BOUND",
            "lot_binding_verified": False,
            "holds": ["HOLD_NW08_AMBIGUOUS_DUPLICATE_OCR_INPUTS"],
        }
    elif nw08_ocr_json_path is not None:
        ocr_res, ocr_rc = v38.evaluate_nw08_measured_ocr_file(
            nw08_ocr_json_path,
            openislet_root=resolved_root,
            coupled_lot_binding=lot_binding_dict,
            trusted_qualification_store=trusted_qualification_store,
        )
        nw08_ocr_dispatch_res = ocr_res
        if ocr_rc == 3:
            if "FAIL_HARD_STOP_NW08_3D_FVM_BELOW_15MMHG_FLOOR" not in hard_stops:
                hard_stops.append("FAIL_HARD_STOP_NW08_3D_FVM_BELOW_15MMHG_FLOOR")
        elif ocr_rc != 0:
            for oh in (ocr_res.get("holds") or ["HOLD_NW08_MEASURED_OCR_DISPATCH_FAILED"]):
                if oh not in holds:
                    holds.append(oh)
    elif nw08_ocr_record is not None:
        ocr_res, ocr_rc = v38.evaluate_nw08_measured_ocr_record(
            nw08_ocr_record,
            openislet_root=resolved_root,
            coupled_lot_binding=lot_binding_dict,
            trusted_qualification_store=trusted_qualification_store,
        )
        nw08_ocr_dispatch_res = ocr_res
        if ocr_rc == 3:
            if "FAIL_HARD_STOP_NW08_3D_FVM_BELOW_15MMHG_FLOOR" not in hard_stops:
                hard_stops.append("FAIL_HARD_STOP_NW08_3D_FVM_BELOW_15MMHG_FLOOR")
        elif ocr_rc != 0:
            for oh in (ocr_res.get("holds") or ["HOLD_NW08_MEASURED_OCR_DISPATCH_FAILED"]):
                if oh not in holds:
                    holds.append(oh)
    elif effective_require_trusted_ocr and qual_tier != "BANK_QUALIFICATION":
        nw08_required_ocr_missing = True
        if "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING" not in holds:
            holds.append("HOLD_NW08_REQUIRED_OCR_RECORD_MISSING")
        nw08_ocr_dispatch_res = {
            "adjudicated_verdict": "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING",
            "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": "COUPLED_COMPOSITE_LOT_BOUND",
            "lot_binding_verified": False,
            "required_by_lot": True,
            "ocr_input_supplied": False,
            "holds": ["HOLD_NW08_REQUIRED_OCR_RECORD_MISSING"],
        }

    auth_bank_record: Dict[str, Any] | None = None
    if hard_stops:
        comp_verdict = "FAIL_HARD_STOP_COMPOSITE_RELEASE"
    elif holds:
        if "HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION" in holds and all(
            h in (
                "HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION",
                "HOLD_COMPOSITE_GATE0V_NOT_PASSED:HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION",
            )
            for h in holds
        ):
            comp_verdict = "HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION"
        elif nw08_required_ocr_missing and all(
            h in (
                "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING",
                "HOLD_COMPOSITE_GATE0V_NOT_PASSED:HOLD_NW08_REQUIRED_OCR_RECORD_MISSING",
            )
            for h in holds
        ):
            comp_verdict = "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING"
        elif "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE" in holds and all(
            h == "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE"
            or h.startswith("HOLD_GATE0V_KILL_")
            or h.startswith("HOLD_COMPOSITE_GATE0V_NOT_PASSED:HOLD_CLUSTERED_DEFF_GT_1")
            for h in holds
        ):
            comp_verdict = "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE"
        else:
            comp_verdict = "HOLD_COMPOSITE_RELEASE"
    elif qual_tier == "BANK_QUALIFICATION":
        bank_geno = gate0v_obs.get("antiviral_genotype_stratum") if isinstance(gate0v_obs, dict) else None
        if not (isinstance(bank_geno, str) and bank_geno in v38.ALLOWED_ANTIVIRAL_GENOTYPES):
            holds.append("HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM")
            comp_verdict = "HOLD_COMPOSITE_RELEASE"
        else:
            comp_verdict = "PASS_COMPOSITE_BANK_QUALIFICATION"
            auth_bank_record = v38.build_authenticated_bank_qualification_record(
                mcb_id=str(top_mcb),
                product_variant_id=str(canonical_pvid),
                bank_lot_id=str(top_lot),
                bank_payload_sha256=computed_comp_sha,
                verdict="PASS_COMPOSITE_BANK_QUALIFICATION",
                operational_tier="BANK_QUALIFICATION",
                legacy_tier=str((legacy_summary or {}).get("lot_release_readiness_tier")),
                legacy_evaluator_passed=bool((legacy_summary or {}).get("legacy_evaluator_passed")),
                legacy_safety_kill_s9_triggered=bool((legacy_summary or {}).get("safety_kill_s9_triggered")),
                gate0v_verdict=str((gate0v_summary or {}).get("verdict")),
                gate0v_evaluator_passed=bool((gate0v_summary or {}).get("gate0v_evaluator_passed")),
                gate0v_hard_stops_count=int((gate0v_summary or {}).get("hard_stops_count") or 0),
                gate0v_holds_count=int((gate0v_summary or {}).get("holds_count") or 0),
                antiviral_genotype_stratum=str(bank_geno),
            )
    elif qual_tier == "LOT_RELEASE_SURROGATE":
        if (
            prior_qual_auth.get("archived_bank_payload_verified") is not True
            or prior_qual_auth.get("archived_bank_payload_live_revalidation_passed") is not True
            or prior_qual_auth.get("archived_bank_payload_live_g0v_revalidation_passed") is not True
            or prior_qual_auth.get("archived_bank_payload_live_legacy_revalidation_passed") is not True
            or prior_qual_auth.get("archived_bank_payload_live_composite_revalidation_passed") is not True
        ):
            if (
                prior_qual_auth.get("archived_bank_payload_live_legacy_revalidation_passed") is not True
                and prior_qual_auth.get("archived_bank_payload_format")
                in ("standalone_gate0v_bank_payload_missing_legacy_for_composite_release", "canonical_gate0v_bank_payload")
                and "HOLD_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE" not in holds
            ):
                holds.append("HOLD_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE")
            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")
            comp_verdict = "HOLD_COMPOSITE_RELEASE"
        else:
            comp_verdict = "PASS_COMPOSITE_CLINICAL_RELEASE"
    elif qual_tier == "AUTOLOGOUS_D1B_PROCESS_QUAL":
        comp_verdict = "PASS_COMPOSITE_AUTOLOGOUS_CLINICAL_RELEASE"
    else:
        comp_verdict = "HOLD_COMPOSITE_RELEASE"

    out_doc: Dict[str, Any] = {
        "composite_verdict": comp_verdict,
        "release_authorizing": bool(comp_verdict in CLINICAL_RELEASE_PASS_VERDICTS),
        "bank_qualification_authorized": bool(comp_verdict == "PASS_COMPOSITE_BANK_QUALIFICATION"),
        "qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
        "physical_qualification_complete": False,
        "operational_tier": qual_tier,
        "lot_binding": lot_binding_dict,
        "tested_vs_inherited_scope": g0v_scope,
        "prior_qualification_authentication": prior_qual_auth,
        "hard_stops": hard_stops,
        "holds": holds,
        "legacy_result_summary": legacy_summary,
        "gate0v_result_summary": gate0v_summary,
        "authenticated_bank_qualification_record": auth_bank_record,
    }
    if nw08_ocr_dispatch_res is not None:
        out_doc["nw08_measured_ocr_dispatch_result"] = nw08_ocr_dispatch_res
    return out_doc


def evaluate_composite_lot_file(
    lot_json_path: Path,
    *,
    legacy_evaluator: Callable[..., Dict[str, Any]] | None,
    gate0v_evaluator: Callable[..., Dict[str, Any]] | None,
    trusted_qualification_store: Path | str | None = None,
    openislet_root: Path | None = None,
    nw08_ocr_json_path: Path | str | None = None,
) -> Tuple[Dict[str, Any], int]:
    """
    Fail-closed CLI boundary loader: uses the single canonical strict RFC-8259 JSON decoder
    (`v38.strict_json_loads`, enforcing bounded nesting depth `MAX_JSON_NESTING_DEPTH = 64` and
    rejecting `RecursionError`, duplicate keys at any depth, NaN/Infinity constants, overflowing
    floats, signed negative zero `-0`/`-0.0`, nonzero underflow, and out-of-range integers), catches
    missing files, OSError, UnicodeDecodeError, StrictJSONDecodeError, json.JSONDecodeError,
    TypeError, ValueError, OverflowError, and RecursionError, and ALWAYS emits a structured JSON
    HOLD (exit 2, `release_authorizing = False`) — ZERO uncaught tracebacks! Delegates coupled
    `--nw08-ocr-json` and mandatory `require_trusted_nw08_ocr_record = True` enforcement directly
    into `evaluate_composite_clinical_release(...)` so CLI and Python API behave identically.
    """
    v38 = _get_v38_module()
    if not lot_json_path.is_file():
        return (
            {
                "composite_verdict": "HOLD_COMPOSITE_RELEASE",
                "release_authorizing": False,
                "bank_qualification_authorized": False,
                "qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
                "physical_qualification_complete": False,
                "operational_tier": None,
                "hard_stops": [],
                "holds": [f"HOLD_COMPOSITE_LOT_FILE_NOT_FOUND:{lot_json_path.name}"],
                "lot_binding": None,
                "tested_vs_inherited_scope": None,
                "prior_qualification_authentication": None,
                "legacy_result_summary": None,
                "gate0v_result_summary": None,
                "authenticated_bank_qualification_record": None,
            },
            2,
        )
    try:
        raw_text = lot_json_path.read_text(encoding="utf-8")
        doc = v38.strict_json_loads(
            raw_text,
            max_int_abs=v38.MAX_STRICT_JSON_INT_ABS,
            max_depth=v38.MAX_JSON_NESTING_DEPTH,
        )
    except v38.StrictJSONDecodeError as exc:
        strict_holds = [
            "HOLD_INVALID_INPUT_JSON",
            f"HOLD_COMPOSITE_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:{exc.reason_code}",
            f"HOLD_COMPOSITE_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 (
            {
                "composite_verdict": "HOLD_COMPOSITE_RELEASE",
                "release_authorizing": False,
                "bank_qualification_authorized": False,
                "qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
                "physical_qualification_complete": False,
                "operational_tier": None,
                "hard_stops": [],
                "holds": strict_holds,
                "lot_binding": None,
                "tested_vs_inherited_scope": None,
                "prior_qualification_authentication": None,
                "legacy_result_summary": None,
                "gate0v_result_summary": None,
                "authenticated_bank_qualification_record": None,
            },
            2,
        )
    except (OSError, UnicodeDecodeError, json.JSONDecodeError, TypeError, ValueError, OverflowError, RecursionError) as exc:
        err_holds = ["HOLD_INVALID_INPUT_JSON", f"HOLD_COMPOSITE_MALFORMED_LOT_JSON:{type(exc).__name__}"]
        if isinstance(exc, RecursionError):
            err_holds.insert(1, "HOLD_COMPOSITE_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED")
        return (
            {
                "composite_verdict": "HOLD_COMPOSITE_RELEASE",
                "release_authorizing": False,
                "bank_qualification_authorized": False,
                "qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
                "physical_qualification_complete": False,
                "operational_tier": None,
                "hard_stops": [],
                "holds": err_holds,
                "lot_binding": None,
                "tested_vs_inherited_scope": None,
                "prior_qualification_authentication": None,
                "legacy_result_summary": None,
                "gate0v_result_summary": None,
                "authenticated_bank_qualification_record": None,
            },
            2,
        )
    res = evaluate_composite_clinical_release(
        doc,
        legacy_evaluator=legacy_evaluator,
        gate0v_evaluator=gate0v_evaluator,
        trusted_qualification_store=trusted_qualification_store,
        openislet_root=openislet_root,
        nw08_ocr_json_path=nw08_ocr_json_path,
    )

    verdict = res["composite_verdict"]
    if verdict in PASS_VERDICTS:
        return res, 0
    if verdict == "FAIL_HARD_STOP_COMPOSITE_RELEASE":
        return res, 3
    return res, 2


def build_legacy_complete_stage0_observations(
    *,
    lot_id: str,
    mcb_id: str,
    product_variant_id: str | None = None,
    product_variant: str | None = None,
    beta_only_cells_scored: float = 5990.0,
) -> Dict[str, Any]:
    """
    Real Stage-0 observation set using canonical `wetlab_endpoint_contract_v0.8.0.json`
    metadata keys (`product_variant_id`, `current_lot_id`, `mcb_id`) that clears live
    OpenIslet `scripts/wetlab_contract.py` to `READY_FOR_ENCAPSULATION_COMPLETE_STAGE0_EVIDENCE`
    for `execution_supported: true` products even with beta-only Gate 0V n = 5,990 — proving
    why the executable composite wrapper is mandatory!
    """
    pvid = (
        product_variant_id
        if product_variant_id is not None
        else (product_variant if product_variant is not None else "ISLET1_A4_ARM1B")
    )
    return {
        "current_lot_id": lot_id,
        "mcb_id": mcb_id,
        "product_variant_id": pvid,
        "obs_icasp9_log10_kill": 4.6,
        "obs_tp53_ppm1d_bcor_vaf": 0.0,
        "obs_castseq_translocation_freq": 0.0,
        "obs_chop_coincidence_fold": 1.15,
        "obs_hc10_surface_fold_wt": 1.05,
        "obs_gate0m_shutoff_t90_min": 2.2,
        "obs_basal_insulin_frac_peak": 0.09,
        "obs_glucose_threshold_mM": 5.1,
        "obs_hlae_hour0_molecules": 18000.0,
        "obs_cd47_hour0_molecules": 220000.0,
        "obs_nkg2a_lysis_pct": 5.5,
        "obs_serpinb9_hour0_uM": 0.35,
        "obs_regimeII_lysis_2h_pct": 5.0,
        "obs_lot_ocr_ratio": 1.02,
        "obs_hlae_hour0_molecules_se": 200.0,
        "obs_cd47_hour0_molecules_se": 1000.0,
        "obs_stage7_yield_ratio": 0.985,
        "obs_stage7_yield_se": 0.01,
        "obs_cd47_fold": 8.0,
        "obs_cd47_fold_se": 0.01,
        "obs_serpinb9_log10_kass": 6.4,
        "obs_serpinb9_log10_kass_se": 0.01,
        "obs_icasp9_log10_kill_se": 0.05,
        "obs_pouch_min_po2_mmhg": 23.0,
        "obs_pouch_min_po2_se": 0.01,
        "obs_pouch_max_h2o2_uM": 2.0,
        "obs_pouch_max_h2o2_se": 0.01,
        "obs_pouch_max_ph": 7.40,
        "obs_pouch_max_ph_se": 0.001,
        "obs_ifng_hla_dr_dq_negative_pct": 99.99,
        "obs_ifng_hla_dr_dq_negative_se": 0.001,
        "obs_tp53_ppm1d_bcor_duplex_depth": 62958.0,
        "obs_castseq_duplex_or_amplicon_depth": 62958.0,
        "obs_mcb_effective_clonogenic_trials": 299573228.0,
        "obs_mcb_clonogenic_survivor_count_k": 0,
        "obs_nkg2a_lysis_se": 0.5,
        "obs_nkg2c_adaptive_nk_lysis_pct": 5.0,
        "obs_nkg2c_adaptive_nk_lysis_se": 0.5,
        "obs_kir_nkg2a_neg_nk_lysis_pct": 5.5,
        "obs_kir_nkg2a_neg_nk_lysis_se": 0.5,
        "obs_phagocytosis_index_pct": 3.5,
        "obs_phagocytosis_index_se": 0.5,
        "obs_chronic_capsule_thickness_um": 9.5,
        "obs_outer_band_kperf_s_inv": 0.1358,
        "obs_indirect_apc_cd4_ifng_si": 1.4,
        "obs_indirect_apc_dq2_dq8_cd4_stimulation_index": 1.2,
        "obs_gate0d_activated_cd4_fasl_apoptosis_pct": 85.0,
        "obs_gate0d_transwell_beta_annexin_v_pct": 6.0,
        "obs_exogenous_b2m_w632_surface_fold_isotype": 1.05,
        "obs_exogenous_b2m_t1d_ctl_lysis_pct": 2.0,
        "obs_gate0m_glucagon_2mM_fold_increase": 2.4,
        "obs_residual_psc_effective_fraction": 1.0e-10,
        "obs_residual_psc_effective_trials": 299573228.0,
        "obs_20q11_bcl2l1_cnv_ratio": 2.00,
        "obs_20q11_bcl2l1_single_cell_mosaic_fraction": 0.002,
        "obs_hazard_state_prolif_survivor_count_k": 0.0,
        "obs_hazard_state_prolif_effective_trials": 299573228.0,
        "obs_cd47_p10_single_cell_molecules": 210000.0,
        "obs_cd47_p10_single_cell_se": 2000.0,
        "obs_hypoxic_72h_cd47_p10_single_cell_molecules": 182000.0,
        "obs_hypoxic_72h_cd47_p10_single_cell_se": 500.0,
        "obs_hypoxic_72h_hlae_p10_single_cell_molecules": 15200.0,
        "obs_hypoxic_72h_hlae_p10_single_cell_se": 50.0,
        "obs_hypoxic_72h_cd47_retention_molecules": 183354.0,
        "obs_hypoxic_72h_cd47_retention_se": 500.0,
        "obs_hypoxic_72h_hlae_retention_molecules": 15250.0,
        "obs_hypoxic_72h_hlae_retention_se": 50.0,
        "obs_periimplant_fluid_film_um": 35.0,
        "obs_explant_en_bloc_recovery_fraction": 0.995,
        "obs_explant_en_bloc_recovery_se": 0.001,
        "obs_gate0s_ap1903_supernatant_insulin_dump_fraction_24h": 0.08,
        "obs_gate0s_ap1903_1h_insulin_burst_iu": 1.8,
        "obs_ap1903_pulsed_pk_log10_kill": 4.6,
        "obs_ap1903_monotherapy_pulsed_pk_log10_kill": 4.5,
        "obs_ap1903_step1_sublethal_survivor_count_k": 0.0,
        "obs_ap1903_step1_effective_trials": 29957323.0,
        "obs_hypoxic_15mmhg_f_isr_translation_ratio": 0.78,
        "obs_iec_cd47_p10_molecules": 195000.0,
        "obs_iec_cd47_p10_se": 2000.0,
        "obs_iec_abo_ab_antigen_mfi_ratio": 1.01,
        "obs_iec_abo_ab_antigen_mfi_se": 0.005,
        "obs_post_stress_nkg2d_dnam1_attributed_lysis_pct": 2.5,
        "obs_senescent_p16_sasp_positive_cell_pct": 0.3,
        "obs_nkg2a_neg_kir2dl_neg_nkg2c_pos_nk_lysis_pct": 5.2,
        "obs_nkg2a_neg_kir2dl_neg_nkg2c_pos_nk_lysis_se": 0.5,
        "obs_il12_il18_sirpa_low_nk_lysis_pct": 6.4,
        "obs_il12_il18_sirpa_low_nk_lysis_se": 0.6,
        "obs_cd47_cc2c6_over_b6h12_ratio": 0.94,
        "obs_complement_c3b_opsonized_phagocytosis_pct": 3.2,
        "obs_complement_c3b_opsonized_phagocytosis_se": 0.4,
        "obs_iec_vascular_support_viability_pct": 91.5,
        "obs_recipient_insulin_clearance_tau_min": 6.5,
        "obs_12pulse_unprimed_hypoxic_serial_lysis_pct": 5.8,
        "obs_hlae_nkg2c_over_nkg2a_kd_ratio": 4.8,
        "obs_immaturity_corner_min_glucose_mM": 3.85,
        "obs_alpha_counterregulatory_gain_ratio": 0.92,
        "obs_ucn3_maturity_ratio": 0.88,
        "obs_combined_stress_embodiment_a_star_lysis_pct": 5.8,
        "obs_combined_stress_comp_r4_lysis_pct": 5.2,
        "obs_combined_stress_comp_r4_gsis_si": 2.9,
        "obs_combined_stress_comp_r4_viable_beta_mass_pct": 91.0,
        "obs_combined_stress_comp_r4_shutoff_t90_min": 2.1,
        "obs_combined_stress_comp_r4_max_h2o2_uM": 2.8,
        "obs_combined_stress_comp_r4_max_ph": 7.38,
        "obs_gate0v_cvb_day14_log10_viral_reduction": 4.2,
        "obs_gate0v_day28_persistent_vp1_ie1_positive_cell_pct": 0.0,
        "obs_gate0v_day28_persistent_vp1_ie1_cells_scored": beta_only_cells_scored,
        "obs_post_stress_20q11_bcl2l1_outgrowth_fold": 0.92,
        "obs_assembled_cassette_chandler_loop_sc5b9_fold": 1.25,
        "obs_assembled_cassette_chandler_loop_platelet_retention_pct": 86.0,
        "obs_hypoxic_72h_five_transgene_joint_above_threshold_fraction": 0.95,
        "obs_apoptotic_effero_clearance_retention_pct_of_wt": 92.0,
        "obs_nutlin3a_p21_mdm2_fold_induction": 8.4,
        "obs_vascular_pericyte_ng2_pdgfrb_coverage_pct": 78.0,
        "obs_assembled_cluster_slc18a1_enterochromaffin_pct": 0.3,
        "obs_assembled_cluster_ins_gcg_polyhormonal_pct": 0.8,
        "obs_assembled_cluster_ki67_progenitor_pct": 0.1,
        "obs_post_stress_mafa_nkx61_beta_identity_retention_pct": 91.0,
    }


def _make_composite_bundle(
    lot_id: str,
    mcb_id: str,
    product_variant_id: str,
    legacy_obs: Dict[str, Any],
    gate0v_obs: Dict[str, Any],
    *,
    prior_bank_qual_record: Dict[str, Any] | None = None,
    nw08_route_id: str | None = None,
    nw08_measurement_evidence_sha256: str | None = None,
    nw08_measurement_not_before_utc: str | None = None,
    require_trusted_nw08_ocr_record: bool | None = None,
) -> Dict[str, Any]:
    doc: Dict[str, Any] = {
        "lot_id": lot_id,
        "mcb_id": mcb_id,
        "product_variant_id": product_variant_id,
        "legacy_stage0_observations": legacy_obs,
        "gate0v_wholegraft_payload": gate0v_obs,
    }
    if prior_bank_qual_record is not None:
        doc["prior_bank_qualification_record"] = prior_bank_qual_record
    if nw08_route_id is not None:
        doc["nw08_route_id"] = nw08_route_id
    if nw08_measurement_evidence_sha256 is not None:
        doc["nw08_measurement_evidence_sha256"] = nw08_measurement_evidence_sha256
    if nw08_measurement_not_before_utc is not None:
        doc["nw08_measurement_not_before_utc"] = nw08_measurement_not_before_utc
    if require_trusted_nw08_ocr_record is not None:
        doc["require_trusted_nw08_ocr_record"] = require_trusted_nw08_ocr_record
    doc["payload_sha256"] = compute_composite_payload_sha256(doc)
    return doc


def run_differential_self_test(openislet_root: Path) -> Dict[str, Any]:
    """
    Execute the Round-02 differential test suite importing REAL read-only
    OpenIslet/scripts/wetlab_contract.py AND verify_iip0043_wholegraft_gate0v_and_calibration.py,
    proving B1 (external trusted store), B2 (canonical product/lot/MCB reconciliation),
    B6 (adverse supplemental data adjudication & tier-distinct PASS codes), and CLI fail-closed HOLD.
    """
    wc_path = openislet_root / "scripts" / "wetlab_contract.py"
    wc_sha_before = hashlib.sha256(wc_path.read_bytes()).hexdigest()

    wc = _load_module("openislet_wetlab_contract_ro", wc_path)
    v38 = _get_v38_module()

    leg_fn = wc.evaluate_stage0_decision_tree
    g0v_fn = v38.evaluate_wholegraft_gate0v_and_stress_ap1903

    bank_lot_id = "BANK-2026-MCB01-Q01"
    clin_lot_id = "LOT-2026-CLIN-001"
    mcb_id = "MCB-ISLET1-A-001"
    pv_lead = "ISLET1_A4_ARM1B"

    cases: List[Dict[str, Any]] = []

    def _run_case(
        name: str,
        doc: Dict[str, Any],
        expected_verdict: str,
        *,
        l_fn=leg_fn,
        g_fn=g0v_fn,
        store_path: Path | str | None = None,
        expected_legacy_pass: bool | None = None,
        expected_gate0v_pass: bool | None = None,
        expected_token: str | None = None,
    ) -> Dict[str, Any]:
        res = evaluate_composite_clinical_release(
            doc,
            legacy_evaluator=l_fn,
            gate0v_evaluator=g_fn,
            trusted_qualification_store=store_path,
            openislet_root=openislet_root,
        )
        ok = res["composite_verdict"] == expected_verdict
        if expected_legacy_pass is not None:
            ok = ok and bool((res["legacy_result_summary"] or {}).get("legacy_evaluator_passed") is expected_legacy_pass)
        if expected_gate0v_pass is not None:
            ok = ok and bool((res["gate0v_result_summary"] or {}).get("gate0v_evaluator_passed") is expected_gate0v_pass)
        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["composite_verdict"],
            "operational_tier": res.get("operational_tier"),
            "legacy_passed": (res["legacy_result_summary"] or {}).get("legacy_evaluator_passed"),
            "legacy_tier": (res["legacy_result_summary"] or {}).get("lot_release_readiness_tier"),
            "legacy_resolved_pvid": (res["legacy_result_summary"] or {}).get("resolved_product_variant_id"),
            "gate0v_passed": (res["gate0v_result_summary"] or {}).get("gate0v_evaluator_passed"),
            "gate0v_verdict": (res["gate0v_result_summary"] or {}).get("verdict"),
            "expected_token": expected_token,
            "hard_stops": res["hard_stops"][:3],
            "holds": res["holds"][:3],
            "passed": ok,
        })
        return res

    with tempfile.TemporaryDirectory() as td:
        trusted_store = Path(td) / "independent_qa_store.json"

        # 1. BANK_QUALIFICATION on canonical ISLET1_A4_ARM1B -> PASS_COMPOSITE_BANK_QUALIFICATION
        leg_bank = build_legacy_complete_stage0_observations(
            lot_id=bank_lot_id, mcb_id=mcb_id, product_variant_id=pv_lead, beta_only_cells_scored=5990.0
        )
        g0v_bank = v38.build_passing_reference_payload(
            lot_id=bank_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            qualification_tier="BANK_QUALIFICATION",
            openislet_root=openislet_root,
        )
        bank_bundle = _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, g0v_bank)
        bank_res = _run_case(
            "bank_qualification_canonical_arm1b_emits_pass_bank",
            bank_bundle,
            "PASS_COMPOSITE_BANK_QUALIFICATION",
            expected_legacy_pass=True,
            expected_gate0v_pass=True,
        )
        auth_bank_rec = bank_res["authenticated_bank_qualification_record"]
        v38.write_record_to_trusted_qualification_store(
            trusted_store,
            auth_bank_rec,
            category="bank_qualifications",
            archived_payload=bank_bundle,
        )

        # 2. B1 LOT_RELEASE_SURROGATE clinical lot WITH independent external trusted store -> PASS_COMPOSITE_CLINICAL_RELEASE!
        leg_clin = build_legacy_complete_stage0_observations(
            lot_id=clin_lot_id, mcb_id=mcb_id, product_variant_id=pv_lead, beta_only_cells_scored=5990.0
        )
        g0v_clin = v38.build_passing_reference_payload(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            qualification_tier="LOT_RELEASE_SURROGATE",
            bridged_mcb_qualification_sha256=auth_bank_rec["sha256"],
            openislet_root=openislet_root,
        )
        clin_bundle = _make_composite_bundle(clin_lot_id, mcb_id, pv_lead, leg_clin, g0v_clin)
        _run_case(
            "b1_clinical_lot_with_external_trusted_store_emits_pass_clinical_release",
            clin_bundle,
            "PASS_COMPOSITE_CLINICAL_RELEASE",
            store_path=trusted_store,
            expected_legacy_pass=True,
            expected_gate0v_pass=True,
        )

        # 3. B1 Self-attested inline bank-qual record WITHOUT --trusted-qualification-store -> HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE!
        g0v_self_att = v38.build_passing_reference_payload(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            qualification_tier="LOT_RELEASE_SURROGATE",
            bridged_mcb_qualification_record=auth_bank_rec,
            openislet_root=openislet_root,
        )
        _run_case(
            "b1_self_attested_inline_bank_qual_without_external_store_held",
            _make_composite_bundle(clin_lot_id, mcb_id, pv_lead, leg_clin, g0v_self_att, prior_bank_qual_record=auth_bank_rec),
            "HOLD_COMPOSITE_RELEASE",
            store_path=None,
            expected_legacy_pass=True,
            expected_token="HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE",
        )

        # 4. B1 Reference SHA-256 NOT present in external trusted store -> HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE!
        g0v_absent = v38.build_passing_reference_payload(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            qualification_tier="LOT_RELEASE_SURROGATE",
            bridged_mcb_qualification_sha256=hashlib.sha256(b"UNREGISTERED_BANK_APPROVAL").hexdigest(),
            openislet_root=openislet_root,
        )
        _run_case(
            "b1_unknown_digest_absent_from_external_store_held",
            _make_composite_bundle(clin_lot_id, mcb_id, pv_lead, leg_clin, g0v_absent),
            "HOLD_COMPOSITE_RELEASE",
            store_path=trusted_store,
            expected_token="HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE",
        )

        # 5. B1 Mismatched MCB ID in external trusted store -> HOLD!
        wrong_mcb_bank = copy.deepcopy(auth_bank_rec)
        wrong_mcb_bank["mcb_id"] = "MCB-DIFFERENT-999"
        wrong_mcb_bank["sha256"] = compute_qualification_record_sha256(wrong_mcb_bank)
        v38.write_record_to_trusted_qualification_store(trusted_store, wrong_mcb_bank, category="bank_qualifications")
        g0v_wrong_mcb = v38.build_passing_reference_payload(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            qualification_tier="LOT_RELEASE_SURROGATE",
            bridged_mcb_qualification_sha256=wrong_mcb_bank["sha256"],
            openislet_root=openislet_root,
        )
        _run_case(
            "b1_mismatched_mcb_id_in_trusted_store_held",
            _make_composite_bundle(clin_lot_id, mcb_id, pv_lead, leg_clin, g0v_wrong_mcb),
            "HOLD_COMPOSITE_RELEASE",
            store_path=trusted_store,
            expected_token="PRIOR_BANK_QUAL_MCB_ID_MISMATCH",
        )

        # 6. B1 Mismatched product_variant_id in external trusted store -> HOLD!
        wrong_pv_bank = copy.deepcopy(auth_bank_rec)
        wrong_pv_bank["product_variant_id"] = "ISLET1_A4_ARM1A"
        wrong_pv_bank["product_variant"] = "ISLET1_A4_ARM1A"
        wrong_pv_bank["sha256"] = compute_qualification_record_sha256(wrong_pv_bank)
        v38.write_record_to_trusted_qualification_store(trusted_store, wrong_pv_bank, category="bank_qualifications")
        g0v_wrong_pv = v38.build_passing_reference_payload(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            qualification_tier="LOT_RELEASE_SURROGATE",
            bridged_mcb_qualification_sha256=wrong_pv_bank["sha256"],
            openislet_root=openislet_root,
        )
        _run_case(
            "b1_mismatched_product_variant_id_in_trusted_store_held",
            _make_composite_bundle(clin_lot_id, mcb_id, pv_lead, leg_clin, g0v_wrong_pv),
            "HOLD_COMPOSITE_RELEASE",
            store_path=trusted_store,
            expected_token="PRIOR_BANK_QUAL_PRODUCT_VARIANT_ID_MISMATCH",
        )

        # 7. B1 Failing underlying Gate 0V verdict in trusted store -> HOLD!
        fail_bank = copy.deepcopy(auth_bank_rec)
        fail_bank["verdict"] = "HOLD_COMPOSITE_RELEASE"
        fail_bank["sha256"] = compute_qualification_record_sha256(fail_bank)
        v38.write_record_to_trusted_qualification_store(trusted_store, fail_bank, category="bank_qualifications")
        g0v_fail_bank = v38.build_passing_reference_payload(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            qualification_tier="LOT_RELEASE_SURROGATE",
            bridged_mcb_qualification_sha256=fail_bank["sha256"],
            openislet_root=openislet_root,
        )
        _run_case(
            "b1_failing_prior_bank_verdict_in_trusted_store_held",
            _make_composite_bundle(clin_lot_id, mcb_id, pv_lead, leg_clin, g0v_fail_bank),
            "HOLD_COMPOSITE_RELEASE",
            store_path=trusted_store,
            expected_token="VERDICT_NOT_PASS_COMPOSITE_BANK_QUALIFICATION",
        )

        # 8. B1 Tampered record inside external trusted store -> HOLD!
        tampered_store = Path(td) / "tampered_store.json"
        tampered_rec = copy.deepcopy(auth_bank_rec)
        tampered_rec["bank_lot_id"] = "BANK-TAMPERED"
        tampered_store.write_text(
            json.dumps({"bank_qualifications": {auth_bank_rec["sha256"]: tampered_rec}}),
            encoding="utf-8",
        )
        _run_case(
            "b1_tampered_bank_record_inside_external_store_held",
            clin_bundle,
            "HOLD_COMPOSITE_RELEASE",
            store_path=tampered_store,
            expected_token="RECORD_INTERNAL_SHA256_MISMATCH",
        )

        # 9. B2 Unregistered product_variant_id ("ISLET1_DESIGN_A_LEAD") rejected fail-closed!
        leg_unreg = build_legacy_complete_stage0_observations(lot_id=bank_lot_id, mcb_id=mcb_id, product_variant_id="ISLET1_DESIGN_A_LEAD")
        g0v_unreg = v38.build_passing_reference_payload(lot_id=bank_lot_id, mcb_id=mcb_id, product_variant_id="ISLET1_DESIGN_A_LEAD", openislet_root=openislet_root)
        _run_case(
            "b2_unregistered_product_variant_id_held",
            _make_composite_bundle(bank_lot_id, mcb_id, "ISLET1_DESIGN_A_LEAD", leg_unreg, g0v_unreg),
            "HOLD_COMPOSITE_RELEASE",
            expected_token="UNREGISTERED_PRODUCT_VARIANT_ID",
        )

        # 10. B2 Registered alias ("ARM_1B") reconciles canonically to ISLET1_A4_ARM1B across wrapper, wetlab_contract, and Gate 0V!
        leg_alias = build_legacy_complete_stage0_observations(lot_id=bank_lot_id, mcb_id=mcb_id, product_variant_id="ARM_1B")
        _run_case(
            "b2_registered_alias_arm1b_reconciles_canonically",
            _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_alias, g0v_bank),
            "PASS_COMPOSITE_BANK_QUALIFICATION",
            expected_legacy_pass=True,
            expected_gate0v_pass=True,
        )

        # 11. B2 Legacy vs Gate 0V product_variant_id mismatch (ISLET1_A4_ARM1A vs ISLET1_A4_ARM1B) -> HOLD!
        leg_other_pv = build_legacy_complete_stage0_observations(lot_id=bank_lot_id, mcb_id=mcb_id, product_variant_id="ISLET1_A4_ARM1A")
        _run_case(
            "b2_legacy_vs_gate0v_product_variant_id_mismatch_held",
            _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_other_pv, g0v_bank),
            "HOLD_COMPOSITE_RELEASE",
            expected_token="LEGACY_PRODUCT_VARIANT_ID_MISMATCH",
        )

        # 12. B2 Staged execution_supported=False CD55/CFH comparator is HONESTLY HELD by live wetlab_contract.py even when Gate 0V passes!
        pv_cfh = "ISLET1_Y_FULLSTACK_V2_CD55_CFH_COMPARATOR"
        leg_cfh = build_legacy_complete_stage0_observations(lot_id=bank_lot_id, mcb_id=mcb_id, product_variant_id=pv_cfh)
        g0v_cfh = v38.build_passing_reference_payload(
            lot_id=bank_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_cfh,
            ectopic_receptors=["CD55_FULL_LENGTH"],
            include_cd46_addendum=False,
            include_cd55_addendum=True,
            openislet_root=openislet_root,
        )
        _run_case(
            "b2_staged_y_cd55_cfh_comparator_gate0v_passes_legacy_holds_unsupported",
            _make_composite_bundle(bank_lot_id, mcb_id, pv_cfh, leg_cfh, g0v_cfh),
            "HOLD_COMPOSITE_RELEASE",
            expected_legacy_pass=False,
            expected_gate0v_pass=True,
            expected_token="RESEARCH_COMPARATOR_UNSUPPORTED_VARIANT_HOLD",
        )

        # 13. B2 Staged execution_supported=False D1b L1B CD46_WT comparator (on its canonical AUTOLOGOUS_D1B_PROCESS_QUAL tier) without addendum holds BOTH evaluators!
        pv_cd46 = "ISLET1_D1_AUTO_V2_L1B_CIITA_CD64T_CD46WT_COMPARATOR"
        proc_d1b_cd46 = v38.build_authenticated_process_qualification_record(
            product_variant_id=pv_cd46,
            process_qual_id="PROCQUAL-D1B-L1B-COMP",
        )
        v38.write_record_to_trusted_qualification_store(trusted_store, proc_d1b_cd46, category="process_qualifications")
        leg_cd46 = build_legacy_complete_stage0_observations(lot_id=bank_lot_id, mcb_id=mcb_id, product_variant_id=pv_cd46)
        g0v_cd46_no = v38.build_passing_reference_payload(
            lot_id=bank_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_cd46,
            qualification_tier="AUTOLOGOUS_D1B_PROCESS_QUAL",
            process_qualification_ref_sha256=proc_d1b_cd46["sha256"],
            ectopic_receptors=["CD46_WT"],
            include_cd46_addendum=False,
            openislet_root=openislet_root,
        )
        _run_case(
            "b2_staged_d1b_cd46_without_addendum_holds_both",
            _make_composite_bundle(bank_lot_id, mcb_id, pv_cd46, leg_cd46, g0v_cd46_no),
            "HOLD_COMPOSITE_RELEASE",
            store_path=trusted_store,
            expected_legacy_pass=False,
            expected_gate0v_pass=False,
            expected_token="CD46_VIRAL_ADDENDUM",
        )

        # 14. B2 Canonical ISLET1_A4_ARM1B_TYK2_PE passes with TYK2_P1104A_HET__IFIH1_WT & non-inferiority!
        pv_tyk2 = "ISLET1_A4_ARM1B_TYK2_PE"
        leg_tyk2 = build_legacy_complete_stage0_observations(lot_id=bank_lot_id, mcb_id=mcb_id, product_variant_id=pv_tyk2)
        g0v_tyk2 = v38.build_passing_reference_payload(
            lot_id=bank_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_tyk2,
            antiviral_genotype_stratum="TYK2_P1104A_HET__IFIH1_WT",
            openislet_root=openislet_root,
        )
        _run_case(
            "b2_canonical_arm1b_tyk2_pe_matched_genotype_passes_bank_qual",
            _make_composite_bundle(bank_lot_id, mcb_id, pv_tyk2, leg_tyk2, g0v_tyk2),
            "PASS_COMPOSITE_BANK_QUALIFICATION",
            expected_legacy_pass=True,
            expected_gate0v_pass=True,
        )

        # 15. DIFFERENTIAL PROOF: Real legacy wetlab_contract.py PASSES on beta-only n=5,990 while Gate 0V HOLDS -> HOLD!
        g0v_beta_only = copy.deepcopy(g0v_bank)
        g0v_beta_only["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["day28_persistence_by_lineage"] = {
            "beta": g0v_beta_only["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["day28_persistence_by_lineage"]["beta"]
        }
        g0v_beta_only["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_beta_only)
        _run_case(
            "differential_legacy_pass_beta_only_n5990_vs_new_hold_composite_hold",
            _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, g0v_beta_only),
            "HOLD_COMPOSITE_RELEASE",
            expected_legacy_pass=True,
            expected_gate0v_pass=False,
            expected_token="MISSING_LINEAGE_CVB4_E2_ALPHA",
        )

        # 16. Legacy HOLD (incomplete Stage-0 panel) + Gate 0V PASS -> Composite HOLD!
        leg_incomplete = {
            "current_lot_id": bank_lot_id,
            "mcb_id": mcb_id,
            "product_variant_id": pv_lead,
            "obs_icasp9_log10_kill": 4.6,
            "obs_tp53_ppm1d_bcor_vaf": 0.0,
            "obs_castseq_translocation_freq": 0.0,
        }
        _run_case(
            "legacy_hold_incomplete_vs_new_pass_composite_hold",
            _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_incomplete, g0v_bank),
            "HOLD_COMPOSITE_RELEASE",
            expected_legacy_pass=False,
            expected_gate0v_pass=True,
            expected_token="LEGACY_EVALUATOR_NOT_READY",
        )

        # 17. Lot ID mismatch between envelope and Gate 0V -> HOLD!
        g0v_diff_lot = v38.build_passing_reference_payload(
            lot_id="LOT-OTHER-999", mcb_id=mcb_id, product_variant_id=pv_lead, openislet_root=openislet_root
        )
        _run_case(
            "lot_id_mismatch_composite_hold",
            _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, g0v_diff_lot),
            "HOLD_COMPOSITE_RELEASE",
            expected_token="GATE0V_LOT_ID_MISMATCH",
        )

        # 18. MCB ID mismatch between envelope and legacy -> HOLD!
        leg_diff_mcb = build_legacy_complete_stage0_observations(lot_id=bank_lot_id, mcb_id="MCB-WRONG-002", product_variant_id=pv_lead)
        _run_case(
            "mcb_id_mismatch_composite_hold",
            _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_diff_mcb, g0v_bank),
            "HOLD_COMPOSITE_RELEASE",
            expected_token="LEGACY_MCB_ID_MISMATCH",
        )

        # 19. Composite payload SHA-256 tamper -> HOLD!
        tampered_doc = _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, g0v_bank)
        tampered_doc["payload_sha256"] = "a" * 64
        _run_case(
            "composite_payload_sha256_mismatch_hold",
            tampered_doc,
            "HOLD_COMPOSITE_RELEASE",
            expected_token="PAYLOAD_SHA256_MISMATCH",
        )

        # 20 & 21. Missing evaluator -> HOLD!
        _run_case(
            "missing_gate0v_evaluator_composite_hold",
            _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, g0v_bank),
            "HOLD_COMPOSITE_RELEASE",
            g_fn=None,
            expected_token="MISSING_GATE0V_WHOLEGRAFT_EVALUATOR",
        )
        _run_case(
            "missing_legacy_evaluator_composite_hold",
            _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, g0v_bank),
            "HOLD_COMPOSITE_RELEASE",
            l_fn=None,
            expected_token="MISSING_LEGACY_WETLAB_CONTRACT_EVALUATOR",
        )

        # 22. B6 Adverse supplemental HCMV reactivation submitted on LOT_RELEASE_SURROGATE -> FAIL_HARD_STOP_COMPOSITE_RELEASE!
        g0v_clin_adv = copy.deepcopy(g0v_clin)
        g0v_clin_adv["gate0v_b_infectious_challenge"]["pathogens"]["hcmv"] = {
            "day28_latent_and_defective_genome_arm": {"reactivation_7d_outgrowth_pfu_ml": "2.5"}
        }
        g0v_clin_adv["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_clin_adv)
        _run_case(
            "b6_adverse_supplemental_hcmv_on_surrogate_tier_hard_stop",
            _make_composite_bundle(clin_lot_id, mcb_id, pv_lead, leg_clin, g0v_clin_adv),
            "FAIL_HARD_STOP_COMPOSITE_RELEASE",
            store_path=trusted_store,
            expected_legacy_pass=True,
            expected_token="SUPPLEMENTAL_HCMV_LATENT_REACTIVATION_OUTGROWTH",
        )

        # 23. Legacy PASS + Gate 0V FAIL_HARD_STOP -> FAIL_HARD_STOP_COMPOSITE_RELEASE!
        g0v_hardstop = copy.deepcopy(g0v_bank)
        g0v_hardstop["gate0v_b_infectious_challenge"]["pathogens"]["hcmv"]["day28_latent_and_defective_genome_arm"]["reactivation_7d_outgrowth_pfu_ml"] = "2.5"
        g0v_hardstop["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_hardstop)
        _run_case(
            "legacy_pass_vs_new_hard_stop_composite_hard_stop",
            _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, g0v_hardstop),
            "FAIL_HARD_STOP_COMPOSITE_RELEASE",
            expected_legacy_pass=True,
            expected_token="HCMV_LATENT_REACTIVATION_OUTGROWTH",
        )

        # 24. CLI boundary regression: Malformed JSON emits structured HOLD_COMPOSITE_RELEASE (exit 2), ZERO traceback!
        bad_json_path = Path(td) / "malformed_lot.json"
        bad_json_path.write_text("{not valid json!!!", encoding="utf-8")
        bad_res, bad_rc = evaluate_composite_lot_file(
            bad_json_path,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
        )
        mal_ok = bool(
            bad_rc == 2
            and bad_res["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and any("MALFORMED_LOT_JSON:JSONDecodeError" in h for h in bad_res["holds"])
        )
        cases.append({
            "case": "malformed_json_cli_boundary_structured_hold_exit_2",
            "expected_verdict": "HOLD_COMPOSITE_RELEASE",
            "actual_verdict": bad_res["composite_verdict"],
            "operational_tier": None,
            "legacy_passed": None,
            "legacy_tier": None,
            "legacy_resolved_pvid": None,
            "gate0v_passed": None,
            "gate0v_verdict": None,
            "expected_token": "MALFORMED_LOT_JSON:JSONDecodeError",
            "exit_code": bad_rc,
            "hard_stops": bad_res["hard_stops"][:3],
            "holds": bad_res["holds"][:3],
            "passed": mal_ok,
        })

        # 25. R04-B1a: Allogeneic ISLET1_A4_ARM1B submitted on AUTOLOGOUS_D1B_PROCESS_QUAL EVEN WITH
        # matching external QA process-qual record MUST fail closed (HOLD_COMPOSITE_RELEASE, exit 2)!
        bad_allo_proc = v38.build_authenticated_process_qualification_record(
            product_variant_id=pv_lead,
            process_qual_id="PROCQUAL-MISAPPLIED-ALLO-ARM1B",
        )
        v38.write_record_to_trusted_qualification_store(trusted_store, bad_allo_proc, category="process_qualifications")
        g0v_allo_on_auto = v38.build_passing_reference_payload(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            qualification_tier="AUTOLOGOUS_D1B_PROCESS_QUAL",
            process_qualification_ref_sha256=bad_allo_proc["sha256"],
            openislet_root=openislet_root,
        )
        _run_case(
            "r04_b1_allogeneic_arm1b_on_autologous_tier_with_matching_qa_record_held",
            _make_composite_bundle(clin_lot_id, mcb_id, pv_lead, leg_clin, g0v_allo_on_auto),
            "HOLD_COMPOSITE_RELEASE",
            store_path=trusted_store,
            expected_legacy_pass=True,
            expected_gate0v_pass=False,
            expected_token="HOLD_INAPPLICABLE_QUALIFICATION_TIER_FOR_PRODUCT_FAMILY",
        )

        # 26. R04-B1b: Autologous D1b submitted on BANK_QUALIFICATION -> HOLD_COMPOSITE_RELEASE!
        pv_d1a = "ISLET1_D1_AUTO_V2_L1A_CIITA_CD64T_IL1RN"
        leg_d1a = build_legacy_complete_stage0_observations(lot_id=bank_lot_id, mcb_id=mcb_id, product_variant_id=pv_d1a)
        g0v_d1a_bank = v38.build_passing_reference_payload(
            lot_id=bank_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_d1a,
            qualification_tier="BANK_QUALIFICATION",
            openislet_root=openislet_root,
        )
        _run_case(
            "r04_b1_autologous_d1b_on_bank_qualification_tier_held",
            _make_composite_bundle(bank_lot_id, mcb_id, pv_d1a, leg_d1a, g0v_d1a_bank),
            "HOLD_COMPOSITE_RELEASE",
            expected_gate0v_pass=False,
            expected_token="HOLD_INAPPLICABLE_QUALIFICATION_TIER_FOR_PRODUCT_FAMILY",
        )

        # 27. R04-B1c: Autologous D1b submitted on LOT_RELEASE_SURROGATE -> HOLD_COMPOSITE_RELEASE!
        g0v_d1a_surr = v38.build_passing_reference_payload(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_d1a,
            qualification_tier="LOT_RELEASE_SURROGATE",
            bridged_mcb_qualification_sha256=auth_bank_rec["sha256"],
            openislet_root=openislet_root,
        )
        leg_d1a_clin = build_legacy_complete_stage0_observations(lot_id=clin_lot_id, mcb_id=mcb_id, product_variant_id=pv_d1a)
        _run_case(
            "r04_b1_autologous_d1b_on_lot_release_surrogate_tier_held",
            _make_composite_bundle(clin_lot_id, mcb_id, pv_d1a, leg_d1a_clin, g0v_d1a_surr),
            "HOLD_COMPOSITE_RELEASE",
            store_path=trusted_store,
            expected_gate0v_pass=False,
            expected_token="HOLD_INAPPLICABLE_QUALIFICATION_TIER_FOR_PRODUCT_FAMILY",
        )

        # 28. R04-B2a: Exact Round-03 counterexample — external QA bank record omitting antiviral_genotype_stratum
        # + archived WT bank bundle used for protective-LOF current lot -> HOLD_COMPOSITE_RELEASE!
        nogeno_bank = copy.deepcopy(auth_bank_rec)
        nogeno_bank.pop("antiviral_genotype_stratum", None)
        nogeno_bank["sha256"] = compute_qualification_record_sha256(nogeno_bank)
        v38.write_record_to_trusted_qualification_store(
            trusted_store, nogeno_bank, category="bank_qualifications", archived_payload=bank_bundle
        )
        g0v_lof_nogeno = v38.build_passing_reference_payload(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            qualification_tier="LOT_RELEASE_SURROGATE",
            bridged_mcb_qualification_sha256=nogeno_bank["sha256"],
            antiviral_genotype_stratum="TYK2_WT__IFIH1_PROTECTIVE_LOF",
            openislet_root=openislet_root,
        )
        _run_case(
            "r04_b2_missing_bank_stratum_with_archived_wt_for_lof_lot_held",
            _make_composite_bundle(clin_lot_id, mcb_id, pv_lead, leg_clin, g0v_lof_nogeno),
            "HOLD_COMPOSITE_RELEASE",
            store_path=trusted_store,
            expected_legacy_pass=True,
            expected_gate0v_pass=False,
            expected_token="HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM",
        )

        # 29. R04-B2b: Bank record declaring LOF contradicting archived WT bank payload -> HOLD_COMPOSITE_RELEASE!
        contradict_bank = copy.deepcopy(auth_bank_rec)
        contradict_bank["antiviral_genotype_stratum"] = "TYK2_WT__IFIH1_PROTECTIVE_LOF"
        contradict_bank["sha256"] = compute_qualification_record_sha256(contradict_bank)
        v38.write_record_to_trusted_qualification_store(
            trusted_store, contradict_bank, category="bank_qualifications", archived_payload=bank_bundle
        )
        g0v_lof_contra = v38.build_passing_reference_payload(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            qualification_tier="LOT_RELEASE_SURROGATE",
            bridged_mcb_qualification_sha256=contradict_bank["sha256"],
            antiviral_genotype_stratum="TYK2_WT__IFIH1_PROTECTIVE_LOF",
            openislet_root=openislet_root,
        )
        _run_case(
            "r04_b2_bank_record_stratum_contradicts_archived_wt_payload_held",
            _make_composite_bundle(clin_lot_id, mcb_id, pv_lead, leg_clin, g0v_lof_contra),
            "HOLD_COMPOSITE_RELEASE",
            store_path=trusted_store,
            expected_legacy_pass=True,
            expected_gate0v_pass=False,
            expected_token="HOLD_UNVERIFIED_OR_MISMATCHED_BANK_GENOTYPE_STRATUM",
        )

        # 30. R04-B3a: Extra non-canonical lineage key inside required stress regime with adverse raw counts -> FAIL_HARD_STOP!
        g0v_extra_lin_adv = copy.deepcopy(g0v_bank)
        extra_arm = copy.deepcopy(g0v_extra_lin_adv["gate0v_kill_stress_ap1903"]["hypoxia_1pct_plus_cytokines"]["beta"])
        extra_arm["ap1903_24h_viable_survivors_k"] = 7000
        g0v_extra_lin_adv["gate0v_kill_stress_ap1903"]["hypoxia_1pct_plus_cytokines"]["ductal_noncanonical"] = extra_arm
        v38.reconcile_fixture_per_unit_counts(g0v_extra_lin_adv)
        g0v_extra_lin_adv["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_extra_lin_adv)
        _run_case(
            "r04_b3_extra_noncanonical_lineage_key_adverse_counts_hard_stop",
            _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, g0v_extra_lin_adv),
            "FAIL_HARD_STOP_COMPOSITE_RELEASE",
            expected_legacy_pass=True,
            expected_gate0v_pass=False,
            expected_token="AP1903_24H_KILL_BELOW_99P9PCT_HYPOXIA_1PCT_PLUS_CYTOKINES_DUCTAL_NONCANONICAL",
        )

        # 31. R04-B3b: Zero-killing arm paired with poorly surviving vehicle control -> FAIL_HARD_STOP!
        g0v_zero_kill_low_veh = copy.deepcopy(g0v_bank)
        g0v_zero_kill_low_veh["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"]["alpha"]["veh_24h_viable_n"] = 50
        g0v_zero_kill_low_veh["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"]["alpha"]["ap1903_24h_viable_survivors_k"] = 10000
        v38.reconcile_fixture_per_unit_counts(g0v_zero_kill_low_veh)
        g0v_zero_kill_low_veh["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_zero_kill_low_veh)
        _run_case(
            "r04_b3_zero_killing_with_low_vehicle_survival_preserves_hard_stop",
            _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, g0v_zero_kill_low_veh),
            "FAIL_HARD_STOP_COMPOSITE_RELEASE",
            expected_legacy_pass=True,
            expected_gate0v_pass=False,
            expected_token="AP1903_24H_KILL_BELOW_99P9PCT_ER_STRESS_TG_OR_TM_ALPHA",
        )

        # 32. R04-B4: CD55 comparator with legacy aggregate-only block (no per-strain strain_results) -> HOLD!
        g0v_cfh_agg = copy.deepcopy(g0v_cfh)
        g0v_cfh_agg["cd55_tropic_echovirus_addendum"] = {
            "echovirus_strain_panel": ["echovirus_7", "echovirus_11"],
            "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": v38._valid_digest("cd55_legacy_agg_comp"),
        }
        g0v_cfh_agg["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_cfh_agg)
        _run_case(
            "r04_b4_cd55_legacy_aggregate_only_block_held",
            _make_composite_bundle(bank_lot_id, mcb_id, pv_cfh, leg_cfh, g0v_cfh_agg),
            "HOLD_COMPOSITE_RELEASE",
            expected_legacy_pass=False,
            expected_gate0v_pass=False,
            expected_token="CD55_MISSING_PER_STRAIN_RESULTS_AGGREGATE_ONLY_REJECTED",
        )

        # 33. R05-B1a: File-backed directory store WITH valid archived bank payload -> PASS_COMPOSITE_CLINICAL_RELEASE!
        trusted_dir = Path(td) / "independent_qa_store_dir"
        v38.write_record_to_trusted_qualification_store(
            trusted_dir,
            auth_bank_rec,
            category="bank_qualifications",
            archived_payload=bank_bundle,
        )
        res_dir_pass = _run_case(
            "r05_b1_file_backed_dir_store_with_valid_archived_bank_payload_passes",
            clin_bundle,
            "PASS_COMPOSITE_CLINICAL_RELEASE",
            store_path=trusted_dir,
            expected_legacy_pass=True,
            expected_gate0v_pass=True,
        )
        if res_dir_pass["prior_qualification_authentication"].get("archived_bank_payload_verified") is not True:
            cases[-1]["passed"] = False

        # 34. R05-B1b: Embedded-dict registry JSON store with ABSENT archived bank payload -> HOLD (exit 2)!
        reg_absent_arch = Path(td) / "r05_reg_absent_archive.json"
        v38.write_record_to_trusted_qualification_store(
            reg_absent_arch,
            auth_bank_rec,
            category="bank_qualifications",
            archived_payload=None,
        )
        clin_bundle_file = Path(td) / "r05_clin_bundle.json"
        clin_bundle_file.write_text(json.dumps(clin_bundle), encoding="utf-8")
        res_reg_abs, rc_reg_abs = evaluate_composite_lot_file(
            clin_bundle_file,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=reg_absent_arch,
            openislet_root=openislet_root,
        )
        ok_34 = bool(
            rc_reg_abs == 2
            and res_reg_abs["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and (res_reg_abs["gate0v_result_summary"] or {}).get("verdict") == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
            and "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD" in res_reg_abs["holds"]
            and res_reg_abs["prior_qualification_authentication"]["archived_bank_payload_verified"] is False
        )
        cases.append({
            "case": "r05_b1_registry_store_absent_archived_bank_payload_held_exit_2",
            "expected_verdict": "HOLD_COMPOSITE_RELEASE",
            "actual_verdict": res_reg_abs["composite_verdict"],
            "operational_tier": res_reg_abs.get("operational_tier"),
            "legacy_passed": (res_reg_abs["legacy_result_summary"] or {}).get("legacy_evaluator_passed"),
            "legacy_tier": (res_reg_abs["legacy_result_summary"] or {}).get("lot_release_readiness_tier"),
            "legacy_resolved_pvid": (res_reg_abs["legacy_result_summary"] or {}).get("resolved_product_variant_id"),
            "gate0v_passed": (res_reg_abs["gate0v_result_summary"] or {}).get("gate0v_evaluator_passed"),
            "gate0v_verdict": (res_reg_abs["gate0v_result_summary"] or {}).get("verdict"),
            "expected_token": "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD",
            "exit_code": rc_reg_abs,
            "archived_bank_payload_verified": res_reg_abs["prior_qualification_authentication"]["archived_bank_payload_verified"],
            "hard_stops": res_reg_abs["hard_stops"][:3],
            "holds": res_reg_abs["holds"][:4],
            "passed": ok_34,
        })

        # 35. R05-B1c: Embedded-dict registry JSON store with NON-OBJECT archived bank payloads (None/list/str/int) -> HOLD (exit 2)!
        reg_nonobj_all_ok = True
        for tag, bad_val in (("none", None), ("list", ["not", "an", "object"]), ("str", "invalid"), ("int", 7)):
            reg_bad = Path(td) / f"r05_reg_nonobj_{tag}.json"
            reg_bad.write_text(
                json.dumps({
                    "schema_version": v38.TRUSTED_STORE_SCHEMA_VERSION,
                    "store_authority_id": "OPENISLET_QA_RELEASE_BOARD_V1",
                    "bank_qualifications": {auth_bank_rec["sha256"]: auth_bank_rec},
                    "process_qualifications": {},
                    "archived_payloads": {auth_bank_rec["bank_payload_sha256"]: bad_val},
                }),
                encoding="utf-8",
            )
            r_b, rc_b = evaluate_composite_lot_file(
                clin_bundle_file,
                legacy_evaluator=leg_fn,
                gate0v_evaluator=g0v_fn,
                trusted_qualification_store=reg_bad,
                openislet_root=openislet_root,
            )
            if not (
                rc_b == 2
                and r_b["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
                and (r_b["gate0v_result_summary"] or {}).get("verdict") == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
                and "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD" in r_b["holds"]
                and r_b["prior_qualification_authentication"]["archived_bank_payload_verified"] is False
            ):
                reg_nonobj_all_ok = False
        cases.append({
            "case": "r05_b1_registry_store_nonobject_archived_bank_payloads_held_exit_2",
            "expected_verdict": "HOLD_COMPOSITE_RELEASE",
            "actual_verdict": "HOLD_COMPOSITE_RELEASE" if reg_nonobj_all_ok else "UNEXPECTED_PASS_OR_EXIT",
            "operational_tier": "LOT_RELEASE_SURROGATE",
            "legacy_passed": True,
            "legacy_tier": LEGACY_PASS_TIER,
            "legacy_resolved_pvid": pv_lead,
            "gate0v_passed": False,
            "gate0v_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
            "expected_token": "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD",
            "exit_code": 2 if reg_nonobj_all_ok else -1,
            "archived_bank_payload_verified": False if reg_nonobj_all_ok else None,
            "hard_stops": [],
            "holds": ["HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD"],
            "passed": reg_nonobj_all_ok,
        })

        # 36. R05-B1d: File-backed directory store with ABSENT archived bank payload -> HOLD (exit 2)!
        dir_absent_arch = Path(td) / "r05_dir_absent_archive"
        v38.write_record_to_trusted_qualification_store(
            dir_absent_arch,
            auth_bank_rec,
            category="bank_qualifications",
            archived_payload=None,
        )
        res_dir_abs, rc_dir_abs = evaluate_composite_lot_file(
            clin_bundle_file,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=dir_absent_arch,
            openislet_root=openislet_root,
        )
        ok_36 = bool(
            rc_dir_abs == 2
            and res_dir_abs["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and (res_dir_abs["gate0v_result_summary"] or {}).get("verdict") == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
            and "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD" in res_dir_abs["holds"]
            and res_dir_abs["prior_qualification_authentication"]["archived_bank_payload_verified"] is False
        )
        cases.append({
            "case": "r05_b1_dir_store_absent_archived_bank_payload_held_exit_2",
            "expected_verdict": "HOLD_COMPOSITE_RELEASE",
            "actual_verdict": res_dir_abs["composite_verdict"],
            "operational_tier": res_dir_abs.get("operational_tier"),
            "legacy_passed": (res_dir_abs["legacy_result_summary"] or {}).get("legacy_evaluator_passed"),
            "legacy_tier": (res_dir_abs["legacy_result_summary"] or {}).get("lot_release_readiness_tier"),
            "legacy_resolved_pvid": (res_dir_abs["legacy_result_summary"] or {}).get("resolved_product_variant_id"),
            "gate0v_passed": (res_dir_abs["gate0v_result_summary"] or {}).get("gate0v_evaluator_passed"),
            "gate0v_verdict": (res_dir_abs["gate0v_result_summary"] or {}).get("verdict"),
            "expected_token": "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD",
            "exit_code": rc_dir_abs,
            "archived_bank_payload_verified": res_dir_abs["prior_qualification_authentication"]["archived_bank_payload_verified"],
            "hard_stops": res_dir_abs["hard_stops"][:3],
            "holds": res_dir_abs["holds"][:4],
            "passed": ok_36,
        })

        # 37. R05-B1e: File-backed directory store with NON-OBJECT archived bank payloads (None/list/str/int) -> HOLD (exit 2)!
        dir_nonobj_all_ok = True
        for tag, bad_val in (("none", None), ("list", ["not", "an", "object"]), ("str", "invalid"), ("int", 7)):
            dir_bad = Path(td) / f"r05_dir_nonobj_{tag}"
            v38.write_record_to_trusted_qualification_store(
                dir_bad,
                auth_bank_rec,
                category="bank_qualifications",
                archived_payload=None,
            )
            arch_dir_b = dir_bad / "archived_payloads"
            arch_dir_b.mkdir(parents=True, exist_ok=True)
            (arch_dir_b / f"{auth_bank_rec['bank_payload_sha256']}.json").write_text(
                json.dumps(bad_val), encoding="utf-8"
            )
            r_d, rc_d = evaluate_composite_lot_file(
                clin_bundle_file,
                legacy_evaluator=leg_fn,
                gate0v_evaluator=g0v_fn,
                trusted_qualification_store=dir_bad,
                openislet_root=openislet_root,
            )
            if not (
                rc_d == 2
                and r_d["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
                and (r_d["gate0v_result_summary"] or {}).get("verdict") == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
                and "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD" in r_d["holds"]
                and r_d["prior_qualification_authentication"]["archived_bank_payload_verified"] is False
            ):
                dir_nonobj_all_ok = False
        cases.append({
            "case": "r05_b1_dir_store_nonobject_archived_bank_payloads_held_exit_2",
            "expected_verdict": "HOLD_COMPOSITE_RELEASE",
            "actual_verdict": "HOLD_COMPOSITE_RELEASE" if dir_nonobj_all_ok else "UNEXPECTED_PASS_OR_EXIT",
            "operational_tier": "LOT_RELEASE_SURROGATE",
            "legacy_passed": True,
            "legacy_tier": LEGACY_PASS_TIER,
            "legacy_resolved_pvid": pv_lead,
            "gate0v_passed": False,
            "gate0v_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
            "expected_token": "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD",
            "exit_code": 2 if dir_nonobj_all_ok else -1,
            "archived_bank_payload_verified": False if dir_nonobj_all_ok else None,
            "hard_stops": [],
            "holds": ["HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD"],
            "passed": dir_nonobj_all_ok,
        })

        # 38. R06-B1a: Indirect-only conditional escape on BANK_QUALIFICATION -> HOLD_COMPOSITE_RELEASE (exit 2), NEVER PASS!
        g0v_ind_only = v38.build_passing_reference_payload(
            lot_id=bank_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            qualification_tier="BANK_QUALIFICATION",
            use_direct_infected_veh_survivor_mode=False,
            openislet_root=openislet_root,
        )
        ind_bundle = _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, g0v_ind_only)
        ind_bundle_file = Path(td) / "r06_ind_only_bundle.json"
        ind_bundle_file.write_text(json.dumps(ind_bundle), encoding="utf-8")
        res_ind_c, rc_ind_c = evaluate_composite_lot_file(
            ind_bundle_file,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            openislet_root=openislet_root,
        )
        ok_38 = bool(
            rc_ind_c == 2
            and res_ind_c["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and (res_ind_c["legacy_result_summary"] or {}).get("legacy_evaluator_passed") is True
            and (res_ind_c["gate0v_result_summary"] or {}).get("verdict") == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
            and "HOLD_INDIRECT_CONDITIONAL_ESCAPE_UNSUPPORTED_FOR_RELEASE" in res_ind_c["holds"]
        )
        cases.append({
            "case": "r06_b1_indirect_only_conditional_escape_composite_hold_exit_2",
            "expected_verdict": "HOLD_COMPOSITE_RELEASE",
            "actual_verdict": res_ind_c["composite_verdict"],
            "operational_tier": res_ind_c.get("operational_tier"),
            "legacy_passed": (res_ind_c["legacy_result_summary"] or {}).get("legacy_evaluator_passed"),
            "legacy_tier": (res_ind_c["legacy_result_summary"] or {}).get("lot_release_readiness_tier"),
            "legacy_resolved_pvid": (res_ind_c["legacy_result_summary"] or {}).get("resolved_product_variant_id"),
            "gate0v_passed": (res_ind_c["gate0v_result_summary"] or {}).get("gate0v_evaluator_passed"),
            "gate0v_verdict": (res_ind_c["gate0v_result_summary"] or {}).get("verdict"),
            "expected_token": "HOLD_INDIRECT_CONDITIONAL_ESCAPE_UNSUPPORTED_FOR_RELEASE",
            "exit_code": rc_ind_c,
            "hard_stops": res_ind_c["hard_stops"][:3],
            "holds": res_ind_c["holds"][:4],
            "passed": ok_38,
        })

        # 39. R06-B1b: Indirect-only bundle WITH conclusive adverse viral caspase blockade -> FAIL_HARD_STOP (exit 3)!
        g0v_ind_adv = copy.deepcopy(g0v_ind_only)
        g0v_ind_adv["gate0v_kill_stress_ap1903"]["active_or_persistent_hcmv_infection"]["plvap_iec"]["caspase9_3_activity_fold_over_vehicle"] = "1.2"
        g0v_ind_adv["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_ind_adv)
        _run_case(
            "r06_b1_indirect_only_with_adverse_caspase_composite_hard_stop",
            _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, g0v_ind_adv),
            "FAIL_HARD_STOP_COMPOSITE_RELEASE",
            expected_legacy_pass=True,
            expected_gate0v_pass=False,
            expected_token="VIRAL_CASPASE_BLOCKADE",
        )

        # 40. R06-B2: Exact component-probability ratio boundary (veh 51/100, treated 0/90402 -> HOLD exit 2; 0/90404 -> PASS exit 0)!
        g0v_b2_h = copy.deepcopy(g0v_bank)
        arm_b2 = g0v_b2_h["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"]["alpha"]
        arm_b2["veh_72h_viable_n"] = 51
        arm_b2["veh_72h_input_n"] = 100
        arm_b2["ap1903_72h_input_n"] = 90402
        arm_b2["ap1903_72h_viable_survivors_k"] = 0
        v38.reconcile_fixture_per_unit_counts(g0v_b2_h)
        g0v_b2_h["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_b2_h)
        _run_case(
            "r06_b2_exact_component_ratio_veh51of100_0of90402_composite_hold",
            _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, g0v_b2_h),
            "HOLD_COMPOSITE_RELEASE",
            expected_legacy_pass=True,
            expected_gate0v_pass=False,
            expected_token="72H_UNDERPOWERED_N_EFF",
        )

        g0v_b2_p = copy.deepcopy(g0v_b2_h)
        g0v_b2_p["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"]["alpha"]["ap1903_72h_input_n"] = 90404
        v38.reconcile_fixture_per_unit_counts(g0v_b2_p)
        g0v_b2_p["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_b2_p)
        _run_case(
            "r06_b2_exact_component_ratio_veh51of100_0of90404_composite_pass",
            _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, g0v_b2_p),
            "PASS_COMPOSITE_BANK_QUALIFICATION",
            expected_legacy_pass=True,
            expected_gate0v_pass=True,
        )

        # 41. R06-B3a: Indeterminate straddling interval (1/5,000) under low vehicle survival -> HOLD (exit 2), NEVER FAIL_HARD_STOP!
        g0v_strad = copy.deepcopy(g0v_bank)
        arm_st = g0v_strad["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"]["alpha"]
        arm_st["veh_24h_viable_n"] = 50
        arm_st["veh_24h_input_n"] = 1000
        arm_st["ap1903_24h_input_n"] = 5000
        arm_st["ap1903_24h_viable_survivors_k"] = 1
        v38.reconcile_fixture_per_unit_counts(g0v_strad)
        g0v_strad["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_strad)
        _run_case(
            "r06_b3_1of5000_straddling_under_low_veh_composite_hold_not_hard_stop",
            _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, g0v_strad),
            "HOLD_COMPOSITE_RELEASE",
            expected_legacy_pass=True,
            expected_gate0v_pass=False,
            expected_token="HOLD_INDETERMINATE_INTERVAL_STRADDLING_CAP_UNDER_CONTROL_HOLD",
        )

        # 42. R06-B3b: Conclusively adverse 30/5,000 under low vehicle survival -> FAIL_HARD_STOP_COMPOSITE_RELEASE!
        g0v_conc = copy.deepcopy(g0v_strad)
        g0v_conc["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"]["alpha"]["ap1903_24h_viable_survivors_k"] = 30
        v38.reconcile_fixture_per_unit_counts(g0v_conc)
        g0v_conc["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_conc)
        _run_case(
            "r06_b3_30of5000_conclusive_l_gt_cap_under_low_veh_composite_hard_stop",
            _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, g0v_conc),
            "FAIL_HARD_STOP_COMPOSITE_RELEASE",
            expected_legacy_pass=True,
            expected_gate0v_pass=False,
            expected_token="AP1903_24H_KILL_BELOW_99P9PCT_ER_STRESS_TG_OR_TM_ALPHA",
        )

        # 43-46. R06-B4: Archived bank payload full structure, self-digest, nested identity, and live revalidation
        #        negative tests across BOTH store layouts (registry JSON AND file-backed directory store, CLI exit 2)!
        def _run_r06_b4_both_layouts(case_name: str, bad_arch_obj: Dict[str, Any], arch_key_sha: str) -> None:
            bad_rec_b4 = copy.deepcopy(auth_bank_rec)
            bad_rec_b4["bank_payload_sha256"] = arch_key_sha
            bad_rec_b4["sha256"] = compute_qualification_record_sha256(bad_rec_b4)
            g0v_surr_b4 = v38.build_passing_reference_payload(
                lot_id=clin_lot_id,
                mcb_id=mcb_id,
                product_variant_id=pv_lead,
                qualification_tier="LOT_RELEASE_SURROGATE",
                bridged_mcb_qualification_sha256=bad_rec_b4["sha256"],
                openislet_root=openislet_root,
            )
            b4_bundle = _make_composite_bundle(clin_lot_id, mcb_id, pv_lead, leg_clin, g0v_surr_b4)
            b4_file = Path(td) / f"r06_b4_bundle_{case_name}.json"
            b4_file.write_text(json.dumps(b4_bundle), encoding="utf-8")

            reg_st = Path(td) / f"r06_b4_reg_{case_name}.json"
            reg_st.write_text(
                json.dumps({
                    "schema_version": v38.TRUSTED_STORE_SCHEMA_VERSION,
                    "store_authority_id": "OPENISLET_QA_RELEASE_BOARD_V1",
                    "bank_qualifications": {bad_rec_b4["sha256"]: bad_rec_b4},
                    "process_qualifications": {},
                    "archived_payloads": {arch_key_sha: bad_arch_obj},
                }),
                encoding="utf-8",
            )
            dir_st = Path(td) / f"r06_b4_dir_{case_name}"
            v38.write_record_to_trusted_qualification_store(dir_st, bad_rec_b4, category="bank_qualifications", archived_payload=None)
            (dir_st / "archived_payloads").mkdir(parents=True, exist_ok=True)
            (dir_st / "archived_payloads" / f"{arch_key_sha}.json").write_text(json.dumps(bad_arch_obj), encoding="utf-8")

            all_ok_both = True
            last_holds_b4: List[str] = []
            for st_l in (reg_st, dir_st):
                r_l, rc_l = evaluate_composite_lot_file(
                    b4_file,
                    legacy_evaluator=leg_fn,
                    gate0v_evaluator=g0v_fn,
                    trusted_qualification_store=st_l,
                    openislet_root=openislet_root,
                )
                last_holds_b4 = r_l["holds"]
                if not (
                    rc_l == 2
                    and r_l["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
                    and (r_l["gate0v_result_summary"] or {}).get("verdict") == "HOLD_INCOMPLETE_OR_UNDERPOWERED"
                    and "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD" in r_l["holds"]
                    and r_l["prior_qualification_authentication"]["archived_bank_payload_verified"] is False
                ):
                    all_ok_both = False
            cases.append({
                "case": case_name,
                "expected_verdict": "HOLD_COMPOSITE_RELEASE",
                "actual_verdict": "HOLD_COMPOSITE_RELEASE" if all_ok_both else "UNEXPECTED_PASS_OR_EXIT",
                "operational_tier": "LOT_RELEASE_SURROGATE",
                "legacy_passed": True,
                "legacy_tier": LEGACY_PASS_TIER,
                "legacy_resolved_pvid": pv_lead,
                "gate0v_passed": False,
                "gate0v_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
                "expected_token": "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD",
                "exit_code": 2 if all_ok_both else -1,
                "archived_bank_payload_verified": False if all_ok_both else None,
                "hard_stops": [],
                "holds": last_holds_b4[:4],
                "passed": all_ok_both,
            })

        # 43. (i) Metadata-only stub archive
        stub_b4 = {
            "lot_id": bank_lot_id,
            "mcb_id": mcb_id,
            "product_variant_id": pv_lead,
            "qualification_tier": "BANK_QUALIFICATION",
            "antiviral_genotype_stratum": "TYK2_WT__IFIH1_WT_OR_A946T",
        }
        stub_b4_sha = v38.compute_canonical_lot_sha256(stub_b4)
        stub_b4["payload_sha256"] = stub_b4_sha
        _run_r06_b4_both_layouts("r06_b4_both_layouts_metadata_only_stub_archive_held_exit_2", stub_b4, stub_b4_sha)

        # 44. (ii) Tampered internal payload_sha256 on archived composite bank bundle
        tamp_b4 = copy.deepcopy(bank_bundle)
        tamp_b4_sha = compute_composite_payload_sha256(tamp_b4)
        tamp_b4["payload_sha256"] = hashlib.sha256(b"TAMPERED_COMP_ARCHIVE_SELF_SHA").hexdigest()
        _run_r06_b4_both_layouts("r06_b4_both_layouts_tampered_internal_payload_sha256_held_exit_2", tamp_b4, tamp_b4_sha)

        # 45. (iii) Contradictory nested mcb_id inside archived composite bank bundle
        contra_g0v_b4 = v38.build_passing_reference_payload(
            lot_id=bank_lot_id,
            mcb_id="MCB-NESTED-CONFLICT-999",
            product_variant_id=pv_lead,
            qualification_tier="BANK_QUALIFICATION",
            openislet_root=openislet_root,
        )
        contra_b4 = _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, contra_g0v_b4)
        _run_r06_b4_both_layouts("r06_b4_both_layouts_contradictory_nested_mcb_id_held_exit_2", contra_b4, contra_b4["payload_sha256"])

        # 46. (iv) Structurally complete archived bank bundle that FAILS BANK_QUALIFICATION
        fail_g0v_b4 = copy.deepcopy(g0v_bank)
        fail_g0v_b4["gate0v_b_infectious_challenge"]["pathogens"]["cvb4_e2"]["day28_persistence_by_lineage"]["pericyte"]["stage2_confirmed_infectious_k"] = 1
        fail_g0v_b4["payload_sha256"] = v38.compute_canonical_lot_sha256(fail_g0v_b4)
        fail_bundle_b4 = _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, fail_g0v_b4)
        _run_r06_b4_both_layouts("r06_b4_both_layouts_structurally_complete_failing_archive_held_exit_2", fail_bundle_b4, fail_bundle_b4["payload_sha256"])

        # 47. R06-M3: Autologous process record carrying allogeneic PASS_WHOLEGRAFT_BANK_QUALIFICATION fails closed!
        bad_m3_proc = v38.build_authenticated_process_qualification_record(
            product_variant_id=pv_d1a,
            process_qual_id="PROCQUAL-M3-WRONG-BANK-VERDICT",
            underlying_gate0v_verdict="PASS_WHOLEGRAFT_BANK_QUALIFICATION",
        )
        v38.write_record_to_trusted_qualification_store(trusted_store, bad_m3_proc, category="process_qualifications")
        g0v_m3_bad = v38.build_passing_reference_payload(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_d1a,
            qualification_tier="AUTOLOGOUS_D1B_PROCESS_QUAL",
            process_qualification_ref_sha256=bad_m3_proc["sha256"],
            openislet_root=openislet_root,
        )
        _run_case(
            "r06_m3_autologous_process_record_with_bank_pass_verdict_held",
            _make_composite_bundle(clin_lot_id, mcb_id, pv_d1a, leg_d1a_clin, g0v_m3_bad),
            "HOLD_COMPOSITE_RELEASE",
            store_path=trusted_store,
            expected_gate0v_pass=False,
            expected_token="UNDERLYING_GATE0V_VERDICT_NOT_AUTOLOGOUS_PROCESS_QUAL_PASS",
        )

        # ------------------------------------------------------------------
        # Round-07 Final-Closure Differential Matrix (B1, B2, M1)
        # ------------------------------------------------------------------
        # 48. R07-B1a: Plain whole-graft-only bank archive (NO archived legacy observations) in BOTH store
        #     layouts (embedded-dict registry JSON AND file-backed directory store) MUST BE REJECTED by
        #     composite clinical release (exit 2, archived_bank_payload_live_legacy_revalidation_passed=False,
        #     HOLD_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE, NEVER PASS_COMPOSITE_CLINICAL_RELEASE)!
        plain_bank_rec = copy.deepcopy(auth_bank_rec)
        plain_bank_rec["bank_payload_sha256"] = g0v_bank["payload_sha256"]
        plain_bank_rec["sha256"] = compute_qualification_record_sha256(plain_bank_rec)
        g0v_clin_plain = v38.build_passing_reference_payload(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            qualification_tier="LOT_RELEASE_SURROGATE",
            bridged_mcb_qualification_sha256=plain_bank_rec["sha256"],
            openislet_root=openislet_root,
        )
        clin_plain_bundle = _make_composite_bundle(clin_lot_id, mcb_id, pv_lead, leg_clin, g0v_clin_plain)
        clin_plain_file = Path(td) / "r07_b1_clin_plain_bundle.json"
        clin_plain_file.write_text(json.dumps(clin_plain_bundle), encoding="utf-8")

        reg_plain_r07 = Path(td) / "r07_b1_reg_plain.json"
        dir_plain_r07 = Path(td) / "r07_b1_dir_plain"
        v38.write_record_to_trusted_qualification_store(
            reg_plain_r07, plain_bank_rec, category="bank_qualifications", archived_payload=g0v_bank
        )
        v38.write_record_to_trusted_qualification_store(
            dir_plain_r07, plain_bank_rec, category="bank_qualifications", archived_payload=g0v_bank
        )

        r07_plain_comp_ok = True
        last_plain_holds: List[str] = []
        for st_pl in (reg_plain_r07, dir_plain_r07):
            r_pl, rc_pl = evaluate_composite_lot_file(
                clin_plain_file,
                legacy_evaluator=leg_fn,
                gate0v_evaluator=g0v_fn,
                trusted_qualification_store=st_pl,
                openislet_root=openislet_root,
            )
            last_plain_holds = r_pl["holds"]
            pqa_pl = r_pl["prior_qualification_authentication"]
            if not (
                rc_pl == 2
                and r_pl["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
                and pqa_pl.get("archived_bank_payload_verified") is False
                and pqa_pl.get("archived_bank_payload_live_g0v_revalidation_passed") is True
                and pqa_pl.get("archived_bank_payload_live_legacy_revalidation_passed") is False
                and "HOLD_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE" in r_pl["holds"]
                and "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD" in r_pl["holds"]
                and "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE" in r_pl["holds"]
            ):
                r07_plain_comp_ok = False
        cases.append({
            "case": "r07_b1_both_layouts_plain_standalone_wholegraft_bank_archive_rejected_exit_2",
            "expected_verdict": "HOLD_COMPOSITE_RELEASE",
            "actual_verdict": "HOLD_COMPOSITE_RELEASE" if r07_plain_comp_ok else "UNEXPECTED_PASS_OR_META",
            "operational_tier": "LOT_RELEASE_SURROGATE",
            "legacy_passed": True,
            "legacy_tier": LEGACY_PASS_TIER,
            "legacy_resolved_pvid": pv_lead,
            "gate0v_passed": True,
            "gate0v_verdict": "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE",
            "expected_token": "HOLD_MISSING_ARCHIVED_LEGACY_PAYLOAD_FOR_COMPOSITE_RELEASE",
            "exit_code": 2 if r07_plain_comp_ok else -1,
            "archived_bank_payload_verified": False if r07_plain_comp_ok else None,
            "archived_bank_payload_live_g0v_revalidation_passed": True if r07_plain_comp_ok else None,
            "archived_bank_payload_live_legacy_revalidation_passed": False if r07_plain_comp_ok else None,
            "hard_stops": [],
            "holds": last_plain_holds[:4],
            "passed": r07_plain_comp_ok,
        })

        # 49. R07-B1b: Composite bank archive with FAILING archived legacy observations (both hard-stop
        #     legacy kill failure AND incomplete legacy observations) in BOTH store layouts -> REJECTED (exit 2)!
        leg_bank_fail_s9 = copy.deepcopy(leg_bank)
        leg_bank_fail_s9["obs_icasp9_log10_kill"] = 1.0
        leg_bank_incomplete = {
            "current_lot_id": bank_lot_id,
            "mcb_id": mcb_id,
            "product_variant_id": pv_lead,
            "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,
        }
        r07_fail_leg_ok = True
        last_fail_leg_holds: List[str] = []
        for sub_tag, bad_leg_obs in (("s9_hard_stop", leg_bank_fail_s9), ("incomplete_panel", leg_bank_incomplete)):
            bad_leg_bundle = _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, bad_leg_obs, g0v_bank)
            bad_leg_rec = copy.deepcopy(auth_bank_rec)
            bad_leg_rec["bank_payload_sha256"] = bad_leg_bundle["payload_sha256"]
            bad_leg_rec["sha256"] = compute_qualification_record_sha256(bad_leg_rec)
            g0v_surr_bl = v38.build_passing_reference_payload(
                lot_id=clin_lot_id,
                mcb_id=mcb_id,
                product_variant_id=pv_lead,
                qualification_tier="LOT_RELEASE_SURROGATE",
                bridged_mcb_qualification_sha256=bad_leg_rec["sha256"],
                openislet_root=openislet_root,
            )
            bl_file = Path(td) / f"r07_b1_fail_leg_{sub_tag}_clin.json"
            bl_file.write_text(
                json.dumps(_make_composite_bundle(clin_lot_id, mcb_id, pv_lead, leg_clin, g0v_surr_bl)),
                encoding="utf-8",
            )
            reg_bl = Path(td) / f"r07_b1_fail_leg_{sub_tag}_reg.json"
            dir_bl = Path(td) / f"r07_b1_fail_leg_{sub_tag}_dir"
            v38.write_record_to_trusted_qualification_store(
                reg_bl, bad_leg_rec, category="bank_qualifications", archived_payload=bad_leg_bundle
            )
            v38.write_record_to_trusted_qualification_store(
                dir_bl, bad_leg_rec, category="bank_qualifications", archived_payload=bad_leg_bundle
            )
            for st_bl in (reg_bl, dir_bl):
                r_bl, rc_bl = evaluate_composite_lot_file(
                    bl_file,
                    legacy_evaluator=leg_fn,
                    gate0v_evaluator=g0v_fn,
                    trusted_qualification_store=st_bl,
                    openislet_root=openislet_root,
                )
                last_fail_leg_holds = r_bl["holds"]
                pqa_bl = r_bl["prior_qualification_authentication"]
                if not (
                    rc_bl == 2
                    and r_bl["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
                    and pqa_bl.get("archived_bank_payload_verified") is False
                    and pqa_bl.get("archived_bank_payload_live_legacy_revalidation_passed") is False
                    and "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD" in r_bl["holds"]
                    and any("ARCHIVED_LEGACY_REVALIDATION_FAILED" in h for h in r_bl["holds"])
                ):
                    r07_fail_leg_ok = False
        cases.append({
            "case": "r07_b1_both_layouts_composite_bank_archive_failing_legacy_obs_rejected_exit_2",
            "expected_verdict": "HOLD_COMPOSITE_RELEASE",
            "actual_verdict": "HOLD_COMPOSITE_RELEASE" if r07_fail_leg_ok else "UNEXPECTED_PASS_OR_META",
            "operational_tier": "LOT_RELEASE_SURROGATE",
            "legacy_passed": True,
            "legacy_tier": LEGACY_PASS_TIER,
            "legacy_resolved_pvid": pv_lead,
            "gate0v_passed": True,
            "gate0v_verdict": "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE",
            "expected_token": "ARCHIVED_LEGACY_REVALIDATION_FAILED",
            "exit_code": 2 if r07_fail_leg_ok else -1,
            "archived_bank_payload_verified": False if r07_fail_leg_ok else None,
            "archived_bank_payload_live_legacy_revalidation_passed": False if r07_fail_leg_ok else None,
            "hard_stops": [],
            "holds": last_fail_leg_holds[:4],
            "passed": r07_fail_leg_ok,
        })

        # 50. R07-B1c: Complete passing dual-replay composite bank archive in BOTH store layouts -> ACCEPTED
        #     (PASS_COMPOSITE_CLINICAL_RELEASE, exit 0) with explicit BOTH live replay booleans == True!
        r07_dual_pass_ok = True
        for st_ok in (trusted_store, trusted_dir):
            r_dp, rc_dp = evaluate_composite_lot_file(
                clin_bundle_file,
                legacy_evaluator=leg_fn,
                gate0v_evaluator=g0v_fn,
                trusted_qualification_store=st_ok,
                openislet_root=openislet_root,
            )
            pqa_dp = r_dp["prior_qualification_authentication"]
            if not (
                rc_dp == 0
                and r_dp["composite_verdict"] == "PASS_COMPOSITE_CLINICAL_RELEASE"
                and pqa_dp.get("archived_bank_payload_verified") is True
                and pqa_dp.get("archived_bank_payload_live_g0v_revalidation_passed") is True
                and pqa_dp.get("archived_bank_payload_live_legacy_revalidation_passed") is True
            ):
                r07_dual_pass_ok = False
        cases.append({
            "case": "r07_b1_both_layouts_complete_dual_replay_composite_bank_archive_passes_exit_0",
            "expected_verdict": "PASS_COMPOSITE_CLINICAL_RELEASE",
            "actual_verdict": "PASS_COMPOSITE_CLINICAL_RELEASE" if r07_dual_pass_ok else "UNEXPECTED_HOLD_OR_META",
            "operational_tier": "LOT_RELEASE_SURROGATE",
            "legacy_passed": True,
            "legacy_tier": LEGACY_PASS_TIER,
            "legacy_resolved_pvid": pv_lead,
            "gate0v_passed": True,
            "gate0v_verdict": "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE",
            "expected_token": None,
            "exit_code": 0 if r07_dual_pass_ok else -1,
            "archived_bank_payload_verified": True if r07_dual_pass_ok else None,
            "archived_bank_payload_live_g0v_revalidation_passed": True if r07_dual_pass_ok else None,
            "archived_bank_payload_live_legacy_revalidation_passed": True if r07_dual_pass_ok else None,
            "hard_stops": [],
            "holds": [],
            "passed": r07_dual_pass_ok,
        })

        # 51. R07-B1d: Standalone verify_iip0043 (legacy_evaluator=None) STILL accepts plain whole-graft-only
        #     bank archives across BOTH store layouts (standalone evidence boundary strictly preserved)!
        r07_standalone_ok = True
        for st_pl in (reg_plain_r07, dir_plain_r07):
            r_sa = g0v_fn(g0v_clin_plain, trusted_qualification_store=st_pl, openislet_root=openislet_root)
            pqa_sa = r_sa["lot_binding"]["prior_qualification_authentication"]
            if not (
                r_sa["verdict"] == "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE"
                and pqa_sa.get("archived_bank_payload_verified") is True
                and pqa_sa.get("archived_bank_payload_live_g0v_revalidation_passed") is True
                and pqa_sa.get("archived_bank_payload_live_legacy_revalidation_passed") is None
            ):
                r07_standalone_ok = False
        cases.append({
            "case": "r07_b1_both_layouts_standalone_verify_iip0043_accepts_plain_wholegraft_bank_archive",
            "expected_verdict": "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE",
            "actual_verdict": "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE" if r07_standalone_ok else "UNEXPECTED_HOLD",
            "operational_tier": "LOT_RELEASE_SURROGATE",
            "legacy_passed": None,
            "legacy_tier": None,
            "legacy_resolved_pvid": None,
            "gate0v_passed": True if r07_standalone_ok else False,
            "gate0v_verdict": "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE" if r07_standalone_ok else "HOLD",
            "expected_token": None,
            "exit_code": 0 if r07_standalone_ok else -1,
            "archived_bank_payload_verified": True if r07_standalone_ok else None,
            "archived_bank_payload_live_g0v_revalidation_passed": True if r07_standalone_ok else None,
            "archived_bank_payload_live_legacy_revalidation_passed": None,
            "hard_stops": [],
            "holds": [],
            "passed": r07_standalone_ok,
        })

        # 52. R07-B2: PAIRED_HIGH_INPUT_ALIQUOT with mismatched counts & well-formed 64-hex digest -> HOLD (exit 2), NEVER PASS!
        g0v_phi_c = copy.deepcopy(g0v_bank)
        arm_phi_c = g0v_phi_c["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]
        arm_phi_c["infected_surveillance_aliquot_linkage_mode"] = "PAIRED_HIGH_INPUT_ALIQUOT"
        arm_phi_c["paired_aliquot_linkage_evidence_sha256"] = v38._valid_digest("r07_b2_comp_paired_digest")
        arm_phi_c["ap1903_72h_input_n"] = 100000
        arm_phi_c["ap1903_72h_viable_survivors_k"] = 0
        arm_phi_c["pre_ap1903_lineage_input_cells_n"] = 5_141_940
        arm_phi_c["post_ap1903_viable_survivors_total_n"] = 2
        arm_phi_c["survivors_scored_n"] = 2
        v38.reconcile_fixture_per_unit_counts(g0v_phi_c)
        g0v_phi_c["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_phi_c)
        _run_case(
            "r07_b2_paired_high_input_mismatched_counts_valid_digest_composite_hold",
            _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, g0v_phi_c),
            "HOLD_COMPOSITE_RELEASE",
            expected_legacy_pass=True,
            expected_gate0v_pass=False,
            expected_token="HOLD_NON_SAME_ALIQUOT_UNVERIFIED_COUNT_RECONCILIATION",
        )

        # 53. R07-M1: Zero-event 0/1,000 straddling interval under low vehicle control -> HOLD with straddling token!
        g0v_zstrad_c = copy.deepcopy(g0v_bank)
        arm_zsc = g0v_zstrad_c["gate0v_kill_stress_ap1903"]["er_stress_tg_or_tm"]["alpha"]
        arm_zsc["veh_24h_viable_n"] = 50
        arm_zsc["veh_24h_input_n"] = 1000
        arm_zsc["ap1903_24h_input_n"] = 1000
        arm_zsc["ap1903_24h_viable_survivors_k"] = 0
        v38.reconcile_fixture_per_unit_counts(g0v_zstrad_c)
        g0v_zstrad_c["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_zstrad_c)
        _run_case(
            "r07_m1_zero_event_0of1000_straddling_under_low_veh_composite_hold",
            _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, g0v_zstrad_c),
            "HOLD_COMPOSITE_RELEASE",
            expected_legacy_pass=True,
            expected_gate0v_pass=False,
            expected_token="HOLD_INDETERMINATE_INTERVAL_STRADDLING_CAP_UNDER_CONTROL_HOLD",
        )

        # ------------------------------------------------------------------
        # Round-08 Final-Closure Parity Matrix (B1 Direct vs Archived Envelope Parity)
        # ------------------------------------------------------------------
        def _run_r08_b1_parity_case(
            case_name: str,
            mutate_archive_fn: Callable[[Dict[str, Any]], None],
            expected_direct_hold: str,
        ) -> None:
            arch_r08 = copy.deepcopy(bank_bundle)
            mutate_archive_fn(arch_r08)
            arch_r08["payload_sha256"] = compute_composite_payload_sha256(arch_r08)
            direct_r08 = evaluate_composite_clinical_release(
                arch_r08,
                legacy_evaluator=leg_fn,
                gate0v_evaluator=g0v_fn,
                openislet_root=openislet_root,
            )
            brec_r08 = copy.deepcopy(auth_bank_rec)
            brec_r08["bank_payload_sha256"] = arch_r08["payload_sha256"]
            brec_r08["sha256"] = compute_qualification_record_sha256(brec_r08)
            g0v_surr_r08 = v38.build_passing_reference_payload(
                lot_id=clin_lot_id,
                mcb_id=mcb_id,
                product_variant_id=pv_lead,
                qualification_tier="LOT_RELEASE_SURROGATE",
                bridged_mcb_qualification_sha256=brec_r08["sha256"],
                openislet_root=openislet_root,
            )
            clin_r08_file = Path(td) / f"r08_b1_{case_name}_clin.json"
            clin_r08_file.write_text(
                json.dumps(_make_composite_bundle(clin_lot_id, mcb_id, pv_lead, leg_clin, g0v_surr_r08)),
                encoding="utf-8",
            )
            reg_r08 = Path(td) / f"r08_b1_{case_name}_reg.json"
            dir_r08 = Path(td) / f"r08_b1_{case_name}_dir"
            v38.write_record_to_trusted_qualification_store(
                reg_r08, brec_r08, category="bank_qualifications", archived_payload=arch_r08
            )
            v38.write_record_to_trusted_qualification_store(
                dir_r08, brec_r08, category="bank_qualifications", archived_payload=arch_r08
            )

            parity_ok = bool(
                direct_r08["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
                and expected_direct_hold in direct_r08["holds"]
            )
            last_holds_r08: List[str] = []
            for st_r08 in (reg_r08, dir_r08):
                r_arch, rc_arch = evaluate_composite_lot_file(
                    clin_r08_file,
                    legacy_evaluator=leg_fn,
                    gate0v_evaluator=g0v_fn,
                    trusted_qualification_store=st_r08,
                    openislet_root=openislet_root,
                )
                last_holds_r08 = r_arch["holds"]
                pqa_arch = r_arch["prior_qualification_authentication"]
                if not (
                    rc_arch == 2
                    and r_arch["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
                    and expected_direct_hold in r_arch["holds"]
                    and "HOLD_ARCHIVED_BANK_ENVELOPE_MISMATCH" in r_arch["holds"]
                    and "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD" in r_arch["holds"]
                    and pqa_arch.get("archived_bank_payload_verified") is False
                    and pqa_arch.get("archived_bank_payload_live_revalidation_passed") is False
                    and pqa_arch.get("archived_bank_payload_live_g0v_revalidation_passed") is False
                    and pqa_arch.get("archived_bank_payload_live_legacy_revalidation_passed") is False
                    and pqa_arch.get("archived_bank_payload_live_composite_revalidation_passed") is False
                ):
                    parity_ok = False

            cases.append({
                "case": case_name,
                "expected_verdict": "HOLD_COMPOSITE_RELEASE",
                "actual_verdict": "HOLD_COMPOSITE_RELEASE" if parity_ok else "PARITY_DRIFT_OR_UNEXPECTED_PASS",
                "operational_tier": "LOT_RELEASE_SURROGATE",
                "legacy_passed": True,
                "legacy_tier": LEGACY_PASS_TIER,
                "legacy_resolved_pvid": pv_lead,
                "gate0v_passed": False,
                "gate0v_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
                "expected_token": expected_direct_hold,
                "exit_code": 2 if parity_ok else -1,
                "direct_verdict": direct_r08["composite_verdict"],
                "archived_bank_payload_verified": False if parity_ok else None,
                "archived_bank_payload_live_revalidation_passed": False if parity_ok else None,
                "hard_stops": [],
                "holds": last_holds_r08[:5],
                "passed": parity_ok,
            })

        # 55. R08-B1a: Conflicting qualification_tier=BANK_QUALIFICATION + operational_tier=LOT_RELEASE_SURROGATE
        #     held identically in BOTH direct composite AND archived composite across BOTH store layouts!
        _run_r08_b1_parity_case(
            "r08_b1a_both_layouts_conflicting_archived_operational_tier_matches_direct_hold_exit_2",
            lambda doc: doc.update(
                qualification_tier="BANK_QUALIFICATION", operational_tier="LOT_RELEASE_SURROGATE"
            ),
            "HOLD_COMPOSITE_OPERATIONAL_TIER_MISMATCH",
        )

        # 56. R08-B1b: Missing top-level canonical product_variant_id (alias-only product_variant)
        #     held identically in BOTH direct composite AND archived composite across BOTH store layouts!
        _run_r08_b1_parity_case(
            "r08_b1b_both_layouts_alias_only_missing_top_product_variant_id_matches_direct_hold_exit_2",
            lambda doc: doc.__setitem__("product_variant", doc.pop("product_variant_id")),
            "HOLD_COMPOSITE_MISSING_TOP_PRODUCT_VARIANT_ID",
        )

        # 57. R08-B1c: Conflicting top-level qualification_tier=LOT_RELEASE_SURROGATE (with operational_tier
        #     omitted or BANK_QUALIFICATION) held identically in BOTH direct AND archived across BOTH layouts!
        _run_r08_b1_parity_case(
            "r08_b1c_both_layouts_conflicting_top_qualification_tier_matches_direct_hold_exit_2",
            lambda doc: doc.update(
                qualification_tier="LOT_RELEASE_SURROGATE", operational_tier="BANK_QUALIFICATION"
            ),
            "HOLD_COMPOSITE_OPERATIONAL_TIER_MISMATCH",
        )

        # 58. R08-B1d: Conflicting nested gate0v operational_tier=LOT_RELEASE_SURROGATE held identically
        #     in BOTH direct AND archived across BOTH store layouts!
        def _mut_nested_g0v_op_tier(doc: Dict[str, Any]) -> None:
            doc["gate0v_wholegraft_payload"]["operational_tier"] = "LOT_RELEASE_SURROGATE"
            doc["gate0v_wholegraft_payload"]["payload_sha256"] = v38.compute_canonical_lot_sha256(
                doc["gate0v_wholegraft_payload"]
            )

        _run_r08_b1_parity_case(
            "r08_b1d_both_layouts_conflicting_nested_gate0v_operational_tier_matches_direct_hold_exit_2",
            _mut_nested_g0v_op_tier,
            "HOLD_COMPOSITE_OPERATIONAL_TIER_MISMATCH",
        )

        # ------------------------------------------------------------------
        # Round-09 Final-Closure Regressions (R09-B1 Strict JSON & R09-M1 NW-08 CLI Coupling)
        # ------------------------------------------------------------------
        # 59. R09-B1a: Direct composite lot file rejects top-level, nested, and unicode-escaped
        #     duplicate JSON object keys with structured HOLD_COMPOSITE_RELEASE (exit 2)!
        raw_bank_str = json.dumps(bank_bundle, sort_keys=True)
        dup_top_f = Path(td) / "r09_b1a_top_dup.json"
        dup_top_f.write_text(
            '{"product_variant_id": "ISLET1_FAKE_VARIANT", ' + raw_bank_str[1:],
            encoding="utf-8",
        )
        dup_nested_f = Path(td) / "r09_b1a_nested_dup.json"
        dup_nested_f.write_text(
            raw_bank_str.replace(
                '"gate0v_wholegraft_payload": {',
                '"gate0v_wholegraft_payload": {"qualification_tier": "LOT_RELEASE_SURROGATE", ',
                1,
            ),
            encoding="utf-8",
        )
        dup_uni_f = Path(td) / "r09_b1a_unicode_dup.json"
        dup_uni_f.write_text(
            '{"lot_\\u0069d": "FAKE-LOT", ' + raw_bank_str[1:],
            encoding="utf-8",
        )
        r09_d1a_ok = True
        r09_d1a_holds: List[str] = []
        for f_dup in (dup_top_f, dup_nested_f, dup_uni_f):
            res_d, rc_d = evaluate_composite_lot_file(
                f_dup,
                legacy_evaluator=leg_fn,
                gate0v_evaluator=g0v_fn,
                openislet_root=openislet_root,
            )
            r09_d1a_holds = res_d["holds"]
            if not (
                rc_d == 2
                and res_d["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
                and "HOLD_COMPOSITE_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:DUPLICATE_JSON_KEY" in res_d["holds"]
            ):
                r09_d1a_ok = False
        cases.append({
            "case": "r09_b1a_direct_composite_lot_file_top_nested_unicode_duplicate_keys_hold_exit_2",
            "expected_verdict": "HOLD_COMPOSITE_RELEASE",
            "actual_verdict": "HOLD_COMPOSITE_RELEASE" if r09_d1a_ok else "UNEXPECTED_ACCEPT",
            "operational_tier": None,
            "legacy_passed": None,
            "legacy_tier": None,
            "legacy_resolved_pvid": None,
            "gate0v_passed": None,
            "gate0v_verdict": None,
            "expected_token": "HOLD_COMPOSITE_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:DUPLICATE_JSON_KEY",
            "exit_code": 2 if r09_d1a_ok else -1,
            "hard_stops": [],
            "holds": r09_d1a_holds[:3],
            "passed": r09_d1a_ok,
        })

        # 60. R09-B1b: Direct composite lot file rejects NaN, Infinity, -Infinity with structured HOLD exit 2!
        r09_d1b_ok = True
        r09_d1b_holds: List[str] = []
        for idx_nc, tok_nc in enumerate(("NaN", "Infinity", "-Infinity")):
            f_nc = Path(td) / f"r09_b1b_const_{idx_nc}.json"
            f_nc.write_text(f'{{"lot_id": "X", "bad_num": {tok_nc}}}', encoding="utf-8")
            res_nc, rc_nc = evaluate_composite_lot_file(
                f_nc,
                legacy_evaluator=leg_fn,
                gate0v_evaluator=g0v_fn,
                openislet_root=openislet_root,
            )
            r09_d1b_holds = res_nc["holds"]
            if not (
                rc_nc == 2
                and res_nc["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
                and "HOLD_COMPOSITE_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:NON_STANDARD_JSON_CONSTANT" in res_nc["holds"]
            ):
                r09_d1b_ok = False
        cases.append({
            "case": "r09_b1b_direct_composite_lot_file_nan_infinity_constants_hold_exit_2",
            "expected_verdict": "HOLD_COMPOSITE_RELEASE",
            "actual_verdict": "HOLD_COMPOSITE_RELEASE" if r09_d1b_ok else "UNEXPECTED_ACCEPT",
            "operational_tier": None,
            "legacy_passed": None,
            "legacy_tier": None,
            "legacy_resolved_pvid": None,
            "gate0v_passed": None,
            "gate0v_verdict": None,
            "expected_token": "HOLD_COMPOSITE_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:NON_STANDARD_JSON_CONSTANT",
            "exit_code": 2 if r09_d1b_ok else -1,
            "hard_stops": [],
            "holds": r09_d1b_holds[:3],
            "passed": r09_d1b_ok,
        })

        # 61. R09-B1c: External trusted store rejects duplicate keys AND NaN across registry JSON,
        #     directory bank record JSON, and directory archived bank payload JSON with HOLD exit 2!
        clin_clean_r09 = Path(td) / "r09_b1c_clean_clin.json"
        clin_clean_r09.write_text(json.dumps(clin_bundle, sort_keys=True), encoding="utf-8")

        reg_dup_c = Path(td) / "r09_b1c_reg_dup.json"
        v38.write_record_to_trusted_qualification_store(
            reg_dup_c, auth_bank_rec, category="bank_qualifications", archived_payload=bank_bundle
        )
        reg_dup_c.write_text(
            reg_dup_c.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_c = Path(td) / "r09_b1c_dir_rec_dup"
        v38.write_record_to_trusted_qualification_store(
            dir_rec_dup_c, auth_bank_rec, category="bank_qualifications", archived_payload=bank_bundle
        )
        rec_c_f = dir_rec_dup_c / "bank_qualifications" / f"{auth_bank_rec['sha256']}.json"
        rec_c_f.write_text('{"verdict": "HOLD_FAKE", ' + rec_c_f.read_text(encoding="utf-8").lstrip()[1:], encoding="utf-8")

        dir_arch_dup_c = Path(td) / "r09_b1c_dir_arch_dup"
        v38.write_record_to_trusted_qualification_store(
            dir_arch_dup_c, auth_bank_rec, category="bank_qualifications", archived_payload=bank_bundle
        )
        arch_c_f = dir_arch_dup_c / "archived_payloads" / f"{bank_bundle['payload_sha256']}.json"
        arch_c_f.write_text(
            '{"product_variant_id": "ISLET1_FAKE_VARIANT", ' + arch_c_f.read_text(encoding="utf-8").lstrip()[1:],
            encoding="utf-8",
        )

        dir_arch_nan_c = Path(td) / "r09_b1c_dir_arch_nan"
        v38.write_record_to_trusted_qualification_store(
            dir_arch_nan_c, auth_bank_rec, category="bank_qualifications", archived_payload=bank_bundle
        )
        arch_nan_c_f = dir_arch_nan_c / "archived_payloads" / f"{bank_bundle['payload_sha256']}.json"
        arch_nan_c_f.write_text(
            '{"nan_probe": NaN, ' + arch_nan_c_f.read_text(encoding="utf-8").lstrip()[1:],
            encoding="utf-8",
        )

        r09_d1c_ok = True
        r09_d1c_holds: List[str] = []
        for st_c in (reg_dup_c, dir_rec_dup_c, dir_arch_dup_c, dir_arch_nan_c):
            res_sc, rc_sc = evaluate_composite_lot_file(
                clin_clean_r09,
                legacy_evaluator=leg_fn,
                gate0v_evaluator=g0v_fn,
                trusted_qualification_store=st_c,
                openislet_root=openislet_root,
            )
            r09_d1c_holds = res_sc["holds"]
            pqa_sc = res_sc.get("prior_qualification_authentication") or {}
            if not (
                rc_sc == 2
                and res_sc["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
                and "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE" in res_sc["holds"]
                and "HOLD_MISSING_OR_INVALID_ARCHIVED_BANK_PAYLOAD" in res_sc["holds"]
                and pqa_sc.get("archived_bank_payload_verified") is False
                and pqa_sc.get("archived_bank_payload_live_revalidation_passed") is False
                and any("AMBIGUOUS_OR_NONCANONICAL_JSON" in h for h in res_sc["holds"])
            ):
                r09_d1c_ok = False
        cases.append({
            "case": "r09_b1c_external_store_registry_dir_record_and_dir_archive_dup_key_nan_hold_exit_2",
            "expected_verdict": "HOLD_COMPOSITE_RELEASE",
            "actual_verdict": "HOLD_COMPOSITE_RELEASE" if r09_d1c_ok else "UNEXPECTED_ACCEPT",
            "operational_tier": "LOT_RELEASE_SURROGATE",
            "legacy_passed": True,
            "legacy_tier": LEGACY_PASS_TIER,
            "legacy_resolved_pvid": pv_lead,
            "gate0v_passed": False,
            "gate0v_verdict": "HOLD_INCOMPLETE_OR_UNDERPOWERED",
            "expected_token": "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE",
            "exit_code": 2 if r09_d1c_ok else -1,
            "hard_stops": [],
            "holds": r09_d1c_holds[:4],
            "passed": r09_d1c_ok,
        })

        # 62. R09-M1 + R10-B1: Explicit composite CLI coupling (`--nw08-ocr-json`) gates composite release
        #     on lot-bound, geometry-reconciled live 3D FVM NW-08 measured-OCR dispatch
        #     (matched PASS -> exit 0, matched FAIL -> exit 3, dup-key -> exit 2)!
        r2_ev_sha = v38._valid_digest("r09_m1_r10_b1_raw_respirometry_r2")
        bank_r2_bundle = _make_composite_bundle(
            bank_lot_id,
            mcb_id,
            pv_lead,
            leg_bank,
            g0v_bank,
            nw08_route_id="R2_DZ40",
            nw08_measurement_evidence_sha256=r2_ev_sha,
        )
        clean_bank_f = Path(td) / "r09_m1_clean_bank.json"
        clean_bank_f.write_text(json.dumps(bank_r2_bundle, sort_keys=True), encoding="utf-8")
        ocr_pass_rec = v38.build_bound_nw08_ocr_record(
            lot_id=bank_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            route_id="R2_DZ40",
            lot_payload_sha256=bank_r2_bundle["payload_sha256"],
            measured_ocr=1.097,
            uncertainty_se=0.0,
            measurement_record_id="OCR-REC-BANK-PASS-001",
            measurement_evidence_sha256=r2_ev_sha,
            measurement_timestamp_utc="2026-11-29T00:00:00Z",
        )
        ocr_fail_rec = v38.build_bound_nw08_ocr_record(
            lot_id=bank_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            route_id="R2_DZ40",
            lot_payload_sha256=bank_r2_bundle["payload_sha256"],
            measured_ocr=10.0,
            uncertainty_se=0.0,
            baseline_vasc_ocr_mult=5.0,
            measurement_record_id="OCR-REC-BANK-FAIL-001",
            measurement_evidence_sha256=r2_ev_sha,
            measurement_timestamp_utc="2026-11-29T00:00:00Z",
        )
        ocr_pass_f = Path(td) / "r09_m1_ocr_pass.json"
        ocr_pass_f.write_text(json.dumps(ocr_pass_rec, sort_keys=True), encoding="utf-8")
        ocr_fail_f = Path(td) / "r09_m1_ocr_fail.json"
        ocr_fail_f.write_text(json.dumps(ocr_fail_rec, sort_keys=True), encoding="utf-8")
        ocr_dup_f = Path(td) / "r09_m1_ocr_dup.json"
        ocr_dup_f.write_text(
            '{"route_id": "R1_350_stress", "route_id": "R2_DZ40", "measured_ocr": 1.097, "uncertainty_se": 0.0}',
            encoding="utf-8",
        )
        res_op, rc_op = evaluate_composite_lot_file(
            clean_bank_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            openislet_root=openislet_root,
            nw08_ocr_json_path=ocr_pass_f,
        )
        res_of, rc_of = evaluate_composite_lot_file(
            clean_bank_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            openislet_root=openislet_root,
            nw08_ocr_json_path=ocr_fail_f,
        )
        res_od, rc_od = evaluate_composite_lot_file(
            clean_bank_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            openislet_root=openislet_root,
            nw08_ocr_json_path=ocr_dup_f,
        )
        r09_m1_ok = bool(
            rc_op == 0
            and res_op["composite_verdict"] == "PASS_COMPOSITE_BANK_QUALIFICATION"
            and (res_op.get("nw08_measured_ocr_dispatch_result") or {}).get("adjudicated_verdict") == "PASS"
            and (res_op.get("nw08_measured_ocr_dispatch_result") or {}).get("lot_binding_verified") is True
            and rc_of == 3
            and res_of["composite_verdict"] == "FAIL_HARD_STOP_COMPOSITE_RELEASE"
            and "FAIL_HARD_STOP_NW08_3D_FVM_BELOW_15MMHG_FLOOR" in res_of["hard_stops"]
            and res_of["authenticated_bank_qualification_record"] is None
            and rc_od == 2
            and res_od["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and "HOLD_NW08_AMBIGUOUS_OR_NONCANONICAL_OCR_JSON:DUPLICATE_JSON_KEY" in res_od["holds"]
            and res_od["authenticated_bank_qualification_record"] is None
        )
        cases.append({
            "case": "r09_m1_composite_coupled_nw08_ocr_json_pass_fail_and_strict_json_hold",
            "expected_verdict": "PASS_0_FAIL_3_HOLD_2",
            "actual_verdict": f"PASS_{rc_op}_FAIL_{rc_of}_HOLD_{rc_od}",
            "operational_tier": "BANK_QUALIFICATION",
            "legacy_passed": True,
            "legacy_tier": LEGACY_PASS_TIER,
            "legacy_resolved_pvid": pv_lead,
            "gate0v_passed": True,
            "gate0v_verdict": "PASS_WHOLEGRAFT_BANK_QUALIFICATION",
            "expected_token": "FAIL_HARD_STOP_NW08_3D_FVM_BELOW_15MMHG_FLOOR",
            "exit_code": 0 if r09_m1_ok else -1,
            "hard_stops": res_of["hard_stops"][:2],
            "holds": res_od["holds"][:2],
            "passed": r09_m1_ok,
        })

        # 63. R09-B1d: In-memory composite dict with float('nan') fails closed cleanly to HOLD (no traceback)!
        nan_mem_comp = copy.deepcopy(bank_bundle)
        nan_mem_comp["nonfinite_probe"] = float("nan")
        res_nm = evaluate_composite_clinical_release(
            nan_mem_comp,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            openislet_root=openislet_root,
        )
        ok_nm = bool(
            res_nm["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and "HOLD_COMPOSITE_NONCANONICAL_OR_NONFINITE_PAYLOAD" in res_nm["holds"]
        )
        cases.append({
            "case": "r09_b1d_in_memory_nonfinite_float_composite_payload_fails_closed_hold",
            "expected_verdict": "HOLD_COMPOSITE_RELEASE",
            "actual_verdict": res_nm["composite_verdict"],
            "operational_tier": res_nm["operational_tier"],
            "legacy_passed": (res_nm.get("legacy_result_summary") or {}).get("legacy_evaluator_passed"),
            "legacy_tier": (res_nm.get("legacy_result_summary") or {}).get("lot_release_readiness_tier"),
            "legacy_resolved_pvid": (res_nm.get("legacy_result_summary") or {}).get("resolved_product_variant_id"),
            "gate0v_passed": (res_nm.get("gate0v_result_summary") or {}).get("gate0v_evaluator_passed"),
            "gate0v_verdict": (res_nm.get("gate0v_result_summary") or {}).get("verdict"),
            "expected_token": "HOLD_COMPOSITE_NONCANONICAL_OR_NONFINITE_PAYLOAD",
            "exit_code": 2 if ok_nm else -1,
            "hard_stops": res_nm["hard_stops"][:2],
            "holds": res_nm["holds"][:3],
            "passed": ok_nm,
        })

        # ------------------------------------------------------------------
        # Round-10 Final-Closure Regressions (R10-B1 Coupled NW-08 Binding & R10-B2 Structured Type/Range Holds)
        # ------------------------------------------------------------------
        clin_ev_sha = v38._valid_digest("r10_b1_clinical_respirometry_raw_v1")
        clin_r2_bundle = _make_composite_bundle(
            clin_lot_id,
            mcb_id,
            pv_lead,
            leg_clin,
            g0v_clin,
            nw08_route_id="R2_DZ40",
            nw08_measurement_evidence_sha256=clin_ev_sha,
            nw08_measurement_not_before_utc="2026-11-28T00:00:00Z",
        )
        clin_r1_bundle = _make_composite_bundle(
            clin_lot_id,
            mcb_id,
            pv_lead,
            leg_clin,
            g0v_clin,
            nw08_route_id="R1_350_stress",
            nw08_measurement_evidence_sha256=clin_ev_sha,
            nw08_measurement_not_before_utc="2026-11-28T00:00:00Z",
        )
        clin_r2_f = Path(td) / "r10_b1_clin_r2.json"
        clin_r2_f.write_text(json.dumps(clin_r2_bundle, sort_keys=True), encoding="utf-8")
        clin_r1_f = Path(td) / "r10_b1_clin_r1.json"
        clin_r1_f.write_text(json.dumps(clin_r1_bundle, sort_keys=True), encoding="utf-8")
        clin_noroute_f = Path(td) / "r10_b1_clin_noroute.json"
        clin_noroute_f.write_text(json.dumps(clin_bundle, sort_keys=True), encoding="utf-8")

        # 64. R10-B1a: Clinical LOT_RELEASE_SURROGATE lot declaring R2_DZ40 + matched passing bound OCR -> PASS (exit 0)!
        clin_ocr_r2_pass = v38.build_bound_nw08_ocr_record(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            route_id="R2_DZ40",
            lot_payload_sha256=clin_r2_bundle["payload_sha256"],
            measured_ocr=1.3164,
            uncertainty_se=0.0,
            measurement_record_id="OCR-CLIN-R2-PASS-001",
            measurement_evidence_sha256=clin_ev_sha,
            measurement_timestamp_utc="2026-11-29T01:00:00Z",
        )
        clin_ocr_r2_f = Path(td) / "r10_b1_ocr_clin_r2_pass.json"
        clin_ocr_r2_f.write_text(json.dumps(clin_ocr_r2_pass, sort_keys=True), encoding="utf-8")
        res_64, rc_64 = evaluate_composite_lot_file(
            clin_r2_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
            nw08_ocr_json_path=clin_ocr_r2_f,
        )
        ok_64 = bool(
            rc_64 == 0
            and res_64["composite_verdict"] == "PASS_COMPOSITE_CLINICAL_RELEASE"
            and (res_64.get("nw08_measured_ocr_dispatch_result") or {}).get("lot_binding_verified") is True
            and (res_64.get("nw08_measured_ocr_dispatch_result") or {}).get("solver_executed") is True
            and (res_64.get("nw08_measured_ocr_dispatch_result") or {}).get("route_id") == "R2_DZ40"
        )
        cases.append({
            "case": "r10_b1a_coupled_clinical_lot_matched_passing_bound_ocr_passes_exit_0",
            "expected_verdict": "PASS_COMPOSITE_CLINICAL_RELEASE",
            "actual_verdict": res_64["composite_verdict"],
            "operational_tier": res_64["operational_tier"],
            "legacy_passed": (res_64.get("legacy_result_summary") or {}).get("legacy_evaluator_passed"),
            "legacy_tier": (res_64.get("legacy_result_summary") or {}).get("lot_release_readiness_tier"),
            "legacy_resolved_pvid": (res_64.get("legacy_result_summary") or {}).get("resolved_product_variant_id"),
            "gate0v_passed": (res_64.get("gate0v_result_summary") or {}).get("gate0v_evaluator_passed"),
            "gate0v_verdict": (res_64.get("gate0v_result_summary") or {}).get("verdict"),
            "expected_token": None,
            "exit_code": rc_64,
            "hard_stops": res_64["hard_stops"][:2],
            "holds": res_64["holds"][:2],
            "passed": ok_64,
        })

        # 65. R10-B1b: Exact Round-09 route-swap exploit — clinical lot declares R1_350_stress, sidecar
        #     claims R2_DZ40 (even with matching lot/MCB/product/lot_payload_sha256/self-digest) -> HOLD exit 2!
        clin_ocr_swap = v38.build_bound_nw08_ocr_record(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            route_id="R2_DZ40",
            lot_payload_sha256=clin_r1_bundle["payload_sha256"],
            measured_ocr=1.3164,
            uncertainty_se=0.0,
            measurement_record_id="OCR-CLIN-SWAP-R2",
            measurement_evidence_sha256=clin_ev_sha,
            measurement_timestamp_utc="2026-11-29T01:00:00Z",
        )
        clin_ocr_swap_f = Path(td) / "r10_b1_ocr_swap.json"
        clin_ocr_swap_f.write_text(json.dumps(clin_ocr_swap, sort_keys=True), encoding="utf-8")
        res_65, rc_65 = evaluate_composite_lot_file(
            clin_r1_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
            nw08_ocr_json_path=clin_ocr_swap_f,
        )
        ok_65 = bool(
            rc_65 == 2
            and res_65["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and "HOLD_NW08_COUPLED_ROUTE_ID_MISMATCH" in res_65["holds"]
            and (res_65.get("nw08_measured_ocr_dispatch_result") or {}).get("lot_binding_verified") is False
            and (res_65.get("nw08_measured_ocr_dispatch_result") or {}).get("solver_executed") is False
        )
        cases.append({
            "case": "r10_b1b_coupled_clinical_lot_route_swap_r1_350_to_r2_dz40_held_exit_2",
            "expected_verdict": "HOLD_COMPOSITE_RELEASE",
            "actual_verdict": res_65["composite_verdict"],
            "operational_tier": res_65["operational_tier"],
            "legacy_passed": (res_65.get("legacy_result_summary") or {}).get("legacy_evaluator_passed"),
            "legacy_tier": (res_65.get("legacy_result_summary") or {}).get("lot_release_readiness_tier"),
            "legacy_resolved_pvid": (res_65.get("legacy_result_summary") or {}).get("resolved_product_variant_id"),
            "gate0v_passed": (res_65.get("gate0v_result_summary") or {}).get("gate0v_evaluator_passed"),
            "gate0v_verdict": (res_65.get("gate0v_result_summary") or {}).get("verdict"),
            "expected_token": "HOLD_NW08_COUPLED_ROUTE_ID_MISMATCH",
            "exit_code": rc_65,
            "hard_stops": res_65["hard_stops"][:2],
            "holds": res_65["holds"][:3],
            "passed": ok_65,
        })

        # 66. R10-B1c: Matched failing R1_350_stress bound OCR record (1.3164 -> 14.8446 mmHg < 15.0) -> FAIL exit 3!
        clin_ocr_r1_fail = v38.build_bound_nw08_ocr_record(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            route_id="R1_350_stress",
            lot_payload_sha256=clin_r1_bundle["payload_sha256"],
            measured_ocr=1.3164,
            uncertainty_se=0.0,
            measurement_record_id="OCR-CLIN-R1-FAIL-001",
            measurement_evidence_sha256=clin_ev_sha,
            measurement_timestamp_utc="2026-11-29T01:00:00Z",
        )
        clin_ocr_r1_fail_f = Path(td) / "r10_b1_ocr_clin_r1_fail.json"
        clin_ocr_r1_fail_f.write_text(json.dumps(clin_ocr_r1_fail, sort_keys=True), encoding="utf-8")
        res_66, rc_66 = evaluate_composite_lot_file(
            clin_r1_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
            nw08_ocr_json_path=clin_ocr_r1_fail_f,
        )
        ok_66 = bool(
            rc_66 == 3
            and res_66["composite_verdict"] == "FAIL_HARD_STOP_COMPOSITE_RELEASE"
            and "FAIL_HARD_STOP_NW08_3D_FVM_BELOW_15MMHG_FLOOR" in res_66["hard_stops"]
            and (res_66.get("nw08_measured_ocr_dispatch_result") or {}).get("lot_binding_verified") is True
            and (res_66.get("nw08_measured_ocr_dispatch_result") or {}).get("solver_executed") is True
            and (res_66.get("nw08_measured_ocr_dispatch_result") or {}).get("face_min_mmhg_unrounded", 99.0) < 15.0
        )
        cases.append({
            "case": "r10_b1c_coupled_clinical_lot_matched_failing_r1_350_ocr_hard_stop_exit_3",
            "expected_verdict": "FAIL_HARD_STOP_COMPOSITE_RELEASE",
            "actual_verdict": res_66["composite_verdict"],
            "operational_tier": res_66["operational_tier"],
            "legacy_passed": (res_66.get("legacy_result_summary") or {}).get("legacy_evaluator_passed"),
            "legacy_tier": (res_66.get("legacy_result_summary") or {}).get("lot_release_readiness_tier"),
            "legacy_resolved_pvid": (res_66.get("legacy_result_summary") or {}).get("resolved_product_variant_id"),
            "gate0v_passed": (res_66.get("gate0v_result_summary") or {}).get("gate0v_evaluator_passed"),
            "gate0v_verdict": (res_66.get("gate0v_result_summary") or {}).get("verdict"),
            "expected_token": "FAIL_HARD_STOP_NW08_3D_FVM_BELOW_15MMHG_FLOOR",
            "exit_code": rc_66,
            "hard_stops": res_66["hard_stops"][:2],
            "holds": res_66["holds"][:2],
            "passed": ok_66,
        })

        # 67. R10-B1d: Stale lot_payload_sha256, mismatched lot/MCB/product, tampered ocr_record_sha256,
        #     mismatched evidence digest, stale timestamp, unbound 3-field legacy JSON, and lot missing
        #     nw08_route_id -> ALL HOLD_COMPOSITE_RELEASE (exit 2)!
        bad_coupled_matrix: List[Tuple[str, Path, Dict[str, Any], str]] = [
            (
                "stale_lot_hash",
                clin_r2_f,
                v38.build_bound_nw08_ocr_record(
                    lot_id=clin_lot_id, mcb_id=mcb_id, product_variant_id=pv_lead, route_id="R2_DZ40",
                    lot_payload_sha256=v38._valid_digest("older_lot_hash"), measured_ocr=1.097, uncertainty_se=0.0,
                    measurement_record_id="OCR-STALE-1", measurement_evidence_sha256=clin_ev_sha,
                    measurement_timestamp_utc="2026-11-29T01:00:00Z",
                ),
                "HOLD_NW08_COUPLED_STALE_OR_MISMATCHED_LOT_PAYLOAD_SHA256",
            ),
            (
                "wrong_lot_id",
                clin_r2_f,
                v38.build_bound_nw08_ocr_record(
                    lot_id="LOT-OTHER-999", mcb_id=mcb_id, product_variant_id=pv_lead, route_id="R2_DZ40",
                    lot_payload_sha256=clin_r2_bundle["payload_sha256"], measured_ocr=1.097, uncertainty_se=0.0,
                    measurement_record_id="OCR-BADLOT-1", measurement_evidence_sha256=clin_ev_sha,
                    measurement_timestamp_utc="2026-11-29T01:00:00Z",
                ),
                "HOLD_NW08_COUPLED_LOT_ID_MISMATCH",
            ),
            (
                "wrong_mcb_id",
                clin_r2_f,
                v38.build_bound_nw08_ocr_record(
                    lot_id=clin_lot_id, mcb_id="MCB-WRONG-999", product_variant_id=pv_lead, route_id="R2_DZ40",
                    lot_payload_sha256=clin_r2_bundle["payload_sha256"], measured_ocr=1.097, uncertainty_se=0.0,
                    measurement_record_id="OCR-BADMCB-1", measurement_evidence_sha256=clin_ev_sha,
                    measurement_timestamp_utc="2026-11-29T01:00:00Z",
                ),
                "HOLD_NW08_COUPLED_MCB_ID_MISMATCH",
            ),
            (
                "wrong_pvid",
                clin_r2_f,
                v38.build_bound_nw08_ocr_record(
                    lot_id=clin_lot_id, mcb_id=mcb_id, product_variant_id="ISLET1_A4_ARM1A", route_id="R2_DZ40",
                    lot_payload_sha256=clin_r2_bundle["payload_sha256"], measured_ocr=1.097, uncertainty_se=0.0,
                    measurement_record_id="OCR-BADPV-1", measurement_evidence_sha256=clin_ev_sha,
                    measurement_timestamp_utc="2026-11-29T01:00:00Z",
                ),
                "HOLD_NW08_COUPLED_PRODUCT_VARIANT_ID_MISMATCH",
            ),
            (
                "tampered_self_digest",
                clin_r2_f,
                {**clin_ocr_r2_pass, "measured_ocr": 1.097},
                "HOLD_NW08_OCR_RECORD_SHA256_MISMATCH",
            ),
            (
                "mismatched_evidence_sha",
                clin_r2_f,
                v38.build_bound_nw08_ocr_record(
                    lot_id=clin_lot_id, mcb_id=mcb_id, product_variant_id=pv_lead, route_id="R2_DZ40",
                    lot_payload_sha256=clin_r2_bundle["payload_sha256"], measured_ocr=1.097, uncertainty_se=0.0,
                    measurement_record_id="OCR-BADEV-1", measurement_evidence_sha256=v38._valid_digest("other_ev"),
                    measurement_timestamp_utc="2026-11-29T01:00:00Z",
                ),
                "HOLD_NW08_COUPLED_MEASUREMENT_EVIDENCE_SHA256_MISMATCH",
            ),
            (
                "stale_timestamp",
                clin_r2_f,
                v38.build_bound_nw08_ocr_record(
                    lot_id=clin_lot_id, mcb_id=mcb_id, product_variant_id=pv_lead, route_id="R2_DZ40",
                    lot_payload_sha256=clin_r2_bundle["payload_sha256"], measured_ocr=1.097, uncertainty_se=0.0,
                    measurement_record_id="OCR-OLDTS-1", measurement_evidence_sha256=clin_ev_sha,
                    measurement_timestamp_utc="2026-11-27T23:59:59Z",
                ),
                "HOLD_NW08_COUPLED_STALE_MEASUREMENT_TIMESTAMP_UTC",
            ),
            (
                "unbound_legacy_3field",
                clin_r2_f,
                {"route_id": "R2_DZ40", "measured_ocr": 1.097, "uncertainty_se": 0.0},
                "HOLD_NW08_COUPLED_MISSING_REQUIRED_BINDING_KEY:lot_id",
            ),
            (
                "lot_missing_planned_route",
                clin_noroute_f,
                v38.build_bound_nw08_ocr_record(
                    lot_id=clin_lot_id, mcb_id=mcb_id, product_variant_id=pv_lead, route_id="R2_DZ40",
                    lot_payload_sha256=clin_bundle["payload_sha256"], measured_ocr=1.097, uncertainty_se=0.0,
                    measurement_record_id="OCR-NOROUTE-1", measurement_evidence_sha256=clin_ev_sha,
                    measurement_timestamp_utc="2026-11-29T01:00:00Z",
                ),
                "HOLD_NW08_COUPLED_LOT_MISSING_PLANNED_ROUTE",
            ),
        ]
        ok_67 = True
        last_67_holds: List[str] = []
        for tag_67, lot_f_67, ocr_obj_67, exp_tok_67 in bad_coupled_matrix:
            of_67 = Path(td) / f"r10_b1d_{tag_67}.json"
            of_67.write_text(json.dumps(ocr_obj_67, sort_keys=True), encoding="utf-8")
            r_67, rc_67 = evaluate_composite_lot_file(
                lot_f_67,
                legacy_evaluator=leg_fn,
                gate0v_evaluator=g0v_fn,
                trusted_qualification_store=trusted_store,
                openislet_root=openislet_root,
                nw08_ocr_json_path=of_67,
            )
            last_67_holds = r_67["holds"]
            if not (
                rc_67 == 2
                and r_67["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
                and exp_tok_67 in r_67["holds"]
                and (r_67.get("nw08_measured_ocr_dispatch_result") or {}).get("solver_executed") is False
            ):
                ok_67 = False
        cases.append({
            "case": "r10_b1d_coupled_stale_hash_mismatched_ids_tampered_digest_unbound_and_missing_route_held_exit_2",
            "expected_verdict": "HOLD_COMPOSITE_RELEASE",
            "actual_verdict": "HOLD_COMPOSITE_RELEASE" if ok_67 else "UNEXPECTED_PASS_OR_TOKEN",
            "operational_tier": "LOT_RELEASE_SURROGATE",
            "legacy_passed": True,
            "legacy_tier": LEGACY_PASS_TIER,
            "legacy_resolved_pvid": pv_lead,
            "gate0v_passed": True,
            "gate0v_verdict": "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE",
            "expected_token": "HOLD_NW08_COUPLED_LOT_MISSING_PLANNED_ROUTE",
            "exit_code": 2 if ok_67 else -1,
            "hard_stops": [],
            "holds": last_67_holds[:3],
            "passed": ok_67,
        })

        # 68. R10-B1e: External `--trusted-qualification-store` `nw08_ocr_records` verification across BOTH
        #     registry JSON and directory store layouts (registered -> exit 0; unregistered/tampered -> exit 2)!
        clin_r2_req_store = _make_composite_bundle(
            clin_lot_id,
            mcb_id,
            pv_lead,
            leg_clin,
            g0v_clin,
            nw08_route_id="R2_DZ40",
            nw08_measurement_evidence_sha256=clin_ev_sha,
            require_trusted_nw08_ocr_record=True,
        )
        clin_r2_req_f = Path(td) / "r10_b1e_clin_req_store.json"
        clin_r2_req_f.write_text(json.dumps(clin_r2_req_store, sort_keys=True), encoding="utf-8")
        ocr_r2_req_rec = v38.build_bound_nw08_ocr_record(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            route_id="R2_DZ40",
            lot_payload_sha256=clin_r2_req_store["payload_sha256"],
            measured_ocr=1.097,
            uncertainty_se=0.0,
            measurement_record_id="OCR-CLIN-STORE-001",
            measurement_evidence_sha256=clin_ev_sha,
            measurement_timestamp_utc="2026-11-29T02:00:00Z",
        )
        ocr_r2_req_f = Path(td) / "r10_b1e_ocr_req.json"
        ocr_r2_req_f.write_text(json.dumps(ocr_r2_req_rec, sort_keys=True), encoding="utf-8")
        reg_with_ocr = Path(td) / "r10_b1e_reg_ocr.json"
        dir_with_ocr = Path(td) / "r10_b1e_dir_ocr"
        for st_ocr in (reg_with_ocr, dir_with_ocr):
            v38.write_record_to_trusted_qualification_store(
                st_ocr, auth_bank_rec, category="bank_qualifications", archived_payload=bank_bundle
            )
            v38.write_record_to_trusted_qualification_store(st_ocr, ocr_r2_req_rec, category="nw08_ocr_records")
        ok_68 = True
        for st_ocr in (reg_with_ocr, dir_with_ocr):
            rp_68, rcp_68 = evaluate_composite_lot_file(
                clin_r2_req_f,
                legacy_evaluator=leg_fn,
                gate0v_evaluator=g0v_fn,
                trusted_qualification_store=st_ocr,
                openislet_root=openislet_root,
                nw08_ocr_json_path=ocr_r2_req_f,
            )
            if not (
                rcp_68 == 0
                and rp_68["composite_verdict"] == "PASS_COMPOSITE_CLINICAL_RELEASE"
                and (((rp_68.get("nw08_measured_ocr_dispatch_result") or {}).get("nw08_lot_binding") or {}).get("external_ocr_store_verification") or {}).get("verified") is True
            ):
                ok_68 = False
        # Unregistered OCR record against store missing nw08_ocr_records when require_trusted_nw08_ocr_record=True -> HOLD exit 2!
        rm_68, rcm_68 = evaluate_composite_lot_file(
            clin_r2_req_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
            nw08_ocr_json_path=ocr_r2_req_f,
        )
        if not (
            rcm_68 == 2
            and rm_68["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and "HOLD_NW08_COUPLED_UNVERIFIED_EXTERNAL_OCR_STORE_RECORD" in rm_68["holds"]
        ):
            ok_68 = False
        cases.append({
            "case": "r10_b1e_coupled_external_trusted_store_nw08_ocr_records_both_layouts_pass_and_unregistered_hold",
            "expected_verdict": "PASS_0_AND_UNREGISTERED_HOLD_2",
            "actual_verdict": "PASS_0_AND_UNREGISTERED_HOLD_2" if ok_68 else "STORE_VERIFICATION_FAILED",
            "operational_tier": "LOT_RELEASE_SURROGATE",
            "legacy_passed": True,
            "legacy_tier": LEGACY_PASS_TIER,
            "legacy_resolved_pvid": pv_lead,
            "gate0v_passed": True,
            "gate0v_verdict": "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE",
            "expected_token": "HOLD_NW08_COUPLED_UNVERIFIED_EXTERNAL_OCR_STORE_RECORD",
            "exit_code": 0 if ok_68 else -1,
            "hard_stops": [],
            "holds": rm_68["holds"][:3],
            "passed": ok_68,
        })

        # 69. R10-B2: Composite CLI boundary rejects schema-invalid unhashable list qualification_tier AND
        #     out-of-float64-range finite integers (10**400) / overflowing floats (1e500) on --nw08-ocr-json
        #     with structured JSON HOLD_COMPOSITE_RELEASE (exit 2), ZERO uncaught tracebacks!
        list_tier_lot_f = Path(td) / "r10_b2_list_tier_lot.json"
        list_tier_lot_f.write_text(
            json.dumps({"lot_id": "L1", "mcb_id": "M1", "product_variant_id": pv_lead, "qualification_tier": ["BANK_QUALIFICATION"]}),
            encoding="utf-8",
        )
        r_lt_69, rc_lt_69 = evaluate_composite_lot_file(
            list_tier_lot_f, legacy_evaluator=leg_fn, gate0v_evaluator=g0v_fn, openislet_root=openislet_root
        )
        ok_69 = bool(rc_lt_69 == 2 and r_lt_69["composite_verdict"] == "HOLD_COMPOSITE_RELEASE")
        last_69_holds = r_lt_69["holds"]
        for tag_69, raw_69 in (
            ("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}}}'),
            ("flt_1e500", '{"route_id": "R2_DZ40", "measured_ocr": 1e500, "uncertainty_se": 0}'),
        ):
            hf_69 = Path(td) / f"r10_b2_ocr_{tag_69}.json"
            hf_69.write_text(raw_69, encoding="utf-8")
            rh_69, rch_69 = evaluate_composite_lot_file(
                clin_r2_f,
                legacy_evaluator=leg_fn,
                gate0v_evaluator=g0v_fn,
                trusted_qualification_store=trusted_store,
                openislet_root=openislet_root,
                nw08_ocr_json_path=hf_69,
            )
            last_69_holds = rh_69["holds"]
            if not (rch_69 == 2 and rh_69["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"):
                ok_69 = False
        cases.append({
            "case": "r10_b2_composite_cli_boundary_unhashable_list_tier_and_10pow400_ocr_structured_hold_exit_2",
            "expected_verdict": "HOLD_COMPOSITE_RELEASE",
            "actual_verdict": "HOLD_COMPOSITE_RELEASE" if ok_69 else "UNHANDLED_ERROR_OR_WRONG_RC",
            "operational_tier": "LOT_RELEASE_SURROGATE",
            "legacy_passed": True,
            "legacy_tier": LEGACY_PASS_TIER,
            "legacy_resolved_pvid": pv_lead,
            "gate0v_passed": True,
            "gate0v_verdict": "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE",
            "expected_token": "HOLD_NW08_AMBIGUOUS_OR_NONCANONICAL_OCR_JSON",
            "exit_code": 2 if ok_69 else -1,
            "hard_stops": [],
            "holds": last_69_holds[:3],
            "passed": ok_69,
        })

        # ------------------------------------------------------------------
        # Round-11 Final-Closure Regressions (R11-B1, R11-B3, R11-B4)
        # ------------------------------------------------------------------
        # 70. R11-B1: Complete 4-state release acceptance matrix for `require_trusted_nw08_ocr_record = True`
        #     across BOTH Python API (`evaluate_composite_clinical_release`) AND CLI file entry point
        #     (`evaluate_composite_lot_file`), plus independent biological FAIL preservation & strict bool check!
        clin_r1_req_store = _make_composite_bundle(
            clin_lot_id,
            mcb_id,
            pv_lead,
            leg_clin,
            g0v_clin,
            nw08_route_id="R1_350_stress",
            nw08_measurement_evidence_sha256=clin_ev_sha,
            require_trusted_nw08_ocr_record=True,
        )
        clin_r1_req_f = Path(td) / "r11_b1_clin_r1_req.json"
        clin_r1_req_f.write_text(json.dumps(clin_r1_req_store, sort_keys=True), encoding="utf-8")
        ocr_r1_req_fail = v38.build_bound_nw08_ocr_record(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            route_id="R1_350_stress",
            lot_payload_sha256=clin_r1_req_store["payload_sha256"],
            measured_ocr=1.3164,
            uncertainty_se=0.0,
            measurement_record_id="OCR-CLIN-R1-REQ-FAIL",
            measurement_evidence_sha256=clin_ev_sha,
            measurement_timestamp_utc="2026-11-29T02:00:00Z",
        )
        ocr_r1_req_fail_f = Path(td) / "r11_b1_ocr_r1_req_fail.json"
        ocr_r1_req_fail_f.write_text(json.dumps(ocr_r1_req_fail, sort_keys=True), encoding="utf-8")
        reg_with_both_ocr = Path(td) / "r11_b1_reg_both_ocr.json"
        v38.write_record_to_trusted_qualification_store(
            reg_with_both_ocr, auth_bank_rec, category="bank_qualifications", archived_payload=bank_bundle
        )
        v38.write_record_to_trusted_qualification_store(reg_with_both_ocr, ocr_r2_req_rec, category="nw08_ocr_records")
        v38.write_record_to_trusted_qualification_store(reg_with_both_ocr, ocr_r1_req_fail, category="nw08_ocr_records")

        # State 1: Required OCR omitted -> HOLD_NW08_REQUIRED_OCR_RECORD_MISSING (exit 2, release_authorizing=False)
        api_s1 = evaluate_composite_clinical_release(
            clin_r2_req_store,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=reg_with_both_ocr,
            openislet_root=openislet_root,
        )
        cli_s1, rc_s1 = evaluate_composite_lot_file(
            clin_r2_req_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=reg_with_both_ocr,
            openislet_root=openislet_root,
            nw08_ocr_json_path=None,
        )
        # State 2: Matched OCR sidecar present with missing/unverified QA store entry -> HOLD (exit 2, release_authorizing=False)
        api_s2 = evaluate_composite_clinical_release(
            clin_r2_req_store,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
            nw08_ocr_record=ocr_r2_req_rec,
        )
        cli_s2, rc_s2 = evaluate_composite_lot_file(
            clin_r2_req_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
            nw08_ocr_json_path=ocr_r2_req_f,
        )
        # State 3: Verified bound OCR solving below 15.0 mmHg floor -> FAIL (exit 3, release_authorizing=False)
        api_s3 = evaluate_composite_clinical_release(
            clin_r1_req_store,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=reg_with_both_ocr,
            openislet_root=openislet_root,
            nw08_ocr_record=ocr_r1_req_fail,
        )
        cli_s3, rc_s3 = evaluate_composite_lot_file(
            clin_r1_req_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=reg_with_both_ocr,
            openislet_root=openislet_root,
            nw08_ocr_json_path=ocr_r1_req_fail_f,
        )
        # State 4: Verified bound OCR clearing 15.0 mmHg floor -> PASS (exit 0, release_authorizing=True)
        api_s4 = evaluate_composite_clinical_release(
            clin_r2_req_store,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=reg_with_both_ocr,
            openislet_root=openislet_root,
            nw08_ocr_record=ocr_r2_req_rec,
        )
        cli_s4, rc_s4 = evaluate_composite_lot_file(
            clin_r2_req_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=reg_with_both_ocr,
            openislet_root=openislet_root,
            nw08_ocr_json_path=ocr_r2_req_f,
        )
        # Biological FAIL + missing required OCR -> preserves FAIL_HARD_STOP_COMPOSITE_RELEASE (exit 3, release_authorizing=False)
        g0v_bio_fail = copy.deepcopy(g0v_clin)
        g0v_bio_fail["cxadr_ko_present"] = True
        g0v_bio_fail["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_bio_fail)
        clin_bio_fail_req = _make_composite_bundle(
            clin_lot_id,
            mcb_id,
            pv_lead,
            leg_clin,
            g0v_bio_fail,
            nw08_route_id="R2_DZ40",
            require_trusted_nw08_ocr_record=True,
        )
        clin_bf_f = Path(td) / "r11_b1_bio_fail_req.json"
        clin_bf_f.write_text(json.dumps(clin_bio_fail_req, sort_keys=True), encoding="utf-8")
        cli_bf, rc_bf = evaluate_composite_lot_file(
            clin_bf_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=reg_with_both_ocr,
            openislet_root=openislet_root,
            nw08_ocr_json_path=None,
        )
        # Non-bool require_trusted_nw08_ocr_record ("true", 1, None) -> HOLD exit 2, release_authorizing=False!
        nonbool_ok = True
        for bad_rt in ("true", 1, None):
            bad_doc = copy.deepcopy(clin_r2_bundle)
            bad_doc["require_trusted_nw08_ocr_record"] = bad_rt
            bad_doc["payload_sha256"] = compute_composite_payload_sha256(bad_doc)
            r_nb = evaluate_composite_clinical_release(
                bad_doc,
                legacy_evaluator=leg_fn,
                gate0v_evaluator=g0v_fn,
                trusted_qualification_store=reg_with_both_ocr,
                openislet_root=openislet_root,
            )
            if not (
                r_nb["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
                and r_nb["release_authorizing"] is False
                and "HOLD_NW08_COUPLED_INVALID_REQUIRE_TRUSTED_OCR_FLAG" in r_nb["holds"]
            ):
                nonbool_ok = False

        ok_70 = bool(
            api_s1["composite_verdict"] == "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING"
            and api_s1["release_authorizing"] is False
            and "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING" in api_s1["holds"]
            and rc_s1 == 2
            and cli_s1["composite_verdict"] == "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING"
            and cli_s1["release_authorizing"] is False
            and api_s2["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and api_s2["release_authorizing"] is False
            and rc_s2 == 2
            and cli_s2["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and cli_s2["release_authorizing"] is False
            and api_s3["composite_verdict"] == "FAIL_HARD_STOP_COMPOSITE_RELEASE"
            and api_s3["release_authorizing"] is False
            and rc_s3 == 3
            and cli_s3["composite_verdict"] == "FAIL_HARD_STOP_COMPOSITE_RELEASE"
            and cli_s3["release_authorizing"] is False
            and api_s4["composite_verdict"] == "PASS_COMPOSITE_CLINICAL_RELEASE"
            and api_s4["release_authorizing"] is True
            and rc_s4 == 0
            and cli_s4["composite_verdict"] == "PASS_COMPOSITE_CLINICAL_RELEASE"
            and cli_s4["release_authorizing"] is True
            and rc_bf == 3
            and cli_bf["composite_verdict"] == "FAIL_HARD_STOP_COMPOSITE_RELEASE"
            and cli_bf["release_authorizing"] is False
            and "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING" in cli_bf["holds"]
            and nonbool_ok
        )
        cases.append({
            "case": "r11_b1_required_nw08_ocr_4state_matrix_api_and_cli_fail_preserved_strict_bool",
            "expected_verdict": "HOLD2_HOLD2_FAIL3_PASS0_BIOFAIL3",
            "actual_verdict": f"S1_{rc_s1}_S2_{rc_s2}_S3_{rc_s3}_S4_{rc_s4}_BF_{rc_bf}",
            "operational_tier": "LOT_RELEASE_SURROGATE",
            "legacy_passed": True,
            "legacy_tier": LEGACY_PASS_TIER,
            "legacy_resolved_pvid": pv_lead,
            "gate0v_passed": True,
            "gate0v_verdict": "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE",
            "expected_token": "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING",
            "exit_code": 0 if ok_70 else -1,
            "hard_stops": cli_s3["hard_stops"][:2],
            "holds": cli_s1["holds"][:3],
            "passed": ok_70,
        })

        # 71. R11-B3: Clustered composite lot (`deff = 2.0161290322580645`, even with 3x scaled counts)
        #     routes to `HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE` (exit 2, release_authorizing=False),
        #     and `PASS_COMPOSITE_BANK_QUALIFICATION` sets `release_authorizing=False, bank_qualification_authorized=True`!
        g0v_sol_clin = copy.deepcopy(g0v_clin)
        g0v_sol_clin["clustering_and_independence_spec"]["clustering_design_effect_deff"] = "2.0161290322580645"
        for _pb in g0v_sol_clin["gate0v_b_infectious_challenge"]["pathogens"].values():
            _pb["total_viable_cells_acquired_n"] *= 3
            _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 _te in _pb["day28_latent_and_defective_genome_arm"]["ddpcr_targets"].values():
                _te["n"] *= 3
            for _le in _pb["day28_persistence_by_lineage"].values():
                _le["cells_assigned_n"] *= 3
                _le["cells_scored_n"] *= 3
        for _rb in g0v_sol_clin["gate0v_kill_stress_ap1903"].values():
            for _lb in _rb.values():
                _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
        v38.reconcile_fixture_per_unit_counts(g0v_sol_clin)
        g0v_sol_clin["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_sol_clin)
        clin_sol_deff = _make_composite_bundle(clin_lot_id, mcb_id, pv_lead, leg_clin, g0v_sol_clin)
        clin_sol_f = Path(td) / "r11_b3_clin_sol_deff.json"
        clin_sol_f.write_text(json.dumps(clin_sol_deff, sort_keys=True), encoding="utf-8")
        res_71, rc_71 = evaluate_composite_lot_file(
            clin_sol_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
        )
        ok_71 = bool(
            rc_71 == 2
            and res_71["composite_verdict"] == "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE"
            and res_71["release_authorizing"] is False
            and "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE" in res_71["holds"]
            and (res_71.get("gate0v_result_summary") or {}).get("exact_directional_confidence_certified") is False
            and bank_res["release_authorizing"] is False
            and bank_res["bank_qualification_authorized"] is True
        )
        cases.append({
            "case": "r11_b3_clustered_deff_2p0161_composite_lot_held_cluster_level_inference_exit_2",
            "expected_verdict": "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE",
            "actual_verdict": res_71["composite_verdict"],
            "operational_tier": res_71["operational_tier"],
            "legacy_passed": (res_71.get("legacy_result_summary") or {}).get("legacy_evaluator_passed"),
            "legacy_tier": (res_71.get("legacy_result_summary") or {}).get("lot_release_readiness_tier"),
            "legacy_resolved_pvid": (res_71.get("legacy_result_summary") or {}).get("resolved_product_variant_id"),
            "gate0v_passed": (res_71.get("gate0v_result_summary") or {}).get("gate0v_evaluator_passed"),
            "gate0v_verdict": (res_71.get("gate0v_result_summary") or {}).get("verdict"),
            "expected_token": "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE",
            "exit_code": rc_71,
            "hard_stops": res_71["hard_stops"][:2],
            "holds": res_71["holds"][:3],
            "passed": ok_71,
        })

        # 72. R11-B4: JSON nesting depth > 64 AND monkeypatched parser RecursionError on `{}` map cleanly
        #     to structured exit-2 HOLD (`release_authorizing=False`, `JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED`)
        #     across composite lot intake, coupled `--nw08-ocr-json` intake, AND `--trusted-qualification-store` intake!
        deep_70_f = Path(td) / "r11_b4_deep_70.json"
        deep_70_f.write_text('{"a":' * 70 + "1" + "}" * 70, encoding="utf-8")
        empty_f = Path(td) / "r11_b4_empty.json"
        empty_f.write_text("{}", encoding="utf-8")
        r_d_lot, rc_d_lot = evaluate_composite_lot_file(
            deep_70_f, legacy_evaluator=leg_fn, gate0v_evaluator=g0v_fn, openislet_root=openislet_root
        )
        r_d_ocr, rc_d_ocr = evaluate_composite_lot_file(
            clin_r2_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
            nw08_ocr_json_path=deep_70_f,
        )
        r_d_store, rc_d_store = evaluate_composite_lot_file(
            clin_r2_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=deep_70_f,
            openislet_root=openislet_root,
        )
        orig_v38_loads = v38.json.loads

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

        v38.json.loads = _raise_rec_comp  # type: ignore[assignment]
        try:
            r_r_lot, rc_r_lot = evaluate_composite_lot_file(
                empty_f, legacy_evaluator=leg_fn, gate0v_evaluator=g0v_fn, openislet_root=openislet_root
            )
        finally:
            v38.json.loads = orig_v38_loads  # type: ignore[assignment]

        ok_72 = bool(
            rc_d_lot == 2
            and r_d_lot["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and r_d_lot["release_authorizing"] is False
            and "HOLD_COMPOSITE_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED" in r_d_lot["holds"]
            and rc_d_ocr == 2
            and r_d_ocr["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and r_d_ocr["release_authorizing"] is False
            and "HOLD_NW08_AMBIGUOUS_OR_NONCANONICAL_OCR_JSON:JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED" in r_d_ocr["holds"]
            and rc_d_store == 2
            and r_d_store["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and r_d_store["release_authorizing"] is False
            and "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE" in r_d_store["holds"]
            and any("JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED" in h for h in r_d_store["holds"])
            and rc_r_lot == 2
            and r_r_lot["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and r_r_lot["release_authorizing"] is False
            and "HOLD_COMPOSITE_AMBIGUOUS_OR_NONCANONICAL_LOT_JSON:JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED" in r_r_lot["holds"]
        )
        cases.append({
            "case": "r11_b4_depth_gt_64_and_injected_recursion_error_composite_lot_ocr_and_store_hold_exit_2",
            "expected_verdict": "HOLD_COMPOSITE_RELEASE",
            "actual_verdict": "HOLD_COMPOSITE_RELEASE" if ok_72 else "UNHANDLED_RECURSION_OR_WRONG_RC",
            "operational_tier": "LOT_RELEASE_SURROGATE",
            "legacy_passed": True,
            "legacy_tier": LEGACY_PASS_TIER,
            "legacy_resolved_pvid": pv_lead,
            "gate0v_passed": True,
            "gate0v_verdict": "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE",
            "expected_token": "JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED",
            "exit_code": 2 if ok_72 else -1,
            "hard_stops": [],
            "holds": r_r_lot["holds"][:3],
            "passed": ok_72,
        })

        # ------------------------------------------------------------------
        # Round-12 Final-Closure Composite Regressions (R12-B1 & R12-B2)
        # ------------------------------------------------------------------
        # 73. R12-B1: Composite `--lot-json` with missing clustering_and_independence_spec,
        #     invalid deff, independent_biological_units_n: 6 -> 3, or mutated per_unit_counts
        #     MUST fail closed (exit 2 HOLD, exact_directional_confidence_certified=False,
        #     release_authorizing=False), while deterministic biological FAIL_HARD_STOP
        #     (cxadr_ko_present=True with missing spec) preserves exit 3 FAIL_HARD_STOP!
        g0v_r12_miss = copy.deepcopy(g0v_bank)
        g0v_r12_miss.pop("clustering_and_independence_spec", None)
        g0v_r12_miss["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_r12_miss)
        f_r12_miss = Path(td) / "r12_b1_missing_spec.json"
        f_r12_miss.write_text(json.dumps(_make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, g0v_r12_miss), sort_keys=True), encoding="utf-8")
        r_73_miss, rc_73_miss = evaluate_composite_lot_file(
            f_r12_miss, legacy_evaluator=leg_fn, gate0v_evaluator=g0v_fn, openislet_root=openislet_root
        )

        g0v_r12_u3 = copy.deepcopy(g0v_bank)
        g0v_r12_u3["clustering_and_independence_spec"]["independent_biological_units_n"] = 3
        g0v_r12_u3["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_r12_u3)
        f_r12_u3 = Path(td) / "r12_b1_units_3.json"
        f_r12_u3.write_text(json.dumps(_make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, g0v_r12_u3), sort_keys=True), encoding="utf-8")
        r_73_u3, rc_73_u3 = evaluate_composite_lot_file(
            f_r12_u3, legacy_evaluator=leg_fn, gate0v_evaluator=g0v_fn, openislet_root=openislet_root
        )

        g0v_r12_mut = copy.deepcopy(g0v_bank)
        g0v_r12_mut["gate0v_kill_stress_ap1903"]["normoxia_baseline"]["beta"]["per_unit_counts"]["ap1903_24h"][0]["n"] += 1
        g0v_r12_mut["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_r12_mut)
        f_r12_mut = Path(td) / "r12_b1_mutated_partition.json"
        f_r12_mut.write_text(json.dumps(_make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, g0v_r12_mut), sort_keys=True), encoding="utf-8")
        r_73_mut, rc_73_mut = evaluate_composite_lot_file(
            f_r12_mut, legacy_evaluator=leg_fn, gate0v_evaluator=g0v_fn, openislet_root=openislet_root
        )

        g0v_r12_cx = copy.deepcopy(g0v_r12_miss)
        g0v_r12_cx["cxadr_ko_present"] = True
        g0v_r12_cx["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_r12_cx)
        f_r12_cx = Path(td) / "r12_b1_missing_spec_bio_fail.json"
        f_r12_cx.write_text(json.dumps(_make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, g0v_r12_cx), sort_keys=True), encoding="utf-8")
        r_73_cx, rc_73_cx = evaluate_composite_lot_file(
            f_r12_cx, legacy_evaluator=leg_fn, gate0v_evaluator=g0v_fn, openislet_root=openislet_root
        )

        ok_73 = bool(
            rc_73_miss == 2
            and r_73_miss["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and r_73_miss["release_authorizing"] is False
            and (r_73_miss.get("gate0v_result_summary") or {}).get("exact_directional_confidence_certified") is False
            and (r_73_miss.get("gate0v_result_summary") or {}).get("confidence_scope") == "UNCERTIFIED_MISSING_OR_INVALID_SAMPLING_SPEC"
            and rc_73_u3 == 2
            and r_73_u3["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and r_73_u3["release_authorizing"] is False
            and "HOLD_INSUFFICIENT_INDEPENDENT_BIOLOGICAL_UNITS" in r_73_u3["holds"]
            and (r_73_u3.get("gate0v_result_summary") or {}).get("exact_directional_confidence_certified") is False
            and rc_73_mut == 2
            and r_73_mut["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and r_73_mut["release_authorizing"] is False
            and "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS" in r_73_mut["holds"]
            and (r_73_mut.get("gate0v_result_summary") or {}).get("exact_directional_confidence_certified") is False
            and rc_73_cx == 3
            and r_73_cx["composite_verdict"] == "FAIL_HARD_STOP_COMPOSITE_RELEASE"
            and r_73_cx["release_authorizing"] is False
            and (r_73_cx.get("gate0v_result_summary") or {}).get("exact_directional_confidence_certified") is False
        )
        cases.append({
            "case": "r12_b1_sampling_spec_missing_invalid_6_to_3_partition_mismatch_hold_bio_fail_preserved",
            "expected_verdict": "HOLD_COMPOSITE_RELEASE",
            "actual_verdict": r_73_u3["composite_verdict"],
            "operational_tier": r_73_u3["operational_tier"],
            "legacy_passed": (r_73_u3.get("legacy_result_summary") or {}).get("legacy_evaluator_passed"),
            "legacy_tier": (r_73_u3.get("legacy_result_summary") or {}).get("lot_release_readiness_tier"),
            "legacy_resolved_pvid": (r_73_u3.get("legacy_result_summary") or {}).get("resolved_product_variant_id"),
            "gate0v_passed": (r_73_u3.get("gate0v_result_summary") or {}).get("gate0v_evaluator_passed"),
            "gate0v_verdict": (r_73_u3.get("gate0v_result_summary") or {}).get("verdict"),
            "expected_token": "HOLD_INSUFFICIENT_INDEPENDENT_BIOLOGICAL_UNITS",
            "exit_code": rc_73_u3,
            "hard_stops": r_73_cx["hard_stops"][:2],
            "holds": r_73_u3["holds"][:3],
            "passed": ok_73,
        })

        # 74. R12-B2 (a): Coupled composite `--nw08-ocr-json` (even when FULLY lot-bound!) with
        #     `"uncertainty_se": -1e-400`, `-0.0`, and `"-0.0"` MUST fail closed (exit 2
        #     HOLD_COMPOSITE_RELEASE, release_authorizing=False, solver_executed=False)!
        ocr_bound_base = v38.build_bound_nw08_ocr_record(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            route_id="R2_DZ40",
            lot_payload_sha256=clin_r2_bundle["payload_sha256"],
            measured_ocr=1.097,
            uncertainty_se=0.0,
            measurement_record_id="OCR-R12B2-BOUND-1",
            measurement_evidence_sha256=clin_ev_sha,
            measurement_timestamp_utc="2026-11-29T01:00:00Z",
        )
        f_ocr_uf = Path(td) / "r12_b2_ocr_underflow.json"
        f_ocr_uf.write_text(
            json.dumps(ocr_bound_base, sort_keys=True).replace('"uncertainty_se": 0.0', '"uncertainty_se": -1e-400'),
            encoding="utf-8",
        )
        ocr_bound_sz = copy.deepcopy(ocr_bound_base)
        ocr_bound_sz["uncertainty_se"] = v38.Decimal("-0.0")
        ocr_bound_sz["ocr_record_sha256"] = v38.compute_nw08_ocr_record_sha256(ocr_bound_sz)
        f_ocr_sz = Path(td) / "r12_b2_ocr_signed_zero.json"
        f_ocr_sz.write_text(v38._canonical_json_dumps(ocr_bound_sz), encoding="utf-8")
        ocr_bound_sz_s = copy.deepcopy(ocr_bound_base)
        ocr_bound_sz_s["uncertainty_se"] = "-0.0"
        ocr_bound_sz_s["ocr_record_sha256"] = v38.compute_nw08_ocr_record_sha256(ocr_bound_sz_s)
        f_ocr_sz_s = Path(td) / "r12_b2_ocr_signed_zero_str.json"
        f_ocr_sz_s.write_text(json.dumps(ocr_bound_sz_s, sort_keys=True), encoding="utf-8")

        r_74_uf, rc_74_uf = evaluate_composite_lot_file(
            clin_r2_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
            nw08_ocr_json_path=f_ocr_uf,
        )
        r_74_sz, rc_74_sz = evaluate_composite_lot_file(
            clin_r2_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
            nw08_ocr_json_path=f_ocr_sz,
        )
        r_74_szs, rc_74_szs = evaluate_composite_lot_file(
            clin_r2_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
            nw08_ocr_json_path=f_ocr_sz_s,
        )
        ok_74 = bool(
            rc_74_uf == 2
            and r_74_uf["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and r_74_uf["release_authorizing"] is False
            and "HOLD_NW08_AMBIGUOUS_OR_NONCANONICAL_OCR_JSON:NONZERO_FLOAT_UNDERFLOW_REJECTED" in r_74_uf["holds"]
            and (r_74_uf.get("nw08_measured_ocr_dispatch_result") or {}).get("solver_executed") is False
            and rc_74_sz == 2
            and r_74_sz["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and r_74_sz["release_authorizing"] is False
            and "INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE" in r_74_sz["holds"]
            and (r_74_sz.get("nw08_measured_ocr_dispatch_result") or {}).get("solver_executed") is False
            and rc_74_szs == 2
            and r_74_szs["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and r_74_szs["release_authorizing"] is False
            and "INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE" in r_74_szs["holds"]
            and (r_74_szs.get("nw08_measured_ocr_dispatch_result") or {}).get("solver_executed") is False
        )
        cases.append({
            "case": "r12_b2_coupled_nw08_ocr_underflow_neg_1e_minus_400_and_signed_zero_hold_exit_2",
            "expected_verdict": "HOLD_COMPOSITE_RELEASE",
            "actual_verdict": r_74_uf["composite_verdict"],
            "operational_tier": r_74_uf["operational_tier"],
            "legacy_passed": (r_74_uf.get("legacy_result_summary") or {}).get("legacy_evaluator_passed"),
            "legacy_tier": (r_74_uf.get("legacy_result_summary") or {}).get("lot_release_readiness_tier"),
            "legacy_resolved_pvid": (r_74_uf.get("legacy_result_summary") or {}).get("resolved_product_variant_id"),
            "gate0v_passed": (r_74_uf.get("gate0v_result_summary") or {}).get("gate0v_evaluator_passed"),
            "gate0v_verdict": (r_74_uf.get("gate0v_result_summary") or {}).get("verdict"),
            "expected_token": "HOLD_NW08_AMBIGUOUS_OR_NONCANONICAL_OCR_JSON:NONZERO_FLOAT_UNDERFLOW_REJECTED",
            "exit_code": rc_74_uf,
            "hard_stops": [],
            "holds": r_74_uf["holds"][:3],
            "passed": ok_74,
        })

        # 75. R12-B2 (b): Composite `--lot-json` with `clustering_design_effect_deff: 1.00000000000000001`
        #     (raw JSON number) AND `"1.00000000000000001"` (JSON string) 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!
        g0v_deff_str = copy.deepcopy(g0v_clin)
        g0v_deff_str["clustering_and_independence_spec"]["clustering_design_effect_deff"] = "1.00000000000000001"
        g0v_deff_str["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_deff_str)
        f_deff_str = Path(td) / "r12_b2_comp_deff_str.json"
        f_deff_str.write_text(
            json.dumps(_make_composite_bundle(clin_lot_id, mcb_id, pv_lead, leg_clin, g0v_deff_str), sort_keys=True),
            encoding="utf-8",
        )

        g0v_deff_num = copy.deepcopy(g0v_clin)
        g0v_deff_num["clustering_and_independence_spec"]["clustering_design_effect_deff"] = v38.Decimal("1.00000000000000001")
        g0v_deff_num["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_deff_num)
        comp_num_txt = v38._canonical_json_dumps(
            _make_composite_bundle(clin_lot_id, mcb_id, pv_lead, leg_clin, g0v_deff_num)
        )
        f_deff_num = Path(td) / "r12_b2_comp_deff_num.json"
        f_deff_num.write_text(comp_num_txt, encoding="utf-8")

        r_75_str, rc_75_str = evaluate_composite_lot_file(
            f_deff_str,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
        )
        r_75_num, rc_75_num = evaluate_composite_lot_file(
            f_deff_num,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
        )
        ok_75 = bool(
            '"clustering_design_effect_deff":1.00000000000000001' in comp_num_txt
            and rc_75_str == 2
            and rc_75_num == 2
            and r_75_str["composite_verdict"] == "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE"
            and r_75_num["composite_verdict"] == "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE"
            and r_75_str["release_authorizing"] is False
            and r_75_num["release_authorizing"] is False
            and (r_75_str.get("gate0v_result_summary") or {}).get("exact_directional_confidence_certified") is False
            and (r_75_num.get("gate0v_result_summary") or {}).get("exact_directional_confidence_certified") is False
            and "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE" in r_75_str["holds"]
            and "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE" in r_75_num["holds"]
        )
        cases.append({
            "case": "r12_b2_composite_lot_deff_json_number_vs_string_1p00000000000000001_identical_clustered_hold",
            "expected_verdict": "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE",
            "actual_verdict": r_75_num["composite_verdict"],
            "operational_tier": r_75_num["operational_tier"],
            "legacy_passed": (r_75_num.get("legacy_result_summary") or {}).get("legacy_evaluator_passed"),
            "legacy_tier": (r_75_num.get("legacy_result_summary") or {}).get("lot_release_readiness_tier"),
            "legacy_resolved_pvid": (r_75_num.get("legacy_result_summary") or {}).get("resolved_product_variant_id"),
            "gate0v_passed": (r_75_num.get("gate0v_result_summary") or {}).get("gate0v_evaluator_passed"),
            "gate0v_verdict": (r_75_num.get("gate0v_result_summary") or {}).get("verdict"),
            "expected_token": "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE",
            "exit_code": rc_75_num,
            "hard_stops": [],
            "holds": r_75_num["holds"][:3],
            "passed": ok_75,
        })

        # ------------------------------------------------------------------
        # Round-13 Final-Closure Composite Regressions (R13-B1, B2, B3, B4, M1, M2)
        # ------------------------------------------------------------------
        reg_r13 = Path(td) / "r13_trusted_reg.json"
        dir_r13 = Path(td) / "r13_trusted_dir"
        for st_13 in (reg_r13, dir_r13):
            v38.write_record_to_trusted_qualification_store(
                st_13, auth_bank_rec, category="bank_qualifications", archived_payload=bank_bundle
            )

        # 76. R13-B1 (a): Single-cell clinical surrogate lot with adverse k=1 viral survivor in a
        #     submitted supplemental stress arm's `per_unit_counts` (and aggregate=0) MUST fail closed
        #     with `FAIL_HARD_STOP_COMPOSITE_RELEASE` (exit 3, release_authorizing=False) across BOTH
        #     store layouts, while clean unexpected `per_unit_counts` fails closed with exit 2 HOLD!
        g0v_sc_clin = v38.build_passing_reference_payload(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            qualification_tier="LOT_RELEASE_SURROGATE",
            bridged_mcb_qualification_sha256=auth_bank_rec["sha256"],
            independent_biological_units_n=6_000_000,
            independent_sampling_unit_class="INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT",
            openislet_root=openislet_root,
        )
        g0v_sc_adv = copy.deepcopy(g0v_sc_clin)
        sup_arm_cvb = copy.deepcopy(g0v_bank["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"])
        sup_arm_cvb["beta"]["per_unit_counts"]["infected_viral_pos_72h"][0]["k"] = 1
        g0v_sc_adv["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"] = sup_arm_cvb
        g0v_sc_adv["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_sc_adv)
        f_sc_adv = Path(td) / "r13_b1_sc_adverse_supp.json"
        f_sc_adv.write_text(
            json.dumps(_make_composite_bundle(clin_lot_id, mcb_id, pv_lead, leg_clin, g0v_sc_adv), sort_keys=True),
            encoding="utf-8",
        )
        g0v_sc_unexp = copy.deepcopy(g0v_sc_clin)
        g0v_sc_unexp["gate0v_kill_stress_ap1903"]["normoxia_baseline"]["beta"]["per_unit_counts"] = copy.deepcopy(
            g0v_bank["gate0v_kill_stress_ap1903"]["normoxia_baseline"]["beta"]["per_unit_counts"]
        )
        g0v_sc_unexp["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_sc_unexp)
        f_sc_unexp = Path(td) / "r13_b1_sc_clean_unexp.json"
        f_sc_unexp.write_text(
            json.dumps(_make_composite_bundle(clin_lot_id, mcb_id, pv_lead, leg_clin, g0v_sc_unexp), sort_keys=True),
            encoding="utf-8",
        )
        ok_76 = True
        r_76_last: Dict[str, Any] = {}
        rc_76_last = -1
        for st_13 in (reg_r13, dir_r13):
            r_76_last, rc_76_last = evaluate_composite_lot_file(
                f_sc_adv,
                legacy_evaluator=leg_fn,
                gate0v_evaluator=g0v_fn,
                trusted_qualification_store=st_13,
                openislet_root=openislet_root,
            )
            r_76_u, rc_76_u = evaluate_composite_lot_file(
                f_sc_unexp,
                legacy_evaluator=leg_fn,
                gate0v_evaluator=g0v_fn,
                trusted_qualification_store=st_13,
                openislet_root=openislet_root,
            )
            if not (
                rc_76_last == 3
                and r_76_last["composite_verdict"] == "FAIL_HARD_STOP_COMPOSITE_RELEASE"
                and r_76_last["release_authorizing"] is False
                and "HARD_STOP_ADVERSE_PER_UNIT_POST_AP1903_VIRAL_ESCAPE" in r_76_last["hard_stops"]
                and (r_76_last.get("gate0v_result_summary") or {}).get("exact_directional_confidence_certified") is False
                and rc_76_u == 2
                and r_76_u["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
                and r_76_u["release_authorizing"] is False
                and "HOLD_UNEXPECTED_PER_UNIT_COUNTS_IN_SINGLE_CELL_MODE" in r_76_u["holds"]
            ):
                ok_76 = False
        cases.append({
            "case": "r13_b1_single_cell_adverse_per_unit_counts_supplemental_arm_composite_hard_stop_both_stores",
            "expected_verdict": "FAIL_HARD_STOP_COMPOSITE_RELEASE",
            "actual_verdict": r_76_last.get("composite_verdict"),
            "operational_tier": r_76_last.get("operational_tier"),
            "legacy_passed": (r_76_last.get("legacy_result_summary") or {}).get("legacy_evaluator_passed"),
            "legacy_tier": (r_76_last.get("legacy_result_summary") or {}).get("lot_release_readiness_tier"),
            "legacy_resolved_pvid": (r_76_last.get("legacy_result_summary") or {}).get("resolved_product_variant_id"),
            "gate0v_passed": (r_76_last.get("gate0v_result_summary") or {}).get("gate0v_evaluator_passed"),
            "gate0v_verdict": (r_76_last.get("gate0v_result_summary") or {}).get("verdict"),
            "expected_token": "HARD_STOP_ADVERSE_PER_UNIT_POST_AP1903_VIRAL_ESCAPE",
            "exit_code": rc_76_last,
            "hard_stops": (r_76_last.get("hard_stops") or [])[:3],
            "holds": (r_76_last.get("holds") or [])[:3],
            "passed": ok_76,
        })

        # 77. R13-B1 (b): Multi-well malformed row (missing/empty unit_id) BEFORE an adverse k=1 row
        #     MUST preserve `FAIL_HARD_STOP_COMPOSITE_RELEASE` (exit 3, NEVER downgraded to HOLD)!
        g0v_mw_mal = copy.deepcopy(g0v_clin)
        sup_mal_cvb = copy.deepcopy(g0v_bank["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"])
        sup_mal_cvb["beta"]["per_unit_counts"]["infected_viral_pos_72h"][0]["unit_id"] = ""
        sup_mal_cvb["beta"]["per_unit_counts"]["infected_viral_pos_72h"][1]["k"] = 1
        g0v_mw_mal["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"] = sup_mal_cvb
        g0v_mw_mal["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_mw_mal)
        f_mw_mal = Path(td) / "r13_b1_mw_malformed_plus_adverse.json"
        f_mw_mal.write_text(
            json.dumps(_make_composite_bundle(clin_lot_id, mcb_id, pv_lead, leg_clin, g0v_mw_mal), sort_keys=True),
            encoding="utf-8",
        )
        r_77, rc_77 = evaluate_composite_lot_file(
            f_mw_mal,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=reg_r13,
            openislet_root=openislet_root,
        )
        ok_77 = bool(
            rc_77 == 3
            and r_77["composite_verdict"] == "FAIL_HARD_STOP_COMPOSITE_RELEASE"
            and r_77["release_authorizing"] is False
            and "HARD_STOP_ADVERSE_PER_UNIT_POST_AP1903_VIRAL_ESCAPE" in r_77["hard_stops"]
        )
        cases.append({
            "case": "r13_b1_multi_well_malformed_row_plus_adverse_survivor_composite_preserves_hard_stop",
            "expected_verdict": "FAIL_HARD_STOP_COMPOSITE_RELEASE",
            "actual_verdict": r_77["composite_verdict"],
            "operational_tier": r_77["operational_tier"],
            "legacy_passed": (r_77.get("legacy_result_summary") or {}).get("legacy_evaluator_passed"),
            "legacy_tier": (r_77.get("legacy_result_summary") or {}).get("lot_release_readiness_tier"),
            "legacy_resolved_pvid": (r_77.get("legacy_result_summary") or {}).get("resolved_product_variant_id"),
            "gate0v_passed": (r_77.get("gate0v_result_summary") or {}).get("gate0v_evaluator_passed"),
            "gate0v_verdict": (r_77.get("gate0v_result_summary") or {}).get("verdict"),
            "expected_token": "HARD_STOP_ADVERSE_PER_UNIT_POST_AP1903_VIRAL_ESCAPE",
            "exit_code": rc_77,
            "hard_stops": r_77["hard_stops"][:3],
            "holds": r_77["holds"][:3],
            "passed": ok_77,
        })

        # 78. R13-B2: Impossible same-well subset (125 direct infected-vehicle survivors in WELL-01
        #     which has only 90 total veh_72h survivors) MUST fail closed with exit 2 HOLD and
        #     `HOLD_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION` (bank_qualification_authorized=False)!
        g0v_b2_sub = copy.deepcopy(g0v_bank)
        div_b2 = g0v_b2_sub["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["per_unit_counts"]["direct_infected_veh_72h"]
        div_b2[0]["k"] = 125
        for _ix in range(1, len(div_b2)):
            div_b2[_ix]["k"] = 0
        g0v_b2_sub["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_b2_sub)
        f_b2_sub = Path(td) / "r13_b2_impossible_subset_125_gt_90.json"
        f_b2_sub.write_text(
            json.dumps(_make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, g0v_b2_sub), sort_keys=True),
            encoding="utf-8",
        )
        r_78, rc_78 = evaluate_composite_lot_file(
            f_b2_sub, legacy_evaluator=leg_fn, gate0v_evaluator=g0v_fn, openislet_root=openislet_root
        )
        ok_78 = bool(
            rc_78 == 2
            and r_78["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and r_78["release_authorizing"] is False
            and r_78["bank_qualification_authorized"] is False
            and "HOLD_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION" in r_78["holds"]
            and (r_78.get("gate0v_result_summary") or {}).get("exact_directional_confidence_certified") is False
            and (r_78.get("gate0v_result_summary") or {}).get("clustering_design_effect_deff") is None
        )
        cases.append({
            "case": "r13_b2_composite_within_unit_direct_infected_veh_125_gt_90_contradiction_hold_exit_2",
            "expected_verdict": "HOLD_COMPOSITE_RELEASE",
            "actual_verdict": r_78["composite_verdict"],
            "operational_tier": r_78["operational_tier"],
            "legacy_passed": (r_78.get("legacy_result_summary") or {}).get("legacy_evaluator_passed"),
            "legacy_tier": (r_78.get("legacy_result_summary") or {}).get("lot_release_readiness_tier"),
            "legacy_resolved_pvid": (r_78.get("legacy_result_summary") or {}).get("resolved_product_variant_id"),
            "gate0v_passed": (r_78.get("gate0v_result_summary") or {}).get("gate0v_evaluator_passed"),
            "gate0v_verdict": (r_78.get("gate0v_result_summary") or {}).get("verdict"),
            "expected_token": "HOLD_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION",
            "exit_code": rc_78,
            "hard_stops": r_78["hard_stops"][:2],
            "holds": r_78["holds"][:3],
            "passed": ok_78,
        })

        # 79. R13-B3: Subtractive policy — `require_trusted_nw08_ocr_record=True` on `BANK_QUALIFICATION`
        #     is rejected identically at direct admission (even with a matching QA-registered bank OCR
        #     sidecar!) AND at archived bank replay across BOTH store layouts!
        bank_req_ocr = _make_composite_bundle(
            bank_lot_id,
            mcb_id,
            pv_lead,
            leg_bank,
            g0v_bank,
            nw08_route_id="R2_DZ40",
            nw08_measurement_evidence_sha256=clin_ev_sha,
            require_trusted_nw08_ocr_record=True,
        )
        bank_ocr_rec = v38.build_bound_nw08_ocr_record(
            lot_id=bank_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            route_id="R2_DZ40",
            lot_payload_sha256=bank_req_ocr["payload_sha256"],
            measured_ocr=1.097,
            uncertainty_se=0.0,
            measurement_record_id="OCR-BANK-R13B3-001",
            measurement_evidence_sha256=clin_ev_sha,
            measurement_timestamp_utc="2026-11-29T02:00:00Z",
        )
        forged_bank_rec_ocr = v38.build_authenticated_bank_qualification_record(
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            bank_lot_id=bank_lot_id,
            bank_payload_sha256=bank_req_ocr["payload_sha256"],
            verdict="PASS_COMPOSITE_BANK_QUALIFICATION",
            operational_tier="BANK_QUALIFICATION",
        )
        f_bank_req_ocr = Path(td) / "r13_b3_bank_req_ocr.json"
        f_bank_req_ocr.write_text(json.dumps(bank_req_ocr, sort_keys=True), encoding="utf-8")
        f_bank_ocr_rec = Path(td) / "r13_b3_bank_ocr_sidecar.json"
        f_bank_ocr_rec.write_text(json.dumps(bank_ocr_rec, sort_keys=True), encoding="utf-8")

        g0v_dep_b3 = v38.build_passing_reference_payload(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            qualification_tier="LOT_RELEASE_SURROGATE",
            bridged_mcb_qualification_sha256=forged_bank_rec_ocr["sha256"],
            openislet_root=openislet_root,
        )
        dep_lot_b3 = _make_composite_bundle(clin_lot_id, mcb_id, pv_lead, leg_clin, g0v_dep_b3)
        f_dep_b3 = Path(td) / "r13_b3_dep_lot.json"
        f_dep_b3.write_text(json.dumps(dep_lot_b3, sort_keys=True), encoding="utf-8")

        reg_b3 = Path(td) / "r13_b3_reg.json"
        dir_b3 = Path(td) / "r13_b3_dir"
        for st_b3 in (reg_b3, dir_b3):
            v38.write_record_to_trusted_qualification_store(
                st_b3, forged_bank_rec_ocr, category="bank_qualifications", archived_payload=bank_req_ocr
            )
            v38.write_record_to_trusted_qualification_store(st_b3, bank_ocr_rec, category="nw08_ocr_records")

        ok_79 = True
        r_79_dir_last: Dict[str, Any] = {}
        rc_79_dir_last = -1
        for st_b3 in (reg_b3, dir_b3):
            r_79_dir_last, rc_79_dir_last = evaluate_composite_lot_file(
                f_bank_req_ocr,
                legacy_evaluator=leg_fn,
                gate0v_evaluator=g0v_fn,
                trusted_qualification_store=st_b3,
                openislet_root=openislet_root,
                nw08_ocr_json_path=f_bank_ocr_rec,
            )
            r_79_arch, rc_79_arch = evaluate_composite_lot_file(
                f_dep_b3,
                legacy_evaluator=leg_fn,
                gate0v_evaluator=g0v_fn,
                trusted_qualification_store=st_b3,
                openislet_root=openislet_root,
            )
            pqa_79 = r_79_arch.get("prior_qualification_authentication") or {}
            if not (
                rc_79_dir_last == 2
                and r_79_dir_last["composite_verdict"] == "HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION"
                and r_79_dir_last["release_authorizing"] is False
                and r_79_dir_last["bank_qualification_authorized"] is False
                and "HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION" in r_79_dir_last["holds"]
                and (r_79_dir_last.get("nw08_measured_ocr_dispatch_result") or {}).get("solver_executed") is False
                and rc_79_arch == 2
                and r_79_arch["release_authorizing"] is False
                and "HOLD_ARCHIVED_BANK_ENVELOPE_MISMATCH" in r_79_arch["holds"]
                and "HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION" in r_79_arch["holds"]
                and pqa_79.get("archived_bank_payload_live_revalidation_passed") is False
                and pqa_79.get("archived_bank_payload_live_g0v_revalidation_passed") is False
                and pqa_79.get("archived_bank_payload_live_legacy_revalidation_passed") is False
                and pqa_79.get("archived_bank_payload_live_composite_revalidation_passed") is False
            ):
                ok_79 = False
        cases.append({
            "case": "r13_b3_bank_require_trusted_nw08_ocr_rejected_direct_and_archived_replay_both_stores",
            "expected_verdict": "HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION",
            "actual_verdict": r_79_dir_last.get("composite_verdict"),
            "operational_tier": r_79_dir_last.get("operational_tier"),
            "legacy_passed": (r_79_dir_last.get("legacy_result_summary") or {}).get("legacy_evaluator_passed"),
            "legacy_tier": (r_79_dir_last.get("legacy_result_summary") or {}).get("lot_release_readiness_tier"),
            "legacy_resolved_pvid": (r_79_dir_last.get("legacy_result_summary") or {}).get("resolved_product_variant_id"),
            "gate0v_passed": (r_79_dir_last.get("gate0v_result_summary") or {}).get("gate0v_evaluator_passed"),
            "gate0v_verdict": (r_79_dir_last.get("gate0v_result_summary") or {}).get("verdict"),
            "expected_token": "HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION",
            "exit_code": rc_79_dir_last,
            "hard_stops": [],
            "holds": (r_79_dir_last.get("holds") or [])[:3],
            "passed": ok_79,
        })

        # 80. R13-B4: Live composite PASS responses across ALL 3 tiers (Bank, Clinical Surrogate
        #     across BOTH store layouts, and Autologous Process Qual) MUST attach explicit
        #     `qualification_scope = "CONDITIONAL_ON_MODELED_ASSUMPTIONS_PENDING_PHYSICAL_QUALIFICATION"`
        #     and `physical_qualification_complete = False` on BOTH Python API and file/CLI intake!
        r_80_clin_reg, rc_80_cr = evaluate_composite_lot_file(
            clin_r2_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=reg_r13,
            openislet_root=openislet_root,
        )
        r_80_clin_dir, rc_80_cd = evaluate_composite_lot_file(
            clin_r2_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=dir_r13,
            openislet_root=openislet_root,
        )
        pq_80 = v38.build_authenticated_process_qualification_record(
            product_variant_id="ISLET1_D1_AUTO_V2_L1A_CIITA_CD64T_IL1RN",
            process_qual_id="PQ-COMP-R13-80",
        )
        v38.write_record_to_trusted_qualification_store(reg_r13, pq_80, category="process_qualifications")
        g0v_auto_80 = v38.build_passing_reference_payload(
            lot_id="AUTO-COMP-R13-80",
            mcb_id="MCB-AUTO-COMP-R13-80",
            product_variant_id="ISLET1_D1_AUTO_V2_L1A_CIITA_CD64T_IL1RN",
            qualification_tier="AUTOLOGOUS_D1B_PROCESS_QUAL",
            process_qualification_ref_sha256=pq_80["sha256"],
            openislet_root=openislet_root,
        )
        leg_auto_80 = build_legacy_complete_stage0_observations(
            lot_id="AUTO-COMP-R13-80",
            mcb_id="MCB-AUTO-COMP-R13-80",
            product_variant_id="ISLET1_D1_AUTO_V2_L1A_CIITA_CD64T_IL1RN",
        )
        auto_80_bundle = _make_composite_bundle(
            "AUTO-COMP-R13-80", "MCB-AUTO-COMP-R13-80", "ISLET1_D1_AUTO_V2_L1A_CIITA_CD64T_IL1RN", leg_auto_80, g0v_auto_80
        )

        def _promoted_auto_legacy_stub(obs: Dict[str, Any], **_kw: Any) -> Dict[str, Any]:
            return {
                "lot_release_readiness_tier": LEGACY_PASS_TIER,
                "safety_kill_s9_triggered": False,
                "resolved_architecture_assignments": {
                    "product_variant_id": obs.get("product_variant_id"),
                    "product_execution_supported": True,
                    "lot_release_readiness_tier": LEGACY_PASS_TIER,
                },
            }

        r_80_auto = evaluate_composite_clinical_release(
            auto_80_bundle,
            legacy_evaluator=_promoted_auto_legacy_stub,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=reg_r13,
            openislet_root=openislet_root,
        )
        ok_80 = bool(
            bank_res["composite_verdict"] == "PASS_COMPOSITE_BANK_QUALIFICATION"
            and bank_res.get("qualification_scope") == QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL
            and bank_res.get("physical_qualification_complete") is False
            and rc_80_cr == 0
            and r_80_clin_reg["composite_verdict"] == "PASS_COMPOSITE_CLINICAL_RELEASE"
            and r_80_clin_reg["release_authorizing"] is True
            and r_80_clin_reg.get("qualification_scope") == QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL
            and r_80_clin_reg.get("physical_qualification_complete") is False
            and (r_80_clin_reg.get("gate0v_result_summary") or {}).get("qualification_scope") == QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL
            and (r_80_clin_reg.get("gate0v_result_summary") or {}).get("physical_qualification_complete") is False
            and rc_80_cd == 0
            and r_80_clin_dir["composite_verdict"] == "PASS_COMPOSITE_CLINICAL_RELEASE"
            and r_80_clin_dir.get("qualification_scope") == QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL
            and r_80_clin_dir.get("physical_qualification_complete") is False
            and r_80_auto["composite_verdict"] == "PASS_COMPOSITE_AUTOLOGOUS_CLINICAL_RELEASE"
            and r_80_auto["release_authorizing"] is True
            and r_80_auto.get("qualification_scope") == QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL
            and r_80_auto.get("physical_qualification_complete") is False
        )
        cases.append({
            "case": "r13_b4_composite_live_pass_all_tiers_emit_qualification_scope_and_physical_complete_false",
            "expected_verdict": "PASS_COMPOSITE_CLINICAL_RELEASE",
            "actual_verdict": r_80_clin_reg["composite_verdict"],
            "operational_tier": r_80_clin_reg["operational_tier"],
            "legacy_passed": (r_80_clin_reg.get("legacy_result_summary") or {}).get("legacy_evaluator_passed"),
            "legacy_tier": (r_80_clin_reg.get("legacy_result_summary") or {}).get("lot_release_readiness_tier"),
            "legacy_resolved_pvid": (r_80_clin_reg.get("legacy_result_summary") or {}).get("resolved_product_variant_id"),
            "gate0v_passed": (r_80_clin_reg.get("gate0v_result_summary") or {}).get("gate0v_evaluator_passed"),
            "gate0v_verdict": (r_80_clin_reg.get("gate0v_result_summary") or {}).get("verdict"),
            "expected_token": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
            "exit_code": rc_80_cr,
            "hard_stops": [],
            "holds": [],
            "passed": ok_80,
        })

        # 81. R13-M1 & R13-M2: Composite `--lot-json` and coupled `--nw08-ocr-json` reject JSON integer
        #     `-0` AND string `"-0"` with exit 2 HOLD (`INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE`),
        #     AND invalid sampling spec (`units=3, deff=2.0`) / missing partition clear `clustering_design_effect_deff`
        #     to `None` while reporting `submitted_clustering_design_effect_deff_unvalidated`!
        f_lot_ni0 = Path(td) / "r13_m1_lot_neg_zero_int.json"
        f_lot_ni0.write_text('{"qualification_tier": "BANK_QUALIFICATION", "probe": -0}', encoding="utf-8")
        r_81_lot, rc_81_lot = evaluate_composite_lot_file(
            f_lot_ni0, legacy_evaluator=leg_fn, gate0v_evaluator=g0v_fn, openislet_root=openislet_root
        )
        f_ocr_ni0 = Path(td) / "r13_m1_ocr_neg_zero_int.json"
        f_ocr_ni0.write_text(
            json.dumps(ocr_bound_base, sort_keys=True).replace('"uncertainty_se": 0.0', '"uncertainty_se": -0'),
            encoding="utf-8",
        )
        r_81_ocr, rc_81_ocr = evaluate_composite_lot_file(
            clin_r2_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=reg_r13,
            openislet_root=openislet_root,
            nw08_ocr_json_path=f_ocr_ni0,
        )
        g0v_81_u3d2 = copy.deepcopy(g0v_bank)
        g0v_81_u3d2["clustering_and_independence_spec"]["independent_biological_units_n"] = 3
        g0v_81_u3d2["clustering_and_independence_spec"]["clustering_design_effect_deff"] = "2.0"
        g0v_81_u3d2["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_81_u3d2)
        f_81_u3d2 = Path(td) / "r13_m2_u3_deff2.json"
        f_81_u3d2.write_text(
            json.dumps(_make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, g0v_81_u3d2), sort_keys=True),
            encoding="utf-8",
        )
        r_81_m2, rc_81_m2 = evaluate_composite_lot_file(
            f_81_u3d2, legacy_evaluator=leg_fn, gate0v_evaluator=g0v_fn, openislet_root=openislet_root
        )
        ok_81 = bool(
            rc_81_lot == 2
            and r_81_lot["release_authorizing"] is False
            and "INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE" in r_81_lot["holds"]
            and rc_81_ocr == 2
            and r_81_ocr["release_authorizing"] is False
            and "INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE" in r_81_ocr["holds"]
            and (r_81_ocr.get("nw08_measured_ocr_dispatch_result") or {}).get("solver_executed") is False
            and rc_81_m2 == 2
            and r_81_m2["release_authorizing"] is False
            and (r_81_m2.get("gate0v_result_summary") or {}).get("clustering_design_effect_deff") is None
            and (r_81_m2.get("gate0v_result_summary") or {}).get("submitted_clustering_design_effect_deff_unvalidated") == "2.0"
        )
        cases.append({
            "case": "r13_m1_m2_composite_neg_zero_int_rejected_and_unvalidated_deff_none",
            "expected_verdict": "HOLD_COMPOSITE_RELEASE",
            "actual_verdict": r_81_ocr["composite_verdict"],
            "operational_tier": r_81_ocr["operational_tier"],
            "legacy_passed": (r_81_ocr.get("legacy_result_summary") or {}).get("legacy_evaluator_passed"),
            "legacy_tier": (r_81_ocr.get("legacy_result_summary") or {}).get("lot_release_readiness_tier"),
            "legacy_resolved_pvid": (r_81_ocr.get("legacy_result_summary") or {}).get("resolved_product_variant_id"),
            "gate0v_passed": (r_81_ocr.get("gate0v_result_summary") or {}).get("gate0v_evaluator_passed"),
            "gate0v_verdict": (r_81_ocr.get("gate0v_result_summary") or {}).get("verdict"),
            "expected_token": "INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE",
            "exit_code": rc_81_ocr,
            "hard_stops": [],
            "holds": r_81_ocr["holds"][:3],
            "passed": ok_81,
        })

        # ------------------------------------------------------------------
        # Round-14 Final-Closure Regressions (R14-B1 Mesh-Convergence HOLD,
        # R14-B2 Small-Sample Student-t OCR Inference & Bare-SE HOLD,
        # R14-B3 Cross-Interface Process-Wide Callback Serialization)
        # ------------------------------------------------------------------
        # 82. R14-B1: Coupled composite release routes BOTH observed mesh-resolution reversals
        #     (R1_390_stress @ 1.3164, bed=35 AND R2_DZ40 @ 2.099752752324571, bed=32) to
        #     HOLD_COMPOSITE_RELEASE (exit 2, release_authorizing=False,
        #     HOLD_NW08_MESH_CONVERGENCE_STRADDLES_15MMHG_FLOOR) before any coupled authorization!
        clin_r1_390_bundle = _make_composite_bundle(
            clin_lot_id,
            mcb_id,
            pv_lead,
            leg_clin,
            g0v_clin,
            nw08_route_id="R1_390_stress",
            nw08_measurement_evidence_sha256=clin_ev_sha,
            nw08_measurement_not_before_utc="2026-11-28T00:00:00Z",
        )
        clin_r1_390_f = Path(td) / "r14_b1_clin_r1_390.json"
        clin_r1_390_f.write_text(json.dumps(clin_r1_390_bundle, sort_keys=True), encoding="utf-8")
        ocr_r14_r1_rev = v38.build_bound_nw08_ocr_record(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            route_id="R1_390_stress",
            lot_payload_sha256=clin_r1_390_bundle["payload_sha256"],
            measured_ocr=1.3164,
            uncertainty_se=0.0,
            measurement_record_id="OCR-R14-B1-R1-REV",
            measurement_evidence_sha256=clin_ev_sha,
            measurement_timestamp_utc="2026-11-29T01:00:00Z",
        )
        ocr_r14_r2_rev = v38.build_bound_nw08_ocr_record(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            route_id="R2_DZ40",
            lot_payload_sha256=clin_r2_bundle["payload_sha256"],
            measured_ocr=2.099752752324571,
            uncertainty_se=0.0,
            baseline_vasc_ocr_mult=2.0,
            p_bed_mmhg=32.0,
            measurement_record_id="OCR-R14-B1-R2-REV",
            measurement_evidence_sha256=clin_ev_sha,
            measurement_timestamp_utc="2026-11-29T01:00:00Z",
        )
        f_r14_r1_rev = Path(td) / "r14_b1_ocr_r1_rev.json"
        f_r14_r1_rev.write_text(json.dumps(ocr_r14_r1_rev, sort_keys=True), encoding="utf-8")
        f_r14_r2_rev = Path(td) / "r14_b1_ocr_r2_rev.json"
        f_r14_r2_rev.write_text(json.dumps(ocr_r14_r2_rev, sort_keys=True), encoding="utf-8")
        r_82_r1, rc_82_r1 = evaluate_composite_lot_file(
            clin_r1_390_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
            nw08_ocr_json_path=f_r14_r1_rev,
        )
        r_82_r2, rc_82_r2 = evaluate_composite_lot_file(
            clin_r2_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
            nw08_ocr_json_path=f_r14_r2_rev,
        )
        ok_82 = bool(
            rc_82_r1 == 2
            and r_82_r1["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and r_82_r1["release_authorizing"] is False
            and "HOLD_NW08_MESH_CONVERGENCE_STRADDLES_15MMHG_FLOOR" in r_82_r1["holds"]
            and (r_82_r1.get("nw08_measured_ocr_dispatch_result") or {}).get("adjudicated_verdict") == "HOLD"
            and rc_82_r2 == 2
            and r_82_r2["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and r_82_r2["release_authorizing"] is False
            and "HOLD_NW08_MESH_CONVERGENCE_STRADDLES_15MMHG_FLOOR" in r_82_r2["holds"]
            and (r_82_r2.get("nw08_measured_ocr_dispatch_result") or {}).get("adjudicated_verdict") == "HOLD"
        )
        cases.append({
            "case": "r14_b1_coupled_mesh_reversals_r1_390_and_r2_dz40_route_to_hold_exit_2",
            "expected_verdict": "HOLD_COMPOSITE_RELEASE",
            "actual_verdict": r_82_r1["composite_verdict"],
            "operational_tier": r_82_r1["operational_tier"],
            "legacy_passed": (r_82_r1.get("legacy_result_summary") or {}).get("legacy_evaluator_passed"),
            "legacy_tier": (r_82_r1.get("legacy_result_summary") or {}).get("lot_release_readiness_tier"),
            "legacy_resolved_pvid": (r_82_r1.get("legacy_result_summary") or {}).get("resolved_product_variant_id"),
            "gate0v_passed": (r_82_r1.get("gate0v_result_summary") or {}).get("gate0v_evaluator_passed"),
            "gate0v_verdict": (r_82_r1.get("gate0v_result_summary") or {}).get("verdict"),
            "expected_token": "HOLD_NW08_MESH_CONVERGENCE_STRADDLES_15MMHG_FLOOR",
            "exit_code": rc_82_r1 if ok_82 else -1,
            "hard_stops": r_82_r1["hard_stops"][:2],
            "holds": r_82_r1["holds"][:3],
            "passed": ok_82,
        })

        # 83. R14-B2: Coupled OCR record with bare positive SE (no model/df) -> HOLD exit 2;
        #     same OCR=1.25, SE=0.06 with small-sample STUDENT_T_ESTIMATED_SE (n=6, df=5) -> FAIL exit 3!
        ocr_r14_bare_se = v38.build_bound_nw08_ocr_record(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            route_id="R1_390_stress",
            lot_payload_sha256=clin_r1_390_bundle["payload_sha256"],
            measured_ocr=1.25,
            uncertainty_se=0.06,
            measurement_record_id="OCR-R14-B2-BARE-SE",
            measurement_evidence_sha256=clin_ev_sha,
            measurement_timestamp_utc="2026-11-29T01:00:00Z",
        )
        ocr_r14_t6 = v38.build_bound_nw08_ocr_record(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            route_id="R1_390_stress",
            lot_payload_sha256=clin_r1_390_bundle["payload_sha256"],
            measured_ocr=1.25,
            uncertainty_se=0.06,
            ocr_uncertainty_model="STUDENT_T_ESTIMATED_SE",
            ocr_replicates_n=6,
            measurement_record_id="OCR-R14-B2-STUDENT-T6",
            measurement_evidence_sha256=clin_ev_sha,
            measurement_timestamp_utc="2026-11-29T01:00:00Z",
        )
        f_r14_bare = Path(td) / "r14_b2_bare_se.json"
        f_r14_bare.write_text(json.dumps(ocr_r14_bare_se, sort_keys=True), encoding="utf-8")
        f_r14_t6 = Path(td) / "r14_b2_student_t6.json"
        f_r14_t6.write_text(json.dumps(ocr_r14_t6, sort_keys=True), encoding="utf-8")
        r_83_bare, rc_83_bare = evaluate_composite_lot_file(
            clin_r1_390_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
            nw08_ocr_json_path=f_r14_bare,
        )
        r_83_t6, rc_83_t6 = evaluate_composite_lot_file(
            clin_r1_390_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
            nw08_ocr_json_path=f_r14_t6,
        )
        ok_83 = bool(
            rc_83_bare == 2
            and r_83_bare["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and r_83_bare["release_authorizing"] is False
            and "HOLD_NW08_OCR_MISSING_UNCERTAINTY_MODEL_OR_DF" in r_83_bare["holds"]
            and (r_83_bare.get("nw08_measured_ocr_dispatch_result") or {}).get("solver_executed") is False
            and rc_83_t6 == 3
            and r_83_t6["composite_verdict"] == "FAIL_HARD_STOP_COMPOSITE_RELEASE"
            and r_83_t6["release_authorizing"] is False
            and "FAIL_HARD_STOP_NW08_3D_FVM_BELOW_15MMHG_FLOOR" in r_83_t6["hard_stops"]
            and (r_83_t6.get("nw08_measured_ocr_dispatch_result") or {}).get("ocr_degrees_of_freedom") == 5
        )
        cases.append({
            "case": "r14_b2_coupled_bare_se_held_exit_2_and_student_t_n6_flips_to_fail_exit_3",
            "expected_verdict": "HOLD_2_FAIL_3",
            "actual_verdict": f"{r_83_bare['composite_verdict']}_{rc_83_bare}__{r_83_t6['composite_verdict']}_{rc_83_t6}",
            "operational_tier": r_83_t6["operational_tier"],
            "legacy_passed": (r_83_t6.get("legacy_result_summary") or {}).get("legacy_evaluator_passed"),
            "legacy_tier": (r_83_t6.get("legacy_result_summary") or {}).get("lot_release_readiness_tier"),
            "legacy_resolved_pvid": (r_83_t6.get("legacy_result_summary") or {}).get("resolved_product_variant_id"),
            "gate0v_passed": (r_83_t6.get("gate0v_result_summary") or {}).get("gate0v_evaluator_passed"),
            "gate0v_verdict": (r_83_t6.get("gate0v_result_summary") or {}).get("verdict"),
            "expected_token": "HOLD_NW08_OCR_MISSING_UNCERTAINTY_MODEL_OR_DF",
            "exit_code": 0 if ok_83 else -1,
            "hard_stops": r_83_t6["hard_stops"][:2],
            "holds": r_83_bare["holds"][:3],
            "passed": ok_83,
        })

        # 84. R14-B3: Concurrent direct `verify_iip0043` and wrapper `_get_v38_module()` share the
        #     canonical process-wide lock and produce identical serial/concurrent 3D FVM minima!
        from concurrent.futures import ThreadPoolExecutor as _TPE
        import threading as _thr

        direct_copy = _load_module("iip0043_r14_b3_direct_copy_self_test", _resolve_gate0v_verifier_path())
        shared_lock_ok = bool(direct_copy._FVM_SOLVER_LOCK is v38._FVM_SOLVER_LOCK)
        ser_35 = direct_copy.dispatch_and_solve_nw08_measured_ocr("R3P_35", 1.3164, 0.0, openislet_root=openislet_root, p_bed_mmhg=35.0)
        ser_30 = v38.dispatch_and_solve_nw08_measured_ocr("R3P_30", 1.3164, 0.0, openislet_root=openislet_root, p_bed_mmhg=30.0)
        conc_match = True
        for _att in range(3):
            b_sync = _thr.Barrier(2)

            def _run_c(m_obj, rt, pb):
                b_sync.wait(timeout=10)
                rr = m_obj.dispatch_and_solve_nw08_measured_ocr(rt, 1.3164, 0.0, openislet_root=openislet_root, p_bed_mmhg=pb)
                return (rr["face_min_mmhg_unrounded"], rr["adjudicated_verdict"])

            with _TPE(max_workers=2) as tp:
                f1 = tp.submit(_run_c, direct_copy, "R3P_35", 35.0)
                f2 = tp.submit(_run_c, v38, "R3P_30", 30.0)
                p1, p2 = f1.result(), f2.result()
            if p1 != (ser_35["face_min_mmhg_unrounded"], ser_35["adjudicated_verdict"]) or p2 != (
                ser_30["face_min_mmhg_unrounded"],
                ser_30["adjudicated_verdict"],
            ):
                conc_match = False
        ok_84 = bool(shared_lock_ok and conc_match)
        cases.append({
            "case": "r14_b3_concurrent_direct_and_wrapper_shared_lock_identical_serial_concurrent_results",
            "expected_verdict": "SHARED_LOCK_AND_EXACT_CONCURRENT_PARITY",
            "actual_verdict": "SHARED_LOCK_AND_EXACT_CONCURRENT_PARITY" if ok_84 else "CONCURRENT_MISMATCH",
            "operational_tier": "CROSS_INTERFACE_CONCURRENCY",
            "legacy_passed": True,
            "legacy_tier": LEGACY_PASS_TIER,
            "legacy_resolved_pvid": pv_lead,
            "gate0v_passed": True,
            "gate0v_verdict": "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE",
            "expected_token": None,
            "exit_code": 0 if ok_84 else -1,
            "hard_stops": [],
            "holds": [],
            "passed": ok_84,
        })

        # ------------------------------------------------------------------
        # Round-16 Closure Regression (R16-B1 Coupled Zero-SE Inferential Models)
        # ------------------------------------------------------------------
        # 85. R16-B1: Coupled composite release (`--nw08-ocr-json` AND Python API `nw08_ocr_record=`)
        #     rejects `uncertainty_se == 0` under BOTH `STUDENT_T_ESTIMATED_SE` and `KNOWN_SIGMA_NORMAL`
        #     BEFORE solving (`HOLD_COMPOSITE_RELEASE`, exit 2, `HOLD_NW08_INFERENTIAL_MODEL_REQUIRES_POSITIVE_SE`,
        #     `solver_executed = False`, `release_authorizing = False`), retains explicit
        #     `ZERO_UNCERTAINTY_DETERMINISTIC_POINT` PASS (exit 0), preserves positive-SE Student-t
        #     FAIL (`R1_390_stress, OCR=1.25, SE=0.06, n=6` -> exit 3), AND preserves independent
        #     biological `FAIL_HARD_STOP` precedence (`exit 3` over zero-SE OCR `HOLD` while recording
        #     `HOLD_NW08_INFERENTIAL_MODEL_REQUIRES_POSITIVE_SE` and `solver_executed = False`)!
        ocr_r16_st0_r2 = v38.build_bound_nw08_ocr_record(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            route_id="R2_DZ40",
            lot_payload_sha256=clin_r2_bundle["payload_sha256"],
            measured_ocr=1.097,
            uncertainty_se=0.0,
            ocr_uncertainty_model="STUDENT_T_ESTIMATED_SE",
            ocr_replicates_n=6,
            measurement_record_id="OCR-R16-B1-ST0-R2",
            measurement_evidence_sha256=clin_ev_sha,
            measurement_timestamp_utc="2026-11-29T01:00:00Z",
        )
        ocr_r16_st0_r1 = v38.build_bound_nw08_ocr_record(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            route_id="R1_390_stress",
            lot_payload_sha256=clin_r1_390_bundle["payload_sha256"],
            measured_ocr=1.25,
            uncertainty_se=0.0,
            ocr_uncertainty_model="STUDENT_T_ESTIMATED_SE",
            ocr_replicates_n=6,
            measurement_record_id="OCR-R16-B1-ST0-R1",
            measurement_evidence_sha256=clin_ev_sha,
            measurement_timestamp_utc="2026-11-29T01:00:00Z",
        )
        ocr_r16_ks0_r2 = v38.build_bound_nw08_ocr_record(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            route_id="R2_DZ40",
            lot_payload_sha256=clin_r2_bundle["payload_sha256"],
            measured_ocr=1.097,
            uncertainty_se=0.0,
            ocr_uncertainty_model="KNOWN_SIGMA_NORMAL",
            ocr_uncertainty_provenance="calibrated_respirometer_known_sigma_cert_v1",
            measurement_record_id="OCR-R16-B1-KS0-R2",
            measurement_evidence_sha256=clin_ev_sha,
            measurement_timestamp_utc="2026-11-29T01:00:00Z",
        )
        ocr_r16_det0_r2 = v38.build_bound_nw08_ocr_record(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            route_id="R2_DZ40",
            lot_payload_sha256=clin_r2_bundle["payload_sha256"],
            measured_ocr=1.097,
            uncertainty_se=0.0,
            ocr_uncertainty_model="ZERO_UNCERTAINTY_DETERMINISTIC_POINT",
            measurement_record_id="OCR-R16-B1-DET0-R2",
            measurement_evidence_sha256=clin_ev_sha,
            measurement_timestamp_utc="2026-11-29T01:00:00Z",
        )
        f_r16_st0_r2 = Path(td) / "r16_b1_ocr_st0_r2.json"
        f_r16_st0_r2.write_text(json.dumps(ocr_r16_st0_r2, sort_keys=True), encoding="utf-8")
        f_r16_st0_r1 = Path(td) / "r16_b1_ocr_st0_r1.json"
        f_r16_st0_r1.write_text(json.dumps(ocr_r16_st0_r1, sort_keys=True), encoding="utf-8")
        f_r16_ks0_r2 = Path(td) / "r16_b1_ocr_ks0_r2.json"
        f_r16_ks0_r2.write_text(json.dumps(ocr_r16_ks0_r2, sort_keys=True), encoding="utf-8")
        f_r16_det0_r2 = Path(td) / "r16_b1_ocr_det0_r2.json"
        f_r16_det0_r2.write_text(json.dumps(ocr_r16_det0_r2, sort_keys=True), encoding="utf-8")

        r_85_st0_r2, rc_85_st0_r2 = evaluate_composite_lot_file(
            clin_r2_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
            nw08_ocr_json_path=f_r16_st0_r2,
        )
        r_85_st0_r1, rc_85_st0_r1 = evaluate_composite_lot_file(
            clin_r1_390_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
            nw08_ocr_json_path=f_r16_st0_r1,
        )
        r_85_ks0_r2, rc_85_ks0_r2 = evaluate_composite_lot_file(
            clin_r2_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
            nw08_ocr_json_path=f_r16_ks0_r2,
        )
        r_85_ks0_api = evaluate_composite_clinical_release(
            clin_r2_bundle,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
            nw08_ocr_record=ocr_r16_ks0_r2,
        )
        r_85_det0_r2, rc_85_det0_r2 = evaluate_composite_lot_file(
            clin_r2_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
            nw08_ocr_json_path=f_r16_det0_r2,
        )

        # Independent biological FAIL_HARD_STOP (adverse supplemental HCMV reactivation) + zero-SE
        # STUDENT_T_ESTIMATED_SE OCR MUST still exit 3 (`FAIL_HARD_STOP_COMPOSITE_RELEASE`) while
        # preserving OCR HOLD diagnostics (`HOLD_NW08_INFERENTIAL_MODEL_REQUIRES_POSITIVE_SE`)!
        g0v_clin_bio_fail = copy.deepcopy(g0v_clin)
        g0v_clin_bio_fail["gate0v_b_infectious_challenge"]["pathogens"]["hcmv"] = {
            "day28_latent_and_defective_genome_arm": {"reactivation_7d_outgrowth_pfu_ml": "2.5"}
        }
        g0v_clin_bio_fail["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_clin_bio_fail)
        clin_bio_fail_bundle = _make_composite_bundle(
            clin_lot_id,
            mcb_id,
            pv_lead,
            leg_clin,
            g0v_clin_bio_fail,
            nw08_route_id="R2_DZ40",
            nw08_measurement_evidence_sha256=clin_ev_sha,
            nw08_measurement_not_before_utc="2026-11-28T00:00:00Z",
        )
        clin_bio_fail_f = Path(td) / "r16_b1_clin_bio_fail_r2.json"
        clin_bio_fail_f.write_text(json.dumps(clin_bio_fail_bundle, sort_keys=True), encoding="utf-8")
        ocr_r16_bio_fail_st0 = v38.build_bound_nw08_ocr_record(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            route_id="R2_DZ40",
            lot_payload_sha256=clin_bio_fail_bundle["payload_sha256"],
            measured_ocr=1.097,
            uncertainty_se=0.0,
            ocr_uncertainty_model="STUDENT_T_ESTIMATED_SE",
            ocr_replicates_n=6,
            measurement_record_id="OCR-R16-B1-BIOFAIL-ST0",
            measurement_evidence_sha256=clin_ev_sha,
            measurement_timestamp_utc="2026-11-29T01:00:00Z",
        )
        f_r16_bio_fail_st0 = Path(td) / "r16_b1_ocr_bio_fail_st0.json"
        f_r16_bio_fail_st0.write_text(json.dumps(ocr_r16_bio_fail_st0, sort_keys=True), encoding="utf-8")
        r_85_bio_hs, rc_85_bio_hs = evaluate_composite_lot_file(
            clin_bio_fail_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
            nw08_ocr_json_path=f_r16_bio_fail_st0,
        )

        tok_pos_se = "HOLD_NW08_INFERENTIAL_MODEL_REQUIRES_POSITIVE_SE"
        ok_85 = bool(
            rc_85_st0_r2 == 2
            and r_85_st0_r2["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and r_85_st0_r2["release_authorizing"] is False
            and tok_pos_se in r_85_st0_r2["holds"]
            and (r_85_st0_r2.get("nw08_measured_ocr_dispatch_result") or {}).get("solver_executed") is False
            and rc_85_st0_r1 == 2
            and r_85_st0_r1["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and r_85_st0_r1["release_authorizing"] is False
            and tok_pos_se in r_85_st0_r1["holds"]
            and (r_85_st0_r1.get("nw08_measured_ocr_dispatch_result") or {}).get("solver_executed") is False
            and rc_85_ks0_r2 == 2
            and r_85_ks0_r2["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and r_85_ks0_r2["release_authorizing"] is False
            and tok_pos_se in r_85_ks0_r2["holds"]
            and (r_85_ks0_r2.get("nw08_measured_ocr_dispatch_result") or {}).get("solver_executed") is False
            and r_85_ks0_api["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and r_85_ks0_api["release_authorizing"] is False
            and tok_pos_se in r_85_ks0_api["holds"]
            and (r_85_ks0_api.get("nw08_measured_ocr_dispatch_result") or {}).get("solver_executed") is False
            and rc_85_det0_r2 == 0
            and r_85_det0_r2["composite_verdict"] == "PASS_COMPOSITE_CLINICAL_RELEASE"
            and r_85_det0_r2["release_authorizing"] is True
            and (r_85_det0_r2.get("nw08_measured_ocr_dispatch_result") or {}).get("ocr_uncertainty_model")
            == "ZERO_UNCERTAINTY_DETERMINISTIC_POINT"
            and rc_85_bio_hs == 3
            and r_85_bio_hs["composite_verdict"] == "FAIL_HARD_STOP_COMPOSITE_RELEASE"
            and r_85_bio_hs["release_authorizing"] is False
            and tok_pos_se in r_85_bio_hs["holds"]
            and (r_85_bio_hs.get("nw08_measured_ocr_dispatch_result") or {}).get("solver_executed") is False
            and rc_83_t6 == 3
            and r_83_t6["composite_verdict"] == "FAIL_HARD_STOP_COMPOSITE_RELEASE"
        )
        cases.append({
            "case": "r16_b1_coupled_zero_se_inferential_models_held_exit_2_det_pass_pos_se_fail_bio_hard_stop_exit_3",
            "expected_verdict": "HOLD_2_DET_PASS_0_BIO_FAIL_3",
            "actual_verdict": (
                f"{r_85_st0_r2['composite_verdict']}_{rc_85_st0_r2}__"
                f"{r_85_ks0_r2['composite_verdict']}_{rc_85_ks0_r2}__"
                f"{r_85_det0_r2['composite_verdict']}_{rc_85_det0_r2}__"
                f"{r_85_bio_hs['composite_verdict']}_{rc_85_bio_hs}"
            ),
            "operational_tier": r_85_st0_r2["operational_tier"],
            "legacy_passed": (r_85_st0_r2.get("legacy_result_summary") or {}).get("legacy_evaluator_passed"),
            "legacy_tier": (r_85_st0_r2.get("legacy_result_summary") or {}).get("lot_release_readiness_tier"),
            "legacy_resolved_pvid": (r_85_st0_r2.get("legacy_result_summary") or {}).get("resolved_product_variant_id"),
            "gate0v_passed": (r_85_st0_r2.get("gate0v_result_summary") or {}).get("gate0v_evaluator_passed"),
            "gate0v_verdict": (r_85_st0_r2.get("gate0v_result_summary") or {}).get("verdict"),
            "expected_token": tok_pos_se,
            "exit_code": rc_85_st0_r2 if ok_85 else -1,
            "hard_stops": r_85_bio_hs["hard_stops"][:2],
            "holds": r_85_st0_r2["holds"][:3],
            "passed": ok_85,
        })

        # ------------------------------------------------------------------
        # Round-17 Closure Regressions (R17-B1, R17-B2, R17-M1)
        # ------------------------------------------------------------------
        # 86. R17-B1 (a)-(e): Composite offline acceptance suite for mandatory sampling-unit
        #     reconciliation of ALL release-critical recovery calibrants and Day-28 negative controls!
        def _eval_r17_bank_variant(tag: str, mutator: Callable[[Dict[str, Any]], None]) -> Tuple[Dict[str, Any], int]:
            g0v_mut = copy.deepcopy(g0v_bank)
            mutator(g0v_mut)
            g0v_mut["payload_sha256"] = v38.compute_canonical_lot_sha256(g0v_mut)
            b_mut = _make_composite_bundle(bank_lot_id, mcb_id, pv_lead, leg_bank, g0v_mut)
            fp_mut = Path(td) / f"r17_b1_bank_{tag}.json"
            fp_mut.write_text(json.dumps(b_mut, sort_keys=True), encoding="utf-8")
            return evaluate_composite_lot_file(
                fp_mut,
                legacy_evaluator=leg_fn,
                gate0v_evaluator=g0v_fn,
                openislet_root=openislet_root,
            )

        r_86_a, rc_86_a = _eval_r17_bank_variant("pos_ctrl", lambda _p: None)
        r_86_b, rc_86_b = _eval_r17_bank_variant(
            "miss_stress_cal",
            lambda p: p["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["per_unit_counts"].pop("spike_calibrant", None),
        )
        r_86_c, rc_86_c = _eval_r17_bank_variant(
            "miss_d28_neg_ctrl",
            lambda p: p["gate0v_b_infectious_challenge"]["pathogens"]["cvb3"]["day28_persistence_by_lineage"]["alpha"].pop("uninfected_ctrl_per_unit_counts", None),
        )
        r_86_d, rc_86_d = _eval_r17_bank_variant(
            "miss_d28_cal",
            lambda p: p["gate0v_b_infectious_challenge"]["pathogens"]["hcmv"]["day28_persistence_by_lineage"]["plvap_iec"].pop("fragile_infected_spike_per_unit_counts", None),
        )

        def _mut_86_e(p: Dict[str, Any]) -> None:
            p["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["per_unit_counts"].pop("spike_calibrant", None)
            p["gate0v_b_infectious_challenge"]["pathogens"]["cvb3"]["day28_persistence_by_lineage"]["alpha"].pop("uninfected_ctrl_per_unit_counts", None)
            p["gate0v_b_infectious_challenge"]["pathogens"]["hcmv"]["day28_persistence_by_lineage"]["plvap_iec"].pop("fragile_infected_spike_per_unit_counts", None)
            p["gate0v_kill_stress_ap1903"]["active_or_persistent_cvb4_infection"]["beta"]["post_ap1903_viable_viral_pos_k"] = 1

        r_86_e, rc_86_e = _eval_r17_bank_variant("bio_hard_stop_with_missing_cal", _mut_86_e)

        g0v_86_a = r_86_a.get("gate0v_result_summary") or {}
        sb_86_a = g0v_86_a.get("sampling_unit_basis") or {}
        tok_part_mm = "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS"
        ok_86 = bool(
            rc_86_a == 0
            and r_86_a["composite_verdict"] == "PASS_COMPOSITE_BANK_QUALIFICATION"
            and g0v_86_a.get("exact_directional_confidence_certified") is True
            and sb_86_a.get("all_sampling_units_reconciled") is True
            and sb_86_a.get("estimand_partitions_checked") == 209
            and sb_86_a.get("estimand_partitions_reconciled") == 209
            and all(
                (
                    rc_x == 2
                    and r_x["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
                    and r_x["release_authorizing"] is False
                    and tok_part_mm in r_x["holds"]
                    and (r_x.get("gate0v_result_summary") or {}).get("exact_directional_confidence_certified") is False
                    and ((r_x.get("gate0v_result_summary") or {}).get("sampling_unit_basis") or {}).get("all_sampling_units_reconciled") is False
                    and ((r_x.get("gate0v_result_summary") or {}).get("sampling_unit_basis") or {}).get("estimand_partitions_reconciled") == 208
                )
                for r_x, rc_x in ((r_86_b, rc_86_b), (r_86_c, rc_86_c), (r_86_d, rc_86_d))
            )
            and rc_86_e == 3
            and r_86_e["composite_verdict"] == "FAIL_HARD_STOP_COMPOSITE_RELEASE"
            and r_86_e["release_authorizing"] is False
            and (r_86_e.get("gate0v_result_summary") or {}).get("exact_directional_confidence_certified") is False
            and ((r_86_e.get("gate0v_result_summary") or {}).get("sampling_unit_basis") or {}).get("all_sampling_units_reconciled") is False
            and len(r_86_e["hard_stops"]) >= 1
        )
        cases.append({
            "case": "r17_b1_composite_sampling_unit_reconciliation_calibrants_and_neg_ctrl_a_through_e",
            "expected_verdict": "PASS_0_HOLDS_2_HARD_STOP_3",
            "actual_verdict": (
                f"{r_86_a['composite_verdict']}_{rc_86_a}__"
                f"{r_86_b['composite_verdict']}_{rc_86_b}__"
                f"{r_86_c['composite_verdict']}_{rc_86_c}__"
                f"{r_86_d['composite_verdict']}_{rc_86_d}__"
                f"{r_86_e['composite_verdict']}_{rc_86_e}"
            ),
            "operational_tier": r_86_a["operational_tier"],
            "legacy_passed": (r_86_a.get("legacy_result_summary") or {}).get("legacy_evaluator_passed"),
            "legacy_tier": (r_86_a.get("legacy_result_summary") or {}).get("lot_release_readiness_tier"),
            "legacy_resolved_pvid": (r_86_a.get("legacy_result_summary") or {}).get("resolved_product_variant_id"),
            "gate0v_passed": g0v_86_a.get("gate0v_evaluator_passed"),
            "gate0v_verdict": g0v_86_a.get("verdict"),
            "checked_partitions": sb_86_a.get("estimand_partitions_checked"),
            "reconciled_partitions": sb_86_a.get("estimand_partitions_reconciled"),
            "expected_token": tok_part_mm,
            "exit_code": 0 if ok_86 else -1,
            "hard_stops": r_86_e["hard_stops"][:2],
            "holds": r_86_b["holds"][:3],
            "passed": ok_86,
        })

        # 87. R17-B2 + R17-M1: Coupled clinical release with Sol's exact sub-ULP positive-SE OCR
        #     record (`R2_DZ40, OCR=1.097, SE=1e-20, STUDENT_T_ESTIMATED_SE, n=6`) and KNOWN_SIGMA_NORMAL
        #     verifies strictly upward native solver scaling (`mult_f64 > 1.0`, `eff_ocr >= ocr_u95_dec`),
        #     rejects old under-covering `z=1.6448536269514722` (HOLD exit 2), AND confirms direct
        #     `dispatch_and_solve_nw08_measured_ocr` emits `qualification_scope` & `physical_qualification_complete=False`!
        from decimal import Decimal as _Decimal
        from fractions import Fraction as _Fraction

        ocr_r17_sub_ulp_t6 = v38.build_bound_nw08_ocr_record(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            route_id="R2_DZ40",
            lot_payload_sha256=clin_r2_bundle["payload_sha256"],
            measured_ocr=1.097,
            uncertainty_se=1e-20,
            ocr_uncertainty_model="STUDENT_T_ESTIMATED_SE",
            ocr_replicates_n=6,
            measurement_record_id="OCR-R17-B2-SUBULP-T6",
            measurement_evidence_sha256=clin_ev_sha,
            measurement_timestamp_utc="2026-11-29T01:00:00Z",
        )
        ocr_r17_old_z = v38.build_bound_nw08_ocr_record(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            route_id="R2_DZ40",
            lot_payload_sha256=clin_r2_bundle["payload_sha256"],
            measured_ocr=1.097,
            uncertainty_se=1e-20,
            z_one_sided_95=1.6448536269514722,
            ocr_uncertainty_model="KNOWN_SIGMA_NORMAL",
            ocr_uncertainty_provenance="calibrated_respirometer_known_sigma_cert_v1",
            measurement_record_id="OCR-R17-B2-OLDZ-REJECT",
            measurement_evidence_sha256=clin_ev_sha,
            measurement_timestamp_utc="2026-11-29T01:00:00Z",
        )
        ocr_r17_new_z = v38.build_bound_nw08_ocr_record(
            lot_id=clin_lot_id,
            mcb_id=mcb_id,
            product_variant_id=pv_lead,
            route_id="R2_DZ40",
            lot_payload_sha256=clin_r2_bundle["payload_sha256"],
            measured_ocr=1.097,
            uncertainty_se=1e-20,
            z_one_sided_95=v38.MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95,
            ocr_uncertainty_model="KNOWN_SIGMA_NORMAL",
            ocr_uncertainty_provenance="calibrated_respirometer_known_sigma_cert_v1",
            measurement_record_id="OCR-R17-B2-NEWZ-PASS",
            measurement_evidence_sha256=clin_ev_sha,
            measurement_timestamp_utc="2026-11-29T01:00:00Z",
        )
        f_r17_t6 = Path(td) / "r17_b2_ocr_sub_ulp_t6.json"
        f_r17_t6.write_text(json.dumps(ocr_r17_sub_ulp_t6, sort_keys=True), encoding="utf-8")
        f_r17_oldz = Path(td) / "r17_b2_ocr_old_z.json"
        f_r17_oldz.write_text(json.dumps(ocr_r17_old_z, sort_keys=True), encoding="utf-8")
        f_r17_newz = Path(td) / "r17_b2_ocr_new_z.json"
        f_r17_newz.write_text(json.dumps(ocr_r17_new_z, sort_keys=True), encoding="utf-8")

        r_87_t6, rc_87_t6 = evaluate_composite_lot_file(
            clin_r2_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
            nw08_ocr_json_path=f_r17_t6,
        )
        r_87_oldz, rc_87_oldz = evaluate_composite_lot_file(
            clin_r2_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
            nw08_ocr_json_path=f_r17_oldz,
        )
        r_87_newz, rc_87_newz = evaluate_composite_lot_file(
            clin_r2_f,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=trusted_store,
            openislet_root=openislet_root,
            nw08_ocr_json_path=f_r17_newz,
        )
        direct_disp_r17_fast = v38.dispatch_and_solve_nw08_measured_ocr(
            "R2_DZ40",
            1.097,
            0.0,
            openislet_root=openislet_root,
            ocr_uncertainty_model="ZERO_UNCERTAINTY_DETERMINISTIC_POINT",
        )
        direct_disp_r17_sub = v38.dispatch_and_solve_nw08_measured_ocr(
            "R2_DZ40",
            1.097,
            1e-20,
            openislet_root=openislet_root,
            ocr_uncertainty_model="STUDENT_T_ESTIMATED_SE",
            ocr_degrees_of_freedom=5,
        )
        nw_87_t6 = r_87_t6.get("nw08_measured_ocr_dispatch_result") or {}
        nw_87_newz = r_87_newz.get("nw08_measured_ocr_dispatch_result") or {}
        u95_87_t6 = _Decimal(str(nw_87_t6.get("solved_at_vascular_ocr_u95_exact_dec")))
        u95_87_newz = _Decimal(str(nw_87_newz.get("solved_at_vascular_ocr_u95_exact_dec")))
        ok_87 = bool(
            rc_87_t6 == 0
            and r_87_t6["composite_verdict"] == "PASS_COMPOSITE_CLINICAL_RELEASE"
            and r_87_t6["release_authorizing"] is True
            and nw_87_t6.get("solver_executed") is True
            and float(nw_87_t6.get("native_solver_vasc_scale_float64")) > 1.0
            and _Fraction(float(nw_87_t6.get("native_solver_vasc_scale_float64"))) >= _Fraction(u95_87_t6) / _Fraction(_Decimal("1.097"))
            and _Fraction(float(nw_87_t6.get("native_solver_effective_vascular_ocr_float64"))) >= _Fraction(u95_87_t6)
            and rc_87_oldz == 2
            and r_87_oldz["composite_verdict"] == "HOLD_COMPOSITE_RELEASE"
            and r_87_oldz["release_authorizing"] is False
            and (r_87_oldz.get("nw08_measured_ocr_dispatch_result") or {}).get("solver_executed") is False
            and rc_87_newz == 0
            and r_87_newz["composite_verdict"] == "PASS_COMPOSITE_CLINICAL_RELEASE"
            and float(nw_87_newz.get("native_solver_vasc_scale_float64")) > 1.0
            and _Fraction(float(nw_87_newz.get("native_solver_effective_vascular_ocr_float64"))) >= _Fraction(u95_87_newz)
            and direct_disp_r17_fast.get("qualification_scope") == v38.QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL
            and direct_disp_r17_fast.get("physical_qualification_complete") is False
            and direct_disp_r17_sub.get("qualification_scope") == v38.QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL
            and direct_disp_r17_sub.get("physical_qualification_complete") is False
            and float(direct_disp_r17_sub.get("native_solver_vasc_scale_float64")) > 1.0
        )
        cases.append({
            "case": "r17_b2_m1_coupled_sub_ulp_upward_solver_scale_old_z_held_and_direct_dispatch_scope",
            "expected_verdict": "PASS_0_OLDZ_HOLD_2_NEWZ_PASS_0",
            "actual_verdict": (
                f"{r_87_t6['composite_verdict']}_{rc_87_t6}__"
                f"{r_87_oldz['composite_verdict']}_{rc_87_oldz}__"
                f"{r_87_newz['composite_verdict']}_{rc_87_newz}"
            ),
            "operational_tier": r_87_t6["operational_tier"],
            "legacy_passed": (r_87_t6.get("legacy_result_summary") or {}).get("legacy_evaluator_passed"),
            "legacy_tier": (r_87_t6.get("legacy_result_summary") or {}).get("lot_release_readiness_tier"),
            "legacy_resolved_pvid": (r_87_t6.get("legacy_result_summary") or {}).get("resolved_product_variant_id"),
            "gate0v_passed": (r_87_t6.get("gate0v_result_summary") or {}).get("gate0v_evaluator_passed"),
            "gate0v_verdict": (r_87_t6.get("gate0v_result_summary") or {}).get("verdict"),
            "sub_ulp_t6_native_scale_f64": nw_87_t6.get("native_solver_vasc_scale_float64"),
            "sub_ulp_t6_effective_ocr_f64": nw_87_t6.get("native_solver_effective_vascular_ocr_float64"),
            "expected_token": "HOLD_NW08_OCR_INVALID_PARAMETERS",
            "exit_code": 0 if ok_87 else -1,
            "hard_stops": [],
            "holds": r_87_oldz["holds"][:3],
            "passed": ok_87,
        })

    wc_sha_after = hashlib.sha256(wc_path.read_bytes()).hexdigest()
    passed_n = sum(1 for c in cases if c["passed"])
    return {
        "schema_version": "0.8.0-exp031-composite-release-v16-r17",
        "legacy_wetlab_contract_sha256_before": wc_sha_before,
        "legacy_wetlab_contract_sha256_after": wc_sha_after,
        "legacy_wetlab_contract_zero_byte_untouched": wc_sha_before == wc_sha_after,
        "total_cases": len(cases),
        "passed_cases": passed_n,
        "all_passed": bool(passed_n == len(cases) and wc_sha_before == wc_sha_after),
        "cases": cases,
    }


# ---------------------------------------------------------------------------
# Wave-6 Governed Gate 0V Producer Receipt Adapters (v2_round8_governed; Audit R7-06 / R7-07 / R7-12)
# ---------------------------------------------------------------------------

from collections.abc import Mapping as _AbcMapping, Sequence as _AbcSequence
import math as _math_g0v
import os as _os_g0v
import re as _re_g0v

_GY030_REQUIRED_5_LINEAGES = frozenset({"alpha", "beta", "delta", "pericyte", "plvap_iec"})
_FORBIDDEN_CALLER_PHYSICAL_ASSAY_KEYS = frozenset({
    "dossier_type",
    "evidence_tier",
    "physical_qualification_complete",
    "whole_graft_stressed_tested",
    "lineages_verified",
    "estimand1_u_esc",
    "estimand2_u_cond",
    "caspase_fold_activity",
    "five_virus_max_fold_vs_wt",
    "nhs20_cdc_c5b9_u95_pct",
    "qa_decision",
    "gate0v_assay_payload",
})
_PHYSICAL_ASSAY_NUMERIC_FIELDS = (
    "estimand1_u_esc",
    "estimand2_u_cond",
    "caspase_fold_activity",
    "five_virus_max_fold_vs_wt",
    "nhs20_cdc_c5b9_u95_pct",
)
_MAX_SAFE_INT_ABS_V2_ROUND8 = 10**300
_SAFE_STORE_ID_RE_V2_ROUND8 = _re_g0v.compile(r"^[A-Za-z0-9._:-]{1,128}$")
_QA_ISSUER_REGISTRY_SCHEMA_V2_ROUND8 = "openislet_gate0v_qa_issuer_registry_v1"
_GATE0V_TRUST_CONFIG_SCHEMA_V2_ROUND9 = "openislet_gate0v_governed_trust_config_v1"
_GATE0V_TRUST_CONFIG_AUTHORITY_ID_V2_ROUND9 = "OPENISLET_GATE0V_OWNER_TRUST_ANCHOR_V1"
_GATE0V_TRUST_CONFIG_REL_PATH_V2_ROUND9 = Path("data") / "protocols" / "gate0v_governed_trust_config.json"
_PINNED_GATE0V_TRUST_CONFIG_SHA256 = "72efc0c671bd505b98f562c97e20f8048ddf749f674959b12f8745893d5b1a2d"
_GATE0V_INSTALLATION_IDENTITY_SCHEMA_V2_ROUND10 = "openislet_gate0v_installation_identity_v1"
_GATE0V_INSTALLATION_IDENTITY_AUTHORITY_ID_V2_ROUND10 = "OPENISLET_GOVERNED_GATE0V_OWNER_V1"
_GATE0V_INSTALLATION_IDENTITY_REL_PATH_V2_ROUND10 = Path("data") / "protocols" / "gate0v_installation_identity.json"
_PINNED_GATE0V_INSTALLATION_IDENTITY_SHA256 = "bccd641aaa535470fea13fb04e9dba40f4ca09c3be8594112bd6fe16eff89751"
_SYNTHETIC_ISSUER_FORBIDDEN_MARKERS_V2_ROUND10 = ("SYNTHETIC", "FIXTURE", "MOCK", "PLUMBING")
_FORBIDDEN_MODELED_SCOPES_V2_ROUND8 = frozenset({
    "MODELED_COMPUTATIONAL_ONLY",
    QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
})


def _safe_str_v2_round8(val: Any) -> str:
    return val if isinstance(val, str) else ""


def _is_safe_store_id_v2_round8(val: Any) -> bool:
    return (
        isinstance(val, str)
        and val == val.strip()
        and bool(_SAFE_STORE_ID_RE_V2_ROUND8.match(val))
        and ".." not in val
    )


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


def _safe_finite_number_v2_round8(val: Any) -> Tuple[bool, float | None, str | None]:
    """Audit R7-12: Typed value check + guarded finite float conversion (never raises TypeError or OverflowError)."""
    if isinstance(val, bool) or not isinstance(val, (int, float)):
        return False, None, f"NON_NUMERIC_VALUE:{type(val).__name__}"
    if isinstance(val, int) and abs(val) > _MAX_SAFE_INT_ABS_V2_ROUND8:
        return False, None, "INTEGER_OVERFLOW"
    try:
        fv = float(val)
    except (OverflowError, ValueError, TypeError):
        return False, None, "INTEGER_OVERFLOW"
    if not _math_g0v.isfinite(fv):
        return False, None, "NON_FINITE_NUMBER"
    return True, fv, None


def _check_json_structure_v2_round8(obj: Any, depth: int = 0) -> Tuple[bool, str | None]:
    if depth > MAX_JSON_NESTING_DEPTH:
        return False, "JSON_MAX_DEPTH_EXCEEDED"
    if obj is None or isinstance(obj, (bool, str, int)):
        return True, None
    if isinstance(obj, float):
        return (_math_g0v.isfinite(obj), None if _math_g0v.isfinite(obj) else "NON_FINITE_FLOAT")
    if isinstance(obj, _AbcMapping):
        for k, v in obj.items():
            if not isinstance(k, str):
                return False, f"NON_STRING_DICT_KEY:{type(k).__name__}"
            ok, err = _check_json_structure_v2_round8(v, depth + 1)
            if not ok:
                return False, err
        return True, None
    if isinstance(obj, (list, tuple)):
        for item in obj:
            ok, err = _check_json_structure_v2_round8(item, depth + 1)
            if not ok:
                return False, err
        return True, None
    return False, f"UNSUPPORTED_JSON_TYPE:{type(obj).__name__}"


def _safe_canonical_sha256_v2_round8(obj: Any) -> str | None:
    ok, _err = _check_json_structure_v2_round8(obj, 0)
    if not ok:
        return None
    try:
        canon = json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False)
        return hashlib.sha256(canon.encode("utf-8")).hexdigest()
    except (TypeError, ValueError, OverflowError, RecursionError):
        return None


def _canonical_sha256_v2_round5(obj: Any) -> str:
    digest = _safe_canonical_sha256_v2_round8(obj)
    if digest is None:
        raise ValueError("Cannot compute canonical SHA-256 for malformed/non-finite/non-JSON object")
    return digest


def _unfreeze_owner_obj_v2_round7(obj: Any) -> Any:
    if isinstance(obj, _AbcMapping):
        return {k: _unfreeze_owner_obj_v2_round7(v) for k, v in obj.items()}
    if isinstance(obj, (tuple, list)):
        return [_unfreeze_owner_obj_v2_round7(v) for v in obj]
    return obj


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


def _reject_json_constant_v2_round8(tok: str) -> Any:
    raise ValueError(f"Non-finite JSON constant forbidden: {tok!r}")


def _safe_load_governed_json_v2_round8(path: Path) -> Tuple[Any, str | None]:
    """Load an immutable on-disk governed JSON file cleanly without symlinks, duplicate keys, or uncaught exceptions."""
    try:
        if path.is_symlink():
            return None, "SYMLINK_FORBIDDEN"
        if not path.is_file():
            return None, "FILE_NOT_FOUND"
        raw_text = path.read_text(encoding="utf-8")
        obj = json.loads(
            raw_text,
            object_pairs_hook=_strict_no_dup_pairs_v2_round8,
            parse_constant=_reject_json_constant_v2_round8,
        )
        ok, err = _check_json_structure_v2_round8(obj, 0)
        if not ok:
            return None, err or "MALFORMED_JSON_STRUCTURE"
        return obj, None
    except (OSError, UnicodeDecodeError, ValueError, TypeError, OverflowError, RecursionError) as exc:
        return None, f"MALFORMED_JSON:{type(exc).__name__}"


def _safe_validate_5_lineages_v2_round8(lineages: Any) -> Tuple[bool, str | None, bool]:
    """Return (ok, error_code, is_malformed_type). Never calls set() on unhashable nested dicts/lists."""
    if not isinstance(lineages, list):
        return False, f"LINEAGES_NOT_LIST:{type(lineages).__name__}", True
    for item in lineages:
        if not isinstance(item, str):
            return False, f"LINEAGES_NON_STRING_ENTRY:{type(item).__name__}", True
    if len(lineages) != len(set(lineages)) or set(lineages) != _GY030_REQUIRED_5_LINEAGES:
        return False, "DOSSIER_5_LINEAGES_INCOMPLETE", False
    return True, None, False


def _seal_gate0v_receipt_v2_round5(body: Dict[str, Any]) -> Dict[str, Any]:
    rec = copy.deepcopy({k: v for k, v in body.items() if k not in ("archive_sha256", "record_sha256")})
    rec["archive_sha256"] = _canonical_sha256_v2_round5(rec)
    return rec


def seal_owner_physical_dossier_record_v2_round7(body: _AbcMapping[str, Any]) -> Dict[str, Any]:
    """Seal an owner-governed physical Gate 0V wet-lab dossier with its immutable archive_sha256."""
    rec = _unfreeze_owner_obj_v2_round7({k: v for k, v in body.items() if k not in ("archive_sha256", "record_sha256")})
    rec["archive_sha256"] = _canonical_sha256_v2_round5(rec)
    return rec


def seal_owner_qa_signoff_record_v2_round7(body: _AbcMapping[str, Any]) -> Dict[str, Any]:
    """Seal an independent QA sign-off record bound to an archived physical Gate 0V dossier."""
    rec = _unfreeze_owner_obj_v2_round7({k: v for k, v in body.items() if k not in ("archive_sha256", "record_sha256")})
    rec["archive_sha256"] = _canonical_sha256_v2_round5(rec)
    return rec


def seal_owner_qa_issuer_registry_v2_round8(body: _AbcMapping[str, Any]) -> Dict[str, Any]:
    """Seal an independent QA issuer authority registry with its immutable registry_sha256."""
    rec = _unfreeze_owner_obj_v2_round7({k: v for k, v in body.items() if k != "registry_sha256"})
    rec["registry_sha256"] = _canonical_sha256_v2_round5(rec)
    return rec


def write_governed_gate0v_store_v2_round8(
    store_root: Path | str,
    *,
    qa_issuer_registry: _AbcMapping[str, Any] | None = None,
    dossiers: _AbcSequence[_AbcMapping[str, Any]] = (),
    qa_signoffs: _AbcSequence[_AbcMapping[str, Any]] = (),
) -> Path:
    """Populate a separately governed on-disk Gate 0V evidence store layout:
      <root>/qa_issuer_registry.json
      <root>/physical_dossiers/<dossier_id>.json
      <root>/qa_signoffs/<qa_signoff_id>.json
      <root>/issued_receipts/   (single canonical key <archive_sha256>.json written ONLY on PASS)"""
    root = Path(store_root)
    d_dir = root / "physical_dossiers"
    q_dir = root / "qa_signoffs"
    i_dir = root / "issued_receipts"
    d_dir.mkdir(parents=True, exist_ok=True)
    q_dir.mkdir(parents=True, exist_ok=True)
    i_dir.mkdir(parents=True, exist_ok=True)

    if qa_issuer_registry is not None:
        reg_plain = _unfreeze_owner_obj_v2_round7(qa_issuer_registry)
        (root / "qa_issuer_registry.json").write_text(
            json.dumps(reg_plain, indent=2, sort_keys=True, ensure_ascii=False, allow_nan=False) + "\n",
            encoding="utf-8",
        )
    for raw_d in dossiers:
        d_plain = _unfreeze_owner_obj_v2_round7(raw_d)
        did = d_plain.get("dossier_id")
        if not _is_safe_store_id_v2_round8(did):
            raise ValueError(f"Unsafe dossier_id for governed store write: {did!r}")
        (d_dir / f"{did}.json").write_text(
            json.dumps(d_plain, indent=2, sort_keys=True, ensure_ascii=False, allow_nan=False) + "\n",
            encoding="utf-8",
        )
    for raw_q in qa_signoffs:
        q_plain = _unfreeze_owner_obj_v2_round7(raw_q)
        qid = q_plain.get("qa_signoff_id")
        if not _is_safe_store_id_v2_round8(qid):
            raise ValueError(f"Unsafe qa_signoff_id for governed store write: {qid!r}")
        (q_dir / f"{qid}.json").write_text(
            json.dumps(q_plain, indent=2, sort_keys=True, ensure_ascii=False, allow_nan=False) + "\n",
            encoding="utf-8",
        )
    return root


def build_gate0v_installation_identity_v2_round10(
    *,
    installation_id: str,
    authorized_qa_issuer_registry_sha256: str,
    provenance_mode: str = "OWNER_PROVISIONED_PRODUCTION_INSTALLATION",
    owner_authority_id: str = _GATE0V_INSTALLATION_IDENTITY_AUTHORITY_ID_V2_ROUND10,
) -> Dict[str, Any]:
    """Audit R9-03: Build separate installation identity record binding an authorized OpenIslet
    checkout independently of artifact relative paths."""
    body: Dict[str, Any] = {
        "schema_version": _GATE0V_INSTALLATION_IDENTITY_SCHEMA_V2_ROUND10,
        "installation_id": str(installation_id),
        "owner_authority_id": str(owner_authority_id),
        "provenance_mode": str(provenance_mode),
        "authorized_qa_issuer_registry_sha256": str(authorized_qa_issuer_registry_sha256),
    }
    body["installation_identity_sha256"] = _canonical_sha256_v2_round5(body)
    return body


def build_gate0v_governed_trust_config_v2_round9(
    *,
    qa_issuer_registry_sha256: str,
    canonical_arm_manifest_sha256: str,
    installation_id: str,
    installation_identity_sha256: str,
    installation_identity_path: str = "data/protocols/gate0v_installation_identity.json",
    provenance_mode: str = "OWNER_PROVISIONED_PRODUCTION",
    authorized_store_root: str = "data/governed_gate0v_store",
    canonical_arm_manifest_path: str = "data/protocols/wave6_canonical_arm_manifest.json",
) -> Dict[str, Any]:
    """Audit R8-03 & Audit R9-03: Build owner-configured Gate 0V trust anchor using strictly repo-relative
    paths and pinning qa_issuer_registry.json, wave6_canonical_arm_manifest.json, AND separate
    gate0v_installation_identity.json raw SHA-256 + installation_id."""
    body: Dict[str, Any] = {
        "schema_version": _GATE0V_TRUST_CONFIG_SCHEMA_V2_ROUND9,
        "owner_authority_id": _GATE0V_TRUST_CONFIG_AUTHORITY_ID_V2_ROUND9,
        "provenance_mode": str(provenance_mode),
        "installation_id": str(installation_id),
        "installation_identity_path": str(installation_identity_path),
        "installation_identity_sha256": str(installation_identity_sha256),
        "authorized_store_root": str(authorized_store_root),
        "canonical_arm_manifest_path": str(canonical_arm_manifest_path),
        "qa_issuer_registry_sha256": str(qa_issuer_registry_sha256),
        "canonical_arm_manifest_sha256": str(canonical_arm_manifest_sha256),
    }
    body["trust_config_sha256"] = _canonical_sha256_v2_round5(body)
    return body


def _is_safe_repo_rel_path_v2_round9(rel_str: Any) -> bool:
    if not isinstance(rel_str, str) or not rel_str.strip() or rel_str != rel_str.strip():
        return False
    p = Path(rel_str)
    if p.is_absolute() or ".." in p.parts:
        return False
    return True


def _load_and_verify_owner_trust_config_v2_round9(
    resolved_root: Path,
) -> Tuple[Dict[str, Any] | None, str | None]:
    """Audit R8-03 & Audit R9-03: Verify BOTH owner-configured `<repo_root>/data/protocols/gate0v_governed_trust_config.json`
    against `_PINNED_GATE0V_TRUST_CONFIG_SHA256` AND separate `<repo_root>/data/protocols/gate0v_installation_identity.json`
    against `_PINNED_GATE0V_INSTALLATION_IDENTITY_SHA256`, binding installation_id and authorized QA issuer registry."""
    if not _is_safe_sha256_v2_round8(_PINNED_GATE0V_TRUST_CONFIG_SHA256):
        return None, "TRUST_CONFIG_OWNER_PIN_NOT_CONFIGURED"
    if not _is_safe_sha256_v2_round8(_PINNED_GATE0V_INSTALLATION_IDENTITY_SHA256):
        return None, "INSTALLATION_IDENTITY::INSTALLATION_IDENTITY_OWNER_PIN_NOT_CONFIGURED"
    cfg_path = resolved_root / _GATE0V_TRUST_CONFIG_REL_PATH_V2_ROUND9
    if cfg_path.is_symlink():
        return None, "TRUST_CONFIG_SYMLINK_FORBIDDEN"
    if not cfg_path.is_file():
        return None, "MISSING_OWNER_TRUST_CONFIG"
    try:
        raw_bytes = cfg_path.read_bytes()
    except OSError as exc:
        return None, f"TRUST_CONFIG_READ_ERROR:{type(exc).__name__}"
    raw_sha = hashlib.sha256(raw_bytes).hexdigest()
    if raw_sha != _PINNED_GATE0V_TRUST_CONFIG_SHA256:
        return None, f"TRUST_CONFIG_OWNER_PIN_MISMATCH:{raw_sha}!={_PINNED_GATE0V_TRUST_CONFIG_SHA256}"
    try:
        cfg_obj = json.loads(
            raw_bytes.decode("utf-8"),
            object_pairs_hook=_strict_no_dup_pairs_v2_round8,
            parse_constant=_reject_json_constant_v2_round8,
        )
    except (UnicodeDecodeError, ValueError, TypeError) as exc:
        return None, f"TRUST_CONFIG_MALFORMED_JSON:{type(exc).__name__}"
    if not isinstance(cfg_obj, dict):
        return None, "TRUST_CONFIG_NOT_MAPPING"
    if cfg_obj.get("schema_version") != _GATE0V_TRUST_CONFIG_SCHEMA_V2_ROUND9:
        return None, "TRUST_CONFIG_SCHEMA_INVALID"
    if cfg_obj.get("owner_authority_id") != _GATE0V_TRUST_CONFIG_AUTHORITY_ID_V2_ROUND9:
        return None, "TRUST_CONFIG_AUTHORITY_INVALID"
    embedded_sha = cfg_obj.get("trust_config_sha256")
    recomp_sha = _safe_canonical_sha256_v2_round8({k: v for k, v in cfg_obj.items() if k != "trust_config_sha256"})
    if not _is_safe_sha256_v2_round8(embedded_sha) or recomp_sha != embedded_sha:
        return None, "TRUST_CONFIG_EMBEDDED_SHA256_MISMATCH"
    rel_store = cfg_obj.get("authorized_store_root")
    rel_manifest = cfg_obj.get("canonical_arm_manifest_path")
    rel_inst_id = cfg_obj.get("installation_identity_path")
    if (
        not _is_safe_repo_rel_path_v2_round9(rel_store)
        or not _is_safe_repo_rel_path_v2_round9(rel_manifest)
        or not _is_safe_repo_rel_path_v2_round9(rel_inst_id)
    ):
        return None, "TRUST_CONFIG_UNSAFE_RELATIVE_PATHS"
    reg_pin = cfg_obj.get("qa_issuer_registry_sha256")
    man_pin = cfg_obj.get("canonical_arm_manifest_sha256")
    inst_pin = cfg_obj.get("installation_identity_sha256")
    expected_inst_id = cfg_obj.get("installation_id")
    if (
        not _is_safe_sha256_v2_round8(reg_pin)
        or not _is_safe_sha256_v2_round8(man_pin)
        or not _is_safe_sha256_v2_round8(inst_pin)
        or not _is_safe_store_id_v2_round8(expected_inst_id)
    ):
        return None, "TRUST_CONFIG_INVALID_PIN_DIGESTS"
    root_res = resolved_root.resolve()
    store_raw = resolved_root / rel_store
    manifest_raw = resolved_root / rel_manifest
    inst_raw = resolved_root / rel_inst_id
    store_res = store_raw.resolve()
    manifest_res = manifest_raw.resolve()
    try:
        store_res.relative_to(root_res)
        manifest_res.relative_to(root_res)
    except ValueError:
        return None, "TRUST_CONFIG_PATH_ESCAPES_REPO_ROOT"

    # Audit R9-03: Separate installation identity file verification (check symlink BEFORE resolve!)
    if inst_raw.is_symlink():
        return None, "INSTALLATION_IDENTITY::INSTALLATION_IDENTITY_SYMLINK_FORBIDDEN"
    inst_res = inst_raw.resolve()
    try:
        inst_res.relative_to(root_res)
    except ValueError:
        return None, "INSTALLATION_IDENTITY::PATH_ESCAPES_REPO_ROOT"
    expected_inst_default = (resolved_root / _GATE0V_INSTALLATION_IDENTITY_REL_PATH_V2_ROUND10).resolve()
    if inst_res != expected_inst_default:
        return None, "INSTALLATION_IDENTITY::INSTALLATION_IDENTITY_PATH_MISMATCH"
    if not inst_raw.is_file():
        return None, "INSTALLATION_IDENTITY::MISSING_INSTALLATION_IDENTITY"
    try:
        inst_raw_bytes = inst_raw.read_bytes()
    except OSError as exc:
        return None, f"INSTALLATION_IDENTITY::READ_ERROR:{type(exc).__name__}"
    inst_raw_sha = hashlib.sha256(inst_raw_bytes).hexdigest()
    if inst_raw_sha != _PINNED_GATE0V_INSTALLATION_IDENTITY_SHA256:
        return None, f"INSTALLATION_IDENTITY::COMPILED_PIN_MISMATCH:{inst_raw_sha}!={_PINNED_GATE0V_INSTALLATION_IDENTITY_SHA256}"
    if inst_raw_sha != inst_pin:
        return None, f"INSTALLATION_IDENTITY::TRUST_CONFIG_PIN_MISMATCH:{inst_raw_sha}!={inst_pin}"
    try:
        inst_obj = json.loads(
            inst_raw_bytes.decode("utf-8"),
            object_pairs_hook=_strict_no_dup_pairs_v2_round8,
            parse_constant=_reject_json_constant_v2_round8,
        )
    except (UnicodeDecodeError, ValueError, TypeError) as exc:
        return None, f"INSTALLATION_IDENTITY::MALFORMED_JSON:{type(exc).__name__}"
    if not isinstance(inst_obj, dict):
        return None, "INSTALLATION_IDENTITY::NOT_MAPPING"
    if inst_obj.get("schema_version") != _GATE0V_INSTALLATION_IDENTITY_SCHEMA_V2_ROUND10:
        return None, "INSTALLATION_IDENTITY::SCHEMA_INVALID"
    if inst_obj.get("owner_authority_id") != _GATE0V_INSTALLATION_IDENTITY_AUTHORITY_ID_V2_ROUND10:
        return None, "INSTALLATION_IDENTITY::OWNER_AUTHORITY_INVALID"
    inst_embedded_sha = inst_obj.get("installation_identity_sha256")
    inst_recomp_sha = _safe_canonical_sha256_v2_round8(
        {k: v for k, v in inst_obj.items() if k != "installation_identity_sha256"}
    )
    if not _is_safe_sha256_v2_round8(inst_embedded_sha) or inst_recomp_sha != inst_embedded_sha:
        return None, "INSTALLATION_IDENTITY::EMBEDDED_SHA256_MISMATCH"
    if inst_obj.get("installation_id") != expected_inst_id:
        return None, f"INSTALLATION_IDENTITY::INSTALLATION_ID_MISMATCH:{inst_obj.get('installation_id')!r}!={expected_inst_id!r}"
    if inst_obj.get("authorized_qa_issuer_registry_sha256") != reg_pin:
        return None, (
            f"INSTALLATION_IDENTITY::AUTHORIZED_REGISTRY_SHA_DISAGREEMENT:"
            f"{inst_obj.get('authorized_qa_issuer_registry_sha256')!r}!={reg_pin!r}"
        )

    return {
        "config": cfg_obj,
        "config_sha256": raw_sha,
        "installation_identity": inst_obj,
        "installation_id": str(expected_inst_id),
        "installation_identity_sha256": inst_raw_sha,
        "provenance_mode": str(cfg_obj.get("provenance_mode") or ""),
        "installation_provenance_mode": str(inst_obj.get("provenance_mode") or ""),
        "authorized_store_raw_path": store_raw,
        "authorized_store_resolved": store_res,
        "canonical_manifest_raw_path": manifest_raw,
        "canonical_manifest_resolved": manifest_res,
        "qa_issuer_registry_sha256": str(reg_pin),
        "canonical_arm_manifest_sha256": str(man_pin),
    }, None


def _resolve_governed_manifest_and_arm_v2_round8(
    *,
    arm_id: Any,
    canonical_manifest_path: Path | str | None,
    openislet_root: Path | None,
) -> Tuple[Dict[str, Any] | None, str | None]:
    """Derive canonical_arm_manifest_sha256 STRICTLY from governed on-disk manifest bytes (Audit R7-07)."""
    resolved_root = _resolve_openislet_root(openislet_root)
    if canonical_manifest_path is not None:
        if not isinstance(canonical_manifest_path, (Path, str)):
            return None, "MALFORMED_CANONICAL_MANIFEST_PATH"
        mpath = Path(canonical_manifest_path)
    else:
        mpath = resolved_root / "data" / "protocols" / "wave6_canonical_arm_manifest.json"
    if mpath.is_symlink():
        return None, "CANONICAL_MANIFEST_SYMLINK_FORBIDDEN"
    if not mpath.is_file():
        return None, "CANONICAL_MANIFEST_UNAVAILABLE"
    try:
        raw_bytes = mpath.read_bytes()
        manifest_sha = hashlib.sha256(raw_bytes).hexdigest()
        manifest_obj = json.loads(
            raw_bytes.decode("utf-8"),
            object_pairs_hook=_strict_no_dup_pairs_v2_round8,
            parse_constant=_reject_json_constant_v2_round8,
        )
    except (OSError, UnicodeDecodeError, ValueError, TypeError):
        return None, "CANONICAL_MANIFEST_MALFORMED_JSON"
    if not isinstance(manifest_obj, dict) or not isinstance(manifest_obj.get("arms"), dict):
        return None, "CANONICAL_MANIFEST_INVALID_SCHEMA"
    if not isinstance(arm_id, str) or arm_id not in manifest_obj["arms"]:
        return None, "UNKNOWN_WAVE6_ARM_ID"
    arm_cfg = manifest_obj["arms"][arm_id]
    if not isinstance(arm_cfg, dict) or not isinstance(arm_cfg.get("product_id"), str) or not isinstance(arm_cfg.get("cell_origin"), str):
        return None, "CANONICAL_MANIFEST_MALFORMED_ARM_ROW"
    product_id = str(arm_cfg["product_id"])
    bank_origin = str(arm_cfg["cell_origin"])
    v38 = _get_v38_module()
    reg_rec = v38.resolve_canonical_product_variant(product_id, openislet_root=resolved_root)
    if reg_rec is None:
        return None, f"OWNER_REGISTRY_UNRESOLVED_PRODUCT:{product_id}"
    tier_family = str(reg_rec["product_tier_family"])
    expected_tier_family = "AUTOLOGOUS_D1B_AUTO_C" if bank_origin == "autologous_hiPSC" else "ALLOGENEIC_MCB_BANKED"
    if tier_family != expected_tier_family:
        return None, f"OWNER_REGISTRY_TIER_FAMILY_DISAGREEMENT:{tier_family}!={expected_tier_family}"
    return {
        "manifest": manifest_obj,
        "manifest_sha256": manifest_sha,
        "manifest_path": str(mpath),
        "product_id": product_id,
        "bank_origin": bank_origin,
        "tier_family": tier_family,
        "canonical_product_def": reg_rec,
        "resolved_root": resolved_root,
    }, None


def _make_canonical_gate0v_record_id_v2_round9(prefix: str, product_id: str, lot_id: str) -> str:
    """Build a strict <=64-char canonical ASCII record_id matching ^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$."""
    p_clean = product_id or "UNKNOWN_PRODUCT"
    l_clean = lot_id or "UNKNOWN_LOT"
    cand = f"{prefix}:{p_clean}:{l_clean}"
    if len(cand) <= 64 and _re_g0v.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,63}", cand):
        return cand
    short_h = hashlib.sha256(f"{prefix}:{p_clean}:{l_clean}".encode("utf-8")).hexdigest()[:16]
    pref_clean = _re_g0v.sub(r"[^A-Za-z0-9._:-]+", "-", prefix).strip("-._:") or "G0V"
    return f"{pref_clean[:24]}:{short_h}"


def _make_fail_closed_gate0v_custody_receipt_v2_round7(
    *,
    decision: str,
    authority_scope: str,
    evidence_tier: str,
    record_prefix: str,
    product_id: str,
    lot_id: str,
    bank_id: str,
    bank_origin: str,
    manifest_sha: str,
    construct_manifest_sha256: str,
    dossier_id: str | None,
    qa_signoff_id: str | None,
    custody_failure_reasons: List[str],
    extra_fields: Dict[str, Any] | None = None,
) -> Dict[str, Any]:
    body: Dict[str, Any] = {
        "schema_revision": "v2_round5_unified",
        "record_id": _make_canonical_gate0v_record_id_v2_round9(record_prefix, product_id, lot_id),
        "gate_source": "GATE-0V",
        "product_id": product_id or "",
        "lot_id": lot_id or "",
        "bank_id": bank_id or "",
        "bank_origin": bank_origin or "",
        "canonical_arm_manifest_sha256": manifest_sha or "",
        "construct_manifest_sha256": construct_manifest_sha256 or "",
        "evidence_tier": evidence_tier,
        "evidence_class": "UNAUTHENTICATED_FAIL_OR_HOLD",
        "operational_wetlab_authority": False,
        "plumbing_control_only": False,
        "decision": decision,
        "authority_scope": authority_scope,
        "bank_qualified": False,
        "promotion_authorized": False,
        "physical_qualification_complete": False,
        "release_authorizing": False,
        "modeled_qualification_only": False,
        "custody_verification_mode": "GOVERNED_ON_DISK_OWNER_STORE_AUTHENTICATED",
        "custody_authenticated": False,
        "physical_dossier_id": dossier_id,
        "qa_signoff_id": qa_signoff_id,
        "custody_failure_reasons": [str(x) for x in custody_failure_reasons],
        "lineages_verified": [],
        "whole_graft_stressed_tested": False,
    }
    if extra_fields:
        for k, v in extra_fields.items():
            if k not in ("archive_sha256", "record_sha256"):
                body[k] = v
    return _seal_gate0v_receipt_v2_round5(body)


def emit_gate0v_modeled_receipt_v2_round5(
    composite_result: Dict[str, Any],
    *,
    arm_id: str,
    lot_id: str,
    bank_id: str,
    construct_manifest_sha256: str,
    canonical_manifest_path: Path | str | None = None,
    canonical_arm_manifest: Dict[str, Any] | None = None,
    canonical_arm_manifest_sha256: str | None = None,
    openislet_root: Path | None = None,
) -> Dict[str, Any]:
    """Wrap an actual owning evaluate_composite_clinical_release() solver result into a sealed
    v2_round5_unified GATE-0V receipt strictly scoped to MODELED_COMPUTATIONAL_ONLY.
    Derives canonical_arm_manifest_sha256 strictly from governed manifest bytes when available and
    rejects authenticated physical wet-lab dossiers (non-substitution invariant)."""
    if not isinstance(composite_result, dict):
        raise ValueError("composite_result must be a dict emitted by evaluate_composite_clinical_release")
    if composite_result.get("dossier_type") == "AUTHENTICATED_PHYSICAL_WETLAB_GATE0V_DOSSIER":
        raise ValueError("NON_SUBSTITUTION_ERROR: physical wet-lab dossier cannot be wrapped as a modeled composite result")
    if composite_result.get("physical_qualification_complete") is True:
        raise ValueError("NON_SUBSTITUTION_ERROR: modeled receipt adapter requires physical_qualification_complete=False")
    if "composite_verdict" not in composite_result or "qualification_scope" not in composite_result:
        raise ValueError("composite_result missing required evaluate_composite_clinical_release keys (composite_verdict, qualification_scope)")
    if not _is_clean_nonempty_str(lot_id) or not _is_clean_nonempty_str(bank_id):
        raise ValueError("lot_id and bank_id must be non-empty trimmed strings")
    if not _is_valid_sha256_hex(construct_manifest_sha256):
        raise ValueError(f"Invalid construct_manifest_sha256={construct_manifest_sha256!r}")

    ctx, ctx_err = _resolve_governed_manifest_and_arm_v2_round8(
        arm_id=arm_id,
        canonical_manifest_path=canonical_manifest_path,
        openislet_root=openislet_root,
    )
    if ctx is None:
        raise ValueError(f"Governed canonical manifest resolution failed for modeled receipt: {ctx_err}")
    manifest_sha = str(ctx["manifest_sha256"])
    if canonical_arm_manifest_sha256 is not None and str(canonical_arm_manifest_sha256) != manifest_sha:
        raise ValueError(
            f"FAIL_CANONICAL_MANIFEST_SHA256_MISMATCH: caller supplied {canonical_arm_manifest_sha256!r} != governed bytes {manifest_sha!r}"
        )
    product_id = str(ctx["product_id"])
    bank_origin = str(ctx["bank_origin"])
    solver_digest = _canonical_sha256_v2_round5(composite_result)
    return _seal_gate0v_receipt_v2_round5({
        "schema_revision": "v2_round5_unified",
        "record_id": _make_canonical_gate0v_record_id_v2_round9("G0V-MOD", product_id, lot_id),
        "gate_source": "GATE-0V",
        "product_id": product_id,
        "lot_id": lot_id,
        "bank_id": bank_id,
        "bank_origin": bank_origin,
        "canonical_arm_manifest_sha256": manifest_sha,
        "construct_manifest_sha256": construct_manifest_sha256,
        "evidence_tier": "MODELED_COMPUTATIONAL_ONLY",
        "evidence_class": "MODELED_COMPUTATIONAL_ONLY",
        "operational_wetlab_authority": False,
        "plumbing_control_only": False,
        "decision": str(composite_result["composite_verdict"]),
        "authority_scope": "MODELED_COMPUTATIONAL_ONLY",
        "bank_qualified": False,
        "promotion_authorized": False,
        "physical_qualification_complete": False,
        "release_authorizing": False,
        "modeled_qualification_only": True,
        "qualification_scope": str(composite_result.get("qualification_scope") or QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL),
        "producer_composite_verdict": str(composite_result["composite_verdict"]),
        "producer_composite_result_sha256": solver_digest,
        "lineages_verified": sorted(_GY030_REQUIRED_5_LINEAGES),
        "whole_graft_stressed_tested": False,
    })


_SYNTHETIC_FORBIDDEN_TOP_LEVEL_SIMULATION_KEYS_V2_ROUND13 = (
    "owner_gate0v_qualification_tier",
    "owner_gate0v_verdict",
    "lineages_verified",
    "whole_graft_stressed_tested",
    "estimand1_u_esc",
    "estimand2_u_cond",
    "caspase_fold_activity",
    "five_virus_max_fold_vs_wt",
    "nhs20_cdc_c5b9_u95_pct",
)


def _is_synthetic_plumbing_installation_v2_round13(trust_ctx: Dict[str, Any] | None) -> bool:
    """Audit R12-06: Determine whether a verified trust_ctx belongs to a synthetic/plumbing control
    installation (as opposed to an OWNER_PROVISIONED_PRODUCTION installation)."""
    if not isinstance(trust_ctx, dict):
        return False
    t_mode = str(trust_ctx.get("provenance_mode") or "")
    i_mode = str(trust_ctx.get("installation_provenance_mode") or "")
    inst_id = str(trust_ctx.get("installation_id") or "")
    is_prod = (
        t_mode == "OWNER_PROVISIONED_PRODUCTION"
        and i_mode == "OWNER_PROVISIONED_PRODUCTION_INSTALLATION"
        and not any(
            tok in s.upper()
            for s in (t_mode, i_mode, inst_id)
            for tok in _SYNTHETIC_ISSUER_FORBIDDEN_MARKERS_V2_ROUND10
        )
    )
    return not is_prod


def _finalize_gate0v_cli_receipt(
    raw_receipt: Dict[str, Any],
    *,
    is_synthetic_plumbing: bool,
) -> Dict[str, Any]:
    """Audit R12-06: Single unified receipt finalizer routed across EVERY return path (PASS,
    FAIL/adverse, AND HOLD) of `issue_gate0v_physical_receipt_from_governed_root`.
    Whenever `is_synthetic_plumbing` is True, strips ALL production-named simulation/evaluation
    fields from top level into `synthetic_plumbing_simulation`, enforces all 5 authority flags
    strictly False, sets uniform SYNTHETIC_FIXTURE / SYNTHETIC_PLUMBING_CONTROL_FIXTURE /
    plumbing_control_only=True typing, assigns a safe non-authorizing decision
    (`SYNTHETIC_SELF_TEST_PASS` / `SYNTHETIC_SELF_TEST_FAIL` / `SYNTHETIC_SELF_TEST_HOLD`),
    and seals `archive_sha256`."""
    body = copy.deepcopy({k: v for k, v in raw_receipt.items() if k not in ("archive_sha256", "record_sha256")})
    if not is_synthetic_plumbing:
        return _seal_gate0v_receipt_v2_round5(body)

    orig_decision = str(body.get("decision") or "")
    orig_scope = str(body.get("authority_scope") or "")
    orig_ev_tier = str(body.get("evidence_tier") or "")
    orig_bank_qual = bool(body.get("bank_qualified", False))
    orig_promo = bool(body.get("promotion_authorized", False))
    orig_phys = bool(body.get("physical_qualification_complete", False))
    orig_rel_auth = bool(body.get("release_authorizing", False))

    if orig_decision.startswith("PASS_") or orig_decision == "SYNTHETIC_SELF_TEST_PASS" or orig_phys is True:
        sim_outcome = "PASS"
        safe_decision = "SYNTHETIC_SELF_TEST_PASS"
        synth_prefix = "G0V-SYNTH"
    elif orig_decision.startswith("HOLD_") or orig_decision == "SYNTHETIC_SELF_TEST_HOLD" or orig_ev_tier == "UNAUTHENTICATED_HOLD":
        sim_outcome = "HOLD"
        safe_decision = "SYNTHETIC_SELF_TEST_HOLD"
        synth_prefix = "G0V-SYNTH-HOLD"
    else:
        sim_outcome = "FAIL"
        safe_decision = "SYNTHETIC_SELF_TEST_FAIL"
        synth_prefix = "G0V-SYNTH-FAIL"

    qual_tier_val = body.pop("owner_gate0v_qualification_tier", None)
    eval_verdict_val = body.pop("owner_gate0v_verdict", None)
    lineages_val = body.pop("lineages_verified", None)
    whole_graft_val = body.pop("whole_graft_stressed_tested", None)
    sim_metrics: Dict[str, Any] = {}
    for mk in (
        "estimand1_u_esc",
        "estimand2_u_cond",
        "caspase_fold_activity",
        "five_virus_max_fold_vs_wt",
        "nhs20_cdc_c5b9_u95_pct",
    ):
        if mk in body:
            sim_metrics[mk] = body.pop(mk)

    existing_sim = body.get("synthetic_plumbing_simulation")
    sim_block: Dict[str, Any] = copy.deepcopy(existing_sim) if isinstance(existing_sim, dict) else {}
    sim_block["simulated_outcome"] = sim_outcome
    sim_block["all_criteria_satisfied"] = (sim_outcome == "PASS")
    if qual_tier_val is not None or "simulated_qualification_tier" not in sim_block:
        sim_block["simulated_qualification_tier"] = qual_tier_val
    if eval_verdict_val is not None or "simulated_evaluator_verdict" not in sim_block:
        sim_block["simulated_evaluator_verdict"] = eval_verdict_val
    if lineages_val is not None or "simulated_five_lineage_verified" not in sim_block:
        sim_block["simulated_five_lineage_verified"] = list(lineages_val) if isinstance(lineages_val, list) else []
    if whole_graft_val is not None or "simulated_whole_graft_passed" not in sim_block:
        sim_block["simulated_whole_graft_passed"] = bool(whole_graft_val) if whole_graft_val is not None else False
    if "simulated_decision" not in sim_block:
        sim_block["simulated_decision"] = orig_decision
    if "simulated_authority_scope" not in sim_block:
        sim_block["simulated_authority_scope"] = orig_scope
    if "simulated_bank_qualified" not in sim_block:
        sim_block["simulated_bank_qualified"] = orig_bank_qual
    if "simulated_physical_pass" not in sim_block:
        sim_block["simulated_physical_pass"] = (sim_outcome == "PASS")
    if "simulated_promotion_pass" not in sim_block:
        sim_block["simulated_promotion_pass"] = orig_promo
    if "simulated_release_authorizing" not in sim_block:
        sim_block["simulated_release_authorizing"] = orig_rel_auth
    if sim_metrics:
        sim_block["simulated_metrics"] = sim_metrics

    body["record_id"] = _make_canonical_gate0v_record_id_v2_round9(
        synth_prefix,
        str(body.get("product_id") or ""),
        str(body.get("lot_id") or ""),
    )
    body["evidence_tier"] = "SYNTHETIC_FIXTURE"
    body["evidence_class"] = "SYNTHETIC_PLUMBING_CONTROL_FIXTURE"
    body["plumbing_control_only"] = True
    body["operational_wetlab_authority"] = False
    body["bank_qualified"] = False
    body["promotion_authorized"] = False
    body["physical_qualification_complete"] = False
    body["release_authorizing"] = False
    body["decision"] = safe_decision
    body["authority_scope"] = "SYNTHETIC_SELF_TEST"
    body["custody_verification_mode"] = "SYNTHETIC_PLUMBING_CONTROL_FIXTURE_ONLY"
    body["synthetic_plumbing_simulation"] = sim_block
    for _fk in _SYNTHETIC_FORBIDDEN_TOP_LEVEL_SIMULATION_KEYS_V2_ROUND13:
        body.pop(_fk, None)
    return _seal_gate0v_receipt_v2_round5(body)


def issue_gate0v_physical_receipt_from_governed_root(
    lookup_request: _AbcMapping[str, Any] | None = None,
    *,
    arm_id: Any = None,
    lot_id: Any = None,
    bank_id: Any = None,
    product_id: Any = None,
    construct_manifest_sha256: Any = None,
    dossier_id: Any = None,
    qa_signoff_id: Any = None,
    expected_dossier_sha256: Any = None,
    expected_qa_signoff_sha256: Any = None,
    expected_canonical_manifest_sha256: Any = None,
    release_scope: Any = None,
    governed_store_root: Path | str | None = None,
    canonical_manifest_path: Path | str | None = None,
    openislet_root: Path | None = None,
) -> Tuple[Dict[str, Any], int]:
    """Audit R7-06 + R7-07 + R7-12 + R12-06 governed Gate 0V physical receipt producer entry point.
    Reads ONLY separately governed on-disk stores (`physical_dossiers/`, `qa_signoffs/`,
    `qa_issuer_registry.json`, `trusted_qualification_store.json`), derives
    `canonical_arm_manifest_sha256` strictly from governed manifest bytes, validates independent
    QA issuer authority, enforces owner product-family qualification tier rules via
    `v38.is_qualification_tier_allowed_for_product`, validates all 5 quantitative Gate 0V domains
    with typed safe finite conversions, executes the real owner `v38.evaluate_wholegraft_gate0v_and_stress_ap1903`
    before issuing or registering authority, routes EVERY return path (PASS, FAIL/adverse, AND HOLD)
    through `_finalize_gate0v_cli_receipt`, and registers passing receipts strictly ONCE under
    `<governed_store_root>/issued_receipts/<archive_sha256>.json`.

    Returns `(receipt_dict, exit_code)` where exit_code is 0 (PASS), 2 (HOLD), or 3 (FAIL)."""
    # Audit R8-03, R9-03 & R12-06: Load & verify owner-configured trust anchor + installation identity
    # upfront so EVERY return path knows whether this installation is synthetic plumbing vs production!
    resolved_root_pre = _resolve_openislet_root(openislet_root)
    trust_ctx, trust_err = _load_and_verify_owner_trust_config_v2_round9(resolved_root_pre)
    is_synthetic_installation = _is_synthetic_plumbing_installation_v2_round13(trust_ctx)

    def _return_finalized(raw_rec: Dict[str, Any], rc: int, *, force_synthetic: bool = False) -> Tuple[Dict[str, Any], int]:
        return (
            _finalize_gate0v_cli_receipt(
                raw_rec,
                is_synthetic_plumbing=(is_synthetic_installation or force_synthetic),
            ),
            rc,
        )

    req_map: Dict[str, Any] = {}
    if lookup_request is not None:
        if not isinstance(lookup_request, _AbcMapping):
            return _return_finalized(
                _make_fail_closed_gate0v_custody_receipt_v2_round7(
                    decision="FAIL_MALFORMED_ARCHIVED_MEASUREMENT",
                    authority_scope="REJECTED_MALFORMED_ARCHIVED_MEASUREMENT",
                    evidence_tier="UNAUTHENTICATED_FAIL",
                    record_prefix="G0V-MALFORMED-FAIL",
                    product_id="",
                    lot_id="",
                    bank_id="",
                    bank_origin="",
                    manifest_sha="",
                    construct_manifest_sha256="",
                    dossier_id=None,
                    qa_signoff_id=None,
                    custody_failure_reasons=[f"LOOKUP_REQUEST_NOT_MAPPING:{type(lookup_request).__name__}"],
                ),
                3,
            )
        req_map = dict(lookup_request)

    def _pick_anchor(field_name: str, kw_val: Any) -> Any:
        rv = req_map.get(field_name)
        if rv is not None and kw_val is not None and rv != kw_val:
            return ("__CONFLICT__", rv, kw_val)
        return kw_val if kw_val is not None else rv

    eff_arm_id = _pick_anchor("arm_id", arm_id)
    eff_lot_id = _pick_anchor("lot_id", lot_id)
    eff_bank_id = _pick_anchor("bank_id", bank_id)
    eff_product_id = _pick_anchor("product_id", product_id)
    eff_construct_sha = _pick_anchor("construct_manifest_sha256", construct_manifest_sha256)
    eff_dossier_id = _pick_anchor("dossier_id", dossier_id)
    eff_qa_signoff_id = _pick_anchor("qa_signoff_id", qa_signoff_id)
    eff_exp_dossier_sha = _pick_anchor("expected_dossier_sha256", expected_dossier_sha256)
    eff_exp_qa_sha = _pick_anchor("expected_qa_signoff_sha256", expected_qa_signoff_sha256)
    eff_exp_manifest_sha = _pick_anchor("expected_canonical_manifest_sha256", expected_canonical_manifest_sha256)
    if eff_exp_manifest_sha is None and "canonical_arm_manifest_sha256" in req_map:
        eff_exp_manifest_sha = req_map.get("canonical_arm_manifest_sha256")
    eff_req_scope = _pick_anchor("release_scope", release_scope)

    # Check modeled non-substitution BEFORE anything else!
    is_modeled_attempt = (
        "composite_verdict" in req_map
        or req_map.get("modeled_qualification_only") is True
        or (isinstance(req_map.get("authority_scope"), str) and req_map.get("authority_scope") in _FORBIDDEN_MODELED_SCOPES_V2_ROUND8)
        or (isinstance(req_map.get("evidence_tier"), str) and req_map.get("evidence_tier") in _FORBIDDEN_MODELED_SCOPES_V2_ROUND8)
        or (isinstance(req_map.get("qualification_scope"), str) and req_map.get("qualification_scope") in _FORBIDDEN_MODELED_SCOPES_V2_ROUND8)
    )

    # Resolve governed manifest bytes FIRST (Audit R7-07: hash strictly derived from disk bytes!)
    if isinstance(eff_arm_id, tuple) and eff_arm_id and eff_arm_id[0] == "__CONFLICT__":
        return _return_finalized(
            _make_fail_closed_gate0v_custody_receipt_v2_round7(
                decision="FAIL_PHYSICAL_EVIDENCE_CUSTODY_MISMATCH",
                authority_scope="REJECTED_CUSTODY_MISMATCH",
                evidence_tier="UNAUTHENTICATED_FAIL",
                record_prefix="G0V-CUSTODY-FAIL",
                product_id=_safe_str_v2_round8(eff_product_id),
                lot_id=_safe_str_v2_round8(eff_lot_id),
                bank_id=_safe_str_v2_round8(eff_bank_id),
                bank_origin="",
                manifest_sha="",
                construct_manifest_sha256=_safe_str_v2_round8(eff_construct_sha),
                dossier_id=_safe_str_v2_round8(eff_dossier_id) or None,
                qa_signoff_id=_safe_str_v2_round8(eff_qa_signoff_id) or None,
                custody_failure_reasons=["CONFLICTING_LOOKUP_ANCHOR:arm_id"],
            ),
            3,
        )
    if eff_arm_id is not None and not isinstance(eff_arm_id, str):
        return _return_finalized(
            _make_fail_closed_gate0v_custody_receipt_v2_round7(
                decision="FAIL_MALFORMED_ARCHIVED_MEASUREMENT",
                authority_scope="REJECTED_MALFORMED_ARCHIVED_MEASUREMENT",
                evidence_tier="UNAUTHENTICATED_FAIL",
                record_prefix="G0V-MALFORMED-FAIL",
                product_id=_safe_str_v2_round8(eff_product_id),
                lot_id=_safe_str_v2_round8(eff_lot_id),
                bank_id=_safe_str_v2_round8(eff_bank_id),
                bank_origin="",
                manifest_sha="",
                construct_manifest_sha256=_safe_str_v2_round8(eff_construct_sha),
                dossier_id=_safe_str_v2_round8(eff_dossier_id) or None,
                qa_signoff_id=_safe_str_v2_round8(eff_qa_signoff_id) or None,
                custody_failure_reasons=[f"MALFORMED_ARM_ID_TYPE:{type(eff_arm_id).__name__}"],
            ),
            3,
        )

    if trust_ctx is None:
        is_inst_id_err = isinstance(trust_err, str) and trust_err.startswith("INSTALLATION_IDENTITY::")
        return _return_finalized(
            _make_fail_closed_gate0v_custody_receipt_v2_round7(
                decision="FAIL_UNTRUSTED_INSTALLATION_IDENTITY" if is_inst_id_err else "FAIL_UNTRUSTED_STORE_OR_MANIFEST_PATH",
                authority_scope="REJECTED_UNTRUSTED_INSTALLATION_IDENTITY" if is_inst_id_err else "REJECTED_UNTRUSTED_TRUST_ANCHOR",
                evidence_tier="UNAUTHENTICATED_FAIL",
                record_prefix="G0V-INSTID-FAIL" if is_inst_id_err else "G0V-TRUST-FAIL",
                product_id=_safe_str_v2_round8(eff_product_id),
                lot_id=_safe_str_v2_round8(eff_lot_id),
                bank_id=_safe_str_v2_round8(eff_bank_id),
                bank_origin="",
                manifest_sha="",
                construct_manifest_sha256=_safe_str_v2_round8(eff_construct_sha),
                dossier_id=_safe_str_v2_round8(eff_dossier_id) or None,
                qa_signoff_id=_safe_str_v2_round8(eff_qa_signoff_id) or None,
                custody_failure_reasons=[f"OWNER_TRUST_CONFIG_REJECTED:{trust_err}"],
            ),
            3,
        )

    # Reject any caller-supplied canonical_manifest_path that is a symlink or diverges from configured owner anchor!
    if canonical_manifest_path is not None:
        if not isinstance(canonical_manifest_path, (Path, str)):
            return _return_finalized(
                _make_fail_closed_gate0v_custody_receipt_v2_round7(
                    decision="FAIL_UNTRUSTED_STORE_OR_MANIFEST_PATH",
                    authority_scope="REJECTED_UNTRUSTED_TRUST_ANCHOR",
                    evidence_tier="UNAUTHENTICATED_FAIL",
                    record_prefix="G0V-TRUST-FAIL",
                    product_id=_safe_str_v2_round8(eff_product_id),
                    lot_id=_safe_str_v2_round8(eff_lot_id),
                    bank_id=_safe_str_v2_round8(eff_bank_id),
                    bank_origin="",
                    manifest_sha="",
                    construct_manifest_sha256=_safe_str_v2_round8(eff_construct_sha),
                    dossier_id=_safe_str_v2_round8(eff_dossier_id) or None,
                    qa_signoff_id=_safe_str_v2_round8(eff_qa_signoff_id) or None,
                    custody_failure_reasons=[f"UNTRUSTED_MANIFEST_PATH_TYPE:{type(canonical_manifest_path).__name__}"],
                ),
                3,
            )
        caller_mpath = Path(canonical_manifest_path)
        if caller_mpath.is_symlink() or caller_mpath.resolve() != trust_ctx["canonical_manifest_resolved"]:
            return _return_finalized(
                _make_fail_closed_gate0v_custody_receipt_v2_round7(
                    decision="FAIL_UNTRUSTED_STORE_OR_MANIFEST_PATH",
                    authority_scope="REJECTED_UNTRUSTED_TRUST_ANCHOR",
                    evidence_tier="UNAUTHENTICATED_FAIL",
                    record_prefix="G0V-TRUST-FAIL",
                    product_id=_safe_str_v2_round8(eff_product_id),
                    lot_id=_safe_str_v2_round8(eff_lot_id),
                    bank_id=_safe_str_v2_round8(eff_bank_id),
                    bank_origin="",
                    manifest_sha="",
                    construct_manifest_sha256=_safe_str_v2_round8(eff_construct_sha),
                    dossier_id=_safe_str_v2_round8(eff_dossier_id) or None,
                    qa_signoff_id=_safe_str_v2_round8(eff_qa_signoff_id) or None,
                    custody_failure_reasons=["CALLER_CANONICAL_MANIFEST_PATH_OUTSIDE_OWNER_TRUST_ANCHOR"],
                ),
                3,
            )

    ctx, ctx_err = _resolve_governed_manifest_and_arm_v2_round8(
        arm_id=eff_arm_id,
        canonical_manifest_path=trust_ctx["canonical_manifest_raw_path"],
        openislet_root=resolved_root_pre,
    )
    if ctx is None:
        is_hold_manifest = ctx_err in ("CANONICAL_MANIFEST_UNAVAILABLE",)
        return _return_finalized(
            _make_fail_closed_gate0v_custody_receipt_v2_round7(
                decision="HOLD_PHYSICAL_EVIDENCE_UNAVAILABLE" if is_hold_manifest else "FAIL_PHYSICAL_EVIDENCE_CUSTODY_MISMATCH",
                authority_scope="UNQUALIFIED_PENDING_PHYSICAL_EVIDENCE" if is_hold_manifest else "REJECTED_CUSTODY_MISMATCH",
                evidence_tier="UNAUTHENTICATED_HOLD" if is_hold_manifest else "UNAUTHENTICATED_FAIL",
                record_prefix="G0V-CUSTODY-HOLD" if is_hold_manifest else "G0V-CUSTODY-FAIL",
                product_id=_safe_str_v2_round8(eff_product_id),
                lot_id=_safe_str_v2_round8(eff_lot_id),
                bank_id=_safe_str_v2_round8(eff_bank_id),
                bank_origin="",
                manifest_sha="",
                construct_manifest_sha256=_safe_str_v2_round8(eff_construct_sha),
                dossier_id=_safe_str_v2_round8(eff_dossier_id) or None,
                qa_signoff_id=_safe_str_v2_round8(eff_qa_signoff_id) or None,
                custody_failure_reasons=[ctx_err or "CANONICAL_MANIFEST_RESOLUTION_FAILED"],
            ),
            2 if is_hold_manifest else 3,
        )

    canonical_product_id = str(ctx["product_id"])
    bank_origin = str(ctx["bank_origin"])
    tier_family = str(ctx["tier_family"])
    canonical_product_def = ctx["canonical_product_def"]
    manifest_sha = str(ctx["manifest_sha256"])
    resolved_root: Path = ctx["resolved_root"]
    v38 = _get_v38_module()

    def _emit_fail(decision: str, scope: str, prefix: str, reasons: List[str], extra: Dict[str, Any] | None = None) -> Tuple[Dict[str, Any], int]:
        return _return_finalized(
            _make_fail_closed_gate0v_custody_receipt_v2_round7(
                decision=decision,
                authority_scope=scope,
                evidence_tier="UNAUTHENTICATED_FAIL",
                record_prefix=prefix,
                product_id=canonical_product_id,
                lot_id=_safe_str_v2_round8(eff_lot_id),
                bank_id=_safe_str_v2_round8(eff_bank_id),
                bank_origin=bank_origin,
                manifest_sha=manifest_sha,
                construct_manifest_sha256=_safe_str_v2_round8(eff_construct_sha),
                dossier_id=_safe_str_v2_round8(eff_dossier_id) or None,
                qa_signoff_id=_safe_str_v2_round8(eff_qa_signoff_id) or None,
                custody_failure_reasons=reasons,
                extra_fields=extra,
            ),
            3,
        )

    # Audit R8-03: Configured canonical manifest bytes MUST match owner trust-config SHA-256 pin!
    if manifest_sha != trust_ctx["canonical_arm_manifest_sha256"]:
        return _emit_fail(
            "FAIL_CANONICAL_MANIFEST_SHA256_MISMATCH",
            "REJECTED_MANIFEST_HASH_MISMATCH",
            "G0V-MANIFEST-FAIL",
            [f"GOVERNED_MANIFEST_BYTES_MISMATCH_OWNER_TRUST_PIN:{manifest_sha}!={trust_ctx['canonical_arm_manifest_sha256']}"],
        )

    if is_modeled_attempt:
        return _emit_fail(
            "FAIL_PHYSICAL_EVIDENCE_CUSTODY_MISMATCH",
            "REJECTED_CUSTODY_MISMATCH",
            "G0V-CUSTODY-FAIL",
            ["NON_SUBSTITUTION_ERROR:MODELED_OUTPUT_REJECTED_AS_PHYSICAL_EVIDENCE"],
        )

    # Reject caller-supplied raw physical assay dicts (NEVER self-hash caller bodies!)
    forbidden_present = sorted(_FORBIDDEN_CALLER_PHYSICAL_ASSAY_KEYS.intersection(req_map.keys()))
    if forbidden_present:
        return _emit_fail(
            "FAIL_PHYSICAL_EVIDENCE_CUSTODY_MISMATCH",
            "REJECTED_CUSTODY_MISMATCH",
            "G0V-CUSTODY-FAIL",
            [f"FORBIDDEN_CALLER_SUPPLIED_ASSAY_BODY_KEYS:{','.join(forbidden_present)}"],
        )

    # Check conflicting anchor arguments
    conflict_reasons: List[str] = []
    for fname, fval in (
        ("lot_id", eff_lot_id),
        ("bank_id", eff_bank_id),
        ("product_id", eff_product_id),
        ("construct_manifest_sha256", eff_construct_sha),
        ("dossier_id", eff_dossier_id),
        ("qa_signoff_id", eff_qa_signoff_id),
        ("expected_dossier_sha256", eff_exp_dossier_sha),
        ("expected_qa_signoff_sha256", eff_exp_qa_sha),
        ("expected_canonical_manifest_sha256", eff_exp_manifest_sha),
        ("release_scope", eff_req_scope),
    ):
        if isinstance(fval, tuple) and fval and fval[0] == "__CONFLICT__":
            conflict_reasons.append(f"CONFLICTING_LOOKUP_ANCHOR:{fname}")
    if conflict_reasons:
        return _emit_fail(
            "FAIL_PHYSICAL_EVIDENCE_CUSTODY_MISMATCH",
            "REJECTED_CUSTODY_MISMATCH",
            "G0V-CUSTODY-FAIL",
            conflict_reasons,
        )

    # Audit R7-12: Typed check on lookup anchor types BEFORE any dict/path lookup (no TypeError on nested JSON!)
    malformed_anchor_reasons: List[str] = []
    for fname, fval in (
        ("lot_id", eff_lot_id),
        ("bank_id", eff_bank_id),
        ("product_id", eff_product_id),
        ("construct_manifest_sha256", eff_construct_sha),
        ("dossier_id", eff_dossier_id),
        ("qa_signoff_id", eff_qa_signoff_id),
        ("expected_dossier_sha256", eff_exp_dossier_sha),
        ("expected_qa_signoff_sha256", eff_exp_qa_sha),
        ("expected_canonical_manifest_sha256", eff_exp_manifest_sha),
        ("release_scope", eff_req_scope),
    ):
        if fval is not None and not isinstance(fval, str):
            malformed_anchor_reasons.append(f"MALFORMED_LOOKUP_ANCHOR_TYPE:{fname}:{type(fval).__name__}")
    if malformed_anchor_reasons:
        return _emit_fail(
            "FAIL_MALFORMED_ARCHIVED_MEASUREMENT",
            "REJECTED_MALFORMED_ARCHIVED_MEASUREMENT",
            "G0V-MALFORMED-FAIL",
            malformed_anchor_reasons,
        )

    # Audit R7-07: If caller supplied expected_canonical_manifest_sha256, it MUST match governed manifest bytes!
    if eff_exp_manifest_sha is not None and eff_exp_manifest_sha != manifest_sha:
        return _emit_fail(
            "FAIL_CANONICAL_MANIFEST_SHA256_MISMATCH",
            "REJECTED_MANIFEST_HASH_MISMATCH",
            "G0V-MANIFEST-FAIL",
            [f"CALLER_CANONICAL_MANIFEST_SHA256_MISMATCH:{eff_exp_manifest_sha}!={manifest_sha}"],
        )

    # Resolve separately governed on-disk store root STRICTLY against owner trust anchor (Audit R7-06 & Audit R8-03)!
    if governed_store_root is None:
        store_root = trust_ctx["authorized_store_raw_path"]
    elif isinstance(governed_store_root, (Path, str)):
        caller_sroot = Path(governed_store_root)
        if caller_sroot.is_symlink() or caller_sroot.resolve() != trust_ctx["authorized_store_resolved"]:
            return _emit_fail(
                "FAIL_UNTRUSTED_STORE_OR_MANIFEST_PATH",
                "REJECTED_UNTRUSTED_TRUST_ANCHOR",
                "G0V-TRUST-FAIL",
                ["CALLER_GOVERNED_STORE_ROOT_OUTSIDE_OWNER_TRUST_ANCHOR"],
            )
        store_root = trust_ctx["authorized_store_raw_path"]
    else:
        return _emit_fail(
            "FAIL_MUTABLE_CALLER_STORE_FORBIDDEN",
            "REJECTED_MUTABLE_CALLER_STORE",
            "G0V-STORE-FAIL",
            [f"GOVERNED_STORE_ROOT_MUST_BE_PATH:{type(governed_store_root).__name__}"],
        )

    hold_reasons: List[str] = []
    if not _is_clean_nonempty_str(eff_dossier_id):
        hold_reasons.append("MISSING_LOOKUP_DOSSIER_ID")
    elif not _is_safe_store_id_v2_round8(eff_dossier_id):
        return _emit_fail(
            "FAIL_PHYSICAL_EVIDENCE_CUSTODY_MISMATCH",
            "REJECTED_CUSTODY_MISMATCH",
            "G0V-CUSTODY-FAIL",
            ["UNSAFE_LOOKUP_DOSSIER_ID"],
        )
    if not _is_clean_nonempty_str(eff_qa_signoff_id):
        hold_reasons.append("MISSING_LOOKUP_QA_SIGNOFF_ID")
    elif not _is_safe_store_id_v2_round8(eff_qa_signoff_id):
        return _emit_fail(
            "FAIL_PHYSICAL_EVIDENCE_CUSTODY_MISMATCH",
            "REJECTED_CUSTODY_MISMATCH",
            "G0V-CUSTODY-FAIL",
            ["UNSAFE_LOOKUP_QA_SIGNOFF_ID"],
        )
    if store_root.is_symlink() or not store_root.is_dir():
        hold_reasons.append("GOVERNED_OWNER_STORE_ROOT_UNAVAILABLE")

    dossier_path = store_root / "physical_dossiers" / f"{eff_dossier_id}.json" if _is_safe_store_id_v2_round8(eff_dossier_id) else None
    qa_path = store_root / "qa_signoffs" / f"{eff_qa_signoff_id}.json" if _is_safe_store_id_v2_round8(eff_qa_signoff_id) else None
    issuer_reg_path = store_root / "qa_issuer_registry.json"

    # Audit R8-03: If the governed store directory exists, an absent qa_issuer_registry.json is a hard FAIL (never HOLD/PASS)!
    if not hold_reasons and not issuer_reg_path.is_file() and not issuer_reg_path.is_symlink():
        return _emit_fail(
            "FAIL_EMPTY_OR_MISSING_QA_ISSUER_REGISTRY",
            "REJECTED_EMPTY_OR_MISSING_QA_ISSUER_REGISTRY",
            "G0V-REGISTRY-FAIL",
            ["ABSENT_QA_ISSUER_REGISTRY_IN_GOVERNED_STORE"],
        )

    if not hold_reasons:
        if dossier_path is None or (not dossier_path.is_file() and not dossier_path.is_symlink()):
            hold_reasons.append("ABSENT_PHYSICAL_DOSSIER_IN_GOVERNED_STORE")
        if qa_path is None or (not qa_path.is_file() and not qa_path.is_symlink()):
            hold_reasons.append("ABSENT_QA_SIGNOFF_IN_GOVERNED_STORE")

    if hold_reasons:
        return _return_finalized(
            _make_fail_closed_gate0v_custody_receipt_v2_round7(
                decision="HOLD_PHYSICAL_EVIDENCE_UNAVAILABLE",
                authority_scope="UNQUALIFIED_PENDING_PHYSICAL_EVIDENCE",
                evidence_tier="UNAUTHENTICATED_HOLD",
                record_prefix="G0V-CUSTODY-HOLD",
                product_id=canonical_product_id,
                lot_id=_safe_str_v2_round8(eff_lot_id),
                bank_id=_safe_str_v2_round8(eff_bank_id),
                bank_origin=bank_origin,
                manifest_sha=manifest_sha,
                construct_manifest_sha256=_safe_str_v2_round8(eff_construct_sha),
                dossier_id=_safe_str_v2_round8(eff_dossier_id) or None,
                qa_signoff_id=_safe_str_v2_round8(eff_qa_signoff_id) or None,
                custody_failure_reasons=hold_reasons,
            ),
            2,
        )

    # Load immutable on-disk governed files cleanly (no uncaught JSON/symlink/type errors!)
    dossier_obj, d_load_err = _safe_load_governed_json_v2_round8(dossier_path)  # type: ignore[arg-type]
    qa_obj, q_load_err = _safe_load_governed_json_v2_round8(qa_path)  # type: ignore[arg-type]
    issuer_reg_raw_sha: str | None = None
    if issuer_reg_path.is_file() and not issuer_reg_path.is_symlink():
        try:
            issuer_reg_raw_sha = hashlib.sha256(issuer_reg_path.read_bytes()).hexdigest()
        except OSError:
            issuer_reg_raw_sha = None
    issuer_reg_obj, reg_load_err = _safe_load_governed_json_v2_round8(issuer_reg_path)

    empty_registry_reasons: List[str] = []
    registry_pin_reasons: List[str] = []
    malformed_reasons: List[str] = []
    missing_dossier_manifest_reasons: List[str] = []
    missing_qa_manifest_reasons: List[str] = []
    manifest_mismatch_reasons: List[str] = []
    issuer_auth_reasons: List[str] = []
    tier_rule_reasons: List[str] = []
    adverse_qual_reasons: List[str] = []
    custody_reasons: List[str] = []

    if d_load_err is not None:
        malformed_reasons.append(f"DOSSIER_LOAD_ERROR:{d_load_err}")
    elif not isinstance(dossier_obj, dict):
        malformed_reasons.append(f"OWNER_DOSSIER_NOT_MAPPING:{type(dossier_obj).__name__}")
    if q_load_err is not None:
        malformed_reasons.append(f"QA_SIGNOFF_LOAD_ERROR:{q_load_err}")
    elif not isinstance(qa_obj, dict):
        malformed_reasons.append(f"OWNER_QA_SIGNOFF_NOT_MAPPING:{type(qa_obj).__name__}")
    if reg_load_err is not None:
        if reg_load_err == "FILE_NOT_FOUND":
            empty_registry_reasons.append(f"QA_ISSUER_REGISTRY_LOAD_ERROR:{reg_load_err}")
        elif reg_load_err == "SYMLINK_FORBIDDEN":
            registry_pin_reasons.append(f"QA_ISSUER_REGISTRY_LOAD_ERROR:{reg_load_err}")
        else:
            issuer_auth_reasons.append(f"QA_ISSUER_REGISTRY_LOAD_ERROR:{reg_load_err}")
    elif not isinstance(issuer_reg_obj, dict):
        empty_registry_reasons.append("QA_ISSUER_REGISTRY_NOT_MAPPING")

    # Validate caller identity anchors
    if not _is_clean_nonempty_str(eff_lot_id):
        custody_reasons.append("INVALID_LOT_ID")
    if not _is_clean_nonempty_str(eff_bank_id):
        custody_reasons.append("INVALID_BANK_ID")
    if not _is_clean_nonempty_str(eff_product_id):
        custody_reasons.append("MISSING_LOOKUP_PRODUCT_ID")
    elif eff_product_id != canonical_product_id:
        custody_reasons.append(f"PRODUCT_ID_MISMATCH:{eff_product_id}!={canonical_product_id}")
    if not _is_safe_sha256_v2_round8(eff_construct_sha):
        custody_reasons.append("INVALID_CONSTRUCT_MANIFEST_SHA256")

    # Validate QA issuer registry non-emptiness, owner trust pin, and self-digest (Audit R7-06 & Audit R8-03)!
    verified_issuers: Dict[str, Any] = {}
    if isinstance(issuer_reg_obj, dict):
        issuers_raw = issuer_reg_obj.get("issuers")
        if not isinstance(issuers_raw, dict) or len(issuers_raw) == 0:
            empty_registry_reasons.append(
                f"QA_ISSUER_REGISTRY_EMPTY_OR_INVALID_ISSUERS:{type(issuers_raw).__name__}:len={len(issuers_raw) if isinstance(issuers_raw, (dict, list)) else -1}"
            )
        else:
            verified_issuers = issuers_raw
        if issuer_reg_raw_sha != trust_ctx["qa_issuer_registry_sha256"]:
            registry_pin_reasons.append(
                f"QA_ISSUER_REGISTRY_OWNER_TRUST_PIN_MISMATCH:{issuer_reg_raw_sha}!={trust_ctx['qa_issuer_registry_sha256']}"
            )
        if issuer_reg_obj.get("schema_version") != _QA_ISSUER_REGISTRY_SCHEMA_V2_ROUND8:
            issuer_auth_reasons.append("QA_ISSUER_REGISTRY_SCHEMA_INVALID")
        reg_sha = issuer_reg_obj.get("registry_sha256")
        if not _is_safe_sha256_v2_round8(reg_sha):
            issuer_auth_reasons.append("QA_ISSUER_REGISTRY_SHA256_INVALID")
        else:
            recomp_reg_sha = _safe_canonical_sha256_v2_round8(
                {k: v for k, v in issuer_reg_obj.items() if k != "registry_sha256"}
            )
            if recomp_reg_sha != reg_sha:
                issuer_auth_reasons.append("QA_ISSUER_REGISTRY_DIGEST_TAMPER_MISMATCH")

    # Validate archived physical dossier integrity, typed fields, quantitative thresholds & anchors
    dossier_sha = ""
    parsed_metrics: Dict[str, float] = {}
    release_scope_val: str | None = None
    if isinstance(dossier_obj, dict):
        d_sha_raw = dossier_obj.get("archive_sha256")
        if not _is_safe_sha256_v2_round8(d_sha_raw):
            custody_reasons.append("DOSSIER_ARCHIVE_SHA256_INVALID")
        else:
            dossier_sha = str(d_sha_raw)
            recomp_d = _safe_canonical_sha256_v2_round8(
                {k: v for k, v in dossier_obj.items() if k not in ("archive_sha256", "record_sha256")}
            )
            if recomp_d is None:
                malformed_reasons.append("DOSSIER_NON_CANONICALIZABLE_ARCHIVE")
            elif recomp_d != dossier_sha:
                custody_reasons.append("DOSSIER_DIGEST_TAMPER_MISMATCH")
            if eff_exp_dossier_sha is not None and eff_exp_dossier_sha != dossier_sha:
                custody_reasons.append("DOSSIER_EXPECTED_SHA256_MISMATCH")

        if (
            "composite_verdict" in dossier_obj
            or dossier_obj.get("modeled_qualification_only") is True
            or (isinstance(dossier_obj.get("authority_scope"), str) and dossier_obj.get("authority_scope") in _FORBIDDEN_MODELED_SCOPES_V2_ROUND8)
            or (isinstance(dossier_obj.get("evidence_tier"), str) and dossier_obj.get("evidence_tier") in _FORBIDDEN_MODELED_SCOPES_V2_ROUND8)
            or (isinstance(dossier_obj.get("qualification_scope"), str) and dossier_obj.get("qualification_scope") in _FORBIDDEN_MODELED_SCOPES_V2_ROUND8)
        ):
            custody_reasons.append("MODELED_DOSSIER_REJECTED_BY_PHYSICAL_CUSTODY")
        if dossier_obj.get("dossier_type") != "AUTHENTICATED_PHYSICAL_WETLAB_GATE0V_DOSSIER":
            custody_reasons.append("INVALID_PHYSICAL_DOSSIER_TYPE")
        if dossier_obj.get("evidence_tier") != "AUTHENTICATED_ARCHIVED_WETLAB":
            custody_reasons.append("INVALID_PHYSICAL_DOSSIER_EVIDENCE_TIER")
        if dossier_obj.get("physical_qualification_complete") is not True:
            if not isinstance(dossier_obj.get("physical_qualification_complete"), bool):
                malformed_reasons.append("MALFORMED_PHYSICAL_QUALIFICATION_COMPLETE_TYPE")
            else:
                custody_reasons.append("DOSSIER_PHYSICAL_QUALIFICATION_INCOMPLETE")
        if dossier_obj.get("whole_graft_stressed_tested") is not True:
            if not isinstance(dossier_obj.get("whole_graft_stressed_tested"), bool):
                malformed_reasons.append("MALFORMED_WHOLEGRAFT_STRESSED_TYPE")
            else:
                adverse_qual_reasons.append("FAIL_GATE0V_WHOLEGRAFT_STRESSED_NOT_TESTED")

        lin_ok, lin_err, lin_malformed = _safe_validate_5_lineages_v2_round8(dossier_obj.get("lineages_verified"))
        if not lin_ok:
            if lin_malformed:
                malformed_reasons.append(f"MALFORMED_LINEAGES:{lin_err}")
            else:
                adverse_qual_reasons.append(lin_err or "DOSSIER_5_LINEAGES_INCOMPLETE")

        raw_rscope = dossier_obj.get("release_scope")
        if not isinstance(raw_rscope, str):
            malformed_reasons.append(f"MALFORMED_RELEASE_SCOPE_TYPE:{type(raw_rscope).__name__}")
        elif raw_rscope not in ("CLINICAL_LOT_RELEASE", "BANK_QUALIFICATION_ONLY"):
            custody_reasons.append("DOSSIER_INVALID_RELEASE_SCOPE")
        else:
            release_scope_val = raw_rscope
            if eff_req_scope is not None and eff_req_scope != release_scope_val:
                custody_reasons.append(f"CALLER_RELEASE_SCOPE_MISMATCH:{eff_req_scope}!={release_scope_val}")

        # Audit R8-09: Mandatory canonical_arm_manifest_sha256 attestation on archived physical dossier!
        d_msha = dossier_obj.get("canonical_arm_manifest_sha256")
        if d_msha is None:
            missing_dossier_manifest_reasons.append("MISSING_DOSSIER_CANONICAL_ARM_MANIFEST_SHA256")
        elif not isinstance(d_msha, str):
            malformed_reasons.append("MALFORMED_DOSSIER_MANIFEST_SHA_TYPE")
        elif not _is_safe_sha256_v2_round8(d_msha):
            missing_dossier_manifest_reasons.append("INVALID_OR_EMPTY_DOSSIER_CANONICAL_ARM_MANIFEST_SHA256")
        elif d_msha != manifest_sha:
            manifest_mismatch_reasons.append(f"DOSSIER_CANONICAL_MANIFEST_SHA256_MISMATCH:{d_msha}!={manifest_sha}")

        # Audit R7-12 + R7-07: Guarded finite numeric check + ALL 5 quantitative Gate 0V thresholds!
        for num_f in _PHYSICAL_ASSAY_NUMERIC_FIELDS:
            ok_n, fv_n, err_n = _safe_finite_number_v2_round8(dossier_obj.get(num_f))
            if not ok_n or fv_n is None:
                malformed_reasons.append(f"MALFORMED_NUMERIC_MEASUREMENT:{num_f}:{err_n}")
            else:
                parsed_metrics[num_f] = fv_n

        if "estimand1_u_esc" in parsed_metrics:
            v = parsed_metrics["estimand1_u_esc"]
            if v < 0.0 or v > 1.0e-4:
                adverse_qual_reasons.append(f"FAIL_GATE0V_ESTIMAND1_U_ESC_GT_1E_MINUS_4:{v}")
        if "estimand2_u_cond" in parsed_metrics:
            v = parsed_metrics["estimand2_u_cond"]
            if v < 0.0 or v > 1.0e-3:
                adverse_qual_reasons.append(f"FAIL_GATE0V_ESTIMAND2_U_COND_GT_1E_MINUS_3:{v}")
        if "caspase_fold_activity" in parsed_metrics:
            v = parsed_metrics["caspase_fold_activity"]
            if v < 5.0:
                adverse_qual_reasons.append(f"FAIL_GATE0V_CASPASE_FOLD_ACTIVITY_LT_5X:{v}")
        if "five_virus_max_fold_vs_wt" in parsed_metrics:
            v = parsed_metrics["five_virus_max_fold_vs_wt"]
            if v <= 0.0 or v > 1.20:
                adverse_qual_reasons.append(f"FAIL_GATE0V_FIVE_VIRUS_INFECTIVITY_EXCEEDED:{v}")
        if "nhs20_cdc_c5b9_u95_pct" in parsed_metrics:
            v = parsed_metrics["nhs20_cdc_c5b9_u95_pct"]
            if v < 0.0 or v > 5.0:
                adverse_qual_reasons.append(f"FAIL_GATE0V_NHS20_CDC_LYSIS_GT_5PCT:{v}")

        # 6-anchor identity binding on physical dossier
        if dossier_obj.get("dossier_id") != eff_dossier_id:
            custody_reasons.append("DOSSIER_ID_MISMATCH")
        if dossier_obj.get("arm_id") != eff_arm_id:
            custody_reasons.append("DOSSIER_ARM_ID_MISMATCH")
        if dossier_obj.get("product_id") != canonical_product_id:
            custody_reasons.append("DOSSIER_PRODUCT_ID_MISMATCH")
        if dossier_obj.get("lot_id") != eff_lot_id:
            custody_reasons.append("DOSSIER_LOT_ID_MISMATCH")
        if dossier_obj.get("bank_id") != eff_bank_id:
            custody_reasons.append("DOSSIER_BANK_ID_MISMATCH")
        if dossier_obj.get("construct_manifest_sha256") != eff_construct_sha:
            custody_reasons.append("DOSSIER_CONSTRUCT_MANIFEST_SHA256_MISMATCH")
        if dossier_obj.get("qa_signoff_id") != eff_qa_signoff_id:
            custody_reasons.append("DOSSIER_QA_SIGNOFF_ID_MISMATCH")

    # Validate independent QA sign-off record + positive non-empty QA issuer authority (Audit R7-06, R8-03, R8-09)!
    qa_sha = ""
    qa_issuer_id_val = ""
    qa_reviewer_id_val = ""
    qa_issuer_class_val = ""
    positive_issuer_authorized = False
    positive_reviewer_authorized = False
    if isinstance(qa_obj, dict):
        q_sha_raw = qa_obj.get("archive_sha256")
        if not _is_safe_sha256_v2_round8(q_sha_raw):
            custody_reasons.append("QA_SIGNOFF_ARCHIVE_SHA256_INVALID")
        else:
            qa_sha = str(q_sha_raw)
            recomp_q = _safe_canonical_sha256_v2_round8(
                {k: v for k, v in qa_obj.items() if k not in ("archive_sha256", "record_sha256")}
            )
            if recomp_q is None:
                malformed_reasons.append("QA_SIGNOFF_NON_CANONICALIZABLE_ARCHIVE")
            elif recomp_q != qa_sha:
                custody_reasons.append("QA_SIGNOFF_DIGEST_TAMPER_MISMATCH")
            if eff_exp_qa_sha is not None and eff_exp_qa_sha != qa_sha:
                custody_reasons.append("QA_EXPECTED_SHA256_MISMATCH")

        if qa_obj.get("record_type") != "INDEPENDENT_QA_SIGNOFF_GATE0V":
            custody_reasons.append("INVALID_QA_SIGNOFF_RECORD_TYPE")
        if qa_obj.get("qa_decision") != "APPROVED":
            custody_reasons.append(f"QA_SIGNOFF_NOT_APPROVED:{qa_obj.get('qa_decision')!r}")
        if qa_obj.get("revoked") is not False:
            custody_reasons.append("QA_SIGNOFF_REVOKED_OR_INVALID_FLAG")

        raw_issuer_id = qa_obj.get("qa_issuer_id")
        raw_reviewer_id = qa_obj.get("qa_reviewer_id")
        raw_qa_scope = qa_obj.get("approved_release_scope")
        if not _is_safe_store_id_v2_round8(raw_issuer_id):
            issuer_auth_reasons.append("FAIL_UNAUTHORIZED_QA_ISSUER:MISSING_OR_INVALID_QA_ISSUER_ID")
        if not _is_safe_store_id_v2_round8(raw_reviewer_id):
            issuer_auth_reasons.append("FAIL_UNAUTHORIZED_QA_ISSUER:MISSING_OR_INVALID_QA_REVIEWER_ID")
        if not verified_issuers:
            empty_registry_reasons.append("QA_ISSUER_REGISTRY_EMPTY_FOR_AUTHORIZATION")
        elif isinstance(raw_issuer_id, str) and isinstance(raw_reviewer_id, str):
            prod_reg_strict = bool(
                isinstance(issuer_reg_obj, dict)
                and (
                    issuer_reg_obj.get("provenance_mode") == "OWNER_PROVISIONED_PRODUCTION_REGISTRY"
                    or issuer_reg_obj.get("synthetic_fixture_issuers_forbidden") is True
                )
            )
            issuer_upper = raw_issuer_id.upper()
            if prod_reg_strict and any(tok in issuer_upper for tok in _SYNTHETIC_ISSUER_FORBIDDEN_MARKERS_V2_ROUND10):
                issuer_auth_reasons.append(f"FAIL_SYNTHETIC_ISSUER_FORBIDDEN_IN_PRODUCTION:{raw_issuer_id}")
            issuer_entry = verified_issuers.get(raw_issuer_id)
            if not isinstance(issuer_entry, dict):
                issuer_auth_reasons.append(f"FAIL_UNAUTHORIZED_QA_ISSUER:UNKNOWN_ISSUER:{raw_issuer_id}")
            else:
                issuer_entry_ok = True
                if prod_reg_strict:
                    icls = str(issuer_entry.get("issuer_class") or "")
                    if icls != "OWNER_PROVISIONED_PRODUCTION" or any(
                        tok in icls.upper() for tok in _SYNTHETIC_ISSUER_FORBIDDEN_MARKERS_V2_ROUND10
                    ):
                        issuer_auth_reasons.append(
                            f"FAIL_SYNTHETIC_ISSUER_FORBIDDEN_IN_PRODUCTION:ISSUER_CLASS:{icls!r}"
                        )
                        issuer_entry_ok = False
                if issuer_entry.get("issuer_id") != raw_issuer_id:
                    issuer_auth_reasons.append("FAIL_UNAUTHORIZED_QA_ISSUER:ISSUER_ID_KEY_MISMATCH")
                    issuer_entry_ok = False
                if issuer_entry.get("active") is not True or issuer_entry.get("revoked") is not False:
                    issuer_auth_reasons.append(f"FAIL_UNAUTHORIZED_QA_ISSUER:ISSUER_INACTIVE_OR_REVOKED:{raw_issuer_id}")
                    issuer_entry_ok = False
                auth_reviewers = issuer_entry.get("authorized_reviewer_ids")
                if not isinstance(auth_reviewers, list) or not all(isinstance(r, str) for r in auth_reviewers) or raw_reviewer_id not in auth_reviewers:
                    issuer_auth_reasons.append(f"FAIL_UNAUTHORIZED_QA_ISSUER:UNAUTHORIZED_REVIEWER:{raw_reviewer_id}")
                    issuer_entry_ok = False
                auth_scopes = issuer_entry.get("authorized_release_scopes")
                if not isinstance(auth_scopes, list) or not all(isinstance(s, str) for s in auth_scopes) or not isinstance(raw_qa_scope, str) or raw_qa_scope not in auth_scopes:
                    issuer_auth_reasons.append(f"FAIL_UNAUTHORIZED_QA_ISSUER:UNAUTHORIZED_SCOPE:{raw_qa_scope!r}")
                    issuer_entry_ok = False
                if prod_reg_strict and any(tok in issuer_upper for tok in _SYNTHETIC_ISSUER_FORBIDDEN_MARKERS_V2_ROUND10):
                    issuer_entry_ok = False
                if issuer_entry_ok:
                    positive_issuer_authorized = True
                    positive_reviewer_authorized = True
                    qa_issuer_id_val = raw_issuer_id
                    qa_reviewer_id_val = raw_reviewer_id
                    qa_issuer_class_val = str(issuer_entry.get("issuer_class") or "")

        # Audit R8-09: Mandatory canonical_arm_manifest_sha256 attestation on archived QA sign-off!
        q_msha = qa_obj.get("canonical_arm_manifest_sha256")
        if q_msha is None:
            missing_qa_manifest_reasons.append("MISSING_QA_CANONICAL_ARM_MANIFEST_SHA256")
        elif not isinstance(q_msha, str):
            malformed_reasons.append("MALFORMED_QA_MANIFEST_SHA_TYPE")
        elif not _is_safe_sha256_v2_round8(q_msha):
            missing_qa_manifest_reasons.append("INVALID_OR_EMPTY_QA_CANONICAL_ARM_MANIFEST_SHA256")
        elif q_msha != manifest_sha:
            manifest_mismatch_reasons.append(f"QA_CANONICAL_MANIFEST_SHA256_MISMATCH:{q_msha}!={manifest_sha}")

        if qa_obj.get("qa_signoff_id") != eff_qa_signoff_id:
            custody_reasons.append("QA_SIGNOFF_ID_MISMATCH")
        if qa_obj.get("dossier_id") != eff_dossier_id:
            custody_reasons.append("QA_DOSSIER_ID_MISMATCH")
        if not dossier_sha or qa_obj.get("dossier_archive_sha256") != dossier_sha:
            custody_reasons.append("QA_DOSSIER_ARCHIVE_SHA256_MISMATCH")
        if qa_obj.get("arm_id") != eff_arm_id:
            custody_reasons.append("QA_ARM_ID_MISMATCH")
        if qa_obj.get("product_id") != canonical_product_id:
            custody_reasons.append("QA_PRODUCT_ID_MISMATCH")
        if qa_obj.get("lot_id") != eff_lot_id:
            custody_reasons.append("QA_LOT_ID_MISMATCH")
        if qa_obj.get("bank_id") != eff_bank_id:
            custody_reasons.append("QA_BANK_ID_MISMATCH")
        if qa_obj.get("construct_manifest_sha256") != eff_construct_sha:
            custody_reasons.append("QA_CONSTRUCT_MANIFEST_SHA256_MISMATCH")
        if release_scope_val is not None and raw_qa_scope != release_scope_val:
            custody_reasons.append("QA_APPROVED_RELEASE_SCOPE_MISMATCH")

    # Audit R7-07: Reuse REAL owner qualification tier rule BEFORE issuing or registering authority!
    qual_tier: str | None = None
    if release_scope_val is not None:
        if release_scope_val == "BANK_QUALIFICATION_ONLY":
            qual_tier = "BANK_QUALIFICATION"
        else:
            qual_tier = "AUTOLOGOUS_D1B_PROCESS_QUAL" if tier_family == "AUTOLOGOUS_D1B_AUTO_C" else "LOT_RELEASE_SURROGATE"
        tier_allowed, owner_tier_reasons = v38.is_qualification_tier_allowed_for_product(canonical_product_def, qual_tier)
        if not tier_allowed:
            tier_rule_reasons.extend(
                owner_tier_reasons or [f"FAIL_INAPPLICABLE_QUALIFICATION_TIER:{qual_tier}:{tier_family}"]
            )

    # Audit R7-07: Reuse REAL owner Gate 0V qualification evaluator BEFORE issuing or registering authority!
    owner_eval_verdict: str | None = None
    if isinstance(dossier_obj, dict) and qual_tier is not None and not tier_rule_reasons and not malformed_reasons:
        assay_payload = dossier_obj.get("gate0v_assay_payload")
        if assay_payload is None:
            custody_reasons.append("MISSING_ARCHIVED_GATE0V_ASSAY_PAYLOAD")
        elif not isinstance(assay_payload, dict):
            malformed_reasons.append(f"MALFORMED_GATE0V_ASSAY_PAYLOAD_TYPE:{type(assay_payload).__name__}")
        else:
            if assay_payload.get("lot_id") != eff_lot_id:
                custody_reasons.append("ASSAY_PAYLOAD_LOT_ID_MISMATCH")
            if assay_payload.get("mcb_id") != eff_bank_id:
                custody_reasons.append("ASSAY_PAYLOAD_MCB_ID_MISMATCH")
            if assay_payload.get("product_variant_id") != canonical_product_id:
                custody_reasons.append("ASSAY_PAYLOAD_PRODUCT_ID_MISMATCH")
            if assay_payload.get("qualification_tier") != qual_tier:
                custody_reasons.append(f"ASSAY_PAYLOAD_QUALIFICATION_TIER_MISMATCH:{assay_payload.get('qualification_tier')!r}!={qual_tier!r}")
            tstore_path = store_root / "trusted_qualification_store.json"
            tstore_arg: Path | None = tstore_path if (tstore_path.is_file() and not tstore_path.is_symlink()) else None
            try:
                owner_eval = v38.evaluate_wholegraft_gate0v_and_stress_ap1903(
                    copy.deepcopy(assay_payload),
                    trusted_qualification_store=tstore_arg,
                    openislet_root=resolved_root,
                )
            except (TypeError, ValueError, OverflowError, RecursionError, KeyError) as exc:
                malformed_reasons.append(f"OWNER_GATE0V_EVAL_MALFORMED:{type(exc).__name__}")
                owner_eval = None
            if isinstance(owner_eval, dict):
                owner_eval_verdict = str(owner_eval.get("verdict") or "")
                expected_v = GATE0V_PASS_VERDICTS_BY_TIER.get(qual_tier)
                hard_stops = list(owner_eval.get("hard_stops") or [])
                holds = list(owner_eval.get("holds") or [])
                if (
                    owner_eval.get("gate0v_component_passed") is not True
                    or owner_eval_verdict != expected_v
                    or hard_stops
                    or holds
                ):
                    adverse_qual_reasons.append(f"OWNER_GATE0V_EVALUATOR_REJECTED:{owner_eval_verdict}")
                    for hs in hard_stops[:5]:
                        adverse_qual_reasons.append(f"OWNER_GATE0V_HARD_STOP:{hs}")
                    for hl in holds[:5]:
                        adverse_qual_reasons.append(f"OWNER_GATE0V_HOLD:{hl}")

    # Emit structured fail-closed receipt if ANY failure category triggered (ZERO registration!)
    if empty_registry_reasons:
        return _emit_fail(
            "FAIL_EMPTY_OR_MISSING_QA_ISSUER_REGISTRY",
            "REJECTED_EMPTY_OR_MISSING_QA_ISSUER_REGISTRY",
            "G0V-REGISTRY-FAIL",
            empty_registry_reasons + registry_pin_reasons + issuer_auth_reasons,
        )
    if registry_pin_reasons:
        return _emit_fail(
            "FAIL_QA_ISSUER_REGISTRY_TRUST_PIN_MISMATCH",
            "REJECTED_UNTRUSTED_QA_ISSUER_REGISTRY",
            "G0V-REGISTRY-FAIL",
            registry_pin_reasons + issuer_auth_reasons,
        )
    if malformed_reasons:
        return _emit_fail(
            "FAIL_MALFORMED_ARCHIVED_MEASUREMENT",
            "REJECTED_MALFORMED_ARCHIVED_MEASUREMENT",
            "G0V-MALFORMED-FAIL",
            malformed_reasons + custody_reasons + adverse_qual_reasons,
        )
    if missing_dossier_manifest_reasons:
        return _emit_fail(
            "FAIL_MISSING_DOSSIER_MANIFEST_ATTESTATION",
            "REJECTED_MISSING_MANIFEST_ATTESTATION",
            "G0V-MANIFEST-FAIL",
            missing_dossier_manifest_reasons + custody_reasons,
        )
    if missing_qa_manifest_reasons:
        return _emit_fail(
            "FAIL_MISSING_QA_MANIFEST_ATTESTATION",
            "REJECTED_MISSING_MANIFEST_ATTESTATION",
            "G0V-MANIFEST-FAIL",
            missing_qa_manifest_reasons + custody_reasons,
        )
    if manifest_mismatch_reasons:
        return _emit_fail(
            "FAIL_CANONICAL_MANIFEST_SHA256_MISMATCH",
            "REJECTED_MANIFEST_HASH_MISMATCH",
            "G0V-MANIFEST-FAIL",
            manifest_mismatch_reasons + custody_reasons,
        )
    if issuer_auth_reasons:
        return _emit_fail(
            "FAIL_UNAUTHORIZED_QA_ISSUER",
            "REJECTED_UNAUTHORIZED_QA_ISSUER",
            "G0V-ISSUER-FAIL",
            issuer_auth_reasons + custody_reasons,
        )
    if tier_rule_reasons:
        return _emit_fail(
            "FAIL_INAPPLICABLE_QUALIFICATION_TIER_FOR_PRODUCT_FAMILY",
            "REJECTED_INAPPLICABLE_QUALIFICATION_TIER",
            "G0V-TIER-FAIL",
            tier_rule_reasons + custody_reasons,
        )
    if custody_reasons:
        return _emit_fail(
            "FAIL_PHYSICAL_EVIDENCE_CUSTODY_MISMATCH",
            "REJECTED_CUSTODY_MISMATCH",
            "G0V-CUSTODY-FAIL",
            custody_reasons + adverse_qual_reasons,
        )
    if adverse_qual_reasons:
        return _emit_fail(
            "FAIL_GATE0V_QUALIFICATION_CRITERIA_FAILED",
            "REJECTED_ADVERSE_GATE0V_MEASUREMENT",
            "G0V-QUAL-FAIL",
            adverse_qual_reasons,
            extra={"owner_gate0v_verdict": owner_eval_verdict, "owner_gate0v_qualification_tier": qual_tier},
        )

    # Audit R8-03: Explicit positive authorization invariant BEFORE emitting any authorizing receipt!
    if not (positive_issuer_authorized and positive_reviewer_authorized and bool(qa_issuer_id_val) and bool(qa_reviewer_id_val)):
        return _emit_fail(
            "FAIL_UNAUTHORIZED_QA_ISSUER",
            "REJECTED_UNAUTHORIZED_QA_ISSUER",
            "G0V-ISSUER-FAIL",
            ["FAIL_MISSING_POSITIVE_ISSUER_OR_REVIEWER_AUTHORIZATION"],
        )

    if release_scope_val is None or qual_tier is None:
        return _emit_fail(
            "FAIL_PHYSICAL_EVIDENCE_CUSTODY_MISMATCH",
            "REJECTED_CUSTODY_MISMATCH",
            "G0V-CUSTODY-FAIL",
            ["UNRESOLVED_RELEASE_SCOPE_OR_TIER"],
        )

    if release_scope_val == "BANK_QUALIFICATION_ONLY":
        decision = "PASS_WHOLEGRAFT_BANK_QUALIFICATION"
        authority_scope = "BANK_QUALIFICATION_ONLY"
        bank_qualified = True
        promotion_authorized = False
    else:
        decision = (
            "PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL"
            if tier_family == "AUTOLOGOUS_D1B_AUTO_C"
            else "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE"
        )
        authority_scope = "CLINICAL_LOT_RELEASE"
        bank_qualified = True
        promotion_authorized = True

    reg_prov_mode = str(issuer_reg_obj.get("provenance_mode") or "") if isinstance(issuer_reg_obj, dict) else ""
    trust_prov_mode = str(trust_ctx.get("provenance_mode") or "")
    inst_prov_mode = str(trust_ctx.get("installation_provenance_mode") or "")
    # Audit R10-04: ONLY a genuine owner-provisioned production chain may emit operational wet-lab
    # physical_qualification_complete=True / promotion_authorized=True! Synthetic/plumbing control
    # registries ALWAYS emit strictly typed non-authorizing SYNTHETIC_FIXTURE receipts!
    is_owner_provisioned_production = (
        trust_prov_mode == "OWNER_PROVISIONED_PRODUCTION"
        and inst_prov_mode == "OWNER_PROVISIONED_PRODUCTION_INSTALLATION"
        and reg_prov_mode == "OWNER_PROVISIONED_PRODUCTION_REGISTRY"
        and isinstance(issuer_reg_obj, dict)
        and issuer_reg_obj.get("synthetic_fixture_issuers_forbidden") is True
        and qa_issuer_class_val == "OWNER_PROVISIONED_PRODUCTION"
        and not any(
            tok in s.upper()
            for s in (trust_prov_mode, inst_prov_mode, reg_prov_mode, qa_issuer_class_val, qa_issuer_id_val)
            for tok in _SYNTHETIC_ISSUER_FORBIDDEN_MARKERS_V2_ROUND10
        )
    )

    scope_short_tag = "BANK" if release_scope_val == "BANK_QUALIFICATION_ONLY" else "CLIN"
    rec_body: Dict[str, Any] = {
        "schema_revision": "v2_round5_unified",
        "record_id": _make_canonical_gate0v_record_id_v2_round9(f"G0V:{scope_short_tag}", canonical_product_id, str(eff_lot_id)),
        "gate_source": "GATE-0V",
        "product_id": canonical_product_id,
        "lot_id": str(eff_lot_id),
        "bank_id": str(eff_bank_id),
        "bank_origin": bank_origin,
        "canonical_arm_manifest_sha256": manifest_sha,
        "construct_manifest_sha256": str(eff_construct_sha),
        "evidence_tier": "AUTHENTICATED_ARCHIVED_WETLAB",
        "evidence_class": "OWNER_PROVISIONED_PRODUCTION",
        "operational_wetlab_authority": True,
        "plumbing_control_only": False,
        "decision": decision,
        "authority_scope": authority_scope,
        "bank_qualified": bank_qualified,
        "promotion_authorized": promotion_authorized,
        "physical_qualification_complete": True,
        "modeled_qualification_only": False,
        "custody_verification_mode": "GOVERNED_ON_DISK_OWNER_STORE_AUTHENTICATED",
        "custody_authenticated": True,
        "owner_trust_config_sha256": trust_ctx["config_sha256"],
        "installation_id": trust_ctx["installation_id"],
        "installation_identity_sha256": trust_ctx["installation_identity_sha256"],
        "trust_provenance_mode": trust_prov_mode,
        "qa_issuer_registry_sha256": trust_ctx["qa_issuer_registry_sha256"],
        "qa_issuer_registry_provenance_mode": reg_prov_mode,
        "physical_dossier_id": str(eff_dossier_id),
        "physical_dossier_sha256": dossier_sha,
        "qa_signoff_id": str(eff_qa_signoff_id),
        "qa_signoff_sha256": qa_sha,
        "qa_issuer_id": qa_issuer_id_val,
        "qa_reviewer_id": qa_reviewer_id_val,
        "owner_gate0v_qualification_tier": qual_tier,
        "owner_gate0v_verdict": owner_eval_verdict,
        "lineages_verified": sorted(_GY030_REQUIRED_5_LINEAGES),
        "whole_graft_stressed_tested": True,
        "estimand1_u_esc": parsed_metrics["estimand1_u_esc"],
        "estimand2_u_cond": parsed_metrics["estimand2_u_cond"],
        "caspase_fold_activity": parsed_metrics["caspase_fold_activity"],
        "five_virus_max_fold_vs_wt": parsed_metrics["five_virus_max_fold_vs_wt"],
        "nhs20_cdc_c5b9_u95_pct": parsed_metrics["nhs20_cdc_c5b9_u95_pct"],
    }
    if release_scope_val == "CLINICAL_LOT_RELEASE":
        rec_body["release_authorizing"] = True
    # Audit R10-04, R11-05 & R12-06: Route PASS through the SAME single unified finalizer!
    sealed = _finalize_gate0v_cli_receipt(
        rec_body,
        is_synthetic_plumbing=(not is_owner_provisioned_production),
    )

    # Audit R7-06: Register positive receipt strictly ONCE under a single canonical key (<archive_sha256>.json)!
    issued_dir = store_root / "issued_receipts"
    if issued_dir.is_symlink():
        return _emit_fail(
            "FAIL_PHYSICAL_EVIDENCE_CUSTODY_MISMATCH",
            "REJECTED_CUSTODY_MISMATCH",
            "G0V-CUSTODY-FAIL",
            ["ISSUED_RECEIPTS_DIR_SYMLINK_FORBIDDEN"],
        )
    issued_dir.mkdir(parents=True, exist_ok=True)
    reg_file = issued_dir / f"{sealed['archive_sha256']}.json"
    if reg_file.is_symlink():
        return _emit_fail(
            "FAIL_PHYSICAL_EVIDENCE_CUSTODY_MISMATCH",
            "REJECTED_CUSTODY_MISMATCH",
            "G0V-CUSTODY-FAIL",
            ["ISSUED_RECEIPT_FILE_SYMLINK_FORBIDDEN"],
        )
    serialized = json.dumps(sealed, indent=2, sort_keys=True, ensure_ascii=False, allow_nan=False) + "\n"
    if reg_file.is_file():
        existing_txt = reg_file.read_text(encoding="utf-8")
        if existing_txt != serialized:
            return _emit_fail(
                "FAIL_PHYSICAL_EVIDENCE_CUSTODY_MISMATCH",
                "REJECTED_CUSTODY_MISMATCH",
                "G0V-CUSTODY-FAIL",
                ["ISSUED_RECEIPT_CONFLICTING_OVERWRITE_FORBIDDEN"],
            )
    else:
        tmp_file = issued_dir / f".tmp_{sealed['archive_sha256']}_{_os_g0v.getpid()}.json"
        tmp_file.write_text(serialized, encoding="utf-8")
        _os_g0v.replace(tmp_file, reg_file)
    return sealed, 0


def emit_gate0v_physical_evidence_receipt_v2_round5(
    lookup_request: _AbcMapping[str, Any] | None = None,
    *,
    arm_id: Any = None,
    lot_id: Any = None,
    bank_id: Any = None,
    product_id: Any = None,
    construct_manifest_sha256: Any = None,
    dossier_id: Any = None,
    qa_signoff_id: Any = None,
    expected_dossier_sha256: Any = None,
    expected_qa_signoff_sha256: Any = None,
    expected_canonical_manifest_sha256: Any = None,
    release_scope: Any = None,
    governed_store_root: Path | str | None = None,
    canonical_manifest_path: Path | str | None = None,
    owner_physical_dossier_store: Any = None,
    owner_qa_signoff_store: Any = None,
    owner_qa_issuer_registry: Any = None,
    issued_receipt_store: Any = None,
    canonical_arm_manifest: Any = None,
    canonical_arm_manifest_sha256: Any = None,
    openislet_root: Path | None = None,
) -> Dict[str, Any]:
    """Governed Python wrapper for Gate 0V physical receipt issuance (Audit R7-06 / R7-07 / R7-12 / R12-06).
    STRICTLY REJECTS mutable caller-supplied dict/mapping stores with FAIL_MUTABLE_CALLER_STORE_FORBIDDEN
    and delegates exclusively to on-disk governed store resolution."""
    if any(
        x is not None
        for x in (
            owner_physical_dossier_store,
            owner_qa_signoff_store,
            owner_qa_issuer_registry,
            issued_receipt_store,
        )
    ):
        _tctx_m, _ = _load_and_verify_owner_trust_config_v2_round9(_resolve_openislet_root(openislet_root))
        return _finalize_gate0v_cli_receipt(
            _make_fail_closed_gate0v_custody_receipt_v2_round7(
                decision="FAIL_MUTABLE_CALLER_STORE_FORBIDDEN",
                authority_scope="REJECTED_MUTABLE_CALLER_STORE",
                evidence_tier="UNAUTHENTICATED_FAIL",
                record_prefix="G0V-STORE-FAIL",
                product_id=_safe_str_v2_round8(product_id),
                lot_id=_safe_str_v2_round8(lot_id),
                bank_id=_safe_str_v2_round8(bank_id),
                bank_origin="",
                manifest_sha="",
                construct_manifest_sha256=_safe_str_v2_round8(construct_manifest_sha256),
                dossier_id=_safe_str_v2_round8(dossier_id) or None,
                qa_signoff_id=_safe_str_v2_round8(qa_signoff_id) or None,
                custody_failure_reasons=["CALLER_SUPPLIED_IN_MEMORY_STORE_FORBIDDEN_USE_GOVERNED_STORE_ROOT"],
            ),
            is_synthetic_plumbing=_is_synthetic_plumbing_installation_v2_round13(_tctx_m),
        )
    eff_exp_msha = expected_canonical_manifest_sha256 if expected_canonical_manifest_sha256 is not None else canonical_arm_manifest_sha256
    rec, _rc = issue_gate0v_physical_receipt_from_governed_root(
        lookup_request,
        arm_id=arm_id,
        lot_id=lot_id,
        bank_id=bank_id,
        product_id=product_id,
        construct_manifest_sha256=construct_manifest_sha256,
        dossier_id=dossier_id,
        qa_signoff_id=qa_signoff_id,
        expected_dossier_sha256=expected_dossier_sha256,
        expected_qa_signoff_sha256=expected_qa_signoff_sha256,
        expected_canonical_manifest_sha256=eff_exp_msha,
        release_scope=release_scope,
        governed_store_root=governed_store_root,
        canonical_manifest_path=canonical_manifest_path,
        openislet_root=openislet_root,
    )
    return rec


def _add_wave6_physical_receipt_cli_args_v2_round8(parser: argparse.ArgumentParser) -> None:
    parser.add_argument(
        "--issue-physical-receipt",
        action="store_true",
        help="Resolve separately governed Gate 0V physical dossier, QA sign-off, and QA issuer registry stores on disk and issue a single-key receipt on PASS.",
    )
    parser.add_argument("--governed-store-root", type=Path, default=None, help="Separately governed on-disk Gate 0V store directory")
    parser.add_argument("--canonical-manifest", type=Path, default=None, help="Governed wave6_canonical_arm_manifest.json path on disk (hashed strictly from bytes)")
    parser.add_argument("--lookup-request-json", type=Path, default=None, help="Optional JSON file containing caller lookup anchors only")
    parser.add_argument("--arm-id", type=str, default=None, help="Wave-6 arm ID lookup anchor")
    parser.add_argument("--lot-id", type=str, default=None, help="Lot ID lookup anchor")
    parser.add_argument("--bank-id", type=str, default=None, help="Bank / MCB ID lookup anchor")
    parser.add_argument("--product-id", type=str, default=None, help="Canonical product_variant_id lookup anchor")
    parser.add_argument("--construct-manifest-sha256", type=str, default=None, help="Construct manifest SHA-256 lookup anchor")
    parser.add_argument("--dossier-id", type=str, default=None, help="Governed physical dossier ID lookup anchor")
    parser.add_argument("--qa-signoff-id", type=str, default=None, help="Governed independent QA sign-off ID lookup anchor")
    parser.add_argument("--expected-dossier-sha256", type=str, default=None, help="Optional expected physical dossier archive SHA-256")
    parser.add_argument("--expected-qa-signoff-sha256", type=str, default=None, help="Optional expected QA sign-off archive SHA-256")
    parser.add_argument("--expected-canonical-manifest-sha256", type=str, default=None, help="Optional caller assertion anchor checked against governed manifest bytes")
    parser.add_argument("--release-scope", type=str, default=None, help="Optional caller requested release scope (CLINICAL_LOT_RELEASE or BANK_QUALIFICATION_ONLY)")
    parser.add_argument("--issued-receipt-out", type=Path, default=None, help="Optional path to also write the emitted receipt JSON")


def _run_wave6_physical_receipt_cli_v2_round8(args: argparse.Namespace, *, openislet_root: Path) -> int:
    lookup_req: Any = None
    if args.lookup_request_json is not None:
        loaded_req, req_err = _safe_load_governed_json_v2_round8(args.lookup_request_json)
        if req_err is not None:
            _tctx_cli, _ = _load_and_verify_owner_trust_config_v2_round9(_resolve_openislet_root(openislet_root))
            rec = _finalize_gate0v_cli_receipt(
                _make_fail_closed_gate0v_custody_receipt_v2_round7(
                    decision="FAIL_MALFORMED_ARCHIVED_MEASUREMENT",
                    authority_scope="REJECTED_MALFORMED_ARCHIVED_MEASUREMENT",
                    evidence_tier="UNAUTHENTICATED_FAIL",
                    record_prefix="G0V-MALFORMED-FAIL",
                    product_id=_safe_str_v2_round8(args.product_id),
                    lot_id=_safe_str_v2_round8(args.lot_id),
                    bank_id=_safe_str_v2_round8(args.bank_id),
                    bank_origin="",
                    manifest_sha="",
                    construct_manifest_sha256=_safe_str_v2_round8(args.construct_manifest_sha256),
                    dossier_id=_safe_str_v2_round8(args.dossier_id) or None,
                    qa_signoff_id=_safe_str_v2_round8(args.qa_signoff_id) or None,
                    custody_failure_reasons=[f"LOOKUP_REQUEST_JSON_LOAD_ERROR:{req_err}"],
                ),
                is_synthetic_plumbing=_is_synthetic_plumbing_installation_v2_round13(_tctx_cli),
            )
            serialized = json.dumps(rec, indent=2, sort_keys=True, ensure_ascii=False, allow_nan=False)
            if args.issued_receipt_out is not None:
                args.issued_receipt_out.parent.mkdir(parents=True, exist_ok=True)
                args.issued_receipt_out.write_text(serialized + "\n", encoding="utf-8")
            print(serialized)
            return 3
        lookup_req = loaded_req

    rec, rc = issue_gate0v_physical_receipt_from_governed_root(
        lookup_req,
        arm_id=args.arm_id,
        lot_id=args.lot_id,
        bank_id=args.bank_id,
        product_id=args.product_id,
        construct_manifest_sha256=args.construct_manifest_sha256,
        dossier_id=args.dossier_id,
        qa_signoff_id=args.qa_signoff_id,
        expected_dossier_sha256=args.expected_dossier_sha256,
        expected_qa_signoff_sha256=args.expected_qa_signoff_sha256,
        expected_canonical_manifest_sha256=args.expected_canonical_manifest_sha256,
        release_scope=args.release_scope,
        governed_store_root=args.governed_store_root,
        canonical_manifest_path=args.canonical_manifest,
        openislet_root=openislet_root,
    )
    serialized = json.dumps(rec, indent=2, sort_keys=True, ensure_ascii=False, allow_nan=False)
    if args.issued_receipt_out is not None:
        args.issued_receipt_out.parent.mkdir(parents=True, exist_ok=True)
        args.issued_receipt_out.write_text(serialized + "\n", encoding="utf-8")
    print(serialized)
    return rc


def main() -> int:
    parser = argparse.ArgumentParser(
        description="EXP-031 Round-02 Executable Dual-Evaluator Composite Release Wrapper (legacy wetlab_contract.py AND whole-graft Gate 0V)"
    )
    parser.add_argument("--repo-root", type=Path, default=None, help="Path to OpenIslet science repository (read-only)")
    parser.add_argument("--lot-json", type=Path, default=None, help="Composite measured-lot JSON bundle to evaluate")
    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 and AUTOLOGOUS_D1B_PROCESS_QUAL; deployment prerequisite: independent "
            "QA operator administration and write-restricted storage control."
        ),
    )
    parser.add_argument(
        "--nw08-ocr-json",
        type=Path,
        default=None,
        help=(
            "Optional lot-bound measured-OCR NW-08 record JSON file. In coupled composite release mode, "
            "MUST bind cryptographically to the current composite lot (`lot_id`, `mcb_id`, canonical "
            "`product_variant_id`, lot-declared `nw08_route_id`, current `lot_payload_sha256`, "
            "`measurement_record_id`, `measurement_evidence_sha256`, UTC `measurement_timestamp_utc`, "
            "and canonical `ocr_record_sha256`, plus external `--trusted-qualification-store` "
            "`nw08_ocr_records` verification when active) before gating composite release on live 3D FVM "
            "dispatch_and_solve_nw08_measured_ocr (PASS -> exit 0, FAIL -> exit 3, unbound/stale/mismatched/"
            "ambiguous JSON -> structured HOLD exit 2). Standalone unbound diagnostic CLI: "
            "scripts/verify_iip0043_wholegraft_gate0v_and_calibration.py --dispatch-nw08-ocr <ocr.json>."
        ),
    )
    parser.add_argument("--self-test", action="store_true", help="Run differential unit test suite against live read-only wetlab_contract.py")
    parser.add_argument("--out", type=Path, default=DEFAULT_RECEIPT_PATH, help="Output receipt JSON path for --self-test")
    _add_wave6_physical_receipt_cli_args_v2_round8(parser)
    args = parser.parse_args()

    openislet_root = _resolve_openislet_root(args.repo_root)

    if getattr(args, "issue_physical_receipt", False):
        return _run_wave6_physical_receipt_cli_v2_round8(args, openislet_root=openislet_root)

    if args.lot_json is not None:
        wc_path = openislet_root / "scripts" / "wetlab_contract.py"
        v38_path = _resolve_gate0v_verifier_path()
        try:
            leg_fn = _load_module("openislet_wetlab_contract_ro", wc_path).evaluate_stage0_decision_tree if wc_path.is_file() else None
        except Exception:
            leg_fn = None
        try:
            g0v_fn = _get_v38_module().evaluate_wholegraft_gate0v_and_stress_ap1903 if v38_path.is_file() else None
        except Exception:
            g0v_fn = None
        res, rc = evaluate_composite_lot_file(
            args.lot_json,
            legacy_evaluator=leg_fn,
            gate0v_evaluator=g0v_fn,
            trusted_qualification_store=args.trusted_qualification_store,
            openislet_root=openislet_root,
            nw08_ocr_json_path=args.nw08_ocr_json,
        )
        print(json.dumps(res, indent=2, sort_keys=True, allow_nan=False))
        return rc

    # Default or --self-test: execute differential suite & write receipt
    receipt = run_differential_self_test(openislet_root)
    args.out.parent.mkdir(parents=True, exist_ok=True)
    args.out.write_text(json.dumps(receipt, indent=2) + "\n", encoding="utf-8")
    print(
        f"Composite release self-test | passed={receipt['passed_cases']}/{receipt['total_cases']} | "
        f"legacy_wetlab_untouched={receipt['legacy_wetlab_contract_zero_byte_untouched']} | "
        f"all_passed={receipt['all_passed']}"
    )
    return 0 if receipt["all_passed"] else 1


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