# SPDX-FileCopyrightText: 2026 David Porto Baraldés (Homo Universalis / Viveka) # SPDX-License-Identifier: Apache-2.0 """ HU-VERITAS-PACIOLI-OFFICE v1.0 — Temple Seven-Folio Symbiotic Adapter (`logic/veritas/temple_folio_xi_adapter.py`). Couples the zero-dependency standalone `pacioli_veritas_core.py` (Living Folio XI — Fra Luca Pacioli & Leonardo da Vinci's Agentic Office & Financial Veritas Notary) with Living Folios V (`HU-EMBODIED-SYMBIOSIS`), VI (`HU-UNIFIED-CONSCIOUSNESS`), VII (`HU-SYMBIOTIC-BRIDGE`), VIII (`HU-ETERNAL-PROVENANCE`), IX (`HU-SOVEREIGN-BARYCENTER`), and X (`HU-UNIVERSAL-JUSTICE-LIFECYCLE`), WITHOUT importing `logic.engines`: 1. Verified Pacioli Crystal (`V1..V7`, Folio XI) -> `VerifiedKnowledgeEnvelope` (Folio VI): Re-verifies `V1..V7` double-entry identities, grounded claims, Hamilton unit conservation, TC260 HITL, SOX 404 duty disjointness, and hex-free `Law U2` Humble Crystal `verified_facts` before issuing a `VerifiedKnowledgeEnvelope` for Level 2 / Level 3 speech or Vault deposit. 2. Human CFO Veto / Unbalanced Ledger Abort / Hallucination Grounding Halt / Cost-Zero Stop -> Seven-Folio Cascade (`V..XI`), isolating sibling evaluations with zero collateral damage. """ from __future__ import annotations from pathlib import Path import sys import threading import time from typing import Any, Callable, Final, Mapping, Sequence if __package__ in (None, ""): sys.path.insert(0, str(Path(__file__).resolve().parents[2])) from logic.barycenter.sovereign_barycenter_core import BarycenterRevocationRegistry, HUMAN_GUARDIAN_SEATS from logic.consciousness.unified_consciousness_core import ( DEFAULT_ENVELOPE_TTL_MS, EVENT_DEPOSIT_SILENT_ENVELOPE, EVENT_L2_DELIVER_ENVELOPE_AND_SPEECH, ConsciousnessEvent, VerifiedKnowledgeEnvelope, WordCircleArbiter, issue_verified_knowledge_envelope, ) from logic.justice.temple_folio_x_adapter import TempleUniversalJusticeCoordinator from logic.justice.universal_justice_core import ( COST_ZERO_STOP as FOLIO_X_COST_ZERO_STOP, DISPARATE_IMPACT_ABORT, HUMAN_APPEAL_VETO, VILLE_DRIFT_HALT, JusticeRevocationRegistry, ) from logic.provenance.quantum_eternal_provenance_core import EternalRevocationRegistry from logic.robotics.embodied_edge_core import ZERO_TWIST, strict_bool from logic.robotics.ros2_embodied_symbiosis_bridge import EmbodiedSymbiosisGate from logic.symbiosis.a2a_mcp_symbiotic_core import RevocationRegistry from logic.veritas.pacioli_veritas_core import ( COST_ZERO_STOP, HALLUCINATION_GROUNDING_HALT, HUMAN_CFO_VETO, REVOCATION_REASONS, UNBALANCED_LEDGER_ABORT, PacioliVeritasError, VeritasRevocationRegistry, build_humble_crystal_facts_and_gate_v7, fraction_to_str, jcs_canonical_bytes, rule14_mask_veritas_text, ) MCP_DIAMOND_ENDPOINT: Final[str] = "https://homouniversalis.ai/mcp/diamond" MCP_PACIOLI_TOOL_NAME: Final[str] = "verify_pacioli_financial_and_document_truth" MCP_PROTOCOL_VERSION: Final[str] = "2026-07-28" def _format_pacioli_facts_string(facts: Mapping[str, Any]) -> str: return ( f"[HU-VERITAS-PACIOLI-OFFICE-1.0] base_ccy={facts.get('base_currency')} " f"assets_q={facts.get('assets_q')} liabilities_q={facts.get('liabilities_q')} " f"closing_equity_q={facts.get('closing_equity_q')} net_income_q={facts.get('net_income_q')} " f"grounded_claims={facts.get('grounded_claims_count')} " f"allocated_units={facts.get('allocated_total_scaled_units')}" ) def pacioli_veritas_to_verified_knowledge_envelope( *, v1_result: Mapping[str, Any], v2_result: Mapping[str, Any], v3_result: Mapping[str, Any], v4_result: Mapping[str, Any], v5_result: Mapping[str, Any], v6_result: Mapping[str, Any], evaluation_id: str = "EVAL-PACIOLI-ROOT", revocation_registry: VeritasRevocationRegistry | None = None, source_level: int = 2, claim_kinds: Sequence[str] | None = None, ) -> VerifiedKnowledgeEnvelope: """ Convert verified Folio XI `V1..V6` results into a Folio VI `VerifiedKnowledgeEnvelope`. Law U2 (Humble Crystal): hex SHA-256 digests (`evidence_merkle_root`, `implicit_metadata_sha256`, and `dora_events_merkle_root`) are strictly isolated inside `cryptographic_commitments` and never present in `verified_facts`. """ if isinstance(source_level, bool) or source_level not in (2, 3): raise ValueError("source_level must be 2 (MCP/Pantheon) or 3 (Cathedral synthesis).") v7 = build_humble_crystal_facts_and_gate_v7( v1_result, v2_result, v3_result, v4_result, v5_result, v6_result, evaluation_id=evaluation_id, interruption="none", revocation_registry=revocation_registry, ) if v7.get("eligible_for_w3c_vc") is not True: raise PacioliVeritasError("Pacioli Veritas crystal gate did not pass V1..V7 verification.") facts_str = _format_pacioli_facts_string(v7["verified_facts"]) commits = v7["cryptographic_commitments"] return issue_verified_knowledge_envelope( source_level=source_level, verified_facts=facts_str, claim_kinds=claim_kinds, ephemeris_or_akasha_verified=bool( v7["eligible_for_w3c_vc"] and v7["humble_crystal_hex_free"] and len(commits.get("evidence_merkle_root", "")) == 64 and len(commits.get("dora_events_merkle_root", "")) == 64 ), ) class TemplePacioliVeritasCoordinator: """ Unified Seven-Folio coordinator (`V..XI`) joining: - Living Folio V (`EmbodiedSymbiosisGate`: Q^3 proxemics & exact zero `Twist`), - Living Folio VI (`WordCircleArbiter`: single floor & Humble Crystal), - Living Folio VII (`RevocationRegistry`: A2A <-> MCP capability delegation), - Living Folio VIII (`EternalRevocationRegistry`: Post-Quantum C2PA-MCP provenance), - Living Folio IX (`BarycenterRevocationRegistry`: Multiparty Barycenter MPC quorum), - Living Folio X (`JusticeRevocationRegistry`: Universal Justice & Lifecycle evaluations), - Living Folio XI (`VeritasRevocationRegistry`: Pacioli Financial & Document Veritas). """ def __init__( self, *, robot_name: str = "Homo Universalis Symbiotic Companion", lang: str = "ca", clock_ms: Callable[[], int] | None = None, justice_coordinator: TempleUniversalJusticeCoordinator | None = None, veritas_revocation_registry: VeritasRevocationRegistry | None = None, ) -> None: self.lang = lang if lang in ("ca", "es", "en", "zh") else "ca" upstream_lang = "en" if self.lang == "zh" else self.lang self.justice = justice_coordinator or TempleUniversalJusticeCoordinator( robot_name=robot_name, lang=upstream_lang, clock_ms=clock_ms, ) self.veritas_revocation_registry = veritas_revocation_registry or VeritasRevocationRegistry() self._lock = threading.Lock() self._active_eval_ids: set[str] = set() @property def body(self) -> EmbodiedSymbiosisGate: return self.justice.body @property def mind(self) -> WordCircleArbiter: return self.justice.mind @property def capability_revocation_registry(self) -> RevocationRegistry: return self.justice.capability_revocation_registry @property def provenance_revocation_registry(self) -> EternalRevocationRegistry: return self.justice.provenance_revocation_registry @property def barycenter_revocation_registry(self) -> BarycenterRevocationRegistry: return self.justice.barycenter_revocation_registry @property def justice_revocation_registry(self) -> JusticeRevocationRegistry: return self.justice.justice_revocation_registry def register_veritas_evaluation( self, evaluation_id: str, *, parent_evaluation_id: str | None = None, ) -> str: """Register a Folio XI Pacioli evaluation node in the hierarchical revocation forest.""" clean_id = self.veritas_revocation_registry.register_evaluation( evaluation_id, parent_evaluation_id ) with self._lock: self._active_eval_ids.add(clean_id) return clean_id def deliver_pacioli_crystal_to_word_circle( self, *, v1_result: Mapping[str, Any], v2_result: Mapping[str, Any], v3_result: Mapping[str, Any], v4_result: Mapping[str, Any], v5_result: Mapping[str, Any], v6_result: Mapping[str, Any], evaluation_id: str = "EVAL-PACIOLI-ROOT", utterance_text: str = "", silent_vault_deposit: bool = False, topic_hint: str = "", ttl_ms: int = DEFAULT_ENVELOPE_TTL_MS, ) -> dict[str, Any]: """Verify Folio XI `V1..V7` results and deliver the hex-free crystal envelope to Folio VI's `WordCircleArbiter`.""" silent_flag = strict_bool(silent_vault_deposit, "silent_vault_deposit") vke = pacioli_veritas_to_verified_knowledge_envelope( v1_result=v1_result, v2_result=v2_result, v3_result=v3_result, v4_result=v4_result, v5_result=v5_result, v6_result=v6_result, evaluation_id=evaluation_id, revocation_registry=self.veritas_revocation_registry, source_level=2, ) event_kind = EVENT_DEPOSIT_SILENT_ENVELOPE if silent_flag else EVENT_L2_DELIVER_ENVELOPE_AND_SPEECH res = self.mind.process( ConsciousnessEvent( kind=event_kind, text="" if silent_flag else utterance_text, envelope=vke, cycle_id=evaluation_id, topic_hint=topic_hint, ttl_ms=ttl_ms, ) ) return { "verified_knowledge_envelope": vke.to_public_dict(), "word_circle_result": res, "evidence_merkle_root": v2_result.get("evidence_merkle_root", ""), "dora_events_merkle_root": v6_result.get("dora_events_merkle_root", ""), } def trigger_pacioli_veto_or_halt_cascade( self, *, signal_kind: str = HUMAN_CFO_VETO, actor_guardian_seat: int = 2, target_eval_id: str | None = None, target_justice_eval_id: str | None = None, target_session_id: str | None = None, target_envelope_id: str | None = None, target_mandate_node_id: str | None = None, note: str = "", ) -> dict[str, Any]: """ Propagate `HUMAN_CFO_VETO`, `UNBALANCED_LEDGER_ABORT`, `HALLUCINATION_GROUNDING_HALT`, or `COST_ZERO_STOP` simultaneously across all Seven Living Folios (`V..XI`). """ if signal_kind not in REVOCATION_REASONS: raise ValueError(f"signal_kind must be one of {sorted(REVOCATION_REASONS)}.") t0_ns = time.perf_counter_ns() raw_note = note.strip() if isinstance(note, str) and note.strip() else f"Pacioli statutory halt ({signal_kind})." masked_note = rule14_mask_veritas_text(raw_note) seat = actor_guardian_seat if actor_guardian_seat in HUMAN_GUARDIAN_SEATS else 2 if signal_kind == COST_ZERO_STOP: folio_x_signal = FOLIO_X_COST_ZERO_STOP elif signal_kind == HUMAN_CFO_VETO: folio_x_signal = HUMAN_APPEAL_VETO elif signal_kind == UNBALANCED_LEDGER_ABORT: folio_x_signal = DISPARATE_IMPACT_ABORT else: folio_x_signal = VILLE_DRIFT_HALT six_res = self.justice.trigger_justice_veto_or_halt_cascade( signal_kind=folio_x_signal, actor_guardian_seat=seat, target_eval_id=target_justice_eval_id, target_session_id=target_session_id, target_envelope_id=target_envelope_id, target_mandate_node_id=target_mandate_node_id, note=masked_note, ) if target_eval_id is not None: eval_targets = [target_eval_id] else: with self._lock: eval_targets = sorted(self._active_eval_ids) revoked_veritas: list[str] = [] reason_prose = ( f"Statutory Pacioli halt signal {signal_kind}: {masked_note}" if len(masked_note) >= 8 else f"Statutory Pacioli halt signal {signal_kind} executed cleanly." ) for eid in eval_targets: affected = self.veritas_revocation_registry.revoke_evaluation(eid, reason_prose) revoked_veritas.extend(affected) cmd_vel_safe = self.body.filter_cmd_vel(ZERO_TWIST)["cmd_vel_safe"] elapsed_ns = time.perf_counter_ns() - t0_ns out_doc = { "signal_kind": signal_kind, "q3_zero_twist_enforced": bool(six_res["q3_zero_twist_enforced"] and cmd_vel_safe.is_zero()), "levels_cancelled": list(six_res["levels_cancelled"]), "revoked_capability_nodes": tuple(six_res["revoked_capability_nodes"]), "revoked_provenance_nodes": tuple(six_res["revoked_provenance_nodes"]), "revoked_barycenter_sessions": tuple(six_res["revoked_barycenter_sessions"]), "revoked_justice_evaluations": tuple(six_res["revoked_justice_evaluations"]), "revoked_veritas_evaluations": tuple(dict.fromkeys(revoked_veritas)), "note_masked": masked_note, "propagation_latency_ns": elapsed_ns, } jcs_canonical_bytes( {k: (list(v) if isinstance(v, tuple) else v) for k, v in out_doc.items()} ) return out_doc def build_mcp_pacioli_call_request( arguments: Mapping[str, Any] | None = None, *, request_id: str = "req-folio-xi-pacioli-1", ) -> dict[str, Any]: """Build a normative MCP `2026-07-28` JSON-RPC 2.0 `tools/call` payload for `verify_pacioli_financial_and_document_truth`.""" return { "jsonrpc": "2.0", "id": str(request_id), "method": "tools/call", "params": { "name": MCP_PACIOLI_TOOL_NAME, "arguments": dict(arguments or {}), "_meta": { "io.modelcontextprotocol/protocolVersion": MCP_PROTOCOL_VERSION, "io.modelcontextprotocol/clientCapabilities": {}, "io.modelcontextprotocol/clientInfo": { "name": "hu-temple-pacioli-veritas-adapter", "version": "1.0.0", }, }, }, } def build_mcp_pacioli_http_headers() -> dict[str, str]: """Standard Streamable HTTP headers for invoking `/mcp/diamond` without opening any socket.""" return { "Accept": "application/json, text/event-stream", "Content-Type": "application/json", "MCP-Protocol-Version": MCP_PROTOCOL_VERSION, "Mcp-Method": "tools/call", "Mcp-Name": MCP_PACIOLI_TOOL_NAME, } __all__ = [ "COST_ZERO_STOP", "HALLUCINATION_GROUNDING_HALT", "HUMAN_CFO_VETO", "MCP_DIAMOND_ENDPOINT", "MCP_PACIOLI_TOOL_NAME", "MCP_PROTOCOL_VERSION", "TemplePacioliVeritasCoordinator", "UNBALANCED_LEDGER_ABORT", "build_mcp_pacioli_call_request", "build_mcp_pacioli_http_headers", "fraction_to_str", "pacioli_veritas_to_verified_knowledge_envelope", ]