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…

    _w6_ft_manifest = json.loads('{"1334978": {"bytes": 16015, "file": "1334978_PMC443416.txt", "pmcid": "PMC443416", "sha256": "b9eed2d034211a4c90b2686395c47650622d9a4ee7fd889c791bf5468604c5e0"}, "17503968": {"bytes": 64680, "file": "17503968_PMC1868042.txt", "pmcid": "PMC1868042", "sha256": "3186879e13088ca92f42f6b46651e40071497e68154426ed5762a4dd1ee3b1df"}, "21912932": {"bytes": 56711, "file": "21912932_PMC3233362.txt", "pmcid": "PMC3233362", "sha256": "c6f7647a6adfb234e70f0a5410e28cb76421c7ff8333b432eb82504f005d13d8"}, "22315720": {"bytes": 65555, "file": "22315720_PMC3253030.txt", "pmcid": "PMC3253030", "sha256": "f7ee7e756a56d61255dfaf05a2b8f1f990a1a539fb802a269fafee069105cfba"}, "23572523": {"bytes": 34167, "file": "23572523_PMC3663534.txt", "pmcid": "PMC3663534", "sha256": "01053773b98f586a98125c64446672ebe674f9672fa20d3fe63b7f06e998b314"}, "23616575": {"bytes": 68965, "file": "23616575_PMC3825029.txt", "pmcid": "PMC3825029", "sha256": "aa426f775dbb545be9600e91ff775750d9c0284af6248e8efa76f0a51b5a2464"}, "23935835": {"bytes": 52681, "file": "23935835_PMC3723782.txt", "pmcid": "PMC3723782", "sha256": "d23d87a9d06a5de3cdd87754004ba3e9d55538fe800eaae8c6a1d353723b868c"}, "30449685": {"bytes": 57104, "file": "30449685_PMC6402969.txt", "pmcid": "PMC6402969", "sha256": "ce10d19c52c41261a15e4b5411e08a8e563e6568ff3e21524353692e3a8c1275"}, "33722583": {"bytes": 64619, "file": "33722583_PMC9053078.txt", "pmcid": "PMC9053078", "sha256": "86f42f50b88fddad6821a7954d53f5b63c357d11edbffca8f5c25fe257b199d0"}, "35046043": {"bytes": 54886, "file": "35046043_PMC8794823.txt", "pmcid": "PMC8794823", "sha256": "cc1081e39699363fc1fc3e883d8014fef1a76049ecbe0749330f15a58c863d66"}, "35725270": {"bytes": 72212, "file": "35725270_PMC9339508.txt", "pmcid": "PMC9339508", "sha256": "5e14aa6d81927a8ae97e95bd8511e7ed71762029f6f624f01abcc4ffe86e2a50"}, "36560629": {"bytes": 41388, "file": "36560629_PMC9781616.txt", "pmcid": "PMC9781616", "sha256": "52405e9107b0c6fdfffa8cd353b44e3664356d0d6221ac6ed07fc175d1f1daad"}, "37106062": {"bytes": 81619, "file": "37106062_PMC10859913.txt", "pmcid": "PMC10859913", "sha256": "0bdcda899e8b873e202f160d1658f5481f312ed24d44eb1fc195587a0a7a1166"}, "37306457": {"bytes": 66031, "file": "37306457_PMC10524879.txt", "pmcid": "PMC10524879", "sha256": "cf76d84c2ad8be413787d72b20c6aabdf5d846f062fbcee4d3286930afee67e6"}, "38135691": {"bytes": 91814, "file": "38135691_PMC10746718.txt", "pmcid": "PMC10746718", "sha256": "3888a971deb907bca7c18f4c2ccea82e6c3d27d9a11f7faa602a8adcf8b3f424"}, "38848367": {"bytes": 110749, "file": "38848367_PMC11160476.txt", "pmcid": "PMC11160476", "sha256": "4f7371f41fb8741075f6c39e6102abd5522f0be97fa07e66e24a00308a060921"}, "40066448": {"bytes": 96482, "file": "40066448_PMC11891242.txt", "pmcid": "PMC11891242", "sha256": "ce528e80ffc29dc0b27936886585e665417a6b3b63b8bdb47c384147a907bc09"}, "41118637": {"bytes": 48291, "file": "41118637_PMC12707259.txt", "pmcid": "PMC12707259", "sha256": "bdd7e41602c53487715cfe582634c5fafccc582673bfea3c16aa94e774b6ba28"}}')
    _w6_auth_cert_bindings = json.loads('{"PMID:30449685:L1": {"applicability": "justified_bridge", "cited_outcome_digests": {"PMID:30449685:O1": {"end": 755, "pmid": "30449685", "quote_sha256": "ae73f2fa8f8cb374733c43b6c3d7ff8130ca171a8e28cb869356f330fa2c8960", "source_body_sha256": "0bee067ccb8763e0bd145e878dde03183a95df52642dc016b33135610dedd34d", "source_type": "abstract", "span": "abstract[118:755]|norm=exact", "start": 118}}, "cited_outcome_ids": ["O1"], "cited_outcome_tuples": ["PMID:30449685:O1"], "edge_id": "PMID:30449685:L1", "evidence_scope_class": "direct_human_islet_biomarker", "pmid": "30449685", "queue_id": "PMID:30449685", "relation": "supports", "target_gate_or_module": "Gate 1 / M2 W6-C4 ENTPD3 mature beta-cell surface QC assay retaining ITGA1 + GP2 sorting (IIP-0058)", "target_gate_or_module_materialized": "Gate 1 / M2 W6-C4 ENTPD3 mature beta-cell surface QC assay retaining ITGA1 + GP2 sorting"}}')
    _w6_auth_cert_edges = frozenset(_w6_auth_cert_bindings.keys())
    _w6_valid_scope_classes = frozenset(json.loads('["contextual_epidemiology", "direct_clinical_comparator", "direct_human_islet_biomarker", "direct_human_islet_safety_guard", "direct_nhp_islet_benchmark", "discovery_context", "mechanistic_analog"]'))
    _w6_active_phase = 'STAGED_PRE_FOLDIN'
    _w6_exp_study_status = 'STAGED_TYPED_DELTA_PENDING_FULL_GRAPH_REBUILD'
    _w6_exp_approved_edges = []
    _w6_pinned_approval_receipts = json.loads('{"W6-DEC124-APPROVAL-STAGED-PRE-FOLDIN-MAT-V1": {"approval_authority_id": "OPENISLET_DEC124_RELEASE_GOVERNANCE_V1", "approval_receipt_id": "W6-DEC124-APPROVAL-STAGED-PRE-FOLDIN-MAT-V1", "approved_cert_eligible_edge_ids": [], "approved_certification_phase": "STAGED_PRE_FOLDIN", "approved_wave6_graph_digest": "693f33c2342b555d8b10b06117c30dcd581182855ea3ba373ddb9cee84866a0d", "expected_study_certification_status": "STAGED_TYPED_DELTA_PENDING_FULL_GRAPH_REBUILD", "graph_representation": "materialized", "publication_certification_granted": false, "receipt_sha256": "fb9206912ddc219a0f7fe8ad98889510c9c6482070d7b716db448201a356f610", "schema_version": "wave6_certification_approval_receipt_v1"}, "W6-DEC124-APPROVAL-STAGED-PRE-FOLDIN-RAW-V1": {"approval_authority_id": "OPENISLET_DEC124_RELEASE_GOVERNANCE_V1", "approval_receipt_id": "W6-DEC124-APPROVAL-STAGED-PRE-FOLDIN-RAW-V1", "approved_cert_eligible_edge_ids": [], "approved_certification_phase": "STAGED_PRE_FOLDIN", "approved_wave6_graph_digest": "76ce65551d935b306908746fdf1182b9dc09c630e60e09afe80eb25fa2103b1e", "expected_study_certification_status": "STAGED_TYPED_DELTA_PENDING_FULL_GRAPH_REBUILD", "graph_representation": "raw", "publication_certification_granted": false, "receipt_sha256": "928817167f0974b41e99dcd541a5ea9e168aaa6e9f715ce597fb97bf1043a130", "schema_version": "wave6_certification_approval_receipt_v1"}}')
    _w6_approval_schema = 'wave6_certification_approval_receipt_v1'
    _w6_approval_authority_id = 'OPENISLET_DEC124_RELEASE_GOVERNANCE_V1'

    # Audit R8-01: Verify phase-specific governed publication certification approval receipt identity,
    # authority, phase binding, approved edge allowlist, and pinned receipt digest BEFORE accepting
    # any Wave-6 study phase or certification authority (BOTH structural and source-backed modes)!
    _w6_approval_rec = ceg.get("wave6_certification_approval_receipt")
    if not isinstance(_w6_approval_rec, dict):
        raise ValueError("WAVE6_CERTIFICATION_APPROVAL_MISMATCH: missing required wave6_certification_approval_receipt")
    _w6_rec_id = _w6_approval_rec.get("approval_receipt_id")
    if not isinstance(_w6_rec_id, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{5,95}", _w6_rec_id):
        raise ValueError(f"WAVE6_CERTIFICATION_APPROVAL_MISMATCH: invalid approval_receipt_id={_w6_rec_id!r}")
    if _w6_approval_rec.get("schema_version") != _w6_approval_schema:
        raise ValueError(f"WAVE6_CERTIFICATION_APPROVAL_MISMATCH: unexpected schema_version={_w6_approval_rec.get('schema_version')!r}")
    if _w6_approval_rec.get("approval_authority_id") != _w6_approval_authority_id:
        raise ValueError(f"WAVE6_CERTIFICATION_APPROVAL_MISMATCH: untrusted approval_authority_id={_w6_approval_rec.get('approval_authority_id')!r}")
    if _w6_approval_rec.get("approved_certification_phase") != _w6_active_phase:
        raise ValueError(
            f"WAVE6_CERTIFICATION_APPROVAL_MISMATCH: receipt phase={_w6_approval_rec.get('approved_certification_phase')!r} "
            f"mismatches active governed phase={_w6_active_phase!r}"
        )
    if _w6_approval_rec.get("expected_study_certification_status") != _w6_exp_study_status:
        raise ValueError(
            f"WAVE6_CERTIFICATION_APPROVAL_MISMATCH: expected_study_certification_status={_w6_approval_rec.get('expected_study_certification_status')!r} "
            f"mismatches phase status={_w6_exp_study_status!r}"
        )
    if _w6_approval_rec.get("approved_cert_eligible_edge_ids") != _w6_exp_approved_edges:
        raise ValueError(
            f"WAVE6_CERTIFICATION_APPROVAL_MISMATCH: approved_cert_eligible_edge_ids={_w6_approval_rec.get('approved_cert_eligible_edge_ids')!r} "
            f"mismatches phase allowlist={_w6_exp_approved_edges!r}"
        )
    _w6_exp_pub_granted = (_w6_active_phase == "GOVERNED_FOLDED_IN_RELEASE")
    if _w6_approval_rec.get("publication_certification_granted") is not _w6_exp_pub_granted:
        raise ValueError(
            f"WAVE6_CERTIFICATION_APPROVAL_MISMATCH: publication_certification_granted={_w6_approval_rec.get('publication_certification_granted')!r} "
            f"mismatches active phase={_w6_active_phase!r}"
        )
    _w6_rec_body = {k: v for k, v in _w6_approval_rec.items() if k != "receipt_sha256"}
    _w6_rec_recomp = _sha256_str(json.dumps(_w6_rec_body, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
    if _w6_approval_rec.get("receipt_sha256") != _w6_rec_recomp:
        raise ValueError("WAVE6_CERTIFICATION_APPROVAL_MISMATCH: approval receipt receipt_sha256 self-digest mismatch")
    _w6_rec_pinned = _w6_pinned_approval_receipts.get(_w6_rec_id)
    if not isinstance(_w6_rec_pinned, dict) or _w6_approval_rec != _w6_rec_pinned:
        raise ValueError(f"WAVE6_CERTIFICATION_APPROVAL_MISMATCH: approval receipt {_w6_rec_id!r} is unpinned or tampered for phase={_w6_active_phase!r}")

    for _w6q, _w6pm in sorted(_w6_expected_qid_to_pmid.items()):
        _w6st = studies.get(_w6q)
        if not isinstance(_w6st, dict):
            raise ValueError(f"Missing required Wave-6 study {_w6q}")
        if _study_pmid(_w6st) != _w6pm:
            raise ValueError(f"Wave-6 study {_w6q} PMID mismatch ({_study_pmid(_w6st)!r} != {_w6pm!r})")
        if _w6st.get("dec124_certification_status") != _w6_exp_study_status:
            raise ValueError(
                f"WAVE6_CERTIFICATION_APPROVAL_MISMATCH: Wave-6 study {_w6q} dec124_certification_status={_w6st.get('dec124_certification_status')!r} "
                f"mismatches active governed phase status={_w6_exp_study_status!r}"
            )

    _w6_cert_true_found: set[str] = set()
    for _we in edges:
        _wq_e = _we.get("queue_id")
        _we_scope = _we.get("evidence_scope_class")
        if _wq_e not in _w6_expected_qid_to_pmid:
            if _we_scope is not None and (not isinstance(_we_scope, str) or _we_scope not in _w6_valid_scope_classes):
                raise ValueError(f"Edge {_we.get('edge_id')} evidence_scope_class={_we_scope!r} violates closed VALID_EVIDENCE_SCOPE_CLASSES enum")
            continue
        _weid = str(_we.get("edge_id") or "")
        if not isinstance(_we_scope, str) or _we_scope not in _w6_valid_scope_classes:
            raise ValueError(f"Wave-6 edge {_weid} evidence_scope_class={_we_scope!r} violates closed VALID_EVIDENCE_SCOPE_CLASSES enum {sorted(_w6_valid_scope_classes)}")
        if _we.get("primary_certification_eligible") is True:
            _w6_cert_true_found.add(_weid)
            if _weid not in _w6_auth_cert_bindings:
                raise ValueError(f"Unauthorized Wave-6 cert-eligible edge {_weid} rejected (authorized={sorted(_w6_auth_cert_edges)})")
            if _we.get("applicability") == "unvalidated_transfer":
                raise ValueError(f"Wave-6 unvalidated_transfer edge {_weid} cannot be primary_certification_eligible=True")
            _wbind = _w6_auth_cert_bindings[_weid]
            if _wq_e != _wbind["queue_id"] or _study_pmid(studies[_wq_e]) != _wbind["pmid"]:
                raise ValueError(f"Authorized Wave-6 edge {_weid} study binding mismatch ({_wq_e!r})")
            if _we.get("target_gate_or_module") != _wbind["target_gate_or_module_materialized"]:
                raise ValueError(f"Authorized Wave-6 edge {_weid} target_gate_or_module={_we.get('target_gate_or_module')!r} mismatches pinned materialized binding")
            if _we.get("relation") != _wbind["relation"]:
                raise ValueError(f"Authorized Wave-6 edge {_weid} relation={_we.get('relation')!r} mismatches pinned {_wbind['relation']!r}")
            if _we.get("applicability") != _wbind["applicability"]:
                raise ValueError(f"Authorized Wave-6 edge {_weid} applicability={_we.get('applicability')!r} mismatches pinned {_wbind['applicability']!r}")
            if _we_scope != _wbind["evidence_scope_class"]:
                raise ValueError(f"Authorized Wave-6 edge {_weid} evidence_scope_class={_we_scope!r} mismatches pinned {_wbind['evidence_scope_class']!r}")
            if tuple(_we.get("cited_outcome_ids") or ()) != tuple(_wbind["cited_outcome_ids"]):
                raise ValueError(f"Authorized Wave-6 edge {_weid} cited_outcome_ids={_we.get('cited_outcome_ids')!r} mismatches pinned {_wbind['cited_outcome_ids']!r} (outcome reassignment rejected)")
            if tuple(_we.get("cited_outcome_tuples") or ()) != tuple(_wbind["cited_outcome_tuples"]):
                raise ValueError(f"Authorized Wave-6 edge {_weid} cited_outcome_tuples={_we.get('cited_outcome_tuples')!r} mismatches pinned {_wbind['cited_outcome_tuples']!r} (outcome reassignment rejected)")
            for _boid, _bdig in _wbind["cited_outcome_digests"].items():
                _boc = outcomes.get(_boid)
                if not isinstance(_boc, dict):
                    raise ValueError(f"Authorized Wave-6 edge {_weid} missing bound outcome {_boid}")
                _bsp = _boc.get("source_pin") or {}
                if _boc.get("quote_sha256") != _bdig["quote_sha256"]:
                    raise ValueError(f"Authorized Wave-6 edge {_weid} bound outcome {_boid} quote_sha256 mismatches pinned immutable digest")
                if (
                    _bsp.get("source_type") != _bdig["source_type"]
                    or str(_bsp.get("pmid") or "").strip() != _bdig["pmid"]
                    or _bsp.get("span") != _bdig["span"]
                    or _bsp.get("start") != _bdig["start"]
                    or _bsp.get("end") != _bdig["end"]
                    or _bsp.get("source_body_sha256") != _bdig["source_body_sha256"]
                ):
                    raise ValueError(f"Authorized Wave-6 edge {_weid} bound outcome {_boid} source_pin mismatches pinned coordinates/digest")
        _wesp = _we.get("source_pin")
        if not isinstance(_wesp, dict) or _wesp.get("source_type") != "outcome_span_backed_edge":
            raise ValueError(f"Wave-6 edge {_weid} missing outcome_span_backed_edge source_pin")
        if str(_wesp.get("pmid") or "").strip() != _w6_expected_qid_to_pmid[_wq_e]:
            raise ValueError(f"Wave-6 edge {_weid} source_pin.pmid={_wesp.get('pmid')!r} mismatches {_w6_expected_qid_to_pmid[_wq_e]!r}")
        if _wesp.get("pmcid") != studies[_wq_e].get("pmcid"):
            raise ValueError(f"Wave-6 edge {_weid} source_pin.pmcid={_wesp.get('pmcid')!r} mismatches study pmcid")
        _wcited = list(_we.get("cited_outcome_tuples") or [])
        if _wesp.get("pinned_outcome_spans") != [outcomes[t]["source_pin"] for t in _wcited]:
            raise ValueError(f"Wave-6 edge {_weid} pinned_outcome_spans disagrees with cited outcomes' source_pins")
    if _w6_cert_true_found != set(_w6_auth_cert_edges):
        raise ValueError(f"Wave-6 cert-eligible edge roster {sorted(_w6_cert_true_found)} mismatches authorized {sorted(_w6_auth_cert_edges)}")

    _w6_src_dir = repo_root / "data" / "wave6_sources"
    _w6_abs_live: dict[str, str] = {}
    _w6_ft_live: dict[str, str] = {}
    _w6_sources_loaded = False
    if require_sources or _w6_src_dir.is_dir():
        _w6_ef_path = _w6_src_dir / "efetch_60.json"
        if not _w6_ef_path.is_file():
            raise ValueError(f"Wave-6 source-backed verification requires {_w6_ef_path}")
        _w6_ef_raw = _w6_ef_path.read_bytes()
        _w6_ef_sha = hashlib.sha256(_w6_ef_raw).hexdigest()
        if len(_w6_ef_raw) != 115379 or _w6_ef_sha != '122c289cd545fbb92347e3fe6b99c587eb6ad7d25da4de876c021f319afe3a5a':
            raise ValueError(f"Wave-6 efetch_60.json digest/size mismatch (bytes={len(_w6_ef_raw)}, sha256={_w6_ef_sha})")
        for _w6_rec in json.loads(_w6_ef_raw.decode("utf-8")):
            _w6_abs_live[str(_w6_rec["pmid"])] = str(_w6_rec.get("abstract") or "")
        for _w6_pm_k, _w6_fmeta in sorted(_w6_ft_manifest.items()):
            _w6_fp = _w6_src_dir / _w6_fmeta["file"]
            if not _w6_fp.is_file():
                raise ValueError(f"Wave-6 source-backed verification missing PMC full-text body {_w6_fp}")
            _w6_fbytes = _w6_fp.read_bytes()
            _w6_fsha = hashlib.sha256(_w6_fbytes).hexdigest()
            if len(_w6_fbytes) != _w6_fmeta["bytes"] or _w6_fsha != _w6_fmeta["sha256"]:
                raise ValueError(f"Wave-6 PMC full-text body {_w6_fmeta['file']} digest/size mismatch")
            _w6_ft_live[_w6_pm_k] = _w6_fbytes.decode("utf-8")
        _w6_sources_loaded = True

    def _check_w6_pin(_oid_w: str, _pin_w: dict[str, Any], _sha_w: Any, _spec_w: dict[str, Any], _lbl_w: str) -> None:
        if not isinstance(_pin_w, dict):
            raise ValueError(f"Wave-6 outcome {_oid_w} {_lbl_w} must be dict")
        if str(_pin_w.get("pmid") or "").strip() != _spec_w["pmid"]:
            raise ValueError(f"Wave-6 outcome {_oid_w} {_lbl_w} pmid={_pin_w.get('pmid')!r} mismatches {_spec_w['pmid']!r}")
        if _pin_w.get("source_type") != _spec_w["source_type"]:
            raise ValueError(f"Wave-6 outcome {_oid_w} {_lbl_w} source_type={_pin_w.get('source_type')!r} mismatches {_spec_w['source_type']!r}")
        if _pin_w.get("span") != _spec_w["span"]:
            raise ValueError(f"Wave-6 outcome {_oid_w} {_lbl_w} span={_pin_w.get('span')!r} mismatches pinned {_spec_w['span']!r}")
        if _pin_w.get("start") != _spec_w["start"] or _pin_w.get("end") != _spec_w["end"]:
            raise ValueError(f"Wave-6 outcome {_oid_w} {_lbl_w} start/end mismatch pinned coordinates")
        if not isinstance(_sha_w, str) or not re.fullmatch(r"[0-9a-f]{64}", _sha_w) or _sha_w == ("0" * 64):
            raise ValueError(f"Wave-6 outcome {_oid_w} {_lbl_w} invalid/zero quote_sha256")
        # Enforce immutable pinned quote_sha256 in BOTH structural and source-backed modes (Audit R5-01)!
        if _sha_w != _spec_w["quote_sha256"]:
            raise ValueError(f"Wave-6 outcome {_oid_w} {_lbl_w} quote_sha256={_sha_w} mismatches pinned immutable digest {_spec_w['quote_sha256']}")