`).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.')+`
4,416 evaluation rows represent repeated observations over four methods and six conditions, not 4,416 independent examples.
${pill('NOT DEPLOYMENT APPROVAL','unverified')}
Passing gates reflects this documented research exercise only. Real external validation has not been established.
`;}
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.')+`
${levels.map(([name,items])=>`
${esc(name)}
${items.map(a=>``).join('')}
`).join('')}
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.
`;}
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.')+`
Inventory root: ${esc(state.manifest.bundleRoot)} 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.
`;}
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.')+`
Bootstrap resamples fixed paired examples (seed ${r.interval.seed}, ${r.interval.iterations} resamples). It does not capture retraining, new institutions or annotation uncertainty.
Individual paired outcomes
Corrected errors versus newly incorrect predictions.
`;}
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.')+`
End-to-end gate result
${pill(g.status,g.status==='PASS'?'good':'bad')}
A model may pass its nine gates while an artifact-integrity or manifest check blocks the overall decision.
${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')}
`:''}
Different splits, candidate methods, or policies are not chronological deployed-model versions. Compare them as research snapshots only.
`;}
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.')+`
${state.audit.length} local events
${pill('LOCAL · UNSIGNED','unverified')}
#
UTC time
Action
Description
SHA prefix
${[...state.audit].reverse().map(x=>`
${x.seq}
${esc(x.at)}
${esc(x.kind)}
${esc(x.message)}
${x.digest.slice(0,16)}
`).join('')}
The log is kept only in this browser tab until exported.
`;}
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.')+`
Export a reproducibility record
The reproducibility manifest records SHA-256 digests of each bundled research artifact.
Offline command-line reproduction
The ZIP includes real Node.js scripts and a GitHub Actions template. Uploading the ZIP to Hugging Face does NOT activate CI on GitHub.
Exit code 0 = research PASS, 2 = gate BLOCK, 3 = integrity BLOCK, 1 = invalid input. GitHub Actions must be separately installed in a GitHub repository.
Optional: import a run report
Uploaded JSON is always tagged LOCAL IMPORT · UNVERIFIED, even if it claims to match the bundled hash.
Only .json files below 1 MB are accepted. No server upload.
`;}
function methods(){return header('09 / METHODS','Research methods & limitations','A transparent explanation of what ReproChain AI verifies and what it cannot verify.')+`
What the app actually verifies
1. A dependency graph with no missing parents or directed cycles.
2. Individual file contents match SHA-256 digests in the bundled manifest.
3. The inventory-root SHA-256 matches its declared manifest value.
4. All release-gate calculations are recomputed from fixed predictions.
5. Every locally generated run records thresholds, metrics and provenance identifiers.
6. Reports and lineage export are reproducible within the same source snapshot.
What the app does not establish
• SHA-256 checks against a manifest hosted alongside the files are not a trusted signature.
• Dataset annotations and model results are from a synthetic-curated research task.
• Graph relationships describe documented dependencies, not independently audited training execution.
• There is no real production model monitoring, automatic publishing or authentication.
• A PASS is not evidence of legal compliance, fairness, suitability for a workplace or scientific generalization.
Public profile positioning
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.
`;}
const views={overview,lineage,vault,replay,governance,runs,audit,export:exportView,methods};
function render(){if(!state.manifest||!state.result){$('content').innerHTML=`
${esc(state.error||'Loading evidence…')}
`;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=`