#!/usr/bin/env python3
"""W6-C3 (Provisional Next-Free IIP-0057 / DEC-138 / GATE-36 / GY-035; staging slot iip0057,
explicitly de-collided from live IIP-0048 / DEC-128 GY-009 promoter-scope correction and live
GATE-32 / DEC-130 Islet-SHIELD whole-islet-debris recall): Foundry v2.0 Islet-SHIELD
(Unambiguous off_target_kd_l95_um >= 15.0 uM & >= 15,000x Periodic Selectivity + Mass-Conserving
Coupled TMDD + Mandatory Live GATE-32 Whole-Islet-Debris Recall Co-Prerequisite), Pre-Transplant
Multi-Antigen Inverse Vaccine, GY-021-Clean PE2max INS p.Leu82Ile, and Pruned
Viral-Receptor-Avoidance Cuff v2.0 Verifier.

Pure Python standard library ONLY:
  - ZERO third-party / numpy / scipy / network dependencies during execution
  - ZERO wetlab_contract.py imports (Zero-LIMS-Touch)
  - ZERO ast.Assert statements (byte-identical execution under -B and -O -B)
  - Strict fail-closed JSON decoding (duplicate keys, NaN/Inf, and >1e300 rejected)
  - Release-relative discovery & hash verification of external wave6_canonical_arm_manifest.json
    and wave6_master_contract.json (ZERO hardcoded staging-path fallbacks; < 1e-12 unrounded parity)
  - Consistent free-ligand Langmuir receptor occupancy convention across linear PK, TMDD, & GATE-36
  - Exact 6-state mass-conserving coupled nonlinear TMDD ODE (< 1e-10 mass ledger conservation)
  - Unified v2_round5_unified 14-field evidence schema across collision-free upstream W6-C1 GATE-34
    (explicitly rejecting live GATE-32 role collision), independent current-assay GATE-36-<MODULE>,
    AND mandatory live GATE-32 (DEC-130 / GY-010 PASS_DEBRIS_RECALL_FULL_CREDIT) co-prerequisite for
    SHIELD, with complete canonical-body SHA-256 recomputation, alias-consistent store resolution,
    contradictory producer-flag rejection, coherent authority tuples, exact archive-derived threshold
    evaluation (ZERO threshold-crossing tolerance), & synthetic isolation
  - Deterministic coordinate-based heavy-atom contact counter (<= 4.5 A and <= 4.0 A) on RCSB coords
  - Explicit CLI modes: --standalone vs default REPO_CROSSCHECK (--openislet-root)
  - Supports --check (byte-exact) and --check-portable (semantic + mandatory portable_payload_sha256)

Usage:
  PYTHONDONTWRITEBYTECODE=1 python3 -B scripts/verify_iip0057_foundry_v2_shield_invvax_insl82i_cuffv2.py --standalone
  PYTHONDONTWRITEBYTECODE=1 python3 -B scripts/verify_iip0057_foundry_v2_shield_invvax_insl82i_cuffv2.py --standalone --check
  PYTHONDONTWRITEBYTECODE=1 python3 -O -B scripts/verify_iip0057_foundry_v2_shield_invvax_insl82i_cuffv2.py --standalone --check-portable
"""
from __future__ import annotations

import argparse
import collections
import copy
from decimal import Decimal, InvalidOperation
import hashlib
import json
import math
from pathlib import Path
import re
import sys
from typing import Any, Callable
import unicodedata

sys.dont_write_bytecode = True

GENERATED_DATE = "2026-12-01"
SCHEMA_VERSION = "iip0057_foundry_v2_shield_invvax_insl82i_cuffv2_v0.9.0"

EXPECTED_FASTA_SHA256 = "e64235d3e510715a11a4793acaf99723e4e791bb934fb7d94abaaaa603c285ba"
EXPECTED_FASTA_RECORD_COUNT = 13
EXPECTED_RCSB_COORDS_SHA256 = "fa33b321eb9fd5b3abaa427769c4086716919c712bf288e1966b86a760bb8627"
EXPECTED_ARM_MANIFEST_SHA256 = "0a051b69687bd791feeaf55e97c07d993e27cdd7c453e6e3b67b599d243a4235"
EXPECTED_ARM_MANIFEST_CANONICAL_JSON_SHA256 = "9e84e0b64925f9fdeb9450b364728a4076fa43cf8b46085ba2215722541f0d50"
EXPECTED_MASTER_CONTRACT_SHA256 = "53f90447f1f32213adff883f26d30aa1268f4848e6d3d1d946c03d9c7c8a8b42"
EXPECTED_MASTER_CONTRACT_FILE_SHA256 = "2108aa272bfe657c2767ba0f10961443fa280d5f074a84d5578d42c204fff35a"

# Unified Round-14 producer-owned 14-field evidence record schema (v2_round5_unified)
UPSTREAM_EVIDENCE_SCHEMA_REVISION = "v2_round5_unified"
UPSTREAM_EVIDENCE_REQUIRED_FIELDS = (
    "record_id",
    "gate_source",
    "product_id",
    "lot_id",
    "bank_id",
    "bank_origin",
    "canonical_arm_manifest_sha256",
    "construct_manifest_sha256",
    "evidence_tier",
    "decision",
    "authority_scope",
    "bank_qualified",
    "promotion_authorized",
    "archive_sha256",
)
UPSTREAM_EVIDENCE_BOOL_FIELDS = frozenset({"bank_qualified", "promotion_authorized"})
ALLOWED_BANK_ORIGINS = frozenset({"allogeneic_hiPSC", "autologous_hiPSC", "allogeneic_EnSC"})
ALLOWED_EVIDENCE_TIERS = frozenset({"AUTHENTICATED_ARCHIVED_WETLAB", "SYNTHETIC_FIXTURE"})
ALLOWED_AUTHORITY_SCOPES = frozenset({
    "CLINICAL_LOT_RELEASE",
    "BANK_QUALIFICATION_ONLY",
    "STAGE_LIMITED_SORT_ONLY",
    "COMPONENT_SORT_QUALIFICATION_ONLY",
    "WAVE7_RESERVE_ONLY",
    "SYNTHETIC_SELF_TEST",
    "REJECTED_OR_HELD",
})
# Collision-free Round-14 gate source bindings:
# - Upstream W6-C1 Dual-FailSafe / Hygiene lot-release authority = "GATE-34" (explicitly rejects live "GATE-32" role collision!)
# - Live DEC-130 / GY-010 Islet-SHIELD whole-islet-debris recall co-prerequisite = "GATE-32" (PASS_DEBRIS_RECALL_FULL_CREDIT)
# - W6-C3 module current-assay gates = "GATE-36-SHIELD", "GATE-36-INS", "GATE-36-CUFF", "GATE-36-INVVAX"
CANONICAL_UPSTREAM_GATE34_SOURCE = "GATE-34"
CANONICAL_LIVE_GATE32_DEBRIS_RECALL_SOURCE = "GATE-32"
# Backward-compatible export aliases checked by Wave-6 atomic fold-in rehearsal:
CANONICAL_GATE32_SOURCE = CANONICAL_UPSTREAM_GATE34_SOURCE
ALLOWED_GATE34_UPSTREAM_AUTH_DECISIONS = frozenset({"PASS", "PASS_GATE34_CLINICAL_LOT_RELEASE"})
ALLOWED_GATE32_AUTH_DECISIONS = ALLOWED_GATE34_UPSTREAM_AUTH_DECISIONS
ALLOWED_LIVE_GATE32_DEBRIS_FULL_CREDIT_DECISIONS = frozenset({"PASS_DEBRIS_RECALL_FULL_CREDIT"})
ALLOWED_LIVE_GATE32_DEBRIS_PARTIAL_HOLD_DECISIONS = frozenset({"HOLD_PARTIAL_EPITOPE_COVERAGE_GRADED_CAP"})
LIVE_GATE32_MIN_L95_SUPPRESSED_FRAC = 0.70
LIVE_GATE32_MAX_RESIDUAL_CLASS2_U95_FRAC = 0.30
CANONICAL_GATE36_MODULE_SOURCES: dict[str, str] = {
    "shield": "GATE-36-SHIELD",
    "ins": "GATE-36-INS",
    "cuff": "GATE-36-CUFF",
    "invvax": "GATE-36-INVVAX",
}
CANONICAL_GATE34_MODULE_SOURCES = CANONICAL_GATE36_MODULE_SOURCES

# SHIELD calibrated lower measurement floor (Audit F14: rejects 1e-320 underflow -> inf selectivity)
MIN_CALIBRATED_KD_ON_NM = 1e-6
MIN_CALIBRATED_KD_OFF_UM = 1e-6

# Strict canonical ASCII identifier grammar for INS donor IDs & Gate 34 panel/subject/assay IDs (Audit R7-05 / R8-06 / R9-04)
CANONICAL_DONOR_ID_PATTERN = r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$"
CANONICAL_DONOR_ID_RE = re.compile(CANONICAL_DONOR_ID_PATTERN)
CANONICAL_DONOR_EQUIVALENCE_ORDER = "STRIP_ASCII_SEPARATORS_FIRST_THEN_NORMALIZE_NUMERIC_LEADING_ZEROS"
_DONOR_INVISIBLE_OR_SPACE_RE = re.compile(r"[\s\u00ad\u200b-\u200f\u2028-\u202f\u2060-\u206f\ufeff]+")
_ASCII_DONOR_SEPARATOR_RE = re.compile(r"[._:-]+")
_UNICODE_DASH_CHARS = frozenset({"\u2010", "\u2011", "\u2012", "\u2013", "\u2014", "\u2015", "\u2212", "\u2043", "\u2053"})
INS_DONOR_ISSUER_FIELDS = (
    "donor_issuer_id",
    "hla_registry_issuer",
    "registry_issuer",
    "registry_issuer_id",
    "donor_registry_issuer_id",
    "hla_registry_issuer_id",
    "donor_issuer",
    "issuer_id",
)
DEFAULT_INS_CANONICAL_ISSUER_ID = "OPENISLET_T1D_HLA_BIOREPO_V1"

# Strict 4-state archive-only official statistics provenance labels (Audit R10-03, R11-04 & R12-07 closures)
INS_STATISTICS_DERIVATION_SOURCES = frozenset({
    "AUTHENTICATED_ARCHIVE_ROSTER_VERIFIED",
    "AUTHENTICATED_ARCHIVE_ONLY_CALLER_CONFLICT",
    "SYNTHETIC_FIXTURE_ARCHIVE_SELF_TEST",
    "SYNTHETIC_FIXTURE_ARCHIVE_ONLY_CALLER_CONFLICT",
    "UNVERIFIED_HOLD_NO_AUTHENTICATED_ARCHIVE",
    "UNVERIFIED_HOLD_MISSING_ARCHIVED_ISSUER",
    "UNVERIFIED_HOLD_INCOMPLETE_ARCHIVE",
    "WITHHELD_NO_AUTHENTICATED_ARCHIVE_WITH_INDEPENDENT_FAIL",
    "WITHHELD_INCOMPLETE_ARCHIVE_WITH_INDEPENDENT_FAIL",
    "WITHHELD_INTERNAL_ARCHIVE_CONFLICT",
    "MALFORMED_INPUT",
})
SHIELD_STATISTICS_DERIVATION_SOURCES = frozenset({
    "AUTHENTICATED_ARCHIVE_VERIFIED",
    "AUTHENTICATED_ARCHIVE_ONLY_CALLER_CONFLICT",
    "SYNTHETIC_FIXTURE_ARCHIVE_SELF_TEST",
    "SYNTHETIC_FIXTURE_ARCHIVE_ONLY_CALLER_CONFLICT",
    "UNVERIFIED_HOLD_NO_AUTHENTICATED_ARCHIVE",
    "UNVERIFIED_HOLD_INCOMPLETE_ARCHIVE",
    "WITHHELD_NO_AUTHENTICATED_ARCHIVE_WITH_INDEPENDENT_FAIL",
    "WITHHELD_INCOMPLETE_ARCHIVE_WITH_INDEPENDENT_FAIL",
    "WITHHELD_INTERNAL_ARCHIVE_CONFLICT",
    "MALFORMED_INPUT",
})

# INS governed kit catalogs & per-allele target analytes (UniProt P01308 p.Leu82Ile)
MANDATORY_CPEP_ELISA_KITS = ("Roche Elecsys", "Mercodia", "Siemens")
GOVERNED_CPEP_ELISA_KIT_CATALOGS: dict[str, frozenset[str]] = {
    "Roche Elecsys": frozenset({"ROCHE-03184897190", "ROCHE-07027168190", "03184897190"}),
    "Mercodia": frozenset({"MERCODIA-10-1136-01", "MERCODIA-10-1141-01"}),
    "Siemens": frozenset({"SIEMENS-ADVIA-03649928", "SIEMENS-ATELLICA-10995541", "ADVIA-03649928"}),
}
MANDATORY_INS_HLA_ALLELES = ("HLA-DRB1*04:01", "HLA-A*02:01", "HLA-A*11:01")
MANDATORY_INS_HLA_TARGET_PEPTIDES: dict[str, frozenset[str]] = {
    "HLA-DRB1*04:01": frozenset({"GSLQPLAIEGSLQKRGIV"}),
    "HLA-A*02:01": frozenset({"SLQPLAIEGSL", "LQPLAIEGSL", "PLAIEGSL", "AIEGSLQKRGI"}),
    "HLA-A*11:01": frozenset({"LAIEGSLQK"}),
}

# Cuff v2.0 canonical 3-protein core assembly
CANONICAL_CORE_CUFF_PROTEINS = frozenset({"sCR1_v2", "THBD-M406L", "CD200-ECD"})

# InvVax governed matrix-specific analytical assay registries (strictly disjoint)
GOVERNED_INVVAX_PLASMA_ASSAY_REGISTRY = frozenset({
    "LCMS_INVVAX_PLASMA_V1",
    "LCMS_INVVAX_PLASMA_V2",
    "ELISA_INVVAX_PLASMA_V1",
})
GOVERNED_INVVAX_LYMPH_NODE_ASSAY_REGISTRY = frozenset({
    "LCMS_INVVAX_LYMPH_NODE_V1",
    "LCMS_INVVAX_LYMPH_NODE_V2",
    "IHC_MS_INVVAX_LYMPH_NODE_V1",
})

OCCUPANCY_CONVENTION = "FREE_LIGAND_LANGMUIR_C_FREE_OVER_C_FREE_PLUS_KD"

# Frozen LIMS SHA-256 pins (Zero-LIMS-Touch reference invariants)
FROZEN_LIMS_SHA256 = {
    "scripts/wetlab_contract.py": "331ecd2f2d8602dfceae8b89263d0f360cfadfd0638a46d7d668a376294cfc73",
    "scripts/ingest_wetlab_results.py": "e050593675170515382257ce379449db596c87cc06ffc26d31d128e127630cb1",
    "data/protocols/wetlab_endpoint_contract_v0.8.0.json": "757bc1d9c2722c129cc4fd5962e8995b9f5bc5f7035f8530f5716da9aa2ac26f",
}

# Canonical IUPAC average amino-acid masses (Da), water mass, Kyte-Doolittle & EMBOSS pKa
AA_WEIGHTS: dict[str, float] = {
    "A": 89.0932, "R": 174.2010, "N": 132.1179, "D": 133.1027, "C": 121.1582,
    "E": 147.1293, "Q": 146.1445, "G": 75.0666,  "H": 155.1546, "I": 131.1729,
    "L": 131.1729, "K": 146.1876, "M": 149.2113, "F": 165.1891, "P": 115.1305,
    "S": 105.0926, "T": 119.1192, "W": 204.2252, "Y": 181.1885, "V": 117.1463,
}
WATER_MW = 18.01528
KD_SCALE: dict[str, float] = {
    "A": 1.8, "R": -4.5, "N": -3.5, "D": -3.5, "C": 2.5,
    "Q": -3.5, "E": -3.5, "G": -0.4, "H": -3.2, "I": 4.5,
    "L": 3.8, "K": -3.9, "M": 1.9, "F": 2.8, "P": -1.6,
    "S": -0.8, "T": -0.7, "W": -0.9, "Y": -1.3, "V": 4.2,
}
EMBOSS_PKA: dict[str, float] = {
    "Nterm": 8.6, "Cterm": 3.6,
    "D": 3.9, "E": 4.1, "C": 8.5, "Y": 10.1,
    "H": 6.5, "K": 10.8, "R": 12.5,
}
CODON_TABLE: dict[str, str] = {
    "TTT": "F", "TTC": "F", "TTA": "L", "TTG": "L",
    "CTT": "L", "CTC": "L", "CTA": "L", "CTG": "L",
    "ATT": "I", "ATC": "I", "ATA": "I", "ATG": "M",
    "GTT": "V", "GTC": "V", "GTA": "V", "GTG": "V",
    "TCT": "S", "TCC": "S", "TCA": "S", "TCG": "S",
    "CCT": "P", "CCC": "P", "CCA": "P", "CCG": "P",
    "ACT": "T", "ACC": "T", "ACA": "T", "ACG": "T",
    "GCT": "A", "GCC": "A", "GCA": "A", "GCG": "A",
    "TAT": "Y", "TAC": "Y", "TAA": "*", "TAG": "*",
    "CAT": "H", "CAC": "H", "CAA": "Q", "CAG": "Q",
    "AAT": "N", "AAC": "N", "AAA": "K", "AAG": "K",
    "GAT": "D", "GAC": "D", "GAA": "E", "GAG": "E",
    "TGT": "C", "TGC": "C", "TGA": "*", "TGG": "W",
    "CGT": "R", "CGC": "R", "CGA": "R", "CGG": "R",
    "AGT": "S", "AGC": "S", "AGA": "R", "AGG": "R",
    "GGT": "G", "GGC": "G", "GGA": "G", "GGG": "G",
}

# Live-verified Ensembl GRCh38 human INS canonical CDS (ENST00000381330.5 / NM_000207.3, 333 bp)
INS_GRCH38_CANONICAL_CDS = (
    "ATGGCCCTGTGGATGCGCCTCCTGCCCCTGCTGGCGCTGCTGGCCCTCTGGGGACCTGACCCAGCCGCAGCCTTTGTG"
    "AACCAACACCTGTGCGGCTCACACCTGGTGGAAGCTCTCTACCTAGTGTGCGGGGAACGAGGCTTCTTCTACACACCC"
    "AAGACCCGCCGGGAGGCAGAGGACCTGCAGGTGGGGCAGGTGGAGCTGGGCGGGGGCCCTGGTGCAGGCAGCCTGCAG"
    "CCCTTGGCCCTGGAGGGGTCCCTGCAGAAGCGTGGCATTGTGGAACAATGCTGTACCAGCATCTGCTCCCTCTACCAG"
    "CTGGAGAACTACTGCAACTAG"
)

# Live-verified Ensembl GRCh38 INS coding (-1) strand 243 bp flank (chr11:2159819..2160061:-1; codon 82 = [120:123])
INS_GRCH38_FLANK_MINUS_243BP = (
    "TCCTCCTGTGTCCCTCTGCCTCGCCGCTGTTCCGGAACCTGCTCTGCGCGGCACGTCCTGGCAGTGGGGCAGGTGGAG"
    "CTGGGCGGGGGCCCTGGTGCAGGCAGCCTGCAGCCCTTGGCCCTGGAGGGGTCCCTGCAGAAGCGTGGCATTGTGGAA"
    "CAATGCTGTACCAGCATCTGCTCCCTCTACCAGCTGGAGAACTACTGCAACTAGACGCAGCCCGCAGGCAGCCCCACA"
    "CCCGCCGCC"
)

# Live-verified UniProt P01308 human preproinsulin (110 aa)
UNIPROT_P01308_PREPROINSULIN = (
    "MALWMRLLPLLALLALWGPDPAAAFVNQHLCGSHLVEALYLVCGERGFFYTPKTRREAEDLQVGQVELGGGPGAGSLQPL"
    "ALEGSLQKRGIVEQCCTSICSLYQLENYCN"
)

# Live-verified UniProt P01857-1 secreted human IgG1 Fc WT baseline (EU 221..446, VSP_061818 G446, K447 clipped, 226 aa)
UNIPROT_P01857_1_FC_WT_226AA = (
    "DKTHTCPPCPAPELLGGPSVFLFPPKPKDTLMISRTPEVTCVVVDVSHEDPEVKFNWYVDGVEVHNAKTKPREEQYNSTY"
    "RVVSVLTVLHQDWLNGKEYKCKVSNKALPAPIEKTISKAKGQPREPQVYTLPPSRDELTKNQVSLTCLVKGFYPSDIAVE"
    "WESNGQPENNYKTTPPVLDSDGSFFLYSKLTVDKSRWQQGNVFSCSVMHEALHNHYTQKSLSLSPG"
)

# Live-verified ClinicalTrials.gov v2 registry snapshot (queried 2026-11-30; indication/sponsor terms audited)
PINNED_CLINICAL_TRIALS_SNAPSHOT: dict[str, dict[str, Any]] = {
    "NCT06783309": {
        "platform": "CNP-103 (COUR PLGA multi-Ag: preproinsulin, GAD65, IGRP, ZnT8)",
        "indication": "Newly diagnosed Type 1 Diabetes (NOT islet transplant recipients)",
        "status": "RECRUITING",
        "phases": ["PHASE1", "PHASE2"],
        "enrollment": 72,
        "posted_results": False,
        "whyStopped": None,
    },
    "NCT06001177": {
        "platform": "KAN-101 (Anokion pGal Ph2 SYNNERGY)",
        "indication": "Celiac disease (gluten challenge; NOT T1D)",
        "status": "COMPLETED",
        "phases": ["PHASE2"],
        "enrollment": 55,
        "posted_results": True,
        "primary_outcome_note": "Primary histological outcome did NOT show statistically significant benefit.",
        "whyStopped": None,
    },
    "NCT04248855": {
        "platform": "KAN-101 (Anokion pGal Ph1 ACeD)",
        "indication": "Celiac disease (gluten challenge; NOT T1D)",
        "status": "COMPLETED",
        "phases": ["PHASE1"],
        "enrollment": 41,
        "posted_results": True,
        "pk_note": "Celiac cohort plasma t1/2 geometric mean 31.72 min with high variability (PMID:37329900).",
        "whyStopped": None,
    },
    "NCT05574010": {
        "platform": "KAN-101 (ACeD-it)",
        "indication": "Celiac disease",
        "status": "TERMINATED",
        "phases": ["PHASE1", "PHASE2"],
        "enrollment": 128,
        "posted_results": False,
        "whyStopped": "Sponsor decision",
    },
    "NCT06798454": {
        "platform": "PVT201 (Parvus Navacim Ph1)",
        "indication": "Primary Biliary Cholangitis / Primary Sclerosing Cholangitis (PBC/PSC — NOT T1D)",
        "status": "COMPLETED",
        "phases": ["PHASE1"],
        "enrollment": 24,
        "posted_results": False,
        "whyStopped": None,
    },
    "NCT05018585": {
        "platform": "DIAGNODE-3 (rhGAD65-alum)",
        "indication": "Type 1 Diabetes (HLA-DR3-DQ2)",
        "status": "TERMINATED",
        "phases": ["PHASE3"],
        "enrollment": 321,
        "posted_results": False,
        "whyStopped": "Stopped for futility.",
    },
    "NCT04524949": {
        "platform": "IMCY-0098 (IMPACT proinsulin)",
        "indication": "Type 1 Diabetes",
        "status": "TERMINATED",
        "phases": ["PHASE2"],
        "enrollment": 110,
        "posted_results": True,
        "whyStopped": "No efficacy at primary analysis after 1 year. Long term follow-up stopped.",
    },
    "NCT05425446": {
        "platform": "DONQ52 (Chugai anti-HLA-DQ2.5/gluten Fab Ph1)",
        "indication": "Celiac disease (domain-transfer comparator)",
        "status": "COMPLETED",
        "phases": ["PHASE1"],
        "enrollment": 56,
        "posted_results": False,
        "whyStopped": None,
    },
    "NCT07239336": {
        "platform": "DONQ52 (Chugai anti-HLA-DQ2.5/gluten Fab Ph2)",
        "indication": "Celiac disease (domain-transfer comparator)",
        "status": "RECRUITING",
        "phases": ["PHASE2"],
        "enrollment": 92,
        "posted_results": False,
        "whyStopped": None,
    },
    "NCT05937581": {
        "platform": "CSL040 (CSL Behring sCR1 Ph1)",
        "indication": "Healthy volunteers (complement inhibition)",
        "status": "COMPLETED",
        "phases": ["PHASE1"],
        "enrollment": 62,
        "posted_results": False,
        "whyStopped": None,
    },
}


# ---------------------------------------------------------------------------
# Fail-Closed Core Helpers & Strict JSON Decoding (ZERO assert statements!)
# ---------------------------------------------------------------------------
def require_cond(cond: bool, msg: str) -> None:
    if not cond:
        raise RuntimeError(msg)


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


def sha256_str(text: str) -> str:
    return sha256_bytes(text.encode("utf-8"))


def sha256_file(path: Path) -> str:
    return sha256_bytes(path.read_bytes())


def _canonical_json_sha256(obj: Any) -> str:
    return sha256_str(json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False))


def compute_canonical_record_sha256(record: dict[str, Any]) -> str:
    """Compute canonical JSON SHA-256 of the COMPLETE evidence record body excluding archive_sha256."""
    body = {k: v for k, v in record.items() if k != "archive_sha256"}
    return _canonical_json_sha256(body)


def seal_evidence_record(record_body: dict[str, Any]) -> dict[str, Any]:
    """Return a deep copy sealed with exact canonical JSON SHA-256 archive_sha256."""
    check_strictly_finite(record_body, "evidence_record")
    body = copy.deepcopy({k: v for k, v in record_body.items() if k != "archive_sha256"})
    body["archive_sha256"] = compute_canonical_record_sha256(body)
    return body


def _clopper_pearson_upper_95_pct(k: int, n: int) -> float:
    """Exact one-sided 95% Clopper-Pearson upper confidence bound (percent) for k/n."""
    require_cond(isinstance(k, int) and isinstance(n, int) and 0 <= k <= n and n > 0, f"Invalid Clopper-Pearson args: {k}/{n}")
    if k == 0:
        return (1.0 - (0.05 ** (1.0 / n))) * 100.0
    if k == n:
        return 100.0
    log_n_fact = math.lgamma(n + 1)

    def _lower_tail(p: float) -> float:
        if p <= 0.0:
            return 1.0
        if p >= 1.0:
            return 0.0
        lp = math.log(p)
        lq = math.log1p(-p)
        log_terms = [
            log_n_fact - math.lgamma(i + 1) - math.lgamma(n - i + 1) + i * lp + (n - i) * lq
            for i in range(k + 1)
        ]
        m = max(log_terms)
        return math.exp(m) * sum(math.exp(t - m) for t in log_terms)

    lo, hi = k / n, 1.0
    for _ in range(80):
        mid = 0.5 * (lo + hi)
        if _lower_tail(mid) > 0.05:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi) * 100.0


def _is_valid_nonzero_sha256(val: Any) -> bool:
    if not isinstance(val, str) or len(val) != 64:
        return False
    if any(ch not in "0123456789abcdef" for ch in val):
        return False
    return len(set(val)) > 1


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


def _parse_strict_finite_float(token: str) -> float:
    try:
        dec = Decimal(token)
    except InvalidOperation as exc:
        raise ValueError(f"Invalid JSON float token: {token!r}") from exc
    if not dec.is_finite() or dec.copy_abs() > Decimal("1e300"):
        raise ValueError(f"Non-finite or overflowing JSON decimal token: {token!r}")
    val = float(token)
    if not math.isfinite(val) or abs(val) > 1e300:
        raise ValueError(f"Non-finite or overflowing JSON float: {token!r}")
    return val


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


def _reject_duplicate_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
    out: dict[str, Any] = {}
    for k, v in pairs:
        if k in out:
            raise ValueError(f"Duplicate JSON object key rejected fail-closed: {k!r}")
        out[k] = v
    return out


def check_strictly_finite(obj: Any, label: str, path: str = "$") -> None:
    if isinstance(obj, bool) or obj is None or isinstance(obj, str):
        return
    if isinstance(obj, int):
        if abs(obj) > 10 ** 300:
            raise ValueError(f"Overflowing int in {label} at {path}")
        return
    if isinstance(obj, float):
        if not math.isfinite(obj) or abs(obj) > 1e300:
            raise ValueError(f"Non-finite or overflowing float in {label} at {path}: {obj!r}")
        return
    if isinstance(obj, dict):
        for k, v in obj.items():
            if not isinstance(k, str):
                raise ValueError(f"Non-string dict key in {label} at {path}: {type(k).__name__}")
            check_strictly_finite(v, label, f"{path}.{k}")
        return
    if isinstance(obj, (list, tuple)):
        for i, v in enumerate(obj):
            check_strictly_finite(v, label, f"{path}[{i}]")
        return
    raise ValueError(f"Unsupported non-JSON type in {label} at {path}: {type(obj).__name__}")


def load_strict_json_text(raw: str, label: str) -> Any:
    obj = json.loads(
        raw,
        object_pairs_hook=_reject_duplicate_keys,
        parse_constant=_reject_nonfinite_constant,
        parse_float=_parse_strict_finite_float,
        parse_int=_parse_strict_finite_int,
    )
    check_strictly_finite(obj, label)
    return obj


def load_strict_json(path: Path) -> Any:
    if not path.is_file():
        raise FileNotFoundError(f"Missing required JSON file: {path}")
    return load_strict_json_text(path.read_text(encoding="utf-8"), path.name)


def revcomp(s: str) -> str:
    return s.translate(str.maketrans("ACGTacgt", "TGCAtgca"))[::-1]


def parse_fasta_text(text: str) -> dict[str, tuple[str, str]]:
    out: dict[str, tuple[str, str]] = {}
    cur_id: str | None = None
    cur_hdr: str = ""
    chunks: list[str] = []
    for raw_ln in text.splitlines():
        ln = raw_ln.strip()
        if not ln:
            continue
        if ln.startswith(">"):
            if cur_id is not None:
                require_cond(cur_id not in out, f"Duplicate FASTA record ID: {cur_id}")
                out[cur_id] = (cur_hdr, "".join(chunks))
            cur_hdr = ln[1:]
            cur_id = cur_hdr.split("|")[0].strip()
            chunks = []
        else:
            chunks.append(ln)
    if cur_id is not None:
        require_cond(cur_id not in out, f"Duplicate FASTA record ID: {cur_id}")
        out[cur_id] = (cur_hdr, "".join(chunks))
    return out


# ---------------------------------------------------------------------------
# Release-Relative External Manifest & Master Contract Loader (Fail-Closed!)
# ---------------------------------------------------------------------------
def resolve_release_shared_paths(
    repo_root: Path,
    *,
    shared_dir: Path | None = None,
    master_contract_path: Path | None = None,
    arm_manifest_path: Path | None = None,
) -> tuple[Path, Path]:
    """Resolve canonical master contract and arm manifest strictly release-relatively (ZERO absolute-path fallbacks)."""
    if master_contract_path is not None:
        contract_p = master_contract_path.resolve()
    elif shared_dir is not None:
        contract_p = (shared_dir.resolve() / "wave6_master_contract.json")
    else:
        candidates = (
            repo_root.parent / "shared" / "wave6_master_contract.json",
            repo_root / "shared" / "wave6_master_contract.json",
            repo_root / "data" / "protocols" / "wave6_master_contract.json",
        )
        found = next((p.resolve() for p in candidates if p.is_file()), None)
        if found is None:
            raise FileNotFoundError(
                "Missing canonical Wave-6 master contract in release-relative paths: "
                + ", ".join(str(p) for p in candidates)
            )
        contract_p = found

    if arm_manifest_path is not None:
        manifest_p = arm_manifest_path.resolve()
    elif shared_dir is not None and master_contract_path is None:
        manifest_p = (shared_dir.resolve() / "wave6_canonical_arm_manifest.json")
    else:
        # Resolve sibling manifest strictly relative to contract_p via canonical_arm_manifest_relpath
        if not contract_p.is_file():
            raise FileNotFoundError(f"Missing canonical Wave-6 master contract (fail-closed): {contract_p}")
        raw_mc = load_strict_json(contract_p)
        rel = raw_mc.get("canonical_arm_manifest_relpath") if isinstance(raw_mc, dict) else None
        if not isinstance(rel, str) or not rel.strip() or Path(rel).is_absolute() or ".." in Path(rel).parts:
            raise ValueError(f"Invalid or non-relative canonical_arm_manifest_relpath: {rel!r}")
        manifest_p = (contract_p.parent / rel).resolve()
    return contract_p, manifest_p


def load_and_verify_arm_manifest(path: Path) -> tuple[dict[str, Any], str]:
    if not path.is_file():
        raise FileNotFoundError(f"Missing canonical arm manifest (fail-closed): {path}")
    raw_sha = sha256_file(path)
    require_cond(
        raw_sha == EXPECTED_ARM_MANIFEST_SHA256,
        f"Canonical arm manifest SHA-256 mismatch: got {raw_sha}, expected {EXPECTED_ARM_MANIFEST_SHA256}",
    )
    obj = load_strict_json(path)
    require_cond(isinstance(obj, dict) and isinstance(obj.get("arms"), dict), "Malformed canonical arm manifest")
    canon_sha = _canonical_json_sha256(obj)
    require_cond(
        canon_sha == EXPECTED_ARM_MANIFEST_CANONICAL_JSON_SHA256,
        f"Canonical arm manifest JSON digest mismatch: got {canon_sha}, expected {EXPECTED_ARM_MANIFEST_CANONICAL_JSON_SHA256}",
    )
    arm_a = obj["arms"].get("A")
    require_cond(isinstance(arm_a, dict), "Canonical arm manifest missing Design A")
    for flag in ("r4_eligible", "shield_eligible", "invvax_eligible", "cuff_v2_eligible", "exvivo_rest_eligible", "ins_l82i_eligible"):
        require_cond(arm_a.get(flag) is False, f"Design A invariant violated in manifest: {flag}={arm_a.get(flag)!r}")
    cuff_inv = obj.get("cuff_v2_canonical_inventory")
    require_cond(isinstance(cuff_inv, dict) and cuff_inv.get("core_immobilized_proteins_count") == 3, "Cuff v2 canonical inventory mismatch")
    ev_schema = obj.get("upstream_lot_evidence_record_schema_v1")
    require_cond(
        isinstance(ev_schema, dict)
        and ev_schema.get("schema_revision") == UPSTREAM_EVIDENCE_SCHEMA_REVISION
        and tuple(ev_schema.get("required_fields", [])) == UPSTREAM_EVIDENCE_REQUIRED_FIELDS,
        "Canonical arm manifest upstream_lot_evidence_record_schema_v1 mismatch",
    )
    cgs = ev_schema.get("canonical_gate_sources")
    require_cond(
        isinstance(cgs, dict)
        and cgs.get("gate34") == CANONICAL_UPSTREAM_GATE34_SOURCE
        and cgs.get("live_gate32_shield_debris_recall") == CANONICAL_LIVE_GATE32_DEBRIS_RECALL_SOURCE
        and cgs.get("gate36_shield") == CANONICAL_GATE36_MODULE_SOURCES["shield"]
        and cgs.get("gate36_ins") == CANONICAL_GATE36_MODULE_SOURCES["ins"]
        and cgs.get("gate36_cuff") == CANONICAL_GATE36_MODULE_SOURCES["cuff"]
        and cgs.get("gate36_invvax") == CANONICAL_GATE36_MODULE_SOURCES["invvax"],
        "Canonical arm manifest canonical_gate_sources mismatch",
    )
    g32_pol = ev_schema.get("live_gate32_debris_recall_policy")
    require_cond(
        isinstance(g32_pol, dict)
        and g32_pol.get("gate_source") == CANONICAL_LIVE_GATE32_DEBRIS_RECALL_SOURCE
        and g32_pol.get("required_verdict") == "PASS_DEBRIS_RECALL_FULL_CREDIT"
        and g32_pol.get("min_l95_suppressed_frac") == LIVE_GATE32_MIN_L95_SUPPRESSED_FRAC
        and g32_pol.get("max_residual_class2_u95_frac") == LIVE_GATE32_MAX_RESIDUAL_CLASS2_U95_FRAC
        and g32_pol.get("unrelated_recall_preserved_required") is True,
        "Canonical arm manifest live_gate32_debris_recall_policy mismatch",
    )
    return obj, raw_sha


def load_and_verify_master_contract(path: Path, expected_manifest_sha: str) -> tuple[dict[str, Any], str, str]:
    if not path.is_file():
        raise FileNotFoundError(f"Missing canonical Wave-6 master contract (fail-closed): {path}")
    file_sha = sha256_file(path)
    require_cond(
        file_sha == EXPECTED_MASTER_CONTRACT_FILE_SHA256,
        f"Master contract file SHA-256 mismatch: got {file_sha}, expected {EXPECTED_MASTER_CONTRACT_FILE_SHA256}",
    )
    obj = load_strict_json(path)
    require_cond(isinstance(obj, dict), "Malformed master contract")
    declared_hash = obj.get("contract_sha256")
    require_cond(isinstance(declared_hash, str), "Master contract missing contract_sha256")
    payload_copy = copy.deepcopy(obj)
    payload_copy.pop("contract_sha256", None)
    recomputed_hash = sha256_str(json.dumps(payload_copy, sort_keys=True, separators=(",", ":")))
    require_cond(
        recomputed_hash == declared_hash and recomputed_hash == EXPECTED_MASTER_CONTRACT_SHA256,
        f"Master contract SHA-256 mismatch: recomputed={recomputed_hash}, declared={declared_hash}, expected={EXPECTED_MASTER_CONTRACT_SHA256}",
    )
    require_cond(
        obj.get("canonical_arm_manifest_sha256") == expected_manifest_sha,
        f"Master contract manifest pin mismatch: {obj.get('canonical_arm_manifest_sha256')} != {expected_manifest_sha}",
    )
    inv = obj.get("strict_invariants")
    require_cond(isinstance(inv, dict), "Master contract missing strict_invariants")
    require_cond(inv.get("h1_allo_locked_pct") == 88.0, f"Master contract H1 lock violated: {inv.get('h1_allo_locked_pct')}")
    require_cond(inv.get("design_a_zero_post_transplant_drugs_and_exvivo_rest") is True, "Master contract Design A zero-drug/rest invariant violated")
    require_cond(inv.get("design_a_zero_additional_biologics_beyond_v080_catalase_hydrogel") is True, "Master contract Design A zero-additional-biologics invariant violated")
    require_cond(inv.get("design_a_contains_preexisting_p04040_catalase_hydrogel") is True, "Master contract Design A catalase disclosure violated")
    require_cond(inv.get("design_a_strictly_zero_protein_biologics") is False, "Master contract Design A strict protein biologic flag violated")
    require_cond(inv.get("design_a_preexisting_catalase_hydrogel_exception_disclosed") is True, "Design A catalase disclosure missing")
    require_cond(inv.get("design_a_invariant_tuple") == [0.88, 0.78, 0.57, 0.69], "Master contract Design A tuple violated")
    require_cond(inv.get("gy_021_enforced_pe2max_only_no_pe4max_mlh1dn") is True, "Master contract GY-021 invariant violated")
    require_cond(inv.get("invvax_stage0_prior_bounded_10_to_17_pct") is True, "Master contract InvVax prior invariant violated")
    require_cond(inv.get("synthetic_fixtures_cannot_authorize_clinical_promotion") is True, "Synthetic fixture isolation invariant missing")
    return obj, recomputed_hash, file_sha


# ---------------------------------------------------------------------------
# Biophysical Profile Utilities (Pure Stdlib)
# ---------------------------------------------------------------------------
def calc_mw_da(seq: str, n_disulfides: int = 0) -> float:
    mw = sum(AA_WEIGHTS[a] for a in seq) - (len(seq) - 1) * WATER_MW
    return mw - 2.01588 * n_disulfides


def calc_rh_nm(mw_da: float) -> float:
    return 0.066 * (mw_da ** (1.0 / 3.0))


def calc_charge(seq: str, ph: float, n_disulfides: int = 0) -> float:
    pos = 1.0 / (1.0 + 10.0 ** (ph - EMBOSS_PKA["Nterm"]))
    neg = 1.0 / (1.0 + 10.0 ** (EMBOSS_PKA["Cterm"] - ph))
    free_cys = max(0, seq.count("C") - 2 * n_disulfides)
    for aa in ("H", "K", "R"):
        pos += seq.count(aa) / (1.0 + 10.0 ** (ph - EMBOSS_PKA[aa]))
    for aa in ("D", "E", "Y"):
        neg += seq.count(aa) / (1.0 + 10.0 ** (EMBOSS_PKA[aa] - ph))
    neg += free_cys / (1.0 + 10.0 ** (EMBOSS_PKA["C"] - ph))
    return pos - neg


def calc_pi(seq: str, n_disulfides: int = 0) -> float:
    lo, hi = 0.0, 14.0
    for _ in range(60):
        mid = 0.5 * (lo + hi)
        if calc_charge(seq, mid, n_disulfides) > 0.0:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)


def biophysical_profile(
    seq: str,
    n_disulfides: int = 0,
    disulfide_status: str = "EXPECTED_TOPOLOGY_PENDING_EXPRESSED_LCMS_ELLMAN_QC",
) -> dict[str, Any]:
    mw_da = calc_mw_da(seq, n_disulfides)
    rh = calc_rh_nm(mw_da)
    pi = calc_pi(seq, n_disulfides)
    q74 = calc_charge(seq, 7.4, n_disulfides)
    gravy = sum(KD_SCALE[a] for a in seq) / len(seq)
    nglyc = [m.start() + 1 for m in re.finditer(r"(?=N[^P][ST])", seq)]
    ng_ns = [f"{m.group(0)}@{m.start()+1}" for m in re.finditer(r"N[GS]", seq)]
    dp_sites = [m.start() + 1 for m in re.finditer(r"DP", seq)]
    dibasic = [f"{m.group(0)}@{m.start()+1}" for m in re.finditer(r"[KR][KR]", seq)]
    cys_n = seq.count("C")
    unpaired_cys = cys_n - 2 * n_disulfides
    return {
        "length_aa": len(seq),
        "mw_kda": round(mw_da / 1000.0, 4),
        "rh_nm_spherical": round(rh, 3),
        "pI_emboss": round(pi, 3),
        "charge_pH74": round(q74, 3),
        "gravy": round(gravy, 4),
        "cys_total": cys_n,
        "expected_intramolecular_disulfides": n_disulfides,
        "expected_unpaired_cys": unpaired_cys,
        "disulfide_status": disulfide_status,
        "met_count": seq.count("M"),
        "trp_count": seq.count("W"),
        "nglyc_sequon_count": len(nglyc),
        "deamidation_NG_NS_count": len(ng_ns),
        "dp_cleavage_count": len(dp_sites),
        "dibasic_count": len(dibasic),
    }


def count_non_native_junction_kmers(native_core: str, conjugated_seq: str) -> int:
    wt_kmers: set[str] = set()
    for k in (8, 9, 10, 11):
        for i in range(len(native_core) - k + 1):
            wt_kmers.add(native_core[i : i + k])
    n_native = len(native_core)
    cnt = 0
    for k in (8, 9, 10, 11):
        for i in range(len(conjugated_seq) - k + 1):
            if i + k > n_native:
                if conjugated_seq[i : i + k] not in wt_kmers:
                    cnt += 1
    return cnt


# ---------------------------------------------------------------------------
# Deterministic Coordinate-Based RCSB Heavy-Atom Contact Counter (Zero Hardcoding)
# ---------------------------------------------------------------------------
def _count_heavy_atom_contacts(
    binder_atoms: list[list[Any]],
    target_atoms: list[list[Any]],
    cutoff_A: float,
) -> tuple[int, dict[str, int], dict[str, int]]:
    c2 = cutoff_A * cutoff_A
    total = 0
    per_t: dict[str, int] = collections.Counter()
    per_b: dict[str, int] = collections.Counter()
    for bc, br, ba, _, bx, by, bz in binder_atoms:
        for tc, tr, ta, _, tx, ty, tz in target_atoms:
            dx = bx - tx
            dy = by - ty
            dz = bz - tz
            if dx * dx + dy * dy + dz * dz <= c2:
                total += 1
                per_t[f"{ta}{tr}"] += 1
                per_b[f"{bc}:{ba}{br}"] += 1
    return total, dict(per_t), dict(per_b)


def compute_deterministic_pdb_contacts(coords_path: Path) -> dict[str, Any]:
    """Compute exact heavy-atom interface contacts directly from verified RCSB CC0-1.0 3D coordinates."""
    require_cond(coords_path.is_file(), f"Missing RCSB coordinate subset file: {coords_path}")
    actual_sha = sha256_file(coords_path)
    require_cond(
        actual_sha == EXPECTED_RCSB_COORDS_SHA256,
        f"RCSB coordinate subset SHA-256 mismatch: {actual_sha} != {EXPECTED_RCSB_COORDS_SHA256}",
    )
    payload = load_strict_json(coords_path)
    require_cond(isinstance(payload, dict) and isinstance(payload.get("complexes"), dict), "Malformed RCSB coords JSON")

    complex_results: dict[str, Any] = {}
    for key, entry in payload["complexes"].items():
        b_atoms = entry["binder_atoms"]
        a_atoms = entry["dq_alpha_atoms"]
        beta_atoms = entry["dq_beta_atoms"]
        p_atoms = entry["peptide_atoms"]
        cdr_ranges = entry.get("cdr_ranges") or {}

        cut_out: dict[str, Any] = {}
        for cut_lbl, cut_val in (("le_4p5A", 4.5), ("le_4p0A", 4.0)):
            n_a, _, _ = _count_heavy_atom_contacts(b_atoms, a_atoms, cut_val)
            n_b, _, _ = _count_heavy_atom_contacts(b_atoms, beta_atoms, cut_val)
            n_p, pep_res_counts, b_pep_counts = _count_heavy_atom_contacts(b_atoms, p_atoms, cut_val)
            tot = n_a + n_b + n_p
            require_cond(tot > 0, f"Zero heavy-atom contacts computed for {key} at {cut_val} A")
            sorted_pep = sorted(pep_res_counts.items(), key=lambda x: (-x[1], x[0]))
            max_res, max_cnt = sorted_pep[0] if sorted_pep else ("none", 0)
            cdr_breakdown: dict[str, int] = {}
            for loop_name, spec in cdr_ranges.items():
                lch, rlo, rhi = spec[0], int(spec[1]), int(spec[2])
                cnt_loop = 0
                for bk, v in b_pep_counts.items():
                    bc, bres = bk.split(":")
                    rnum = int(bres[1:])
                    if bc == lch and rlo <= rnum <= rhi:
                        cnt_loop += v
                cdr_breakdown[loop_name] = cnt_loop

            rec_cut: dict[str, Any] = {
                "cutoff_A": cut_val,
                "total_contact_pairs": tot,
                "dq_alpha_pairs": n_a,
                "dq_beta_pairs": n_b,
                "peptide_pairs": n_p,
                "peptide_share_pct": round(100.0 * n_p / tot, 2),
                "dq_alpha_share_pct": round(100.0 * n_a / tot, 2),
                "dq_beta_share_pct": round(100.0 * n_b / tot, 2),
                "distinct_peptide_residues_contacted": len(pep_res_counts),
                "max_single_pep_residue": max_res,
                "max_single_pep_residue_pairs": max_cnt,
                "max_single_pep_residue_share_pct": round(100.0 * max_cnt / n_p, 2) if n_p else 0.0,
            }
            if cdr_breakdown:
                rec_cut["cdr_peptide_contact_pairs"] = cdr_breakdown
                if "CDR_H3" in cdr_breakdown and n_p:
                    rec_cut["cdr_h3_share_of_peptide_contacts_pct"] = round(100.0 * cdr_breakdown["CDR_H3"] / n_p, 2)
            cut_out[cut_lbl] = rec_cut

        complex_results[key] = {
            "pdb_id": entry["pdb_id"],
            "source_cif_sha256": entry["source_cif_sha256"],
            "license": entry["license"],
            "primary_pmid": entry["primary_pmid"],
            "format": entry["format"],
            "comparator_disclosure": entry["comparator_disclosure"],
            "peptide_sequence_resolved": entry["peptide_sequence_resolved"],
            "peptide_range": entry["peptide_range"],
            "mhc_alpha_range": entry["mhc_alpha_range"],
            "mhc_beta_range": entry["mhc_beta_range"],
            "contacts_le_4p5A": cut_out["le_4p5A"],
            "contacts_le_4p0A": cut_out["le_4p0A"],
        }

    require_cond(
        complex_results["8W84_DONQ52_parent_DQ25_glia_a2"]["contacts_le_4p5A"]["peptide_pairs"] == 141
        and complex_results["8W84_DONQ52_parent_DQ25_glia_a2"]["contacts_le_4p5A"]["total_contact_pairs"] == 341,
        "8W84 coordinate contact check failed",
    )
    require_cond(
        complex_results["6DFX_T1D3_TCR_DQ8_InsB_R3_copy1"]["contacts_le_4p5A"]["peptide_pairs"] == 102
        and complex_results["6DFX_T1D3_TCR_DQ8_InsB_R3_copy1"]["contacts_le_4p5A"]["total_contact_pairs"] == 340,
        "6DFX coordinate contact check failed",
    )
    require_cond(
        complex_results["6XP6_3C11_Fab_DQ25_glia_a2_copy1"]["contacts_le_4p5A"]["peptide_pairs"] == 66
        and complex_results["6XP6_3C11_Fab_DQ25_glia_a2_copy1"]["contacts_le_4p5A"]["total_contact_pairs"] == 298,
        "6XP6 coordinate contact check failed",
    )
    require_cond(
        complex_results["8VD2_ET650_4_TCR_DQ8_HIP"]["contacts_le_4p5A"]["peptide_pairs"] == 123
        and complex_results["8VD2_ET650_4_TCR_DQ8_HIP"]["contacts_le_4p5A"]["total_contact_pairs"] == 398,
        "8VD2 coordinate contact check failed",
    )

    u_entry = payload["unbound_comparators"]["8VDU_DQ8_HIP6_unbound_crest_copy1"]
    mhc_atoms = u_entry["mhc_atoms"]
    by_res: dict[int, list[list[Any]]] = collections.defaultdict(list)
    for atom in u_entry["peptide_atoms"]:
        by_res[int(atom[1])].append(atom)
    crest_res: list[str] = []
    buried_res: list[str] = []
    c2_45 = 4.5 * 4.5
    for rseq in sorted(by_res):
        r_atoms = by_res[rseq]
        aa = r_atoms[0][2]
        n_mhc = 0
        for _, _, _, _, px, py, pz in r_atoms:
            for _, _, _, _, mx, my, mz in mhc_atoms:
                dx, dy, dz = px - mx, py - my, pz - mz
                if dx * dx + dy * dy + dz * dz <= c2_45:
                    n_mhc += 1
        ratio = n_mhc / max(1, len(r_atoms))
        if ratio >= 5.0:
            buried_res.append(f"{aa}{rseq}")
        else:
            crest_res.append(f"{aa}{rseq}")

    unbound_8vdu = {
        "pdb_id": u_entry["pdb_id"],
        "source_cif_sha256": u_entry["source_cif_sha256"],
        "license": u_entry["license"],
        "primary_pmid": u_entry["primary_pmid"],
        "format": u_entry["format"],
        "comparator_disclosure": u_entry["comparator_disclosure"],
        "peptide_sequence_resolved": u_entry["peptide_sequence_resolved"],
        "n_residues": len(by_res),
        "tcr_facing_crest_residues": crest_res,
        "mhc_buried_anchor_residues": buried_res,
    }

    return {
        "coordinate_subset_relpath": "data/structures/rcsb_shield_interface_coords_v0.9.0.json",
        "coordinate_subset_sha256": actual_sha,
        "computation_mode": "DETERMINISTIC_3D_HEAVY_ATOM_COORDINATE_COUNTER_ZERO_HARDCODED_COUNTS",
        "comparator_scope_note": (
            "All five structures are deposited RCSB CC0-1.0 experimental comparator complexes (celiac Fabs or TCRs). "
            "They define structural design benchmarks and do NOT establish mass, specificity, Fc silencing, or binding "
            "affinity of the yet-to-be-expressed Foundry v2.0 bispecific Fab."
        ),
        "complexes": complex_results,
        "unbound_comparators": {"8VDU_DQ8_HIP6_unbound_crest_copy1": unbound_8vdu},
    }


# ---------------------------------------------------------------------------
# PART A: Converged Periodic SHIELD PK, Mass-Conserving TMDD & >=15 uM Gate
# ---------------------------------------------------------------------------
def renkin_glomerular_sieving(rh_nm: float, r_pore_nm: float = 5.2, charge_cutoff_nm: float = 3.6) -> float:
    if rh_nm >= charge_cutoff_nm:
        return 0.0
    lam = rh_nm / r_pore_nm
    if lam >= 1.0:
        return 0.0
    steric = (1.0 - lam) ** 2
    drag = 1.0 - 2.104 * lam + 2.09 * (lam ** 3) - 0.95 * (lam ** 5)
    return max(0.0, min(1.0, steric * drag))


def free_ligand_ro(c_free_nM: float, kd_nM: float) -> float:
    """Single consistent free-ligand modeled receptor occupancy convention: C_free / (C_free + Kd)."""
    if c_free_nM <= 0.0 or kd_nM <= 0.0:
        return 0.0
    return min(1.0, max(0.0, c_free_nM / (c_free_nM + kd_nM)))


def _solve_4x4_linear(A_in: list[list[float]], b_in: list[float]) -> list[float]:
    A = [list(row) for row in A_in]
    b = list(b_in)
    for i in range(4):
        piv = max(range(i, 4), key=lambda r: abs(A[r][i]))
        require_cond(abs(A[piv][i]) > 1e-15, "Singular 4x4 periodic fixed-point matrix")
        A[i], A[piv] = A[piv], A[i]
        b[i], b[piv] = b[piv], b[i]
        div = A[i][i]
        for j in range(i, 4):
            A[i][j] /= div
        b[i] /= div
        for r in range(4):
            if r != i:
                fac = A[r][i]
                for j in range(i, 4):
                    A[r][j] -= fac * A[i][j]
                b[r] -= fac * b[i]
    return b


def simulate_linear_periodic_pk(
    name: str,
    mw_kda: float,
    rh_eff_nm: float,
    dose_mg: float,
    tau_days: float,
    route: str,
    F_sc: float,
    ka_per_day: float,
    V1_L: float,
    V2_L: float,
    Q_L_per_day: float,
    CL_L_per_day: float,
    kp_dln: float,
    k_ln_eq_per_day: float,
    dt_days: float = 1.0 / 24.0,
    conv_tol: float = 1e-10,
    max_cycles: int = 500,
    parameter_basis: str = "modeled_linear_pk_pending_nhp_human_pk",
) -> dict[str, Any]:
    """Exact converged periodic steady-state 4-state 2-compartment + dLN free-concentration PK solver.

    Solves BOTH:
      (1) Closed-form periodic fixed point (I - M) y* = M d via exact 4x4 RK4 cycle propagator M
      (2) Cycle-by-cycle iteration until relative cycle-to-cycle change < 1e-10
    and computes modeled receptor occupancy via the single consistent free_ligand_ro convention.
    """
    dose_nmol = (dose_mg / mw_kda) * 1e3
    k10 = CL_L_per_day / V1_L
    k12 = Q_L_per_day / V1_L
    k21 = Q_L_per_day / V2_L

    tr = k10 + k12 + k21
    det = k10 * k21
    disc = math.sqrt(max(0.0, tr * tr - 4.0 * det))
    alpha = 0.5 * (tr + disc)
    beta = 0.5 * (tr - disc)
    t_half_alpha_h = (math.log(2.0) / alpha) * 24.0
    t_half_beta_d = math.log(2.0) / beta

    steps_per_cycle = int(round(tau_days / dt_days))
    dt = tau_days / steps_per_cycle

    def deriv(y0: float, y1: float, y2: float, y3: float) -> tuple[float, float, float, float]:
        c1 = y1 / V1_L
        return (
            -ka_per_day * y0,
            ka_per_day * y0 - (k10 + k12) * y1 + k21 * y2,
            k12 * y1 - k21 * y2,
            k_ln_eq_per_day * (kp_dln * c1 - y3),
        )

    def rk4_one_cycle(y_start: list[float]) -> tuple[list[float], float, float]:
        y0, y1, y2, y3 = y_start
        c1_pk = y1 / V1_L
        cln_pk = y3
        for _ in range(steps_per_cycle):
            k1_0, k1_1, k1_2, k1_3 = deriv(y0, y1, y2, y3)
            k2_0, k2_1, k2_2, k2_3 = deriv(
                y0 + 0.5 * dt * k1_0, y1 + 0.5 * dt * k1_1,
                y2 + 0.5 * dt * k1_2, y3 + 0.5 * dt * k1_3,
            )
            k3_0, k3_1, k3_2, k3_3 = deriv(
                y0 + 0.5 * dt * k2_0, y1 + 0.5 * dt * k2_1,
                y2 + 0.5 * dt * k2_2, y3 + 0.5 * dt * k2_3,
            )
            k4_0, k4_1, k4_2, k4_3 = deriv(
                y0 + dt * k3_0, y1 + dt * k3_1,
                y2 + dt * k3_2, y3 + dt * k3_3,
            )
            f = dt / 6.0
            y0 = max(0.0, y0 + f * (k1_0 + 2.0 * k2_0 + 2.0 * k3_0 + k4_0))
            y1 = max(0.0, y1 + f * (k1_1 + 2.0 * k2_1 + 2.0 * k3_1 + k4_1))
            y2 = max(0.0, y2 + f * (k1_2 + 2.0 * k2_2 + 2.0 * k3_2 + k4_2))
            y3 = max(0.0, y3 + f * (k1_3 + 2.0 * k2_3 + 2.0 * k3_3 + k4_3))
            c1_now = y1 / V1_L
            if c1_now > c1_pk:
                c1_pk = c1_now
            if y3 > cln_pk:
                cln_pk = y3
        return [y0, y1, y2, y3], c1_pk, cln_pk

    d_vec = [0.0, dose_nmol, 0.0, 0.0] if route == "IV" else [dose_nmol * F_sc, 0.0, 0.0, 0.0]

    # Cycle 1 readout
    y_c1, _, _ = rk4_one_cycle(d_vec)

    # Method 1: Exact 4x4 periodic fixed point (I - M) y_trough = M d
    M = [[0.0] * 4 for _ in range(4)]
    for col in range(4):
        e = [1.0 if i == col else 0.0 for i in range(4)]
        y_col, _, _ = rk4_one_cycle(e)
        for row in range(4):
            M[row][col] = y_col[row]
    A_mat = [[(1.0 if r == c else 0.0) - M[r][c] for c in range(4)] for r in range(4)]
    rhs = [sum(M[r][c] * d_vec[c] for c in range(4)) for r in range(4)]
    y_trough = _solve_4x4_linear(A_mat, rhs)
    y_trough = [max(0.0, v) for v in y_trough]
    y_post = [y_trough[i] + d_vec[i] for i in range(4)]
    y_check, c1_cmax_ss, cln_cmax_ss = rk4_one_cycle(y_post)
    fixed_pt_rel_err = max(
        abs(y_check[i] - y_trough[i]) / max(1e-12, abs(y_trough[i]))
        for i in range(4)
    )
    require_cond(fixed_pt_rel_err < 1e-10, f"Periodic fixed point did not converge for {name}: err={fixed_pt_rel_err}")

    # Method 2: Cycle-by-cycle iteration to < 1e-10 relative cycle-to-cycle change
    y_it = [0.0, 0.0, 0.0, 0.0]
    cycles_to_converge = 0
    c1_pk_it = 0.0
    for cyc in range(1, max_cycles + 1):
        y_prev = list(y_it)
        y_it, c1_pk_it, _ = rk4_one_cycle([y_it[i] + d_vec[i] for i in range(4)])
        cycles_to_converge = cyc
        rel = max(abs(y_it[i] - y_prev[i]) / max(1e-12, abs(y_it[i])) for i in range(4))
        if rel < conv_tol:
            break
    require_cond(
        abs(c1_pk_it - c1_cmax_ss) / max(1e-12, c1_cmax_ss) < 1e-8,
        f"Periodic fixed-point vs cycle-iteration mismatch for {name}: {c1_cmax_ss} vs {c1_pk_it}",
    )

    c1_tr_ss = y_trough[1] / V1_L
    cln_tr_ss = y_trough[3]
    ro_c1: dict[str, float] = {}
    ro_ss: dict[str, float] = {}
    for kd in (0.1, 1.0, 5.0, 10.0):
        key = f"Kd_{kd:g}nM"
        ro_c1[key] = round(100.0 * free_ligand_ro(y_c1[3], kd), 4)
        ro_ss[key] = round(100.0 * free_ligand_ro(cln_tr_ss, kd), 4)

    sieving = renkin_glomerular_sieving(rh_eff_nm)
    return {
        "modality": name,
        "parameter_basis": parameter_basis,
        "occupancy_convention": OCCUPANCY_CONVENTION,
        "mw_kda": mw_kda,
        "rh_eff_nm": rh_eff_nm,
        "renkin_sieving_coeff": round(sieving, 4),
        "predicted_renal_CL_L_per_day": round(sieving * 172.8, 3),
        "simulated_CL_L_per_day": CL_L_per_day,
        "kp_dln": kp_dln,
        "dose_mg": dose_mg,
        "route": route,
        "tau_days": tau_days,
        "t_half_alpha_h": round(t_half_alpha_h, 3),
        "t_half_beta_days": round(t_half_beta_d, 4),
        "t_half_beta_min": round(t_half_beta_d * 1440.0, 2),
        "periodic_convergence_cycles_le_1e10": cycles_to_converge,
        "periodic_fixed_point_rel_err": float(f"{fixed_pt_rel_err:.2e}"),
        "periodic_ss_Cmax_plasma_nM": round(c1_cmax_ss, 4),
        "periodic_ss_Cmax_dLN_nM": round(cln_cmax_ss, 4),
        "periodic_ss_trough_plasma_nM": round(c1_tr_ss, 4),
        "periodic_ss_trough_dLN_nM": round(cln_tr_ss, 4),
        "cycle1_trough_dLN_RO_pct": ro_c1,
        "periodic_ss_trough_dLN_RO_pct": ro_ss,
    }


def simulate_coupled_nonlinear_tmdd_periodic(
    label: str,
    dose_mg: float,
    tau_days: float,
    kd_off_nM: float,
    kd_on_nM: float = 1.0,
    r_off_nmol: float = 16.60539,
    k_int_off_per_day: float = 0.5,
    b_max_dln_nM: float = 0.083,
    k_int_on_per_day: float = 0.5,
    v_dln_L: float = 0.05,
    mw_kda: float = 150.0,
    F_sc: float = 0.68,
    ka_per_day: float = 0.25,
    V1_L: float = 3.0,
    V2_L: float = 2.8,
    Q_L_per_day: float = 0.50,
    CL_L_per_day: float = 0.092,
    kp_dln: float = 0.25,
    k_ln_eq_per_day: float = 1.0,
    dt_days: float = 1.0 / 24.0,
    conv_tol: float = 1e-10,
    max_cycles: int = 200,
) -> dict[str, Any]:
    """Mass-conserving 6-state coupled nonlinear Michaelis-Menten TMDD periodic ODE (R2-14 closure).

    State vector in nmol: (A_sc, A_central, A_periph, A_dln, A_eliminated_lin, A_eliminated_tmdd).
      - Exact balanced central <-> dLN exchange counterterm: J_cent_to_dln = k_ln_eq * V_dln * (Kp_dln * c1 - cln)
        subtracted from dA_central/dt and added to dA_dln/dt (sum = 0).
      - Single-charged dLN on-target internalization: F_on = Vmax_on_nmol_d * cln / (Kd_on + cln)
        subtracted ONLY from dA_dln/dt and credited to dA_eliminated_tmdd/dt (ZERO double-charging!).
      - Systemic off-target internalization: F_off = Vmax_off_nmol_d * c1 / (Kd_off + c1)
        subtracted from dA_central/dt and credited to dA_eliminated_tmdd/dt.
      - Linear elimination: k10 * A_central subtracted from dA_central/dt and credited to dA_eliminated_lin/dt.
    Verifies exact mass conservation:
      A_sc + A_central + A_periph + A_dln + A_eliminated_lin + A_eliminated_tmdd == Dose_cumulative
    to < 1e-10 relative error at EVERY dosing cycle, using the single free_ligand_ro convention.
    """
    dose_nmol = (dose_mg / mw_kda) * 1e3
    bioavail_dose_nmol = dose_nmol * F_sc
    k10 = CL_L_per_day / V1_L
    k12 = Q_L_per_day / V1_L
    k21 = Q_L_per_day / V2_L
    vmax_off_nmol_d = r_off_nmol * k_int_off_per_day
    vmax_on_nmol_d = b_max_dln_nM * k_int_on_per_day * v_dln_L
    steps = int(round(tau_days / dt_days))
    dt = tau_days / steps

    def deriv(y: list[float]) -> tuple[float, float, float, float, float, float]:
        a_sc, a_c, a_p, a_ln, _, _ = y
        c1 = max(0.0, a_c / V1_L)
        cln = max(0.0, a_ln / v_dln_L)
        j_cent_to_dln = k_ln_eq_per_day * v_dln_L * (kp_dln * c1 - cln)
        f_off = vmax_off_nmol_d * free_ligand_ro(c1, kd_off_nM)
        f_on = vmax_on_nmol_d * free_ligand_ro(cln, kd_on_nM)
        f_lin = k10 * a_c
        return (
            -ka_per_day * a_sc,
            ka_per_day * a_sc - f_lin - k12 * a_c + k21 * a_p - j_cent_to_dln - f_off,
            k12 * a_c - k21 * a_p,
            j_cent_to_dln - f_on,
            f_lin,
            f_off + f_on,
        )

    y = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
    dose_cumulative = 0.0
    max_rel_mass_err = 0.0
    final_rel_mass_err = 0.0
    cyc_used = 0
    c1_pk = 0.0
    rel = 1.0
    for cyc in range(1, max_cycles + 1):
        prev = (y[0], y[1], y[2], y[3])
        y[0] += bioavail_dose_nmol
        dose_cumulative += bioavail_dose_nmol
        c1_pk = y[1] / V1_L
        for _ in range(steps):
            k1 = deriv(y)
            k2 = deriv([y[i] + 0.5 * dt * k1[i] for i in range(6)])
            k3 = deriv([y[i] + 0.5 * dt * k2[i] for i in range(6)])
            k4 = deriv([y[i] + dt * k3[i] for i in range(6)])
            f = dt / 6.0
            y = [y[i] + f * (k1[i] + 2.0 * k2[i] + 2.0 * k3[i] + k4[i]) for i in range(6)]
            require_cond(all(v >= -1e-12 for v in y), f"Negative TMDD mass state for {label}: {y}")
            c1_now = y[1] / V1_L
            if c1_now > c1_pk:
                c1_pk = c1_now
        total_mass = sum(y)
        final_rel_mass_err = abs(total_mass - dose_cumulative) / max(1e-12, dose_cumulative)
        if final_rel_mass_err > max_rel_mass_err:
            max_rel_mass_err = final_rel_mass_err
        require_cond(
            final_rel_mass_err < 1e-10,
            f"TMDD mass ledger conservation violated at cycle {cyc} for {label}: rel_err={final_rel_mass_err}",
        )
        cyc_used = cyc
        rel = max(abs(y[i] - prev[i]) / max(1e-12, abs(y[i])) for i in range(4))
        if rel < conv_tol:
            break

    require_cond(rel < conv_tol, f"Coupled TMDD ODE failed to converge for {label}: rel={rel}")
    c1_tr = y[1] / V1_L
    cln_tr = y[3] / v_dln_L
    on_ro_pct = 100.0 * free_ligand_ro(cln_tr, kd_on_nM)
    off_pk_ro_pct = 100.0 * free_ligand_ro(c1_pk, kd_off_nM)
    off_tr_ro_pct = 100.0 * free_ligand_ro(c1_tr, kd_off_nM)
    off_dln_ro_pct = 100.0 * free_ligand_ro(cln_tr, kd_off_nM)

    return {
        "scenario": label,
        "occupancy_convention": OCCUPANCY_CONVENTION,
        "dose_mg": dose_mg,
        "tau_days": tau_days,
        "kd_on_nM": kd_on_nM,
        "kd_off_uM": round(kd_off_nM / 1000.0, 4),
        "r_off_nmol": round(r_off_nmol, 3),
        "b_max_dln_nM": b_max_dln_nM,
        "v_dln_L": v_dln_L,
        "k_int_per_day": k_int_off_per_day,
        "converged_cycles": cyc_used,
        "periodic_Cmax_plasma_nM": round(c1_pk, 4),
        "periodic_trough_plasma_nM": round(c1_tr, 4),
        "periodic_trough_dLN_nM": round(cln_tr, 4),
        "on_target_dLN_trough_RO_pct": round(on_ro_pct, 4),
        "off_target_plasma_peak_RO_pct": round(off_pk_ro_pct, 4),
        "off_target_plasma_trough_RO_pct": round(off_tr_ro_pct, 4),
        "off_target_dLN_trough_RO_pct": round(off_dln_ro_pct, 4),
        "passes_5p6_peak_gate": off_pk_ro_pct <= 5.6,
        "mass_ledger_nmol": {
            "A_sc_nmol": round(y[0], 6),
            "A_central_nmol": round(y[1], 6),
            "A_periph_nmol": round(y[2], 6),
            "A_dln_nmol": round(y[3], 6),
            "A_eliminated_lin_nmol": round(y[4], 6),
            "A_eliminated_tmdd_nmol": round(y[5], 6),
            "dose_cumulative_nmol": round(dose_cumulative, 6),
            "max_rel_mass_conservation_err": float(f"{max_rel_mass_err:.3e}"),
            "final_rel_mass_conservation_err": float(f"{final_rel_mass_err:.3e}"),
            "mass_conserved_lt_1e10": max_rel_mass_err < 1e-10,
        },
    }


def compute_converged_pan_dq_selectivity_proof(pk_by_name: dict[str, dict[str, Any]]) -> dict[str, Any]:
    """Converged periodic steady-state pan-DQ modeled receptor occupancy audit (unambiguous >= 15,000 nM / >= 15,000x)."""
    regimens = {
        "Fab_KiH_LALAPG_LS_150mg_Q28D": pk_by_name["v2.0_Fab_KiH_LALAPG_LS_150kDa_SC_150mg_Q28D"],
        "Fab_KiH_LALAPG_LS_300mg_Q28D": pk_by_name["v2.0_Fab_KiH_LALAPG_LS_150kDa_SC_300mg_Q28D"],
        "Fab_KiH_LALAPG_LS_300mg_Q84D": pk_by_name["v2.0_Fab_KiH_LALAPG_LS_150kDa_SC_300mg_Q84D_Quarterly"],
    }
    selectivity_grid = (100, 500, 1000, 5000, 10000, 15000, 20000)
    tables: dict[str, list[dict[str, Any]]] = {}
    for rlabel, pkr in regimens.items():
        cmax_pl = pkr["periodic_ss_Cmax_plasma_nM"]
        tr_pl = pkr["periodic_ss_trough_plasma_nM"]
        tr_dln = pkr["periodic_ss_trough_dLN_nM"]
        rows = []
        for mult in selectivity_grid:
            kd_off_nM = float(mult)  # At Kd_on = 1.0 nM
            kd_off_uM = kd_off_nM / 1000.0
            ro_cmax_pl = 100.0 * free_ligand_ro(cmax_pl, kd_off_nM)
            ro_tr_pl = 100.0 * free_ligand_ro(tr_pl, kd_off_nM)
            ro_tr_dln = 100.0 * free_ligand_ro(tr_dln, kd_off_nM)
            # Single unambiguous conservative selectivity policy:
            # off_target_kd_l95_um >= 15.0 uM (15,000 nM) AND conservative ratio (off_target_kd_l95_um * 1000 / on_target_kd_u95_nm) >= 15,000x
            if ro_cmax_pl > 5.6 or ro_tr_dln > 1.1 or kd_off_nM < 15000.0 or mult < 15000:
                verdict = "FAIL"
            else:
                verdict = "PASS"
            rows.append({
                "selectivity_fold_at_Kd_on_1nM": mult,
                "Kd_off_nM": kd_off_nM,
                "Kd_off_uM": kd_off_uM,
                "modeled_pan_DQ_offtarget_RO_plasma_Cmax_pct": round(ro_cmax_pl, 4),
                "modeled_pan_DQ_offtarget_RO_plasma_trough_pct": round(ro_tr_pl, 4),
                "modeled_pan_DQ_offtarget_RO_dLN_trough_pct": round(ro_tr_dln, 4),
                "gate34_shield_sel_verdict": verdict,
            })
        tables[rlabel] = rows

    cmax_300 = regimens["Fab_KiH_LALAPG_LS_300mg_Q28D"]["periodic_ss_Cmax_plasma_nM"]
    razor_kd_off_uM = round(cmax_300 * (100.0 - 5.6) / 5.6 / 1000.0, 4)
    row_map_300 = {r["selectivity_fold_at_Kd_on_1nM"]: r for r in tables["Fab_KiH_LALAPG_LS_300mg_Q28D"]}
    row_map_150 = {r["selectivity_fold_at_Kd_on_1nM"]: r for r in tables["Fab_KiH_LALAPG_LS_150mg_Q28D"]}

    require_cond(abs(cmax_300 - 611.3188) < 1e-3, f"300mg Q28D converged Cmax mismatch: {cmax_300}")
    require_cond(abs(row_map_300[10000]["modeled_pan_DQ_offtarget_RO_plasma_Cmax_pct"] - 5.7610) < 1e-3, "300mg 10uM must be 5.7610%")
    require_cond(row_map_300[10000]["gate34_shield_sel_verdict"] == "FAIL", "300mg 10uM MUST FAIL")
    require_cond(row_map_150[5000]["gate34_shield_sel_verdict"] == "FAIL", "150mg 5uM MUST FAIL")
    require_cond(row_map_150[10000]["gate34_shield_sel_verdict"] == "FAIL", "150mg 10uM MUST FAIL under unified >=15,000x / >=15 uM policy")
    require_cond(abs(row_map_300[15000]["modeled_pan_DQ_offtarget_RO_plasma_Cmax_pct"] - 3.9159) < 1e-3, "300mg 15uM peak RO mismatch")
    require_cond(row_map_300[15000]["gate34_shield_sel_verdict"] == "PASS", "300mg 15uM MUST PASS")
    require_cond(abs(razor_kd_off_uM - 10.3051) < 1e-2, f"Razor threshold mismatch: {razor_kd_off_uM}")

    systemic_dq_nmol = (1e11 * 1e5) / 6.02214076e23 * 1e9
    return {
        "occupancy_convention": OCCUPANCY_CONVENTION,
        "systemic_healthy_apc_HLA_DQ_pool_nmol": round(systemic_dq_nmol, 2),
        "systemic_HLA_DQ_conc_in_3L_plasma_nM": round(systemic_dq_nmol / 3.0, 2),
        "periodic_converged_300mg_Q28D_plasma_Cmax_nM": cmax_300,
        "periodic_converged_300mg_Q28D_plasma_trough_nM": regimens["Fab_KiH_LALAPG_LS_300mg_Q28D"]["periodic_ss_trough_plasma_nM"],
        "periodic_converged_300mg_Q28D_dLN_trough_nM": regimens["Fab_KiH_LALAPG_LS_300mg_Q28D"]["periodic_ss_trough_dLN_nM"],
        "legacy_100x_gate_fails_with_modeled_pan_dq_ro_pct": [
            row_map_150[100]["modeled_pan_DQ_offtarget_RO_plasma_Cmax_pct"],
            row_map_300[100]["modeled_pan_DQ_offtarget_RO_plasma_Cmax_pct"],
        ],
        "withdrawn_10uM_300mg_Q28D_converged_peak_RO_pct": row_map_300[10000]["modeled_pan_DQ_offtarget_RO_plasma_Cmax_pct"],
        "withdrawn_10uM_300mg_Q28D_verdict": "FAIL_WITHDRAWN_EXCEEDS_5P6_PCT_AT_PERIODIC_STEADY_STATE",
        "withdrawn_5uM_150mg_Q28D_verdict": "FAIL_WITHDRAWN_EXCEEDS_5P6_PCT_AT_PERIODIC_STEADY_STATE",
        "exact_razor_Kd_off_uM_at_300mg_for_5p6_pct": razor_kd_off_uM,
        "unambiguous_selectivity_policy": "off_target_kd_l95_um >= 15.0 uM (15,000 nM) AND selectivity_ratio_l95 >= 15,000x ((off_target_kd_l95_um * 1000) / on_target_kd_u95_nm >= 15,000); worst-case peak off-target RO computed with lower 95% bound off_target_kd_l95_um <= 5.6%",
        "elevated_gate34_shield_sel_min_Kd_off_l95_nM": 15000.0,
        "elevated_gate34_shield_sel_min_Kd_off_l95_uM": 15.0,
        "elevated_gate34_shield_sel_min_selectivity_fold": 15000.0,
        "elevated_15uM_300mg_Q28D_peak_plasma_RO_pct": row_map_300[15000]["modeled_pan_DQ_offtarget_RO_plasma_Cmax_pct"],
        "elevated_15uM_300mg_Q28D_safety_margin_below_5p6_pp": round(5.6 - row_map_300[15000]["modeled_pan_DQ_offtarget_RO_plasma_Cmax_pct"], 4),
        "elevated_15uM_300mg_Q28D_plasma_trough_RO_pct": row_map_300[15000]["modeled_pan_DQ_offtarget_RO_plasma_trough_pct"],
        "elevated_15uM_300mg_Q28D_dLN_trough_RO_pct": row_map_300[15000]["modeled_pan_DQ_offtarget_RO_dLN_trough_pct"],
        "compartment_separation_note": (
            "Plasma peak, plasma trough, and dLN trough modeled healthy-APC off-target receptor occupancies are strictly separated "
            "with strict physical ordering peak_free_nm >= plasma_trough_free_nm >= dln_trough_free_nm > 0: "
            "at 300 mg Q28D and off_target_kd_l95_um = 10 uM, plasma peak = 5.7610% (FAIL), plasma trough = 4.1329%, dLN trough = 1.0827%; "
            "under the unambiguous off_target_kd_l95_um >= 15.0 uM (15,000 nM) AND >= 15,000x conservative selectivity floor, plasma peak = 3.9159% "
            "(PASS, +1.6841 pp margin), plasma trough = 2.7937%, dLN trough = 0.7244%."
        ),
        "selectivity_occupancy_tables": tables,
    }


def verify_part_a(fasta_records: dict[str, tuple[str, str]], coords_path: Path) -> dict[str, Any]:
    pk_list = [
        simulate_linear_periodic_pk(
            "v1.3_Miniprotein_6.5kDa_IV_150mg_Q28D_CL195", 6.50, 1.24, 150.0, 28.0,
            "IV", 1.0, 24.0, 3.0, 1.5, 150.0, 195.0, 0.80, 48.0, dt_days=1.0 / (24.0 * 30.0),
            parameter_basis="modeled_v13_total_clearance_195_L_per_day",
        ),
        simulate_linear_periodic_pk(
            "v1.3_Miniprotein_6.5kDa_SC_150mg_Q28D_CL195", 6.50, 1.24, 150.0, 28.0,
            "SC", 0.65, 8.4, 3.0, 1.5, 150.0, 195.0, 0.80, 48.0, dt_days=1.0 / (24.0 * 30.0),
            parameter_basis="modeled_v13_total_clearance_195_L_per_day",
        ),
        simulate_linear_periodic_pk(
            "v1.3_Miniprotein_6.5kDa_SC_10mg_DAILY_Q1D_CL195", 6.50, 1.24, 10.0, 1.0,
            "SC", 0.65, 8.4, 3.0, 1.5, 150.0, 195.0, 0.80, 48.0, dt_days=1.0 / (24.0 * 60.0),
            parameter_basis="modeled_v13_total_clearance_195_L_per_day",
        ),
        simulate_linear_periodic_pk(
            "v1.3_Miniprotein_6.5kDa_SC_10mg_DAILY_Q1D_PureRenal_CL52p7", 6.50, 1.24, 10.0, 1.0,
            "SC", 0.65, 8.4, 3.0, 1.5, 150.0, 52.704, 0.80, 48.0, dt_days=1.0 / (24.0 * 60.0),
            parameter_basis="sensitivity_pure_renal_filtration_52p7_L_per_day_no_catabolism",
        ),
        simulate_linear_periodic_pk(
            "v1.3_Miniprotein_6.5kDa_SC_150mg_Q28D_PureRenal_CL52p7", 6.50, 1.24, 150.0, 28.0,
            "SC", 0.65, 8.4, 3.0, 1.5, 150.0, 52.704, 0.80, 48.0, dt_days=1.0 / (24.0 * 30.0),
            parameter_basis="sensitivity_pure_renal_filtration_52p7_L_per_day_no_catabolism",
        ),
        simulate_linear_periodic_pk(
            "v2.0_Fab_KiH_LALAPG_LS_150kDa_SC_150mg_Q28D", 150.0, 5.20, 150.0, 28.0,
            "SC", 0.68, 0.25, 3.0, 2.8, 0.50, 0.092, 0.25, 1.0, dt_days=1.0 / 24.0,
            parameter_basis="modeled_FcRn_LS_45p66d_parameter_pending_NHP_human_PK",
        ),
        simulate_linear_periodic_pk(
            "v2.0_Fab_KiH_LALAPG_LS_150kDa_SC_300mg_Q28D", 150.0, 5.20, 300.0, 28.0,
            "SC", 0.68, 0.25, 3.0, 2.8, 0.50, 0.092, 0.25, 1.0, dt_days=1.0 / 24.0,
            parameter_basis="modeled_FcRn_LS_45p66d_parameter_pending_NHP_human_PK",
        ),
        simulate_linear_periodic_pk(
            "v2.0_Fab_KiH_LALAPG_LS_150kDa_SC_300mg_Q84D_Quarterly", 150.0, 5.20, 300.0, 84.0,
            "SC", 0.68, 0.25, 3.0, 2.8, 0.50, 0.092, 0.25, 1.0, dt_days=1.0 / 24.0,
            parameter_basis="modeled_FcRn_LS_45p66d_parameter_pending_NHP_human_PK",
        ),
        simulate_linear_periodic_pk(
            "v2.0_Fab_KiH_LALAPG_LS_150kDa_SC_300mg_Q84D_Stress_2xCL_Kp0p15", 150.0, 5.20, 300.0, 84.0,
            "SC", 0.68, 0.25, 3.0, 2.8, 0.50, 0.184, 0.15, 1.0, dt_days=1.0 / 24.0,
            parameter_basis="stress_sensitivity_2x_CL_and_low_Kp_dLN_0p15",
        ),
    ]
    pk_by_name = {r["modality"]: r for r in pk_list}

    require_cond(pk_by_name["v1.3_Miniprotein_6.5kDa_SC_150mg_Q28D_CL195"]["periodic_ss_trough_dLN_RO_pct"]["Kd_1nM"] == 0.0, "v1.3 Q28D CL195 must be 0.00%")
    require_cond(pk_by_name["v1.3_Miniprotein_6.5kDa_SC_150mg_Q28D_PureRenal_CL52p7"]["periodic_ss_trough_dLN_RO_pct"]["Kd_1nM"] == 0.0, "v1.3 Q28D CL52.7 must be 0.00%")
    require_cond(abs(pk_by_name["v1.3_Miniprotein_6.5kDa_SC_10mg_DAILY_Q1D_PureRenal_CL52p7"]["t_half_beta_min"] - 88.82) < 0.05, "v1.3 pure renal t1/2 must be ~88.82 min")
    require_cond(abs(pk_by_name["v1.3_Miniprotein_6.5kDa_SC_10mg_DAILY_Q1D_PureRenal_CL52p7"]["periodic_ss_trough_dLN_RO_pct"]["Kd_1nM"] - 11.11) < 0.05, "v1.3 pure renal daily free-ligand RO must be ~11.11%")

    q84 = pk_by_name["v2.0_Fab_KiH_LALAPG_LS_150kDa_SC_300mg_Q84D_Quarterly"]
    q84_st = pk_by_name["v2.0_Fab_KiH_LALAPG_LS_150kDa_SC_300mg_Q84D_Stress_2xCL_Kp0p15"]
    require_cond(abs(q84["periodic_ss_trough_dLN_RO_pct"]["Kd_1nM"] - 95.7374) < 0.01, "Q84D 1nM free-ligand RO mismatch")
    require_cond(abs(q84["periodic_ss_trough_dLN_RO_pct"]["Kd_5nM"] - 81.7914) < 0.01, "Q84D 5nM free-ligand RO mismatch")
    require_cond(abs(q84_st["periodic_ss_trough_dLN_RO_pct"]["Kd_5nM"] - 39.4512) < 0.02, "Q84D 2xCL/Kp0.15 5nM free-ligand RO mismatch")

    # Mass-conserving 6-state coupled nonlinear TMDD ODE scenarios (R2-14 closure: < 1e-10 mass conservation!)
    coupled_tmdd = [
        simulate_coupled_nonlinear_tmdd_periodic("300mg_Q28D_100x_KdOff100nM_1xSink", 300.0, 28.0, 100.0, 1.0, b_max_dln_nM=0.083),
        simulate_coupled_nonlinear_tmdd_periodic("300mg_Q28D_1000x_KdOff1uM_1xSink", 300.0, 28.0, 1000.0, 1.0, b_max_dln_nM=0.083),
        simulate_coupled_nonlinear_tmdd_periodic("300mg_Q28D_10000x_KdOff10uM_1xSink", 300.0, 28.0, 10000.0, 1.0, b_max_dln_nM=0.083),
        simulate_coupled_nonlinear_tmdd_periodic("300mg_Q28D_15000x_KdOff15uM_1xSink", 300.0, 28.0, 15000.0, 1.0, b_max_dln_nM=0.083),
        simulate_coupled_nonlinear_tmdd_periodic("300mg_Q28D_15000x_KdOff15uM_10xDLNSink", 300.0, 28.0, 15000.0, 1.0, b_max_dln_nM=0.830),
        simulate_coupled_nonlinear_tmdd_periodic("300mg_Q28D_15000x_KdOff15uM_10xDLN_3xOffTargetSink", 300.0, 28.0, 15000.0, 1.0, r_off_nmol=3.0 * 16.60539, b_max_dln_nM=0.830),
    ]
    tmdd_map = {r["scenario"]: r for r in coupled_tmdd}
    require_cond(not tmdd_map["300mg_Q28D_100x_KdOff100nM_1xSink"]["passes_5p6_peak_gate"], "Coupled TMDD 100x must fail 5.6% peak gate")
    require_cond(not tmdd_map["300mg_Q28D_10000x_KdOff10uM_1xSink"]["passes_5p6_peak_gate"], "Coupled TMDD 10uM must still fail 5.6% peak gate")
    tmdd_15 = tmdd_map["300mg_Q28D_15000x_KdOff15uM_1xSink"]
    require_cond(tmdd_15["passes_5p6_peak_gate"], "Coupled TMDD 15uM must pass 5.6% peak gate")
    require_cond(abs(tmdd_15["periodic_Cmax_plasma_nM"] - 607.9646) < 1e-3, f"Balanced TMDD 15uM Cmax mismatch: {tmdd_15['periodic_Cmax_plasma_nM']}")
    require_cond(abs(tmdd_15["off_target_plasma_peak_RO_pct"] - 3.8952) < 1e-3, f"Balanced TMDD 15uM off-target peak RO mismatch: {tmdd_15['off_target_plasma_peak_RO_pct']}")
    require_cond(all(r["mass_ledger_nmol"]["mass_conserved_lt_1e10"] for r in coupled_tmdd), "All TMDD runs must conserve mass < 1e-10")
    require_cond(tmdd_map["300mg_Q28D_15000x_KdOff15uM_10xDLNSink"]["on_target_dLN_trough_RO_pct"] >= 99.0, "Coupled TMDD 10x dLN sink must hold >=99% on-target RO")

    kp_sens: dict[str, Any] = {}
    for kp in (0.15, 0.25, 0.35):
        sim = simulate_linear_periodic_pk(
            f"LALAPG_LS_150mg_Q28D_Kp_{kp}", 150.0, 5.20, 150.0, 28.0,
            "SC", 0.68, 0.25, 3.0, 2.8, 0.50, 0.092, kp, 1.0, dt_days=1.0 / 24.0,
        )
        kp_sens[f"Kp_dLN_{kp}"] = {
            "periodic_ss_trough_dLN_nM": sim["periodic_ss_trough_dLN_nM"],
            "periodic_ss_trough_RO_Kd1nM_pct": sim["periodic_ss_trough_dLN_RO_pct"]["Kd_1nM"],
            "periodic_ss_trough_RO_Kd5nM_pct": sim["periodic_ss_trough_dLN_RO_pct"]["Kd_5nM"],
        }

    pan_dq_proof = compute_converged_pan_dq_selectivity_proof(pk_by_name)
    pdb_contacts = compute_deterministic_pdb_contacts(coords_path)

    knob_seq = fasta_records["IGHG1_LALAPG_LS_Knob"][1]
    hole_seq = fasta_records["IGHG1_LALAPG_LS_Hole"][1]
    require_cond(len(knob_seq) == 226 and len(hole_seq) == 226, "Fc Knob/Hole must be 226 aa")
    require_cond(knob_seq.startswith("DKTHTCPPCP") and knob_seq.endswith("SLSLSPG"), "Knob must match secreted P01857-1 G446")
    require_cond(hole_seq.startswith("DKTHTCPPCP") and hole_seq.endswith("SLSLSPG"), "Hole must match secreted P01857-1 G446")

    def expected_fc(muts: list[tuple[int, str, str]]) -> str:
        arr = list(UNIPROT_P01857_1_FC_WT_226AA)
        for eu, wt, mut in muts:
            idx = eu - 221
            require_cond(arr[idx] == wt, f"IGHG1 WT mismatch at EU {eu}: expected {wt}, got {arr[idx]}")
            arr[idx] = mut
        return "".join(arr)

    common = [(234, "L", "A"), (235, "L", "A"), (329, "P", "G"), (428, "M", "L"), (434, "N", "S")]
    exp_knob = expected_fc(common + [(354, "S", "C"), (366, "T", "W")])
    exp_hole = expected_fc(common + [(349, "Y", "C"), (366, "T", "S"), (368, "L", "A"), (407, "Y", "V")])
    require_cond(knob_seq == exp_knob, "FASTA IGHG1_LALAPG_LS_Knob sequence mismatch")
    require_cond(hole_seq == exp_hole, "FASTA IGHG1_LALAPG_LS_Hole sequence mismatch")
    require_cond(knob_seq[297 - 221] == "N" and hole_seq[297 - 221] == "N", "N297 glycan site must be preserved WT")
    require_cond(knob_seq.count("C") == 7 and hole_seq.count("C") == 7, "Knob+Hole dimer must carry 14 Cys = 7 SS")
    fc_dimer_mw_kda = round((calc_mw_da(knob_seq, 2) + calc_mw_da(hole_seq, 2) - 3.0 * 2.01588) / 1000.0, 4)

    return {
        "clinical_lead_policy": {
            "lead_format": "Fully human bispecific Fab-KiH common-LC hIgG1-LALAPG-LS (150 kDa; Fc scaffold deposited, target VH/VL & common-LC pending Foundry wet-lab)",
            "patient_facing_label": "Zero chronic systemic immunosuppression; chronic targeted biologic on staged arms {B, X, Y, D, Z}",
            "occupancy_convention": OCCUPANCY_CONVENTION,
            "unambiguous_selectivity_policy": "off_target_kd_l95_um >= 15.0 uM (15,000 nM) AND selectivity_ratio_l95 >= 15,000x ((off_target_kd_l95_um * 1000) / on_target_kd_u95_nm >= 15,000); worst-case peak off-target RO computed with L95 <= 5.6%",
            "q84d_gating_policy": "Q84D permitted ONLY if on_target_kd_u95_nm <= 1.0 nM AND measured_human_pk_verified == True AND timed_pk_day == 84 bound in current_assay_evidence_record (dosing_regimen='Q84D', human_pk_qualified=True, matching compartment troughs) AND recomputed dLN trough on-target RO >= 90.0%",
            "design_a_zero_additional_biologics_beyond_v080_catalase_hydrogel": True,
            "design_a_contains_preexisting_p04040_catalase_hydrogel": True,
            "design_a_strictly_zero_protein_biologics": False,
            "design_a_preexisting_catalase_hydrogel_exception": "Governed v0.8.0 Design A retains pre-existing passive CaO2-PDMS + >=20 um recombinant human P04040 catalase hydrogel (GY-013 / GATE-31); zero SHIELD/InvVax/Cuff v2.0/INS L82I permitted.",
            "camelid_vhh_fc_dropped_from_clinical_lead": True,
            "distal_ln_dp2_albumin_hitchhiking_claim_dropped": True,
            "fcrn_45p66d_half_life_status": "MODELED_PARAMETER_PENDING_NHP_AND_HUMAN_PK",
            "honest_solo_c3_lift_pp_range": [1.5, 2.2],
            "honest_solo_c3_lift_pp_central": 1.8,
        },
        "linear_periodic_pk_simulations": pk_list,
        "coupled_nonlinear_tmdd_ode_simulations": coupled_tmdd,
        "kp_dln_sensitivity_LALAPG_LS_150mg_Q28D": kp_sens,
        "converged_pan_dq_selectivity_proof": pan_dq_proof,
        "ighg1_P01857_1_secreted_LALAPG_LS_KiH_fc_scaffold": {
            "scope_disclosure": "FASTA supplies Fc heterodimer scaffolds ONLY; target anti-DQ2.5+HIP11 and anti-DQ8+InsB-R3 VH/VL domains and common light chain are pending Foundry wet-lab discovery.",
            "uniprot_isoform": "P01857-1 (secreted VSP_061818 G446, EU 221..446, K447 clipped)",
            "fc_knob_length_aa": len(knob_seq),
            "fc_hole_length_aa": len(hole_seq),
            "fc_knob_sha256": sha256_str(knob_seq),
            "fc_hole_sha256": sha256_str(hole_seq),
            "fc_heterodimer_total_cys": 14,
            "fc_heterodimer_expected_disulfides": 7,
            "fc_heterodimer_expected_unpaired_cys": 0,
            "disulfide_status": "EXPECTED_TOPOLOGY_PENDING_EXPRESSED_LCMS_QC",
            "fc_heterodimer_mw_kda": fc_dimer_mw_kda,
            "n297_glycan_preserved": True,
            "adcc_cdc_status": "EXPECTED_SILENCED_LALAPG_PENDING_EXPRESSED_CELLULAR_ASSAY",
        },
        "deterministic_rcsb_pdb_contact_audits": pdb_contacts,
    }


# ---------------------------------------------------------------------------
# PART B: INS p.Leu82Ile (C-Peptide L26I) — PE2max + ELISA + DR4 + HLA-A*11:01
# ---------------------------------------------------------------------------
def verify_part_b() -> dict[str, Any]:
    cds = INS_GRCH38_CANONICAL_CDS
    flank = INS_GRCH38_FLANK_MINUS_243BP
    prot_wt = UNIPROT_P01308_PREPROINSULIN

    translated = "".join(CODON_TABLE[cds[i : i + 3]] for i in range(0, len(cds) - 3, 3))
    require_cond(translated == prot_wt, "INS CDS translation must match UniProt P01308 100%")
    wt_codon_82 = cds[243:246]
    require_cond(wt_codon_82 == "CTG" and prot_wt[81] == "L", "INS codon 82 must be WT CTG (Leu)")
    require_cond(flank[120:123] == "CTG", "GRCh38 chr11:2159939-2159941 (-1) must be CTG")

    single_nt = []
    ile_1nt = 0
    for pos in range(3):
        for b in "ACGT":
            if b == wt_codon_82[pos]:
                continue
            cand = wt_codon_82[:pos] + b + wt_codon_82[pos + 1 :]
            aa = CODON_TABLE[cand]
            if aa == "I":
                ile_1nt += 1
            ed = "CBE" if (wt_codon_82[pos], b) in {("C", "T"), ("G", "A")} else (
                "ABE" if (wt_codon_82[pos], b) in {("A", "G"), ("T", "C")} else "Transversion/PE"
            )
            single_nt.append({"cds_pos": 244 + pos, "change": f"{wt_codon_82}->{cand}", "aa": aa, "is_ile": aa == "I", "editor": ed})
    require_cond(ile_1nt == 0 and len(single_nt) == 9, "Exactly 0/9 single-nt edits of CTG yield Ile")
    require_cond(CODON_TABLE["TTA"] == "L", "CBE double C>T+G>A still yields synonymous Leu")

    cds_mut = cds[:243] + "ATC" + cds[246:]
    prot_mut = "".join(CODON_TABLE[cds_mut[i : i + 3]] for i in range(0, len(cds_mut) - 3, 3))
    require_cond(prot_mut[81] == "I", "Mutant codon 82 must encode Ile")
    require_cond(prot_mut[0:24] == prot_wt[0:24], "Signal peptide must stay 100% WT")
    require_cond(prot_mut[24:54] == prot_wt[24:54], "Mature B-chain must stay 100% WT")
    require_cond(prot_mut[54:56] == "RR" and prot_mut[87:89] == "KR", "PC1/3 and PC2 motifs must stay 100% WT")
    require_cond(prot_mut[89:110] == prot_wt[89:110], "Mature A-chain must stay 100% WT")
    ideal_bystanders = sum(1 for a, b in zip(prot_wt, prot_mut) if a != b) - 1
    require_cond(ideal_bystanders == 0, f"Expected 0 ideal bystander AA changes, got {ideal_bystanders}")

    flank_mut = flank[:120] + "ATC" + flank[123:]
    sp1 = flank[101:121]
    pam1_wt, pam1_mut = flank[121:124], flank_mut[121:124]
    pbs1 = revcomp(flank[107:118])
    rtt1 = revcomp(flank_mut[118:132])
    require_cond(sp1 == "CAGCCTGCAGCCCTTGGCCC" and pam1_wt == "TGG" and pam1_mut == "TCG", "epegRNA-1 verification failed")
    require_cond(pbs1 == "CCAAGGGCTGC" and rtt1 == "GGACCCCTCGATGG", "epegRNA-1 PBS/RTT mismatch")

    rc_wt, rc_mut = revcomp(flank), revcomp(flank_mut)
    sp2 = rc_wt[101:121]
    pam2_wt, pam2_mut = rc_wt[121:124], rc_mut[121:124]
    pbs2 = revcomp(rc_wt[106:118])
    rtt2 = revcomp(rc_mut[118:132])
    require_cond(sp2 == "GCTTCTGCAGGGACCCCTCC" and pam2_wt == "AGG" and pam2_mut == "ATG", "epegRNA-2 verification failed")
    require_cond(pbs2 == "GGGGTCCCTGCA" and rtt2 == "CCCTTGGCCATCGA", "epegRNA-2 PBS/RTT mismatch")

    wt_gt = [i for i in range(105, 130) if flank[i + 3 : i + 5] == "GT"]
    mut_gt = [i for i in range(105, 130) if flank_mut[i + 3 : i + 5] == "GT"]
    wt_ag = [i for i in range(98, 128) if flank[i + 12 : i + 14] == "AG"]
    mut_ag = [i for i in range(98, 128) if flank_mut[i + 12 : i + 14] == "AG"]
    require_cond(len(mut_gt) == len(wt_gt) and len(mut_ag) == len(wt_ag), "CTG->ATC must create 0 cryptic GT/AG splice motifs")

    # Expanded 9-allele MHC-I scan INCLUDING HLA-A*11:01 (PMID:29343547 transfected K562 surrogate PPI 80-88 LALEGSLQK!)
    mhci_motifs = {
        "HLA-A*02:01": (set("LMIVQT"), set("VLI")),
        "HLA-A*01:01": (set("TSD"), set("YF")),
        "HLA-A*03:01": (set("LMVIT"), set("KYR")),
        "HLA-A*11:01": (set("VILMTSAQ"), set("KR")),
        "HLA-A*24:02": (set("YF"), set("FLI")),
        "HLA-B*07:02": (set("P"), set("LFMVI")),
        "HLA-B*08:01": (set("LKRI"), set("LMIV")),
        "HLA-B*44:02": (set("E"), set("FYWL")),
        "HLA-C*07:01": (set("RY"), set("YLFM")),
    }
    de_novo_mhci = 0
    a0201_watch: list[str] = []
    a1101_watch: list[str] = []
    for k in (8, 9, 10, 11):
        for s in range(max(0, 81 - k + 1), min(len(prot_wt) - k + 1, 82)):
            pw, pm = prot_wt[s : s + k], prot_mut[s : s + k]
            wt_h = {al for al, (p2, pc) in mhci_motifs.items() if pw[1] in p2 and pw[-1] in pc}
            mut_h = {al for al, (p2, pc) in mhci_motifs.items() if pm[1] in p2 and pm[-1] in pc}
            if mut_h - wt_h:
                de_novo_mhci += 1
            if "HLA-A*02:01" in mut_h:
                a0201_watch.append(pm)
            if "HLA-A*11:01" in mut_h:
                a1101_watch.append(pm)
    require_cond(de_novo_mhci == 0, f"Expected 0 de-novo MHC-I anchor gains across 9 alleles, got {de_novo_mhci}")
    require_cond("LAIEGSLQK" in a1101_watch, "HLA-A*11:01 watch list must capture PPI 80-88 LAIEGSLQK")
    require_cond(
        set(a0201_watch) == set(MANDATORY_INS_HLA_TARGET_PEPTIDES["HLA-A*02:01"]),
        f"HLA-A*02:01 governed target peptides must match P01308 L82I watch list: {a0201_watch}",
    )

    ppi_80_88_wt = prot_wt[79:88]
    ppi_80_88_mut = prot_mut[79:88]
    require_cond(ppi_80_88_wt == "LALEGSLQK" and ppi_80_88_mut == "LAIEGSLQK", "PPI 80-88 mismatch")

    dq_gains = 0
    for s in range(max(0, 81 - 8), min(len(prot_wt) - 8, 82)):
        cw, cm = prot_wt[s : s + 9], prot_mut[s : s + 9]
        if sum(cm[i] in "DE" for i in (3, 5, 6)) > sum(cw[i] in "DE" for i in (3, 5, 6)):
            dq_gains += 1
        if sum(cm[i] in "DE" for i in (0, 8)) > sum(cw[i] in "DE" for i in (0, 8)):
            dq_gains += 1
    require_cond(dq_gains == 0, "Expected 0 de-novo DQ2.5/DQ8 acidic anchors")

    c19_a3_wt = "GSLQPLALEGSLQKRGIV"
    c19_idx = prot_wt.index(c19_a3_wt)
    c19_a3_mut = prot_mut[c19_idx : c19_idx + len(c19_a3_wt)]
    l82_pos_in_c19_a3 = 82 - c19_idx
    dr4_core_wt = "LALEGSLQK"
    dr4_core_idx = prot_wt.index(dr4_core_wt)
    dr4_core_mut = prot_mut[dr4_core_idx : dr4_core_idx + 9]
    l82_pos_in_dr4_core = 82 - dr4_core_idx
    require_cond(l82_pos_in_c19_a3 == 8 and c19_a3_mut == "GSLQPLAIEGSLQKRGIV", "C19-A3 pos-8 check failed")
    require_cond(l82_pos_in_dr4_core == 3 and dr4_core_mut == "LAIEGSLQK", "DRB1*04:01 P3 core check failed")

    u95_0_of_12_pct = round(_clopper_pearson_upper_95_pct(0, 12), 4)
    u95_0_of_4_pct = round(_clopper_pearson_upper_95_pct(0, 4), 4)
    require_cond(abs(u95_0_of_12_pct - 22.0922) < 1e-3, f"0/12 U95 mismatch: {u95_0_of_12_pct}")
    require_cond(abs(u95_0_of_4_pct - 52.7129) < 1e-3, f"0/4 U95 mismatch: {u95_0_of_4_pct}")

    return {
        "grch38_locus": "chr11:2159939-2159941 (-1 strand, ENSG00000254647 / ENST00000381330.5 / NM_000207.3)",
        "wt_codon_82": wt_codon_82,
        "edited_codon_82": "ATC",
        "single_nt_ile_outcomes": ile_1nt,
        "base_editors_disqualified": True,
        "gy021_mandatory_editor": "PE2max + epegRNA (100% MLH1dn-FREE; un-gated PE4max BANNED)",
        "epegRNA_1": {"spacer": sp1, "wt_pam": pam1_wt, "edited_pam": pam1_mut, "pbs": pbs1, "rtt": rtt1, "polyT": any("TTTT" in x for x in (sp1, pbs1, rtt1))},
        "epegRNA_2": {"spacer": sp2, "wt_pam": pam2_wt, "edited_pam": pam2_mut, "pbs": pbs2, "rtt": rtt2, "polyT": any("TTTT" in x for x in (sp2, pbs2, rtt2))},
        "ideal_product_mature_B_A_PC1_3_PC2_100pct_wt": True,
        "ideal_product_bystander_aa_changes": ideal_bystanders,
        "ideal_vs_measured_scope_note": "Sequence enumeration verifies ideal CTG->ATC translation only; clonal bystander sequencing, RNA splicing (Delta PSI), proinsulin processing, and dynamic GSIS remain mandatory wet-lab measurements.",
        "in_silico_cryptic_gt_donors_created": len(mut_gt) - len(wt_gt),
        "in_silico_cryptic_ag_acceptors_created": len(mut_ag) - len(wt_ag),
        "external_variant_db_provenance": {
            "query_date_utc": "2026-12-01",
            "locus_queried": "GRCh38 chr11:2159939-2159941 (-1 strand; +strand CAG->GAT; INS NM_000207.3:c.244_246delinsATC / p.Leu82Ile)",
            "clinvar_query": {
                "api_source": "NCBI ClinVar E-utilities",
                "query_date_utc": "2026-12-01",
                "gene_query": "INS[gene]",
                "gene_total_variation_ids": 255,
                "exact_codon82_query": "11[chr] AND 2159939:2159941[chrpos]",
                "exact_codon82_variation_count": 0,
                "flanking_control_query": "11[chr] AND 2159930:2159950[chrpos]",
                "flanking_control_variation_count": 6,
                "flanking_retrievable_variation_ids": [
                    {"variation_id": "5022809", "hgvs": "NM_000207.3(INS):c.243C>T (p.Ala81=)", "classification": "Likely benign"},
                    {"variation_id": "4714280", "hgvs": "NM_000207.3(INS):c.241dup (p.Ala81fs)", "classification": "Uncertain significance"},
                    {"variation_id": "3346944", "hgvs": "NM_000207.3(INS):c.242C>T (p.Ala81Val)", "classification": "Uncertain significance"},
                    {"variation_id": "2822542", "hgvs": "NM_000207.3(INS):c.249G>A (p.Glu83=)", "classification": "Likely benign"},
                    {"variation_id": "68729", "hgvs": "NM_000207.3(INS):c.250G>A (p.Gly84Arg)", "classification": "Uncertain significance"},
                    {"variation_id": "4537654", "hgvs": "NM_000207.3(INS):c.254C>G (p.Ser85Cys)", "classification": "Uncertain significance"},
                ],
            },
            "gnomad_v4p1_query": {
                "dataset": "gnomad_r4 (gnomAD v4.1 GraphQL API)",
                "query_date_utc": "2026-12-01",
                "region_queried": "GRCh38 chr11:2159930-2159950",
                "region_total_variants": 32,
                "codon82_exome_an_denominator_range": [1445176, 1446030],
                "flanking_genome_an_denominator_range": [152164, 152282],
                "target_mnv_variant_id": "11-2159939-CAG-GAT",
                "target_mnv_observed_records": 0,
                "codon82_covered_alleles": [
                    {"variant_id": "11-2159939-C-G", "rsids": [], "coding_change": "c.246G>C (p.Leu82=)", "consequence": "synonymous_variant", "exome_ac": 1, "exome_an": 1446030},
                    {"variant_id": "11-2159939-C-T", "rsids": ["rs934790989"], "coding_change": "c.246G>A (p.Leu82=)", "consequence": "synonymous_variant", "exome_ac": 1, "exome_an": 1446030},
                    {"variant_id": "11-2159940-A-G", "rsids": [], "coding_change": "c.245T>C (p.Leu82Pro)", "consequence": "missense_variant", "exome_ac": 0, "exome_an": 1445176},
                    {"variant_id": "11-2159941-G-T", "rsids": [], "coding_change": "c.244C>A (p.Leu82Met)", "consequence": "missense_variant", "exome_ac": 0, "exome_an": 1445358},
                ],
            },
            "ensembl_vep_prediction": "SIFT = 0.38 (tolerated), PolyPhen = 0.502 (possibly_damaging — mandates human beta-cell processing & GSIS QC)",
            "note": "Absence of p.Leu82Ile in ClinVar (0 at chr11:2159939-2159941) and gnomAD v4.1 (0 MNV records across ~1.445M exome alleles) does NOT prove clinical benignity; functional beta-cell qualification is mandatory.",
        },
        "mhci_alleles_scanned_count": len(mhci_motifs),
        "mhci_alleles_scanned": sorted(mhci_motifs.keys()),
        "de_novo_mhci_anchor_gains": de_novo_mhci,
        "a0201_watch_peptides": a0201_watch,
        "hla_a1101_surrogate_ppi80_88_audit": {
            "primary_pmid": "PMID:29343547",
            "citation": "Kronenberg-Versteeg et al. 2018 Diabetes (p. 10 & Supp. Fig. 2A: eluted from transfected K562 surrogate cells expressing HLA-A*11:01 — NOT endogenous primary human beta-cell elution)",
            "biological_system": "TRANSFECTED_K562_SURROGATE_CELLS",
            "endogenous_product_cell_elution_status": "PROSPECTIVE_STAGE0_GATE_PENDING_EDITED_PRODUCT_PEPTIDOMICS",
            "p01308_1based_span": "80..88",
            "peptide_wt": ppi_80_88_wt,
            "peptide_mut": ppi_80_88_mut,
            "l82i_position_in_9mer": 3,
            "a1101_watch_peptides": a1101_watch,
            "mandatory_in_pre_edit_hla_panel": True,
        },
        "de_novo_dq25_dq8_acidic_anchor_gains": dq_gains,
        "mandatory_hla_dr4_c19_a3_audit": {
            "epitope_wt": c19_a3_wt,
            "epitope_mut": c19_a3_mut,
            "p01308_1based_span": f"{c19_idx + 1}..{c19_idx + len(c19_a3_wt)}",
            "l82i_position_in_c19_a3_1based": l82_pos_in_c19_a3,
            "drb1_0401_core_wt": dr4_core_wt,
            "drb1_0401_core_mut": dr4_core_mut,
            "l82i_core_pocket": f"P{l82_pos_in_dr4_core}",
            "pre_edit_binding_and_elispot_required": True,
        },
        "donor_panel_statistical_bound": {
            "min_donors_per_mandatory_allele": 2,
            "min_unique_donors_deduplicated": 12,
            "exact_one_sided_95pct_U95_for_0_of_12_pct": u95_0_of_12_pct,
            "exact_one_sided_95pct_U95_for_0_of_4_duplicate_panel_pct": u95_0_of_4_pct,
            "interpretation": "Deduplicated unique donors across mandatory panels must be >= 12: 0/12 unique reactive donors gives exact one-sided 95% U95 = 22.0922% (whereas reusing 4 donors across 3 allele panels yields 0/4 U95 = 52.7129% -> FAIL).",
        },
        "preprint_disclosure": {
            "pmid": "PMID:42523473",
            "citation": "Elyanow et al. 2026 (PREPRINT — not yet peer-reviewed)",
            "status": "PREPRINT",
        },
        "day1_pre_edit_cpeptide_elisa_gate": {
            "platforms": list(MANDATORY_CPEP_ELISA_KITS),
            "recovery_pct_bounds": [85.0, 115.0],
            "target_clinical_span_nmol_L": [0.05, 5.00],
            "mercodia_10_1136_01_published_operating_range_nmol_L": [0.10, 4.00],
            "mercodia_spec_note": (
                "Mercodia C-peptide ELISA (10-1136-01) has a published operating range of 0.10-4.00 nmol/L "
                "(100-4,000 pmol/L). Covering both ends of the 0.05-5.00 nmol/L candidate interval requires "
                "demonstrated low-end coverage at 0.05 nmol/L (below 0.10 nmol/L) AND validated sample-dilution "
                "linearity at 5.00 nmol/L (above 4.00 nmol/L), with pinned kit_catalog_id and kit_lot_id."
            ),
            "must_pass_before_ipsc_editing": True,
        },
        "honest_solo_c3_lift_pp_range": [0.5, 0.8],
        "honest_solo_c3_lift_pp_central": 0.6,
    }


# ---------------------------------------------------------------------------
# PART C: Pruned Viral-Receptor-Avoidance Cuff v2.0 (Honest Disulfide Bookkeeping & 7AL7 Nuance)
# ---------------------------------------------------------------------------
def verify_part_c(fasta_path: Path, fasta_records: dict[str, tuple[str, str]]) -> dict[str, Any]:
    actual_sha = sha256_file(fasta_path)
    require_cond(actual_sha == EXPECTED_FASTA_SHA256, f"FASTA SHA-256 mismatch: {actual_sha} != {EXPECTED_FASTA_SHA256}")
    require_cond(len(fasta_records) == EXPECTED_FASTA_RECORD_COUNT, f"Expected {EXPECTED_FASTA_RECORD_COUNT} FASTA records, got {len(fasta_records)}")

    for rid, (_, seq) in fasta_records.items():
        require_cond("fasl" not in rid.lower() and "adipoq" not in rid.lower(), f"Retired ADIPOQ-Hexa-FasL found: {rid}")
        require_cond("IIPNKHDAL" not in seq, f"Banned GY-026 IIPNKHDAL found in {rid}")
        require_cond(all(ch in AA_WEIGHTS for ch in seq), f"Invalid AA residue in {rid}")

    disulfide_specs: dict[str, dict[str, Any]] = {
        "sCR1_v2_CSL040_LHR_ABC_Intein0aa": {"len": 1351, "ss": 42, "unp": 0, "group": "CORE_IMMOBILIZED_CUFF_V2", "role": "CORE_PRUNED_CUFF_CO_LEAD_0AA_INTEIN", "peg_kda": 3.4},
        "sCR1_v2_CSL040_LHR_ABC_GGS_LPETG": {"len": 1359, "ss": 42, "unp": 0, "group": "CORE_IMMOBILIZED_CUFF_V2", "role": "CORE_PRUNED_CUFF_CO_LEAD_ESRTA", "peg_kda": 3.4},
        "THBD_363_497_M406L_S490A_S492A_Intein0aa": {"len": 135, "ss": 9, "unp": 0, "max_met": 0, "max_trp": 0, "group": "CORE_IMMOBILIZED_CUFF_V2", "role": "CORE_PRUNED_CUFF_CO_LEAD_0AA_INTEIN", "peg_kda": 3.4},
        "THBD_363_497_M406L_S490A_S492A_GGS_LPETG_CSnull": {"len": 143, "ss": 9, "unp": 0, "max_met": 0, "max_trp": 0, "group": "CORE_IMMOBILIZED_CUFF_V2", "role": "CORE_PRUNED_CUFF_CO_LEAD_ESRTA", "peg_kda": 3.4},
        "THBD_363_497_M406L_GGS_LPETG_CSplus_comparator": {"len": 143, "ss": 9, "unp": 0, "max_met": 0, "max_trp": 0, "group": "CORE_IMMOBILIZED_CUFF_V2_COMPARATOR", "role": "COMPARATOR_CS_PLUS", "peg_kda": 3.4},
        "CD200_ECD_Intein0aa": {"len": 202, "ss": 3, "unp": 0, "group": "CORE_IMMOBILIZED_CUFF_V2", "role": "CORE_PRUNED_CUFF_CO_LEAD_0AA_INTEIN", "peg_kda": 20.0},
        "CD200_ECD_GGS_LPETG": {"len": 210, "ss": 3, "unp": 0, "group": "CORE_IMMOBILIZED_CUFF_V2", "role": "CORE_PRUNED_CUFF_CO_LEAD_ESRTA", "peg_kda": 20.0},
        "CFH_19_445_GGS_LPETG_Archived_Backup": {"len": 435, "ss": 14, "unp": 0, "group": "RETIRED_ARCHIVED_BACKUP", "role": "PERMANENTLY_RETIRED_FROM_PRIMARY_CUFF", "peg_kda": 3.4},
        "CCL22_Mature_O00626": {"len": 69, "ss": 2, "unp": 0, "group": "NONCORE_OPTIONAL_COMPARATOR", "role": "GRAFT_INTRINSIC_TREG_CHEMOKINE"},
        "IL1RN_Mature_P18510": {
            "len": 152, "ss": 0, "unp": 4, "group": "NONCORE_SOLUBLE_COMPANION_WITH_FREE_THIOLS",
            "role": "SOLUBLE_IL1RA_COMPANION_EXCLUDED_FROM_ZERO_UNPAIRED_CLAIM",
            "cys_note": "4 Cys monomeric free thiols per UniProt P18510 / PDB 1ILR (optional C91-C141 disulfide noted in UniProt -> 2-4 free thiols); EXCLUDED from covalent zero-unpaired Cuff v2.0.",
        },
        "IL18BP_Mature_O95998": {
            "len": 164, "ss": 2, "unp": 2, "max_met": 0,
            "group": "NONCORE_SOLUBLE_COMPANION_PENDING_MONOMER_LCMS",
            "role": "SOLUBLE_IL18BP_COMPANION_0MET_EXCLUDED_FROM_ZERO_UNPAIRED_CLAIM",
            "disulfide_status": "PARTIAL_CRYSTAL_7AL7_START_RES63_OMITS_CYS51_CYS131_INTERMOLECULAR_2P21A_FULL_LENGTH_MONOMER_PENDING_INTACT_LCMS",
            "cys_note": (
                "6 Cys in mature O95998[31..194] (Cys51, Cys64, Cys86, Cys89, Cys131, Cys150). Crystal structure PDB:7AL7 "
                "(PMC9111989) confirms 2 intramolecular disulfides, starts at residue 63 (omitting Cys51), and shows Cys131 "
                "forming a 2.21 A intermolecular disulfide with IL-18 Cys74; therefore PDB:7AL7 does NOT establish two free "
                "thiols in full-length isolated monomeric IL-18BP, and full-length monomeric free-thiol count awaits intact-protein LC-MS. "
                "Explicitly EXCLUDED from covalent zero-unpaired Cuff v2.0."
            ),
        },
    }

    profiles: dict[str, Any] = {}
    for rid, spec in disulfide_specs.items():
        require_cond(rid in fasta_records, f"Missing required FASTA record: {rid}")
        seq = fasta_records[rid][1]
        dstat = spec.get("disulfide_status", "EXPECTED_TOPOLOGY_PENDING_EXPRESSED_LCMS_ELLMAN_QC")
        bp = biophysical_profile(seq, n_disulfides=spec["ss"], disulfide_status=dstat)
        require_cond(bp["length_aa"] == spec["len"], f"{rid} length mismatch: {bp['length_aa']} != {spec['len']}")
        require_cond(bp["expected_unpaired_cys"] == spec["unp"], f"{rid} expected unpaired Cys mismatch: {bp['expected_unpaired_cys']} != {spec['unp']}")
        if "max_met" in spec:
            require_cond(bp["met_count"] <= spec["max_met"], f"{rid} Met violation: {bp['met_count']}")
        if "max_trp" in spec:
            require_cond(bp["trp_count"] <= spec["max_trp"], f"{rid} Trp violation: {bp['trp_count']}")
        entry: dict[str, Any] = {"group": spec["group"], "role": spec["role"], "sha256": sha256_str(seq), "biophysics": bp}
        if "cys_note" in spec:
            entry["cys_bookkeeping_note"] = spec["cys_note"]
        profiles[rid] = entry

    intein_vs_esrta = {}
    for label, core_id, lpet_id in (
        ("sCR1_v2", "sCR1_v2_CSL040_LHR_ABC_Intein0aa", "sCR1_v2_CSL040_LHR_ABC_GGS_LPETG"),
        ("THBD_M406L_CSnull", "THBD_363_497_M406L_S490A_S492A_Intein0aa", "THBD_363_497_M406L_S490A_S492A_GGS_LPETG_CSnull"),
        ("CD200_ECD", "CD200_ECD_Intein0aa", "CD200_ECD_GGS_LPETG"),
    ):
        core_seq = fasta_records[core_id][1]
        lpet_seq = fasta_records[lpet_id][1]
        require_cond(lpet_seq == core_seq + "GGSLPETG", f"{lpet_id} must equal {core_id} + GGSLPETG")
        post_esrta = core_seq + "GGSLPETGGG"
        n_lpet_foreign = count_non_native_junction_kmers(core_seq, post_esrta)
        n_intein_foreign = count_non_native_junction_kmers(core_seq, core_seq)
        require_cond(n_lpet_foreign == 40 and n_intein_foreign == 0, f"{label} junction kmer audit mismatch: {n_lpet_foreign}/{n_intein_foreign}")
        intein_vs_esrta[label] = {
            "esrta_LPET_GGG_foreign_8_11mers": n_lpet_foreign,
            "split_intein_0aa_foreign_8_11mers": n_intein_foreign,
            "scope_note": "Sequence-level specification only; conjugation yield, residual unreacted species, and orientation require wet-lab CMC.",
        }

    return {
        "fasta_relpath": "data/constructs/openislet_foundry_v2_cuff_v2_and_shield_fc_v0.9.0.fasta",
        "fasta_sha256": actual_sha,
        "record_count": len(fasta_records),
        "cmc_pruned_core_covalent_cuff_proteins": 3,
        "core_3_proteins": [
            "sCR1_v2 (3.4 kDa PEG)",
            "THBD-M406L (3.4 kDa PEG; CS-null lead + CS+ comparator)",
            "CD200-ECD (20 kDa PEG spacer; steric reach vs ~70 nm sCR1 rod pending functional co-immobilization assay)",
        ],
        "peg_20kda_steric_reach_disclosure": (
            "A 20 kDa PEG chain contour length (~126 nm fully extended) does NOT establish a 70 nm functional reach in solution "
            "(Flory/random-coil radius ~7-10 nm); co-immobilized CD200R accessibility alongside sCR1_v2 is a mandatory Gate-34 functional requirement."
        ),
        "cfh_19_445_permanently_retired_from_primary_cuff": True,
        "adipoq_hexa_fasl_permanently_retired": True,
        "zero_expected_unpaired_ecd_cys_scope": (
            "STRICTLY SCOPED to the 2 Fc heterodimer chains (14 Cys = 7 expected SS in dimer) + 3 core immobilized Cuff v2.0 proteins "
            "(sCR1_v2: 84 Cys = 42 SS; THBD-M406L: 18 Cys = 9 SS; CD200-ECD: 6 Cys = 3 SS; plus archived CFH[19-445] & optional CCL22) "
            "as reference-domain topology expectations pending expressed non-reducing LC-MS / Ellman free-thiol QC. "
            "Explicitly EXCLUDES non-core soluble companions IL1RN (4 Cys monomeric free thiols) and IL18BP (6 Cys: PDB:7AL7 starts at "
            "residue 63 omitting Cys51, shows 2 intramolecular SS, and forms a 2.21 A intermolecular disulfide between Cys131 and IL-18 Cys74 — "
            "full-length monomeric free-thiol count awaits intact-protein LC-MS)."
        ),
        "split_intein_0aa_co_lead_vs_esrta_kmer_audit": intein_vs_esrta,
        "construct_profiles": profiles,
    }


# ---------------------------------------------------------------------------
# PART D: InvVax Evidence Fidelity, Clean H3 Sensitivity, & Exact <1e-12 Parity
# ---------------------------------------------------------------------------
def biv_bern(p1: float, p2: float, phi: float) -> dict[tuple[int, int], float]:
    require_cond(0.0 <= p1 <= 1.0 and 0.0 <= p2 <= 1.0 and 0.0 <= phi <= 1.0, f"Invalid biv_bern inputs: {p1},{p2},{phi}")
    p11 = (1.0 - phi) * (p1 * p2) + phi * min(p1, p2)
    out = {
        (0, 0): max(0.0, 1.0 - p1 - p2 + p11),
        (1, 0): max(0.0, p1 - p11),
        (0, 1): max(0.0, p2 - p11),
        (1, 1): max(0.0, p11),
    }
    require_cond(abs(sum(out.values()) - 1.0) < 1e-12, "biv_bern mass conservation error")
    return out


def frechet_joint(probs: list[float], phi: float) -> list[float]:
    m = len(probs)
    require_cond(0.0 <= phi <= 1.0 and all(0.0 <= p <= 1.0 for p in probs), "Invalid frechet_joint inputs")
    n_states = 1 << m
    d_ind = [0.0] * n_states
    for mask in range(n_states):
        w = 1.0
        for i in range(m):
            w *= probs[i] if (mask & (1 << i)) else (1.0 - probs[i])
        d_ind[mask] = w
    if phi == 0.0:
        return d_ind
    order = sorted(range(m), key=lambda i: probs[i])
    d_pos = [0.0] * n_states
    prev = 0.0
    for idx, i in enumerate(order):
        w = probs[i] - prev
        if w > 0.0:
            d_pos[sum(1 << j for j in order[idx:])] += w
        prev = probs[i]
    d_pos[0] += 1.0 - prev
    out = [(1.0 - phi) * d_ind[s] + phi * d_pos[s] for s in range(n_states)]
    require_cond(abs(sum(out) - 1.0) < 1e-12, "frechet_joint mass conservation error")
    return out


def frechet_couple(base_dist: list[float], u_new: float, phi: float, event_fn: Callable[[int], bool]) -> list[float]:
    n0 = len(base_dist)
    require_cond(0.0 <= u_new <= 1.0 and 0.0 <= phi <= 1.0, "Invalid frechet_couple inputs")
    p_e1 = sum(base_dist[mi] for mi in range(n0) if event_fn(mi))
    p_e0 = 1.0 - p_e1
    d_ind = [0.0] * (2 * n0)
    for mi in range(n0):
        w = base_dist[mi]
        d_ind[mi] = w * (1.0 - u_new)
        d_ind[mi | n0] = w * u_new
    d_pos = [0.0] * (2 * n0)
    p11 = min(p_e1, u_new)
    p10 = p_e1 - p11
    p01 = max(0.0, u_new - p_e1)
    p00 = p_e0 - p01
    for mi in range(n0):
        w = base_dist[mi]
        if w == 0.0:
            continue
        if event_fn(mi):
            frac = w / p_e1 if p_e1 > 0 else 0.0
            d_pos[mi] = p10 * frac
            d_pos[mi | n0] = p11 * frac
        else:
            frac = w / p_e0 if p_e0 > 0 else 0.0
            d_pos[mi] = p00 * frac
            d_pos[mi | n0] = p01 * frac
    out = [(1.0 - phi) * d_ind[k] + phi * d_pos[k] for k in range(2 * n0)]
    require_cond(abs(sum(out) - 1.0) < 1e-12, "frechet_couple mass conservation error")
    return out


def strassen_bipartite_bounds(
    v_h123: list[float],
    dh4: list[float],
    routes: tuple[str, ...],
    cell_classes: tuple[str, ...],
    compat_map: dict[str, frozenset[str]],
) -> tuple[float, float]:
    n = len(routes)
    all_routes = sorted(set(routes))
    r_idx = {r: k for k, r in enumerate(all_routes)}
    cell_groups: dict[int, float] = {}
    for mc, wc in enumerate(v_h123):
        if wc == 0.0:
            continue
        rmask = 0
        for i in range(n):
            if (mc >> i) & 1:
                for r in compat_map[cell_classes[i]]:
                    if r in r_idx:
                        rmask |= 1 << r_idx[r]
        cell_groups[rmask] = cell_groups.get(rmask, 0.0) + wc
    route_groups: dict[int, float] = {}
    for mh, wh in enumerate(dh4):
        if wh == 0.0:
            continue
        rmask = 0
        for j in range(n):
            if (mh >> j) & 1:
                rmask |= 1 << r_idx[routes[j]]
        route_groups[rmask] = route_groups.get(rmask, 0.0) + wh
    c_keys, r_keys = list(cell_groups.keys()), list(route_groups.keys())
    c_vals, r_vals = [cell_groups[k] for k in c_keys], [route_groups[k] for k in r_keys]
    max_def_e = 0.0
    max_def_ec = 0.0
    for sm in range(1 << len(c_keys)):
        p_s = 0.0
        neigh_e = [False] * len(r_keys)
        neigh_ec = [False] * len(r_keys)
        for i in range(len(c_keys)):
            if (sm >> i) & 1:
                p_s += c_vals[i]
                cm = c_keys[i]
                for j, rm in enumerate(r_keys):
                    if (cm & rm) != 0:
                        neigh_e[j] = True
                    else:
                        neigh_ec[j] = True
        p_ne = sum(r_vals[j] for j in range(len(r_keys)) if neigh_e[j])
        p_nec = sum(r_vals[j] for j in range(len(r_keys)) if neigh_ec[j])
        if p_s - p_ne > max_def_e:
            max_def_e = p_s - p_ne
        if p_s - p_nec > max_def_ec:
            max_def_ec = p_s - p_nec
    return max(0.0, max_def_ec) * 100.0, min(1.0, 1.0 - max_def_e) * 100.0


def eval_5arm_exact_2pow20(
    arms: list[tuple[float, float, float, float]],
    *,
    c1: float = 0.88,
    c3: float = 0.89,
    phi_inc: float = 0.50,
    phi_yx: float = 0.75,
    phi_c: float = 0.25,
) -> dict[str, Any]:
    """Exact 5-arm (A, B, X, Y, D) 2^20 + Strassen engine (Design A strictly frozen at (0.88, 0.78, 0.57, 0.69))."""
    require_cond(len(arms) == 5, "Expected 5 arms")
    require_cond(arms[0] == (0.88, 0.78, 0.57, 0.69), f"Design A invariance violated: {arms[0]}")
    routes = ("R1", "R2", "R1", "R3P", "R3P")
    cell_classes = ("INC", "INC", "INC", "STAGED_BASE", "STAGED_BASE")
    compat_map = {"INC": frozenset({"R1", "R2"}), "STAGED_BASE": frozenset({"R3P"})}
    for i in range(5):
        require_cond(routes[i] in compat_map[cell_classes[i]], f"Home-route violation on arm {i}")

    d1 = [0.0] * 32
    u_d1 = arms[4][0] / c1
    d1[0] = 1.0 - c1
    d1[15] = c1 * (1.0 - u_d1)
    d1[31] = c1 * u_d1
    c1_eff = c1

    c2_inc, c2_y, c2_univ, c2_auto = 0.87, 0.87, 0.95, 0.93
    d2_inc = frechet_joint([arms[0][1] / c2_inc, arms[1][1] / c2_inc, arms[2][1] / c2_inc], phi_inc)
    r2 = c2_inc / c2_y
    u_y2 = arms[3][1] / c2_y
    d2_both = frechet_couple(d2_inc, u_y2, phi_yx, lambda mi: bool(mi & 4))
    d2_allo4 = [r2 * d2_both[k] for k in range(16)]
    d2_allo4[0] += (1.0 - r2) * (1.0 - u_y2)
    d2_allo4[8] += (1.0 - r2) * u_y2
    biv2 = biv_bern(c2_y / c2_univ, c2_auto / c2_univ, phi_c)
    u_d2 = arms[4][1] / c2_auto
    d2 = [0.0] * 32
    d2[0] += 1.0 - c2_univ
    for (s0, s1), wp in biv2.items():
        w = c2_univ * wp
        if s0 == 0 and s1 == 0:
            d2[0] += w
        elif s0 == 1 and s1 == 0:
            for m4 in range(16):
                d2[m4] += w * d2_allo4[m4]
        elif s0 == 0 and s1 == 1:
            d2[0] += w * (1.0 - u_d2)
            d2[16] += w * u_d2
        else:
            for m4 in range(16):
                d2[m4] += w * d2_allo4[m4] * (1.0 - u_d2)
                d2[m4 | 16] += w * d2_allo4[m4] * u_d2
    c2_eff = c2_univ * (1.0 - biv2[(0, 0)])

    d3_inc = frechet_joint([arms[0][2] / c3, arms[1][2] / c3, arms[2][2] / c3], phi_inc)
    d3_both = frechet_couple(d3_inc, arms[3][2] / c3, phi_yx, lambda mi: bool(mi & 4))
    d3_5cond = frechet_couple(d3_both, arms[4][2] / c3, phi_c, lambda m4: m4 != 0)
    d3 = [0.0] * 32
    d3[0] = 1.0 - c3
    for k in range(32):
        d3[k] += c3 * d3_5cond[k]
    c3_eff = c3

    c4_univ, c4_pouch, c4_r3p = 0.92, 0.85, 0.85
    sh4 = biv_bern(c4_pouch / c4_univ, c4_r3p / c4_univ, phi_c)
    d4 = [0.0] * 32
    d4[0] = 1.0 - c4_univ
    for (sp, s3), ws in sh4.items():
        wt = c4_univ * ws
        route_masks = []
        for rname, sflag, cr in (("R1", sp, c4_pouch), ("R2", sp, c4_pouch), ("R3P", s3, c4_r3p)):
            idxs = [i for i in range(5) if routes[i] == rname]
            if sflag == 0:
                route_masks.append([(0, 1.0)])
            else:
                fj = frechet_joint([arms[i][3] / cr for i in idxs], 1.0)
                route_masks.append([
                    (sum((1 << idxs[k]) for k in range(len(idxs)) if (bm >> k) & 1), pr)
                    for bm, pr in enumerate(fj) if pr > 0
                ])
        comb = [(0, wt)]
        for ev in route_masks:
            comb = [(m0 | m1, w0 * w1) for m0, w0 in comb for m1, w1 in ev]
        for mf, wf in comb:
            d4[mf] += wf
    c4_eff = c4_univ * (1.0 - sh4[(0, 0)])

    caps = [c1_eff, c2_eff, c3_eff, c4_eff]
    for h_idx, dh in enumerate((d1, d2, d3, d4)):
        require_cond(abs(sum(dh) - 1.0) < 1e-12, f"H{h_idx+1} distribution sum != 1.0")
        require_cond(caps[h_idx] >= (1.0 - dh[0]) - 1e-12, f"H{h_idx+1} cap incoherent")
        for i in range(5):
            marg = sum(dh[m] for m in range(32) if (m >> i) & 1)
            require_cond(abs(marg - arms[i][h_idx]) < 1e-9, f"Arm {i} H{h_idx+1} marginal mismatch")

    v = d1
    for dh in (d2, d3):
        nxt = [0.0] * 32
        for m1 in range(32):
            if v[m1] == 0.0:
                continue
            for m2 in range(32):
                if dh[m2] != 0.0:
                    nxt[m1 & m2] += v[m1] * dh[m2]
        v = nxt

    locked = 0.0
    mod100 = 0.0
    for mc in range(1, 32):
        wc = v[mc]
        if wc == 0.0:
            continue
        allowed: set[str] = set()
        for i in range(5):
            if (mc >> i) & 1:
                allowed.update(compat_map[cell_classes[i]])
        for mh in range(1, 32):
            wh = d4[mh]
            if wh == 0.0:
                continue
            if (mc & mh) != 0:
                locked += wc * wh
            if any(routes[j] in allowed for j in range(5) if (mh >> j) & 1):
                mod100 += wc * wh

    s_min, s_max = strassen_bipartite_bounds(v, d4, routes, cell_classes, compat_map)
    locked_exact = locked * 100.0
    modular_exact = mod100 * 100.0
    ceiling_exact = c1_eff * c2_eff * c3_eff * c4_eff * 100.0
    caps_exact = [c * 100.0 for c in caps]
    any_exact = [(1.0 - d[0]) * 100.0 for d in (d1, d2, d3, d4)]
    strassen_exact = [s_min, s_max]

    return {
        "c3_pct": round(c3 * 100.0, 2),
        "locked_exact": locked_exact,
        "modular_exact": modular_exact,
        "ceiling_exact": ceiling_exact,
        "locked_pct": round(locked_exact, 4),
        "modular_pct": round(modular_exact, 4),
        "ceiling_pct": round(ceiling_exact, 4),
        "hurdle_caps_exact_pct": caps_exact,
        "hurdle_caps_pct": [round(x, 4) for x in caps_exact],
        "hurdle_any_success_exact_pct": any_exact,
        "hurdle_any_success_pct": [round(x, 4) for x in any_exact],
        "strassen_h123_h4_exact": strassen_exact,
        "strassen_h123_h4_pct": [round(s_min, 4), round(s_max, 4)],
    }


def subadditive_channel_reduction(F_base_pp: float, rel_reductions: list[float], omega: float) -> float:
    if not rel_reductions:
        return 0.0
    s_ind = math.prod(1.0 - r for r in rel_reductions)
    s_max = 1.0 - max(rel_reductions)
    return F_base_pp * (1.0 - ((1.0 - omega) * s_ind + omega * s_max))


def _check_contract_row_exact(
    computed: dict[str, Any],
    expected: dict[str, Any],
    label: str,
    exact_delta: float | None = None,
    *,
    exact_tol: float = 1e-12,
) -> float:
    """Verify BOTH unrounded IEEE-754 float64 parity (< 1e-12) AND exact 4-decimal display parity."""
    max_exact_err = 0.0
    for fld in ("locked_exact", "modular_exact", "ceiling_exact"):
        err = abs(computed[fld] - expected[fld])
        require_cond(
            err < exact_tol,
            f"Unrounded master contract parity drift >= {exact_tol} on {label}.{fld}: computed={computed[fld]!r} expected={expected[fld]!r} err={err:.3e}",
        )
        max_exact_err = max(max_exact_err, err)
    for fld in ("locked_pct", "modular_pct", "ceiling_pct"):
        require_cond(
            computed[fld] == expected[fld],
            f"Display master contract parity mismatch on {label}.{fld}: computed={computed[fld]} expected={expected[fld]}",
        )
    for vec_exact in ("hurdle_caps_exact_pct", "hurdle_any_success_exact_pct", "strassen_h123_h4_exact"):
        if vec_exact in expected:
            cv, ev = computed[vec_exact], expected[vec_exact]
            require_cond(len(cv) == len(ev), f"Vector length mismatch on {label}.{vec_exact}")
            for i, (a, b) in enumerate(zip(cv, ev)):
                err = abs(a - b)
                require_cond(
                    err < exact_tol,
                    f"Unrounded vector parity drift >= {exact_tol} on {label}.{vec_exact}[{i}]: {a!r} vs {b!r} err={err:.3e}",
                )
                max_exact_err = max(max_exact_err, err)
    for vec_pct in ("hurdle_caps_pct", "hurdle_any_success_pct", "strassen_h123_h4_pct"):
        if vec_pct in expected:
            require_cond(
                computed[vec_pct] == expected[vec_pct],
                f"Display vector mismatch on {label}.{vec_pct}: computed={computed[vec_pct]} expected={expected[vec_pct]}",
            )
    if exact_delta is not None:
        exp_d_exact = expected["delta_vs_honest_l1_exact_pp"]
        err_d = abs(exact_delta - exp_d_exact)
        require_cond(
            err_d < exact_tol,
            f"Unrounded delta parity drift >= {exact_tol} on {label}: computed={exact_delta!r} expected={exp_d_exact!r} err={err_d:.3e}",
        )
        max_exact_err = max(max_exact_err, err_d)
        disp_d = round(exact_delta, 4)
        require_cond(
            disp_d == expected["delta_vs_honest_l1_pct_pp"],
            f"Display delta mismatch on {label}: computed={disp_d} expected={expected['delta_vs_honest_l1_pct_pp']}",
        )
    return max_exact_err


def verify_part_d(master_contract: dict[str, Any], contract_sha256: str, manifest_sha256: str) -> dict[str, Any]:
    # Design A STRICTLY FROZEN at (0.88, 0.78, 0.57, 0.69) across ALL scenarios!
    L1_ARMS = [(0.88, 0.78, 0.57, 0.69), (0.88, 0.79, 0.64, 0.70), (0.88, 0.82, 0.73, 0.69), (0.88, 0.84, 0.80, 0.72), (0.62, 0.92, 0.70, 0.70)]
    C3_NOINV_ARMS = [(0.88, 0.78, 0.57, 0.69), (0.88, 0.79, 0.70, 0.70), (0.88, 0.82, 0.78, 0.69), (0.88, 0.84, 0.83, 0.72), (0.62, 0.92, 0.75, 0.70)]
    C3_FULL_ARMS = [(0.88, 0.78, 0.57, 0.69), (0.88, 0.79, 0.73, 0.70), (0.88, 0.82, 0.80, 0.69), (0.88, 0.84, 0.85, 0.72), (0.62, 0.92, 0.77, 0.70)]

    r_l1_phi0 = eval_5arm_exact_2pow20(L1_ARMS, c3=0.89, phi_inc=0.0)
    r_l1_honest = eval_5arm_exact_2pow20(L1_ARMS, c3=0.89, phi_inc=0.50)
    r_c3_noinv = eval_5arm_exact_2pow20(C3_NOINV_ARMS, c3=0.930, phi_inc=0.50)
    r_c3_full = eval_5arm_exact_2pow20(C3_FULL_ARMS, c3=0.942, phi_inc=0.50)
    r_c3_cap89 = eval_5arm_exact_2pow20(C3_FULL_ARMS, c3=0.890, phi_inc=0.50)

    delta_noinv_exact = r_c3_noinv["modular_exact"] - r_l1_honest["modular_exact"]
    delta_full_exact = r_c3_full["modular_exact"] - r_l1_honest["modular_exact"]
    delta_cap89_exact = r_c3_cap89["modular_exact"] - r_l1_honest["modular_exact"]
    common_cap_effect_exact = r_c3_full["modular_exact"] - r_c3_cap89["modular_exact"]

    rs = master_contract["reachable_scenarios"]
    ms = master_contract["mandatory_audit_sensitivities"]
    s24 = master_contract["states_24"]
    ev = master_contract["released_product_24state_scenario_average"]

    err_l1 = _check_contract_row_exact(r_l1_phi0, rs["L1_shipped_IIP0035_phi0"], "L1_shipped_IIP0035_phi0")
    err_hon = _check_contract_row_exact(r_l1_honest, rs["L1_honest_monoculture_phi_inc_0.50"], "L1_honest_monoculture_phi_inc_0.50")
    err_noinv = _check_contract_row_exact(r_c3_noinv, rs["W6_C3_noinv_standalone_A_frozen"], "W6_C3_noinv_standalone_A_frozen", delta_noinv_exact)
    err_full = _check_contract_row_exact(r_c3_full, rs["W6_C3_full_standalone_A_frozen"], "W6_C3_full_standalone_A_frozen", delta_full_exact)
    err_cap89 = _check_contract_row_exact(r_c3_cap89, ms["Sens_C3_full_c3cap_held_0.89"], "Sens_C3_full_c3cap_held_0.89", delta_cap89_exact)

    # Verify single-package 24-state EV entries match BOTH unrounded (< 1e-12) AND display pct!
    err_s24_part = max(
        abs(s24["c1=0|c2=0|c3=partial|c4=0"]["modular_exact"] - r_c3_noinv["modular_exact"]),
        abs(s24["c1=0|c2=0|c3=partial|c4=0"]["locked_exact"] - r_c3_noinv["locked_exact"]),
    )
    err_s24_full = max(
        abs(s24["c1=0|c2=0|c3=full|c4=0"]["modular_exact"] - r_c3_full["modular_exact"]),
        abs(s24["c1=0|c2=0|c3=full|c4=0"]["locked_exact"] - r_c3_full["locked_exact"]),
    )
    require_cond(err_s24_part < 1e-12 and s24["c1=0|c2=0|c3=partial|c4=0"]["modular_pct"] == r_c3_noinv["modular_pct"], "states_24 C3 partial drift")
    require_cond(err_s24_full < 1e-12 and s24["c1=0|c2=0|c3=full|c4=0"]["modular_pct"] == r_c3_full["modular_pct"], "states_24 C3 full drift")

    for reg in ("Conservative", "Central", "Upper"):
        p_full = ev[reg]["priors"]["p_c3_none_partial_full"][2]
        require_cond(0.10 <= p_full <= 0.17, f"InvVax Stage-0 prior out of [0.10, 0.17] for {reg}: {p_full}")

    max_unrounded_err = max(err_l1, err_hon, err_noinv, err_full, err_cap89, err_s24_part, err_s24_full)

    # Illustrative H3 channel-budget omega sensitivity (ZERO ABT-199, ZERO CCL22 double-count)
    F_a, F_b, F_c = 6.5, 2.5, 2.0
    omega_grid = (0.0, 0.10, 0.25, 0.50, 0.75, 0.90, 1.00)
    sweep_noinv = []
    sweep_full = []
    for om in omega_grid:
        da_n = subadditive_channel_reduction(F_a, [1.8 / F_a, 0.6 / F_a, 0.9 / F_a], om)
        da_f = subadditive_channel_reduction(F_a, [2.8 / F_a, 1.8 / F_a, 0.6 / F_a, 0.9 / F_a], om)
        db = 1.15
        dc = 0.85
        raw_n = round(89.0 + da_n + db + dc, 3)
        raw_f = round(89.0 + da_f + db + dc, 3)
        sweep_noinv.append({
            "omega": om, "ch_a_pp": round(da_n, 3), "ch_b_pp": db, "ch_c_pp": dc,
            "raw_c3_pct": raw_n, "capped_c3_pct": min(93.0, raw_n),
        })
        sweep_full.append({
            "omega": om, "ch_a_pp": round(da_f, 3), "ch_b_pp": db, "ch_c_pp": dc,
            "raw_c3_pct": raw_f, "capped_c3_pct": min(94.2, raw_f),
        })
    require_cond(sweep_noinv[3]["raw_c3_pct"] >= 93.0 and sweep_full[3]["raw_c3_pct"] >= 94.2, "Clean central omega=0.50 must support 93.0%/94.2%")
    require_cond(all(sweep_full[i]["raw_c3_pct"] >= sweep_full[i + 1]["raw_c3_pct"] for i in range(len(omega_grid) - 1)), "Omega sweep must be monotonically non-increasing")

    tak101_hl_min = round((7.0 * 24.0) / 4.9, 1)
    tak101_hl_max = round((7.0 * 24.0) / 2.0, 1)
    kan101_geomean_hl = round((7.0 * 1440.0) / 31.72, 1)
    require_cond(tak101_hl_min == 34.3 and tak101_hl_max == 84.0, f"TAK-101 7d half-lives mismatch: {tak101_hl_min}..{tak101_hl_max}")
    require_cond(abs(kan101_geomean_hl - 317.8) < 0.2, f"KAN-101 geomean half-lives mismatch: {kan101_geomean_hl}")

    return {
        "invvax_evidence_fidelity": {
            "schedule_days": [-28, -21, -7],
            "prospective_clearance_requirement": "Measured pre-transplant Day -4 plasma (< plasma_llod <= 1.0 ng/mL) and tissue (< tissue_llod <= 1.0 ng/g) clearance is a PROSPECTIVE Gate-34 requirement (not yet observed).",
            "unsourced_cnp103_1p5h_claim_removed": True,
            "cnp103_sponsor_antigen_panel": ["preproinsulin", "GAD65", "IGRP", "ZnT8"],
            "tak101_sister_nanoparticle_free_gliadin_t_half_h_range": [2.0, 4.9],
            "tak101_7day_half_lives_range": [tak101_hl_min, tak101_hl_max],
            "tak101_provenance": "Kelly et al. 2021 Gastroenterology (PMID:33722583 / PMC9053078): celiac sister-study nanoparticle-free gliadin plasma measurement; does NOT certify CNP-103 plasma or tissue clearance.",
            "kan101_celiac_geomean_t_half_min": 31.72,
            "kan101_7day_geomean_half_lives": kan101_geomean_hl,
            "kan101_caveats": "Murray et al. 2023 (PMID:37329900) geometric mean with high inter-individual variability (not worst-case T1D bound); Phase 2 NCT06001177 primary histological outcome was NOT statistically significant.",
            "cnp103_trial_scope": "NCT06783309 enrolls newly diagnosed T1D patients (NOT islet transplant recipients), has NO posted results, and provides zero human C-peptide graft efficacy readouts.",
            "pvt201_and_blimp1_scope_corrections": {
                "PVT201_NCT06798454": "PBC/PSC clinical program (NOT T1D).",
                "Garnica_2025_PMID_40066448": "Mouse CNS (EAE) BLIMP-1 TR1 study (NOT human T1D).",
            },
            "hla_enrollment_vs_efficacy_note": "HLA-unrestricted trial enrollment does NOT guarantee 100% clinical efficacy across all HLA genotypes; zero-AE guarantee removed.",
            "human_t1d_cpeptide_readouts_count": 0,
            "honest_solo_c3_lift_pp_range": [2.5, 3.0],
            "honest_solo_c3_lift_pp_central": 2.8,
            "stage0_prior_strictly_bounded_pct": [10.0, 17.0],
            "master_contract_invvax_priors_pct": {
                "Conservative": round(ev["Conservative"]["priors"]["p_c3_none_partial_full"][2] * 100.0, 2),
                "Central": round(ev["Central"]["priors"]["p_c3_none_partial_full"][2] * 100.0, 2),
                "Upper": round(ev["Upper"]["priors"]["p_c3_none_partial_full"][2] * 100.0, 2),
            },
        },
        "clinical_trials_verified_snapshot": PINNED_CLINICAL_TRIALS_SNAPSHOT,
        "h3_channel_sensitivity_disclosure": (
            "Illustrative channel-budget sensitivity ONLY: arm-specific H3 marginals and the shared H3 common cap "
            "(c3: 89.0% -> 93.0% No-InvVax / 94.2% Full) are explicit scenario assumptions preceding the illustrative omega sweep. "
            "Holding the shared common H3 cap fixed at 89.0% shifts standalone full modular success from 63.2079% to 60.9698% "
            "(a 2.2381 pp common-cap scenario effect). Phantom ABT-199 (+0.25 pp) and CCL22 double-counting are removed."
        ),
        "h3_scenario_input_ledger": {
            "shared_common_h3_cap_baseline_pct": 89.0,
            "shared_common_h3_cap_noinv_pct": 93.0,
            "shared_common_h3_cap_full_pct": 94.2,
            "common_cap_scenario_effect_exact_pp": common_cap_effect_exact,
            "common_cap_scenario_effect_pct_pp": round(common_cap_effect_exact, 4),
            "arm_level_inputs_and_gates": [
                {"arm": "A", "h3_base": 0.57, "h3_noinv": 0.57, "h3_full": 0.57, "adjunct_exposure": "NONE (frozen; pre-existing catalase hydrogel only)", "qualifying_gates": ["FROZEN_INVARIANT"]},
                {"arm": "B", "h3_base": 0.64, "h3_noinv": 0.70, "h3_full": 0.73, "adjunct_exposure": "SHIELD + INS L82I + Cuff v2.0 (+ prospective InvVax in Full)", "qualifying_gates": ["Gate 34-SHIELD-SEL", "Gate 34-INS-L82I-ELISA-PE2MAX", "Gate 34-CUFF-V2-DISULFIDE-C5B9", "Gate 34-INVVAX-RECALL"]},
                {"arm": "X", "h3_base": 0.73, "h3_noinv": 0.78, "h3_full": 0.80, "adjunct_exposure": "SHIELD + INS L82I + Cuff v2.0 (+ prospective InvVax in Full)", "qualifying_gates": ["Gate 34-SHIELD-SEL", "Gate 34-INS-L82I-ELISA-PE2MAX", "Gate 34-CUFF-V2-DISULFIDE-C5B9", "Gate 34-INVVAX-RECALL"]},
                {"arm": "Y", "h3_base": 0.80, "h3_noinv": 0.83, "h3_full": 0.85, "adjunct_exposure": "SHIELD + INS L82I + Cuff v2.0 (+ prospective InvVax in Full)", "qualifying_gates": ["Gate 34-SHIELD-SEL", "Gate 34-INS-L82I-ELISA-PE2MAX", "Gate 34-CUFF-V2-DISULFIDE-C5B9", "Gate 34-INVVAX-RECALL"]},
                {"arm": "D", "h3_base": 0.70, "h3_noinv": 0.75, "h3_full": 0.77, "adjunct_exposure": "SHIELD + INS L82I + Cuff v2.0 (+ prospective InvVax in Full)", "qualifying_gates": ["Gate 34-SHIELD-SEL", "Gate 34-INS-L82I-ELISA-PE2MAX", "Gate 34-CUFF-V2-DISULFIDE-C5B9", "Gate 34-INVVAX-RECALL"]},
            ],
        },
        "clean_subadditive_omega_sweep_no_invvax": sweep_noinv,
        "clean_subadditive_omega_sweep_with_invvax": sweep_full,
        "exact_2pow20_parity_wave6_master_contract": {
            "external_master_contract_verified": True,
            "external_master_contract_sha256": contract_sha256,
            "external_arm_manifest_sha256": manifest_sha256,
            "unrounded_parity_tolerance": 1e-12,
            "max_unrounded_parity_error_all_c3_scenarios": max_unrounded_err,
            "design_a_strictly_frozen_tuple": [0.88, 0.78, 0.57, 0.69],
            "L1_shipped_IIP0035_phi0": r_l1_phi0,
            "L1_honest_monoculture_phi_inc_0.50": r_l1_honest,
            "W6_C3_noinv_standalone_A_frozen": {
                **r_c3_noinv,
                "delta_vs_honest_l1_exact_pp": delta_noinv_exact,
                "delta_vs_honest_l1_pct_pp": round(delta_noinv_exact, 4),
            },
            "W6_C3_full_standalone_A_frozen": {
                **r_c3_full,
                "delta_vs_honest_l1_exact_pp": delta_full_exact,
                "delta_vs_honest_l1_pct_pp": round(delta_full_exact, 4),
            },
            "Sens_C3_full_c3cap_held_0.89": {
                **r_c3_cap89,
                "delta_vs_honest_l1_exact_pp": delta_cap89_exact,
                "delta_vs_honest_l1_pct_pp": round(delta_cap89_exact, 4),
            },
        },
    }


# ---------------------------------------------------------------------------
# PART E: STRICT Fail-Closed Gate 34 Evaluators (R2-01, R2-06, R2-07, R2-18 Closed!)
# ---------------------------------------------------------------------------
def _require_exact_bool(val: Any, name: str) -> bool:
    if type(val) is not bool:
        raise ValueError(f"{name} must be exact bool (str/int rejected), got {type(val).__name__}")
    return val


def _require_exact_int(val: Any, name: str, *, lo: int | None = None, hi: int | None = None) -> int:
    if isinstance(val, bool) or not isinstance(val, int):
        raise ValueError(f"{name} must be exact int (float/bool/str rejected), got {type(val).__name__}")
    if abs(val) > 10 ** 300:
        raise ValueError(f"{name} overflowing integer rejected")
    if lo is not None and val < lo:
        raise ValueError(f"{name} out of physical bounds (< {lo}): {val}")
    if hi is not None and val > hi:
        raise ValueError(f"{name} out of physical bounds (> {hi}): {val}")
    return val


def _require_bounded_float(
    val: Any, name: str, *, lo: float | None = None, hi: float | None = None, strict_lo: bool = False
) -> float:
    if isinstance(val, bool) or not isinstance(val, (int, float)):
        raise ValueError(f"{name} must be finite numeric (bool/str rejected), got {type(val).__name__}")
    if isinstance(val, int) and abs(val) > 10 ** 300:
        raise ValueError(f"{name} overflowing integer rejected before float conversion")
    fval = float(val)
    if not math.isfinite(fval) or abs(fval) > 1e300:
        raise ValueError(f"{name} non-finite or overflowing")
    if lo is not None:
        if (strict_lo and fval <= lo) or (not strict_lo and fval < lo):
            raise ValueError(f"{name} out of physical bounds ({'<=' if strict_lo else '<'} {lo}): {fval}")
    if hi is not None and fval > hi:
        raise ValueError(f"{name} out of physical bounds (> {hi}): {fval}")
    return fval


def _require_nonempty_str(val: Any, name: str) -> str:
    if not isinstance(val, str) or not val.strip():
        raise ValueError(f"{name} must be non-empty string, got {type(val).__name__}")
    return val.strip()


def _is_strict_canonical_ascii_id(raw: str) -> bool:
    """Enforce strict canonical ASCII identifier grammar: ^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$, ASCII-only, NFKC-invariant, zero C*/Z*/M* chars."""
    if not isinstance(raw, str) or not raw:
        return False
    if not raw.isascii():
        return False
    if unicodedata.normalize("NFKC", raw) != raw:
        return False
    if any(unicodedata.category(ch)[0] in ("C", "Z", "M") for ch in raw):
        return False
    return CANONICAL_DONOR_ID_RE.fullmatch(raw) is not None


def _require_canonical_ascii_id(
    val: Any,
    name: str,
    *,
    rtag: str,
    fail_reasons: list[str],
) -> str:
    """Validate strict canonical ASCII identifier grammar on Gate 34 assay/study/lot/analyte IDs without silent whitespace normalization."""
    if not isinstance(val, str) or not val.strip():
        raise ValueError(f"{name} must be non-empty string, got {type(val).__name__}")
    if not _is_strict_canonical_ascii_id(val):
        fail_reasons.append(f"{rtag}NONCANONICAL_ASCII_IDENTIFIER_REJECTED:{name}:{val[:64]!r}")
        return val.strip()
    return val


def _scrub_donor_id_casefold(raw: str) -> str:
    """Apply NFKD, strip Unicode C*/Z*/M* chars, map Unicode dashes to '-', normalize digits & NFKC, and casefold."""
    def _clean_pass(text: str) -> str:
        out_chars: list[str] = []
        for ch in text:
            cat = unicodedata.category(ch)
            if cat[0] in ("C", "Z", "M"):
                continue
            if cat == "Pd" or ch in _UNICODE_DASH_CHARS:
                out_chars.append("-")
            elif cat == "Nd":
                out_chars.append(str(unicodedata.digit(ch)))
            else:
                out_chars.append(ch)
        return "".join(out_chars)

    nfkd_clean = _clean_pass(unicodedata.normalize("NFKD", raw))
    nfkc_clean = _clean_pass(unicodedata.normalize("NFKC", nfkd_clean))
    return _DONOR_INVISIBLE_OR_SPACE_RE.sub("", nfkc_clean).casefold()


def _canonical_donor_identity_key(raw: str) -> str:
    """Compute strictly ordered separator-first -> numeric-padding-second canonical donor identity key (Audit R8-06).

    Order invariant:
      1. NFKD -> strip C*/Z*/M* -> map Unicode dashes (`\\u2010-\\u2015`, `\\u2212`, etc.) to '-' -> NFKC -> casefold
      2. Strip ALL ASCII separators (`._:-`) and any non-alphanumeric punctuation FIRST
      3. Normalize every contiguous ASCII digit run by stripping leading zeros (preserving single '0') SECOND
    """
    scrubbed = _scrub_donor_id_casefold(raw)
    no_sep = _ASCII_DONOR_SEPARATOR_RE.sub("", scrubbed)
    alnum = "".join(ch for ch in no_sep if ch.isalnum())
    return re.sub(r"[0-9]+", lambda m: m.group(0).lstrip("0") or "0", alnum)


def _extract_and_validate_issuer_ids(
    obj: dict[str, Any],
    *,
    location: str,
    rtag: str,
    fail_reasons: list[str],
) -> tuple[list[str], list[str], bool, bool]:
    """Validate donor/registry issuer identity fields on `obj` under strict canonical ASCII grammar (Audit R9-04).

    Returns (all_nonempty_issuers, valid_canonical_issuers, has_noncanonical, saw_empty_str).
    - Non-string values raise ValueError (FAIL_MALFORMED_INPUT).
    - Omitted or None fields are absent (never treated as agreeing with another absent issuer).
    - Exact empty strings ("") set saw_empty_str=True (missing/unestablished; fails if mixed with a non-empty issuer).
    - Any non-empty string violating strict canonical ASCII grammar (including whitespace-only, invisible chars,
      or non-ASCII chars) records INS_NONCANONICAL_DONOR_ISSUER_ID_REJECTED (FAIL).
    """
    nonempty: list[str] = []
    valid_canon: list[str] = []
    has_noncanonical = False
    saw_empty_str = False
    for fld in INS_DONOR_ISSUER_FIELDS:
        if fld not in obj or obj[fld] is None:
            continue
        raw_val = obj[fld]
        if not isinstance(raw_val, str):
            raise ValueError(f"{location}.{fld} must be canonical ASCII string, got {type(raw_val).__name__}")
        if raw_val == "":
            saw_empty_str = True
            continue
        if not _is_strict_canonical_ascii_id(raw_val):
            has_noncanonical = True
            fail_reasons.append(f"{rtag}INS_NONCANONICAL_DONOR_ISSUER_ID_REJECTED:{location}.{fld}:{raw_val[:64]!r}")
        else:
            valid_canon.append(raw_val)
        nonempty.append(raw_val)
    if saw_empty_str and nonempty:
        fail_reasons.append(f"{rtag}INS_INCONSISTENT_DONOR_ISSUER_ID_FAIL:{location}:empty_and_nonempty_issuer_fields")
    return nonempty, valid_canon, has_noncanonical, saw_empty_str


def _parse_and_validate_donor_id(
    raw: Any,
    *,
    field_name: str,
    allele_tag: str,
    rtag: str,
    fail_reasons: list[str],
) -> tuple[str, str, str]:
    """Validate strict canonical ASCII donor ID grammar and return (raw, casefold_key, canon_key).

    Raises ValueError ONLY for non-string or empty/separator-only malformed entries.
    For non-canonical strings with recoverable alphanumeric content (e.g. whitespace-padded,
    tabs/newlines, zero-width chars, soft hyphens, fullwidth chars, combining marks, or Unicode
    hyphens), records INS_NONCANONICAL_DONOR_ID_REJECTED in fail_reasons while computing scrubbed
    NFKD/NFKC casefolded and separator-first -> numeric-padding-second canonical identity keys so
    deduplicated donor counts and Clopper-Pearson U95 bounds are NEVER understated.
    """
    if not isinstance(raw, str):
        raise ValueError(f"{field_name} must be str, got {type(raw).__name__}")
    is_canon = _is_strict_canonical_ascii_id(raw)
    casefold_key = _scrub_donor_id_casefold(raw)
    canon_key = _canonical_donor_identity_key(raw)
    if not casefold_key or not canon_key:
        raise ValueError(f"{field_name} must contain non-empty canonical donor identifier")
    if not is_canon:
        fail_reasons.append(f"{rtag}INS_NONCANONICAL_DONOR_ID_REJECTED:{allele_tag}:{raw[:64]!r}")
    return raw, casefold_key, canon_key


def _validate_optional_canonical_id_list(
    src: dict[str, Any],
    *,
    keys: tuple[str, ...],
    expected_count: int | None,
    min_unique: int | None,
    pfx: str,
    rtag: str,
    module_tag: str,
    fail_reasons: list[str],
) -> bool:
    """Apply identical canonical ASCII ID grammar & separator-first -> numeric-padding-second deduplication to optional donor/subject ID lists across Gate 34.

    Returns True iff any internal ID-list consistency contradiction occurred (noncanonical ID, duplicate ID,
    formatting variant, unique count != declared count, or disagreeing alias lists).
    """
    present_canon_sets: dict[str, set[str]] = {}
    seen_raw_across_keys: dict[str, set[str]] = {}
    had_internal_conflict = False
    for key in keys:
        if key not in src or src[key] is None:
            continue
        raw_ids = src[key]
        if not isinstance(raw_ids, (list, tuple)):
            raise ValueError(f"{pfx}{key} must be list of canonical ASCII ID strings")
        parsed = [
            _parse_and_validate_donor_id(
                x,
                field_name=f"{pfx}{key}[]",
                allele_tag=f"{module_tag}.{key}",
                rtag=rtag,
                fail_reasons=fail_reasons,
            )
            for x in raw_ids
        ]
        if any(not _is_strict_canonical_ascii_id(raw_id) for raw_id, _, _ in parsed):
            had_internal_conflict = True
        canon_keys = [ckey for _, _, ckey in parsed]
        seen_raw: dict[str, set[str]] = {}
        for raw_id, _, ckey in parsed:
            seen_raw.setdefault(ckey, set()).add(raw_id)
            seen_raw_across_keys.setdefault(ckey, set()).add(raw_id)
        present_canon_sets[key] = set(canon_keys)
        if len(set(canon_keys)) != len(canon_keys):
            fail_reasons.append(f"{rtag}{module_tag}_DUPLICATE_DONOR_OR_SUBJECT_ID:{key}")
            had_internal_conflict = True
        for ckey, raws in sorted(seen_raw.items()):
            if len(raws) > 1:
                fail_reasons.append(
                    f"{rtag}{module_tag}_INCONSISTENT_ID_FORMATTING_VARIANT:{key}:{ckey}:{sorted(r[:32] for r in raws)}"
                )
                had_internal_conflict = True
        if expected_count is not None and len(set(canon_keys)) != expected_count:
            fail_reasons.append(
                f"{rtag}{module_tag}_UNIQUE_ID_COUNT_MISMATCH:{key}:unique={len(set(canon_keys))}!=declared={expected_count}"
            )
            had_internal_conflict = True
        if min_unique is not None and len(set(canon_keys)) < min_unique:
            fail_reasons.append(
                f"{rtag}{module_tag}_INSUFFICIENT_UNIQUE_IDS:{key}:unique={len(set(canon_keys))}<{min_unique}"
            )
    if len(present_canon_sets) > 1:
        key_names = sorted(present_canon_sets.keys())
        base_set = present_canon_sets[key_names[0]]
        for other_k in key_names[1:]:
            if present_canon_sets[other_k] != base_set:
                fail_reasons.append(f"{rtag}{module_tag}_ALIAS_ID_LIST_MISMATCH:{key_names[0]}!={other_k}")
                had_internal_conflict = True
        for ckey, raws in sorted(seen_raw_across_keys.items()):
            if len(raws) > 1:
                fail_reasons.append(
                    f"{rtag}{module_tag}_INCONSISTENT_ID_FORMATTING_VARIANT:cross_alias:{ckey}:{sorted(r[:32] for r in raws)}"
                )
                had_internal_conflict = True
    return had_internal_conflict


def _malformed_rejection(exc: Exception, extra: dict[str, Any] | None = None) -> dict[str, Any]:
    out: dict[str, Any] = {
        "verdict": "FAIL",
        "decision": "FAIL_MALFORMED_INPUT",
        "promotion_authorized": False,
        "evidence_tier": None,
        "reasons": [f"MALFORMED_INPUT:{exc}"],
        "missing_fields": [],
    }
    if extra:
        out.update(extra)
    return out


def _verify_manifest_context(
    arm_manifest: Any,
    obs: dict[str, Any],
    fail_reasons: list[str],
    missing_fields: list[str],
) -> dict[str, Any] | None:
    """Require a verified canonical wave6_canonical_arm_manifest across ALL FOUR Gate 34 evaluators."""
    verified_manifest: dict[str, Any] | None = None
    if not isinstance(arm_manifest, dict):
        fail_reasons.append("MISSING_OR_INVALID_CANONICAL_MANIFEST")
    else:
        try:
            check_strictly_finite(arm_manifest, "arm_manifest")
            canon_sha = _canonical_json_sha256(arm_manifest)
        except (TypeError, ValueError, OverflowError):
            canon_sha = ""
        if canon_sha != EXPECTED_ARM_MANIFEST_CANONICAL_JSON_SHA256:
            fail_reasons.append("MUTATED_OR_UNTRUSTED_CANONICAL_MANIFEST")
        else:
            verified_manifest = arm_manifest

    if "manifest_sha256" not in obs or obs["manifest_sha256"] is None:
        missing_fields.append("manifest_sha256")
    else:
        msha = _require_nonempty_str(obs["manifest_sha256"], "manifest_sha256")
        if msha != EXPECTED_ARM_MANIFEST_SHA256:
            fail_reasons.append(f"MANIFEST_SHA256_MISMATCH:{msha}")

    if "canonical_arm_manifest_sha256" in obs and obs["canonical_arm_manifest_sha256"] is not None:
        cmsha = _require_nonempty_str(obs["canonical_arm_manifest_sha256"], "canonical_arm_manifest_sha256")
        if cmsha != EXPECTED_ARM_MANIFEST_SHA256:
            fail_reasons.append(f"CANONICAL_ARM_MANIFEST_SHA256_MISMATCH:{cmsha}")

    return verified_manifest


def _check_arm_and_design_a_invariants(
    obs: dict[str, Any],
    eligibility_key: str,
    verified_manifest: dict[str, Any] | None,
    fail_reasons: list[str],
    missing_fields: list[str],
) -> tuple[str | None, dict[str, Any] | None]:
    """Enforce target_arm_id != 'A' (verified against manifest) AND design_a_exposed == False."""
    arm_id: str | None = None
    arm_entry: dict[str, Any] | None = None
    if "target_arm_id" not in obs or obs["target_arm_id"] is None:
        missing_fields.append("target_arm_id")
    else:
        arm_id = _require_nonempty_str(obs["target_arm_id"], "target_arm_id")
        valid_arms = ("A", "B", "X", "Y", "D", "Z")
        if arm_id not in valid_arms:
            fail_reasons.append(f"UNKNOWN_TARGET_ARM_ID:{arm_id}")
        elif arm_id == "A":
            fail_reasons.append(f"DESIGN_A_FROZEN_INELIGIBLE:{eligibility_key}")
        elif verified_manifest is not None:
            arms_tbl = verified_manifest.get("arms", {})
            entry = arms_tbl.get(arm_id)
            if not isinstance(entry, dict) or entry.get(eligibility_key) is not True:
                fail_reasons.append(f"MANIFEST_ARM_INELIGIBLE:{arm_id}:{eligibility_key}")
            else:
                arm_entry = entry

    if "design_a_exposed" not in obs or obs["design_a_exposed"] is None:
        missing_fields.append("design_a_exposed")
    else:
        da_exp = _require_exact_bool(obs["design_a_exposed"], "design_a_exposed")
        if da_exp is True:
            fail_reasons.append("DESIGN_A_EXPOSURE_INVARIANT_VIOLATED")

    return arm_id, arm_entry


def _check_contradictory_producer_flags(
    obj: dict[str, Any],
    *,
    tag: str,
    field_name: str,
    evidence_tier: str | None,
    fail_reasons: list[str],
) -> bool:
    """Reject ANY record/payload carrying contradictory physical/release/modeled producer flags (Audit R4-01). Returns True if any flag contradicted."""
    had_contradiction = False
    if "physical_qualification_complete" in obj:
        pqc = _require_exact_bool(obj["physical_qualification_complete"], f"{field_name}.physical_qualification_complete")
        if pqc is False:
            fail_reasons.append(f"{tag}_PHYSICAL_QUALIFICATION_COMPLETE_FALSE_REJECTED")
            had_contradiction = True
    if "release_authorizing" in obj:
        ra = _require_exact_bool(obj["release_authorizing"], f"{field_name}.release_authorizing")
        if ra is False:
            fail_reasons.append(f"{tag}_RELEASE_AUTHORIZING_FALSE_REJECTED")
            had_contradiction = True
    if "modeled_qualification_only" in obj:
        mqo = _require_exact_bool(obj["modeled_qualification_only"], f"{field_name}.modeled_qualification_only")
        if mqo is True:
            fail_reasons.append(f"{tag}_MODELED_QUALIFICATION_ONLY_TRUE_REJECTED")
            had_contradiction = True
    if "qualification_scope" in obj and obj["qualification_scope"] is not None:
        qs = _require_nonempty_str(obj["qualification_scope"], f"{field_name}.qualification_scope")
        qsu = qs.upper()
        if any(tok in qsu for tok in ("MODELED", "PENDING_PHYSICAL", "SIMULATION", "UNQUALIFIED")):
            fail_reasons.append(f"{tag}_CONTRADICTORY_QUALIFICATION_SCOPE_REJECTED:{qs}")
            had_contradiction = True
        elif "SYNTHETIC" in qsu and evidence_tier != "SYNTHETIC_FIXTURE":
            fail_reasons.append(f"{tag}_SYNTHETIC_QUALIFICATION_SCOPE_ON_NON_SYNTHETIC_RECORD:{qs}")
            had_contradiction = True
    return had_contradiction


def _check_authority_tuple_coherence(
    parsed: dict[str, Any],
    *,
    tag: str,
    allowed_auth_decisions: frozenset[str],
    fail_reasons: list[str],
    allow_partial_hold_decisions: frozenset[str] = frozenset(),
) -> bool:
    """Enforce coherent (decision, authority_scope, bank_qualified, promotion_authorized) tuples (Audit R4-01 / Round-14 live GATE-32 partial-hold support). Returns True if incoherent or unauthorized."""
    rec_tier = parsed.get("evidence_tier")
    dec = parsed.get("decision")
    scope = parsed.get("authority_scope")
    bq = parsed.get("bank_qualified")
    pa = parsed.get("promotion_authorized")

    incoherent = False
    if pa is True and bq is not True:
        incoherent = True
    if pa is True and scope is not None and scope != "CLINICAL_LOT_RELEASE":
        incoherent = True
    if pa is True and dec is not None and dec not in allowed_auth_decisions:
        incoherent = True
    if scope == "CLINICAL_LOT_RELEASE":
        if rec_tier is not None and rec_tier != "AUTHENTICATED_ARCHIVED_WETLAB":
            incoherent = True
        if bq is False or pa is False or (dec is not None and dec not in allowed_auth_decisions):
            incoherent = True
    elif scope in (
        "BANK_QUALIFICATION_ONLY",
        "STAGE_LIMITED_SORT_ONLY",
        "COMPONENT_SORT_QUALIFICATION_ONLY",
        "WAVE7_RESERVE_ONLY",
    ):
        if pa is True:
            incoherent = True
        if scope == "BANK_QUALIFICATION_ONLY" and bq is False:
            incoherent = True
    elif scope == "REJECTED_OR_HELD":
        if bq is True or pa is True:
            incoherent = True
    elif scope == "SYNTHETIC_SELF_TEST":
        if rec_tier is not None and rec_tier != "SYNTHETIC_FIXTURE":
            incoherent = True
        if bq is True or pa is True or (dec is not None and dec != "SYNTHETIC_SELF_TEST_PASS"):
            incoherent = True
    if dec is not None and (
        dec.startswith("FAIL") or dec.startswith("HOLD") or dec.startswith("REJECT") or dec.startswith("STAGE_LIMITED")
    ):
        if pa is True or scope == "CLINICAL_LOT_RELEASE":
            incoherent = True

    if incoherent:
        fail_reasons.append(
            f"{tag}_INCOHERENT_AUTHORITY_TUPLE:tier={rec_tier},decision={dec},scope={scope},bank_qualified={bq},promotion_authorized={pa}"
        )

    is_coherent_partial_hold = (
        rec_tier == "AUTHENTICATED_ARCHIVED_WETLAB"
        and dec is not None
        and dec in allow_partial_hold_decisions
        and scope == "REJECTED_OR_HELD"
        and bq is False
        and pa is False
    )

    synthetic_invalid = False
    if rec_tier == "AUTHENTICATED_ARCHIVED_WETLAB":
        if not is_coherent_partial_hold:
            if dec is not None and dec not in allowed_auth_decisions:
                fail_reasons.append(f"{tag}_WETLAB_DECISION_NOT_AUTHORIZED:{dec}")
            if scope is not None and scope != "CLINICAL_LOT_RELEASE":
                fail_reasons.append(f"{tag}_AUTHORITY_SCOPE_NOT_CLINICAL_LOT_RELEASE:{scope}")
            if bq is not None and bq is not True:
                fail_reasons.append(f"{tag}_BANK_NOT_QUALIFIED")
            if pa is not None and pa is not True:
                fail_reasons.append(f"{tag}_PROMOTION_NOT_AUTHORIZED")
    elif rec_tier == "SYNTHETIC_FIXTURE":
        if dec is not None and dec != "SYNTHETIC_SELF_TEST_PASS":
            fail_reasons.append(f"{tag}_SYNTHETIC_DECISION_INVALID:{dec}")
            synthetic_invalid = True
        if scope is not None and scope != "SYNTHETIC_SELF_TEST":
            fail_reasons.append(f"{tag}_SYNTHETIC_AUTHORITY_SCOPE_INVALID:{scope}")
            synthetic_invalid = True
        if bq is not None and bq is not False:
            fail_reasons.append(f"{tag}_SYNTHETIC_CANNOT_QUALIFY_BANK")
            synthetic_invalid = True
        if pa is not None and pa is not False:
            fail_reasons.append(f"{tag}_SYNTHETIC_CANNOT_AUTHORIZE_PROMOTION")
            synthetic_invalid = True
    return incoherent or synthetic_invalid


def _parse_parent_identity_and_tier(
    obs: dict[str, Any],
    arm_entry: dict[str, Any] | None,
    fail_reasons: list[str],
    missing_fields: list[str],
) -> tuple[dict[str, str | None], bool]:
    """Require and verify parent observation identity, manifest digests, producer flags, and evidence_tier."""
    out: dict[str, str | None] = {
        "evidence_tier": None,
        "product_id": None,
        "lot_id": None,
        "bank_id": None,
        "bank_origin": None,
        "construct_manifest_sha256": None,
    }
    parent_env_ok = True
    for fld in ("evidence_tier", "product_id", "lot_id", "bank_id", "bank_origin", "construct_manifest_sha256"):
        if fld not in obs or obs[fld] is None:
            missing_fields.append(fld)
            parent_env_ok = False
        else:
            out[fld] = _require_nonempty_str(obs[fld], fld)

    ev_tier = out["evidence_tier"]
    if ev_tier is not None and ev_tier not in ALLOWED_EVIDENCE_TIERS:
        fail_reasons.append(f"INVALID_PARENT_EVIDENCE_TIER:{ev_tier}")
        parent_env_ok = False

    if _check_contradictory_producer_flags(
        obs, tag="PARENT_OBS", field_name="obs", evidence_tier=ev_tier, fail_reasons=fail_reasons
    ):
        parent_env_ok = False

    borig = out["bank_origin"]
    if borig is not None and borig not in ALLOWED_BANK_ORIGINS:
        fail_reasons.append(f"INVALID_PARENT_BANK_ORIGIN:{borig}")
        parent_env_ok = False

    csha = out["construct_manifest_sha256"]
    if csha is not None:
        if not _is_valid_nonzero_sha256(csha):
            fail_reasons.append("INVALID_OR_ZERO_PARENT_CONSTRUCT_MANIFEST_SHA256")
            parent_env_ok = False
        elif csha == EXPECTED_ARM_MANIFEST_SHA256:
            fail_reasons.append("PARENT_CONSTRUCT_MANIFEST_DIGEST_CONFLATED_WITH_ARM_MANIFEST")
            parent_env_ok = False

    if arm_entry is not None:
        if out["product_id"] is not None and out["product_id"] != arm_entry["product_id"]:
            fail_reasons.append(f"PARENT_PRODUCT_ID_MISMATCH:{out['product_id']}!={arm_entry['product_id']}")
            parent_env_ok = False
        if borig is not None and borig != arm_entry["cell_origin"]:
            fail_reasons.append(f"PARENT_BANK_ORIGIN_MISMATCH:{borig}!={arm_entry['cell_origin']}")
            parent_env_ok = False

    return out, parent_env_ok


def _validate_evidence_record_v2(
    rec_raw: Any,
    *,
    field_name: str,
    expected_gate_source: str,
    allowed_auth_decisions: frozenset[str],
    parent_id: dict[str, str | None],
    arm_entry: dict[str, Any] | None,
    fail_reasons: list[str],
    missing_fields: list[str],
    allow_partial_hold_decisions: frozenset[str] = frozenset(),
) -> tuple[dict[str, Any] | None, bool]:
    """Validate all 14 required fields, complete canonical body digest, producer flags, and authority tuple coherence of a v2_round5_unified record."""
    if rec_raw is None:
        missing_fields.append(field_name)
        return None, False
    if not isinstance(rec_raw, dict):
        raise ValueError(f"{field_name} must be dict")

    tag = field_name.upper()
    parsed: dict[str, Any] = {}
    all_present = True
    integrity_ok = True
    for fld in UPSTREAM_EVIDENCE_REQUIRED_FIELDS:
        if fld not in rec_raw or rec_raw[fld] is None:
            missing_fields.append(f"{field_name}.{fld}")
            all_present = False
            integrity_ok = False
        elif fld in UPSTREAM_EVIDENCE_BOOL_FIELDS:
            parsed[fld] = _require_exact_bool(rec_raw[fld], f"{field_name}.{fld}")
        else:
            parsed[fld] = _require_nonempty_str(rec_raw[fld], f"{field_name}.{fld}")

    if "gate_source" in parsed and parsed["gate_source"] != expected_gate_source:
        if (
            field_name == "upstream_lot_evidence_record"
            and parsed["gate_source"] == CANONICAL_LIVE_GATE32_DEBRIS_RECALL_SOURCE
        ):
            fail_reasons.append(
                f"{tag}_LIVE_GATE32_ROLE_COLLISION_REJECTED:GATE-32_IS_LIVE_DEC130_DEBRIS_RECALL_NOT_W6_C1_GATE34"
            )
        fail_reasons.append(f"{tag}_GATE_SOURCE_MISMATCH:{parsed['gate_source']}!={expected_gate_source}")
        integrity_ok = False

    rec_tier = parsed.get("evidence_tier")
    if rec_tier is not None:
        if rec_tier not in ALLOWED_EVIDENCE_TIERS:
            fail_reasons.append(f"{tag}_INVALID_EVIDENCE_TIER:{rec_tier}")
            integrity_ok = False
        elif parent_id["evidence_tier"] in ALLOWED_EVIDENCE_TIERS and rec_tier != parent_id["evidence_tier"]:
            fail_reasons.append(f"EVIDENCE_TIER_MISMATCH:{field_name}={rec_tier}!=parent={parent_id['evidence_tier']}")
            integrity_ok = False

    if _check_contradictory_producer_flags(
        rec_raw, tag=tag, field_name=field_name, evidence_tier=rec_tier, fail_reasons=fail_reasons
    ):
        integrity_ok = False

    if "bank_origin" in parsed and parsed["bank_origin"] not in ALLOWED_BANK_ORIGINS:
        fail_reasons.append(f"{tag}_INVALID_BANK_ORIGIN:{parsed['bank_origin']}")
        integrity_ok = False

    if "authority_scope" in parsed and parsed["authority_scope"] not in ALLOWED_AUTHORITY_SCOPES:
        fail_reasons.append(f"{tag}_INVALID_AUTHORITY_SCOPE:{parsed['authority_scope']}")
        integrity_ok = False

    if "canonical_arm_manifest_sha256" in parsed and parsed["canonical_arm_manifest_sha256"] != EXPECTED_ARM_MANIFEST_SHA256:
        fail_reasons.append(f"{tag}_CANONICAL_ARM_MANIFEST_SHA256_MISMATCH")
        integrity_ok = False

    if "construct_manifest_sha256" in parsed:
        rcsha = parsed["construct_manifest_sha256"]
        if not _is_valid_nonzero_sha256(rcsha):
            fail_reasons.append(f"{tag}_INVALID_OR_ZERO_CONSTRUCT_MANIFEST_SHA256")
            integrity_ok = False
        elif rcsha == EXPECTED_ARM_MANIFEST_SHA256:
            fail_reasons.append(f"{tag}_CONSTRUCT_MANIFEST_DIGEST_CONFLATED_WITH_ARM_MANIFEST")
            integrity_ok = False
        elif parent_id["construct_manifest_sha256"] is not None and rcsha != parent_id["construct_manifest_sha256"]:
            fail_reasons.append(f"{tag}_CONSTRUCT_MANIFEST_MISMATCH_WITH_PARENT")
            integrity_ok = False

    if "archive_sha256" in parsed:
        if not _is_valid_nonzero_sha256(parsed["archive_sha256"]):
            fail_reasons.append(f"{tag}_INVALID_OR_ZERO_ARCHIVE_SHA256")
            integrity_ok = False
        else:
            recomp_sha = compute_canonical_record_sha256(rec_raw)
            if recomp_sha != parsed["archive_sha256"]:
                fail_reasons.append(f"{tag}_ARCHIVE_BODY_DIGEST_MISMATCH")
                integrity_ok = False

    if arm_entry is not None:
        if "product_id" in parsed and parsed["product_id"] != arm_entry["product_id"]:
            fail_reasons.append(f"{tag}_CROSS_PRODUCT_MISMATCH:{parsed['product_id']}!={arm_entry['product_id']}")
            integrity_ok = False
        if "bank_origin" in parsed and parsed["bank_origin"] != arm_entry["cell_origin"]:
            fail_reasons.append(f"{tag}_BANK_ORIGIN_MISMATCH:{parsed['bank_origin']}!={arm_entry['cell_origin']}")
            integrity_ok = False

    if parent_id["product_id"] is not None and "product_id" in parsed and parsed["product_id"] != parent_id["product_id"]:
        fail_reasons.append(f"{tag}_PARENT_PRODUCT_MISMATCH:{parsed['product_id']}!={parent_id['product_id']}")
        integrity_ok = False
    if parent_id["lot_id"] is not None and "lot_id" in parsed and parsed["lot_id"] != parent_id["lot_id"]:
        fail_reasons.append(f"{tag}_CROSS_LOT_MISMATCH:{parsed['lot_id']}!={parent_id['lot_id']}")
        integrity_ok = False
    if parent_id["bank_id"] is not None and "bank_id" in parsed and parsed["bank_id"] != parent_id["bank_id"]:
        fail_reasons.append(f"{tag}_CROSS_BANK_MISMATCH:{parsed['bank_id']}!={parent_id['bank_id']}")
        integrity_ok = False
    if parent_id["bank_origin"] is not None and "bank_origin" in parsed and parsed["bank_origin"] != parent_id["bank_origin"]:
        fail_reasons.append(f"{tag}_PARENT_BANK_ORIGIN_MISMATCH:{parsed['bank_origin']}!={parent_id['bank_origin']}")
        integrity_ok = False

    if _check_authority_tuple_coherence(
        parsed,
        tag=tag,
        allowed_auth_decisions=allowed_auth_decisions,
        fail_reasons=fail_reasons,
        allow_partial_hold_decisions=allow_partial_hold_decisions,
    ):
        integrity_ok = False

    return (parsed if all_present else None), (integrity_ok and all_present)


def _lookup_and_verify_store_record(
    trusted_evidence_store: Any,
    *,
    field_name: str,
    rec_raw: dict[str, Any],
    parsed: dict[str, Any],
    expected_gate_source: str,
    allowed_auth_decisions: frozenset[str],
    allow_partial_hold_decisions: frozenset[str] = frozenset(),
) -> tuple[str | None, list[str], bool, list[str]]:
    """Resolve record by record_id and/or archive_sha256 in trusted_evidence_store with alias-consistency & full-body SHA-256 verification (Review #5 / Audit R4-01 / Audit R10-03 / Round-14 live GATE-32).

    Returns (status, all_errs, store_integrity_ok, integrity_errs).
    `store_integrity_ok` is True iff the stored archive entry resolves cleanly without index alias conflict,
    corrupt non-dict payload, body/digest mismatch, field mismatch, or contradictory producer flags.
    """
    if not isinstance(trusted_evidence_store, dict):
        return "HOLD_UNRESOLVED", [f"UNRESOLVED_IN_TRUSTED_EVIDENCE_STORE:{field_name}"], False, []

    rid = parsed["record_id"]
    asha = parsed["archive_sha256"]
    has_rid = rid in trusted_evidence_store
    has_sha = asha in trusted_evidence_store
    if not has_rid and not has_sha:
        return "HOLD_UNRESOLVED", [f"UNRESOLVED_IN_TRUSTED_EVIDENCE_STORE:{field_name}"], False, []

    integrity_errs: list[str] = []
    release_errs: list[str] = []
    if has_rid and has_sha:
        stored_by_id = trusted_evidence_store[rid]
        stored_by_sha = trusted_evidence_store[asha]
        if not isinstance(stored_by_id, dict) or not isinstance(stored_by_sha, dict):
            corrupt_errs = [
                f"CONFLICTING_TRUSTED_STORE_INDEX_ALIASES:{field_name}",
                f"TRUSTED_EVIDENCE_STORE_ENTRY_NOT_DICT:{field_name}",
            ]
            return "FAIL_CORRUPT", corrupt_errs, False, corrupt_errs
        check_strictly_finite(stored_by_id, f"store[{field_name}:rid]")
        check_strictly_finite(stored_by_sha, f"store[{field_name}:sha]")
        j_id = json.dumps(stored_by_id, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False)
        j_sha = json.dumps(stored_by_sha, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False)
        if stored_by_id != stored_by_sha or j_id != j_sha:
            alias_errs = [f"CONFLICTING_TRUSTED_STORE_INDEX_ALIASES:{field_name}"]
            return "FAIL_MISMATCH", alias_errs, False, alias_errs
        stored = stored_by_id
    else:
        stored = trusted_evidence_store[rid] if has_rid else trusted_evidence_store[asha]

    if not isinstance(stored, dict):
        nd_errs = [f"TRUSTED_EVIDENCE_STORE_ENTRY_NOT_DICT:{field_name}"]
        return "FAIL_CORRUPT", nd_errs, False, nd_errs
    check_strictly_finite(stored, f"store[{field_name}]")

    stored_sha = stored.get("archive_sha256")
    if not _is_valid_nonzero_sha256(stored_sha):
        integrity_errs.append(f"TRUSTED_EVIDENCE_STORE_INVALID_ARCHIVE_SHA256:{field_name}")
    else:
        recomp_stored = compute_canonical_record_sha256(stored)
        if recomp_stored != stored_sha:
            integrity_errs.append(f"TRUSTED_EVIDENCE_STORE_BODY_DIGEST_MISMATCH:{field_name}")
        if recomp_stored != asha:
            integrity_errs.append(f"TRUSTED_EVIDENCE_STORE_ARCHIVE_SHA256_MISMATCH:{field_name}")

    for fld in UPSTREAM_EVIDENCE_REQUIRED_FIELDS:
        sval = stored.get(fld)
        pval = parsed[fld]
        if type(sval) is not type(pval) or sval != pval:
            integrity_errs.append(f"TRUSTED_EVIDENCE_STORE_MISMATCH:{field_name}.{fld}")

    stored_canon = json.dumps(stored, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False)
    rec_canon = json.dumps(rec_raw, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False)
    if stored_canon != rec_canon:
        integrity_errs.append(f"TRUSTED_EVIDENCE_STORE_FULL_BODY_MISMATCH:{field_name}")

    _check_contradictory_producer_flags(
        stored,
        tag=f"TRUSTED_EVIDENCE_STORE_{field_name.upper()}",
        field_name=f"store[{field_name}]",
        evidence_tier=stored.get("evidence_tier") if isinstance(stored.get("evidence_tier"), str) else None,
        fail_reasons=integrity_errs,
    )

    if stored.get("evidence_tier") != "AUTHENTICATED_ARCHIVED_WETLAB":
        integrity_errs.append(f"TRUSTED_EVIDENCE_STORE_TIER_NOT_AUTHENTICATED_WETLAB:{field_name}")
    if stored.get("gate_source") != expected_gate_source:
        if (
            field_name == "upstream_lot_evidence_record"
            and stored.get("gate_source") == CANONICAL_LIVE_GATE32_DEBRIS_RECALL_SOURCE
        ):
            integrity_errs.append(f"TRUSTED_EVIDENCE_STORE_LIVE_GATE32_ROLE_COLLISION_REJECTED:{field_name}")
        integrity_errs.append(f"TRUSTED_EVIDENCE_STORE_GATE_SOURCE_MISMATCH:{field_name}")
    if stored.get("canonical_arm_manifest_sha256") != EXPECTED_ARM_MANIFEST_SHA256:
        integrity_errs.append(f"TRUSTED_EVIDENCE_STORE_ARM_MANIFEST_MISMATCH:{field_name}")
    if "archived_payload_bytes_sha256" in stored and stored["archived_payload_bytes_sha256"] != asha:
        integrity_errs.append(f"TRUSTED_EVIDENCE_STORE_PAYLOAD_DIGEST_MISMATCH:{field_name}")

    is_stored_partial_hold = (
        stored.get("decision") in allow_partial_hold_decisions
        and stored.get("authority_scope") == "REJECTED_OR_HELD"
        and stored.get("bank_qualified") is False
        and stored.get("promotion_authorized") is False
    )
    if not is_stored_partial_hold:
        if stored.get("decision") not in allowed_auth_decisions:
            release_errs.append(f"TRUSTED_EVIDENCE_STORE_DECISION_NOT_AUTHORIZED:{field_name}")
        if stored.get("authority_scope") != "CLINICAL_LOT_RELEASE":
            release_errs.append(f"TRUSTED_EVIDENCE_STORE_AUTHORITY_SCOPE_NOT_CLINICAL_LOT_RELEASE:{field_name}")
        if stored.get("bank_qualified") is not True:
            release_errs.append(f"TRUSTED_EVIDENCE_STORE_BANK_NOT_QUALIFIED:{field_name}")
        if stored.get("promotion_authorized") is not True:
            release_errs.append(f"TRUSTED_EVIDENCE_STORE_PROMOTION_NOT_AUTHORIZED:{field_name}")

    all_errs = integrity_errs + release_errs
    store_integrity_ok = len(integrity_errs) == 0
    if all_errs:
        return "FAIL_MISMATCH", all_errs, store_integrity_ok, integrity_errs
    if is_stored_partial_hold:
        return "HOLD_PARTIAL_COVERAGE", [], True, []
    return None, [], True, []


def _evaluate_live_gate32_debris_recall_fields(
    g32_raw: dict[str, Any],
    *,
    parsed_g32: dict[str, Any] | None,
    fail_reasons: list[str],
    missing_fields: list[str],
    hold_reasons: list[str],
) -> None:
    """Enforce live GATE-32 (DEC-130 / GY-010) whole-islet-debris recall thresholds directly on the archived record."""
    pfx = "live_gate32_debris_recall_record."
    rec_tier = parsed_g32.get("evidence_tier") if parsed_g32 is not None else None
    rec_dec = parsed_g32.get("decision") if parsed_g32 is not None else None

    if "debris_recall_verdict" not in g32_raw or g32_raw["debris_recall_verdict"] is None:
        missing_fields.append(f"{pfx}debris_recall_verdict")
        verdict_val: str | None = None
    else:
        verdict_val = _require_nonempty_str(g32_raw["debris_recall_verdict"], f"{pfx}debris_recall_verdict")

    is_coherent_partial_hold = False
    if verdict_val is not None:
        if rec_tier == "AUTHENTICATED_ARCHIVED_WETLAB":
            if rec_dec in ALLOWED_LIVE_GATE32_DEBRIS_PARTIAL_HOLD_DECISIONS:
                if verdict_val != rec_dec:
                    fail_reasons.append(f"LIVE_GATE32_VERDICT_DECISION_MISMATCH:{verdict_val}!={rec_dec}")
                elif (
                    parsed_g32 is not None
                    and parsed_g32.get("authority_scope") == "REJECTED_OR_HELD"
                    and parsed_g32.get("bank_qualified") is False
                    and parsed_g32.get("promotion_authorized") is False
                ):
                    is_coherent_partial_hold = True
                    hold_reasons.append("HOLD_LIVE_GATE32_PARTIAL_EPITOPE_COVERAGE_GRADED_CAP")
            elif verdict_val in ALLOWED_LIVE_GATE32_DEBRIS_PARTIAL_HOLD_DECISIONS:
                if rec_dec in ALLOWED_LIVE_GATE32_DEBRIS_FULL_CREDIT_DECISIONS:
                    fail_reasons.append(f"LIVE_GATE32_VERDICT_DECISION_MISMATCH:{verdict_val}!={rec_dec}")
                else:
                    hold_reasons.append("HOLD_LIVE_GATE32_PARTIAL_EPITOPE_COVERAGE_GRADED_CAP")
            elif verdict_val != "PASS_DEBRIS_RECALL_FULL_CREDIT":
                fail_reasons.append(f"LIVE_GATE32_DEBRIS_RECALL_VERDICT_FAIL:{verdict_val}")
        else:
            if verdict_val in ALLOWED_LIVE_GATE32_DEBRIS_PARTIAL_HOLD_DECISIONS:
                is_coherent_partial_hold = True
                hold_reasons.append("HOLD_LIVE_GATE32_PARTIAL_EPITOPE_COVERAGE_GRADED_CAP")
            elif verdict_val != "PASS_DEBRIS_RECALL_FULL_CREDIT":
                fail_reasons.append(f"LIVE_GATE32_DEBRIS_RECALL_VERDICT_FAIL:{verdict_val}")

    if "debris_recall_l95_suppressed_frac" not in g32_raw or g32_raw["debris_recall_l95_suppressed_frac"] is None:
        missing_fields.append(f"{pfx}debris_recall_l95_suppressed_frac")
        l95_val: float | None = None
    else:
        l95_val = _require_bounded_float(
            g32_raw["debris_recall_l95_suppressed_frac"], f"{pfx}debris_recall_l95_suppressed_frac", lo=0.0, hi=1.0
        )
    if l95_val is not None and l95_val < LIVE_GATE32_MIN_L95_SUPPRESSED_FRAC:
        if is_coherent_partial_hold:
            hold_reasons.append(f"HOLD_LIVE_GATE32_DEBRIS_RECALL_L95_BELOW_0P70:{l95_val!r}")
        else:
            fail_reasons.append(f"LIVE_GATE32_DEBRIS_RECALL_L95_BELOW_0P70_FAIL:{l95_val!r}")

    if "residual_class2_recall_u95_frac" not in g32_raw or g32_raw["residual_class2_recall_u95_frac"] is None:
        missing_fields.append(f"{pfx}residual_class2_recall_u95_frac")
        res_val: float | None = None
    else:
        res_val = _require_bounded_float(
            g32_raw["residual_class2_recall_u95_frac"], f"{pfx}residual_class2_recall_u95_frac", lo=0.0, hi=1.0
        )
    if res_val is not None and res_val > LIVE_GATE32_MAX_RESIDUAL_CLASS2_U95_FRAC:
        if is_coherent_partial_hold:
            hold_reasons.append(f"HOLD_LIVE_GATE32_RESIDUAL_CLASS2_RECALL_U95_GT_0P30:{res_val!r}")
        else:
            fail_reasons.append(f"LIVE_GATE32_RESIDUAL_CLASS2_RECALL_U95_GT_0P30_FAIL:{res_val!r}")

    if "unrelated_recall_preserved" not in g32_raw or g32_raw["unrelated_recall_preserved"] is None:
        missing_fields.append(f"{pfx}unrelated_recall_preserved")
        unrel_val: bool | None = None
    else:
        unrel_val = _require_exact_bool(g32_raw["unrelated_recall_preserved"], f"{pfx}unrelated_recall_preserved")
    if unrel_val is False:
        fail_reasons.append("LIVE_GATE32_UNRELATED_RECALL_NOT_PRESERVED_FAIL")


def _verify_upstream_evidence_and_finalize(
    obs: dict[str, Any],
    expected_module_gate_source: str,
    module_binding_checker: Callable[[dict[str, Any], list[str], list[str], list[str]], None] | None,
    arm_entry: dict[str, Any] | None,
    trusted_evidence_store: dict[str, dict[str, Any]] | None,
    fail_reasons: list[str],
    missing_fields: list[str],
    hold_reasons: list[str],
    extra_out: dict[str, Any] | None = None,
    *,
    verified_manifest: dict[str, Any] | None = None,
    extra_builder: Callable[[dict[str, Any]], dict[str, Any]] | None = None,
    require_live_gate32_debris_recall: bool = False,
) -> dict[str, Any]:
    """Enforce v2_round5_unified evidence schema across parent, W6-C1 GATE-34 upstream, independent GATE-36-<MODULE> current-assay, & (for SHIELD) mandatory live GATE-32 whole-islet-debris recall records with unconditional store authentication before statistics emission (Audit R10-03 / Round-14 Review)."""
    parent_id, parent_env_ok = _parse_parent_identity_and_tier(obs, arm_entry, fail_reasons, missing_fields)

    allowed_cur_decisions = frozenset({
        "PASS",
        f"PASS_{expected_module_gate_source.replace('-', '_')}",
        f"PASS_{expected_module_gate_source.replace('-', '')}",
    })

    up_raw = obs.get("upstream_lot_evidence_record") if "upstream_lot_evidence_record" in obs else None
    cur_raw = obs.get("current_assay_evidence_record") if "current_assay_evidence_record" in obs else None

    parsed_up, up_env_ok = _validate_evidence_record_v2(
        up_raw,
        field_name="upstream_lot_evidence_record",
        expected_gate_source=CANONICAL_UPSTREAM_GATE34_SOURCE,
        allowed_auth_decisions=ALLOWED_GATE34_UPSTREAM_AUTH_DECISIONS,
        parent_id=parent_id,
        arm_entry=arm_entry,
        fail_reasons=fail_reasons,
        missing_fields=missing_fields,
    )
    parsed_cur, cur_env_ok = _validate_evidence_record_v2(
        cur_raw,
        field_name="current_assay_evidence_record",
        expected_gate_source=expected_module_gate_source,
        allowed_auth_decisions=allowed_cur_decisions,
        parent_id=parent_id,
        arm_entry=arm_entry,
        fail_reasons=fail_reasons,
        missing_fields=missing_fields,
    )

    g32_raw: Any = None
    parsed_g32: dict[str, Any] | None = None
    g32_env_ok = True
    if require_live_gate32_debris_recall:
        g32_raw = obs.get("live_gate32_debris_recall_record") if "live_gate32_debris_recall_record" in obs else None
        if g32_raw is None:
            missing_fields.append("live_gate32_debris_recall_record")
            hold_reasons.append("HOLD_MISSING_LIVE_GATE32_WHOLE_DEBRIS_RECALL")
            g32_env_ok = False
        else:
            parsed_g32, g32_env_ok = _validate_evidence_record_v2(
                g32_raw,
                field_name="live_gate32_debris_recall_record",
                expected_gate_source=CANONICAL_LIVE_GATE32_DEBRIS_RECALL_SOURCE,
                allowed_auth_decisions=ALLOWED_LIVE_GATE32_DEBRIS_FULL_CREDIT_DECISIONS,
                parent_id=parent_id,
                arm_entry=arm_entry,
                fail_reasons=fail_reasons,
                missing_fields=missing_fields,
                allow_partial_hold_decisions=ALLOWED_LIVE_GATE32_DEBRIS_PARTIAL_HOLD_DECISIONS,
            )
            if isinstance(g32_raw, dict):
                _evaluate_live_gate32_debris_recall_fields(
                    g32_raw,
                    parsed_g32=parsed_g32,
                    fail_reasons=fail_reasons,
                    missing_fields=missing_fields,
                    hold_reasons=hold_reasons,
                )

    if isinstance(cur_raw, dict) and module_binding_checker is not None:
        module_binding_checker(cur_raw, fail_reasons, missing_fields, hold_reasons)

    records_unconflated = True
    if parsed_up is not None and parsed_cur is not None:
        if parsed_up["record_id"] == parsed_cur["record_id"]:
            fail_reasons.append("UPSTREAM_AND_CURRENT_ASSAY_RECORD_ID_CONFLATED")
            records_unconflated = False
        if parsed_up["archive_sha256"] == parsed_cur["archive_sha256"]:
            fail_reasons.append("UPSTREAM_AND_CURRENT_ASSAY_ARCHIVE_DIGEST_CONFLATED")
            records_unconflated = False
        if parsed_up["evidence_tier"] != parsed_cur["evidence_tier"]:
            fail_reasons.append(
                f"EVIDENCE_TIER_MISMATCH:upstream={parsed_up['evidence_tier']}!=current_assay={parsed_cur['evidence_tier']}"
            )
            records_unconflated = False
    if require_live_gate32_debris_recall and parsed_g32 is not None:
        for other_name, other_rec in (("upstream", parsed_up), ("current_assay", parsed_cur)):
            if other_rec is not None:
                if parsed_g32["record_id"] == other_rec["record_id"]:
                    fail_reasons.append(f"LIVE_GATE32_AND_{other_name.upper()}_RECORD_ID_CONFLATED")
                    records_unconflated = False
                if parsed_g32["archive_sha256"] == other_rec["archive_sha256"]:
                    fail_reasons.append(f"LIVE_GATE32_AND_{other_name.upper()}_ARCHIVE_DIGEST_CONFLATED")
                    records_unconflated = False
                if parsed_g32["evidence_tier"] != other_rec["evidence_tier"]:
                    fail_reasons.append(
                        f"EVIDENCE_TIER_MISMATCH:live_gate32={parsed_g32['evidence_tier']}!={other_name}={other_rec['evidence_tier']}"
                    )
                    records_unconflated = False

    ev_tier = parent_id["evidence_tier"]
    all_tiers = {
        parent_id["evidence_tier"],
        parsed_up["evidence_tier"] if parsed_up is not None else None,
        parsed_cur["evidence_tier"] if parsed_cur is not None else None,
    }
    if require_live_gate32_debris_recall:
        all_tiers.add(parsed_g32["evidence_tier"] if parsed_g32 is not None else None)

    has_required_parsed = (
        parsed_up is not None
        and parsed_cur is not None
        and (not require_live_gate32_debris_recall or parsed_g32 is not None)
    )
    is_pure_synthetic = (
        ev_tier == "SYNTHETIC_FIXTURE"
        and has_required_parsed
        and all_tiers == {"SYNTHETIC_FIXTURE"}
    )
    is_pure_wetlab = (
        ev_tier == "AUTHENTICATED_ARCHIVED_WETLAB"
        and has_required_parsed
        and all_tiers == {"AUTHENTICATED_ARCHIVED_WETLAB"}
    )

    # Always resolve trusted_evidence_store BEFORE building official statistics so unauthenticated,
    # missing-store, or tampered-store records NEVER leak verified numbers on FAIL or HOLD (Audit R10-03)!
    up_status: str | None = None
    up_errs: list[str] = []
    up_store_integrity_ok = False
    up_store_integrity_errs: list[str] = []

    cur_status: str | None = None
    cur_errs: list[str] = []
    cur_store_integrity_ok = False
    cur_store_integrity_errs: list[str] = []

    g32_status: str | None = None
    g32_errs: list[str] = []
    g32_store_integrity_ok = not require_live_gate32_debris_recall
    g32_store_integrity_errs: list[str] = []

    if is_pure_wetlab and isinstance(up_raw, dict) and isinstance(cur_raw, dict):
        up_status, up_errs, up_store_integrity_ok, up_store_integrity_errs = _lookup_and_verify_store_record(
            trusted_evidence_store,
            field_name="upstream_lot_evidence_record",
            rec_raw=up_raw,
            parsed=parsed_up,
            expected_gate_source=CANONICAL_UPSTREAM_GATE34_SOURCE,
            allowed_auth_decisions=ALLOWED_GATE34_UPSTREAM_AUTH_DECISIONS,
        )
        cur_status, cur_errs, cur_store_integrity_ok, cur_store_integrity_errs = _lookup_and_verify_store_record(
            trusted_evidence_store,
            field_name="current_assay_evidence_record",
            rec_raw=cur_raw,
            parsed=parsed_cur,
            expected_gate_source=expected_module_gate_source,
            allowed_auth_decisions=allowed_cur_decisions,
        )
        if require_live_gate32_debris_recall and isinstance(g32_raw, dict) and parsed_g32 is not None:
            g32_status, g32_errs, g32_store_integrity_ok, g32_store_integrity_errs = _lookup_and_verify_store_record(
                trusted_evidence_store,
                field_name="live_gate32_debris_recall_record",
                rec_raw=g32_raw,
                parsed=parsed_g32,
                expected_gate_source=CANONICAL_LIVE_GATE32_DEBRIS_RECALL_SOURCE,
                allowed_auth_decisions=ALLOWED_LIVE_GATE32_DEBRIS_FULL_CREDIT_DECISIONS,
                allow_partial_hold_decisions=ALLOWED_LIVE_GATE32_DEBRIS_PARTIAL_HOLD_DECISIONS,
            )

    fail_store_errs: list[str] = []
    hold_store_errs: list[str] = []
    for st, errs in ((up_status, up_errs), (cur_status, cur_errs), (g32_status, g32_errs)):
        if st in ("FAIL_CORRUPT", "FAIL_MISMATCH"):
            fail_store_errs.extend(errs)
        elif st == "HOLD_UNRESOLVED":
            hold_store_errs.extend(errs)
    store_tamper_errs = up_store_integrity_errs + cur_store_integrity_errs + g32_store_integrity_errs

    manifest_ok = (
        verified_manifest is not None
        and arm_entry is not None
        and obs.get("manifest_sha256") == EXPECTED_ARM_MANIFEST_SHA256
        and (
            "canonical_arm_manifest_sha256" not in obs
            or obs["canonical_arm_manifest_sha256"] in (None, EXPECTED_ARM_MANIFEST_SHA256)
        )
    )
    envelope_chain_ok = (
        manifest_ok
        and parent_env_ok
        and has_required_parsed
        and up_env_ok
        and cur_env_ok
        and g32_env_ok
        and records_unconflated
    )
    if fail_reasons:
        final_verdict = "FAIL"
    elif store_tamper_errs and (missing_fields or hold_reasons):
        final_verdict = "FAIL"
    elif missing_fields or hold_reasons:
        final_verdict = "HOLD"
    elif "SYNTHETIC_FIXTURE" in all_tiers:
        final_verdict = "SYNTHETIC_SELF_TEST_PASS"
    elif fail_store_errs:
        final_verdict = "FAIL"
    elif hold_store_errs:
        final_verdict = "HOLD"
    else:
        final_verdict = "PASS"

    auth_ctx: dict[str, Any] = {
        "evidence_tier": ev_tier,
        "is_synthetic": is_pure_synthetic,
        "final_verdict": final_verdict,
        "archive_authenticated": bool(
            envelope_chain_ok
            and is_pure_wetlab
            and up_store_integrity_ok
            and cur_store_integrity_ok
            and g32_store_integrity_ok
        ),
        "synthetic_archive_sealed": bool(envelope_chain_ok and is_pure_synthetic),
        "up_store_status": up_status,
        "cur_store_status": cur_status,
        "g32_store_status": g32_status,
        "up_store_integrity_ok": up_store_integrity_ok,
        "cur_store_integrity_ok": cur_store_integrity_ok,
        "g32_store_integrity_ok": g32_store_integrity_ok,
    }
    extra = extra_builder(auth_ctx) if extra_builder is not None else (extra_out or {})

    def _finish(result: dict[str, Any]) -> dict[str, Any]:
        check_strictly_finite(result, f"gate36_{expected_module_gate_source}_result")
        # Defense-in-depth invariant (Audit R12-07): FAIL/FAIL_* NEVER pairs with *_HOLD_* derivation source,
        # HOLD/HOLD_* NEVER pairs with *_WITH_INDEPENDENT_FAIL, and every emitted source MUST be declared.
        verdict_val = str(result.get("verdict", ""))
        decision_val = str(result.get("decision", ""))
        for src_key, allowed_sources in (
            ("shield_statistics_derivation_source", SHIELD_STATISTICS_DERIVATION_SOURCES),
            ("ins_statistics_derivation_source", INS_STATISTICS_DERIVATION_SOURCES),
        ):
            if src_key in result:
                src_val = result[src_key]
                require_cond(
                    isinstance(src_val, str) and src_val in allowed_sources,
                    f"Internal invariant violation: undeclared {src_key}={src_val!r}",
                )
                if verdict_val.startswith("FAIL") or decision_val.startswith("FAIL"):
                    require_cond(
                        "_HOLD_" not in src_val and not src_val.startswith("UNVERIFIED_HOLD"),
                        f"Internal invariant violation: FAIL verdict/decision ({verdict_val}/{decision_val}) "
                        f"paired with HOLD source label {src_key}={src_val!r}",
                    )
                if verdict_val.startswith("HOLD") or decision_val.startswith("HOLD"):
                    require_cond(
                        not src_val.endswith("_WITH_INDEPENDENT_FAIL"),
                        f"Internal invariant violation: HOLD verdict/decision ({verdict_val}/{decision_val}) "
                        f"paired with FAIL source label {src_key}={src_val!r}",
                    )
                if verdict_val in ("PASS", "SYNTHETIC_SELF_TEST_PASS"):
                    require_cond(
                        "_HOLD_" not in src_val and not src_val.startswith("WITHHELD_"),
                        f"Internal invariant violation: {verdict_val} paired with non-verified "
                        f"source label {src_key}={src_val!r}",
                    )
        return result

    any_corrupt = up_status == "FAIL_CORRUPT" or cur_status == "FAIL_CORRUPT" or g32_status == "FAIL_CORRUPT"

    if fail_reasons:
        combined_fails = list(fail_reasons)
        for err in store_tamper_errs:
            if err not in combined_fails:
                combined_fails.append(err)
        return _finish({
            "verdict": "FAIL",
            "decision": "FAIL",
            "promotion_authorized": False,
            "evidence_tier": ev_tier,
            "reasons": combined_fails,
            "missing_fields": missing_fields,
            **extra,
        })
    if store_tamper_errs and (missing_fields or hold_reasons):
        dec = "FAIL_EVIDENCE_STORE_CORRUPT" if any_corrupt else "FAIL_EVIDENCE_STORE_MISMATCH"
        return _finish({
            "verdict": "FAIL",
            "decision": dec,
            "promotion_authorized": False,
            "evidence_tier": ev_tier,
            "reasons": store_tamper_errs + [f"MISSING_MANDATORY_FIELD:{f}" for f in missing_fields] + hold_reasons,
            "missing_fields": missing_fields,
            **extra,
        })
    if missing_fields or hold_reasons:
        reasons = [f"MISSING_MANDATORY_FIELD:{f}" for f in missing_fields] + hold_reasons + hold_store_errs
        return _finish({
            "verdict": "HOLD",
            "decision": "HOLD",
            "promotion_authorized": False,
            "evidence_tier": ev_tier,
            "reasons": reasons,
            "missing_fields": missing_fields,
            **extra,
        })

    # Strict Synthetic Isolation: if ANY required record is SYNTHETIC_FIXTURE -> promotion_authorized=False!
    if "SYNTHETIC_FIXTURE" in all_tiers:
        return _finish({
            "verdict": "SYNTHETIC_SELF_TEST_PASS",
            "decision": "SYNTHETIC_SELF_TEST_PASS",
            "promotion_authorized": False,
            "evidence_tier": "SYNTHETIC_FIXTURE",
            "reasons": [],
            "missing_fields": [],
            **extra,
        })

    # AUTHENTICATED_ARCHIVED_WETLAB: ALL required records (GATE-34 upstream, GATE-36-<MODULE> current assay,
    # and live GATE-32 whole-islet-debris recall for SHIELD) MUST resolve and hash-verify in trusted_evidence_store!
    require_cond(
        isinstance(up_raw, dict)
        and parsed_up is not None
        and isinstance(cur_raw, dict)
        and parsed_cur is not None
        and (not require_live_gate32_debris_recall or (isinstance(g32_raw, dict) and parsed_g32 is not None)),
        "Internal invariant violation: missing parsed evidence records at store resolution",
    )

    if fail_store_errs:
        dec = "FAIL_EVIDENCE_STORE_CORRUPT" if any_corrupt else "FAIL_EVIDENCE_STORE_MISMATCH"
        return _finish({
            "verdict": "FAIL",
            "decision": dec,
            "promotion_authorized": False,
            "evidence_tier": "AUTHENTICATED_ARCHIVED_WETLAB",
            "reasons": fail_store_errs,
            "missing_fields": [],
            **extra,
        })
    if hold_store_errs:
        return _finish({
            "verdict": "HOLD",
            "decision": "HOLD_UNRESOLVED_TRUSTED_EVIDENCE_STORE",
            "promotion_authorized": False,
            "evidence_tier": "AUTHENTICATED_ARCHIVED_WETLAB",
            "reasons": hold_store_errs,
            "missing_fields": [],
            **extra,
        })

    return _finish({
        "verdict": "PASS",
        "decision": "PASS",
        "promotion_authorized": True,
        "evidence_tier": "AUTHENTICATED_ARCHIVED_WETLAB",
        "reasons": [],
        "missing_fields": [],
        **extra,
    })


def _evaluate_shield_measurements(
    src: dict[str, Any],
    *,
    is_archive: bool,
    fail_reasons: list[str],
    missing_fields: list[str],
    hold_reasons: list[str],
) -> dict[str, Any]:
    """Validate and enforce ALL governing SHIELD-SEL measurements, completeness, & internal consistency directly on `src` (ZERO threshold tolerance)."""
    pfx = "current_assay_evidence_record." if is_archive else ""
    rtag = "ARCHIVE_" if is_archive else ""
    reg_key = "dosing_regimen" if is_archive else "regimen_id"
    hpk_key = "human_pk_qualified" if is_archive else "measured_human_pk_verified"
    local_missing_fields: list[str] = []

    def _opt(key: str) -> tuple[bool, Any]:
        if key not in src or src[key] is None:
            fname = f"{pfx}{key}"
            missing_fields.append(fname)
            local_missing_fields.append(fname)
            return False, None
        return True, src[key]

    internal_conflict = False
    if "kd_off_u95_nm" in src:
        fail_reasons.append(f"{rtag}DEPRECATED_WRONG_DIRECTION_FIELD_KD_OFF_U95_NM_REJECTED")
        internal_conflict = True

    has_study, study_raw = _opt("study_id")
    study_id: str | None = None
    if has_study:
        study_id = _require_canonical_ascii_id(study_raw, f"{pfx}study_id", rtag=rtag, fail_reasons=fail_reasons)
        if not _is_strict_canonical_ascii_id(study_raw):
            internal_conflict = True

    has_fmt, fmt_raw = _opt("format_id")
    fmt_id: str | None = None
    if has_fmt:
        fmt_id = _require_canonical_ascii_id(fmt_raw, f"{pfx}format_id", rtag=rtag, fail_reasons=fail_reasons)
        if not _is_strict_canonical_ascii_id(fmt_raw):
            internal_conflict = True
        if fmt_id != "FULLY_HUMAN_FAB_KIH_COMMON_LC_HIGG1_LALAPG_LS":
            fail_reasons.append(f"{rtag}FORBIDDEN_OR_NON_LEAD_FORMAT:{fmt_id}")

    has_reg, reg_raw = _opt(reg_key)
    regimen_id: str | None = None
    if has_reg:
        regimen_id = _require_canonical_ascii_id(reg_raw, f"{pfx}{reg_key}", rtag=rtag, fail_reasons=fail_reasons)
        if not _is_strict_canonical_ascii_id(reg_raw):
            internal_conflict = True
        if regimen_id not in ("Q28D", "Q84D"):
            fail_reasons.append(f"{rtag}UNSUPPORTED_REGIMEN_ID:{regimen_id}")
            internal_conflict = True
    if is_archive and "regimen_id" in src and src["regimen_id"] is not None:
        reg_alias_raw = src["regimen_id"]
        reg_alias = _require_canonical_ascii_id(reg_alias_raw, f"{pfx}regimen_id", rtag=rtag, fail_reasons=fail_reasons)
        if not _is_strict_canonical_ascii_id(reg_alias_raw):
            internal_conflict = True
        if regimen_id is not None and reg_alias != regimen_id:
            fail_reasons.append(f"ARCHIVE_REGIMEN_ALIAS_MISMATCH:{reg_alias}!={regimen_id}")
            internal_conflict = True
        elif regimen_id is None:
            regimen_id = reg_alias
            if regimen_id not in ("Q28D", "Q84D"):
                fail_reasons.append(f"{rtag}UNSUPPORTED_REGIMEN_ID:{regimen_id}")
                internal_conflict = True

    has_tday, tday_raw = _opt("timed_pk_day")
    timed_pk_day = _require_exact_int(tday_raw, f"{pfx}timed_pk_day", lo=1, hi=365) if has_tday else None
    if regimen_id == "Q28D" and timed_pk_day is not None and timed_pk_day != 28:
        fail_reasons.append(f"{rtag}Q28D_TIMED_PK_DAY_MISMATCH:{timed_pk_day}!=28")
        internal_conflict = True
    elif regimen_id == "Q84D" and timed_pk_day is not None and timed_pk_day != 84:
        fail_reasons.append(f"{rtag}Q84D_TIMED_PK_DAY_MISMATCH:{timed_pk_day}!=84")
        internal_conflict = True

    has_hpk, hpk_raw = _opt(hpk_key)
    human_pk_verified = _require_exact_bool(hpk_raw, f"{pfx}{hpk_key}") if has_hpk else None
    if is_archive and "measured_human_pk_verified" in src and src["measured_human_pk_verified"] is not None:
        hpk_alias = _require_exact_bool(src["measured_human_pk_verified"], f"{pfx}measured_human_pk_verified")
        if human_pk_verified is not None and hpk_alias is not human_pk_verified:
            fail_reasons.append(f"ARCHIVE_HUMAN_PK_ALIAS_MISMATCH:{hpk_alias}!={human_pk_verified}")
            internal_conflict = True
        elif human_pk_verified is None and regimen_id == "Q84D" and hpk_alias is False:
            fail_reasons.append(f"{rtag}Q84D_REQUIRES_MEASURED_HUMAN_PK_FAIL")
            internal_conflict = True

    has_conv, conv_raw = _opt("periodic_pk_converged")
    periodic_pk_converged = _require_exact_bool(conv_raw, f"{pfx}periodic_pk_converged") if has_conv else None
    if periodic_pk_converged is False:
        hold_reasons.append(f"{rtag}PERIODIC_PK_NOT_CONVERGED")

    has_lots, lots_raw = _opt("gmp_lot_count")
    gmp_lots = _require_exact_int(lots_raw, f"{pfx}gmp_lot_count", lo=0) if has_lots else None
    if gmp_lots is not None:
        if gmp_lots == 0:
            fail_reasons.append(f"{rtag}ZERO_GMP_LOTS")
        elif gmp_lots < 2:
            hold_reasons.append(f"{rtag}INSUFFICIENT_GMP_LOTS:{gmp_lots}<2")

    has_don, don_raw = _opt("donor_hla_dq_panel_n")
    don_n = _require_exact_int(don_raw, f"{pfx}donor_hla_dq_panel_n", lo=0) if has_don else None
    if don_n is not None:
        if don_n == 0:
            fail_reasons.append(f"{rtag}ZERO_DONOR_HLA_DQ_PANEL")
        elif don_n < 6:
            hold_reasons.append(f"{rtag}INSUFFICIENT_DONOR_HLA_DQ_PANEL:{don_n}<6")
    if _validate_optional_canonical_id_list(
        src,
        keys=("donor_hla_dq_ids", "donor_ids"),
        expected_count=don_n,
        min_unique=6,
        pfx=pfx,
        rtag=rtag,
        module_tag="SHIELD",
        fail_reasons=fail_reasons,
    ):
        internal_conflict = True

    has_neg, neg_raw = _opt("off_target_negative_states_tested")
    neg_n = _require_exact_int(neg_raw, f"{pfx}off_target_negative_states_tested", lo=0) if has_neg else None
    if neg_n is not None:
        if neg_n == 0:
            fail_reasons.append(f"{rtag}ZERO_NEGATIVE_DESIGN_STATES")
        elif neg_n < 7:
            hold_reasons.append(f"{rtag}INCOMPLETE_NEGATIVE_DESIGN_PANEL:{neg_n}<7")

    # On-target upper 95% Kd bound with calibrated 1 fM (1e-6 nM) lower measurement floor (Audit F14)
    has_kdon, kdon_raw = _opt("on_target_kd_u95_nm")
    kd_on_nm = _require_bounded_float(kdon_raw, f"{pfx}on_target_kd_u95_nm", lo=0.0, hi=1e9, strict_lo=True) if has_kdon else None
    kd_on_calibrated = False
    if kd_on_nm is not None:
        if kd_on_nm < MIN_CALIBRATED_KD_ON_NM:
            fail_reasons.append(f"{rtag}ON_TARGET_KD_BELOW_CALIBRATED_LIMIT_1FM_FAIL:{kd_on_nm:.3e}nM")
            internal_conflict = True
        else:
            kd_on_calibrated = True
            if kd_on_nm > 25.0:
                fail_reasons.append(f"{rtag}ON_TARGET_KD_FAIL:{kd_on_nm}nM")
            elif kd_on_nm > 5.0:
                hold_reasons.append(f"{rtag}ON_TARGET_KD_INTERMEDIATE:{kd_on_nm}nM")

    # Off-target LOWER 95% Kd bound in uM (exact >= 15.0 uM, ZERO tolerance!)
    has_kdoff, kdoff_raw = _opt("off_target_kd_l95_um")
    kd_off_l95_um = _require_bounded_float(kdoff_raw, f"{pfx}off_target_kd_l95_um", lo=0.0, hi=1e9, strict_lo=True) if has_kdoff else None
    kd_off_l95_nm: float | None = None
    if kd_off_l95_um is not None:
        if kd_off_l95_um < MIN_CALIBRATED_KD_OFF_UM:
            fail_reasons.append(f"{rtag}OFF_TARGET_KD_L95_BELOW_CALIBRATED_LIMIT_FAIL:{kd_off_l95_um:.3e}uM")
            internal_conflict = True
        if kd_off_l95_um < 15.0:
            fail_reasons.append(f"{rtag}OFF_TARGET_KD_L95_BELOW_15UM_FAIL:{kd_off_l95_um!r}uM")
        kd_off_l95_nm = kd_off_l95_um * 1000.0

    # Optional off_target_kd_u95_um interval coherence check: require L95 <= U95
    kd_off_u95_um: float | None = None
    if "off_target_kd_u95_um" in src and src["off_target_kd_u95_um"] is not None:
        kd_off_u95_um = _require_bounded_float(src["off_target_kd_u95_um"], f"{pfx}off_target_kd_u95_um", lo=0.0, hi=1e9, strict_lo=True)
        if kd_off_l95_um is not None and kd_off_l95_um > kd_off_u95_um:
            fail_reasons.append(f"{rtag}OFF_TARGET_KD_INTERVAL_INVERTED_FAIL:l95={kd_off_l95_um}>u95={kd_off_u95_um}")
            internal_conflict = True

    has_sel, sel_raw = _opt("selectivity_ratio_l95")
    sel_l95 = _require_bounded_float(sel_raw, f"{pfx}selectivity_ratio_l95", lo=0.0, hi=1e15, strict_lo=True) if has_sel else None
    if sel_l95 is not None and sel_l95 < 15000.0:
        fail_reasons.append(f"{rtag}SELECTIVITY_RATIO_L95_BELOW_15000X_FAIL:{sel_l95!r}")

    # Conservative joint selectivity ratio: (off_target_kd_l95_um * 1000.0) / on_target_kd_u95_nm >= 15000.0 (exact!)
    recomputed_ratio: float | None = None
    if kd_off_l95_nm is not None and kd_on_nm is not None and kd_on_calibrated:
        ratio_candidate = kd_off_l95_nm / kd_on_nm
        if not math.isfinite(ratio_candidate):
            fail_reasons.append(f"{rtag}NONFINITE_RECOMPUTED_SELECTIVITY_RATIO_FAIL")
            internal_conflict = True
        else:
            recomputed_ratio = ratio_candidate
            if recomputed_ratio < 15000.0:
                fail_reasons.append(f"{rtag}CONSERVATIVE_SELECTIVITY_RATIO_BELOW_15000X_FAIL:{recomputed_ratio:.6f}")
            if sel_l95 is not None and sel_l95 > recomputed_ratio * (1.0 + 1e-12):
                fail_reasons.append(f"{rtag}SELECTIVITY_RATIO_L95_INCONSISTENT_EXCEEDS_CONSERVATIVE_KD_RATIO:{sel_l95}>{recomputed_ratio:.6f}")
                internal_conflict = True

    # Q84D strict gating
    if regimen_id == "Q84D":
        if kd_on_nm is not None and kd_on_nm > 1.0:
            fail_reasons.append(f"{rtag}Q84D_REQUIRES_KD_ON_LE_1NM_FAIL:{kd_on_nm!r}nM")
        if human_pk_verified is False:
            fail_reasons.append(f"{rtag}Q84D_REQUIRES_MEASURED_HUMAN_PK_FAIL")
            internal_conflict = True

    has_pk, pk_raw = _opt("peak_free_nm")
    peak_free_nm = _require_bounded_float(pk_raw, f"{pfx}peak_free_nm", lo=0.0, hi=1e9) if has_pk else None
    if peak_free_nm is not None and peak_free_nm <= 0.0:
        fail_reasons.append(f"{rtag}ZERO_PLASMA_PEAK_EXPOSURE_REJECTED")
        internal_conflict = True

    has_ptr, ptr_raw = _opt("plasma_trough_free_nm")
    plasma_trough_free_nm = _require_bounded_float(ptr_raw, f"{pfx}plasma_trough_free_nm", lo=0.0, hi=1e9) if has_ptr else None
    if plasma_trough_free_nm is not None and plasma_trough_free_nm <= 0.0:
        fail_reasons.append(f"{rtag}ZERO_PLASMA_TROUGH_EXPOSURE_REJECTED")
        internal_conflict = True

    has_dln, dln_raw = _opt("dln_trough_free_nm")
    dln_trough_free_nm = _require_bounded_float(dln_raw, f"{pfx}dln_trough_free_nm", lo=0.0, hi=1e9) if has_dln else None
    if dln_trough_free_nm is not None and dln_trough_free_nm <= 0.0:
        fail_reasons.append(f"{rtag}ZERO_DLN_TROUGH_EXPOSURE_REJECTED")
        internal_conflict = True

    # Strict physical compartment ordering: peak_free_nm >= plasma_trough_free_nm >= dln_trough_free_nm > 0
    if peak_free_nm is not None and plasma_trough_free_nm is not None and peak_free_nm < plasma_trough_free_nm:
        fail_reasons.append(f"{rtag}EXPOSURE_ORDERING_INCONSISTENT_PEAK_LT_PLASMA_TROUGH:{peak_free_nm}<{plasma_trough_free_nm}")
        internal_conflict = True
    if plasma_trough_free_nm is not None and dln_trough_free_nm is not None and plasma_trough_free_nm < dln_trough_free_nm:
        fail_reasons.append(f"{rtag}EXPOSURE_ORDERING_INCONSISTENT_PLASMA_TROUGH_LT_DLN_TROUGH:{plasma_trough_free_nm}<{dln_trough_free_nm}")
        internal_conflict = True
    if peak_free_nm is not None and dln_trough_free_nm is not None and peak_free_nm < dln_trough_free_nm:
        fail_reasons.append(f"{rtag}EXPOSURE_ORDERING_INCONSISTENT_PEAK_LT_DLN_TROUGH:{peak_free_nm}<{dln_trough_free_nm}")
        internal_conflict = True

    has_rep_ro, rep_ro_raw = _opt("reported_off_target_peak_ro_pct")
    rep_off_ro = _require_bounded_float(rep_ro_raw, f"{pfx}reported_off_target_peak_ro_pct", lo=0.0, hi=100.0) if has_rep_ro else None
    if rep_off_ro is not None and rep_off_ro > 5.6:
        fail_reasons.append(f"{rtag}REPORTED_OFF_TARGET_PEAK_RO_EXCEEDS_5P6_FAIL:{rep_off_ro!r}%")

    has_adcc, adcc_raw = _opt("fc_adcc_cdc_pct")
    adcc_pct = _require_bounded_float(adcc_raw, f"{pfx}fc_adcc_cdc_pct", lo=0.0, hi=100.0) if has_adcc else None
    if adcc_pct is not None:
        if adcc_pct > 2.0:
            fail_reasons.append(f"{rtag}FC_EFFECTOR_CYTOTOXICITY_FAIL:{adcc_pct}%")
        elif adcc_pct > 1.0:
            hold_reasons.append(f"{rtag}FC_SILENCING_INTERMEDIATE:{adcc_pct}%")

    has_tcell, tcell_raw = _opt("tcell_inhibition_l95_pct")
    tcell_inh = _require_bounded_float(tcell_raw, f"{pfx}tcell_inhibition_l95_pct", lo=0.0, hi=100.0) if has_tcell else None
    if tcell_inh is not None:
        if tcell_inh < 50.0:
            fail_reasons.append(f"{rtag}FUNCTIONAL_TCELL_INHIBITION_FAIL:{tcell_inh}%")
        elif tcell_inh < 70.0:
            hold_reasons.append(f"{rtag}FUNCTIONAL_TCELL_INHIBITION_INTERMEDIATE:{tcell_inh}%")

    has_apc, apc_raw = _opt("apc_cytotoxicity_u95_pct")
    apc_tox = _require_bounded_float(apc_raw, f"{pfx}apc_cytotoxicity_u95_pct", lo=0.0, hi=100.0) if has_apc else None
    if apc_tox is not None and apc_tox > 5.0:
        fail_reasons.append(f"{rtag}APC_CYTOTOXICITY_FAIL:{apc_tox}%")
    if "off_target_apc_killing_u95_pct" in src and src["off_target_apc_killing_u95_pct"] is not None:
        apc_alias = _require_bounded_float(src["off_target_apc_killing_u95_pct"], f"{pfx}off_target_apc_killing_u95_pct", lo=0.0, hi=100.0)
        if apc_alias > 5.0:
            fail_reasons.append(f"{rtag}OFF_TARGET_APC_KILLING_FAIL:{apc_alias}%")
        if apc_tox is not None and apc_alias != apc_tox:
            fail_reasons.append(f"{rtag}APC_CYTOTOXICITY_ALIAS_MISMATCH:{apc_alias}!={apc_tox}")
            internal_conflict = True

    has_mono, mono_raw = _opt("sec_mals_monomer_pct")
    mono_pct = _require_bounded_float(mono_raw, f"{pfx}sec_mals_monomer_pct", lo=0.0, hi=100.0) if has_mono else None
    if mono_pct is not None:
        if mono_pct < 90.0:
            fail_reasons.append(f"{rtag}SEC_MALS_MONOMER_FAIL:{mono_pct}%")
        elif mono_pct < 95.0:
            hold_reasons.append(f"{rtag}SEC_MALS_MONOMER_INTERMEDIATE:{mono_pct}%")

    has_het, het_raw = _opt("ce_sds_heterodimer_pct")
    het_pct = _require_bounded_float(het_raw, f"{pfx}ce_sds_heterodimer_pct", lo=0.0, hi=100.0) if has_het else None
    if het_pct is not None:
        if het_pct < 90.0:
            fail_reasons.append(f"{rtag}CE_SDS_HETERODIMER_FAIL:{het_pct}%")
        elif het_pct < 95.0:
            hold_reasons.append(f"{rtag}CE_SDS_HETERODIMER_INTERMEDIATE:{het_pct}%")

    # Worst-case off-target healthy-APC occupancy using LOWER 95% bound off_target_kd_l95_um
    pan_dq_peak_ro: float | None = None
    pan_dq_plasma_trough_ro: float | None = None
    pan_dq_dln_trough_ro: float | None = None
    on_target_dln_trough_ro: float | None = None

    # Recompute peak off-target RO & enforce two-sided reported_off_target_peak_ro_pct agreement ONLY when
    # peak_free_nm is actually present (Audit R12-07: NEVER substitute plasma/dLN trough exposure when peak is
    # omitted, so omitting peak_free_nm alone returns governed HOLD instead of a false internal-conflict FAIL!).
    if kd_off_l95_nm is not None and peak_free_nm is not None:
        concs = [c for c in (peak_free_nm, plasma_trough_free_nm, dln_trough_free_nm) if c is not None]
        max_conc = max(concs)
        pan_dq_peak_ro = 100.0 * free_ligand_ro(max_conc, kd_off_l95_nm)
        if pan_dq_peak_ro > 5.6:
            fail_reasons.append(f"{rtag}PAN_DQ_PEAK_RO_L95_EXCEEDS_5P6_FAIL:{pan_dq_peak_ro:.4f}%")
        if rep_off_ro is not None and abs(rep_off_ro - pan_dq_peak_ro) > 0.05:
            fail_reasons.append(
                f"{rtag}REPORTED_OFF_TARGET_RO_DEVIATES_FROM_RECOMPUTED:{rep_off_ro:.4f}%!=recomputed:{pan_dq_peak_ro:.4f}%"
            )
            internal_conflict = True
    if kd_off_l95_nm is not None and plasma_trough_free_nm is not None:
        pan_dq_plasma_trough_ro = 100.0 * free_ligand_ro(plasma_trough_free_nm, kd_off_l95_nm)
        if pan_dq_plasma_trough_ro > 5.6:
            fail_reasons.append(f"{rtag}PAN_DQ_PLASMA_TROUGH_RO_L95_EXCEEDS_5P6_FAIL:{pan_dq_plasma_trough_ro:.4f}%")
    if kd_off_l95_nm is not None and dln_trough_free_nm is not None:
        pan_dq_dln_trough_ro = 100.0 * free_ligand_ro(dln_trough_free_nm, kd_off_l95_nm)
        if pan_dq_dln_trough_ro > 1.1:
            fail_reasons.append(f"{rtag}PAN_DQ_DLN_TROUGH_RO_L95_EXCEEDS_1P1_FAIL:{pan_dq_dln_trough_ro:.4f}%")
    if kd_on_nm is not None and kd_on_calibrated and dln_trough_free_nm is not None:
        on_target_dln_trough_ro = 100.0 * free_ligand_ro(dln_trough_free_nm, kd_on_nm)
        if on_target_dln_trough_ro < 90.0:
            fail_reasons.append(f"{rtag}ON_TARGET_DLN_TROUGH_RO_BELOW_90_FAIL:{on_target_dln_trough_ro:.4f}%")

    fields_map = {
        "study_id": study_id,
        "format_id": fmt_id,
        "dosing_regimen": regimen_id,
        "timed_pk_day": timed_pk_day,
        "human_pk_qualified": human_pk_verified,
        "periodic_pk_converged": periodic_pk_converged,
        "gmp_lot_count": gmp_lots,
        "donor_hla_dq_panel_n": don_n,
        "off_target_negative_states_tested": neg_n,
        "on_target_kd_u95_nm": kd_on_nm,
        "off_target_kd_l95_um": kd_off_l95_um,
        "selectivity_ratio_l95": sel_l95,
        "peak_free_nm": peak_free_nm,
        "plasma_trough_free_nm": plasma_trough_free_nm,
        "dln_trough_free_nm": dln_trough_free_nm,
        "reported_off_target_peak_ro_pct": rep_off_ro,
        "fc_adcc_cdc_pct": adcc_pct,
        "tcell_inhibition_l95_pct": tcell_inh,
        "apc_cytotoxicity_u95_pct": apc_tox,
        "sec_mals_monomer_pct": mono_pct,
        "ce_sds_heterodimer_pct": het_pct,
    }
    archive_complete_ok = (
        len(local_missing_fields) == 0
        and all(v is not None for v in fields_map.values())
        and periodic_pk_converged is True
    )
    archive_internally_consistent_ok = not internal_conflict

    return {
        "fields": fields_map,
        "local_missing_fields": local_missing_fields,
        "archive_complete_ok": archive_complete_ok,
        "archive_internally_consistent_ok": archive_internally_consistent_ok,
        "off_target_kd_u95_um": kd_off_u95_um,
        "kd_on_calibrated": kd_on_calibrated,
        "internal_conflict": internal_conflict,
        "pan_dq_peak_ro": pan_dq_peak_ro,
        "pan_dq_plasma_trough_ro": pan_dq_plasma_trough_ro,
        "pan_dq_dln_trough_ro": pan_dq_dln_trough_ro,
        "on_target_dln_trough_ro": on_target_dln_trough_ro,
        "recomputed_ratio": recomputed_ratio,
    }


def evaluate_gate34_shield_sel(
    obs: dict[str, Any],
    arm_manifest: dict[str, Any] | None = None,
    *,
    trusted_evidence_store: dict[str, dict[str, Any]] | None = None,
) -> dict[str, Any]:
    """Fail-closed Gate 34-SHIELD-SEL evaluator (Round-12 Audit R11-04: gate ALL official stats on complete authenticated archive + every internal consistency check; keep caller reconciliation separate)."""
    empty_ro = {
        "occupancy_convention": OCCUPANCY_CONVENTION,
        "pan_dq_peak_ro_pct": None,
        "pan_dq_plasma_trough_ro_pct": None,
        "pan_dq_dln_trough_ro_pct": None,
        "dln_trough_on_target_ro_pct": None,
        "recomputed_selectivity_ratio": None,
        "shield_statistics_derivation_source": "MALFORMED_INPUT",
        "caller_measurements_reconciliation_status": "MALFORMED_INPUT",
        "caller_reported_unverified_pan_dq_peak_ro_pct": None,
        "caller_reported_unverified_pan_dq_plasma_trough_ro_pct": None,
        "caller_reported_unverified_pan_dq_dln_trough_ro_pct": None,
        "caller_reported_unverified_dln_trough_on_target_ro_pct": None,
        "caller_reported_unverified_recomputed_selectivity_ratio": None,
    }
    try:
        if not isinstance(obs, dict):
            raise ValueError("obs must be dict")
        check_strictly_finite(obs, "gate34_shield_sel_obs")

        fail_reasons: list[str] = []
        missing_fields: list[str] = []
        hold_reasons: list[str] = []

        verified_manifest = _verify_manifest_context(arm_manifest, obs, fail_reasons, missing_fields)
        _, arm_entry = _check_arm_and_design_a_invariants(obs, "shield_eligible", verified_manifest, fail_reasons, missing_fields)

        obs_eval = _evaluate_shield_measurements(
            obs, is_archive=False, fail_reasons=fail_reasons, missing_fields=missing_fields, hold_reasons=hold_reasons
        )

        cur_raw = obs.get("current_assay_evidence_record") if "current_assay_evidence_record" in obs else None
        if cur_raw is not None and not isinstance(cur_raw, dict):
            raise ValueError("current_assay_evidence_record must be dict")

        cur_eval: dict[str, Any] | None = None
        caller_matches_archive = False
        if isinstance(cur_raw, dict):
            cur_eval = _evaluate_shield_measurements(
                cur_raw, is_archive=True, fail_reasons=fail_reasons, missing_fields=missing_fields, hold_reasons=hold_reasons
            )
            caller_matches_archive = (not obs_eval["internal_conflict"]) and (len(obs_eval["local_missing_fields"]) == 0)
            # Enforce EXACT equality (ZERO numeric tolerance!) on ALL 21 governing fields between archive & parent!
            for fld, obs_v in obs_eval["fields"].items():
                cur_v = cur_eval["fields"].get(fld)
                if obs_v is None or cur_v is None:
                    caller_matches_archive = False
                elif type(obs_v) is bool or type(cur_v) is bool:
                    if obs_v is not cur_v:
                        fail_reasons.append(f"SHIELD_ASSAY_BINDING_MISMATCH:{fld}:{cur_v}!={obs_v}")
                        caller_matches_archive = False
                elif cur_v != obs_v:
                    fail_reasons.append(f"SHIELD_ASSAY_BINDING_MISMATCH:{fld}:{cur_v!r}!={obs_v!r}")
                    caller_matches_archive = False
            if obs_eval["off_target_kd_u95_um"] is not None and cur_eval["off_target_kd_u95_um"] is not None:
                if cur_eval["off_target_kd_u95_um"] != obs_eval["off_target_kd_u95_um"]:
                    fail_reasons.append(
                        f"SHIELD_ASSAY_BINDING_MISMATCH:off_target_kd_u95_um:{cur_eval['off_target_kd_u95_um']!r}!={obs_eval['off_target_kd_u95_um']!r}"
                    )
                    caller_matches_archive = False

        def _fmt_ro(val: float | None) -> float | None:
            return round(val, 4) if val is not None and math.isfinite(val) else None

        def _caller_shield_unverified() -> dict[str, Any]:
            c_ratio = obs_eval["recomputed_ratio"] if obs_eval["kd_on_calibrated"] else None
            return {
                "caller_reported_unverified_pan_dq_peak_ro_pct": _fmt_ro(obs_eval["pan_dq_peak_ro"]),
                "caller_reported_unverified_pan_dq_plasma_trough_ro_pct": _fmt_ro(obs_eval["pan_dq_plasma_trough_ro"]),
                "caller_reported_unverified_pan_dq_dln_trough_ro_pct": _fmt_ro(obs_eval["pan_dq_dln_trough_ro"]),
                "caller_reported_unverified_dln_trough_on_target_ro_pct": _fmt_ro(obs_eval["on_target_dln_trough_ro"]),
                "caller_reported_unverified_recomputed_selectivity_ratio": _fmt_ro(c_ratio),
            }

        def _build_shield_extra(auth_ctx: dict[str, Any]) -> dict[str, Any]:
            null_official = {
                "occupancy_convention": OCCUPANCY_CONVENTION,
                "pan_dq_peak_ro_pct": None,
                "pan_dq_plasma_trough_ro_pct": None,
                "pan_dq_dln_trough_ro_pct": None,
                "dln_trough_on_target_ro_pct": None,
                "recomputed_selectivity_ratio": None,
            }
            null_caller = {
                "caller_reported_unverified_pan_dq_peak_ro_pct": None,
                "caller_reported_unverified_pan_dq_plasma_trough_ro_pct": None,
                "caller_reported_unverified_pan_dq_dln_trough_ro_pct": None,
                "caller_reported_unverified_dln_trough_on_target_ro_pct": None,
                "caller_reported_unverified_recomputed_selectivity_ratio": None,
            }
            is_auth_wetlab = auth_ctx["archive_authenticated"]
            is_sealed_synth = auth_ctx["synthetic_archive_sealed"]
            is_fail_verdict = auth_ctx["final_verdict"] == "FAIL" or str(auth_ctx["final_verdict"]).startswith("FAIL")

            # State 1a: Unauthenticated / missing archive / missing store / tampered store / broken envelope
            if cur_eval is None or (not is_auth_wetlab and not is_sealed_synth):
                src_label = (
                    "WITHHELD_NO_AUTHENTICATED_ARCHIVE_WITH_INDEPENDENT_FAIL"
                    if is_fail_verdict
                    else "UNVERIFIED_HOLD_NO_AUTHENTICATED_ARCHIVE"
                )
                return {
                    **null_official,
                    "shield_statistics_derivation_source": src_label,
                    "caller_measurements_reconciliation_status": "UNVERIFIED_ARCHIVE_UNAVAILABLE",
                    **_caller_shield_unverified(),
                }

            # State 2: Any internal archive consistency check fails (always FAIL verdict)
            if not cur_eval["archive_internally_consistent_ok"]:
                return {
                    **null_official,
                    "shield_statistics_derivation_source": "WITHHELD_INTERNAL_ARCHIVE_CONFLICT",
                    "caller_measurements_reconciliation_status": "WITHHELD_INTERNAL_ARCHIVE_CONFLICT",
                    **_caller_shield_unverified(),
                }

            # State 1b: Authenticated archive is incomplete (omitted mandatory archived field e.g. study_id, or unconverged periodic PK)
            if not cur_eval["archive_complete_ok"]:
                src_label = (
                    "WITHHELD_INCOMPLETE_ARCHIVE_WITH_INDEPENDENT_FAIL"
                    if is_fail_verdict
                    else "UNVERIFIED_HOLD_INCOMPLETE_ARCHIVE"
                )
                return {
                    **null_official,
                    "shield_statistics_derivation_source": src_label,
                    "caller_measurements_reconciliation_status": "UNVERIFIED_ARCHIVE_UNAVAILABLE",
                    **_caller_shield_unverified(),
                }

            arch_ratio = cur_eval["recomputed_ratio"] if cur_eval["kd_on_calibrated"] else None
            official_stats = {
                "occupancy_convention": OCCUPANCY_CONVENTION,
                "pan_dq_peak_ro_pct": _fmt_ro(cur_eval["pan_dq_peak_ro"]),
                "pan_dq_plasma_trough_ro_pct": _fmt_ro(cur_eval["pan_dq_plasma_trough_ro"]),
                "pan_dq_dln_trough_ro_pct": _fmt_ro(cur_eval["pan_dq_dln_trough_ro"]),
                "dln_trough_on_target_ro_pct": _fmt_ro(cur_eval["on_target_dln_trough_ro"]),
                "recomputed_selectivity_ratio": _fmt_ro(arch_ratio),
            }
            if any(
                official_stats[k] is None
                for k in (
                    "pan_dq_peak_ro_pct",
                    "pan_dq_plasma_trough_ro_pct",
                    "pan_dq_dln_trough_ro_pct",
                    "dln_trough_on_target_ro_pct",
                    "recomputed_selectivity_ratio",
                )
            ):
                return {
                    **null_official,
                    "shield_statistics_derivation_source": "WITHHELD_INTERNAL_ARCHIVE_CONFLICT",
                    "caller_measurements_reconciliation_status": "WITHHELD_INTERNAL_ARCHIVE_CONFLICT",
                    **_caller_shield_unverified(),
                }

            if caller_matches_archive:
                # State 3: Authenticated, complete, internally consistent archive + clean caller reconciliation
                src_label = (
                    "AUTHENTICATED_ARCHIVE_VERIFIED"
                    if is_auth_wetlab
                    else "SYNTHETIC_FIXTURE_ARCHIVE_SELF_TEST"
                )
                return {
                    **official_stats,
                    "shield_statistics_derivation_source": src_label,
                    "caller_measurements_reconciliation_status": "MATCHED",
                    **null_caller,
                }

            # State 4: Authenticated, complete, internally consistent archive contradicted ONLY by caller
            src_label = (
                "AUTHENTICATED_ARCHIVE_ONLY_CALLER_CONFLICT"
                if is_auth_wetlab
                else "SYNTHETIC_FIXTURE_ARCHIVE_ONLY_CALLER_CONFLICT"
            )
            return {
                **official_stats,
                "shield_statistics_derivation_source": src_label,
                "caller_measurements_reconciliation_status": "CONFLICT_CALLER_MISMATCH",
                **_caller_shield_unverified(),
            }

        return _verify_upstream_evidence_and_finalize(
            obs,
            CANONICAL_GATE36_MODULE_SOURCES["shield"],
            None,
            arm_entry,
            trusted_evidence_store,
            fail_reasons,
            missing_fields,
            hold_reasons,
            verified_manifest=verified_manifest,
            extra_builder=_build_shield_extra,
            require_live_gate32_debris_recall=True,
        )
    except ValueError as exc:
        return _malformed_rejection(exc, empty_ro)


def _is_more_conservative_hla(cand: dict[str, Any], base: dict[str, Any], *, prefer_equal: bool = False) -> bool:
    """Return True if HLA panel summary `cand` is strictly more conservative than `base` (lower unique donors / higher U95)."""
    if not cand.get("donor_lists_complete"):
        return False
    if not base.get("donor_lists_complete"):
        return True
    c_n = cand.get("unique_donor_count", 0)
    b_n = base.get("unique_donor_count", 0)
    if c_n == 0 and b_n > 0:
        return True
    if b_n == 0 and c_n > 0:
        return False
    c_u95 = cand.get("exact_u95_pct")
    b_u95 = base.get("exact_u95_pct")
    if c_u95 is not None and b_u95 is None:
        return True
    if c_u95 is not None and b_u95 is not None:
        if c_u95 > b_u95:
            return True
        if c_u95 < b_u95:
            return False
    if c_n < b_n:
        return True
    if c_n > b_n:
        return False
    return prefer_equal


def _merge_seen_raw_maps(*maps: dict[str, set[str]]) -> dict[str, set[str]]:
    merged: dict[str, set[str]] = {}
    for mp in maps:
        for ckey, raws in mp.items():
            merged.setdefault(ckey, set()).update(raws)
    return merged


def _evaluate_ins_hla_panels(
    hrec_raw: Any,
    *,
    pfx: str,
    rtag: str,
    field_label: str,
    fail_reasons: list[str],
    missing_fields: list[str],
    hold_reasons: list[str],
    local_missing_fields: list[str] | None = None,
) -> dict[str, Any]:
    """Validate per-allele HLA panels with strict canonical ASCII donor IDs, separator-first canonical deduplication, & shared issuer identity."""
    if not isinstance(hrec_raw, dict):
        raise ValueError(f"{pfx}{field_label} must be dict")
    def _miss_panel(field_path: str) -> None:
        missing_fields.append(field_path)
        if local_missing_fields is not None:
            local_missing_fields.append(field_path)

    pooled_panel_entries = 0
    unique_donor_canon_keys: set[str] = set()
    unique_reactive_canon_keys: set[str] = set()
    seen_raw_by_canon_key: dict[str, set[str]] = {}
    observed_peptides: dict[str, str] = {}
    parsed_panels: dict[str, dict[str, Any]] = {}
    alleles_complete = True
    donor_lists_complete = True
    reactive_lists_complete = True
    panel_internal_conflict = False

    container_issuers, container_valid, container_noncanon, container_empty = _extract_and_validate_issuer_ids(
        hrec_raw, location=f"{pfx}{field_label}", rtag=rtag, fail_reasons=fail_reasons
    )
    if len(set(container_issuers)) > 1:
        fail_reasons.append(
            f"{rtag}INS_INCONSISTENT_DONOR_ISSUER_ID_FAIL:{field_label}:{sorted(set(container_issuers))}"
        )
        panel_internal_conflict = True
    observed_issuer_ids: set[str] = set(container_issuers)
    valid_issuer_ids: set[str] = set(container_valid)
    has_noncanonical_issuer = container_noncanon
    saw_empty_issuer = container_empty
    allele_issuer_presence_count = 0

    for allele in MANDATORY_INS_HLA_ALLELES:
        if allele not in hrec_raw or hrec_raw[allele] is None:
            alleles_complete = False
            donor_lists_complete = False
            reactive_lists_complete = False
            panel_internal_conflict = True
            fail_reasons.append(f"{rtag}MISSING_MANDATORY_HLA_ALLELE_RECORD:{allele}")
            continue
        arec = hrec_raw[allele]
        if not isinstance(arec, dict):
            raise ValueError(f"{pfx}{field_label}.{allele} must be dict")
        p_al: dict[str, Any] = {}

        al_issuers, al_valid, al_noncanon, al_empty = _extract_and_validate_issuer_ids(
            arec, location=f"{pfx}{field_label}.{allele}", rtag=rtag, fail_reasons=fail_reasons
        )
        if al_noncanon:
            has_noncanonical_issuer = True
        if al_empty:
            saw_empty_issuer = True
        if al_issuers:
            allele_issuer_presence_count += 1
            observed_issuer_ids.update(al_issuers)
            valid_issuer_ids.update(al_valid)
            if len(set(al_issuers)) > 1:
                fail_reasons.append(f"{rtag}INS_INCONSISTENT_DONOR_ISSUER_ID_FAIL:{allele}:{sorted(set(al_issuers))}")
                panel_internal_conflict = True

        if "peptide_tested" not in arec or arec["peptide_tested"] is None:
            _miss_panel(f"{pfx}{field_label}.{allele}.peptide_tested")
        else:
            pt = _require_canonical_ascii_id(arec["peptide_tested"], f"{pfx}hla[{allele}].peptide_tested", rtag=rtag, fail_reasons=fail_reasons)
            if not _is_strict_canonical_ascii_id(arec["peptide_tested"]):
                panel_internal_conflict = True
            observed_peptides[allele] = pt
            p_al["peptide_tested"] = pt
            allowed_peps = MANDATORY_INS_HLA_TARGET_PEPTIDES[allele]
            if pt not in allowed_peps:
                fail_reasons.append(f"{rtag}WRONG_PEPTIDE_TESTED:{allele}:{pt} not in {sorted(allowed_peps)}")
        if "binding_assay_verified" not in arec or arec["binding_assay_verified"] is None:
            _miss_panel(f"{pfx}{field_label}.{allele}.binding_assay_verified")
        else:
            bav = _require_exact_bool(arec["binding_assay_verified"], f"{pfx}hla[{allele}].binding_assay_verified")
            p_al["binding_assay_verified"] = bav
            if bav is False:
                fail_reasons.append(f"{rtag}ALLELE_BINDING_ASSAY_NOT_VERIFIED:{allele}")
        if "mutant_binding_gain_fold" not in arec or arec["mutant_binding_gain_fold"] is None:
            _miss_panel(f"{pfx}{field_label}.{allele}.mutant_binding_gain_fold")
        else:
            bfold = _require_bounded_float(
                arec["mutant_binding_gain_fold"], f"{pfx}hla[{allele}].mutant_binding_gain_fold", lo=0.0, hi=1e6, strict_lo=True
            )
            p_al["mutant_binding_gain_fold"] = bfold
            if bfold > 5.0:
                fail_reasons.append(f"{rtag}ALLELE_MUTANT_BINDING_GAIN_FAIL:{allele}={bfold}x")
            elif bfold > 2.0:
                hold_reasons.append(f"{rtag}ALLELE_MUTANT_BINDING_GAIN_BORDERLINE:{allele}={bfold}x")

        panel_raw_dids: list[str] | None = None
        panel_canon_dids: list[str] | None = None
        if "donor_ids" not in arec or arec["donor_ids"] is None:
            _miss_panel(f"{pfx}{field_label}.{allele}.donor_ids")
            donor_lists_complete = False
        else:
            raw_dids = arec["donor_ids"]
            if not isinstance(raw_dids, (list, tuple)):
                raise ValueError(f"{pfx}hla[{allele}].donor_ids must be list of non-empty strings")
            parsed_dids = [
                _parse_and_validate_donor_id(
                    x,
                    field_name=f"{pfx}hla[{allele}].donor_ids[]",
                    allele_tag=allele,
                    rtag=rtag,
                    fail_reasons=fail_reasons,
                )
                for x in raw_dids
            ]
            panel_raw_dids = [raw_did for raw_did, _, _ in parsed_dids]
            panel_canon_dids = [ckey for _, _, ckey in parsed_dids]
            for raw_did, _, ckey in parsed_dids:
                seen_raw_by_canon_key.setdefault(ckey, set()).add(raw_did)
            p_al["donor_ids"] = sorted(panel_raw_dids)
            p_al["canonical_donor_ids"] = sorted(panel_canon_dids)
            if len(set(panel_canon_dids)) != len(panel_canon_dids):
                fail_reasons.append(f"{rtag}DUPLICATE_DONOR_ID_WITHIN_ALLELE_PANEL:{allele}")
            pooled_panel_entries += len(panel_canon_dids)
            unique_donor_canon_keys.update(panel_canon_dids)
            if len(set(panel_canon_dids)) < 2:
                fail_reasons.append(f"{rtag}INSUFFICIENT_PER_ALLELE_UNIQUE_DONORS:{allele}={len(set(panel_canon_dids))}<2")

        ad_n: int | None = None
        if "donor_count" not in arec or arec["donor_count"] is None:
            _miss_panel(f"{pfx}{field_label}.{allele}.donor_count")
        else:
            ad_n = _require_exact_int(arec["donor_count"], f"{pfx}hla[{allele}].donor_count", lo=0)
            p_al["donor_count"] = ad_n
            if ad_n < 2:
                fail_reasons.append(f"{rtag}INSUFFICIENT_PER_ALLELE_DONORS:{allele}={ad_n}<2")
            if panel_canon_dids is not None and ad_n != len(panel_canon_dids):
                fail_reasons.append(f"{rtag}DONOR_COUNT_ID_LIST_MISMATCH:{allele}:count={ad_n}!=len(donor_ids)={len(panel_canon_dids)}")
                panel_internal_conflict = True

        panel_raw_rdids: list[str] | None = None
        panel_canon_rdids: list[str] | None = None
        if "reactive_donor_ids" not in arec or arec["reactive_donor_ids"] is None:
            _miss_panel(f"{pfx}{field_label}.{allele}.reactive_donor_ids")
            reactive_lists_complete = False
        else:
            raw_rdids = arec["reactive_donor_ids"]
            if not isinstance(raw_rdids, (list, tuple)):
                raise ValueError(f"{pfx}hla[{allele}].reactive_donor_ids must be list of non-empty strings")
            parsed_rdids = [
                _parse_and_validate_donor_id(
                    x,
                    field_name=f"{pfx}hla[{allele}].reactive_donor_ids[]",
                    allele_tag=f"{allele}.reactive",
                    rtag=rtag,
                    fail_reasons=fail_reasons,
                )
                for x in raw_rdids
            ]
            panel_raw_rdids = [raw_rdid for raw_rdid, _, _ in parsed_rdids]
            panel_canon_rdids = [ckey for _, _, ckey in parsed_rdids]
            for raw_rdid, _, ckey in parsed_rdids:
                seen_raw_by_canon_key.setdefault(ckey, set()).add(raw_rdid)
            p_al["reactive_donor_ids"] = sorted(panel_raw_rdids)
            p_al["canonical_reactive_donor_ids"] = sorted(panel_canon_rdids)
            if len(set(panel_canon_rdids)) != len(panel_canon_rdids):
                fail_reasons.append(f"{rtag}DUPLICATE_REACTIVE_DONOR_ID_WITHIN_ALLELE_PANEL:{allele}")
                panel_internal_conflict = True
            if panel_raw_dids is not None and panel_canon_dids is not None:
                if (not set(panel_raw_rdids).issubset(set(panel_raw_dids))) or (
                    not set(panel_canon_rdids).issubset(set(panel_canon_dids))
                ):
                    fail_reasons.append(f"{rtag}REACTIVE_DONOR_NOT_IN_PANEL_DONOR_IDS:{allele}")
                    panel_internal_conflict = True
            unique_reactive_canon_keys.update(panel_canon_rdids)

        if "reactive_donors" not in arec or arec["reactive_donors"] is None:
            _miss_panel(f"{pfx}{field_label}.{allele}.reactive_donors")
        else:
            rd_n = _require_exact_int(arec["reactive_donors"], f"{pfx}hla[{allele}].reactive_donors", lo=0)
            p_al["reactive_donors"] = rd_n
            if ad_n is not None and rd_n > ad_n:
                fail_reasons.append(f"{rtag}REACTIVE_DONORS_EXCEED_DONOR_COUNT:{allele}:{rd_n}>{ad_n}")
                panel_internal_conflict = True
            if panel_canon_rdids is not None and rd_n != len(panel_canon_rdids):
                fail_reasons.append(f"{rtag}REACTIVE_DONOR_COUNT_ID_LIST_MISMATCH:{allele}:{rd_n}!={len(panel_canon_rdids)}")
                panel_internal_conflict = True

        sfu_val: float | None = None
        if "max_elispot_sfu" not in arec or arec["max_elispot_sfu"] is None:
            _miss_panel(f"{pfx}{field_label}.{allele}.max_elispot_sfu")
        else:
            sfu_val = _require_bounded_float(arec["max_elispot_sfu"], f"{pfx}hla[{allele}].max_elispot_sfu", lo=0.0, hi=1e6)
            p_al["max_elispot_sfu"] = sfu_val
            if sfu_val > 50.0:
                fail_reasons.append(f"{rtag}ALLELE_ELISPOT_SFU_FAIL:{allele}={sfu_val}")
            elif sfu_val >= 20.0:
                hold_reasons.append(f"{rtag}ALLELE_ELISPOT_SFU_BORDERLINE:{allele}={sfu_val}")
        if "max_fold_vs_wt" not in arec or arec["max_fold_vs_wt"] is None:
            _miss_panel(f"{pfx}{field_label}.{allele}.max_fold_vs_wt")
        else:
            fold_val = _require_bounded_float(arec["max_fold_vs_wt"], f"{pfx}hla[{allele}].max_fold_vs_wt", lo=0.0, hi=1e6)
            p_al["max_fold_vs_wt"] = fold_val
            if (sfu_val is not None and sfu_val > 50.0 and fold_val > 3.0) or fold_val > 5.0:
                fail_reasons.append(f"{rtag}ALLELE_ELISPOT_FOLD_FAIL:{allele}={fold_val}x")
            elif fold_val > 2.0:
                hold_reasons.append(f"{rtag}ALLELE_ELISPOT_FOLD_BORDERLINE:{allele}={fold_val}x")
        parsed_panels[allele] = p_al

    partial_allele_issuers = 0 < allele_issuer_presence_count < len(MANDATORY_INS_HLA_ALLELES)
    if partial_allele_issuers:
        fail_reasons.append(
            f"{rtag}INS_PARTIAL_PANEL_DONOR_ISSUER_ID_FAIL:{field_label}:present={allele_issuer_presence_count}/{len(MANDATORY_INS_HLA_ALLELES)}"
        )
        panel_internal_conflict = True
    if saw_empty_issuer and observed_issuer_ids:
        fail_reasons.append(
            f"{rtag}INS_INCONSISTENT_DONOR_ISSUER_ID_FAIL:{field_label}:empty_and_nonempty_issuer_fields"
        )
        panel_internal_conflict = True
    if len(observed_issuer_ids) > 1:
        fail_reasons.append(
            f"{rtag}INS_INCONSISTENT_DONOR_ISSUER_ID_FAIL:{field_label}:{sorted(observed_issuer_ids)}"
        )
        panel_internal_conflict = True
    if has_noncanonical_issuer:
        panel_internal_conflict = True
    issuer_missing = len(observed_issuer_ids) == 0
    effective_issuer_id: str | None = (
        next(iter(valid_issuer_ids))
        if (
            len(valid_issuer_ids) == 1
            and len(observed_issuer_ids) == 1
            and not has_noncanonical_issuer
            and not partial_allele_issuers
            and not saw_empty_issuer
        )
        else None
    )

    for ckey, raws in sorted(seen_raw_by_canon_key.items()):
        if len(raws) > 1:
            fail_reasons.append(
                f"{rtag}INS_INCONSISTENT_DONOR_ID_FORMATTING_VARIANT:{ckey}:{sorted(r[:32] for r in raws)}"
            )

    unique_donor_count = len(unique_donor_canon_keys)
    unique_reactive_count = len(unique_reactive_canon_keys)
    exact_u95_pct: float | None = (
        round(_clopper_pearson_upper_95_pct(unique_reactive_count, unique_donor_count), 4)
        if unique_donor_count > 0 and unique_reactive_count <= unique_donor_count and reactive_lists_complete
        else None
    )

    if alleles_complete and donor_lists_complete:
        if unique_donor_count == 0:
            fail_reasons.append(f"{rtag}ZERO_UNIQUE_HLA_DONORS")
        elif unique_donor_count < 12:
            fail_reasons.append(
                f"{rtag}INSUFFICIENT_UNIQUE_HLA_DONORS_AFTER_DEDUPLICATION_FAIL:unique={unique_donor_count}<12"
                f"(pooled={pooled_panel_entries},u95={exact_u95_pct}%)"
            )
        if unique_donor_count > 0:
            react_pct = 100.0 * unique_reactive_count / unique_donor_count
            if react_pct > 15.0:
                fail_reasons.append(f"{rtag}DONOR_ELISPOT_REACTIVE_PCT_FAIL:{react_pct:.2f}%")
            elif unique_reactive_count > 0:
                hold_reasons.append(f"{rtag}DONOR_ELISPOT_NONZERO_REACTIVE:{unique_reactive_count}/{unique_donor_count}")

    return {
        "parsed_panels": parsed_panels,
        "observed_peptides": observed_peptides,
        "pooled_panel_entries": pooled_panel_entries,
        "unique_donor_count": unique_donor_count,
        "unique_reactive_count": unique_reactive_count,
        "exact_u95_pct": exact_u95_pct,
        "alleles_complete": alleles_complete,
        "donor_lists_complete": donor_lists_complete,
        "reactive_lists_complete": reactive_lists_complete,
        "panel_internal_conflict": panel_internal_conflict,
        "unique_donor_canon_keys": unique_donor_canon_keys,
        "unique_reactive_canon_keys": unique_reactive_canon_keys,
        "seen_raw_by_canon_key": seen_raw_by_canon_key,
        "effective_issuer_id": effective_issuer_id,
        "observed_issuer_ids": observed_issuer_ids,
        "valid_issuer_ids": valid_issuer_ids,
        "issuer_missing": issuer_missing,
        "has_noncanonical_issuer": has_noncanonical_issuer,
        "saw_empty_issuer": saw_empty_issuer,
    }


def _evaluate_ins_measurements(
    src: dict[str, Any],
    *,
    is_archive: bool,
    fail_reasons: list[str],
    missing_fields: list[str],
    hold_reasons: list[str],
) -> dict[str, Any]:
    """Validate and enforce ALL governing INS p.Leu82Ile measurements, completeness, & cutoffs directly on `src` (ZERO tolerance)."""
    pfx = "current_assay_evidence_record." if is_archive else ""
    rtag = "ARCHIVE_" if is_archive else ""
    local_missing_fields: list[str] = []
    internal_archive_non_roster_conflict = False

    def _miss(field_path: str) -> None:
        missing_fields.append(field_path)
        local_missing_fields.append(field_path)

    def _opt(key: str) -> tuple[bool, Any]:
        if key not in src or src[key] is None:
            _miss(f"{pfx}{key}")
            return False, None
        return True, src[key]

    has_study, study_raw = _opt("study_id")
    study_id: str | None = None
    if has_study:
        study_id = _require_canonical_ascii_id(study_raw, f"{pfx}study_id", rtag=rtag, fail_reasons=fail_reasons)
        if not _is_strict_canonical_ascii_id(study_raw):
            internal_archive_non_roster_conflict = True

    top_issuers, top_valid_issuers, top_noncanon, top_empty = _extract_and_validate_issuer_ids(
        src, location=pfx.rstrip(".") or "obs", rtag=rtag, fail_reasons=fail_reasons
    )
    if len(set(top_issuers)) > 1:
        fail_reasons.append(f"{rtag}INS_INCONSISTENT_DONOR_ISSUER_ID_FAIL:top_level:{sorted(set(top_issuers))}")

    has_ed, ed_raw = _opt("editor_class")
    editor_class: str | None = None
    if has_ed:
        editor_class = _require_nonempty_str(ed_raw, f"{pfx}editor_class")
        if editor_class != "PE2max":
            fail_reasons.append(f"{rtag}GY021_EDITOR_CLASS_VIOLATION:{editor_class}")

    has_mlh, mlh_raw = _opt("mlh1dn_used")
    mlh1dn_used = _require_exact_bool(mlh_raw, f"{pfx}mlh1dn_used") if has_mlh else None
    if mlh1dn_used is True:
        fail_reasons.append(f"{rtag}GY021_VIOLATION_MLH1DN_BANNED")

    # Structured per-kit C-peptide ELISA records with GOVERNED kit catalog allowlist
    observed_kit_catalogs: dict[str, str] = {}
    parsed_kits: dict[str, dict[str, Any]] = {}
    has_kits, kits_raw = _opt("day1_cpeptide_elisa_kit_records")
    if has_kits:
        if not isinstance(kits_raw, dict):
            raise ValueError(f"{pfx}day1_cpeptide_elisa_kit_records must be dict")
        for kit in MANDATORY_CPEP_ELISA_KITS:
            if kit not in kits_raw or kits_raw[kit] is None:
                _miss(f"{pfx}day1_cpeptide_elisa_kit_records.{kit}")
                continue
            krec = kits_raw[kit]
            if not isinstance(krec, dict):
                raise ValueError(f"{pfx}day1_cpeptide_elisa_kit_records.{kit} must be dict")
            pk: dict[str, Any] = {}
            if "kit_catalog_id" not in krec or krec["kit_catalog_id"] is None:
                _miss(f"{pfx}day1_cpeptide_elisa_kit_records.{kit}.kit_catalog_id")
            else:
                cat_id = _require_canonical_ascii_id(krec["kit_catalog_id"], f"{pfx}elisa[{kit}].kit_catalog_id", rtag=rtag, fail_reasons=fail_reasons)
                if not _is_strict_canonical_ascii_id(krec["kit_catalog_id"]):
                    internal_archive_non_roster_conflict = True
                observed_kit_catalogs[kit] = cat_id
                pk["kit_catalog_id"] = cat_id
                if cat_id not in GOVERNED_CPEP_ELISA_KIT_CATALOGS[kit]:
                    fail_reasons.append(f"{rtag}UNREGISTERED_CPEP_KIT_CATALOG_ID:{kit}:{cat_id}")
            if "kit_lot_id" not in krec or krec["kit_lot_id"] is None:
                _miss(f"{pfx}day1_cpeptide_elisa_kit_records.{kit}.kit_lot_id")
            else:
                pk["kit_lot_id"] = _require_canonical_ascii_id(krec["kit_lot_id"], f"{pfx}elisa[{kit}].kit_lot_id", rtag=rtag, fail_reasons=fail_reasons)
                if not _is_strict_canonical_ascii_id(krec["kit_lot_id"]):
                    internal_archive_non_roster_conflict = True
            for cfld, ckind in (
                ("low_conc_nmol_L", "low"),
                ("mid_conc_nmol_L", "mid"),
                ("diluted_high_conc_nmol_L", "high"),
            ):
                if cfld not in krec or krec[cfld] is None:
                    _miss(f"{pfx}day1_cpeptide_elisa_kit_records.{kit}.{cfld}")
                else:
                    cval = _require_bounded_float(krec[cfld], f"{pfx}elisa[{kit}].{cfld}", lo=0.0, hi=1e6, strict_lo=True)
                    pk[cfld] = cval
                    if ckind == "low" and cval > 0.05:
                        fail_reasons.append(f"{rtag}ELISA_LOW_CONC_DOES_NOT_COVER_0P05:{kit}={cval}")
                    elif ckind == "mid" and not (0.05 < cval < 5.00):
                        fail_reasons.append(f"{rtag}ELISA_MID_CONC_OUT_OF_SPAN:{kit}={cval}")
                    elif ckind == "high" and cval < 5.00:
                        fail_reasons.append(f"{rtag}ELISA_HIGH_CONC_DOES_NOT_COVER_5P00:{kit}={cval}")
            for rfld in ("low_conc_recovery_pct", "mid_conc_recovery_pct", "diluted_high_conc_recovery_pct"):
                if rfld not in krec or krec[rfld] is None:
                    _miss(f"{pfx}day1_cpeptide_elisa_kit_records.{kit}.{rfld}")
                else:
                    rval = _require_bounded_float(krec[rfld], f"{pfx}elisa[{kit}].{rfld}", lo=0.0, hi=300.0)
                    pk[rfld] = rval
                    if rval < 85.0 or rval > 115.0:
                        fail_reasons.append(f"{rtag}DAY1_CPEP_ELISA_RECOVERY_FAIL:{kit}.{rfld}={rval}%")
            parsed_kits[kit] = pk

    # Optional ELISA alias guards if present on archive
    if "elisa_kit_id" in src and src["elisa_kit_id"] is not None:
        ek = src["elisa_kit_id"]
        all_gov = set().union(*GOVERNED_CPEP_ELISA_KIT_CATALOGS.values())
        if isinstance(ek, str):
            ek_s = _require_canonical_ascii_id(ek, f"{pfx}elisa_kit_id", rtag=rtag, fail_reasons=fail_reasons)
            if not _is_strict_canonical_ascii_id(ek):
                internal_archive_non_roster_conflict = True
            if ek_s not in all_gov:
                fail_reasons.append(f"{rtag}UNREGISTERED_ELISA_KIT_ID_ALIAS:{ek_s}")
        elif isinstance(ek, dict):
            for kit in MANDATORY_CPEP_ELISA_KITS:
                if kit in ek and ek[kit] is not None:
                    kc = _require_canonical_ascii_id(ek[kit], f"{pfx}elisa_kit_id.{kit}", rtag=rtag, fail_reasons=fail_reasons)
                    if not _is_strict_canonical_ascii_id(ek[kit]):
                        internal_archive_non_roster_conflict = True
                    if kc not in GOVERNED_CPEP_ELISA_KIT_CATALOGS[kit]:
                        fail_reasons.append(f"{rtag}UNREGISTERED_ELISA_KIT_ID_ALIAS:{kit}:{kc}")
                    if kit in observed_kit_catalogs and kc != observed_kit_catalogs[kit]:
                        fail_reasons.append(f"{rtag}ELISA_KIT_ID_ALIAS_MISMATCH:{kit}:{kc}!={observed_kit_catalogs[kit]}")
                        internal_archive_non_roster_conflict = True
        else:
            raise ValueError(f"{pfx}elisa_kit_id must be str or dict")
    for alias_rec in ("elisa_recovery_pct", "dilution_linearity_pct"):
        if alias_rec in src and src[alias_rec] is not None:
            av = _require_bounded_float(src[alias_rec], f"{pfx}{alias_rec}", lo=0.0, hi=300.0)
            if av < 85.0 or av > 115.0:
                fail_reasons.append(f"{rtag}{alias_rec.upper()}_OUT_OF_RANGE_FAIL:{av}%")

    has_mlo, mlo_raw = _opt("mercodia_low_end_0p05_verified")
    mercodia_low = _require_exact_bool(mlo_raw, f"{pfx}mercodia_low_end_0p05_verified") if has_mlo else None
    if mercodia_low is False:
        fail_reasons.append(f"{rtag}MERCODIA_LOW_END_0P05_COVERAGE_NOT_VERIFIED")

    has_mhi, mhi_raw = _opt("mercodia_dilution_linearity_5p00_verified")
    mercodia_hi = _require_exact_bool(mhi_raw, f"{pfx}mercodia_dilution_linearity_5p00_verified") if has_mhi else None
    if mercodia_hi is False:
        fail_reasons.append(f"{rtag}MERCODIA_DILUTION_LINEARITY_5P00_NOT_VERIFIED")

    has_hbv, hbv_raw = _opt("hla_binding_verified")
    hla_binding_verified = _require_exact_bool(hbv_raw, f"{pfx}hla_binding_verified") if has_hbv else None
    if hla_binding_verified is False:
        fail_reasons.append(f"{rtag}HLA_BINDING_NOT_VERIFIED_FAIL")

    has_hrec, hrec_raw = _opt("hla_allele_panel_records")
    if has_hrec:
        hla_res = _evaluate_ins_hla_panels(
            hrec_raw,
            pfx=pfx,
            rtag=rtag,
            field_label="hla_allele_panel_records",
            fail_reasons=fail_reasons,
            missing_fields=missing_fields,
            hold_reasons=hold_reasons,
            local_missing_fields=local_missing_fields,
        )
    else:
        hla_res = {
            "parsed_panels": {},
            "observed_peptides": {},
            "pooled_panel_entries": 0,
            "unique_donor_count": 0,
            "unique_reactive_count": 0,
            "exact_u95_pct": None,
            "alleles_complete": False,
            "donor_lists_complete": False,
            "reactive_lists_complete": False,
            "panel_internal_conflict": False,
            "unique_donor_canon_keys": set(),
            "unique_reactive_canon_keys": set(),
            "seen_raw_by_canon_key": {},
            "effective_issuer_id": None,
            "observed_issuer_ids": set(),
            "valid_issuer_ids": set(),
            "issuer_missing": True,
            "has_noncanonical_issuer": False,
            "saw_empty_issuer": False,
        }

    # Optional per_allele_panels alias (Audit R4-05 / R8-06 / R9-04 / R10-03 guard): validate, deduplicate, & reconcile canonical IDs + positive issuer identity!
    internal_archive_roster_conflict = bool(has_hrec and hla_res["panel_internal_conflict"])
    if len(set(top_issuers)) > 1 or top_noncanon:
        internal_archive_roster_conflict = True
    alias_hla_res: dict[str, Any] | None = None
    if "per_allele_panels" in src and src["per_allele_panels"] is not None:
        alias_hla_res = _evaluate_ins_hla_panels(
            src["per_allele_panels"],
            pfx=pfx,
            rtag=f"{rtag}ALIAS_",
            field_label="per_allele_panels",
            fail_reasons=fail_reasons,
            missing_fields=missing_fields,
            hold_reasons=hold_reasons,
            local_missing_fields=local_missing_fields,
        )
        if alias_hla_res["panel_internal_conflict"]:
            internal_archive_roster_conflict = True
        if has_hrec:
            if alias_hla_res["unique_donor_canon_keys"] != hla_res["unique_donor_canon_keys"]:
                fail_reasons.append(f"{rtag}PER_ALLELE_PANELS_CANONICAL_DONOR_SET_MISMATCH")
                internal_archive_roster_conflict = True
            if alias_hla_res["unique_reactive_canon_keys"] != hla_res["unique_reactive_canon_keys"]:
                fail_reasons.append(f"{rtag}PER_ALLELE_PANELS_CANONICAL_REACTIVE_SET_MISMATCH")
                internal_archive_roster_conflict = True
            if alias_hla_res["parsed_panels"] != hla_res["parsed_panels"]:
                fail_reasons.append(f"{rtag}PER_ALLELE_PANELS_ALIAS_MISMATCH")
                internal_archive_roster_conflict = True
            # Positive issuer disagreement between two present roster forms ALWAYS fails closed;
            # omitted/empty issuer handling (HOLD if archive omits, FAIL if current omits when archive establishes one)
            # is enforced across both archive and current payloads in evaluate_gate34_ins_l82i_elisa_pe2max!
            if (
                not hla_res["issuer_missing"]
                and not alias_hla_res["issuer_missing"]
                and (
                    hla_res["effective_issuer_id"] != alias_hla_res["effective_issuer_id"]
                    or hla_res["observed_issuer_ids"] != alias_hla_res["observed_issuer_ids"]
                )
            ):
                fail_reasons.append(
                    f"{rtag}INS_ROSTER_DONOR_ISSUER_ID_MISMATCH:"
                    f"hla_allele_panel_records={hla_res['effective_issuer_id']!r}!=per_allele_panels={alias_hla_res['effective_issuer_id']!r}"
                )
                internal_archive_roster_conflict = True
            cross_roster_raw = _merge_seen_raw_maps(
                hla_res["seen_raw_by_canon_key"], alias_hla_res["seen_raw_by_canon_key"]
            )
            for ckey, raws in sorted(cross_roster_raw.items()):
                if len(raws) > 1:
                    fail_reasons.append(
                        f"{rtag}INS_INCONSISTENT_DONOR_ID_FORMATTING_VARIANT:cross_roster:{ckey}:{sorted(r[:32] for r in raws)}"
                    )

    present_roster_forms: dict[str, dict[str, Any]] = {}
    if has_hrec:
        present_roster_forms["hla_allele_panel_records"] = hla_res
    if alias_hla_res is not None:
        present_roster_forms["per_allele_panels"] = alias_hla_res

    all_observed_issuers: set[str] = set(top_issuers)
    for fres in present_roster_forms.values():
        all_observed_issuers.update(fres["observed_issuer_ids"])
    if len(all_observed_issuers) > 1:
        fail_reasons.append(f"{rtag}INS_INCONSISTENT_DONOR_ISSUER_ID_FAIL:all_scopes:{sorted(all_observed_issuers)}")
        internal_archive_roster_conflict = True
    if top_empty and all_observed_issuers:
        fail_reasons.append(f"{rtag}INS_INCONSISTENT_DONOR_ISSUER_ID_FAIL:top_level:empty_and_nonempty_issuer_fields")
        internal_archive_roster_conflict = True
    effective_issuer_id: str | None = (
        next(iter(all_observed_issuers))
        if (
            len(all_observed_issuers) == 1
            and not top_noncanon
            and not top_empty
            and len(present_roster_forms) >= 1
            and all(fres["effective_issuer_id"] is not None for fres in present_roster_forms.values())
            and (not top_issuers or set(top_valid_issuers) == all_observed_issuers)
        )
        else None
    )

    merged_seen_raw = _merge_seen_raw_maps(
        hla_res["seen_raw_by_canon_key"],
        alias_hla_res["seen_raw_by_canon_key"] if alias_hla_res is not None else {},
    )

    # Archive-specific summary fields reconciled DIRECTLY against deduplicated archived rosters & kits!
    if is_archive:
        if "unique_hla_donor_count" not in src or src["unique_hla_donor_count"] is None:
            _miss(f"{pfx}unique_hla_donor_count")
        else:
            ud_cur = _require_exact_int(src["unique_hla_donor_count"], f"{pfx}unique_hla_donor_count", lo=0)
            if ud_cur < 12:
                fail_reasons.append(f"ARCHIVE_UNIQUE_HLA_DONOR_COUNT_SUMMARY_BELOW_12_FAIL:{ud_cur}<12")
            if hla_res["donor_lists_complete"] and ud_cur != hla_res["unique_donor_count"]:
                fail_reasons.append(
                    f"INS_ARCHIVE_SUMMARY_UNIQUE_DONOR_COUNT_MISMATCH:summary={ud_cur}!=archived_roster={hla_res['unique_donor_count']}"
                )
            if alias_hla_res is not None and alias_hla_res["donor_lists_complete"] and ud_cur != alias_hla_res["unique_donor_count"]:
                fail_reasons.append(
                    f"INS_ARCHIVE_SUMMARY_UNIQUE_DONOR_COUNT_MISMATCH:summary={ud_cur}!=alias_roster={alias_hla_res['unique_donor_count']}"
                )
        if "kit_catalog_ids" not in src or src["kit_catalog_ids"] is None:
            _miss(f"{pfx}kit_catalog_ids")
        else:
            kmap = src["kit_catalog_ids"]
            if not isinstance(kmap, dict):
                raise ValueError(f"{pfx}kit_catalog_ids must be dict")
            for kit in MANDATORY_CPEP_ELISA_KITS:
                if kit not in kmap or kmap[kit] is None:
                    _miss(f"{pfx}kit_catalog_ids.{kit}")
                else:
                    kc = _require_canonical_ascii_id(kmap[kit], f"{pfx}kit_catalog_ids.{kit}", rtag=rtag, fail_reasons=fail_reasons)
                    if not _is_strict_canonical_ascii_id(kmap[kit]):
                        internal_archive_non_roster_conflict = True
                    if kc not in GOVERNED_CPEP_ELISA_KIT_CATALOGS[kit]:
                        fail_reasons.append(f"INS_ASSAY_UNREGISTERED_KIT_CATALOG_ID:{kit}:{kc}")
                    if kit in observed_kit_catalogs and kc != observed_kit_catalogs[kit]:
                        fail_reasons.append(f"INS_ARCHIVE_KIT_SUMMARY_MISMATCH:{kit}:{kc}!={observed_kit_catalogs[kit]}")
                        internal_archive_non_roster_conflict = True
        if "hla_peptides_tested" not in src or src["hla_peptides_tested"] is None:
            _miss(f"{pfx}hla_peptides_tested")
        else:
            pmap = src["hla_peptides_tested"]
            if not isinstance(pmap, dict):
                raise ValueError(f"{pfx}hla_peptides_tested must be dict")
            for al in MANDATORY_INS_HLA_ALLELES:
                if al not in pmap or pmap[al] is None:
                    _miss(f"{pfx}hla_peptides_tested.{al}")
                else:
                    ap = _require_canonical_ascii_id(pmap[al], f"{pfx}hla_peptides_tested.{al}", rtag=rtag, fail_reasons=fail_reasons)
                    if not _is_strict_canonical_ascii_id(pmap[al]):
                        internal_archive_non_roster_conflict = True
                    if ap not in MANDATORY_INS_HLA_TARGET_PEPTIDES[al]:
                        fail_reasons.append(f"INS_ASSAY_WRONG_PEPTIDE_TESTED:{al}:{ap}")
                    if al in hla_res["observed_peptides"] and ap != hla_res["observed_peptides"][al]:
                        fail_reasons.append(f"INS_ARCHIVE_PEPTIDE_SUMMARY_MISMATCH:{al}:{ap}!={hla_res['observed_peptides'][al]}")
                        internal_archive_non_roster_conflict = True

    has_pcp, pcp_raw = _opt("product_cell_peptidomics_verified")
    pcp_verified = _require_exact_bool(pcp_raw, f"{pfx}product_cell_peptidomics_verified") if has_pcp else None
    if pcp_verified is False:
        hold_reasons.append(f"{rtag}PROSPECTIVE_EDITED_PRODUCT_CELL_PEPTIDOMICS_PENDING")

    has_spl, spl_raw = _opt("rna_splicing_delta_psi_pct")
    dpsi = _require_bounded_float(spl_raw, f"{pfx}rna_splicing_delta_psi_pct", lo=0.0, hi=100.0) if has_spl else None
    if dpsi is not None:
        if dpsi >= 5.0:
            fail_reasons.append(f"{rtag}RNA_SPLICING_ABERRANT_FAIL:delta_psi={dpsi}%")
        elif dpsi >= 1.0:
            hold_reasons.append(f"{rtag}RNA_SPLICING_BORDERLINE:delta_psi={dpsi}%")

    has_pi, pi_raw = _opt("proinsulin_to_insulin_ratio_vs_wt")
    pi_rat = _require_bounded_float(pi_raw, f"{pfx}proinsulin_to_insulin_ratio_vs_wt", lo=0.0, hi=1e6, strict_lo=True) if has_pi else None
    if pi_rat is not None:
        if pi_rat > 2.0:
            fail_reasons.append(f"{rtag}PROINSULIN_PROCESSING_FAIL:{pi_rat}x")
        elif pi_rat > 1.25:
            hold_reasons.append(f"{rtag}PROINSULIN_PROCESSING_BORDERLINE:{pi_rat}x")

    has_bys, bys_raw = _opt("per_lot_bystander_edit_pct")
    bys_pct = _require_bounded_float(bys_raw, f"{pfx}per_lot_bystander_edit_pct", lo=0.0, hi=100.0) if has_bys else None
    if bys_pct is not None:
        if bys_pct > 1.0:
            fail_reasons.append(f"{rtag}PER_LOT_BYSTANDER_EDIT_FAIL:{bys_pct}%")
        elif bys_pct > 0.1:
            hold_reasons.append(f"{rtag}PER_LOT_BYSTANDER_EDIT_BORDERLINE:{bys_pct}%")
    if "bystander_edit_rate_pct" in src and src["bystander_edit_rate_pct"] is not None:
        bys_alias = _require_bounded_float(src["bystander_edit_rate_pct"], f"{pfx}bystander_edit_rate_pct", lo=0.0, hi=100.0)
        if bys_alias > 1.0:
            fail_reasons.append(f"{rtag}BYSTANDER_EDIT_RATE_ALIAS_FAIL:{bys_alias}%")
        elif bys_alias > 0.1:
            hold_reasons.append(f"{rtag}BYSTANDER_EDIT_RATE_ALIAS_BORDERLINE:{bys_alias}%")
        if bys_pct is not None and bys_alias != bys_pct:
            fail_reasons.append(f"{rtag}BYSTANDER_EDIT_RATE_ALIAS_MISMATCH:{bys_alias}!={bys_pct}")
            internal_archive_non_roster_conflict = True

    has_gsis, gsis_raw = _opt("gsis_si")
    gsis_si = _require_bounded_float(gsis_raw, f"{pfx}gsis_si", lo=0.0, hi=1e6) if has_gsis else None
    if gsis_si is not None:
        if gsis_si < 2.0:
            fail_reasons.append(f"{rtag}GSIS_SI_FAIL:{gsis_si}")
        elif gsis_si < 2.5:
            hold_reasons.append(f"{rtag}GSIS_SI_INTERMEDIATE:{gsis_si}")
    if "gsis_stimulation_index" in src and src["gsis_stimulation_index"] is not None:
        gsis_alias = _require_bounded_float(src["gsis_stimulation_index"], f"{pfx}gsis_stimulation_index", lo=0.0, hi=1e6)
        if gsis_alias < 2.0:
            fail_reasons.append(f"{rtag}GSIS_STIMULATION_INDEX_ALIAS_FAIL:{gsis_alias}")
        elif gsis_alias < 2.5:
            hold_reasons.append(f"{rtag}GSIS_STIMULATION_INDEX_ALIAS_INTERMEDIATE:{gsis_alias}")
        if gsis_si is not None and gsis_alias != gsis_si:
            fail_reasons.append(f"{rtag}GSIS_STIMULATION_INDEX_ALIAS_MISMATCH:{gsis_alias}!={gsis_si}")
            internal_archive_non_roster_conflict = True

    has_gpc, gpc_raw = _opt("gsis_pct_of_wt")
    gpc = _require_bounded_float(gpc_raw, f"{pfx}gsis_pct_of_wt", lo=0.0, hi=300.0) if has_gpc else None
    if gpc is not None:
        if gpc < 75.0:
            fail_reasons.append(f"{rtag}GSIS_PCT_WT_FAIL:{gpc}%")
        elif gpc < 85.0:
            hold_reasons.append(f"{rtag}GSIS_PCT_WT_INTERMEDIATE:{gpc}%")

    has_hip, hip_raw = _opt("hip_reduction_pct")
    hip_drop = _require_bounded_float(hip_raw, f"{pfx}hip_reduction_pct", lo=0.0, hi=100.0) if has_hip else None
    if hip_drop is not None:
        if hip_drop < 50.0:
            fail_reasons.append(f"{rtag}HIP11_ABLATION_FAIL:{hip_drop}%")
        elif hip_drop < 80.0:
            hold_reasons.append(f"{rtag}HIP11_ABLATION_INTERMEDIATE:{hip_drop}%")

    # Select conservative HLA summary if alias per_allele_panels was also supplied
    eff_hla = hla_res
    if alias_hla_res is not None and _is_more_conservative_hla(alias_hla_res, eff_hla):
        eff_hla = alias_hla_res

    return {
        "scalars": {
            "study_id": study_id,
            "editor_class": editor_class,
            "mlh1dn_used": mlh1dn_used,
            "mercodia_low_end_0p05_verified": mercodia_low,
            "mercodia_dilution_linearity_5p00_verified": mercodia_hi,
            "hla_binding_verified": hla_binding_verified,
            "product_cell_peptidomics_verified": pcp_verified,
            "rna_splicing_delta_psi_pct": dpsi,
            "proinsulin_to_insulin_ratio_vs_wt": pi_rat,
            "per_lot_bystander_edit_pct": bys_pct,
            "gsis_si": gsis_si,
            "gsis_pct_of_wt": gpc,
            "hip_reduction_pct": hip_drop,
        },
        "local_missing_fields": local_missing_fields,
        "archive_complete_ok": len(local_missing_fields) == 0,
        "internal_archive_non_roster_conflict": internal_archive_non_roster_conflict,
        "parsed_kits": parsed_kits,
        "observed_kit_catalogs": observed_kit_catalogs,
        "hla": eff_hla,
        "primary_hla": hla_res,
        "alias_hla": alias_hla_res,
        "has_primary_hla": has_hrec,
        "primary_hla_complete": bool(
            has_hrec
            and hla_res["alleles_complete"]
            and hla_res["donor_lists_complete"]
            and hla_res["reactive_lists_complete"]
            and (
                alias_hla_res is None
                or (
                    alias_hla_res["alleles_complete"]
                    and alias_hla_res["donor_lists_complete"]
                    and alias_hla_res["reactive_lists_complete"]
                )
            )
        ),
        "internal_archive_roster_conflict": internal_archive_roster_conflict,
        "archive_issuer_missing": (not present_roster_forms) or any(fres["issuer_missing"] for fres in present_roster_forms.values()),
        "present_roster_forms": present_roster_forms,
        "merged_seen_raw_by_canon_key": merged_seen_raw,
        "effective_issuer_id": effective_issuer_id,
        "all_observed_issuers": all_observed_issuers,
        "top_issuers": top_issuers,
        "top_empty": top_empty,
    }


def evaluate_gate34_ins_l82i_elisa_pe2max(
    obs: dict[str, Any],
    arm_manifest: dict[str, Any] | None = None,
    *,
    trusted_evidence_store: dict[str, dict[str, Any]] | None = None,
) -> dict[str, Any]:
    """Fail-closed Gate 34-INS-L82I-ELISA-PE2MAX evaluator (Round-11 Audit R10-03: strict 4-state archive-only official statistics; null on unverified/HOLD/missing-issuer/internal-archive-conflict; caller stats labeled separately)."""
    empty_ins = {
        "unique_hla_donors_verified": None,
        "pooled_allele_panel_observations": None,
        "total_hla_donors_verified": None,
        "total_reactive_donors": None,
        "exact_one_sided_95pct_u95_pct": None,
        "ins_statistics_derivation_source": "MALFORMED_INPUT",
        "caller_roster_reconciliation_status": "MALFORMED_INPUT",
        "caller_reported_unverified_unique_donors": None,
        "caller_reported_unverified_reactive_donors": None,
        "caller_reported_unverified_u95_pct": None,
    }
    try:
        if not isinstance(obs, dict):
            raise ValueError("obs must be dict")
        check_strictly_finite(obs, "gate34_ins_l82i_obs")

        fail_reasons: list[str] = []
        missing_fields: list[str] = []
        hold_reasons: list[str] = []

        verified_manifest = _verify_manifest_context(arm_manifest, obs, fail_reasons, missing_fields)
        _, arm_entry = _check_arm_and_design_a_invariants(obs, "ins_l82i_eligible", verified_manifest, fail_reasons, missing_fields)

        obs_eval = _evaluate_ins_measurements(
            obs, is_archive=False, fail_reasons=fail_reasons, missing_fields=missing_fields, hold_reasons=hold_reasons
        )

        cur_raw = obs.get("current_assay_evidence_record") if "current_assay_evidence_record" in obs else None
        if cur_raw is not None and not isinstance(cur_raw, dict):
            raise ValueError("current_assay_evidence_record must be dict")

        cur_eval: dict[str, Any] | None = None
        caller_roster_matches_archive = False
        if isinstance(cur_raw, dict):
            cur_eval = _evaluate_ins_measurements(
                cur_raw, is_archive=True, fail_reasons=fail_reasons, missing_fields=missing_fields, hold_reasons=hold_reasons
            )
            # Enforce EXACT equality (ZERO numeric tolerance!) across ALL scalar fields, kit records, & HLA allele panels!
            for fld, obs_v in obs_eval["scalars"].items():
                cur_v = cur_eval["scalars"].get(fld)
                if obs_v is not None and cur_v is not None:
                    if type(obs_v) is bool or type(cur_v) is bool:
                        if obs_v is not cur_v:
                            fail_reasons.append(f"INS_ASSAY_BINDING_MISMATCH:{fld}:{cur_v}!={obs_v}")
                    elif cur_v != obs_v:
                        fail_reasons.append(f"INS_ASSAY_BINDING_MISMATCH:{fld}:{cur_v!r}!={obs_v!r}")

            for kit in MANDATORY_CPEP_ELISA_KITS:
                ok_k = obs_eval["parsed_kits"].get(kit)
                ck_k = cur_eval["parsed_kits"].get(kit)
                if ok_k is not None and ck_k is not None:
                    for subk, ov in ok_k.items():
                        if subk in ck_k and ck_k[subk] != ov:
                            fail_reasons.append(f"INS_ASSAY_BINDING_MISMATCH:elisa.{kit}.{subk}:{ck_k[subk]!r}!={ov!r}")

            for al in MANDATORY_INS_HLA_ALLELES:
                oa = obs_eval["primary_hla"]["parsed_panels"].get(al)
                ca = cur_eval["primary_hla"]["parsed_panels"].get(al)
                if oa is not None and ca is not None:
                    for subk, ov in oa.items():
                        if subk in ca:
                            cv = ca[subk]
                            if type(ov) is bool or type(cv) is bool:
                                if cv is not ov:
                                    fail_reasons.append(f"INS_ASSAY_BINDING_MISMATCH:hla.{al}.{subk}:{cv}!={ov}")
                            elif cv != ov:
                                fail_reasons.append(f"INS_ASSAY_BINDING_MISMATCH:hla.{al}.{subk}:{cv!r}!={ov!r}")

            # Cross-check archive summary & canonical donor sets against parent observations
            if obs_eval["hla"]["donor_lists_complete"] and cur_eval["hla"]["donor_lists_complete"]:
                if cur_eval["hla"]["unique_donor_count"] != obs_eval["hla"]["unique_donor_count"]:
                    fail_reasons.append(
                        f"INS_ASSAY_BINDING_MISMATCH:unique_hla_donors:archive={cur_eval['hla']['unique_donor_count']}!=parent={obs_eval['hla']['unique_donor_count']}"
                    )
                if cur_eval["hla"]["unique_donor_canon_keys"] != obs_eval["hla"]["unique_donor_canon_keys"]:
                    fail_reasons.append("INS_ASSAY_BINDING_MISMATCH:canonical_donor_key_set")

            # Strict 1-to-1 raw-vs-canonical consistency across BOTH parent and archive rosters!
            parent_archive_raw = _merge_seen_raw_maps(
                obs_eval["merged_seen_raw_by_canon_key"], cur_eval["merged_seen_raw_by_canon_key"]
            )
            for ckey, raws in sorted(parent_archive_raw.items()):
                if len(raws) > 1:
                    fail_reasons.append(
                        f"INS_INCONSISTENT_DONOR_ID_FORMATTING_VARIANT:parent_vs_archive:{ckey}:{sorted(r[:32] for r in raws)}"
                    )

            # Mandatory positive canonical ASCII HLA registry issuer enforcement across ALL present roster forms (Audit R9-04):
            # NEVER treat omitted issuers (None == None) as agreeing or equivalent!
            # - Archive omits issuer (absent, None, or "") on ANY present archived roster form -> HOLD!
            # - Archive establishes positive canonical issuer across ALL present archived forms ->
            #     Current omits issuer on ANY present form OR disagrees -> FAIL!
            # - Conflicting positive issuers across parent & archive scopes -> FAIL!
            union_issuers = obs_eval["all_observed_issuers"] | cur_eval["all_observed_issuers"]
            if len(union_issuers) > 1:
                fail_reasons.append(
                    f"INS_ASSAY_BINDING_MISMATCH:donor_issuer_id:{sorted(union_issuers)}"
                )

            arch_forms: dict[str, dict[str, Any]] = cur_eval["present_roster_forms"]
            obs_forms: dict[str, dict[str, Any]] = obs_eval["present_roster_forms"]
            arch_missing_forms = [fname for fname, fres in arch_forms.items() if fres["issuer_missing"]]

            if not arch_forms:
                hold_reasons.append("HOLD_MISSING_ARCHIVED_HLA_REGISTRY_ISSUER:no_archived_roster_present")
            elif arch_missing_forms:
                for fname in arch_missing_forms:
                    hold_reasons.append(f"HOLD_MISSING_ARCHIVED_HLA_REGISTRY_ISSUER:{fname}")

            archive_established_issuer: str | None = cur_eval["effective_issuer_id"]
            if archive_established_issuer is not None:
                obs_missing_forms = [fname for fname, fres in obs_forms.items() if fres["issuer_missing"]]
                for fname in obs_missing_forms:
                    fail_reasons.append(
                        f"INS_MISSING_CURRENT_HLA_REGISTRY_ISSUER:{fname}:archive={archive_established_issuer!r}"
                    )
                if len(obs_forms) == 2 and len(obs_missing_forms) == 1:
                    obs_p = obs_forms["hla_allele_panel_records"]["effective_issuer_id"]
                    obs_a = obs_forms["per_allele_panels"]["effective_issuer_id"]
                    fail_reasons.append(
                        f"INS_ROSTER_DONOR_ISSUER_ID_MISMATCH:"
                        f"hla_allele_panel_records={obs_p!r}!=per_allele_panels={obs_a!r}"
                    )
                for fname, fres in obs_forms.items():
                    if not fres["issuer_missing"] and fres["effective_issuer_id"] is not None:
                        if fres["effective_issuer_id"] != archive_established_issuer:
                            fail_reasons.append(
                                f"INS_ASSAY_BINDING_MISMATCH:donor_issuer_id:{fname}:"
                                f"archive={archive_established_issuer!r}!=parent={fres['effective_issuer_id']!r}"
                            )
                if obs_eval["top_issuers"]:
                    for ti in sorted(set(obs_eval["top_issuers"])):
                        if ti != archive_established_issuer:
                            fail_reasons.append(
                                f"INS_ASSAY_BINDING_MISMATCH:donor_issuer_id:top_level:"
                                f"archive={archive_established_issuer!r}!=parent={ti!r}"
                            )
                if obs_eval["top_empty"]:
                    fail_reasons.append(
                        f"INS_MISSING_CURRENT_HLA_REGISTRY_ISSUER:top_level:archive={archive_established_issuer!r}"
                    )

            # Determine exact caller-vs-archive HLA roster & issuer reconciliation (Audit R10-03)
            if (
                cur_eval["has_primary_hla"]
                and cur_eval["primary_hla_complete"]
                and not cur_eval["internal_archive_roster_conflict"]
                and archive_established_issuer is not None
                and not cur_eval["archive_issuer_missing"]
            ):
                obs_alias = obs_eval["alias_hla"]
                alias_reconciles = (
                    obs_alias is None
                    or (
                        obs_alias["alleles_complete"]
                        and obs_alias["donor_lists_complete"]
                        and obs_alias["reactive_lists_complete"]
                        and obs_alias["parsed_panels"] == cur_eval["primary_hla"]["parsed_panels"]
                        and obs_alias["unique_donor_canon_keys"] == cur_eval["primary_hla"]["unique_donor_canon_keys"]
                        and obs_alias["unique_reactive_canon_keys"] == cur_eval["primary_hla"]["unique_reactive_canon_keys"]
                    )
                )
                caller_roster_matches_archive = bool(
                    obs_eval["has_primary_hla"]
                    and obs_eval["primary_hla_complete"]
                    and not obs_eval["internal_archive_roster_conflict"]
                    and obs_eval["primary_hla"]["parsed_panels"] == cur_eval["primary_hla"]["parsed_panels"]
                    and obs_eval["primary_hla"]["unique_donor_canon_keys"] == cur_eval["primary_hla"]["unique_donor_canon_keys"]
                    and obs_eval["primary_hla"]["unique_reactive_canon_keys"] == cur_eval["primary_hla"]["unique_reactive_canon_keys"]
                    and alias_reconciles
                    and obs_eval["merged_seen_raw_by_canon_key"] == cur_eval["merged_seen_raw_by_canon_key"]
                    and obs_eval["effective_issuer_id"] == archive_established_issuer
                    and obs_eval["all_observed_issuers"] == {archive_established_issuer}
                    and not obs_eval["top_empty"]
                    and not obs_eval["archive_issuer_missing"]
                )
        else:
            hold_reasons.append("HOLD_MISSING_ARCHIVED_HLA_REGISTRY_ISSUER:current_assay_evidence_record_missing")

        def _caller_ins_unverified() -> dict[str, Any]:
            c_hla = obs_eval["hla"]
            if (
                c_hla["alleles_complete"]
                and c_hla["donor_lists_complete"]
                and c_hla["reactive_lists_complete"]
                and c_hla["unique_donor_count"] > 0
                and c_hla["exact_u95_pct"] is not None
            ):
                return {
                    "caller_reported_unverified_unique_donors": c_hla["unique_donor_count"],
                    "caller_reported_unverified_reactive_donors": c_hla["unique_reactive_count"],
                    "caller_reported_unverified_u95_pct": c_hla["exact_u95_pct"],
                }
            return {
                "caller_reported_unverified_unique_donors": None,
                "caller_reported_unverified_reactive_donors": None,
                "caller_reported_unverified_u95_pct": None,
            }

        def _build_ins_extra(auth_ctx: dict[str, Any]) -> dict[str, Any]:
            null_official = {
                "unique_hla_donors_verified": None,
                "pooled_allele_panel_observations": None,
                "total_hla_donors_verified": None,
                "total_reactive_donors": None,
                "exact_one_sided_95pct_u95_pct": None,
            }
            null_caller = {
                "caller_reported_unverified_unique_donors": None,
                "caller_reported_unverified_reactive_donors": None,
                "caller_reported_unverified_u95_pct": None,
            }
            is_auth_wetlab = auth_ctx["archive_authenticated"]
            is_sealed_synth = auth_ctx["synthetic_archive_sealed"]
            is_fail_verdict = auth_ctx["final_verdict"] == "FAIL" or str(auth_ctx["final_verdict"]).startswith("FAIL")

            # State 1a: Unauthenticated / missing archive / missing or failed trusted store (Audit R12-07: final_verdict-aware, NEVER *_HOLD_* on FAIL!)
            if cur_eval is None or (not is_auth_wetlab and not is_sealed_synth):
                src_label = (
                    "WITHHELD_NO_AUTHENTICATED_ARCHIVE_WITH_INDEPENDENT_FAIL"
                    if is_fail_verdict
                    else "UNVERIFIED_HOLD_NO_AUTHENTICATED_ARCHIVE"
                )
                return {
                    **null_official,
                    "ins_statistics_derivation_source": src_label,
                    "caller_roster_reconciliation_status": "UNVERIFIED_ARCHIVE_UNAVAILABLE",
                    **_caller_ins_unverified(),
                }

            # State 2: Internally conflicting / invalid archive (roster or non-roster internal archive conflict)
            if cur_eval["internal_archive_roster_conflict"] or cur_eval["internal_archive_non_roster_conflict"]:
                return {
                    **null_official,
                    "ins_statistics_derivation_source": "WITHHELD_INTERNAL_ARCHIVE_CONFLICT",
                    "caller_roster_reconciliation_status": "WITHHELD_INTERNAL_ARCHIVE_CONFLICT",
                    **_caller_ins_unverified(),
                }

            # State 1b: Archive omits mandatory primary roster or omits positive canonical HLA registry issuer
            if not cur_eval["has_primary_hla"] or not cur_eval["primary_hla_complete"]:
                src_label = (
                    "WITHHELD_INCOMPLETE_ARCHIVE_WITH_INDEPENDENT_FAIL"
                    if is_fail_verdict
                    else "UNVERIFIED_HOLD_INCOMPLETE_ARCHIVE"
                )
                return {
                    **null_official,
                    "ins_statistics_derivation_source": src_label,
                    "caller_roster_reconciliation_status": "UNVERIFIED_ARCHIVE_UNAVAILABLE",
                    **_caller_ins_unverified(),
                }
            if cur_eval["effective_issuer_id"] is None or cur_eval["archive_issuer_missing"]:
                src_label = (
                    "WITHHELD_INCOMPLETE_ARCHIVE_WITH_INDEPENDENT_FAIL"
                    if is_fail_verdict
                    else "UNVERIFIED_HOLD_MISSING_ARCHIVED_ISSUER"
                )
                return {
                    **null_official,
                    "ins_statistics_derivation_source": src_label,
                    "caller_roster_reconciliation_status": "UNVERIFIED_ARCHIVE_UNAVAILABLE",
                    **_caller_ins_unverified(),
                }

            # State 1c: Authenticated archive omits any other mandatory archived field (e.g. study_id, editor_class, ELISA/summary fields)
            if not cur_eval["archive_complete_ok"]:
                src_label = (
                    "WITHHELD_INCOMPLETE_ARCHIVE_WITH_INDEPENDENT_FAIL"
                    if is_fail_verdict
                    else "UNVERIFIED_HOLD_INCOMPLETE_ARCHIVE"
                )
                return {
                    **null_official,
                    "ins_statistics_derivation_source": src_label,
                    "caller_roster_reconciliation_status": "UNVERIFIED_ARCHIVE_UNAVAILABLE",
                    **_caller_ins_unverified(),
                }

            # Archive is authenticated (or sealed synthetic), internally complete, non-conflicting, with explicit positive issuer.
            # Official statistics are computed 100% STRICTLY from cur_eval["primary_hla"] (ZERO caller contamination!).
            arch_hla = cur_eval["primary_hla"]
            if arch_hla["unique_donor_count"] <= 0 or arch_hla["exact_u95_pct"] is None:
                return {
                    **null_official,
                    "ins_statistics_derivation_source": "WITHHELD_INTERNAL_ARCHIVE_CONFLICT",
                    "caller_roster_reconciliation_status": "WITHHELD_INTERNAL_ARCHIVE_CONFLICT",
                    **_caller_ins_unverified(),
                }

            official_stats = {
                "unique_hla_donors_verified": arch_hla["unique_donor_count"],
                "pooled_allele_panel_observations": arch_hla["pooled_panel_entries"],
                "total_hla_donors_verified": arch_hla["unique_donor_count"],
                "total_reactive_donors": arch_hla["unique_reactive_count"],
                "exact_one_sided_95pct_u95_pct": arch_hla["exact_u95_pct"],
            }

            if caller_roster_matches_archive:
                # State 3: Clean caller reconciliation
                src_label = (
                    "AUTHENTICATED_ARCHIVE_ROSTER_VERIFIED"
                    if is_auth_wetlab
                    else "SYNTHETIC_FIXTURE_ARCHIVE_SELF_TEST"
                )
                return {
                    **official_stats,
                    "ins_statistics_derivation_source": src_label,
                    "caller_roster_reconciliation_status": "MATCHED",
                    **null_caller,
                }

            # State 4: Authenticated archive contradicted by caller -> official stats strictly from archive, caller isolated!
            src_label = (
                "AUTHENTICATED_ARCHIVE_ONLY_CALLER_CONFLICT"
                if is_auth_wetlab
                else "SYNTHETIC_FIXTURE_ARCHIVE_ONLY_CALLER_CONFLICT"
            )
            return {
                **official_stats,
                "ins_statistics_derivation_source": src_label,
                "caller_roster_reconciliation_status": "CONFLICT_CALLER_MISMATCH",
                **_caller_ins_unverified(),
            }

        return _verify_upstream_evidence_and_finalize(
            obs,
            CANONICAL_GATE34_MODULE_SOURCES["ins"],
            None,
            arm_entry,
            trusted_evidence_store,
            fail_reasons,
            missing_fields,
            hold_reasons,
            verified_manifest=verified_manifest,
            extra_builder=_build_ins_extra,
        )
    except ValueError as exc:
        return _malformed_rejection(exc, empty_ins)


def _evaluate_cuff_measurements(
    src: dict[str, Any],
    *,
    is_archive: bool,
    fail_reasons: list[str],
    missing_fields: list[str],
    hold_reasons: list[str],
) -> dict[str, Any]:
    """Validate and enforce ALL governing Cuff v2.0 measurements & cutoffs directly on `src` (ZERO threshold tolerance)."""
    pfx = "current_assay_evidence_record." if is_archive else ""
    rtag = "ARCHIVE_" if is_archive else ""

    def _opt(key: str) -> tuple[bool, Any]:
        if key not in src or src[key] is None:
            missing_fields.append(f"{pfx}{key}")
            return False, None
        return True, src[key]

    has_study, study_raw = _opt("study_id")
    study_id = _require_canonical_ascii_id(study_raw, f"{pfx}study_id", rtag=rtag, fail_reasons=fail_reasons) if has_study else None

    # Exact 3-protein core assembly manifest: {"sCR1_v2", "THBD-M406L", "CD200-ECD"}
    has_core, core_raw = _opt("core_cuff_proteins")
    parsed_core: list[str] | None = None
    if has_core:
        if not isinstance(core_raw, (list, tuple)):
            raise ValueError(f"{pfx}core_cuff_proteins must be list of strings")
        parsed_core = [_require_canonical_ascii_id(x, f"{pfx}core_cuff_protein", rtag=rtag, fail_reasons=fail_reasons) for x in core_raw]
        if len(parsed_core) != 3 or set(parsed_core) != CANONICAL_CORE_CUFF_PROTEINS:
            fail_reasons.append(f"{rtag}CORE_3_PROTEIN_CUFF_MANIFEST_MISMATCH:{parsed_core}")
    if "core_proteins" in src and src["core_proteins"] is not None:
        cp_alias_raw = src["core_proteins"]
        if not isinstance(cp_alias_raw, (list, tuple)):
            raise ValueError(f"{pfx}core_proteins must be list of strings")
        cp_alias = [_require_canonical_ascii_id(x, f"{pfx}core_proteins[]", rtag=rtag, fail_reasons=fail_reasons) for x in cp_alias_raw]
        if len(cp_alias) != 3 or set(cp_alias) != CANONICAL_CORE_CUFF_PROTEINS:
            fail_reasons.append(f"{rtag}CORE_PROTEINS_ALIAS_MANIFEST_MISMATCH:{cp_alias}")
        if parsed_core is not None and set(cp_alias) != set(parsed_core):
            fail_reasons.append(f"{rtag}CORE_PROTEINS_ALIAS_MISMATCH:{cp_alias}!={parsed_core}")

    # Lot-linked per-protein conjugation yield, PEG tier, exact 0 unpaired ECD Cys, & free thiol
    parsed_conj: dict[str, dict[str, Any]] = {}
    has_conj, conj_raw = _opt("per_protein_conjugation_records")
    if has_conj:
        if not isinstance(conj_raw, dict):
            raise ValueError(f"{pfx}per_protein_conjugation_records must be dict")
        peg_rules = {
            "sCR1_v2": ("max", 5.0),
            "THBD-M406L": ("max", 5.0),
            "CD200-ECD": ("min", 20.0),
        }
        for prot in ("sCR1_v2", "THBD-M406L", "CD200-ECD"):
            if prot not in conj_raw or conj_raw[prot] is None:
                missing_fields.append(f"{pfx}per_protein_conjugation_records.{prot}")
                continue
            prec = conj_raw[prot]
            if not isinstance(prec, dict):
                raise ValueError(f"{pfx}per_protein_conjugation_records.{prot} must be dict")
            pp: dict[str, Any] = {}
            if "protein_lot_id" not in prec or prec["protein_lot_id"] is None:
                missing_fields.append(f"{pfx}per_protein_conjugation_records.{prot}.protein_lot_id")
            else:
                pp["protein_lot_id"] = _require_canonical_ascii_id(prec["protein_lot_id"], f"{pfx}conj[{prot}].protein_lot_id", rtag=rtag, fail_reasons=fail_reasons)
            if "conjugation_yield_pct" not in prec or prec["conjugation_yield_pct"] is None:
                missing_fields.append(f"{pfx}per_protein_conjugation_records.{prot}.conjugation_yield_pct")
            else:
                cy = _require_bounded_float(prec["conjugation_yield_pct"], f"{pfx}conj[{prot}].conjugation_yield_pct", lo=0.0, hi=100.0)
                pp["conjugation_yield_pct"] = cy
                if cy < 60.0:
                    fail_reasons.append(f"{rtag}CONJUGATION_YIELD_FAIL:{prot}={cy}%")
                elif cy < 80.0:
                    hold_reasons.append(f"{rtag}CONJUGATION_YIELD_INTERMEDIATE:{prot}={cy}%")
            if "peg_kda" not in prec or prec["peg_kda"] is None:
                missing_fields.append(f"{pfx}per_protein_conjugation_records.{prot}.peg_kda")
            else:
                pkda = _require_bounded_float(prec["peg_kda"], f"{pfx}conj[{prot}].peg_kda", lo=0.0, hi=1e6, strict_lo=True)
                pp["peg_kda"] = pkda
                mode, bound = peg_rules[prot]
                if (mode == "max" and pkda > bound) or (mode == "min" and pkda < bound):
                    fail_reasons.append(f"{rtag}PEG_TIER_VIOLATION:{prot}={pkda}kDa")
            if "unpaired_ecd_cys" not in prec or prec["unpaired_ecd_cys"] is None:
                missing_fields.append(f"{pfx}per_protein_conjugation_records.{prot}.unpaired_ecd_cys")
            else:
                uc = _require_exact_int(prec["unpaired_ecd_cys"], f"{pfx}conj[{prot}].unpaired_ecd_cys", lo=0)
                pp["unpaired_ecd_cys"] = uc
                if uc > 0:
                    fail_reasons.append(f"{rtag}UNPAIRED_ECD_CYS_FAIL:{prot}={uc}")
            if "free_thiol_mol_per_mol" not in prec or prec["free_thiol_mol_per_mol"] is None:
                missing_fields.append(f"{pfx}per_protein_conjugation_records.{prot}.free_thiol_mol_per_mol")
            else:
                ftm = _require_bounded_float(prec["free_thiol_mol_per_mol"], f"{pfx}conj[{prot}].free_thiol_mol_per_mol", lo=0.0, hi=1e6)
                pp["free_thiol_mol_per_mol"] = ftm
                if ftm > 0.20:
                    fail_reasons.append(f"{rtag}FREE_THIOL_MOL_FAIL:{prot}={ftm}")
                elif ftm > 0.05:
                    hold_reasons.append(f"{rtag}FREE_THIOL_MOL_INTERMEDIATE:{prot}={ftm}")
            parsed_conj[prot] = pp

    has_ftu, ftu_raw = _opt("free_thiol_um")
    free_thiol_um = _require_bounded_float(ftu_raw, f"{pfx}free_thiol_um", lo=0.0, hi=1e6) if has_ftu else None

    # Co-immobilized CD200R accessibility alongside sCR1_v2
    has_cd200r, cd200r_raw = _opt("coimmobilized_cd200r_accessibility_verified")
    cd200r_acc = _require_exact_bool(cd200r_raw, f"{pfx}coimmobilized_cd200r_accessibility_verified") if has_cd200r else None
    if cd200r_acc is False:
        fail_reasons.append(f"{rtag}COIMMOBILIZED_CD200R_ACCESSIBILITY_FAILED")

    has_cd200b, cd200b_raw = _opt("coimmobilized_cd200r_binding_pct_of_unhindered")
    cd200r_bind = _require_bounded_float(cd200b_raw, f"{pfx}coimmobilized_cd200r_binding_pct_of_unhindered", lo=0.0, hi=200.0) if has_cd200b else None
    if cd200r_bind is not None:
        if cd200r_bind < 50.0:
            fail_reasons.append(f"{rtag}COIMMOBILIZED_CD200R_BINDING_FAIL:{cd200r_bind}%")
        elif cd200r_bind < 75.0:
            hold_reasons.append(f"{rtag}COIMMOBILIZED_CD200R_BINDING_INTERMEDIATE:{cd200r_bind}%")
    if "cd200r_binding_pct" in src and src["cd200r_binding_pct"] is not None:
        b_alias = _require_bounded_float(src["cd200r_binding_pct"], f"{pfx}cd200r_binding_pct", lo=0.0, hi=200.0)
        if b_alias < 50.0:
            fail_reasons.append(f"{rtag}CD200R_BINDING_ALIAS_FAIL:{b_alias}%")
        elif b_alias < 75.0:
            hold_reasons.append(f"{rtag}CD200R_BINDING_ALIAS_INTERMEDIATE:{b_alias}%")
        if cd200r_bind is not None and b_alias != cd200r_bind:
            fail_reasons.append(f"{rtag}CD200R_BINDING_ALIAS_MISMATCH:{b_alias}!={cd200r_bind}")

    has_fasl, fasl_raw = _opt("fasl_present")
    fasl_present = _require_exact_bool(fasl_raw, f"{pfx}fasl_present") if has_fasl else None
    if fasl_present is True:
        fail_reasons.append(f"{rtag}GY013_RETIRED_ADIPOQ_HEXA_FASL_PRESENT")

    has_fllod, fllod_raw = _opt("fasl_lcms_below_llod")
    fasl_below = _require_exact_bool(fllod_raw, f"{pfx}fasl_lcms_below_llod") if has_fllod else None
    if fasl_below is False:
        fail_reasons.append(f"{rtag}FASL_LCMS_DETECTED_ABOVE_LLOD")

    has_cfh, cfh_raw = _opt("retired_cfh_19_445_absent")
    cfh_absent = _require_exact_bool(cfh_raw, f"{pfx}retired_cfh_19_445_absent") if has_cfh else None
    if cfh_absent is False:
        fail_reasons.append(f"{rtag}RETIRED_CFH_19_445_PRESENT_IN_PRIMARY_CUFF")

    has_mono, mono_raw = _opt("monomer_pct")
    mono = _require_bounded_float(mono_raw, f"{pfx}monomer_pct", lo=0.0, hi=100.0) if has_mono else None
    if mono is not None:
        if mono < 90.0:
            fail_reasons.append(f"{rtag}CUFF_MONOMER_FAIL:{mono}%")
        elif mono < 95.0:
            hold_reasons.append(f"{rtag}CUFF_MONOMER_INTERMEDIATE:{mono}%")

    has_ret, ret_raw = _opt("retention_30d_pct")
    ret30 = _require_bounded_float(ret_raw, f"{pfx}retention_30d_pct", lo=0.0, hi=100.0) if has_ret else None
    if ret30 is not None:
        if ret30 < 85.0:
            fail_reasons.append(f"{rtag}RETENTION_30D_FAIL:{ret30}%")
        elif ret30 < 95.0:
            hold_reasons.append(f"{rtag}RETENTION_30D_INTERMEDIATE:{ret30}%")

    has_lch, lch_raw = _opt("leaching_30d_serum_pct")
    lch = _require_bounded_float(lch_raw, f"{pfx}leaching_30d_serum_pct", lo=0.0, hi=100.0) if has_lch else None
    if lch is not None:
        if lch > 5.0:
            fail_reasons.append(f"{rtag}LEACHING_30D_FAIL:{lch}%")
        elif lch > 2.0:
            hold_reasons.append(f"{rtag}LEACHING_30D_INTERMEDIATE:{lch}%")

    # Paired intact-serum vs IgG-attributable CD16+ ADCC U95 (GY-023)
    has_pctrl, pctrl_raw = _opt("paired_igg_depleted_control_included")
    pctrl = _require_exact_bool(pctrl_raw, f"{pfx}paired_igg_depleted_control_included") if has_pctrl else None
    if pctrl is False:
        fail_reasons.append(f"{rtag}GY023_PAIRED_IGG_DEPLETED_CONTROL_MISSING")

    has_adn, adn_raw = _opt("adcc_donor_n")
    adn = _require_exact_int(adn_raw, f"{pfx}adcc_donor_n", lo=0) if has_adn else None
    if adn is not None:
        if adn == 0:
            fail_reasons.append(f"{rtag}GY023_ZERO_ADCC_DONORS")
        elif adn < 6:
            hold_reasons.append(f"{rtag}GY023_INSUFFICIENT_ADCC_DONORS:{adn}<6")
    _validate_optional_canonical_id_list(
        src,
        keys=("adcc_donor_ids", "donor_ids"),
        expected_count=adn,
        min_unique=6,
        pfx=pfx,
        rtag=rtag,
        module_tag="CUFF",
        fail_reasons=fail_reasons,
    )

    has_intact, intact_raw = _opt("intact_serum_total_killing_u95_pct")
    intact_u95 = _require_bounded_float(intact_raw, f"{pfx}intact_serum_total_killing_u95_pct", lo=0.0, hi=100.0) if has_intact else None
    if intact_u95 is not None:
        if intact_u95 > 15.0:
            fail_reasons.append(f"{rtag}GY023_INTACT_SERUM_KILLING_U95_FAIL:{intact_u95}%")
        elif intact_u95 > 5.0:
            hold_reasons.append(f"{rtag}GY023_INTACT_SERUM_KILLING_U95_INTERMEDIATE:{intact_u95}%")
    if "serum_killing_u95_pct" in src and src["serum_killing_u95_pct"] is not None:
        sk_alias = _require_bounded_float(src["serum_killing_u95_pct"], f"{pfx}serum_killing_u95_pct", lo=0.0, hi=100.0)
        if sk_alias > 15.0:
            fail_reasons.append(f"{rtag}SERUM_KILLING_ALIAS_U95_FAIL:{sk_alias}%")
        elif sk_alias > 5.0:
            hold_reasons.append(f"{rtag}SERUM_KILLING_ALIAS_U95_INTERMEDIATE:{sk_alias}%")
        if intact_u95 is not None and sk_alias != intact_u95:
            fail_reasons.append(f"{rtag}SERUM_KILLING_ALIAS_MISMATCH:{sk_alias}!={intact_u95}")

    has_padcc, padcc_raw = _opt("paired_igg_attributable_cd16_adcc_u95_pct")
    paired_u95 = _require_bounded_float(padcc_raw, f"{pfx}paired_igg_attributable_cd16_adcc_u95_pct", lo=0.0, hi=100.0) if has_padcc else None
    if paired_u95 is not None:
        if paired_u95 > 15.0:
            fail_reasons.append(f"{rtag}GY023_PAIRED_IGG_CD16_ADCC_U95_FAIL:{paired_u95}%")
        elif paired_u95 > 5.0:
            hold_reasons.append(f"{rtag}GY023_PAIRED_IGG_CD16_ADCC_U95_INTERMEDIATE:{paired_u95}%")
    if "cd16_adcc_u95_pct" in src and src["cd16_adcc_u95_pct"] is not None:
        adcc_alias = _require_bounded_float(src["cd16_adcc_u95_pct"], f"{pfx}cd16_adcc_u95_pct", lo=0.0, hi=100.0)
        if adcc_alias > 15.0:
            fail_reasons.append(f"{rtag}CD16_ADCC_ALIAS_U95_FAIL:{adcc_alias}%")
        elif adcc_alias > 5.0:
            hold_reasons.append(f"{rtag}CD16_ADCC_ALIAS_U95_INTERMEDIATE:{adcc_alias}%")
        if paired_u95 is not None and adcc_alias != paired_u95:
            fail_reasons.append(f"{rtag}CD16_ADCC_ALIAS_MISMATCH:{adcc_alias}!={paired_u95}")

    # Pathway-specific GY-025 classical, lectin, alternative, and overall 20% NHS complement bounds
    c4_vals: dict[str, float | None] = {}
    for cpfx, tag in (("classical_c4b2a_residual", "GY025_CLASSICAL_C4B2A"), ("lectin_c4b2a_residual", "GY025_LECTIN_C4B2A")):
        has_l, l_raw = _opt(f"{cpfx}_l95_pct")
        has_u, u_raw = _opt(f"{cpfx}_u95_pct")
        lv = _require_bounded_float(l_raw, f"{pfx}{cpfx}_l95_pct", lo=0.0, hi=100.0) if has_l else None
        uv = _require_bounded_float(u_raw, f"{pfx}{cpfx}_u95_pct", lo=0.0, hi=100.0) if has_u else None
        c4_vals[f"{cpfx}_l95_pct"] = lv
        c4_vals[f"{cpfx}_u95_pct"] = uv
        if lv is not None and uv is not None and lv > uv:
            fail_reasons.append(f"{rtag}{tag}_INTERVAL_INVERTED:{lv}>{uv}")
        if lv is not None and lv > 10.0:
            fail_reasons.append(f"{rtag}{tag}_L95_EXCEEDS_10_FAIL:{lv}%")
        elif uv is not None and uv > 10.0:
            hold_reasons.append(f"{rtag}{tag}_U95_EXCEEDS_10_HOLD:{uv}%")
    if "classical_c4b2a_l95_pct" in src and src["classical_c4b2a_l95_pct"] is not None:
        c4_alias = _require_bounded_float(src["classical_c4b2a_l95_pct"], f"{pfx}classical_c4b2a_l95_pct", lo=0.0, hi=100.0)
        if c4_alias > 10.0:
            fail_reasons.append(f"{rtag}CLASSICAL_C4B2A_L95_ALIAS_FAIL:{c4_alias}%")
        if c4_vals["classical_c4b2a_residual_l95_pct"] is not None and c4_alias != c4_vals["classical_c4b2a_residual_l95_pct"]:
            fail_reasons.append(f"{rtag}CLASSICAL_C4B2A_L95_ALIAS_MISMATCH:{c4_alias}!={c4_vals['classical_c4b2a_residual_l95_pct']}")

    c5_vals: dict[str, float | None] = {}
    for key, tag in (
        ("alternative_c5b9_residual_u95_pct", "GY025_ALTERNATIVE_C5B9"),
        ("overall_20pct_nhs_c5b9_residual_u95_pct", "GY025_OVERALL_20PCT_NHS_C5B9"),
    ):
        has_k, k_raw = _opt(key)
        val = _require_bounded_float(k_raw, f"{pfx}{key}", lo=0.0, hi=100.0) if has_k else None
        c5_vals[key] = val
        if val is not None:
            if val > 15.0:
                fail_reasons.append(f"{rtag}{tag}_U95_FAIL:{val}%")
            elif val > 5.0:
                hold_reasons.append(f"{rtag}{tag}_U95_INTERMEDIATE:{val}%")

    drop_vals: dict[str, float | None] = {}
    for key, tag in (
        ("classical_c4d_c5b9_drop_pct", "CLASSICAL_COMPLEMENT"),
        ("lectin_c4d_c5b9_drop_pct", "LECTIN_COMPLEMENT"),
        ("alternative_c3b_c5b9_drop_pct", "ALTERNATIVE_COMPLEMENT"),
    ):
        has_k, k_raw = _opt(key)
        val = _require_bounded_float(k_raw, f"{pfx}{key}", lo=0.0, hi=100.0) if has_k else None
        drop_vals[key] = val
        if val is not None:
            if val < 70.0:
                fail_reasons.append(f"{rtag}{tag}_BLOCKADE_FAIL:{val}%")
            elif val < 90.0:
                hold_reasons.append(f"{rtag}{tag}_BLOCKADE_INTERMEDIATE:{val}%")

    # Governing GY-025 exact-stack efferocytosis & Gate 0G pericyte recruitment endpoints (EXACT cutoffs, ZERO tolerance!)
    has_eff_abs, eff_abs_raw = _opt("exact_stack_efferocytosis_abs_pct")
    eff_abs = _require_bounded_float(eff_abs_raw, f"{pfx}exact_stack_efferocytosis_abs_pct", lo=0.0, hi=100.0) if has_eff_abs else None
    if eff_abs is not None and eff_abs < 80.0:
        fail_reasons.append(f"{rtag}GY025_EXACT_STACK_EFFEROCYTOSIS_ABS_FAIL:{eff_abs!r}%<80.0%")

    has_eff_wt, eff_wt_raw = _opt("exact_stack_efferocytosis_pct_of_wt")
    eff_wt = _require_bounded_float(eff_wt_raw, f"{pfx}exact_stack_efferocytosis_pct_of_wt", lo=0.0, hi=200.0) if has_eff_wt else None
    if eff_wt is not None and eff_wt < 70.0:
        fail_reasons.append(f"{rtag}GY025_EXACT_STACK_EFFEROCYTOSIS_WT_FAIL:{eff_wt!r}%<70.0%")

    has_peri_wt, peri_wt_raw = _opt("exact_stack_pericyte_recruitment_pct_of_wt")
    peri_wt = _require_bounded_float(peri_wt_raw, f"{pfx}exact_stack_pericyte_recruitment_pct_of_wt", lo=0.0, hi=200.0) if has_peri_wt else None
    if peri_wt is not None and peri_wt < 70.0:
        fail_reasons.append(f"{rtag}GY025_EXACT_STACK_PERICYTE_RECRUITMENT_WT_FAIL:{peri_wt!r}%<70.0%")

    # Vascular safety endpoints (GY-025 PLVAP+ iEC + THBD APC/aPTT + PMN lysis)
    has_t50, t50_raw = _opt("plvap_iec_morphogenesis_t50_h")
    t50 = _require_bounded_float(t50_raw, f"{pfx}plvap_iec_morphogenesis_t50_h", lo=0.0, hi=1e6, strict_lo=True) if has_t50 else None
    if t50 is not None:
        if t50 > 48.0:
            fail_reasons.append(f"{rtag}GY025_PLVAP_IEC_MORPHOGENESIS_T50_FAIL:{t50}h")
        elif t50 > 36.0:
            hold_reasons.append(f"{rtag}GY025_PLVAP_IEC_MORPHOGENESIS_T50_HOLD:{t50}h")

    has_viab, viab_raw = _opt("plvap_iec_viability_pct")
    viab = _require_bounded_float(viab_raw, f"{pfx}plvap_iec_viability_pct", lo=0.0, hi=100.0) if has_viab else None
    if viab is not None:
        if viab < 70.0:
            fail_reasons.append(f"{rtag}GY025_PLVAP_IEC_VIABILITY_FAIL:{viab}%")
        elif viab < 85.0:
            hold_reasons.append(f"{rtag}GY025_PLVAP_IEC_VIABILITY_HOLD:{viab}%")

    has_thbd, thbd_raw = _opt("thbd_h2o2_apc_retention_pct")
    apc_ret = _require_bounded_float(thbd_raw, f"{pfx}thbd_h2o2_apc_retention_pct", lo=0.0, hi=100.0) if has_thbd else None
    if apc_ret is not None:
        if apc_ret < 70.0:
            fail_reasons.append(f"{rtag}THBD_APC_RETENTION_FAIL:{apc_ret}%")
        elif apc_ret < 85.0:
            hold_reasons.append(f"{rtag}THBD_APC_RETENTION_INTERMEDIATE:{apc_ret}%")

    has_aptt, aptt_raw = _opt("bulk_aptt_ratio")
    aptt = _require_bounded_float(aptt_raw, f"{pfx}bulk_aptt_ratio", lo=0.0, hi=100.0, strict_lo=True) if has_aptt else None
    if aptt is not None:
        if aptt > 1.30:
            fail_reasons.append(f"{rtag}BULK_APTT_SAFETY_FAIL:{aptt}x")
        elif aptt > 1.15:
            hold_reasons.append(f"{rtag}BULK_APTT_INTERMEDIATE:{aptt}x")

    has_pmn, pmn_raw = _opt("pmn_residual_lysis_pct")
    pmn = _require_bounded_float(pmn_raw, f"{pfx}pmn_residual_lysis_pct", lo=0.0, hi=100.0) if has_pmn else None
    if pmn is not None:
        if pmn > 15.0:
            fail_reasons.append(f"{rtag}PMN_LYSIS_FAIL:{pmn}%")
        elif pmn > 5.0:
            hold_reasons.append(f"{rtag}PMN_LYSIS_INTERMEDIATE:{pmn}%")

    return {
        "core_cuff_proteins": parsed_core,
        "parsed_conj": parsed_conj,
        "scalars": {
            "study_id": study_id,
            "free_thiol_um": free_thiol_um,
            "coimmobilized_cd200r_accessibility_verified": cd200r_acc,
            "coimmobilized_cd200r_binding_pct_of_unhindered": cd200r_bind,
            "fasl_present": fasl_present,
            "fasl_lcms_below_llod": fasl_below,
            "retired_cfh_19_445_absent": cfh_absent,
            "monomer_pct": mono,
            "retention_30d_pct": ret30,
            "leaching_30d_serum_pct": lch,
            "paired_igg_depleted_control_included": pctrl,
            "adcc_donor_n": adn,
            "intact_serum_total_killing_u95_pct": intact_u95,
            "paired_igg_attributable_cd16_adcc_u95_pct": paired_u95,
            **c4_vals,
            **c5_vals,
            **drop_vals,
            "exact_stack_efferocytosis_abs_pct": eff_abs,
            "exact_stack_efferocytosis_pct_of_wt": eff_wt,
            "exact_stack_pericyte_recruitment_pct_of_wt": peri_wt,
            "plvap_iec_morphogenesis_t50_h": t50,
            "plvap_iec_viability_pct": viab,
            "thbd_h2o2_apc_retention_pct": apc_ret,
            "bulk_aptt_ratio": aptt,
            "pmn_residual_lysis_pct": pmn,
        },
    }


def evaluate_gate34_cuff_v2(
    obs: dict[str, Any],
    arm_manifest: dict[str, Any] | None = None,
    *,
    trusted_evidence_store: dict[str, dict[str, Any]] | None = None,
) -> dict[str, Any]:
    """Fail-closed Gate 34-CUFF-V2 evaluator (Round-5: ALL governing endpoints derived directly from verified current_assay_evidence_record, ZERO threshold tolerance)."""
    try:
        if not isinstance(obs, dict):
            raise ValueError("obs must be dict")
        check_strictly_finite(obs, "gate34_cuff_v2_obs")

        fail_reasons: list[str] = []
        missing_fields: list[str] = []
        hold_reasons: list[str] = []

        verified_manifest = _verify_manifest_context(arm_manifest, obs, fail_reasons, missing_fields)
        _, arm_entry = _check_arm_and_design_a_invariants(obs, "cuff_v2_eligible", verified_manifest, fail_reasons, missing_fields)

        obs_eval = _evaluate_cuff_measurements(
            obs, is_archive=False, fail_reasons=fail_reasons, missing_fields=missing_fields, hold_reasons=hold_reasons
        )

        cur_raw = obs.get("current_assay_evidence_record") if "current_assay_evidence_record" in obs else None
        if cur_raw is not None and not isinstance(cur_raw, dict):
            raise ValueError("current_assay_evidence_record must be dict")

        if isinstance(cur_raw, dict):
            cur_eval = _evaluate_cuff_measurements(
                cur_raw, is_archive=True, fail_reasons=fail_reasons, missing_fields=missing_fields, hold_reasons=hold_reasons
            )
            if obs_eval["core_cuff_proteins"] is not None and cur_eval["core_cuff_proteins"] is not None:
                if set(cur_eval["core_cuff_proteins"]) != set(obs_eval["core_cuff_proteins"]) or len(cur_eval["core_cuff_proteins"]) != len(obs_eval["core_cuff_proteins"]):
                    fail_reasons.append(
                        f"CUFF_ASSAY_BINDING_MISMATCH:core_cuff_proteins:{cur_eval['core_cuff_proteins']}!={obs_eval['core_cuff_proteins']}"
                    )
            for prot in ("sCR1_v2", "THBD-M406L", "CD200-ECD"):
                op = obs_eval["parsed_conj"].get(prot)
                cp = cur_eval["parsed_conj"].get(prot)
                if op is not None and cp is not None:
                    for subk, ov in op.items():
                        if subk in cp and cp[subk] != ov:
                            fail_reasons.append(f"CUFF_ASSAY_BINDING_MISMATCH:conj.{prot}.{subk}:{cp[subk]!r}!={ov!r}")
            # Enforce EXACT equality (ZERO numeric tolerance!) across ALL 31 scalar Cuff governing fields!
            for fld, obs_v in obs_eval["scalars"].items():
                cur_v = cur_eval["scalars"].get(fld)
                if obs_v is not None and cur_v is not None:
                    if type(obs_v) is bool or type(cur_v) is bool:
                        if obs_v is not cur_v:
                            fail_reasons.append(f"CUFF_ASSAY_BINDING_MISMATCH:{fld}:{cur_v}!={obs_v}")
                    elif cur_v != obs_v:
                        fail_reasons.append(f"CUFF_ASSAY_BINDING_MISMATCH:{fld}:{cur_v!r}!={obs_v!r}")

        return _verify_upstream_evidence_and_finalize(
            obs,
            CANONICAL_GATE34_MODULE_SOURCES["cuff"],
            None,
            arm_entry,
            trusted_evidence_store,
            fail_reasons,
            missing_fields,
            hold_reasons,
            verified_manifest=verified_manifest,
        )
    except ValueError as exc:
        return _malformed_rejection(exc)


def _evaluate_invvax_measurements(
    src: dict[str, Any],
    *,
    is_archive: bool,
    fail_reasons: list[str],
    missing_fields: list[str],
    hold_reasons: list[str],
) -> dict[str, Any]:
    """Validate and enforce ALL governing InvVax measurements & cutoffs directly on `src` (ZERO threshold tolerance)."""
    pfx = "current_assay_evidence_record." if is_archive else ""
    rtag = "ARCHIVE_" if is_archive else ""

    def _opt(key: str) -> tuple[bool, Any]:
        if key not in src or src[key] is None:
            missing_fields.append(f"{pfx}{key}")
            return False, None
        return True, src[key]

    has_study, study_raw = _opt("study_id")
    study_id = _require_canonical_ascii_id(study_raw, f"{pfx}study_id", rtag=rtag, fail_reasons=fail_reasons) if has_study else None

    # Registered 3-administration pre-transplant schedule
    has_days, days_raw = _opt("administration_days")
    admin_days: list[int] | None = None
    if has_days:
        if not isinstance(days_raw, (list, tuple)) or len(days_raw) == 0:
            raise ValueError(f"{pfx}administration_days must be non-empty list of ints")
        admin_days = [_require_exact_int(d, f"{pfx}administration_days[]", lo=-365, hi=365) for d in days_raw]
        if len(admin_days) != 3:
            fail_reasons.append(f"{rtag}INVVAX_REQUIRES_EXACTLY_3_ADMINISTRATIONS_FAIL:count={len(admin_days)}:{admin_days}")
        if any(admin_days[i] >= admin_days[i + 1] for i in range(len(admin_days) - 1)):
            fail_reasons.append(f"{rtag}ADMINISTRATION_DAYS_NOT_STRICTLY_ASCENDING:{admin_days}")
        if any(d > -7 for d in admin_days):
            fail_reasons.append(f"{rtag}ADMINISTRATION_DAY_VIOLATES_PRE_TRANSPLANT_WINDOW:{admin_days}")

    has_last, last_raw = _opt("last_dose_day")
    last_dose_day = _require_exact_int(last_raw, f"{pfx}last_dose_day", lo=-365, hi=365) if has_last else None
    if last_dose_day is not None:
        if last_dose_day > -7:
            fail_reasons.append(f"{rtag}LAST_DOSE_DAY_POST_TRANSPLANT_OR_LATE_FAIL:day={last_dose_day}>-7")
        if admin_days is not None and last_dose_day != max(admin_days):
            fail_reasons.append(f"{rtag}LAST_DOSE_DAY_INCONSISTENT_WITH_SCHEDULE:{last_dose_day}!={max(admin_days)}")

    has_cday, cday_raw = _opt("clearance_sample_day")
    clearance_sample_day = _require_exact_int(cday_raw, f"{pfx}clearance_sample_day", lo=-365, hi=365) if has_cday else None
    if clearance_sample_day is not None:
        if clearance_sample_day > -4:
            fail_reasons.append(f"{rtag}CLEARANCE_SAMPLE_DAY_AFTER_DAY_MINUS4_FAIL:day={clearance_sample_day}>-4")
        if last_dose_day is not None and clearance_sample_day <= last_dose_day:
            fail_reasons.append(f"{rtag}CLEARANCE_SAMPLE_NOT_AFTER_LAST_DOSE_FAIL:sample={clearance_sample_day}<=dose={last_dose_day}")

    # Distinct matrix-specific governed validated assay registries
    has_paid, paid_raw = _opt("plasma_assay_id")
    plasma_assay_id = _require_canonical_ascii_id(paid_raw, f"{pfx}plasma_assay_id", rtag=rtag, fail_reasons=fail_reasons) if has_paid else None
    if plasma_assay_id is not None and plasma_assay_id not in GOVERNED_INVVAX_PLASMA_ASSAY_REGISTRY:
        fail_reasons.append(f"{rtag}UNREGISTERED_INVVAX_PLASMA_ASSAY_ID:{plasma_assay_id}")

    has_lnaid, lnaid_raw = _opt("lymph_node_assay_id")
    lymph_node_assay_id = _require_canonical_ascii_id(lnaid_raw, f"{pfx}lymph_node_assay_id", rtag=rtag, fail_reasons=fail_reasons) if has_lnaid else None
    if lymph_node_assay_id is not None and lymph_node_assay_id not in GOVERNED_INVVAX_LYMPH_NODE_ASSAY_REGISTRY:
        fail_reasons.append(f"{rtag}UNREGISTERED_INVVAX_LYMPH_NODE_ASSAY_ID:{lymph_node_assay_id}")

    if plasma_assay_id is not None and lymph_node_assay_id is not None and plasma_assay_id == lymph_node_assay_id:
        fail_reasons.append(f"{rtag}INVVAX_DUPLICATE_MATRIX_ASSAY_ID_FAIL:{plasma_assay_id}")

    _validate_optional_canonical_id_list(
        src,
        keys=("subject_ids", "donor_ids"),
        expected_count=None,
        min_unique=None,
        pfx=pfx,
        rtag=rtag,
        module_tag="INVVAX",
        fail_reasons=fail_reasons,
    )

    # Qualified assay LLOD ceilings (<= 1.0) + STRICT quantitative measurements < LLOD (ZERO tolerance!)
    has_pllod, pllod_raw = _opt("plasma_llod_ng_ml")
    plasma_llod = _require_bounded_float(pllod_raw, f"{pfx}plasma_llod_ng_ml", lo=0.0, hi=1e12, strict_lo=True) if has_pllod else None
    if plasma_llod is not None and plasma_llod > 1.0:
        fail_reasons.append(f"{rtag}PLASMA_ASSAY_LLOD_UNQUALIFIED_ABOVE_1_NG_ML:{plasma_llod}")

    has_tllod, tllod_raw = _opt("tissue_llod_ng_g")
    tissue_llod = _require_bounded_float(tllod_raw, f"{pfx}tissue_llod_ng_g", lo=0.0, hi=1e12, strict_lo=True) if has_tllod else None
    if tissue_llod is not None and tissue_llod > 1.0:
        fail_reasons.append(f"{rtag}TISSUE_ASSAY_LLOD_UNQUALIFIED_ABOVE_1_NG_G:{tissue_llod}")
    if "lymph_node_llod_ng_ml" in src and src["lymph_node_llod_ng_ml"] is not None:
        ln_llod_alias = _require_bounded_float(src["lymph_node_llod_ng_ml"], f"{pfx}lymph_node_llod_ng_ml", lo=0.0, hi=1e12, strict_lo=True)
        if ln_llod_alias > 1.0:
            fail_reasons.append(f"{rtag}LYMPH_NODE_LLOD_ALIAS_ABOVE_1_FAIL:{ln_llod_alias}")
        if tissue_llod is not None and ln_llod_alias != tissue_llod:
            fail_reasons.append(f"{rtag}LYMPH_NODE_LLOD_ALIAS_MISMATCH:{ln_llod_alias}!={tissue_llod}")

    has_pconc, pconc_raw = _opt("measured_plasma_conc_ng_ml")
    plasma_conc = _require_bounded_float(pconc_raw, f"{pfx}measured_plasma_conc_ng_ml", lo=0.0, hi=1e12) if has_pconc else None
    if plasma_conc is not None and plasma_llod is not None and plasma_conc >= plasma_llod:
        fail_reasons.append(f"{rtag}PLASMA_CLEARANCE_NOT_BELOW_LLOD:{plasma_conc!r}>={plasma_llod!r}")
    if "plasma_conc_day0_ng_ml" in src and src["plasma_conc_day0_ng_ml"] is not None:
        pc_alias = _require_bounded_float(src["plasma_conc_day0_ng_ml"], f"{pfx}plasma_conc_day0_ng_ml", lo=0.0, hi=1e12)
        if plasma_llod is not None and pc_alias >= plasma_llod:
            fail_reasons.append(f"{rtag}PLASMA_CONC_DAY0_ALIAS_NOT_BELOW_LLOD:{pc_alias!r}>={plasma_llod!r}")
        if plasma_conc is not None and pc_alias != plasma_conc:
            fail_reasons.append(f"{rtag}PLASMA_CONC_DAY0_ALIAS_MISMATCH:{pc_alias!r}!={plasma_conc!r}")

    has_tconc, tconc_raw = _opt("measured_tissue_conc_ng_g")
    tissue_conc = _require_bounded_float(tconc_raw, f"{pfx}measured_tissue_conc_ng_g", lo=0.0, hi=1e12) if has_tconc else None
    if tissue_conc is not None and tissue_llod is not None and tissue_conc >= tissue_llod:
        fail_reasons.append(f"{rtag}TISSUE_CLEARANCE_NOT_BELOW_LLOD:{tissue_conc!r}>={tissue_llod!r}")
    if "lymph_node_conc_day0_ng_ml" in src and src["lymph_node_conc_day0_ng_ml"] is not None:
        tc_alias = _require_bounded_float(src["lymph_node_conc_day0_ng_ml"], f"{pfx}lymph_node_conc_day0_ng_ml", lo=0.0, hi=1e12)
        if tissue_llod is not None and tc_alias >= tissue_llod:
            fail_reasons.append(f"{rtag}LYMPH_NODE_CONC_DAY0_ALIAS_NOT_BELOW_LLOD:{tc_alias!r}>={tissue_llod!r}")
        if tissue_conc is not None and tc_alias != tissue_conc:
            fail_reasons.append(f"{rtag}LYMPH_NODE_CONC_DAY0_ALIAS_MISMATCH:{tc_alias!r}!={tissue_conc!r}")

    has_ae, ae_raw = _opt("max_ae_grade")
    ae = _require_exact_int(ae_raw, f"{pfx}max_ae_grade", lo=0, hi=5) if has_ae else None
    if ae is not None:
        if ae >= 2:
            fail_reasons.append(f"{rtag}ADVERSE_EVENT_GRADE_FAIL:{ae}")
        elif ae == 1:
            hold_reasons.append(f"{rtag}ADVERSE_EVENT_GRADE_1_HOLD:{ae}")

    has_d90, d90_raw = _opt("day90_cpeptide_retention_pct")
    d90 = _require_bounded_float(d90_raw, f"{pfx}day90_cpeptide_retention_pct", lo=0.0, hi=200.0) if has_d90 else None
    if d90 is not None:
        if d90 < 60.0:
            fail_reasons.append(f"{rtag}DAY90_CPEPTIDE_FAIL:{d90}%")
        elif d90 < 80.0:
            hold_reasons.append(f"{rtag}DAY90_CPEPTIDE_INTERMEDIATE:{d90}%")

    has_lym, lym_raw = _opt("lymphocyte_count_pct_of_baseline")
    lym = _require_bounded_float(lym_raw, f"{pfx}lymphocyte_count_pct_of_baseline", lo=0.0, hi=200.0) if has_lym else None
    if lym is not None:
        if lym < 80.0:
            fail_reasons.append(f"{rtag}LYMPHOPENIA_FAIL:{lym}%")
        elif lym < 90.0:
            hold_reasons.append(f"{rtag}LYMPHOPENIA_INTERMEDIATE:{lym}%")

    has_treg, treg_raw = _opt("treg_tr1_fold_expansion")
    treg = _require_bounded_float(treg_raw, f"{pfx}treg_tr1_fold_expansion", lo=0.0, hi=1e6) if has_treg else None
    if treg is not None:
        if treg < 1.2:
            fail_reasons.append(f"{rtag}TREG_TR1_EXPANSION_FAIL:{treg}x")
        elif treg < 2.0:
            hold_reasons.append(f"{rtag}TREG_TR1_EXPANSION_INTERMEDIATE:{treg}x")

    has_brd, brd_raw = _opt("islet_antigens_suppressed_count")
    brd = _require_exact_int(brd_raw, f"{pfx}islet_antigens_suppressed_count", lo=0, hi=10) if has_brd else None
    if brd is not None:
        if brd < 2:
            fail_reasons.append(f"{rtag}ANTIGEN_BREADTH_FAIL:{brd}<2")
        elif brd < 3:
            hold_reasons.append(f"{rtag}ANTIGEN_BREADTH_INTERMEDIATE:{brd}<3")

    has_idrop, idrop_raw = _opt("islet_ag_elispot_drop_pct")
    idrop = _require_bounded_float(idrop_raw, f"{pfx}islet_ag_elispot_drop_pct", lo=0.0, hi=100.0) if has_idrop else None
    if idrop is not None:
        if idrop < 50.0:
            fail_reasons.append(f"{rtag}ISLET_AG_SUPPRESSION_FAIL:{idrop}%")
        elif idrop < 80.0:
            hold_reasons.append(f"{rtag}ISLET_AG_SUPPRESSION_INTERMEDIATE:{idrop}%")

    has_vr, vr_raw = _opt("viral_vaccine_recall_retention_pct")
    vr = _require_bounded_float(vr_raw, f"{pfx}viral_vaccine_recall_retention_pct", lo=0.0, hi=200.0) if has_vr else None
    if vr is not None:
        if vr < 75.0:
            fail_reasons.append(f"{rtag}ZERO_IS_VIOLATION_VIRAL_RECALL_SUPPRESSED:{vr}%")
        elif vr < 85.0:
            hold_reasons.append(f"{rtag}VIRAL_RECALL_INTERMEDIATE:{vr}%")

    return {
        "fields": {
            "study_id": study_id,
            "administration_days": admin_days,
            "last_dose_day": last_dose_day,
            "clearance_sample_day": clearance_sample_day,
            "plasma_assay_id": plasma_assay_id,
            "lymph_node_assay_id": lymph_node_assay_id,
            "plasma_llod_ng_ml": plasma_llod,
            "tissue_llod_ng_g": tissue_llod,
            "measured_plasma_conc_ng_ml": plasma_conc,
            "measured_tissue_conc_ng_g": tissue_conc,
            "max_ae_grade": ae,
            "day90_cpeptide_retention_pct": d90,
            "lymphocyte_count_pct_of_baseline": lym,
            "treg_tr1_fold_expansion": treg,
            "islet_antigens_suppressed_count": brd,
            "islet_ag_elispot_drop_pct": idrop,
            "viral_vaccine_recall_retention_pct": vr,
        }
    }


def evaluate_gate34_invvax_recall(
    obs: dict[str, Any],
    arm_manifest: dict[str, Any] | None = None,
    *,
    trusted_evidence_store: dict[str, dict[str, Any]] | None = None,
) -> dict[str, Any]:
    """Fail-closed Gate 34-INVVAX-RECALL evaluator (Round-5: ALL governing endpoints derived directly from verified current_assay_evidence_record, ZERO threshold tolerance)."""
    try:
        if not isinstance(obs, dict):
            raise ValueError("obs must be dict")
        check_strictly_finite(obs, "gate34_invvax_obs")

        fail_reasons: list[str] = []
        missing_fields: list[str] = []
        hold_reasons: list[str] = []

        verified_manifest = _verify_manifest_context(arm_manifest, obs, fail_reasons, missing_fields)
        _, arm_entry = _check_arm_and_design_a_invariants(obs, "invvax_eligible", verified_manifest, fail_reasons, missing_fields)

        obs_eval = _evaluate_invvax_measurements(
            obs, is_archive=False, fail_reasons=fail_reasons, missing_fields=missing_fields, hold_reasons=hold_reasons
        )

        cur_raw = obs.get("current_assay_evidence_record") if "current_assay_evidence_record" in obs else None
        if cur_raw is not None and not isinstance(cur_raw, dict):
            raise ValueError("current_assay_evidence_record must be dict")

        if isinstance(cur_raw, dict):
            cur_eval = _evaluate_invvax_measurements(
                cur_raw, is_archive=True, fail_reasons=fail_reasons, missing_fields=missing_fields, hold_reasons=hold_reasons
            )
            # Enforce EXACT equality (ZERO numeric tolerance!) across ALL 17 governing InvVax fields!
            for fld, obs_v in obs_eval["fields"].items():
                cur_v = cur_eval["fields"].get(fld)
                if obs_v is not None and cur_v is not None:
                    if cur_v != obs_v:
                        fail_reasons.append(f"INVVAX_ASSAY_BINDING_MISMATCH:{fld}:{cur_v!r}!={obs_v!r}")

        return _verify_upstream_evidence_and_finalize(
            obs,
            CANONICAL_GATE34_MODULE_SOURCES["invvax"],
            None,
            arm_entry,
            trusted_evidence_store,
            fail_reasons,
            missing_fields,
            hold_reasons,
            verified_manifest=verified_manifest,
        )
    except ValueError as exc:
        return _malformed_rejection(exc)


def _make_evidence_record_v2(
    *,
    record_id: str,
    gate_source: str,
    product_id: str,
    lot_id: str,
    bank_id: str,
    bank_origin: str,
    construct_manifest_sha256: str,
    evidence_tier: str = "SYNTHETIC_FIXTURE",
    decision: str | None = None,
    authority_scope: str | None = None,
    bank_qualified: bool | None = None,
    promotion_authorized: bool | None = None,
    extra_fields: dict[str, Any] | None = None,
) -> dict[str, Any]:
    """Create and canonically seal a v2_round5_unified 14-field evidence record."""
    if evidence_tier == "AUTHENTICATED_ARCHIVED_WETLAB":
        dec = decision if decision is not None else "PASS"
        scope = authority_scope if authority_scope is not None else "CLINICAL_LOT_RELEASE"
        bq = True if bank_qualified is None else bank_qualified
        pa = True if promotion_authorized is None else promotion_authorized
    else:
        dec = decision if decision is not None else "SYNTHETIC_SELF_TEST_PASS"
        scope = authority_scope if authority_scope is not None else "SYNTHETIC_SELF_TEST"
        bq = False if bank_qualified is None else bank_qualified
        pa = False if promotion_authorized is None else promotion_authorized

    body: dict[str, Any] = {
        "record_id": record_id,
        "gate_source": gate_source,
        "product_id": product_id,
        "lot_id": lot_id,
        "bank_id": bank_id,
        "bank_origin": bank_origin,
        "canonical_arm_manifest_sha256": EXPECTED_ARM_MANIFEST_SHA256,
        "construct_manifest_sha256": construct_manifest_sha256,
        "evidence_tier": evidence_tier,
        "decision": dec,
        "authority_scope": scope,
        "bank_qualified": bq,
        "promotion_authorized": pa,
    }
    if extra_fields:
        for k, v in extra_fields.items():
            require_cond(k != "archive_sha256", "extra_fields cannot override archive_sha256")
            body[k] = copy.deepcopy(v)
    return seal_evidence_record(body)


def _make_upstream_evidence_record(
    *,
    record_id: str,
    gate_source: str,
    product_id: str,
    lot_id: str,
    bank_id: str,
    bank_origin: str,
    construct_manifest_sha256: str | None = None,
    evidence_tier: str = "SYNTHETIC_FIXTURE",
    decision: str | None = None,
    authority_scope: str | None = None,
    bank_qualified: bool | None = None,
    promotion_authorized: bool | None = None,
) -> dict[str, Any]:
    csha = construct_manifest_sha256 or sha256_str(f"lot_construct_manifest|{product_id}|{lot_id}|v0.9.0")
    return _make_evidence_record_v2(
        record_id=record_id,
        gate_source=gate_source,
        product_id=product_id,
        lot_id=lot_id,
        bank_id=bank_id,
        bank_origin=bank_origin,
        construct_manifest_sha256=csha,
        evidence_tier=evidence_tier,
        decision=decision,
        authority_scope=authority_scope,
        bank_qualified=bank_qualified,
        promotion_authorized=promotion_authorized,
    )


def _canonical_synthetic_gate34_fixtures() -> dict[str, dict[str, Any]]:
    """Synthetic self-test fixtures ONLY (evidence_tier='SYNTHETIC_FIXTURE'; NEVER authorizes clinical promotion)."""
    sh_csha = sha256_str("lot_construct_manifest|ISLET1_DESIGN_B_V090|SYNTH_SHIELD_LOT_001|v0.9.0")
    ins_csha = sha256_str("lot_construct_manifest|ISLET1_DESIGN_Y_V3|SYNTH_INS_LOT_001|v0.9.0")
    cuff_csha = sha256_str("lot_construct_manifest|ISLET1_DESIGN_B_V090|SYNTH_CUFF_LOT_001|v0.9.0")
    iv_csha = sha256_str("lot_construct_manifest|ISLET1_DESIGN_D1B_LEAN_K2|SYNTH_INVVAX_LOT_001|v0.9.0")

    ins_elisa_kits = {
        "Roche Elecsys": {
            "kit_catalog_id": "ROCHE-03184897190",
            "kit_lot_id": "ROCHE_LOT_SYNTH_01",
            "low_conc_nmol_L": 0.05,
            "low_conc_recovery_pct": 96.2,
            "mid_conc_nmol_L": 1.00,
            "mid_conc_recovery_pct": 98.5,
            "diluted_high_conc_nmol_L": 5.00,
            "diluted_high_conc_recovery_pct": 99.1,
        },
        "Mercodia": {
            "kit_catalog_id": "MERCODIA-10-1136-01",
            "kit_lot_id": "MERCODIA_LOT_SYNTH_01",
            "low_conc_nmol_L": 0.05,
            "low_conc_recovery_pct": 97.4,
            "mid_conc_nmol_L": 1.00,
            "mid_conc_recovery_pct": 101.2,
            "diluted_high_conc_nmol_L": 5.00,
            "diluted_high_conc_recovery_pct": 102.0,
        },
        "Siemens": {
            "kit_catalog_id": "SIEMENS-ADVIA-03649928",
            "kit_lot_id": "SIEMENS_LOT_SYNTH_01",
            "low_conc_nmol_L": 0.05,
            "low_conc_recovery_pct": 94.8,
            "mid_conc_nmol_L": 1.00,
            "mid_conc_recovery_pct": 96.0,
            "diluted_high_conc_nmol_L": 5.00,
            "diluted_high_conc_recovery_pct": 97.5,
        },
    }
    ins_hla_panels = {
        "donor_issuer_id": DEFAULT_INS_CANONICAL_ISSUER_ID,
        "HLA-DRB1*04:01": {
            "peptide_tested": "GSLQPLAIEGSLQKRGIV",
            "binding_assay_verified": True,
            "mutant_binding_gain_fold": 1.05,
            "donor_ids": ["T1D_DON_001", "T1D_DON_002", "T1D_DON_003", "T1D_DON_004"],
            "donor_count": 4,
            "reactive_donor_ids": [],
            "reactive_donors": 0,
            "max_elispot_sfu": 8.0,
            "max_fold_vs_wt": 1.1,
        },
        "HLA-A*02:01": {
            "peptide_tested": "SLQPLAIEGSL",
            "binding_assay_verified": True,
            "mutant_binding_gain_fold": 1.02,
            "donor_ids": ["T1D_DON_005", "T1D_DON_006", "T1D_DON_007", "T1D_DON_008"],
            "donor_count": 4,
            "reactive_donor_ids": [],
            "reactive_donors": 0,
            "max_elispot_sfu": 5.0,
            "max_fold_vs_wt": 1.0,
        },
        "HLA-A*11:01": {
            "peptide_tested": "LAIEGSLQK",
            "binding_assay_verified": True,
            "mutant_binding_gain_fold": 1.08,
            "donor_ids": ["T1D_DON_009", "T1D_DON_010", "T1D_DON_011", "T1D_DON_012"],
            "donor_count": 4,
            "reactive_donor_ids": [],
            "reactive_donors": 0,
            "max_elispot_sfu": 6.0,
            "max_fold_vs_wt": 1.05,
        },
    }
    cuff_conj = {
        "sCR1_v2": {
            "protein_lot_id": "SCR1_SYNTH_LOT_01",
            "conjugation_yield_pct": 88.5,
            "peg_kda": 3.4,
            "unpaired_ecd_cys": 0,
            "free_thiol_mol_per_mol": 0.02,
        },
        "THBD-M406L": {
            "protein_lot_id": "THBD_SYNTH_LOT_01",
            "conjugation_yield_pct": 91.0,
            "peg_kda": 3.4,
            "unpaired_ecd_cys": 0,
            "free_thiol_mol_per_mol": 0.01,
        },
        "CD200-ECD": {
            "protein_lot_id": "CD200_SYNTH_LOT_01",
            "conjugation_yield_pct": 86.0,
            "peg_kda": 20.0,
            "unpaired_ecd_cys": 0,
            "free_thiol_mol_per_mol": 0.02,
        },
    }

    return {
        "shield": {
            "evidence_tier": "SYNTHETIC_FIXTURE",
            "target_arm_id": "B",
            "product_id": "ISLET1_DESIGN_B_V090",
            "lot_id": "SYNTH_SHIELD_LOT_001",
            "bank_id": "MCB_B_SYNTH_01",
            "bank_origin": "allogeneic_hiPSC",
            "manifest_sha256": EXPECTED_ARM_MANIFEST_SHA256,
            "construct_manifest_sha256": sh_csha,
            "design_a_exposed": False,
            "study_id": "SHIELD_PK_SEL_Q28D_SYNTH_001",
            "upstream_lot_evidence_record": _make_evidence_record_v2(
                record_id="REC_G34_SYNTH_SHIELD_001",
                gate_source=CANONICAL_UPSTREAM_GATE34_SOURCE,
                product_id="ISLET1_DESIGN_B_V090",
                lot_id="SYNTH_SHIELD_LOT_001",
                bank_id="MCB_B_SYNTH_01",
                bank_origin="allogeneic_hiPSC",
                construct_manifest_sha256=sh_csha,
            ),
            "live_gate32_debris_recall_record": _make_evidence_record_v2(
                record_id="REC_LIVE_G32_DEBRIS_SYNTH_SHIELD_001",
                gate_source=CANONICAL_LIVE_GATE32_DEBRIS_RECALL_SOURCE,
                product_id="ISLET1_DESIGN_B_V090",
                lot_id="SYNTH_SHIELD_LOT_001",
                bank_id="MCB_B_SYNTH_01",
                bank_origin="allogeneic_hiPSC",
                construct_manifest_sha256=sh_csha,
                extra_fields={
                    "debris_recall_verdict": "PASS_DEBRIS_RECALL_FULL_CREDIT",
                    "debris_recall_l95_suppressed_frac": 0.78,
                    "residual_class2_recall_u95_frac": 0.22,
                    "unrelated_recall_preserved": True,
                },
            ),
            "current_assay_evidence_record": _make_evidence_record_v2(
                record_id="REC_G36_SHIELD_SYNTH_001",
                gate_source=CANONICAL_GATE36_MODULE_SOURCES["shield"],
                product_id="ISLET1_DESIGN_B_V090",
                lot_id="SYNTH_SHIELD_LOT_001",
                bank_id="MCB_B_SYNTH_01",
                bank_origin="allogeneic_hiPSC",
                construct_manifest_sha256=sh_csha,
                extra_fields={
                    "study_id": "SHIELD_PK_SEL_Q28D_SYNTH_001",
                    "format_id": "FULLY_HUMAN_FAB_KIH_COMMON_LC_HIGG1_LALAPG_LS",
                    "dosing_regimen": "Q28D",
                    "timed_pk_day": 28,
                    "human_pk_qualified": True,
                    "periodic_pk_converged": True,
                    "gmp_lot_count": 3,
                    "donor_hla_dq_panel_n": 8,
                    "off_target_negative_states_tested": 7,
                    "on_target_kd_u95_nm": 1.0,
                    "off_target_kd_l95_um": 15.0,
                    "selectivity_ratio_l95": 15000.0,
                    "peak_free_nm": 611.3188,
                    "plasma_trough_free_nm": 431.1056,
                    "dln_trough_free_nm": 109.4573,
                    "reported_off_target_peak_ro_pct": 3.9159,
                    "fc_adcc_cdc_pct": 0.0,
                    "tcell_inhibition_l95_pct": 78.0,
                    "apc_cytotoxicity_u95_pct": 1.2,
                    "sec_mals_monomer_pct": 97.5,
                    "ce_sds_heterodimer_pct": 96.8,
                },
            ),
            "format_id": "FULLY_HUMAN_FAB_KIH_COMMON_LC_HIGG1_LALAPG_LS",
            "regimen_id": "Q28D",
            "timed_pk_day": 28,
            "measured_human_pk_verified": True,
            "periodic_pk_converged": True,
            "gmp_lot_count": 3,
            "donor_hla_dq_panel_n": 8,
            "off_target_negative_states_tested": 7,
            "on_target_kd_u95_nm": 1.0,
            "off_target_kd_l95_um": 15.0,
            "selectivity_ratio_l95": 15000.0,
            "peak_free_nm": 611.3188,
            "plasma_trough_free_nm": 431.1056,
            "dln_trough_free_nm": 109.4573,
            "reported_off_target_peak_ro_pct": 3.9159,
            "fc_adcc_cdc_pct": 0.0,
            "tcell_inhibition_l95_pct": 78.0,
            "apc_cytotoxicity_u95_pct": 1.2,
            "sec_mals_monomer_pct": 97.5,
            "ce_sds_heterodimer_pct": 96.8,
        },
        "ins": {
            "evidence_tier": "SYNTHETIC_FIXTURE",
            "target_arm_id": "Y",
            "product_id": "ISLET1_DESIGN_Y_V3",
            "lot_id": "SYNTH_INS_LOT_001",
            "bank_id": "MCB_Y_SYNTH_01",
            "bank_origin": "allogeneic_hiPSC",
            "manifest_sha256": EXPECTED_ARM_MANIFEST_SHA256,
            "construct_manifest_sha256": ins_csha,
            "design_a_exposed": False,
            "study_id": "INS_L82I_DAY1_HLA_PEPTIDOMICS_SYNTH_001",
            "upstream_lot_evidence_record": _make_evidence_record_v2(
                record_id="REC_G34_SYNTH_INS_001",
                gate_source=CANONICAL_UPSTREAM_GATE34_SOURCE,
                product_id="ISLET1_DESIGN_Y_V3",
                lot_id="SYNTH_INS_LOT_001",
                bank_id="MCB_Y_SYNTH_01",
                bank_origin="allogeneic_hiPSC",
                construct_manifest_sha256=ins_csha,
            ),
            "current_assay_evidence_record": _make_evidence_record_v2(
                record_id="REC_G36_INS_SYNTH_001",
                gate_source=CANONICAL_GATE36_MODULE_SOURCES["ins"],
                product_id="ISLET1_DESIGN_Y_V3",
                lot_id="SYNTH_INS_LOT_001",
                bank_id="MCB_Y_SYNTH_01",
                bank_origin="allogeneic_hiPSC",
                construct_manifest_sha256=ins_csha,
                extra_fields={
                    "study_id": "INS_L82I_DAY1_HLA_PEPTIDOMICS_SYNTH_001",
                    "editor_class": "PE2max",
                    "mlh1dn_used": False,
                    "day1_cpeptide_elisa_kit_records": copy.deepcopy(ins_elisa_kits),
                    "kit_catalog_ids": {
                        "Roche Elecsys": "ROCHE-03184897190",
                        "Mercodia": "MERCODIA-10-1136-01",
                        "Siemens": "SIEMENS-ADVIA-03649928",
                    },
                    "mercodia_low_end_0p05_verified": True,
                    "mercodia_dilution_linearity_5p00_verified": True,
                    "hla_binding_verified": True,
                    "hla_allele_panel_records": copy.deepcopy(ins_hla_panels),
                    "unique_hla_donor_count": 12,
                    "hla_peptides_tested": {
                        "HLA-DRB1*04:01": "GSLQPLAIEGSLQKRGIV",
                        "HLA-A*02:01": "SLQPLAIEGSL",
                        "HLA-A*11:01": "LAIEGSLQK",
                    },
                    "product_cell_peptidomics_verified": True,
                    "rna_splicing_delta_psi_pct": 0.2,
                    "proinsulin_to_insulin_ratio_vs_wt": 1.05,
                    "per_lot_bystander_edit_pct": 0.0,
                    "gsis_si": 3.4,
                    "gsis_pct_of_wt": 96.0,
                    "hip_reduction_pct": 91.0,
                },
            ),
            "editor_class": "PE2max",
            "mlh1dn_used": False,
            "day1_cpeptide_elisa_kit_records": copy.deepcopy(ins_elisa_kits),
            "mercodia_low_end_0p05_verified": True,
            "mercodia_dilution_linearity_5p00_verified": True,
            "hla_binding_verified": True,
            "hla_allele_panel_records": copy.deepcopy(ins_hla_panels),
            "product_cell_peptidomics_verified": True,
            "rna_splicing_delta_psi_pct": 0.2,
            "proinsulin_to_insulin_ratio_vs_wt": 1.05,
            "per_lot_bystander_edit_pct": 0.0,
            "gsis_si": 3.4,
            "gsis_pct_of_wt": 96.0,
            "hip_reduction_pct": 91.0,
        },
        "cuff": {
            "evidence_tier": "SYNTHETIC_FIXTURE",
            "target_arm_id": "B",
            "product_id": "ISLET1_DESIGN_B_V090",
            "lot_id": "SYNTH_CUFF_LOT_001",
            "bank_id": "MCB_B_SYNTH_01",
            "bank_origin": "allogeneic_hiPSC",
            "manifest_sha256": EXPECTED_ARM_MANIFEST_SHA256,
            "construct_manifest_sha256": cuff_csha,
            "design_a_exposed": False,
            "study_id": "CUFF_V2_EXACT_STACK_GY025_SYNTH_001",
            "upstream_lot_evidence_record": _make_evidence_record_v2(
                record_id="REC_G34_SYNTH_CUFF_001",
                gate_source=CANONICAL_UPSTREAM_GATE34_SOURCE,
                product_id="ISLET1_DESIGN_B_V090",
                lot_id="SYNTH_CUFF_LOT_001",
                bank_id="MCB_B_SYNTH_01",
                bank_origin="allogeneic_hiPSC",
                construct_manifest_sha256=cuff_csha,
            ),
            "current_assay_evidence_record": _make_evidence_record_v2(
                record_id="REC_G36_CUFF_SYNTH_001",
                gate_source=CANONICAL_GATE36_MODULE_SOURCES["cuff"],
                product_id="ISLET1_DESIGN_B_V090",
                lot_id="SYNTH_CUFF_LOT_001",
                bank_id="MCB_B_SYNTH_01",
                bank_origin="allogeneic_hiPSC",
                construct_manifest_sha256=cuff_csha,
                extra_fields={
                    "study_id": "CUFF_V2_EXACT_STACK_GY025_SYNTH_001",
                    "core_cuff_proteins": ["sCR1_v2", "THBD-M406L", "CD200-ECD"],
                    "per_protein_conjugation_records": copy.deepcopy(cuff_conj),
                    "free_thiol_um": 0.4,
                    "coimmobilized_cd200r_accessibility_verified": True,
                    "coimmobilized_cd200r_binding_pct_of_unhindered": 89.0,
                    "fasl_present": False,
                    "fasl_lcms_below_llod": True,
                    "retired_cfh_19_445_absent": True,
                    "monomer_pct": 97.0,
                    "retention_30d_pct": 97.5,
                    "leaching_30d_serum_pct": 1.1,
                    "paired_igg_depleted_control_included": True,
                    "adcc_donor_n": 8,
                    "intact_serum_total_killing_u95_pct": 3.2,
                    "paired_igg_attributable_cd16_adcc_u95_pct": 2.1,
                    "classical_c4b2a_residual_l95_pct": 2.0,
                    "classical_c4b2a_residual_u95_pct": 6.4,
                    "lectin_c4b2a_residual_l95_pct": 2.4,
                    "lectin_c4b2a_residual_u95_pct": 7.1,
                    "alternative_c5b9_residual_u95_pct": 3.2,
                    "overall_20pct_nhs_c5b9_residual_u95_pct": 3.8,
                    "classical_c4d_c5b9_drop_pct": 94.0,
                    "lectin_c4d_c5b9_drop_pct": 93.0,
                    "alternative_c3b_c5b9_drop_pct": 95.0,
                    "exact_stack_efferocytosis_abs_pct": 86.5,
                    "exact_stack_efferocytosis_pct_of_wt": 88.0,
                    "exact_stack_pericyte_recruitment_pct_of_wt": 84.0,
                    "plvap_iec_morphogenesis_t50_h": 24.0,
                    "plvap_iec_viability_pct": 92.0,
                    "thbd_h2o2_apc_retention_pct": 91.0,
                    "bulk_aptt_ratio": 1.04,
                    "pmn_residual_lysis_pct": 3.0,
                },
            ),
            "core_cuff_proteins": ["sCR1_v2", "THBD-M406L", "CD200-ECD"],
            "per_protein_conjugation_records": copy.deepcopy(cuff_conj),
            "free_thiol_um": 0.4,
            "coimmobilized_cd200r_accessibility_verified": True,
            "coimmobilized_cd200r_binding_pct_of_unhindered": 89.0,
            "fasl_present": False,
            "fasl_lcms_below_llod": True,
            "retired_cfh_19_445_absent": True,
            "monomer_pct": 97.0,
            "retention_30d_pct": 97.5,
            "leaching_30d_serum_pct": 1.1,
            "paired_igg_depleted_control_included": True,
            "adcc_donor_n": 8,
            "intact_serum_total_killing_u95_pct": 3.2,
            "paired_igg_attributable_cd16_adcc_u95_pct": 2.1,
            "classical_c4b2a_residual_l95_pct": 2.0,
            "classical_c4b2a_residual_u95_pct": 6.4,
            "lectin_c4b2a_residual_l95_pct": 2.4,
            "lectin_c4b2a_residual_u95_pct": 7.1,
            "alternative_c5b9_residual_u95_pct": 3.2,
            "overall_20pct_nhs_c5b9_residual_u95_pct": 3.8,
            "classical_c4d_c5b9_drop_pct": 94.0,
            "lectin_c4d_c5b9_drop_pct": 93.0,
            "alternative_c3b_c5b9_drop_pct": 95.0,
            "exact_stack_efferocytosis_abs_pct": 86.5,
            "exact_stack_efferocytosis_pct_of_wt": 88.0,
            "exact_stack_pericyte_recruitment_pct_of_wt": 84.0,
            "plvap_iec_morphogenesis_t50_h": 24.0,
            "plvap_iec_viability_pct": 92.0,
            "thbd_h2o2_apc_retention_pct": 91.0,
            "bulk_aptt_ratio": 1.04,
            "pmn_residual_lysis_pct": 3.0,
        },
        "invvax": {
            "evidence_tier": "SYNTHETIC_FIXTURE",
            "target_arm_id": "D",
            "product_id": "ISLET1_DESIGN_D1B_LEAN_K2",
            "lot_id": "SYNTH_INVVAX_LOT_001",
            "bank_id": "MCB_D_SYNTH_01",
            "bank_origin": "autologous_hiPSC",
            "manifest_sha256": EXPECTED_ARM_MANIFEST_SHA256,
            "construct_manifest_sha256": iv_csha,
            "design_a_exposed": False,
            "study_id": "INVVAX_PRETX_3DOSE_WASHOUT_SYNTH_001",
            "upstream_lot_evidence_record": _make_evidence_record_v2(
                record_id="REC_G34_SYNTH_INVVAX_001",
                gate_source=CANONICAL_UPSTREAM_GATE34_SOURCE,
                product_id="ISLET1_DESIGN_D1B_LEAN_K2",
                lot_id="SYNTH_INVVAX_LOT_001",
                bank_id="MCB_D_SYNTH_01",
                bank_origin="autologous_hiPSC",
                construct_manifest_sha256=iv_csha,
            ),
            "current_assay_evidence_record": _make_evidence_record_v2(
                record_id="REC_G36_INVVAX_SYNTH_001",
                gate_source=CANONICAL_GATE36_MODULE_SOURCES["invvax"],
                product_id="ISLET1_DESIGN_D1B_LEAN_K2",
                lot_id="SYNTH_INVVAX_LOT_001",
                bank_id="MCB_D_SYNTH_01",
                bank_origin="autologous_hiPSC",
                construct_manifest_sha256=iv_csha,
                extra_fields={
                    "study_id": "INVVAX_PRETX_3DOSE_WASHOUT_SYNTH_001",
                    "administration_days": [-28, -21, -7],
                    "last_dose_day": -7,
                    "clearance_sample_day": -4,
                    "plasma_assay_id": "LCMS_INVVAX_PLASMA_V1",
                    "lymph_node_assay_id": "LCMS_INVVAX_LYMPH_NODE_V1",
                    "plasma_llod_ng_ml": 0.05,
                    "tissue_llod_ng_g": 0.10,
                    "measured_plasma_conc_ng_ml": 0.01,
                    "measured_tissue_conc_ng_g": 0.02,
                    "max_ae_grade": 0,
                    "day90_cpeptide_retention_pct": 92.0,
                    "lymphocyte_count_pct_of_baseline": 98.0,
                    "treg_tr1_fold_expansion": 2.6,
                    "islet_antigens_suppressed_count": 4,
                    "islet_ag_elispot_drop_pct": 86.0,
                    "viral_vaccine_recall_retention_pct": 94.0,
                },
            ),
            "administration_days": [-28, -21, -7],
            "last_dose_day": -7,
            "clearance_sample_day": -4,
            "plasma_assay_id": "LCMS_INVVAX_PLASMA_V1",
            "lymph_node_assay_id": "LCMS_INVVAX_LYMPH_NODE_V1",
            "plasma_llod_ng_ml": 0.05,
            "tissue_llod_ng_g": 0.10,
            "measured_plasma_conc_ng_ml": 0.01,
            "measured_tissue_conc_ng_g": 0.02,
            "max_ae_grade": 0,
            "day90_cpeptide_retention_pct": 92.0,
            "lymphocyte_count_pct_of_baseline": 98.0,
            "treg_tr1_fold_expansion": 2.6,
            "islet_antigens_suppressed_count": 4,
            "islet_ag_elispot_drop_pct": 86.0,
            "viral_vaccine_recall_retention_pct": 94.0,
        },
    }


def build_trusted_store_for_obs(
    obs: dict[str, Any],
    *,
    store_key_mode: str = "record_id",
) -> dict[str, dict[str, Any]]:
    """Build a trusted_evidence_store indexing upstream_lot_evidence_record, current_assay_evidence_record, and (when present) live_gate32_debris_recall_record."""
    store: dict[str, dict[str, Any]] = {}
    for rk in (
        "upstream_lot_evidence_record",
        "current_assay_evidence_record",
        "live_gate32_debris_recall_record",
    ):
        rec = obs.get(rk)
        if isinstance(rec, dict):
            if store_key_mode == "both":
                if isinstance(rec.get("record_id"), str):
                    store[rec["record_id"]] = copy.deepcopy(rec)
                if isinstance(rec.get("archive_sha256"), str):
                    store[rec["archive_sha256"]] = copy.deepcopy(rec)
            elif store_key_mode == "archive_sha256":
                if isinstance(rec.get("archive_sha256"), str):
                    store[rec["archive_sha256"]] = copy.deepcopy(rec)
            else:
                if isinstance(rec.get("record_id"), str):
                    store[rec["record_id"]] = copy.deepcopy(rec)
    return store


def make_authenticated_gate34_fixture_and_store(
    module_name: str,
    *,
    arm_id: str | None = None,
    arm_manifest: dict[str, Any] | None = None,
    upstream_record: dict[str, Any] | None = None,
    live_gate32_debris_recall_record: dict[str, Any] | None = None,
    store_key_mode: str = "record_id",
) -> tuple[dict[str, Any], dict[str, dict[str, Any]]]:
    """Build an in-memory mock AUTHENTICATED_ARCHIVED_WETLAB Gate 36 observation + trusted_evidence_store.

    Populates ALL governing module fields in current_assay_evidence_record (GATE-36-<MODULE>) identically
    to parent obs, supports direct relay of an unmodified W6-C1 GATE-34 upstream_lot_evidence_record_v1,
    and for SHIELD automatically builds & stores a matching sealed live GATE-32 whole-islet-debris recall
    co-prerequisite record (PASS_DEBRIS_RECALL_FULL_CREDIT) in record_id, archive_sha256, or both mode.
    """
    fx_all = _canonical_synthetic_gate34_fixtures()
    require_cond(module_name in fx_all, f"Unknown Gate 36 module: {module_name}")
    obs = copy.deepcopy(fx_all[module_name])

    if upstream_record is not None:
        up = copy.deepcopy(upstream_record)
        if arm_id is not None:
            obs["target_arm_id"] = arm_id
        elif arm_manifest is not None and isinstance(arm_manifest.get("arms"), dict):
            for ak, aentry in arm_manifest["arms"].items():
                if aentry.get("product_id") == up.get("product_id"):
                    obs["target_arm_id"] = ak
                    break
        obs["product_id"] = up["product_id"]
        obs["lot_id"] = up["lot_id"]
        obs["bank_id"] = up["bank_id"]
        obs["bank_origin"] = up["bank_origin"]
        obs["construct_manifest_sha256"] = up["construct_manifest_sha256"]
        obs["evidence_tier"] = up["evidence_tier"]
        obs["upstream_lot_evidence_record"] = up
    else:
        if arm_id is not None and arm_manifest is not None:
            aentry = arm_manifest["arms"][arm_id]
            obs["target_arm_id"] = arm_id
            obs["product_id"] = aentry["product_id"]
            obs["bank_origin"] = aentry["cell_origin"]
            obs["lot_id"] = f"AUTH_{module_name.upper()}_{arm_id}_LOT_001"
            obs["bank_id"] = f"MCB_{arm_id}_AUTH_01"
            obs["construct_manifest_sha256"] = sha256_str(f"lot_construct_manifest|{obs['product_id']}|{obs['lot_id']}|v0.9.0")
        obs["evidence_tier"] = "AUTHENTICATED_ARCHIVED_WETLAB"
        up = _make_evidence_record_v2(
            record_id=f"REC_G34_AUTH_{module_name.upper()}_{obs['target_arm_id']}_001",
            gate_source=CANONICAL_UPSTREAM_GATE34_SOURCE,
            product_id=obs["product_id"],
            lot_id=obs["lot_id"],
            bank_id=obs["bank_id"],
            bank_origin=obs["bank_origin"],
            construct_manifest_sha256=obs["construct_manifest_sha256"],
            evidence_tier="AUTHENTICATED_ARCHIVED_WETLAB",
            decision="PASS",
            authority_scope="CLINICAL_LOT_RELEASE",
            bank_qualified=True,
            promotion_authorized=True,
        )
        obs["upstream_lot_evidence_record"] = up

    cur_extra = {
        k: v
        for k, v in obs["current_assay_evidence_record"].items()
        if k not in UPSTREAM_EVIDENCE_REQUIRED_FIELDS
    }
    is_auth = obs["evidence_tier"] == "AUTHENTICATED_ARCHIVED_WETLAB"
    cur = _make_evidence_record_v2(
        record_id=f"REC_G36_{module_name.upper()}_{'AUTH' if is_auth else 'SYNTH'}_{obs['target_arm_id']}_001",
        gate_source=CANONICAL_GATE36_MODULE_SOURCES[module_name],
        product_id=obs["product_id"],
        lot_id=obs["lot_id"],
        bank_id=obs["bank_id"],
        bank_origin=obs["bank_origin"],
        construct_manifest_sha256=obs["construct_manifest_sha256"],
        evidence_tier=obs["evidence_tier"],
        decision="PASS" if is_auth else "SYNTHETIC_SELF_TEST_PASS",
        authority_scope="CLINICAL_LOT_RELEASE" if is_auth else "SYNTHETIC_SELF_TEST",
        bank_qualified=True if is_auth else False,
        promotion_authorized=True if is_auth else False,
        extra_fields=cur_extra,
    )
    obs["current_assay_evidence_record"] = cur

    if module_name == "shield":
        if live_gate32_debris_recall_record is not None:
            g32_debris = copy.deepcopy(live_gate32_debris_recall_record)
        else:
            g32_debris = _make_evidence_record_v2(
                record_id=f"REC_LIVE_G32_DEBRIS_{'AUTH' if is_auth else 'SYNTH'}_{obs['target_arm_id']}_001",
                gate_source=CANONICAL_LIVE_GATE32_DEBRIS_RECALL_SOURCE,
                product_id=obs["product_id"],
                lot_id=obs["lot_id"],
                bank_id=obs["bank_id"],
                bank_origin=obs["bank_origin"],
                construct_manifest_sha256=obs["construct_manifest_sha256"],
                evidence_tier=obs["evidence_tier"],
                decision="PASS_DEBRIS_RECALL_FULL_CREDIT" if is_auth else "SYNTHETIC_SELF_TEST_PASS",
                authority_scope="CLINICAL_LOT_RELEASE" if is_auth else "SYNTHETIC_SELF_TEST",
                bank_qualified=True if is_auth else False,
                promotion_authorized=True if is_auth else False,
                extra_fields={
                    "debris_recall_verdict": "PASS_DEBRIS_RECALL_FULL_CREDIT",
                    "debris_recall_l95_suppressed_frac": 0.78,
                    "residual_class2_recall_u95_frac": 0.22,
                    "unrelated_recall_preserved": True,
                },
            )
        obs["live_gate32_debris_recall_record"] = g32_debris

    store = build_trusted_store_for_obs(obs, store_key_mode=store_key_mode)
    return obs, store


def run_gate34_self_tests(arm_manifest: dict[str, Any]) -> dict[str, Any]:
    fx = _canonical_synthetic_gate34_fixtures()
    ok_sh, ok_ins, ok_cuff, ok_iv = fx["shield"], fx["ins"], fx["cuff"], fx["invvax"]
    cases: dict[str, dict[str, Any]] = {}

    def _rec(name: str, res: dict[str, Any]) -> None:
        cases[name] = {
            "decision": res["decision"],
            "promotion_authorized": res["promotion_authorized"],
        }

    def _reseal_cur(base_obs: dict[str, Any], cur_updates: dict[str, Any]) -> tuple[dict[str, Any], dict[str, dict[str, Any]]]:
        o = copy.deepcopy(base_obs)
        c = copy.deepcopy(o["current_assay_evidence_record"])
        c.update(cur_updates)
        o["current_assay_evidence_record"] = seal_evidence_record(c)
        st = build_trusted_store_for_obs(o, store_key_mode="record_id")
        return o, st

    # 1. SHIELD-SEL synthetic & adversarial checks (Round-5 archive-derived, zero threshold tolerance)
    _rec("shield_synthetic_15uM_self_test_no_promo", evaluate_gate34_shield_sel(ok_sh, arm_manifest))
    _rec("shield_missing_manifest_fail", evaluate_gate34_shield_sel(ok_sh, None))
    _rec(
        "shield_l95_7p5uM_u95_15uM_review_probe_fail",
        evaluate_gate34_shield_sel(
            {**ok_sh, "on_target_kd_u95_nm": 0.5, "off_target_kd_l95_um": 7.5, "off_target_kd_u95_um": 15.0, "selectivity_ratio_l95": 15000.0},
            arm_manifest,
        ),
    )
    _rec("shield_1nM_peak_2000nM_trough_fail", evaluate_gate34_shield_sel({**ok_sh, "peak_free_nm": 1.0, "plasma_trough_free_nm": 2000.0}, arm_manifest))
    _rec("shield_plasma_trough_lt_dln_trough_fail", evaluate_gate34_shield_sel({**ok_sh, "plasma_trough_free_nm": 80.0, "dln_trough_free_nm": 150.0}, arm_manifest))
    _rec("shield_kd_on_1e_320_underflow_fail", evaluate_gate34_shield_sel({**ok_sh, "on_target_kd_u95_nm": 1e-320}, arm_manifest))
    _rec("shield_5000x_selectivity_fail", evaluate_gate34_shield_sel({**ok_sh, "on_target_kd_u95_nm": 2.0, "selectivity_ratio_l95": 5000.0}, arm_manifest))
    _rec("shield_q84d_relabeled_q28d_dataset_fail", evaluate_gate34_shield_sel({**ok_sh, "regimen_id": "Q84D"}, arm_manifest))
    _rec("shield_q84d_2nM_fail", evaluate_gate34_shield_sel({**ok_sh, "regimen_id": "Q84D", "timed_pk_day": 84, "on_target_kd_u95_nm": 2.0, "off_target_kd_l95_um": 30.0}, arm_manifest))
    _rec("shield_q84d_unmeasured_human_pk_fail", evaluate_gate34_shield_sel({**ok_sh, "regimen_id": "Q84D", "timed_pk_day": 84, "measured_human_pk_verified": False}, arm_manifest))
    _rec("shield_design_a_arm_fail", evaluate_gate34_shield_sel({**ok_sh, "target_arm_id": "A"}, arm_manifest))

    # 2. INS L82I synthetic & adversarial checks (governed kit/analyte + 4-donor deduplication probe)
    _rec("ins_synthetic_self_test_no_promo", evaluate_gate34_ins_l82i_elisa_pe2max(ok_ins, arm_manifest))
    dup4_ins = copy.deepcopy(ok_ins)
    for al in MANDATORY_INS_HLA_ALLELES:
        dup4_ins["hla_allele_panel_records"][al]["donor_ids"] = ["D1", "D2", "D3", "D4"]
        dup4_ins["hla_allele_panel_records"][al]["donor_count"] = 4
    _rec("ins_4_duplicated_donors_across_3_alleles_fail", evaluate_gate34_ins_l82i_elisa_pe2max(dup4_ins, arm_manifest))
    _rec("ins_hla_binding_false_fail", evaluate_gate34_ins_l82i_elisa_pe2max({**ok_ins, "hla_binding_verified": False}, arm_manifest))
    _rec("ins_design_a_exposed_fail", evaluate_gate34_ins_l82i_elisa_pe2max({**ok_ins, "design_a_exposed": True}, arm_manifest))
    _rec("ins_pe4max_mlh1dn_fail", evaluate_gate34_ins_l82i_elisa_pe2max({**ok_ins, "mlh1dn_used": True}, arm_manifest))

    # 3. Cuff v2.0 synthetic & adversarial checks (exact 3-protein + GY-025 efferocytosis/pericyte)
    _rec("cuff_synthetic_3protein_self_test_no_promo", evaluate_gate34_cuff_v2(ok_cuff, arm_manifest))
    _rec("cuff_1protein_manifest_fail", evaluate_gate34_cuff_v2({**ok_cuff, "core_cuff_proteins": ["sCR1_v2"]}, arm_manifest))
    _rec("cuff_zero_efferocytosis_fail", evaluate_gate34_cuff_v2({**ok_cuff, "exact_stack_efferocytosis_abs_pct": 0.0}, arm_manifest))
    _rec("cuff_zero_pericyte_fail", evaluate_gate34_cuff_v2({**ok_cuff, "exact_stack_pericyte_recruitment_pct_of_wt": 0.0}, arm_manifest))
    _rec("cuff_cd200r_accessibility_false_fail", evaluate_gate34_cuff_v2({**ok_cuff, "coimmobilized_cd200r_accessibility_verified": False}, arm_manifest))
    _rec("cuff_design_a_exposed_fail", evaluate_gate34_cuff_v2({**ok_cuff, "design_a_exposed": True}, arm_manifest))

    # 4. InvVax synthetic & adversarial checks (3-dose schedule + distinct governed matrix assay IDs)
    _rec("invvax_synthetic_self_test_no_promo", evaluate_gate34_invvax_recall(ok_iv, arm_manifest))
    _rec("invvax_single_dose_minus7_fail", evaluate_gate34_invvax_recall({**ok_iv, "administration_days": [-7], "last_dose_day": -7}, arm_manifest))
    _rec("invvax_duplicate_matrix_assay_id_fail", evaluate_gate34_invvax_recall({**ok_iv, "lymph_node_assay_id": "LCMS_INVVAX_PLASMA_V1"}, arm_manifest))
    _rec("invvax_post_tx_day_plus1_fail", evaluate_gate34_invvax_recall({**ok_iv, "administration_days": [-28, -21, 1], "last_dose_day": 1}, arm_manifest))
    _rec("invvax_llod_1e6_fail", evaluate_gate34_invvax_recall({**ok_iv, "plasma_llod_ng_ml": 1e6}, arm_manifest))
    _rec("invvax_design_a_exposed_fail", evaluate_gate34_invvax_recall({**ok_iv, "design_a_exposed": True}, arm_manifest))

    # 5. Authenticated archived wet-lab dual-record isolation, store-tamper, alias-conflict, producer-flag, & Round-5 archive-vs-parent probes
    auth_sh, auth_store = make_authenticated_gate34_fixture_and_store("shield", arm_manifest=arm_manifest)
    _rec("auth_without_store_holds_no_promo", evaluate_gate34_shield_sel(auth_sh, arm_manifest, trusted_evidence_store=None))
    _rec(
        "auth_with_upstream_only_store_holds_no_promo",
        evaluate_gate34_shield_sel(
            auth_sh,
            arm_manifest,
            trusted_evidence_store={auth_sh["upstream_lot_evidence_record"]["record_id"]: copy.deepcopy(auth_sh["upstream_lot_evidence_record"])},
        ),
    )
    tampered_store = copy.deepcopy(auth_store)
    tampered_store[auth_sh["upstream_lot_evidence_record"]["record_id"]]["promotion_authorized"] = False
    _rec("auth_store_promotion_false_tamper_fail", evaluate_gate34_shield_sel(auth_sh, arm_manifest, trusted_evidence_store=tampered_store))
    _rec("auth_with_verified_dual_store_authorizes", evaluate_gate34_shield_sel(auth_sh, arm_manifest, trusted_evidence_store=auth_store))

    # Round-5 Review #4 / Audit R4-05 archive-vs-parent contradiction & zero-threshold-tolerance probes
    sh_adv, sh_adv_st = _reseal_cur(auth_sh, {"apc_cytotoxicity_u95_pct": 100.0})
    _rec("r5_shield_archive_apc_100pct_vs_parent_fail", evaluate_gate34_shield_sel(sh_adv, arm_manifest, trusted_evidence_store=sh_adv_st))
    sh_eps, sh_eps_st = _reseal_cur(auth_sh, {"off_target_kd_l95_um": 14.9999999995})
    _rec("r5_shield_archive_14p9999999995uM_zero_tol_fail", evaluate_gate34_shield_sel(sh_eps, arm_manifest, trusted_evidence_store=sh_eps_st))

    auth_ins, _ = make_authenticated_gate34_fixture_and_store("ins", arm_manifest=arm_manifest)
    ins_bys, ins_bys_st = _reseal_cur(auth_ins, {"per_lot_bystander_edit_pct": 100.0})
    _rec("r5_ins_archive_bystander_100pct_vs_parent_fail", evaluate_gate34_ins_l82i_elisa_pe2max(ins_bys, arm_manifest, trusted_evidence_store=ins_bys_st))
    ins_gsis, ins_gsis_st = _reseal_cur(auth_ins, {"gsis_si": 1.0})
    _rec("r5_ins_archive_gsis_1p0_vs_parent_fail", evaluate_gate34_ins_l82i_elisa_pe2max(ins_gsis, arm_manifest, trusted_evidence_store=ins_gsis_st))
    ins_4don_panels = copy.deepcopy(auth_ins["current_assay_evidence_record"]["hla_allele_panel_records"])
    for al in MANDATORY_INS_HLA_ALLELES:
        ins_4don_panels[al]["donor_ids"] = ["ARCH_D1", "ARCH_D2", "ARCH_D3", "ARCH_D4"]
        ins_4don_panels[al]["donor_count"] = 4
    ins_4don, ins_4don_st = _reseal_cur(auth_ins, {"hla_allele_panel_records": ins_4don_panels})
    r_ins_4don = evaluate_gate34_ins_l82i_elisa_pe2max(ins_4don, arm_manifest, trusted_evidence_store=ins_4don_st)
    require_cond(
        r_ins_4don["unique_hla_donors_verified"] == 4 and abs(r_ins_4don["exact_one_sided_95pct_u95_pct"] - 52.7129) < 1e-3,
        f"INS archived 4-donor U95 must equal 52.7129%, got {r_ins_4don}",
    )
    _rec("r5_ins_archive_4donors_vs_12_claimed_fail", r_ins_4don)

    auth_cuff, _ = make_authenticated_gate34_fixture_and_store("cuff", arm_manifest=arm_manifest)
    cuff_sk, cuff_sk_st = _reseal_cur(auth_cuff, {"intact_serum_total_killing_u95_pct": 100.0})
    _rec("r5_cuff_archive_serum_killing_100pct_vs_parent_fail", evaluate_gate34_cuff_v2(cuff_sk, arm_manifest, trusted_evidence_store=cuff_sk_st))
    cuff_c4, cuff_c4_st = _reseal_cur(auth_cuff, {"classical_c4b2a_residual_l95_pct": 14.0})
    _rec("r5_cuff_archive_c4b2a_14pct_vs_parent_fail", evaluate_gate34_cuff_v2(cuff_c4, arm_manifest, trusted_evidence_store=cuff_c4_st))
    cuff_eps_base = copy.deepcopy(auth_cuff)
    cuff_eps_base["exact_stack_efferocytosis_abs_pct"] = 80.0
    cuff_eps, cuff_eps_st = _reseal_cur(cuff_eps_base, {"exact_stack_efferocytosis_abs_pct": 79.9999995})
    _rec("r5_cuff_archive_eff_79p9999995_zero_tol_fail", evaluate_gate34_cuff_v2(cuff_eps, arm_manifest, trusted_evidence_store=cuff_eps_st))

    auth_iv, _ = make_authenticated_gate34_fixture_and_store("invvax", arm_manifest=arm_manifest)
    iv_ae, iv_ae_st = _reseal_cur(auth_iv, {"max_ae_grade": 5})
    _rec("r5_invvax_archive_ae_grade5_vs_parent_fail", evaluate_gate34_invvax_recall(iv_ae, arm_manifest, trusted_evidence_store=iv_ae_st))
    iv_llod_base = copy.deepcopy(auth_iv)
    iv_llod_base["measured_plasma_conc_ng_ml"] = 0.0499999995
    iv_llod, iv_llod_st = _reseal_cur(iv_llod_base, {"measured_plasma_conc_ng_ml": 0.05})
    _rec("r5_invvax_archive_conc_at_llod_zero_tol_fail", evaluate_gate34_invvax_recall(iv_llod, arm_manifest, trusted_evidence_store=iv_llod_st))

    # Round-5 Review #5 alias conflict & Audit R4-01 contradictory producer flags
    auth_sh_both, alias_store = make_authenticated_gate34_fixture_and_store("shield", arm_manifest=arm_manifest, store_key_mode="both")
    alias_store[auth_sh_both["upstream_lot_evidence_record"]["archive_sha256"]]["bank_qualified"] = False
    _rec("r5_store_conflicting_index_aliases_fail", evaluate_gate34_shield_sel(auth_sh_both, arm_manifest, trusted_evidence_store=alias_store))

    pqc_sh, pqc_st = _reseal_cur(auth_sh, {"physical_qualification_complete": False})
    _rec("r5_contradictory_physical_qual_false_fail", evaluate_gate34_shield_sel(pqc_sh, arm_manifest, trusted_evidence_store=pqc_st))

    # Round-8 Audit R7-05: Strict canonical ASCII INS donor ID grammar, formatting normalization, & deduplication
    auth_ins_ok, auth_ins_st = make_authenticated_gate34_fixture_and_store("ins", arm_manifest=arm_manifest)
    r_ins_12_ok = evaluate_gate34_ins_l82i_elisa_pe2max(auth_ins_ok, arm_manifest, trusted_evidence_store=auth_ins_st)
    require_cond(
        r_ins_12_ok["decision"] == "PASS"
        and r_ins_12_ok["promotion_authorized"] is True
        and r_ins_12_ok["unique_hla_donors_verified"] == 12
        and abs(r_ins_12_ok["exact_one_sided_95pct_u95_pct"] - 22.0922) < 1e-3,
        f"INS 12 distinct canonical donors must PASS with U95=22.0922%, got {r_ins_12_ok}",
    )
    _rec("r8_ins_12_distinct_canonical_donors_pass", r_ins_12_ok)

    def _matched_ins_panel_probe(panel_donor_map: dict[str, list[str]], reactive_map: dict[str, list[str]] | None = None) -> dict[str, Any]:
        o = copy.deepcopy(auth_ins_ok)
        panels = copy.deepcopy(o["hla_allele_panel_records"])
        for al, dids in panel_donor_map.items():
            panels[al]["donor_ids"] = list(dids)
            panels[al]["donor_count"] = len(dids)
            if reactive_map is not None and al in reactive_map:
                panels[al]["reactive_donor_ids"] = list(reactive_map[al])
                panels[al]["reactive_donors"] = len(reactive_map[al])
        o["hla_allele_panel_records"] = copy.deepcopy(panels)
        o_m, st_m = _reseal_cur(o, {"hla_allele_panel_records": copy.deepcopy(panels), "unique_hla_donor_count": 12})
        return evaluate_gate34_ins_l82i_elisa_pe2max(o_m, arm_manifest, trusted_evidence_store=st_m)

    r_r8_ws = _matched_ins_panel_probe({
        "HLA-DRB1*04:01": ["DONOR_01", "DONOR_02", "DONOR_03", "DONOR_04"],
        "HLA-A*02:01": [" DONOR_01 ", " DONOR_02 ", " DONOR_03 ", " DONOR_04 "],
        "HLA-A*11:01": ["DONOR_01\t", "DONOR_02\t", "DONOR_03\t", "DONOR_04\t"],
    })
    require_cond(
        r_r8_ws["decision"] == "FAIL"
        and r_r8_ws["promotion_authorized"] is False
        and r_r8_ws["unique_hla_donors_verified"] == 4
        and abs(r_r8_ws["exact_one_sided_95pct_u95_pct"] - 52.7129) < 1e-3
        and any("INS_NONCANONICAL_DONOR_ID_REJECTED" in r for r in r_r8_ws["reasons"]),
        f"R8 whitespace-padded 4-donor probe failed expectation: {r_r8_ws}",
    )
    _rec("r8_ins_4donors_whitespace_padded_fail", r_r8_ws)

    r_r8_case = _matched_ins_panel_probe({
        "HLA-DRB1*04:01": ["DONOR_01", "DONOR_02", "DONOR_03", "DONOR_04"],
        "HLA-A*02:01": ["donor_01", "donor_02", "donor_03", "donor_04"],
        "HLA-A*11:01": ["Donor_01", "Donor_02", "Donor_03", "Donor_04"],
    })
    require_cond(
        r_r8_case["decision"] == "FAIL"
        and r_r8_case["promotion_authorized"] is False
        and r_r8_case["unique_hla_donors_verified"] == 4
        and abs(r_r8_case["exact_one_sided_95pct_u95_pct"] - 52.7129) < 1e-3,
        f"R8 case-variant 4-donor probe failed expectation: {r_r8_case}",
    )
    _rec("r8_ins_4donors_case_variants_fail", r_r8_case)

    r_r8_uni = _matched_ins_panel_probe({
        "HLA-DRB1*04:01": ["DONOR_01", "DONOR_02", "DONOR_03", "DONOR_04"],
        "HLA-A*02:01": ["DONOR_01\u200b", "DONOR_02\u00ad", "DONOR_03\u200b", "DONOR_04\u00ad"],
        "HLA-A*11:01": ["\uff24\uff2f\uff2e\uff2f\uff32_\uff10\uff11", "\uff24\uff2f\uff2e\uff2f\uff32_\uff10\uff12", "\uff24\uff2f\uff2e\uff2f\uff32_\uff10\uff13", "\uff24\uff2f\uff2e\uff2f\uff32_\uff10\uff14"],
    })
    require_cond(
        r_r8_uni["decision"] == "FAIL"
        and r_r8_uni["promotion_authorized"] is False
        and r_r8_uni["unique_hla_donors_verified"] == 4
        and abs(r_r8_uni["exact_one_sided_95pct_u95_pct"] - 52.7129) < 1e-3
        and any("INS_NONCANONICAL_DONOR_ID_REJECTED" in r for r in r_r8_uni["reasons"]),
        f"R8 unicode/NFKC 4-donor probe failed expectation: {r_r8_uni}",
    )
    _rec("r8_ins_4donors_unicode_nfkc_invisibles_fail", r_r8_uni)

    r_r8_sep = _matched_ins_panel_probe({
        "HLA-DRB1*04:01": ["DONOR_01", "DONOR_02", "DONOR_03", "DONOR_04"],
        "HLA-A*02:01": ["DONOR-01", "DONOR-02", "DONOR-03", "DONOR-04"],
        "HLA-A*11:01": ["DONOR.01", "DONOR.02", "DONOR.03", "DONOR.04"],
    })
    require_cond(
        r_r8_sep["decision"] == "FAIL"
        and r_r8_sep["promotion_authorized"] is False
        and r_r8_sep["unique_hla_donors_verified"] == 4
        and abs(r_r8_sep["exact_one_sided_95pct_u95_pct"] - 52.7129) < 1e-3,
        f"R8 separator-variant 4-donor probe failed expectation: {r_r8_sep}",
    )
    _rec("r8_ins_4donors_separator_variants_fail", r_r8_sep)

    r_r8_react = _matched_ins_panel_probe(
        {
            "HLA-DRB1*04:01": ["T1D_DON_001", "T1D_DON_002", "T1D_DON_003", "T1D_DON_004"],
            "HLA-A*02:01": ["T1D_DON_005", "T1D_DON_006", "T1D_DON_007", "T1D_DON_008"],
            "HLA-A*11:01": ["T1D_DON_009", "T1D_DON_010", "T1D_DON_011", "T1D_DON_012"],
        },
        reactive_map={"HLA-DRB1*04:01": [" T1D_DON_001\u200b"]},
    )
    require_cond(
        r_r8_react["decision"] == "FAIL"
        and r_r8_react["promotion_authorized"] is False
        and any("INS_NONCANONICAL_DONOR_ID_REJECTED" in r for r in r_r8_react["reasons"]),
        f"R8 reactive noncanonical donor ID probe failed expectation: {r_r8_react}",
    )
    _rec("r8_ins_reactive_noncanonical_donor_id_fail", r_r8_react)

    # Round-9 Audit R8-06 & Round-10 Audit R9-04: Separator-first -> numeric-padding-second canonical donor identity & mandatory positive canonical ASCII issuer on every present roster form
    def _both_mode_ins_roster_probe(
        panel_donor_map: dict[str, list[str]],
        *,
        primary_issuer: str | None = DEFAULT_INS_CANONICAL_ISSUER_ID,
        alias_issuer: str | None = DEFAULT_INS_CANONICAL_ISSUER_ID,
        cur_primary_issuer: str | None = "__SAME__",
        cur_alias_issuer: str | None = "__SAME__",
        issuer_field: str = "donor_issuer_id",
        include_alias_on_parent: bool = True,
        include_alias_on_archive: bool = True,
        store_key_mode: str = "both",
        claimed_unique: int = 12,
    ) -> dict[str, Any]:
        o, _ = make_authenticated_gate34_fixture_and_store("ins", arm_manifest=arm_manifest, store_key_mode=store_key_mode)
        base_panels = copy.deepcopy(o["hla_allele_panel_records"])
        for ifld in INS_DONOR_ISSUER_FIELDS:
            base_panels.pop(ifld, None)
        for al, dids in panel_donor_map.items():
            base_panels[al]["donor_ids"] = list(dids)
            base_panels[al]["donor_count"] = len(dids)
            for ifld in INS_DONOR_ISSUER_FIELDS:
                base_panels[al].pop(ifld, None)

        def _with_iss(iss: str | None) -> dict[str, Any]:
            p = copy.deepcopy(base_panels)
            if iss is not None:
                p[issuer_field] = iss
            return p

        p_obs_main = _with_iss(primary_issuer)
        p_obs_alias = _with_iss(alias_issuer)
        p_cur_main = _with_iss(primary_issuer if cur_primary_issuer == "__SAME__" else cur_primary_issuer)
        p_cur_alias = _with_iss(alias_issuer if cur_alias_issuer == "__SAME__" else cur_alias_issuer)

        o["hla_allele_panel_records"] = copy.deepcopy(p_obs_main)
        if include_alias_on_parent:
            o["per_allele_panels"] = copy.deepcopy(p_obs_alias)
        else:
            o.pop("per_allele_panels", None)
        cur_body = copy.deepcopy(o["current_assay_evidence_record"])
        cur_body["hla_allele_panel_records"] = copy.deepcopy(p_cur_main)
        if include_alias_on_archive:
            cur_body["per_allele_panels"] = copy.deepcopy(p_cur_alias)
        else:
            cur_body.pop("per_allele_panels", None)
        cur_body["unique_hla_donor_count"] = claimed_unique
        o["current_assay_evidence_record"] = seal_evidence_record(cur_body)
        u = o["upstream_lot_evidence_record"]
        c = o["current_assay_evidence_record"]
        if store_key_mode == "record_id":
            st = {u["record_id"]: copy.deepcopy(u), c["record_id"]: copy.deepcopy(c)}
        elif store_key_mode == "archive_sha256":
            st = {u["archive_sha256"]: copy.deepcopy(u), c["archive_sha256"]: copy.deepcopy(c)}
        else:
            st = {
                u["record_id"]: copy.deepcopy(u),
                u["archive_sha256"]: copy.deepcopy(u),
                c["record_id"]: copy.deepcopy(c),
                c["archive_sha256"]: copy.deepcopy(c),
            }
        return evaluate_gate34_ins_l82i_elisa_pe2max(o, arm_manifest, trusted_evidence_store=st)

    r_r9_digit_01 = _both_mode_ins_roster_probe({
        "HLA-DRB1*04:01": ["DONOR_01", "DONOR_02", "DONOR_03", "DONOR_04"],
        "HLA-A*02:01": ["DONOR_0-1", "DONOR_0-2", "DONOR_0-3", "DONOR_0-4"],
        "HLA-A*11:01": ["DONOR_0.1", "DONOR_0.2", "DONOR_0.3", "DONOR_0.4"],
    })
    require_cond(
        r_r9_digit_01["decision"] == "FAIL"
        and r_r9_digit_01["promotion_authorized"] is False
        and r_r9_digit_01["unique_hla_donors_verified"] == 4
        and abs(r_r9_digit_01["exact_one_sided_95pct_u95_pct"] - 52.7129) < 1e-3
        and any("INS_INCONSISTENT_DONOR_ID_FORMATTING_VARIANT" in r for r in r_r9_digit_01["reasons"]),
        f"R9 digit-separator 0_1/0-1/0.1 probe failed expectation: {r_r9_digit_01}",
    )
    _rec("r9_ins_4donors_digit_separator_0_1_both_rosters_fail", r_r9_digit_01)

    r_r9_digit_101 = _both_mode_ins_roster_probe({
        "HLA-DRB1*04:01": ["D-101", "D-102", "D-103", "D-104"],
        "HLA-A*02:01": ["D-10-1", "D-10-2", "D-10-3", "D-10-4"],
        "HLA-A*11:01": ["D-1-01", "D-1-02", "D-1-03", "D-1-04"],
    })
    require_cond(
        r_r9_digit_101["decision"] == "FAIL"
        and r_r9_digit_101["promotion_authorized"] is False
        and r_r9_digit_101["unique_hla_donors_verified"] == 4
        and abs(r_r9_digit_101["exact_one_sided_95pct_u95_pct"] - 52.7129) < 1e-3
        and any("INS_INCONSISTENT_DONOR_ID_FORMATTING_VARIANT" in r for r in r_r9_digit_101["reasons"]),
        f"R9 digit-separator D-101/D-10-1/D-1-01 probe failed expectation: {r_r9_digit_101}",
    )
    _rec("r9_ins_4donors_digit_separator_d101_both_rosters_fail", r_r9_digit_101)

    distinct12_r10 = {
        "HLA-DRB1*04:01": ["DONOR_01", "DONOR_02", "DONOR_03", "DONOR_04"],
        "HLA-A*02:01": ["DONOR_05", "DONOR_06", "DONOR_07", "DONOR_08"],
        "HLA-A*11:01": ["DONOR_09", "DONOR_10", "DONOR_11", "DONOR_12"],
    }

    r_r9_issuer_mis = _both_mode_ins_roster_probe(
        distinct12_r10,
        primary_issuer="BIOREPO_T1D_A",
        alias_issuer="BIOREPO_T1D_B",
    )
    require_cond(
        r_r9_issuer_mis["decision"] == "FAIL"
        and r_r9_issuer_mis["promotion_authorized"] is False
        and any("INS_ROSTER_DONOR_ISSUER_ID_MISMATCH" in r for r in r_r9_issuer_mis["reasons"]),
        f"R9 roster issuer mismatch probe failed expectation: {r_r9_issuer_mis}",
    )
    _rec("r9_ins_roster_issuer_identity_mismatch_fail", r_r9_issuer_mis)

    r_r9_12_ok = _both_mode_ins_roster_probe(
        distinct12_r10,
        primary_issuer="BIOREPO_T1D_V1",
        alias_issuer="BIOREPO_T1D_V1",
    )
    require_cond(
        r_r9_12_ok["decision"] == "PASS"
        and r_r9_12_ok["promotion_authorized"] is True
        and r_r9_12_ok["unique_hla_donors_verified"] == 12
        and abs(r_r9_12_ok["exact_one_sided_95pct_u95_pct"] - 22.0922) < 1e-3,
        f"R9 12 distinct canonical donors with shared roster issuer must PASS, got {r_r9_12_ok}",
    )
    _rec("r9_ins_12_distinct_donors_both_rosters_same_issuer_pass", r_r9_12_ok)

    # Round-10 Audit R9-04 & Round-11 Audit R10-03: Mandatory positive canonical ASCII HLA registry issuer on EVERY present roster form; HOLD & null verified stats when archive omits!
    for lk_mode in ("record_id", "archive_sha256"):
        r_r10_omit = _both_mode_ins_roster_probe(
            distinct12_r10,
            primary_issuer=None,
            alias_issuer=None,
            store_key_mode=lk_mode,
        )
        require_cond(
            r_r10_omit["decision"] == "HOLD"
            and r_r10_omit["promotion_authorized"] is False
            and r_r10_omit["unique_hla_donors_verified"] is None
            and r_r10_omit["total_reactive_donors"] is None
            and r_r10_omit["exact_one_sided_95pct_u95_pct"] is None
            and r_r10_omit["ins_statistics_derivation_source"] == "UNVERIFIED_HOLD_MISSING_ARCHIVED_ISSUER"
            and any("HOLD_MISSING_ARCHIVED_HLA_REGISTRY_ISSUER" in r for r in r_r10_omit["reasons"]),
            f"R10/R11 omitted issuer across both rosters ({lk_mode}) must HOLD with null official stats, got {r_r10_omit}",
        )
    _rec("r10_ins_both_rosters_omitted_issuer_hold", r_r10_omit)

    r_r10_single_omit = _both_mode_ins_roster_probe(
        distinct12_r10,
        primary_issuer=None,
        include_alias_on_parent=False,
        include_alias_on_archive=False,
    )
    require_cond(
        r_r10_single_omit["decision"] == "HOLD"
        and r_r10_single_omit["promotion_authorized"] is False
        and r_r10_single_omit["unique_hla_donors_verified"] is None
        and r_r10_single_omit["exact_one_sided_95pct_u95_pct"] is None
        and r_r10_single_omit["ins_statistics_derivation_source"] == "UNVERIFIED_HOLD_MISSING_ARCHIVED_ISSUER"
        and any("HOLD_MISSING_ARCHIVED_HLA_REGISTRY_ISSUER:hla_allele_panel_records" in r for r in r_r10_single_omit["reasons"]),
        f"R10/R11 single-form archived omitted issuer must HOLD with null official stats, got {r_r10_single_omit}",
    )
    _rec("r10_ins_single_form_archived_omitted_issuer_hold", r_r10_single_omit)

    r_r10_arch_one_omit = _both_mode_ins_roster_probe(
        distinct12_r10,
        primary_issuer="BIOREPO_T1D_V1",
        alias_issuer="BIOREPO_T1D_V1",
        cur_primary_issuer="BIOREPO_T1D_V1",
        cur_alias_issuer=None,
    )
    require_cond(
        r_r10_arch_one_omit["decision"] == "HOLD"
        and r_r10_arch_one_omit["promotion_authorized"] is False
        and r_r10_arch_one_omit["unique_hla_donors_verified"] is None
        and r_r10_arch_one_omit["exact_one_sided_95pct_u95_pct"] is None
        and r_r10_arch_one_omit["ins_statistics_derivation_source"] == "UNVERIFIED_HOLD_MISSING_ARCHIVED_ISSUER"
        and any("HOLD_MISSING_ARCHIVED_HLA_REGISTRY_ISSUER:per_allele_panels" in r for r in r_r10_arch_one_omit["reasons"]),
        f"R10/R11 archive one-form omitted issuer must HOLD with null official stats, got {r_r10_arch_one_omit}",
    )
    _rec("r10_ins_archive_one_form_omitted_issuer_hold", r_r10_arch_one_omit)

    r_r10_cur_omit_fail = _both_mode_ins_roster_probe(
        distinct12_r10,
        primary_issuer="BIOREPO_T1D_V1",
        alias_issuer=None,
        cur_primary_issuer="BIOREPO_T1D_V1",
        cur_alias_issuer="BIOREPO_T1D_V1",
    )
    require_cond(
        r_r10_cur_omit_fail["decision"] == "FAIL"
        and r_r10_cur_omit_fail["promotion_authorized"] is False
        and r_r10_cur_omit_fail["unique_hla_donors_verified"] == 12
        and abs(r_r10_cur_omit_fail["exact_one_sided_95pct_u95_pct"] - 22.0922) < 1e-3
        and r_r10_cur_omit_fail["ins_statistics_derivation_source"] == "AUTHENTICATED_ARCHIVE_ONLY_CALLER_CONFLICT"
        and any("INS_MISSING_CURRENT_HLA_REGISTRY_ISSUER:per_allele_panels" in r for r in r_r10_cur_omit_fail["reasons"]),
        f"R10/R11 current omitted issuer vs archive-established issuer must FAIL with archive-only stats, got {r_r10_cur_omit_fail}",
    )
    _rec("r10_ins_current_omitted_issuer_vs_archived_fail", r_r10_cur_omit_fail)

    r_r10_pos_hla_iss = _both_mode_ins_roster_probe(
        distinct12_r10,
        primary_issuer="BIOREPO_T1D_V1",
        alias_issuer="BIOREPO_T1D_V1",
        issuer_field="hla_registry_issuer",
    )
    require_cond(
        r_r10_pos_hla_iss["decision"] == "PASS"
        and r_r10_pos_hla_iss["promotion_authorized"] is True
        and r_r10_pos_hla_iss["unique_hla_donors_verified"] == 12
        and r_r10_pos_hla_iss["total_reactive_donors"] == 0
        and abs(r_r10_pos_hla_iss["exact_one_sided_95pct_u95_pct"] - 22.0922) < 1e-3
        and r_r10_pos_hla_iss["ins_statistics_derivation_source"] == "AUTHENTICATED_ARCHIVE_ROSTER_VERIFIED"
        and r_r10_pos_hla_iss["caller_roster_reconciliation_status"] == "MATCHED"
        and r_r10_pos_hla_iss["caller_reported_unverified_u95_pct"] is None,
        f"R10/R11 positive hla_registry_issuer across both rosters must PASS with AUTHENTICATED_ARCHIVE_ROSTER_VERIFIED, got {r_r10_pos_hla_iss}",
    )
    _rec("r10_ins_both_rosters_positive_hla_registry_issuer_pass", r_r10_pos_hla_iss)

    # Round-11 Audit R10-03: Strict 4-state archive-only official statistics (zero caller contamination; null on HOLD/unverified/internal-archive-conflict)
    for lk_mode in ("record_id", "archive_sha256"):
        ins_c11, st_c11 = make_authenticated_gate34_fixture_and_store("ins", arm_manifest=arm_manifest, store_key_mode=lk_mode)
        ins_c11["hla_allele_panel_records"]["HLA-DRB1*04:01"]["reactive_donor_ids"] = ["T1D_DON_001"]
        ins_c11["hla_allele_panel_records"]["HLA-DRB1*04:01"]["reactive_donors"] = 1
        r_r11_caller_react = evaluate_gate34_ins_l82i_elisa_pe2max(ins_c11, arm_manifest, trusted_evidence_store=st_c11)
        require_cond(
            r_r11_caller_react["decision"] == "FAIL"
            and r_r11_caller_react["promotion_authorized"] is False
            and r_r11_caller_react["unique_hla_donors_verified"] == 12
            and r_r11_caller_react["total_reactive_donors"] == 0
            and abs(r_r11_caller_react["exact_one_sided_95pct_u95_pct"] - 22.0922) < 1e-3
            and r_r11_caller_react["ins_statistics_derivation_source"] == "AUTHENTICATED_ARCHIVE_ONLY_CALLER_CONFLICT"
            and r_r11_caller_react["caller_roster_reconciliation_status"] == "CONFLICT_CALLER_MISMATCH"
            and r_r11_caller_react["caller_reported_unverified_unique_donors"] == 12
            and r_r11_caller_react["caller_reported_unverified_reactive_donors"] == 1
            and abs(r_r11_caller_react["caller_reported_unverified_u95_pct"] - 33.8681) < 1e-3,
            f"R11 caller-only reactive donor ({lk_mode}) contaminated official archive U95: {r_r11_caller_react}",
        )
    _rec("r11_ins_caller_only_reactive_preserves_archive_u95_fail", r_r11_caller_react)

    ins_no_arch, st_no_arch = make_authenticated_gate34_fixture_and_store("ins", arm_manifest=arm_manifest)
    ins_no_arch.pop("current_assay_evidence_record")
    r_r11_no_arch = evaluate_gate34_ins_l82i_elisa_pe2max(ins_no_arch, arm_manifest, trusted_evidence_store=st_no_arch)
    require_cond(
        r_r11_no_arch["decision"] == "HOLD"
        and r_r11_no_arch["promotion_authorized"] is False
        and r_r11_no_arch["unique_hla_donors_verified"] is None
        and r_r11_no_arch["total_reactive_donors"] is None
        and r_r11_no_arch["exact_one_sided_95pct_u95_pct"] is None
        and r_r11_no_arch["ins_statistics_derivation_source"] == "UNVERIFIED_HOLD_NO_AUTHENTICATED_ARCHIVE"
        and r_r11_no_arch["caller_reported_unverified_unique_donors"] == 12,
        f"R11 missing archive must HOLD with null official stats, got {r_r11_no_arch}",
    )
    _rec("r11_ins_missing_archive_null_verified_stats_hold", r_r11_no_arch)

    r_r11_no_store = evaluate_gate34_ins_l82i_elisa_pe2max(auth_ins_ok, arm_manifest, trusted_evidence_store=None)
    require_cond(
        r_r11_no_store["decision"] == "HOLD_UNRESOLVED_TRUSTED_EVIDENCE_STORE"
        and r_r11_no_store["promotion_authorized"] is False
        and r_r11_no_store["unique_hla_donors_verified"] is None
        and r_r11_no_store["total_reactive_donors"] is None
        and r_r11_no_store["exact_one_sided_95pct_u95_pct"] is None
        and r_r11_no_store["ins_statistics_derivation_source"] == "UNVERIFIED_HOLD_NO_AUTHENTICATED_ARCHIVE"
        and r_r11_no_store["caller_reported_unverified_unique_donors"] == 12,
        f"R11 missing trusted store must HOLD with null official stats, got {r_r11_no_store}",
    )
    _rec("r11_ins_missing_trusted_store_null_verified_stats_hold", r_r11_no_store)

    ins_conf_alias = copy.deepcopy(auth_ins_ok["current_assay_evidence_record"]["hla_allele_panel_records"])
    ins_conf_alias["HLA-DRB1*04:01"]["reactive_donor_ids"] = ["T1D_DON_001"]
    ins_conf_alias["HLA-DRB1*04:01"]["reactive_donors"] = 1
    ins_conf, ins_conf_st = _reseal_cur(auth_ins_ok, {"per_allele_panels": ins_conf_alias})
    r_r11_int_conf = evaluate_gate34_ins_l82i_elisa_pe2max(ins_conf, arm_manifest, trusted_evidence_store=ins_conf_st)
    require_cond(
        r_r11_int_conf["decision"] == "FAIL"
        and r_r11_int_conf["promotion_authorized"] is False
        and r_r11_int_conf["unique_hla_donors_verified"] is None
        and r_r11_int_conf["total_reactive_donors"] is None
        and r_r11_int_conf["exact_one_sided_95pct_u95_pct"] is None
        and r_r11_int_conf["ins_statistics_derivation_source"] == "WITHHELD_INTERNAL_ARCHIVE_CONFLICT",
        f"R11 internally conflicting archive must FAIL with null official stats, got {r_r11_int_conf}",
    )
    _rec("r11_ins_internal_archive_conflict_null_verified_stats_fail", r_r11_int_conf)

    ins_1of12_panels = copy.deepcopy(auth_ins_ok["hla_allele_panel_records"])
    ins_1of12_panels["HLA-DRB1*04:01"]["reactive_donor_ids"] = ["T1D_DON_001"]
    ins_1of12_panels["HLA-DRB1*04:01"]["reactive_donors"] = 1
    ins_1of12_panels["HLA-DRB1*04:01"]["max_elispot_sfu"] = 65.0
    ins_1of12_base = copy.deepcopy(auth_ins_ok)
    ins_1of12_base["hla_allele_panel_records"] = copy.deepcopy(ins_1of12_panels)
    ins_1of12, ins_1of12_st = _reseal_cur(ins_1of12_base, {"hla_allele_panel_records": copy.deepcopy(ins_1of12_panels)})
    r_r11_arch_1of12 = evaluate_gate34_ins_l82i_elisa_pe2max(ins_1of12, arm_manifest, trusted_evidence_store=ins_1of12_st)
    require_cond(
        r_r11_arch_1of12["decision"] == "FAIL"
        and r_r11_arch_1of12["promotion_authorized"] is False
        and r_r11_arch_1of12["unique_hla_donors_verified"] == 12
        and r_r11_arch_1of12["total_reactive_donors"] == 1
        and abs(r_r11_arch_1of12["exact_one_sided_95pct_u95_pct"] - 33.8681) < 1e-3
        and r_r11_arch_1of12["ins_statistics_derivation_source"] == "AUTHENTICATED_ARCHIVE_ROSTER_VERIFIED"
        and r_r11_arch_1of12["caller_roster_reconciliation_status"] == "MATCHED"
        and r_r11_arch_1of12["caller_reported_unverified_u95_pct"] is None,
        f"R11 archive-driven 1/12 reactive FAIL must report archive 33.8681%, got {r_r11_arch_1of12}",
    )
    _rec("r11_ins_archive_1of12_reactive_matched_fail", r_r11_arch_1of12)

    sh_caller_adv = copy.deepcopy(auth_sh)
    sh_caller_adv["off_target_kd_l95_um"] = 7.5
    r_r11_sh_caller = evaluate_gate34_shield_sel(sh_caller_adv, arm_manifest, trusted_evidence_store=auth_store)
    require_cond(
        r_r11_sh_caller["decision"] == "FAIL"
        and r_r11_sh_caller["promotion_authorized"] is False
        and abs(r_r11_sh_caller["pan_dq_peak_ro_pct"] - 3.9159) < 1e-3
        and r_r11_sh_caller["shield_statistics_derivation_source"] == "AUTHENTICATED_ARCHIVE_ONLY_CALLER_CONFLICT"
        and abs(r_r11_sh_caller["caller_reported_unverified_pan_dq_peak_ro_pct"] - 7.5366) < 1e-3,
        f"R11 SHIELD caller-only adverse probe contaminated official RO: {r_r11_sh_caller}",
    )
    _rec("r11_shield_caller_only_adverse_preserves_archive_ro_fail", r_r11_sh_caller)

    r_r11_sh_nostore = evaluate_gate34_shield_sel(auth_sh, arm_manifest, trusted_evidence_store=None)
    require_cond(
        r_r11_sh_nostore["decision"] == "HOLD_UNRESOLVED_TRUSTED_EVIDENCE_STORE"
        and r_r11_sh_nostore["promotion_authorized"] is False
        and r_r11_sh_nostore["pan_dq_peak_ro_pct"] is None
        and r_r11_sh_nostore["recomputed_selectivity_ratio"] is None
        and r_r11_sh_nostore["shield_statistics_derivation_source"] == "UNVERIFIED_HOLD_NO_AUTHENTICATED_ARCHIVE",
        f"R11 SHIELD missing store must HOLD with null official RO/selectivity, got {r_r11_sh_nostore}",
    )
    _rec("r11_shield_missing_store_null_verified_stats_hold", r_r11_sh_nostore)

    # Round-12 Audit R11-04: Gate ALL official SHIELD (& INS) statistics on complete authenticated archive + every internal consistency check; separate caller reconciliation!
    shield_official_stat_keys = (
        "pan_dq_peak_ro_pct",
        "pan_dq_plasma_trough_ro_pct",
        "pan_dq_dln_trough_ro_pct",
        "dln_trough_on_target_ro_pct",
        "recomputed_selectivity_ratio",
    )

    def _reseal_module_mode(
        mod_name: str,
        cur_mutator: Callable[[dict[str, Any]], None],
        *,
        store_key_mode: str,
        parent_mutator: Callable[[dict[str, Any]], None] | None = None,
    ) -> tuple[dict[str, Any], dict[str, dict[str, Any]]]:
        o, _ = make_authenticated_gate34_fixture_and_store(mod_name, arm_manifest=arm_manifest, store_key_mode=store_key_mode)
        if parent_mutator is not None:
            parent_mutator(o)
        c = copy.deepcopy(o["current_assay_evidence_record"])
        cur_mutator(c)
        o["current_assay_evidence_record"] = seal_evidence_record(c)
        st = build_trusted_store_for_obs(o, store_key_mode=store_key_mode)
        return o, st

    for lk_mode in ("record_id", "archive_sha256", "both"):
        sh_no_sid, st_no_sid = _reseal_module_mode(
            "shield",
            lambda c: c.pop("study_id", None),
            store_key_mode=lk_mode,
        )
        r_r12_no_sid = evaluate_gate34_shield_sel(sh_no_sid, arm_manifest, trusted_evidence_store=st_no_sid)
        require_cond(
            r_r12_no_sid["decision"] == "HOLD"
            and r_r12_no_sid["promotion_authorized"] is False
            and all(r_r12_no_sid[k] is None for k in shield_official_stat_keys)
            and r_r12_no_sid["shield_statistics_derivation_source"] == "UNVERIFIED_HOLD_INCOMPLETE_ARCHIVE",
            f"R12 SHIELD omitted archived study_id ({lk_mode}) must HOLD with null official stats, got {r_r12_no_sid}",
        )

        sh_no_sid_fail, st_no_sid_fail = _reseal_module_mode(
            "shield",
            lambda c: c.pop("study_id", None),
            store_key_mode=lk_mode,
            parent_mutator=lambda p: p.__setitem__("off_target_kd_l95_um", 7.5),
        )
        r_r12_no_sid_fail = evaluate_gate34_shield_sel(sh_no_sid_fail, arm_manifest, trusted_evidence_store=st_no_sid_fail)
        require_cond(
            r_r12_no_sid_fail["decision"] == "FAIL"
            and r_r12_no_sid_fail["promotion_authorized"] is False
            and all(r_r12_no_sid_fail[k] is None for k in shield_official_stat_keys)
            and r_r12_no_sid_fail["shield_statistics_derivation_source"] == "WITHHELD_INCOMPLETE_ARCHIVE_WITH_INDEPENDENT_FAIL"
            and "_HOLD_" not in r_r12_no_sid_fail["shield_statistics_derivation_source"],
            f"R12 SHIELD omitted archived study_id + independent FAIL ({lk_mode}) must never pair FAIL with HOLD label: {r_r12_no_sid_fail}",
        )

        sh_trough_gt_pk, st_tgp = _reseal_module_mode(
            "shield",
            lambda c: c.update({"peak_free_nm": 1.0, "plasma_trough_free_nm": 2000.0}),
            store_key_mode=lk_mode,
            parent_mutator=lambda p: p.update({"peak_free_nm": 1.0, "plasma_trough_free_nm": 2000.0}),
        )
        r_r12_tgp = evaluate_gate34_shield_sel(sh_trough_gt_pk, arm_manifest, trusted_evidence_store=st_tgp)
        require_cond(
            r_r12_tgp["decision"] == "FAIL"
            and r_r12_tgp["promotion_authorized"] is False
            and all(r_r12_tgp[k] is None for k in shield_official_stat_keys)
            and r_r12_tgp["shield_statistics_derivation_source"] == "WITHHELD_INTERNAL_ARCHIVE_CONFLICT",
            f"R12 SHIELD archived trough > peak ({lk_mode}) must withhold ALL official stats, got {r_r12_tgp}",
        )

        sh_reg_conf, st_rc = _reseal_module_mode(
            "shield",
            lambda c: c.update({"dosing_regimen": "Q28D", "timed_pk_day": 84}),
            store_key_mode=lk_mode,
            parent_mutator=lambda p: p.update({"regimen_id": "Q28D", "timed_pk_day": 84}),
        )
        r_r12_reg = evaluate_gate34_shield_sel(sh_reg_conf, arm_manifest, trusted_evidence_store=st_rc)
        require_cond(
            r_r12_reg["decision"] == "FAIL"
            and r_r12_reg["promotion_authorized"] is False
            and all(r_r12_reg[k] is None for k in shield_official_stat_keys)
            and r_r12_reg["shield_statistics_derivation_source"] == "WITHHELD_INTERNAL_ARCHIVE_CONFLICT",
            f"R12 SHIELD contradictory archived regimen/interval ({lk_mode}) must withhold ALL official stats, got {r_r12_reg}",
        )

        sh_75_conf, st_75 = _reseal_module_mode(
            "shield",
            lambda c: c.update({"off_target_kd_l95_um": 7.5}),
            store_key_mode=lk_mode,
            parent_mutator=lambda p: p.update({"off_target_kd_l95_um": 7.5}),
        )
        r_r12_75_conf = evaluate_gate34_shield_sel(sh_75_conf, arm_manifest, trusted_evidence_store=st_75)
        require_cond(
            r_r12_75_conf["decision"] == "FAIL"
            and r_r12_75_conf["promotion_authorized"] is False
            and all(r_r12_75_conf[k] is None for k in shield_official_stat_keys)
            and r_r12_75_conf["shield_statistics_derivation_source"] == "WITHHELD_INTERNAL_ARCHIVE_CONFLICT",
            f"R12 SHIELD inconsistent 7.5 uM archive ({lk_mode}) must NOT emit 7.5366%, got {r_r12_75_conf}",
        )

        ins_no_sid, st_ins_no_sid = _reseal_module_mode(
            "ins",
            lambda c: c.pop("study_id", None),
            store_key_mode=lk_mode,
        )
        r_r12_ins_no_sid = evaluate_gate34_ins_l82i_elisa_pe2max(ins_no_sid, arm_manifest, trusted_evidence_store=st_ins_no_sid)
        require_cond(
            r_r12_ins_no_sid["decision"] == "HOLD"
            and r_r12_ins_no_sid["promotion_authorized"] is False
            and r_r12_ins_no_sid["unique_hla_donors_verified"] is None
            and r_r12_ins_no_sid["total_reactive_donors"] is None
            and r_r12_ins_no_sid["exact_one_sided_95pct_u95_pct"] is None
            and r_r12_ins_no_sid["ins_statistics_derivation_source"] == "UNVERIFIED_HOLD_INCOMPLETE_ARCHIVE",
            f"R12 INS omitted archived study_id ({lk_mode}) must HOLD with null official stats, got {r_r12_ins_no_sid}",
        )

    _rec("r12_shield_omitted_archived_study_id_null_stats_hold", r_r12_no_sid)
    _rec("r12_shield_omitted_archived_study_id_independent_fail_withheld", r_r12_no_sid_fail)
    _rec("r12_shield_archived_trough_gt_peak_null_stats_fail", r_r12_tgp)
    _rec("r12_shield_archived_regimen_interval_conflict_null_stats_fail", r_r12_reg)
    _rec("r12_shield_archived_7p5uM_metric_conflict_null_stats_fail", r_r12_75_conf)
    _rec("r12_ins_omitted_archived_study_id_null_stats_hold", r_r12_ins_no_sid)

    # Round-13 Audit R12-07: (1) SHIELD omitted archived peak_free_nm returns HOLD (NEVER false trough-substituted RO conflict FAIL!);
    # (2) INS missing/unauthenticated/incomplete archive + independent FAIL NEVER emits *_HOLD_* derivation source!
    ins_official_stat_keys = (
        "unique_hla_donors_verified",
        "pooled_allele_panel_observations",
        "total_hla_donors_verified",
        "total_reactive_donors",
        "exact_one_sided_95pct_u95_pct",
    )
    for lk_mode in ("record_id", "archive_sha256", "both"):
        sh_no_peak, st_no_peak = _reseal_module_mode(
            "shield",
            lambda c: c.pop("peak_free_nm", None),
            store_key_mode=lk_mode,
        )
        r_r13_sh_no_peak = evaluate_gate34_shield_sel(sh_no_peak, arm_manifest, trusted_evidence_store=st_no_peak)
        require_cond(
            r_r13_sh_no_peak["decision"] == "HOLD"
            and r_r13_sh_no_peak["verdict"] == "HOLD"
            and r_r13_sh_no_peak["promotion_authorized"] is False
            and all(r_r13_sh_no_peak[k] is None for k in shield_official_stat_keys)
            and r_r13_sh_no_peak["shield_statistics_derivation_source"] == "UNVERIFIED_HOLD_INCOMPLETE_ARCHIVE"
            and not any("REPORTED_OFF_TARGET_RO_DEVIATES" in r for r in r_r13_sh_no_peak["reasons"]),
            f"R13 SHIELD omitted archived peak_free_nm ({lk_mode}) must HOLD without false conflict: {r_r13_sh_no_peak}",
        )

        ins_base_r13, st_base_r13 = make_authenticated_gate34_fixture_and_store(
            "ins", arm_manifest=arm_manifest, store_key_mode=lk_mode
        )
        ins_no_arch_fail = copy.deepcopy(ins_base_r13)
        ins_no_arch_fail.pop("current_assay_evidence_record")
        ins_no_arch_fail["gsis_si"] = 1.0
        r_r13_ins_no_arch_fail = evaluate_gate34_ins_l82i_elisa_pe2max(
            ins_no_arch_fail, arm_manifest, trusted_evidence_store=st_base_r13
        )
        require_cond(
            r_r13_ins_no_arch_fail["decision"] == "FAIL"
            and r_r13_ins_no_arch_fail["promotion_authorized"] is False
            and all(r_r13_ins_no_arch_fail[k] is None for k in ins_official_stat_keys)
            and r_r13_ins_no_arch_fail["ins_statistics_derivation_source"] == "WITHHELD_NO_AUTHENTICATED_ARCHIVE_WITH_INDEPENDENT_FAIL"
            and "_HOLD_" not in r_r13_ins_no_arch_fail["ins_statistics_derivation_source"],
            f"R13 INS missing archive + caller FAIL ({lk_mode}) paired FAIL with HOLD label: {r_r13_ins_no_arch_fail}",
        )

        ins_nostore_fail = copy.deepcopy(ins_base_r13)
        ins_nostore_fail["hla_allele_panel_records"]["HLA-DRB1*04:01"]["reactive_donor_ids"] = ["T1D_DON_001"]
        ins_nostore_fail["hla_allele_panel_records"]["HLA-DRB1*04:01"]["reactive_donors"] = 1
        r_r13_ins_nostore_fail = evaluate_gate34_ins_l82i_elisa_pe2max(
            ins_nostore_fail, arm_manifest, trusted_evidence_store=None
        )
        require_cond(
            r_r13_ins_nostore_fail["decision"] == "FAIL"
            and r_r13_ins_nostore_fail["promotion_authorized"] is False
            and all(r_r13_ins_nostore_fail[k] is None for k in ins_official_stat_keys)
            and r_r13_ins_nostore_fail["ins_statistics_derivation_source"] == "WITHHELD_NO_AUTHENTICATED_ARCHIVE_WITH_INDEPENDENT_FAIL"
            and "_HOLD_" not in r_r13_ins_nostore_fail["ins_statistics_derivation_source"],
            f"R13 INS missing store + caller FAIL ({lk_mode}) paired FAIL with HOLD label: {r_r13_ins_nostore_fail}",
        )

        cur_k_r13 = ins_base_r13["current_assay_evidence_record"]["archive_sha256" if lk_mode == "archive_sha256" else "record_id"]
        st_tamp_r13 = copy.deepcopy(st_base_r13)
        st_tamp_r13[cur_k_r13]["gsis_si"] = 9.9
        r_r13_ins_tamp_fail = evaluate_gate34_ins_l82i_elisa_pe2max(
            ins_base_r13, arm_manifest, trusted_evidence_store=st_tamp_r13
        )
        require_cond(
            r_r13_ins_tamp_fail["verdict"] == "FAIL"
            and r_r13_ins_tamp_fail["decision"] == "FAIL_EVIDENCE_STORE_MISMATCH"
            and r_r13_ins_tamp_fail["promotion_authorized"] is False
            and all(r_r13_ins_tamp_fail[k] is None for k in ins_official_stat_keys)
            and r_r13_ins_tamp_fail["ins_statistics_derivation_source"] == "WITHHELD_NO_AUTHENTICATED_ARCHIVE_WITH_INDEPENDENT_FAIL"
            and "_HOLD_" not in r_r13_ins_tamp_fail["ins_statistics_derivation_source"],
            f"R13 INS tampered store FAIL ({lk_mode}) paired FAIL with HOLD label: {r_r13_ins_tamp_fail}",
        )

        def _strip_ins_issuer(rec: dict[str, Any]) -> None:
            for ifld in INS_DONOR_ISSUER_FIELDS:
                rec["hla_allele_panel_records"].pop(ifld, None)

        ins_no_iss_fail, st_no_iss_fail = _reseal_module_mode(
            "ins",
            _strip_ins_issuer,
            store_key_mode=lk_mode,
            parent_mutator=lambda p: p.__setitem__("gsis_si", 1.0),
        )
        r_r13_ins_no_iss_fail = evaluate_gate34_ins_l82i_elisa_pe2max(
            ins_no_iss_fail, arm_manifest, trusted_evidence_store=st_no_iss_fail
        )
        require_cond(
            r_r13_ins_no_iss_fail["decision"] == "FAIL"
            and r_r13_ins_no_iss_fail["promotion_authorized"] is False
            and all(r_r13_ins_no_iss_fail[k] is None for k in ins_official_stat_keys)
            and r_r13_ins_no_iss_fail["ins_statistics_derivation_source"] == "WITHHELD_INCOMPLETE_ARCHIVE_WITH_INDEPENDENT_FAIL"
            and "_HOLD_" not in r_r13_ins_no_iss_fail["ins_statistics_derivation_source"],
            f"R13 INS missing archived issuer + caller FAIL ({lk_mode}) paired FAIL with HOLD label: {r_r13_ins_no_iss_fail}",
        )

    _rec("r13_shield_omitted_archived_peak_null_stats_hold", r_r13_sh_no_peak)
    _rec("r13_ins_missing_archive_independent_fail_withheld", r_r13_ins_no_arch_fail)
    _rec("r13_ins_missing_store_independent_fail_withheld", r_r13_ins_nostore_fail)
    _rec("r13_ins_tampered_store_fail_withheld", r_r13_ins_tamp_fail)
    _rec("r13_ins_missing_archived_issuer_independent_fail_withheld", r_r13_ins_no_iss_fail)

    # Round-14 Review Closure:
    # (1) Reject live GATE-32 role collision on upstream_lot_evidence_record across ALL 4 modules (require GATE-34);
    # (2) Enforce collision-free GATE-36-<MODULE> current-assay gate_sources;
    # (3) Require live GATE-32 (DEC-130 / GY-010) whole-islet-debris recall co-prerequisite on SHIELD!
    for lk_mode in ("record_id", "archive_sha256", "both"):
        sh_r14, st_r14 = make_authenticated_gate34_fixture_and_store("shield", arm_manifest=arm_manifest, store_key_mode=lk_mode)
        r_r14_ok = evaluate_gate34_shield_sel(sh_r14, arm_manifest, trusted_evidence_store=st_r14)
        require_cond(
            r_r14_ok["decision"] == "PASS"
            and r_r14_ok["promotion_authorized"] is True
            and sh_r14["upstream_lot_evidence_record"]["gate_source"] == "GATE-34"
            and sh_r14["current_assay_evidence_record"]["gate_source"] == "GATE-36-SHIELD"
            and sh_r14["live_gate32_debris_recall_record"]["gate_source"] == "GATE-32",
            f"R14 valid GATE-34 + GATE-36-SHIELD + live GATE-32 ({lk_mode}) failed: {r_r14_ok}",
        )

        # Missing live_gate32_debris_recall_record -> HOLD (HOLD_MISSING_LIVE_GATE32_WHOLE_DEBRIS_RECALL)
        sh_no_g32 = copy.deepcopy(sh_r14)
        sh_no_g32.pop("live_gate32_debris_recall_record")
        r_r14_missing = evaluate_gate34_shield_sel(sh_no_g32, arm_manifest, trusted_evidence_store=st_r14)
        require_cond(
            r_r14_missing["decision"] == "HOLD"
            and r_r14_missing["promotion_authorized"] is False
            and "HOLD_MISSING_LIVE_GATE32_WHOLE_DEBRIS_RECALL" in r_r14_missing["reasons"]
            and all(r_r14_missing[k] is None for k in shield_official_stat_keys)
            and r_r14_missing["shield_statistics_derivation_source"] == "UNVERIFIED_HOLD_NO_AUTHENTICATED_ARCHIVE",
            f"R14 missing live_gate32_debris_recall_record ({lk_mode}) failed: {r_r14_missing}",
        )

        # Missing live_gate32_debris_recall_record + independent FAIL -> FAIL (NEVER *_HOLD_* derivation source!)
        sh_no_g32_fail = copy.deepcopy(sh_no_g32)
        sh_no_g32_fail["off_target_kd_l95_um"] = 7.5
        r_r14_missing_fail = evaluate_gate34_shield_sel(sh_no_g32_fail, arm_manifest, trusted_evidence_store=st_r14)
        require_cond(
            r_r14_missing_fail["decision"] == "FAIL"
            and r_r14_missing_fail["promotion_authorized"] is False
            and all(r_r14_missing_fail[k] is None for k in shield_official_stat_keys)
            and r_r14_missing_fail["shield_statistics_derivation_source"] == "WITHHELD_NO_AUTHENTICATED_ARCHIVE_WITH_INDEPENDENT_FAIL"
            and "_HOLD_" not in r_r14_missing_fail["shield_statistics_derivation_source"],
            f"R14 missing live_gate32 + independent FAIL ({lk_mode}) failed: {r_r14_missing_fail}",
        )

        # Coherent partial-epitope-coverage HOLD_PARTIAL_EPITOPE_COVERAGE_GRADED_CAP -> HOLD, promotion_authorized=False
        sh_part = copy.deepcopy(sh_r14)
        g32_part = copy.deepcopy(sh_part["live_gate32_debris_recall_record"])
        g32_part.update({
            "decision": "HOLD_PARTIAL_EPITOPE_COVERAGE_GRADED_CAP",
            "authority_scope": "REJECTED_OR_HELD",
            "bank_qualified": False,
            "promotion_authorized": False,
            "debris_recall_verdict": "HOLD_PARTIAL_EPITOPE_COVERAGE_GRADED_CAP",
            "debris_recall_l95_suppressed_frac": 0.55,
            "residual_class2_recall_u95_frac": 0.45,
            "unrelated_recall_preserved": True,
        })
        sh_part["live_gate32_debris_recall_record"] = seal_evidence_record(g32_part)
        st_part = build_trusted_store_for_obs(sh_part, store_key_mode=lk_mode)
        r_r14_part = evaluate_gate34_shield_sel(sh_part, arm_manifest, trusted_evidence_store=st_part)
        require_cond(
            r_r14_part["decision"] == "HOLD"
            and r_r14_part["promotion_authorized"] is False
            and "HOLD_LIVE_GATE32_PARTIAL_EPITOPE_COVERAGE_GRADED_CAP" in r_r14_part["reasons"],
            f"R14 partial-coverage live GATE-32 ({lk_mode}) failed: {r_r14_part}",
        )

        # Below-threshold L95 < 0.70, residual > 0.30, unrelated_recall_preserved=False -> FAIL!
        for mut_name, g32_upd, exp_code in (
            ("l95_low", {"debris_recall_l95_suppressed_frac": 0.69}, "LIVE_GATE32_DEBRIS_RECALL_L95_BELOW_0P70_FAIL"),
            ("residual_high", {"residual_class2_recall_u95_frac": 0.31}, "LIVE_GATE32_RESIDUAL_CLASS2_RECALL_U95_GT_0P30_FAIL"),
            ("unrelated_false", {"unrelated_recall_preserved": False}, "LIVE_GATE32_UNRELATED_RECALL_NOT_PRESERVED_FAIL"),
        ):
            sh_bad = copy.deepcopy(sh_r14)
            g32_bad = copy.deepcopy(sh_bad["live_gate32_debris_recall_record"])
            g32_bad.update(g32_upd)
            sh_bad["live_gate32_debris_recall_record"] = seal_evidence_record(g32_bad)
            st_bad = build_trusted_store_for_obs(sh_bad, store_key_mode=lk_mode)
            r_bad = evaluate_gate34_shield_sel(sh_bad, arm_manifest, trusted_evidence_store=st_bad)
            require_cond(
                r_bad["decision"] == "FAIL"
                and r_bad["promotion_authorized"] is False
                and any(exp_code in r for r in r_bad["reasons"]),
                f"R14 live GATE-32 {mut_name} ({lk_mode}) failed: {r_bad}",
            )
            if mut_name == "l95_low":
                r_r14_l95_fail = r_bad
            elif mut_name == "residual_high":
                r_r14_res_fail = r_bad
            else:
                r_r14_unrel_fail = r_bad

        # Live GATE-32 role collision on upstream_lot_evidence_record -> explicit FAIL across ALL 4 modules!
        sh_coll = copy.deepcopy(sh_r14)
        up_coll = copy.deepcopy(sh_coll["upstream_lot_evidence_record"])
        up_coll["gate_source"] = "GATE-32"
        sh_coll["upstream_lot_evidence_record"] = seal_evidence_record(up_coll)
        st_coll = build_trusted_store_for_obs(sh_coll, store_key_mode=lk_mode)
        r_r14_coll = evaluate_gate34_shield_sel(sh_coll, arm_manifest, trusted_evidence_store=st_coll)
        require_cond(
            r_r14_coll["decision"] == "FAIL"
            and r_r14_coll["promotion_authorized"] is False
            and any("LIVE_GATE32_ROLE_COLLISION_REJECTED" in r for r in r_r14_coll["reasons"]),
            f"R14 upstream GATE-32 role collision ({lk_mode}) failed: {r_r14_coll}",
        )

    _rec("r14_shield_live_gate32_debris_recall_full_credit_pass", r_r14_ok)
    _rec("r14_shield_missing_live_gate32_debris_recall_hold", r_r14_missing)
    _rec("r14_shield_missing_live_gate32_plus_independent_fail_withheld", r_r14_missing_fail)
    _rec("r14_shield_live_gate32_partial_coverage_graded_cap_hold", r_r14_part)
    _rec("r14_shield_live_gate32_l95_below_0p70_fail", r_r14_l95_fail)
    _rec("r14_shield_live_gate32_residual_gt_0p30_fail", r_r14_res_fail)
    _rec("r14_shield_live_gate32_unrelated_recall_false_fail", r_r14_unrel_fail)
    _rec("r14_upstream_live_gate32_role_collision_rejected_fail", r_r14_coll)

    expected = {
        "shield_synthetic_15uM_self_test_no_promo": {"decision": "SYNTHETIC_SELF_TEST_PASS", "promotion_authorized": False},
        "shield_missing_manifest_fail": {"decision": "FAIL", "promotion_authorized": False},
        "shield_l95_7p5uM_u95_15uM_review_probe_fail": {"decision": "FAIL", "promotion_authorized": False},
        "shield_1nM_peak_2000nM_trough_fail": {"decision": "FAIL", "promotion_authorized": False},
        "shield_plasma_trough_lt_dln_trough_fail": {"decision": "FAIL", "promotion_authorized": False},
        "shield_kd_on_1e_320_underflow_fail": {"decision": "FAIL", "promotion_authorized": False},
        "shield_5000x_selectivity_fail": {"decision": "FAIL", "promotion_authorized": False},
        "shield_q84d_relabeled_q28d_dataset_fail": {"decision": "FAIL", "promotion_authorized": False},
        "shield_q84d_2nM_fail": {"decision": "FAIL", "promotion_authorized": False},
        "shield_q84d_unmeasured_human_pk_fail": {"decision": "FAIL", "promotion_authorized": False},
        "shield_design_a_arm_fail": {"decision": "FAIL", "promotion_authorized": False},
        "ins_synthetic_self_test_no_promo": {"decision": "SYNTHETIC_SELF_TEST_PASS", "promotion_authorized": False},
        "ins_4_duplicated_donors_across_3_alleles_fail": {"decision": "FAIL", "promotion_authorized": False},
        "ins_hla_binding_false_fail": {"decision": "FAIL", "promotion_authorized": False},
        "ins_design_a_exposed_fail": {"decision": "FAIL", "promotion_authorized": False},
        "ins_pe4max_mlh1dn_fail": {"decision": "FAIL", "promotion_authorized": False},
        "cuff_synthetic_3protein_self_test_no_promo": {"decision": "SYNTHETIC_SELF_TEST_PASS", "promotion_authorized": False},
        "cuff_1protein_manifest_fail": {"decision": "FAIL", "promotion_authorized": False},
        "cuff_zero_efferocytosis_fail": {"decision": "FAIL", "promotion_authorized": False},
        "cuff_zero_pericyte_fail": {"decision": "FAIL", "promotion_authorized": False},
        "cuff_cd200r_accessibility_false_fail": {"decision": "FAIL", "promotion_authorized": False},
        "cuff_design_a_exposed_fail": {"decision": "FAIL", "promotion_authorized": False},
        "invvax_synthetic_self_test_no_promo": {"decision": "SYNTHETIC_SELF_TEST_PASS", "promotion_authorized": False},
        "invvax_single_dose_minus7_fail": {"decision": "FAIL", "promotion_authorized": False},
        "invvax_duplicate_matrix_assay_id_fail": {"decision": "FAIL", "promotion_authorized": False},
        "invvax_post_tx_day_plus1_fail": {"decision": "FAIL", "promotion_authorized": False},
        "invvax_llod_1e6_fail": {"decision": "FAIL", "promotion_authorized": False},
        "invvax_design_a_exposed_fail": {"decision": "FAIL", "promotion_authorized": False},
        "auth_without_store_holds_no_promo": {"decision": "HOLD_UNRESOLVED_TRUSTED_EVIDENCE_STORE", "promotion_authorized": False},
        "auth_with_upstream_only_store_holds_no_promo": {"decision": "HOLD_UNRESOLVED_TRUSTED_EVIDENCE_STORE", "promotion_authorized": False},
        "auth_store_promotion_false_tamper_fail": {"decision": "FAIL_EVIDENCE_STORE_MISMATCH", "promotion_authorized": False},
        "auth_with_verified_dual_store_authorizes": {"decision": "PASS", "promotion_authorized": True},
        "r5_shield_archive_apc_100pct_vs_parent_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r5_shield_archive_14p9999999995uM_zero_tol_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r5_ins_archive_bystander_100pct_vs_parent_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r5_ins_archive_gsis_1p0_vs_parent_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r5_ins_archive_4donors_vs_12_claimed_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r5_cuff_archive_serum_killing_100pct_vs_parent_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r5_cuff_archive_c4b2a_14pct_vs_parent_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r5_cuff_archive_eff_79p9999995_zero_tol_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r5_invvax_archive_ae_grade5_vs_parent_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r5_invvax_archive_conc_at_llod_zero_tol_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r5_store_conflicting_index_aliases_fail": {"decision": "FAIL_EVIDENCE_STORE_MISMATCH", "promotion_authorized": False},
        "r5_contradictory_physical_qual_false_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r8_ins_12_distinct_canonical_donors_pass": {"decision": "PASS", "promotion_authorized": True},
        "r8_ins_4donors_whitespace_padded_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r8_ins_4donors_case_variants_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r8_ins_4donors_unicode_nfkc_invisibles_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r8_ins_4donors_separator_variants_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r8_ins_reactive_noncanonical_donor_id_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r9_ins_4donors_digit_separator_0_1_both_rosters_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r9_ins_4donors_digit_separator_d101_both_rosters_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r9_ins_roster_issuer_identity_mismatch_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r9_ins_12_distinct_donors_both_rosters_same_issuer_pass": {"decision": "PASS", "promotion_authorized": True},
        "r10_ins_both_rosters_omitted_issuer_hold": {"decision": "HOLD", "promotion_authorized": False},
        "r10_ins_single_form_archived_omitted_issuer_hold": {"decision": "HOLD", "promotion_authorized": False},
        "r10_ins_archive_one_form_omitted_issuer_hold": {"decision": "HOLD", "promotion_authorized": False},
        "r10_ins_current_omitted_issuer_vs_archived_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r10_ins_both_rosters_positive_hla_registry_issuer_pass": {"decision": "PASS", "promotion_authorized": True},
        "r11_ins_caller_only_reactive_preserves_archive_u95_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r11_ins_missing_archive_null_verified_stats_hold": {"decision": "HOLD", "promotion_authorized": False},
        "r11_ins_missing_trusted_store_null_verified_stats_hold": {"decision": "HOLD_UNRESOLVED_TRUSTED_EVIDENCE_STORE", "promotion_authorized": False},
        "r11_ins_internal_archive_conflict_null_verified_stats_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r11_ins_archive_1of12_reactive_matched_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r11_shield_caller_only_adverse_preserves_archive_ro_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r11_shield_missing_store_null_verified_stats_hold": {"decision": "HOLD_UNRESOLVED_TRUSTED_EVIDENCE_STORE", "promotion_authorized": False},
        "r12_shield_omitted_archived_study_id_null_stats_hold": {"decision": "HOLD", "promotion_authorized": False},
        "r12_shield_omitted_archived_study_id_independent_fail_withheld": {"decision": "FAIL", "promotion_authorized": False},
        "r12_shield_archived_trough_gt_peak_null_stats_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r12_shield_archived_regimen_interval_conflict_null_stats_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r12_shield_archived_7p5uM_metric_conflict_null_stats_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r12_ins_omitted_archived_study_id_null_stats_hold": {"decision": "HOLD", "promotion_authorized": False},
        "r13_shield_omitted_archived_peak_null_stats_hold": {"decision": "HOLD", "promotion_authorized": False},
        "r13_ins_missing_archive_independent_fail_withheld": {"decision": "FAIL", "promotion_authorized": False},
        "r13_ins_missing_store_independent_fail_withheld": {"decision": "FAIL", "promotion_authorized": False},
        "r13_ins_tampered_store_fail_withheld": {"decision": "FAIL_EVIDENCE_STORE_MISMATCH", "promotion_authorized": False},
        "r13_ins_missing_archived_issuer_independent_fail_withheld": {"decision": "FAIL", "promotion_authorized": False},
        "r14_shield_live_gate32_debris_recall_full_credit_pass": {"decision": "PASS", "promotion_authorized": True},
        "r14_shield_missing_live_gate32_debris_recall_hold": {"decision": "HOLD", "promotion_authorized": False},
        "r14_shield_missing_live_gate32_plus_independent_fail_withheld": {"decision": "FAIL", "promotion_authorized": False},
        "r14_shield_live_gate32_partial_coverage_graded_cap_hold": {"decision": "HOLD", "promotion_authorized": False},
        "r14_shield_live_gate32_l95_below_0p70_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r14_shield_live_gate32_residual_gt_0p30_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r14_shield_live_gate32_unrelated_recall_false_fail": {"decision": "FAIL", "promotion_authorized": False},
        "r14_upstream_live_gate32_role_collision_rejected_fail": {"decision": "FAIL", "promotion_authorized": False},
    }
    require_cond(cases == expected, f"Gate 36 self-test mismatch: {cases}")
    return {
        "synthetic_fixture_self_test_only": True,
        "certifies_wetlab_lot": False,
        "synthetic_fixtures_never_authorize_promotion": True,
        "all_passed": True,
        "total_cases": len(cases),
        "cases": cases,
    }


# ---------------------------------------------------------------------------
# Portable Payload SHA-256 & Cross-Surface Receipt Builder
# ---------------------------------------------------------------------------
def portable_projection(receipt: dict[str, Any]) -> dict[str, Any]:
    proj = copy.deepcopy(receipt)
    proj.pop("portable_payload_sha256", None)
    rt = proj.get("runtime_environment")
    if isinstance(rt, dict):
        rt.pop("python_version", None)
    return proj


def compute_portable_payload_sha256(receipt: dict[str, Any]) -> str:
    canonical = json.dumps(portable_projection(receipt), sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    return sha256_str(canonical)


def build_verification_receipt(
    repo_root: Path,
    *,
    standalone: bool,
    shared_dir: Path | None = None,
    master_contract_path: Path | None = None,
    arm_manifest_path: Path | None = None,
    openislet_root: Path | None = None,
) -> dict[str, Any]:
    fasta_path = repo_root / "data" / "constructs" / "openislet_foundry_v2_cuff_v2_and_shield_fc_v0.9.0.fasta"
    coords_path = repo_root / "data" / "structures" / "rcsb_shield_interface_coords_v0.9.0.json"
    sc_path = repo_root / "data" / "protocols" / "iip0057_foundry_v2_h3_side_contract_v0.9.0.json"
    proto_path = repo_root / "docs" / "GATE-36-FOUNDRY-V2-SHIELD-INVVAX-INSL82I-CUFFV2-PROTOCOL.md"
    gy_path = repo_root / "data" / "protocols" / "iip0057_gy035_entry.json"

    contract_p, manifest_p = resolve_release_shared_paths(
        repo_root,
        shared_dir=shared_dir,
        master_contract_path=master_contract_path,
        arm_manifest_path=arm_manifest_path,
    )

    require_cond(fasta_path.is_file(), f"Missing required FASTA: {fasta_path}")
    require_cond(coords_path.is_file(), f"Missing required RCSB coords JSON: {coords_path}")
    require_cond(sc_path.is_file(), f"Missing required side contract: {sc_path}")
    require_cond(proto_path.is_file(), f"Missing required GATE-34 protocol doc: {proto_path}")
    require_cond(gy_path.is_file(), f"Missing required GY-034 entry JSON: {gy_path}")

    lims_live_checked = False
    if not standalone:
        lims_root = openislet_root.resolve() if openislet_root is not None else repo_root
        for rel_lims, exp_sha in FROZEN_LIMS_SHA256.items():
            p_lims = lims_root / rel_lims
            if not p_lims.is_file():
                raise FileNotFoundError(
                    f"REPO_CROSSCHECK mode requires frozen LIMS file {p_lims} "
                    f"(pass --standalone for isolated staging verification or --openislet-root <repo>)."
                )
            got_sha = sha256_file(p_lims)
            require_cond(got_sha == exp_sha, f"Frozen LIMS SHA-256 mismatch on {rel_lims}: {got_sha} != {exp_sha}")
        lims_live_checked = True

    arm_manifest, manifest_sha = load_and_verify_arm_manifest(manifest_p)
    master_contract, contract_sha, contract_file_sha = load_and_verify_master_contract(contract_p, manifest_sha)

    fasta_records = parse_fasta_text(fasta_path.read_text(encoding="utf-8"))
    sc_obj = load_strict_json(sc_path)
    proto_text = proto_path.read_text(encoding="utf-8")
    gy_obj = load_strict_json(gy_path)

    # Cross-check companion artifacts (side contract, protocol doc, GY-035 [staged gy035_entry.json])
    require_cond(
        sc_obj.get("proposal_id") == "IIP-0057"
        and sc_obj.get("decision_id") == "DEC-138"
        and sc_obj.get("gate_id") == "GATE-36"
        and sc_obj.get("graveyard_card_id") == "GY-035",
        "Side contract provisional Round-14 ID mismatch (expected IIP-0057 / DEC-138 / GATE-36 / GY-035)",
    )
    require_cond(sc_obj["zero_lims_touch_compliance"]["deposited_fasta_sha256"] == EXPECTED_FASTA_SHA256, "Side contract FASTA SHA-256 mismatch")
    require_cond(sc_obj["zero_lims_touch_compliance"]["rcsb_coords_sha256"] == EXPECTED_RCSB_COORDS_SHA256, "Side contract RCSB coords SHA-256 mismatch")
    require_cond(sc_obj["zero_lims_touch_compliance"]["canonical_arm_manifest_sha256"] == EXPECTED_ARM_MANIFEST_SHA256, "Side contract manifest SHA-256 mismatch")
    require_cond(sc_obj["zero_lims_touch_compliance"]["canonical_arm_manifest_canonical_json_sha256"] == EXPECTED_ARM_MANIFEST_CANONICAL_JSON_SHA256, "Side contract manifest canonical SHA-256 mismatch")
    require_cond(sc_obj["zero_lims_touch_compliance"]["wave6_master_contract_sha256"] == EXPECTED_MASTER_CONTRACT_SHA256, "Side contract master contract SHA-256 mismatch")
    require_cond(sc_obj["zero_lims_touch_compliance"]["wave6_master_contract_file_sha256"] == EXPECTED_MASTER_CONTRACT_FILE_SHA256, "Side contract master contract file SHA-256 mismatch")
    require_cond(sc_obj["governance_and_invariants"]["design_a_zero_additional_biologics_beyond_v080_catalase_hydrogel"] is True, "Design A zero-additional-biologics invariant missing")
    require_cond(sc_obj["governance_and_invariants"]["design_a_contains_preexisting_p04040_catalase_hydrogel"] is True, "Design A catalase disclosure missing")
    require_cond(sc_obj["governance_and_invariants"]["design_a_strictly_zero_protein_biologics"] is False, "Design A strict protein biologic flag mismatch")
    require_cond(sc_obj["governance_and_invariants"]["gy_021_enforced_pe2max_only_no_pe4max_mlh1dn"] is True, "GY-021 PE2max invariant missing")
    common_inv = sc_obj["executable_gate_34_subgates"]["common_promotion_and_manifest_invariants"]
    require_cond(
        common_inv["unified_evidence_schema_revision"] == UPSTREAM_EVIDENCE_SCHEMA_REVISION
        and common_inv["zero_threshold_crossing_tolerance_enforced"] is True
        and common_inv["alias_consistent_trusted_store_lookup_enforced"] is True
        and common_inv["contradictory_producer_flags_rejected"] is True
        and common_inv["all_governing_measurements_derived_from_verified_current_assay_archive"] is True
        and common_inv.get("upstream_lot_release_gate_source") == CANONICAL_UPSTREAM_GATE34_SOURCE
        and common_inv.get("rejected_upstream_role_collision_source") == CANONICAL_LIVE_GATE32_DEBRIS_RECALL_SOURCE
        and common_inv.get("module_current_assay_gate_sources") == CANONICAL_GATE36_MODULE_SOURCES,
        "Side contract Round-14 common invariants / gate source de-collision mismatch",
    )
    sh_gate = sc_obj["executable_gate_34_subgates"]["Gate_34_SHIELD_SEL"]
    require_cond(
        sh_gate["off_target_kd_l95_um_min"] == 15.0
        and sh_gate["selectivity_ratio_l95_min"] == 15000.0
        and sh_gate["on_target_kd_u95_nm_calibrated_floor"] == MIN_CALIBRATED_KD_ON_NM
        and sh_gate.get("official_statistics_strictly_authenticated_archive_only") is True
        and sh_gate.get("null_official_statistics_on_unverified_or_conflict") is True
        and sh_gate.get("archive_completeness_required_before_official_statistics") is True
        and sh_gate.get("all_internal_archive_consistency_checks_required_before_official_statistics") is True
        and sh_gate.get("caller_reconciliation_separated_from_archive_gating") is True
        and sh_gate.get("omitted_peak_never_substitutes_trough_for_ro_agreement") is True
        and sh_gate.get("fail_verdict_never_emits_hold_derivation_source") is True
        and sh_gate.get("live_gate32_debris_recall_required") is True
        and sh_gate.get("live_gate32_gate_source") == CANONICAL_LIVE_GATE32_DEBRIS_RECALL_SOURCE
        and sh_gate.get("live_gate32_required_verdict") == "PASS_DEBRIS_RECALL_FULL_CREDIT"
        and sh_gate.get("live_gate32_min_l95_suppressed_frac") == LIVE_GATE32_MIN_L95_SUPPRESSED_FRAC
        and sh_gate.get("live_gate32_max_residual_class2_u95_frac") == LIVE_GATE32_MAX_RESIDUAL_CLASS2_U95_FRAC
        and sh_gate.get("live_gate32_unrelated_recall_preserved_required") is True
        and sh_gate.get("live_gate32_missing_hold_code") == "HOLD_MISSING_LIVE_GATE32_WHOLE_DEBRIS_RECALL"
        and set(sh_gate.get("shield_statistics_derivation_sources", [])) == set(SHIELD_STATISTICS_DERIVATION_SOURCES),
        "Side contract Round-14 SHIELD L95/15,000x/1fM floor, live GATE-32 debris-recall co-prerequisite, & complete/consistent archive-only stats mismatch",
    )
    ins_gate = sc_obj["executable_gate_34_subgates"]["Gate_34_INS_L82I_ELISA_PE2MAX"]
    require_cond(
        ins_gate["min_unique_hla_donors"] == 12
        and ins_gate["governed_kit_catalog_allowlist_enforced"] is True
        and ins_gate.get("canonical_donor_id_grammar") == CANONICAL_DONOR_ID_PATTERN
        and ins_gate.get("canonical_donor_id_ascii_nfkc_no_czm_required") is True
        and ins_gate.get("canonical_donor_id_casefold_and_separator_deduplication_required") is True
        and ins_gate.get("canonical_donor_id_equivalence_order") == CANONICAL_DONOR_EQUIVALENCE_ORDER
        and ins_gate.get("inconsistent_donor_id_formatting_fail_code") == "INS_INCONSISTENT_DONOR_ID_FORMATTING_VARIANT"
        and ins_gate.get("shared_donor_issuer_identity_across_rosters_required") is True
        and ins_gate.get("positive_canonical_issuer_required_every_present_roster_form") is True
        and ins_gate.get("none_equals_none_issuer_equivalence_prohibited") is True
        and ins_gate.get("omitted_archived_issuer_decision") == "HOLD"
        and ins_gate.get("omitted_archived_issuer_hold_code") == "HOLD_MISSING_ARCHIVED_HLA_REGISTRY_ISSUER"
        and ins_gate.get("omitted_current_issuer_vs_archived_fail_code") == "INS_MISSING_CURRENT_HLA_REGISTRY_ISSUER"
        and ins_gate.get("official_statistics_strictly_authenticated_archive_only") is True
        and ins_gate.get("null_official_statistics_on_unverified_hold_or_internal_conflict") is True
        and ins_gate.get("archive_completeness_required_before_official_statistics") is True
        and ins_gate.get("caller_statistics_isolated_in_unverified_fields") is True
        and ins_gate.get("fail_verdict_never_emits_hold_derivation_source") is True
        and set(ins_gate.get("ins_statistics_derivation_sources", [])) == set(INS_STATISTICS_DERIVATION_SOURCES),
        "Side contract Round-13 INS canonical donor ID, mandatory positive roster issuer, FAIL-vs-HOLD source discipline, & complete archive-only official statistics gate mismatch",
    )
    cuff_gate = sc_obj["executable_gate_34_subgates"]["Gate_34_CUFF_V2_DISULFIDE_C5B9"]
    require_cond(
        cuff_gate["gy025_min_exact_stack_efferocytosis_abs_pct"] == 80.0
        and cuff_gate["gy025_min_exact_stack_efferocytosis_pct_of_wt"] == 70.0
        and cuff_gate["gy025_min_exact_stack_pericyte_recruitment_pct_of_wt"] == 70.0,
        "Side contract Round-5 Cuff GY-025 exact-stack efferocytosis/pericyte mismatch",
    )
    iv_gate = sc_obj["executable_gate_34_subgates"]["Gate_34_INVVAX_RECALL"]
    require_cond(iv_gate["required_administration_count"] == 3 and iv_gate["distinct_matrix_assay_registries_required"] is True, "Side contract Round-5 InvVax 3-dose/matrix registry mismatch")
    for tok in (
        "off_target_kd_l95_um", "15,000", "0.10", "4.00", "K562", "7AL7",
        "efferocytosis", "pericyte", "lymph_node_assay_id", "v2_round5_unified",
        "viral-receptor-avoidance", "CONFLICTING_TRUSTED_STORE_INDEX_ALIASES",
        "Product-of-Caps", CANONICAL_DONOR_ID_PATTERN, "INS_NONCANONICAL_DONOR_ID_REJECTED",
        "INS_INCONSISTENT_DONOR_ID_FORMATTING_VARIANT", "donor_issuer_id",
        "hla_registry_issuer", "HOLD_MISSING_ARCHIVED_HLA_REGISTRY_ISSUER",
        "INS_MISSING_CURRENT_HLA_REGISTRY_ISSUER",
        "AUTHENTICATED_ARCHIVE_ROSTER_VERIFIED",
        "AUTHENTICATED_ARCHIVE_ONLY_CALLER_CONFLICT",
        "UNVERIFIED_HOLD_NO_AUTHENTICATED_ARCHIVE",
        "UNVERIFIED_HOLD_MISSING_ARCHIVED_ISSUER",
        "UNVERIFIED_HOLD_INCOMPLETE_ARCHIVE",
        "WITHHELD_NO_AUTHENTICATED_ARCHIVE_WITH_INDEPENDENT_FAIL",
        "WITHHELD_INCOMPLETE_ARCHIVE_WITH_INDEPENDENT_FAIL",
        "WITHHELD_INTERNAL_ARCHIVE_CONFLICT",
        "caller_reported_unverified_u95_pct",
        "GATE-36-SHIELD", "GATE-36-INS", "GATE-36-CUFF", "GATE-36-INVVAX",
        "PASS_DEBRIS_RECALL_FULL_CREDIT", "HOLD_MISSING_LIVE_GATE32_WHOLE_DEBRIS_RECALL",
        "HOLD_PARTIAL_EPITOPE_COVERAGE_GRADED_CAP", "Test 2B", "Test 2A", "Test 3", "Test 1", "GY-032",
    ):
        require_cond(tok in proto_text, f"GATE-36 protocol missing mandatory Round-14 term: {tok}")
    require_cond("kd_off_u95_nm" not in proto_text and "Viral-Safe" not in proto_text, "GATE-36 protocol retains retired wording")
    require_cond(gy_obj.get("graveyard_card_id") == "GY-035" and gy_obj.get("severity_level") == "BLOCK", "GY-035 schema mismatch")

    checked_inputs: dict[str, str] = {
        "fasta_sha256": sha256_file(fasta_path),
        "rcsb_coords_sha256": sha256_file(coords_path),
        "side_contract_sha256": sha256_file(sc_path),
        "protocol_doc_sha256": sha256_file(proto_path),
        "gy035_entry_sha256": sha256_file(gy_path),
        "canonical_arm_manifest_sha256": manifest_sha,
        "wave6_master_contract_canonical_sha256": contract_sha,
        "wave6_master_contract_file_sha256": contract_file_sha,
    }

    part_a = verify_part_a(fasta_records, coords_path)
    part_b = verify_part_b()
    part_c = verify_part_c(fasta_path, fasta_records)
    part_d = verify_part_d(master_contract, contract_sha, manifest_sha)
    gate_tests = run_gate34_self_tests(arm_manifest)

    receipt: dict[str, Any] = {
        "schema_version": SCHEMA_VERSION,
        "staging_slot": "W6-C3 (iip0057)",
        "proposal_id": "IIP-0057",
        "decision_id": "DEC-138",
        "gate_id": "GATE-36",
        "graveyard_card_id": "GY-035",
        "upstream_lot_release_gate_source": CANONICAL_UPSTREAM_GATE34_SOURCE,
        "live_gate32_debris_recall_co_prerequisite": CANONICAL_LIVE_GATE32_DEBRIS_RECALL_SOURCE,
        "module_current_assay_gate_sources": dict(CANONICAL_GATE36_MODULE_SOURCES),
        "generated_date": GENERATED_DATE,
        "mode": "STANDALONE" if standalone else "REPO_CROSSCHECK",
        "live_frozen_lims_files_checked": lims_live_checked,
        "computational_replay_status": "REPRODUCED_COMPUTATIONAL_SENSITIVITY_PENDING_WETLAB",
        "certifies_manufactured_lot_or_clinical_efficacy": False,
        "runtime_environment": {
            "python_version": sys.version.split()[0],
            "optimize_flag_verified_byte_identical": True,
            "portable_comparison_ignored_fields": ["runtime_environment.python_version", "portable_payload_sha256"],
            "portable_check_cli_flag": "--check-portable",
        },
        "zero_lims_touch_invariants": {
            "frozen_lims_sha256_pins": FROZEN_LIMS_SHA256,
            "core_3arm_and_layer1_delta_pp": 0.0,
            "h1_allo_locked_pct": 88.0,
            "design_a_zero_additional_biologics_beyond_v080_catalase_hydrogel": True,
            "design_a_contains_preexisting_p04040_catalase_hydrogel": True,
            "design_a_strictly_zero_protein_biologics": False,
            "design_a_preexisting_catalase_hydrogel_exception_disclosed": True,
            "design_a_invariant_tuple": [0.88, 0.78, 0.57, 0.69],
        },
        "checked_inputs_sha256": checked_inputs,
        "part_a_foundry_v2_islet_shield": part_a,
        "part_b_ins_pLeu82Ile_pe2max_elisa_dr4_a1101": part_b,
        "part_c_pruned_viral_receptor_avoidance_cuff_v2": part_c,
        "part_d_invvax_h3_sensitivity_and_master_parity": part_d,
        "part_e_gate34_adjudicator_synthetic_self_tests": gate_tests,
    }
    receipt["portable_payload_sha256"] = compute_portable_payload_sha256(receipt)
    return receipt


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="W6-C3 Provisional IIP-0057 / DEC-138 / GATE-36 / GY-035 Verifier (Round-14)")
    parser.add_argument(
        "--standalone",
        action="store_true",
        help="Run standalone offline verification (skips live LIMS repo file hashing; still hash-verifies canonical arm manifest & master contract)",
    )
    parser.add_argument("--check", action="store_true", help="Verify existing receipt is byte-exact (fail-closed)")
    parser.add_argument("--check-portable", action="store_true", help="Verify semantic equality and mandatory portable_payload_sha256 ignoring python_version (fail-closed)")
    parser.add_argument("--repo-root", type=Path, default=Path(__file__).resolve().parents[1], help="Root directory containing data/, docs/, scripts/")
    parser.add_argument("--shared-dir", type=Path, default=None, help="Directory containing wave6_canonical_arm_manifest.json and wave6_master_contract.json")
    parser.add_argument("--master-contract", type=Path, default=None, help="Explicit path to wave6_master_contract.json")
    parser.add_argument("--arm-manifest", type=Path, default=None, help="Explicit path to wave6_canonical_arm_manifest.json")
    parser.add_argument("--openislet-root", type=Path, default=None, help="Live OpenIslet repo root for REPO_CROSSCHECK mode (when --standalone is omitted)")
    parser.add_argument("--output", type=Path, default=None, help="Output/checked receipt JSON path")
    args = parser.parse_args(argv)

    repo_root = args.repo_root.resolve()
    require_cond(repo_root.is_dir(), f"Invalid --repo-root directory: {repo_root}")
    out_path = args.output.resolve() if args.output is not None else (repo_root / "data" / "extracted" / f"{SCHEMA_VERSION}.json")

    receipt = build_verification_receipt(
        repo_root,
        standalone=bool(args.standalone),
        shared_dir=args.shared_dir,
        master_contract_path=args.master_contract,
        arm_manifest_path=args.arm_manifest,
        openislet_root=args.openislet_root,
    )
    rendered = json.dumps(receipt, indent=2, ensure_ascii=False) + "\n"

    if args.check:
        if not out_path.is_file():
            raise FileNotFoundError(f"--check failed (fail-closed): expected receipt missing: {out_path}")
        existing_bytes = out_path.read_bytes()
        if existing_bytes != rendered.encode("utf-8"):
            raise RuntimeError(f"--check failed (fail-closed): byte mismatch against {out_path.name}")
        print(
            f"PASS (--check byte-exact): receipt={out_path.name} mode={receipt['mode']} "
            f"sha256={sha256_bytes(existing_bytes)} portable_payload_sha256={receipt['portable_payload_sha256']} "
            f"(optimize={sys.flags.optimize})"
        )
        return 0

    if args.check_portable:
        if not out_path.is_file():
            raise FileNotFoundError(f"--check-portable failed (fail-closed): expected receipt missing: {out_path}")
        existing = load_strict_json(out_path)
        require_cond(isinstance(existing, dict), f"Malformed receipt in {out_path.name}")
        require_cond(
            isinstance(existing.get("portable_payload_sha256"), str) and len(existing["portable_payload_sha256"]) == 64,
            "--check-portable failed (fail-closed): missing or malformed portable_payload_sha256",
        )
        rt = existing.get("runtime_environment")
        require_cond(isinstance(rt, dict) and isinstance(rt.get("python_version"), str), "Missing runtime_environment.python_version")
        existing_psha = compute_portable_payload_sha256(existing)
        fresh_psha = receipt["portable_payload_sha256"]
        require_cond(portable_projection(existing) == portable_projection(receipt), "--check-portable failed: semantic projection mismatch")
        require_cond(existing.get("portable_payload_sha256") == fresh_psha and existing_psha == fresh_psha, "--check-portable failed: portable_payload_sha256 mismatch")
        print(
            f"PASS (--check-portable semantic match): receipt={out_path.name} mode={receipt['mode']} "
            f"portable_payload_sha256={fresh_psha} (optimize={sys.flags.optimize})"
        )
        return 0

    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(rendered, encoding="utf-8")
    print(
        f"PASS (wrote receipt): receipt={out_path.name} mode={receipt['mode']} "
        f"sha256={sha256_str(rendered)} portable_payload_sha256={receipt['portable_payload_sha256']} "
        f"(optimize={sys.flags.optimize})"
    )
    return 0


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