GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / stars / modular-star

Sense and 6 more files

A JavaScript module in the modular star folder of Stars that reads blocks, reactions, families and dependencies. It reads JSON (`readJson`) and finds block (`findBlock`).

663 lines of JavaScript from stars, in 7 files. Topic: Kuiper, cosmos and drawing engines. Section 1583 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. Sense storage · stars / modular-star/sense.mjs lines 1–315
  2. Structure storage · stars / modular-star/structure.mjs lines 1–139
  3. Test test · stars / modular-star/test.mjs lines 1–84
  4. Universe Compact Proof ingest · stars / modular-star/universe-compact-proof.mjs lines 1–18
  5. Universe Compact storage · stars / modular-star/universe-compact.mjs lines 1–27
  6. Universe Model ingest · stars / modular-star/universe-model.mjs lines 1–54
  7. View interaction · stars / modular-star/universe-viewer/view.js lines 1–26

Sense

A JavaScript module in the modular star folder of Stars that reads blocks, reactions, families and dependencies. It reads JSON (`readJson`) and finds block (`findBlock`).

storagestars / modular-star/sense.mjs · lines 1–315 of 315 · Entry point · pattern plural (shared by 9 files)

What it does
It loads blocks, reactions, families and dependencies. Defines 10 functions or classes, including readJson, esc, plural, findBlock, family. Uses libraries node:fs, node:path. Side effects: reads or writes files.
Inputs & outputs
In: JSON file blocks.json; JSON file reactions.json; JSON file families.json; JSON file dependencies.json; JSON file decays.json; JSON file engine-join.json; JSON file index.json; JSON file engine-graph.json. Out: JSON file graph.json.
Downstream impact
It is itself an entry point (JavaScript module); no other file was found loading it.
What it achieves
Defines `readJson`, `esc`, `plural` and 7 more. It reads `blocks/blocks.json`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
stars · modular-star · JavaScript module
Uses
Stars — Index Page (estate URL), node:fs, node:path
Used by
none found
Produces
readJson, esc, plural, findBlock, family, familyGh, add, wire, blockId, blockGh
Defines here
readJson, esc, plural, findBlock, family, familyGh, add, wire, blockId, blockGh
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/sense.mjs:1-315 · blob f864f5dc1b47270972c34144524e104d14f22ebd · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env node
// sense.mjs — makes sense of the code universe for the Spider dashboard.
//
// Reads the published star data (blocks/, code/, modular/) and writes one small graph,
// sense/graph.json, whose ORDER and WIRING tell a story instead of listing files:
//   the whole → its purposes → the blocks that serve each purpose → the canonical homes
//   → the copies that should import them (illusion) → the decisions still open
//   → what is proven together → what breaks → what everything leans on.
// Also writes sense/SENSE.md explaining the graph in plain language.
//
// Usage: node modular-star/sense.mjs --out .      (node 24, no dependencies)
import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync } from 'node:fs';
import { join } from 'node:path';

const args = process.argv.slice(2);
const outIdx = args.indexOf('--out');
const ROOT = outIdx >= 0 && args[outIdx + 1] ? args[outIdx + 1] : '.';
const STARS = 'https://ventusltd.github.io/stars/';
const MAX_NODES = 300;

const readJson = (p) => JSON.parse(readFileSync(join(ROOT, p), 'utf8'));
const esc = (s) => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`;

// ---------- load ----------
const blocksFile = readJson('blocks/blocks.json');
const reactions = readJson('blocks/reactions.json');
const families = existsSync(join(ROOT, 'blocks/families.json')) ? readJson('blocks/families.json') : {};
const deps = readJson('modular/dependencies.json');
const decays = readJson('modular/decays.json');
const engineJoin = readJson('modular/engine-join.json');
const codeIndex = existsSync(join(ROOT, 'code/index.json')) ? readJson('code/index.json') : null;

const blocks = blocksFile.blocks || [];
const categories = blocksFile.categories || [];
const bySymbol = new Map(blocks.map((b) => [b.symbol, b]));
const byNumber = new Map(blocks.map((b) => [String(b.number), b]));
const findBlock = (ref) => {
  if (ref == null) return null;
  if (typeof ref === 'object') return findBlock(ref.symbol ?? ref.number ?? ref.block ?? ref.id);
  return bySymbol.get(String(ref)) || byNumber.get(String(ref)) || null;
};

// Function families: read only the buckets we need (families named by decays, hubs, engine-join).
const familyCache = new Map();
const bucketSize = codeIndex?.bucket_size || 500;
function family(n) {
  const key = String(n);
  if (familyCache.has(key)) return familyCache.get(key);
  const bucket = Math.floor(Number(n) / bucketSize);
  const p = join(ROOT, 'code/f', `${bucket}.json`);
  let rec = null;
  if (existsSync(p)) {
    try { rec = JSON.parse(readFileSync(p, 'utf8'))[key] || null; } catch { rec = null; }
  }
  familyCache.set(key, rec);
  return rec;
}
const familyGh = (rec) => {
  const pl = rec?.places?.[0];
  if (!pl) return null;
  return `https://github.com/${pl.repo}/blob/${pl.commit || 'main'}/${pl.path}#L${pl.first}-L${pl.last}`;
};

// ---------- graph builder ----------
const nodes = [];
const edges = [];
const ids = new Set();
function add(node) {
  if (ids.has(node.id)) return node.id;
  ids.add(node.id);
  nodes.push(node);
  return node.id;
}
function wire(from, to, type) {
  if (!ids.has(from) || !ids.has(to) || from === to) return;
  edges.push({ from, to, type });
}

// ---------- 1. the whole ----------
const familyCount = codeIndex?.families ?? deps.families_with_uses ?? 0;
const canonicalCount = Object.values(engineJoin.families || {}).filter((f) => f.joins?.some((j) => j.type === 'canonical')).length;
const fragmentCount = Object.values(engineJoin.families || {}).reduce((n, f) => n + (f.joins || []).filter((j) => j.type === 'fragment').length, 0);
const unsettled = blocks.filter((b) => b.state === 'UNSETTLED');
const settled = blocks.filter((b) => b.state === 'SETTLED');

add({
  id: 'universe', label: 'The code universe', type: 'whole', rag: 'amber',
  reason: `${familyCount.toLocaleString()} distinct functions across globalgrid2050 architecture development, organised into ${blocks.length} numbered blocks; ${settled.length} blocks are settled, ${unsettled.length} are open decisions, and ${fragmentCount} copies still shadow a canonical home.`
    + `<br><small>Read downwards: purpose → block → canonical home → copies → decisions → proof → faults → foundations.</small>`,
  gh: 'https://github.com/Ventusltd/stars/blob/main/CODE-UNIVERSE.md',
  ext: `${STARS}table.html`,
});

// ---------- 2. chapters ----------
const CH = {
  purpose: add({ id: 'ch-purpose', label: 'What the code is for', type: 'chapter', rag: 'green',
    reason: 'The purposes globalgrid2050 architecture development serves; every block below belongs to one of them.', gh: null, ext: `${STARS}table.html` }),
  canonical: add({ id: 'ch-canonical', label: 'What is canonical', type: 'chapter', rag: 'green',
    reason: `The ${canonicalCount} functions whose one true home the engine graph declares; everything else with the same name is a copy.`,
    gh: 'https://github.com/Ventusltd/ventus-grid-engine/blob/main/genome/engine-graph.json', ext: `${STARS}modular/engine-join.json` }),
  illusion: add({ id: 'ch-illusion', label: 'What is illusion', type: 'chapter', rag: 'red',
    reason: `${fragmentCount} copies of canonical functions that look like separate code but are the same thing written twice; each should import its home.`,
    gh: 'https://github.com/Ventusltd/ventus-grid-engine/blob/main/genome/engine-graph.json', ext: `${STARS}modular/engine-join.json` }),
  decision: add({ id: 'ch-decision', label: 'What is a decision, not a fact', type: 'chapter', rag: 'amber',
    reason: `${unsettled.length} values globalgrid2050 architecture development uses in more than one form; which is true cannot be computed, it has to be decided.`,
    gh: 'https://github.com/Ventusltd/stars/blob/main/CODE-UNIVERSE.md', ext: `${STARS}table.html?state=UNSETTLED` }),
  proof: add({ id: 'ch-proof', label: 'What is proven together', type: 'chapter', rag: 'amber',
    reason: `${reactions.reactions?.length ?? 0} pairs of blocks are used together in shipped apps; "seen together" is evidence of fit, not a passed test.`,
    gh: null, ext: `${STARS}blocks/reactions.json` }),
  fault: add({ id: 'ch-fault', label: 'What breaks', type: 'chapter', rag: 'red',
    reason: `${decays.decays?.length ?? 0} error messages seen in composition tests, each traced to the exact function that throws it.`,
    gh: null, ext: `${STARS}modular/decays.json` }),
  foundation: add({ id: 'ch-foundation', label: 'What everything leans on', type: 'chapter', rag: 'green',
    reason: 'The most-used functions in globalgrid2050 architecture development; a change here is felt everywhere.', gh: null, ext: `${STARS}modular/dependencies.json` }),
};
for (const id of Object.values(CH)) wire('universe', id, 'contains');

// ---------- 3. purposes (categories) ----------
const catIds = new Map();
for (const c of categories) {
  if (c.id === 'other') continue;
  const members = blocks.filter((b) => b.category === c.id && b.kind !== 'auto');
  if (!members.length) continue;
  const id = add({
    id: `cat-${c.id}`, label: c.title, type: 'purpose', rag: members.some((b) => b.state === 'UNSETTLED') ? 'amber' : 'green',
    reason: `${c.blurb || c.title}. ${plural(members.length, 'block')} serve this purpose.`,
    gh: null, ext: `${STARS}table.html?category=${encodeURIComponent(c.id)}`,
  });
  catIds.set(c.id, id);
  wire(CH.purpose, id, 'contains');
}

// ---------- 4. blocks (the named parts) ----------
const blockId = (b) => `block-${b.number}`;
const blockGh = (b) => {
  const f = b.files?.[0];
  if (!f) return null;
  if (typeof f === 'string') return f.startsWith('http') ? f : null;
  return f.gh || (f.repo && f.path ? `https://github.com/${f.repo}/blob/main/${f.path}` : null);
};
const namedBlocks = blocks.filter((b) => b.kind !== 'auto');
for (const b of namedBlocks) {
  const rag = b.state === 'UNSETTLED' ? 'amber' : b.state === 'SETTLED' ? 'green' : 'amber';
  const what = b.description || b.title;
  const rel = [];
  if (b.functions) rel.push(plural(b.functions, 'function'));
  if (b.depends_on?.length) rel.push(`depends on ${b.depends_on.length}`);
  if (b.used_by?.length) rel.push(`used by ${b.used_by.length}`);
  add({
    id: blockId(b), label: `${b.number} ${b.symbol} · ${b.title}`, type: b.kind || 'block', rag,
    reason: `${esc(what).replace(/\.?$/, '.')}${rel.length ? `<br><small>${rel.join(' · ')}</small>` : ''}`,
    gh: blockGh(b), ext: `${STARS}table.html?block=${b.number}`,
  });
}
for (const b of namedBlocks) {
  const cat = catIds.get(b.category);
  if (cat) wire(cat, blockId(b), 'contains');
  for (const d of b.depends_on || []) { const t = findBlock(d); if (t && ids.has(blockId(t))) wire(blockId(b), blockId(t), 'depends-on'); }
  if (b.state === 'UNSETTLED') wire(CH.decision, blockId(b), 'concerns');
}

// ---------- 5. canonical homes and their copies (illusion) ----------
// Group engine-join by canonical label (an engine file). One node per home, one node per copy (capped).
const homes = new Map(); // label -> { gh, functions:Set, fragments:[] }
for (const [fam, rec] of Object.entries(engineJoin.families || {})) {
  const joins = rec.joins || [];
  const canon = joins.filter((j) => j.type === 'canonical');
  const frags = joins.filter((j) => j.type === 'fragment');
  for (const c of canon) {
    const h = homes.get(c.label) || { gh: c.gh, functions: new Set(), fragments: [] };
    h.functions.add(rec.name);
    for (const f of frags) h.fragments.push({ ...f, fn: rec.name, family: fam });
    homes.set(c.label, h);
  }
}
const homeList = [...homes.entries()].sort((a, b) => b[1].fragments.length - a[1].fragments.length);
const homeIds = new Map();
for (const [label, h] of homeList) {
  const id = add({
    id: `home-${label.replace(/[^a-z0-9]+/gi, '-')}`, label, type: 'canonical', rag: h.fragments.length ? 'amber' : 'green',
    reason: `The one true home of ${[...h.functions].slice(0, 4).map(esc).join(', ')}${h.functions.size > 4 ? ` and ${h.functions.size - 4} more` : ''}.`
      + (h.fragments.length ? `<br><small>${`${h.fragments.length} ${h.fragments.length === 1 ? 'copy' : 'copies'}`} elsewhere should import from here.</small>` : ''),
    gh: h.gh || null, ext: `${STARS}modular/engine-join.json`,
  });
  homeIds.set(label, id);
  wire(CH.canonical, id, 'contains');
}
// Copies: budget what remains so the whole graph stays under MAX_NODES with room for the rest.
const RESERVE = 20 + 12 + 25; // hubs + decays + slack
let copyBudget = MAX_NODES - nodes.length - RESERVE;
const copySeen = new Set();
for (const [label, h] of homeList) {
  for (const f of h.fragments) {
    if (copyBudget <= 0) break;
    const key = f.label;
    if (copySeen.has(key)) { wire(`copy-${key.replace(/[^a-z0-9]+/gi, '-')}`, homeIds.get(label), 'should-import'); continue; }
    copySeen.add(key);
    const id = add({
      id: `copy-${key.replace(/[^a-z0-9]+/gi, '-')}`, label: key, type: 'copy', rag: 'red',
      reason: `A copy of ${esc(f.fn)} that lives apart from its home; it reads as separate code but is the same function written again.`
        + `<br><small>${esc(f.relation || 'copy')} · family ${f.family}</small>`,
      gh: f.gh || null, ext: `${STARS}code.html?family=${f.family}`,
    });
    copyBudget--;
    wire(id, homeIds.get(label), 'should-import');
    wire(CH.illusion, id, 'contains');
  }
}
const copiesShown = copySeen.size;

// ---------- 6. proven together (reactions as edges between blocks) ----------
let seen = 0, unstable = 0, mixed = 0;
const appsBySymbol = new Map();
for (const app of reactions.apps || []) for (const s of app.blocks || []) appsBySymbol.set(s, (appsBySymbol.get(s) || 0) + 1);
for (const r of reactions.reactions || []) {
  const a = findBlock(r.a), b = findBlock(r.b);
  if (!a || !b || !ids.has(blockId(a)) || !ids.has(blockId(b)) || r.verdict === 'untested') continue;
  const type = r.verdict === 'proven' ? 'proven' : r.verdict === 'unstable' ? 'unstable' : r.verdict === 'fails' ? 'fails' : r.verdict === 'mixed evidence' ? 'mixed-evidence' : 'seen-together';
  if (type === 'unstable' || type === 'fails') unstable++; else if (type === 'mixed-evidence') mixed++; else seen++;
  wire(blockId(a), blockId(b), type);
}
// Blocks that appear in no shipped app are untested by use.
for (const b of namedBlocks) {
  if (b.kind === 'constant') continue;
  if ((appsBySymbol.get(b.symbol) || 0) > 0) wire(CH.proof, blockId(b), 'contains');
}

// ---------- 7. what breaks (decays → throwing functions → blocks) ----------
const familyToBlock = new Map();
for (const b of blocks) for (const f of b.inside || []) familyToBlock.set(String(f.family), b);
const decayList = [...(decays.decays || [])].sort((a, b) => (b.red_stars || 0) - (a.red_stars || 0)).slice(0, 12);
decayList.forEach((d, i) => {
  const throwers = (d.families || []).slice(0, 3);
  const first = throwers[0] ? family(throwers[0].family) : null;
  const id = add({
    id: `decay-${i}`, label: d.needle || d.message, type: 'fault', rag: 'red',
    reason: `An error seen ${(d.red_stars || 0).toLocaleString()} times in composition tests; ${plural((d.families || []).length, 'function')} can throw it.`
      + `<br><small>${esc(d.message)}</small>`,
    gh: familyGh(first), ext: throwers[0] ? `${STARS}code.html?family=${throwers[0].family}` : `${STARS}modular/decays.json`,
  });
  wire(CH.fault, id, 'contains');
  const hit = new Set();
  for (const t of d.families || []) { const b = familyToBlock.get(String(t.family)); if (b && ids.has(blockId(b))) hit.add(blockId(b)); }
  for (const bid of hit) wire(id, bid, 'thrown-by');
});

// ---------- 8. foundations (hubs) ----------
const hubs = (deps.hubs || []).slice(0, 20);
for (const h of hubs) {
  const rec = family(h.family);
  const id = add({
    id: `hub-${h.family}`, label: `${h.name} · family ${h.family}`, type: 'foundation', rag: 'green',
    reason: `A function ${plural(h.used_by, 'other function')} rely on; it is a foundation, so a change here reaches all of them.`
      + (rec?.repos?.length ? `<br><small>in ${plural(rec.repos.length, 'repository')}, ${plural(rec.places?.length || 0, 'place')}</small>` : ''),
    gh: familyGh(rec), ext: `${STARS}code.html?family=${h.family}`,
  });
  wire(CH.foundation, id, 'contains');
  const b = familyToBlock.get(String(h.family));
  if (b && ids.has(blockId(b))) wire(blockId(b), id, 'contains');
}

// ---------- write ----------
const edgeTypes = {};
for (const e of edges) edgeTypes[e.type] = (edgeTypes[e.type] || 0) + 1;
const graph = {
  id: 'sense',
  title: 'Sense of the code universe',
  generated_utc: new Date().toISOString(),
  note: 'Order is the narrative: whole, chapters, purposes, blocks, canonical homes, copies, faults, foundations. Edge types are the shared vocabulary (relationships/VOCABULARY.md): contains, depends-on, canonical, should-import, concerns, proven, seen-together, mixed-evidence, unstable, fails, thrown-by.',
  source: { blocks: 'blocks/blocks.json', reactions: 'blocks/reactions.json', dependencies: 'modular/dependencies.json', decays: 'modular/decays.json', engine_join: 'modular/engine-join.json' },
  nodes, edges,
};
mkdirSync(join(ROOT, 'sense'), { recursive: true });
const out = JSON.stringify(graph);
writeFileSync(join(ROOT, 'sense/graph.json'), out);

const md = `# Sense of the code universe

Generated ${graph.generated_utc}. ${nodes.length} nodes, ${edges.length} edges, ${(out.length / 1024).toFixed(1)} KB.

This graph is not a list of files. It is globalgrid2050 architecture development's code read in an order that makes sense, so the FOCUS list on the
Spider dashboard reads as a narrative from the whole to the parts:

1. **The code universe** — ${familyCount.toLocaleString()} distinct functions, ${blocks.length} numbered blocks.
2. **What the code is for** — ${catIds.size} purposes, each containing the blocks that serve it.
3. **The blocks** — ${namedBlocks.length} named blocks (constants, engines, cartridges, layers, apps, tools), wired by *depends-on*
   so a reader can walk from a purpose to a part to what that part needs.
4. **What is canonical** — ${homeList.length} homes declared by the engine graph, holding ${canonicalCount} canonical functions.
5. **What is illusion** — ${fragmentCount} copies of those functions exist elsewhere (${copiesShown} shown here); each is wired
   *should-import* to its home. They look like separate code; they are the same function written twice.
6. **What is a decision, not a fact** — ${unsettled.length} values in use in more than one form. No computation settles them.
7. **What is proven together** — ${seen} block pairs with passed tests or app co-occurrence, ${mixed} pairs with mixed test evidence and ${unstable} unstable pairs, drawn as edges
   between the blocks. A block not wired from this chapter has never shipped in an app; *proven* wires are composition tests that passed, *seen-together* wires are use without a test.
8. **What breaks** — the ${decayList.length} most frequent composition-test errors, each wired to the block whose function throws it.
9. **What everything leans on** — the ${hubs.length} most-used functions in globalgrid2050 architecture development.

## Reading the colours

- green: settled, canonical, or a foundation.
- amber: open decision, or a home that still has copies.
- red: a copy that should import its home, or an error that is actually thrown.

## Edge types

${Object.entries(edgeTypes).map(([t, n]) => `- \`${t}\`: ${n}`).join('\n')}

## Sources

blocks/blocks.json, blocks/reactions.json, modular/dependencies.json, modular/decays.json, modular/engine-join.json, code/f/*.json
(all published at ${STARS}).
`;
writeFileSync(join(ROOT, 'sense/SENSE.md'), md);
console.log(`sense/graph.json: ${nodes.length} nodes, ${edges.length} edges, ${(out.length / 1024).toFixed(1)} KB`);
console.log(`edge types: ${JSON.stringify(edgeTypes)}`);

Structure

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

storagestars / modular-star/structure.mjs · lines 1–139 of 139 · Entry point · pattern catTitle (shared by 5 files)

What it does
It fetches blocks, live sites and engine graph. Defines 15 functions or classes, including arg, esc, mono, kb, utc. Uses libraries node:fs, node:path. Side effects: reads or writes files; makes network requests.
Inputs & outputs
In: data source: ventus-grid-engine data; JSON file blocks.json; JSON file source.json; JSON file live-sites.json; JSON file engine-graph.json; JSON file graph.json; command-line arguments. Out: JSON file graph.json.
Downstream impact
Used directly by 1 file: Modular Star Workflow (stars).
What it achieves
It reads JSON (`readJson`), gets JSON (`getJson`) and registers text (`registerText`). The structure of GlobalGrid2050 architecture development, top-down: Estate → repositories → categories → the named blocks → the engine's canonical modules, as a Spider graph whose enumeration reads like a table of contents. It reads `blocks/blocks.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, esc, mono, kb, utc, readJson, getJson, catTitle, registerText, repoRole, edge, rel
Defines here
arg, esc, mono, kb, utc, readJson, getJson, catTitle, registerText, repoRole, edge, rel, blockOfModule, mid, ml
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/structure.mjs:1-139 · blob 70bdc5bfae3b0a45c711ab36ea1432158d85eaca · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: unknown · users: none · canonical: supporting_data
// The structure of globalgrid2050 architecture development, top-down: Estate → repositories → categories → the named blocks → the engine's
// canonical modules, as a Spider graph whose enumeration reads like a table of contents.
// Reads blocks/blocks.json (blocks, categories, interdependencies), modular/source.json (which repositories were
// scanned, at which commit), modular-star/live-sites.json (public sites), spider/register.py (the graphs this
// repository publishes) and the engine graph at ventus-grid-engine (fetched; optional). No auto-blocks, no
// functions, so the graph stays well under 300 cards. Writes structure/graph.json and structure/STRUCTURE.md.
// Usage: node modular-star/structure.mjs --out .
import { readFileSync, writeFileSync, mkdirSync, existsSync, statSync } 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', '.');
const SITE = 'https://ventusltd.github.io/stars/';
const ENGINE_SITE = 'https://ventusltd.github.io/ventus-grid-engine/';
const GH = 'https://github.com/';
const now = new Date();
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
const mono = s => `<div style="font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12px;color:#9aa3b5;margin-top:4px;white-space:pre-wrap">${s}</div>`;
const kb = n => n >= 1024 ? Math.round(n / 1024) + ' KB' : n + ' B';
const utc = iso => iso ? new Date(iso).toISOString().replace('T', ' ').slice(0, 16) + ' UTC' : 'unknown';
const readJson = (f, d) => { try { return JSON.parse(readFileSync(path.join(OUT, f), 'utf8')); } catch { return d; } };
const getJson = async u => { try { const r = await fetch(u); return r.ok ? await r.json() : null; } catch { return null; } };

// ---- inputs
const table = readJson('blocks/blocks.json', { categories: [], blocks: [] });
const categories = table.categories || [];
const catIndex = new Map(categories.map((c, i) => [c.id, i]));
const catTitle = id => categories.find(c => c.id === id)?.title || id;
const named = (table.blocks || []).filter(b => b.kind !== 'auto').sort((a, b) => (catIndex.get(a.category) ?? 99) - (catIndex.get(b.category) ?? 99) || a.number - b.number);
const source = readJson('modular/source.json', { repositories: [] });
const scanned = new Map((source.repositories || []).map(r => [r.repo, r]));
const sites = new Map(((() => { try { return JSON.parse(readFileSync(new URL('./live-sites.json', import.meta.url), 'utf8')); } catch { return { sites: [] }; } })().sites || []).map(s => [s.repo, s.site]));
const registerText = (() => { try { return readFileSync(path.join(OUT, 'spider', 'register.py'), 'utf8'); } catch { return ''; } })();
const published = [...registerText.matchAll(/\(\s*"([\w-]+)",\s*"([^"]+)",\s*"([^"]+)"/g)].map(m => ({ id: m[1], title: m[2], src: m[3] }));
const engineGraph = await getJson(ENGINE_SITE + 'genome/engine-graph.json');
const engineModules = (engineGraph?.nodes || []).filter(n => n.type === 'canonical');

// ---- repositories: those blocks live in, plus the ones named in the registry (this repository and the source of the tests)
const ENGINE_REPO = 'Ventusltd/ventus-grid-engine';
const blocksIn = new Map();
for (const b of named) for (const r of b.repos || []) { if (!blocksIn.has(r)) blocksIn.set(r, []); blocksIn.get(r).push(b.symbol); }
const extra = ['Ventusltd/stars', ...[...registerText.matchAll(/\b(star-maker|code-generator)\b/g)].map(m => 'Ventusltd/' + m[1])];
const repoNames = [...new Set([ENGINE_REPO, ...blocksIn.keys(), ...extra])].filter(r => r.startsWith('Ventusltd/'));
repoNames.sort((a, b) => (a === ENGINE_REPO ? -1 : b === ENGINE_REPO ? 1 : 0) || (blocksIn.get(b)?.length || 0) - (blocksIn.get(a)?.length || 0) || a.localeCompare(b));
const repoRole = r => r === ENGINE_REPO ? 'The engine: the canonical modules every other copy is measured against, and the Spider dashboard.' :
  r === 'Ventusltd/stars' ? `This repository: the numbered code database, the periodic table and the reports. Publishes ${published.length} graphs for the dashboard: ${published.map(p => p.title).join(', ')}.` :
  r === 'Ventusltd/star-maker' ? 'The recorded composition tests (the stars) that the reports read.' :
  r === 'Ventusltd/code-generator' ? 'Assembles apps from blocks of the periodic table.' : 'A public repository of globalgrid2050 architecture development.';

const nodes = [], edges = [];
const edge = (from, to, type) => edges.push({ from, to, type });

// ---- 1. globalgrid2050 architecture development
nodes.push({ id: 'estate', label: 'globalgrid2050 architecture development', type: 'estate', rag: 'green',
  reason: `Every public repository, the named blocks of the periodic table found across them, and the engine's canonical modules. Read top-down: estate, repositories, categories, blocks, modules.` +
    mono(esc(`${repoNames.length} repositories · ${categories.length} categories · ${named.length} named blocks · ${engineModules.length} engine modules · ${source.repositories?.length || 0} repositories scanned ${utc(source.generated_utc)}`)),
  gh: `${GH}Ventusltd`, ext: `${SITE}table.html` });

// ---- 2. repositories
for (const r of repoNames) {
  const short = r.split('/')[1], sc = scanned.get(r), syms = blocksIn.get(r) || [];
  const line = [syms.length ? `${syms.length} blocks: ${syms.join(', ')}` : 'no named block found here', sc ? `${sc.code_files} code files scanned at ${String(sc.commit).slice(0, 7)}` : 'not in the last scan', sites.get(r) ? `site ${sites.get(r)}` : null].filter(Boolean).join('\n');
  nodes.push({ id: `repo:${r}`, label: short, type: 'repo', rag: syms.length || sc?.code_files ? 'green' : 'grey', reason: esc(repoRole(r)) + mono(esc(line)), gh: GH + r, ext: sites.get(r) || GH + r });
  edge('estate', `repo:${r}`, 'contains');
}

// ---- 3. categories, in table order
for (const c of categories) {
  const inCat = named.filter(b => b.category === c.id);
  if (!inCat.length) continue;
  nodes.push({ id: `category:${c.id}`, label: c.title, type: 'category', rag: 'green', reason: esc(c.blurb) + mono(esc(`${inCat.length} blocks: ${inCat.map(b => b.symbol).join(', ')}`)), gh: null, ext: `${SITE}table.html?category=${c.id}` });
}

// ---- 4. the named blocks, by category then number
const rel = b => [b.depends_on?.length ? 'depends on: ' + b.depends_on.map(d => d.symbol).join(', ') : 'depends on: none recorded', b.used_by?.length ? 'used by: ' + b.used_by.join(', ') : 'used by: none recorded'].join(' · ');
for (const b of named) {
  const rag = b.state === 'UNSETTLED' ? 'amber' : b.functions ? 'green' : 'grey';
  const line = [`#${b.number} · ${catTitle(b.category)} · ${b.functions} functions · in ${(b.repos || []).length} repositories`, rel(b), b.state === 'UNSETTLED' ? 'unsettled: more than one value is in use' : null].filter(Boolean).join('\n');
  nodes.push({ id: `block:${b.symbol}`, label: `${b.symbol} · ${b.title}`, type: b.kind, rag, reason: esc(b.description) + mono(esc(line)),
    gh: b.files?.[0] ? `${GH}${b.files[0].repo}/blob/${b.files[0].commit}/${b.files[0].path}` : null, ext: `${SITE}table.html?block=${b.symbol}` });
  edge(`category:${b.category}`, `block:${b.symbol}`, 'contains');
  for (const r of b.repos || []) if (repoNames.includes(r)) edge(`repo:${r}`, `block:${b.symbol}`, 'contains');
  for (const d of b.depends_on || []) edge(`block:${b.symbol}`, `block:${d.symbol}`, 'depends-on');
}

// ---- 5. the engine's canonical modules, in the engine graph's own order
const blockOfModule = label => named.find(b => (b.files || []).some(f => f.repo === ENGINE_REPO && f.path === label));
for (const n of engineModules) {
  const id = `module:${n.label}`, b = blockOfModule(n.label);
  nodes.push({ id, label: n.label, type: 'module', rag: n.rag || 'green', reason: esc(n.reason || 'A canonical module of the engine.') + mono(esc(`canonical module · ${b ? 'block ' + b.symbol + ' · ' + b.title : 'no block of the periodic table yet'}`)),
    gh: n.gh || `${GH}${ENGINE_REPO}/blob/main/${n.label}`, ext: `${ENGINE_SITE}?graph=engine-graph&focus=${encodeURIComponent(n.label)}` });
  edge(`repo:${ENGINE_REPO}`, id, 'contains');
  if (b) edge(id, `block:${b.symbol}`, 'implements');
}
if (!engineModules.length) nodes.push({ id: 'module:none', label: 'Engine modules', type: 'module', rag: 'grey', reason: 'The engine graph could not be fetched during this run, so its modules are not listed. They return on the next run.', gh: `${GH}${ENGINE_REPO}`, ext: `${ENGINE_SITE}?graph=engine-graph` });

// ---- write the graph
mkdirSync(path.join(OUT, 'structure'), { recursive: true });
const graph = { schema: 'structure-graph.v1', label: 'Structure of globalgrid2050 architecture development', generated_utc: now.toISOString(),
  note: 'Top-down: globalgrid2050 architecture development, its repositories, the categories of the periodic table, the named blocks with their interdependencies, and the canonical modules of the engine in the engine graph\'s order. Rebuilt by the Modular star workflow.',
  counts: { repositories: repoNames.length, categories: nodes.filter(n => n.type === 'category').length, blocks: named.length, engine_modules: engineModules.length },
  nodes, edges };
writeFileSync(path.join(OUT, 'structure', 'graph.json'), JSON.stringify(graph));

// ---- STRUCTURE.md with Mermaid diagrams
const mid = s => 'n_' + s.replace(/[^a-z0-9]+/gi, '_');
const ml = s => `"${String(s).replace(/"/g, '#quot;')}"`;
const cls = { green: 'ok', amber: 'warn', red: 'fail', blue: 'live', grey: 'off' };
const defs = ['  classDef ok fill:#153d2a,stroke:#39d353,color:#e6edf3', '  classDef warn fill:#3d2f0f,stroke:#ffd54a,color:#e6edf3', '  classDef fail fill:#3d1414,stroke:#ff6b6b,color:#e6edf3', '  classDef live fill:#12304a,stroke:#58a6ff,color:#e6edf3', '  classDef off fill:#21262d,stroke:#6b7280,color:#9aa3b5'];
const d1 = ['flowchart TD', ...defs, `  estate[${ml('globalgrid2050 architecture development')}]:::ok`];
for (const r of repoNames) { const n = nodes.find(x => x.id === `repo:${r}`); d1.push(`  ${mid(r)}[${ml(r.split('/')[1] + (blocksIn.get(r)?.length ? ' · ' + blocksIn.get(r).length + ' blocks' : ''))}]:::${cls[n.rag]}`, `  estate --> ${mid(r)}`); }
const d2 = ['flowchart LR', ...defs];
for (const c of categories) { const inCat = named.filter(b => b.category === c.id); if (!inCat.length) continue; d2.push(`  subgraph ${mid(c.id)}[${ml(c.title)}]`); for (const b of inCat) d2.push(`    ${mid('block:' + b.symbol)}[${ml(b.symbol + ' · ' + b.title)}]:::${cls[nodes.find(n => n.id === 'block:' + b.symbol).rag]}`); d2.push('  end'); }
for (const b of named) for (const d of b.depends_on || []) if (named.some(x => x.symbol === d.symbol)) d2.push(`  ${mid('block:' + b.symbol)} --> ${mid('block:' + d.symbol)}`);
const d3 = ['flowchart LR', ...defs, `  engine[${ml('ventus-grid-engine')}]:::ok`];
for (const n of engineModules) { const b = blockOfModule(n.label); d3.push(`  ${mid(n.label)}[${ml(n.label)}]:::${cls[n.rag] || 'ok'}`, `  engine --> ${mid(n.label)}`); if (b) d3.push(`  ${mid(n.label)} -. block .-> ${mid('block:' + b.symbol)}[${ml(b.symbol + ' · ' + b.title)}]:::${cls[nodes.find(x => x.id === 'block:' + b.symbol).rag]}`); }
const md = `# Structure of globalgrid2050 architecture development

Updated ${utc(now.toISOString())} by GitHub Actions. Top-down: globalgrid2050 architecture development, its repositories, the categories of the periodic table, the named blocks with their interdependencies, and the canonical modules of the engine in the engine graph's own order.
The same structure, card by card, is \`structure/graph.json\` (${kb(statSync(path.join(OUT, 'structure', 'graph.json')).size)}, ${nodes.length} cards, ${edges.length} links), registered for the Spider dashboard as **Structure of globalgrid2050 architecture development**. Amber is a block whose value is not yet settled; grey has no function inside yet.

## Repositories (${repoNames.length})

\`\`\`mermaid
${d1.join('\n')}
\`\`\`

## Blocks by category (${named.length}), arrows mean "depends on"

\`\`\`mermaid
${d2.join('\n')}
\`\`\`

## Engine modules (${engineModules.length}), in the engine graph's order

${engineModules.length ? '```mermaid\n' + d3.join('\n') + '\n```' : 'The engine graph could not be fetched during this run.'}
`;
writeFileSync(path.join(OUT, 'structure', 'STRUCTURE.md'), md);
console.log(`Structure: ${nodes.length} nodes (${repoNames.length} repositories, ${named.length} blocks, ${engineModules.length} engine modules), ${edges.length} edges, ${kb(statSync(path.join(OUT, 'structure', 'graph.json')).size)}.`);

Test

A JavaScript module in the modular star folder of Stars.

teststars / modular-star/test.mjs · lines 1–84 of 84 · Entry point

What it does
It tests its inputs. Defines B, one. Uses libraries node:test, node:assert/strict, node:fs, node:os, node:child_process. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Downstream impact
Used directly by 1 file: Modular Star Workflow (stars).
What it achieves
Defines `one`.
Why it matters
Run by Modular Star Workflow.
Application
stars · modular-star · JavaScript module
Uses
Stars — Modular Star (script call), node:test, node:assert/strict, node:fs, node:os, node:child_process, node:path
Used by
run by Modular Star Workflow (workflow run)
Produces
B, one
Defines here
B, one
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/test.mjs:1-84 · blob 6e5c53bd2012a71527dc97ca76820d768abab376 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: unknown · users: none · canonical: unknown
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { spawnSync } from 'node:child_process';
import path from 'node:path';
import { openDb, ingestFile, rebuildTablet, extractJs, extractHtml, extractAny, gitBlobId, elementSource } from './lib.mjs';

const B = s => Buffer.from(s);
const ADD = 'function add(a, b) {\n  const s = a + b;\n  return s;\n}\n';
const one = (ctx, sql) => ctx.db.prepare(sql).get();

test('the same function in two files is one element found in two places', () => {
  const ctx = openDb(':memory:');
  ingestFile(ctx, { repo: 'r1', commit: 'c1', path: 'a.js', bytes: B(ADD) });
  ingestFile(ctx, { repo: 'r2', commit: 'c2', path: 'lib/b.js', bytes: B('// helper\n' + ADD) });
  assert.equal(one(ctx, 'SELECT count(*) c FROM element').c, 1);
  assert.equal(one(ctx, 'SELECT count(*) c FROM tablet_element').c, 2);
});

test('a reformatted copy is a new element in the same family', () => {
  const ctx = openDb(':memory:');
  ingestFile(ctx, { repo: 'r', commit: 'c', path: 'a.js', bytes: B(ADD) });
  ingestFile(ctx, { repo: 'r', commit: 'c', path: 'b.js', bytes: B('function add(a,b){\n    const s=a+b; // sum\n    return s;\n}\n') });
  assert.equal(one(ctx, 'SELECT count(*) c FROM element').c, 2);
  assert.equal(one(ctx, 'SELECT count(*) c FROM family').c, 1);
});

test('self-contained functions are told apart from ones that need outside names', () => {
  const f = extractJs('function a(x) {\n  return Math.max(x, 0);\n}\nfunction b(id) {\n  return document.getElementById(id);\n}\nclass P {\n  get x() {\n    return this.v;\n  }\n}\n');
  const by = Object.fromEntries(f.map(x => [x.name, x]));
  assert.equal(by.a.standalone, true);
  assert.deepEqual(by.b.needs, ['document']);
  assert.equal(by.b.standalone, false);
  assert.equal(by.P.standalone, true);
  assert.equal(by.x.kind, 'method');
});

test('functions inside HTML scripts keep the file line numbers and exact source', () => {
  const html = '<html>\n<body>\n<script>function g(x) {\n  return x * 2;\n}\n</script>\n';
  const [g] = extractHtml(html);
  assert.equal(g.first, 3);
  assert.equal(g.last, 5);
  const ctx = openDb(':memory:');
  const tablet = ingestFile(ctx, { repo: 'r', commit: 'c', path: 'i.html', bytes: B(html) });
  const te = ctx.db.prepare('SELECT * FROM tablet_element WHERE tablet = ?').get(tablet);
  assert.equal(elementSource(ctx, te), 'function g(x) {\n  return x * 2;\n}');
});

test('numbers survive reopening, and new lines get new higher numbers', () => {
  const file = path.join(mkdtempSync(path.join(tmpdir(), 'modular-')), 't.sqlite');
  let ctx = openDb(file);
  ingestFile(ctx, { repo: 'r', commit: 'c1', path: 'a.js', bytes: B(ADD) });
  const before = ctx.db.prepare('SELECT n, sha FROM line ORDER BY n').all();
  ctx.db.close();
  ctx = openDb(file);
  ingestFile(ctx, { repo: 'r', commit: 'c2', path: 'z.js', bytes: B('const z = 1;\n' + ADD) });
  const after = ctx.db.prepare('SELECT n, sha FROM line ORDER BY n').all();
  for (const r of before) assert.deepEqual(Buffer.from(after.find(x => x.n === r.n).sha), Buffer.from(r.sha));
  assert.equal(after.length, before.length + 1);
  assert.ok(after.at(-1).n > before.at(-1).n);
});

test('files rebuild byte for byte, including Windows line endings and no final newline', () => {
  const ctx = openDb(':memory:');
  const bytes = B('\uFEFFfunction w() {\r\n  return 1;\r\n}\r\nconst end = 2;');
  const tablet = ingestFile(ctx, { repo: 'r', commit: 'c', path: 'w.js', bytes });
  const rebuilt = rebuildTablet(ctx, tablet);
  assert.deepEqual(rebuilt, bytes);
  assert.equal(gitBlobId(rebuilt), gitBlobId(bytes));
});

test('unusual line breaks are refused rather than mis-numbered', () => {
  assert.match(extractAny('js', B('function q() {\r  return 1;\r}\r')).issue, /Unusual line breaks/);
});

const python = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');
test('Python functions: same logic in a different layout shares a family', { skip: spawnSync(python, ['--version']).status !== 0 }, () => {
  const ctx = openDb(':memory:');
  ingestFile(ctx, { repo: 'r', commit: 'c', path: 'a.py', bytes: B('def area(w, h):\n    # rectangle\n    return w * h\n\n\n') });
  ingestFile(ctx, { repo: 'r', commit: 'c', path: 'b.py', bytes: B('def area(w,h):\n\n    return (w*h)\n') });
  assert.equal(one(ctx, 'SELECT count(*) c FROM element').c, 2);
  assert.equal(one(ctx, 'SELECT count(*) c FROM family').c, 1);
});

Universe Compact Proof

A JavaScript module in the modular star folder of Stars that uses SHA-256.

ingeststars / modular-star/universe-compact-proof.mjs · lines 1–18 of 18 · Not reached from any entry point (candidate for review) · pattern expand (shared by 9 files)

What it does
It loads data. Defines read, expand, has. Uses libraries node:fs/promises. Side effects: reads or writes files.
Inputs & outputs
In: command-line arguments.
What it achieves
Defines `read`, `expand` and `has`.
Why it matters
No other file in the estate was found to import it.
Application
stars · modular-star · JavaScript module
Uses
node:fs/promises
Used by
none found
Produces
read, expand, has
Defines here
read, expand, has
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
stars@030ebc202d35959fecd162327892f671d1d9a0cc modular-star/universe-compact-proof.mjs:1-18 · blob 7eb82e71a811f5d3e2b022e299340220f247dc78 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: duplicate_candidate
import fs from 'node:fs/promises';import path from 'node:path';import{digest}from'./universe-model.mjs';
const root=process.argv[2];if(!root)throw Error('Generation directory required');
const manifest=JSON.parse(await fs.readFile(path.join(root,'manifest.json'),'utf8'));const tables={},relations=new Map();let bytes=0,files=0,max=0;
async function read(entry){const resolved=path.resolve(root,entry.path);if(!resolved.startsWith(path.resolve(root)+path.sep))throw Error('Escaping manifest path');const b=await fs.readFile(resolved);if(b.length>=600000||b.length!==entry.bytes||digest(b)!==entry.sha256)throw Error('Hash/size mismatch: '+entry.path);bytes+=b.length;max=Math.max(max,b.length);files++;return JSON.parse(b);}
for(const e of manifest.relations||[])relations.set(e.path,await read(e));
function expand(value){if(Array.isArray(value))return value;if(value?.parts){const result=value.parts.flatMap(p=>{if(!relations.has(p))throw Error('Missing relation part');return relations.get(p);});if(result.length!==value.count)throw Error('Relation count mismatch');return result;}throw Error('Missing relation array');}
for(const[kind,entries]of Object.entries(manifest.indexes)){const map=new Map();tables[kind]=map;for(const e of entries){const rows=await read(e);if(rows.length!==e.count||rows[0]?.n!==e.first||rows.at(-1)?.n!==e.last)throw Error('Index bounds mismatch');for(const r of rows){if(map.has(r.n))throw Error('Duplicate primary key');for(const[k,v]of Object.entries(r))if(v?.parts)r[k]=expand(v);map.set(r  … [line shortened here: 409 characters; full line on GitHub]
const countNames={line:'lines',family:'families',tablet:'tablets',source:'sources',block:'blocks',repository:'repositories'};
for(const[kind,name]of Object.entries(countNames))if(tables[kind].size!==manifest.counts[name])throw Error('Primary key count mismatch: '+kind);
const has=(kind,n)=>{if(!tables[kind]?.has(n))throw Error(`Unresolved ${kind} key ${n}`);return tables[kind].get(n);};
for(const r of tables.line.values()){if(digest(Buffer.from(r.base64,'base64'))!==r.sha256)throw Error('Stored line byte hash mismatch');for(const n of r.families)if(!has('family',n).lines.includes(r.n))throw Error('Missing reverse family-to-line relation');for(const n of r.tablets)if(!has('tablet',n).lines.includes(r.n))throw Error('Missing reverse tablet-to-line relation');}
for(const r of tables.family.values()){for(const n of r.lines)if(!has('line',n).families.includes(r.n))throw Error('Missing reverse line-to-family relation');for(const n of r.tablets)has('tablet',n);for(const n of r.uses)if(!has('family',n).used_by.includes(r.n))throw Error('Missing reverse dependency candidate');for(const n of r.used_by)if(!has('family',n).uses.includes(r.n))throw Error('Missing   … [line shortened here: 546 characters; full line on GitHub]
for(const r of tables.tablet.values()){for(const n of r.lines)if(!has('line',n).tablets.includes(r.n))throw Error('Missing reverse line-to-tablet relation');for(const n of r.sources)if(has('source',n).tablet!==r.n)throw Error('Source/tablet mismatch');for(const n of r.families)if(!has('family',n).tablets.includes(r.n))throw Error('Tablet/family mismatch');}
for(const r of tables.source.values()){if(!/^[a-f0-9]{40}$/.test(r.commit)||digest(JSON.stringify([r.repo,r.commit,r.path]))!==r.n)throw Error('Invalid pinned source identity');if(!has('tablet',r.tablet).sources.includes(r.n))throw Error('Missing reverse source occurrence');}
for(const r of tables.block.values())for(const n of r.families)if(!has('family',n).blocks.includes(r.n))throw Error('Missing forward membership');
for(const r of tables.repository.values()){for(const n of r.families)has('family',n);for(const n of r.sources)if(has('source',n).repo!==r.n)throw Error('Repository/source mismatch');}
bytes+=(await fs.stat(path.join(root,'manifest.json'))).size;if(bytes>=200000000)throw Error('200 MB publication bound exceeded');
console.log(JSON.stringify({observed_utc:new Date().toISOString(),passed:true,source_commit:manifest.source_commit,database_sha256:manifest.database_sha256,counts:manifest.counts,total_bytes:bytes,files:files+1,max_file_bytes:max,checks:['shard hashes and sizes','all permanent key counts','all exact line byte hashes','reciprocal line/family/tablet membership','reciprocal candidate dependencies','r  … [line shortened here: 520 characters; full line on GitHub]

Universe Compact

A JavaScript module in the modular star folder of Stars that reads families, using SHA-256.

storagestars / modular-star/universe-compact.mjs · lines 1–27 of 27 · Not reached from any entry point (candidate for review) · pattern table (shared by 65 files)

What it does
It loads families. Defines json, table, sorted. Uses libraries node:fs/promises, node:fs, node:path. Side effects: reads or writes files.
Inputs & outputs
In: JSON file families.json; JSON file index.json; command-line arguments. Out: JSON file.
What it achieves
Defines `json`, `table` and `sorted`.
Why it matters
No other file in the estate was found to import it.
Application
stars · modular-star · JavaScript module
Uses
Universe Model (import), node:fs/promises, node:fs, node:path
Used by
none found
Produces
json, table, sorted
Defines here
json, table, sorted
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/universe-compact.mjs:1-27 · blob d1a392d4ef12cc06a1ae62561d4a2a0f2af81df7 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unreached_review
import fs from 'node:fs/promises';
import {readFileSync} from 'node:fs';
import path from 'node:path';
import {readUniverse,digest} from './universe-model.mjs';
const [db,source,out,commit]=process.argv.slice(2);
if(!db||!source||!out||!/^[a-f0-9]{40}$/.test(commit||''))throw Error('Usage: universe-compact.mjs db source new-output exact-commit');
const json=p=>JSON.parse(readFileSync(path.join(source,p),'utf8'));
const m=readUniverse(db,json('blocks/families.json'),json('code/index.json'));
await fs.mkdir(out,{recursive:false});
let bytesTotal=0,maxBytes=0;const indexes={},files=[],relations=[];await fs.mkdir(path.join(out,'relations'));
async function table(kind,records){
 await fs.mkdir(path.join(out,kind));indexes[kind]=[];let batch=[],bytes=2;
 async function flush(){if(!batch.length)return;const name=`${kind}/${indexes[kind].length}.json`,content=Buffer.from(JSON.stringify(batch));if(content.length>=600000)throw Error('Shard too large');await fs.writeFile(path.join(out,name),content,{flag:'wx'});const entry={path:name,first:batch[0].n,last:batch.at(-1).n,count:batch.length,bytes:content.length,sha256:digest(content)};indexes[kind].push  … [line shortened here: 514 characters; full line on GitHub]
 for(const row of records){
  if(Buffer.byteLength(JSON.stringify(row))>570000){for(const [field,values]of Object.entries(row)){if(!Array.isArray(values)||values.length<1000)continue;const parts=[];for(let i=0;i<values.length;i+=1000){const name='relations/'+relations.length+'.json',content=Buffer.from(JSON.stringify(values.slice(i,i+1000)));if(content.length>=600000)throw Error('Relation shard too large');await fs.writeFile  … [line shortened here: 661 characters; full line on GitHub]
  const size=Buffer.byteLength(JSON.stringify(row))+1;if(size>580000)throw Error(`Record needs relation partitioning: ${kind}/${row.n} (${size})`);if(bytes+size>580000)await flush();batch.push(row);bytes+=size;}await flush();
}
const sorted=map=>[...map.keys()].sort((a,b)=>typeof a==='number'?a-b:a.localeCompare(b));
await table('line',sorted(m.lines).map(n=>({n,sha256:m.lines.get(n).sha,base64:m.lines.get(n).base64,families:[...(m.lineFamilies.get(n)||[])],tablets:[...(m.lineTablets.get(n)||[])]})));
await table('family',sorted(m.families).map(n=>{const f=m.families.get(n);return {n,names:[...f.names],needs:[...f.needs],lines:[...f.lines],tablets:[...f.tablets],uses:[...f.uses.keys()],used_by:[...f.usedBy.keys()],blocks:[...(m.memberships.get(n)||[])],scope:f.repos.size?'Retained source history':'No retained source occurrence'};}));
await table('tablet',sorted(m.tablets).map(n=>{const t=m.tablets.get(n);return {n,git_blob:t.git_blob,lines:t.lines,families:[...t.families],sources:[...t.sources]};}));
await table('source',sorted(m.sources).map(n=>{const s=m.sources.get(n);return {n,repo:s.repo,commit:s.commit_sha,path:s.path,tablet:s.tablet};}));
await table('block',Object.keys(m.groups).sort().map(n=>({n,families:m.groups[n]})));
await table('repository',sorted(m.repos).map(n=>({n,families:[...m.repos.get(n).families],sources:[...m.repos.get(n).sources]})));
const manifest={schema:'stars-universe-normalized/1',observed_utc:new Date().toISOString(),source_commit:commit,database_sha256:m.database_sha256,counts:{lines:m.lines.size,families:m.families.size,tablets:m.tablets.size,sources:m.sources.size,blocks:Object.keys(m.groups).length,repositories:m.repos.size},scope:'All retained database keys and occurrences; name-match candidates are not verified run  … [line shortened here: 528 characters; full line on GitHub]
const content=Buffer.from(JSON.stringify(manifest));if(content.length>=600000)throw Error('Manifest too large');if(bytesTotal+content.length>=200000000)throw Error('Universe exceeds 200 MB');await fs.writeFile(path.join(out,'manifest.json'),content,{flag:'wx'});
console.log(JSON.stringify({observed_utc:manifest.observed_utc,counts:manifest.counts,bytes:bytesTotal+content.length,files:files.length+relations.length+1,max_file_bytes:Math.max(maxBytes,content.length),source_commit:commit,database_sha256:m.database_sha256}));

Universe Model

A JavaScript module in the modular star folder of Stars that uses SHA-256. It reads universe (`readUniverse`).

ingeststars / modular-star/universe-model.mjs · lines 1–54 of 54 · Not reached from any entry point (candidate for review) · pattern unpack (shared by 7 files)

What it does
It loads data. Defines add, digest, unpack, readUniverse. Uses libraries node:sqlite, node:crypto, node:fs. Side effects: reads or writes files.
Downstream impact
Used directly by 1 file: Universe Compact (stars).
What it achieves
Defines `add`, `digest`, `unpack` and 1 more.
Why it matters
Imported by Universe Compact.
Application
stars · modular-star · JavaScript module
Uses
node:sqlite, node:crypto, node:fs
Used by
imported by Universe Compact (import)
Produces
digest, unpack, readUniverse
Defines here
add, digest, unpack, readUniverse
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/universe-model.mjs:1-54 · blob d143e4e998b1a2f0f7daa0547b59cdf9e6b13321 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: unreached_review
import { DatabaseSync } from 'node:sqlite';
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
const add = (map, key, value) => { if (!map.has(key)) map.set(key, new Set()); map.get(key).add(value); };
export const digest = value => createHash('sha256').update(value).digest('hex');
export const unpack = bytes => { const b=Buffer.from(bytes); if(b.length%4)throw Error('Malformed numbered tablet'); const out=[];for(let i=0;i<b.length;i+=4)out.push(b.readUInt32LE(i));return out; };
export function readUniverse(dbPath, groups, codeIndex) {
  const databaseBytes=readFileSync(dbPath); // Missing input must fail before SQLite can create a file.
  const db=new DatabaseSync(dbPath,{readOnly:true});
  try {
    const integrity=db.prepare('PRAGMA quick_check').get();
    if(Object.values(integrity)[0]!=='ok')throw Error('Numbered database integrity check failed');
    const lines=new Map(),tablets=new Map(),families=new Map(),sources=new Map(),repos=new Map(),lineFamilies=new Map(),lineTablets=new Map(),memberships=new Map();
    for(const l of db.prepare('SELECT n,sha,text FROM line').iterate()) {
      const bytes=Buffer.from(l.text),sha=Buffer.from(l.sha).toString('hex');
      if(digest(bytes)!==sha)throw Error('Line content does not match permanent key digest: '+l.n);
      lines.set(l.n,{n:l.n,sha,text:bytes.toString('utf8'),base64:bytes.toString('base64'),families:new Set(),tablets:new Set()});
    }
    if(lines.size!==codeIndex.lines)throw Error(`Database and code export line counts differ: ${lines.size}/${codeIndex.lines}`);
    for(const t of db.prepare('SELECT n,git_blob,lang,lines,issue FROM tablet').iterate()) {
      const keys=unpack(t.lines);
      for(const n of keys) {if(!lines.has(n))throw Error('Tablet references absent permanent line '+n);add(lineTablets,n,t.n);}
      tablets.set(t.n,{n:t.n,git_blob:t.git_blob,lang:t.lang,issue:t.issue,lines:keys,families:new Set(),sources:new Set()});
    }
    for(const f of db.prepare('SELECT n,lang FROM family').iterate())families.set(f.n,{n:f.n,lang:f.lang,names:new Set(),needs:new Set(),lines:new Set(),tablets:new Set(),sources:new Set(),repos:new Set(),uses:new Map(),usedBy:new Map()});
    for(const s of db.prepare('SELECT * FROM scan').iterate())repos.set(s.repo,{...s,sources:new Set(),families:new Set()});
    for(const o of db.prepare('SELECT repo,commit_sha,path,tablet,seen_utc FROM occurrence ORDER BY repo,commit_sha,path').iterate()) {
      if(!tablets.has(o.tablet)||!/^[a-f0-9]{40}$/.test(o.commit_sha))throw Error('Unresolved or unpinned source occurrence');
      const key=digest(JSON.stringify([o.repo,o.commit_sha,o.path]));
      const source={...o,key,families:new Set()};sources.set(key,source);tablets.get(o.tablet).sources.add(key);
      if(!repos.has(o.repo))repos.set(o.repo,{repo:o.repo,issue:'No current scan record',sources:new Set(),families:new Set()});
      repos.get(o.repo).sources.add(key);
    }
    for(const te of db.prepare('SELECT e.family,e.needs,te.tablet,te.first,te.last,te.name FROM tablet_element te JOIN element e ON e.n=te.element').iterate()) {
      const f=families.get(te.family),t=tablets.get(te.tablet);
      if(!f||!t||te.first<1||te.last<te.first||te.last>t.lines.length)throw Error('Unresolved family occurrence');
      if(te.name)f.names.add(te.name);
      if(te.needs)for(const n of JSON.parse(te.needs))f.needs.add(n);
      f.tablets.add(t.n);t.families.add(f.n);
      for(const n of t.lines.slice(te.first-1,te.last)){f.lines.add(n);add(lineFamilies,n,f.n);}
    }
    for(const t of tablets.values())for(const sourceKey of t.sources){const s=sources.get(sourceKey);for(const n of t.families){s.families.add(n);const f=families.get(n);f.sources.add(sourceKey);f.repos.add(s.repo);repos.get(s.repo).families.add(n);}}
    for(const [sym,keys]of Object.entries(groups)){if(!Array.isArray(keys))throw Error('Invalid group');for(const n of keys){if(!families.has(n))throw Error('Group references absent family '+n);add(memberships,n,sym);}}
    // All candidates are retained. These are lexical name matches, never runtime call proof.
    const definers=new Map();
    for(const f of families.values())for(const name of f.names)if(name!=='(anonymous)'&&name.length>1)add(definers,name,f.n);
    for(const f of families.values())for(const name of f.needs){
      const candidates=[...(definers.get(name)||[])].filter(n=>n!==f.n);
      const same=candidates.filter(n=>[...families.get(n).repos].some(r=>f.repos.has(r)));
      for(const n of (same.length?same:candidates)){add(f.uses,n,name);add(families.get(n).usedBy,f.n,name);}
    }
    return {database_sha256:digest(databaseBytes),lines,tablets,families,sources,repos,lineFamilies,lineTablets,memberships,groups,codeIndex};
  } finally {db.close();}
}

View

A JavaScript file in the universe viewer folder of Stars that works with choose relation (`chooseRelation`) and draws SVG graphics, using SHA-256.

Set aside from the main view: 92% of its lines are the same as sandbox/202609141552-numbered-universe/view.js (testcode), which stays. (near-copy-of, proposed by families.py). 92% of lines shared with View; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9231 to testcode@a8a215982b13d6e2f6019b40bf0bef5755719773 sandbox/202609141552-numbered-universe/view.js:1-26 b7a0778e32ff1d914fbb1bee20c64654a11cdf0d
  • sha256 f50a9779c9921fe989f9817860d4a5fdeeae93ca96d96b1e86b8aded065c6e23
  • target sha256 3e39f4c91bc80b0a421f05917093bba1415642b8d4a2541a36380cd6a2af1dda
  • group of 2 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

interactionstars / modular-star/universe-viewer/view.js · lines 1–26 of 26 · Not reached from any entry point (candidate for review) · pattern chooseRelation (shared by 2 files)

What it does
It draws its content. Defines 10 functions or classes, including el, json, record, array, go. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
Inputs & outputs
Out: SVG drawing.
What it achieves
It is built from the button step (`button`), the SVG step (`svg`) and the render step (`render`). Defines `json`, `record`, `array` and 5 more. It responds to click, keydown and hashchange events.
Why it matters
No other file in the estate was found to import it.
Application
stars · modular-star/universe-viewer · script
Uses
none found
Used by
none found
Produces
el, json, record, array, go, button, svg, render, chooseRelation, show
Defines here
el, json, record, array, go, button, svg, render, chooseRelation, show
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
stars@030ebc202d35959fecd162327892f671d1d9a0cc modular-star/universe-viewer/view.js:1-26 · blob 8d2c5b054a00d5e7eee413e3b2d76c1ec338df1c · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: unknown · users: none · canonical: duplicate_candidate
'use strict';
const el=id=>document.getElementById(id),cache=new Map();let manifest,current,entries=[],offset=0,serial=0;
const labels={family:'Family',line:'Line',block:'Block',tablet:'Source tablet',source:'Pinned source',repository:'Repository'};
const relKinds={families:'family',lines:'line',tablets:'tablet',sources:'source',uses:'family',used_by:'family',blocks:'block'};
const relLabels={families:'Recorded families',lines:'Permanent line keys',tablets:'Source tablets',sources:'Pinned source occurrences',uses:'Candidate uses',used_by:'Candidate used by',blocks:'Block memberships'};
async function json(file){if(cache.has(file))return cache.get(file);const r=await fetch('data/'+file);if(!r.ok)throw Error('Missing snapshot input: '+file+' (HTTP '+r.status+')');const value=await r.json();cache.set(file,value);if(cache.size>10)cache.delete(cache.keys().next().value);return value;}
async function record(kind,key){const list=manifest.indexes[kind];if(!list)throw Error('Unknown record type');key=['line','family','tablet'].includes(kind)?Number(key):String(key);const part=list.find(p=>key>=p.first&&key<=p.last);if(!part)throw Error('Permanent key not present in this snapshot');const r=(await json(part.path)).find(r=>r.n===key);if(!r)throw Error('Indexed key missing');return r;}
async function array(value){if(Array.isArray(value))return value;if(value?.parts){const result=[];for(const p of value.parts)result.push(...await json(p));if(result.length!==value.count)throw Error('Relation count mismatch');return result;}throw Error('Missing relation input');}
function go(kind,key){location.hash=new URLSearchParams({kind,key}).toString();}
function button(text,action){const b=document.createElement('button');b.textContent=text;b.addEventListener('click',action);return b;}
function svg(tag,attrs,text){const n=document.createElementNS('http://www.w3.org/2000/svg',tag);for(const[k,v]of Object.entries(attrs))n.setAttribute(k,v);if(text)n.textContent=text;return n;}
function render(){const subset=entries.slice(offset,offset+12);el('items').replaceChildren();el('graph').replaceChildren();const graph=el('graph');const center=svg('g',{});center.append(svg('rect',{x:370,y:185,width:260,height:60,rx:6}),svg('text',{x:385,y:220},(el('title').textContent||'Records').slice(0,30)));graph.append(center);
 subset.forEach((item,i)=>{const x=i<6?10:750,y=10+(i%6)*70;graph.prepend(svg('line',{x1:500,y1:215,x2:x+115,y2:y+25}));const group=svg('g',{tabindex:0,role:'button','aria-label':item.label});group.append(svg('rect',{x,y,width:240,height:50,rx:5}),svg('text',{x:x+8,y:y+29},item.label.slice(0,31)));const open=()=>go(item.kind,item.key);group.addEventListener('click',open);group.addEventListener('ke  … [line shortened here: 541 characters; full line on GitHub]
 el('position').textContent=`${entries.length?offset+1:0}–${Math.min(offset+12,entries.length)} of ${entries.length} relationships`;el('previous').disabled=offset===0;el('next').disabled=offset+12>=entries.length;
}
async function chooseRelation(){const field=el('relation').value;entries=field?(await array(current.record[field])).map(key=>({kind:relKinds[field],key,label:`${labels[relKinds[field]]} ${key}`})):[];offset=0;render();}
async function show(){const own=++serial;try{const p=new URLSearchParams(location.hash.slice(1)),kind=p.get('kind')||'block',key=p.get('key');el('kind').value=kind;el('detail').replaceChildren();el('code').hidden=true;el('relation').replaceChildren();
 if(key===null){el('title').textContent='Browse '+labels[kind].toLowerCase()+' records';entries=[];for(const part of manifest.indexes[kind]){for(const row of await json(part.path))entries.push({kind,key:row.n,label:`${labels[kind]} ${row.n}${row.names?.length?' '+row.names[0]:''}`});}if(own!==serial)return;current=null;offset=0;render();return;}
 const r=await record(kind,key);if(own!==serial)return;current={kind,record:r};el('key').value=key;el('title').textContent=`${labels[kind]} ${r.n}${r.names?.length?' · '+r.names.join(' / '):''}`;
 if(r.scope){const p=document.createElement('p');p.textContent=r.scope;el('detail').append(p);}
 if(kind==='line'){const bytes=Uint8Array.from(atob(r.base64),c=>c.charCodeAt(0));const hash=[...new Uint8Array(await crypto.subtle.digest('SHA-256',bytes))].map(x=>x.toString(16).padStart(2,'0')).join('');if(hash!==r.sha256)throw Error('Line checksum mismatch');el('code').textContent=new TextDecoder().decode(bytes);el('code').hidden=false;el('detail').textContent=`Exact stored bytes verified: SHA  … [line shortened here: 415 characters; full line on GitHub]
 if(kind==='source'){const a=document.createElement('a');a.href='https://github.com/'+r.repo+'/blob/'+r.commit+'/'+r.path.split('/').map(encodeURIComponent).join('/');a.textContent='Open file at recorded commit '+r.commit;a.target='_blank';a.rel='noopener';el('detail').append(a);r.tablets=[r.tablet];}
 for(const field of Object.keys(relKinds))if(r[field]){const count=Array.isArray(r[field])?r[field].length:r[field].count;const o=document.createElement('option');o.value=field;o.textContent=`${relLabels[field]} (${count})`;el('relation').append(o);}await chooseRelation();
 }catch(e){el('title').textContent='Record unavailable';el('detail').textContent=e.message;entries=[];render();}}
el('back').onclick=()=>history.back();el('home').onclick=()=>{location.hash='kind=block';};el('open').onclick=()=>go(el('kind').value,el('key').value);el('browse').onclick=()=>{location.hash='kind='+el('kind').value;};el('relation').onchange=()=>chooseRelation().catch(e=>{el('detail').textContent=e.message;});el('previous').onclick=()=>{offset=Math.max(0,offset-12);render();};el('next').onclick=()  … [line shortened here: 461 characters; full line on GitHub]
(async()=>{manifest=await json('manifest.json');el('status').textContent=`${manifest.counts.lines} permanent line keys · ${manifest.counts.families} retained family keys · ${manifest.counts.repositories} repositories\nSnapshot ${manifest.observed_utc} · source ${manifest.source_commit}\nHistorical keys are retained; no supersession mapping is inferred.`;await show();})().catch(e=>{el('status').tex  … [line shortened here: 447 characters; full line on GitHub]