OpenIslet

scripts/verify_iip0050_islet_shield_coverage_and_debris_gate.py

Standalone Zero-LIMS-Touch Verifier & Executable Stage-0 Debris-Recall Evaluator for

script Release v0.8.0 gen-eb955f8266035aba 51 KB · 5 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_iip0050_islet_shield_coverage_and_debris_gate.py · SHA-256: b5a517900e706ea4…

        if p.is_file():
            dr_dp_counts[rel] = len(re_dr_dp.findall(p.read_text(encoding="utf-8")))

    gy = load_strict_json_file(repo_root / GRAVEYARD_REL)
    gy10 = next(
        (e for e in gy.get("graveyard_entries", []) if e.get("graveyard_id") == "GRAVEYARD_010_MHC_NULL_INDIRECT_APC_BYSTANDER_BLINDSPOT"),
        None,
    )
    if gy10 is None:
        raise RuntimeError("GRAVEYARD_010 entry missing in idea_graveyard_v0.5.json")
    gy10_blob = json.dumps(gy10, ensure_ascii=False)
    gy10_synced = all(
        tok in gy10_blob
        for tok in ("IIP-0050", "GATE-32", "HLA-DR", "HLA-DP", "33151102", "33841327", "32291282", "27798614", "27920090", "24550292")
    )
    dt = load_strict_json_file(repo_root / DECISION_TREE_REL)
    dt_blk = dt.get(DECISION_TREE_KEY)
    dt_synced = isinstance(dt_blk, dict) and dt_blk.get("gate_id") == GATE_ID and dt_blk.get("contribution_id") == CONTRIBUTION_ID

    return {
        "frozen_wave5_dr_dp_reference_counts": dr_dp_counts,
        "all_frozen_wave5_dr_dp_counts_zero": all(v == 0 for v in dr_dp_counts.values()) and len(dr_dp_counts) == 4,
        "gy010_logit_delta_preserved": gy10.get("evaluator_logit_delta") == -0.25,
        "gy010_severity_preserved": gy10.get("severity_level") == "WARN",
        "gy010_grid_entry_count": len(gy.get("graveyard_entries", [])),
        "offgrid_guardrail_count": len(gy.get("off_grid_molecular_dead_end_guardrails", {}).get("guardrails", [])),
        "gy010_iip0050_addendum_synced": gy10_synced,
        "decision_tree_gate32_block_synced": dt_synced,
    }


def build_verification_report(repo_root: Path) -> Dict[str, Any]:
    pin_checks: Dict[str, Dict[str, Any]] = {}
    for rel, expected in FROZEN_SHA256_PINS.items():
        actual = sha256_file(repo_root / rel)
        pin_checks[rel] = {
            "expected_sha256": expected,
            "actual_sha256": actual,
            "matched": actual == expected,
        }
        if actual != expected:
            raise RuntimeError(f"Frozen SHA-256 pin mismatch for {rel}: {actual} != {expected}")

    pb_sha = _extract_playbook_sec4120_sha256(repo_root / PLAYBOOK_REL)
    if pb_sha != EXPECTED_PLAYBOOK_SEC4120_SHA256:
        raise RuntimeError(f"Playbook sec 4.1.20 SHA-256 mismatch: {pb_sha} != {EXPECTED_PLAYBOOK_SEC4120_SHA256}")

    sc = load_strict_json_file(repo_root / SIDE_CONTRACT_REL)
    if sc.get("gate_id") != GATE_ID or sc.get("contribution_id") != CONTRIBUTION_ID:
        raise RuntimeError("Side contract gate_id/contribution_id mismatch")

    grid_2d = compute_exact_2d_coverage_pk_grid(repo_root)
    self_tests = run_gate32_decision_table_self_tests()
    audit = audit_wave5_dr_dp_baseline_and_gy010(repo_root)

    if not (
        audit["all_frozen_wave5_dr_dp_counts_zero"]
        and audit["gy010_logit_delta_preserved"]
        and audit["gy010_iip0050_addendum_synced"]
        and audit["decision_tree_gate32_block_synced"]
    ):
        raise RuntimeError(f"Audit check failed: {audit}")

    return {
        "schema_version": "iip0050_islet_shield_coverage_verification_v0.8.0",
        "contribution_id": CONTRIBUTION_ID,
        "decision_id": DECISION_ID,
        "gate_id": GATE_ID,
        "gate_alias": GATE_ALIAS,
        "generated_date": GENERATED_DATE,
        "live_headline_delta_pp_today": 0.0,
        "zero_lims_touch_and_wave5_pins": {
            "all_pins_matched": True,
            "playbook_sec4120_sha256_matched": True,
            "pins": pin_checks,
        },
        "exact_2pow20_2d_coverage_pk_sensitivity": grid_2d,
        "gate32_decision_table_self_tests": self_tests,
        "wave5_and_graveyard_audit": audit,
        "all_checks_passed": True,
    }


def main(argv: Optional[List[str]] = None) -> int:
    parser = argparse.ArgumentParser(description="IIP-0050 / Gate 32 verifier and debris-recall evaluator")
    parser.add_argument("--repo-root", type=Path, default=REPO_ROOT)
    parser.add_argument("--output", type=Path, default=None, help="Write deterministic verification JSON receipt")
    parser.add_argument("--check", action="store_true", help="Verify on-disk receipt matches recomputed output")
    parser.add_argument("--evaluate-debris-assay", type=Path, default=None, help="Evaluate a Stage-0 Gate 32 JSON payload")
    args = parser.parse_args(argv)

    if args.evaluate_debris_assay is not None:
        try:
            obs = load_strict_json_file(args.evaluate_debris_assay)
        except Exception as exc:
            err_out = {
                "gate_id": GATE_ID,
                "gate_alias": GATE_ALIAS,
                "verdict": "HOLD_INVALID_OR_MISSING_INPUT",
                "exit_code": 2,
                "channel_a_credit_cap_f": 0.0,
                "trackb_retirement_authorized": False,
                "trackb_atg_triggered": False,
                "reasons": [f"Strict JSON parse failure: {exc}"],
                "derived_summary": {},
            }
            print(json.dumps(err_out, indent=2, ensure_ascii=False))
            return 2
        res = evaluate_gate32_debris_recall(obs)
        print(json.dumps(res, indent=2, ensure_ascii=False))
        return int(res["exit_code"])

    report = build_verification_report(args.repo_root)
    rendered = json.dumps(report, indent=2, ensure_ascii=False) + "\n"

    if args.output is not None:
        args.output.parent.mkdir(parents=True, exist_ok=True)
        args.output.write_text(rendered, encoding="utf-8")
        print(f"Wrote {args.output} (all_checks_passed={report['all_checks_passed']})")
        return 0

    if args.check:
        target = args.repo_root / VERIFICATION_REL
        if not target.is_file():
            print(f"ERROR: Missing receipt {target}", file=sys.stderr)
            return 1
        actual = target.read_text(encoding="utf-8")
        try:
            actual_obj = json.loads(actual)
        except Exception as exc:
            print(f"ERROR: Invalid JSON in receipt {target}: {exc}", file=sys.stderr)
            return 1
        if actual != json.dumps(actual_obj, indent=2, ensure_ascii=False) + "\n":
            print(f"ERROR: On-disk receipt {target} fails canonical JSON formatting check", file=sys.stderr)
            return 1

        def _norm_parity_err(obj: dict, label: str) -> dict:
            out = json.loads(json.dumps(obj))
            sec = out.get("exact_2pow20_2d_coverage_pk_sensitivity")
            if not isinstance(sec, dict) or "max_parity_error_vs_iip0042_receipt" not in sec:
                raise ValueError(f"Missing max_parity_error_vs_iip0042_receipt in {label}")
            err = sec["max_parity_error_vs_iip0042_receipt"]
            if isinstance(err, bool) or not isinstance(err, (int, float)) or not math.isfinite(float(err)) or float(err) < 0.0 or float(err) > 1e-12:
                raise ValueError(f"Parity error out of [0, 1e-12] bound in {label}: {err!r}")
            sec["max_parity_error_vs_iip0042_receipt"] = "__PARITY_ERROR_BOUNDED_LE_1E12__"
            return out

        try:
            norm_actual = json.dumps(_norm_parity_err(actual_obj, "on-disk receipt"), indent=2, ensure_ascii=False) + "\n"
            norm_rendered = json.dumps(_norm_parity_err(report, "recomputed report"), indent=2, ensure_ascii=False) + "\n"
        except ValueError as exc:
            print(f"ERROR: {exc}", file=sys.stderr)
            return 1
        if norm_actual != norm_rendered:
            print(f"ERROR: On-disk receipt {target} drifts substantively from recomputed output", file=sys.stderr)
            return 1
        print(
            f"PASS: {target.name} verified (all substantive fields byte-exact; parity_err={report['exact_2pow20_2d_coverage_pk_sensitivity']['max_parity_error_vs_iip0042_receipt']:.2e} <= 1e-12) "
            f"| self_tests={report['gate32_decision_table_self_tests']['total_cases']}/{report['gate32_decision_table_self_tests']['total_cases']}"
        )
        return 0

    print(rendered)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())