GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / star-maker / machinery/bench

Server and 5 more files

A JavaScript module in the bench folder of Star Maker that reads choice (`readChoice`), writes choice (`writeChoice`) and gets browser (`getBrowser`), using SHA-256.

673 lines of JavaScript and PowerShell from star-maker, in 6 files. Topic: Kuiper, cosmos and drawing engines. Section 1560 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Logic storage · star-maker / machinery/bench/logic.mjs lines 1–80
  2. Magnetar storage · star-maker / machinery/bench/magnetar.mjs lines 1–64
  3. Random storage · star-maker / machinery/bench/random.mjs lines 1–32
  4. Server interaction · star-maker / machinery/bench/server.mjs lines 1–243
  5. Starmaker storage · star-maker / machinery/bench/starmaker.mjs lines 1–225
  6. Tick automation · star-maker / machinery/bench/tick.ps1 lines 1–29

Logic

A JavaScript module in the bench folder of Star Maker. It is built from the lineage step (`lineage`), the norm step (`norm`) and the canon step (`canon`).

storagestar-maker / machinery/bench/logic.mjs · lines 1–80 of 80 · Not reached from any entry point (candidate for review) · pattern lineage (shared by 2 files)

What it does
It loads data. Defines lineage, norm, canon, walk. Uses libraries node:fs/promises, node:path. Side effects: reads or writes files.
What it achieves
LOGIC STARS — our own reasoning, no model, no Meta.
Why it matters
No other file in the estate was found to import it.
Application
star-maker · machinery/bench · JavaScript module
Uses
node:fs/promises, node:path
Used by
none found
Produces
lineage, norm, canon, walk
Defines here
lineage, norm, canon, walk
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
star-maker@2c477b0cc673304c5b288cee9d0e0ae42d273b2e machinery/bench/logic.mjs:1-80 · blob b6d99acbd447c57560ff63b7a6e57d53e30f72d6 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unreached_review
// LOGIC STARS — our own reasoning, no model, no Meta. Read every constant in every repo and find
// the ones that disagree with themselves: one NAME, several VALUES, across files. Those are the
// things a mind can reason with: a voltage that is 33 here and 66 there, a technology list that
// has wind_onshore in one place and wind in another, an earth radius with three decimals.
//
//   node logic.mjs      → star-maker/logic/<name>.json + LOGIC.md
import { readFile, readdir, writeFile, mkdir, stat } from 'node:fs/promises';
import path from 'node:path';

const ROOT = process.env.ESTATE_DIR || 'C:/Users/vikra/Documents/GitHub';
const SKY = process.env.SKY_DIR || 'C:/Users/vikra/Documents/GitHub/star-maker';
const SKIP = /[\\/](\.git|node_modules|dist|build|vendor|\.venv|homepage_versions|restore_points|site_versions)[\\/]/;
const EXT = new Set(['.js', '.mjs', '.cjs', '.py', '.ts']);
const lineage = p => p.replace(/\d{12}[-_]?/g, '').replace(/[\\/]/g, '/');   // collapse timestamped copies

// NAME = literal   (js const/let/var, py module-level); literal = number, string, array, new Set([...])
const RX = /(?:^|\n)[ \t]*(?:(?:export\s+)?(?:const|let|var)\s+)?([A-Z][A-Z0-9_]{2,})\s*(?::\s*[\w<>\[\]]+)?\s*=\s*(-?\d+(?:\.\d+)?(?:e-?\d+)?|'[^'\n]*'|"[^"\n]*"|\[[^\]\n]{0,400}\]|new Set\(\[[^\]\n]{0,400}\]\)|Object\.freeze\(\[[^\]\n]{0,400}\]\))\s*[;,\n]/g;
const norm = v => v.startsWith('new Set(') ? 'set' + v.slice(7, -1) : v.startsWith('Object.freeze(') ? v.slice(14, -1) : v;
const canon = v => { const n = norm(v); if (/^[\[s]/.test(n)) { const items = (n.match(/'[^']*'|"[^"]*"|-?\d+(?:\.\d+)?/g) || []).map(x => x.replace(/^["']|["']$/g, '')); return (n.startsWith('set') ? 'set' : 'list') + JSON.stringify(items.slice().sort()); } return n.replace(/^["']|["']$/g, ''); };

async function* walk(dir) {
  for (const e of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
    const p = path.join(dir, e.name);
    if (SKIP.test(p + (e.isDirectory() ? '/' : ''))) continue;
    if (e.isDirectory()) yield* walk(p); else if (EXT.has(path.extname(e.name)) && (await stat(p)).size < 3_000_000) yield p;
  }
}

const byName = new Map();  // name → Map(canonValue → Set(lineage file))
let files = 0, hits = 0;
for await (const f of walk(ROOT)) {
  files++;
  const text = await readFile(f, 'utf8').catch(() => '');
  const rel = lineage(path.relative(ROOT, f));
  for (const m of text.matchAll(RX)) {
    const name = m[1], value = canon(m[2]);
    if (/^(TRUE|FALSE|NULL|NONE|__[A-Z_]+__)$/.test(name)) continue;
    hits++;
    if (!byName.has(name)) byName.set(name, new Map());
    const vals = byName.get(name);
    if (!vals.has(value)) vals.set(value, new Set());
    vals.get(value).add(rel);
  }
}

const stars = [];
for (const [name, vals] of byName) {
  if (vals.size < 2) continue;
  const values = [...vals].map(([value, fs]) => ({ value, files: [...fs].sort() }));
  const repos = new Set(values.flatMap(v => v.files.map(f => f.split('/')[0])));
  const kind = /TECH|BUCKET|LAYER|IDS|TYPES|VOCAB|STATUS/.test(name) && values.some(v => /^(list|set)/.test(v.value)) ? 'vocabulary-drift'
             : /^R_|RADIUS|EARTH|KM|KV|MVA|MW|VOLT|FREQ|HZ|TOL|EPS|LIMIT|MAX|MIN|THRESH/.test(name) ? 'physics-drift' : 'constant-drift';
  stars.push({ name, kind, distinct_values: values.length, repos: [...repos].sort(), files: values.reduce((n, v) => n + v.files.length, 0), values,
    reason: `${name} is defined ${values.length} different ways across ${repos.size} repo(s); a reader of one file cannot know which is true.` });
}
stars.sort((a, b) => (b.repos.length * b.distinct_values) - (a.repos.length * a.distinct_values) || b.files - a.files);

await mkdir(path.join(SKY, 'logic'), { recursive: true });
for (const s of stars) await writeFile(path.join(SKY, 'logic', `${s.name}.json`), JSON.stringify(s, null, 2));
const md = `# Logic stars — ${stars.length} constants that disagree with themselves

Scanned ${files} code files across the estate (timestamped copies collapsed to one lineage), ${hits} constant definitions read. No model was used; this is a regular-expression reading of \`NAME = literal\` and a comparison of the literals. A logic star is one NAME with two or more distinct VALUES. Updated ${new Date().toISOString()}.

| kind | stars |
|---|---|
| physics-drift | ${stars.filter(s => s.kind === 'physics-drift').length} |
| vocabulary-drift | ${stars.filter(s => s.kind === 'vocabulary-drift').length} |
| constant-drift | ${stars.filter(s => s.kind === 'constant-drift').length} |

## Physics — reason with these first
${stars.filter(s => s.kind === 'physics-drift').slice(0, 40).map(s => `- **${s.name}** — ${s.distinct_values} values across ${s.repos.join(', ')}: ${s.values.map(v => `\`${v.value.slice(0, 40)}\` (${v.files.length})`).join(' · ')}`).join('\n') || '- none'}

## Vocabularies that drift (a list of technologies, layers, ids that is not the same list everywhere)
${stars.filter(s => s.kind === 'vocabulary-drift').slice(0, 40).map(s => `- **${s.name}** — ${s.distinct_values} versions across ${s.repos.join(', ')}`).join('\n') || '- none'}

## Everything else, most-spread first
${stars.filter(s => s.kind === 'constant-drift').slice(0, 60).map(s => `- **${s.name}** — ${s.distinct_values} values, ${s.files} files, ${s.repos.join(', ')}`).join('\n') || '- none'}
`;
await writeFile(path.join(SKY, 'LOGIC.md'), md);
console.log(`logic: ${files} files, ${hits} constants, ${stars.length} logic stars → ${path.join(SKY, 'LOGIC.md')}`);

Magnetar

A JavaScript module in the bench folder of Star Maker that reads field. It is built from the hops step (`hops`).

storagestar-maker / machinery/bench/magnetar.mjs · lines 1–64 of 64 · Not reached from any entry point (candidate for review)

What it does
It loads field. Defines hops. Uses libraries node:fs/promises, node:child_process, node:util, node:path. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: JSON file atoms.json. Out: JSON file field.json; JSON file graph.json.
What it achieves
THE MAGNETAR — a neutron star with a field a thousand trillion times the Earth's.
Why it matters
No other file in the estate was found to import it.
Application
star-maker · machinery/bench · JavaScript module
Uses
node:fs/promises, node:child_process, node:util, node:path
Used by
none found
Produces
hops
Defines here
hops
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
star-maker@2c477b0cc673304c5b288cee9d0e0ae42d273b2e machinery/bench/magnetar.mjs:1-64 · blob f6642784629d4a1b656d7c3eac216b8e7db778af · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: unreached_review
// THE MAGNETAR — a neutron star with a field a thousand trillion times the Earth's. Laws used:
// mass bends everything toward it; a dipole has two poles and its field falls with the cube of
// distance; the crust cracks under magnetic stress and the starquake is a flare — a burst you can
// date. Applied: mass of a repo = the callers its souls attract from elsewhere (electrons bound
// to it); the two heaviest repos are the poles; the field at a repo = Σ pole mass / hops³, where
// hops = 1 if the repo bonds to the pole directly, 2 if through another repo, 3 otherwise;
// starquakes = commits that moved many files at once, dated, per repo (git log). No model.
//
//   node magnetar.mjs  → star-maker/magnetar/{field.json, graph.json}, MAGNETAR.md
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import path from 'node:path';
const run = promisify(execFile);
const SKY = process.env.SKY_DIR || 'C:/Users/vikra/Documents/GitHub/star-maker';
const ROOT = process.env.ESTATE_DIR || 'C:/Users/vikra/Documents/GitHub';
const OUT = path.join(SKY, 'magnetar'); await mkdir(OUT, { recursive: true });
const atoms = JSON.parse(await readFile(path.join(SKY, 'electron', 'atoms.json'), 'utf8')).top;   // top 500 bonded souls

// mass and bonds
const mass = new Map(), bonds = new Map();   // repo → Set(repo it bonds to)
for (const a of atoms) for (const home of a.homes) { mass.set(home, (mass.get(home) || 0) + a.valence); for (const r of a.valence_repos) (bonds.get(r) || bonds.set(r, new Set()).get(r)).add(home); }
const repos = [...new Set([...mass.keys(), ...bonds.keys()])];
const poles = [...mass].sort((a, b) => b[1] - a[1]).slice(0, 2).map(([r, m]) => ({ repo: r, mass: m }));
const hops = (from, to) => from === to ? 0 : bonds.get(from)?.has(to) ? 1 : [...(bonds.get(from) || [])].some(mid => bonds.get(mid)?.has(to)) ? 2 : 3;
const field = repos.map(r => { const f = poles.map(p => ({ pole: p.repo, hops: hops(r, p.repo), strength: r === p.repo ? p.mass : p.mass / Math.pow(hops(r, p.repo), 3) }));
  return { repo: r, mass: mass.get(r) || 0, field: Math.round(f.reduce((s, x) => s + x.strength, 0) * 10) / 10, toward: f.sort((a, b) => b.strength - a.strength)[0].pole, bonds_out: [...(bonds.get(r) || [])].length }; })
  .sort((a, b) => b.field - a.field);

// starquakes: commits in the last 60 days that moved ≥ 40 files
const quakes = [];
for (const r of repos) {
  try {
    const { stdout } = await run('git', ['-C', path.join(ROOT, r), 'log', '--since=60 days ago', '--shortstat', '--format=%h|%ci|%s', '-n', '400'], { maxBuffer: 1 << 24 });
    const lines = stdout.split('\n'); let cur = null;
    for (const l of lines) { if (/^[0-9a-f]{7,}\|/.test(l)) { const [h, d, ...s] = l.split('|'); cur = { repo: r, sha: h, date: d.slice(0, 16), subject: s.join('|').slice(0, 90), files: 0 }; }
      else if (cur && /files? changed/.test(l)) { cur.files = Number((l.match(/(\d+) files? changed/) || [0, 0])[1]); if (cur.files >= 40) quakes.push(cur); cur = null; } }
  } catch {}
}
quakes.sort((a, b) => b.files - a.files);
await writeFile(path.join(OUT, 'field.json'), JSON.stringify({ generated_utc: new Date().toISOString(), poles, field, starquakes: quakes.slice(0, 200) }, null, 2));
const nodes = field.map(f => ({ label: `repo ${f.repo}`, type: poles.some(p => p.repo === f.repo) ? 'pole' : 'body', rag: quakes.some(q => q.repo === f.repo && q.files >= 200) ? 'red' : 'green', reason: `mass ${f.mass} · field ${f.field} · drawn toward ${f.toward} · ${quakes.filter(q => q.repo === f.repo).length} starquakes in 60 days` }));
const edges = field.filter(f => !poles.some(p => p.repo === f.repo)).map(f => ({ from: `repo ${f.repo}`, to: `repo ${f.toward}`, kind: 'FIELD_LINE' }));
await writeFile(path.join(OUT, 'graph.json'), JSON.stringify({ schema: 'magnetar-graph.v1', label: 'The Magnetar', generated_utc: new Date().toISOString(), note: 'Repos as bodies in the field of the two heaviest; FIELD_LINE points where a repo is drawn.', focus_default: nodes[0]?.label, nodes, edges }, null, 2));
const md = `# The Magnetar — two poles, ${repos.length} bodies, ${quakes.length} starquakes in 60 days

Mass = the callers a repo's souls attract from other repos. The two heaviest are the poles; field at a body = Σ pole mass / hops³. A starquake = one commit that moved ≥ 40 files: the crust cracking. Updated ${new Date().toISOString()}. No model.

## Poles
${poles.map(p => `- **${p.repo}** — mass ${p.mass}`).join('\n')}

## The field (who is drawn where)
| body | mass | field | drawn toward | bonds out |
|---|---|---|---|---|
${field.slice(0, 30).map(f => `| ${f.repo} | ${f.mass} | ${f.field} | ${f.toward} | ${f.bonds_out} |`).join('\n')}

## Starquakes (the biggest single commits, dated — where the crust cracked)
${quakes.slice(0, 30).map(q => `- **${q.files} files** · ${q.repo} · ${q.date} · \`${q.sha}\` ${q.subject}`).join('\n') || '- none'}

## For the Spider
\`magnetar/graph.json\` — ${nodes.length} nodes, ${edges.length} FIELD_LINE edges.
`;
await writeFile(path.join(SKY, 'MAGNETAR.md'), md);
console.log(`magnetar: poles ${poles.map(p => p.repo).join(' & ')} · ${repos.length} bodies · ${quakes.length} starquakes`);

Random

A JavaScript module in the bench folder of Star Maker. It is built from the rnd step (`rnd`).

Set aside from the main view: 93% of its lines are the same as builders/random.mjs (stars), which stays. (near-copy-of, proposed by families.py). 93% of lines shared with Random; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.931 to stars@030ebc202d35959fecd162327892f671d1d9a0cc builders/random.mjs:1-34 853ea451814f8c0329c0ab6a281fecfcac672946
  • sha256 4568aa2129330866cb4ebc143d7542f719bba63fc097b652ca6683269b2e24c5
  • target sha256 f5133c6eb467d3de72b425652fd4b13f89442c303102e5485f2daaa3bb1d8032
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

storagestar-maker / machinery/bench/random.mjs · lines 1–32 of 32 · Not reached from any entry point (candidate for review)

What it does
It loads data. Defines rnd. Uses libraries node:fs/promises, node:path. Side effects: reads or writes files.
Inputs & outputs
In: JSON file graph.json; command-line arguments. Out: JSON file graph.json.
What it achieves
THE RANDOM STAR — picks links on probability alone, no defined logic.
Why it matters
No other file in the estate was found to import it.
Application
star-maker · machinery/bench · JavaScript module
Uses
node:fs/promises, node:path
Used by
none found
Produces
rnd
Defines here
rnd
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
star-maker@2c477b0cc673304c5b288cee9d0e0ae42d273b2e machinery/bench/random.mjs:1-32 · blob 1b137e6ed117f7caa4ad5145f8f5f7821130797c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unreached_review
// THE RANDOM STAR — picks links on probability alone, no defined logic. It takes every node the
// other stars have drawn and joins pairs at random, with a random kind. Nothing here is a
// finding; it is serendipity, offered to Claude + VIK-AI in case an accident is an insight.
// Seeded by the date, so today's randomness can be reproduced tomorrow (a star with a seed).
//
//   node random.mjs [n]  → star-maker/random/graph.json, RANDOM.md
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import path from 'node:path';
const SKY = process.env.SKY_DIR || 'C:/Users/vikra/Documents/GitHub/star-maker';
const OUT = path.join(SKY, 'random'); await mkdir(OUT, { recursive: true });
const N = Number(process.argv[2] || 150);
const seedStr = new Date().toISOString().slice(0, 10);
let s = [...seedStr].reduce((h, c) => (h * 31 + c.charCodeAt(0)) >>> 0, 7) || 1;
const rnd = () => { s ^= s << 13; s >>>= 0; s ^= s >> 17; s ^= s << 5; s >>>= 0; return s / 4294967296; };   // xorshift32
const pool = [];
for (const g of ['soul', 'electron', 'chemistry', 'vedic', 'magnetar']) { try { for (const n of JSON.parse(await readFile(path.join(SKY, g, 'graph.json'), 'utf8')).nodes) pool.push({ ...n, star: g }); } catch {} }
const KINDS = ['MIGHT_TOUCH', 'RHYMES_WITH', 'COULD_REPLACE', 'REMINDS_OF', 'WHAT_IF', 'ENTANGLED_MAYBE'];
const edges = [], used = new Map();
for (let i = 0; i < N && pool.length > 1; i++) { const a = pool[Math.floor(rnd() * pool.length)], b = pool[Math.floor(rnd() * pool.length)]; if (a === b) continue; edges.push({ from: a.label, to: b.label, kind: KINDS[Math.floor(rnd() * KINDS.length)], p: Math.round(rnd() * 1000) / 1000 }); used.set(a.label, a); used.set(b.label, b); }
const nodes = [...used.values()].map(n => ({ label: n.label, type: n.star, rag: 'green', reason: `from the ${n.star} star · ${(n.reason || '').slice(0, 80)}` }));
await writeFile(path.join(OUT, 'graph.json'), JSON.stringify({ schema: 'random-graph.v1', label: 'The Random star', seed: seedStr, generated_utc: new Date().toISOString(), note: 'Links chosen by probability alone. Not findings. Serendipity for Claude + VIK-AI.', focus_default: nodes[0]?.label, nodes, edges }, null, 2));
const md = `# The Random star — ${edges.length} links by chance, seed \`${seedStr}\`

No logic. Pairs drawn at random from every node the other stars drew (${pool.length} in the pool), joined with a random kind and a random weight. None of it is a finding. It exists because a mind that only follows evidence never trips over anything, and sometimes tripping is how a wire is found. Regenerated with the same seed, it gives the same links; a new day, new chance.

${edges.slice(0, 40).map(e => `- ${e.from} —${e.kind} (${e.p})→ ${e.to}`).join('\n')}

## For the Spider
\`random/graph.json\` — ${nodes.length} nodes, ${edges.length} edges. Fly it when you want to get lost on purpose.
`;
await writeFile(path.join(SKY, 'RANDOM.md'), md);
console.log(`random: ${edges.length} links from ${pool.length} nodes, seed ${seedStr}`);

Server

A JavaScript module in the bench folder of Star Maker that reads choice (`readChoice`), writes choice (`writeChoice`) and gets browser (`getBrowser`), using SHA-256.

interactionstar-maker / machinery/bench/server.mjs · lines 1–243 of 243 · Not reached from any entry point (candidate for review) · pattern liveManifest (shared by 2 files)

What it does
It loads data. Defines 16 functions or classes, including dirBytes, runsDir, sha256File, family, liveManifest. Uses libraries node:http, node:fs/promises, node:fs, node:crypto, node:url. Side effects: changes the web page (DOM); reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
README: "The Bench (`server.mjs`) serves GridAtlas read-only from the gridatlas repo and overlays a composition per universe at `/u//atlas/`"
Inputs & outputs
In: JSON file choice.json; JSON file current.json.
What it achieves
It reads choice (`readChoice`), writes choice (`writeChoice`) and gets browser (`getBrowser`). VENTUS OS · THE BENCH — GridAtlas on the lift.
Why it matters
No other file in the estate was found to import it.
Application
star-maker · machinery/bench · JavaScript module
Uses
node:http, node:fs/promises, node:fs, node:crypto, node:url, node:path, puppeteer-core
Used by
none found
Produces
dirBytes, runsDir, sha256File, family, liveManifest, parts, readChoice, writeChoice, universeId, composedManifest, getBrowser, testDrive
Defines here
dirBytes, runsDir, sha256File, family, liveManifest, parts, readChoice, writeChoice, universeId, composedManifest, getBrowser, testDrive, attribute, json, serveFile, body
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
star-maker@2c477b0cc673304c5b288cee9d0e0ae42d273b2e machinery/bench/server.mjs:1-243 · blob 4faff27e07f9dfcd2f0ef378d3c819432adc8d17 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, storage · domain stage: unknown · users: none · canonical: unreached_review
// VENTUS OS · THE BENCH — GridAtlas on the lift.
//
// Serves the real GridAtlas app read-only from the gridatlas repo, but answers
// /atlas/current.json from the bench's own composition, so cartridges can be
// unplugged or swapped to any version in cartridges/ without touching the repo.
// A test drive loads the composed app in Chrome on the GPU and reports health
// per part: exceptions and console errors are attributed to the cartridge whose
// blob URL raised them. Nothing here writes to the repo.
//
//   node server.mjs            → http://127.0.0.1:8790/   (bench UI)
//                                http://127.0.0.1:8790/atlas/   (the composed car, open in your own Chrome)
import http from 'node:http';
import { readFile, readdir, writeFile, mkdir, stat } from 'node:fs/promises';
import { appendFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import puppeteer from 'puppeteer-core';

const PORT = Number(process.env.BENCH_PORT || 8790);
const ATLAS_DIR = process.env.ATLAS_DIR || 'C:/Users/vikra/Documents/GitHub/gridatlas/atlas';
// The shell's canonical deep link fetches /uk_renewables_pipeline/v9/... (served on the live
// site by the globalgrid2050 repo). Serve the same bytes here so deep-link stars arrive for real.
const GG_DIR = process.env.GG_DIR || 'C:/Users/vikra/Documents/GitHub/globalgrid2050';
const CHROME = process.env.CHROME_PATH || 'C:/Program Files/Google/Chrome/Application/chrome.exe';
const BENCH = path.dirname(fileURLToPath(import.meta.url));
const STATE_FILE = path.join(BENCH, 'state', 'choice.json');
const RUNS = path.join(BENCH, 'runs');
// Storage law: the sandbox may use at most CEILING on the local SSD; beyond that, runs go to
// the external SSD. Size is re-measured every 200 runs (a full walk is cheap at this scale).
const SANDBOX_ROOT = path.resolve(BENCH, '..');
const OVERFLOW_RUNS = process.env.BENCH_OVERFLOW_DIR || 'D:/Claude-Sandbox-MSI/bench-runs';
const CEILING_BYTES = Number(process.env.BENCH_CEILING_GB || 100) * 1024 ** 3;
await mkdir(path.dirname(STATE_FILE), { recursive: true });
await mkdir(RUNS, { recursive: true });
let sandboxBytes = 0, runsSinceMeasure = 200;
async function dirBytes(dir) {
  let total = 0;
  for (const e of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
    const p = path.join(dir, e.name);
    if (e.isDirectory()) { if (e.name !== 'node_modules') total += await dirBytes(p); }
    else total += (await stat(p).catch(() => ({ size: 0 }))).size;
  }
  return total;
}
async function runsDir() {
  if (++runsSinceMeasure >= 200) { sandboxBytes = await dirBytes(SANDBOX_ROOT); runsSinceMeasure = 0; }
  if (sandboxBytes < CEILING_BYTES) return RUNS;
  await mkdir(OVERFLOW_RUNS, { recursive: true }).catch(() => {});
  return OVERFLOW_RUNS;
}

const MIME = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.json': 'application/json',
  '.geojson': 'application/geo+json', '.parquet': 'application/octet-stream', '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml',
  '.wasm': 'application/wasm', '.txt': 'text/plain', '.csv': 'text/csv', '.pbf': 'application/x-protobuf', '.ico': 'image/x-icon' };

// ---------- parts: what is on the shelf ----------
const shaCache = new Map();
async function sha256File(file) {
  if (!shaCache.has(file)) shaCache.set(file, createHash('sha256').update(await readFile(file)).digest('hex'));
  return shaCache.get(file);
}
const family = f => f.replace(/^\d{12}-/, '').replace(/-v\d+-\d+\.js$/, '').replace(/\.js$/, '');

async function liveManifest() { return JSON.parse(await readFile(path.join(ATLAS_DIR, 'current.json'), 'utf8')); }

async function parts() {
  const live = await liveManifest();
  const files = (await readdir(path.join(ATLAS_DIR, 'cartridges'))).filter(f => f.endsWith('.js'));
  const shellIndex = await readFile(path.join(ATLAS_DIR, live.shell.index), 'utf8');
  const shellScripts = [...shellIndex.matchAll(/<script\b[^>]*\bsrc=["']([^"']+)["']/gi)].map(m => m[1]);
  const cartridges = await Promise.all(live.cartridge_order.map(async id => {
    const c = live.cartridges.find(x => x.id === id);
    const current = path.basename(c.path);
    const fam = family(current);
    const versions = await Promise.all(files.filter(f => family(f) === fam).sort().reverse().map(async f => ({
      file: f, stamp: f.slice(0, 12), contract: (f.match(/-v(\d+)-(\d+)\.js$/) || ['', '?', '?']).slice(1).join('.'),
      bytes: (await stat(path.join(ATLAS_DIR, 'cartridges', f))).size, live: f === current,
    })));
    return { id, live_version: c.version, live_generation: c.generation, replace_script: c.replace_script,
      family: fam, capabilities: c.capabilities || [], contract: c.contract || null, live_file: current, versions };
  }));
  return { generation: live.generation, release_id: live.release_id, shell: live.shell, shell_scripts: shellScripts, cartridges };
}

// ---------- composition: what is bolted on right now ----------
async function readChoice() {
  try { return JSON.parse(await readFile(STATE_FILE, 'utf8')); } catch { return { enabled: {}, selected: {} }; }
}
async function writeChoice(choice) { await writeFile(STATE_FILE, JSON.stringify(choice, null, 2)); }

// Parallel universes: /u/<id>/atlas/ serves the same atlas with its own composition, so many
// compositions can be driven at once without sharing state. A universe id is the hash of its
// choice — the same seed always addresses the same star.
const universes = new Map();
function universeId(choice) { return createHash('sha1').update(JSON.stringify(choice)).digest('hex').slice(0, 12); }

async function composedManifest(choiceOverride) {
  const live = await liveManifest();
  const choice = choiceOverride || await readChoice();
  const m = structuredClone(live);
  m.previous_generation = live.generation;
  m.generation = 'bench-' + new Date().toISOString().replace(/[-:T]/g, '').slice(0, 12);
  m.bench = { source_generation: live.generation, choice };
  m.cartridge_order = live.cartridge_order.filter(id => choice.enabled[id] !== false);
  m.cartridges = await Promise.all(live.cartridges.filter(c => m.cartridge_order.includes(c.id)).map(async c => {
    const f = choice.selected[c.id];
    if (!f || f === path.basename(c.path)) return c;
    return { ...c, path: './cartridges/' + f, sha256: await sha256File(path.join(ATLAS_DIR, 'cartridges', f)),
      generation: f.slice(0, 12), bench_swapped_from: path.basename(c.path) };
  }));
  return m;
}

// ---------- test drive: run the composed car on the GPU ----------
// One Chrome for all universes: concurrent callers share a single launch promise, so parallel
// drives never race to start a second Chrome on the same profile.
let browserPromise = null, browserHeaded = null;
async function getBrowser(headed) {
  if (browserPromise && browserHeaded === headed) { const b = await browserPromise.catch(() => null); if (b && b.connected) return b; }
  if (browserPromise) { const old = await browserPromise.catch(() => null); await old?.close().catch(() => {}); }
  browserHeaded = headed;
  browserPromise = puppeteer.launch({ executablePath: CHROME, headless: !headed, defaultViewport: { width: 1600, height: 1000 }, protocolTimeout: 180000,
    userDataDir: path.join(BENCH, 'state', 'chrome-profile'),
    args: ['--use-angle=d3d11', '--enable-gpu', '--ignore-gpu-blocklist', '--enable-gpu-rasterization', '--disable-background-timer-throttling'] });
  return browserPromise;
}

async function testDrive({ headed = false, settleMs = 12000, choice = null, query = '', expect = null } = {}) {
  const manifest = await composedManifest(choice || undefined);
  let uid = null;
  if (choice) { uid = universeId(choice); universes.set(uid, choice); }
  const page = await (await getBrowser(headed)).newPage();
  const cdp = await page.createCDPSession();
  await cdp.send('Runtime.enable');
  const exceptions = [], consoleMsgs = [], failedReq = [];
  cdp.on('Runtime.exceptionThrown', e => {
    const d = e.exceptionDetails;
    exceptions.push({ text: String(d.exception?.description || d.text || '').split('\n')[0].slice(0, 300),
      url: d.url || d.stackTrace?.callFrames?.[0]?.url || '', line: d.lineNumber });
  });
  page.on('console', m => { if (['error', 'warning'].includes(m.type())) consoleMsgs.push({ type: m.type(), text: m.text().slice(0, 300), url: m.location()?.url || '' }); });
  page.on('requestfailed', r => failedReq.push(`${r.failure()?.errorText} ${r.url()}`.slice(0, 200)));
  page.on('response', r => { if (r.status() >= 400) failedReq.push(`HTTP ${r.status()} ${r.url()}`.slice(0, 200)); });

  const url = (uid ? `http://127.0.0.1:${PORT}/u/${uid}/atlas/` : `http://127.0.0.1:${PORT}/atlas/`) + (query ? (query.startsWith('?') ? query : '?' + query) : '');
  const t0 = Date.now();
  let navError = null;
  await page.goto(url, { waitUntil: 'networkidle2', timeout: 90000 }).catch(e => { navError = e.message.slice(0, 200); });
  await new Promise(r => setTimeout(r, settleMs));
  const loadMs = Date.now() - t0;

  const probe = await page.evaluate((expect) => {
    const text = document.body?.innerText || '';
    return {
      arrived: expect ? text.includes(expect) : null,
      km: (text.match(/\b\d+(?:\.\d+)?\s?km\b/g) || []).slice(0, 5),
      router: document.body?.dataset?.gridatlasRouter || (document.documentElement.dataset.gridatlasGeneration ? 'composed' : 'unknown'),
      generation: document.documentElement.dataset.gridatlasGeneration || null,
      loaded: (window.__GRIDATLAS_ATLAS__ || {}).loaded_cartridges || [],
      scripts: [...document.querySelectorAll('script[data-gridatlas-cartridge]')].map(s => ({ id: s.dataset.gridatlasCartridge, src: s.src })),
      loaderText: document.getElementById('gridatlas-loader')?.innerText || '',
      layers: { ok: (text.match(/\[OK\]/g) || []).length, wait: (text.match(/\[WAIT\]/g) || []).length, fail: (text.match(/\[(FAIL|ERR|ERROR)\]/g) || []).length },
      canvases: document.querySelectorAll('canvas').length,
      banners: [...document.querySelectorAll('body *')].filter(el => el.children.length === 0 && el.offsetParent && /not installed|mismatch|failed|error/i.test(el.textContent))
        .slice(0, 6).map(el => el.textContent.trim().slice(0, 200)),
    };
  }, expect).catch(e => ({ router: 'probe-failed', probeError: e.message, loaded: [], scripts: [], layers: {}, banners: [] }));
  const deeplinkFailed = consoleMsgs.filter(m => /DEEP LINK FAILED/.test(m.text)).map(m => m.text.slice(0, 200));

  const byBlob = new Map(probe.scripts.map(s => [s.src, s.id]));
  const attribute = u => byBlob.get(u) || (!u ? 'unattributed' : u.includes('/atlas/releases/') ? 'shell' : /cdn\.|unpkg|jsdelivr/.test(u) ? 'vendor' : u.includes('/atlas/') ? 'loader' : /favicon\.ico/.test(u) ? 'noise' : 'other');
  const findings = [
    ...exceptions.map(e => ({ level: 'exception', part: attribute(e.url), text: e.text, url: e.url, line: e.line })),
    ...consoleMsgs.map(m => ({ level: m.type === 'error' ? 'console-error' : 'warning', part: attribute(m.url), text: m.text, url: m.url })),
  ];
  const partIds = [...manifest.cartridge_order, 'shell', 'loader', 'vendor', 'other', 'unattributed'];
  const health = Object.fromEntries(partIds.map(id => {
    const mine = findings.filter(f => f.part === id);
    const colour = mine.some(f => f.level === 'exception') ? 'red' : mine.some(f => f.level === 'console-error') ? 'amber' : 'green';
    return [id, { colour, findings: mine.length }];
  }));
  const realConsoleErrors = findings.filter(f => f.level === 'console-error' && f.part !== 'noise');
  const verdict = probe.router === 'failed' || navError || exceptions.length ? 'RED' : (realConsoleErrors.length || probe.banners.length) ? 'AMBER' : 'GREEN';

  const shot = await page.screenshot({ type: 'jpeg', quality: 60 });
  await page.close();
  const stamp = new Date().toISOString().replace(/[-:.]/g, '').slice(0, 18) + '-' + Math.random().toString(36).slice(2, 6);   // ms + salt: 32 drives can finish in the same second
  const run = { stamp, universe: uid, verdict, loadMs, navError, query: query || null, arrival: expect ? { expected: expect, arrived: probe.arrived, km: probe.km, failed: deeplinkFailed } : null, composition: { generation: manifest.generation, source_generation: manifest.bench.source_generation, order: manifest.cartridge_order,
      cartridges: manifest.cartridges.map(c => ({ id: c.id, file: path.basename(c.path), swapped_from: c.bench_swapped_from || null })) },
    probe: { ...probe, scripts: undefined }, health, findings, failedRequests: failedReq.slice(0, 30), screenshot: `runs/${stamp}.jpg` };
  const dir = await runsDir();
  run.screenshot_path = path.join(dir, `${stamp}.jpg`);
  run.overflow = dir !== RUNS;
  await writeFile(path.join(dir, `${stamp}.json`), JSON.stringify(run, null, 2));
  await writeFile(run.screenshot_path, shot);
  return run;
}

// ---------- http ----------
const json = (res, code, body) => { res.writeHead(code, { 'content-type': 'application/json', 'cache-control': 'no-store' }); res.end(JSON.stringify(body)); };
async function serveFile(res, root, rel) {
  const file = path.normalize(path.join(root, rel));
  if (!file.startsWith(path.normalize(root))) return json(res, 403, { error: 'forbidden' });
  try {
    const data = await readFile(file);
    res.writeHead(200, { 'content-type': MIME[path.extname(file).toLowerCase()] || 'application/octet-stream', 'cache-control': 'no-store' });
    res.end(data);
  } catch { json(res, 404, { error: 'not found', file: rel }); }
}
const body = req => new Promise(r => { let s = ''; req.on('data', c => s += c); req.on('end', () => r(s ? JSON.parse(s) : {})); });

http.createServer(async (req, res) => {
  const u = new URL(req.url, `http://127.0.0.1:${PORT}`);
  try {
    const um = u.pathname.match(/^\/u\/([a-f0-9]{12})\/atlas\/(.*)$/);
    if (um) {
      const choice = universes.get(um[1]); if (!choice) return json(res, 404, { error: 'unknown universe' });
      if (um[2] === 'current.json') return json(res, 200, await composedManifest(choice));
      const rel = decodeURIComponent(um[2]) || 'index.html'; return serveFile(res, ATLAS_DIR, rel.endsWith('/') || rel === '' ? rel + 'index.html' : rel);
    }
    if (u.pathname.startsWith('/uk_renewables_pipeline/')) return serveFile(res, path.join(GG_DIR, 'uk_renewables_pipeline'), decodeURIComponent(u.pathname.slice(24)));
    if (u.pathname === '/atlas/current.json') return json(res, 200, await composedManifest());
    if (u.pathname.startsWith('/atlas/')) { const rel = decodeURIComponent(u.pathname.slice(7)) || 'index.html'; return serveFile(res, ATLAS_DIR, rel.endsWith('/') || rel === '' ? rel + 'index.html' : rel); }
    if (u.pathname === '/api/parts') return json(res, 200, await parts());
    if (u.pathname === '/api/choice' && req.method === 'GET') return json(res, 200, await readChoice());
    if (u.pathname === '/api/choice' && req.method === 'POST') { await writeChoice(await body(req)); return json(res, 200, await composedManifest()); }
    if (u.pathname === '/api/reset') { await writeChoice({ enabled: {}, selected: {} }); return json(res, 200, { ok: true }); }
    if (u.pathname === '/api/manifest') return json(res, 200, await composedManifest());
    if (u.pathname === '/api/testdrive' && req.method === 'POST') { const o = await body(req); return json(res, 200, await testDrive(o)); }
    if (u.pathname === '/api/runs') {
      const files = (await readdir(RUNS)).filter(f => f.endsWith('.json')).sort().reverse().slice(0, 30);
      return json(res, 200, await Promise.all(files.map(async f => { const r = JSON.parse(await readFile(path.join(RUNS, f), 'utf8')); return { stamp: r.stamp, verdict: r.verdict, loadMs: r.loadMs, order: r.composition.order, cartridges: r.composition.cartridges, screenshot: r.screenshot, health: r.health }; })));
    }
    if (u.pathname.startsWith('/runs/')) { const rel = u.pathname.slice(6); return (await stat(path.join(RUNS, rel)).catch(() => null)) ? serveFile(res, RUNS, rel) : serveFile(res, OVERFLOW_RUNS, rel); }
    if (u.pathname === '/api/storage') return json(res, 200, { sandbox_bytes: sandboxBytes, ceiling_bytes: CEILING_BYTES, overflow_dir: OVERFLOW_RUNS, overflowing: sandboxBytes >= CEILING_BYTES });
    if (u.pathname === '/' || u.pathname === '/index.html') return serveFile(res, BENCH, 'index.html');
    json(res, 404, { error: 'no route' });
  } catch (e) {
    try { appendFileSync(path.join(BENCH, 'state', 'server.log'), `${new Date().toISOString()}  500 ${u.pathname}  ${String(e.message).slice(0, 300)}\n`); } catch {}
    json(res, 500, { error: e.message, stack: e.stack });
  }
}).listen(PORT, '127.0.0.1', () => console.log(`BENCH  http://127.0.0.1:${PORT}/   composed atlas → http://127.0.0.1:${PORT}/atlas/`));

Starmaker

A JavaScript module in the bench folder of Star Maker that fetches star control and targets. It reads dial (`readDial`), makes star (`makeStar`) and replays batch (`replayBatch`).

storagestar-maker / machinery/bench/starmaker.mjs · lines 1–225 of 225 · Not reached from any entry point (candidate for review) · pattern survey (shared by 9 files)

What it does
It fetches star control and targets. Defines 18 functions or classes, including readDial, log, git, stampNow, exists. Uses libraries node:fs/promises, node:child_process, node:util, node:crypto, node:url. Side effects: reads or writes files; makes network requests; starts processes.
Inputs & outputs
In: JSON file star-control.json; JSON file build_manifest.json; JSON file targets.json; JSON file report.json.
What it achieves
Runs all night on the MSI.
Why it matters
No other file in the estate was found to import it.
Application
star-maker · machinery/bench · JavaScript module
Uses
node:fs/promises, node:child_process, node:util, node:crypto, node:url, node:path, node:fs
Used by
none found
Produces
readDial, log, git, stampNow, exists, api, seeds, deeplinkSeeds, starId, makeStar, pass, worker
Defines here
readDial, log, git, stampNow, exists, api, seeds, deeplinkSeeds, starId, makeStar, pass, worker, survey, index, by, push, replayBatch, worker
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
star-maker@2c477b0cc673304c5b288cee9d0e0ae42d273b2e machinery/bench/starmaker.mjs:1-225 · blob 4152a7a6a16dae322e483db7854dd0e191780958 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: unknown · users: none · canonical: unreached_review
// STAR-MAKER — runs all night on the MSI. Every composition of GridAtlas is a seed; every drive
// on the GPU is a star; the star-maker repo is the sky.
//
// Pass:    enumerate seeds (live · every unplug subset · every shelf version), drive the ones not
//          yet in the sky, N at a time (GPU headroom), write stars/<id>.json (+ shots/ for non-green).
// Survey:  hourly, the eyes rig over every published page → sky/survey-<stamp>.json.
// Loop:    push after each pass/survey; new pass only when the live atlas generation changes.
//
//   node starmaker.mjs          (Bench server.mjs must be running on :8790)
import { readFile, readdir, writeFile, mkdir, copyFile, access } from 'node:fs/promises';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import path from 'node:path';

const run = promisify(execFile);
const BENCH_URL = 'http://127.0.0.1:8790';
const BENCH = path.dirname(fileURLToPath(import.meta.url));
const EYES = path.resolve(BENCH, '..', 'eyes');
const SKY = process.env.SKY_DIR || 'C:/Users/vikra/Documents/GitHub/star-maker';
const ATLAS_REPO = process.env.ATLAS_REPO || 'C:/Users/vikra/Documents/GitHub/gridatlas';
const HOST_NAME = process.env.STAR_HOST || 'MSI · RTX 5070 Ti';
const ORDER = process.env.STAR_ORDER || 'forward';   // a second machine runs 'reverse' so the two meet in the middle
const CONCURRENCY = Number(process.env.STAR_CONCURRENCY || 12);  // measured at 4: GPU 9 %, VRAM 1.6 GB, CPU 2 % — a drive is 12 s of waiting, so breadth is the lever
// Live control: state/star-control.json {"concurrency": N} is re-read every few seconds, so the
// watch can turn the dial without a restart. Workers above the dial idle; below it, they work.
const MAX_WORKERS = Number(process.env.STAR_MAX_WORKERS || 32);   // 24 cores: each universe is a Chrome renderer; the tick's headroom law sets the live dial
const CONTROL_FILE = path.join(path.dirname(fileURLToPath(import.meta.url)), 'state', 'star-control.json');
let dial = CONCURRENCY;
async function readDial() { try { const c = JSON.parse(await readFile(CONTROL_FILE, 'utf8')); if (Number.isFinite(c.concurrency)) dial = Math.max(1, Math.min(MAX_WORKERS, c.concurrency)); } catch {} }
const SURVEY_EVERY_MS = 60 * 60 * 1000;
const IDLE_MS = 30 * 60 * 1000;
const MAX_STARS_PER_PASS = Number(process.env.STAR_MAX || 6000);
const PUSH_EVERY = 100;  // stars between pushes during a long pass, so the sky grows while the pass runs
// Log to a file directly: stdout redirected by a parent shell dies with that shell overnight.
import { appendFileSync } from 'node:fs';
const LOG_FILE = path.join(path.dirname(fileURLToPath(import.meta.url)), 'state', 'starmaker.log');
const log = m => { const line = `${new Date().toISOString()}  ${m}\n`; try { appendFileSync(LOG_FILE, line); } catch {} try { process.stdout.write(line); } catch {} };
const git = (...a) => run('git', ['-C', SKY, ...a], { maxBuffer: 1 << 24 });
const stampNow = () => new Date().toISOString().replace(/[-:]/g, '').slice(0, 15);
const exists = p => access(p).then(() => true, () => false);
const api = (p, body) => fetch(BENCH_URL + p, body ? { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) } : {}).then(r => { if (!r.ok) throw new Error(`${p} HTTP ${r.status}`); return r.json(); });

for (const d of ['stars', 'shots', 'sky']) await mkdir(path.join(SKY, d), { recursive: true });

function seeds(parts) {
  const ids = parts.cartridges.map(c => c.id);
  const out = [{ kind: 'live', label: 'live composition as published', choice: { enabled: {}, selected: {} } }];
  for (let mask = 1; mask < (1 << ids.length); mask++) {
    const off = ids.filter((_, i) => mask & (1 << i));
    out.push({ kind: 'unplug', label: `without ${off.join(' + ')}`, choice: { enabled: Object.fromEntries(off.map(id => [id, false])), selected: {} } });
  }
  for (const c of parts.cartridges) for (const v of c.versions) if (!v.live)
    out.push({ kind: 'version', label: `${c.id} ⇄ ${v.file}`, choice: { enabled: {}, selected: { [c.id]: v.file } } });
  // Phase 2 — constellations: every pair of versions of the two big cartridges, newest first.
  // This is the overnight work: version-interaction faults live here, not in single swaps.
  const [a, b] = parts.cartridges.filter(c => c.versions.length > 10).sort((x, y) => y.versions.length - x.versions.length);
  if (a && b) for (const va of a.versions) for (const vb of b.versions) if (!(va.live && vb.live))
    out.push({ kind: 'constellation', label: `${a.id} ⇄ ${va.stamp} × ${b.id} ⇄ ${vb.stamp}`, choice: { enabled: {}, selected: { [a.id]: va.file, [b.id]: vb.file } } });
  return out;
}

// Phase 4 — deep-link stars: the MAP button, for real projects, from the same canonical
// partitions the shell reads. A star arrives if the project's name is on the page afterwards.
const GG_DIR = process.env.GG_DIR || 'C:/Users/vikra/Documents/GitHub/globalgrid2050';
const DEEPLINK_MAX = Number(process.env.STAR_DEEPLINKS || 3000);
async function deeplinkSeeds() {
  let manifest;
  try { manifest = JSON.parse(await readFile(path.join(GG_DIR, 'uk_renewables_pipeline/v9/data/v9.1/build_manifest.json'), 'utf8')); } catch { return []; }
  const feats = [];
  for (const part of manifest.atlas_partitions || []) {
    try {
      const g = JSON.parse(await readFile(path.join(GG_DIR, 'uk_renewables_pipeline/v9', part.path), 'utf8'));
      for (const f of g.features || []) if (f.geometry?.type === 'Point' && f.properties?.repd_ref && f.properties?.name)
        feats.push({ ref: String(f.properties.repd_ref), tech: part.technology, name: String(f.properties.name), lon: f.geometry.coordinates[0], lat: f.geometry.coordinates[1] });
    } catch {}
  }
  // deterministic spread across technologies: order by hash of the ref, not by file order
  feats.sort((a, b) => createHash('sha1').update(a.ref).digest('hex') < createHash('sha1').update(b.ref).digest('hex') ? -1 : 1);
  return feats.slice(0, DEEPLINK_MAX).map(f => ({
    kind: 'deeplink', label: `MAP → ${f.name} (${f.tech}, REPD ${f.ref})`, choice: { enabled: {}, selected: {} },
    query: `repd_ref=${encodeURIComponent(f.ref)}&technology=${f.tech}&latitude=${f.lat}&longitude=${f.lon}&zoom=12`, expect: f.name,
  }));
}
const starId = (gen, choice, query = '') => createHash('sha1').update(gen + JSON.stringify(choice) + query).digest('hex').slice(0, 12);

async function makeStar(gen, seed, replayOf = null) {
  const id = replayOf || starId(gen, seed.choice, seed.query || '');
  const file = path.join(SKY, 'stars', `${id}.json`);
  if (!replayOf && await exists(file)) return null;
  const r = await api('/api/testdrive', { choice: seed.choice, query: seed.query || '', expect: seed.expect || null });
  let verdict = r.verdict;
  const findings = r.findings.filter(f => f.part !== 'noise').slice(0, 25).map(f => ({ level: f.level, part: f.part, text: f.text, line: f.line }));
  if (seed.expect && r.arrival && !r.arrival.arrived) { verdict = 'RED'; findings.unshift({ level: 'arrival', part: 'shell', text: `did not arrive at "${seed.expect}"${r.arrival.failed[0] ? ' — ' + r.arrival.failed[0] : ''}` }); }
  if (replayOf) {
    const prev = JSON.parse(await readFile(file, 'utf8'));
    const same = prev.verdict === verdict && JSON.stringify(prev.findings.filter(f => f.level === 'exception').map(f => f.text)) === JSON.stringify(findings.filter(f => f.level === 'exception').map(f => f.text));
    prev.replays = [...(prev.replays || []), { at: new Date().toISOString(), host: HOST_NAME, verdict, same, findings: same ? undefined : findings.slice(0, 5) }];
    await writeFile(file, JSON.stringify(prev, null, 2));
    return { ...prev, verdict: same ? 'SAME' : 'DIFF', id };
  }
  const star = {
    id, seed: { source_generation: gen, kind: seed.kind, label: seed.label, choice: seed.choice, query: seed.query || undefined, expect: seed.expect || undefined },
    verdict, arrival: r.arrival || undefined, loadMs: r.loadMs, router: r.probe.router, layers: r.probe.layers, canvases: r.probe.canvases,
    loaded: r.composition.order, health: r.health,
    findings, banners: r.probe.banners, bench_run: r.stamp, made_at: new Date().toISOString(), host: HOST_NAME,
  };
  if (verdict !== 'GREEN') { await copyFile(r.screenshot_path || path.join(BENCH, r.screenshot), path.join(SKY, 'shots', `${id}.jpg`)); star.shot = `shots/${id}.jpg`; }
  await writeFile(file, JSON.stringify(star, null, 2));
  return star;
}

async function pass() {
  const parts = await api('/api/parts');
  const gen = parts.generation;
  const queue = [...seeds(parts), ...await deeplinkSeeds()].slice(0, MAX_STARS_PER_PASS);
  if (ORDER === 'reverse') queue.reverse();
  await readDial();
  log(`pass on generation ${gen}: ${queue.length} seeds, dial ${dial} (max ${MAX_WORKERS})`);
  let made = 0, skipped = 0, failed = 0; const t0 = Date.now();
  const dialWatcher = setInterval(async () => { const before = dial; await readDial(); if (dial !== before) log(`dial ${before} → ${dial}`); }, 5000);
  const worker = async (i) => {
    while (queue.length) {
      if (i >= dial) { await new Promise(r => setTimeout(r, 5000)); continue; }
      const seed = queue.shift();
      try { const s = await makeStar(gen, seed); if (s) { made++; log(`  ${s.verdict.padEnd(5)} ${s.id} ${seed.label}`); if (made % PUSH_EVERY === 0) await push(`stars: +${PUSH_EVERY} (${made} this pass) on ${gen}`).catch(e => log('mid-pass push: ' + e.message)); } else skipped++; }
      catch (e) {
        if (!seed.retried) { seed.retried = true; queue.push(seed); log(`  RETRY ${seed.label}: ${e.message}`); }
        else { failed++; log(`  ERROR ${seed.label}: ${e.message}`); }
      }
    }
  };
  await Promise.all(Array.from({ length: MAX_WORKERS }, (_, i) => worker(i)));
  clearInterval(dialWatcher);
  log(`pass done: ${made} new stars, ${skipped} already in the sky, ${failed} failed, ${Math.round((Date.now() - t0) / 1000)} s`);
  return { gen, made, skipped, failed };
}

async function survey() {
  const stamp = stampNow();
  const targets = path.join(EYES, 'targets.json');
  await run('node', ['eyes.mjs', targets, '--failures-only', '--concurrency', String(CONCURRENCY)], { cwd: EYES, maxBuffer: 1 << 24 }).catch(e => log('survey error: ' + e.message.slice(0, 200)));
  const runs = (await readdir(path.join(EYES, 'runs'))).sort().reverse();
  if (runs[0]) await copyFile(path.join(EYES, 'runs', runs[0], 'report.json'), path.join(SKY, 'sky', `survey-${stamp}.json`));
  log(`survey ${stamp} written`);
}

async function index() {
  const files = (await readdir(path.join(SKY, 'stars'))).filter(f => f.endsWith('.json'));
  const stars = await Promise.all(files.map(async f => JSON.parse(await readFile(path.join(SKY, 'stars', f), 'utf8'))));
  const by = v => stars.filter(s => s.verdict === v);
  const gens = [...new Set(stars.map(s => s.seed.source_generation))].sort();
  const md = `# The sky — ${stars.length} stars

Generated on the MSI (RTX 5070 Ti) by star-maker. A star is one composition of GridAtlas driven on the GPU. Updated ${new Date().toISOString()}.

| verdict | stars |
|---|---|
| 🟢 GREEN | ${by('GREEN').length} |
| 🟡 AMBER | ${by('AMBER').length} |
| 🔴 RED | ${by('RED').length} |

Source generations: ${gens.join(', ')}

## Red stars (supernovae)
${by('RED').map(s => `- \`${s.id}\` ${s.seed.label} — ${s.findings.filter(f => f.level === 'exception').map(f => `**${f.part}**: ${f.text}`).slice(0, 2).join('; ')}${s.shot ? ` ([shot](${s.shot}))` : ''}`).join('\n') || '- none'}

## Amber stars
${by('AMBER').map(s => `- \`${s.id}\` ${s.seed.label} — ${(s.banners[0] || s.findings[0]?.text || '').slice(0, 120)}`).join('\n') || '- none'}

## Hidden wires found (a part that fails only when another is unplugged)
${stars.filter(s => s.seed.kind === 'unplug' && s.verdict === 'RED').flatMap(s => s.findings.filter(f => f.level === 'exception').map(f => `- **${f.part}** breaks ${s.seed.label}: ${f.text}`)).filter((v, i, a) => a.indexOf(v) === i).join('\n') || '- none yet'}
`;
  await writeFile(path.join(SKY, 'SKY.md'), md);
}

async function push(msg) {
  await index();
  for (const p of ['stars', 'shots', 'sky', 'SKY.md', 'logic', 'LOGIC.md', 'soul', 'SOUL.md', 'chemistry', 'CHEMISTRY.md', 'electron', 'ELECTRON.md', 'magnetar', 'MAGNETAR.md', 'vedic', 'VEDIC.md', 'random', 'RANDOM.md', 'voltage', 'VOLTAGE.md', 'elements', 'PERIODIC-TABLE.md']) await git('add', '--', p).catch(() => {});
  if ((await git('status', '--porcelain')).stdout.trim())
    await git('commit', '-q', '-m', `${msg}\n\nCo-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>`);
  // Two machines share one sky: take theirs first (their stars then count as "already made"),
  // then push ours. A conflict can only be two hosts writing the same star; ours wins locally
  // and the difference is a finding for the morning, not a failure.
  await git('pull', '--rebase', '--autostash', '--quiet', '-X', 'ours').catch(e => log('pull failed: ' + e.message.slice(0, 200)));
  await git('push', '--quiet').catch(e => log('push failed: ' + e.message.slice(0, 200)));
  log(`pushed: ${msg}`);
}

// Phase 5 — replay: never idle. Re-drive existing stars, oldest-replayed first, and record
// whether the same seed gave the same star. A DIFF is a finding (flakiness, network, time).
async function replayBatch(n = 200) {
  const files = (await readdir(path.join(SKY, 'stars'))).filter(f => f.endsWith('.json'));
  const stars = await Promise.all(files.map(async f => JSON.parse(await readFile(path.join(SKY, 'stars', f), 'utf8'))));
  stars.sort((a, b) => (a.replays?.length || 0) - (b.replays?.length || 0) || (a.made_at < b.made_at ? -1 : 1));
  const queue = stars.slice(0, n);
  await readDial();
  log(`replay batch: ${queue.length} stars, dial ${dial}`);
  let same = 0, diff = 0;
  const worker = async (i) => {
    while (queue.length) {
      if (i >= dial) { await new Promise(r => setTimeout(r, 5000)); continue; }
      const s = queue.shift();
      try { const r = await makeStar(s.seed.source_generation, s.seed, s.id); if (r.verdict === 'SAME') same++; else { diff++; log(`  DIFF  ${s.id} ${s.seed.label}`); } }
      catch (e) { log(`  ERROR replay ${s.id}: ${e.message}`); }
    }
  };
  await Promise.all(Array.from({ length: MAX_WORKERS }, (_, i) => worker(i)));
  log(`replay done: ${same} same, ${diff} diff`);
  return { same, diff };
}

log(`star-maker up · sky at ${SKY} · order ${ORDER}`);
let lastGen = null, lastSurvey = 0;
for (;;) {
  try {
    const parts = await api('/api/parts');
    if (parts.generation !== lastGen) { const r = await pass(); lastGen = r.gen; await push(`stars: ${r.made} new on generation ${r.gen}`); }
    else { const r = await replayBatch(200); await push(`replay: ${r.same} same, ${r.diff} diff`); }
    if (Date.now() - lastSurvey > SURVEY_EVERY_MS) { await survey(); lastSurvey = Date.now(); await push(`sky: survey ${stampNow()}`); }
    await run('git', ['-C', ATLAS_REPO, 'pull', '--ff-only', '--quiet']).catch(() => {});
  } catch (e) { log('loop error: ' + e.message); }
  await new Promise(r => setTimeout(r, 15000));
}

Tick

A PowerShell script in the bench folder of Star Maker.

automationstar-maker / machinery/bench/tick.ps1 · lines 1–29 of 29 · Not reached from any entry point (candidate for review)

What it does
Side effects: starts processes.
What it achieves
The 10-minute watch in one command.
Why it matters
No other file in the estate was found to import it.
Application
star-maker · machinery/bench · PowerShell script
Uses
none found
Used by
none found
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
star-maker@2c477b0cc673304c5b288cee9d0e0ae42d273b2e machinery/bench/tick.ps1:1-29 · blob fa7692cb29c65b49d548a092f254b91f0891fcad · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unreached_review
# tick.ps1 — the 10-minute watch in one command. Prints the state and turns the dial by the
# headroom law. Law: GPU < 40 % and CPU < 50 % and VRAM < 6 GB and temp < 75 → dial +2 (max 16);
# GPU > 70 % or CPU > 70 % or VRAM > 8 GB or temp > 80 → dial −2 (min 4); otherwise hold.
$b = 'C:\Users\vikra\Desktop\Claude-Sandbox-MSI\bench'; $sky = 'C:\Users\vikra\Documents\GitHub\star-maker'
$ctl = "$b\state\star-control.json"
$procs = Get-CimInstance Win32_Process -Filter "name='node.exe'" | % { (($_.CommandLine).Trim() -split '\s+')[-1] }
$alive = @('server.mjs','starmaker.mjs','controlpad.mjs') | % { "$_=" + [int]($procs -contains $_) }
$m = [regex]::Matches((nvidia-smi --query-gpu=utilization.gpu,memory.used,temperature.gpu --format=csv,noheader,nounits), '\d+')
$g = [int]$m[0].Value; $vram = [int]$m[1].Value; $temp = [int]$m[2].Value
$cpu = [int](Get-CimInstance Win32_Processor).LoadPercentage
$ram = [math]::Round((Get-CimInstance Win32_OperatingSystem).FreePhysicalMemory/1MB, 1)
$stars = Get-ChildItem "$sky\stars" -Filter *.json
$recent = ($stars | ? { $_.LastWriteTime -gt (Get-Date).AddMinutes(-10) }).Count
$tail = Get-Content "$b\state\starmaker.log" | Select-Object -Last 1
$errs = (Get-Content "$b\state\starmaker.log" | Select-Object -Last 200 | Select-String 'ERROR|failed').Count
$dial = 12; if (Test-Path $ctl) { $dial = [int](Get-Content $ctl -Raw | ConvertFrom-Json).concurrency }
$new = $dial
# Target: keep at least 12 of 24 cores and >= 10 % GPU busy, never hot. Climb fast when cold.
# RAM law (architect, 2026-09-13): the workers may take everything above ~5 GB of Windows
# headroom plus a 2 GB overrun buffer — climb while free RAM > 7 GB, back off below 5 GB.
if ($g -lt 40 -and $cpu -lt 50 -and $vram -lt 6144 -and $temp -lt 75 -and $ram -gt 7) { $new = [math]::Min(32, $dial + $(if ($cpu -lt 25) { 4 } else { 2 })) }
if ($g -gt 70 -or $cpu -gt 70 -or $vram -gt 8192 -or $temp -gt 80 -or $ram -lt 5) { $new = [math]::Max(4, $dial - 4) }
if ($tail -match 'pass done') { $new = $dial }   # nothing to speed up
if ($new -ne $dial) { "{`"concurrency`": $new}" | Set-Content $ctl -Encoding ascii }
$storage = try { (Invoke-RestMethod http://127.0.0.1:8790/api/storage -TimeoutSec 5) } catch { $null }
$sb = if ($storage) { [math]::Round($storage.sandbox_bytes/1GB, 2) } else { '?' }
$lastPush = git -C $sky log -1 --format='%cr' 2>$null
"TICK $(Get-Date -Format 'HH:mm') | $($alive -join ' ') | stars $($stars.Count) (+$recent in 10 min) | GPU ${g}% ${vram} MiB ${temp} C | CPU ${cpu}% | RAM free ${ram} GB | errs(last 200 lines) ${errs} | dial ${dial} -> ${new} | sandbox ${sb} GB overflow=$($storage.overflowing) | last push ${lastPush}"
"LAST: $tail"