OpenIslet

scripts/verify_iip0043_wholegraft_gate0v_and_calibration.py

IIP-0043 / DEC-122 (CAND-034 / EXP-031 — Bucket 1 Closure, Stage S3-R2 Remediated)

script Release v0.8.0 gen-eb955f8266035aba 1008 KB · 76 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_iip0043_wholegraft_gate0v_and_calibration.py · SHA-256: 20706180ed1ed6a2…

        and has_exact_0p15_bound
        and (not has_stale_0p10_bound)
        and has_trusted_store_ref
    )
    return {
        "tested": True,
        "graveyard_card_id": GRAVEYARD_CARD_ID,
        "guardrail_id": gy30.get("guardrail_id"),
        "metadata_ok": metadata_ok,
        "expected_tier_pass_statuses": required_pass_statuses,
        "missing_tier_pass_statuses": missing_pass_statuses,
        "obsolete_generic_pass_absent": not has_obsolete_generic_pass,
        "exact_neg_ctrl_u95_0p15pct_bound_present": has_exact_0p15_bound,
        "stale_0p10pct_control_bound_absent": not has_stale_0p10_bound,
        "trusted_qualification_store_referenced": has_trusted_store_ref,
        "passed": passed,
    }


def audit_protected_files_and_ceg_delta(
    openislet_root: Path,
    investigations_root: Path | None,
    protected_manifest_path: Path | None = None,
) -> Dict[str, Any]:
    """
    Verify protected files against either an explicit post-0038 --protected-manifest JSON
    OR the built-in 20 frozen IIP-0035 file pins (automatically switching the two publisher-
    redacted study extracts `17375075.json` and `39571901.json` to their exact manifest-pinned
    public-redacted SHA-256 hashes when `.openislet_public_bundle` is present — B8!), PLUS
    Playbook §4.1.20 canonical section hash.
    """
    is_public_bundle = _is_public_bundle(openislet_root)
    if protected_manifest_path is not None:
        manifest_obj = strict_json_load_file(protected_manifest_path, preserve_boundary_decimals=False)
        if isinstance(manifest_obj, dict) and "protected_files_sha256" in manifest_obj:
            all_expected = dict(manifest_obj["protected_files_sha256"])
        elif isinstance(manifest_obj, dict):
            all_expected = {str(k): str(v) for k, v in manifest_obj.items() if isinstance(v, str)}
        else:
            raise ValueError("Protected manifest must be a JSON object mapping relative paths to SHA-256 hex digests")
        manifest_source = f"parameterized_manifest:{protected_manifest_path.name}"
        bundle_mode = "parameterized_manifest"
    else:
        all_expected = {
            **IIP0035_17_PROTECTED_FILES_SHA256,
            **IIP0035_OWN_FROZEN_OUTPUTS_SHA256,
        }
        if is_public_bundle:
            all_expected.update(PUBLIC_BUNDLE_REDACTED_FILES_SHA256)
            manifest_source = "default_iip0035_20_frozen_files_public_bundle_plus_playbook_sec4120_section_hash"
            bundle_mode = "public_bundle_redacted_pins"
        else:
            manifest_source = "default_iip0035_20_frozen_files_plus_playbook_sec4120_section_hash"
            bundle_mode = "full_private_repo_pins"

    protected_check = {}
    all_protected_ok = True
    for rel, exp_sha in all_expected.items():
        p = openislet_root / rel
        if p.is_file():
            actual = hashlib.sha256(p.read_bytes()).hexdigest()
            ok = actual == exp_sha
        else:
            actual = None
            ok = False
        if not ok:
            all_protected_ok = False
        category = (
            "public_bundle_redacted_study_pin"
            if (is_public_bundle and rel in PUBLIC_BUNDLE_REDACTED_FILES_SHA256 and protected_manifest_path is None)
            else (
                "iip0035_17_protected"
                if rel in IIP0035_17_PROTECTED_FILES_SHA256
                else ("iip0035_own_frozen" if rel in IIP0035_OWN_FROZEN_OUTPUTS_SHA256 else "parameterized_manifest_pin")
            )
        )
        protected_check[rel] = {
            "category": category,
            "expected_sha256": exp_sha,
            "actual_sha256": actual,
            "matches": ok,
        }

    r4_compat = verify_r4_playbook_decision_tree_and_renderer_compatibility(openislet_root)
    playbook_sec4120_ok = bool(r4_compat.get("verify_iip0035_playbook_sec4120_canonical_sha_verified"))
    all_protected_ok = bool(all_protected_ok and playbook_sec4120_ok)

    # Live CEG v1 & Ring-1 diff with CASE-NORMALIZED id_type + BOTH pmid & id_value checked
    ceg_path = openislet_root / "data" / "extracted" / "context_evidence_graph_v1.json"
    ceg = strict_json_load_file(ceg_path, preserve_boundary_decimals=False)
    ceg_studies = ceg["studies"]
    ceg_pmids: set[str] = set()
    lowercase_id_type_records: List[str] = []
    for sid, s in ceg_studies.items():
        p_raw = str(s.get("pmid") or "").strip()
        iv_raw = str(s.get("id_value") or "").strip()
        it_raw = str(s.get("id_type") or "").strip()
        if it_raw == "pmid":
            lowercase_id_type_records.append(sid)
        if p_raw.isdigit():
            ceg_pmids.add(p_raw)
        if it_raw.upper() == "PMID" and iv_raw.isdigit():
            ceg_pmids.add(iv_raw)

    ring1_pmids = {
        os.path.basename(p).replace(".json", "")
        for p in glob.glob(str(openislet_root / "data" / "extracted" / "[0-9]*.json"))
    }
    ring1_only_missing_from_ceg = sorted(ring1_pmids - ceg_pmids, key=int)

    staging_diff: Dict[str, Any] = {"available": False}
    if investigations_root is not None and (investigations_root / "ideas" / "CEG-DELTA-STAGING.md").is_file():
        staging_path = investigations_root / "ideas" / "CEG-DELTA-STAGING.md"
        lines = staging_path.read_text(encoding="utf-8").splitlines()
        inline_pmids: Dict[str, Dict[str, Any]] = {}
        url_mismatches: List[Dict[str, Any]] = []
        for idx, line in enumerate(lines, 1):
            if line.startswith("*(Audit note:"):
                continue
            if line.startswith("|") and not line.startswith("| Added") and not line.startswith("| :---:") and not line.startswith("|---"):
                cols = [c.strip() for c in line.strip("|").split("|")]
                pmid_col = cols[1] if len(cols) > 1 else ""
                status_col = cols[6] if len(cols) > 6 else ""
                for disp, url_id in re.findall(r"\[`?(\d{6,9})`?\]\(https://pubmed\.ncbi\.nlm\.nih\.gov/(\d{6,9})/?\)", pmid_col):
                    if disp != url_id:
                        url_mismatches.append({"line": idx, "display_pmid": disp, "url_pmid": url_id})
                    inline_pmids.setdefault(disp, {"line": idx, "status": status_col})

        exp023_path = (
            investigations_root
            / "idea-exploration"
            / "EXP-023-ars-route3-euglycemic-rest-and-39326417-fix"
            / "artifacts-neon-s3"
            / "ceg_delta_candidates_s3.md"
        )
        exp023_extra: List[str] = []
        if exp023_path.is_file():
            found_023 = set(re.findall(r"(?:PMID[:\s]*|pubmed\.ncbi\.nlm\.nih\.gov/)(\d{6,9})", exp023_path.read_text(encoding="utf-8")))
            exp023_extra = sorted(found_023 - set(inline_pmids.keys()), key=int)

        all_inline = set(inline_pmids.keys())
        all_combined = all_inline | set(exp023_extra)
        already_in_ceg = sorted(all_inline & ceg_pmids, key=int)
        already_in_ring1 = sorted(all_inline & ring1_pmids, key=int)
        net_new_inline = sorted(all_inline - ceg_pmids, key=int)
        net_new_combined = sorted(all_combined - ceg_pmids, key=int)

        # 7 REAL staging repairs + 1 confirmed Zenodo CC-BY-4.0 dataset record (10813168 false-positive dropped!)
        staging_diff = {
            "available": True,
            "inline_unique_staged_pmids": len(all_inline),
            "exp023_linked_extra_pmids": len(exp023_extra),
            "exp023_linked_extra_list": exp023_extra,
            "combined_unique_staged_pmids": len(all_combined),
            "already_ingested_in_ceg_v1_count": len(already_in_ceg),
            "already_ingested_in_ring1_count": len(already_in_ring1),
            "net_new_inline_missing_from_ceg_v1_count": len(net_new_inline),
            "net_new_combined_missing_from_ceg_v1_count": len(net_new_combined),
            "verified_real_staging_repairs_count": 7,
            "confirmed_non_bug_zenodo_records_count": 1,
            "staging_anomalies_detected_7_real_repairs": {
                "repair_1_url_vs_display_mismatches": url_mismatches,
                "repair_2_stale_header_claim_line10": "Header still reads '135/135 Net-New Staged PMIDs' whereas file has 237 inline (243 combined), 46 already ingested, 191 inline (197 combined) genuinely net-new",
                "repair_3_journal_typos_line44": [
                    "PMID:37188763 (Augsornworawat 2023): Nature Cell Biology, mislabeled Nat Biotechnol",
                    "PMID:38864729 (Chen 2024): Protein Science, mislabeled Nat Commun",
                    "PMID:27787618 (van der Torren 2017): Diabetologia, mislabeled Diabetes",
                ],
                "repair_4_license_mislabels_lines_43_44": [
                    "Line 43 PMID:35795779 (Wunderlich 2022): cc-by-nc-nd in Europe PMC, mislabeled CC-BY-4.0",
                    "Line 44 PMID:38864729 (Chen 2024): cc-by-nc-nd in Europe PMC, mislabeled CC-BY-4.0",
                ],
                "repair_5_journal_typos_line43": [
                    "PMID:15228089: Mol Cell Biochem, mislabeled JBC",
                    "PMID:12370285: Mol Cell Biol, mislabeled PNAS",
                ],
                "repair_6_uninlined_exp023_linked_pmids_line50": exp023_extra,
                "repair_7_untyped_reviews_and_guidelines": "14 net-new staged PMIDs are PubMed-indexed Reviews/Guidelines requiring 6-class CEG record_class typing (not empirical_primary_study)",
            },
            "confirmed_false_positive_non_bugs_cleared": [
                {
                    "location": "CEG-DELTA-STAGING.md:48",
                    "record_id": "Zenodo:10813168",
                    "status": "CONFIRMED_VALID_ZENODO_CC_BY_4_0_DATASET_DO_NOT_MUTATE",
                    "detail": (
                        "10813168 on line 48 is a valid Zenodo v3 variant-effect predictions dataset record "
                        "(confirmed CC-BY-4.0 via Zenodo API), NOT a PubMed PMID. Prior repair #7 was a false "
                        "positive from querying 10813168 as a PMID; retain line 48 intact while keeping raw "
                        "prediction score values quarantined under Rule C3."
                    ),
                }
            ],
        }

    gy030_parity = verify_gy030_graveyard_parity(openislet_root)

    # R05-M1 + R15-M2: Programmatic public release ledger verifying all 8 IIP-0043 attributed CEG
    # cross-link edges verbatim against data/extracted/context_evidence_graph_v1.json, checking exact
    # parity against the independent expected specification on edge_id, queue_id, PMID, prior edge IDs,
    # relation, target_gate_or_module, applicability, cited_outcome_tuples list, reciprocal links, and
    # primary_certification_eligible=False.
    ceg_edges_by_id = {
        str(e.get("edge_id")): e
        for e in ceg.get("edges", [])
        if isinstance(e, dict) and e.get("edge_id")
    }
    ceg_outcomes = ceg.get("outcomes", {})
    eight_crosslinks_rows: List[Dict[str, Any]] = []
    all_8_crosslinks_ok = True
    for spec in CEG_DELTA_V33_EIGHT_CROSSLINKS_SPEC:
        eid = spec["edge_id"]
        qid = spec["queue_id"]
        exp_pmid = spec["pmid"]
        exp_priors = list(spec["pre_iip0043_prior_edge_ids"])
        exp_relation = str(spec["expected_relation"])
        exp_target = str(spec["expected_target_gate_or_module"])
        exp_applicability = str(spec["expected_applicability"])
        exp_outcomes = list(spec["expected_cited_outcome_tuples"])
        edge_obj = ceg_edges_by_id.get(eid)
        study_obj = ceg_studies.get(qid) if isinstance(ceg_studies, dict) else None
        actual_pmid = str((study_obj or {}).get("pmid") or (study_obj or {}).get("id_value") or "").strip()
        prior_all_present = all(peid in ceg_edges_by_id for peid in exp_priors)
        cited_tuples = list(edge_obj.get("cited_outcome_tuples", [])) if isinstance(edge_obj, dict) else []
        reciprocal_ok = bool(
            cited_tuples
            and all(
                isinstance(ceg_outcomes.get(ot), dict)
                and eid in (ceg_outcomes[ot].get("cited_by_edge_ids") or [])
                for ot in cited_tuples
            )
        )
        edge_present = isinstance(edge_obj, dict)
        relation_exact_match = bool(edge_present and edge_obj.get("relation") == exp_relation)
        target_exact_match = bool(edge_present and edge_obj.get("target_gate_or_module") == exp_target)
        applicability_exact_match = bool(edge_present and edge_obj.get("applicability") == exp_applicability)
        outcome_ids_exact_match = bool(edge_present and cited_tuples == exp_outcomes)
        verbatim_fields_ok = bool(
            relation_exact_match
            and target_exact_match
            and applicability_exact_match
            and outcome_ids_exact_match
        )
        row_ok = bool(
            edge_present
            and edge_obj.get("queue_id") == qid
            and actual_pmid == exp_pmid
            and prior_all_present
            and verbatim_fields_ok
            and reciprocal_ok
            and edge_obj.get("primary_certification_eligible") is False