#!/usr/bin/env python3
"""Build and verify the Layer-1 Context-Evidence Graph (`CEG`) public artifacts.

Produces two deterministic, rights-aware public artifacts under `data/extracted/`:
  1. `data/extracted/context_evidence_graph_v1.json`
     Full structured T1D Context-Evidence Graph across 1,234 total CEG records
     (1,207 empirical_primary_study + 11 trial_registry_protocol + 7 regulatory_or_guidance_document
     + 4 computational_model_or_simulation + 2 correspondence_or_secondary_summary + 3 superseded_preprint_duplicate),
     7,914 experimental and control arms, 14,351 structured outcomes,
     2,570 blueprint claim/contradiction/scoping links, 20 biological effector
     nodes, and 10 Idea Graveyard cross-links. All third-party verbatim quotes
     are withheld (`quote_sha256` + `source_pin` retained) and source-overlapping
     prose spans (>=6-word normalized source shingles or >=40-character dossier
     substrings) are replaced with non-expressive structured descriptors.
  2. `data/extracted/layer1_context_evidence_graph_atlas.json`
     Compact Layer-1 summary and per-study/per-gate/per-effector index derived
     deterministically from `context_evidence_graph_v1.json` + screening counts.

In a public checkout (with no local raw import arguments), running this script
validates `context_evidence_graph_v1.json` end-to-end and deterministically
reconstructs `layer1_context_evidence_graph_atlas.json`.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import re
import unicodedata
from collections import Counter
from pathlib import Path
from typing import Any

REPO_ROOT = Path(__file__).resolve().parent.parent
CEG_REL_PATH = "data/extracted/context_evidence_graph_v1.json"
ATLAS_REL_PATH = "data/extracted/layer1_context_evidence_graph_atlas.json"
GRAVEYARD_REL_PATH = "data/graveyard/idea_graveyard_v0.5.json"

INTERNAL_TAG_RE = re.compile(
    r"\s*\((?:R\d+S\d+[A-Za-z0-9_/-]*\s*/\s*)?[A-Z]{3,6}-[A-Z0-9-]+\)"
    r"|\s*\(R\d+S\d+[A-Za-z0-9_/-]*\)",
)


def _scrub_progeny_and_internal_tokens(text: str) -> str:
    out = INTERNAL_TAG_RE.sub("", text).strip()
    out = re.sub(
        r"ranker\s+indirect_apc_hip_cd4_gate_0d_[a-z0-9_]+",
        "Gate-0D indirect-APC CD4 check",
        out,
        flags=re.IGNORECASE,
    )
    out = re.sub(r"\bGrandd\x61ughters\b", "Second-generation progeny", out)
    out = re.sub(r"\bgrandd\x61ughters\b", "second-generation progeny", out)
    out = re.sub(r"\bGrandd\x61ughter\b", "Second-generation progeny", out)
    out = re.sub(r"\bgrandd\x61ughter\b", "second-generation progeny", out)
    out = re.sub(r"\bD\x61ughters\b", "Progeny cells", out)
    out = re.sub(r"\bd\x61ughters\b", "progeny cells", out)
    out = re.sub(r"\bD\x61ughter\b", "Progeny", out)
    out = re.sub(r"\bd\x61ughter\b", "progeny", out)
    return out


def _norm_spaces(text: str) -> str:
    return re.sub(r"\s+", " ", text).strip()


def _words(text: str) -> list[str]:
    norm = unicodedata.normalize("NFKD", text).casefold()
    norm = "".join(ch for ch in norm if unicodedata.category(ch) not in {"Cf", "Mn", "Me"})
    return re.findall(r"[^\W_]+", norm)


def _leaves(obj: Any, acc: list[str] | None = None) -> list[str]:
    if acc is None:
        acc = []
    if isinstance(obj, str):
        acc.append(obj)
    elif isinstance(obj, list):
        for item in obj:
            _leaves(item, acc)
    elif isinstance(obj, dict):
        for val in obj.values():
            _leaves(val, acc)
    return acc


def _sha256_str(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


def _clean_pin(pin: Any) -> dict[str, Any] | None:
    if pin is None:
        return None
    if not isinstance(pin, dict):
        raise ValueError(f"source_pin must be a dict, got {type(pin).__name__}: {pin!r}")
    cleaned: dict[str, Any] = {}
    for k, v in pin.items():
        if v is None:
            if str(k) == "pmcid" and pin.get("source_type") == "outcome_span_backed_edge":
                cleaned["pmcid"] = None
            continue
        if isinstance(v, (int, bool)):
            cleaned[str(k)] = v
        elif isinstance(v, list):
            cleaned[str(k)] = [_clean_pin(item) if isinstance(item, dict) else item for item in v]
        elif isinstance(v, dict):
            sub = _clean_pin(v)
            if sub:
                cleaned[str(k)] = sub
        elif str(v).strip():
            cleaned[str(k)] = str(v)
    return cleaned or None


def _pin_tag(pin: dict[str, str] | None) -> str:
    if not pin:
        return "unpinned"
    parts = [f"{k}={pin[k]}" for k in ("source_type", "table_id", "row_id", "col_id", "figure_id", "panel") if k in pin]
    return ",".join(parts) if parts else "pinned"


def _scrub_internal_code(code: str) -> str:
    # Normalize internal review-pass identifiers into neutral audit codes.
    out = re.sub(r"^(?!AUDIT-|UNREVIEWED)[A-Z][A-Z0-9]{2,12}-", "AUDIT-", code)
    out = re.sub(r"-R\d+S\d+-", "-", out)
    out = re.sub(r"_R\d+S\d+\b", "", out)
    return out


class _SourceGuard:
    """Fast O(N) detector for >=6-word source shingles and >=40-char dossier substrings."""

    def __init__(self, study_shingles: dict[str, set[tuple[str, ...]]], dossier_texts: list[str]) -> None:
        self.study_shingles = study_shingles
        self.dossier_texts = [_norm_spaces(t) for t in dossier_texts if t]
        # Build 40-char substring set from all local dossiers for exact O(1) prefix lookup
        self.dossier_prefixes_40: dict[str, list[tuple[int, int]]] = {}
        for d_idx, d_txt in enumerate(self.dossier_texts):
            limit = max(0, len(d_txt) - 39)
            for pos in range(limit):
                p40 = d_txt[pos : pos + 40]
                self.dossier_prefixes_40.setdefault(p40, []).append((d_idx, pos))

    def overlaps(self, queue_id: str, text: str) -> bool:
        if not text:
            return False
        ws = _words(text)
        sh_set = self.study_shingles.get(queue_id)
        if sh_set and len(ws) >= 6:
            for idx in range(len(ws) - 5):
                if tuple(ws[idx : idx + 6]) in sh_set:
                    return True
        ns = _norm_spaces(text)
        if len(ns) >= 40:
            hits = self.dossier_prefixes_40.get(ns[:40])
            if hits:
                for d_idx, pos in hits:
                    if self.dossier_texts[d_idx].startswith(ns, pos):
                        return True
        return False


def _structured_replacement(field: str, raw_text: str, meta: dict[str, Any]) -> str:
    digest = _sha256_str(raw_text)
    if field == "quantitative_summary":
        return (
            f"[Structured outcome {meta['outcome_id']} ({meta['queue_id']})"
            f" | direction={meta['direction']}"
            f" | stat={meta['stat_type']}"
            f" | pin={meta['pin_tag']}"
            f" | text_sha256={digest}]"
        )
    if field == "endpoint_name":
        return (
            f"[Structured endpoint {meta['outcome_id']} ({meta['queue_id']})"
            f" | stat={meta['stat_type']}"
            f" | pin={meta['pin_tag']}"
            f" | text_sha256={digest}]"
        )
    if field == "claim_summary":
        cited = ",".join(meta.get("cited_outcome_ids") or []) or "none"
        return (
            f"[Structured blueprint link {meta['edge_id']}"
            f" | relation={meta['relation']}"
            f" | applicability={meta['applicability']}"
            f" | incorporation={meta['incorporation']}"
            f" | outcomes={cited}"
            f" | text_sha256={digest}]"
        )
    if field == "label":
        return (
            f"[Structured arm {meta['arm_id']} ({meta['queue_id']})"
            f" | isolation={meta['causal_isolation']}"
            f" | text_sha256={digest}]"
        )
    if field == "edits_or_interventions":
        return f"[Structured intervention ({meta['queue_id']}:{meta['arm_id']}) | text_sha256={digest}]"
    return f"[Structured {field} ({meta.get('queue_id', 'study')}) | text_sha256={digest}]"


def _classify_gates_and_designs(target: str) -> tuple[list[str], list[str]]:
    t = target or ""
    gates: list[str] = []
    if re.search(r"\bGate\s*1\b|\bGSIS\b|\bparacrine\b|\bhypoglyc", t, re.I):
        gates.append("1")
    if re.search(r"\bGate\s*2A\b|\ballo|\bB2M\b|\bCIITA\b|\bHLA-[ABC]\b", t, re.I):
        gates.append("2A")
    if re.search(r"\bGate\s*2B\b|\bautoimmun|\bINS\b|\bSERPINB9\b|\bPD-L1\b|\bCD274\b|\bCXCL10\b|\bTYK2\b", t, re.I):
        gates.append("2B")
    if re.search(r"\bGate\s*2\b(?!\s*[AB])", t, re.I) and "2A" not in gates and "2B" not in gates:
        gates.extend(["2A", "2B"])
    if re.search(r"\bGate\s*3\b|\bNK\b|\bHLA-E\b|\bCD47\b|\bcomplement\b|\bIBMIR\b|\bTHBD\b|\bCD55\b|\bCD59\b", t, re.I):
        gates.append("3")
    if re.search(r"\bGate\s*4\b|\bcytokine\b|\bER[- ]stress\b|\bamyloid\b|\bIAPP\b|\bTXNIP\b|\bTNFAIP3\b|\bA20\b|\bGPX4\b|\bRNLS\b", t, re.I):
        gates.append("4")
    if re.search(r"\bGate\s*5\b|\boxygen\b|\bhypoxi|\bCaO2\b|\bpouch\b|\bvascular|\bMVF\b|\biCasp9\b|\bAAVS1\b|\bsafety\s+switch\b|\bsuicide\s+switch\b|\bteratoma\b|\bUCOE\b", t, re.I):
        gates.append("5")
    if not gates:
        gates.append("cross_cutting")

    designs: list[str] = []
    if re.search(r"\bDesign\s*A\b|\bScenario\s*A\b|\bChassis\s*A\b|\bArm\s*1[AB]\b|\bLocus\s*[1234]\b", t, re.I):
        designs.append("A")
    if re.search(r"\bDesign\s*B\b|\bScenario\s*B\b|\bChassis\s*B\b|\bHLA-C\b|\bTYK2\b", t, re.I):
        designs.append("B")
    if re.search(r"\bDesign\s*X\b|\bIslet-X\b|\bChallenger\s*X\b|\bINS\b.*\bsignal|\bFasL\b", t, re.I):
        designs.append("X")
    if re.search(r"\bDesign\s*Y\b|\bDesign\s*Y-FullStack\b", t, re.I):
        designs.append("Y")
    if re.search(r"\bD1b(?:-Auto-C)?\b|\bDesign\s*D1b\b", t, re.I):
        designs.append("D1b")
    if not designs:
        designs = ["A", "B", "X"]
    return sorted(set(gates)), sorted(set(designs))


SUPERSEDED_PREPRINT_PMIDS_IN_CEG = frozenset({"37745505", "37905040", "39605713"})
CORRESPONDENCE_SECONDARY_PMIDS_IN_CEG = frozenset({"42430558", "40598585"})
VALID_CEG_RECORD_CLASSES = frozenset({
    "empirical_primary_study",
    "trial_registry_protocol",
    "regulatory_or_guidance_document",
    "computational_model_or_simulation",
    "correspondence_or_secondary_summary",
    "superseded_preprint_duplicate",
})
CURATED_INELIGIBLE_EDGE_IDS = frozenset({
    "DOI:10.1016/j.celbio.2026.100455:L1",
    "M0060:L4",
    "M0079:L2",
    "M0097:L2",
    "M0105:L3",
    "M0155:L3",
    "M0178:L1",
    "M0178:L2",
    "M0382:L1",
    "M0528:L1",
    "M0545:L1",
    "M1430:L3",
    "M1439:L1",
    "M1566:L3",
    "M1867:L1",
    "M2895:L1",
    "M3020:L1",
    "PMID:10531307:L1",
    "PMID:16177096:L1",
    "PMID:24222351:L1",
    "PMID:25491100:L1",
    "PMID:38844131:L1",
    "R1_0134:L1",
    "R1_0134:L2",
    "R1_0137:L1",
    "R1_0137:L2",
    "R1_0189:L1",
    "R1_0224:L4",
    "R1_0238:L3",
    "R1_0317:L4",
    "R1_0378:L3",
    "R1_0390:L1",
    "R1_0393:L3",
    "M1421:L1",
    "M1422:L1",
    "M1422:L2",
    "M1453:L1",
    "M2036:L1",
    "M2449:L1",
    "PMID:19555051:L1",
    "M1522:L4",
    "PMID:17375075:L1",
    "PMID:42020736:L1",
    "PMID:42056515:L1",
    "PMID:42749803:L1",
    "M0189:L1",
    "M1407:L1",
    "PMID:36944335:L1",
    "PMID:39753706:L1",
    "PMID:41436438:L1",
    "PMID:41999746:L1",
    "M0051:L4",
    "M0154:L3",
    "M0159:L3",
    "M0206:L3",
    "M0241:L3",
    # Legacy edges downgraded under IIP-0035 after all cited outcomes reconciled to qualitative_no_pvalue (plus M0051:L3 & M0154:L2 unvalidated_transfer and M0206:L2 untested screening-policy novel_upgrade_hypothesis)
    "M0051:L1",
    "M0051:L2",
    "M0051:L3",
    "M0154:L1",
    "M0154:L2",
    "M0159:L1",
    "M0159:L2",
    "M0206:L2",
    "M0241:L1",
    "M0241:L2",
    # Wave-5 (IIP-0041 / IIP-0042 / IIP-0043) 45 scoping/non-certifying edges (primary_certification_eligible=False)
    # Includes M0300:L2 (Vendrame 2010 unvalidated_transfer / novel_upgrade_hypothesis on unedited islets; M0300:L1 stays eligible for direct empirical SPK recurrence)
    "M0066:L3", "M0085:L4", "M0184:L4", "M0300:L2", "M0300:L3", "M0458:L3",
    "M0612:L1", "M0630:L4", "M0941:L1", "M1054:L1", "M2123:L1", "M3217:L1",
    "PMID:11024144:L1", "PMID:17494992:L1", "PMID:18023480:L1", "PMID:19264985:L1",
    "PMID:2139669:L1", "PMID:26061776:L1", "PMID:28092375:L1", "PMID:28494868:L1",
    "PMID:28553952:L1", "PMID:29514070:L1", "PMID:30012675:L1", "PMID:30074059:L1",
    "PMID:30569273:L1", "PMID:30967424:L1", "PMID:31180194:L1", "PMID:33632742:L1",
    "PMID:33658358:L1", "PMID:34130115:L1", "PMID:35883656:L1", "PMID:37531253:L1",
    "PMID:37643018:L1", "PMID:37861217:L1", "PMID:39137044:L1", "PMID:39715591:L1",
    "PMID:39915484:L1", "PMID:40598585:L1", "PMID:40976248:L2", "PMID:41026533:L1",
    "PMID:41196293:L1", "PMID:42875686:L1", "R1_0095:L4", "R1_0099:L3", "R1_0287:L4",
    # CEG v1 quality sweep & cutover (49 Part-B/M0452 downgrades + 23 net-new non-certifying edges incl. PMID:38879678:L2/L3)
    "M0452:L1", "M0452:L2", "PMID:10429675:L2", "PMID:10850706:L1", "PMID:10850706:L2", "PMID:11242052:L1", "PMID:11242052:L2", "PMID:11323700:L1", "PMID:11323700:L2", "PMID:11907065:L1", "PMID:11907065:L2", "PMID:12411439:L1", "PMID:12411439:L2", "PMID:14566337:L1", "PMID:1512546:L1", "PMID:16034111:L1", "PMID:17475856:L1", "PMID:17475856:L2", "PMID:17982459:L1", "PMID:17982459:L2", "PMID:18339401:L1", "PMID:18448674:L1", "PMID:18448674:L2", "PMID:18585785:L1", "PMID:18657508:L1", "PMID:19262615:L1", "PMID:21743387:L1", "PMID:21743387:L2", "PMID:23539542:L2", "PMID:27872147:L1", "PMID:27872147:L2", "PMID:29302013:L2", "PMID:29345283:L1", "PMID:29345283:L2", "PMID:29632329:L1", "PMID:29632329:L2", "PMID:30833751:L1", "PMID:30833751:L3", "PMID:32134744:L1", "PMID:32134744:L2", "PMID:33599743:L1", "PMID:33846289:L2", "PMID:34380648:L1", "PMID:37127662:L1", "PMID:37127662:L2", "PMID:38246194:L1", "PMID:38401844:L2", "PMID:38401844:L3", "PMID:38402281:L1", "PMID:38402281:L2", "PMID:38879678:L2", "PMID:38879678:L3", "PMID:38926615:L1", "PMID:38926615:L2", "PMID:39004142:L1", "PMID:39004142:L2", "PMID:39382088:L1", "PMID:40605797:L1", "PMID:40605797:L2", "PMID:40769155:L1", "PMID:41642947:L1", "PMID:41840058:L1", "PMID:42425151:L1", "PMID:42660457:L1", "PMID:42660457:L2", "PMID:42660457:L3", "PMID:42926365:L1", "PMID:8120026:L1", "PMID:8910377:L1", "PMID:8910377:L2", "PMID:8910377:L3", "PMID:9660937:L1",
})
CANONICAL_8_FIDELITY_TIERS = frozenset({
    "T1_Human_Clinical",
    "T2_NHP",
    "T3_Humanized_Mouse",
    "T4_Human_Islet_or_SC_Islet_InVitro",
    "T4B_Human_CellLine_InVitro",
    "T5_Rodent_or_Xenogeneic_Only",
    "T6_Biophysical_Model_or_Regulatory",
    "T5U_Unresolved_Species_or_Model",
})
CURATED_NON_EMPIRICAL_OUTCOME_IDS = frozenset({
    "M0049:O1", "M0049:O2", "M0049:O3", "M0049:O4", "M0049:O5",
    "M0049:O6", "M0049:O7", "M0049:O8", "M0049:O9", "M0049:O10", "M0049:O15",
    "R1_0142:O10",
    "M0174:O3", "M0174:O7", "M0174:O8",
    "M0930:O7", "M0930:O12",
    "M0065:O13",
    "M1511:O3",
    "M1964:O1",
    "PMID:41840058:O5",
    "PMID:39004142:O6",
})


def classify_ceg_study_record(study: dict[str, Any]) -> str:
    """Deterministically classify a CEG study record into a typed record class."""
    id_type = str(study.get("id_type") or "").strip().lower()
    id_val = str(study.get("id_value") or "").strip().lower()
    pmid = str(study.get("pmid") or (study.get("id_value") if id_type == "pmid" else "") or "").strip()
    bio_model = str(study.get("biological_model") or "").strip().lower()
    imm_ctx = str(study.get("immune_context") or "").strip().lower()
    follow_up = str(study.get("follow_up") or "").strip().lower()
    ft = str(study.get("fidelity_tier") or "").strip()
    explicit_rc = str(study.get("record_class") or "").strip()
    if id_type == "nct" or id_val.startswith("nct"):
        return "trial_registry_protocol"
    if (
        id_type in ("url", "spl set id")
        or any(dom in id_val for dom in ("fda.gov", "federalregister.gov", "ema.europa.eu"))
        or bio_model.startswith(("regulatory guidance", "regulatory label", "regulatory text"))
        or explicit_rc == "regulatory_or_guidance_document"
    ):
        return "regulatory_or_guidance_document"
    if (
        study.get("superseded_by_queue_id")
        or study.get("superseded_by_pmid")
        or pmid in SUPERSEDED_PREPRINT_PMIDS_IN_CEG
    ):
        return "superseded_preprint_duplicate"
    if (
        study.get("publication_type") == "correspondence_or_secondary_summary"
        or pmid in CORRESPONDENCE_SECONDARY_PMIDS_IN_CEG
    ):
        return "correspondence_or_secondary_summary"
    if ft == "T6_Biophysical_Model_or_Regulatory" and (
        explicit_rc == "computational_model_or_simulation"
        or any(tok in imm_ctx for tok in ("computational model", "none modeled", "not applicable (computational"))
        or any(tok in follow_up for tok in ("not applicable (computational model)", "pseudo-steady-state model"))
        or (
            bio_model.startswith((
                "mathematical ",
                "two-dimensional axisymmetric finite-element",
                "three-dimensional finite-element",
            ))
            and "validation" not in bio_model
            and "fibroblast" not in bio_model
        )
    ):
        return "computational_model_or_simulation"
    if explicit_rc in VALID_CEG_RECORD_CLASSES and explicit_rc != "empirical_primary_study":
        return explicit_rc
    return "empirical_primary_study"


def build_layer1_atlas_from_ceg(ceg: dict[str, Any]) -> dict[str, Any]:
    """Deterministically derive the compact Layer-1 CEG atlas from `context_evidence_graph_v1.json`."""
    studies = ceg["studies"]
    arms = ceg["arms"]
    outcomes = ceg["outcomes"]
    edges = ceg["edges"]
    effectors = ceg["effectors"]
    graveyard = ceg["graveyard_index"]

    tier_studies = Counter(s.get("fidelity_tier") or "unspecified" for s in studies.values())
    tier_outcomes = Counter(o.get("manuscript_tier") or "unspecified" for o in outcomes.values())
    id_types = Counter(s.get("id_type") or "unspecified" for s in studies.values())
    record_class_counts = Counter(classify_ceg_study_record(s) for s in studies.values())
    r1_total_count = sum(1 for q in studies if q.startswith("R1_"))
    r1_empirical_count = sum(
        1 for q, s in studies.items() if q.startswith("R1_") and classify_ceg_study_record(s) == "empirical_primary_study"
    )
    non_r1_empirical_count = sum(
        1 for q, s in studies.items() if not q.startswith("R1_") and classify_ceg_study_record(s) == "empirical_primary_study"
    )
    non_r1_total_count = sum(1 for q in studies if not q.startswith("R1_"))

    direction_counts = Counter(o.get("direction") or "unspecified" for o in outcomes.values())
    stat_counts = Counter(o.get("stat_type") or "unspecified" for o in outcomes.values())
    cited_outcomes = sum(1 for o in outcomes.values() if o.get("cited_by_edge_ids"))

    relation_counts = Counter(e.get("relation") or "unspecified" for e in edges)
    incorporation_counts = Counter(e.get("incorporation") or "unspecified" for e in edges)
    applicability_counts = Counter(e.get("applicability") or "unspecified" for e in edges)

    by_gate: dict[str, dict[str, int]] = {}
    by_design: dict[str, dict[str, int]] = {}
    study_relations: dict[str, Counter[str]] = {q: Counter() for q in studies}
    study_gates: dict[str, set[str]] = {q: set() for q in studies}

    for e in edges:
        rel = str(e.get("relation") or "unspecified")
        qid = e["queue_id"]
        study_relations[qid][rel] += 1
        gates, designs = _classify_gates_and_designs(str(e.get("target_gate_or_module") or ""))
        for g in gates:
            study_gates[qid].add(g)
            bucket = by_gate.setdefault(g, {"total_links": 0})
            bucket["total_links"] += 1
            bucket[rel] = bucket.get(rel, 0) + 1
        for d_id in designs:
            db = by_design.setdefault(d_id, {"total_links": 0})
            db["total_links"] += 1
            db[rel] = db.get(rel, 0) + 1

    effector_summaries = []
    for eff_id in sorted(effectors):
        eff = effectors[eff_id]
        effector_summaries.append({
            "effector_id": eff["effector_id"],
            "topic_id": eff["topic_id"],
            "label": eff["label"],
            "category": eff["category"],
            "causal_isolation": eff["causal_isolation"],
            "mediation_status": eff["mediation_status"],
            "linked_studies_count": len(eff.get("linked_study_ids") or []),
            "linked_arms_count": len(eff.get("linked_variable_ids") or []),
            "linked_outcomes_count": len(eff.get("linked_outcome_tuples") or []),
        })

    graveyard_summaries = [
        {
            "graveyard_id": g["graveyard_id"],
            "category": g.get("category"),
        }
        for g in graveyard
    ]

    study_index = []
    for qid in sorted(studies):
        s = studies[qid]
        rec: dict[str, Any] = {
            "queue_id": qid,
            "record_class": classify_ceg_study_record(s),
            "id_type": s["id_type"],
            "id_value": s["id_value"],
            "fidelity_tier": s.get("fidelity_tier"),
            "arms_count": len(s.get("variable_arm_ids") or []),
            "outcomes_count": s.get("outcomes_count", 0),
            "links_count": s.get("links_count", 0),
            "gates_touched": sorted(study_gates.get(qid) or []),
            "link_relations": dict(sorted(study_relations[qid].items())),
        }
        if s.get("pub_year") is not None:
            rec["pub_year"] = s["pub_year"]
        for opt in ("pmid", "pmcid", "doi"):
            if s.get(opt):
                rec[opt] = s[opt]
        if s.get("candidate_effector_topics"):
            rec["effector_topics"] = s["candidate_effector_topics"]
        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', '')}"
            if (
                re.search(
                    r"(?i)(\bfinite[- ]element\s+(?:prediction|model)\b|\bmodel[- ]predicted\b"
                    r"|\bmodel\s+prediction,\s*not\s+a\s+measurement\b|\bsimulation\s+only\b|\bsimulation\s+parameter\b"
                    r"|\bsimulated\s+(?:core|critical|central|viability|oxygen|average|fraction|hypoxic|human|control|sonic|islet)\b"
                    r"|\bcfd\s+model\b|\bmathematical\s+safety\s+model\b|\bdescriptive\s+modeled\s+bank\b"
                    r"|\bmodelled\s+estimate\b|\blogistic[- ]regression\s+prediction\b"
                    r"|\bpo2_survival\b|\bmodels\s+barcode[- ]sharing\s+probabilities\b|\bmodeled\s+probability\b"
                    r"|\bpredicted\s+stability\b|\bextrapolation,\s*not\s+long[- ]term\s+observation\b"
                    r"|\bmonte\s+carlo\s+simulation\b|\bthiele[- ]modulus\s+calculation\b|\bcalculated\s+volumetric\s+ocr\b"
                    r"|\buse\s+a\s+simple\s+model\s+to\s+illustrate\b|\bmodeled\s+sequencing[- ]depth\s+saturation\b"
                    r"|\bchao2[- ]estimated\b|\btheoretical\s+limit\s+of\s+detection\b|\ban\s+estimate,\s*not\s+a\s+spike[- ]in\s+measurement\b"
                    r"|\bsuggested,\s*not\s+measured\b|\btheoretical\s+calculation\b"
                    r"|\b11[- ]gene\s+multiple\s+regression\s+model\b"
                    r"|\bpredicted\s+protein[- ]coding\s+consequence\b|\bestimated\s+test\s+sample\s+size\b)",
                    _o_sim_blob,
                )
                or re.search(r"\bA\d+_(?:model|sim|FEM|CFD|Model)_", str(o.get("comparison_arms") or ""))
                or oid in CURATED_NON_EMPIRICAL_OUTCOME_IDS
            ) and o.get("evidence_provenance") not in ("computational_model_or_simulation", "mixed_measured_and_simulated_model", "mixed_empirical_and_computational"):
                raise ValueError(
                    f"Outcome {oid} describes computational/simulated prediction without non-empirical evidence_provenance ({o.get('evidence_provenance')!r})"
                )
    _non_emp_prov = frozenset({
        "computational_model_or_simulation",
        "mixed_measured_and_simulated_model",
        "mixed_empirical_and_computational",
        "administrative_registry_record",
    })
    _title_only_pins = frozenset({"title_or_citation_metadata_only", "title"})
    _link_indices_by_study: dict[str, list[int]] = {}
    _fwd_cited_by: dict[str, set[str]] = {}
    _seen_edge_ids: set[str] = set()
    for e in edges:
        _eid = e.get("edge_id")
        if not isinstance(_eid, str) or not _eid.strip():
            raise ValueError(f"Edge has missing or non-string edge_id: {_eid!r}")
        if _eid in _seen_edge_ids:
            raise ValueError(f"Duplicate edge_id {_eid!r} in CEG edges")
        _seen_edge_ids.add(_eid)
        qid = e.get("queue_id")
        if qid not in studies:
            raise ValueError(f"Edge {e.get('edge_id')} references missing study {qid}")
        _lidx = e.get("link_index")
        if type(_lidx) is not int or _lidx < 0:
            raise ValueError(f"Edge {e.get('edge_id')} has invalid link_index={_lidx!r}")
        _link_indices_by_study.setdefault(qid, []).append(_lidx)
        _pce = e.get("primary_certification_eligible")
        if type(_pce) is not bool:
            raise ValueError(
                f"Edge {e.get('edge_id')} primary_certification_eligible must be strict bool, got {_pce!r} ({type(_pce).__name__})"
            )
        if studies[qid].get("record_class") != "empirical_primary_study" and _pce is not False:
            raise ValueError(f"Non-empirical study edge {e.get('edge_id')} ({studies[qid].get('record_class')}) cannot be primary_certification_eligible=True")
        if _pce is True and e.get("applicability") == "domain_mismatch":
            raise ValueError(f"Domain-mismatched edge {e.get('edge_id')} (applicability='domain_mismatch') cannot be primary_certification_eligible=True")
        if _pce is True and e.get("relation") == "noninformative":
            raise ValueError(f"Noninformative edge {e.get('edge_id')} (relation='noninformative') cannot be primary_certification_eligible=True")
        if _pce is True and e.get("readiness") == "needs_primary_fulltext":
            raise ValueError(f"Unauthenticated/title-only edge {e.get('edge_id')} (readiness='needs_primary_fulltext') cannot be primary_certification_eligible=True")
        _st_pin = studies[qid].get("source_pin")
        if _pce is True and isinstance(_st_pin, dict) and _st_pin.get("source_type") in _title_only_pins:
            raise ValueError(f"Title-only study edge {e.get('edge_id')} cannot be primary_certification_eligible=True")
        if _pce is True and e.get("evidence_provenance") in _non_emp_prov:
            raise ValueError(f"Simulated/modeled edge {e.get('edge_id')} ({e.get('evidence_provenance')}) cannot be primary_certification_eligible=True")
        if _pce is True and _eid in CURATED_INELIGIBLE_EDGE_IDS:
            raise ValueError(f"Curated-ineligible edge {_eid} cannot be primary_certification_eligible=True")
        if _pce is True and re.search(r"(?i)(\btitle[- ]only\b|\bno\s+measured\s+result\b|\bread\s+from\s+the\s+title\s+alone\b)", str(e.get("claim_summary") or "")):
            raise ValueError(f"Edge {e.get('edge_id')} narrative states title-only / no measured result while primary_certification_eligible=True")
        _cited_tuples = e.get("cited_outcome_tuples") or []
        if len(_cited_tuples) != len(set(_cited_tuples)):
            raise ValueError(f"Edge {e.get('edge_id')} cited_outcome_tuples contains duplicate outcome(s): {_cited_tuples!r}")
        if _pce is True and not _cited_tuples:
            raise ValueError(f"Primary-certification-eligible edge {e.get('edge_id')} must cite at least one outcome (cited_outcome_tuples is empty)")
        for tok in _cited_tuples:
            if not isinstance(tok, str) or tok not in outcomes:
                raise ValueError(f"Edge {e.get('edge_id')} cites unresolved outcome {tok}")
            _fwd_cited_by.setdefault(tok, set()).add(str(e.get("edge_id")))
            if _pce is True:
                _oc = outcomes[tok]
                _oc_qid = _oc.get("queue_id")
                if _oc_qid not in studies or studies[_oc_qid].get("record_class") != "empirical_primary_study":
                    raise ValueError(
                        f"Primary-certification-eligible edge {e.get('edge_id')} cites outcome {tok} owned by non-empirical/duplicate study {_oc_qid} ({studies.get(_oc_qid, {}).get('record_class')})"
                    )
                _oc_st_pin = studies[_oc_qid].get("source_pin")
                if isinstance(_oc_st_pin, dict) and _oc_st_pin.get("source_type") in _title_only_pins:
                    raise ValueError(
                        f"Primary-certification-eligible edge {e.get('edge_id')} cites outcome {tok} owned by title-only study {_oc_qid} (source_type={_oc_st_pin.get('source_type')!r})"
                    )
                if _oc.get("evidence_provenance") in _non_emp_prov:
                    raise ValueError(
                        f"Primary-certification-eligible edge {e.get('edge_id')} cites computational/simulated or mixed provenance outcome {tok} ({_oc.get('evidence_provenance')})"
                    )
                _oc_sim_text = re.sub(
                    r"(?i)(\brandom\s+simulated\s+genes\b|\bin\s+silico-predicted\s+cas9\s+off-target\s+sites\b|\bsimulated\s+intraportal\s+hypoxia\b|\brelative\s+to\s+simulated\s+genes\b)",
                    "",
                    " ".join(str(_oc.get(k) or "") for k in ("endpoint_name", "quantitative_summary", "comparison_arms", "intervention_value", "assay_or_endpoint")),
                )
                if re.search(
                    r"(?i)(\bsimulated\b|\bin[\s-]+silico\b|\bcomputational\s+model\s+only\b|\bsimulation[- ]only\b|\bsimulation\s+only\b|\bmodel[- ]predicted\b|\bfinite[- ]element\s+(?:prediction|model)\b|\bmonte\s+carlo\s+simulation\b|\btheoretical\s+calculation\b)",
                    _oc_sim_text,
                ):
                    raise ValueError(
                        f"Primary-certification-eligible edge {e.get('edge_id')} cites outcome {tok} carrying simulation-only narrative"
                    )
                _oc_pin_t = (_oc.get("source_pin") or {}).get("source_type") if isinstance(_oc.get("source_pin"), dict) else None
                if _oc_pin_t in _title_only_pins:
                    raise ValueError(
                        f"Primary-certification-eligible edge {e.get('edge_id')} cites title-only outcome {tok} (source_type={_oc_pin_t!r})"
                    )
        _cited_local = e.get("cited_outcome_ids")
        if not isinstance(_cited_local, list):
            raise ValueError(f"Edge {e.get('edge_id')} cited_outcome_ids must be a list")
        if len(_cited_local) != len(set(_cited_local)):
            raise ValueError(f"Edge {e.get('edge_id')} cited_outcome_ids contains duplicate outcome(s): {_cited_local!r}")
        if _pce is True and not _cited_local:
            raise ValueError(f"Primary-certification-eligible edge {e.get('edge_id')} must cite at least one outcome (cited_outcome_ids is empty)")
        _resolved_local: set[str] = set()
        for _loc in _cited_local:
            if not isinstance(_loc, str) or not _loc.strip():
                raise ValueError(f"Edge {e.get('edge_id')} has invalid cited_outcome_id {_loc!r}")
            _full_loc = _loc if ":" in _loc else f"{qid}:{_loc}"
            if _full_loc not in outcomes:
                raise ValueError(f"Edge {e.get('edge_id')} cited_outcome_id {_loc!r} resolves to unresolved outcome {_full_loc!r}")
            _resolved_local.add(_full_loc)
        if _resolved_local != set(_cited_tuples):
            raise ValueError(
                f"Edge {e.get('edge_id')} cited_outcome_ids {sorted(_resolved_local)} mismatches cited_outcome_tuples {sorted(set(_cited_tuples))}"
            )
    for oid, _oc_sym in outcomes.items():
        _bwd_edges = _oc_sym.get("cited_by_edge_ids")
        if _bwd_edges is not None and not isinstance(_bwd_edges, list):
            raise ValueError(f"Outcome {oid} cited_by_edge_ids must be a list or omitted, got {type(_bwd_edges).__name__}")
        if _bwd_edges is not None and len(_bwd_edges) != len(set(_bwd_edges)):
            raise ValueError(f"Outcome {oid} cited_by_edge_ids contains duplicate edge_id(s): {_bwd_edges!r}")
        _bwd_set = set(_bwd_edges or [])
        _fwd_set = _fwd_cited_by.get(oid, set())
        if _bwd_set != _fwd_set:
            raise ValueError(
                f"Outcome {oid} cited_by_edge_ids {sorted(_bwd_set)} is asymmetric with citing edges {sorted(_fwd_set)}"
            )
    for qid, _idxs in _link_indices_by_study.items():
        if sorted(_idxs) != list(range(len(_idxs))):
            raise ValueError(f"Study {qid} has non-contiguous or out-of-range link_index sequence {sorted(_idxs)} (expected 0..{len(_idxs)-1})")
        if studies[qid].get("links_count") != len(_idxs):
            raise ValueError(f"Study {qid} links_count={studies[qid].get('links_count')} disagrees with {len(_idxs)} edges")
    for eff_id, eff in effectors.items():
        for sq in eff.get("linked_study_ids") or []:
            if sq not in studies:
                raise ValueError(f"Effector {eff_id} references missing study {sq}")
        for sv in eff.get("linked_variable_ids") or []:
            if sv not in arms:
                raise ValueError(f"Effector {eff_id} references missing arm {sv}")
        for tok in eff.get("linked_outcome_tuples") or []:
            if not isinstance(tok, str) or tok not in outcomes:
                raise ValueError(f"Effector {eff_id} references missing outcome {tok}")

    gy_path = repo_root / GRAVEYARD_REL_PATH
    if gy_path.is_file():
        gy_ids = {row["graveyard_id"] for row in json.loads(gy_path.read_text(encoding="utf-8")).get("graveyard_entries", [])}
        for g in graveyard:
            if g.get("graveyard_id") not in gy_ids:
                raise ValueError(f"CEG graveyard entry {g.get('graveyard_id')} missing from {GRAVEYARD_REL_PATH}")

    # Global study<->arm ownership symmetry, outcomes_count, and same-study explicit outcome arm FKs
    _actual_out_counts: dict[str, int] = {}
    for _oid_g, _o_g in outcomes.items():
        _oqid_g = _o_g.get("queue_id")
        _actual_out_counts[_oqid_g] = _actual_out_counts.get(_oqid_g, 0) + 1
        for _af in ("comparator_arm_id", "focal_arm_id", "intervention_arm_id"):
            _av = _o_g.get(_af)
            if _av is not None:
                if not isinstance(_av, str) or not _av.strip():
                    raise ValueError(f"Outcome {_oid_g} has invalid {_af}={_av!r}")
                _full_av = _av if _av.startswith("VAR:") else f"VAR:{_oqid_g}:{_av}"
                if _full_av not in arms:
                    raise ValueError(f"Outcome {_oid_g} {_af}={_av!r} does not resolve in CEG arms")
                if arms[_full_av].get("queue_id") != _oqid_g:
                    raise ValueError(f"Outcome {_oid_g} {_af}={_av!r} belongs to study {arms[_full_av].get('queue_id')!r}, not {_oqid_g!r}")
    for _qid_g, _st_g in studies.items():
        _st_vids = _st_g.get("variable_arm_ids") or []
        if len(_st_vids) != len(set(_st_vids)):
            raise ValueError(f"Study {_qid_g} has duplicate entries in variable_arm_ids")
        for _vid_g in _st_vids:
            if arms[_vid_g].get("queue_id") != _qid_g:
                raise ValueError(f"Study {_qid_g} variable_arm_ids references arm {_vid_g} owned by {arms[_vid_g].get('queue_id')!r}")
        if _st_g.get("outcomes_count") != _actual_out_counts.get(_qid_g, 0):
            raise ValueError(f"Study {_qid_g} outcomes_count={_st_g.get('outcomes_count')} disagrees with actual {_actual_out_counts.get(_qid_g, 0)}")
    for _vid_g, _a_g in arms.items():
        _aq_g = _a_g.get("queue_id")
        if _vid_g not in set(studies[_aq_g].get("variable_arm_ids") or []):
            raise ValueError(f"Arm {_vid_g} owned by {_aq_g} is missing from study variable_arm_ids")

    # Strict IIP-0034 & IIP-0035 new-record typed arm FKs, same-study joins, effector refs, no-partial-dossier span audit & full-leaf rolling-40 _SourceGuard
    _iip0034_qids = frozenset({"PMID:17375075", "PMID:42020736", "PMID:42056515", "PMID:42749803"})
    _iip0034_eids = frozenset({"PMID:17375075:L1", "PMID:42020736:L1", "PMID:42056515:L1", "PMID:42749803:L1", "M1522:L4"})
    _iip0034_req_pmids = ("17375075", "39696686", "42020736", "42056515", "42749803")
    _iip0035_qids = frozenset({"M0189", "M1407", "PMID:36944335", "PMID:39753706", "PMID:41436438", "PMID:41999746"})
    _iip0035_expected_edge_bindings = {
        "M0189:L1": ("M0189", ("M0189:O1", "M0189:O2"), "9489a2d260775e0591af72799e3a2297260f4b2df14dc29cdc59acbad01e7c7b"),
        "M1407:L1": ("M1407", ("M1407:O1",), "97edc6fff8dca53a997b4d6c544eebad6253eba29f0cd720cf335994947f451a"),
        "PMID:36944335:L1": ("PMID:36944335", ("PMID:36944335:O1",), "8177ff0a7f4837d6609155d02f26064aa674e6d6433d5519344421888b80d8cb"),
        "PMID:39753706:L1": ("PMID:39753706", ("PMID:39753706:O1", "PMID:39753706:O2"), "7f8df9e1e6c03a9d386e2e57c0592bc28fe88d8694487daf36d324ef1efe40cf"),
        "PMID:41436438:L1": ("PMID:41436438", ("PMID:41436438:O1",), "05ce92c5032f16e4b53d438cdcf9b63b4251d57a8769661be819ce1a104379d6"),
        "PMID:41999746:L1": ("PMID:41999746", ("PMID:41999746:O1",), "9a30fdc5656e490bf78c93d018a740d8b67eb27c2059a73a0059279db2db9e33"),
        "M0051:L4": ("M0051", ("M0051:O1", "M0051:O5"), "fa7fb021669e6a71f22cc4078dd477bda9904c47e819b2c250a9e2081f9962bf"),
        "M0154:L3": ("M0154", ("M0154:O1", "M0154:O3", "M0154:O4"), "dfc1fb8e65f7db6084552b462c21532d9cab4d326ca13eef0f280e50e4cd5f2c"),
        "M0159:L3": ("M0159", ("M0159:O2",), "1c18c658d8351a5128abb0b5a21846fa2a15fe4001b0b733cee5d650d51de8cc"),
        "M0206:L3": ("M0206", ("M0206:O1", "M0206:O2", "M0206:O9", "M0206:O11", "M0206:O12", "M0206:O17"), "9c3f1e834d57b4683fcb135274c0cc00e482f0752ba61636b1dd595b75d796b5"),
        "M0241:L3": ("M0241", ("M0241:O1", "M0241:O2", "M0241:O4"), "60a3e30568b5bd329c5595fbfb5fa779c344f597f0ba8f0bc84c049f9f24c00f"),
    }
    _iip0035_eids = frozenset(_iip0035_expected_edge_bindings)
    _iip0035_adjudicated_inelig_legacy_outcomes = {
        "M0051:L1": (("M0051:O1", "M0051:O5"), "fda2fee5e96b1ae2f699dea5a5919eef81acb185440cfdb446157be83fff582b"),
        "M0051:L2": (("M0051:O1", "M0051:O5"), "b0b8d71b045b709de53cc8d8975a44f88bf343886f9944a8775f4f107b0acb29"),
        "M0051:L3": (("M0051:O4",), "a1b650ca58d7ee3f65d7ce05ad380e3bcbe2de5515f58b2ad8ce2f5b9ce6e147"),
        "M0154:L1": (("M0154:O1", "M0154:O2"), "b0b04b722d7ae4282cf253721cc6c9a536b39ba352dea2d69f2711eb947c5966"),
        "M0154:L2": (("M0154:O1", "M0154:O3", "M0154:O4"), "54844b79b54e02a1ba799f3bc4cae9366b949d7ad737ab0ff317aec213f36667"),
        "M0159:L1": (("M0159:O2", "M0159:O3"), "eec8033b2915fc19c425683bff865193b98e0534e520b52a50e07bb2cd980081"),
        "M0159:L2": (("M0159:O1", "M0159:O2", "M0159:O3"), "c4ab223e2234ae63414688b3c3c0110cfba5f2f15c189331945cc3afccee5258"),
        "M0206:L2": (("M0206:O9", "M0206:O12", "M0206:O10", "M0206:O14", "M0206:O17"), "bf2d25dc5e33e302309c364e95c85c87934028065912bf4673e67b27c91de241"),
        "M0241:L1": (("M0241:O2", "M0241:O3"), "0415b7d3450a99d88ec2b370284472391a5b9c4399f1f72e05497c6eaac7f255"),
        "M0241:L2": (("M0241:O1", "M0241:O4"), "fe8c8f2f7c3d40ba478a86ce88e9a9c49d7ca24f6df3a2f1b9a6f3fa807554bb"),
    }
    _iip0035_m206_l1_expected_sha = "c8f8cb8f03df508b94717777577b0e2b76754a49c0b55140cf7f02f2d57224c1"
    _iip0035_expected_arm_digests = {
        "VAR:M0189:A1": "9020bdec3108bc526a05cf1e13398c37e0b7d1c01d2f7a0b8a5129e8ff7dbd19",
        "VAR:M0189:A2_allogeneic_ctrl": "d9a3ab49db3a1550ec72677e231e8f78c0669498b1ce87f9b3cc15809d9af47e",
        "VAR:M1407:A1": "80003667e1218301f14566c81b6b226f12f08b72e8ebff76ea177c81e2e11ee8",
        "VAR:PMID:36944335:A1": "223640329c6632b6a2bd0adb299ac60ed8629b709f0bd573a93abfd9335663d1",
        "VAR:PMID:39753706:A1": "12df2f6220286f5d8e98d4f9f950e2dfc95f30e207cb367fb44e8a483ab195c5",
        "VAR:PMID:39753706:A2_original_protocol_ctrl": "97ce0849c5fe173b9707d41139d258cc2c2038dff728c2301838e51fb7a776ad",
        "VAR:PMID:41436438:A1": "47e244e5b004fbfad064117b9e2becb09f127252c705e773f4b59a30927e2776",
        "VAR:PMID:41999746:A1": "f050b9f19a1ca640dc14637faf81855973cb5dc3c6376c0429e9af0371c9db03",
        "VAR:PMID:41999746:A2_p53_suppressed": "aff8562531c232b9f4f0ec8901053ba94fe42ce918a62eadf4ced84ddfff0c50",
    }
    _iip0035_expected_study_digests = {
        "M0051": "9055b09619127bd732fb7a01c55d5892c8b969943071f2060384e88a4470a8ec",
        "M0154": "4ebf6675583e3c4280bd47ad99856ae2a9dcd4274ee625723363ccda00ec5c74",
        "M0159": "51a9f1e1eb1df33b6bb788ffada5a4568dba0460a001289489ddc2187419267d",
        "M0189": "7ffd063adaee8afa4e0459b06cdf78dd6b8d6fb1bcd7af583d8ea4af34e692e0",
        "M0206": "db841bb24d0809dfba7182e115522a1a1ebf8eb69ebbbba79caf103118f284da",
        "M0241": "aedb1f65d2aaa5e50f313233e6abbf0aa291ba895698cdc42b17fc4376f76294",
        "M1407": "6853a47499993ff09a7ce678abaf46b60247c381ad8895a3539b75e07986da52",
        "PMID:36944335": "4ba894d0e55d502d206a649a4b3bbbfff7198a21c3b7a2aba541e17724074534",
        "PMID:39753706": "beb5b67461b96dc2d45dad5d553daae964cb77c4f301775b9fbd1ae8284cb565",
        "PMID:41436438": "251ecb8d8de9aaed414a3b0db37dd320af2600f2584bfd85ae011a89aa3c8ebb",
        "PMID:41999746": "90ff19574e43e343599dd14a4b64524b6e9897b6f2b0b3ea1e5f252864bfcfd8",
    }
    _iip0035_expected_dossier_digests = {
        "2642862": "a463f7f1770ed78ca7c892db54c59b2970cc83226cd48e71302218b9b48d89fa",
        "31427818": "f6593b87fda7d0bc1211d17d30288dbb86f6b408af77482adf4022e7531c1b98",
        "35953586": "6ff5efa024e5614f8a98125f51fbb3958b90c36dc1426293328b6537fa3d678b",
        "36944335": "ef775e8802dc187a5e04949fb88c2dda258044d9a205849a08699ac01a3eb03a",
        "38843830": "cc6ba867300b9c420070dd7bb25a7a59e7c5395269388652b50ca567f24611d1",
        "39753706": "948c18dddd97935f2c0cb6fa73fd905c8dc2aff31e7b64dfbe39d574059c552e",
        "41201433": "184652ef2fdbc682abf441f25930a58bb990f238e4f3e8846bf4c229ae8dd544",
        "41436438": "9db3a80db0a50ded4b7d8054c451b9ed017ffe3e17201808eef81b7d84b2e787",
        "41690310": "b55f46afb7307ff6793ad519b06a5735aee77a0b610cdeda0c8ed0d03fec3d5f",
        "41764741": "e7095034b47de98edcf0c2c8a46a1659600e2299a8928880b56b81ec6a58dbe6",
        "41999746": "dd2f6aac6a4812460da51ebae389980cf025d626ea41f810bd985d5193c67aa1",
    }
    _iip0035_adjudicated_inelig_legacy = frozenset(_iip0035_adjudicated_inelig_legacy_outcomes)
    _iip0035_req_pmids = ("2642862", "31427818", "35953586", "36944335", "38843830", "39753706", "41201433", "41436438", "41690310", "41764741", "41999746")
    _iip0035_crosslink_eids = frozenset({"M0051:L4", "M0154:L3", "M0159:L3", "M0206:L3", "M0241:L3"})
    _strict_study_expected_pmid = {
        "PMID:17375075": "17375075", "PMID:42020736": "42020736", "PMID:42056515": "42056515", "PMID:42749803": "42749803",
        "M0189": "38843830", "M1407": "2642862", "PMID:36944335": "36944335", "PMID:39753706": "39753706",
        "PMID:41436438": "41436438", "PMID:41999746": "41999746",
    }
    _strict_new_qids = _iip0034_qids | _iip0035_qids
    _strict_new_eids = _iip0034_eids | _iip0035_eids
    _strict_req_pmids = _iip0034_req_pmids + _iip0035_req_pmids
    _edges_by_eid_35 = {e.get("edge_id"): e for e in edges if isinstance(e, dict) and isinstance(e.get("edge_id"), str)}
    _missing_35_eids = sorted(eid for eid in _iip0035_expected_edge_bindings if eid not in _edges_by_eid_35)
    if _missing_35_eids:
        raise ValueError(f"Missing required IIP-0035 CEG edges: {_missing_35_eids}")
    for _eid35, (_exp_owner35, _exp_outs35, _exp_esha35) in sorted(_iip0035_expected_edge_bindings.items()):
        _eobj35 = _edges_by_eid_35[_eid35]
        if _eobj35.get("queue_id") != _exp_owner35:
            raise ValueError(f"IIP-0035 edge {_eid35} owner queue_id={_eobj35.get('queue_id')!r} mismatches expected {_exp_owner35!r}")
        if tuple(_eobj35.get("cited_outcome_tuples") or ()) != _exp_outs35:
            raise ValueError(f"IIP-0035 edge {_eid35} cited_outcome_tuples={_eobj35.get('cited_outcome_tuples')!r} mismatches expected {list(_exp_outs35)!r}")
        if _eobj35.get("primary_certification_eligible") is not False:
            raise ValueError(f"IIP-0035 edge {_eid35} must keep primary_certification_eligible=False")
        if _eid35 in _iip0035_crosslink_eids:
            _pn35 = _eobj35.get("provenance_note")
            if (
                not isinstance(_pn35, str)
                or len(_pn35.strip()) < 40
                or not re.search(r"(?i)\b(?:reused|legacy|prior)\b", _pn35)
                or not re.search(r"(?i)\b(?:outside|non-certifying|primary_certification_eligible\s*=\s*false|scoping)\b", _pn35)
            ):
                raise ValueError(f"IIP-0035 cross-link edge {_eid35} missing grounded provenance_note disclosing reused legacy outcomes and non-certifying scoping status")
    for _leg_eid, (_leg_outs, _leg_sha) in sorted(_iip0035_adjudicated_inelig_legacy_outcomes.items()):
        if _leg_eid not in _edges_by_eid_35:
            raise ValueError(f"Missing adjudicated legacy edge {_leg_eid}")
        _le_o = _edges_by_eid_35[_leg_eid]
        if _le_o.get("primary_certification_eligible") is not False:
            raise ValueError(f"Adjudicated legacy ineligible edge {_leg_eid} must have primary_certification_eligible=False")
        if tuple(_le_o.get("cited_outcome_tuples") or ()) != _leg_outs:
            raise ValueError(f"Adjudicated legacy edge {_leg_eid} cited_outcome_tuples={_le_o.get('cited_outcome_tuples')!r} mismatches pinned {list(_leg_outs)!r}")
        if not isinstance(_le_o.get("legacy_certification_adjudication_note"), str) or len(_le_o["legacy_certification_adjudication_note"].strip()) < 25:
            raise ValueError(f"Adjudicated legacy edge {_leg_eid} missing required legacy_certification_adjudication_note")
    _iip0035_reclass_qual_oids = frozenset({
        "M0051:O1", "M0051:O2", "M0051:O3", "M0051:O4", "M0051:O5", "M0051:O6",
        "M0154:O1", "M0154:O2", "M0154:O3", "M0154:O4",
        "M0159:O1", "M0159:O2", "M0159:O3", "M0206:O16", "M0206:O17",
        "M0241:O1", "M0241:O2", "M0241:O3", "M0241:O4",
    })
    _QUANTITATIVE_CEG_STAT_TYPES = frozenset({
        "adjusted_difference_95ci", "descriptive_scalar", "fold_change", "hazard_or_odds_ratio",
        "mean_sd", "mean_sem", "mean_unspecified_spread", "median_iqr", "median_no_iqr",
        "proportion_or_rate", "qualitative_with_pvalue", "threshold_or_limit",
    })
    def _is_strictly_quantitative_outcome(_o_obj: object) -> bool:
        if not isinstance(_o_obj, dict):
            return False
        _st_t = _o_obj.get("stat_type")
        if not isinstance(_st_t, str) or _st_t not in _QUANTITATIVE_CEG_STAT_TYPES:
            return False
        _qs_s = _o_obj.get("quantitative_summary")
        if not isinstance(_qs_s, str) or not _qs_s.strip():
            return False
        if _qs_s.startswith("[Structured outcome "):
            _m_st = re.search(r"\| stat=([^|\]]+)", _qs_s)
            _m_dr = re.search(r"\| direction=([^|\]]+)", _qs_s)
            _m_sh = re.search(r"\| text_sha256=([0-9a-f]{64})\]", _qs_s)
            return bool(
                _m_st and _m_st.group(1).strip() == _st_t
                and _m_dr and _m_dr.group(1).strip() == str(_o_obj.get("direction") or "")
                and _m_sh and _m_sh.group(1) != ("0" * 64)
            )
        _qs_clean = re.sub(r"(?i)\b(?:19|20)\d{2}\b|\bfig(?:ure|\.)?\s*\d+[a-z]?\b|\bno\s+(?:statistically\s+)?significant\b", "", _qs_s)
        return bool(re.search(r"(?i)\d|\b(?:seven|eight|nine|ten)\b|\b(?:p|q)\s*[<>=]", _qs_clean))
    _m206_l1 = _edges_by_eid_35.get("M0206:L1")
    if _m206_l1 is None:
        raise ValueError("Missing adjudicated legacy edge M0206:L1")
    if _m206_l1.get("primary_certification_eligible") is not True:
        raise ValueError("Adjudicated legacy edge M0206:L1 must retain primary_certification_eligible=True")
    if not isinstance(_m206_l1.get("legacy_certification_adjudication_note"), str) or len(_m206_l1["legacy_certification_adjudication_note"].strip()) < 25:
        raise ValueError("Adjudicated legacy edge M0206:L1 missing required legacy_certification_adjudication_note")
    _m206_l1_cited = set(_m206_l1.get("cited_outcome_tuples") or ())
    for _mq1_oid in ("M0206:O1", "M0206:O4", "M0206:O5", "M0206:O9", "M0206:O12", "M0206:O14"):
        if _mq1_oid not in _m206_l1_cited or not _is_strictly_quantitative_outcome(outcomes.get(_mq1_oid)):
            raise ValueError("Adjudicated eligible edge M0206:L1 lost required quantitative supporting outcomes (M0206:O1/O4/O5/O9/O12/O14)")
    _m206_quant_pins = {
        "M0206:O9": "206461c65c89f8beb98b07c60682def3a7630a8f304bc775fe335fd6881b7599",
        "M0206:O10": "657046a02a07b1d552081851f167b7b295524f9452e65a5fbbbcb60046e6e954",
        "M0206:O12": "6afc1cccdbbf01657d8e24a0474f0873e6f347f6d7f0ef3e7133b66d5598fa62",
        "M0206:O13": "97e837e2971618c7c4932c65be5e622b8a756f406a93ef5aeae5d97667c8df40",
        "M0206:O14": "d46885980a5df070f33af99b205b6a8767be818b28015002150ff860c40be3df",
    }
    _iip0035_reclass_qual_full_pins = {
        "M0051:O1": "a0bc9db01f9c48fb685c66935a6b9109f1cbad7d84b2d6ee43155bb37f464d5e",
        "M0051:O2": "9ed9340d7c048a9c4ad61157baaab275f5702b09b9870b6e78a13c2b75cbb4ae",
        "M0051:O3": "90ad72f976b7d53bf04440e95873de9307d0c890f09856b53e86c2de204cd44f",
        "M0051:O4": "55c5057c0407ead476b421a8cb6f612f9a9f3ca35121776be928f73d0ffb9837",
        "M0051:O5": "6295e33d78bc392be430f6aa666ce970bc6b75c054becd5c2772a237e9df2788",
        "M0051:O6": "eba0288a320e9e0683bee3c7a68f9b6fb43a84134a15610fc4a2fb03d3993c53",
        "M0154:O1": "57091a572aad298fa2ec83b0e1bb8d41d6ee6d095ff50963ba5167a65e895dda",
        "M0154:O2": "dfd88df33001b3d33cc7308a738ef038be85fda382f743f6c95316713b08d994",
        "M0154:O3": "7feec71e4681d21b8fcdec2a0aeb5b2614bb13d72d997e925c5baf9025f92b46",
        "M0154:O4": "13254ce5be0d57e4bddbc22ea63c8762cfc95489e108ecbb0b8c94f36d0d13ad",
        "M0159:O1": "b84f01f9419fea8281e3945f36d25a33eeaccddfd7fde8cc4a1d8cc074800590",
        "M0159:O2": "a926f9f872f5deee6ccc2339f389280701405365385b161dd793100325db7600",
        "M0159:O3": "2ac6e7dd0f20e834096488ef19cd2f4669572d5ed80a7388f5b1b63b559f2bbe",
        "M0206:O16": "e6066f67c0cf36927213c0e5ede9c7e620edbf7235e4cc01a3e1ff5a75f8e0c6",
        "M0206:O17": "4c401ace0a25a7d12cb267e57afff7fd99cb97449168f7c176c2bf95038a4f48",
        "M0241:O1": "597a4f4057f533288848b064131bff70f4a9058c4cb3a4f190d238e981cd838d",
        "M0241:O2": "0e11c337fe4fecee4e91d09e515b0c01faa3da0a0628958492520e568566bc96",
        "M0241:O3": "b0ff58c33ea4ca207ab3f5240ad55a157428bc161a7fade71d6ae72373aa4a6a",
        "M0241:O4": "b3704a8198b3726f0d0cec304b171170cd6dec40493751f1479da5070b1d1fb4",
    }
    _iip0035_extra_touched_legacy_pins = {
        "M0206:O1": "26bf1b6d4882eadf88a82b849e51f532f4b385e8155fc715d32724f179d0cf14",
        "M0206:O2": "5af461ec5e52c0a98ba11825c508c92916751cab607209e340ca0de7bbe2e42f",
        "M0206:O11": "2cec03ac91647ee462d33c73aea9f5ee6d6270a2879bfa06d21499d74424ef54",
    }
    for _e_rc in edges:
        if _e_rc.get("primary_certification_eligible") is True:
            _rc_cites = list(_e_rc.get("cited_outcome_tuples") or ())
            if any(tok in _iip0035_reclass_qual_oids for tok in _rc_cites):
                if not any(_is_strictly_quantitative_outcome(outcomes.get(tok)) for tok in _rc_cites):
                    raise ValueError(f"Primary-certification-eligible edge {_e_rc.get('edge_id')} citing reclassified qualitative outcomes retains zero quantitative outcomes")
    _iip0035_expected_outcome_semantics = {
        "M0189:O1": (("VAR:M0189:A1",), ("VAR:M0189:A2_allogeneic_ctrl",), "favorable_to_intervention", "2ec0a977b228e707bc2625dbecf2e40f2cfe382374a8e468e4b8820d637f6db4", ("8", "14", "autologous")),
        "M0189:O2": (("VAR:M0189:A2_allogeneic_ctrl",), (), "unfavorable_or_toxic", "42085854453c51bb47668076b3a22186a9f3c504532f88a6399cdecddee78fc5", ("8", "weeks", "allogeneic")),
        "M1407:O1": (("VAR:M1407:A1",), (), "unfavorable_or_toxic", "43fb4a54bd27bc337ee9e68e7f1e186093d7c11f24ad9a6d03481ef0ff5c36bc", ("200", "8", "3", "5")),
        "PMID:36944335:O1": (("VAR:PMID:36944335:A1",), (), "favorable_to_intervention", "546ab2caf3e9efd8ed2aa5e6fa07f7fde2f9b0bf75eaa98f921a9182bee06398", ("16", "17")),
        "PMID:39753706:O1": (("VAR:PMID:39753706:A1",), ("VAR:PMID:39753706:A2_original_protocol_ctrl",), "favorable_to_intervention", "a121f1e0d76d8d437b85b1f6ce1770c1ed80ab23d2818d607b956b4f1bf768fa", ("20-fold", "16", "resistant")),
        "PMID:39753706:O2": (("VAR:PMID:39753706:A1",), (), "favorable_to_intervention", "c11043d7a9680fbc516cf5b1a320e6ee48ce984faef52367608eb18f18ec3d32", ("10", "day", "15", "100%")),
        "PMID:41436438:O1": (("VAR:PMID:41436438:A1",), (), "favorable_to_intervention", "e3b925d9248ae8353729616a7a6f865f3c716d3ea95de0aa5171289412f78b7c", ("14", "100")),
        "PMID:41999746:O1": (("VAR:PMID:41999746:A1",), ("VAR:PMID:41999746:A2_p53_suppressed",), "favorable_to_intervention", "b92e09e4ac38dfd2f262f4ef9ca01ec877a82910a2707e20936833a84929547b", ("p53", "impairs")),
    }
    for _sem_oid in sorted(_iip0035_expected_outcome_semantics):
        if not isinstance(outcomes.get(_sem_oid), dict):
            raise ValueError(f"Missing required IIP-0035 outcome {_sem_oid}")
    for _chk_qid, _chk_pm in sorted(_strict_study_expected_pmid.items()):
        _chk_st = studies.get(_chk_qid)
        if isinstance(_chk_st, dict):
            if _study_pmid(_chk_st) != _chk_pm or str(_chk_st.get("id_value") or "") != _chk_pm:
                raise ValueError(f"Study {_chk_qid} owner PMID/id_value mismatch: got pmid={_study_pmid(_chk_st)!r}, id_value={_chk_st.get('id_value')!r}, expected {_chk_pm!r}")
            if _chk_qid.startswith("PMID:") and _chk_qid.split(":", 1)[1] != _chk_pm:
                raise ValueError(f"Study {_chk_qid} queue_id PMID prefix disagrees with expected {_chk_pm!r}")
    _sf_led = (ceg.get("screening_funnel") or {}).get("iip0035_record_level_screening_ledger")
    if not isinstance(_sf_led, list) or len(_sf_led) != 11:
        raise ValueError("CEG screening_funnel missing 11-record iip0035_record_level_screening_ledger")
    _led_expected_rows = {
        "M0051": ("41201433", "existing_wave1_ceg_candidate_crosslinked_only_deferred_from_ring1_to_preserve_layer1_baseline", (0, 0, 0, 0, 0, 0, 0, 0)),
        "M0154": ("41690310", "existing_wave1_ceg_candidate_promoted_to_ring1_and_crosslinked", (0, 1, -1, 0, 0, 0, 0, 0)),
        "M0159": ("41764741", "existing_wave1_ceg_candidate_promoted_to_ring1_and_crosslinked", (0, 1, -1, 0, 0, 0, 0, 0)),
        "M0206": ("35953586", "existing_wave1_ceg_candidate_promoted_to_ring1_and_crosslinked", (0, 1, -1, 0, 0, 0, 0, 0)),
        "M0241": ("31427818", "existing_wave1_ceg_candidate_promoted_to_ring1_and_crosslinked", (0, 1, -1, 0, 0, 0, 0, 0)),
        "M0189": ("38843830", "existing_wave2b_queued_candidate_extracted_to_ring1_and_wave1_ceg", (0, 1, -1, 0, 0, 0, 1, -1)),
        "M1407": ("2642862", "existing_parked_context_record_promoted_to_ring1_and_wave1_ceg", (0, 1, -1, 1, -1, 0, 1, 0)),
        "PMID:36944335": ("36944335", "new_literature_screened_advanced_to_ring1_and_wave1_ceg", (1, 1, 0, 1, 0, 0, 1, 0)),
        "PMID:39753706": ("39753706", "new_literature_screened_advanced_to_ring1_and_wave1_ceg", (1, 1, 0, 1, 0, 0, 1, 0)),
        "PMID:41436438": ("41436438", "new_literature_screened_advanced_to_ring1_and_wave1_ceg", (1, 1, 0, 1, 0, 0, 1, 0)),
        "PMID:41999746": ("41999746", "new_literature_screened_advanced_to_ring1_and_wave1_ceg", (1, 1, 0, 1, 0, 0, 1, 0)),
    }
    _led_delta_keys = ("d_screened_total", "d_ring1_screened", "d_new_screened", "d_advanced", "d_parked", "d_excluded", "d_wave1_extracted", "d_remaining_catalog")
    _seen_led_qids: set[str] = set()
    for _lr in _sf_led:
        if not isinstance(_lr, dict):
            raise ValueError("CEG iip0035_record_level_screening_ledger contains non-dict row")
        _lq = _lr.get("queue_id")
        if not isinstance(_lq, str) or _lq not in _led_expected_rows or _lq in _seen_led_qids:
            raise ValueError(f"CEG screening ledger has unexpected or duplicate queue_id={_lq!r}")
        _seen_led_qids.add(_lq)
        _exp_lpm, _exp_ltr, _exp_dtup = _led_expected_rows[_lq]
        if _lq not in studies or _study_pmid(studies[_lq]) != _exp_lpm or type(_lr.get("pmid")) is not str or _lr.get("pmid") != _exp_lpm:
            raise ValueError(f"CEG screening ledger row {_lq} PMID mismatch (row_pmid={_lr.get('pmid')!r}, study_pmid={_study_pmid(studies[_lq]) if _lq in studies else None!r}, expected={_exp_lpm!r})")
        if _lq.startswith("PMID:") and _lr.get("discovery_provenance") != "targeted_iip0035_proposal_screening_not_in_frozen_wave0_discovered_pmids_all_sources":
            raise ValueError(f"CEG screening ledger row {_lq} missing required targeted discovery_provenance tag (got {_lr.get('discovery_provenance')!r})")
        if _lr.get("transition") != _exp_ltr:
            raise ValueError(f"CEG screening ledger row {_lq} transition={_lr.get('transition')!r} mismatches expected {_exp_ltr!r}")
        _got_dtup = []
        for _dk in _led_delta_keys:
            _dv = _lr.get(_dk)
            if type(_dv) is not int:
                raise ValueError(f"CEG screening ledger row {_lq} field {_dk}={_dv!r} must be strict int")
            _got_dtup.append(_dv)
        if tuple(_got_dtup) != _exp_dtup:
            raise ValueError(f"CEG screening ledger row {_lq} deltas={tuple(_got_dtup)!r} mismatch expected {_exp_dtup!r}")
        if _got_dtup[1] + _got_dtup[2] != _got_dtup[0] or _got_dtup[3] + _got_dtup[4] + _got_dtup[5] != _got_dtup[0] or _got_dtup[6] + _got_dtup[7] != _got_dtup[3]:
            raise ValueError(f"CEG screening ledger row {_lq} violates per-row conservation: {tuple(_got_dtup)!r}")
    if _seen_led_qids != set(_led_expected_rows):
        raise ValueError(f"CEG screening ledger missing expected records: {sorted(set(_led_expected_rows) - _seen_led_qids)}")
    _led_base = {"d_screened_total": 3938, "d_ring1_screened": 594, "d_new_screened": 3344, "d_advanced": 3263, "d_parked": 522, "d_excluded": 153, "d_wave1_extracted": 1176, "d_remaining_catalog": 2087}
    _led_map = {"d_screened_total": "screened_records_total", "d_ring1_screened": "ring1_existing_records_screened", "d_new_screened": "new_candidate_records_screened", "d_advanced": "candidates_advanced_total", "d_parked": "contextual_reviews_parked_total", "d_excluded": "off_topic_records_excluded_total", "d_wave1_extracted": "wave1_ceg_records_extracted_total", "d_remaining_catalog": "remaining_supporting_catalog_queued_for_later_waves"}
    _ceg_counts_35 = ceg.get("counts") if isinstance(ceg.get("counts"), dict) else {}
    _sf_w5_led = (ceg.get("screening_funnel") or {}).get("wave5_delta_screening_ledger")
    if not isinstance(_sf_w5_led, list) or len(_sf_w5_led) != 40:
        raise ValueError("CEG screening_funnel missing 40-record wave5_delta_screening_ledger")
    _sf_hist35 = (ceg.get("screening_funnel") or {}).get("historical_iip0035_1182_milestone")
    if not isinstance(_sf_hist35, dict):
        raise ValueError("CEG screening_funnel missing historical_iip0035_1182_milestone snapshot")
    _seen_w5_qids: set[str] = set()
    for _wr in _sf_w5_led:
        if not isinstance(_wr, dict):
            raise ValueError("CEG wave5_delta_screening_ledger contains non-dict row")
        _wq = _wr.get("queue_id")
        if not isinstance(_wq, str) or _wq not in studies or _wq in _seen_w5_qids:
            raise ValueError(f"CEG wave5_delta_screening_ledger has invalid or duplicate queue_id={_wq!r}")
        _seen_w5_qids.add(_wq)
        _w_dtup = []
        for _dk in _led_delta_keys:
            _dv = _wr.get(_dk)
            if type(_dv) is not int:
                raise ValueError(f"CEG wave5 ledger row {_wq} field {_dk}={_dv!r} must be strict int")
            _w_dtup.append(_dv)
        if _w_dtup[1] + _w_dtup[2] != _w_dtup[0] or _w_dtup[3] + _w_dtup[4] + _w_dtup[5] != _w_dtup[0] or _w_dtup[6] + _w_dtup[7] != _w_dtup[3]:
            raise ValueError(f"CEG wave5 ledger row {_wq} violates per-row conservation: {tuple(_w_dtup)!r}")
    _sf_w5_hist = (ceg.get("screening_funnel") or {}).get("historical_wave5_1216_milestone")
    if not isinstance(_sf_w5_hist, dict):
        raise ValueError("CEG screening_funnel missing historical_wave5_1216_milestone snapshot")
    _sf_44_led = (ceg.get("screening_funnel") or {}).get("ceg_v1_cutover_record_level_screening_ledger")
    if not isinstance(_sf_44_led, list) or len(_sf_44_led) != 21:
        raise ValueError("CEG screening_funnel missing 21-record ceg_v1_cutover_record_level_screening_ledger")
    _seen_44_qids: set[str] = set()
    for _r44 in _sf_44_led:
        if not isinstance(_r44, dict):
            raise ValueError("CEG ceg_v1_cutover_record_level_screening_ledger contains non-dict row")
        _q44 = _r44.get("queue_id")
        if not isinstance(_q44, str) or _q44 in _seen_44_qids:
            raise ValueError(f"CEG ceg_v1_cutover_record_level_screening_ledger has invalid or duplicate queue_id={_q44!r}")
        _seen_44_qids.add(_q44)
        _t44 = []
        for _dk in _led_delta_keys:
            _dv = _r44.get(_dk)
            if type(_dv) is not int:
                raise ValueError(f"CEG cutover ledger row {_q44} field {_dk}={_dv!r} must be strict int")
            _t44.append(_dv)
        if _t44[1] + _t44[2] != _t44[0] or _t44[3] + _t44[4] + _t44[5] != _t44[0] or _t44[6] + _t44[7] != _t44[3]:
            raise ValueError(f"CEG cutover ledger row {_q44} violates per-row conservation: {tuple(_t44)!r}")
    _w5_led_sha = _sha256_str(json.dumps(_sf_w5_led, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
    if _w5_led_sha != '0fe43d7e1ecf5db53cf2bf549ab95b995bfdf7d41864da267113b4a6f83f1118':
        raise ValueError(f"CEG wave5_delta_screening_ledger identity modified ({_w5_led_sha} != 0fe43d7e1ecf5db53cf2bf549ab95b995bfdf7d41864da267113b4a6f83f1118)")
    _c44_led_sha = _sha256_str(json.dumps(_sf_44_led, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
    if _c44_led_sha != 'e1dff9c39c3ff24088541d8537fe37007e4948d5450af1f08302106c0a7d5283':
        raise ValueError(f"CEG ceg_v1_cutover_record_level_screening_ledger identity modified ({_c44_led_sha} != e1dff9c39c3ff24088541d8537fe37007e4948d5450af1f08302106c0a7d5283)")
    _w6_expected_qid_to_pmid = json.loads('{"PMID:1334978": "1334978", "PMID:17130499": "17130499", "PMID:17503968": "17503968", "PMID:21912932": "21912932", "PMID:22315720": "22315720", "PMID:23572523": "23572523", "PMID:23616575": "23616575", "PMID:23935835": "23935835", "PMID:30449685": "30449685", "PMID:32433410": "32433410", "PMID:33722583": "33722583", "PMID:34033222": "34033222", "PMID:35046043": "35046043", "PMID:35725270": "35725270", "PMID:36560629": "36560629", "PMID:37106062": "37106062", "PMID:37306457": "37306457", "PMID:37679570": "37679570", "PMID:38135691": "38135691", "PMID:38768856": "38768856", "PMID:38848367": "38848367", "PMID:39647511": "39647511", "PMID:40066448": "40066448", "PMID:41118637": "41118637", "PMID:8384206": "8384206"}')
    _sf_w6_led = (ceg.get("screening_funnel") or {}).get("wave6_delta_record_level_screening_ledger")
    if not isinstance(_sf_w6_led, list) or len(_sf_w6_led) != 25:
        raise ValueError("CEG screening_funnel missing 25-record wave6_delta_record_level_screening_ledger")
    _sf_pre_w6 = (ceg.get("screening_funnel") or {}).get("historical_baseline_pre_wave6_milestone")
    if not isinstance(_sf_pre_w6, dict):
        raise ValueError("CEG screening_funnel missing historical_baseline_pre_wave6_milestone snapshot")
    _seen_w6_qids: set[str] = set()
    for _rw6 in _sf_w6_led:
        if not isinstance(_rw6, dict):
            raise ValueError("CEG wave6_delta_record_level_screening_ledger contains non-dict row")
        _qw6 = _rw6.get("queue_id")
        if not isinstance(_qw6, str) or _qw6 not in _w6_expected_qid_to_pmid or _qw6 not in studies or _qw6 in _seen_w6_qids:
            raise ValueError(f"CEG wave6 ledger has invalid, baseline, or duplicate queue_id={_qw6!r}")
        _seen_w6_qids.add(_qw6)
        _exp_w6_pm = _w6_expected_qid_to_pmid[_qw6]
        if type(_rw6.get("pmid")) is not str or _rw6.get("pmid") != _exp_w6_pm or _study_pmid(studies[_qw6]) != _exp_w6_pm:
            raise ValueError(f"CEG wave6 ledger row {_qw6} PMID mismatch (row={_rw6.get('pmid')!r}, study={_study_pmid(studies[_qw6])!r}, expected={_exp_w6_pm!r})")
        if _rw6.get("transition") != "new_literature_screened_advanced_to_wave1_ceg":
            raise ValueError(f"CEG wave6 ledger row {_qw6} unexpected transition={_rw6.get('transition')!r}")
        _tw6 = []
        for _dk in _led_delta_keys:
            _dv = _rw6.get(_dk)
            if type(_dv) is not int:
                raise ValueError(f"CEG wave6 ledger row {_qw6} field {_dk}={_dv!r} must be strict int")
            _tw6.append(_dv)
        if tuple(_tw6) != (1, 0, 1, 1, 0, 0, 1, 0):
            raise ValueError(f"CEG wave6 ledger row {_qw6} deltas={tuple(_tw6)!r} violate exact per-study unit contribution (1,0,1,1,0,0,1,0)")
    if _seen_w6_qids != set(_w6_expected_qid_to_pmid):
        raise ValueError(f"CEG wave6 ledger missing expected Wave-6 studies: {sorted(set(_w6_expected_qid_to_pmid) - _seen_w6_qids)}")
    for _dk, _sfk in _led_map.items():
        _calc35 = _led_base[_dk] + sum(r[_dk] for r in _sf_led)
        if _sf_hist35.get(_sfk) != _calc35:
            raise ValueError(f"CEG historical_iip0035_1182_milestone.{_sfk}={_sf_hist35.get(_sfk)} disagrees with 11-record IIP-0035 ledger sum {_calc35}")
        _calc_w5 = _calc35 + sum(r[_dk] for r in _sf_w5_led)
        if _sf_w5_hist.get(_sfk) != _calc_w5:
            raise ValueError(f"CEG historical_wave5_1216_milestone.{_sfk}={_sf_w5_hist.get(_sfk)} disagrees with cumulative IIP-0035+Wave5 ledger sum {_calc_w5}")
        _calc_44 = _calc_w5 + sum(r[_dk] for r in _sf_44_led)
        if _sf_pre_w6.get(_sfk) != _calc_44:
            raise ValueError(f"CEG historical_baseline_pre_wave6_milestone.{_sfk}={_sf_pre_w6.get(_sfk)} disagrees with cumulative CEG-v1 sum {_calc_44}")
        _calc_w6 = _calc_44 + sum(r[_dk] for r in _sf_w6_led)
        if ceg["screening_funnel"].get(_sfk) != _calc_w6:
            raise ValueError(f"CEG screening_funnel {_sfk}={ceg['screening_funnel'].get(_sfk)} disagrees with cumulative IIP-0035+Wave5+CEG-v1-cutover+Wave6 ledger sum {_calc_w6}")
        if _sfk in _ceg_counts_35 and _ceg_counts_35.get(_sfk) != _calc_w6:
            raise ValueError(f"CEG counts.{_sfk}={_ceg_counts_35.get(_sfk)} disagrees with screening_funnel {_calc_w6}")
    _arm_tok_re = re.compile(r"\b(A\d+(?:_[A-Za-z0-9_]+)?)\b")
    _span_re = re.compile(r"^([A-Za-z0-9_\.\[\]]+)\[(\d+):(\d+)\]\|norm=exact$")

    for _qid34 in sorted(_strict_new_qids):
        _st34 = studies.get(_qid34)
        if isinstance(_st34, dict) and _qid34 in _strict_study_expected_pmid:
            _exp_pm = _strict_study_expected_pmid[_qid34]
            if _study_pmid(_st34) != _exp_pm or str(_st34.get("id_value") or "") != _exp_pm:
                raise ValueError(f"Study {_qid34} owner PMID/id_value mismatch: got pmid={_study_pmid(_st34)!r}, id_value={_st34.get('id_value')!r}, expected {_exp_pm!r}")
            if _qid34.startswith("PMID:") and _qid34.split(":", 1)[1] != _exp_pm:
                raise ValueError(f"Study {_qid34} queue_id PMID prefix disagrees with expected {_exp_pm!r}")
        if not isinstance(_st34, dict):
            raise ValueError(f"Missing required IIP-0034 study {_qid34}")
        for _ef in (_st34.get("candidate_effector_topics") or []):
            if _ef not in effectors:
                raise ValueError(f"IIP-0034 study {_qid34} references unresolved effector {_ef!r}")
    for _vid34, _a34 in arms.items():
        _aq34 = _a34.get("queue_id")
        if _aq34 not in _strict_new_qids:
            continue
        _exp_vid = f"VAR:{_aq34}:{_a34.get('arm_id')}"
        if _vid34 != _exp_vid or _a34.get("variable_id") != _exp_vid:
            raise ValueError(f"IIP-0034 arm {_vid34} mismatches embedded variable_id/arm_id ({_exp_vid})")
        for _ef in (_a34.get("candidate_effector_topics") or []):
            if _ef not in effectors:
                raise ValueError(f"IIP-0034 arm {_vid34} references unresolved effector {_ef!r}")
    _legacy_m1522_eids = frozenset({"M1522:L1", "M1522:L2"})
    _iip0042_evidence_qids = frozenset({
        "M0300",
        "PMID:22099783",
        "PMID:30012675",
        "PMID:30569273",
        "PMID:30967424",
        "PMID:31180194",
        "PMID:33632742",
        "PMID:33658358",
        "PMID:37861217",
        "PMID:39137044",
        "PMID:40447640",
        "PMID:40598585",
        "PMID:40976248",
        "PMID:41026533",
        "PMID:41196293",
    })
    for _e34 in edges:
        _eq34 = _e34.get("queue_id")
        _eid34 = str(_e34.get("edge_id") or "")
        if _eid34 in _iip0035_crosslink_eids:
            if _e34.get("primary_certification_eligible") is not False:
                raise ValueError(f"IIP-0035 cross-link edge {_eid34} must keep primary_certification_eligible=False")
            _pnote = _e34.get("provenance_note")
            if (
                not isinstance(_pnote, str)
                or len(_pnote.strip()) < 40
                or not re.search(r"(?i)\b(?:reused|legacy|prior)\b", _pnote)
                or not re.search(r"(?i)\b(?:outside|non-certifying|primary_certification_eligible\s*=\s*false|scoping)\b", _pnote)
            ):
                raise ValueError(
                    f"IIP-0035 cross-link edge {_eid34} missing grounded provenance_note disclosing reused legacy outcomes and non-certifying scoping status"
                )
        if _e34.get("primary_certification_eligible") is True and _e34.get("applicability") == "unvalidated_transfer":
            if (
                _eq34 in _strict_new_qids
                or _eid34 in _strict_new_eids
                or (_eq34 == "M1522" and _eid34 not in _legacy_m1522_eids)
                or _eq34 in _iip0042_evidence_qids
            ):
                raise ValueError(
                    f"Edge {_eid34} ({_eq34}) with applicability='unvalidated_transfer' cannot be primary_certification_eligible=True"
                )
        if _eid34 in _strict_new_eids or _eq34 in _strict_new_qids:
            for _tok34 in (_e34.get("cited_outcome_tuples") or []):
                if outcomes[_tok34].get("queue_id") != _eq34:
                    raise ValueError(f"IIP-0034 edge {_eid34} cites cross-study outcome {_tok34} (owned by {outcomes[_tok34].get('queue_id')!r}, not {_eq34!r})")
            for _ef in (_e34.get("candidate_effector_topics") or []):
                if _ef not in effectors:
                    raise ValueError(f"IIP-0034 edge {_eid34} references unresolved effector {_ef!r}")

    _dossiers_dir = repo_root / "data" / "dossiers"
    _has_dossiers_dir = _dossiers_dir.is_dir()
    _loaded_dos_by_pmid: dict[str, dict[str, Any]] = {}
    if _has_dossiers_dir or require_sources:
        _present_34 = [pm for pm in _iip0034_req_pmids if (_dossiers_dir / f"{pm}.json").is_file()]
        _present_35 = [pm for pm in _iip0035_req_pmids if (_dossiers_dir / f"{pm}.json").is_file()]
        _req_cohorts: list[str] = []
        if require_sources:
            _req_cohorts = list(_strict_req_pmids)
        else:
            if _present_34:
                _req_cohorts.extend(_iip0034_req_pmids)
            if _present_35:
                _req_cohorts.extend(_iip0035_req_pmids)
            if not _req_cohorts:
                _req_cohorts = list(_strict_req_pmids)
        _missing_dos = [pm for pm in _req_cohorts if not (_dossiers_dir / f"{pm}.json").is_file()]
        if _missing_dos:
            raise ValueError(
                f"Incomplete local dossier set for source-level CEG verification: missing {_missing_dos} under {_dossiers_dir}"
            )
        for _pm34 in _req_cohorts:
            _dobj_34 = json.loads((_dossiers_dir / f"{_pm34}.json").read_text(encoding="utf-8"))
            _int_pm34 = str(_dobj_34.get("pmid") or "").strip()
            if _int_pm34 != _pm34:
                raise ValueError(f"Dossier {_pm34}.json internal pmid={_int_pm34!r} mismatches filename stem {_pm34!r}")
            if _pm34 in _iip0035_expected_dossier_digests:
                _got_dsha35 = _sha256_str(json.dumps(_dobj_34, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
                if _got_dsha35 != _iip0035_expected_dossier_digests[_pm34]:
                    raise ValueError(f"IIP-0035 dossier {_pm34}.json full-object digest {_got_dsha35} mismatches pinned {_iip0035_expected_dossier_digests[_pm34]}")
            _loaded_dos_by_pmid[_pm34] = _dobj_34

    def _resolve_dossier_span(_dos_obj: dict[str, Any], _path_expr: str) -> str:
        _cur: Any = _dos_obj
        for _part in _path_expr.split("."):
            _m_idx = re.fullmatch(r"([A-Za-z0-9_]+)\[(\d+)\]", _part)
            if _m_idx:
                _cur = _cur[_m_idx.group(1)][int(_m_idx.group(2))]
            else:
                _cur = _cur[_part]
        if not isinstance(_cur, str):
            raise ValueError(f"Dossier span path {_path_expr!r} did not resolve to string")
        return _cur

    def _verify_pin_obj(_oid_p: str, _pm_p: str, _pin_obj: dict[str, Any], _expected_sha: Any) -> None:
        _sp_str = str((_pin_obj or {}).get("span") or "")
        _m_sp = _span_re.fullmatch(_sp_str)
        if not _m_sp:
            raise ValueError(f"Outcome {_oid_p} has malformed span={_sp_str!r}")
        _p_expr, _s_i, _e_i = _m_sp.group(1), int(_m_sp.group(2)), int(_m_sp.group(3))
        if _s_i < 0 or _e_i <= _s_i:
            raise ValueError(f"Outcome {_oid_p} has invalid span coordinates [{_s_i}:{_e_i}]")
        if not isinstance(_expected_sha, str) or not re.fullmatch(r"[0-9a-f]{64}", _expected_sha):
            raise ValueError(f"Outcome {_oid_p} missing valid 64-hex quote_sha256")
        if _pm_p in _loaded_dos_by_pmid:
            _src_txt = _resolve_dossier_span(_loaded_dos_by_pmid[_pm_p], _p_expr)
            if _e_i > len(_src_txt):
                raise ValueError(f"Outcome {_oid_p} span [{_s_i}:{_e_i}] exceeds dossier length {len(_src_txt)}")
            _slice_sha = _sha256_str(_src_txt[_s_i:_e_i])
            if _slice_sha != _expected_sha:
                raise ValueError(f"Outcome {_oid_p} span digest {_slice_sha} mismatches quote_sha256 {_expected_sha!r}")

    _verified_iip0034_span_oids: list[str] = []
    _verified_iip0035_span_oids: list[str] = []
    for oid, o in outcomes.items():
        _oqid = o.get("queue_id")
        if _oqid not in _strict_new_qids:
            continue
        _exp_oid = f"{_oqid}:{o.get('outcome_id')}"
        if oid != _exp_oid or o.get("outcome_node_id") != _exp_oid:
            raise ValueError(f"IIP-0034 outcome {oid} mismatches embedded outcome_node_id/outcome_id ({_exp_oid})")
        for _ef in (o.get("candidate_effector_topics") or []):
            if _ef not in effectors:
                raise ValueError(f"IIP-0034 outcome {oid} references unresolved effector {_ef!r}")
        _iv_arms = o.get("intervention_arm_ids")
        _cmp_arms = o.get("comparator_arm_ids")
        if not isinstance(_iv_arms, list) or not _iv_arms or not isinstance(_cmp_arms, list):
            raise ValueError(f"IIP-0034 outcome {oid} missing required typed intervention_arm_ids/comparator_arm_ids lists")
        if len(_iv_arms) != len(set(_iv_arms)) or len(_cmp_arms) != len(set(_cmp_arms)):
            raise ValueError(f"IIP-0034 outcome {oid} contains duplicate entries in intervention_arm_ids or comparator_arm_ids")
        if not set(_iv_arms).isdisjoint(set(_cmp_arms)):
            raise ValueError(f"IIP-0034 outcome {oid} intervention_arm_ids and comparator_arm_ids overlap")
        for _t_vid in (*_iv_arms, *_cmp_arms):
            if not isinstance(_t_vid, str) or _t_vid not in arms:
                raise ValueError(f"IIP-0034 outcome {oid} typed arm ref {_t_vid!r} does not resolve in CEG arms")
            if arms[_t_vid].get("queue_id") != _oqid:
                raise ValueError(f"IIP-0034 outcome {oid} typed arm ref {_t_vid!r} belongs to {arms[_t_vid].get('queue_id')!r}, not {_oqid!r}")
        _opt_cmp = o.get("comparator_arm_id")
        if _opt_cmp is not None:
            _full_opt_cmp = _opt_cmp if _opt_cmp.startswith("VAR:") else f"VAR:{_oqid}:{_opt_cmp}"
            if _full_opt_cmp not in _cmp_arms:
                raise ValueError(f"IIP-0034 outcome {oid} comparator_arm_id {_opt_cmp!r} disagrees with comparator_arm_ids={_cmp_arms!r}")
        _ca_raw = o.get("comparison_arms")
        if not isinstance(_ca_raw, str) or not _ca_raw.strip():
            raise ValueError(f"IIP-0034 outcome {oid} comparison_arms must be a non-empty string")
        _ca_tokens = _arm_tok_re.findall(_ca_raw)
        _ca_vids: set[str] = set()
        for _atok in _ca_tokens:
            _cand_vid = f"VAR:{_oqid}:{_atok}"
            if _cand_vid not in arms or arms[_cand_vid].get("queue_id") != _oqid:
                raise ValueError(f"Outcome {oid} comparison_arms references unresolved or cross-study arm {_cand_vid}")
            _ca_vids.add(_cand_vid)
        if _ca_vids != (set(_iv_arms) | set(_cmp_arms)):
            raise ValueError(
                f"IIP-0034 outcome {oid} typed arm lists ({sorted(set(_iv_arms) | set(_cmp_arms))}) disagree with comparison_arms ({sorted(_ca_vids)})"
            )
        _vs_split = re.split(r"\bvs\b", _ca_raw, maxsplit=1, flags=re.IGNORECASE)
        if len(_vs_split) == 2:
            _lhs_vids = {f"VAR:{_oqid}:{t}" for t in _arm_tok_re.findall(_vs_split[0])}
            _rhs_vids = {f"VAR:{_oqid}:{t}" for t in _arm_tok_re.findall(_vs_split[1])}
            if _lhs_vids != set(_iv_arms) or _rhs_vids != set(_cmp_arms):
                raise ValueError(
                    f"IIP-0034 outcome {oid} typed intervention/comparator roles disagree with comparison_arms LHS/RHS"
                )
        elif _cmp_arms:
            raise ValueError(f"IIP-0034 outcome {oid} lists comparator_arm_ids={_cmp_arms!r} without a 'vs' contrast in comparison_arms")
        _opt_iv = o.get("intervention_arm_id")
        if _opt_iv is not None:
            _full_opt_iv = _opt_iv if str(_opt_iv).startswith("VAR:") else f"VAR:{_oqid}:{_opt_iv}"
            if _full_opt_iv != _iv_arms[0] or _full_opt_iv in _cmp_arms:
                raise ValueError(f"Outcome {oid} singular intervention_arm_id={_opt_iv!r} disagrees with primary intervention_arm_ids={_iv_arms!r} / comparator_arm_ids={_cmp_arms!r}")
        if _oqid in _iip0035_qids:
            _fa = o.get("focal_arm_id")
            if not isinstance(_fa, str) or _fa != _iv_arms[0] or _fa in _cmp_arms:
                raise ValueError(f"IIP-0035 outcome {oid} focal_arm_id={_fa!r} must match primary intervention arm {_iv_arms[0]!r} and never appear in comparator_arm_ids={_cmp_arms!r}")
            if not isinstance(_opt_iv, str) or _opt_iv != _iv_arms[0] or _opt_iv in _cmp_arms:
                raise ValueError(f"IIP-0035 outcome {oid} required singular intervention_arm_id={_opt_iv!r} must match primary intervention arm {_iv_arms[0]!r} and never appear in comparator_arm_ids={_cmp_arms!r}")
            if oid in _iip0035_expected_outcome_semantics:
                _sem_iv, _sem_cmp, _sem_dir, _sem_csha, _sem_toks = _iip0035_expected_outcome_semantics[oid]
                if tuple(_iv_arms) != _sem_iv or tuple(_cmp_arms) != _sem_cmp:
                    raise ValueError(f"IIP-0035 outcome {oid} arm-role semantics ({_iv_arms!r}, {_cmp_arms!r}) mismatch expected ({list(_sem_iv)!r}, {list(_sem_cmp)!r})")
                if o.get("direction") != _sem_dir:
                    raise ValueError(f"IIP-0035 outcome {oid} direction={o.get('direction')!r} mismatches expected {_sem_dir!r}")
                _joined_o = " ".join(str(o.get(k) or "") for k in ("endpoint_name", "intervention_value", "quantitative_summary")).lower()
                for _tk in _sem_toks:
                    if _tk.lower() not in _joined_o:
                        raise ValueError(f"IIP-0035 outcome {oid} missing required structured endpoint/magnitude token {_tk!r}")
        _pm_o = _study_pmid(studies[_oqid])
        _exp_pm_o = _strict_study_expected_pmid.get(_oqid)
        if _exp_pm_o is not None and _pm_o != _exp_pm_o:
            raise ValueError(f"Outcome {oid} resolved PMID {_pm_o!r} mismatches expected owner {_exp_pm_o!r}")
        if _loaded_dos_by_pmid and _oqid in _iip0035_qids and all(pm in _loaded_dos_by_pmid for pm in _iip0035_req_pmids):
            if _pm_o not in _loaded_dos_by_pmid:
                raise ValueError(f"Outcome {oid} owner PMID {_pm_o!r} missing from loaded IIP-0035 dossiers (refusing silent span skip)")
        if _loaded_dos_by_pmid and _oqid in _iip0034_qids and all(pm in _loaded_dos_by_pmid for pm in _iip0034_req_pmids):
            if _pm_o not in _loaded_dos_by_pmid:
                raise ValueError(f"Outcome {oid} owner PMID {_pm_o!r} missing from loaded IIP-0034 dossiers (refusing silent span skip)")
        _sp_primary = o.get("source_pin") or {}
        if isinstance(_sp_primary, dict) and "quote_sha256" in _sp_primary and _sp_primary["quote_sha256"] != o.get("quote_sha256"):
            raise ValueError(
                f"Outcome {oid} nested source_pin.quote_sha256 {_sp_primary['quote_sha256']!r} conflicts with top-level quote_sha256 {o.get('quote_sha256')!r}"
            )
        _verify_pin_obj(oid, _pm_o, _sp_primary, o.get("quote_sha256"))
        if _pm_o in _loaded_dos_by_pmid:
            if _oqid in _iip0035_qids:
                if oid in _iip0035_expected_outcome_semantics:
                    _m_t = _span_re.fullmatch(str((_sp_primary or {}).get("span") or ""))
                    if _m_t:
                        _sl_txt = _resolve_dossier_span(_loaded_dos_by_pmid[_pm_o], _m_t.group(1))[int(_m_t.group(2)):int(_m_t.group(3))].lower()
                        for _tk in _iip0035_expected_outcome_semantics[oid][4]:
                            if _tk.lower() not in _sl_txt:
                                raise ValueError(f"IIP-0035 outcome {oid} pinned source span lacks required magnitude/endpoint token {_tk!r}")
                _verified_iip0035_span_oids.append(oid)
            elif _oqid in _iip0034_qids:
                _verified_iip0034_span_oids.append(oid)
        for _sec_pin in (o.get("secondary_source_pins") or []):
            if not isinstance(_sec_pin, dict):
                raise ValueError(f"Outcome {oid} malformed secondary_source_pins entry")
            _verify_pin_obj(oid, _pm_o, _sec_pin, _sec_pin.get("quote_sha256"))

    if all(pm in _loaded_dos_by_pmid for pm in _iip0035_req_pmids) and len(_verified_iip0035_span_oids) != 8:
        raise ValueError(f"Expected exactly 8 exact-span-verified IIP-0035 outcomes, got {len(_verified_iip0035_span_oids)}: {sorted(_verified_iip0035_span_oids)}")
    if all(pm in _loaded_dos_by_pmid for pm in _iip0034_req_pmids) and len(_verified_iip0034_span_oids) != 8:
        raise ValueError(f"Expected exactly 8 exact-span-verified IIP-0034 outcomes, got {len(_verified_iip0034_span_oids)}: {sorted(_verified_iip0034_span_oids)}")

    if _loaded_dos_by_pmid:
        _union_shingles: set[tuple[str, ...]] = set()
        _rolling40_set: set[str] = set()
        for _d34 in _loaded_dos_by_pmid.values():
            _dt34 = " ".join(_leaves(_d34))
            _ws34 = _words(_dt34)
            _union_shingles.update(tuple(_ws34[i : i + 6]) for i in range(max(0, len(_ws34) - 5)))
            _nd34 = _norm_spaces(_dt34).lower()
            _rolling40_set.update(_nd34[i : i + 40] for i in range(max(0, len(_nd34) - 39)))

        _SG_SKIP_KEYS = frozenset({
            "doi", "pmid", "pmcid", "title", "first_author", "senior_author", "journal", "citation_short", "queue_id", "context_id", "variable_id", "outcome_node_id", "edge_id",
            "arm_id", "outcome_id", "quote_sha256", "span", "source_type", "intervention_arm_ids",
            "comparator_arm_ids", "cited_outcome_ids", "cited_outcome_tuples", "cited_by_edge_ids",
            "variable_arm_ids", "candidate_effector_topics", "record_class", "fidelity_tier", "manuscript_tier",
            "direction", "stat_type", "relation", "applicability", "incorporation", "readiness",
            "causal_isolation", "id_type", "id_value", "role", "figure_id", "panel", "table_id", "row_id", "col_id",
        })

        def _scan_sg(_obj: Any, _path_lbl: str) -> None:
            if isinstance(_obj, dict):
                for _k, _v in _obj.items():
                    if _k in _SG_SKIP_KEYS and not (isinstance(_v, str) and len(_v) > 32 and _k in {"figure_id", "panel", "table_id", "row_id", "col_id"}):
                        continue
                    _scan_sg(_v, f"{_path_lbl}.{_k}")
            elif isinstance(_obj, list):
                for _i, _v in enumerate(_obj):
                    _scan_sg(_v, f"{_path_lbl}[{_i}]")
            elif isinstance(_obj, str) and _obj:
                _ws_t = _words(_obj)
                if len(_ws_t) >= 6:
                    for _i in range(len(_ws_t) - 5):
                        if tuple(_ws_t[_i : _i + 6]) in _union_shingles:
                            raise ValueError(f"CEG {_path_lbl} violates _SourceGuard (6-word union shingle)")
                _ns_t = _norm_spaces(_obj).lower()
                if len(_ns_t) >= 40:
                    for _i in range(len(_ns_t) - 39):
                        if _ns_t[_i : _i + 40] in _rolling40_set:
                            raise ValueError(f"CEG {_path_lbl} violates _SourceGuard (rolling 40-char dossier substring)")

        _sg_qids: set[str] = set()
        _sg_eids: set[str] = set()
        if all(pm in _loaded_dos_by_pmid for pm in _iip0034_req_pmids):
            _sg_qids.update(_iip0034_qids)
            _sg_eids.update(_iip0034_eids)
        if all(pm in _loaded_dos_by_pmid for pm in _iip0035_req_pmids):
            _sg_qids.update(_iip0035_qids)
            _sg_eids.update(_iip0035_eids)
        for _qid34 in sorted(_sg_qids):
            _scan_sg(studies[_qid34], f"study.{_qid34}")
        for _vid, _a in arms.items():
            if _a.get("queue_id") in _sg_qids:
                _scan_sg(_a, f"arm.{_vid}")
        for _oid, _o in outcomes.items():
            if (
                _o.get("queue_id") in _sg_qids
                or (all(pm in _loaded_dos_by_pmid for pm in _iip0034_req_pmids) and _oid in {"M1522:O6", "M1522:O7", "M1522:O15", "M1522:O16"})
                or (all(pm in _loaded_dos_by_pmid for pm in _iip0035_req_pmids) and (_oid in _iip0035_reclass_qual_full_pins or _oid in _m206_quant_pins or _oid in _iip0035_extra_touched_legacy_pins))
            ):
                _scan_sg(_o, f"outcome.{_oid}")
        for _e in edges:
            if _e.get("edge_id") in _sg_eids:
                _scan_sg(_e, f"edge.{_e.get('edge_id')}")
            elif all(pm in _loaded_dos_by_pmid for pm in _iip0035_req_pmids) and (_e.get("edge_id") in _iip0035_adjudicated_inelig_legacy or _e.get("edge_id") in {"M0206:L1", "M0206:L2"}):
                _scan_sg(_e, f"edge.{_e.get('edge_id')}")
    # Run FULL-OBJECT IIP-0035 digest checks AFTER _SourceGuard so verbatim source leaks always trip _SourceGuard first!
    for _st_qid35, _exp_stsha35 in sorted(_iip0035_expected_study_digests.items()):
        _st_o35 = studies.get(_st_qid35)
        if not isinstance(_st_o35, dict):
            raise ValueError(f"Missing required IIP-0035 study {_st_qid35}")
        _got_stsha35 = _sha256_str(json.dumps(_st_o35, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
        if _got_stsha35 != _exp_stsha35:
            raise ValueError(f"IIP-0035 study {_st_qid35} full-object digest {_got_stsha35} mismatches pinned {_exp_stsha35}")
    for _arm_vid35, _exp_asha35 in sorted(_iip0035_expected_arm_digests.items()):
        _arm_o35 = arms.get(_arm_vid35)
        if not isinstance(_arm_o35, dict):
            raise ValueError(f"Missing required IIP-0035 arm {_arm_vid35}")
        _got_asha35 = _sha256_str(json.dumps(_arm_o35, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
        if _got_asha35 != _exp_asha35:
            raise ValueError(f"IIP-0035 arm {_arm_vid35} full-object digest {_got_asha35} mismatches pinned {_exp_asha35}")
    for _oid35_c, _sem_t35 in sorted(_iip0035_expected_outcome_semantics.items()):
        _oo35 = outcomes[_oid35_c]
        _got_csha35 = _sha256_str(json.dumps(_oo35, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
        if _got_csha35 != _sem_t35[3]:
            raise ValueError(f"IIP-0035 outcome {_oid35_c} full-object structured endpoint/magnitude digest {_got_csha35} mismatches pinned {_sem_t35[3]}")
    for _mq_oid, _mq_sha in sorted(_m206_quant_pins.items()):
        _mq_o = outcomes.get(_mq_oid)
        _mq_got = _sha256_str(json.dumps(_mq_o, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
        if _mq_got != _mq_sha:
            raise ValueError(f"Touched M0206 quantitative outcome {_mq_oid} full-object digest {_mq_got} mismatches pinned {_mq_sha}")
    for _rq_oid, _rq_sha in sorted({**_iip0035_reclass_qual_full_pins, **_iip0035_extra_touched_legacy_pins}.items()):
        _rq_o = outcomes.get(_rq_oid)
        if not isinstance(_rq_o, dict):
            raise ValueError(f"Missing proposal-modified legacy outcome {_rq_oid}")
        _rq_got = _sha256_str(json.dumps(_rq_o, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
        if _rq_got != _rq_sha:
            raise ValueError(f"Proposal-modified legacy outcome {_rq_oid} full-object digest {_rq_got} mismatches pinned {_rq_sha}")
    for _eid35, (_exp_owner35, _exp_outs35, _exp_esha35) in sorted(_iip0035_expected_edge_bindings.items()):
        _eobj35 = _edges_by_eid_35[_eid35]
        _got_esha35 = _sha256_str(json.dumps(_eobj35, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
        if _got_esha35 != _exp_esha35:
            raise ValueError(f"IIP-0035 edge {_eid35} full-object digest {_got_esha35} mismatches pinned {_exp_esha35}")
    for _leg_eid, (_leg_outs, _leg_sha) in sorted(_iip0035_adjudicated_inelig_legacy_outcomes.items()):
        _le_o = _edges_by_eid_35[_leg_eid]
        _got_lsha = _sha256_str(json.dumps(_le_o, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
        if _got_lsha != _leg_sha:
            raise ValueError(f"Adjudicated legacy edge {_leg_eid} full-object digest {_got_lsha} mismatches pinned {_leg_sha}")
    _got_m206_l1_sha = _sha256_str(json.dumps(_m206_l1, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
    if _got_m206_l1_sha != _iip0035_m206_l1_expected_sha:
        raise ValueError(f"Adjudicated legacy edge M0206:L1 full-object digest {_got_m206_l1_sha} mismatches pinned {_iip0035_m206_l1_expected_sha}")

    # Wave-6 governed verification (Audit R5-01): 25 studies, dec124_certification_status hold preservation,
    # closed VALID_EVIDENCE_SCOPE_CLASSES enum in BOTH modes, complete pinned authorized cert-eligible edge
    # bindings (target, relation, applicability, scope, cited outcomes, immutable digests) in BOTH modes,
    # edge source_pin reconciliation, and 55 exact primary+secondary source spans verified against BOTH
    # immutable pinned digests (structural mode) AND live raw Wave-6 source bytes when require_sources=True!
    _w6_pin_specs = json.loads('{"PMID:1334978:O1": {"pmid": "1334978", "primary": {"body_file": null, "body_sha256": null, "end": 662, "pmcid": null, "pmid": "1334978", "quote_sha256": "3ad3d91f867467e1434c4f3b71fe3971c5ef9fcd9a6421f59af0b4fa7b18b48e", "source_body_sha256": "51062974fd93e917a169dbb1c88d87934bee4bde0133feb45f1e45b2e8ce7a0d", "source_type": "abstract", "span": "abstract[163:662]|norm=exact", "start": 163}, "secondaries": []}, "PMID:17130499:O1": {"pmid": "17130499", "primary": {"body_file": null, "body_sha256": null, "end": 984, "pmcid": null, "pmid": "17130499", "quote_sha256": "7a6f54a735e31dba6261e365f56a4f7abf92604f947569f865f002fa6ca30188", "source_body_sha256": "3f77b66ccc8f6c5a8ddbd0e1ad5943566ecff0b754fae49fdfe605b24867b9db", "source_type": "abstract", "span": "abstract[407:984]|norm=exact", "start": 407}, "secondaries": []}, "PMID:17503968:O1": {"pmid": "17503968", "primary": {"body_file": "17503968_PMC1868042.txt", "body_sha256": "3186879e13088ca92f42f6b46651e40071497e68154426ed5762a4dd1ee3b1df", "end": 18746, "pmcid": "PMC1868042", "pmid": "17503968", "quote_sha256": "1e3aaff6c2dd7b5bdadf5ce144b75b499e6667bba47aa522c786ab77817110ef", "source_body_sha256": null, "source_type": "fulltext_results", "span": "fulltext[17569:18746]|norm=exact", "start": 17569}, "secondaries": []}, "PMID:17503968:O2": {"pmid": "17503968", "primary": {"body_file": "17503968_PMC1868042.txt", "body_sha256": "3186879e13088ca92f42f6b46651e40071497e68154426ed5762a4dd1ee3b1df", "end": 20536, "pmcid": "PMC1868042", "pmid": "17503968", "quote_sha256": "b85bba579fe29c300d16585132ec0af1d0b07587775d1b5e9a36fd57b99f9ef8", "source_body_sha256": null, "source_type": "fulltext_results", "span": "fulltext[19644:20536]|norm=exact", "start": 19644}, "secondaries": []}, "PMID:17503968:O3": {"pmid": "17503968", "primary": {"body_file": null, "body_sha256": null, "end": 1628, "pmcid": null, "pmid": "17503968", "quote_sha256": "7087984daa22cef5532e80cd7b7d20bcef72be656c8b4c3e2f77debf57012e69", "source_body_sha256": "e94df896f2c624d06c6739fdccacc6622bc2b4655686de821e713edc5e2a10e7", "source_type": "abstract", "span": "abstract[1225:1628]|norm=exact", "start": 1225}, "secondaries": []}, "PMID:21912932:O1": {"pmid": "21912932", "primary": {"body_file": null, "body_sha256": null, "end": 1203, "pmcid": null, "pmid": "21912932", "quote_sha256": "eefad3a66b1fd1bce700421958a3f113bb8f9253599d040b2322f6f413a9f432", "source_body_sha256": "0354750e0aa0087f9608a989496e562b4f57a42b8fdbafd410171b01dd7de6a6", "source_type": "abstract", "span": "abstract[0:1203]|norm=exact", "start": 0}, "secondaries": []}, "PMID:22315720:O1": {"pmid": "22315720", "primary": {"body_file": null, "body_sha256": null, "end": 816, "pmcid": null, "pmid": "22315720", "quote_sha256": "c81579f248edaf1a415f3542d8840c2ff5b396c5a8c1a27c06020885d5b782bb", "source_body_sha256": "42330ac201c6e0990b36d2b00328622fee6460f83ca6bb37a067189494a69f0a", "source_type": "abstract", "span": "abstract[404:816]|norm=exact", "start": 404}, "secondaries": []}, "PMID:23572523:O1": {"pmid": "23572523", "primary": {"body_file": null, "body_sha256": null, "end": 793, "pmcid": null, "pmid": "23572523", "quote_sha256": "2b2e0a076a655373d85cdbd0eb7fc8d93051e210af57222cb5313d22a7f3bac3", "source_body_sha256": "23661b0aca70ec5a6fb67e478e00e46a071533375890250db6c9a43493bab785", "source_type": "abstract", "span": "abstract[445:793]|norm=exact", "start": 445}, "secondaries": []}, "PMID:23572523:O2": {"pmid": "23572523", "primary": {"body_file": null, "body_sha256": null, "end": 1060, "pmcid": null, "pmid": "23572523", "quote_sha256": "0c55579db0bbfb006b96207808c3cc10d57aabfc87c848076d935ac571c7580f", "source_body_sha256": "23661b0aca70ec5a6fb67e478e00e46a071533375890250db6c9a43493bab785", "source_type": "abstract", "span": "abstract[794:1060]|norm=exact", "start": 794}, "secondaries": []}, "PMID:23616575:O1": {"pmid": "23616575", "primary": {"body_file": "23616575_PMC3825029.txt", "body_sha256": "aa426f775dbb545be9600e91ff775750d9c0284af6248e8efa76f0a51b5a2464", "end": 31137, "pmcid": "PMC3825029", "pmid": "23616575", "quote_sha256": "f6be29fd7f6877f423b3c6c22853d987d5d77a40f63cdaecf9e1c42ecf82ffb6", "source_body_sha256": null, "source_type": "fulltext_results", "span": "fulltext[30609:31137]|norm=exact", "start": 30609}, "secondaries": []}, "PMID:23616575:O2": {"pmid": "23616575", "primary": {"body_file": "23616575_PMC3825029.txt", "body_sha256": "aa426f775dbb545be9600e91ff775750d9c0284af6248e8efa76f0a51b5a2464", "end": 35496, "pmcid": "PMC3825029", "pmid": "23616575", "quote_sha256": "d1e8bf056ba55a5da51393e1e74c4f951f6dfa56988aeda50903e97873de9087", "source_body_sha256": null, "source_type": "fulltext_results", "span": "fulltext[34432:35496]|norm=exact", "start": 34432}, "secondaries": []}, "PMID:23935835:O1": {"pmid": "23935835", "primary": {"body_file": null, "body_sha256": null, "end": 1516, "pmcid": null, "pmid": "23935835", "quote_sha256": "83fb380e01244e98bc26db64427998c228d308e775ff4de62165c05854a485b5", "source_body_sha256": "fb891d6df35e53788e24384b6c4499bd2ebce21698294eb67b76c893ada2ab3b", "source_type": "abstract", "span": "abstract[565:1516]|norm=exact", "start": 565}, "secondaries": [{"body_file": null, "body_sha256": null, "end": 564, "pmcid": null, "pmid": "23935835", "quote_sha256": "da0ffa6cb9ee3e435a52399429595166162be3c32830dbdf6b10e712628674a2", "source_body_sha256": "fb891d6df35e53788e24384b6c4499bd2ebce21698294eb67b76c893ada2ab3b", "source_type": "abstract", "span": "abstract[233:564]|norm=exact", "start": 233}, {"body_file": "23935835_PMC3723782.txt", "body_sha256": "d23d87a9d06a5de3cdd87754004ba3e9d55538fe800eaae8c6a1d353723b868c", "end": 9145, "pmcid": "PMC3723782", "pmid": "23935835", "quote_sha256": "95ced49b4dc89a4aa9f9778237a44f0e7981823bd101987950970a0ed17624f3", "source_body_sha256": null, "source_type": "fulltext_methods", "span": "fulltext[8516:9145]|norm=exact", "start": 8516}, {"body_file": "23935835_PMC3723782.txt", "body_sha256": "d23d87a9d06a5de3cdd87754004ba3e9d55538fe800eaae8c6a1d353723b868c", "end": 23016, "pmcid": "PMC3723782", "pmid": "23935835", "quote_sha256": "f43e1fd5ccf5135309a600d5e23aff7c06f176013bb549e3761741bca94f1b35", "source_body_sha256": null, "source_type": "fulltext_results", "span": "fulltext[22731:23016]|norm=exact", "start": 22731}]}, "PMID:23935835:O2": {"pmid": "23935835", "primary": {"body_file": "23935835_PMC3723782.txt", "body_sha256": "d23d87a9d06a5de3cdd87754004ba3e9d55538fe800eaae8c6a1d353723b868c", "end": 21400, "pmcid": "PMC3723782", "pmid": "23935835", "quote_sha256": "4469fcbb62ba53a3dd99d2fcd28d03f78b88003eb79f8926b1f05948a5a29bd8", "source_body_sha256": null, "source_type": "fulltext_results", "span": "fulltext[21098:21400]|norm=exact", "start": 21098}, "secondaries": []}, "PMID:23935835:O3": {"pmid": "23935835", "primary": {"body_file": "23935835_PMC3723782.txt", "body_sha256": "d23d87a9d06a5de3cdd87754004ba3e9d55538fe800eaae8c6a1d353723b868c", "end": 33162, "pmcid": "PMC3723782", "pmid": "23935835", "quote_sha256": "c25f05d1f4be50c3abae1e479fb5d9ace4370f1e08b783cbe27dd739dbbe5977", "source_body_sha256": null, "source_type": "fulltext_results", "span": "fulltext[32810:33162]|norm=exact", "start": 32810}, "secondaries": [{"body_file": "23935835_PMC3723782.txt", "body_sha256": "d23d87a9d06a5de3cdd87754004ba3e9d55538fe800eaae8c6a1d353723b868c", "end": 9145, "pmcid": "PMC3723782", "pmid": "23935835", "quote_sha256": "95ced49b4dc89a4aa9f9778237a44f0e7981823bd101987950970a0ed17624f3", "source_body_sha256": null, "source_type": "fulltext_methods", "span": "fulltext[8516:9145]|norm=exact", "start": 8516}, {"body_file": "23935835_PMC3723782.txt", "body_sha256": "d23d87a9d06a5de3cdd87754004ba3e9d55538fe800eaae8c6a1d353723b868c", "end": 9971, "pmcid": "PMC3723782", "pmid": "23935835", "quote_sha256": "f7a9feedc747bd805d50b8d1a1b0543a1e8e2e7828d543e0ec4841ed5f7cebb0", "source_body_sha256": null, "source_type": "fulltext_methods", "span": "fulltext[9619:9971]|norm=exact", "start": 9619}]}, "PMID:23935835:O4": {"pmid": "23935835", "primary": {"body_file": "23935835_PMC3723782.txt", "body_sha256": "d23d87a9d06a5de3cdd87754004ba3e9d55538fe800eaae8c6a1d353723b868c", "end": 35136, "pmcid": "PMC3723782", "pmid": "23935835", "quote_sha256": "6c33ac071e92bf3bcfd5b8a340d46a3c15653a8a1be76f1f1640880c1138f84b", "source_body_sha256": null, "source_type": "fulltext_results", "span": "fulltext[34664:35136]|norm=exact", "start": 34664}, "secondaries": [{"body_file": "23935835_PMC3723782.txt", "body_sha256": "d23d87a9d06a5de3cdd87754004ba3e9d55538fe800eaae8c6a1d353723b868c", "end": 10845, "pmcid": "PMC3723782", "pmid": "23935835", "quote_sha256": "86ad8314b333d7948f5a751d08489f8b86705582c7049a80b66045c9a2b27ad2", "source_body_sha256": null, "source_type": "fulltext_methods", "span": "fulltext[10520:10845]|norm=exact", "start": 10520}, {"body_file": "23935835_PMC3723782.txt", "body_sha256": "d23d87a9d06a5de3cdd87754004ba3e9d55538fe800eaae8c6a1d353723b868c", "end": 12227, "pmcid": "PMC3723782", "pmid": "23935835", "quote_sha256": "de3eb9277bfa9bb14cc3d69f3d7613b6d1f8d6d8ba9b0d119802dcb1d930ab12", "source_body_sha256": null, "source_type": "fulltext_methods", "span": "fulltext[11700:12227]|norm=exact", "start": 11700}]}, "PMID:30449685:O1": {"pmid": "30449685", "primary": {"body_file": null, "body_sha256": null, "end": 755, "pmcid": null, "pmid": "30449685", "quote_sha256": "ae73f2fa8f8cb374733c43b6c3d7ff8130ca171a8e28cb869356f330fa2c8960", "source_body_sha256": "0bee067ccb8763e0bd145e878dde03183a95df52642dc016b33135610dedd34d", "source_type": "abstract", "span": "abstract[118:755]|norm=exact", "start": 118}, "secondaries": []}, "PMID:30449685:O2": {"pmid": "30449685", "primary": {"body_file": null, "body_sha256": null, "end": 817, "pmcid": null, "pmid": "30449685", "quote_sha256": "285f34002146ee90252fe6a74356e50d1ced1bc83052d231301be6968a10515d", "source_body_sha256": "0bee067ccb8763e0bd145e878dde03183a95df52642dc016b33135610dedd34d", "source_type": "abstract", "span": "abstract[585:817]|norm=exact", "start": 585}, "secondaries": []}, "PMID:32433410:O1": {"pmid": "32433410", "primary": {"body_file": null, "body_sha256": null, "end": 1000, "pmcid": null, "pmid": "32433410", "quote_sha256": "4ae6cab07186e799fdf21a05061537bb4aa35c0f5ae6f4b58a1b158624ab3557", "source_body_sha256": "0d56bbbabff96629974915bc052296afc6a6a232c28f35b675aa08b67c03f028", "source_type": "abstract", "span": "abstract[521:1000]|norm=exact", "start": 521}, "secondaries": [{"body_file": null, "body_sha256": null, "end": 520, "pmcid": null, "pmid": "32433410", "quote_sha256": "a9851b79c3200e2e04d9d59e9a125d8d58ddb7a8fdccb26c29390b3ebad072c2", "source_body_sha256": "0d56bbbabff96629974915bc052296afc6a6a232c28f35b675aa08b67c03f028", "source_type": "abstract", "span": "abstract[376:520]|norm=exact", "start": 376}]}, "PMID:32433410:O2": {"pmid": "32433410", "primary": {"body_file": null, "body_sha256": null, "end": 1118, "pmcid": null, "pmid": "32433410", "quote_sha256": "683fe8f92927499d81e7fc6ca1d34687b0f3126736b8386a275aaeca43f65a99", "source_body_sha256": "0d56bbbabff96629974915bc052296afc6a6a232c28f35b675aa08b67c03f028", "source_type": "abstract", "span": "abstract[1001:1118]|norm=exact", "start": 1001}, "secondaries": []}, "PMID:33722583:O1": {"pmid": "33722583", "primary": {"body_file": null, "body_sha256": null, "end": 1079, "pmcid": null, "pmid": "33722583", "quote_sha256": "576e3d6cbda5f89bdf9669e8d7073d2b4790ee7419b3829c3e5b6611f34ba24d", "source_body_sha256": "2bd3c3d0f04b2df3cb049d3f27a910f75685850e45a20884584fdbf4bbb8efb9", "source_type": "abstract", "span": "abstract[866:1079]|norm=exact", "start": 866}, "secondaries": [{"body_file": null, "body_sha256": null, "end": 640, "pmcid": null, "pmid": "33722583", "quote_sha256": "900ab22870fcb54cd0202c5c006cc4bd9aa6bd82b32155aa33cbc9f7effb625f", "source_body_sha256": "2bd3c3d0f04b2df3cb049d3f27a910f75685850e45a20884584fdbf4bbb8efb9", "source_type": "abstract", "span": "abstract[401:640]|norm=exact", "start": 401}]}, "PMID:33722583:O2": {"pmid": "33722583", "primary": {"body_file": null, "body_sha256": null, "end": 1313, "pmcid": null, "pmid": "33722583", "quote_sha256": "4ac86a005ea480671beacd64eafe18aa59bea1b7c66a2b9869de81ff00509685", "source_body_sha256": "2bd3c3d0f04b2df3cb049d3f27a910f75685850e45a20884584fdbf4bbb8efb9", "source_type": "abstract", "span": "abstract[1080:1313]|norm=exact", "start": 1080}, "secondaries": []}, "PMID:33722583:O3": {"pmid": "33722583", "primary": {"body_file": null, "body_sha256": null, "end": 1641, "pmcid": null, "pmid": "33722583", "quote_sha256": "5254bb2bb2c1af0e8403d83ec49f1edeaedc63cac8d28012ecd91425693cc545", "source_body_sha256": "2bd3c3d0f04b2df3cb049d3f27a910f75685850e45a20884584fdbf4bbb8efb9", "source_type": "abstract", "span": "abstract[1314:1641]|norm=exact", "start": 1314}, "secondaries": []}, "PMID:34033222:O1": {"pmid": "34033222", "primary": {"body_file": null, "body_sha256": null, "end": 942, "pmcid": null, "pmid": "34033222", "quote_sha256": "1ff650d3f3042068342c679049a029055922349368d83a70bc87f1d32f93b80b", "source_body_sha256": "64aeb7c85b3e8979cc58bdbc3b7f510f23fe30fd6ca1bb9d48660fba2af5eb46", "source_type": "abstract", "span": "abstract[691:942]|norm=exact", "start": 691}, "secondaries": []}, "PMID:34033222:O2": {"pmid": "34033222", "primary": {"body_file": null, "body_sha256": null, "end": 1251, "pmcid": null, "pmid": "34033222", "quote_sha256": "10ca64785f68365e05a7410fe6e908428743f028182683346519afaf52e23481", "source_body_sha256": "64aeb7c85b3e8979cc58bdbc3b7f510f23fe30fd6ca1bb9d48660fba2af5eb46", "source_type": "abstract", "span": "abstract[943:1251]|norm=exact", "start": 943}, "secondaries": []}, "PMID:35046043:O1": {"pmid": "35046043", "primary": {"body_file": null, "body_sha256": null, "end": 976, "pmcid": null, "pmid": "35046043", "quote_sha256": "9b353fe049759be3d7ce5ee0fada4fafc17be9688e7767419aa1590f95e3715f", "source_body_sha256": "472f6fb75ac7814cc455d68e2326df3ebbf335513c67017c03b0ad020a61cdd2", "source_type": "abstract", "span": "abstract[318:976]|norm=exact", "start": 318}, "secondaries": []}, "PMID:35725270:O1": {"pmid": "35725270", "primary": {"body_file": null, "body_sha256": null, "end": 1518, "pmcid": null, "pmid": "35725270", "quote_sha256": "de99485accdf31df4f3180d7f53b5042e6267d4ac3d4ab5f2956d0af09fd108a", "source_body_sha256": "9ac1ff0e8b95486aa856bd5caac1d06acac5766aed9bc413dfd7ad3df9d889d4", "source_type": "abstract", "span": "abstract[1067:1518]|norm=exact", "start": 1067}, "secondaries": []}, "PMID:36560629:O1": {"pmid": "36560629", "primary": {"body_file": null, "body_sha256": null, "end": 1028, "pmcid": null, "pmid": "36560629", "quote_sha256": "a3d67d1e14c6b480c44e5b8f1c674ffb4f385b49e06c10e45dc5b85d58b03c90", "source_body_sha256": "4d7081db79676bc1c89c054211646fd6ebdd9113236be96452e0dd21cca86f17", "source_type": "abstract", "span": "abstract[301:1028]|norm=exact", "start": 301}, "secondaries": []}, "PMID:37106062:O1": {"pmid": "37106062", "primary": {"body_file": null, "body_sha256": null, "end": 920, "pmcid": null, "pmid": "37106062", "quote_sha256": "f48ddab246e9643d681d229b1b25cc667c10a041086d8f3835dd0bbbd14114c8", "source_body_sha256": "f699df188e4df51734a2f55d522d8cbff3dcd5800ff0e04350ef57fec03558c6", "source_type": "abstract", "span": "abstract[585:920]|norm=exact", "start": 585}, "secondaries": []}, "PMID:37106062:O2": {"pmid": "37106062", "primary": {"body_file": null, "body_sha256": null, "end": 1079, "pmcid": null, "pmid": "37106062", "quote_sha256": "125d2d6b2f752aad6ba7202e2a2739bd4cc7d7c17f91226583b851c6a931c81f", "source_body_sha256": "f699df188e4df51734a2f55d522d8cbff3dcd5800ff0e04350ef57fec03558c6", "source_type": "abstract", "span": "abstract[846:1079]|norm=exact", "start": 846}, "secondaries": []}, "PMID:37306457:O1": {"pmid": "37306457", "primary": {"body_file": null, "body_sha256": null, "end": 1434, "pmcid": null, "pmid": "37306457", "quote_sha256": "7d007e3a18adc0a9b8c2f1e1043d6a98cb233e6564a0eb621b3e8959d299a7b4", "source_body_sha256": "06e9129ade283e96eb85955e82ea73e917d4242f6a197320ebb16f5126e3c45a", "source_type": "abstract", "span": "abstract[547:1434]|norm=exact", "start": 547}, "secondaries": []}, "PMID:37679570:O1": {"pmid": "37679570", "primary": {"body_file": null, "body_sha256": null, "end": 954, "pmcid": null, "pmid": "37679570", "quote_sha256": "f363076f4ace5b9c94d1fc6bf0320342f5c31270d5327db596f0cb6b5942b73e", "source_body_sha256": "1fb939dbc08cd4eeca464056e186e67d75c988ca2918f476e8651f3b77a45c60", "source_type": "abstract", "span": "abstract[578:954]|norm=exact", "start": 578}, "secondaries": []}, "PMID:37679570:O2": {"pmid": "37679570", "primary": {"body_file": null, "body_sha256": null, "end": 954, "pmcid": null, "pmid": "37679570", "quote_sha256": "1d09186a7d7c126a1b8d6054b725048e03c8991ca3835b7c937b3ed198784dd1", "source_body_sha256": "1fb939dbc08cd4eeca464056e186e67d75c988ca2918f476e8651f3b77a45c60", "source_type": "abstract", "span": "abstract[224:954]|norm=exact", "start": 224}, "secondaries": []}, "PMID:38135691:O1": {"pmid": "38135691", "primary": {"body_file": null, "body_sha256": null, "end": 882, "pmcid": null, "pmid": "38135691", "quote_sha256": "c41e2889dda0cc85cbc9e511a6c4f30b56b528c1bc9f9358adcb57de371c9224", "source_body_sha256": "b67f5d169c630dc72ecab71ae70b83f968b23a53f1c08405cabd7577c941fa06", "source_type": "abstract", "span": "abstract[393:882]|norm=exact", "start": 393}, "secondaries": []}, "PMID:38135691:O2": {"pmid": "38135691", "primary": {"body_file": null, "body_sha256": null, "end": 1068, "pmcid": null, "pmid": "38135691", "quote_sha256": "f742c9989ad947edf4c5b79c3428c2bc9f52e02dbf55d8948a7448ac53d97567", "source_body_sha256": "b67f5d169c630dc72ecab71ae70b83f968b23a53f1c08405cabd7577c941fa06", "source_type": "abstract", "span": "abstract[883:1068]|norm=exact", "start": 883}, "secondaries": []}, "PMID:38768856:O1": {"pmid": "38768856", "primary": {"body_file": null, "body_sha256": null, "end": 1838, "pmcid": null, "pmid": "38768856", "quote_sha256": "fd76ce7c192ad71aab6028fabe4678f80a6d580355bb829cc81e3137ebc10509", "source_body_sha256": "1598da81c95e8c272a4d5126d44d60e80b9ef0a2a784800663f397591e468256", "source_type": "abstract", "span": "abstract[1362:1838]|norm=exact", "start": 1362}, "secondaries": []}, "PMID:38848367:O1": {"pmid": "38848367", "primary": {"body_file": "38848367_PMC11160476.txt", "body_sha256": "4f7371f41fb8741075f6c39e6102abd5522f0be97fa07e66e24a00308a060921", "end": 47472, "pmcid": "PMC11160476", "pmid": "38848367", "quote_sha256": "6bdab56d20cce848200f9d12be17d9fed9a8a25aa1dae8eace40196ea872211f", "source_body_sha256": null, "source_type": "fulltext_results", "span": "fulltext[45279:47472]|norm=exact", "start": 45279}, "secondaries": []}, "PMID:38848367:O2": {"pmid": "38848367", "primary": {"body_file": "38848367_PMC11160476.txt", "body_sha256": "4f7371f41fb8741075f6c39e6102abd5522f0be97fa07e66e24a00308a060921", "end": 47937, "pmcid": "PMC11160476", "pmid": "38848367", "quote_sha256": "c3ee411873d6f64c4e742c71c0ab2e8b9c9f378275d4dd58acdfde73b4d6a5b4", "source_body_sha256": null, "source_type": "fulltext_results", "span": "fulltext[47473:47937]|norm=exact", "start": 47473}, "secondaries": []}, "PMID:38848367:O3": {"pmid": "38848367", "primary": {"body_file": "38848367_PMC11160476.txt", "body_sha256": "4f7371f41fb8741075f6c39e6102abd5522f0be97fa07e66e24a00308a060921", "end": 43942, "pmcid": "PMC11160476", "pmid": "38848367", "quote_sha256": "63503c20ab408bbe7181faaa4cbd9eeac80aeb1662c225bccb78fb9386f3393e", "source_body_sha256": null, "source_type": "fulltext_results", "span": "fulltext[42453:43942]|norm=exact", "start": 42453}, "secondaries": []}, "PMID:38848367:O4": {"pmid": "38848367", "primary": {"body_file": null, "body_sha256": null, "end": 760, "pmcid": null, "pmid": "38848367", "quote_sha256": "6352f9a119be1e50f28a73dc018a666a571c11f73f6f45c17993a23a338f847e", "source_body_sha256": "69a30c7789d36ad22aafc0c542d17c54722ee3a065ca3544e0db26636b256cc0", "source_type": "abstract", "span": "abstract[580:760]|norm=exact", "start": 580}, "secondaries": []}, "PMID:39647511:O1": {"pmid": "39647511", "primary": {"body_file": null, "body_sha256": null, "end": 1169, "pmcid": null, "pmid": "39647511", "quote_sha256": "d021c2d67660b3b0b9cdc5724ab29541bf56e23b9d9ffe66faee08ffcc61c438", "source_body_sha256": "c0a7c027a1ccac75c05297be5f893824cac0f98d4fc6ec74037437be43a2990b", "source_type": "abstract", "span": "abstract[424:1169]|norm=exact", "start": 424}, "secondaries": []}, "PMID:39647511:O2": {"pmid": "39647511", "primary": {"body_file": null, "body_sha256": null, "end": 642, "pmcid": null, "pmid": "39647511", "quote_sha256": "72863d23c150377bbf1ab4ac49838a71f5876c0855f8201e602c22cad580d5db", "source_body_sha256": "c0a7c027a1ccac75c05297be5f893824cac0f98d4fc6ec74037437be43a2990b", "source_type": "abstract", "span": "abstract[424:642]|norm=exact", "start": 424}, "secondaries": []}, "PMID:39647511:O3": {"pmid": "39647511", "primary": {"body_file": null, "body_sha256": null, "end": 1276, "pmcid": null, "pmid": "39647511", "quote_sha256": "39ecbe9bdd760324b1f4c17ab2c1d3ce1cc8971b65bbffcaed9c4efdafcd7b04", "source_body_sha256": "c0a7c027a1ccac75c05297be5f893824cac0f98d4fc6ec74037437be43a2990b", "source_type": "abstract", "span": "abstract[1170:1276]|norm=exact", "start": 1170}, "secondaries": []}, "PMID:40066448:O1": {"pmid": "40066448", "primary": {"body_file": null, "body_sha256": null, "end": 1108, "pmcid": null, "pmid": "40066448", "quote_sha256": "d5e7d17d4d60aff26984ed99703fd8b206eb9f48c358c2ea37f43d7c35948c19", "source_body_sha256": "14d9046149806ec29f774a104e48a752a0b4c7f8bea89a3e0580b50985e1a102", "source_type": "abstract", "span": "abstract[446:1108]|norm=exact", "start": 446}, "secondaries": []}, "PMID:41118637:O1": {"pmid": "41118637", "primary": {"body_file": null, "body_sha256": null, "end": 896, "pmcid": null, "pmid": "41118637", "quote_sha256": "d90c06869c038c6ff71224bd4c169d3afadc4d08d5b78f72de7cd7143321bebc", "source_body_sha256": "cf0927c0f8712fb72a054ae41acb99967043805e56c2674a1da8fc7f1fe0c522", "source_type": "abstract", "span": "abstract[751:896]|norm=exact", "start": 751}, "secondaries": []}, "PMID:41118637:O2": {"pmid": "41118637", "primary": {"body_file": null, "body_sha256": null, "end": 1436, "pmcid": null, "pmid": "41118637", "quote_sha256": "a61ebac0ebb96c1f906c45c28f6c42e12a208128d44820bf4dda3c4de078c515", "source_body_sha256": "cf0927c0f8712fb72a054ae41acb99967043805e56c2674a1da8fc7f1fe0c522", "source_type": "abstract", "span": "abstract[1056:1436]|norm=exact", "start": 1056}, "secondaries": []}, "PMID:8384206:O1": {"pmid": "8384206", "primary": {"body_file": null, "body_sha256": null, "end": 1406, "pmcid": null, "pmid": "8384206", "quote_sha256": "8ebe8ed7c2993b50a63fdf0108d9d417443af213a4d0e4d0041642af7a73d0dd", "source_body_sha256": "05671d865f705eca1f6ceeac74e6b5a884467b6cf90c6fa307fdd7defca0a380", "source_type": "abstract", "span": "abstract[674:1406]|norm=exact", "start": 674}, "secondaries": []}}')
    _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']}")
        if _spec_w["source_type"] == "abstract":
            if _pin_w.get("body_file") is not None:
                raise ValueError(f"Wave-6 outcome {_oid_w} {_lbl_w} abstract pin must not set body_file")
            if _pin_w.get("source_body_sha256") != _spec_w["source_body_sha256"]:
                raise ValueError(f"Wave-6 outcome {_oid_w} {_lbl_w} source_body_sha256={_pin_w.get('source_body_sha256')!r} mismatches pinned {_spec_w['source_body_sha256']!r}")
            if _w6_sources_loaded:
                _ab_w = _w6_abs_live[_spec_w["pmid"]]
                if _pin_w.get("source_body_sha256") != _sha256_str(_ab_w):
                    raise ValueError(f"Wave-6 outcome {_oid_w} {_lbl_w} source_body_sha256 mismatch")
                _act_w = _sha256_str(_ab_w[_spec_w["start"]:_spec_w["end"]])
                if _sha_w != _act_w:
                    raise ValueError(f"Wave-6 outcome {_oid_w} {_lbl_w} quote_sha256={_sha_w} mismatches live abstract slice {_act_w}")
        else:
            if _pin_w.get("body_file") != _spec_w["body_file"] or _pin_w.get("pmcid") != _spec_w["pmcid"]:
                raise ValueError(f"Wave-6 outcome {_oid_w} {_lbl_w} body_file/pmcid mismatch")
            if _pin_w.get("body_sha256") != _spec_w["body_sha256"]:
                raise ValueError(f"Wave-6 outcome {_oid_w} {_lbl_w} body_sha256 mismatch")
            if _w6_sources_loaded:
                _ft_w = _w6_ft_live[_spec_w["pmid"]]
                _act_w = _sha256_str(_ft_w[_spec_w["start"]:_spec_w["end"]])
                if _sha_w != _act_w:
                    raise ValueError(f"Wave-6 outcome {_oid_w} {_lbl_w} quote_sha256={_sha_w} mismatches live fulltext slice {_act_w}")

    _w6_verified_prim_cnt = 0
    _w6_verified_sec_cnt = 0
    for _woid, _wspec in sorted(_w6_pin_specs.items()):
        _wo = outcomes.get(_woid)
        if not isinstance(_wo, dict):
            raise ValueError(f"Missing required Wave-6 outcome {_woid}")
        _check_w6_pin(_woid, _wo.get("source_pin") or {}, _wo.get("quote_sha256"), _wspec["primary"], "primary source_pin")
        _w6_verified_prim_cnt += 1
        _w_req_secs = _wspec["secondaries"]
        _w_got_secs = _wo.get("secondary_source_pins") or []
        if not isinstance(_w_got_secs, list) or len(_w_got_secs) != len(_w_req_secs):
            raise ValueError(f"Wave-6 outcome {_woid} secondary_source_pins count={len(_w_got_secs) if isinstance(_w_got_secs, list) else type(_w_got_secs).__name__} mismatches required {len(_w_req_secs)}")
        for _sidx, (_sobj, _sspec) in enumerate(zip(_w_got_secs, _w_req_secs)):
            _check_w6_pin(_woid, _sobj, _sobj.get("quote_sha256") if isinstance(_sobj, dict) else None, _sspec, f"secondary_source_pins[{_sidx}]")
            _w6_verified_sec_cnt += 1
    if _w6_verified_prim_cnt != 46 or _w6_verified_sec_cnt != 9:
        raise ValueError(f"Wave-6 span count mismatch: primary={_w6_verified_prim_cnt}, secondary={_w6_verified_sec_cnt}")

    # Audit R6-01 & Audit R7-01: Complete canonical semantic-claim digest validation for ALL 25 Wave-6 studies,
    # ALL 61 Wave-6 arms, ALL 46 Wave-6 outcomes, and ALL 32 Wave-6 edges in BOTH structural
    # (require_sources=False) AND source-backed (require_sources=True) modes BEFORE returning any receipt!
    _w6_study_sem_digests = json.loads('{"PMID:1334978": {"materialized_sha256": "9c1066e254716db374627dfa342602167d799b31a485c4cf13e2406f1dab63ce", "raw_sha256": "d02fb0248e2daa1c20c2b17b14cfe7586d0e3d8fd22e23f1eff2d97540586376"}, "PMID:17130499": {"materialized_sha256": "ccc6ac81dc03142c626a0852a323a346f3ad4b7a93fafd2d9398c703f4c8ef2b", "raw_sha256": "66ddeb50ff8c18baaaac2547ac3612c3938b960139acb3efe17765843768b8db"}, "PMID:17503968": {"materialized_sha256": "f385f65aa34d7c54c66165c5d95fd4ec6a20986c83dab93f2e19d7116a84aa22", "raw_sha256": "7c93b6dfd612874e87d91567f5a09f1af9364641996eb6360e34d8f83ca642ef"}, "PMID:21912932": {"materialized_sha256": "630a192680ac2ec2af50b6f18fac728749773444392625374adfbccff6a75ccf", "raw_sha256": "901e5c58e388d52056d0247502cbfe390fb443e707f904c1ec5c17cb55bc9132"}, "PMID:22315720": {"materialized_sha256": "ce2f1aceffc58ebdbfb795444783d2413b4ad1a22c233d12777a0bf8dc88215c", "raw_sha256": "e79513940edc1459151a7363f9b460d342feeef899feb9308680a3cc6e379807"}, "PMID:23572523": {"materialized_sha256": "1b2adf8f6f315f93ffe5a478cc9d04c9bdc0efd874a0479373af764812f4fb4f", "raw_sha256": "7cf423deb2f49c233e8d4b8d9203813a0876cec0a6ba9073067169f5def31d2b"}, "PMID:23616575": {"materialized_sha256": "205d5fd43aca3066b1af6fc4bddda27874fab28415db23aa75df9e8f6fced544", "raw_sha256": "0c3d40ac4aa4fb862c4ab132af4ba5905a265acc98ba3d2d0b258027a6f7b95f"}, "PMID:23935835": {"materialized_sha256": "272e32dc8601c31468f39dfbfa760b411604f2e464cce580ec5b12a0b8cb1716", "raw_sha256": "25ed11de01f56ec5a99363926437f2efbf69b76cceaaa03c1dce98aa371a6878"}, "PMID:30449685": {"materialized_sha256": "251e1a567213b9f46580671a6b9c3671cd568d2e802079748c3cd6dd673f3a1d", "raw_sha256": "3cf011e1f9c625daf086ddc01d9e5e611ac6c3335ac1b21e85d7ed148abe2390"}, "PMID:32433410": {"materialized_sha256": "aed5630abe0a315f2df2f36740c17ce97a9f6b1b959ac6cc0682c8d753a7870f", "raw_sha256": "0b468b0f2ec3b623af633c8853d1353fcc7b9f732b22ec94fc622add8a5584df"}, "PMID:33722583": {"materialized_sha256": "b3758d3fc560296b8796940021bac289723662413d6eaf72f39f1b07bdee20ee", "raw_sha256": "ce6c6c998b07064367637593ec6d29c8a782b283f3e65db533dc54696d816486"}, "PMID:34033222": {"materialized_sha256": "652a728d8ac3357b11216e8dd6f5493e96813a97a524212691c51facf7c7aa6b", "raw_sha256": "162cba7a1d36d56f9fee83e3ee4ba9c2b6278ffaa104ec82ab9441e6c0ae4014"}, "PMID:35046043": {"materialized_sha256": "d90d2e562452ee1d24ae05b48cdcaf4abdba1ffe96280ebcfcdee580ad8fd2e7", "raw_sha256": "928537acfa8170c7cb9d50562f448fc4c2b547facf5b91c66f8f464b00cfddae"}, "PMID:35725270": {"materialized_sha256": "154bc5a6ecd30fbcdabfb1ca53dde823e0a3a20504128b8d8ec0f5ea08306d6e", "raw_sha256": "5231b4e1cbca39f502aa4c37357b84fca27a6c47ece3a5d40f19d97c898a6a86"}, "PMID:36560629": {"materialized_sha256": "b30f3a6294869abfcb8ad666384df0b4c9f763a90f3a9ba13c89edaf403cc192", "raw_sha256": "f0c697c561a8c352a8317e7f165f24a11540b9b441b4db3dc60d90eb03b43bd3"}, "PMID:37106062": {"materialized_sha256": "e27694b11e637fa82a4531581cc07a122c41c8d5e4a5e90e5c9146e978170e61", "raw_sha256": "6c5719d46e0d5eec5692aa36f31e10124234f0fecf96b2668becc0966ce3cf3a"}, "PMID:37306457": {"materialized_sha256": "703180d5b13d2a4e982492c1485cd7a7bd2af5770abd223c1a6da322cf6fe2f0", "raw_sha256": "53868b678d640fee0275782b7e7000308b79b4c916d556e69d06c132ea2c3c11"}, "PMID:37679570": {"materialized_sha256": "41ed9b5c9812dd865be0246ed85b9e8c929f8d946002f2641eca74385ae845f9", "raw_sha256": "aa9cf320bc4b671f7fb9e4778f7f61e44f7dbc6ad21d11af53f7aacb52b1caa8"}, "PMID:38135691": {"materialized_sha256": "0495775d19227826b70d203b25a3ac6d8fe49f3d48f939a2c977da6bb5c5edb4", "raw_sha256": "b1cb648fe33ae6351d25b4a1003210984fdea79939a541e1ed8febf730dc601e"}, "PMID:38768856": {"materialized_sha256": "d1a08c16bfe2772ae3262ae4a9ec27b0dc571f3acd0d1480c8e1173dbd2d518c", "raw_sha256": "70458024db33cbfd0dc4c5963fa87f6b74e04d55877d95bd1240d9ffc135714a"}, "PMID:38848367": {"materialized_sha256": "98708904395a67a2351c46572eb71b671542a3fb7aa0c0ba52d8e35c94066905", "raw_sha256": "ad9b05db87ebef742ed9f652875cf09d5a1ac45a801591df4da062aee11978e6"}, "PMID:39647511": {"materialized_sha256": "df8e0d89de3eb7496dadcbdff0fc25d45e207d1cfb331376fc4f175b760a9769", "raw_sha256": "2368cceb3875601cb9c3cc85765760ec75c6a636bff420ddf93ae6195132a515"}, "PMID:40066448": {"materialized_sha256": "1b6b2e6c5e21a8a028100482cd2933be43d2506284943e7debc02bcf418224bd", "raw_sha256": "74f0c3c0c5840d287ba6cb8ed2386c2cd13201a73a0f4b57c45aed1879e40a9f"}, "PMID:41118637": {"materialized_sha256": "7418decd56df55b92995351e488b8e1c65601837527b15282207922c048b3a7e", "raw_sha256": "ef4902e04ac86fbb74b695493366c79360ba67fe390e03341ff3f5427af1cf5b"}, "PMID:8384206": {"materialized_sha256": "5ff77691f6e6dc4afe863e0fbc582fcbec3c0ef39ff2fc593018503c0c74c5bb", "raw_sha256": "13c14db277d1af6f14da16e592f7cbd54f21404514fc72aa085fd14040124b04"}}')
    _w6_arm_sem_digests = json.loads('{"VAR:PMID:1334978:A0_thbd_wt_oxidants": {"materialized_sha256": "d4a212b5350042657098e12e630e24388e4e9b1eed093a606ea0a2c58177f14d", "raw_sha256": "d4a212b5350042657098e12e630e24388e4e9b1eed093a606ea0a2c58177f14d"}, "VAR:PMID:1334978:A1_thbd_met388_mutant_oxidants": {"materialized_sha256": "7b37a22982419af9cd3c99b50920a84c928ba8a146ed418f36d78c0eeb19b3b2", "raw_sha256": "7b37a22982419af9cd3c99b50920a84c928ba8a146ed418f36d78c0eeb19b3b2"}, "VAR:PMID:17130499:A0_rat_islets_glucose_20mM_ctrl": {"materialized_sha256": "59c5f0ac90a014d7b121a5ce002acfbdb61cce80d7e3f3d918fe2b9f12b16027", "raw_sha256": "59c5f0ac90a014d7b121a5ce002acfbdb61cce80d7e3f3d918fe2b9f12b16027"}, "VAR:PMID:17130499:A1_rat_islets_ca_blockers": {"materialized_sha256": "714074aaee774f69d1abf3afaa95995bfaa071995ea85d08049de4cb678bcc9f", "raw_sha256": "714074aaee774f69d1abf3afaa95995bfaa071995ea85d08049de4cb678bcc9f"}, "VAR:PMID:17503968:A0_human_islets_glucose_ctrl": {"materialized_sha256": "910022b03a3e268f49dc042908b8833e66daa42c3de6ceb2d2be6a9c5e5cc409", "raw_sha256": "910022b03a3e268f49dc042908b8833e66daa42c3de6ceb2d2be6a9c5e5cc409"}, "VAR:PMID:17503968:A1_human_islets_dz_secretion_fig5": {"materialized_sha256": "1fb8bf5f84bcd2f792ed46ae0c6d2a0597d46ec349bccaa59ed31d4f02e6ffc8", "raw_sha256": "1fb8bf5f84bcd2f792ed46ae0c6d2a0597d46ec349bccaa59ed31d4f02e6ffc8"}, "VAR:PMID:17503968:A2_human_islets_dz_ca2_fig6": {"materialized_sha256": "22e186a70c23ea989e826206f26134bb8e50d9e3f932562783e3d97b4e898a68", "raw_sha256": "22e186a70c23ea989e826206f26134bb8e50d9e3f932562783e3d97b4e898a68"}, "VAR:PMID:17503968:A3_rodent_islets_channel_blockers": {"materialized_sha256": "6670bb04022c43d827b2c4f5e07e796417b5172d6fb27706b03e8b0166e08cf5", "raw_sha256": "6670bb04022c43d827b2c4f5e07e796417b5172d6fb27706b03e8b0166e08cf5"}, "VAR:PMID:21912932:A1_human_t1d_hla_epidemiology_review": {"materialized_sha256": "f45ad666ca6cc01d3373971c4704405f1d7e51f3d1a23e74645016aaac26910c", "raw_sha256": "f45ad666ca6cc01d3373971c4704405f1d7e51f3d1a23e74645016aaac26910c"}, "VAR:PMID:22315720:A1_human_t1d_gwas_review": {"materialized_sha256": "258ad081188eb66cec4b1efdf5dd3089f81d5c2e02008edb4c2f2128b976978e", "raw_sha256": "258ad081188eb66cec4b1efdf5dd3089f81d5c2e02008edb4c2f2128b976978e"}, "VAR:PMID:23572523:A0_wt_casp9_apaf1": {"materialized_sha256": "dd727daa03d6edc7191621725e64b2861ef02be6e7f84ef6065ca94a6c2a2405", "raw_sha256": "dd727daa03d6edc7191621725e64b2861ef02be6e7f84ef6065ca94a6c2a2405"}, "VAR:PMID:23572523:A1_casp9_tm_apaf1": {"materialized_sha256": "dfb49dd74fd8782c086d1f44c664e7d89c05e0de7e67e608b09d19737be6e79b", "raw_sha256": "dfb49dd74fd8782c086d1f44c664e7d89c05e0de7e67e608b09d19737be6e79b"}, "VAR:PMID:23616575:A0_full_length_fh_ctrl": {"materialized_sha256": "3034397fb72b7c97703ff989fef87156eafbf7f09a054791305c4cb2f30f6274", "raw_sha256": "3034397fb72b7c97703ff989fef87156eafbf7f09a054791305c4cb2f30f6274"}, "VAR:PMID:23616575:A1_soluble_minifh_ap_elisa": {"materialized_sha256": "2a51282c7b0284f06308f6192fc79dabc0f34c4be731c1acbd6063cf2c32fc66", "raw_sha256": "2a51282c7b0284f06308f6192fc79dabc0f34c4be731c1acbd6063cf2c32fc66"}, "VAR:PMID:23616575:A2_soluble_minifh_pnh_rbc": {"materialized_sha256": "d2c6e211e920e8ccb0a6ac2a4d7d2c40383ce2783772dfe0e53a207bc5e84049", "raw_sha256": "d2c6e211e920e8ccb0a6ac2a4d7d2c40383ce2783772dfe0e53a207bc5e84049"}, "VAR:PMID:23935835:A0_rat_vehicle_ctrl": {"materialized_sha256": "78a19d7acb686ef9fe92e77a0e69a905caab15080bc566ce69b4ed8abe82bd9d", "raw_sha256": "78a19d7acb686ef9fe92e77a0e69a905caab15080bc566ce69b4ed8abe82bd9d"}, "VAR:PMID:23935835:A1_rat_22h_dz_325uM": {"materialized_sha256": "f7d7656c56b4305c0621f0a3e78d12804732939f846e3ae1d2a7807c20eb5326", "raw_sha256": "f7d7656c56b4305c0621f0a3e78d12804732939f846e3ae1d2a7807c20eb5326"}, "VAR:PMID:23935835:A2_human_pilot_22h_dz_325uM": {"materialized_sha256": "abb9c560d49ce2a73f0f129ff1eed41c882abed5e2caae0e8bca13f22f7b3eda", "raw_sha256": "abb9c560d49ce2a73f0f129ff1eed41c882abed5e2caae0e8bca13f22f7b3eda"}, "VAR:PMID:23935835:A3_human_pilot_vehicle_ctrl": {"materialized_sha256": "8bf6c2505eb85f3b2b0b2cf0cfbb20b22817d28ed04d255425f7ba82ba34a5ab", "raw_sha256": "8bf6c2505eb85f3b2b0b2cf0cfbb20b22817d28ed04d255425f7ba82ba34a5ab"}, "VAR:PMID:23935835:A4_human_48h_dz_325uM_xenograft": {"materialized_sha256": "11543b292527145bc56471ea8ba4042a4badf62898917c37162a86638c191e05", "raw_sha256": "11543b292527145bc56471ea8ba4042a4badf62898917c37162a86638c191e05"}, "VAR:PMID:23935835:A5_human_48h_naoh_ctrl_xenograft": {"materialized_sha256": "e93741ad7da9037fda720adca538deae46aec13e49dc9cbc31242d968dee3319", "raw_sha256": "e93741ad7da9037fda720adca538deae46aec13e49dc9cbc31242d968dee3319"}, "VAR:PMID:30449685:A1_human_adult_islets_ntpdase3": {"materialized_sha256": "8ddf3f8d4e674c85d9762ca69a01f3fde555e2dc0b616fd028ff80cda5f3961b", "raw_sha256": "8ddf3f8d4e674c85d9762ca69a01f3fde555e2dc0b616fd028ff80cda5f3961b"}, "VAR:PMID:30449685:A2_human_islets_mouse_imaging": {"materialized_sha256": "f940eca4503947bfa7ce639aa1d82d84831412daca77aeb505117576e40cfd77", "raw_sha256": "f940eca4503947bfa7ce639aa1d82d84831412daca77aeb505117576e40cfd77"}, "VAR:PMID:32433410:A0_nhp_pancreas_uw_ctrl_8h": {"materialized_sha256": "3c32401aa7405caa6c864035f2dfa3336a460ac118d80c19631ff03aec64aed7", "raw_sha256": "3c32401aa7405caa6c864035f2dfa3336a460ac118d80c19631ff03aec64aed7"}, "VAR:PMID:32433410:A1_nhp_pancreas_uw_150uM_dz_8h": {"materialized_sha256": "f053c48cf6d459bdd7e7f5b0a1f15e52ef1d418f571e0b9be8d2de621f1d101a", "raw_sha256": "f053c48cf6d459bdd7e7f5b0a1f15e52ef1d418f571e0b9be8d2de621f1d101a"}, "VAR:PMID:32433410:A2_diabetic_mouse_dz_nhp_graft": {"materialized_sha256": "fb53596ef9048296d90ad1047f857efd59c7b44e6b99a19e25299f5471f35f8c", "raw_sha256": "fb53596ef9048296d90ad1047f857efd59c7b44e6b99a19e25299f5471f35f8c"}, "VAR:PMID:32433410:A3_diabetic_mouse_uw_ctrl_graft": {"materialized_sha256": "83154b534a5df0947dca4d45ef17c0a8c5ae7d92390ae377830a685978952bf5", "raw_sha256": "83154b534a5df0947dca4d45ef17c0a8c5ae7d92390ae377830a685978952bf5"}, "VAR:PMID:33722583:A0_celiac_placebo_iv": {"materialized_sha256": "f11c7e8f592d77b1bffa2c3d56cb336003805aa09aba0fcae7a9afe93d149d74", "raw_sha256": "f11c7e8f592d77b1bffa2c3d56cb336003805aa09aba0fcae7a9afe93d149d74"}, "VAR:PMID:33722583:A1_celiac_tak101_iv": {"materialized_sha256": "3e3c1e2dd01bf585dd485e712b9b7ae3f7b4e0cee2c0e7e481134be9c1076d20", "raw_sha256": "3e3c1e2dd01bf585dd485e712b9b7ae3f7b4e0cee2c0e7e481134be9c1076d20"}, "VAR:PMID:34033222:A0_tpiat_placebo_7d": {"materialized_sha256": "d5fc9530050e5eb8f97a02462fc00545cbe873a23d5da4fc3663afd316566ca1", "raw_sha256": "d5fc9530050e5eb8f97a02462fc00545cbe873a23d5da4fc3663afd316566ca1"}, "VAR:PMID:34033222:A1_tpiat_reparixin_7d": {"materialized_sha256": "56e39764a9538d1d26137823b30508fbb4a3f0472b879daa1c705f9990578cfd", "raw_sha256": "56e39764a9538d1d26137823b30508fbb4a3f0472b879daa1c705f9990578cfd"}, "VAR:PMID:35046043:A0_cvb3_cd55_nonbinding_isolates": {"materialized_sha256": "60470cf5d8bb2f58bb51c5b963aa775f4ec8801010ea3eeb565720ddde9b0c20", "raw_sha256": "60470cf5d8bb2f58bb51c5b963aa775f4ec8801010ea3eeb565720ddde9b0c20"}, "VAR:PMID:35046043:A1_cvb3_cd55_binding_isolates": {"materialized_sha256": "fba29413bcc9f66c741d88799cad45d8efc7fc94853c25f5d1bb5c87c4b2d924", "raw_sha256": "fba29413bcc9f66c741d88799cad45d8efc7fc94853c25f5d1bb5c87c4b2d924"}, "VAR:PMID:35725270:A0_nod_single_antigen_cnp": {"materialized_sha256": "25f56b82e8d3b47fa025dd6ba3cde1f89942303532ab8f2e08a1bae1adc7c08d", "raw_sha256": "25f56b82e8d3b47fa025dd6ba3cde1f89942303532ab8f2e08a1bae1adc7c08d"}, "VAR:PMID:35725270:A1_nod_cnp_t1d_3protein": {"materialized_sha256": "cbb093f58c36135215dd3153c82316eebe03a01f8c8a2dc500700e4d58af03a7", "raw_sha256": "cbb093f58c36135215dd3153c82316eebe03a01f8c8a2dc500700e4d58af03a7"}, "VAR:PMID:36560629:A0_e6_cd55_pose_comparator": {"materialized_sha256": "5e57b1c1a242bed3867685529bfd42c179b34f0442f34d4a7eed59071c82bfa3", "raw_sha256": "5e57b1c1a242bed3867685529bfd42c179b34f0442f34d4a7eed59071c82bfa3"}, "VAR:PMID:36560629:A1_e11_cd55_scr1_4": {"materialized_sha256": "7edc400b6398fe8a615ef71e981017fd3b113d7201a586cc84df62ab2c16f44a", "raw_sha256": "7edc400b6398fe8a615ef71e981017fd3b113d7201a586cc84df62ab2c16f44a"}, "VAR:PMID:37106062:A1_human_gastric_gins_in_vitro": {"materialized_sha256": "96dcf1b9f114cf4dec8638deb2cae467b09557f01291196131d6b96aa13eccaf", "raw_sha256": "96dcf1b9f114cf4dec8638deb2cae467b09557f01291196131d6b96aa13eccaf"}, "VAR:PMID:37106062:A2_gins_diabetic_mouse_xenograft": {"materialized_sha256": "029bd6d285597a81245147a00a2d9fd1e2d6355898b1dcb0c56f2c2a81f73840", "raw_sha256": "029bd6d285597a81245147a00a2d9fd1e2d6355898b1dcb0c56f2c2a81f73840"}, "VAR:PMID:37306457:A0_mouse_lip_c3_cd11b_dko": {"materialized_sha256": "ac4fe0a0bc41554eb0b91df7a9771e47680aab469572b45ae85f10053e0e9f37", "raw_sha256": "ac4fe0a0bc41554eb0b91df7a9771e47680aab469572b45ae85f10053e0e9f37"}, "VAR:PMID:37306457:A1_mouse_lip_minifh_or_fh19_20": {"materialized_sha256": "3092f61f38406182c510f59ff028d6b25e221c5320535939979a3792f888fcd1", "raw_sha256": "3092f61f38406182c510f59ff028d6b25e221c5320535939979a3792f888fcd1"}, "VAR:PMID:37679570:A1_nhp_pgal_siv_vax": {"materialized_sha256": "9269a8254406dabb07a835b3e185ac44684f364f3947a998e5e2d4d79f84d98b", "raw_sha256": "9269a8254406dabb07a835b3e185ac44684f364f3947a998e5e2d4d79f84d98b"}, "VAR:PMID:37679570:A2_mouse_eae_pgal": {"materialized_sha256": "a08297bfa19c9ab5963968a07b1126684a8f24124492f2b84a8d1bd0b3f6a8db", "raw_sha256": "a08297bfa19c9ab5963968a07b1126684a8f24124492f2b84a8d1bd0b3f6a8db"}, "VAR:PMID:38135691:A1_donq52_gluten_phla_in_vitro": {"materialized_sha256": "73acb4075d031eb866e4db0b13ab6ff0632f0b943825d09ff17095ad38d84baf", "raw_sha256": "73acb4075d031eb866e4db0b13ab6ff0632f0b943825d09ff17095ad38d84baf"}, "VAR:PMID:38135691:A2_dq25_tg_mouse_donq52_sc": {"materialized_sha256": "97dc671068b1385511290d9b4753042488c5bf983c54041faaf175f15e384b6f", "raw_sha256": "97dc671068b1385511290d9b4753042488c5bf983c54041faaf175f15e384b6f"}, "VAR:PMID:38768856:A0_celiac_pbmc_spvl3_ctrl": {"materialized_sha256": "7b52c7133ef92b805debd0908764522d118ccb3db8fa404f08bd17d6601f1bed", "raw_sha256": "7b52c7133ef92b805debd0908764522d118ccb3db8fa404f08bd17d6601f1bed"}, "VAR:PMID:38768856:A1_celiac_pbmc_donq52": {"materialized_sha256": "e47ba69a517b381d4b5f6450c227f547728d461732fd71f140082b0f78da88b5", "raw_sha256": "e47ba69a517b381d4b5f6450c227f547728d461732fd71f140082b0f78da88b5"}, "VAR:PMID:38848367:A0_oxidative_islets_plasma_thrombin": {"materialized_sha256": "85c6e011e1b63386eb63cae888df042432e440295e55d0a8f8628a8b5afcd0e9", "raw_sha256": "85c6e011e1b63386eb63cae888df042432e440295e55d0a8f8628a8b5afcd0e9"}, "VAR:PMID:38848367:A1_nhp_omentum_ppcn_autograft": {"materialized_sha256": "b78b535202b119a177e0dd2d888b5cb07f32452fe60a02cd82823bc287ca2e8e", "raw_sha256": "b78b535202b119a177e0dd2d888b5cb07f32452fe60a02cd82823bc287ca2e8e"}, "VAR:PMID:38848367:A2_nhp_omentum_ppcn_scaffold_only": {"materialized_sha256": "df3ca53de5d3074e3578c559fe2b6be57221c88a2fd84b10ceb04a2f12d37036", "raw_sha256": "df3ca53de5d3074e3578c559fe2b6be57221c88a2fd84b10ceb04a2f12d37036"}, "VAR:PMID:38848367:A3_oxidative_islets_ppcn": {"materialized_sha256": "2d1c859baacc6e31afa25e60fa80b7b79b77fe51eaa5defe21e2588bf504a56f", "raw_sha256": "2d1c859baacc6e31afa25e60fa80b7b79b77fe51eaa5defe21e2588bf504a56f"}, "VAR:PMID:39647511:A1_nhp_csl040_iv_500mgkg": {"materialized_sha256": "7a0da171a9e3722d2af1529a11cd9eaebf94815f90c0812ca59ea837d5ac1fa5", "raw_sha256": "7a0da171a9e3722d2af1529a11cd9eaebf94815f90c0812ca59ea837d5ac1fa5"}, "VAR:PMID:39647511:A2_rat_csl040_iv_500mgkg": {"materialized_sha256": "67610edec7431e9ff4e03002d925e48f94e4650c034a8691034e06bbbd05f7d5", "raw_sha256": "67610edec7431e9ff4e03002d925e48f94e4650c034a8691034e06bbbd05f7d5"}, "VAR:PMID:39647511:A3_human_in_vitro_cra": {"materialized_sha256": "ba9967508b50e3a427188ce71d04ec2bd6f1d8fabd23d9c78cd117a65ac3ac19", "raw_sha256": "ba9967508b50e3a427188ce71d04ec2bd6f1d8fabd23d9c78cd117a65ac3ac19"}, "VAR:PMID:40066448:A0_mouse_cns_blimp1_il10_ko": {"materialized_sha256": "975d2d54b28df0c1fb86c1e61bc224c19438b0eed8de133cb9f55431b1743ba2", "raw_sha256": "975d2d54b28df0c1fb86c1e61bc224c19438b0eed8de133cb9f55431b1743ba2"}, "VAR:PMID:40066448:A1_mouse_cns_pmhcii_np_withdrawal": {"materialized_sha256": "5b9c144a76b5d66eb9bc76aedb47da9101aab312deae4e5d991aab34bc6aadeb", "raw_sha256": "5b9c144a76b5d66eb9bc76aedb47da9101aab312deae4e5d991aab34bc6aadeb"}, "VAR:PMID:41118637:A0_nod_wt_ctrl": {"materialized_sha256": "78ec8e76b7ed942fc82e68f91769b3d944f5752920727fb42e579c356f718166", "raw_sha256": "78ec8e76b7ed942fc82e68f91769b3d944f5752920727fb42e579c356f718166"}, "VAR:PMID:41118637:A1_human_cpep_l_to_i_catd": {"materialized_sha256": "217071acd2819c8009acd4ee9667fa31b2e4fcd70003d238dd4db1b53016c094", "raw_sha256": "217071acd2819c8009acd4ee9667fa31b2e4fcd70003d238dd4db1b53016c094"}, "VAR:PMID:41118637:A2_nod_ins2_i_i_ki": {"materialized_sha256": "be536993e18dbc360d78a5001ba88973cb8f584dee50a42f4ef8578f540f4afd", "raw_sha256": "be536993e18dbc360d78a5001ba88973cb8f584dee50a42f4ef8578f540f4afd"}, "VAR:PMID:8384206:A0_thbd_wt_and_other_loop_mutants": {"materialized_sha256": "fc1d70f1efd9e3566acacc20b4733e3bbbebb61c191706a9be4159a172b38eea", "raw_sha256": "fc1d70f1efd9e3566acacc20b4733e3bbbebb61c191706a9be4159a172b38eea"}, "VAR:PMID:8384206:A1_thbd_met388leu_kinetics": {"materialized_sha256": "97cf59edb3d6d23f6be88b7b3addc5b1c09e9c8535b0348aa1308ccf82bbdc5b", "raw_sha256": "97cf59edb3d6d23f6be88b7b3addc5b1c09e9c8535b0348aa1308ccf82bbdc5b"}}')
    _w6_out_sem_digests = json.loads('{"PMID:1334978:O1": "50258124a15586f79e1aad13f17b0cdeb018057669b74b8825a3227d4542dadc", "PMID:17130499:O1": "8d7897b49299710834d5c4c71c1ec4db5f7763f0d9f4c0e009ba1855c19a368c", "PMID:17503968:O1": "d903c886f1f388e5ca5d03a413a7f021b0bec257ef27a7e45cb4ed2f774fb4a9", "PMID:17503968:O2": "28b506bef183a1de3037b09bb23536ca9c4b857a37b78160c8e16bb2c4468db6", "PMID:17503968:O3": "b112d29e02e4864044316f121f28bc754a07b86ddf78a386d42bf98fcc07479a", "PMID:21912932:O1": "bd90353ba8f242efebfb694081ab7c7c16c8b8057768b9b5181637587b5444e9", "PMID:22315720:O1": "b3e808d870cd8dc2e2fcd8ad3de53a83ea3b1ea2c9d58e6494e39c75e3f2c2fc", "PMID:23572523:O1": "115fa79e0db8ce9ce423bb5bf949e7096fd4266410191697021761b917ecb0a1", "PMID:23572523:O2": "7944f79f5e3d2d9a9c5ffa0ac2bd3d66d1a18a200fdc73c1d4d0b410b4351907", "PMID:23616575:O1": "46fa3d3d2e7d4c36e5e539d46075fb5b3ca05bdfea6567def87b0e438c6db4f6", "PMID:23616575:O2": "245e2eca149b0cf7c9fac3e7e0fab2250b96be10fdc4edbb81163acc21d8b1ce", "PMID:23935835:O1": "3053b67397bc47bbe1e05402c13e3f3d594deb483badbf8173c9aba767d8f796", "PMID:23935835:O2": "616b3c769624cfe2a759de35bca058e420d026b5b9796a5e9c670f17186f9d60", "PMID:23935835:O3": "248e52bce9c45278edf43ce633295d2f4f33c6ecd769e4ebead9dcb09991b73a", "PMID:23935835:O4": "e46cbc853ef6be48df212412448806d6560c2bc6accde78c1df9846c6309114c", "PMID:30449685:O1": "f19fa437d88f4b624a117bc9bc61c0312e8b07bed5fd5907f1855c546e0ae0c4", "PMID:30449685:O2": "e0f962557e974a95a1e930d6512c1f1c180f7b2f054b7ba01e3a3ec76ef9cbd5", "PMID:32433410:O1": "3e2e22387535dccf9cfd04c14fc7e772b933b966e502e6fdaac082cc80dba3c5", "PMID:32433410:O2": "7b1c52e138446987d60e85c1b97681a76e5c1f72a8dbc53bbd8316b731d9a02c", "PMID:33722583:O1": "9447e1c1282559ea75b8f7226160ef42a9e85655a12133cf92dec83d7b09cee2", "PMID:33722583:O2": "ca0450fddf7eb36e98718bdc3301f63866b4a989df46a926e1f62412aec50afe", "PMID:33722583:O3": "60f4c0b3a9627f159504e92959a3a3f6e227ebf31b44033af39ac556717a0ede", "PMID:34033222:O1": "6183496d289f9703b6f9df65986f861122b655eb2eb07509659b4682953b9de8", "PMID:34033222:O2": "7bf098f8a8e09bc92417d490b99637cdad34104c469842002bef18bc11d34c6f", "PMID:35046043:O1": "d3cbfa6cacbb4a6fe19b704280044105bd6f5358f8f1e4b3ea5cea478512c9da", "PMID:35725270:O1": "c9052c6cf3e1f329fe9313c388aab7e3bf3b3af62d47f9686f82a34af1a57233", "PMID:36560629:O1": "419775f153bb06a412dad66664e301af77c22195d71c7b427ac0246d94cfd478", "PMID:37106062:O1": "91e430c714e2a86d56d0bb1f3c0f4336fffa8af9e8e46c958d8e8ea52d00097f", "PMID:37106062:O2": "691eefac1b799179da10575992f9b2241fc1641b324b643f4145ec8fca178f82", "PMID:37306457:O1": "38468a1bf5450da2b07b3969adf5d3a0b1cd0da405824ed83567a5460b222bb2", "PMID:37679570:O1": "401f5d1a840892ea1652cf738f25f2ec30118d457e6e8e020eb5e46b73660dfd", "PMID:37679570:O2": "656632d68f9aaeda11aecced771c80ca6356c4a10fd34e81f8c60777e6262749", "PMID:38135691:O1": "e91606bfaf839c53a3a9f240a49055e574b33cc50b8ba57bf2f07da0b440bad7", "PMID:38135691:O2": "f5f5f75b065bac96fa5f2c4fc8c6c2e0a8a90ca9582b3563930a3b8eb9ef0c9d", "PMID:38768856:O1": "ff98ac86a9b8d7da7de13bd4fddc85eac09367a64d907e97e80daf1c210eca76", "PMID:38848367:O1": "984524b01b61d921eacc924d5e05003bd6c5330eb32815f1a929127052b9c408", "PMID:38848367:O2": "301f1a9effcfda7b40a41e1f3bf7c12f5e9fa4de237a4acf8e3dcc13b84078f2", "PMID:38848367:O3": "8a80f8e6e1344f3314a20e7909b4256b159554c22d93a9cab1a9971171997415", "PMID:38848367:O4": "007d5c29bcde85baf31016e3b1c140a11b3aba8fe0852cc363300374c3197ceb", "PMID:39647511:O1": "2c27acdeb12e6c64b0e600f7524e14208bb651004b73899999fb55ed0d24a2f6", "PMID:39647511:O2": "9f19df651c6835bee6febf71a9f13a87f40d92e8b031357a130c55d38d905540", "PMID:39647511:O3": "e82657d242917d05b60df0589ff6c25bc1f4c87d80ab14bfd7470b5176ed08be", "PMID:40066448:O1": "b166cae46ab0b32dc23ba413742badb564bc21de8e0289b11a0708b164dd2ab4", "PMID:41118637:O1": "387349620a0fd29e55b6b8ebcaf43844e397cf64f82afc9fc4bf7c68a75545db", "PMID:41118637:O2": "0623840c8ebda6cad2060f393183b4e88333e7a6a17ba3f65ea1b2e7274ac0dc", "PMID:8384206:O1": "b5a90581225ca1a62fd400b4af5dbb3d6a15ff2b07052ca97a37a5a65b67dd42"}')
    _w6_edge_sem_digests = json.loads('{"PMID:1334978:L1": {"materialized_sha256": "ba77d6f37e4a05cee55b9f2dd59522a20fe1fb5a99d7d31f2c50aaaa6daa1bbc", "raw_sha256": "ba77d6f37e4a05cee55b9f2dd59522a20fe1fb5a99d7d31f2c50aaaa6daa1bbc"}, "PMID:17130499:L1": {"materialized_sha256": "6d820248e8c32be2de16d7312bd27505a3de39b6a6606a77b6245ffbbc3000ab", "raw_sha256": "779a421ad8cf4d8d4173552f79ff961ab8fef18e9e7b74a7633630d811d66adf"}, "PMID:17503968:L1": {"materialized_sha256": "71b5a6af2719204956f130472537140869ba06f46429200ddd576718f4582b51", "raw_sha256": "8016c349b967307cad81ae4549c996433d8e58b1c5ac232fc581ac1c4ffbf857"}, "PMID:17503968:L2": {"materialized_sha256": "cb2fbae0d28c550cfcedf79953fba5cb20e15d795d2340ac6e46329ab5c85e8a", "raw_sha256": "91d4dbf1ed20da61b7ae95c3fa9fc801c4c51f517926bbf2fb7edc62a8fdb1a7"}, "PMID:21912932:L1": {"materialized_sha256": "f784160dfa3973e767d86aaa62d9c7f31bc1bd65b4b6d4ff93367b199c6c22e7", "raw_sha256": "f784160dfa3973e767d86aaa62d9c7f31bc1bd65b4b6d4ff93367b199c6c22e7"}, "PMID:22315720:L1": {"materialized_sha256": "60c8c96cfe3aec7a77a76b0548e139eb3a87cbe282113082b2e1fdde7a41b086", "raw_sha256": "60c8c96cfe3aec7a77a76b0548e139eb3a87cbe282113082b2e1fdde7a41b086"}, "PMID:23572523:L1": {"materialized_sha256": "b0a41c25703bc1b76cb9c76ac4a582e005c929f9f1929cb21ff69ca94dc69328", "raw_sha256": "7a99c46ba28bf621d3164bb7d1fded582ac822d84c479aa538d73361c0123fc0"}, "PMID:23616575:L1": {"materialized_sha256": "e931c6d0bd386f6f61e75da432e41bd52c2c496591b14143edd5a437539d15ee", "raw_sha256": "e931c6d0bd386f6f61e75da432e41bd52c2c496591b14143edd5a437539d15ee"}, "PMID:23935835:L1": {"materialized_sha256": "adbcdaef4fff2a8fd900d3c833a351a7fa6f359199ee3584f8853277112e4aee", "raw_sha256": "412d7cc788e66ad3f9d69bec4b971977b109b67b2aa07baee4168171790f87a6"}, "PMID:23935835:L2": {"materialized_sha256": "865a20ad23cdac5fc5e3e63c5d8b063130f822647d030ff73503f8b4663972bd", "raw_sha256": "1ba0a2a6dab5f9119b92290da249795d6f0bc55d6edfc343a639bc5e0ea1100b"}, "PMID:23935835:L3": {"materialized_sha256": "082261bdd48106bdaf8b05ab38329636c5dd9841282d6d9def919f1be0aa2888", "raw_sha256": "86b4e4d3767ccdc339665904ff68b3680c76c0ba2c07e14fddec2557ab73c576"}, "PMID:30449685:L1": {"materialized_sha256": "efeb6e6182278053485d5cde341839a166dd6e3fc6f2ff91abeaa2a5406517d2", "raw_sha256": "b3810d3666fff295357ed7f19ccbd9d47614360425b2840792fb5b5e02e618f4"}, "PMID:30449685:L2": {"materialized_sha256": "5dcf9e33ead3eef4ca9e9a8c62e7d86321f7e874bd757d16d91e63dbaabacc28", "raw_sha256": "d33298e470b1b913c5d989bca91d09c43b82fbe913e131d637473f4f72df27be"}, "PMID:32433410:L1": {"materialized_sha256": "43dad4fab3d945c692df887a014ec596ef5ecb85b66e60c98b2f65e1fdfebcf1", "raw_sha256": "d78d4dccfb1cdf897aa8d930685821c577fef1cf0f8abd723b2dce0a0516d06b"}, "PMID:32433410:L2": {"materialized_sha256": "26ff2ebb89c67698939b96671b890d57520b253446d31bab836d33188e60e4b3", "raw_sha256": "f32ea72ffbf2a94192c683b8fe8db972ad9242b3536c1c7397dcb13c4a69a5db"}, "PMID:33722583:L1": {"materialized_sha256": "53b3bd13d72e58b145b59dc9525a4a4bb5bfaebeddad37be0ca8a90d96b0b630", "raw_sha256": "8bbfc245edfe1cf6b84a142c0fd2e2a6b1a7c19cb1ce90f9c86272deeb0f7b25"}, "PMID:34033222:L1": {"materialized_sha256": "0f5a17eba40844fd9414258b62d582538c63ea74f83147b29393e759ac67ca59", "raw_sha256": "0f5a17eba40844fd9414258b62d582538c63ea74f83147b29393e759ac67ca59"}, "PMID:35046043:L1": {"materialized_sha256": "00c821b7fa5943149930a6d0c7e8a5a972cd235308b9500178c63207bd6365a7", "raw_sha256": "d06dc3ec9674271f0fbba3a312b7e506263429efae2ed8cf80ab51ff85b95d4f"}, "PMID:35725270:L1": {"materialized_sha256": "54434bd52ca0c2e3269f67c6fa9ff615be4cf42eb2a9deb5ecf889a001a25a38", "raw_sha256": "86d6af540f2f89dd0c62ac407aadae599d32e6ddaf9f16f75eff495c66e4b09b"}, "PMID:36560629:L1": {"materialized_sha256": "4269671d03a3fe6e83873f1545bf112008f84d9c05c38b6c7bdd97fe7838fdde", "raw_sha256": "15596dfe8cf862ad01244ac8bad32e6971255db4e10fc5fbc2bae249968aa3f6"}, "PMID:37106062:L1": {"materialized_sha256": "145f3d4d677c30a68d6ae9e200372fb43d301c61ca476ff035ba3674d55a74d2", "raw_sha256": "145f3d4d677c30a68d6ae9e200372fb43d301c61ca476ff035ba3674d55a74d2"}, "PMID:37306457:L1": {"materialized_sha256": "bc5dfd9228074c74fc7cffa362697039a20bf8ac064f2e0449a353b3facfa73d", "raw_sha256": "c8997755f4cc1f0766e6d5ce3b93d53226ae234bf62c24d9b38a3e76427dc176"}, "PMID:37679570:L1": {"materialized_sha256": "282cca550f14c1763059835a36140af73129bf27ef47d266ceb446d4becf3917", "raw_sha256": "a89335d1df01f46aa28eb6789b1d77fea7a29b0de18422ce5800ae25ff9f3b4b"}, "PMID:38135691:L1": {"materialized_sha256": "a28d22fc0bf38ee8b95c8368afcab2ea2526b650d45dd089abfc7541a5660d67", "raw_sha256": "77c6b3d37b026d503ab7b9869d89b647fc38104ea771c05793511245cf603aa0"}, "PMID:38768856:L1": {"materialized_sha256": "9c99bc55d156c5767421210d8f5ea3ad2fb0172ffc79c62f8b8449d26990b66b", "raw_sha256": "e68834f53ab8fbf14b909eed56cc7e814a871c34bd6b6efbb955bcfce9820f71"}, "PMID:38848367:L1": {"materialized_sha256": "fd8694fa06853a72c1be59d9a6cdfebc5ff631de781b61c471922b143e1ba33b", "raw_sha256": "e3ab0170c3a2fd77eb53ab43eabee48b01fd561b6913629ec5995b441d8f6bc2"}, "PMID:38848367:L2": {"materialized_sha256": "008c69f2505b58caed948141e40200d5ee96f0669010fdb342cf90a8e083969d", "raw_sha256": "11f8ad3d44d3f8d53c1901a18b8895dd0865553ab90156ee945505e93b0ecdff"}, "PMID:38848367:L3": {"materialized_sha256": "0788b3f52156e62b1449d5fa06c78fab1d9c4ae3143a46367af58cef107c60f7", "raw_sha256": "efd580c8d5abe05e61595f3b1e7ff370f4a69a1492d7c4aca31605026a2f9e0f"}, "PMID:39647511:L1": {"materialized_sha256": "c8d1948ebc063ca1ebea8621fd5d001ea91ab57278f7c2238c0a4e2141a00697", "raw_sha256": "f926a6ab75ec2584dabd4e2710ba6c95a67fea0ac0557ac5138b8fbcdcb9523a"}, "PMID:40066448:L1": {"materialized_sha256": "8c2ae4f12c5b2350d79af2542a6b8fb74dd91beafde8dd0c257d7f2ea9fa440d", "raw_sha256": "bb2f7a96c9c446c844bcfdc0c891b5155e9a9056ee4969b89e936bb3d9a5fe17"}, "PMID:41118637:L1": {"materialized_sha256": "518f092d3544a7e2fa518d4d2e625f1242edec63f3f5a0fe82dc3a75509524ee", "raw_sha256": "b418227f0dd48b65c27807d0a9e60603313bb55f6e4c5bc706eb7ea458ecdc75"}, "PMID:8384206:L1": {"materialized_sha256": "ec0d04afd80e71cf2771363126bcc8e5bf7db8b770a01ceb5d90d975a71df315", "raw_sha256": "ec0d04afd80e71cf2771363126bcc8e5bf7db8b770a01ceb5d90d975a71df315"}}')
    _w6_expected_pmids_set = frozenset(_w6_expected_qid_to_pmid.values())

    _w6_seen_study_sem: set[str] = set()
    _w6_actual_study_digests: dict[str, str] = {}
    _w6_actual_study_phases: dict[str, str] = {}
    for _wqid_s, _wst_s in sorted(studies.items()):
        if (
            _wqid_s not in _w6_expected_qid_to_pmid
            and _wst_s.get("queue_id") not in _w6_expected_qid_to_pmid
            and _study_pmid(_wst_s) not in _w6_expected_pmids_set
        ):
            continue
        if _wqid_s not in _w6_study_sem_digests or _wst_s.get("queue_id") != _wqid_s:
            raise ValueError(f"WAVE6_STUDY_SEMANTIC_CLAIM_MISMATCH: unexpected or miskeyed Wave-6 study {_wqid_s!r}")
        if _wst_s.get("dec124_certification_status") != _w6_exp_study_status:
            raise ValueError(
                f"WAVE6_STUDY_SEMANTIC_CLAIM_MISMATCH: study {_wqid_s} dec124_certification_status={_wst_s.get('dec124_certification_status')!r} "
                f"mismatches active governed phase status={_w6_exp_study_status!r}"
            )
        # Audit R8-01: Hash FULL study object INCLUDING dec124_certification_status and all phase/certification fields!
        _wst_sem_sha = _sha256_str(json.dumps(_wst_s, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
        _wst_exp_pair = _w6_study_sem_digests[_wqid_s]
        if _wst_sem_sha not in (_wst_exp_pair["raw_sha256"], _wst_exp_pair["materialized_sha256"]):
            raise ValueError(
                f"WAVE6_STUDY_SEMANTIC_CLAIM_MISMATCH: Wave-6 study {_wqid_s} full semantic/phase digest {_wst_sem_sha} "
                f"mismatches pinned raw/materialized digests (dec124_certification_status/phase/pmid/fidelity_tier/record_class/title/year tamper rejected)"
            )
        _w6_actual_study_digests[_wqid_s] = _wst_sem_sha
        _w6_actual_study_phases[_wqid_s] = _wst_s["dec124_certification_status"]
        _w6_seen_study_sem.add(_wqid_s)
    if _w6_seen_study_sem != set(_w6_study_sem_digests.keys()) or len(_w6_seen_study_sem) != 25:
        raise ValueError(f"WAVE6_STUDY_SEMANTIC_CLAIM_MISMATCH: verified {len(_w6_seen_study_sem)}/25 Wave-6 studies")

    _w6_seen_arm_sem: set[str] = set()
    _w6_actual_arm_digests: dict[str, str] = {}
    for _wvid_s, _wa_s in sorted(arms.items()):
        if _wvid_s not in _w6_arm_sem_digests and _wa_s.get("queue_id") not in _w6_expected_qid_to_pmid:
            continue
        if _wvid_s not in _w6_arm_sem_digests or _wa_s.get("variable_id") != _wvid_s:
            raise ValueError(f"WAVE6_ARM_SEMANTIC_CLAIM_MISMATCH: unexpected or miskeyed Wave-6 arm {_wvid_s!r}")
        _wa_sem_sha = _sha256_str(json.dumps(_wa_s, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
        _wa_exp_pair = _w6_arm_sem_digests[_wvid_s]
        if _wa_sem_sha not in (_wa_exp_pair["raw_sha256"], _wa_exp_pair["materialized_sha256"]):
            raise ValueError(
                f"WAVE6_ARM_SEMANTIC_CLAIM_MISMATCH: Wave-6 arm {_wvid_s} semantic digest {_wa_sem_sha} "
                f"mismatches pinned raw/materialized digests (label/n_donors_or_animals/edits/role tamper rejected)"
            )
        _w6_actual_arm_digests[_wvid_s] = _wa_sem_sha
        _w6_seen_arm_sem.add(_wvid_s)
    if _w6_seen_arm_sem != set(_w6_arm_sem_digests.keys()) or len(_w6_seen_arm_sem) != 61:
        raise ValueError(f"WAVE6_ARM_SEMANTIC_CLAIM_MISMATCH: verified {len(_w6_seen_arm_sem)}/61 Wave-6 arms")

    _w6_seen_out_sem: set[str] = set()
    _w6_actual_out_digests: dict[str, str] = {}
    for _woid_s, _wo_s in sorted(outcomes.items()):
        if _woid_s not in _w6_out_sem_digests and (not isinstance(_wo_s, dict) or _wo_s.get("queue_id") not in _w6_expected_qid_to_pmid):
            continue
        if _woid_s not in _w6_out_sem_digests or _wo_s.get("outcome_node_id") != _woid_s:
            raise ValueError(f"WAVE6_OUTCOME_SEMANTIC_CLAIM_MISMATCH: unexpected or miskeyed Wave-6 outcome {_woid_s}")
        _wo_sem_body = {k: v for k, v in _wo_s.items() if k != "cited_by_edge_ids"}
        _wo_sem_sha = _sha256_str(json.dumps(_wo_sem_body, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
        if _wo_sem_sha != _w6_out_sem_digests[_woid_s]:
            raise ValueError(
                f"WAVE6_OUTCOME_SEMANTIC_CLAIM_MISMATCH: Wave-6 outcome {_woid_s} semantic digest {_wo_sem_sha} "
                f"mismatches pinned {_w6_out_sem_digests[_woid_s]} (summary/direction/horizon/transfer/tier/pin tamper rejected)"
            )
        _w6_actual_out_digests[_woid_s] = _wo_sem_sha
        _w6_seen_out_sem.add(_woid_s)
    if _w6_seen_out_sem != set(_w6_out_sem_digests.keys()) or len(_w6_seen_out_sem) != 46:
        raise ValueError(f"WAVE6_OUTCOME_SEMANTIC_CLAIM_MISMATCH: verified {len(_w6_seen_out_sem)}/46 Wave-6 outcomes")

    _w6_seen_edge_sem: set[str] = set()
    _w6_actual_edge_digests: dict[str, str] = {}
    for _we_s in edges:
        _weid_s = str(_we_s.get("edge_id") or "")
        if _weid_s not in _w6_edge_sem_digests and _we_s.get("queue_id") not in _w6_expected_qid_to_pmid:
            continue
        if _weid_s not in _w6_edge_sem_digests:
            raise ValueError(f"WAVE6_EDGE_SEMANTIC_CLAIM_MISMATCH: unexpected unpinned Wave-6 edge {_weid_s}")
        if _weid_s in _w6_seen_edge_sem:
            raise ValueError(f"WAVE6_EDGE_SEMANTIC_CLAIM_MISMATCH: duplicate Wave-6 edge {_weid_s}")
        _we_sem_sha = _sha256_str(json.dumps(_we_s, sort_keys=True, ensure_ascii=False, separators=(",", ":")))
        _we_exp_pair = _w6_edge_sem_digests[_weid_s]
        if _we_sem_sha not in (_we_exp_pair["raw_sha256"], _we_exp_pair["materialized_sha256"]):
            raise ValueError(
                f"WAVE6_EDGE_SEMANTIC_CLAIM_MISMATCH: Wave-6 edge {_weid_s} semantic/authority digest {_we_sem_sha} "
                f"mismatches pinned raw/materialized digests (claim_summary/polarity/horizon/transfer_limits/authority tamper rejected)"
            )
        _w6_actual_edge_digests[_weid_s] = _we_sem_sha
        _w6_seen_edge_sem.add(_weid_s)
    if _w6_seen_edge_sem != set(_w6_edge_sem_digests.keys()) or len(_w6_seen_edge_sem) != 32:
        raise ValueError(f"WAVE6_EDGE_SEMANTIC_CLAIM_MISMATCH: verified {len(_w6_seen_edge_sem)}/32 Wave-6 edges")

    # Audit R8-01: Verify exact whole-graph digest (25 full studies + 61 arms + 46 outcomes + 32 edges + 25 study phases)
    # against the verified phase-specific governed approval receipt in BOTH modes!
    _w6_actual_graph_digest = _sha256_str(
        json.dumps(
            {
                "study_digests": dict(sorted(_w6_actual_study_digests.items())),
                "arm_digests": dict(sorted(_w6_actual_arm_digests.items())),
                "outcome_digests": dict(sorted(_w6_actual_out_digests.items())),
                "edge_digests": dict(sorted(_w6_actual_edge_digests.items())),
                "study_certification_statuses": dict(sorted(_w6_actual_study_phases.items())),
            },
            sort_keys=True,
            ensure_ascii=False,
            separators=(",", ":"),
        )
    )
    if _w6_actual_graph_digest != _w6_approval_rec.get("approved_wave6_graph_digest"):
        raise ValueError(
            f"WAVE6_CERTIFICATION_APPROVAL_MISMATCH: actual Wave-6 graph digest {_w6_actual_graph_digest} "
            f"mismatches approval receipt approved_wave6_graph_digest={_w6_approval_rec.get('approved_wave6_graph_digest')!r}"
        )

    return {
        "studies": len(studies),
        "arms": len(arms),
        "outcomes": len(outcomes),
        "edges": len(edges),
        "effectors": len(effectors),
        "graveyard_index": len(graveyard),
    }


def verify_ceg_payload_detailed(
    ceg: dict[str, Any],
    repo_root: Path = REPO_ROOT,
    *,
    require_sources: bool = False,
) -> dict[str, Any]:
    """Run verify_ceg_payload and return explicit verification_mode alongside counts."""
    counts = verify_ceg_payload(ceg, repo_root=repo_root, require_sources=require_sources)
    _dos_dir = repo_root / "data" / "dossiers"
    _p34 = ["17375075", "39696686", "42020736", "42056515", "42749803"]
    _p35 = ["2642862", "31427818", "35953586", "36944335", "38843830", "39753706", "41201433", "41436438", "41690310", "41764741", "41999746"]
    _q35 = frozenset({"M0189", "M1407", "PMID:36944335", "PMID:39753706", "PMID:41436438", "PMID:41999746"})
    has_src_34 = _dos_dir.is_dir() and all((_dos_dir / f"{pm}.json").is_file() for pm in _p34)
    has_src_35 = _dos_dir.is_dir() and all((_dos_dir / f"{pm}.json").is_file() for pm in _p35)
    _verified_35_oids = (
        sorted(oid for oid, o in (ceg.get("outcomes") or {}).items() if isinstance(o, dict) and o.get("queue_id") in _q35)
        if has_src_35
        else []
    )
    _w6_qids_sorted = sorted(["PMID:1334978", "PMID:17130499", "PMID:17503968", "PMID:21912932", "PMID:22315720", "PMID:23572523", "PMID:23616575", "PMID:23935835", "PMID:30449685", "PMID:32433410", "PMID:33722583", "PMID:34033222", "PMID:35046043", "PMID:35725270", "PMID:36560629", "PMID:37106062", "PMID:37306457", "PMID:37679570", "PMID:38135691", "PMID:38768856", "PMID:38848367", "PMID:39647511", "PMID:40066448", "PMID:41118637", "PMID:8384206"])
    _w6_src_dir_det = repo_root / "data" / "wave6_sources"
    has_src_w6 = _w6_src_dir_det.is_dir() and (_w6_src_dir_det / "efetch_60.json").is_file()
    _w6_prim_cnt = sum(1 for oid, o in (ceg.get("outcomes") or {}).items() if isinstance(o, dict) and o.get("queue_id") in set(_w6_qids_sorted))
    _w6_sec_abs_cnt = sum(
        1
        for o in (ceg.get("outcomes") or {}).values()
        if isinstance(o, dict) and o.get("queue_id") in set(_w6_qids_sorted)
        for sp in (o.get("secondary_source_pins") or [])
        if isinstance(sp, dict) and sp.get("source_type") == "abstract"
    )
    _w6_sec_ft_cnt = sum(
        1
        for o in (ceg.get("outcomes") or {}).values()
        if isinstance(o, dict) and o.get("queue_id") in set(_w6_qids_sorted)
        for sp in (o.get("secondary_source_pins") or [])
        if isinstance(sp, dict) and sp.get("source_type") != "abstract"
    )
    _mode = (
        "iip0035_11dossiers_and_wave6_25studies_55spans_verified"
        if (has_src_35 and len(_verified_35_oids) == 8 and has_src_w6 and _w6_prim_cnt == 46 and (_w6_sec_abs_cnt + _w6_sec_ft_cnt) == 9)
        else (
            "iip0035_11dossiers_8new_exact_spans_verified"
            if (has_src_35 and len(_verified_35_oids) == 8)
            else ("iip0034_5dossiers_8new_exact_spans_verified" if has_src_34 else "structural_public_only")
        )
    )
    _e35_ids = sorted([
        "M0051:L4", "M0154:L3", "M0159:L3", "M0189:L1", "M0206:L3", "M0241:L3",
        "M1407:L1", "PMID:36944335:L1", "PMID:39753706:L1", "PMID:41436438:L1", "PMID:41999746:L1",
    ])
    return {
        "counts": counts,
        "verification_mode": _mode,
        "iip0034_dossiers_verified": _p34 if has_src_34 else [],
        "iip0035_dossiers_verified": _p35 if has_src_35 else [],
        "iip0035_verified_exact_span_outcome_ids": _verified_35_oids,
        "iip0035_verified_exact_span_outcome_count": len(_verified_35_oids),
        "iip0035_sourceguard_executed": bool(has_src_35),
        "iip0035_sourceguard_scanned_study_ids": sorted(_q35) if has_src_35 else [],
        "iip0035_sourceguard_scanned_edge_ids": _e35_ids if has_src_35 else [],
        "iip0035_sourceguard_scanned_touched_legacy_outcome_ids": (
            sorted([
                "M0051:O1", "M0051:O2", "M0051:O3", "M0051:O4", "M0051:O5", "M0051:O6",
                "M0154:O1", "M0154:O2", "M0154:O3", "M0154:O4",
                "M0159:O1", "M0159:O2", "M0159:O3", "M0206:O1", "M0206:O2", "M0206:O9", "M0206:O10",
                "M0206:O11", "M0206:O12", "M0206:O13", "M0206:O14", "M0206:O16", "M0206:O17",
                "M0241:O1", "M0241:O2", "M0241:O3", "M0241:O4",
            ])
            if has_src_35
            else []
        ),
        "iip0035_sourceguard_scanned_adjudicated_legacy_edge_ids": (
            sorted(["M0051:L1", "M0051:L2", "M0051:L3", "M0154:L1", "M0154:L2", "M0159:L1", "M0159:L2", "M0206:L1", "M0206:L2", "M0241:L1", "M0241:L2"])
            if has_src_35
            else []
        ),
        "iip0035_sourceguard_scan_scope": (
            "executed_on_6_new_study_families_11_new_edges_27_touched_legacy_outcomes_and_11_adjudicated_legacy_edges"
            if has_src_35
            else "skipped_public_bundle_no_local_dossiers"
        ),
        "reused_m1522_outcomes_exact_span_verified": False,
        "reused_legacy_crosslink_outcomes_exact_span_verified": False,
        "izadifar_dossier_contains_figure_legends": False,
        "m1522_reused_outcomes_note": "M1522:O6/O7/O15/O16 use figure/panel + digest pins outside the exact-span pass (Izadifar dossier carries no figure legends) and remain ineligible scoping references on M1522:L4.",
        "iip0035_reused_crosslink_outcomes_note": "Reused legacy cross-linked outcomes on M0051:L4, M0154:L3, M0159:L3, M0206:L3, and M0241:L3 carry prior CEG source pins outside the IIP-0035 8-new-outcome exact-span pass and remain primary_certification_eligible=False scoping qualifications only.",
        "wave6_verification_mode": "source_recomputed_verified" if has_src_w6 else "structural_pin_verified",
        "wave6_source_verification_executed": bool(has_src_w6),
        "wave6_structural_span_pin_count": (_w6_prim_cnt + _w6_sec_abs_cnt + _w6_sec_ft_cnt),
        "wave6_source_recomputed_span_count": (_w6_prim_cnt + _w6_sec_abs_cnt + _w6_sec_ft_cnt) if has_src_w6 else 0,
        "wave6_authorized_edge_bindings_verified": True,
        "wave6_valid_evidence_scope_classes_enforced": True,
        "wave6_semantic_claim_binding_verified": True,
        "wave6_study_semantic_digests_verified": 25,
        "wave6_arm_semantic_digests_verified": 61,
        "wave6_outcome_semantic_digests_verified": 46,
        "wave6_edge_semantic_digests_verified": 32,
        "wave6_verified_study_ids": _w6_qids_sorted if has_src_w6 else [],
        "wave6_verified_studies_count": len(_w6_qids_sorted) if has_src_w6 else 0,
        "wave6_verified_primary_span_count": _w6_prim_cnt if has_src_w6 else 0,
        "wave6_verified_secondary_abstract_span_count": _w6_sec_abs_cnt if has_src_w6 else 0,
        "wave6_verified_secondary_fulltext_span_count": _w6_sec_ft_cnt if has_src_w6 else 0,
        "wave6_verified_total_spans_count": (_w6_prim_cnt + _w6_sec_abs_cnt + _w6_sec_ft_cnt) if has_src_w6 else 0,
        "wave6_authorized_cert_eligible_edge_ids": ["PMID:30449685:L1"],
        "wave6_certification_approval_receipt_verified": True,
        "wave6_approved_certification_phase": (ceg.get("wave6_certification_approval_receipt") or {}).get("approved_certification_phase"),
        "wave6_approval_receipt_id": (ceg.get("wave6_certification_approval_receipt") or {}).get("approval_receipt_id"),
        "wave6_approved_wave6_graph_digest": (ceg.get("wave6_certification_approval_receipt") or {}).get("approved_wave6_graph_digest"),
        "wave6_publication_certification_granted": bool((ceg.get("wave6_certification_approval_receipt") or {}).get("publication_certification_granted")),
        "wave6_phase_approved_cert_eligible_edge_ids": list((ceg.get("wave6_certification_approval_receipt") or {}).get("approved_cert_eligible_edge_ids") or []),
    }


def import_and_materialize(
    raw_graph_path: Path,
    screening_ledger_path: Path,
    source_packets_dir: Path,
    repo_root: Path = REPO_ROOT,
) -> tuple[dict[str, Any], dict[str, Any]]:
    raw = json.loads(raw_graph_path.read_text(encoding="utf-8"))
    ledger = json.loads(screening_ledger_path.read_text(encoding="utf-8"))

    study_shingles: dict[str, set[tuple[str, ...]]] = {}
    study_years: dict[str, int] = {}
    for pkt_file in sorted(source_packets_dir.glob("*packets*.json")):
        data = json.loads(pkt_file.read_text(encoding="utf-8"))
        if not isinstance(data, list):
            continue
        for pkt in data:
            if not isinstance(pkt, dict) or "queue_id" not in pkt:
                continue
            qid = str(pkt["queue_id"])
            yr = pkt.get("year")
            if isinstance(yr, int) and not isinstance(yr, bool) and 1900 <= yr <= 2100:
                study_years[qid] = yr
            ws = _words(" ".join(_leaves(pkt)))
            study_shingles.setdefault(qid, set()).update(
                tuple(ws[i : i + 6]) for i in range(max(0, len(ws) - 5))
            )

    pmid_to_qid = {
        str(s.get("pmid")): qid
        for qid, s in raw["study_contexts"].items()
        if s.get("pmid")
    }
    dossier_texts: list[str] = []
    dossier_dir = repo_root / "data" / "dossiers"
    if dossier_dir.is_dir():
        for fp in sorted(dossier_dir.glob("*.json")):
            d_obj = json.loads(fp.read_text(encoding="utf-8"))
            d_txt = " ".join(_leaves(d_obj))
            dossier_texts.append(d_txt)
            qid = pmid_to_qid.get(fp.stem)
            if qid:
                ws = _words(d_txt)
                study_shingles.setdefault(qid, set()).update(
                    tuple(ws[i : i + 6]) for i in range(max(0, len(ws) - 5))
                )

    guard = _SourceGuard(study_shingles, dossier_texts)

    def clean_text(qid: str, field: str, value: Any, meta: dict[str, Any]) -> Any:
        if not isinstance(value, str):
            return value
        text = _scrub_progeny_and_internal_tokens(value)
        if not text:
            return text
        if guard.overlaps(qid, value) or guard.overlaps(qid, text):
            return _structured_replacement(field, text, meta)
        return text

    studies: dict[str, Any] = {}
    for qid in sorted(raw["study_contexts"]):
        s = raw["study_contexts"][qid]
        meta = {"queue_id": qid}
        st: dict[str, Any] = {
            "context_id": s["context_id"],
            "queue_id": qid,
            "id_type": s["id_type"],
            "id_value": s["id_value"],
            "fidelity_tier": s.get("fidelity_tier"),
            "biological_model": clean_text(qid, "biological_model", s.get("biological_model"), meta),
            "immune_context": clean_text(qid, "immune_context", s.get("immune_context"), meta),
            "donor_or_cell_source": clean_text(qid, "donor_or_cell_source", s.get("donor_or_cell_source"), meta),
            "follow_up": clean_text(qid, "follow_up", s.get("follow_up"), meta),
            "variable_arm_ids": list(s.get("variable_arm_ids") or []),
            "blueprint_targets": [clean_text(qid, "blueprint_target", bt, meta) for bt in (s.get("blueprint_targets") or [])],
            "outcomes_count": int(s.get("outcomes_count") or 0),
            "links_count": int(s.get("links_count") or 0),
        }
        if qid in study_years:
            st["pub_year"] = study_years[qid]
        elif isinstance(s.get("pub_year"), int) and not isinstance(s.get("pub_year"), bool):
            st["pub_year"] = s["pub_year"]
        for opt in (
            "pmid",
            "pmcid",
            "doi",
            "title",
            "first_author",
            "senior_author",
            "journal",
            "citation_short",
            "curated_gene_tags",
            "curated_gene_scope",
            "superseded_by_queue_id",
            "superseded_by_pmid",
            "publication_type",
            "same_patient_followup_of_queue_id",
            "same_patient_followup_of_pmid",
            "same_patient_linked_queue_id",
            "correspondence_pin_status",
            "dec124_certification_status",
            "assay_model_class",
        ):
            if s.get(opt):
                st[opt] = s[opt]
        if "has_experimental_subcomponent" in s and s["has_experimental_subcomponent"] is not None:
            st["has_experimental_subcomponent"] = bool(s["has_experimental_subcomponent"])
        if s.get("experimental_subcomponent_note"):
            st["experimental_subcomponent_note"] = clean_text(
                qid, "experimental_subcomponent_note", s.get("experimental_subcomponent_note"), meta
            )
        if s.get("tier_qualification_note"):
            st["tier_qualification_note"] = clean_text(
                qid, "tier_qualification_note", s.get("tier_qualification_note"), meta
            )
        if s.get("candidate_effector_topics"):
            st["candidate_effector_topics"] = list(s["candidate_effector_topics"])
        st_pin = _clean_pin(s.get("source_pin"))
        if st_pin:
            st["source_pin"] = st_pin
        _raw_rc = s.get("record_class")
        if _raw_rc is not None and _raw_rc not in VALID_CEG_RECORD_CLASSES:
            raise ValueError(f"Raw study {qid} has invalid record_class={_raw_rc!r}")
        _pre_rc = classify_ceg_study_record(s)
        _post_rc = classify_ceg_study_record(st)
        st["record_class"] = (
            _pre_rc
            if _pre_rc != "empirical_primary_study"
            else (_raw_rc if _raw_rc in VALID_CEG_RECORD_CLASSES and _raw_rc != "empirical_primary_study" else _post_rc)
        )
        studies[qid] = st

    arms: dict[str, Any] = {}
    for vid in sorted(raw["variable_nodes"]):
        v = raw["variable_nodes"][vid]
        qid = v["queue_id"]
        meta = {
            "queue_id": qid,
            "arm_id": v["arm_id"],
            "causal_isolation": v.get("causal_isolation") or "NOT_ESTABLISHED",
        }
        ar: dict[str, Any] = {
            "variable_id": vid,
            "queue_id": qid,
            "context_id": v["context_id"],
            "arm_id": v["arm_id"],
            "label": clean_text(qid, "label", v.get("label"), meta),
            "edits_or_interventions": [
                clean_text(qid, "edits_or_interventions", ed, meta)
                for ed in (v.get("edits_or_interventions") or [])
            ],
            "n_donors_or_animals": clean_text(qid, "n_donors_or_animals", v.get("n_donors_or_animals"), meta),
            "causal_isolation": v.get("causal_isolation"),
        }
        if v.get("arm_role"):
            ar["arm_role"] = str(v["arm_role"])
        if v.get("arm_role"):
            ar["arm_role"] = str(v["arm_role"])
        if v.get("host_species_or_recipient"):
            ar["host_species_or_recipient"] = str(v["host_species_or_recipient"])
        if v.get("candidate_effector_topics"):
            ar["candidate_effector_topics"] = list(v["candidate_effector_topics"])
        arms[vid] = ar

    outcomes: dict[str, Any] = {}
    for oid in sorted(raw["outcome_nodes"]):
        o = raw["outcome_nodes"][oid]
        qid = o["queue_id"]
        pin = _clean_pin(o.get("source_pin"))
        vq = str(o.get("verbatim_quote") or "")
        meta = {
            "queue_id": qid,
            "outcome_id": o["outcome_id"],
            "direction": o.get("direction") or "unspecified",
            "stat_type": o.get("stat_type") or "unspecified",
            "pin_tag": _pin_tag(pin),
        }
        reach = o.get("outcome_reachability") or {}
        cited_edges = list(reach.get("cited_by_blueprint_link_edge_ids") or o.get("cited_by_edge_ids") or [])
        oc: dict[str, Any] = {
            "outcome_node_id": oid,
            "queue_id": qid,
            "outcome_id": o["outcome_id"],
            "endpoint_name": clean_text(qid, "endpoint_name", o.get("endpoint_name"), meta),
            "comparison_arms": clean_text(qid, "comparison_arms", o.get("comparison_arms"), meta),
            "direction": o.get("direction"),
            "stat_type": o.get("stat_type"),
            "quantitative_summary": clean_text(qid, "quantitative_summary", o.get("quantitative_summary"), meta),
            "manuscript_tier": o.get("manuscript_tier"),
        }
        for val_key in ("intervention_value", "comparator_value", "p_value_or_ci", "n_summary"):
            raw_v = o.get(val_key)
            if raw_v is not None and str(raw_v).strip() and str(raw_v).strip().lower() != "not reported":
                oc[val_key] = clean_text(qid, val_key, str(raw_v), meta)
        if o.get("requires_figure_digitization"):
            oc["requires_figure_digitization"] = True
        if pin:
            oc["source_pin"] = pin
        if vq:
            oc["quote_sha256"] = _sha256_str(vq)
        elif o.get("quote_sha256"):
            oc["quote_sha256"] = str(o["quote_sha256"])
        if o.get("evidence_provenance"):
            oc["evidence_provenance"] = str(o["evidence_provenance"])
        if cited_edges:
            oc["cited_by_edge_ids"] = cited_edges
        if o.get("candidate_effector_topics"):
            oc["candidate_effector_topics"] = list(o["candidate_effector_topics"])
        if o.get("assay_model_class"):
            oc["assay_model_class"] = str(o["assay_model_class"])
        if o.get("assay_or_endpoint"):
            oc["assay_or_endpoint"] = clean_text(qid, "assay_or_endpoint", str(o["assay_or_endpoint"]), meta)
        if o.get("host_species_or_recipient"):
            oc["host_species_or_recipient"] = str(o["host_species_or_recipient"])
        if o.get("timepoint"):
            oc["timepoint"] = clean_text(qid, "timepoint", str(o["timepoint"]), meta)
        if isinstance(o.get("outcome_context_override"), dict):
            oco_in = o["outcome_context_override"]
            oco_out = {
                "study_manuscript_fidelity_tier": oco_in.get("study_manuscript_fidelity_tier"),
                "outcome_effective_assay_tier": oco_in.get("outcome_effective_assay_tier"),
                "override_reason": clean_text(qid, "override_reason", oco_in.get("override_reason"), meta),
                "override_provenance": _scrub_internal_code(str(oco_in.get("override_provenance") or "")),
            }
            if oco_in.get("assay_model_class"):
                oco_out["assay_model_class"] = str(oco_in["assay_model_class"])
            oc["outcome_context_override"] = oco_out
        if isinstance(o.get("comparator_audit_override"), dict):
            cao_in = o["comparator_audit_override"]
            keep_cao_keys = (
                "corrected_comparison_arms",
                "focal_intervention_arm",
                "misbound_master_arm_id",
                "baseline_comparator_arm",
                "assay_context",
                "audit_note",
            )
            oc["comparator_audit_override"] = {
                k: clean_text(qid, k, cao_in[k], meta)
                for k in keep_cao_keys
                if k in cao_in and cao_in[k] is not None
            }
        if isinstance(o.get("focal_arm_id"), str) and o["focal_arm_id"].strip():
            oc["focal_arm_id"] = str(o["focal_arm_id"]).strip()
        if isinstance(o.get("intervention_arm_id"), str) and o["intervention_arm_id"].strip():
            oc["intervention_arm_id"] = str(o["intervention_arm_id"]).strip()
        if isinstance(o.get("intervention_arm_ids"), list):
            oc["intervention_arm_ids"] = list(o["intervention_arm_ids"])
        if isinstance(o.get("comparator_arm_ids"), list):
            oc["comparator_arm_ids"] = list(o["comparator_arm_ids"])
        if isinstance(o.get("secondary_source_pins"), list):
            oc["secondary_source_pins"] = [dict(sp) for sp in o["secondary_source_pins"] if isinstance(sp, dict)]
        outcomes[oid] = oc

    edges: list[dict[str, Any]] = []
    for e in sorted(raw["edges"], key=lambda item: (item["queue_id"], item["link_index"])):
        qid = e["queue_id"]
        meta = {
            "queue_id": qid,
            "edge_id": e["edge_id"],
            "relation": e.get("relation") or "unspecified",
            "applicability": e.get("applicability") or "unspecified",
            "incorporation": e.get("incorporation") or "unspecified",
            "cited_outcome_ids": list(e.get("cited_outcome_ids") or []),
        }
        cited_tuples = [
            f"{t[0]}:{t[1]}" if isinstance(t, (list, tuple)) and len(t) == 2 else str(t)
            for t in (e.get("cited_outcome_tuples") or [])
        ]
        _raw_pce = e.get("primary_certification_eligible")
        if type(_raw_pce) is not bool:
            raise ValueError(
                f"Raw edge {e.get('edge_id')} primary_certification_eligible must be strict bool, got {_raw_pce!r} ({type(_raw_pce).__name__})"
            )
        _edge_prov = e.get("evidence_provenance")
        _imp_non_emp_prov = frozenset({
            "computational_model_or_simulation",
            "mixed_measured_and_simulated_model",
            "mixed_empirical_and_computational",
            "administrative_registry_record",
        })
        _imp_title_pins = frozenset({"title_or_citation_metadata_only", "title"})
        _st_pin_imp_t = (studies[qid].get("source_pin") or {}).get("source_type") if isinstance(studies[qid].get("source_pin"), dict) else None
        _cites_nonemp_or_sim = any(
            studies.get(outcomes[tok]["queue_id"], {}).get("record_class") != "empirical_primary_study"
            or outcomes[tok].get("evidence_provenance") in _imp_non_emp_prov
            or (isinstance(outcomes[tok].get("source_pin"), dict) and outcomes[tok]["source_pin"].get("source_type") in _imp_title_pins)
            or (
                isinstance(studies.get(outcomes[tok]["queue_id"], {}).get("source_pin"), dict)
                and studies[outcomes[tok]["queue_id"]]["source_pin"].get("source_type") in _imp_title_pins
            )
            for tok in cited_tuples
            if tok in outcomes
        )
        ed: dict[str, Any] = {
            "edge_id": e["edge_id"],
            "queue_id": qid,
            "link_index": int(e["link_index"]),
            "target_gate_or_module": clean_text(qid, "target_gate_or_module", e.get("target_gate_or_module"), meta),
            "relation": e.get("relation"),
            "applicability": e.get("applicability"),
            "incorporation": e.get("incorporation"),
            "readiness": e.get("readiness"),
            "primary_certification_eligible": (
                False
                if (
                    studies[qid].get("record_class") != "empirical_primary_study"
                    or e.get("applicability") == "domain_mismatch"
                    or e.get("relation") == "noninformative"
                    or e.get("readiness") == "needs_primary_fulltext"
                    or _st_pin_imp_t in _imp_title_pins
                    or _edge_prov in _imp_non_emp_prov
                    or e["edge_id"] in CURATED_INELIGIBLE_EDGE_IDS
                    or (
                        e.get("applicability") == "unvalidated_transfer"
                        and (
                            qid in {
                                "PMID:17375075", "PMID:42020736", "PMID:42056515", "PMID:42749803",
                                "M0300", "PMID:22099783", "PMID:30012675", "PMID:30569273",
                                "PMID:30967424", "PMID:31180194", "PMID:33632742", "PMID:33658358",
                                "PMID:37861217", "PMID:39137044", "PMID:40447640", "PMID:40598585",
                                "PMID:40976248", "PMID:41026533", "PMID:41196293",
                            }
                            or (qid == "M1522" and e["edge_id"] not in {"M1522:L1", "M1522:L2"})
                        )
                    )
                    or not cited_tuples
                    or _cites_nonemp_or_sim
                )
                else _raw_pce
            ),
            "cited_outcome_ids": list(e.get("cited_outcome_ids") or []),
            "cited_outcome_tuples": cited_tuples,
            "claim_summary": clean_text(qid, "claim_summary", e.get("claim_summary"), meta),
        }
        if _edge_prov:
            ed["evidence_provenance"] = str(_edge_prov)
        if e.get("provenance_note"):
            ed["provenance_note"] = clean_text(qid, "provenance_note", e.get("provenance_note"), meta)
        if e.get("legacy_certification_adjudication_note"):
            ed["legacy_certification_adjudication_note"] = clean_text(qid, "legacy_certification_adjudication_note", e.get("legacy_certification_adjudication_note"), meta)
        if e.get("polarity"):
            ed["polarity"] = str(e["polarity"])
        if "cert_eligible" in e and type(e["cert_eligible"]) is bool:
            ed["cert_eligible"] = ed["primary_certification_eligible"]
        if e.get("evidence_scope_class"):
            ed["evidence_scope_class"] = str(e["evidence_scope_class"])
        if e.get("wave_horizon_scope"):
            ed["wave_horizon_scope"] = str(e["wave_horizon_scope"])
        if e.get("horizon"):
            ed["horizon"] = str(e["horizon"])
        if e.get("host_species_or_recipient"):
            ed["host_species_or_recipient"] = str(e["host_species_or_recipient"])
        if e.get("transfer_limits"):
            ed["transfer_limits"] = clean_text(qid, "transfer_limits", str(e["transfer_limits"]), meta)
        _e_sp_clean = _clean_pin(e.get("source_pin"))
        if _e_sp_clean:
            ed["source_pin"] = _e_sp_clean
        if e.get("candidate_effector_topics"):
            ed["candidate_effector_topics"] = list(e["candidate_effector_topics"])
        edges.append(ed)

    effectors: dict[str, Any] = {}
    for eff_id in sorted(raw["effector_nodes"]):
        eff = raw["effector_nodes"][eff_id]
        effectors[eff_id] = {
            "effector_id": eff["effector_id"],
            "topic_id": eff["topic_id"],
            "label": eff["label"],
            "category": eff["category"],
            "causal_isolation": eff["causal_isolation"],
            "mediation_status": eff["mediation_status"],
            "semantic_status": eff.get("semantic_status"),
            "linked_study_ids": sorted(eff.get("linked_study_ids") or []),
            "linked_variable_ids": sorted(eff.get("linked_variable_ids") or []),
            "linked_outcome_tuples": [
                f"{t[0]}:{t[1]}" if isinstance(t, (list, tuple)) and len(t) == 2 else str(t)
                for t in (eff.get("linked_outcome_tuples") or [])
            ],
        }

    # Build graveyard_index directly from the canonical public graveyard file for zero source-prose drift
    gy_src = json.loads((repo_root / GRAVEYARD_REL_PATH).read_text(encoding="utf-8"))["graveyard_entries"]
    gy_by_id = {row["graveyard_id"]: row for row in gy_src}
    graveyard_index: list[dict[str, Any]] = []
    for g in raw["graveyard_index"]:
        gid = g["graveyard_id"]
        canon = gy_by_id.get(gid, {})
        graveyard_index.append({
            "graveyard_id": gid,
            "category": g.get("Category") or canon.get("severity") or "BLOCK",
            "severity": canon.get("severity"),
        })

    l_sum = ledger.get("summary")
    if not isinstance(l_sum, dict) or "total_studies" not in l_sum:
        raise ValueError("screening_ledger.summary must be a dict containing explicit total_studies and overall_counts")
    _oc_counts = l_sum.get("overall_counts")
    _wave_counts = l_sum.get("candidate_extraction_waves")
    if not isinstance(_oc_counts, dict) or not all(k in _oc_counts for k in ("ADVANCE", "PARK_CONTEXT", "EXCLUDE_OFF_TOPIC")):
        raise ValueError("screening_ledger.summary.overall_counts must specify ADVANCE, PARK_CONTEXT, and EXCLUDE_OFF_TOPIC")
    if not isinstance(_wave_counts, dict) or "Wave_2B_Supporting_Catalog_P2_P3" not in _wave_counts:
        raise ValueError("screening_ledger.summary.candidate_extraction_waves must specify Wave_2B_Supporting_Catalog_P2_P3")
    _tot_screened = l_sum["total_studies"]
    _r1_screened = l_sum.get("ring1_existing_records_screened", 642)
    _new_screened = l_sum.get("new_candidate_records_screened", 3328)
    _adv_total = _oc_counts["ADVANCE"]
    _park_total = _oc_counts["PARK_CONTEXT"]
    _excl_total = _oc_counts["EXCLUDE_OFF_TOPIC"]
    _rem_total = _wave_counts["Wave_2B_Supporting_Catalog_P2_P3"]
    if not all(type(v) is int and v >= 0 for v in (_tot_screened, _r1_screened, _new_screened, _adv_total, _park_total, _excl_total, _rem_total)):
        raise ValueError("screening_ledger counts must be non-negative integers")
    if _r1_screened + _new_screened != _tot_screened:
        raise ValueError(f"Inconsistent screening_ledger totals: ring1 ({_r1_screened}) + new ({_new_screened}) != total_studies ({_tot_screened})")
    if _adv_total + _park_total + _excl_total != _tot_screened:
        raise ValueError(f"Inconsistent screening_ledger totals: ADVANCE ({_adv_total}) + PARK_CONTEXT ({_park_total}) + EXCLUDE_OFF_TOPIC ({_excl_total}) != total_studies ({_tot_screened})")
    if len(studies) + _rem_total != _adv_total:
        raise ValueError(f"Inconsistent screening_ledger totals: extracted ({len(studies)}) + queued ({_rem_total}) != ADVANCE ({_adv_total})")
    rc_import = Counter(classify_ceg_study_record(s) for s in studies.values())
    screening_funnel = {
        "screened_records_total": _tot_screened,
        "ring1_existing_records_screened": _r1_screened,
        "new_candidate_records_screened": _new_screened,
        "candidates_advanced_total": _adv_total,
        "contextual_reviews_parked_total": _park_total,
        "off_topic_records_excluded_total": _excl_total,
        "wave1_ceg_records_extracted_total": len(studies),
        "wave1_primary_empirical_extracted_total": rc_import["empirical_primary_study"],
        "wave1_trial_registry_protocols_extracted": rc_import["trial_registry_protocol"],
        "wave1_regulatory_or_guidance_records_extracted": rc_import["regulatory_or_guidance_document"],
        "wave1_computational_models_extracted": rc_import["computational_model_or_simulation"],
        "wave1_correspondence_or_secondary_extracted": rc_import["correspondence_or_secondary_summary"],
        "wave1_superseded_preprint_duplicates_extracted": rc_import["superseded_preprint_duplicate"],
        "wave1_ring1_core_records_extracted_total": sum(1 for q in studies if q.startswith("R1_")),
        "wave1_ring1_empirical_core_extracted": sum(1 for q, s in studies.items() if q.startswith("R1_") and classify_ceg_study_record(s) == "empirical_primary_study"),
        "wave1_new_empirical_studies_extracted": sum(1 for q, s in studies.items() if not q.startswith("R1_") and classify_ceg_study_record(s) == "empirical_primary_study"),
        "wave1_non_r1_records_extracted_total": sum(1 for q in studies if not q.startswith("R1_")),
        "remaining_supporting_catalog_queued_for_later_waves": _rem_total,
    }
    _raw_sf_led = (raw.get("screening_funnel") or {}).get("iip0035_record_level_screening_ledger")
    _led_sf_led = l_sum.get("iip0035_record_level_screening_ledger")
    if isinstance(_led_sf_led, list) and len(_led_sf_led) == 11:
        screening_funnel["iip0035_record_level_screening_ledger"] = list(_led_sf_led)
    elif isinstance(_raw_sf_led, list) and len(_raw_sf_led) == 11:
        screening_funnel["iip0035_record_level_screening_ledger"] = list(_raw_sf_led)
    _raw_hist35 = (raw.get("screening_funnel") or {}).get("historical_iip0035_1182_milestone")
    _led_hist35 = l_sum.get("historical_iip0035_1182_milestone")
    if isinstance(_led_hist35, dict):
        screening_funnel["historical_iip0035_1182_milestone"] = dict(_led_hist35)
    elif isinstance(_raw_hist35, dict):
        screening_funnel["historical_iip0035_1182_milestone"] = dict(_raw_hist35)
    _raw_w5_led = (raw.get("screening_funnel") or {}).get("wave5_delta_screening_ledger")
    _led_w5_led = l_sum.get("wave5_delta_screening_ledger")
    if isinstance(_led_w5_led, list) and len(_led_w5_led) == 40:
        screening_funnel["wave5_delta_screening_ledger"] = list(_led_w5_led)
    elif isinstance(_raw_w5_led, list) and len(_raw_w5_led) == 40:
        screening_funnel["wave5_delta_screening_ledger"] = list(_raw_w5_led)
    _raw_w5_hist = (raw.get("screening_funnel") or {}).get("historical_wave5_1216_milestone")
    _led_w5_hist = l_sum.get("historical_wave5_1216_milestone")
    if isinstance(_led_w5_hist, dict):
        screening_funnel["historical_wave5_1216_milestone"] = dict(_led_w5_hist)
    elif isinstance(_raw_w5_hist, dict):
        screening_funnel["historical_wave5_1216_milestone"] = dict(_raw_w5_hist)
    _raw_44_led = (raw.get("screening_funnel") or {}).get("ceg_v1_cutover_record_level_screening_ledger")
    _led_44_led = l_sum.get("ceg_v1_cutover_record_level_screening_ledger")
    if isinstance(_led_44_led, list) and len(_led_44_led) == 21:
        screening_funnel["ceg_v1_cutover_record_level_screening_ledger"] = list(_led_44_led)
    elif isinstance(_raw_44_led, list) and len(_raw_44_led) == 21:
        screening_funnel["ceg_v1_cutover_record_level_screening_ledger"] = list(_raw_44_led)
    _raw_pre_w6 = (raw.get("screening_funnel") or {}).get("historical_baseline_pre_wave6_milestone")
    _led_pre_w6 = l_sum.get("historical_baseline_pre_wave6_milestone")
    if isinstance(_led_pre_w6, dict):
        screening_funnel["historical_baseline_pre_wave6_milestone"] = dict(_led_pre_w6)
    elif isinstance(_raw_pre_w6, dict):
        screening_funnel["historical_baseline_pre_wave6_milestone"] = dict(_raw_pre_w6)
    _raw_h1234 = (raw.get("screening_funnel") or {}).get("historical_ceg_v1_1234_milestone")
    _led_h1234 = l_sum.get("historical_ceg_v1_1234_milestone")
    if isinstance(_led_h1234, dict):
        screening_funnel["historical_ceg_v1_1234_milestone"] = dict(_led_h1234)
    elif isinstance(_raw_h1234, dict):
        screening_funnel["historical_ceg_v1_1234_milestone"] = dict(_raw_h1234)
    _raw_w6_led = (raw.get("screening_funnel") or {}).get("wave6_delta_record_level_screening_ledger")
    _led_w6_led = l_sum.get("wave6_delta_record_level_screening_ledger")
    if isinstance(_led_w6_led, list) and len(_led_w6_led) == 25:
        screening_funnel["wave6_delta_record_level_screening_ledger"] = list(_led_w6_led)
    elif isinstance(_raw_w6_led, list) and len(_raw_w6_led) == 25:
        screening_funnel["wave6_delta_record_level_screening_ledger"] = list(_raw_w6_led)

    ceg_payload: dict[str, Any] = {
        "schema_version": "openislet_context_evidence_graph_v1.0",
        "graph_name": "OpenIslet T1D Context-Evidence Graph",
        "graph_acronym": "CEG",
        "license": "CC-BY-4.0",
        "quote_and_rights_policy": {
            "verbatim_quote_status": "WITHHELD_IN_PUBLIC_CEG_SEE_QUOTE_SHA256_AND_SOURCE_PIN",
            "non_oa_prose_overlap_policy": (
                "All inline verbatim_quote strings are withheld (preserving 64-hex quote_sha256 and source_pin), "
                "and any string field sharing a >=6-word normalized source shingle or >=40-character local dossier "
                "substring is replaced with a deterministic non-expressive structured descriptor."
            ),
            "omitted_outcome_field_defaults": {
                "verbatim_quote": None,
                "intervention_value": "not reported",
                "comparator_value": "not reported",
                "p_value_or_ci": "not reported",
                "n_summary": "not reported",
                "requires_figure_digitization": False,
                "cited_by_edge_ids": [],
            },
        },
        "evidence_hierarchy_and_scoring_note": (
            f"Context-indexed evidence graph across {len(studies):,} total CEG records ("
            f"{rc_import['empirical_primary_study']:,} empirical_primary_study + "
            f"{rc_import['trial_registry_protocol']:,} trial_registry_protocol + "
            f"{rc_import['regulatory_or_guidance_document']:,} regulatory_or_guidance_document + "
            f"{rc_import['computational_model_or_simulation']:,} computational_model_or_simulation + "
            f"{rc_import['correspondence_or_secondary_summary']:,} correspondence_or_secondary_summary + "
            f"{rc_import['superseded_preprint_duplicate']:,} superseded_preprint_duplicate), "
            f"{len(arms):,} arms, {len(outcomes):,} outcomes, and {len(edges):,} blueprint links. "
            "Layer-1 2,160-stack prior-anchored scenario scores remain invariant on the 642-study Ring-1 baseline "
            "(+0.00 pp under Wave-5 IIP-0041/IIP-0042/IIP-0043, the DEC-124 CEG v1 quality sweep, and Wave-6 staged CEG delta) "
            "unless explicitly updated through an accepted Islet Improvement Proposal."
        ),
        "counts": {
            "screened_records_total": screening_funnel["screened_records_total"],
            "candidates_advanced_total": screening_funnel["candidates_advanced_total"],
            "studies": len(studies),
            "record_class_counts": dict(sorted(rc_import.items())),
            "arms": len(arms),
            "outcomes": len(outcomes),
            "edges": len(edges),
            "effectors": len(effectors),
            "graveyard_entries_indexed": len(graveyard_index),
            "unresolved_exact_outcome_mentions": 0,
        },
        "screening_funnel": screening_funnel,
        "studies": studies,
        "arms": arms,
        "outcomes": outcomes,
        "edges": edges,
        "effectors": effectors,
        "graveyard_index": graveyard_index,
    }
    if isinstance(raw.get("wave6_certification_approval_receipt"), dict):
        ceg_payload["wave6_certification_approval_receipt"] = dict(raw["wave6_certification_approval_receipt"])
    _w6_imp_raw_rec = json.loads('{"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_imp_mat_rec = json.loads('{"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_raw_rec_in = raw.get("wave6_certification_approval_receipt")
    if isinstance(_w6_raw_rec_in, dict) and (_w6_raw_rec_in == _w6_imp_raw_rec or _w6_raw_rec_in == _w6_imp_mat_rec):
        ceg_payload["wave6_certification_approval_receipt"] = dict(_w6_imp_mat_rec)
    elif _w6_raw_rec_in is not None:
        ceg_payload["wave6_certification_approval_receipt"] = _w6_raw_rec_in

    verify_ceg_payload(ceg_payload, repo_root=repo_root)
    atlas_payload = build_layer1_atlas_from_ceg(ceg_payload)
    return ceg_payload, atlas_payload


def main() -> None:
    parser = argparse.ArgumentParser(description="Build or verify OpenIslet Layer-1 Context-Evidence Graph artifacts.")
    parser.add_argument("--root", type=Path, default=REPO_ROOT, help="OpenIslet repository root")
    parser.add_argument("--verify", action="store_true", help="Verify existing artifacts without modifying files")
    parser.add_argument("--import-raw-graph", type=Path, default=None, help="Optional raw CEG JSON to import")
    parser.add_argument("--import-screening-ledger", type=Path, default=None, help="Optional screening ledger JSON")
    parser.add_argument("--source-packets-dir", type=Path, default=None, help="Optional directory of source packets for shingle scrubbing")
    args = parser.parse_args()

    root = args.root.resolve()
    ceg_path = root / CEG_REL_PATH
    atlas_path = root / ATLAS_REL_PATH

    if args.import_raw_graph is not None:
        if args.import_screening_ledger is None or args.source_packets_dir is None:
            raise ValueError("--import-raw-graph requires --import-screening-ledger and --source-packets-dir")
        ceg_payload, atlas_payload = import_and_materialize(
            args.import_raw_graph.resolve(),
            args.import_screening_ledger.resolve(),
            args.source_packets_dir.resolve(),
            repo_root=root,
        )
        ceg_bytes = (json.dumps(ceg_payload, ensure_ascii=False, allow_nan=False, separators=(",", ":")) + "\n").encode("utf-8")
        atlas_bytes = (json.dumps(atlas_payload, indent=2, ensure_ascii=False, allow_nan=False) + "\n").encode("utf-8")
        ceg_path.parent.mkdir(parents=True, exist_ok=True)
        ceg_path.write_bytes(ceg_bytes)
        atlas_path.write_bytes(atlas_bytes)
        print(
            f"Materialized {CEG_REL_PATH} ({len(ceg_bytes) / 1024 / 1024:.2f} MB) "
            f"and {ATLAS_REL_PATH} ({len(atlas_bytes) / 1024 / 1024:.2f} MB)."
        )
        return

    if not ceg_path.is_file():
        raise FileNotFoundError(f"Missing {ceg_path}")
    import math as _math
    def _bceg_no_dup(pairs):
        out = {}
        for k, v in pairs:
            if k in out:
                raise ValueError(f"Duplicate JSON key in CEG: {k!r}")
            out[k] = v
        return out
    def _bceg_no_nan(tok):
        raise ValueError(f"Non-standard JSON constant in CEG: {tok!r}")
    def _bceg_finite_float(tok):
        v = float(tok)
        if not _math.isfinite(v):
            raise ValueError(f"Non-finite JSON float overflow in CEG: {tok!r}")
        return v
    ceg_payload = json.loads(ceg_path.read_text(encoding="utf-8"), object_pairs_hook=_bceg_no_dup, parse_constant=_bceg_no_nan, parse_float=_bceg_finite_float)
    detail = verify_ceg_payload_detailed(ceg_payload, repo_root=root)
    counts = detail["counts"]
    expected_atlas = (json.dumps(build_layer1_atlas_from_ceg(ceg_payload), indent=2, ensure_ascii=False, allow_nan=False) + "\n").encode("utf-8")
    if args.verify:
        if not atlas_path.is_file() or atlas_path.read_bytes() != expected_atlas:
            raise ValueError(f"{ATLAS_REL_PATH} is missing or out of sync with {CEG_REL_PATH}")
        print(f"Verified CEG ({counts['studies']} studies, {counts['outcomes']} outcomes, {counts['edges']} links; mode={detail['verification_mode']}, exact_spans_verified={detail['iip0035_verified_exact_span_outcome_count']}, sourceguard_executed={detail['iip0035_sourceguard_executed']}) and Layer-1 atlas.")
    else:
        atlas_path.write_bytes(expected_atlas)
        print(f"Verified CEG and wrote {ATLAS_REL_PATH} ({len(expected_atlas) / 1024 / 1024:.2f} MB).")


if __name__ == "__main__":
    main()
