Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

41.5 KB
Raw Blame
import {clone, validateProject, validateTransition, canonical, digest, event, history, planFrozen, settingsValid, assert} from './project.mjs';
import {generatePlan, approveProtocol, appendPhase, combinations, center} from './design.mjs';
import {parseCSV, decode, prepareImport, commitImport, recordMeasurement, verifySources, collectionCSV} from './measurements.mjs';
import {fitProject, plannedAnalysis, predict, compare, predictionSnapshot, confirmationResults} from './analysis.mjs';
import {esc, number, interval, settingLabel, chartSVG, coefficientSVG, reportHTML, runSheetHTML, kitFiles} from './formats.mjs';
import {zipFiles} from './archive.mjs';

const config = JSON.parse(document.querySelector('#signal-data').textContent), originalHTML = document.documentElement.outerHTML;
const $ = s => document.querySelector(s), main = $('#main'), dialog = $('#dialog');
let p = validateProject(config.project), edits = history(p), tab = 'plan', plot = 'run', fit, planned, source = null, baseRevision = config.project.revision, incoming = null, dirty = false, formDirty = false, toastTimer, polling = false, sourceError = null;
let pendingCSV = null, prepared = null, candidateA, candidateB, recovery = null;
const draftKey = 'signal-draft:' + p.id, workspaceId = p.id;
const palettes = ['#087f79','#c36443','#7365a7','#397baf','#bd8720','#b85680','#567c32','#525d69'];
const field = (label, name, value, attrs = '') => `<label>${esc(label)}<input name="${esc(name)}" value="${esc(value)}" ${attrs}></label>`;
const area = (label, name, value, rows = 3, attrs = '') => `<label>${esc(label)}<textarea name="${esc(name)}" rows="${rows}" ${attrs}>${esc(value)}</textarea></label>`;
const option = (value, label, selected) => `<option value="${esc(value)}" ${selected ? 'selected' : ''}>${esc(label)}</option>`;
const pill = (s, type = '') => `<span class="pill ${type}">${esc(s)}</span>`;
const metric = (value, label, accent = false) => `<div class="metric ${accent ? 'accent' : ''}"><strong>${esc(value)}</strong><span>${esc(label)}</span></div>`;
const table = (headers, rows, attrs = '') => `<div class="table-scroll"><table ${attrs}><thead><tr>${headers.map(h => `<th>${esc(h)}</th>`).join('')}</tr></thead><tbody>${rows.join('')}</tbody></table></div>`;
const hero = (step, title, description) => `<div class="hero"><div><div class="eyebrow">${step} / ${['Design a fair test','Keep the evidence','Read the signal','Learn, then test again'][Number(step)-1]}</div><h1>${esc(title)}</h1><p>${esc(description)}</p></div><div class="stage-number">${step}</div></div>`;
function notify(message, error = false) {const el = $('#toast'); el.textContent = message; el.hidden = false; el.classList.toggle('error', error); clearTimeout(toastTimer); toastTimer = setTimeout(() => {el.hidden = true;}, error ? 12000 : 6500);}
function download(name, body, type = 'application/octet-stream') {const blob = body instanceof Blob ? body : new Blob([body], {type}), url = URL.createObjectURL(blob), a = document.createElement('a'); a.href = url; a.download = name; a.click(); setTimeout(() => URL.revokeObjectURL(url), 10000);}
function persist() {try {localStorage.setItem(draftKey, JSON.stringify({baseRevision, project: p}));} catch {notify('Browser storage is full. Save to your workspace or download the editable project to keep this change.', true);}}
function chooseDefaults() {const block = p.design.blocks[0]; candidateA = {settings: Object.fromEntries(p.factors.map(f => [f.id, f.levels[0]])), block}; candidateB = {settings: Object.fromEntries(p.factors.map(f => [f.id, f.levels.at(-1)])), block};}
function changed(next, {resetCandidates = false} = {}) {next = validateProject(next); validateTransition(p, next); p = edits.push(next); dirty = true; formDirty = false; if (resetCandidates) chooseDefaults(); persist(); render();}
function offlineHTML(project = p) {const doc = new DOMParser().parseFromString(originalHTML, 'text/html'); doc.querySelector('#signal-data').textContent = JSON.stringify({project, assets: config.assets}).replace(/</g, '\\u003c'); doc.title = project.title + ' — Signal'; return '<!doctype html>\n' + doc.documentElement.outerHTML;}
function checkForm() {if (!formDirty) return true; notify('Apply your form changes first, or use “Discard form edits”.', true); return false;}
function showDialog(html) {$('#dialog-content').innerHTML = html; if (!dialog.open) dialog.showModal();}
function planView() {
  const frozen = planFrozen(p), disabled = frozen ? 'disabled' : '';
  return hero('01', p.title, p.question) + `<div class="metrics">${metric(p.runs.length, 'runs in your collection sheet', true)}${metric(p.factors.length, 'factors you can change')}${metric(p.design.blocks.length, 'complete blocks')}${metric(planned.rank + '/' + planned.parameters, 'model terms distinguishable')}</div>
  ${frozen ? `<div class="strip"><strong>${p.approved ? 'Protocol approved' : 'Collection has started'}</strong>The original conditions and run order are preserved. Add another phase from Next experiment, or begin a separate project for a different protocol.</div>` : ''}
  <form id="plan-form"><div class="two-col"><div>
  <section class="card"><h2>The question</h2><div class="form-grid">${field('Experiment name','title',p.title,disabled+' required maxlength="160" class="span-all"')}${area('What will this experiment help you decide?','question',p.question,3,disabled+' required')}${field('Measured response','response-name',p.response.name,disabled+' required')}${field('Response unit','response-unit',p.response.unit,disabled+' required')}
  <label>Goal<select name="goal" ${disabled}>${['maximize','minimize','target'].map(x=>option(x, x==='target'?'Approach a target':x==='maximize'?'Larger is better':'Smaller is better',p.response.goal===x)).join('')}</select></label>${field('Target (used for target goal)','target',p.response.target??0,disabled+' type="number" step="any"')}</div></section>
  <section class="card"><div class="section-head"><h2>What you can vary</h2><button type="button" data-action="add-factor" ${disabled}>+ Add factor</button></div><div class="factor-grid">${p.factors.map((f,i)=>`<div class="factor"><div class="factor-head"><strong>FACTOR ${String(i+1).padStart(2,'0')}</strong><button type="button" data-action="remove-factor" data-id="${esc(f.id)}" ${disabled || (p.factors.length===1?'disabled':'')}>Remove</button></div><div class="form-grid">${field('Name','factor-name-'+f.id,f.name,disabled+' required')}<label>Type<select name="factor-type-${esc(f.id)}" ${disabled}>${option('number','Numeric',f.type==='number')}${option('category','Category',f.type==='category')}</select></label>${field('Unit','factor-unit-'+f.id,f.unit,disabled)}${area('Levels · one per line','factor-levels-'+f.id,f.levels.join('\n'),3,disabled+' required')}</div></div>`).join('')}</div><p class="helper">Every combination is tested. Numeric factors use the low and high levels to code the model; categories use the first level as the reference.</p></section>
  <section class="card"><h2>A repeatable procedure</h2><div class="form-grid">${area('One independent experimental unit','protocol-unit',p.protocol.unit,3,disabled+' required')}${area('How will you randomize and control the conditions?','randomization',p.protocol.randomization,3,disabled+' required')}${area('Procedure · one step per line','steps',p.protocol.steps.join('\n'),7,disabled+' required class="span-all"')}${area('Analysis planned before collection','analysis-plan',p.protocol.analysisPlan,4,disabled+' required')}${area('Practical notes and departures to record','notes',p.protocol.notes,4,disabled)}</div></section></div>
  <div><section class="card"><h2>Build your run sheet</h2><div class="form-grid">${field('Independent repetitions per combination','replicates',p.design.replicates,disabled+' type="number" min="1" max="20" required')}${field('Randomization seed','seed',p.design.seed,disabled+' required')}${area('Complete blocks · one name per line','blocks',p.design.blocks.join('\n'),3,disabled+' required')}<label>Scheduled controls per block<select name="controls" ${disabled}>${[0,2,3,4,5].map(x=>option(x,x===0?'None':x+' midpoint / reference controls',p.design.controls===x)).join('')}</select></label></div><p class="helper">A block repeats every combination under a shared condition, such as a shelf or a material lot. Controls bracket and span each block; they use numeric midpoints and the first category level.</p><div class="report-actions"><button class="primary" type="submit" ${disabled}>Apply plan & rebuild run sheet</button></div></section>
  <section class="card"><h2>Before you collect</h2><div class="check-row"><span>Independent runs</span><span>${p.runs.length}</span></div><div class="check-row"><span>Planned model columns</span><span>${planned.parameters}</span></div><div class="check-row"><span>Identifiable columns</span><span>${planned.rank}</span></div><div class="check-row"><span>Residual degrees of freedom</span><span>${planned.df}</span></div>${planned.rank<planned.parameters?'<div class="strip warn">This design cannot separate all requested model terms. Revise the model or add informative points.</div>':''}<p class="helper">Re-reading one jar, pot or sample does not create another independent run.</p><div class="actions report-actions"><button type="button" data-action="approve" ${frozen?'disabled':''}>${p.approved?'Approved ✓':'Approve protocol'}</button><button type="button" data-tab="collect">Collection sheet →</button></div></section>
  <div class="actions"><button type="button" data-action="undo" ${edits.canUndo&&!frozen?'':'disabled'}>Undo plan edit</button><button type="button" data-action="redo" ${edits.canRedo&&!frozen?'':'disabled'}>Redo</button><button type="button" data-action="discard-form">Discard form edits</button></div></div></div></form>`;
}
function collectView() {
  const measurements=new Map(p.measurements.map(m=>[m.runId,m]));
  return hero('02','Your evidence, intact.','Use the run sheet in the real world. Import the results or record each measurement here; leave unfinished runs blank.')+
  `<div class="metrics">${metric(p.measurements.length,'measured responses',true)}${metric(fit.pending,'still to collect')}${metric(p.sources.length,'original CSV files retained')}${metric(fit.excluded,'excluded, with reasons')}</div>
  <section class="card"><div class="section-head"><h2>Collection sheet</h2><div class="actions"><button data-action="download-sheet">Download blank CSV</button><button data-action="print-sheet">Printable sheet</button><button data-action="import-csv" class="primary">Import measurements</button></div></div><p class="helper">Response: <strong>${esc(p.response.name)} in ${esc(p.response.unit)}</strong>. Click a run to record a result, correct a transcription or document an exclusion.</p>
  ${table(['Run / order',...p.factors.map(f=>f.name+(f.unit?' · '+f.unit:'')),'Block','Response · '+p.response.unit,'State'],p.runs.map(r=>{const m=measurements.get(r.id);return `<tr data-run="${r.id}"><td><strong>${r.id}</strong><div class="small">${r.order} · ${r.kind==='control'?'control':r.phase}</div></td>${p.factors.map(f=>`<td>${esc(r.settings[f.id])}</td>`).join('')}<td>${esc(r.block)}</td><td class="${m?'state-measured':'state-pending'}">${m?number(m.value):'—'}</td><td><button data-action="measure" data-id="${r.id}">${m?.excluded?'Excluded':m?'Review':'Record'}</button></td></tr>`;}))}</section>
  <section class="card"><div class="chart">${chartSVG(p,fit,'run')}</div><div class="plot-tip" id="plot-tip">Hover or focus a point to inspect its run.</div></section>
  <section class="card"><h2>Original files and recorded changes</h2>${p.sources.length?p.sources.map(s=>`<details><summary>${esc(s.name)} · original CSV</summary><p class="small wrap">SHA-256 ${esc(s.sha256)}</p><p class="small">${esc(s.mapping.runId)} → run id · ${esc(s.mapping.response)} → ${esc(p.response.name)} · ${esc(s.unit)}</p><button data-action="original-csv" data-id="${esc(s.id)}">Download original bytes</button></details>`).join(''):'<p class="muted">No files imported yet. Manual entries keep their own change history.</p>'}<details><summary>Change log · ${p.audit.length} records</summary>${p.audit.slice().reverse().slice(0,40).map(e=>`<div class="audit-row">${esc(e.reason)}<small>${esc(e.at)} · ${esc(e.action)}</small></div>`).join('')}<p class="small">The complete log travels with the editable project.</p></details></section>`;
}
function legend() {return `<div class="legend">${p.design.blocks.map((b,i)=>`<span><i class="dot" style="background:${palettes[i%palettes.length]}"></i>${esc(b)}</span>`).join('')}</div>`;}
function modelControls() {
  const terms=p.factors.map(f=>({id:f.id,label:f.name}));
  for(let i=0;i<p.factors.length;i++)for(let j=i+1;j<p.factors.length;j++)terms.push({id:p.factors[i].id+':'+p.factors[j].id,label:p.factors[i].name+' × '+p.factors[j].name});
  for(const f of p.factors.filter(f=>f.type==='number'))terms.push({id:f.id+'^2',label:f.name+' · curvature'});
  return `<form id="model-form"><div class="terms">${terms.map(t=>`<label><input type="checkbox" name="term" value="${esc(t.id)}" ${p.model.terms.includes(t.id)?'checked':''}>${esc(t.label)}</label>`).join('')}<label><input type="checkbox" name="blocks" ${p.model.blocks?'checked':''}>Account for fixed block differences</label></div><label>Pointwise confidence<select name="confidence">${[.8,.9,.95,.99].map(c=>option(c,c*100+'%',p.model.confidence===c)).join('')}</select></label>${area('Reason for changing the model','reason','',2,p.measurements.length?'required':'')}<p class="helper">Interactions retain both main effects; curvature retains its numeric main effect. Model changes after looking at results are recorded as exploratory.</p><div class="actions report-actions"><button type="submit">Apply model</button><button type="button" data-action="discard-form">Discard form edits</button></div></form>`;
}
function analyzeView() {
  const intro=hero('03','What changed the outcome?','Inspect the measurements, the uncertainty and the model’s blind spots before choosing what to try next.');
  const metrics=`<div class="metrics">${metric(fit.n,'independent runs in this fit',true)}${metric(fit.ok?number(fit.rmse):'—','residual SD · '+p.response.unit)}${metric(fit.ok?number(fit.looRMSE):'—','leave-one-out prediction RMSE')}${metric(fit.df,'residual degrees of freedom')}</div>`;
  const results=!fit.ok?`<div class="empty"><h2>${p.measurements.length?'The model needs more evidence.':'Begin with your measurements.'}</h2><p>${esc(fit.issue)}</p><button data-tab="collect" class="primary">Go to collection</button></div>`:
  `<section class="card"><div class="section-head"><h2>Look at the evidence</h2><div class="tabs">${[['run','Run order'],['fit','Measured vs fitted'],['residual','Residuals']].map(([v,label])=>`<button data-action="plot" data-mode="${v}" class="${plot===v?'selected':''}">${label}</button>`).join('')}</div></div><div class="chart">${chartSVG(p,fit,plot)}</div><div class="plot-tip" id="plot-tip">Hover or focus a point to inspect its run.</div><p class="helper">${plot==='run'?'Look for drift across the collection order or unexpected differences between blocks.':plot==='fit'?'The dashed line is a perfect match. Prediction quality on new runs still needs confirmation.':'Look for curvature, changing spread or patterns the chosen terms have missed.'}</p></section>
  <section class="card"><h2>Effects, with room for uncertainty</h2><div class="chart">${coefficientSVG(fit)}</div>${table(['Model term','Coefficient',p.model.confidence*100+'% interval'],fit.coefficients.map(c=>`<tr><td>${esc(c.label)}</td><td>${number(c.value)}</td><td>${interval(c.ci)}</td></tr>`))}<p class="helper">Numeric factors are coded from −1 to +1 across the planned range. Categories compare with the first level. These are model coefficients, not a ranking of causal importance.</p></section>
  <section class="card"><h2>Measurements worth reviewing</h2>${fit.residuals.some(r=>r.review)?table(['Run','Residual','Leverage','Cook’s distance',''],fit.residuals.filter(r=>r.review).map(r=>`<tr><td>${r.runId}</td><td>${number(r.residual)}</td><td>${number(r.leverage)}</td><td>${number(r.cook)}</td><td><button data-action="measure" data-id="${r.runId}">Review original</button></td></tr>`)):'<p class="muted">No rows cross the displayed leverage or influence review thresholds.</p>'}<p class="helper">Leverage &gt; 2p/n or Cook’s distance &gt; 4/n prompts review. Nothing is removed automatically.</p>${fit.excluded?'<button data-action="sensitivity">Compare with all recorded measurements</button>':''}</section>`;
  return intro+metrics+`<div class="two-col"><div>${results}</div><div><section class="card"><h2>Your model</h2>${modelControls()}</section><section class="card"><h2>Read the uncertainty correctly</h2><p class="small">A mean interval describes the model’s average response at a setting. A prediction interval is wider: it describes one new independent observation.</p><p class="small">The fit assumes independent runs, constant residual variance and a suitable linear mean model with approximately normal errors. The intervals are pointwise; searching many settings does not provide simultaneous coverage.</p>${fit.warnings.map(w=>`<div class="strip warn">${esc(w)}</div>`).join('')}<button data-tab="followup" class="primary">Compare the next settings →</button></section></div></div>`;
}
function candidateCard(key, candidate, label) {
  const prediction=fit.ok?predict(p,fit,candidate.settings,candidate.block):null;
  return `<div><div class="candidate-title"><h3>${label}</h3>${pill(key.toUpperCase())}</div>${p.factors.map(f=>`<label class="setting">${esc(f.name)}${f.unit?' · '+esc(f.unit):''}${f.type==='number'?`<div class="setting-fields"><input type="range" data-candidate="${key}" data-factor="${f.id}" min="${f.levels[0]}" max="${f.levels.at(-1)}" step="${(f.levels.at(-1)-f.levels[0])/100}" value="${candidate.settings[f.id]}" aria-label="${label} ${esc(f.name)} slider"><input type="number" data-candidate="${key}" data-factor="${f.id}" min="${f.levels[0]}" max="${f.levels.at(-1)}" step="any" value="${candidate.settings[f.id]}" aria-label="${label} ${esc(f.name)}"></div>`:`<select data-candidate="${key}" data-factor="${f.id}">${f.levels.map(v=>option(v,v,candidate.settings[f.id]===v)).join('')}</select>`}</label>`).join('')}<label class="setting">Comparable block<select data-candidate="${key}" data-block="true">${p.design.blocks.map(v=>option(v,v,candidate.block===v)).join('')}</select></label>${prediction?`<div class="prediction"><div class="eyebrow">Predicted ${esc(p.response.name)}</div><div class="value">${number(prediction.mean)} <small style="font-size:17px">${esc(p.response.unit)}</small></div><div>${p.model.confidence*100}% mean interval: ${interval(prediction.meanCI)}</div><small>One new observation: ${interval(prediction.predictionCI)}</small></div>`:'<div class="strip">No response estimate yet. Additional independent runs can help identify the model.</div>'}</div>`;
}
function followupControls() { return `<section class="card"><h2>Turn the comparison into a test</h2><form id="followup-form"><div class="form-grid">${field('Phase name','label','Confirmation '+(p.phases.length), 'required')}${field('Independent repetitions per point','repeats',3,'type="number" min="1" max="20" required')}<label class="span-all">Purpose<select name="kind"><option value="confirmation" ${fit.ok&&fit.inferential?'':'disabled'}>Confirm · keep new data out of original fit</option><option value="extension" ${fit.ok&&fit.inferential?'':'selected'}>Extend · add new data to the model</option></select></label>${field('Randomization seed','seed',p.design.seed+'-next-'+p.phases.length,'required')}${area('Why this follow-up?','reason','Compare the reference and candidate with fresh independent runs under comparable conditions.',4,'required')}</div><div class="strip">The settings above become labeled, randomized runs. Confirmation keeps a snapshot of today’s forecast. Extension deliberately adds future observations to the training fit.</div><button class="primary" type="submit">Append follow-up runs</button></form></section>`; }
function followupView() {
  const intro=hero('04','Make the next test count.','Compare candidate settings, freeze the prediction, and put it to a fresh test. The original evidence stays intact.');
  if(!fit.ok)return intro+`<div class="strip warn"><strong>${esc(fit.issue)}</strong>You can collect the remaining runs or append an extension at informative settings. Confirmation becomes available after estimating residual uncertainty.</div><div class="two-col"><section class="card"><h2>Choose additional settings</h2><div class="candidate-grid">${candidateCard('a',candidateA,'Point A')}${candidateCard('b',candidateB,'Point B')}</div></section><div>${followupControls()}</div></div>`;
  const comparison=compare(p,fit,candidateA,candidateB), score=v=>p.response.goal==='maximize'?-v:p.response.goal==='minimize'?v:Math.abs(v-p.response.target);
  const ranked=combinations(p).map(settings=>predict(p,fit,settings,candidateB.block)).sort((a,b)=>score(a.mean)-score(b.mean)).slice(0,6), confirmations=confirmationResults(p);
  return intro+`<div class="two-col"><div><section class="card"><div class="section-head"><h2>Compare two possibilities</h2>${pill(p.model.confidence*100+'% pointwise intervals')}</div><div class="candidate-grid">${candidateCard('a',candidateA,'Reference')}${candidateCard('b',candidateB,'Candidate')}</div><div class="comparison"><div class="eyebrow">Candidate minus reference</div><strong>${number(comparison.difference)} ${esc(p.response.unit)}</strong><div>Mean difference interval: ${interval(comparison.ci)}</div></div><p class="helper">Predictions stay inside the planned ranges. Unmeasured combinations still rely on the model; these intervals do not establish an optimum.</p></section>
  <section class="card"><h2>Explore the planned combinations</h2><p class="helper">The six closest candidates for your stated goal, under the selected block and model. Choose one to compare; this is an exploratory ordering.</p>${table(['Settings','Predicted mean',''],ranked.map((r,i)=>`<tr><td>${esc(settingLabel(p,r.settings))}</td><td>${number(r.mean)} ${esc(p.response.unit)}</td><td><button data-action="candidate" data-settings="${esc(JSON.stringify(r.settings))}">Compare</button></td></tr>`),'class="ranked"')}</section>
  ${confirmations.length?`<section class="card"><h2>Did the new measurements agree?</h2>${confirmations.map(c=>`<div class="strip"><strong>${esc(c.phase)} · ${c.n}/${c.planned} measured</strong>${esc(settingLabel(p,c.prediction.settings))}<div class="form-grid" style="margin-top:15px"><div>Frozen model mean<div class="measure-value">${number(c.prediction.mean)}</div><span class="small">Mean CI ${interval(c.prediction.meanCI)}</span></div><div>New measured mean<div class="measure-value">${number(c.mean)}</div><span class="small">Own CI ${interval(c.ci)}</span></div></div><p>Actual minus predicted: ${number(c.difference)} ${esc(p.response.unit)}. The original fit does not use these responses.</p><button data-action="phase-csv" data-id="${c.phaseId}">Download this phase’s run sheet</button></div>`).join('')}<p class="helper">Each observed mean interval uses only its fresh repetitions. Comparing it with the original forecast is a diagnostic, not a pass/fail decision rule.</p></section>`:''}</div>
  <div>${followupControls()}
  <section class="card"><h2>Record your decision</h2><form id="conclusion-form">${area('What do the evidence and practical tradeoffs support?','conclusion',p.conclusion??'',7)}<button type="submit" style="margin-top:14px">Save decision note</button></form><p class="helper">This note accompanies the report. Separate what you measured, what the model predicts and what still needs testing.</p></section><section class="card"><h2>Take the whole experiment with you</h2><p class="small">Keep the source, original files, run sheets, figures, model matrix and Python reproduction script together.</p><div class="actions"><button data-action="report">Download report</button><button data-action="export" class="primary">Export complete kit ↗</button></div></section></div></div>`;
}
function render() {
  fit=fitProject(p); planned=plannedAnalysis(p); document.title=p.title+' — Signal'; $('#side-title').textContent=p.title;
  $('#side-status').innerHTML=`<div class="side-count"><strong>${p.measurements.length}</strong><span class="small">/ ${p.runs.length} measured</span></div><div class="progress"><span style="width:${p.runs.length?p.measurements.length/p.runs.length*100:0}%"></span></div><div class="side-note">${p.approved?'Protocol approved':'Protocol open for review'}<br>${p.sources.length} original files · ${p.audit.length} recorded changes</div>`;
  for(const el of document.querySelectorAll('[data-tab]'))el.classList.toggle('active',el.dataset.tab===tab);
  main.innerHTML=(p.evidenceNote?`<div class="strip warn">${esc(p.evidenceNote)}</div>`:'')+({plan:planView,collect:collectView,analyze:analyzeView,followup:followupView}[tab])();
  renderConnection();
}
function renderConnection() {
  $('#save-source').disabled=!source||p.id!==source.id;
  $('#connection').textContent=sourceError?('Source needs attention · '+sourceError):source?(p.id!==source.id?'Portable project · download to keep':dirty?'Unsaved workspace changes':'Saved in your workspace'):'Offline project · editable and portable';
  const conflict=$('#conflict'); conflict.hidden=!incoming&&!recovery;
  if(incoming)conflict.innerHTML=`The workspace source changed while you had a draft. Both versions are available.<div class="actions"><button data-action="download-project">Keep my draft</button><button data-action="incoming-project">Download source</button><button data-action="load-source">Keep draft & load source</button></div>`;
  else if(recovery)conflict.innerHTML=`A previous browser draft belongs to a different source edition.<div class="actions"><button data-action="recovery">Download that draft</button><button data-action="dismiss-recovery">Keep current edition</button></div>`;
}
function readPlan(form) {
  const q=clone(p),data=new FormData(form);assert(!planFrozen(p),'This protocol is locked.');
  q.title=String(data.get('title'));q.question=String(data.get('question'));q.response={...q.response,name:String(data.get('response-name')),unit:String(data.get('response-unit')),goal:String(data.get('goal')),target:Number(data.get('target'))};
  if(q.response.goal==='target')assert(String(data.get('target')).trim()!=='','Enter a target response.');
  q.factors=q.factors.map(f=>{const type=String(data.get('factor-type-'+f.id)),levels=String(data.get('factor-levels-'+f.id)).split('\n').map(x=>x.trim()).filter(Boolean);return {...f,name:String(data.get('factor-name-'+f.id)),type,unit:String(data.get('factor-unit-'+f.id)),levels:type==='number'?levels.map(Number):levels};});
  q.design={seed:String(data.get('seed')),replicates:Number(data.get('replicates')),blocks:String(data.get('blocks')).split('\n').map(x=>x.trim()).filter(Boolean),controls:Number(data.get('controls'))};
  q.protocol={unit:String(data.get('protocol-unit')),randomization:String(data.get('randomization')),steps:String(data.get('steps')).split('\n').map(x=>x.trim()).filter(Boolean),analysisPlan:String(data.get('analysis-plan')),notes:String(data.get('notes'))};
  q.model.terms=q.model.terms.filter(t=>!t.endsWith('^2')||q.factors.find(f=>f.id===t.slice(0,-2))?.type==='number');
  event(q,'plan-edit','Revised the uncollected experimental plan.',{before:{factors:p.factors,response:p.response,design:p.design,protocol:p.protocol,runs:p.runs}});q.runs=[];q.phases=[];delete q.comparison;
  return generatePlan(q);
}
function measurementDialog(id) {
  const run=p.runs.find(r=>r.id===id),m=p.measurements.find(m=>m.runId===id);assert(run,'Choose a known run.');
  showDialog(`<div class="eyebrow">Run ${esc(id)} · ${esc(run.block)}</div><h2>${m?'Review the measurement':'Record what you measured'}</h2><p>${esc(settingLabel(p,run.settings))}</p><form id="measurement-form" data-id="${id}"><div class="form-grid">${field(p.response.name+' ('+p.response.unit+')','value',m?.value??'','type="number" step="any" required')}${field('Reason for this entry or correction','reason',m?'':'Direct observation','required maxlength="600"')}${area('Run note','note',m?.note??'',3)}${area('Exclusion reason · leave blank to include','excluded',m?.excluded??'',3)}</div><p class="helper">${m?'Original '+esc(m.origin.kind==='csv'?m.origin.source+', line '+m.origin.row:'direct entry')+': '+number(m.origin.value)+' '+esc(p.response.unit)+'. Corrections keep this value and the complete change history.':'Enter an actual observation. A blank run is pending; it is never replaced with a model prediction.'}</p><div class="actions"><button type="button" data-action="close">Cancel</button><button type="submit" class="primary">${m?'Record change':'Save measurement'}</button></div></form>`);
}
function importDialog() {
  const parsed=parseCSV(decode(pendingCSV.bytes));prepared=null;
  showDialog(`<div class="eyebrow">Import measurements</div><h2>Match the columns, then review.</h2><p>${esc(pendingCSV.name)} · ${parsed.rows.length} rows · original bytes will be retained.</p><form id="import-form"><div class="form-grid"><label>Run id column<select name="runId">${parsed.headers.map(h=>option(h,h,h==='run_id')).join('')}</select></label><label>Measured response column<select name="response">${parsed.headers.map(h=>option(h,h,h==='response')).join('')}</select></label>${field('Confirm the response unit','unit',p.response.unit,'required')}</div><p class="helper">Known run ids link each result to its settings. Missing responses remain pending. Duplicate ids, unknown ids, existing results and mismatched settings are rejected together.</p><div id="import-preview"></div><div class="actions"><button type="button" data-action="close">Cancel</button><button type="submit">Preview import</button><button type="button" data-action="commit-import" id="commit-import" class="primary" disabled>Import measurements</button></div></form>`);
}
async function previewImport() {
  const data=new FormData($('#import-form'));prepared=await prepareImport(p,pendingCSV.bytes,{name:pendingCSV.name,mapping:{runId:String(data.get('runId')),response:String(data.get('response'))},unit:String(data.get('unit'))});
  $('#import-preview').innerHTML=`<div class="strip"><strong>${prepared.records.length} measured responses · ${prepared.pending} blank cells</strong>Nothing has been applied yet.</div>${table(['Run','Measured response','Original line'],prepared.records.slice(0,5).map(r=>`<tr><td>${r.runId}</td><td>${number(r.value)} ${esc(prepared.source.unit)}</td><td>${r.row}</td></tr>`))}`;$('#commit-import').disabled=false;
}
async function saveSource() {
  assert(source&&p.id===source.id,'Download this portable project or open it in its own workspace.');assert(!incoming,'Resolve the source change first; both versions are available.');
  const sent=await verifySources(p),response=await fetch('/api/project',{method:'PUT',headers:{'content-type':'application/json','if-match':baseRevision},body:JSON.stringify(sent)}),body=await response.json();
  if(response.status===409){incoming=body.project;renderConnection();throw new Error(body.error);}
  assert(response.ok,body.error||'The source could not be saved.');source=body.project;baseRevision=source.revision;
  if(canonical(p)===canonical(sent)){p=validateProject(source);edits=history(p);dirty=false;formDirty=false;}
  persist();render();notify(dirty?'Saved the submitted edition; your newer changes are still in the draft.':'Saved the complete experiment. The previous source edition is retained in workspace history.');
}
async function pollSource() {
  if(polling||!/^https?:$/.test(location.protocol)||!['127.0.0.1','localhost'].includes(location.hostname))return;polling=true;
  try{const response=await fetch('/api/project');if(response.status===503)return;if(!response.ok){const err=await response.json();if(sourceError!==err.error)notify('Workspace source needs attention. Your current draft is preserved: '+err.error,true);sourceError=err.error;renderConnection();return;}sourceError=null;const body=await response.json();assert(body.project,'No source project.');const next=body.project;await verifySources(next);source??=next;
    if(next.revision!==baseRevision){if(dirty||formDirty||p.id!==next.id){incoming=next;renderConnection();}else{source=next;baseRevision=next.revision;p=validateProject(next);edits=history(p);chooseDefaults();render();}}else{source=next;renderConnection();}
  }catch{}finally{polling=false;}
}
async function action(button) {
  const name=button.dataset.action;
  if(name==='close'){dialog.close();return;}
  if(name==='discard-form'){formDirty=false;render();return;}
  if(!['original-csv','download-project','incoming-project','recovery','dismiss-recovery'].includes(name)&&!checkForm())return;
  if(name==='open'){$('#project-file').value='';$('#project-file').click();}
  else if(name==='download-project')download(p.id+'.signal.json',JSON.stringify(p,null,2),'application/json');
  else if(name==='save')await saveSource();
  else if(name==='export'){await verifySources(p);download(p.id+'-experiment.zip',zipFiles(kitFiles(p,offlineHTML(),config.assets)));notify('Exported editable studio, original measurements, run sheets, report and reproducible calculations.');}
  else if(name==='report')download(p.id+'-report.html',reportHTML(p),'text/html');
  else if(name==='download-sheet')download(p.id+'-collection.csv',collectionCSV(p),'text/csv');
  else if(name==='print-sheet')download(p.id+'-collection-sheet.html',runSheetHTML(p),'text/html');
  else if(name==='phase-csv')download(p.id+'-'+button.dataset.id+'.csv',collectionCSV(p,{phase:button.dataset.id}),'text/csv');
  else if(name==='approve'){changed(approveProtocol(p));notify('The protocol and original run order are now protected.');}
  else if(name==='undo'||name==='redo'){assert(!planFrozen(p),'Collected or approved plans use logged revisions.');p=name==='undo'?edits.undo():edits.redo();dirty=true;persist();chooseDefaults();render();}
  else if(name==='add-factor'||name==='remove-factor'){
    assert(!planFrozen(p),'This protocol is locked.');const q=clone(p);event(q,'plan-edit',name==='add-factor'?'Added a factor before collection.':'Removed a factor before collection.',{before:{factors:p.factors,runs:p.runs}});
    if(name==='add-factor'){assert(q.factors.length<6,'Use at most six factors.');let n=1;while(q.factors.some(f=>f.id==='factor'+n))n++;const id='factor'+n;q.factors.push({id,name:'New factor',type:'number',unit:'',levels:[0,1]});q.model.terms.push(id);}
    else{q.factors=q.factors.filter(f=>f.id!==button.dataset.id);q.model.terms=q.model.terms.filter(t=>!t.split(':').map(x=>x.replace('^2','')).includes(button.dataset.id));}
    q.runs=[];q.phases=[];delete q.comparison;changed(generatePlan(q),{resetCandidates:true});
  }
  else if(name==='measure')measurementDialog(button.dataset.id);
  else if(name==='import-csv'){$('#csv-file').value='';$('#csv-file').click();}
  else if(name==='commit-import'){await previewImport();changed(commitImport(p,prepared));dialog.close();notify('Imported measured responses. The original file and exact row references are preserved.');}
  else if(name==='original-csv'){const s=p.sources.find(s=>s.id===button.dataset.id);download(s.name,Uint8Array.from(atob(s.base64),x=>x.charCodeAt(0)),'text/csv');}
  else if(name==='plot'){plot=button.dataset.mode;render();}
  else if(name==='candidate'){candidateB.settings=JSON.parse(button.dataset.settings);const q=clone(p);q.comparison={a:candidateA,b:candidateB};changed(q);}
  else if(name==='sensitivity'){
    const all=fitProject(p,{includeExcluded:true});showDialog(`<h2>Keep the exclusions visible.</h2><p>The primary fit uses ${fit.n} rows; the sensitivity fit includes all ${all.n} recorded training rows. Confirmation runs stay held out in both.</p>${all.ok&&fit.ok?table(['Term','Primary','All recorded','Change'],fit.coefficients.map((c,i)=>`<tr><td>${esc(c.label)}</td><td>${number(c.value)}</td><td>${number(all.coefficients[i].value)}</td><td>${number(all.coefficients[i].value-c.value)}</td></tr>`)):`<p>${esc(all.issue??fit.issue)}</p>`}<div class="actions"><button data-action="close">Close</button></div>`);
  }
  else if(name==='incoming-project')download(p.id+'-workspace-source.signal.json',JSON.stringify(incoming,null,2),'application/json');
  else if(name==='load-source'){assert(incoming,'No source change.');download(p.id+'-previous-draft.signal.json',JSON.stringify(p,null,2),'application/json');p=await verifySources(incoming);source=incoming;baseRevision=source.revision;incoming=null;dirty=false;formDirty=false;edits=history(p);chooseDefaults();persist();render();}
  else if(name==='recovery')download('recovered-draft.signal.json',JSON.stringify(recovery.project,null,2),'application/json');
  else if(name==='dismiss-recovery'){recovery=null;persist();renderConnection();}
}
document.addEventListener('click',e=>{
  const button=e.target.closest('button');if(button){if(button.dataset.tab){if(!checkForm())return;tab=button.dataset.tab;render();window.scrollTo({top:0,behavior:'instant'});}else if(button.dataset.action)void action(button).catch(err=>notify(err.message,true));return;}
  const row=e.target.closest('tr[data-run]');if(row&&checkForm())measurementDialog(row.dataset.run);
});
document.addEventListener('submit',e=>{e.preventDefault();void (async()=>{
  if(e.target.id==='plan-form'){changed(readPlan(e.target),{resetCandidates:true});notify('Updated the plan and randomized the new collection sheet.');}
  else if(e.target.id==='measurement-form'){const data=new FormData(e.target);changed(recordMeasurement(p,e.target.dataset.id,{value:data.get('value'),note:String(data.get('note')),excluded:String(data.get('excluded')).trim()||null,reason:String(data.get('reason'))}));dialog.close();notify('Recorded the measurement and its change history.');}
  else if(e.target.id==='import-form')await previewImport();
  else if(e.target.id==='model-form'){
    const data=new FormData(e.target),q=clone(p),terms=data.getAll('term').map(String);for(const t of [...terms])for(const part of t.split(':').map(x=>x.replace('^2','')))if(!terms.includes(part))terms.unshift(part);
    const after={terms,blocks:data.has('blocks'),confidence:Number(data.get('confidence'))};event(q,'model',String(data.get('reason')).trim()||'Revised the model before collecting data.',{before:q.model,after,afterCollection:q.measurements.length>0});q.model=after;changed(q);notify('Updated the model. All original measurements are retained.');
  }
  else if(e.target.id==='followup-form'){
    const data=new FormData(e.target),points=[candidateA,candidateB].filter((x,i,a)=>a.findIndex(y=>canonical(x)===canonical(y))===i),kind=String(data.get('kind'));
    const snapshot=kind==='confirmation'?await predictionSnapshot(p,fit,points):undefined;
    changed(appendPhase(p,{points,repeats:Number(data.get('repeats')),label:String(data.get('label')),seed:String(data.get('seed')),reason:String(data.get('reason')),kind,snapshot}));notify('Added a new phase. The original run settings and measurements are unchanged.');
  }
  else if(e.target.id==='conclusion-form'){const q=clone(p);q.conclusion=String(new FormData(e.target).get('conclusion'));event(q,'decision','Updated the interpretation and decision note.',{before:p.conclusion??'',after:q.conclusion});changed(q);notify('Saved the decision note for the report.');}
})().catch(err=>notify(err.message,true));});
document.addEventListener('input',e=>{if(e.target.closest('#plan-form,#model-form,#conclusion-form,#followup-form'))formDirty=true;if(e.target.closest('#import-form')){$('#commit-import').disabled=true;prepared=null;}});
document.addEventListener('change',e=>{void (async()=>{
  if(e.target.id==='csv-file'&&e.target.files[0]){const file=e.target.files[0];assert(file.size<=1000000,'Use a CSV below 1 MB.');pendingCSV={name:file.name,bytes:new Uint8Array(await file.arrayBuffer())};importDialog();}
  else if(e.target.id==='project-file'&&e.target.files[0]){const file=e.target.files[0];assert(file.size<=5000000,'Use a complete project below 5 MB.');const next=await verifySources(JSON.parse(await file.text()));download(p.id+'-before-open.signal.json',JSON.stringify(p,null,2),'application/json');p=next;edits=history(p);dirty=true;formDirty=false;incoming=null;tab='plan';chooseDefaults();persist();render();notify('Opened the complete experiment and downloaded the previous project for recovery.');}
  else if(e.target.dataset.candidate){assert(checkForm(),'Apply form edits before changing the comparison.');const key=e.target.dataset.candidate,candidate=clone(key==='a'?candidateA:candidateB);if(e.target.dataset.block)candidate.block=e.target.value;else{const f=p.factors.find(f=>f.id===e.target.dataset.factor);candidate.settings[f.id]=f.type==='number'?Number(e.target.value):e.target.value;}settingsValid(p,candidate.settings);if(fit.ok)predict(p,fit,candidate.settings,candidate.block);if(key==='a')candidateA=candidate;else candidateB=candidate;const q=clone(p);q.comparison={a:candidateA,b:candidateB};changed(q);}
})().catch(err=>notify(err.message,true));});
for(const type of ['pointerover','focusin'])document.addEventListener(type,e=>{const circle=e.target.closest('circle[data-run]');if(circle&&$('#plot-tip'))$('#plot-tip').textContent=circle.querySelector('title').textContent;});
window.addEventListener('beforeunload',e=>{if(formDirty){e.preventDefault();e.returnValue='';}});
async function start(){
  p=await verifySources(p);baseRevision??=await digest(p);chooseDefaults();
  try{const saved=JSON.parse(localStorage.getItem(draftKey));if(saved){await verifySources(saved.project);if(saved.baseRevision===baseRevision){p=validateProject(saved.project);dirty=canonical(p)!==canonical(validateProject(config.project));edits=history(p);chooseDefaults();}else recovery=saved;}}catch{}
  if(p.comparison){candidateA=clone(p.comparison.a);candidateB=clone(p.comparison.b);}
  render();await pollSource();setInterval(pollSource,2500);document.documentElement.dataset.ready='true';
}
void start().catch(e=>{main.innerHTML=`<div class="strip warn"><h1>Open a valid experiment to continue.</h1><p>${esc(e.message)}</p></div>`;notify(e.message,true);});