# SPDX-FileCopyrightText: 2026 David Porto Baraldés (Homo Universalis / Viveka) # SPDX-License-Identifier: Apache-2.0 """ Living Folio IX of Leonardo da Vinci (`logic/engines/sovereign_barycenter_crucible.py`): HU-SOVEREIGN-BARYCENTER v1.0 — The `(0, 0, 0)` Central Barycenter of the Stella Octangula: Maliciously-Detected Symbiotic Human-AI Multiparty Computation, Homomorphic Prime-Subgroup Bivariate BGW VSS & Asymmetric Wang-Guy-Davenport Rational Reconstruction Notary. 1. Q1 — Certified Prime Tower, Antipodal Omega_8 <-> Q^3 Bijection & Symbiotic Quorum: - 128-bit Proth prime field `F_p` (`p = 231 * 2^120 + 1`) and 2048-bit exact Pocklington prime chain (`R_1 -> R_2 -> R_3 -> Q`) hosting prime-order-`p` NUMS subgroup `G_p`, - Quadruple Barycenter Identity at `(0, 0, 0)` and mandatory `|S| >= 5` Human-AI symbiotic quorum (`>= 1` AI Creator in `{1,3,5,7}` & `>= 1` Human Guardian in `{2,4,6,8}`, EU AI Act Art. 14). 2. Q2/Q3 — Shannon 4-Private Symmetric Bivariate BGW VSS & Damgard-Nielsen G_p^5 Sacrifice: - Symmetric `5x5` bivariate polynomials (`15` free coefficients, unconditional 4-privacy), - Deterministic `RFC 6962` JCS pre-sacrifice commitment root, disjoint Beaver `triple_id`s, and Fiat-Shamir `Damgard-Nielsen` sacrifice (`tau(0) == 0`, soundness `< 2^-127.85` per `MUL`). 3. Q4/Q5 — Zero-Origin Output Blinding, `[8, 5, 4]_p` Spectral Shield & Zero-Knowledge Hygiene: - `K_m0[0] == H^r_m0_0` blinding, mandatory `"strict_abort"` catching 100% of 1-, 2-, and 3-seat corruptions (`d_min = 4`, EU AI Act Art. 15), and fail-closed rejection of raw secrets / Rule 14 PII. 4. Q6 — Canonical Rational DAG Bound Propagation & Asymmetric Wang-Guy-Davenport Reconstruction: - Zero IEEE-754 floats, strict pre-reconstruction gate `2 * max(1, B_num) * B_den < p`, and exact signed rational recovery in `fractions.Fraction`. 5. Q7 — Five-Folio V..IX Veto Cascade, RFC 6962 Commitment, IEEE 7001 & W3C VC 2.0 `MaatSovereignBarycenterCredential` (`vc+jwt`, JOSE ES256 canonical low-S, SMT-256). Honest scope (`WO-13`): stateless algorithmic and cryptographic multiparty transcript SELF-ASSESSMENT. Hiding/4-privacy are information-theoretically unconditional; `zk_public_transcript` binding is computational under the 2048-bit `F_Q^*` discrete logarithm and SHA-256. Does not prove physical multi-host hardware isolation when one client generates all shares locally; not a certified FIPS 140-3 HSM, not binding GDPR Chapter V / China CAC legal counsel, and not ISO 10218 / CE 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.barycenter.sovereign_barycenter_core import ( BARYCENTER_WEIGHTING, BYZANTINE_SYNDROME_ABORT, COST_ZERO_STOP, HUMAN_GUARDIAN_SEATS, HUMAN_QUORUM_VETO, PROTH_P, S_CANONICAL, BarycenterArithmeticCircuit, BarycenterCircuitGate, BarycenterRevocationRegistry, BeaverSacrificeAbortError, BeaverTripleReuseError, ByzantineSyndromeAbortError, CircuitBoundOverflowError, HomomorphicCommitmentMismatchError, RationalReconstructionError, RawSecretLeakError, SessionRevokedError, SovereignBarycenterError, SymbioticQuorumError, build_canonical_barycenter_circuit, build_canonical_barycenter_specimen, execute_barycenter_mpc, fraction_to_str, int_to_hex, rule14_mask_barycenter_text, run_self_tests as run_core_self_tests, verify_barycenter_transcript, verify_pocklington_chain, verify_proth_prime_p, ) from logic.barycenter.temple_folio_ix_adapter import ( TempleSovereignBarycenterCoordinator, barycenter_transcript_to_verified_knowledge_envelope, ) 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.robotics.embodied_edge_core import scan_forbidden_telemetry, strict_bool, to_fraction __all__ = [ "BARYCENTER_ASSURANCE_TEXT", "BARYCENTER_DECISION_LOG_ID", "BARYCENTER_INTERRUPTIONS", "BARYCENTER_LAWS", "BARYCENTER_REGULATORY_SCOPE", "FOLIO_IX_ID", "IEEE_7001_AUDIENCES", "MAAT_SOVEREIGN_BARYCENTER_CREDENTIAL_TYPE", "RING_WEIGHTS", "SOVEREIGN_BARYCENTER_SPEC_VERSION", "audit_sovereign_barycenter_mpc", "build_sovereign_barycenter_ieee7001_explanations", "get_canonical_sovereign_barycenter_specimen", "get_sovereign_barycenter_regulatory_boundary", "issue_w3c_sovereign_barycenter_credential", "run_folio_ix_self_test", "verify_sovereign_barycenter_credential", ] # ============================================================================ # SECTION 0 — IDENTITY, HONEST SCOPE & CONSTANTS (ZERO FLOAT) # ============================================================================ FOLIO_IX_ID: Final[str] = "folio-IX-sovereign-barycenter-mpc-quorum" SOVEREIGN_BARYCENTER_SPEC_VERSION: Final[str] = "HU-SOVEREIGN-BARYCENTER/v1.0" BARYCENTER_LAWS: Final[tuple[str, ...]] = ("Q1", "Q2", "Q3", "Q4", "Q5", "Q6", "Q7") MAAT_SOVEREIGN_BARYCENTER_CREDENTIAL_TYPE: Final[str] = "MaatSovereignBarycenterCredential" BARYCENTER_DECISION_LOG_ID: Final[str] = "hu-sovereign-barycenter-commitment-2026" BARYCENTER_REGULATORY_SCOPE: Final[str] = ( "stateless_multiparty_bgw_mpc_quorum_self_assessment_not_physical_isolation_proof_not_hsm_not_legal_advice" ) BARYCENTER_ASSURANCE_TEXT: Final[str] = ( "self-assessed algorithmic and cryptographic conformity of 8-seat Stella Octangula Bivariate BGW " "multiparty computation, Human-AI symbiotic quorum (EU AI Act Art. 14), Damgard-Nielsen G_p^5 sacrifice, " "[8, 5, 4]_p Byzantine spectral shield and exact Wang-Guy-Davenport rational reconstruction; " "not proof of physical multi-host hardware isolation, not a certified FIPS 140-3 HSM, not binding " "cross-border data-transfer legal advice and not a safety-rated function; recompute independently" ) BARYCENTER_INTERRUPTIONS: Final[tuple[str, ...]] = ( "none", "human_quorum_veto", "byzantine_syndrome_abort", "cost_zero_stop", ) PROTH_PRIME_HEX: Final[str] = int_to_hex(PROTH_P) SPECTRAL_MINIMUM_DISTANCE: Final[int] = 4 _REGULATORY_BOUNDARY: Final[dict[str, Any]] = { "covered_by_this_self_assessment": [ "EU AI Act (EU) 2024/1689 Art. 14 human oversight: valid >= 5-of-8 quorums intersect both odd AI Creator seats {1,3,5,7} and even Human Guardian seats {2,4,6,8}", "EU AI Act Art. 15 robustness & cybersecurity: [8, 5, 4]_p spectral syndrome strict_abort detects 100% of 1-, 2-, and 3-seat corruptions and Damgard-Nielsen sacrifice detects poisoned Beaver triples (< 2^-127.85)", "EU AI Act Art. 50(1) transparency & IEEE 7001-2021: explicit AI notary disclosure and descriptive explanations for five stakeholder audiences", "GDPR Art. 5(1)(c) & Art. 25 privacy by design + Rule 14 Zero-Knowledge: zk_public_transcript mode exposes 0.000000 bits of Shannon information on private inputs (c_levels = 1)", "Unconditional vs computational boundary: 4-privacy over F_p and homomorphic commitment hiding in G_p are unconditional; non-interactive Mode-A binding is computational under 2048-bit F_Q^* discrete log and SHA-256", ], "outside_this_self_assessment": [ "Physical multi-party host/network isolation when a single client generates all shares locally in simulation", "Hardware cryptographic module certification (FIPS 140-3 / Common Criteria)", "Binding legal opinions on cross-border data transfers (GDPR Chapter V, China CAC PIPL, HIPAA BAA)", "Physical machinery safety certification: ISO 10218, ISO 13482, ISO/TS 15066, Regulation (EU) 2023/1230", ], "safety_rated_function": False, "certified_hardware_security_module": False, "physical_multi_host_isolation_proven": False, "legal_data_transfer_counsel": False, "clinical_or_medical_device": False, } RING_WEIGHTS: Final[dict[str, Fraction]] = { "ring_i_proth_pocklington_and_quadruple_barycenter": Fraction(1, 4), "ring_ii_bivariate_bgw_vss_and_homomorphic_sacrifice": Fraction(1, 5), "ring_iii_spectral_byzantine_shield_and_zk_hygiene": Fraction(1, 5), "ring_iv_exact_wgd_rational_and_five_folio_veto_cascade": Fraction(1, 5), "ring_v_rfc6962_ieee7001_eu_ai_act_w3c_vc": Fraction(3, 20), } _CANONICAL_BARYCENTER_SPECIMEN: Final[dict[str, Any]] = { "council_name": "Homo Universalis Barycenter Council", "agent_domain": "homouniversalis.ai", "quorum_seats": [1, 2, 3, 4, 7], "diag_active": 2, "input_x0_q": "3/4", "input_x1_q": "5/6", "input_x2_q": "2/5", "fault_policy": "strict_abort", "transcript_privacy_mode": "zk_public_transcript", "corrupt_seat_count": 0, "reuse_beaver_triple": False, "poison_beaver_sacrifice": False, "inject_raw_secret_in_zk": False, "public_note": "Living Folio IX: 4-party symbiotic resource & clinical consensus", "downstream_disclosure_text": "I am an AI cryptographic notary. Consensus output 91/120 verified at (0, 0, 0) with 0 private inputs exposed.", "eu_ai_act_art50_disclosed": True, "interruption": "none", "actor_guardian_seat": 2, "cost_zero_stop_policy": True, "budget_b": 250, "telemetry_fields": {"quorum_size": 5, "mul_gates": 1}, } def _qs(value: Fraction) -> str: return fraction_to_str(value) def get_canonical_sovereign_barycenter_specimen() -> dict[str, Any]: """Deep copy of Canonical Specimen #0001 ('(3/4 + 5/6) * 2/5 + 1/8 == 91/120' across S_CANONICAL).""" return copy.deepcopy(_CANONICAL_BARYCENTER_SPECIMEN) def get_sovereign_barycenter_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_sovereign_barycenter_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")) out_q = summary.get("reconstructed_output", "91/120") q_cnt = summary.get("quorum_seats_count", 5) if lang == "es": companion = "Soy un sistema de inteligencia artificial, no una persona. " + ( "Se ha detenido la decisión colectiva sin revelar ningún secreto privado y llevando el movimiento a cero exacto." if halted else f"El quórum simbiótico humano-IA ({q_cnt}/8 asientos) verificó el resultado racional exacto ({out_q}) sin exponer entradas privadas." ) elif lang == "en": companion = "I am an artificial intelligence system, not a person. " + ( "The collective computation halted cleanly with zero private inputs exposed and motion set to an exact zero." if halted else f"The human-AI symbiotic quorum ({q_cnt}/8 seats) verified the exact rational result ({out_q}) with zero private inputs exposed." ) else: companion = "Soc un sistema d'intel·ligència artificial, no una persona. " + ( "S'ha aturat la decisió col·lectiva sense exposar cap secret privat i portant el moviment al zero exacte." if halted else f"El quòrum simbiòtic humà-IA ({q_cnt}/8 seients) ha verificat el resultat racional exacte ({out_q}) sense exposar cap dada privada." ) return { "companion_human": companion, "bystander_public": ( f"Stateless multiparty consensus notary under the {SOVEREIGN_BARYCENTER_SPEC_VERSION} self-assessment; " f"quorum_seats_count={q_cnt}; privacy_mode={summary.get('transcript_privacy_mode')}; interruption={summary.get('interruption')}." ), "safety_engineer": ( f"proth_p_verified={summary.get('proth_p_verified')}; pocklington_2048_verified={summary.get('pocklington_verified')}; " f"sacrifice_verified={summary.get('sacrifice_verified')}; spectral_d_min={SPECTRAL_MINIMUM_DISTANCE}; " f"q3_zero_twist_on_veto={summary.get('q3_zero_twist_on_veto')}; supervisory cryptographic software, not a safety-rated function or HSM." ), "incident_investigator": ( f"pre_sacrifice_commitment_root={summary.get('pre_sacrifice_root')}; decision_commitment_root={summary.get('commitment_root')}; " "every commitment leaf is RFC 6962 domain-separated (0x00/0x01) under Rule 14 with c_levels=1 zero-origin blinding." ), "expert_witness_regulator": ( "Self-assessed alignment with EU AI Act Art. 14 human-AI quorum oversight, Art. 15 Byzantine robustness, " "Art. 50(1) AI disclosure, IEEE 7001-2021 five-audience explainability and GDPR Art. 25 data minimisation; " "not legal data-transfer advice, not physical host-isolation certification and not a FIPS 140-3 HSM." ), } 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"{SOVEREIGN_BARYCENTER_SPEC_VERSION}:{BARYCENTER_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": BARYCENTER_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 THE SOVEREIGN BARYCENTER # ============================================================================ _PROTH_BOOT_VERIFIED: Final[bool] = verify_proth_prime_p() _POCKLINGTON_BOOT_VERIFIED: Final[bool] = verify_pocklington_chain() def audit_sovereign_barycenter_mpc( *, council_name: str = "Homo Universalis Barycenter Council", agent_domain: str = "homouniversalis.ai", quorum_seats: Sequence[int] | None = None, diag_active: int = 2, input_x0_q: Any = "3/4", input_x1_q: Any = "5/6", input_x2_q: Any = "2/5", transcript: Mapping[str, Any] | None = None, fault_policy: str = "strict_abort", transcript_privacy_mode: str = "zk_public_transcript", corrupt_seat_count: int = 0, reuse_beaver_triple: bool = False, poison_beaver_sacrifice: bool = False, inject_raw_secret_in_zk: bool = False, public_note: str = "Living Folio IX: 4-party symbiotic resource & clinical consensus", downstream_disclosure_text: str = "I am an AI cryptographic notary. Consensus output 91/120 verified at (0, 0, 0) with 0 private inputs exposed.", 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 or verify one deterministic 8-seat Stella Octangula Bivariate BGW MPC quorum scenario across the Five Sovereign Barycenter Rings (`Q1..Q7`). """ for label, val in ( ("council_name", council_name), ("agent_domain", agent_domain), ("fault_policy", fault_policy), ("transcript_privacy_mode", transcript_privacy_mode), ("public_note", public_note), ("downstream_disclosure_text", downstream_disclosure_text), ): if not isinstance(val, str): raise TypeError(f"{label} must be a str.") if not council_name.strip(): raise ValueError("council_name must not be empty.") if interruption not in BARYCENTER_INTERRUPTIONS: raise ValueError(f"interruption must be one of {list(BARYCENTER_INTERRUPTIONS)}.") if fault_policy not in ("strict_abort", "pinpoint_1_abort_2"): raise ValueError("fault_policy must be 'strict_abort' or 'pinpoint_1_abort_2'.") if transcript_privacy_mode not in ("zk_public_transcript", "diagnostic_audit_only"): raise ValueError("transcript_privacy_mode must be 'zk_public_transcript' or 'diagnostic_audit_only'.") if isinstance(diag_active, bool) or not isinstance(diag_active, int) or diag_active not in (1, 2, 3, 4): raise ValueError("diag_active must be a strict integer in 1..4.") if isinstance(corrupt_seat_count, bool) or not isinstance(corrupt_seat_count, int) or not (0 <= corrupt_seat_count <= 8): raise ValueError("corrupt_seat_count must be a strict integer in 0..8.") if isinstance(actor_guardian_seat, bool) or not isinstance(actor_guardian_seat, int) or not (1 <= actor_guardian_seat <= 8): raise ValueError("actor_guardian_seat must be a strict integer in 1..8.") if isinstance(budget_b, bool) or not isinstance(budget_b, int) or not (1 <= budget_b <= 10_000): raise ValueError("budget_b must be a strict integer in [1, 10000].") reuse_flag = strict_bool(reuse_beaver_triple, "reuse_beaver_triple") poison_flag = strict_bool(poison_beaver_sacrifice, "poison_beaver_sacrifice") raw_leak_flag = strict_bool(inject_raw_secret_in_zk, "inject_raw_secret_in_zk") 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") x0_q = to_fraction(input_x0_q, field="input_x0_q") x1_q = to_fraction(input_x1_q, field="input_x1_q") x2_q = to_fraction(input_x2_q, field="input_x2_q") seats_list = [int(s) for s in (quorum_seats if quorum_seats is not None else S_CANONICAL)] if any(isinstance(s, bool) or not isinstance(s, int) for s in (quorum_seats or S_CANONICAL)): raise TypeError("quorum_seats must contain strict integers.") 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"Q4_E4_forbidden_telemetry:{k}" for k in forbidden_telemetry) q1_ok = False q2_ok = False q3_ok = False q4_ok = False q5_ok = False q6_ok = False reconstructed_out_str = "0" spatial_bary_out = ["0", "0", "0"] pre_sac_root_hex = "0" * 64 circuit_sha_hex = "0" * 64 vke_id = "" pinpointed_faults: list[dict[str, Any]] = [] rev_reg = BarycenterRevocationRegistry() try: if transcript is not None: tx_to_verify: dict[str, Any] = copy.deepcopy(dict(transcript)) else: seed_bytes = hashlib.sha256( f"HU-FOLIO-IX-AUDIT:{council_name}:{x0_q}:{x1_q}:{x2_q}:{diag_active}".encode("utf-8") ).digest() if reuse_flag: dup_circ = BarycenterArithmeticCircuit( "dup-audit-circuit", ( BarycenterCircuitGate(0, "INPUT", input_index=0, bound_num=max(4, abs(x0_q.numerator)), bound_den=max(4, x0_q.denominator)), BarycenterCircuitGate(1, "MUL", left=0, right=0, triple_id="reused-tid-0"), BarycenterCircuitGate(2, "MUL", left=1, right=0, triple_id="reused-tid-0"), ), 2, ) tx_to_verify = execute_barycenter_mpc( dup_circ, [x0_q], seed=seed_bytes, quorum_seats=seats_list, diag_active=diag_active, mode=transcript_privacy_mode, # type: ignore[arg-type] public_note=public_note, ) else: circ = build_canonical_barycenter_circuit((x0_q, x1_q, x2_q)) tx_to_verify = execute_barycenter_mpc( circ, (x0_q, x1_q, x2_q), seed=seed_bytes, quorum_seats=seats_list, diag_active=diag_active, mode=transcript_privacy_mode, # type: ignore[arg-type] public_note=public_note, ) if poison_flag: tau_y = list(tx_to_verify["mul_proofs"][0]["tau_opening"]["y8"]) tau_y[0] = int_to_hex((int(tau_y[0], 16) + 1) % PROTH_P) # Shift all 8 shares by +1 so degree <= 4 holds while tau(0) becomes 1 != 0 tx_to_verify["mul_proofs"][0]["tau_opening"]["y8"] = [ int_to_hex((int(h, 16) + 1) % PROTH_P) for h in tx_to_verify["mul_proofs"][0]["tau_opening"]["y8"] ] if corrupt_seat_count > 0: corrupted = list(tx_to_verify["final_opening"]["y8"]) for idx_c in range(min(8, corrupt_seat_count)): corrupted[idx_c] = int_to_hex((int(corrupted[idx_c], 16) + 701 + idx_c) % PROTH_P) tx_to_verify["final_opening"]["y8"] = corrupted if raw_leak_flag: tx_to_verify["raw_private_inputs"] = [_qs(x0_q), _qs(x1_q), _qs(x2_q)] sid = str(tx_to_verify.get("session_id") or "folio-ix-audit-session") rev_reg.register_session(sid) if interruption in ("human_quorum_veto", "byzantine_syndrome_abort", "cost_zero_stop"): sig_map = { "human_quorum_veto": HUMAN_QUORUM_VETO, "byzantine_syndrome_abort": BYZANTINE_SYNDROME_ABORT, "cost_zero_stop": COST_ZERO_STOP, } rev_reg.revoke_session( sid, sig_map[interruption], actor_seat=actor_guardian_seat if interruption == "human_quorum_veto" else None, detail="Audit interruption signal", ) ver_res = verify_barycenter_transcript( tx_to_verify, mode=transcript_privacy_mode, # type: ignore[arg-type] fault_policy=fault_policy, # type: ignore[arg-type] revocation_registry=rev_reg, ) reconstructed_out_str = str(ver_res["reconstructed_output"]) spatial_bary_out = list(ver_res["spatial_barycenter_q3"]) pre_sac_root_hex = str(ver_res["pre_sacrifice_commitment_root"]) circuit_sha_hex = str(ver_res["circuit_jcs_sha256"]) pinpointed_faults = list(ver_res["pinpointed_faults"]) seats_list = [int(s) for s in tx_to_verify["quorum_seats"]] if transcript_privacy_mode == "zk_public_transcript" and fault_policy == "strict_abort": vke = barycenter_transcript_to_verified_knowledge_envelope( tx_to_verify, revocation_registry=rev_reg, source_level=2, ) vke_id = vke.envelope_id ver_ok = bool(ver_res["verified"] and _PROTH_BOOT_VERIFIED and _POCKLINGTON_BOOT_VERIFIED) q1_ok = bool(ver_ok and ver_res["quadruple_identity_verified"]) q2_ok = bool(ver_ok and len(pre_sac_root_hex) == 64) q3_ok = bool(ver_ok and len(circuit_sha_hex) == 64) q4_ok = bool(ver_ok and transcript_privacy_mode == "zk_public_transcript" and not forbidden_telemetry) q5_ok = bool(ver_ok and fault_policy == "strict_abort" and len(pinpointed_faults) == 0) q6_ok = bool(ver_ok) if transcript_privacy_mode != "zk_public_transcript": violations.append("Q4_diagnostic_mode_not_eligible_for_public_credential") if fault_policy != "strict_abort": violations.append("Q5_non_strict_fault_policy_not_eligible_for_public_credential") except SymbioticQuorumError as exc: violations.append(f"Q1_symbiotic_quorum_rejected:{rule14_mask_barycenter_text(str(exc))}") except BeaverTripleReuseError as exc: violations.append(f"Q3_beaver_triple_reuse_blocked:{rule14_mask_barycenter_text(str(exc))}") except BeaverSacrificeAbortError as exc: violations.append(f"Q3_beaver_sacrifice_aborted:{rule14_mask_barycenter_text(str(exc))}") except ByzantineSyndromeAbortError as exc: violations.append(f"Q5_byzantine_syndrome_aborted:{rule14_mask_barycenter_text(str(exc))}") except RawSecretLeakError as exc: violations.append(f"Q4_raw_secret_or_pii_blocked:{rule14_mask_barycenter_text(str(exc))}") except (CircuitBoundOverflowError, RationalReconstructionError) as exc: violations.append(f"Q6_rational_bound_or_wgd_rejected:{rule14_mask_barycenter_text(str(exc))}") except SessionRevokedError as exc: violations.append(f"Q7_session_revoked:{rule14_mask_barycenter_text(str(exc))}") except (HomomorphicCommitmentMismatchError, SovereignBarycenterError, ValueError, TypeError) as exc: violations.append(f"Q2_or_transcript_rejected:{rule14_mask_barycenter_text(str(exc))}") masked_disc = sanitize_three_rings_zk( rule14_mask_barycenter_text(downstream_disclosure_text), today_utc_date=today_utc_date ) residual_pii = int(masked_disc["total_redactions"]) # Independent Five-Folio (V + VI + VII + VIII + IX) veto / abort cascade probe coord = TempleSovereignBarycenterCoordinator(lang=lang_norm, clock_ms=lambda: 1000) coord.body.on_human_pose(("6/5", "0", "0")) coord.body.on_vulnerable_presence(False) coord.register_barycenter_session("probe-barycenter-root") coord.register_barycenter_session("probe-barycenter-child", parent_session_id="probe-barycenter-root") probe_sig = ( COST_ZERO_STOP if interruption == "cost_zero_stop" else (BYZANTINE_SYNDROME_ABORT if interruption == "byzantine_syndrome_abort" else HUMAN_QUORUM_VETO) ) probe_seat = actor_guardian_seat if actor_guardian_seat in HUMAN_GUARDIAN_SEATS else 2 veto_cascade = coord.trigger_barycenter_veto_or_abort_cascade( signal_kind=probe_sig, actor_seat=probe_seat, note="Barycenter sanctuary probe VVK-1234-5678", ) probe_child_revoked = coord.barycenter_revocation_registry.is_revoked("probe-barycenter-child") cascade_ok = bool( policy and residual_pii == 0 and veto_cascade["q3_zero_twist_enforced"] and veto_cascade["levels_cancelled"] == [1, 2, 3] and probe_child_revoked and "VVK-1234" not in veto_cascade["note_masked"] ) if not policy: violations.append("Q7_cost_zero_stop_policy_disabled") shield = audit_cognitive_sovereignty( downstream_disclosure_text, budget_B=budget_b, 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(q1_ok) ring_ii = bool(q2_ok and q3_ok) ring_iii = bool(q4_ok and q5_ok) ring_iv = bool(q6_ok and cascade_ok and shield_non_l7_ok) commitment = _commit_run_rfc6962( { "spec": SOVEREIGN_BARYCENTER_SPEC_VERSION, "council_name": rule14_mask_barycenter_text(council_name), "pre_sacrifice_commitment_root": pre_sac_root_hex, "reconstructed_output": reconstructed_out_str, "rings_pre_v": {"i": ring_i, "ii": ring_ii, "iii": ring_iii, "iv": ring_iv}, } ) summary_for_ieee = { "reconstructed_output": reconstructed_out_str, "quorum_seats_count": len(seats_list), "transcript_privacy_mode": transcript_privacy_mode, "interruption": interruption, "halted_or_vetoed": (interruption != "none") or (not (ring_i and ring_ii and ring_iii and ring_iv)), "proth_p_verified": _PROTH_BOOT_VERIFIED, "pocklington_verified": _POCKLINGTON_BOOT_VERIFIED, "sacrifice_verified": q3_ok, "q3_zero_twist_on_veto": veto_cascade["q3_zero_twist_enforced"], "pre_sacrifice_root": pre_sac_root_hex, "commitment_root": commitment["root_hash"], } explanations = build_sovereign_barycenter_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("Q7_eu_ai_act_art50_not_disclosed") q7_ok = bool( 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(art50_flag and explanations_complete and commitment["inclusion_self_check_passed"]) rings_passed = { "ring_i_proth_pocklington_and_quadruple_barycenter": ring_i, "ring_ii_bivariate_bgw_vss_and_homomorphic_sacrifice": ring_ii, "ring_iii_spectral_byzantine_shield_and_zk_hygiene": ring_iii, "ring_iv_exact_wgd_rational_and_five_folio_veto_cascade": ring_iv, "ring_v_rfc6962_ieee7001_eu_ai_act_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 = { "Q1": q1_ok, "Q2": q2_ok, "Q3": q3_ok, "Q4": q4_ok, "Q5": q5_ok, "Q6": q6_ok, "Q7": q7_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_proth_pocklington_and_quadruple_barycenter"].update( { "proth_prime_hex": PROTH_PRIME_HEX, "pocklington_modulus_bits": 2048, "quorum_seats": seats_list, "spatial_barycenter_q3": spatial_bary_out, } ) rings_out["ring_ii_bivariate_bgw_vss_and_homomorphic_sacrifice"].update( { "pre_sacrifice_commitment_root": pre_sac_root_hex, "circuit_jcs_sha256": circuit_sha_hex, "bivariate_individual_degree_max": 4, "free_polynomial_parameters": 15, } ) rings_out["ring_iii_spectral_byzantine_shield_and_zk_hygiene"].update( { "spectral_minimum_distance": SPECTRAL_MINIMUM_DISTANCE, "fault_policy": fault_policy, "transcript_privacy_mode": transcript_privacy_mode, "pinpointed_faults": pinpointed_faults, "forbidden_telemetry_keys": forbidden_telemetry, } ) rings_out["ring_iv_exact_wgd_rational_and_five_folio_veto_cascade"].update( { "reconstructed_barycenter_rational": reconstructed_out_str, "folio_vi_verified_knowledge_envelope_id": vke_id, "q3_zero_twist_on_veto": veto_cascade["q3_zero_twist_enforced"], "veto_propagation_latency_ns": int(veto_cascade["propagation_latency_ns"]), } ) return { "schema_version": SOVEREIGN_BARYCENTER_SPEC_VERSION, "folio_id": FOLIO_IX_ID, "self_assessment": True, "assurance": BARYCENTER_ASSURANCE_TEXT, "regulatory_scope": BARYCENTER_REGULATORY_SCOPE, "regulatory_boundary": get_sovereign_barycenter_regulatory_boundary(), "council_name": rule14_mask_barycenter_text(council_name), "agent_domain": rule14_mask_barycenter_text(agent_domain), "quorum_seats": seats_list, "quorum_seats_count": len(seats_list), "diag_active": diag_active, "barycenter_weighting": BARYCENTER_WEIGHTING, "spatial_barycenter_q3": spatial_bary_out, "proth_prime_hex": PROTH_PRIME_HEX, "spectral_minimum_distance": SPECTRAL_MINIMUM_DISTANCE, "transcript_privacy_mode": transcript_privacy_mode, "fault_policy": fault_policy, "interruption": interruption, "reconstructed_barycenter_rational": reconstructed_out_str, "pre_sacrifice_commitment_root": pre_sac_root_hex, "circuit_jcs_sha256": circuit_sha_hex, "folio_vi_verified_knowledge_envelope_id": vke_id, "five_barycenter_rings": rings_out, "exact_rational_score": _qs(exact_total), "total_score_100": score_100, "sovereign_barycenter_grade": _grade_for(score_100), "passes_internal_barycenter_criteria": bool(all(rings_passed.values()) and q7_ok), "barycenter_laws_status": laws_status, "barycenter_laws_verified": [law for law in BARYCENTER_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 `MaatSovereignBarycenterCredential` # ============================================================================ 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_sovereign_barycenter_credential( *, council_id: str, council_name: str, barycenter_score_100: int, barycenter_laws_verified: Sequence[str], fil_dor_laws_verified: Sequence[str], symbiotic_quorum_verified: bool, quorum_seats_count: int, homomorphic_sacrifice_verified: bool, zero_float_rational_verified: bool, transcript_privacy_mode: str, reconstructed_barycenter_rational: str, 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 `MaatSovereignBarycenterCredential` (also typed `MaatHumanDignityCredential` so the Folio IV verifier policy applies) as a VC-JOSE-COSE compact JWS (`typ: vc+jwt`, ES256 low-S, JCS). """ if isinstance(barycenter_score_100, bool) or not isinstance(barycenter_score_100, int) or not (0 <= barycenter_score_100 <= 100): raise ValueError("barycenter_score_100 must be an integer in [0, 100].") if isinstance(quorum_seats_count, bool) or not isinstance(quorum_seats_count, int) or not (5 <= quorum_seats_count <= 8): raise ValueError("quorum_seats_count must be an integer in [5, 8].") for label, val in ( ("council_id", council_id), ("council_name", council_name), ("transcript_privacy_mode", transcript_privacy_mode), ("reconstructed_barycenter_rational", reconstructed_barycenter_rational), ): if not isinstance(val, str) or not val.strip(): raise ValueError(f"{label} must be a non-empty string.") if transcript_privacy_mode != "zk_public_transcript": raise ValueError("Public credentials require transcript_privacy_mode == 'zk_public_transcript'.") rec_q = to_fraction(reconstructed_barycenter_rational, field="reconstructed_barycenter_rational") for label, flag in ( ("symbiotic_quorum_verified", symbiotic_quorum_verified), ("homomorphic_sacrifice_verified", homomorphic_sacrifice_verified), ("zero_float_rational_verified", zero_float_rational_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) q_laws = [str(x) for x in barycenter_laws_verified] if any(law not in BARYCENTER_LAWS for law in q_laws): raise ValueError("barycenter_laws_verified must only contain Q1..Q7.") if not isinstance(signer, CredentialSigner): raise TypeError("signer must implement the CredentialSigner protocol (asymmetric ES256).") if isinstance(max_lifetime_days, bool) or not isinstance(max_lifetime_days, int) or max_lifetime_days <= 0: raise ValueError("max_lifetime_days must be a positive integer.") for root_label, root_hex in ( ("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_lifetime_days) ) if valid_until_dt <= valid_from_dt or valid_until_dt - valid_from_dt > timedelta(days=max_lifetime_days): raise ValueError("Invalid credential validity window.") if credential_uuid is not None: vc_uuid_obj = uuid.UUID(str(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-SBC-{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_SOVEREIGN_BARYCENTER_CREDENTIAL_TYPE], "issuer": { "id": "did:web:homouniversalis.ai", "name": "Homo Universalis — Viveka (Ma'at Sovereign Notary)", "notaryFolio": "https://homouniversalis.ai/oracle/barycenter", }, "validFrom": _format_rfc3339_utc(valid_from_dt), "validUntil": _format_rfc3339_utc(valid_until_dt), "credentialStatus": { "id": f"https://homouniversalis.ai/oracle/barycenter#status-{effective_serial}", "type": "HUSparseMerkleStatus2026", "statusLog": MAAT_SMT_REVOCATION_LOG_ID, "serialId": effective_serial, }, "credentialSubject": { "id": council_id.strip(), "name": council_name.strip(), "barycenterSpec": SOVEREIGN_BARYCENTER_SPEC_VERSION, "sovereignBarycenterScore100": barycenter_score_100, "barycenterLawsVerified": q_laws, "lawsVerified": [str(x) for x in fil_dor_laws_verified], "c_levels": 1, "cost_zero_stop": cost_zero_stop, "symbioticQuorumVerified": symbiotic_quorum_verified, "quorumSeatsCount": quorum_seats_count, "prothPrimeHex": PROTH_PRIME_HEX, "spectralMinimumDistance": SPECTRAL_MINIMUM_DISTANCE, "homomorphicSacrificeVerified": homomorphic_sacrifice_verified, "zeroFloatRationalVerified": zero_float_rational_verified, "transcriptPrivacyMode": transcript_privacy_mode, "reconstructedBarycenterRational": _qs(rec_q), "barycenterWeightingScheme": BARYCENTER_WEIGHTING, "rule14ZeroKnowledge": rule14_zero_knowledge, "aiIdentityDisclosed": eu_ai_act_art50_disclosed, "hardwareSecurityModuleClaimed": False, "regulatoryScope": BARYCENTER_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_sovereign_barycenter_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 `MaatSovereignBarycenterCredential`: full Folio IV policy (ES256, issuer, validity, signed SMT-256 status) plus Folio IX invariants (type, honest scope, Q1..Q7 laws, Art. 14 quorum >= 5, Art. 50 disclosure, no HSM claim). """ 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_SOVEREIGN_BARYCENTER_CREDENTIAL_TYPE not in (claims.get("type") or []): raise MaatCredentialVerificationError( CredentialErrorCode.INVALID_CREDENTIAL_TYPE, "Missing MaatSovereignBarycenterCredential 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("sovereignBarycenterScore100") q_cnt = subj.get("quorumSeatsCount") q_laws = subj.get("barycenterLawsVerified") if ( subj.get("regulatoryScope") != BARYCENTER_REGULATORY_SCOPE or subj.get("barycenterSpec") != SOVEREIGN_BARYCENTER_SPEC_VERSION or isinstance(score, bool) or not isinstance(score, int) or not (0 <= score <= 100) or isinstance(q_cnt, bool) or not isinstance(q_cnt, int) or not (5 <= q_cnt <= 8) or not isinstance(q_laws, list) or any(law not in BARYCENTER_LAWS for law in q_laws) or subj.get("c_levels") != 1 or subj.get("transcriptPrivacyMode") != "zk_public_transcript" or subj.get("aiIdentityDisclosed") is not True or subj.get("hardwareSecurityModuleClaimed") is not False ): raise MaatCredentialVerificationError( CredentialErrorCode.DOMAIN_INVARIANT_VIOLATION, "Sovereign barycenter 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, SovereignBarycenterError): return True return False def run_folio_ix_self_test() -> dict[str, Any]: """ Ephemeral deterministic self-test of Living Folio IX (0 network calls), executing both the standalone pure-stdlib `run_self_tests()` (`8/8` mutants) and the Ma'at W3C VC 2.0 + Five-Folio (V + VI + VII + VIII + IX) symbiotic integration verification. """ t0 = time.perf_counter_ns() core_report = run_core_self_tests() specimen = get_canonical_sovereign_barycenter_specimen() audit = audit_sovereign_barycenter_mpc(**specimen, lang="en") specimen_ok = bool(audit["passes_internal_barycenter_criteria"]) vc_signer = LocalEphemeralSigner(kid="maat-barycenter-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, 25, 12, 0, 0, tzinfo=timezone.utc) serial = "MAAT-SBC-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_barycenter_rings"] vc = issue_w3c_sovereign_barycenter_credential( council_id="https://homouniversalis.ai/oracle/barycenter#specimen-0001-symbiotic-consensus", council_name=specimen["council_name"], barycenter_score_100=audit["total_score_100"], barycenter_laws_verified=audit["barycenter_laws_verified"], fil_dor_laws_verified=audit["fil_dor_laws_verified"], symbiotic_quorum_verified=rings["ring_i_proth_pocklington_and_quadruple_barycenter"]["passed"], quorum_seats_count=audit["quorum_seats_count"], homomorphic_sacrifice_verified=rings["ring_ii_bivariate_bgw_vss_and_homomorphic_sacrifice"]["passed"], zero_float_rational_verified=rings["ring_iv_exact_wgd_rational_and_five_folio_veto_cascade"]["passed"], transcript_privacy_mode=audit["transcript_privacy_mode"], reconstructed_barycenter_rational=audit["reconstructed_barycenter_rational"], rule14_zero_knowledge=rings["ring_iii_spectral_byzantine_shield_and_zk_hygiene"]["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-25T00:00:00Z", valid_until_utc="2027-11-25T00:00:00Z", serial_id=serial, ) def _verify(cred: Any) -> VerifiedCredential: return verify_sovereign_barycenter_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"]["sovereignBarycenterScore100"] = 0 head_b64, _payload_b64, sig_b64 = vc["compact_jws"].split(".") forged_payload = json.dumps(forged_claims, ensure_ascii=False, separators=(",", ":")).encode("utf-8") 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_quorum_veto_and_w3c_vc_low_s"] = bool( mutants.pop("mutant_8_quorum_veto_revocation") and vc_tamper_killed ) killed = sum(1 for ok in mutants.values() if ok) elapsed_us = (time.perf_counter_ns() - t0) // 1000 return { "folio_id": FOLIO_IX_ID, "spec": SOVEREIGN_BARYCENTER_SPEC_VERSION, "canonical_output": audit["reconstructed_barycenter_rational"], "specimen_verified": specimen_ok, "w3c_vc_verified": vc_ok, "proth_pocklington_verified": bool(core_report["proth_prime_verified"] and core_report["pocklington_chain_verified"]), "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 core_report["proth_prime_verified"] and core_report["pocklington_chain_verified"] and core_report["zero_216_verified"] ), "elapsed_us": elapsed_us, } if __name__ == "__main__": print(json.dumps(run_folio_ix_self_test(), indent=2, ensure_ascii=False))