"reason": "FAIL_D1_GLOBAL_GATE0V_INVALID_OR_OUT_OF_RANGE", } if d28_k < 0 or d28_n < 1 or d28_k > d28_n: return { "cleared": False, "failed": True, "hard_stop": False, "lot_binding_invalid": False, "reason": "FAIL_D1_GLOBAL_GATE0V_INVALID_OR_OUT_OF_RANGE", } if verdict != "PASS": return { "cleared": False, "failed": False, "hard_stop": False, "lot_binding_invalid": False, "reason": "HOLD_D1_L1B_GATE0V_VERDICT_NOT_PASS", } _g0v_cal_kw = _resolve_assay_calibration(record, local_prefix=None, panel_map=panel_observations) cp_v = evaluate_sound_decimal_clopper_pearson_zero_event( gate_id="GATE0V_DAY28_VP1_IE1", k=d28_k, n_raw=d28_n, max_u95_fraction=day28_u95_max, **_g0v_cal_kw, ) if cp_v["status"] == "FAIL_HARD_STOP": return { "cleared": False, "failed": True, "hard_stop": True, "lot_binding_invalid": False, "reason": "FAIL_HARD_STOP_D1_L1B_GATE0V_DAY28_VP1_IE1_POSITIVE_EVENT_SWITCH_TO_L1A_IL1RN", "day28_u95_str": cp_v.get("u95_exact_sound_decimal_str"), "cp_result": cp_v, } if d14_d < day14_min or d14_l95_d < day14_l95_min: return { "cleared": False, "failed": True, "hard_stop": False, "lot_binding_invalid": False, "reason": "FAIL_D1_L1B_GATE0V_CD46WT_VIRAL_CLEARANCE_SWITCH_TO_L1A_IL1RN", "day28_u95_str": cp_v.get("u95_exact_sound_decimal_str"), "cp_result": cp_v, } if t72_u95_d > early_72h_max: return { "cleared": False, "failed": True, "hard_stop": False, "lot_binding_invalid": False, "reason": "FAIL_D1_L1B_GATE0V_EARLY_72H_TITER_VETO_SWITCH_TO_L1A_IL1RN", "day28_u95_str": cp_v.get("u95_exact_sound_decimal_str"), "cp_result": cp_v, } if cp_v["status"] != "PASS" or d28_n < day28_n_min: g0v_hold_reason = ( "HOLD_D1_L1B_GATE0V_DAY28_INSUFFICIENT_DENOMINATOR" if cp_v["status"] in ("PASS", "HOLD_INCONCLUSIVE_INSUFFICIENT_INDEPENDENT_DENOMINATOR") else f"HOLD_D1_L1B_GATE0V_DAY28_{cp_v['status']}" ) return { "cleared": False, "failed": False, "hard_stop": False, "lot_binding_invalid": False, "reason": g0v_hold_reason, "day28_u95_str": cp_v.get("u95_exact_sound_decimal_str"), "cp_result": cp_v, } return { "cleared": True, "failed": False, "hard_stop": False, "lot_binding_invalid": False, "reason": "STANDALONE_SUBCHECK_PASSED_LIVE_LIMS_LEDGER_UNVERIFIED", "mcb_lot_id": mcb_lot_id, "day28_u95_str": cp_v.get("u95_exact_sound_decimal_str"), "cp_result": cp_v, } def _extract_dec_from_cell_threshold(threshold_str: str, pattern: str, label: str) -> Decimal: m = re.search(pattern, threshold_str) if not m: raise ValueError(f"Controlling 45-cell contract missing required threshold clause {label!r} in {threshold_str!r}") dv = _safe_exact_decimal(m.group(1)) if dv is None: raise ValueError(f"Controlling 45-cell contract threshold {label!r} is not a valid Decimal: {m.group(1)!r}") return dv # Updated from da7f53e8... (114/148) -> 2377b9ca... (121/148) after community #36-#40 + Wave-5 Ring-1 expansion (604->642) refreshed Layer-2 atlas; # Playbook §4.1.20 canonical body SHA (e3fb5ec7...) & frozen IIP-0035 JSON (9361b7ba...) remain 0-byte unchanged. EXPECTED_PLAYBOOK_LAYER_SCOPE_BODY_SHA256 = "2377b9ca900090493d537884ecc0906eb3e17562eb8bb686cee7480b00846117" def _strict_typed_equal(a: Any, b: Any) -> bool: """Strict type-aware JSON equality where bool != int AND int != float/Decimal (while float/Decimal compare exact).""" if isinstance(a, bool) or isinstance(b, bool): return type(a) is type(b) and a == b if isinstance(a, int) or isinstance(b, int): return type(a) is int and type(b) is int and a == b if isinstance(a, dict) and isinstance(b, dict): return a.keys() == b.keys() and all(_strict_typed_equal(a[k], b[k]) for k in a) if isinstance(a, list) and isinstance(b, list): return len(a) == len(b) and all(_strict_typed_equal(x, y) for x, y in zip(a, b)) if isinstance(a, (float, Decimal)) and isinstance(b, (float, Decimal)): da = _safe_exact_decimal(a) db = _safe_exact_decimal(b) return da is not None and db is not None and da == db return type(a) is type(b) and a == b def _verify_playbook_sec4120( repo_root: Path, *, require_canonical_sha: bool = True, ) -> Dict[str, Any]: """Parse docs/STAGE-0-EXECUTION-PLAYBOOK.md §4.1.20 via CommonMark heading scanner & verify canonical SHA-256.""" pb_path = repo_root / PLAYBOOK_REL_PATH if not pb_path.is_file(): raise ValueError(f"Missing Stage-0 execution playbook: {pb_path}") pb_norm = pb_path.read_text(encoding="utf-8").replace("\r\n", "\n").replace("\r", "\n") all_headings = _parse_commonmark_headings(pb_norm) matched_4120 = [ h for h in all_headings if re.search(r"(? start_off and h["container_depth"] == 0 and h["level"] <= 4: next_heading_off = h["start_offset"] break end_marker = "" end_idx = pb_norm.find(end_marker, start_off, next_heading_off) if end_idx == -1: raise ValueError(f"Missing required post-4.1.20 end marker {end_marker!r} before next top-level heading") # Require EXACTLY ONE literal standalone OPENISLET_CURRENT_LAYER_SCOPE footer pair in canonical mode # (rejecting complete deletion, duplication, incomplete markers, or any residual prose/comments before next heading). trailing_under_4120 = pb_norm[end_idx + len(end_marker):next_heading_off] _ls_matches = list( re.finditer( r"(?m)^\n(.*?)\n[ \t]*$", trailing_under_4120, re.S, ) ) footer_present = len(_ls_matches) == 1 footer_verified = False if len(_ls_matches) > 1: raise ValueError(f"Duplicate OPENISLET_CURRENT_LAYER_SCOPE footers ({len(_ls_matches)}) under Playbook §4.1.20") if len(_ls_matches) == 1: _ls_m = _ls_matches[0] _ls_body = _ls_m.group(1) if re.search(r"(?m)^[ ]{0,3}#{1,6}\s", _ls_body): raise ValueError("Unexpected Markdown heading smuggled inside OPENISLET_CURRENT_LAYER_SCOPE footer under Playbook §4.1.20") if re.search(r"(?i)\b(?:D1-0[1-9]|D1b|DEC-114|IIP-0035|KIR3DL1|VTCN1|HLA-C\*03:04|AP1903|Gate\s*0V|C5b-9|overrid\w*|waiv\w*|exempt\w*|bypass\w*)\b", _ls_body): raise ValueError("Unexpected D1b-Auto-C / DEC-114 or override prose inside OPENISLET_CURRENT_LAYER_SCOPE footer under Playbook §4.1.20") _ls_sha = hashlib.sha256(_ls_body.strip().encode("utf-8")).hexdigest() footer_verified = (_ls_sha == EXPECTED_PLAYBOOK_LAYER_SCOPE_BODY_SHA256) if require_canonical_sha and not footer_verified: raise ValueError( f"OPENISLET_CURRENT_LAYER_SCOPE footer under Playbook §4.1.20 SHA-256 mismatch: found {_ls_sha}, expected {EXPECTED_PLAYBOOK_LAYER_SCOPE_BODY_SHA256}" ) trailing_residual = trailing_under_4120[:_ls_m.start()] + trailing_under_4120[_ls_m.end():] else: if require_canonical_sha: raise ValueError( "Missing required canonical OPENISLET_CURRENT_LAYER_SCOPE generated footer under Playbook §4.1.20" ) trailing_residual = trailing_under_4120 if trailing_residual.strip(): raise ValueError( "Unexpected content (visible text or unpinned comment) appended under Playbook §4.1.20 after end marker before next rendered heading: " f"{trailing_residual.strip()[:120]!r}" ) pb_sec_full = pb_norm[start_off:end_idx].strip() pb_sha = hashlib.sha256(pb_sec_full.encode("utf-8")).hexdigest() if require_canonical_sha and pb_sha != EXPECTED_DEC114_PLAYBOOK_SEC4120_SHA256: raise ValueError( f"DEC-114 Playbook section 4.1.20 SHA-256 mismatch: found {pb_sha}, expected {EXPECTED_DEC114_PLAYBOOK_SEC4120_SHA256}" ) return { "pb_sec_full": pb_sec_full, "pb_sha": pb_sha, "footer_present": footer_present, "footer_verified": footer_verified, "canonical_sha_verified": bool(pb_sha == EXPECTED_DEC114_PLAYBOOK_SEC4120_SHA256 and footer_verified), "all_headings": all_headings, "matched_4120": matched_4120, "h4120": h4120, } def _canonicalize_json_for_digest(obj: Any) -> Any: """Convert exact finite Decimal scalars matching canonical float JSON representation so Decimal-parsed product_defs hash identically.""" if isinstance(obj, dict): return {k: _canonicalize_json_for_digest(v) for k, v in obj.items()} if isinstance(obj, list): return [_canonicalize_json_for_digest(v) for v in obj] if isinstance(obj, Decimal): if not obj.is_finite(): raise ValueError(f"Non-finite Decimal in product_def: {obj!r}") fv = float(obj) if not math.isfinite(fv) or Decimal(str(fv)) != obj: raise ValueError(f"Non-canonical Decimal value in product_def: {obj!r}") return fv return obj def _load_controlling_contract_for_product( pvid: str, *, decision_tree_block: Dict[str, Any] | None = None, repo_root: Path = ROOT, require_canonical_sha: bool = True, ) -> Dict[str, Any]: """Load, verify (45-cell DEC-114 table, Playbook §4.1.20, AND staged product registry/FASTAs), and parse clauses.""" pb_info = _verify_playbook_sec4120(repo_root, require_canonical_sha=require_canonical_sha) staged_registry_verified = False if require_canonical_sha: # Enforce identical staged-FASTA & product-registry cryptographic verification across BOTH direct Python and CLI! pc.load_product_contracts(repo_root, require_staged_fastas=True) staged_registry_verified = True disk_blk: Dict[str, Any] | None = None disk_sha: str | None = None dt_path = repo_root / DECISION_TREE_REL_PATH if require_canonical_sha or decision_tree_block is None: if not dt_path.is_file(): raise ValueError(f"Missing controlling Stage-0 decision tree: {dt_path}") dt_doc = _load_json_strict(dt_path)