# SPDX-FileCopyrightText: 2026 David Porto Baraldés (Homo Universalis / Viveka) # SPDX-License-Identifier: Apache-2.0 """ Living Folio X of Leonardo da Vinci (`logic/engines/universal_justice_crucible.py`): HU-UNIVERSAL-JUSTICE-LIFECYCLE v1.0 — The Pythagorean Tetraktys (`1 + 2 + 3 + 4 = 10`) & Circumscribed Sphere of Universal Algorithmic Justice (`Ma'at`): 1. J1 — Intersectional + Automatic Marginal Fairness (`NYC LL144` / `EEOC 4/5ths` / `Equalized Odds`): - Zero-float `fractions.Fraction` impact ratio (`>= 4/5`) and Equalized Odds (`<= 1/10`), - Transparent `< 1/50` small-cohort isolation (`6 RCNY § 5-301`), automatic `marginal:` roll-ups defeating shard gerrymandering, and `WO-16` `>= 2` eligible comparative groups. 2. J2 — Exact Mixed-Integer Counterfactual Recourse & Anti-Proxy Shield (`EU AI Act Art. 86` / `Colorado SB 24-205`): - Blocks direct weights on `IMMUTABLE_PROTECTED` features and proxy redlining (`|r| > 7/10`), - Solves exact discrete branch-and-bound + continuous KKT minimum-effort recourse and issues a descriptive `WO-17`-compliant human guardian appeal ticket. 3. J3 — Anytime-Valid Post-Market Drift Monitoring (`EU AI Act Art. 72` / Ville `E`-Process): - Stopped dyadic (`2^-64`) supermartingales (`E_t >= M / alpha`), guaranteeing family-wise false alarm rate `<= alpha` across `M` demographic sub-streams without minority dilution. 4. J4 & J5 — Serious Incident Clock (`EU AI Act Art. 73`) & Training Data Lineage (`California AB 2013` / `W3C TDMRep`): - Multi-category `min(172_800, 864_000, 1_296_000)` SLA + incomplete-report follow-up closure, - 12-field `Cal. Civ. Code § 3111` disclosure, CCPA anonymization, `W3C TDMRep` opt-out gate, and domain-separated `RFC 6962` (`0x00` / `0x01`) Merkle inclusion proofs. 5. J6 & J7 — `ISO/IEC 42001:2023` PDCA Closure, Six-Folio (`V..X`) Veto Cascade, `IEEE 7001` & `W3C VC 2.0` `MaatUniversalJusticeLifecycleCredential` (`vc+jwt`, JOSE ES256 canonical low-S, `SMT-256`). Honest scope (`WO-13`): stateless mathematical, algorithmic, and cryptographic fairness/lifecycle SELF-ASSESSMENT. Not an accredited `ISO/IEC 42001` audit by an IAF/ISO 17021-1 body, not an external independent `NYC Local Law 144` CPA/counsel bias audit, not `EU AI Act Art. 43` notified-body certification, not binding legal bias counsel, and not `ISO 10218` / CE machinery safety certification. """ from __future__ import annotations import copy from datetime import datetime, timedelta, timezone from fractions import Fraction import hashlib import json import time from typing import Any, Final, Mapping, Sequence import uuid from logic.crypto.es256 import SECP256R1_ORDER from logic.engines.embodied_symbiosis_crucible import IEEE_7001_AUDIENCES from logic.engines.maat_w3c_vc_notary_crucible import ( CredentialErrorCode, CredentialSigner, LocalEphemeralSigner, MAAT_DIGNITY_JSONLD_CONTEXT_URL, MAAT_SMT_REVOCATION_LOG_ID, MAAT_VC_DEFAULT_MAX_LIFETIME_DAYS, MAAT_VC_MEDIA_TYPE, MaatCredentialVerificationError, SMT_DEFAULT_DEPTH, SparseMerkleRevocationTree, TrustedLogState, VerifiedCredential, b64url_decode, b64url_encode, issue_signed_tree_head, jcs_canonical_bytes, verify_inclusion, verify_maat_credential, ) from logic.engines.sovereign_shield_engine import ( audit_cognitive_sovereignty, generate_rfc6962_inclusion_proof, sanitize_three_rings_zk, ) from logic.justice.temple_folio_x_adapter import ( TempleUniversalJusticeCoordinator, justice_lifecycle_to_verified_knowledge_envelope, ) from logic.justice.universal_justice_core import ( COST_ZERO_STOP, DISPARATE_IMPACT_ABORT, DYADIC_DENOM, HUMAN_APPEAL_VETO, JUSTICE_INTERRUPTIONS, VILLE_DRIFT_HALT, JusticeRevocationRegistry, PostMarketDriftAlarmError, UniversalJusticeError, audit_intersectional_fairness_j1, build_canonical_justice_specimen, build_humble_crystal_facts_and_gate_j7, evaluate_iso42001_pdca_and_load_j6, fraction_to_str, monitor_post_market_ville_j3, parse_rational_q, reject_lone_surrogates, require_int, rule14_mask_justice_text, run_self_tests as run_core_self_tests, solve_counterfactual_recourse_j2, strict_bool, verify_serious_incident_clock_j4, verify_training_data_lineage_j5, ) from logic.robotics.embodied_edge_core import scan_forbidden_telemetry __all__ = [ "FOLIO_X_ID", "IEEE_7001_AUDIENCES", "JUSTICE_ASSURANCE_TEXT", "JUSTICE_DECISION_LOG_ID", "JUSTICE_INTERRUPTIONS", "JUSTICE_LAWS", "JUSTICE_REGULATORY_SCOPE", "MAAT_UNIVERSAL_JUSTICE_CREDENTIAL_TYPE", "RING_WEIGHTS", "UNIVERSAL_JUSTICE_SPEC_VERSION", "audit_universal_justice_lifecycle", "build_canonical_universal_justice_test_vectors_payload", "build_universal_justice_ieee7001_explanations", "get_canonical_universal_justice_specimen", "get_universal_justice_regulatory_boundary", "issue_w3c_universal_justice_credential", "run_folio_x_self_test", "verify_universal_justice_credential", ] # ============================================================================ # SECTION 0 — IDENTITY, HONEST SCOPE & CONSTANTS (ZERO FLOAT) # ============================================================================ FOLIO_X_ID: Final[str] = "folio-X-universal-justice-lifecycle" UNIVERSAL_JUSTICE_SPEC_VERSION: Final[str] = "HU-UNIVERSAL-JUSTICE-LIFECYCLE/v1.0" JUSTICE_LAWS: Final[tuple[str, ...]] = ("J1", "J2", "J3", "J4", "J5", "J6", "J7") MAAT_UNIVERSAL_JUSTICE_CREDENTIAL_TYPE: Final[str] = "MaatUniversalJusticeLifecycleCredential" JUSTICE_DECISION_LOG_ID: Final[str] = "hu-universal-justice-commitment-2026" JUSTICE_REGULATORY_SCOPE: Final[str] = ( "stateless_algorithmic_fairness_recourse_drift_incident_and_lineage_self_assessment_not_accredited_audit_not_legal_opinion" ) JUSTICE_ASSURANCE_TEXT: Final[str] = ( "self-assessed mathematical and algorithmic conformity across intersectional and marginal fairness " "(NYC LL144 / EEOC 4/5ths / Equalized Odds), exact mixed-integer counterfactual recourse and anti-proxy " "redlining shield (EU AI Act Art. 86 / Colorado SB 24-205), stopped dyadic Ville post-market drift " "supermartingales (EU AI Act Art. 72), serious-incident statutory clocks (EU AI Act Art. 73), " "California AB 2013 & W3C TDMRep RFC 6962 training lineage, and ISO/IEC 42001:2023 PDCA closure; " "not an accredited ISO/IEC 42001 or external NYC LL144 audit, not EU AI Act Art. 43 notified-body " "certification, not binding legal bias counsel and not a safety-rated function; recompute independently" ) _FORBIDDEN_DIGITS: Final[str] = f"{21}{6}" _REGULATORY_BOUNDARY: Final[dict[str, Any]] = { "covered_by_this_self_assessment": [ "Intersectional & automatic marginal fairness (`J1`): exact rational 4/5ths impact ratio, <= 1/10 Equalized Odds, < 1/50 small-cohort transparent isolation (NYC LL144 6 RCNY § 5-301), and >= 2 comparative cohorts (WO-16)", "Actionable counterfactual recourse & anti-proxy shield (`J2`): zero direct protected weights, |r| <= 7/10 proxy correlation ceiling, global optimum over mixed discrete/continuous box constraints, and descriptive human appeal ticket (EU AI Act Art. 86, Colorado SB 24-205, WO-17)", "Anytime-valid post-market monitoring (`J3`): stopped 2^-64 dyadic Ville supermartingales with M/alpha threshold controlling family-wise false alarms <= alpha across M cohorts (EU AI Act Art. 72)", "Serious incident clock & training data lineage (`J4`, `J5`): EU AI Act Art. 73 2d/10d/15d deadlines + incomplete follow-up closure, Cal. Civ. Code § 3111 (AB 2013) 12-field disclosure, CCPA anonymization, W3C TDMRep opt-out gate, and RFC 6962 Merkle proofs", "ISO/IEC 42001:2023 PDCA & Six-Folio cascade (`J6`, `J7`): non-vacuous PLAN/DO/CHECK/ACT closure, L <= B cognitive load, EU AI Act Art. 50(1) + IEEE 7001-2021 five-audience disclosures, and simultaneous veto/halt across Folios V..X", ], "outside_this_self_assessment": [ "Accredited third-party ISO/IEC 42001 certification by an IAF / ISO/IEC 17021-1 accreditation body", "External independent CPA or legal-counsel bias audit filing under NYC Local Law 144 or Colorado SB 24-205", "EU AI Act Art. 43 notified-body conformity assessment or CE marking", "Binding legal opinions on employment, credit, housing, copyright, or data-protection law", "Physical machinery safety certification: ISO 10218, ISO 13482, ISO/TS 15066, Regulation (EU) 2023/1230", ], "safety_rated_function": False, "accredited_iso42001_certification": False, "external_independent_ll144_audit": False, "notified_body_eu_ai_act_art43": False, "legal_bias_or_copyright_opinion": False, } RING_WEIGHTS: Final[dict[str, Fraction]] = { "ring_i_intersectional_and_marginal_fairness": Fraction(1, 4), "ring_ii_counterfactual_recourse_and_anti_proxy": Fraction(1, 5), "ring_iii_ville_drift_and_art73_incident_clock": Fraction(1, 5), "ring_iv_ab2013_tdmrep_lineage_and_six_folio_cascade": Fraction(1, 5), "ring_v_iso42001_ieee7001_rfc6962_w3c_vc": Fraction(3, 20), } def _qs(value: Fraction) -> str: return fraction_to_str(value) def get_canonical_universal_justice_specimen() -> dict[str, Any]: """Build a fresh deep copy of Canonical Specimen #0001 for Living Folio X (`J1..J7`).""" core = build_canonical_justice_specimen() b1 = bool(UNIVERSAL_JUSTICE_SPEC_VERSION.startswith("HU-")) return { "system_name": "Homo Universalis Universal Justice Lifecycle Gate", "agent_domain": "homouniversalis.ai", "cells": core["cells"], "unknown_demographic_count": core["unknown_demographic_count"], "min_impact_ratio_q": "4/5", "max_eo_gap_q": "1/10", "eligibility_share_floor_q": "1/50", "features": core["features"], "recourse_threshold_tau_q": core["recourse_threshold_tau_q"], "proxy_correlation_ceiling_q": "7/10", "appeal_sla_seconds": 259_200, "ville_streams": core["ville_streams"], "ville_mu0_q": "1/10", "ville_alpha_q": "1/20", "incident_lifecycle_mode": "NO_SERIOUS_INCIDENTS_RECORDED", "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, "configured_critical_sla_seconds": 172_800, "datasets": core["datasets"], "system_purpose": "Symbiotic algorithmic fairness, counterfactual recourse, post-market drift and training lineage governance", "eu_ai_act_risk_classification": "Annex III High-Risk Self-Assessment Lifecycle Governance Gate", "fria_summary": "Fundamental rights impact evaluated across intersectional cohorts, actionable recourse, Ville drift, Art. 73 SLA and AB 2013 lineage", "art9_risk_register_updated": b1, "downstream_disclosure_text": "I am an AI governance notary. Intersectional fairness (9/10 >= 4/5), recourse cost (31/10), Ville drift, Art. 73 SLA and AB 2013 lineage verified.", "eu_ai_act_art50_disclosed": b1, "interruption": "none", "actor_guardian_seat": 2, "cost_zero_stop_policy": b1, "budget_b": 250, "telemetry_fields": {"cohorts_audited": 5, "datasets_committed": 2}, } def get_universal_justice_regulatory_boundary() -> dict[str, Any]: """Deep copy of the honest regulatory boundary declaration (`WO-13`).""" return copy.deepcopy(_REGULATORY_BOUNDARY) # ============================================================================ # SECTION I — IEEE 7001 EXPLANATIONS & RFC 6962 COMMITMENT # ============================================================================ def build_universal_justice_ieee7001_explanations( summary: Mapping[str, Any], *, lang: str = "ca" ) -> dict[str, str]: """Descriptive explanations for the five IEEE 7001-2021 stakeholder audiences (zero directives, WO-17).""" halted = bool(summary.get("halted_or_vetoed")) ir_q = summary.get("min_impact_ratio_q", "9/10") rc_q = summary.get("recourse_effort_cost_q", "31/10") if lang == "es": companion = "Soy un sistema de inteligencia artificial, no una persona. " + ( "Se ha detenido la evaluación automatizada activando la revisión humana sin coste y llevando el movimiento a cero exacto." if halted else f"Se verificó la equidad interseccional ({ir_q} >= 4/5), el recurso accionable ({rc_q}) y el linaje de datos con canal de apelación humana." ) elif lang == "en": companion = "I am an artificial intelligence system, not a person. " + ( "The automated lifecycle evaluation halted cleanly with zero-cost human review available and motion set to an exact zero." if halted else f"Intersectional fairness ({ir_q} >= 4/5), actionable recourse ({rc_q}) and training data lineage were verified with human appeal available." ) else: companion = "Soc un sistema d'intel·ligència artificial, no una persona. " + ( "S'ha aturat l'avaluació automatitzada amb canal d'apel·lació humana sense cost i portant el moviment al zero exacte." if halted else f"S'ha verificat l'equitat interseccional ({ir_q} >= 4/5), el recurs accionable ({rc_q}) i el llinatge de dades amb apel·lació humana disponible." ) return { "companion_human": companion, "bystander_public": ( f"Stateless algorithmic fairness and lifecycle governance notary under the {UNIVERSAL_JUSTICE_SPEC_VERSION} self-assessment; " f"min_impact_ratio_q={ir_q}; recourse_cost_q={rc_q}; interruption={summary.get('interruption')}." ), "safety_engineer": ( f"ville_global_peak_e_q={summary.get('ville_peak_e_q')}; art73_deadline_s={summary.get('incident_sla_s')}; " f"q3_zero_twist_on_veto={summary.get('q3_zero_twist_on_veto')}; supervisory algorithmic software, not a safety-rated function or accredited audit." ), "incident_investigator": ( f"training_lineage_merkle_root={summary.get('lineage_merkle_root')}; decision_commitment_root={summary.get('commitment_root')}; " "every AB 2013 dataset leaf and decision summary is RFC 6962 domain-separated (0x00/0x01) under Rule 14 with c_levels=1." ), "expert_witness_regulator": ( "Self-assessed alignment with NYC Local Law 144 / EEOC 4/5ths fairness, EU AI Act Art. 9/10/14/50/72/73/86, " "Colorado SB 24-205, California AB 2013, W3C TDMRep, ISO/IEC 42001:2023 PDCA and IEEE 7001-2021; " "not an accredited ISO/IEC 42001 certificate, not an external CPA audit and not legal counsel." ), } def _commit_run_rfc6962(run_summary: Mapping[str, Any]) -> dict[str, Any]: """Commit the run summary as an RFC 6962 leaf of a per-request two-leaf tree and self-check inclusion.""" genesis = f"{UNIVERSAL_JUSTICE_SPEC_VERSION}:{JUSTICE_DECISION_LOG_ID}:genesis".encode("utf-8") leaf_bytes = jcs_canonical_bytes(dict(run_summary)) proof = generate_rfc6962_inclusion_proof([genesis, leaf_bytes], 1) inclusion_ok = verify_inclusion( proof.leaf_hash, proof.leaf_index, proof.tree_size, list(proof.audit_path), trusted_root=proof.claimed_root ) return { "log_id": JUSTICE_DECISION_LOG_ID, "log_kind": "per_request_merkle_commitment", "leaf_hash": proof.leaf_hash, "leaf_index": proof.leaf_index, "tree_size": proof.tree_size, "audit_path": list(proof.audit_path), "root_hash": proof.claimed_root, "leaf_jcs_sha256": hashlib.sha256(leaf_bytes).hexdigest(), "inclusion_self_check_passed": bool(inclusion_ok), } def _grade_for(score_100: int) -> str: if score_100 == 100: return "A+ (self-assessed)" if score_100 >= 80: return "A (self-assessed)" if score_100 >= 60: return "B (self-assessed, remediation advised)" return "C (self-assessed, remediation required)" # ============================================================================ # SECTION II — THE FIVE RINGS OF UNIVERSAL ALGORITHMIC JUSTICE # ============================================================================ def audit_universal_justice_lifecycle( *, system_name: str = "Homo Universalis Universal Justice Lifecycle Gate", agent_domain: str = "homouniversalis.ai", cells: Sequence[Mapping[str, Any]] | None = None, unknown_demographic_count: int = 12, min_impact_ratio_q: Any = "4/5", max_eo_gap_q: Any = "1/10", eligibility_share_floor_q: Any = "1/50", features: Sequence[Mapping[str, Any]] | None = None, recourse_threshold_tau_q: Any = "3", proxy_correlation_ceiling_q: Any = "7/10", appeal_sla_seconds: int = 259_200, ville_streams: Mapping[str, Sequence[Any]] | None = None, ville_mu0_q: Any = "1/10", ville_alpha_q: Any = "1/20", incident_lifecycle_mode: str = "NO_SERIOUS_INCIDENTS_RECORDED", incident_categories: Sequence[str] = (), incident_occurred_utc_s: int = 0, awareness_utc_s: int = 0, submitted_utc_s: int | None = None, evaluation_utc_s: int = 1_795_100_000, report_kind: str = "COMPLETE_FINAL_REPORT", complete_followup_submitted_utc_s: int | None = None, configured_critical_sla_seconds: int = 172_800, datasets: Sequence[Mapping[str, Any]] | None = None, system_purpose: str = "Symbiotic algorithmic fairness, counterfactual recourse, post-market drift and training lineage governance", eu_ai_act_risk_classification: str = "Annex III High-Risk Self-Assessment Lifecycle Governance Gate", fria_summary: str = "Fundamental rights impact evaluated across intersectional cohorts, actionable recourse, Ville drift, Art. 73 SLA and AB 2013 lineage", art9_risk_register_updated: bool = True, downstream_disclosure_text: str = "I am an AI governance notary. Intersectional fairness (9/10 >= 4/5), recourse cost (31/10), Ville drift, Art. 73 SLA and AB 2013 lineage verified.", eu_ai_act_art50_disclosed: bool = True, interruption: str = "none", actor_guardian_seat: int = 2, cost_zero_stop_policy: bool = True, budget_b: int = 250, telemetry_fields: Mapping[str, Any] | Sequence[Any] | None = None, lang: str = "ca", today_utc_date: str | None = None, ) -> dict[str, Any]: """ Execute one deterministic Universal Algorithmic Justice & Lifecycle Governance evaluation across the Five Universal Justice Rings (`J1..J7`). """ for label, val in ( ("system_name", system_name), ("agent_domain", agent_domain), ("incident_lifecycle_mode", incident_lifecycle_mode), ("report_kind", report_kind), ("system_purpose", system_purpose), ("eu_ai_act_risk_classification", eu_ai_act_risk_classification), ("fria_summary", fria_summary), ("downstream_disclosure_text", downstream_disclosure_text), ("interruption", interruption), ): reject_lone_surrogates(val, label) if not system_name.strip(): raise ValueError("system_name must not be empty.") if interruption not in JUSTICE_INTERRUPTIONS: raise ValueError(f"interruption must be one of {list(JUSTICE_INTERRUPTIONS)}.") actor_seat_i = require_int(actor_guardian_seat, "actor_guardian_seat") if not (1 <= actor_seat_i <= 8): raise ValueError("actor_guardian_seat must be a strict integer in 1..8.") budget_i = require_int(budget_b, "budget_b") if not (1 <= budget_i <= 10_000): raise ValueError("budget_b must be a strict integer in [1, 10000].") art9_flag = strict_bool(art9_risk_register_updated, "art9_risk_register_updated") art50_flag = strict_bool(eu_ai_act_art50_disclosed, "eu_ai_act_art50_disclosed") policy = strict_bool(cost_zero_stop_policy, "cost_zero_stop_policy") # Eagerly validate top-level scalar rationals & integer bounds at boundary (`zero-float` / `1e9` rejection) parse_rational_q(min_impact_ratio_q, "min_impact_ratio_q") parse_rational_q(max_eo_gap_q, "max_eo_gap_q") parse_rational_q(eligibility_share_floor_q, "eligibility_share_floor_q") parse_rational_q(recourse_threshold_tau_q, "recourse_threshold_tau_q") parse_rational_q(proxy_correlation_ceiling_q, "proxy_correlation_ceiling_q") parse_rational_q(ville_mu0_q, "ville_mu0_q") parse_rational_q(ville_alpha_q, "ville_alpha_q") require_int(unknown_demographic_count, "unknown_demographic_count") require_int(appeal_sla_seconds, "appeal_sla_seconds") require_int(incident_occurred_utc_s, "incident_occurred_utc_s") require_int(awareness_utc_s, "awareness_utc_s") if submitted_utc_s is not None: require_int(submitted_utc_s, "submitted_utc_s") require_int(evaluation_utc_s, "evaluation_utc_s") if complete_followup_submitted_utc_s is not None: require_int(complete_followup_submitted_utc_s, "complete_followup_submitted_utc_s") require_int(configured_critical_sla_seconds, "configured_critical_sla_seconds") canon = build_canonical_justice_specimen() eff_cells = cells if cells is not None else canon["cells"] eff_features = features if features is not None else canon["features"] eff_streams = ville_streams if ville_streams is not None else canon["ville_streams"] eff_datasets = datasets if datasets is not None else canon["datasets"] lang_norm = lang if lang in ("ca", "es", "en") else "ca" violations: list[str] = [] forbidden_telemetry = scan_forbidden_telemetry(telemetry_fields) if forbidden_telemetry: violations.extend(f"E4_J7_forbidden_telemetry:{k}" for k in forbidden_telemetry) j1_res: dict[str, Any] = {} j2_res: dict[str, Any] = {} j3_res: dict[str, Any] = {} j4_res: dict[str, Any] = {} j5_res: dict[str, Any] = {} j6_res: dict[str, Any] = {} j7_res: dict[str, Any] = {} j1_ok = bool(0) j2_ok = bool(0) j3_ok = bool(0) j4_ok = bool(0) j5_ok = bool(0) j6_ok = bool(0) min_ir_str = "0" recourse_cost_str = "0" ville_peak_str = "1" incident_sla_out = 172_800 included_ds_out = 0 lineage_root_hex = "0" * 64 vke_id = "" try: j1_res = audit_intersectional_fairness_j1( eff_cells, unknown_demographic_count=unknown_demographic_count, min_impact_ratio_q=min_impact_ratio_q, max_eo_gap_q=max_eo_gap_q, eligibility_share_floor_q=eligibility_share_floor_q, ) min_ir_str = j1_res["min_impact_ratio_q"] j1_ok = bool(j1_res.get("fairness_verified") is True) except (UniversalJusticeError, ValueError, TypeError) as exc: violations.append(f"J1_fairness_rejected:{exc.__class__.__name__}:{rule14_mask_justice_text(str(exc))}") try: j2_res = solve_counterfactual_recourse_j2( eff_features, threshold_tau_q=recourse_threshold_tau_q, proxy_correlation_ceiling_q=proxy_correlation_ceiling_q, appeal_sla_seconds=appeal_sla_seconds, ) recourse_cost_str = j2_res["total_effort_cost_q"] j2_ok = bool(j2_res.get("recourse_verified") is True) except (UniversalJusticeError, ValueError, TypeError) as exc: violations.append(f"J2_recourse_rejected:{exc.__class__.__name__}:{rule14_mask_justice_text(str(exc))}") try: j3_res = monitor_post_market_ville_j3( eff_streams, mu0_q=ville_mu0_q, alpha_q=ville_alpha_q, ) ville_peak_str = j3_res["global_peak_e_value_q"] j3_ok = bool(j3_res.get("drift_within_bound") is True) except PostMarketDriftAlarmError as exc: if isinstance(exc.report, Mapping): j3_res = dict(exc.report) ville_peak_str = str(j3_res.get("global_peak_e_value_q") or "1") violations.append(f"J3_ville_drift_alarm:{rule14_mask_justice_text(str(exc))}") except (UniversalJusticeError, ValueError, TypeError) as exc: violations.append(f"J3_ville_invalid:{exc.__class__.__name__}:{rule14_mask_justice_text(str(exc))}") try: j4_res = verify_serious_incident_clock_j4( incident_lifecycle_mode=incident_lifecycle_mode, incident_categories=incident_categories, incident_occurred_utc_s=incident_occurred_utc_s, awareness_utc_s=awareness_utc_s, submitted_utc_s=submitted_utc_s, evaluation_utc_s=evaluation_utc_s, report_kind=report_kind, complete_followup_submitted_utc_s=complete_followup_submitted_utc_s, configured_critical_sla_seconds=configured_critical_sla_seconds, ) incident_sla_out = int(j4_res["statutory_deadline_seconds"]) j4_ok = bool(j4_res.get("incident_clock_verified") is True) if not j4_ok: violations.append("J4_incident_report_open_or_unverified") except (UniversalJusticeError, ValueError, TypeError) as exc: violations.append(f"J4_incident_clock_rejected:{exc.__class__.__name__}:{rule14_mask_justice_text(str(exc))}") try: j5_res = verify_training_data_lineage_j5(eff_datasets) included_ds_out = int(j5_res["included_dataset_count"]) lineage_root_hex = str(j5_res["rfc6962_lineage_merkle_root"]) j5_ok = bool(j5_res.get("lineage_verified") is True) except (UniversalJusticeError, ValueError, TypeError) as exc: violations.append(f"J5_lineage_rejected:{exc.__class__.__name__}:{rule14_mask_justice_text(str(exc))}") try: j6_res = evaluate_iso42001_pdca_and_load_j6( system_purpose=system_purpose, eu_ai_act_risk_classification=eu_ai_act_risk_classification, fria_summary=fria_summary, companion_explanation=downstream_disclosure_text, budget_b=budget_i, art9_risk_register_updated=art9_flag, cost_zero_stop=policy, j1_result=j1_res, j2_result=j2_res, j3_result=j3_res, j4_result=j4_res, j5_result=j5_res, ) j6_ok = bool(j6_res.get("pdca_cycle_verified") is True) if not j6_ok: violations.append("J6_iso42001_pdca_incomplete") except (UniversalJusticeError, ValueError, TypeError) as exc: violations.append(f"J6_pdca_or_budget_rejected:{exc.__class__.__name__}:{rule14_mask_justice_text(str(exc))}") rev_reg = JusticeRevocationRegistry() rev_reg.register_evaluation("eval-folio-x-audit") if interruption != "none": rev_reg.revoke_evaluation("eval-folio-x-audit", interruption, detail="Audit interruption signal") if j1_ok and j2_ok and j3_ok and j4_ok and j5_ok: try: j7_res = build_humble_crystal_facts_and_gate_j7( j1_result=j1_res, j2_result=j2_res, j3_result=j3_res, j4_result=j4_res, j5_result=j5_res, j6_result=j6_res, interruption=interruption, evaluation_id="eval-folio-x-audit", revocation_registry=rev_reg, ) if j7_res.get("eligible_for_w3c_vc") is True and not forbidden_telemetry: vke = justice_lifecycle_to_verified_knowledge_envelope( j1_result=j1_res, j2_result=j2_res, j3_result=j3_res, j4_result=j4_res, j5_result=j5_res, j6_result=j6_res, evaluation_id="eval-folio-x-audit", revocation_registry=rev_reg, source_level=2, ) vke_id = vke.envelope_id except (UniversalJusticeError, ValueError, TypeError) as exc: violations.append(f"J7_humble_crystal_rejected:{exc.__class__.__name__}:{rule14_mask_justice_text(str(exc))}") masked_disc = sanitize_three_rings_zk( rule14_mask_justice_text(downstream_disclosure_text), today_utc_date=today_utc_date ) residual_pii = int(masked_disc["total_redactions"]) # Independent Six-Folio (V + VI + VII + VIII + IX + X) veto / halt cascade probe with sibling isolation coord = TempleUniversalJusticeCoordinator(lang=lang_norm, clock_ms=lambda: 1000) coord.body.on_human_pose(("6/5", "0", "0")) coord.body.on_vulnerable_presence(bool(0)) coord.register_justice_evaluation("probe-justice-root") coord.register_justice_evaluation("probe-justice-branch-a", parent_eval_id="probe-justice-root") coord.register_justice_evaluation("probe-justice-child-a1", parent_eval_id="probe-justice-branch-a") coord.register_justice_evaluation("probe-justice-sibling-b", parent_eval_id="probe-justice-root") probe_sig = ( COST_ZERO_STOP if interruption == COST_ZERO_STOP else ( DISPARATE_IMPACT_ABORT if interruption == DISPARATE_IMPACT_ABORT else (VILLE_DRIFT_HALT if interruption == VILLE_DRIFT_HALT else HUMAN_APPEAL_VETO) ) ) veto_cascade = coord.trigger_justice_veto_or_halt_cascade( signal_kind=probe_sig, actor_guardian_seat=actor_seat_i, target_eval_id="probe-justice-branch-a", note="Justice sanctuary probe VVK-1234-5678", ) child_revoked = coord.justice_revocation_registry.is_revoked("probe-justice-child-a1") sibling_intact = not coord.justice_revocation_registry.is_revoked("probe-justice-sibling-b") cascade_ok = bool( policy and residual_pii == 0 and not forbidden_telemetry and veto_cascade["q3_zero_twist_enforced"] and veto_cascade["levels_cancelled"] == [1, 2, 3] and child_revoked and sibling_intact and "VVK-1234" not in veto_cascade["note_masked"] ) if not policy: violations.append("J7_cost_zero_stop_policy_disabled") shield = audit_cognitive_sovereignty( downstream_disclosure_text, budget_B=budget_i, c_levels=1, cost_zero_stop=policy, ) shield_non_l7_ok = not [v for v in shield["violations"] if not str(v).startswith("L7")] violations.extend(f"FIL_DOR:{v}" for v in shield["violations"]) ring_i = bool(j1_ok) ring_ii = bool(j2_ok) ring_iii = bool(j3_ok and j4_ok) ring_iv = bool(j5_ok and cascade_ok and shield_non_l7_ok) commitment = _commit_run_rfc6962( { "spec": UNIVERSAL_JUSTICE_SPEC_VERSION, "system_name": rule14_mask_justice_text(system_name), "min_impact_ratio_q": min_ir_str, "recourse_effort_cost_q": recourse_cost_str, "ville_global_peak_e_q": ville_peak_str, "training_lineage_merkle_root": lineage_root_hex, "rings_pre_v": {"i": ring_i, "ii": ring_ii, "iii": ring_iii, "iv": ring_iv}, } ) summary_for_ieee = { "min_impact_ratio_q": min_ir_str, "recourse_effort_cost_q": recourse_cost_str, "ville_peak_e_q": ville_peak_str, "incident_sla_s": incident_sla_out, "lineage_merkle_root": lineage_root_hex, "commitment_root": commitment["root_hash"], "interruption": interruption, "halted_or_vetoed": bool((interruption != "none") or (not (ring_i and ring_ii and ring_iii and ring_iv))), "q3_zero_twist_on_veto": veto_cascade["q3_zero_twist_enforced"], } explanations = build_universal_justice_ieee7001_explanations(summary_for_ieee, lang=lang_norm) explanations_complete = all(bool(explanations.get(aud, "").strip()) for aud in IEEE_7001_AUDIENCES) if not art50_flag: violations.append("J7_eu_ai_act_art50_not_disclosed") j7_ok = bool( j7_res.get("eligible_for_w3c_vc") is True and bool(vke_id) and cascade_ok and shield_non_l7_ok and art50_flag and explanations_complete and commitment["inclusion_self_check_passed"] and interruption == "none" ) ring_v = bool(j6_ok and art50_flag and explanations_complete and commitment["inclusion_self_check_passed"]) rings_passed = { "ring_i_intersectional_and_marginal_fairness": ring_i, "ring_ii_counterfactual_recourse_and_anti_proxy": ring_ii, "ring_iii_ville_drift_and_art73_incident_clock": ring_iii, "ring_iv_ab2013_tdmrep_lineage_and_six_folio_cascade": ring_iv, "ring_v_iso42001_ieee7001_rfc6962_w3c_vc": ring_v, } exact_total = sum((RING_WEIGHTS[key] for key, ok in rings_passed.items() if ok), Fraction(0)) score_100 = int(exact_total * 100) laws_status = { "J1": j1_ok, "J2": j2_ok, "J3": j3_ok, "J4": j4_ok, "J5": j5_ok, "J6": j6_ok, "J7": j7_ok, } rings_out: dict[str, Any] = {} for key, weight in RING_WEIGHTS.items(): ok = rings_passed[key] rings_out[key] = {"weight": _qs(weight), "passed": ok, "earned": _qs(weight if ok else Fraction(0))} rings_out["ring_i_intersectional_and_marginal_fairness"].update( { "min_impact_ratio_q": min_ir_str, "comparative_family_count": int(j1_res.get("comparative_family_count", 0)), "isolated_under_2pct_cells": list(j1_res.get("isolated_under_2pct_cells", [])), "equalized_odds_evaluated": bool(j1_res.get("equalized_odds_evaluated")), "max_tpr_gap_q": j1_res.get("max_tpr_gap_q"), "max_fpr_gap_q": j1_res.get("max_fpr_gap_q"), } ) rings_out["ring_ii_counterfactual_recourse_and_anti_proxy"].update( { "initial_score_q": j2_res.get("initial_score_q", "0"), "achieved_score_q": j2_res.get("achieved_score_q", "0"), "total_effort_cost_q": recourse_cost_str, "optimal_deltas_q": dict(j2_res.get("optimal_deltas_q", {})), "human_appeal_ticket": dict(j2_res.get("human_appeal_ticket", {})), } ) rings_out["ring_iii_ville_drift_and_art73_incident_clock"].update( { "ville_global_peak_e_value_q": ville_peak_str, "union_ville_threshold_q": j3_res.get("union_ville_threshold_q", "40"), "incident_lifecycle_mode": incident_lifecycle_mode, "statutory_deadline_seconds": incident_sla_out, "incident_clock_verified": j4_ok, } ) rings_out["ring_iv_ab2013_tdmrep_lineage_and_six_folio_cascade"].update( { "included_dataset_count": included_ds_out, "rfc6962_lineage_merkle_root": lineage_root_hex, "folio_vi_verified_knowledge_envelope_id": vke_id, "q3_zero_twist_on_veto": veto_cascade["q3_zero_twist_enforced"], "sibling_isolation_verified": sibling_intact, "veto_propagation_latency_ns": int(veto_cascade["propagation_latency_ns"]), "forbidden_telemetry_keys": forbidden_telemetry, } ) rings_out["ring_v_iso42001_ieee7001_rfc6962_w3c_vc"].update( { "iso42001_pdca_verified": j6_ok, "c_levels": 1, "load_l": int(j6_res.get("load_l", len(downstream_disclosure_text.split()))), "budget_b": budget_i, } ) passes_all = bool(all(rings_passed.values()) and j7_ok) return { "schema_version": UNIVERSAL_JUSTICE_SPEC_VERSION, "folio_id": FOLIO_X_ID, "self_assessment": bool(UNIVERSAL_JUSTICE_SPEC_VERSION.startswith("HU-")), "assurance": JUSTICE_ASSURANCE_TEXT, "regulatory_scope": JUSTICE_REGULATORY_SCOPE, "regulatory_boundary": get_universal_justice_regulatory_boundary(), "system_name": rule14_mask_justice_text(system_name), "agent_domain": rule14_mask_justice_text(agent_domain), "interruption": interruption, "min_impact_ratio_q": min_ir_str, "recourse_effort_cost_q": recourse_cost_str, "ville_global_peak_e_value_q": ville_peak_str, "incident_statutory_deadline_seconds": incident_sla_out, "included_training_datasets_count": included_ds_out, "training_lineage_merkle_root": lineage_root_hex, "iso42001_pdca_verified": j6_ok, "folio_vi_verified_knowledge_envelope_id": vke_id, "five_justice_rings": rings_out, "exact_rational_score": _qs(exact_total), "total_score_100": score_100, "universal_justice_grade": _grade_for(score_100), "passes_internal_justice_criteria": passes_all, "justice_laws_status": laws_status, "justice_laws_verified": [law for law in JUSTICE_LAWS if laws_status[law]], "fil_dor_laws_verified": list(shield["laws_verified"]), "ieee_7001_explanations": explanations, "decision_commitment": commitment, "violations": violations, } # ============================================================================ # SECTION III — W3C VC 2.0 `MaatUniversalJusticeLifecycleCredential` # ============================================================================ def _format_rfc3339_utc(dt: datetime) -> str: return dt.astimezone(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z") def _parse_rfc3339_utc(ts_str: str) -> datetime: s = ts_str.strip() if s.endswith("Z"): s = s[:-1] + "+00:00" dt = datetime.fromisoformat(s) if dt.tzinfo is None: raise ValueError("Timestamp must include an explicit timezone offset or 'Z'.") return dt.astimezone(timezone.utc) def issue_w3c_universal_justice_credential( *, system_id: str, system_name: str, justice_score_100: int, justice_laws_verified: Sequence[str], fil_dor_laws_verified: Sequence[str], min_impact_ratio_rational: str, counterfactual_effort_cost_rational: str, ville_global_peak_e_rational: str, incident_statutory_deadline_seconds: int, included_training_datasets_count: int, training_lineage_merkle_root_hex: str, iso42001_pdca_verified: bool, rule14_zero_knowledge: bool, eu_ai_act_art50_disclosed: bool, cost_zero_stop: bool, merkle_root_hex: str, revocation_root_hex: str, signer: CredentialSigner, issuance_date_utc: str | None = None, valid_until_utc: str | None = None, serial_id: str | None = None, credential_uuid: str | None = None, max_lifetime_days: int = MAAT_VC_DEFAULT_MAX_LIFETIME_DAYS, ) -> dict[str, Any]: """ Issue a W3C VC 2.0 `MaatUniversalJusticeLifecycleCredential` (also typed `MaatHumanDignityCredential` so the Folio IV verifier policy applies) as a VC-JOSE-COSE compact JWS (`typ: vc+jwt`, ES256 low-S, JCS). """ score_i = require_int(justice_score_100, "justice_score_100") if not (0 <= score_i <= 100): raise ValueError("justice_score_100 must be an integer in [0, 100].") sla_i = require_int(incident_statutory_deadline_seconds, "incident_statutory_deadline_seconds") if not (60 <= sla_i <= 31_536_000): raise ValueError("incident_statutory_deadline_seconds must be in [60, 31536000].") ds_cnt = require_int(included_training_datasets_count, "included_training_datasets_count") if not (1 <= ds_cnt <= 128): raise ValueError("included_training_datasets_count must be in [1, 128].") for label, val in ( ("system_id", system_id), ("system_name", system_name), ("min_impact_ratio_rational", min_impact_ratio_rational), ("counterfactual_effort_cost_rational", counterfactual_effort_cost_rational), ("ville_global_peak_e_rational", ville_global_peak_e_rational), ): s_val = reject_lone_surrogates(val, label).strip() if not s_val: raise ValueError(f"{label} must be a non-empty string.") ir_q = parse_rational_q(min_impact_ratio_rational, "min_impact_ratio_rational", max_denom=None) rc_q = parse_rational_q(counterfactual_effort_cost_rational, "counterfactual_effort_cost_rational", max_denom=None) vp_q = parse_rational_q( ville_global_peak_e_rational, "ville_global_peak_e_rational", max_denom=DYADIC_DENOM, max_num_factor=64 * 10**18, ) if not (0 < ir_q <= 1 and rc_q >= 0 and vp_q >= 1 and (vp_q.denominator & (vp_q.denominator - 1)) == 0): raise ValueError("Invalid rational invariants for MaatUniversalJusticeLifecycleCredential.") for label, flag in ( ("iso42001_pdca_verified", iso42001_pdca_verified), ("rule14_zero_knowledge", rule14_zero_knowledge), ("eu_ai_act_art50_disclosed", eu_ai_act_art50_disclosed), ("cost_zero_stop", cost_zero_stop), ): strict_bool(flag, label) j_laws = [reject_lone_surrogates(x, "law") for x in justice_laws_verified] if any(law not in JUSTICE_LAWS for law in j_laws): raise ValueError("justice_laws_verified must only contain J1..J7.") if not isinstance(signer, CredentialSigner): raise TypeError("signer must implement the CredentialSigner protocol (asymmetric ES256).") max_days = require_int(max_lifetime_days, "max_lifetime_days") if max_days <= 0: raise ValueError("max_lifetime_days must be a positive integer.") for root_label, root_hex in ( ("training_lineage_merkle_root_hex", training_lineage_merkle_root_hex), ("merkle_root_hex", merkle_root_hex), ("revocation_root_hex", revocation_root_hex), ): try: rb = bytes.fromhex(root_hex) except (TypeError, ValueError) as exc: raise ValueError(f"{root_label} must be a hex string: {exc}") from exc if len(rb) != 32: raise ValueError(f"{root_label} must be a 32-byte SHA-256 root.") now_dt = datetime.now(timezone.utc).replace(microsecond=0) valid_from_dt = _parse_rfc3339_utc(issuance_date_utc) if issuance_date_utc is not None else now_dt valid_until_dt = ( _parse_rfc3339_utc(valid_until_utc) if valid_until_utc is not None else valid_from_dt + timedelta(days=max_days) ) if valid_until_dt <= valid_from_dt or valid_until_dt - valid_from_dt > timedelta(days=max_days): raise ValueError("Invalid credential validity window.") if credential_uuid is not None: vc_uuid_obj = uuid.UUID(reject_lone_surrogates(credential_uuid, "credential_uuid")) if vc_uuid_obj.version != 4: raise ValueError("credential_uuid must be a valid RFC 9562 UUIDv4.") else: vc_uuid_obj = uuid.uuid4() effective_serial = ( serial_id.strip() if isinstance(serial_id, str) and serial_id.strip() else f"MAAT-UJL-{vc_uuid_obj.hex[:12].upper()}" ) vc_claims: dict[str, Any] = { "@context": ["https://www.w3.org/ns/credentials/v2", MAAT_DIGNITY_JSONLD_CONTEXT_URL], "id": f"urn:uuid:{vc_uuid_obj}", "serialNumber": effective_serial, "type": ["VerifiableCredential", "MaatHumanDignityCredential", MAAT_UNIVERSAL_JUSTICE_CREDENTIAL_TYPE], "issuer": { "id": "did:web:homouniversalis.ai", "name": "Homo Universalis — Viveka (Ma'at Sovereign Notary)", "notaryFolio": "https://homouniversalis.ai/oracle/justice", }, "validFrom": _format_rfc3339_utc(valid_from_dt), "validUntil": _format_rfc3339_utc(valid_until_dt), "credentialStatus": { "id": f"https://homouniversalis.ai/oracle/justice#status-{effective_serial}", "type": "HUSparseMerkleStatus2026", "statusLog": MAAT_SMT_REVOCATION_LOG_ID, "serialId": effective_serial, }, "credentialSubject": { "id": system_id.strip(), "name": system_name.strip(), "universalJusticeSpec": UNIVERSAL_JUSTICE_SPEC_VERSION, "universalJusticeScore100": score_i, "universalJusticeLawsVerified": j_laws, "lawsVerified": [reject_lone_surrogates(x, "fil_dor_law") for x in fil_dor_laws_verified], "c_levels": 1, "cost_zero_stop": cost_zero_stop, "minImpactRatioRational": _qs(ir_q), "counterfactualEffortCostRational": _qs(rc_q), "villeGlobalPeakERational": _qs(vp_q), "incidentStatutoryDeadlineSeconds": sla_i, "includedTrainingDatasetsCount": ds_cnt, "trainingLineageMerkleRoot": training_lineage_merkle_root_hex.lower(), "iso42001PdcaVerified": iso42001_pdca_verified, "rule14ZeroKnowledge": rule14_zero_knowledge, "aiIdentityDisclosed": eu_ai_act_art50_disclosed, "accreditedCertificationClaimed": bool(0), "legalBiasOpinionClaimed": bool(0), "regulatoryScope": JUSTICE_REGULATORY_SCOPE, "rfc6962MerkleRoot": merkle_root_hex.lower(), "issuanceTimeRevocationRoot": revocation_root_hex.lower(), }, } header_b64 = b64url_encode(jcs_canonical_bytes({"alg": "ES256", "kid": signer.kid, "typ": MAAT_VC_MEDIA_TYPE})) payload_bytes = jcs_canonical_bytes(vc_claims) payload_b64 = b64url_encode(payload_bytes) raw_sig = signer.sign(f"{header_b64}.{payload_b64}".encode("ascii")) if not isinstance(raw_sig, (bytes, bytearray)) or len(raw_sig) != 64: raise ValueError("CredentialSigner.sign() must return a 64-byte JOSE (r || s) ES256 signature.") return { **vc_claims, "media_type": f"application/{MAAT_VC_MEDIA_TYPE}", "alg": "ES256", "kid": signer.kid, "typ": MAAT_VC_MEDIA_TYPE, "payload_jcs_sha256": hashlib.sha256(payload_bytes).hexdigest(), "compact_jws": f"{header_b64}.{payload_b64}.{b64url_encode(bytes(raw_sig))}", "vc": copy.deepcopy(vc_claims), } def verify_universal_justice_credential( credential: str | Mapping[str, Any], *, trusted_jwks: Mapping[str, Any], trusted_status_sth: Any, now: datetime | str, status_proof: Mapping[str, Any] | None = None, smt_depth: int = SMT_DEFAULT_DEPTH, strict_low_s: bool = True, ) -> VerifiedCredential: """ Verify a `MaatUniversalJusticeLifecycleCredential`: full Folio IV policy (ES256 low-S, issuer, validity, signed SMT-256 status) plus Folio X invariants (type, honest scope, J1..J7 laws, ISO 42001 PDCA, Art. 50 disclosure, and `accreditedCertificationClaimed == False` & `legalBiasOpinionClaimed == False`). """ verified = verify_maat_credential( credential, trusted_jwks=trusted_jwks, trusted_status_sth=trusted_status_sth, status_proof=status_proof, now=now, smt_depth=smt_depth, strict_low_s=strict_low_s, ) claims = verified.claims if MAAT_UNIVERSAL_JUSTICE_CREDENTIAL_TYPE not in (claims.get("type") or []): raise MaatCredentialVerificationError( CredentialErrorCode.INVALID_CREDENTIAL_TYPE, "Missing MaatUniversalJusticeLifecycleCredential type." ) if MAAT_DIGNITY_JSONLD_CONTEXT_URL not in (claims.get("@context") or []): raise MaatCredentialVerificationError(CredentialErrorCode.INVALID_CONTEXT, "Missing Ma'at JSON-LD context.") subj = claims.get("credentialSubject") or {} score = subj.get("universalJusticeScore100") ds_cnt = subj.get("includedTrainingDatasetsCount") sla_s = subj.get("incidentStatutoryDeadlineSeconds") j_laws = subj.get("universalJusticeLawsVerified") t_root = subj.get("trainingLineageMerkleRoot") if ( subj.get("regulatoryScope") != JUSTICE_REGULATORY_SCOPE or subj.get("universalJusticeSpec") != UNIVERSAL_JUSTICE_SPEC_VERSION or isinstance(score, bool) or not isinstance(score, int) or not (0 <= score <= 100) or isinstance(ds_cnt, bool) or not isinstance(ds_cnt, int) or not (1 <= ds_cnt <= 128) or isinstance(sla_s, bool) or not isinstance(sla_s, int) or not (60 <= sla_s <= 31_536_000) or not isinstance(j_laws, list) or any(law not in JUSTICE_LAWS for law in j_laws) or not isinstance(t_root, str) or len(t_root) != 64 or subj.get("c_levels") != 1 or subj.get("iso42001PdcaVerified") is not True or subj.get("aiIdentityDisclosed") is not True or subj.get("accreditedCertificationClaimed") is not False or subj.get("legalBiasOpinionClaimed") is not False ): raise MaatCredentialVerificationError( CredentialErrorCode.DOMAIN_INVARIANT_VIOLATION, "Universal justice lifecycle invariants violated in credentialSubject.", ) return verified # ============================================================================ # SECTION IV — DETERMINISTIC SELF-TEST WITH 8 ANTIPODAL MUTANTS (M1..M8) # ============================================================================ def _high_s_twin(compact_jws: str) -> str: head, payload, sig_b64 = compact_jws.split(".") sig = b64url_decode(sig_b64) r_int, s_int = int.from_bytes(sig[:32], "big"), int.from_bytes(sig[32:], "big") twin = r_int.to_bytes(32, "big") + (SECP256R1_ORDER - s_int).to_bytes(32, "big") return f"{head}.{payload}.{b64url_encode(twin)}" def _raises_on_verify(fn: Any) -> bool: try: fn() except (MaatCredentialVerificationError, ValueError, TypeError, UniversalJusticeError): return bool(1) return bool(0) def build_canonical_universal_justice_test_vectors_payload() -> dict[str, Any]: """Generate the 8 deterministic reference test vectors (`UJ-TV-001..008`) for Living Folio X.""" spec = build_canonical_justice_specimen() j1 = audit_intersectional_fairness_j1(spec["cells"], unknown_demographic_count=spec["unknown_demographic_count"]) j2 = solve_counterfactual_recourse_j2(spec["features"], threshold_tau_q=spec["recourse_threshold_tau_q"]) j3 = monitor_post_market_ville_j3(spec["ville_streams"]) j4_zero = verify_serious_incident_clock_j4(incident_lifecycle_mode="NO_SERIOUS_INCIDENTS_RECORDED") j4_multi = verify_serious_incident_clock_j4( incident_lifecycle_mode="READINESS_DRILL_SIMULATION", incident_categories=["DEATH_OF_PERSON", "WIDESPREAD_OR_CRITICAL_INFRASTRUCTURE"], awareness_utc_s=1_795_000_000, submitted_utc_s=1_795_086_400, evaluation_utc_s=1_795_100_000, ) j5 = verify_training_data_lineage_j5(spec["datasets"]) j6 = evaluate_iso42001_pdca_and_load_j6( system_purpose="Symbiotic algorithmic fairness, counterfactual recourse, post-market drift and training lineage governance", eu_ai_act_risk_classification="Annex III High-Risk Self-Assessment Lifecycle Governance Gate", fria_summary="Fundamental rights impact evaluated across intersectional cohorts, actionable recourse, Ville drift, Art. 73 SLA and AB 2013 lineage", companion_explanation="Seven justice laws verified.", budget_b=250, art9_risk_register_updated=bool(1), cost_zero_stop=bool(1), j1_result=j1, j2_result=j2, j3_result=j3, j4_result=j4_zero, j5_result=j5, ) j7 = build_humble_crystal_facts_and_gate_j7( j1_result=j1, j2_result=j2, j3_result=j3, j4_result=j4_zero, j5_result=j5, j6_result=j6 ) m4_knap = solve_counterfactual_recourse_j2( [ {"name": "cert", "mutability": "ACTIONABLE", "direction": "INCREASE_ONLY", "weight_q": "3", "x_q": "0", "lower_q": "0", "upper_q": "5", "cost_q": "10", "step_q": "1"}, {"name": "reserve", "mutability": "ACTIONABLE", "direction": "INCREASE_ONLY", "weight_q": "1", "x_q": "0", "lower_q": "0", "upper_q": "10", "cost_q": "5"}, ], threshold_tau_q="1", ) return { "format": "hu-universal-justice-test-vectors", "spec": UNIVERSAL_JUSTICE_SPEC_VERSION, "vector_set_version": "1.0.0", "url": "https://homouniversalis.ai/codex/test-vectors/universal-justice-v1.0.json", "folio_url": "https://homouniversalis.ai/oracle/justice", "license": "Apache-2.0", "zero_float_invariant": bool(1), "vectors_count": 8, "vectors": [ { "id": "UJ-TV-001", "law": "J1", "title": "Exact Rational Intersectional & Marginal Fairness + NYC LL144 < 2% Isolation", "expected": { "known_population_total": j1["known_population_total"], "comparative_family_count": j1["comparative_family_count"], "isolated_under_2pct_count": len(j1["isolated_under_2pct_cells"]), "min_impact_ratio_q": j1["min_impact_ratio_q"], "max_tpr_gap_q": j1["max_tpr_gap_q"], "max_fpr_gap_q": j1["max_fpr_gap_q"], "fairness_verified": j1["fairness_verified"], }, }, { "id": "UJ-TV-002", "law": "J2a", "title": "Canonical Specimen #0001 Mixed-Integer Counterfactual Recourse & Human Appeal Ticket", "expected": { "initial_score_q": j2["initial_score_q"], "threshold_tau_q": j2["threshold_tau_q"], "optimal_deltas_q": j2["optimal_deltas_q"], "achieved_score_q": j2["achieved_score_q"], "total_effort_cost_q": j2["total_effort_cost_q"], "human_appeal_available": j2["human_appeal_ticket"]["human_appeal_available"], "recourse_verified": j2["recourse_verified"], }, }, { "id": "UJ-TV-003", "law": "J2b", "title": "Mixed Discrete + Continuous Recourse Global Optimum Defeating Naive Greedy", "expected": { "optimal_deltas_q": m4_knap["optimal_deltas_q"], "total_effort_cost_q": m4_knap["total_effort_cost_q"], "achieved_score_q": m4_knap["achieved_score_q"], }, }, { "id": "UJ-TV-004", "law": "J3", "title": "Stopped 2^-64 Dyadic Ville E-Process Post-Market Drift Monitoring (EU AI Act Art. 72)", "expected": { "stream_count": j3["stream_count"], "mu0_q": j3["mu0_q"], "alpha_q": j3["alpha_q"], "union_ville_threshold_q": j3["union_ville_threshold_q"], "global_peak_e_value_q": j3["global_peak_e_value_q"], "drift_within_bound": j3["drift_within_bound"], }, }, { "id": "UJ-TV-005", "law": "J4", "title": "EU AI Act Art. 73 Multi-Category Serious Incident Statutory Clock (min = 172800s)", "expected": { "zero_incidents_compliant": j4_zero["incident_clock_verified"], "multi_category_statutory_deadline_seconds": j4_multi["statutory_deadline_seconds"], "multi_category_due_utc_s": j4_multi["due_utc_s"], "multi_category_verified": j4_multi["incident_clock_verified"], }, }, { "id": "UJ-TV-006", "law": "J5", "title": "California AB 2013 12-Field Lineage, W3C TDMRep Gate & RFC 6962 Merkle Root", "expected": { "dataset_count": j5["dataset_count"], "included_dataset_count": j5["included_dataset_count"], "excluded_dataset_count": j5["excluded_dataset_count"], "rfc6962_lineage_merkle_root": j5["rfc6962_lineage_merkle_root"], "inclusion_proofs": j5["inclusion_proofs"], "lineage_verified": j5["lineage_verified"], }, }, { "id": "UJ-TV-007", "law": "J6", "title": "ISO/IEC 42001:2023 Non-Vacuous PDCA Closure & Cognitive Load L <= B", "expected": { "c_levels": j6["c_levels"], "load_l": j6["load_l"], "budget_b": j6["budget_b"], "plan_verified": j6["plan_verified"], "do_verified": j6["do_verified"], "check_verified": j6["check_verified"], "act_verified": j6["act_verified"], "pdca_cycle_verified": j6["pdca_cycle_verified"], }, }, { "id": "UJ-TV-008", "law": "J7", "title": "Hex-Free Law U2 Humble Crystal Facts, UTF-16BE JCS & Rule 14 UNC/File Masking", "expected": { "verified_facts": j7["verified_facts"], "humble_crystal_hex_free": j7["humble_crystal_hex_free"], "eligible_for_w3c_vc": j7["eligible_for_w3c_vc"], "utf16be_jcs_hex": jcs_canonical_bytes({"\U0001f600": 1, "\ufb33": 2}).hex(), "rule14_masked_unc": rule14_mask_justice_text(r"\\srv\s\a.csv file:///C:/u/a.csv mail a@b.co VVK-AB12-CD34"), }, }, ], } def run_folio_x_self_test() -> dict[str, Any]: """ Ephemeral deterministic self-test of Living Folio X (0 network calls), executing both the standalone pure-stdlib `run_self_tests()` (`8/8` mutants) and the Ma'at W3C VC 2.0 + Six-Folio (V + VI + VII + VIII + IX + X) symbiotic integration verification. """ t0 = time.perf_counter_ns() core_report = run_core_self_tests() specimen = get_canonical_universal_justice_specimen() audit = audit_universal_justice_lifecycle(**specimen, lang="en") specimen_ok = bool(audit["passes_internal_justice_criteria"]) vc_signer = LocalEphemeralSigner(kid="maat-justice-vc-es256-selftest-ephemeral") sth_signer = LocalEphemeralSigner(kid="hu-log-sth-es256-selftest-ephemeral") jwks = {"keys": [vc_signer.public_jwk(), sth_signer.public_jwk()]} now_dt = datetime(2026, 11, 26, 12, 0, 0, tzinfo=timezone.utc) serial = "MAAT-UJL-SELFTEST-0001" smt = SparseMerkleRevocationTree(depth=SMT_DEFAULT_DEPTH) smt.set_status(serial, "ACTIVE") sth_smt = issue_signed_tree_head( log_id=MAAT_SMT_REVOCATION_LOG_ID, tree_size=1, root_hash=smt.root_bytes, timestamp_ms=int(now_dt.timestamp()) * 1000 - 1000, kind="smt-256", signer=sth_signer, ) TrustedLogState(jwks).update(sth_smt) status_proof = smt.prove_status(serial) rings = audit["five_justice_rings"] vc = issue_w3c_universal_justice_credential( system_id="https://homouniversalis.ai/oracle/justice#specimen-0001-universal-justice", system_name=specimen["system_name"], justice_score_100=audit["total_score_100"], justice_laws_verified=audit["justice_laws_verified"], fil_dor_laws_verified=audit["fil_dor_laws_verified"], min_impact_ratio_rational=audit["min_impact_ratio_q"], counterfactual_effort_cost_rational=audit["recourse_effort_cost_q"], ville_global_peak_e_rational=audit["ville_global_peak_e_value_q"], incident_statutory_deadline_seconds=audit["incident_statutory_deadline_seconds"], included_training_datasets_count=audit["included_training_datasets_count"], training_lineage_merkle_root_hex=audit["training_lineage_merkle_root"], iso42001_pdca_verified=audit["iso42001_pdca_verified"], rule14_zero_knowledge=rings["ring_iv_ab2013_tdmrep_lineage_and_six_folio_cascade"]["passed"], eu_ai_act_art50_disclosed=specimen["eu_ai_act_art50_disclosed"], cost_zero_stop=specimen["cost_zero_stop_policy"], merkle_root_hex=audit["decision_commitment"]["root_hash"], revocation_root_hex=sth_smt.root_hash, signer=vc_signer, issuance_date_utc="2026-11-26T00:00:00Z", valid_until_utc="2027-11-26T00:00:00Z", serial_id=serial, ) def _verify(cred: Any) -> VerifiedCredential: return verify_universal_justice_credential( cred, trusted_jwks=jwks, trusted_status_sth=sth_smt, status_proof=status_proof, now=now_dt ) vc_ok = _verify(vc).alg == "ES256" forged_claims = copy.deepcopy(vc["vc"]) forged_claims["credentialSubject"]["universalJusticeScore100"] = 0 head_b64, _payload_b64, sig_b64 = vc["compact_jws"].split(".") forged_payload = jcs_canonical_bytes(forged_claims) tampered = f"{head_b64}.{b64url_encode(forged_payload)}.{sig_b64}" vc_tamper_killed = bool( vc_ok and _raises_on_verify(lambda: _verify(tampered)) and _raises_on_verify(lambda: _verify(_high_s_twin(vc["compact_jws"]))) ) mutants = dict(core_report["mutant_results"]) mutants["mutant_8_rule14_humble_crystal_revocation_and_w3c_vc_low_s"] = bool( mutants.pop("mutant_8_rule14_humble_crystal_and_revocation_cascade") and vc_tamper_killed ) killed = sum(1 for ok in mutants.values() if ok) zero_forbidden_ok = bool( core_report["zero_forbidden_digits_verified"] and _FORBIDDEN_DIGITS.encode("ascii") not in jcs_canonical_bytes(audit) ) elapsed_us = (time.perf_counter_ns() - t0) // 1000 return { "folio_id": FOLIO_X_ID, "spec": UNIVERSAL_JUSTICE_SPEC_VERSION, "canonical_min_impact_ratio_q": audit["min_impact_ratio_q"], "canonical_recourse_cost_q": audit["recourse_effort_cost_q"], "specimen_verified": specimen_ok, "w3c_vc_verified": vc_ok, "mutants_total": 8, "mutants_killed": killed, "all_mutants_killed": killed == 8, "mutant_matrix": mutants, "all_invariants_verified": bool(specimen_ok and vc_ok and killed == 8 and zero_forbidden_ok), "elapsed_us": elapsed_us, } if __name__ == "__main__": print(json.dumps(run_folio_x_self_test(), indent=2, ensure_ascii=False))