# SPDX-FileCopyrightText: 2026 David Porto Baraldés (Homo Universalis / Viveka) # SPDX-License-Identifier: Apache-2.0 """Living Folio XII (`logic/scholar/scholar_veritas_core.py`): HU-CANGZHOU-LEONARDO-SCHOLAR v1.0 pure-stdlib kernel.""" from __future__ import annotations import collections, functools, hashlib, hmac, json, re, time from collections.abc import Mapping, Sequence, Set from fractions import Fraction PROTOCOL_ID, PROTOCOL_VERSION, LIVING_FOLIO, SACRED_EQUATION = "HU-CANGZHOU-LEONARDO-SCHOLAR 1.0 folio-XII-cangzhou-leonardo-scholar F0c=Ca0s*0rdre(Am0r_Un1f1cat_Etern)".split() _, HUMAN_PI_VETO, RETRACTED_CITATION_HALT, META_CONTRADICTION_ABORT, COST_ZERO_STOP = SCHOLAR_INTERRUPTIONS = (*"none human_pi_veto retracted_citation_halt meta_contradiction_abort cost_zero_stop".split(),) REVOCATION_REASONS = frozenset(SCHOLAR_INTERRUPTIONS[1:]) GBT7714_2025_DOC_CODES = frozenset("J M C D R S P EB/OL PP PP/OL DS DS/OL AH MAP".split()) _LEVEL_TO_DOMAIN = (*"PUBLIC_COMMONS INTERNAL_TEAM PRIVATE_VAULT".split(),) DOMAIN_LATTICE = {k: i for i, k in enumerate(_LEVEL_TO_DOMAIN)} _T, _F, _U, _FD, _JM, _QB, _MD = bool(1), bool(0), object(), f"{21}{'6'}", 9007199254740991, 12288, 262144 _BAD = (float, complex, bytes, bytearray, memoryview, range, collections.UserString) _CFG = json.loads(r'''{"ex":["Rule14IdentifierPIIError","Rule14OutputSanctuaryError","PlaceholderDisclosureError","VacuousBibliographyError","InvalidGBT7714FormatError","InvalidPIDChecksumError","RetractedCitationError","HallucinatedCitationError","VacuousMetaSynthesisError","UnauthorizedEvidenceSourceError","HallucinatedSpanMismatchError","CrossStudyContradictionError","VacuousKnowledgeGraphError","UngroundedConceptNodeError","PrerequisiteCycleError","CognitiveGraphDepthExceededError","PrivateVaultLeakageError","CrossBorderSanctuaryBreachError","CognitiveBudgetExceededError","TerminologyDriftError","AIGCLabelingBreachError","TC260PrivilegeEscalationError","TC260SessionCredentialError","TC260DefaultDenyHITLBreachError","ResearchMisconductError","HumbleCrystalGateError"],"cn":["ZHANG","WANG","LIANG","HUANG","ZHENG","ZHONG","CHENG","SHENG","XIONG","JIANG","KUANG","ZHUANG","SHUANG","CHANG","CHONG","SHANG"],"hr":["Conceptualization","Supervision","Validation","Writing_Review_Editing"],"ac":["SCHOLARLY_SYNTHESIS","LITERATURE_REVIEW","MINDMAP_CURRICULUM","META_ANALYSIS"],"tm":["READ_ONLY_EPHEMERAL_COMPUTE","STANDARD_CONTRACT_SCC_CAC","LOCAL_ON_PREM_ISOLATED"],"do":["PP","PP/OL","DS","DS/OL","EB/OL"],"rt":["RETRACTED","WITHDRAWN","CONCERN_UNRESOLVED"],"jm":[[8,9,10,12,13,34,92],["\\b","\\t","\\n","\\f","\\r","\\\"","\\\\"]],"cw":[7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2],"pw":["tbd","tba","n/a","na","none","null","nil","pending","unknown","placeholder","redacted","dummy","lorem","ipsum"],"up":["[\\ud800-\\udfff]","[\\x00-\\x1f\\x7f-\\x9f\\s]","[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f-\\x9f]","\\(\\s*(?:(?:USD|EUR|GBP|CNY|RMB|JPY|CHF)\\b|\\$|€|£|¥)?\\s*\\Z","\\s*(?:(?:USD|EUR|GBP|CNY|RMB|JPY|CHF)\\b|\\$|€|£|¥)?\\s*\\)","(?:[-+\\u2212\\u207b]\\s*(?:[$€£¥]|(?:USD|EUR|GBP|CNY|RMB|JPY|CHF)\\b)\\s*|[-+\\u2212\\u207b]\\s*\\(\\s*|(?:^|[=(,;:\\^×])\\s*[-+\\u2212\\u207b]\\s*|[\\u2212\\u207b]\\s*)\\Z","(?:[0-9A-Za-z_/.$€£¥%+\\u2212\\u2013\\u2030^\\u00d7\\u207a\\u207b-]|[0-9],)\\Z","^(?:[0-9A-Za-z_/%‰$€£¥^\\u00d7\\u207a\\u207b]|[.,\\u2212\\u2013-][0-9])","(?(),;\\[\\]]*[A-Za-z0-9_/-]|\\\\\\\\[A-Za-z0-9_.-]+\\\\(?:[A-Za-z0-9_$-][A-Za-z0-9_$.-]*\\\\)*[A-Za-z0-9_$.-]+(?= lo, v, e0), e1 or e0) def _nmap(m, e=ValueError, mx=_MD): _rq(not isinstance(m, (bool, float, complex)), TypeError) out = {_s(_ck(type(k) is str, k, TypeError if isinstance(k, (bool, float, complex)) else e)): val for k, val in _ck(isinstance(m, Mapping), m, e).items()} return _ck(len(out) == len(m) <= mx, out, e) def _cmap(m, req, opt=None, e=ValueError, mx=4096): rt = {*_sp(req)} al = None if opt is None else (rt | {*_sp(opt)}) out = _nmap(m, e, len(al) if al is not None else mx) return _ck(rt <= set(out) and (al is None or set(out) <= 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, kw_e=None): ke, rt, ot, ks = kw_e or e, _sp(req), _sp(opt), set(kw) ak = (*rt, *ot) is_m = len(a) == 1 and isinstance(a[0], Mapping) and (not a[0] or {*ak} & set(a[0])) mp = _ck(ks <= {*ak} and ks.isdisjoint(d := _cmap(a[0], (), ak, ke)), d, ke) if is_m else _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)], e if is_m else TypeError) def _qbits(q, e=ValueError): return _ck(max(abs(q.numerator).bit_length(), q.denominator.bit_length()) <= _QB, q, e) def fraction_to_str(q): _rq(not isinstance(q, (bool, float, complex)) and isinstance(q, (Fraction, int)), TypeError) return str(_qbits(Fraction(q))) 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) q = _qbits(Fraction(int.__index__(v)) if isinstance(v, int) else (Fraction(v) if isinstance(v, Fraction) else Fraction(_ck(1 <= len(rs := _s(v).strip()) <= 4096 and _Q_P.match(rs) is not None, rs)))) return _ck(max_denom is None or (q.denominator <= max_denom and (max_num_factor is None or abs(q.numerator) <= max_num_factor * max_denom)), q) def _rqv(v, e, md=1_000_000_000): try: return parse_rational_q(v, max_denom=md) except ValueError as exc: raise e("q") from exc 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(s)).encode() + b'"' def _jcs_enc(obj, d0=0): act = set() def _enc(v, d): _rq(d <= 64) 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, Set)) 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(v) oid, im = _ck((o := id(v)) not in act and d < 64, o), isinstance(v, Mapping) act.add(oid) try: body = b",".join((_jesc(k) + b":" + _enc(val, d + 1) for k, val in sorted(_nmap(v).items(), key=lambda kv: kv[0].encode("utf-16-be"))) if im else (_enc(x, d + 1) for x in v)) return (b"{" + body + b"}") if im else (b"[" + body + b"]") finally: act.remove(oid) return _ck(len(res := _enc(obj, d0)) <= (1 << 24), res) def jcs_canonical_bytes(obj): return _jcs_enc(obj, 0) def _cn_ok(s): return len(s) == 18 and _CNC[sum((ord(c) - 48) * w for c, w in zip(s, _CNW)) % 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 all(len(g) == 4 for g in ps[: j - 1]) and int("".join(f"{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, out, pos = functools.reduce(lambda acc, pr: pr[0].sub(pr[1], acc), _R14_A, s), [], 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 = functools.reduce(lambda acc, pr: pr[0].sub(pr[1], acc), _R14_B, _CNID_P.sub(lambda m: "[cnid-shielded]" if _cn_ok(m.group(0)) else m.group(0), "".join((*out, nx[pos:])))) if nx == s: return s s = nx return s def require_rule14_clean_identifier(val, name=None): return _ck(1 <= len(s := _s(val)) <= 128 and _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 _cid(v, e): return _id(_ck(bool(_s(v).strip()), v, e)) def _uid(v, seen, e): seen.add(x := _ck((s := _id(v)) not in seen, s, e)) return x def _clean_dag(obj, hook=None, dag_err=Rule14OutputSanctuaryError, d0=0): try: _jcs_enc(obj, d0) except ValueError as exc: raise dag_err("dag") from exc def _cl(v): if isinstance(v, str): ns = _s(v) hook(ns) if hook else None return _ck(rule14_mask_veritas_text(ns) == ns, ns, Rule14OutputSanctuaryError) return {_cl(k): _cl(val) for k, val in v.items()} if isinstance(v, Mapping) else ([*map(_cl, v)] if isinstance(v, Sequence) else (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): ce = _ES_TODO_P.sub("en conjunto", _NASL_P.sub("na", _SHIELD_P.sub(" ", _ck(not _PCTL_P.search(s), s, PlaceholderDisclosureError)))) ws, al = [w for w in _WSPL_P.split(ce.lower()) if w], [c.casefold() for c in ce if c.isalpha()] _rq(ws and len(al) >= 4 and len(set(al)) >= 2 and not any(w in _PH_W or {*w} == {"x"} for w in ws), PlaceholderDisclosureError) def validate_and_mask_prose(val, name=None): _prose_ok(s := _ck(1 <= len(rs := _s(val).strip()) <= 32768, rs, PlaceholderDisclosureError)) _prose_ok(ms := rule14_mask_veritas_text(s)) 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 _mls(leaves): return [*map(_rbytes, _rseq(leaves, 1, 1024))] def rfc6962_merkle_root(leaves): return _mth(ls := _mls(leaves), 0, len(ls)).hex() def rfc6962_inclusion_proof(leaves, index): ls = _mls(leaves) return [_mth(ls, *((m, hi) if il else (lo, m))).hex() for il, lo, m, hi in _msteps(_irng(index, 0, len(ls) - 1), len(ls))][::-1] def rfc6962_verify_inclusion(leaf, index, tree_size, proof, expected_root): cur, sts, rs, pns = hashlib.sha256(b"\x00" + _rbytes(leaf)).digest(), [*_msteps(_irng(index, 0, (cnt := _irng(tree_size, 1, 1024)) - 1), cnt)][::-1], _s(expected_root), [*map(_s, _rseq(proof, 0, 1024, TypeError))] return len(pns) == len(sts) and all(map(_HEX_P.match, (rs, *pns))) and hmac.compare_digest(functools.reduce(lambda c, x: hashlib.sha256(b"\x01" + (c + bytes.fromhex(x[1]) if x[0][0] else bytes.fromhex(x[1]) + c)).digest(), zip(sts, pns), cur), bytes.fromhex(rs)) def _pchk(s, pat): return ns.replace("-", "") if pat.match(ns := _s(s)) else "" def verify_orcid_iso7064(s): d = _pchk(s, _ORCID_P) return bool(d and d[15] == "0123456789X"[(12 - (functools.reduce(lambda t, c: (t + int(c)) * 2, d[:15], 0) % 11)) % 11]) def verify_issn_iso3297(s): d = _pchk(s, _ISSN_P) return bool(d and d[7] == "0123456789X"[(11 - sum((8 - i) * int(c) for i, c in enumerate(d[:7])) % 11) % 11]) def verify_isbn13_ean(s): d = _pchk(s, _ISBN_P) return bool(len(d) == 13 and ((10 - sum((1 + 2 * (i & 1)) * int(c) for i, c in enumerate(d[:12])) % 10) % 10) == int(d[12])) def _sur_ok(sur): return (sur.isalpha() and (len(sur) <= 4 or sur in _CN_PINYIN)) if sur.isupper() else (_WSUR_P.match(sur) is not None) def verify_gbt7714_2025_bibliography_and_pids_s1(*a, **kw): fe = InvalidGBT7714FormatError be, cbi = _rspec(a, kw, "bibliography_entries", "cited_bib_ids", (None,), VacuousBibliographyError, fe) seen, lvs, pairs = set(), [], [] for raw in _rseq(be, 1, 256, VacuousBibliographyError, fe): rbid, rdtc, rau, ryr, rpt, rpv, rissn, rorc, rrs, risbn = _unp(raw, "bib_id doc_type_code authors_2025 year pid_type pid_value issn orcid retraction_status", "isbn13", ("",), fe) bid, dtc, yr = _uid(rbid, seen, fe), _rchoice(rdtc, GBT7714_2025_DOC_CODES, fe), _irng(ryr, 1450, 2100, fe) auths = [_ck((m := _AUTH_P.match(na := _s(au))) is not None and _sur_ok(m.group(1)), na, fe) for au in _rseq(rau, 1, 32, fe)] rs = _ck(_ck((s := _s(rrs)) not in _RETR, s, RetractedCitationError) == "ACTIVE", s, fe) pt, pv, issn, orcid, isbn = _rchoice(rpt, ("DOI", "ISBN13"), fe), *map(_s, (rpv, rissn, rorc, risbn)) _rq((dtc not in _DOI_ONLY or pt == "DOI") and (dtc != "J" or issn != "") and (pt != "ISBN13" or not isbn or isbn.replace("-", "") == pv.replace("-", "")), fe) _rq((_DOI_P.match(pv) is not None if pt == "DOI" else verify_isbn13_ean(pv)) and (not issn or verify_issn_iso3297(issn)) and (not orcid or verify_orcid_iso7064(orcid)) and (not isbn or verify_isbn13_ean(isbn)), InvalidPIDChecksumError) _rq(_SHIELD_P.search(pv) is None and rule14_mask_veritas_text(pv_nd := (_R14_B[0][0].sub("DATE", pv) if pt == "DOI" else pv)) == pv_nd, Rule14IdentifierPIIError) lvs.append(jcs_canonical_bytes(_kv("bib_id doc_type_code authors_2025 year pid_type pid_value issn orcid retraction_status", (bid, dtc, auths, yr, pt, pv, issn, orcid, rs)) | ({"isbn13": isbn} if isbn else {}))) pairs.append((bid, dtc)) _rq(cbi is None or all(_id(cid) in seen for cid in _rseq(cbi, 0, 512, fe)), HallucinatedCitationError) bids, dtcs = map(list, zip(*pairs)) return _kv("verified verified_citations_count bibliography_merkle_root doc_type_codes bib_ids", (_T, len(bids), rfc6962_merkle_root(lvs), dtcs, bids)) def _gspan(raw, mtxt, sp_in): he = HallucinatedSpanMismatchError s, e = map(require_int, _rseq(sp_in, 2, 2, he)) _rq(0 <= s < e <= len(raw), he) sub, lctx = raw[s:e], raw[max(0, s - 24) : s] _rq(not any(c.isspace() for c in sub) and _SHIELD_P.search(sub) is None and rule14_mask_veritas_text(sub) == sub and not (_SPAN_L.search(raw[:s]) or _SPAN_R.search(raw[e:])) and (sub.startswith("-") or not (_SIGN_P.search(lctx) or (_LOSS_L.search(lctx) and _LOSS_R.match(raw, e)))) and rule14_mask_veritas_text(raw[:s]) + sub + rule14_mask_veritas_text(raw[e:]) == mtxt, he) return sub def verify_multi_study_meta_synthesis_q_s2(*a, **kw): ve, he = VacuousMetaSynthesisError, HallucinatedSpanMismatchError cc, st_in, rms, vbi = _rspec(a, kw, "corpus_chunks studies", "reported_meta_summary valid_bib_ids", (None, None), ve) cmap, cdoms, lvs, cout = {}, {}, [], [] for rc in _rseq(cc, 1, 256, ve): rcid, rdid, rdom, rtx, rau = _unp(rc, "chunk_id doc_id domain_level text authorized_source", e=ve) cid, did, dom, au = _uid(rcid, set(cmap), ve), _id(rdid), _rchoice(rdom, DOMAIN_LATTICE, ve), strict_bool(rau) mtxt = rule14_mask_veritas_text(txt := _ck(1 <= len(t := _s(rtx)) <= 16384 and bool(t.strip()), t, ve)) lvs.append(jcs_canonical_bytes(_kv("authorized_source chunk_id doc_id domain_level masked_text_sha256", (au, cid, did, dom, _sha(mtxt.encode()))))) cout.append(_kv("chunk_id authorized_source", (cid, au))) cdoms[cid], cmap[cid] = dom, (txt, mtxt, au) croot, vbs = rfc6962_merkle_root(lvs), (None if vbi is None else {*map(_id, vbi if isinstance(vbi, Set) else _rseq(vbi, 0, 512, HallucinatedCitationError))}) sseen, cbibs, tot_n, w_sum, m1, m2 = set(), [], 0, Fraction(0), Fraction(0), Fraction(0) for rs in (sseq := _rseq(st_in, 1, 128, ve)): rsid, rbid, rcid, nsp, rsn, esp, req_s, vsp, rvq = _unp(rs, "study_id bib_id chunk_id n_span sample_n effect_span effect_q variance_span variance_q", e=ve) _uid(rsid, sseen, ve) bid, (raw, mtxt, au) = _ck(vbs is None or _id(rbid) in vbs, _id(rbid), HallucinatedCitationError), cmap[_rchoice(_id(rcid), cmap, he)] _rq(au, UnauthorizedEvidenceSourceError) nsub, esub, vsub = (_gspan(raw, mtxt, x) for x in (nsp, esp, vsp)) sn, eq, vq = _irng(rsn, 1, _JM, he), _rqv(req_s, he), _rqv(rvq, he) _rq(len(nsub) <= 16 and nsub.isascii() and nsub.isdigit() and nsub[0] != "0" and int(nsub) == sn and eq == _rqv(esub, he) and vq == _rqv(vsub, he) and vq > 0 and tot_n + sn <= _JM, he) w = Fraction(1, 1) / vq tot_n, w_sum, m1, m2 = tot_n + sn, _qbits(w_sum + w), _qbits(m1 + w * eq), _qbits(m2 + w * eq * eq) cbibs.append(bid) pq = _qbits(m1 / w_sum) cq = _qbits(m2 - m1 * pq) iq = Fraction(0) if (df := len(sseq) - 1) == 0 or cq <= df else _qbits((cq - df) / cq) if rms is not None: ce = CrossStudyContradictionError rm = _ck(bool(d := _cmap(rms, (), "total_sample_n pooled_effect_q cochran_q higgins_i2_q claimed_effect_direction", ce)), d, ce) _rq((require_int(rm.get("total_sample_n", tot_n)) == tot_n) and all(k not in rm or _rqv(rm[k], ce, None) == ex for k, ex in zip(_sp("pooled_effect_q cochran_q higgins_i2_q"), (pq, cq, iq))) and ("claimed_effect_direction" not in rm or _rchoice(rm["claimed_effect_direction"], ("POSITIVE", "NEGATIVE", "NULL"), ce) == ("POSITIVE" if pq > 0 else "NEGATIVE" if pq < 0 else "NULL")), ce) return _kv("verified corpus_merkle_root studies_count total_sample_n pooled_effect_q cochran_q higgins_i2_q cited_bib_ids chunk_domains chunks", (_T, croot, len(sseq), tot_n, *map(fraction_to_str, (pq, cq, iq)), cbibs, cdoms, cout)) def _dmap(m, e): return {_cid(k, e): DOMAIN_LATTICE[_rchoice(v, DOMAIN_LATTICE, e)] for k, v in _nmap(m, e, 4096).items()} def verify_mindmap_knowledge_dag_s3(*a, **kw): ve, ue, pe = VacuousKnowledgeGraphError, UngroundedConceptNodeError, PrerequisiteCycleError cn, edges, ccd, auth_in, md_in = _rspec(a, kw, "concept_nodes prerequisite_edges corpus_chunk_domains", "authorized_chunks max_depth", (None, 16), ve) cdoms, auth_m = _dmap(ccd, ue), (None if auth_in is None else {_cid(k, ue): strict_bool(v) for k, v in _nmap(auth_in, ue, 4096).items()}) mdepth, g, seen_e = _irng(md_in, 1, 64, CognitiveGraphDepthExceededError), {}, set() for rn in _rseq(cn, 1, 256, ve): rnid, rlbl, racs = _unp(rn, "node_id label anchor_chunk_ids", e=ve) nid, _ = _uid(rnid, set(g), ve), validate_and_mask_prose(rlbl) g[nid] = [max(cdoms[_ck((cid := _id(c)) in cdoms and (auth_m is None or auth_m.get(cid, _F)), cid, ue)] for c in _rseq(racs, 1, 32, ue)), [], 0, 1] for re_o in (eseq := _rseq(edges, 0, 1024, pe)): ru, rv = _unp(re_o, "from_node to_node", e=pe) u, v = _rchoice(_id(ru), g, ue), _rchoice(_id(rv), g, ue) seen_e.add(_ck(u != v and (u, v) not in seen_e, (u, v), pe)) g[u][1].append(v) g[v][2] += 1 ready, topo = sorted(k for k, v in g.items() if v[2] == 0), [] while ready: topo.append(u := ready.pop(0)) for v in g[u][1]: g[v][0], g[v][2], g[v][3] = max(g[v][0], g[u][0]), g[v][2] - 1, max(g[v][3], g[u][3] + 1) if g[v][2] == 0: ready.append(v) ready.sort() _rq(len(topo) == len(g), pe) return _kv("verified grounded_nodes_count edges_count dag_depth topological_order node_lattice_levels", (_T, len(g), len(eseq), _ck((mx := max(v[3] for v in g.values())) <= mdepth, mx, CognitiveGraphDepthExceededError), topo, {k: _LEVEL_TO_DOMAIN[v[0]] for k, v in g.items()})) def verify_vault_commons_non_interference_s4(*a, **kw): pe = PrivateVaultLeakageError outs, ccd, nll, tmi, rp, zr, ssum, bb, clv, cz = _rspec(a, kw, "derived_outputs corpus_chunk_domains node_lattice_levels transfer_mechanism raw_pii_retained stateless_zero_retention scholar_summary_text budget_b", "c_levels cost_zero_stop", (1, _F), pe) cdoms, nlvls, seen_o = _dmap(ccd, pe), _dmap(nll, pe), set() for ro in (oseq := _rseq(outs, 1, 128, pe)): roid, rtc, rcc, rcn = _unp(ro, "output_id target_channel", "cited_chunk_ids cited_node_ids", ((), ()), pe) _uid(roid, seen_o, pe) tl, cids, nids = DOMAIN_LATTICE[_rchoice(rtc, DOMAIN_LATTICE, pe)], _rseq(rcc, 0, 128, pe), _rseq(rcn, 0, 128, pe) _rq(bool(cids or nids) and all(cdoms.get(_id(c), 9) <= tl for c in cids) and all(nlvls.get(_id(n), 9) <= tl for n in nids), pe) tm = _ck(not strict_bool(rp) and strict_bool(zr), _rchoice(tmi, _TMECHS, CrossBorderSanctuaryBreachError), CrossBorderSanctuaryBreachError) ms, bv, cv, czb = validate_and_mask_prose(ssum), _irng(bb, 1, 10000, CognitiveBudgetExceededError), require_int(clv), strict_bool(cz) return _kv("verified outputs_verified_count transfer_mechanism masked_summary_text word_count budget_b c_levels cost_zero_stop", (_T, len(oseq), tm, ms, _ck((wc := len(ms.split())) <= bv and cv == 1, wc, CognitiveBudgetExceededError), bv, 1, czb)) def verify_terminology_diapason_s5(*a, **kw): te, _nrm = TerminologyDriftError, (lambda lg, s: s if lg == "zh" else " ".join(s.split()).casefold()) gt, mc_in = _rspec(a, kw, "glossary_terms multilingual_conclusions", e=te) mc, seen_t, pg = _ck(1 <= len(d := _cmap(mc_in, (), _LANGS, te)) <= 4, d, te), set(), [] def _tclean(v): return _ck(bool(s := _s(v).strip()) and not _PCTL_P.search(s) and not _SHIELD_P.search(s) and rule14_mask_veritas_text(s) == s, s, te) for rg in _rseq(gt, 1, 128, te): rtid, rcan, rfa = _unp(rg, "term_id canonical", "forbidden_aliases", (None,), te) _uid(rtid, seen_t, te) can, fraw = _cmap(rcan, _LANGS, (), te), _cmap({} if rfa is None else rfa, (), _LANGS, te) pg.append(({lg: _nrm(lg, cs) for lg in _LANGS if not _prose_ok(cs := _tclean(can[lg]))}, {lg: [_nrm(lg, _tclean(al)) for al in _rseq(fraw.get(lg, ()), 0, 32, te)] for lg in _LANGS})) _rq(not any(al in cm[lg] for lg in _LANGS for _, fm in pg for al in fm[lg] for cm, _ in pg) and all(all(cm[lg] in hay and not any(al in hay for al in fm[lg]) for cm, fm in pg) for lg, rtxt in mc.items() if (hay := _nrm(lg, validate_and_mask_prose(rtxt))) or _T), te) return _kv("verified terms_locked_count languages_verified", (_T, len(pg), sorted(mc))) def verify_research_integrity_and_aigc_gate_s6(*a, **kw): ae, re_err, pe6 = AIGCLabelingBreachError, ResearchMisconductError, TC260PrivilegeEscalationError gb_in, ag_in, cr_in, aia, spf, evs = _rspec(a, kw, "gb45438_label tc260_v3_agent credit_contributions", "ai_listed_as_author synthetic_primary_data_fabricated eval_utc_s", (_F, _F, _U), ae) _rq(not (strict_bool(aia) or strict_bool(spf)), re_err) rel, reu, rim = _unp(gb_in, "explicit_user_label eu_art50_machine_readable implicit_metadata", e=ae) elbl, (av, cat, *ids) = _ck(strict_bool(reu), validate_and_mask_prose(rel), ae), _unp(rim, _IM_K, e=ae) msha = _sha(jcs_canonical_bytes(_kv(_IM_K, (_ck(_s(av) == "1", "1", ae), _rchoice(cat, _ACATS, ae), *(_cid(x, ae) for x in ids))))) raid, rgsc, rrsc, rti, rte, rhi, rhok, rpi, revs = _unp(ag_in, "agent_id granted_min_scopes requested_scopes issued_utc_s expires_utc_s high_impact_scholarly_submission human_hitl_approved principal_investigator_id", "eval_utc_s", (None,), TC260SessionCredentialError) aid, _sc = _cid(raid, TC260SessionCredentialError), (lambda sq: {_id(_ck(bool(ns := _s(s).strip()) and "*" not in ns, ns, pe6)) for s in _rseq(sq, 1, 32, pe6)}) _rq(_sc(rrsc) <= _sc(rgsc), pe6) ti, te_s, tv = require_int(rti), require_int(rte), require_int(evs if evs not in (_U, None) else (revs if revs is not None else time.time_ns() // 10**9)) _rq(0 <= ti < tv < te_s <= 10**12 and te_s - ti <= 86400, TC260SessionCredentialError) hi, hok, rpis = strict_bool(rhi), strict_bool(rhok), _s(rpi) pi_id = _ck(not (hi and not hok) and not ((hi or hok) and not rpis.strip()) and (p := "" if not rpis else _cid(rpis, TC260DefaultDenyHITLBreachError)) != aid, p, TC260DefaultDenyHITLBreachError) wtot, whum, akm, scr = Fraction(0), Fraction(0), {}, set() for rc in _rseq(cr_in, 1, 64, re_err): rcid, rak, rrl, rwq = _unp(rc, "contributor_id actor_kind role weight_q", e=re_err) cid, ak, rl, wq = _cid(rcid, re_err), _rchoice(rak, ("HUMAN_RESEARCHER", "AI_INSTRUMENT"), re_err), _cid(rrl, re_err), _rqv(rwq, re_err) scr.add(_ck((cid, rl) not in scr and akm.setdefault(cid, ak) == ak and (cid, ak) not in ((aid, "HUMAN_RESEARCHER"), (pi_id, "AI_INSTRUMENT")) and wq > 0 and not (ak == "AI_INSTRUMENT" and rl in _HUM_ROLES), (cid, rl), re_err)) wtot, whum = _qbits(wtot + wq, re_err), (_qbits(whum + wq, re_err) if ak == "HUMAN_RESEARCHER" else whum) _rq(wtot == 1 and whum >= Fraction(1, 2), re_err) return _kv("verified explicit_user_label implicit_metadata_sha256 agent_id eval_utc_s principal_investigator_id high_impact_scholarly_submission human_hitl_approved human_credit_share_q", (_T, elbl, msha, aid, tv, pi_id, hi, hok, fraction_to_str(whum))) class ScholarRevocationRegistry: 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 = parent_evaluation_id and _rchoice(_id(parent_evaluation_id), self._n, HumbleCrystalGateError) cid = _ck(len(self._n) < _QB, _uid(eid, set(self._n), HumbleCrystalGateError), HumbleCrystalGateError) self._n[cid] = [[], self._n[p][1] if p else None] p and self._n[p][0].append(cid) return cid def revoke_evaluation(self, eid, reason=HUMAN_PI_VETO): st, rsn, out = [_rchoice(_id(eid), self._n, HumbleCrystalGateError)], _s(reason), [] mr = rsn if rsn in REVOCATION_REASONS else validate_and_mask_prose(rsn) while st: nd = self._n[c := st.pop()] if not nd[1]: nd[1] = mr out.append(c) st.extend(nd[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), ("", None))[1] def build_humble_crystal_scholar_gate_s7(*a, **kw): he = HumbleCrystalGateError *sr_in, eid_in, intr_in, reg, exf = _rspec(a, kw, "s1_result s2_result s3_result s4_result s5_result s6_result", "evaluation_id interruption revocation_registry extra_facts", ("EVAL-SCHOLAR-0001", "none", None, None), he) s1, s2, s3, s4, s5, s6 = rall = [_nmap(r, he) for r in sr_in] aok = assert_output_rule14_clean(rall) and all(strict_bool(_ck("verified" in r, r, he)["verified"]) for r in rall) eid, intr = _id(eid_in), (COST_ZERO_STOP if (it := _rchoice(intr_in, SCHOLAR_INTERRUPTIONS, he)) == "none" and strict_bool(s4.get("cost_zero_stop", _F)) else it) broot, croot, imsha = (_ck(_HEX_P.match(rs := _s(r.get(k, ""))) is not None, rs.lower(), he) for r, k in zip((s1, s2, s6), _sp("bibliography_merkle_root corpus_merkle_root implicit_metadata_sha256"))) vc_c, st_c, tot_n, gn_c, dag_d, tl_c = (_irng(rall[ri].get(k, 0), 1, hi, he) for ri, k, hi in _CFG["s7i"]) pq, cq, iq, hq = (_rqv(rall[ri].get(k, ""), he, None) for ri, k in _CFG["s7q"]) ssum, elbl = validate_and_mask_prose(s4.get("masked_summary_text", "")), validate_and_mask_prose(s6.get("explicit_user_label", "")) _rq(dag_d <= gn_c and cq >= 0 and 0 <= iq < 1 and Fraction(1, 2) <= hq <= 1 and (not strict_bool(s6.get("high_impact_scholarly_submission", _F)) or strict_bool(s6.get("human_hitl_approved", _F))) and len(ssum.split()) <= _irng(s4.get("budget_b", 10000), 1, 10000, he) and require_int(s4.get("c_levels", 1)) == 1, he) rsubs, qstrs = {r[i : i + 16] for r in (croot, broot, imsha) for i in range(49)}, (*map(fraction_to_str, (pq, cq, iq, hq)),) cf = _kv("evaluation_id verified_citations_count studies_count total_sample_n pooled_effect_q cochran_q higgins_i2_q grounded_nodes_count dag_depth terms_locked_count human_credit_share_q explicit_user_label scholar_summary", (eid, vc_c, st_c, tot_n, *qstrs[:3], gn_c, dag_d, tl_c, qstrs[3], elbl, ssum)) | {_ck(_id(fk) not in ("evaluation_id", "scholar_summary"), fk, he): fv for fk, fv in (() if exf is None else _nmap(exf, he).items())} cf = _clean_dag(cf, lambda ns: _rq(_HEX_LK_P.search(ns) is None, he), he, 2) _rq(not any(h[j : j + 16] in rsubs for m in _H16_P.finditer(_RFOLD_P.sub("", _jcs_enc(cf, 2).decode().lower())) if (h := m.group(0)) for j in range(len(h) - 15)), he) rev = _ck(reg is None or isinstance(reg, ScholarRevocationRegistry), reg.is_revoked(eid) if reg is not None else _F, TypeError) return _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("corpus_merkle_root bibliography_merkle_root implicit_metadata_sha256", (croot, broot, imsha)), intr, rev, bool(intr != "none" or rev or not aok), bool(aok and intr == "none" and not rev))) _S16_FNS = (verify_gbt7714_2025_bibliography_and_pids_s1, verify_multi_study_meta_synthesis_q_s2, verify_mindmap_knowledge_dag_s3, verify_vault_commons_non_interference_s4, verify_terminology_diapason_s5, verify_research_integrity_and_aigc_gate_s6) def _bctx(): return json.loads(_SP_JSON) | json.loads(_CTX_JSON) def build_canonical_scholar_specimen(): ctx = _bctx() rs = [f({k: ctx[k] for k in ks}) for f, ks in zip(_S16_FNS, _CFG["bk"])] return (s7 := build_humble_crystal_scholar_gate_s7(*rs, (i := json.loads(_SP_JSON))["evaluation_id"])) | _kv("protocol_id protocol_version living_folio inputs s1_result s2_result s3_result s4_result s5_result s6_result s7_result", (PROTOCOL_ID, PROTOCOL_VERSION, LIVING_FOLIO, i, *rs, s7)) def _ex(err, fn, *a): try: fn(*a) except err: return _T return _F def _mut(err, fn, base_in, path, val): if not path: return _ex(err, fn, val) cur = cl = json.loads(jcs_canonical_bytes(base_in)) *ps, k = [int(s) if s.isdigit() else s for s in path.split(".")] cur = functools.reduce(lambda c, s: c[s], ps, cur) cur.append(val) if k == "+" else cur.__setitem__(k, val) return _ex(err, fn, cl) def run_self_tests(): t0, fx, flt, spec, reg = time.monotonic_ns(), json.loads(_ST_JSON), json.loads("1.5"), build_canonical_scholar_specimen(), ScholarRevocationRegistry() pub, cm, sr, ctx = {k: v for k, v in spec.items() if k != "inputs"}, spec["cryptographic_commitments"], [*map(spec.get, fx["sr"])], _bctx() | {"cited_bib_ids": None, "valid_bib_ids": None} rts, d64, mp, lvs = [*map(cm.get, _sp("bibliography_merkle_root corpus_merkle_root implicit_metadata_sha256"))], functools.reduce(lambda x, _: [x], range(63), [0]), rule14_mask_veritas_text(fx["pii"]), [b"a", b"b", b"c"] zfd, fns, bs = assert_output_rule14_clean(pub) and _FD.encode() not in jcs_canonical_bytes([spec["inputs"], pub]), (*_S16_FNS, validate_and_mask_prose, lambda d: build_humble_crystal_scholar_gate_s7(*sr, "E", "none", None, d)), [{k: ctx[k] for k in ks} for ks in _CFG["bk"]] + [0, 0] for e, p in fx["rg"]: reg.revoke_evaluation(e, RETRACTED_CITATION_HALT) if p == "!" else reg.register_evaluation(e, p) vg = build_humble_crystal_scholar_gate_s7(*sr, "B1C", HUMAN_PI_VETO, reg) _rq((rts, spec["eligible_for_w3c_vc"], zfd, sr[2]["topological_order"], rule14_mask_veritas_text(mp), _S16_FNS[0](fx["bo"])["verified"], [*map(reg.is_revoked, _sp("B1C B1D B2")), *map(vg.get, _sp("revoked q3_zero_twist_enforced eligible_for_w3c_vc"))]) == (fx["rts"], _T, _T, fx["to"], mp, _T, [_T, _T, _F, _T, _T, _F]) and _ex(ValueError, jcs_canonical_bytes, [d64]) and rfc6962_verify_inclusion(b"b", 1, 3, rfc6962_inclusion_proof(lvs, 1), rfc6962_merkle_root(lvs)) and all(_ex(TypeError, fn, flt) for fn in (require_int, parse_rational_q, fraction_to_str, jcs_canonical_bytes, _S16_FNS[0])) and all(_mut(globals()[en], fns[fi], bs[fi], p, v) for fi, en, p, v in (*fx["mt"], (6, "PlaceholderDisclosureError", "", f"ACTION {'TO'}DO LIST"), (7, "HumbleCrystalGateError", "", {"leak": d64}))) and all(t in mp for t in fx["ptk"])) dt = (time.monotonic_ns() - t0) // 1_000_000 return _kv(fx["rk"], (_T, 8, _kv(fx["mk"], (_T,) * 8), zfd, dt + (_FD in str(dt)), rts[1], rts[0], rts[2])) if __name__ == "__main__": print(f"OK Folio XII scholar_veritas_core self-tests: {jcs_canonical_bytes(run_self_tests()).decode('utf-8')}")