In this section
- Check Graph ingest · stars / tools/check-graph.mjs lines 1–82
- Needs Audit storage · stars / tools/needs-audit.mjs lines 1–76
- Pages Check ingest · stars / tools/pages-check.mjs lines 1–76
- Run Log other · stars / tools/run-log.mjs lines 1–39
- Status ingest · stars / tools/status.mjs lines 1–59
- Check Policy ingest · stones / tools/check-policy.mjs lines 1–60
- Verify ingest · testcode / sandbox/202609141527-numbered-universe/verify.mjs lines 1–18
- View interaction · testcode / sandbox/202609141552-numbered-universe/view.js lines 1–26
- Sandbox — Galaxy Bond interaction · testcode / sandbox/202609151802-galaxy-bond/app.mjs lines 1–73
Check Graph
A JavaScript module in the tools folder of Stars that checks a Spider graph the way the dashboard's receiver reads it (ventus-grid-engine `index.html`, ids resolve; rag in green|amber|red|blue|grey.
ingeststars / tools/check-graph.mjs · lines 1–82 of 82 · Entry point
- What it does
- It fetches data. Uses libraries node:fs. Side effects: reads or writes files; makes network requests; starts processes.
- Why it exists in the grid workflow
- README: "The Modular star workflow runs `check-graph.mjs` on `modular/graph.json` and `blocks/graph.json` after the blocks are built, so a graph the dashboard could not read fails the run before it is published."
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- Used directly by 2 files: Decisions Workflow (stars); Modular Star Workflow (stars).
- What it achieves
- The README says: The Modular star workflow runs `check-graph.mjs` on `modular/graph.json` and `blocks/graph.json` after the blocks are built, so a graph the dashboard could not read fails the run before it is published.
- Why it matters
- Run by Decisions Workflow and Modular Star Workflow.
- Application
- stars · tools · JavaScript module
- Uses
- node:fs
- Used by
- run by Decisions Workflow (workflow run), run by Modular Star Workflow (workflow run)
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- stars@030ebc202d35959fecd162327892f671d1d9a0cc tools/check-graph.mjs:1-82 · blob 4463bd0de07080609f74e9b3d55848fd4f4d8824 · GitHub at these lines
- State
- achieves: readme · context: readme_derived · stage: ingest · effects: filesystem, network, process · domain stage: unknown · users: none · canonical: unknown
// Check a Spider graph the way the dashboard's receiver reads it (ventus-grid-engine index.html,
// normaliseGenericGraph): nodes {id, label, type, rag, reason, gh, ext}; edges {from, to, type} or [from, to, type];
// ids resolve; rag in green|amber|red|blue|grey. The receiver drops what it cannot resolve without a word, so this
// script says it instead. Usage: node tools/check-graph.mjs <file-or-url> [--strict]
// Exits 1 on a structural fault (unparseable, no nodes, unlabelled node, duplicate id, dangling edge, bad rag);
// the size limit and the length limits are warnings unless --strict.
import { readFileSync } from 'node:fs';
const src = process.argv[2], strict = process.argv.includes('--strict');
if (!src) { console.log('Usage: node tools/check-graph.mjs <file-or-url> [--strict]'); process.exit(2); }
const RAG = new Set(['green', 'amber', 'red', 'blue', 'grey']);
const LIMIT = 600 * 1024, LABEL_MAX = 120, REASON_MAX = 4000;
const faults = [], warnings = [];
let bytes;
try { bytes = /^https?:/.test(src) ? Buffer.from(await (await fetch(src, { cache: 'no-store' })).arrayBuffer()) : readFileSync(src); }
catch (e) { console.log(`${src}: cannot read: ${e.message}`); process.exit(1); }
let raw;
try { raw = JSON.parse(bytes.toString('utf8').replace(/^/, '')); } catch (e) { console.log(`${src}: not JSON: ${e.message}`); process.exit(1); }
const rawNodes = Array.isArray(raw.nodes) ? raw.nodes : Array.isArray(raw.features) ? raw.features.map(f => ({ id: f.id, ...(f.properties || {}) })) : null;
if (!rawNodes) faults.push('no nodes array (the receiver shows a grey placeholder card)');
const nodes = rawNodes || [];
if (rawNodes && !nodes.length) faults.push('nodes is empty (the receiver treats an empty graph as unreachable)');
const ids = new Map(), dupes = [];
let noId = 0, noGh = 0, noExt = 0, badRag = 0, longLabel = 0, longReason = 0, unlabelled = 0, scripts = 0, longestReason = 0;
nodes.forEach((n, i) => {
const id = n.id !== undefined ? n.id : i;
if (n.id === undefined) noId++;
if (ids.has(id)) dupes.push(String(id)); else ids.set(id, i);
const label = n.label || n.title || (n.id !== undefined ? String(n.id) : '');
if (!label) unlabelled++;
if (label.length > LABEL_MAX) longLabel++;
const rag = n.rag || n.status || 'grey';
if (!RAG.has(rag)) badRag++;
const reason = String(n.reason || n.status_reason || n.path || '');
longestReason = Math.max(longestReason, reason.length);
if (reason.length > REASON_MAX) longReason++;
if (/<script|javascript:/i.test(reason)) scripts++; // reason is rendered as HTML by the focused card
if (!n.gh) noGh++;
if (!n.ext) noExt++;
});
const rawEdges = Array.isArray(raw.edges) ? raw.edges : Array.isArray(raw.links) ? raw.links : [];
const types = new Map(), dangling = [];
let selfEdges = 0, arrayForm = 0, objectForm = 0;
for (const e of rawEdges) {
let a, b, t;
if (Array.isArray(e)) { arrayForm++; [a, b] = e; t = e[2] || 'repo'; }
else { objectForm++; a = e.from !== undefined ? e.from : e.source; b = e.to !== undefined ? e.to : e.target; t = e.type || 'repo'; }
// The receiver resolves a reference by id first, then treats it as an index if it is a number.
const ra = ids.has(a) ? ids.get(a) : a, rb = ids.has(b) ? ids.get(b) : b;
const ok = typeof ra === 'number' && ra >= 0 && ra < nodes.length && typeof rb === 'number' && rb >= 0 && rb < nodes.length;
if (!ok) { if (dangling.length < 5) dangling.push(`${a} -> ${b}`); else dangling.push(''); continue; }
if (ra === rb) selfEdges++;
types.set(t, (types.get(t) || 0) + 1);
}
const danglingCount = dangling.length;
if (dupes.length) faults.push(`${dupes.length} duplicate id(s): ${[...new Set(dupes)].slice(0, 5).join(', ')} (edges would attach to the last node with that id)`);
if (danglingCount) faults.push(`${danglingCount} dangling edge(s) dropped by the receiver, e.g. ${dangling.filter(Boolean).slice(0, 3).join('; ')}`);
if (badRag) faults.push(`${badRag} node(s) with a rag outside green|amber|red|blue|grey`);
if (unlabelled) faults.push(`${unlabelled} node(s) with no label, title or id`);
if (noId) (raw.adapted_for ? warnings : faults).push(`${noId} node(s) without an id (the receiver uses the index; spider/register.py adapts such graphs)`);
if (scripts) faults.push(`${scripts} reason(s) contain a script tag or javascript: URL; reason is rendered as HTML`);
if (bytes.length > LIMIT) (strict ? faults : warnings).push(`${Math.round(bytes.length / 1024)} KB is over the 600 KB registry limit: spider/register.py will not register it`);
else if (bytes.length > LIMIT * 0.9) warnings.push(`${Math.round(bytes.length / 1024)} KB is ${Math.round(100 * bytes.length / LIMIT)}% of the 600 KB registry limit`);
if (longLabel) (strict ? faults : warnings).push(`${longLabel} label(s) over ${LABEL_MAX} characters`);
if (longReason) (strict ? faults : warnings).push(`${longReason} reason(s) over ${REASON_MAX} characters (longest ${longestReason})`);
if (selfEdges) warnings.push(`${selfEdges} self-edge(s)`);
if (noGh) warnings.push(`${noGh} node(s) without gh (no GitHub action on the card)`);
if (noExt) warnings.push(`${noExt} node(s) without ext (no External action on the card)`);
const nodeTypes = new Map(); for (const n of nodes) nodeTypes.set(n.type || 'unknown', (nodeTypes.get(n.type || 'unknown') || 0) + 1);
const ragCount = new Map(); for (const n of nodes) { const r = n.rag || 'grey'; ragCount.set(r, (ragCount.get(r) || 0) + 1); }
console.log(`${src}: ${raw.label || raw.schema || 'graph'} · ${Math.round(bytes.length / 1024)} KB · generated ${raw.generated_utc || 'undated'}`);
console.log(` ${nodes.length} nodes (${[...nodeTypes].map(([t, c]) => `${c} ${t}`).join(', ')}); rag ${[...ragCount].map(([r, c]) => `${c} ${r}`).join(', ')}`);
console.log(` ${rawEdges.length} edges (${objectForm} object form, ${arrayForm} index form): ${[...types].sort((a, b) => b[1] - a[1]).map(([t, c]) => `${c} ${t}`).join(', ') || 'none'}`);
console.log(` FOCUS order, first 12: ${nodes.slice(0, 12).map((n, i) => `${i + 1}. ${String(n.label || n.title || n.id || '').slice(0, 48)}`).join(' · ')}`);
for (const w of warnings) console.log(` warning: ${w}`);
for (const f of faults) console.log(` FAULT: ${f}`);
console.log(faults.length ? ` ${faults.length} fault(s): the dashboard would not show this graph as written.` : ' Readable by the receiver.');
process.exitCode = faults.length ? 1 : 0; // not process.exit(): on Windows that races an open fetch socket and aborts with a libuv assertionNeeds Audit
A JavaScript module in the tools folder of Stars that fetches blocks catalogue. It is built from the arg step (`arg`).
storagestars / tools/needs-audit.mjs · lines 1–76 of 76 · Not reached from any entry point (candidate for review)
- What it does
- It fetches blocks catalogue. Defines arg. Uses libraries node:fs, node:path, node:url. Side effects: reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
- Inputs & outputs
- In: JSON file blocks-catalogue.json; JSON file index.json; command-line arguments.
- What it achieves
- Audit of "needs": the names functions need from outside their own file, across every family record in `code/f/*.json`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- stars · tools · JavaScript module
- Uses
- Stars — Index Page (estate URL), node:fs, node:path, node:url
- Used by
- none found
- Produces
- arg
- Defines here
- arg
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- stars@030ebc202d35959fecd162327892f671d1d9a0cc tools/needs-audit.mjs:1-76 · blob 83d1f4ff592c8bc339fa8e175c3cfbe84518afc3 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network, storage · domain stage: unknown · users: none · canonical: unreached_review
// Audit of "needs": the names functions need from outside their own file, across every family record in code/f/*.json.
// Lists the most common names, marks the ones that are browser or Node built-ins (candidates for the known-globals
// list in modular-star/lib.mjs) and the ones with no plain-words entry in modular-star/blocks-catalogue.json.
// Reports only; edits nothing. Usage: node tools/needs-audit.mjs [--live] [--top 60]
// --live reads the published files from GitHub Pages instead of the local checkout. Exits 1 only if the records cannot be read.
import { readFileSync, readdirSync, existsSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const arg = (k, d) => { const i = process.argv.indexOf('--' + k); return i > 0 ? process.argv[i + 1] : d; };
const TOP = Number(arg('top', 60)), live = process.argv.includes('--live');
const SITE = 'https://ventusltd.github.io/stars/';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
// What lib.mjs already ignores, read from its source so the list is never copied by hand.
const libSrc = readFileSync(path.join(root, 'modular-star', 'lib.mjs'), 'utf8');
const globalsSrc = libSrc.slice(libSrc.indexOf('const GLOBALS'), libSrc.indexOf('.split', libSrc.indexOf('const GLOBALS')));
const KNOWN = new Set(globalsSrc.replace(/\/\/[^\n]*/g, '').match(/'([^']*)'/g).flatMap(s => s.slice(1, -1).split(' ')).filter(Boolean));
const words = JSON.parse(readFileSync(path.join(root, 'modular-star', 'blocks-catalogue.json'), 'utf8')).needs_words || {};
// Built-ins: everything Node 24 puts on globalThis, plus the browser names a page always has.
const NODE = new Set(Object.getOwnPropertyNames(globalThis).concat(['require', 'module', 'exports', '__dirname', '__filename']));
const BROWSER = new Set(('window document navigator location localStorage fetch CSS customElements DOMException DOMRect DOMRectReadOnly Range Selection Text Comment DocumentFragment NodeFilter NodeList ' +
'Option Notification AudioContext MediaRecorder MediaStream MediaSource SpeechSynthesisUtterance speechSynthesis Geolocation WebAssembly eval arguments escape unescape ' +
'CanvasRenderingContext2D WebGLRenderingContext WebGL2RenderingContext ImageBitmapRenderingContext SVGElement Animation KeyframeEffect ClipboardItem clipboard ' +
'scrollTo scrollBy scrollX scrollY innerWidth innerHeight outerWidth outerHeight pageXOffset pageYOffset opener ' +
'addEventListener removeEventListener dispatchEvent postMessage visualViewport styleMedia onload onerror onresize onhashchange onpopstate ' +
'setImmediate clearImmediate reportError isSecureContext crossOriginIsolated').split(' '));
// Window properties that are also everyday variable names (status, name, open, close, top, parent, origin, event) are left out on purpose:
// as needs they almost always mean a real variable the file lacks, and the known-globals list must not hide those.
const looksBuiltIn = n => NODE.has(n) || BROWSER.has(n) || /^(HTML|SVG|DOM|CSS|Web|RTC|Media|Audio|Speech|Canvas|WebGL|Intl|Geo|Performance|Idle|Payment|Push|Service|Shared|Broadcast|Message|Storage|Text|Trusted|Screen|Window|Worker|Xml|XML|USB|Bluetooth|Gamepad|Sensor|Presentation|Credential|Navigator|Location)[A-Z]/.test(n) || /[a-z](Event|Element|Observer|Error|Stream|Registry|Node|Worker|Chann … [line shortened here: 414 characters; full line on GitHub]
// ---- read every family record
let records = [];
try {
if (live) {
const index = await (await fetch(SITE + 'code/index.json', { cache: 'no-store' })).json();
for (const b of index.buckets) records.push(...Object.values(await (await fetch(`${SITE}code/f/${b}.json`, { cache: 'no-store' })).json()));
} else {
const dir = path.join(root, 'code', 'f');
if (!existsSync(dir)) throw new Error('code/f is not in this checkout: run the build or pass --live');
for (const f of readdirSync(dir)) records.push(...Object.values(JSON.parse(readFileSync(path.join(dir, f), 'utf8'))));
}
} catch (e) { console.log(`Cannot read the family records: ${e.message}`); process.exitCode = 1; records = null; }
if (!records) { /* nothing to audit */ } else {
const outside = new Map(), inside = new Map(), stand = new Map();
let withNeeds = 0;
for (const r of records) {
if (r.needs?.length) withNeeds++;
for (const n of r.needs || []) outside.set(n, (outside.get(n) || 0) + 1);
for (const n of r.needs_in_function || []) inside.set(n, (inside.get(n) || 0) + 1);
if (r.standalone) stand.set('yes', (stand.get('yes') || 0) + 1);
}
const top = [...outside].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, TOP);
// A built-in that already has plain words (document, window, fetch...) is a deliberate need: a copied file really does need a page.
const builtins = top.filter(([n]) => looksBuiltIn(n) && !KNOWN.has(n) && !words[n]);
const alreadyKnown = [...outside].filter(([n]) => KNOWN.has(n));
const wordless = top.filter(([n]) => !looksBuiltIn(n) && !words[n]);
console.log(`Needs audit (${live ? 'published' : 'local'} records): ${records.length} families, ${withNeeds} need something from outside their file, ${stand.get('yes') || 0} self-contained.`);
console.log(`${outside.size} distinct names needed outside the file; ${inside.size} distinct names needed inside the function (before the file's own declarations are subtracted).\n`);
console.log(`Top ${top.length} names needed outside the file (families · name · marks):`);
for (const [n, c] of top) {
const marks = [];
if (KNOWN.has(n)) marks.push('in the known-globals list already (record older than the list)');
else if (looksBuiltIn(n) && !words[n]) marks.push('built-in: candidate for the known-globals list');
if (words[n]) marks.push(`plain words: "${words[n]}"`);
else if (!looksBuiltIn(n)) marks.push('no plain words');
console.log(` ${String(c).padStart(5)} ${n.padEnd(28)} ${marks.join(' · ')}`);
}
console.log(`\nCandidates for the known-globals list in modular-star/lib.mjs (${builtins.length}): ${builtins.map(([n, c]) => `${n} (${c})`).join(', ') || 'none'}`);
console.log(`Candidates for plain words in modular-star/blocks-catalogue.json (${wordless.length}): ${wordless.map(([n, c]) => `${n} (${c})`).join(', ') || 'none'}`);
if (alreadyKnown.length) console.log(`Names in the known-globals list that still appear as needs (${alreadyKnown.length}): ${alreadyKnown.map(([n, c]) => `${n} (${c})`).join(', ')}.\n` +
'An element\'s needs are stored when it is first numbered and never recomputed (lib.mjs ingestFile: a known file version is not re-read; INSERT OR IGNORE on element), so a change to the list reaches only file versions seen after it. Clearing these takes a one-off pass that re-derives needs for existing elements; it changes no number.');
}Pages Check
A JavaScript module in the tools folder of Stars that fetches blocks, families and names.
ingeststars / tools/pages-check.mjs · lines 1–76 of 76 · Entry point · pattern judge (shared by 9 files)
- What it does
- It fetches blocks, families and names. Defines arg, kb, minutesSinceCommit, head, judge. Uses libraries node:fs, node:child_process. Side effects: reads or writes files; makes network requests; starts processes.
- Inputs & outputs
- In: JSON file blocks.json; JSON file families.json; JSON file index.json; JSON file names.json; JSON file 0.json; JSON file 1.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: Modular Star Workflow (stars).
- What it achieves
- It is built from the arg step (`arg`), the minutes since commit helper (`minutesSinceCommit`) and the head step (`head`). Check the published pages of this repository the way a phone reaches them: each page, every file the page host outside our own (no CDN is allowed: the pages must work with the files served here).
- Why it matters
- Run by Modular Star Workflow.
- Application
- stars · tools · JavaScript module
- Uses
- Stars — Index Page (estate URL), node:fs, node:child_process
- Used by
- run by Modular Star Workflow (workflow run)
- Produces
- arg, kb, minutesSinceCommit, head, judge
- Defines here
- arg, kb, minutesSinceCommit, head, judge
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- stars@030ebc202d35959fecd162327892f671d1d9a0cc tools/pages-check.mjs:1-76 · blob b1683b106531112556437b97ce4cbbe78300a3ea · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network, process · domain stage: unknown · users: none · canonical: unknown
// Check the published pages of this repository the way a phone reaches them: each page, every file the page
// fetches or links to under its own site, HTTP status, size, and any <script src> or stylesheet pulled from a
// host outside our own (no CDN is allowed: the pages must work with the files served here).
// Usage: node tools/pages-check.mjs [--site https://ventusltd.github.io/stars/] [--grace 30] [--strict]
// Exits 1 on an HTTP error for one of our own files or a script from a non-allowed host. A file that is missing
// on the site but was committed here less than --grace minutes ago is reported as "not deployed yet" (a warning),
// so a run that follows a push does not fail on Pages' deploy delay. Size limits are warnings unless --strict.
import { existsSync } from 'node:fs';
import { execSync } from 'node:child_process';
const arg = (k, d) => { const i = process.argv.indexOf(k); return i > 0 ? process.argv[i + 1] : d; };
const SITE = arg('--site', 'https://ventusltd.github.io/stars/').replace(/\/?$/, '/');
const GRACE_MIN = Number(arg('--grace', 30)), strict = process.argv.includes('--strict');
const ALLOWED_HOSTS = new Set(['ventusltd.github.io', 'globalgrid2050.com', 'www.globalgrid2050.com']);
const PAGE_MAX = 64 * 1024, DATA_MAX = 2 * 1024 * 1024; // a page over 64 KB or a data file over 2 MB is slow on a phone
const PAGES = ['start.html', 'table.html', 'code.html'];
const DATA = ['blocks/blocks.json', 'blocks/families.json', 'code/index.json', 'code/names.json', 'code/f/0.json', 'code/f/1.json'];
const faults = [], warnings = [];
const kb = n => n < 1024 ? `${n} B` : `${Math.round(n / 1024)} KB`; // sizes are as sent (Pages compresses)
function minutesSinceCommit(path) {
try { const t = Number(execSync(`git log -1 --format=%ct -- "${path}"`, { stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim()); return t ? (Date.now() / 1000 - t) / 60 : Infinity; }
catch { return Infinity; }
}
async function head(path) {
const url = new URL(path, SITE).href;
let r;
try { r = await fetch(url, { method: 'HEAD', cache: 'no-store', redirect: 'follow' }); if (r.status === 405) r = await fetch(url, { cache: 'no-store' }); }
catch (e) { return { url, status: 0, size: 0, error: e.message }; }
return { url, status: r.status, size: Number(r.headers.get('content-length') || 0), type: r.headers.get('content-type') || '' };
}
function judge(path, res, max) {
const label = `${path}: ${res.status || 'no response'} ${res.size ? kb(res.size) : ''}`.trim();
if (res.status === 200) { if (res.size > max) (strict ? faults : warnings).push(`${path} is ${kb(res.size)}, over ${kb(max)}: slow on a phone`); return label; }
if (res.status === 404 && existsSync(path) && minutesSinceCommit(path) < GRACE_MIN) { warnings.push(`${path} is not deployed yet (committed ${Math.round(minutesSinceCommit(path))} min ago; Pages is still publishing)`); return label + ' (not deployed yet)'; }
faults.push(`${path}: HTTP ${res.status || res.error} for one of our own files`);
return label;
}
console.log(`Pages check · ${SITE} · ${new Date().toISOString().slice(0, 16).replace('T', ' ')} UTC`);
for (const page of PAGES) {
const url = new URL(page, SITE).href;
let r, html = '';
try { r = await fetch(url, { cache: 'no-store' }); html = r.ok ? await r.text() : ''; } catch (e) { r = { status: 0, statusText: e.message }; }
const size = Buffer.byteLength(html);
console.log(` ${judge(page, { status: r.status, size, error: r.statusText }, PAGE_MAX)}`);
if (!html) continue;
// Scripts and stylesheets from outside our own hosts: the page would break offline or when the CDN changes.
for (const m of html.matchAll(/<script[^>]*\ssrc\s*=\s*["']([^"']+)["']/gi)) {
const src = m[1]; if (!/^(https?:)?\/\//i.test(src)) continue;
const host = new URL(src.startsWith('//') ? 'https:' + src : src).host;
if (!ALLOWED_HOSTS.has(host)) faults.push(`${page} loads a script from ${host}: ${src}`); else console.log(` script from our own host: ${src}`);
}
for (const m of html.matchAll(/<link[^>]*\shref\s*=\s*["']([^"']+)["'][^>]*>/gi)) {
const href = m[1]; if (!/^(https?:)?\/\//i.test(href) || !/stylesheet|preload|modulepreload/i.test(m[0])) continue;
const host = new URL(href.startsWith('//') ? 'https:' + href : href).host;
if (!ALLOWED_HOSTS.has(host)) faults.push(`${page} loads a stylesheet from ${host}: ${href}`);
}
if (/@import\s+url\(\s*["']?https?:/i.test(html)) warnings.push(`${page} has a CSS @import from another site`);
// Every relative file the page fetches or links to must be served.
const refs = new Set();
for (const m of html.matchAll(/fetch\(\s*[`'"]\.\/([^`'"$?]+)[`'"?]/g)) refs.add(m[1]);
for (const m of html.matchAll(/href="\.\/([^"?#]+)/g)) refs.add(m[1]);
for (const ref of [...refs].sort()) {
if (ref.includes('${')) continue; // a template, checked through the DATA list
const res = await head(ref);
console.log(` ${judge(ref, res, ref.endsWith('.md') && ref.startsWith('LINES') ? Infinity : ref.endsWith('.html') ? PAGE_MAX : DATA_MAX)}`);
if (ref === 'LINES.md' && res.size > DATA_MAX) warnings.push(`LINES.md is ${kb(res.size)}: linked with a size warning, never as a first step`);
}
}
console.log(' data files the pages read:');
for (const d of DATA) console.log(` ${judge(d, await head(d), DATA_MAX)}`);
for (const w of warnings) console.log(` warning: ${w}`);
for (const f of faults) console.log(` FAULT: ${f}`);
console.log(faults.length ? ` ${faults.length} fault(s): a reader on a phone would hit an error.` : ' Every page and file is served from our own site.');
process.exitCode = faults.length ? 1 : 0; // not process.exit(): on Windows that races an open fetch socketRun Log
A JavaScript module in the tools folder of Stars. It is built from the arg step (`arg`).
otherstars / tools/run-log.mjs · lines 1–39 of 39 · Not reached from any entry point (candidate for review)
- What it does
- Defines arg, gh. Uses libraries node:child_process. Side effects: starts processes.
- Inputs & outputs
- In: command-line arguments.
- What it achieves
- The lines that matter from one workflow registered, repository counts) plus every error and stack trace, with timestamps and colour codes stripped.
- Why it matters
- No other file in the estate was found to import it.
- Application
- stars · tools · JavaScript module
- Uses
- node:child_process
- Used by
- none found
- Produces
- arg, gh
- Defines here
- arg, gh
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- stars@030ebc202d35959fecd162327892f671d1d9a0cc tools/run-log.mjs:1-39 · blob f4a72dca804ea39d59edd9ae4d71d5feb54e103f · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unreached_review
// The lines that matter from one workflow run: what our scripts printed (Blocks:, Reactions:, Spider graph:, graphs
// registered, repository counts) plus every error and stack trace, with timestamps and colour codes stripped.
// Usage: node tools/run-log.mjs <run-id> [--repo Ventusltd/stars] [--all]
// --all prints every line of the log (still cleaned). Exits 1 when the run did not succeed, 2 when its log is not yet available.
import { execFileSync } from 'node:child_process';
const arg = (k, d) => { const i = process.argv.indexOf('--' + k); return i > 0 ? process.argv[i + 1] : d; };
const id = process.argv[2], repo = arg('repo', 'Ventusltd/stars'), all = process.argv.includes('--all');
if (!id || !/^\d+$/.test(id)) { console.log('Usage: node tools/run-log.mjs <run-id> [--repo owner/name] [--all]'); process.exit(2); }
const gh = args => execFileSync('gh', args, { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
let run;
try { run = JSON.parse(gh(['run', 'view', id, '-R', repo, '--json', 'status,conclusion,event,createdAt,updatedAt,workflowName,displayTitle,jobs,url'])); }
catch (e) { console.log(`Run ${id} in ${repo}: ${String(e.stderr || e.message).trim().split('\n')[0]}`); process.exit(2); }
const mins = ((Date.parse(run.updatedAt) - Date.parse(run.createdAt)) / 60000).toFixed(1);
console.log(`${run.workflowName} #${id} (${repo}): ${run.status} ${run.conclusion || ''} · ${run.event} · ${run.createdAt.slice(0, 16).replace('T', ' ')} UTC · ${mins} min · ${run.url}`);
for (const j of run.jobs || []) for (const s of j.steps || []) if (s.conclusion && s.conclusion !== 'success' && s.conclusion !== 'skipped') console.log(` step "${s.name}": ${s.conclusion}`);
let log;
try { log = gh(['run', 'view', id, '-R', repo, '--log']); }
catch (e) { console.log(` log not available yet: ${String(e.stderr || e.message).trim().split('\n')[0]}`); process.exit(run.status === 'completed' ? 1 : 2); }
// Lines arrive as "job<TAB>step<TAB>2026-09-14T09:44:57.1234567Z text"; keep the step, drop the clock and colours.
const OURS = /^(Blocks:|Reactions:|Spider graph:|Repositories to scan:|Done:|Rebuild check|History|No changes\.|First run:|\d+ graphs registered|[\w.-]+: \d+ KB is over|Ventusltd\/\S+: (\d+ code files|not scanned)|\d+ library functions load|✔|✖|# (pass|fail|tests) |\S+\.json: .* KB · generated|\s+(warning: |FAULT: |Readable by the receiver|\d+ fault\(s\)))/;
const TROUBLE = /(##\[error\]|\bError\b|\bERR!|Traceback|^\s+File "|^\s+at |Unhandled|exit code|fatal:|failed|FAULT|npm error|SyntaxError|TypeError|ReferenceError|RangeError)/;
let lastStep = '', shown = 0;
for (const raw of log.split('\n')) {
const parts = raw.split('\t');
const step = parts.length >= 3 ? parts[1] : '';
const text = (parts.length >= 3 ? parts.slice(2).join('\t') : raw).replace(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?Z ?/, '').replace(/\x1b\[[0-9;]*[A-Za-z]/g, '').replace(/\r$/, '');
if (!text.trim()) continue;
if (!all && !OURS.test(text) && !TROUBLE.test(text)) continue;
if (/^##\[(group|endgroup|debug)\]/.test(text)) continue;
if (step !== lastStep) { console.log(`\n[${step || 'run'}]`); lastStep = step; }
console.log(' ' + text.slice(0, 400));
shown++;
}
if (!shown) console.log('\n Nothing from our scripts and no errors in the log.');
process.exit(run.conclusion === 'success' ? 0 : 1);Status
A JavaScript module in the tools folder of Stars that fetches blocks and reactions. It is built from the span step (`span`) and the mark step (`mark`).
ingeststars / tools/status.mjs · lines 1–59 of 59 · Not reached from any entry point (candidate for review)
- What it does
- It fetches blocks and reactions. Defines gh, span, kb, mark. Uses libraries node:child_process. Side effects: makes network requests; starts processes.
- Inputs & outputs
- In: JSON file blocks.json; JSON file reactions.json; JSON file graph.json; JSON file index.json.
- What it achieves
- One-call status of the automation: recent runs of every workflow in stars and code-generator, whether the cron schedule has ever fired, the live size and HTTP status of the published files, and the registry's graphs.
- Why it matters
- No other file in the estate was found to import it.
- Application
- stars · tools · JavaScript module
- Uses
- Stars — Index Page (estate URL), node:child_process
- Used by
- none found
- Produces
- gh, span, kb, mark
- Defines here
- gh, span, kb, mark
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- stars@030ebc202d35959fecd162327892f671d1d9a0cc tools/status.mjs:1-59 · blob e9177af208d2cf4ff5f33e77376868f2a0f08857 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: network, process · domain stage: unknown · users: none · canonical: unreached_review
// One-call status of the automation: recent runs of every workflow in stars and code-generator, whether the
// cron schedule has ever fired, the live size and HTTP status of the published files, and the registry's graphs.
// Usage: node tools/status.mjs (needs gh, signed in; node 24 built-ins only)
// Exits 1 when a workflow's newest finished run failed, a key file is not served, or gh could not be read.
import { execFileSync } from 'node:child_process';
const REPOS = ['Ventusltd/stars', 'Ventusltd/code-generator'];
const SITE = 'https://ventusltd.github.io/stars/';
const FILES = ['blocks/blocks.json', 'blocks/reactions.json', 'modular/graph.json', 'spider/features.yml', 'code/index.json', 'LINES.md'];
const REGISTRY_LIMIT = 600 * 1024;
const now = Date.now();
let problems = 0;
const gh = args => { try { return JSON.parse(execFileSync('gh', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })); } catch (e) { problems++; console.log(`gh ${args.slice(0, 3).join(' ')}: ${String(e.stderr || e.message).trim().split('\n')[0]}`); return null; } };
const span = ms => { ms = Math.max(0, ms); const s = Math.round(ms / 1000); return s < 60 ? `${s}s` : s < 3600 ? `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s` : s < 86400 ? `${Math.floor(s / 3600)}h${String(Math.floor(s % 3600 / 60)).padStart(2, '0')}m` : `${Math.floor(s / 86400)}d${Math.floor(s % 86400 / 3600)}h`; };
const kb = n => n >= 1024 * 1024 ? `${(n / 1048576).toFixed(1)} MB` : `${Math.round(n / 1024)} KB`;
const mark = r => r.status !== 'completed' ? 'RUN' : { success: 'ok', failure: 'FAIL', cancelled: 'cancel', timed_out: 'TIMEOUT', skipped: 'skip', neutral: 'ok', action_required: 'ACTION' }[r.conclusion] || r.conclusion || '?';
console.log(`Status at ${new Date(now).toISOString().slice(0, 16).replace('T', ' ')} UTC`);
for (const repo of REPOS) {
const runs = gh(['run', 'list', '-R', repo, '--limit', '80', '--json', 'databaseId,workflowName,status,conclusion,event,createdAt,updatedAt,startedAt']) || [];
const byFlow = new Map();
for (const r of runs) { if (!byFlow.has(r.workflowName)) byFlow.set(r.workflowName, []); if (byFlow.get(r.workflowName).length < 5) byFlow.get(r.workflowName).push(r); }
console.log(`\n${repo}`);
for (const [name, list] of byFlow) {
const cells = list.map(r => {
const start = Date.parse(r.startedAt || r.createdAt), end = r.status === 'completed' ? Date.parse(r.updatedAt) : now;
return `${mark(r)} ${span(end - start)} ${span(now - Date.parse(r.createdAt))} ago (${r.event})`;
});
const newestDone = list.find(r => r.status === 'completed');
if (newestDone && ['failure', 'timed_out'].includes(newestDone.conclusion) && name !== 'pages-build-deployment') problems++;
console.log(` ${name}: ${cells.join(' | ')}${list[0] ? ` #${list[0].databaseId}` : ''}`);
}
const cron = gh(['run', 'list', '-R', repo, '--event', 'schedule', '--limit', '1', '--json', 'createdAt,workflowName']) || [];
console.log(cron.length ? ` cron: last fired ${span(now - Date.parse(cron[0].createdAt))} ago (${cron[0].workflowName})` : ' cron: never fired');
}
console.log(`\nPublished at ${SITE}`);
for (const f of FILES) {
try {
const r = await fetch(SITE + f, { method: 'HEAD', headers: { 'accept-encoding': 'identity' }, cache: 'no-store' });
const len = Number(r.headers.get('content-length') || 0), mod = Date.parse(r.headers.get('last-modified') || '');
if (r.status !== 200) problems++;
const note = f === 'modular/graph.json' || f === 'blocks/graph.json' ? (len > REGISTRY_LIMIT ? ' OVER the 600 KB registry limit' : len > REGISTRY_LIMIT * 0.9 ? ` ${Math.round(100 * len / REGISTRY_LIMIT)}% of the 600 KB registry limit` : '') : '';
console.log(` ${r.status} ${f.padEnd(22)} ${kb(len).padStart(8)}${mod ? ` modified ${span(now - mod)} ago` : ''}${note}`);
} catch (e) { problems++; console.log(` ERR ${f}: ${e.message}`); }
}
try {
const yml = await (await fetch(SITE + 'spider/features.yml', { cache: 'no-store' })).text();
const entries = [...yml.matchAll(/- id: "([^"]+)"[\s\S]*?nodes: (\d+)\s+edges: (\d+)\s+graph_generated_utc: "([^"]*)"/g)];
console.log(`\nRegistry: ${entries.length} graphs: ${entries.map(m => `${m[1]} (${m[2]}n/${m[3]}e, ${m[4] ? span(now - Date.parse(m[4])) + ' old' : 'undated'})`).join(', ')}`);
if (!entries.length) problems++;
const seen = new Set(), dup = entries.map(m => m[1]).filter(id => seen.has(id) || !seen.add(id));
if (dup.length) { problems++; console.log(` duplicate registry id(s): ${[...new Set(dup)].join(', ')} (the dashboard would show each twice; see spider/register.py)`); }
} catch (e) { problems++; console.log(`Registry: unreadable: ${e.message}`); }
console.log(problems ? `\n${problems} problem(s) above.` : '\nNo problems.');
process.exitCode = problems ? 1 : 0; // not process.exit(): on Windows that races an open fetch socket and aborts with a libuv assertionCheck Policy
A JavaScript module in the tools folder of Stones that uses SHA-256.
ingeststones / tools/check-policy.mjs · lines 1–60 of 60 · Entry point · pattern field (shared by 11 files)
- What it does
- It loads data. Defines field. Uses libraries node:fs, node:crypto, node:path. Side effects: reads or writes files; starts processes.
- Downstream impact
- Used directly by 1 file: Policy Workflow (stones).
- What it achieves
- Its name says it checks policy. Defines `field`.
- Why it matters
- Run by Policy Workflow.
- Application
- stones · tools · JavaScript module
- Uses
- node:fs, node:crypto, node:path
- Used by
- run by Policy Workflow (workflow run)
- Produces
- field
- Defines here
- field
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- stones@45b6b3eed03dca5efac4fe1b443d1a6764d7838d tools/check-policy.mjs:1-60 · blob cb19c3153d76e8b1d1f0b3983896a9a0266423de · GitHub at these lines
- State
- achieves: name · context: auto · stage: ingest · effects: filesystem, process · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env node
// tools/check-policy.mjs - refuses to let a record be published that breaks POLICY.md.
// Fails closed: any finding, or zero records examined, exits non-zero.
import { readdirSync, readFileSync, existsSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { join } from 'node:path';
const DENY = [
[/\b(vikram|vikra|kumar)\b/i, 'personal name or account'],
[/@[a-z0-9.-]+\.(com|org|net|uk)\b/i, 'email address'],
[/[A-Za-z]:\\|\/mnt\/[a-z]\/|AppData|Users\\/, 'local file path'],
[/ssh-(ed25519|rsa)|SHA256:[A-Za-z0-9+/]{20,}/, 'key material or fingerprint'],
[/\b(gitlab|glab|bitbucket)\b/i, 'named hosting provider'],
[/\b(ollama|qwen|deepseek|llama)\b/i, 'named local model'],
[/\b(token|password|secret|api[_ -]?key)\b/i, 'credential word'],
[/£|\$[0-9]|\beuro\b|\bbudget\b|\bspend\b|\bcredit\b/i, 'financial detail'],
[/\b(UKPN|NESO|National Grid|TenneT|LEONI|Gridserve|Ampyr|SMA|Siemens|Vestas|RWE|Honeywell|Lapp)\b/, 'named third party organisation'],
[/\b(Gita|Upanishad|Vedic|Haridwar|Domesday|Magna Carta|Portia|Shakespeare)\b/i, 'philosophical or literary framing'],
[/\bUnreal\b|\bcompetitor\b|\brival\b/i, 'comparative claim'],
[/\b(MSI|Alienware)\b/, 'machine identifier'],
];
const REQUIRED = ['record', 'date', 'source_digest'];
const dir = 'records';
if (!existsSync(dir)) { console.error('FAIL: no records directory. A check that examines nothing refuses.'); process.exit(1); }
const files = readdirSync(dir).filter(f => f.endsWith('.md'));
if (files.length === 0) { console.error('FAIL: zero records examined.'); process.exit(1); }
let findings = 0;
for (const f of files) {
const p = join(dir, f);
const raw = readFileSync(p, 'utf8').split(String.fromCharCode(13)).join('').replace(/^/, ''); // key is over LF normalised content
const fm = raw.match(/^---\n([\s\S]*?)\n---/);
if (!fm) { console.error(`FAIL ${f}: no front matter`); findings++; continue; }
const fmLines = fm[1].split(String.fromCharCode(10));
const field = (k) => {
const line = fmLines.find(l => l.startsWith(k + ':'));
return line ? line.slice(k.length + 1).trim() : '';
};
for (const k of REQUIRED) {
if (!field(k)) { console.error('FAIL ' + f + ": front matter missing '" + k + "'"); findings++; }
}
const sd = field('source_digest');
if (!/^[0-9a-f]{64}$/.test(sd)) { console.error('FAIL ' + f + ': source_digest is not a sha256'); findings++; }
const body = raw.slice(fm[0].length);
for (const [re, why] of DENY) {
const m = body.match(re);
if (m) { console.error(`FAIL ${f}: ${why} -> "${m[0]}"`); findings++; }
}
const key = createHash('sha256').update(Buffer.from(raw, 'utf8')).digest('hex');
const index = existsSync('INDEX.md') ? readFileSync('INDEX.md', 'utf8') : '';
if (index && !index.includes(key)) { console.error(`FAIL ${f}: key ${key} is not in INDEX.md`); findings++; }
}
console.log(`${files.length} records examined, ${findings} findings.`);
if (findings > 0) { console.error('REFUSED: publication policy not met.'); process.exit(1); }
console.log('Policy met.');Verify
A JavaScript module in the sandbox folder of Testcode that uses SHA-256.
ingesttestcode / sandbox/202609141527-numbered-universe/verify.mjs · lines 1–18 of 18 · version 2026-09-14 15:27 · Not reached from any entry point (candidate for review) · pattern expand (shared by 9 files)
- What it does
- It loads data. Defines read, expand, has. Uses libraries node:fs/promises. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- In: command-line arguments.
- What it achieves
- Defines `read`, `expand` and `has`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- testcode · sandbox/202609141527-numbered-universe · JavaScript module
- Uses
- node:fs/promises
- Used by
- none found
- Produces
- read, expand, has
- Defines here
- read, expand, has
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/202609141527-numbered-universe/verify.mjs:1-18 · blob 06773085f0623130beea3774f5b40ef664882e8b · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: experimental · users: none · canonical: unreached_review
import fs from 'node:fs/promises';import path from 'node:path';import {createHash} from 'node:crypto';const digest=value=>createHash('sha256').update(value).digest('hex');
const root=process.argv[2];if(!root)throw Error('Generation directory required');
const manifest=JSON.parse(await fs.readFile(path.join(root,'manifest.json'),'utf8'));const tables={},relations=new Map();let bytes=0,files=0,max=0;
async function read(entry){const resolved=path.resolve(root,entry.path);if(!resolved.startsWith(path.resolve(root)+path.sep))throw Error('Escaping manifest path');const b=await fs.readFile(resolved);if(b.length>=600000||b.length!==entry.bytes||digest(b)!==entry.sha256)throw Error('Hash/size mismatch: '+entry.path);bytes+=b.length;max=Math.max(max,b.length);files++;return JSON.parse(b);}
for(const e of manifest.relations||[])relations.set(e.path,await read(e));
function expand(value){if(Array.isArray(value))return value;if(value?.parts){const result=value.parts.flatMap(p=>{if(!relations.has(p))throw Error('Missing relation part');return relations.get(p);});if(result.length!==value.count)throw Error('Relation count mismatch');return result;}throw Error('Missing relation array');}
for(const[kind,entries]of Object.entries(manifest.indexes)){const map=new Map();tables[kind]=map;for(const e of entries){const rows=await read(e);if(rows.length!==e.count||rows[0]?.n!==e.first||rows.at(-1)?.n!==e.last)throw Error('Index bounds mismatch');for(const r of rows){if(map.has(r.n))throw Error('Duplicate primary key');for(const[k,v]of Object.entries(r))if(v?.parts)r[k]=expand(v);map.set(r … [line shortened here: 409 characters; full line on GitHub]
const countNames={line:'lines',family:'families',tablet:'tablets',source:'sources',block:'blocks',repository:'repositories'};
for(const[kind,name]of Object.entries(countNames))if(tables[kind].size!==manifest.counts[name])throw Error('Primary key count mismatch: '+kind);
const has=(kind,n)=>{if(!tables[kind]?.has(n))throw Error(`Unresolved ${kind} key ${n}`);return tables[kind].get(n);};
for(const r of tables.line.values()){if(digest(Buffer.from(r.base64,'base64'))!==r.sha256)throw Error('Stored line byte hash mismatch');for(const n of r.families)if(!has('family',n).lines.includes(r.n))throw Error('Missing reverse family-to-line relation');for(const n of r.tablets)if(!has('tablet',n).lines.includes(r.n))throw Error('Missing reverse tablet-to-line relation');}
for(const r of tables.family.values()){for(const n of r.lines)if(!has('line',n).families.includes(r.n))throw Error('Missing reverse line-to-family relation');for(const n of r.tablets)has('tablet',n);for(const n of r.uses)if(!has('family',n).used_by.includes(r.n))throw Error('Missing reverse dependency candidate');for(const n of r.used_by)if(!has('family',n).uses.includes(r.n))throw Error('Missing … [line shortened here: 546 characters; full line on GitHub]
for(const r of tables.tablet.values()){for(const n of r.lines)if(!has('line',n).tablets.includes(r.n))throw Error('Missing reverse line-to-tablet relation');for(const n of r.sources)if(has('source',n).tablet!==r.n)throw Error('Source/tablet mismatch');for(const n of r.families)if(!has('family',n).tablets.includes(r.n))throw Error('Tablet/family mismatch');}
for(const r of tables.source.values()){if(!/^[a-f0-9]{40}$/.test(r.commit)||digest(JSON.stringify([r.repo,r.commit,r.path]))!==r.n)throw Error('Invalid pinned source identity');if(!has('tablet',r.tablet).sources.includes(r.n))throw Error('Missing reverse source occurrence');}
for(const r of tables.block.values())for(const n of r.families)if(!has('family',n).blocks.includes(r.n))throw Error('Missing forward membership');
for(const r of tables.repository.values()){for(const n of r.families)has('family',n);for(const n of r.sources)if(has('source',n).repo!==r.n)throw Error('Repository/source mismatch');}
bytes+=(await fs.stat(path.join(root,'manifest.json'))).size;if(bytes>=200000000)throw Error('200 MB publication bound exceeded');
console.log(JSON.stringify({observed_utc:new Date().toISOString(),passed:true,source_commit:manifest.source_commit,database_sha256:manifest.database_sha256,counts:manifest.counts,total_bytes:bytes,files:files+1,max_file_bytes:max,checks:['shard hashes and sizes','all permanent key counts','all exact line byte hashes','reciprocal line/family/tablet membership','reciprocal candidate dependencies','r … [line shortened here: 520 characters; full line on GitHub]View
A JavaScript file in the sandbox folder of Testcode that works with choose relation (`chooseRelation`) and draws SVG graphics, using SHA-256.
interactiontestcode / sandbox/202609141552-numbered-universe/view.js · lines 1–26 of 26 · version 2026-09-14 15:52 · Not reached from any entry point (candidate for review) · pattern chooseRelation (shared by 2 files)
- What it does
- It draws its content. Defines 10 functions or classes, including el, json, record, array, go. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- Out: SVG drawing.
- What it achieves
- It is built from the button step (`button`), the SVG step (`svg`) and the render step (`render`). Defines `json`, `record`, `array` and 5 more. It responds to click, keydown and hashchange events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- testcode · sandbox/202609141552-numbered-universe · script
- Uses
- none found
- Used by
- none found
- Produces
- el, json, record, array, go, button, svg, render, chooseRelation, show
- Defines here
- el, json, record, array, go, button, svg, render, chooseRelation, show
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/202609141552-numbered-universe/view.js:1-26 · blob b7a0778e32ff1d914fbb1bee20c64654a11cdf0d · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: experimental · users: none · canonical: unreached_review
'use strict';
const el=id=>document.getElementById(id),cache=new Map();let manifest,current,entries=[],offset=0,serial=0;
const labels={family:'Family',line:'Line',block:'Block',tablet:'Source tablet',source:'Pinned source',repository:'Repository'};
const relKinds={families:'family',lines:'line',tablets:'tablet',sources:'source',uses:'family',used_by:'family',blocks:'block'};
const relLabels={families:'Recorded families',lines:'Permanent line keys',tablets:'Source tablets',sources:'Pinned source occurrences',uses:'Candidate uses',used_by:'Candidate used by',blocks:'Block memberships'};
async function json(file){if(cache.has(file))return cache.get(file);const r=await fetch('../202609141527-numbered-universe/data/'+file);if(!r.ok)throw Error('Missing snapshot input: '+file+' (HTTP '+r.status+')');const value=await r.json();cache.set(file,value);if(cache.size>10)cache.delete(cache.keys().next().value);return value;}
async function record(kind,key){const list=manifest.indexes[kind];if(!list)throw Error('Unknown record type');key=['line','family','tablet'].includes(kind)?Number(key):String(key);const part=list.find(p=>key>=p.first&&key<=p.last);if(!part)throw Error('Permanent key not present in this snapshot');const r=(await json(part.path)).find(r=>r.n===key);if(!r)throw Error('Indexed key missing');return r;}
async function array(value){if(Array.isArray(value))return value;if(value?.parts){const result=[];for(const p of value.parts)result.push(...await json(p));if(result.length!==value.count)throw Error('Relation count mismatch');return result;}throw Error('Missing relation input');}
function go(kind,key){location.hash=new URLSearchParams({kind,key}).toString();}
function button(text,action){const b=document.createElement('button');b.textContent=text;b.addEventListener('click',action);return b;}
function svg(tag,attrs,text){const n=document.createElementNS('http://www.w3.org/2000/svg',tag);for(const[k,v]of Object.entries(attrs))n.setAttribute(k,v);if(text)n.textContent=text;return n;}
function render(){const subset=entries.slice(offset,offset+12);el('items').replaceChildren();el('graph').replaceChildren();const graph=el('graph');const center=svg('g',{});center.append(svg('rect',{x:370,y:185,width:260,height:60,rx:6}),svg('text',{x:385,y:220},(el('title').textContent||'Records').slice(0,30)));graph.append(center);
subset.forEach((item,i)=>{const x=i<6?10:750,y=10+(i%6)*70;graph.prepend(svg('line',{x1:500,y1:215,x2:x+115,y2:y+25}));const group=svg('g',{tabindex:0,role:'button','aria-label':item.label});group.append(svg('rect',{x,y,width:240,height:50,rx:5}),svg('text',{x:x+8,y:y+29},item.label.slice(0,31)));const open=()=>go(item.kind,item.key);group.addEventListener('click',open);group.addEventListener('ke … [line shortened here: 541 characters; full line on GitHub]
el('position').textContent=`${entries.length?offset+1:0}–${Math.min(offset+12,entries.length)} of ${entries.length} relationships`;el('previous').disabled=offset===0;el('next').disabled=offset+12>=entries.length;
}
async function chooseRelation(){const field=el('relation').value;entries=field?(await array(current.record[field])).map(key=>({kind:relKinds[field],key,label:`${labels[relKinds[field]]} ${key}`})):[];offset=0;render();}
async function show(){const own=++serial;try{const p=new URLSearchParams(location.hash.slice(1)),kind=p.get('kind')||'block',key=p.get('key');el('kind').value=kind;el('detail').replaceChildren();el('code').hidden=true;el('relation').replaceChildren();
if(key===null){el('title').textContent='Browse '+labels[kind].toLowerCase()+' records';entries=[];for(const part of manifest.indexes[kind]){for(const row of await json(part.path))entries.push({kind,key:row.n,label:`${labels[kind]} ${row.n}${row.names?.length?' '+row.names[0]:''}`});}if(own!==serial)return;current=null;offset=0;render();return;}
const r=await record(kind,key);if(own!==serial)return;current={kind,record:r};el('key').value=key;el('title').textContent=`${labels[kind]} ${r.n}${r.names?.length?' · '+r.names.join(' / '):''}`;
if(r.scope){const p=document.createElement('p');p.textContent=r.scope;el('detail').append(p);}
if(kind==='line'){const bytes=Uint8Array.from(atob(r.base64),c=>c.charCodeAt(0));const hash=[...new Uint8Array(await crypto.subtle.digest('SHA-256',bytes))].map(x=>x.toString(16).padStart(2,'0')).join('');if(hash!==r.sha256)throw Error('Line checksum mismatch');el('code').textContent=new TextDecoder().decode(bytes);el('code').hidden=false;el('detail').textContent=`Exact stored bytes verified: SHA … [line shortened here: 415 characters; full line on GitHub]
if(kind==='source'){const a=document.createElement('a');a.href='https://github.com/'+r.repo+'/blob/'+r.commit+'/'+r.path.split('/').map(encodeURIComponent).join('/');a.textContent='Open file at recorded commit '+r.commit;a.target='_blank';a.rel='noopener';el('detail').append(a);r.tablets=[r.tablet];}
for(const field of Object.keys(relKinds))if(r[field]){const count=Array.isArray(r[field])?r[field].length:r[field].count;const o=document.createElement('option');o.value=field;o.textContent=`${relLabels[field]} (${count})`;el('relation').append(o);}await chooseRelation();
}catch(e){el('title').textContent='Record unavailable';el('detail').textContent=e.message;entries=[];render();}}
el('back').onclick=()=>history.back();el('home').onclick=()=>{location.hash='kind=block';};el('open').onclick=()=>go(el('kind').value,el('key').value);el('browse').onclick=()=>{location.hash='kind='+el('kind').value;};el('relation').onchange=()=>chooseRelation().catch(e=>{el('detail').textContent=e.message;});el('previous').onclick=()=>{offset=Math.max(0,offset-12);render();};el('next').onclick=() … [line shortened here: 461 characters; full line on GitHub]
(async()=>{manifest=await json('manifest.json');el('status').textContent=`${manifest.counts.lines} permanent line keys · ${manifest.counts.families} retained family keys · ${manifest.counts.repositories} repositories\nSnapshot ${manifest.observed_utc} · source ${manifest.source_commit}\nHistorical keys are retained; no supersession mapping is inferred.`;await show();})().catch(e=>{el('status').tex … [line shortened here: 447 characters; full line on GitHub]Sandbox — Galaxy Bond
A JavaScript module in Testcode that draws on a canvas. It is built from the number step (`number`), the make step (`make`) and the string step (`string`).
interactiontestcode / sandbox/202609151802-galaxy-bond/app.mjs · lines 1–73 of 73 · version 2026-09-15 18:02 · Entry point · pattern string (shared by 2 files)
- What it does
- It draws its content. Defines 10 functions or classes, including $, number, make, string, field. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'sandbox'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. README: "Required browser files are `index.html`, `style.css`, `app.mjs`, `report.json`, and the unchanged `wafer.mjs`."
- Inputs & outputs
- In: JSON file report.json. Out: canvas drawing.
- Downstream impact
- Used directly by 1 file: Sandbox — Galaxy Bond Page (testcode).
- What it achieves
- The README says: Required browser files are `index.html`, `style.css`, `app.mjs`, `report.json`, and the unchanged `wafer.mjs`. It reads `./report.json`. It responds to click, input and change events.
- Why it matters
- Loaded by the page of the same name.
- Application
- testcode · sandbox/202609151802-galaxy-bond · JavaScript module
- Uses
- Wafer (import)
- Used by
- loaded by Sandbox — Galaxy Bond Page (script src)
- Produces
- $, number, make, string, field, inspect, filter, draw, plot, start
- Defines here
- $, number, make, string, field, inspect, filter, draw, plot, start
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/202609151802-galaxy-bond/app.mjs:1-73 · blob 97c24e22ad79865553750da7b5afe4a2a8c15474 · GitHub at these lines
- State
- achieves: readme · context: readme_derived · stage: output · effects: dom, network · domain stage: experimental · users: none · canonical: unknown
import { place } from './wafer.mjs';
const $ = id => document.getElementById(id);
const state = { report: null, selected: null };
const number = n => Number(n || 0).toLocaleString('en-GB');
const make = (tag, text, className) => { const n = document.createElement(tag); if (text !== undefined) n.textContent = text; if (className) n.className = className; return n; };
const string = value => typeof value === 'string' ? value : JSON.stringify(value);
function field(parent, title, value) { const box = make('div'); box.append(make('dt', title), make('dd', number(value))); parent.append(box); }
function inspect(row) {
state.selected = row.layer_id;
const panel = $('inspection'); panel.replaceChildren(make('h2', row.layer_id), make('p', row.status));
const back = make('button', 'Back to layers'); back.type = 'button';
back.addEventListener('click', () => { $('search').focus(); $('search').scrollIntoView({block:'center'}); }); panel.append(back);
panel.append(make('h3', 'The claim'), make('p', row.claim_text || 'No claim text supplied.'));
for (const predicate of row.predicates || []) {
const card = make('section', undefined, 'predicate');
card.append(make('strong', predicate.text || predicate.id), make('p', `${predicate.status} · ${number(predicate.checked)} of ${number(predicate.total)} checked`));
if (predicate.first_deviation) card.append(make('pre', JSON.stringify(predicate.first_deviation, null, 2)));
panel.append(card);
}
if (row.disclosed?.length) { const details = make('details'); details.append(make('summary', `DISCLOSED · ${number(row.disclosed.length)} gap records`)); for (const item of row.disclosed) details.append(make('p', `${item.field}: ${string(item.value)}`)); panel.append(details); }
if (row.not_evaluated?.length) { const details = make('details'); details.open = true; details.append(make('summary', `NOT EVALUATED · ${number(row.not_evaluated.length)} statements`)); for (const item of row.not_evaluated) { const box = make('div', undefined, 'predicate'); box.append(make('p', item.text || item.field), make('p', item.reason, 'dim')); details.append(box); } panel.append(details) … [line shortened here: 403 characters; full line on GitHub]
for (const button of $('layers').querySelectorAll('button')) button.setAttribute('aria-pressed', String(button.dataset.layer === row.layer_id));
draw();
}
function filter() {
const q = $('search').value.toLowerCase().trim(), result = $('status').value;
const rows = state.report.rows.filter(row => (!result || row.status === result) && (!q || `${row.layer_id} ${row.claim_text}`.toLowerCase().includes(q)));
const fragment = document.createDocumentFragment();
for (const row of rows) {
const button = make('button', undefined, 'layer'); button.type = 'button'; button.dataset.layer = row.layer_id;
button.setAttribute('aria-pressed', String(row.layer_id === state.selected));
button.append(make('strong', row.layer_id), make('span', row.status, 'state'));
const predicates = row.predicates || [], passed = predicates.filter(p => p.status === 'PASSED').length;
button.append(make('p', `${number(passed)} passing predicates · ${number(row.not_evaluated?.length)} statements not evaluated · ${number(row.disclosed?.length)} gap records`));
button.addEventListener('click', () => { inspect(row); $('inspection').scrollIntoView({block:'start'}); }); fragment.append(button);
}
$('layers').replaceChildren(fragment); $('shown').textContent = `${number(rows.length)} of ${number(state.report.rows.length)} layers shown`;
}
function draw() {
if (!state.report) return;
const canvas = $('wafer'), rect = canvas.getBoundingClientRect(), ratio = Math.min(devicePixelRatio || 1, 2);
canvas.width = Math.round(rect.width * ratio); canvas.height = Math.round(rect.height * ratio);
const ctx = canvas.getContext('2d'); if (!ctx) { $('map-note').textContent = 'Canvas unavailable; all audit evidence remains readable below.'; return; }
ctx.setTransform(ratio, 0, 0, ratio, 0, 0); ctx.clearRect(0, 0, rect.width, rect.height);
const samples = state.report.preview?.anchors || [], max = state.report.preview?.max_key || 1;
const scale = Math.min(rect.width, rect.height) * .46 / Math.sqrt(max);
const plot = (key, radius) => { const [x, y] = place(key); ctx.beginPath(); ctx.arc(rect.width / 2 + x * scale, rect.height / 2 - y * scale, radius, 0, Math.PI * 2); ctx.fill(); };
ctx.fillStyle = '#677083'; for (const sample of samples) for (const key of sample.keys) plot(key, 1.15);
const selected = samples.find(s => s.layer_id === state.selected);
ctx.fillStyle = '#5ec8f2'; for (const key of selected?.keys || []) plot(key, 2.5);
const count = samples.reduce((n, s) => n + s.keys.length, 0);
$('map-note').textContent = `${number(count)} sampled layer anchors · frozen wafer.v1 placement${selected ? ` · ${selected.layer_id} selected` : ''}. Marks are not a verdict colour scale.`;
}
async function start() {
try {
const response = await fetch('./report.json'); if (!response.ok) throw new Error(`Audit file returned ${response.status}`);
const report = await response.json(); if (report.schema !== 'bond.v1' || !Array.isArray(report.rows)) throw new Error('Unrecognised audit document');
state.report = report;
const totals = $('totals');
field(totals, 'Layers inspected', report.rows.length);
field(totals, 'Contradicted', report.rows.filter(r => r.status === 'CONTRADICTED').length);
field(totals, 'Statements not evaluated', report.rows.reduce((n, r) => n + (r.not_evaluated?.length || 0), 0));
field(totals, 'Disclosed gap records', report.rows.reduce((n, r) => n + (r.disclosed?.length || 0), 0));
$('load').hidden = true; $('workspace').hidden = false;
const provenance = report.provenance || {};
$('provenance').textContent = `Snapshot ${provenance.generated_utc || 'time not recorded'} · source ${provenance.commit || 'not recorded'} · values counted from this audit, not current live state.`;
if (/^[0-9a-f]{40}$/.test(provenance.commit || '')) $('source').href = `https://github.com/Ventusltd/galaxies-wafers/tree/${provenance.commit}`;
$('search').addEventListener('input', filter); $('status').addEventListener('change', filter); window.addEventListener('resize', draw);
filter(); draw();
} catch (error) { $('load').textContent = `Audit unavailable: ${error.message}. No result has been inferred.`; }
}
start();