OpenIslet

scripts/verify_iip0044_foundry_v1_3_biologics.py

IIP-0044 / DEC-123 (CAND-035 / EXP-032): OpenIslet Foundry v1.3 Clean-Room

script Release v0.8.0 gen-eb955f8266035aba 619 KB · 44 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_iip0044_foundry_v1_3_biologics.py · SHA-256: 1d6c53a0817f6254…

    Decimal("14.0067"),
    Decimal("15.9994"),
    Decimal("32.065"),
)
_AMINO_ACID_RESIDUE_FORMULAS_CHNOS: dict[str, tuple[int, int, int, int, int]] = {
    "A": (3, 5, 1, 1, 0),
    "R": (6, 12, 4, 1, 0),
    "N": (4, 6, 2, 2, 0),
    "D": (4, 5, 1, 3, 0),
    "C": (3, 5, 1, 1, 1),
    "E": (5, 7, 1, 3, 0),
    "Q": (5, 8, 2, 2, 0),
    "G": (2, 3, 1, 1, 0),
    "H": (6, 7, 3, 1, 0),
    "I": (6, 11, 1, 1, 0),
    "L": (6, 11, 1, 1, 0),
    "K": (6, 12, 2, 1, 0),
    "M": (5, 9, 1, 1, 1),
    "F": (9, 9, 1, 1, 0),
    "P": (5, 7, 1, 1, 0),
    "S": (3, 5, 1, 2, 0),
    "T": (4, 7, 1, 2, 0),
    "W": (11, 10, 2, 1, 0),
    "Y": (9, 9, 1, 2, 0),
    "V": (5, 9, 1, 1, 0),
}


def compute_unmodified_average_mw_da(seq: str) -> Decimal:
    """Compute exact unmodified average molecular mass (Da) directly from amino acid elemental formulas + H2O termini."""
    c_n, h_n, n_n, o_n, s_n = 0, 2, 0, 1, 0
    for aa in seq:
        if aa not in _AMINO_ACID_RESIDUE_FORMULAS_CHNOS:
            raise ValueError(f"Unsupported amino acid symbol {aa!r} in unmodified MW calculation")
        rc, rh, rn, ro, rs = _AMINO_ACID_RESIDUE_FORMULAS_CHNOS[aa]
        c_n += rc
        h_n += rh
        n_n += rn
        o_n += ro
        s_n += rs
    wc, wh, wn, wo, ws = _IUPAC_ATOMIC_WEIGHTS_CHNOS
    return wc * c_n + wh * h_n + wn * n_n + wo * o_n + ws * s_n


def verify_fasta_file(
    path: Path,
    expected_sha256: str,
    expected_specs: dict[str, dict[str, Any]],
) -> dict[str, Any]:
    if not path.is_file():
        raise FileNotFoundError(f"Missing required CC-BY-4.0 FASTA: {path.name}")
    raw = path.read_bytes()
    actual_sha = sha256_bytes(raw)
    require_cond(
        actual_sha == expected_sha256,
        f"FASTA SHA-256 mismatch for {path.name}: actual={actual_sha}, expected={expected_sha256}",
    )
    records = parse_fasta_text(raw.decode("utf-8"))
    require_cond(
        len(records) == len(expected_specs),
        f"FASTA record count mismatch for {path.name}: actual={len(records)}, expected={len(expected_specs)}",
    )
    seen: list[str] = []
    per_seq: dict[str, dict[str, Any]] = {}
    for seq_id, hdr, seq in records:
        require_cond(seq_id in expected_specs, f"Unexpected sequence ID in {path.name}: {seq_id}")
        spec = expected_specs[seq_id]
        require_cond(seq == spec["seq"], f"Sequence mismatch for {seq_id} in {path.name}")
        require_cond(len(seq) == spec["len"], f"Length mismatch for {seq_id}: {len(seq)} != {spec['len']}")
        require_cond("CC-BY-4.0" in hdr, f"Missing CC-BY-4.0 license tag in header for {seq_id}")

        cys_count = seq.count("C")
        met_pos = [i + 1 for i, aa in enumerate(seq) if aa == "M"]
        trp_pos = [i + 1 for i, aa in enumerate(seq) if aa == "W"]
        ng_ns = [m.start() + 1 for m in re.finditer(r"N[GS]", seq)]
        dg_ds = [m.start() + 1 for m in re.finditer(r"D[GS]", seq)]
        n_glyc = [m.start() + 1 for m in re.finditer(r"N[^P][ST]", seq)]
        mw_da = compute_unmodified_average_mw_da(seq)
        mw_kda = mw_da / Decimal("1000")
        mw_da_5dp = mw_da.quantize(Decimal("0.00001"), rounding=ROUND_HALF_UP)
        mw_kda_5dp = mw_kda.quantize(Decimal("0.00001"), rounding=ROUND_HALF_UP)
        mw_kda_2dp = mw_kda.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)

        require_cond(cys_count == spec["cys"], f"Cys mismatch for {seq_id}: {cys_count} != {spec['cys']}")
        require_cond(met_pos == spec["met"], f"Met positions mismatch for {seq_id}: {met_pos} != {spec['met']}")
        require_cond(trp_pos == spec["trp"], f"Trp positions mismatch for {seq_id}: {trp_pos} != {spec['trp']}")
        require_cond(ng_ns == spec["ng_ns"], f"NG/NS mismatch for {seq_id}: {ng_ns} != {spec['ng_ns']}")
        require_cond(dg_ds == spec["dg_ds"], f"DG/DS mismatch for {seq_id}: {dg_ds} != {spec['dg_ds']}")
        require_cond(n_glyc == spec["n_glyc"], f"N-glyc mismatch for {seq_id}: {n_glyc} != {spec['n_glyc']}")

        seen.append(seq_id)
        per_seq[seq_id] = {
            "length": len(seq),
            "cys": cys_count,
            "disulfide_pairs": cys_count // 2,
            "met_count": len(met_pos),
            "trp_count": len(trp_pos),
            "ng_ns_count": len(ng_ns),
            "dg_ds_count": len(dg_ds),
            "n_glyc_count": len(n_glyc),
            "unmodified_average_mw_da": float(mw_da_5dp),
            "unmodified_average_mw_kda": float(mw_kda_5dp),
            "unmodified_average_mw_kda_2dp": float(mw_kda_2dp),
            "sha256_seq": sha256_bytes(seq.encode("utf-8")),
        }

    require_cond(set(seen) == set(expected_specs.keys()), f"Missing sequence IDs in {path.name}")
    return {
        "filename": path.name,
        "sha256": actual_sha,
        "bytes": len(raw),
        "sequence_count": len(records),
        "all_sequences_verified": True,
        "sequences": per_seq,
    }


def verify_thbd_p07204_m406l(shipped_seq: str) -> dict[str, Any]:
    require_cond(len(UNIPROT_P07204_363_480_WT) == 118, "WT P07204[363..480] reference must be 118 aa")
    require_cond(len(shipped_seq) == 118, f"IsletGUARD_THBD_M406L length must be 118 aa, got {len(shipped_seq)}")
    diffs = [
        {"pos_1based_slice": i + 1, "uniprot_pos_1based": 363 + i, "wt": a, "shipped": b}
        for i, (a, b) in enumerate(zip(UNIPROT_P07204_363_480_WT, shipped_seq))
        if a != b
    ]
    require_cond(
        len(diffs) == 1 and diffs[0] == {"pos_1based_slice": 44, "uniprot_pos_1based": 406, "wt": "M", "shipped": "L"},
        f"IsletGUARD_THBD_M406L must differ from P07204[363..480] strictly at M406L (slice pos 44): {diffs}",
    )
    cys = shipped_seq.count("C")
    n_glyc = [m.start() + 1 for m in re.finditer(r"N[^P][ST]", shipped_seq)]
    require_cond(cys == 18 and cys // 2 == 9, f"Expected 18 Cys / 9 reference disulfides, got {cys}")
    require_cond(n_glyc == [20, 47], f"Expected 2 reference N-glyc sequons [20, 47], got {n_glyc}")
    return {
        "uniprot_accession": "P07204",
        "slice_1based_closed": [363, 480],
        "length_aa": 118,
        "single_substitution_verified": diffs[0],
        "cys_count": cys,
        "reference_disulfide_pairs_uniprot_p07204": cys // 2,
        "reference_n_glyc_sequon_positions_1based": n_glyc,
        "reference_n_glyc_uniprot_p07204_positions": [382, 409],
        "product_glycan_and_disulfide_measured": False,
        "mammalian_or_insect_expression_required": True,
        "passed": True,
    }


def _canonical_json_sha256(obj: Any) -> str:
    return sha256_bytes(json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))


def _extract_guard_policy(
    side_contract: dict[str, Any] | Path | None,
) -> tuple[frozenset[str], frozenset[str], str, dict[str, str]]:
    """Enforce the frozen canonical Islet-GUARD policy ({'A', 'X'} on ROUTE_1_CAO2_HYDROGEL
    for IsletGUARD_THBD_M406L) across all three call modes:
      - side_contract is None: uses the frozen in-code canonical policy directly (no external file read).
      - side_contract is Path: authenticates BOTH the raw file SHA-256 AND canonical JSON SHA-256
        against the pinned finalized IIP-0044 side contract plus frozen policy parity.
      - side_contract is dict: authenticates canonical JSON SHA-256 plus frozen policy parity.
    Fails closed with ValueError on any tampered, widened, or unpinned policy.
    """
    if side_contract is None:
        return (
            ISLET_GUARD_ALLOWED_ARMS,
            ISLET_GUARD_ALLOWED_ROUTES,
            ISLET_GUARD_CONSTRUCT_ID,
            dict(DEFAULT_PORTFOLIO_ROUTE_ARM_BINDINGS),
        )
    if isinstance(side_contract, Path):
        if not side_contract.is_file():
            raise ValueError(f"Missing Islet-GUARD side_contract file: {side_contract.name}")
        raw_bytes = side_contract.read_bytes()
        file_sha = sha256_bytes(raw_bytes)
        if file_sha != EXPECTED_IIP0044_SIDE_CONTRACT_FILE_SHA256:
            raise ValueError(
                f"Tampered or unpinned Islet-GUARD side_contract file SHA-256 rejected fail-closed: "
                f"got {file_sha}, expected {EXPECTED_IIP0044_SIDE_CONTRACT_FILE_SHA256}"
            )
        side_contract_obj = load_strict_json_text(raw_bytes.decode("utf-8"), side_contract.name)
    elif isinstance(side_contract, dict):
        side_contract_obj = side_contract
    else:
        raise ValueError(f"Invalid side_contract type for Islet-GUARD eligibility check: {type(side_contract).__name__}")

    guard_cfg = side_contract_obj.get("programs_registered", {}).get("Islet_GUARD")
    if not isinstance(guard_cfg, dict):
        raise ValueError("Missing programs_registered.Islet_GUARD in side_contract (fail-closed)")
    allowed_arms_raw = guard_cfg.get("allowed_route_arms")
    disallowed_arms_raw = guard_cfg.get("disallowed_route_arms")
    allowed_routes_raw = guard_cfg.get("allowed_route_ids")
    construct_id_raw = guard_cfg.get("allowed_construct_id") or guard_cfg.get("lead_id")
    bindings_raw = guard_cfg.get("portfolio_route_arm_bindings")
    if not isinstance(allowed_arms_raw, list) or not allowed_arms_raw:
        raise ValueError("Invalid allowed_route_arms in side_contract (fail-closed)")
    if not isinstance(disallowed_arms_raw, list) or not disallowed_arms_raw:
        raise ValueError("Invalid disallowed_route_arms in side_contract (fail-closed)")
    if not isinstance(allowed_routes_raw, list) or not allowed_routes_raw:
        raise ValueError("Invalid allowed_route_ids in side_contract (fail-closed)")
    if type(construct_id_raw) is not str or not construct_id_raw.strip():
        raise ValueError("Invalid allowed_construct_id in side_contract (fail-closed)")
    if not isinstance(bindings_raw, dict) or not bindings_raw:
        raise ValueError("Invalid portfolio_route_arm_bindings in side_contract (fail-closed)")

    allowed_arms = frozenset(str(a).strip().upper() for a in allowed_arms_raw)
    disallowed_arms = frozenset(str(a).strip().upper() for a in disallowed_arms_raw)
    allowed_routes = frozenset(ROUTE_ALIAS_MAP.get(str(r).strip().upper(), str(r).strip().upper()) for r in allowed_routes_raw)
    construct_id = construct_id_raw.strip()
    bindings = {
        str(k).strip().upper(): ROUTE_ALIAS_MAP.get(str(v).strip().upper(), str(v).strip().upper())
        for k, v in bindings_raw.items()
    }

    # Enforce frozen canonical Islet-GUARD policy directly at the callable boundary (B4!)
    if allowed_arms != ISLET_GUARD_ALLOWED_ARMS:
        raise ValueError(
            f"Tampered Islet-GUARD allowed_route_arms rejected fail-closed at callable boundary: "
            f"got {sorted(allowed_arms)}, frozen canonical policy requires {sorted(ISLET_GUARD_ALLOWED_ARMS)}"
        )
    if disallowed_arms != frozenset({"B", "Y", "D"}):
        raise ValueError(
            f"Tampered Islet-GUARD disallowed_route_arms rejected fail-closed at callable boundary: "
            f"got {sorted(disallowed_arms)}, frozen canonical policy requires ['B', 'D', 'Y']"
        )
    if allowed_routes != ISLET_GUARD_ALLOWED_ROUTES:
        raise ValueError(
            f"Tampered Islet-GUARD allowed_route_ids rejected fail-closed at callable boundary: "
            f"got {sorted(allowed_routes)}, frozen canonical policy requires {sorted(ISLET_GUARD_ALLOWED_ROUTES)}"
        )
    if construct_id != ISLET_GUARD_CONSTRUCT_ID:
        raise ValueError(
            f"Tampered Islet-GUARD construct_id rejected fail-closed at callable boundary: "
            f"got {construct_id!r}, frozen canonical policy requires {ISLET_GUARD_CONSTRUCT_ID!r}"
        )
    if bindings != DEFAULT_PORTFOLIO_ROUTE_ARM_BINDINGS:
        raise ValueError(
            f"Tampered Islet-GUARD portfolio_route_arm_bindings rejected fail-closed at callable boundary: "
            f"got {bindings!r}"
        )

    # Enforce pinned canonical SHA-256 of the finalized IIP-0044 side contract at the callable boundary (B4!)
    actual_canon_sha = _canonical_json_sha256(side_contract_obj)
    if actual_canon_sha != EXPECTED_IIP0044_SIDE_CONTRACT_CANONICAL_SHA256:
        raise ValueError(
            f"Unpinned or mutated IIP-0044 side_contract rejected fail-closed at callable boundary: "
            f"canonical_sha256={actual_canon_sha}, expected={EXPECTED_IIP0044_SIDE_CONTRACT_CANONICAL_SHA256}"
        )

    return (allowed_arms, allowed_routes, construct_id, bindings)