GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Cables and conductors / globalgrid2050 / testcode/wafer-development-environment/202609190330-cable-cross-sections

Pilot and 1 more file (part 1)

A JavaScript module in the testcode folder of GlobalGrid2050 that draws electron, using IEC 60909 and uses data from the ventus-grid-engine repository. Served with the page at https://globalgrid2050.com/testcode/wafer-development-environment/202609190330-cable-cross-sections/.

609 lines of JavaScript from globalgrid2050, in 2 files. Topic: Cables and conductors. Section 30 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. Pilot interaction · globalgrid2050 / testcode/wafer-development-environment/202609190330-cable-cross-sections/pilot.mjs lines 1–499
  2. Kuiper Pulse Check ingest · globalgrid2050 / testcode/wafer-development-environment/202609190330-cable-cross-sections/proof/kuiper-pulse.check.mjs lines 1–110

Pilot

A JavaScript module in the testcode folder of GlobalGrid2050 that draws electron, using IEC 60909 and uses data from the ventus-grid-engine repository. Served with the page at https://globalgrid2050.com/testcode/wafer-development-environment/202609190330-cable-cross-sections/.

interactionglobalgrid2050 / testcode/wafer-development-environment/202609190330-cable-cross-sections/pilot.mjs · lines 1–499 of 499 · version 2026-09-19 03:30 · Entry point · pattern clockTargets (shared by 3 files)

What it does
It draws electron, qubit and entangle. Defines 36 functions or classes, including $, here, hash32, mulberry32, atomOf. Side effects: changes the web page (DOM); makes network requests; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: 400kV, 132kV, 33kV.
Inputs & outputs
In: data source: ventus-grid-engine data; data source: gridatlas data; data source: pipelinenews data; data source: grid-dictionary data; data source: spiders data; data source: star-solar-star data; data source: code-generator data; data source: testcode data. Out: browser storage (setItem); canvas drawing. Voltage levels named: 400kV, 132kV, 33kV.
Downstream impact
Used directly by 1 file: Wafer Development Environment — Cable Cross Sections Page (globalgrid2050, https://globalgrid2050.com/testcode/wafer-development-environment/202609190330-cable-cross-sections/). Reached from 88 other entry points, including GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html); GlobalGrid2050 Homepage Before Four Nests (globalgrid2050, https://globalgrid2050.com/homepage-before-four-nests-20260925.html); Homepage V037 (globalgrid2050, https://globalgrid2050.com/homepage_versions/homepage_v037.html). It is itself an entry point, published at https://globalgrid2050.com/testcode/wafer-development-environment/202609190330-cable-cross-sections/.
What it achieves
It describes line (`describeLine`) and loads net (`loadNet`). Quantum Twin — primary key to actual code flights. Its code works with 132 kV, 400 kV and 33 kV. It responds to click, pointerdown and pointermove events.
Why it matters
Loaded by the Cable Cross Sections page at https://globalgrid2050.com/testcode/wafer-development-environment/202609190330-cable-cross-sections/.
Application
globalgrid2050 · testcode/wafer-development-environment/202609190330-cable-cross-sections · JavaScript module
Uses
GridAtlas — Atlas Page (estate URL), Grid Dictionary — Index Page (estate URL), Spiders — Index Page (estate URL), Code Generator — Index Page (estate URL), Galaxies Wafers — Index Page (estate URL), Stars — Index Page (estate URL)
Used by
loaded by Wafer Development Environment — Cable Cross Sections Page (script src)
Produces
$, here, hash32, mulberry32, atomOf, twinOf, log, say, esc, fly, gh, signal
Defines here
$, here, hash32, mulberry32, atomOf, twinOf, log, say, esc, fly, gh, signal, plainLabel, describeLine, run, earthUrl, W, hud, repoOf, scopeKeys, scopeFail, rasterLogo, toWafer, logoTargets, panelLink, j, loadNet, networkTargets, clockTargets, put
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/wafer-development-environment/202609190330-cable-cross-sections/pilot.mjs:1-499 · blob 7c04e9d03d995ae984afdc5d56cb4df81c28369c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network, storage · domain stage: experimental · users: none · canonical: production_core
// Quantum Twin — primary key to actual code flights. The pilot on top of the Line Wafer.
// Two twins: the permanent key (chronological, never reused) and the actual line it stands for (repo, commit, path, line).
// This file drives the wafer through its own controls (line number · connect to… · FLY) and adds a command box,
// a narration card, qubit/measure (the Quantum Twin Star's own model and generator), apps, entanglement and engine calls.
// It runs in two modes: on the website (static files, engine imported live from ventus-grid-engine's published modules)
// and in CPU WORLD (a local server adds read-from-git and the runner swarm). No model, no colour beyond the wafer's own.
const $ = id => document.getElementById(id);
const here = (() => { const m = document.querySelector('meta[name="wafer-data"]'); return m ? new URL(m.content, location.href).href : new URL('.', location.href).href; })();
const ENGINE_WEB = 'https://ventusltd.github.io/ventus-grid-engine/engine/';
let labels = null, apps = null, keysDb = null, qubit = null, entangle = null, serverMode = false; const born = { count: 0, seed: '2026-09-14' };
const DIES = ['sld-sandbox', 'substation-intelligence', 'place-global-search', 'streaming-parquet-bridge'];

// The Quantum Twin Star's own generator (testcode/202609142202/quantum.js), copied exactly so a measurement here reproduces one there.
function hash32(str){ let h = 0x811c9dc5 >>> 0; for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0; } return h >>> 0; }
function mulberry32(a){ return function(){ a |= 0; a = a + 0x6D2B79F5 | 0; let t = Math.imul(a ^ a >>> 15, 1 | a); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; }; }
function atomOf(k){ if (!keysDb || !qubit) return null; const i = keysDb.keys.indexOf(k); if (i < 0) return null; const fid = String(keysDb.family[i]); const a = qubit.atoms[fid]; return a ? { fid, i, ...a } : null; }
function twinOf(k){ if (!keysDb) return null; const i = keysDb.keys.indexOf(k); if (i < 0) return null; const pl = keysDb.places[keysDb.place[i]]; return { repo: pl[0], commit: pl[1], path: pl[2], line: keysDb.line[i] }; }

const css = document.createElement('style'); css.textContent = `
#pilot{position:fixed;left:0;right:0;bottom:0;display:flex;gap:8px;padding:8px 12px;background:transparent;border-top:1px solid #1b203055;z-index:20;opacity:.45;transition:opacity .15s,background .15s}
#pilot:hover,#pilot:focus-within{opacity:1;background:#0e121bf2;border-top-color:#1b2030}
#pilot input{flex:1;font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;background:#11151f;color:#cfe3f2;border:1px solid #1b2030;border-radius:6px;padding:.6rem .9rem}
#pilot input:focus{outline:1px solid #5ec8f2}
#say{position:fixed;left:50%;top:12vh;transform:translateX(-50%);width:min(72ch,84vw);max-height:70vh;min-width:280px;min-height:64px;background:#0e121bf2;border:1px solid #1b2030;border-radius:8px;padding:0;font:14px/1.5 ui-monospace,Menlo,Consolas,monospace;color:#cfe3f2;display:none;z-index:20;white-space:pre-wrap;resize:both;overflow:auto;display:none;flex-direction:column}
#say.open{display:flex} #say.max{left:12px;top:12px;right:12px;bottom:60px;transform:none;width:auto;max-height:none;height:auto}
#say.min{height:auto!important;max-height:none;resize:none;width:min(48ch,84vw)} #say.min #saybody{display:none}
#saybar{display:flex;align-items:center;gap:6px;padding:4px 8px;border-bottom:1px solid #1b2030;background:#11151f;cursor:move;user-select:none;font-size:11px;color:#8b93a7;letter-spacing:.06em;text-transform:uppercase}
#saybar span{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} #saybar button{font:12px ui-monospace,Menlo,Consolas,monospace;background:#0e121b;color:#cfe3f2;border:1px solid #1b2030;border-radius:4px;width:24px;height:22px;cursor:pointer;padding:0}
#saybar button:hover{border-color:#5ec8f2} #saybody{padding:.8rem 1.1rem;overflow:auto;flex:1}
#saybody b{color:#5ec8f2} #say i{color:#f2b05e;font-style:normal} #say a{color:#5ec8f2} #saybody pre{max-height:38vh;overflow:auto;background:#11151f;border:1px solid #1b2030;border-radius:4px;padding:6px 8px;margin:6px 0;font:12px/1.5 ui-monospace,Menlo,Consolas,monospace;white-space:pre}
#saybody pre em{color:#5b6377;font-style:normal} #saybody pre u{display:block;text-decoration:none;color:#5b6377;font-size:11px;padding-left:4.2em;margin:0 0 2px}
#saybody pre .hit u{color:#8b93a7}
#saybody pre .hit{display:inline-block;width:100%;background:#1b2030;color:#f2b05e}
#saybody a.dev{float:right;font-size:11px;color:#5b6377}
#say code{display:block;background:#11151f;border:1px solid #1b2030;border-radius:4px;padding:2px 6px;color:#cfe3f2;margin:4px 0}
#eg{position:fixed;right:12px;bottom:112px;background:transparent;border:0;border-radius:8px;padding:0;display:flex;flex-direction:column;gap:4px;max-width:46vw;z-index:20}
#eg label{font:11px ui-monospace,Menlo,Consolas,monospace;letter-spacing:.08em;text-transform:uppercase;color:#8b93a7;display:none}
#eg:hover label,#eg:focus-within label{display:block}
#eg:hover,#eg:focus-within{background:#0e121bf2;border:1px solid #1b2030;padding:.5rem .7rem}
#eg select{font:12px ui-monospace,Menlo,Consolas,monospace;background:#11151f;color:#cfe3f2;border:1px solid #1b2030;border-radius:6px;padding:.45rem .7rem}
#plog{position:fixed;left:12px;bottom:58px;max-width:min(60ch,62vw);max-height:30vh;overflow:hidden;font:11px/1.5 ui-monospace,Menlo,Consolas,monospace;color:#8b93a7;white-space:pre-wrap;pointer-events:auto;cursor:pointer;z-index:19}
#plog:empty{display:none} #plog span{display:none;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
/* At rest the log is a chip, not a sentence: a truncated line of narration printed over the
   drawing is the clutter the owner asked to remove. Click it to read everything. */
#plog:not(.open) span{display:none}
#plog:not(.open)::before{content:'log';display:inline-block;padding:.1rem .4rem;border:1px solid #1b2030;border-radius:4px;background:#0b0e15cc;color:#6f7789;font-size:10px;letter-spacing:.04em}
#plog.open span{display:block;white-space:pre-wrap;opacity:1}
#plog.open{background:#0b0e15ee;border:1px solid #1b2030;border-radius:6px;padding:.3rem .5rem}
/* ONE THIN FRAME, NO TWO THINGS IN THE SAME LANE. The command bar, the example picker, the beam and the log used
   to be given separate fixed positions that happened to overlap, so text printed through text and the drawing was
   covered twice over. They are stacked here, bottom upward, each in its own lane, and the belt keeps everything above. */
#beam{bottom:calc(env(safe-area-inset-bottom,0px) + 8.8rem) !important}
#pilot{bottom:calc(env(safe-area-inset-bottom,0px) + 3.9rem)}
#eg{bottom:calc(env(safe-area-inset-bottom,0px) + 10.2rem)}
#plog{bottom:calc(env(safe-area-inset-bottom,0px) + 12.3rem)}
@media (min-width:760px){#beam{bottom:calc(env(safe-area-inset-bottom,0px) + 5.1rem) !important}
/* the beam takes the right of that lane, so the picker takes the left rather than sitting on top of it */
#eg{left:12px;right:auto;bottom:calc(env(safe-area-inset-bottom,0px) + 5.1rem);max-width:34vw}
#plog{bottom:calc(env(safe-area-inset-bottom,0px) + 8.6rem)}}
#core button{pointer-events:auto;min-height:44px;min-width:44px;padding:.55rem .9rem;font:13px/1.2 ui-monospace,Menlo,Consolas,monospace;letter-spacing:.04em;background:#0e121bf2;color:#cfe3f2;border:1px solid #5ec8f2;border-radius:8px;cursor:pointer;touch-action:manipulation}
#core button:hover,#core button:focus-visible{background:#11151f;border-color:#f2b05e;outline:none} #core button small{display:block;color:#8b93a7;font-size:10px;letter-spacing:.06em;text-transform:uppercase}
@media (max-width:640px){#earth{position:fixed;inset:0;z-index:30;display:none;flex-direction:column;background:#0b0e15}
#earth.open{display:flex}
#earthbar{display:flex;align-items:center;gap:10px;padding:6px 12px;background:#11151f;border-bottom:1px solid #1b2030;font:12px ui-monospace,Menlo,Consolas,monospace;color:#cfe3f2}
#earthbar b{color:#f2b05e;letter-spacing:.08em} #earthbar span{flex:1;color:#8b93a7;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
#earthbar button,#earthbar a{font:12px ui-monospace,Menlo,Consolas,monospace;background:#0e121b;color:#5ec8f2;border:1px solid #1b2030;border-radius:6px;padding:.4rem .8rem;cursor:pointer;text-decoration:none}
#earthframe{flex:1;border:0;width:100%;background:#000}
`; document.head.appendChild(css);
document.body.insertAdjacentHTML('beforeend', `
<div id="say"></div><div id="plog"></div>
<div id="eg"><label>examples: pick one, it lands in the box, press Enter</label><select id="egs">
<option value="">— choose an example command —</option><option value="draw grid">Draw the grid: 400 kV, 132 kV and every substation</option><option value="draw grid400">Draw the 400 kV grid</option><option value="draw grid132">Draw the 132 kV network</option><option value="draw substations">Draw every substation</option><option value="draw shotwick">Draw Shotwick Solar Farm and the grid around it<  … [line shortened here: 1,363 characters; full line on GitHub]
<option value="block 39885">Go to the most-copied line in the estate (39885)</option>
<option value="twin 39885">The code behind block 39885, in the card</option>
<option value="state 39885">State of block 39885: HOME or AWAY, from its callers</option>
<option value="measure 39885">Measure block 39885: one recorded draw, HOME or AWAY</option>
<option value="connect 39885 1217">Connect two lines with the beam</option>
<option value="app gridatlas">Go to GridAtlas</option>
<option value="land gridatlas">Land on GridAtlas: the live app, inside this page</option>
<option value="land pipelinenews">Land on Pipeline News</option>
<option value="space">Back to space: the wafer</option>
<option value="apps">List every app on the wafer</option>
<option value="run voltage-drop.voltageDropVolts {&quot;currentA&quot;:120,&quot;lengthM&quot;:250,&quot;resistanceOhmPerKm&quot;:0.32,&quot;powerFactor&quot;:0.95,&quot;phases&quot;:&quot;three&quot;}">Engine: voltage drop, 120 A over 250 m, 0.32 Ω/km, pf 0.95</option>
<option value="entangle">Check: how many blocks are found at their recorded line</option>
<option value="help">Help</option></select></div>
<form id="pilot"><input id="pin" autocomplete="off" autofocus placeholder="type a sentence or a command: block 39885 · twin 39885 · state 39885 · measure 39885 · app gridatlas · run voltage-drop… · help"></form>`);

const EARTH_HTML = '<div id="earth"><div id="earthbar"><b>EARTH</b><span id="earthname"></span><a id="earthtab" target="_blank">open in its own tab</a><button id="earthback">back to space</button></div><iframe id="earthframe" title="the live app"></iframe></div>';
const lines = []; const plogEsc = t => String(t).replace(/&/g, '&amp;').replace(/</g, '&lt;');
// The run's narration used to print twelve lines of faint text straight across the belt, and the card
// printed through it. It is folded to its newest line; a tap opens the whole run and a second tap folds it.
const log = s => { lines.push(s); if (lines.length > 12) lines.shift(); $('plog').innerHTML = lines.map(l => `<span>${plogEsc(l)}</span>`).join(''); };
$('plog').addEventListener('click', () => $('plog').classList.toggle('open'));
// the card is a small window: minimise, maximise, resize (drag the corner), close; any new answer reopens it
const sayEl = $('say'); sayEl.innerHTML = '<div id="saybar"><span id="saytitle">card</span><button id="saymin" title="minimise">–</button><button id="saymax" title="maximise">▢</button><button id="sayclose" title="close">×</button></div><div id="saybody"></div>';
let lastCard = '';
const say = html => { if (!html) { sayEl.classList.remove('open'); return; } lastCard = html; $('saybody').innerHTML = html; const t = $('saybody').querySelector('b'); $('saytitle').textContent = t ? t.textContent : 'card'; sayEl.classList.remove('min'); sayEl.classList.add('open'); };
$('saymin').onclick = e => { e.stopPropagation(); sayEl.classList.toggle('min'); }; $('saymax').onclick = e => { e.stopPropagation(); sayEl.classList.remove('min'); sayEl.classList.toggle('max'); }; $('sayclose').onclick = e => { e.stopPropagation(); sayEl.classList.remove('open', 'max', 'min'); };
$('saybar').ondblclick = () => sayEl.classList.toggle('min');
(() => { let d = null; $('saybar').addEventListener('pointerdown', e => { if (e.target.tagName === 'BUTTON' || sayEl.classList.contains('max')) return; const r = sayEl.getBoundingClientRect(); d = { x: e.clientX - r.left, y: e.clientY - r.top }; sayEl.style.transform = 'none'; sayEl.style.left = r.left + 'px'; sayEl.style.top = r.top + 'px'; $('saybar').setPointerCapture(e.pointerId); });
  $('saybar').addEventListener('pointermove', e => { if (!d) return; sayEl.style.left = Math.max(0, e.clientX - d.x) + 'px'; sayEl.style.top = Math.max(0, e.clientY - d.y) + 'px'; }); $('saybar').addEventListener('pointerup', () => { d = null; }); $('saybar').addEventListener('pointercancel', () => { d = null; }); })();
window.__card = () => ({ open: sayEl.classList.contains('open'), min: sayEl.classList.contains('min'), max: sayEl.classList.contains('max'), w: sayEl.offsetWidth, h: sayEl.offsetHeight, title: $('saytitle').textContent });
const esc = s => String(s).replace(/</g, '&lt;');
const fly = (a, b) => { $('a').value = String(a); $('b').value = b ? String(b) : ''; $('beam').requestSubmit(); };
const gh = t => `https://github.com/${t.repo}/blob/${t.commit}/${t.path}#L${t.line}`;
const signal = o => { if (serverMode) fetch('/signal', { method: 'POST', body: JSON.stringify(o) }).catch(() => {}); try { const L = JSON.parse(localStorage.getItem('qt-signals') || '[]'); L.push({ ...o, t: new Date().toISOString() }); localStorage.setItem('qt-signals', JSON.stringify(L.slice(-500))); } catch {} };


// ---------- plain English: engine calls get a label; every line in the code view gets a note (same rules as pipeline/describe.py) ----------
const PLAIN = {
  'voltage-drop.voltageDropVolts': a => `voltage drop for ${a.currentA} A over ${a.lengthM} m at ${a.resistanceOhmPerKm} Ω/km${a.reactanceOhmPerKm ? ' (reactance ' + a.reactanceOhmPerKm + ')' : ''}, power factor ${a.powerFactor}, ${a.phases || 'three'}-phase`,
  'voltage-drop.dropPercent': a => `${a.dropVolts} V drop as a share of ${a.nominalVolts} V`, 'voltage-drop.lossesWatts': a => `heat lost in the cable: ${a.currentA} A over ${a.lengthM} m at ${a.resistanceOhmPerKm} Ω/km`,
  'diversified-demand.diversifiedDemandKw': a => `demand of ${a.unitCount} units at ${a.perUnitKw} kW each, coincidence ${a.coincidenceFactor}`,
  'current-from-power.currentA': a => `current for ${a.apparentPowerVa} VA at ${a.voltageV} V, ${a.phases || 'three'}-phase`, 'firm-capacity.apparentPowerMva': a => `apparent power for ${a.mw} MW at power factor ${a.powerFactor}`,
  'power-factor.reactivePowerKvar': a => `reactive power for ${a.kw} kW at power factor ${a.powerFactor}`,
};
const plainLabel = (mod, fn, args) => { const f = PLAIN[`${mod}.${fn}`]; try { return f ? f(args) : `${mod.replace(/-/g, ' ')}: ${fn.replace(/([A-Z])/g, ' $1').toLowerCase()}`; } catch { return `${mod}.${fn}`; } };
const DESCRIBE_RULES = [
  [/^\s*$/, 'blank line'], [/^\s*\/\//, 'a comment'], [/^\s*\/\*|^\s*\*/, 'a comment block'],
  [/^\s*(import|export)\b/, 'brings code in or out of this file'], [/^\s*(?:async\s+)?function\s+(\w+)/, 'defines the function $1'],
  [/^\s*(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s*)?\(?[^=]*=>/, 'defines the function $1'], [/^\s*(?:const|let|var)\s+(\w+)\s*=/, 'sets $1'],
  [/\.addEventListener\(\s*['"](\w+)/, 'listens for a $1 on the page'], [/^\s*return\b/, 'hands a result back'], [/^\s*if\b/, 'decides: only when the condition holds'],
  [/^\s*(?:else|\} else)/, 'otherwise'], [/^\s*for\b|^\s*while\b/, 'repeats for each item'], [/^\s*try\b/, 'tries, ready to catch a failure'], [/^\s*catch\b|\} catch/, 'handles a failure'],
  [/\.(?:querySelector|getElementById)\(/, 'finds a part of the page'], [/\.innerHTML\s*=|\.textContent\s*=/, 'writes text onto the page'], [/\bfetch\(/, 'asks a server for data'],
  [/\bclassList\./, 'changes how a part of the page looks'], [/\bconsole\./, 'writes to the developer console'], [/\bthrow\b/, 'stops with an error'],
  [/^\s*\}\s*\)?;?\s*$|^\s*\]\s*;?\s*$/, 'closes a block'], [/^\s*(\w+)\s*\(.*\)\s*;?\s*$/, 'calls $1'], [/\bawait\b/, 'waits for a result'], [/=/, 'sets a value'],
];
const describeLine = line => { for (const [re, note] of DESCRIBE_RULES) { const m = line.match(re); if (m) return note.replace(/\$(\d)/g, (_, i) => m[+i] || ''); } return 'a line of code'; };
window.__describe = describeLine;

const cmds = {
  help(){ say(`<b>commands</b>\nblock &lt;key&gt; · twin &lt;key&gt; · read &lt;key&gt; · state &lt;key&gt; · measure &lt;key&gt; [seed] · connect &lt;a&gt; &lt;b&gt; · land &lt;app&gt; · space · app &lt;name&gt; · apps · engine · run &lt;module&gt;.&lt;fn&gt; {…} · entangle · reset\ndraw kuiper · pulse [&lt;blob SHA&gt; | &lt;x,y&gt;] · pulse stop — pulse injects a disturbance into the Kuiper bel  … [line shortened here: 773 characters; full line on GitHub]

<b>every command this page answers</b>, read from the table itself rather than typed here, so nothing can go missing:
${Object.keys(cmds).sort().join(' · ')}
<b>every system draw can draw:</b>
${Object.keys(NETWORKS).sort().join(' · ')}`); },
  block(k){ k = parseInt(k, 10); if (!Number.isFinite(k)) return log('block <key>'); fly(k); say(`<b>block ${k}</b>\nthe beam is on line ${k}; the panel on the left shows what it is.\n<i>next:</i> twin ${k}`); log(`block ${k}`); },
  fly(k){ return cmds.block(k); }, goto(k){ return cmds.block(k); },
  async twin(k){ k = parseInt(k, 10); const t = twinOf(k); if (!t) return log(`twin ${k}: this block has no recorded line`); fly(k); return cmds.showCode(k, t, 'twin'); },
  async read(k){ k = parseInt(k, 10); const t = twinOf(k); if (!t) return log(`read ${k}: this block has no recorded line`); fly(k); return cmds.showCode(k, t, 'read'); },
  // the code itself, in the card, scrollable, the line highlighted; the source link is a fallback for developers
  async showCode(k, t, verb){ const raw = `https://raw.githubusercontent.com/${t.repo}/${t.commit}/${t.path}`; let lines = null;
    try { const r = await fetch(raw); if (r.ok) lines = (await r.text()).split(/\r?\n/); } catch {}
    if (!lines && serverMode) { try { const r = await (await fetch('/line?key=' + k)).json(); if (!r.error) lines = [...r.before, r.text, ...r.after].map(x => x ?? ''); } catch {} }
    const head = `<b>${verb} ${k}</b> — ${esc(t.repo.split('/').pop())} · ${esc(t.path.split('/').pop())} · line ${t.line}`;
    if (!lines) { say(`${head}
could not load the file here.
<a target="_blank" href="${gh(t)}">source, for developers</a>`); return log(`${verb} ${k}: file not loaded; source link shown`); }
    const from = Math.max(1, t.line - 20), to = Math.min(lines.length, t.line + 20); const rows = [];
    for (let n = from; n <= to; n++) rows.push(`<span class="${n === t.line ? 'hit' : ''}"><em>${String(n).padStart(5)}</em> ${esc(lines[n - 1] ?? '')}<u>${esc(describeLine(lines[n - 1] ?? ''))}</u></span>`);
    say(`${head}
<pre id="code">${rows.join('\n')}</pre><i>next:</i> state ${k}   <a class="dev" target="_blank" href="${gh(t)}">source, for developers</a>`);
    const hit = document.querySelector('#code .hit'); if (hit) hit.scrollIntoView({ block: 'center' }); log(`${verb} ${k}: ${t.path.split('/').pop()} line ${t.line}: ${(lines[t.line - 1] || '').trim().slice(0, 60)}`); },
  state(k){ k = parseInt(k, 10); const a = atomOf(k); if (!a) return log(`state ${k}: this block has no family record`); const n = a.K + a.L + a.M; const pAway = n ? a.M / n : 0; const theta = 2 * Math.asin(Math.sqrt(pAway)); fly(k);
    say(`<b>state ${k}</b> — block family #${esc(a.fid)} ${esc(a.name && a.name !== '(anonymous)' ? a.name : 'unnamed')} (${a.source === 'electron.json' ? 'from the published data' : 'estimated from where its copies sit'})\ncallers: K ${a.K} same directory · L ${a.L} same repository · M ${a.M} other repositories\nHOME P = ${(1 - pAway).toFixed(3)} · AWAY P = ${pAway.toFixed(3)} (AWAY = M ÷ (K+L+M)  … [line shortened here: 593 characters; full line on GitHub]
  qubit(k){ return cmds.state(k); },
  measure(rest){ const [ks, seedArg] = (rest || '').split(/\s+/); const k = parseInt(ks, 10); const a = atomOf(k); if (!a) return log(`measure ${ks}: this block has no family record`); if (seedArg) born.seed = seedArg;
    const n = a.K + a.L + a.M; const pAway = n ? a.M / n : 0; const r = mulberry32(hash32(`${born.seed}|${a.fid}|${born.count}`))(); born.count++; const away = r < pAway; const outcome = away ? 'AWAY' : 'HOME';
    const audit = `Draw ${born.count + 1}: seed "${born.seed}" · state #${a.fid} · r=${r.toFixed(6)} ${away ? '<' : '≥'} P(away)=${pAway.toFixed(3)} → ${outcome}`;
    say(`<b>measure ${k}</b> — result: <b>${outcome}</b>\n${esc(audit)}\nThe same seed, block and count always give the same result. Type <i>state ${k}</i> to see the probabilities again.`); log(audit);
    signal({ kind: 'born', key: k, family: a.fid, seed: born.seed, count: born.count, r, p_away: pAway, outcome: away ? 'AWAY' : 'HOME', shells: { K: a.K, L: a.L, M: a.M } }); },
  connect(ab){ const [a, b] = (ab || '').split(/\s+/).map(x => parseInt(x, 10)); if (!Number.isFinite(a) || !Number.isFinite(b)) return log('connect <a> <b>'); fly(a, b); say(`<b>connect ${a} → ${b}</b>\nthe beam joins two keys; both twins are real lines.`); log(`connect ${a} ${b}`); },
  apps(){ if (!apps) return log('apps not loaded'); const list = apps.apps.filter(a => a.app); say(`<b>${list.length} apps</b> (${esc(apps.rule)})\n` + list.map((a, i) => { const L = labels && labels.labels[a.name]; return `${i + 1}. ${a.name} — ${L ? labels.kinds[L.kind] + ': ' + L.what : ''} · ${a.keys.toLocaleString()} blocks`; }).join('\n') + `\n<i>next:</i> app &lt;name&gt;`); log(`${list.len  … [line shortened here: 415 characters; full line on GitHub]
  app(name){ if (!apps) return log('apps not loaded'); const list = apps.apps.filter(a => a.app); const a = list.find(x => x.name === (name || '').toLowerCase()) || list.find(x => x.name.includes((name || '').toLowerCase())); if (!a) return log(`no app "${name}"`);
    const [k0, k1] = apps.first[a.repo]; fly(k0, k1); const url = a.name === 'globalgrid2050' ? 'https://globalgrid2050.com/' : `https://ventusltd.github.io/${a.name}/`;
    say(`<b>app ${esc(a.name)}</b> — ${(() => { const L = labels && labels.labels[a.name]; return L ? esc(labels.kinds[L.kind] + '. ' + L.what) : ''; })()}\n${a.keys.toLocaleString()} blocks in ${a.families} gates · index ${esc(a.index || '?')}\nthe beam spans its first and middle lines (${k0} → ${k1}).\n<a target="_blank" href="${url}">open ${esc(a.name)} — see the code in action</a>  ·  <a targe  … [line shortened here: 490 characters; full line on GitHub]
  async engine(){ const mods = ['voltage-drop', 'diversified-demand', 'current-from-power', 'firm-capacity', 'power-factor', 'connection-capacity']; const out = []; for (const m of mods) { try { const mod = await import(ENGINE_WEB + m + '.js'); out.push(`${m}: ${Object.keys(mod).filter(k => typeof mod[k] === 'function').join(', ')}`); } catch (e) { out.push(`${m}: (not reachable: ${e.message})`);   … [line shortened here: 403 characters; full line on GitHub]
    say(`<b>engine</b> — ventus-grid-engine, imported live from its published modules\n${esc(out.join('\n'))}\n<i>next:</i> run voltage-drop.voltageDropVolts {…}`); log('engine listed'); },
  async run(rest){ const m = /^([a-z0-9-]+)\.([A-Za-z0-9_]+)\s*(\{[\s\S]*\})?$/.exec((rest || '').trim()); if (!m) return log('run <module>.<fn> {…}'); let args = {}; try { args = m[3] ? JSON.parse(m[3]) : {}; } catch { return log('run: arguments are not valid JSON'); }
    let result, err, us = 0; try { const mod = await import(ENGINE_WEB + m[1] + '.js'); if (typeof mod[m[2]] !== 'function') throw new Error(`no function ${m[2]} in ${m[1]}; has ${Object.keys(mod).filter(k => typeof mod[k] === 'function').join(', ')}`); const t0 = performance.now(); result = mod[m[2]](args); us = (performance.now() - t0) * 1000; } catch (e) { err = e.message; }
    if (err) { say(`<b>engine ${esc(m[1])}.${esc(m[2])}</b>\n<code>refused: ${esc(err)}</code>`); return log(`run refused: ${err}`); }
    const big = (result?.unit && /^(kW|kVA)$/.test(result.unit) && result.value > 100) || (result?.unit && /^(MW|MVA)$/.test(result.unit) && result.value > 0.1) || Object.entries(args).some(([k, v]) => (/mw|mva/i.test(k) && v * 1000 > 100) || (/kw|kva/i.test(k) && v > 100));
    say(`<b>${esc(plainLabel(m[1], m[2], args))}</b>\nengine ${esc(m[1])}.${esc(m[2])} · ${us.toFixed(0)} µs · imported from ventusltd.github.io/ventus-grid-engine\nin <code>${esc(JSON.stringify(args))}</code>out <code>${esc(JSON.stringify(result, null, 1))}</code>${big ? '<i>above 100 kW: a chartered electrical engineer must sign any real design.</i>\n' : ''}This page shows figures; it is not the  … [line shortened here: 563 characters; full line on GitHub]
  entangle(){ if (!entangle) return log('entangle not loaded'); say(`<b>entangle</b> (${esc(entangle.generated_utc)})\n${entangle.resolved.toLocaleString()} of ${entangle.keys.toLocaleString()} blocks reach their twin line (${(entangle.rate * 100).toFixed(2)} %) · ${entangle.broken.toLocaleString()} broken\nmeasured by fetching every twin from its commit and hashing the line (pipeline/entangle.py)  … [line shortened here: 503 characters; full line on GitHub]
  reset(){ $('a').value = ''; $('b').value = ''; $('panel').hidden = true; say(''); log('reset'); }, home(){ return cmds.reset(); },
  die(w){ return log('die: available in CPU WORLD (needs route-gridatlas.json)'); }, light(w){ return cmds.app('gridatlas'); },
};
async function run(line){ const [c, ...rest] = line.trim().split(/\s+/); const w = (c || '').toLowerCase(); const fn = Object.hasOwn(cmds, w) ? cmds[w] : null;
  if (!fn) { const p = plan(line, { appNames: apps ? apps.apps.filter(a => a.app).map(a => a.name) : [], dies: DIES }); log(`> ${line}`); log(`  plan: ${p.commands.length ? p.commands.join(' → ') : '(none)'} — ${p.because}`); if (p.commands.length) log(`  you could have typed: ${p.commands.join('   then   ')}`);
    for (const c2 of p.commands) { const [w2, ...r2] = c2.split(/\s+/); if (Object.hasOwn(cmds, w2)) { try { await cmds[w2](r2.join(' ')); } catch (e) { log('error: ' + e.message); } } } signal({ kind: 'pilot', sentence: line, plan: p.commands }); return; }
  log(`> ${line}`); try { await fn(rest.join(' ')); } catch (e) { log('error: ' + e.message); } }
$('pilot').onsubmit = e => { e.preventDefault(); const v = $('pin').value; $('pin').value = ''; if (v.trim()) run(v); };
$('egs').onchange = e => { if (e.target.value) { if (e.target.value === $('pin').dataset.last && lastCard && !sayEl.classList.contains('open')) { say(lastCard); log('card reopened'); } else { $('pin').value = e.target.value; $('pin').dataset.last = e.target.value; log('example loaded — press Enter to run it'); $('pin').focus(); } } e.target.selectedIndex = 0; };
addEventListener('keydown', e => { const t = e.target.tagName; if (t === 'INPUT' || t === 'SELECT' || t === 'TEXTAREA' || t === 'BUTTON') return; if (e.key.length === 1) $('pin').focus(); });

// ---------- space <-> earth: the live apps, by name, inside the page ----------
const EARTH = { gridatlas: 'https://ventusltd.github.io/gridatlas/atlas/', pipelinenews: 'https://ventusltd.github.io/pipelinenews/', globalgrid2050: 'https://globalgrid2050.com/', 'grid-dictionary': 'https://ventusltd.github.io/grid-dictionary/', spiders: 'https://ventusltd.github.io/spiders/', 'star-solar-star': 'https://ventusltd.github.io/star-solar-star/', 'code-generator': 'https://ventusltd  … [line shortened here: 889 characters; full line on GitHub]
document.body.insertAdjacentHTML('beforeend', EARTH_HTML);
const earthUrl = name => EARTH[name] || (apps && apps.apps.find(a => a.app && a.name === name) ? `https://ventusltd.github.io/${name}/` : null);
cmds.land = function(name){ name = (name || '').toLowerCase().trim(); const key = Object.keys(EARTH).find(k => k === name) || Object.keys(EARTH).find(k => k.includes(name)) || (apps ? (apps.apps.find(a => a.app && a.name.includes(name)) || {}).name : null);
  const url = key ? earthUrl(key) : null; if (!url) return log(`land <app>: ${Object.keys(EARTH).join(', ')}`);
  $('earthname').textContent = `${key} · ${url}`; $('earthtab').href = url; $('earthframe').src = url; $('earth').classList.add('open'); say(''); log(`landed on ${key} — type space to come back`); };
cmds.visit = cmds.land; cmds.go = cmds.land; cmds.open = cmds.land;
cmds.space = function(){ $('earth').classList.remove('open'); $('earthframe').src = 'about:blank'; log('back in space: the wafer'); };
$('earthback').onclick = () => cmds.space();
document.body.insertAdjacentHTML('beforeend', '<div id="hud" style="position:fixed;right:12px;top:44px;font:11px/1.5 ui-monospace,Menlo,Consolas,monospace;color:#8b93a7;pointer-events:none;z-index:19"></div>');
const W = () => window.__wafer; const fmtN = n => n.toLocaleString('en-GB');
const hud = s => { const st = W() && W().state(); if (!st) return; $('hud').textContent = `showing ${fmtN(st.scopeN)} of ${fmtN(st.n)} lines${s ? ' · ' + s : ''}`; };
let scopeName = 'all';
const repoOf = name => { if (!apps) return null; const a = apps.apps.find(x => x.name === name) || apps.apps.find(x => x.name.includes(name)); return a ? a.repo : null; };
// a scope is a set with a rule: all · an app (apps.json keys per repo) · module <path> · gate <family#> · line <key>
function scopeKeys(spec){ const s = (spec || 'all').trim(); const [kind, ...r] = s.split(/\s+/); const arg = r.join(' ');
  if (!s || s === 'all' || s === 'estate') return { name: 'all', keys: null };
  if (kind === 'line' || kind === 'key') { const k = parseInt(arg, 10); return Number.isFinite(k) ? { name: `line ${k}`, keys: [k] } : null; }
  if (kind === 'gate' || kind === 'family') { if (!keysDb) return null; const fid = parseInt(arg, 10); const ks = []; for (let i = 0; i < keysDb.keys.length; i++) if (keysDb.family[i] === fid) ks.push(keysDb.keys[i]); return ks.length ? { name: `gate ${fid}`, keys: ks } : null; }
  if (kind === 'module' || kind === 'file' || kind === 'die') { if (!keysDb) return null; const ks = []; for (let i = 0; i < keysDb.keys.length; i++) if (keysDb.places[keysDb.place[i]][2].includes(arg)) ks.push(keysDb.keys[i]); return ks.length ? { name: `module ${arg}`, keys: ks } : null; }
  const repo = repoOf(s.toLowerCase()); const ks = repo && apps.keys ? apps.keys[repo] : null; return ks ? { name: repo.split('/').pop(), keys: ks } : null; }
const scopeFail = spec => { log(`scope ${spec}: not a scope — try all, an app name (apps), module <path>, gate <family#>, line <key>`); };
cmds.scope = function(spec){ if (!W()) return log('the wafer is not ready'); const sc = scopeKeys(spec); if (!sc) return scopeFail(spec); const r = W().scope(sc.keys); scopeName = sc.name; hud(sc.name);
  log(`scope ${sc.name}: showing ${fmtN(r.shown)} of ${fmtN(r.of)} lines${r.missing ? ` · ${fmtN(r.missing)} keys not numbered here` : ''}`); return r; };
cmds.gravity = async function(spec){ if (!W()) return log('the wafer is not ready'); const sc = scopeKeys(spec); if (!sc) return scopeFail(spec); scopeName = sc.name; const k = W().kepler();
  log(`gravity ${sc.name}: Kepler r(θ) = p/(1 + e·cos θ), e = ${k.e}, p = ${k.p.toFixed(1)}, the wafer's centre at the focus, points in key order`); const r = await W().gravity(sc.keys); hud(sc.name + ' · kepler'); log(`gravity ${sc.name}: ${fmtN(r.shown)} lines in orbit${r.missing ? ` · ${fmtN(r.missing)} keys not numbered here` : ''}`); return r; };
cmds.orbit = cmds.gravity; cmds.isolate = cmds.gravity;
cmds.release = async function(){ if (!W()) return log('the wafer is not ready'); const r = await W().release(); scopeName = 'all'; hud(); log(`release: showing ${fmtN(r.shown)} of ${fmtN(r.of)} lines, back on the wafer law`); return r; };
// LOGO: the same dust, the same blend; the target is the wordmark rasterised once, deterministically, off screen (sampled only, never shown)
const LOGO = { lines: ['VENTUS — CABLES AND CONNECTIVITY', 'GLOBALGRID2050'], font: 'bold 120px ui-monospace', step: 2, lineGap: 150, fill: 1.6 };
let logoRaster = null;
function rasterLogo(){ if (logoRaster) return logoRaster; const c = document.createElement('canvas'); const g = c.getContext('2d'); g.font = LOGO.font;
  const w = Math.ceil(Math.max(...LOGO.lines.map(t => g.measureText(t).width))) + 40, h = LOGO.lineGap * LOGO.lines.length + 40; c.width = w; c.height = h; g.font = LOGO.font; g.textAlign = 'center'; g.textBaseline = 'middle'; g.fillStyle = '#fff';
  LOGO.lines.forEach((t, i) => g.fillText(t, w / 2, 20 + LOGO.lineGap * (i + 0.5))); const px = g.getImageData(0, 0, w, h).data; const on = new Uint8Array(w * h); const samples = [];
  for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { if (px[(y * w + x) * 4 + 3] > 127) { on[y * w + x] = 1; if (x % LOGO.step === 0 && y % LOGO.step === 0) samples.push(x, y); } }
  const st = W().state(); const s = LOGO.fill * Math.sqrt(st.max) / w; /* wafer units per canvas px: the text spans 1.6·R inside the wafer */
  const G = W().kepler().coreOut; /* the two lines part around the core: line 1 lifted by 0.10·R, line 2 lowered by it; the pupil stays empty */
  const toWafer = (x, y) => [(x - w / 2) * s, (h / 2 - y) * s + (y < h / 2 ? G : -G)]; const toCanvas = (X, Y) => [X / s + w / 2, h / 2 - (Y > 0 ? Y - G : Y + G) / s];
  return (logoRaster = { w, h, on, samples, n: samples.length / 2, s, toWafer, toCanvas }); }
function logoTargets(m){ const L = rasterLogo(); const t = new Float32Array(m * 2); const S = L.n;
  for (let j = 0; j < m; j++) { let q, dx = 0, dy = 0; if (m <= S) q = Math.floor(j * S / m); else { q = j % S; const c = Math.floor(j / S); dx = ((c * 7) % LOGO.step) / LOGO.step - 0.5; dy = ((c * 3) % LOGO.step) / LOGO.step - 0.5; } /* cycle with a tiny deterministic offset */
    const [X, Y] = L.toWafer(L.samples[2 * q] + dx, L.samples[2 * q + 1] + dy); t[2 * j] = X; t[2 * j + 1] = Y; } return t; }
cmds.logo = async function(spec){ if (!W()) return log('the wafer is not ready'); const sc = scopeKeys(spec || scopeName); if (!sc) return scopeFail(spec); const r = await W().scope(sc.keys); scopeName = sc.name; const L = rasterLogo(); const m = W().state().scopeN;
  log(`logo ${sc.name}: ${fmtN(m)} lines → "${LOGO.lines.join(' / ')}" (${fmtN(L.n)} glyph samples, ${LOGO.font}, grid ${LOGO.step} px)`); await W().blend(logoTargets(m)); hud(sc.name + ' · logo'); log(`logo ${sc.name}: assembled`); return r; };
cmds.wordmark = cmds.logo;
// test instrument: share of in-scope points within tolPx (screen px) of a glyph pixel
window.__logoCheck = (tolPx = 3) => { const L = rasterLogo(); const st = W().state(); const rad = Math.max(1, Math.ceil(tolPx / (st.view.zoom * L.s))); const P = W().positions(); let hit = 0;
  for (const [, X, Y] of P) { const [cx, cy] = L.toCanvas(X, Y); let ok = false; for (let y = Math.round(cy) - rad; y <= Math.round(cy) + rad && !ok; y++) for (let x = Math.round(cx) - rad; x <= Math.round(cx) + rad; x++) if (x >= 0 && y >= 0 && x < L.w && y < L.h && L.on[y * L.w + x]) { ok = true; break; } if (ok) hit++; }
  return { n: P.length, hit, share: P.length ? hit / P.length : 0, radiusCanvasPx: rad, samples: L.n }; };
window.__scopeKeys = spec => { const sc = scopeKeys(spec); return sc ? { name: sc.name, count: sc.keys ? sc.keys.length : null } : null; };
setTimeout(() => hud(), 1500);

// an app is a scope with gravity: app <name> and land <name> pull that app's lines in under Kepler; space releases them to the wafer law
{ const _app = cmds.app, _land = cmds.land, _space = cmds.space;
  cmds.app = async function(name){ const r = _app.call(cmds, name); if (W() && name && scopeKeys(name)) await cmds.gravity(name); return r; };
  cmds.land = async function(name){ if (W() && name && scopeKeys(name)) await cmds.gravity(name); return _land.call(cmds, name); };
  cmds.space = function(){ const r = _space.call(cmds); if (W()) cmds.release(); return r; }; }

window.__earth = () => ({ open: $('earth').classList.contains('open'), name: $('earthname').textContent, src: $('earthframe').src });


// the particles do the work: when the wafer's own panel opens for a line, add one plain link to the app that line belongs to
const APP_OF_REPO = { gridatlas: 'gridatlas', pipelinenews: 'pipelinenews', globalgrid2050: 'globalgrid2050', 'ventus-grid-engine': 'spider sandbox', elements: 'periodic table', 'grid-dictionary': 'grid-dictionary', spiders: 'spiders', 'star-solar-star': 'star-solar-star', 'code-generator': 'code-generator', testcode: 'testcode', 'galaxies-wafers': 'galaxies-wafers', stars: 'stars' };
// THE CARD IS A NAVIGATION SURFACE, not a viewer with a dead end. A body's card already shows the code and the
// way to the source; these are the ways onward from it. The repository the line belongs to is read from the key
// index, never guessed, and a repository this page cannot name an app for gets no route rather than a wrong one.
const panelLink = () => { const body = $('panelbody'); if (!body || body.querySelector('.landlink')) return; const m = (body.innerText || '').match(/Line\s+([\d,]+)/); if (!m) return; const key = +m[1].replace(/,/g, ''); const t = twinOf(key); if (!t) return;
  const repo = t.repo.split('/')[1]; const app = APP_OF_REPO[repo]; if (!app) return; const url = EARTH[app] || `https://ventusltd.github.io/${repo}/`;
  body.insertAdjacentHTML('beforeend', `<p class="landlink" style="margin:.7rem 0 0;display:flex;flex-wrap:wrap;gap:.2rem .9rem">`
    + `<a href="${url}" data-go="land ${app}" style="color:#5ec8f2">land on ${app}, this line's app</a>`
    + `<a href="#" data-go="app ${app}" style="color:#5ec8f2">pull ${esc(app)}'s lines into orbit</a>`
    + `<a href="#" data-go="apps" style="color:#8b93a7">every app on the wafer</a></p>`);
  for (const a of body.querySelectorAll('.landlink a')) a.addEventListener('click', e => { e.preventDefault(); run(a.dataset.go); }); };
new MutationObserver(panelLink).observe($('panelbody'), { childList: true, subtree: true });
window.__pilot = run;
(async () => {
  serverMode = /^(127\.0\.0\.1|localhost)$/.test(location.hostname) && await fetch('/gpu', { cache: 'no-store' }).then(r => r.ok).catch(() => false);
  if (serverMode) (async function poll(){ try { const { lines: L } = await (await fetch('/pilot/next')).json(); for (const l of L) { log(`[powershell] ${l}`); await run(l); } } catch {} setTimeout(poll, 500); })();
  const j = async f => fetch(here + f).then(r => r.ok ? r.json() : null).catch(() => null);
  [keysDb, qubit, apps, entangle, labels] = await Promise.all([j('keys.json'), j('qubit.json'), j('apps.json'), j('entangle.json'), j('labels.json')]);
  // the key index, published once for the whole page: app.mjs asks it which real line a block stands for, so the
  // card can show the lines around it and link to the source. Three answers, kept apart: the twin, null (this key
  // has no recorded line), or {error} (the index itself is not here). Until this line runs there is no __twin at
  // all, which is how "still loading" is told from "no record".
  window.__twin = k => keysDb ? twinOf(k) : { error: 'the key index (keys.json) did not load on this page' };
  log(`Quantum Twin — primary key to actual code. ${keysDb ? keysDb.count.toLocaleString() : '?'} blocks with a recorded line; ${qubit ? Object.keys(qubit.atoms).length.toLocaleString() : '?'} block families.`);
  log('Type a sentence or a command. Every answer shows the command it became. Try: block 39885');
  const qd = new URLSearchParams(location.search).get('draw'); const start = qd ? (['logo', 'clock'].includes(qd) ? qd : 'draw ' + qd) : document.querySelector('meta[name="wafer-start"]')?.content; if (start) { /* fire as soon as the wafer is actually there, instead of waiting a fixed guess: poll for window.__wafer every 80 ms, give it one short grace period, cap at 6 s */ for (let w = 0; w < 75 &  … [line shortened here: 835 characters; full line on GitHub]
})();

// ---------- NETWORK: a whole system drawn from a typed command, on the wafer's own dust (no new looks) ----------
// draw underground: the London Underground's topology (Transport for London open data; stations and the order of
// stops) laid out by an eight-direction schematic law, then the in-scope particles are placed along its edges and at
// its stations by the same blend gravity and the logo use. Positions are computed, never stored; identity never moves.
const netCache = {};
const NETWORKS = { grid: 'the grid: 400 kV, 132 kV and every substation', underground: 'the London Underground', grid400: 'the 400 kV grid', grid132: 'the 132 kV network', substations: 'every substation', shotwick: 'Shotwick Solar Farm and its grid', uk: 'the British Isles', world: 'the world', trench: 'a cable trench in flat formation (a stated arrangement, not a design)', fault: 'a fault study:   … [line shortened here: 1,064 characters; full line on GitHub]
const loadNet = async name => netCache[name] || (netCache[name] = await fetch(new URL(name + '-network.json', location.href)).then(r => r.ok ? r.json() : null).catch(() => null));
function networkTargets(N, m){
  const S = 0.85 * W().kepler().R, st = N.stations, E = N.edges, GA = 2.399963229728653;
  const perStation = E.length ? 9 : Math.max(1, Math.floor(m / st.length)), stationDots = Math.min(m, perStation * st.length), edgeDots = E.length ? m - stationDots : 0;
  const lens = E.map(([a, b, w]) => Math.hypot(st[b][0] - st[a][0], st[b][1] - st[a][1]) * (w == null ? 1 : w)); const L = lens.reduce((a, b) => a + b, 0) || 1;
  const t = new Float32Array(m * 2); let j = 0;
  for (let e = 0; e < E.length && j < edgeDots; e++) { const [a, b] = E[e]; const k = Math.max(1, Math.round(edgeDots * lens[e] / L));
    for (let i = 0; i < k && j < edgeDots; i++, j++) { const u = (i + 0.5) / k; t[2 * j] = S * (st[a][0] + (st[b][0] - st[a][0]) * u); t[2 * j + 1] = S * (st[a][1] + (st[b][1] - st[a][1]) * u); } }
  for (let s = 0; j < m; s++, j++) { const q = s % st.length, c = Math.floor(s / st.length), th = c * GA, r = 0.004 * S * Math.sqrt(c);
    t[2 * j] = S * st[q][0] + r * Math.cos(th); t[2 * j + 1] = S * st[q][1] + r * Math.sin(th); }
  return t;
}
cmds.draw = async function(spec){
  let what = (spec || '').trim().toLowerCase().split(/\s+/)[0] || ''; if (/^(tube|london)$/.test(what)) what = 'underground'; 
  if (!NETWORKS[what]) return log('draw <system> — one of: ' + Object.keys(NETWORKS).join(', '));
  if (!W()) return log('the wafer is not ready');
  const N = await loadNet(what); if (!N) return log(`draw ${what}: ${what}-network.json missing`);
  await W().scope(null); const m = W().state().scopeN;
  log(`draw ${what}: ${N.stations.length} nodes, ${N.edges.length} edges; ${m.toLocaleString('en-GB')} lines placed by: ${N.law}`);
  await W().blend(networkTargets(N, m)); hud(what);
  const c = N.counts;   /* counts, when the file carries measured ones. No count is typed into this page. */
  if (c) log(`draw ${what}: ${fmtN(c.bodies)} bodies · ${fmtN(c.duplicated)} duplicated · ${fmtN(c.unique)} unique · ${fmtN(c.repositories)} repositories · ${fmtN(c.tracked_paths)} tracked paths · ${fmtN(W().state().n)} numbered lines (run ${c.run})`);
  say(`<b>${NETWORKS[what]}, drawn from a typed command</b>
${N.stations.length.toLocaleString('en-GB')} nodes and ${N.edges.length.toLocaleString('en-GB')} edges from ${N.source}, drawn with the wafer's own particles. Every dot is still a numbered line of code; only the law that places it changed. It charts published data; it is not a design.
${c ? `<i>the count is the spectacle:</i> ${fmtN(c.bodies)} bodies · ${fmtN(c.duplicated)} duplicated · ${fmtN(c.unique)} unique · ${fmtN(c.repositories)} repositories · ${fmtN(c.tracked_paths)} tracked paths · ${fmtN(W().state().n)} numbered lines. Every one of these is read from ${esc(c.source_file)} of run ${esc(c.run)}; ${fmtN(c.measured)} of ${fmtN(c.bodies)} bodies carry a measured copy coun  … [line shortened here: 620 characters; full line on GitHub]
<small>${N.attribution}</small>`);
  log(`draw ${what}: drawn`); return { system: what, nodes: N.stations.length, edges: N.edges.length, placed: m };
};
cmds.underground = () => cmds.draw('underground'); cmds.tube = cmds.underground;

// ---------- CLOCK: time as a law on the same dust. The face is a ring of ticks, the hands are lines of particles
// from the centre; positions are a pure function of the clock at the moment of drawing; redrawn every 10 s while on.
let clockTimer = null;
function clockTargets(m, d){
  const R = 0.85 * W().kepler().R, t = new Float32Array(m * 2); let j = 0;
  const put = (x, y) => { if (j < m) { t[2 * j] = x; t[2 * j + 1] = y; j++; } };
  const ring = Math.floor(m * 0.45), ticks = Math.floor(m * 0.15), hands = m - ring - ticks;
  for (let i = 0; i < ring; i++) { const a = i / ring * 2 * Math.PI; put(R * Math.cos(a), R * Math.sin(a)); }
  for (let i = 0; i < ticks; i++) { const h = i % 12, u = (Math.floor(i / 12) % 40) / 40, a = Math.PI / 2 - h * Math.PI / 6; const r = R * (0.86 + 0.1 * u); put(r * Math.cos(a), r * Math.sin(a)); }
  const s = d.getSeconds() + d.getMilliseconds() / 1000, mi = d.getMinutes() + s / 60, h = (d.getHours() % 12) + mi / 60;
  const handSpec = [[Math.PI / 2 - h * Math.PI / 6, 0.5, 0.45], [Math.PI / 2 - mi * Math.PI / 30, 0.75, 0.4], [Math.PI / 2 - s * Math.PI / 30, 0.8, 0.15]];
  const total = handSpec.reduce((a, [, , w]) => a + w, 0);
  for (const [a, len, w] of handSpec) { const n = Math.floor(hands * w / total); const side = 0.012 * R;
    for (let i = 0; i < n; i++) { const u = i / n, off = ((i % 5) - 2) / 2 * side; put(u * len * R * Math.cos(a) - off * Math.sin(a), u * len * R * Math.sin(a) + off * Math.cos(a)); } }
  while (j < m) put(R * Math.cos(j), R * Math.sin(j));
  return t;
}
cmds.clock = async function(){
  if (!W()) return log('the wafer is not ready');
  await W().scope(null); const m = W().state().scopeN; const d = new Date();
  await W().blend(clockTargets(m, d)); hud('clock'); scopeName = 'clock';
  log(`clock: ${d.toTimeString().slice(0, 8)} drawn with ${m.toLocaleString('en-GB')} lines; the hands are a pure function of the time; redrawn every 10 s`);
  say(`<b>a clock, drawn from a typed command</b>\n${d.toTimeString().slice(0, 8)}. The face, the twelve ticks and the three hands are the wafer's own particles; their positions are a pure function of the clock, so this drawing can be recomputed for any instant. Time is a law like any other.\n<i>next:</i> release · draw grid · logo`);
  if (clockTimer) clearInterval(clockTimer);
  clockTimer = setInterval(async () => { if (scopeName !== 'clock') { clearInterval(clockTimer); clockTimer = null; return; } await W().blend(clockTargets(W().state().scopeN, new Date())); }, 10000);
  log('draw clock: drawn'); return { drawn: m };
};
cmds.time = cmds.clock;

// ---------- PULSE: a disturbance injected into the Kuiper belt and watched travel outward ----------
//
// WHAT THIS IS NOT. It is not an electrical result and it must never be read as one. `draw fault` on
// this same page is a real fault study: pandapower, IEC 60909, a published example network. This is
// not that. Here the bodies are files of code, the distances are the geometric distances of the
// belt's own drawing, and there are no edges in the dataset at all, so nothing here is an impedance,
// a travelling-wave velocity, a surge or a current. It is a pattern explorer: a way to look at how a
// disturbance injected at one place sweeps a population, so that the shape can be thought about
// before any real network is modelled. A chart, not a design.
//
// HOW IT IS DRAWN. The engine's rule holds: nothing per point may change — not size, not brightness,
// not colour. So light is made the only way the wafer allows, by how much dust a body is given. A
// body's share of the m in-scope particles is its response s_q, and the particles it receives are
// laid out in the same phyllotaxis cluster the networks already use, so a body with a large share is
// a wide bright bloom and a body with a small share is a point of base dust. The total dust is
// conserved in every frame: the light moves, it is never created.
//
// THE LAW, in full, printed with every run:
//   d_q      geometric distance, in the belt's own unit coordinates, from the injection point to
//            body q, taken from the belt's own computed positions. NOT electrical distance.
//   R(t)     the wavefront radius, R = v*t, with v = d_max / PULSE.T so the front crosses the whole
//            belt exactly once in T seconds, and t the seconds since injection.
//   f_q      the wavefront, a Gaussian of half-width sigma: f = exp(-((d_q - R)/sigma)^2).
//   g_q      the decay, geometric attenuation with distance travelled: g = exp(-d_q/lambda).
//   w_q      the response weight: copies, the MEASURED number of tracked paths whose bytes hash to
//            this body's blob SHA. A body with no measured copy count is weight 1 — base dust. No
//            intensity is ever invented.
//   s_q      the share of the dust: s = 1 + GAIN*f_q*g_q*w_q. The 1 is the base dust every body
//            always keeps, so the belt stays visible behind the front.
// Particles are handed out by exact cumulative share, so the counts sum to m with no rounding drift.
const PULSE = { T: 9, SIGMA: 0.035, LAMBDA: 0.9, GAIN: 14, CLUSTER: 0.0016, FPS: 24 };
const pulseLawText = (v, dmax) => `d = geometric distance in the drawing (NOT electrical distance; this dataset has no edges); R(t) = v·t with v = ${v.toFixed(4)} belt units/s so the front crosses d_max = ${dmax.toFixed(3)} once in ${PULSE.T} s; wavefront f = exp(−((d−R)/${PULSE.SIGMA})²); decay g = exp(−d/${PULSE.LAMBDA}); response weight w = copies (measured), unmeasured bodies weight 1; dust sh  … [line shortened here: 467 characters; full line on GitHub]

// measured copies per station, or null when the file carries none. A check that examines nothing refuses.
function stationCopies(N){
  const st = N.stations; let measured = 0;
  const w = new Float64Array(st.length);
  for (let i = 0; i < st.length; i++) { const c = st[i][3]; if (Number.isFinite(c) && c > 0) { w[i] = c; measured++; } else w[i] = 1; }
  return measured ? { w, measured, unmeasured: st.length - measured } : null;
}

// distances from the injection point to every station, in the network's own unit coordinates
function pulseDistances(N, ox, oy){
  const st = N.stations, d = new Float64Array(st.length); let dmax = 0;
  for (let i = 0; i < st.length; i++) { const x = st[i][0] - ox, y = st[i][1] - oy; const r = Math.sqrt(x * x + y * y); d[i] = r; if (r > dmax) dmax = r; }
  return { d, dmax };
}

// one frame of the pulse: 2·m scope-order coordinates. The buffers are reused across frames, because
// a 2 MB allocation thirty times a second is the one cost that would make the front stutter.
let pulseBuf = null, pulseShare = null;
function pulseTargets(N, m, w, d, R){
  const S = 0.85 * W().kepler().R, st = N.stations, GA = 2.399963229728653;
  const n = st.length;
  if (!pulseShare || pulseShare.length !== n) pulseShare = new Float64Array(n);
  const s = pulseShare; let tot = 0;
  for (let q = 0; q < n; q++) {
    const u = (d[q] - R) / PULSE.SIGMA;
    const f = u * u > 36 ? 0 : Math.exp(-u * u);
    const v = 1 + PULSE.GAIN * f * Math.exp(-d[q] / PULSE.LAMBDA) * w[q];
    s[q] = v; tot += v;
  }
  if (!pulseBuf || pulseBuf.length !== m * 2) pulseBuf = new Float32Array(m * 2);
  const t = pulseBuf;
  let cum = 0, j = 0;
  for (let q = 0; q < n; q++) {
    cum += s[q];
    const end = q === n - 1 ? m : Math.min(m, Math.floor(m * cum / tot));
    for (let i = 0; j < end; i++, j++) {
      const th = i * GA, r = PULSE.CLUSTER * S * Math.sqrt(i);
      t[2 * j] = S * st[q][0] + r * Math.cos(th);
      t[2 * j + 1] = S * st[q][1] + r * Math.sin(th);
    }
  }
  return t;
}

// the origin: a blob SHA (or a unique prefix of one), or "x,y" in the belt's own coordinates, or
// nothing — in which case it is the most-copied body in the estate, which is a measurement, not a choice.
function pulseOrigin(N, spec){
  const st = N.stations, a = (spec || '').trim().toLowerCase();
  if (/^-?[\d.]+\s*,\s*-?[\d.]+$/.test(a)) { const [x, y] = a.split(',').map(Number); return { x, y, how: `the position ${x}, ${y} in the belt's own coordinates` }; }
  if (/^[0-9a-f]{4,40}$/.test(a)) {
    const hit = st.findIndex(s => String(s[2]).startsWith(a));
    if (hit < 0) return null;
    return { x: st[hit][0], y: st[hit][1], i: hit, how: `body ${st[hit][2]} (blob SHA), copies ${st[hit][3] == null ? 'not measured' : st[hit][3]}` };
  }
  if (a) return null;
  let best = 0; for (let i = 0; i < st.length; i++) if ((st[i][3] || 0) > (st[best][3] || 0)) best = i;
  return { x: st[best][0], y: st[best][1], i: best, how: `the most-copied body in the estate, ${st[best][2]}, copies ${st[best][3]} — chosen by measurement, not by hand` };
}

let pulseRaf = null;
function pulseStop(){ if (pulseRaf) { cancelAnimationFrame(pulseRaf); pulseRaf = null; } }

cmds.pulse = async function(spec){
  const arg = (spec || '').trim().toLowerCase();
  if (/^(stop|off|end|halt)$/.test(arg)) { if (!pulseRaf) return log('pulse: nothing is running'); pulseStop(); scopeName = 'kuiper'; hud('kuiper'); log('pulse: stopped; the belt is left drawn. release returns every line to its own place'); return { stopped: true }; }
  if (!W()) return log('the wafer is not ready');
  const N = await loadNet('kuiper'); if (!N) return log('pulse: kuiper-network.json missing');
  const C = stationCopies(N);
  if (!C) return log('pulse: refused — kuiper-network.json carries no measured copy count per body, and this draws nothing without one. Regenerate it with kuiper-weigh.mjs.');
  const O = pulseOrigin(N, arg);
  if (!O) return log(`pulse ${arg}: refused — no body in the belt has a blob SHA starting "${arg}", and "${arg}" is not an x,y position. Nothing was drawn.`);

  pulseStop();
  await W().scope(null); const m = W().state().scopeN;
  const { d, dmax } = pulseDistances(N, O.x, O.y);
  const v = dmax / PULSE.T;
  const c = N.counts || {};
  log(`pulse: injected at ${O.how}`);
  log(`pulse law: ${pulseLawText(v, dmax)}`);
  log(`pulse: ${fmtN(N.stations.length)} bodies, ${fmtN(C.measured)} with a measured copy count, ${fmtN(C.unmeasured)} left as base dust; ${fmtN(m)} numbered lines carry the light`);
  log('pulse: this is NOT an electrical result. Geometric distance over code bodies. draw fault is the real fault study on this page.');

  say(`<b>a pulse injected into the Kuiper belt — a propagation PATTERN, not an electrical result</b>
<b>This charts nothing about any real network.</b> The bodies are files of code, the distances are the geometric distances of this drawing, and this dataset has no edges at all — so there is no impedance here, no travelling-wave velocity, no surge and no current. It is a pattern explorer: a way to see the shape a disturbance makes as it sweeps a population, before any real network is modelled. The  … [line shortened here: 561 characters; full line on GitHub]
Injected at ${esc(O.how)}.
<i>the law, in full:</i> ${esc(pulseLawText(v, dmax))}
<i>the count is the spectacle:</i> ${fmtN(c.bodies ?? N.stations.length)} bodies · ${fmtN(c.duplicated ?? 0)} duplicated · ${fmtN(c.unique ?? 0)} unique · ${fmtN(c.repositories ?? 0)} repositories · ${fmtN(c.tracked_paths ?? 0)} tracked paths · ${fmtN(W().state().n)} numbered lines. How brightly a body answers the front is its copy count, measured; a body with no measured count stays base dust.
<i>next:</i> pulse stop · draw kuiper · draw fault · release
<small>${esc(N.attribution)}</small>`);

  scopeName = 'pulse';
  const t0 = performance.now(); const step = 1000 / PULSE.FPS; let last = -1e9;
  return await new Promise(res => {
    const tick = now => {
      if (scopeName !== 'pulse') { pulseRaf = null; return res({ ended: 'scope changed' }); }
      if (now - last < step) { pulseRaf = requestAnimationFrame(tick); return; }
      last = now;
      const t = (now - t0) / 1000, R = v * t;
      const done = R > dmax + 4 * PULSE.SIGMA;
      /* when the front has left the belt the wafer is settled back onto draw kuiper's own placement,
         so the resting state after a pulse is exactly the resting state after draw kuiper — not a
         half-lit frame — and the pick index is rebuilt to match it. */
      W().frame(done ? networkTargets(N, m) : pulseTargets(N, m, C.w, d, R), done);
      if (done) { pulseRaf = null; scopeName = 'kuiper'; hud('kuiper · pulse passed'); log(`pulse: the front has crossed the whole belt, d_max = ${dmax.toFixed(3)} in ${PULSE.T} s; the belt is settled back on draw kuiper's placement. release returns every line to its own place`); return res({ crossed: dmax, seconds: PULSE.T, bodies: N.stations.length, lines: m }); }
      hud(`kuiper · pulse R = ${R.toFixed(3)} of ${dmax.toFixed(3)}`);
      pulseRaf = requestAnimationFrame(tick);
    };
    pulseRaf = requestAnimationFrame(tick);
  });
};
cmds.inject = cmds.pulse;

// release stops the pulse first, then does exactly what it always did: every line back to its own place.
{ const _release = cmds.release;
  cmds.release = async function(){ pulseStop(); scopeName = 'all'; return _release.call(cmds); }; }

// Two laws must never share the position buffer. Every command that moves the dust stops the pulse
// first, so the wafer is never left half under one law and half under another.
for (const name of ['draw', 'clock', 'logo', 'scope', 'gravity']) {
  const f = cmds[name];
  cmds[name] = function(...a){ pulseStop(); if (scopeName === 'pulse') scopeName = 'kuiper'; return f.apply(cmds, a); };
}
cmds.time = cmds.clock; cmds.wordmark = cmds.logo; cmds.orbit = cmds.gravity; cmds.isolate = cmds.gravity;
cmds.underground = () => cmds.draw('underground'); cmds.tube = cmds.underground;

Kuiper Pulse Check

A JavaScript module in the proof folder of GlobalGrid2050 that reads Kuiper network. It is built from the cut step (`cut`) and the load step (`load`).

ingestglobalgrid2050 / testcode/wafer-development-environment/202609190330-cable-cross-sections/proof/kuiper-pulse.check.mjs · lines 1–110 of 110 · version 2026-09-19 03:30 · Not reached from any entry point (candidate for review)

What it does
It loads Kuiper network. Defines cut, load, ok, no. Uses libraries node:fs, node:path, node:url. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'testcode'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file -network.json; JSON file kuiper-network.json; command-line arguments.
What it achieves
`proof/kuiper-pulse.check`.mjs — the Kuiper belt's pulse, checked without a browser.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · testcode/wafer-development-environment/202609190330-cable-cross-sections/proof · JavaScript module
Uses
node:fs, node:path, node:url
Used by
none found
Produces
cut, load, ok, no
Defines here
cut, load, ok, no
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 testcode/wafer-development-environment/202609190330-cable-cross-sections/proof/kuiper-pulse.check.mjs:1-110 · blob 0a7188585e9aa5e808706fa5faca396d7b716125 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: experimental · users: none · canonical: unreached_review
// proof/kuiper-pulse.check.mjs — the Kuiper belt's pulse, checked without a browser.
//
// It re-implements nothing. It cuts the placement laws out of the shipped pilot.mjs by name and runs
// that source text, so what is checked is what is served. Run it from anywhere:
//     node proof/kuiper-pulse.check.mjs [<path to estate-bodies.json>]
// The second argument is optional: without it the join back to the estate run is reported as NOT
// EXAMINED rather than as a pass, because a check that examines nothing refuses.

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const src = fs.readFileSync(path.join(DIR, 'pilot.mjs'), 'utf8');

function cut(name, kind) {
  const start = src.indexOf(kind === 'const' ? `const ${name} =` : `function ${name}(`);
  if (start < 0) throw new Error('not found in pilot.mjs: ' + name);
  if (kind === 'const') return src.slice(start, src.indexOf('\n', start));
  let depth = 0;
  for (let j = src.indexOf('{', start); j < src.length; j++) {
    if (src[j] === '{') depth++;
    else if (src[j] === '}' && !--depth) return src.slice(start, j + 1);
  }
  throw new Error('unbalanced braces: ' + name);
}

const R = 100;                       // stand-in for the wafer radius; any positive number works
const P = new Function(
  `const W = () => ({ kepler: () => ({ R: ${R} }) });\nlet pulseBuf = null, pulseShare = null;\n` +
  [cut('PULSE', 'const'), cut('networkTargets'), cut('pulseTargets'), cut('pulseDistances'),
   cut('stationCopies'), cut('pulseOrigin')].join('\n') +
  '\nreturn { networkTargets, pulseTargets, pulseDistances, stationCopies, pulseOrigin, PULSE };')();

const load = f => JSON.parse(fs.readFileSync(path.join(DIR, f), 'utf8'));
const M = 245170;                    // 250,174 numbered lines less the 2 % rim: the scope draw() gets

let fail = 0, refused = 0;
const ok = (c, m) => { console.log((c ? '  PASS   ' : '  FAIL   ') + m); if (!c) fail++; };
const no = m => { console.log('  REFUSE ' + m); refused++; };

console.log('1. no other system\'s placement changed');
for (const f of fs.readdirSync(DIR).filter(x => x.endsWith('-network.json'))) {
  const t = P.networkTargets(load(f), M);
  ok(t.length === 2 * M && t.every(Number.isFinite), `${f}: networkTargets gives ${M.toLocaleString('en-GB')} finite points`);
}
{ // the fourth element must be invisible to the law that draw uses
  const N = load('kuiper-network.json');
  const three = { ...N, stations: N.stations.map(s => [s[0], s[1], s[2]]) };
  const a = P.networkTargets(three, M), b = P.networkTargets(N, M);
  ok(Buffer.compare(Buffer.from(a.buffer), Buffer.from(b.buffer)) === 0,
    'draw kuiper places every line at byte-identical coordinates with and without the fourth element');
}

console.log('\n2. the measured quantity');
const N = load('kuiper-network.json'), C = P.stationCopies(N), c = N.counts;
ok(!!C, 'a measured copy count is present, so the pulse may examine something');
ok(C.measured === N.stations.length && C.unmeasured === 0, `${C.measured} measured, ${C.unmeasured} unmeasured (unmeasured bodies stay base dust)`);
let dup = 0, uni = 0, paths = 0;
for (const s of N.stations) { if (s[3] > 1) dup++; else uni++; paths += s[3]; }
ok(dup + uni === c.bodies && dup === c.duplicated && uni === c.unique && paths === c.tracked_paths,
  `recounted from the stations themselves: ${c.bodies} bodies, ${dup} duplicated, ${uni} unique, ${paths} tracked paths`);

const BODIES = process.argv[2];
if (!BODIES) no('the join back to estate-bodies.json: NOT EXAMINED — pass its path to check it');
else {
  const by = new Map(JSON.parse(fs.readFileSync(BODIES, 'utf8')).bodies.map(b => [b.id, b.copies]));
  let bad = 0; for (const s of N.stations) if (by.get(s[2]) !== s[3]) bad++;
  ok(bad === 0, `every station's fourth element equals estate-bodies.json copies for that blob SHA (${N.stations.length} of ${N.stations.length})`);
}

console.log('\n3. the pulse law');
const O = P.pulseOrigin(N, '');
ok(O && N.stations[O.i][3] === c.max_copies, `the default origin is the most-copied body, copies ${c.max_copies} — a measurement, not a choice`);
ok(P.pulseOrigin(N, 'zzzz') === null, 'an origin naming no body refuses, and nothing is drawn');
ok(P.pulseOrigin(N, N.stations[9][2].slice(0, 8))?.x === N.stations[9][0], 'a blob SHA prefix resolves to that body');
const { d, dmax } = P.pulseDistances(N, O.x, O.y);
const v = dmax / P.PULSE.T;
ok(d.length === N.stations.length && dmax > 0, `geometric distance computed for ${d.length} bodies, d_max = ${dmax.toFixed(4)}, v = ${v.toFixed(4)} belt units/s`);

let good = true;
for (let step = 0; step <= 12; step++) {
  const t = P.pulseTargets(N, M, C.w, d, v * (step * P.PULSE.T / 12));
  if (t.length !== 2 * M || !t.every(Number.isFinite)) { good = false; break; }
}
ok(good, `every frame is exactly ${M.toLocaleString('en-GB')} finite points: the dust is conserved, the light only moves`);

{ // the response is the measured copy count and nothing else
  const Rf = dmax * 0.5, n = N.stations.length, s = new Float64Array(n);
  let tot = 0;
  for (let q = 0; q < n; q++) {
    const u = (d[q] - Rf) / P.PULSE.SIGMA, f = u * u > 36 ? 0 : Math.exp(-u * u);
    s[q] = 1 + P.PULSE.GAIN * f * Math.exp(-d[q] / P.PULSE.LAMBDA) * C.w[q]; tot += s[q];
  }
  const dots = new Int32Array(n);
  let cum = 0, j = 0, total = 0;
  for (let q = 0; q < n; q++) { cum += s[q]; const end = q === n - 1 ? M : Math.min(M, Math.floor(M * cum / tot)); dots[q] = Math.max(0, end - j); j = end; total += dots[q]; }
  ok(total === M, `the dots handed out sum to exactly ${M.toLocaleString('en-GB')}: no rounding drift`);
  let dD = 0, dN = 0, uD = 0, uN = 0, far = 0;
  for (let q = 0; q < n; q++) {
    if (Math.abs(d[q] - Rf) < P.PULSE.SIGMA) { if (N.stations[q][3] > 1) { dD += dots[q]; dN++; } else { uD += dots[q]; uN++; } }
    else if (d[q] > Rf + 6 * P.PULSE.SIGMA) far += dots[q];
  }
  const da = dD / Math.max(1, dN), ua = uD / Math.max(1, uN);
  ok(da > ua, `in the front band a duplicated body averages ${da.toFixed(1)} dots against ${ua.toFixed(1)} for a unique one — the copy count, measured, is the only cause`);
  ok(far > 0, `the belt away from the front keeps its base dust (${far.toLocaleString('en-GB')} dots)`);
}

console.log('\n' + (fail ? `${fail} FAILED` : 'all checks passed') + (refused ? `, ${refused} NOT EXAMINED` : ''));
process.exit(fail ? 1 : 0);