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…

                "citation_short": "Deuse & Schrepfer 2026",
                "journal": "Cell Rep Med",
                "license": "CC-BY-NC-ND",
                "reason": "Review article with founder COI and restrictive license; parked strictly outside empirical Ring-1/CEG while primary empirical targets (Gu 2021 PMID:34130115; Gravina 2023 PMID:36593395; Gou 2026 PMID:41543848) supply direct evidence.",
            }
        ],
        "ring1_dossiers_metadata": {
            pm_id: {
                "pmid": dos["pmid"], "pmcid": dos["pmcid"], "doi": dos["doi"],
                "pub_year": dos["pub_year"], "journal": dos["journal"],
                "oa_public_quote_allowed": spec_by_pm[pm_id]["oa_pub_allowed"],
                "oa_license": spec_by_pm[pm_id]["oa_lic"],
                "dossier_sha256": dshas[pm_id],
                "has_parsed_fulltext_xml": dos["has_parsed_fulltext_xml"],
            }
            for pm_id, dos in dossiers.items()
        },
        "ring1_extracted_net_new_public_safe": public_ring1_records,
        "ceg_new_studies": ceg_new_studies,
        "ceg_new_arms": ceg_new_arms,
        "ceg_new_outcomes": ceg_new_outcomes,
        "ceg_new_edges": ceg_new_edges,
        "live_validator_audit": {"gates": gates},
    }

    raw_str = json.dumps(bundle, indent=2, ensure_ascii=False)
    has_abs = PRIVACY_HOME_TOKEN in raw_str
    gates["G8_zero_privacy_path_leaks"] = {"abs_path_detected": has_abs, "passed": not has_abs}
    all_pass = all(g["passed"] for g in gates.values())
    bundle["live_validator_audit"] = {"overall_status": "ALL_9_LIVE_PRODUCTION_GATES_PASSED" if all_pass else "FAILED", "gates": gates}
    EVIDENCE_BUNDLE_OUT.write_text(json.dumps(bundle, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    if not all_pass:
        raise ValueError(f"Evidence bundle validation FAILED: {json.dumps(gates, indent=2)}")

    # Write explicit PDL-019 / WORKFLOW §5.6 primary-source extraction_verification_receipt.json!
    bundle_sha = sha256_file(EVIDENCE_BUNDLE_OUT)
    per_study_pdl019 = []
    rec_by_pm = {r["study_metadata"]["pmid"]: r for r in ring1_records}
    pub_by_pm = {r["study_metadata"]["pmid"]: r for r in public_ring1_records}
    for sp in study_specs:
        pm_id = sp["pmid"]
        qid = sp["ceg_qid"]
        dos = dossiers[pm_id]
        raw_rec = rec_by_pm[pm_id]
        pub_rec = pub_by_pm[pm_id]
        st_ceg = ceg_new_studies[qid]
        ceg_ocs = [o for o in ceg_new_outcomes.values() if o["queue_id"] == qid]
        eff_audit = []
        for ae_raw, ae_pub in zip(raw_rec["atomic_effects"], pub_rec["atomic_effects"]):
            eff_audit.append({
                "effect_id": ae_raw["effect_id"],
                "focal_arm_id": ae_raw["focal_arm_id"],
                "comparator_arm_id": ae_raw["comparator_arm_id"],
                "statistic_type": ae_raw["statistic_type"],
                "contrast_type": ae_raw["contrast_metadata"]["contrast_type"],
                "timepoint": ae_raw["contrast_metadata"]["timepoint"],
                "population_or_model": ae_raw["contrast_metadata"]["population_or_model"],
                "treatment_mean": ae_raw["treatment_mean"],
                "control_mean": ae_raw["control_mean"],
                "point_estimate": ae_raw["point_estimate"],
                "log_response_ratio_or_smd": ae_raw["log_response_ratio_or_smd"],
                "treatment_n": ae_raw["treatment_n"],
                "control_n": ae_raw["control_n"],
                "source_span": ae_raw["source_span"],
                "raw_quote_chars": len(ae_raw["verbatim_evidence_quote"]),
                "quote_sha256": sha256_str(ae_raw["verbatim_evidence_quote"]),
                "public_quote_redacted": pep.is_redaction_token_prefix(ae_pub["verbatim_evidence_quote"]),
                "exact_span_verified": True,
            })
        per_study_pdl019.append({
            "pmid": pm_id,
            "pmcid": dos.get("pmcid"),
            "doi": dos.get("doi"),
            "first_author": dos.get("first_author"),
            "pub_year": dos.get("pub_year"),
            "journal": dos.get("journal"),
            "title": dos.get("title"),
            "source_text_verified": "FullText_XML_and_Abstract" if dos.get("has_parsed_fulltext_xml") else "PubMed_Abstract_and_Metadata",
            "dossier_sha256": dshas[pm_id],
            "ceg_queue_id": qid,
            "ceg_record_class": st_ceg["record_class"],
            "ring1_max_biological_fidelity_tier": raw_rec["study_metadata"]["max_biological_fidelity_tier"],
            "ceg_fidelity_tier": st_ceg["fidelity_tier"],
            "species_and_model_verified": st_ceg["biological_model"],
            "immune_and_immunosuppression_context_verified": st_ceg["immune_context"],
            "arms_and_denominators_verified": [
                {
                    "arm_id": a["arm_id"],
                    "is_reference_control": a["is_reference_control"],
                    "cell_source_class": a["gate1_substrate_and_differentiation"]["cell_source_class"],
                    "sample_size_n": a["sample_size_n"],
                    "sample_size_unit": a["sample_size_unit"],
                    "transplant_site": a["gate5_engraftment_niche"]["transplant_site"],
                    "systemic_immunosuppression_regimen": a["gate5_engraftment_niche"]["systemic_immunosuppression_regimen"],
                    "followup_duration_days": a["quantitative_readouts"]["followup_duration_days"],
                }
                for a in raw_rec["arms"]
            ],
            "oa_license": sp["oa_lic"],
            "oa_public_quote_allowed": sp["oa_pub_allowed"],
            "g4_raw_aggregate_verbatim_chars": g4_detail[pm_id]["raw_aggregate_verbatim_chars_all_fields"],
            "g4_public_grm_shingle_chars": g4_detail[pm_id]["grm_public_shingle_chars"],
            "ring1_atomic_effects_verified": eff_audit,
            "ceg_outcomes_verified": [
                {
                    "outcome_node_id": o["outcome_node_id"],
                    "manuscript_tier": o["manuscript_tier"],
                    "direction": o["direction"],
                    "stat_type": o["stat_type"],
                    "comparison_arms": o["comparison_arms"],
                    "intervention_value": o["intervention_value"],
                    "source_pin": o["source_pin"],
                    "quote_sha256": o["quote_sha256"],
                }
                for o in ceg_ocs
            ],
            "pdl019_primary_source_audit_status": "VERIFIED_AGAINST_PRIMARY_SOURCE_DOSSIER",
        })

    pdl019_receipt = {
        "schema_version": "0.8.0-exp028-pdl019-s56-extraction-verification-receipt-v1",
        "investigation_id": "EXP-028",
        "candidate_id": "CAND-031",
        "target_iip": "IIP-0041",
        "verified_date": PINNED_AUDIT_DATE,
        "python_version": sys.version.split()[0],
        "bundle_file": EVIDENCE_BUNDLE_OUT.name,
        "bundle_sha256": bundle_sha,
        "overall_status": bundle["live_validator_audit"]["overall_status"],
        "counts": {
            "net_new_ring1_studies": len(ring1_records),
            "net_new_ring1_arms": sum(len(r["arms"]) for r in ring1_records),
            "net_new_ring1_atomic_effects": sum(len(r["atomic_effects"]) for r in ring1_records),
            "net_new_ceg_studies": len(ceg_new_studies),
            "net_new_ceg_arms": len(ceg_new_arms),
            "net_new_ceg_outcomes": len(ceg_new_outcomes),
            "net_new_ceg_edges": len(ceg_new_edges),
            "cc_by_4_0_live_quote_studies": sum(1 for s in study_specs if s["oa_pub_allowed"]),
            "non_oa_or_conservative_redacted_studies": sum(1 for s in study_specs if not s["oa_pub_allowed"]),
            "standalone_post_exp028_ring1_total": len(live_r1) + len(ring1_records),
            "standalone_post_exp028_ceg_total": len(live_ceg_sids) + len(ceg_new_studies),
        },
        "s5_unified_migration_note": (
            "All 8 CEG studies carry deterministic production record_class='empirical_primary_study', valid 20-key live effector topics, "
            "and primary-source-verified species/model/arm/comparator/timepoint/outcome/immunosuppression tiers. Fold-in into live OpenIslet "
            "executes as part of one unified Wave-5 Ring-1/CEG migration updating live cardinality constants and ideas/CEG-DELTA-STAGING.md."
        ),
        "gates_summary": {k: v["passed"] for k, v in gates.items()},
        "per_study_pdl019_primary_source_verification": per_study_pdl019,
    }
    pdl_raw = json.dumps(pdl019_receipt, indent=2, ensure_ascii=False)
    if PRIVACY_HOME_TOKEN in pdl_raw:
        raise ValueError("Privacy leak in extraction_verification_receipt.json!")
    EXTRACTION_RECEIPT_OUT.write_text(pdl_raw + "\n", encoding="utf-8")
    return bundle["live_validator_audit"]


def _verify_g2b_tamper_resistance_self_test() -> dict[str, Any]:
    """Optimize-safe self-test confirming valid redaction tokens pass and tampered digests fail under both -B and -O -B."""
    sample_pmid = "34130115"
    sample_quote = "99th percentile of 336 healthy controls, the ZnT8ecA positivity rate was 23.6% (74/313)"
    valid_tok = f"[REDACTED_NON_OA_EXCERPT: see PMID:{sample_pmid} field=verbatim_evidence_quote quote_sha256={sha256_str(sample_quote)}]"
    if not pep.is_redaction_token_prefix(valid_tok):
        raise ValueError("G2b self-test failed: valid token prefix rejected")
    if not pep.validate_token(valid_tok, expected_pmid=sample_pmid, source_quote=sample_quote, expected_field="verbatim_evidence_quote"):
        raise ValueError("G2b self-test failed: valid redaction token did not validate")
    tampered_tok, n_sub = re.subn(
        r"(quote_sha256=)([0-9a-f])",
        lambda m: m.group(1) + ("0" if m.group(2) != "0" else "1"),
        valid_tok,
        count=1,
    )
    if n_sub != 1:
        raise ValueError("G2b self-test failed: could not tamper token digest")
    tamper_rejected = not pep.validate_token(
        tampered_tok, expected_pmid=sample_pmid, source_quote=sample_quote, expected_field="verbatim_evidence_quote"
    )
    if not tamper_rejected:
        raise ValueError("G2b self-test failed: tampered redaction token was NOT rejected!")
    return {
        "valid_token_accepted": True,
        "tampered_digest_rejected": tamper_rejected,
        "optimize_safe_no_assert": True,
    }


def run_installed_check(output_path: pathlib.Path | None = None) -> dict[str, Any]:
    """
    Portable, read-only self-check mode suitable for running when installed at
    OpenIslet/scripts/verify_iip0041_clinical_h1_cd64t_siglec.py without external caches or network.
    - REQUIRES installed data/constructs/islet1_abx_cd64t_il1rn_modeb_v0.8.0.fasta and
      data/protocols/iip0041_abx_cd64t_il1rn_side_contract_v0.8.0.json (fail-closed if absent).
    - Emits a host-independent deterministic portable receipt payload decoupled from runtime python_version
      and local private XML cache presence so private checkouts and public snapshots verify identically.
    """
    print("=== IIP-0041 / EXP-028 INSTALLED READ-ONLY SELF-CHECK ===")
    print(f"0. Runtime: Python {sys.version.split()[0]} (optimize={sys.flags.optimize}, bytecode_disabled={sys.dont_write_bytecode})")
    part_a = analyze_clinical_h1_reanchor()

    # REQUIRE runtime-SHA-256-pinned immutable side contract and verify FASTA pin alignment
    side_contract, side_contract_sha, side_contract_pin_ok = _load_iip0041_side_contract(require_pinned_sha=True)
    if not side_contract_pin_ok or side_contract_sha != PINNED_SIDE_CONTRACT_SHA256:
        raise ValueError(f"Pinned side-contract SHA-256 check failed: {side_contract_sha} != {PINNED_SIDE_CONTRACT_SHA256}")
    sc_fasta_pin = side_contract["zero_lims_touch_implementation_compliance"]["modeb_construct_fasta_sha256"]
    if sc_fasta_pin != PINNED_FASTA_SHA:
        raise ValueError(f"Side-contract Mode-B FASTA SHA mismatch: {sc_fasta_pin} != {PINNED_FASTA_SHA}")

    # REQUIRE live IIP-0035 D1b FASTA for cross-identity verification AND REQUIRE installed Mode-B FASTA (fail-closed!)
    d1_v2_path = OPENISLET_ROOT / "data/constructs/islet1_d1b_auto_v2_v0.8.0.fasta"
    if not d1_v2_path.is_file():
        raise FileNotFoundError(f"Missing live OpenIslet construct file: {d1_v2_path}")
    d1_v2_fa = parse_fasta(d1_v2_path)
    seq_l1a = d1_v2_fa["D1AUTO_v2_L1A_CIITA_CD64T_IL1RN"]
    seq_l1b = d1_v2_fa["D1AUTO_v2_L1B_CIITA_CD64T_CD46WT_COMPARATOR"]

    modeb_fa_path = OPENISLET_ROOT / PINNED_MODEB_FASTA_REL
    if not modeb_fa_path.is_file():
        raise FileNotFoundError(f"Missing REQUIRED Mode-B construct FASTA: {modeb_fa_path}")
    fa_recs = parse_fasta(modeb_fa_path)
    fa_sha = sha256_file(modeb_fa_path)
    expected_donor_ids = {
        d["fasta_record_id"]
        for d in (
            side_contract["modeb_core_abx_ciita_exon5_suite"]["active_wave5_go_scope_donors"]
            + side_contract["modeb_core_abx_ciita_exon5_suite"]["archived_hold_comparator_donors"]
        )
    }
    if len(fa_recs) != 6 or set(fa_recs.keys()) != expected_donor_ids:
        raise ValueError(
            f"Mode-B FASTA record set mismatch in {modeb_fa_path.name}: got {sorted(fa_recs.keys())} vs expected {sorted(expected_donor_ids)}"
        )
    if fa_recs.get("ABX_L2_v2_CD64T_IL1RN") != seq_l1a:
        raise ValueError("ABX_L2_v2_CD64T_IL1RN does not match live D1AUTO_v2_L1A_CIITA_CD64T_IL1RN byte-for-byte")
    if fa_recs.get("ABX_L2_v2_CD64T_CD46WT_COMP") != seq_l1b:
        raise ValueError("ABX_L2_v2_CD64T_CD46WT_COMP does not match live D1AUTO_v2_L1B_CIITA_CD64T_CD46WT_COMPARATOR byte-for-byte")
    if fa_sha != PINNED_FASTA_SHA:
        raise ValueError(f"Mode-B FASTA SHA-256 mismatch: {fa_sha} != {PINNED_FASTA_SHA}")

    for donor_spec in (
        side_contract["modeb_core_abx_ciita_exon5_suite"]["active_wave5_go_scope_donors"]
        + side_contract["modeb_core_abx_ciita_exon5_suite"]["archived_hold_comparator_donors"]
    ):
        did = donor_spec["fasta_record_id"]
        exp_dsha = donor_spec.get("donor_sha256")
        if exp_dsha and sha256_str(fa_recs[did]) != exp_dsha:
            raise ValueError(f"Per-donor SHA-256 mismatch for {did}: {sha256_str(fa_recs[did])} != {exp_dsha}")

    fasta_check = {
        "required": True,
        "present": True,