OpenIslet

scripts/verify_iip0042_master_multilayer_portfolio_crosswalk.py

IIP-0042 / DEC-121 (CAND-033 / EXP-030): Master Exact 2^20 Multi-Layer Portfolio

script Release v0.8.0 gen-eb955f8266035aba 881 KB · 63 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_iip0042_master_multilayer_portfolio_crosswalk.py · SHA-256: 16964a158458b5cf…

                continue

            scan_txt = raw_txt
            if rel == "data/extracted/iip0044_tier1_metrics_cleanroom_summary_v0.8.0.json":
                scan_txt = strip_verified_iip0044_tier2_exclusion_manifest(raw_txt, rel)

            assert_public_hygiene_clean(
                scan_txt,
                rel,
                check_currency=False,
                check_vendor=False,
                check_coords=True,
                allow_authorized_coord_file=is_auth_coord,
            )
            if is_auth_coord:
                authorized_coord_files_verified.append(rel)
            public_inventory_scanned += 1

        # 1b. Declared-manifest completeness, mandatory 17/17 pre-Wave-5 structure pins & EXACT disk-membership check!
        if not isinstance(mf.get("public_redistribution_allowlist_spec"), dict):
            raise RuntimeError(
                "Gate 30-TOS-QUARANTINE fail-closed: manifest.json missing 'public_redistribution_allowlist_spec' "
                "required to verify declared public inventory completeness"
            )
        auth_spec = mf["public_redistribution_allowlist_spec"]
        auth_inc = auth_spec.get("public_package_included_paths")
        auth_exc = auth_spec.get("local_research_cache_excluded_from_public_bundle", [])
        if not isinstance(auth_inc, list) or len(auth_inc) == 0:
            raise RuntimeError(
                "Gate 30-TOS-QUARANTINE fail-closed: public_redistribution_allowlist_spec.public_package_included_paths empty"
            )
        all_manifest_artifacts = _extract_manifest_inventory_paths(artifacts_obj, "artifacts")
        expected_allowlisted_public = {
            rel
            for rel in all_manifest_artifacts
            if not any(fnmatch.fnmatch(rel, pat) for pat in auth_exc)
            and any(fnmatch.fnmatch(rel, pat) for pat in auth_inc)
        }
        pub_rel_set = set(pub_rels)
        missing_allowlisted = sorted(expected_allowlisted_public - pub_rel_set)
        if missing_allowlisted:
            raise RuntimeError(
                f"Gate 30-TOS-QUARANTINE fail-closed: incomplete/truncated public inventory omits "
                f"{len(missing_allowlisted)} allowlisted manifest artifacts (sample: {missing_allowlisted[:5]})"
            )
        required_wave5_all = set(WAVE5_STRICT_IIP0042_PUBLIC_FILES) | set(WAVE5_STRICT_4CLASS_PUBLIC_FILES)
        missing_wave5_in_manifest = sorted(required_wave5_all - pub_rel_set)
        if missing_wave5_in_manifest:
            raise RuntimeError(
                f"Gate 30-TOS-QUARANTINE fail-closed: public manifest inventory missing declared Wave-5 files: "
                f"{missing_wave5_in_manifest}"
            )
        verified_coord_set = set(authorized_coord_files_verified)
        if (
            len(authorized_coord_files_verified) != len(AUTHORIZED_PRE_WAVE5_PUBLIC_COORDINATE_FILES)
            or verified_coord_set != AUTHORIZED_PRE_WAVE5_PUBLIC_COORDINATE_FILES
        ):
            missing_coords = sorted(AUTHORIZED_PRE_WAVE5_PUBLIC_COORDINATE_FILES - verified_coord_set)
            raise RuntimeError(
                f"Gate 30-TOS-QUARANTINE fail-closed: incomplete pre-Wave-5 structure verification coverage "
                f"({len(verified_coord_set)}/{len(AUTHORIZED_PRE_WAVE5_PUBLIC_COORDINATE_FILES)} verified; "
                f"missing={missing_coords[:5]})"
            )
        structures_dir = openislet_root / "data" / "structures"
        if structures_dir.is_dir():
            disk_structs = {
                str(p.relative_to(openislet_root).as_posix())
                for p in structures_dir.rglob("*")
                if p.is_file() and p.suffix.lower() in (".cif", ".mmcif", ".pdb")
            }
            unmanifested_structs = sorted(disk_structs - AUTHORIZED_PRE_WAVE5_PUBLIC_COORDINATE_FILES)
            if unmanifested_structs:
                raise RuntimeError(
                    f"Gate 30-TOS-QUARANTINE fail-closed: unmanifested structure files under data/structures/: "
                    f"{unmanifested_structs}"
                )

        # 1c. Exact disk-membership check confirming ZERO unmanifested extra files!
        # Public-bundle mode & .openislet_public_bundle marker were verified symmetrically in Step 1.0 above.
        if is_public_bundle_mode:
            if (openislet_root / ".git").is_symlink():
                raise RuntimeError(
                    "Gate 30-TOS-QUARANTINE fail-closed: unsafe:.git symlink prohibited inside public bundle"
                )
            allowed_bundle_files = pub_rel_set | {"manifest.json", ".openislet_public_bundle"}
            unmanifested_extra: list[str] = []
            for p in openislet_root.rglob("*"):
                rel_p = p.relative_to(openislet_root).as_posix()
                if rel_p == ".git" or rel_p.startswith(".git/"):
                    continue
                if p.is_symlink():
                    raise RuntimeError(
                        f"Gate 30-TOS-QUARANTINE fail-closed: symlink prohibited inside public bundle: {rel_p}"
                    )
                if not p.is_dir():
                    pst = p.lstat()
                    if not stat.S_ISREG(pst.st_mode) or pst.st_nlink != 1:
                        raise RuntimeError(
                            f"Gate 30-TOS-QUARANTINE fail-closed: unsafe non-regular or multi-hardlink file inside public bundle: {rel_p}"
                        )
                    if rel_p not in allowed_bundle_files:
                        unmanifested_extra.append(rel_p)
            if unmanifested_extra:
                raise RuntimeError(
                    f"Gate 30-TOS-QUARANTINE fail-closed: {len(unmanifested_extra)} unmanifested extra file(s) "
                    f"in public bundle root (sample: {sorted(unmanifested_extra)[:5]})"
                )
            public_disk_membership_scope = "EXACT_PUBLIC_BUNDLE_ROOT"
            exact_disk_membership_verified = True
        else:
            # Local research checkout: verify ZERO unmanifested files anywhere matching public allowlist paths
            unmanifested_public_extra: list[str] = []
            for p in openislet_root.rglob("*"):
                rel_p = p.relative_to(openislet_root).as_posix()
                if rel_p == ".git" or rel_p.startswith(".git/"):
                    continue
                if not p.is_file():
                    continue
                if rel_p in ("manifest.json", ".openislet_public_bundle"):
                    continue
                if (
                    any(fnmatch.fnmatch(rel_p, pat) for pat in auth_inc)
                    and not any(fnmatch.fnmatch(rel_p, pat) for pat in auth_exc)
                    and rel_p not in pub_rel_set
                ):
                    unmanifested_public_extra.append(rel_p)
            if unmanifested_public_extra:
                raise RuntimeError(
                    f"Gate 30-TOS-QUARANTINE fail-closed: {len(unmanifested_public_extra)} unmanifested extra file(s) "
                    f"under public allowlist paths (sample: {sorted(unmanifested_public_extra)[:5]})"
                )
            public_disk_membership_scope = "ALLOWLISTED_PUBLIC_PATHS_IN_REPO_TREE"
            exact_disk_membership_verified = True

        declared_manifest_verified = bool(
            manifest_sha256_verified_count == len(pub_rels) and exact_disk_membership_verified
        )

    # Strict 4-class Wave-5 public surface scan across ALL 23 distinct installed Wave-5 public files (fail-closed if missing!)
    wave5_installed_scanned: list[str] = []
    for rel in WAVE5_STRICT_IIP0042_PUBLIC_FILES:
        fp = openislet_root / rel
        if not fp.is_file():
            raise FileNotFoundError(f"Gate 30-TOS-QUARANTINE fail-closed: missing declared Wave-5 file: {rel}")
        txt = fp.read_text(encoding="utf-8")
        if fp.suffix == ".md":
            txt = mask_canonical_layer2_disclaimer_only(txt)
        assert_public_hygiene_clean(txt, rel, vendor_token_set=_VENDOR_TOKENS)
        wave5_installed_scanned.append(rel)

    for rel in WAVE5_STRICT_4CLASS_PUBLIC_FILES:
        fp = openislet_root / rel
        if not fp.is_file():
            raise FileNotFoundError(f"Gate 30-TOS-QUARANTINE fail-closed: missing declared Wave-5 file: {rel}")
        txt = fp.read_text(encoding="utf-8")
        if fp.suffix == ".md":
            txt = mask_canonical_layer2_disclaimer_only(txt)
        elif rel == "data/extracted/iip0044_tier1_metrics_cleanroom_summary_v0.8.0.json":
            txt = strip_verified_iip0044_tier2_exclusion_manifest(txt, rel)
        assert_public_hygiene_clean(txt, rel, vendor_token_set=_COMMERCIAL_AI_VENDOR_TOKENS)
        wave5_installed_scanned.append(rel)

    # Extract and scan ALL 4 Wave-5 decision blocks (DEC-120..DEC-123) directly from stage0_decision_tree_v1.json (fail-closed!)
    dt_path = openislet_root / "data" / "protocols" / "stage0_decision_tree_v1.json"
    if not dt_path.is_file():
        raise FileNotFoundError(
            "Gate 30-TOS-QUARANTINE fail-closed: missing data/protocols/stage0_decision_tree_v1.json"
        )
    dt_obj = load_strict_json_text(dt_path.read_text(encoding="utf-8"), "stage0_decision_tree_v1.json")
    if not isinstance(dt_obj, dict):
        raise RuntimeError("stage0_decision_tree_v1.json must decode to a JSON object")
    dt_blocks_scanned: list[str] = []
    for key, mode_tag in WAVE5_REQUIRED_DECISION_TREE_BLOCKS:
        if key not in dt_obj:
            raise RuntimeError(
                f"Gate 30-TOS-QUARANTINE fail-closed: required Wave-5 decision-tree block missing: {key}"
            )
        vset = _VENDOR_TOKENS if mode_tag == "STRICT_IIP0042" else _COMMERCIAL_AI_VENDOR_TOKENS
        blk_txt = json.dumps(dt_obj[key], sort_keys=True, ensure_ascii=False)
        assert_public_hygiene_clean(blk_txt, f"stage0_decision_tree_v1.json::{key}", vendor_token_set=vset)
        if key == "DEC-121":
            _check_nct_prose_no_swaps(blk_txt, "stage0_decision_tree_v1.json::DEC-121")
        dt_blocks_scanned.append(key)

    extra_labels_scanned: list[str] = []
    if extra_wave5_texts:
        for lbl, txt in extra_wave5_texts.items():
            assert_public_hygiene_clean(txt, lbl, vendor_token_set=_VENDOR_TOKENS)
            extra_labels_scanned.append(lbl)

    coord_full_coverage = (
        len(authorized_coord_files_verified) == len(AUTHORIZED_PRE_WAVE5_PUBLIC_COORDINATE_FILES)
        and set(authorized_coord_files_verified) == AUTHORIZED_PRE_WAVE5_PUBLIC_COORDINATE_FILES
    )
    all_clean_flag = bool(declared_manifest_verified and coord_full_coverage)

    return {
        "inventory_source": inventory_source,
        "manifest_scan_mode": manifest_mode,
        "manifest_file_sha256": manifest_file_sha256,
        "declared_manifest_sha256_and_disk_membership_verified": declared_manifest_verified,
        "manifest_sha256_digests_verified_count": manifest_sha256_verified_count,
        "exact_public_disk_membership_verified": exact_disk_membership_verified,
        "public_disk_membership_scope": public_disk_membership_scope,
        "inventory_trust_boundary_note": _INVENTORY_TRUST_BOUNDARY_NOTE,
        "public_manifest_files_scanned": public_inventory_scanned,
        "authorized_pre_wave5_coordinate_files_expected_count": len(AUTHORIZED_PRE_WAVE5_PUBLIC_COORDINATE_FILES),
        "authorized_pre_wave5_coordinate_files_verified_count": len(authorized_coord_files_verified),
        "authorized_pre_wave5_coordinate_sha256_verified": coord_full_coverage,
        "wave5_4class_files_scanned_count": len(wave5_installed_scanned),
        "wave5_extra_texts_scanned_count": len(extra_labels_scanned),
        "decision_tree_blocks_scanned": dt_blocks_scanned,
        "negative_self_tests": neg_self_tests,
        "all_clean": all_clean_flag,
    }


def _mean_and_t95_ci(values: list[float], label: str) -> tuple[float, float, float, float, float]:
    """Return (mean, l95_t, u95_t, min_val, max_val) from strictly finite donor-level values (overflow-immune)."""
    if not isinstance(values, list) or len(values) < 2:
        raise ValueError(f"{label} requires a list of >= 2 donor observations")
    nums = [require_finite_number(v, f"{label}[{i}]") for i, v in enumerate(values)]
    n = len(nums)
    scale_abs = max(abs(x) for x in nums)
    if scale_abs == 0.0:
        return 0.0, 0.0, 0.0, 0.0, 0.0
    mean_scaled = sum(x / scale_abs for x in nums) / float(n)
    mean = mean_scaled * scale_abs
    devs = [(x / scale_abs) - mean_scaled for x in nums]
    max_dev = max(abs(d) for d in devs)
    if max_dev == 0.0:
        return mean, mean, mean, min(nums), max(nums)
    norm_devs = [d / max_dev for d in devs]
    se_scaled = (math.sqrt(sum(d * d for d in norm_devs) / float(n - 1)) / math.sqrt(float(n))) * max_dev
    half_scaled = _student_t_95_critical(n - 1) * se_scaled
    return mean, (mean_scaled - half_scaled) * scale_abs, (mean_scaled + half_scaled) * scale_abs, min(nums), max(nums)


_XREACT_REQUIRED_STRATA = (
    "sc_islet_cd64t_null",
    "sc_islet_cd64t_pos",
    "iec_cd64t_null",
    "iec_cd64t_pos",
)
_XREACT_CD64T_POS_STRATA = ("sc_islet_cd64t_pos", "iec_cd64t_pos")
_XREACT_SC_ISLET_STRATA = ("sc_islet_cd64t_null", "sc_islet_cd64t_pos")
_XREACT_IEC_STRATA = ("iec_cd64t_null", "iec_cd64t_pos")
_XREACT_REQUIRED_DOSES_UG_ML = (0.0, 1.0, 5.0, 15.0, 50.0)
_XREACT_CLINICAL_BRACKET_DOSES_UG_ML = (1.0, 5.0, 15.0)
_XREACT_INDEPENDENT_IGG_LOT_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{1,63}$")