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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
import {canonical} from './project.mjs';
import {fitProject, plannedAnalysis, confirmationResults, compare} from './analysis.mjs';
import {csv, collectionCSV, bytesFromBase64} from './measurements.mjs';
export const esc = x => String(x ?? '').replace(/[&<>"']/g, c => ({'&': '&', '<': '<', '>': '>', '"': '"', "'": '''}[c]));
export const number = (x, digits = 3) => x === null || x === undefined || !Number.isFinite(x) ? '—' : Math.abs(x) !== 0 && (Math.abs(x) < .001 || Math.abs(x) >= 1e6) ? x.toExponential(2) : x.toLocaleString('en-US', {maximumFractionDigits: digits});
const shortLabel = (value, max) => value.length > max ? value.slice(0, max - 1) + '…' : value;
export const interval = x => x ? `${number(x[0])} to ${number(x[1])}` : 'Not available';
export const settingLabel = (p, settings) => p.factors.map(f => `${f.name}: ${settings[f.id]}${f.unit ? ' ' + f.unit : ''}`).join(' · ');
const palette = ['#087f79', '#c36443', '#7365a7', '#397baf', '#bd8720', '#b85680', '#567c32', '#525d69'];
const range = values => {let min = Math.min(...values), max = Math.max(...values); const margin = (max - min || Math.max(1, Math.abs(max) * .1)) * .12; return [min - margin, max + margin];};
export function chartSVG(p, fit, mode = 'run') {
const measured = new Map(p.measurements.map(m => [m.runId, m]));
const points = mode === 'run' ? p.runs.filter(r => measured.has(r.id)).map(r => ({id: r.id, x: r.order, y: measured.get(r.id).value, block: r.block, excluded: measured.get(r.id).excluded, label: settingLabel(p, r.settings)})) :
fit.ok ? fit.residuals.map(r => ({id: r.runId, x: r.fitted, y: mode === 'residual' ? r.residual : r.measured, block: r.block, review: r.review, label: settingLabel(p, r.settings)})) : [];
const title = mode === 'run' ? 'Measurements in collection order' : mode === 'residual' ? 'Residuals against fitted response' : 'Measured and fitted responses';
const xlabel = mode === 'run' ? 'Run order' : `Fitted ${p.response.name} (${p.response.unit})`;
const ylabel = mode === 'residual' ? `Residual (${p.response.unit})` : `${p.response.name} (${p.response.unit})`;
const height = 355 + Math.ceil(p.design.blocks.length / 3) * 22;
let body = `<rect width="760" height="${height}" fill="#fcfcf8"/><text x="24" y="29" font-size="16" font-weight="650">${esc(title)}</text>`;
if (!points.length) body += '<text x="380" y="177" text-anchor="middle" fill="#677b78" font-size="15">Your measurements will appear here.</text>';
else {
const xr = range(points.map(x => x.x)), yr = range([...points.map(x => x.y), ...(mode === 'residual' ? [0] : [])]);
if (mode === 'run') xr.splice(0, 2, 0, Math.max(...points.map(x => x.x)) + 1);
if (mode === 'fit') {const joint = range(points.flatMap(x => [x.x, x.y])); xr.splice(0, 2, ...joint); yr.splice(0, 2, ...joint);}
const sx = v => 88 + (v - xr[0]) / (xr[1] - xr[0]) * 638, sy = v => 270 - (v - yr[0]) / (yr[1] - yr[0]) * 205;
for (let i = 0; i <= 4; i++) {
const x = mode === 'run' ? 1 + Math.round(i * (xr[1] - 2) / 4) : xr[0] + i * (xr[1] - xr[0]) / 4, y = yr[0] + i * (yr[1] - yr[0]) / 4;
body += `<path d="M88 ${sy(y)}H726" stroke="#e1e8e3"/><text x="77" y="${sy(y) + 4}" text-anchor="end" font-size="13">${esc(number(y, 2))}</text><text x="${sx(x)}" y="291" text-anchor="middle" font-size="13">${esc(number(x, 2))}</text>`;
}
if (mode === 'residual') body += `<path d="M88 ${sy(0)}H726" stroke="#8d9f96" stroke-dasharray="5 4"/>`;
if (mode === 'fit') body += `<path d="M${sx(xr[0])} ${sy(xr[0])}L${sx(xr[1])} ${sy(xr[1])}" stroke="#8d9f96" stroke-dasharray="5 4"/>`;
for (const q of points) {
const color = palette[p.design.blocks.indexOf(q.block) % palette.length];
body += `<circle data-run="${esc(q.id)}" cx="${sx(q.x)}" cy="${sy(q.y)}" r="${q.review ? 6 : 4.5}" fill="${q.excluded ? '#fcfcf8' : color}" stroke="${q.review ? '#b95332' : color}" stroke-width="${q.review ? 2 : 1}" tabindex="0"><title>${esc(q.id)} · ${esc(q.block)} · ${esc(q.label)} · ${number(q.y)}${q.excluded ? ' · excluded: ' + esc(q.excluded) : ''}</title></circle>`;
}
body += `<text x="407" y="321" text-anchor="middle" font-size="13"><title>${esc(xlabel)}</title>${esc(shortLabel(xlabel, 76))}</text><text transform="translate(22 166) rotate(-90)" text-anchor="middle" font-size="13"><title>${esc(ylabel)}</title>${esc(shortLabel(ylabel, 36))}</text>`;
}
p.design.blocks.forEach((block, i) => {const x = 28 + i % 3 * 245, y = 350 + Math.floor(i / 3) * 22; body += `<circle cx="${x}" cy="${y - 4}" r="4" fill="${palette[i % palette.length]}"/><text x="${x + 10}" y="${y}" font-size="13"><title>${esc(block)}</title>${esc(block.length > 28 ? block.slice(0, 25) + '…' : block)}</text>`;});
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 ${height}" role="img" aria-label="${esc(title)}" style="font-family:Arial,sans-serif;fill:#173e39">${body}</svg>`;
}
export function coefficientSVG(fit) {
if (!fit.ok) return '';
const rows = fit.coefficients.filter(c => c.id !== 'intercept'), height = Math.max(180, rows.length * 39 + 100);
const span = range([0, ...rows.flatMap(c => c.ci ?? [c.value])]), sx = v => 290 + (v - span[0]) / (span[1] - span[0]) * 425;
let body = `<rect width="760" height="${height}" fill="#fcfcf8"/><text x="24" y="30" font-size="16" font-weight="650">Model coefficients and ${fit.model.confidence * 100}% intervals</text><path d="M${sx(0)} 48V${height - 45}" stroke="#bdccc1" stroke-dasharray="5 4"/>`;
rows.forEach((c, i) => {const y = 67 + i * 39, label = c.label.length > 35 ? c.label.slice(0, 32) + '…' : c.label;
body += `<text x="24" y="${y + 4}" font-size="13"><title>${esc(c.label)}</title>${esc(label)}</text>${c.ci ? `<path d="M${sx(c.ci[0])} ${y}H${sx(c.ci[1])}" stroke="#087f79" stroke-width="3"/>` : ''}<circle cx="${sx(c.value)}" cy="${y}" r="4.5" fill="#087f79"/>`;
});
for (let i = 0; i <= 4; i++) {const v = span[0] + (span[1] - span[0]) * i / 4; body += `<text x="${sx(v)}" y="${height - 24}" font-size="13" text-anchor="middle">${number(v)}</text>`;}
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 ${height}" role="img" aria-label="Model coefficient intervals" style="font-family:Arial,sans-serif;fill:#173e39">${body}</svg>`;
}
const reportStyle = `@page{size:A4;margin:17mm 15mm}*{box-sizing:border-box}body{font-family:Arial,sans-serif;color:#173e39;font-size:10.5pt;line-height:1.45;margin:0}h1{font-size:30pt;line-height:1.08;letter-spacing:-1pt;margin:8mm 0}h2{font-size:19pt;line-height:1.2;margin:3mm 0 5mm}h3{font-size:12pt;margin:6mm 0 2mm}p{overflow-wrap:anywhere}.eyebrow{font-size:9pt;text-transform:uppercase;letter-spacing:1.5pt;color:#087f79}.subtle{color:#526f67}.page{break-before:page}.page:first-child{break-before:auto}.metrics{display:flex;gap:4mm;margin:7mm 0}.metric{flex:1;background:#eef3ea;padding:4mm}.metric strong{display:block;font-size:21pt}table{width:100%;border-collapse:collapse;font-size:9pt;table-layout:fixed}td,th{padding:2.4mm 1.8mm;border-bottom:1px solid #dbe4db;text-align:left;overflow-wrap:anywhere}th{background:#eef3ea}tr{break-inside:avoid}thead{display:table-header-group}svg{display:block;width:100%;height:auto;break-inside:avoid;margin:4mm 0}.note{padding:4mm;background:#f5eddc;border-left:3px solid #c98934}.hash{font-family:monospace;font-size:8pt;overflow-wrap:anywhere}.procedure li{margin-bottom:2.8mm}a{color:#087f79}.source{break-inside:avoid}footer{font-size:8pt;color:#526f67;margin-top:7mm}h2,h3{break-after:avoid}`;
function table(headers, rows) {return `<table><thead><tr>${headers.map(h => `<th>${esc(h)}</th>`).join('')}</tr></thead><tbody>${rows.map(row => `<tr>${row.map(c => `<td>${esc(c)}</td>`).join('')}</tr>`).join('')}</tbody></table>`;}
export function reportHTML(p, fit = fitProject(p)) {
const planned = plannedAnalysis(p), confidence = p.model.confidence * 100, confirmations = confirmationResults(p);
const sources = p.sources.map(s => `<div class="source"><h3>${esc(s.name)}</h3><p>${esc(s.unit)} · mapped ${esc(s.mapping.runId)} → run id, ${esc(s.mapping.response)} → response</p><p class="hash">SHA-256 ${esc(s.sha256)}</p></div>`).join('');
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${esc(p.title)} — experiment report</title><style>${reportStyle}</style></head><body>
<section class="page"><div class="eyebrow">Signal / Experiment report</div><h1>${esc(p.title)}</h1>${p.evidenceNote?`<p class="note">${esc(p.evidenceNote)}</p>`:''}<p style="font-size:15pt">${esc(p.question)}</p><div class="metrics"><div class="metric"><strong>${p.runs.length}</strong>planned runs</div><div class="metric"><strong>${p.measurements.length}</strong>measured</div><div class="metric"><strong>${fit.n}</strong>in primary fit</div></div><h2>The decision</h2><p>${esc(p.conclusion || 'No conclusion has been recorded. Interpret the measured evidence and confirmation results before deciding what to change.')}</p><h3>Measurement</h3><p>${esc(p.response.name)} (${esc(p.response.unit)}). Goal: ${esc(p.response.goal)}${p.response.goal === 'target' ? ' ' + number(p.response.target) + ' ' + esc(p.response.unit) : ''}.</p><h3>Independent experimental unit</h3><p>${esc(p.protocol.unit)}</p><h3>Planned analysis</h3><p>${esc(p.protocol.analysisPlan)}</p><p class="note">${esc(fit.ok ? fit.assumptions : fit.issue)}</p><footer>Editable source, original CSVs, run sheet, design matrix and a Python reproduction script accompany this report.<strong>Method references</strong><p><a href="https://www.itl.nist.gov/div898/handbook/pri/section3/pri3331.htm">NIST: factorial designs</a> · <a href="https://www.itl.nist.gov/div898/handbook/pri/section3/pri337.htm">center/control scheduling</a> · <a href="https://www.itl.nist.gov/div898/handbook/pri/section4/pri46.htm">confirmation runs</a>. Numerical SVD: ml-matrix 6.15.0; Student-t quantiles: jstat 1.9.6. Full notices included.</p></footer></section>
<section class="page"><div class="eyebrow">01 / Protocol</div><h2>A test someone else can repeat</h2>${table(['Factor', 'Planned levels', 'Unit'], p.factors.map(f => [f.name, f.levels.join(' / '), f.unit || 'category']))}<h3>Run allocation</h3><p>${p.design.replicates} independent repetitions of every combination per complete block. Blocks: ${esc(p.design.blocks.join(', '))}. Seed: ${esc(p.design.seed)}. ${p.design.controls} scheduled controls per block; numeric midpoints and the first categorical level.</p><p>${esc(p.protocol.randomization)}</p><ol class="procedure">${p.protocol.steps.map(s => `<li>${esc(s)}</li>`).join('')}</ol><p>${esc(p.protocol.notes)}</p><p class="subtle">${p.approved ? 'Protocol approved and locked.' : 'Protocol not yet approved.'} Planned model rank ${planned.rank}/${planned.parameters}; ${planned.df} residual degrees of freedom if every training run is measured.</p></section>
<section class="page"><div class="eyebrow">02 / Observations</div><h2>Keep the evidence visible</h2>${chartSVG(p, fit, 'run')}<p>Hollow points are excluded with recorded reasons; all originals remain in the delivery. Colors identify the declared blocks.</p><h3>Collection status</h3><p>${fit.pending} pending · ${fit.excluded} excluded · ${fit.confirmation} held-out confirmation measurements.</p>${table(['Run', p.response.name + ' (' + p.response.unit + ')', 'Source / reason'], p.measurements.slice(0, 8).map(m => [m.runId, number(m.value), m.excluded || (m.origin.kind === 'csv' ? m.origin.source + ', line ' + m.origin.row : 'Direct entry')]))}<p class="subtle">${p.measurements.length > 8 ? 'First eight measurements shown here. ' : ''}The complete measurements.csv and source files contain every recorded row.</p></section>
<section class="page"><div class="eyebrow">03 / Analysis</div><h2>What the measurements support</h2>${fit.ok ? `<div class="metrics"><div class="metric"><strong>${number(fit.rmse)}</strong>residual SD (${esc(p.response.unit)})</div><div class="metric"><strong>${fit.df}</strong>residual df</div><div class="metric"><strong>${number(fit.looRMSE)}</strong>leave-one-out RMSE</div></div>${table(['Term', 'Coefficient', confidence + '% interval'], fit.coefficients.map(c => [c.label, number(c.value), interval(c.ci)]))}<p>Numeric factors are coded −1 at the lowest planned level and +1 at the highest; category effects use the first level as reference. Coefficients use these coded units. Intervals are pointwise and model dependent.</p>${coefficientSVG(fit)}` : `<p class="note">${esc(fit.issue)}</p>`}</section>
${fit.ok ? `<section class="page"><div class="eyebrow">04 / Diagnostics</div><h2>Check what the model has missed</h2>${chartSVG(p, fit, 'residual')}<p>Review curvature, changing residual spread and run-order patterns. Outlined points cross a leverage or influence review threshold; they remain in the fit.</p>${fit.warnings.map(w => `<p class="note">${esc(w)}</p>`).join('')}${fit.residuals.some(r => r.review) ? table(['Run', 'Residual', 'Leverage', 'Cook’s distance'], fit.residuals.filter(r => r.review).slice(0, 8).map(r => [r.runId, number(r.residual), number(r.leverage), number(r.cook)])) : '<p>No observations cross the displayed review thresholds.</p>'}<p class="subtle">Leverage > 2p/n or Cook’s distance > 4/n prompts review, not automatic deletion. At most eight flagged rows are listed here; analysis.json retains every diagnostic. A favorable diagnostic does not establish the experimental assumptions.</p></section>` : ''}
<section class="page"><div class="eyebrow">05 / Follow-up and provenance</div><h2>Test the prediction with new runs</h2>${confirmations.length ? confirmations.map(c => `<h3>${esc(c.phase)} · ${esc(c.prediction.block)}</h3><p>${esc(settingLabel(p, c.prediction.settings))}</p>${table(['Frozen prediction', 'New measurements', 'Actual minus predicted'], [[number(c.prediction.mean) + ' · mean CI ' + interval(c.prediction.meanCI), c.n + '/' + c.planned + ' measured · mean ' + number(c.mean) + ' · own CI ' + interval(c.ci), number(c.difference)]])}<p class="subtle">Original interval for one new observation: ${interval(c.prediction.predictionCI)}. The observed mean’s interval uses only the new repetitions. It is not a pass/fail test.</p>`).join('') : '<p>No confirmation phase yet. Compare settings, freeze the prediction and collect fresh independent runs before treating a candidate as established.</p>'}<h2>Original files</h2>${sources || '<p>No CSV files imported. Direct measurements are recorded in the change log.</p>'}<h3>Change log</h3><p>${p.audit.length} changes preserved in project.signal.json and audit.json, including model changes, corrections and exclusions.</p></section>
</body></html>`;
}
export function runSheetHTML(p) {
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${esc(p.title)} — collection sheet</title><style>${reportStyle}@page{size:A4 landscape;margin:14mm}td{height:11mm}table{font-size:9pt}h1{font-size:23pt}</style></head><body><div class="eyebrow">Signal / Collection sheet</div><h1>${esc(p.title)}</h1><p>${esc(p.response.name)} in ${esc(p.response.unit)} · one result per ${esc(p.protocol.unit)} · seed ${esc(p.design.seed)}</p>${table(['Run / order', 'Phase / block', ...p.factors.map(f => f.name + (f.unit ? ' (' + f.unit + ')' : '')), p.response.name + ' (' + p.response.unit + ')', 'Notes / departure'], p.runs.map(r => [r.id + ' / ' + r.order, r.phase + ' / ' + r.block + (r.kind === 'control' ? ' · control' : ''), ...p.factors.map(f => r.settings[f.id]), '', '']))}<footer>Keep the run ids when importing measurements. Leave unmeasured responses blank. Do not enter predicted values as measured results.</footer></body></html>`;
}
export function kitFiles(p, html, assets) {
const fit = fitProject(p), files = {
'experiment.html': html, 'project.signal.json': JSON.stringify(p, null, 2) + '\n',
'collection.csv': collectionCSV(p), 'measurements.csv': collectionCSV(p, {blank: false}),
'report.html': reportHTML(p, fit), 'collection-sheet.html': runSheetHTML(p),
'analysis.json': JSON.stringify(fit, null, 2) + '\n', 'confirmations.json': JSON.stringify(confirmationResults(p), null, 2) + '\n',
'audit.json': JSON.stringify(p.audit, null, 2) + '\n',
'design-matrix.csv': csv([['run_id', ...fit.columns.map(c => c.id), 'measured_response'], ...fit.matrix.X.map((row, i) => [fit.matrix.runIds[i], ...row, fit.matrix.y[i]])]),
'charts/collection.svg': chartSVG(p, fit, 'run'), 'charts/residuals.svg': chartSVG(p, fit, 'residual'),
'reproduce.py': assets.reproduce, 'requirements.txt': assets.requirements, 'THIRD_PARTY_LICENSES.txt': assets.licenses,
'README.txt': `SIGNAL — ${p.title}\n\nOpen experiment.html in a modern browser to edit, inspect and continue collecting offline. Open project.signal.json to retain the entire source and original inputs. The studio does not invent missing responses.\n\nPrint collection-sheet.html at actual size, or fill collection.csv without changing run ids. Blank responses are pending. Measurements and corrections remain in the project and audit.json; original CSV bytes are in sources/.\n\nThe report describes the model and assumptions. Numeric settings use planned-range coding, categorical terms use the first level as reference and blocks are fixed effects. Confirmation runs remain outside the training fit. A prediction interval describes one new observation; a mean confidence interval describes the model mean. These are pointwise intervals, not a guarantee of an optimum.\n\nTo independently repeat the fitted calculations, use Python 3.9–3.12, install requirements.txt into an isolated environment, and run python reproduce.py. The script reads the exact delivered matrix and writes reproduction.json. No Python is required for the browser studio.\n\nOriginal implementation and Signal identity: OpenHarness contributors, MIT. Numerical library notices are included.\n`,
'LICENSE.txt': assets.license,
};
if (fit.ok) {files['charts/coefficients.svg'] = coefficientSVG(fit); files['charts/measured-fitted.svg'] = chartSVG(p, fit, 'fit');}
if (fit.ok && p.comparison) files['comparison.json'] = JSON.stringify(compare(p, fit, p.comparison.a, p.comparison.b), null, 2) + '\n';
for (const source of p.sources) files['sources/' + source.id + '.csv'] = bytesFromBase64(source.base64);
for (const phase of p.phases.filter(x => x.kind !== 'plan')) files['followup/' + phase.id + '.csv'] = collectionCSV(p, {phase: phase.id});
if (fit.excluded) files['sensitivity-all-recorded.json'] = JSON.stringify(fitProject(p, {includeExcluded: true}), null, 2) + '\n';
return files;
}