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…

    5-file Tier-2 carve-out list inside IIP-0044 summary JSON BEFORE masking it for Tier-2 scanning.
    Rejects nested dicts/lists, floats/scores, extra keys, or non-canonical values before masking.
    """
    obj = load_strict_json_text(json_text, label)
    if not isinstance(obj, dict):
        raise ValueError(f"{label} must be a JSON object")
    scb = obj.get("source_cleanroom_bundle")
    if isinstance(scb, dict) and "excluded_tier2_carveout_files_5" in scb:
        carveouts = scb["excluded_tier2_carveout_files_5"]
        if not isinstance(carveouts, list) or len(carveouts) != 5:
            raise RuntimeError(f"Invalid excluded_tier2_carveout_files_5 length in {label}")
        seen_paths: set[str] = set()
        for item in carveouts:
            if not isinstance(item, dict) or set(item.keys()) != _ALLOWED_CARVEOUT_ITEM_KEYS:
                raise RuntimeError(f"Unauthorized keys in excluded_tier2_carveout_files_5 entry in {label}")
            rp = item["relpath"]
            if type(rp) is not str or rp not in EXPECTED_IIP0044_TIER2_CARVEOUT_RELPATHS or rp in seen_paths:
                raise RuntimeError(f"Unexpected or duplicate Tier-2 carveout relpath in {label}: {rp!r}")
            seen_paths.add(rp)
            sh = item["sha256"]
            if type(sh) is not str or not _RE_SHA256_HEX.match(sh):
                raise RuntimeError(f"Invalid lowercase 64-hex sha256 in Tier-2 carveout entry {rp}")
            bsize = item["bytes"]
            if type(bsize) is not int or bsize <= 0:
                raise RuntimeError(f"Tier-2 carveout entry {rp} must declare positive integer bytes, got {bsize!r}")
            tier_val = item["tier"]
            if type(tier_val) is not str or tier_val != _EXPECTED_CARVEOUT_TIER:
                raise RuntimeError(f"Invalid tier metadata in Tier-2 carveout entry {rp}: {tier_val!r}")
            lic_val = item["license_terms"]
            if type(lic_val) is not str or lic_val != _EXPECTED_CARVEOUT_LICENSE_TERMS:
                raise RuntimeError(f"Invalid license_terms metadata in Tier-2 carveout entry {rp}: {lic_val!r}")
            if item["deposited_in_openislet"] is not False:
                raise RuntimeError(f"Tier-2 carveout entry {rp} must declare deposited_in_openislet=false")
            if type(item["numeric_outputs_included"]) is not int or item["numeric_outputs_included"] != 0:
                raise RuntimeError(f"Tier-2 carveout entry {rp} must declare integer numeric_outputs_included=0")
            rat = item["carveout_rationale"]
            if type(rat) is not str or not (1 <= len(rat) <= 240):
                raise RuntimeError(f"Tier-2 carveout rationale for {rp} must be a concise scalar string (<=240 chars)")
            rat_no_cc = rat.replace("CC-BY-4.0", "CC_BY_FOUR")
            if _RE_CARVEOUT_FORBIDDEN_SCORE.search(rat_no_cc) or re.search(r"\b\d+\.\d+\b", rat_no_cc):
                raise RuntimeError(f"Prohibited numeric score or metric keyword inside carveout rationale for {rp}: {rat!r}")
            # Validate all non-relpath fields carry ZERO Tier-2 markers, coordinates, home paths, or currency
            non_rp_str = json.dumps({k: v for k, v in item.items() if k != "relpath"}, ensure_ascii=False)
            sub_counts = scan_public_hygiene_text(
                non_rp_str, f"{label}::carveout_meta[{rp}]", check_vendor=False
            )
            if any(v > 0 for v in sub_counts.values()):
                raise RuntimeError(f"Gate 30-TOS-QUARANTINE violation inside carveout metadata {rp}: {sub_counts}")
        if seen_paths != EXPECTED_IIP0044_TIER2_CARVEOUT_RELPATHS:
            raise RuntimeError(f"Incomplete excluded_tier2_carveout_files_5 set in {label}")
        scb_copy = dict(scb)
        del scb_copy["excluded_tier2_carveout_files_5"]
        obj_copy = dict(obj)
        obj_copy["source_cleanroom_bundle"] = scb_copy
        return json.dumps(obj_copy, ensure_ascii=False)
    return json_text


def _scan_plain_text_segment(
    text: str,
    *,
    check_currency: bool,
    check_vendor: bool,
    vendor_token_set: tuple[str, ...],
    check_coords: bool,
    allow_authorized_coord_file: bool,
    from_json_string: bool = False,
) -> dict[str, int]:
    norm = text.replace("\r\n", "\n").replace("\r", "\n")
    home_hits = len(_RE_LOCAL_HOME_PATH.findall(norm))
    currency_hits = len(_RE_CURRENCY.findall(norm)) if check_currency else 0
    low = norm.lower()
    vendor_hits = (
        sum(
            len(re.findall(r"(?<![a-z0-9])" + re.escape(tok) + r"(?![a-z0-9])", low))
            for tok in vendor_token_set
        )
        if check_vendor
        else 0
    )
    tier2_hits = sum(low.count(tok.lower()) for tok in _TIER2_HOSTED_TOKENS)
    if not check_coords or allow_authorized_coord_file:
        coord_hits = 0
    else:
        coord_hits = len(_RE_COORDINATE_ROW.findall(norm)) + len(_RE_EMBEDDED_COORDINATE_ROW.findall(norm))
        if from_json_string:
            coord_hits += len(_RE_JSON_MMCIF_TAG.findall(norm))
    return {
        "home_path_hits": home_hits,
        "currency_hits": currency_hits,
        "vendor_model_hits": vendor_hits,
        "tier2_hosted_numeric_hits": tier2_hits,
        "unauthorized_coordinate_row_hits": coord_hits,
    }


def scan_public_hygiene_text(
    text: str,
    label: str,
    *,
    check_currency: bool = True,
    check_vendor: bool = True,
    vendor_token_set: tuple[str, ...] = _VENDOR_TOKENS,
    check_coords: bool = True,
    allow_authorized_coord_file: bool = False,
) -> dict[str, int]:
    """Scan raw text AND (when valid JSON) every recursively decoded JSON string value against
    Gate 30-TOS-QUARANTINE classes without stripping arbitrary sections.
    """
    raw_counts = _scan_plain_text_segment(
        text,
        check_currency=check_currency,
        check_vendor=check_vendor,
        vendor_token_set=vendor_token_set,
        check_coords=check_coords,
        allow_authorized_coord_file=allow_authorized_coord_file,
        from_json_string=False,
    )
    stripped = text.lstrip()
    if stripped.startswith(("{", "[")):
        try:
            parsed = json.loads(text)
        except Exception:
            parsed = None
        if parsed is not None:
            dec_totals = {k: 0 for k in raw_counts}
            for s in _iter_decoded_json_strings(parsed):
                sc = _scan_plain_text_segment(
                    s,
                    check_currency=check_currency,
                    check_vendor=check_vendor,
                    vendor_token_set=vendor_token_set,
                    check_coords=check_coords,
                    allow_authorized_coord_file=allow_authorized_coord_file,
                    from_json_string=True,
                )
                for k, v in sc.items():
                    dec_totals[k] += v
            for k in raw_counts:
                if dec_totals[k] > raw_counts[k]:
                    raw_counts[k] = dec_totals[k]
    return raw_counts


def assert_public_hygiene_clean(
    text: str,
    label: str,
    *,
    check_currency: bool = True,
    check_vendor: bool = True,
    vendor_token_set: tuple[str, ...] = _VENDOR_TOKENS,
    check_coords: bool = True,
    allow_authorized_coord_file: bool = False,
) -> dict[str, int]:
    """Fail-closed Gate 30-TOS-QUARANTINE + public-prose hygiene scanner."""
    counts = scan_public_hygiene_text(
        text,
        label,
        check_currency=check_currency,
        check_vendor=check_vendor,
        vendor_token_set=vendor_token_set,
        check_coords=check_coords,
        allow_authorized_coord_file=allow_authorized_coord_file,
    )
    if any(v > 0 for v in counts.values()):
        raise RuntimeError(f"Gate 30-TOS-QUARANTINE / public hygiene violation in {label}: {counts}")
    return counts


def run_gate30_tos_quarantine_negative_self_tests() -> dict[str, Any]:
    """Built-in adversarial negative probes proving Gate 30-TOS-QUARANTINE catches every prohibited class,
    including coordinate rows hidden inside JSON strings and invalid carve-out metadata.
    """
    probes: list[tuple[str, str, str]] = [
        ("mac_home_path", "prefix " + _HOME_MAC + "alice/secret.txt", "home_path_hits"),
        ("linux_home_path", "prefix " + _HOME_LINUX + "bob/work/file.json", "home_path_hits"),
        ("win_home_path", "path C:\\" + "Users" + "\\carol\\notes.txt", "home_path_hits"),
        ("usd_dollar_amount", "cost $" + "250000 estimate", "currency_hits"),
        ("eur_symbol_amount", "cost \u20ac" + "1500 total", "currency_hits"),
        ("gbp_symbol_amount", "cost \u00a3" + "900 total", "currency_hits"),
        ("iso_eur_amount", "budget 4200 " + "EU" + "R planned", "currency_hits"),
        ("iso_gbp_amount", "budget GB" + "P 3100 planned", "currency_hits"),
        ("tier2_hosted_token", "copied " + _T2_TAG + "_s0.cif", "tier2_hosted_numeric_hits"),
        ("tier2_numeric_score", "score " + _TIER2_HOSTED_TOKENS[4], "tier2_hosted_numeric_hits"),
        ("pdb_atom_coordinate_row", "AT" + "OM      1  N   ALA A   1      11.104  13.207   2.100  1.00 20.00           N\n", "unauthorized_coordinate_row_hits"),
        ("mmcif_atom_site_row", "_atom" + "_site.group_PDB\n", "unauthorized_coordinate_row_hits"),
        (
            "json_string_pdb_coordinate_row",
            json.dumps({"note": "AT" + "OM      1  N   ALA A   1      11.104  13.207   2.100  1.00 20.00           N"}),
            "unauthorized_coordinate_row_hits",
        ),
        (
            "json_string_mmcif_coordinate_row",
            json.dumps({"note": "header\n_atom" + "_site.group_PDB"}),
            "unauthorized_coordinate_row_hits",
        ),
        ("vendor_model_token", "reviewed by " + _COMMERCIAL_AI_VENDOR_TOKENS[0], "vendor_model_hits"),
    ]
    results: dict[str, bool] = {}
    for pname, ptext, exp_key in probes:
        c = scan_public_hygiene_text(ptext, f"probe:{pname}")
        if c[exp_key] <= 0:
            raise RuntimeError(f"Gate 30-TOS-QUARANTINE self-probe {pname!r} failed to trigger {exp_key}: {c}")
        results[pname] = True
    # Positive URL control: public https://.../home/... URL MUST NOT false-trigger local home path
    url_ctrl = scan_public_hygiene_text("https://www.ncbi.nlm.nih.gov/home/about/policies/", "probe:url_control")
    if url_ctrl["home_path_hits"] != 0:
        raise RuntimeError(f"URL home-path control false-triggered: {url_ctrl}")
    # Narrow footer control: injecting a leak INSIDE the rendered footer block MUST still trigger!
    injected_footer = (
        "<!-- OPENISLET_CURRENT_LAYER_SCOPE -->\n"
        + _CANONICAL_LAYER2_QUARANTINE_SENTENCE
        + "\nInjected leak: "
        + _HOME_LINUX
        + "mallory/data \u20ac500\n"
        "<!-- OPENISLET_CURRENT_LAYER_SCOPE_END -->\n"
    )
    masked = mask_canonical_layer2_disclaimer_only(injected_footer)
    fc = scan_public_hygiene_text(masked, "probe:injected_footer")
    if fc["home_path_hits"] <= 0 or fc["currency_hits"] <= 0:
        raise RuntimeError(f"Narrow footer masking failed to catch injected footer leak: {fc}")
    # Carveout nested object / synthetic score probe MUST be rejected BEFORE masking!
    bad_carveout = {
        "source_cleanroom_bundle": {
            "excluded_tier2_carveout_files_5": [
                {
                    "relpath": rp,
                    "sha256": "a" * 64,
                    "bytes": 1000,
                    "tier": _EXPECTED_CARVEOUT_TIER,
                    "license_terms": _EXPECTED_CARVEOUT_LICENSE_TERMS,
                    "deposited_in_openislet": False,
                    "numeric_outputs_included": 0,
                    "carveout_rationale": {"nested_score": 0.91} if idx == 0 else "Excluded metadata only.",
                }
                for idx, rp in enumerate(sorted(EXPECTED_IIP0044_TIER2_CARVEOUT_RELPATHS))
            ]
        }
    }
    carveout_nested_rejected = False
    try:
        strip_verified_iip0044_tier2_exclusion_manifest(json.dumps(bad_carveout), "probe:nested_carveout")
    except RuntimeError:
        carveout_nested_rejected = True
    if not carveout_nested_rejected:
        raise RuntimeError("Carve-out schema validator failed to reject nested dict in carveout_rationale")
    return {
        "total_negative_probes": len(probes),
        "all_negative_probes_caught": True,
        "url_home_control_clean": True,