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…

                f"Authoritative typed JSON bindings (18 active PMIDs, 4 typed role-enum PMID bindings [PMID:18252895, PMID:21912932, PMID:22315720, PMID:31556206], 6 wwPDB-to-primary-PMID bindings, 3 UniProtKB-to-gene/slice bindings, typed 3-way 1JK8/WT15/6DFX peptide-record bindings, and min_expression_batches=3) complemented by bounded deterministic prose regression checks across all 4 authored surfaces (DEC-123, IIP-0044 side contract, Tier-1 summary JSON, and FOUNDRY-V1-3 protocol) and aligned IIP-0042 surfaces for documented citation-role, bidirectional 1JK8 conflation, and <3 batch contradiction families (complementing, not replacing, human/blind text review); typed fail-first Gate 30-SHIELD-SPR adjudicator ({shield_spr_tests['total_cases']} self-tests synchronized identically across 77/77 shared AST symbols with verify_iip0042 on pre-adjudication WT15/HIP11/6DFX register-QC enforcing pairwise-distinct peptide reagent lot IDs across ALL mandatory peptide reagents [HIP11, WT15, 6DFX, plus optional 1JK8 whenever supplied] before dependent biological or batch credit and excluding register_qc_records from Comp1/Comp2 SPR assay batch counts [counting Comp1 SPR batches strictly from validated Comp1 on/off-target SPR rows], strict validation of optional non-null 1JK8 peptide_reagent_lot_id whenever supplied [keeping 1JK8 omitted or JSON null optional], hip11_peptide_reagent_lot_id & Comp1/Comp2 parent-batch coverage, cross-allele WT15 off-target reagent-lot reconciliation, mandatory per-comparator WT15 + 6DFX register-control screens requiring a non-empty shared comparator expression-batch intersection evaluated across BOTH WT15 and 6DFX with construct-bound batches and unique evidence IDs before granting complete-comparator credit or Track-B candidacy [optional physical 14-aa 1JK8 omitted or JSON null], and pre-adjudication physicochemical SEC-MALS/DLS material qualification [component-level SEC-MALS/DLS lot qualification for single-component Comp1/Comp2 SPR rows plus per-mixture physical co-formulation qualification via qualified_coformulation_mixtures binding each unique mixture_id to its exact (comp1_expression_batch_id, comp2_expression_batch_id) pair, per-mixture monomer_pct >= 95.0% / dls_pdi <= 0.15 / no_aggregates_or_precipitation=True, and laboratory-attested 1:1 molar ratio metadata — donor material is matched to physical lot pair while 1:1 molar ratio remains a laboratory attestation when optional ratio fields are omitted] requiring single-component SPR rows to use qualified component expression lots AND every rostered donor cocktail row's exact cocktail_mixture_id and component lot pair to match a passing physical mixture before fail-first arbitration [excluding crossed, unlisted, omitted, disjoint, or off-spec rows from biological FAIL, batch-linkage credit, and Track-B candidacy while preserving donor dependency topology, fixed N_roster, and independent qualified SPR FAIL], mandatory closed-schema cryptographically SHA-256-pinned outcome-blind preregistered_donor_family_roster committing donor membership, fixed per-donor cytotoxicity sample size N [predeclared_per_donor_unit_count_n or exact per-donor map predeclared_per_donor_unit_counts], and single-look fixed horizon [planned_analysis_looks == 1, single_look_fixed_horizon_plan_locked == True] inside roster_sha256 and reconciled 100% on ALL raw submitted + excluded donor IDs AND fixed-N unit counts across ALL raw submitted rostered donor rows BEFORE duplicate-donor exclusion [unified fail-first precedence with explicit failure_domain='INDEPENDENT_NON_DONOR_SPR' preserving independent valid qualified-material non-donor SPR FAIL while out-of-spec/missing physicochemical SEC-MALS/DLS measurements hold as unqualified material inputs with failure_domain=None and invalid, multi-look, or sample-size-mismatched rosters block overall PASS and donor-based FAIL; confirmatory cytotoxicity PASS and Track-B candidate eligibility requiring 100% measured rostered donors with 0 pre-assay exclusions; exact Boole FWER <= 0.05 scoped strictly to the fixed-roster, fixed-N, single-look donor cytotoxicity family conditional on external outcome-blind custody of the full analysis plan before readouts], machine-checked trackb_shield_trigger_state distinguishing complete zero-hold full-roster SHIELD-1-only Comp2 failure vs overall SHIELD failure while excluding all non-FAIL/held/incomplete/pre-assay-excluded/partial-FAIL states, retained donor batch/run Union-Find dependency topology independent of unrelated per-donor CI/summary errors, cluster-conservative distribution-free exact Clopper-Pearson responder-proportion suppression inference across donor/expression-batch/assay-run/joint connected-component clusters [narrowed strictly to sampling_design_class=='SIMPLE_RANDOM_OR_CONSECUTIVE_INDEPENDENT_T1D_COHORT' paired 1:1 with class-specific between_donor_independence_justification tokens, rejecting contradictory class-vs-justification declarations as invalid HOLD in both directions and routing matching STRATIFIED_INDEPENDENT_T1D_HLA_DQ_COHORT to non-authorizing HOLD with STRATIFIED_COHORT_REQUIRES_TARGET_WEIGHTED_SUPPRESSION_ESTIMATOR while preserving independent SPR FAIL and fixed-roster Bonferroni cytotoxicity FAIL; >= 9 disjoint batch/run clusters for confirmatory PASS, mandatory closed-schema donor_sampling_and_independence_design + per-donor assay_run_id, suppression assay acceptance range [-1000.0, 100.0]%, anti-enhancement min >= 0.0%, L95_CP(k_lt_40) > 60.0% FAIL, descriptive-only responder U95 without marginal upper-coverage guarantee, signed non-inverted overflow-immune Student-t non-authorizing diagnostic], mandatory closed-schema 1:1 canonical allowlisted gy018_independence_justification rejecting free-text prose and extra keys, two-pass order-independent canonical key uniqueness across all evidence lists, WT15 peptide_sequence + peptide_reagent_lot_id linkage across both on-target and cross-allele off-target rows, row-level SPR validity/registration gating excluding invalid/unregistered/conflicted rows from bio FAIL, Comp1+Comp2 off-targets, construct-bound expression_batch_ids provenance rejecting empty construct_ids and requiring >=3 distinct Comp1 & >=3 distinct Comp2 linked batches, quantitative SEC-MALS >= 95.0% / PDI <= 0.15, optional physical 14-aa 1JK8 omitted or JSON null, mandatory typed T1D donor eligibility [t1d_diagnosis_confirmed=True, donor_clinical_cohort='T1D', non-empty unpadded t1d_prequalification_ref, rejecting contradictory non-T1D donor tokens], qualifying donor HLA allowlist, exact GY-018 design_effect_deff == 1.0 [zero tolerance preserved as exact Decimal through load_strict_json_text] with invalid/ineligible donors gated out of confidence bounds, fixed-roster Bonferroni FWER <= 0.05 cytotoxicity FAIL rule under H0_all: max_i p_i <= 5.0% at alpha_donor = 0.05 / N_roster [cohort Student-t lower bound non-authorizing diagnostic only], two-sided CI validation, and exact raw JSON decimal |d| > 10^300 / Python binary64 >1e300 ValueError), independent full-clause IIP-0042 JSON/Markdown alignment checker ({alignment_self_tests['total_cases']} self-tests), raw-byte --check receipt verification rejecting LF-to-CRLF mutation, and targeted {len(hygiene_results)}-surface Foundry/aligned-IIP-0042 Gate 30-TOS-QUARANTINE hygiene scan (complete public manifest.json SHA-256, exact public disk membership, 17/17 pre-Wave-5 structure pins, and 23-file/4-DEC Wave-5 inventory authentication are assigned to scripts/verify_iip0042_master_multilayer_portfolio_crosswalk.py per GATE-30 Protocol §2.4)",
            ],
            "external_upstream_foundry_v1_3_not_reexecuted_locally": (
                "Raw upstream Foundry v1.3 .cif/.pdb/MD trajectory bytes, upstream byte counts and per-file license claims "
                "for the 69 non-deposited files, upstream model runs/settings, metric derivation from raw structures, "
                "Comp1's full 6-peptide celiac panel underlying the reported 5/6 passing count, GUARD's reported 0.94-1.02 A "
                "1DX5 EGF5 reference geometry and 0 Ca2+ MD setup outside the locally recomputed 5.487 A > 3.0 A RMSD verdict, "
                "verdicts tagged UPSTREAM_REPORTED_PROVENANCE_ONLY (4/10 Comp1 gates and GUARD bimodal docking), "
                "and upstream absence of hosted inputs are declared external provenance outside the public OpenIslet snapshot."
            ),
        },
        "checked_inputs_sha256": checked_inputs_sha256,
        "fasta_verification": {
            "all_leads": leads_check,
            "comp2_comparators": comp2_check,
            "total_sequences_verified": leads_check["sequence_count"] + comp2_check["sequence_count"],
            "sequence_derived_shield_lead_masses_kda": {
                "method": "IUPAC_STANDARD_ELEMENTAL_AVERAGE_ATOMIC_WEIGHTS_PLUS_H2O_TERMINI",
                "IsletSHIELD_QF09_pI2": {
                    "unmodified_average_mw_da": qf09_mw["unmodified_average_mw_da"],
                    "unmodified_average_mw_kda": qf09_mw["unmodified_average_mw_kda"],
                    "unmodified_average_mw_kda_2dp": qf09_mw["unmodified_average_mw_kda_2dp"],
                },
                "IsletSHIELD_Comp2_T006": {
                    "unmodified_average_mw_da": t006_mw["unmodified_average_mw_da"],
                    "unmodified_average_mw_kda": t006_mw["unmodified_average_mw_kda"],
                    "unmodified_average_mw_kda_2dp": t006_mw["unmodified_average_mw_kda_2dp"],
                },
                "matches_side_contract_masses": True,
            },
        },
        "uniprot_p07204_m406l_verification": thbd_check,
        "islet_guard_route1_arm_restriction_tests": guard_arm_tests,
        "gate30_shield_spr_decision_table_self_tests": shield_spr_tests,
        "stage0_tier1_audit_parity": audit_parity,
        "zero_lims_touch_invariance": lims_invariance,
        "gate_30_tos_quarantine_hygiene": {
            "scan_scope": (
                "TARGETED_10_SURFACE_FOUNDRY_AND_ALIGNED_IIP0042_SCAN_ONLY"
                if installed_check
                else "TARGETED_STAGING_FOUNDRY_SURFACES_SCAN_ONLY"
            ),
            "full_public_manifest_and_disk_inventory_verified_here": False,
            "full_inventory_gate30_entry_point": (
                "scripts/verify_iip0042_master_multilayer_portfolio_crosswalk.py::verify_gate30_tos_quarantine_full_inventory"
            ),
            "scanned_files_count": len(hygiene_results),
            "all_scanned_files_clean": True,
            "file_hit_counts": hygiene_results,
            "negative_self_tests": hygiene_neg_tests,
        },
        "iip0042_alignment_audit": iip0042_alignment,
    }
    return receipt


def build_cli_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description="IIP-0044 / DEC-123 OpenIslet Foundry v1.3 Clean-Room Biologics Standalone Verifier"
    )
    parser.add_argument(
        "--repo-root",
        type=Path,
        default=None,
        help="Path to read-only OpenIslet repository root (fail-closed if invalid).",
    )
    parser.add_argument(
        "--output",
        type=Path,
        default=None,
        help="Output .json receipt file or directory path.",
    )
    parser.add_argument(
        "--check",
        action="store_true",
        help="Read-only verification mode: verifies existing receipt byte-for-byte without writing.",
    )
    parser.add_argument(
        "--installed-check",
        action="store_true",
        help="Strict installed OpenIslet mode: requires all IIP-0044 files and independent IIP-0042 alignment installed.",
    )
    return parser


def resolve_output_file(output_arg: Path | None, installed_check: bool, repo_root: Path | None) -> Path:
    if output_arg is not None:
        p = output_arg.expanduser().resolve()
        if p.suffix.lower() == ".json":
            return p
        return p / "iip0044_verification_receipt.json"
    if installed_check and repo_root is not None:
        return repo_root / "data" / "extracted" / "iip0044_foundry_v1_3_biologics_verification_v0.8.0.json"
    return SCRIPT_DIR / "iip0044_verification_receipt.json"


def main(argv: list[str] | None = None) -> None:
    args = build_cli_parser().parse_args(argv)
    repo_root = resolve_repo_root(args.repo_root, args.installed_check)
    receipt = run_verification(repo_root=repo_root, installed_check=args.installed_check)

    raw_json = json.dumps(receipt, indent=2, ensure_ascii=False, allow_nan=False) + "\n"
    require_tos_quarantine_clean(raw_json, "generated_receipt_json")
    expected_bytes = raw_json.encode("utf-8")

    out_file = resolve_output_file(args.output, args.installed_check, repo_root)
    if args.check:
        if not out_file.is_file():
            raise FileNotFoundError(f"--check failed (fail-closed): expected receipt missing: {out_file.name}")
        existing_bytes = out_file.read_bytes()
        require_cond(
            existing_bytes == expected_bytes,
            f"--check failed (fail-closed): raw byte mismatch for {out_file.name} "
            f"(existing={sha256_bytes(existing_bytes)}, fresh={sha256_bytes(expected_bytes)})",
        )
        print(
            f"PASS (--check byte-exact): mode={receipt['verification_mode']} "
            f"seqs={receipt['fasta_verification']['total_sequences_verified']}/12 "
            f"odds_credit={receipt['live_odds_credit_pp']:+.2f}pp "
            f"hygiene_files={receipt['gate_30_tos_quarantine_hygiene']['scanned_files_count']} "
            f"sha256={sha256_bytes(existing_bytes)} (optimize={sys.flags.optimize})"
        )
        return

    if args.installed_check and args.output is None:
        print(
            f"PASS (--installed-check read-only): seqs={receipt['fasta_verification']['total_sequences_verified']}/12 "
            f"odds_credit={receipt['live_odds_credit_pp']:+.2f}pp "
            f"iip0042_aligned={receipt['iip0042_alignment_audit']['aligned']} "
            f"sha256={sha256_bytes(expected_bytes)} (optimize={sys.flags.optimize})"
        )
        return

    if not out_file.parent.exists():
        raise FileNotFoundError(f"Output parent directory does not exist (fail-closed): {out_file.parent.name}")
    out_file.write_bytes(expected_bytes)
    print(
        f"PASS: mode={receipt['verification_mode']} "
        f"seqs={receipt['fasta_verification']['total_sequences_verified']}/12 "
        f"odds_credit={receipt['live_odds_credit_pp']:+.2f}pp "
        f"hygiene_files={receipt['gate_30_tos_quarantine_hygiene']['scanned_files_count']} "
        f"wrote={out_file.name} sha256={sha256_file(out_file)} (optimize={sys.flags.optimize})"
    )


if __name__ == "__main__":
    main()