In this section
- Generate interaction · code-generator / generate.mjs lines 1–319
- Code Generator — Index Page render · code-generator / index.html lines 1–166
- Rules storage · code-generator / rules.mjs lines 1–73
- Compass transform · compass / src/compass.mjs lines 1–68
Generate
A JavaScript module in Code Generator that draws blocks, reactions and parts, and uses data from the stars repository. Served with the page at https://ventusltd.github.io/code-generator/.
interactioncode-generator / generate.mjs · lines 1–319 of 319 · Entry point · pattern applyInputs (shared by 2 files)
- What it does
- It draws blocks, reactions and parts. Defines 17 functions or classes, including arg, getJson, rawUrl, ghUrl, family. Uses libraries node:fs, node:path. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes.
- Inputs & outputs
- In: data source: stars data; JSON file blocks.json; JSON file index.json; JSON file reactions.json; JSON file graph.json; JSON file parts.json; JSON file apps.json; form fields (user input). Out: JSON file parts.json; JSON file apps.json.
- Downstream impact
- Used directly by 1 file: Generate Workflow (code-generator). It is itself an entry point, published at https://ventusltd.github.io/code-generator/.
- What it achieves
- It gets JSON (`getJson`), loads kind (`loadKind`) and applies inputs (`applyInputs`). Build an app from blocks of the periodic table (or from numbered families). It writes `spider/graphs/apps.json`. It responds to error and unhandledrejection events.
- Why it matters
- Run by Generate Workflow.
- Application
- code-generator · / · JavaScript module
- Uses
- Rules (import), Stars — Index Page (estate URL), Code Generator — Index Page (estate URL), Table (estate URL), node:fs, node:path
- Used by
- run by Generate Workflow (workflow run)
- Produces
- arg, getJson, rawUrl, ghUrl, family, decisionUrl, definers, place, loadKind, fileAt, esc, $
- Defines here
- arg, getJson, rawUrl, ghUrl, family, decisionUrl, definers, place, loadKind, fileAt, esc, $, note, applyInputs, loadOne, loadLib, q
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e generate.mjs:1-319 · blob d384f93b7721ca41012c31f96d15dc62786f00d4 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process · domain stage: unknown · users: none · canonical: unknown
// Code generator — build an app from blocks of the periodic table (or from numbered families).
// node generate.mjs --name substation-finder --blocks Si,Vn,Ug,Ps,Dt [--title "Substation finder"]
// node generate.mjs --name geodesy --families 511,8770
// A block's files are copied exactly from GitHub at the commit the modular star recorded, one file per source
// lineage (the newest version). Nothing is invented: what the app still needs from its surroundings is listed.
// Output: apps/<name>/ (the files under <symbol>/, index.html, REPORT.md, WORK-ORDERS.md, parts.json),
// requests/<name>-<n>.json (one work order each, for the agents) and the Spider graph of all apps.
import { mkdirSync, writeFileSync, readdirSync, readFileSync, existsSync } from 'node:fs';
import path from 'node:path';
import { classify, inferType, usageIn, PLAIN, LIBRARIES } from './rules.mjs';
const STARS = 'https://ventusltd.github.io/stars/';
const SITE = 'https://ventusltd.github.io/code-generator/';
const REPO = 'Ventusltd/code-generator';
const arg = (k, d) => { const i = process.argv.indexOf('--' + k); return i > 0 ? process.argv[i + 1] : d; };
const name = arg('name'), title = arg('title', arg('name'));
if (!name || !/^[a-z0-9][a-z0-9-]{0,40}$/.test(name)) { console.error('--name: lowercase letters, digits and hyphens'); process.exit(2); }
const blockSyms = String(arg('blocks', '')).split(/[\s,]+/).filter(Boolean);
const familyNums = [...new Set(String(arg('families', '')).split(/[\s,]+/).filter(Boolean).map(Number))];
if (!blockSyms.length && !familyNums.length) { console.error('give --blocks or --families'); process.exit(2); }
const getJson = async u => { const r = await fetch(u); if (!r.ok) throw new Error(`${u} ${r.status}`); return r.json(); };
const rawUrl = p => `https://raw.githubusercontent.com/${p.repo}/${p.commit}/${p.path.split('/').map(encodeURIComponent).join('/')}`;
const ghUrl = p => `https://github.com/${p.repo}/blob/${p.commit}/${p.path.split('/').map(encodeURIComponent).join('/')}`;
const table = await getJson(STARS + 'blocks/blocks.json');
const index = await getJson(STARS + 'code/index.json');
const reactions = await getJson(STARS + 'blocks/reactions.json').catch(() => ({ reactions: [] }));
const buckets = new Map();
const family = async n => { const b = Math.floor(n / index.bucket_size); if (!buckets.has(b)) buckets.set(b, getJson(`${STARS}code/f/${b}.json`).catch(() => ({}))); return (await buckets.get(b))[n] || null; };
// Decision records from the stars repository: judgement with permanent keys. Linked, never restated.
const decisionsAll = await (async () => { try { const g = await getJson(STARS + 'decisions/graph.json'); const ids = g.nodes.filter(n => n.type === 'decision').map(n => n.id.replace(/^decision:/, '')); return (await Promise.all(ids.map(id => getJson(`${STARS}decisions/${id}.json`).catch(() => null)))).filter(Boolean); } catch { return []; } })();
const decisionUrl = d => `https://github.com/Ventusltd/stars/blob/main/decisions/${d.id}.json`;
const stamp = new Date().toISOString();
const dir = path.join('apps', name);
mkdirSync(dir, { recursive: true });
const parts = [], missing = [];
// ---- blocks: copy each block's files whole
for (const sym of blockSyms) {
const b = table.blocks.find(x => x.symbol === sym);
if (!b) { missing.push(sym); continue; }
const copied = [];
for (const f of b.files) {
try {
const r = await fetch(rawUrl(f)); if (!r.ok) throw new Error(r.status);
const text = await r.text();
const target = path.join(dir, b.symbol, path.basename(f.path));
mkdirSync(path.dirname(target), { recursive: true });
writeFileSync(target, text);
copied.push({ ...f, saved: path.relative(dir, target).replace(/\\/g, '/'), link: ghUrl(f), text });
} catch (e) { copied.push({ ...f, saved: null, error: String(e.message).slice(0, 80) }); }
}
parts.push({ kind: 'block', symbol: b.symbol, number: b.number, title: b.title, description: b.description, category: b.category, functions: b.functions, needs: b.needs, inside: b.inside.slice(0, 20), files: copied, repos: b.repos, depends_on: b.depends_on || [] });
}
// ---- families: copy single functions (the older route)
for (const n of familyNums) {
const f = await family(n); if (!f) { missing.push(String(n)); continue; }
const p = f.places[0];
try {
const r = await fetch(rawUrl(p)); if (!r.ok) throw new Error(r.status);
const lines = (await r.text()).split('\n').slice(p.first - 1, p.last);
const target = path.join(dir, 'functions', `${n}-${f.names[0].replace(/[^A-Za-z0-9_$]/g, '_')}${/\.py$/i.test(p.path) ? '.py' : '.mjs'}`);
mkdirSync(path.dirname(target), { recursive: true });
const text = `// family #${n} ${f.names[0]} · ${ghUrl(p)}#L${p.first}-L${p.last}\n${lines.join('\n')}\n`;
writeFileSync(target, text);
parts.push({ kind: 'family', family: n, title: f.names[0], description: `Function ${f.names[0]}, used in ${f.places.length} place(s).`, functions: 1, needs: (f.needs || []).map(x => ({ name: x, meaning: x })), inside: [{ family: n, name: f.names[0] }], files: [{ ...p, saved: path.relative(dir, target).replace(/\\/g, '/'), link: `${ghUrl(p)}#L${p.first}-L${p.last}`, text }], repos: f.repos, lin … [line shortened here: 431 characters; full line on GitHub]
} catch (e) { missing.push(String(n)); }
}
if (missing.length) console.log(`Not found or not fetchable: ${missing.join(', ')}`);
if (!parts.length) { console.error('Nothing to generate.'); process.exit(1); }
// ---- needs: every name used but not defined by the chosen parts, sorted by what to do about it
const have = new Set(parts.flatMap(p => p.inside.map(f => f.name)));
const chosenSyms = new Set(parts.filter(p => p.symbol).map(p => p.symbol));
const definers = nm => table.blocks.filter(b => !chosenSyms.has(b.symbol) && b.kind !== 'auto' && b.inside.some(f => f.name === nm)).map(b => ({ symbol: b.symbol, title: b.title }));
const needs = [];
for (const n of [...new Map(parts.flatMap(p => p.needs).filter(n => !have.has(n.name)).map(n => [n.name, n])).values()]) {
const users = parts.filter(p => p.needs.some(x => x.name === n.name));
const where = [];
let usage = null;
for (const p of users) for (const f of p.files) {
if (!f.text) continue;
const u = usageIn(n.name, f.text, /\.py$/i.test(f.path));
if (!u) continue;
if (!u.used) { usage = usage || { used: false, mentioned: true }; continue; }
where.push({ symbol: p.symbol || null, family: p.family || null, repo: f.repo, commit: f.commit, path: f.path, saved: f.saved, line: u.line, link: `${f.link.split('#')[0]}#L${u.line}` });
usage = usage?.used ? { used: true, declared: usage.declared || u.declared, how: usage.how === 'value' ? u.how : usage.how } : u;
}
if (!usage) usage = { used: false, mentioned: false };
const defs = definers(n.name);
const kind = classify(n.name, { definers: defs, usage });
const decisions = kind === 'word' || kind === 'browser' || kind === 'node' || /^[a-z]+$/.test(n.name) ? [] : decisionsAll.filter(d => new RegExp(`(?<![\\w$])${n.name.replace(/[$]/g, '\\$')}(?![\\w$])`).test([d.question, d.rationale, ...(d.evidence || [])].join(' ')) || (n.meaning.match(/\b([A-Z][a-z]?)'s neighbour/) && [d.subject.key, ...(d.also || [])].includes('block:' + n.meaning.match(/\b([A … [line shortened here: 431 characters; full line on GitHub]
needs.push({ name: n.name, meaning: n.meaning, kind, plain: PLAIN[kind], type: kind === 'missing' || kind === 'library' ? inferType(n.name, usage.how) : null, defined_by: defs, used_by: users.map(p => p.symbol || `#${p.family}`), where: where.slice(0, 12), decisions: decisions.map(d => ({ id: d.id, key: d.subject.key, status: d.status, question: d.question, url: decisionUrl(d) })) });
}
const order = { missing: 0, library: 1, block: 2, defined: 3, browser: 4, node: 5, absent: 6, word: 7 };
needs.sort((a, b) => order[a.kind] - order[b.kind] || a.name.localeCompare(b.name));
const toWrite = needs.filter(n => n.kind === 'missing' || n.kind === 'library');
// ---- chemistry: block pairs the table has no evidence for
const pairs = [];
const syms = parts.filter(p => p.symbol).map(p => p.symbol);
for (let i = 0; i < syms.length; i++) for (let j = i + 1; j < syms.length; j++) {
const r = reactions.reactions.find(x => (x.a === syms[i] && x.b === syms[j]) || (x.a === syms[j] && x.b === syms[i]));
pairs.push(r ? { a: syms[i], b: syms[j], verdict: r.verdict, probability: r.probability, basis: r.basis } : { a: syms[i], b: syms[j], verdict: 'untested', probability: 0.25, basis: 'no evidence either way' });
}
const untested = pairs.filter(p => p.verdict === 'untested' || p.verdict === 'fails');
// ---- open decisions on the chosen blocks, by key
const blockDecisions = decisionsAll.filter(d => d.status === 'open' && [d.subject.key, ...(d.also || [])].some(k => k.split('+').some(s => chosenSyms.has(s.replace(/^block:/, '')))));
// ---- load order: a block's dependencies (among the chosen) load before it; the rest keep the order given
const bySym = new Map(parts.filter(p => p.symbol).map(p => [p.symbol, p]));
const ordered = [], placed = new Set();
const place = (p, trail = []) => { if (!p || placed.has(p.symbol || p.family)) return; if (trail.includes(p)) return; for (const d of p.depends_on || []) if (bySym.has(d.symbol)) place(bySym.get(d.symbol), [...trail, p]); placed.add(p.symbol || p.family); ordered.push(p); };
for (const p of parts) place(p);
const loadKind = f => /\.mjs$/i.test(f) ? 'module' : /\.js$/i.test(f) ? 'script' : /\.py$/i.test(f) ? 'python' : /\.html?$/i.test(f) ? 'page' : 'other';
const seenSaved = new Set();
const plan = ordered.flatMap(p => p.files.filter(f => f.saved && !seenSaved.has(f.saved) && seenSaved.add(f.saved)).map(f => ({ part: p.symbol || `#${p.family}`, title: p.title, saved: f.saved, kind: loadKind(f.saved), load: /^(module|script)$/.test(loadKind(f.saved)), source: f.link, after: (p.depends_on || []).filter(d => bySym.has(d.symbol)).map(d => d.symbol) })));
// ---- work orders: one per missing need and one per untested pair; numbers are kept across re-runs by key
mkdirSync('requests', { recursive: true });
const existing = readdirSync('requests').filter(f => f.startsWith(name + '-') && f.endsWith('.json')).map(f => { try { return JSON.parse(readFileSync(path.join('requests', f), 'utf8')); } catch { return null; } }).filter(x => x && x.key);
let next = existing.reduce((m, r) => Math.max(m, Number(String(r.id).slice(name.length + 1)) || 0), 0) + 1;
const orders = [];
const fileAt = w => `${w.repo}/${w.path}@${w.commit.slice(0, 7)}:${w.line}`;
for (const n of toWrite) {
const key = `need:${n.name}`; const prior = existing.find(r => r.key === key);
const id = prior ? prior.id : `${name}-${next++}`;
const blocks = n.used_by.map(s => bySym.get(s)).filter(Boolean).map(b => ({ symbol: b.symbol, number: b.number, title: b.title }));
const where = n.where.map(w => ({ repo: w.repo, commit: w.commit, path: w.path, line: w.line, link: w.link, saved: w.saved }));
const isLib = n.kind === 'library';
const brief = isLib
? `The app ${name} uses the library global \`${n.name}\` (${LIBRARIES[n.name]}) in ${blocks.map(b => b.symbol).join(', ') || n.used_by.join(', ')}, first at ${where[0] ? fileAt(where[0]) : 'an unknown line'}. Decide which version the app should load and add one script tag for it to apps/${name}/index.html before the parts; record the version and its source URL in this request. Nothing in the c … [line shortened here: 424 characters; full line on GitHub]
: `The app ${name} uses \`${n.name}\` (${n.type}; ${n.meaning}) in ${blocks.map(b => `${b.symbol} ${b.title}`).join(', ') || n.used_by.join(', ')}, first at ${where[0] ? fileAt(where[0]) : 'an unknown line'}, and nothing in the table defines it. Read the ${where.length} place${where.length === 1 ? '' : 's'} listed to learn what the callers expect of it, write it as a new file in a repository o … [line shortened here: 720 characters; full line on GitHub]
orders.push({ schema: 'code-generator.work-order.v1', id, key, kind: isLib ? 'library' : 'need', app: name, title: isLib ? `${n.name}: supply the library for ${name}` : `${n.name}: write the missing ${n.type} for ${name}`,
missing: { name: n.name, type: n.type, meaning: n.meaning }, used_in: { blocks, families: parts.filter(p => p.family && n.used_by.includes(`#${p.family}`)).map(p => p.family), files: where },
must_provide: [{ name: n.name, type: n.type }], acceptance: `${SITE}apps/${name}/index.html loads without "${n.name} is not defined"; its needs table shows ${n.name} as provided.`,
decisions: n.decisions.map(d => d.url), brief, status: 'open', issue: prior?.issue || null, created_utc: prior?.created_utc || stamp, updated_utc: stamp });
}
for (const p of untested) {
const key = `pair:${p.a}+${p.b}`; const prior = existing.find(r => r.key === key);
const id = prior ? prior.id : `${name}-${next++}`;
const A = bySym.get(p.a), B = bySym.get(p.b);
const files = [A, B].flatMap(b => b.files.filter(f => f.saved).map(f => ({ repo: f.repo, commit: f.commit, path: f.path, link: f.link, saved: f.saved })));
const decs = decisionsAll.filter(d => [d.subject.key, ...(d.also || [])].some(k => k === `block:${p.a}+block:${p.b}` || k === `block:${p.b}+block:${p.a}`)).map(decisionUrl);
orders.push({ schema: 'code-generator.work-order.v1', id, key, kind: 'pair', app: name, title: `${p.a} + ${p.b}: test ${A.title} with ${B.title} for ${name}`,
missing: { name: `${p.a}+${p.b}`, type: 'compatibility test', meaning: `${A.title} and ${B.title} have never been loaded together (${p.basis}).` },
used_in: { blocks: [A, B].map(b => ({ symbol: b.symbol, number: b.number, title: b.title })), families: [], files },
must_provide: [{ name: `tests/${p.a}+${p.b}`, type: 'a recorded composition test: the two blocks\' files loaded together, every error listed, verdict proven or fails' }],
acceptance: `${SITE}apps/${name}/index.html loads the files of ${p.a} and ${p.b} with no error attributed to either; the chemistry for ${p.a}+${p.b} on the periodic table changes from untested to a verdict with evidence.`,
decisions: decs, brief: `Blocks ${p.a} (${A.title}) and ${p.b} (${B.title}) are chosen together in ${name} but the periodic table has no evidence they work together. Load the files listed (the assembly page apps/${name}/index.html does this in order) and record what happens: which file throws, on what name, and whether the two blocks need the same value under different names. Report the result … [line shortened here: 490 characters; full line on GitHub]
status: 'open', issue: prior?.issue || null, created_utc: prior?.created_utc || stamp, updated_utc: stamp });
}
for (const o of orders) writeFileSync(path.join('requests', `${o.id}.json`), JSON.stringify(o, null, 2) + '\n');
// ---- recipe
const recipe = { schema: 'code-generator.recipe.v3', name, title, generated_utc: stamp, blocks: blockSyms, families: familyNums,
needs: needs.map(n => ({ name: n.name, meaning: n.meaning, kind: n.kind, type: n.type, defined_by: n.defined_by.map(d => d.symbol), used_by: n.used_by, decisions: n.decisions.map(d => d.id) })),
inputs: toWrite.map(n => n.name), pairs, work_orders: orders.map(o => ({ id: o.id, key: o.key, title: o.title })), decisions: blockDecisions.map(d => ({ id: d.id, key: d.subject.key, url: decisionUrl(d) })),
load_order: plan.map(f => f.saved),
parts: parts.map(p => ({ kind: p.kind, symbol: p.symbol, number: p.number, family: p.family, title: p.title, functions: p.functions, files: p.files.map(f => ({ repo: f.repo, commit: f.commit, path: f.path, saved: f.saved })) })) };
writeFileSync(path.join(dir, 'parts.json'), JSON.stringify(recipe, null, 2));
// ---- the assembly page: opens on Pages, loads the parts in order, says what loaded and what threw
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
const page = { name, title, generated_utc: stamp, plan, inputs: toWrite.map(n => ({ name: n.name, type: n.type, meaning: n.meaning, used_by: n.used_by, order: orders.find(o => o.key === 'need:' + n.name)?.id || null })),
provided: needs.filter(n => n.kind === 'browser').map(n => n.name), other: needs.filter(n => !/^(missing|library|browser)$/.test(n.kind)).map(n => ({ name: n.name, kind: n.kind, plain: n.plain, defined_by: n.defined_by.map(d => d.symbol) })), pairs: untested.map(p => `${p.a}+${p.b}`) };
const html = `<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>${esc(title)} · assembly</title>
<style>
:root{color-scheme:dark}
body{margin:0;padding:16px 18px 40px;background:#0b0d12;color:#eef2fb;font:15px/1.5 Inter,ui-sans-serif,system-ui,sans-serif}
a{color:#00e5ff} h1{font-size:22px;margin:0 0 4px} h2{font-size:15px;font-family:ui-monospace,monospace;letter-spacing:.14em;text-transform:uppercase;color:#9aa3b5;margin:22px 0 8px}
.ey{font-family:ui-monospace,monospace;font-size:11px;letter-spacing:.2em;text-transform:uppercase;color:#00e5ff} .muted{color:#9aa3b5}
.card{border:1px solid #262b36;border-radius:14px;padding:14px 16px;margin:12px 0;background:linear-gradient(160deg,rgba(255,255,255,.055),rgba(255,255,255,.014))}
label{display:block;margin:10px 0 4px} label b{font-family:ui-monospace,monospace} label small{color:#9aa3b5;display:block}
input{width:100%;box-sizing:border-box;padding:9px 12px;background:#12151c;border:1px solid #262b36;color:inherit;font:inherit;border-radius:10px}
.btn{background:#0f1218;border:1px solid #00e5ff;color:#eef2fb;padding:9px 14px;border-radius:999px;font:inherit;cursor:pointer;margin:12px 8px 0 0} .btn:disabled{opacity:.4;cursor:not-allowed}
table{border-collapse:collapse;width:100%;font-size:13px} td,th{padding:6px 8px;border-bottom:1px solid #1a1f2a;text-align:left;vertical-align:top} th{color:#9aa3b5;font-weight:500}
.ok{color:#39d353} .bad{color:#ff5555} .wait{color:#9aa3b5} .amber{color:#ffd54a} .mono{font-family:ui-monospace,monospace;font-size:12px}
details{margin:8px 0} summary{cursor:pointer;color:#9aa3b5} .wrap{overflow-x:auto}
</style>
<div class="ey">Ventus · Global Grid 2050 · Code generator · assembly</div>
<h1>${esc(title)}</h1>
<div class="muted">Built ${stamp.slice(0, 16).replace('T', ' ')} UTC from ${parts.length} part${parts.length === 1 ? '' : 's'}: ${esc(ordered.map(p => p.symbol ? `${p.symbol} ${p.title}` : `#${p.family} ${p.title}`).join(', '))}. Every file is copied unchanged from GitHub at a pinned commit; this page loads them in dependency order and reports what happened. <a href="REPORT.md">Report</a> · <a hre … [line shortened here: 474 characters; full line on GitHub]
<div class="card" id="inputs-card">
<h2>Values still needed</h2>
${page.inputs.length ? `<p class="muted">These names are used by the parts but defined nowhere in the table. Give each a value here to try the assembly; each also has a work order for the agents.</p><form id="inputs">${page.inputs.map(n => `<label for="need-${esc(n.name)}"><b>${esc(n.name)}</b> <span class="muted">· ${esc(n.type)} · used by ${esc(n.used_by.join(', '))}${n.order ? ` · <a href=".. … [line shortened here: 971 characters; full line on GitHub]
<button class="btn" id="go">Load the parts</button> <span class="muted" id="state">not started</span>
</div>
<div class="card">
<h2>What loaded</h2>
<div class="wrap"><table id="files"><thead><tr><th>order</th><th>part</th><th>file</th><th>kind</th><th>result</th></tr></thead><tbody>
${plan.map((f, i) => `<tr data-file="${esc(f.saved)}"><td>${i + 1}</td><td class="mono">${esc(f.part)}</td><td class="mono"><a href="${esc(f.source)}">${esc(f.saved)}</a></td><td>${esc(f.kind)}</td><td class="${f.load ? 'wait' : 'muted'} res">${f.load ? 'waiting' : f.kind === 'python' ? 'Python: not loadable in a page' : f.kind === 'page' ? 'a page of its own: not loaded here' : 'not loaded'}</t … [line shortened here: 423 characters; full line on GitHub]
</tbody></table></div>
${page.pairs.length ? `<p class="amber">Untested combinations: ${esc(page.pairs.join(', '))}. Whatever this page reports for their files is the first evidence.</p>` : ''}
</div>
<div class="card">
<h2>Provided by the browser</h2>
<p class="muted">Names the parts use that a web browser supplies. Checked when the page opens.</p>
<div class="mono" id="provided">${page.provided.map(n => `<span data-provided="${esc(n)}">${esc(n)}</span>`).join(' · ') || 'none'}</div>
${page.other.length ? `<details><summary>${page.other.length} other name${page.other.length === 1 ? '' : 's'} the table listed as needs, and why nothing is written for them</summary><div class="wrap"><table><thead><tr><th>name</th><th>what it is</th></tr></thead><tbody>${page.other.map(n => `<tr><td class="mono">${esc(n.name)}</td><td>${esc(n.plain)}${n.defined_by.length ? ' (' + esc(n.defined_b … [line shortened here: 486 characters; full line on GitHub]
</div>
<script type="application/json" id="plan">${JSON.stringify(page).replace(/</g, '\\u003c')}</script>
<script>
(function () {
var plan = JSON.parse(document.getElementById('plan').textContent);
var $ = function (s) { return document.querySelector(s); };
var rows = {}; plan.plan.forEach(function (f) { rows[f.saved] = document.querySelector('tr[data-file="' + f.saved.replace(/"/g, '"') + '"] .res'); });
var current = null, errors = {};
function note(file, cls, text) { var r = rows[file]; if (!r) return; r.className = 'res ' + cls; r.textContent = text; }
window.addEventListener('error', function (e) {
var file = current; var src = e.filename || '';
plan.plan.forEach(function (f) { if (src && src.indexOf(f.saved) >= 0) file = f.saved; });
if (!file) return; errors[file] = (errors[file] || []).concat([(e.message || String(e.error || e))]);
note(file, 'bad', 'threw: ' + errors[file].join(' | '));
});
window.addEventListener('unhandledrejection', function (e) { if (!current) return; var m = e.reason && e.reason.message || String(e.reason); errors[current] = (errors[current] || []).concat([m]); note(current, 'bad', 'rejected: ' + errors[current].join(' | ')); });
plan.provided.forEach(function (n) { var el = document.querySelector('[data-provided="' + n + '"]'); var ok; try { ok = typeof window[n] !== 'undefined' || (n in window); } catch (x) { ok = false; } if (el) el.className = ok ? 'ok' : 'bad'; });
function applyInputs() {
var missing = [];
Array.prototype.forEach.call(document.querySelectorAll('input[data-need]'), function (i) {
var v = i.value.trim(), n = i.dataset.need;
if (!v) { missing.push(n); return; }
try { if (/^function|^class/.test(i.dataset.type)) window[n] = (0, eval)('(' + v + ')'); else if (/^library/.test(i.dataset.type)) window['__lib_' + n] = v; else { try { window[n] = JSON.parse(v); } catch (x) { window[n] = v; } } }
catch (x) { missing.push(n + ' (' + x.message + ')'); }
});
return missing;
}
function loadOne(f) {
return new Promise(function (resolve) {
current = f.saved;
var s = document.createElement('script'); if (f.kind === 'module') s.type = 'module'; s.src = f.saved;
s.onload = function () { setTimeout(function () { if (!errors[f.saved]) note(f.saved, 'ok', 'loaded'); current = null; resolve(); }, 0); };
s.onerror = function () { note(f.saved, 'bad', 'failed to load (not served, or a module that could not be fetched)'); current = null; resolve(); };
note(f.saved, 'wait', 'loading…'); document.body.appendChild(s);
});
}
function loadLib(url) { return new Promise(function (resolve) { var s = document.createElement('script'); s.src = url; s.onload = resolve; s.onerror = resolve; document.body.appendChild(s); }); }
$('#go').onclick = function () {
var missing = applyInputs();
var libs = Object.keys(window).filter(function (k) { return k.indexOf('__lib_') === 0; }).map(function (k) { return window[k]; });
$('#go').disabled = true; $('#state').textContent = missing.length ? 'loading without ' + missing.join(', ') : 'loading';
var q = Promise.resolve(); libs.forEach(function (u) { q = q.then(function () { return loadLib(u); }); });
plan.plan.filter(function (f) { return f.load; }).forEach(function (f) { q = q.then(function () { return loadOne(f); }); });
q.then(function () { var bad = Object.keys(errors).length, all = plan.plan.filter(function (f) { return f.load; }).length; $('#state').textContent = (all - bad) + ' of ' + all + ' file' + (all === 1 ? '' : 's') + ' loaded clean' + (bad ? '; ' + bad + ' threw' : '') + (missing.length ? '; still missing ' + missing.join(', ') : ''); $('#state').className = bad || missing.length ? 'amber' : 'ok'; … [line shortened here: 404 characters; full line on GitHub]
};
if (!plan.inputs.length && location.search.indexOf('auto') >= 0) $('#go').click();
})();
</script>
</html>
`;
writeFileSync(path.join(dir, 'index.html'), html);
// ---- REPORT.md
const md = [`# ${title}`, '', `Built ${stamp.slice(0, 16).replace('T', ' ')} UTC from ${parts.length} part${parts.length === 1 ? '' : 's'} of the [periodic table](https://ventusltd.github.io/stars/table.html). Open the [assembly page](${SITE}apps/${name}/index.html) to see what loads. Rebuild with:`, '', '```',
`node generate.mjs --name ${name}${blockSyms.length ? ' --blocks ' + blockSyms.join(',') : ''}${familyNums.length ? ' --families ' + familyNums.join(',') : ''}`, '```', ''];
md.push('## Bill of materials', '');
for (const p of parts) {
md.push(`### ${p.symbol ? p.symbol + ' · #' + p.number + ' · ' : '#' + p.family + ' · '}${p.title}`, '', p.description, '', `${p.functions} function${p.functions === 1 ? '' : 's'} inside${p.repos?.length ? ' · from ' + p.repos.map(r => r.split('/')[1]).join(', ') : ''}${p.depends_on?.length ? ' · loads after ' + p.depends_on.map(d => d.symbol + (bySym.has(d.symbol) ? '' : ' (not chosen)')).join( … [line shortened here: 418 characters; full line on GitHub]
md.push('| file | copied to | source |', '|---|---|---|');
for (const f of p.files) md.push(`| ${f.path} | ${f.saved || 'not copied: ' + f.error} | [${f.repo.split('/')[1]}](${f.link || ghUrl(f)}) |`);
md.push('');
}
md.push('## Load order', '', 'The assembly page loads the parts in this order: a block\'s dependencies among the chosen blocks first, then the order given.', '', ...plan.map((f, i) => `${i + 1}. \`${f.saved}\` (${f.part}${f.after.length ? ', after ' + f.after.join(', ') : ''}) — ${f.load ? f.kind : f.kind + ', not loaded'}`), '');
if (toWrite.length) md.push('## Still needed from outside', '', 'These names are used by the parts and defined nowhere in the table. Each is an input on the assembly page and a work order for the agents; the generator does not guess.', '', ...toWrite.map(n => `- \`${n.name}\` — ${n.type}; ${n.meaning}; used by ${n.used_by.join(', ')}${n.where[0] ? ` at [${n.where[0].path}:${n.where[0].line}](${n.w … [line shortened here: 595 characters; full line on GitHub]
const rest = needs.filter(n => n.kind !== 'missing' && n.kind !== 'library');
if (rest.length) md.push('## Other names the table listed', '', 'Listed as needs by the periodic table, but nothing is written for them, for the reason given.', '', '| name | what it is |', '|---|---|', ...rest.map(n => `| \`${n.name}\` | ${n.plain}${n.defined_by.length ? ' (' + n.defined_by.map(d => `[${d.symbol}](https://ventusltd.github.io/stars/table.html?block=${d.symbol})`).join(', ') + ')' … [line shortened here: 415 characters; full line on GitHub]
md.push('## Chemistry', '', ...pairs.map(p => `- ${p.a} + ${p.b}: ${p.verdict} (${Math.round(p.probability * 100)}%) — ${p.basis}${untested.includes(p) ? ` → work order ${orders.find(o => o.key === `pair:${p.a}+${p.b}`)?.id}` : ''}`), '');
md.push('## Open decisions', '', blockDecisions.length || needs.some(n => n.decisions.length) ? 'Judgement the engine cannot settle, held as records in the stars repository. An open record is a question; a decided record is permission.' : 'No decision record concerns these blocks.', '');
for (const d of blockDecisions) md.push(`- [${d.id}](${decisionUrl(d)}) · ${d.subject.key} · ${d.status} — ${d.question}`);
for (const n of needs) for (const d of n.decisions) if (!blockDecisions.some(x => x.id === d.id)) md.push(`- [${d.id}](${d.url}) · ${d.key} · ${d.status} — ${d.question} (concerns \`${n.name}\`)`);
md.push('', '## Work orders', '', orders.length ? `${orders.length} work order${orders.length === 1 ? '' : 's'} in [WORK-ORDERS.md](WORK-ORDERS.md), one request file each under \`requests/\`, raised as GitHub issues labelled \`work-order\`.` : 'None: nothing is missing and every pair has evidence.', '');
md.push('## Proof', '', 'Every file is fetched from GitHub at the exact commit the modular star recorded and copied unchanged. The workflow checks that each JavaScript file parses and that the assembly page declares an input for every missing name. That proves the app is assembled correctly, not that it is right for its new purpose; the assembly page, opened in a browser, shows which files load an … [line shortened here: 417 characters; full line on GitHub]
writeFileSync(path.join(dir, 'REPORT.md'), md.join('\n') + '\n');
// ---- WORK-ORDERS.md: the same requests in plain words, for a person
const wo = [`# Work orders — ${title}`, '', `Written ${stamp.slice(0, 16).replace('T', ' ')} UTC. Each order is one file under \`requests/\` and one GitHub issue labelled [work-order](https://github.com/${REPO}/issues?q=is%3Aissue+label%3Awork-order). An agent takes an order, writes the missing package as a new file in a repository, and the next hourly run of the star numbers it.`, ''];
if (!orders.length) wo.push('Nothing to write: every name is provided or defined, and every pair of blocks has evidence.', '');
for (const o of orders) {
wo.push(`## ${o.id} · ${o.title}`, '', `**What is missing.** \`${o.missing.name}\` — ${o.missing.type}. ${o.missing.meaning}`, '',
`**Where it will be used.** ${o.used_in.blocks.map(b => `${b.symbol} · #${b.number} · ${b.title}`).join('; ') || o.used_in.families.map(f => '#' + f).join(', ')}`, '');
if (o.used_in.files.length) wo.push(...o.used_in.files.slice(0, 8).map(f => `- [${f.path}${f.line ? ':' + f.line : ''}](${f.link}) at ${f.commit.slice(0, 7)}`), '');
wo.push(`**What it must provide.** ${o.must_provide.map(m => `\`${m.name}\` (${m.type})`).join(', ')}`, '', `**Acceptance.** ${o.acceptance}`, '');
if (o.decisions.length) wo.push(`**Decisions that bear on it.** ${o.decisions.map(u => `[${u.split('/').pop().replace('.json', '')}](${u})`).join(', ')}`, '');
wo.push(`**Brief.** ${o.brief}`, '', `Request file: \`requests/${o.id}.json\`${o.issue ? ` · issue [#${o.issue.number}](${o.issue.url})` : ''}`, '');
}
writeFileSync(path.join(dir, 'WORK-ORDERS.md'), wo.join('\n') + '\n');
// ---- Spider graph of every generated app and its blocks, on the same keys as the periodic table graph
const apps = readdirSync('apps', { withFileTypes: true }).filter(e => e.isDirectory() && existsSync(path.join('apps', e.name, 'parts.json'))).map(e => JSON.parse(readFileSync(path.join('apps', e.name, 'parts.json'), 'utf8')));
const nodes = [], edges = [], seen = new Set();
for (const a of apps) {
const open = (a.inputs || (a.needs || []).map(n => n.name || n));
nodes.push({ id: `app:${a.name}`, label: a.title, type: 'app', rag: open.length ? 'amber' : 'green', reason: `${a.parts.length} part(s)` + (open.length ? ` · still needs ${open.slice(0, 5).join(', ')}` : ' · complete') + (a.work_orders?.length ? ` · ${a.work_orders.length} work order(s)` : ''), gh: `https://github.com/${REPO}/tree/main/apps/${a.name}`, ext: `${SITE}apps/${a.name}/${a.load_order … [line shortened here: 434 characters; full line on GitHub]
for (const p of a.parts) {
if (!p.files) p.files = p.source ? [p.source] : []; // recipes written by the first version carry a single source
if (p.kind !== 'block') { p.kind = 'family'; p.functions = p.functions || 1; p.title = p.title || p.name || (await family(p.family))?.names?.[0] || '(unnamed family)'; }
const id = p.kind === 'block' ? `block:${p.symbol}` : `family:${p.family}`;
if (!seen.has(id)) { seen.add(id); nodes.push({ id, label: p.kind === 'block' ? `${p.symbol} · ${p.title}` : `#${p.family} ${p.title}`, type: p.kind, rag: 'green', reason: `${p.functions} function(s)`, gh: p.files[0] ? `https://github.com/${p.files[0].repo}/blob/${p.files[0].commit}/${p.files[0].path}` : null, ext: p.kind === 'block' ? `${STARS}table.html?block=${p.symbol}` : `${STARS}code.htm … [line shortened here: 427 characters; full line on GitHub]
edges.push({ from: `app:${a.name}`, to: id, type: 'made-of' });
}
for (const w of a.work_orders || []) { const id = `order:${w.id}`; if (!seen.has(id)) { seen.add(id); nodes.push({ id, label: w.title, type: 'work-order', rag: 'amber', reason: 'to be written by an agent', gh: `https://github.com/${REPO}/blob/main/requests/${w.id}.json`, ext: `https://github.com/${REPO}/issues?q=is%3Aissue+label%3Awork-order+${encodeURIComponent('"' + w.id + '"')}` }); } edges.p … [line shortened here: 456 characters; full line on GitHub]
}
mkdirSync('spider/graphs', { recursive: true });
writeFileSync('spider/graphs/apps.json', JSON.stringify({ schema: 'code-generator-graph.v1', label: 'Applications', generated_utc: stamp, nodes, edges }));
const q = s => JSON.stringify(s);
writeFileSync('spider/features.yml', ['# Graphs this repository publishes for the Spider dashboard. Written by generate.mjs.', 'schema_version: spider-features-v1', `site: ${q(SITE)}`, 'graphs:',
' - id: "generated-apps"', ' title: "Applications"', ` path: ${q(SITE + 'spider/graphs/apps.json')}`, ' edges_path: null', ' source_spider: "code-generator (generate.mjs)"',
` description: ${q('Apps built from blocks of the periodic table, wired to the blocks they are made of and the work orders still open. Amber apps still need values from their surroundings; the assembly page shows what loads.')}`, ` nodes: ${nodes.length}`, ` edges: ${edges.length}`].join('\n') + '\n');
console.log(`apps/${name}: ${parts.length} part(s), ${parts.reduce((s, p) => s + p.files.filter(f => f.saved).length, 0)} file(s) copied, ${plan.filter(f => f.load).length} loadable; ${toWrite.length} name(s) to be written, ${untested.length} untested pair(s), ${orders.length} work order(s).`);Code Generator — Index Page
A web page that draws reactions and presets, and uses data from the Stars repository. Published at https://ventusltd.github.io/code-generator/.
rendercode-generator / index.html · lines 1–166 of 166 · Entry point · pattern definers (shared by 2 files)
- What it does
- It draws reactions and presets. Defines 9 functions or classes, including $, esc, cat, fillBlocks, add. Side effects: changes the web page (DOM); makes network requests.
- Inputs & outputs
- In: data source: stars data; JSON file reactions.json; JSON file blocks.json; JSON file presets.json; form fields (user input). Out: web page.
- Downstream impact
- Used directly by 15 files: Pilot (globalgrid2050, https://globalgrid2050.com/testcode/wafer-development-environment/202609190330-cable-cross-sections/); Pilot (globalgrid2050); Pilot (globalgrid2050, https://globalgrid2050.com/testcode/wafer-development-environment/202609170036-estate/); Pilot (globalgrid2050, https://globalgrid2050.com/testcode/wafer-development-environment/202609180205-underground/); and 11 more. Reached from 375 other entry points, including 404 (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/404.html); Galaxies Wafers — App (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/); Galaxies Wafers — Index Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/). It is itself an entry point, published at https://ventusltd.github.io/code-generator/.
- What it achieves
- It is built from the fill blocks helper (`fillBlocks`), the add step (`add`) and the render step (`render`). Defines `esc`, `cat`, `fillBlocks` and 5 more.
- Why it matters
- Loaded by the Start page in Stars at https://ventusltd.github.io/stars/start.html and 3 other pages. Also imported by 11 files, including Pilot, Features and Lens Grammar Proof, from GlobalGrid2050.
- Application
- code-generator · / · page
- Uses
- Rules (import), Table (link), Stars — Index Page (estate URL)
- Used by
- named by URL in Pilot (estate URL), named by URL in Pilot (estate URL), named by URL in Pilot (estate URL), named by URL in Pilot (estate URL), named by URL in Pilot (estate URL), named by URL in Pilot (estate URL), linked from Start (link), linked from Table (link), and 7 more
- Produces
- $, esc, cat, fillBlocks, add, render, chemistry, build, definers
- Defines here
- $, esc, cat, fillBlocks, add, render, chemistry, build, definers
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e index.html:1-166 · blob b3844520c997451f12b6349e16c9673effdf8420 · 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">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Code generator</title>
<style>
:root{color-scheme:dark}
body{margin:0;padding:16px 18px 40px;background:#0b0d12;color:#eef2fb;font:15px/1.5 Inter,ui-sans-serif,system-ui,sans-serif}
a{color:#00e5ff}
h1{font-size:22px;margin:0 0 4px}
.ey{font-family:ui-monospace,monospace;font-size:11px;letter-spacing:.2em;text-transform:uppercase;color:#00e5ff}
.muted{color:#9aa3b5}
label{display:block;font-family:ui-monospace,monospace;font-size:11px;letter-spacing:.14em;text-transform:uppercase;color:#9aa3b5;margin:14px 0 6px}
select,input{width:100%;box-sizing:border-box;padding:11px 12px;background:#12151c;border:1px solid #262b36;color:inherit;font:inherit;border-radius:10px}
select{appearance:none;background-image:linear-gradient(45deg,transparent 50%,#9aa3b5 50%),linear-gradient(135deg,#9aa3b5 50%,transparent 50%);background-position:calc(100% - 18px) 55%,calc(100% - 13px) 55%;background-size:5px 5px;background-repeat:no-repeat}
.card{border:1px solid #262b36;border-radius:14px;padding:14px 16px;margin:12px 0;background:linear-gradient(160deg,rgba(255,255,255,.055),rgba(255,255,255,.014))}
.row{display:flex;gap:12px;flex-wrap:wrap}.row>*{flex:1 1 240px;min-width:0}
.btn{background:#0f1218;border:1px solid #385464;color:#eef2fb;padding:9px 14px;border-radius:999px;font:inherit;cursor:pointer;margin:8px 8px 0 0}
.btn:hover{border-color:#00e5ff}.btn.primary{border-color:#00e5ff;background:rgba(0,229,255,.12)}.btn:disabled{opacity:.4;cursor:not-allowed}
.part{border-left:3px solid var(--c,#262b36);padding:8px 12px;margin:8px 0;background:#0f1218;border-radius:0 10px 10px 0}
.part b{font-size:15px}.part .sym{font-family:ui-monospace,monospace;color:#9aa3b5;margin-right:6px}
.part .x{float:right;color:#9aa3b5;cursor:pointer}
.green{color:#39d353}.amber{color:#ffd54a}
details{margin-top:6px}summary{cursor:pointer;color:#9aa3b5;font-size:13px}
.inside{font-family:ui-monospace,monospace;font-size:12px;columns:2;column-gap:18px}
pre{background:#070910;border:1px solid #1a1f2a;border-radius:8px;padding:10px;overflow:auto;font-size:12px;max-height:40vh}
@media(max-width:600px){.inside{columns:1}}
</style>
<div class="ey">Ventus · Global Grid 2050 · Code generator</div>
<h1>Build an app from blocks</h1>
<div class="muted" id="status">Loading the periodic table…</div>
<div class="card">
<label for="preset">What are you building?</label>
<select id="preset"><option value="">Choose a starting point…</option></select>
<div class="row">
<div><label for="category">Category</label><select id="category"></select></div>
<div><label for="block">Block</label><select id="block"></select></div>
</div>
<button class="btn" id="add">Add this block</button>
</div>
<div class="card">
<label for="name">Name of the app</label>
<input id="name" value="my-app" placeholder="lowercase letters, digits and hyphens">
<div id="parts"><p class="muted">Nothing chosen yet. Pick a starting point above, or add blocks one at a time.</p></div>
<div id="needs"></div>
<button class="btn primary" id="build" disabled>Build it</button>
</div>
<div class="card" id="chem" hidden>
<label>Chemistry: will these blocks work together?</label>
<div id="pairs"></div>
<label>Apps that already mix these blocks</label>
<div id="likes"></div>
<div id="missing"></div>
</div>
<div class="card" id="out" hidden>
<label>Your app</label>
<p id="summary"></p>
<div class="row">
<div><label>Built from existing code</label><div id="built"></div></div>
<div><label>To be written</label><div id="todo"></div></div>
</div>
<button class="btn" id="copyCmd">Copy the build command</button><button class="btn" id="copyBom">Copy the bill of materials</button><button class="btn" id="orders">See the work orders on GitHub</button>
<pre id="bom"></pre>
<p class="muted">The build command makes the app durable in this repository: every block's files copied exactly from GitHub, an assembly page that loads them and shows what fails, a report, a recipe, and one work order for each thing to be written, raised as a GitHub issue labelled <code>work-order</code> for the agents. The bill of materials is the same thing in plain words.</p>
</div>
<p class="muted">Blocks come from the <a href="https://ventusltd.github.io/stars/table.html">periodic table of globalgrid2050 architecture development</a>. What a block still needs from its surroundings is listed, never guessed. Underneath every block are its numbered functions; you do not need to know them to build with it.</p>
<script type="module">
import { classify, PLAIN, LIBRARIES } from './rules.mjs';
const STARS = 'https://ventusltd.github.io/stars/';
const ORDERS = 'https://github.com/Ventusltd/code-generator/issues?q=is%3Aissue+label%3Awork-order';
const $ = s => document.querySelector(s);
const esc = s => String(s).replace(/[&<>"]/g, c => ({'&':'&','<':'<','>':'>','"':'"'}[c]));
let data, presets; const chosen = new Map();
const cat = id => data.categories.find(c => c.id === id);
function fillBlocks() {
const c = $('#category').value, s = $('#block'); s.innerHTML = '';
for (const b of data.blocks.filter(b => b.category === c && b.functions > 0 && (b.kind !== 'auto' || b.functions >= 8))) { const o = document.createElement('option'); o.value = b.symbol; o.textContent = `${b.title} (${b.functions} functions)`; s.append(o); }
}
function add(sym) { const b = data.blocks.find(x => x.symbol === sym); if (b && !chosen.has(sym)) { chosen.set(sym, b); render(); } }
function render() {
const p = $('#parts'); p.innerHTML = '';
for (const [sym, b] of chosen) {
const c = cat(b.category);
p.insertAdjacentHTML('beforeend', `<div class="part" style="--c:${c.colour}"><span class="x" data-x="${esc(sym)}">remove</span><span class="sym">${esc(sym)} · #${b.number}</span><b>${esc(b.title)}</b><div>${esc(b.description)}</div><div class="muted">${b.functions} functions · ${b.files.length} file${b.files.length === 1 ? '' : 's'}${b.repos.length ? ' · from ' + b.repos.map(r => esc(r.split(' … [line shortened here: 431 characters; full line on GitHub]
${b.inside.length ? `<details><summary>What is inside</summary><div class="inside">${b.inside.slice(0, 24).map(f => `<div><a href="${STARS}code.html?family=${f.family}" target="_blank" rel="noopener">#${f.family}</a> ${esc(f.name)}</div>`).join('')}</div></details>` : ''}</div>`);
}
p.querySelectorAll('.x').forEach(x => x.onclick = () => { chosen.delete(x.dataset.x); render(); });
if (!chosen.size) p.innerHTML = '<p class="muted">Nothing chosen yet. Pick a starting point above, or add blocks one at a time.</p>';
const have = new Set([...chosen.values()].flatMap(b => b.inside.map(f => f.name)));
const needs = [...new Map([...chosen.values()].flatMap(b => b.needs).filter(n => !have.has(n.name)).map(n => [n.name, n])).values()];
$('#needs').innerHTML = chosen.size ? (needs.length ? `<p><span class="amber">Still needed from outside:</span> ${needs.slice(0, 10).map(n => esc(n.meaning)).join('; ')}</p>` : '<p class="green">Complete: these blocks need nothing from outside.</p>') : '';
$('#build').disabled = !chosen.size;
chemistry();
}
let reactions = null;
async function chemistry() {
const c = $('#chem'); if (chosen.size < 1) { c.hidden = true; return; }
if (!reactions) { try { reactions = await (await fetch(STARS + 'blocks/reactions.json', {cache: 'no-cache'})).json(); } catch { return; } }
c.hidden = false;
const syms = [...chosen.keys()];
const verdictColour = { proven: '#39d353', 'seen together': '#00e5ff', unstable: '#ffd54a', fails: '#ff5555', untested: '#9aa3b5' };
const rows = [];
for (let i = 0; i < syms.length; i++) for (let j = i + 1; j < syms.length; j++) {
const r = reactions.reactions.find(x => (x.a === syms[i] && x.b === syms[j]) || (x.a === syms[j] && x.b === syms[i])) || { a: syms[i], b: syms[j], probability: 0.25, verdict: 'untested', basis: 'no evidence either way', examples: [] };
rows.push(r);
}
$('#pairs').innerHTML = rows.length ? rows.map(r => `<div class="part" style="--c:${verdictColour[r.verdict]}"><b>${esc(chosen.get(r.a).title)} + ${esc(chosen.get(r.b).title)}</b> <span style="color:${verdictColour[r.verdict]}">${Math.round(r.probability * 100)}% · ${esc(r.verdict)}</span><div class="muted">${esc(r.basis)}${r.decay ? ' · most common failure: ' + esc(r.decay) : ''}${r.examples[0] … [line shortened here: 637 characters; full line on GitHub]
const likes = reactions.apps.map(a => ({ a, overlap: a.blocks.filter(s => chosen.has(s)).length })).filter(x => x.overlap > 0).sort((x, y) => y.overlap - x.overlap || x.a.blocks.length - y.a.blocks.length).slice(0, 4);
$('#likes').innerHTML = likes.length ? likes.map(({ a, overlap }) => `<div class="part" style="--c:#b8ccff"><b>${esc(a.title)}</b> <span class="muted">shares ${overlap} of your block${overlap === 1 ? '' : 's'} · ${a.blocks.length} blocks in all</span><div>${a.live ? `<a href="${esc(a.live)}" target="_blank" rel="noopener">Open the live app</a> · ` : ''}<a href="${esc(a.gh)}" target="_blank" rel= … [line shortened here: 589 characters; full line on GitHub]
$('#likes').querySelectorAll('[data-sim]').forEach(el => el.onclick = e => { e.preventDefault(); chosen.clear(); for (const s of el.dataset.sim.split(',')) add(s); });
const untested = rows.filter(r => r.verdict === 'untested' || r.verdict === 'fails');
lastUntested = untested;
const have = new Set([...chosen.values()].flatMap(b => b.inside.map(f => f.name)));
const needs = [...new Map([...chosen.values()].flatMap(b => b.needs).filter(n => !have.has(n.name)).map(n => [n.name, n])).values()];
if (untested.length || needs.length) {
const prompt = `Test this combination of Ventus blocks for me. Blocks: ${[...chosen.values()].map(b => `${b.symbol} ${b.title} (${b.functions} functions; files: ${b.files.map(f => f.repo + '/' + f.path + '@' + f.commit.slice(0, 7)).join(', ')})`).join('; ')}. ` +
(untested.length ? `Untested pairs: ${untested.map(r => r.a + '+' + r.b).join(', ')}. ` : '') + (needs.length ? `Values still needed from outside: ${needs.map(n => n.name + ' (' + n.meaning + ')').join(', ')}. ` : '') +
'Write a small test page that loads these files together, report every error, and say which value each missing name must take. Do not change the files.';
$('#missing').innerHTML = `<label>What is missing</label><p><span class="amber">${untested.length ? untested.length + ' untested combination' + (untested.length === 1 ? '' : 's') : ''}${untested.length && needs.length ? ' and ' : ''}${needs.length ? needs.length + ' value' + (needs.length === 1 ? '' : 's') + ' still needed from outside' : ''}.</span> This is new ground: no app has done it yet. … [line shortened here: 526 characters; full line on GitHub]
$('#copyPrompt').onclick = () => navigator.clipboard.writeText(prompt).then(() => $('#copyPrompt').textContent = 'Copied');
} else $('#missing').innerHTML = '<p class="green">Every pair has evidence and nothing is missing.</p>';
}
function build() {
const name = ($('#name').value.trim() || 'my-app').toLowerCase().replace(/[^a-z0-9-]+/g, '-');
const syms = [...chosen.keys()];
const cmd = `gh workflow run generate.yml -R Ventusltd/code-generator -f name=${name} -f blocks=${syms.join(',')}`;
const bom = [`Bill of materials — ${name}`, ''].concat([...chosen.values()].map(b => `${b.symbol} #${b.number} ${b.title}\n ${b.description}\n ${b.functions} functions · files: ${b.files.map(f => f.repo.split('/')[1] + '/' + f.path).join(', ')}`)).join('\n');
$('#summary').innerHTML = `<b>${esc(name)}</b> from ${chosen.size} block${chosen.size === 1 ? '' : 's'}: ${[...chosen.values()].map(b => esc(b.title)).join(', ')}.`;
// Built from existing code: every chosen block, copied unchanged. To be written: what no block defines, and what no evidence covers.
$('#built').innerHTML = [...chosen.values()].map(b => `<div class="part" style="--c:${cat(b.category).colour}"><b>${esc(b.title)}</b> <span class="muted">${esc(b.symbol)} · ${b.functions} functions in ${b.files.length} file${b.files.length === 1 ? '' : 's'}, copied as they are</span></div>`).join('');
const have = new Set([...chosen.values()].flatMap(b => b.inside.map(f => f.name)));
const definers = nm => data.blocks.filter(b => !chosen.has(b.symbol) && b.kind !== 'auto' && b.inside.some(f => f.name === nm)).map(b => b.symbol);
const needs = [...new Map([...chosen.values()].flatMap(b => b.needs).filter(n => !have.has(n.name)).map(n => [n.name, n])).values()].map(n => ({ ...n, defs: definers(n.name), kind: classify(n.name, { definers: definers(n.name) }) }));
const todo = [];
for (const n of needs.filter(n => n.kind === 'library')) todo.push(`<div class="part" style="--c:#ffd54a"><b>${esc(n.name)}</b> <span class="muted">a library to supply: ${esc(LIBRARIES[n.name])}</span></div>`);
for (const n of needs.filter(n => n.kind === 'missing')) todo.push(`<div class="part" style="--c:#ffd54a"><b>${esc(n.name)}</b> <span class="muted">${esc(n.meaning !== n.name ? n.meaning : 'a value or function no block defines')} — to be written by an agent</span></div>`);
for (const n of needs.filter(n => n.kind === 'block')) todo.push(`<div class="part" style="--c:#00e5ff"><b>${esc(n.name)}</b> <span class="muted">already exists in block ${esc(n.defs.join(', '))}: add it rather than write it</span></div>`);
for (const r of lastUntested) todo.push(`<div class="part" style="--c:#ffd54a"><b>${esc(chosen.get(r.a).title)} + ${esc(chosen.get(r.b).title)}</b> <span class="muted">never loaded together: a test to be written and recorded</span></div>`);
const hidden = needs.filter(n => /^(browser|node|word)$/.test(n.kind)).length;
$('#todo').innerHTML = (todo.join('') || '<p class="green">Nothing: every name is provided and every pair has evidence.</p>') + (hidden ? `<p class="muted">${hidden} other name${hidden === 1 ? '' : 's'} the table lists are provided by the browser or are words from comments; the build sorts them and writes nothing for them.</p>` : '');
$('#bom').textContent = bom + '\n\n' + cmd; $('#out').hidden = false;
$('#copyCmd').onclick = () => navigator.clipboard.writeText(cmd).then(() => $('#copyCmd').textContent = 'Copied');
$('#copyBom').onclick = () => navigator.clipboard.writeText(bom).then(() => $('#copyBom').textContent = 'Copied');
$('#orders').onclick = () => window.open(ORDERS, '_blank', 'noopener');
}
let lastUntested = [];
(async () => {
try {
[data, presets] = await Promise.all([fetch(STARS + 'blocks/blocks.json', {cache: 'no-cache'}).then(r => r.json()), fetch(STARS + 'blocks/presets.json', {cache: 'no-cache'}).then(r => r.json())]);
const named = data.blocks.filter(b => b.kind !== 'auto').length;
$('#status').textContent = `${named} named blocks · ${data.blocks.reduce((s, b) => s + b.functions, 0).toLocaleString('en-GB')} functions underneath · table updated ${data.generated_utc.slice(0, 16).replace('T', ' ')} UTC`;
for (const p of presets.presets) { const o = document.createElement('option'); o.value = p.id; o.textContent = `${p.title} — ${p.blurb}`; $('#preset').append(o); }
for (const c of data.categories) if (data.blocks.some(b => b.category === c.id && b.functions > 0)) { const o = document.createElement('option'); o.value = c.id; o.textContent = c.title; $('#category').append(o); }
fillBlocks();
$('#category').onchange = fillBlocks; $('#add').onclick = () => add($('#block').value); $('#build').onclick = build;
$('#preset').onchange = () => { const p = presets.presets.find(x => x.id === $('#preset').value); if (!p) return; chosen.clear(); for (const s of p.blocks) add(s); $('#name').value = p.id; render(); };
const pre = new URLSearchParams(location.search).get('blocks'); if (pre) for (const s of pre.split(',')) add(s);
} catch (e) { $('#status').textContent = 'The periodic table is not reachable: ' + e.message; }
})();
</script>
</html>Rules
A JavaScript module in Code Generator that strips comments (`stripComments`). Served with the page at https://ventusltd.github.io/code-generator/.
storagecode-generator / rules.mjs · lines 1–73 of 73 · Entry point · pattern stripComments (shared by 2 files)
- What it does
- It maps its content. Defines classify, inferType, blank, stripComments, usageIn. Side effects: makes network requests; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- README: "`rules.mjs` holds the sorting of needs that the generator and the picker share"
- Inputs & outputs
- In: browser IndexedDB; DuckDB queries; user-supplied file (file picker).
- Downstream impact
- Used directly by 2 files: Generate (code-generator, https://ventusltd.github.io/code-generator/); Code Generator — Index Page (code-generator, https://ventusltd.github.io/code-generator/). Reached from 385 other entry points, including 404 (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/404.html); Galaxies Wafers — App (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/); Galaxies Wafers — Index Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/). It is itself an entry point, published at https://ventusltd.github.io/code-generator/.
- What it achieves
- It is built from the classify step (`classify`), the infer type helper (`inferType`) and the blank step (`blank`). Rules shared by the generator (Node) and the picker (browser): what a "need" is, and what to do about it.
- Why it matters
- Loaded by the Code Generator page at https://ventusltd.github.io/code-generator/. Also imported by Generate.
- Application
- code-generator · / · JavaScript module
- Uses
- none found
- Used by
- imported by Generate (import), imported by Code Generator — Index Page (import)
- Produces
- BROWSER, NODE, LIBRARIES, WORDS, classify, PLAIN, inferType, stripComments, usageIn
- Defines here
- classify, inferType, blank, stripComments, usageIn
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- code-generator@3897d83efcd0259d21dce87704b0c33118fe2c2e rules.mjs:1-73 · blob 927c7368fdd480f29a4735049721e231b3e8e8c2 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: network, storage · domain stage: unknown · users: none · canonical: supporting_data
// Rules shared by the generator (Node) and the picker (browser): what a "need" is, and what to do about it.
// A need is a name a block uses but does not define. The periodic table lists them; these rules sort them:
// browser — the web browser provides it (document, fetch, Blob …): nothing to write, the assembly page checks it
// node — Node.js provides it (Buffer, process …): the file is a Node script, not a page part
// library — a known third-party library global (maplibregl …): a script tag supplies it; raised as a work order
// block — another block of the table defines it: add that block rather than write anything
// defined — the copied files declare it themselves (a parameter or local the table's scan mistook): nothing to do
// word — appears only in comments or prose, never as code: not a need
// missing — used as code, defined nowhere: a value or function to be written; an input on the page, a work order
export const BROWSER = new Set(('window document navigator location history localStorage sessionStorage indexedDB caches screen devicePixelRatio innerWidth innerHeight ' +
'fetch Request Response Headers Blob File FileReader FileList URL URLSearchParams FormData Worker SharedWorker XMLHttpRequest WebSocket EventSource BroadcastChannel MessageChannel ' +
'Event CustomEvent EventTarget ErrorEvent MessageEvent MouseEvent PointerEvent TouchEvent KeyboardEvent WheelEvent DragEvent InputEvent FocusEvent PopStateEvent HashChangeEvent StorageEvent ' +
'MutationObserver ResizeObserver IntersectionObserver PerformanceObserver performance requestAnimationFrame cancelAnimationFrame requestIdleCallback cancelIdleCallback ' +
'setTimeout setInterval clearTimeout clearInterval queueMicrotask structuredClone atob btoa crypto alert confirm prompt getComputedStyle matchMedia scrollTo scrollBy open close focus blur print postMessage addEventListener removeEventListener dispatchEvent ' +
'createImageBitmap ImageBitmap ImageCapture Image Audio Video HTMLElement HTMLImageElement HTMLCanvasElement HTMLInputElement Element Node NodeList DocumentFragment DOMParser XMLSerializer Range Selection DOMRect Path2D CanvasRenderingContext2D OffscreenCanvas ' +
'CompressionStream DecompressionStream ReadableStream WritableStream TransformStream TextEncoder TextDecoder AbortController AbortSignal ' +
'Notification MediaRecorder MediaStream AudioContext ClipboardItem ServiceWorker Cache Storage CSS customElements WebAssembly SharedArrayBuffer ' +
'console Intl JSON Math Date Promise Map Set WeakMap WeakSet WeakRef Symbol Proxy Reflect Array Object String Number Boolean RegExp Error TypeError RangeError SyntaxError BigInt ArrayBuffer DataView ' +
'Uint8Array Uint16Array Uint32Array Int8Array Int16Array Int32Array Float32Array Float64Array globalThis self parent top frames isNaN isFinite parseInt parseFloat encodeURIComponent decodeURIComponent encodeURI decodeURI undefined NaN Infinity').split(/\s+/));
export const NODE = new Set('Buffer process require module exports __dirname __filename global setImmediate clearImmediate'.split(' '));
export const LIBRARIES = { maplibregl: 'MapLibre GL JS, the map library', mapboxgl: 'Mapbox GL JS', L: 'Leaflet', d3: 'D3', THREE: 'three.js', duckdb: 'DuckDB-Wasm', Chart: 'Chart.js', Papa: 'PapaParse', JSZip: 'JSZip', pako: 'pako', turf: 'Turf.js', proj4: 'proj4', Vue: 'Vue', React: 'React', ReactDOM: 'ReactDOM', jQuery: 'jQuery', $: 'jQuery', mermaid: 'Mermaid', Plotly: 'Plotly', Cesium: 'Cesiu … [line shortened here: 423 characters; full line on GitHub]
// English function words and prose that the table's scan sometimes reads as names. Never a need.
export const WORDS = new Set('a an and the is are was were be been has have had not no that this these those it its until then than when where which who what why how seen first last never again actually genuinely leave leaves produced stranded visible outcome arrival into from with for of to in on at by as or if else so do does did can could may might must shall should will would there here also o … [line shortened here: 466 characters; full line on GitHub]
// Sort one need. `usage` is what the generator found in the copied files ({ used, declared, how, line, mentioned }); the picker has no files, so it passes null.
export function classify(name, { definers = [], usage = null } = {}) {
if (BROWSER.has(name)) return 'browser';
if (NODE.has(name)) return 'node';
if (name in LIBRARIES) return 'library';
if (definers.length) return 'block';
if (usage) { if (usage.declared) return 'defined'; if (WORDS.has(name)) return 'word'; if (!usage.used) return usage.mentioned ? 'word' : 'absent'; return 'missing'; }
// No files to look at: a plain lowercase dictionary-looking word is prose, anything with capitals, digits or underscores is a name.
return WORDS.has(name) || /^[a-z]{1,12}$/.test(name) ? 'word' : 'missing';
}
export const PLAIN = {
browser: 'provided by the web browser', node: 'provided by Node.js, not by a web page', library: 'a library a script tag must supply',
block: 'defined by another block of the table: add it', defined: 'declared inside the copied files; nothing to write', word: 'a word from comments or text, not code',
absent: 'not in the copied files; the table saw it in another version of the block', missing: 'used but defined nowhere: to be written'
};
// Guess a type from how a name is used: `new X(` a class, `X(` a function, `X.` or `X[` an object, ALL_CAPS a constant.
export function inferType(name, how) {
if (name in LIBRARIES) return 'library (global object)';
if (how === 'new') return 'class';
if (how === 'call') return 'function';
if (how === 'member') return 'object';
if (/^[A-Z][A-Z0-9_]+$/.test(name)) return /_ID$|_CLASS$|_KEY$|_NAME$|_URL$|_PATH$/.test(name) ? 'constant (string)' : 'constant';
return 'value';
}
// Blank out comments and string literals (newlines kept, so line numbers hold) so prose does not count as code. Rough by design.
const blank = m => m.replace(/[^\n]/g, ' ');
export function stripComments(text, isPython) {
if (isPython) return text.replace(/"""[\s\S]*?"""|'''[\s\S]*?'''/g, blank).replace(/(^|[^\\])#.*$/gm, '$1').replace(/"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'/g, blank);
return text.replace(/\/\*[\s\S]*?\*\//g, blank).replace(/(^|[^:\\'"`])\/\/.*$/gm, '$1').replace(/`(?:[^`\\]|\\.)*`/g, blank).replace(/"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'/g, blank);
}
// Where and how a name is used in one file (comments and strings removed). Returns { mentioned } when it appears only in prose, null when absent.
export function usageIn(name, text, isPython) {
const code = stripComments(text, isPython);
const esc = name.replace(/[$]/g, '\\$');
const id = new RegExp(`(?<![\\w$.])${esc}(?![\\w$])`);
const viaWindow = new RegExp(`\\b(?:window|globalThis|self)\\.${esc}(?![\\w$])`);
const lines = code.split('\n');
let first = -1;
for (let i = 0; i < lines.length; i++) if (id.test(lines[i]) || viaWindow.test(lines[i])) { first = i + 1; break; }
if (first < 0) return new RegExp(`(?<![\\w$])${esc}(?![\\w$])`).test(text) ? { used: false, mentioned: true } : null;
const declared = new RegExp(`\\b(?:const|let|var|function|class|def|import)\\s+(?:\\*\\s+as\\s+)?${esc}(?![\\w$])|(?<![\\w$.])${esc}\\s*=[^=>]|\\(([^()]*(?<![\\w$.])${esc}(?![\\w$])[^()]*)\\)\\s*(?:=>|\\{|:|->)|(?<![\\w$.])${esc}\\s*=>|\\{[^{}]*(?<![\\w$.])${esc}(?![\\w$])[^{}]*\\}\\s*=[^=]|\\bfor\\s*\\(\\s*(?:const|let|var)?\\s*${esc}\\b|\\bfor\\s+${esc}\\s+in\\b|\\bcatch\\s*\\(\\s*${esc}\\s*\\ … [line shortened here: 441 characters; full line on GitHub]
const how = new RegExp(`\\bnew\\s+${esc}\\s*\\(`).test(code) ? 'new' : new RegExp(`(?<![\\w$.])${esc}\\s*\\(`).test(code) ? 'call' : new RegExp(`(?<![\\w$.])${esc}\\s*[.\\[]`).test(code) ? 'member' : 'value';
return { used: true, declared, how, line: first };
}Compass
A JavaScript module that simulates step (`simulateStep`). It simulates step (`simulateStep`) and is built from the valid step (`valid`) and the mode of helper (`modeOf`).
transformcompass / src/compass.mjs · lines 1–68 of 68 · pattern overlay (shared by 4 files)
- What it does
- It calculates its inputs. Defines 8 functions or classes, including valid, modeOf, ambiguous, evaluate, simulateStep.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'compass'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- Downstream impact
- Used directly by 1 file: Compass Test (compass). Reached from 1 other entry point, including Verify Workflow (compass).
- What it achieves
- New adapter; all historical source modules remain byte-identical.
- Why it matters
- Checked by Compass Test.
- Application
- compass · src · JavaScript module
- Uses
- Heading (import), Route Follower (import), Position Overlay (import), ../upstream/tools/satnav/vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/nav/compass.mjs, ../upstream/tools/satnav/vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/vendor/grid-distance-maths/src/geodesy.mjs
- Used by
- imported by Compass Test (import)
- Produces
- MODEL, MAX_BATCH, evaluate, simulateStep, evaluateBatch, tracking, overlay
- Defines here
- valid, modeOf, ambiguous, evaluate, simulateStep, evaluateBatch, tracking, overlay
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- compass@e200c888acbcc7af59d7cc38b29806e90b0a50db src/compass.mjs:1-68 · blob b7e1c44a0283fe92af2b67de3c1eb930f8ac6628 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unknown
// SPDX-License-Identifier: Apache-2.0
// New adapter; all historical source modules remain byte-identical.
import { guide, fixQuality } from '../upstream/tools/satnav/vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/nav/compass.mjs';
import * as maths from '../upstream/tools/satnav/vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/vendor/grid-distance-maths/src/geodesy.mjs';
import { deviceHeading } from '../upstream/tools/satnav/orientation/heading.mjs';
import { createRouteFollower } from '../upstream/tools/satnav/line/route-follower.mjs';
import { createPositionOverlay } from '../upstream/tools/satnav/line/position-overlay.mjs';
export { deviceHeading, fixQuality };
export const MODEL = 'historical-grid-distance-maths/R_ATLAS';
export const MAX_BATCH = 10000;
const valid = p => Array.isArray(p) && p.length === 2 && p.every(Number.isFinite) && Math.abs(p[0])<=180 && Math.abs(p[1])<=90;
function modeOf(mode) {
if (!['observed','simulated','replay'].includes(mode)) throw new Error('INVALID_POSITION_SOURCE');
return mode;
}
function ambiguous(from,to) {
const delta = ((to[0]-from[0])%360+360)%360;
return Math.abs(from[1])===90 || (Math.abs(delta-180)<1e-9 && Math.abs(from[1]+to[1])<1e-9) ||
(Math.abs(to[1])===90 && Math.abs(from[1]+to[1])<1e-9);
}
export function evaluate({mode,fix,target,nowMs}) {
modeOf(mode);
if (!Number.isFinite(nowMs)) throw new Error('EXPLICIT_CLOCK_REQUIRED');
const status = fixQuality(fix,nowMs);
const result = {mode,status,model:MODEL,reference:'true-geographic',trackingOnly:true,accessStatus:'unverified',guidance:null};
if (status!=='usable') return result;
if (!valid(target?.coordinates)) return {...result,status:'invalid_target'};
const g = guide(fix,target,nowMs);
if (g && ambiguous([fix.longitude,fix.latitude],target.coordinates)) {
return {...result,status:'bearing_undetermined',guidance:{...g,bearingDeg:null}};
}
return {...result,guidance:g};
}
export function simulateStep({longitude,latitude,distanceM,bearingDeg,timestampMs,accuracyM=0}) {
if(!valid([longitude,latitude])||!Number.isFinite(distanceM)||distanceM<0||distanceM>100000||
!Number.isFinite(bearingDeg)||bearingDeg<0||bearingDeg>=360||!Number.isFinite(timestampMs)||
!Number.isFinite(accuracyM)||accuracyM<0) throw new Error('INVALID_SIMULATION_STEP');
if (Math.abs(latitude)===90 && distanceM>0) throw new Error('POLAR_HEADING_UNDEFINED');
const at=distanceM===0?[longitude,latitude]:maths.destinationPoint(longitude,latitude,distanceM/1000,bearingDeg);
// The historical direct formula may return an unwrapped longitude.
at[0]=((at[0]+180)%360+360)%360-180;
if (!valid(at)) throw new Error('INVALID_SIMULATED_RESULT');
return {mode:'simulated',fix:{longitude:at[0],latitude:at[1],accuracyM,timestampMs}};
}
export function evaluateBatch(requests) {
if(!Array.isArray(requests)||requests.length>MAX_BATCH) throw new Error('BATCH_LIMIT');
return requests.map(evaluate);
}
export function tracking(geometry) {
const locate=createRouteFollower(geometry,maths);
return ({mode,fix,nowMs})=>{
modeOf(mode);
if (!Number.isFinite(nowMs)) throw new Error('EXPLICIT_CLOCK_REQUIRED');
return {...locate(fix,nowMs),mode,model:MODEL,trackingOnly:true,accessStatus:'unverified'};
};
}
export function overlay(coordinates) {
const locate=createPositionOverlay(coordinates,maths);
return ({mode,fix,nowMs})=>{
modeOf(mode);
if (!Number.isFinite(nowMs)) throw new Error('EXPLICIT_CLOCK_REQUIRED');
const out=locate(fix,nowMs);
// Historical overlay uses measured-gps labels: never display simulated data as observed.
return {mode,model:MODEL,metrics:{...out.metrics,mode,trackingOnly:true,accessStatus:'unverified'},
features:out.features.map(f=>({...f,properties:{...f.properties,positionSource:mode,
role:mode==='observed'?f.properties.role:({'measured-gps':mode+'-position','gps-accuracy':mode+'-accuracy'}[f.properties.role]??f.properties.role)}}))};
};
}