_CANONICAL_LAYER2_QUARANTINE_SENTENCE = ( "The local 3,118-row AVI table is quarantined in the private cache: end-to-end batch generation provenance " "for the full 3,118-row table is incomplete (as a whole it is not a certified model scan), a limited " f"28 Oct 2026 live re-run against {_AG_LOW} v0.10.0 verified 59/59 sampled rows (9 candidate edits plus " f"50 random rows), {_AG_CAP} non-commercial output terms conflict with CC-BY-4.0 public redistribution, " f"and zero {_AG_CAP} outputs are shipped publicly or used as active ranking weights or insertion-safety certifications." ) # Canonical Locked Policy Option 1 eligibility rule (must match side contract verbatim!) CANONICAL_TRACKB_ELIGIBILITY_RULE = ( "Under Locked Policy Option 1, Design A excludes ATG/lymphodepleting induction unconditionally " "(Track A targets zero chronic systemic recipient immunosuppression; rescue fail-safe prodrug AP1903 " "and any future investigational Islet-SHIELD protein exposure are explained individually to patients); " "optional Track-B reset (Day-1 active 0.5 mg/kg IV rabbit ATG + Day-2 IV placebo) " "is eligible ONLY if Gate 30-ATG-XREACT passes FIRST (ordered BEFORE Gate 30-SHIELD-SPR) " "AND Gate 30-SHIELD-SPR emits a complete zero-hold FAIL with machine-checked " "derived_summary.trackb_shield_trigger_state in " "{ELIGIBLE_CANDIDATE_SHIELD1_ONLY_COMP2_FAIL_PENDING_XREACT_AND_OWNER_REAUTH, " "ELIGIBLE_CANDIDATE_OVERALL_SHIELD_FAIL_PENDING_XREACT_AND_OWNER_REAUTH} " "(all non-FAIL, held, invalid, and partial-FAIL-with-HOLD states emit " "INELIGIBLE_NON_FAIL_OR_HELD_OR_INCOMPLETE and remain ineligible) " "AND explicit owner re-authorization (adjudicator chain: " "GATE30_SHIELD_SPR_SOFTWARE_PLUS_GATE30_ATG_XREACT_PASS_PLUS_OWNER_REAUTHORIZATION). " "Full-cocktail branch carries strictly 0.0000 pp Track-B credit." ) _RE_SHA256_HEX = re.compile(r"^[0-9a-f]{64}$") # Exact two-sided 95% Student-t critical values (alpha = 0.05) for df = 1..30 _STUDENT_T_95_TWO_SIDED: dict[int, float] = { 1: 12.706204736432095, 2: 4.302652729911275, 3: 3.182446305284263, 4: 2.7764451051977987, 5: 2.5705818366147395, 6: 2.4469118487916806, 7: 2.3646242510102993, 8: 2.3060041350333704, 9: 2.2621571627409915, 10: 2.2281388519649385, 11: 2.200985160082949, 12: 2.1788128296634177, 13: 2.1603686564610127, 14: 2.1447866879169273, 15: 2.131449545559323, 16: 2.1199052992210112, 17: 2.1098155778331806, 18: 2.10092204024096, 19: 2.093024054408263, 20: 2.0859634472658364, 21: 2.079613844727662, 22: 2.0738730679040147, 23: 2.0686576104190406, 24: 2.0638985616280205, 25: 2.059538552753294, 26: 2.055529438642871, 27: 2.0518305164802833, 28: 2.048407141795244, 29: 2.045229642132703, 30: 2.0422724563012373, } def _student_t_95_critical(df: int) -> float: if df < 1: raise ValueError(f"Degrees of freedom must be >= 1, got {df}") if df in _STUDENT_T_95_TWO_SIDED: return _STUDENT_T_95_TWO_SIDED[df] # Cornish-Fisher expansion accurate to < 1e-6 for df > 30 z = 1.959963984540054 z3 = z ** 3 z5 = z ** 5 return z + (z3 + z) / (4.0 * df) + (5.0 * z5 + 16.0 * z3 + 3.0 * z) / (96.0 * (df ** 2)) _EXACT_DECIMAL_PRESERVED_JSON_KEYS: frozenset[str] = frozenset({"design_effect_deff"}) def _reject_nonfinite_json_constant(token: str) -> Any: raise ValueError(f"Non-finite JSON constant rejected: {token!r}") def _parse_strict_finite_float(token: str) -> Decimal: try: dec_val = Decimal(token) except InvalidOperation as exc: raise ValueError(f"Invalid JSON float token rejected during decoding: {token!r}") from exc if not dec_val.is_finite() or dec_val.copy_abs() > Decimal("1e300"): raise ValueError(f"Non-finite or overflowing JSON decimal token rejected during decoding: {token!r}") val = float(token) if not math.isfinite(val) or abs(val) > 1e300: raise ValueError(f"Non-finite or overflowing JSON float rejected during decoding: {token!r}") return dec_val def _parse_strict_finite_int(token: str) -> int: val = int(token) if abs(val) > 10 ** 300: raise ValueError(f"Overflowing JSON integer token rejected during decoding: {token[:32]!r}...") return val def _coerce_non_dict_decimals_to_float(val: Any) -> Any: """Convert raw parsed Decimal tokens outside preserved exact-equality keys to binary64 float, without mutating child dicts whose keys were already finalized by object_pairs_hook. """ if isinstance(val, Decimal): return float(val) if isinstance(val, list): return [_coerce_non_dict_decimals_to_float(item) for item in val] return val def _reject_duplicate_json_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]: out: dict[str, Any] = {} for k, v in pairs: if k in out: raise ValueError(f"Duplicate JSON object key rejected fail-closed: {k!r}") if k in _EXACT_DECIMAL_PRESERVED_JSON_KEYS: out[k] = v else: out[k] = _coerce_non_dict_decimals_to_float(v) return out def load_strict_json_text(raw_text: str, label: str) -> Any: """Strict fail-closed JSON parser rejecting duplicate keys, NaN/Inf constants, and overflowing numbers, while preserving exact Decimal precision on design_effect_deff for zero-tolerance GY-018 equality checks. """ data = json.loads( raw_text, object_pairs_hook=_reject_duplicate_json_keys, parse_constant=_reject_nonfinite_json_constant, parse_float=_parse_strict_finite_float, parse_int=_parse_strict_finite_int, ) data = _coerce_non_dict_decimals_to_float(data) assert_strictly_finite_json(data, label) return data def assert_strictly_finite_json(obj: Any, label: str, path: str = "$") -> None: """Fail-closed recursive guard rejecting NaN/Inf or abs(x) > 10^300 (int, float, or Decimal) anywhere in loaded JSON fixtures.""" if isinstance(obj, bool) or obj is None or isinstance(obj, str): return if isinstance(obj, Decimal): if not obj.is_finite() or obj.copy_abs() > Decimal("1e300"): raise ValueError(f"Non-finite or overflowing Decimal in {label} at {path}: {obj!r}") return if isinstance(obj, (int, float)): if isinstance(obj, int) and abs(obj) > 10 ** 300: raise ValueError(f"Overflowing integer in {label} at {path}") if isinstance(obj, float) and (not math.isfinite(obj) or abs(obj) > 1e300): raise ValueError(f"Non-finite or overflowing float in {label} at {path}: {obj!r}") if not math.isfinite(obj): raise ValueError(f"Non-finite numeric value in {label} at {path}: {obj!r}") return if isinstance(obj, dict): for k, v in obj.items(): assert_strictly_finite_json(v, label, f"{path}.{k}") return if isinstance(obj, (list, tuple)): for idx, v in enumerate(obj): assert_strictly_finite_json(v, label, f"{path}[{idx}]") return def require_finite_number(val: Any, label: str) -> float: """Reject booleans, None, non-numbers, NaN, Inf, and abs(x) > 10^300 (int or float) before any arithmetic comparison.""" if isinstance(val, bool) or not isinstance(val, (int, float)): raise ValueError(f"Non-finite or non-numeric scalar for {label}: {val!r}") if isinstance(val, int) and abs(val) > 10 ** 300: raise ValueError(f"Overflowing integer scalar for {label}") fval = float(val) if not math.isfinite(fval) or abs(fval) > 1e300: raise ValueError(f"Non-finite or overflowing numeric scalar for {label}: {val!r}") return fval def load_verified_json_fixture( path: Path, label: str, *, expected_sha256: str | None = None, ) -> tuple[dict[str, Any], str, int]: """ Fail-closed fixture loader: 1. Requires file to exist and be non-empty. 2. Computes SHA-256 over the exact loaded bytes BEFORE parsing or parity comparison. 3. Validates pinned SHA-256 BEFORE parity pass. 4. Rejects duplicate JSON keys, non-finite JSON constants (NaN/Infinity/-Infinity), and overflowing float/int tokens DURING decoding, then recursively validates finiteness. """ if not path.is_file(): raise FileNotFoundError(f"Missing required fixture for {label}: {path.name}") raw_bytes = path.read_bytes() if not raw_bytes: raise ValueError(f"Empty fixture file for {label}: {path.name}") digest = hashlib.sha256(raw_bytes).hexdigest() if expected_sha256 is not None: exp_norm = expected_sha256.strip().lower() if not _RE_SHA256_HEX.match(exp_norm): raise ValueError(f"Invalid expected SHA-256 digest format for {label}: {expected_sha256!r}") if digest != exp_norm: raise RuntimeError( f"Pinned SHA-256 mismatch for {label} ({path.name}): got {digest}, expected {exp_norm}" ) data = load_strict_json_text(raw_bytes.decode("utf-8"), label) if not isinstance(data, dict) or not data: raise ValueError(f"Fixture {label} ({path.name}) must decode to a non-empty JSON object") return data, digest, len(raw_bytes) def mask_canonical_layer2_disclaimer_only(md_text: str) -> str: """Narrowly mask ONLY the single exact canonical Layer-2 quarantine disclaimer sentence inside .... Never strips the rest of the footer block so any injected leak inside the footer still fails closed. """ def _replace_footer(match: re.Match[str]) -> str: body = match.group(0) return body.replace(_CANONICAL_LAYER2_QUARANTINE_SENTENCE, "[CANONICAL_LAYER2_QUARANTINE_DISCLAIMER_VERIFIED]") return re.sub( r".*?", _replace_footer, md_text, flags=re.S, ) def _iter_decoded_json_strings(obj: Any) -> list[str]: """Recursively collect every string key and value from a parsed JSON structure.""" out: list[str] = [] stack: list[Any] = [obj] while stack: cur = stack.pop() if isinstance(cur, str): out.append(cur) elif isinstance(cur, dict): for k, v in cur.items(): if isinstance(k, str): out.append(k) stack.append(v) elif isinstance(cur, (list, tuple)): stack.extend(cur) return out def strip_verified_iip0044_tier2_exclusion_manifest(json_text: str, label: str) -> str: """Strictly validate EVERY field type, scalar value, and schema constraint of the metadata-only