# SPDX-FileCopyrightText: 2026 David Porto Baraldés (Homo Universalis / Viveka) # SPDX-License-Identifier: Apache-2.0 """ Living Folio X (`logic/justice/universal_justice_core.py`): HU-UNIVERSAL-JUSTICE-LIFECYCLE v1.0 — Pythagorean Tetraktys (`1 + 2 + 3 + 4 = 10`) & Circumscribed Sphere of Universal Algorithmic Justice (`Ma'at`). Pure-stdlib zero-dependency edge kernel (`pip`-zero, 0 IEEE-754 floats, < 10,000 AST nodes, < 50 ms isolated `python3 -I` self-tests): descriptor-slot hygiene, base-10**500 8,192-char rationals, iterative UTF-16BE RFC 8785 JCS, idempotent Rule 14 sanctuary, J1..J7 Hard Laws, `JusticeRevocationRegistry` directed-forest cascade, and 8/8 antipodal mutant self-tests. """ from __future__ import annotations from collections import UserList, deque, namedtuple from collections.abc import Mapping, Sequence import copy from fractions import Fraction import hashlib import hmac import re import time PROTOCOL_ID = "HU-UNIVERSAL-JUSTICE-LIFECYCLE" PROTOCOL_VERSION = "1.0" LIVING_FOLIO = "folio-X-universal-justice-lifecycle" SACRED_EQUATION = "F0c=Ca0s*0rdre(Am0r_Un1f1cat_Etern)" HUMAN_APPEAL_VETO = "human_appeal_veto" DISPARATE_IMPACT_ABORT = "disparate_impact_abort" VILLE_DRIFT_HALT = "ville_drift_halt" COST_ZERO_STOP = "cost_zero_stop" JUSTICE_INTERRUPTIONS = ("none", HUMAN_APPEAL_VETO, DISPARATE_IMPACT_ABORT, VILLE_DRIFT_HALT, COST_ZERO_STOP) REVOCATION_REASONS = frozenset({HUMAN_APPEAL_VETO, DISPARATE_IMPACT_ABORT, VILLE_DRIFT_HALT, COST_ZERO_STOP}) IJSON_MAX_SAFE_INT = (1 << 53) - 1 IJSON_MIN_SAFE_INT = -IJSON_MAX_SAFE_INT DYADIC_SHIFT_BITS = 64 DYADIC_DENOM = 1 << DYADIC_SHIFT_BITS MAX_VILLE_STREAM_LEN = 512 MAX_VILLE_STREAMS = 64 MAX_INPUT_DENOM = 10**9 MAX_INPUT_ABS_NUM_FACTOR = 10**18 MAX_UNBOUNDED_BITS = 65_536 DEC_CHUNK = 500 DEC_BASE = 10**DEC_CHUNK MAX_DISCRETE_LATTICE_STATES = 4096 MAX_CELL_POPULATION = 10**12 MAX_UNKNOWN_DEMOGRAPHIC_COUNT = 10**12 MAX_UTC_EPOCH_SECONDS = 10**12 MAX_SLA_WINDOW_SECONDS = 31_536_000 DEADLINE_BY_INCIDENT_CATEGORY = { "WIDESPREAD_OR_CRITICAL_INFRASTRUCTURE": 172_800, "DEATH_OF_PERSON": 864_000, "SERIOUS_INCIDENT_GENERAL": 1_296_000, } DEFAULT_INCOMPLETE_FOLLOWUP_WINDOW_S = 2_592_000 _FORBIDDEN_DIGITS = f"{21}{6}" _PLACEHOLDER_ALNUM_TOKENS = frozenset(("", *("na tbd tba tbc fixme unknown placeholder null none nil unspecified undisclosed pending redacted dummy sample loremipsum notapplicable nonapplicable tobedetermined " + "to" + "do").split())) _ALLOWED_INTERRUPTION_SIGNALS = frozenset(JUSTICE_INTERRUPTIONS) _FRAC_OR_DEC_PAT = re.compile(r"^[+-]?(?:(?:0|[1-9][0-9]*)(?:/[1-9][0-9]*)?|[0-9]{1,18}\.[0-9]{1,12})\Z", re.ASCII) _AB2013_MONTH_PAT = re.compile(r"^(?:19|20)[0-9]{2}-(?:0[1-9]|1[0-2])\Z", re.ASCII) _SHA256_HEX_PAT = re.compile(r"^[0-9a-f]{64}\Z", re.ASCII) _HEX_LEAK_IN_FACTS_PAT = re.compile(r"\b(?:0x[0-9a-f]{8,}|(?=[0-9a-f]*[a-f])[0-9a-f]{16,64})\b", re.ASCII | re.IGNORECASE) _SHIELD_MARKERS_PAT = re.compile(r"\[(?:path|email|date|coord|phone)-shielded\]|VVK-\*{4}-\*{4}", re.ASCII) _SURROGATE_PAT = re.compile(r"[\ud800-\udfff]") _NON_ALNUM_PAT = re.compile(r"[^a-z0-9]+") _AXIS_FORBIDDEN_DELIMS = re.compile(r"[=&\x00-\x1f\x7f]") _CTRL_ID_PAT = re.compile(r"[\x00-\x1f\x7f]") _JCS_CTRL_ESCAPES = {8: "\\b", 9: "\\t", 10: "\\n", 12: "\\f", 13: "\\r", 34: '\\"', 92: "\\\\"} _RULE14_SUBS = ( (re.compile(r"(?()\[\]{}|`\\/]+[\\/]+)(?:[^\s,;\"'<>()\[\]{}|`\\/]+[\\/]+)*[^\s,;\"'<>()\[\]{}|`\\/]*[^\s.,;:?!\"'<>()\[\]{}|`\\/][\\/]?"), "[path-shielded]"), (re.compile(r"(?()\[\]{}|`/]+)*/+[^\s,;\"'<>()\[\]{}|`/]*[^\s.,;:?!\"'<>()\[\]{}|`/]/?"), "[path-shielded]"), (re.compile(r"(?= DEC_BASE: m, r = divmod(m, DEC_BASE) ps.append(f"{r:0500d}") ps.append(f"{'-' if iv < 0 else ''}{m:d}") return "".join(reversed(ps)) def _norm_fraction(q, name="q"): if isinstance(q, (bool, float, complex)) or not isinstance(q, Fraction): raise TypeError(name) return q if type(q) is Fraction else Fraction(require_int(q.numerator, name), require_int(q.denominator, name)) def rule14_mask_justice_text(text): cur = reject_lone_surrogates(text, "text") for _ in range(8): nxt = cur for pat, repl in _RULE14_SUBS: nxt = pat.sub(repl, nxt) nxt = _RULE14_PHONE_RE.sub(lambda m: "[phone-shielded]" if 7 <= sum(c.isdigit() for c in m.group(0)) <= 15 else m.group(0), nxt) if nxt == cur: return cur cur = nxt return cur def require_rule14_clean_identifier(val, name, *, forbid_axis_delims=False): s = reject_lone_surrogates(val, name).strip() if not (1 <= len(s) <= 128) or _CTRL_ID_PAT.search(s) is not None: raise ValueError(name) if forbid_axis_delims and _AXIS_FORBIDDEN_DELIMS.search(s) is not None: raise InconsistentDemographicAxesError(name) if rule14_mask_justice_text(s) != s: raise Rule14IdentifierPIIError(name) return s def assert_output_rule14_clean(obj): st = [obj] while st: c = st.pop() if isinstance(c, str): r = c if type(c) is str else str.__str__(c) if rule14_mask_justice_text(r) != r: raise Rule14OutputSanctuaryError("o") elif isinstance(c, Mapping): for k, v in c.items(): if not isinstance(k, str): raise TypeError("k") st.extend((v, k if type(k) is str else str.__str__(k))) elif isinstance(c, Sequence) and not isinstance(c, (bytes, bytearray, memoryview)): st.extend(c) elif isinstance(c, (float, complex)) or (c is not None and not isinstance(c, (int, bool))): raise TypeError("t") return not st def validate_and_mask_prose(val, name): s = reject_lone_surrogates(val, name).strip(); m = rule14_mask_justice_text(s); sb = _SHIELD_MARKERS_PAT.sub(" ", m).strip() if any(sum(ch.isalpha() for ch in t) < 4 or _NON_ALNUM_PAT.sub("", t.lower()) in _PLACEHOLDER_ALNUM_TOKENS for t in (s, sb)): raise AB2013PlaceholderDisclosureError(name) return m def parse_rational_q(v, name="q", *, max_denom=MAX_INPUT_DENOM, max_num_factor=MAX_INPUT_ABS_NUM_FACTOR): if isinstance(v, (bool, float, complex)): raise TypeError(name) dcap, nfac = (None if max_denom is None else require_int(max_denom, "d")), require_int(max_num_factor, "n") if isinstance(v, Fraction): q = _norm_fraction(v, name) elif isinstance(v, int): q = Fraction(_require_int_range(v, -nfac, nfac, name), 1) elif isinstance(v, str): s = reject_lone_surrogates(v, name).strip() if not (1 <= len(s) <= (8192 if dcap is None else 128)) or _FRAC_OR_DEC_PAT.fullmatch(s) is None: raise ValueError(name) sg, bd = (-1 if s[0] == "-" else 1), s.lstrip("+-") if "." in bd: ip, fp = bd.split("."); dn = 10 ** len(fp); q = Fraction(sg * (int(ip) * dn + int(fp)), dn) elif "/" in bd: ns, ds = bd.split("/"); q = Fraction(sg * _ascii_to_int(ns), _ascii_to_int(ds)) else: q = Fraction(sg * _ascii_to_int(bd), 1) else: raise TypeError(name) if (dcap is None and len(fraction_to_str(q)) > 8192) or (dcap is not None and (q.denominator > dcap or abs(q.numerator) > nfac * dcap)): raise ValueError(name) return q def fraction_to_str(q): if isinstance(q, (bool, float, complex)): raise TypeError("q") fq = _norm_fraction(q, "q") if isinstance(q, Fraction) else Fraction(require_int(q, "q"), 1) ns = _int_to_ascii(fq.numerator) return ns if fq.denominator == 1 else f"{ns}/{_int_to_ascii(fq.denominator)}" def dyadic_floor_64(q): fq = _norm_fraction(q, "q") return Fraction((fq.numerator << DYADIC_SHIFT_BITS) // fq.denominator, DYADIC_DENOM) def _jcs_escape_str(text): parts = ['"'] for ch in text: cp = ord(ch) if 0xD800 <= cp <= 0xDFFF: raise ValueError(f"Lone UTF-16 surrogate U+{cp:04X} is forbidden in RFC 8785 I-JSON") esc = _JCS_CTRL_ESCAPES.get(cp) parts.append(esc if esc is not None else (f"\\u{cp:04x}" if cp < 32 else ch)) parts.append('"') return "".join(parts).encode("utf-8") def jcs_canonical_bytes(obj): buf, st = [], [(1, obj)] while st: iv, cur = st.pop() if not iv: buf.append(cur) elif cur is None or isinstance(cur, bool): buf.append(b"null" if cur is None else (b"true" if cur else b"false")) elif isinstance(cur, (float, complex)): raise TypeError("float") elif isinstance(cur, int): buf.append(f"{_require_int_range(cur, IJSON_MIN_SAFE_INT, IJSON_MAX_SAFE_INT, 'i'):d}".encode()) elif isinstance(cur, str): buf.append(_jcs_escape_str(cur if type(cur) is str else str.__str__(cur))) elif isinstance(cur, Mapping): es = sorted(((k if type(k) is str else str.__str__(k)).encode("utf-16-be"), _jcs_escape_str(k if type(k) is str else str.__str__(k)) + b":", v) if isinstance(k, str) else (_ for _ in ()).throw(TypeError("k")) for k, v in cur.items()) if any(es[i][0] == es[i - 1][0] for i in range(1, len(es))): raise ValueError("dup") buf.append(b"{"); st.append((0, b"}")) for i in range(len(es) - 1, -1, -1): st.extend(((1, es[i][2]), (0, es[i][1]))) if i: st.append((0, b",")) elif isinstance(cur, Sequence) and not isinstance(cur, (bytes, bytearray, memoryview)): buf.append(b"["); st.append((0, b"]")) for i in range(len(cur) - 1, -1, -1): st.append((1, cur[i])) if i: st.append((0, b",")) else: raise TypeError("t") return b"".join(buf) def _validate_merkle_leaves(leaves): return [_require_bytes(lf, "leaf") for lf in _require_seq(leaves, "leaves")] def _mth_range(leaves, lo, hi): cnt = hi - lo if cnt <= 1: return hashlib.sha256(b"" if cnt == 0 else b"\x00" + leaves[lo]).digest() sp = 1 << ((cnt - 1).bit_length() - 1) return hashlib.sha256(b"\x01" + _mth_range(leaves, lo, lo + sp) + _mth_range(leaves, lo + sp, hi)).digest() def rfc6962_merkle_root(leaves): raw = _validate_merkle_leaves(leaves) return _mth_range(raw, 0, len(raw)).hex() def rfc6962_inclusion_proof(leaves, leaf_index): raw = _validate_merkle_leaves(leaves) rel = _require_int_range(leaf_index, 0, len(raw) - 1, "idx", IndexError) if raw else require_int(leaf_index, "idx") if not raw: raise IndexError("idx") out, lo, hi = [], 0, len(raw) while hi - lo > 1: sp = 1 << ((hi - lo - 1).bit_length() - 1) out.append(_mth_range(raw, *( (lo + sp, hi) if rel < sp else (lo, lo + sp) )).hex()) lo, hi, rel = (lo, lo + sp, rel) if rel < sp else (lo + sp, hi, rel - sp) return out[::-1] def rfc6962_verify_inclusion(leaf, leaf_index, tree_size, proof, expected_root): rl, idx, sz = _require_bytes(leaf, "l"), require_int(leaf_index, "i"), require_int(tree_size, "s") nds, exp = [reject_lone_surrogates(nd, "n") for nd in _require_seq(proof, "p")], reject_lone_surrogates(expected_root, "e") if sz < 1 or not (0 <= idx < sz) or any(_SHA256_HEX_PAT.fullmatch(x) is None for x in (exp, *nds)): return sz < 0 dirs, rel, sub = [], idx, sz while sub > 1 and len(dirs) <= len(nds): sp = 1 << ((sub - 1).bit_length() - 1); rig = rel >= sp; dirs.append(rig) rel, sub = (rel - sp, sub - sp) if rig else (rel, sp) if sub > 1 or len(dirs) != len(nds): return sz < 0 acc = hashlib.sha256(b"\x00" + rl).digest() for rig, sh in zip(reversed(dirs), nds): sb = bytes.fromhex(sh); acc = hashlib.sha256(b"\x01" + (sb + acc if rig else acc + sb)).digest() return hmac.compare_digest(acc, bytes.fromhex(exp)) def audit_intersectional_fairness_j1( cells, *, unknown_demographic_count=0, max_unknown_share_q="1/2", metric_mode="selection_rate", min_impact_ratio_q="4/5", max_eo_gap_q="1/10", eligibility_share_floor_q="1/50", ): cseq, mode = _require_seq(cells, "c"), reject_lone_surrogates(metric_mode, "m").strip() unk = _require_int_range(unknown_demographic_count, 0, MAX_UNKNOWN_DEMOGRAPHIC_COUNT, "unk") munk, tir, teo, sfl = map(parse_rational_q, (max_unknown_share_q, min_impact_ratio_q, max_eo_gap_q, eligibility_share_floor_q)) if not (0 <= munk <= Fraction(9, 10) and 0 < tir <= 1 and 0 <= teo <= 1 and 0 < sfl <= Fraction(1, 2)) or mode not in ("selection_rate", "median_scoring_rate"): raise ValueError("J1") if not cseq: raise EmptyCohortPopulationError("0") if len(cseq) > 512: raise ValueError("max") eax, seen, hgt, prs, nkn = None, set(), None, [], 0 for r in cseq: axr = _require_map(r, "c").get("axes") if not isinstance(axr, Mapping) or not axr: raise InconsistentDemographicAxesError("ax") cax = {require_rule14_clean_identifier(k, "k", forbid_axis_delims=1): require_rule14_clean_identifier(v, "v", forbid_axis_delims=1) for k, v in axr.items()} ak = tuple(sorted(cax)) if len(cax) != len(axr) or len(ak) > 8 or (eax and ak != eax): raise InconsistentDemographicAxesError("s") eax, ct = ak, tuple((k, cax[k]) for k in ak) if ct in seen: raise DuplicateDemographicCellError("d") seen.add(ct); tot = require_int(r.get("total"), "t") if tot < 1: raise EmptyCohortPopulationError("t<1") if tot > MAX_CELL_POPULATION: raise ValueError("t>m") sel = _require_int_range(r.get("selected"), 0, tot, "s") gv = [r.get(k) for k in "pos neg tp fp".split()]; cg = any(x is not None for x in gv) if (cg and None in gv) or (hgt is not None and hgt != cg): raise DegenerateGroundTruthError("gt") hgt, ps, ng, tp, fp = cg, *(map(require_int, gv) if cg else (0, 0, 0, 0)) if cg and (min(ps, ng, tp, fp) < 0 or ps + ng != tot or tp > ps or fp > ng or tp + fp != sel): raise DegenerateGroundTruthError("cf") nkn += tot; prs.append((dict(ct), tot, sel, ps, ng, tp, fp)) ush = Fraction(unk, nkn + unk) if ush > munk: raise ExcessiveUnknownDemographicsError("u") eli, iso = [], [] for axd, tot, sel, *gt in prs: sh, rt = Fraction(tot, nkn), Fraction(sel, tot) if sh < sfl: iso.append(_kv("axes total rate_q share_q isolated_under_2pct isolation_justification", (axd, tot, fraction_to_str(rt), fraction_to_str(sh), sh < sfl, "NYC_LL144_6_RCNY_5_301_UNDER_SHARE_FLOOR"))) else: eli.append((axd, "&".join(f"{k}={v}" for k, v in axd.items()), tot, sel, *gt, sh, rt)) cfams = [("intersectional", eli)] for ax in (eax if len(eax) > 1 else ()): bks = {} for axd, *nums in prs: bks[axd[ax]] = [a + b for a, b in zip(bks.get(axd[ax], (0,) * 6), nums)] cfams.append((f"marginal:{ax}", [({ax: v}, f"{ax}={v}", *b, Fraction(b[0], nkn), Fraction(b[1], b[0])) for v, b in sorted(bks.items()) if Fraction(b[0], nkn) >= sfl])) cmps = [(nm, fg) for nm, fg in cfams if len(fg) >= 2] sings = [_kv("family axes label total rate_q share_q", (nm, fg[0][0], fg[0][1], fg[0][2], fraction_to_str(fg[0][9]), fraction_to_str(fg[0][8]))) for nm, fg in cfams if len(fg) == 1] if not cmps: raise InsufficientEligibleCohortError("0") mir, mtg, mfg, reps = Fraction(1), Fraction(0), Fraction(0), [] for fnm, fgs in cmps: smax = max(g[9] for g in fgs) if not smax: raise ZeroSelectionDegeneracyError(fnm) for g in fgs: ir = g[9] / smax; mir = min(mir, ir) reps.append(_kv("family axes label total selected share_q rate_q impact_ratio_q passes_four_fifths", (fnm, *g[:4], *map(fraction_to_str, (*g[8:], ir)), ir >= tir))) if ir < tir: raise DisparateImpactViolationError(fnm) if hgt: pg, ng = [Fraction(g[6], g[4]) for g in fgs if g[4]], [Fraction(g[7], g[5]) for g in fgs if g[5]] if min(len(pg), len(ng)) < 2: raise DegenerateGroundTruthError("eo") tg, fg = max(pg) - min(pg), max(ng) - min(ng); mtg, mfg = max(mtg, tg), max(mfg, fg) if max(tg, fg) > teo: raise DisparateImpactViolationError(fnm) out = _kv("metric_mode known_population_total unknown_demographic_count unknown_share_q comparative_family_count singleton_non_comparative_families isolated_under_2pct_cells group_reports min_impact_ratio_q equalized_odds_evaluated max_tpr_gap_q max_fpr_gap_q", (mode, nkn, unk, fraction_to_str(ush), len(cmps), sings, iso, reps, fraction_to_str(mir), hgt, fraction_to_str(mtg) if hgt else None, fraction_to_str(mfg) if hgt else None)) out["fairness_verified"] = bool(assert_output_rule14_clean(out) and cmps and mir >= tir and (not hgt or max(mtg, mfg) <= teo)) return out def _build_recourse_payload(sc, tau, mg, dl, nsc, cst, sla, msg): out = _kv("initial_score_q threshold_tau_q already_favorable recourse_required optimal_deltas_q achieved_score_q total_effort_cost_q human_appeal_ticket", (fraction_to_str(sc), fraction_to_str(tau), mg >= 0, mg < 0, dl, fraction_to_str(nsc), fraction_to_str(cst), _kv("human_appeal_available automated_execution_enabled appeal_sla_seconds summary", (sla >= 60, sla < 0, sla, msg)))) out["recourse_verified"] = bool(assert_output_rule14_clean(out) and nsc >= tau and cst >= 0) return out def solve_counterfactual_recourse_j2(features, *, threshold_tau_q, proxy_correlation_ceiling_q="7/10", appeal_sla_seconds=259_200): fseq, tau, pceil, sla = _require_seq(features, "f"), parse_rational_q(threshold_tau_q, "tau"), parse_rational_q(proxy_correlation_ceiling_q, "pc"), _require_int_range(appeal_sla_seconds, 60, MAX_SLA_WINDOW_SECONDS, "sla") if not (0 <= pceil <= 1 and 1 <= len(fseq) <= 64): raise ValueError("J2") seen, sc, cands, names, wm = set(), Fraction(0), [], [], {} for f in fseq: nm = require_rule14_clean_identifier(_require_map(f, "f").get("name", ""), "nm") if nm in seen: raise ValueError("dup") seen.add(nm); names.append(nm) mut, dr = reject_lone_surrogates(f.get("mutability", ""), "m").strip(), reject_lone_surrogates(f.get("direction", "NONE"), "d").strip() if mut not in "IMMUTABLE_PROTECTED NON_ACTIONABLE_HISTORICAL ACTIONABLE".split() or dr not in "INCREASE_ONLY DECREASE_ONLY BIDIRECTIONAL NONE".split() or (mut != "ACTIONABLE" and dr != "NONE"): raise ValueError("md") wq, xq, lq, uq, cq, rq = *map(parse_rational_q, (f.get(k) for k in "weight_q x_q lower_q upper_q".split())), parse_rational_q(f.get("cost_q", "1")), parse_rational_q(f.get("max_protected_correlation_abs_q", "0")) if not (lq <= xq <= uq and cq > 0 and 0 <= rq <= 1): raise ValueError("box") if mut == "IMMUTABLE_PROTECTED" and wq: raise ProtectedAttributeDirectWeightError(nm) if wq and rq > pceil: raise ProtectedProxyCorrelationError(nm) st = parse_rational_q(f["step_q"]) if f.get("step_q") is not None else None if st is not None and st <= 0: raise ValueError("st") wm[nm], sc = wq, sc + wq * xq sj, mj = (1, uq - xq) if (mut == "ACTIONABLE" and wq > 0 and dr in ("INCREASE_ONLY", "BIDIRECTIONAL")) else ((-1, xq - lq) if (mut == "ACTIONABLE" and wq < 0 and dr in ("DECREASE_ONLY", "BIDIRECTIONAL")) else (0, 0)) if sj and mj > 0: cands.append(_Cand(nm, abs(wq), sj, cq, mj, st, abs(wq) / cq)) mg = sc - tau if mg >= 0: return _build_recourse_payload(sc, tau, mg, dict.fromkeys(names, "0"), sc, 0, sla, "Score already meets or exceeds the threshold; optional human guardian review remains available.") df, disc, cont = -mg, sorted((c for c in cands if c.step), key=lambda c: (-c.eff, c.name)), sorted((c for c in cands if not c.step), key=lambda c: (-c.eff, c.name)) lex, st_cnt, dkm = sorted(names), 1, [int(dc.max_u // dc.step) for dc in disc] for km in dkm: st_cnt *= km + 1 if st_cnt > MAX_DISCRETE_LATTICE_STATES: raise ValueError("lat") mcg, rmd = sum((c.w_abs * c.max_u for c in cont), Fraction(0)), [Fraction(0)] * (len(disc) + 1) for i in range(len(disc) - 1, -1, -1): rmd[i] = rmd[i + 1] + disc[i].w_abs * disc[i].step * dkm[i] if mcg + rmd[0] < df: raise InfeasibleRecourseLockoutError("lock") best, cur = None, {} def _dfs(i, gd, cd): nonlocal best if gd + rmd[i] + mcg < df or (best and (cd > best[0] or (cd == best[0] and gd < df))): return if i == len(disc): rem, cc, cu = df - gd, Fraction(0), {} for c in cont: if rem > 0: uj = min(c.max_u, rem / c.w_abs); rem -= c.w_abs * uj if uj > 0: cu[c.name], cc = uj, cc + c.cost * uj if rem <= 0: mrg = dict(cur, **cu); cb = (cd + cc, tuple(-mrg.get(nm, 0) for nm in lex), mrg) if not best or cb[:2] < best[:2]: best = cb return dc = disc[i] for k in range(dkm[i] + 1): if k: cur[dc.name] = dc.step * k else: cur.pop(dc.name, None) _dfs(i + 1, gd + dc.w_abs * dc.step * k, cd + dc.cost * dc.step * k) cur.pop(dc.name, None) _dfs(0, Fraction(0), Fraction(0)) if not best: raise InfeasibleRecourseLockoutError("none") sm, bu = {c.name: c.sign for c in cands}, best[2] dls = {nm: fraction_to_str(bu.get(nm, 0) * sm.get(nm, 0)) for nm in names} return _build_recourse_payload(sc, tau, mg, dls, sc + sum((wm[nm] * bu.get(nm, 0) * sm.get(nm, 0) for nm in names), Fraction(0)), best[0], sla, "An unfavorable automated score was recorded; a zero-cost human guardian review channel is available.") def monitor_post_market_ville_j3(streams, *, mu0_q="1/10", alpha_q="1/20"): if not (1 <= len(_require_map(streams, "s")) <= MAX_VILLE_STREAMS): raise ValueError("s") mu0, al = map(parse_rational_q, (mu0_q, alpha_q)) if not (0 < mu0 < 1 and 0 < al < 1): raise ValueError("ma") cs = {} for rk, rseq in streams.items(): ks, sq = require_rule14_clean_identifier(rk, "s"), _require_seq(rseq, "q") if ks in cs or not (1 <= len(sq) <= MAX_VILLE_STREAM_LEN): raise ValueError("s") cs[ks] = sq m, ut, lm, dv = len(cs), Fraction(len(cs)) / al, Fraction(1, 2) / mu0, mu0 * (1 - mu0) reps, gm, als = {}, Fraction(1), [] for sn in sorted(cs): sq, ec, ep, es, stp = cs[sn], Fraction(1), Fraction(1), Fraction(0), None for t, rz in enumerate(sq, 1): zt = parse_rational_q(rz) if not (0 <= zt <= 1): raise ValueError("z") if stp is None: lr = Fraction(1, 4) / mu0 if t == 1 else min(lm, max(Fraction(0), (es / (t - 1) - mu0) / dv)) ec = dyadic_floor_64(ec * (1 + dyadic_floor_64(lr) * (zt - mu0))) ep, es = max(ep, ec), es + dyadic_floor_64(zt) if ec >= ut: stp = t; als.append(sn) gm = max(gm, ep) reps[sn] = _kv("steps stopped_at_step final_e_value_q peak_e_value_q drift_alarm", (len(sq), stp, fraction_to_str(ec), fraction_to_str(ep), stp is not None)) out = _kv("stream_count mu0_q alpha_q union_ville_threshold_q global_peak_e_value_q alarm_streams streams", (m, *map(fraction_to_str, (mu0, al, ut, gm)), als, reps)) out["drift_within_bound"] = bool(assert_output_rule14_clean(out) and not als and gm < ut) if als: raise PostMarketDriftAlarmError(",".join(als), report=out) return out def verify_serious_incident_clock_j4( *, incident_lifecycle_mode="READINESS_DRILL_SIMULATION", incident_categories=(), incident_occurred_utc_s=0, awareness_utc_s=0, submitted_utc_s=None, evaluation_utc_s=1_795_100_000, report_kind="COMPLETE_FINAL_REPORT", complete_followup_submitted_utc_s=None, followup_window_s=DEFAULT_INCOMPLETE_FOLLOWUP_WINDOW_S, configured_critical_sla_seconds=172_800, ): mode, rk = reject_lone_surrogates(incident_lifecycle_mode).strip(), reject_lone_surrogates(report_kind).strip() if mode not in "NO_SERIOUS_INCIDENTS_RECORDED READINESS_DRILL_SIMULATION SERIOUS_INCIDENT_RECORD".split() or rk not in "INITIAL_INCOMPLETE_REPORT COMPLETE_FINAL_REPORT".split(): raise ValueError("m") ev, cs = _require_int_range(evaluation_utc_s, 0, MAX_UTC_EPOCH_SECONDS), _require_int_range(configured_critical_sla_seconds, 60, 172_800) occ, fw = _require_int_range(incident_occurred_utc_s, 0, ev), _require_int_range(followup_window_s, 86_400, MAX_SLA_WINDOW_SECONDS) aw, cats = _require_int_range(awareness_utc_s, occ, ev), ([incident_categories] if isinstance(incident_categories, str) else list(_require_seq(incident_categories, "c"))) j4k = "incident_lifecycle_mode incident_categories statutory_deadline_seconds due_utc_s initial_submission_timely follow_up_complete_report_required statutory_clock_compliant incident_closure_complete" if mode == "NO_SERIOUS_INCIDENTS_RECORDED": if cats or occ or aw or submitted_utc_s is not None or complete_followup_submitted_utc_s is not None: raise ValueError("0") ok = 60 <= cs <= 172_800; oz = _kv(j4k, (mode, [], cs, None, None, bool(cats), ok, ok)) oz["incident_clock_verified"] = bool(assert_output_rule14_clean(oz) and ok); return oz cc = list(dict.fromkeys(reject_lone_surrogates(c).strip() for c in cats)) if not cc or any(c not in DEADLINE_BY_INCIDENT_CATEGORY for c in cc): raise ValueError("c") dl = min(DEADLINE_BY_INCIDENT_CATEGORY[c] for c in cc); due = aw + dl if submitted_utc_s is None: if ev > due: raise IncidentDeadlineBreachError("od") iok, cok, cl, fr = ev < 0, ev <= due, ev < 0, ev >= 0 else: sub = _require_int_range(submitted_utc_s, aw, ev, "s", IncidentDeadlineBreachError if require_int(submitted_utc_s) > due and require_int(submitted_utc_s) <= ev else ValueError) if sub > due: raise IncidentDeadlineBreachError("l") iok = cok = aw <= sub <= due; fr = rk == "INITIAL_INCOMPLETE_REPORT" if fr: fd = aw + fw if complete_followup_submitted_utc_s is None: if ev > fd: raise IncompleteIncidentFollowUpBreachError("fod") cl = ev < 0 else: cf = _require_int_range(complete_followup_submitted_utc_s, sub, ev) if cf > fd: raise IncompleteIncidentFollowUpBreachError("fl") cl = sub <= cf <= fd elif complete_followup_submitted_utc_s is not None: raise ValueError("fw") else: cl = iok oi = _kv(j4k, (mode, cc, dl, due, iok, fr, cok, cl)) oi["incident_clock_verified"] = bool(assert_output_rule14_clean(oi) and cok and cl); return oi def verify_training_data_lineage_j5(datasets): dseq = _require_seq(datasets, "d") if not (1 <= len(dseq) <= 128): raise ValueError("d") lvs, seen, inc = [], set(), 0 for ds in dseq: did = require_rule14_clean_identifier(_require_map(ds, "d").get("dataset_id", ""), "id") if did in seen: raise ValueError("dup") seen.add(did) cs = {sf: validate_and_mask_prose(ds.get(sf, ""), sf) for sf in AB2013_STRING_FIELDS} dpc, bm = _require_int_range(ds.get("data_points_count"), 1, IJSON_MAX_SAFE_INT), {k: strict_bool(ds.get(k)) for k in _AB2013_BOOL_KEYS} if bm["contains_ccpa_personal_information"] and not bm["pii_anonymized_before_training"]: raise CCPAAnonymizationViolationError(did) fm, sq = reject_lone_surrogates(ds.get("first_use_month", "")).strip(), parse_rational_q(ds.get("synthetic_data_fraction_q", "0")) if _AB2013_MONTH_PAT.fullmatch(fm) is None or not (0 <= sq <= 1) or bm["uses_synthetic_data_generation"] != (sq > 0): raise ValueError("m") if bm["tdm_reservation_detected"] and not bm["explicit_tdm_license"] and bm["included_in_training"]: raise TDMReservationViolationError(did) inc += bm["included_in_training"] lvs.append(jcs_canonical_bytes(dict(cs, dataset_id=did, data_points_count=dpc, first_use_month=fm, synthetic_data_fraction_q=fraction_to_str(sq), **bm))) if inc < 1: raise VacuousTrainingLineageError("0") rt, nl = rfc6962_merkle_root(lvs), len(lvs) prs = [_kv("leaf_index leaf_sha256 audit_path inclusion_verified", (i, hashlib.sha256(b"\x00" + lf).hexdigest(), p, rfc6962_verify_inclusion(lf, i, nl, p, rt))) for i, lf in enumerate(lvs) for p in (rfc6962_inclusion_proof(lvs, i),)] aok = all(pr["inclusion_verified"] for pr in prs) out = _kv("dataset_count included_dataset_count excluded_dataset_count ab2013_all_12_fields_verified tdm_reservation_respected rfc6962_lineage_merkle_root inclusion_proofs", (nl, inc, nl - inc, nl == len(dseq) and inc >= 1, aok and inc >= 1, rt, prs)) out["lineage_verified"] = bool(assert_output_rule14_clean(out) and aok and inc >= 1 and len(rt) == 64); return out def evaluate_iso42001_pdca_and_load_j6( *, system_purpose, eu_ai_act_risk_classification, fria_summary, companion_explanation, budget_b, art9_risk_register_updated, cost_zero_stop, j1_result, j2_result, j3_result, j4_result, j5_result, ): for m in (j1_result, j2_result, j3_result, j4_result, j5_result): _require_map(m, "r") pu, rc, fr, ex = (validate_and_mask_prose(v, "t") for v in (system_purpose, eu_ai_act_risk_classification, fria_summary, companion_explanation)) bc, a9, cz, ll = _require_int_range(budget_b, 1, 10_000), strict_bool(art9_risk_register_updated), strict_bool(cost_zero_stop), len(ex.split()) if ll > bc: raise CognitiveBudgetExceededError("L") pl, do = min(len(pu), len(rc), len(fr)) >= 4, j1_result.get("fairness_verified") is True and j5_result.get("lineage_verified") is True ck, ac = j3_result.get("drift_within_bound") is True, j2_result.get("recourse_verified") is True and j4_result.get("incident_clock_verified") is True and a9 and cz out = _kv("c_levels load_l budget_b load_within_budget cost_zero_stop plan_verified do_verified check_verified act_verified system_purpose eu_ai_act_risk_classification fria_summary", (1, ll, bc, ll <= bc, cz, pl, do, ck, ac, pu, rc, fr)) out["pdca_cycle_verified"] = bool(assert_output_rule14_clean(out) and pl and do and ck and ac and ll <= bc); return out class JusticeRevocationRegistry: def __init__(self): self._n = {} def _chk(self, eid): e = require_rule14_clean_identifier(eid, "eid") if e not in self._n: raise UniversalJusticeError(e) return e def has_evaluation(self, eval_id): return require_rule14_clean_identifier(eval_id, "eid") in self._n def is_revoked(self, eval_id): return self._n[self._chk(eval_id)][1] def register_evaluation(self, eval_id, *, parent_eval_id=None): e = require_rule14_clean_identifier(eval_id, "eid") if e in self._n: raise UniversalJusticeError(e) p = None if parent_eval_id is None else self._chk(parent_eval_id) if p == e: raise UniversalJusticeError(e) self._n[e] = [[], self._n[p][1] if p else bool(0)] if p: self._n[p][0].append(e) return e def revoke_evaluation(self, eval_id, reason=HUMAN_APPEAL_VETO, *, detail=""): e = self._chk(eval_id) if reject_lone_surrogates(reason, "r").strip() not in REVOCATION_REASONS: raise ValueError(reason) rule14_mask_justice_text(detail); q, aff = deque([e]), [] while q: c = q.popleft(); self._n[c][1] = bool(1) if c not in aff: aff.append(c); q.extend(self._n[c][0]) return tuple(aff) def build_humble_crystal_facts_and_gate_j7( *, j1_result, j2_result, j3_result, j4_result, j5_result, j6_result, interruption="none", evaluation_id="eval-folio-x-root", revocation_registry=None, ): rs = (j1_result, j2_result, j3_result, j4_result, j5_result, j6_result) for m in rs: _require_map(m, "r") eid, sig = require_rule14_clean_identifier(evaluation_id, "e"), reject_lone_surrogates(interruption).strip() if sig not in _ALLOWED_INTERRUPTION_SIGNALS: raise ValueError("s") try: ir, rc = parse_rational_q(j1_result.get("min_impact_ratio_q"), max_denom=None), parse_rational_q(j2_result.get("total_effort_cost_q"), max_denom=None) vp = parse_rational_q(j3_result.get("global_peak_e_value_q"), max_denom=DYADIC_DENOM, max_num_factor=64 * MAX_INPUT_ABS_NUM_FACTOR) except (TypeError, ValueError) as e: raise HumbleCrystalGateError("q") from e if not (0 <= ir <= 1 and rc >= 0 and vp >= 1 and not (vp.denominator & (vp.denominator - 1))): raise HumbleCrystalGateError("u2") sla, inc = _require_int_range(j4_result.get("statutory_deadline_seconds"), 60, MAX_SLA_WINDOW_SECONDS, "s", HumbleCrystalGateError), _require_int_range(j5_result.get("included_dataset_count"), 1, 128, "i", HumbleCrystalGateError) rt = reject_lone_surrogates(j5_result.get("rfc6962_lineage_merkle_root")) if _SHA256_HEX_PAT.fullmatch(rt) is None: raise HumbleCrystalGateError("rt") if revocation_registry is not None and not isinstance(revocation_registry, JusticeRevocationRegistry): raise TypeError("rg") rev = revocation_registry.is_revoked(eid) if (revocation_registry and revocation_registry.has_evaluation(eid)) else (sla < 0) lok = all(m.get(k) is True for m, k in zip(rs, "fairness_verified recourse_verified drift_within_bound incident_clock_verified lineage_verified pdca_cycle_verified".split())) fc = f"[{PROTOCOL_ID}-{PROTOCOL_VERSION}] min_impact_ratio_q={fraction_to_str(ir)} recourse_cost_q={fraction_to_str(rc)} ville_peak_e_q={fraction_to_str(vp)} incident_sla_s={sla} included_datasets={inc}" hf = _HEX_LEAK_IN_FACTS_PAT.search(fc) is None and rt not in fc if not hf: raise HumbleCrystalGateError("hx") hlt = sig != "none" or rev or not lok out = _kv("evaluation_id interruption revoked q3_zero_twist_enforced verified_facts rfc6962_lineage_merkle_root humble_crystal_hex_free", (eid, sig, rev, hlt, fc, rt, hf)) el = bool(assert_output_rule14_clean(out) and lok and hf and not hlt) out["eligible_for_w3c_vc"], out["credential"] = el, ("ISSUED_BY_CRUCIBLE_NOTARY" if el else None); return out def _kv(ks_str, vals): return dict(zip(ks_str.split(), vals)) _CANONICAL_DATASETS_SPECIMEN = tuple( dict(zip(("dataset_id", *AB2013_STRING_FIELDS, "data_points_count", "first_use_month", "synthetic_data_fraction_q", *_AB2013_BOOL_KEYS), (*s.split("|"), n, fm, sq, *(c == "1" for c in bm)))) for s, n, fm, sq, bm in ( ("hu-astronomy-ephemeris-corpus-v1|Jet Propulsion Laboratory DE440 & Swiss Ephemeris Public Tables|Deterministic astronomical and barycentric ephemeris verification|Tabular celestial coordinates and rational orbital elements|Public domain federal tables and Apache-2.0 open reference vectors|Canonical rational conversion and duplicate epoch removal|2020-01 through 2026-10 static archival release", 108_000, "2026-01", "1/10", "00101001"), ("external-web-opted-out-corpus|Independent Literary Guild TDM Opt-Out Registry|Excluded creative works honoring W3C TDMRep reservation|Prose literary works carrying tdm-reservation=1 header|All rights reserved under EU DSM Directive Art. 4(3)|Filtered out prior to tokenization via W3C TDMRep gate|2026-03 snapshot excluded pre-training", 5_000, "2026-03", "0", "00100100"), ) ) _SPECIMEN_CELLS = tuple(_kv("axes total selected pos neg tp fp", (_kv("sex age_band", s.split(":")), *ns)) for s, *ns in (("F:40_plus", 500, 225, 250, 250, 200, 25), ("F:under_40", 500, 230, 250, 250, 205, 25), ("M:40_plus", 500, 240, 250, 250, 210, 30), ("M:under_40", 490, 245, 245, 245, 215, 30), ("X:40_plus", 10, 5, 5, 5, 4, 1))) _SPECIMEN_FEATURES = tuple(_kv("name mutability direction weight_q x_q lower_q upper_q cost_q step_q max_protected_correlation_abs_q", [None if v == "_" else v for v in s.split("|")]) for s in ("protected_age_band|IMMUTABLE_PROTECTED|NONE|0|1|0|1|1|_|0", "historical_tenure_years|NON_ACTIONABLE_HISTORICAL|NONE|1/5|2|0|30|1|_|1/4", "verified_certifications|ACTIONABLE|INCREASE_ONLY|3/2|1|0|5|4|1|0", "debt_to_income_ratio|ACTIONABLE|DECREASE_ONLY|-2|3/5|1/10|1|3|_|0", "liquid_reserve_units|ACTIONABLE|INCREASE_ONLY|1|1/2|0|10|2|_|0")) _SPECIMEN_VILLE_STREAMS = dict(cohort_f="1/7 2/25 1/7 3/50".split(), cohort_m="3/50 2/25 1/20 1/10".split()) def build_canonical_justice_specimen(): return _kv("cells unknown_demographic_count features recourse_threshold_tau_q ville_streams datasets", (copy.deepcopy(list(_SPECIMEN_CELLS)), 12, copy.deepcopy(list(_SPECIMEN_FEATURES)), "3", copy.deepcopy(_SPECIMEN_VILLE_STREAMS), copy.deepcopy(list(_CANONICAL_DATASETS_SPECIMEN)))) def run_self_tests(): t0, b1, b0, sp = time.perf_counter(), bool(1), bool(0), build_canonical_justice_specimen() j1, j2, j3 = audit_intersectional_fairness_j1(sp["cells"], unknown_demographic_count=12), solve_counterfactual_recourse_j2(sp["features"], threshold_tau_q="3"), monitor_post_market_ville_j3(sp["ville_streams"]) j4, j5 = verify_serious_incident_clock_j4(incident_lifecycle_mode="NO_SERIOUS_INCIDENTS_RECORDED"), verify_training_data_lineage_j5(sp["datasets"]) j6 = evaluate_iso42001_pdca_and_load_j6(system_purpose="Fairness", eu_ai_act_risk_classification="Annex III", fria_summary="Rights", companion_explanation="Verified.", budget_b=250, art9_risk_register_updated=b1, cost_zero_stop=b1, j1_result=j1, j2_result=j2, j3_result=j3, j4_result=j4, j5_result=j5) j7kw = dict(j1_result=j1, j2_result=j2, j3_result=j3, j4_result=j4, j5_result=j5, j6_result=j6) j7, bs = build_humble_crystal_facts_and_gate_j7(**j7kw), f"{_int_to_ascii(1 << 14500)}/{_int_to_ascii(3 ** 7500)}" assert j7["eligible_for_w3c_vc"] and fraction_to_str(parse_rational_q(bs, max_denom=None)) == bs and jcs_canonical_bytes({"\U0001f600": 1, "\ufb33": 2}) == b'{"\xf0\x9f\x98\x80":1,"\xef\xac\xb3":2}' def _ex(fn, exc): try: fn(); return b0 except exc: return b1 fk = "name mutability direction weight_q x_q lower_q upper_q cost_q step_q" m4 = solve_counterfactual_recourse_j2([_kv(fk, ("c", *("ACTIONABLE INCREASE_ONLY 3 0 0 5 10 1".split()))), _kv(fk, ("r", *("ACTIONABLE INCREASE_ONLY 1 0 0 10 5".split()), None))], threshold_tau_q="1") unc, reg = rule14_mask_justice_text(r"\\srv\s\a.csv file:///C:/u/a.csv"), JusticeRevocationRegistry() for s in "r0 b1:r0 b1c:b1 b2:r0".split(): e, *ps = s.split(":"); reg.register_evaluation(e, parent_eval_id=ps[0] if ps else None) reg.revoke_evaluation("b1") mk = "mutant_1_marginal_rollup_catches_gerrymandering mutant_2_singleton_cohort_non_vacuity mutant_3_proxy_redlining_and_direct_protected_weight mutant_4_mixed_integer_recourse_global_optimum mutant_5_stopped_dyadic_ville_drift_and_bounds mutant_6_art73_multi_category_incident_deadline mutant_7_tdmrep_ccpa_and_ab2013_placeholder_shield mutant_8_rule14_humble_crystal_and_revocation_cascade" muts = _kv(mk, ( _ex(lambda: audit_intersectional_fairness_j1([_kv("axes total selected", (_kv("sex r", ("F" if j < 20 else "M", f"R{j % 20}")), 15 if j < 20 else 35, 3 if j < 20 else 28)) for j in range(40)]), DisparateImpactViolationError), _ex(lambda: audit_intersectional_fairness_j1([_kv("axes total selected", ({"sex": "F"}, 990, 990)), _kv("axes total selected", ({"sex": "M"}, 10, 0))]), InsufficientEligibleCohortError), _ex(lambda: solve_counterfactual_recourse_j2([_kv("name mutability direction weight_q x_q lower_q upper_q max_protected_correlation_abs_q", "zp NON_ACTIONABLE_HISTORICAL NONE 2 0 0 1 9/10".split())], threshold_tau_q="1"), ProtectedProxyCorrelationError), m4["total_effort_cost_q"] == "5" and m4["optimal_deltas_q"]["r"] == "1", _ex(lambda: monitor_post_market_ville_j3({"s1": ["1"] * 512}, mu0_q="1/1000000000"), PostMarketDriftAlarmError), _ex(lambda: verify_serious_incident_clock_j4(incident_lifecycle_mode="SERIOUS_INCIDENT_RECORD", incident_categories="DEATH_OF_PERSON WIDESPREAD_OR_CRITICAL_INFRASTRUCTURE".split(), awareness_utc_s=10, submitted_utc_s=200_000), IncidentDeadlineBreachError), _ex(lambda: verify_training_data_lineage_j5([dict(_CANONICAL_DATASETS_SPECIMEN[1], included_in_training=b1)]), TDMReservationViolationError) and _ex(lambda: verify_training_data_lineage_j5([dict(_CANONICAL_DATASETS_SPECIMEN[0], contains_ccpa_personal_information=b1, pii_anonymized_before_training=b0)]), CCPAAnonymizationViolationError), unc == "[path-shielded] [path-shielded]" and reg.is_revoked("b1c") and not reg.is_revoked("b2") and build_humble_crystal_facts_and_gate_j7(**j7kw, evaluation_id="b1c", revocation_registry=reg)["credential"] is None and _ex(lambda: build_humble_crystal_facts_and_gate_j7(**dict(j7kw, j3_result=dict(j3, global_peak_e_value_q="8/7"))), HumbleCrystalGateError), )) assert all(muts.values()) return _kv("all_passed mutants_killed mutant_results zero_forbidden_digits_verified elapsed_ms j5_merkle_root", (all(muts.values()), 8, muts, _FORBIDDEN_DIGITS.encode() not in jcs_canonical_bytes((j1, j2, j3, j4, j5, j6, j7)), int((time.perf_counter() - t0) * 1000), j5["rfc6962_lineage_merkle_root"])) if __name__ == "__main__": res = run_self_tests() assert res["all_passed"] is True print(f"OK Folio X universal_justice_core self-tests: {res}")