#!/usr/bin/env python3 """ Standalone Zero-LIMS-Touch Executable Verifier for IIP-0060 / DEC-141 / GATE-39: Cuff Humoral Multi-Stratum Coverage Reconciliation, Product-Bound Omission Guard, Anti-PEG Upper-Tail Titre Characterization, and DAY28 Primed-Serum Disambiguation. Zero wetlab_contract.py imports; zero mutations to frozen LIMS contracts, ingest_wetlab_results.py, FASTAs, 36 Idea Graveyard rules, or live odds (+0.00 pp). Deterministic under -B and -O -B. """ from __future__ import annotations import argparse import hashlib import json import math import sys from pathlib import Path from typing import Any ROOT = Path(__file__).resolve().parent.parent SIDE_CONTRACT_PATH = ( ROOT / "data" / "protocols" / "iip0060_cuff_stratum_coverage_side_contract_v0.9.0.json" ) DEFAULT_RECEIPT_PATH = ( ROOT / "data" / "extracted" / "iip0060_cuff_stratum_coverage_verification_v0.9.0.json" ) def clopper_pearson_u95_zero_failures(n: int, eta: float = 1.0) -> float: if n <= 0 or eta <= 0.0: return 1.0 return min(1.0, (1.0 - (0.05 ** (1.0 / n))) / eta) def evaluate_gate39_cuff_coverage(lot_manifest: dict[str, Any], side_contract: dict[str, Any]) -> dict[str, Any]: """Fail-closed evaluation of cross-stratum cuff humoral coverage on a Stage-0 lot manifest.""" reasons: list[str] = [] warnings: list[str] = [] product_id = str(lot_manifest.get("product_id", "")) cuff_present = lot_manifest.get("cuff_present") cuff_arm = lot_manifest.get("cuff_bioconjugation_arm") rules = side_contract["cuff_arm_and_product_binding_rules"] # 1. Explicit non-cuff protection (never over-block non-cuff lots like un-cuffed Design Z or strict Design A) if cuff_present is False: return { "verdict": "NOT_APPLICABLE_NON_CUFF_LOT", "pass": True, "reasons": [], "warnings": [], "diagnostics": {"product_id": product_id, "cuff_present": False}, } if cuff_present is not True: return { "verdict": "HOLD_UNDECLARED_CUFF_PRESENCE", "pass": False, "reasons": ["HOLD_UNDECLARED_CUFF_PRESENCE: lot manifest must explicitly declare boolean cuff_present."], "warnings": [], "diagnostics": {"product_id": product_id}, } # 2. Enforce Wave-6 Design A strict zero-additional-biologics boundary (no Cuff v2.0 on Design A) if product_id in set(rules["design_a_product_ids"]) and cuff_arm == "CUFF_V2_ACELLULAR_SCR1_THBD_CD200": return { "verdict": "BLOCK_DESIGN_A_ZERO_ADDITIONAL_BIOLOGIC_BOUNDARY", "pass": False, "reasons": [ "BLOCK_DESIGN_A_ZERO_ADDITIONAL_BIOLOGIC_BOUNDARY: Design A forbids Cuff v2.0 additional biologics (wave6_canonical_arm_manifest.json)." ], "warnings": [], "diagnostics": {"product_id": product_id, "cuff_bioconjugation_arm": cuff_arm}, } lot_id = lot_manifest.get("lot_id") device_scope = lot_manifest.get("assembled_device_lot_scope") if not lot_id or not device_scope: reasons.append("HOLD_MISSING_LOT_OR_DEVICE_SCOPE: lot_id and assembled_device_lot_scope required for cross-stratum reconciliation.") batches = lot_manifest.get("stratum_batch_receipts") if not isinstance(batches, list) or len(batches) == 0: return { "verdict": "HOLD_CUFF_OMISSION_BYPASS_BLOCKED", "pass": False, "reasons": [ "HOLD_CUFF_OMISSION_BYPASS_BLOCKED: cuff_present=True lot submitted zero cuff stratum batch receipts (omission bypass blocked regardless of opt-in boolean)." ], "warnings": [], "diagnostics": {"product_id": product_id, "cuff_present": True, "submitted_strata": []}, } allowed_strata = set(side_contract["allowed_cuff_serum_challenge_strata"]) sa_bearing = cuff_arm in set(rules["streptavidin_bearing_cuff_arms"]) sa_free_arm = cuff_arm in set(rules["streptavidin_free_cuff_arms"]) sa_free_verified = lot_manifest.get("streptavidin_free_cuff_verified") is True peg_free_verified = ( cuff_arm == "ZWITTERIONIC_ALGINATE_PEG_FREE_CUFF" and lot_manifest.get("peg_free_cuff_verified") is True ) if not sa_bearing and not sa_free_arm: reasons.append(f"HOLD_UNRECOGNIZED_CUFF_ARM: {cuff_arm!r} not in Gate 39 allowed cuff arms.") # Required strata by cuff chemistry required_baseline = ["NORMAL_DONOR_SERA"] if not peg_free_verified: required_baseline.append("HIGH_ANTI_PEG_IGG_GT_500NG_ML") if sa_bearing or not (sa_free_arm and sa_free_verified): required_baseline.append("ANTI_SA_POSITIVE_HUMAN_SERA") require_day28_primed = bool(sa_bearing or not (sa_free_arm and sa_free_verified)) req_cfg = side_contract["stratum_requirements"] min_base_n = int(req_cfg["baseline_prevalence_strata_min_donors"]) min_day28_n = int(req_cfg["day28_primed_sera_policy"]["min_independent_primed_donors"]) upper_tail_cfg = req_cfg["high_anti_peg_upper_tail_policy"] by_stratum: dict[str, dict[str, Any]] = {} for idx, b in enumerate(batches): if not isinstance(b, dict): reasons.append(f"HOLD_MALFORMED_BATCH_RECEIPT: index {idx} not a dict.") continue # Reject any pooled multi-stratum batch if b.get("pooled_across_strata") is True or isinstance(b.get("cuff_serum_challenge_stratum"), list): reasons.append("FAIL_CUFF_ILLEGAL_STRATUM_POOLING: pooling across donor strata is prohibited (IIP-0020 / DEC-099).") continue st = b.get("cuff_serum_challenge_stratum") if st not in allowed_strata: reasons.append(f"FAIL_CUFF_ILLEGAL_STRATUM_POOLING: invalid stratum {st!r}.") continue if b.get("lot_id") != lot_id or b.get("assembled_device_lot_scope") != device_scope: reasons.append( f"HOLD_CUFF_CROSS_LOT_PROVENANCE_MISMATCH: stratum {st} lot/scope ({b.get('lot_id')}/{b.get('assembled_device_lot_scope')}) != ({lot_id}/{device_scope})." ) continue by_stratum[st] = b # Check completeness missing: list[str] = [s for s in required_baseline if s not in by_stratum] if require_day28_primed and "DAY28_SA_FASL_PRIMED_SERA" not in by_stratum: missing.append("DAY28_SA_FASL_PRIMED_SERA") if missing: reasons.append(f"HOLD_CUFF_SERUM_STRATUM_COVERAGE_INCOMPLETE: missing required strata {missing}.") # Validate each submitted stratum receipt u95_by_stratum: dict[str, float] = {} for st, b in by_stratum.items(): if b.get("single_stratum_status") != "CLEARED_CUFF_HUMORAL_HYDROLYSIS_AND_HEPATOCYTE_SAFETY_GATE": reasons.append(f"FAIL_CUFF_STRATUM_BATCH_NOT_CLEARED: {st} status={b.get('single_stratum_status')!r}.") n_donors = b.get("obs_cuff_serum_donor_count") n_fail = b.get("obs_cuff_serum_failing_donor_count") if not isinstance(n_donors, (int, float)) or not isinstance(n_fail, (int, float)): reasons.append(f"HOLD_CUFF_MISSING_DONOR_COUNTS: {st} missing donor or failing count.") continue n_int = int(round(float(n_donors))) fail_int = int(round(float(n_fail))) if fail_int > 0: reasons.append(f"FAIL_CUFF_STRATUM_DONOR_FAILURE: {st} recorded {fail_int} failing donors (max allowed = 0).") if st == "DAY28_SA_FASL_PRIMED_SERA": if n_int < min_day28_n: reasons.append(f"HOLD_CUFF_DAY28_PRIMED_UNDERPOWERED: {st} n={n_int} < {min_day28_n}.") elif n_int < min_base_n: warnings.append( f"DAY28_PRIMED_SERA_POST_EXPOSURE_N_LT_12: n={n_int} (U95={clopper_pearson_u95_zero_failures(n_int):.4f}); n>=12 recommended where available." ) if b.get("paired_pre_vs_day28_anti_sa_fold_documented") is not True: reasons.append("HOLD_CUFF_DAY28_PRIMED_FOLD_UNDOCUMENTED: paired pre vs Day-28 anti-SA IgG fold required.") else: if n_int < min_base_n: reasons.append(f"HOLD_CUFF_STRATUM_UNDERPOWERED_N_LT_12: {st} n={n_int} < {min_base_n} (U95={clopper_pearson_u95_zero_failures(n_int):.4f} > 0.2209).") if st == "HIGH_ANTI_PEG_IGG_GT_500NG_ML": n_hi = b.get("anti_peg_donors_ge_1000ng_ml") ceiling_waiver = b.get("anti_peg_cohort_ceiling_documented") is True if (not isinstance(n_hi, int) or n_hi < int(upper_tail_cfg["min_upper_tail_donors"])) and not ceiling_waiver: reasons.append( f"HOLD_CUFF_ANTI_PEG_UPPER_TAIL_UNCHARACTERIZED: requires >= {upper_tail_cfg['min_upper_tail_donors']} donors >= 1000 ng/mL (or documented cohort-ceiling waiver)." ) u95_by_stratum[st] = round(clopper_pearson_u95_zero_failures(n_int), 6) passed = len(reasons) == 0 return { "verdict": "PASS_GATE39_CUFF_STRATUM_COVERAGE" if passed else reasons[0].split(":")[0], "pass": passed, "reasons": reasons, "warnings": warnings, "diagnostics": { "product_id": product_id, "cuff_bioconjugation_arm": cuff_arm, "required_baseline_strata": required_baseline, "require_day28_primed_sera": require_day28_primed, "submitted_strata": sorted(by_stratum.keys()), "missing_strata": missing, "u95_zero_failure_by_stratum": u95_by_stratum, }, } def run_self_tests(side_contract: dict[str, Any]) -> list[dict[str, Any]]: """Run 12 deterministic adversarial self-tests for GATE-39.""" results: list[dict[str, Any]] = [] def _rec(name: str, ok: bool, detail: str) -> None: results.append({"test": name, "passed": bool(ok), "detail": detail}) # T01: Exact U95 and Yang 2016 prevalence math u12 = clopper_pearson_u95_zero_failures(12) u6 = clopper_pearson_u95_zero_failures(6) _rec( "T01_exact_u95_and_yang2016_expected_draw", math.isclose(u12, 0.22092222, abs_tol=1e-6) and math.isclose(u6, 0.39303776, abs_tol=1e-6) and math.isclose(12 * 0.07, 0.84, abs_tol=1e-9), f"U95(12)={u12:.6f}, U95(6)={u6:.6f}, E[hi_PEG]=0.84", ) def _mk_batch(st: str, n: int = 12, fail: int = 0, lot: str = "LOT-001", scope: str = "DEV-SCOPE-001", **kw: Any) -> dict[str, Any]: rec: dict[str, Any] = { "cuff_serum_challenge_stratum": st, "lot_id": lot, "assembled_device_lot_scope": scope, "single_stratum_status": "CLEARED_CUFF_HUMORAL_HYDROLYSIS_AND_HEPATOCYTE_SAFETY_GATE", "obs_cuff_serum_donor_count": n, "obs_cuff_serum_failing_donor_count": fail, } if st == "HIGH_ANTI_PEG_IGG_GT_500NG_ML": rec.setdefault("anti_peg_donors_ge_1000ng_ml", 4) if st == "DAY28_SA_FASL_PRIMED_SERA": rec.setdefault("paired_pre_vs_day28_anti_sa_fold_documented", True) rec.update(kw) return rec full_sa_lot = { "product_id": "ISLET1_DESIGN_X_V090", "lot_id": "LOT-001", "assembled_device_lot_scope": "DEV-SCOPE-001", "cuff_present": True, "cuff_bioconjugation_arm": "SA_FASL_SA_THBD_PEG_MICROGEL_CUFF", "stratum_batch_receipts": [ _mk_batch("NORMAL_DONOR_SERA", 12), _mk_batch("HIGH_ANTI_PEG_IGG_GT_500NG_ML", 12), _mk_batch("ANTI_SA_POSITIVE_HUMAN_SERA", 12), _mk_batch("DAY28_SA_FASL_PRIMED_SERA", 6), ], } # T02: Complete 4-stratum SA cuff lot passes (with Day-28 n=6 warning disclosed) r2 = evaluate_gate39_cuff_coverage(full_sa_lot, side_contract) _rec("T02_full_4stratum_sa_cuff_lot_passes", r2["pass"] and len(r2["warnings"]) == 1, r2["verdict"])