GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / galaxies-wafers / iterations/32-spider-and-galaxy

Iterations — 32 Spider and Galaxy and 1 more file

A JavaScript module in Galaxies Wafers that draws blocks, families, receivers and provenance, using SHA-256, and uses data from the stars and GridAtlas repositories. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/32-spider-and-galaxy/.

634 lines of JavaScript from galaxies-wafers, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1206 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. Iterations — 32 Spider and Galaxy render · galaxies-wafers / iterations/32-spider-and-galaxy/app.mjs lines 366–868
  2. Bridge ingest · galaxies-wafers / iterations/32-spider-and-galaxy/bridge.mjs lines 1–131

Iterations — 32 Spider and Galaxy

A JavaScript module in Galaxies Wafers that draws blocks, families, receivers and provenance, using SHA-256, and uses data from the stars and GridAtlas repositories. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/32-spider-and-galaxy/.

rendergalaxies-wafers / iterations/32-spider-and-galaxy/app.mjs · lines 366–868 of 868 (continued from section 1205) · Entry point · pattern applyLink (shared by 2 files)

What it does
It draws blocks, families, receivers and provenance. Defines 58 functions or classes, including $, FetchQueue, fetchAs, getJSON, layerDoc. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'spider'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
Inputs & outputs
In: data source: stars data; data source: gridatlas data; JSON file blocks.json; JSON file families.json; JSON file current.json; JSON file receivers.json; JSON file provenance.json; JSON file all-lines.meta.json.
Downstream impact
Used directly by 1 file: Iterations — 32 Spider and Galaxy Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/32-spider-and-galaxy/). Reached from 89 other entry points, including Iterations — 47 Federation Honesty Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/47-federation-honesty/); GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/32-spider-and-galaxy/.
What it achieves
It fetches queue (`FetchQueue`), fetches as (`fetchAs`) and gets JSON (`getJSON`). Spider and Galaxy — one universe, two views. It responds to click, change and toggle events.
Why it matters
Loaded by the page of the same name at https://ventusltd.github.io/galaxies-wafers/iterations/32-spider-and-galaxy/.
Application
galaxies-wafers · iterations/32-spider-and-galaxy · JavaScript module
Uses
Bridge (import), Spider Pane (import), Wafer Pane (import), Link (import), Atlas Join (import), Unknown Paths (import), Galaxies Wafers — Lib (import), GridAtlas — Atlas Page (estate URL), and 1 more
Used by
loaded by Iterations — 32 Spider and Galaxy Page (script src)
Produces
SHA, NEWER_DATA
Defines here
applyLink, fileKey, fetchFresh, atlasConfig, readAtlasFiles, nodeJoin, atlasRow, atlasDdHtml, loadAllGraphs, openAtlasDrawer, runAtlasDrawer, renderAtlasDrawer, openNode, sha256hex, readBuckets, linesHeader, openUnknownDrawer, runUnknownDrawer, pinned, unknownCounts, distinct, renderUnknownDrawer, after, tab, src_n, writeTest, testAtlasLine, testUnknownLine, nameMatch, writeQuestions
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/32-spider-and-galaxy/app.mjs:366-868 · blob cd50e784f880a79cc23a54aa210d0246c1d5a17e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: agent_infra · users: ai_agent · canonical: unknown
  }
  const fams = famList.slice(0, 6).map(f => f.n + ' ' + f.name + (f.block ? ' / block ' + f.block : '')).join('; ') + (famList.length > 6 ? ` and ${famList.length - 6} more` : '');
  return { list: byIndex(list), why: `${k.kind === 'line' ? 'line ' + k.line + ' is carried by famil' + (famList.length > 1 ? 'ies ' : 'y ') : 'family '}${fams}, and no node names ${famList.length > 1 ? 'those families or their blocks' : 'that family or its block'}` };
}

async function applyLink() {
  const L = st.link;
  if (!L || !L.asked.length) return;
  const g = st.manifest.graphs.find(x => x.id === st.current), s = st.graphs.get(st.current);
  const asked = esc(L.asked.join(' · '));
  if (s?.status !== 'OK') { linkBox(`<p class="refuse">Not in the spider yet: ${esc(g.title)} is ${esc(s?.status || 'not loaded')}, so the link's ${asked} cannot be looked for.</p>`); return; }
  if (!st.reg) { linkBox(`<p class="refuse">Not in the spider yet: the block register did not load, so the link's ${asked} cannot be looked for.</p>`); return; }
  const tries = [];
  if (L.node != null) tries.push(['node', 'node=' + L.node]);
  if (L.key) tries.push(['key', 'key=' + L.key.raw]);
  if (L.repo) tries.push(['repo', 'repo=' + L.repo + (L.path ? ' path=' + L.path : '')]);
  const misses = [];
  for (const [kind, label] of tries) {
    const r = await linkMatches(kind);
    if (!r.list.length) { misses.push(`${esc(label)}: ${esc(r.why)}`); continue; }
    const [i] = r.list[0];
    try { await tapSpider(i, true); } catch (e) { misses.push(`${esc(label)}: the tap failed: ${esc(e.message)}`); continue; }
    if (r.list.length > 1) spider.highlight(r.list);
    st.linkSelected = { by: label, nodes: r.list.map(([j]) => String(s.graph.nodes[j].id)) };
    linkBox(`<p class="known">Opened by the link at ${esc(s.graph.nodes[i].label)} in ${esc(g.title)}: ${esc(label)} ${esc(r.list[0][1])}.${r.list.length > 1 ? ` ${fmt(r.list.length)} nodes match; all are ringed on the spider: ${r.list.slice(0, 8).map(([j]) => esc(s.graph.nodes[j].label)).join(', ')}${r.list.length > 8 ? ' …' : ''}.` : ''}</p>`
      + (misses.length ? `<p class="dim">Tried first: ${misses.join('; ')}.</p>` : ''));
    return;
  }
  st.linkSelected = { by: null, nodes: [] };
  spider.highlight([]);
  linkBox(`<p class="refuse">Not in the spider yet: no node of ${esc(g.title)} (${fmt(s.graph.nodes.length)} nodes read) matches the link's ${asked}.</p><ul>${misses.map(m => `<li class="dim">${m}</li>`).join('')}</ul>`);
  say(`<h2>${asked}</h2><p class="refuse">Not in the spider yet: ${misses.join('; ')}.</p><p class="dim">Choose another graph, or tap a node.</p>`);
}

/* ── the named-functions toggle ────────────────────────────────────────────── */
let blocksOn = false;
$('wakeBlocks').addEventListener('click', async () => {
  const tag = $('wakeBlocksTag');
  if (blocksOn) { blocksOn = false; wafer.unwakeAll(id => id !== 'blocks'); tag.textContent = '[WAIT]'; return; }
  const B = st.layerById.get('blocks');
  if (!B) { tag.textContent = '[FAIL]'; return; }
  tag.textContent = '[LOAD]';
  try {
    const d = await layerDoc(B.file);
    const feats = d.features.filter(f => f.geometry?.type === 'Point');
    if (!feats.length) { tag.textContent = '[EMPTY]'; return; }
    wafer.wake('blocks', B.colour, feats.map(f => f.geometry.key), feats.map(f => ({ block: f.properties.block, function: f.properties.function, family: f.properties.family, via: 'layer blocks' })));
    blocksOn = true; tag.textContent = `[OK ${fmt(feats.length)}]`;
  } catch (e) { tag.textContent = '[FAIL]'; say(`<p class="refuse">layers/blocks.json: ${esc(e.message)}</p>`); }
});
$('clearWake').addEventListener('click', () => { blocksOn = false; $('wakeBlocksTag').textContent = '[WAIT]'; wafer.unwakeAll(); spider.highlight([]); });

$('findNode').addEventListener('change', e => {
  const s = st.graphs.get(st.current); const q = e.target.value.trim().toLowerCase();
  if (!s?.graph || !q) return;
  const i = s.graph.nodes.findIndex(n => n.label.toLowerCase() === q) >= 0 ? s.graph.nodes.findIndex(n => n.label.toLowerCase() === q) : s.graph.nodes.findIndex(n => n.label.toLowerCase().includes(q));
  if (i < 0) { say(`<p class="refuse">No node of this graph has a label containing "${esc(e.target.value)}".</p>`); return; }
  tapSpider(i);
});

/* ── shared keys with Grid Atlas (atlas-join.mjs) ─────────────────────────────
   Fetched only when a node with a Grid Atlas file link is tapped, or when the
   reader opens the drawer. A file's text is held only while its line ranges
   are read; what is kept is the ids it declares. */
const ATLAS_LIVE = 'https://ventusltd.github.io/gridatlas/atlas/';
const fileIds = new Map();      /* raw + '#' + lines -> {ids: Map id -> Set(form)} | {error} */
const fileRead = new Map();     /* raw -> promise while in flight */
const fileKey = f => f.raw + '#' + (f.lines ? f.lines.join('-') : '');

function fetchFresh(url, kind) {   /* the same queue and timeout, no cache: the caller keeps what it needs */
  return queue.add(async () => {
    const ctl = new AbortController(), t = setTimeout(() => ctl.abort(), 15000);
    try {
      const r = await fetch(url, { signal: ctl.signal, cache: 'default' });
      if (!r.ok) { const e = new Error('HTTP ' + r.status); e.status = r.status; throw e; }
      return kind === 'text' ? await r.text() : kind === 'json' ? await r.json() : await r.arrayBuffer();
    } catch (e) { if (e.name === 'AbortError') throw new Error('no answer within 15 s'); throw e; }
    finally { clearTimeout(t); }
  });
}

async function atlasConfig() {
  if (!st.atlasCfgP) {
    st.atlasCfgP = (async () => {
      const cur = await getJSON(ATLAS_LIVE + 'current.json');
      const url = new URL(cur.shell.index, ATLAS_LIVE).href;
      const html = await fetchFresh(url, 'text');
      const ids = configLayerIds(html);
      const labels = new Map([...html.matchAll(/\{\s*id:\s*"([^"]+)"\s*,\s*label:\s*"([^"]*)"/g)].map(m => [m[1], m[2]]));
      const receivers = await getJSON(CDN + 'deeplink/receivers.json');
      return { ids: new Set(ids), order: ids, labels, url, release: cur.shell.release_id, generation: cur.generation, receivers };
    })();
    st.atlasCfgP.catch(() => { st.atlasCfgP = null; });
  }
  return st.atlasCfgP;
}

/* Read every file these descriptors name, once per file, all line ranges of it together. */
async function readAtlasFiles(files, onDone) {
  const byRaw = new Map();
  for (const f of files) { const have = fileIds.get(fileKey(f)); if (have && !have.error) continue; if (!byRaw.has(f.raw)) byRaw.set(f.raw, []); byRaw.get(f.raw).push(f); }
  await Promise.all([...byRaw].map(async ([raw, fs]) => {
    if (!fileRead.has(raw)) {
      fileRead.set(raw, (async () => {
        let text = null, error = null;
        try { text = await fetchFresh(raw, 'text'); } catch (e) { error = e.status ? 'HTTP ' + e.status : e.message; }
        return { text, error };
      })());
    }
    const got = await fileRead.get(raw);
    for (const f of fs) fileIds.set(fileKey(f), got.error ? { error: got.error } : { ids: declaredLayerIds(got.text, f.lines) });
    fileRead.delete(raw);  /* the text goes with the promise; only the ids stay */
    onDone?.();
  }));
}

async function nodeJoin(n) {
  const urls = atlasUrls(n), files = urls.map(atlasFile).filter(Boolean);
  const out = { urls, files, ids: new Map(), inCfg: [], errors: [] };
  if (!files.length) return out;
  const [cfg] = await Promise.all([atlasConfig(), readAtlasFiles(files)]);
  for (const f of files) {
    const r = fileIds.get(fileKey(f));
    if (r.error) { out.errors.push(`${f.path}: ${r.error}`); continue; }
    for (const [id, forms] of r.ids) {
      if (!out.ids.has(id)) out.ids.set(id, { forms: new Set(), files: new Set() });
      forms.forEach(x => out.ids.get(id).forms.add(x)); out.ids.get(id).files.add(f);
    }
  }
  out.inCfg = [...out.ids.keys()].filter(id => cfg.ids.has(id));
  out.cfg = cfg;
  return out;
}

function atlasRow(n, seq) {
  st.atlasDd = null;
  const urls = atlasUrls(n);
  if (!urls.length) return '';
  const files = urls.map(atlasFile).filter(Boolean);
  if (!files.length) return `<dt>Atlas layer ids</dt><dd><span class="refuse">EMPTY</span> <span class="dim">· ${fmt(urls.length)} link(s) name Grid Atlas, but none names a cartridge, cartridge part, composition manifest or config file, so no layer id is declared to read</span></dd>`;
  nodeJoin(n).then(r => { if (seq === tapSeq) { st.atlasDd = atlasDdHtml(r); say($('sayBody').innerHTML); } })
    .catch(e => { if (seq === tapSeq) { st.atlasDd = `<span class="refuse">FAIL</span> ${esc(e.message)}`; say($('sayBody').innerHTML); } });
  return `<dt>Atlas layer ids</dt><dd id="atlasIds"><span class="dim">LOAD · reading ${fmt(new Set(files.map(f => f.raw)).size)} Grid Atlas file(s) this node links…</span></dd>`;
}

function atlasDdHtml(r) {
  const cfg = r.cfg, c = st.contract;
  const method = [...new Set(r.files.map(f => f.kind))].join(', ');
  const src = r.files.map(f => `${esc(f.path)}${f.lines ? ' lines ' + f.lines.join('-') : ''} <span class="dim">(${f.pinned ? 'pinned @' + esc(f.ref.slice(0, 7)) : f.ref ? 'ref ' + esc(f.ref) + ', not pinned' : 'served page, not pinned'})</span>`).join('; ');
  const errs = r.errors.length ? `<br><span class="refuse">FAIL ${r.errors.map(esc).join('; ')}</span>` : '';
  const other = [...r.ids.keys()].filter(id => !cfg.ids.has(id));
  if (!r.inCfg.length) return `<span class="refuse">EMPTY</span> <span class="dim">· declared in the ${esc(method)} file: no Grid Atlas v9 config layer id${other.length ? ` (it declares ${fmt(other.length)} id(s) of its own that the config does not: ${other.slice(0, 8).map(esc).join(', ')})` : ''}. Read: ${src}</span>${errs}`;
  const rl = c ? receiverLink(c, cfg.receivers) : null;
  const list = r.inCfg.map(id => {
    const d = r.ids.get(id), b = c ? bucketsForLayer(c, id) : [];
    return `<li><b>${esc(id)}</b> ${esc(cfg.labels.get(id) || '')} <span class="dim">· ${[...d.forms].map(esc).join('; ')}${b.length ? ' · contract buckets resolving to it: ' + b.map(esc).join(', ') : ''}</span></li>`;
  }).join('');
  return `<span class="known">${fmt(r.inCfg.length)} Grid Atlas layer id(s)</span> <span class="dim">· join method: declared in the ${esc(method)} file, matched to the ${esc(cfg.release)} config</span><ul>${list}</ul>`
    + (other.length ? `<p class="dim">Also declared, not config layers: ${other.slice(0, 12).map(esc).join(', ')}${other.length > 12 ? ' …' : ''}</p>` : '')
    + (rl ? `<p><a class="mapbtn" href="${esc(rl.href)}" target="_blank" rel="noopener">MAP</a> <span class="dim">opens the canonical receiver ${esc(rl.href)} (deeplink/receivers.json${rl.agrees ? ', agrees with contract.js CANONICAL_RECEIVER' : ', <span class="refuse">differs from contract.js</span>'}). No layer parameter: ${esc(rl.why)}.</span></p>` : '<p class="dim">The deep-link contract has n  … [line shortened here: 443 characters; full line on GitHub]
    + `<p class="dim">Read: ${src}</p>${errs}`;
}

/* Every graph of the manifest, through the queue, each row relabelled as it lands. */
async function loadAllGraphs(onEach) {
  await Promise.all(st.manifest.graphs.map(g => loadGraph(g.id).then(s => { onEach?.(); return s; })));
}

let atlasRun = null;
function openAtlasDrawer() {
  if (atlasRun) return;
  atlasRun = runAtlasDrawer().catch(e => { $('aStatus').innerHTML = `<span class="refuse">FAIL</span> ${esc(e.message)}`; atlasRun = null; });
}
async function runAtlasDrawer() {
  const status = $('aStatus');
  let g = 0; const G = st.manifest.graphs.length;
  status.textContent = `LOAD · spider graphs 0/${G}`;
  await loadAllGraphs(() => { status.textContent = `LOAD · spider graphs ${++g}/${G}`; });
  const cfg = await atlasConfig();
  const nodes = [];
  for (const gr of st.manifest.graphs) {
    const s = st.graphs.get(gr.id); if (s?.status !== 'OK') continue;
    s.graph.nodes.forEach((n, i) => { const urls = atlasUrls(n); if (urls.length) nodes.push({ g: gr.id, i, n, urls, files: urls.map(atlasFile).filter(Boolean) }); });
  }
  const all = nodes.flatMap(x => x.files), raws = new Set(all.map(f => f.raw));
  let done = 0;
  status.textContent = `LOAD · Grid Atlas files 0/${raws.size}`;
  await readAtlasFiles(all, () => { status.textContent = `LOAD · Grid Atlas files ${++done}/${raws.size}`; });
  const A = { nodes: nodes.length, urls: new Set(nodes.flatMap(x => x.urls)).size, withFile: 0, joined: [], noFile: 0, noDecl: 0, failed: 0, reached: new Map(), files: raws.size, pinnedFiles: new Set(all.filter(f => f.pinned).map(f => f.raw)).size, cfg };
  for (const x of nodes) {
    if (!x.files.length) { A.noFile++; continue; }
    A.withFile++;
    const r = await nodeJoin(x.n);
    if (r.inCfg.length) { A.joined.push({ ...x, ids: r.inCfg }); r.inCfg.forEach(id => A.reached.set(id, (A.reached.get(id) || 0) + 1)); }
    else if (r.errors.length === x.files.length) A.failed++;
    else A.noDecl++;
  }
  st.atlasSummary = A;
  status.innerHTML = `<span class="known">OK</span> <span class="dim">· ${fmt(A.files)} files read (${fmt(A.pinnedFiles)} pinned by commit)</span>`;
  renderAtlasDrawer(0);
  writeTest(); writeQuestions();
}
function renderAtlasDrawer(page) {
  const A = st.atlasSummary, PER = 12;
  const ids = [...A.reached].sort((a, b) => b[1] - a[1]);
  const rows = A.joined.slice(page * PER, page * PER + PER).map((x, k) => `<li><button type="button" class="rowbtn" data-k="${page * PER + k}">${esc(x.g)} · ${esc(x.n.label.slice(0, 60))}</button> <span class="dim">${x.ids.map(esc).join(', ')}</span></li>`).join('');
  $('aBody').innerHTML = `<p><b>${fmt(A.joined.length)}</b> spider nodes joined · <b>${fmt(A.reached.size)}</b> Grid Atlas layer ids reached · <b>${fmt(A.nodes - A.joined.length)}</b> nodes with a Grid Atlas URL but no declared config layer (${fmt(A.noFile)} link no cartridge, part, manifest or config file; ${fmt(A.noDecl)} link one that declares none; ${fmt(A.failed)} whose files failed to load).  … [line shortened here: 473 characters; full line on GitHub]
    <p class="dim">Join method: declared in the cartridge file. A layer id counts when the file a node links (a cartridge, cartridge part, composition manifest or config file, read as served, over the linked lines when the link names them) declares it as a ukConfig entry, a LAYER_ID / LAYER_IDS / LAYERS constant, a data-layer-id attribute or an engine layer name 'l-&lt;id&gt;', and the Grid Atlas   … [line shortened here: 521 characters; full line on GitHub]
    <p>Reached: ${ids.map(([id, k]) => `<b>${esc(id)}</b> ${esc(A.cfg.labels.get(id) || '')} (${fmt(k)} nodes)`).join(' · ') || 'none'}</p>
    ${st.contract ? `<p class="dim">Deep link: ${esc(receiverLink(st.contract, A.cfg.receivers).why)}.</p>` : ''}
    <ul class="pagelist">${rows}</ul>
    <p class="pager">${page > 0 ? `<button type="button" data-p="${page - 1}">previous</button>` : ''} <span class="dim">${fmt(page * PER + 1)}–${fmt(Math.min(A.joined.length, page * PER + PER))} of ${fmt(A.joined.length)}</span> ${page * PER + PER < A.joined.length ? `<button type="button" data-p="${page + 1}">next</button>` : ''}</p>`;
  $('aBody').querySelectorAll('[data-p]').forEach(b => b.addEventListener('click', () => renderAtlasDrawer(Number(b.dataset.p))));
  $('aBody').querySelectorAll('[data-k]').forEach(b => b.addEventListener('click', () => openNode(A.joined[Number(b.dataset.k)])));
}
async function openNode(x) {
  if (st.current !== x.g) { writeGraphChoice(x.g); linkBox(null); await showGraph(x.g); }
  tapSpider(x.i);
  $('say').scrollIntoView({ block: 'nearest', behavior: 'smooth' });
}

/* ── the unknown paths (unknown-paths.mjs) ─────────────────────────────────── */
const PACK_STARS = '15667ee5bdd5c3bb07946a6968c335e59fde6a15';  /* the stars commit whose code/index.json has the sha256 the pack's provenance records; checked below at run time */
export const NEWER_DATA = 'https://globalgrid2050.com/testcode/202609152203/data/';
const LINES_MD = 'https://ventusltd.github.io/stars/LINES.md';

async function sha256hex(buf) {
  if (!crypto?.subtle) return null;
  const h = new Uint8Array(await crypto.subtle.digest('SHA-256', buf));
  return [...h].map(b => b.toString(16).padStart(2, '0')).join('');
}

/* Read a list of code-index buckets into one index; bytes checked against a provenance sha256 when given. */
async function readBuckets(list, onEach) {
  const ix = newIndex(); const R = { ok: 0, match: 0, differ: 0, unverified: 0, failed: [] , bytes: 0 };
  const dec = new TextDecoder();
  await Promise.all(list.map(async b => {
    try {
      const buf = await fetchFresh(b.url, 'bin');
      R.bytes += buf.byteLength;
      if (b.sha256) { const h = await sha256hex(buf); if (h === null) R.unverified++; else if (h === b.sha256) R.match++; else R.differ++; }
      addBucket(ix, JSON.parse(dec.decode(buf)));
      R.ok++;
    } catch (e) { R.failed.push(b.url.split('/').pop() + ': ' + (e.status ? 'HTTP ' + e.status : e.message)); }
    onEach?.();
  }));
  return { ix, R };
}

/* The first lines of LINES.md, streamed and then cancelled: its header names its generation. */
async function linesHeader() {
  return queue.add(async () => {
    const ctl = new AbortController(), t = setTimeout(() => ctl.abort(), 15000);
    try {
      const r = await fetch(LINES_MD, { signal: ctl.signal, cache: 'no-store' });
      if (!r.ok) throw new Error('HTTP ' + r.status);
      const total = Number(r.headers.get('content-length')) || null;
      const reader = r.body.getReader(); const dec = new TextDecoder(); let text = '', bytes = 0;
      while (text.length < 4000 && !/```text/.test(text)) { const { value, done } = await reader.read(); if (done) break; bytes += value.byteLength; text += dec.decode(value, { stream: true }); }
      reader.cancel().catch(() => {});
      const line = (text.split('\n').find(l => /unique lines/.test(l)) || '').trim();
      return { line, bytes, total };
    } finally { clearTimeout(t); }
  });
}

let unknownRun = null;
function openUnknownDrawer() {
  if (unknownRun) return;
  unknownRun = runUnknownDrawer().catch(e => { $('uStatus').innerHTML = `<span class="refuse">FAIL</span> ${esc(e.message)}`; unknownRun = null; });
}
async function runUnknownDrawer() {
  const status = $('uStatus');
  let g = 0; const G = st.manifest.graphs.length;
  status.textContent = `LOAD · spider graphs 0/${G}`;
  await loadAllGraphs(() => { status.textContent = `LOAD · spider graphs ${++g}/${G}`; });
  if (!st.reg) throw new Error('the block register did not load, so no path can be called unknown');
  const items = [];
  for (const gr of st.manifest.graphs) {
    const s = st.graphs.get(gr.id); if (s?.status !== 'OK') continue;
    s.graph.nodes.forEach((n, i) => {
      const ref = nodeRefs(gr.id, n); if (ref.kind !== 'path') return;
      if (counterpart(ref, st.reg, null).state !== 'unknown') return;
      items.push({ g: gr.id, i, n, repo: ref.repo, path: ref.path, shape: shapeOf(n, ref) });
    });
  }
  /* the pack this page draws, and the code-index generation it was built from */
  const prov = await getJSON(DATA + 'provenance.json');
  const src = prov.sources.filter(x => /\/stars\/code\/f\/\d+\.json$/.test(x.url));
  const idxSrc = prov.sources.find(x => /\/stars\/code\/index\.json$/.test(x.url));
  const pinned = url => url.replace('https://ventusltd.github.io/stars/', `https://raw.githubusercontent.com/Ventusltd/stars/${PACK_STARS}/`);
  const idxHash = await sha256hex(await fetchFresh(pinned(idxSrc.url), 'bin'));
  let k = 0;
  status.textContent = `LOAD · pack code-index buckets 0/${src.length}`;
  const old = await readBuckets(src.map(x => ({ url: pinned(x.url), sha256: x.sha256 })), () => { status.textContent = `LOAD · pack code-index buckets ${++k}/${src.length}`; });
  for (const it of items) Object.assign(it, classify(it, old.ix));
  const U = { items, old, prov, idxOk: idxHash === idxSrc.sha256, idxHash, bySrc: null };
  /* class 3, and class 2, against the newer source */
  const later = items.filter(it => it.cls === 3 || it.cls === 2);
  if (later.length) {
    let newer = null;
    try {
      const meta = await fetchFresh(NEWER_DATA + 'all-lines.meta.json', 'json');
      const p2 = await fetchFresh(NEWER_DATA + 'provenance.json', 'json');
      newer = { kind: 'pack', meta, prov: p2, list: p2.sources.filter(x => /\/stars\/code\/f\/\d+\.json$/.test(x.url)).map(x => ({ url: x.url, sha256: x.sha256 })) };
    } catch (e) {
      const idx = await fetchFresh('https://ventusltd.github.io/stars/code/index.json', 'json');
      newer = { kind: 'served', why: e.message, idx, list: idx.buckets.map(b => ({ url: `https://ventusltd.github.io/stars/code/f/${b}.json` })) };
      try { newer.lines = await linesHeader(); } catch (e2) { newer.linesError = e2.message; }
    }
    let j = 0;
    status.textContent = `LOAD · newer code-index buckets 0/${newer.list.length}`;
    const nw = await readBuckets(newer.list, () => { status.textContent = `LOAD · newer code-index buckets ${++j}/${newer.list.length}`; });
    newer.read = nw;
    for (const it of later) it.now = holds(nw.ix, it.repo, it.path, it.shape) ? 'numbered after the pack was built' : 'not numbered';
    U.newer = newer;
  }
  st.unknownSummary = U;
  status.innerHTML = `<span class="known">OK</span>`;
  renderUnknownDrawer(3, 0);
  writeTest(); writeQuestions();
}
function unknownCounts(U) {
  const c = { 1: [], 2: [], 3: [], 4: [] };
  for (const it of U.items) c[it.cls].push(it);
  const distinct = list => new Set(list.map(it => it.repo + '/' + it.path)).size;
  return { c, distinct };
}
function renderUnknownDrawer(cls, page) {
  const U = st.unknownSummary, { c, distinct } = unknownCounts(U), PER = 12;
  const o = U.old, N = U.newer;
  const exts = [...o.ix.exts].sort((a, b) => b[1] - a[1]).map(([e, k]) => '.' + e + ' ' + fmt(k)).join(', ');
  const after = list => list.filter(it => it.now === 'numbered after the pack was built').length;
  let newerLine = '';
  if (N) {
    const r = N.read.R;
    newerLine = N.kind === 'pack'
      ? `Newer source: the numbered database pack ${esc(NEWER_DATA.split('/').slice(-3, -2)[0])} (built ${esc(N.prov.built_utc)}, ${fmt(N.meta.lines)} lines, max key ${fmt(N.meta.max)}), newer than the pack drawn here (built ${esc(U.prov.built_utc)}). Its provenance lists ${fmt(N.list.length)} code-index buckets; read from the served stars site, ${fmt(r.match)} match its sha256, ${fmt(r.differ)} d  … [line shortened here: 740 characters; full line on GitHub]
      : `Newer source: the newer pack did not answer (${esc(N.why)}), so the served stars code index answered (generated ${esc(N.idx.generated_utc)}, ${fmt(N.idx.families)} families), newer than the pack. ${N.lines ? `LINES.md was streamed for its header only (${fmt(N.lines.bytes)} of ${N.lines.total ? fmt(N.lines.total) : 'unknown'} bytes, then cancelled): "${esc(N.lines.line.slice(0, 160))}". It  … [line shortened here: 529 characters; full line on GitHub]
  }
  const tab = k => `<button type="button" data-c="${k}"${k === cls ? ' aria-pressed="true" class="on"' : ''}>class ${k}: ${fmt(c[k].length)}</button>`;
  const list = c[cls], rows = list.slice(page * PER, page * PER + PER).map((it, k) => `<li><button type="button" class="rowbtn" data-k="${page * PER + k}">${esc(it.g)} · ${esc(it.n.label.slice(0, 48))}</button> <span>${esc(it.repo)}${it.path ? '/' + esc(it.path) : ' (repository)'}</span> <span class="dim">· ${esc(it.shape)} · ${esc(it.why)}${it.now ? ' · now: ' : ''}</span>${it.now ? `<span class=  … [line shortened here: 497 characters; full line on GitHub]
  $('uBody').innerHTML = `<p>${fmt(U.items.length)} spider nodes name a repository or path that the live block register does not hold (${fmt(distinct(U.items))} distinct). Measured classes:</p>
    <ol class="classes">
      <li><b>${fmt(c[1].length)}</b> nodes (${fmt(distinct(c[1]))} distinct) · not code by file type. <span class="dim">${esc(CLASS_TEXT[1])}</span></li>
      <li><b>${fmt(c[2].length)}</b> nodes (${fmt(distinct(c[2]))} distinct) · code in a repository the numbered database does not scan. <span class="dim">${esc(CLASS_TEXT[2])}</span>${N ? ` <span class="dim">Of these, numbered after the pack was built (the newer source has a place there): ${fmt(after(c[2]))}.</span>` : ''}</li>
      <li><b>${fmt(c[3].length)}</b> nodes (${fmt(distinct(c[3]))} distinct) · code in a scanned repository, absent from the pack. <span class="dim">${esc(CLASS_TEXT[3])}</span>${N ? ` <span class="known">${fmt(after(c[3]))} numbered after the pack was built</span> · <span class="refuse">${fmt(c[3].length - after(c[3]))} not numbered</span>` : ''}</li>
      ${c[4].length ? `<li><b>${fmt(c[4].length)}</b> nodes (${fmt(distinct(c[4]))} distinct) · held by the pack, not by the register. <span class="dim">${esc(CLASS_TEXT[4])}</span></li>` : ''}
    </ol>
    <p class="dim">The pack: ${esc(DATA)} (built ${esc(U.prov.built_utc)}). Its provenance.json lists ${fmt(o.R.ok + o.R.failed.length)} code-index buckets by the stars site URL and sha256, not by commit; they are read at stars@${PACK_STARS.slice(0, 7)}, whose code/index.json sha256 ${U.idxOk ? 'equals' : '<span class="refuse">does not equal</span>'} the provenance record, and ${fmt(o.R.match)} of  … [line shortened here: 1,052 characters; full line on GitHub]
    ${newerLine ? `<p class="dim">${newerLine}</p>` : ''}
    <p class="tabs">${[1, 2, 3, 4].filter(k => k < 4 || c[4].length).map(tab).join(' ')}</p>
    <ul class="pagelist">${rows || '<li class="dim">EMPTY: no node in this class</li>'}</ul>
    <p class="pager">${page > 0 ? `<button type="button" data-p="${page - 1}">previous</button>` : ''} <span class="dim">${list.length ? fmt(page * PER + 1) + '–' + fmt(Math.min(list.length, page * PER + PER)) + ' of ' + fmt(list.length) : ''}</span> ${page * PER + PER < list.length ? `<button type="button" data-p="${page + 1}">next</button>` : ''}</p>`;
  $('uBody').querySelectorAll('[data-c]').forEach(b => b.addEventListener('click', () => renderUnknownDrawer(Number(b.dataset.c), 0)));
  $('uBody').querySelectorAll('[data-p]').forEach(b => b.addEventListener('click', () => renderUnknownDrawer(cls, Number(b.dataset.p))));
  $('uBody').querySelectorAll('[data-k]').forEach(b => b.addEventListener('click', () => openNode(list[Number(b.dataset.k)])));
}
const src_n = o => o.R.ok + o.R.failed.length;

/* ── the spider test, measured here ────────────────────────────────────────── */
function writeTest() {
  if (!st.manifest) return;
  const rows = st.manifest.graphs.map(g => {
    const s = st.graphs.get(g.id);
    if (!s || s.status === 'WAIT') return `<tr><td>${esc(g.id)}</td><td class="dim" colspan="5">WAIT: not fetched until chosen</td></tr>`;
    if (s.status !== 'OK') return `<tr><td>${esc(g.id)}</td><td colspan="5" class="refuse">${esc(s.status)} ${esc(s.why || '')}</td></tr>`;
    const G = s.graph;
    let known = '', atlas = 0, retired = 0, layersParam = 0;
    if (st.reg) {
      const states = G.nodes.map(n => counterpart(nodeRefs(g.id, n), st.reg, st.families).state);
      known = `${fmt(states.filter(x => x === 'known').length)} / ${fmt(G.nodes.length)}` + (states.includes('pending') ? ` (${fmt(states.filter(x => x === 'pending').length)} families uncounted)` : '');
    }
    for (const n of G.nodes) {
      const urls = [n.gh, n.ext, ...(n.reason.match(/https?:\/\/[^\s"'<>)]+/g) || [])].filter(Boolean);
      if (urls.some(u => /gridatlas|repd_grid_atlas/i.test(u))) atlas++;
      if (st.contract && urls.some(u => st.contract.isRetiredReceiver(u))) retired++;
      if (urls.some(u => /[?&]layers?=/.test(u))) layersParam++;
    }
    return `<tr><td>${esc(g.id)}</td><td>${fmt(G.nodes.length)} / ${fmt(G.edges.length)}</td><td>${fmt(G.dangling)}</td><td>${atlas} · ${retired} · ${layersParam}</td><td>${known}</td><td>${s.pinned ? '@' + SHA.slice(0, 7) : 'live'}</td></tr>`;
  }).join('');
  let regLine = 'the block register is loading';
  if (st.reg) {
    const vge = st.reg.byRepo.get('Ventusltd/ventus-grid-engine') || [];
    const spiderFiles = vge.filter(f => f.path === 'index.html' || pathCovers('spider/', f.path));
    regLine = `The live register (generated ${esc(st.reg.generated)}, ${fmt(st.reg.blocks)} blocks) records ${fmt(vge.length)} file(s) in Ventusltd/ventus-grid-engine and <b>${fmt(spiderFiles.length)}</b> at index.html or under spider/. `
      + (spiderFiles.length ? 'The claim that the register has no block for the spider is refuted.' : 'The claim that the register has no block for the spider is confirmed for this generation, so the wafer\'s spider layer stays EMPTY.');
  }
  let nameLine = '<button id="nameBtn" type="button">name-match the spider\'s own functions against the numbered families</button> <span class="dim">(loads the family index and the spider\'s index.html)</span>';
  if (st.nameMatch) nameLine = st.nameMatch;
  $('tBody').className = '';
  $('tBody').innerHTML = `<p>Each row is measured in this browser when its graph is chosen. Columns: nodes / edges, edges that name a missing node, nodes linking Grid Atlas · of those a retired receiver · nodes carrying a layer parameter, nodes with a counterpart in the numbered universe, source.</p>
    <div class="twrap"><table class="t"><tr><th>graph</th><th>nodes / edges</th><th>dangling</th><th>atlas · retired · layers=</th><th>counterpart</th><th>source</th></tr>${rows}</table></div>
    <p>${regLine}</p><p>${nameLine}</p>
    <p>${testAtlasLine()}</p><p>${testUnknownLine()}</p>
    <p class="dim">The full test, run in headless Chrome and WebKit on the live spider page, with the Grid Atlas config comparison and every URL status, is kept with this iteration's test receipts.</p>`;
  $('nameBtn')?.addEventListener('click', nameMatch);
}

function testAtlasLine() {
  const A = st.atlasSummary;
  if (!A) return '<b>Shared keys with Grid Atlas:</b> <span class="dim">WAIT · not measured until the "Shared keys with Grid Atlas" drawer is opened (it reads every Grid Atlas cartridge file the spider links).</span>';
  const rl = st.contract ? receiverLink(st.contract, A.cfg.receivers) : null;
  return `<b>Shared keys with Grid Atlas (measured here):</b> ${fmt(A.nodes)} nodes across the loaded graphs carry ${fmt(A.urls)} distinct Grid Atlas URLs; ${fmt(A.withFile)} of them link a cartridge, cartridge part, composition manifest or config file; <b>${fmt(A.joined.length)}</b> join Grid Atlas by a layer id declared in the cartridge file; <b>${fmt(A.reached.size)}</b> Atlas layer ids reached  … [line shortened here: 819 characters; full line on GitHub]
}
function testUnknownLine() {
  const U = st.unknownSummary;
  if (!U) return '<b>The unknown paths:</b> <span class="dim">WAIT · not classified until "The unknown paths" drawer is opened (it reads the code-index buckets of the pack).</span>';
  const { c } = unknownCounts(U), after = c[3].filter(it => it.now === 'numbered after the pack was built').length;
  return `<b>The unknown paths (measured here):</b> ${fmt(U.items.length)} nodes name a repository or path the live register does not hold: class 1 not code by file type <b>${fmt(c[1].length)}</b>; class 2 in a repository the pack does not scan <b>${fmt(c[2].length)}</b>; class 3 in a scanned repository, absent from the pack <b>${fmt(c[3].length)}</b>${U.newer ? ` (${fmt(after)} numbered after the  … [line shortened here: 660 characters; full line on GitHub]
}

async function nameMatch() {
  $('nameBtn').disabled = true; $('nameBtn').textContent = 'loading…';
  try {
    await ensureFamilies();
    const src = await fetchAs(CDN + 'index.html', 'text');
    const names = [...new Set([...src.matchAll(/function\s+([A-Za-z0-9_$]+)/g)].map(m => m[1]))];
    const byName = new Map();
    for (const f of st.famArr) { if (!byName.has(f.name)) byName.set(f.name, []); byName.get(f.name).push(f); }
    const hits = names.filter(nm => byName.has(nm));
    const unreg = new Set();
    const lines = hits.map(nm => {
      const fs = byName.get(nm);
      fs.forEach(f => { if (f.block && !st.reg.bySymbol.has(f.block)) unreg.add(f.block); });
      return `${esc(nm)}: ${fs.slice(0, 4).map(f => `${f.n}/${esc(f.block ?? '-')}${f.block && !st.reg.bySymbol.has(f.block) ? '<span class="refuse">*</span>' : ''}`).join(' ')}${fs.length > 4 ? ' …' : ''}`;
    });
    st.nameMatch = `<b>Name-match inference.</b> The spider's index.html at @${SHA.slice(0, 7)} declares ${fmt(names.length)} named functions; ${fmt(hits.length)} of those names are numbered families (family/block; <span class="refuse">*</span> = block absent from the live register${unreg.size ? ': ' + [...unreg].map(esc).join(', ') : ''}). A shared name is not proof the family is this file.<br>${  … [line shortened here: 421 characters; full line on GitHub]
    computeBridge(); spider.setBridge(st.bridge); measureBridge();
  } catch (e) { st.nameMatch = `<span class="refuse">name-match could not run: ${esc(e.message)}</span>`; }
  writeTest();
}

/* ── questions ─────────────────────────────────────────────────────────────── */
function writeQuestions() {
  const n = st.manifest?.graphs.length ?? 0;
  const eng = st.reg ? [...st.reg.bySymbol.values()].filter(b => b.files?.some(f => f.repo === 'Ventusltd/ventus-grid-engine' && f.path.startsWith('engine/'))) : [];
  const sld = eng.filter(b => /voltage|current|capacity|fault|power factor|rating|topology|obstacle|demand/i.test(b.title + ' ' + b.description));
  $('qBody').className = '';
  $('qBody').innerHTML = `<ol>
  <li><b>How does this help draw a system or a single-line diagram?</b> None yet, directly. The spider draws repositories, files, blocks and families as cards joined by typed edges (nodes[].label, edges[][2]); the wafer draws numbered lines. Neither draws a busbar, feeder, transformer, cable route, protection or earthing. What the pair does is find the code that could: a tap on a spider node that   … [line shortened here: 688 characters; full line on GitHub]
  <li><b>What is this code used for?</b> The spider is ventus-grid-engine index.html at @${SHA.slice(0, 7)}: loadRoot and loadContents read spider/data, wireReceiver reads spider/manifest.json and calls loadManifestScope then normaliseGenericGraph for each of its ${fmt(n)} graphs, drawSpider draws the focus. Who calls it: its own manifest's overview cards link <code>?graph=</code>; the source comm  … [line shortened here: 650 characters; full line on GitHub]
  <li><b>Where does it lead next?</b> From the spider: to the ${fmt(n)} graphs its manifest lists and to each node's GitHub and external links. From the wafer: to module layers and named functions. ${atlasQ()} To an electrical element itself: not established, because no spider node carries a busbar, feeder or cable identity, only code identities.</li>
  </ol>
  <p class="machine"><b>Machine detail.</b> Inputs: spider/manifest.json graphs[] {id, path, edges_path} and each graph's nodes {id, label, type, rag, reason, gh, ext, path} and edges ([from, to, type] index-array-v1 or {from, to, type}) at ventus-grid-engine@${SHA}; the live block register blocks[] {symbol, files[] {repo, path, commit}}; the numbered database families.json {n, name, block, lineOf  … [line shortened here: 1,445 characters; full line on GitHub]
}
function atlasQ() {
  const A = st.atlasSummary;
  if (!A) return 'To Grid Atlas: open "Shared keys with Grid Atlas" to measure which Atlas layers the linked cartridge files declare.';
  const ids = [...A.reached.keys()];
  return `To Grid Atlas: ${fmt(A.joined.length)} nodes lead to ${fmt(ids.length)} Atlas layers declared in their cartridge files (${ids.map(id => esc(id) + ' ' + esc(A.cfg.labels.get(id) || '')).join('; ')}); the MAP button opens the canonical receiver, where those layers are ticked by hand. By their config labels these are voltage line layers and the substations layer: the network a feeder or cab  … [line shortened here: 475 characters; full line on GitHub]
}

function writeRules() {
  $('rBody').className = '';
  $('rBody').innerHTML = `<ul>
  <li>One fetch queue, four requests at a time, each with a 15 s timeout; one shared promise per URL, dropped when it fails so a retry can happen.</li>
  <li>A spider graph is fetched only when chosen in the list; only its row is relabelled WAIT, LOAD, OK, EMPTY or FAIL. Preloaded: the manifest, the Federation graph (the spider's own default), the block register and the wafer's layer manifest.</li>
  <li>Spider nodes are drawn on one canvas, never as page elements; at most ${MAX_LABELS_TEXT} neighbour labels are written.</li>
  <li>The wafer ground is one GPU draw of every numbered line. A woken line is drawn only when its radius √key lies in the band of radii the pane can see, and at most ${fmt(MAX_DRAWN)} woken lines are drawn in one frame.</li>
  <li>Shared keys with Grid Atlas: a node's linked cartridge files are read when that node is tapped; every file the spider links is read only when that drawer is opened. A file's text is dropped once its layer ids are read; only the ids stay.</li>
  <li>The unknown paths: the code-index buckets of the pack and of the newer pack are read only when that drawer is opened, through the same queue; each bucket is parsed, its place paths kept and the rest dropped. LINES.md is streamed only if the newer pack does not answer, and only as far as its header.</li>
  <li>At most ${MAX_DOCS} layer files are held; the least recently used is dropped first. A spider node wakes at most ${MAX_BLOCKS_WOKEN} blocks. The family index and its line file load only when a family is asked for.</li>
  </ul>`;
}
const MAX_LABELS_TEXT = 28;

/* ── start ─────────────────────────────────────────────────────────────────── */
(async function start() {
  if (matchMedia('(min-width:760px)').matches) $('questions').open = true;
  writeRules();
  $('atlasKeys').addEventListener('toggle', () => { if ($('atlasKeys').open && st.manifest) openAtlasDrawer(); });
  $('unknownPaths').addEventListener('toggle', () => { if ($('unknownPaths').open && st.manifest) openUnknownDrawer(); });
  import(CDN + 'deeplink/contract.js').then(m => { st.contract = m; writeTest(); }).catch(e => { st.contractError = e.message; });

  const waferP = wafer.load().then(() => true, e => { $('waferFoot').textContent = 'Could not load the numbered database: ' + e.message; return false; });

  try {
    st.manifest = await getJSON(CDN + 'spider/manifest.json');
  } catch (e) {
    $('spiderFoot').textContent = 'The spider manifest could not load: ' + e.message; return;
  }
  const pick = $('graphPick');
  for (const g of st.manifest.graphs) {
    const o = document.createElement('option'); o.value = g.id; o.textContent = optionText(g); pick.appendChild(o);
  }
  pick.addEventListener('change', () => { writeGraphChoice(pick.value); linkBox(null); showGraph(pick.value); });
  st.link = readLink(location.search, st.manifest.graphs.map(g => g.id));
  linkBox(null);

  const regP = getJSON(REGISTER).then(r => { st.regRaw = r; st.reg = indexRegister(r); })
    .catch(e => { $('bridgeLine').textContent = 'The block register could not load: ' + e.message; });
  const layP = getJSON(ROOT + 'layers/manifest.json').then(m => { st.layers = m; for (const l of m.layers) st.layerById.set(l.id, l); })
    .catch(e => { say(`<p class="refuse">layers/manifest.json: ${esc(e.message)}; no lines can be woken.</p>`); });
  const startId = st.link.graph || 'federation';
  await Promise.all([regP, layP, loadGraph(startId)]);
  await showGraph(startId);
  writeQuestions();
  await waferP;
  await applyLink();
})();

window.__pair = { st, spider, wafer };

Bridge

A JavaScript module in the iterations folder of Galaxies Wafers that reads graph (`readGraph`). Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/32-spider-and-galaxy/. It reads graph (`readGraph`) and indexes register (`indexRegister`).

ingestgalaxies-wafers / iterations/32-spider-and-galaxy/bridge.mjs · lines 1–131 of 131

What it does
It lists and searches its content. Defines 7 functions or classes, including readGraph, end, nodeRefs, indexRegister, pathCovers.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'spider'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Downstream impact
Used directly by 1 file: Iterations — 32 Spider and Galaxy (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/32-spider-and-galaxy/). Reached from 90 other entry points, including Iterations — 32 Spider and Galaxy Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/32-spider-and-galaxy/); Iterations — 47 Federation Honesty Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/47-federation-honesty/); GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html).
What it achieves
One universe, two views: how a spider node is read as a place in the numbered universe, and back.
Why it matters
Imported by Iterations — 32 Spider and Galaxy.
Application
galaxies-wafers · iterations/32-spider-and-galaxy · JavaScript module
Uses
none found
Used by
imported by Iterations — 32 Spider and Galaxy (import)
Produces
readGraph, nodeRefs, indexRegister, pathCovers, counterpart, nodesForBlock
Defines here
readGraph, end, nodeRefs, indexRegister, pathCovers, counterpart, nodesForBlock
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/32-spider-and-galaxy/bridge.mjs:1-131 · blob fda524b246940d86feeb2890000350dfc34f44a5 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unknown
/* bridge.mjs — one universe, two views: how a spider node is read as a place
 * in the numbered universe, and back. No DOM and no fetch, so the page and the
 * tests import the same code.
 *
 * A spider node can name the numbered universe in three ways, tried in this
 * order, and the method used is always reported with the answer:
 *   1. a numbered function family: id "family:N" or a link carrying ?family=N
 *   2. a register block: id "block:X", a label carrying "block:X", or ?block=X
 *   3. a repository and path: id "Ventusltd/repo" or "repo:Ventusltd/repo", the
 *      contents cartridge's own path field (repository globalgrid2050), or a
 *      github.com/Ventusltd/<repo>/(blob|tree)/<ref>/<path> link
 * Anything else names nothing the numbered universe can hold.
 */

/* The spider's own normalisation (index.html normaliseGenericGraph and
   reshapeNodes), reproduced for reading, plus the one thing the spider does
   not report: edges whose ends name no node, which it drops without saying so. */
export function readGraph(raw, edgesRaw) {
  const rawNodes = Array.isArray(raw) ? raw
    : Array.isArray(raw?.nodes) ? raw.nodes
    : Array.isArray(raw?.features) ? raw.features.map(f => ({ id: f.id, ...(f.properties || {}) })) : [];
  const ids = new Map();
  const nodes = rawNodes.map((n, i) => {
    const id = n.id !== undefined ? n.id : i;
    ids.set(id, i);
    return {
      id, label: String(n.label || n.title || id),
      type: n.type || n.nodeKind || n.repo_type || 'unknown',
      rag: n.rag || n.status || 'grey',
      reason: String(n.reason || n.status_reason || n.path || ''),
      gh: n.gh || null, ext: n.ext || n.public_url || null,
      path: typeof n.path === 'string' ? n.path : null
    };
  });
  let src = edgesRaw ?? raw;
  const rawEdges = Array.isArray(src) && edgesRaw ? src
    : Array.isArray(src?.edges) ? src.edges : Array.isArray(src?.links) ? src.links : [];
  const edges = []; let dangling = 0;
  const end = (x, arr) => (arr && typeof x === 'number') ? (x >= 0 && x < nodes.length ? x : -1) : (ids.has(x) ? ids.get(x) : -1);
  for (const e of rawEdges) {
    const arr = Array.isArray(e);
    const a = arr ? e[0] : (e.from ?? e.source), b = arr ? e[1] : (e.to ?? e.target);
    const ia = end(a, arr), ib = end(b, arr);
    if (ia < 0 || ib < 0) { dangling++; continue; }
    edges.push([ia, ib, (arr ? e[2] : e.type) || 'repo']);
  }
  return { nodes, edges, rawEdges: rawEdges.length, dangling };
}

const GH = /^https:\/\/github\.com\/(Ventusltd\/[^/?#]+)(?:\/(?:blob|tree)\/[^/]+\/([^?#]*))?/;

/* What a node names. graphId matters only for the contents cartridge, whose
   path field is relative to the globalgrid2050 repository (its manifest says so). */
export function nodeRefs(graphId, n) {
  const hay = [String(n.id), n.label, n.gh || '', n.ext || ''].join(' ');
  let m = /(?:^|[^a-z])family[:=](\d+)/.exec(hay);
  if (m) return { kind: 'family', family: Number(m[1]), method: 'family number in the node id or link' };
  m = /block[:=]([A-Za-z][A-Za-z0-9]{0,5})\b/.exec(hay);
  if (m) return { kind: 'block', block: m[1], method: 'block symbol in the node id, label or link' };
  const id = String(n.id);
  m = /^(?:repo:)?(Ventusltd\/[A-Za-z0-9._-]+)$/.exec(id);
  if (m) return { kind: 'path', repo: m[1], path: '', method: 'repository named by the node id' };
  if (graphId === 'globalgrid2050-contents' && n.path !== null)
    return { kind: 'path', repo: 'Ventusltd/globalgrid2050', path: n.path, method: 'contents cartridge path (repository globalgrid2050)' };
  m = GH.exec(n.gh || '');
  if (m) return { kind: 'path', repo: m[1], path: decodeURIComponent(m[2] || ''), method: 'GitHub link on the node' };
  return { kind: 'none', method: 'names no family, block, repository or path' };
}

/* Index the live block register: repository -> [{path, symbol}], symbol -> block. */
export function indexRegister(register) {
  const byRepo = new Map(), bySymbol = new Map();
  for (const b of register.blocks || []) {
    bySymbol.set(b.symbol, b);
    for (const f of b.files || []) {
      if (!byRepo.has(f.repo)) byRepo.set(f.repo, []);
      byRepo.get(f.repo).push({ path: f.path, symbol: b.symbol });
    }
  }
  return { byRepo, bySymbol, generated: register.generated_utc, blocks: (register.blocks || []).length };
}

/* A register file lies under a node's path: the node names the whole repo, the
   exact file, or a folder the file is inside. */
export function pathCovers(nodePath, filePath) {
  const p = String(nodePath || '').replace(/^\/+/, '');
  if (!p) return true;
  if (filePath === p) return true;
  return filePath.startsWith(p.endsWith('/') ? p : p + '/');
}

/* The galaxy's answer for one node. families: Map n -> family, or null while
   the family index has not been asked for. */
export function counterpart(refs, reg, families) {
  if (refs.kind === 'family') {
    if (!families) return { state: 'pending', why: 'family ' + refs.family + ' needs the family index, which loads only when asked' };
    const f = families.get(refs.family);
    if (!f) return { state: 'unknown', why: 'family ' + refs.family + ' is not in the numbered database' };
    return { state: 'known', family: f, blocks: f.block ? [f.block] : [], why: 'numbered family ' + f.n + ' ' + f.name + (f.block ? ', block ' + f.block : '') };
  }
  if (refs.kind === 'block') {
    const b = reg.bySymbol.get(refs.block);
    if (!b) return { state: 'unknown', why: 'block ' + refs.block + ' is not in the live register' };
    return { state: 'known', blocks: [b.symbol], why: 'register block ' + b.symbol + ' #' + b.number + ' ' + b.title };
  }
  if (refs.kind === 'path') {
    const files = reg.byRepo.get(refs.repo);
    if (!files) return { state: 'unknown', why: 'the live register records no file in ' + refs.repo };
    const hit = files.filter(f => pathCovers(refs.path, f.path));
    if (!hit.length) return { state: 'unknown', why: 'the live register records ' + files.length + ' file(s) in ' + refs.repo + ', none at or under "' + refs.path + '"' };
    const blocks = [...new Set(hit.map(h => h.symbol))];
    return { state: 'known', blocks, files: hit, why: hit.length + ' register file(s) in ' + refs.repo + (refs.path ? ' under "' + refs.path + '"' : '') + ', blocks ' + blocks.join(', ') };
  }
  return { state: 'none', why: 'the node ' + refs.method };
}

/* The reverse: which nodes of a graph name a block (by symbol, by a register
   file of that block, or by a family the block carries). */
export function nodesForBlock(symbol, family, graphId, nodes, reg) {
  const b = reg.bySymbol.get(symbol);
  const files = b ? (b.files || []) : [];
  const out = [];
  nodes.forEach((n, i) => {
    const r = nodeRefs(graphId, n);
    if (r.kind === 'block' && r.block === symbol) out.push([i, 'names block ' + symbol]);
    else if (r.kind === 'family' && family != null && r.family === family) out.push([i, 'names family ' + family]);
    else if (r.kind === 'path' && files.some(f => f.repo === r.repo && pathCovers(r.path, f.path)))
      out.push([i, 'names ' + r.repo + (r.path ? '/' + r.path : '') + ', where block ' + symbol + ' has a file']);
  });
  return out;
}