{"site-index.html.txt":"\nTRUTHGUARDGLOBAL — Evidence before answers\nSkip to content
TGTRUTHGUARDGLOBAL
\n

OPEN RESEARCH INITIATIVE / WEB 2.1

Evidence before answers.

The same factual standard for every person. An open research initiative for preserving evidence, independently reviewing knowledge and making corrections transparent.

Research prototype · Global AI integration is not yet established.

\n
MITOriginal code license
—Source files in manifest
SHA-256Browser integrity checks
EN / TRCurrent UI languages
\n

01 / STANDARD

One factual foundation. Everyone.

A first-time user deserves the same factual standard as an expert. Private conversations are not shared without permission; expertise cannot replace evidence. Uncertainty, scope and legitimate disagreement must be preserved.

01

Hard copy

Preserve provenance with lawful source snapshots, dates, links and content digests.

02

Independent verification

Review the claim, scope, source independence and counterevidence.

03

Versions & corrections

Check freshness, signatures and revocations; research again when necessary.

A checksum or signature proves integrity, not the factual truth of a claim.

Read the technical protocol →
\n

02 / DEVELOPER CENTER

Open source library

Search, preview, download and compare source files against the manifest. MIT licensing applies to original software.

Select a file

\n

03 / VERIFICATION LAB

Verify a file yourself.

Compute the SHA-256 digest of a local file and compare it with an expected digest from a trusted source. Your file stays in your browser.

\n

04 / GLOBAL CONTRIBUTION

Improve a claim or the code.

Export a structured evidence, correction or code proposal. Remote submissions and a public GitHub contribution repository are not connected yet.

\n

05 / TRANSPARENCY

Development status

Completed work and future targets are kept separate.

Published

Code & protocol

Source library, technical documentation, integrity tools and local contribution drafts.

Outstanding

Open collaboration

Independent public GitHub repository, submission queue, governance and reviewer network.

Outstanding

Real-world evaluation

Independent accuracy evaluation, 33-language target, production API and AI provider integrations.

\n","site-style.css.txt":":root{color-scheme:light;--bg:#f4f7f6;--surface:#fff;--ink:#172d35;--muted:#50636a;--border:#d8e2e0;--accent:#08705e;--hero:#102b35;--hero-ink:#f1f8f6;--code:#14262d;--code-ink:#dcebe5;--focus:#13947c;--notice:#fff9e8;--notice-ink:#684b19}html[data-theme=dark]{color-scheme:dark;--bg:#101b22;--surface:#17272f;--ink:#eff7f4;--muted:#aebfc4;--border:#354952;--accent:#85d9bd;--hero:#122a33;--notice:#382f21;--notice-ink:#f5d99e}*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.65 system-ui,-apple-system,BlinkMacSystemFont,\"Segoe UI\",sans-serif}a{color:var(--accent);text-underline-offset:4px}button,input,textarea,select{font:inherit}button,a,input,textarea,select{touch-action:manipulation}button,a.primary,a.secondary{cursor:pointer}button:disabled{cursor:not-allowed;opacity:.5}:focus-visible{outline:3px solid var(--focus);outline-offset:4px}.skip{position:absolute;left:-9999px}.skip:focus{left:16px;top:16px;z-index:10;background:var(--surface);padding:8px}.top{background:var(--surface);border-bottom:1px solid var(--border)}.top-inner,nav,main,footer{max-width:1230px;margin:auto;padding-left:28px;padding-right:28px}.top-inner{display:flex;justify-content:space-between;align-items:center;padding-top:18px;padding-bottom:14px;gap:15px}.brand{display:flex;align-items:center;gap:11px;color:var(--ink);text-decoration:none;font-size:14px;font-weight:850;letter-spacing:.06em;line-height:1.15}.brand small{display:block;font-size:10px;letter-spacing:.2em;color:var(--muted);margin-top:4px}.mark{display:grid;place-content:center;width:42px;height:42px;background:#123f42;color:#fff;border-radius:9px;font-size:22px;letter-spacing:-.17em;padding-right:4px}.mark span{display:inline;color:#a7dfc8}.controls{display:flex;gap:8px}button,.secondary,.primary{display:inline-flex;align-items:center;justify-content:center;min-height:42px;border:1px solid var(--border);border-radius:7px;background:var(--surface);color:var(--ink);font-weight:650;padding:9px 15px;text-decoration:none}.primary{background:#08705e;color:#fff;border-color:#08705e}.controls button{font-size:13px;min-height:36px;padding:5px 10px}nav{display:flex;gap:24px;overflow:auto;white-space:nowrap}nav a{display:inline-block;padding:11px 0 14px;color:var(--muted);font-size:14px;font-weight:650;text-decoration:none}nav a:hover{color:var(--accent)}main{padding-top:24px;padding-bottom:45px}.hero{background:var(--hero);color:var(--hero-ink);border-radius:16px;display:grid;grid-template-columns:minmax(0,1.7fr) minmax(0,1fr);gap:36px;padding:44px;align-items:center}.hero h1{font-size:clamp(42px,5.7vw,79px);line-height:1.04;letter-spacing:-.06em;margin:16px 0}.kicker{font-size:11px;font-weight:800;letter-spacing:.16em;color:var(--accent);margin:0 0 12px}.hero .kicker{color:#a5dfcb}.lead{font-size:19px;color:#c4dadb;max-width:690px;margin:20px 0}.hero .secondary{background:transparent;color:#eef7f5;border-color:#709293}.actions{display:flex;gap:10px;flex-wrap:wrap;margin:20px 0}.fine{font-size:13px;color:var(--muted)}.hero .fine{color:#bbcccf}.hero-side{border:1px solid #476771;border-radius:12px;padding:23px;background:#173943}.chain{display:grid;gap:8px}.chain div{display:flex;align-items:center;gap:12px;padding:12px;background:#21464e;border-radius:6px;font-size:14px}.chain span{color:#abdfce;font-size:12px;font-weight:800}.metrics{display:grid;grid-template-columns:repeat(4,1fr);background:var(--surface);border:1px solid var(--border);border-radius:12px;margin:16px 0 0}.metrics div{padding:18px;border-right:1px solid var(--border)}.metrics div:last-child{border:0}.metrics strong{display:block;font-size:21px;letter-spacing:-.03em}.metrics span{display:block;color:var(--muted);font-size:13px}section:not(.hero):not(.metrics){padding:49px 0;border-bottom:1px solid var(--border);scroll-margin-top:12px}.section-head{max-width:850px;margin-bottom:24px}.section-head h2{font-size:clamp(26px,3.5vw,39px);line-height:1.15;letter-spacing:-.035em;margin:0 0 12px}.section-head p:not(.kicker){color:var(--muted);margin:0}.three{display:grid;grid-template-columns:repeat(3,1fr);gap:15px}.three article,.explain,.lab,.workspace,.road{background:var(--surface);border:1px solid var(--border);border-radius:12px}.three article{padding:23px}.index{font-size:12px;color:var(--accent);font-weight:800}.three h3,.explain h3,.road h3{font-size:18px;margin:8px 0}.three p,.explain p,.road p{color:var(--muted);margin:0 0 10px}.notice{background:var(--notice);color:var(--notice-ink);padding:14px 18px;border-left:3px solid #c49b56;border-radius:5px;margin:20px 0}.workspace{display:grid;grid-template-columns:minmax(220px,1fr) minmax(0,2fr);overflow:hidden}.files-panel{padding:18px;min-width:0}.files{display:grid;gap:5px;max-height:460px;overflow:auto}.files button{text-align:left;justify-content:flex-start;font-size:13px;font-weight:600;overflow-wrap:anywhere;min-width:0}.files button[aria-pressed=true]{border-color:var(--accent);color:var(--accent)}.code-panel{min-width:0;background:var(--code);color:var(--code-ink);padding:15px 18px}.panel-bar{display:flex;gap:8px;align-items:center;flex-wrap:wrap;border-bottom:1px solid #40565c;padding-bottom:10px}.panel-bar strong{margin-right:auto;font-size:14px;overflow-wrap:anywhere}.panel-bar button,.panel-bar a{font-size:12px;min-height:30px;padding:3px 8px;color:#e4f2ec;background:#254149;border:1px solid #587173;border-radius:4px}.code-panel .fine{color:#b7ccca}pre{margin:12px 0 0;overflow:auto;max-height:460px;min-height:330px;font:12px/1.6 ui-monospace,SFMono-Regular,Consolas,monospace;white-space:pre}.lab{display:grid;grid-template-columns:minmax(0,1.6fr) minmax(0,1fr);gap:20px;padding:22px}.explain{background:var(--bg);padding:22px;align-self:start}label{display:block;font-weight:700;font-size:14px;margin:12px 0 5px}input:not([type=checkbox]),textarea,select{display:block;width:100%;border:1px solid var(--border);background:var(--surface);color:var(--ink);border-radius:7px;padding:10px;min-height:42px}input[type=file]{padding:7px;font-size:13px}textarea{resize:vertical}.lab form>.primary{margin-top:16px}.digest{display:block;overflow-wrap:anywhere;color:var(--accent);font-family:monospace;font-size:14px}.check{display:flex;align-items:flex-start;gap:10px;font-weight:500}.check input{width:18px;height:18px;flex-shrink:0;margin-top:4px}.road{display:grid;gap:0}.road>div{padding:20px;border-bottom:1px solid var(--border)}.road>div:last-child{border:0}.tag{font-size:12px;color:var(--muted);border:1px solid var(--border);padding:3px 8px;border-radius:5px}.tag.done{color:var(--accent);border-color:var(--accent)}footer{display:flex;justify-content:space-between;gap:20px;flex-wrap:wrap;padding-top:24px;padding-bottom:40px;color:var(--muted);font-size:14px}footer p{margin:5px 0}@media(max-width:780px){.hero,.workspace,.lab{grid-template-columns:1fr}.hero{padding:28px;gap:20px}.three{grid-template-columns:1fr}.metrics{grid-template-columns:repeat(2,1fr)}.metrics div:nth-child(2){border-right:0}.metrics div:nth-child(-n+2){border-bottom:1px solid var(--border)}.files{max-height:220px}pre{min-height:160px;max-height:350px}.top-inner,nav,main,footer{padding-left:16px;padding-right:16px}nav{gap:17px}.hero-side{padding:16px}.hero .lead{font-size:17px}}@media(prefers-reduced-motion:reduce){html{scroll-behavior:auto}}[hidden]{display:none!important}","site-app.js.txt":"'use strict';\nconst $=id=>document.getElementById(id);const nodes=[...document.querySelectorAll('[data-tr]')];nodes.forEach(n=>n.dataset.en=n.textContent);\nlet lang='en',theme='light',entries=[],selected=null,preview='',requestId=0;\ntry{lang=localStorage.getItem('tg-lang')==='tr'?'tr':'en';theme=localStorage.getItem('tg-theme')==='dark'?'dark':'light'}catch{}\nconst t=(en,tr)=>lang==='tr'?tr:en;\nfunction setLang(){document.documentElement.lang=lang;nodes.forEach(n=>{if(n.id!=='selected-name'||!selected)n.textContent=n.dataset[lang]});$('language').textContent=lang==='tr'?'TR / EN':'EN / TR';try{localStorage.setItem('tg-lang',lang)}catch{}renderFiles()}\nfunction setTheme(){document.documentElement.dataset.theme=theme;try{localStorage.setItem('tg-theme',theme)}catch{}}\n$('language').addEventListener('click',()=>{lang=lang==='en'?'tr':'en';setLang()});$('theme').addEventListener('click',()=>{theme=theme==='light'?'dark':'light';setTheme()});\nasync function sha(bytes){const d=await crypto.subtle.digest('SHA-256',bytes);return [...new Uint8Array(d)].map(x=>x.toString(16).padStart(2,'0')).join('')}\nfunction renderFiles(){const q=$('search').value.toLowerCase().trim();const list=entries.filter(e=>e.path.toLowerCase().includes(q));$('files').replaceChildren();$('library-status').textContent=entries.length?t(list.length+' files',list.length+' dosya'):t('Loading source manifest…','Kaynak listesi yükleniyor…');for(const e of list){const b=document.createElement('button');b.type='button';b.textContent=e.path.split('/').pop();b.setAttribute('aria-pressed',String(selected?.path===e.path));b.addEventListener('click',()=>openFile(e));$('files').append(b)}}\nasync function openFile(e){selected=e;let id=++requestId;preview='';$('copy').disabled=true;$('download').hidden=true;$('selected-name').textContent=e.path.split('/').pop();$('code').textContent='';$('code-status').textContent=t('Loading…','Yükleniyor…');renderFiles();try{const r=await fetch(e.path,{cache:'no-cache'});if(!r.ok)throw Error('HTTP '+r.status);const b=await r.arrayBuffer();const actual=await sha(b);if(id!==requestId)return;preview=new TextDecoder().decode(b);$('code').textContent=preview;$('copy').disabled=false;if(actual===e.sha256){$('download').href=e.path;$('download').hidden=false;$('code-status').textContent=t('Matches published manifest. This does not prove factual accuracy.','Yayımlanan dosya özetiyle eşleşiyor. Olgusal doğruluğu kanıtlamaz.')}else{$('code-status').textContent=t('Digest mismatch — do not trust this copy.','Dosya özeti uyuşmuyor — bu kopyaya güvenmeyin.');$('copy').disabled=true}}catch{if(id===requestId)$('code-status').textContent=t('File or integrity check unavailable.','Dosya veya bütünlük kontrolü kullanılamıyor.')}}\n$('search').addEventListener('input',renderFiles);$('copy').addEventListener('click',async()=>{try{await navigator.clipboard.writeText(preview);$('code-status').textContent=t('Copied.','Kopyalandı.')}catch{$('code-status').textContent=t('Clipboard unavailable. Select and copy the text.','Pano kullanılamıyor. Metni seçip kopyalayın.')}});\n$('hash-form').addEventListener('submit',async e=>{e.preventDefault();$('hash-output').textContent='';const f=$('hash-file').files[0],expected=$('expected').value.trim().toLowerCase();if(!f||f.size>25*1024*1024){$('hash-result').textContent=t('Choose a file no larger than 25 MB.','En fazla 25 MB dosya seçin.');return}if(expected&&!/^[a-f0-9]{64}$/.test(expected)){$('hash-result').textContent=t('Expected digest must contain 64 hexadecimal characters.','Beklenen özet 64 onaltılık karakter olmalı.');return}try{const h=await sha(await f.arrayBuffer());$('hash-output').textContent=h;$('hash-result').textContent=expected?(expected===h?t('MATCH — file integrity confirmed.','EŞLEŞTİ — dosya bütünlüğü doğrulandı.'):t('MISMATCH — contents differ.','UYUŞMAZLIK — içerik farklı.')):t('Digest computed; no expected value supplied.','Özet hesaplandı; karşılaştırma değeri verilmedi.')}catch{$('hash-result').textContent=t('Digest unavailable in this browser.','Bu tarayıcıda özet hesaplanamadı.')}});\n$('proposal').addEventListener('submit',e=>{e.preventDefault();const src=$('source-url').value.trim();if(src&&!/^https?:\\/\\//i.test(src)){$('proposal-result').textContent=t('Use a public HTTP(S) URL.','Kamuya açık HTTP(S) bağlantısı kullanın.');return}const data={schema:'truthguard-contribution-v2',kind:$('kind').value,title:$('topic').value.trim(),public_source:src,details:$('details').value.trim(),created_at:new Date().toISOString(),status:'local_draft_not_submitted'};if(!data.title||!data.details){$('proposal-result').textContent=t('Title and details are required.','Başlık ve ayrıntı gereklidir.');return}const u=URL.createObjectURL(new Blob([JSON.stringify(data,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=u;a.download='truthguard-contribution.json';a.click();setTimeout(()=>URL.revokeObjectURL(u),1000);$('proposal-result').textContent=t('Draft downloaded; not submitted.','Taslak indirildi; gönderilmedi.')});\nsetTheme();setLang();\n(async()=>{try{const r=await fetch('/source/manifest.json',{cache:'no-cache'});if(!r.ok)throw Error('manifest');const m=await r.json();entries=m.files.filter(e=>typeof e.path==='string'&&/^\\/source\\/[A-Za-z0-9_.-]+$/.test(e.path)&&/^[a-f0-9]{64}$/.test(e.sha256));$('file-count').textContent=entries.length;renderFiles();if(entries.length)openFile(entries.find(e=>e.path.endsWith('/hard_copy.py'))||entries[0])}catch{$('library-status').textContent=t('Source manifest unavailable.','Kaynak listesi kullanılamıyor.')}})();","site-global.html.txt":"Global manifesto — TRUTHGUARDGLOBAL
TRUTHGUARDGLOBALHome / Ana sayfa

GLOBAL / 33 LANGUAGES

Global manifesto

33 draft translations of the core mission. Native-speaker review is pending. This is not a complete 33-language website translation.

Temel amacın 33 dilde taslak çevirisi. Ana dili konuşan uzmanların denetimi bekleniyor. Sitenin tamamının 33 dile çevrildiği anlamına gelmez.

English

Evidence before answers. The same factual accuracy standard for everyone.

Türkçe

Cevaptan önce kanıt. Herkes için aynı olgusal doğruluk standardı.

العربية

الأدلة قبل الإجابات. معيار واحد لدقة الحقائق للجميع.

Español

La evidencia antes que las respuestas. El mismo estándar de exactitud factual para todos.

Français

Les preuves avant les réponses. La même exigence d’exactitude factuelle pour tous.

Deutsch

Belege vor Antworten. Derselbe Maßstab für faktische Genauigkeit für alle.

Italiano

Le prove prima delle risposte. Lo stesso standard di accuratezza fattuale per tutti.

Português

Evidências antes das respostas. O mesmo padrão de exatidão factual para todos.

Русский

Доказательства прежде ответов. Единый стандарт фактической точности для всех.

中文

先有证据,再给答案。人人享有同等的事实准确性标准。

日本語

回答より先に根拠を。すべての人に同じ事実の正確性の基準を。

한국어

답변보다 증거가 먼저입니다. 모두에게 동일한 사실 정확성 기준을 적용합니다.

हिन्दी

उत्तर से पहले प्रमाण। सभी के लिए तथ्यात्मक सटीकता का समान मानक।

বাংলা

উত্তরের আগে প্রমাণ। সবার জন্য তথ্যগত নির্ভুলতার একই মানদণ্ড।

اردو

جواب سے پہلے ثبوت۔ سب کے لیے حقائق کی درستگی کا یکساں معیار۔

Bahasa Indonesia

Bukti sebelum jawaban. Standar akurasi faktual yang sama untuk semua.

Bahasa Melayu

Bukti sebelum jawapan. Piawaian ketepatan fakta yang sama untuk semua.

Filipino

Ebidensya bago sagot. Iisang pamantayan ng katumpakan ng mga katotohanan para sa lahat.

Tiếng Việt

Bằng chứng trước câu trả lời. Cùng một tiêu chuẩn chính xác về sự thật cho mọi người.

ไทย

หลักฐานมาก่อนคำตอบ มาตรฐานความถูกต้องของข้อเท็จจริงเดียวกันสำหรับทุกคน

Kiswahili

Ushahidi kabla ya majibu. Kiwango sawa cha usahihi wa ukweli kwa kila mtu.

فارسی

شواهد پیش از پاسخ‌ها. معیار یکسان دقت اطلاعات واقعی برای همه.

עברית

ראיות לפני תשובות. אותו תקן לדיוק עובדתי לכולם.

Українська

Докази перед відповідями. Єдиний стандарт фактичної точності для всіх.

Polski

Dowody przed odpowiedziami. Ten sam standard poprawności faktów dla wszystkich.

Nederlands

Bewijs vóór antwoorden. Dezelfde norm voor feitelijke juistheid voor iedereen.

Svenska

Belägg före svar. Samma standard för faktamässig korrekthet för alla.

Ελληνικά

Πρώτα τα τεκμήρια, μετά οι απαντήσεις. Το ίδιο πρότυπο ακρίβειας των γεγονότων για όλους.

Română

Dovezi înainte de răspunsuri. Același standard de acuratețe factuală pentru toți.

Čeština

Důkazy před odpověďmi. Stejný standard faktické přesnosti pro všechny.

தமிழ்

பதில்களுக்கு முன் ஆதாரம். அனைவருக்கும் ஒரே உண்மைத் துல்லியத் தரநிலை.

తెలుగు

సమాధానాల కంటే ముందు ఆధారాలు. అందరికీ ఒకే వాస్తవ ఖచ్చితత్వ ప్రమాణం.

नेपाली

उत्तरभन्दा पहिले प्रमाण। सबैका लागि तथ्यगत शुद्धताको समान मापदण्ड।

","site-math.html.txt":"Exact arithmetic — TRUTHGUARDGLOBAL
TRUTHGUARDGLOBALHome / Ana sayfa

Exact arithmetic / Kesin aritmetik

Independent calculation route. Decimal inputs are converted into exact rational numbers; no floating-point approximation. Only the four supported arithmetic operations are verified. / Ondalık sayılar tam kesirlere dönüştürülür; yalnızca dört temel işlem doğrulanır.

","site-math.js.txt":"function rational(a,b,op){\n const parse=s=>{if(typeof s!==\"string\"||!/^[-+]?\\d{1,100}(?:\\.\\d{1,100})?$/.test(s.trim()))throw Error(\"invalid\");s=s.trim();let neg=s[0]===\"-\";s=s.replace(/^[-+]/,\"\");let [w,d=\"\"]=s.split(\".\");return [BigInt(w+d)*(neg?-1n:1n),10n**BigInt(d.length)]};\n let [x,y]=parse(a),[u,v]=parse(b),n,d;\n switch(op){case \"+\":n=x*v+u*y;d=y*v;break;case \"-\":n=x*v-u*y;d=y*v;break;case \"*\":n=x*u;d=y*v;break;case \"/\":if(u===0n)throw Error(\"zero\");n=x*v;d=y*u;break;default:throw Error(\"operation\")}\n if(d<0n){n=-n;d=-d}let p=n<0n?-n:n,q=d;while(q){[p,q]=[q,p%q]}return [String(n/p),String(d/p)];\n}\ndocument.getElementById(\"math-form\").addEventListener(\"submit\",e=>{e.preventDefault();const $=id=>document.getElementById(id);try{const [n,d]=rational($(\"a\").value,$(\"b\").value,$(\"op\").value);$(\"math-result\").textContent=\"Exact result / Kesin sonuç: \"+(d===\"1\"?n:n+\" / \"+d)}catch{$(\"math-result\").textContent=\"Invalid input or division by zero / Geçersiz girdi veya sıfıra bölme\"}});","site-arithmetic-tests.json.txt":"{\n \"scope\": \"exact rational arithmetic only\",\n \"test_count\": 10,\n \"passed\": 10,\n \"cases\": [\n {\n \"a\": \"0.1\",\n \"b\": \"0.2\",\n \"o\": \"+\",\n \"expected\": \"3/10\",\n \"actual\": \"3/10\",\n \"pass\": true\n },\n {\n \"a\": \"1\",\n \"b\": \"3\",\n \"o\": \"/\",\n \"expected\": \"1/3\",\n \"actual\": \"1/3\",\n \"pass\": true\n },\n {\n \"a\": \"-6\",\n \"b\": \"-8\",\n \"o\": \"/\",\n \"expected\": \"3/4\",\n \"actual\": \"3/4\",\n \"pass\": true\n },\n {\n \"a\": \"2.50\",\n \"b\": \"4\",\n \"o\": \"*\",\n \"expected\": \"10/1\",\n \"actual\": \"10/1\",\n \"pass\": true\n },\n {\n \"a\": \"1.25\",\n \"b\": \"2.5\",\n \"o\": \"-\",\n \"expected\": \"-5/4\",\n \"actual\": \"-5/4\",\n \"pass\": true\n },\n {\n \"a\": \"0\",\n \"b\": \"7\",\n \"o\": \"/\",\n \"expected\": \"0/1\",\n \"actual\": \"0/1\",\n \"pass\": true\n },\n {\n \"a\": \"99999999999999999999\",\n \"b\": \"1\",\n \"o\": \"+\",\n \"expected\": \"100000000000000000000/1\",\n \"actual\": \"100000000000000000000/1\",\n \"pass\": true\n },\n {\n \"a\": \"1\",\n \"b\": \"0\",\n \"o\": \"/\",\n \"expected\": \"error\",\n \"actual\": \"error\",\n \"pass\": true\n },\n {\n \"a\": \"1e3\",\n \"b\": \"2\",\n \"o\": \"+\",\n \"expected\": \"error\",\n \"actual\": \"error\",\n \"pass\": true\n },\n {\n \"a\": \"4\",\n \"b\": \"3\",\n \"o\": \"?\",\n \"expected\": \"error\",\n \"actual\": \"error\",\n \"pass\": true\n }\n ]\n}","truth_guard.py":"\"\"\"Fail-closed evidence policy gate; not a factuality oracle.\"\"\"\nfrom datetime import datetime, timezone, timedelta\nfrom urllib.parse import urlparse\nimport unittest\nimport hashlib\nimport json\n\n\ndef stamp(value):\n d = datetime.fromisoformat(value.replace('Z', '+00:00'))\n if d.tzinfo is None or d.utcoffset() is None:\n raise ValueError('Timezone required')\n return d\n\n\ndef gate(claims, attestations, *, now, trusted_verifiers, high_risk=True,\n max_age_hours=24):\n \"\"\"Attestations MUST come from a trusted external verifier, never the LLM.\n An ALLOW result concerns policy compliance only, not guaranteed truth.\n high_risk is retained for compatibility; False never relaxes the rule.\n \"\"\"\n try:\n cutoff = timedelta(hours=max_age_hours)\n if not isinstance(now, datetime) or now.utcoffset() is None or cutoff <= timedelta(0):\n raise ValueError('Invalid clock or freshness window')\n if not isinstance(claims, list) or not claims or not isinstance(attestations, list):\n raise ValueError('Missing claims or attestations')\n ids = set()\n results = []\n for c in claims:\n cid, statement, kind = c['id'], c['text'], c['kind']\n if not isinstance(cid, str) or not cid.strip() or cid in ids:\n raise ValueError('Invalid or duplicate claim ID')\n ids.add(cid)\n if not isinstance(statement, str) or not statement.strip() or kind not in ('fact', 'forecast', 'opinion'):\n raise ValueError('Invalid claim')\n if type(c.get('current')) is not bool:\n raise ValueError('Explicit freshness classification required')\n reasons, origins, hosts, citations = [], set(), set(), []\n method_reviewed = False\n if kind == 'opinion':\n reasons.append('Opinion label cannot bypass factual verification')\n if kind != 'opinion':\n for a in attestations:\n if a.get('claim_id') != cid or a.get('claim_text') != statement:\n continue\n if a.get('verifier') not in trusted_verifiers:\n continue\n verdict = a['verdict']\n if verdict == 'contradicts':\n reasons.append('Unresolved contradictory evidence')\n continue\n if verdict != 'supports':\n continue\n u = urlparse(a['url'])\n observed, published, checked = (stamp(a[k]) for k in ('observed_at', 'published_at', 'checked_at'))\n if u.scheme != 'https' or not u.hostname or u.username or u.password:\n continue\n if not observed <= published <= checked <= now or now - checked > cutoff:\n continue\n if c['current'] and now - observed > cutoff:\n continue\n if a.get('primary') is not True or not isinstance(a.get('excerpt'), str) or not a['excerpt'].strip():\n continue\n origin = a['independent_origin']\n if not isinstance(origin, str) or not origin.strip():\n continue\n host = u.hostname.lower().rstrip('.')\n if origin in origins or host in hosts:\n continue\n origins.add(origin); hosts.add(host); citations.append(a['url'])\n if a.get('method_reviewed') is True:\n method_reviewed = True\n if len(origins) < 2:\n reasons.append('Insufficient independent, current primary evidence')\n if kind == 'forecast':\n f = c.get('forecast', {})\n required = ('method', 'assumptions', 'counterevidence', 'invalidation', 'uncertainty', 'horizon')\n if not all(isinstance(f.get(k), str) and f[k].strip() for k in required):\n reasons.append('Forecast methodology or uncertainty missing')\n if f.get('guaranteed') is not False:\n reasons.append('Forecast cannot be guaranteed')\n if not method_reviewed:\n reasons.append('No trusted method review')\n results.append({'id': cid, 'kind': kind, 'status': 'HOLD' if reasons else 'ALLOW',\n 'reasons': reasons, 'citations': citations})\n return {'status': 'HOLD' if any(r['status'] == 'HOLD' for r in results) else 'ALLOW',\n 'claims': results}\n except (KeyError, TypeError, ValueError, AttributeError, OverflowError):\n return {'status': 'HOLD', 'reason': 'Malformed input; verification required'}\n\n\n\ndef response_digest(answer, claims):\n payload = json.dumps([answer, claims], ensure_ascii=False, sort_keys=True,\n separators=(',', ':'), allow_nan=False)\n return hashlib.sha256(payload.encode('utf-8')).hexdigest()\n\n\ndef gate_response(answer, claims, attestations, coverage, *, now,\n trusted_verifiers, max_age_hours=24):\n \"\"\"Require an external review of the exact answer and complete inventory.\n The caller must authenticate the coverage review and all attestations.\n \"\"\"\n try:\n if not isinstance(answer, str) or not answer.strip():\n raise ValueError('Missing answer')\n if (coverage.get('verifier') not in trusted_verifiers\n or coverage.get('complete') is not True\n or coverage.get('presentation_checked') is not True\n or coverage.get('digest') != response_digest(answer, claims)):\n return {'status': 'HOLD', 'reason': 'Complete answer review required'}\n checked = stamp(coverage['checked_at'])\n if not timedelta(0) <= now - checked <= timedelta(hours=max_age_hours):\n return {'status': 'HOLD', 'reason': 'Coverage review expired or future dated'}\n return gate(claims, attestations, now=now,\n trusted_verifiers=trusted_verifiers, max_age_hours=max_age_hours)\n except (KeyError, TypeError, ValueError, AttributeError, OverflowError):\n return {'status': 'HOLD', 'reason': 'Invalid response review'}\n\n\nclass GuardTests(unittest.TestCase):\n def setUp(self):\n self.now = stamp('2026-12-04T00:00:00Z')\n self.claim = {'id': 'c1', 'text': 'Synthetic test claim', 'kind': 'fact', 'current': True}\n self.a = {'claim_id': 'c1', 'claim_text': self.claim['text'], 'verifier': 'reviewer',\n 'verdict': 'supports', 'url': 'https://example.org/a', 'primary': True,\n 'excerpt': 'Synthetic test fixture, not actual evidence', 'independent_origin': 'A',\n 'observed_at': '2026-12-03T23:00:00Z', 'published_at': '2026-12-03T23:10:00Z',\n 'checked_at': '2026-12-03T23:30:00Z'}\n self.b = dict(self.a, url='https://example.net/b', independent_origin='B')\n\n def check(self, claims, evidence, expected):\n self.assertEqual(gate(claims, evidence, now=self.now,\n trusted_verifiers={'reviewer'})['status'], expected)\n\n def test_two_independent(self): self.check([self.claim], [self.a, self.b], 'ALLOW')\n def test_missing(self): self.check([self.claim], [], 'HOLD')\n def test_duplicate_origin(self): self.check([self.claim], [self.a, dict(self.b, independent_origin='A')], 'HOLD')\n def test_duplicate_host(self): self.check([self.claim], [self.a, dict(self.b, url='https://example.org/b')], 'HOLD')\n def test_untrusted(self): self.check([self.claim], [self.a, dict(self.b, verifier='model')], 'HOLD')\n def test_mismatch(self): self.check([self.claim], [self.a, dict(self.b, claim_text='Different claim')], 'HOLD')\n def test_stale(self): self.check([self.claim], [self.a, dict(self.b, observed_at='2026-11-01T00:00:00Z')], 'HOLD')\n def test_future(self): self.check([self.claim], [self.a, dict(self.b, checked_at='2026-12-05T00:00:00Z')], 'HOLD')\n def test_conflict(self): self.check([self.claim], [self.a, self.b, dict(self.a, verdict='contradicts')], 'HOLD')\n def test_forecast(self): self.check([dict(self.claim, kind='forecast')], [self.a, self.b], 'HOLD')\n def test_valid_forecast(self):\n f = {k: 'Synthetic fixture' for k in ('method', 'assumptions', 'counterevidence', 'invalidation', 'uncertainty', 'horizon')}\n f['guaranteed'] = False\n self.check([dict(self.claim, kind='forecast', forecast=f)], [dict(self.a, method_reviewed=True), self.b], 'ALLOW')\n def test_opinion_bypass(self): self.check([dict(self.claim, kind='opinion')], [], 'HOLD')\n def test_malformed(self): self.check([{}], [], 'HOLD')\n def test_empty(self): self.check([], [], 'HOLD')\n def test_duplicate_claim(self): self.check([self.claim, self.claim], [self.a, self.b], 'HOLD')\n\n def test_no_low_risk_bypass(self):\n self.assertEqual(gate([self.claim], [self.a], now=self.now,\n trusted_verifiers={'reviewer'}, high_risk=False)['status'], 'HOLD')\n def test_no_low_risk_opinion_bypass(self):\n self.assertEqual(gate([dict(self.claim, kind='opinion')], [], now=self.now,\n trusted_verifiers={'reviewer'}, high_risk=False)['status'], 'HOLD')\n def test_response_coverage(self):\n claims, answer = [self.claim], self.claim['text']\n review = {'verifier': 'reviewer', 'complete': True, 'presentation_checked': True,\n 'digest': response_digest(answer, claims), 'checked_at': self.now.isoformat()}\n def check(text, inventory, coverage, expected):\n self.assertEqual(gate_response(text, inventory, [self.a, self.b], coverage,\n now=self.now, trusted_verifiers={'reviewer'})['status'], expected)\n check(answer, claims, review, 'ALLOW')\n check(answer, claims, {}, 'HOLD')\n check(answer + ' Extra unchecked claim.', claims, review, 'HOLD')\n check(answer, [], review, 'HOLD')\n check(answer, claims, dict(review, complete=False), 'HOLD')\n check(answer, claims, dict(review, presentation_checked=False), 'HOLD')\n check(answer, claims, dict(review, verifier='model'), 'HOLD')\n check(answer, claims, dict(review, checked_at='2026-12-05T00:00:00Z'), 'HOLD')\n\n\nif __name__ == '__main__':\n unittest.main()\n","knowledge_registry.py":"\"\"\"Shared public knowledge candidate registry. No private-chat ingestion.\"\"\"\nimport hashlib\nimport json\nfrom datetime import datetime\nfrom truth_guard import gate_response, stamp\n\n\ndef digest(record):\n return hashlib.sha256(json.dumps(record, ensure_ascii=False, sort_keys=True,\n separators=(',', ':'), allow_nan=False).encode()).hexdigest()\n\n\ndef admit(record, *, now, trusted_verifiers, trusted_publishers):\n \"\"\"External authentication, rights and semantic reviews are prerequisites.\"\"\"\n try:\n body = record['body']\n review = record['publication_review']\n if review['reviewer'] not in trusted_publishers or review['digest'] != digest(body):\n return False\n if any(review.get(k) is not True for k in\n ('public_sources_only', 'privacy_checked', 'rights_checked', 'identity_checked')):\n return False\n if not all(isinstance(body.get(k), str) and body[k].strip() for k in\n ('entity_id', 'question_id', 'scope', 'language', 'answer')):\n return False\n if type(body['version']) is not int or body['version'] < 1:\n return False\n if not stamp(body['valid_from']) <= now < stamp(body['expires_at']):\n return False\n if any(c['kind'] != 'fact' for c in body['claims']):\n return False\n return gate_response(body['answer'], body['claims'], body['attestations'],\n body['coverage'], now=now, trusted_verifiers=trusted_verifiers,\n max_age_hours=body['max_age_hours'])['status'] == 'ALLOW'\n except (KeyError, TypeError, ValueError, AttributeError, OverflowError):\n return False\n\n\ndef resolve(records, *, entity_id, question_id, scope, language, now,\n trusted_verifiers, trusted_publishers):\n \"\"\"Do not pick winners by user reputation, votes, or latest upload alone.\"\"\"\n eligible = []\n for r in records:\n try:\n b = r['body']\n if (b['entity_id'], b['question_id'], b['scope'], b['language']) != (\n entity_id, question_id, scope, language):\n continue\n except (TypeError, KeyError):\n continue\n if admit(r, now=now, trusted_verifiers=trusted_verifiers,\n trusted_publishers=trusted_publishers):\n eligible.append(r)\n if not eligible:\n return {'status': 'RESEARCH_REQUIRED'}\n # A revision is not an automatic override. Any overlapping different\n # answer needs reconciliation or explicit expiry/revocation upstream.\n answers = {r['body']['answer'] for r in eligible}\n if len(answers) != 1:\n return {'status': 'CONFLICT_REVIEW_REQUIRED'}\n chosen = max(eligible, key=lambda r: (r['body']['version'], digest(r['body'])))\n return {'status': 'POLICY_APPROVED', 'answer': chosen['body']['answer'],\n 'record_digest': digest(chosen['body']), 'version': chosen['body']['version'],\n 'expires_at': chosen['body']['expires_at']}\n\n\n# This module does not crawl conversations, rank users, authenticate reviewers,\n# perform entity resolution, or assert that approved claims are objectively true.\n","universal_core.py":"\"\"\"Profile-neutral shared knowledge policy, with externally authenticated state.\nThis is not an evidence oracle; never trust a client-supplied checkpoint.\n\"\"\"\nfrom datetime import timedelta\nfrom knowledge_registry import digest, resolve\nfrom truth_guard import stamp\n\n\ndef retrieve(records, *, key, checkpoint, now, trusted_verifiers,\n trusted_publishers, max_age_hours=24):\n \"\"\"No user ID, experience, subscription, or chat history in the factual key.\"\"\"\n hold = {'status': 'RESEARCH_REQUIRED'}\n try:\n if len(key) != 4 or not all(isinstance(x, str) and x.strip() for x in key):\n return hold\n if not timedelta(0) <= now - stamp(checkpoint['checked_at']) <= timedelta(minutes=15):\n return hold\n revoked = set(checkpoint['revoked_digests'])\n floor = checkpoint['version_floors'].get(tuple(key), 1)\n if type(floor) is not int or floor < 1 or max_age_hours <= 0:\n return hold\n eligible = []\n for record in records:\n b = record['body']\n if tuple(b[k] for k in ('entity_id', 'question_id', 'scope', 'language')) != tuple(key):\n continue\n if digest(b) in revoked or b['version'] < floor:\n continue\n if any(d in revoked for d in b.get('dependency_digests', [])):\n continue\n if not 0 < b['max_age_hours'] <= max_age_hours:\n continue\n eligible.append(record)\n result = resolve(eligible, entity_id=key[0], question_id=key[1],\n scope=key[2], language=key[3], now=now,\n trusted_verifiers=trusted_verifiers, trusted_publishers=trusted_publishers)\n if result['status'] == 'POLICY_APPROVED':\n chosen = next(r['body'] for r in eligible if digest(r['body']) == result['record_digest'])\n result['claim_ids'] = sorted(c['id'] for c in chosen['claims'])\n result['core_digest'] = digest(chosen['claims'])\n return result\n except (KeyError, TypeError, ValueError, AttributeError, OverflowError, StopIteration):\n return hold\n\n\ndef parity_report(cases):\n \"\"\"Paired results for identical normalized factual scope and snapshot.\n Missing or abstaining answers are tracked separately; parity is not accuracy.\n \"\"\"\n total = approved = identical = mismatches = unavailable = 0\n for novice, expert in cases:\n total += 1\n if novice.get('status') != 'POLICY_APPROVED' or expert.get('status') != 'POLICY_APPROVED':\n unavailable += 1\n continue\n approved += 1\n fields = ('core_digest', 'claim_ids', 'record_digest')\n if all(novice.get(k) is not None and novice[k] == expert.get(k) for k in fields):\n identical += 1\n else:\n mismatches += 1\n return {'pairs': total, 'both_approved': approved, 'identical_core': identical,\n 'mismatches': mismatches, 'unavailable': unavailable}\n","hard_copy.py":"\"\"\"Signed, evidence-bound answer packages. Integrity is not factual truth.\"\"\"\nimport hashlib\nimport json\nimport re\nfrom datetime import timedelta\nfrom urllib.parse import urlsplit\nfrom cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey\nfrom cryptography.exceptions import InvalidSignature\nfrom truth_guard import stamp\n\n\ndef canonical(value):\n # Project-specific canonical JSON; not an RFC 8785 implementation.\n return json.dumps(value, ensure_ascii=False, sort_keys=True,\n separators=(',', ':'), allow_nan=False).encode('utf-8')\n\n\ndef sha(data):\n return hashlib.sha256(data).hexdigest()\n\n\ndef signed_bytes(role, body):\n return canonical({'protocol': 'TG-HC-1', 'role': role, 'body': body})\n\n\ndef verify_signature(role, body, signature, keyring):\n key = keyring[signature['key_id']]\n if key['role'] != role:\n raise ValueError('Wrong signing role')\n raw = bytes.fromhex(key['public_key'])\n Ed25519PublicKey.from_public_bytes(raw).verify(\n bytes.fromhex(signature['signature']), signed_bytes(role, body))\n return key['org'], raw\n\n\ndef verify_package(body, approvals, blobs, checkpoint, *, keyring, now,\n expected_key, minimum_sequence, max_age_hours=24):\n \"\"\"Caller pins trusted keys, expected scope, clock, and monotonic sequence.\n blobs maps SHA-256 to original UTF-8 evidence bytes; no private-chat ingestion.\n Every approval must come from a separately governed external reviewer.\n \"\"\"\n try:\n if not isinstance(minimum_sequence, int) or minimum_sequence < 0 or max_age_hours <= 0:\n raise ValueError('Invalid local policy')\n cb = checkpoint['body']\n authority, authority_key = verify_signature('checkpoint', cb, checkpoint['signature'], keyring)\n if type(cb['sequence']) is not int or cb['sequence'] < minimum_sequence:\n raise ValueError('Rollback')\n if not timedelta(0) <= now - stamp(cb['checked_at']) <= timedelta(minutes=15):\n raise ValueError('Stale checkpoint')\n if tuple(body['key']) != tuple(expected_key) or len(expected_key) != 4:\n raise ValueError('Scope mismatch')\n if body['schema'] != 'TG-HC-1' or not isinstance(body['answer'], str) or not body['answer'].strip():\n raise ValueError('Invalid answer')\n created, expires = stamp(body['created_at']), stamp(body['expires_at'])\n if not created <= now < expires or now - created > timedelta(hours=max_age_hours):\n raise ValueError('Expired answer')\n package_id = sha(canonical(body))\n revoked = set(cb['revoked'])\n if package_id in revoked or any(x in revoked for x in body['dependencies']):\n raise ValueError('Revoked package or dependency')\n key_id = sha(canonical(body['key']))\n floor = cb['version_floors'].get(key_id, 1)\n if type(body['version']) is not int or type(floor) is not int or body['version'] < max(1, floor):\n raise ValueError('Obsolete version')\n if not isinstance(body['claims'], list) or not body['claims']:\n raise ValueError('Missing claims')\n ids = set()\n for claim in body['claims']:\n cid = claim['id']\n if not isinstance(cid, str) or not cid.strip() or cid in ids:\n raise ValueError('Invalid claim ID')\n ids.add(cid)\n if claim['kind'] != 'fact' or not isinstance(claim['text'], str) or not claim['text'].strip():\n raise ValueError('Only factual claims enter shared core')\n origins, hosts, contents = set(), set(), set()\n for e in claim['evidence']:\n h = e['sha256']\n if not isinstance(h, str) or not re.fullmatch(r'[0-9a-f]{64}', h) or h in revoked:\n raise ValueError('Invalid or revoked evidence')\n data = blobs[h]\n if not isinstance(data, bytes) or not 0 < len(data) <= 2_000_000 or sha(data) != h:\n raise ValueError('Missing or modified hard copy')\n if not isinstance(e['quote'], str) or not e['quote'].strip() or e['quote'] not in data.decode('utf-8'):\n raise ValueError('Quote absent from original')\n url = urlsplit(e['url'])\n if url.scheme != 'https' or not url.hostname or url.username or url.password:\n raise ValueError('Invalid source URL')\n if not stamp(e['published_at']) <= stamp(e['captured_at']) <= created:\n raise ValueError('Invalid capture chronology')\n if not isinstance(e['origin'], str) or not e['origin'].strip():\n raise ValueError('Missing provenance')\n origins.add(e['origin']); hosts.add(url.hostname.lower().rstrip('.')); contents.add(h)\n if min(len(origins), len(hosts), len(contents)) < 2:\n raise ValueError('Independent source route not satisfied')\n orgs, keys = set(), set()\n for approval in approvals:\n a = approval['body']\n org, raw = verify_signature('review', a, approval['signature'], keyring)\n if org == authority or raw == authority_key:\n raise ValueError('Checkpoint and review roles must be separate')\n if a['package_id'] != package_id or not created <= stamp(a['reviewed_at']) <= now:\n raise ValueError('Approval scope or time mismatch')\n if any(a.get(k) is not True for k in ('support_checked', 'independence_checked',\n 'coverage_checked', 'freshness_checked', 'privacy_checked', 'rights_checked')):\n raise ValueError('Incomplete independent review')\n orgs.add(org); keys.add(raw)\n if min(len(orgs), len(keys)) < 2:\n raise ValueError('Two independent reviewers required')\n return {'status': 'VERIFIED_PACKAGE', 'answer': body['answer'],\n 'package_id': package_id, 'checkpoint_sequence': cb['sequence'],\n 'expires_at': body['expires_at']}\n except (KeyError, TypeError, ValueError, AttributeError, OverflowError, InvalidSignature):\n return {'status': 'HOLD'}\n","test_registry.py":"import unittest\nfrom copy import deepcopy\nfrom knowledge_registry import digest, resolve\nfrom truth_guard import GuardTests, response_digest\n\n\nclass RegistryTests(unittest.TestCase):\n def setUp(self):\n fixture = GuardTests()\n fixture.setUp()\n self.args = dict(entity_id='example:entity', question_id='definition',\n scope='global', language='tr', now=fixture.now,\n trusted_verifiers={'reviewer'}, trusted_publishers={'publisher'})\n self.record = {'body': dict(entity_id='example:entity', question_id='definition',\n scope='global', language='tr', version=1,\n answer=fixture.claim['text'], claims=[fixture.claim],\n attestations=[fixture.a, fixture.b], max_age_hours=24,\n valid_from='2026-12-03T00:00:00Z', expires_at='2026-12-05T00:00:00Z')}\n self.record['body']['coverage'] = dict(verifier='reviewer', complete=True,\n presentation_checked=True, checked_at=fixture.now.isoformat(),\n digest=response_digest(fixture.claim['text'], [fixture.claim]))\n self.record['publication_review'] = dict(reviewer='publisher', public_sources_only=True,\n privacy_checked=True, rights_checked=True, identity_checked=True)\n self.seal(self.record)\n\n def seal(self, record):\n record['publication_review']['digest'] = digest(record['body'])\n\n def check(self, records, expected, **kwargs):\n self.assertEqual(resolve(records, **dict(self.args, **kwargs))['status'], expected)\n\n def test_approved(self): self.check([self.record], 'POLICY_APPROVED')\n def test_missing(self): self.check([], 'RESEARCH_REQUIRED')\n def test_wrong_entity(self): self.check([self.record], 'RESEARCH_REQUIRED', entity_id='other')\n def test_wrong_language(self): self.check([self.record], 'RESEARCH_REQUIRED', language='en')\n def test_expiry(self):\n self.record['body']['expires_at'] = '2026-12-03T23:59:00Z'\n self.seal(self.record)\n self.check([self.record], 'RESEARCH_REQUIRED')\n def test_privacy(self):\n self.record['publication_review']['privacy_checked'] = False\n self.check([self.record], 'RESEARCH_REQUIRED')\n def test_tampering(self):\n self.record['body']['version'] = 2\n self.check([self.record], 'RESEARCH_REQUIRED')\n def test_conflict(self):\n other = deepcopy(self.record)\n b = other['body']; b['answer'] = b['claims'][0]['text'] = 'Another synthetic claim'\n for a in b['attestations']: a['claim_text'] = b['answer']\n b['coverage']['digest'] = response_digest(b['answer'], b['claims'])\n b['version'] = 2; self.seal(other)\n self.check([self.record, other], 'CONFLICT_REVIEW_REQUIRED')\n\n\nif __name__ == '__main__':\n unittest.main()\n","test_universal.py":"import unittest\nfrom copy import deepcopy\nimport test_registry\nfrom knowledge_registry import digest\nfrom universal_core import retrieve, parity_report\n\n\nclass UniversalTests(unittest.TestCase):\n def setUp(self):\n fixture = test_registry.RegistryTests(); fixture.setUp()\n self.r = fixture.record\n self.args = {k: fixture.args[k] for k in ('now', 'trusted_verifiers', 'trusted_publishers')}\n self.key = ('example:entity', 'definition', 'global', 'tr')\n self.checkpoint = {'checked_at': self.args['now'].isoformat(), 'revoked_digests': [], 'version_floors': {}}\n\n def get(self):\n return retrieve([self.r], key=self.key, checkpoint=self.checkpoint, **self.args)\n\n def test_equal_core(self):\n a, b = self.get(), self.get()\n self.assertEqual(a['status'], 'POLICY_APPROVED')\n self.assertEqual(parity_report([(a,b)])['identical_core'], 1)\n def test_revocation(self):\n self.checkpoint['revoked_digests'] = [digest(self.r['body'])]\n self.assertEqual(self.get()['status'], 'RESEARCH_REQUIRED')\n def test_version_floor(self):\n self.checkpoint['version_floors'][self.key] = 2\n self.assertEqual(self.get()['status'], 'RESEARCH_REQUIRED')\n def test_stale_checkpoint(self):\n self.checkpoint['checked_at'] = '2026-12-03T23:00:00Z'\n self.assertEqual(self.get()['status'], 'RESEARCH_REQUIRED')\n def test_future_checkpoint(self):\n self.checkpoint['checked_at'] = '2026-12-05T00:00:00Z'\n self.assertEqual(self.get()['status'], 'RESEARCH_REQUIRED')\n def test_stale_policy_override(self):\n self.r['body']['max_age_hours'] = 99999\n self.r['publication_review']['digest'] = digest(self.r['body'])\n self.assertEqual(self.get()['status'], 'RESEARCH_REQUIRED')\n def test_dependency(self):\n self.r['body']['dependency_digests'] = ['obsolete']\n self.r['publication_review']['digest'] = digest(self.r['body'])\n self.checkpoint['revoked_digests'] = ['obsolete']\n self.assertEqual(self.get()['status'], 'RESEARCH_REQUIRED')\n def test_parity_not_accuracy(self):\n a = self.get(); b = deepcopy(a); b['core_digest'] = 'changed'\n self.assertEqual(parity_report([(a,b), (a,{}), (a,a)]),\n {'pairs':3,'both_approved':2,'identical_core':1,'mismatches':1,'unavailable':1})\n def test_missing_core(self):\n a = {'status':'POLICY_APPROVED'}\n self.assertEqual(parity_report([(a,a)])['mismatches'],1)\n","test_hard_copy.py":"import unittest\nfrom copy import deepcopy\nfrom cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey\nfrom hard_copy import canonical, sha, signed_bytes, verify_package\nfrom truth_guard import stamp\n\n\nclass HardCopyTests(unittest.TestCase):\n def setUp(self):\n self.now = stamp('2026-12-04T00:00:00Z')\n self.keys = {k: Ed25519PrivateKey.generate() for k in ('ledger', 'a', 'b')}\n self.ring = {k: {'role': 'checkpoint' if k == 'ledger' else 'review',\n 'org': k, 'public_key': p.public_key().public_bytes_raw().hex()}\n for k, p in self.keys.items()}\n self.blobs = {sha(x): x for x in (b'Synthetic proof A', b'Synthetic proof B')}\n evidence = [dict(sha256=h, quote=data.decode(), url='https://example.'+t,\n origin=t, published_at='2026-12-03T20:00:00Z',\n captured_at='2026-12-03T21:00:00Z')\n for (h,data), t in zip(self.blobs.items(), ('org','net'))]\n self.body = dict(schema='TG-HC-1', key=['test','definition','global','tr'],\n version=1, answer='Synthetic claim', dependencies=[],\n created_at='2026-12-03T22:00:00Z', expires_at='2026-12-04T01:00:00Z',\n claims=[dict(id='c1', kind='fact', text='Synthetic claim', evidence=evidence)])\n self.cb = dict(sequence=5, checked_at=self.now.isoformat(), revoked=[], version_floors={})\n self.seal()\n\n def signed(self, role, body, key):\n return dict(body=body, signature=dict(key_id=key, signature=self.keys[key].sign(signed_bytes(role,body)).hex()))\n\n def seal(self):\n a = dict(package_id=sha(canonical(self.body)), reviewed_at=self.now.isoformat(),\n support_checked=True, independence_checked=True, coverage_checked=True,\n freshness_checked=True, privacy_checked=True, rights_checked=True)\n self.approvals = [self.signed('review', deepcopy(a), k) for k in ('a','b')]\n self.checkpoint = self.signed('checkpoint', deepcopy(self.cb), 'ledger')\n\n def check(self, expected='HOLD', **kw):\n args = dict(keyring=self.ring, now=self.now, expected_key=['test','definition','global','tr'], minimum_sequence=5)\n args.update(kw)\n self.assertEqual(verify_package(self.body,self.approvals,self.blobs,self.checkpoint,**args)['status'],expected)\n\n def test_valid(self): self.check('VERIFIED_PACKAGE')\n def test_changed_answer(self): self.body['answer'] += ' invented'; self.check()\n def test_bad_signature(self): self.approvals[0]['signature']['signature'] = '00'*64; self.check()\n def test_changed_blob(self): self.blobs[next(iter(self.blobs))] = b'changed'; self.check()\n def test_missing_blob(self): self.blobs.clear(); self.check()\n def test_fabricated_quote(self): self.body['claims'][0]['evidence'][0]['quote']='invented'; self.seal(); self.check()\n def test_same_reviewer(self): self.approvals[1]=self.approvals[0]; self.check()\n def test_same_org(self): self.ring['b']['org']='a'; self.check()\n def test_revoked_source(self): self.cb['revoked']=[next(iter(self.blobs))]; self.seal(); self.check()\n def test_revoked_answer(self): self.cb['revoked']=[sha(canonical(self.body))]; self.seal(); self.check()\n def test_dependency(self): self.body['dependencies']=['obsolete']; self.cb['revoked']=['obsolete']; self.seal(); self.check()\n def test_rollback(self): self.check(minimum_sequence=6)\n def test_stale_checkpoint(self): self.cb['checked_at']='2026-12-03T23:00:00Z'; self.seal(); self.check()\n def test_expired(self): self.body['expires_at']=self.now.isoformat(); self.seal(); self.check()\n def test_wrong_scope(self): self.check(expected_key=['other','definition','global','tr'])\n def test_version_floor(self): self.cb['version_floors'][sha(canonical(self.body['key']))]=2; self.seal(); self.check()\n def test_rights_missing(self): a=self.approvals[0]['body']; a['rights_checked']=False; self.approvals[0]=self.signed('review',a,'a'); self.check()\n def test_duplicate_source(self): e=self.body['claims'][0]['evidence']; e[1]=deepcopy(e[0]); self.seal(); self.check()\n","HARD_COPY_V5.md":"# TRUTH GUARD v5.0 — HARD COPY / Evidence-Bound Answers\n\n**Mission:** learn and distribute the best independently verified factual knowledge available, with the same factual baseline for all users. Hard copy means a preserved, lawful source snapshot, not a frozen assertion of eternal truth. Any AI, search engine, education service or website should be able to validate the same answer package.\n\n## Proposed protocol\n1. Research the normalized question, establish entity, scope, date and jurisdiction, and separate facts, proofs, forecasts and opinions.\n2. Capture the original public source, where copying is permitted, with source URL, publication and capture time, content SHA-256, exact evidence excerpt and provenance. Never ingest private conversations automatically. Archive access is subject to copyright, consent, retention and deletion rules.\n3. Independently verify whether each claim is actually supported, source independence, omissions, contradictions and current validity. A hash proves byte integrity, not factual accuracy. A signature identifies an approving key, not an infallible authority.\n4. Publish the exact answer and all claim/evidence links as a content-addressed package. Require two different reviewer organizations and keys in this prototype, separate from the checkpoint authority.\n5. Before distribution verify signatures, scope, bytes, quote, expiry, revocation, dependencies and monotonic checkpoint sequence. Clients must obtain authenticated fresh state and persist sequence floors. If verification fails, research again or state the uncertainty; do not invent an answer.\n6. Correct errors by publishing a new version and revoking incorrect records. Archived copies must remain clearly marked as obsolete where retention is lawful. Propagate revocations across dependencies and consumers. No private or unlawful data should be made indelible.\n7. Present source links and a package identifier; offer different depth and languages only after checking factual equivalence. Keep new and experienced users on the same factual baseline.\n\n## Implementation\nhard_copy.py verifies a project-specific JSON envelope with SHA-256 and Ed25519 using the cryptography package. It supports UTF-8 source bytes up to 2 MB per object and the two-source evidence route. It verifies exact substring presence but does not validate logical entailment, source authenticity, real independence, completeness or the truth of reviewer attestations itself. Those must be performed independently. It is not an RFC 8785 implementation, a WARC capture tool, or a public-key infrastructure. All inputs must be schema-validated and bounded in production; trust keys and time must be configured out-of-band; protect signing keys, persist monotonic checkpoint sequence and implement key revocation, ledger consistency, equivocation detection, full dependency closure, access control and independent audits. The current format has no binary PDF, OCR, single authoritative record or mathematical proof route. Do not use as a production security boundary.\n\n## Standards to build on\n- W3C PROV-O: https://www.w3.org/TR/prov-o/\n- WARC archive reference: https://www.loc.gov/preservation/digital/formats/fdd/fdd000236.shtml\n- HTTP integrity digests RFC 9530: https://www.rfc-editor.org/rfc/rfc9530.html\n\nThese are design references, not claims of standards compliance or endorsement.\n\n## Reproduce\nInstall cryptography (tested locally with 46.0.4). From this directory run python -m unittest discover -v. The 53 tests include 18 hard-copy tests, using synthetic documents and locally generated ephemeral keys only. No real-world truth rate is established.\n\n## Public collaboration and distribution\nProposed separate public repository, reviewed open-source license, contributor charter, documented JSON schema and HTTP API, independent reviewer accreditation, public benchmarks, correction feed, and opt-in integrations. Invite researchers, universities, open data projects and AI providers through official channels; do not spam or imply endorsement. Preserve a free factual core, with optional grants, sponsorship and paid hosting/integration. No sponsors, public deployment or GPT integration have been secured. The existing repository is private; do not expose unrelated files or change its visibility.\n\nMovement statement: **Evidence before answers. Equal accuracy for everyone. Corrections propagate everywhere.**\n","UNIVERSAL_ACCURACY_V4.md":"# TRUTH GUARD / GLOBAL KNOWLEDGE NETWORK v4.0\n## Equal factual access — design proposal and tested policy prototype\n\nMission: every factual question deserves the same accuracy and completeness baseline, regardless of language, educational background, subscription, chat history, topic or apparent importance. Personalization changes presentation, not established facts. Never mine private conversations or expose user memories. Research leads must be explicitly contributed and independently sourced.\n\n### Proposed end-to-end pipeline\n1. Normalize question intent, entity identity, jurisdiction, date, units and language. Ambiguous identities trigger disambiguation. Seed the catalog using lawful public registries, not an impossible enumeration of every possible question.\n2. Maintain atomic claims with stable IDs, citations, source dates, observation dates, validity periods, uncertainty, scope and dependencies. Use W3C PROV-O (https://www.w3.org/TR/prov-o/) and Wikidata statement qualifiers as interoperability references, not automatic truth labels.\n3. Invite expert contributions through opt-in submission. Evaluate evidence, not seniority, follower counts or chat length. Require privacy, publication rights, conflict of interest, and independent review.\n4. Choose evidence routes by claim type: reproducible calculations and formal proofs; unique authoritative record with independent verification of the same record; multiple genuinely independent sources for empirical claims; qualified and scoped accounts of unresolved controversies; forecasts labeled as conditional and never stored as facts. Only the multiple-source policy route is implemented in the inherited gate.\n5. Publish a versioned, independently reviewed factual core. Never treat a reviewed snapshot as infallible or permanently final. Maintain an authenticated, monotonic correction/revocation ledger and invalidate dependent records. When a fact changes, do not serve outdated versions silently.\n6. Retrieve the same approved core for the same normalized factual scope and snapshot, without user profile keys. Review all translations and expansions for factual equivalence. Never use a shorter answer to conceal essential facts. Personalized details and private context remain separate.\n7. If no acceptable record exists, research or explain the exact gap. Do not invent a claim or forecast. A narrow question need not contain unrelated facts.\n8. Publish corrections, appeal routes and transparent provenance. Use federated registries and independently verifiable signatures; avoid a single authority determining all truth.\n\n### Pilot and measurement\nStart with a balanced, independently adjudicated set of everyday definitions, arithmetic, product facts, education, scientific claims, current events, religious source attribution and blockchain topics. Vaulta is a useful pilot for aliases, token transitions, governance, on-chain data as of a block and contested claims; no private research hypothesis becomes a fact by default.\nProposed pilot: 1,000 matched questions, two profiles (novice/expert), three languages, 6,000 answer instances, repeated across model versions. Stratify difficulty and domain. Hold out cases from development. Report factual error per claim, essential-fact omission per answer, false approval, false rejection, abstention quality, citation support, stale data, correction delay, privacy leaks, and profile/language gaps with confidence intervals. A paired-core match alone is not a truth metric. Use independent adjudicators and report disagreements. Do not claim a global error rate without representative sampling.\n\n### Implementation\nuniversal_core.py adds profile-independent retrieval, expiry of trusted correction checkpoint, revocation and dependent-record blocking, version floors, externally enforced maximum freshness and paired-core metrics. test_universal.py adds nine regression cases. All tests use synthetic inputs; authentication, persistent monotonic checkpoint state, dependency-closure construction, semantic review, independent ground truth, multilingual equivalence, real external evidence and production integrations remain to be built. The caller must authenticate checkpoints and attestations and enforce role separation; this module is not a security boundary or an oracle.\n\n### Open development and funding\nPublish a separate clean public repository under an approved open-source license; do not change the private parent repo visibility. Add reproducible tests, contributor and security policies, a corrections process, transparent governance and documented data licensing. Invite researchers and open-source communities through opt-in outreach, not spam. Proposal: free factual core, optional GitHub Sponsors, grants and paid verification API/integration/support. No paid influence on factual ranking. GitHub Sponsors documentation lists the Philippines among supported regions: https://docs.github.com/en/sponsors/getting-started-with-github-sponsors/about-github-sponsors . Eligibility, identity, banking and tax onboarding remain personal requirements. No funding or external adoption is secured. A public code license does not license third-party evidence or private data.\n","GLOBAL_KNOWLEDGE_NETWORK.md":"# TRUTH GUARD v3.0 — Global Knowledge Network (GKN)\nStatus: proposal and local policy prototype, not a deployed service.\n\n## Founding principle\nThe factual accuracy baseline must be identical for a first-time user and an experienced researcher. Depth, language and teaching style may differ, but established facts must not. A person's private conversation is not a public knowledge source. Expertise is useful for identifying research leads; neither conversation length nor contributor status establishes truth.\n\n## Shared knowledge architecture\n- Entity registry: stable identifiers, aliases, languages, disambiguation, relationships and scope. Expand coverage incrementally; do not claim a complete inventory of all words, products or possible questions.\n- Claim registry: atomic statements with original source links, evidence passages, publication and observation times, jurisdiction, units, uncertainty, dependencies and revision history.\n- Research: find official sources, reproduce arithmetic and proofs, check contrary evidence. For unique primary records, establish a reviewed single-source route instead of fabricating independent evidence. This route is not implemented in the prototype.\n- Contributor workflow: explicitly opt in to publish a specific contribution; establish publication rights, strip private and identifying information, independently review sources, require an authenticated publisher and verifier, disclose conflicts of interest.\n- Versioned publication: attach review to exact answer and evidence digest, publish validity period, maintain revocation and correction history. Stale or conflicting answers trigger fresh research.\n- Retrieval: resolve entity, question intent, date, jurisdiction and language, find reviewed current records, verify exact coverage, then adapt wording and depth without changing factual content. If reliable shared knowledge is unavailable, research or abstain.\n- Corrections: invalidate affected claims and all derived answers; notify relevant consumers where supported. Do not silently overwrite the audit trail.\n- Expert contributions: assess the evidence, not the author's popularity, identity or history of chatbot use.\n- Security: signed attestations, authenticated role-separated services, abuse prevention, source provenance and prompt-injection defenses; no automatic cross-account chat access or unconsented training data.\n- Interoperability: propose a public JSON schema/API and exportable, versioned claims. Consumers must independently validate signatures and respect revocations. No requirement for a single central authority.\n\n## Vaulta example (illustrative, not factual claims)\nResolve the blockchain entity versus unrelated products using stable IDs. Independently research official documentation, chain data and primary announcements. Record claims for identity, governance, token migration, supply as of a specified block, and disputed ownership claims separately. Never treat a user's hypothesis as established fact. Every user receives the same approved factual core; live supply requires a fresh observation. A new contributor can submit a sourced correction without reading private chats.\n\n## One question, one factual foundation\nWhere there is an objectively determinate answer within a defined scope, seek consistency. For ambiguous questions, changing values, differing legal jurisdictions, disputed scholarly views and predictions, preserve scope and uncertainty instead of imposing artificial consensus.\n\n## Open-source collaboration and sustainability proposal\nCreate a separate public repository after confirming its scope and removing private project history. Proposed code license: Apache-2.0, pending rights review. Evidence content needs separate source-specific rights review. Publish contribution guidelines, reproducible benchmarks, reviewer conflict-of-interest rules, issue templates, a corrections log and a governance charter. Invite independent researchers, maintainers and institutions through opt-in channels. Do not spam or claim endorsements.\nPossible revenue: voluntary sponsorship, research grants, institutional verification API and hosted integration/support; preserve a free public factual core and prohibit pay-to-rank claims. Contributor attribution is opt-in; publish transparent compensation terms and a budget before making commitments. No grants, sponsorships or payments have been secured. Public disclosure may affect intellectual-property options; obtain qualified advice if relevant.\n\n## Implementation status\nImplemented: policy gate and candidate registry with scope matching, exact-answer review requirement, expiry and conflict handling. Not implemented: evidence retrieval, signatures, semantic equivalence, entity matching, persistent storage, revocation feed, public API, independent reviewer network, full benchmark, public repo or GPT-wide integration. Prototype is not an accuracy guarantee. A private branch has no automatic influence on other users' ChatGPT responses.\n","requirements-hard-copy.txt":"cryptography==46.0.4\n","site-manifest.webmanifest.txt":"{\"name\":\"TRUTHGUARDGLOBAL\",\"short_name\":\"TruthGuard\",\"start_url\":\"/\",\"scope\":\"/\",\"display\":\"standalone\",\"background_color\":\"#f4f7f6\",\"theme_color\":\"#102b35\",\"icons\":[{\"src\":\"/icon.svg\",\"sizes\":\"any\",\"type\":\"image/svg+xml\",\"purpose\":\"any\"}]}","site-icon.svg.txt":"","LICENSE":"MIT License\n\nCopyright (c) 2026 TRUTHGUARDGLOBAL contributors\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.","CONTRIBUTING.md":"# Contributing\nInspect, copy, modify and redistribute the original MIT-licensed software. Third-party sources and dependencies retain their own licenses.\nDownload Python files into a directory, use a Python 3.10+ virtual environment, install requirements-hard-copy.txt, then run python -m unittest discover -v.\nSupply reproducible bug reports, regression tests, minimal patches and evidence-backed corrections. Include scope, source date, counterevidence, and publication rights. Never include private conversations, credentials or unauthorized data.\nThe site contribution form exports a local JSON draft; no remote submission service or public GitHub contribution repository is connected yet. Independent review is required.\nThe protocol and tools are research prototypes, not factuality guarantees. The 33-language manifesto is a translation draft, not complete reviewed localization."}