GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / globalgrid2050 / kuiper-grid/i0073/cartridges

Kuiper Programs (part 12)

A JavaScript module in the cartridges folder of GlobalGrid2050 covering solar, cables, substations and transformers, using SHA-256, and uses data from the faraday repository.

511 lines of JavaScript from globalgrid2050, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1256 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. Kuiper Programs interaction · globalgrid2050 / kuiper-grid/i0073/cartridges/005100000000-kuiper-programs.js lines 701–1211

Kuiper Programs

A JavaScript module in the cartridges folder of GlobalGrid2050 covering solar, cables, substations and transformers, using SHA-256, and uses data from the faraday repository.

interactionglobalgrid2050 / kuiper-grid/i0073/cartridges/005100000000-kuiper-programs.js · lines 701–1211 of 1211 (continued from section 1255) · Not reached from any entry point (candidate for review) · pattern itemOf (shared by 3 files)

What it does
It draws solar, cables, substations and transformers. Defines 100 functions or classes, including closestPair, blackSky, nameInLines, makeBody, bodyTo. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'kuiper'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: solar, cables, substations, transformers.
Inputs & outputs
In: data source: faraday data; JSON file current.json.
What it achieves
It makes body (`makeBody`), sets tag (`setTag`) and merges menu (`mergeMenu`). A cartridge of the Kuiper shell. Its code works with 50 kW, 500 kW and 604 GWh. It responds to click, keydown and focus events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · kuiper-grid/i0073/cartridges · JavaScript module
Uses
Faraday — Index Page (estate URL), Wafer Development Environment — Proof S0004 Page (estate URL), ./fire.js
Used by
none found
Produces
closestPair, blackSky, nameInLines, makeBody, bodyTo, labels, bodyJump, bodyMove, bodyDrawnDiameter, bodyDotPx, sheet, setTag
Defines here
runsHere, fitMenu, open, close, el, runIt, itemOf, render, stop, c0, fireCommand, close, line, label, table, sldNetwork, sldPieces, line, ring, sldLayout, SYMBOL, sldFinal, makeSldBody, nameLayer, amberName, pocWords, makeSldNames, at, addAmberName, placeSldNames
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/i0073/cartridges/005100000000-kuiper-programs.js:701-1211 · blob 94b73e018e0180ec2e0b544bbc7c5654c0f94876 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
    + '.fm-row:hover,.fm-row:focus{background:#0b1f28;outline:1px solid #1d6470;outline-offset:-1px}'
    + '.fm-name{color:#e8f6fa}'
    + '.fm-said{color:#7f98a3;font-size:10.5px;margin-top:2px;line-height:1.35}'
    + '.fm-cmd{display:none;width:100%;text-align:left;background:none;border:0;color:#5f7783;font:inherit;font-size:10px;'
    + 'padding:0 14px 8px;word-break:break-all;cursor:text}'
    + '#firemenu.rawon .fm-cmd{display:block}'
    + '.fm-cmd:hover,.fm-cmd:focus{color:#8fb3bd;outline:none}'
    + '.fm-note{padding:8px 14px 10px;color:#7f98a3;font-size:10.5px;line-height:1.4}'
    + '.fm-foot{display:flex;flex-wrap:wrap;gap:10px;align-items:center;justify-content:space-between;padding:9px 14px;'
    + 'border-top:1px solid #12303a;color:#5f7783;font-size:10px;line-height:1.4}'
    + '.fm-link{background:none;border:0;color:#7f98a3;font:inherit;font-size:10px;cursor:pointer;text-decoration:underline;padding:4px 0}'
    + '.fm-link:hover,.fm-link:focus{color:#00ffff;outline:none}'
    + '#firemenu #apps{display:flex;flex-wrap:wrap;gap:6px;padding:4px 14px 10px;margin:0}'
    + '#firemenu .fm-view{display:flex;flex-wrap:wrap;gap:6px;padding:4px 14px 10px}'
    + '#firecard{position:fixed;z-index:11;left:14px;top:14px;width:19rem;max-width:calc(100vw - 28px);max-height:70vh;overflow:auto;'
    + 'background:#040a10f2;border:1px solid #1d6470;color:#cfeaf2;padding:12px 14px;font-size:12px;line-height:1.45;display:none}'
    + '#firecard h4{margin:0 0 6px;color:#00ffff;font-size:11px;letter-spacing:.12em;font-weight:normal}#firecard .said{color:#fff;margin:0 0 8px}'
    + '#firecard table{border-collapse:collapse;width:100%;margin:0 0 8px}#firecard td{padding:2px 0;border-bottom:1px solid #12303a}'
    + '#firecard td+td{text-align:right;color:#fff}'
    + '#firecard .small{color:#7f98a3;font-size:10.5px}'
    + '#firecard .x{position:absolute;right:8px;top:6px;background:none;border:0;color:#7f98a3;font:inherit;cursor:pointer}'
    + '#firecard .more{background:none;border:0;color:#7f98a3;font:inherit;font-size:10.5px;text-decoration:underline;cursor:pointer;padding:4px 0}'
    // A THUMB IS NOT A MOUSE POINTER: every control a finger uses is at least 44 px on a phone.
    + '@media (max-width:700px){#firebox{min-height:44px;font-size:13px}'
    + '#firemenu{left:8px;right:8px;transform:none;width:auto;bottom:58px;max-height:64vh}'
    + '.fm-row{min-height:44px;padding:11px 14px}.fm-x{min-height:44px;min-width:44px}'
    + '#firecard{left:8px;right:8px;top:auto;bottom:150px;width:auto;max-height:36vh}}';
  document.head.append(st);

  const bar = document.createElement('div'); bar.id = 'firebar';
  const box = document.createElement('input'); box.id = 'firebox'; box.type = 'text'; box.autocomplete = 'off'; box.spellcheck = false;
  // THE BAR IS EMPTY AND STAYS EMPTY. No command, no JSON, no example: one plain sentence that says what
  // the bar is for, and nothing at all once a reader starts typing.
  box.placeholder = 'Search the tests, or type a command';
  box.setAttribute('aria-label', 'search the tests, or type a command');
  box.setAttribute('aria-expanded', 'false');
  box.setAttribute('aria-controls', 'firemenu');
  bar.append(box); foot.prepend(bar);

  const shade = document.createElement('div'); shade.id = 'fireshade';
  const menu = document.createElement('div'); menu.id = 'firemenu';
  menu.setAttribute('role', 'dialog'); menu.setAttribute('aria-label', 'the tests, the applications and the view');
  document.body.append(shade, menu);
  // THE APPLICATIONS LEAVE THE FACE AT ONCE, not at the first time the pop-up is opened, or the row would
  // still be sitting under the disc until somebody touched the bar.
  const appsFirst = document.getElementById('apps'); if (appsFirst) menu.append(appsFirst);
  const card = document.createElement('div'); card.id = 'firecard'; document.body.append(card);

  // the applications keep their own element, so the record's own checks still find them; it is simply
  // not on the face any more, it is in this pop-up
  const appsEl = document.getElementById('apps');
  const viewEl = document.createElement('div'); viewEl.className = 'fm-view';
  for (const [k, words] of [['n', 'NEW CODE'], ['r', 'RANDOM LINE'], ['/', 'FIND'], ['Backspace', 'WHOLE VIEW']]) {
    const b = document.createElement('button'); b.type = 'button'; b.textContent = words; b.setAttribute('data-k', k);
    b.addEventListener('click', () => { close(); dispatchEvent(new KeyboardEvent('keydown', { key:k })); });
    viewEl.append(b);
  }

  let ALL = dedupeCommands(FIRE_FALLBACK.filter(runsHere)), PINS = curateCommands(ALL, PINNED_SHOWN);
  let SAID = 'the few tests kept inside this page are listed while the published list is read';
  let allPinned = false, rawOn = false;

  function runsHere(c){ try { return FIRE_DRAWS.includes(window.FIRE.parse(c.command).name); } catch (_) { return false; } }
  // THE POP-UP SITS ABOVE THE BAR, WHATEVER HEIGHT THE BAR IS. Its lower edge was a number written down
  // once (64 px), and at 1366x900 the foot is taller than that, so the last row of the list sat behind the
  // bar. The foot is measured instead, every time the pop-up is opened and every time the window changes,
  // and the pop-up is given whatever height is left above it, so it scrolls inside rather than overlapping.
  const fitMenu = () => { const f = document.getElementById('foot');
    const h = f ? Math.round(f.getBoundingClientRect().height) : 56;
    menu.style.bottom = (h + 10) + 'px';
    menu.style.maxHeight = Math.max(160, innerHeight - h - 28) + 'px'; };
  const open = () => { if (menu.classList.contains('open')) { fitMenu(); render(); return; }
    menu.classList.add('open'); shade.style.display = 'block'; box.setAttribute('aria-expanded', 'true'); fitMenu(); render(); };
  const close = () => { menu.classList.remove('open'); shade.style.display = 'none'; box.setAttribute('aria-expanded', 'false'); allPinned = false; };
  const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text !== undefined) e.textContent = text; return e; };

  function runIt(command){
    close();
    box.value = '';                                       // THE BAR GOES BACK TO EMPTY: a fired command is not left sitting in it
    fireCommand(command);
  }
  // AN ANSWER ALWAYS SHUTS THE LIST, whichever way the command was fired: from a row, from the bar, from a
  // ?fire= address, or from a script. The list is what you ask with; the diagram is the answer, and the
  // answer must not arrive behind the question.
  closeFireMenu = () => { close(); box.value = ''; };
  function itemOf(c){
    const wrap = el('div', 'fm-item');
    const b = el('button', 'fm-row'); b.type = 'button';
    b.append(el('div', 'fm-name', plainName(c)));
    if (c.sentence && c.sentence !== plainName(c)) b.append(el('div', 'fm-said', c.sentence));
    b.addEventListener('click', () => runIt(c.command));
    const raw = el('button', 'fm-cmd', c.command); raw.type = 'button';
    raw.title = 'put this command in the bar, to change a number and fire it again';
    raw.addEventListener('click', e => { e.stopPropagation(); box.value = c.command; close(); box.focus(); });
    wrap.append(b, raw);
    return wrap;
  }
  function render(){
    const q = box.value.trim();
    const typed = /^fire\s+\S/i.test(q);
    menu.replaceChildren();
    const head = el('div', 'fm-head');
    head.append(el('div', 'fm-title', typed ? 'A COMMAND' : (q ? 'WHAT MATCHES' : 'TESTS')));
    const x = el('button', 'fm-x', 'close'); x.type = 'button'; x.setAttribute('aria-label', 'close');
    x.addEventListener('click', () => { close(); box.blur(); });
    head.append(x); menu.append(head);
    if (typed) {
      menu.append(el('div', 'fm-sec', 'RUN WHAT IS TYPED'));
      const wrap = el('div', 'fm-item'), b = el('button', 'fm-row'); b.type = 'button';
      b.append(el('div', 'fm-name', q));
      b.append(el('div', 'fm-said', 'runs on this device; nothing you type leaves it'));
      b.addEventListener('click', () => runIt(q));
      wrap.append(b); menu.append(wrap);
    } else if (q) {
      const hits = dedupeCommands(searchCommands(ALL, q));
      menu.append(el('div', 'fm-sec', hits.length ? hits.length + ' OF ' + ALL.length : 'NOTHING MATCHES'));
      if (!hits.length) menu.append(el('div', 'fm-note', 'No test in the published list has all of those words in it. Try fewer words, or a shape: chain, star, tree, sub-board.'));
      for (const c of hits.slice(0, 40)) menu.append(itemOf(c));
    } else {
      menu.append(el('div', 'fm-sec', 'PINNED'));
      const show = allPinned ? PINS : PINS.slice(0, PINNED_SHOWN);
      for (const c of show) menu.append(itemOf(c));
      if (PINS.length > show.length) {
        const wrap = el('div', 'fm-item'), more = el('button', 'fm-row'); more.type = 'button';
        more.append(el('div', 'fm-name', 'More pinned tests (' + (PINS.length - show.length) + ')'));
        more.append(el('div', 'fm-said', 'every other test is reached by typing in the bar above'));
        more.addEventListener('click', () => { allPinned = true; render(); });
        wrap.append(more); menu.append(wrap);
      }
    }
    menu.append(el('div', 'fm-sec', 'THE APPLICATIONS'));
    if (appsEl) menu.append(appsEl);
    menu.append(el('div', 'fm-sec', 'THE VIEW'));
    menu.append(viewEl);
    const foot2 = el('div', 'fm-foot');
    const toggle = el('button', 'fm-link', rawOn ? 'hide the commands' : 'show the commands'); toggle.type = 'button';
    toggle.addEventListener('click', () => { rawOn = !rawOn; menu.classList.toggle('rawon', rawOn); toggle.textContent = rawOn ? 'hide the commands' : 'show the commands'; });
    foot2.append(el('div', null, SAID), toggle);
    menu.append(foot2);
  }

  // the list itself, fetched and hashed the way GridAtlas reads a composition
  loadFireConfig(FIRE_CONFIG).then(r => {
    if (r.ok) {
      const listed = dedupeCommands(r.commands.filter(runsHere));
      if (!listed.length) { SAID = 'the published list holds nothing this device can run, so the few kept in this page are listed'; return render(); }
      const dropped = r.commands.filter(runsHere).length - listed.length;
      ALL = listed;
      const pinned = listed.filter(c => typeof c.pin === 'number').sort((a, b) => a.pin - b.pin);
      PINS = pinned.length ? pinned : curateCommands(listed, 100);
      SAID = listed.length + ' tests, list ' + r.generation + ', fetched with no cache and hashed here'
           + (dropped ? '; ' + dropped + ' repeats of another test left out' : '');
    } else SAID = 'the published list was not used (' + r.reason + '), so the few kept in this page are listed';
    if (menu.classList.contains('open')) render();
  }).catch(e => { SAID = 'the published list was not used (' + (e && e.message ? e.message : e) + '), so the few kept in this page are listed';
    if (menu.classList.contains('open')) render(); });

  // KEYS TYPED IN THE BOX STAY IN THE BOX, and a press inside the pop-up never reaches the disc behind it.
  // BUT ESCAPE IS NOT A KEY THE POP-UP KEEPS. Driving the face found this: tab into the bar, which opens the
  // pop-up, walk into the list, and press Escape - nothing happened, because this very line swallowed it
  // before the window listener that closes the pop-up could hear it. From then on every key belonged to a
  // list the reader thought was shut: / did not open the find box and WHOLE VIEW did not bring the disc
  // back. Escape now closes the pop-up wherever it is pressed inside it, and hands the keyboard back.
  const stop = e => {
    if (e.type === 'keydown' && e.key === 'Escape') { e.stopPropagation(); close(); box.blur(); return; }
    e.stopPropagation();
  };
  for (const x of [box, menu, card]) for (const ev of ['keydown', 'keyup', 'keypress', 'pointerdown', 'mousedown', 'touchstart', 'wheel', 'click']) x.addEventListener(ev, stop);
  box.addEventListener('focus', open);
  box.addEventListener('click', open);
  box.addEventListener('input', () => { if (menu.classList.contains('open')) render(); else open(); });
  box.addEventListener('keydown', e => {
    if (e.key === 'Escape') { close(); box.blur(); return; }
    if (e.key !== 'Enter') return;
    const q = box.value.trim(); if (!q) return;
    if (/^fire\s+\S/i.test(q)) return runIt(q);
    const first = dedupeCommands(searchCommands(ALL, q))[0];
    if (first) runIt(first.command);
  });
  shade.addEventListener('pointerdown', e => { e.stopPropagation(); close(); box.blur(); });
  addEventListener('resize', () => { if (menu.classList.contains('open')) fitMenu(); });
  addEventListener('orientationchange', () => { if (menu.classList.contains('open')) fitMenu(); });
  addEventListener('keydown', e => { if (e.key === 'Escape' && menu.classList.contains('open')) { e.preventDefault(); close(); box.blur(); } });
  if (typeof layout === 'function') layout();
  // ?fire=<command> still runs a command on arrival: every firing is a link
  try { const q = new URLSearchParams(location.search).get('fire'); if (q) setTimeout(() => fireCommand(/^fire\s/i.test(q) ? q : 'fire ' + q), 600); } catch (_) {}
}
// SOMETHING IS ON THE SCREEN AT ONCE. The bar used to be built only after the whole record had loaded and
// the application buttons had been made, so a visitor on a slow line saw a black page with nothing on it
// while a megabyte arrived. It is built as soon as this file runs.
if (document.readyState === 'loading') addEventListener('DOMContentLoaded', () => { try { makeFireBar(); } catch (_) {} });
else { try { makeFireBar(); } catch (_) {} }

let lastFire = null;
const c0 = text => { try { return window.FIRE.parse(text).inputs; } catch (_) { return {}; } };
// THE FIGURES A READER ACTUALLY WANTS, in the order an engineer would read them out. Everything else is
// behind MORE: the card used to be a table of fourteen rows and a paragraph, which is a page, not an answer.
const CARD_FIRST = ['connection point kw', 'lowest volts pu', 'highest volts pu', 'worst transformer pct', 'busiest cable amps',
                    'p poc kw', 'worst tx pct', 'export limit kw'];
function fireCommand(text){
  if (closeFireMenu) { try { closeFireMenu(); } catch (_) {} }
  const card = document.getElementById('firecard'); if (!card) return null;
  const F = (typeof window !== 'undefined' && window.FIRE) || null;
  const close = () => { const b = document.createElement('button'); b.className = 'x'; b.type = 'button'; b.textContent = 'close';
    b.setAttribute('aria-label', 'close this answer'); b.addEventListener('click', () => { card.style.display = 'none'; }); return b; };
  const line = (tag, cls, t) => { const e = document.createElement(tag); if (cls) e.className = cls; e.textContent = t; return e; };
  card.replaceChildren(close()); card.style.display = 'block';
  // ON A PHONE THE ANSWER SITS ABOVE THE BAR THAT ASKED FOR IT, against the real height of the foot.
  if (innerWidth <= 700) { const f = document.getElementById('foot'); if (f) card.style.bottom = Math.round(f.getBoundingClientRect().height + 8) + 'px'; }
  let out;
  try { if (!F) throw new Error('the commands did not load'); out = F.fire(text); }
  catch (e) { card.append(line('h4', null, 'NOT RUN'), line('p', 'said', String(e.message || e))); lastFire = { ran:false, error:String(e.message || e) }; return lastFire; }
  if (!out.ran) { card.append(line('h4', null, 'NOT RUN'), line('p', 'said', 'No command called "' + out.name + '" runs here yet. These do: ' + F.names.join(', ') + '.')); lastFire = { ran:false, name:out.name }; return lastFire; }
  card.append(line('h4', null, out.family + '  ·  RAN ON YOUR DEVICE'), line('p', 'said', out.said));
  // one flat list of every figure, then the few that lead
  const rows = [];
  for (const [k, v] of Object.entries(out.numbers)) { if (v && typeof v === 'object') for (const [k2, v2] of Object.entries(v)) rows.push([k + ' ' + k2, v2]); else rows.push([k, v]); }
  const label = k => k.replace(/_/g, ' ');
  const lead = [], rest = [];
  for (const r of rows) (CARD_FIRST.includes(label(r[0])) ? lead : rest).push(r);
  while (lead.length < 4 && rest.length) lead.push(rest.shift());
  const table = list => { const tb = document.createElement('table');
    for (const [k, v] of list) { const tr = document.createElement('tr');
      tr.append(line('td', null, label(k)), line('td', null, v === null ? 'none' : String(v))); tb.append(tr); }
    return tb; };
  card.append(table(lead.slice(0, 4)));
  if (rest.length || lead.length > 4) {
    const more = line('button', 'more', 'more (' + (rest.length + Math.max(0, lead.length - 4)) + ' figures, and how)'); more.type = 'button';
    const box = document.createElement('div'); box.style.display = 'none';
    box.append(table(lead.slice(4).concat(rest)), line('p', 'small', 'How: ' + out.how),
      line('p', 'small', 'Every input is a public estimate. Change any number in the command and fire again: it runs here and nothing you type leaves this device. An estimate, not a study; provided as is, without warranty of any kind.'));
    more.addEventListener('click', () => { const on = box.style.display === 'none'; box.style.display = on ? 'block' : 'none';
      more.textContent = on ? 'less' : 'more (' + (rest.length + Math.max(0, lead.length - 4)) + ' figures, and how)'; });
    card.append(more, box);
  }
  lastFire = { ran:true, name:out.name, family:out.family, numbers:out.numbers };
  try { const fp = FIRE_PROGRAM;
    if (out.name === 'site-pulse' || out.name === 'network') { fp.sld = out.name === 'network' ? { kind:'network', net:out.net, solved:out.solved, inputs:c0(text) } : c0(text); if (typeof unisolate === 'function' && iso) unisolate(true);
      programs.push(fp); try { isolate('fire'); } finally { const at = programs.indexOf(fp); if (at >= 0) programs.splice(at, 1); } }      // THE DOTS DRAW THE NETWORK OF THIS COMMAND
    else if (programs.find(p => p.name === 'tests')) isolate('tests'); } catch (e) { console.warn('fire: the dots did not respond', e); }
  return lastFire;
}

// ===== THE SINGLE LINE DIAGRAM, DRAWN BY THE DOTS ================================================
// A site pulse has a real network: grid, connection point, intake cable, busbar, generator, feeders, transformers, loads, solar.
// The lines of the repository that holds the tests leave their places and BECOME that diagram: one dot a line of code, placed along
// the busbar, the feeders and the transformer rings. Then the two pulses of the method run on it: currents summed back to the
// grid, volts out from it; what is over a limit ends amber; what is disconnected ends dark. The engine computes (FIRE.sitePulse.solve);
// the dots show and switch. Values ride in a uniform array read by dot number, so the shell's one draw call is unchanged.
const SLD_MAX = 896;                                  // 224 four-number uniforms: inside what every WebGL 2 device must offer
let sldNow = null, sldLoop = 0;
function sldNetwork(inputs){
  const SP = window.FIRE && window.FIRE.sitePulse; if (!SP) return null;
  const sc = SP.SCENARIOS[inputs.scenario]; if (!sc) return null;
  const site = inputs.site || SP.standardSite(), share = inputs.load_share === undefined ? 1 : inputs.load_share;
  const r = SP.solve(site, sc[1], sc[2], sc[3], share), c = SP.CANDIDATE;
  return { site, r, c, pvShare:sc[1], genOn:sc[2], off:sc[3], over: Math.max(0, -r.p_poc_kw) > site.export_limit_kw };
}
// every piece of the drawing: a list of [x0,y0,x1,y1] lines and [cx,cy,r] rings, each with a tag and its distance from the grid
function sldPieces(net){
  const P = [], subs = net.site.subs, n = subs.length, kmMax = Math.max(...subs.map(s => s.km));
  const line = (tag, d, x0, y0, x1, y1) => P.push({ tag, d, kind:'line', x0, y0, x1, y1, len:Math.hypot(x1 - x0, y1 - y0) });
  const ring = (tag, d, cx, cy, r) => P.push({ tag, d, kind:'ring', cx, cy, r, len:2 * Math.PI * r });
  ring('grid', 0, 0, 0.88, 0.07);
  line('poc', 0.07, 0, 0.80, 0, 0.62); line('poc', 0.25, -0.07, 0.61, 0.07, 0.61);
  line('board', 0.27, 0, 0.59, 0, 0.44);
  line('bus', 0.45, -0.92, 0.42, 0.92, 0.42); line('bus', 0.45, -0.92, 0.395, 0.92, 0.395);
  line('gen', 0.45, -0.62, 0.445, -0.62, 0.57); ring('gen', 0.6, -0.62, 0.65, 0.075);
  subs.forEach((s, i) => { const x = n === 1 ? 0 : -0.8 + 1.6 * i / (n - 1), dx = 0.45 + Math.abs(x), L = 0.12 + 0.2 * s.km / kmMax;
    const t = 'f' + s.n, yT = 0.37 - L;
    line(t, dx, x, 0.37, x, yT);
    ring(t, dx + L, x, yT - 0.06, 0.05); ring(t, dx + L + 0.1, x, yT - 0.175, 0.05);
    const yL = yT - 0.235; line(t, dx + L + 0.2, x, yL, x, yL - 0.12);
    line('load' + s.n, dx + L + 0.32, x - 0.045, yL - 0.13, x, yL - 0.2); line('load' + s.n, dx + L + 0.32, x + 0.045, yL - 0.13, x, yL - 0.2);
    if (s.n === net.site.pv_on) { const sx = x + (x > 0.5 ? -0.13 : 0.13); line('pv', dx + L + 0.26, x + Math.sign(sx - x) * 0.015, yL - 0.05, sx - Math.sign(sx - x) * 0.05, yL - 0.05);
      ring('pv', dx + L + 0.4, sx, yL - 0.05, 0.045); ring('pv', dx + L + 0.4, sx, yL - 0.05, 0.016); } });
  return P;
}
function sldLayout(net, m){
  const P = net.kind === 'network' ? netPieces(net.net) : sldPieces(net), total = P.reduce((t, p) => t + p.len, 0), s = total / m;
  // A SYMBOL IS NOT A LENGTH. Dots were handed out in proportion to how long each piece is, so a cable
  // hundreds of units long took hundreds of dots and the generator - one short stub and a circle two
  // hundredths of the drawing across - got the floor of five, which is a faint pentagon nobody can find.
  // The Supervisor looked at a tree of twelve with its generator RUNNING and could not see a generator.
  // The pieces that are SYMBOLS (the grid, the generator, the solar) are given enough dots to read as the
  // thing they are; the long cables give them up, which costs a cable nothing.
  const SYMBOL = t => t === 'grid' || t === 'gen' || t.startsWith('pv');
  let counts = P.map(p => Math.max(SYMBOL(p.tag) ? (p.kind === 'ring' ? 16 : 6) : (p.kind === 'ring' ? 5 : 2), Math.round(p.len / s)));
  let diff = m - counts.reduce((a, b) => a + b, 0);
  const order = P.map((p, i) => i).sort((a, b) => P[b].len - P[a].len);          // the rounding is taken up by the longest pieces
  for (let q = 0; diff !== 0 && q < 10 * m; q++) { const i = order[q % order.length]; if (diff > 0) { counts[i]++; diff--; }
    else if (counts[i] > (SYMBOL(P[i].tag) ? (P[i].kind === 'ring' ? 16 : 6) : 3)) { counts[i]--; diff++; } }
  const unit = new Float32Array(2 * m), tag = new Array(m), dist = new Float32Array(m); let j = 0, dMax = 0;
  P.forEach((p, i) => { for (let q = 0; q < counts[i] && j < m; q++, j++) { const u = (q + 0.5) / counts[i];
    if (p.kind === 'line') { unit[2*j] = p.x0 + (p.x1 - p.x0) * u; unit[2*j+1] = p.y0 + (p.y1 - p.y0) * u; dist[j] = p.d + p.len * u; }
    else { const a = 2 * Math.PI * u + i; unit[2*j] = p.cx + p.r * Math.cos(a); unit[2*j+1] = p.cy + p.r * Math.sin(a); dist[j] = p.d + p.r; }
    tag[j] = p.tag; dMax = Math.max(dMax, dist[j]); } });
  for (; j < m; j++) { unit[2*j] = unit[0]; unit[2*j+1] = unit[1]; tag[j] = 'grid'; }
  return { unit, tag, dist, dMax, spacing:s };
}
// what each dot ends as: 0..1 brightness, 2 = over a limit (amber), -1 = disconnected (dark)
function sldFinal(net, tag){
  const r = net.r, c = net.c, vs = Object.values(r.V), vBad = Math.max(...vs) > c.volts_high_pu || Math.min(...vs) < c.volts_low_pu;
  return tag.map(t => {
    if (t === 'grid') return 0.95; if (t === 'poc') return net.over ? 2 : 0.95; if (t === 'board') return 0.9; if (t === 'bus') return vBad ? 2 : 0.95;
    if (t === 'gen') return net.genOn ? 1 : -1; if (t === 'pv') return net.pvShare > 0 ? 1 : -1;
    const k = +t.replace(/\D/g, ''), load = r.tx_loading_pct['lv' + k];
    if (load === undefined) return -1;                                               // a disconnected substation
    if (t[0] === 'l') return (net.off.includes('pvload') && k === net.site.pv_on) ? -1 : 0.85;
    return load > 100 ? 2 : 0.3 + 0.65 * Math.min(1, load / 100); });
}
function makeSldBody(st){
  const net = (st.prog.sld && st.prog.sld.kind === 'network') ? st.prog.sld : sldNetwork(st.prog.sld || {}); if (!net) return null;
  // EVERY DOT OF THE SKY CAN BE CALLED: the diagram's dots are lines of code from the whole record, evenly through all the keys,
  // so they leave from everywhere on the disc at once.
  // EVERY DOT OF THE DIAGRAM IS A REAL LINE OF CODE, AND SAYS WHOSE. The shell answers a tap on dot j with the piece of work
  // st.idx[j]; a diagram has more dots than the application has pieces of work, so a tap found nothing, threw, and never let the
  // mouse go. So dot j is given the piece of work that issued its key (commits are in key order: a halving search), its place is
  // that work's own middle line, and a tap on the diagram opens that work.
  const m = SLD_MAX, from = new Float32Array(2 * m), owner = new Array(m);
  for (let j = 0; j < m; j++) { const key = Math.floor((j + 0.5) * SPACE / m); let lo = 0, hi = commits.length - 1;
    while (lo < hi) { const mid = (lo + hi) >> 1; if (commits[mid].k1 > key) hi = mid; else lo = mid + 1; }
    owner[j] = lo; const c0 = commits[lo], p = keyPlace(Math.min(Math.max(key, c0.k0), Math.max(c0.k0, c0.k1 - 1))); from[2*j] = p[0]; from[2*j+1] = p[1]; }
  st.idx = owner;
  const lay = sldLayout(net, m), R = Math.sqrt(SPACE), frac = BODY_RADIUS_MAX, to = new Float32Array(2 * m);
  // THE DRAWING FILLS THE DISC. Each drawing was laid out in its own units and then scaled by how far its
  // farthest point lay FROM THE ORIGIN, which is not where the drawing is: a network whose busbar sits high
  // and whose loads hang low was pushed off centre and left using about half the disc, with a ring of empty
  // dark around it. Its own extent is found, its middle is moved to the middle of the disc, and it is blown
  // up until its farthest dot is at the rim. Nothing about the drawing changes but its size and its place.
  { let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;
    for (let j = 0; j < m; j++) { const x = lay.unit[2*j], y = lay.unit[2*j+1];
      if (x < x0) x0 = x; if (x > x1) x1 = x; if (y < y0) y0 = y; if (y > y1) y1 = y; }
    const mx = (x0 + x1) / 2, my = (y0 + y1) / 2;
    let far = 0;
    for (let j = 0; j < m; j++) { const d = Math.hypot(lay.unit[2*j] - mx, lay.unit[2*j+1] - my); if (d > far) far = d; }
    const k = far > 1e-9 ? 0.97 / far : 1;
    for (let j = 0; j < m; j++) { lay.unit[2*j] = (lay.unit[2*j] - mx) * k; lay.unit[2*j+1] = (lay.unit[2*j+1] - my) * k; }
    lay.spacing *= k; }
  for (let q = 0; q < 2 * m; q++) to[q] = lay.unit[q] * R * frac;
  const gap = closestPair(lay.unit) * R * frac;
  sldNow = { net, lay, final:net.kind === 'network' ? netFinal(net, lay.tag) : sldFinal(net, lay.tag), t0:0, vals:new Float32Array(SLD_MAX) };
  nameLayer();
  sldNames = makeSldNames(lay, net);
  { const amber = addAmberName(lay, sldNow.final); if (amber) sldNames.push(amber); }
  return { n:m, from, pos:new Float32Array(from), states:[{ shape:'sld', to, gap, frac, hold:0, unresolved:false }], k:-1, gap:0, shown:false, sld:true, sldGap:lay.spacing * R * frac };
}
// ===== THE FEWEST WORDS A DIAGRAM NEEDS ==========================================================
// A picture of nine substations with no word on it anywhere is a pattern, not a single line diagram, to
// anybody who is not an engineer. Three words are added, and no more: GRID where the grid is, what the
// connection point is doing (exports 50 kW, or imports 1,649 kW) where the connection point is, and the
// name of whatever ended AMBER, because amber is the only thing on the picture that is a warning and a
// colour nobody can look up. They are drawn as plain text over the canvas, no boxes and no lines, at the
// place the drawing itself puts them, and they appear only once the dots have landed.
let sldNames = null;
function nameLayer(){
  let el = document.getElementById('sldnames');
  if (!el) { el = document.createElement('div'); el.id = 'sldnames';
    const st = document.createElement('style');
    st.textContent = '#sldnames{position:fixed;inset:0;z-index:4;pointer-events:none}'
      + '#sldnames span{position:absolute;transform:translate(-50%,-50%);color:#cfeaf2;font-size:10.5px;letter-spacing:.06em;'
      + 'white-space:nowrap;text-shadow:0 0 6px #000,0 0 3px #000}'
      + '#sldnames span.warn{color:#ffb454}'
      + '@media (max-width:700px){#sldnames span{font-size:9.5px}}';
    document.head.append(st); document.body.append(el); }
  return el;
}
const AMBER_WORDS = { bus:'volts outside the band', poc:'over the export limit', grid:'', board:'' };
function amberName(tag){
  if (!tag) return '';
  if (AMBER_WORDS[tag] !== undefined) return AMBER_WORDS[tag];
  if (tag.startsWith('tx')) return 'transformer over its rating';
  if (tag.startsWith('load')) return 'volts outside the band at the load';
  if (tag.startsWith('hv')) return 'volts outside the band on this cable';
  if (tag.startsWith('f')) return 'transformer over its rating';
  return '';
}
// WHAT THE CONNECTION POINT IS DOING, in the words the bench itself uses: minus is out to the grid.
function pocWords(net){
  let kw = null;
  if (net.kind === 'network' && net.solved) kw = net.solved.p;
  else if (net.r && net.r.p_poc_kw !== undefined) kw = net.r.p_poc_kw;
  if (kw === null || kw === undefined || !isFinite(kw)) return '';
  const n = Math.abs(Math.round(kw));
  return (kw < 0 ? 'exports ' : 'imports ') + (typeof fmt === 'function' ? fmt(n) : String(n)) + ' kW';
}
// the places, in the drawing's own units AFTER it has been fitted to the disc, so they follow the dots
function makeSldNames(lay, net){
  const want = [], first = tag => { for (let j = 0; j < lay.tag.length; j++) if (lay.tag[j] === tag) return j; return -1; };
  const at = j => ({ x:lay.unit[2*j], y:lay.unit[2*j+1] });
  const g = first('grid'); if (g >= 0) want.push(Object.assign(at(g), { text:'GRID', dy:-0.10, warn:false }));
  const pc = first('poc'), words = pocWords(net);
  if (pc >= 0 && words) want.push(Object.assign(at(pc), { text:words, dy:0, dx:0.22, warn:false }));
  return want;
}
function addAmberName(lay, final){
  const seen = new Set();
  for (let j = 0; j < final.length; j++) {
    if (final[j] !== 2) continue;
    const words = amberName(lay.tag[j]);
    if (!words || seen.has(words)) continue;
    seen.add(words);
    return { x:lay.unit[2*j], y:lay.unit[2*j+1], text:words, dy:-0.06, warn:true };
  }
  return null;
}
// THE WORDS FOLLOW THE PICTURE. They are put where they belong every time the camera moves, and nowhere
// else: no animation loop of their own is started, because a loop that runs for ever to move three words
// is a loop that runs for ever.
function placeSldNames(){
  const el = document.getElementById('sldnames');
  if (!el) return;
  if (!sldNames || !body || !body.sld || !body.shown || bodyAnim || !sldNow) { el.replaceChildren(); return; }
  const R = Math.sqrt(SPACE), frac = BODY_RADIUS_MAX;
  if (el.childElementCount !== sldNames.length) {
    el.replaceChildren(...sldNames.map(n => { const sp = document.createElement('span');
      sp.textContent = n.text; if (n.warn) sp.className = 'warn'; return sp; }));
  }
  sldNames.forEach((n, i) => { const sp = el.children[i]; if (!sp) return;
    const wx = (n.x + (n.dx || 0)) * R * frac, wy = (n.y + (n.dy || 0)) * R * frac;
    sp.style.left = ((wx - cx) * zoom + innerWidth / 2) + 'px';
    sp.style.top = (innerHeight / 2 - (wy - cy) * zoom) + 'px'; });
}
addEventListener('wheel', placeSldNames, { passive:true });
addEventListener('pointermove', placeSldNames);
addEventListener('pointerup', placeSldNames);
addEventListener('resize', placeSldNames);
addEventListener('orientationchange', placeSldNames);

function sldUniforms(){
  if (!BP) return; gl.useProgram(BP);
  const on = !!(body && body.sld && sldNow);
  gl.uniform1f(gl.getUniformLocation(BP, 'u_sld'), on ? 1 : 0);
  if (on) gl.uniform4fv(gl.getUniformLocation(BP, 'u_val[0]'), sldNow.vals);
}
function sldTick(now){
  sldLoop = 0; if (!(body && body.sld && sldNow)) return;
  const S = sldNow, m = body.n, arrived = !bodyAnim && body.shown;
  if (arrived && !S.t0) S.t0 = now;
  const t = S.t0 ? (now - S.t0) / 1000 : -1, T = 1.5, D = S.lay.dMax, w = D * 0.06;
  for (let j = 0; j < m; j++) { const d = S.lay.dist[j], f = S.final[j]; let v;
    if (t < 0) v = 0.55;                                                              // in flight: every dot alike
    else if (t < T) { const front = D * (1 - t / T); v = Math.abs(d - front) < w ? 1.25 : (d > front ? 0.5 : 0.22); }      // PULSE ONE: back toward the grid
    else if (t < 2 * T) { const front = D * (t / T - 1); v = Math.abs(d - front) < w ? 1.25 : (d < front ? f : 0.22); }     // PULSE TWO: out from the grid, leaving the answer
    else v = f;
    S.vals[j] = v; }
  sldUniforms(); placeSldNames(); dirty = true;
  if (t < 2 * T + 0.2) sldLoop = requestAnimationFrame(sldTick);
}
function sldStart(){ if (!sldLoop) sldLoop = requestAnimationFrame(sldTick); }

// ===== ANY RADIAL NETWORK, DRAWN BY THE DOTS: fire network {"seed":N} ==========================
// The generator's network (a star, a chain, a tree, sub-boards) laid out as a single line diagram: the busbar on top, every
// substation in its own column, a branch leaving its parent's tee sideways and then down, so no two lines ever share a place.
function netPieces(net){
  const P = [], subs = net.subs, n = subs.length, kids = {}; subs.forEach(s => (kids[s.parent] = kids[s.parent] || []).push(s.n));
  const col = {}, depth = {}; let c = 0;
  (function walk(p, d){ for (const k of (kids[p] || [])) { col[k] = c++; depth[k] = d; walk(k, d + 1); } })(0, 1);
  const maxD = Math.max(...Object.values(depth)), dy = Math.min(0.17, 1.05 / maxD), X = k => n === 1 ? 0 : -0.9 + 1.8 * col[k] / (n - 1), Y = k => 0.37 - dy * (depth[k] - 1) - 0.05;
  const line = (tag, d, x0, y0, x1, y1) => { const len = Math.hypot(x1 - x0, y1 - y0); if (len > 1e-6) P.push({ tag, d, kind:'line', x0, y0, x1, y1, len }); return d + len; };
  const ring = (tag, d, cx, cy, r) => P.push({ tag, d, kind:'ring', cx, cy, r, len:2 * Math.PI * r });
  ring('grid', 0, 0, 0.9, 0.06); let d0 = line('poc', 0.06, 0, 0.83, 0, 0.66); line('poc', d0, -0.06, 0.65, 0.06, 0.65); d0 = line('board', d0, 0, 0.63, 0, 0.45);
  line('bus', d0, -0.95, 0.43, 0.95, 0.43); line('bus', d0, -0.95, 0.405, 0.95, 0.405);
  const teeD = { 0: d0 };
  const sym = (tagT, tagL, tagP, d, x, y, s, r) => {                     // transformer, load and any solar, hanging from (x, y)
    let dd = line(tagT, d, x, y - 0.012, x, y - 0.04); ring(tagT, dd, x, y - 0.04 - r, r); ring(tagT, dd + 0.05, x, y - 0.04 - 3 * r - 0.012, r);
    const yl = y - 0.04 - 4 * r - 0.024; dd = line(tagT, dd + 0.1, x, yl, x, yl - 0.05);
    line(tagL, dd, x - 0.03, yl - 0.06, x, yl - 0.105); line(tagL, dd, x + 0.03, yl - 0.06, x, yl - 0.105);
    if (s.pv_kw > 0) { const sx = x + 0.06; line(tagP, dd, x + 0.012, yl - 0.025, sx - 0.03, yl - 0.025); ring(tagP, dd + 0.05, sx, yl - 0.025, 0.026); ring(tagP, dd + 0.05, sx, yl - 0.025, 0.009); }
    if (net.generator_at === s.n && net.generator_kw > 0) { const gx = x - 0.06; line('gen', dd, x - 0.012, yl - 0.025, gx + 0.03, yl - 0.025); ring('gen', dd + 0.05, gx, yl - 0.025, 0.028); } };
  if (net.generator_at === 0 && net.generator_kw > 0) { line('gen', d0, -0.75, 0.455, -0.75, 0.56); ring('gen', d0 + 0.15, -0.75, 0.62, 0.06); }
  const r = Math.min(0.032, 0.6 / n / 2.4 + 0.012);
  (function walk(p){ for (const k of (kids[p] || [])) { const s = subs[k - 1], x = X(k), y = Y(k), t = 'hv' + k; let d;
      if (p === 0) d = line(t, teeD[0] + Math.abs(x), x, 0.393, x, y);
      else { d = line(t, teeD[p], X(p) + 0.012, Y(p), x, Y(p)); d = line(t, d, x, Y(p) - 0.012, x, y); }
      teeD[k] = d; sym('tx' + k, 'load' + k, 'pv' + k, d, x, y, s, r); walk(k); } })(0);
  let far = 0; for (const p of P) far = Math.max(far, p.kind === 'ring' ? Math.hypot(p.cx, p.cy) + p.r : Math.max(Math.hypot(p.x0, p.y0), Math.hypot(p.x1, p.y1)));
  const k = 0.98 / Math.max(0.98, far);                                   // the whole drawing inside the disc
  for (const p of P) { if (p.kind === 'ring') { p.cx *= k; p.cy *= k; p.r *= k; } else { p.x0 *= k; p.y0 *= k; p.x1 *= k; p.y1 *= k; } p.len *= k; }
  return P;
}
function netFinal(model, tag){
  const net = model.net, r = model.solved, e = r.each, c = window.FIRE.topo.C, over = Math.max(0, -r.p) > net.export_limit_kw, aMax = Math.max(1e-9, r.amps);
  const bad = v => v > c.volts_high_pu || v < c.volts_low_pu;
  return tag.map(t => { if (t === 'grid') return 0.95; if (t === 'poc') return over ? 2 : 0.95; if (t === 'board') return 0.9; if (t === 'bus') return bad(e.volts.board) ? 2 : 0.95;
    if (t === 'gen') return model.inputs.generator ? 1 : -1;
    const k = t.replace(/\D/g, '');
    if (t.startsWith('pv')) return (model.inputs.solar === undefined ? 1 : model.inputs.solar) > 0 ? 1 : -1;
    if (t.startsWith('load')) return bad(e.volts['lv' + k]) ? 2 : 0.85;
    if (t.startsWith('tx')) return e.tx['lv' + k] > 100 ? 2 : 0.3 + 0.65 * Math.min(1, e.tx['lv' + k] / 100);
    return bad(e.volts['hv' + k]) ? 2 : 0.3 + 0.65 * Math.min(1, e.amps['hv' + k] / aMax); });
}

// ===== THE POINTER IS ALWAYS LET GO ==============================================================
// THE FAULT: the shell answers a tap on body dot j with commits[iso.idx[j]] and calls pointerGone(e)
// AFTERWARDS. A drawn diagram has 896 dots and an application has however many pieces of work it has,
// so for most dots iso.idx[j] was undefined, reading .k0 of undefined threw, pointerGone never ran,
// the pointer stayed in the map and the disc went on following a mouse whose button was up. The cure
// above gives every diagram dot its own piece of work, so nothing throws. THIS is the second belt:
// whatever any handler does, the pointer is let go. A listener added here runs AFTER the shell's own
// (they are on the same target in the same phase, and an exception in one listener never stops the
// next), so a throw anywhere in the shell's answer can no longer leave a button pressed for ever.
// It is registered from a timer so that it is registered after the shell's, whatever the load order.
setTimeout(function(){
  var net = function(e){ try { if (typeof pointerGone === 'function') pointerGone(e); } catch (_) {} };
  addEventListener('pointerup', net);
  addEventListener('pointercancel', net);
  addEventListener('pointerout', function(e){ if (e.pointerType === 'mouse' && !e.relatedTarget && e.buttons === 0) net(e); });
  addEventListener('blur', function(){ try { if (typeof pts !== 'undefined' && pts.clear) pts.clear();
    if (typeof drag !== 'undefined') drag = null; if (typeof pinch !== 'undefined') pinch = null; } catch (_) {} });
}, 0);