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…

    if arch_vals:
        if caller_res["has_explicit_none"]:
            code = f"CALLER_STUDY_{field_tag}_ALIAS_NULL_OR_MISMATCH"
            if code not in failures:
                failures.append(code)
            caller_conflict = True
        if caller_vals:
            if any(av != cv for _, av in arch_vals for _, cv in caller_vals):
                if mismatch_fail_code not in failures:
                    failures.append(mismatch_fail_code)
                caller_conflict = True
    else:
        if caller_res["has_explicit_none"] and caller_vals:
            hcode = f"HOLD_CALLER_STUDY_{field_tag}_ALIAS_NULL"
            if hcode not in holds:
                holds.append(hcode)
            caller_conflict = True

    return arch_internal_conflict, arch_incomplete, caller_conflict


def _audit_study_level_host_aliases(
    rec: Mapping[str, Any],
    *,
    role: str,
    gate_tag: str,
    required_host: str = "SCID-Beige",
    alias_keys: Sequence[str] = STUDY_TERATOMA_HOST_ALIASES,
    wrong_host_fail_code: str,
    invalid_host_fail_code: str,
    missing_hold_code: str,
    holds: list[str],
    failures: list[str],
) -> dict[str, Any]:
    """Common study-level teratoma host-strain alias validator shared identically by GP2 & EnSC
    across BOTH archive and caller payloads (Audit R12-05)."""
    present_keys = [k for k in alias_keys if k in rec]
    explicit_none_keys = [k for k in present_keys if rec[k] is None]
    non_none_items = [(k, rec[k]) for k in present_keys if rec[k] is not None]

    valid_vals: list[tuple[str, str]] = []
    has_invalid = False
    has_wrong_host = False
    has_alias_conflict = False

    for k, v in non_none_items:
        if not _is_nonempty_str(v):
            has_invalid = True
        else:
            valid_vals.append((k, v))
            if not _is_canonical_id(v) or v != required_host:
                has_wrong_host = True

    if has_invalid:
        if invalid_host_fail_code not in failures:
            failures.append(invalid_host_fail_code)
    if has_wrong_host:
        if wrong_host_fail_code not in failures:
            failures.append(wrong_host_fail_code)
    if len(valid_vals) >= 2 and any(v != valid_vals[0][1] for _, v in valid_vals[1:]):
        has_alias_conflict = True
        code = f"FAIL_{gate_tag}_{role}_STUDY_HOST_STRAIN_ALIAS_CONFLICT"
        if code not in failures:
            failures.append(code)

    has_explicit_none = bool(explicit_none_keys)
    all_missing = len(non_none_items) == 0
    incomplete = False
    if role == "ARCHIVE":
        if all_missing or has_explicit_none:
            incomplete = True
            if missing_hold_code not in holds:
                holds.append(missing_hold_code)
    else:
        if all_missing:
            incomplete = True
            if missing_hold_code not in holds:
                holds.append(missing_hold_code)
        elif has_explicit_none:
            incomplete = True

    hard_fail = bool(has_invalid or has_wrong_host or has_alias_conflict)
    resolved_val: Optional[str] = valid_vals[0][1] if (valid_vals and not has_alias_conflict and not has_invalid) else None
    return {
        "present_keys": present_keys,
        "explicit_none_keys": explicit_none_keys,
        "valid_vals": valid_vals,
        "resolved_val": resolved_val,
        "has_invalid": has_invalid,
        "has_wrong_host": has_wrong_host,
        "has_alias_conflict": has_alias_conflict,
        "has_explicit_none": has_explicit_none,
        "all_missing": all_missing,
        "incomplete": incomplete,
        "hard_fail": hard_fail,
    }


def _reconcile_study_level_host_archive_and_caller(
    *,
    arch_res: Mapping[str, Any],
    caller_res: Mapping[str, Any],
    gate_tag: str,
    mismatch_fail_code: str,
    holds: list[str],
    failures: list[str],
) -> tuple[bool, bool, bool]:
    """Reconcile audited archive and caller study-level host-strain aliases (Audit R12-05)."""
    arch_internal_conflict = bool(arch_res["hard_fail"])
    arch_incomplete = bool(arch_res["incomplete"])
    caller_conflict = bool(caller_res["hard_fail"])

    arch_vals: list[tuple[str, str]] = list(arch_res["valid_vals"])
    caller_vals: list[tuple[str, str]] = list(caller_res["valid_vals"])

    if arch_vals:
        if caller_res["has_explicit_none"]:
            code = "CALLER_STUDY_HOST_STRAIN_ALIAS_NULL_OR_MISMATCH"
            if code not in failures:
                failures.append(code)
            caller_conflict = True
        if caller_vals:
            if any(av != cv for _, av in arch_vals for _, cv in caller_vals):
                if mismatch_fail_code not in failures:
                    failures.append(mismatch_fail_code)
                caller_conflict = True
    else:
        if caller_res["has_explicit_none"] and caller_vals:
            if "HOLD_CALLER_STUDY_HOST_STRAIN_ALIAS_NULL" not in holds:
                holds.append("HOLD_CALLER_STUDY_HOST_STRAIN_ALIAS_NULL")
            caller_conflict = True

    return arch_internal_conflict, arch_incomplete, caller_conflict


def _finalize_gate_verdict(
    gate: str,
    failures: list[str],
    holds: list[str],
    pass_verdict: str,
    pass_reason: str,
    *,
    evidence_tier: Optional[str],
    pass_authority_scope: str = "CLINICAL_LOT_RELEASE",
    bank_qualified_on_wetlab_pass: bool = True,
    authorize_promotion_on_wetlab_pass: bool = True,
    extra: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
    """Finalize verdict while STRICTLY enforcing synthetic fixture isolation and authority scopes.

    ANY SYNTHETIC_FIXTURE evaluation MUST return promotion_authorized=False, bank_qualified=False,
    authority_scope='SYNTHETIC_SELF_TEST', and decision='SYNTHETIC_SELF_TEST_PASS'.
    """
    out: dict[str, Any] = {"gate": gate, "evidence_tier": evidence_tier}
    if extra:
        out.update(extra)
    if failures:
        out.update({
            "verdict": "FAIL",
            "decision": "FAIL",
            "authority_scope": "REJECTED_OR_HELD",
            "bank_qualified": False,
            "promotion_authorized": False,
            "reason": failures[0],
            "failures": failures,
            "holds": holds,
        })
    elif holds:
        out.update({
            "verdict": "HOLD",
            "decision": "HOLD",
            "authority_scope": "REJECTED_OR_HELD",
            "bank_qualified": False,
            "promotion_authorized": False,
            "reason": holds[0],
            "failures": [],
            "holds": holds,
        })
    elif evidence_tier == "SYNTHETIC_FIXTURE":
        out.update({
            "verdict": "SYNTHETIC_SELF_TEST_PASS",
            "decision": "SYNTHETIC_SELF_TEST_PASS",
            "authority_scope": "SYNTHETIC_SELF_TEST",
            "bank_qualified": False,
            "promotion_authorized": False,
            "reason": f"SYNTHETIC_FIXTURE_ISOLATED_SELF_TEST_ONLY:{pass_reason}",
            "failures": [],
            "holds": [],
        })
    elif evidence_tier == "AUTHENTICATED_ARCHIVED_WETLAB":
        out.update({
            "verdict": pass_verdict,
            "decision": pass_verdict,
            "authority_scope": pass_authority_scope,
            "bank_qualified": bool(bank_qualified_on_wetlab_pass),
            "promotion_authorized": bool(authorize_promotion_on_wetlab_pass),
            "reason": pass_reason,
            "failures": [],
            "holds": [],
        })
    else:
        out.update({
            "verdict": "HOLD",
            "decision": "HOLD",
            "authority_scope": "REJECTED_OR_HELD",
            "bank_qualified": False,
            "promotion_authorized": False,
            "reason": "MISSING_OR_UNAUTHENTICATED_evidence_tier",
            "failures": [],
            "holds": holds + ["MISSING_OR_UNAUTHENTICATED_evidence_tier"],
        })
    return _enforce_strict_json_report(out)


def evaluate_gate35_sort_gp2(
    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 35-SORT-GP2 (Intermediate Bank Only).

    Enforces:
      - Structured FAIL dict on top-level non-dict payloads (never raises)
      - Mandatory hash-verified canonical_manifest context on AUTHENTICATED_ARCHIVED_WETLAB
      - Allogeneic-only intermediate MCB scope: even on wet-lab PASS, emits
        verdict='PASS_GP2_INTERMEDIATE_BANK_QUALIFIED', authority_scope='BANK_QUALIFICATION_ONLY',
        bank_qualified=True, promotion_authorized=False ALWAYS
      - Explicit challenge_dose_cells >= 10_000_000 and per_animal_exposures list
        (len == teratoma_n >= 12, unique animal_id, each dose_cells >= 10_000_000 & lot_id == lot_id)
      - Integer-count reconciliation, mature acinar <= 2.0%, SCID-Beige host, unified v2_round5_unified store.
    """
    if not isinstance(payload, dict):
        return {
            "gate": "Gate 37-SORT-GP2",
            "evidence_tier": None,
            "verdict": "FAIL",
            "decision": "FAIL",
            "authority_scope": "REJECTED_OR_HELD",
            "bank_qualified": False,
            "intermediate_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] = []