OpenIslet

scripts/verify_iip0043_wholegraft_gate0v_and_calibration.py

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

script Release v0.8.0 gen-eb955f8266035aba 1008 KB · 76 sections

Use this file in any AI chat (paste-only or attachment-capable):

Download as text (.txt) Download section (.txt)

Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0043_wholegraft_gate0v_and_calibration.py · SHA-256: 20706180ed1ed6a2…

            "route3p_hybrid333_h180_30mmhg_nominal_65um_mmhg": round(r3p_h180_30_nom_live, 4),
            "route3p_hybrid333_h180_30mmhg_krbh_65um_FAIL_mmhg": round(r3p_h180_30_krbh_live, 4),
            "route3p_hybrid333_h180_35mmhg_vpio120_mmhg": round(r3p_h180_35_vpio120_live, 4),
            "route1_350um_staggered_pureplus10_nx80_mmhg": round(r1_350_p10_live, 4),
            "route1_390um_staggered_coupledplus10_nx80_mmhg": round(r1_390_cpl10_live, 4),
        },
        "true_3d_fvm_vascular_voxel_1p3164_replays": fvm_3d,
        "nw08_trigger_and_floor_unit_tests": trigger_tests,
        "nw08_live_dispatch_solver_tests": live_dispatch_tests,
        "five_lineage_source_typed_calibration_matrix": calibration_table_5lineages,
        "layer4_oxygen_margin_linearized_screen_nominal_routes": regime_rows,
        "marginal_live_corners_margin_uncertainty_triggers": marginal_corners,
        "nw08_r14_numerical_and_statistical_policy": {
            "mesh_convergence_policy_version": NW08_MESH_CONVERGENCE_POLICY_VERSION,
            "near_floor_trigger_bands_by_route_family_mmhg": {
                k: [CANONICAL_NW08_PO2_FLOOR_MMHG + lo, CANONICAL_NW08_PO2_FLOOR_MMHG + hi]
                for k, (lo, hi) in NW08_MESH_CONVERGENCE_TRIGGER_BANDS_BY_FAMILY.items()
            },
            "safety_factor_fs": NW08_MESH_CONVERGENCE_SAFETY_FACTOR_FS,
            "admissible_asymptotic_order_range_p": [
                NW08_MESH_CONVERGENCE_MIN_ADMISSIBLE_ORDER_P,
                NW08_MESH_CONVERGENCE_MAX_ADMISSIBLE_ORDER_P,
            ],
            "formal_order_cap_p": NW08_MESH_CONVERGENCE_FORMAL_ORDER_P,
            "upward_order_clamping_prohibited": True,
            "predeclared_grid_ladders_by_route_family": {
                "R1_390": [[80, 80, 78], [96, 96, 94], [112, 112, 109]],
                "R1_350": [[80, 80, 70], [96, 96, 84], [112, 112, 98]],
                "R2": [[48, 48, 28], [72, 72, 42], [96, 96, 56]],
                "R3P": [[28, 28, 32], [42, 42, 48], [56, 56, 64]],
            },
            "straddling_verdict_token": NW08_HOLD_TOKEN_STRADDLES_FLOOR,
            "unqualified_slow_or_non_asymptotic_order_verdict_token": NW08_HOLD_TOKEN_UNQUALIFIED_ORDER,
            "inferential_model_requires_positive_se_token": NW08_HOLD_TOKEN_INFERENTIAL_REQUIRES_POSITIVE_SE,
            "mesh_uncertainty_status_taxonomy": {
                "single_grid_policy_pass": NW08_MESH_STATUS_SINGLE_GRID_POLICY_PASS,
                "single_grid_policy_fail": NW08_MESH_STATUS_SINGLE_GRID_POLICY_FAIL,
                "three_grid_monotone_fallback": NW08_MESH_STATUS_THREE_GRID_MONOTONE_FALLBACK,
                "three_grid_asymptotic_gci_qualified": NW08_MESH_STATUS_THREE_GRID_ASYMPTOTIC_GCI_QUALIFIED,
                "three_grid_oscillatory_bound": NW08_MESH_STATUS_THREE_GRID_OSCILLATORY_BOUND,
                "three_grid_unqualified_order_hold": NW08_MESH_STATUS_THREE_GRID_UNQUALIFIED_ORDER_HOLD,
            },
            "allowed_ocr_uncertainty_models": sorted(NW08_ALLOWED_OCR_UNCERTAINTY_MODELS),
            "student_t_one_sided_95_df1_outward_upper": exact_student_t_one_sided_95(1),
            "student_t_one_sided_95_df5_n6": round(exact_student_t_one_sided_95(5), 7),
            "student_t_outward_upper_enclosure_enforced": True,
            "normal_z_repeated_sampling_coverage_at_df5": round(
                exact_student_t_cdf(MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95, 5), 6
            ),
            "bare_positive_se_without_model_or_df_rejected_token": "HOLD_NW08_OCR_MISSING_UNCERTAINTY_MODEL_OR_DF",
            "process_wide_fvm_lock_and_callback_owner_serialized": True,
            "isolated_child_subprocess_solver_execution": True,
            "per_root_solver_module_origin_verified": True,
        },
        "calibration_and_trigger_policy": (
            "True route-specific 3D FVM vascular-voxel replay (m_vasc = 1.3164, gated on native UNROUNDED float64 "
            "face minima >= 15.0 mmHg and predeclared 3-grid numerical convergence inside route-family near-floor "
            "bands [R1: 14.88-15.25, R2: 14.75-15.25, R3P: 14.70-15.30 mmHg] under NASA/Roache GCI and ASME V&V-20 "
            "oscillatory half-range bounds with Fs = 1.25 and NO upward clamping of sub-asymptotic order p_obs < 0.5) "
            "confirms all 3 nominal routes pass comfortably (R1 390 um: 16.9277, R2 Design Z: 23.7724, R3P 35 mmHg: "
            "19.8121 mmHg). On near-floor stress corners, R1 390 Coupled+10% at +9.09% (1.3164: 80x80x78=15.0741, "
            "96x96x94=14.9753, 112x112x109=15.0638; interval [14.9629, 15.0864]), R2 Design Z at bed 32 mmHg / 2.09975 "
            "(48x48x28=14.9898, 72x72x42=15.0237, 96x96x56=15.1380; interval [14.9527, 15.3234]), and R1 350 baseline "
            "(15.0394, 14.8640, 14.9211; interval [14.8421, 15.0613]) straddle 15.0 mmHg across predeclared grids and "
            "route to unresolved HOLD (HOLD_NW08_MESH_CONVERGENCE_STRADDLES_15MMHG_FLOOR, exit 2) before any coupled "
            "authorization. Monotone sequences with sub-asymptotic slow observed order p_obs < 0.5 (e.g., synthetic "
            "R2 sequence 15.012547946, 15.011044645, 15.010000000 with p_obs=0.06 and true limit 14.95 < 15.0), "
            "non-positive order, extreme super-convergence (p_obs > 2.5), or non-asymptotic drift toward 15.0 mmHg "
            "NEVER clamp p upward to 0.5 and instead route fail-closed to HOLD "
            "(HOLD_NW08_MESH_CONVERGENCE_UNQUALIFIED_SLOW_OR_NON_ASYMPTOTIC_ORDER, interval_valid=False, exit 2). "
            "At +20% (1.44804), R1 390 Coupled+10% decisively FAILS across all three grids (14.8489, 14.7492, 14.8373; "
            "upper bound 14.8614 < 15.0). R3P VPIO120 at 1.3164 clears 15.0 mmHg monotonically away from the floor "
            "across all three grids (15.1005, 15.1059, 15.3084; conservative lower bound 15.0485 >= 15.0 -> PASS), "
            "while R1 350 um (14.8446), R3P Bed30 (14.9062), and R3P Bed30 KRBH (14.0951; already failing live at "
            "14.4198) decisively FAIL < 15.0 mmHg. Executable dispatch_and_solve_nw08_measured_ocr(...) requires "
            "explicit inferential model provenance whenever uncertainty_se > 0 (exact Student-t t_{0.95, df} for "
            "small-sample estimated SE, e.g. t_{0.95,5}=2.0150484 for n=6 replicates; scoped KNOWN_SIGMA_NORMAL with "
            "external calibration provenance; or INDEPENDENT_JUSTIFIED_UPPER_BOUND), rejects undeclared bare SE "
            "fail-closed, and serializes native Layer-4 callbacks process-wide across direct and composite-wrapper "
            "interfaces. Reported breach percentages are two-point linear extrapolations (not exact nonlinear 3D thresholds)."
        ),
    }


# ---------------------------------------------------------------------------
# Part C: Parameterized Protected Manifest, Playbook §4.1.20 Section Hash,
#         render_documentation.py Check & Case-Normalized CEG Diff
# ---------------------------------------------------------------------------
def verify_r4_playbook_decision_tree_and_renderer_compatibility(openislet_root: Path) -> Dict[str, Any]:
    """
    Read-only temp-dir & in-memory proof that Option-2 placement:
      - Adds dedicated block to stage0_decision_tree_v1.json (preserving DEC-114 block SHA-256)
      - Creates standalone docs/GATE-0V-WHOLEGRAFT-PROTOCOL.md
      - Leaves docs/STAGE-0-EXECUTION-PLAYBOOK.md §4.1.20 canonical section hash invariant
      - Passes render_documentation.render_text() cleanly on docs/GATE-0V-WHOLEGRAFT-PROTOCOL.md
        (recording authored vs post-render sizes & documenting that S5 MUST hash-pin the
        protocol doc AFTER running render_documentation.py at the end of the fold sequence!).
    """
    v35_path = openislet_root / "scripts" / "verify_iip0035_d1b_auto_and_portfolio.py"
    rd_path = openislet_root / "scripts" / "render_documentation.py"
    pb_path = openislet_root / "docs" / "STAGE-0-EXECUTION-PLAYBOOK.md"
    dt_path = openislet_root / "data" / "protocols" / "stage0_decision_tree_v1.json"
    if not (v35_path.is_file() and pb_path.is_file() and dt_path.is_file()):
        return {"tested": False, "passed": False, "reason": "Missing live IIP-0035 files"}

    spec = importlib.util.spec_from_file_location("v35_compat_probe", str(v35_path))
    if spec is None or spec.loader is None:
        return {"tested": False, "passed": False, "reason": "Could not load verify_iip0035 module"}
    v35 = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(v35)

    proto_authored = (
        "# Gate 0V Whole-Graft Viral Safety, Stress AP1903 Erasure & NW-08 Calibration Protocol (IIP-0043)\n\n"
        "Standalone companion protocol preserving Playbook §4.1.20 canonical section hash.\n"
        "Clinical release mandates composite PASS from both legacy wetlab_contract.py and "
        "verify_iip0043_wholegraft_gate0v_and_calibration.py on the same lot_id/mcb_id/payload_sha256.\n"
    )

    with tempfile.TemporaryDirectory() as td:
        tr = Path(td)
        (tr / "docs").mkdir(parents=True)
        (tr / "data" / "protocols").mkdir(parents=True)
        (tr / "docs" / "STAGE-0-EXECUTION-PLAYBOOK.md").write_bytes(pb_path.read_bytes())
        (tr / "docs" / "GATE-0V-WHOLEGRAFT-PROTOCOL.md").write_text(proto_authored, encoding="utf-8")
        dt_doc = strict_json_load_file(dt_path, preserve_boundary_decimals=False)
        dt_doc["wholegraft_gate0v_composite_and_nw08_calibration_iip_0043"] = {
            "decision_id": "DEC-122",
            "companion_protocol_doc": "docs/GATE-0V-WHOLEGRAFT-PROTOCOL.md",
            "required_evaluators": [
                "scripts/wetlab_contract.py",
                "scripts/verify_iip0043_wholegraft_gate0v_and_calibration.py",
                "scripts/evaluate_gate0v_composite_release.py",
            ],
            "graveyard_guardrail_id": GRAVEYARD_GUARDRAIL_ID,
            "graveyard_card_id": GRAVEYARD_CARD_ID,
            "playbook_sec4120_untouched": True,
        }
        (tr / "data" / "protocols" / "stage0_decision_tree_v1.json").write_text(
            json.dumps(dt_doc, indent=2), encoding="utf-8"
        )
        pb_res = v35._verify_playbook_sec4120(tr, require_canonical_sha=True)
        dt_reloaded = strict_json_load_file(tr / "data" / "protocols" / "stage0_decision_tree_v1.json", preserve_boundary_decimals=False)
        dec114_blk = dt_reloaded["autologous_d1b_auto_c_v2_vanguard_gates_iip_0035"]
        dec114_sha = hashlib.sha256(
            json.dumps(dec114_blk, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
        ).hexdigest()
        dt_ok = dec114_sha == v35.EXPECTED_DEC114_DECISION_TREE_SHA256
        pb_ok = bool(pb_res.get("canonical_sha_verified"))
        pb_sec_sha = pb_res.get("controlling_playbook_sec4120_sha256")

    # Test render_documentation.py in-memory on docs/GATE-0V-WHOLEGRAFT-PROTOCOL.md
    renderer_check: Dict[str, Any] = {"tested": False, "passed": False}
    if rd_path.is_file():
        rd_spec = importlib.util.spec_from_file_location("rd_compat_probe", str(rd_path))
        if rd_spec is not None and rd_spec.loader is not None:
            rd_mod = importlib.util.module_from_spec(rd_spec)
            rd_spec.loader.exec_module(rd_mod)
            manifest_path = openislet_root / "manifest.json"
            pin_count = 0
            if manifest_path.is_file():
                m_obj = strict_json_load_file(manifest_path, preserve_boundary_decimals=False)
                if isinstance(m_obj, dict):
                    if isinstance(m_obj.get("artifacts"), (list, dict)):
                        pin_count = len(m_obj["artifacts"])
                    elif isinstance(m_obj.get("files"), (list, dict)):
                        pin_count = len(m_obj["files"])
                    else:
                        pin_count = len(m_obj)
            # In public-bundle mode (where islet1_candidate_stack_rankings.json is excluded from public export),
            # load the pinned identical data/extracted/documentation_facts_v0.8.0.json so post_render_bytes
            # matches full-repo derive_facts(repo, 1643) byte-for-byte (B8)!
            facts_json_path = openislet_root / "data" / "extracted" / "documentation_facts_v0.8.0.json"
            rankings_path = openislet_root / "data" / "extracted" / "islet1_candidate_stack_rankings.json"
            if facts_json_path.is_file() and (_is_public_bundle(openislet_root) or not rankings_path.is_file()):
                facts = strict_json_load_file(facts_json_path, preserve_boundary_decimals=False)
                facts_source = "pinned_documentation_facts_v0.8.0.json"
            else:
                facts = rd_mod.derive_facts(openislet_root, pin_count)
                facts_source = "derived_from_repo_artifacts"
            rendered_doc = rd_mod.render_text(proto_authored, facts, "GATE-0V-WHOLEGRAFT-PROTOCOL.md")
            rendered_again = rd_mod.render_text(rendered_doc, facts, "GATE-0V-WHOLEGRAFT-PROTOCOL.md")
            idempotent = rendered_doc == rendered_again
            has_facts_block = "<!-- OPENISLET_GENERATED_FACTS_START -->" in rendered_doc
            has_scope_footer = "<!-- OPENISLET_CURRENT_LAYER_SCOPE -->" in rendered_doc
            renderer_check = {
                "tested": True,
                "facts_source": facts_source,
                "manifest_pin_count": pin_count,
                "authored_bytes": len(proto_authored.encode("utf-8")),
                "post_render_bytes": len(rendered_doc.encode("utf-8")),
                "generated_facts_block_inserted": has_facts_block,
                "layer_scope_footer_inserted": has_scope_footer,
                "render_idempotent_on_second_pass": idempotent,
                "post_render_pinning_rule": (
                    "render_documentation.py transforms every docs/*.md by injecting generated corpus facts and "
                    "layer-scope footers; therefore docs/GATE-0V-WHOLEGRAFT-PROTOCOL.md MUST be SHA-256 pinned "
                    "ONLY AFTER final render_documentation.py execution at the end of Stage S5."
                ),
                "passed": bool(has_facts_block and has_scope_footer and idempotent),
            }

    return {
        "tested": True,
        "non_breaking_placement": "stage0_decision_tree_v1.json dedicated block + standalone docs/GATE-0V-WHOLEGRAFT-PROTOCOL.md (Playbook §4.1.20 section hash pinned rather than whole-file hash)",
        "playbook_sec4120_expected_sha256": PLAYBOOK_SEC4120_EXPECTED_SHA256,
        "playbook_sec4120_actual_sha256": pb_sec_sha,
        "verify_iip0035_playbook_sec4120_canonical_sha_verified": pb_ok,
        "verify_iip0035_dec114_decision_tree_sha256_preserved": dt_ok,
        "render_documentation_protocol_doc_replay": renderer_check,
        "passed": bool(pb_ok and dt_ok and renderer_check.get("passed", False)),
    }


def verify_gy030_graveyard_parity(openislet_root: Path) -> Dict[str, Any]:
    """
    R03-B3: Programmatic parity check verifying that `GY-030` in
    `data/graveyard/idea_graveyard_v0.5.json` agrees with this verifier's exact
    true Clopper-Pearson negative-control bound (`U95 <= 0.15%` on `n >= 20,000`)
    and tier-specific PASS statuses (`PASS_WHOLEGRAFT_BANK_QUALIFICATION`,
    `PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE`, `PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL`),
    with zero stale generic PASS or `0.10%` control-bound instructions!
    """
    gy_path = openislet_root / "data" / "graveyard" / "idea_graveyard_v0.5.json"
    if not gy_path.is_file():
        return {"tested": True, "passed": False, "reason": "Missing data/graveyard/idea_graveyard_v0.5.json"}
    gy_doc = strict_json_load_file(gy_path, preserve_boundary_decimals=False)
    guards = gy_doc.get("off_grid_molecular_dead_end_guardrails", {}).get("guardrails", [])
    gy30 = next((g for g in guards if g.get("graveyard_card_id") == GRAVEYARD_CARD_ID), None)
    if not isinstance(gy30, dict):
        return {"tested": True, "passed": False, "reason": f"Missing {GRAVEYARD_CARD_ID} entry in idea_graveyard_v0.5.json"}

    assay_text = str(gy30.get("cheapest_falsification_assay") or "")
    summary_text = str(gy30.get("summary") or "")
    combined_text = assay_text + "\n" + summary_text

    required_pass_statuses = sorted(GATE0V_PASS_VERDICTS_BY_TIER.values())
    missing_pass_statuses = [st for st in required_pass_statuses if st not in assay_text]
    has_obsolete_generic_pass = "PASS_WHOLEGRAFT_GATE0V_AND_STRESS_AP1903" in combined_text
    has_exact_0p15_bound = "U95 <= 0.15%" in assay_text and "n >= 20,000" in assay_text
    has_stale_0p10_bound = bool(re.search(r"(?:<=|U95\s*<=)\s*0\.10%|0\.10%\s*UCL", assay_text))
    has_trusted_store_ref = "--trusted-qualification-store" in assay_text
    metadata_ok = bool(
        gy30.get("guardrail_id") == GRAVEYARD_GUARDRAIL_ID
        and gy30.get("severity_level") == "BLOCK"
        and gy30.get("contribution_id") == "IIP-0043"
    )
    passed = bool(
        metadata_ok
        and len(missing_pass_statuses) == 0
        and (not has_obsolete_generic_pass)