scripts/evaluate_gate0v_composite_release.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/evaluate_gate0v_composite_release.py · SHA-256: 2be0252340222fe4…
#!/usr/bin/env python3
"""
IIP-0043 / DEC-122 (CAND-034 / EXP-031) Executable Dual-Evaluator Composite Release Wrapper
(Round-02 Remediated across B1, B2, and B6).
Enforces Stage-0 dual-evaluator Option-2 composite release governance:
- Imports legacy OpenIslet/scripts/wetlab_contract.py (100% READ-ONLY; zero mutation)
AND standalone verify_iip0043_wholegraft_gate0v_and_calibration.py.
- B1 / R03-M2 (Trusted External Qualification Store): Prior BANK_QUALIFICATION and
AUTOLOGOUS_D1B_PROCESS_QUAL approvals are resolved SOLELY from an independent
external `--trusted-qualification-store <dir_or_registry.json>` — self-attested
prior qualification records embedded in the caller's lot bundle are NEVER accepted.
Omitting or failing external store verification emits `HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE`
(exit 2). Deployment prerequisite: software record-content and SHA-256 verification
require independent QA operator administration, write-restricted storage control, and
separation of duties over `--trusted-qualification-store`.
- B2 (Canonical Product/Lot/MCB Reconciliation): Resolves `product_variant_id` canonically
against `data/protocols/islet1_product_definitions_v0.8.0.json` (+ allowlisted `IIP-0041`
side-contract `ABX_L2_v2_*` donors), preserves canonical `product_variant_id`,
`current_lot_id`, and `mcb_id` when invoking `wetlab_contract.py`, and reconciles
`wetlab_contract.py`'s resolved `product_variant_id` against the composite envelope and
Gate 0V record. Unregistered variants, mismatches, or `execution_supported: false`
staged research comparators fail closed with `HOLD_COMPOSITE_RELEASE` (exit 2).
- B6 (Tier-Distinct PASS Codes & Adverse-Data Adjudication): Requires tier-matched Gate 0V
PASS codes (`PASS_WHOLEGRAFT_BANK_QUALIFICATION`, `PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE`,
`PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL`), propagates exact tested-vs-inherited scope,
and preserves `FAIL_HARD_STOP_COMPOSITE_RELEASE` (exit 3) for any submitted adverse finding.
Run with:
PYTHONDONTWRITEBYTECODE=1 python3 -B evaluate_gate0v_composite_release.py --self-test
PYTHONDONTWRITEBYTECODE=1 python3 -B evaluate_gate0v_composite_release.py --lot-json <lot.json> --trusted-qualification-store <store>
"""
from __future__ import annotations
import argparse
import copy
import hashlib
import importlib.util
import inspect
import json
from pathlib import Path
import sys
import tempfile
from typing import Any, Callable, Dict, List, Tuple
sys.dont_write_bytecode = True
SCRIPT_DIR = Path(__file__).resolve().parent
DEFAULT_RECEIPT_PATH = (
SCRIPT_DIR.parent / "data" / "extracted" / "iip0043_composite_release_evaluator_v0.8.0.json"
if SCRIPT_DIR.name == "scripts"
else SCRIPT_DIR / "composite_release_evaluator_receipt.json"
)
LEGACY_PASS_TIER = "READY_FOR_ENCAPSULATION_COMPLETE_STAGE0_EVIDENCE"
GATE0V_PASS_VERDICTS_BY_TIER: Dict[str, str] = {
"BANK_QUALIFICATION": "PASS_WHOLEGRAFT_BANK_QUALIFICATION",
"LOT_RELEASE_SURROGATE": "PASS_WHOLEGRAFT_LOT_RELEASE_SURROGATE",
"AUTOLOGOUS_D1B_PROCESS_QUAL": "PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL",
}
PASS_VERDICTS = frozenset({
"PASS_COMPOSITE_BANK_QUALIFICATION",
"PASS_COMPOSITE_CLINICAL_RELEASE",
"PASS_COMPOSITE_AUTOLOGOUS_CLINICAL_RELEASE",
})
CLINICAL_RELEASE_PASS_VERDICTS = frozenset({
"PASS_COMPOSITE_CLINICAL_RELEASE",
"PASS_COMPOSITE_AUTOLOGOUS_CLINICAL_RELEASE",
})
MAX_JSON_NESTING_DEPTH: int = 64
QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL: str = (
"CONDITIONAL_ON_MODELED_ASSUMPTIONS_PENDING_PHYSICAL_QUALIFICATION"
)
_V38_MOD_CACHE: Any = None
def _resolve_openislet_root(repo_root_arg: Path | None = None) -> Path:
if repo_root_arg is not None:
return repo_root_arg.resolve()
cand_inst = SCRIPT_DIR.parent
cand_sib = SCRIPT_DIR.parents[3] / "OpenIslet" if len(SCRIPT_DIR.parents) >= 4 else cand_inst
if (cand_inst / "scripts" / "wetlab_contract.py").is_file():
return cand_inst
return cand_sib
def _resolve_gate0v_verifier_path() -> Path:
for fname in (
"verify_iip0043_wholegraft_gate0v_and_calibration.py",
"verify_exp031_wholegraft_gate0v_and_calibration.py",
"verify_iip0044_wholegraft_gate0v_and_calibration.py",
):
cand = SCRIPT_DIR / fname
if cand.is_file():
return cand
return SCRIPT_DIR / "verify_iip0043_wholegraft_gate0v_and_calibration.py"
def _load_module(name: str, path: Path):
spec = importlib.util.spec_from_file_location(name, str(path))
if spec is None or spec.loader is None:
raise ImportError(f"Could not create module spec for {path}")
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
def _get_v38_module():
global _V38_MOD_CACHE
v38_path = _resolve_gate0v_verifier_path().resolve()
if _V38_MOD_CACHE is None:
for mod_name in ("verify_iip0043_wholegraft_gate0v_and_calibration", "iip0043_gate0v_verifier_shared"):
existing = sys.modules.get(mod_name)
existing_file = getattr(existing, "__file__", None) if existing is not None else None
if existing is not None and existing_file:
try:
if Path(existing_file).resolve() == v38_path:
_V38_MOD_CACHE = existing
break
except OSError:
pass
if _V38_MOD_CACHE is None:
_V38_MOD_CACHE = _load_module("iip0043_gate0v_verifier_shared", v38_path)
sys.modules.setdefault("iip0043_gate0v_verifier_shared", _V38_MOD_CACHE)
return _V38_MOD_CACHE
def _is_valid_sha256_hex(val: Any) -> bool:
return isinstance(val, str) and len(val) == 64 and all(c in "0123456789abcdef" for c in val) and len(set(val)) > 1
def _is_clean_nonempty_str(val: Any) -> bool:
return isinstance(val, str) and bool(val.strip()) and val == val.strip()
def strict_json_loads(
raw_text: str,
*,
max_int_abs: int | None = None,
max_depth: int = MAX_JSON_NESTING_DEPTH,
preserve_boundary_decimals: bool = True,
) -> Any:
"""Delegate strictly to the single canonical RFC-8259 JSON decoder in verify_iip0043 (R09-B1 + R10-B2 + R11-B4 + R12-B2)."""
return _get_v38_module().strict_json_loads(
raw_text,
max_int_abs=max_int_abs,
max_depth=max_depth,
preserve_boundary_decimals=preserve_boundary_decimals,
)
def compute_composite_payload_sha256(composite_doc: Dict[str, Any]) -> str:
"""Canonical SHA-256 of a composite lot release bundle excluding top-level payload_sha256."""
body = {k: v for k, v in composite_doc.items() if k != "payload_sha256"}
canonical = _get_v38_module()._canonical_json_dumps(body)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def compute_qualification_record_sha256(record: Dict[str, Any]) -> str:
"""Canonical SHA-256 of a bank/process qualification record excluding its `sha256` field."""
body = {k: v for k, v in record.items() if k != "sha256"}
canonical = _get_v38_module()._canonical_json_dumps(body)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def _call_with_optional_kwargs(fn: Callable[..., Any], payload: Dict[str, Any], optional_kwargs: Dict[str, Any]) -> Any:
"""Invoke an evaluator passing only optional kwargs present in its signature (or **kwargs)."""
sig = inspect.signature(fn)
params = sig.parameters
has_var_kw = any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values())
if has_var_kw:
return fn(payload, **optional_kwargs)
filtered = {k: v for k, v in optional_kwargs.items() if k in params}
return fn(payload, **filtered)
def evaluate_composite_clinical_release(
composite_doc: Dict[str, Any],
*,
legacy_evaluator: Callable[..., Dict[str, Any]] | None,
gate0v_evaluator: Callable[..., Dict[str, Any]] | None,
trusted_qualification_store: Path | str | None = None,
openislet_root: Path | None = None,
nw08_ocr_json_path: Path | str | None = None,
nw08_ocr_record: Dict[str, Any] | None = None,
_revalidating_archived_bank: bool = False,
) -> Dict[str, Any]:
"""
Fail-closed conjunction of legacy Stage-0 wetlab_contract.py AND whole-graft Gate 0V
evaluator bound to the same measured lot with:
- Shared canonical composite-envelope validation (`v38.validate_canonical_composite_envelope`)
enforced identically at BOTH direct submission AND archived bank replay (R08-B1)
- Canonical product_variant_id resolution & cross-evaluator reconciliation (B2)
- Independent external `--trusted-qualification-store` verification for all prior
bank/process qualification inheritance with live composite bank replay (B1 / R07-B1 / R08-B1)
- Mandatory fail-closed NW-08 measured-OCR enforcement whenever a lot (or verified trusted
record) declares `require_trusted_nw08_ocr_record = True` across BOTH Python API and CLI,
emitting `HOLD_NW08_REQUIRED_OCR_RECORD_MISSING` (`release_authorizing = False`, exit 2)
when omitted while preserving any independent biological `FAIL_HARD_STOP` (R11-B1)
- Tier-distinct PASS codes & full adverse-data adjudication across tiers (B6)
"""
hard_stops: List[str] = []
holds: List[str] = []
resolved_root = _resolve_openislet_root(openislet_root)
v38 = _get_v38_module()
if legacy_evaluator is None:
holds.append("HOLD_COMPOSITE_MISSING_LEGACY_WETLAB_CONTRACT_EVALUATOR")
if gate0v_evaluator is None:
holds.append("HOLD_COMPOSITE_MISSING_GATE0V_WHOLEGRAFT_EVALUATOR")
if not isinstance(composite_doc, dict):
return {
"composite_verdict": "HOLD_COMPOSITE_RELEASE",
"release_authorizing": False,
"bank_qualification_authorized": False,
"qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
"physical_qualification_complete": False,
"operational_tier": None,
"hard_stops": [],
"holds": holds + ["HOLD_COMPOSITE_PAYLOAD_NOT_DICT"],
"lot_binding": None,
"tested_vs_inherited_scope": None,
"prior_qualification_authentication": None,
"legacy_result_summary": None,
"gate0v_result_summary": None,
"authenticated_bank_qualification_record": None,
}
# R08-B1: Validate the composite envelope through the EXACT SAME shared canonical validator
# used by archived composite bank replay (`v38.validate_canonical_composite_envelope`).
env = v38.validate_canonical_composite_envelope(composite_doc, openislet_root=resolved_root)
for eh in env["holds"]:
if eh not in holds:
holds.append(eh)
top_lot = env["top_lot"]
top_mcb = env["top_mcb"]
top_pvid_raw = env["top_pvid_raw"]
top_sha = env["top_sha"]
computed_comp_sha = env["computed_comp_sha"]
canonical_product_def = env["canonical_product_def"]
canonical_pvid = env["canonical_pvid"]
legacy_obs = env["legacy_obs"]
gate0v_obs = env["gate0v_obs"]
leg_pvid_canon = env["leg_pvid_canon"]
qual_tier = env["qual_tier"]