# SPDX-FileCopyrightText: 2026 David Porto Baraldés (Homo Universalis / Viveka) # SPDX-License-Identifier: Apache-2.0 """ Living Folio XI of Leonardo da Vinci (`logic/engines/pacioli_veritas_crucible.py`): HU-VERITAS-PACIOLI-OFFICE v1.0 — Fra Luca Pacioli & Leonardo da Vinci's Agentic Office & Financial Veritas Notary (`De Divina Proportione` & `Summa de Arithmetica`, 1494–2026): 1. V1 — Exact Rational Double-Entry Ledger, Multi-Currency Cocycle & XBRL DAG (`Summa`, 1494): - Zero-float `fractions.Fraction` double-entry balance (`sum(debits) == sum(credits)`), - Arbitrage-free multiplicative FX cocycle (`fx[A] == rate(A->B) * fx[B]`), - Accounting identity `Assets == Liabilities + Opening_Equity + (Revenues - Expenses)`, - Weighted `XBRL Calculation Linkbase v1.1` (`weight in {-1, +1}`) cycle-free DAG roll-up. 2. V2 — Verifiable RAG Citation & Formula Grounding (`可信、可溯源、结果引用` for AI Office): - `RFC 6962` (`0x00` / `0x01`) Merkle grounding over `masked_text_sha256` evidence leaves, - Context-sensitive numeric/accounting `LITERAL_SPAN` boundary guard (blocking `(500)` / `(EUR 500)` loss sign inversions, `.500` / `150.25` truncations, and PII slice overlaps), - Acyclic `SYMBOLIC_DERIVED` (`SUM`, `DIFF`, `MUL`, `DIV`, `GROWTH_RATE`) provenance in Q. 3. V3 — Sovereign Signed Banker's Rounding & Hamilton Largest-Remainder Apportionment: - Exact round-half-to-even (`bankers_round_half_even_int`) and 1-cent-leak-free Hamilton apportionment (`sum(allocated_units) == total_scaled_units`). 4. V4 & V5 — Unified East-West Regulatory Passport (`GB 45438-2025` + `EU AI Act Art. 50(2)` + `TC260 v3.0` Sept 2026 + `PIPL` / `GDPR` Rule 14 Zero-Retention Sanctuary): - Explicit AIGC disclosure + 6-key `RFC 8785` JCS `implicit_metadata_sha256`, - `TC260 v3.0` least-privilege scope containment, `<= 86,400 s` session TTL, and independent human HITL countersignature (`human_approver_id != agent_id`), - Stateless zero-retention sanctuary (`raw_pii_retained == False`) with `ISO 13616` Mod-97 IBAN and `GB 11643-1999` Mod 11-2 CN-ID deterministic masking, `c_levels == 1`, `L <= B`. 5. V6 & V7 — `EU DORA Art. 15` ICT Hash-Chain, `SOX 404` Segregation of Duties, Seven-Folio (`V..XI`) `Twist = 0` Veto Cascade, `IEEE 7001` (`CA`/`ES`/`EN`/`ZH`), & `W3C VC 2.0` `MaatPacioliVeritasCredential` (`vc+jwt`, JOSE `ES256` canonical low-S, `SMT-256`). Honest scope (`WO-13`): stateless mathematical, cryptographic, accounting-invariant, and document grounding SELF-ASSESSMENT. Not a statutory CPA / statutory auditor opinion (`ISA` / `PCAOB` / `CICPA`), not an official `CAC` / `TC260` regulatory filing or `EU AI Act Art. 43` notified-body certification, not binding tax, legal, or investment advice, 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.robotics.embodied_edge_core import scan_forbidden_telemetry from logic.veritas.pacioli_veritas_core import ( COST_ZERO_STOP, HALLUCINATION_GROUNDING_HALT, HUMAN_CFO_VETO, PACIOLI_INTERRUPTIONS, UNBALANCED_LEDGER_ABORT, PacioliVeritasError, VeritasRevocationRegistry, bankers_round_half_even_int, build_canonical_pacioli_specimen, build_dora_event, build_humble_crystal_facts_and_gate_v7, fraction_to_str, parse_rational_q, reject_lone_surrogates, require_int, rule14_mask_veritas_text, run_self_tests as run_core_self_tests, strict_bool, verify_cross_border_zk_sanctuary_v5, verify_dora_ict_reconstruction_and_sox_v6, verify_east_west_aigc_and_tc260_agent_gate_v4, verify_pacioli_double_entry_ledger_v1, verify_rag_citation_and_table_grounding_v2, verify_sovereign_rounding_and_apportionment_v3, ) from logic.veritas.temple_folio_xi_adapter import ( TemplePacioliVeritasCoordinator, pacioli_veritas_to_verified_knowledge_envelope, ) __all__ = [ "FOLIO_XI_ID", "IEEE_7001_AUDIENCES", "MAAT_PACIOLI_VERITAS_CREDENTIAL_TYPE", "PACIOLI_ASSURANCE_TEXT", "PACIOLI_DECISION_LOG_ID", "PACIOLI_INTERRUPTIONS", "PACIOLI_LAWS", "PACIOLI_REGULATORY_SCOPE", "PACIOLI_VERITAS_SPEC_VERSION", "RING_WEIGHTS", "audit_pacioli_veritas_office", "build_canonical_pacioli_veritas_test_vectors_payload", "build_pacioli_veritas_ieee7001_explanations", "get_canonical_pacioli_veritas_specimen", "get_pacioli_veritas_regulatory_boundary", "issue_w3c_pacioli_veritas_credential", "run_folio_xi_self_test", "verify_pacioli_veritas_credential", ] # ============================================================================ # SECTION 0 — IDENTITY, HONEST SCOPE & CONSTANTS (ZERO FLOAT) # ============================================================================ FOLIO_XI_ID: Final[str] = "folio-XI-pacioli-veritas-office" PACIOLI_VERITAS_SPEC_VERSION: Final[str] = "HU-VERITAS-PACIOLI-OFFICE/v1.0" PACIOLI_LAWS: Final[tuple[str, ...]] = ("V1", "V2", "V3", "V4", "V5", "V6", "V7") MAAT_PACIOLI_VERITAS_CREDENTIAL_TYPE: Final[str] = "MaatPacioliVeritasCredential" PACIOLI_DECISION_LOG_ID: Final[str] = "hu-pacioli-veritas-office-log-2026" PACIOLI_REGULATORY_SCOPE: Final[str] = ( "stateless_pacioli_double_entry_rag_citation_east_west_aigc_tc260_and_dora_sox_self_assessment_not_cpa_audit_not_cac_filing" ) PACIOLI_ASSURANCE_TEXT: Final[str] = ( "self-assessed mathematical and cryptographic conformity across Pacioli exact rational double-entry " "accounting, arbitrage-free FX cocycles and weighted XBRL Calculation v1.1 roll-ups (V1), RFC 6962 " "verifiable RAG citation spans and acyclic symbolic formula grounding (V2), signed Banker's rounding " "and zero-cent-leak Hamilton apportionment (V3), unified East-West GB 45438-2025 + EU AI Act Art. 50(2) " "AIGC labeling and TC260 v3.0 agentic HITL governance (V4), stateless PIPL/GDPR Rule 14 IBAN/CN-ID " "zero-retention sanctuary (V5), and EU DORA Art. 15 ICT hash-chain with SOX 404 Segregation of Duties " "(V6/V7); not a statutory CPA financial audit, not an official CAC regulatory filing, not EU AI Act " "Art. 43 notified-body certification and not tax, legal or investment advice; recompute independently" ) _FORBIDDEN_DIGITS: Final[str] = f"{21}{6}" _REGULATORY_BOUNDARY: Final[dict[str, Any]] = { "covered_by_this_self_assessment": [ "Pacioli exact rational double-entry & XBRL Calculation v1.1 (`V1`): zero-float Fraction balance, arbitrage-free FX cocycle, A = L + E + (R - X), and cycle-free weighted {-1, +1} XBRL DAG", "Verifiable RAG citation & table formula grounding (`V2`): RFC 6962 Merkle proofs over Rule 14 masked chunks, context-sensitive numeric/loss-parentheses span checks, and acyclic Q formula DAG", "Sovereign Banker's rounding & Hamilton apportionment (`V3`): exact round-half-to-even and sum(allocated_units) == total_scaled_units conservation with zero 1-cent leak", "East-West AIGC & TC260 v3.0 agentic gate (`V4`, `V5`): GB 45438-2025 + EU AI Act Art. 50(2) JCS metadata digest, <= 86400s session TTL, independent human HITL, and zero-retention IBAN/CN-ID sanctuary", "EU DORA Art. 15, SOX 404 & Seven-Folio cascade (`V6`, `V7`): 7-key hash-chained ICT log, preparer/approver disjointness, Law U2 hex-free Humble Crystal, and simultaneous Twist = 0 halt across Folios V..XI", ], "outside_this_self_assessment": [ "Statutory external CPA / registered auditor financial statement opinion under ISA, PCAOB, IFRS or CAS / CICPA", "Official Cyberspace Administration of China (CAC) algorithm registry filing or TC260 government certification", "EU AI Act Art. 43 notified-body conformity assessment, DORA supervisory examination or CE marking", "Binding tax, accounting, securities, investment or legal advice", "Physical machinery safety certification: ISO 10218, ISO 13482, ISO/TS 15066, Regulation (EU) 2023/1230", ], "safety_rated_function": bool(0), "statutory_cpa_financial_audit": bool(0), "official_cac_regulatory_filing": bool(0), "notified_body_eu_ai_act_art43": bool(0), "tax_investment_or_legal_advice": bool(0), } RING_WEIGHTS: Final[dict[str, Fraction]] = { "ring_i_pacioli_double_entry_fx_and_xbrl_dag": Fraction(1, 4), "ring_ii_verifiable_rag_citation_and_formula_grounding": Fraction(1, 4), "ring_iii_bankers_rounding_and_hamilton_apportionment": Fraction(3, 20), "ring_iv_east_west_gb45438_tc260_and_pipl_gdpr_sanctuary": Fraction(1, 5), "ring_v_dora_art15_sox404_seven_folio_and_w3c_vc": Fraction(3, 20), } def _qs(value: Fraction) -> str: return fraction_to_str(value) def get_canonical_pacioli_veritas_specimen() -> dict[str, Any]: """Build a fresh deep copy of Canonical Specimen #0001 for Living Folio XI (`V1..V7`).""" core = build_canonical_pacioli_specimen() inp = core["inputs"] b1 = bool(PACIOLI_VERITAS_SPEC_VERSION.startswith("HU-")) return { "office_name": "Homo Universalis Pacioli Agentic Office & Financial Veritas Gate", "agent_domain": "homouniversalis.ai", "base_currency": inp["v1"]["base_currency"], "fx_rates_to_base": inp["v1"]["fx_rates_to_base"], "declared_cross_rates": inp["v1"]["declared_cross_rates"], "journal_entries": inp["v1"]["journal_entries"], "reported_statement_totals": inp["v1"]["reported_statement_totals"], "xbrl_rollups": inp["v1"]["xbrl_rollups"], "evidence_chunks": inp["v2"]["evidence_chunks"], "claims": inp["v2"]["claims"], "scale_per_unit": inp["v3"]["scale_per_unit"], "line_roundings": inp["v3"]["line_roundings"], "apportionment_tables": inp["v3"]["apportionment_tables"], "gb45438_label": inp["v4"]["gb45438_label"], "tc260_v3_agent": inp["v4"]["tc260_v3_agent"], "transfer_mechanism": inp["v5"]["transfer_mechanism"], "raw_pii_retained": inp["v5"]["raw_pii_retained"], "stateless_zero_retention": inp["v5"]["stateless_zero_retention"], "office_summary_text": inp["v5"]["office_summary_text"], "execution_events": inp["v6"]["execution_events"], "downstream_disclosure_text": ( "I am an AI financial and document notary. Pacioli ledger (assets 12600 EUR, closing equity 11540 EUR), " "12 grounded RAG claims, Hamilton 154000 cents, GB 45438 / TC260 HITL and DORA / SOX 404 verified." ), "eu_ai_act_art50_disclosed": b1, "interruption": "none", "actor_guardian_seat": 2, "cost_zero_stop_policy": b1, "budget_b": 120, "telemetry_fields": {"journal_entries_audited": 3, "grounded_claims_verified": 12}, } def get_pacioli_veritas_regulatory_boundary() -> dict[str, Any]: """Deep copy of the honest regulatory boundary declaration (`WO-13`).""" return copy.deepcopy(_REGULATORY_BOUNDARY) # ============================================================================ # SECTION I — QUADRILINGUAL IEEE 7001 EXPLANATIONS (`CA`/`ES`/`EN`/`ZH`) & RFC 6962 # ============================================================================ def build_pacioli_veritas_ieee7001_explanations( summary: Mapping[str, Any], *, lang: str = "ca" ) -> dict[str, str]: """Descriptive explanations for the five IEEE 7001-2021 audiences in CA, ES, EN, and ZH (zero directives, WO-17).""" halted = bool(summary.get("halted_or_vetoed")) ccy = summary.get("base_currency", "EUR") aq = summary.get("assets_q", "12600") ceq = summary.get("closing_equity_q", "11540") gcnt = summary.get("grounded_claims_count", 12) if lang == "zh": companion = "我是一个人工智能办公与财务核验公证系统,并非自然人。" + ( "自动核验已安全停止,人工复核通道保持零成本开放,物理运动指令已精确归零。" if halted else f"已按精确有理数完成帕乔利复式记账核验(资产 {aq} {ccy},期末权益 {ceq} {ccy})、{gcnt} 项可溯源引用核验、GB 45438 标识与人工审批隔离。" ) elif lang == "es": companion = "Soy un sistema de inteligencia artificial de notaría documental y financiera, no una persona. " + ( "La verificación automatizada se ha detenido limpiamente con revisión humana sin coste disponible y movimiento en cero exacto." if halted else f"Se verificó la partida doble racional de Pacioli (activos {aq} {ccy}, patrimonio final {ceq} {ccy}), {gcnt} citas documentales trazables, etiquetado GB 45438 / Art. 50 y segregación SOX 404." ) elif lang == "en": companion = "I am an artificial intelligence financial and document notary system, not a person. " + ( "The automated verification halted cleanly with zero-cost human CFO review available and motion set to an exact zero." if halted else f"Exact rational Pacioli double-entry accounting (assets {aq} {ccy}, closing equity {ceq} {ccy}), {gcnt} grounded RAG citations, GB 45438 / Art. 50 labeling, and SOX 404 segregation were verified." ) else: companion = "Soc un sistema d'intel·ligència artificial de notaria documental i financera, no una persona. " + ( "La verificació automatitzada s'ha aturat netament amb revisió humana sense cost disponible i moviment al zero exacte." if halted else f"S'ha verificat la partida doble racional de Pacioli (actius {aq} {ccy}, patrimoni final {ceq} {ccy}), {gcnt} citacions traçables, etiquetatge GB 45438 / Art. 50 i segregació SOX 404." ) return { "companion_human": companion, "bystander_public": ( f"Stateless Pacioli financial and AI-office truth notary under the {PACIOLI_VERITAS_SPEC_VERSION} self-assessment; " f"assets_q={aq} {ccy}; closing_equity_q={ceq} {ccy}; grounded_claims={gcnt}; interruption={summary.get('interruption')}." ), "safety_engineer": ( f"allocated_scaled_units={summary.get('allocated_scaled_units')}; dora_events={summary.get('dora_events_count')}; " f"q3_zero_twist_on_veto={summary.get('q3_zero_twist_on_veto')}; deterministic Q arithmetic, not a safety-rated function or statutory CPA audit." ), "incident_investigator": ( f"evidence_merkle_root={summary.get('evidence_merkle_root')}; implicit_metadata_sha256={summary.get('implicit_metadata_sha256')}; " f"dora_events_merkle_root={summary.get('dora_events_merkle_root')}; decision_commitment_root={summary.get('commitment_root')}; " "all evidence chunks and DORA events are RFC 6962 domain-separated (0x00/0x01) under Rule 14 with c_levels=1." ), "expert_witness_regulator": ( "Self-assessed alignment with Pacioli double-entry accounting, XBRL Calculation v1.1, China GB 45438-2025 & TC260 v3.0 (Sept 2026), " "PIPL Art. 38 / GDPR Art. 25 zero-retention compute, EU AI Act Art. 50, EU DORA Art. 15, SOX Section 404, and IEEE 7001-2021; " "not a statutory CPA financial audit, not an official CAC filing, and not legal or investment advice." ), } 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"{PACIOLI_VERITAS_SPEC_VERSION}:{PACIOLI_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": PACIOLI_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 PACIOLI FINANCIAL & DOCUMENT VERITAS # ============================================================================ def audit_pacioli_veritas_office( *, office_name: str = "Homo Universalis Pacioli Agentic Office & Financial Veritas Gate", agent_domain: str = "homouniversalis.ai", base_currency: str = "EUR", fx_rates_to_base: Mapping[str, Any] | None = None, declared_cross_rates: Sequence[Mapping[str, Any]] | None = None, journal_entries: Sequence[Mapping[str, Any]] | None = None, reported_statement_totals: Mapping[str, Any] | None = None, xbrl_rollups: Sequence[Mapping[str, Any]] | None = None, evidence_chunks: Sequence[Mapping[str, Any]] | None = None, claims: Sequence[Mapping[str, Any]] | None = None, scale_per_unit: int = 100, line_roundings: Sequence[Mapping[str, Any]] | None = None, apportionment_tables: Sequence[Mapping[str, Any]] | None = None, gb45438_label: Mapping[str, Any] | None = None, tc260_v3_agent: Mapping[str, Any] | None = None, transfer_mechanism: str = "READ_ONLY_EPHEMERAL_COMPUTE", raw_pii_retained: bool = False, stateless_zero_retention: bool = True, office_summary_text: str = "Quarterly Pacioli ledger reconciled in EUR with grounded evidence and zero retained personal data.", execution_events: Sequence[Mapping[str, Any]] | None = None, downstream_disclosure_text: str = ( "I am an AI financial and document notary. Pacioli ledger (assets 12600 EUR, closing equity 11540 EUR), " "12 grounded RAG claims, Hamilton 154000 cents, GB 45438 / TC260 HITL and DORA / SOX 404 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 = 120, telemetry_fields: Mapping[str, Any] | Sequence[Any] | None = None, lang: str = "ca", today_utc_date: str | None = None, ) -> dict[str, Any]: """ Execute one deterministic Pacioli Financial & Document Veritas evaluation across the Five Veritas Rings (`V1..V7`). """ for label, val in ( ("office_name", office_name), ("agent_domain", agent_domain), ("base_currency", base_currency), ("transfer_mechanism", transfer_mechanism), ("office_summary_text", office_summary_text), ("downstream_disclosure_text", downstream_disclosure_text), ("interruption", interruption), ): reject_lone_surrogates(val, label) if not office_name.strip(): raise ValueError("office_name must not be empty.") if interruption not in PACIOLI_INTERRUPTIONS: raise ValueError(f"interruption must be one of {list(PACIOLI_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].") scale_i = require_int(scale_per_unit, "scale_per_unit") 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") raw_pii_flag = strict_bool(raw_pii_retained, "raw_pii_retained") zero_ret_flag = strict_bool(stateless_zero_retention, "stateless_zero_retention") canon_in = build_canonical_pacioli_specimen()["inputs"] eff_fx = fx_rates_to_base if fx_rates_to_base is not None else canon_in["v1"]["fx_rates_to_base"] eff_cross = declared_cross_rates if declared_cross_rates is not None else canon_in["v1"]["declared_cross_rates"] eff_jes = journal_entries if journal_entries is not None else canon_in["v1"]["journal_entries"] eff_rst = ( reported_statement_totals if reported_statement_totals is not None else (canon_in["v1"]["reported_statement_totals"] if journal_entries is None and fx_rates_to_base is None else None) ) eff_xbrl = ( xbrl_rollups if xbrl_rollups is not None else (canon_in["v1"]["xbrl_rollups"] if journal_entries is None and fx_rates_to_base is None else ()) ) eff_chunks = evidence_chunks if evidence_chunks is not None else canon_in["v2"]["evidence_chunks"] eff_claims = claims if claims is not None else canon_in["v2"]["claims"] eff_lround = line_roundings if line_roundings is not None else (canon_in["v3"]["line_roundings"] if scale_i == 100 else ()) eff_tables = apportionment_tables if apportionment_tables is not None else canon_in["v3"]["apportionment_tables"] eff_gb = gb45438_label if gb45438_label is not None else canon_in["v4"]["gb45438_label"] eff_tc = tc260_v3_agent if tc260_v3_agent is not None else canon_in["v4"]["tc260_v3_agent"] eff_events = execution_events if execution_events is not None else canon_in["v6"]["execution_events"] lang_norm = lang if lang in ("ca", "es", "en", "zh") else "ca" violations: list[str] = [] forbidden_telemetry = scan_forbidden_telemetry(telemetry_fields) if forbidden_telemetry: violations.extend(f"E4_V7_forbidden_telemetry:{k}" for k in forbidden_telemetry) v1_res: dict[str, Any] = {} v2_res: dict[str, Any] = {} v3_res: dict[str, Any] = {} v4_res: dict[str, Any] = {} v5_res: dict[str, Any] = {} v6_res: dict[str, Any] = {} v7_res: dict[str, Any] = {} v1_ok = bool(0) v2_ok = bool(0) v3_ok = bool(0) v4_ok = bool(0) v5_ok = bool(0) v6_ok = bool(0) assets_str = "0" liabilities_str = "0" closing_eq_str = "0" net_income_str = "0" grounded_cnt = 0 allocated_units = 0 ev_root_hex = "0" * 64 meta_sha_hex = "0" * 64 dora_root_hex = "0" * 64 dora_events_cnt = 0 vke_id = "" try: v1_res = verify_pacioli_double_entry_ledger_v1( base_currency=base_currency, fx_rates_to_base=eff_fx, journal_entries=eff_jes, declared_cross_rates=eff_cross, reported_statement_totals=eff_rst, xbrl_rollups=eff_xbrl, ) assets_str = str(v1_res["assets_q"]) liabilities_str = str(v1_res["liabilities_q"]) closing_eq_str = str(v1_res["closing_equity_q"]) net_income_str = str(v1_res["net_income_q"]) v1_ok = bool(v1_res.get("verified") is True) except (PacioliVeritasError, ValueError, TypeError) as exc: violations.append(f"V1_ledger_rejected:{exc.__class__.__name__}:{rule14_mask_veritas_text(str(exc))}") try: v2_res = verify_rag_citation_and_table_grounding_v2( evidence_chunks=eff_chunks, claims=eff_claims, ) grounded_cnt = int(v2_res["grounded_claims_count"]) ev_root_hex = str(v2_res["evidence_merkle_root"]) v2_ok = bool(v2_res.get("verified") is True) except (PacioliVeritasError, ValueError, TypeError) as exc: violations.append(f"V2_grounding_rejected:{exc.__class__.__name__}:{rule14_mask_veritas_text(str(exc))}") try: v3_res = verify_sovereign_rounding_and_apportionment_v3( scale_per_unit=scale_i, apportionment_tables=eff_tables, line_roundings=eff_lround, ) allocated_units = int(v3_res["allocated_total_scaled_units"]) v3_ok = bool(v3_res.get("verified") is True) except (PacioliVeritasError, ValueError, TypeError) as exc: violations.append(f"V3_apportionment_rejected:{exc.__class__.__name__}:{rule14_mask_veritas_text(str(exc))}") try: v4_res = verify_east_west_aigc_and_tc260_agent_gate_v4( gb45438_label=eff_gb, tc260_v3_agent=eff_tc, ) meta_sha_hex = str(v4_res["implicit_metadata_sha256"]) v4_ok = bool(v4_res.get("verified") is True) except (PacioliVeritasError, ValueError, TypeError) as exc: violations.append(f"V4_aigc_tc260_rejected:{exc.__class__.__name__}:{rule14_mask_veritas_text(str(exc))}") try: v5_res = verify_cross_border_zk_sanctuary_v5( transfer_mechanism=transfer_mechanism, raw_pii_retained=raw_pii_flag, stateless_zero_retention=zero_ret_flag, office_summary_text=office_summary_text, budget_b=budget_i, c_levels=1, cost_zero_stop=bool(interruption == COST_ZERO_STOP), ) v5_ok = bool(v5_res.get("verified") is True) except (PacioliVeritasError, ValueError, TypeError) as exc: violations.append(f"V5_sanctuary_rejected:{exc.__class__.__name__}:{rule14_mask_veritas_text(str(exc))}") try: v6_res = verify_dora_ict_reconstruction_and_sox_v6( execution_events=eff_events, ) dora_root_hex = str(v6_res["dora_events_merkle_root"]) dora_events_cnt = int(v6_res["events_count"]) v6_ok = bool(v6_res.get("verified") is True) except (PacioliVeritasError, ValueError, TypeError) as exc: violations.append(f"V6_dora_sox_rejected:{exc.__class__.__name__}:{rule14_mask_veritas_text(str(exc))}") rev_reg = VeritasRevocationRegistry() rev_reg.register_evaluation("eval-folio-xi-audit") if interruption != "none": rev_reg.revoke_evaluation("eval-folio-xi-audit", reason=f"Audit interruption signal: {interruption}") if v1_ok and v2_ok and v3_ok and v4_ok and v5_ok and v6_ok: try: v7_res = build_humble_crystal_facts_and_gate_v7( v1_result=v1_res, v2_result=v2_res, v3_result=v3_res, v4_result=v4_res, v5_result=v5_res, v6_result=v6_res, evaluation_id="eval-folio-xi-audit", interruption=interruption, revocation_registry=rev_reg, ) if v7_res.get("eligible_for_w3c_vc") is True and not forbidden_telemetry: vke = pacioli_veritas_to_verified_knowledge_envelope( v1_result=v1_res, v2_result=v2_res, v3_result=v3_res, v4_result=v4_res, v5_result=v5_res, v6_result=v6_res, evaluation_id="eval-folio-xi-audit", revocation_registry=rev_reg, source_level=2, ) vke_id = vke.envelope_id except (PacioliVeritasError, ValueError, TypeError) as exc: violations.append(f"V7_humble_crystal_rejected:{exc.__class__.__name__}:{rule14_mask_veritas_text(str(exc))}") masked_disc = sanitize_three_rings_zk( rule14_mask_veritas_text(downstream_disclosure_text), today_utc_date=today_utc_date ) residual_pii = int(masked_disc["total_redactions"]) # Independent Seven-Folio (V + VI + VII + VIII + IX + X + XI) veto / halt cascade probe with sibling isolation coord = TemplePacioliVeritasCoordinator(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_veritas_evaluation("probe-pacioli-root") coord.register_veritas_evaluation("probe-pacioli-branch-a", parent_evaluation_id="probe-pacioli-root") coord.register_veritas_evaluation("probe-pacioli-child-a1", parent_evaluation_id="probe-pacioli-branch-a") coord.register_veritas_evaluation("probe-pacioli-sibling-b", parent_evaluation_id="probe-pacioli-root") probe_sig = ( COST_ZERO_STOP if interruption == COST_ZERO_STOP else ( UNBALANCED_LEDGER_ABORT if interruption == UNBALANCED_LEDGER_ABORT else (HALLUCINATION_GROUNDING_HALT if interruption == HALLUCINATION_GROUNDING_HALT else HUMAN_CFO_VETO) ) ) veto_cascade = coord.trigger_pacioli_veto_or_halt_cascade( signal_kind=probe_sig, actor_guardian_seat=actor_seat_i, target_eval_id="probe-pacioli-branch-a", note="Pacioli sanctuary probe VVK-1234-5678", ) child_revoked = coord.veritas_revocation_registry.is_revoked("probe-pacioli-child-a1") sibling_intact = not coord.veritas_revocation_registry.is_revoked("probe-pacioli-sibling-b") zero_twist_ok = bool(veto_cascade["q3_zero_twist_enforced"]) cascade_ok = bool( policy and residual_pii == 0 and not forbidden_telemetry and zero_twist_ok 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("V7_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(v1_ok) ring_ii = bool(v2_ok) ring_iii = bool(v3_ok) ring_iv = bool(v4_ok and v5_ok and shield_non_l7_ok) commitment = _commit_run_rfc6962( { "spec": PACIOLI_VERITAS_SPEC_VERSION, "office_name": rule14_mask_veritas_text(office_name), "base_currency": base_currency.strip().upper(), "assets_q": assets_str, "closing_equity_q": closing_eq_str, "evidence_merkle_root": ev_root_hex, "implicit_metadata_sha256": meta_sha_hex, "dora_events_merkle_root": dora_root_hex, "rings_pre_v": {"i": ring_i, "ii": ring_ii, "iii": ring_iii, "iv": ring_iv}, } ) summary_for_ieee = { "base_currency": base_currency.strip().upper(), "assets_q": assets_str, "closing_equity_q": closing_eq_str, "grounded_claims_count": grounded_cnt, "allocated_scaled_units": allocated_units, "dora_events_count": dora_events_cnt, "evidence_merkle_root": ev_root_hex, "implicit_metadata_sha256": meta_sha_hex, "dora_events_merkle_root": dora_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 and v6_ok))), "q3_zero_twist_on_veto": zero_twist_ok, } explanations = build_pacioli_veritas_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("V7_eu_ai_act_art50_not_disclosed") v7_ok = bool( v7_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(v6_ok and cascade_ok and art50_flag and explanations_complete and commitment["inclusion_self_check_passed"]) rings_passed = { "ring_i_pacioli_double_entry_fx_and_xbrl_dag": ring_i, "ring_ii_verifiable_rag_citation_and_formula_grounding": ring_ii, "ring_iii_bankers_rounding_and_hamilton_apportionment": ring_iii, "ring_iv_east_west_gb45438_tc260_and_pipl_gdpr_sanctuary": ring_iv, "ring_v_dora_art15_sox404_seven_folio_and_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 = { "V1": v1_ok, "V2": v2_ok, "V3": v3_ok, "V4": v4_ok, "V5": v5_ok, "V6": v6_ok, "V7": v7_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_pacioli_double_entry_fx_and_xbrl_dag"].update( { "base_currency": v1_res.get("base_currency", base_currency), "journal_entries_count": int(v1_res.get("journal_entries_count", 0)), "assets_q": assets_str, "liabilities_q": liabilities_str, "closing_equity_q": closing_eq_str, "net_income_q": net_income_str, "xbrl_totals": dict(v1_res.get("xbrl_totals", {})), } ) rings_out["ring_ii_verifiable_rag_citation_and_formula_grounding"].update( { "grounded_claims_count": grounded_cnt, "evidence_merkle_root": ev_root_hex, "chunks_count": len(v2_res.get("chunks", [])), } ) rings_out["ring_iii_bankers_rounding_and_hamilton_apportionment"].update( { "scale_per_unit": scale_i, "allocated_total_scaled_units": allocated_units, "tables": list(v3_res.get("tables", [])), } ) rings_out["ring_iv_east_west_gb45438_tc260_and_pipl_gdpr_sanctuary"].update( { "implicit_metadata_sha256": meta_sha_hex, "tc260_human_hitl_approved": bool(v4_res.get("human_hitl_approved")), "transfer_mechanism": v5_res.get("transfer_mechanism", transfer_mechanism), "c_levels": 1, "word_count": int(v5_res.get("word_count", 0)), "budget_b": budget_i, } ) rings_out["ring_v_dora_art15_sox404_seven_folio_and_w3c_vc"].update( { "dora_events_count": dora_events_cnt, "dora_events_merkle_root": dora_root_hex, "preparer_actors": list(v6_res.get("preparer_actors", [])), "approver_actors": list(v6_res.get("approver_actors", [])), "folio_vi_verified_knowledge_envelope_id": vke_id, "q3_zero_twist_on_veto": zero_twist_ok, "sibling_isolation_verified": sibling_intact, "forbidden_telemetry_keys": forbidden_telemetry, } ) passes_all = bool(all(rings_passed.values()) and v7_ok) return { "schema_version": PACIOLI_VERITAS_SPEC_VERSION, "folio_id": FOLIO_XI_ID, "self_assessment": bool(PACIOLI_VERITAS_SPEC_VERSION.startswith("HU-")), "assurance": PACIOLI_ASSURANCE_TEXT, "regulatory_scope": PACIOLI_REGULATORY_SCOPE, "regulatory_boundary": get_pacioli_veritas_regulatory_boundary(), "office_name": rule14_mask_veritas_text(office_name), "agent_domain": rule14_mask_veritas_text(agent_domain), "interruption": interruption, "base_currency": v1_res.get("base_currency", base_currency), "assets_q": assets_str, "liabilities_q": liabilities_str, "closing_equity_q": closing_eq_str, "net_income_q": net_income_str, "grounded_claims_count": grounded_cnt, "allocated_total_scaled_units": allocated_units, "evidence_merkle_root": ev_root_hex, "implicit_metadata_sha256": meta_sha_hex, "dora_events_merkle_root": dora_root_hex, "sox404_segregation_verified": v6_ok, "folio_vi_verified_knowledge_envelope_id": vke_id, "five_pacioli_rings": rings_out, "exact_rational_score": _qs(exact_total), "total_score_100": score_100, "pacioli_veritas_grade": _grade_for(score_100), "passes_internal_pacioli_criteria": passes_all, "pacioli_laws_status": laws_status, "pacioli_laws_verified": [law for law in PACIOLI_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 `MaatPacioliVeritasCredential` # ============================================================================ 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_pacioli_veritas_credential( *, office_id: str, office_name: str, pacioli_score_100: int, pacioli_laws_verified: Sequence[str], fil_dor_laws_verified: Sequence[str], base_currency: str, assets_rational: str, liabilities_rational: str, closing_equity_rational: str, net_income_rational: str, grounded_claims_count: int, allocated_total_scaled_units: int, evidence_merkle_root_hex: str, implicit_metadata_sha256_hex: str, dora_events_merkle_root_hex: str, sox404_segregation_verified: bool, gb45438_aigc_labeled: 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 `MaatPacioliVeritasCredential` (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(pacioli_score_100, "pacioli_score_100") if not (0 <= score_i <= 100): raise ValueError("pacioli_score_100 must be an integer in [0, 100].") g_cnt = require_int(grounded_claims_count, "grounded_claims_count") if not (1 <= g_cnt <= 256): raise ValueError("grounded_claims_count must be in [1, 256].") alloc_u = require_int(allocated_total_scaled_units, "allocated_total_scaled_units") if not (0 <= alloc_u <= (1 << 53) - 1): raise ValueError("allocated_total_scaled_units out of I-JSON range.") for label, val in ( ("office_id", office_id), ("office_name", office_name), ("base_currency", base_currency), ("assets_rational", assets_rational), ("liabilities_rational", liabilities_rational), ("closing_equity_rational", closing_equity_rational), ("net_income_rational", net_income_rational), ): s_val = reject_lone_surrogates(val, label).strip() if not s_val: raise ValueError(f"{label} must be a non-empty string.") ccy = base_currency.strip() if len(ccy) != 3 or not ccy.isalpha() or not ccy.isupper(): raise ValueError("base_currency must be a 3-letter uppercase ISO 4217 code.") aq = parse_rational_q(assets_rational, "assets_rational", max_denom=None) lq = parse_rational_q(liabilities_rational, "liabilities_rational", max_denom=None) ceq = parse_rational_q(closing_equity_rational, "closing_equity_rational", max_denom=None) niq = parse_rational_q(net_income_rational, "net_income_rational", max_denom=None) if aq != lq + ceq: raise ValueError("Pacioli accounting identity violated: assets_rational != liabilities_rational + closing_equity_rational.") for label, flag in ( ("sox404_segregation_verified", sox404_segregation_verified), ("gb45438_aigc_labeled", gb45438_aigc_labeled), ("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) v_laws = [reject_lone_surrogates(x, "law") for x in pacioli_laws_verified] if any(law not in PACIOLI_LAWS for law in v_laws): raise ValueError("pacioli_laws_verified must only contain V1..V7.") 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 ( ("evidence_merkle_root_hex", evidence_merkle_root_hex), ("implicit_metadata_sha256_hex", implicit_metadata_sha256_hex), ("dora_events_merkle_root_hex", dora_events_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-PVO-{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_PACIOLI_VERITAS_CREDENTIAL_TYPE], "issuer": { "id": "did:web:homouniversalis.ai", "name": "Homo Universalis — Viveka (Ma'at Sovereign Notary)", "notaryFolio": "https://homouniversalis.ai/oracle/pacioli", }, "validFrom": _format_rfc3339_utc(valid_from_dt), "validUntil": _format_rfc3339_utc(valid_until_dt), "credentialStatus": { "id": f"https://homouniversalis.ai/oracle/pacioli#status-{effective_serial}", "type": "HUSparseMerkleStatus2026", "statusLog": MAAT_SMT_REVOCATION_LOG_ID, "serialId": effective_serial, }, "credentialSubject": { "id": office_id.strip(), "name": office_name.strip(), "pacioliVeritasSpec": PACIOLI_VERITAS_SPEC_VERSION, "pacioliVeritasScore100": score_i, "pacioliLawsVerified": v_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, "baseCurrency": ccy, "assetsRational": _qs(aq), "liabilitiesRational": _qs(lq), "closingEquityRational": _qs(ceq), "netIncomeRational": _qs(niq), "groundedClaimsCount": g_cnt, "allocatedTotalScaledUnits": alloc_u, "evidenceMerkleRoot": evidence_merkle_root_hex.lower(), "implicitMetadataSha256": implicit_metadata_sha256_hex.lower(), "doraEventsMerkleRoot": dora_events_merkle_root_hex.lower(), "sox404SegregationVerified": sox404_segregation_verified, "gb45438AigcLabeled": gb45438_aigc_labeled, "rule14ZeroKnowledge": rule14_zero_knowledge, "aiIdentityDisclosed": eu_ai_act_art50_disclosed, "statutoryCpaAuditClaimed": bool(0), "cacFilingClaimed": bool(0), "regulatoryScope": PACIOLI_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_pacioli_veritas_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 `MaatPacioliVeritasCredential`: full Folio IV policy (ES256 low-S, issuer, validity, signed SMT-256 status) plus Folio XI invariants (type, honest scope, V1..V7 laws, Pacioli accounting identity, SOX 404, GB 45438, Art. 50, and `statutoryCpaAuditClaimed == False` & `cacFilingClaimed == 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_PACIOLI_VERITAS_CREDENTIAL_TYPE not in (claims.get("type") or []): raise MaatCredentialVerificationError( CredentialErrorCode.INVALID_CREDENTIAL_TYPE, "Missing MaatPacioliVeritasCredential 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("pacioliVeritasScore100") g_cnt = subj.get("groundedClaimsCount") alloc_u = subj.get("allocatedTotalScaledUnits") v_laws = subj.get("pacioliLawsVerified") ev_root = subj.get("evidenceMerkleRoot") im_sha = subj.get("implicitMetadataSha256") dr_root = subj.get("doraEventsMerkleRoot") try: aq = parse_rational_q(subj.get("assetsRational"), max_denom=None) lq = parse_rational_q(subj.get("liabilitiesRational"), max_denom=None) ceq = parse_rational_q(subj.get("closingEquityRational"), max_denom=None) parse_rational_q(subj.get("netIncomeRational"), max_denom=None) identity_ok = bool(aq == lq + ceq) except Exception: identity_ok = bool(0) if ( not identity_ok or subj.get("regulatoryScope") != PACIOLI_REGULATORY_SCOPE or subj.get("pacioliVeritasSpec") != PACIOLI_VERITAS_SPEC_VERSION or isinstance(score, bool) or not isinstance(score, int) or not (0 <= score <= 100) or isinstance(g_cnt, bool) or not isinstance(g_cnt, int) or not (1 <= g_cnt <= 256) or isinstance(alloc_u, bool) or not isinstance(alloc_u, int) or not (0 <= alloc_u <= (1 << 53) - 1) or not isinstance(v_laws, list) or any(law not in PACIOLI_LAWS for law in v_laws) or not all(isinstance(h, str) and len(h) == 64 for h in (ev_root, im_sha, dr_root)) or subj.get("c_levels") != 1 or subj.get("sox404SegregationVerified") is not True or subj.get("gb45438AigcLabeled") is not True or subj.get("aiIdentityDisclosed") is not True or subj.get("statutoryCpaAuditClaimed") is not False or subj.get("cacFilingClaimed") is not False ): raise MaatCredentialVerificationError( CredentialErrorCode.DOMAIN_INVARIANT_VIOLATION, "Pacioli Veritas 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, PacioliVeritasError): return bool(1) return bool(0) def build_canonical_pacioli_veritas_test_vectors_payload() -> dict[str, Any]: """Generate the 8 deterministic reference test vectors (`PV-TV-001..008`) for Living Folio XI.""" sp = build_canonical_pacioli_specimen() v1, v2, v3, v4, v5, v6, v7 = (sp[f"v{k}_result"] for k in range(1, 8)) return { "format": "hu-pacioli-veritas-test-vectors", "spec": PACIOLI_VERITAS_SPEC_VERSION, "vector_set_version": "1.0.0", "url": "https://homouniversalis.ai/codex/test-vectors/pacioli-veritas-v1.0.json", "folio_url": "https://homouniversalis.ai/oracle/pacioli", "license": "Apache-2.0", "zero_float_invariant": bool(1), "vectors_count": 8, "vectors": [ { "id": "PV-TV-001", "law": "V1a", "title": "Exact Rational Multi-Currency Double-Entry Ledger & Arbitrage-Free FX Cocycle", "expected": { "base_currency": v1["base_currency"], "journal_entries_count": v1["journal_entries_count"], "assets_q": v1["assets_q"], "liabilities_q": v1["liabilities_q"], "opening_equity_q": v1["opening_equity_q"], "revenues_q": v1["revenues_q"], "expenses_q": v1["expenses_q"], "net_income_q": v1["net_income_q"], "closing_equity_q": v1["closing_equity_q"], "verified": v1["verified"], }, }, { "id": "PV-TV-002", "law": "V1b", "title": "Weighted XBRL Calculation Linkbase v1.1 ({-1, +1}) Disjoint DAG Roll-Up", "expected": { "xbrl_totals": v1["xbrl_totals"], }, }, { "id": "PV-TV-003", "law": "V2", "title": "RFC 6962 Verifiable RAG Citation Spans & Acyclic Symbolic Formula Grounding in Q", "expected": { "evidence_merkle_root": v2["evidence_merkle_root"], "grounded_claims_count": v2["grounded_claims_count"], "verified_claims": v2["verified_claims"], "verified": v2["verified"], }, }, { "id": "PV-TV-004", "law": "V3", "title": "Signed Banker's Half-to-Even Rounding & Zero-Cent-Leak Hamilton Apportionment", "expected": { "scale_per_unit": v3["scale_per_unit"], "allocated_total_scaled_units": v3["allocated_total_scaled_units"], "tables": v3["tables"], "signed_half_even_ties": [bankers_round_half_even_int(x) for x in ("25/2", "27/2", "-25/2", "-27/2")], }, }, { "id": "PV-TV-005", "law": "V4", "title": "East-West GB 45438-2025 + EU AI Act Art. 50(2) JCS Metadata & TC260 v3.0 Agentic HITL", "expected": { "explicit_user_label": v4["explicit_user_label"], "implicit_metadata_sha256": v4["implicit_metadata_sha256"], "agent_id": v4["agent_id"], "eval_utc_s": v4["eval_utc_s"], "high_impact_financial_action": v4["high_impact_financial_action"], "human_hitl_approved": v4["human_hitl_approved"], }, }, { "id": "PV-TV-006", "law": "V5", "title": "Stateless PIPL / GDPR Zero-Retention Sanctuary, ISO 13616 IBAN & GB 11643 CN-ID Masking", "expected": { "transfer_mechanism": v5["transfer_mechanism"], "word_count": v5["word_count"], "budget_b": v5["budget_b"], "c_levels": v5["c_levels"], "masked_iban_cnid_specimen": rule14_mask_veritas_text( "IBAN DE89 3704 0044 0532 0130 00, CNID 110105199003071239, VVK-AB12-CD34" ), }, }, { "id": "PV-TV-007", "law": "V6", "title": "EU DORA Art. 15 Hash-Chained ICT Reconstruction & SOX Section 404 Duty Disjointness", "expected": { "events_count": v6["events_count"], "preparer_actors": v6["preparer_actors"], "approver_actors": v6["approver_actors"], "dora_events_merkle_root": v6["dora_events_merkle_root"], "verified": v6["verified"], }, }, { "id": "PV-TV-008", "law": "V7", "title": "Hex-Free Law U2 Humble Crystal Verified Facts & Cryptographic Commitments Isolation", "expected": { "evaluation_id": v7["evaluation_id"], "verified_facts": v7["verified_facts"], "humble_crystal_hex_free": v7["humble_crystal_hex_free"], "cryptographic_commitments": v7["cryptographic_commitments"], "eligible_for_w3c_vc": v7["eligible_for_w3c_vc"], }, }, ], } def run_folio_xi_self_test() -> dict[str, Any]: """ Ephemeral deterministic self-test of Living Folio XI (0 network calls), executing both the standalone pure-stdlib `run_self_tests()` (`8/8` mutants) and the Ma'at W3C VC 2.0 + Seven-Folio (V + VI + VII + VIII + IX + X + XI) symbiotic integration verification. """ t0 = time.perf_counter_ns() core_report = run_core_self_tests() specimen = get_canonical_pacioli_veritas_specimen() audit = audit_pacioli_veritas_office(**specimen, lang="zh") specimen_ok = bool(audit["passes_internal_pacioli_criteria"]) vc_signer = LocalEphemeralSigner(kid="maat-pacioli-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, 27, 12, 0, 0, tzinfo=timezone.utc) serial = "MAAT-PVO-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_pacioli_rings"] vc = issue_w3c_pacioli_veritas_credential( office_id="https://homouniversalis.ai/oracle/pacioli#specimen-0001-pacioli-veritas", office_name=specimen["office_name"], pacioli_score_100=audit["total_score_100"], pacioli_laws_verified=audit["pacioli_laws_verified"], fil_dor_laws_verified=audit["fil_dor_laws_verified"], base_currency=audit["base_currency"], assets_rational=audit["assets_q"], liabilities_rational=audit["liabilities_q"], closing_equity_rational=audit["closing_equity_q"], net_income_rational=audit["net_income_q"], grounded_claims_count=audit["grounded_claims_count"], allocated_total_scaled_units=audit["allocated_total_scaled_units"], evidence_merkle_root_hex=audit["evidence_merkle_root"], implicit_metadata_sha256_hex=audit["implicit_metadata_sha256"], dora_events_merkle_root_hex=audit["dora_events_merkle_root"], sox404_segregation_verified=audit["sox404_segregation_verified"], gb45438_aigc_labeled=rings["ring_iv_east_west_gb45438_tc260_and_pipl_gdpr_sanctuary"]["passed"], rule14_zero_knowledge=rings["ring_iv_east_west_gb45438_tc260_and_pipl_gdpr_sanctuary"]["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-27T00:00:00Z", valid_until_utc="2027-11-27T00:00:00Z", serial_id=serial, ) def _verify(cred: Any) -> VerifiedCredential: return verify_pacioli_veritas_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"]["pacioliVeritasScore100"] = 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_dora_chain_sox404_humble_crystal_revocation_and_w3c_vc_low_s"] = bool( mutants.pop("mutant_8_dora_chain_sox404_humble_crystal_and_revocation") and vc_tamper_killed ) killed = sum(1 for ok in mutants.values() if ok) tv_payload = build_canonical_pacioli_veritas_test_vectors_payload() zero_forbidden_ok = bool( core_report["zero_forbidden_digits_verified"] and _FORBIDDEN_DIGITS.encode("ascii") not in jcs_canonical_bytes(audit) and _FORBIDDEN_DIGITS.encode("ascii") not in jcs_canonical_bytes(tv_payload) ) elapsed_us = (time.perf_counter_ns() - t0) // 1000 return { "folio_id": FOLIO_XI_ID, "spec": PACIOLI_VERITAS_SPEC_VERSION, "canonical_assets_q": audit["assets_q"], "canonical_closing_equity_q": audit["closing_equity_q"], "canonical_grounded_claims_count": audit["grounded_claims_count"], "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_xi_self_test(), indent=2, ensure_ascii=False))