GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / galaxies-wafers / iterations/31-code-card-everywhere

Iterations — 32 Spider and Galaxy and 3 more files

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/.

700 lines of JavaScript and CSS and HTML from galaxies-wafers, in 4 files. Topic: Kuiper, cosmos and drawing engines. Section 1205 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. Card render · galaxies-wafers / iterations/31-code-card-everywhere/card.mjs lines 701–839
  2. Iterations — 31 Code Card Everywhere Page render · galaxies-wafers / iterations/31-code-card-everywhere/index.html lines 1–45
  3. Iterations — 31 Code Card Everywhere Style Sheet render · galaxies-wafers / iterations/31-code-card-everywhere/style.css lines 1–151
  4. Iterations — 32 Spider and Galaxy render · galaxies-wafers / iterations/32-spider-and-galaxy/app.mjs lines 1–365

Card

A JavaScript module in the iterations folder of Galaxies Wafers that draws blocks and cables, and uses data from the stars repository. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/31-code-card-everywhere/.

rendergalaxies-wafers / iterations/31-code-card-everywhere/card.mjs · lines 701–839 of 839 (continued from section 1204) · pattern machineDetail (shared by 2 files)

What it does
It draws blocks and cables. Defines 53 functions or classes, including Queue, LRU, cached, rawURL, ghURL. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain terms in the code: cables.
Inputs & outputs
In: data source: stars data; JSON file blocks.json; JSON file index.json. Out: canvas drawing.
Downstream impact
Used directly by 1 file: Iterations — 31 Code Card Everywhere (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/31-code-card-everywhere/). Reached from 91 other entry points, including Iterations — 31 Code Card Everywhere Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/31-code-card-everywhere/); Iterations — 39 Decisions and Permission Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/39-decisions-and-permission/); Iterations — 41 Golden Angle Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/41-golden-angle/).
What it achieves
It reads source (`readSource`), binds wafer (`bindWafer`) and sets tag (`setTag`). Iteration 31, Code Card Everywhere. Its code works with 100 kW. It responds to click, wafer and keydown events.
Why it matters
Imported by Iterations — 31 Code Card Everywhere.
Application
galaxies-wafers · iterations/31-code-card-everywhere · JavaScript module
Uses
Galaxies Wafers — Lib (import), Stars — Index Page (estate URL)
Used by
imported by Iterations — 31 Code Card Everywhere (import)
Produces
bindWafer, cardTap, openLine
Defines here
machineDetail, questions, openRoute, tileBandWidth, openArea
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/31-code-card-everywhere/card.mjs:701-839 · blob bbfdf38796eff93ab9b7a7580f93b8b7d5cae7ec · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
  return [...new Set(out)];
}
function machineDetail(fnText, lines, pl) {
  const sig = fnText.match(/function\s*\*?\s*[\w$]*\s*\(([\s\S]*?)\)\s*\{/) || fnText.match(/\(([^()]*)\)\s*=>/);
  let inputs = 'no parameter list read from this window';
  if (sig) {
    const names = sig[1].replace(/[{}\[\]]/g, '').split(',').map(p => p.split('=')[0].split(':').pop().trim()).filter(p => /^[A-Za-z_$][\w$]*$/.test(p));
    inputs = names.length ? names.map(n => { const u = unitOf(n); return u ? `${n} (${u})` : `${n} (no unit in the name)`; }).join(', ') : 'none';
  }
  const outs = outputsOf(fnText);
  const throws = [...new Set([...fnText.matchAll(/throw\s+new\s+(\w+)/g)].map(m => m[1]))];
  const src = lines.join('\n');
  const nc = src.match(/export\s+const\s+NOT_COMPUTED\s*=\s*Object\.freeze\(\{([\s\S]*?)\n\}\);/);
  const ncKeys = nc ? [...nc[1].matchAll(/^\s{2,8}([A-Za-z_$][\w$]*)\s*:/gm)].map(m => m[1]) : [];
  const other = [...src.matchAll(/export\s+const\s+(NOT_[A-Z_]+|NO_[A-Z_]+|NEVER_[A-Z_]+)\s*=/g)].map(m => m[1]).filter(n => n !== 'NOT_COMPUTED' || !nc);
  return `inputs: ${inputs} (units read from parameter name suffixes, name-match inference) · outputs: ${outs.length ? outs.join('; ') : 'no quantity/unit fields in this function'} · refusals: ${throws.length ? 'throws ' + throws.join(', ') : 'no throw in this function'}${ncKeys.length ? ' · NOT_COMPUTED: ' + ncKeys.join(', ') : ''}${other.length ? ' · also ' + other.join(', ') : ''} · source ${pl  … [line shortened here: 434 characters; full line on GitHub]
}

function questions(body, q) {
  const d = el('details', 'cc-q');
  if (window.matchMedia('(min-width: 760px)').matches) d.open = true;
  d.append(el('summary', null, 'Questions'));
  const dl = el('dl', 'cc-dl');
  row(dl, 'draws', q.sld);
  row(dl, 'used for', q.use);
  row(dl, 'leads to', q.next);
  d.append(el('div', 'cc-small', '1 how does this help draw a system or single-line diagram · 2 what is this code used for, and who calls it · 3 where does it lead next'), dl);
  const m = el('div', 'cc-machine'); m.append(el('span', 'cc-sub', 'Machine detail '), document.createTextNode(q.machine));
  d.append(m);
  body.append(d);
}

/* ── a route ───────────────────────────────────────────────────────────────── */

async function openRoute(layer, f) {
  const keys = f.geometry.keys || [];
  mark = { kind: 'route', keys }; W.redraw();
  const p = f.properties || {};
  const { body, setTag, live } = sheet(layer.label, ` route · ${fmt(keys.length)} stops`);
  const dl = el('dl', 'cc-dl');
  const module = [p.block && `block ${p.block}`, p.function && `function ${p.function}`, p.family != null && `family #${p.family}`, p.module_path].filter(Boolean).join(' · ');
  row(dl, 'module', module || 'the route names no module');
  const first = keys[0], last = keys[keys.length - 1];
  row(dl, 'first line', btn(fmt(first), 'cc-key', () => openLine(first, { family: p.family })));
  row(dl, 'last line', btn(fmt(last), 'cc-key', () => openLine(last, { family: p.family })));
  for (const [k, v] of Object.entries(p)) if (!['block', 'function', 'family'].includes(k)) row(dl, k, typeof v === 'object' ? JSON.stringify(v) : String(v));
  body.append(dl);
  const stops = el('div', 'cc-stops');
  stops.append(el('div', 'cc-sub', 'STOPS, IN ROUTE ORDER'));
  const shownStops = keys.slice(0, 400);
  stops.append(el('div', 'cc-stoplist', shownStops.map((k, j) => `${j + 1}:${k}`).join('  ') + (keys.length > 400 ? `  … and ${fmt(keys.length - 400)} more` : '')));
  const pick = el('input', 'cc-pick'); pick.setAttribute('inputmode', 'numeric'); pick.setAttribute('aria-label', 'stop number'); pick.value = '1';
  const openStop = btn('OPEN STOP', 'cc-mini', () => {
    const j = Number(pick.value.replace(/\D/g, '')) - 1;
    if (j >= 0 && j < keys.length) openLine(keys[j], { family: p.family });
    else pick.value = '1';
  });
  const pr = el('div', 'cc-row'); pr.append(el('span', 'cc-grey', `stop 1 to ${keys.length}: `), pick, openStop);
  stops.append(pr);
  body.append(stops, el('div', 'cc-small', 'evidence: ' + (layer.evidence ?? 'none recorded') + ' · tap a stop to open its code card'));

  if (p.family == null) {
    setTag('OK', 'the route as the layer draws it');
    return questions(body, { sld: 'none yet: this route names no family.', use: `drawn by the layer ${layer.id}; it names no module.`, next: 'not established: the route names no family to follow.', machine: `input: ${fmt(keys.length)} keys · output: a polyline through their placements · source: layers/${layer.id}` });
  }
  setTag('LOAD', `reading family #${p.family}'s record…`);
  let fr, reg;
  try { [fr, reg] = await Promise.all([familyRecord(p.family, () => setTag('WAIT', 'queued behind other fetches…')), register().catch(() => null)]); }
  catch (e) { setTag('FAIL', 'Could not read the family record: ' + e.message); return; }
  if (!live()) return;
  if (fr.missing) { setTag('EMPTY', fr.missing); return; }
  const rec = fr.rec, pl = rec.places?.[0], block = p.block && reg ? reg.get(p.block) : null;
  if (pl) {
    const h = el('div', 'cc-codehead');
    h.append(`${pl.path} · ${pl.repo} @ ${pl.commit.slice(0, 7)} · lines ${pl.first}–${pl.last} · `, link(ghURL(pl.repo, pl.commit, pl.path, pl.first, pl.last), 'on GitHub'));
    body.insertBefore(h, stops);
  }
  const sld = pl ? SLD[pl.path] : null;
  setTag('OK', `family #${p.family}: ${(rec.names || []).join(', ')}`);
  questions(body, {
    sld: sld && pl.repo === ENGINE_REPO ? `${sld.element}: ${pl.path} → ${sld.fn}(). The page's module-to-element table; open a stop to see the function checked in its source.` : `none yet: ${pl ? pl.path : 'this family'} is not mapped to a diagram element.`,
    use: `${block ? `block ${block.symbol} (${block.title})` : 'no block in the register'} · function ${(rec.names || []).join(', ')}${pl ? ` · ${pl.path} @ ${pl.commit.slice(0, 7)}` : ''} · called by: ${rec.used_by?.length ? rec.used_by.slice(0, 8).map(u => `#${u.family} ${u.name}`).join(', ') + ' (name-match inference)' : 'no caller recorded'}.`,
    next: rec.uses?.length ? `uses ${rec.uses.slice(0, 8).map(u => `#${u.family} ${u.name} (${u.via})`).join(', ')} (name-match inference)` : `not established: family #${p.family} records no uses${block?.depends_on?.length ? '' : ' and its block declares no depends_on'}.`,
    machine: `route: ${fmt(keys.length)} keys from ${fmt(first)} to ${fmt(last)}, ${p.route ?? 'order as stored in the layer'} · family lines in the record: ${rec.lines.length}${pl ? ` · source ${pl.repo} ${pl.path} @ ${pl.commit}` : ''}`
  });
}

/* ── empty ground ──────────────────────────────────────────────────────────── */

let bandS = null;
async function tileBandWidth() {
  if (bandS) return bandS;
  const m = await cached(onceMap, ROOT + 'layers/manifest.json', 'json');
  const t = (m.layers || []).find(l => l.tiles);
  if (!t) return null;
  const idx = await cached(onceMap, ROOT + t.tiles, 'json');
  bandS = idx.scheme?.S ? { S: idx.scheme.S, law: idx.scheme.law, layer: t.id } : null;
  return bandS;
}

async function openArea(wx, wy, near, zoom) {
  const U = W.U;
  mark = { kind: 'point', x: wx, y: wy, key: near?.key ?? -1 }; W.redraw();
  const r = Math.hypot(wx, wy) / SPACING;
  const b = Math.floor(r);
  const k0 = b * b, k1 = (b + 1) * (b + 1);
  const { body, setTag, live } = sheet('Empty ground', ` radius ${r.toFixed(2)} · no line within ${REACH} px`);
  const dl = el('dl', 'cc-dl');
  row(dl, 'point', `x ${wx.toFixed(2)}, y ${wy.toFixed(2)} in wafer units`);
  row(dl, 'ring', `r = sqrt(key) puts radius ${b} to ${b + 1} at keys ${fmt(k0)} to ${fmt(k1 - 1)} · ${fmt(issuedIn(k0, k1))} of those ${fmt(k1 - k0)} numbers were issued`);
  const bandDD = row(dl, 'tile band', 'reading the tile scheme…');
  if (near) {
    const dd = row(dl, 'nearest line', btn(fmt(near.key), 'cc-key', () => openLine(near.key)));
    dd.append(` · ${near.d.toFixed(2)} units away, ${(near.d * zoom).toFixed(0)} px at this zoom · ${(U.ownerOf?.get(near.key) || []).length} ${(U.ownerOf?.get(near.key) || []).length === 1 ? 'family' : 'families'}`);
  }
  body.append(dl);
  setTag('OK', 'computed from the placement law and the issued keys');
  questions(body, {
    sld: 'none yet: empty ground draws nothing.',
    use: `nothing: no issued line sits within ${REACH} px of this point.`,
    next: near ? `the nearest issued line, ${fmt(near.key)}; tap its number for its code card.` : 'not established: no issued line was found.',
    machine: `input: a tap at wafer x ${wx.toFixed(2)}, y ${wy.toFixed(2)} · output: radius ${r.toFixed(3)} and key range [${k0}, ${k1}) from r = sqrt(key) · source: numbered database built ${U.meta.built_utc}`
  });
  try {
    const t = await tileBandWidth();
    if (!live()) return;
    if (!t) { bandDD.textContent = 'EMPTY: no layer in the manifest is tiled, so no tile band scheme is published'; return; }
    const tb = Math.floor(Math.floor(Math.sqrt(Math.max(0, Math.floor(r * r)))) / t.S);
    const a = (tb * t.S) ** 2, z = ((tb + 1) * t.S) ** 2;
    bandDD.textContent = `band ${tb} of the layer tiles (${t.law}, S = ${t.S}, read from layers/tiles/${t.layer}): keys ${fmt(a)} to ${fmt(z - 1)} · ${fmt(issuedIn(a, z))} issued`;
  } catch (e) { if (live()) bandDD.textContent = 'FAIL: could not read the tile scheme: ' + e.message; }
}

window.__codecard = Object.freeze({
  get fetches() { return fetchCount; },
  get cachedSources() { return sources.size; },
  get cachedBuckets() { return buckets.size; },
  openLine: (k, o) => openLine(k, o)
});

Iterations — 31 Code Card Everywhere Page

A web page in Galaxies Wafers. Published at https://ventusltd.github.io/galaxies-wafers/iterations/31-code-card-everywhere/.

rendergalaxies-wafers / iterations/31-code-card-everywhere/index.html · lines 1–45 of 45 · Entry point

What it does
It draws its content. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
Inputs & outputs
In: form fields (user input). Out: web page.
Downstream impact
Used directly by 8 files: Iterations — 39 Decisions and Permission Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/39-decisions-and-permission/); Iterations — 41 Golden Angle Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/41-golden-angle/); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); Homepage Versions — Before Refresh Page (globalgrid2050, https://globalgrid2050.com/homepage_versions/20260922-before-refresh/); and 4 more. Reached from 82 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); Homepage V037 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v037.html); Homepage V038 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v038.html). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/31-code-card-everywhere/.
What it achieves
Code Card Everywhere — tap anything on the wafer, read its code.
Why it matters
Loaded by the 39 Decisions and Permission page at https://ventusltd.github.io/galaxies-wafers/iterations/39-decisions-and-permission/ and 7 other pages.
Application
galaxies-wafers · iterations/31-code-card-everywhere · page
Uses
Iterations — 31 Code Card Everywhere Style Sheet (stylesheet), Galaxies Wafers — Proof Page (link), Iterations — 31 Code Card Everywhere (script src), Layers Panel (script src)
Used by
linked from Iterations — 39 Decisions and Permission Page (link), linked from Iterations — 41 Golden Angle Page (link), linked from GlobalGrid2050 Homepage Before Four Nests (link), linked from Homepage Versions — Before Refresh Page (link), linked from Homepage V122 (link), linked from Homepage V123 (link), linked from Homepage V124 (link), linked from Homepage V125 (link)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/31-code-card-everywhere/index.html:1-45 · blob dcf5f7932788c0f79a732b07f442ac83439ea8b1 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, maximum-scale=5">
<meta name="color-scheme" content="dark">
<title>Code Card Everywhere — tap anything on the wafer, read its code</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="style.css">
</head>
<body>

<canvas id="stage" aria-label="Every permanently numbered line of code in the estate, placed by its own number."></canvas>

<header id="bar">
  <span id="wordmark">CODE CARD EVERYWHERE</span>
  <span id="count" class="dim">loading the numbered database…</span>
</header>

<form id="beam" autocomplete="off">
  <input id="a" inputmode="numeric" pattern="[0-9]*" placeholder="line number" aria-label="line number to fly to">
  <input id="b" inputmode="numeric" pattern="[0-9]*" placeholder="connect to…" aria-label="second line number to connect to">
  <button id="go" type="submit">FLY</button>
</form>

<section id="card" hidden aria-live="polite"></section>

<section id="panel" hidden>
  <button id="close" type="button" aria-label="close">✕</button>
  <div id="panelbody"></div>
</section>

<footer id="foot">
  <span id="prov" class="dim">provenance loading</span>
  <span id="wake" class="dim">tick a layer to wake its lines</span>
  <span id="hint" class="dim">drag to steer · pinch or scroll to focus · tap anything for its code card</span>
  <a id="proofs" href="../../proof/">check every claim on this page</a>
</footer>

<noscript><p class="dim" style="padding:1rem">This surface is drawn from the numbered database at run time, so it needs JavaScript. Nothing here is typed into the page.</p></noscript>

<script type="module" src="app.mjs"></script>
<script type="module" src="layers-panel.mjs"></script>
</body>
</html>

Iterations — 31 Code Card Everywhere Style Sheet

A style sheet in Galaxies Wafers. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/31-code-card-everywhere/.

rendergalaxies-wafers / iterations/31-code-card-everywhere/style.css · lines 1–151 of 151 · Entry point

What it does
Side effects: changes the web page (DOM).
Downstream impact
Used directly by 1 file: Iterations — 31 Code Card Everywhere Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/31-code-card-everywhere/). Reached from 90 other entry points, including Iterations — 39 Decisions and Permission Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/39-decisions-and-permission/); Iterations — 41 Golden Angle Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/41-golden-angle/); GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/31-code-card-everywhere/.
What it achieves
The Line Wafer. Designed at 430 px first; the desktop is the same layout with more room.
Why it matters
Loaded by the 31 Code Card Everywhere page at https://ventusltd.github.io/galaxies-wafers/iterations/31-code-card-everywhere/.
Application
galaxies-wafers · iterations/31-code-card-everywhere · style sheet
Uses
none found
Used by
loaded by Iterations — 31 Code Card Everywhere Page (stylesheet)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/31-code-card-everywhere/style.css:1-151 · blob 128006e2000a5e9b2295d71696916581a6623de4 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
/* The Line Wafer. Designed at 430 px first; the desktop is the same layout with
   more room. One canvas, three chrome strips, nothing that scrolls the page. */

:root{
  --ink:#d8dee9; --dim:#8b93a7; --ground:#0b0d12; --edge:#1b2030;
  --lit:#ffd54a; --beam:#5ec8f2;
  --top:env(safe-area-inset-top,0px); --bot:env(safe-area-inset-bottom,0px);
}
*{box-sizing:border-box}
html,body{height:100%}
body{
  margin:0; background:var(--ground); color:var(--ink);
  font:13px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
  overflow:hidden; overscroll-behavior:none; -webkit-text-size-adjust:100%;
}
#stage{position:fixed; inset:0; width:100%; height:100%; display:block; touch-action:none}

#bar{
  position:fixed; left:0; right:0; top:0; z-index:2;
  display:flex; gap:.75rem; align-items:baseline; flex-wrap:wrap;
  padding:calc(var(--top) + .5rem) .75rem .5rem;
  background:linear-gradient(#0b0d12ee,#0b0d1200); pointer-events:none;
}
#wordmark{letter-spacing:.14em; font-size:11px}
.dim{color:var(--dim)}

#beam{
  position:fixed; z-index:3; left:.5rem; right:.5rem;
  bottom:calc(var(--bot) + 3.4rem);
  display:flex; gap:.4rem;
}
#beam input{
  flex:1 1 0; min-width:0; padding:.6rem .55rem;
  background:#11151f; color:var(--ink); border:1px solid var(--edge); border-radius:6px;
  font:inherit; font-size:16px; /* 16px stops iOS zooming the page on focus */
}
#beam input:focus{outline:none; border-color:var(--beam)}
#beam button{
  flex:0 0 auto; padding:.6rem .9rem; border-radius:6px; cursor:pointer;
  background:#11151f; color:var(--beam); border:1px solid var(--beam);
  font:inherit; font-size:13px; letter-spacing:.1em;
}
#beam button:active{background:#16202c}

#panel{
  position:fixed; z-index:4; left:.5rem; right:.5rem;
  bottom:calc(var(--bot) + 6.6rem);
  max-height:52vh; overflow:auto; -webkit-overflow-scrolling:touch;
  background:#0e121bf2; border:1px solid var(--edge); border-radius:8px;
  padding:.75rem .8rem 1rem;
}
#panel[hidden]{display:none!important}
#close{
  position:absolute; top:.35rem; right:.4rem; width:2rem; height:2rem;
  background:none; border:0; color:var(--dim); font:inherit; font-size:15px; cursor:pointer;
}
#panel h2{margin:0 .5rem .5rem 0; font-size:15px; font-weight:600; letter-spacing:.02em}
#panel h2 .n{color:var(--lit)}
#panel dl{display:grid; grid-template-columns:auto 1fr; gap:.15rem .6rem; margin:.5rem 0}
#panel dt{color:var(--dim)}
#panel dd{margin:0; overflow-wrap:anywhere}
#panel p{margin:.5rem 0 0}
#panel ul{margin:.35rem 0 0; padding-left:1.1rem}
#panel li{margin:.15rem 0}
.fam{color:var(--beam)}
.refuse{color:var(--lit)}

#foot{
  position:fixed; z-index:2; left:0; right:0; bottom:0;
  display:flex; gap:.15rem; flex-direction:column;
  padding:.35rem .75rem calc(var(--bot) + .35rem);
  background:linear-gradient(#0b0d1200,#0b0d12ee); pointer-events:none;
  font-size:10.5px;
}
#hint{text-align:left}
#foot a{color:var(--beam); pointer-events:auto; text-decoration:underline}

@media (min-width:760px){
  #beam{left:auto; right:1rem; width:26rem; bottom:calc(var(--bot) + 2.9rem)}
  #foot{flex-direction:row; gap:.6rem; justify-content:space-between}
  #hint{text-align:right}
  #panel{left:1rem; right:auto; width:26rem; bottom:calc(var(--bot) + 2.5rem); max-height:66vh}
  #foot{font-size:11px}
}

/* Dark Pixels: the wake line reads a little brighter than the other footer text */
#wake{color:var(--ink)}
/* the footer carries a third line here, so on a phone the form and panel sit one line higher */
@media (max-width:759px){
  #beam{bottom:calc(var(--bot) + 5.4rem)}
  #panel{bottom:calc(var(--bot) + 8.6rem); max-height:44vh}
}

/* iteration 31: the code card — Grid Atlas popup grammar (iteration 07), as one sheet */
#card{position:fixed; z-index:6; left:.5rem; right:.5rem; bottom:calc(var(--bot) + .5rem);
  max-height:64vh; overflow:auto; -webkit-overflow-scrolling:touch; overscroll-behavior:contain;
  background:#000; color:#d8dee9; border:1px solid #444; border-radius:4px;
  font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; padding:8px 10px 12px; box-shadow:0 1px 8px #000c}
#card[hidden]{display:none!important}
#card .cc-x{position:sticky; float:right; top:0; background:#000; border:0; color:#888; font:inherit; font-size:18px; cursor:pointer; padding:0 6px; line-height:1.2}
#card .cc-title{display:inline; color:#ffd54a; font-size:13px; font-weight:bold}
#card .cc-grey{color:#888}
#card .cc-amber{color:#ffae00}
#card .cc-small{color:#666; font-size:10.5px; margin:.2rem 0}
#card .cc-sub{color:#00ffff; font-size:10.5px; letter-spacing:.08em; font-weight:bold}
#card .cc-tagline{margin:.35rem 0 .25rem}
#card .cc-tag{display:inline-block; font:600 10px/1 ui-monospace,monospace; padding:.2rem .35rem; border:1px solid currentColor; border-radius:3px; margin-right:.4rem; letter-spacing:.06em}
#card .cc-tag[data-s="WAIT"]{color:#9aa3b5} #card .cc-tag[data-s="LOAD"]{color:#ffd54a}
#card .cc-tag[data-s="OK"]{color:#00ffff} #card .cc-tag[data-s="EMPTY"]{color:#b39ddb} #card .cc-tag[data-s="FAIL"]{color:#ff9f43}
#card .cc-row{margin:.25rem 0; overflow-wrap:anywhere}
#card .cc-select{max-width:100%; background:#0a0a0a; color:#00ffff; border:1px solid #444; border-radius:3px; font:inherit; font-size:16px; padding:.15rem .25rem}
#card .cc-dl{display:grid; grid-template-columns:auto 1fr; gap:.15rem .6rem; margin:.4rem 0}
#card .cc-dl dt{color:#888}
#card .cc-dl dd{margin:0; overflow-wrap:anywhere}
#card .cc-link{color:#00ffff}
#card .cc-codehead{color:#888; font-size:11px; overflow-wrap:anywhere; margin:.4rem 0 .2rem}
#card .cc-check{color:#aaa; font-size:11px; margin:.1rem 0 .3rem}
#card .cc-code{position:relative; max-height:34vh; overflow:auto; margin:0; padding:6px 8px; background:#0a0a0a; border:1px solid #333;
  font:11px/16px ui-monospace,Consolas,monospace; white-space:pre; tab-size:4; color:#d8dee9; cursor:pointer}
#card .cc-hi{position:absolute; left:0; right:0; min-width:100%; pointer-events:none}
#card .cc-hi-target{background:#ffd54a26; border-left:3px solid #ffd54a}
#card .cc-hi-sel{background:#00ffff14; outline:1px solid #00ffff55}
#card .cc-strip{border:1px solid #333; border-top:0; padding:6px 8px; background:#050505}
#card .cc-stripline{font:12px/2 ui-monospace,Consolas,monospace; white-space:pre-wrap; overflow-wrap:anywhere; color:#d8dee9}
#card .cc-digit{font:inherit; font-size:16px; width:auto; min-width:1.4em; padding:0 .15rem; margin:0 1px; background:#111; color:#ffae00; border:1px solid #444; border-radius:3px; text-align:center}
#card .cc-digit.cc-changed{border-color:#00ffff; color:#00ffff}
#card .cc-digit.cc-blank{border-style:dashed}
#card .cc-nav{display:flex; gap:.35rem; flex-wrap:wrap; margin:.3rem 0}
#card .cc-mini, #card .cc-key{background:#0a0a0a; color:#00ffff; border:1px solid #444; border-radius:3px; font:inherit; font-size:11px; padding:.3rem .5rem; cursor:pointer}
#card .cc-key{padding:.1rem .4rem; font-size:12px}
#card .cc-pick{width:5em; font:inherit; font-size:16px; background:#111; color:#ffae00; border:1px solid #444; border-radius:3px; margin-right:.35rem}
#card .cc-local{color:#ffae00; font-size:11px}
#card .cc-run{margin-top:.6rem; border-top:1px solid #333; padding-top:.45rem}
#card .popup-btn{display:block; width:100%; margin:.4rem 0; padding:.45rem 0; font:inherit; font-size:11px; font-weight:bold; border:1px solid #00ffff; border-radius:3px; background:#0a0a0a; color:#00ffff; cursor:pointer; letter-spacing:.06em}
#card .popup-btn:disabled{opacity:.5}
#card .cc-results .cc-cols{display:grid; grid-template-columns:1fr; gap:.4rem; margin-top:.35rem}
#card .cc-col{border:1px solid #333; border-radius:3px; padding:.35rem .45rem; min-width:0}
#card .cc-value{color:#ffd54a; font-size:14px; overflow-wrap:anywhere}
#card .cc-json{max-height:22vh; overflow:auto; margin:.25rem 0 0; font-size:10.5px; color:#aaa; white-space:pre-wrap; overflow-wrap:anywhere}
#card .cc-refuse{color:#ffae00; overflow-wrap:anywhere}
#card .cc-disclaimer{color:#888; font-size:10.5px; margin-top:.4rem; border-left:2px solid #444; padding-left:.4rem}
#card .cc-stops{margin-top:.4rem}
#card .cc-stoplist{color:#aaa; font-size:11px; max-height:8em; overflow:auto; overflow-wrap:anywhere}
#card .cc-q{margin-top:.6rem; border-top:1px solid #333; padding-top:.35rem}
#card .cc-q summary{color:#00ffff; cursor:pointer; letter-spacing:.06em}
#card .cc-machine{font-size:11px; color:#aaa; overflow-wrap:anywhere; margin-top:.25rem}
@media (min-width:760px){
  #card{left:auto; right:1rem; width:34rem; top:calc(var(--top) + 5rem); bottom:calc(var(--bot) + 2.5rem); max-height:none}
  #card .cc-results .cc-cols{grid-template-columns:1fr 1fr}
}
#card .cc-run .cc-grey, #card .cc-run .cc-local{overflow-wrap:anywhere}

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 1–365 of 868 · 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
$, FetchQueue, fetchAs, getJSON, layerDoc, waferFoot, say, graphUrl, optionText, relabel, loadGraph, showGraph, computeBridge, measureBridge, ensureFamilies, ensureFamLines, keysForBlock, tapSpider, receiverRow, tapWafer, replaceQuery, writeSelection, writeGraphChoice, linkBox, byIndex, linkMatches
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:1-365 · 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
/* Spider and Galaxy — one universe, two views.
 *
 * LEFT: the spider of Ventusltd/ventus-grid-engine, drawn here on a canvas from
 * the spider's own published JSON at a pinned commit (spider/manifest.json and
 * the graph files it lists). Graphs the manifest points at on another origin
 * are read live from there and labelled so.
 * RIGHT: the dark wafer of iteration 21: every permanently numbered line of
 * code, dark, with only the lines a question wakes lit.
 * THE BRIDGE (bridge.mjs): a spider node that names a numbered family, a
 * register block, or a repository and path is looked up in the live block
 * register and the numbered database; its lines are woken on the wafer. A lit
 * line on the wafer is looked up the other way, to the spider nodes that name
 * its block, its family or a file of its block.
 *
 * LOADING, LEARNED FROM GRID ATLAS (ventus-corev8engine.js): one fetch queue
 * for all network work, four at a time; every fetch has a 15 s timeout; one
 * shared promise per URL, dropped on failure so a retry can happen; a graph or
 * layer is fetched only when chosen, and its row alone is relabelled
 * WAIT / LOAD / OK / EMPTY / FAIL. Preloaded, as the Atlas preloads its
 * topology: the spider manifest, its default Federation graph, the block
 * register and the wafer's layer manifest, which the bridge cannot work without.
 */
import { readGraph, nodeRefs, indexRegister, counterpart, nodesForBlock, pathCovers } from './bridge.mjs';
import { createSpider } from './spider-pane.mjs';
import { createWafer, MAX_DRAWN, DATA } from './wafer-pane.mjs';
import { readLink } from './link.mjs';
import { atlasUrls, atlasFile, declaredLayerIds, configLayerIds, receiverLink, bucketsForLayer } from './atlas-join.mjs';
import { shapeOf, newIndex, addBucket, holds, classify, CLASS_TEXT } from './unknown-paths.mjs';
import { esc, fmt } from '../../lib.mjs';

export const SHA = '23bc10acb5fb9577d5cd68b04ad6ed336c182013'; // ventus-grid-engine main after the spider manifest fix (genome-spider reads its real graph)
const CDN = `https://cdn.jsdelivr.net/gh/Ventusltd/ventus-grid-engine@${SHA}/`;
const REGISTER = 'https://ventusltd.github.io/stars/blocks/blocks.json';
const ROOT = '../../';
const MAX_BLOCKS_WOKEN = 12;   /* blocks woken for one spider node */
const MAX_DOCS = 24;           /* layer files held in memory, least recently used evicted */
const $ = id => document.getElementById(id);

/* ── one queue, one cache, one timeout ─────────────────────────────────────── */
class FetchQueue {
  constructor(n) { this.n = n; this.active = 0; this.wait = []; }
  async add(task) {
    if (this.active >= this.n) await new Promise(r => this.wait.push(r));
    this.active++;
    try { return await task(); } finally { this.active--; this.wait.shift()?.(); }
  }
}
const queue = new FetchQueue(4);
const urlCache = new Map();
function fetchAs(url, kind) {
  const k = kind + ' ' + url;
  if (urlCache.has(k)) return urlCache.get(k);
  const p = 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 === 'json' ? await r.json() : kind === 'text' ? await r.text() : await r.arrayBuffer();
    } catch (e) { if (e.name === 'AbortError') throw new Error('no answer within 15 s'); throw e; }
    finally { clearTimeout(t); }
  });
  urlCache.set(k, p);
  p.catch(() => urlCache.delete(k));
  return p;
}
const getJSON = u => fetchAs(u, 'json');

/* layer documents, capped */
const docs = new Map();
async function layerDoc(file) {
  if (docs.has(file)) { const d = docs.get(file); docs.delete(file); docs.set(file, d); return d; }
  const d = await getJSON(ROOT + file);
  docs.set(file, d);
  while (docs.size > MAX_DOCS) { const oldest = docs.keys().next().value; docs.delete(oldest); urlCache.delete('json ' + ROOT + oldest); }
  return d;
}

/* ── state ─────────────────────────────────────────────────────────────────── */
const st = {
  manifest: null, graphs: new Map(), current: null,
  reg: null, regRaw: null, layers: null, layerById: new Map(),
  families: null, famLines: null, contract: null,
  bridge: [], refs: []
};

const spider = createSpider($('spiderStage'), { onTap: tapSpider });
const wafer = createWafer($('waferStage'), {
  onTap: tapWafer,
  onStatus: s => { $('waferFoot').textContent = s; },
  onFrame: s => waferFoot(s)
});

let lastFoot = '';
function waferFoot(s) {
  const text = s.total
    ? `${fmt(s.total)} lines woken · ${fmt(s.inBand)} in the visible band · ${fmt(s.drawn)} drawn${s.capped ? ' (cap of ' + fmt(MAX_DRAWN) + ' reached)' : ''} · atlas zoom ${s.atlasZoom.toFixed(1)} · frame ${s.frameMs.toFixed(1)} ms`
    : `every numbered line dark · nothing woken · frame ${s.frameMs.toFixed(1)} ms`;
  if (text !== lastFoot) { $('waferFoot').textContent = text; lastFoot = text; }
}

function say(html) {
  $('sayBody').className = ''; $('sayBody').innerHTML = html;
  const el = $('atlasIds');  /* the tapped node's Atlas layer ids, once read */
  if (el && st.atlasDd) el.innerHTML = st.atlasDd;
}

/* ── the spider's graphs ───────────────────────────────────────────────────── */
function graphUrl(p) { return /^https?:/.test(p) ? p : CDN + p.replace(/^\.\//, ''); }
function optionText(g) {
  const s = st.graphs.get(g.id) || { status: 'WAIT' };
  let t = `${g.title} [${s.status}]`;
  if (s.status === 'OK') t += ` ${fmt(s.graph.nodes.length)} nodes · ${fmt(s.graph.edges.length)} edges`;
  return t;
}
function relabel(id) {   /* update only this graph's row */
  const o = $('graphPick').querySelector(`option[value="${CSS.escape(id)}"]`);
  const g = st.manifest.graphs.find(x => x.id === id);
  if (o && g) o.textContent = optionText(g);
}

async function loadGraph(id) {
  const g = st.manifest.graphs.find(x => x.id === id);
  let s = st.graphs.get(id);
  if (s && (s.status === 'OK' || s.status === 'LOAD')) return s;
  s = { status: 'LOAD' }; st.graphs.set(id, s); relabel(id);
  try {
    const raw = await getJSON(graphUrl(g.path));
    const er = g.edges_path ? await getJSON(graphUrl(g.edges_path)) : undefined;
    s.graph = readGraph(raw, er);
    s.pinned = !/^https?:/.test(g.path);
    s.status = s.graph.nodes.length ? 'OK' : 'EMPTY';
    if (!s.graph.nodes.length) s.why = 'the file loaded and holds no nodes';
  } catch (e) {
    s.status = 'FAIL'; s.why = (e.status ? `HTTP ${e.status} for ${graphUrl(g.path)}` : e.message);
  }
  relabel(id);
  return s;
}

async function showGraph(id) {
  st.current = id;
  $('graphPick').value = id;
  const s = await loadGraph(id);
  if (st.current !== id) return;
  const g = st.manifest.graphs.find(x => x.id === id);
  if (s.status !== 'OK') {
    spider.setGraph({ nodes: [], edges: [] }, []);
    $('spiderFoot').textContent = `${g.title} [${s.status}] ${s.why || ''}`;
    say(`<h2>${esc(g.title)}</h2><p class="refuse">${s.status}: ${esc(s.why || '')}</p><p class="dim">The spider's manifest lists this graph at ${esc(g.path)}. ${esc(g.description || '')}</p>`);
    measureBridge(); writeTest(); return;
  }
  computeBridge();
  spider.setGraph(s.graph, st.bridge);
  $('spiderFoot').textContent = `${s.pinned ? 'pinned ventus-grid-engine@' + SHA.slice(0, 7) : 'read live from ' + new URL(graphUrl(g.path)).host + ', not pinned'} · ${fmt(s.graph.nodes.length)} nodes · ${fmt(s.graph.edges.length)} edges drawn · ${fmt(s.graph.dangling)} edges name a missing node`;
  measureBridge(); writeTest(); writeQuestions();
}

/* ── the bridge ────────────────────────────────────────────────────────────── */
function computeBridge() {
  const s = st.graphs.get(st.current);
  if (!s?.graph || !st.reg) { st.bridge = []; return; }
  st.refs = s.graph.nodes.map(n => nodeRefs(st.current, n));
  st.bridge = st.refs.map(r => counterpart(r, st.reg, st.families).state);
}
function measureBridge() {
  const s = st.graphs.get(st.current);
  const g = st.manifest?.graphs.find(x => x.id === st.current);
  if (!s?.graph || !st.reg) { $('bridgeLine').textContent = s?.status === 'FAIL' ? `${g.title}: no graph, so no bridge` : 'measuring the bridge…'; return; }
  const c = { known: 0, unknown: 0, none: 0, pending: 0 };
  for (const b of st.bridge) c[b]++;
  const total = st.bridge.length;
  $('bridgeLine').innerHTML = `${esc(g.title)}: <b>${fmt(c.known)}</b> of ${fmt(total)} spider nodes have a counterpart in the numbered universe · ${fmt(c.unknown)} name something it does not hold · ${fmt(c.none)} name nothing it could hold`
    + (c.pending ? ` · ${fmt(c.pending)} name a family: <button id="famBtn" type="button">load the family index to count them</button>` : '');
  $('famBtn')?.addEventListener('click', async () => { $('famBtn').disabled = true; $('famBtn').textContent = 'loading the family index…'; await ensureFamilies(); computeBridge(); spider.setBridge(st.bridge); measureBridge(); writeTest(); });
}

async function ensureFamilies() {
  if (st.families) return true;
  try {
    const arr = await getJSON(DATA + 'families.json');
    st.families = new Map(arr.map(f => [f.n, f]));
    st.famArr = arr;
    return true;
  } catch (e) { say(`<p class="refuse">The family index could not load: ${esc(e.message)}. Family nodes stay uncounted.</p>`); return false; }
}
async function ensureFamLines() {
  if (st.famLines) return true;
  try { st.famLines = new Uint32Array(await fetchAs(DATA + 'lines.bin', 'bin')); return true; }
  catch (e) { say(`<p class="refuse">The family line index could not load: ${esc(e.message)}.</p>`); return false; }
}

/* Keys a block charts: its module layer when layers/manifest.json has one,
   otherwise its functions' first lines from the blocks layer. */
async function keysForBlock(sym) {
  const L = st.layerById.get('module-' + sym);
  if (L) {
    const d = await layerDoc(L.file);
    const keys = [], props = [];
    for (const f of d.features) {
      const ks = f.geometry?.type === 'Point' ? [f.geometry.key] : (f.geometry?.keys || []);
      for (const k of ks) { keys.push(k); props.push({ block: sym, function: f.properties?.function, family: f.properties?.family, via: L.id }); }
    }
    return { keys, props, colour: L.colour, via: `layer ${L.id} (${L.label})` };
  }
  const B = st.layerById.get('blocks');
  if (B) {
    const d = await layerDoc(B.file);
    const feats = d.features.filter(f => f.properties?.block === sym && f.geometry?.type === 'Point');
    if (feats.length) return { keys: feats.map(f => f.geometry.key), props: feats.map(f => ({ block: sym, function: f.properties.function, family: f.properties.family, via: 'blocks' })), colour: B.colour, via: `first lines in layer blocks` };
  }
  return { keys: [], props: [], colour: null, via: null };
}

let tapSeq = 0;
async function tapSpider(i, fromLink = false) {
  const seq = ++tapSeq;
  const s = st.graphs.get(st.current); if (!s?.graph) return;
  const n = s.graph.nodes[i];
  spider.focus(i);
  if (!fromLink) { writeSelection(n); linkBox(null); }
  let refs = nodeRefs(st.current, n);
  if (!st.reg) { say('<p class="dim">The block register is still loading.</p>'); return; }
  if (refs.kind === 'family' && !st.families) { say(`<h2>${esc(n.label)}</h2><p class="dim">This node names family ${refs.family}; loading the family index…</p>`); await ensureFamilies(); if (seq !== tapSeq) return; computeBridge(); spider.setBridge(st.bridge); measureBridge(); }
  const cp = counterpart(refs, st.reg, st.families);
  const head = `<h2>${esc(n.label)}</h2><dl>
    <dt>spider type</dt><dd>${esc(n.type)}</dd>
    <dt>status label</dt><dd>${esc(n.rag)} <span class="dim">(the spider's own label${n.reason ? ': ' + esc(n.reason.replace(/<[^>]*>/g, ' ').slice(0, 220)) : ''})</span></dd>
    <dt>names</dt><dd>${esc(refs.kind === 'path' ? refs.repo + (refs.path ? '/' + refs.path : ' (whole repository)') : refs.kind === 'family' ? 'family ' + refs.family : refs.kind === 'block' ? 'block ' + refs.block : 'nothing numbered')} <span class="dim">· ${esc(refs.method)}</span></dd>
    ${receiverRow(n)}
    ${atlasRow(n, seq)}
  </dl>`;
  wafer.unwakeAll(id => id === 'blocks');
  if (cp.state !== 'known') {
    say(head + `<p class="refuse">Not in the numbered universe yet: ${esc(cp.why)}.</p>`);
    return;
  }
  say(head + `<p class="known">${esc(cp.why)}</p><p class="dim">waking its lines…</p>`);
  const woke = [];
  if (refs.kind === 'family') {
    if (!(await ensureFamLines())) return;
    if (seq !== tapSeq) return;
    const f = cp.family, keys = Array.from(st.famLines.subarray(f.lineOffset, f.lineOffset + f.lineCount));
    wafer.wake('fam-' + f.n, '#ff8c00', keys, keys.map(() => ({ block: f.block, function: f.name, family: f.n, via: 'family' })));
    woke.push(`family ${f.n} ${esc(f.name)}: ${fmt(keys.length)} lines`);
    if (keys.length) wafer.frame('fam-' + f.n);
  } else {
    const blocks = cp.blocks.slice(0, MAX_BLOCKS_WOKEN);
    const results = await Promise.all(blocks.map(async sym => { try { return [sym, await keysForBlock(sym)]; } catch (e) { return [sym, { keys: [], error: e.message }]; } }));
    if (seq !== tapSeq) return;
    let first = null;
    for (const [sym, r] of results) {
      if (r.keys.length) { wafer.wake('blk-' + sym, r.colour || '#00cc00', r.keys, r.props); first ??= 'blk-' + sym; woke.push(`block ${esc(sym)}: ${fmt(r.keys.length)} lines, ${esc(r.via)}`); }
      else woke.push(`block ${esc(sym)}: <span class="refuse">${r.error ? 'layer failed: ' + esc(r.error) : 'in the register, but no layer charts numbered lines for it'}</span>`);
    }
    if (cp.blocks.length > MAX_BLOCKS_WOKEN) woke.push(`<span class="dim">${fmt(cp.blocks.length - MAX_BLOCKS_WOKEN)} more blocks not woken (at most ${MAX_BLOCKS_WOKEN} per node)</span>`);
    if (first) wafer.frame(first);
  }
  say(head + `<p class="known">${esc(cp.why)}</p><ul>${woke.map(w => `<li>${w}</li>`).join('')}</ul><p class="dim">Tap a lit line on the wafer to come back.</p>`);
}

function receiverRow(n) {
  if (!st.contract) return '';
  const urls = [n.gh, n.ext].filter(Boolean);
  const retired = urls.filter(u => st.contract.isRetiredReceiver(u));
  const canon = urls.filter(u => u.startsWith(st.contract.CANONICAL_RECEIVER));
  const atlas = urls.filter(u => /gridatlas|repd_grid_atlas/i.test(u));
  if (!atlas.length && !retired.length) return '';
  return `<dt>Grid Atlas</dt><dd>${retired.length ? '<span class="refuse">links a retired receiver</span> ' : ''}${canon.length ? 'links the canonical receiver ' : ''}${!retired.length && !canon.length ? 'names Grid Atlas source, not a receiver' : ''} <span class="dim">(deeplink/contract.js isRetiredReceiver)</span></dd>`;
}

function tapWafer(x, y) {
  const hit = wafer.pickWoken(x, y);
  const s = st.graphs.get(st.current);
  if (!hit) { spider.highlight([]); say('<p class="dim">No lit line within reach. Only woken lines answer a tap; tap a spider node or wake the named functions first.</p>'); return; }
  const p = hit.props || {};
  const g = st.manifest.graphs.find(x => x.id === st.current);
  const head = `<h2>Line <span class="n">${fmt(hit.key)}</span></h2><dl>
    <dt>block</dt><dd>${esc(p.block ?? 'none recorded')}${p.block && st.reg?.bySymbol.get(p.block) ? ' · ' + esc(st.reg.bySymbol.get(p.block).title) : ''}</dd>
    <dt>function</dt><dd>${esc(p.function ?? 'none recorded')}${p.family != null ? ' · family ' + p.family : ''}</dd>
    <dt>woken by</dt><dd>${esc(p.via ?? '')}</dd></dl>`;
  if (!s?.graph || !p.block) { spider.highlight([]); say(head + `<p class="refuse">No spider graph is drawn, or the line carries no block, so no spider node can be named.</p>`); return; }
  const list = nodesForBlock(p.block, p.family, st.current, s.graph.nodes, st.reg);
  spider.highlight(list);
  if (!list.length) {
    const b = st.reg.bySymbol.get(p.block);
    const files = b ? b.files.map(f => f.repo + '/' + f.path) : [];
    say(head + `<p class="refuse">No node of ${esc(g.title)} names block ${esc(p.block)}${p.family != null ? ', family ' + p.family : ''} or a file of that block.</p>`
      + (files.length ? `<p class="dim">The register places block ${esc(p.block)} in ${fmt(files.length)} file(s), first: ${esc(files[0])}.</p>` : `<p class="dim">The live register records no file for block ${esc(p.block)}.</p>`));
    return;
  }
  say(head + `<p class="known">${fmt(list.length)} node(s) of ${esc(g.title)} lit on the spider:</p><ul>${list.slice(0, 10).map(([i, why]) => `<li>${esc(s.graph.nodes[i].label)} <span class="dim">· ${esc(why)}</span></li>`).join('')}</ul>${list.length > 10 ? `<p class="dim">first ten of ${fmt(list.length)} listed; all are ringed on the spider.</p>` : ''}`);
}

/* ── links in and out: ?graph= ?node= ?key= ?repo= ?path= (link.mjs) ─────────
   A link selects nodes exactly as a manual tap does (tapSpider). A manual tap
   or graph choice writes the selection back with replaceState, keeping every
   parameter it does not own. */
const OWN = ['node', 'key', 'repo', 'path'];
function replaceQuery(edit) {
  const u = new URL(location.href);
  edit(u.searchParams);
  const next = u.pathname + u.search + u.hash;
  if (next !== location.pathname + location.search + location.hash) history.replaceState(history.state, '', next);
}
function writeSelection(n) {
  const r = nodeRefs(st.current, n);
  replaceQuery(q => {
    q.set('graph', st.current); for (const k of OWN) q.delete(k);
    q.set('node', String(n.id));
    if (r.kind === 'block') q.set('key', 'block:' + r.block);
    else if (r.kind === 'family') q.set('key', 'family:' + r.family);
    else if (r.kind === 'path') { q.set('repo', r.repo); if (r.path) q.set('path', r.path); }
  });
}
function writeGraphChoice(id) { replaceQuery(q => { q.set('graph', id); for (const k of OWN) q.delete(k); }); }

/* The link strip: warnings (always, while the link carries them) and the outcome. */
function linkBox(outcome) {
  const box = $('linkBox'), L = st.link;
  const warn = L && L.warnings.length ? `<p class="refuse">Link warning${L.warnings.length > 1 ? 's' : ''}:</p><ul>${L.warnings.map(w => `<li class="refuse">${esc(w)}</li>`).join('')}</ul>` : '';
  box.innerHTML = warn + (outcome || '');
  box.hidden = !box.innerHTML;
}

const byIndex = list => { const m = new Map(); for (const [i, why] of list) if (!m.has(i)) m.set(i, why); return [...m]; };

/* Which nodes of the drawn graph a link parameter names, and how. */
async function linkMatches(kind) {
  const L = st.link, s = st.graphs.get(st.current), nodes = s.graph.nodes, gid = st.current;
  if (kind === 'node') {
    const i = nodes.findIndex(n => String(n.id) === L.node);
    return { list: i < 0 ? [] : [[i, 'node id ' + L.node]], why: i < 0 ? `no node has the id "${L.node}"` : '' };
  }
  if (kind === 'repo') {
    const direct = [];
    nodes.forEach((n, i) => { const r = nodeRefs(gid, n); if (r.kind === 'path' && r.repo === L.repo && pathCovers(r.path, L.path || '')) direct.push([i, 'names ' + r.repo + (r.path ? '/' + r.path : '')]); });
    const files = (st.reg.byRepo.get(L.repo) || []).filter(f => pathCovers(L.path || '', f.path));
    const syms = [...new Set(files.map(f => f.symbol))];
    const via = syms.flatMap(sym => nodesForBlock(sym, null, gid, nodes, st.reg).map(([i, w]) => [i, w + ' (the register places block ' + sym + ' at this path)']));
    return { list: byIndex([...direct, ...via]), why: `the live register records ${fmt(files.length)} file(s) at or under ${L.repo}${L.path ? '/' + L.path : ''}${syms.length ? ' (blocks ' + syms.join(', ') + ')' : ''}, and no node names that path or those blocks` };
  }
  const k = L.key;
  if (k.kind === 'block') {
    const list = nodesForBlock(k.block, null, gid, nodes, st.reg);
    list.sort((a, b) => (b[1].startsWith('names block') ? 1 : 0) - (a[1].startsWith('names block') ? 1 : 0));
    return { list, why: st.reg.bySymbol.has(k.block) ? `block ${k.block} is in the live register, but no node names it or a file of it` : `block ${k.block} is not in the live register, and no node names it` };
  }
  if (!(await ensureFamilies())) return { list: [], why: 'the family index could not load' };
  const famList = [];
  if (k.kind === 'family') {
    const f = st.families.get(k.family);
    if (!f) return { list: [], why: `family ${k.family} is not in the numbered database` };
    famList.push(f);
  } else {
    if (!(await ensureFamLines())) return { list: [], why: 'the family line index could not load' };
    for (const f of st.famArr) {
      const sub = st.famLines.subarray(f.lineOffset, f.lineOffset + f.lineCount);
      if (sub.includes(k.line)) famList.push(f);
    }
    if (!famList.length) return { list: [], why: `line ${k.line} is carried by no numbered function family, so no block or family can name it` };
  }
  const list = [];
  for (const f of famList) {
    nodes.forEach((n, i) => { const r = nodeRefs(gid, n); if (r.kind === 'family' && r.family === f.n) list.push([i, 'names family ' + f.n]); });
    if (f.block) list.push(...nodesForBlock(f.block, f.n, gid, nodes, st.reg).map(([i, w]) => [i, w + ' (family ' + f.n + ' ' + f.name + ')']));