OpenIslet

scripts/verify_iip0058_armz_ensc_isletsort_v2_and_2p24_portfolio.py

Provisional IIP-0058 / DEC-139 / GATE-37 / GY-036 (Round-14 Blueprint Alignment; staged in iip0058/):

script Release v0.8.0 gen-eb955f8266035aba 837 KB · 62 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_iip0058_armz_ensc_isletsort_v2_and_2p24_portfolio.py · SHA-256: 33439d619c00fcc3…

        return _enforce_strict_json_report({
            "gate": "Gate 37-SORT-ITGA1-Ridge",
            "evidence_tier": valid_tier,
            "verdict": "STAGE_LIMITED_SORT_ONLY",
            "decision": "STAGE_LIMITED_SORT_ONLY",
            "authority_scope": "STAGE_LIMITED_SORT_ONLY",
            "bank_qualified": (valid_tier == "AUTHENTICATED_ARCHIVED_WETLAB"),
            "component_sort_qualified": False,
            "clinical_release_requires_atomic_ledger": True,
            "promotion_authorized": False,
            "release_qc_complete": False,
            "computed_live_cell_selectivity_ratio": extra["computed_live_cell_selectivity_ratio"],
            "reason": "ENTPD3_MATURE_BETA_QC_ABSENT_STAGE_LIMITED_SORT_ONLY",
            "failures": [],
            "holds": [],
        })

    return _finalize_gate_verdict(
        "Gate 37-SORT-ITGA1-Ridge",
        failures,
        holds,
        "PASS_COMPONENT_SORT_QUALIFICATION",
        "ALL_ITGA1_RIDGE_FUNCTIONAL_ENTPD3_AND_OQ018_COMPONENT_SORT_CRITERIA_MET_CLINICAL_RELEASE_REQUIRES_ATOMIC_LEDGER",
        evidence_tier=valid_tier,
        pass_authority_scope="COMPONENT_SORT_QUALIFICATION_ONLY",
        bank_qualified_on_wetlab_pass=True,
        authorize_promotion_on_wetlab_pass=False,
        extra=extra,
    )


def _validate_gate5_oq012_live_blueprint(
    arch_g5: Mapping[str, Any],
    holds: list[str],
    failures: list[str],
) -> None:
    """Enforce exact live Blueprint Section 7 / wetlab_contract.py Gate 5 OQ-012 stringency.

    Requires:
      - oq012_clonogenic_regrowth_pass is True
      - survivor_count_k == 0 (ANY k >= 1, including 1/100,000, returns FAIL!)
      - Explicit tested_cells_n (strict int in [1, 10^12]),
        clonogenic_fraction_f (exact Decimal in (0, 1]),
        spike_in_detection_efficiency_eta (exact Decimal in [0.30, 1.0]; < 0.30 -> FAIL),
        and effective_clonogenic_trials_n_eff (strict int in [1, 10^12], reconciled against
        exact floor(tested_cells_n * clonogenic_fraction_f * spike_in_detection_efficiency_eta) —
        if n_eff > floor(...) -> FAIL!)
      - Missing/None recovery or effective-denominator fields -> governed HOLD
        (HOLD_GATE5_OQ012_INCOMPLETE_RECOVERY_DENOMINATOR)
      - Recomputed exact 75-digit Decimal Clopper-Pearson U95(k, n_eff):
        - If k == 0 and n_eff < 299,573,228 (incl. n_eff = 299,573,227 or 0/100,000) ->
          governed HOLD (HOLD_GATE5_OQ012_UNDERPOWERED_BELOW_299573228_EFFECTIVE_TRIALS)
        - Clinical PASS requires k == 0, n_eff >= 299,573,228, and recomputed U95(0, n_eff) <= 1e-8
          with zero understatement in reported u95_exact.
    """
    for canon_k, leg_k in (
        ("tested_cells_n", "cells_assayed"),
        ("survivor_count_k", "survivors_observed"),
        ("u95_exact", "clonogenic_escape_u95"),
    ):
        if leg_k in arch_g5 and canon_k in arch_g5 and arch_g5[leg_k] != arch_g5[canon_k]:
            failures.append("FAIL_GATE5_LEGACY_ALIAS_CONTRADICTION")

    oq012_pass = arch_g5.get("oq012_clonogenic_regrowth_pass")
    if oq012_pass is None:
        holds.append("HOLD_MISSING_GATE5_OQ012_CLONOGENIC_REGROWTH_PASS")
    elif oq012_pass is not True:
        failures.append("FAIL_GATE5_OQ012_CLONOGENIC_REGROWTH_NOT_PASSED")

    k_s = arch_g5.get("survivor_count_k")
    n_s = arch_g5.get("tested_cells_n")
    u95_s = arch_g5.get("u95_exact")

    valid_n: Optional[int] = None
    if n_s is None:
        holds.append("HOLD_MISSING_GATE5_SURVIVOR_OR_TESTED_COUNTS")
    elif not _is_strict_int(n_s) or n_s < MIN_GATE5_TESTED_CELLS or n_s > MAX_CLONOGENIC_CELLS:
        failures.append("FAIL_GATE5_TESTED_CELLS_OUT_OF_DOMAIN")
    else:
        valid_n = n_s

    valid_k: Optional[int] = None
    if k_s is None:
        if "HOLD_MISSING_GATE5_SURVIVOR_OR_TESTED_COUNTS" not in holds:
            holds.append("HOLD_MISSING_GATE5_SURVIVOR_OR_TESTED_COUNTS")
    elif not _is_strict_int(k_s) or k_s < 0 or (valid_n is not None and k_s > valid_n):
        failures.append("FAIL_GATE5_INVALID_SURVIVOR_COUNT")
    else:
        valid_k = k_s
        if k_s >= 1:
            failures.append("FAIL_GATE5_OQ012_NONZERO_SURVIVOR_OR_U95_GT_1E8")

    # Recovery & effective clonogenic trials denominator (live Blueprint Section 7 OQ-012)
    f_raw = arch_g5.get("clonogenic_fraction_f")
    eta_raw = arch_g5.get("spike_in_detection_efficiency_eta")
    n_eff_raw = arch_g5.get("effective_clonogenic_trials_n_eff")

    missing_recovery = False
    f_dec: Optional[Decimal] = None
    if f_raw is None:
        missing_recovery = True
    else:
        f_d = _to_exact_decimal(f_raw)
        if f_d is None or f_d <= Decimal(0) or f_d > Decimal(1):
            failures.append("FAIL_GATE5_OQ012_INVALID_CLONOGENIC_FRACTION_F")
        else:
            f_dec = f_d

    eta_dec: Optional[Decimal] = None
    if eta_raw is None:
        missing_recovery = True
    else:
        eta_d = _to_exact_decimal(eta_raw)
        if eta_d is None or eta_d <= Decimal(0) or eta_d > Decimal(1):
            failures.append("FAIL_GATE5_OQ012_INVALID_SPIKE_IN_ETA")
        elif eta_d < MIN_GATE5_SPIKE_IN_ETA:
            failures.append("FAIL_GATE5_OQ012_SPIKE_IN_ETA_LT_0P30")
        else:
            eta_dec = eta_d

    n_eff_val: Optional[int] = None
    if n_eff_raw is None:
        missing_recovery = True
    elif not _is_strict_int(n_eff_raw) or n_eff_raw < 1 or n_eff_raw > MAX_CLONOGENIC_CELLS:
        failures.append("FAIL_GATE5_OQ012_INVALID_EFFECTIVE_TRIALS_N_EFF")
    else:
        n_eff_val = n_eff_raw

    if missing_recovery:
        holds.append("HOLD_GATE5_OQ012_INCOMPLETE_RECOVERY_DENOMINATOR")

    if valid_n is not None and f_dec is not None and eta_dec is not None and n_eff_val is not None:
        with localcontext() as ctx:
            ctx.prec = 75
            max_n_eff = int((Decimal(valid_n) * f_dec * eta_dec).to_integral_value(rounding=ROUND_FLOOR))
        if n_eff_val > max_n_eff:
            failures.append("FAIL_GATE5_OQ012_EFFECTIVE_TRIALS_EXCEEDS_FLOOR_N_F_ETA")

    if u95_s is None:
        holds.append("HOLD_MISSING_GATE5_U95_EXACT")
    elif not _is_num(u95_s) or float(u95_s) <= 0.0 or float(u95_s) > 1.0:
        failures.append("FAIL_GATE5_INVALID_U95_EXACT")

    if valid_k is not None and n_eff_val is not None:
        if valid_k > n_eff_val:
            if "FAIL_GATE5_OQ012_NONZERO_SURVIVOR_OR_U95_GT_1E8" not in failures:
                failures.append("FAIL_GATE5_OQ012_NONZERO_SURVIVOR_OR_U95_GT_1E8")
        else:
            u95_g5_dec = clopper_pearson_u95_decimal(valid_k, n_eff_val, alpha=0.05)
            if _is_num(u95_s) and 0.0 < float(u95_s) <= 1.0:
                u95_tol = min(Decimal("1e-15"), u95_g5_dec * Decimal("1e-12"))
                if Decimal.from_float(float(u95_s)) < u95_g5_dec - u95_tol:
                    failures.append("FAIL_GATE5_U95_EXACT_UNDERSTATED")
            if valid_k == 0:
                if n_eff_val < MIN_GATE5_OQ012_EFFECTIVE_TRIALS:
                    holds.append("HOLD_GATE5_OQ012_UNDERPOWERED_BELOW_299573228_EFFECTIVE_TRIALS")
                else:
                    if u95_g5_dec > MAX_GATE5_OQ012_U95:
                        failures.append("FAIL_GATE5_OQ012_NONZERO_SURVIVOR_OR_U95_GT_1E8")
                    if _is_num(u95_s) and Decimal(str(float(u95_s))) > MAX_GATE5_OQ012_U95:
                        failures.append("FAIL_GATE5_OQ012_NONZERO_SURVIVOR_OR_U95_GT_1E8")

    # Validate optional long-horizon OQ-012 metadata whenever supplied
    if "oq012_long_horizon_passed" in arch_g5 and arch_g5["oq012_long_horizon_passed"] is not True:
        failures.append("FAIL_GATE5_OQ012_NOT_PASSED")
    if "followup_days" in arch_g5:
        f_days = arch_g5["followup_days"]
        if not _is_num(f_days) or float(f_days) < 180.0:
            failures.append("FAIL_GATE5_OQ012_FOLLOWUP_LT_180D")
    if "viable_residual_burden_verified" in arch_g5 and arch_g5["viable_residual_burden_verified"] is not True:
        failures.append("FAIL_GATE5_OQ012_VIABLE_RESIDUAL_UNVERIFIED")


def evaluate_gate35_ensc_p19_singlepass(
    payload: Any,
    *,
    trusted_evidence_store: Optional[Mapping[str, Any]] = None,
    canonical_manifest: Optional[Mapping[str, Any]] = None,
    canonical_manifest_sha256: Optional[str] = None,
) -> dict[str, Any]:
    """Strict manifest-linked fail-closed evaluator for Gate 37-EnSC-P20-SinglePass.

    Enforces:
      - Structured FAIL dict on top-level non-dict payloads (never raises)
      - Mandatory hash-verified canonical_manifest context on AUTHENTICATED_ARCHIVED_WETLAB
      - Single versioned ENSC_TERMINAL_REAGENT_REGISTRY_V2 (FAIL all 15 ALK5/TGFBR1 inhibitors,
        FAIL blank tokens & generic unidentifiable class labels, ALLOW concrete registered compounds,
        HOLD unknown/unregistered reagents)
      - Collision-free upstream W6-C1 GATE-34 Dual-FailSafe (explicitly REJECTING live GATE-32
        as a DEC-130 Islet-SHIELD debris recall role collision!) and GATE-37-ENSC current assay
      - Exact live Blueprint Section 7 / wetlab_contract.py Gate 5 OQ-012 (k==0, n_eff>=299,573,228,
        eta>=0.30, n_eff <= floor(n*f*eta), exact 75-digit Decimal Clopper-Pearson U95<=1e-8)
      - Strict separation of Gate 0V bank qualification vs clinical lot-release authority:
        bank-only Gate 0V -> STAGE_LIMITED_BANK_QUALIFIED (bank_qualified=True, promotion_authorized=False);
        clinical lot release (promotion_authorized=True) requires clinical Gate 0V (whole_graft_stressed_tested=True)
        AND clinical Gate 34 (promotion_authorized=True) AND live OQ-012 Gate 5 (gate_source='GATE-5',
        promotion_authorized=True) AND clinical Genomic QC (GY-006) AND clinical GATE-37-ENSC
      - Synthetic fixture isolation (promotion_authorized=False on SYNTHETIC_FIXTURE).
    """
    if not isinstance(payload, dict):
        return {
            "gate": "Gate 37-EnSC-P19-SinglePass",
            "evidence_tier": None,
            "verdict": "FAIL",
            "decision": "FAIL",
            "authority_scope": "REJECTED_OR_HELD",
            "bank_qualified": False,
            "promotion_authorized": False,
            "reason": "INVALID_TOP_LEVEL_PAYLOAD_MUST_BE_DICT",
            "failures": ["INVALID_TOP_LEVEL_PAYLOAD_MUST_BE_DICT"],
            "holds": [],
        }
    failures: list[str] = []
    holds: list[str] = []

    ev_tier = payload.get("evidence_tier")
    if ev_tier is None:
        holds.append("MISSING_evidence_tier")
    elif not _is_nonempty_str(ev_tier) or ev_tier not in _ALLOWED_EVIDENCE_TIERS:
        failures.append("INVALID_evidence_tier")
    valid_tier = ev_tier if (_is_nonempty_str(ev_tier) and ev_tier in _ALLOWED_EVIDENCE_TIERS) else None

    _verify_canonical_manifest_context(canonical_manifest, canonical_manifest_sha256, valid_tier, failures)
    valid_construct_sha = _verify_parent_manifest_digests(payload, holds, failures)

    lot_id = payload.get("lot_id")
    if lot_id is None:
        holds.append("MISSING_lot_id")
    elif not _is_nonempty_str(lot_id):
        failures.append("INVALID_lot_id")
    valid_lot = lot_id if _is_nonempty_str(lot_id) else None

    mcb_id = payload.get("mcb_id")
    if mcb_id is None:
        holds.append("MISSING_mcb_id")
    elif not _is_nonempty_str(mcb_id):
        failures.append("INVALID_mcb_id")
    valid_mcb = mcb_id if _is_nonempty_str(mcb_id) else None

    product_id = payload.get("product_id")
    if product_id is None:
        holds.append("MISSING_product_id")
    elif not _is_nonempty_str(product_id) or product_id != "ISLET1_ARM_Z_ENSC_V090":
        failures.append("FAIL_PRODUCT_ID_NOT_CANONICAL_ARM_Z_ENSC")

    # Seedline & baseline oncogene/BCOR
    seed = payload.get("seedline_source")
    if seed is None:
        holds.append("MISSING_seedline_source")
    elif not _is_nonempty_str(seed):