Spaces:
Running
Running
Download app.js from Hugdrigo/reprochain-ai: direct link, hf CLI and curl.
- Browser
- Download file 28.4 kB
-
https://huggingface.co/spaces/Hugdrigo/reprochain-ai/resolve/main/app.js
- Command line
-
hf download hf://spaces/Hugdrigo/reprochain-ai/app.js
-
curl -L -o app.js https://huggingface.co/spaces/Hugdrigo/reprochain-ai/resolve/main/app.js
28.4 kB
| /* ReproChain AI browser application | No third-party packages, no remote write calls. */ | |
| (()=>{'use strict'; | |
| const E=window.EvalFlowEngine,R=window.ReproChainEngine; | |
| const $=id=>document.getElementById(id); | |
| const fmt=n=>Number.isFinite(n)?(n*100).toFixed(1)+'%':'n/a'; | |
| const round=n=>Number.isFinite(n)?n.toFixed(3):'n/a'; | |
| const esc=s=>String(s??'').replaceAll('&','&').replaceAll('<','<').replaceAll('>','>').replaceAll('"','"').replaceAll("'",'''); | |
| const pill=(text,kind='')=>`<span class="pill ${kind}">${esc(text)}</span>`; | |
| const bytesToHex=b=>Array.from(new Uint8Array(b)).map(x=>x.toString(16).padStart(2,'0')).join(''); | |
| const digest=async data=>bytesToHex(await crypto.subtle.digest('SHA-256',typeof data==='string'?new TextEncoder().encode(data):data)); | |
| const dl=(text,name,mime='text/plain')=>{const obj=new Blob([text],{type:mime});const url=URL.createObjectURL(obj);const a=document.createElement('a');a.href=url;a.download=name;document.body.appendChild(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(url),1500);}; | |
| const state={manifest:null,verify:{},rootVerified:false,snap:null,policy:{...E.DEFAULT_POLICY},result:null,governance:null,runs:[],audit:[],view:'overview',selection:'predictions',simulateTamper:false,loading:true,error:'',selectedRun:0,registryA:0,registryB:1,imported:false}; | |
| function integ(){return R.integrity(state.manifest,patchedVerify());} | |
| function patchedVerify(){if(!state.simulateTamper)return state.verify;return {...state.verify,predictions:{...state.verify.predictions,match:false,observed:'SIMULATED-TAMPER-ONLY'}};} | |
| function overall(){return R.evaluateRelease(state.result,integ(),{rootVerified:state.rootVerified,simulatedTamper:state.simulateTamper});} | |
| function status(){const i=integ();$('kArtifact').textContent=String(i.total);$('kRecords').textContent=state.snap?.rows?.length?.toLocaleString('en-US')||'…';$('kRoot').textContent=state.rootVerified?'VALID':'FAIL';$('sourceBadge').textContent=state.imported?'CUSTOM LOCAL INPUT':'FIXED SYNTHETIC EVIDENCE';$('statusBadge').textContent=state.governance?.status==='PASS'?'RESEARCH GATES PASS':'RESEARCH GATES BLOCK';$('statusBadge').className='mini-badge '+(state.governance?.status==='PASS'?'':'warn');$('statusLine').textContent=`${i.verified}/${i.total} source hashes verified · manifest root ${state.rootVerified?'matched':'mismatch'} · ${state.runs.length} recorded runs · no data sent to a server`; | |
| } | |
| async function logEvent(kind,message){const previous=state.audit.length?state.audit.at(-1).digest:'GENESIS';const e={seq:state.audit.length+1,kind,message,at:new Date().toISOString(),previous};e.digest=await digest(R.stable(e));state.audit.push(e);} | |
| function stat(label,value,note=''){return `<div class="metric"><small>${esc(label)}</small><strong>${esc(value)}</strong>${note?`<div class="sub">${esc(note)}</div>`:''}</div>`;} | |
| function header(k,title,lead){return `<div class="section-kicker">${esc(k)}</div><h2 class="section-title">${esc(title)}</h2><p class="lead">${esc(lead)}</p>`;} | |
| function bars(items){return items.map(x=>`<div class="bar-row"><span class="bar-label">${esc(x.name)}</span><div class="track"><div class="fill ${x.bad?'fail':''}" style="width:${Math.max(0,Math.min(100,x.value*100))}%"></div></div><b>${fmt(x.value)}</b></div>`).join('');} | |
| function gatelist(gates){return gates.map(g=>`<div class="gate"><div><div class="gate-title">${esc(g.label)}</div><small>${g.actual==null?'No data':g.unit==='count'?g.actual:fmt(g.actual)} · ${esc(g.comparator)} ${g.unit==='count'?g.limit:fmt(g.limit)}</small></div>${pill(g.pass?'PASS':'BLOCK',g.pass?'good':'bad')}</div>`).join('');} | |
| function overview(){const r=state.result,g=state.governance,i=integ();return header('AT A GLANCE','Reproducibility command center','From original dataset to evaluation gate: every bundled artifact carries a verifiable fingerprint.')+`<div class="stat-grid">${stat('SHA-256 artifact checks',i.verified+'/'+i.total, i.passed?'Bundled evidence intact':'Investigate integrity warning')}${stat('Candidate Accuracy',fmt(r.candidateMetrics.accuracy),E.NAME[r.candidate])}${stat('Paired comparison',fmt(r.pair.delta),'Accuracy delta vs baseline')}${stat('Research gate status',g.status,g.status==='PASS'?'Synthetic evidence only':'Review failed requirements')}</div><div class="grid-2"><section class="panel"><div class="split-top"><h3>Evaluation replay</h3>${pill(r.status,'good')}</div><p class="subhead">${esc(E.NAME[r.baseline])} → ${esc(E.NAME[r.candidate])} · ${esc(r.split)} · n=${r.pair.n}</p>${bars([{name:'Baseline Accuracy',value:r.baselineMetrics.accuracy},{name:'Candidate Accuracy',value:r.candidateMetrics.accuracy},{name:'Candidate macro-F1',value:r.candidateMetrics.macroF1}])}<div class="notice">${r.pair.improved} corrected predictions · ${r.pair.regressed} newly incorrect · fixed paired examples, not retrained model versions.</div></section><section class="panel"><div class="split-top"><h3>Supply-chain gate summary</h3>${pill(g.status,g.status==='PASS'?'good':'bad')}</div><p class="subhead">All required conditions must pass. These checks cannot authorize real-world model deployment.</p>${g.requirements.map(x=>`<div class="gate"><div class="gate-title">${esc(x.label)}</div>${pill(x.pass?'PASS':'BLOCK',x.pass?'good':'bad')}</div>`).join('')}</section></div><section class="panel" style="margin-top:13px"><h3>Evidence provenance</h3><p class="subhead">Upstream original training / held-out examples and fixed prediction records from EvalFlow CI Lab.</p><div class="grid-3"><div class="tiny-card">${pill('SYNTHETIC RESEARCH','unverified')}<p>1,026 unique annotated research-style sentences: 842 training, 130 IID test, 54 challenge.</p></div><div class="tiny-card">${pill('FIXED PREDICTIONS')}<p>4,416 evaluation rows represent repeated observations over four methods and six conditions, not 4,416 independent examples.</p></div><div class="tiny-card">${pill('NOT DEPLOYMENT APPROVAL','unverified')}<p>Passing gates reflects this documented research exercise only. Real external validation has not been established.</p></div></div></section>`;} | |
| function layer(id){const a=state.manifest.artifacts.find(x=>x.id===id);if(!a.parents.length)return 0;if(['predictions','release-engine','hash-registry'].includes(id))return 1;if(['reference-decision'].includes(id))return 2;return 3;} | |
| function lineage(){const m=state.manifest,sel=R.lineage(m,state.selection),info=m.artifacts.find(x=>x.id===state.selection),detailStatus=patchedVerify()[state.selection];const levels=[['Input evidence',m.artifacts.filter(x=>layer(x.id)===0)],['Evaluation artifacts',m.artifacts.filter(x=>layer(x.id)===1)],['Policy decisions',m.artifacts.filter(x=>layer(x.id)===2)],['App / documentation',m.artifacts.filter(x=>layer(x.id)===3)]];return header('02 / PROVENANCE','Artifact lineage graph','Choose an artifact to inspect its upstream dependencies, downstream consumers, license, and SHA-256 digest.')+`<div class="panel"><div class="lineage-stages">${levels.map(([name,items])=>`<div class="lineage-col"><div class="stage-title">${esc(name)}</div>${items.map(a=>`<button data-node="${a.id}" class="node-card ${a.id===state.selection?'selected':''}"><span class="node-name">${esc(a.id)}</span><span class="node-meta">${esc(a.kind)} · ${a.parents.length} upstream</span></button>`).join('')}</div>`).join('')}</div><div class="notice">Directed dependencies are shown by the selected node's upstream/downstream links below. This is a documented artifact-dependency graph, not a verified training-execution trace.</div></div><div class="grid-2" style="margin-top:13px"><section class="panel"><div class="split-top"><h3>${esc(info.id)}</h3>${pill(detailStatus?.match?'SHA VERIFIED':'NOT VERIFIED',detailStatus?.match?'good':'bad')}</div><dl><div class="keyline"><dt>File</dt><dd class="mono">${esc(info.file)}</dd></div><div class="keyline"><dt>Category</dt><dd>${esc(info.kind)}</dd></div><div class="keyline"><dt>License</dt><dd>${esc(info.license)}</dd></div><div class="keyline"><dt>Digest</dt><dd class="mono">${esc(info.sha256)}</dd></div></dl><p class="lead">${esc(info.description)}</p></section><section class="panel"><h3>Dependency inspection</h3><div class="keyline"><dt>Direct parents</dt><dd>${sel.parents.length?sel.parents.map(esc).join(', '):'None'}</dd></div><div class="keyline"><dt>All ancestors</dt><dd>${sel.ancestors.length?sel.ancestors.map(esc).join(', '):'Root asset'}</dd></div><div class="keyline"><dt>Direct children</dt><dd>${sel.children.length?sel.children.map(esc).join(', '):'None'}</dd></div><div class="keyline"><dt>Downstream</dt><dd>${sel.descendants.length?sel.descendants.map(esc).join(', '):'Leaf asset'}</dd></div><div class="btn-row"><button class="secondary" data-export="graph">Download GraphML</button><button class="secondary" data-export="manifest">Export manifest</button></div></section></div>`;} | |
| function vault(){const i=integ(),items=R.inventory(state.manifest,patchedVerify());return header('03 / INTEGRITY','Artifact integrity vault','Recalculate SHA-256 in your browser. A supplied digest is useful for detecting changes, but is not a trusted digital signature.')+`<div class="stat-grid">${stat('Checked files',i.total)}${stat('Verified',i.verified)}${stat('Mismatched',i.mismatched)}${stat('Unavailable',i.missing)}</div><div class="panel"><div class="split-top"><h3>Content-addressed inventory</h3>${pill(i.passed?'ALL MATCH':'INTEGRITY FAILURE',i.passed?'good':'bad')}</div><div class="btn-row"><button id="rescan" class="secondary">↻ Recalculate hashes</button><button id="tamper" class="danger">${state.simulateTamper?'Clear simulated tamper':'Simulate tampered prediction file'}</button></div>${state.simulateTamper?'<div class="notice warn">SIMULATION ONLY. The prediction file on disk is unchanged. This toggle exercises the governance fail-closed rule.</div>':''}<div class="scroll"><table><thead><tr><th>Artifact</th><th>Category</th><th>SHA-256 prefix</th><th>Verification</th></tr></thead><tbody>${items.map(a=>`<tr><td><b>${esc(a.file)}</b></td><td>${esc(a.kind)}</td><td class="mono">${esc(a.expected.slice(0,18))}…</td><td>${pill(a.verified?'MATCH':'FAILED',a.verified?'good':'bad')}</td></tr>`).join('')}</tbody></table></div><div class="notice">Inventory root: <span class="mono">${esc(state.manifest.bundleRoot)}</span><br>Recomputed root: ${state.rootVerified?'MATCH':'DIFFERENT'}. An attacker able to replace both files and this manifest could forge local checks; use an independently trusted signature for stronger assurance.</div></div>`;} | |
| function replay(){const r=state.result;return header('04 / REPLAY','Experiment replay & paired comparisons','The same fixed predictions and labels are recomputed without any model retraining. An experiment record is a reproducible local snapshot.')+`<div class="grid-2"><section class="panel"><div class="split-top"><h3>Candidate evaluation</h3>${pill(r.status,r.status==='PASS'?'good':'bad')}</div><div class="stat-grid" style="grid-template-columns:1fr 1fr">${stat('Accuracy',fmt(r.candidateMetrics.accuracy))}${stat('Macro-F1',fmt(r.candidateMetrics.macroF1))}${stat('Paired delta',fmt(r.pair.delta))}${stat('Paired bootstrap 95%','['+fmt(r.interval.low)+', '+fmt(r.interval.high)+']')}</div><p class="subhead">Bootstrap resamples fixed paired examples (seed ${r.interval.seed}, ${r.interval.iterations} resamples). It does not capture retraining, new institutions or annotation uncertainty.</p></section><section class="panel"><h3>Individual paired outcomes</h3><p class="subhead">Corrected errors versus newly incorrect predictions.</p>${bars([{name:'Corrected errors',value:r.pair.improved/Math.max(1,r.pair.n)},{name:'New errors',value:r.pair.regressed/Math.max(1,r.pair.n)},{name:'Unchanged outcomes',value:r.pair.tied/Math.max(1,r.pair.n)}])}<div class="notice">Matched examples: ${r.pair.n} · Baseline-only: ${r.pair.onlyBase.length} · Candidate-only: ${r.pair.onlyCandidate.length}</div></section></div><section class="panel" style="margin-top:13px"><h3>Research gate results</h3><div class="grid-2">${r.gates.map(g=>`<div class="gate"><div><div class="gate-title">${esc(g.label)}</div><small>Actual ${g.unit==='count'?g.actual:fmt(g.actual)} · required ${esc(g.comparator)} ${g.unit==='count'?g.limit:fmt(g.limit)}</small></div>${pill(g.pass?'PASS':'BLOCK',g.pass?'good':'bad')}</div>`).join('')}</div></section>`;} | |
| function governance(){const g=state.governance;const edit=['minN','minAccuracy','minMacroF1','maxRegression','maxTypoFlip','maxContextFlip','minLanguageN','minLanguageAccuracy'];return header('05 / GOVERNANCE','Quality gates & fail-closed rules','Edit the documented research policy. The release decision combines model checks with artifact-integrity checks.')+`<div class="grid-2"><section class="panel"><div class="split-top"><h3>End-to-end gate result</h3>${pill(g.status,g.status==='PASS'?'good':'bad')}</div><p class="subhead">A model may pass its nine gates while an artifact-integrity or manifest check blocks the overall decision.</p>${g.requirements.map(x=>`<div class="gate"><div class="gate-title">${esc(x.label)}</div>${pill(x.pass?'PASS':'BLOCK',x.pass?'good':'bad')}</div>`).join('')}</section><section class="panel"><h3>Configure research policy</h3><p class="subhead">Percent thresholds are decimals, e.g. 0.75 for 75%.</p><div class="tool-grid">${edit.map(k=>`<label>${esc(k)}<input id="p_${k}" type="number" step="${['minN','minLanguageN'].includes(k)?'1':'0.01'}" min="0" max="${['minN','minLanguageN'].includes(k)?'10000':'1'}" value="${state.policy[k]}"></label>`).join('')}</div><div class="btn-row"><button id="apply" class="primary">Apply and replay</button><button id="defaults" class="secondary">Restore default policy</button></div><div class="status-line">The policy applies to the local research comparison only. No production release or GitHub update occurs.</div></section></div>`;} | |
| function runs(){const all=state.runs,valid=i=>i>=0&&i<all.length;const a=all[state.registryA],b=all[state.registryB];return header('06 / REGISTRY','Recorded research runs','Session-only experiment history. Every local replay records its exact policy, inputs, scoring, and governance outcome.')+`<div class="panel"><div class="split-top"><h3>${all.length} local run snapshots</h3>${pill('SESSION ONLY','unverified')}</div><div class="scroll"><table><thead><tr><th>Run</th><th>Comparison</th><th>Split</th><th>Accuracy</th><th>Δ Accuracy</th><th>Gate</th><th>Digest</th></tr></thead><tbody>${all.map((run,i)=>`<tr><td>#${run.replayId}</td><td>${esc(E.NAME[run.baseline])} → ${esc(E.NAME[run.candidate])}</td><td>${esc(run.split)}</td><td>${fmt(run.accuracy)}</td><td>${fmt(run.delta)}</td><td>${pill(run.governance,run.governance==='PASS'?'good':run.governance==='BLOCK'?'bad':'unverified')}</td><td class="mono">${esc(run.recordDigest?.slice(0,12)||'pending')}</td></tr>`).join('')}</tbody></table></div></div><div class="panel" style="margin-top:13px"><h3>Compare two recorded snapshots</h3><div class="tool-grid"><label>Run A<select id="regA">${all.map((x,i)=>`<option value="${i}" ${state.registryA===i?'selected':''}>#${x.replayId} · ${esc(x.candidate)} / ${esc(x.split)}</option>`).join('')}</select></label><label>Run B<select id="regB">${all.map((x,i)=>`<option value="${i}" ${state.registryB===i?'selected':''}>#${x.replayId} · ${esc(x.candidate)} / ${esc(x.split)}</option>`).join('')}</select></label></div>${valid(state.registryA)&&valid(state.registryB)?`<div class="stat-grid">${stat('Run A Accuracy',fmt(a.accuracy))}${stat('Run B Accuracy',fmt(b.accuracy))}${stat('Difference (B − A)',fmt(b.accuracy-a.accuracy))}${stat('Provenance',a.bundleRoot===b.bundleRoot?'Same bundle':'Different origins')}</div>`:''}<div class="notice warn">Different splits, candidate methods, or policies are not chronological deployed-model versions. Compare them as research snapshots only.</div></div>`;} | |
| function audit(){return header('07 / AUDIT','Local audit chain','Actions are linked by SHA-256 over the previous event digest. This makes changes detectable within an exported file but is not a digitally signed or independently anchored log.')+`<div class="panel"><div class="split-top"><h3>${state.audit.length} local events</h3>${pill('LOCAL · UNSIGNED','unverified')}</div><div class="scroll"><table><thead><tr><th>#</th><th>UTC time</th><th>Action</th><th>Description</th><th>SHA prefix</th></tr></thead><tbody>${[...state.audit].reverse().map(x=>`<tr><td>${x.seq}</td><td>${esc(x.at)}</td><td>${esc(x.kind)}</td><td>${esc(x.message)}</td><td class="mono">${x.digest.slice(0,16)}</td></tr>`).join('')}</tbody></table></div><div class="btn-row"><button id="auditVerify" class="primary">Verify local audit chain</button><button data-export="audit" class="secondary">Download audit JSON</button></div><div id="auditMessage" class="status-line">The log is kept only in this browser tab until exported.</div></div>`;} | |
| function exportView(){return header('08 / REPRODUCE','Research exports and executable checks','Export the decision, source inventory, graph edges, reproducibility bundle, or run history. All data stays in the browser until you deliberately download it.')+`<div class="grid-2"><section class="panel"><h3>Export a reproducibility record</h3><p class="subhead">The reproducibility manifest records SHA-256 digests of each bundled research artifact.</p><div class="btn-row"><button data-export="report" class="primary">Audit brief .md</button><button data-export="run" class="secondary">Run snapshot .json</button><button data-export="inventory" class="secondary">Artifact inventory .csv</button><button data-export="runs" class="secondary">Run registry .csv</button><button data-export="graph" class="secondary">GraphML</button><button data-export="bundle" class="secondary">Provenance bundle .json</button><button data-export="manifest" class="secondary">Manifest .json</button></div></section><section class="panel"><h3>Offline command-line reproduction</h3><p class="subhead">The ZIP includes real Node.js scripts and a GitHub Actions template. Uploading the ZIP to Hugging Face does NOT activate CI on GitHub.</p><div class="codeblock">node verify_bundle.js<br>node run_reprochain.js --baseline=nb --candidate=hybrid --split=challenge</div><div class="notice">Exit code 0 = research PASS, 2 = gate BLOCK, 3 = integrity BLOCK, 1 = invalid input. GitHub Actions must be separately installed in a GitHub repository.</div></section></div><section class="panel" style="margin-top:13px"><h3>Optional: import a run report</h3><p class="subhead">Uploaded JSON is always tagged LOCAL IMPORT · UNVERIFIED, even if it claims to match the bundled hash.</p><input id="importRun" type="file" accept=".json,application/json"><div id="importMsg" class="status-line">Only .json files below 1 MB are accepted. No server upload.</div></section>`;} | |
| function methods(){return header('09 / METHODS','Research methods & limitations','A transparent explanation of what ReproChain AI verifies and what it cannot verify.')+`<div class="grid-2"><section class="panel"><h3>What the app actually verifies</h3><p>1. A dependency graph with no missing parents or directed cycles.</p><p>2. Individual file contents match SHA-256 digests in the bundled manifest.</p><p>3. The inventory-root SHA-256 matches its declared manifest value.</p><p>4. All release-gate calculations are recomputed from fixed predictions.</p><p>5. Every locally generated run records thresholds, metrics and provenance identifiers.</p><p>6. Reports and lineage export are reproducible within the same source snapshot.</p></section><section class="panel"><h3>What the app does not establish</h3><p>• SHA-256 checks against a manifest hosted alongside the files are not a trusted signature.</p><p>• Dataset annotations and model results are from a synthetic-curated research task.</p><p>• Graph relationships describe documented dependencies, not independently audited training execution.</p><p>• There is no real production model monitoring, automatic publishing or authentication.</p><p>• A PASS is not evidence of legal compliance, fairness, suitability for a workplace or scientific generalization.</p></section></div><div class="panel" style="margin-top:13px"><h3>Public profile positioning</h3><p class="lead">Demonstrates evidence lineage, content-addressed artifact validation, deterministic NLP evaluation, reproducible release gating, local audit-event chaining, safe offline exports and real CLI automation integration.</p><div class="btn-row"><a href="METHODOLOGY.md">Read methodology</a><a href="SECURITY.md">Read threat model</a><a href="DATA_PROVENANCE.md">Read provenance</a><a href="DEPLOYMENT_ES.md">Instrucciones en español</a></div></div>`;} | |
| const views={overview,lineage,vault,replay,governance,runs,audit,export:exportView,methods}; | |
| function render(){if(!state.manifest||!state.result){$('content').innerHTML=`<div class="panel"><h2>${esc(state.error||'Loading evidence…')}</h2></div>`;return;}state.governance=overall();status();document.querySelectorAll('.nav-btn').forEach(x=>x.classList.toggle('active',x.dataset.view===state.view));$('content').innerHTML=views[state.view]();wire();} | |
| function wire(){document.querySelectorAll('[data-node]').forEach(x=>x.addEventListener('click',()=>{state.selection=x.dataset.node;render();}));document.querySelectorAll('[data-export]').forEach(x=>x.addEventListener('click',()=>exportKind(x.dataset.export)));if($('tamper'))$('tamper').onclick=async()=>{state.simulateTamper=!state.simulateTamper;await logEvent('INTEGRITY SIMULATION',state.simulateTamper?'Local tamper simulation enabled':'Local tamper simulation disabled');render();};if($('rescan'))$('rescan').onclick=()=>rescan();if($('apply'))$('apply').onclick=()=>{try{const p={...state.policy};for(const k of ['minN','minAccuracy','minMacroF1','maxRegression','maxTypoFlip','maxContextFlip','minLanguageN','minLanguageAccuracy'])p[k]=Number($('p_'+k).value);state.policy=E.policyCheck(p);recompute();}catch(err){alert('Invalid policy: '+err.message);}};if($('defaults'))$('defaults').onclick=()=>{state.policy={...E.DEFAULT_POLICY};recompute();};if($('regA'))$('regA').onchange=e=>{state.registryA=Number(e.target.value);render();};if($('regB'))$('regB').onchange=e=>{state.registryB=Number(e.target.value);render();};if($('auditVerify'))$('auditVerify').onclick=()=>verifyAudit();if($('importRun'))$('importRun').onchange=e=>importRun(e);} | |
| async function recordCurrent(){const run=R.buildRun(state.result,overall(),{bundleRoot:state.manifest.bundleRoot,integrity:integ().passed?'matched':'mismatch',replayId:state.runs.length+1});run.recordDigest=await digest(R.stable(run));state.runs.push(run);state.registryB=state.runs.length-1;await logEvent('EXPERIMENT REPLAY',`${run.baseline} → ${run.candidate} / ${run.split}: ${run.governance}`);} | |
| async function recompute(){try{state.result=E.evaluate(state.snap.rows,$('baseline').value,$('candidate').value,$('split').value,state.policy);await recordCurrent();render();}catch(err){alert('Evaluation could not run: '+err.message);}} | |
| async function rescan(){const manifest=state.manifest;for(const a of manifest.artifacts){const resp=await fetch('./'+a.file,{cache:'no-store'});if(!resp.ok){state.verify[a.id]={observed:null,match:false};continue;}const obs=await digest(await resp.arrayBuffer());state.verify[a.id]={observed:obs,match:obs===a.sha256};}state.rootVerified=(await digest(R.merkleInput(manifest)))===manifest.bundleRoot;await logEvent('FILE RECHECK',`${integ().verified}/${integ().total} SHA-256 matches`);render();} | |
| async function verifyAudit(){let prev='GENESIS';for(const e of state.audit){const h=await digest(R.stable({seq:e.seq,kind:e.kind,message:e.message,at:e.at,previous:prev}));if(h!==e.digest){$('auditMessage').textContent='FAILED: audit event '+e.seq+' does not match.';return;}prev=e.digest;}$('auditMessage').textContent=`PASS: ${state.audit.length} event hashes linked correctly (local, unsigned chain).`;} | |
| async function importRun(e){const f=e.target.files[0];if(!f)return;try{if(f.size>1e6)throw Error('Maximum file size is 1 MB');const o=R.validateImportedRun(JSON.parse(await f.text()));o.replayId=state.runs.length+1;o.recordDigest=await digest(R.stable(o));state.runs.push(o);await logEvent('UNVERIFIED IMPORT',`Imported local JSON: ${f.name}`);$('importMsg').textContent='LOCAL IMPORT · UNVERIFIED. Loaded into run registry only.';}catch(err){$('importMsg').textContent='Rejected: '+err.message;}} | |
| function exportKind(kind){const r=state.result,manifest=state.manifest;if(kind==='graph')return dl(R.graphml(manifest),'reprochain-lineage.graphml','application/graphml+xml');if(kind==='manifest')return dl(JSON.stringify(manifest,null,2),'reprochain-manifest.json','application/json');if(kind==='audit')return dl(JSON.stringify(state.audit,null,2),'reprochain-audit-chain.json','application/json');if(kind==='inventory')return dl(E.csv(R.inventory(manifest,patchedVerify()),['id','file','kind','parents','expected','observed','verified']),'reprochain-artifact-inventory.csv','text/csv');if(kind==='runs')return dl(R.summaryCsv(state.runs),'reprochain-run-registry.csv','text/csv');if(kind==='run')return dl(JSON.stringify(state.runs.at(-1),null,2),'reprochain-run-snapshot.json','application/json');if(kind==='bundle')return dl(JSON.stringify({schema:'reprochain.bundle.v1',manifest,verification:integ(),rootVerified:state.rootVerified,simulatedTamper:state.simulateTamper,latestRun:state.runs.at(-1),runs:state.runs,audit:state.audit,disclaimer:'Unsigned local research replay. Synthetic-curated dataset. No production certification.'},null,2),'reprochain-reproducibility-bundle.json','application/json');if(kind==='report'){const g=overall();const report='# ReproChain AI — audit report\n\n- Source: Academic Rhetorical Intent Mini v1.1 (synthetic-curated)\n- Candidate: '+E.NAME[r.candidate]+'\n- Baseline: '+E.NAME[r.baseline]+'\n- Split: '+r.split+'\n- Accuracy: '+fmt(r.candidateMetrics.accuracy)+'\n- Macro-F1: '+fmt(r.candidateMetrics.macroF1)+'\n- Artifact hashes: '+integ().verified+'/'+integ().total+'\n- Inventory root: '+(state.rootVerified?'MATCH':'FAIL')+'\n- Research governance: '+g.status+'\n\n## Supply-chain checks\n';const text=report+g.requirements.map(x=>'- '+x.label+': '+(x.pass?'PASS':'BLOCK')).join('\n')+'\n\n## Model gates\n'+r.gates.map(x=>'- '+x.label+': '+(x.pass?'PASS':'BLOCK')).join('\n')+'\n\n## Limitations\nThis report reproduces research checks using fixed predictions; it does not certify production safety, originality of annotations, or actual model training provenance.\n';return dl(text,'reprochain-research-audit.md','text/markdown');}} | |
| async function startup(){try{if(!E||!R)throw Error('Application scripts did not load');const resp=await fetch('./manifest.json');if(!resp.ok)throw Error('Cannot load manifest.json');const manifest=await resp.json();R.validateManifest(manifest);state.manifest=manifest;state.selection='predictions';state.rootVerified=await digest(R.merkleInput(manifest))===manifest.bundleRoot;const inventory=manifest.artifacts;const result=await Promise.all(inventory.map(async a=>{try{const f=await fetch('./'+a.file);if(!f.ok)throw Error('HTTP '+f.status);const buffer=await f.arrayBuffer();return {a,buffer,observed:await digest(buffer)}}catch{return {a,observed:null};}}));for(const it of result)state.verify[it.a.id]={observed:it.observed,match:it.observed===it.a.sha256};const pred=result.find(x=>x.a.id==='predictions');if(!pred?.buffer)throw Error('Prediction data missing');state.snap=JSON.parse(new TextDecoder().decode(pred.buffer));E.verify(state.snap.rows);const splits={'challenge':54,'iid':130};if(state.snap.rows.length!==4416)throw Error('Unexpected record count');state.result=E.evaluate(state.snap.rows,'nb','hybrid','challenge',state.policy);await logEvent('SOURCE LOADED',`${integ().verified}/${integ().total} verified, root ${state.rootVerified?'match':'mismatch'}`);await recordCurrent();state.loading=false;render();}catch(err){state.error='Initialization failed: '+err.message;state.loading=false;$('statusLine').textContent=state.error;$('content').innerHTML=`<div class="notice warn">${esc(state.error)}</div>`;console.error(err);}} | |
| document.querySelectorAll('.nav-btn').forEach(x=>x.onclick=()=>{state.view=x.dataset.view;render();});$('replay').onclick=()=>recompute();startup(); | |
| })(); | |