GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / galaxies-wafers / iterations/36-elements-assembly

Assembly and 3 more files

A JavaScript module in the iterations folder of Galaxies Wafers that draws provenance and elements, using SHA-256, and uses data from the elements repository. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/36-elements-assembly/.

538 lines of JavaScript and CSS and HTML from galaxies-wafers, in 4 files. Topic: Kuiper, cosmos and drawing engines. Section 1215 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. Assembly render · galaxies-wafers / iterations/36-elements-assembly/assembly.mjs lines 701–954
  2. Engine ingest · galaxies-wafers / iterations/36-elements-assembly/engine.mjs lines 1–132
  3. Iterations — 36 Elements Assembly Page render · galaxies-wafers / iterations/36-elements-assembly/index.html lines 1–67
  4. Iterations — 36 Elements Assembly Style Sheet render · galaxies-wafers / iterations/36-elements-assembly/style.css lines 1–85

Assembly

A JavaScript module in the iterations folder of Galaxies Wafers that draws provenance and elements, using SHA-256, and uses data from the elements repository. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/36-elements-assembly/.

rendergalaxies-wafers / iterations/36-elements-assembly/assembly.mjs · lines 701–954 of 954 (continued from section 1214) · Entry point · pattern fillQuestions (shared by 2 files)

What it does
It draws provenance, elements, functions and surfaces. Defines 73 functions or classes, including $, el, s, inQueue, getURL. Side effects: changes the web page (DOM); makes network requests.
Inputs & outputs
In: data source: elements data; JSON file provenance.json; JSON file elements.json; JSON file functions.json; JSON file surfaces.json; JSON file apps.json; JSON file families.json. Out: canvas drawing.
Downstream impact
Used directly by 1 file: Iterations — 36 Elements Assembly Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/36-elements-assembly/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/36-elements-assembly/.
What it achieves
It gets URL (`getURL`), builds source rows (`buildSourceRows`) and sets row (`setRow`). The same universe at four assembly levels, each a zoom gate: sequence order, read from the numbered database (`families.json` `lineOffset`/lineCount into lines.bin). It responds to click, change and pointerdown events.
Why it matters
Loaded by the 36 Elements Assembly page at https://ventusltd.github.io/galaxies-wafers/iterations/36-elements-assembly/.
Application
galaxies-wafers · iterations/36-elements-assembly · JavaScript module
Uses
Galaxies Wafers — Lib (import), Wafer (import), Engine (import), Actions (dynamic import)
Used by
loaded by Iterations — 36 Elements Assembly Page (script src)
Produces
$, el, s, inQueue, getURL, buildSourceRows, setRow, hex, load, p, index, ensure
Defines here
unitOf, describe, headline, draw4, run4, step, fillQuestions, fillMachine, tapAt, gestures, rect, zoomBy, up, redraw, gateMoved, search
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/36-elements-assembly/assembly.mjs:701-954 · blob b510937ed96d28b0a02defa345357c95701fdbfe · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
    ['outputs', R ? (R.ok ? `${describe(R.result)}` : `refused: ${R.kind}: ${R.message}`) : 'not run yet'],
    ['refusals', 'a throw from the module is shown as the module states it; a proof whose text no longer holds the fixture refuses the run'],
    ['module', `${CDN}${S.engineFile}`],
    ['source commit', `${ENGINE_REPO}@${PIN}`]
  ]);
}
const UNIT = [['OhmPerKm', 'ohm per km'], ['Twh', 'terawatt-hours'], ['KwhPerYear', 'kilowatt-hours per year'], ['GbpPerMwh', 'pounds per megawatt-hour'], ['Mva', 'megavolt-amperes'], ['Kw', 'kilowatts'], ['Kv', 'kilovolts'], ['Hours', 'hours'], ['M', 'metres'], ['A', 'amperes']];
const WHOLE = { mva: 'megavolt-amperes', kv: 'kilovolts', kw: 'kilowatts', mw: 'megawatts' };
function unitOf(n) { if (WHOLE[n]) return WHOLE[n]; for (const [s, u] of UNIT) if (n.length > s.length && n.endsWith(s)) return u; return null; }
function describe(v) {
  if (v === null || typeof v !== 'object') return JSON.stringify(v);
  if ('value' in v) return `value ${JSON.stringify(v.value)}${v.unit ? ' ' + v.unit : ''}${v.quantity ? ' · ' + v.quantity : ''} · fields: ${Object.keys(v).join(', ')}`;
  if (Array.isArray(v)) return `an array of ${fmt(v.length)} items`;
  return `an object with fields ${Object.keys(v).join(', ')}`;
}
function headline(v) {
  if (v === null || typeof v !== 'object') return typeof v === 'number' ? String(+v.toPrecision(10)) : JSON.stringify(v);
  if ('value' in v) return `${typeof v.value === 'number' ? +v.value.toPrecision(10) : JSON.stringify(v.value)} ${v.unit || ''}`.trim();
  if ('direction' in v) return String(v.direction);
  if ('areaKm2' in v) return `${+v.areaKm2.toPrecision(8)} km2`;
  if (Array.isArray(v)) return `${v.length} items`;
  if (v.type) return `${v.type}${v.features ? ` · ${v.features.length} features` : ''}`;
  return Object.keys(v).slice(0, 3).join(', ');
}
function draw4(t, R, glow = -1) {
  const out = draw2((G, r) => {
    const { c, w, h } = G;
    const ox = Math.min(w - 60, r.nx + 150), oy = Math.min(h - 50, r.ny + 120);
    if (!R) { if (!lastRun) return; R = lastRun; }
    const [sx, sy] = [r.nx, r.ny];
    c.strokeStyle = '#5ec8f2'; c.lineWidth = 1.2; c.beginPath(); c.moveTo(sx, sy);
    const u = Math.min(1, t), mx = sx + (ox - sx) * u, my = sy + (oy - sy) * u;
    c.lineTo(mx, my); c.stroke();
    for (let j = 0; j < 5; j++) {                 /* the result flowing out: five pulses along the path */
      const q = ((t * 1.6) - j * 0.14); if (q < 0 || q > 1) continue;
      circle(c, sx + (ox - sx) * q, sy + (oy - sy) * q, 3.2, '#ffd54a');
    }
    if (t >= 1) {
      const txt = R.ok ? headline(R.result) : `refused: ${R.kind}`;
      c.font = '12px ui-monospace,Menlo,Consolas,monospace';
      const tw = Math.min(w - 20, c.measureText(txt).width + 16);
      const bx = Math.max(10, Math.min(w - tw - 10, ox - tw / 2));
      c.fillStyle = '#000'; c.strokeStyle = R.ok ? '#ffd54a' : '#ffb86b'; c.lineWidth = 1.2;
      c.fillRect(bx, oy - 14, tw, 26); c.strokeRect(bx, oy - 14, tw, 26);
      label(c, txt.length > 44 ? txt.slice(0, 43) + '…' : txt, bx + tw / 2, oy + 4, R.ok ? '#ffd54a' : '#ffb86b', 12);
    }
  }, glow);
  return out;
}
async function run4(e, path, fx) {
  const mine = token;
  const btn = document.querySelector('.runbtn'); if (btn) btn.disabled = true;
  const res = $('result');
  res.replaceChildren(el('div', 'dim', `reading ${fx.proof} at ${PIN.slice(0, 7)}, then importing ${path} in a worker…`));
  SOURCES.proof.url = ENGINE_RAW + fx.proof;
  setRow('proof', 'LOAD', SOURCES.proof.url);
  try {
    const proof = await getURL(ENGINE_RAW + fx.proof, 'text');
    setRow('proof', 'OK', `${ENGINE_RAW + fx.proof} · ${fmt(proof.split('\n').length)} lines`);
    const bad = checkProof(fx, proof);
    let R;
    if (bad) R = { ok: false, kind: 'Refused', message: bad };
    else R = await runInWorker(path, fx);
    if (mine !== token) return;
    lastRun = { key: e.key, path, ...R };
    res.replaceChildren();
    if (R.ok) {
      res.append(el('div', 'value', headline(R.result)), el('div', 'dim', `${fx.fn}(${fx.args.map(a => JSON.stringify(a)).join(', ')}) → ${describe(R.result)}`));
      const pre = el('pre', null, JSON.stringify(R.result, null, 1).slice(0, 4000)); res.append(pre);
    } else res.append(el('div', 'refuse', `${R.kind}: ${R.message}`));
    res.append(el('div', 'disclaimer', DISCLAIMER));
    res.dataset.run = R.ok ? 'ok' : 'refused';
    const t0 = performance.now();
    const step = t => { const u = Math.min(1.2, (t - t0) / 1100); draw4(u >= 1.2 ? 1 : u, lastRun); anim = u < 1.2 ? requestAnimationFrame(step) : null; if (u >= 1.2) draw4(1, lastRun); };
    anim = requestAnimationFrame(step);
    fillMachine(machine4(e, fx, lastRun));
  } catch (err) {
    setRow('proof', 'FAIL', err.message);
    if (mine === token) res.replaceChildren(el('div', 'refuse', 'Could not run: ' + err.message));
  } finally { if (btn) btn.disabled = false; }
}

/* ── panels ───────────────────────────────────────────────────────────────── */
function fillQuestions(node) { $('qbody').replaceChildren(node); $('qbody').className = ''; }
function fillMachine(node) { $('mbody').replaceChildren(node); $('mbody').className = ''; }

/* ── taps on the drawings ─────────────────────────────────────────────────── */
function tapAt(x, y) {
  if (S.level === 1 && wafer) {
    const i = wafer.nearestSeq(x, y);
    if (i >= 0) {
      const key = wafer.seq[i];
      $('result').replaceChildren(el('div', null, `line:${key} · position ${i + 1} of ${wafer.seq.length} in family:${S.family}'s sequence · appears ${wafer.seq.filter(k => k === key).length} time(s) in it`));
    }
    return;
  }
  let best = null, bd = Infinity;
  for (const h of hits) { const d = Math.hypot(h.x - x, h.y - y); if (d <= h.r && d < bd) { bd = d; best = h; } }
  if (!best) return;
  if (best.kind === 'atom') {
    S.family = famN(best.key); S.ringLine = -1;
    const f = I.fn.get(best.key);
    if (S.level === 4) draw4(lastRun ? 1 : 0); else draw2();
    const box = el('div');
    box.append(el('div', null, f ? `${f.key} ${f.name || '(name not yet known)'} · ${f.lines} line occurrences, ${f.distinct_lines ?? 'unknown'} distinct lines · sequence line:${f.first_line.split(':')[1]} … line:${f.last_line.split(':')[1]} · ${f.category || 'no category'}` : `${best.key}: not in the catalogue (10 lines or fewer, or not in the numbered database)`));
    box.append(button('light its lines (level 1)', () => setLevel(1, 'from an atom')));
    const [row, out] = buttonRow({ type: 'function', key: best.key, family: famN(best.key), firstLine: f ? +f.first_line.split(':')[1] : null, element: I.el.get(S.element) || null }, el('div', 'btnrow'));
    box.append(row, out);
    $('result').replaceChildren(box);
  } else if (best.kind === 'neighbour' || best.kind === 'element') {
    const ne = I.el.get(best.key);
    if (!ne) { $('result').replaceChildren(el('div', 'refuse', `${best.key} is named by the register but is not in the elements catalogue.`)); return; }
    S.element = best.key; S.family = null; S.surface = null; lastRun = null;
    setLevel(2, `${best.rel} ${best.key}`);
  }
}

function gestures() {
  const view = $('view');
  const pts = new Map(); let down = null, moved = 0, pinch = null;
  const rect = () => view.getBoundingClientRect();
  const zoomBy = (f, cx, cy) => {
    if (S.level === 1 && wafer) {
      const v = wafer.view, r = rect();
      const wx = (cx - r.left - v.w / 2) / v.zoom + v.x, wy = (v.h / 2 - (cy - r.top)) / v.zoom + v.y;
      v.zoom = Math.max(0.02, Math.min(4000, v.zoom * f));
      v.x = wx - (cx - r.left - v.w / 2) / v.zoom; v.y = wy - (v.h / 2 - (cy - r.top)) / v.zoom;
      if (wafer.fitZoom && v.zoom < wafer.fitZoom * 0.3) { S.gate = 1.6; setLevel(2, 'zoomed out past gate 1'); return; }
      wafer.render(); if (machine1) fillMachine(machine1());
      return;
    }
    if (!S.level) return;
    S.gate = Math.max(1, Math.min(4, S.gate - Math.log2(f) * 0.5));
    $('gate').value = String(S.gate);
    gateMoved();
  };
  view.addEventListener('pointerdown', e => {
    view.setPointerCapture(e.pointerId); pts.set(e.pointerId, [e.clientX, e.clientY]);
    if (pts.size === 1) { down = [e.clientX, e.clientY]; moved = 0; }
    if (pts.size === 2) { const [p, q] = [...pts.values()]; pinch = Math.hypot(p[0] - q[0], p[1] - q[1]); }
  });
  view.addEventListener('pointermove', e => {
    if (!pts.has(e.pointerId)) return;
    const prev = pts.get(e.pointerId); pts.set(e.pointerId, [e.clientX, e.clientY]);
    if (pts.size === 2 && pinch) {
      const [p, q] = [...pts.values()], d = Math.hypot(p[0] - q[0], p[1] - q[1]);
      if (d > 0) { zoomBy(d / pinch, (p[0] + q[0]) / 2, (p[1] + q[1]) / 2); pinch = d; }
      moved = 99; return;
    }
    if (pts.size === 1) {
      const dx = e.clientX - prev[0], dy = e.clientY - prev[1]; moved += Math.abs(dx) + Math.abs(dy);
      if (S.level === 1 && wafer) { wafer.view.x -= dx / wafer.view.zoom; wafer.view.y += dy / wafer.view.zoom; wafer.render(); }
      else if (S.level >= 2) { S.pan[0] += dx; S.pan[1] += dy; redraw(); }
    }
  });
  const up = e => {
    if (pts.size === 1 && down && moved < 8) { const r = rect(); tapAt(e.clientX - r.left, e.clientY - r.top); }
    pts.delete(e.pointerId); if (pts.size < 2) pinch = null; if (!pts.size) down = null;
    if (S.level === 1 && machine1 && moved >= 8) fillMachine(machine1());
  };
  view.addEventListener('pointerup', up);
  view.addEventListener('pointercancel', e => { pts.delete(e.pointerId); pinch = null; down = null; });
  view.addEventListener('wheel', e => { e.preventDefault(); zoomBy(Math.exp(-e.deltaY * 0.0016), e.clientX, e.clientY); }, { passive: false });
}
function redraw() {
  if (S.level === 2) draw2(); else if (S.level === 3) draw3(); else if (S.level === 4) draw4(lastRun ? 1 : 0);
}
function gateMoved() {
  const L = Math.round(S.gate);
  if (L !== S.level) {
    if (L === 1 && S.family == null) { const e = I.el && I.el.get(S.element); if (e) S.family = defaultFamily(e); }
    const g = S.gate; setLevel(L, 'crossed a gate').then(() => { S.gate = g; $('gate').value = String(g); });
  } else redraw();
}

/* ── search: fly to a key ─────────────────────────────────────────────────── */
async function search(raw) {
  const q = raw.trim();
  const m = /^(block|family|line|surface):(.+)$/.exec(q);
  refuse('');
  if (!m) { refuse(`Refused: "${q}" is not a key. Keys are block:<Sym>, family:<n>, line:<n> or surface:<url>.`); return false; }
  const [, kind, rest] = m;
  try {
    if (kind === 'block') {
      await load('elements');
      const e = I.el.get(q);
      if (!e) { refuse(`Refused: ${q} is not in the elements catalogue at ${CAT_COMMIT.slice(0, 7)} (${fmt(D.data.elements.length)} elements; symbols are case-sensitive).`); return false; }
      S.element = q; S.family = null; S.surface = null; S.ringLine = -1; lastRun = null;
      await setLevel(e.kind === 'app' ? 3 : 2, 'searched ' + q); return true;
    }
    if (kind === 'family' || kind === 'line') {
      const pk = parseKey(rest);
      if (!pk.ok) { refuse(`Refused: ${q}: ${pk.why}.`); return false; }
      setRow('families', rows.families.state === 'OK' ? 'OK' : 'LOAD');
      await ensure(1);
      if (kind === 'family') {
        const fi = I.fam.get(pk.key);
        if (fi === undefined) { refuse(`Refused: family:${pk.key} is not in the numbered database (${fmt(D.data.families.length)} families), so it names no function.`); return false; }
        const f = D.data.families[fi];
        S.family = pk.key; S.ringLine = -1;
        if (I.el.has(`block:${f.block}`)) S.element = `block:${f.block}`;
        if (!I.fn.has(q)) S.note = `${q} is in the numbered database but not in the elements catalogue, which lists functions over 10 lines; its ${f.lineCount} line occurrences are read from the numbered database.`;
      } else {
        if (indexOfKey(D.data.allLines, pk.key) < 0) { refuse(`Refused: line:${pk.key} was never issued. The numbering holds ${fmt(D.data.allLines.length)} keys between 1 and ${fmt(D.data.allLines[D.data.allLines.length - 1])}; a gap is a real answer.`); return false; }
        const fams = D.data.families, L = D.data.lines, carriers = [];
        let j = 0;
        for (let i = 0; i < L.length; i++) {
          if (L[i] !== pk.key) continue;
          while (j + 1 < fams.length && fams[j + 1].lineOffset <= i) j++;
          if (carriers[carriers.length - 1] !== j) carriers.push(j);
        }
        if (!carriers.length) { refuse(`Refused: line:${pk.key} is issued, but no function family carries it, so no function assembles it.`); return false; }
        const pick = carriers.find(ix => I.fn.has(`family:${fams[ix].n}`)) ?? carriers[0];
        S.family = fams[pick].n; S.ringLine = pk.key;
        if (I.el.has(`block:${fams[pick].block}`)) S.element = `block:${fams[pick].block}`;
        S.note = `line:${pk.key} is carried by ${fmt(carriers.length)} function ${carriers.length === 1 ? 'family' : 'families'}; showing family:${fams[pick].n}${carriers.length > 1 ? ' (the first of them in the catalogue, else the first)' : ''}.`;
      }
      lastRun = null;
      await setLevel(1, 'searched ' + q); return true;
    }
    if (kind === 'surface') {
      await load('surfaces');
      let key = q; if (!I.surf.has(key) && I.surf.has(q + '/')) key = q + '/';
      if (!I.surf.has(key)) { refuse(`Refused: ${q} is not one of the ${fmt(D.data.surfaces.length)} served surfaces in the catalogue (a surface key is a folder address ending in /).`); return false; }
      S.surface = key; S.element = I.surf.get(key).blocks[0] || S.element; lastRun = null;
      await setLevel(3, 'searched ' + q); return true;
    }
  } catch (e) { refuse(`Could not answer ${q}: ${e.message}`); return false; }
}

/* ── start ────────────────────────────────────────────────────────────────── */
buildSourceRows();
gestures();
for (const b of document.querySelectorAll('#rail button')) b.addEventListener('click', () => {
  const L = +b.dataset.level;
  if (L === 1 && S.family == null && I.el) { const e = I.el.get(S.element); if (e && I.fn) S.family = defaultFamily(e); }
  setLevel(L, 'chosen');
});
$('gate').addEventListener('input', () => { if (!S.level) { setLevel(Math.round(+$('gate').value)); return; } S.gate = +$('gate').value; gateMoved(); });
$('search').addEventListener('submit', e => { e.preventDefault(); search($('q').value); document.activeElement && document.activeElement.blur(); });
$('questions').addEventListener('toggle', () => { if ($('questions').open) runSldCheck(); });
let rz = 0;
window.addEventListener('resize', () => { cancelAnimationFrame(rz); rz = requestAnimationFrame(() => { if (S.level === 1 && wafer) { wafer.resize(); wafer.render(); } else redraw(); }); });
if (window.matchMedia('(min-width:760px)').matches) { $('questions').open = true; $('machine').open = true; }
window.__assembly = { S, D, I, queue, get fetchCount() { return fetchCount; }, get wafer() { return wafer; }, get hits() { return hits; }, search, setLevel };

(function readURL() {
  const q = new URLSearchParams(location.search);
  const key = q.get('key'), level = +q.get('level');
  if (key) { search(key).then(ok => { if (ok && level >= 1 && level <= 4 && level !== S.level) setLevel(level); }); return; }
  if (level >= 1 && level <= 4) { setLevel(level); return; }
  sayGate('nothing loaded yet · choose a level, slide the assembly zoom, or type a key');
  setCard('Assembly', `Four levels of one universe: numbered lines assemble into functions, functions into elements (register blocks), elements into apps and served surfaces, and engine elements run. Start at ${S.element} with a level, or type a key. Catalogue commit ${CAT_COMMIT.slice(0, 7)}.`);
})();

Engine

A JavaScript module in the iterations folder of Galaxies Wafers that fetches cables and interconnectors, using haversine. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/36-elements-assembly/.

ingestgalaxies-wafers / iterations/36-elements-assembly/engine.mjs · lines 1–132 of 132 · pattern collapse (shared by 4 files)

What it does
It fetches cables and interconnectors. Defines collapse, checkProof, refuse, runInWorker, done. Side effects: makes network requests.
Why it exists in the grid workflow
Domain terms in the code: cables, interconnectors.
Downstream impact
Used directly by 1 file: Assembly (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/36-elements-assembly/). Reached from 1 other entry point, including Iterations — 36 Elements Assembly Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/36-elements-assembly/).
What it achieves
It checks proof (`checkProof`) and runs worker (`runInWorker`). Level 4, IN ACTION. Its code works with 100 kW.
Why it matters
Imported by Assembly.
Application
galaxies-wafers · iterations/36-elements-assembly · JavaScript module
Uses
none found
Used by
imported by Assembly (import)
Produces
ENGINE_REPO, PIN, CDN, RAW, DISCLAIMER, FIXTURES, NOT_RECORDED, SLD, collapse, checkProof, runInWorker
Defines here
collapse, checkProof, refuse, runInWorker, done
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/36-elements-assembly/engine.mjs:1-132 · blob 510cd45b020ea921454a3de456b8ad9bef1de80f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: network · domain stage: unknown · users: none · canonical: unknown
/* engine.mjs — level 4, IN ACTION.
 *
 * Approach reused from iteration 31 (card.mjs): the first input each engine
 * module's own proof calls it with, held with the exact text that must appear
 * in that proof at the pinned commit (whitespace collapsed) and the proof line
 * the call sits on. The page reads the proof at the pin and refuses to run if
 * either check fails, so a fixture cannot drift away from its proof unseen.
 *
 * The module itself is imported, never copied: a Web Worker built from a Blob
 * imports it from jsDelivr at the pinned commit, removes its own network access,
 * calls one exported function with the fixture and posts the answer back. A run
 * that does not answer within 10 s (module download included) is stopped.
 *
 * Where the proof's first call is built from constants the proof computes or
 * imports, no input is recorded here, and the page says so with the reason.
 */

export const ENGINE_REPO = 'Ventusltd/ventus-grid-engine';
export const PIN = 'd9cd18b0e2034325814924e6e4a0e958014f2748';
export const CDN = `https://cdn.jsdelivr.net/gh/${ENGINE_REPO}@${PIN}/`;
export const RAW = `https://raw.githubusercontent.com/${ENGINE_REPO}/${PIN}/`;
const RUN_MS = 10000;   /* includes importing the module and its imports from the CDN */

export const DISCLAIMER = '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.';

/* args are passed positionally. {$ref:'EXPORT.KEY'} is resolved inside the worker
   from the module's own export, so the page never types a module constant. */
export const FIXTURES = {
  'engine/geo-core.js': { fn: 'haversine', args: [0, 0, 0, 1], proof: 'proofs/geodesy.proof.mjs', line: 60,
    evidence: ['haversine(0, 0, 0, 1)'], names: ['lon1 (degrees east)', 'lat1 (degrees north)', 'lon2 (degrees east)', 'lat2 (degrees north)'], returns: 'km (the module\'s @returns)' },
  'engine/geo-area.js': { fn: 'polygonAreaKm2', args: [[[-0.1, 51.5], [-0.095, 51.502], [-0.09, 51.4995], [-0.093, 51.496], [-0.099, 51.4965]]],
    proof: 'proofs/geodesy.proof.mjs', line: 87,
    evidence: ['const LONDON = [[-0.1000, 51.5000], [-0.0950, 51.5020], [-0.0900, 51.4995], [-0.0930, 51.4960], [-0.0990, 51.4965]];', 'polygonAreaKm2(LONDON)'],
    names: ['pts ([lon, lat] pairs, degrees)'] },
  'engine/geo-shapes.js': { fn: 'destinationCirclePoints', args: [-2.35, 56.05, 10, 24], proof: 'proofs/geodesy.proof.mjs', line: 162,
    evidence: ['destinationCirclePoints(-2.35, 56.05, 10, 24)'], names: ['lon (degrees east)', 'lat (degrees north)', 'radiusKm (km)', 'n (points)'] },
  'engine/geo-geojson.js': { fn: 'circleFeatureCollection', args: [-2.35, 56.05, 10], proof: 'proofs/geodesy.proof.mjs', line: 182,
    evidence: ['circleFeatureCollection(-2.35, 56.05, 10)'], names: ['lon (degrees east)', 'lat (degrees north)', 'radiusKm (km)'] },
  'engine/electrification-demand.js': { fn: 'averagePowerGw', args: [{ annualTwh: 8.76 }], proof: 'proofs/electrification-demand.proof.mjs', line: 51,
    evidence: ['averagePowerGw({ annualTwh: 8.76 })'] },
  'engine/firm-capacity.js': { fn: 'apparentPowerMva', args: [{ mw: 100, powerFactor: 0.95 }], proof: 'proofs/firm-capacity.proof.mjs', line: 29,
    evidence: ['apparentPowerMva({ mw: 100, powerFactor: 0.95 })'] },
  'engine/connection-capacity.js': { fn: 'exceedance', args: [{ profileKw: [20, 42, 36, 20], capKw: 30, intervalHours: 0.5 }],
    proof: 'proofs/connection-capacity.proof.mjs', line: 28,
    evidence: ['exceedance({ profileKw: [20, 42, 36, 20], capKw: 30, intervalHours: HALF_HOUR })', 'const HALF_HOUR = 0.5;'] },
  'engine/current-from-power.js': { fn: 'currentFromMvaAtKv', args: [{ mva: 1200, kv: 400 }], proof: 'proofs/current-from-power.proof.mjs', line: 54,
    evidence: ['currentFromMvaAtKv({ mva: 1200, kv: 400 })'] },
  'engine/diversified-demand.js': { fn: 'populationEnergyTwh', args: [{ unitCount: 10000000, perUnitKwhPerYear: 2500 }],
    proof: 'proofs/diversified-demand.proof.mjs', line: 23,
    evidence: ['populationEnergyTwh({ unitCount: 10_000_000, perUnitKwhPerYear: 2500 })'] },
  'engine/electrification-model.js': { fn: 'quantity', args: [12.25, 'kW', { $ref: 'MEANING.THERMAL_OUTPUT' }],
    proof: 'proofs/electrification-model.proof.mjs', line: 24,
    evidence: ["quantity(12.25, 'kW', MEANING.THERMAL_OUTPUT)"], names: ['value', 'unit', 'meaning (the module\'s MEANING.THERMAL_OUTPUT)'] },
  'engine/power-factor.js': { fn: 'apparentPowerKva', args: [{ kw: 1000, powerFactor: 0.85 }], proof: 'proofs/power-factor.proof.mjs', line: 25,
    evidence: ['apparentPowerKva({ kw: 1000, powerFactor: 0.85 })'] },
  'engine/voltage-drop.js': { fn: 'voltageDropVolts', args: [{ currentA: 200, lengthM: 250, resistanceOhmPerKm: 0.1, reactanceOhmPerKm: 0.08, powerFactor: 0.9, phases: 'three' }],
    proof: 'proofs/voltage-drop.proof.mjs', line: 33,
    evidence: ["const a = { currentA: 200, lengthM: 250, resistanceOhmPerKm: 0.1, reactanceOhmPerKm: 0.08, powerFactor: 0.9, phases: 'three' };", 'voltageDropVolts(a)'] },
  'engine/interconnector-economics.js': { fn: 'flowDirection', args: [{ gbPriceGbpPerMwh: 90, neighbourPriceGbpPerMwh: 60 }],
    proof: 'proofs/interconnector-economics.proof.mjs', line: 47,
    evidence: ['flowDirection({ gbPriceGbpPerMwh: 90, neighbourPriceGbpPerMwh: 60 })'] }
};

/* No runnable input recorded, and why: the proof's first call is not a literal. */
export const NOT_RECORDED = {
  'engine/v9-nearest-search.js': 'its proof (proofs/v9-engine.proof.mjs line 71) first calls index([DECOY_NORTH, TRUE_EAST, FAR, LOW_VOLTAGE]), points whose coordinates the proof computes, and the answer is an object of functions',
  'engine/network-topology.js': 'its proof (proofs/network-topology.proof.mjs line 72) first calls index(PRODUCT), a product the proof builds in code',
  'engine/published-fault-level.js': 'its proof (proofs/published-fault-level.proof.mjs line 74) first calls record(clone()), a copy of a record the proof holds',
  'engine/route-obstacles.js': 'its proof (proofs/route-obstacles.proof.mjs line 37) first calls routeEstimate with a distance constant and CABLE_FACTOR imported from engine/corridor-estimate.js'
};

/* Which single-line-diagram element a module feeds, and through which function
   (iteration 31's table). The function must exist in the source read at PIN. */
export const SLD = {
  'engine/voltage-drop.js': { element: 'cable route (the feeder cable between two busbars)', fn: 'voltageDropVolts' },
  'engine/current-from-power.js': { element: 'feeder (the current a circuit rating implies)', fn: 'currentFromMvaAtKv' },
  'engine/firm-capacity.js': { element: 'transformer (firm capacity of a substation\'s units)', fn: 'firmCapacityMva' },
  'engine/power-factor.js': { element: 'feeder (reactive power and its correction)', fn: 'correctionKvar' },
  'engine/route-obstacles.js': { element: 'cable route (length with crossings)', fn: 'routeEstimate' },
  'engine/published-fault-level.js': { element: 'protection (a published fault level at a busbar)', fn: 'quote' }
};

export const collapse = s => s.replace(/\s+/g, ' ');

/* Returns null when the proof agrees, otherwise the refusal sentence. */
export function checkProof(fx, proofText) {
  const flat = collapse(proofText);
  for (const ev of fx.evidence) {
    if (!flat.includes(collapse(ev))) return `"${ev}" was not found in ${fx.proof} at ${PIN.slice(0, 7)}, so this page will not claim it is the proof's input.`;
  }
  const lines = proofText.split('\n');
  if (!(lines[fx.line - 1] || '').includes(fx.fn + '(')) return `${fx.proof} line ${fx.line} at ${PIN.slice(0, 7)} does not call ${fx.fn}, so the recorded line is wrong and nothing was run.`;
  return null;
}

const WORKER_SRC = `
self.onmessage = async ({ data }) => {
  let m;
  try { m = await import(data.url); }
  catch (e) { postMessage({ ok: false, kind: 'ImportFailed', message: String(e && e.message || e) }); return; }
  const refuse = () => { throw new Error('network access is refused inside this run'); };
  for (const k of ['fetch', 'XMLHttpRequest', 'WebSocket', 'EventSource', 'importScripts']) { try { self[k] = refuse; } catch (e) {} }
  try {
    if (typeof m[data.fn] !== 'function') { postMessage({ ok: false, kind: 'NotExported', message: 'the module exports no function named ' + data.fn }); return; }
    const args = data.args.map(a => {
      if (a && typeof a === 'object' && typeof a.$ref === 'string') {
        const [ex, key] = a.$ref.split('.');
        if (!m[ex] || !(key in m[ex])) throw new Error('the module has no export ' + a.$ref);
        return m[ex][key];
      }
      return a;
    });
    const r = m[data.fn](...args);
    postMessage({ ok: true, resolved: args, result: JSON.parse(JSON.stringify(r === undefined ? null : r)) });
  } catch (e) {
    postMessage({ ok: false, kind: (e && e.name) || 'Error', message: String(e && e.message !== undefined ? e.message : e) });
  }
};`;

export function runInWorker(path, fx) {
  return new Promise(resolve => {
    const wurl = URL.createObjectURL(new Blob([WORKER_SRC], { type: 'text/javascript' }));
    let w = null;
    const done = r => { clearTimeout(timer); try { w && w.terminate(); } catch (e) {} URL.revokeObjectURL(wurl); resolve(r); };
    const timer = setTimeout(() => done({ ok: false, kind: 'Stopped', message: `stopped after ${RUN_MS / 1000} s without an answer, module download included` }), RUN_MS);
    try { w = new Worker(wurl, { type: 'module' }); }
    catch (e) { done({ ok: false, kind: 'NoWorker', message: 'this browser would not start a module worker: ' + e.message }); return; }
    w.onmessage = e => done(e.data);
    w.onerror = e => { if (e.preventDefault) e.preventDefault(); done({ ok: false, kind: 'LoadError', message: e.message || 'the module could not be loaded in the worker' }); };
    w.postMessage({ url: CDN + path, fn: fx.fn, args: fx.args });
  });
}

Iterations — 36 Elements Assembly Page

A web page in Galaxies Wafers that reads inputs for gate. Published at https://ventusltd.github.io/galaxies-wafers/iterations/36-elements-assembly/.

rendergalaxies-wafers / iterations/36-elements-assembly/index.html · lines 1–67 of 67 · 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/36-elements-assembly/.
What it achieves
Assembly — lines into functions, functions into elements, elements into apps, and in action.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
galaxies-wafers · iterations/36-elements-assembly · page
Uses
Iterations — 36 Elements Assembly Style Sheet (stylesheet), Assembly (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/36-elements-assembly/index.html:1-67 · blob aa98d5d83f41a9a330d952c15414c8aee7c63925 · 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>Assembly — lines into functions, functions into elements, elements into apps, and in action</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="style.css">
</head>
<body>

<header id="bar">
  <div id="brand"><span id="wordmark">ASSEMBLY</span> <span id="counts" class="dim">nothing loaded until a level is viewed</span></div>
  <form id="search" autocomplete="off">
    <input id="q" spellcheck="false" autocapitalize="off" placeholder="block:Gc · family:80299 · line:193185 · surface:…" aria-label="a permanent key to fly to">
    <button type="submit">FLY</button>
  </form>
</header>

<nav id="rail" aria-label="assembly level">
  <button type="button" data-level="1"><b>1</b> lines → function</button>
  <button type="button" data-level="2"><b>2</b> functions → element</button>
  <button type="button" data-level="3"><b>3</b> elements → app</button>
  <button type="button" data-level="4"><b>4</b> in action</button>
  <label id="gatebox"><span class="dim">assembly zoom</span>
    <input id="gate" type="range" min="1" max="4" step="0.01" value="2" aria-label="assembly zoom: pinch or slide across a gate to change level">
  </label>
</nav>

<main id="view">
  <canvas id="wafer" aria-label="the dark wafer: every numbered line, the chosen function's lines lit"></canvas>
  <canvas id="mol" aria-label="the assembly drawing for the level being viewed"></canvas>
  <div id="gatesay" class="dim"></div>
</main>

<section id="card" aria-live="polite">
  <div id="refusal" hidden></div>
  <h2 id="title">Assembly</h2>
  <div id="sub" class="dim">Choose a level or type a key. Each level fetches only the files it draws.</div>
  <div id="actions"></div>
  <div id="btnrow" class="btnrow" role="group" aria-label="actions for this card"></div>
  <div id="evidence" class="dim"></div>
  <div id="handoff" class="handoff"></div>
  <div id="result"></div>
</section>

<details id="questions">
  <summary>Questions</summary>
  <div id="qbody" class="dim">Open a level first.</div>
</details>

<details id="machine">
  <summary>Machine detail</summary>
  <div id="mbody" class="dim">Open a level first.</div>
</details>

<details id="sources">
  <summary>Sources and loading</summary>
  <p class="dim" id="rule"></p>
  <ul id="srclist"></ul>
</details>

<noscript><p class="dim">This page is drawn from the elements catalogue and the numbered database at run time, so it needs JavaScript.</p></noscript>
<script type="module" src="assembly.mjs"></script>
</body>
</html>

Iterations — 36 Elements Assembly Style Sheet

A style sheet in Galaxies Wafers. Served with the page at https://ventusltd.github.io/galaxies-wafers/iterations/36-elements-assembly/.

rendergalaxies-wafers / iterations/36-elements-assembly/style.css · lines 1–85 of 85 · Entry point

What it does
Side effects: changes the web page (DOM).
Downstream impact
Used directly by 1 file: Iterations — 36 Elements Assembly Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/36-elements-assembly/). It is itself an entry point, published at https://ventusltd.github.io/galaxies-wafers/iterations/36-elements-assembly/.
What it achieves
390 px first; the desktop is the same column with more room.
Why it matters
Loaded by the 36 Elements Assembly page at https://ventusltd.github.io/galaxies-wafers/iterations/36-elements-assembly/.
Application
galaxies-wafers · iterations/36-elements-assembly · style sheet
Uses
none found
Used by
loaded by Iterations — 36 Elements Assembly 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/36-elements-assembly/style.css:1-85 · blob dddc5f12f01d080b5bf207112da4e1ab2b6c08ff · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
/* Assembly. 390 px first; the desktop is the same column with more room.
   Grid Atlas popup grammar: black ground, #444 edge, monospace, amber title,
   grey detail, bordered cyan buttons. */
:root{
  --ink:#d8dee9; --dim:#8b93a7; --ground:#05060a; --edge:#444; --panel:#0b0d12;
  --lit:#ffd54a; --beam:#5ec8f2; --kv400:#0054ff;
  --top:env(safe-area-inset-top,0px); --bot:env(safe-area-inset-bottom,0px);
}
*{box-sizing:border-box}
html{background:var(--ground)}
body{
  margin:0 auto; max-width:980px; background:var(--ground); color:var(--ink);
  font:13px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
  padding:calc(var(--top) + .4rem) .6rem calc(var(--bot) + 1.2rem);
  -webkit-text-size-adjust:100%;
}
.dim{color:var(--dim)}
#bar{display:flex; flex-direction:column; gap:.35rem}
#wordmark{letter-spacing:.14em; font-size:11px; color:var(--lit)}
#counts{font-size:11px}
#search{display:flex; gap:.35rem}
#search input{
  flex:1 1 auto; min-width:0; padding:.55rem .5rem; font:inherit; font-size:16px;
  background:#11151f; color:var(--ink); border:1px solid var(--edge); border-radius:6px;
}
#search input:focus{outline:none; border-color:var(--beam)}
button, .btn{
  font:inherit; padding:.5rem .7rem; border-radius:6px; cursor:pointer;
  background:#0b0d12; color:var(--beam); border:1px solid var(--beam); text-decoration:none;
  display:inline-block;
}
button:disabled{opacity:.45; cursor:default}
#rail{display:grid; grid-template-columns:1fr 1fr; gap:.3rem; margin:.45rem 0}
#rail button{color:var(--dim); border-color:var(--edge); text-align:left; font-size:12px; padding:.45rem .5rem}
#rail button b{color:var(--ink)}
#rail button[aria-pressed="true"]{color:var(--lit); border-color:var(--lit)}
#gatebox{grid-column:1 / -1; display:flex; gap:.5rem; align-items:center; font-size:11px}
#gate{flex:1 1 auto; accent-color:var(--beam)}
#view{
  position:relative; height:min(58vh, 520px); min-height:300px;
  border:1px solid var(--edge); border-radius:8px; overflow:hidden; background:#030406;
  touch-action:none;
}
#view canvas{position:absolute; inset:0; width:100%; height:100%; display:block}
#gatesay{position:absolute; left:.45rem; bottom:.35rem; font-size:10.5px; pointer-events:none; right:.45rem}
#card{border:1px solid var(--edge); border-radius:8px; background:#000; padding:.6rem .7rem; margin-top:.5rem}
#card h2{margin:0 0 .2rem; font-size:14px; color:var(--lit); font-weight:600; word-break:break-word}
#sub{word-break:break-word}
#actions{display:flex; flex-wrap:wrap; gap:.35rem; margin-top:.45rem}
#actions select{font:inherit; font-size:14px; background:#11151f; color:var(--ink); border:1px solid var(--edge); border-radius:6px; padding:.4rem; max-width:100%}
#result{margin-top:.4rem}
#result pre{white-space:pre-wrap; word-break:break-word; max-height:14rem; overflow:auto; background:#0b0d12; border:1px solid #222; padding:.4rem; margin:.3rem 0; font-size:11px}
.value{color:var(--lit); font-size:15px}
.disclaimer{color:var(--dim); font-size:11px; border-left:2px solid var(--edge); padding-left:.45rem; margin-top:.4rem}
#refusal{color:#ffb86b; border:1px dashed #ffb86b; border-radius:6px; padding:.4rem .5rem; margin-bottom:.45rem}
#refusal[data-kind="note"]{color:var(--ink); border-color:var(--edge)}
.refuse{color:#ffb86b}
details{border:1px solid var(--edge); border-radius:8px; margin-top:.5rem; background:var(--panel)}
summary{cursor:pointer; padding:.5rem .7rem; color:var(--beam); letter-spacing:.06em}
details > div, details > p, details > ul{padding:0 .7rem .6rem; margin:0}
#qbody dt, #mbody dt{color:var(--ink); margin-top:.45rem}
#qbody dd, #mbody dd{margin:.1rem 0 0 0; color:var(--dim); word-break:break-word}
#qbody q{color:var(--ink)}
#srclist{list-style:none}
#srclist li{padding:.15rem 0; word-break:break-all; font-size:11px}
.tag{display:inline-block; min-width:3.6em; text-align:center; border:1px solid var(--edge); border-radius:4px; font-size:10px; padding:0 .25rem; margin-right:.35rem; color:var(--dim)}
.tag[data-s="OK"]{color:var(--beam); border-color:var(--beam)}
.tag[data-s="LOAD"]{color:var(--lit); border-color:var(--lit)}
.tag[data-s="EMPTY"], .tag[data-s="FAIL"]{color:#ffb86b; border-color:#ffb86b}
a{color:var(--beam)}
@media (min-width:760px){
  #bar{flex-direction:row; align-items:center; justify-content:space-between}
  #search{flex:0 1 26rem}
  #rail{grid-template-columns:repeat(4,1fr) 2fr}
  #gatebox{grid-column:auto}
  #view{height:min(62vh, 620px)}
}

/* the button row: short uppercase labels, as the GRID and MAP buttons */
.btnrow{display:flex; flex-wrap:wrap; gap:.3rem; margin-top:.45rem}
.btnrow button, .btnrow a{font-size:11px; letter-spacing:.08em; padding:.42rem .55rem; min-width:3.9rem; text-align:center}
.btnrow button[data-state="reason"]{color:#ffb86b; border-color:#ffb86b}
#evidence{font-size:10.5px; margin-top:.3rem}
.handoff{margin-top:.35rem}
.handoff a{margin-right:.4rem}