OpenIslet

scripts/verify_iip0043_wholegraft_gate0v_and_calibration.py

IIP-0043 / DEC-122 (CAND-034 / EXP-031 — Bucket 1 Closure, Stage S3-R2 Remediated)

script Release v0.8.0 gen-eb955f8266035aba 1008 KB · 76 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_iip0043_wholegraft_gate0v_and_calibration.py · SHA-256: 20706180ed1ed6a2…

                "allowed_qualification_tiers": list(PRODUCT_TIER_FAMILY_ALLOWED_TIERS[tier_family]),
                "execution_supported": bool(entry.get("execution_supported", False)),
                "required_ectopic_viral_receptors": list(CANONICAL_ECTOPIC_VIRAL_RECEPTORS.get(cid, ())),
                "tyk2_product_genotype_class": tyk2_mode,
                "aliases": list(entry.get("aliases") or []),
            }
            products_by_id[cid] = rec
            alias_to_canonical[cid] = cid
            for al in rec["aliases"]:
                if isinstance(al, str) and al.strip():
                    alias_to_canonical[al] = cid

    sc36_path = root / "data" / "protocols" / "iip0041_abx_cd64t_il1rn_side_contract_v0.8.0.json"
    if sc36_path.is_file():
        sc36 = strict_json_load_file(sc36_path, preserve_boundary_decimals=False)
        suite = sc36.get("modeb_core_abx_ciita_exon5_suite") or {}
        donors = list(suite.get("active_wave5_go_scope_donors") or []) + list(
            suite.get("archived_hold_comparator_donors") or []
        )
        for d in donors:
            did = d.get("fasta_record_id")
            if isinstance(did, str) and did.strip():
                rec = {
                    "product_variant_id": did,
                    "registry_source": "iip0041_abx_cd64t_il1rn_side_contract_v0.8.0.json",
                    "family": "ABX_MODEB_SIDE_CONTRACT",
                    "product_tier_family": "ALLOGENEIC_ABX_SIDE_CONTRACT",
                    "allowed_qualification_tiers": list(PRODUCT_TIER_FAMILY_ALLOWED_TIERS["ALLOGENEIC_ABX_SIDE_CONTRACT"]),
                    "execution_supported": False,
                    "manufacture_authorized": bool(d.get("manufacture_authorized", False)),
                    "required_ectopic_viral_receptors": list(CANONICAL_ECTOPIC_VIRAL_RECEPTORS.get(did, ())),
                    "tyk2_product_genotype_class": "TYK2_UNEDITED_DONOR_DECLARED",
                    "aliases": [],
                }
                products_by_id[did] = rec
                alias_to_canonical[did] = did

    return {
        "products_by_id": products_by_id,
        "alias_to_canonical": alias_to_canonical,
    }


def resolve_canonical_product_variant(
    raw_identifier: Any,
    *,
    openislet_root: Path | None = None,
) -> Dict[str, Any] | None:
    """
    Resolve a submitted product_variant_id (or registered alias) canonically against
    islet1_product_definitions_v0.8.0.json + allowlisted IIP-0041 ABX_L2_v2_* side contract.
    Returns None for unregistered, empty, whitespace-padded, or non-string identifiers.
    """
    if not _is_valid_identifier(raw_identifier):
        return None
    root = openislet_root.resolve() if openislet_root is not None else _resolve_roots(None, None)[0]
    reg = _load_canonical_product_registry_cached(str(root))
    cid = reg["alias_to_canonical"].get(str(raw_identifier))
    if cid is None:
        return None
    return copy.deepcopy(reg["products_by_id"][cid])


def _implied_ectopic_receptors_for_product(
    product_variant_id: str,
    *,
    openislet_root: Path | None = None,
) -> set[str]:
    """
    Return exact ectopic viral receptors required by a canonically registered product_variant_id.
    ZERO fragile substring inference: looks up strictly in the canonical product registry!
    """
    resolved = resolve_canonical_product_variant(product_variant_id, openislet_root=openislet_root)
    if resolved is None:
        return set()
    return set(resolved.get("required_ectopic_viral_receptors") or [])


def is_qualification_tier_allowed_for_product(
    canonical_product_def: Dict[str, Any] | None,
    qual_tier: Any,
) -> Tuple[bool, List[str]]:
    """
    R04-B1: Enforce strict canonical product-family-to-qualification-tier allowlist.
      - AUTOLOGOUS_D1B_PROCESS_QUAL is allowed ONLY for canonical autologous D1b-Auto-C
        variants (ISLET1_D1_AUTO_*).
      - BANK_QUALIFICATION and LOT_RELEASE_SURROGATE require allogeneic MCB-banked product
        families (rejecting autologous D1b variants on allogeneic tiers).
    """
    if canonical_product_def is None or not isinstance(qual_tier, str) or qual_tier not in ALLOWED_QUALIFICATION_TIERS:
        return False, []
    allowed = canonical_product_def.get("allowed_qualification_tiers") or []
    if qual_tier in allowed:
        return True, []
    fam = str(canonical_product_def.get("product_tier_family") or "UNKNOWN_FAMILY")
    pvid = str(canonical_product_def.get("product_variant_id") or "UNKNOWN_PRODUCT")
    return False, [
        "HOLD_INAPPLICABLE_QUALIFICATION_TIER_FOR_PRODUCT_FAMILY",
        f"HOLD_INAPPLICABLE_QUALIFICATION_TIER_{qual_tier}_FOR_{fam}_{pvid}",
    ]


def compute_canonical_qualification_artifact_sha256(record: Dict[str, Any]) -> str:
    """Canonical SHA-256 of an authenticated bank/process qualification record excluding its `sha256` field."""
    body = {k: v for k, v in record.items() if k != "sha256"}
    canonical = _canonical_json_dumps(body)
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def _safe_canonical_qualification_artifact_sha256(record: Dict[str, Any]) -> str | None:
    """Return canonical record SHA-256 or None if record contains non-finite floats, excessive depth, or non-JSON values."""
    try:
        return compute_canonical_qualification_artifact_sha256(record)
    except (TypeError, ValueError, OverflowError, RecursionError):
        return None


def build_authenticated_bank_qualification_record(
    *,
    mcb_id: str,
    product_variant_id: str | None = None,
    product_variant: str | None = None,
    bank_lot_id: str,
    bank_payload_sha256: str,
    verdict: str = "PASS_COMPOSITE_BANK_QUALIFICATION",
    operational_tier: str = "BANK_QUALIFICATION",
    legacy_tier: str = "READY_FOR_ENCAPSULATION_COMPLETE_STAGE0_EVIDENCE",
    legacy_evaluator_passed: bool = True,
    legacy_safety_kill_s9_triggered: bool = False,
    gate0v_verdict: str = "PASS_WHOLEGRAFT_BANK_QUALIFICATION",
    gate0v_evaluator_passed: bool = True,
    gate0v_hard_stops_count: int = 0,
    gate0v_holds_count: int = 0,
    antiviral_genotype_stratum: str = "TYK2_WT__IFIH1_WT_OR_A946T",
    approved_by_authority_id: str = "OPENISLET_QA_RELEASE_BOARD_V1",
) -> Dict[str, Any]:
    """Construct an authenticated, digest-bound prior bank-qualification record for storage in an external trusted store."""
    pvid = product_variant_id if product_variant_id is not None else product_variant
    rec: Dict[str, Any] = {
        "schema_version": BANK_QUAL_RECORD_SCHEMA_VERSION,
        "operational_tier": operational_tier,
        "verdict": verdict,
        "mcb_id": mcb_id,
        "product_variant_id": pvid,
        "product_variant": pvid,
        "antiviral_genotype_stratum": antiviral_genotype_stratum,
        "bank_lot_id": bank_lot_id,
        "bank_payload_sha256": bank_payload_sha256,
        "approved_by_authority_id": approved_by_authority_id,
        "legacy_tier": legacy_tier,
        "legacy_evaluator_passed": bool(legacy_evaluator_passed),
        "legacy_safety_kill_s9_triggered": bool(legacy_safety_kill_s9_triggered),
        "gate0v_verdict": gate0v_verdict,
        "gate0v_evaluator_passed": bool(gate0v_evaluator_passed),
        "gate0v_hard_stops_count": int(gate0v_hard_stops_count),
        "gate0v_holds_count": int(gate0v_holds_count),
    }
    rec["sha256"] = compute_canonical_qualification_artifact_sha256(rec)
    return rec


def build_authenticated_process_qualification_record(
    *,
    product_variant_id: str | None = None,
    product_variant: str | None = None,
    process_qual_id: str,
    process_qual_payload_sha256: str | None = None,
    verdict: str = "PASS_AUTOLOGOUS_D1B_PROCESS_QUALIFICATION",
    operational_tier: str = "AUTOLOGOUS_D1B_PROCESS_QUAL",
    underlying_gate0v_verdict: str = "PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL",
    underlying_gate0v_passed: bool = True,
    underlying_hard_stops_count: int = 0,
    underlying_holds_count: int = 0,
    approved_by_authority_id: str = "OPENISLET_QA_RELEASE_BOARD_V1",
) -> Dict[str, Any]:
    """Construct an authenticated prior autologous D1b process-qualification record aligned to autologous family semantics."""
    pvid = product_variant_id if product_variant_id is not None else product_variant
    pq_sha = (
        process_qual_payload_sha256
        if process_qual_payload_sha256 is not None
        else hashlib.sha256(f"OPENISLET_PROC_QUAL_PAYLOAD::{pvid}::{process_qual_id}".encode("utf-8")).hexdigest()
    )
    rec: Dict[str, Any] = {
        "schema_version": PROC_QUAL_RECORD_SCHEMA_VERSION,
        "operational_tier": operational_tier,
        "verdict": verdict,
        "product_variant_id": pvid,
        "product_variant": pvid,
        "process_qual_id": process_qual_id,
        "process_qual_payload_sha256": pq_sha,
        "approved_by_authority_id": approved_by_authority_id,
        "underlying_gate0v_verdict": underlying_gate0v_verdict,
        "underlying_gate0v_passed": bool(underlying_gate0v_passed),
        "underlying_hard_stops_count": int(underlying_hard_stops_count),
        "underlying_holds_count": int(underlying_holds_count),
    }
    rec["sha256"] = compute_canonical_qualification_artifact_sha256(rec)
    return rec


def compute_nw08_ocr_record_sha256(record: Dict[str, Any]) -> str:
    """R10-B1 Canonical SHA-256 of a bound NW-08 measured-OCR record excluding `ocr_record_sha256`."""
    body = {k: v for k, v in record.items() if k != "ocr_record_sha256"}
    canonical = _canonical_json_dumps(body)
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def _safe_nw08_ocr_record_sha256(record: Dict[str, Any]) -> str | None:
    """Return canonical NW-08 OCR record SHA-256 or None if record contains non-finite, excessive depth, or non-JSON values."""
    try:
        return compute_nw08_ocr_record_sha256(record)
    except (TypeError, ValueError, OverflowError, RecursionError):
        return None


def build_bound_nw08_ocr_record(
    *,
    lot_id: str,
    mcb_id: str,
    product_variant_id: str,
    route_id: str,
    lot_payload_sha256: str,
    measured_ocr: float,
    uncertainty_se: float,
    measurement_record_id: str,
    measurement_evidence_sha256: str,
    measurement_timestamp_utc: str = "2026-11-29T00:00:00Z",
    baseline_min_face_mmhg: float | None = None,
    baseline_vasc_ocr_mult: float | None = None,
    p_bed_mmhg: float | None = None,
    local_3d_slope_mmhg_per_pct: float | None = None,
    z_one_sided_95: float | None = None,
    floor_mmhg: float | None = None,
    always_solve_3d: bool | None = None,
    ocr_uncertainty_model: str | None = None,
    ocr_replicates_n: int | None = None,
    ocr_degrees_of_freedom: int | None = None,
    ocr_uncertainty_provenance: str | None = None,
    measured_ocr_u95_override: float | None = None,
) -> Dict[str, Any]:
    """
    R10-B1 + R14-B2 Construct a cryptographically lot-, geometry-, evidence-, and
    inferential-model-bound NW-08 measured-OCR sidecar record for coupled composite release
    (`--nw08-ocr-json`). Whenever `uncertainty_se > 0`, explicit inferential provenance
    (`ocr_uncertainty_model` + `ocr_replicates_n`/`ocr_degrees_of_freedom` or
    `ocr_uncertainty_provenance`/`measured_ocr_u95_override`) is bound into `ocr_record_sha256`.
    """
    rec: Dict[str, Any] = {
        "lot_id": lot_id,
        "mcb_id": mcb_id,