/* EvalFlow CI Lab — Static browser interface. Source and fixed evaluation remain local. */ (function(){'use strict'; const E=window.EvalFlowEngine;const state={rows:[],meta:null,view:'overview',result:null,policy:{...E.DEFAULT_POLICY},history:[],error:null,filter:'all',search:'',sliceKey:'language',caseLimit:10,dataSource:'bundled synthetic snapshot',imported:false}; const $=id=>document.getElementById(id);const fmt=n=>n==null?'n/a':Number(n).toLocaleString('en-US',{maximumFractionDigits:2});const pct=n=>n==null?'n/a':(n*100).toFixed(1)+'%';const delta=n=>n==null?'n/a':(n>=0?'+':'')+(n*100).toFixed(1)+' pp';const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));const c=(name,body,side='')=>`

${name}

${side}
${body}
`;const stat=(label,val,sub='')=>`
${label}${val}${sub}
`; function badge(ok,text){return `${text??(ok?'PASS':'BLOCK')}`;} function meter(label,val,color=''){return `
${esc(label)}
${pct(val)}
`;} function rowsTable(headers,content){return `
${headers.map(h=>``).join('')}${content}
${esc(h)}
`;} function overview(){const r=state.result,b=r.baselineMetrics,a=r.candidateMetrics,tests=r.gates.filter(g=>g.pass).length;return `
${stat('Candidate Accuracy',pct(a.accuracy),'Held-out '+a.n+' examples')}${stat('Candidate macro-F1',pct(a.macroF1),'Six academic labels')}${stat('Paired Accuracy delta',delta(r.pair.delta),'vs '+E.NAME[r.baseline])}${stat('Research release gate',badge(r.passed,r.status),`${tests} of ${r.gates.length} checks pass`)}
${c('Method comparison',`
Both methods are tested against identical synthetic examples; these are different classifiers, not sequential versions.
${meter('Baseline · '+E.NAME[r.baseline],b.accuracy,'blue')}${meter('Candidate · '+E.NAME[r.candidate],a.accuracy)}${meter('Baseline macro-F1',b.macroF1,'blue')}${meter('Candidate macro-F1',a.macroF1)}
Paired estimate: ${delta(r.pair.delta)} · Fixed-prediction bootstrap 95% interval: ${delta(r.interval.low)} to ${delta(r.interval.high)}
`,'EVIDENCE-BASED')} ${c('Release decision',`
${badge(r.passed,r.passed?'ALL GATES PASS':'RESEARCH GATES BLOCK')}${tests}/${r.gates.length} gate rules satisfied
${r.gates.map(g=>`
${badge(g.pass)}
${esc(g.label)}
Observed ${g.unit==='count'?fmt(g.actual):pct(g.actual)} · Rule ${g.comparator} ${g.unit==='count'?fmt(g.limit):pct(g.limit)}
`).join('')}

Gate results are advisory; no automatic code deployment, model update, or real CI task is performed by this browser.

`,'POLICY CONTRACT')}
${c('Research provenance',`
${stat('Dataset','1,026','842 train / 130 IID / 54 challenge')}${stat('Fixed records',fmt(state.rows.length),'Six stress conditions')}${stat('Source',esc(state.imported?'USER-IMPORTED':'BUNDLED'),'Snapshot, not a live model')}
`,'AUDIT TRAIL')}`;} function pipeline(){const r=state.result;const phases=[['01','Load evidence',state.rows.length+' fixed prediction records','pass'],['02','Validate schema', 'Unique model / split / attack / example keys','pass'],['03','Match examples',r.pair.n+' paired examples, '+r.pair.onlyBase.length+' missing from candidate',r.pair.complete?'pass':'fail'],['04','Compute metrics','Accuracy, macro-F1 and paired differences','pass'],['05','Stress and slices','Language strata, typo and context flip rates','pass'],['06','Evaluate policy',r.gates.filter(x=>!x.pass).length+' rule violations',r.passed?'pass':'fail'],['07','Emit audit artifacts','CLI JSON, Markdown and CSV available','pass']];return `
${c('Pipeline stages',`
${phases.map(([id,label,desc,status])=>`
STAGE ${id}${badge(status==='pass')}
${label}

${esc(desc)}

`).join('')}
`,'LOCAL REPLAY')}
${c('Reproducible command',`
node ci_evalflow.js --baseline=${r.baseline} --candidate=${r.candidate} --split=${r.split} --policy=release_policy.json --output=artifacts

Node 20+ · no npm dependencies · exit code 0 when all gates pass, 2 when gates block, 1 for invalid input. The included GitHub Actions example uses these commands.

`,'CLI')}`;} function regressions(){const r=state.result;const pairs=r.pair.rows;let filtered=pairs;if(state.filter==='improved')filtered=filtered.filter(x=>x.candidateCorrect&&!x.baseCorrect);if(state.filter==='regressed')filtered=filtered.filter(x=>!x.candidateCorrect&&x.baseCorrect);if(state.filter==='changed')filtered=filtered.filter(x=>x.candidatePred!==x.basePred);if(state.search)filtered=filtered.filter(x=>(x.id+' '+x.baseText+' '+x.language+' '+x.truth).toLowerCase().includes(state.search.toLowerCase()));return `
${stat('Paired examples',fmt(r.pair.n),'Identical gold labels')}${stat('Candidate repairs',r.pair.improved,'Wrong → correct')}${stat('New mistakes',r.pair.regressed,'Correct → wrong')}${stat('Paired change',delta(r.pair.delta),'Candidate − baseline')}
${c('Example-level audit',`

Showing ${Math.min(filtered.length,10)} of ${filtered.length} matching pairs. Values are original fixed classifier predictions.

${filtered.slice(0,10).map(x=>`
${esc(x.id)} · ${esc(E.LANG[x.language])}${badge(x.candidateCorrect&&!x.baseCorrect,'REPAIRED')}${!x.candidateCorrect&&x.baseCorrect?badge(false,'NEW ERROR'):''}

${esc(x.baseText)}

Gold: ${esc(x.truth)} · Baseline: ${esc(x.basePred)} ${x.baseCorrect?'✓':'✗'} · Candidate: ${esc(x.candidatePred)} ${x.candidateCorrect?'✓':'✗'}
`).join('')||'
No examples match the current filter.
'}`,'TRACEABLE PAIRS')}`;} function gates(){const r=state.result,p=state.policy;const forms=[['minN','Minimum examples','count',1,1000,1],['minAccuracy','Minimum Accuracy','fraction',0,1,.01],['minMacroF1','Minimum macro-F1','fraction',0,1,.01],['maxRegression','Maximum regression tolerated','fraction',0,1,.01],['maxTypoFlip','Maximum typo flip rate','fraction',0,1,.01],['maxContextFlip','Maximum context flip rate','fraction',0,1,.01],['minLanguageN','Minimum language sample','count',1,1000,1],['minLanguageAccuracy','Minimum language Accuracy','fraction',0,1,.01]];const fields=forms.map(([id,title,unit,min,max,step])=>``).join('');return `${c('Editable research quality contract',`
${fields}
`,'POLICY AS CODE')}
${c('Gate audit · '+r.status,rowsTable(['Gate','Observed','Threshold','Result'],r.gates.map(g=>`${esc(g.label)}${g.unit==='count'?fmt(g.actual):pct(g.actual)}${g.comparator} ${g.unit==='count'?fmt(g.limit):pct(g.limit)}${badge(g.pass)}`).join('')),`${r.gates.length} CHECKS`)}
${c('What the gate cannot measure',`

Documentation completeness, ethics certification, external validity, subgroup fairness and live-model stability are not measured. Fixed predictions can identify mathematical regressions, but not drift in a production service.

A blocking gate identifies a breached research policy. A passing gate does not certify safety or justify deployment.

`,'SCOPE')}`;} function slices(){const r=state.result,key=state.sliceKey,base=E.byGroup(E.get(state.rows,r.baseline,r.split),key),cand=E.byGroup(E.get(state.rows,r.candidate,r.split),key),match=new Map(base.map(x=>[x.label,x]));return `${c('Compare groups',`
${cand.map(v=>`${meter(v.label,v.accuracy)}
${v.n} examples · Baseline ${pct(match.get(v.label)?.accuracy)} · Candidate ${pct(v.accuracy)} · Difference ${delta(v.accuracy-(match.get(v.label)?.accuracy??v.accuracy))}
`).join('')}`,'STRATIFIED EVALUATION')}
${key==='domain'&&cand.length<2?'
':''}${c('Full slice registry',rowsTable(['Group','Examples','Baseline','Candidate','Change'],cand.map(v=>`${esc(v.label)}${v.n}${pct(match.get(v.label)?.accuracy)}${pct(v.accuracy)}${delta(v.accuracy-(match.get(v.label)?.accuracy??v.accuracy))}`).join('')),'DESCRIPTIVE')}
`;} function stress(){const m=state.result.candidateMetrics;return `
${stat('Original examples',m.n,'Fixed held-out split')}${stat('Test conditions',m.attacks.length,'One is destructive')}${stat('Method',esc(E.NAME[m.method]),'Predictions fixed')}
${c('Robustness coverage and flips',rowsTable(['Condition','Evaluated','Actually changed','Flip rate','Matched accuracy'],m.attacks.map(a=>`${esc(a.id)} ${a.destructive?'NO ACCURACY CLAIM':''}${a.n}${a.matched} (${pct(a.changedShare)})${pct(a.flipRate)}${a.destructive?'Not scored':pct(a.matchedAccuracy)}`).join('')),'SIX CONDITIONS')}
${c('What the stress measurements mean',`
${m.attacks.filter(x=>x.id!=='original').map(x=>meter(x.id,x.flipRate,x.flipRate>.15?'red':'' )).join('')}`,'NO FABRICATED ROBUSTNESS')}`;} function registry(){const rows=state.history;return `${c('Local session run registry',`
${rows.length} run replay(s) in this browser session. Nothing is saved to your Hugging Face account automatically. Export the JSON before closing the page if you want to retain these runs.
${rowsTable(['Run','Comparison','Split','Candidate Accuracy','Policy result'],rows.map((x,i)=>`${esc(x.id)}
${esc(x.created)}${esc(E.NAME[x.baseline])} → ${esc(E.NAME[x.candidate])}${esc(x.split)}${pct(x.candidateAccuracy)}${badge(x.passed,x.passed?'PASS':'BLOCK')}`).join(''))}
`,'LOCAL ONLY')}
${c('Repeatability contract',`

Baseline and candidate predictions, sample IDs, gold labels, source hash manifest, release thresholds and random bootstrap seed are versionable artifacts. A reproducible CI run requires pushing these files to a separate code repository with the included workflow.

`,'DATA LINEAGE')}`;} function automation(){return `${c('GitHub Actions integration, opt-in',`
01Version source

Commit benchmark data and all engine source files to GitHub.

02Automated tests

On pushes and pull requests, GitHub runs deterministic engine unit tests.

03Release gates

The Node CLI evaluates the pinned comparisons and exits nonzero when blocked.

node test_engine.js\nnode ci_evalflow.js --baseline=nb --candidate=hybrid --split=challenge --policy=release_policy.json --output=artifacts

The command above reuses 54 fixed challenge examples. The generated report and JSON artifacts are available for GitHub Actions uploads. No hosted model is retrained or deployed by this workflow.

`,'NO PAID COMPUTE')}
${c('Practical release discipline',`

Use a pinned data SHA-256 manifest, fixed test splits, sample-level evidence, a declared policy and a CI status check before tagging a release. Do not merge a failing quality report without documenting the exception and its risk.

`,'REPRODUCIBILITY')}`;} function exportsView(){const r=state.result;return `${c('Download reproducible artifacts',`

All outputs are generated in your browser from the selected models and current quality policy. Model predictions are fixed snapshots from the synthetic benchmark.

Import a different record snapshot in the same JSON schema to run local exploratory checks. Files remain in your browser and are never uploaded to a service.

`,'EXPORT / IMPORT')}
${c('Active provenance',`
Source: ${esc(state.dataSource)}${state.rows.length} rowsBootstrap seed ${r.interval.seed}${r.interval.iterations} resamples

An official SHA-256 registry of the original source artifacts is included as DATA_PROVENANCE.md. View METHODS.md, REPRODUCE.md and SECURITY.md before using results outside the synthetic research demonstration.

`,'HASHES / LICENSE')}`;} const VIEWS={overview:['Command center',overview],pipeline:['Pipeline replay',pipeline],regressions:['Paired regressions',regressions],gates:['Release gates',gates],slices:['Slice diagnostics',slices],stress:['Robustness checks',stress],registry:['Run registry',registry],automation:['CI integration',automation],export:['Export & provenance',exportsView]}; function showError(e){state.error=e instanceof Error?e.message:String(e);$('error').hidden=false;$('error').textContent=state.error;} function clearError(){state.error=null;$('error').hidden=true;$('error').textContent='';} function render(){if(!state.result)return;const [label,fn]=VIEWS[state.view];$('viewTitle').textContent=label;document.querySelectorAll('.nav-btn').forEach(b=>{const active=b.dataset.view===state.view;b.classList.toggle('active',active);b.setAttribute('aria-current',active?'page':'false');});$('content').innerHTML=fn();} function run(addHistory=true){try{clearError();const base=$('baseline').value,cand=$('candidate').value,split=$('split').value;const result=E.evaluate(state.rows,base,cand,split,state.policy);state.result=result;if(addHistory){state.history.unshift({id:'REPLAY-'+String(state.history.length+1).padStart(3,'0'),created:new Date().toISOString(),baseline:base,candidate:cand,split,candidateAccuracy:result.candidateMetrics.accuracy,passed:result.passed,policy:{...state.policy}});}render();}catch(e){showError(e);}} function changeView(name){if(!VIEWS[name])return;state.view=name;render();} function download(name,text,type='text/plain'){const blob=new Blob([text],{type});const link=document.createElement('a');link.href=URL.createObjectURL(blob);link.download=name;document.body.append(link);link.click();link.remove();setTimeout(()=>URL.revokeObjectURL(link.href),1000);} function compactResult(r){return {project:'EvalFlow CI Lab',kind:'research-release-replay',source:state.dataSource,methodComparisonOnly:true,baseline:r.baseline,candidate:r.candidate,split:r.split,policy:r.policy,status:r.status,passed:r.passed,baselineMetrics:r.baselineMetrics,candidateMetrics:r.candidateMetrics,paired:{n:r.pair.n,delta:r.pair.delta,improved:r.pair.improved,regressed:r.pair.regressed,complete:r.pair.complete},interval:r.interval,gates:r.gates,note:r.note};} function handleExport(kind){const r=state.result;if(!r)return;switch(kind){case'report':download('evalflow_audit.md',E.report(r),'text/markdown');break;case'result':download('evalflow_release_replay.json',JSON.stringify(compactResult(r),null,2),'application/json');break;case'paired':download('evalflow_paired_examples.csv',E.csv(r.pair.rows,['id','language','domain','truth','basePred','candidatePred','baseCorrect','candidateCorrect','baseText']),'text/csv');break;case'gates':download('evalflow_gate_decisions.csv',E.csv(r.gates,['id','label','actual','limit','comparator','pass','unit']),'text/csv');break;case'registry':download('evalflow_session_runs.json',JSON.stringify({kind:'local-replay-registry',source:state.dataSource,runs:state.history},null,2),'application/json');break;default:showError('Unknown export type');}} async function importJson(file){try{clearError();if(!file||file.size>10*1024*1024)throw Error('Choose a JSON file smaller than 10 MB');const parsed=JSON.parse(await file.text());const rows=Array.isArray(parsed)?parsed:(parsed?.rows??null);E.verify(rows);state.rows=rows;state.imported=true;state.dataSource='user-imported local JSON';$('heroRecords').textContent=fmt(rows.length);$('dataStatus').textContent='LOCAL IMPORT · UNVERIFIED SOURCE';state.history=[];run();}catch(e){showError(e);}} async function restore(){try{clearError();const res=await fetch('robustness_snapshots.json');if(!res.ok)throw Error('Cannot load bundled evidence (HTTP '+res.status+')');const blob=await res.json();E.verify(blob.rows);state.rows=blob.rows;state.meta=blob.metadata;state.imported=false;state.dataSource='bundled synthetic snapshot';state.history=[];$('heroRecords').textContent=fmt(state.rows.length);$('dataStatus').textContent='SNAPSHOT LOADED';run();}catch(e){showError(e);$('dataStatus').textContent='ERROR · EVIDENCE UNAVAILABLE';}} document.addEventListener('click',ev=>{const t=ev.target.closest('button');if(!t)return;if(t.classList.contains('nav-btn'))changeView(t.dataset.view);else if(t.id==='run')run();else if(t.id==='downloadTop')handleExport('report');else if(t.dataset.export)handleExport(t.dataset.export);else if(t.id==='resetPolicy'){state.policy={...E.DEFAULT_POLICY};run();}else if(t.id==='applyPolicy'){try{const p={};for(const k of Object.keys(E.DEFAULT_POLICY)){p[k]=k==='requireComplete'?true:Number($('policy_'+k).value);}state.policy=E.policyCheck(p);run();}catch(e){showError(e);}}else if(t.id==='restore')restore();}); document.addEventListener('change',ev=>{const t=ev.target;if(t.id==='sliceKey'){state.sliceKey=t.value;render();}else if(t.id==='caseFilter'){state.filter=t.value;render();}else if(t.id==='importJson')importJson(t.files[0]);}); document.addEventListener('input',ev=>{if(ev.target.id==='caseSearch'){state.search=ev.target.value;render();const input=$('caseSearch');input.focus();input.setSelectionRange(input.value.length,input.value.length);}}); restore(); })();