GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / galaxies-wafers / iterations/46-chemistry-ledger

Grid and 9 more files

A JavaScript module in the iterations folder of Galaxies Wafers that draws elements and functions, using haversine, and uses data from the elements repository. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/48-grid-challenge/.

698 lines of JavaScript and HTML and CSS from galaxies-wafers, in 10 files. Topic: Kuiper, cosmos and drawing engines. Section 1227 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. Cl render · galaxies-wafers / iterations/46-chemistry-ledger/cl.css lines 1–59
  2. Iterations — 46 Chemistry Ledger Page render · galaxies-wafers / iterations/46-chemistry-ledger/index.html lines 1–61
  3. Ledger ingest · galaxies-wafers / iterations/46-chemistry-ledger/ledger.mjs lines 1–87
  4. Grid render · galaxies-wafers / iterations/48-grid-challenge/grid.mjs lines 1–177
  5. Iterations — 48 Grid Challenge Page render · galaxies-wafers / iterations/48-grid-challenge/index.html lines 1–40
  6. Iterations — 48 Grid Challenge Style Sheet render · galaxies-wafers / iterations/48-grid-challenge/style.css lines 1–31
  7. Galaxies Wafers — Iterations Page render · galaxies-wafers / iterations/index.html lines 1–92
  8. Galaxies Wafers — Lib ingest · galaxies-wafers / lib.mjs lines 1–119
  9. Judge Check other · galaxies-wafers / proof/browser/judge.check.mjs lines 1–22
  10. Judge transform · galaxies-wafers / proof/browser/judge.mjs lines 1–10

Cl

A style sheet in the iterations folder of Galaxies Wafers. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/46-chemistry-ledger/.

rendergalaxies-wafers / iterations/46-chemistry-ledger/cl.css · lines 1–59 of 59 · Entry point

What it does
Side effects: changes the web page (DOM).
Downstream impact
Used directly by 1 file: Iterations — 46 Chemistry Ledger Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/46-chemistry-ledger/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/46-chemistry-ledger/.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
Loaded by the 46 Chemistry Ledger page at https://ventusltd.github.io/galaxies-wafers/iterations/46-chemistry-ledger/.
Application
galaxies-wafers · iterations/46-chemistry-ledger · style sheet
Uses
none found
Used by
loaded by Iterations — 46 Chemistry Ledger 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/46-chemistry-ledger/cl.css:1-59 · blob 1ab78505db40b5018f1f10f833aad59b922baae4 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
:root{--ink:#d8dee9;--dim:#8b93a7;--ground:#0b0d12;--edge:#1b2030;--lit:#ffd54a;--beam:#5ec8f2;--wire:#efe9dc}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--ground);color:var(--ink);font:13px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
  padding:calc(env(safe-area-inset-top,0px) + .8rem) 1rem calc(env(safe-area-inset-bottom,0px) + 2rem)}
main{max-width:60rem;margin:0 auto}
h1{font-size:14px;letter-spacing:.18em;font-weight:600;margin:0 0 .35rem;color:#fff}
h2{font-size:11px;letter-spacing:.14em;font-weight:400;color:var(--dim);margin:1.2rem 0 .4rem}
p{margin:.35rem 0}
.dim{color:var(--dim)} .small{font-size:11.5px}
a{color:var(--beam)}
code{color:var(--beam);overflow-wrap:anywhere}
q{quotes:"\201C" "\201D"}
.summary{border-left:3px solid var(--wire);padding:.35rem .6rem;background:#10131b;margin:.6rem 0}
.summary b{color:#fff}
.layers{display:grid;gap:.2rem;margin:.6rem 0}
.layer{display:flex;align-items:center;gap:.55rem;min-height:40px;padding:0 .2rem;border-bottom:1px solid var(--edge);cursor:pointer}
.layer input{width:20px;height:20px;accent-color:#d8dee9;flex:none}
.layer span{overflow-wrap:anywhere}
.seg{display:flex;flex-wrap:wrap;gap:.35rem;margin:.5rem 0}
.seg button{font:inherit;color:var(--ink);background:#07080c;border:1px solid var(--edge);border-radius:.35rem;padding:.45rem .6rem;min-height:40px}
.seg button[aria-pressed=true]{border-color:#fff;box-shadow:inset 0 0 0 1px #fff}
.plane{position:relative;margin:.4rem -1rem 0;height:min(90vw,520px);background:#05060a;border-top:1px solid var(--edge);border-bottom:1px solid var(--edge)}
#plane{display:block;width:100%;height:100%;touch-action:manipulation;cursor:crosshair}
.fit{position:absolute;right:.6rem;top:.6rem;font:inherit;color:var(--ink);background:#0b0d12e6;border:1px solid var(--edge);border-radius:.35rem;min-width:44px;min-height:40px}
.drawn{position:absolute;left:.6rem;bottom:.35rem;font-size:10.5px;pointer-events:none}
.card{border:1px solid var(--edge);border-radius:.45rem;background:#10131b;padding:.55rem .7rem;margin:.7rem 0;overflow-wrap:anywhere}
.card h3{margin:0 0 .35rem;font-size:14px;color:#fff;font-weight:600}
.card .msg{display:block;background:#05060a;border:1px solid var(--edge);border-left:3px dashed var(--wire);padding:.4rem .5rem;margin:.35rem 0;color:#fff;font-size:12.5px}
.card dl{display:grid;grid-template-columns:minmax(6.5rem,auto) 1fr;gap:.25rem .7rem;margin:.4rem 0}
.card dt{color:var(--dim)} .card dd{margin:0}
.card .big{font-size:15px;color:#fff;font-weight:600}
.rows{list-style:none;margin:0;padding:0;display:grid;gap:.4rem}
.rows button{all:unset;display:block;box-sizing:border-box;width:100%;cursor:pointer;border:1px solid var(--edge);border-radius:.4rem;background:#07080c;padding:.45rem .55rem;min-height:44px;overflow-wrap:anywhere}
.rows button:focus-visible{outline:1px solid #fff}
.rows button.on{border-color:#fff}
.rows .t{color:#fff}
.rows li.plain{border:1px solid var(--edge);border-radius:.4rem;padding:.45rem .55rem;overflow-wrap:anywhere}
.questions{border:1px solid var(--edge);border-radius:.45rem;background:#10131b;padding:0 .65rem;margin:1.2rem 0 .5rem}
.questions summary{font-size:11px;letter-spacing:.14em;text-transform:uppercase;cursor:pointer;color:var(--beam);min-height:40px;display:flex;align-items:center}
.questions dt{color:#fff;margin-top:.5rem;font-size:12px}
.questions dd{margin:.2rem 0 .6rem;font-size:11.5px;overflow-wrap:anywhere}
.machine{border-left:3px solid var(--beam);padding:.35rem .6rem;background:#07080c;overflow-wrap:anywhere}
footer{margin-top:1.2rem;overflow-wrap:anywhere}
@media (min-width:900px){.plane{margin:.4rem 0 0;border:1px solid var(--edge);border-radius:.45rem}}
.grid{display:grid;gap:.5rem;margin:.5rem 0}
.row h3{margin:.2rem 0;font-size:11px;letter-spacing:.12em;color:var(--dim);font-weight:400}
.cells{display:grid;grid-template-columns:repeat(auto-fill,minmax(4.6rem,1fr));gap:.25rem}
.cell{all:unset;box-sizing:border-box;cursor:pointer;border:1px solid var(--edge);border-radius:.3rem;background:#07080c;padding:.25rem .3rem;min-height:44px;font-size:10.5px;line-height:1.25;overflow-wrap:anywhere}
.cell b{display:block;color:#fff;font-size:12px;font-weight:600}
.cell .n{color:var(--dim)}
.cell.on{border-color:#fff;box-shadow:inset 0 0 0 1px #fff}
.grid.filter .cell{opacity:.28}
.grid.filter .cell.match{opacity:1;border-color:var(--wire);border-style:dashed}
.card table{border-collapse:collapse;width:100%;font-size:11.5px}
.card td{border-top:1px solid var(--edge);padding:.25rem .3rem;vertical-align:top}
.card td.k{text-align:right;color:#fff;white-space:nowrap}
.more{font:inherit;color:var(--ink);background:#07080c;border:1px solid var(--edge);border-radius:.35rem;min-height:40px;padding:0 .7rem;margin-top:.4rem}
.rule{border-left:3px solid var(--wire);padding:.3rem .55rem;background:#07080c;margin:.4rem 0}

Iterations — 46 Chemistry Ledger Page

A web page in Galaxies Wafers that reads inputs for open ledger and open graph. Published at https://ventusltd.github.io/galaxies-wafers/iterations/46-chemistry-ledger/.

rendergalaxies-wafers / iterations/46-chemistry-ledger/index.html · lines 1–61 of 61 · 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
It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/46-chemistry-ledger/.
What it achieves
The README says: The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
galaxies-wafers · iterations/46-chemistry-ledger · page
Uses
Cl (stylesheet), Iterations — 37 Hidden Wires Page (link), Iterations — 46 Chemistry Ledger (script src)
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/46-chemistry-ledger/index.html:1-61 · blob e779374a4f44b71f42c83e8ce31d6e5919eb90b2 · GitHub at these lines
State
achieves: readme · 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">
<meta name="color-scheme" content="dark">
<title>Chemistry Ledger</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="cl.css">
</head>
<body>
<main>
  <header>
    <h1>CHEMISTRY LEDGER</h1>
    <p class="dim">star-maker drove compositions of parts in a browser and recorded each as a star. A <b>compound</b> is one composition; its <b>elements</b> are the parts in it (a cartridge by symbol, with a version stamp when one was pinned). A compound <b>decays</b> when it produces an exception. Every number below is counted by this page from the published files when you open the ledger.</p>
    <p id="summary" class="summary">WAIT — nothing is fetched until you open the ledger.</p>
  </header>

  <section class="layers" aria-label="Layers">
    <label class="layer"><input type="checkbox" id="open-ledger"><span id="lbl-ledger">Ledger · compounds.json + CHEMISTRY.md [WAIT]</span></label>
    <label class="layer"><input type="checkbox" id="open-graph"><span id="lbl-graph">Graph · graph.json edges [WAIT]</span></label>
  </section>

  <h2>ELEMENTS</h2>
  <div class="seg" id="mode" role="group" aria-label="Show">
    <button type="button" data-m="all" aria-pressed="true">all counts</button>
    <button type="button" data-m="noble" aria-pressed="false">noble</button>
    <button type="button" data-m="radioactive" aria-pressed="false">radioactive</button>
  </div>
  <p id="rule" class="rule small dim">Rules are read from CHEMISTRY.md when the ledger opens.</p>
  <p class="dim small">Each cell: element · compositions it appears in · compositions with a green star / with a red star.</p>
  <div id="grid" class="grid"><p class="dim">WAIT — tick Ledger.</p></div>

  <section id="card" class="card" aria-live="polite">
    <p class="dim">Tap an element to read its failure messages and its compounds.</p>
  </section>

  <h2>GRAPH · <span id="graphcount">not loaded</span></h2>
  <div class="plane">
    <canvas id="plane" aria-label="Chemistry graph. Elements on the outer ring, decay messages inside. Tap a node to read it."></canvas>
    <div id="drawn" class="drawn dim"></div>
  </div>
  <p class="dim small">Outer ring: element nodes of graph.json, sorted by label. Inner ring: its decay nodes. Faint solid lines: UNSTABLE_WITH. Dashed lines: DECAYS_TO. Only edges whose two ends are both nodes in the file are drawn.</p>

  <details id="questions" class="questions">
    <summary>Questions</summary>
    <dl>
      <dt>1. How does this help draw a system or a single-line diagram?</dt>
      <dd>It draws no busbar, feeder, transformer, cable route, protection or earthing. It feeds the <b>single-line panel</b> indirectly: it shows which compositions of parts let the sld-sandbox cartridge (<b>Ss</b>, the part that draws the SLD panel) run. Counted from <code>compounds[].decays[].text</code>: the text <q>sld-sandbox requires the sld-styles module</q> appears in <span id="q-styles">  … [line shortened here: 635 characters; full line on GitHub]
      <dt>2. What is this code used for?</dt>
      <dd>This page: <code>ledger.mjs</code> <code>parts</code>, <code>splitElement</code>, <code>countElements</code>, <code>readRules</code>, <code>isNoble</code>, <code>isRadioactive</code>, <code>drawableEdges</code>, <code>decayTotals</code>, <code>layout</code>; drawn by <code>app.mjs</code>. It reads star-maker <code>chemistry/compounds.json</code>, <code>chemistry/graph.json</code> and <co  … [line shortened here: 759 characters; full line on GitHub]
      <dt>3. Where does it lead next?</dt>
      <dd>To <a href="../37-hidden-wires/">iterations/37-hidden-wires</a>, which draws each decay text as a wire from the failing part to the module it names, and checks whether the register now declares it. Radioactive elements found here: <span id="q-rad">not yet known</span>.</dd>
    </dl>
  </details>
  <p id="machine" class="machine small">Machine detail · not yet known: tick Ledger.</p>
  <footer class="dim small">Source: star-maker, public repository, pinned commit shown above. Screening-grade record of software compositions; it says nothing about any electrical asset.</footer>
</main>
<script type="module" src="app.mjs"></script>
</body>
</html>

Ledger

A JavaScript module in the iterations folder of Galaxies Wafers that splits element (`splitElement`), counts elements (`countElements`) and reads rules (`readRules`). Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/46-chemistry-ledger/.

ingestgalaxies-wafers / iterations/46-chemistry-ledger/ledger.mjs · lines 1–87 of 87 · pattern parts (shared by 7 files)

What it does
It lists and searches its content. Defines 9 functions or classes, including parts, splitElement, countElements, readRules, isNoble.
Downstream impact
Used directly by 1 file: Iterations — 46 Chemistry Ledger (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/46-chemistry-ledger/). Reached from 1 other entry point, including Iterations — 46 Chemistry Ledger Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/46-chemistry-ledger/).
What it achieves
It splits element (`splitElement`), counts elements (`countElements`) and reads rules (`readRules`). The arithmetic of the Chemistry Ledger.
Why it matters
Imported by Iterations — 46 Chemistry Ledger.
Application
galaxies-wafers · iterations/46-chemistry-ledger · JavaScript module
Uses
none found
Used by
imported by Iterations — 46 Chemistry Ledger (import)
Produces
SEP, parts, splitElement, countElements, readRules, isNoble, isRadioactive, drawableEdges, decayTotals, layout
Defines here
parts, splitElement, countElements, readRules, isNoble, isRadioactive, drawableEdges, decayTotals, layout
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/46-chemistry-ledger/ledger.mjs:1-87 · blob 9eabdc7ffc98f4458af16f7f30475a8bdfc6bdad · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
/* ledger.mjs — the arithmetic of the Chemistry Ledger. No DOM, no fetch.
   Everything here counts what star-maker's chemistry files contain. */

export const SEP = '\u00b7'; // the middle dot star-maker writes between elements

/* "Si(202609030137)·Sp·Ss(202609072337)·Ug" -> ["Si(202609030137)","Sp",...] */
export function parts(formula) {
  return String(formula).split(SEP).map(s => s.trim()).filter(Boolean);
}

/* "Si(202609030137)" -> { symbol:"Si", stamp:"202609030137" }; "Shell" -> { symbol:"Shell", stamp:null } */
export function splitElement(label) {
  const m = /^([A-Za-z]+)(?:\(([^)]*)\))?$/.exec(label);
  return m ? { symbol: m[1], stamp: m[2] == null ? null : m[2] } : { symbol: label, stamp: null };
}

/* One pass over compounds[]: per element, how many compositions carry it,
   how many of those produced a red / green / amber star, star totals, and
   the decay texts grouped. */
export function countElements(compounds) {
  const map = new Map();
  compounds.forEach((c, idx) => {
    for (const p of new Set(parts(c.formula))) {
      let e = map.get(p);
      if (!e) {
        e = { label: p, ...splitElement(p), compounds: 0, redCompounds: 0, greenCompounds: 0, amberCompounds: 0,
              stars: 0, green: 0, amber: 0, red: 0, decays: new Map(), idx: [], kinds: {} };
        map.set(p, e);
      }
      e.compounds++;
      if (c.red > 0) e.redCompounds++;
      if (c.green > 0 && c.red === 0 && c.amber === 0) e.greenCompounds++;
      if (c.amber > 0) e.amberCompounds++;
      e.stars += c.stars; e.green += c.green; e.amber += c.amber; e.red += c.red;
      e.kinds[c.kind] = (e.kinds[c.kind] || 0) + 1;
      e.idx.push(idx);
      for (const d of c.decays || []) {
        const g = e.decays.get(d.text) || { text: d.text, stars: 0, compounds: 0 };
        g.stars += d.n; g.compounds++;
        e.decays.set(d.text, g);
      }
    }
  });
  return map;
}

/* Rules as CHEMISTRY.md states them in its own section headings. Returns the
   thresholds and the 1-based line numbers, or a reason when not found. */
export function readRules(md) {
  const lines = String(md).split(/\r?\n/);
  const out = { noble: null, radioactive: null };
  lines.forEach((line, i) => {
    let m = /^##\s*Noble elements\s*\((.*never in a red compound,\s*\u2265\s*(\d+)\s*compounds.*)\)/i.exec(line);
    if (m) out.noble = { line: i + 1, text: line.replace(/^##\s*/, ''), minCompounds: Number(m[2]) };
    m = /^##\s*Radioactive elements\s*\((.*red in\s*\u2265\s*(\d+)\s*%\s*of their compounds.*)\)/i.exec(line);
    if (m) out.radioactive = { line: i + 1, text: line.replace(/^##\s*/, ''), minRedShare: Number(m[2]) / 100 };
  });
  return out;
}

export function isNoble(e, rule) { return !!rule && e.redCompounds === 0 && e.compounds >= rule.minCompounds; }
export function isRadioactive(e, rule) { return !!rule && e.compounds > 0 && e.redCompounds / e.compounds >= rule.minRedShare; }

/* Graph edges whose both ends are nodes in graph.json. */
export function drawableEdges(graph) {
  const labels = new Set((graph.nodes || []).map(n => n.label));
  const kept = [], dropped = [];
  for (const e of graph.edges || []) (labels.has(e.from) && labels.has(e.to) ? kept : dropped).push(e);
  return { kept, dropped };
}

/* Compositions carrying one decay text, and the stars counted on it. */
export function decayTotals(compounds, needle) {
  let compositions = 0, stars = 0;
  for (const c of compounds) for (const d of c.decays || []) if (d.text.includes(needle)) { compositions++; stars += d.n; }
  return { compositions, stars };
}

/* Deterministic layout: elements on a ring grouped by symbol then stamp; decay nodes on an inner ring. */
export function layout(nodes) {
  const els = nodes.filter(n => n.type === 'element').slice().sort((a, b) => a.label < b.label ? -1 : a.label > b.label ? 1 : 0);
  const others = nodes.filter(n => n.type !== 'element');
  const pos = new Map();
  els.forEach((n, i) => { const t = -Math.PI / 2 + 2 * Math.PI * i / Math.max(1, els.length); pos.set(n.label, { x: Math.cos(t), y: Math.sin(t), n }); });
  others.forEach((n, i) => { const t = -Math.PI / 2 + 2 * Math.PI * i / Math.max(1, others.length); pos.set(n.label, { x: 0.32 * Math.cos(t), y: 0.32 * Math.sin(t), n }); });
  return pos;
}

Grid

A JavaScript module in the iterations folder of Galaxies Wafers that draws elements and functions, using haversine, and uses data from the elements repository. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/48-grid-challenge/.

rendergalaxies-wafers / iterations/48-grid-challenge/grid.mjs · lines 1–177 of 177 · Entry point · pattern catalogue (shared by 4 files)

What it does
It draws elements, functions, interconnectors and substations. Defines 14 functions or classes, including $, el, enqueue, pump, getJSON. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain terms in the code: interconnectors, substations.
Inputs & outputs
In: data source: elements data; JSON file elements.json; JSON file functions.json.
Downstream impact
Used directly by 1 file: Iterations — 48 Grid Challenge Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/48-grid-challenge/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/48-grid-challenge/.
What it achieves
It gets JSON (`getJSON`), matches element (`matchElement`) and renders counts (`renderCounts`). Which Element Meets Which Grid Question. It responds to toggle events.
Why it matters
Loaded by the 48 Grid Challenge page at https://ventusltd.github.io/galaxies-wafers/iterations/48-grid-challenge/.
Application
galaxies-wafers · iterations/48-grid-challenge · JavaScript module
Uses
none found
Used by
loaded by Iterations — 48 Grid Challenge Page (script src)
Produces
QUESTIONS, matchElement
Defines here
$, el, enqueue, pump, getJSON, catalogue, esc, wordRe, matchElement, highlighted, assemblyButton, appButton, renderCounts, openQuestion
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/48-grid-challenge/grid.mjs:1-177 · blob c9e5c94b8aecc199b0c1d259d9e0c0c30f28f425 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
/* grid.mjs — Which Element Meets Which Grid Question.
 * A lens over the elements catalogue. Grid Atlas loading grammar: every question row
 * exists from the start, nothing is fetched until a reader opens one; one queue of 4,
 * a 15 s AbortController timeout per fetch, one shared promise per URL (a failure leaves
 * the cache so a retry is possible); each question fills itself once and only its own
 * status span changes. No physics is computed here. */
const CAT_COMMIT = 'f7a92fb085c38dcbbd5cb469a66cd5ca61fb95bf';   /* Ventusltd/elements main when this page was built */
const CAT = `https://raw.githubusercontent.com/Ventusltd/elements/${CAT_COMMIT}/catalogue/`;
const ENGINE_COMMIT = 'd9cd18b0e2034325814924e6e4a0e958014f2748';
const CONCURRENCY = 4, FETCH_MS = 15000;
const LABEL = 'matched by words in the element’s own title or description — not a claim the element answers it';

/* The fixed list. galaxy = the iteration that demonstrates the question; modules are the
   engine modules that iteration imports (read from its source when this page was built). */
export const QUESTIONS = [
  { id: 'nearest', q: 'Where is the nearest mapped substation to a point?', terms: ['substation', 'substations', 'nearest'],
    galaxy: [{ dir: '28-nearest-search-trap', name: 'The Nearest-Search Trap', modules: ['v9-nearest-search.js', 'v9-geodesy.js'] }] },
  { id: 'route', q: 'How long is the cable route between two points?', terms: ['route', 'routes', 'distance', 'length', 'haversine'],
    galaxy: [{ dir: '27-earth-radii-and-argument-order', name: 'Earth radii and argument order', modules: ['geo-core.js', 'corridor-estimate.js'] }] },
  { id: 'current', q: 'What current flows at this power and voltage?', terms: ['current', 'amps', 'ampacity', 'power factor'],
    galaxy: [{ dir: '25-one-feeder', name: 'One Feeder', modules: ['current-from-power.js', 'power-factor.js'] }] },
  { id: 'vdrop', q: 'How much voltage is lost along a cable?', terms: ['voltage drop', 'volt drop', 'voltage'],
    galaxy: [{ dir: '25-one-feeder', name: 'One Feeder', modules: ['voltage-drop.js'] }] },
  { id: 'ratings', q: 'Which circuits and ratings exist at a site?', terms: ['rating', 'ratings', 'circuit', 'circuits'],
    galaxy: [{ dir: '29-rating-envelope', name: 'Ratings That Do Not Add', modules: ['rating-envelope.js', 'network-topology.js'] }] },
  { id: 'meanings', q: 'Which kilowatt is meant: connected load, peak demand or energy?', terms: ['electrification', 'kilowatt', 'kw'],
    galaxy: [{ dir: '24-electrification-model', name: 'Seven Meanings', modules: ['electrification-model.js'] }] },
  { id: 'diversity', q: 'What demand arrives after diversity?', terms: ['diversity', 'diversified', 'demand'],
    galaxy: [{ dir: '13-diversified-demand', name: 'Demand lab', modules: ['diversified-demand.js'] }] },
  { id: 'firm', q: 'What capacity remains when the largest unit is out?', terms: ['firm', 'largest unit', 'n-1', 'capacity'],
    galaxy: [{ dir: '16-firm-capacity', name: 'Firm arithmetic', modules: ['firm-capacity.js'] }] },
  { id: 'ic', q: 'What does an interconnector earn gross from a price spread?', terms: ['interconnector', 'interconnectors', 'price spread', 'spread'],
    galaxy: [{ dir: '15-price-spread', name: 'Spread lab', modules: ['interconnector-economics.js'] }] },
  { id: 'system', q: 'How does one system connect, stop by stop, from site to network?', terms: ['topology', 'network', 'connection'],
    galaxy: [{ dir: '35-system-journey', name: 'One System, Stop by Stop', modules: ['network-topology.js', 'rating-envelope.js', 'voltage-drop.js'] }] },
];

const $ = id => document.getElementById(id);
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text !== undefined) e.textContent = text; return e; };

/* ── bounded queue + url cache ── */
let active = 0; const waiting = [];
function enqueue(job) { return new Promise((res, rej) => { waiting.push({ job, res, rej }); pump(); }); }
function pump() {
  while (active < CONCURRENCY && waiting.length) {
    const { job, res, rej } = waiting.shift(); active++;
    job().then(res, rej).finally(() => { active--; pump(); });
  }
}
const cache = new Map();
let fetchCount = 0;
function getJSON(url) {
  if (cache.has(url)) return cache.get(url);
  const p = enqueue(async () => {
    const ac = new AbortController(); const t = setTimeout(() => ac.abort(), FETCH_MS);
    fetchCount++;
    try {
      const r = await fetch(url, { signal: ac.signal });
      if (!r.ok) throw new Error(`HTTP ${r.status} for ${url}`);
      return await r.json();
    } catch (e) { throw new Error(e.name === 'AbortError' ? `timed out after ${FETCH_MS / 1000} s: ${url}` : e.message); }
    finally { clearTimeout(t); }
  });
  cache.set(url, p);
  p.catch(() => cache.delete(url));
  return p;
}

let CATALOGUE = null;
async function catalogue() {
  if (CATALOGUE) return CATALOGUE;
  $('catstate').textContent = 'LOAD · elements.json and functions.json';
  const [elements, functions] = await Promise.all([getJSON(CAT + 'elements.json'), getJSON(CAT + 'functions.json')]);
  const fn = new Map(functions.map(f => [f.key, f]));
  CATALOGUE = { elements, fn };
  $('catstate').textContent = `OK · ${elements.length.toLocaleString('en-GB')} elements, ${functions.length.toLocaleString('en-GB')} functions at commit ${CAT_COMMIT.slice(0, 7)}`;
  return CATALOGUE;
}

/* whole-word, case-insensitive; returns the distinct terms found */
const esc = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const wordRe = terms => new RegExp(`(^|[^a-z0-9])(${terms.slice().sort((a, b) => b.length - a.length).map(esc).join('|')})(?=[^a-z0-9]|$)`, 'gi');
export function matchElement(e, terms) {
  const found = new Set();
  for (const text of [e.title || '', e.description || '']) {
    const re = wordRe(terms); let m;
    while ((m = re.exec(text))) { found.add(m[2].toLowerCase()); re.lastIndex = m.index + m[0].length; }
  }
  return [...found];
}
function highlighted(text, terms) {
  const frag = document.createDocumentFragment(), re = wordRe(terms);
  let last = 0, m;
  while ((m = re.exec(text))) {
    const start = m.index + m[1].length;
    frag.append(text.slice(last, start), el('mark', null, m[2]));
    last = start + m[2].length; re.lastIndex = last;
  }
  frag.append(text.slice(last));
  return frag;
}

function assemblyButton(e) {
  const a = el('a', 'btn', 'ASSEMBLY');
  a.href = `../36-elements-assembly/?key=${encodeURIComponent(e.key)}`;
  a.title = `open ${e.key} in the Assembly page (it accepts ?key=block:<symbol>)`;
  return a;
}
function appButton(e) {
  const live = e.live || [];
  const page = live.find(u => /\.html?$|\/$/.test(u));
  const href = page || live[0];
  if (!href) return el('span', 'why', `APP: ${e.key} records no live address in the catalogue, so there is no surface to open.`);
  const a = el('a', 'btn', 'APP'); a.href = href; a.target = '_blank'; a.rel = 'noopener';
  a.title = page ? `the live address the catalogue records for ${e.key}` : `the first live file the catalogue records for ${e.key} (${href})`;
  return a;
}

const counts = new Map();
function renderCounts() {
  const parts = QUESTIONS.filter(q => counts.has(q.id)).map(q => `${q.id} ${counts.get(q.id)}`);
  $('counts').textContent = parts.length ? `Match counts (counted in this browser): ${parts.join(' · ')}` : 'Match counts: not yet counted (open a question).';
}

const rows = new Map();
async function openQuestion(q) {
  const row = rows.get(q.id);
  if (row.state === 'loaded' || row.state === 'loading') return;
  row.state = 'loading'; row.st.textContent = 'LOAD · fetching the catalogue';
  try {
    const { elements, fn } = await catalogue();
    const hits = [];
    for (const e of elements) { const f = matchElement(e, q.terms); if (f.length) hits.push({ e, f }); }
    counts.set(q.id, hits.length); renderCounts();
    row.st.textContent = hits.length ? `OK · ${hits.length} of ${elements.length} elements matched` : `EMPTY · no element's own title or description contains any of these words`;
    const box = row.hits; box.replaceChildren();
    if (hits.length) box.append(el('p', 'label', LABEL));
    for (const { e, f } of hits) {
      const card = el('div', 'el');
      const h = el('h3'); h.append(highlighted(e.title || '', q.terms)); card.append(h);
      card.append(el('div', 'k', `${e.key} · ${e.kind} · ${e.category_title || e.category} · state ${e.state} · words matched: ${f.join(', ')}`));
      const d = el('p'); d.append(highlighted(e.description || '', q.terms)); card.append(d);
      const names = (e.function_keys || []).map(k => (fn.get(k) && fn.get(k).name) || `${k} (not in functions.json)`);
      if (names.length) card.append(el('div', 'k', `functions inside: ${names.slice(0, 8).join(', ')}${names.length > 8 ? ` and ${names.length - 8} more` : ''}`));
      const b = el('div', 'btns'); b.append(assemblyButton(e), appButton(e)); card.append(b);
      box.append(card);
    }
    row.state = 'loaded';
  } catch (err) {
    row.state = 'failed';
    row.st.textContent = `FAIL · ${err.message} · close and reopen to retry`;
    $('catstate').textContent = `FAIL · ${err.message}`;
  }
}

/* build the fixed rows once */
const list = $('list');
for (const q of QUESTIONS) {
  const d = el('details'); d.id = 'q-' + q.id;
  const s = el('summary'); s.append(el('b', null, q.q));
  const st = el('span', 'st', 'WAIT · opens on tap'); s.append(st); d.append(s);
  const body = el('div', 'body');
  const terms = el('p', 'terms'); terms.append('Search terms (whole word, any case): '); for (const t of q.terms) terms.append(el('span', null, t)); body.append(terms);
  for (const g of q.galaxy) {
    const p = el('p', 'galaxy'); p.append('Demonstrated with a real engine module in ');
    const a = el('a', 'btn', `${g.dir.slice(0, 2)} ${g.name}`); a.href = `../${g.dir}/`; p.append(a);
    p.append(el('span', 'why', ` imports ${g.modules.join(', ')} from ventus-grid-engine@${ENGINE_COMMIT.slice(0, 7)}`));
    body.append(p);
  }
  const hits = el('div'); body.append(hits); d.append(body);
  rows.set(q.id, { st, hits, state: 'idle' });
  d.addEventListener('toggle', () => { if (d.open) openQuestion(q); else if (rows.get(q.id).state === 'failed') rows.get(q.id).state = 'idle'; });
  list.append(d);
}
for (const c of document.querySelectorAll('.cc')) c.textContent = CAT_COMMIT.slice(0, 7);
if (window.matchMedia('(min-width:760px)').matches) { $('questions').open = true; $('machine').open = true; }
window.__grid = { QUESTIONS, counts, rows, get fetchCount() { return fetchCount; }, openQuestion };

Iterations — 48 Grid Challenge Page

A web page in Galaxies Wafers. Published at https://ventusltd.github.io/galaxies-wafers/iterations/48-grid-challenge/.

rendergalaxies-wafers / iterations/48-grid-challenge/index.html · lines 1–40 of 40 · 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
Out: web page.
Downstream impact
It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/48-grid-challenge/.
What it achieves
Which Element Meets Which Grid Question. Its code works with 100 kW.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
galaxies-wafers · iterations/48-grid-challenge · page
Uses
Iterations — 48 Grid Challenge Style Sheet (stylesheet), Grid (script src)
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 iterations/48-grid-challenge/index.html:1-40 · blob b56bc0fff7d8e83a719bad2bbf7e358230afc625 · 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>Which Element Meets Which Grid Question</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
  <div class="mark">GRID QUESTIONS</div>
  <h1>Which element meets which grid question</h1>
  <p class="dim">The elements catalogue asks: “how can this or that solve the next Grid Challenge?” Below is a fixed list of grid questions in plain engineering words. Open one: the page then fetches the catalogue (once) and lists the elements whose <b>own</b> title or description contains that question's search terms, next to the galaxy iteration that already demonstrates the question with a real  … [line shortened here: 419 characters; full line on GitHub]
  <p id="cat" class="dim">Catalogue: <span id="catstate">WAIT · nothing fetched until a question is opened</span></p>
</header>

<p class="boundary">Illustrative physics drawn by a computer from published data. Not an engineering design or certified calculation. Any real design above 100 kW needs study and approval by a qualified chartered electrical engineer under the applicable standards.</p>

<main id="list" aria-label="grid questions"></main>

<details id="questions">
  <summary>Questions</summary>
  <ol>
    <li><b>How does this help draw a system or a single-line diagram?</b> It draws nothing itself. It points each SLD question at candidate elements: substation (nearest-search question), cable route (route question), feeder current and voltage drop (feeder questions), circuit ratings (ratings question), demand and firm capacity (site questions). The data fields read are <code>title</code>, <code>  … [line shortened here: 612 characters; full line on GitHub]
    <li><b>What is this code used for?</b> <code>grid.mjs</code> in this directory: <code>QUESTIONS</code> (the fixed list), <code>matchElement()</code> (whole-word, case-insensitive search of the element's own title and description), <code>openQuestion()</code> (fills one question once). Catalogue commit: <span class="cc"></span>. Callers: none in the estate; this page only (name-match inference   … [line shortened here: 436 characters; full line on GitHub]
    <li><b>Where does it lead next?</b> ASSEMBLY opens the matched element in iteration 36 (<code>?key=block:…</code>), and the linked galaxy iteration runs the real engine module for the question. Whether an element truly answers a question is <b>not established</b>: a word match is not evidence of function.</li>
  </ol>
</details>

<details id="machine">
  <summary>Machine detail</summary>
  <p>Inputs: <code>elements.json</code> and <code>functions.json</code> at elements commit <span class="cc"></span> (fetched when the first question is opened; bounded queue of 4, 15 s timeout each, one promise per URL, a failed fetch can be retried). Per question: a list of search terms (words, case-insensitive, whole-word). Outputs: per question, a count of matched elements (counted at run time)  … [line shortened here: 735 characters; full line on GitHub]
  <p id="counts" class="dim">Match counts: not yet counted (open a question).</p>
</details>

<script type="module" src="grid.mjs"></script>
</body>
</html>

Iterations — 48 Grid Challenge Style Sheet

A style sheet in Galaxies Wafers. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/48-grid-challenge/.

rendergalaxies-wafers / iterations/48-grid-challenge/style.css · lines 1–31 of 31 · Entry point

What it does
Side effects: changes the web page (DOM).
Downstream impact
Used directly by 1 file: Iterations — 48 Grid Challenge Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/48-grid-challenge/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/48-grid-challenge/.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
Loaded by the 48 Grid Challenge page at https://ventusltd.github.io/galaxies-wafers/iterations/48-grid-challenge/.
Application
galaxies-wafers · iterations/48-grid-challenge · style sheet
Uses
none found
Used by
loaded by Iterations — 48 Grid Challenge 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/48-grid-challenge/style.css:1-31 · blob 0b06e445e21e713e8246b6ab8e087824d4cafbf4 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
:root{--ink:#d8dee9;--dim:#8b93a7;--ground:#05060a;--edge:#444;--panel:#0b0d12;--lit:#ffd54a;--beam:#5ec8f2;--mark:#ffd54a33;
--top:env(safe-area-inset-top,0px);--bot:env(safe-area-inset-bottom,0px)}
*{box-sizing:border-box}
main,details,p,.el,.k,h3,summary{overflow-wrap:anywhere;min-width:0}
html{background:var(--ground)}
body{margin:0 auto;max-width:980px;background:var(--ground);color:var(--ink);font:13px/1.5 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;padding:calc(var(--top) + .5rem) .75rem calc(var(--bot) + 1.5rem);-webkit-text-size-adjust:100%}
.dim{color:var(--dim)}
.mark{letter-spacing:.14em;font-size:11px;color:var(--lit)}
h1{font-size:17px;margin:.2rem 0 .4rem;color:var(--ink)}
p{margin:.35rem 0}
code{color:#b9c4d6;word-break:break-word}
.boundary{border:1px solid var(--edge);border-radius:6px;padding:.5rem .6rem;background:var(--panel);color:#c9cfdb;font-size:12px}
details{border:1px solid var(--edge);border-radius:6px;background:var(--panel);margin:.5rem 0}
summary{cursor:pointer;padding:.6rem .6rem;list-style-position:inside}
summary b{color:var(--lit);font-weight:normal}
.body{padding:0 .6rem .6rem}
.st{font-size:11px;color:var(--dim);display:block;margin-top:.15rem}
.terms span{display:inline-block;border:1px solid var(--edge);border-radius:4px;padding:0 .3rem;margin:0 .2rem .2rem 0}
.label{font-size:11px;color:var(--dim);border-left:2px solid var(--edge);padding-left:.4rem}
.galaxy{margin:.4rem 0}
.el{border-top:1px solid #222;padding:.5rem 0}
.el h3{font-size:13px;margin:0 0 .15rem;color:var(--lit);font-weight:normal}
.el .k{color:var(--dim);font-size:11px}
mark{background:var(--mark);color:#fff;border-bottom:1px solid var(--lit)}
.btns{display:flex;flex-wrap:wrap;gap:.35rem;margin-top:.35rem;align-items:center}
a.btn,button.btn{font:inherit;font-size:12px;padding:.45rem .7rem;border-radius:6px;background:#0b0d12;color:var(--beam);border:1px solid var(--beam);text-decoration:none;display:inline-block;min-height:36px}
.why{font-size:11px;color:var(--dim)}
#questions ol,#machine p{padding:0 .6rem .6rem 1.6rem;margin:0}
#machine p{padding-left:.6rem}
#questions li{margin:.3rem 0}
@media (min-width:760px){body{font-size:14px}h1{font-size:20px}}

Galaxies Wafers — Iterations Page

A web page using data from GitHub API. Published at https://ventusltd.github.io/galaxies-wafers/iterations/. It is built from the esc step (`esc`), the when step (`when`) and the card step (`card`).

rendergalaxies-wafers / iterations/index.html · lines 1–92 of 92 · Entry point

What it does
It draws its content. Defines $, esc, when, card. Side effects: changes the web page (DOM); makes network requests.
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: data source: GitHub API; JSON file index.json. Out: web page.
Downstream impact
Used directly by 15 files: Iterations — 25 One Feeder Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/25-one-feeder/); Iterations — 43 Registry Growth Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/43-registry-growth/); 404 (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/404.html); Iterations — 24 Electrification Model Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/24-electrification-model/); and 11 more. Reached from 3 other entry points, including Iterations — 42 Counts That Say Themselves (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/42-counts-that-say-themselves/); Iterations — 46 Chemistry Ledger Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/46-chemistry-ledger/); Iterations — 47 Federation Honesty Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/47-federation-honesty/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/.
What it achieves
The README says: The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/. Its code works with 100 kW. It reads `index.json`.
Why it matters
Loaded by the 25 One Feeder page at https://ventusltd.github.io/galaxies-wafers/iterations/25-one-feeder/ and 14 other pages.
Application
galaxies-wafers · iterations · page
Uses
Galaxies Wafers — Index Page (link), Galaxies Wafers — Atlas Page (link), Layers (link)
Used by
linked from Iterations — 25 One Feeder Page (link), linked from Iterations — 43 Registry Growth Page (link), linked from 404 (link), linked from Iterations — 24 Electrification Model Page (link), linked from Iterations — 27 Earth Radii and Argument Order Page (link), linked from Iterations — 28 Nearest Search Trap Page (link), linked from Iterations — 29 Rating Envelope Page (link), linked from Iterations — 34 Cpu Floorplan Page (link), and 7 more
Produces
$, esc, when, card
Defines here
$, esc, when, card
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/index.html:1-92 · blob e46c25a8da1c7273f49e4f7d0e4ece963f14f172 · GitHub at these lines
State
achieves: readme · context: readme_derived · stage: output · effects: dom, network · 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">
<meta name="color-scheme" content="dark">
<title>Galaxies Wafers — every version</title>
<style>
:root{--ink:#d8dee9;--dim:#8b93a7;--ground:#0b0d12;--edge:#1b2030;--lit:#ffd54a;--beam:#5ec8f2;--hot:#ff2bd6}
*{box-sizing:border-box}
body{margin:0;background:var(--ground);color:var(--ink);font:14px/1.5 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
  padding:calc(env(safe-area-inset-top,0px) + 1rem) 1rem calc(env(safe-area-inset-bottom,0px) + 2rem);-webkit-text-size-adjust:100%}
main{max-width:46rem;margin:0 auto}
h1{font-size:13px;letter-spacing:.14em;font-weight:600;margin:0 0 .25rem}
.dim{color:var(--dim)}
nav{display:flex;flex-wrap:wrap;gap:.5rem;margin:.75rem 0 1.25rem}
nav a{border:1px solid var(--edge);border-radius:.4rem;padding:.35rem .6rem;color:var(--beam);text-decoration:none}
ol{list-style:none;margin:0;padding:0;display:grid;gap:.6rem}
li a.card{display:block;border:1px solid var(--edge);border-radius:.5rem;padding:.7rem .8rem;color:inherit;text-decoration:none;background:#10131b}
li a.card:active,li a.card:hover{border-color:var(--beam)}
.n{color:var(--lit);font-weight:600;margin-right:.4rem}
.t{font-size:14px}
.meta{font-size:11.5px;color:var(--dim);margin-top:.3rem;overflow-wrap:anywhere}
.src{color:var(--hot)}
.new{border-color:var(--hot)!important}
.state{font-size:12px;margin:.5rem 0 1rem}
footer{margin-top:2rem;font-size:11.5px;color:var(--dim)}
</style>
</head>
<body>
<main>
<h1>GALAXIES WAFERS · EVERY VERSION</h1>
<div class="dim">Newest first. Each card opens that version. Counts and dates are read from the repository when this page loads.</div>
<nav>
  <a href="../">The Line Wafer</a>
  <a href="../atlas/">The Ground</a>
  <a href="../proof/layers.html">Layer proofs</a>
  <a href="https://github.com/Ventusltd/galaxies-wafers">Source</a>
</nav>
<div id="state" class="state dim">loading iterations/index.json…</div>
<ol id="list"></ol>
<footer>
Illustrative physics and code drawn by a computer from published data. Not an engineering design or a certified calculation.
Any real design above 100 kW needs study and approval by a qualified chartered electrical engineer under the applicable standards.
</footer>
</main>
<script type="module">
const $ = id => document.getElementById(id);
const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const when = iso => { const d = new Date(iso); return isNaN(d) ? '' : d.toISOString().replace('T', ' ').slice(0, 16) + ' UTC'; };

function card(r, isNew) {
  const src = r.source ? `<div class="meta src">copied from ${esc(r.source.repo)} ${esc(r.source.path)} at ${esc((r.source.sha || '').slice(0, 7))}</div>` : '';
  const commit = r.commit ? `${esc(r.commit.slice(0, 7))} · ${esc(when(r.committed))}` : 'not yet indexed';
  return `<li><a class="card${isNew ? ' new' : ''}" href="${encodeURIComponent(r.dir)}/">
    <div class="t"><span class="n">${esc(String(r.n).padStart(2, '0'))}</span>${esc(r.title)}</div>
    <div class="meta">${commit}${r.subject ? ' · ' + esc(r.subject) : ''}</div>${src}</a></li>`;
}

(async () => {
  let idx;
  try {
    const res = await fetch('index.json', { cache: 'no-cache' });
    if (!res.ok) throw new Error('HTTP ' + res.status);
    idx = await res.json();
  } catch (e) {
    $('state').textContent = 'FAIL · iterations/index.json could not be read: ' + e.message;
    return;
  }
  const rows = [...idx.iterations].sort((a, b) => b.n - a.n);
  $('list').innerHTML = rows.map(r => card(r, false)).join('');
  $('state').textContent = `OK · ${rows.length} versions in the index`;

  /* Versions pushed after the index was last built: ask GitHub for the directory
     list once. If that fails (offline, rate limit) the index above still stands. */
  try {
    const res = await fetch('https://api.github.com/repos/Ventusltd/galaxies-wafers/contents/iterations?ref=main');
    if (!res.ok) throw new Error('HTTP ' + res.status);
    const known = new Set(idx.iterations.map(r => r.dir));
    const extra = (await res.json()).filter(x => x.type === 'dir' && /^\d+-/.test(x.name) && !known.has(x.name))
      .map(x => ({ n: parseInt(x.name, 10), dir: x.name, title: x.name.replace(/^\d+-/, '').replace(/-/g, ' ') }));
    if (extra.length) {
      $('list').insertAdjacentHTML('afterbegin', extra.sort((a, b) => b.n - a.n).map(r => card(r, true)).join(''));
      $('state').textContent = `OK · ${rows.length} versions in the index · ${extra.length} newer on main, not yet indexed (pink)`;
    }
  } catch (e) {
    $('state').textContent += ' · live check skipped: ' + e.message;
  }
})();
</script>
</body>
</html>

Galaxies Wafers — Lib

A JavaScript module that works with fanout count (`fanoutCount`) and connect answer (`connectAnswer`). Served with the page at https://ventusltd.github.io/galaxies-wafers/. It parses key (`parseKey`) and indexes key (`indexOfKey`).

ingestgalaxies-wafers / lib.mjs · lines 1–119 of 119 · pattern placeAll (shared by 2 files)

What it does
It lists and searches its content. Defines 9 functions or classes, including place, placeAll, parseKey, indexOfKey, ownersOf.
Why it exists in the grid workflow
README: "The page (`index.html`, `app.mjs`, `lib.mjs`) is inherited unchanged from testcode/202609151339."
Downstream impact
Used directly by 45 files: Wafer Development Environment — Cable Cross Sections (globalgrid2050, https://globalgrid2050.com/testcode/wafer-development-environment/202609190330-cable-cross-sections/); Layers Panel (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/01-route-alpha/); Layers Panel (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/02-tunnels/); Layers Panel (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/04-400kv-engine/); and 41 more. Reached from 245 other entry points, including 404 (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/404.html); Galaxies Wafers — Index Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/); Galaxies Wafers — Iterations Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/).
What it achieves
The logic of The Line Wafer, with no DOM and no fetch.
Why it matters
Imported by 45 files, including Wafer Development Environment — Cable Cross Sections, Layers Panel and Iterations — 01 Route Alpha, from GlobalGrid2050 and Star Electron Star.
Application
galaxies-wafers · / · JavaScript module
Uses
none found
Used by
imported by Wafer Development Environment — Cable Cross Sections (import), imported by Layers Panel (import), imported by Layers Panel (import), imported by Layers Panel (import), imported by Layers Panel (import), imported by Layers Panel (import), imported by Layers Panel (import), imported by Layers Panel (import), and 37 more, mentioned in Standalone (comment link)
Produces
GOLDEN, SPACING, place, placeAll, MAX_SAFE_KEY, parseKey, indexOfKey, ownersOf, fanoutCount, connectAnswer, esc, fmt
Defines here
place, placeAll, parseKey, indexOfKey, ownersOf, fanoutCount, connectAnswer, esc, fmt
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 lib.mjs:1-119 · blob b1468c8612bfb25f139df85e02fe6ad2e4237f45 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
/* lib.mjs — the logic of The Line Wafer, with no DOM and no fetch.
 *
 * WHY IT IS A SEPARATE FILE. The first version of this page kept its logic
 * inside app.mjs and its checks in a second file that reimplemented the same
 * ideas. A reviewer pointed out the obvious consequence: the checks were
 * proving a copy, not the page. Everything a claim is made about now lives
 * here, and both the page and the proofs import it, so a check that passes is
 * a check on the code that ships.
 */

export const GOLDEN = Math.PI * (3 - Math.sqrt(5));   /* the golden angle, 2.39996… rad */
export const SPACING = 1.0;

/* The addressing scheme. A number's place on the surface is a pure function of
   the number, so the same key is the same point on every device. A number that
   was never issued still has a place: that is what makes the surface unbounded
   rather than merely large. */
export function place(key) {
  const r = SPACING * Math.sqrt(key), t = key * GOLDEN;
  return [r * Math.cos(t), r * Math.sin(t)];
}

export function placeAll(keys) {
  const n = keys.length, p = new Float32Array(n * 2);
  for (let i = 0; i < n; i++) {
    const k = keys[i], r = SPACING * Math.sqrt(k), t = k * GOLDEN;
    p[i * 2] = r * Math.cos(t);
    p[i * 2 + 1] = r * Math.sin(t);
  }
  return p;
}

/* One strict parser for every number that enters this page, from a form field
   or from the URL. parseInt would accept "12abc" as 12 and would silently
   truncate a number too large to be exact, landing the beam on a different
   line than the one that was typed. */
export const MAX_SAFE_KEY = Number.MAX_SAFE_INTEGER;
export function parseKey(raw) {
  if (typeof raw !== 'string') raw = String(raw ?? '');
  const s = raw.trim().replace(/[ ,_]/g, '');
  if (!/^[0-9]+$/.test(s)) return { ok: false, why: 'a line number is digits only' };
  const n = Number(s);
  if (!Number.isSafeInteger(n)) return { ok: false, why: 'that number is too large to be held exactly' };
  if (n < 1) return { ok: false, why: 'the numbering starts at 1' };
  return { ok: true, key: n };
}

export function indexOfKey(keys, key) {
  let lo = 0, hi = keys.length - 1;
  while (lo <= hi) {
    const m = (lo + hi) >> 1;
    if (keys[m] === key) return m;
    if (keys[m] < key) lo = m + 1; else hi = m - 1;
  }
  return -1;
}

/* Which families carry each numbered line. */
export function ownersOf(families, famLines) {
  const owner = new Map();
  for (let f = 0; f < families.length; f++) {
    const o = families[f].lineOffset, c = families[f].lineCount;
    for (let i = o; i < o + c; i++) {
      const k = famLines[i], cur = owner.get(k);
      if (cur === undefined) owner.set(k, [f]);
      else if (cur[cur.length - 1] !== f) cur.push(f);
    }
  }
  return owner;
}

/* TWO RELATIONS, AND THEY ARE NOT THE SAME RELATION.
 *
 * FANOUT is one line number appearing in several families. The same text sits
 * in several places. That is duplication.
 *
 * CO-MEMBERSHIP is two different line numbers appearing in the same family.
 * They are two different lines of one function. That is not duplication and it
 * is emphatically not the same text; it is neighbourhood.
 *
 * The page's first version confused them, and claimed that a line carried by
 * only one family had nothing to join to. That was wrong: two lines each
 * carried by the same single family join through it perfectly well, and the
 * page could be shown doing it. Both relations are answered here, separately,
 * and named separately wherever they are printed.
 */
export function fanoutCount(owner) {
  let n = 0;
  for (const v of owner.values()) if (v.length > 1) n++;
  return n;
}

/* The whole answer to "connect a to b", with no DOM and no wording, so the
   proofs can assert on the decision rather than on a sentence. */
export function connectAnswer(a, b, { keys, owner }) {
  const absent = [];
  if (indexOfKey(keys, a) < 0) absent.push(a);
  if (b !== a && indexOfKey(keys, b) < 0) absent.push(b);
  if (absent.length) return { verdict: 'absent', absent, both: [] };
  if (a === b) return { verdict: 'same-line', absent: [], both: owner.get(a) || [] };
  const A = owner.get(a) || [], B = owner.get(b) || [];
  if (!A.length || !B.length) {
    return { verdict: 'no-family', absent: [], both: [],
             without: [...(A.length ? [] : [a]), ...(B.length ? [] : [b])], A, B };
  }
  const setB = new Set(B);
  const both = A.filter(f => setB.has(f));
  return { verdict: both.length ? 'joined' : 'disjoint', absent: [], both, A, B };
}

/* Dataset text is data. A function family is named by whatever was in the
   source, and a code catalogue can legitimately contain < and &. Everything
   that reaches the page goes through here or through textContent. */
export function esc(s) {
  return String(s ?? '').replace(/[&<>"']/g, c =>
    ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
}

export const fmt = n => Number(n).toLocaleString('en-GB');

Judge Check

A JavaScript module in the browser folder of Galaxies Wafers.

othergalaxies-wafers / proof/browser/judge.check.mjs · lines 1–22 of 22 · Entry point

What it does
Side effects: starts processes.
Inputs & outputs
In: JSON file a.json.
Downstream impact
Used directly by 1 file: Browser Matrix Workflow (galaxies-wafers).
What it achieves
Negative and positive fixtures for `judge`.
Why it matters
Run by Browser Matrix Workflow.
Application
galaxies-wafers · proof/browser · JavaScript module
Uses
Judge (import)
Used by
run by Browser Matrix Workflow (workflow run)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
galaxies-wafers@5814793812add74605660fa821e6a39b8de80588 proof/browser/judge.check.mjs:1-22 · blob 8228cabe4ae3ccd90ed02ccb0ff11a252ea83ddf · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unknown
/* Negative and positive fixtures for judge(). Run: node proof/browser/judge.check.mjs
 * The first fixture is the exact false pass from run 35007615561: iteration 09's
 * three requested layers left in WAIT while the job reported pass. */
import { judge } from './judge.mjs';

const cases = [
  ['09 false pass: three layers left WAIT', { layers: { 'module-Ps': 'WAIT', 'module-Gn': 'WAIT', 'module-x126': 'WAIT' } }, false],
  ['a layer still LOAD at the deadline', { layers: { a: 'OK', b: 'LOAD 2/5' } }, false],
  ['a layer FAIL', { layers: { a: 'FAIL' } }, false],
  ['a requested layer with no row', { layers: { ghost: 'absent' } }, false],
  ['a page error', { errors: ['TypeError: x'], layers: { a: 'OK' } }, false],
  ['a failed same-site request', { failedRequests: ['404 https://example/layers/a.json'], layers: {} }, false],
  ['all requested layers OK or EMPTY', { layers: { a: 'OK', spider: 'EMPTY' } }, true],
  ['no layers requested, no errors', { layers: {} }, true],
];
let bad = 0;
for (const [name, input, want] of cases) {
  const got = judge(input).pass;
  if (got !== want) { bad++; console.error(`FAIL ${name}: pass=${got}, expected ${want}`); }
}
if (bad) { console.error(`judge proof FAILED (${bad} of ${cases.length})`); process.exit(1); }
console.log(`judge proof PASS — ${cases.length} fixtures (6 must fail, 2 must pass)`);

Judge

A JavaScript module in the browser folder of Galaxies Wafers. It is built from the judge step (`judge`).

transformgalaxies-wafers / proof/browser/judge.mjs · lines 1–10 of 10 · pattern judge (shared by 9 files)

What it does
It calculates its inputs. Defines judge.
Downstream impact
Used directly by 2 files: Judge Check (galaxies-wafers); Smoke (galaxies-wafers). Reached from 1 other entry point, including Browser Matrix Workflow (galaxies-wafers).
What it achieves
The verdict for one browser job, kept pure so its failure cases can be proved without a browser (see judge.check.mjs).
Why it matters
Imported by Judge Check. Checked by Smoke.
Application
galaxies-wafers · proof/browser · JavaScript module
Uses
none found
Used by
imported by Judge Check (import), imported by Smoke (import)
Produces
judge
Defines here
judge
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 proof/browser/judge.mjs:1-10 · blob ab3a0316e60afc64fbf3a622be32cf2dd8bf9cea · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
/* The verdict for one browser job, kept pure so its failure cases can be proved
 * without a browser (see judge.check.mjs). A requested layer passes only if it
 * ends OK or EMPTY. WAIT, LOAD, FAIL, a missing row ("absent") or anything else
 * fails, because a page that never loads what was asked has not passed. */
export function judge({ errors = [], failedRequests = [], layers = {} }) {
  const entries = Object.entries(layers);
  const failedLayers = entries.filter(([, s]) => s === 'FAIL').map(([id]) => id);
  const unsettledLayers = entries.filter(([, s]) => !/^(OK|EMPTY)$/.test(s)).map(([id, s]) => `${id}:${s}`);
  return { failedLayers, unsettledLayers, pass: !errors.length && !failedRequests.length && !unsettledLayers.length };
}