scripts/verify_iip0044_foundry_v1_3_biologics.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0044_foundry_v1_3_biologics.py · SHA-256: 1d6c53a0817f6254…
def validate_islet_guard_eligibility(
arm_id: str,
route_id: str,
construct_id: str = ISLET_GUARD_CONSTRUCT_ID,
*,
side_contract: dict[str, Any] | Path | None = None,
) -> bool:
"""Callable-boundary-pinned Stage-0 registration & standalone gate eligibility evaluator
for Islet-GUARD (THBD M406L): enforces the frozen canonical policy ({'A', 'X'} on
ROUTE_1_CAO2_HYDROGEL for IsletGUARD_THBD_M406L) across all three call modes:
1. side_contract=None -> frozen in-code policy directly;
2. side_contract=Path -> raw file SHA-256 + canonical JSON SHA-256 + frozen policy parity;
3. side_contract=dict -> canonical JSON SHA-256 + frozen policy parity.
Rejects unknown arms/routes and any tampered or widened side contract fail-closed (ValueError).
"""
norm_arm = arm_id.strip().upper()
if norm_arm not in PORTFOLIO_ALL_ARMS:
raise ValueError(f"Unknown portfolio arm for Islet-GUARD eligibility check: {arm_id!r}")
raw_route = route_id.strip().upper()
if raw_route not in ROUTE_ALIAS_MAP:
raise ValueError(f"Unknown route_id for Islet-GUARD eligibility check: {route_id!r}")
norm_route = ROUTE_ALIAS_MAP[raw_route]
norm_construct = construct_id.strip()
if not norm_construct:
raise ValueError("Empty construct_id rejected fail-closed")
allowed_arms, allowed_routes, expected_construct, _ = _extract_guard_policy(side_contract)
return (
norm_arm in allowed_arms
and norm_route in allowed_routes
and norm_construct == expected_construct
)
def validate_islet_guard_arm_eligibility(
arm_id: str,
*,
route_id: str | None = None,
construct_id: str = ISLET_GUARD_CONSTRUCT_ID,
side_contract: dict[str, Any] | Path | None = None,
) -> bool:
"""Backward-compatible wrapper binding arm_id to its canonical portfolio route when route_id is omitted."""
norm_arm = arm_id.strip().upper()
if norm_arm not in PORTFOLIO_ALL_ARMS:
raise ValueError(f"Unknown portfolio arm for Islet-GUARD eligibility check: {arm_id!r}")
_, _, _, bindings = _extract_guard_policy(side_contract)
eff_route = bindings[norm_arm] if route_id is None else route_id
return validate_islet_guard_eligibility(
norm_arm,
eff_route,
construct_id=construct_id,
side_contract=side_contract,
)
def run_islet_guard_arm_restriction_tests(*, side_contract: dict[str, Any]) -> dict[str, Any]:
"""Verify callable-boundary-pinned Islet-GUARD restriction across arms, routes, constructs,
omitted side contract, and direct tampered/widened policy rejection (B4)."""
allowed_arms, allowed_routes, allowed_construct, _ = _extract_guard_policy(side_contract)
require_cond(
allowed_arms == frozenset({"A", "X"}),
f"Side contract Islet_GUARD allowed_route_arms must be ['A', 'X'], got {sorted(allowed_arms)}",
)
require_cond(
allowed_routes == frozenset({"ROUTE_1_CAO2_HYDROGEL"}),
f"Side contract Islet_GUARD allowed_route_ids must be ['ROUTE_1_CAO2_HYDROGEL'], got {sorted(allowed_routes)}",
)
require_cond(
allowed_construct == ISLET_GUARD_CONSTRUCT_ID,
f"Side contract Islet_GUARD allowed_construct_id must be {ISLET_GUARD_CONSTRUCT_ID!r}, got {allowed_construct!r}",
)
arm_results: dict[str, bool] = {}
for arm in PORTFOLIO_ALL_ARMS:
eligible = validate_islet_guard_arm_eligibility(arm, side_contract=side_contract)
expected = arm in ("A", "X")
require_cond(eligible == expected, f"Islet-GUARD arm restriction failed for arm {arm}: {eligible} != {expected}")
# Verify omitted side_contract matches canonical policy identically
require_cond(
validate_islet_guard_arm_eligibility(arm, side_contract=None) == expected,
f"Islet-GUARD omitted side_contract mismatch for arm {arm}",
)
arm_results[arm] = eligible
# Explicit (arm_id, route_id) matrix proving wrong-route A/X (R2, R3P, R3B) and R1-paired B/Y/D are rejected!
arm_route_matrix: dict[str, bool] = {}
for arm in PORTFOLIO_ALL_ARMS:
for route in PORTFOLIO_ALL_ROUTES:
eligible = validate_islet_guard_eligibility(arm, route, side_contract=side_contract)
expected = (arm in ("A", "X")) and (route == "ROUTE_1_CAO2_HYDROGEL")
require_cond(
eligible == expected,
f"Islet-GUARD (arm={arm}, route={route}) eligibility failed: got {eligible}, expected {expected}",
)
arm_route_matrix[f"{arm}@{route}"] = eligible
# Direct boundary tamper probe: widening allowed_route_arms to ["A", "X", "B"] MUST raise ValueError!
widened_sc = json.loads(json.dumps(side_contract))
widened_sc["programs_registered"]["Islet_GUARD"]["allowed_route_arms"] = ["A", "X", "B"]
widened_rejected = False
try:
validate_islet_guard_eligibility("B", "ROUTE_1_CAO2_HYDROGEL", side_contract=widened_sc)
except ValueError:
widened_rejected = True
require_cond(widened_rejected, "Direct validate_islet_guard_eligibility failed to reject widened arm ['A', 'X', 'B'] contract")
wrong_construct_rejected = not validate_islet_guard_eligibility(
"A", "ROUTE_1_CAO2_HYDROGEL", construct_id="IsletGUARD_THBD_WT", side_contract=side_contract
)
require_cond(wrong_construct_rejected, "Wrong construct_id on A@ROUTE_1_CAO2_HYDROGEL must be rejected")
unknown_arm_rejected = False
try:
validate_islet_guard_eligibility("Z_INVALID", "ROUTE_1_CAO2_HYDROGEL", side_contract=side_contract)
except ValueError:
unknown_arm_rejected = True
require_cond(unknown_arm_rejected, "Unknown arm must be rejected fail-closed")
unknown_route_rejected = False
try:
validate_islet_guard_eligibility("A", "ROUTE_99_INVALID", side_contract=side_contract)
except ValueError:
unknown_route_rejected = True
require_cond(unknown_route_rejected, "Unknown route_id must be rejected fail-closed")
return {
"policy_binding": "CALLABLE_BOUNDARY_FROZEN_POLICY_AND_PINNED_SIDE_CONTRACT_SHA256",
"pinned_side_contract_canonical_sha256": EXPECTED_IIP0044_SIDE_CONTRACT_CANONICAL_SHA256,
"enforcement_scope": "STAGE0_REGISTRATION_AND_STANDALONE_GATE_POLICY_0_00_PP_LIVE_CREDIT",
"allowed_arms": ["A", "X"],
"disallowed_arms": ["B", "Y", "D"],
"allowed_route_ids": ["ROUTE_1_CAO2_HYDROGEL"],
"allowed_construct_id": ISLET_GUARD_CONSTRUCT_ID,
"arm_eligibility_map": arm_results,
"wrong_route_ax_rejected": (
not arm_route_matrix["A@ROUTE_2_ANGIOGENIC_POUCH"]
and not arm_route_matrix["A@ROUTE_3P_PASSIVE_MACRO"]
and not arm_route_matrix["X@ROUTE_2_ANGIOGENIC_POUCH"]
and not arm_route_matrix["X@ROUTE_3P_PASSIVE_MACRO"]
and not arm_route_matrix["A@ROUTE_3B_ACTIVE_IEOG"]
),
"disallowed_arms_on_r1_rejected": (
not arm_route_matrix["B@ROUTE_1_CAO2_HYDROGEL"]
and not arm_route_matrix["Y@ROUTE_1_CAO2_HYDROGEL"]
and not arm_route_matrix["D@ROUTE_1_CAO2_HYDROGEL"]
),
"widened_side_contract_rejected_at_callable_boundary": widened_rejected,
"wrong_construct_rejected": wrong_construct_rejected,
"unknown_arm_rejected_fail_closed": unknown_arm_rejected,
"unknown_route_rejected_fail_closed": unknown_route_rejected,
"passed": True,
}
def _scan_tos_plain_segment(text: str, *, 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))
low = norm.lower()
tier2_hits = sum(low.count(tok.lower()) for tok in _TIER2_TOKENS)
vendor_hits = sum(
len(re.findall(r"(?<![a-z0-9])" + re.escape(tok) + r"(?![a-z0-9])", low))
for tok in _COMMERCIAL_AI_VENDOR_TOKENS
)
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,
"tier2_hosted_hits": tier2_hits,
"commercial_ai_vendor_hits": vendor_hits,
"unauthorized_coordinate_row_hits": coord_hits,
}
def scan_tos_quarantine_text(text: str, label: str) -> dict[str, int]:
"""Gate 30-TOS-QUARANTINE & public hygiene scanner for IIP-0044 artifacts.
Inspects BOTH raw text lines AND recursively decoded JSON string values (catching coordinate
rows, escaped paths, or restricted tokens hidden inside JSON strings).
"""
counts = _scan_tos_plain_segment(text, 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 counts}
for s in _iter_decoded_json_strings(parsed):
sc = _scan_tos_plain_segment(s, from_json_string=True)
for k, v in sc.items():
dec_totals[k] += v
for k in counts:
if dec_totals[k] > counts[k]:
counts[k] = dec_totals[k]
return counts
def require_tos_quarantine_clean(text: str, label: str) -> dict[str, int]:
counts = scan_tos_quarantine_text(text, label)
if any(v > 0 for v in counts.values()):
raise RuntimeError(f"Gate 30-TOS-QUARANTINE / hygiene violation in {label}: {counts}")
return counts
def run_tos_quarantine_negative_self_tests() -> dict[str, Any]:
probes = {
"mac_home_path_probe": ("prefix " + _HOME_MAC + "alice/file.txt", "home_path_hits"),
"linux_home_path_probe": ("prefix " + _HOME_LINUX + "bob/file.txt", "home_path_hits"),
"win_home_path_probe": ("prefix C:\\" + "Users" + "\\carol\\file.txt", "home_path_hits"),
"usd_currency_probe": ("budget $" + "1500 total", "currency_hits"),
"eur_currency_probe": ("budget \u20ac" + "1500 total", "currency_hits"),
"gbp_currency_probe": ("budget 900 " + "GB" + "P total", "currency_hits"),
"tier2_file_probe": ("copied " + _TIER2_TOKENS[0] + "_s0.cif", "tier2_hosted_hits"),
"tier2_numeric_probe": ("binding_confidence " + _TIER2_TOKENS[4], "tier2_hosted_hits"),
"commercial_ai_vendor_probe": ("reviewed by " + _COMMERCIAL_AI_VENDOR_TOKENS[0], "commercial_ai_vendor_hits"),
"pdb_coord_probe": ("AT" + "OM 1 N ALA A 1 11.104 13.207 2.100\n", "unauthorized_coordinate_row_hits"),
"mmcif_coord_probe": ("_atom" + "_site.group_PDB\n", "unauthorized_coordinate_row_hits"),
"json_string_pdb_coord_probe": (
json.dumps({"note": "AT" + "OM 1 N ALA A 1 11.104 13.207 2.100"}),
"unauthorized_coordinate_row_hits",
),
"json_string_mmcif_coord_probe": (
json.dumps({"note": "line1\n_atom" + "_site.group_PDB"}),
"unauthorized_coordinate_row_hits",
),
}
rejected = {}
for name, (ptext, expected_key) in probes.items():
counts = scan_tos_quarantine_text(ptext, name)
require_cond(counts[expected_key] > 0, f"Hygiene self-test {name} failed to catch {expected_key}")
rejected[name] = True
# Negative carve-out schema probe: nested dict inside carveout_rationale MUST fail BEFORE masking!
bad_carve = {
"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": {"hosted_iptm": 0.91} if idx == 0 else "Excluded metadata only.",