OpenIslet

scripts/verify_iip0051_htmpk_azt_switch_gate.py

Standalone Zero-LIMS-Touch Verifier & Executable Stage-0 Switch Evaluator for

script Release v0.8.0 gen-eb955f8266035aba 30 KB · 3 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_iip0051_htmpk_azt_switch_gate.py · SHA-256: a2060242361d1b3d…

#!/usr/bin/env python3
"""
Standalone Zero-LIMS-Touch Verifier & Executable Stage-0 Switch Evaluator for
IIP-0051 / DEC-131 / GATE-33 (`Gate 33-HTMPK-AZT-PK`) / GY-002 Amendment:
  "Bind Designs Y and D hTMPK-F105Y/AZT gates (Y-09 / D1-04) to clinical AZT
   exposure, intracellular AZT-MP/TP PK, >= 10^6-cell clonogenic dynamic range,
   Marin 2012 counter-evidence, and post-mitotic scope boundaries"
  (Community submission by Hayley / @hsmosshs; GitHub Issue #51)

Capabilities:
  1. Verifies strict Zero-LIMS-Touch & Frozen SHA-256 invariance across
     wetlab_contract.py, ingest_wetlab_results.py, wetlab_endpoint_contract_v0.8.0.json,
     iip0044_foundry_v1_3_biologics_side_contract_v0.8.0.json,
     islet1_combinatorial_pareto_and_ladder_v0.8.0.json, and Playbook sec 4.1.20.
  2. Re-derives exact clinical human AZT exposure anchors (Wang et al. 1999
     PMID:10390227: 1.5 ug/mL = 5.6129 uM alone, 1.2 ug/mL = 4.4903 uM with
     abacavir at MW 267.24 g/mol; 100-200 uM static in vitro = 17.82x-44.54x Cmax),
     rat mitochondrial TK2 IC50 context (7.0 uM, McKee et al. 2004 PMID:15371631),
     and clonogenic dynamic-range bounds (proving why 70% flow-cytometry death =
     0.5229 log10 is incommensurable with >= 4.0-log10 clonogenic clearance and
     why >= 10^6 plated clonogenic cells/arm are required).
  3. Provides fail-closed, strict-JSON executable Stage-0 Gate 33 adjudication
     (`evaluate_gate33_htmpk_azt_switch`, `--evaluate-azt-switch <json>`) with:
       - Separate promoter qualification (`CDK1p` Y-09 vs 404-bp `CDK1_300` D1-04)
       - Hard GY-002 rejection (`FAIL_GY002_POSTMITOTIC_SCOPE_VIOLATION`, exit 3)
         if claimed as a post-mitotic whole-graft erasability substitute
       - Rejection of supraphysiologic >= 50 uM-only AZT certification
       - Mandatory intracellular AZT-MP/TP LC-MS + >= 10^6 clonogenic arm +
         matched 10 nM AP1903 iCasp9 comparator + 1:100 mature Stage-7 beta-cell
         bystander viability/GSIS & mitochondrial safety check
       - Hard firewall preserving primary AAVS1 iCasp9 (`primary_aavs1_icasp9_gate_unaffected = True`)
  4. Audits Playbook Y-09/D1-04/R3P-05 unpinned AZT gap, GY-002 sync,
     ISLET-1-BLUEPRINT.md Design Y/D namespace disambiguation, and
     stage0_decision_tree_v1.json append-only block parity.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import math
import sys
from pathlib import Path
from typing import Any, Dict, List, Mapping, Optional, Tuple

sys.dont_write_bytecode = True

SCRIPT_PATH = Path(__file__).resolve()
SCRIPT_DIR = SCRIPT_PATH.parent
REPO_ROOT = SCRIPT_DIR.parent

GENERATED_DATE = "2026-12-01"
CONTRIBUTION_ID = "IIP-0051"
DECISION_ID = "DEC-131"
GATE_ID = "GATE-33"
GATE_ALIAS = "Gate 33-HTMPK-AZT-PK"

SIDE_CONTRACT_REL = "data/protocols/iip0051_htmpk_azt_switch_gate33_side_contract_v0.8.0.json"
VERIFICATION_REL = "data/extracted/iip0051_htmpk_azt_switch_verification_v0.8.0.json"
PROTOCOL_DOC_REL = "docs/GATE-33-HTMPK-AZT-CLINICAL-PK-AND-CLONOGENIC-PROTOCOL.md"
DECISION_TREE_REL = "data/protocols/stage0_decision_tree_v1.json"
DECISION_TREE_KEY = "htmpk_f105y_azt_clinical_pk_and_clonogenic_gate33_iip_0051"
GRAVEYARD_REL = "data/graveyard/idea_graveyard_v0.5.json"
PLAYBOOK_REL = "docs/STAGE-0-EXECUTION-PLAYBOOK.md"
BLUEPRINT_REL = "ISLET-1-BLUEPRINT.md"
GATE0V_REL = "docs/GATE-0V-WHOLEGRAFT-PROTOCOL.md"

FROZEN_SHA256_PINS: Dict[str, str] = {
    "scripts/wetlab_contract.py": "331ecd2f2d8602dfceae8b89263d0f360cfadfd0638a46d7d668a376294cfc73",
    "scripts/ingest_wetlab_results.py": "e050593675170515382257ce379449db596c87cc06ffc26d31d128e127630cb1",
    "data/protocols/wetlab_endpoint_contract_v0.8.0.json": "757bc1d9c2722c129cc4fd5962e8995b9f5bc5f7035f8530f5716da9aa2ac26f",
    "data/protocols/iip0044_foundry_v1_3_biologics_side_contract_v0.8.0.json": "458a67aee973579d1091e50e97c31bbb356072ff9f4b21ab6184bc403d19f51e",
    "data/extracted/islet1_combinatorial_pareto_and_ladder_v0.8.0.json": "460ebc1939eb98b38627eaa7d6603c086e5a75c127fc1ddeced0d5a325305f40",
}
EXPECTED_PLAYBOOK_SEC4120_SHA256 = "e3fb5ec701678dfdeb62a77c15866327842b60b6b4c503cb86dfc79885a626a8"

ALLOWED_PROMOTER_CONSTRUCTS = frozenset({
    "DESIGN_Y_CLYBL_CDK1P_HTMPK_F105Y",
    "DESIGN_D_CLYBL_404BP_CDK1_300_HTMPK_F105Y",
})
AZT_MW_G_MOL = 267.24
HUMAN_CMAX_ALONE_UG_ML = 1.5
HUMAN_CMAX_WITH_ABC_UG_ML = 1.2
MAX_CERTIFYING_CLINICAL_AZT_PEAK_UM = 10.0
MIN_CLINICAL_AZT_DAYS = 5.0
MIN_CLONOGENIC_PLATED = 1_000_000
MIN_CLONOGENIC_L95_LOG10 = 4.0
MIN_BYSTANDER_BETA_VIAB_L95_PCT = 85.0
MIN_BYSTANDER_BETA_GSIS_L95_PCT = 85.0


class StrictJsonError(ValueError):
    """Raised on malformed, duplicate-key, or non-finite JSON input."""


def _reject_nonfinite_constant(tok: str) -> Any:
    raise StrictJsonError(f"Non-finite JSON constant rejected: {tok}")


def _reject_duplicate_keys_pairs_hook(pairs: List[Tuple[str, Any]]) -> Dict[str, Any]:
    out: Dict[str, Any] = {}
    for k, v in pairs:
        if k in out:
            raise StrictJsonError(f"Duplicate JSON object key rejected: {k!r}")
        out[k] = v
    return out


def load_strict_json_text(text: str, label: str = "input") -> Any:
    try:
        return json.loads(
            text,
            parse_constant=_reject_nonfinite_constant,
            object_pairs_hook=_reject_duplicate_keys_pairs_hook,
        )
    except StrictJsonError:
        raise
    except Exception as exc:
        raise StrictJsonError(f"Invalid JSON in {label}: {exc}") from exc


def load_strict_json_file(path: Path) -> Any:
    return load_strict_json_text(path.read_text(encoding="utf-8"), label=str(path))


def sha256_file(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def _extract_playbook_sec4120_sha256(playbook_path: Path) -> str:
    pb_norm = playbook_path.read_text(encoding="utf-8").replace("\r\n", "\n")
    start_marker = "#### 4.1.20 Preregistered Autologous `D1b-Auto-C v2`"
    end_marker = "<!-- END_IIP0035_PLAYBOOK_SECTION_4_1_20 -->"
    start_idx = pb_norm.find(start_marker)
    end_idx = pb_norm.find(end_marker, start_idx if start_idx >= 0 else 0)
    if start_idx == -1 or end_idx == -1:
        raise RuntimeError("Could not locate Playbook section 4.1.20 canonical boundaries")
    body = pb_norm[start_idx:end_idx].strip()
    return hashlib.sha256(body.encode("utf-8")).hexdigest()


def _is_real_number(val: Any) -> bool:
    return isinstance(val, (int, float)) and not isinstance(val, bool) and math.isfinite(float(val))


def _is_strict_int(val: Any) -> bool:
    return isinstance(val, int) and not isinstance(val, bool)


def compute_azt_pk_and_clonogenic_anchors() -> Dict[str, Any]:
    """Re-derive exact human AZT Cmax micromolar conversions and clonogenic bounds."""
    cmax_alone_uM = (HUMAN_CMAX_ALONE_UG_ML / AZT_MW_G_MOL) * 1000.0
    cmax_abc_uM = (HUMAN_CMAX_WITH_ABC_UG_ML / AZT_MW_G_MOL) * 1000.0
    fold_100_lo = 100.0 / cmax_alone_uM
    fold_100_hi = 100.0 / cmax_abc_uM
    fold_200_lo = 200.0 / cmax_alone_uM
    fold_200_hi = 200.0 / cmax_abc_uM
    marin_70pct_log10 = -math.log10(1.0 - 0.70)
    # Exact 1-sided 95% binomial zero-survivor sample size for U95 <= 1e-4 (4-log10 kill):
    n_zero_surv_4log = math.ceil(math.log(0.05) / math.log(1.0 - 1e-4))
    return {
        "azt_mw_g_mol": AZT_MW_G_MOL,
        "human_300mg_cmax_alone_uM": round(cmax_alone_uM, 4),
        "human_300mg_cmax_with_abacavir_uM": round(cmax_abc_uM, 4),
        "static_100uM_vs_cmax_fold_range": [round(fold_100_lo, 2), round(fold_100_hi, 2)],
        "static_200uM_vs_cmax_fold_range": [round(fold_200_lo, 2), round(fold_200_hi, 2)],
        "rat_mitochondrial_tk2_ic50_uM": 7.0,
        "marin_2012_70pct_flow_death_nominal_log10": round(marin_70pct_log10, 4),
        "exact_zero_survivor_clonogenic_trials_for_u95_le_1e_4": n_zero_surv_4log,
        "min_required_clonogenic_cells_plated_per_arm": MIN_CLONOGENIC_PLATED,
    }


def evaluate_gate33_htmpk_azt_switch(observation: Mapping[str, Any]) -> Dict[str, Any]:
    """
    Fail-closed executable Stage-0 evaluator for Gate 33 (`Gate 33-HTMPK-AZT-PK`).

    HARD INVARIANTS:
      - `postmitotic_whole_graft_substitute_authorized` is ALWAYS False.
      - `primary_aavs1_icasp9_gate_unaffected` is ALWAYS True on chr13 backup HOLDs.
      - Claiming post-mitotic whole-graft substitution emits FAIL_GY002_POSTMITOTIC_SCOPE_VIOLATION (exit 3).
    """
    reasons: List[str] = []

    def _res(
        verdict: str,
        exit_code: int,
        chr13_qualified: bool,
        derived: Dict[str, Any],
    ) -> Dict[str, Any]:
        return {
            "gate_id": GATE_ID,
            "gate_alias": GATE_ALIAS,
            "verdict": verdict,
            "exit_code": exit_code,
            "chr13_backup_switch_qualified": bool(chr13_qualified),
            "postmitotic_whole_graft_substitute_authorized": False,
            "primary_aavs1_icasp9_gate_unaffected": True,
            "reasons": reasons,
            "derived_summary": derived,
        }

    if not isinstance(observation, Mapping):
        reasons.append("Observation payload must be a JSON object.")
        return _res("HOLD_INVALID_OR_MISSING_INPUT", 2, False, {})

    # 1. Hard GY-002 post-mitotic scope boundary check
    claimed_pm = observation.get("claimed_as_postmitotic_whole_graft_substitute")
    if not isinstance(claimed_pm, bool):
        reasons.append("Missing boolean claimed_as_postmitotic_whole_graft_substitute declaration.")
        return _res("HOLD_INVALID_OR_MISSING_INPUT", 2, False, {})
    if claimed_pm is True:
        reasons.append(
            "GY-002 HARD BLOCK: CDK1p/CDK1_300::hTMPK-F105Y is dividing-escape containment only "
            "and is NEVER a post-mitotic whole-graft erasability substitute for pan-lineage AAVS1 iCasp9/AP1903."
        )
        return _res("FAIL_GY002_POSTMITOTIC_SCOPE_VIOLATION", 3, False, {"claimed_postmitotic_substitute": True})

    # 2. Separate promoter architecture check (Y-09 CDK1p vs D1-04 404-bp CDK1_300)
    construct_id = observation.get("promoter_construct_id")
    if construct_id not in ALLOWED_PROMOTER_CONSTRUCTS:
        reasons.append(
            f"promoter_construct_id={construct_id!r} must be explicitly declared in {sorted(ALLOWED_PROMOTER_CONSTRUCTS)} "
            "(Y-09 CDK1p and D1-04 404-bp CDK1_300 must be qualified separately)."
        )
        return _res("HOLD_INVALID_OR_MISSING_INPUT", 2, False, {})

    # 3. Validate clinical AZT PK & intracellular AZT-MP/TP block
    pk_arm = observation.get("clinical_azt_pk_arm")
    if not isinstance(pk_arm, Mapping):
        reasons.append("Missing clinical_azt_pk_arm object.")
        return _res("HOLD_INVALID_OR_MISSING_INPUT", 2, False, {})

    peak_uM = pk_arm.get("certifying_azt_peak_uM")
    days = pk_arm.get("exposure_duration_days")
    lcms_ok = pk_arm.get("intracellular_azt_mp_tp_lcms_verified")
    if not _is_real_number(peak_uM) or float(peak_uM) <= 0.0:
        reasons.append(f"Invalid certifying_azt_peak_uM={peak_uM!r}.")
        return _res("HOLD_INVALID_OR_MISSING_INPUT", 2, False, {})
    if not _is_real_number(days) or float(days) <= 0.0:
        reasons.append(f"Invalid exposure_duration_days={days!r}.")
        return _res("HOLD_INVALID_OR_MISSING_INPUT", 2, False, {})
    if not isinstance(lcms_ok, bool):
        reasons.append("Missing boolean intracellular_azt_mp_tp_lcms_verified.")
        return _res("HOLD_INVALID_OR_MISSING_INPUT", 2, False, {})

    derived: Dict[str, Any] = {
        "promoter_construct_id": construct_id,
        "certifying_azt_peak_uM": float(peak_uM),