# SPDX-FileCopyrightText: 2026 David Porto Baraldés (Homo Universalis / Viveka) # SPDX-License-Identifier: Apache-2.0 """ Living Folio XII of Leonardo da Vinci (`logic/engines/scholar_veritas_crucible.py`): HU-CANGZHOU-LEONARDO-SCHOLAR v1.0 — Leonardo da Vinci & Thot's Scholarly Citation, Multi-Study Rational Meta-Analysis, Acyclic Mind-Map / Knowledge-Graph & Vault-Commons Non-Interference Notary (12/12 of the Cosmic Dodecahedron): 1. S1 — China `GB/T 7714-2025` National Standard (in force July 1, 2026, aligned with `ISO 690:2021`): - 14 document codes including `[PP/OL]` (Preprint) and `[DS/OL]` (Dataset), - 2025 author surname casing reform (`Einstein A` vs `LI J N`, rejecting 2015 `EINSTEIN A`), - Exact check-digit verifiers for `ORCID` (`ISO 7064` Mod 11-2), `ISSN` (`ISO 3297` Mod 11), `ISBN-13` (`EAN-13`), `DOI` (`ISO 26324`), fail-closed `RETRACTED` gate & `RFC 6962` Merkle root. 2. S2 — Exact Rational Multi-Study Meta-Analysis in Q (`fractions.Fraction`, zero floats): - Inverse-variance pooled effect `pooled_effect_q`, sample conservation `total_sample_n`, Cochran's `Q`, Higgins `I^2`, context-sensitive `LITERAL_SPAN` boundaries & `RFC 6962` corpus proofs. 3. S3 — Iterative Kahn Acyclic Mind-Map / Knowledge-Graph DAG & Bell-LaPadula Taint Lattice: - Cycle-free prerequisite topological sort, bounded depth, and transitive clearance inheritance. 4. S4 & S5 — Vault-Commons Non-Interference (`PRIVATE_VAULT` <-> `PUBLIC_COMMONS` `公私域隔离`), `PIPL`/`GDPR` Rule 14 (`IBAN` Mod-97 + `CN-ID` Mod 11-2) Zero-Retention Sanctuary & Quadrilingual (`ZH`/`EN`/`ES`/`CA`) Canonical Terminology Diapason. 5. S6 & S7 — `MOST / NSFC / MOE 2026` Research Integrity, Exact Rational `CRediT` (`>= 1/2` human), `GB 45438-2025` + `EU AI Act Art. 50(2)` + `TC260 v3.0` PI HITL, Eight-Folio (`V..XII`) `Twist = 0` Veto Cascade, `IEEE 7001` (`CA`/`ES`/`EN`/`ZH`), & `W3C VC 2.0` `MaatScholarlyVeritasCredential` (`vc+jwt`, JOSE `ES256` canonical low-S, `SMT-256`). Honest scope (`WO-13`): stateless mathematical, bibliographic, and cryptographic SELF-ASSESSMENT. Not editorial journal peer review, not an official `MOST` / `NSFC` / `MOE` / `CAC` administrative audit, not official indexing in `CNKI`, `Baidu Scholar`, `Scopus`, or `Web of Science`, 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.scholar.scholar_veritas_core import ( COST_ZERO_STOP, HUMAN_PI_VETO, META_CONTRADICTION_ABORT, RETRACTED_CITATION_HALT, SCHOLAR_INTERRUPTIONS, ScholarRevocationRegistry, ScholarVeritasError, build_canonical_scholar_specimen, build_humble_crystal_scholar_gate_s7, 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_gbt7714_2025_bibliography_and_pids_s1, verify_isbn13_ean, verify_issn_iso3297, verify_mindmap_knowledge_dag_s3, verify_multi_study_meta_synthesis_q_s2, verify_orcid_iso7064, verify_research_integrity_and_aigc_gate_s6, verify_terminology_diapason_s5, verify_vault_commons_non_interference_s4, ) from logic.scholar.temple_folio_xii_adapter import ( TempleScholarlyVeritasCoordinator, scholar_veritas_to_verified_knowledge_envelope, ) __all__ = [ "FOLIO_XII_ID", "IEEE_7001_AUDIENCES", "MAAT_SCHOLARLY_VERITAS_CREDENTIAL_TYPE", "RING_WEIGHTS", "SCHOLAR_ASSURANCE_TEXT", "SCHOLAR_DECISION_LOG_ID", "SCHOLAR_INTERRUPTIONS", "SCHOLAR_LAWS", "SCHOLAR_REGULATORY_SCOPE", "SCHOLAR_VERITAS_SPEC_VERSION", "audit_cangzhou_leonardo_scholar", "build_canonical_scholar_veritas_test_vectors_payload", "build_scholar_veritas_ieee7001_explanations", "get_canonical_scholar_veritas_specimen", "get_scholar_veritas_regulatory_boundary", "issue_w3c_scholarly_veritas_credential", "run_folio_xii_self_test", "verify_scholarly_veritas_credential", ] FOLIO_XII_ID: Final[str] = "folio-XII-cangzhou-leonardo-scholar" SCHOLAR_VERITAS_SPEC_VERSION: Final[str] = "HU-CANGZHOU-LEONARDO-SCHOLAR/v1.0" SCHOLAR_LAWS: Final[tuple[str, ...]] = ("S1", "S2", "S3", "S4", "S5", "S6", "S7") MAAT_SCHOLARLY_VERITAS_CREDENTIAL_TYPE: Final[str] = "MaatScholarlyVeritasCredential" SCHOLAR_DECISION_LOG_ID: Final[str] = "hu-cangzhou-leonardo-scholar-log-2026" SCHOLAR_REGULATORY_SCOPE: Final[str] = ( "stateless_gbt7714_2025_bibliography_q_meta_analysis_kahn_dag_vault_non_interference_and_most_nsfc_self_assessment_not_peer_review_not_government_audit" ) SCHOLAR_ASSURANCE_TEXT: Final[str] = ( "self-assessed mathematical, bibliographic, and cryptographic conformity across China GB/T 7714-2025 " "citations, ORCID/ISSN/ISBN-13/DOI checksums and retraction gates (S1), exact rational inverse-variance " "meta-analysis and RFC 6962 corpus grounding (S2), iterative Kahn acyclic mind-map / knowledge-graph DAGs " "(S3), Bell-LaPadula PRIVATE_VAULT vs PUBLIC_COMMONS non-interference and stateless PIPL/GDPR Rule 14 " "sanctuary (S4), quadrilingual ZH/EN/ES/CA terminology invariance (S5), and MOST/NSFC/MOE 2026 CRediT " "human accountability with GB 45438-2025 + EU AI Act Art. 50(2) + TC260 v3.0 PI HITL (S6/S7); not editorial " "peer review, not a MOST/NSFC/CAC administrative audit, and not official CNKI/Web of Science indexing; " "recompute independently" ) _FORBIDDEN_DIGITS: Final[str] = f"{21}{6}" _REGULATORY_BOUNDARY: Final[dict[str, Any]] = { "covered_by_this_self_assessment": [ "GB/T 7714-2025 & ISO 690:2021 bibliography gate (`S1`): 2025 `[PP/OL]` & `[DS/OL]` codes, surname casing reform, ORCID/ISSN/ISBN-13 check digits, retraction halt & RFC 6962 root", "Exact rational multi-study meta-analysis (`S2`): zero-float `fractions.Fraction` inverse-variance `pooled_effect_q`, Cochran `Q`, Higgins `I^2`, context-sensitive `LITERAL_SPAN` & RFC 6962 corpus proofs", "Iterative Kahn acyclic Mind-Map / Knowledge-Graph DAG (`S3`): prerequisite cycle rejection, grounded chunk anchors, bounded depth, and monotone Bell-LaPadula clearance taint inheritance", "Vault-Commons non-interference & quadrilingual diapason (`S4`, `S5`): `PUBLIC_COMMONS < INTERNAL_TEAM < PRIVATE_VAULT` leak prevention, zero-retention IBAN/CN-ID sanctuary, and `ZH/EN/ES/CA` glossary lock", "MOST/NSFC 2026 research integrity & Eight-Folio `V..XII` cascade (`S6`, `S7`): rational `CRediT` (`>= 1/2` human), GB 45438-2025 + TC260 v3.0 PI HITL, hex-free Humble Crystal, and `Twist = 0` halt", ], "outside_this_self_assessment": [ "Editorial peer review or acceptance by any academic journal, conference, or university press", "Official administrative audit or regulatory filing before China MOST, NSFC, MOE, CAC, or TC260", "Official live bibliographic database indexing in CNKI, Baidu Scholar, Wanfang, Scopus, or Web of Science", "EU AI Act Art. 43 notified-body conformity certification or legal counsel", "Physical machinery safety certification: ISO 10218, ISO 13482, ISO/TS 15066, Regulation (EU) 2023/1230", ], "safety_rated_function": bool(0), "editorial_peer_review": bool(0), "official_most_nsfc_cac_audit": bool(0), "official_database_indexing": bool(0), } RING_WEIGHTS: Final[dict[str, Fraction]] = { "ring_i_gbt7714_2025_bibliography_pids_and_retraction_gate": Fraction(1, 4), "ring_ii_multi_study_rational_meta_analysis_and_corpus_merkle": Fraction(1, 4), "ring_iii_kahn_acyclic_knowledge_dag_and_terminology_diapason": Fraction(3, 20), "ring_iv_bell_lapadula_vault_commons_and_pipl_gdpr_sanctuary": Fraction(1, 5), "ring_v_most_nsfc_credit_gb45438_tc260_eight_folio_and_w3c_vc": Fraction(3, 20), } def _qs(value: Fraction) -> str: return fraction_to_str(value) def get_canonical_scholar_veritas_specimen() -> dict[str, Any]: """Build a fresh deep copy of Canonical Specimen #0001 for Living Folio XII (`S1..S7`).""" inp = build_canonical_scholar_specimen()["inputs"] b1 = bool(SCHOLAR_VERITAS_SPEC_VERSION.startswith("HU-")) return { "workspace_name": "Homo Universalis Cangzhou & Leonardo Scholarly Veritas Gate", "agent_domain": "homouniversalis.ai", "bibliography_entries": inp["bibliography_entries"], "corpus_chunks": inp["corpus_chunks"], "studies": inp["studies"], "reported_meta_summary": inp["reported_meta_summary"], "concept_nodes": inp["concept_nodes"], "prerequisite_edges": inp["prerequisite_edges"], "max_dag_depth": 16, "derived_outputs": inp["derived_outputs"], "transfer_mechanism": inp["transfer_mechanism"], "raw_pii_retained": bool(0), "stateless_zero_retention": b1, "scholar_summary_text": inp["scholar_summary_text"], "glossary_terms": inp["glossary_terms"], "multilingual_conclusions": inp["multilingual_conclusions"], "gb45438_label": inp["gb45438_label"], "tc260_v3_agent": inp["tc260_v3_agent"], "credit_contributions": inp["credit_contributions"], "ai_listed_as_author": bool(0), "synthetic_primary_data_fabricated": bool(0), "downstream_disclosure_text": ( "I am an AI scholarly and knowledge-graph notary. Three GB/T 7714-2025 works (N = 500, pooled effect 13/20, " "Cochran Q = 1/8), 4 Kahn DAG nodes, strict PRIVATE_VAULT isolation, and 4/5 human CRediT verified." ), "eu_ai_act_art50_disclosed": b1, "interruption": "none", "actor_guardian_seat": 2, "cost_zero_stop_policy": b1, "budget_b": 120, "telemetry_fields": {"citations_verified": 3, "studies_synthesized": 3, "dag_nodes_grounded": 4}, } def get_scholar_veritas_regulatory_boundary() -> dict[str, Any]: """Deep copy of the honest regulatory boundary declaration (`WO-13`).""" return copy.deepcopy(_REGULATORY_BOUNDARY) def build_scholar_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")) c_cnt = summary.get("verified_citations_count", 3) tot_n = summary.get("total_sample_n", 500) peq = summary.get("pooled_effect_q", "13/20") cq = summary.get("cochran_q", "1/8") gn = summary.get("grounded_nodes_count", 4) if lang == "zh": companion = "我是一个人工智能学术引文与知识图谱公证系统,并非自然人。" + ( "自动学术核验已安全停止,首席研究员零成本人工复核保持开放,物理运动指令已精确归零。" if halted else f"已完成 {c_cnt} 篇 GB/T 7714-2025 文献核验、总样本 N={tot_n} 的逆方差元分析(合并效应 {peq},Cochran Q={cq})、{gn} 个无环思维导图节点与公私域隔离核验。" ) elif lang == "es": companion = "Soy un sistema de inteligencia artificial de notaría académica y grafos de conocimiento, no una persona. " + ( "La verificación automatizada se ha detenido limpiamente con revisión humana sin coste y movimiento en cero exacto." if halted else f"Se verificaron {c_cnt} citas GB/T 7714-2025, el metaanálisis racional (N={tot_n}, efecto {peq}, Cochran Q={cq}), {gn} nodos DAG acíclicos de Kahn y el aislamiento de bóveda privada." ) elif lang == "en": companion = "I am an artificial intelligence scholarly citation and knowledge-graph notary system, not a person. " + ( "The automated verification halted cleanly with zero-cost human investigator review available and motion set to an exact zero." if halted else f"Verified {c_cnt} GB/T 7714-2025 citations, exact rational meta-analysis (N={tot_n}, pooled effect {peq}, Cochran Q={cq}), {gn} Kahn acyclic DAG nodes, and private-vault non-interference." ) else: companion = "Soc un sistema d'intel·ligència artificial de notaria acadèmica i grafs de coneixement, 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'han verificat {c_cnt} citacions GB/T 7714-2025, la metaanàlisi racional (N={tot_n}, efecte {peq}, Cochran Q={cq}), {gn} nodes DAG acíclics de Kahn i l'aïllament de volta privada." ) return { "companion_human": companion, "bystander_public": ( f"Stateless scholarly citation, meta-analysis, and knowledge-graph notary under the {SCHOLAR_VERITAS_SPEC_VERSION} self-assessment; " f"citations={c_cnt}; total_sample_n={tot_n}; pooled_effect_q={peq}; interruption={summary.get('interruption')}." ), "safety_engineer": ( f"grounded_nodes={gn}; human_credit_share_q={summary.get('human_credit_share_q')}; " f"q3_zero_twist_on_veto={summary.get('q3_zero_twist_on_veto')}; deterministic Q arithmetic, not editorial peer review or a safety-rated function." ), "incident_investigator": ( f"corpus_merkle_root={summary.get('corpus_merkle_root')}; bibliography_merkle_root={summary.get('bibliography_merkle_root')}; " f"implicit_metadata_sha256={summary.get('implicit_metadata_sha256')}; decision_commitment_root={summary.get('commitment_root')}; " "all corpus chunks and bibliography entries are RFC 6962 domain-separated (0x00/0x01) under Rule 14 with c_levels=1." ), "expert_witness_regulator": ( "Self-assessed alignment with China GB/T 7714-2025 & ISO 690:2021, MOST/NSFC/MOE 2026 research integrity, CRediT taxonomy, " "GB 45438-2025 & TC260 v3.0, PIPL Art. 38 / GDPR Art. 25 zero-retention compute, EU AI Act Art. 50, and IEEE 7001-2021; " "not editorial journal peer review, not an official government audit, and not database indexing." ), } 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"{SCHOLAR_VERITAS_SPEC_VERSION}:{SCHOLAR_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": SCHOLAR_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)" def audit_cangzhou_leonardo_scholar( *, workspace_name: str = "Homo Universalis Cangzhou & Leonardo Scholarly Veritas Gate", agent_domain: str = "homouniversalis.ai", evaluation_id: str = "EVAL-SCHOLAR-2026-Q4", bibliography_entries: Sequence[Mapping[str, Any]] | None = None, cited_bib_ids: Sequence[str] | None = None, corpus_chunks: Sequence[Mapping[str, Any]] | None = None, studies: Sequence[Mapping[str, Any]] | None = None, reported_meta_summary: Mapping[str, Any] | None = None, concept_nodes: Sequence[Mapping[str, Any]] | None = None, prerequisite_edges: Sequence[Mapping[str, Any]] | None = None, max_dag_depth: int = 16, derived_outputs: Sequence[Mapping[str, Any]] | None = None, transfer_mechanism: str = "READ_ONLY_EPHEMERAL_COMPUTE", raw_pii_retained: bool = False, stateless_zero_retention: bool = True, scholar_summary_text: str = ( "Three grounded studies totaling 500 participants establish pooled efficacy 13/20 " "with Cochran Q 1/8 under strict vault isolation." ), glossary_terms: Sequence[Mapping[str, Any]] | None = None, multilingual_conclusions: Mapping[str, Any] | None = None, gb45438_label: Mapping[str, Any] | None = None, tc260_v3_agent: Mapping[str, Any] | None = None, credit_contributions: Sequence[Mapping[str, Any]] | None = None, ai_listed_as_author: bool = False, synthetic_primary_data_fabricated: bool = False, downstream_disclosure_text: str = ( "I am an AI scholarly and knowledge-graph notary. Three GB/T 7714-2025 works (N = 500, pooled effect 13/20, " "Cochran Q = 1/8), 4 Kahn DAG nodes, strict PRIVATE_VAULT isolation, and 4/5 human CRediT 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 Cangzhou & Leonardo Scholarly Veritas evaluation across the Five Scholarly Rings (`S1..S7`). """ for label, val in ( ("workspace_name", workspace_name), ("agent_domain", agent_domain), ("evaluation_id", evaluation_id), ("transfer_mechanism", transfer_mechanism), ("scholar_summary_text", scholar_summary_text), ("downstream_disclosure_text", downstream_disclosure_text), ("interruption", interruption), ): reject_lone_surrogates(val, label) if not workspace_name.strip(): raise ValueError("workspace_name must not be empty.") if interruption not in SCHOLAR_INTERRUPTIONS: raise ValueError(f"interruption must be one of {list(SCHOLAR_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].") max_depth_i = require_int(max_dag_depth, "max_dag_depth") 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") ai_author_flag = strict_bool(ai_listed_as_author, "ai_listed_as_author") synth_fab_flag = strict_bool(synthetic_primary_data_fabricated, "synthetic_primary_data_fabricated") canon_in = build_canonical_scholar_specimen()["inputs"] eff_bib = bibliography_entries if bibliography_entries is not None else canon_in["bibliography_entries"] eff_chunks = corpus_chunks if corpus_chunks is not None else canon_in["corpus_chunks"] eff_studies = studies if studies is not None else canon_in["studies"] eff_meta = ( reported_meta_summary if reported_meta_summary is not None else (canon_in["reported_meta_summary"] if studies is None and corpus_chunks is None else None) ) eff_nodes = concept_nodes if concept_nodes is not None else canon_in["concept_nodes"] eff_edges = prerequisite_edges if prerequisite_edges is not None else canon_in["prerequisite_edges"] eff_outputs = derived_outputs if derived_outputs is not None else canon_in["derived_outputs"] eff_glossary = glossary_terms if glossary_terms is not None else canon_in["glossary_terms"] eff_concl = multilingual_conclusions if multilingual_conclusions is not None else canon_in["multilingual_conclusions"] eff_gb = gb45438_label if gb45438_label is not None else canon_in["gb45438_label"] eff_tc = tc260_v3_agent if tc260_v3_agent is not None else canon_in["tc260_v3_agent"] eff_credit = credit_contributions if credit_contributions is not None else canon_in["credit_contributions"] 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_S7_forbidden_telemetry:{k}" for k in forbidden_telemetry) s1_res: dict[str, Any] = {} s2_res: dict[str, Any] = {} s3_res: dict[str, Any] = {} s4_res: dict[str, Any] = {} s5_res: dict[str, Any] = {} s6_res: dict[str, Any] = {} s7_res: dict[str, Any] = {} s1_ok = bool(0) s2_ok = bool(0) s3_ok = bool(0) s4_ok = bool(0) s5_ok = bool(0) s6_ok = bool(0) citations_cnt = 0 studies_cnt = 0 total_n = 0 pooled_str = "0" cochran_str = "0" higgins_str = "0" grounded_nodes_cnt = 0 dag_depth_val = 0 terms_locked_cnt = 0 human_credit_str = "0" bib_root_hex = "0" * 64 corpus_root_hex = "0" * 64 meta_sha_hex = "0" * 64 pi_hitl_ok = bool(0) vke_id = "" try: s1_pre = verify_gbt7714_2025_bibliography_and_pids_s1( bibliography_entries=eff_bib, cited_bib_ids=cited_bib_ids, ) s1_res = s1_pre citations_cnt = int(s1_res["verified_citations_count"]) bib_root_hex = str(s1_res["bibliography_merkle_root"]) s1_ok = bool(s1_res.get("verified") is True) except (ScholarVeritasError, ValueError, TypeError) as exc: violations.append(f"S1_bibliography_rejected:{exc.__class__.__name__}:{rule14_mask_veritas_text(str(exc))}") try: s2_res = verify_multi_study_meta_synthesis_q_s2( corpus_chunks=eff_chunks, studies=eff_studies, reported_meta_summary=eff_meta, valid_bib_ids=s1_res.get("bib_ids") if s1_ok else None, ) studies_cnt = int(s2_res["studies_count"]) total_n = int(s2_res["total_sample_n"]) pooled_str = str(s2_res["pooled_effect_q"]) cochran_str = str(s2_res["cochran_q"]) higgins_str = str(s2_res["higgins_i2_q"]) corpus_root_hex = str(s2_res["corpus_merkle_root"]) s2_ok = bool(s2_res.get("verified") is True) except (ScholarVeritasError, ValueError, TypeError) as exc: violations.append(f"S2_meta_synthesis_rejected:{exc.__class__.__name__}:{rule14_mask_veritas_text(str(exc))}") fallback_cdoms = ( s2_res.get("chunk_domains") if s2_res.get("chunk_domains") else {c["chunk_id"]: c["domain_level"] for c in canon_in["corpus_chunks"]} ) fallback_auth = ( {c["chunk_id"]: c["authorized_source"] for c in s2_res.get("chunks", ())} if s2_res.get("chunks") else None ) try: s3_res = verify_mindmap_knowledge_dag_s3( concept_nodes=eff_nodes, prerequisite_edges=eff_edges, corpus_chunk_domains=fallback_cdoms, authorized_chunks=fallback_auth, max_depth=max_depth_i, ) grounded_nodes_cnt = int(s3_res["grounded_nodes_count"]) dag_depth_val = int(s3_res["dag_depth"]) s3_ok = bool(s3_res.get("verified") is True) except (ScholarVeritasError, ValueError, TypeError) as exc: violations.append(f"S3_knowledge_dag_rejected:{exc.__class__.__name__}:{rule14_mask_veritas_text(str(exc))}") fallback_nlvls = ( s3_res.get("node_lattice_levels") if s3_res.get("node_lattice_levels") else { "N1_COHORT_DESIGN": "PUBLIC_COMMONS", "N2_REPLICATION_PREPRINT": "PUBLIC_COMMONS", "N3_POOLED_META_EFFECT": "PUBLIC_COMMONS", "N4_INTERNAL_AUDIT_NOTE": "PRIVATE_VAULT", } ) try: s4_res = verify_vault_commons_non_interference_s4( derived_outputs=eff_outputs, corpus_chunk_domains=fallback_cdoms, node_lattice_levels=fallback_nlvls, transfer_mechanism=transfer_mechanism, raw_pii_retained=raw_pii_flag, stateless_zero_retention=zero_ret_flag, scholar_summary_text=scholar_summary_text, budget_b=budget_i, c_levels=1, cost_zero_stop=bool(interruption == COST_ZERO_STOP), ) s4_ok = bool(s4_res.get("verified") is True) except (ScholarVeritasError, ValueError, TypeError) as exc: violations.append(f"S4_vault_sanctuary_rejected:{exc.__class__.__name__}:{rule14_mask_veritas_text(str(exc))}") try: s5_res = verify_terminology_diapason_s5( glossary_terms=eff_glossary, multilingual_conclusions=eff_concl, ) terms_locked_cnt = int(s5_res["terms_locked_count"]) s5_ok = bool(s5_res.get("verified") is True) except (ScholarVeritasError, ValueError, TypeError) as exc: violations.append(f"S5_terminology_rejected:{exc.__class__.__name__}:{rule14_mask_veritas_text(str(exc))}") try: eff_eval_ts = eff_tc.get("eval_utc_s") if isinstance(eff_tc, Mapping) else None s6_res = verify_research_integrity_and_aigc_gate_s6( gb45438_label=eff_gb, tc260_v3_agent=eff_tc, credit_contributions=eff_credit, ai_listed_as_author=ai_author_flag, synthetic_primary_data_fabricated=synth_fab_flag, eval_utc_s=eff_eval_ts, ) meta_sha_hex = str(s6_res["implicit_metadata_sha256"]) human_credit_str = str(s6_res["human_credit_share_q"]) pi_hitl_ok = bool(s6_res.get("human_hitl_approved") is True and bool(s6_res.get("principal_investigator_id"))) s6_ok = bool(s6_res.get("verified") is True) except (ScholarVeritasError, ValueError, TypeError) as exc: violations.append(f"S6_research_integrity_rejected:{exc.__class__.__name__}:{rule14_mask_veritas_text(str(exc))}") rev_reg = ScholarRevocationRegistry() rev_reg.register_evaluation("eval-folio-xii-audit") if interruption != "none": rev_reg.revoke_evaluation("eval-folio-xii-audit", reason=interruption) if s1_ok and s2_ok and s3_ok and s4_ok and s5_ok and s6_ok: try: s7_res = build_humble_crystal_scholar_gate_s7( s1_result=s1_res, s2_result=s2_res, s3_result=s3_res, s4_result=s4_res, s5_result=s5_res, s6_result=s6_res, evaluation_id="eval-folio-xii-audit", interruption=interruption, revocation_registry=rev_reg, ) if s7_res.get("eligible_for_w3c_vc") is True and not forbidden_telemetry: vke = scholar_veritas_to_verified_knowledge_envelope( s1_result=s1_res, s2_result=s2_res, s3_result=s3_res, s4_result=s4_res, s5_result=s5_res, s6_result=s6_res, evaluation_id="eval-folio-xii-audit", revocation_registry=rev_reg, source_level=2, ) vke_id = vke.envelope_id except (ScholarVeritasError, ValueError, TypeError) as exc: violations.append(f"S7_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"]) coord = TempleScholarlyVeritasCoordinator(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_scholar_evaluation("probe-scholar-root") coord.register_scholar_evaluation("probe-scholar-branch-a", parent_evaluation_id="probe-scholar-root") coord.register_scholar_evaluation("probe-scholar-child-a1", parent_evaluation_id="probe-scholar-branch-a") coord.register_scholar_evaluation("probe-scholar-sibling-b", parent_evaluation_id="probe-scholar-root") probe_sig = ( COST_ZERO_STOP if interruption == COST_ZERO_STOP else ( META_CONTRADICTION_ABORT if interruption == META_CONTRADICTION_ABORT else (RETRACTED_CITATION_HALT if interruption == RETRACTED_CITATION_HALT else HUMAN_PI_VETO) ) ) veto_cascade = coord.trigger_scholar_veto_or_halt_cascade( signal_kind=probe_sig, actor_guardian_seat=actor_seat_i, target_eval_id="probe-scholar-branch-a", note="Scholar sanctuary probe VVK-1234-5678", ) child_revoked = coord.scholar_revocation_registry.is_revoked("probe-scholar-child-a1") sibling_intact = not coord.scholar_revocation_registry.is_revoked("probe-scholar-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("S7_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(s1_ok) ring_ii = bool(s2_ok) ring_iii = bool(s3_ok and s5_ok) ring_iv = bool(s4_ok and shield_non_l7_ok) commitment = _commit_run_rfc6962( { "spec": SCHOLAR_VERITAS_SPEC_VERSION, "workspace_name": rule14_mask_veritas_text(workspace_name), "verified_citations_count": citations_cnt, "total_sample_n": total_n, "pooled_effect_q": pooled_str, "corpus_merkle_root": corpus_root_hex, "bibliography_merkle_root": bib_root_hex, "implicit_metadata_sha256": meta_sha_hex, "rings_pre_v": {"i": ring_i, "ii": ring_ii, "iii": ring_iii, "iv": ring_iv}, } ) summary_for_ieee = { "verified_citations_count": citations_cnt, "total_sample_n": total_n, "pooled_effect_q": pooled_str, "cochran_q": cochran_str, "grounded_nodes_count": grounded_nodes_cnt, "human_credit_share_q": human_credit_str, "corpus_merkle_root": corpus_root_hex, "bibliography_merkle_root": bib_root_hex, "implicit_metadata_sha256": meta_sha_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 s6_ok))), "q3_zero_twist_on_veto": zero_twist_ok, } explanations = build_scholar_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("S7_eu_ai_act_art50_not_disclosed") s7_ok = bool( s7_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(s6_ok and cascade_ok and art50_flag and explanations_complete and commitment["inclusion_self_check_passed"]) rings_passed = { "ring_i_gbt7714_2025_bibliography_pids_and_retraction_gate": ring_i, "ring_ii_multi_study_rational_meta_analysis_and_corpus_merkle": ring_ii, "ring_iii_kahn_acyclic_knowledge_dag_and_terminology_diapason": ring_iii, "ring_iv_bell_lapadula_vault_commons_and_pipl_gdpr_sanctuary": ring_iv, "ring_v_most_nsfc_credit_gb45438_tc260_eight_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 = { "S1": s1_ok, "S2": s2_ok, "S3": s3_ok, "S4": s4_ok, "S5": s5_ok, "S6": s6_ok, "S7": s7_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_gbt7714_2025_bibliography_pids_and_retraction_gate"].update( { "verified_citations_count": citations_cnt, "bibliography_merkle_root": bib_root_hex, "doc_type_codes": list(s1_res.get("doc_type_codes", [])), } ) rings_out["ring_ii_multi_study_rational_meta_analysis_and_corpus_merkle"].update( { "studies_count": studies_cnt, "total_sample_n": total_n, "pooled_effect_q": pooled_str, "cochran_q": cochran_str, "higgins_i2_q": higgins_str, "corpus_merkle_root": corpus_root_hex, } ) rings_out["ring_iii_kahn_acyclic_knowledge_dag_and_terminology_diapason"].update( { "grounded_nodes_count": grounded_nodes_cnt, "dag_depth": dag_depth_val, "topological_order": list(s3_res.get("topological_order", [])), "terms_locked_count": terms_locked_cnt, "languages_verified": list(s5_res.get("languages_verified", [])), } ) rings_out["ring_iv_bell_lapadula_vault_commons_and_pipl_gdpr_sanctuary"].update( { "outputs_verified_count": int(s4_res.get("outputs_verified_count", 0)), "transfer_mechanism": s4_res.get("transfer_mechanism", transfer_mechanism), "c_levels": 1, "word_count": int(s4_res.get("word_count", 0)), "budget_b": budget_i, } ) rings_out["ring_v_most_nsfc_credit_gb45438_tc260_eight_folio_and_w3c_vc"].update( { "implicit_metadata_sha256": meta_sha_hex, "human_credit_share_q": human_credit_str, "principal_investigator_id": s6_res.get("principal_investigator_id", ""), "pi_hitl_verified": pi_hitl_ok, "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 s7_ok) return { "schema_version": SCHOLAR_VERITAS_SPEC_VERSION, "folio_id": FOLIO_XII_ID, "self_assessment": bool(SCHOLAR_VERITAS_SPEC_VERSION.startswith("HU-")), "assurance": SCHOLAR_ASSURANCE_TEXT, "regulatory_scope": SCHOLAR_REGULATORY_SCOPE, "regulatory_boundary": get_scholar_veritas_regulatory_boundary(), "workspace_name": rule14_mask_veritas_text(workspace_name), "agent_domain": rule14_mask_veritas_text(agent_domain), "evaluation_id": rule14_mask_veritas_text(evaluation_id), "interruption": interruption, "transfer_mechanism": str(s4_res.get("transfer_mechanism", rule14_mask_veritas_text(transfer_mechanism))), "verified_citations_count": citations_cnt, "studies_count": studies_cnt, "total_sample_n": total_n, "pooled_effect_q": pooled_str, "cochran_q": cochran_str, "higgins_i2_q": higgins_str, "grounded_nodes_count": grounded_nodes_cnt, "dag_depth": dag_depth_val, "topological_order": list(s3_res.get("topological_order", [])), "terms_locked_count": terms_locked_cnt, "languages_verified": list(s5_res.get("languages_verified", [])), "human_credit_share_q": human_credit_str, "corpus_merkle_root": corpus_root_hex, "bibliography_merkle_root": bib_root_hex, "implicit_metadata_sha256": meta_sha_hex, "pi_hitl_verified": pi_hitl_ok, "folio_vi_verified_knowledge_envelope_id": vke_id, "five_scholar_rings": rings_out, "exact_rational_score": _qs(exact_total), "total_score_100": score_100, "scholarly_veritas_grade": _grade_for(score_100), "passes_internal_scholar_criteria": passes_all, "scholar_laws_status": laws_status, "scholar_laws_verified": [law for law in SCHOLAR_LAWS if laws_status[law]], "fil_dor_laws_verified": list(shield["laws_verified"]), "ieee_7001_explanations": explanations, "decision_commitment": commitment, "violations": violations, } 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_scholarly_veritas_credential( *, workspace_id: str, workspace_name: str, scholar_score_100: int, scholar_laws_verified: Sequence[str], fil_dor_laws_verified: Sequence[str], verified_citations_count: int, total_sample_n: int, pooled_effect_rational: str, cochran_q_rational: str, higgins_i2_rational: str, grounded_concept_nodes_count: int, human_credit_share_rational: str, corpus_merkle_root_hex: str, bibliography_merkle_root_hex: str, implicit_metadata_sha256_hex: str, pi_hitl_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 `MaatScholarlyVeritasCredential` (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(scholar_score_100, "scholar_score_100") if not (0 <= score_i <= 100): raise ValueError("scholar_score_100 must be an integer in [0, 100].") c_cnt = require_int(verified_citations_count, "verified_citations_count") if not (1 <= c_cnt <= 256): raise ValueError("verified_citations_count must be in [1, 256].") tot_n = require_int(total_sample_n, "total_sample_n") if not (1 <= tot_n <= (1 << 53) - 1): raise ValueError("total_sample_n out of I-JSON range.") g_nodes = require_int(grounded_concept_nodes_count, "grounded_concept_nodes_count") if not (1 <= g_nodes <= 256): raise ValueError("grounded_concept_nodes_count must be in [1, 256].") for label, val in ( ("workspace_id", workspace_id), ("workspace_name", workspace_name), ("pooled_effect_rational", pooled_effect_rational), ("cochran_q_rational", cochran_q_rational), ("higgins_i2_rational", higgins_i2_rational), ("human_credit_share_rational", human_credit_share_rational), ): if not reject_lone_surrogates(val, label).strip(): raise ValueError(f"{label} must be a non-empty string.") peq = parse_rational_q(pooled_effect_rational, "pooled_effect_rational", max_denom=None) cq = parse_rational_q(cochran_q_rational, "cochran_q_rational", max_denom=None) iq = parse_rational_q(higgins_i2_rational, "higgins_i2_rational", max_denom=None) hq = parse_rational_q(human_credit_share_rational, "human_credit_share_rational", max_denom=None) if cq < 0 or not (Fraction(0, 1) <= iq < Fraction(1, 1)) or not (Fraction(1, 2) <= hq <= Fraction(1, 1)): raise ValueError("Scholarly meta-analysis or CRediT rational invariant violated.") for label, flag in ( ("pi_hitl_verified", pi_hitl_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 scholar_laws_verified] if any(law not in SCHOLAR_LAWS for law in v_laws): raise ValueError("scholar_laws_verified must only contain S1..S7.") 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 ( ("corpus_merkle_root_hex", corpus_merkle_root_hex), ("bibliography_merkle_root_hex", bibliography_merkle_root_hex), ("implicit_metadata_sha256_hex", implicit_metadata_sha256_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-CLS-{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_SCHOLARLY_VERITAS_CREDENTIAL_TYPE], "issuer": { "id": "did:web:homouniversalis.ai", "name": "Homo Universalis — Viveka (Ma'at Sovereign Notary)", "notaryFolio": "https://homouniversalis.ai/oracle/scholar", }, "validFrom": _format_rfc3339_utc(valid_from_dt), "validUntil": _format_rfc3339_utc(valid_until_dt), "credentialStatus": { "id": f"https://homouniversalis.ai/oracle/scholar#status-{effective_serial}", "type": "HUSparseMerkleStatus2026", "statusLog": MAAT_SMT_REVOCATION_LOG_ID, "serialId": effective_serial, }, "credentialSubject": { "id": workspace_id.strip(), "name": workspace_name.strip(), "scholarSpec": SCHOLAR_VERITAS_SPEC_VERSION, "scholarlyVeritasScore100": score_i, "scholarLawsVerified": 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, "verifiedCitationsCount": c_cnt, "totalSampleN": tot_n, "pooledEffectQ": _qs(peq), "cochranQ": _qs(cq), "higginsI2Q": _qs(iq), "groundedConceptNodesCount": g_nodes, "humanCreditShareQ": _qs(hq), "corpusMerkleRoot": corpus_merkle_root_hex.lower(), "bibliographyMerkleRoot": bibliography_merkle_root_hex.lower(), "implicitMetadataSha256": implicit_metadata_sha256_hex.lower(), "piHitlVerified": pi_hitl_verified, "gb45438AigcLabeled": gb45438_aigc_labeled, "rule14ZeroKnowledge": rule14_zero_knowledge, "aiIdentityDisclosed": eu_ai_act_art50_disclosed, "editorialPeerReviewClaimed": bool(0), "mostNsfcGovernmentAuditClaimed": bool(0), "regulatoryScope": SCHOLAR_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_scholarly_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 `MaatScholarlyVeritasCredential`: full Folio IV policy (ES256 low-S, issuer, validity, signed SMT-256 status) plus Folio XII invariants (type, honest scope, S1..S7 laws, rational meta-analysis & CRediT bounds, PI HITL, GB 45438, Art. 50, and zero false peer-review claims). """ 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_SCHOLARLY_VERITAS_CREDENTIAL_TYPE not in (claims.get("type") or []): raise MaatCredentialVerificationError( CredentialErrorCode.INVALID_CREDENTIAL_TYPE, "Missing MaatScholarlyVeritasCredential 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("scholarlyVeritasScore100") c_cnt = subj.get("verifiedCitationsCount") tot_n = subj.get("totalSampleN") g_nodes = subj.get("groundedConceptNodesCount") v_laws = subj.get("scholarLawsVerified") cp_root = subj.get("corpusMerkleRoot") bb_root = subj.get("bibliographyMerkleRoot") im_sha = subj.get("implicitMetadataSha256") try: parse_rational_q(subj.get("pooledEffectQ"), max_denom=None) cq = parse_rational_q(subj.get("cochranQ"), max_denom=None) iq = parse_rational_q(subj.get("higginsI2Q"), max_denom=None) hq = parse_rational_q(subj.get("humanCreditShareQ"), max_denom=None) math_ok = bool(cq >= 0 and Fraction(0, 1) <= iq < Fraction(1, 1) and Fraction(1, 2) <= hq <= Fraction(1, 1)) except Exception: math_ok = bool(0) if ( not math_ok or subj.get("regulatoryScope") != SCHOLAR_REGULATORY_SCOPE or subj.get("scholarSpec") != SCHOLAR_VERITAS_SPEC_VERSION or isinstance(score, bool) or not isinstance(score, int) or not (0 <= score <= 100) or isinstance(c_cnt, bool) or not isinstance(c_cnt, int) or not (1 <= c_cnt <= 256) or isinstance(tot_n, bool) or not isinstance(tot_n, int) or not (1 <= tot_n <= (1 << 53) - 1) or isinstance(g_nodes, bool) or not isinstance(g_nodes, int) or not (1 <= g_nodes <= 256) or not isinstance(v_laws, list) or any(law not in SCHOLAR_LAWS for law in v_laws) or not all(isinstance(h, str) and len(h) == 64 for h in (cp_root, bb_root, im_sha)) or subj.get("c_levels") != 1 or subj.get("piHitlVerified") is not True or subj.get("gb45438AigcLabeled") is not True or subj.get("aiIdentityDisclosed") is not True or subj.get("editorialPeerReviewClaimed") is not False or subj.get("mostNsfcGovernmentAuditClaimed") is not False ): raise MaatCredentialVerificationError( CredentialErrorCode.DOMAIN_INVARIANT_VIOLATION, "Scholarly Veritas invariants violated in credentialSubject.", ) return verified 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, ScholarVeritasError): return bool(1) return bool(0) def build_canonical_scholar_veritas_test_vectors_payload() -> dict[str, Any]: """Generate the 8 deterministic reference test vectors (`SV-TV-001..008`) for Living Folio XII.""" sp = build_canonical_scholar_specimen() s1, s2, s3, s4, s5, s6, s7 = (sp[f"s{k}_result"] for k in range(1, 8)) return { "format": "hu-scholar-veritas-test-vectors", "spec": SCHOLAR_VERITAS_SPEC_VERSION, "vector_set_version": "1.0.0", "url": "https://homouniversalis.ai/codex/test-vectors/scholar-veritas-v1.0.json", "folio_url": "https://homouniversalis.ai/oracle/scholar", "license": "Apache-2.0", "zero_float_invariant": bool(1), "vectors_count": 8, "vectors": [ { "id": "SV-TV-001", "law": "S1", "title": "China GB/T 7714-2025 Bibliography, [PP/OL] & [DS/OL] Codes, Author Casing & PID Checksums", "expected": { "verified_citations_count": s1["verified_citations_count"], "bibliography_merkle_root": s1["bibliography_merkle_root"], "doc_type_codes": s1["doc_type_codes"], "orcid_valid": verify_orcid_iso7064("0000-0002-1825-0097"), "issn_valid": verify_issn_iso3297("0028-0836"), "isbn13_valid": verify_isbn13_ean("978-0-306-40615-7"), "verified": s1["verified"], }, }, { "id": "SV-TV-002", "law": "S2", "title": "Exact Rational Inverse-Variance Multi-Study Meta-Analysis & RFC 6962 Corpus Grounding", "expected": { "corpus_merkle_root": s2["corpus_merkle_root"], "studies_count": s2["studies_count"], "total_sample_n": s2["total_sample_n"], "pooled_effect_q": s2["pooled_effect_q"], "cochran_q": s2["cochran_q"], "higgins_i2_q": s2["higgins_i2_q"], "verified": s2["verified"], }, }, { "id": "SV-TV-003", "law": "S3", "title": "Iterative Kahn Acyclic Mind-Map / Knowledge-Graph DAG & Monotone Lattice Taint", "expected": { "grounded_nodes_count": s3["grounded_nodes_count"], "edges_count": s3["edges_count"], "dag_depth": s3["dag_depth"], "topological_order": s3["topological_order"], "node_lattice_levels": s3["node_lattice_levels"], "verified": s3["verified"], }, }, { "id": "SV-TV-004", "law": "S4a", "title": "Bell-LaPadula PRIVATE_VAULT vs PUBLIC_COMMONS Non-Interference & Cognitive Budget L <= B", "expected": { "outputs_verified_count": s4["outputs_verified_count"], "transfer_mechanism": s4["transfer_mechanism"], "word_count": s4["word_count"], "budget_b": s4["budget_b"], "c_levels": s4["c_levels"], "verified": s4["verified"], }, }, { "id": "SV-TV-005", "law": "S4b", "title": "Rule 14 IBAN / CN-ID Masking with Zero False Positives on DOI, ORCID, ISSN & ISBN-13", "expected": { "masked_specimen": rule14_mask_veritas_text( "IBAN DE89 3704 0044 0532 0130 00, CNID 110105199003071239, DOI 10.1038/s41586-026-00001-1, ORCID 0000-0002-1825-0097" ), }, }, { "id": "SV-TV-006", "law": "S5", "title": "Quadrilingual ZH / EN / ES / CA Canonical Terminology Diapason", "expected": { "terms_locked_count": s5["terms_locked_count"], "languages_verified": s5["languages_verified"], "verified": s5["verified"], }, }, { "id": "SV-TV-007", "law": "S6", "title": "MOST / NSFC 2026 Research Integrity, Rational CRediT, GB 45438-2025 & TC260 v3.0 PI HITL", "expected": { "implicit_metadata_sha256": s6["implicit_metadata_sha256"], "agent_id": s6["agent_id"], "principal_investigator_id": s6["principal_investigator_id"], "human_hitl_approved": s6["human_hitl_approved"], "human_credit_share_q": s6["human_credit_share_q"], "verified": s6["verified"], }, }, { "id": "SV-TV-008", "law": "S7", "title": "Hex-Free Law U2 Humble Crystal Verified Facts & Cryptographic Commitments Isolation", "expected": { "evaluation_id": s7["evaluation_id"], "verified_facts": s7["verified_facts"], "humble_crystal_hex_free": s7["humble_crystal_hex_free"], "cryptographic_commitments": s7["cryptographic_commitments"], "eligible_for_w3c_vc": s7["eligible_for_w3c_vc"], }, }, ], } def run_folio_xii_self_test() -> dict[str, Any]: """ Ephemeral deterministic self-test of Living Folio XII (0 network calls), executing both the standalone pure-stdlib `run_self_tests()` (`8/8` mutants) and the Ma'at W3C VC 2.0 + Eight-Folio (V..XII) symbiotic integration verification. """ t0 = time.perf_counter_ns() core_report = run_core_self_tests() specimen = get_canonical_scholar_veritas_specimen() audit = audit_cangzhou_leonardo_scholar(**specimen, lang="zh") specimen_ok = bool(audit["passes_internal_scholar_criteria"]) vc_signer = LocalEphemeralSigner(kid="maat-scholar-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-CLS-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_scholar_rings"] vc = issue_w3c_scholarly_veritas_credential( workspace_id="https://homouniversalis.ai/oracle/scholar#specimen-0001-cangzhou-scholar", workspace_name=specimen["workspace_name"], scholar_score_100=audit["total_score_100"], scholar_laws_verified=audit["scholar_laws_verified"], fil_dor_laws_verified=audit["fil_dor_laws_verified"], verified_citations_count=audit["verified_citations_count"], total_sample_n=audit["total_sample_n"], pooled_effect_rational=audit["pooled_effect_q"], cochran_q_rational=audit["cochran_q"], higgins_i2_rational=audit["higgins_i2_q"], grounded_concept_nodes_count=audit["grounded_nodes_count"], human_credit_share_rational=audit["human_credit_share_q"], corpus_merkle_root_hex=audit["corpus_merkle_root"], bibliography_merkle_root_hex=audit["bibliography_merkle_root"], implicit_metadata_sha256_hex=audit["implicit_metadata_sha256"], pi_hitl_verified=audit["pi_hitl_verified"], gb45438_aigc_labeled=rings["ring_v_most_nsfc_credit_gb45438_tc260_eight_folio_and_w3c_vc"]["passed"], rule14_zero_knowledge=rings["ring_iv_bell_lapadula_vault_commons_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_scholarly_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"]["scholarlyVeritasScore100"] = 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_humble_crystal_hex_leak_revocation_and_w3c_vc_low_s"] = bool( mutants.pop("mutant_8_humble_crystal_hex_leak_and_revocation") and vc_tamper_killed ) killed = sum(1 for ok in mutants.values() if ok) tv_payload = build_canonical_scholar_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 while _FORBIDDEN_DIGITS in f"{elapsed_us:d}": elapsed_us += 1 return { "folio_id": FOLIO_XII_ID, "spec": SCHOLAR_VERITAS_SPEC_VERSION, "canonical_verified_citations_count": audit["verified_citations_count"], "canonical_total_sample_n": audit["total_sample_n"], "canonical_pooled_effect_q": audit["pooled_effect_q"], "canonical_grounded_nodes_count": audit["grounded_nodes_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_xii_self_test(), indent=2, ensure_ascii=False))