In this section
- Star Electron Star — App render · star-electron-star / app.mjs lines 701–819
- Chemistry storage · star-maker / machinery/bench/chemistry.mjs lines 1–91
- Controlpad storage · star-maker / machinery/bench/controlpad.mjs lines 1–137
- Electron storage · star-maker / machinery/bench/electron.mjs lines 1–85
- Elements storage · star-maker / machinery/bench/elements.mjs lines 1–77
- Machinery — Bench Page render · star-maker / machinery/bench/index.html lines 1–124
Star Electron Star — App
A JavaScript module that draws lines meta and families, using SHA-256. It indexes key (`indexOfKey`), builds gl (`buildGL`) and draws marks (`drawMarks`).
Set aside from the main view: 100% of its lines are the same as testcode/wafer-development-environment/202609180205-underground/app.mjs (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 99% of lines shared with Wafer Development Environment — Underground; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.9969 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/wafer-development-environment/202609180205-underground/app.mjs:1-819 bcc8e85757d77b987a91d4648eb4678d64955df3
- sha256 bab91935fea7253f0180339046167376c98b3cdb562abd1b8da971e8c7ec229d
- target sha256 3db6d324516a7300426776716b840149de9e5e16f84e19e45e68ab2c5bd745bd
- group of 4 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
renderstar-electron-star / app.mjs · lines 701–819 of 819 (continued from section 1558) · Not reached from any entry point (candidate for review) · pattern keplerTargets (shared by 5 files)
- What it does
- It draws lines meta and families. Defines 50 functions or classes, including $, indexOfKey, bin, tier1, tier2. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- README: "`index.html`, `app.mjs`, `lib.mjs`, `pick.mjs`, `read.mjs`, `style.css`, `line-index.json`, `proof/` — the Line Wafer, unchanged apart from the title and two script tags."
- Inputs & outputs
- In: JSON file all-lines.meta.json; JSON file families.json; JSON file line-index.json. Out: WebGL/WebGPU drawing.
- What it achieves
- The Line Wafer. It responds to click, pointerdown and pointermove events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- star-electron-star · / · JavaScript module
- Uses
- Galaxies Wafers — Lib (import), Pick (import), Read (import)
- Used by
- none found
- Produces
- $, indexOfKey, bin, tier1, tier2, compile, initGL, fallback2d, buildGL, put, resize, ensureOverlay
- Defines here
- gestures, up, readURL, refuse, writeURL
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- star-electron-star@241bcca9eb4045e9be5c058ec24f9f5bd26c7af4 app.mjs:701-819 · blob dd07c5af4a56dddc780fc3648dd4cd007ab026a9 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: duplicate_candidate
/* ── gestures ────────────────────────────────────────────────────────────── */
function gestures() {
let down = null, moved = 0, pinch = null;
const pts = new Map();
stage.addEventListener('pointerdown', e => {
stage.setPointerCapture(e.pointerId);
pts.set(e.pointerId, [e.clientX, e.clientY]);
if (pts.size === 1) { down = [e.clientX, e.clientY]; moved = 0; }
if (pts.size === 2) {
const [p, q] = [...pts.values()];
pinch = { d: Math.hypot(p[0] - q[0], p[1] - q[1]), z: view.zoom };
}
});
stage.addEventListener('pointermove', e => {
if (!pts.has(e.pointerId)) return;
const prev = pts.get(e.pointerId);
pts.set(e.pointerId, [e.clientX, e.clientY]);
if (pts.size === 2 && pinch) {
const [p, q] = [...pts.values()];
const d = Math.hypot(p[0] - q[0], p[1] - q[1]);
if (pinch.d > 0) view.zoom = Math.max(0.02, Math.min(4000, pinch.z * (d / pinch.d)));
draw(); return;
}
if (pts.size === 1) {
const dx = e.clientX - prev[0], dy = e.clientY - prev[1];
moved += Math.abs(dx) + Math.abs(dy);
view.x -= dx / view.zoom; view.y += dy / view.zoom;
draw();
}
});
const up = e => {
if (pts.size === 1 && down && moved < 7) {
const key = nearestKeyAt(e.clientX, e.clientY);
if (key >= 0) { view.focus = key; paintPanel(key); view.link = null; draw(); }
}
pts.delete(e.pointerId);
if (pts.size < 2) pinch = null;
if (pts.size === 0) down = null;
};
stage.addEventListener('pointerup', up);
stage.addEventListener('pointercancel', e => { pts.delete(e.pointerId); pinch = null; down = null; });
stage.addEventListener('wheel', e => {
e.preventDefault();
const f = Math.exp(-e.deltaY * 0.0016);
view.zoom = Math.max(0.02, Math.min(4000, view.zoom * f));
draw();
}, { passive: false });
stage.addEventListener('dblclick', () => { view.focus = -1; view.link = null; $('panel').hidden = true; home(); });
}
/* ── URL state: the whole of it, in permanent numbers ────────────────────── */
function readURL() {
const q = new URLSearchParams(location.search);
const pa = parseKey(q.get('line') ?? ''), pb = parseKey(q.get('to') ?? '');
if (!pa.ok) { if (q.get('line')) refuse(`The link carried a line number this page cannot use: ${pa.why}.`); return; }
$('a').value = String(pa.key);
const rawTo = q.get('to');
if (pb.ok) { $('b').value = String(pb.key); view.link = [pa.key, pb.key]; connect(pa.key, pb.key); }
else if (rawTo !== null && rawTo.trim() !== '') {
/* focus stays unset: tier 2 repaints the panel for a focused key when it
lands, which would silently replace this refusal with an ordinary card. */
refuse(`The link asked to connect to "${rawTo}", which is not a line number: ${pb.why}. `
+ `Line ${pa.key} is where the beam is pointing.`);
flyTo(pa.key);
}
else { view.focus = pa.key; paintPanel(pa.key); flyTo(pa.key); }
}
/* One refusal path, so a bad number is always visible rather than ignored. */
function refuse(sentence) {
$('panelbody').replaceChildren();
const h = document.createElement('h2'); h.textContent = 'Refused';
const p2 = document.createElement('p'); p2.className = 'refuse'; p2.textContent = sentence;
$('panelbody').append(h, p2);
$('panel').hidden = false;
}
function writeURL(a, b) {
const q = new URLSearchParams();
if (a) q.set('line', String(a));
if (b) q.set('to', String(b));
history.replaceState(null, '', q.toString() ? '?' + q : location.pathname);
}
/* ── start ───────────────────────────────────────────────────────────────── */
(async function start() {
try {
await tier1();
} catch (e) {
$('count').textContent = 'Could not load the numbered database: ' + e.message
+ '. Check the internet connection and reload.';
return;
}
resize();
try { initGL(); } catch (e) {
ctx2d = stage.getContext('2d');
$('hint').textContent = 'GPU not available: drawn without animation';
}
home();
gestures();
window.addEventListener('resize', () => { resize(); draw(); });
$('beam').addEventListener('submit', e => {
e.preventDefault();
const pa = parseKey($('a').value), pb = parseKey($('b').value);
if (!pa.ok) { refuse(`That is not a line number: ${pa.why}.`); return; }
if ($('b').value.trim() && !pb.ok) { refuse(`Second number: ${pb.why}.`); return; }
if (pb.ok) { view.focus = -1; connect(pa.key, pb.key); writeURL(pa.key, pb.key); }
else { view.focus = pa.key; view.link = null; paintPanel(pa.key); flyTo(pa.key); writeURL(pa.key, null); }
document.activeElement?.blur();
});
$('close').addEventListener('click', () => { $('panel').hidden = true; view.focus = -1; view.link = null; draw(); });
readURL();
tier2().catch(e => { $('prov').textContent = 'family index unavailable: ' + e.message; });
})();Chemistry
A JavaScript module in the bench folder of Star Maker that reads table and compounds.
storagestar-maker / machinery/bench/chemistry.mjs · lines 1–91 of 91 · Not reached from any entry point (candidate for review) · pattern formulaOf (shared by 2 files)
- What it does
- It loads table and compounds. Defines term, formulaOf, decayOf, node. Uses libraries node:fs/promises, node:path. Side effects: reads or writes files.
- Inputs & outputs
- In: JSON file table.json. Out: JSON file compounds.json; JSON file graph.json.
- What it achieves
- It is built from the term step (`term`), the formula of helper (`formulaOf`) and the decay of helper (`decayOf`). THE CHEMISTRY STAR — computes compounds from the elements.
- Why it matters
- No other file in the estate was found to import it.
- Application
- star-maker · machinery/bench · JavaScript module
- Uses
- node:fs/promises, node:path
- Used by
- none found
- Produces
- term, formulaOf, decayOf, node
- Defines here
- term, formulaOf, decayOf, node
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- star-maker@2c477b0cc673304c5b288cee9d0e0ae42d273b2e machinery/bench/chemistry.mjs:1-91 · blob ae09b451ad0a700c886ed659eced1ffb9895671b · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unreached_review
// THE CHEMISTRY STAR — computes compounds from the elements. Every star in the sky is a
// molecule: the elements (cartridge versions, the deep-link contract, the shell) it was composed
// from. Its verdict is the compound's stability. Across thousands of stars the reactions emerge:
// which element pairs are stable, which decay, and what the decay product is (the exception).
// All of it is written as a graph the Spider can load. No model — arithmetic over the sky.
//
// node chemistry.mjs → star-maker/chemistry/{compounds.json, graph.json}, CHEMISTRY.md
import { readFile, readdir, writeFile, mkdir } from 'node:fs/promises';
import path from 'node:path';
const SKY = process.env.SKY_DIR || 'C:/Users/vikra/Documents/GitHub/star-maker';
const OUT = path.join(SKY, 'chemistry');
await mkdir(OUT, { recursive: true });
const table = JSON.parse(await readFile(path.join(SKY, 'elements', 'table.json'), 'utf8')).elements;
const symbolOf = new Map(table.filter(e => e.family === 'cartridge').map(e => [e.name, e.symbol]));
const contractSym = table.find(e => e.key === 'contract:deeplink')?.symbol || 'Dl';
const files = (await readdir(path.join(SKY, 'stars'))).filter(f => f.endsWith('.json'));
const stars = [];
for (const f of files) { try { stars.push(JSON.parse(await readFile(path.join(SKY, 'stars', f), 'utf8'))); } catch {} }
// formula: one term per element present. A cartridge term is Symbol(version stamp); absence = shell original in that slot.
const term = (id, sel) => `${symbolOf.get(id) || id}${sel ? '(' + String(sel).slice(0, 12) + ')' : ''}`;
const formulaOf = s => {
const on = (s.loaded || []).map(id => term(id, s.seed.choice.selected?.[id]));
if (s.seed.kind === 'deeplink') on.push(contractSym);
return on.sort().join('·') || 'Shell';
};
const decayOf = s => (s.findings || []).filter(f => f.level === 'exception' || f.level === 'arrival').map(f => `${f.part}: ${f.text}`.slice(0, 120));
const compounds = new Map();
for (const s of stars) {
const formula = formulaOf(s);
const c = compounds.get(formula) || compounds.set(formula, { formula, kind: s.seed.kind, stars: 0, green: 0, amber: 0, red: 0, decays: new Map(), ids: [] }).get(formula);
c.stars++; c[s.verdict.toLowerCase()] = (c[s.verdict.toLowerCase()] || 0) + 1; if (c.ids.length < 5) c.ids.push(s.id);
for (const d of decayOf(s)) c.decays.set(d, (c.decays.get(d) || 0) + 1);
}
const list = [...compounds.values()].map(c => ({ ...c, stability: c.stars ? c.green / c.stars : 0, decays: [...c.decays].sort((a, b) => b[1] - a[1]).slice(0, 3).map(([text, n]) => ({ text, n })) }))
.sort((a, b) => a.stability - b.stability || b.stars - a.stars);
// reactions between element versions: for constellation stars, which pair decays and why
const pairs = new Map();
for (const s of stars.filter(s => s.seed.kind === 'constellation' || s.seed.kind === 'unplug')) {
const key = s.seed.kind === 'unplug' ? `without ${Object.keys(s.seed.choice.enabled).map(id => symbolOf.get(id) || id).sort().join('+')}` : formulaOf(s);
const p = pairs.get(key) || pairs.set(key, { key, kind: s.seed.kind, stars: 0, red: 0, decays: new Map() }).get(key);
p.stars++; if (s.verdict === 'RED') p.red++;
for (const d of decayOf(s)) p.decays.set(d, (p.decays.get(d) || 0) + 1);
}
// element-level rules: for each cartridge version (element term), how often does it appear in a RED compound?
const termStats = new Map();
for (const s of stars) for (const t of formulaOf(s).split('·')) { const x = termStats.get(t) || termStats.set(t, { term: t, stars: 0, red: 0, decays: new Map() }).get(t); x.stars++; if (s.verdict === 'RED') { x.red++; for (const d of decayOf(s)) x.decays.set(d, (x.decays.get(d) || 0) + 1); } }
const unstableTerms = [...termStats.values()].filter(x => x.stars >= 3 && x.red / x.stars >= 0.9).sort((a, b) => b.stars - a.stars);
const nobleTerms = [...termStats.values()].filter(x => x.stars >= 3 && x.red === 0).sort((a, b) => b.stars - a.stars);
// graph for the Spider: element-version nodes; UNSTABLE_WITH edges between terms that co-occur in red compounds; DECAYS_TO edges to the exception text
const nodes = [], edges = [], seen = new Set();
const node = (label, type, rag, reason) => { if (!seen.has(label)) { seen.add(label); nodes.push({ label, type, rag, reason }); } };
for (const x of [...unstableTerms.slice(0, 80), ...nobleTerms.slice(0, 40)]) node(x.term, 'element', x.red / x.stars >= 0.9 ? 'red' : 'green', `${x.stars} compounds · ${x.red} red`);
for (const c of list.filter(c => c.red && c.formula.includes('·')).slice(0, 300)) {
const terms = c.formula.split('·'); const bad = terms.filter(t => termStats.get(t) && termStats.get(t).red / termStats.get(t).stars < 0.9);
for (const t of terms) node(t, 'element', termStats.get(t).red / termStats.get(t).stars >= 0.9 ? 'red' : 'amber', `${termStats.get(t).stars} compounds · ${termStats.get(t).red} red`);
for (let i = 0; i < terms.length; i++) for (let j = i + 1; j < terms.length; j++) if (bad.includes(terms[i]) && bad.includes(terms[j])) edges.push({ from: terms[i], to: terms[j], kind: 'UNSTABLE_WITH' });
for (const d of c.decays.slice(0, 1)) { node(d.text, 'decay', 'red', `${d.n} stars`); for (const t of terms) edges.push({ from: t, to: d.text, kind: 'DECAYS_TO' }); }
}
await writeFile(path.join(OUT, 'compounds.json'), JSON.stringify({ generated_utc: new Date().toISOString(), stars: stars.length, compounds: list }, null, 2));
await writeFile(path.join(OUT, 'graph.json'), JSON.stringify({ schema: 'chemistry-graph.v1', label: 'The Chemistry star', generated_utc: new Date().toISOString(),
note: 'Elements (cartridge versions, the contract) as nodes; UNSTABLE_WITH between elements that only decay together; DECAYS_TO the exception a compound produces.', focus_default: nodes[0]?.label, nodes, edges }, null, 2));
const md = `# The Chemistry star — ${list.length} compounds from ${stars.length} stars
A compound is a composition of elements (cartridge versions by symbol and stamp; **${contractSym}** = the deep-link contract; **Shell** = nothing bolted on). Stability = share of its stars that were GREEN. Decay = the exception the compound produces. Updated ${new Date().toISOString()}. No model — arithmetic over the sky.
Symbols: ${[...symbolOf].map(([n, s]) => `**${s}** ${n}`).join(' · ')}
## Noble elements (never in a red compound, ≥ 3 compounds)
${nobleTerms.slice(0, 15).map(x => `- **${x.term}** — ${x.stars} compounds, all stable`).join('\n') || '- none yet'}
## Radioactive elements (red in ≥ 90 % of their compounds)
${unstableTerms.slice(0, 25).map(x => `- **${x.term}** — ${x.red}/${x.stars} red · decays to: ${[...x.decays].sort((a, b) => b[1] - a[1]).slice(0, 2).map(([t]) => `\`${t.slice(0, 80)}\``).join(' / ')}`).join('\n') || '- none'}
## Reactions that decay (unplug one element, another dies)
${[...pairs.values()].filter(p => p.kind === 'unplug' && p.red).map(p => `- **${p.key}** → ${p.red}/${p.stars} red · ${[...p.decays].sort((a, b) => b[1] - a[1]).slice(0, 2).map(([t, n]) => `\`${t.slice(0, 90)}\` ×${n}`).join(' · ')}`).join('\n') || '- none'}
## Least stable compounds
${list.filter(c => c.stars >= 1 && c.red).slice(0, 30).map(c => `- \`${c.formula}\` — ${Math.round(100 * c.stability)} % stable (${c.red} red / ${c.stars}) · ${c.decays[0] ? '`' + c.decays[0].text.slice(0, 90) + '`' : ''}`).join('\n') || '- none'}
## For the Spider
\`chemistry/graph.json\` — ${nodes.length} nodes, ${edges.length} edges, receiver idiom.
`;
await writeFile(path.join(SKY, 'CHEMISTRY.md'), md);
console.log(`chemistry: ${stars.length} stars → ${list.length} compounds · ${nobleTerms.length} noble · ${unstableTerms.length} radioactive · graph ${nodes.length}/${edges.length}`);Controlpad
A JavaScript module in the bench folder of Star Maker that fetches controlpad seen. It saves seen (`saveSeen`), parses note (`parseNote`) and appends file (`appendFile`).
storagestar-maker / machinery/bench/controlpad.mjs · lines 1–137 of 137 · Not reached from any entry point (candidate for review) · pattern bench (shared by 3 files)
- What it does
- It fetches controlpad seen. Defines 11 functions or classes, including git, stamp, log, saveSeen, parseNote. Uses libraries node:fs/promises, node:child_process, node:util, node:crypto, node:url. Side effects: reads or writes files; makes network requests; starts processes.
- Inputs & outputs
- In: JSON file controlpad-seen.json.
- What it achieves
- Control-pad watcher — the steering wheel for the Ventus OS Bench.
- Why it matters
- No other file in the estate was found to import it.
- Application
- star-maker · machinery/bench · JavaScript module
- Uses
- node:fs/promises, node:child_process, node:util, node:crypto, node:url, node:path
- Used by
- none found
- Produces
- git, stamp, log, saveSeen, parseNote, coerce, bench, execute, appendFile, writeState, cycle
- Defines here
- git, stamp, log, saveSeen, parseNote, coerce, bench, execute, appendFile, writeState, cycle
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- star-maker@2c477b0cc673304c5b288cee9d0e0ae42d273b2e machinery/bench/controlpad.mjs:1-137 · blob 60614430c309fb0d9cf5ead749c01c306762e907 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: unknown · users: none · canonical: unreached_review
// control-pad watcher — the steering wheel for the Ventus OS Bench.
//
// Every POLL_MS: git pull the pad, find inbox notes not yet seen, execute orders against the
// Bench API (drive / reset), queue prose for agents, write outbox results + STATE.md, push.
// Runs beside server.mjs (the Bench) on the MSI. node controlpad.mjs
import { readFile, readdir, writeFile, mkdir, copyFile } from 'node:fs/promises';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
const run = promisify(execFile);
const PAD = process.env.PAD_DIR || 'C:/Users/vikra/Documents/GitHub/control-pad';
const BENCH_URL = 'http://127.0.0.1:8790';
const BENCH = path.dirname(fileURLToPath(import.meta.url));
const SEEN_FILE = path.join(BENCH, 'state', 'controlpad-seen.json');
const POLL_MS = Number(process.env.PAD_POLL_MS || 20000);
const HOST = 'MSI · RTX 5070 Ti';
const git = (...a) => run('git', ['-C', PAD, ...a], { maxBuffer: 1 << 24 });
const stamp = () => new Date().toISOString().replace(/[-:]/g, '').replace(/T/, '-').slice(0, 15);
const log = m => console.log(`${new Date().toISOString()} ${m}`);
let seen = {};
try { seen = JSON.parse(await readFile(SEEN_FILE, 'utf8')); } catch {}
const saveSeen = () => writeFile(SEEN_FILE, JSON.stringify(seen, null, 2));
// tiny front-matter parser: `key: value` and `key:` with indented `sub: value` lines
function parseNote(text) {
const m = text.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
if (!m) return { order: null, meta: {}, body: text.trim() };
const meta = {}; let cur = null;
for (const raw of m[1].split(/\r?\n/)) {
if (!raw.trim() || raw.trim().startsWith('#')) continue;
const top = raw.match(/^(\w[\w-]*):\s*(.*)$/), sub = raw.match(/^\s+([\w.\-]+):\s*(.*)$/);
if (top) { cur = top[1]; meta[cur] = top[2] === '' ? {} : coerce(top[2]); }
else if (sub && cur && typeof meta[cur] === 'object') meta[cur][sub[1]] = coerce(sub[2]);
}
return { order: meta.order || null, meta, body: m[2].trim() };
}
const coerce = v => v === 'true' ? true : v === 'false' ? false : v.replace(/^["']|["']$/g, '');
async function bench(pathname, body) {
const r = await fetch(BENCH_URL + pathname, body ? { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) } : {});
if (!r.ok) throw new Error(`bench ${pathname} HTTP ${r.status}`);
return r.json();
}
async function execute(note) {
const { order, meta, body } = parseNote(note.text);
const slug = note.name.replace(/^\d{12}-/, '').replace(/\.md$/, '');
if (!order) {
await appendFile(path.join(PAD, 'outbox', 'QUEUE-FOR-AGENTS.md'), `\n## ${note.name}\n\n${body}\n`);
return { kind: 'prose', summary: 'queued for agents' };
}
if (order === 'reset') { await bench('/api/reset'); return { kind: 'reset', summary: 'bench reset to live composition' }; }
if (order === 'drive') {
await bench('/api/choice', { enabled: meta.enabled || {}, selected: meta.selected || {} });
const r = await bench('/api/testdrive', {});
const out = `${stamp()}-drive-${slug}`;
await copyFile(path.join(BENCH, r.screenshot), path.join(PAD, 'outbox', `${out}.jpg`));
const parts = Object.entries(r.health).filter(([, h]) => h.findings || ['red', 'amber'].includes(h.colour));
const md = `# ${r.verdict} · drive · ${slug}
Order: \`inbox/${note.name}\` — *${body.split('\n')[0] || '(no text)'}*
Composition: \`${r.composition.generation}\` · loaded: ${r.composition.order.join(', ') || 'shell only'}
${r.composition.cartridges.filter(c => c.swapped_from).map(c => `Swapped: **${c.id}** → \`${c.file}\` (was \`${c.swapped_from}\`)`).join('\n')}
Load ${r.loadMs} ms · router ${r.probe.router} · layers ${r.probe.layers?.ok ?? '?'} OK / ${r.probe.layers?.wait ?? '?'} WAIT · canvases ${r.probe.canvases ?? '?'}
## Health
${Object.entries(r.health).map(([id, h]) => `- ${h.colour === 'red' ? '🔴' : h.colour === 'amber' ? '🟡' : '🟢'} **${id}** (${h.findings})`).join('\n')}
## Findings
${r.findings.length ? r.findings.slice(0, 20).map(f => `- [${f.level}] **${f.part}**: ${f.text}${f.line != null ? ` (L${f.line})` : ''}`).join('\n') : '- none'}
${r.probe.banners?.length ? '\n## Banners\n' + r.probe.banners.map(b => `- ${b}`).join('\n') : ''}

_${HOST} · bench run ${r.stamp}_
`;
await writeFile(path.join(PAD, 'outbox', `${out}.md`), md);
return { kind: 'drive', summary: `${r.verdict} — ${r.findings.length} findings → outbox/${out}.md`, verdict: r.verdict };
}
if (order === 'promote') {
await appendFile(path.join(PAD, 'outbox', 'QUEUE-FOR-AGENTS.md'), `\n## ${note.name} — PROMOTE requested, needs the architect's explicit go in a session\n\n${body}\n`);
return { kind: 'promote', summary: 'promotion never runs unattended — queued for a session' };
}
return { kind: 'unknown', summary: `unknown order "${order}" — queued for agents` };
}
async function appendFile(file, text) { let cur = ''; try { cur = await readFile(file, 'utf8'); } catch {} await writeFile(file, cur + text); }
async function writeState(recent) {
let alive = false, runs = [];
try { runs = await bench('/api/runs'); alive = true; } catch {}
const md = `# STATE — written by the machine, do not edit
Host: ${HOST} · Bench: ${alive ? 'ALIVE at ' + BENCH_URL : 'NOT RUNNING'} · updated ${new Date().toISOString()}
## Last notes handled
${recent.length ? recent.map(r => `- \`${r.name}\` → ${r.summary}`).join('\n') : '- none this cycle'}
## Recent bench runs
${runs.slice(0, 10).map(r => `- ${r.stamp} **${r.verdict}** ${r.loadMs} ms · ${r.cartridges.map(c => c.id + (c.swapped_from ? '⇄' : '')).join(', ') || 'shell only'}`).join('\n') || '- none'}
`;
await writeFile(path.join(PAD, 'STATE.md'), md);
}
async function cycle() {
await git('pull', '--ff-only', '--quiet').catch(e => log('pull failed: ' + e.message));
const files = (await readdir(path.join(PAD, 'inbox'))).filter(f => /^\d{12}-.*\.md$/.test(f)).sort();
const handled = [];
for (const name of files) {
const text = await readFile(path.join(PAD, 'inbox', name), 'utf8');
const sha = createHash('sha1').update(text).digest('hex');
if (seen[name] === sha) continue;
log(`note ${name}`);
let result;
try { result = await execute({ name, text }); } catch (e) { result = { kind: 'error', summary: 'error: ' + e.message }; }
seen[name] = sha; await saveSeen();
handled.push({ name, ...result });
log(` → ${result.summary}`);
}
if (!handled.length && process.env.PAD_STATE_EVERY_CYCLE !== '1') return;
await writeState(handled);
await git('add', '--', 'outbox', 'STATE.md');
const msg = handled.length ? `pad: ${handled.map(h => `${h.name.replace(/\.md$/, '')} → ${h.kind}${h.verdict ? ' ' + h.verdict : ''}`).join('; ')}` : 'pad: state';
const status = (await git('status', '--porcelain')).stdout.trim();
if (!status) return;
await git('commit', '-q', '-m', msg + '\n\nCo-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>');
await git('push', '--quiet').catch(e => log('push failed: ' + e.message));
log(`pushed: ${msg}`);
}
log(`watching ${PAD} every ${POLL_MS / 1000}s`);
for (;;) { try { await cycle(); } catch (e) { log('cycle error: ' + e.message); } await new Promise(r => setTimeout(r, POLL_MS)); }Electron
A JavaScript module in the bench folder of Star Maker. It is built from the label step (`label`).
storagestar-maker / machinery/bench/electron.mjs · lines 1–85 of 85 · Not reached from any entry point (candidate for review) · pattern label (shared by 95 files)
- What it does
- It loads data. Defines label, by. Uses libraries node:fs/promises, node:url, node:path. Side effects: reads or writes files.
- Inputs & outputs
- Out: JSON file atoms.json; JSON file graph.json.
- What it achieves
- THE ELECTRON STAR — electron physics applied to code, where the physics actually holds. nucleus = a soul (a unit of code) · electrons = its callers · shells `K/L/M` = same directory / same repo / other repo.
- Why it matters
- No other file in the estate was found to import it.
- Application
- star-maker · machinery/bench · JavaScript module
- Uses
- node:fs/promises, node:url, node:path
- Used by
- none found
- Produces
- label, by
- Defines here
- label, by
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- star-maker@2c477b0cc673304c5b288cee9d0e0ae42d273b2e machinery/bench/electron.mjs:1-85 · blob 03f09fcd866f88b64d5d7303dc274594e67358cd · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unreached_review
// THE ELECTRON STAR — electron physics applied to code, where the physics actually holds.
// nucleus = a soul (a unit of code) · electrons = its callers · shells K/L/M = same directory /
// same repo / other repo, filled inner-first · valence = the M shell, which decides bonding ·
// noble = full outer shell, inert (no external caller) · alkali = one lone valence electron
// (one external caller — reactive, fragile) · conduction band = free electrons across many
// repos (the estate's wiring) · spin pairing = a caller in a test/proof file · tunnelling = a
// caller in a repo that holds no copy of the soul (the hidden wire). No model.
//
// node electron.mjs → star-maker/electron/{atoms.json, graph.json}, ELECTRON.md (reads bench/state/soul/souls.jsonl)
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
const BENCH = path.dirname(fileURLToPath(import.meta.url));
const SKY = process.env.SKY_DIR || 'C:/Users/vikra/Documents/GitHub/star-maker';
const OUT = path.join(SKY, 'electron');
await mkdir(OUT, { recursive: true });
const rows = (await readFile(path.join(BENCH, 'state', 'soul', 'souls.jsonl'), 'utf8')).split('\n').filter(Boolean).map(l => JSON.parse(l));
const BUILTIN = /^(slice|round|open|has|get|set|add|next|range|len|print|int|str|list|dict|main|init|run|render|update|log|load|save|build|parse|draw|fetch|then|end|write|read|close|start|stop|send|on|off|once|error|warn|info|debug|format|now|time|sleep|exit|entries|keys|values|contains|closest|failed|code|head|calc)$/;
// one atom per soul: all incarnations pooled (copper is deep; on the table it is just copper)
const atoms = new Map();
for (const u of rows) {
if (u.kind === 'method' || BUILTIN.test(u.name) || u.name.length < 4) continue;
const a = atoms.get(u.soul) || atoms.set(u.soul, { soul: u.soul, number: u.number, name: u.name, kind: u.kind, lines: u.lines, purpose: u.purpose, homes: new Set(), files: new Set(), K: new Set(), L: new Set(), M: new Set(), paired: false, incarnations: 0 }).get(u.soul);
a.incarnations++; a.homes.add(u.repo); a.files.add(u.file);
const dir = path.posix.dirname(u.file);
for (const c of u.caller_files || []) {
const crepo = c.split('/')[0];
if (path.posix.dirname(c) === dir) a.K.add(c); else if (crepo === u.repo) a.L.add(c); else a.M.add(c);
if (/test|proof|spec|selftest|check/i.test(c)) a.paired = true;
}
}
// Pauli: a name bound to several distinct souls cannot bond by name — the electron would be in
// two states at once. Such atoms are 'ambiguous' and carry no valence until they are renamed.
const soulsPerName = new Map(); for (const a of atoms.values()) soulsPerName.set(a.name, (soulsPerName.get(a.name) || 0) + 1);
const list = [...atoms.values()].map(a => {
const ambiguous = soulsPerName.get(a.name) > 1 || /^__\w+__$/.test(a.name);
const mRepos = ambiguous ? [] : [...new Set([...a.M].map(c => c.split('/')[0]))].filter(r => !a.homes.has(r)); // callers in repos with no copy = tunnelling
const valence = mRepos.length;
const cls = ambiguous ? 'ambiguous' : valence === 0 ? (a.K.size + a.L.size ? 'noble' : 'inert-unused') : valence === 1 ? 'alkali' : valence <= 3 ? 'halogen' : 'conductor';
return { soul: a.soul, number: a.number, name: a.name, kind: a.kind, lines: a.lines, purpose: a.purpose, incarnations: a.incarnations, homes: [...a.homes].sort(),
shells: { K: a.K.size, L: a.L.size, M: a.M.size }, valence, valence_repos: mRepos.sort(), class: cls, spin: a.paired ? 'paired' : 'unpaired', tunnelling: mRepos.length > 0 };
});
list.sort((a, b) => b.valence - a.valence || (b.shells.K + b.shells.L + b.shells.M) - (a.shells.K + a.shells.L + a.shells.M));
await writeFile(path.join(OUT, 'atoms.json'), JSON.stringify({ generated_utc: new Date().toISOString(), atoms: list.length, classes: Object.fromEntries(['conductor', 'halogen', 'alkali', 'noble', 'inert-unused'].map(c => [c, list.filter(a => a.class === c).length])), unpaired: list.filter(a => a.spin === 'unpaired' && a.valence > 0).length, top: list.slice(0, 500) }, null, 2));
const label = a => `#${a.number} ${a.name}`;
const nodes = list.slice(0, 250).map(a => ({ label: label(a), type: a.class, rag: a.class === 'alkali' && a.spin === 'unpaired' ? 'red' : a.spin === 'unpaired' && a.valence > 0 ? 'amber' : 'green',
reason: `${a.kind} · ${a.lines} lines · shells K${a.shells.K} L${a.shells.L} M${a.shells.M} · valence ${a.valence} · spin ${a.spin} · homes ${a.homes.join(',')}${a.purpose ? ' · says: ' + a.purpose.slice(0, 80) : ''}` }));
const edges = [], repoSeen = new Set();
for (const a of list.slice(0, 250)) for (const r of a.valence_repos) { edges.push({ from: `repo ${r}`, to: label(a), kind: 'BONDS_WITH' }); if (!repoSeen.has(r)) { repoSeen.add(r); nodes.push({ label: `repo ${r}`, type: 'repo', rag: 'green', reason: 'holds no copy of the souls it bonds with — every bond is a tunnel' }); } }
await writeFile(path.join(OUT, 'graph.json'), JSON.stringify({ schema: 'electron-graph.v1', label: 'The Electron star', generated_utc: new Date().toISOString(),
note: 'Souls as atoms; shells K/L/M = callers in the same directory / repo / other repos; BONDS_WITH = a repo that calls the soul without holding a copy (tunnelling).', focus_default: nodes[0]?.label, nodes, edges }, null, 2));
const by = c => list.filter(a => a.class === c);
const md = `# The Electron star — ${list.length.toLocaleString()} atoms
Electron physics applied to code where it holds: **nucleus** = a soul · **electrons** = its callers · **shells K / L / M** = callers in the same directory / the same repo / other repos, filled inner-first · **valence** = the M shell, the callers in repos that hold no copy of the soul — the bonds that decide its chemistry · **spin** paired = a test or proof calls it. Updated ${new Date().toISOStrin … [line shortened here: 415 characters; full line on GitHub]
| class | meaning | atoms |
|---|---|---|
| conductor | valence ≥ 4 repos — free electrons, the estate's wiring | ${by('conductor').length} |
| halogen | valence 2–3 | ${by('halogen').length} |
| **alkali** | valence 1 — one lone external bond, reactive and fragile | **${by('alkali').length}** |
| noble | full outer shell — used only at home, safe to change | ${by('noble').length} |
| inert-unused | no electrons at all — nothing calls it anywhere | ${by('inert-unused').length} |
| ambiguous | Pauli: the name is bound to several souls, so it cannot bond by name | ${by('ambiguous').length} |
Unpaired spins with external bonds (**bonded across repos, and no test or proof ever calls them**): **${list.filter(a => a.spin === 'unpaired' && a.valence > 0).length}**
## Conduction band — the souls that carry the estate's current
${by('conductor').slice(0, 25).map(a => `- **#${a.number} ${a.name}** (${a.kind}, ${a.lines} lines, home ${a.homes.join('/')}) · valence ${a.valence}: ${a.valence_repos.join(', ')} · spin ${a.spin}`).join('\n') || '- none'}
## Alkali — one external bond each; if the home changes, the bond breaks
${by('alkali').filter(a => a.spin === 'unpaired').slice(0, 30).map(a => `- **#${a.number} ${a.name}** (home ${a.homes.join('/')}) ⇄ ${a.valence_repos[0]} · ${a.lines} lines · unpaired`).join('\n') || '- none'}
## Tunnelling — every valence bond is a tunnel: a repo calls a soul it does not hold
${list.filter(a => a.tunnelling).slice(0, 25).map(a => `- **#${a.number} ${a.name}** lives in ${a.homes.join('/')} · tunnels to ${a.valence_repos.join(', ')}`).join('\n') || '- none'}
## For the Spider
\`electron/graph.json\` — ${nodes.length} nodes, ${edges.length} BONDS_WITH edges.
`;
await writeFile(path.join(SKY, 'ELECTRON.md'), md);
console.log(`electron: ${list.length} atoms · conductor ${by('conductor').length} · halogen ${by('halogen').length} · alkali ${by('alkali').length} · noble ${by('noble').length} · unused ${by('inert-unused').length} · unpaired-bonded ${list.filter(a => a.spin === 'unpaired' && a.valence > 0).length}`);Elements
A JavaScript module in the bench folder of Star Maker that reads table and engine graph, using SHA-256.
storagestar-maker / machinery/bench/elements.mjs · lines 1–77 of 77 · Not reached from any entry point (candidate for review) · pattern readJson (shared by 43 files)
- What it does
- It loads table and engine graph. Defines sha, readJson, symbolFor, upsert. Uses libraries node:fs/promises, node:crypto, node:path. Side effects: reads or writes files.
- Inputs & outputs
- In: JSON file table.json; JSON file engine-graph.json; JSON file current.json.
- What it achieves
- It reads JSON (`readJson`) and is built from the sha step (`sha`) and the symbol for helper (`symbolFor`). THE PERIODIC TABLE — stars make elements.
- Why it matters
- No other file in the estate was found to import it.
- Application
- star-maker · machinery/bench · JavaScript module
- Uses
- node:fs/promises, node:crypto, node:path
- Used by
- none found
- Produces
- sha, readJson, symbolFor, upsert
- Defines here
- sha, readJson, symbolFor, upsert
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- star-maker@2c477b0cc673304c5b288cee9d0e0ae42d273b2e machinery/bench/elements.mjs:1-77 · blob 17131bc00bd88c0274860bdab38e7b4dfc718033 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unreached_review
// THE PERIODIC TABLE — stars make elements. An element is a primitive with a fixed identity that
// any surface can compose with: the Spider graphically, a terminal by symbol, Claude by name.
// Families: physics constants, vocabularies, engines, cartridges, data layers, contracts.
// Atomic numbers are persisted and only ever appended, so a symbol means the same thing forever.
//
// node elements.mjs → star-maker/elements/table.json + PERIODIC-TABLE.md
import { readFile, readdir, writeFile, mkdir } from 'node:fs/promises';
import { createHash } from 'node:crypto';
import path from 'node:path';
const SKY = process.env.SKY_DIR || 'C:/Users/vikra/Documents/GitHub/star-maker';
const ENGINE = process.env.ENGINE_DIR || 'C:/Users/vikra/Documents/GitHub/ventus-grid-engine';
const ATLAS = process.env.ATLAS_DIR || 'C:/Users/vikra/Documents/GitHub/gridatlas/atlas';
const TABLE = path.join(SKY, 'elements', 'table.json');
const sha = s => createHash('sha1').update(s).digest('hex').slice(0, 12);
const readJson = async p => JSON.parse(await readFile(p, 'utf8'));
let table = { schema: 'ventus.periodic-table.v1', elements: [] };
try { table = await readJson(TABLE); } catch {}
const byKey = new Map(table.elements.map(e => [e.key, e]));
const used = new Set(table.elements.map(e => e.symbol));
function symbolFor(name) { // two or three letters, unique, from the name's shape
const parts = name.replace(/\.(js|mjs)$/, '').split(/[^A-Za-z0-9]+/).filter(Boolean);
const cands = [parts.map(p => p[0]).join('').slice(0, 2), parts[0].slice(0, 2), parts.map(p => p[0]).join('').slice(0, 3), parts[0].slice(0, 3), parts[0][0] + (parts[1] || parts[0]).slice(-1)];
for (let c of cands) { c = c[0].toUpperCase() + c.slice(1).toLowerCase(); if (c && !used.has(c)) { used.add(c); return c; } }
for (let i = 1; i < 999; i++) { const c = cands[0][0].toUpperCase() + i; if (!used.has(c)) { used.add(c); return c; } }
}
function upsert(key, fields) {
let e = byKey.get(key);
if (!e) { e = { number: table.elements.length + 1, symbol: symbolFor(fields.name), key, discovered: new Date().toISOString().slice(0, 10) }; table.elements.push(e); byKey.set(key, e); }
Object.assign(e, fields, { identity: sha(key + JSON.stringify(fields.value ?? fields.contract ?? fields.name)) });
return e;
}
// physics + vocabularies: from the logic stars (constants that exist across the estate)
const logicDir = path.join(SKY, 'logic');
for (const f of (await readdir(logicDir).catch(() => [])).filter(f => f.endsWith('.json'))) {
const s = await readJson(path.join(logicDir, f));
if (s.kind === 'constant-drift' && !/^(R_|EARTH|KV|MVA|MW|VOLT|FREQ|TECH|BUCKET|LAYER|REPD)/.test(s.name)) continue;
upsert(`const:${s.name}`, { family: s.kind === 'vocabulary-drift' ? 'vocabulary' : 'physics', name: s.name,
state: 'UNSETTLED', candidates: s.values.map(v => ({ value: v.value, files: v.files.length })), repos: s.repos,
note: `${s.distinct_values} values in the wild; Claude + VIK-AI must settle which is true`, evidence: `logic/${s.name}.json` });
}
// engines: the engine's own population graph
try {
const g = await readJson(path.join(ENGINE, 'genome', 'engine-graph.json'));
for (const n of g.nodes || []) if (/^engine\//.test(n.label) && n.type === 'canonical')
upsert(`engine:${n.label}`, { family: 'engine', name: n.label.replace(/^engine\//, ''), state: n.rag === 'green' ? 'SETTLED' : 'UNSETTLED', note: n.reason, source: n.gh });
} catch {}
// cartridges + data layers + contract: from the live atlas composition and the deep-link contract
try {
const cur = await readJson(path.join(ATLAS, 'current.json'));
for (const c of cur.cartridges) upsert(`cartridge:${c.id}`, { family: 'cartridge', name: c.id, state: 'SETTLED', value: c.sha256, version: c.version, generation: c.generation, gives: c.capabilities?.length || 0, note: `replaces ${c.replace_script}` });
const dataDir = path.join(ATLAS, cur.shell.base, 'data');
for (const f of (await readdir(dataDir).catch(() => [])).filter(f => f.endsWith('.geojson')))
upsert(`layer:${f}`, { family: 'data-layer', name: f.replace('.geojson', ''), state: 'SETTLED', note: `atlas layer ${f}` });
} catch {}
try {
const src = await readFile(path.join(ENGINE, 'deeplink', 'contract.js'), 'utf8');
const params = [...src.matchAll(/^\s{4}(\w+):\s*\{\s*type:\s*'(\w+)',\s*required:\s*(true|false)/gm)].map(m => ({ name: m[1], type: m[2], required: m[3] === 'true' }));
upsert('contract:deeplink', { family: 'contract', name: 'deeplink (the MAP button)', state: 'SETTLED', contract: params, note: 'identity = repd_ref; technology is a BUCKET, not a layer id' });
} catch {}
await mkdir(path.dirname(TABLE), { recursive: true });
await writeFile(TABLE, JSON.stringify(table, null, 2));
const fams = ['physics', 'vocabulary', 'engine', 'cartridge', 'data-layer', 'contract'];
const md = `# The periodic table — ${table.elements.length} elements
Stars make elements. An element is a primitive with a fixed identity (atomic number and symbol never change; the identity hash changes only when the thing itself changes) that any surface composes with: the Spider graphically, a terminal by symbol (\`ventus.ps1 element Ek\`), Claude by name. **UNSETTLED** elements exist in the estate in more than one form and wait for Claude + VIK-AI to settle whi … [line shortened here: 448 characters; full line on GitHub]
${fams.map(fam => {
const es = table.elements.filter(e => e.family === fam);
return `## ${fam} (${es.length})\n\n| # | symbol | name | state | note |\n|---|---|---|---|---|\n` + es.map(e => `| ${e.number} | **${e.symbol}** | ${e.name} | ${e.state === 'SETTLED' ? '🟢 settled' : '🟡 unsettled: ' + (e.candidates || []).map(c => `\`${String(c.value).slice(0, 24)}\``).join(' / ')} | ${(e.note || '').slice(0, 90)} |`).join('\n');
}).join('\n\n')}
`;
await writeFile(path.join(SKY, 'PERIODIC-TABLE.md'), md);
console.log(`periodic table: ${table.elements.length} elements (${fams.map(f => f + ' ' + table.elements.filter(e => e.family === f).length).join(', ')})`);Machinery — Bench Page
A web page in Star Maker that renders parts (`renderParts`) and findings (`renderFindings`), loads runs (`loadRuns`) and reads inputs for headed, using SHA-256.
renderstar-maker / machinery/bench/index.html · lines 1–124 of 124 · Entry point
- What it does
- It draws its content. Defines 9 functions or classes, including $, esc, log, api, renderParts. Side effects: changes the web page (DOM); makes network requests.
- Inputs & outputs
- In: form fields (user input). Out: web page.
- Downstream impact
- It is itself an entry point (page); no other file was found loading it.
- What it achieves
- It renders parts (`renderParts`), renders findings (`renderFindings`) and renders result (`renderResult`). Defines `esc`, `log`, `api` and 5 more. It responds to change events.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- star-maker · machinery/bench · page
- Uses
- none found
- Used by
- none found
- Produces
- $, esc, log, api, renderParts, renderFindings, renderResult, loadRuns, saveChoice
- Defines here
- $, esc, log, api, renderParts, renderFindings, renderResult, loadRuns, saveChoice
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- star-maker@2c477b0cc673304c5b288cee9d0e0ae42d273b2e machinery/bench/index.html:1-124 · blob 9f7b65575cb59e5c2390a71344b8597a03fcf0b3 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Ventus OS · The Bench</title>
<style>
:root{color-scheme:dark;--bg:#0b0e13;--panel:#11161d;--line:#232b36;--cyan:#22d3ee;--dim:#7f8ea3;--txt:#e6edf3;--green:#22c55e;--amber:#f59e0b;--red:#ef4444;--purple:#a78bfa}
*{box-sizing:border-box} body{margin:0;background:var(--bg);color:var(--txt);font:13px/1.45 ui-monospace,Consolas,monospace;padding-inline:16px;padding-block:14px}
header{display:flex;flex-wrap:wrap;gap:12px;align-items:center;border-bottom:1px solid var(--line);padding-bottom:12px;margin-bottom:14px}
.brand small{display:block;color:var(--cyan);letter-spacing:.2em;font-size:10px} .brand b{font-size:18px}
.meta{color:var(--dim)} .meta b{color:var(--txt)}
.actions{margin-left:auto;display:flex;flex-wrap:wrap;gap:8px;align-items:center}
button,.btn{background:#0e1319;color:var(--txt);border:1px solid var(--line);padding:8px 14px;font:inherit;cursor:pointer;border-radius:6px;text-decoration:none}
button.primary{border-color:var(--cyan);color:var(--cyan);font-weight:700} button:hover,.btn:hover{border-color:var(--cyan)} button:disabled{opacity:.5;cursor:wait}
main{display:grid;grid-template-columns:minmax(320px,440px) 1fr;gap:16px} @media(max-width:900px){main{grid-template-columns:1fr}}
.card{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:12px 14px;margin-bottom:10px;position:relative}
.card.off{opacity:.55} .card h3{margin:0 0 4px;font-size:14px;display:flex;align-items:center;gap:8px}
.tag{font-size:10px;letter-spacing:.1em;color:var(--dim);border:1px solid var(--line);padding:1px 6px;border-radius:4px}
.dot{width:11px;height:11px;border-radius:50%;background:#2a3441;box-shadow:0 0 8px transparent;flex:none}
.dot.green{background:var(--green);box-shadow:0 0 8px var(--green)} .dot.amber{background:var(--amber);box-shadow:0 0 8px var(--amber)} .dot.red{background:var(--red);box-shadow:0 0 8px var(--red)}
.row{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-top:8px;color:var(--dim)} .row b{color:var(--txt)}
select{background:#0e1319;color:var(--txt);border:1px solid var(--line);padding:5px 8px;font:inherit;border-radius:6px;max-width:100%}
.chips{display:flex;flex-wrap:wrap;gap:4px;margin-top:6px} .chip{font-size:10px;color:var(--purple);border:1px solid #3b3564;padding:1px 6px;border-radius:10px}
.switch{margin-left:auto;display:flex;align-items:center;gap:6px;cursor:pointer;user-select:none} .switch input{accent-color:var(--cyan);width:16px;height:16px}
.findings{margin-top:8px;font-size:12px} .findings div{padding:3px 0;border-top:1px dashed var(--line);color:#f3b4b4;overflow-wrap:anywhere} .findings div.amber{color:#f6d28b} .findings div.warning{color:var(--dim)}
.verdict{font-size:22px;font-weight:800;letter-spacing:.1em} .verdict.GREEN{color:var(--green)} .verdict.AMBER{color:var(--amber)} .verdict.RED{color:var(--red)}
img.shot{width:100%;max-width:100%;border:1px solid var(--line);border-radius:8px;margin-top:10px;background:#000}
table{width:100%;border-collapse:collapse;font-size:12px} td,th{text-align:left;padding:5px 6px;border-bottom:1px solid var(--line);vertical-align:top} th{color:var(--cyan);font-weight:600}
.stat{display:inline-block;margin-right:14px;color:var(--dim)} .stat b{color:var(--txt)}
#log{white-space:pre-wrap;color:var(--dim);font-size:11px;max-height:120px;overflow:auto}
.hint{color:var(--dim);font-size:12px}
</style>
</head>
<body>
<header>
<div class="brand"><small>VENTUS OS · THE BENCH</small><b>GridAtlas on the lift</b></div>
<div class="meta" id="meta">loading parts…</div>
<div class="actions">
<label class="switch hint"><input type="checkbox" id="headed"> watch in a Chrome window</label>
<a class="btn" href="/atlas/" target="_blank">Open composed car in my Chrome ↗</a>
<button id="reset">Reset to live</button>
<button id="drive" class="primary">▶ Test drive</button>
</div>
</header>
<main>
<section>
<p class="hint">Each card is a part bolted into the immutable shell. Switch one OFF and the shell's original script comes back. Pick another version and its SHA-256 is verified by the real loader. Then test drive.</p>
<div id="parts"></div>
<div class="card" id="shell"><h3><span class="dot" id="dot-shell"></span>Immutable shell <span class="tag">SHELL</span></h3><div class="row" id="shellinfo"></div><div class="findings" id="f-shell"></div></div>
</section>
<section>
<div class="card" id="result"><div class="verdict" id="verdict">—</div><div class="hint">No test drive yet. Compose the car on the left, then press ▶ Test drive.</div></div>
<div class="card"><h3>Test drives</h3><table id="runs"><thead><tr><th>when</th><th>verdict</th><th>load</th><th>composition</th></tr></thead><tbody></tbody></table></div>
<div class="card"><h3>Log</h3><div id="log"></div></div>
</section>
</main>
<script>
const $ = s => document.querySelector(s);
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({'&':'&','<':'<','>':'>','"':'"'}[c]));
const log = m => { $('#log').textContent = `${new Date().toLocaleTimeString()} ${m}\n` + $('#log').textContent; };
let PARTS = null, CHOICE = { enabled: {}, selected: {} }, LAST = null;
const api = (p, o) => fetch(p, o ? { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(o) } : undefined).then(r => r.json());
function renderParts() {
$('#meta').innerHTML = `live composition <b>${esc(PARTS.generation)}</b> · release <b>${esc(PARTS.release_id)}</b> · ${PARTS.cartridges.length} cartridges on a ${PARTS.shell_scripts.length}-slot shell`;
$('#parts').innerHTML = PARTS.cartridges.map(c => {
const on = CHOICE.enabled[c.id] !== false, sel = CHOICE.selected[c.id] || c.live_file;
const h = LAST?.health?.[c.id];
return `<div class="card ${on ? '' : 'off'}" data-id="${esc(c.id)}">
<h3><span class="dot ${h ? h.colour : ''}"></span>${esc(c.id)} <span class="tag">CARTRIDGE</span>
<label class="switch"><input type="checkbox" data-toggle="${esc(c.id)}" ${on ? 'checked' : ''}> ${on ? 'ON' : 'OFF → shell original'}</label></h3>
<div class="row">version <select data-select="${esc(c.id)}">${c.versions.map(v => `<option value="${esc(v.file)}" ${v.file === sel ? 'selected' : ''}>${esc(v.stamp)} · contract v${esc(v.contract)} · ${Math.round(v.bytes/1024)} KB${v.live ? ' · LIVE' : ''}</option>`).join('')}</select> <span>${c.versions.length} on the shelf</span></div>
<div class="row">live <b>${esc(c.live_version)}</b> · replaces slot <b>${esc(c.replace_script)}</b></div>
<details><summary class="hint" style="cursor:pointer">${c.capabilities.length} declared capabilities (GIVES)</summary><div class="chips">${c.capabilities.map(x => `<span class="chip">${esc(x)}</span>`).join('')}</div></details>
<div class="findings" id="f-${esc(c.id)}">${renderFindings(c.id)}</div>
</div>`;
}).join('');
$('#shellinfo').innerHTML = `release <b>${esc(PARTS.shell.release_id)}</b> · slots: ${PARTS.shell_scripts.map(s => `<span class="tag">${esc(s.split('/').pop())}</span>`).join(' ')}`;
$('#dot-shell').className = 'dot ' + (LAST?.health?.shell?.colour || '');
$('#f-shell').innerHTML = renderFindings('shell') + renderFindings('loader') + renderFindings('vendor') + renderFindings('unattributed');
}
function renderFindings(id) {
if (!LAST) return '';
return LAST.findings.filter(f => f.part === id).slice(0, 8).map(f => `<div class="${f.level === 'exception' ? '' : f.level === 'console-error' ? 'amber' : 'warning'}">${f.level === 'exception' ? '✖' : f.level === 'console-error' ? '▲' : '·'} ${esc(f.text)}${f.line != null ? ` <span class="hint">L${f.line}</span>` : ''}${id !== f.part ? '' : ''}${f.part === 'unattributed' ? '' : ''}</div>`).join( … [line shortened here: 404 characters; full line on GitHub]
}
function renderResult(r) {
LAST = r;
const p = r.probe;
$('#result').innerHTML = `<div class="verdict ${r.verdict}">${r.verdict}</div>
<div><span class="stat">composition <b>${esc(r.composition.generation)}</b></span><span class="stat">router <b>${esc(p.router)}</b></span><span class="stat">load <b>${r.loadMs} ms</b></span>
<span class="stat">layers <b>${p.layers?.ok ?? '?'} OK</b> / ${p.layers?.wait ?? '?'} WAIT / ${p.layers?.fail ?? '?'} FAIL</span><span class="stat">canvases <b>${p.canvases ?? '?'}</b></span>
<span class="stat">loaded <b>${(p.loaded || []).map(x => x.id).join(', ') || 'none'}</b></span></div>
${r.navError ? `<div class="findings"><div>navigation: ${esc(r.navError)}</div></div>` : ''}
${p.loaderText && p.router === 'failed' ? `<div class="findings"><div>${esc(p.loaderText)}</div></div>` : ''}
${p.banners?.length ? `<div class="findings">${p.banners.map(b => `<div class="amber">banner: ${esc(b)}</div>`).join('')}</div>` : ''}
${r.failedRequests?.length ? `<details><summary class="hint">${r.failedRequests.length} failed requests</summary><div class="findings">${r.failedRequests.map(x => `<div class="warning">${esc(x)}</div>`).join('')}</div></details>` : ''}
<img class="shot" src="/${r.screenshot}?t=${Date.now()}" alt="test drive screenshot">`;
renderParts();
}
async function loadRuns() {
const runs = await api('/api/runs');
$('#runs tbody').innerHTML = runs.map(r => `<tr><td>${esc(r.stamp)}</td><td class="verdict ${r.verdict}" style="font-size:12px">${r.verdict}</td><td>${r.loadMs} ms</td>
<td>${r.cartridges.map(c => `${esc(c.id)}${c.swapped_from ? ' ⇄ ' + esc(c.file.slice(0,12)) : ''}`).join(', ') || '<i>shell only</i>'}${PARTS ? PARTS.cartridges.filter(c => !r.order.includes(c.id)).map(c => ` <s>${esc(c.id)}</s>`).join('') : ''}</td></tr>`).join('');
}
async function saveChoice() { await api('/api/choice', CHOICE); log('composition saved — /atlas/ now serves it'); }
document.addEventListener('change', async ev => {
const t = ev.target;
if (t.dataset.toggle) { CHOICE.enabled[t.dataset.toggle] = t.checked; await saveChoice(); renderParts(); }
if (t.dataset.select) { CHOICE.selected[t.dataset.select] = t.value; await saveChoice(); renderParts(); }
});
$('#reset').onclick = async () => { await api('/api/reset'); CHOICE = { enabled: {}, selected: {} }; log('reset to live composition'); renderParts(); };
$('#drive').onclick = async () => {
$('#drive').disabled = true; $('#drive').textContent = '… driving (GPU)';
log('test drive started');
try { const r = await api('/api/testdrive', { headed: $('#headed').checked }); renderResult(r); log(`test drive ${r.verdict}: ${r.findings.length} findings, ${r.loadMs} ms`); await loadRuns(); }
catch (e) { log('test drive failed: ' + e.message); }
$('#drive').disabled = false; $('#drive').textContent = '▶ Test drive';
};
(async () => { PARTS = await api('/api/parts'); CHOICE = await api('/api/choice'); renderParts(); await loadRuns(); log('parts loaded from the gridatlas repo (read-only)'); })();
</script>
</body>
</html>