OpenIslet

scripts/verify_iip0041_clinical_h1_cd64t_siglec.py

EXP-028 (CAND-031 / Target IIP-0041 — Bucket 2A) Remediated Verification Suite

script Release v0.8.0 gen-eb955f8266035aba 984 KB · 69 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_iip0041_clinical_h1_cd64t_siglec.py · SHA-256: f004cf6d8259b8b4…

        "verified": True,
        "filename": modeb_fa_path.name,
        "record_count": len(fa_recs),
        "sha256": fa_sha,
        "matches_live_iip0035_l1a_l1b": True,
        "matches_side_contract_donor_pins": True,
    }

    # Extract staged CD64t[1-313] CDS directly from the verified required Mode-B lead construct
    lead_seq = fa_recs["ABX_L2_v2_CD64T_IL1RN"]
    cd64t_cds = None
    for i in range(len(lead_seq) - 941):
        sub = lead_seq[i : i + 942]
        if sub.startswith("ATG") and sub.endswith("ATTTAG") and sha256_str(sub) == "0390bb1d298aa7dc4eea19909377bf6e3200091f05f28918e94d6dc148beea86":
            cd64t_cds = sub
            break
    if cd64t_cds is None:
        raise ValueError("Could not locate verified 942-bp CD64t[1-313] CDS inside required ABX_L2_v2_CD64T_IL1RN")
    # Portable mode: explicitly decoupled from local private XML cache presence!
    gravina_cmp = verify_gravina_cd64t_cds_comparison(cd64t_cds, check_private_xml_cache=False)

    gate28a_cmc_tests = _run_gate28a_and_cmc_unit_tests()
    arb_tests = _run_locus2_arbitration_unit_tests()
    part_d = analyze_part_d_portfolio_odds()
    g2b_self = _verify_g2b_tamper_resistance_self_test()

    c2b_entry = next(
        c for c in part_a["cohorts"]
        if c["cohort_id"] == "C2b_DescriptiveSensitivity_MixedT1D_AssumedCommonC2b_13of13"
    )
    summary: dict[str, Any] = {
        "mode": "INSTALLED_READ_ONLY_SELF_CHECK",
        "receipt_determinism_policy": "PORTABLE_HOST_INDEPENDENT_EXCLUDES_RUNTIME_PYTHON_VERSION_AND_PRIVATE_CACHE_STATE",
        "private_cache_attestation_included": False,
        "experiment_id": "EXP-028",
        "candidate_id": "CAND-031",
        "target_iip": "IIP-0041",
        "remediation_stage": "R13",
        "receipt_revision": "R17",
        "receipt_content_stage": "R17_CMC_RAW_RESCUE_OUTCOME_AND_FRACTION_CLOSURE",
        "verified_date": PINNED_AUDIT_DATE,
        "portable_receipt_scope_note": (
            "Portable read-only self-check performs an embedded-reference comparison against the curated 942-bp "
            "Gravina 2023 coding sequence (76300c42..., encoding UniProt P12314[1-313], published directly in "
            "Gravina et al. 2023 public Methods [PMC10188358]; independent live retrieval of that external article "
            "text lies outside the public snapshot) and verifies staged Mode-B FASTA pins, runtime-pinned side "
            "contract, executable Gate 28-A/CMC and Gate 28-B unit suites (Gate 28-C0/C1 remain prespecified "
            "research criteria outside the installed runtime evaluator), domain-guard and G2b self-tests, and "
            "locked live portfolio parity without private cache or network access; Ring-1/CEG integrity, raw RCSB "
            "mmCIF parsing, live external PMC10188358 Methods text retrieval, and full Swiss-Prot scans execute "
            "in dedicated repository and full-mode verifiers."
        ),
        "side_contract_sha256": side_contract_sha,
        "pinned_side_contract_sha256": PINNED_SIDE_CONTRACT_SHA256,
        "side_contract_pin_verified": side_contract_pin_ok,
        "live_h1_held": part_a["live_openislet_h1_held_today"],
        "live_headline_delta_pp": part_d["live_headline_delta_pp"],
        "blueprint_h1_estimand_separated": True,
        "release_only_cmc_yield_metric": "P_release_CMC",
        "p_infuse_given_released_unit": "infused_primary_course_equivalents_per_released_lot",
        "separate_cmc_readiness_metric": "H1_CMC_ATTEMPTED_LOT_READINESS = P_release_CMC * P_infuse_given_released * H1_Blueprint",
        "cmc_projected_and_measured_readiness_separated": True,
        "cmc_empirical_product_readiness_labeled_diagnostic_only": True,
        "cmc_typed_course_identity_and_set_alias_enforced": True,
        "gate_28a_single_compatible_cohort_only": part_a["gate_28a_coherent_decision_contract"]["single_compatible_cohort_transport_rule"]["promotion_restricted_to_single_compatible_cohort"],
        "gate_28a_bank_lot_clustering_enforced": True,
        "gate_28a_strict_lot_to_mcb_manifest_and_cohort_attestations_enforced": True,
        "gate_28a_independent_trusted_clinical_store_and_full_digest_enforced": True,
        "gate_28a_zero_unverified_ancestry_fallback_and_wcb_provenance_enforced": True,
        "gate_28a_absent_store_nullifies_hierarchy_and_cluster_outputs": True,
        "gate_28a_bidirectional_rescue_cmc_reconciliation_enforced": True,
        "gate_28a_exact_bidirectional_rescue_identity_and_cardinality_enforced": True,
        "gate_28a_pass0_unconditional_clinical_ancestry_reconciliation_enforced": True,
        "gate_28a_infused_cmc_explicit_wcb_attestation_required": True,
        "gate_28a_wcb_alias_conflict_and_unique_parentage_enforced": True,
        "gate_28a_alternate_manifest_aliases_canonicalized_and_validated": True,
        "gate_28a_raw_cmc_ancestry_reconciled_across_all_dispositions": True,
        "gate_28a_typed_raw_cmc_ancestry_error_propagation_enforced": True,
        "gate_28a_strict_duplicate_key_json_intake_nullifies_ancestry_outputs": True,
        "gate_28a_icc_variance_component_sum_le_1_enforced": True,
        "gate_28a_deterministic_nonresponse_reconciled_against_cmc": True,
        "gate_28a_duplicate_clinical_rescue_order_independent_and_explicit_lot_id_required": True,
        "gate_28a_three_scenario_icc_sensitivity_report_enforced": True,
        "gate_28a_early_rejection_explicit_false_flags_enforced": True,
        "gate_28a_decision_control_flags_bound_in_canonical_digest": True,
        "gate_28a_recipient_wcb_alias_canonicalized_before_hashing": True,
        "gate_28a_contradictory_duplicate_rescue_nullifies_ancestry": True,
        "gate_28a_explicit_rescue_fields_strictly_narrowed": True,
        "gate_28a_rescue_linkage_and_recipient_binding_prevalidated": True,
        "gate_28a_primary_lot_cmc_disposition_prevalidated": True,
        "gate_28a_duplicate_recipient_primary_lot_cmc_disposition_audited": True,
        "gate_28a_raw_cmc_rescue_primary_outcome_reconciled": True,
        "gate_28a_clopper_pearson_95_ci_scope": "NOMINAL_IID_UNADJUSTED_RECIPIENT_COUNTS_ONLY_NOT_CLUSTER_ADJUSTED",
        "gate_28a_cluster_adjusted_beta_probability_scope": (
            "Prespecified decision-model quantities conditional on assumed lot/bank variance-component ICCs "
            "(rho_lot, rho_bank) and cohort exchangeability rather than independent empirical calibration; "
            "attaching the 3-scenario icc_sensitivity_report documents sensitivity across prespecified ICC "
            "grids rather than independent calibration of those variance components."
        ),
        "structural_mmcif_label_asym_id_enforced": True,
        "gate_28b_head_to_head_paired_panel_and_candidate_reconciliation_enforced": True,
        "gate_28b_three_state_incumbent_adjudication_enforced": True,
        "gate_28b_context_independent_rational_mfi_boundary_enforced": True,
        "gate_28b_direct_fraction_mfi_supported": True,
        "gate_28b_mfi_exact_fraction_precision_scope": (
            "Exact fractions.Fraction cross-product comparisons operate on already-decoded Python inputs: "
            "for strict JSON-ingested payloads decoded via IEEE-754 binary64 (float64) in load_strict_json_text / "
            "load_strict_json_bytes, exactness starts at JSON-decoded float64 precision (not raw decimal text "
            "beyond 53-bit binary64 significand precision), whereas direct Python Fraction, Decimal, or int inputs retain "
            "exact rational/decimal/integer precision."
        ),
        "gate_28b_clean_display_decimal_context_trap_immune": True,
        "gate_28b_mfi_display_formatting_overflow_immune": True,
        "published_13_of_13_primary_verified": c2b_entry["primary_verified"],
        "per_study_adjudication_ledger_count": len(part_a["per_study_endpoint_adjudication_ledger"]),
        "uniform_prior_minimum_threshold_verification": part_a["uniform_prior_minimum_threshold_verification"],
        "gate_28a_and_cmc_unit_tests": gate28a_cmc_tests,
        "gravina_2023_sequence_comparison": gravina_cmp,
        "modeb_fasta_check": fasta_check,
        "locus2_arbitration_unit_tests": arb_tests,
        "domain_and_ceiling_guard_unit_tests": part_d["domain_and_ceiling_guard_unit_tests"],
        "core_3arm_h1_only_delta_S0_to_S2a_pp": part_d["attribution_decomposition_and_disclosures"]["core_3arm_h1_only_delta_S0_to_S2a_pp"],
        "core_3arm_h1_only_delta_S0_to_S2a_exact_pp": part_d["attribution_decomposition_and_disclosures"]["core_3arm_h1_only_delta_S0_to_S2a_exact_pp"],
        "five_arm_unrounded_parity_max_abs_err": part_d["live_parity_verification"]["five_arm_W_U3_W_U4_unrounded_max_abs_err"],
        "g2b_tamper_resistance_self_test": g2b_self,
        "overall_status": "INSTALLED_SELF_CHECK_PASSED",
    }
    summary["portable_payload_sha256"] = sha256_str(
        json.dumps(summary, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
    )
    raw = json.dumps(summary, indent=2, ensure_ascii=False)
    if PRIVACY_HOME_TOKEN in raw:
        raise ValueError("Privacy leak detected in installed self-check output!")
    if output_path is not None:
        out_file = output_path if output_path.suffix.lower() == ".json" else (output_path / "iip0041_installed_check_receipt.json")
        out_file.parent.mkdir(parents=True, exist_ok=True)
        out_file.write_text(raw + "\n", encoding="utf-8")
        print(f"Wrote installed self-check receipt: {out_file.name} ({out_file.stat().st_size} B, SHA-256={sha256_file(out_file)})")
    print(
        f"PASS: H1={summary['live_h1_held']}, Core H1-only={summary['core_3arm_h1_only_delta_S0_to_S2a_pp']:+.4f} pp, "
        f"Gravina={gravina_cmp['synonymous_nucleotide_differences_vs_gravina']}nt/{gravina_cmp['amino_acid_differences_vs_gravina']}aa, "
        f"G28A/CMC={gate28a_cmc_tests['total_cases']}/{gate28a_cmc_tests['total_cases']}, "
        f"Arb={arb_tests['total_cases']}/{arb_tests['total_cases']}, Domain={part_d['domain_and_ceiling_guard_unit_tests']['total_negative_tests']}/{part_d['domain_and_ceiling_guard_unit_tests']['total_negative_tests']}, "
        f"G2b-tamper-reject={g2b_self['tampered_digest_rejected']}, PinOK={side_contract_pin_ok}, PortableSHA={summary['portable_payload_sha256'][:12]} (optimize={sys.flags.optimize})"
    )
    return summary


def build_cli_parser() -> argparse.ArgumentParser:
    ap = argparse.ArgumentParser(
        description="EXP-028 / IIP-0041 Clinical H1, Mode-B CD64t+IL1RN, Siglec-7/-9, Portfolio, & Evidence Verifier",
    )
    ap.add_argument("--repo-root", type=pathlib.Path, default=None, help="Path to OpenIslet repository root (fail-closed if invalid).")
    ap.add_argument("--inv-root", type=pathlib.Path, default=None, help="Optional path to OpenIslet-Investigations root (full staged mode).")
    ap.add_argument("--output", type=pathlib.Path, default=None, help="Output directory or .json receipt file path (read-only in --installed-check unless set).")
    ap.add_argument("--installed-check", "--check", dest="installed_check", action="store_true", help="Run read-only installed self-check without external caches or network.")
    return ap


def main(argv: list[str] | None = None) -> None:
    args = build_cli_parser().parse_args(argv)
    configure_runtime_paths(repo_root=args.repo_root, inv_root=args.inv_root, output=args.output)
    if args.installed_check:
        run_installed_check(output_path=args.output)
        return

    OUT_DIR.mkdir(parents=True, exist_ok=True)
    print("=== EXP-028 / IIP-0041 REMEDIATED VERIFICATION SUITE ===")
    print(f"0. Runtime: Python {sys.version.split()[0]} (optimize={sys.flags.optimize}, bytecode_disabled={sys.dont_write_bytecode})")
    print("1. Loading pinned 20,429-protein human Swiss-Prot...")
    prots, sp_kmers, sp_sha = load_swissprot()

    print("2. Running Part A: Clinical Hurdle 1 Audit (Blueprint H1=0.88 post-release estimand; separate H1_CMC_ATTEMPTED_LOT_READINESS; single-cohort Gate 28-A)...")
    part_a = analyze_clinical_h1_reanchor()

    print("3. Running Part B: Mode-B Core A/B/X CIITA Exon 5 FASTA + Protein Gate P1-P4 + Full-vs-Component Arbitration...")
    part_b = build_and_audit_part_b(prots, sp_kmers, sp_sha)

    print("4. Running Part C: Research Comparator Siglec-7/-9 (Split 28-C0/C1) & Permanent GY-029 ST6GAL1 Rule...")
    part_c = analyze_part_c_siglec_glycoengineering(sp_kmers)

    print("5. Running Part D: Exact OQ-016 2^12 & 2^20 Portfolio Odds (Strict Zero-Tol Guards + True Unrounded Deltas)...")
    part_d = analyze_part_d_portfolio_odds()

    print(f"6. Running Part E: Live NCBI E-utilities + Europe PMC verification of {len(ALL_EXP028_PMIDS)} PMIDs...")
    live_pm = fetch_live_pubmed_and_epmc(ALL_EXP028_PMIDS)
    pmid_receipt = {
        "schema_version": "exp028_pmid_receipt_v2",
        "verified_date": PINNED_AUDIT_DATE,
        "python_version": sys.version.split()[0],
        "verification_sources": ["NCBI E-utilities esummary.fcgi", "NCBI E-utilities efetch.fcgi", "Europe PMC REST search API"],
        "total_pmids_verified": len(live_pm),
        "missing_count": 0,
        "retracted_count": sum(1 for r in live_pm.values() if r["retracted"]),
        "records": {
            pm: {k: v for k, v in rec.items() if k != "abstract"}
            for pm, rec in sorted(live_pm.items(), key=lambda x: int(x[0]))
        },
    }
    pmid_raw = json.dumps(pmid_receipt, indent=2, ensure_ascii=False)
    if PRIVACY_HOME_TOKEN in pmid_raw:
        raise ValueError("Privacy leak detected in pmid_verification_receipt.json!")
    PMID_RECEIPT_OUT.write_text(pmid_raw + "\n", encoding="utf-8")

    print("7. Running Part F: §5.6 Ring-1 + CEG Evidence Extraction, Optimize-Safe G2b, All 9/9 Live Validators, & PDL-019 Receipt...")
    ev_audit = build_and_validate_evidence_bundle(live_pm)
    g2b_self = _verify_g2b_tamper_resistance_self_test()

    receipt = {
        "experiment_id": "EXP-028",
        "candidate_id": "CAND-031",
        "target_iip": "IIP-0041",
        "bucket": "2A",
        "remediation_stage": "S3-R3",
        "generated_date": PINNED_AUDIT_DATE,
        "python_version": sys.version.split()[0],
        "part_a_clinical_h1_reanchor": part_a,
        "part_b_abx_cd64t_il1rn_modeb_protein_gate": part_b,
        "part_c_siglec_glycoengineering_and_st6gal1": part_c,
        "part_d_oq016_portfolio_odds": part_d,
        "part_e_live_pmid_verification_summary": {
            "receipt_filename": PMID_RECEIPT_OUT.name,
            "receipt_sha256": sha256_file(PMID_RECEIPT_OUT),
            "total_pmids_verified": pmid_receipt["total_pmids_verified"],
            "retracted_count": pmid_receipt["retracted_count"],
        },
        "part_f_evidence_extraction_validation_summary": {
            "bundle_filename": EVIDENCE_BUNDLE_OUT.name,
            "bundle_sha256": sha256_file(EVIDENCE_BUNDLE_OUT),
            "extraction_verification_receipt_filename": EXTRACTION_RECEIPT_OUT.name,
            "extraction_verification_receipt_sha256": sha256_file(EXTRACTION_RECEIPT_OUT),
            "overall_status": ev_audit["overall_status"],
            "gate_pass_map": {k: v["passed"] for k, v in ev_audit["gates"].items()},
            "g2b_tamper_resistance_self_test": g2b_self,
        },
    }
    rec_raw = json.dumps(receipt, indent=2, ensure_ascii=False)
    if PRIVACY_HOME_TOKEN in rec_raw:
        raise ValueError("Privacy leak detected in verification receipt!")
    RECEIPT_OUT.write_text(rec_raw + "\n", encoding="utf-8")

    print("\n=== ALL EXP-028 STAGE S3-R3 VERIFICATION GATES PASSED ===")
    for fn in (_SCRIPT_PATH, FASTA_OUT, RECEIPT_OUT, PMID_RECEIPT_OUT, EVIDENCE_BUNDLE_OUT, EXTRACTION_RECEIPT_OUT):
        print(f"  {fn.name:48s}  {fn.stat().st_size:7d} B  SHA-256={sha256_file(fn)}")


if __name__ == "__main__":
    main()