raise ValueError(f"Paired comparator {lbl}={cnt!r} must be exact int matching panel ID count {expected_len}") cand_parsed, cand_errs = _validate_candidate_arm_evidence(candidate_arm_evidence) if cand_errs or cand_parsed is None: raise ValueError(f"Invalid paired comparator candidate_arm_evidence: {cand_errs}") inc_state, inc_details, inc_errs = _derive_paired_comparator_incumbent_adjudication(evidence_summary) if inc_errs or inc_state is None: raise ValueError(f"Invalid paired comparator incumbent evidence_summary: {inc_errs}") panel_digest = compute_paired_assay_panel_digest(paired_assay_run_id, sera_ids, nk_ids, diff_ids) rec: dict[str, Any] = { "gate_id": "PAIRED_L2V3_INCUMBENT_COMPARATOR", "verdict": INCUMBENT_STATE_TO_RECORD_VERDICT[inc_state], "incumbent_adjudication_state": inc_state, "derived_incumbent_broken": inc_state == "INCUMBENT_CONCLUSIVELY_BROKEN", "product_track": product_track, "chassis_id": chassis_id, "candidate_construct_id": candidate_construct_id, "product_variant_id": pvid, "candidate_lot_id": candidate_lot_id, "candidate_mcb_id": candidate_mcb_id, "incumbent_comparator_construct_id": incumbent_comparator_construct_id, "incumbent_comparator_lot_id": incumbent_comparator_lot_id, "incumbent_comparator_mcb_id": incumbent_comparator_mcb_id, "paired_assay_run_id": paired_assay_run_id, "t1d_sera_panel_ids": sera_ids, "nk_donor_panel_ids": nk_ids, "differentiation_batch_ids": diff_ids, "panel_digest": panel_digest, "independent_t1d_sera_n": sera_cnt, "independent_nk_donors_n": nk_cnt, "independent_differentiations_n": diff_cnt, "issuer_authority_id": issuer_authority_id, "evidence_summary": copy.deepcopy(evidence_summary), "candidate_arm_evidence": copy.deepcopy(candidate_arm_evidence), "incumbent_adjudication_details": inc_details, } rec["record_sha256"] = compute_upstream_record_sha256(rec) return rec def write_gate28b_trusted_qualification_store( store_path: pathlib.Path | str, *, upstream_records: list[dict[str, Any]] | None = None, paired_comparator_records: list[dict[str, Any]] | None = None, store_authority_id: str = "OPENISLET_QA_RELEASE_BOARD_V1", ) -> pathlib.Path: """Persist Gate 28-B upstream and paired comparator records into an independent trusted store (JSON registry or directory).""" sp = pathlib.Path(store_path) up_list = list(upstream_records or []) pc_list = list(paired_comparator_records or []) for rec in up_list + pc_list: if not isinstance(rec, dict) or not _is_valid_sha256_hex(rec.get("record_sha256")): raise ValueError("Every record written to trusted store must have a valid 64-hex record_sha256") if sp.suffix.lower() == ".json": if sp.is_file(): doc = load_strict_json_bytes(sp.read_bytes(), f"trusted_store:{sp.name}") else: doc = { "schema_version": TRUSTED_QUAL_STORE_SCHEMA_VERSION, "store_authority_id": store_authority_id, "upstream_qualifications": {}, "paired_comparator_records": {}, } for rec in up_list: doc.setdefault("upstream_qualifications", {})[rec["record_sha256"]] = copy.deepcopy(rec) for rec in pc_list: doc.setdefault("paired_comparator_records", {})[rec["record_sha256"]] = copy.deepcopy(rec) sp.parent.mkdir(parents=True, exist_ok=True) sp.write_text(json.dumps(doc, indent=2, sort_keys=True, ensure_ascii=False) + "\n", encoding="utf-8") return sp # Directory store layout (sp / "upstream_qualifications").mkdir(parents=True, exist_ok=True) (sp / "paired_comparator_records").mkdir(parents=True, exist_ok=True) meta_file = sp / "store_metadata.json" if not meta_file.is_file(): meta_file.write_text( json.dumps( {"schema_version": TRUSTED_QUAL_STORE_SCHEMA_VERSION, "store_authority_id": store_authority_id}, indent=2, sort_keys=True, ) + "\n", encoding="utf-8", ) for rec in up_list: (sp / "upstream_qualifications" / f"{rec['record_sha256']}.json").write_text( json.dumps(rec, indent=2, sort_keys=True, ensure_ascii=False) + "\n", encoding="utf-8" ) for rec in pc_list: (sp / "paired_comparator_records" / f"{rec['record_sha256']}.json").write_text( json.dumps(rec, indent=2, sort_keys=True, ensure_ascii=False) + "\n", encoding="utf-8" ) return sp def _lookup_gate28b_trusted_record( store_path: pathlib.Path | str | None, *, category: str, expected_sha256: Any, allowed_issuers: set[str], ) -> tuple[dict[str, Any] | None, str | None, str | None]: """ Resolve a Gate 28-B qualification or paired comparator record STRICTLY from an independent external trusted qualification store (JSON registry file or directory). Never reads caller inline payloads. Returns (record_or_None, error_msg_or_None, deterministic_source_label_or_None). """ if store_path is None: return None, "trusted_qualification_store not provided", None if not isinstance(store_path, (pathlib.Path, str)): return None, "trusted_qualification_store has invalid path type", None sp = pathlib.Path(store_path) if not sp.exists(): return None, f"trusted_qualification_store path missing: {sp.name}", f"missing:{sp.name}" if not _is_valid_sha256_hex(expected_sha256): return None, f"Invalid 64-hex reference digest for {category}: {expected_sha256!r}", f"store:{sp.name}" try: if sp.is_file(): doc = load_strict_json_bytes(sp.read_bytes(), f"trusted_store:{sp.name}") if not isinstance(doc, dict): return None, "Trusted store registry JSON must be an object", f"registry_file:{sp.name}" if doc.get("schema_version") != TRUSTED_QUAL_STORE_SCHEMA_VERSION: return None, f"Trusted store schema_version mismatch: {doc.get('schema_version')!r}", f"registry_file:{sp.name}" if _strict_literal_id(doc.get("store_authority_id")) not in allowed_issuers: return None, f"Trusted store authority {doc.get('store_authority_id')!r} not in allowlist", f"registry_file:{sp.name}" bucket = doc.get(category) if not isinstance(bucket, dict): return None, f"Trusted store missing bucket {category!r}", f"registry_file:{sp.name}" rec = bucket.get(expected_sha256) if not isinstance(rec, dict): return None, f"Record {expected_sha256[:16]}... not found in trusted store bucket {category!r}", f"registry_file:{sp.name}" return rec, None, f"registry_file:{sp.name}" if sp.is_dir(): meta_file = sp / "store_metadata.json" if meta_file.is_file(): meta = load_strict_json_bytes(meta_file.read_bytes(), "store_metadata.json") if ( not isinstance(meta, dict) or meta.get("schema_version") != TRUSTED_QUAL_STORE_SCHEMA_VERSION or _strict_literal_id(meta.get("store_authority_id")) not in allowed_issuers ): return None, "Trusted store directory store_metadata.json failed authority/schema verification", "store_dir" elif (sp / "registry.json").is_file(): return _lookup_gate28b_trusted_record( sp / "registry.json", category=category, expected_sha256=expected_sha256, allowed_issuers=allowed_issuers, ) else: return None, "Trusted store directory missing store_metadata.json", "store_dir" rec_file = sp / category / f"{expected_sha256}.json" if not rec_file.is_file(): return None, f"Record {expected_sha256[:16]}... not found in trusted store dir {category!r}", "store_dir" rec = load_strict_json_bytes(rec_file.read_bytes(), rec_file.name) if not isinstance(rec, dict): return None, f"Trusted store record {rec_file.name} is not a JSON object", "store_dir" return rec, None, "store_dir" except Exception as exc: return None, f"Failed reading trusted store ({type(exc).__name__}): {exc}", f"unreadable:{sp.name}" return None, "Unsupported trusted_qualification_store path type", f"unsupported:{sp.name}" def _validate_iip0041_side_contract_schema(sc: Any) -> None: """Strictly validate required Gate 28-B structure & allowlists on the decoded side contract.""" if not isinstance(sc, dict): raise ValueError("Side contract JSON root must be a dict") if sc.get("schema_version") != "iip0041_abx_cd64t_il1rn_side_contract_v0.8.0": raise ValueError(f"Unexpected side contract schema_version={sc.get('schema_version')!r}") if sc.get("contribution_id") != "IIP-0041" or sc.get("decision_id") != "DEC-120": raise ValueError("Invalid IIP-0041 side contract metadata") zlt = sc.get("zero_lims_touch_implementation_compliance") if not isinstance(zlt, dict) or zlt.get("modeb_construct_fasta_sha256") != PINNED_FASTA_SHA: raise ValueError("Side contract Mode-B FASTA SHA-256 pin mismatch") gates = sc.get("executable_stage0_gates") if not isinstance(gates, dict) or not isinstance(gates.get("Gate_28_B"), dict): raise ValueError("Side contract missing executable_stage0_gates.Gate_28_B") g28b = gates["Gate_28_B"] for req_list_key in ( "allowed_issuer_authorities", "eligible_product_tracks", "blocked_product_tracks", "eligible_chassis", "promotion_eligible_construct_ids", "non_promotable_control_construct_ids", "blocked_cd46_hold_construct_ids", "blocked_tertiary_cfh_cd55_hold_construct_ids", "allowed_zygosities", ): val = g28b.get(req_list_key) if not isinstance(val, list) or len(val) == 0 or not all(_strict_literal_id(x) is not None for x in val): raise ValueError(f"Side contract Gate_28_B.{req_list_key} must be a non-empty list of strict literal IDs") if not isinstance(g28b.get("eligible_incumbent_comparators_by_chassis"), dict): raise ValueError("Side contract missing eligible_incumbent_comparators_by_chassis") if not isinstance(g28b.get("required_authenticated_upstream_records"), dict): raise ValueError("Side contract missing required_authenticated_upstream_records") if not isinstance(g28b.get("required_trusted_paired_comparator_record"), dict): raise ValueError("Side contract missing required_trusted_paired_comparator_record") def _load_iip0041_side_contract( side_contract_path: pathlib.Path | None = None, *, require_pinned_sha: bool = True, ) -> tuple[dict[str, Any], str, bool]: """ Strictly decode and validate the IIP-0041 side contract (rejecting duplicate keys and non-finite numbers) and check its SHA-256 against runtime PINNED_SIDE_CONTRACT_SHA256. Returns (side_contract_dict, actual_sha256, policy_pin_verified). """ sc_path = side_contract_path if side_contract_path is not None else (OPENISLET_ROOT / PINNED_SIDE_CONTRACT_REL) if not sc_path.is_file(): raise FileNotFoundError(f"Missing immutable IIP-0041 side contract: {sc_path}") raw_bytes = sc_path.read_bytes() actual_sha = sha256_bytes(raw_bytes) sc = load_strict_json_bytes(raw_bytes, f"side_contract:{sc_path.name}") _validate_iip0041_side_contract_schema(sc) pin_ok = actual_sha == PINNED_SIDE_CONTRACT_SHA256 if require_pinned_sha and not pin_ok: raise ValueError( f"Pinned IIP-0041 side-contract SHA-256 mismatch: actual={actual_sha} != pinned={PINNED_SIDE_CONTRACT_SHA256}" ) return sc, actual_sha, pin_ok def evaluate_ciita_locus2_arbitration( payload: dict[str, Any], *, side_contract_path: pathlib.Path | None = None, trusted_qualification_store: pathlib.Path | str | None = None, ) -> dict[str, Any]: """ Executable winner-takes-allele CIITA Exon 5 Locus-2 arbitration & full GY-025 / Gate 28-B evaluator (fail-closed). Binds eligibility, allowlists, and quantitative cutoffs to the runtime-SHA-256-pinned data/protocols/iip0041_abx_cd64t_il1rn_side_contract_v0.8.0.json contract: - Runtime Policy Pin (B4): Strictly decodes the side contract (rejecting duplicate keys and non-finite values) and verifies its SHA-256 matches PINNED_SIDE_CONTRACT_SHA256. Any alternate or modified policy file is explicitly non-authorizing (status="NON_AUTHORIZING_UNPINNED_POLICY_DIAGNOSTIC", policy_pin_verified=False, full_promotion_authorized=False, lead_promotion_authorized=False). - Strictly Literal IDs & Context-Independent Rational Bounds: Zero silent whitespace stripping; leading, trailing, or embedded whitespace fails closed. All quantitative threshold checks use exact fractions.Fraction after strict finite validation (immune to ambient decimal.getcontext() precision and traps). Exact Fraction arithmetic operates