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…

    """Return a canonical copy of an upstream_lot_evidence_record_schema_v1 (v2_round5_unified) record with verified archive_sha256."""
    rec = json.loads(json.dumps(dict(record)))
    rec.pop("archive_sha256", None)
    rec.pop("record_sha256", None)
    rec["archive_sha256"] = compute_canonical_record_sha256(rec)
    return rec


def build_trusted_evidence_store(records: Sequence[Mapping[str, Any]]) -> Dict[str, Dict[str, Any]]:
    """Index sealed archived records by their verified canonical archive_sha256."""
    store: Dict[str, Dict[str, Any]] = {}
    for rec in records:
        require_cond(isinstance(rec, Mapping), "Evidence store record must be a mapping")
        arch_sha = rec.get("archive_sha256")
        require_cond(_is_nonzero_sha256_hex(arch_sha), "Evidence store record missing non-zero archive_sha256")
        recomp = compute_canonical_record_sha256(rec)
        require_cond(recomp == arch_sha, f"Evidence store record digest mismatch: {arch_sha} != {recomp}")
        store[str(arch_sha)] = json.loads(json.dumps(dict(rec)))
    return store


def _lookup_in_trusted_store(
    trusted_evidence_store: Any,
    archive_sha: str,
    record_id: Optional[str] = None,
) -> Tuple[Optional[Dict[str, Any]], str]:
    """Resolve an archived record by archive_sha256 and/or record_id with strict alias consistency.

    Returns (record_dict_or_None, status) where status is 'OK', 'NOT_FOUND', or
    'CONFLICTING_INDEX_ALIASES'. If both record_id and archive_sha256 keys exist in the store
    (or nested records_by_sha256 / records_by_id maps), enforces exact complete body equality.
    """
    if trusted_evidence_store is None or not _is_nonzero_sha256_hex(archive_sha):
        return None, "NOT_FOUND"
    valid_rid = record_id if _is_clean_str(record_id) else None

    if isinstance(trusted_evidence_store, Path):
        path_candidates: List[Path] = [trusted_evidence_store / f"{archive_sha}.json"]
        if valid_rid is not None and "/" not in valid_rid and "\\" not in valid_rid and ".." not in valid_rid:
            p_rid = trusted_evidence_store / f"{valid_rid}.json"
            if p_rid != path_candidates[0]:
                path_candidates.append(p_rid)
        existing_paths = [p for p in path_candidates if p.is_file()]
        if not existing_paths:
            return None, "NOT_FOUND"
        loaded: List[Dict[str, Any]] = []
        for p in existing_paths:
            try:
                obj = load_strict_json_text(p.read_text(encoding="utf-8"), p.name)
            except (ValueError, OSError):
                return None, ("CONFLICTING_INDEX_ALIASES" if len(existing_paths) > 1 else "NOT_FOUND")
            if not isinstance(obj, dict):
                return None, ("CONFLICTING_INDEX_ALIASES" if len(existing_paths) > 1 else "NOT_FOUND")
            loaded.append(obj)
        first = loaded[0]
        for other in loaded[1:]:
            if not _strict_json_equal(first, other):
                return None, "CONFLICTING_INDEX_ALIASES"
        return first, "OK"

    if isinstance(trusted_evidence_store, Mapping):
        raw_hits: List[Any] = []
        if archive_sha in trusted_evidence_store:
            raw_hits.append(trusted_evidence_store[archive_sha])
        if valid_rid is not None and valid_rid != archive_sha and valid_rid in trusted_evidence_store:
            raw_hits.append(trusted_evidence_store[valid_rid])
        nested_sha = trusted_evidence_store.get("records_by_sha256")
        if isinstance(nested_sha, Mapping) and archive_sha in nested_sha:
            raw_hits.append(nested_sha[archive_sha])
        nested_id = trusted_evidence_store.get("records_by_id")
        if valid_rid is not None and isinstance(nested_id, Mapping) and valid_rid in nested_id:
            raw_hits.append(nested_id[valid_rid])
        if not raw_hits:
            return None, "NOT_FOUND"
        dict_hits: List[Dict[str, Any]] = []
        for hit in raw_hits:
            if not isinstance(hit, Mapping):
                return None, ("CONFLICTING_INDEX_ALIASES" if len(raw_hits) > 1 else "NOT_FOUND")
            dict_hits.append(dict(hit))
        first = dict_hits[0]
        for other in dict_hits[1:]:
            if not _strict_json_equal(first, other):
                return None, "CONFLICTING_INDEX_ALIASES"
        return first, "OK"
    return None, "NOT_FOUND"


def _build_gate32_emitted_receipt(
    *,
    arm_id: Optional[str],
    product_id: Optional[str],
    lot_id: Optional[str],
    bank_id: Optional[str],
    bank_origin: Optional[str],
    construct_manifest_sha256: Optional[str],
    evidence_tier: Optional[str],
    decision: str,
    authority_scope: str,
    bank_qualified: bool,
    promotion_authorized: bool,
    dual_switch_lot_qualified: bool = False,
    primary_switch_id: Optional[str] = None,
    secondary_switch_id: Optional[str] = None,
    g0v_archive_sha256: Optional[str] = None,
    g5_archive_sha256: Optional[str] = None,
) -> Dict[str, Any]:
    """Emit an interoperable Gate 34 (W6_HYGIENE_DUAL_FAILSAFE) receipt conforming verbatim to v2_round5_unified (14 required fields + prerequisite archive digests)."""
    pid = product_id or "UNRESOLVED_PRODUCT"
    lid = lot_id or "UNRESOLVED_LOT"
    bid = bank_id or "UNRESOLVED_BANK"
    borig = bank_origin if (bank_origin in ALLOWED_BANK_ORIGINS) else (bank_origin or "UNRESOLVED_BANK_ORIGIN")
    csha = construct_manifest_sha256 if _is_nonzero_sha256_hex(construct_manifest_sha256) else "UNRESOLVED_CONSTRUCT_MANIFEST"
    etier = evidence_tier if (evidence_tier in ALLOWED_EVIDENCE_TIERS) else "SYNTHETIC_FIXTURE"
    ascope = authority_scope if (authority_scope in ALLOWED_AUTHORITY_SCOPES) else "REJECTED_OR_HELD"
    passed_or_synth = decision in ("PASS", "SYNTHETIC_SELF_TEST_PASS")
    prim_sw: Optional[str] = primary_switch_id if (passed_or_synth and _is_clean_str(primary_switch_id)) else None
    sec_sw: Optional[str] = secondary_switch_id if (dual_switch_lot_qualified and _is_clean_str(secondary_switch_id)) else None
    g0v_sha: Optional[str] = g0v_archive_sha256 if _is_nonzero_sha256_hex(g0v_archive_sha256) else None
    g5_sha: Optional[str] = g5_archive_sha256 if _is_nonzero_sha256_hex(g5_archive_sha256) else None
    body: Dict[str, Any] = {
        "schema_version": "upstream_lot_evidence_record_schema_v1",
        "schema_revision": UPSTREAM_RECEIPT_SCHEMA_REVISION,
        "record_id": f"G34:{pid}:{lid}:{bid}",
        "gate_source": GATE_ID,
        "gate_role": GATE_ROLE,
        "product_id": pid,
        "lot_id": lid,
        "bank_id": bid,
        "bank_origin": borig,
        "canonical_arm_manifest_sha256": EXPECTED_ARM_MANIFEST_SHA256,
        "construct_manifest_sha256": csha,
        "evidence_tier": etier,
        "decision": decision,
        "authority_scope": ascope,
        "bank_qualified": bool(bank_qualified),
        "promotion_authorized": bool(promotion_authorized),
        "prerequisite_archive_sha256s": {
            "GATE-0V": g0v_sha,
            "GATE-5": g5_sha,
        },
        "dual_switch_lot_qualified": bool(dual_switch_lot_qualified),
        "dual_switch_qualified": bool(dual_switch_lot_qualified),
        "primary_switch": prim_sw,
        "secondary_switch": sec_sw,
        "arm_id": arm_id,
    }
    body["archive_sha256"] = compute_canonical_record_sha256(body)
    return body


def evaluate_gate32_hygiene_safecell_minifh_orthogonality(
    payload: Any,
    *,
    arm_manifest: Optional[Dict[str, Any]] = None,
    trusted_evidence_store: Optional[Any] = None,
) -> Dict[str, Any]:
    """Fail-closed executable Gate 34 adjudicator (W6_HYGIENE_DUAL_FAILSAFE; provisional IIP-0055 / DEC-136 / GY-033).

    Python function name `evaluate_gate32_hygiene_safecell_minifh_orthogonality` is preserved
    strictly for backward import compatibility while emitting collision-free `gate_source='GATE-34'`
    and `gate_role='W6_HYGIENE_DUAL_FAILSAFE'` (preserving live IIP-0046/DEC-126, live GATE-32/DEC-130,
    live GATE-33/DEC-131, and live GY-032/DEC-129).

    Decision lattice:
      - FAIL (authority_scope='REJECTED_OR_HELD', bank_qualified=False, promotion_authorized=False):
              explicit biological/policy violation, wrong type, overflow int (>1e100), tampered
              caller-supplied manifest, placeholder all-zero digest, archive digest tamper/mismatch,
              conflicting trusted_evidence_store index aliases, contradictory producer physical-
              qualification flags (physical_qualification_complete=False, release_authorizing=False,
              modeled_qualification_only=True), incoherent supporting-archive decision/scope tuple,
              unregistered/mismatched switch or locus in construct switch_registry_by_id, caller
              switch declaration contradicting construct registry, cross-product/lot/bank/bank_origin/
              auto-allo scope mismatch, Gate 5 / OQ-012 survivor_count_k >= 1, eta < 0.30,
              n_eff > floor(n*f*eta), U95(0, n_eff) > 1e-8 or understated U95, acute hypoxic/normoxic
              exact Decimal Clopper-Pearson U95 > 1e-4 or caller understatement, hypoxia_o2_pct != 1.0,
              malformed/incomplete 3-way governed benchmark comparator set (WT + D315A + iCasp8) or
              failing registered-switch benchmark observation, parent vs archived
              current_functional_assays_record mismatch, missing/failing secondary CDK1::HSV-TK assay
              on dual-switch arms, cHS4 or CBX3 barrier construct-ID digest mismatch or adverse CBX3
              promoter-originating aberrant splicing/leakage, AAV homogeneity < 95%, or failed G34-04 cohort.
      - HOLD (authority_scope='REJECTED_OR_HELD', bank_qualified=False, promotion_authorized=False):
              missing / None mandatory evidence field, unresolved trusted_evidence_store record,
              Gate 5 / OQ-012 underpowered below 299,573,228 effective clonogenic trials (incl. acute
              0/100,000 screen) or missing recovery/effective-denominator fields, unqualified cHS4 FI
              VEZF1 or CBX3 700-bp UCOE barrier archive missing, or missing G34-04 cohort under
              FULL_CLINICAL_PROMOTION.
      - STAGE_LIMITED_BANK_QUALIFIED (authority_scope='BANK_QUALIFICATION_ONLY',
              bank_qualified=True for authenticated wetlab / False for synthetic, promotion_authorized=False):
              Gate 0V carries bank-only qualification (PASS_WHOLEGRAFT_BANK_QUALIFICATION /
              PASS_COMPOSITE_BANK_QUALIFICATION) or evaluation_scope == 'BANK_QUALIFICATION_ONLY',
              with zero fails/holds and zero other stage limits.
      - STAGE_LIMITED_PASS (authority_scope='REJECTED_OR_HELD', bank_qualified=False,
              promotion_authorized=False): Stage-0 complete with zero fails/holds under explicit
              STAGE0_ONLY_NO_CLINICAL_PROMOTION scope (e.g. D1b pending G34-04 cohort).
      - SYNTHETIC_SELF_TEST_PASS (authority_scope='SYNTHETIC_SELF_TEST', bank_qualified=False,
              promotion_authorized=False): all checks pass, but payload or any upstream archived
              record has evidence_tier == 'SYNTHETIC_FIXTURE'.
      - PASS (authority_scope='CLINICAL_LOT_RELEASE', bank_qualified=True, promotion_authorized=True):
              ONLY when zero fails, zero holds, zero stage limits, evidence_tier ==
              'AUTHENTICATED_ARCHIVED_WETLAB', submission_type == 'EXTERNAL_LOT_SUBMISSION',
              evaluation_scope == 'FULL_CLINICAL_PROMOTION', clinical-lot-release Gate 0V & live
              Blueprint Section 7 OQ-012 Gate 5 (k=0, n_eff>=299,573,228, eta>=0.30, U95<=1e-8),
              and ALL required archived upstream + current-functional-assay receipts resolve
              cryptographically from trusted_evidence_store with exact identity bindings!
    """
    if not isinstance(payload, dict):
        rec_v1 = _build_gate32_emitted_receipt(
            arm_id=None, product_id=None, lot_id=None, bank_id=None, bank_origin=None,
            construct_manifest_sha256=None, evidence_tier=None,
            decision="FAIL", authority_scope="REJECTED_OR_HELD",
            bank_qualified=False, promotion_authorized=False,
        )
        return {
            "gate_id": GATE_ID,
            "gate_source": GATE_ID,
            "gate_role": GATE_ROLE,
            "verdict": "FAIL",
            "decision": "FAIL",
            "authority_scope": "REJECTED_OR_HELD",
            "bank_qualified": False,
            "promotion_authorized": False,
            "evaluation_context": "INVALID_NON_DICT",
            "evidence_tier": None,
            "fail_reasons": ["NON_DICT_PAYLOAD"],
            "hold_reasons": [],
            "stage_limited_reasons": [],
            "reasons": ["NON_DICT_PAYLOAD"],
            "upstream_lot_evidence_record_v1": rec_v1,
        }

    # Verify caller-supplied arm_manifest cryptographically against pinned canonical digest!
    if arm_manifest is None:
        arm_manifest = _load_default_arm_manifest_checked()
    else:
        manifest_ok, _ = verify_arm_manifest_dict_integrity(arm_manifest)
        if not manifest_ok:
            rec_v1 = _build_gate32_emitted_receipt(
                arm_id=None, product_id=None, lot_id=None, bank_id=None, bank_origin=None,
                construct_manifest_sha256=None, evidence_tier=None,
                decision="FAIL", authority_scope="REJECTED_OR_HELD",
                bank_qualified=False, promotion_authorized=False,
            )
            return {
                "gate_id": GATE_ID,
                "gate_source": GATE_ID,
                "gate_role": GATE_ROLE,
                "verdict": "FAIL",
                "decision": "FAIL",
                "authority_scope": "REJECTED_OR_HELD",
                "bank_qualified": False,