OpenIslet

scripts/verify_iip0055_hygiene_safecell_minifh_orthogonality.py

OpenIslet Wave-6 W6-C1 (Provisional IIP-0055 / DEC-136 / GATE-34 / GY-033;

script Release v0.8.0 gen-eb955f8266035aba 417 KB · 30 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_iip0055_hygiene_safecell_minifh_orthogonality.py · SHA-256: d5b98e2ba1310333…

            if not step_ok:
                p = (lo + hi) / Decimal(2)
        require_cond(hi - lo <= Decimal("1e-24") * max(hi, Decimal("1e-35")), f"clopper_pearson_u95 bracket did not converge for k={k}, n={n}")
        return +hi


def clopper_pearson_u95(k: int, n: int, alpha: float = 0.05) -> float:
    """Exact pure-stdlib monotone one-sided (1 - alpha) Clopper-Pearson binomial upper confidence bound.

    Computes the certified 75-digit Decimal bound and rounds UPWARD to IEEE-754 float64
    (via math.nextafter if Decimal.from_float(f) < exact_d) so U95 never understates.
    """
    exact_d = clopper_pearson_u95_decimal(k, n, alpha=alpha)
    if exact_d >= Decimal(1):
        return 1.0
    f = float(exact_d)
    if Decimal.from_float(f) < exact_d:
        f = math.nextafter(f, math.inf)
    return min(1.0, f)


def load_and_verify_external_contracts(
    arm_manifest_path: Optional[Path] = None,
    master_contract_path: Optional[Path] = None,
) -> Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any]]:
    """Fail-closed release-relative loader and SHA-256 verifier for canonical Wave-6 contracts.

    When master_contract_path is None, discovers wave6_master_contract.json across
    [PKG_ROOT.parent/'shared', PKG_ROOT/'data'/'protocols', PKG_ROOT/'shared'].
    When arm_manifest_path is None, resolves canonical_arm_manifest_relpath STRICTLY in
    master_contract_path.parent (fails closed if sibling is missing; ZERO hardcoded temporary fallback!).
    """
    if master_contract_path is None:
        master_contract_path = discover_default_master_contract_path()
    require_cond(master_contract_path.is_file(), f"FAIL_CLOSED: missing Wave-6 master contract at {master_contract_path}")

    master_bytes = master_contract_path.read_bytes()
    master_file_sha = sha256_bytes(master_bytes)
    require_cond(
        master_file_sha == EXPECTED_MASTER_CONTRACT_FILE_SHA256,
        f"FAIL_CLOSED: master contract file SHA-256 mismatch (got={master_file_sha}, expected={EXPECTED_MASTER_CONTRACT_FILE_SHA256})",
    )
    master_contract = load_strict_json_text(master_bytes.decode("utf-8"), master_contract_path.name)
    require_cond(isinstance(master_contract, dict), "Invalid Wave-6 master contract root")
    declared_contract_sha = master_contract.get("contract_sha256")
    require_cond(_is_nonzero_sha256_hex(declared_contract_sha), "Master contract missing valid contract_sha256")
    clone = dict(master_contract)
    clone.pop("contract_sha256", None)
    recomputed_contract_sha = sha256_str(json.dumps(clone, sort_keys=True, separators=(",", ":")))
    require_cond(
        declared_contract_sha == recomputed_contract_sha == EXPECTED_MASTER_CONTRACT_SHA256,
        f"FAIL_CLOSED: master contract_sha256 tamper/mismatch (declared={declared_contract_sha}, recomputed={recomputed_contract_sha}, expected={EXPECTED_MASTER_CONTRACT_SHA256})",
    )

    if arm_manifest_path is None:
        rel_manifest = master_contract.get("canonical_arm_manifest_relpath")
        require_cond(
            _is_clean_str(rel_manifest) and "/" not in rel_manifest and "\\" not in rel_manifest and ".." not in rel_manifest,
            f"FAIL_CLOSED: unsafe or missing canonical_arm_manifest_relpath: {rel_manifest!r}",
        )
        arm_manifest_path = (master_contract_path.parent / rel_manifest).resolve()
    require_cond(arm_manifest_path.is_file(), f"FAIL_CLOSED: missing canonical arm manifest at {arm_manifest_path}")

    manifest_bytes = arm_manifest_path.read_bytes()
    manifest_sha = sha256_bytes(manifest_bytes)
    require_cond(
        manifest_sha == EXPECTED_ARM_MANIFEST_SHA256,
        f"FAIL_CLOSED: canonical arm manifest SHA-256 mismatch (got={manifest_sha}, expected={EXPECTED_ARM_MANIFEST_SHA256})",
    )
    arm_manifest = load_strict_json_text(manifest_bytes.decode("utf-8"), arm_manifest_path.name)
    ok_manifest, _ = verify_arm_manifest_dict_integrity(arm_manifest)
    require_cond(ok_manifest, "FAIL_CLOSED: canonical arm manifest canonical SHA-256 mismatch")
    require_cond(isinstance(arm_manifest, dict) and isinstance(arm_manifest.get("arms"), dict), "Invalid canonical arm manifest schema")
    require_cond(set(arm_manifest["arms"].keys()) == {"A", "B", "X", "Y", "D", "Z"}, "Canonical arm manifest missing expected 6 arms A/B/X/Y/D/Z")
    require_cond(
        master_contract.get("canonical_arm_manifest_sha256") == manifest_sha,
        "FAIL_CLOSED: master contract canonical_arm_manifest_sha256 does not match arm manifest SHA-256",
    )
    # Verify honest pre-wet-lab manifest status, Design A policy flags, and unified Round-5 schema
    for aid, acfg in arm_manifest["arms"].items():
        require_cond(acfg.get("dual_switch_wetlab_qualified") is False, f"FAIL_CLOSED: static manifest arm {aid} cannot declare dual_switch_wetlab_qualified=True")
    da_pol = arm_manifest.get("design_a_strict_policy", {})
    require_cond(isinstance(da_pol, dict), "FAIL_CLOSED: canonical arm manifest missing design_a_strict_policy")
    require_cond(da_pol.get("zero_additional_biologics_beyond_v080_catalase_hydrogel") is True, "FAIL_CLOSED: manifest Design A zero_additional_biologics flag invalid")
    require_cond(da_pol.get("contains_preexisting_p04040_catalase_hydrogel") is True, "FAIL_CLOSED: manifest Design A preexisting catalase flag invalid")
    require_cond(da_pol.get("strictly_zero_protein_biologics") is False, "FAIL_CLOSED: manifest Design A strictly_zero_protein_biologics must be False")
    up_schema = arm_manifest.get("upstream_lot_evidence_record_schema_v1", {})
    require_cond(
        isinstance(up_schema, dict)
        and up_schema.get("schema_revision") == UPSTREAM_RECEIPT_SCHEMA_REVISION
        and up_schema.get("required_fields") == list(UPSTREAM_RECEIPT_SCHEMA_V1_REQUIRED_FIELDS),
        "FAIL_CLOSED: canonical arm manifest upstream_lot_evidence_record_schema_v1 mismatch",
    )
    cgs = up_schema.get("canonical_gate_sources", {})
    cgr = up_schema.get("canonical_gate_roles", {})
    g5_pol = up_schema.get("gate5_oq012_live_blueprint_policy", {})
    require_cond(
        isinstance(cgs, dict) and cgs.get("gate34") == GATE_ID and cgs.get("live_gate32_shield_debris_recall") == "GATE-32",
        "FAIL_CLOSED: canonical arm manifest gate_sources mismatch for collision-free GATE-34 / live GATE-32",
    )
    require_cond(
        isinstance(cgr, dict) and cgr.get(GATE_ID) == GATE_ROLE,
        "FAIL_CLOSED: canonical arm manifest canonical_gate_roles mismatch for GATE-34",
    )
    require_cond(
        isinstance(g5_pol, dict)
        and g5_pol.get("required_observed_survivors_k") == 0
        and g5_pol.get("min_effective_clonogenic_trials_n_eff") == GATE5_OQ012_MIN_EFFECTIVE_TRIALS
        and g5_pol.get("max_u95_exact") == "1e-8",
        "FAIL_CLOSED: canonical arm manifest gate5_oq012_live_blueprint_policy mismatch",
    )
    cand_c1 = (master_contract.get("candidate_assignments") or {}).get("W6-C1", {})
    require_cond(
        isinstance(cand_c1, dict)
        and cand_c1.get("staged_iip") == CONTRIBUTION_ID
        and cand_c1.get("staged_dec") == DECISION_ID
        and cand_c1.get("staged_gate") == GATE_ID
        and cand_c1.get("staged_gy") == GRAVEYARD_ID
        and cand_c1.get("gate_role") == GATE_ROLE,
        f"FAIL_CLOSED: master contract W6-C1 candidate_assignments mismatch: {cand_c1!r}",
    )

    inv = master_contract.get("strict_invariants")
    require_cond(isinstance(inv, dict), "Master contract missing strict_invariants")
    require_cond(inv.get("h1_allo_locked_pct") == 88.0, f"FAIL_CLOSED: master contract H1 lock tampered ({inv.get('h1_allo_locked_pct')})")
    require_cond(inv.get("design_a_zero_post_transplant_drugs_and_exvivo_rest") is True, "FAIL_CLOSED: Design A zero-post-transplant-drug invariant violated")
    require_cond(inv.get("design_a_zero_additional_biologics_beyond_v080_catalase_hydrogel") is True, "FAIL_CLOSED: Design A zero-additional-biologics invariant violated")
    require_cond(inv.get("design_a_contains_preexisting_p04040_catalase_hydrogel") is True, "FAIL_CLOSED: Design A preexisting catalase invariant missing")
    require_cond(inv.get("design_a_strictly_zero_protein_biologics") is False, "FAIL_CLOSED: Design A strictly_zero_protein_biologics invariant must be False")
    require_cond(inv.get("design_a_preexisting_catalase_hydrogel_exception_disclosed") is True, "FAIL_CLOSED: Design A catalase exception invariant missing")
    require_cond(inv.get("design_a_invariant_tuple") == [0.88, 0.78, 0.57, 0.69], "FAIL_CLOSED: Design A invariant tuple tampered")
    require_cond(inv.get("zero_chronic_systemic_immunosuppression") is True, "FAIL_CLOSED: zero chronic IS invariant violated")
    require_cond(inv.get("zero_fabricated_or_rng_dna") is True, "FAIL_CLOSED: zero RNG DNA invariant violated")
    require_cond(
        inv.get("gy_026_txnip_ko_removal_status") == "PENDING_ATOMIC_FOLDIN_MIGRATION",
        f"FAIL_CLOSED: GY-026 status must be PENDING_ATOMIC_FOLDIN_MIGRATION, got {inv.get('gy_026_txnip_ko_removal_status')!r}",
    )
    require_cond(inv.get("gy_027_1_enforced_unhardened_abx_not_on_r4") is True, "FAIL_CLOSED: GY-027(1) R4 invariant violated")
    require_cond(inv.get("gy_027_1_home_route_locked_and_modular_enforced") is True, "FAIL_CLOSED: GY-027(1) home-route invariant violated")
    require_cond(inv.get("gy_030_5_lineage_whole_graft_required_all_arms") is True, "FAIL_CLOSED: GY-030 5-lineage invariant violated")
    require_cond(inv.get("c1_prerequisite_enforced_for_r4_and_z_in_24state_ev") is True, "FAIL_CLOSED: C1 prerequisite EV invariant violated")
    require_cond(inv.get("synthetic_fixtures_cannot_authorize_clinical_promotion") is True, "FAIL_CLOSED: synthetic fixture isolation invariant missing")

    meta = {
        "external_contracts_hash_verified": True,
        "manifest_resolution_mode": "RELEASE_RELATIVE_PAIRED_SIBLING_NO_HARDCODED_FALLBACK",
        "arm_manifest_file": arm_manifest_path.name,
        "arm_manifest_schema": arm_manifest.get("schema_version"),
        "arm_manifest_sha256": manifest_sha,
        "arm_manifest_canonical_sha256": EXPECTED_ARM_MANIFEST_CANONICAL_SHA256,
        "master_contract_file": master_contract_path.name,
        "master_contract_schema": master_contract.get("schema_version"),
        "master_contract_file_sha256": master_file_sha,
        "master_contract_sha256": recomputed_contract_sha,
        "strict_invariants_verified": True,
    }
    return arm_manifest, master_contract, meta


# =============================================================================
# PART A — 100% AUTHENTIC GENOMIC SEQUENCES & PHASE-1A DNA REPAIRS
# =============================================================================
def verify_part_a_authentic_sequences_and_repairs(fasta_path: Path) -> Dict[str, Any]:
    reg = EMBEDDED_AUTHENTIC_ASSETS["authentic_genomic_and_regulatory"]
    rep = EMBEDDED_AUTHENTIC_ASSETS["repaired_constructs"]
    pro = EMBEDDED_AUTHENTIC_ASSETS["proteins"]

    # 1. Verify authentic regulatory elements (0% synthetic random DNA!)
    chs4 = reg["cHS4_0C9_v090"]["seq"]
    chs4_wt = reg["cHS4_0C9_v090"]["wt_contiguous_u78775_1_250"]
    chs4_h = audit_dna_hygiene(chs4)
    chs4_diffs = [(idx + 1, a, b) for idx, (a, b) in enumerate(zip(chs4_wt, chs4)) if a != b]
    require_cond(len(chs4) == 250 and len(chs4_wt) == 250, "cHS4 length != 250 bp")
    require_cond(
        chs4_diffs == [(20, "C", "T"), (21, "C", "A"), (79, "C", "T"), (80, "C", "A")],
        f"cHS4 contiguous U78775.2:1-250(+) diff mismatch: {chs4_diffs}",
    )
    require_cond("CCCCCCCCC" not in chs4 and chs4_h["max_homopolymer_nt"] <= 6, "cHS4 C9 break failed")
    require_cond("CGCTAGGGGGC" in chs4 and "GGGACAGCCCGGGCACGGGGAAGGTGGCACGGG" in chs4, "cHS4 CTCF FII or USF1/2 FIV altered")

    eef = reg["EEF1A1_core_GRCh38_230bp"]["seq"]
    eef_h = audit_dna_hygiene(eef)
    require_cond(len(eef) == 230 and eef_h["gc_global_pct"] == 60.0 and eef_h["passes_synthetic_v090_gates"], "EEF1A1 GRCh38 check failed")
    require_cond("TATATAA" in eef and "TATAAA" not in eef, "EEF1A1 TATATAA vs absent TATAAA check failed")

    cbx3 = reg["CBX3_A2UCOE_GRCh38_700bp"]["seq"]
    cbx3_h = audit_dna_hygiene(cbx3)
    require_cond(
        len(cbx3) == 700 and cbx3_h["t20_count"] == 0 and cbx3_h["max_homopolymer_nt"] <= 6
        and cbx3_h["disjoint_dr_ge20_count"] == 0 and cbx3_h["disjoint_ir_ge20_count"] == 0,
        "CBX3 GRCh38 check failed",
    )

    cxcl10_p = reg["CXCL10_NFkB_ISRE_GRCh38_260bp"]["seq"]
    cxcl10_h = audit_dna_hygiene(cxcl10_p)
    require_cond(len(cxcl10_p) == 260 and cxcl10_h["passes_synthetic_v090_gates"], "CXCL10 promoter check failed")
    require_cond("GGAAAGTGAAACC" in cxcl10_p and "GGGAAATTCC" in cxcl10_p and "GGGACTTCC" in cxcl10_p, "CXCL10 ISRE/NFkB motifs missing")

    emcv = reg["EMCV_IRES_M81861_1_567bp"]["seq"]
    emcv_h = audit_dna_hygiene(emcv)
    require_cond(len(emcv) == 567 and emcv_h["passes_synthetic_v090_gates"] and emcv.endswith("ATGATAATATGGCCACAACCATG"), "EMCV IRES check failed")

    bgh = reg["bGH_polyA_M57764_1_225bp"]["seq"]
    bgh_h = audit_dna_hygiene(bgh)
    require_cond(len(bgh) == 225 and bgh_h["passes_synthetic_v090_gates"] and "AATAAA" in bgh, "bGH polyA check failed")

    # 2. Verify GRCh38 TBP, ACTB, CDK1 700-bp LHA & 700-bp RHA (zero RNG filler; explicit native homopolymers disclosed)
    ha_audit: Dict[str, Any] = {}
    for locus, stop_expected in (("TBP", "TAA"), ("ACTB", "TAG"), ("CDK1", "TAG")):
        lha = reg[f"{locus}_LHA_700bp"]["seq"]
        rha = reg[f"{locus}_RHA_700bp"]["seq"]
        stop = reg[f"{locus}_LHA_700bp"]["stop"]
        require_cond(len(lha) == 700 and len(rha) == 700 and stop == stop_expected, f"{locus} HA sizing/stop fail")
        lh = audit_dna_hygiene(lha)
        rh = audit_dna_hygiene(rha)
        require_cond(lh["t20_count"] == 0 and rh["t20_count"] == 0, f"{locus} HA contains T20")
        ha_audit[locus] = {
            "lha_coords": reg[f"{locus}_LHA_700bp"]["coords"],
            "rha_coords": reg[f"{locus}_RHA_700bp"]["coords"],
            "transcript": reg[f"{locus}_LHA_700bp"]["transcript"],
            "native_stop_codon": stop,
            "lha_700bp": lh,
            "rha_700bp": rh,
        }
    require_cond(ha_audit["TBP"]["rha_700bp"]["max_homopolymer_nt"] == 13, "Expected native GRCh38 TBP RHA T13")
    require_cond(ha_audit["ACTB"]["rha_700bp"]["max_homopolymer_nt"] == 16, "Expected native GRCh38 ACTB RHA T16")

    # 3. Verify Phase-1A Repairs 1, 2, 3
    arm1b_old_sub = rep["arm1b_before_l1_b2m_l2"]
    arm1b_new = rep["arm1b_repaired"]
    arm1b_old_h = audit_dna_hygiene(arm1b_old_sub)
    arm1b_new_payload_h = audit_dna_hygiene(arm1b_new[500:3474])
    arm1b_new_full_h = audit_dna_hygiene(arm1b_new)
    require_cond(arm1b_old_h["max_disjoint_dr_bp"] >= 45, "ARM1B BEFORE DR benchmark failed")
    require_cond(arm1b_new_payload_h["passes_synthetic_v090_gates"] and arm1b_new_full_h["disjoint_dr_ge20_count"] == 0, "ARM1B repair failed")
    require_cond(len(arm1b_new) + AAV6_ITR_OVERHEAD_BP == 4264 <= AAV6_MAX_PACKAGED_BP, "ARM1B AAV6 arithmetic ceiling failed")
    sct_aa = translate(arm1b_new[1646:3149], 0)
    require_cond(len(sct_aa) == 501 and sct_aa.startswith("MSRSVALAVLALLSLSGLEAVMAPRTLVLGGGGSGGGGSGGGGS") and sct_aa.endswith("*"), "ARM1B HLA-E SCT AA check failed")

    ubc_old = rep["ubc_before_180"]
    ubc_new = rep["ubc_after_180"]
    ubc_old_h = audit_dna_hygiene(ubc_old)
    ubc_new_h = audit_dna_hygiene(ubc_new)
    require_cond(ubc_old_h["t20_count"] == 1 and ubc_old_h["max_homopolymer_nt"] == 20, "UBC BEFORE T20 check failed")
    require_cond(ubc_new_h["passes_synthetic_v090_gates"] and "AATAAA" in ubc_new and len(rep["t20_audit_rows"]) == 9, "UBC T20 repair failed")
    # Dynamically recompute BEFORE & AFTER SHA-256 and post-patch hygiene for ALL 9 T20 segment rows
    t20_segs = rep["t20_before_segments_by_sha256"]
    t20_recomputed_rows: List[Dict[str, Any]] = []
    for row in rep["t20_audit_rows"]:
        seg_before = t20_segs.get(row["before_sha256"])