scripts/verify_iip0056_route4_omentum_and_exvivo_rest.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0056_route4_omentum_and_exvivo_rest.py · SHA-256: 25e12d578ba80b55…
d = one / d
delta = d * c
h *= delta
if abs(delta - one) <= eps:
return h
raise RuntimeError(f"Decimal incomplete beta continued fraction did not converge (a={a}, b={b}, x={x})")
def _reg_inc_beta_and_pdf_dec(
k_plus_1: int, n_minus_k: int, x: Decimal, log_beta_inv: Decimal
) -> Tuple[Decimal, Decimal]:
"""High-precision regularized incomplete beta I_x(k+1, n-k) and d/dx I_x(k+1, n-k) in active Decimal context."""
one = Decimal(1)
if x <= 0:
return Decimal(0), Decimal(0)
if x >= one:
return one, Decimal(0)
a = Decimal(k_plus_1)
b = Decimal(n_minus_k)
log_bt = log_beta_inv + a * x.ln() + b * (one - x).ln()
bt = Decimal(0) if log_bt < Decimal("-50000") else log_bt.exp()
if x < (a + one) / (a + b + 2):
ib = bt * _betacf_dec(a, b, x) / a
else:
ib = one - bt * _betacf_dec(b, a, one - x) / b
pdf = bt / (x * (one - x))
return ib, pdf
def clopper_pearson_u95_decimal(k: int, n: int, alpha: Any = Decimal("0.05")) -> Decimal:
"""Error-controlled pure-stdlib Decimal one-sided (1 - alpha) Clopper-Pearson upper bound.
Enforces exact integer domain 1 <= n <= 10^12 and 0 <= k <= n, evaluates Stirling ln(Gamma)
and Lentz continued-fraction I_p(k+1, n-k) at 75-digit Decimal precision (zero float64
lgamma cancellation at n=10^12), and certifies a conservative upper bracket hi with
I_lo < 1 - alpha <= I_hi and hi - lo <= 1e-28 * hi.
"""
require_cond(_is_strict_int(k) and _is_strict_int(n), "clopper_pearson_u95 requires bounded strict integers")
require_cond(1 <= n <= MAX_CLONOGENIC_CELLS, f"clopper_pearson_u95 n out of domain [1, {MAX_CLONOGENIC_CELLS}]: {n}")
require_cond(0 <= k <= n, f"clopper_pearson_u95 k out of domain [0, {n}]: {k}")
require_cond(_is_finite_number(alpha), f"Invalid alpha={alpha}")
a_d_in = _to_exact_decimal(alpha)
require_cond(ZERO_DEC < a_d_in < ONE_DEC, f"Invalid alpha={alpha}")
if k == n:
return Decimal(1)
with localcontext(Context(prec=75, Emax=999_999, Emin=-999_999)):
a_d = +a_d_in
if k == 0:
exact = Decimal(1) - (a_d.ln() / Decimal(n)).exp()
return +exact
target = Decimal(1) - a_d
a_int = k + 1
b_int = n - k
log_beta_inv = _lgamma_pos_int_dec(n + 1) - _lgamma_pos_int_dec(a_int) - _lgamma_pos_int_dec(b_int)
p_hat = Decimal(k) / Decimal(n)
lo = Decimal(0)
hi = Decimal(1)
z = Decimal("1.6448536269514722") if a_d <= Decimal("0.5") else Decimal("0")
se = (p_hat * (Decimal(1) - p_hat) / Decimal(n)).sqrt()
p = p_hat + z * se + Decimal("0.5") / Decimal(n)
if not (lo < p < hi):
p = (lo + hi) / Decimal(2)
tol = Decimal("1e-28")
for _ in range(200):
ib, pdf = _reg_inc_beta_and_pdf_dec(a_int, b_int, p, log_beta_inv)
err = ib - target
if err < 0:
lo = p
else:
hi = p
if hi - lo <= tol * max(hi, Decimal("1e-35")):
break
step_ok = False
if pdf > 0:
step = err / pdf
p_new = p - step
if lo < p_new < hi:
if abs(step) <= tol * max(p_new, Decimal("1e-35")):
eps_b = max(tol * p_new, Decimal("1e-45"))
p_hi = min(hi, p_new + eps_b)
p_lo = max(lo, p_new - eps_b)
ib_hi, _ = _reg_inc_beta_and_pdf_dec(a_int, b_int, p_hi, log_beta_inv)
if ib_hi >= target:
hi = p_hi
ib_lo, _ = _reg_inc_beta_and_pdf_dec(a_int, b_int, p_lo, log_beta_inv)
if ib_lo < target:
lo = p_lo
break
p = p_new
step_ok = True
if not step_ok:
p = (lo + hi) / Decimal(2)
require_cond(hi - lo <= Decimal("1e-24") * max(hi, Decimal("1e-35")), f"clopper_pearson_u95 bracket did not converge for k={k}, n={n}")
return +hi
def clopper_pearson_u95(k: int, n: int, alpha: float = 0.05) -> float:
"""Exact pure-stdlib monotone one-sided (1 - alpha) Clopper-Pearson binomial upper confidence bound.
Computes the certified 75-digit Decimal bound and rounds UPWARD to IEEE-754 float64
(via math.nextafter if Decimal.from_float(f) < exact_d) so U95 never understates.
"""
exact_d = clopper_pearson_u95_decimal(k, n, alpha=alpha)
if exact_d >= Decimal(1):
return 1.0
f = float(exact_d)
if Decimal.from_float(f) < exact_d:
f = math.nextafter(f, math.inf)
return min(1.0, f)
# =============================================================================
# 0B. Fail-Closed Canonical Arm Manifest & Master Contract Verification (S.2)
# =============================================================================
def load_and_verify_canonical_contracts(
manifest_path: Optional[Path] = None,
master_contract_path: Optional[Path] = None,
) -> Dict[str, Any]:
"""Fail-closed load & SHA-256 verification of Wave-6 Round-5 canonical manifest & master contract."""
c_path, m_path = resolve_paired_contract_paths(
master_contract_path=master_contract_path,
manifest_path=manifest_path,
)
require_cond(m_path.is_file(), f"Missing mandatory canonical arm manifest: {m_path}")
require_cond(c_path.is_file(), f"Missing mandatory Wave-6 master contract: {c_path}")
manifest_raw = m_path.read_bytes()
manifest_sha = sha256_bytes(manifest_raw)
require_cond(
manifest_sha == EXPECTED_CANONICAL_MANIFEST_SHA256,
f"Canonical arm manifest SHA-256 mismatch: observed={manifest_sha}, expected={EXPECTED_CANONICAL_MANIFEST_SHA256}",
)
manifest = load_strict_json_text(manifest_raw.decode("utf-8"), m_path.name)
require_cond(isinstance(manifest, dict) and isinstance(manifest.get("arms"), dict), "Malformed canonical arm manifest")
manifest_canon_sha = _canonical_json_sha256(manifest)
require_cond(
manifest_canon_sha == EXPECTED_CANONICAL_MANIFEST_CANONICAL_JSON_SHA256,
f"Canonical arm manifest canonical JSON digest mismatch: observed={manifest_canon_sha}",
)
schema_v1 = manifest.get("upstream_lot_evidence_record_schema_v1")
require_cond(
isinstance(schema_v1, dict) and schema_v1.get("schema_revision") == UPSTREAM_RECEIPT_SCHEMA_REVISION,
f"Canonical arm manifest missing {UPSTREAM_RECEIPT_SCHEMA_REVISION} upstream_lot_evidence_record_schema_v1",
)
cgs = schema_v1.get("canonical_gate_sources", {})
require_cond(
isinstance(cgs, dict)
and cgs.get("live_gate32_shield_debris_recall") == "GATE-32"
and cgs.get("live_gate33_htmpk_azt_pk") == "GATE-33"
and cgs.get("gate34") == UPSTREAM_W6C1_GATE_SOURCE
and cgs.get("gate35") == GATE_ID,
f"Canonical arm manifest gate source collision/mismatch: {cgs}",
)
g5_pol = schema_v1.get("gate5_oq012_live_blueprint_policy", {})
require_cond(
isinstance(g5_pol, dict)
and g5_pol.get("required_observed_survivors_k") == 0
and g5_pol.get("min_effective_clonogenic_trials_n_eff") == MIN_GATE5_EFFECTIVE_TRIALS
and g5_pol.get("max_u95_exact") == "1e-8",
f"Canonical arm manifest missing live Blueprint Section 7 Gate 5 OQ-012 policy: {g5_pol}",
)
contract_bytes = c_path.read_bytes()
contract_file_sha = sha256_bytes(contract_bytes)
require_cond(
contract_file_sha == EXPECTED_MASTER_CONTRACT_FILE_SHA256,
f"Wave-6 master contract file SHA-256 mismatch: observed={contract_file_sha}, expected={EXPECTED_MASTER_CONTRACT_FILE_SHA256}",
)
contract = load_strict_json_text(contract_bytes.decode("utf-8"), c_path.name)
require_cond(isinstance(contract, dict), "Malformed Wave-6 master contract")
embedded_sha = contract.get("contract_sha256")
require_cond(_is_non_all_zero_sha256_hex(embedded_sha), "Master contract missing valid contract_sha256")
contract_no_sha = {k: v for k, v in contract.items() if k != "contract_sha256"}
recomputed_contract_sha = _canonical_json_sha256(contract_no_sha)
require_cond(
recomputed_contract_sha == embedded_sha == EXPECTED_MASTER_CONTRACT_PAYLOAD_SHA256,
f"Wave-6 master contract SHA-256 mismatch: recomputed={recomputed_contract_sha}, "
f"embedded={embedded_sha}, expected={EXPECTED_MASTER_CONTRACT_PAYLOAD_SHA256}",
)
require_cond(
contract.get("canonical_arm_manifest_sha256") == manifest_sha,
"Master contract canonical_arm_manifest_sha256 disagrees with manifest bytes",
)
# Verify strict governance invariants from external Round-4 contract
inv = contract.get("strict_invariants", {})
require_cond(_strict_json_equal(inv.get("h1_allo_locked_pct"), Decimal("88.0")), "Contract invariant violation: h1_allo_locked_pct != 88.0")
require_cond(inv.get("design_a_zero_post_transplant_drugs_and_exvivo_rest") is True, "Contract invariant violation: Design A must prohibit drugs and ex-vivo rest")
require_cond(inv.get("design_a_zero_additional_biologics_beyond_v080_catalase_hydrogel") is True, "Contract invariant violation: Design A must prohibit additional biologics beyond v0.8.0 catalase hydrogel")
require_cond(inv.get("design_a_contains_preexisting_p04040_catalase_hydrogel") is True, "Contract invariant violation: Design A pre-existing P04040 catalase hydrogel must be declared")
require_cond(inv.get("design_a_strictly_zero_protein_biologics") is False, "Contract invariant violation: Design A strictly_zero_protein_biologics must be False due to P04040 catalase")
require_cond(inv.get("design_a_preexisting_catalase_hydrogel_exception_disclosed") is True, "Contract invariant violation: Design A catalase exception must be disclosed")
require_cond(_strict_json_equal(inv.get("design_a_invariant_tuple"), [Decimal("0.88"), Decimal("0.78"), Decimal("0.57"), Decimal("0.69")]), "Contract invariant violation: Design A tuple drifted")
require_cond(inv.get("gy_027_1_enforced_unhardened_abx_not_on_r4") is True, "Contract invariant violation: GY-027(1) not enforced")
require_cond(inv.get("gy_014_enforced_no_invivo_72h_diazoxide_credit") is True, "Contract invariant violation: GY-014 not enforced")
require_cond(_strict_json_equal(inv.get("exvivo_rest_primary_h4_credit_pp"), Decimal("0.0")), "Contract invariant violation: primary exvivo_rest credit must be 0.0")
require_cond(inv.get("gy_030_5_lineage_whole_graft_required_all_arms") is True, "Contract invariant violation: GY-030 5-lineage required")
require_cond(inv.get("c1_prerequisite_enforced_for_r4_and_z_in_24state_ev") is True, "Contract invariant violation: C1 prerequisite must be enforced in 24-state EV")
require_cond(inv.get("synthetic_fixtures_cannot_authorize_clinical_promotion") is True, "Contract invariant violation: synthetic fixtures must never authorize clinical promotion")
# Verify canonical arm eligibility & prospective wet-lab flag invariants from Round-4 manifest
arms = manifest["arms"]
for k in ("A", "B", "X"):
require_cond(arms[k]["r4_eligible"] is False, f"Manifest invariant violation: unhardened {k} must be r4_eligible=False")
require_cond(arms["A"]["product_id"] == "ISLET1_DESIGN_A_V080_REF", "Reference Design A product_id mismatch")
require_cond(arms["A"]["exvivo_rest_eligible"] is False and arms["A"]["cuff_v2_eligible"] is False, "Design A must forbid ex-vivo rest and Cuff v2.0")
require_cond(
arms["Y"]["r4_eligible"] is True
and arms["Y"]["r4_sars_backup_eligible"] is True
and arms["Y"]["cell_origin"] == "allogeneic_hiPSC"
and arms["Y"]["dual_switch_required_for_release"] is True
and arms["Y"]["dual_switch_wetlab_qualified"] is False,
"Design Y-v3 R4/Dual-FailSafe manifest mismatch",
)
require_cond(
arms["Z"]["r4_eligible"] is True
and arms["Z"]["r4_sars_backup_eligible"] is True
and arms["Z"]["cell_origin"] == "allogeneic_EnSC"
and arms["Z"]["dual_switch_required_for_release"] is True
and arms["Z"]["dual_switch_wetlab_qualified"] is False,
"Arm Z-EnSC R4/Dual-FailSafe/allogeneic_EnSC manifest mismatch",
)
require_cond(
arms["D"]["r4_eligible"] is True
and arms["D"]["r4_sars_backup_eligible"] is False
and arms["D"]["cell_origin"] == "autologous_hiPSC"
and arms["D"]["dual_switch_required_for_release"] is False
and arms["D"]["dual_switch_wetlab_qualified"] is False,
"D1b-Lean-K2 must be single-layer ACTB::iCasp8, R4-Omentum only, barred from R4-SARS backup",
)
return {
"manifest": manifest,
"manifest_sha256": manifest_sha,
"manifest_canonical_json_sha256": manifest_canon_sha,
"manifest_schema_version": manifest.get("schema_version"),
"contract": contract,
"contract_sha256": recomputed_contract_sha,
"contract_file_sha256": contract_file_sha,
"contract_schema_version": contract.get("schema_version"),
}
# =============================================================================
# 1. Read-Only OpenIslet NW-08 Constant Verification
# =============================================================================
def verify_nw08_constants(repo_root: Path | None) -> Dict[str, Any]:
"""Return pinned NW-08 constants; when repo_root is provided, verify byte-level match read-only."""
c = dict(PINNED_NW08_CONSTANTS)