OpenIslet

scripts/evaluate_gate0v_composite_release.py

IIP-0043 / DEC-122 (CAND-034 / EXP-031) Executable Dual-Evaluator Composite Release Wrapper

script Release v0.8.0 gen-eb955f8266035aba 357 KB · 28 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/evaluate_gate0v_composite_release.py · SHA-256: 2be0252340222fe4…

    embedded_sha = cfg_obj.get("trust_config_sha256")
    recomp_sha = _safe_canonical_sha256_v2_round8({k: v for k, v in cfg_obj.items() if k != "trust_config_sha256"})
    if not _is_safe_sha256_v2_round8(embedded_sha) or recomp_sha != embedded_sha:
        return None, "TRUST_CONFIG_EMBEDDED_SHA256_MISMATCH"
    rel_store = cfg_obj.get("authorized_store_root")
    rel_manifest = cfg_obj.get("canonical_arm_manifest_path")
    rel_inst_id = cfg_obj.get("installation_identity_path")
    if (
        not _is_safe_repo_rel_path_v2_round9(rel_store)
        or not _is_safe_repo_rel_path_v2_round9(rel_manifest)
        or not _is_safe_repo_rel_path_v2_round9(rel_inst_id)
    ):
        return None, "TRUST_CONFIG_UNSAFE_RELATIVE_PATHS"
    reg_pin = cfg_obj.get("qa_issuer_registry_sha256")
    man_pin = cfg_obj.get("canonical_arm_manifest_sha256")
    inst_pin = cfg_obj.get("installation_identity_sha256")
    expected_inst_id = cfg_obj.get("installation_id")
    if (
        not _is_safe_sha256_v2_round8(reg_pin)
        or not _is_safe_sha256_v2_round8(man_pin)
        or not _is_safe_sha256_v2_round8(inst_pin)
        or not _is_safe_store_id_v2_round8(expected_inst_id)
    ):
        return None, "TRUST_CONFIG_INVALID_PIN_DIGESTS"
    root_res = resolved_root.resolve()
    store_raw = resolved_root / rel_store
    manifest_raw = resolved_root / rel_manifest
    inst_raw = resolved_root / rel_inst_id
    store_res = store_raw.resolve()
    manifest_res = manifest_raw.resolve()
    try:
        store_res.relative_to(root_res)
        manifest_res.relative_to(root_res)
    except ValueError:
        return None, "TRUST_CONFIG_PATH_ESCAPES_REPO_ROOT"

    # Audit R9-03: Separate installation identity file verification (check symlink BEFORE resolve!)
    if inst_raw.is_symlink():
        return None, "INSTALLATION_IDENTITY::INSTALLATION_IDENTITY_SYMLINK_FORBIDDEN"
    inst_res = inst_raw.resolve()
    try:
        inst_res.relative_to(root_res)
    except ValueError:
        return None, "INSTALLATION_IDENTITY::PATH_ESCAPES_REPO_ROOT"
    expected_inst_default = (resolved_root / _GATE0V_INSTALLATION_IDENTITY_REL_PATH_V2_ROUND10).resolve()
    if inst_res != expected_inst_default:
        return None, "INSTALLATION_IDENTITY::INSTALLATION_IDENTITY_PATH_MISMATCH"
    if not inst_raw.is_file():
        return None, "INSTALLATION_IDENTITY::MISSING_INSTALLATION_IDENTITY"
    try:
        inst_raw_bytes = inst_raw.read_bytes()
    except OSError as exc:
        return None, f"INSTALLATION_IDENTITY::READ_ERROR:{type(exc).__name__}"
    inst_raw_sha = hashlib.sha256(inst_raw_bytes).hexdigest()
    if inst_raw_sha != _PINNED_GATE0V_INSTALLATION_IDENTITY_SHA256:
        return None, f"INSTALLATION_IDENTITY::COMPILED_PIN_MISMATCH:{inst_raw_sha}!={_PINNED_GATE0V_INSTALLATION_IDENTITY_SHA256}"
    if inst_raw_sha != inst_pin:
        return None, f"INSTALLATION_IDENTITY::TRUST_CONFIG_PIN_MISMATCH:{inst_raw_sha}!={inst_pin}"
    try:
        inst_obj = json.loads(
            inst_raw_bytes.decode("utf-8"),
            object_pairs_hook=_strict_no_dup_pairs_v2_round8,
            parse_constant=_reject_json_constant_v2_round8,
        )
    except (UnicodeDecodeError, ValueError, TypeError) as exc:
        return None, f"INSTALLATION_IDENTITY::MALFORMED_JSON:{type(exc).__name__}"
    if not isinstance(inst_obj, dict):
        return None, "INSTALLATION_IDENTITY::NOT_MAPPING"
    if inst_obj.get("schema_version") != _GATE0V_INSTALLATION_IDENTITY_SCHEMA_V2_ROUND10:
        return None, "INSTALLATION_IDENTITY::SCHEMA_INVALID"
    if inst_obj.get("owner_authority_id") != _GATE0V_INSTALLATION_IDENTITY_AUTHORITY_ID_V2_ROUND10:
        return None, "INSTALLATION_IDENTITY::OWNER_AUTHORITY_INVALID"
    inst_embedded_sha = inst_obj.get("installation_identity_sha256")
    inst_recomp_sha = _safe_canonical_sha256_v2_round8(
        {k: v for k, v in inst_obj.items() if k != "installation_identity_sha256"}
    )
    if not _is_safe_sha256_v2_round8(inst_embedded_sha) or inst_recomp_sha != inst_embedded_sha:
        return None, "INSTALLATION_IDENTITY::EMBEDDED_SHA256_MISMATCH"
    if inst_obj.get("installation_id") != expected_inst_id:
        return None, f"INSTALLATION_IDENTITY::INSTALLATION_ID_MISMATCH:{inst_obj.get('installation_id')!r}!={expected_inst_id!r}"
    if inst_obj.get("authorized_qa_issuer_registry_sha256") != reg_pin:
        return None, (
            f"INSTALLATION_IDENTITY::AUTHORIZED_REGISTRY_SHA_DISAGREEMENT:"
            f"{inst_obj.get('authorized_qa_issuer_registry_sha256')!r}!={reg_pin!r}"
        )

    return {
        "config": cfg_obj,
        "config_sha256": raw_sha,
        "installation_identity": inst_obj,
        "installation_id": str(expected_inst_id),
        "installation_identity_sha256": inst_raw_sha,
        "provenance_mode": str(cfg_obj.get("provenance_mode") or ""),
        "installation_provenance_mode": str(inst_obj.get("provenance_mode") or ""),
        "authorized_store_raw_path": store_raw,
        "authorized_store_resolved": store_res,
        "canonical_manifest_raw_path": manifest_raw,
        "canonical_manifest_resolved": manifest_res,
        "qa_issuer_registry_sha256": str(reg_pin),
        "canonical_arm_manifest_sha256": str(man_pin),
    }, None


def _resolve_governed_manifest_and_arm_v2_round8(
    *,
    arm_id: Any,
    canonical_manifest_path: Path | str | None,
    openislet_root: Path | None,
) -> Tuple[Dict[str, Any] | None, str | None]:
    """Derive canonical_arm_manifest_sha256 STRICTLY from governed on-disk manifest bytes (Audit R7-07)."""
    resolved_root = _resolve_openislet_root(openislet_root)
    if canonical_manifest_path is not None:
        if not isinstance(canonical_manifest_path, (Path, str)):
            return None, "MALFORMED_CANONICAL_MANIFEST_PATH"
        mpath = Path(canonical_manifest_path)
    else:
        mpath = resolved_root / "data" / "protocols" / "wave6_canonical_arm_manifest.json"
    if mpath.is_symlink():
        return None, "CANONICAL_MANIFEST_SYMLINK_FORBIDDEN"
    if not mpath.is_file():
        return None, "CANONICAL_MANIFEST_UNAVAILABLE"
    try:
        raw_bytes = mpath.read_bytes()
        manifest_sha = hashlib.sha256(raw_bytes).hexdigest()
        manifest_obj = json.loads(
            raw_bytes.decode("utf-8"),
            object_pairs_hook=_strict_no_dup_pairs_v2_round8,
            parse_constant=_reject_json_constant_v2_round8,
        )
    except (OSError, UnicodeDecodeError, ValueError, TypeError):
        return None, "CANONICAL_MANIFEST_MALFORMED_JSON"
    if not isinstance(manifest_obj, dict) or not isinstance(manifest_obj.get("arms"), dict):
        return None, "CANONICAL_MANIFEST_INVALID_SCHEMA"
    if not isinstance(arm_id, str) or arm_id not in manifest_obj["arms"]:
        return None, "UNKNOWN_WAVE6_ARM_ID"
    arm_cfg = manifest_obj["arms"][arm_id]
    if not isinstance(arm_cfg, dict) or not isinstance(arm_cfg.get("product_id"), str) or not isinstance(arm_cfg.get("cell_origin"), str):
        return None, "CANONICAL_MANIFEST_MALFORMED_ARM_ROW"
    product_id = str(arm_cfg["product_id"])
    bank_origin = str(arm_cfg["cell_origin"])
    v38 = _get_v38_module()
    reg_rec = v38.resolve_canonical_product_variant(product_id, openislet_root=resolved_root)
    if reg_rec is None:
        return None, f"OWNER_REGISTRY_UNRESOLVED_PRODUCT:{product_id}"
    tier_family = str(reg_rec["product_tier_family"])
    expected_tier_family = "AUTOLOGOUS_D1B_AUTO_C" if bank_origin == "autologous_hiPSC" else "ALLOGENEIC_MCB_BANKED"
    if tier_family != expected_tier_family:
        return None, f"OWNER_REGISTRY_TIER_FAMILY_DISAGREEMENT:{tier_family}!={expected_tier_family}"
    return {
        "manifest": manifest_obj,
        "manifest_sha256": manifest_sha,
        "manifest_path": str(mpath),
        "product_id": product_id,
        "bank_origin": bank_origin,
        "tier_family": tier_family,
        "canonical_product_def": reg_rec,
        "resolved_root": resolved_root,
    }, None


def _make_canonical_gate0v_record_id_v2_round9(prefix: str, product_id: str, lot_id: str) -> str:
    """Build a strict <=64-char canonical ASCII record_id matching ^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$."""
    p_clean = product_id or "UNKNOWN_PRODUCT"
    l_clean = lot_id or "UNKNOWN_LOT"
    cand = f"{prefix}:{p_clean}:{l_clean}"
    if len(cand) <= 64 and _re_g0v.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,63}", cand):
        return cand
    short_h = hashlib.sha256(f"{prefix}:{p_clean}:{l_clean}".encode("utf-8")).hexdigest()[:16]
    pref_clean = _re_g0v.sub(r"[^A-Za-z0-9._:-]+", "-", prefix).strip("-._:") or "G0V"
    return f"{pref_clean[:24]}:{short_h}"


def _make_fail_closed_gate0v_custody_receipt_v2_round7(
    *,
    decision: str,
    authority_scope: str,
    evidence_tier: str,
    record_prefix: str,
    product_id: str,
    lot_id: str,
    bank_id: str,
    bank_origin: str,
    manifest_sha: str,
    construct_manifest_sha256: str,
    dossier_id: str | None,
    qa_signoff_id: str | None,
    custody_failure_reasons: List[str],
    extra_fields: Dict[str, Any] | None = None,
) -> Dict[str, Any]:
    body: Dict[str, Any] = {
        "schema_revision": "v2_round5_unified",
        "record_id": _make_canonical_gate0v_record_id_v2_round9(record_prefix, product_id, lot_id),
        "gate_source": "GATE-0V",
        "product_id": product_id or "",
        "lot_id": lot_id or "",
        "bank_id": bank_id or "",
        "bank_origin": bank_origin or "",
        "canonical_arm_manifest_sha256": manifest_sha or "",
        "construct_manifest_sha256": construct_manifest_sha256 or "",
        "evidence_tier": evidence_tier,
        "evidence_class": "UNAUTHENTICATED_FAIL_OR_HOLD",
        "operational_wetlab_authority": False,
        "plumbing_control_only": False,
        "decision": decision,
        "authority_scope": authority_scope,
        "bank_qualified": False,
        "promotion_authorized": False,
        "physical_qualification_complete": False,
        "release_authorizing": False,
        "modeled_qualification_only": False,
        "custody_verification_mode": "GOVERNED_ON_DISK_OWNER_STORE_AUTHENTICATED",
        "custody_authenticated": False,
        "physical_dossier_id": dossier_id,
        "qa_signoff_id": qa_signoff_id,
        "custody_failure_reasons": [str(x) for x in custody_failure_reasons],
        "lineages_verified": [],
        "whole_graft_stressed_tested": False,
    }
    if extra_fields:
        for k, v in extra_fields.items():
            if k not in ("archive_sha256", "record_sha256"):
                body[k] = v
    return _seal_gate0v_receipt_v2_round5(body)


def emit_gate0v_modeled_receipt_v2_round5(
    composite_result: Dict[str, Any],
    *,
    arm_id: str,
    lot_id: str,
    bank_id: str,
    construct_manifest_sha256: str,
    canonical_manifest_path: Path | str | None = None,
    canonical_arm_manifest: Dict[str, Any] | None = None,
    canonical_arm_manifest_sha256: str | None = None,
    openislet_root: Path | None = None,
) -> Dict[str, Any]:
    """Wrap an actual owning evaluate_composite_clinical_release() solver result into a sealed
    v2_round5_unified GATE-0V receipt strictly scoped to MODELED_COMPUTATIONAL_ONLY.
    Derives canonical_arm_manifest_sha256 strictly from governed manifest bytes when available and
    rejects authenticated physical wet-lab dossiers (non-substitution invariant)."""
    if not isinstance(composite_result, dict):
        raise ValueError("composite_result must be a dict emitted by evaluate_composite_clinical_release")
    if composite_result.get("dossier_type") == "AUTHENTICATED_PHYSICAL_WETLAB_GATE0V_DOSSIER":
        raise ValueError("NON_SUBSTITUTION_ERROR: physical wet-lab dossier cannot be wrapped as a modeled composite result")
    if composite_result.get("physical_qualification_complete") is True:
        raise ValueError("NON_SUBSTITUTION_ERROR: modeled receipt adapter requires physical_qualification_complete=False")
    if "composite_verdict" not in composite_result or "qualification_scope" not in composite_result:
        raise ValueError("composite_result missing required evaluate_composite_clinical_release keys (composite_verdict, qualification_scope)")
    if not _is_clean_nonempty_str(lot_id) or not _is_clean_nonempty_str(bank_id):