# SPDX-FileCopyrightText: 2026 David Porto Baraldés (Homo Universalis / Viveka) # SPDX-License-Identifier: Apache-2.0 """Living Folio XI (`logic/veritas/pacioli_veritas_core.py`): HU-VERITAS-PACIOLI-OFFICE v1.0 pure-stdlib kernel.""" from __future__ import annotations import collections, hashlib, hmac, json, re, time from collections.abc import Mapping, Sequence from fractions import Fraction PROTOCOL_ID, PROTOCOL_VERSION, LIVING_FOLIO, SACRED_EQUATION = "HU-VERITAS-PACIOLI-OFFICE 1.0 folio-XI-pacioli-veritas-office F0c=Ca0s*0rdre(Am0r_Un1f1cat_Etern)".split() _, HUMAN_CFO_VETO, UNBALANCED_LEDGER_ABORT, HALLUCINATION_GROUNDING_HALT, COST_ZERO_STOP = PACIOLI_INTERRUPTIONS = (*"none human_cfo_veto unbalanced_ledger_abort hallucination_grounding_halt cost_zero_stop".split(),) REVOCATION_REASONS = frozenset(PACIOLI_INTERRUPTIONS[1:]) _T, _F, _U, _FD, _DB, _JM, _QB, _MD = bool(1), bool(0), object(), f"{21}{6}", 10**500, 9007199254740991, 65536, 262144 _BAD = (float, complex, bytes, bytearray, memoryview, range, collections.UserString) _CFG = json.loads(r'''{"up":["[\\ud800-\\udfff]","[\\x00-\\x1f\\x7f-\\x9f]","[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f-\\x9f]","\\([ \\t]*(?:[A-Z]{3}[ \\t]+|[$€£¥][ \\t]*)?\\Z","^[ \\t]*(?:[A-Z]{3}|[$€£¥])?[ \\t]*\\)","[^0-9a-z]+","(?(),;\\[\\]]*[A-Za-z0-9_/-]|\\\\\\\\[A-Za-z0-9_.-]+\\\\(?:[A-Za-z0-9_$-][A-Za-z0-9_$.-]*\\\\)*[A-Za-z0-9_$.-]+(?= lo, v, e0), e1) def _rhex(v, e=ValueError): return _ck(_HEX_P.match(s := _s(v)) is not None, s, e) def _nmap(m, e=ValueError, mx=_MD): out = {_s(k): v for k, v in _ck(isinstance(m, Mapping), m, TypeError).items()} return _ck(len(out) == len(m) <= mx, out, e) def _cmap(m, req, opt="", e=ValueError): rt, al = {*_sp(req)}, {*_sp(req), *_sp(opt)} return _ck(rt <= set(out := _nmap(m, e, len(al))) <= al, out, e) def _unp(m, req, opt="", defs=(), e=ValueError): mp, df = _cmap(m, req, opt, e), dict(zip(ot := _sp(opt), defs)) return [mp[k] for k in _sp(req)] + [mp.get(k, df.get(k)) for k in ot] def _rspec(a, kw, req, opt="", defs=(), e=ValueError): rt, ot, ks = _sp(req), _sp(opt), set(kw) ak = (*rt, *ot) if len(a) == 1 and isinstance(a[0], Mapping) and (not a[0] or {*ak} & set(a[0])): mp = _ck(ks <= {*ot} and ks.isdisjoint(d := _cmap(a[0], rt, ot, e)), d, e) else: mp = _ck(len(a) <= len(ak) and ks <= {*ak} and ks.isdisjoint(d := dict(zip(ak, a))), d, TypeError) bd = dict(zip(ot, defs)) | mp | kw return _ck({*rt} <= set(bd), [*map(bd.get, ak)], TypeError) def _qbits(q, e=PacioliVeritasError): return _ck(max(abs(q.numerator).bit_length(), q.denominator.bit_length()) <= _QB, q, e) def _qsum(qs, e=PacioliVeritasError): return _qbits(sum(qs, Fraction(0)), e) def _d2u(ds): a = int(ds[:r]) if (r := len(ds) % 500) else 0 for i in range(r, len(ds), 500): a = a * _DB + int(ds[i : i + 500]) return a def _i2a(n): u, cs = abs(iv := require_int(n)), [] while u >= _DB: u, r = divmod(u, _DB) cs.append(f"{r:0500d}") return ("-" if iv < 0 else "") + str(u) + "".join(cs[::-1]) def fraction_to_str(q): _rq(not isinstance(q, bool) and isinstance(q, (Fraction, int)), TypeError) qn = Fraction(require_int(q)) if isinstance(q, int) else Fraction(require_int(q.numerator), _irng(q.denominator, 1, 1 << _QB)) return _i2a(qn.numerator) if qn.denominator == 1 else f"{_i2a(qn.numerator)}/{_i2a(qn.denominator)}" def parse_rational_q(v, name=None, *, max_denom=1_000_000_000, max_num_factor=1_000_000_000_000_000_000): _rq(not isinstance(v, (bool, float, complex)), TypeError) mnf, md = _irng(max_num_factor, 1, 1 << _QB), (None if max_denom is None else _irng(max_denom, 1, 1 << _QB)) if isinstance(v, (Fraction, int)): q = Fraction(_ck(abs(iv := int.__index__(v)) <= mnf if md is not None else abs(iv).bit_length() <= _QB, iv)) if isinstance(v, int) else Fraction(require_int(v.numerator), _irng(v.denominator, 1, 1 << (_QB + 64))) else: sg, bd = (-1 if (s := _ck(1 <= len(rs := _s(v)) <= (8192 if md is None else 128) and _Q_P.match(rs) is not None, rs))[0] == "-" else 1), s.lstrip("+-") a, *b = bd.split("/" if "/" in bd else ".") q = Fraction(sg * _d2u(a), _d2u(b[0])) if "/" in bd else (Fraction(sg * _d2u(a + b[0]), 10 ** len(b[0])) if b else Fraction(sg * _d2u(a))) return _ck(q.denominator <= md and abs(q.numerator) <= mnf * md, q) if md is not None else _qbits(q, ValueError) def _pu(v): return parse_rational_q(v, max_denom=None) def _jesc(s): return b'"' + _JESC_P.sub(lambda m: _JESC_M.get(ord(m.group(0))) or f"\\u{ord(m.group(0)):04x}", s).encode() + b'"' def jcs_canonical_bytes(obj): act, seen, bg = set(), set(), [0, 0] def _enc(v, d): if v is None or type(v) is bool: return b"null" if v is None else (b"true" if v else b"false") _rq(not isinstance(v, _BAD) and isinstance(v, (int, str, Mapping, Sequence)), TypeError) if isinstance(v, (int, str)): return f"{_irng(v, -_JM, _JM):d}".encode() if isinstance(v, int) else _jesc(_ck(len(ns := _s(v)) <= 524288, ns)) im, cid = isinstance(v, Mapping), id(v) its = sorted(_nmap(v, ValueError, _MD - bg[0] - 1).items(), key=lambda kv: kv[0].encode("utf-16-be")) if im else v bg[0], bg[1] = bg[0] + 1 + len(its), bg[1] + (len(its) if its and cid in seen else 0) seen.add(cid) act.add(_ck(d < 64 and cid not in act and bg[0] <= _MD and bg[1] <= 4096, cid)) body = b",".join((_jesc(_ck(len(k) <= 524288, k)) + b":" + _enc(val, d + 1) for k, val in its) if im else (_enc(x, d + 1) for x in its)) act.remove(cid) return (b"{" + body + b"}") if im else (b"[" + body + b"]") return _ck(len(res := _enc(obj, 0)) <= 4194304, res) def _jsha(obj): return _sha(jcs_canonical_bytes(obj)) def _cn_ok(s): return len(s) == 18 and _CNC[sum((ord(s[i]) - 48) * _CNW[i] for i in range(17)) % 11] == s[17].upper() def _ib_len(ps): return next((len(p) for j in range(len(ps), 0, -1) if _IBAN_P.fullmatch(p := " ".join(ps[:j])) and 15 <= len(c := p.replace(" ", "")) <= 34 and int("".join(str(int(ch, 36)) for ch in c[4:] + c[:4])) % 97 == 1), 0) def rule14_mask_veritas_text(text): s = _ck(len(ns := _s(text)) <= 524288, ns) for _ in range(16): nx = s for p, r in _R14_A: nx = p.sub(r, nx) if len(nx) >= 15 and not nx.islower(): out, pos = [], 0 while m := _IBAN_P.search(nx, pos): st, en, ps = m.start(), m.end(), m.group(0).split(" ") ml = 0 if (ps[1:] and ((_CNID_P.fullmatch(ps[1]) and _cn_ok(ps[1])) or _ib_len(ps[1:]))) else _ib_len(ps) sk = en if len(ps) == 1 else st + len(ps[0]) + 1 out.extend((nx[pos:st], "[iban-shielded]" if ml else nx[st:sk])) pos = st + ml if ml else sk nx = "".join((*out, nx[pos:])) nx = _CNID_P.sub(lambda m: "[cnid-shielded]" if _cn_ok(m.group(0)) else m.group(0), nx) if len(nx) >= 18 else nx for p, r in _R14_B: nx = p.sub(r, nx) if nx == s: return s s = nx return s def require_rule14_clean_identifier(val, name=None, len_err=ValueError): s = _ck(1 <= len(ns := _s(val)) <= 128 and ns == ns.strip(), ns, len_err) return _ck(_CTL_P.search(s) is None and _SHIELD_P.search(s) is None and rule14_mask_veritas_text(s) == s, s, Rule14IdentifierPIIError) _id = require_rule14_clean_identifier def _uid(v, seen, e=ValueError): seen.add(s := _ck((x := _id(v)) not in seen, x, e)) return s def _clean_dag(obj, hook=None, dag_err=ValueError): try: jcs_canonical_bytes(obj) except ValueError as exc: raise dag_err("dag") from exc def _cl(v): if isinstance(v, str): ns = _ck(rule14_mask_veritas_text(rs := _s(v)) == rs, rs, Rule14OutputSanctuaryError) hook(ns) if hook else None return ns if isinstance(v, (Mapping, Sequence)): return {_cl(k): _cl(val) for k, val in v.items()} if isinstance(v, Mapping) else [*map(_cl, v)] return v if v is None or type(v) is bool else int.__index__(v) return _cl(obj) def assert_output_rule14_clean(obj): return bool(_clean_dag(obj) is not _U) def _prose_ok(s): _rq(_PCTL_P.search(s) is None, PlaceholderDisclosureError) ws = [w for w in _WSPL_P.split(_NASL_P.sub("na", _SHIELD_P.sub(" ", s).strip().lower())) if w and w not in _PH_W and {*w} != {"x"}] al = [*filter(str.isalpha, "".join(ws))] _rq(len(al) >= 4 and len({*al}) >= 2 and " ".join(ws) not in _PH_W, PlaceholderDisclosureError) def validate_and_mask_prose(val, name=None): _prose_ok(raw := _ck(len(rs := _s(val).strip()) <= 32768, rs)) _prose_ok(ms := rule14_mask_veritas_text(raw)) return ms def _mth(ls, lo, hi): sp = 1 << ((hi - lo - 1).bit_length() - 1) if hi - lo > 1 else 0 return hashlib.sha256(b"\x00" + ls[lo] if not sp else b"\x01" + _mth(ls, lo, lo + sp) + _mth(ls, lo + sp, hi)).digest() def _msteps(ci, cnt): lo, hi = 0, cnt while hi - lo > 1: yield ci < (m := lo + (1 << ((hi - lo - 1).bit_length() - 1))), lo, m, hi lo, hi = (lo, m) if ci < m else (m, hi) def rfc6962_merkle_root(leaves): return _mth(ls := [*map(_rbytes, _rseq(leaves, 1, 1024))], 0, len(ls)).hex() def rfc6962_inclusion_proof(leaves, leaf_index): ls = [*map(_rbytes, _rseq(leaves, 1, 1024))] return [_mth(ls, *((m, hi) if il else (lo, m))).hex() for il, lo, m, hi in _msteps(_irng(leaf_index, 0, len(ls) - 1), len(ls))][::-1] def rfc6962_verify_inclusion(leaf, leaf_index, tree_size, proof, expected_root): cur, sts = hashlib.sha256(b"\x00" + _rbytes(leaf)).digest(), [*_msteps(_irng(leaf_index, 0, (cnt := _irng(tree_size, 1, 1024)) - 1), cnt)][::-1] exp, pbs = bytes.fromhex(_rhex(expected_root)), [bytes.fromhex(_rhex(nd)) for nd in _rseq(proof, 0, 1024)] for (il, *_), sb in (zip(sts, pbs) if len(pbs) == len(sts) else ()): cur = hashlib.sha256(b"\x01" + (cur + sb if il else sb + cur)).digest() return len(pbs) == len(sts) and hmac.compare_digest(cur, exp) def _xref(r, k): if isinstance(r, str): return _id(r), 1 rk, rw = _unp(r, k, "weight", (1,), XBRLHierarchyMismatchError) return _id(rk), _ck((w := require_int(rw)) in (-1, 1), w, XBRLHierarchyMismatchError) def _eval_xbrl(nat, xrs): abit, cmap, stm, xe = {k: 1 << i for i, k in enumerate(nat)}, {}, {}, XBRLHierarchyMismatchError for rn in _rseq(xrs or (), 0, 128): rcid, rtot, rca, rcc = _unp(rn, "concept_id reported_total_q", "children_accounts children_concepts", (), xe) cid, ca, cci = _uid(rcid, set(cmap), xe), _rseq(rca or ()), _rseq(rcc or ()) _rq(ca or cci, xe) cov, tms, cc = 0, [], [] for x in ca: aid, w = _xref(x, "account_id") cov |= _ck((b := abit.get(aid, 0)) != 0 and (cov & b) == 0, b, xe) tms.append(w * nat[aid]) for x in cci: sid, w = _xref(x, "concept_id") cc.append((_ck(sid != cid and sid not in {u for u, _ in cc}, sid, xe), w)) cmap[cid] = (_qsum(tms, xe), cov, cc, _pu(rtot)) def _evx(c): _rq(c in cmap and (cur := stm.get(c)) != 1, xe) if not isinstance(cur, tuple): stm[c], (bq, cov, cc, rq) = 1, cmap[c] ts = [bq] for sid, w in cc: sq, sc = _evx(sid) cov |= _ck((cov & sc) == 0, sc, xe) ts.append(w * sq) stm[c] = cur = (_ck((aq := _qsum(ts, xe)) == rq, aq, xe), cov) return cur return {c: fraction_to_str(_evx(c)[0]) for c in cmap} def verify_pacioli_double_entry_ledger_v1(*a, **kw): bc, fx_in, jes, crs, rst, xrs = _rspec(a, kw, "base_currency fx_rates_to_base journal_entries", "declared_cross_rates reported_statement_totals xbrl_rollups") base, fxm = _ck(_CCY_P.match(bs := _s(bc)) is not None, bs), _nmap(fx_in, ValueError, 32) fx = {c: _ck((mc := _CCY_P.match(c)) is not None and (rq := parse_rational_q(v)) > 0, rq, TriangularFXArbitrageError if mc else ValueError) for c, v in _ck(1 <= len(fxm) <= 32, fxm).items()} _rq(fx.get(base) == 1 and all((rq := parse_rational_q(rq_s)) > 0 and _qbits(rq * fx[_rchoice(tc, fx, UnregisteredCurrencyError)]) == fx[_rchoice(fc, fx, UnregisteredCurrencyError)] for fc, tc, rq_s in (_unp(cr, "from_ccy to_ccy rate_q") for cr in _rseq(crs or (), 0, 1024))), TriangularFXArbitrageError) ents, eids, aty, sdc = _rseq(jes, 1, 512, VacuousLedgerError), set(), {}, collections.defaultdict(Fraction) for ent in ents: eid, lns, desc = _unp(ent, "entry_id lines", "description") _uid(eid, eids) _s(desc) if desc is not None else None esum, sds = Fraction(0), set() for ln in _rseq(lns, 2, 64, UnbalancedJournalEntryError): r_aid, r_at, r_sd, r_am, r_cc = _unp(ln, "account_id account_type side amount_q currency") aid, at, sd = _id(r_aid), _rchoice(r_at, ACCOUNTING_ACCOUNT_TYPES), _rchoice(r_sd, ("DEBIT", "CREDIT")) _rq(aty.setdefault(aid, at) == at, InconsistentAccountTypeError) sv = _qbits(_ck((aq := parse_rational_q(r_am)) > 0, aq, UnbalancedJournalEntryError) * fx[_rchoice(r_cc, fx, UnregisteredCurrencyError)]) * (1 if sd == "DEBIT" else -1) sdc[aid], esum = _qbits(sdc[aid] + sv), _qbits(esum + sv) sds.add(sd) _rq(len(sds) == 2 and esum == 0, UnbalancedJournalEntryError) _rq(_qsum(sdc.values(), AccountingIdentityBreachError) == 0, AccountingIdentityBreachError) nat = {k: (v if aty[k] in ("ASSET", "EXPENSE") else -v) for k, v in sdc.items()} A, L, E, R, X = (_qsum((v for k, v in nat.items() if aty[k] == t), AccountingIdentityBreachError) for t in _AT_ORD) tots = _kv(_STM_K, (A, L, E, R, X, ni := _qbits(R - X, AccountingIdentityBreachError), ce := _qbits(E + ni, AccountingIdentityBreachError))) _rq(A == _qbits(L + ce, AccountingIdentityBreachError) and (rst is None or all(_pu(v) == tots[k] for k, v in _cmap(rst, (), _STM_K, AccountingIdentityBreachError).items())), AccountingIdentityBreachError) return _kv("verified base_currency journal_entries_count xbrl_totals", (_T, base, len(ents), _eval_xbrl(nat, xrs))) | _kv(_STM_K, map(fraction_to_str, tots.values())) def verify_rag_citation_and_table_grounding_v2(*a, **kw): ech, cls = _rspec(a, kw, "evidence_chunks claims") cmap, lvs, och, hs, hf = {}, [], [], HallucinatedSpanMismatchError, HallucinatedFormulaMismatchError for idx, ch in enumerate(_rseq(ech, 1, 256, VacuousGroundingError)): rcid, rdid, rtx, rau = _unp(ch, "chunk_id doc_id text authorized_source") cid, did, rt, au = _uid(rcid, set(cmap)), _id(rdid), _ck(1 <= len(t := _s(rtx)) <= 16384, t), strict_bool(rau) lvs.append(lf := jcs_canonical_bytes(_kv("chunk_id doc_id authorized_source masked_text_sha256", (cid, did, au, _sha((mt := rule14_mask_veritas_text(rt)).encode()))))) cmap[cid] = (idx, rt, mt, lf, au) och.append(_kv("chunk_id doc_id authorized_source masked_text", (cid, did, au, mt))) ev_rt, cids, rq, ocl = rfc6962_merkle_root(lvs), set(), {}, [] for cl in _rseq(cls, 1, 256, VacuousGroundingError): cid, ct = _uid((cm := _nmap(cl, ValueError, 8)).get("claim_id"), cids), _s(cm.get("claim_type")) if ct == "LITERAL_SPAN": _, _, rch, rst, ren, rvq = _unp(cm, "claim_id claim_type chunk_id span_start span_end value_q") chid, st, en = _rchoice(_id(rch), cmap, hs), require_int(rst), require_int(ren) vqu, (idx, rt, mt, lf, au) = _pu(_ck(not isinstance(rvq, str) or len(_s(rvq)) <= 128, rvq)), cmap[chid] _rq(au, UnauthorizedEvidenceSourceError) _rq(0 <= st < en <= len(rt) and _Q_P.match(tok := rt[st:en]) is not None and rule14_mask_veritas_text(tok) == tok and not (_SPAN_L.search(rt[:st]) or _SPAN_R.search(rt[en:]) or (_LOSS_L.search(rt[:st]) and _LOSS_R.search(rt[en:]))) and (mt == rt or rule14_mask_veritas_text(rt[:st]) + tok + rule14_mask_veritas_text(rt[en:]) == mt), hs) try: vq, tq = parse_rational_q(rvq), parse_rational_q(tok) except ValueError as exc: raise hs(cid) from exc rq[cid] = _ck(tq == vq == vqu and rfc6962_verify_inclusion(lf, idx, len(lvs), rfc6962_inclusion_proof(lvs, idx), ev_rt), vq, hs) else: _rq(ct == "SYMBOLIC_DERIVED") _, _, rop, rids, rvq = _unp(cm, "claim_id claim_type op input_claim_ids value_q") op, tq = _rchoice(rop, _OPS), _pu(rvq) vs = [rq[_ck((dp := _id(rd)) in rq, _ck(dp != cid and dp in cids, dp, CyclicFormulaDependencyError if dp == cid or dp in cids else hf), hf)] for rd in _rseq(rids, 1, 256, hf, hf)] if op == "SUM": cp = _qsum(vs, hf) else: x, y = _ck(len(vs) == 2, vs, hf) _rq(op not in ("DIV", "GROWTH_RATE") or (y if op == "DIV" else x) != 0, SymbolicDivisionByZeroError) cp = _qbits(x - y if op == "DIFF" else x * y if op == "MUL" else x / y if op == "DIV" else _qbits(y - x, hf) / x, hf) rq[cid] = _ck(cp == tq, cp, hf) ocl.append(_kv("claim_id claim_type value_q", (cid, ct, fraction_to_str(rq[cid])))) return _kv("verified evidence_merkle_root grounded_claims_count chunks verified_claims", (_T, ev_rt, len(ocl), och, ocl)) def bankers_round_half_even_int(q): qt, rm = divmod((qv := _pu(q)).numerator, d := qv.denominator) return qt + (1 if 2 * rm > d else qt & 1 if 2 * rm == d else 0) def verify_sovereign_rounding_and_apportionment_v3(*a, **kw): sc_i, tbls, lns = _rspec(a, kw, "scale_per_unit apportionment_tables", "line_roundings") sc, tids, asum, otb, he = _irng(sc_i, 1, 1_000_000), set(), 0, [], HamiltonApportionmentBreachError for ln in _rseq(lns or (), 0, 128): eq, rsi, lid = _unp(ln, "exact_q reported_scaled_int", "line_id") _id(lid) if lid is not None else None _rq(bankers_round_half_even_int(_qbits(parse_rational_q(eq) * sc)) == require_int(rsi), BankersRoundingMismatchError) for tbl in _rseq(tbls, 1, 64): rtid, rtot, rbks, rrep = _unp(tbl, "table_id total_scaled_units buckets reported_scaled_units") tid, tot, bids = _uid(rtid, tids), _irng(rtot, 0, _JM, he), set() bks = [(_uid(rb, bids), _ck((w := parse_rational_q(rw)) >= 0, w, he)) for rb, rw in (_unp(b, "bucket_id weight_q") for b in _rseq(rbks, 1, 128))] wsum = _ck((ws := _qsum(w for _, w in bks)) > 0, ws, he) nrep = {k: _irng(v, 0, _JM, he) for k, v in _nmap(rrep, he, len(bks)).items()} qks = [(bid, qk := _qbits(Fraction(tot) * wq / wsum), qk.numerator // qk.denominator) for bid, wq in _ck(set(nrep) == bids, bks, he)] alloc = {bid: fk for bid, _, fk in qks} for _, _, bid in sorted((-(qk - fk), -qk, bid) for bid, qk, fk in qks)[: tot - sum(alloc.values())]: alloc[bid] += 1 asum += _ck(sum(nrep.values()) == tot and nrep == alloc, tot, he) otb.append(_kv("table_id total_scaled_units allocated_units", (tid, tot, alloc))) return _kv("verified scale_per_unit allocated_total_scaled_units tables", (_T, sc, _ck(asum <= _JM, asum, he), otb)) def _pscopes(sq): return {_id(_ck("*" not in (s := _s(r)), s, TC260PrivilegeEscalationError)) for r in _rseq(sq, 1, 32, TC260PrivilegeEscalationError, TC260PrivilegeEscalationError)} def verify_east_west_aigc_and_tc260_agent_gate_v4(*a, **kw): gb, ag, evs = _rspec(a, kw, "gb45438_label tc260_v3_agent", "eval_utc_s", (_U,), AIGCLabelingBreachError) rel, reu, rim = _unp(_ck(gb not in (None, _U), gb, AIGCLabelingBreachError), "explicit_user_label eu_art50_machine_readable implicit_metadata", e=AIGCLabelingBreachError) _rq(rel is not None and rim is not None and strict_bool(reu), AIGCLabelingBreachError) elbl, (av, cc, *ids) = validate_and_mask_prose(rel), _unp(rim, _IM_K, e=AIGCLabelingBreachError) _rq(not any(x is None for x in (av, cc, *ids)) and _s(av) == "1", AIGCLabelingBreachError) msha = _jsha(_kv(_IM_K, ("1", _rchoice(cc, _ACATS, AIGCLabelingBreachError), *(_id(x, None, AIGCLabelingBreachError) for x in ids)))) agm = _nmap(ag, TC260PrivilegeEscalationError, len(_TC_K)) ks, ev_in = set(agm), "eval_utc_s" in agm for sr, err in (("agent_id granted_min_scopes requested_scopes", TC260PrivilegeEscalationError), ("issued_utc_s expires_utc_s", TC260SessionCredentialError), ("high_impact_financial_action human_hitl_approved", TC260DefaultDenyHITLBreachError)): _rq(ks <= _TC_K and {*_sp(sr)} <= ks, err) _rq(ev_in or evs is not _U, TC260SessionCredentialError) aid = _ck(_pscopes(agm["requested_scopes"]) <= _pscopes(agm["granted_min_scopes"]), _id(agm["agent_id"]), TC260PrivilegeEscalationError) ti, te, tv = map(require_int, (agm["issued_utc_s"], agm["expires_utc_s"], agm["eval_utc_s"] if ev_in else evs)) _rq((not ev_in or evs is _U or tv == require_int(evs)) and 0 <= ti < tv < te <= 1_000_000_000_000 and te - ti <= 86400, TC260SessionCredentialError) hi, hok, aps = strict_bool(agm["high_impact_financial_action"]), strict_bool(agm["human_hitl_approved"]), (None if agm.get("human_approver_id") is None else _s(agm["human_approver_id"])) _rq((not hi or (hok and bool(aps and aps.strip()) and _id(aps) != aid)) and (not aps or hi or _id(aps) != aid), TC260DefaultDenyHITLBreachError) return _kv("verified explicit_user_label implicit_metadata_sha256 agent_id eval_utc_s high_impact_financial_action human_hitl_approved", (_T, elbl, msha, aid, tv, hi, hok)) def verify_cross_border_zk_sanctuary_v5(*a, **kw): tmi, rp, zr, si, bi, ci, cz = _rspec(a, kw, "transfer_mechanism raw_pii_retained stateless_zero_retention office_summary_text budget_b", "c_levels cost_zero_stop", (1, _F), CrossBorderSanctuaryBreachError) tm = _ck((not strict_bool(rp)) & strict_bool(zr), _rchoice(tmi, _TMECH, CrossBorderSanctuaryBreachError), CrossBorderSanctuaryBreachError) ms, bv, cv, czb = validate_and_mask_prose(si), _irng(bi, 1, 10000, CognitiveBudgetExceededError), require_int(ci), strict_bool(cz) return _kv("verified transfer_mechanism masked_summary_text word_count budget_b c_levels cost_zero_stop", (_T, tm, ms, _ck((wc := len(ms.split())) <= bv and cv == 1, wc, CognitiveBudgetExceededError), bv, cv, czb)) def build_dora_event(seq_no, timestamp_utc_s, actor_id, role, action_type, payload_sha256, prev_event_hash): pre = _kv(_DEV_K[:7], (_irng(seq_no, 1, 1_000_000_000, DORAChainTamperError), _irng(timestamp_utc_s, 0, 1_000_000_000_000, DORAChainTamperError), _id(actor_id), _rchoice(role, _DROLES, DORAChainTamperError), _id(action_type), _rhex(payload_sha256, DORAChainTamperError), _rhex(prev_event_hash, DORAChainTamperError))) return pre | {"event_hash": _jsha(pre)} def verify_dora_ict_reconstruction_and_sox_v6(*a, **kw): (ev_in,), de = _rspec(a, kw, "execution_events", e=DORAChainTamperError), DORAChainTamperError eseq, pts, expp, preps, apprs, lvs = _rseq(ev_in, 2, 128, de, de), 0, "0" * 64, set(), set(), [] for idx, ev in enumerate(eseq, 1): *head, esha_in = _unp(ev, _DEV_K, e=de) sno, ts, esha = require_int(head[0]), require_int(head[1]), _rhex(esha_in, de) pts, built = _ck(sno == idx and pts <= ts <= 1_000_000_000_000, ts, de), build_dora_event(*head) _rq(hmac.compare_digest(built["prev_event_hash"], expp) & hmac.compare_digest(esha, built["event_hash"]), de) (preps if built["role"] == "AGENT_PREPARER" else apprs if built["role"] != "DETERMINISTIC_ENGINE" else set()).add(built["actor_id"]) lvs.append(jcs_canonical_bytes(built | {"event_hash": (expp := esha)})) _rq(bool(preps and apprs) and preps.isdisjoint(apprs), SOXSegregationOfDutiesError) return _kv("verified events_count preparer_actors approver_actors dora_events_merkle_root", (_T, len(eseq), sorted(preps), sorted(apprs), rfc6962_merkle_root(lvs))) class VeritasRevocationRegistry: def __init__(self): self._n = {} def has_evaluation(self, eid): return _id(eid) in self._n def register_evaluation(self, eid, parent_evaluation_id=None): p, e = (None if parent_evaluation_id is None else _rchoice(_id(parent_evaluation_id), self._n, PacioliVeritasError)), _uid(eid, set(self._n), PacioliVeritasError) self._n[_ck(len(self._n) < _MD, e, PacioliVeritasError)] = [[], self._n[p][1] if p else None] self._n[p][0].append(e) if p else None return e def revoke_evaluation(self, eid, reason="Evaluation revoked by statutory notary."): mr, st, out = validate_and_mask_prose(reason), [_rchoice(_id(eid), self._n, PacioliVeritasError)], [] while st: if not self._n[c := st.pop()][1]: self._n[c][1], _ = mr, (out.append(c), st.extend(self._n[c][0])) return sorted(out) def is_revoked(self, eid): return bool(self.revocation_reason(eid)) def revocation_reason(self, eid): return self._n.get(_id(eid), (0, None))[1] def build_humble_crystal_facts_and_gate_v7(*a, **kw): he = HumbleCrystalGateError v1i, v2i, v3i, v4i, v5i, v6i, reid, rintr, rreg, exf = _rspec(a, kw, "v1_result v2_result v3_result v4_result v5_result v6_result", "evaluation_id interruption revocation_registry extra_facts", ("EVAL-PACIOLI-0001", "none", None, None), he) v1m, v2m, v3m, v4m, v5m, v6m = ms = (*map(_nmap, (v1i, v2i, v3i, v4i, v5i, v6i)),) aok = assert_output_rule14_clean(ms) and all([strict_bool(m.get("verified")) for m in ms]) aq, lq, ceq, niq = map(_pu, map(v1m.get, _sp("assets_q liabilities_q closing_equity_q net_income_q"))) _rq(aq == _qbits(lq + ceq, AccountingIdentityBreachError), AccountingIdentityBreachError) gcnt, allu = _irng(v2m.get("grounded_claims_count"), 1, 256, he), _irng(v3m.get("allocated_total_scaled_units"), 0, _JM, he) _rq(not strict_bool(v4m.get("high_impact_financial_action", _F)) or strict_bool(v4m.get("human_hitl_approved", _F)), TC260DefaultDenyHITLBreachError) if {"preparer_actors", "approver_actors"} & set(v6m): pa, aa = ({*map(_id, _rseq(v6m.get(k, ())))} for k in ("preparer_actors", "approver_actors")) _rq(bool(pa and aa) and pa.isdisjoint(aa), SOXSegregationOfDutiesError) rts = tuple(_rhex(m.get(k), he) for m, k in zip((v2m, v4m, v6m), _sp("evidence_merkle_root implicit_metadata_sha256 dora_events_merkle_root"))) eid, rin, reg = _id(reid), _s(rintr), _ck(rreg is None or isinstance(rreg, VeritasRevocationRegistry), rreg, TypeError) intr = _ck(_CTL_P.search(rin) is None and rin == rin.strip() and rin in ((il := rin.lower()), il.upper()) and il in PACIOLI_INTERRUPTIONS, il, he) intr = COST_ZERO_STOP if strict_bool(v5m.get("cost_zero_stop", _F)) and intr == "none" else intr rev, bccy = (_F if reg is None else reg.is_revoked(eid)), _ck(_CCY_P.match(bc := _s(v1m.get("base_currency"))) is not None, bc, he) _prose_ok(elbl := _s(v4m.get("explicit_user_label"))) _prose_ok(osum := _s(v5m.get("masked_summary_text"))) _rq(len(osum.split()) <= _irng(v5m.get("budget_b", 10000), 1, 10000, CognitiveBudgetExceededError) and require_int(v5m.get("c_levels", 1)) == 1, CognitiveBudgetExceededError) facts = _kv("evaluation_id base_currency assets_q liabilities_q closing_equity_q net_income_q grounded_claims_count allocated_total_scaled_units explicit_user_label office_summary", (eid, bccy, *map(fraction_to_str, (aq, lq, ceq, niq)), gcnt, allu, elbl, osum)) for fk, fv in (() if exf is None else _nmap(exf, he).items()): facts[_ck(1 <= len(fk) <= 128 and fk == fk.strip() and _CTL_P.search(fk) is None and fk not in facts, fk, he)] = fv def _nlk(s): _rq(not any(rt in (sl := s.lower()) or rt in _RSEP_P.sub("", sl) for rt in rts), he) try: cf = _clean_dag(facts, lambda s: (_rq(_HEX_LK_P.search(s) is None, he), _nlk(s)), he) _nlk(jcs_canonical_bytes(cf).decode()) out = _kv("verified evaluation_id verified_facts humble_crystal_hex_free cryptographic_commitments interruption revoked q3_zero_twist_enforced eligible_for_w3c_vc", (aok, eid, cf, _T, _kv("evidence_merkle_root implicit_metadata_sha256 dora_events_merkle_root", rts), intr, rev, intr != "none" or rev or not aok, aok and intr == "none" and not rev)) jcs_canonical_bytes(out) except PacioliVeritasError: raise except (ValueError, TypeError) as exc: raise he("ijson") from exc return out _V16_FNS = (verify_pacioli_double_entry_ledger_v1, verify_rag_citation_and_table_grounding_v2, verify_sovereign_rounding_and_apportionment_v3, verify_east_west_aigc_and_tc260_agent_gate_v4, verify_cross_border_zk_sanctuary_v5, verify_dora_ict_reconstruction_and_sox_v6) def build_canonical_pacioli_specimen(): raw, evs, ph, reg = json.loads(_SP_JSON), [], "0" * 64, VeritasRevocationRegistry() for a in raw.pop("dora"): evs.append(ev := build_dora_event(*a[:5], _sha(a[5].encode()), ph)) ph = ev["event_hash"] raw["v6"] = {"execution_events": evs} rs = [f(raw[k]) for k, f in zip("v1 v2 v3 v4 v5 v6".split(), _V16_FNS)] rs.append(build_humble_crystal_facts_and_gate_v7(*rs, eid := reg.register_evaluation("EVAL-PACIOLI-2026-Q4"), "none", reg)) return _kv("evaluation_id inputs v1_result v2_result v3_result v4_result v5_result v6_result v7_result", (eid, raw, *rs)) def _ex(err, fn, *a): try: return bool(fn(*a) and _F) except err: return _T def _mut(err, fn, base_in, path, val=_U): cur = cl = json.loads(jcs_canonical_bytes(base_in)) *ps, k = [int(s) if s.lstrip("-").isdigit() else s for s in path.split(".")] for s in ps: cur = cur[s] cur.pop(k) if val is _U else (cur.append(val) if k == "+" else cur.__setitem__(k, val)) return _ex(err, fn, cl) def run_self_tests(): t0, sp, fx, reg = time.perf_counter_ns(), build_canonical_pacioli_specimen(), json.loads(_ST_JSON), VeritasRevocationRegistry() v7b, i, rts = [*map(sp.get, fx["vr"])], sp["inputs"], fx["rts"] for e, p in fx["rg"]: reg.register_evaluation(e, p) reg.revoke_evaluation("B1") e1 = build_dora_event(*fx["d1"]) z_ok = _FD.encode() not in jcs_canonical_bytes([i, v7b, sp["v7_result"]]) g_ok = z_ok and all(_mut(globals()[en], _V16_FNS[k - 1], i[f"v{k}"], p, *v) for en, k, p, *v in fx["m"]) and all(_ex(HallucinatedSpanMismatchError, _V16_FNS[1], *pr) for pr in fx["sp"]) and [*sp["v7_result"]["cryptographic_commitments"].values(), sp["v7_result"]["eligible_for_w3c_vc"], *map(bankers_round_half_even_int, fx["br"]), reg.is_revoked("B1C"), reg.is_revoked("B2")] == [*rts, _T, *fx["be"]] and rule14_mask_veritas_text(fx["pii"]) == fx["pm"] and _ex(SOXSegregationOfDutiesError, _V16_FNS[5], [e1, build_dora_event(*fx["d2"], e1["event_hash"])]) and _ex(HumbleCrystalGateError, build_humble_crystal_facts_and_gate_v7, *v7b, *fx["hc"]) ms = _kv(fx["mk"], (g_ok,) * 8) return _kv(fx["rk"], (_ck(g_ok and (dt := (time.perf_counter_ns() - t0) // 1_000_000) < 5000, g_ok), sum(ms.values()), ms, z_ok, dt, *rts)) if __name__ == "__main__": print("OK Folio XI pacioli_veritas_core self-tests:", run_self_tests())