OpenIslet

scripts/verify_iip0035_d1b_auto_and_portfolio.py

Deterministic Autologous D1b-Auto-C v2 Mode-B Registry, 45-Cell Stage-0 Contract,

script Release v0.8.0 gen-eb955f8266035aba 288 KB · 23 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_iip0035_d1b_auto_and_portfolio.py · SHA-256: fedb990aeaedd116…

            "w_c4_p1_0p62_phi25_class_level_r1_r2_modular_pct": by_4["W_C4_4Arm_D1b@R3P_S2_Screened_p1=0.62_c4u0.92_phi=0.25"]["modular_k100_under_class_level_r1_r2_expansion_pct"],
            "w_c5_p1_0p62_phi50_locked_pct": by_4["W_C5_4Arm_D1b@R3P_S2_Screened_p1=0.62_c4u0.92_phi=0.50"]["locked_pct"],
            "w_u1_5arm_zero_h3_phi25_locked_pct": by_5["W_U1_5Arm_ZeroH3Lift_Y@3P_D1(p1=0.70)@3P_c4u0.92_phiYX0.75_25"]["locked_pct"],
            "w_u3_5arm_p1_0p62_registered_route_modular_pct": by_5["W_U3_5Arm_ZeroH3Lift_Y@3P_D1(p1=0.62)@3P_c4u0.92_phiYX0.75_25"]["modular_registered_route_only_k100_pct"],
            "w_u3_5arm_p1_0p62_r2_only_modular_pct": by_5["W_U3_5Arm_ZeroH3Lift_Y@3P_D1(p1=0.62)@3P_c4u0.92_phiYX0.75_25"]["modular_k100_under_r2_only_expansion_pct"],
            "w_u3_5arm_p1_0p62_class_level_r1_r2_modular_pct": by_5["W_U3_5Arm_ZeroH3Lift_Y@3P_D1(p1=0.62)@3P_c4u0.92_phiYX0.75_25"]["modular_k100_under_class_level_r1_r2_expansion_pct"],
            "w_u3_class_level_route_transfer_delta_pp": by_5["W_U3_5Arm_ZeroH3Lift_Y@3P_D1(p1=0.62)@3P_c4u0.92_phiYX0.75_25"]["class_level_route_transfer_delta_pp"],
            "w_u8_5arm_extreme_hostile_phi50_registered_locked_pct": by_5["W_U8_5Arm_EXTREME_HOSTILE_Y@3P(0.68)_D1(0.55,0.60)@R2_c4u90_phi50"]["locked_pct"],
            "w_u8_5arm_extreme_hostile_phi50_hypothetical_r2_locked_pct": by_5["W_U8_5Arm_EXTREME_HOSTILE_Y@3P(0.68)_D1(0.55,0.60)@R2_c4u90_phi50"]["locked_under_hypothetical_r2_transfer_pct"],
            "w_u9_5arm_ultra_hostile_phi50_registered_locked_pct": by_5["W_U9_5Arm_ULTRA_HOSTILE_phiYX1.0_Y@3P(0.68)_D1(0.55,0.60)@R2_c90"]["locked_pct"],
            "w_u9_5arm_ultra_hostile_phi50_hypothetical_r2_locked_pct": by_5["W_U9_5Arm_ULTRA_HOSTILE_phiYX1.0_Y@3P(0.68)_D1(0.55,0.60)@R2_c90"]["locked_under_hypothetical_r2_transfer_pct"],
            "w_u9_phi_c_0p625_registered_locked_pct": phi_c_cex[0]["locked_pct"],
            "w_u9_phi_c_0p625_hypothetical_r2_locked_pct": phi_c_cex[0]["locked_under_hypothetical_r2_transfer_pct"],
            "w_u9_phi_c_0p70_registered_locked_pct": phi_c_cex[1]["locked_pct"],
            "w_u9_phi_c_0p70_hypothetical_r2_locked_pct": phi_c_cex[1]["locked_under_hypothetical_r2_transfer_pct"],
            "w_u11_5arm_nested_upside_phi25_locked_pct": by_5["W_U11_5Arm_NestedY(90/92)_Y@Hyb3P_D1(p1=0.70)@3P_c4u0.92_phi25"]["locked_pct"],
            "autologous_p1_continuous_breakeven_exact": p1_exact,
            "scenario_alias_deduplication_map": alias_map,
        },
    }


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Deterministic autologous D1b-Auto-C v2, 45-cell contract, rare-event & 5-arm portfolio verifier (IIP-0035 / DEC-114)."
    )
    mode = parser.add_mutually_exclusive_group()
    mode.add_argument("--write", action="store_true", help=f"Write canonical JSON artifact to {DEFAULT_OUT_PATH}")
    mode.add_argument("--check", action="store_true", help=f"Verify byte-identical match against {DEFAULT_OUT_PATH} and {PORTFOLIO_5ARM_PATH}")
    mode.add_argument(
        "--eval-json",
        type=Path,
        default=None,
        help="Evaluate a raw Stage-0 observation JSON file preserving exact decimal numeric lexemes (parse_float=Decimal)",
    )
    args = parser.parse_args()

    if args.eval_json is not None:
        # Cryptographically verify product registry, 45-cell DEC-114 contract, and Playbook §4.1.20 BEFORE evaluating!
        _reg_audit, by_id = _resolve_and_verify_d1b_auto_v2_registry(ROOT)
        dt_doc = _load_json_strict(ROOT / DECISION_TREE_REL_PATH)
        dec114_blk = dt_doc["autologous_d1b_auto_c_v2_vanguard_gates_iip_0035"]
        req = parse_stage0_observation_json_exact(args.eval_json.read_text(encoding="utf-8"))
        if "observations" in req and not isinstance(req["observations"], dict):
            raise SystemExit("Invalid --eval-json payload: 'observations' must be a JSON object when provided (null/non-object rejected).")
        obs = req["observations"] if isinstance(req.get("observations"), dict) else req
        if obs is not req:
            _allowed_env_keys = frozenset({
                "observations", "product_variant_id", "product_def",
                "evaluated_lot_id", "mcb_lot_id", "lot_id", "batch_id", "mcb_batch_id",
                "global_gate0v_record",
            })
            _unknown_env_keys = sorted(k for k in req.keys() if k not in _allowed_env_keys)
            if _unknown_env_keys:
                raise SystemExit(
                    f"Invalid --eval-json envelope: unexpected top-level key(s) outside 'observations': {_unknown_env_keys}"
                )
        # Pass envelope fields directly into evaluate_stage0_d1b_auto_v2_gates_iip0035() WITHOUT pre-selecting
        # a product_def from distinct_pvids, guaranteeing 100% branch-for-branch parity with direct Python calls!
        env_pdef = req.get("product_def") if (obs is not req and "product_def" in req) else None
        env_pvid = req.get("product_variant_id") if obs is not req else None
        env_lots = (
            {
                k: req[k]
                for k in ("mcb_lot_id", "lot_id", "batch_id", "mcb_batch_id")
                if k in req and req[k] is not None
            }
            if obs is not req
            else None
        )
        res = evaluate_stage0_d1b_auto_v2_gates_iip0035(
            obs,
            product_def=env_pdef,
            product_variant_id=env_pvid,
            evaluated_lot_id=(req.get("evaluated_lot_id") if obs is not req else None),
            extra_lot_bindings=env_lots,
            global_gate0v_record=(
                req["global_gate0v_record"]
                if (obs is not req and "global_gate0v_record" in req)
                else _MISSING_ARG
            ),
            decision_tree_block=dec114_blk,
            repo_root=ROOT,
            require_canonical_sha=True,
        )
        print(json.dumps(res, indent=2, ensure_ascii=False, allow_nan=False))
        return

    payload = compute_full_verification(ROOT)
    serialized = json.dumps(payload, indent=2, ensure_ascii=False, allow_nan=False) + "\n"
    expected_bytes = serialized.encode("utf-8")
    expected_sha = hashlib.sha256(expected_bytes).hexdigest()

    if args.write:
        DEFAULT_OUT_PATH.parent.mkdir(parents=True, exist_ok=True)
        DEFAULT_OUT_PATH.write_bytes(expected_bytes)
        print(f"Wrote {DEFAULT_OUT_PATH} ({len(expected_bytes)} bytes, SHA-256={expected_sha})")
    elif args.check:
        if not DEFAULT_OUT_PATH.is_file():
            raise SystemExit(f"Missing verification artifact: {DEFAULT_OUT_PATH}")
        existing_bytes = DEFAULT_OUT_PATH.read_bytes()
        existing_sha = hashlib.sha256(existing_bytes).hexdigest()
        if existing_bytes != expected_bytes or existing_sha != expected_sha:
            raise SystemExit(
                f"Verification artifact byte/SHA-256 drift detected in {DEFAULT_OUT_PATH}: "
                f"found {existing_sha}, expected {expected_sha}"
            )
        if not PORTFOLIO_5ARM_PATH.is_file():
            raise SystemExit(f"Missing shipped 5-arm autologous portfolio artifact: {PORTFOLIO_5ARM_PATH}")
        shipped_p5_bytes = PORTFOLIO_5ARM_PATH.read_bytes()
        expected_p5 = rank_mod.compute_5arm_autologous_portfolio_iip0035(repo_root=ROOT)
        expected_p5_bytes = (
            json.dumps(expected_p5, indent=2, ensure_ascii=False, allow_nan=False) + "\n"
        ).encode("utf-8")
        shipped_p5_sha = hashlib.sha256(shipped_p5_bytes).hexdigest()
        expected_p5_sha = hashlib.sha256(expected_p5_bytes).hexdigest()
        if shipped_p5_bytes != expected_p5_bytes or shipped_p5_sha != expected_p5_sha:
            raise SystemExit(
                f"Shipped 5-arm autologous portfolio byte/SHA-256 drift detected in {PORTFOLIO_5ARM_PATH}: "
                f"found {shipped_p5_sha}, expected {expected_p5_sha}"
            )
        print(
            f"OK: {DEFAULT_OUT_PATH} (SHA-256={expected_sha}) and "
            f"{PORTFOLIO_5ARM_PATH} (SHA-256={expected_p5_sha}) match deterministic replay byte-for-byte."
        )
    else:
        print(serialized)


if __name__ == "__main__":
    main()