OpenIslet

scripts/build_context_evidence_graph.py

Build and verify the Layer-1 Context-Evidence Graph (`CEG`) public artifacts.

script Release v0.8.0 gen-eb955f8266035aba 229 KB · 16 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/build_context_evidence_graph.py · SHA-256: 2758ba22e378ffed…

        study_index.append(rec)

    return {
        "schema_version": "openislet_layer1_context_evidence_graph_atlas_v1.0",
        "status": "COMPLETE_LAYER1_CONTEXT_EVIDENCE_GRAPH_ATLAS_V1",
        "evidence_class": "STRUCTURED_LITERATURE_CONTEXT_EVIDENCE_GRAPH",
        "scope_and_scoring_separation_note": (
            f"Maps {len(studies):,} total CEG records ({record_class_counts['empirical_primary_study']:,} empirical primary studies, "
            f"{record_class_counts['trial_registry_protocol']:,} trial registry protocols, "
            f"{record_class_counts['regulatory_or_guidance_document']:,} regulatory/guidance documents, "
            f"{record_class_counts['computational_model_or_simulation']:,} computational/modeling-primary records, "
            f"{record_class_counts['correspondence_or_secondary_summary']:,} correspondence/secondary summary, and "
            f"{record_class_counts['superseded_preprint_duplicate']:,} superseded preprint duplicates), "
            f"{len(arms):,} experimental/control arms, {len(outcomes):,} structured outcomes, and {len(edges):,} blueprint links "
            f"across all five Islet-1 biological gates and 20 effector pathways, screened from "
            f"{ceg['screening_funnel']['screened_records_total']:,} deduplicated candidate records. "
            "The Layer-1 2,160-stack prior-anchored scenario evaluator retains its 642-study Ring-1 scoring baseline "
            "unchanged (+0.00 pp under the CEG v1 quality sweep and tier-split cutover) unless an explicit Islet Improvement Proposal "
            "updates a module parameter or Idea Graveyard rule."
        ),
        "summary": {
            "screened_candidate_records_total": ceg["screening_funnel"]["screened_records_total"],
            "candidates_advanced_total": ceg["screening_funnel"]["candidates_advanced_total"],
            "ceg_records_total": len(studies),
            "primary_empirical_studies_extracted": record_class_counts["empirical_primary_study"],
            "trial_registry_protocols_in_ceg": record_class_counts["trial_registry_protocol"],
            "regulatory_or_guidance_records_in_ceg": record_class_counts["regulatory_or_guidance_document"],
            "computational_models_in_ceg": record_class_counts["computational_model_or_simulation"],
            "correspondence_or_secondary_records_in_ceg": record_class_counts["correspondence_or_secondary_summary"],
            "superseded_preprint_duplicates_in_ceg": record_class_counts["superseded_preprint_duplicate"],
            "ring1_core_records_in_ceg_total": r1_total_count,
            "ring1_empirical_core_studies_in_ceg": r1_empirical_count,
            "new_expansion_empirical_studies_in_ceg": non_r1_empirical_count,
            "non_r1_ceg_records_total": non_r1_total_count,
            "ring1_scoring_baseline_studies_unchanged": 642,
            "experimental_and_control_arms_total": len(arms),
            "structured_outcomes_total": len(outcomes),
            "outcomes_cited_by_blueprint_links": cited_outcomes,
            "background_arm_outcomes_retained": len(outcomes) - cited_outcomes,
            "blueprint_links_total": len(edges),
            "biological_effector_nodes_total": len(effectors),
            "graveyard_rules_indexed_total": len(graveyard),
            "unresolved_outcome_citations": 0,
            "inline_verbatim_quotes_shipped": 0,
        },
        "screening_funnel": ceg["screening_funnel"],
        "record_class_distribution": dict(sorted(record_class_counts.items())),
        "study_identifier_types": dict(sorted(id_types.items())),
        "fidelity_tier_distribution": {
            "studies_by_manuscript_tier": dict(sorted(tier_studies.items())),
            "outcomes_by_manuscript_tier": dict(sorted(tier_outcomes.items())),
        },
        "outcome_distributions": {
            "by_direction": dict(sorted(direction_counts.items())),
            "by_stat_type": dict(sorted(stat_counts.items())),
        },
        "blueprint_link_distributions": {
            "by_relation": dict(sorted(relation_counts.items())),
            "by_incorporation": dict(sorted(incorporation_counts.items())),
            "by_applicability": dict(sorted(applicability_counts.items())),
        },
        "gate_and_design_claim_balance": {
            "by_gate": {k: dict(sorted(v.items())) for k, v in sorted(by_gate.items())},
            "by_design": {k: dict(sorted(v.items())) for k, v in sorted(by_design.items())},
        },
        "effector_atlas": effector_summaries,
        "graveyard_evidence_index": graveyard_summaries,
        "study_index": study_index,
    }


def verify_ceg_payload(ceg: dict[str, Any], repo_root: Path = REPO_ROOT, *, require_sources: bool = False) -> dict[str, int]:
    """Fail-closed structural, referential, and rights verification of `context_evidence_graph_v1.json`."""
    studies = ceg.get("studies")
    arms = ceg.get("arms")
    outcomes = ceg.get("outcomes")
    edges = ceg.get("edges")
    effectors = ceg.get("effectors")
    graveyard = ceg.get("graveyard_index")

    if not isinstance(studies, dict) or len(studies) != 1259:
        raise ValueError(f"Expected 1,259 studies in CEG (1,234 baseline + 25 Wave-6), got {len(studies) if isinstance(studies, dict) else type(studies)}")
    if not isinstance(arms, dict) or len(arms) != 7975:
        raise ValueError(f"Expected 7,975 arms in CEG (7,914 baseline + 61 Wave-6), got {len(arms) if isinstance(arms, dict) else type(arms)}")
    if not isinstance(outcomes, dict) or len(outcomes) != 14397:
        raise ValueError(f"Expected 14,397 outcomes in CEG (14,351 baseline + 46 Wave-6), got {len(outcomes) if isinstance(outcomes, dict) else type(outcomes)}")
    if not isinstance(edges, list) or len(edges) != 2602:
        raise ValueError(f"Expected 2,602 edges in CEG (2,570 baseline + 32 Wave-6), got {len(edges) if isinstance(edges, list) else type(edges)}")
    # Audit R7-01: Unconditional canonical map-key vs embedded record ID parity & global edge_id uniqueness!
    for _mk_s, _st_chk in studies.items():
        if not isinstance(_st_chk, dict) or not isinstance(_mk_s, str) or _st_chk.get("queue_id") != _mk_s:
            raise ValueError(f"WAVE6_MAP_KEY_ID_MISMATCH: study map key {_mk_s!r} disagrees with embedded queue_id={_st_chk.get('queue_id') if isinstance(_st_chk, dict) else type(_st_chk).__name__!r}")
        if "study_id" in _st_chk and _st_chk["study_id"] is not None and _st_chk["study_id"] != _mk_s:
            raise ValueError(f"WAVE6_MAP_KEY_ID_MISMATCH: study map key {_mk_s!r} disagrees with embedded study_id={_st_chk['study_id']!r}")
    for _mk_a, _ar_chk in arms.items():
        if not isinstance(_ar_chk, dict) or not isinstance(_mk_a, str) or _ar_chk.get("variable_id") != _mk_a:
            raise ValueError(f"WAVE6_MAP_KEY_ID_MISMATCH: arm map key {_mk_a!r} disagrees with embedded variable_id={_ar_chk.get('variable_id') if isinstance(_ar_chk, dict) else type(_ar_chk).__name__!r}")
    for _mk_o, _oc_chk in outcomes.items():
        if (
            not isinstance(_oc_chk, dict)
            or not isinstance(_mk_o, str)
            or _oc_chk.get("outcome_node_id") != _mk_o
            or f"{_oc_chk.get('queue_id')}:{_oc_chk.get('outcome_id')}" != _mk_o
        ):
            raise ValueError(f"WAVE6_MAP_KEY_ID_MISMATCH: outcome map key {_mk_o!r} disagrees with embedded outcome_node_id/queue_id:outcome_id")
    _seen_all_eids_r7: set[str] = set()
    for _e_chk in edges:
        _eid_chk = _e_chk.get("edge_id") if isinstance(_e_chk, dict) else None
        if not isinstance(_eid_chk, str) or not _eid_chk.strip():
            raise ValueError(f"WAVE6_EDGE_ID_INVALID: malformed edge_id={_eid_chk!r}")
        if _eid_chk in _seen_all_eids_r7:
            raise ValueError(f"WAVE6_DUPLICATE_EDGE_ID: duplicate edge_id={_eid_chk!r} rejected")
        _seen_all_eids_r7.add(_eid_chk)
    if not isinstance(effectors, dict) or len(effectors) != 20:
        raise ValueError(f"Expected 20 effectors in CEG, got {len(effectors) if isinstance(effectors, dict) else type(effectors)}")
    if not isinstance(graveyard, list) or len(graveyard) != 10:
        raise ValueError(f"Expected 10 graveyard entries in CEG, got {len(graveyard) if isinstance(graveyard, list) else type(graveyard)}")

    # Typed record_class integrity, supersession/same-patient linkage, and fail-closed certification gate
    def _study_pmid(st_obj: dict[str, Any]) -> str:
        return str(
            st_obj.get("pmid")
            or (st_obj.get("id_value") if str(st_obj.get("id_type") or "").strip().lower() == "pmid" else "")
            or ""
        ).strip()

    expected_rc_counts: Counter[str] = Counter()
    _seen_study_pmids: dict[str, str] = {}
    for qid, s in studies.items():
        if s.get("fidelity_tier") not in CANONICAL_8_FIDELITY_TIERS:
            raise ValueError(f"Study {qid} has non-canonical fidelity_tier={s.get('fidelity_tier')!r}")
        if type(s.get("pub_year")) is not int or not (1900 <= s["pub_year"] <= 2100):
            raise ValueError(f"Study {qid} missing valid integer pub_year (got {s.get('pub_year')!r})")
        _pm_chk = _study_pmid(s)
        if _pm_chk:
            if _pm_chk in _seen_study_pmids:
                raise ValueError(f"Duplicate PMID {_pm_chk} across studies {_seen_study_pmids[_pm_chk]} and {qid}")
            _seen_study_pmids[_pm_chk] = qid
        expected_rc = classify_ceg_study_record(s)
        if s.get("record_class") != expected_rc:
            raise ValueError(f"Study {qid} has record_class={s.get('record_class')!r}, expected {expected_rc!r}")
        if expected_rc == "empirical_primary_study":
            _fa_chk = str(s.get("first_author") or "").strip()
            _j_chk = str(s.get("journal") or "").strip()
            _t_chk = str(s.get("title") or "").strip()
            if not _fa_chk or (_j_chk and _fa_chk.casefold() == _j_chk.casefold()):
                raise ValueError(
                    f"Empirical study {qid} has journal-as-author or empty first_author={_fa_chk!r} (journal={_j_chk!r})"
                )
            if not _t_chk or re.match(r"^(?:Preprint DOI\b|ADA 2026 Late-Breaking Abstract\b)", _t_chk, flags=re.IGNORECASE):
                raise ValueError(f"Empirical study {qid} has placeholder title={_t_chk!r}")
        expected_rc_counts[expected_rc] += 1
        sup_qid = s.get("superseded_by_queue_id")
        sup_pmid = s.get("superseded_by_pmid")
        if expected_rc == "superseded_preprint_duplicate" and (not sup_qid or not sup_pmid):
            raise ValueError(f"Superseded duplicate study {qid} must declare superseded_by_queue_id and superseded_by_pmid")
        if sup_qid is not None:
            if not isinstance(sup_qid, str) or sup_qid == qid or sup_qid not in studies:
                raise ValueError(f"Study {qid} superseded_by_queue_id={sup_qid!r} does not resolve to another existing study")
            target_pmid = _study_pmid(studies[sup_qid])
            if not isinstance(sup_pmid, str) or not sup_pmid.strip() or sup_pmid.strip() != target_pmid:
                raise ValueError(
                    f"Study {qid} superseded_by_pmid={sup_pmid!r} mismatches target study {sup_qid} PMID {target_pmid!r}"
                )
            _seen_sup = {qid}
            _cur_sup = sup_qid
            while _cur_sup is not None:
                if _cur_sup in _seen_sup:
                    raise ValueError(f"Study {qid} superseded_by_queue_id chain forms a supersession cycle at {_cur_sup!r}")
                _seen_sup.add(_cur_sup)
                _nxt = studies[_cur_sup].get("superseded_by_queue_id") if _cur_sup in studies else None
                _cur_sup = _nxt if isinstance(_nxt, str) and _nxt in studies else None
        elif sup_pmid is not None:
            raise ValueError(f"Study {qid} declares superseded_by_pmid={sup_pmid!r} without superseded_by_queue_id")
        _st_sp = s.get("source_pin")
        if _st_sp is not None and not isinstance(_st_sp, dict):
            raise ValueError(f"Study {qid} source_pin must be a dict, got {type(_st_sp).__name__}")
        for _link_field in ("same_patient_followup_of_queue_id", "same_patient_linked_queue_id"):
            _lqid = s.get(_link_field)
            if _lqid is not None:
                if not isinstance(_lqid, str) or _lqid == qid or _lqid not in studies:
                    raise ValueError(f"Study {qid} {_link_field}={_lqid!r} does not resolve to another existing study")
                if _link_field == "same_patient_followup_of_queue_id" and s.get("same_patient_followup_of_pmid") is not None:
                    _lpmid = str(s.get("same_patient_followup_of_pmid") or "").strip()
                    _tpmid = _study_pmid(studies[_lqid])
                    if _lpmid != _tpmid:
                        raise ValueError(f"Study {qid} same_patient_followup_of_pmid={_lpmid!r} mismatches target {_lqid} PMID {_tpmid!r}")
    if (ceg.get("counts") or {}).get("record_class_counts") != dict(sorted(expected_rc_counts.items())):
        raise ValueError("CEG counts.record_class_counts disagrees with deterministic study record_class classification")
    _sf = ceg.get("screening_funnel") or {}
    if not isinstance(_sf, dict):
        raise ValueError("CEG screening_funnel must be a dict")
    _sf_total = _sf.get("screened_records_total")
    _sf_r1 = _sf.get("ring1_existing_records_screened")
    _sf_new = _sf.get("new_candidate_records_screened")
    _sf_adv = _sf.get("candidates_advanced_total")
    _sf_park = _sf.get("contextual_reviews_parked_total")
    _sf_excl = _sf.get("off_topic_records_excluded_total")
    _sf_w1 = _sf.get("wave1_ceg_records_extracted_total")
    _sf_rem = _sf.get("remaining_supporting_catalog_queued_for_later_waves")
    if not all(type(v) is int for v in (_sf_total, _sf_r1, _sf_new, _sf_adv, _sf_park, _sf_excl, _sf_w1, _sf_rem)):
        raise ValueError("CEG screening_funnel missing required integer totals")
    if _sf_r1 + _sf_new != _sf_total:
        raise ValueError(f"CEG screening_funnel mismatch: ring1 ({_sf_r1}) + new ({_sf_new}) != screened_records_total ({_sf_total})")
    if _sf_adv + _sf_park + _sf_excl != _sf_total:
        raise ValueError(f"CEG screening_funnel mismatch: advanced ({_sf_adv}) + parked ({_sf_park}) + excluded ({_sf_excl}) != screened_records_total ({_sf_total})")
    if _sf_w1 != len(studies) or _sf_w1 + _sf_rem != _sf_adv:
        raise ValueError(f"CEG screening_funnel mismatch: wave1 ({_sf_w1}) + remaining ({_sf_rem}) != candidates_advanced_total ({_sf_adv})")

    # Foreign-key integrity
    for qid, s in studies.items():
        for vid in s.get("variable_arm_ids") or []:
            if vid not in arms:
                raise ValueError(f"Study {qid} references missing arm {vid}")
    for vid, v in arms.items():
        if v.get("queue_id") not in studies:
            raise ValueError(f"Arm {vid} references missing study {v.get('queue_id')}")
    for oid, o in outcomes.items():
        if o.get("manuscript_tier") not in CANONICAL_8_FIDELITY_TIERS:
            raise ValueError(f"Outcome {oid} has non-canonical manuscript_tier={o.get('manuscript_tier')!r}")
        if o.get("queue_id") not in studies:
            raise ValueError(f"Outcome {oid} references missing study {o.get('queue_id')}")
        if "verbatim_quote" in o and o["verbatim_quote"] is not None:
            raise ValueError(f"Outcome {oid} retains a raw verbatim_quote in public CEG")
        if o.get("quote_sha256") is not None and not re.fullmatch(r"[0-9a-f]{64}", str(o["quote_sha256"])):
            raise ValueError(f"Outcome {oid} has malformed quote_sha256")
        _o_sp = o.get("source_pin")
        if not isinstance(_o_sp, dict) or not isinstance(_o_sp.get("source_type"), str) or not _o_sp["source_type"].strip():
            raise ValueError(f"Outcome {oid} source_pin must be a dict with non-empty source_type, got {_o_sp!r}")
        _m_ep_stat = re.search(r"\[Structured endpoint [^\]]*\bstat=([^,|\s\]]+)", str(o.get("endpoint_name") or ""))
        if _m_ep_stat and _m_ep_stat.group(1) != o.get("stat_type"):
            raise ValueError(f"Outcome {oid} endpoint_name structured stat={_m_ep_stat.group(1)!r} disagrees with stat_type={o.get('stat_type')!r}")
        _m_qs_ds = re.search(r"\[Structured outcome [^\]]*\bdirection=([^,|\s\]]+)\s*(?:\||,)\s*stat=([^,|\s\]]+)", str(o.get("quantitative_summary") or ""))
        if _m_qs_ds and (_m_qs_ds.group(1) != o.get("direction") or _m_qs_ds.group(2) != o.get("stat_type")):
            raise ValueError(
                f"Outcome {oid} quantitative_summary structured (direction, stat)=({_m_qs_ds.group(1)!r}, {_m_qs_ds.group(2)!r}) "
                f"disagrees with ({o.get('direction')!r}, {o.get('stat_type')!r})"
            )
        if studies[o["queue_id"]].get("record_class") == "empirical_primary_study":
            _o_narr = f"{o.get('endpoint_name', '')} {o.get('quantitative_summary', '')}"
            if re.search(
                r"(?i)(\btitle[- ]only\b|\btitle\s+claim\b|\bqualitative\s+title\s+statement\s+only\b"
                r"|\bfrom\s+title\b|\bstated\s+only\s+in\s+the\s+title\b|\bread\s+from\s+the\s+title\s+alone\b"
                r"|\bthe\s+title\s+reports\b.*\bno\s+.*data\s+are\s+stated\b|\babstract\s+text\s+itself\s+does\s+not\s+report\b)",
                _o_narr,
            ) and _o_sp["source_type"] not in ("title_or_citation_metadata_only", "title"):
                raise ValueError(
                    f"Outcome {oid} narrative states title-only / unmeasured content while source_pin.source_type={_o_sp['source_type']!r}"
                )
            _o_sim_blob = f"{_o_narr} {o.get('comparison_arms', '')} {o.get('intervention_value', '')}"