scripts/verify_iip0034_planar_and_portfolio.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0034_planar_and_portfolio.py · SHA-256: 24ff92056312d1e8…
f"{min_allocs[-1][0]}+{min_allocs[-1][1]})."
),
}
def _resolve_and_verify_design_y_v2_registry(repo_root: Path) -> Dict[str, Any]:
"""Load product registry, staged FASTAs, DEC-113 96-cell decision-tree contract, and CommonMark Playbook s4.1.19."""
p_defs = pc.load_product_contracts(repo_root, require_staged_fastas=True)
by_id = {p["product_variant_id"]: p for p in p_defs["products"]}
# 1. Verify DEC-113 block in stage0_decision_tree_v1.json (strict no-duplicate-keys, no-NaN, canonical SHA-256)
dt_path = repo_root / DECISION_TREE_REL_PATH
if not dt_path.is_file():
raise ValueError(f"Missing Stage-0 decision tree file: {dt_path}")
dt_doc = _load_json_strict(dt_path)
dec113_blk = dt_doc.get("design_y_fullstack_v2_and_route3p_gates_iip_0034")
if not isinstance(dec113_blk, dict):
raise ValueError("Missing DEC-113 block design_y_fullstack_v2_and_route3p_gates_iip_0034 in stage0_decision_tree_v1.json")
dec113_sha = hashlib.sha256(
json.dumps(dec113_blk, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
).hexdigest()
if dec113_sha != EXPECTED_DEC113_DECISION_TREE_SHA256:
raise ValueError(
f"DEC-113 decision-tree block SHA-256 mismatch: found {dec113_sha}, expected {EXPECTED_DEC113_DECISION_TREE_SHA256}"
)
# 2. Parse Playbook with real CommonMark 0.31.2 block parser & require EXACTLY 1 rendered 4.1.19 heading!
pb_path = repo_root / PLAYBOOK_REL_PATH
if not pb_path.is_file():
raise ValueError(f"Missing Stage-0 execution playbook: {pb_path}")
pb_raw = pb_path.read_text(encoding="utf-8")
pb_norm = pb_raw.replace("\r\n", "\n").replace("\r", "\n")
all_headings = _parse_commonmark_headings(pb_norm)
matched_4119 = [
h for h in all_headings
if re.search(r"(?<![0-9A-Za-z.])4\.1\.19(?![0-9A-Za-z.])", re.sub(r"[`*_]", "", h["rendered_title"]))
]
pb_expected_prefix = "#### 4.1.19 Preregistered `Design Y-FullStack v2`"
if len(matched_4119) != 1:
raise ValueError(
f"CommonMark Playbook audit requires exactly 1 rendered 4.1.19 heading, found {len(matched_4119)}: "
f"{[(h['kind'], h['level'], h['container_depth'], h['start_line'] + 1) for h in matched_4119]}"
)
h4119 = matched_4119[0]
if (
h4119["kind"] != "atx"
or h4119["level"] != 4
or h4119["container_depth"] != 0
or not h4119["raw_first_line"].startswith(pb_expected_prefix)
):
raise ValueError(f"Rendered 4.1.19 heading has unexpected CommonMark structure: {h4119}")
# Determine section end strictly from parser offsets (next top-level heading of level <= 4 OR provenance boundary)
start_off = h4119["start_offset"]
next_heading_off = len(pb_norm)
for h in all_headings:
if h["start_offset"] > start_off and h["container_depth"] == 0 and h["level"] <= 4:
next_heading_off = h["start_offset"]
break
prov_marker = "\n\nCurrent cHS4 provenance:"
prov_idx = pb_norm.find(prov_marker, start_off, next_heading_off)
if prov_idx == -1:
raise ValueError("Missing expected post-4.1.19 provenance boundary after rendered 4.1.19 heading")
pb_sec_full = pb_norm[start_off:prov_idx].strip()
pb_sha = hashlib.sha256(pb_sec_full.encode("utf-8")).hexdigest()
if pb_sha != EXPECTED_DEC113_PLAYBOOK_SEC4119_SHA256:
raise ValueError(
f"DEC-113 Playbook section 4.1.19 SHA-256 mismatch: found {pb_sha}, expected {EXPECTED_DEC113_PLAYBOOK_SEC4119_SHA256}"
)
# 3. Verify product roles, non-executable state, and 1:1 route binding
expected_fullstack_roles = frozenset({"FULL_CHR15_11TU_REFERENCE", "GATE0V_CD55_CFH_BACKUP_COMPARATOR"})
resolved_fullstack_ids: List[str] = []
resolved_excluded_ids: List[str] = []
resolved_fullstack_route_codes: set[str] = set()
resolved_all_route_codes: set[str] = set()
for pvid in sorted(pc.STAGED_DESIGN_Y_V2_PRODUCT_IDS):
if pvid not in by_id:
raise ValueError(f"Loaded product registry missing staged Design Y-FullStack v2 record {pvid}")
prod = by_id[pvid]
if prod.get("execution_supported") is not False:
raise ValueError(f"Loaded product {pvid} must keep execution_supported=False")
phys_route = prod.get("physical_route_id")
mapped_code = PHYSICAL_ROUTE_TO_PORTFOLIO_CODE.get(str(phys_route))
if mapped_code is None:
raise ValueError(f"Unmapped physical_route_id {phys_route!r} on {pvid}")
resolved_all_route_codes.add(mapped_code)
binding = prod.get("staged_design_y_fullstack_v2_donor_binding") or {}
role = str(binding.get("role") or "")
gates_str = str(binding.get("stage0_promotion_gates") or "")
if role in expected_fullstack_roles:
if "EXCLUDED_FROM_FULLSTACK_CLEARANCE" in gates_str:
raise ValueError(f"Full-stack candidate {pvid} must not be marked excluded from full-stack clearance")
resolved_fullstack_ids.append(pvid)
resolved_fullstack_route_codes.add(mapped_code)
else:
if "EXCLUDED_FROM_FULLSTACK_CLEARANCE" not in gates_str:
raise ValueError(f"Non-full-stack record {pvid} ({role}) must be marked EXCLUDED_FROM_FULLSTACK_CLEARANCE")
resolved_excluded_ids.append(pvid)
portfolio_allowed = rank_mod.ALLOWED_CELL_ROUTE_PAIRS_IIP0034["DESIGN_Y_FULLSTACK_V2"]
if resolved_fullstack_route_codes != portfolio_allowed or resolved_all_route_codes != frozenset({"R3P"}):
raise ValueError(
f"Loaded product registry routes ({sorted(resolved_fullstack_route_codes)}) disagree with "
f"ALLOWED_CELL_ROUTE_PAIRS_IIP0034['DESIGN_Y_FULLSTACK_V2'] ({sorted(portfolio_allowed)})"
)
# 4. Validate authoritative typed 96-cell product_by_gate_contract & 30-endpoint DEC-102 crosswalk
# with strict closed operator/disposition allowlists, duplicate/placeholder rejection, AND
# direct cell-to-prose semantic concordance across ALL 3 controlling documents!
xwalk_rows = dec113_blk.get("dec102_endpoint_crosswalk")
if not isinstance(xwalk_rows, list) or len(xwalk_rows) != len(EXPECTED_DEC102_ENDPOINT_IDS):
raise ValueError(
f"DEC-113 dec102_endpoint_crosswalk must contain exactly {len(EXPECTED_DEC102_ENDPOINT_IDS)} unique entries "
f"(got {len(xwalk_rows) if isinstance(xwalk_rows, list) else type(xwalk_rows).__name__})"
)
seen_xwalk_ids: set[str] = set()
for xrow in xwalk_rows:
if not isinstance(xrow, dict) or set(xrow.keys()) != REQUIRED_XWALK_KEYS:
raise ValueError(f"Malformed dec102_endpoint_crosswalk row: {xrow!r}")
if any(not isinstance(v, str) or not v.strip() or _PLACEHOLDER_TOKEN_RE.search(v) for v in xrow.values()):
raise ValueError(f"Empty, non-string, or placeholder field in dec102_endpoint_crosswalk row {xrow.get('dec102_endpoint_id')!r}")
if xrow["operator"] not in VALID_XWALK_OPERATORS:
raise ValueError(f"Unrecognized crosswalk operator {xrow['operator']!r} on {xrow['dec102_endpoint_id']!r}")
if xrow["disposition"] not in VALID_XWALK_DISPOSITIONS:
raise ValueError(f"Unrecognized crosswalk disposition {xrow['disposition']!r} on {xrow['dec102_endpoint_id']!r}")
eid = xrow["dec102_endpoint_id"]
if eid in seen_xwalk_ids:
raise ValueError(f"Duplicate dec102_endpoint_id rejected in crosswalk: {eid!r}")
seen_xwalk_ids.add(eid)
if seen_xwalk_ids != EXPECTED_DEC102_ENDPOINT_IDS:
raise ValueError(
f"DEC-113 dec102_endpoint_crosswalk ID set mismatch: missing={sorted(EXPECTED_DEC102_ENDPOINT_IDS - seen_xwalk_ids)}, "
f"extra={sorted(seen_xwalk_ids - EXPECTED_DEC102_ENDPOINT_IDS)}"
)
pbg = dec113_blk.get("product_by_gate_contract")
if not isinstance(pbg, dict) or pbg.get("cell_count") != 96 or not isinstance(pbg.get("cells"), list) or len(pbg["cells"]) != 96:
raise ValueError("DEC-113 product_by_gate_contract must define exactly 96 typed product-by-gate cells")
cell_map: Dict[tuple[str, str], Dict[str, Any]] = {}
for cell in pbg["cells"]:
if not isinstance(cell, dict) or set(cell.keys()) != REQUIRED_CELL_KEYS:
raise ValueError(f"Malformed typed cell in product_by_gate_contract: {cell!r}")
if any(not isinstance(v, str) or not v.strip() or _PLACEHOLDER_TOKEN_RE.search(v) for v in cell.values()):
raise ValueError(f"Empty, non-string, or placeholder field in typed cell {cell.get('product_variant_id')}:{cell.get('gate_id')}")
if cell["operator"] not in VALID_CELL_OPERATORS:
raise ValueError(f"Unrecognized typed cell operator {cell['operator']!r} on {cell['product_variant_id']}:{cell['gate_id']}")
if cell["disposition"] not in VALID_CELL_DISPOSITIONS:
raise ValueError(f"Unrecognized typed cell disposition {cell['disposition']!r} on {cell['product_variant_id']}:{cell['gate_id']}")
key = (cell["product_variant_id"], cell["gate_id"])
if key in cell_map:
raise ValueError(f"Duplicate product-by-gate cell: {key}")
cell_map[key] = cell
expected_pairs = {(p, g) for p in pc.STAGED_DESIGN_Y_V2_PRODUCT_IDS for g in EXPECTED_96_GATES}
if set(cell_map.keys()) != expected_pairs:
raise ValueError("Typed 96-cell product_by_gate_contract does not match exact 6 products x 16 gates Cartesian set")
# Verify exact per-(role, gate) operator semantics on all 96 typed cells!
for pvid in sorted(pc.STAGED_DESIGN_Y_V2_PRODUCT_IDS):
role = str(by_id[pvid]["staged_design_y_fullstack_v2_donor_binding"]["role"])
for gid in EXPECTED_96_GATES:
cell = cell_map[(pvid, gid)]
if role in expected_fullstack_roles:
exp_op = EXPECTED_FULLSTACK_GATE_OPERATORS[gid]
exp_disp = (
"REQUIRED_EXACT_PRODUCT"
if role == "FULL_CHR15_11TU_REFERENCE"
else ("REQUIRED_AFTER_PRIMARY_GATE0V_FAIL_AND_DELIVERY_HOLD" if gid == "Y-05" else "REQUIRED_AFTER_PRIMARY_GATE0V_FAIL")
)
elif role in ("SEQUENTIAL_STEP1_ATTB_GT_DONOR", "SEQUENTIAL_STEP2_ATTB_CA_DONOR") and gid == "Y-05":
exp_op, exp_disp = "CONJUNCTIVE_PASS", "COMPONENT_EVIDENCE_ONLY_EXCLUDED_FROM_FULLSTACK"
elif role == "DEC053_CHR13_CLYBL_SAFETY_SWITCH" and gid == "Y-09":
exp_op, exp_disp = "CONJUNCTIVE_PASS", "COMPONENT_EVIDENCE_ONLY_EXCLUDED_FROM_FULLSTACK"
elif role == "EQUAL_SPACING_ATTRIBUTION_CONTROL" and gid in ("Y-05", "Y-07"):
exp_op, exp_disp = "COMPARATOR_REFERENCE_ONLY", "CONTROL_BENCHMARK_ONLY_EXCLUDED_FROM_FULLSTACK"
elif gid == "STAGE0_ENDPOINT_CROSSWALK":
exp_op = "EXCLUDED_FROM_FULLSTACK_CLEARANCE"
exp_disp = (
"CONTROL_BENCHMARK_ONLY_EXCLUDED_FROM_FULLSTACK"
if role == "EQUAL_SPACING_ATTRIBUTION_CONTROL"
else "COMPONENT_EVIDENCE_ONLY_EXCLUDED_FROM_FULLSTACK"
)
else:
exp_op, exp_disp = "NOT_APPLICABLE", "NOT_APPLICABLE_EXCLUDED_FROM_FULLSTACK"
if cell["operator"] != exp_op or cell["disposition"] != exp_disp:
raise ValueError(
f"Typed cell operator/disposition mismatch on {pvid}:{gid}: "
f"got ({cell['operator']!r}, {cell['disposition']!r}), expected ({exp_op!r}, {exp_disp!r})"
)
dt_y_rule = str((dec113_blk.get("rules") or {}).get("y05_y09_design_y_fullstack_v2_gates") or "")
dt_r3p_rule = str((dec113_blk.get("rules") or {}).get("r3p01_r3p06_modular_flat_ribbon_planar_envelope_gates") or "")
dt_xwalk = str((dec113_blk.get("rules") or {}).get("stage0_endpoint_crosswalk") or "")
pb_clean = pb_sec_full.replace("`", "")
# Contradiction guards (reject sign reversals, unpinned floor approximations, or broken triggers in ANY doc/cell)
forbidden_patterns = (
(r"(?i)iCasp9\s+kill\s*\(?<=\s*1e-8", "Y-04 sign-reversed 'kill <= 1e-8'"),
(r"(?i)passes\s+Gate\s+0V", "reversed backup trigger 'passes Gate 0V'"),
(r"n_eff\s*=\s*floor\(", "forbidden floor(n_raw*eta) approximation"),
(r"(?i)3x\s+ectopic[- ]GPI", "misleading '3x' GPI wording instead of '3 ectopic GPI'"),
)
all_checked_texts: List[tuple[str, str]] = [
("decision_tree.y05_y09", dt_y_rule),
("decision_tree.r3p01_r3p06", dt_r3p_rule),
("decision_tree.crosswalk", dt_xwalk),
("playbook.sec4119", pb_clean),
]
for (cpvid, cgid), cobj in sorted(cell_map.items()):
all_checked_texts.append((f"typed_cell.{cpvid}:{cgid}", json.dumps(cobj, ensure_ascii=False)))
for pvid in sorted(pc.STAGED_DESIGN_Y_V2_PRODUCT_IDS):
all_checked_texts.append((f"registry.{pvid}", json.dumps(by_id[pvid], ensure_ascii=False)))
for dlabel, dtxt in all_checked_texts:
for pat, desc in forbidden_patterns:
if re.search(pat, dtxt):
raise ValueError(f"Contradiction guard tripped ({desc}) in {dlabel}")
# Direct typed-cell AND cross-document predicate concordance (gate_id, cell_threshold_regex, prose_regex)!
# Checks BOTH the actual typed cell thresholds in product_by_gate_contract AND all 3 controlling prose views!
predicate_specs: List[tuple[str, str, str, str]] = [
("Y-01_cbe_offtarget_0p10", "Y-01", r"CBE_offtarget_U95<=0\.10%", r"CBE\s+off-target\s+U95\s*<=\s*0\.10%"),
("Y-01_5_controls_explicit_se", "Y-01", r"5_supporting_controls==True;EXPLICIT_SE_SUPPLIED", r"EXPLICIT_SE_SUPPLIED"),
("Y-03_paracrine_gsis_adenosine_dpcpx", "Y-03", r"coculture_GSIS_SI_L95>=2\.5;GSIS_retention_L95>=90%;supernatant_adenosine_U95<=25\.0nM;DPCPX_GSIS_delta_U95<=10\.0%", r"2\.5[^;\n]{0,120}90%[^;\n]{0,120}25\.0\s*nM[^;\n]{0,120}10\.0%"),
("Y-04_escape_bound", "Y-04", r"clonogenic_escape_survival_U95<=1e-8\(k==0,N_eff>=299573228\)", r"clonogenic\s+escape/survival[^;\n]{0,60}<=\s*1(?:\.0)?e-8"),
("Y-04_standalone_gsis_3p0", "Y-04", r"obs_gsis_si_L95>=3\.0", r"obs_gsis_si[^;\n]{0,20}>=\s*3\.0"),
("Y-05_hold_interval", "Y-05", r"0\.8%.*1\.0%.*HOLD", r"0\.8%[^;\n]{0,30}1\.0%[^;\n]{0,25}HOLD"),
("Y-05_backup_hold", "Y-05", r"HOLD_PENDING_DEDICATED_12TU_BACKUP_DELIVERY_DONOR_SPEC", r"HOLD_PENDING_DEDICATED_12TU_BACKUP_DELIVERY_DONOR_SPEC"),
("Y-05_pigk_bound", "Y-05", r"CD59_and_CD47_IgV_GPI_ratio_L95>=0\.80", r"HOLD_PIGK_GPI_COMPETITION"),
("Y-05_cd47_floor", "Y-05", r"CD47_L95>=180000_molecules/cell", r"180,000"),
("Y-06_adcc_u95", "Y-06", r"ADCC_total_and_paired_IgG_U95<=5\.0%", r"ADCC\s+U95\s*<=\s*5\.0%"),
("Y-06_viral_u95", "Y-06", r"Gate0V_viral_k==0_U95<=0\.0005\(n>=5990\)", r"k\s*==\s*0[^;\n]{0,70}0\.0005[^;\n]{0,45}5,990"),
("Y-06_c5b9_u95", "Y-06", r"C5b9_U95<=5\.0%", r"C5b-9\s+U95\s*<=\s*5\.0%"),
("Y-07_il1rn_window", "Y-07", r"IL1Ra:IL1beta_in_\[10x,100x\]", r"10[-–]100x"),
("Y-07_conjunctive_si_auc", "Y-07", r"pulse1_and_pulse2_SI_and_AUC", r"SI\s+AND\s+first-phase\s+AUC"),
("Y-07_lcb_0p85", "Y-07", r"L95>=0\.85", r"0\.85"),
("Y-08_vtcn1_fsp1", "Y-08", r"VTCN1_shed_U95_t<=10\.0%;FSP1_AIFM2_viable_L95_t>=80\.0%", r"10%[^;\n]{0,90}80%"),
("Y-09_leak_and_4log", "Y-09", r"G0_Cpep\+_Ki67-_leak_U95_t<=0\.1%;AZT_dividing_log10_reduction_L95_t>=4\.0.*ZM447439<=0\.005uM", r"0\.1%[^;\n]{0,120}4-log10[^;\n]{0,200}0\.005\s*uM"),
("R3P-01_clearance", "R3P-01", r"d_cluster<H_slot;d_cluster\+2\*fibrin<=H_slot", r"d_cluster\s*<\s*H_slot\s+and\s+d_cluster\s*\+\s*2\*fibrin\s*<=\s*H_slot"),
("R3P-02_per_ribbon", "R3P-02", r"F_pull<=15\.0N_per_individually_extracted_ribbon", r"15\.0\s*N[^;\n]{0,45}ribbon"),
("R3P-03_ceus_30mmhg", "R3P-03", r"per_envelope_pO2>=30\.0mmHg_AND_CEUS_Doppler", r"CEUS/Doppler[^;\n]{0,60}30\.0\s*mmHg"),
("R3P-04_oxygen_shutoff", "R3P-04", r"Day0_worst_face>=15\.0mmHg;Day0_core>=5\.0mmHg;post_anastomosis_2p5x_GSIS_core>=5\.0mmHg;empirical_chamber_corrected_fall_t50<3\.0min", r"15\.0[^\n]{0,80}5\.0\s*mmHg[^\n]{0,180}3\.0\s*min"),
("R3P-05_single_dose_93350", "R3P-05", r"single_dose_93350_holds_at_3\.20909e-5", r"93,350[^;\n]{0,120}3\.20909e-5"),
("R3P-05_provenance_alpha", "R3P-05", r"f_clonogenic_provenance_and_alpha_allocation\(alpha_eta>=0\.05_when_eta<1", r"alpha_eta\s*>=\s*0\.05"),
("R3P-06_ada_targets", "R3P-06", r"140_180_vs_noncritical_perioperative_100_180_mg_dL", r"140[-–]180[^;\n]{0,80}100[-–]180\s*mg/dL"),
]
dt_combined = dt_y_rule + "\n" + dt_r3p_rule
for doc_name, blob in (
("decision_tree.rules", dt_combined),
("decision_tree.crosswalk", dt_xwalk),