GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / stars / library

Build and 4 more files (part 2)

A JavaScript module in the modular star folder of Stars that fetches live sites, engine graph, compounds and decays from the ventus-grid-engine repository.

673 lines of JavaScript from stars, in 5 files. Topic: Kuiper, cosmos and drawing engines. Section 1580 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. Standalone geodesy · stars / library/standalone.mjs lines 12440–12585
  2. Blocks storage · stars / modular-star/blocks.mjs lines 1–122
  3. Build render · stars / modular-star/build.mjs lines 1–349
  4. Check Permanent other · stars / modular-star/check-permanent.mjs lines 1–13
  5. Coherence storage · stars / modular-star/coherence.mjs lines 1–43

Standalone

A JavaScript module in the library folder of Stars that maps Renewable Energy Planning Database (REPD) master and heavy emitters UK, using SHA-256, and uses data from the GridAtlas repository.

Set aside from the main view: A comment at the top of the file says a tool wrote it. (noise-generated, proposed by noise.py). All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line 2 comment: // Generated by the modular star 2026-12-05T23:26:43.596Z. Each export is one family's earliest-seen copy, unchanged; the comment links its source.

geodesystars / library/standalone.mjs · lines 12440–12585 of 12585 (continued from section 1562) · Entry point · pattern segmentConductors (shared by 2 files)

What it does
It maps REPD master, heavy emitters UK, notice and substations. Defines 1111 functions or classes, including f1586_invariant, f8767_representativePoint, f8768_voltagesKv, f8772_voltageOf, f8773_ratingsOf. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain terms in the code: substations, 750kV, 400kV, 275kV, 132kV, 66kV.
Inputs & outputs
In: data source: gridatlas data; JSON file repd_master.json; JSON file heavy_emitters_uk.json; JSON file notice.json; form fields (user input). Out: canvas drawing. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326. Voltage levels named: 750kV, 400kV, 275kV, 132kV, 66kV, 33kV, 1.5kV, 1500V.
Downstream impact
Used directly by 4 files: Code (stars, https://ventusltd.github.io/stars/code.html); Proof (stars); Modular Star Workflow (stars); Testcode — Code Record Page (globalgrid2050, https://globalgrid2050.com/testcode/202609141754/code-record/). Reached from 383 other entry points, including Code Generator — Index Page (code-generator, https://ventusltd.github.io/code-generator/); Generate (code-generator, https://ventusltd.github.io/code-generator/); 404 (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/404.html).
What it achieves
It snaps coordinate (`snapCoordinate`), paints cursor (`paintCursor`) and sets plan (`setPlan`). Compiled library of self-contained JavaScript functions that appear in two or more places across Ventusltd code. Its code works with 33 kV, 132 kV and 275 kV. It responds to abort events.
Why it matters
Loaded by the Code page at https://ventusltd.github.io/stars/code.html and 1 other page. Run by Proof and Modular Star Workflow.
Application
stars · library · JavaScript module
VEDIC
MEASURE (GG2050-VEDIC-000001): GridAtlas / Geodesy · Mathematics / Spherical geometry. coordinate_pair, coordinate_pair → distance_km
VEDIC
REPRESENT (GG2050-VEDIC-000002): GridAtlas / Geodesy · Computer science / Geometry processing. geojson_geometry → coordinate_pair_or_null
VEDIC
VOLTAGE (GG2050-VEDIC-000003): GridAtlas / Geodesy · Computer science / Data normalisation. voltage_properties → kilovolt_list
Uses
GlobalGrid2050 — Renewable Energy Planning Database (REPD) Grid Atlas v8 Page (estate URL), Declared Connections (estate URL)
Used by
named by URL in Code (estate URL), run by Proof (script call), run by Modular Star Workflow (workflow run), named by URL in Testcode — Code Record Page (estate URL)
Produces
f1586_invariant, f8767_representativePoint, f8768_voltagesKv, f8772_voltageOf, f8773_ratingsOf, f8775_parametersOf, f5168_escapeHTML, f8321_suppliedArrivalFields, f8850__anonymous_, f8786_crossing, f8788_legality, f8789_startNodes
Defines here
f179120_result, f179416__anonymous_, f179418_fieldPlan, f179518_consecutive, f180799_validDestinationCoordinate, f180923_reconcileNavigationLayers, f180926_rankHigherVoltage, valid, f181073_viewportBounds, outward, f182002_geometry, point, vector, f182005_relativeGuidance, f182014_stableLabel
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
stars@030ebc202d35959fecd162327892f671d1d9a0cc library/standalone.mjs:12440-12585 · blob fc3d8c8b93e14d4a56b8a26da47071d60bc5bc4d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: unknown · users: none · canonical: unknown
export const f179120_result = function result(side) {
  const route = { id: 'fictional', straightLineKm: 1, crossings: [] };
  if (Object.hasOwn(side, 'lengthM')) route.installedLengthM = side.lengthM;
  return screen({
    electrical: { currentA: side.currentA, nominalVolts: 1000, resistanceOhmPerKm: 0.2,
      reactanceOhmPerKm: 0.1, powerFactor: 0.8, phases: 'single' },
    options: [route],
  }).options[0].electrical;
};

// Family #179416 · element #179416 · 2 places in 1 repositories · https://github.com/Ventusltd/gridatlas/blob/f944f8dcbc09cd09c0895f0126682ec241cd576f/atlas/modules/20261202-g203-04-satnav-walk-saved-plan.js#L11-L18
export const f179416__anonymous_ = pin => {
    const at = pin?.coordinate ?? pin;
    if (!Array.isArray(at) || at.length !== 2 || !at.every(Number.isFinite)
        || Math.abs(at[0]) > 180 || Math.abs(at[1]) > 90) {
      throw new Error('A plan pin has invalid coordinates.');
    }
    return [at[0], at[1]];
  };

// Family #179418 · element #179418 · 2 places in 1 repositories · https://github.com/Ventusltd/gridatlas/blob/f944f8dcbc09cd09c0895f0126682ec241cd576f/atlas/modules/20261202-g203-04-satnav-walk-saved-plan.js#L7-L31
export const f179418_fieldPlan = function fieldPlan(pins, maths) {
  if (!Array.isArray(pins) || pins.length < 2 || pins.length > 20000) {
    throw new Error('Choose between 2 and 20,000 plan pins before saving.');
  }
  const coordinates = pins.map(pin => {
    const at = pin?.coordinate ?? pin;
    if (!Array.isArray(at) || at.length !== 2 || !at.every(Number.isFinite)
        || Math.abs(at[0]) > 180 || Math.abs(at[1]) > 90) {
      throw new Error('A plan pin has invalid coordinates.');
    }
    return [at[0], at[1]];
  });
  let totalM = 0;
  const legs = coordinates.slice(1).map((to, i) => {
    const from = coordinates[i];
    const metres = maths.distanceKm(...from, ...to) * 1000;
    const bearing = metres > 0 ? maths.initialBearingDeg(...from, ...to) : null;
    if (!Number.isFinite(metres) || metres < 0 || (bearing !== null && !Number.isFinite(bearing))) {
      throw new Error('Unable to measure the selected plan.');
    }
    totalM += metres;
    return [Math.round(metres), bearing === null ? null : (Math.round(bearing) + 360) % 360];
  });
  return {coordinates, legs, totalM: Math.round(totalM), savedAt: new Date().toISOString()};
};

// Family #179518 · element #179518 · 2 places in 1 repositories · https://github.com/Ventusltd/gridatlas/blob/f944f8dcbc09cd09c0895f0126682ec241cd576f/tools/satnav/pedestrian/mapped-footpaths.mjs#L39-L41
export const f179518_consecutive = function consecutive(a, b) {
  return a && b && b.sequence === a.sequence + 10;
};

// Family #180799 · element #180799 · 2 places in 1 repositories · https://github.com/Ventusltd/gridatlas/blob/f944f8dcbc09cd09c0895f0126682ec241cd576f/atlas/modules/unified-destination-contract.mjs#L61-L65
export const f180799_validDestinationCoordinate = function validDestinationCoordinate(at) {
  return Array.isArray(at) && at.length === 2 &&
    at.every(n => typeof n === 'number' && Number.isFinite(n)) &&
    Math.abs(at[0]) <= 180 && Math.abs(at[1]) <= 90;
};

// Family #180923 · element #180923 · 2 places in 1 repositories · https://github.com/Ventusltd/gridatlas/blob/f944f8dcbc09cd09c0895f0126682ec241cd576f/tools/satnav/guidance/convergence-2km.mjs#L32-L42
export const f180923_reconcileNavigationLayers = function reconcileNavigationLayers(map, ids) {
  if (!ids.every(id => map.getLayer(id))) return false;
  for (const id of ids) {
    if (map.getLayoutProperty(id,'visibility') === 'none') map.setLayoutProperty(id,'visibility','visible');
  }
  const order = map.getStyle()?.layers?.map(layer => layer.id) ?? [];
  const tail = order.slice(-ids.length);
  if (ids.every((id,i) => tail[i] === id)) return false;
  for (const id of ids) map.moveLayer(id);
  return true;
};

// Family #180926 · element #180926 · 2 places in 1 repositories · https://github.com/Ventusltd/gridatlas/blob/f944f8dcbc09cd09c0895f0126682ec241cd576f/tools/satnav/guidance/convergence-2km.mjs#L59-L72
export const f180926_rankHigherVoltage = function rankHigherVoltage(nodes, origin, distanceKm, minimumKv = 33, limit = 5) {
  if (!Array.isArray(nodes) || typeof distanceKm !== 'function') return [];
  const valid = p => Array.isArray(p) && p.length === 2 && p.every(Number.isFinite)
    && Math.abs(p[0]) <= 180 && Math.abs(p[1]) <= 90;
  if (!valid(origin)) return [];
  return nodes.flatMap(node => {
    if (!node || !valid(node.at)) return [];
    const kv = Array.isArray(node.kv) ? node.kv.filter(Number.isFinite) : [];
    if (!kv.some(v => v >= minimumKv)) return [];
    const km = distanceKm(...origin,...node.at);
    if (!Number.isFinite(km) || km <= 0) return [];
    return [{name:String(node.name || 'Unnamed mapped substation'),at:[...node.at],kv:Math.max(...kv),km}];
  }).sort((a,b)=>a.km-b.km || a.name.localeCompare(b.name)).slice(0,limit);
};

// Family #181073 · element #181073 · 2 places in 1 repositories · https://github.com/Ventusltd/gridatlas/blob/f944f8dcbc09cd09c0895f0126682ec241cd576f/atlas/modules/g203-regional-data-viewport.js#L166-L180
export const f181073_viewportBounds = function viewportBounds(west,south,east,north,padding=0.15) {
  if (![west,south,east,north,padding].every(Number.isFinite) || south>north || south < -90 || north > 90 || padding<0 || padding>1) throw new RangeError('Invalid viewport');
  let width=east-west;
  if(width<0) width=((width%360)+360)%360;
  const latitudePad=(north-south)*padding;
  const lo=Math.max(-90,south-latitudePad), hi=Math.min(90,north+latitudePad);
  const padded=width*(1+2*padding);
  if(padded>=360) return {south:lo,north:hi,intervals:[[-180,180]]};
  const rawStart=west-width*padding;
  const start=rawStart>=-180&&rawStart<180?rawStart:(((rawStart+180)%360)+360)%360-180;
  const end=start+padded;
  // Round outward to avoid excluding boundary points through longitude wrapping.
  const outward=(a,z)=>[Math.max(-180,Math.floor((a-1e-12)*1e9)/1e9),Math.min(180,Math.ceil((z+1e-12)*1e9)/1e9)];
  return {south:lo,north:hi,intervals:end<=180?[outward(start,end)]:[outward(start,180),outward(-180,end-360)]};
};

// Family #182002 · element #182002 · 2 places in 1 repositories · https://github.com/Ventusltd/gridatlas/blob/f944f8dcbc09cd09c0895f0126682ec241cd576f/tools/satnav/orientation/orient17a-navigation.mjs#L3-L20
export const f182002_geometry = function geometry(fix,target,now=Date.now()){
 const point=p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite)&&Math.abs(p[0])<=180&&Math.abs(p[1])<=90;
 const pos=[fix?.longitude,fix?.latitude];
 if(!point(pos)||!point(target)||!Number.isFinite(now)||!Number.isFinite(fix?.timestampMs)||fix.timestampMs>now||now-fix.timestampMs>10000||!Number.isFinite(fix.accuracyM)||fix.accuracyM<=0||fix.accuracyM>30)return {distanceM:null,bearingDeg:null,reason:"GPS uncertain"};
 const rad=Math.PI/180,R=6378137;
 const vector=([x,y])=>[Math.cos(y*rad)*Math.cos(x*rad),Math.cos(y*rad)*Math.sin(x*rad),Math.sin(y*rad)];
 const a=vector(pos),b=vector(target),dot=a.reduce((s,v,i)=>s+v*b[i],0);
 const cross=[a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]];
 const central=Math.atan2(Math.hypot(...cross),dot),distanceM=R*central;
 const base={distanceM,bearingDeg:null,accuracyM:fix.accuracyM};
 if(distanceM<=fix.accuracyM)return {...base,reason:"Within GPS uncertainty"};
 if(Math.abs(pos[1])===90||Math.PI-central<=Math.max(1e-10,fix.accuracyM/R))return {...base,reason:"Bearing singular"};
 const x=pos[0]*rad,y=pos[1]*rad;
 const east=-Math.sin(x)*b[0]+Math.cos(x)*b[1];
 const north=-Math.sin(y)*Math.cos(x)*b[0]-Math.sin(y)*Math.sin(x)*b[1]+Math.cos(y)*b[2];
 if(Math.hypot(east,north)<1e-12)return {...base,reason:"Bearing singular"};
 return {...base,bearingDeg:(Math.atan2(east,north)/rad+360)%360,reason:null};
};

// Family #182005 · element #182005 · 2 places in 1 repositories · https://github.com/Ventusltd/gridatlas/blob/f944f8dcbc09cd09c0895f0126682ec241cd576f/tools/satnav/orientation/orient17a-navigation.mjs#L38-L47
export const f182005_relativeGuidance = function relativeGuidance(metrics,heading,now=Date.now()){
 const result={distanceM:metrics?.distanceM??null,relativeDeg:null,label:"Direction uncertain"};
 if(!Number.isFinite(metrics?.bearingDeg)||!Number.isFinite(metrics?.accuracyM)||!Number.isFinite(metrics?.distanceM)||metrics.distanceM<=metrics.accuracyM)return {...result,reason:metrics?.reason??"Bearing unavailable"};
 if(heading?.reference!=="true"||!Number.isFinite(heading.degrees)||heading.degrees<0||heading.degrees>=360||!Number.isFinite(heading.accuracyDeg)||heading.accuracyDeg<0||heading.accuracyDeg>25||!Number.isFinite(heading.timestampMs)||heading.timestampMs>now||now-heading.timestampMs>3000||heading.disturbed===true)return {...result,reason:"Heading reference, accuracy or freshness unverified"};
 const uncertainty=Math.asin(Math.min(1,metrics.accuracyM/metrics.distanceM))*180/Math.PI+heading.accuracyDeg;
 if(uncertainty>45)return {...result,reason:"Combined bearing uncertainty"};
 const r=((metrics.bearingDeg-heading.degrees+540)%360)-180;
 const label=Math.abs(r)<=22.5?"Ahead":Math.abs(r)>=157.5?"Behind":r>0?"Right":"Left";
 return {...result,relativeDeg:r,label,uncertaintyDeg:uncertainty,reason:null};
};

// Family #182014 · element #182014 · 2 places in 1 repositories · https://github.com/Ventusltd/gridatlas/blob/f944f8dcbc09cd09c0895f0126682ec241cd576f/tools/satnav/orientation/orient17a-v9211-heading.mjs#L54-L61
export const f182014_stableLabel = function stableLabel(g,previous){
 if(!Number.isFinite(g.relativeDeg))return g.label;
 const r=g.relativeDeg,a=Math.abs(r);
 if(previous==='Ahead'&&a<=27.5)return 'Ahead';
 if(previous==='Behind'&&a>=152.5)return 'Behind';
 if((previous==='Left'&&r<0||previous==='Right'&&r>0)&&a>17.5&&a<162.5)return previous;
 return g.label;
};

Blocks

A JavaScript module in the modular star folder of Stars that fetches blocks catalogue, table, engine graph and numbers from the star-maker and ventus-grid-engine repositories.

storagestars / modular-star/blocks.mjs · lines 1–122 of 122 · Entry point · pattern lineageOf (shared by 2 files)

What it does
It fetches blocks catalogue, table, engine graph and numbers. Defines 10 functions or classes, including arg, fold, getJson, add, lineageOf. Uses libraries node:fs, node:path. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage sub33kv_design (voltage levels 1kV (all 33kV or below)): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: 1kV.
Inputs & outputs
In: data source: star-maker data; data source: ventus-grid-engine data; JSON file blocks-catalogue.json; JSON file table.json; JSON file engine-graph.json; JSON file numbers.json; command-line arguments. Out: JSON file families.json; JSON file blocks.json; JSON file presets.json; JSON file graph.json. Voltage levels named: 1kV.
Downstream impact
Used directly by 1 file: Modular Star Workflow (stars).
What it achieves
It gets JSON (`getJson`) and is built from the arg step (`arg`) and the fold step (`fold`). The periodic table of blocks: every family grouped into a plain-language block with a permanent number. Its code works with 1 kV. It reads `./blocks-catalogue.json`.
Why it matters
Run by Modular Star Workflow.
Application
stars · modular-star · JavaScript module
Uses
Stars — Index Page (estate URL), node:fs, node:path
Used by
run by Modular Star Workflow (workflow run)
Produces
arg, fold, getJson, add, lineageOf, autoTitle, stampOf, nameOf, s, esc
Defines here
arg, fold, getJson, add, lineageOf, autoTitle, stampOf, nameOf, s, esc
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
stars@030ebc202d35959fecd162327892f671d1d9a0cc modular-star/blocks.mjs:1-122 · blob 272a1b9d864afba2cbb7dc9c0ba5a13c296bf529 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: supporting_data
// The periodic table of blocks: every family grouped into a plain-language block with a permanent number.
// Numbers 1-47 are star-maker's elements and never change; catalogue blocks take 48+ in catalogue order; anything
// unmatched becomes an auto-block per source file, numbered once and persisted in blocks/numbers.json.
// Reads code/f/*.json (written by build.mjs), the star-maker table and the engine-graph. Writes blocks/*.json and
// the Spider graph blocks/graph.json. Usage: node modular-star/blocks.mjs --out .
import { readFileSync, writeFileSync, readdirSync, mkdirSync, existsSync } from 'node:fs';
import path from 'node:path';

const arg = (k, d) => { const i = process.argv.indexOf('--' + k); return i > 0 ? process.argv[i + 1] : d; };
const OUT = arg('out', '.'), SITE = 'https://ventusltd.github.io/stars/';
const now = new Date().toISOString();
const cat = JSON.parse(readFileSync(new URL('./blocks-catalogue.json', import.meta.url), 'utf8'));
const fold = p => p.replace(/(^|[^0-9])\d{8}(\d{4})?(?=[^0-9]|$)/g, '$1{stamp}');
const getJson = async u => { try { const r = await fetch(u); return r.ok ? await r.json() : null; } catch { return null; } };

// ---- inputs
const families = [];
for (const f of readdirSync(path.join(OUT, 'code', 'f'))) for (const r of Object.values(JSON.parse(readFileSync(path.join(OUT, 'code', 'f', f), 'utf8')))) families.push(r);
const table = await getJson('https://raw.githubusercontent.com/Ventusltd/star-maker/main/elements/table.json');
const engineGraph = await getJson('https://ventusltd.github.io/ventus-grid-engine/genome/engine-graph.json');
const engineReason = new Map((engineGraph?.nodes || []).map(n => [n.label, n.reason]));
const numbersPath = path.join(OUT, 'blocks', 'numbers.json');
const numbers = existsSync(numbersPath) ? JSON.parse(readFileSync(numbersPath, 'utf8')) : { next: 48 + cat.blocks.length, auto: {} };

// ---- the blocks, in number order
const blocks = [];
const byKey = new Map();
const add = b => { blocks.push(b); byKey.set(b.key, b); return b; };
for (const e of table?.elements || []) {
  const kind = e.number <= 12 ? 'constant' : e.number <= 31 ? 'engine' : e.number <= 35 ? 'cartridge' : e.number <= 46 ? 'layer' : 'deeplink';
  const category = kind === 'engine' ? (cat.engine_categories[e.name] || 'geodesy') : cat.table_categories[kind];
  const title = kind === 'engine' ? (cat.engine_titles[e.name] || e.name) : kind === 'constant' ? e.name.replace(/_/g, ' ').toLowerCase().replace(/^./, c => c.toUpperCase()) :
    kind === 'layer' ? e.name.replace(/_/g, ' ').replace(/(\d+)kv/i, '$1 kV').replace(/^./, c => c.toUpperCase()) : kind === 'deeplink' ? 'The MAP button (deep-link contract)' : e.name;
  const description = kind === 'engine' ? (cat.engine_descriptions[e.name] || engineReason.get('engine/' + e.name) || '') :
    kind === 'constant' ? `A value globalgrid2050 architecture development must agree on. ${e.state === 'UNSETTLED' ? (e.candidates?.length || 0) + ' different values are in use; which is true is a decision.' : 'Settled.'}` :
    kind === 'layer' ? 'A data layer drawn on the GridAtlas map.' : kind === 'cartridge' ? 'A plug-in part of the GridAtlas map.' : 'The contract every MAP link obeys, so a link always arrives on the right feature.';
  const match = kind === 'engine' ? [`^ventus-grid-engine:engine/${e.name.replace('.', '\\.')}$`] : kind === 'cartridge' ? [`cartridges/\\{stamp\\}-${e.name}`, `parts/\\{stamp\\}-${e.name}`, `modules/\\{stamp\\}-${e.name}`, `/${e.name}\\.js$`] :
    kind === 'layer' ? [`(^|[/_-])${e.name}([/_.-]|$)`] : kind === 'deeplink' ? ['deeplink', 'deep-link'] : [];
  add({ number: e.number, symbol: e.symbol, key: e.symbol, title, description, category, kind, state: e.state || null, match: match.map(m => new RegExp(m, 'i')), families: [], source: 'star-maker table' });
}
cat.blocks.forEach((b, i) => add({ number: 48 + i, symbol: b.symbol, key: b.symbol, title: b.title, description: b.description, category: b.category, kind: b.kind, state: null, match: b.match.map(m => new RegExp(m, 'i')), families: [], source: 'catalogue' }));

// ---- assign every family: first block whose pattern matches any of its source files (lineage form)
const lineageOf = p => p.repo.split('/')[1] + ':' + fold(p.path);
const autoTitle = lineage => { const file = lineage.split(':')[1].split('/').pop().replace(/\{stamp\}-?/g, '').replace(/\.(m?js|py|html?)$/i, ''); return file.replace(/[-_]+/g, ' ').replace(/([a-z])([A-Z])/g, '$1 $2').replace(/^./, c => c.toUpperCase()); };
for (const f of families) {
  const lineages = [...new Set(f.places.map(lineageOf))];
  let block = null;
  outer: for (const b of blocks) for (const l of lineages) for (const m of b.match) if (m.test(l)) { block = b; break outer; }
  if (!block) {
    // Auto-block per source file lineage (the first place's), numbered once and kept.
    const l = lineages[0], key = 'auto:' + l;
    block = byKey.get(key);
    if (!block) {
      if (!numbers.auto[l]) { numbers.auto[l] = numbers.next++; }
      const repo = l.split(':')[0];
      block = add({ number: numbers.auto[l], symbol: 'x' + numbers.auto[l], key, title: autoTitle(l), description: `Functions from ${repo} ${l.split(':')[1]}.`, category: 'other', kind: 'auto', state: null, match: [], families: [], source: 'auto', lineage: l });
    }
  }
  block.families.push(f);
}
mkdirSync(path.join(OUT, 'blocks'), { recursive: true });
writeFileSync(numbersPath, JSON.stringify(numbers, null, 1));

// ---- finish each block: functions inside, needs in plain words, files to copy, where it lives
const stampOf = p => (p.match(/\d{12}|\d{8}/g) || ['0']).sort().pop();
const nameOf = n => cat.needs_words[n] || n;
const out = blocks.map(b => {
  const fams = b.families;
  const defined = new Set(fams.flatMap(f => f.names));
  const needs = [...new Set(fams.flatMap(f => f.needs || []))].filter(x => !defined.has(x)).sort();
  const repos = [...new Set(fams.flatMap(f => f.repos))];
  const live = [...new Set(fams.flatMap(f => f.places.filter(p => p.live).map(p => p.live)))].slice(0, 8);
  // One file per lineage, the newest stamp: what the generator copies when this block is chosen.
  const byLineage = new Map();
  for (const f of fams) for (const p of f.places) { const l = lineageOf(p); const cur = byLineage.get(l); if (!cur || stampOf(p.path) > stampOf(cur.path)) byLineage.set(l, p); }
  const files = [...byLineage.values()].map(p => ({ repo: p.repo, commit: p.commit, path: p.path, live: p.live || null })).slice(0, 12);
  const named = fams.filter(f => f.names[0] !== '(anonymous)');
  b.defined = defined; b.needsRaw = needs;
  return { number: b.number, symbol: b.symbol, title: b.title, description: b.description, category: b.category, kind: b.kind, state: b.state, source: b.source,
    functions: fams.length, named_functions: named.length, families: fams.map(f => f.n),
    inside: named.sort((a, b2) => b2.places.length - a.places.length).slice(0, 40).map(f => ({ family: f.n, name: f.names[0], places: f.places.length, standalone: f.standalone })),
    needs: needs.map(n => ({ name: n, meaning: nameOf(n) })), repos, live, files,
    first_written: fams.map(f => f.first_written).filter(Boolean).sort()[0] || null };
}).sort((a, b) => a.number - b.number);

// Interdependencies between blocks: block A depends on block B when a name A needs is defined inside B.
const namedBlocks = blocks.filter(b => b.kind !== 'auto' && b.families.length);
for (const o of out) {
  const b = byKey.get(o.symbol) || blocks.find(x => x.number === o.number);
  const deps = new Map();
  for (const name of b.needsRaw || []) for (const other of namedBlocks) if (other.number !== b.number && other.defined?.has(name)) { if (!deps.has(other.symbol)) deps.set(other.symbol, []); deps.get(other.symbol).push(name); }
  o.depends_on = [...deps].map(([symbol, via]) => ({ symbol, title: namedBlocks.find(x => x.symbol === symbol).title, via: via.slice(0, 6) }));
}
for (const o of out) o.used_by = out.filter(x => x.depends_on.some(d => d.symbol === o.symbol)).map(x => x.symbol);

mkdirSync(path.join(OUT, 'blocks'), { recursive: true });
// The public table is kept light for phones: family lists live in families.json, the rest in blocks.json.
writeFileSync(path.join(OUT, 'blocks', 'families.json'), JSON.stringify(Object.fromEntries(out.map(b => [b.symbol, b.families]))));
writeFileSync(path.join(OUT, 'blocks', 'blocks.json'), JSON.stringify({ generated_utc: now, categories: cat.categories,
  // Small auto-blocks (under 8 functions) stay in families.json only; they are not shown anywhere.
  blocks: out.filter(b => b.kind !== 'auto' || b.functions >= 8).map(({ families, ...b }) => b.kind === 'auto' ? { ...b, inside: b.inside.slice(0, 6), files: b.files.slice(0, 2), live: b.live.slice(0, 1), repos: b.repos.slice(0, 3) } : { ...b, inside: b.inside.slice(0, 24), files: b.files.slice(0, 8), live: b.live.slice(0, 4) }) }));
writeFileSync(path.join(OUT, 'blocks', 'presets.json'), JSON.stringify({ generated_utc: now, presets: cat.presets }, null, 1));

// ---- Spider graph: blocks wired to their categories and to the repositories they live in. Plain descriptions on the card.
const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
const nodes = [], edges = [];
for (const c of cat.categories) nodes.push({ id: `category:${c.id}`, label: c.title, type: 'category', rag: 'green', reason: c.blurb, gh: null, ext: `${SITE}table.html?category=${c.id}` });
const repoSeen = new Set();
for (const b of out) {
  if (b.kind === 'auto' && b.functions < 8) continue;
  const rag = b.state === 'UNSETTLED' ? 'amber' : b.functions ? (b.needs.length ? 'amber' : 'green') : 'grey';
  nodes.push({ id: `block:${b.symbol}`, label: `${b.symbol} · ${b.title}`, type: b.kind, rag,
    reason: esc(b.description) + (b.functions ? ` <span style="color:#9aa3b5">· ${b.functions} functions inside${b.needs.length ? ' · needs ' + b.needs.slice(0, 5).map(n => esc(n.meaning)).join(', ') : ''}</span>` : ''),
    gh: b.files[0] ? `https://github.com/${b.files[0].repo}/blob/${b.files[0].commit}/${b.files[0].path}` : null, ext: `${SITE}table.html?block=${b.symbol}` });
  edges.push({ from: `category:${b.category}`, to: `block:${b.symbol}`, type: 'contains' }); // edge types follow relationships/VOCABULARY.md
  for (const d of b.depends_on) edges.push({ from: `block:${b.symbol}`, to: `block:${d.symbol}`, type: 'depends-on' });
  for (const r of b.repos.slice(0, 6)) { if (!repoSeen.has(r)) { repoSeen.add(r); nodes.push({ id: `repo:${r}`, label: r.split('/')[1], type: 'repo', rag: 'green', reason: 'repository', gh: `https://github.com/${r}`, ext: null }); } edges.push({ from: `block:${b.symbol}`, to: `repo:${r}`, type: 'found-in' }); }
}
writeFileSync(path.join(OUT, 'blocks', 'graph.json'), JSON.stringify({ schema: 'periodic-table-graph.v1', label: 'The periodic table', generated_utc: now, nodes, edges }));
const autos = out.filter(b => b.kind === 'auto');
console.log(`Blocks: ${out.length} (${out.length - autos.length} named, ${autos.length} auto); families placed ${families.length}; graph ${nodes.length} nodes.`);

Build

A JavaScript module in the modular star folder of Stars that fetches live sites, engine graph, compounds and decays from the ventus-grid-engine repository.

renderstars / modular-star/build.mjs · lines 1–349 of 349 · Entry point · pattern lineageOf (shared by 2 files)

What it does
It fetches live sites, engine graph, compounds and decays. Defines 16 functions or classes, including arg, sh, listRepos, readBlobs, count. Uses libraries node:child_process, node:fs, node:zlib, node:path, acorn. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes.
Inputs & outputs
In: data source: ventus-grid-engine data; JSON file live-sites.json; JSON file engine-graph.json; JSON file compounds.json; JSON file graph.json; command-line arguments. Out: JSON file graph.json; JSON file decays.json; JSON file engine-join.json; JSON file dependencies.json; JSON file names.json; JSON file index.json; JSON file source.json.
Downstream impact
Used directly by 1 file: Modular Star Workflow (stars).
What it achieves
It lists repos (`listRepos`) and reads blobs (`readBlobs`). Modular star — scan the current code of every visible Ventusltd repository into the numbered database, then write the reports, the Spider graph, the prior-work catalogue and the compiled library. It reads `./live-sites.json`.
Why it matters
Run by Modular Star Workflow.
Application
stars · modular-star · JavaScript module
Uses
Stars — Modular Star (script call), Stars — Index Page (estate URL), node:child_process, node:fs, node:zlib, node:path, acorn
Used by
run by Modular Star Workflow (workflow run)
Produces
arg, sh, listRepos, readBlobs, count, enc, lineageOf, gh, esc, tabletOf, lineNumbers, inlineCode
Defines here
arg, sh, listRepos, readBlobs, count, enc, lineageOf, gh, esc, tabletOf, lineNumbers, inlineCode, codePage, link, usesOf, fileDeclares
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
stars@030ebc202d35959fecd162327892f671d1d9a0cc modular-star/build.mjs:1-349 · blob dced4f224fd622468ae8ef0cee2e1d2f9b982f19 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process · domain stage: unknown · users: none · canonical: unknown
// Modular star — scan the current code of every visible Ventusltd repository into the numbered database,
// then write the reports, the Spider graph, the prior-work catalogue and the compiled library.
// Usage: node modular-star/build.mjs --db modular.sqlite --work /tmp/repos --out .
import { execFileSync } from 'node:child_process';
import { mkdirSync, writeFileSync, readFileSync, rmSync } from 'node:fs';
import { gzipSync } from 'node:zlib';
import path from 'node:path';
import * as acorn from 'acorn';
import { openDb, ingestFile, langOf, rebuildTablet, gitBlobId, elementSource, unpack } from './lib.mjs';

const arg = (k, d) => { const i = process.argv.indexOf('--' + k); return i > 0 ? process.argv[i + 1] : d; };
const DB = arg('db', 'modular.sqlite'), WORK = arg('work', '/tmp/repos'), OUT = arg('out', '.');
const OWNER = 'Ventusltd', SKIP = /(^|\/)(node_modules|vendor|dist|build|\.git)\/|\.min\.(js|mjs)$/i;
const now = new Date().toISOString();
const sh = (cmd, args, opts = {}) => execFileSync(cmd, args, { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, ...opts });

function listRepos() {
  // Public repositories only: this repository is public, so nothing from a private repository may enter it.
  return sh('gh', ['api', '--paginate', `users/${OWNER}/repos?type=public&per_page=100`, '--jq', '.[] | {full_name, private, fork, archived, default_branch}'])
    .split('\n').filter(Boolean).map(l => JSON.parse(l))
    .filter(r => r.full_name.startsWith(OWNER + '/') && !r.private && !r.fork && r.full_name !== `${OWNER}/stars`);
}

// Read many blobs in one git process: "<oid> blob <size>\n<bytes>\n" per object.
function readBlobs(dir, oids) {
  const out = new Map();
  for (let i = 0; i < oids.length; i += 200) {
    const chunk = oids.slice(i, i + 200);
    const buf = execFileSync('git', ['-C', dir, 'cat-file', '--batch'], { input: chunk.join('\n') + '\n', maxBuffer: 512 * 1024 * 1024, env: { ...process.env, GIT_NO_LAZY_FETCH: '1' } });
    let pos = 0;
    for (const oid of chunk) {
      const nl = buf.indexOf(0x0a, pos);
      const [got, type, size] = buf.subarray(pos, nl).toString().split(' ');
      if (type === 'missing' || got !== oid) { pos = nl + 1; continue; }
      const len = Number(size);
      out.set(oid, buf.subarray(nl + 1, nl + 1 + len));
      pos = nl + 1 + len + 1;
    }
  }
  return out;
}

const ctx = openDb(DB);
const repos = listRepos();
const gaps = [];
console.log(`Repositories to scan: ${repos.length}`);
for (const r of repos) {
  const dir = path.join(WORK, r.full_name.replace('/', '__'));
  try {
    rmSync(dir, { recursive: true, force: true });
    const url = `https://github.com/${r.full_name}.git`;
    execFileSync('git', ['clone', '--quiet', '--depth', '1', '--filter=blob:limit=1m', '--no-checkout', url, dir], { stdio: 'pipe' });
    const commit = sh('git', ['-C', dir, 'rev-parse', 'HEAD']).trim();
    const entries = sh('git', ['-C', dir, 'ls-tree', '-r', '-z', 'HEAD']).split('\0').filter(Boolean).map(e => {
      const [meta, p] = e.split('\t'); const [, type, oid] = meta.split(/\s+/); return { type, oid, path: p };
    }).filter(e => e.type === 'blob' && langOf(e.path));
    // Blobs over 1 MiB were never downloaded (clone filter); with lazy fetching off they read as missing and are skipped.
    const wanted = entries.filter(e => !SKIP.test(e.path));
    const blobs = readBlobs(dir, [...new Set(wanted.map(e => e.oid))]);
    ctx.db.exec('BEGIN');
    let files = 0;
    for (const e of wanted) {
      const bytes = blobs.get(e.oid);
      if (!bytes || gitBlobId(bytes) !== e.oid) continue;
      ingestFile(ctx, { repo: r.full_name, commit, path: e.path, bytes, oid: e.oid, seen: now });
      files++;
    }
    ctx.db.prepare('INSERT OR REPLACE INTO scan(repo, commit_sha, branch, scanned_utc, files, skipped, issue) VALUES(?,?,?,?,?,?,NULL)')
      .run(r.full_name, commit, r.default_branch, now, files, entries.length - files);
    ctx.db.exec('COMMIT');
    console.log(`${r.full_name}: ${files} code files (${entries.length - files} skipped: vendored, minified or over 1 MiB)`);
  } catch (e) {
    try { ctx.db.exec('ROLLBACK'); } catch {}
    gaps.push({ repo: r.full_name, reason: String(e.message).split('\n')[0].slice(0, 200) });
    console.log(`${r.full_name}: not scanned — ${gaps.at(-1).reason}`);
  } finally {
    rmSync(dir, { recursive: true, force: true });
  }
}

// ---------- proof: files rebuild byte for byte from their numbered lines ----------
const sample = ctx.db.prepare('SELECT n, git_blob FROM tablet ORDER BY random() LIMIT 300').all();
const rebuiltOk = sample.filter(t => gitBlobId(rebuildTablet(ctx, t.n)) === t.git_blob).length;
if (rebuiltOk !== sample.length) { console.error(`Rebuild check failed: ${rebuiltOk}/${sample.length}`); process.exit(1); }

// ---------- reports ----------
const count = t => Number(ctx.db.prepare(`SELECT count(*) c FROM ${t}`).get().c);
const live = new Map(JSON.parse(readFileSync(new URL('./live-sites.json', import.meta.url), 'utf8').replace(/^\uFEFF/, '')).sites.map(s => [s.repo, s.site]));
const enc = p => p.split('/').map(encodeURIComponent).join('/');
// A file's lineage is its path with timestamp stamps (8 or 12 digits) folded, so 202609051152-x.js and 202609041945-x.js match.
const lineageOf = p => p.replace(/(^|[^0-9])\d{8}(\d{4})?(?=[^0-9]|$)/g, '$1{stamp}');
const gh = o => `https://github.com/${o.repo}/blob/${o.commit_sha}/${enc(o.path)}#L${o.first}-L${o.last}`;
const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
const tabletLines = new Map();
const tabletOf = t => { if (!tabletLines.has(t)) tabletLines.set(t, unpack(ctx.db.prepare('SELECT lines FROM tablet WHERE n = ?').get(t).lines)); return tabletLines.get(t); };
const lineNumbers = p => tabletOf(p.tablet).slice(p.first - 1, p.last);
// The code itself, on the focused card, in the dashboard's own monospace: numbered lines, capped so the graph stays light.
const CODE_LINES = 14;
function inlineCode(p) {
  const text = elementSource(ctx, p).split('\n'), nums = lineNumbers(p);
  const shown = text.slice(0, CODE_LINES).map((t, i) => `<span style="color:#4b5568">${String(nums[i] ?? '').padStart(6)}</span> ${esc(t)}`).join('\n');
  return `<pre style="margin:6px 0 0;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.62rem;line-height:1.35;color:var(--text);white-space:pre;overflow:auto;max-height:260px">${shown}${text.length > CODE_LINES ? `\n<span style="color:#4b5568">… ${text.length - CODE_LINES} more lines</span>` : ''}</pre>`;
}

const places = ctx.db.prepare(`
  SELECT e.family fam, te.element el, te.tablet, te.first, te.last, te.col0, te.col1, te.name, e.kind, e.needs, e.standalone,
         o.repo, o.commit_sha, o.path, o.seen_utc
  FROM tablet_element te JOIN element e ON e.n = te.element JOIN occurrence o ON o.tablet = te.tablet
  JOIN scan s ON s.repo = o.repo AND s.commit_sha = o.commit_sha
  ORDER BY e.family, o.seen_utc, te.element`).all();
const families = new Map();
for (const p of places) {
  let f = families.get(p.fam);
  if (!f) families.set(p.fam, f = { n: Number(p.fam), places: [], repos: new Set(), elements: new Set(), names: new Set(), lineages: new Set() });
  f.places.push(p); f.repos.add(p.repo); f.elements.add(Number(p.el)); f.names.add(p.name); f.lineages.add(p.repo + ':' + lineageOf(p.path));
}
const famList = [...families.values()];
// Copies of one file in timestamped release folders are versions, not duplicate work. Only logic that lives in two or
// more different files (lineages) counts as work done more than once.
const repeated = famList.filter(f => f.lineages.size >= 2).sort((a, b) => b.repos.size - a.repos.size || b.lineages.size - a.lineages.size || b.places.length - a.places.length || a.n - b.n);
const versionedOnly = famList.filter(f => f.places.length >= 2 && f.lineages.size === 1).length;
const firstWritten = new Map();
let history = null;
try {
  for (const r of ctx.db.prepare(`SELECT e.family fam, min(ci.date) d FROM tablet_element te JOIN element e ON e.n = te.element
      JOIN occurrence o ON o.tablet = te.tablet JOIN commit_info ci ON ci.repo = o.repo AND ci.sha = o.commit_sha GROUP BY e.family`).all()) firstWritten.set(Number(r.fam), r.d);
  history = ctx.db.prepare('SELECT count(*) repos, sum(commits_done) done, sum(commits_total) total, sum(commits_done >= commits_total) complete FROM wander').get();
} catch { /* history not walked yet */ }
const divergent = ctx.db.prepare(`
  SELECT te.name, count(DISTINCT e.family) fams, count(DISTINCT o.repo) repos
  FROM tablet_element te JOIN element e ON e.n = te.element JOIN occurrence o ON o.tablet = te.tablet
  JOIN scan s ON s.repo = o.repo AND s.commit_sha = o.commit_sha
  WHERE te.name NOT IN ('(anonymous)', 'default', 'constructor', 'init', 'main', 'render', 'update', 'run') AND length(te.name) > 3
  GROUP BY te.name HAVING fams >= 2 AND repos >= 2 ORDER BY repos DESC, fams DESC LIMIT 25`).all();

// Compiled library: one canonical copy of each repeated, self-contained JavaScript function.
const library = [];
for (const f of repeated) {
  const c = f.places.find(p => p.standalone && p.col0 !== null && p.kind !== 'class' && p.kind !== 'method');
  if (!c) continue;
  const src = elementSource(ctx, c);
  try { acorn.parse('(' + src + '\n)', { ecmaVersion: 'latest', sourceType: 'module' }); } catch { continue; }
  library.push({ f, c, src });
}
mkdirSync(path.join(OUT, 'library'), { recursive: true });
writeFileSync(path.join(OUT, 'library', 'standalone.mjs'),
  `// Compiled library of self-contained JavaScript functions that appear in two or more places across Ventusltd code.\n` +
  `// Generated by the modular star ${now}. Each export is one family's earliest-seen copy, unchanged; the comment links its source.\n` +
  `// Candidates for reuse, not reviewed or tested: check the source before depending on one.\n\n` +
  library.map(({ f, c, src }) => `// Family #${f.n} · element #${c.el} · ${f.places.length} places in ${f.repos.size} repositories · ${gh(c)}\n` +
    `export const f${f.n}_${String(c.name).replace(/[^A-Za-z0-9_$]/g, '_').slice(0, 40)} = ${src};\n`).join('\n'));

// Spider graph, in the ventus-grid-engine receiver's generic shape (index.html normaliseGenericGraph):
// nodes {id, label, type, rag, reason, gh, ext}, edges {from, to, type} by id. Ids are the permanent keys, so any
// other graph that uses the same key (family:N, repo:owner/name) joins this one.
const SITE = 'https://ventusltd.github.io/stars/';
const codePage = n => `${SITE}code.html?family=${n}`;
const ENGINE_GRAPH = 'https://ventusltd.github.io/ventus-grid-engine/genome/engine-graph.json';
const familyOf = new Map(famList.map(f => [f.n, f]));

// ---- Join to the engine-graph: the hand-made duplication map the Spider already shows at ?graph=engine-graph.
// Its canonical nodes are files in ventus-grid-engine; its edges carry file+lines evidence. A family whose copy
// sits in one of those files, at those lines, is wired to that node; the node deep-links into the engine graph.
const engineJoin = new Map(); // family n -> [{label, type, gh, relation}]
let engineGraph = null;
try { engineGraph = await (await fetch(ENGINE_GRAPH)).json(); } catch { /* offline: no join this run */ }
if (engineGraph?.nodes) {
  const placeIndex = new Map(); // "repo-name/path" -> places
  for (const f of famList) for (const p of f.places) { const k = p.repo.split('/')[1] + '/' + p.path; if (!placeIndex.has(k)) placeIndex.set(k, []); placeIndex.get(k).push({ ...p, family: f.n }); }
  const link = (n, node, relation) => { if (!engineJoin.has(n)) engineJoin.set(n, []); if (!engineJoin.get(n).some(x => x.label === node.label)) engineJoin.get(n).push({ label: node.label, type: node.type, gh: node.gh, relation }); };
  engineGraph.nodes.forEach(node => { for (const p of placeIndex.get('ventus-grid-engine/' + node.label) || []) link(p.family, node, node.type === 'canonical' ? 'canonical home' : 'engine file'); });
  for (const e of engineGraph.edges || []) {
    const ev = e.evidence; if (!ev?.file) continue;
    const m = String(ev.lines || '').match(/(\d+)\s*-\s*(\d+)/); if (!m) continue; // evidence without a line range cites a whole file: too loose to wire
    const [a, b] = [Number(m[1]), Number(m[2])];
    for (const p of placeIndex.get(ev.file) || []) if (p.first <= b && p.last >= a) {
      const fromNode = engineGraph.nodes[e.from], toNode = engineGraph.nodes[e.to];
      if (toNode) link(p.family, toNode, e.type === 'supersedes' ? 'fragment cited as superseded' : `cited: ${e.type}`);
      if (fromNode && e.type === 'supersedes') link(p.family, fromNode, 'superseded by');
    }
  }
}

// ---- Join to the chemistry stars: each decay message (the error a red composition produces) resolved to the
// numbered lines that contain it, and so to the functions that throw it.
const decays = [];
try {
  const compounds = JSON.parse(readFileSync(path.join(OUT, 'reports', 'chemistry', 'compounds.json'), 'utf8')).compounds || [];
  const counts = new Map();
  for (const c of compounds) for (const d of c.decays || []) counts.set(d.text, (counts.get(d.text) || 0) + (d.n || 1));
  const tabletsByLine = new Map();
  for (const t of ctx.db.prepare('SELECT n, lines FROM tablet').all()) unpack(t.lines).forEach((ln, i) => { if (!tabletsByLine.has(ln)) tabletsByLine.set(ln, []); tabletsByLine.get(ln).push([Number(t.n), i + 1]); });
  const teByTablet = new Map();
  for (const te of ctx.db.prepare('SELECT te.tablet, te.first, te.last, te.name, e.family FROM tablet_element te JOIN element e ON e.n = te.element').all()) { if (!teByTablet.has(te.tablet)) teByTablet.set(te.tablet, []); teByTablet.get(te.tablet).push(te); }
  for (const [text, n] of [...counts].sort((a, b) => b[1] - a[1]).slice(0, 12)) {
    const msg = text.split(': ').slice(-1)[0].trim(); if (msg.length < 12) continue;
    const lines = ctx.db.prepare("SELECT n FROM line WHERE instr(CAST(text AS TEXT), ?) > 0 LIMIT 200").all(msg).map(r => Number(r.n));
    const fams = new Map();
    for (const ln of lines) for (const [t, pos] of tabletsByLine.get(ln) || []) for (const te of teByTablet.get(t) || []) if (te.first <= pos && pos <= te.last) fams.set(Number(te.family), te.name);
    // Named functions first; anonymous wrappers (cartridge IIFEs) are shown with their file so the card still says where.
    const list = [...fams].map(([f, name]) => ({ family: f, name: name === '(anonymous)' ? '(anonymous) in ' + (familyOf.get(f)?.places[0]?.path.split('/').pop() || '?') : name })).filter(x => familyOf.has(x.family)).sort((a, b) => (a.name.startsWith('(anonymous)') ? 1 : 0) - (b.name.startsWith('(anonymous)') ? 1 : 0));
    decays.push({ message: text, red_stars: n, needle: msg, lines, families: list });
  }
} catch { /* no chemistry report in this checkout */ }

const chosen = new Map(repeated.slice(0, 150).map(f => [f.n, f]));
// Only the strong relations join the front-door graph; every relation is kept in engine-join.json.
for (const [n, joins] of engineJoin) if (familyOf.has(n) && joins.some(j => /canonical home|superseded by/.test(j.relation))) chosen.set(n, familyOf.get(n));
for (const d of decays) for (const x of d.families.slice(0, 6)) chosen.set(x.family, familyOf.get(x.family));
// Enumeration order for the FOCUS list: by source file (repository, then path), then by family number, so the list reads like a table of contents.
const top = [...chosen.values()].sort((x, y) => x.places[0].repo.localeCompare(y.places[0].repo) || x.places[0].path.localeCompare(y.places[0].path) || x.n - y.n);
const nodes = [], edges = [], repoNodes = new Set(), engineNodes = new Map();
for (const f of top) {
  const c = f.places[0], id = `family:${f.n}`;
  const needs = c.needs ? JSON.parse(c.needs) : null;
  const joins = (engineJoin.get(f.n) || []).filter(j => /canonical home|superseded by|superseded$/.test(j.relation));
  nodes.push({ id, key: id, label: `#${f.n} ${[...f.names][0]}`, type: c.standalone ? 'library element' : 'element', rag: c.standalone ? 'green' : 'amber',
    reason: `${f.lineages.size} different files · ${f.places.length} places in ${f.repos.size} repositories · ${f.elements.size} version(s)` + (firstWritten.has(f.n) ? ` · first written ${firstWritten.get(f.n).slice(0, 10)}` : '') + (needs?.length ? ` · needs ${needs.slice(0, 6).join(', ')}` : c.standalone ? ' · self-contained' : '')
      + (joins.length ? ` · engine: ${joins.map(j => j.relation + ' ' + j.label).join('; ')}` : '') + inlineCode(c),
    gh: gh(c), ext: codePage(f.n) });
  for (const r of f.repos) { repoNodes.add(r); edges.push({ from: id, to: `repo:${r}`, type: 'found-in' }); }
  for (const j of joins) { const eid = `engine:${j.label}`; if (!engineNodes.has(eid)) engineNodes.set(eid, j); edges.push({ from: id, to: eid, type: j.type === 'canonical' ? 'canonical' : 'should-import' }); } // vocabulary: relationships/VOCABULARY.md
}
// Same name, different code: wire the families that share a name, so the Spider shows where a name means two things.
const byName = new Map();
for (const f of top) for (const name of f.names) if (name.length > 3 && !['(anonymous)', 'default', 'constructor'].includes(name)) byName.set(name, [...(byName.get(name) || []), f.n]);
for (const ns of byName.values()) for (let i = 1; i < ns.length; i++) edges.push({ from: `family:${ns[0]}`, to: `family:${ns[i]}`, type: 'same-name' });
for (const r of repoNodes) nodes.push({ id: `repo:${r}`, key: `repo:${r}`, label: r.split('/')[1], type: 'repo', rag: 'green',
  reason: live.has(r) ? `published at ${live.get(r)}` : 'repository', gh: `https://github.com/${r}`, ext: live.get(r) || null });
for (const [eid, j] of engineNodes) nodes.push({ id: eid, key: eid, label: j.label, type: j.type === 'canonical' ? 'engine canonical' : 'engine ' + j.type, rag: j.type === 'canonical' ? 'green' : 'amber',
  reason: j.type === 'canonical' ? 'the engine\'s canonical module: the copy that should be imported' : `${j.type} in the engine-graph`, gh: j.gh || null,
  ext: `https://ventusltd.github.io/ventus-grid-engine/?graph=engine-graph&focus=${encodeURIComponent(j.label)}` });
for (const d of decays) {
  if (!d.families.length) continue;
  const id = `decay:${d.needle}`;
  nodes.push({ id, key: id, label: d.message.slice(0, 90), type: 'decay', rag: 'red', reason: `${d.red_stars} red composition tests produce this error · found in ${d.lines.length} numbered line(s) · the functions that carry it are wired below`, gh: null, ext: `${SITE}reports/CHEMISTRY.md` });
  for (const x of d.families.slice(0, 6)) if (chosen.has(x.family)) edges.push({ from: id, to: `family:${x.family}`, type: 'thrown-by' });
}
mkdirSync(path.join(OUT, 'modular'), { recursive: true });
writeFileSync(path.join(OUT, 'modular', 'graph.json'), JSON.stringify({ schema: 'modular-star-graph.v1', label: 'The Modular star', generated_utc: now, nodes: nodes.map(({ key, ...n }) => n), edges })); // compact, no redundant key: stays under the registry limit
writeFileSync(path.join(OUT, 'modular', 'decays.json'), JSON.stringify({ generated_utc: now, note: 'Chemistry decay messages resolved to the numbered lines that contain them and the families that throw them.', decays }, null, 1));
writeFileSync(path.join(OUT, 'modular', 'engine-join.json'), JSON.stringify({ generated_utc: now, source: ENGINE_GRAPH, families: Object.fromEntries([...engineJoin].map(([n, j]) => [n, { name: [...familyOf.get(n).names][0], joins: j }])) }, null, 1));
console.log(`Spider graph: ${nodes.length} nodes, ${edges.length} edges; engine join ${engineJoin.size} families; ${decays.length} decay messages resolved.`);

// Code records for the report page (code.html): every family, in buckets of 500 by number, so a page loads one
// small file. Each record carries every place the logic lives, the live page that serves it, and the permanent
// line numbers of its first copy. Plus a name index for search.
const libraryExport = new Map(library.map(({ f, c }) => [f.n, `f${f.n}_${String(c.name).replace(/[^A-Za-z0-9_$]/g, '_').slice(0, 40)}`]));
const buckets = new Map(), names = Object.create(null); // null prototype: a function named constructor or toString must not collide
// Interdependencies: a family "uses" the families that define a name it needs, preferring ones in the same repository.
const definers = new Map();
for (const f of famList) for (const name of f.names) if (name !== '(anonymous)' && name.length > 1) { if (!definers.has(name)) definers.set(name, []); definers.get(name).push(f); }
const usesOf = f => {
  const needs = f.places[0].needs ? JSON.parse(f.places[0].needs) : [];
  const out = [];
  for (const name of needs) {
    const cands = definers.get(name); if (!cands) continue;
    const same = cands.filter(g => [...g.repos].some(r => f.repos.has(r)));
    for (const g of (same.length ? same : cands).slice(0, 3)) if (g.n !== f.n) out.push({ family: g.n, name, via: same.length ? 'same repository' : 'by name only' });
  }
  return out;
};
const usedBy = new Map();
const recs = new Map();
// What a function still needs from OUTSIDE ITS FILE: its needs minus every name its own file declares
// (constants, variables, functions, classes, window.x assignments). This is what a copied file still lacks.
const declaredCache = new Map();
const fileDeclares = tablet => {
  if (!declaredCache.has(tablet)) {
    const src = rebuildTablet(ctx, tablet).toString('utf8');
    const s = new Set();
    for (const m of src.matchAll(/\b(?:const|let|var|function|class)\s+([A-Za-z_$][\w$]*)/g)) s.add(m[1]);
    for (const m of src.matchAll(/\b(?:const|let|var)\s*\{([^}]*)\}/g)) for (const part of m[1].split(',')) { const nm = part.split(':').pop().trim().split('=')[0].trim(); if (/^[A-Za-z_$][\w$]*$/.test(nm)) s.add(nm); }
    for (const m of src.matchAll(/\bwindow\.([A-Za-z_$][\w$]*)\s*=/g)) s.add(m[1]);
    for (const m of src.matchAll(/\bimport\s+(?:\*\s+as\s+)?([A-Za-z_$][\w$]*)|\bimport\s*\{([^}]*)\}/g)) { if (m[1]) s.add(m[1]); if (m[2]) for (const part of m[2].split(',')) { const nm = part.split(' as ').pop().trim(); if (nm) s.add(nm); } }
    declaredCache.set(tablet, s);
  }
  return declaredCache.get(tablet);
};
for (const f of famList) {
  const c = f.places[0];
  const uses = usesOf(f);
  const declared = fileDeclares(c.tablet);
  const needsOutside = (c.needs ? JSON.parse(c.needs) : []).filter(n => !declared.has(n));
  for (const u of uses) { if (!usedBy.has(u.family)) usedBy.set(u.family, []); usedBy.get(u.family).push({ family: f.n, name: u.name }); }
  recs.set(f.n, {
    n: f.n, names: [...f.names].slice(0, 6), kind: c.kind, standalone: !!c.standalone, needs: needsOutside, needs_in_function: c.needs ? JSON.parse(c.needs) : null,
    first_written: firstWritten.get(f.n) || null, library: libraryExport.get(f.n) || null,
    files: f.lineages.size, versions: f.elements.size, repos: [...f.repos],
    lines: lineNumbers(c), uses,
    places: f.places.slice(0, 40).map(p => ({ repo: p.repo, commit: p.commit_sha, path: p.path, first: p.first, last: p.last, name: p.name,
      live: live.has(p.repo) ? live.get(p.repo) + p.path : null })),
  });
}
const hubs = [...usedBy].map(([n, by]) => ({ family: n, name: [...familyOf.get(n).names][0], used_by: by.length })).sort((a, b) => b.used_by - a.used_by).slice(0, 60);
writeFileSync(path.join(OUT, 'modular', 'dependencies.json'), JSON.stringify({ generated_utc: now, note: 'A family uses the families that define a name it needs; hubs are the most used.', families_with_uses: [...recs.values()].filter(r => r.uses.length).length, hubs }, null, 1));
for (const f of famList) {
  const rec = recs.get(f.n);
  rec.used_by = (usedBy.get(f.n) || []).slice(0, 40);
  const b = Math.floor(f.n / 500);
  if (!buckets.has(b)) buckets.set(b, {});
  buckets.get(b)[f.n] = rec;
  for (const name of f.names) if (name !== '(anonymous)') (names[name] ||= []).push(f.n);
}
mkdirSync(path.join(OUT, 'code', 'f'), { recursive: true });
for (const [b, recs] of buckets) writeFileSync(path.join(OUT, 'code', 'f', `${b}.json`), JSON.stringify(recs));
writeFileSync(path.join(OUT, 'code', 'names.json'), JSON.stringify(names));
writeFileSync(path.join(OUT, 'code', 'index.json'), JSON.stringify({ generated_utc: now, families: famList.length, bucket_size: 500, buckets: [...buckets.keys()].sort((a, b) => a - b), lines: count('line'), elements: count('element') }));

// Prior-work catalogue (release asset): exact element hashes and family hashes → where they already live.
const elementRows = ctx.db.prepare('SELECT e.n, e.sha, e.family, f.sha fsha FROM element e JOIN family f ON f.n = e.family').all();
const catalog = { generated_utc: now, elements: {}, families: {} };
for (const e of elementRows) catalog.elements[Buffer.from(e.sha).toString('hex')] = [Number(e.n), Number(e.family)];
for (const f of famList) catalog.families[f.n] = {
  names: [...f.names].slice(0, 5), repos: f.repos.size,
  places: f.places.slice(0, 10).map(p => ({ link: gh(p), live: live.has(p.repo) ? live.get(p.repo) + p.path : null })) };
catalog.family_by_hash = Object.fromEntries(ctx.db.prepare('SELECT n, sha FROM family').all().map(f => [Buffer.from(f.sha).toString('hex'), Number(f.n)]));
writeFileSync(path.join(OUT, 'catalog.json.gz'), gzipSync(JSON.stringify(catalog)));

const scans = ctx.db.prepare('SELECT * FROM scan ORDER BY repo').all();
writeFileSync(path.join(OUT, 'modular', 'source.json'), JSON.stringify({ generated_utc: now, repositories: scans.map(s => ({ repo: s.repo, commit: s.commit_sha, code_files: Number(s.files) })), not_scanned: gaps }, null, 2));

const md = [];
md.push('# The Modular star', '');
md.push(`Updated ${now.slice(0, 16).replace('T', ' ')} UTC by GitHub Actions. It reads the current code of ${scans.length} Ventusltd repositories.`, '');
md.push('Every unique line of code has a permanent number. Each file version is stored as its list of line numbers. Functions and classes are numbered as **elements**, and elements with the same logic, ignoring layout and comments, share a numbered **family**. Numbers never change, so a link to line, element or family #N stays valid.', '');
md.push('## Totals', '', '| | count |', '|---|---|');
md.push(`| Unique lines | ${count('line').toLocaleString('en-GB')} |`, `| File versions | ${count('tablet').toLocaleString('en-GB')} |`, `| Elements (functions and classes) | ${count('element').toLocaleString('en-GB')} |`, `| Families (same logic) | ${count('family').toLocaleString('en-GB')} |`);
md.push(`| Families written in two or more different files (duplicate work) | ${repeated.length.toLocaleString('en-GB')} |`, `| Families only copied between versions of one file | ${versionedOnly.toLocaleString('en-GB')} |`, `| Self-contained functions compiled into the library | ${library.length.toLocaleString('en-GB')} |`, '');
md.push(`Check: ${rebuiltOk} randomly chosen files were rebuilt from their numbered lines, and all matched GitHub byte for byte.`, '');
if (history) md.push(`History walked: ${Number(history.done).toLocaleString('en-GB')} of ${Number(history.total).toLocaleString('en-GB')} commits across ${history.repos} repositories (${history.complete} complete). Each run continues where the last one stopped.`, '');
md.push('## Work already done more than once', '', 'The same logic written in two or more different files. Copies of one file in timestamped release folders are counted as versions, not here. Before writing something similar, reuse one of these.', '');
md.push('| Family | Name | Different files | Places | Repositories | Self-contained | First written | A copy |', '|---|---|---|---|---|---|---|---|');
for (const f of repeated.slice(0, 30)) { const c = f.places[0]; md.push(`| #${f.n} | \`${[...f.names].slice(0, 2).join('`, `')}\` | ${f.lineages.size} | ${f.places.length} | ${f.repos.size} | ${c.standalone ? 'yes' : 'no'} | ${(firstWritten.get(f.n) || '').slice(0, 10) || '–'} | [${c.repo.split('/')[1]}/${c.path}](${gh(c)}) |`); }
md.push('', '## Same name, different code', '', 'These names mean different things in different repositories, so check which version is meant before relying on one.', '');
md.push('| Name | Different versions | Repositories |', '|---|---|---|');
for (const d of divergent) md.push(`| \`${d.name}\` | ${d.fams} | ${d.repos} |`);
md.push('', '## How to check for earlier work before writing code', '');
md.push('```', 'npm install', 'node modular-star/find-prior.mjs path/to/your-file.js', '```');
md.push('This lists every function in the file that already exists, either word for word or with the same logic in a different layout, with links to where it lives.', '');
md.push('## Use in the Spider', '', '`modular/graph.json` is a Spider graph: the most repeated families wired to the repositories they appear in. Green means self-contained; amber means the function needs something from outside itself, which the node lists.', '');
md.push('## Coverage', '');
md.push(`- Current default branch of each repository scanned; earlier history is not yet included. Numbers from earlier runs are kept, so history builds up with every run.`);
md.push('- JavaScript, HTML inline scripts and Python only. Files over 1 MiB, minified files and vendored folders are skipped.');
md.push('- Public repositories only, by design: this repository is public, so private code is never read into it.');
if (gaps.length) md.push(`- Not scanned this run: ${gaps.map(g => g.repo).join(', ')} (see \`modular/source.json\`).`);
writeFileSync(path.join(OUT, 'modular', 'SUMMARY.md'), md.join('\n') + '\n');
ctx.db.close();
console.log(`Done: ${count.length ? '' : ''}${repeated.length} repeated families, ${library.length} library functions, ${gaps.length} repositories not scanned.`);

Check Permanent

A JavaScript module in the modular star folder of Stars.

otherstars / modular-star/check-permanent.mjs · lines 1–13 of 13 · Entry point

What it does
Uses libraries node:sqlite. Side effects: starts processes.
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 1 file: Modular Star Workflow (stars).
What it achieves
Fails if any number from the previous database changed meaning or disappeared.
Why it matters
Run by Modular Star Workflow.
Application
stars · modular-star · JavaScript module
Uses
node:sqlite
Used by
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 modular-star/check-permanent.mjs:1-13 · blob 9e2be018bb8d57cc3140ad80e448a31cea193e83 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unknown
// Fails if any number from the previous database changed meaning or disappeared.
// Usage: node modular-star/check-permanent.mjs before.sqlite after.sqlite
import { DatabaseSync } from 'node:sqlite';
const [before, after] = process.argv.slice(2);
const db = new DatabaseSync(after);
db.prepare('ATTACH DATABASE ? AS old').run(before);
let bad = 0;
for (const [table, key] of [['line', 'sha'], ['tablet', 'git_blob'], ['family', 'sha'], ['element', 'sha']]) {
  const r = db.prepare(`SELECT count(*) c, (SELECT count(*) FROM old.${table}) total FROM old.${table} o LEFT JOIN main.${table} m ON m.n = o.n AND m.${key} = o.${key} WHERE m.n IS NULL`).get();
  console.log(`${table}: ${r.total} earlier numbers, ${r.c} changed or missing`);
  bad += Number(r.c);
}
if (bad) { console.error('Permanent numbers were broken; refusing to save this database.'); process.exit(1); }

Coherence

A JavaScript module in the modular star folder of Stars that reads blocks and reactions.

storagestars / modular-star/coherence.mjs · lines 1–43 of 43 · Entry point

What it does
It loads blocks and reactions. Defines read, gh, runs, size. Uses libraries node:fs, node:child_process. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: JSON file index.json; JSON file blocks.json; JSON file graph.json; JSON file reactions.json. Out: JSON file status.json.
Downstream impact
Used directly by 1 file: Coherence Workflow (stars).
What it achieves
It is built from the read step (`read`), the runs step (`runs`) and the size step (`size`). Coherence intelligent resume — the lab's own memory. It reads `code/index.json` and writes `resume/status.json`.
Why it matters
Run by Coherence Workflow.
Application
stars · modular-star · JavaScript module
Uses
node:fs, node:child_process
Used by
run by Coherence Workflow (workflow run)
Produces
read, gh, runs, size
Defines here
read, gh, runs, size
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
stars@030ebc202d35959fecd162327892f671d1d9a0cc modular-star/coherence.mjs:1-43 · blob 5e3bd91fcb3f4a6a12b8742011c360b49650eb0d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: supporting_data
// Coherence intelligent resume — the lab's own memory. Gathers, in one place, what ran, what exists, what is
// registered, what the graphs say, and what is waiting, so any agent or person resumes from the same page.
// Writes resume/RESUME.md and resume/status.json. Runs on GitHub Actions (coherence.yml), at most 20 minutes.
import { readFileSync, writeFileSync, existsSync, mkdirSync, statSync } from 'node:fs';
import { execFileSync } from 'node:child_process';

const now = new Date().toISOString();
const read = p => existsSync(p) ? readFileSync(p, 'utf8') : '';
const gh = args => { try { return JSON.parse(execFileSync('gh', args, { encoding: 'utf8', timeout: 60000 })); } catch { return []; } };
const runs = (repo, n) => gh(['run', 'list', '-R', repo, '-L', String(n), '--json', 'workflowName,status,conclusion,createdAt,event,databaseId,updatedAt'])
  .map(r => ({ workflow: r.workflowName, status: r.conclusion || r.status, event: r.event, started: r.createdAt, minutes: Math.round((Date.parse(r.updatedAt) - Date.parse(r.createdAt)) / 60000), id: r.databaseId }));
const size = p => existsSync(p) ? Math.round(statSync(p).size / 1024) : null;

const stars = runs('Ventusltd/stars', 8), gen = runs('Ventusltd/code-generator', 4);
const cronFired = stars.some(r => r.event === 'schedule');
const index = existsSync('code/index.json') ? JSON.parse(read('code/index.json')) : null;
const table = existsSync('blocks/blocks.json') ? JSON.parse(read('blocks/blocks.json')) : null;
const registry = [...read('spider/features.yml').matchAll(/- id: "([^"]+)"/g)].map(m => m[1]);
const artefacts = ['LINES.md', 'modular/SUMMARY.md', 'modular/graph.json', 'blocks/blocks.json', 'blocks/reactions.json', 'sense/graph.json', 'proof/graph.json', 'structure/graph.json', 'code/index.json', 'spider/features.yml']
  .map(p => ({ path: p, kb: size(p) }));
const worklog = read('WORKLOG.md').split('\n').filter(l => l.startsWith('- 20')).slice(-6);
const decisions = (read('CODE-UNIVERSE.md').match(/\*\*DECIDE \d\.[^\n]*/g) || []).map(s => s.replace(/\*\*/g, '').slice(0, 160));
const senseHead = read('sense/SENSE.md').split('\n').slice(0, 12).join('\n');
const failures = [...stars, ...gen].filter(r => r.status === 'failure');

const status = { generated_utc: now, runs: { stars, code_generator: gen }, cron_has_fired: cronFired, index: index && { families: index.families, elements: index.elements, lines: index.lines, updated: index.generated_utc },
  blocks: table && { named: table.blocks.filter(b => b.kind !== 'auto').length, auto: table.blocks.filter(b => b.kind === 'auto').length, updated: table.generated_utc }, registry, artefacts, failures, decisions, latest_log: worklog };
mkdirSync('resume', { recursive: true });
writeFileSync('resume/status.json', JSON.stringify(status, null, 1));

const md = [`# Coherence: intelligent resume`, '', `Generated ${now.slice(0, 16).replace('T', ' ')} UTC by the coherence workflow. This is the single page to resume from. It is rebuilt after every Modular star run and on demand; a copy is synchronised to Dropbox \`coherence\\\` while the Ventus workstation is on.`, '',
  '## Health', '', `- Failed runs in the last window: **${failures.length}**${failures.length ? ' — ' + failures.map(f => `${f.workflow} #${f.id}`).join(', ') : ''}.`, `- GitHub schedule has ${cronFired ? '' : 'never '}fired in this repository${cronFired ? '' : ' (runs come from pushes, the chain, the workstation fallback, or by hand)'}.`,
  index ? `- Index: ${index.families.toLocaleString('en-GB')} families, ${index.elements.toLocaleString('en-GB')} functions and classes, ${index.lines.toLocaleString('en-GB')} unique lines (updated ${index.generated_utc.slice(0, 16).replace('T', ' ')} UTC).` : '- Index: not built yet.',
  table ? `- Periodic table: ${status.blocks.named} named blocks, ${status.blocks.auto} auto-blocks.` : '- Periodic table: not built yet.', `- Registered for the dashboard: ${registry.join(', ') || 'nothing yet'}.`, '',
  '## Last runs', '', '| Repository | Workflow | Result | Trigger | Started (UTC) | Minutes |', '|---|---|---|---|---|---|',
  ...stars.map(r => `| stars | ${r.workflow} | ${r.status} | ${r.event} | ${r.started.slice(0, 16).replace('T', ' ')} | ${r.minutes} |`), ...gen.map(r => `| code-generator | ${r.workflow} | ${r.status} | ${r.event} | ${r.started.slice(0, 16).replace('T', ' ')} | ${r.minutes} |`), '',
  '## Artefacts', '', '| File | Size |', '|---|---|', ...artefacts.map(a => `| ${a.path} | ${a.kb === null ? 'missing' : a.kb + ' KB'} |`), '',
  '## What the sense graph says', '', senseHead || '_sense/SENSE.md not built yet._', '',
  '## Decisions waiting', '', ...(decisions.length ? decisions.map(d => `- ${d}`) : ['- See CODE-UNIVERSE.md.']), '',
  '## Latest work log', '', ...worklog, '',
  '## How to resume', '', '1. Read this page, then `WORKLOG.md`.', '2. If a run failed: `gh run view <id> --log-failed` (or `node tools/run-log.mjs <id>`), fix the script, never the generated outputs.', '3. If no Modular star run began in the last 70 minutes: `gh workflow run modular-star.yml -R Ventusltd/stars`.', '4. Continue from the newest work log entry.'];
writeFileSync('resume/RESUME.md', md.join('\n') + '\n');
console.log(`Coherence: ${failures.length} failed run(s); registry ${registry.length}; artefacts ${artefacts.filter(a => a.kb !== null).length}/${artefacts.length}.`);