OpenIslet

scripts/verify_iip0035_d1b_auto_and_portfolio.py

Deterministic Autologous D1b-Auto-C v2 Mode-B Registry, 45-Cell Stage-0 Contract,

script Release v0.8.0 gen-eb955f8266035aba 288 KB · 23 sections

Use this file in any AI chat (paste-only or attachment-capable):

Download as text (.txt) Download section (.txt)

Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0035_d1b_auto_and_portfolio.py · SHA-256: fedb990aeaedd116…

        disk_blk = dt_doc.get("autologous_d1b_auto_c_v2_vanguard_gates_iip_0035")
        if not isinstance(disk_blk, dict):
            raise ValueError("Missing DEC-114 block autologous_d1b_auto_c_v2_vanguard_gates_iip_0035 in stage0_decision_tree_v1.json")
        disk_sha = hashlib.sha256(
            json.dumps(disk_blk, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
        ).hexdigest()
        if require_canonical_sha and disk_sha != EXPECTED_DEC114_DECISION_TREE_SHA256:
            raise ValueError(
                f"On-disk controlling DEC-114 decision-tree SHA-256 mismatch: found {disk_sha}, expected {EXPECTED_DEC114_DECISION_TREE_SHA256}"
            )
    elif dt_path.is_file():
        # Best-effort non-raising on-disk check when require_canonical_sha=False so status fields never
        # misreport an unverified/absent installed decision tree as canonical-verified!
        try:
            _dt_doc_opt = _load_json_strict(dt_path)
            _db_opt = _dt_doc_opt.get("autologous_d1b_auto_c_v2_vanguard_gates_iip_0035")
            if isinstance(_db_opt, dict):
                disk_blk = _db_opt
                disk_sha = hashlib.sha256(
                    json.dumps(disk_blk, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
                ).hexdigest()
        except Exception:
            disk_blk = None
            disk_sha = None
    if decision_tree_block is None:
        if disk_blk is None:
            raise ValueError("Missing on-disk DEC-114 decision-tree block")
        blk = disk_blk
    else:
        blk = decision_tree_block
    dt_sha = hashlib.sha256(
        json.dumps(blk, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
    ).hexdigest()
    on_disk_dt_verified = bool(
        disk_blk is not None
        and disk_sha == EXPECTED_DEC114_DECISION_TREE_SHA256
        and _strict_typed_equal(blk, disk_blk)
    )
    if require_canonical_sha and (dt_sha != EXPECTED_DEC114_DECISION_TREE_SHA256 or not on_disk_dt_verified):
        raise ValueError(
            f"Controlling DEC-114 decision-tree SHA-256 mismatch: found {dt_sha}, expected {EXPECTED_DEC114_DECISION_TREE_SHA256}"
        )
    pbg = blk.get("product_by_gate_contract")
    if not isinstance(pbg, dict) or pbg.get("cell_count") != 45 or not isinstance(pbg.get("cells"), list) or len(pbg["cells"]) != 45:
        raise ValueError("Controlling DEC-114 product_by_gate_contract must define the exact 45-cell Cartesian contract")
    all_cell_map: Dict[tuple[str, str], Dict[str, Any]] = {}
    for c in pbg["cells"]:
        if not isinstance(c, dict) or set(c.keys()) != REQUIRED_CELL_KEYS:
            raise ValueError(f"Malformed typed cell in controlling product_by_gate_contract: {c!r}")
        if any(not isinstance(v, str) or not v.strip() or _PLACEHOLDER_TOKEN_RE.search(v) for v in c.values()):
            raise ValueError(f"Empty, non-string, or placeholder field in typed cell {c.get('product_variant_id')}:{c.get('gate_id')}")
        if c["operator"] not in VALID_CELL_OPERATORS:
            raise ValueError(f"Unrecognized typed cell operator {c['operator']!r} on {c['product_variant_id']}:{c['gate_id']}")
        if c["disposition"] not in VALID_CELL_DISPOSITIONS:
            raise ValueError(f"Unrecognized typed cell disposition {c['disposition']!r} on {c['product_variant_id']}:{c['gate_id']}")
        mdd_c = c["missing_data_disposition"]
        if not mdd_c.startswith("HOLD_") or re.search(r"\bPASS\b", mdd_c, re.IGNORECASE):
            raise ValueError(f"Typed cell missing_data_disposition must be fail-closed HOLD_* on {c['product_variant_id']}:{c['gate_id']}: {mdd_c!r}")
        ckey = (c["product_variant_id"], c["gate_id"])
        if ckey in all_cell_map:
            raise ValueError(f"Duplicate product-by-gate cell in controlling contract: {ckey}")
        all_cell_map[ckey] = c
    expected_cart = {(p, g) for p in pc.STAGED_D1B_AUTO_V2_PRODUCT_IDS for g in EXPECTED_45_GATES}
    if set(all_cell_map.keys()) != expected_cart:
        raise ValueError("Controlling product_by_gate_contract does not match the exact 5 products x 9 gates Cartesian set")

    pvid_cells: Dict[str, Dict[str, Any]] = {
        gid: all_cell_map[(pvid, gid)]
        for gid in EXPECTED_45_GATES
        if (pvid, gid) in all_cell_map
    }
    # Verify expected operators & dispositions across ALL 45 cells (all 5 products x 9 gates) even in diagnostic mode!
    for check_pvid in pc.STAGED_D1B_AUTO_V2_PRODUCT_IDS:
        if check_pvid in D1B_FULLSTACK_CANDIDATE_IDS:
            exp_ops = EXPECTED_L1B_GATE_OPERATORS if check_pvid == "ISLET1_D1_AUTO_V2_L1B_CIITA_CD64T_CD46WT_COMPARATOR" else EXPECTED_L1A_GATE_OPERATORS
            for gid in EXPECTED_45_GATES:
                cell = all_cell_map[(check_pvid, gid)]
                exp_disp = (
                    "REQUIRED_EXACT_PRODUCT_WITH_LOT_MATCHED_GATE0V"
                    if (check_pvid == "ISLET1_D1_AUTO_V2_L1B_CIITA_CD64T_CD46WT_COMPARATOR" and gid == "D1-09")
                    else "REQUIRED_EXACT_PRODUCT"
                )
                if cell["operator"] != exp_ops[gid] or cell["disposition"] != exp_disp:
                    raise ValueError(
                        f"Controlling contract operator/disposition mismatch on {check_pvid}:{gid}: "
                        f"got ({cell['operator']!r}, {cell['disposition']!r}), expected ({exp_ops[gid]!r}, {exp_disp!r})"
                    )
        elif check_pvid in D1B_COMPONENT_DONOR_IDS:
            comp_app = COMPONENT_APPLICABLE_GATES[check_pvid]
            comp_exp_ops = EXPECTED_COMPONENT_GATE_OPERATORS[check_pvid]
            for gid in EXPECTED_45_GATES:
                cell = all_cell_map[(check_pvid, gid)]
                if gid in comp_app:
                    if cell["operator"] != comp_exp_ops[gid] or cell["disposition"] != "COMPONENT_EVIDENCE_ONLY_EXCLUDED_FROM_FULLSTACK":
                        raise ValueError(
                            f"Component cell {check_pvid}:{gid} operator/disposition mismatch: "
                            f"got ({cell['operator']!r}, {cell['disposition']!r}), "
                            f"expected ({comp_exp_ops[gid]!r}, 'COMPONENT_EVIDENCE_ONLY_EXCLUDED_FROM_FULLSTACK')"
                        )
                else:
                    if cell["operator"] != "NOT_APPLICABLE" or cell["disposition"] != "NOT_APPLICABLE_EXCLUDED_FROM_FULLSTACK":
                        raise ValueError(f"Inapplicable component cell {check_pvid}:{gid} must be NOT_APPLICABLE / NOT_APPLICABLE_EXCLUDED_FROM_FULLSTACK")

    cell_missing_dispositions: Dict[str, str] = {
        gid: str(pvid_cells[gid]["missing_data_disposition"])
        for gid in pvid_cells
    }

    is_component_excluded = bool(
        len(pvid_cells) == 9
        and all("EXCLUDED_FROM_FULLSTACK" in str(c.get("disposition") or "") for c in pvid_cells.values())
    )
    thresholds: Dict[str, Any] = {}
    if len(pvid_cells) == 9 and not is_component_excluded:
        t02 = str(pvid_cells["D1-02"]["threshold"])
        t03 = str(pvid_cells["D1-03"]["threshold"])
        t04 = str(pvid_cells["D1-04"]["threshold"])
        t05 = str(pvid_cells["D1-05"]["threshold"])
        t06 = str(pvid_cells["D1-06"]["threshold"])
        t07 = str(pvid_cells["D1-07"]["threshold"])
        t08 = str(pvid_cells["D1-08"]["threshold"])
        t09 = str(pvid_cells["D1-09"]["threshold"])
        thresholds = {
            "min_mm_reject_le": int(_extract_dec_from_cell_threshold(t02, r"reject_le_([0-9]+)mm", "D1-02:min_mm_reject_le")),
            "min_mm_max": int(_extract_dec_from_cell_threshold(t02, r"min_mm_to_HLAC_E_valid_range_0_to_([0-9]+)", "D1-02:min_mm_max")),
            "wt_hlac_min": _extract_dec_from_cell_threshold(t02, r"wt_hlac_retention_pct>=([0-9.eE+-]+)", "D1-02:wt_hlac"),
            "bystander_lt": _extract_dec_from_cell_threshold(t02, r"bystander_ct_pct<([0-9.eE+-]+)", "D1-02:bystander"),
            "chr6_del_eq": _extract_dec_from_cell_threshold(t02, r"chr6p21_interlocus_del_pct==([0-9.eE+-]+)", "D1-02:chr6_del"),
            "chrm_depth_min": _extract_dec_from_cell_threshold(t03, r"chrm_numt_amplicon_depth_x>=([0-9.eE+-]+)", "D1-03:chrm_depth"),
            "chrm_het_lt": _extract_dec_from_cell_threshold(t03, r"chrm_novel_nonsyn_het_pct<([0-9.eE+-]+)", "D1-03:chrm_het"),
            "htmpk_leak_max": _extract_dec_from_cell_threshold(t04, r"G0_beta_htmpk_leak_pct<=([0-9.eE+-]+)", "D1-04:htmpk_leak"),
            "elispot_max": _extract_dec_from_cell_threshold(t04, r"hlac07_ryafsgvay_elispot_above_bg_pct<=([0-9.eE+-]+)", "D1-04:elispot"),
            "ap1903_u95_max": _extract_dec_from_cell_threshold(t04, r"AP1903_k==0_exact_80digit_sound_Decimal_U95<=([0-9.eE+-]+)", "D1-04:ap1903_u95"),
            "azt_forced_chr19_loss_required": ("azt_kill_measured_after_forced_chr19_loss==True" in t04),
            "azt_kill_min": _extract_dec_from_cell_threshold(t04, r"AZT_dividing_log10_kill>=([0-9.eE+-]+)", "D1-04:azt_kill"),
            "l3_ret_min": _extract_dec_from_cell_threshold(t05, r"L3_stage7_day28_retention_pct>=([0-9.eE+-]+)", "D1-05:l3_ret"),
            "l4_ret_min": _extract_dec_from_cell_threshold(t05, r"L4_stage7_day28_retention_pct>=([0-9.eE+-]+)", "D1-05:l4_ret"),
            "min_l3_l4_ret_min": _extract_dec_from_cell_threshold(t05, r"min_L3_L4_stage7_day28_retention_pct>=([0-9.eE+-]+)", "D1-05:min_l3_l4"),
            "fsp1_surv_min": _extract_dec_from_cell_threshold(t05, r"RSL3_fsp1_ferroptosis_survival_pct>=([0-9.eE+-]+)", "D1-05:fsp1"),
            "kir_nk_max": _extract_dec_from_cell_threshold(t06, r"kir3dl1_missing_bw4_autologous_nk_lysis_pct<=([0-9.eE+-]+)", "D1-06:kir_nk"),
            "vtcn1_shed_max": _extract_dec_from_cell_threshold(t07, r"vtcn1_nrd1_soluble_sb7h4_shedding_pct<=([0-9.eE+-]+)", "D1-07:vtcn1"),
            "hlac03_u95_pct_max": _extract_dec_from_cell_threshold(t08, r"HLAC0304_k==0_exact_80digit_sound_Decimal_U95<=([0-9.eE+-]+)%", "D1-08:hlac03_u95"),
            "t1d_c5b9_u95_pct_max": _extract_dec_from_cell_threshold(t08, r"T1D_serum_C5b9_k==0_exact_80digit_sound_Decimal_U95<=([0-9.eE+-]+)%", "D1-08:c5b9_u95"),
            "d1_08_two_branch_enforced": (
                "d1_08_patient_carries_hlac0304_bool_or_derived_from_patient_hla_c_alleles" in t08
                and "hlac0304_positive_control_valid==True" in t08
                and "matched_allele_positive_control_valid==True" in t08
                and "matched_allele_cd8_screen_passed==True" in t08
            ),
            "turnaround_max": _extract_dec_from_cell_threshold(t09, r"autologous_sequential_6locus_gmp_turnaround_weeks<=([0-9.eE+-]+)", "D1-09:turnaround"),
        }
        if not thresholds["azt_forced_chr19_loss_required"]:
            raise ValueError(f"Controlling 45-cell contract D1-04 missing required forced chr19 loss clause: {t04!r}")
        if not thresholds["d1_08_two_branch_enforced"]:
            raise ValueError(f"Controlling 45-cell contract D1-08 missing required two-branch & positive-control clauses: {t08!r}")
        if "REQUIRED_EXACT_PRODUCT_WITH_LOT_MATCHED_GATE0V" == pvid_cells["D1-09"].get("disposition"):
            thresholds["g0v_day14_min"] = _extract_dec_from_cell_threshold(t09, r"Gate0V_day14_log10_reduction>=([0-9.eE+-]+)", "D1-09:g0v_day14")
            thresholds["g0v_day14_l95_min"] = _extract_dec_from_cell_threshold(t09, r"Gate0V_day14_log10_reduction_l95>=([0-9.eE+-]+)", "D1-09:g0v_day14_l95")
            thresholds["g0v_72h_max"] = _extract_dec_from_cell_threshold(t09, r"Gate0V_cvb4_72h_early_titer_log10_pfu_u95<=([0-9.eE+-]+)", "D1-09:g0v_72h")
            thresholds["g0v_day28_u95_max"] = _extract_dec_from_cell_threshold(t09, r"Gate0V_day28_VP1_IE1_k==0_U95<=([0-9.eE+-]+)", "D1-09:g0v_u95")
            m_n = re.search(r"Gate0V_day28_VP1_IE1_k==0_U95<=[0-9.eE+-]+\(n>=([0-9]+)\)", t09, re.ASCII)
            if not m_n:
                raise ValueError(f"Controlling 45-cell contract missing Gate0V n>= threshold in {t09!r}")
            thresholds["g0v_day28_n_min"] = int(m_n.group(1))
    elif len(pvid_cells) == 9 and is_component_excluded:
        if pvid == "ISLET1_D1_AUTO_V2_L3_AAVS1_VTCN1_UCOE2S_ICASP9":
            thresholds = {
                "ap1903_u95_max": _extract_dec_from_cell_threshold(str(pvid_cells["D1-04"]["threshold"]), r"L3_chr19_AAVS1_AP1903_k==0_exact_80digit_sound_Decimal_U95<=([0-9.eE+-]+)", "L3:D1-04:ap1903_u95"),
                "l3_ret_min": _extract_dec_from_cell_threshold(str(pvid_cells["D1-05"]["threshold"]), r"L3_stage7_day28_retention_pct>=([0-9.eE+-]+)", "L3:D1-05:l3_ret"),
                "vtcn1_shed_max": _extract_dec_from_cell_threshold(str(pvid_cells["D1-07"]["threshold"]), r"L3_vtcn1_nrd1_soluble_sb7h4_shedding_pct<=([0-9.eE+-]+)", "L3:D1-07:vtcn1"),
            }
        elif pvid == "ISLET1_D1_AUTO_V2_L4_CLYBL_TANDEM_TUBA1B_FSP1_CHS4_CDK1_HTMPK_F105Y":
            t04_c = str(pvid_cells["D1-04"]["threshold"])
            t05_c = str(pvid_cells["D1-05"]["threshold"])
            thresholds = {
                "htmpk_leak_max": _extract_dec_from_cell_threshold(t04_c, r"L4_G0_beta_htmpk_leak_pct<=([0-9.eE+-]+)", "L4:D1-04:htmpk_leak"),
                "elispot_max": _extract_dec_from_cell_threshold(t04_c, r"L4_hlac07_ryafsgvay_elispot_above_bg_pct<=([0-9.eE+-]+)", "L4:D1-04:elispot"),
                "azt_forced_chr19_loss_required": ("L4_azt_kill_measured_after_forced_chr19_loss==True" in t04_c),
                "azt_kill_min": _extract_dec_from_cell_threshold(t04_c, r"L4_AZT_dividing_log10_kill>=([0-9.eE+-]+)", "L4:D1-04:azt_kill"),
                "l4_ret_min": _extract_dec_from_cell_threshold(t05_c, r"L4_stage7_day28_retention_pct>=([0-9.eE+-]+)", "L4:D1-05:l4_ret"),
                "fsp1_surv_min": _extract_dec_from_cell_threshold(t05_c, r"L4_RSL3_fsp1_ferroptosis_survival_pct>=([0-9.eE+-]+)", "L4:D1-05:fsp1"),
            }
            if not thresholds["azt_forced_chr19_loss_required"]:
                raise ValueError(f"Controlling 45-cell contract L4:D1-04 missing required forced chr19 loss clause: {t04_c!r}")
        elif pvid == "ISLET1_D1_AUTO_V2_L2_CXCL10_SERPINB9_PDL1":
            # Parse L2's complete normative D1-08 component subgate STRICTLY from L2's own cell (ZERO L1A borrowing or numeric fallback!)
            t08_l2 = str(pvid_cells["D1-08"]["threshold"])
            l2_two_branch_ok = (
                "L2_d1_08_patient_carries_hlac0304_bool_or_derived_from_patient_hla_c_alleles" in t08_l2
                and "hlac0304_positive_control_valid==True" in t08_l2
                and "matched_allele_positive_control_valid==True" in t08_l2
                and "matched_allele_cd8_screen_passed==True" in t08_l2
                and "optional_adverse_T1D_serum_C5b9_k>=1_triggers_FAIL_HARD_STOP" in t08_l2
            )
            if not l2_two_branch_ok:
                raise ValueError(f"Controlling 45-cell contract L2:D1-08 missing required self-contained branch/adverse clauses: {t08_l2!r}")
            thresholds = {
                "hlac03_u95_pct_max": _extract_dec_from_cell_threshold(t08_l2, r"L2_HLAC0304_k==0_exact_80digit_sound_Decimal_U95<=([0-9.eE+-]+)%", "L2:D1-08:hlac03_u95"),
                "l2_d1_08_self_contained_enforced": True,
            }

    return {
        "gate_id": str(blk.get("gate_id") or ""),
        "schema_version": str(pbg.get("schema_version") or ""),
        "sha256": dt_sha,
        "staged_registry_verified": staged_registry_verified,
        "canonical_sha_verified": bool(dt_sha == EXPECTED_DEC114_DECISION_TREE_SHA256 and on_disk_dt_verified),
        "on_disk_decision_tree_verified": on_disk_dt_verified,
        "in_memory_block_matches_canonical_sha": bool(dt_sha == EXPECTED_DEC114_DECISION_TREE_SHA256),
        "playbook_sec4120_sha256": pb_info["pb_sha"],
        "playbook_footer_present": pb_info["footer_present"],
        "playbook_footer_verified": pb_info["footer_verified"],
        "playbook_canonical_sha_verified": pb_info["canonical_sha_verified"],
        "cells_loaded": len(pvid_cells),
        "external_refs": [str(pvid_cells[g].get("external_ref") or "") for g in EXPECTED_45_GATES if g in pvid_cells],
        "cell_missing_dispositions": cell_missing_dispositions,
        "is_component_excluded": is_component_excluded,
        "thresholds": thresholds,
    }


def _aggregate_panel_coverage_regime(cal_summary: Dict[str, Any]) -> str:
    """Aggregate per-assay coverage categories independently of distinct Bonferroni percentages."""
    active_entries = [m for m in cal_summary.values() if isinstance(m, dict) and isinstance(m.get("coverage_regime"), str)]
    if not active_entries:
        return "UNAVAILABLE"
    regimes = sorted({str(m["coverage_regime"]) for m in active_entries})
    if len(regimes) == 1:
        return regimes[0]
    cats = {str(m.get("coverage_category") or ("CALIBRATED" if "BONFERRONI" in str(m["coverage_regime"]) else "UNIT_ASSUMED")) for m in active_entries}
    if cats == {"CALIBRATED"}:
        return "ALL_CALIBRATED_VARIED_BONFERRONI_COVERAGE:" + "|".join(regimes)
    if cats == {"UNIT_ASSUMED"}:
        return "ALL_UNIT_ASSUMED_VARIED_OBSERVATION_ALPHA:" + "|".join(regimes)
    if cats == {"CALIBRATED", "UNIT_ASSUMED"}:
        return "MIXED_CALIBRATED_AND_UNIT_ASSUMED:" + "|".join(regimes)
    if "CALIBRATED" not in cats:
        return "MIXED_PARTIAL_AND_UNIT_ASSUMED:" + "|".join(regimes)
    return "MIXED_CALIBRATED_AND_ASSUMPTION_DEPENDENT:" + "|".join(regimes)


def _collect_assumption_only_flags(cal_summary: Dict[str, Any]) -> List[str]:
    """Surface EVERY default or uncalibrated sampling/recovery/eligibility assumption visibly at headline output."""
    flags: List[str] = []
    for _ak, _am in cal_summary.items():
        if not isinstance(_am, dict):
            continue
        _sp = _am.get("sampling_independence_provenance")
        if _sp in ("UNSPECIFIED_DEFAULT_ASSUMED_INDEPENDENT", "EXPLICIT_NON_CLUSTERED_ONLY_INDEPENDENCE_ASSUMED"):
            flags.append(f"{_ak}:SAMPLING_INDEPENDENCE_ASSUMED({_sp})")