GLOBALGRID2050 / EXPLORE CODE

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

Kuiper Programs and 2 more files (part 6)

A JavaScript file in the cartridges folder of GlobalGrid2050 that draws interconnectors, london underground, grid 66kV and motorway services, and uses data from the faraday repository.

700 lines of JavaScript and HTML from globalgrid2050, in 3 files. Topic: Kuiper, cosmos and drawing engines. Section 1399 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 render · globalgrid2050 / kuiper-grid/i0088/cartridges/008800000000-kuiper-programs.js lines 4621–4659
  2. Kuiper Grid — I0088 Page render · globalgrid2050 / kuiper-grid/i0088/index.html lines 1–108
  3. Kuiper Programs render · globalgrid2050 / kuiper-grid/i0089/cartridges/008900000000-kuiper-programs.js lines 1–553

Kuiper Programs

A JavaScript file in the cartridges folder of GlobalGrid2050 that draws interconnectors, london underground, grid 66kV and motorway services, and uses data from the faraday repository.

Set aside from the main view: 99% of its lines are the same as kuiper-grid/i0089/cartridges/008900000000-kuiper-programs.js (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with Kuiper Programs; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9873 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/i0089/cartridges/008900000000-kuiper-programs.js:1-4690 56db141d495fee7c1255ae88d29ac3f7a5fb8724
  • sha256 daff29fbdd867ff327ebc8c6c1338405afe422e1722b551bf8a6898ccb31880f
  • target sha256 71eba91ad4eea2f2602c4ca3427ad22b95e0514f9e9087cd231ed7dcf5fa4633
  • group of 3 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines

renderglobalgrid2050 / kuiper-grid/i0088/cartridges/008800000000-kuiper-programs.js · lines 4621–4659 of 4659 (continued from section 1392) · Not reached from any entry point (candidate for review) · pattern drawLocalSystem (shared by 2 files)

What it does
It draws interconnectors, london underground, grid 66kV and motorway services. Defines 253 functions or classes, including reFire, closestPair, blackSky, nameInLines, makeBody. 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: interconnectors, 750kV, 400kV, 275kV, 132kV, 110kV.
Inputs & outputs
In: data source: faraday data; JSON file interconnectors.config.json; GeoJSON file london_underground.geojson; GeoJSON file grid_66kv.geojson; GeoJSON file motorway_services.geojson; GeoJSON file railways.geojson; JSON file current.json. Out: canvas drawing. Voltage levels named: 750kV, 400kV, 275kV, 132kV, 110kV, 66kV, 50kV, 33kV.
What it achieves
It makes body (`makeBody`), sets tag (`setTag`) and draws tube map (`drawTubeMap`). A cartridge of the Kuiper shell. Its code works with 33 kV, 11 kV and 275 kV. It responds to click events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · kuiper-grid/i0088/cartridges · script
Uses
Faraday — Index Page (estate URL), Wafer Development Environment — Proof S0004 Page (estate URL), ./fire.js
Used by
mentioned in Standalone (comment link)
Produces
reFire, closestPair, blackSky, nameInLines, makeBody, bodyTo, labels, bodyJump, bodyMove, bodyDrawnDiameter, bodyDotPx, sheet
Defines here
netFinal, bad, net
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/i0088/cartridges/008800000000-kuiper-programs.js:4621-4659 · blob d98009f128a079f2699fc0e940870cfd978bea61 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: agent_infra · users: ai_agent · canonical: duplicate_candidate
  (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);

Kuiper Grid — I0088 Page

A web page in GlobalGrid2050 that uses SHA-256. Published at https://globalgrid2050.com/kuiper-grid/i0088/. It is built from the must step (`must`), the attr step (`attr`) and the sha256 step (`sha256`).

Set aside from the main view: 98% of its lines are the same as kuiper-grid/i0073/index.html (globalgrid2050), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with Kuiper Grid — I0097 Page; read that one first. All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line-jaccard 0.9802 to globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 kuiper-grid/i0073/index.html:1-108 073cc692d3750aac95d1654f9a0b315d2b568d11
  • sha256 6919dc77d2659a935e0fce5bad207b1461777489d6ff171a676ad65f90547f0c
  • target sha256 fb96bcf6b8a812967bfc0fc386a3d015e90f507f76ce774101a57ea29aba253a
  • group of 16 (identity.json near-copy edges >= 0.9)
  • canonical rule: reachable, newest stamp, core repo, most lines
  • re-pointed by apply.py version rule from file 3650 to file 3695; similarity was measured to file 3650

renderglobalgrid2050 / kuiper-grid/i0088/index.html · lines 1–108 of 108 · Entry point

What it does
It draws its content. Defines must, attr, sha256. Uses libraries …/NAME, ' + attr(url.href) + '. Side effects: changes the web page (DOM); 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).
Inputs & outputs
In: JSON file current.json. Out: web page.
Downstream impact
Used directly by 1 file: GlobalGrid2050 — Kuiper Grid Page (globalgrid2050, https://globalgrid2050.com/kuiper-grid/). Reached from 108 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); GlobalGrid2050 — Compute Page (globalgrid2050, https://globalgrid2050.com/compute/). It is itself an entry point, published at https://globalgrid2050.com/kuiper-grid/i0088/.
What it achieves
THE WAY OUT. This page is a composer: with script off, or with a refused record, it renders nothing a reader can click. It reads `./current.json`.
Why it matters
Loaded by the Kuiper Grid page at https://globalgrid2050.com/kuiper-grid/.
Application
globalgrid2050 · kuiper-grid/i0088 · page
Uses
Manual (link), GlobalGrid2050 — Plant Page (link), GlobalGrid2050 — Kuiper Grid Page (link), GlobalGrid2050 — Compute Page (link), …/NAME, ' + attr(url.href) + '
Used by
linked from GlobalGrid2050 — Kuiper Grid Page (link)
Produces
must, attr, sha256
Defines here
must, attr, sha256
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/i0088/index.html:1-108 · blob 69785a8139634856c38e370f4b5ea880ebc932b2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: agent_infra · users: ai_agent · canonical: production_core
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>globalgrid2050</title>
  <style>
    html,body{margin:0;background:#0b0d12;color:#d8dee9;font:13px/1.5 ui-monospace,Menlo,Consolas,monospace}
    #composer{display:grid;place-items:center;min-height:50vh;padding:24px;text-align:center}
    #composer strong{color:#5ec8f2;letter-spacing:.1em}
    #composer small{color:#8b93a7}
    #waysout{max-width:44rem;margin:0 auto;padding:0 20px 40px;border-top:1px solid #1b2030}
    #waysout h2{font-size:14px;color:#5ec8f2;letter-spacing:.06em;text-transform:uppercase;margin:24px 0 8px}
    #waysout p{color:#8b93a7;margin:8px 0}
    #waysout ul{margin:10px 0;padding-left:1.1rem}
    #waysout li{margin:7px 0;color:#8b93a7}
    #waysout a{color:#5ec8f2;font-weight:600}
    #waysout .small{font-size:12px;color:#6f7789}
  </style>
</head>
<body data-composer="loading">
  <main id="composer"><div><strong>GLOBALGRID2050</strong><br>checking this page against its record…<br><small>provided as is, without warranty of any kind; a chart, not a design</small></div></main>
  <!-- THE WAY OUT. This page is a composer: with script off, or with a refused
       record, it renders nothing a reader can click. Plain anchors, in the
       served bytes, so this build is never a dead end. -->
  <nav id="waysout">
    <h2>Build i0088 &mdash; part of the Kuiper</h2>
    <p>This address loads one development build. If it has not loaded, or you have script switched off, start from the plain pages:</p>
    <ul>
      <li><a href="/kuiper-grid/manual.html">The manual</a> &mdash; what this is, what to type, what the answer means, and what it refuses</li>
      <li><a href="/plant/">Will this string go over 1500&nbsp;V on the coldest morning?</a> &mdash; three commands ready to copy</li>
      <li><a href="/kuiper-grid/">All development builds</a></li>
      <li><a href="/compute/">Independent compute</a> &nbsp;&middot;&nbsp; <a href="/">Everything else published here</a></li>
    </ul>
    <p class="small">A development build. Two of the four limits this engine measures a design against have no source in any document, and a verdict that turns on one of them is provisional. <a href="/kuiper-grid/manual.html#unsourced">The manual says which.</a></p>
    <p class="small">A chart, not a design. Not a connection offer, not a constructability assessment, not a consenting design. No output of it is engineering.</p>
  </nav>
  <script type="module">
    // THE COMPOSER. GridAtlas's pattern as it stands (gridatlas/atlas/index.html): one frozen shell, features as hashed
    // cartridges, and current.json, the pointer, saying which. This page is the ONE ADDRESS that never changes. It reads
    // the pointer, fetches the shell, fetches every cartridge the pointer names, and lets a cartridge in ONLY if its
    // bytes hash to what the pointer says. A release is a change to the pointer; a rollback is the pointer put back;
    // the shell is never edited. If anything does not match, nothing runs and the page says so in plain words.
    //
    // Two slots:  replace-script  the shell's <script src="…/NAME"> is pointed at the cartridge instead
    //             import-map      an import of NAME anywhere in the shell resolves to the cartridge instead
    // A cartridge is ONE file with no imports of its own neighbours: one file, one job.
    const CLOSE = '</scr' + 'ipt>';
    const box = document.getElementById('composer');
    const must = (ok, why) => { if (!ok) throw new Error(why); };
    const attr = v => String(v).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
    const sha256 = async bytes => [...new Uint8Array(await crypto.subtle.digest('SHA-256', bytes))].map(b => b.toString(16).padStart(2, '0')).join('');

    try {
      const r = await fetch('./current.json', { cache: 'no-store' });
      must(r.ok, 'the record of this page could not be read (' + r.status + ')');
      const cur = await r.json();
      must(cur && cur.schema === 'globalgrid.current.v1', 'the record of this page is in a form this page does not know');
      must(cur.architecture === 'IMMUTABLE_SHELL_PLUS_HASHED_CARTRIDGES', 'the record of this page names another architecture');
      must(Array.isArray(cur.cartridge_order) && Array.isArray(cur.cartridges) && cur.shell, 'the record of this page is incomplete');

      const shellUrl = new URL(cur.shell.index, location.href), shellBase = new URL(cur.shell.base, location.href).href;
      const sr = await fetch(shellUrl, { cache: 'no-store' });
      must(sr.ok, 'the page itself could not be fetched (' + sr.status + ')');
      const shellBytes = await sr.arrayBuffer();
      must(await sha256(shellBytes) === cur.shell.sha256, 'the page itself is not the one that was released');
      let html = new TextDecoder('utf-8').decode(shellBytes);
      must(/<head\b/i.test(html) && /<body\b/i.test(html), 'the page itself is not a page');

      const byId = new Map(cur.cartridges.map(c => [c.id, c])), loaded = [], imports = {};
      const tags = new RegExp('<script\\b([^>]*)\\bsrc=(["\'])([^"\']+)\\2([^>]*)>\\s*<\\/script>', 'gi');
      for (const id of cur.cartridge_order) {
        const c = byId.get(id);
        must(c, 'a part named in the record is missing from it: ' + id);
        must(/^[a-f0-9]{64}$/.test(c.sha256 || ''), id + ': the record holds no fingerprint for it');
        must(c.slot === 'replace-script' || c.slot === 'import-map', id + ': a slot this page does not have');
        must(typeof c.replaces === 'string' && c.replaces, id + ': the record does not say what it replaces');
        const url = new URL(c.path, location.href);
        const cr = await fetch(url, { cache: 'no-store' });
        must(cr.ok, id + ' could not be fetched (' + cr.status + ')');
        must(await sha256(await cr.arrayBuffer()) === c.sha256, id + ' is not the file that was released');
        if (c.slot === 'import-map') imports[new URL(c.replaces, shellBase).href] = url.href;
        else {
          let done = false;
          html = html.replace(tags, (full, a, q, src, b) => {
            if (done || String(src).split(/[?#]/)[0].split('/').pop() !== c.replaces) return full;   // matched by file name
            done = true;
            return '<script' + a + 'data-cartridge="' + attr(id) + '" src="' + attr(url.href) + '"' + b + '>' + CLOSE;
          });
          must(done, id + ': the page has no place for it (' + c.replaces + ')');
        }
        loaded.push({ id, generation: c.generation, sha256: c.sha256 });
      }
      const state = JSON.stringify({ schema: cur.schema, generation: cur.generation, shell: cur.shell, cartridges: loaded }).replace(/</g, '\\u003c');
      const head = '\n<base href="' + attr(shellBase) + '">'
        + (Object.keys(imports).length ? '\n<script type="importmap">' + JSON.stringify({ imports }).replace(/</g, '\\u003c') + CLOSE : '')
        + '\n<script>window.__COMPOSED__=' + state + ';document.documentElement.dataset.generation=' + JSON.stringify(cur.generation) + ';' + CLOSE;
      html = html.replace(/<head([^>]*)>/i, m => m + head);
      document.open(); document.write(html); document.close();
    } catch (e) {
      console.error('[composer]', e);
      document.body.dataset.composer = 'refused';
      box.innerHTML = '<div><strong>THIS PAGE DID NOT OPEN</strong><br>' + String(e && e.message || e).replace(/[<>&]/g, '')
        + '<br><small>Nothing was run. The released page has not been changed. The plain pages below still work.<br>provided as is, without warranty of any kind; a chart, not a design</small></div>';
    }
  </script>
</body>
</html>

Kuiper Programs

A JavaScript file in the cartridges folder of GlobalGrid2050 that draws interconnectors, london underground, grid 66kV and motorway services, and uses data from the faraday repository.

renderglobalgrid2050 / kuiper-grid/i0089/cartridges/008900000000-kuiper-programs.js · lines 1–553 of 4690 · Not reached from any entry point (candidate for review) · pattern drawLocalSystem (shared by 2 files)

What it does
It draws interconnectors, london underground, grid 66kV and motorway services. Defines 253 functions or classes, including reFire, closestPair, blackSky, nameInLines, makeBody. 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: interconnectors, 750kV, 400kV, 275kV, 132kV, 110kV.
Inputs & outputs
In: data source: faraday data; JSON file interconnectors.config.json; GeoJSON file london_underground.geojson; GeoJSON file grid_66kv.geojson; GeoJSON file motorway_services.geojson; GeoJSON file railways.geojson; JSON file current.json. Out: canvas drawing. Voltage levels named: 750kV, 400kV, 275kV, 132kV, 110kV, 66kV, 50kV, 33kV.
What it achieves
It makes body (`makeBody`), sets tag (`setTag`) and draws tube map (`drawTubeMap`). A cartridge of the Kuiper shell. Its code works with 33 kV, 11 kV and 275 kV. It responds to click events.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · kuiper-grid/i0089/cartridges · script
Uses
Faraday — Index Page (estate URL), Wafer Development Environment — Proof S0004 Page (estate URL), ./fire.js
Used by
none found
Produces
reFire, closestPair, blackSky, nameInLines, makeBody, bodyTo, labels, bodyJump, bodyMove, bodyDrawnDiameter, bodyDotPx, sheet
Defines here
reFire, closestPair, blackSky, nameInLines, makeBody, bodyTo, labels, bodyJump, bodyMove, bodyDrawnDiameter, bodyDotPx, sheet, setTag, revealCode, sparksTo, ensureGlow, systemFind, systemWork, systemProgram, fireSystem, systemCard, put, systemsList, tubeClassOf, tubeIsTransmission, tubeInk, TUBE_ADJ, tubeName, tubeDegree, TUBE_BRIDGES
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/i0089/cartridges/008900000000-kuiper-programs.js:1-553 · blob 56db141d495fee7c1255ae88d29ac3f7a5fb8724 · 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
'use strict';
// kuiper-programs.js - a cartridge of the Kuiper shell. Cut from the whole page with no change of behaviour;
// replaced, when it is, by a newer file the pointer names and the composer checks by its hash.
let ASM = null, gatherAnim = null, homeAnim = null;
// the live answer window and the way back to a preset: declared here because the bar is built long
// before the part of this file that uses them has run
let fireLive = null, fireAgain = null;
// CHANGE ONE INPUT AND FIRE AGAIN, keeping everything else the reader has set. The view buttons use it.
function reFire(extra){
  if (!fireLive || !fireLive.boxes) return;
  Object.assign(fireLive.boxes.vals, extra);
  fireCommand(fireLive.boxes.cmd(), fireLive.rec, true);
}
// ===== THE BODY: a smaller Kuiper of one application's own work =====================================
let body = null, bodyAnim = null, BP = null, bodyBuf = null;
// THE PALETTE OF THE ONE PULSE. The ring that sweeps the disc is white and ice blue; what it leaves lit is
// the same light, at full brightness. No second look: the saturated green was one, and it is gone.
const FARADAY = [0.80, 0.96, 1.0];
// THE BODY FILLS THE INNER DISC, so a third of the gap is a bigger dot and the body reads from across a
// room without a single dot breaking the rule that makes it a population and not a patch.
const BODY_RADIUS = 0.55, BODY_RADIUS_MAX = 0.92, DOT_MAX_PX = 5, DOT_MIN_PX = 1.0;
const VS_BODY = `#version 300 es
precision highp float;
in vec2 a_pos; uniform float u_zoom, u_size, u_sld; uniform vec2 u_center, u_res; uniform vec4 u_val[224]; out float v_val;
void main(){ gl_Position = vec4((a_pos - u_center) * u_zoom / (0.5*u_res), 0.0, 1.0); gl_PointSize = u_size;
  int i = min(gl_VertexID, 895); v_val = u_sld > 0.5 ? u_val[i >> 2][i & 3] : 1.0; }`;
// A DOT IS A DISC WITH A HARD EDGE, AND IT IS NOT ADDED TO WHAT IS UNDER IT. Light that adds is how
// neighbours merge into a white patch; here a dot covers what it covers and nothing more.
const FS_BODY = `#version 300 es
precision highp float; uniform vec3 u_on; uniform float u_sld; in float v_val; out vec4 o;
// A DIAGRAM'S DOT CARRIES A VALUE: under 0 disconnected, 0 to 1 how bright, about 1.25 the front of a pulse, 2 over a limit.
void main(){ if (length(gl_PointCoord - 0.5) > 0.5) discard; vec3 c = u_on;
  if (u_sld > 0.5 && v_val < -1.5) discard;          // melted away: a solid shapes drawing keeps no loose dots
  if (u_sld > 0.5) { c = v_val < 0.0 ? vec3(0.09, 0.12, 0.15) : v_val > 1.6 ? vec3(1.0, 0.62, 0.15) : v_val > 1.1 ? vec3(1.0) : mix(vec3(0.10, 0.16, 0.20), u_on, v_val); }
  o = vec4(c, 1.0); }`;
// THE GAP, MEASURED. The nearest two centres among the places the module returned, found with a grid
// so a large application costs no more than a small one. Nothing here is judged by eye.
function closestPair(pos){
  const m = pos.length / 2; if (m < 2) return Infinity;
  let x0 = 1e300, x1 = -1e300, y0 = 1e300, y1 = -1e300;
  for (let q = 0; q < pos.length; q += 2) { x0 = Math.min(x0, pos[q]); x1 = Math.max(x1, pos[q]); y0 = Math.min(y0, pos[q+1]); y1 = Math.max(y1, pos[q+1]); }
  const cell = Math.max(1e-9, Math.sqrt(Math.max(1e-18, (x1 - x0) * (y1 - y0)) / m)), grid = new Map();
  let best = Infinity;
  for (let j = 0; j < m; j++) { const gx = Math.floor((pos[2*j] - x0) / cell), gy = Math.floor((pos[2*j+1] - y0) / cell);
    for (let dx = -1; dx <= 1; dx++) for (let dy = -1; dy <= 1; dy++) { const cellm = grid.get((gx + dx) + ':' + (gy + dy)); if (!cellm) continue;
      for (const k of cellm) { const d = Math.hypot(pos[2*j] - pos[2*k], pos[2*j+1] - pos[2*k+1]); if (d < best) best = d; } }
    const key = gx + ':' + gy; (grid.get(key) || grid.set(key, []).get(key)).push(j); }
  return best;
}
// THE BLACK SKY RULE, as one question any body can be asked: are all centres at least three dot radii
// apart? It is the same function the page obeys and the test plants a too tight body against.
function blackSky(pos, dotRadius){ const gap = closestPair(pos); return { gap, dotRadius, ok: gap >= 3 * dotRadius * (1 - 1e-4) }; }   // exactly a third is allowed; the margin is for rounding, not for squeezing
function nameInLines(words){ const w = String(words).split(' '); if (String(words).length <= 9 || w.length < 2) return String(words);
  const half = Math.ceil(w.length / 2); return w.slice(0, half).join(' ') + ' / ' + w.slice(half).join(' '); }
function makeBody(st){
  if (!ASM || !st.idx.length) return null;
  if (st.prog.sld) { const d = makeSldBody(st); if (d) return d; }
  const seq = (st.prog.on.sequence && st.prog.on.sequence.length) ? st.prog.on.sequence : (st.prog.on.shape ? [{ shape:st.prog.on.shape }] : []);
  if (!seq.length) return null;
  const m = st.idx.length, R = Math.sqrt(SPACE), from = new Float32Array(2 * m);
  // ONE DOT FOR EVERY PIECE OF WORK, IN ORDER OF KEY: the module puts dot j at place j, and place 0 is
  // the middle, so the oldest work is the middle of the small Kuiper and the newest is its rim.
  st.idx.forEach((ci, j) => { const c0 = commits[ci], p = keyPlace(c0.k0 + Math.floor((c0.k1 - c0.k0) / 2)); from[2*j] = p[0]; from[2*j+1] = p[1]; });
  // THE SIZE THE SHOW WILL REALLY BE SEEN AT. On a phone the short tile rises under the picture and the
  // disc is refitted smaller above it, so what resolves is decided for THAT size, not for the empty screen.
  const zHome = homeCamera().z * (narrow() ? 0.62 : 1), states = [];
  for (const step of seq) { const shape = step.shape === 'text' ? 'text:' + nameInLines(st.app.button) : step.shape;
    // A NAME NEEDS ENOUGH DOTS TO BE A NAME: about six to a letter. Nine pieces of work cannot spell
    // two words, and a scatter that means nothing is worse than the small Kuiper it would replace.
    // A NAME ONLY WHEN IT CAN BE READ. A letter is a shape of squares and needs a dot for every one of them;
    // with fewer, letters lose strokes (85 pieces of work spelt CABL S). Counted from the module's own
    // lettering, not estimated.
    if (step.shape === 'text') { const ink = ASM.raster ? ASM.raster(nameInLines(st.app.button)) : null;
      const squares = ink ? ink.on.reduce((t, v) => t + v, 0) : 1e9; if (m < squares) continue; }
    let unit; try { unit = ASM.targets(shape, m); } catch (e) { continue; }
    const unitGap = closestPair(unit);
    // large enough that a dot a third of the gap wide is at least a pixel; never larger than the disc
    let frac = BODY_RADIUS; const need = DOT_MIN_PX * 3 / Math.max(1e-12, unitGap * R * zHome);
    if (need > frac) frac = Math.min(BODY_RADIUS_MAX, need);
    const to = new Float32Array(unit.length); for (let q = 0; q < unit.length; q++) to[q] = unit[q] * R * frac;
    const gap = unitGap * R * frac;
    const unresolved = gap * zHome / 3 < DOT_MIN_PX * 0.999;
    // WHAT CANNOT BE RESOLVED IS NOT SHOWN AS IF IT COULD. A state that would need dots under a pixel is
    // left out, and the show ends on the last state that does resolve: the work gathers and STAYS, it
    // is never simply gone from the middle of the disc, which is what a phone showed.
    if (unresolved && states.length) continue;
    states.push({ shape, to, gap, frac, hold:step.hold_ms || 0, unresolved }); }
  if (!states.length) return null;
  return { n:m, from, pos:new Float32Array(from), states, k:-1, gap:0, shown:false };
}
function bodyTo(arr){ if (body) body.live = closestPair(arr);
  if (!BP) { BP = prog(VS_BODY, FS_BODY); bodyBuf = gl.createBuffer(); }
  gl.bindBuffer(gl.ARRAY_BUFFER, bodyBuf); gl.bufferData(gl.ARRAY_BUFFER, arr, gl.DYNAMIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, null);
  sldUniforms(); if (body && body.sld) sldStart(); }
function labels(show){ const o = document.getElementById('o'); if (o) o.style.visibility = show ? 'visible' : 'hidden'; }
function bodyJump(k){ if (!body) return; labels(false); const stt = body.states[k]; body.pos.set(stt.to); body.k = k; body.gap = stt.gap; body.shown = true; bodyAnim = null; bodyTo(body.pos); dirty = true; }
function bodyMove(k){ if (!body) return; labels(false); bodyAnim = { k, t0:performance.now(), from:new Float32Array(body.pos), gap0:body.shown ? body.gap : body.states[k].gap, phase:'move' };
  body.shown = true; dirty = true;
  // A ROW SEVERAL SCREENS WIDE IS SHOWN WHOLE WHILE THE WORK GATHERS ALONG IT, and only then is the
  // reader taken to the near end, where the inverter and the first modules can actually be read.
  if (body.sld && sldShapes && sldShapes.kind === 'string') { try { stringWholeView(); } catch (_) {} } }
// the dot's radius ON THE SCREEN, from the measured gap and the zoom of this moment: a third of the
// gap, never more, however the visitor zooms
// THE SIZE FOLLOWS THE CANVAS, NOT THE SCREEN. This canvas is as many pixels as the window is wide, so a
// point size is already in the units the gap is measured in. Multiplying by the screen's pixel ratio
// drew every dot at twice its size on a real screen and at its right size in every test.
function bodyDrawnDiameter(){ return Math.max(1, 2 * bodyDotPx() * (cv.width / Math.max(1, innerWidth))); }
// A THIRD OF THE GAP AS THE DOTS ARE NOW. At rest the gap is the state's own; in flight it is measured
// from where the dots are at that frame, because leaving the rim they are almost on top of one another
// and no resting spacing describes them.
function bodyDotPx(){ const gap = body.sld ? body.sldGap : body.live !== undefined ? body.live : body.gap;   // a diagram's dot is sized by the spacing along its lines, where a junction would make every dot a speck      // measured every time the dots are placed
  // A WIRING DRAWING'S DOTS ARE THE ENTRANCE AND NOTHING MORE, so they are held to a fine weight: on a
  // drawing several screens wide the same rule would grow them into discs sitting on top of the words.
  const cap = (body.sld && body.fineDots) ? 1.6 : DOT_MAX_PX;
  return Math.max(0.5, Math.min(cap, gap * zoom / 3)); }
// BESIDE THE SHELL, NOT BESIDE THIS FILE. Released, this part lives in a folder of parts and the module lives
// beside the shell; a script asks for a module relative to its own address, so './assemble.mjs' asked for a
// file that is not there. The page's base address is the shell's folder, with the composer or without it.
// AND A FAILED LOAD SAYS SO. The catch used to swallow it, and on the live address the dots simply never
// gathered, with nothing on the page or in the console to say why.
let asmWhy = null;
const asmReady = import(new URL('assemble.mjs', document.baseURI).href).then(m => { ASM = m; })
  .catch(e => { ASM = null; asmWhy = String(e && e.message || e); console.error('[kuiper] the gathering animation could not be loaded:', asmWhy); });
const GATHER_RADIUS = 0.30;                      // of the record's own radius: a body, with the dark disc still around it
function sheet(title, sub){
  const mine = ++cardToken;
  card.classList.remove('short');
  card.replaceChildren();
  card.style.display = 'block';
  card.scrollTop = 0;
  const x = el('button', 'cc-x', '\u00d7'); x.type = 'button'; x.setAttribute('aria-label', 'close');
  x.addEventListener('click', closeCard);
  card.append(x, el('span', 'cc-title', title));
  if (sub) card.append(el('span', 'cc-grey', sub));
  const tagLine = el('div', 'cc-tagline'), tag = el('span', 'cc-tag'), msg = el('span', 'cc-grey');
  tagLine.append(tag, msg); card.append(tagLine);
  const body = el('div', 'cc-body'); card.append(body);
  // THE SINGLE WRITER OF THE STATE. Nothing else touches the chip, and a writer for a card that has
  // been replaced does nothing at all.
  const setTag = (st, text) => { if (mine !== cardToken) return false;
    tag.dataset.s = st; tag.textContent = st; if (text != null) msg.textContent = text; return true; };
  dirty = true;
  return { mine, body, setTag, live: () => mine === cardToken };
}
function revealCode(){
  const w = cardShown && cardShown.window; if (!w) return;
  const cr = card.getBoundingClientRect(), pr = w.node.getBoundingClientRect();
  if (pr.bottom > cr.bottom - 4) card.scrollTop += pr.bottom - cr.bottom + 8;
  else if (pr.top < cr.top) card.scrollTop -= cr.top - pr.top + 8;
  w.scrollToTarget();
}
function sparksTo(arr){ ensureGlow(); gl.bindBuffer(gl.ARRAY_BUFFER, glowBuf);
  gl.bufferData(gl.ARRAY_BUFFER, arr, gl.DYNAMIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, null); }
function ensureGlow(){ if (!PG) { PG = prog(VS_GLOW, FS_GLOW); glowBuf = gl.createBuffer(); } }
// ===== ISOLATE AN APPLICATION =================================================================
// ===== THE MENU: BUTTONS ADDED AS DATA =========================================================
// The shell's own buttons come from cosmos/apps.tsv and cosmos/programs.json, which are inside the frozen shell.
// A button added after the shell was frozen is ONE ENTRY HERE: the same two records the shell reads, and nothing
// else. select.repository lights every piece of work of that repository that is on this record.
const MENU = [
  { app: { app:'tests', button:'TESTS', repo:'ventusltd/faraday', prefixes:[], live:'https://ventusltd.github.io/faraday/' },
    program: { name:'tests', button:'TESTS', select:{ app:'tests', repository:'faraday' }, pulse:{ origin:'centre', seconds:1.5 }, off:{ dim:0.1 },
               on:{ colour:[0.80,0.96,1.0], size:0, bright:0, sparks:1, sequence:[{ shape:'cluster', hold_ms:1500 }, { shape:'text', hold_ms:900 }] },
               end:{ tile:'https://ventusltd.github.io/faraday/' },
               says:'Every test we have run. Choose a sentence in the bar below and it runs again here, on your device.' } },
  // A CORRECTION TO A BUTTON THE SHELL CARRIES. The shell's REAL SYSTEMS row points at a folder two builds old, and its sentence
  // ("a single line view of a real system") describes a different page from the one that opens. The work it lights stays the nine
  // pieces the frozen record holds for it; that is put right when the record is next cut, not here.
  { override:true,
    app: { app:'real-systems', live:'https://globalgrid2050.com/testcode/wafer-development-environment/202609192215-proof-s0004/' },
    program: { name:'real-systems', end:{ tile:'https://globalgrid2050.com/testcode/wafer-development-environment/202609192215-proof-s0004/' },
               says:'The wafer development environment: every numbered line of the estate, and a box that draws the grid, a substation or a fault study from one sentence.' } }
];
// THE PROGRAM A FIRED COMMAND RUNS: no button of its own and no tile; its shape is the network of the command that fired it.
// It is in the list of programs only for the moment it is started, so the row of buttons and its checks never see it.
const FIRE_PROGRAM = { name:'fire', button:'TESTS', select:{ app:'tests', repository:'faraday' }, pulse:{ origin:'centre', seconds:1.0 }, off:{ dim:0.06 },
  on:{ colour:[0.80,0.96,1.0], size:0, bright:0, sparks:0, sequence:[{ shape:'sld', hold_ms:0 }] }, end:{} };

// ===== THE SYSTEMS OF THE ESTATE: A PULSE FOR EACH ===========================================
// The soul of the grid, isolated: a local run over the whole estate found the systems, and each one is
// DATA here, exactly as the menu above is data. A system is a set of FILES, and a body on this disc is a
// piece of work, so a system's bodies are the work whose repository is one of the system's repositories
// AND that touched a file under one of that repository's folders. Nothing is animated here: the pulse,
// the dimming, the lit colour and the ending card are the engine's own (isolate / isolateNow / appCard).
// WHAT I ADDED AND WHY. The frozen record on the disc holds, per body: repository index, commit id, lines,
// day. It holds NO path, so the menu's select.repository can only light a WHOLE repository. The paths are
// in the estate's own table kuiper-work.mjs (commit id -> the files it changed), which the card part already
// loads on demand through workTable(). So the one hook is: select.prefixes, honoured where a system's work
// list is built (systemWork below), by reading that same table. No other selection path is touched.
const SYSTEMS = [
  { id:"030-network-topology", system:"network topology graphs: nodes, edges, buses, branches", kind:"electrical", connected:true, files_total:1706, button:"NETWORK TOPOLOGY GRAPH", says:"These files describe how the grid joins up: the nodes, the busbars and the branches that connect them into one network.", author:"opus agent 30 of 100, 20 Sept 2026",
    repos:[{ repo:"globalgrid2050", files:747, prefixes:["testcode/202609052011","testcode/202609052015","testcode/202609052020","testcode/202609052023","testcode/202609052008","testcode/202609051958"] }, { repo:"testcode", files:528, prefixes:["sandbox/202609052028","sandbox/202609052011","sandbox/202609052015","sandbox/202609052020","sandbox/202609052023","sandbox/202609052008"] }, { repo:"solar  … [line shortened here: 600 characters; full line on GitHub]
  { id:"013-single-line-diagrams", system:"single line diagrams (SLD) and schematic drawing code", kind:"electrical", connected:true, files_total:1557, button:"SINGLE LINE DIAGRAMS (", says:"These files are the single line and schematic drawings that show how the electrical system is wired together.", author:"opus agent 13 of 100, 20 Sept 2026",
    repos:[{ repo:"globalgrid2050", files:531, prefixes:["testcode/202609052011","testcode/202609052015","testcode/202609052020","testcode/202609052023",".github/workflows","testcode/202609051905"] }, { repo:"particle-physics-drawing-engine", files:465, prefixes:["results/msi","results/20260918T0056Z","results/20260918T0101Z","results/20260918T0118Z","results/20260918T0125Z","results/20260918T0127  … [line shortened here: 591 characters; full line on GitHub]
  { id:"010-primary-substations", system:"primary substations 33/11 kV", kind:"electrical", connected:true, files_total:1503, button:"PRIMARY SUBSTATIONS 33", says:"These files describe the primary substations that step 33 kV down to 11 kV and feed the local distribution network.", author:"opus agent 10 of 100, 20 Sept 2026",
    repos:[{ repo:"globalgrid2050", files:657, prefixes:["testcode/202609052011","testcode/202609052015","testcode/202609052020","testcode/202609052023",".github/workflows","testcode/202609051905"] }, { repo:"testcode", files:384, prefixes:["sandbox/202609052028","sandbox/202609052011","sandbox/202609052015","sandbox/202609052020","sandbox/202609052023","sandbox/202609051905"] }, { repo:"gridatlas  … [line shortened here: 529 characters; full line on GitHub]
  { id:"033-inverters", system:"solar and battery inverters, MPPT, PCS", kind:"electrical", connected:true, files_total:1430, button:"SOLAR AND BATTERY INVE", says:"These files describe the machines that turn solar and battery direct current into grid alternating current, and how they are sized, grouped and controlled.", author:"opus agent 33 of 100, 20 Sept 2026",
    repos:[{ repo:"globalgrid2050", files:810, prefixes:["testcode/202609052011","testcode/202609052015","testcode/202609052020","testcode/202609052023","testcode/202609052008","testcode/202609051958"] }, { repo:"testcode", files:528, prefixes:["sandbox/202609052028","sandbox/202609052011","sandbox/202609052015","sandbox/202609052020","sandbox/202609052023","sandbox/202609052008"] }, { repo:"chatg  … [line shortened here: 475 characters; full line on GitHub]
  { id:"100-cosmos-galaxies", system:"stars, galaxies and cosmic structure models (non-grid connected systems)", kind:"physics", connected:true, files_total:917, button:"STARS, GALAXIES AND CO", says:"These lit files hold the star, galaxy and cosmic structure models that draw the sky the disc sits in.", author:"opus agent 100 of 100, 20 Sept 2026",
    repos:[{ repo:"galaxies-wafers", files:735, prefixes:["iterations/12-visibility-lab","layers/modules","iterations/22-fast-zoom","layers/tiles","iterations/11-the-bond","iterations/14-electrical-hops"] }, { repo:"Kuiper-belt", files:169, prefixes:["cosmos/commits","data/20260918T234405Z","data/20260918T234855Z","data/20260919T001154Z","data/20260918T231829Z","data/20260918T234128Z"] }, { repo:"  … [line shortened here: 513 characters; full line on GitHub]
  { id:"099-particle-physics", system:"particle tracks, detectors and physics drawing systems (non-grid connected systems)", kind:"physics", connected:true, files_total:468, button:"PARTICLE TRACKS, DETEC", says:"These lit files are the particle and physics drawing code: the engines that draw moving points, tracks and detector pictures.", author:"opus agent 99 of 100, 20 Sept 2026",
    repos:[{ repo:"particle-physics-drawing-engine", files:465, prefixes:["results/msi","results/20260918T0056Z","results/20260918T0101Z","results/20260918T0118Z","results/20260918T0125Z","results/20260918T0127Z"] }, { repo:"globalgrid2050", files:2, prefixes:["testcode/202609142225","testcode/202609160224"] }, { repo:"galaxies-wafers", files:1, prefixes:["iterations/03-code-particle"] }] },
  { id:"032-solar-dc-strings", system:"PV DC strings, modules, junction boxes, string wiring", kind:"electrical", connected:true, files_total:443, button:"PV DC STRINGS, MODULES", says:"These files describe the DC side of a solar farm: the panels, how they are wired into strings, and the boxes where those strings come together.", author:"opus agent 32 of 100, 20 Sept 2026",
    repos:[{ repo:"chatgpt-audits", files:161, prefixes:["202608310033-study/PROJECT-STUDIES"] }, { repo:"globalgrid2050", files:145, prefixes:["testcode/202609051958","testcode/202609052008","testcode/202609052011","testcode/202609052015","testcode/202609052020","testcode/202609052023"] }, { repo:"testcode", files:119, prefixes:["sandbox/202609051958","sandbox/202609052008","sandbox/202609052011"  … [line shortened here: 476 characters; full line on GitHub]
  { id:"005-distribution-33kv", system:"33 kV circuits and primary networks", kind:"electrical", connected:true, files_total:196, button:"33 KV CIRCUITS AND PRI", says:"These files describe the 33 kV primary network: the feeders, cables, switchgear and primary substations that carry power from bulk supply points down to the 11 kV network.", author:"opus agent 5 of 100, 20 Sept 2026",
    repos:[{ repo:"globalgrid2050", files:129, prefixes:["repd_grid_atlasv6/data","repd_grid_atlasv7/data","repd_grid_atlasv8/data","pipelinenews_intelligence/202608311858","pipelinenews_intelligence/202608312037","pipelinenews_intelligence/202608312056"] }, { repo:"pipelinenews", files:66, prefixes:["releases/202608311858-pipelinenews","releases/202608312018-pipelinenews","releases/202608312037-p  … [line shortened here: 615 characters; full line on GitHub]
  { id:"064-rivers", system:"rivers and watercourses", kind:"water", connected:true, files_total:172, button:"RIVERS AND WATERCOURSE", says:"These lit files map the rivers, streams and watercourses the network must cross, follow or keep clear of.", author:"opus agent 64 of 100, 20 Sept 2026",
    repos:[{ repo:"teleprinter", files:98, prefixes:["drivers/codex","drivers/gridatlas"] }, { repo:"chatgpt-audits", files:37, prefixes:["202608310033-study/PROJECT-STUDIES"] }, { repo:"gpu-drivers-for-global-grid", files:29, prefixes:["claude/results",".gitattributes",".github/workflows",".gitignore","README.md","claude/README.md"] }] },
  { id:"016-overhead-lines", system:"overhead lines, conductors, towers, spans, sag", kind:"electrical", connected:true, files_total:145, button:"OVERHEAD LINES, CONDUC", says:"These files describe the overhead lines that carry power through the air: the conductors, the towers that hold them and how far each span is allowed to sag.", author:"opus agent 16 of 100, 20 Sept 2026",
    repos:[{ repo:"globalgrid2050", files:63, prefixes:["repd_grid_atlasv6/data","repd_grid_atlasv7/data","repd_grid_atlasv8/data","testcode/202609051901","testcode/202609051905","testcode/202609051906"] }, { repo:"testcode", files:51, prefixes:["sandbox/202609051901","sandbox/202609051905","sandbox/202609051906","sandbox/202609051927","sandbox/202609051932","sandbox/202609051936"] }, { repo:"grid  … [line shortened here: 526 characters; full line on GitHub]
  { id:"009-grid-supply-points", system:"grid supply points and bulk supply points", kind:"electrical", connected:true, files_total:142, button:"GRID SUPPLY POINTS AND", says:"These files are the high voltage supply points where the transmission network hands power to the local distribution network.", author:"opus agent 9 of 100, 20 Sept 2026",
    repos:[{ repo:"globalgrid2050", files:63, prefixes:["repd_grid_atlasv6/data","repd_grid_atlasv7/data","repd_grid_atlasv8/data","testcode/202609051901","testcode/202609051905","testcode/202609051906"] }, { repo:"testcode", files:51, prefixes:["sandbox/202609051901","sandbox/202609051905","sandbox/202609051906","sandbox/202609051927","sandbox/202609051932","sandbox/202609051936"] }, { repo:"grid  … [line shortened here: 526 characters; full line on GitHub]
  { id:"018-subsea-cables", system:"subsea and offshore export cables", kind:"electrical", connected:true, files_total:125, button:"SUBSEA AND OFFSHORE EX", says:"These files describe the cables that carry power under the sea from offshore generation to the shore.", author:"opus agent 18 of 100, 20 Sept 2026",
    repos:[{ repo:"globalgrid2050", files:98, prefixes:["uk_energy_tracking_v6/generation_history","uk_renewables_pipeline/202609071221","uk_renewables_pipeline/202609081016","uk_renewables_pipeline/202609082224",".github/workflows","data_science_protocol/audit_reports"] }, { repo:"data-interconnectors", files:11, prefixes:[".gitattributes",".github/workflows","CHANGELOG.md","DATA_SOURCES.md","DEP  … [line shortened here: 556 characters; full line on GitHub]
  { id:"017-underground-cables", system:"underground cable routes, ducts, joints, trenches", kind:"electrical", connected:true, files_total:110, button:"UNDERGROUND CABLE ROUT", says:"These files trace the buried cable routes, their ducts, trenches and joint bays that carry power out of sight beneath the ground.", author:"opus agent 17 of 100, 20 Sept 2026",
    repos:[{ repo:"particle-physics-drawing-engine", files:60, prefixes:["results/msi","results/20260918T0056Z","results/20260918T0101Z","results/20260918T0118Z","results/20260918T0125Z","results/20260918T0127Z"] }, { repo:"cable-trench-or-drill", files:36, prefixes:["releases/202609052001","releases/202609051921",".github/workflows","src/route-constraints",".gitattributes","DEVELOPMENT-PLAN.md"]   … [line shortened here: 646 characters; full line on GitHub]
  { id:"015-hvdc", system:"HVDC links and converter stations", kind:"electrical", connected:true, files_total:96, button:"HVDC LINKS AND CONVERT", says:"These files describe the direct current links and the converter stations at each end that move bulk power between distant parts of the grid.", author:"opus agent 15 of 100, 20 Sept 2026",
    repos:[{ repo:"globalgrid2050", files:71, prefixes:["uk_energy_tracking_v6/generation_history","uk_renewables_pipeline/202609071221","uk_renewables_pipeline/202609081016","uk_renewables_pipeline/202609082224",".github/workflows","data_science_protocol/audit_reports"] }, { repo:"data-interconnectors", files:11, prefixes:[".gitattributes",".github/workflows","CHANGELOG.md","DATA_SOURCES.md","DEP  … [line shortened here: 556 characters; full line on GitHub]
  { id:"006-distribution-11kv", system:"11 kV feeders and ring mains", kind:"electrical", connected:true, files_total:62, button:"11 KV FEEDERS AND RING", says:"These files are the medium-voltage distribution layer: the 11 kV feeders, ring mains and the substations they link.", author:"opus agent 6 of 100, 20 Sept 2026",
    repos:[{ repo:"globalgrid2050", files:36, prefixes:["repd_grid_atlasv6/data","repd_grid_atlasv6/scripts","repd_grid_atlasv7/data","repd_grid_atlasv7/scripts","repd_grid_atlasv8/data","repd_grid_atlasv8/scripts"] }, { repo:"testcode", files:17, prefixes:["sandbox/202609051901","sandbox/202609051905","sandbox/202609051906","sandbox/202609051927","sandbox/202609051932","sandbox/202609051936"] },   … [line shortened here: 478 characters; full line on GitHub]
  { id:"004-distribution-66kv", system:"66 kV circuits", kind:"electrical", connected:true, files_total:44, button:"66 KV CIRCUITS", says:"These lit files are the 66 kV circuits: the sub-transmission layer that carries power from the big grid substations out to the local distribution network.", author:"opus agent 4 of 100, 20 Sept 2026",
    repos:[{ repo:"globalgrid2050", files:24, prefixes:["grid_66kv.geojson","repd_grid_atlasv6/data","repd_grid_atlasv6/scripts","repd_grid_atlasv7/data","repd_grid_atlasv7/scripts","repd_grid_atlasv8/data"] }, { repo:"testcode", files:17, prefixes:["sandbox/202609051901","sandbox/202609051905","sandbox/202609051906","sandbox/202609051927","sandbox/202609051932","sandbox/202609051936"] }, { repo:"  … [line shortened here: 454 characters; full line on GitHub]
  { id:"057-a-roads", system:"A roads and primary routes", kind:"transport", connected:true, files_total:38, button:"A ROADS AND PRIMARY RO", says:"These files trace the main roads and primary routes the grid must follow, cross or avoid.", author:"opus agent 57 of 100, 20 Sept 2026",
    repos:[{ repo:"chatgpt-audits", files:16, prefixes:["202608310033-study/PROJECT-STUDIES"] }, { repo:"globalgrid2050", files:16, prefixes:[".github/workflows","motorway_services.geojson","repd_grid_atlasv6/.github","repd_grid_atlasv6/data","repd_grid_atlasv6/scripts","repd_grid_atlasv7/.github"] }, { repo:"data-gridatlas", files:3, prefixes:["202608291237-data-gridatlas/data"] }] },
  { id:"056-motorways", system:"motorways and the strategic road network", kind:"transport", connected:true, files_total:26, button:"MOTORWAYS AND THE STRA", says:"These files describe the motorway and main road network, its junctions, crossings and verges, and where cables and routes follow or cross it.", author:"opus agent 56 of 100, 20 Sept 2026",
    repos:[{ repo:"globalgrid2050", files:14, prefixes:[".github/workflows","motorway_services.geojson","repd_grid_atlasv6/.github","repd_grid_atlasv6/data","repd_grid_atlasv6/scripts","repd_grid_atlasv7/.github"] }, { repo:"chatgpt-audits", files:10, prefixes:["202608310033-study/PROJECT-STUDIES"] }, { repo:"data-gridatlas", files:2, prefixes:["202608291237-data-gridatlas/data"] }] },
  { id:"051-railway-lines", system:"railway lines and track geometry", kind:"transport", connected:true, files_total:20, button:"RAILWAY LINES AND TRAC", says:"These lit files describe railway routes, track alignment and the equipment that runs along the line.", author:"opus agent 51 of 100, 20 Sept 2026",
    repos:[{ repo:"globalgrid2050", files:11, prefixes:["repd_grid_atlasv8/scripts",".github/workflows","railways.geojson","repd_grid_atlasv6/data","repd_grid_atlasv6/scripts","repd_grid_atlasv7/data"] }, { repo:"chatgpt-audits", files:5, prefixes:["202608310033-study/PROJECT-STUDIES"] }, { repo:"gridatlas", files:3, prefixes:["atlas/releases"] }] }
];
// ONE MENU-STYLE ENTRY PER SYSTEM, made when it is fired and not before, so the face keeps its own few
// buttons and 19 more are never drawn on it.
function systemFind(q){ q = String(q || '').trim().toLowerCase(); if (!q) return null;
  return SYSTEMS.find(s => s.id.toLowerCase() === q) || SYSTEMS.find(s => s.system.toLowerCase() === q)
      || SYSTEMS.find(s => s.id.toLowerCase().startsWith(q)) || SYSTEMS.find(s => s.system.toLowerCase().startsWith(q))
      || SYSTEMS.find(s => s.system.toLowerCase().includes(q)) || null; }
// THE SELECTION: the work of this system's repositories whose changed files sit under this system's folders.
function systemWork(sys, W){ const out = [];
  for (const r of sys.repos) { const ri = repos.findIndex(x => x.name === r.repo); if (ri < 0) continue;
    for (const c of commits) { if (c.repo !== ri) continue;
      const w = W && W[c.sha]; if (!w) continue;                     // no file list for it: it is not claimed
      let hit = false;
      for (let i = 2; i < w.length && !hit; i++) { const p = w[i] && w[i][0];
        if (p) for (const pre of r.prefixes) if (p.indexOf(pre) === 0) { hit = true; break; } }
      if (hit) out.push(c.sha); } }
  return out; }
function systemProgram(sys){
  const name = 'sys-' + sys.id;
  if (!apps.find(x => x.app === name)) apps.push({ app:name, button:sys.button, repo:sys.repos[0] ? sys.repos[0].repo : '', prefixes:sys.repos[0] ? sys.repos[0].prefixes : [], live:'' });
  if (!programs.find(x => x.name === name)) programs.push({ name, button:sys.button,
    select:{ app:name, repository:sys.repos[0] ? sys.repos[0].repo : '', prefixes:sys.repos.map(r => ({ repo:r.repo, prefixes:r.prefixes })) },
    pulse:{ origin:'centre', seconds:1.5 }, off:{ dim:0.1 },
    on:{ colour:[0.80,0.96,1.0], size:0, bright:0, sparks:6, sequence:[{ shape:'cluster', hold_ms:1200 }] },
    end:{ tile:'system' }, says:sys.says });
  return name; }
// FIRE A SYSTEM: read the estate's file table, make the selection, then hand it to the engine's own pulse.
let systemShown = null;
function fireSystem(q){ const sys = systemFind(q); if (!sys) return Promise.resolve(null);
  const name = systemProgram(sys);
  return (typeof workTable === 'function' ? workTable() : Promise.resolve(null)).then(W => {
    appWork[name] = systemWork(sys, W);
    systemShown = sys; isolate(name);
    return { id:sys.id, lit:appWork[name].length, files_total:sys.files_total }; }); }
// THE CARD AT THE END OF THE PULSE: the engine's own card, then the system's plain words under it. Where no
// address is known for a system, the OPEN tile is taken off rather than a link invented.
function systemCard(st, sys){ appCard(st);
  const tile = card.querySelector('.cc-tile'); if (tile && !st.app.live) tile.remove();
  const put = (s, cls) => card.append(el('div', cls || 'cc-plain', s));
  put(sys.system, 'cc-title'); put(sys.kind + ' · ' + fmt(st.lit) + ' pieces of work lit · the run counted ' + fmt(sys.files_total) + ' files in all');
  for (const r of sys.repos) put(r.repo + ' · ' + fmt(r.files) + ' files · ' + r.prefixes.join('  '));
  if (sys.says) put(sys.says);
  put('found by: ' + sys.author);
  if (typeof layout === 'function') layout(); }
// THE TYPED WORDS. "systems" lists them in plain text; "system <id or name>" fires that one.
function systemsList(){ return SYSTEMS.map(s => s.id + '  ' + s.system + '  · ' + s.files_total + ' files').join(String.fromCharCode(10)); }
if (typeof window !== 'undefined') { window.KUIPER_SYSTEMS = { all:SYSTEMS, list:systemsList, fire:fireSystem, find:systemFind };
  try { if (window.FIRE && window.FIRE.register) {
    window.FIRE.register('systems', 'THE ESTATE', () => ({ numbers:{ systems:SYSTEMS.length }, said:systemsList(), how:'found by a run over every file of the estate' }));
    window.FIRE.register('system', 'THE ESTATE', i => { const s = systemFind(i && (i.id || i.name)); if (!s) throw new Error('no such system; type "systems" for the list');
      fireSystem(s.id); return { numbers:{ files:s.files_total }, said:s.system + ' — its pulse is running on the disc', how:'the work of ' + s.repos.map(r => r.repo).join(', ') + ' under the folders of this system' }; }); } } catch (_) {}
}

// ===== GRID TUBE MAP: START =====================================================================
// WHAT THIS IS FOR. Not a single line diagram. A commercial and financial modelling picture of the
// energy transition, drawn the way an underground map is drawn: a traveller does not need to know
// how a train works to use the map to travel. So there are no inverters, no transformers and no
// surge arresters here. TWO SYSTEMS ONLY: every substation with a real coordinate, and the 132 kV
// network that joins them. ONE CLICK puts a Faraday CAGE around what we need to look at; TWO CLICKS
// open the card that says, in words, what that station is.
// WHAT IS REUSED AND WHAT IS NEW. The camera, the zoom and the nine pixel text floor are the
// engine's (shapePoint / shapeScale / TEXT_FLOOR_PX); the layer is made the way shapeLayer makes
// one; the frame pump is the shell's own onDraw, so there is NO second animation system here - the
// sweep advances on the frames the wafer already draws and asks for the next by setting dirty. The
// card is the engine's card element and its own classes. The palette adds five colours and no more.
/* TUBE-DATA:START */ const TUBE_DATA = {"attribution":"Contains open map data \u00a9 OpenStreetMap contributors, available under the Open Database License (ODbL) v1.0. Any derived database must be shared alike under the same licence. https://www.openstreetmap.org/copyright","made":"2026-09-20T16:47:38Z","source":"open map data substations + 132 kV lines; topology only, no capacity","kvOrder":[400  … [line shortened here: 471,154 characters; full line on GitHub]
// THE RICHER SET, from the same open map data and the same snap: every link at 66, 132, 220, 275 and
// 400 kV, by index into the stations above, [a, b, kV, km, circuits]. The cage still walks the 132 kV
// graph, which is the one whose shape has been checked; the NATION VIEW draws all of it, because a
// country drawn in one class is a country with no transmission on it.
/* TUBE-LINKS-ALL:START */ TUBE_DATA.linksAll = [[310,821,132,4.34,1],[310,5435,132,4.33,1],[60,277,132,14.16,1],[60,4273,132,19.36,1],[2441,1638,132,0.4,1],[1078,2874,66,10.64,1],[1078,663,66,15.98,2],[339,5333,132,3.3,1],[339,1043,132,9.38,2],[1500,1501,66,7.96,1],[705,1057,275,3.58,1],[705,5746,400,35.1,1],[705,1052,275,13.35,1],[705,5222,400,27.55,1],[1388,5744,132,17.28,1],[1388,290,132,9.86,  … [line shortened here: 44,203 characters; full line on GitHub]


// THE SAME GRID AS THE ATLAS MAP. The voltage classes, their order, and the rule that decides which
// class a voltage IS are lifted from gridatlas atlas/modules/202609012040-grid-scope.js (composed
// into atlas/cartridges/202609200022-sld-sandbox-v9-8.js), so a person who knows that map recognises
// this one as the same grid. The rule is MEMBERSHIP within half a kilovolt, never "the first class
// this exceeds": that older rule labelled 750 kV as 400 and 50 kV as 33, and a voltage the standard
// classes do not contain is a fact about the data, not a number to round into a familiar one. An
// unclassified voltage is drawn and counted as unclassified.
const TUBE_CLASSES_KV = [400, 275, 220, 132, 66, 33];
const TUBE_CLASS_TOLERANCE_KV = 0.5;
function tubeClassOf(kv){ if (!Number.isFinite(kv)) return null;
  for (const known of TUBE_CLASSES_KV) if (Math.abs(kv - known) <= TUBE_CLASS_TOLERANCE_KV) return known;
  return null; }
// TRANSMISSION, by the Atlas's own test (nearest_transmission: kv >= 275 - 0.5).
function tubeIsTransmission(kv){ return Number(kv) >= 275 - TUBE_CLASS_TOLERANCE_KV; }
// Voltage class is the only thing a colour says here, exactly as a line colour on an underground map
// says only which line it is. The order is the Atlas's, highest class first; five of these are new to
// the engine, the rest are the engine's own ink.
const TUBE_KV = { 400: '#ffb454', 275: '#ff4b3a', 220: '#c89bff', 132: '#5ec8f2', 66: '#6fe3a8', 33: '#94a2b5' };
const TUBE_UNCLASSED = '#6d7d92';
const TUBE_LIT = '#eaf6ff', TUBE_DARK = '#1b2430', TUBE_CAGE = '#7ff0ff', TUBE_GROUND = '#04060a';
const TUBE_TEXT_FLOOR_PX = 9;                       // the engine's floor, kept word for word
// The Atlas's own words about what a picture like this cannot tell you, carried with the numbers so
// they cannot be separated from them by a renderer, a screenshot or a quote.
const TUBE_NOT = 'Not a statement about capacity, headroom, availability or the cost of connecting here.';
// THE RED LINE OVER A GRID VIEW IS A GRID SENTENCE. The engine's own red line warns about cable and
// array sizing, which is the right warning over a string drawing and the WRONG one over a map of the
// network: nobody sizes a cable from this picture, and the thing a reader might wrongly take from it
// is that a line on it means capacity. So the grid views carry their own line and the solar sentence
// stays on the solar views, where it is true.
const TUBE_WARNING = 'DEVELOPMENT ENVIRONMENT. A map of the network from open data: not a statement about capacity, headroom or what is connected.';
function tubeInk(kv){ const c = tubeClassOf(kv); return c === null ? TUBE_UNCLASSED : TUBE_KV[c]; }

const TUBE = { on: false, view: 'nation', focus: -1, hops: 2, kv: 0, t0: 0, phase: '',
               lit: null, litLinks: null, hull: null, lattice: null, morph: 1, drawMs: 0, hit: [],
               local: null, hitLocal: [], bandTop: 0 };

// ---- the graph, made once from the data ------------------------------------------------------
const TUBE_ADJ = (() => { const a = TUBE_DATA.stations.map(() => []);
  TUBE_DATA.links132.forEach((L, i) => { a[L[0]].push([L[1], i]); a[L[1]].push([L[0], i]); }); return a; })();
function tubeName(i){ const s = TUBE_DATA.stations[i]; return (s && s[5]) || 'unnamed station'; }
function tubeDegree(i){ return TUBE_ADJ[i] ? TUBE_ADJ[i].length : 0; }
// A BRIDGE LINK is one whose loss cuts the network in two. It is the single most commercial fact on
// the whole picture and it is found here rather than asserted: Tarjan's low-link walk, once.
const TUBE_BRIDGES = (() => { const n = TUBE_ADJ.length, disc = new Int32Array(n).fill(-1), low = new Int32Array(n), br = new Set();
  let t = 0;
  for (let s = 0; s < n; s++) { if (disc[s] >= 0) continue;
    const st = [[s, -1, 0]];
    while (st.length) { const f = st[st.length - 1];
      if (f[2] === 0) { disc[f[0]] = low[f[0]] = t++; }
      if (f[2] < TUBE_ADJ[f[0]].length) { const [to, li] = TUBE_ADJ[f[0]][f[2]++];
        if (li === f[1]) continue;
        if (disc[to] < 0) st.push([to, li, 0]); else low[f[0]] = Math.min(low[f[0]], disc[to]); }
      else { st.pop(); const p = st[st.length - 1];
        if (p) { low[p[0]] = Math.min(low[p[0]], low[f[0]]); if (low[f[0]] > disc[p[0]]) br.add(f[1]); } } } }
  return br; })();
// THE GEOGRAPHY, ONCE, into the disc's own unit square, so the engine's camera does all the rest.
const TUBE_GEO = (() => { const S = TUBE_DATA.stations;
  let x0 = 1e9, x1 = -1e9, y0 = 1e9, y1 = -1e9;
  const mid = S.reduce((a, s) => a + s[2], 0) / Math.max(1, S.length);
  const k = Math.cos(mid * Math.PI / 180);                       // longitude shortens away from the line
  const p = S.map(s => [s[1] * k, s[2]]);
  for (const q of p) { x0 = Math.min(x0, q[0]); x1 = Math.max(x1, q[0]); y0 = Math.min(y0, q[1]); y1 = Math.max(y1, q[1]); }
  const sc = 1.82 / Math.max(1e-9, Math.max(x1 - x0, y1 - y0));
  return p.map(q => [(q[0] - (x0 + x1) / 2) * sc, (q[1] - (y0 + y1) / 2) * sc]); })();

// ---- the layer, made the way the engine makes one --------------------------------------------
function tubeLayer(){ let el2 = document.getElementById('tubemap');
  if (!el2) { el2 = document.createElement('canvas'); el2.id = 'tubemap'; el2.setAttribute('aria-hidden', 'true');
    const st = document.createElement('style');
    st.textContent = '#tubemap{position:fixed;inset:0;z-index:9;pointer-events:none}';
    // THE DISC'S OWN WORDS BELONG TO THE DISC. While this picture is up the month rings' labels are
    // put away, because a tube map with SEP 26 written across it is two pictures at once.
    st.textContent += 'body.tube-on #labels,body.tube-on #names,body.tube-on #sldnames{display:none}';
    // AND THE ENGINE'S OWN RED LINE WITH THEM. It is pinned to the top of the screen by the chrome
    // with !important, so the parent being hidden is what puts it away; this says so out loud rather
    // than leaving it to be inherited, because the sentence it carries is wrong over this picture.
    st.textContent += 'body.tube-on #sldnames span.danger{display:none !important}';
    // THE GRID'S OWN RED LINE, in the same place and the same ink, WRAPPED rather than clipped: a
    // warning that ends in an ellipsis on a telephone is not a warning.
    st.textContent += '#tubewarn{display:none}body.tube-on #tubewarn{display:block;position:fixed;left:0;right:0;top:0;'
      + 'z-index:11;pointer-events:none;text-align:center;padding:3px 10px;color:#ff5a4f;background:#160b0aee;'
      + 'border-bottom:1px solid #4a2019;font:600 9.5px/1.45 ui-monospace,Menlo,Consolas,monospace;letter-spacing:.04em}';
    // AND THE LITTLE "layouts" BUTTON SITS UNDER THAT LINE, NEVER ON IT. The chrome pins the button
    // 20px from the top; on a telephone the red line wraps to two rows and the button is written over
    // the second row. The band already measures the line every frame, so the button is hung off that
    // same measurement and clears it at every width.
    st.textContent += 'body.tube-on #presets{top:var(--tubewarn-bottom,20px) !important}';
    document.head.append(st);
    const c = document.getElementById('c');
    if (c && c.parentNode) c.parentNode.insertBefore(el2, c.nextSibling); else document.body.append(el2); }
  let w = document.getElementById('tubewarn');
  if (!w) { w = document.createElement('div'); w.id = 'tubewarn'; w.setAttribute('aria-hidden', 'true');
    document.body.append(w); }
  if (w.textContent !== TUBE_WARNING) w.textContent = TUBE_WARNING;
  return el2; }
// WHERE THE PICTURE MAY BE DRAWN. The red line has a height of its own and the foot and the answer
// window have theirs; a band is worked out once a frame so no word is ever written under another.
function tubeBand(){ let top = 14, bottom = innerHeight - 14;
  const w = document.getElementById('tubewarn');
  if (w) { const r = w.getBoundingClientRect(); if (r.height > 2) top = Math.max(top, r.bottom + 6);
    try { document.documentElement.style.setProperty('--tubewarn-bottom',
      (r.height > 2 ? r.bottom + 6 : 20) + 'px'); } catch (_) {} }
  const foot = document.getElementById('foot');
  if (foot) { const r = foot.getBoundingClientRect(); if (r.height > 2) bottom = Math.min(bottom, r.top - 8); }
  try { const r = typeof sayRect === 'function' && sayRect();
    if (r && r.height > 8) bottom = Math.min(bottom, r.top - 8); } catch (_) {}
  // AND THE CARD, WHEN ONE IS OPEN. It is a panel the reader can see through to nothing, and a
  // picture drawn under it is a picture half told.
  { const c = document.getElementById('card');
    if (c && c.style.display !== 'none' && c.offsetHeight > 8) {
      const r = c.getBoundingClientRect();
      if (r.width > innerWidth * 0.6) bottom = Math.min(bottom, r.top - 8); } }
  if (bottom - top < 160) { top = 14; bottom = innerHeight - 14; }
  return { top, bottom }; }
function tubeGone(){ TUBE.on = false; TUBE.hit = []; TUBE.hitLocal = []; TUBE.local = null;
  try { document.body.classList.remove('tube-on'); } catch (_) {}
  const el2 = document.getElementById('tubemap'); if (!el2) return;
  const ctx = el2.getContext && el2.getContext('2d');
  if (ctx) { ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, el2.width, el2.height); } }

// ---- THE CAGE: who is inside it ---------------------------------------------------------------
// Hops along the NETWORK, not miles across the ground: two stops from here is two stops from here
// whichever way the wire bends. A kv filter, when one is typed, refuses to walk through a class it
// was not asked about.
function tubeBFS(from, hops, kv){ const seen = new Map([[from, 0]]), links = new Set(), q = [from];
  for (let h = 0; h < hops; h++) { const next = [];
    for (const a of q) for (const [b, li] of TUBE_ADJ[a]) {
      if (kv && TUBE_DATA.stations[b][3] !== kv && b !== from) continue;
      links.add(li);
      if (!seen.has(b)) { seen.set(b, h + 1); next.push(b); } }
    q.length = 0; q.push(...next); }
  // a link is only inside the cage when BOTH its ends are
  for (const li of Array.from(links)) { const L = TUBE_DATA.links132[li];
    if (!seen.has(L[0]) || !seen.has(L[1])) links.delete(li); }
  return { set: seen, links }; }
// The outline itself: the precomputed hull when the data carries one, else the gift wrap in the page.
function tubeHullOf(pts){ if (pts.length < 3) return pts.slice();
  const p = pts.slice().sort((a, b) => a[0] - b[0] || a[1] - b[1]);
  const cr = (o, a, b) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
  const lo = [], up = [];
  for (const q of p) { while (lo.length >= 2 && cr(lo[lo.length - 2], lo[lo.length - 1], q) <= 0) lo.pop(); lo.push(q); }
  for (let i = p.length - 1; i >= 0; i--) { const q = p[i];
    while (up.length >= 2 && cr(up[up.length - 2], up[up.length - 1], q) <= 0) up.pop(); up.push(q); }
  lo.pop(); up.pop(); return lo.concat(up); }
function tubeSwell(hull, pad){ if (hull.length < 2) return hull;
  let mx = 0, my = 0; for (const q of hull) { mx += q[0]; my += q[1]; } mx /= hull.length; my /= hull.length;
  return hull.map(q => { const dx = q[0] - mx, dy = q[1] - my, d = Math.max(1e-9, Math.hypot(dx, dy));
    return [q[0] + dx / d * pad, q[1] + dy / d * pad]; }); }

// ---- THE TUBE MAP: the caged set re-laid on an octilinear lattice ----------------------------
// Every station goes to the nearest free crossing of a square lattice; where two want the same
// crossing the second takes the nearest free one, searched outward in rings, so the ORDER of the
// network survives even though the geography does not. That is the whole trick of an underground
// map: keep the sequence, drop the miles.
function tubeLattice(ids, focus){
  const pitch = (TUBE_DATA.defaults && TUBE_DATA.defaults.pitch) || 0.16;
  const rot = ((TUBE_DATA.defaults && TUBE_DATA.defaults.rotation) || 0) * Math.PI / 180;
  const f = TUBE_GEO[focus], cosR = Math.cos(rot), sinR = Math.sin(rot);
  let far = 0; for (const i of ids) far = Math.max(far, Math.hypot(TUBE_GEO[i][0] - f[0], TUBE_GEO[i][1] - f[1]));
  // A REGION IS NOT A CAGE. A cage holds a handful of stations and reads well in seven pitches; a
  // region circle can hold hundreds, and forcing them into those same seven pitches piles stations
  // that are miles apart onto neighbouring crossings. So a region takes its lattice from its own
  // extent: wide enough that no row carries much more than forty stations, about as many as an
  // underground map names along one line.
  const REGION_ROW_MAX = 40;
  const cols = Math.max(7, Math.ceil(1.5 * Math.sqrt(ids.length)), Math.ceil(ids.length / REGION_ROW_MAX));
  const half = (typeof TUBE !== 'undefined' && TUBE && TUBE.view === 'region')
    ? Math.max(3.4, (cols - 1) / 2) : 3.4;
  const k = far > 1e-9 ? (pitch * half) / far : 1;                // the cage fills about seven pitches
  const taken = new Map(), out = new Map();
  const order = ids.slice().sort((a, b) =>
    Math.hypot(TUBE_GEO[a][0] - f[0], TUBE_GEO[a][1] - f[1]) - Math.hypot(TUBE_GEO[b][0] - f[0], TUBE_GEO[b][1] - f[1]));
  for (const i of order) { const dx = (TUBE_GEO[i][0] - f[0]) * k, dy = (TUBE_GEO[i][1] - f[1]) * k;
    const rx = dx * cosR - dy * sinR, ry = dx * sinR + dy * cosR;
    let gx = Math.round(rx / pitch), gy = Math.round(ry / pitch);
    for (let r = 0; r < 40; r++) { let done = false;
      for (let a = -r; a <= r && !done; a++) for (let b = -r; b <= r && !done; b++) {
        if (r > 0 && Math.abs(a) !== r && Math.abs(b) !== r) continue;
        const key = (gx + a) + ',' + (gy + b);
        if (!taken.has(key)) { taken.set(key, i); out.set(i, [(gx + a) * pitch, (gy + b) * pitch]); done = true; } }
      if (done) break; } }
  return out; }
// A LINK IS 0, 45 OR 90 DEGREES AND NOTHING ELSE: the diagonal is taken first and the straight run
// finishes the job, which is what makes a tube map read as a diagram rather than a sketch.
function tubeRoute(a, b){ const dx = b[0] - a[0], dy = b[1] - a[1];
  const ax = Math.abs(dx), ay = Math.abs(dy);
  if (ax < 1e-9 || ay < 1e-9 || Math.abs(ax - ay) < 1e-9) return [a, b];
  const d = Math.min(ax, ay), sx = Math.sign(dx), sy = Math.sign(dy);
  return [a, [a[0] + sx * d, a[1] + sy * d], b]; }
// AN INTERCHANGE is a station where classes meet - the one place a traveller changes line.
function tubeInterchange(i){ const c = TUBE_DATA.stations[i][3];
  for (const [b] of TUBE_ADJ[i]) if (TUBE_DATA.stations[b][3] !== c) return true;
  return false; }

// ---- the drawing ------------------------------------------------------------------------------
function tubeAt(i){ const g = TUBE_GEO[i];
  if (TUBE.lattice && TUBE.lattice.has(i)) { const l = TUBE.lattice.get(i), u = TUBE.morph;
    return [g[0] + (l[0] + TUBE_GEO[TUBE.focus][0] - g[0]) * u, g[1] + (l[1] + TUBE_GEO[TUBE.focus][1] - g[1]) * u]; }
  return g; }
function drawTubeMap(){
  if (!TUBE.on) return;
  const el2 = tubeLayer(), t = performance.now();
  const dpr = Math.max(1, Math.min(3, window.devicePixelRatio || 1));
  const W = Math.max(1, Math.round(innerWidth * dpr)), H = Math.max(1, Math.round(innerHeight * dpr));
  if (el2.width !== W || el2.height !== H) { el2.width = W; el2.height = H; }
  const ctx = el2.getContext('2d'); if (!ctx) return;
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, innerWidth, innerHeight);
  // THE GROUND. True black, because the marks are what must be read and the disc beneath is not part
  // of this picture at all.
  ctx.fillStyle = TUBE_GROUND; ctx.fillRect(0, 0, innerWidth, innerHeight);
  const band = tubeBand(); TUBE.bandTop = band.top;
  // THE LOCAL SYSTEM IS A PICTURE OF ITS OWN and does not share the nation's camera; it is drawn
  // straight onto the band, because one station's system has no geography worth keeping.
  if (TUBE.view === 'local' && TUBE.local) { drawLocalSystem(ctx, dpr, band, t);
    TUBE.drawMs = TUBE.drawMs * 0.8 + (performance.now() - t) * 0.2; return; }
  const px = shapeScale(), S = p => shapePoint(p);
  const caged = TUBE.lit, cagedL = TUBE.litLinks;
  // THE SWEEP. The ring leaves the tapped station and everything it has passed that belongs to the
  // cage stays lit; everything else goes dark. It advances on the frames the shell already draws.
  let sweep = 1e9;
  if (TUBE.phase === 'pulse') { const u = Math.min(1, (t - TUBE.t0) / 1100);
    sweep = u * Math.hypot(innerWidth, innerHeight) * 0.75;
    if (u >= 1) { TUBE.phase = 'lay'; TUBE.t0 = t; }
    try { dirty = true; } catch (_) {} }
  else if (TUBE.phase === 'lay') { const u = Math.min(1, (t - TUBE.t0) / 700);
    TUBE.morph = u < 1 ? u * u * (3 - 2 * u) : 1;
    if (u >= 1) TUBE.phase = 'tube'; try { dirty = true; } catch (_) {} }
  const centre = TUBE.focus >= 0 ? S(tubeAt(TUBE.focus)) : null;
  const passed = p => !centre || sweep >= 1e8 || Math.hypot(p[0] - centre[0], p[1] - centre[1]) <= sweep;
  ctx.lineCap = 'round'; ctx.lineJoin = 'round';
  // 1. THE LINKS. Dark ones first, in one batched path, so a phone strokes once and not 5,800 times.
  const L = TUBE_DATA.links132;
  if (!caged || TUBE.phase === 'pulse') { ctx.beginPath();
    for (let i = 0; i < L.length; i++) { if (caged && cagedL.has(i)) continue;
      const a = S(tubeAt(L[i][0])), b = S(tubeAt(L[i][1]));
      if (Math.max(a[0], b[0]) < -40 || Math.min(a[0], b[0]) > innerWidth + 40) continue;
      if (Math.max(a[1], b[1]) < -40 || Math.min(a[1], b[1]) > innerHeight + 40) continue;
      ctx.moveTo(a[0], a[1]); ctx.lineTo(b[0], b[1]); }
    ctx.lineWidth = 1; ctx.strokeStyle = TUBE_DARK; ctx.stroke(); }
  // 2. THE LIT LINKS, one stroke per voltage class, weight by how many circuits run the route.
  // THE WHOLE NETWORK IS MORE THAN ONE CLASS. The cage walks the 132 kV graph, which is the one whose
  // shape has been checked; but a nation view drawn in 132 kV alone shows a country with no
  // transmission on it. So when the richer set is carried, THE NATION VIEW DRAWS IT - every link at
  // its own class colour - and the cage stays on the graph it can honestly walk.
  const ALLL = (!caged && TUBE_DATA.linksAll && TUBE_DATA.linksAll.length) ? TUBE_DATA.linksAll : null;
  const src = ALLL || L;
  const wantL = caged ? Array.from(cagedL) : src.map((_, i) => i);
  const byW = new Map();
  for (const i of wantL) { const lk = src[i];
    if (caged && (!passed(S(tubeAt(lk[0]))) && !passed(S(tubeAt(lk[1]))))) continue;
    const kvc = ALLL ? lk[2] : Math.max(TUBE_DATA.stations[lk[0]][3], TUBE_DATA.stations[lk[1]][3]);
    const key = kvc + ':' + Math.min(4, (ALLL ? lk[4] : lk[3]) || 1);