/* 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='')=>`${esc(text)}`; 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 `
${esc(label)}${esc(value)}${note?`
${esc(note)}
`:''}
`;} function header(k,title,lead){return `
${esc(k)}

${esc(title)}

${esc(lead)}

`;} function bars(items){return items.map(x=>`
${esc(x.name)}
${fmt(x.value)}
`).join('');} function gatelist(gates){return gates.map(g=>`
${esc(g.label)}
${g.actual==null?'No data':g.unit==='count'?g.actual:fmt(g.actual)} · ${esc(g.comparator)} ${g.unit==='count'?g.limit:fmt(g.limit)}
${pill(g.pass?'PASS':'BLOCK',g.pass?'good':'bad')}
`).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.')+`
${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')}

Evaluation replay

${pill(r.status,'good')}

${esc(E.NAME[r.baseline])} → ${esc(E.NAME[r.candidate])} · ${esc(r.split)} · n=${r.pair.n}

${bars([{name:'Baseline Accuracy',value:r.baselineMetrics.accuracy},{name:'Candidate Accuracy',value:r.candidateMetrics.accuracy},{name:'Candidate macro-F1',value:r.candidateMetrics.macroF1}])}
${r.pair.improved} corrected predictions · ${r.pair.regressed} newly incorrect · fixed paired examples, not retrained model versions.

Supply-chain gate summary

${pill(g.status,g.status==='PASS'?'good':'bad')}

All required conditions must pass. These checks cannot authorize real-world model deployment.

${g.requirements.map(x=>`
${esc(x.label)}
${pill(x.pass?'PASS':'BLOCK',x.pass?'good':'bad')}
`).join('')}

Evidence provenance

Upstream original training / held-out examples and fixed prediction records from EvalFlow CI Lab.

${pill('SYNTHETIC RESEARCH','unverified')}

1,026 unique annotated research-style sentences: 842 training, 130 IID test, 54 challenge.

${pill('FIXED PREDICTIONS')}

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.

${esc(info.id)}

${pill(detailStatus?.match?'SHA VERIFIED':'NOT VERIFIED',detailStatus?.match?'good':'bad')}
File
${esc(info.file)}
Category
${esc(info.kind)}
License
${esc(info.license)}
Digest
${esc(info.sha256)}

${esc(info.description)}

Dependency inspection

Direct parents
${sel.parents.length?sel.parents.map(esc).join(', '):'None'}
All ancestors
${sel.ancestors.length?sel.ancestors.map(esc).join(', '):'Root asset'}
Direct children
${sel.children.length?sel.children.map(esc).join(', '):'None'}
Downstream
${sel.descendants.length?sel.descendants.map(esc).join(', '):'Leaf asset'}
`;} 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.')+`
${stat('Checked files',i.total)}${stat('Verified',i.verified)}${stat('Mismatched',i.mismatched)}${stat('Unavailable',i.missing)}

Content-addressed inventory

${pill(i.passed?'ALL MATCH':'INTEGRITY FAILURE',i.passed?'good':'bad')}
${state.simulateTamper?'
SIMULATION ONLY. The prediction file on disk is unchanged. This toggle exercises the governance fail-closed rule.
':''}
${items.map(a=>``).join('')}
ArtifactCategorySHA-256 prefixVerification
${esc(a.file)}${esc(a.kind)}${esc(a.expected.slice(0,18))}…${pill(a.verified?'MATCH':'FAILED',a.verified?'good':'bad')}
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.')+`

Candidate evaluation

${pill(r.status,r.status==='PASS'?'good':'bad')}
${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)+']')}

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.

${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)}])}
Matched examples: ${r.pair.n} · Baseline-only: ${r.pair.onlyBase.length} · Candidate-only: ${r.pair.onlyCandidate.length}

Research gate results

${r.gates.map(g=>`
${esc(g.label)}
Actual ${g.unit==='count'?g.actual:fmt(g.actual)} · required ${esc(g.comparator)} ${g.unit==='count'?g.limit:fmt(g.limit)}
${pill(g.pass?'PASS':'BLOCK',g.pass?'good':'bad')}
`).join('')}
`;} 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.

${g.requirements.map(x=>`
${esc(x.label)}
${pill(x.pass?'PASS':'BLOCK',x.pass?'good':'bad')}
`).join('')}

Configure research policy

Percent thresholds are decimals, e.g. 0.75 for 75%.

${edit.map(k=>``).join('')}
The policy applies to the local research comparison only. No production release or GitHub update occurs.
`;} function runs(){const all=state.runs,valid=i=>i>=0&&i

${all.length} local run snapshots

${pill('SESSION ONLY','unverified')}
${all.map((run,i)=>``).join('')}
RunComparisonSplitAccuracyΔ AccuracyGateDigest
#${run.replayId}${esc(E.NAME[run.baseline])} → ${esc(E.NAME[run.candidate])}${esc(run.split)}${fmt(run.accuracy)}${fmt(run.delta)}${pill(run.governance,run.governance==='PASS'?'good':run.governance==='BLOCK'?'bad':'unverified')}${esc(run.recordDigest?.slice(0,12)||'pending')}

Compare two recorded snapshots

${valid(state.registryA)&&valid(state.registryB)?`
${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')}
${[...state.audit].reverse().map(x=>``).join('')}
#UTC timeActionDescriptionSHA prefix
${x.seq}${esc(x.at)}${esc(x.kind)}${esc(x.message)}${x.digest.slice(0,16)}
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.

node verify_bundle.js
node run_reprochain.js --baseline=nb --candidate=hybrid --split=challenge
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=`
${esc(state.error)}
`;console.error(err);}} document.querySelectorAll('.nav-btn').forEach(x=>x.onclick=()=>{state.view=x.dataset.view;render();});$('replay').onclick=()=>recompute();startup(); })();